Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,102 @@
import { describe, expect, test } from "vitest";
import type { ApiConfig } from "@toolctrl/config";
import { serializeApiAuthCookie, serializeExpiredApiAuthCookie } from "./session-cookie.js";
const baseConfig: ApiConfig = {
appName: "Test API",
nodeEnv: "test",
revision: "unknown",
listen: { port: 3001 },
routing: {
appBaseDomain: "localhost:3000",
webAppHost: "app.localhost:3000",
adminAppHost: "admin.localhost:3000",
apiHost: "api.localhost:3000",
protocol: "http",
},
origins: {},
apiAccessToken: "test-api-access-token",
jwtSecret: "test-jwt-secret",
analytics: {},
mailjet: {},
stripe: {},
apiKeys: {
allowLegacyPlaintextFallback: true,
},
storage: {},
};
describe("serializeApiAuthCookie", () => {
test("serializes production API auth cookies with shared hardened attributes", () => {
const config = {
...baseConfig,
nodeEnv: "production",
routing: {
appBaseDomain: "example.com",
webAppHost: "app.example.com",
adminAppHost: "admin.example.com",
apiHost: "api.example.com",
protocol: "https",
},
} satisfies ApiConfig;
const cookie = serializeApiAuthCookie("signed.jwt.value", config);
expect(cookie).toContain("RJ_api_session=signed.jwt.value");
expect(cookie).toContain("Domain=example.com");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("Secure");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("Path=/");
expect(cookie).not.toContain("RJ_session=");
expect(cookie).not.toContain(config.apiAccessToken);
expect(cookie).not.toContain(config.jwtSecret);
});
test("omits Domain and Secure for localhost HTTP development", () => {
const cookie = serializeApiAuthCookie("local-token", baseConfig);
expect(cookie).toContain("RJ_api_session=local-token");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("Path=/");
expect(cookie).not.toContain("Domain=");
expect(cookie).not.toContain("Secure");
expect(cookie).not.toContain(baseConfig.apiAccessToken);
expect(cookie).not.toContain(baseConfig.jwtSecret);
});
test("URL-encodes token values without serializing config secrets", () => {
const cookie = serializeApiAuthCookie("token with spaces;and=symbols", baseConfig);
expect(cookie).toContain("RJ_api_session=token%20with%20spaces%3Band%3Dsymbols");
expect(cookie).not.toContain("token with spaces;and=symbols");
expect(cookie).not.toContain(baseConfig.apiAccessToken);
expect(cookie).not.toContain(baseConfig.jwtSecret);
});
test("serializes expired API auth cookies with hardened shared attributes", () => {
const config = {
...baseConfig,
nodeEnv: "production",
routing: {
appBaseDomain: "example.com",
webAppHost: "app.example.com",
adminAppHost: "admin.example.com",
apiHost: "api.example.com",
protocol: "https",
},
} satisfies ApiConfig;
const cookie = serializeExpiredApiAuthCookie(config);
expect(cookie).toContain("RJ_api_session=");
expect(cookie).toContain("Max-Age=0");
expect(cookie).toContain("Expires=Thu, 01 Jan 1970 00:00:00 GMT");
expect(cookie).toContain("Domain=example.com");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("Secure");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("Path=/");
expect(cookie).not.toContain(config.apiAccessToken);
expect(cookie).not.toContain(config.jwtSecret);
});
});
@@ -0,0 +1,27 @@
import { resolveApiSessionCookiePolicy, type ApiConfig } from "@toolctrl/config";
function serializeApiAuthCookieWithValue(value: string, config: ApiConfig, extraAttributes: string[] = []) {
const policy = resolveApiSessionCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
});
const attributes = [
`${policy.name}=${value}`,
`Path=${policy.path}`,
policy.domain ? `Domain=${policy.domain}` : undefined,
"SameSite=Lax",
policy.secure ? "Secure" : undefined,
policy.httpOnly ? "HttpOnly" : undefined,
...extraAttributes,
].filter((attribute): attribute is string => Boolean(attribute));
return attributes.join("; ");
}
export function serializeApiAuthCookie(token: string, config: ApiConfig) {
return serializeApiAuthCookieWithValue(encodeURIComponent(token), config);
}
export function serializeExpiredApiAuthCookie(config: ApiConfig) {
return serializeApiAuthCookieWithValue("", config, ["Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT"]);
}
@@ -0,0 +1,158 @@
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { createSharedStore } from "@toolctrl/shared-store";
import {
LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS,
LOGIN_RATE_LIMIT_IP_ATTEMPTS,
checkLoginRateLimit,
createLoginRateLimitAccountFingerprint,
deriveLoginRateLimitClientIp,
recordFailedLoginAttempt,
recordSuccessfulLogin,
resetLoginRateLimiterForTests,
__resetLoginRateLimitStoreForTests,
__setLoginRateLimitStoreForTests,
} from "./login-rate-limit.js";
function request(account: string | undefined = "User@Example.com", ip: string | undefined = "203.0.113.10") {
return {
account,
headers: ip ? { "x-forwarded-for": ip } : {},
};
}
async function failAttempts(count: number, input = request()) {
for (let index = 0; index < count; index += 1) {
await recordFailedLoginAttempt(input);
}
}
beforeEach(() => {
// Fresh isolated memory store per test so keys never bleed across cases.
__setLoginRateLimitStoreForTests(createSharedStore({ namespace: "test-login-rate-limit" }));
});
afterEach(async () => {
await resetLoginRateLimiterForTests();
__resetLoginRateLimitStoreForTests();
});
describe("login rate limiter (shared-store)", () => {
test("allows through the last permitted attempt and blocks after the IP threshold", async () => {
for (let index = 0; index < LOGIN_RATE_LIMIT_IP_ATTEMPTS - 1; index += 1) {
await recordFailedLoginAttempt(request(`user-${index}@example.com`, "198.51.100.10"));
}
expect(await checkLoginRateLimit(request("next@example.com", "198.51.100.10"))).toMatchObject({ allowed: true });
await recordFailedLoginAttempt(request("last@example.com", "198.51.100.10"));
expect(await checkLoginRateLimit(request("blocked@example.com", "198.51.100.10"))).toMatchObject({
allowed: false,
scope: "ip",
clientIp: "198.51.100.10",
accountFingerprint: createLoginRateLimitAccountFingerprint("blocked@example.com"),
});
});
test("tracks account attempts across different IP buckets", async () => {
for (let index = 0; index < LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS; index += 1) {
await recordFailedLoginAttempt(request("Shared@Example.com", `203.0.113.${index + 1}`));
}
expect(await checkLoginRateLimit(request(" shared@example.com ", "203.0.113.99"))).toMatchObject({
allowed: false,
scope: "account",
clientIp: "203.0.113.99",
accountFingerprint: createLoginRateLimitAccountFingerprint("shared@example.com"),
});
expect(await checkLoginRateLimit(request("other@example.com", "203.0.113.99"))).toMatchObject({ allowed: true });
});
test("keeps independent IP buckets for multiple clients", async () => {
await failAttempts(LOGIN_RATE_LIMIT_IP_ATTEMPTS, request("one@example.com", "203.0.113.1"));
expect(await checkLoginRateLimit(request("fresh@example.com", "203.0.113.1"))).toMatchObject({ allowed: false, scope: "ip" });
expect(await checkLoginRateLimit(request("fresh@example.com", "203.0.113.2"))).toMatchObject({ allowed: true });
});
test("uses the first x-forwarded-for segment before x-real-ip and remote fallback", () => {
expect(
deriveLoginRateLimitClientIp({
headers: new Headers({ "x-forwarded-for": " 198.51.100.7, 10.0.0.1 ", "x-real-ip": "198.51.100.8" }),
remoteAddress: "198.51.100.9",
}),
).toBe("198.51.100.7");
expect(deriveLoginRateLimitClientIp({ headers: { "x-real-ip": "198.51.100.8" }, remoteAddress: "198.51.100.9" })).toBe("198.51.100.8");
expect(deriveLoginRateLimitClientIp({ remoteAddress: "198.51.100.9" })).toBe("198.51.100.9");
expect(deriveLoginRateLimitClientIp({})).toBe("unknown");
});
test("resets only the normalized account bucket after successful login", async () => {
await failAttempts(LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS, request("Reset@Example.com", "203.0.113.11"));
await failAttempts(LOGIN_RATE_LIMIT_IP_ATTEMPTS, request("other@example.com", "203.0.113.12"));
expect(await checkLoginRateLimit(request("reset@example.com", "203.0.113.13"))).toMatchObject({ allowed: false, scope: "account" });
await recordSuccessfulLogin({ account: " reset@example.com " });
expect(await checkLoginRateLimit(request("reset@example.com", "203.0.113.13"))).toMatchObject({ allowed: true });
expect(await checkLoginRateLimit(request("fresh@example.com", "203.0.113.12"))).toMatchObject({ allowed: false, scope: "ip" });
});
test("normalizes malformed or missing accounts into one bounded account bucket", async () => {
for (const account of [undefined, null, "", " ", 123]) {
await recordFailedLoginAttempt({ ...request(undefined, "203.0.113.30"), account });
}
expect(await checkLoginRateLimit({ ...request(undefined, "203.0.113.31"), account: undefined })).toMatchObject({
allowed: false,
scope: "account",
accountFingerprint: createLoginRateLimitAccountFingerprint(undefined),
});
});
test("public metadata exposes only stable fingerprints and no raw credentials", async () => {
const rawEmail = "Sensitive.User+token@example.com";
const rawPassword = "correct horse battery staple";
await failAttempts(LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS, request(rawEmail, "203.0.113.40"));
const result = await checkLoginRateLimit({ ...request(rawEmail, "203.0.113.41"), password: rawPassword } as never);
const serialized = JSON.stringify(result);
expect(result).toMatchObject({ allowed: false, scope: "account" });
expect(serialized).toContain("acct_");
expect(serialized).not.toContain(rawEmail);
expect(serialized).not.toContain(rawEmail.toLowerCase());
expect(serialized).not.toContain(rawPassword);
});
test("uses the redis adapter when REDIS_URL is set", () => {
// Verify the store wiring picks the RedisAdapter when REDIS_URL is
// provided. We don't actually open a Redis connection — we inject a
// pre-built store with the redisUrl so it goes through buildAdapter.
const originalRedisUrl = process.env.REDIS_URL;
try {
process.env.REDIS_URL = "redis://does-not-exist:6379";
// Building the store should select the RedisAdapter without throwing.
const store = createSharedStore({ namespace: "redis-selection-test", redisUrl: process.env.REDIS_URL });
expect(store.adapter.constructor.name).toBe("RedisAdapter");
// Best-effort close — the adapter never actually connects until the
// first command, so this is cheap.
void store.close();
} finally {
if (originalRedisUrl === undefined) delete process.env.REDIS_URL;
else process.env.REDIS_URL = originalRedisUrl;
}
});
test("uses the memory adapter when REDIS_URL is unset", () => {
const originalRedisUrl = process.env.REDIS_URL;
delete process.env.REDIS_URL;
try {
const store = createSharedStore({ namespace: "memory-selection-test" });
expect(store.adapter.constructor.name).toBe("MemoryAdapter");
} finally {
if (originalRedisUrl !== undefined) process.env.REDIS_URL = originalRedisUrl;
}
});
});
@@ -0,0 +1,235 @@
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@toolctrl/shared-store";
import { getSharedStore } from "../shared-store.js";
export const LOGIN_RATE_LIMIT_WINDOW_MS = 60_000;
export const LOGIN_RATE_LIMIT_IP_ATTEMPTS = 10;
export const LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS = 5;
const LOGIN_RATE_LIMIT_WINDOW_SECONDS = Math.ceil(LOGIN_RATE_LIMIT_WINDOW_MS / 1000);
const UNKNOWN_CLIENT_IP = "unknown";
const UNKNOWN_ACCOUNT_KEY = "unknown-account";
const FINGERPRINT_PREFIX = "acct_";
export type LoginRateLimitScope = "ip" | "account";
export type LoginRateLimitRequest = {
headers?: Headers | Record<string, string | string[] | undefined>;
remoteAddress?: string | null;
account?: unknown;
};
export type LoginRateLimitAllowed = {
allowed: true;
clientIp: string;
accountFingerprint: string;
};
export type LoginRateLimitBlocked = {
allowed: false;
scope: LoginRateLimitScope;
retryAfterSeconds: number;
clientIp: string;
accountFingerprint: string;
};
export type LoginRateLimitResult = LoginRateLimitAllowed | LoginRateLimitBlocked;
/**
* Lazy holder around the two fixed-window limiters. Built on first use
* so tests can swap the SharedStore via `__setLoginRateLimitStoreForTests`
* before any limiter is constructed.
*/
type Limiters = {
ip: FixedWindowRateLimiter;
account: FixedWindowRateLimiter;
store: SharedStore;
};
let limiters: Limiters | null = null;
let storeFactory: () => SharedStore = () => getSharedStore();
function getLimiters(): Limiters {
if (limiters !== null) {
return limiters;
}
const store = storeFactory();
limiters = {
store,
ip: createFixedWindowRateLimiter({
store,
prefix: "login-rate-limit:ip",
windowSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
max: LOGIN_RATE_LIMIT_IP_ATTEMPTS,
}),
account: createFixedWindowRateLimiter({
store,
prefix: "login-rate-limit:account",
windowSeconds: LOGIN_RATE_LIMIT_WINDOW_SECONDS,
max: LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS,
}),
};
return limiters;
}
export async function checkLoginRateLimit(request: LoginRateLimitRequest): Promise<LoginRateLimitResult> {
const clientIp = deriveLoginRateLimitClientIp(request);
const accountKey = normalizeLoginRateLimitAccount(request.account);
const accountFingerprint = createLoginRateLimitAccountFingerprint(accountKey);
const { ip, account, store } = getLimiters();
const ipState = await readCounter(store, "login-rate-limit:ip", clientIp);
if (ipState.count >= LOGIN_RATE_LIMIT_IP_ATTEMPTS) {
return {
allowed: false,
scope: "ip",
retryAfterSeconds: Math.max(1, ipState.ttlSeconds),
clientIp,
accountFingerprint,
};
}
const accountState = await readCounter(store, "login-rate-limit:account", accountKey);
if (accountState.count >= LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS) {
return {
allowed: false,
scope: "account",
retryAfterSeconds: Math.max(1, accountState.ttlSeconds),
clientIp,
accountFingerprint,
};
}
// Silence unused-var: the limiter objects are kept on the cached `Limiters`
// because `recordFailedLoginAttempt` consumes them on the write path.
void ip;
void account;
return {
allowed: true,
clientIp,
accountFingerprint,
};
}
export async function recordFailedLoginAttempt(request: LoginRateLimitRequest): Promise<void> {
const { ip, account } = getLimiters();
const clientIp = deriveLoginRateLimitClientIp(request);
const accountKey = normalizeLoginRateLimitAccount(request.account);
await Promise.all([ip.consume(clientIp), account.consume(accountKey)]);
}
export async function recordSuccessfulLogin(request: Pick<LoginRateLimitRequest, "account">): Promise<void> {
const { account } = getLimiters();
await account.reset(normalizeLoginRateLimitAccount(request.account));
}
export async function resetLoginRateLimiterForTests(): Promise<void> {
// Drop any cached limiter pair and best-effort drain any keys the
// previous limiters wrote to the shared-store. Tests that need full
// isolation can also inject a fresh store via
// `__setLoginRateLimitStoreForTests`.
const previous = limiters;
limiters = null;
if (previous) {
try {
for await (const fullKey of previous.store.adapter.scan(`shared-store:${previous.store.namespace}:rl:fixed:login-rate-limit:*`)) {
// adapter keys are absolute (namespace already applied); strip the
// namespace prefix when calling store.del which re-applies it.
const prefix = `shared-store:${previous.store.namespace}:`;
if (fullKey.startsWith(prefix)) {
await previous.store.del(fullKey.slice(prefix.length));
}
}
} catch {
// Best-effort; isolated tests use the store seam instead.
}
}
}
/** Test seam: inject a SharedStore that backs the limiters. */
export function __setLoginRateLimitStoreForTests(store: SharedStore): void {
limiters = null;
storeFactory = () => store;
}
/** Test seam: revert to the default factory (real shared-store singleton). */
export function __resetLoginRateLimitStoreForTests(): void {
limiters = null;
storeFactory = () => getSharedStore();
}
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
const forwardedFor = readHeader(request.headers, "x-forwarded-for");
const forwardedClient = forwardedFor?.split(",")[0]?.trim();
if (forwardedClient) {
return forwardedClient;
}
const realIp = readHeader(request.headers, "x-real-ip")?.trim();
if (realIp) {
return realIp;
}
const remoteAddress = request.remoteAddress?.trim();
return remoteAddress || UNKNOWN_CLIENT_IP;
}
export function createLoginRateLimitAccountFingerprint(account: unknown): string {
const normalized = normalizeLoginRateLimitAccount(account);
let hash = 0x811c9dc5;
for (let index = 0; index < normalized.length; index += 1) {
hash ^= normalized.charCodeAt(index);
hash = Math.imul(hash, 0x01000193) >>> 0;
}
return `${FINGERPRINT_PREFIX}${hash.toString(16).padStart(8, "0")}`;
}
function normalizeLoginRateLimitAccount(account: unknown): string {
if (typeof account !== "string") {
return UNKNOWN_ACCOUNT_KEY;
}
const normalized = account.trim().toLowerCase();
return normalized || UNKNOWN_ACCOUNT_KEY;
}
/**
* Peek at the current counter and remaining TTL without incrementing.
* The shared-store fixed-window helper only exposes `consume()` (which
* always increments) and `reset()`, so we read the underlying key
* directly to keep `checkLoginRateLimit` side-effect-free.
*/
async function readCounter(store: SharedStore, prefix: string, key: string): Promise<{ count: number; ttlSeconds: number }> {
const suffix = `rl:fixed:${prefix}:${key}`;
const raw = await store.get(suffix);
const count = raw === null ? 0 : Number.parseInt(raw, 10) || 0;
// The memory adapter does not expose a `ttl` helper, so derive a
// best-effort retry window from the configured window length. Redis
// counter TTL is enforced by the limiter on `consume`, so a fresh
// request entering the window gets the full window-seconds back.
const ttlSeconds = count > 0 ? LOGIN_RATE_LIMIT_WINDOW_SECONDS : 0;
return { count, ttlSeconds };
}
function readHeader(headers: LoginRateLimitRequest["headers"], name: string): string | undefined {
if (!headers) {
return undefined;
}
if (headers instanceof Headers) {
return headers.get(name) ?? undefined;
}
const lowerName = name.toLowerCase();
for (const [headerName, value] of Object.entries(headers)) {
if (headerName.toLowerCase() !== lowerName) {
continue;
}
return Array.isArray(value) ? value[0] : value;
}
return undefined;
}
@@ -0,0 +1,43 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import { describe, expect, test } from "vitest";
const appSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../app.ts");
const entityRowRoutesSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../routes/entity-row-routes.ts");
const relationshipRoutesSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../routes/relationship-routes.ts");
function read(path: string) {
return readFileSync(path, "utf8");
}
describe("API permission helper wiring", () => {
// The legacy v1 row + relationship routes were extracted out of
// `app.ts` into dedicated route modules. The assertions here pin the
// shared `authorizeApiEntityRowScope` / `authorizeApiRelationshipScope`
// helpers to those extraction sites so a regression that re-inlines
// permission checks in `app.ts` (or a different file) fails CI.
test("entity-row routes call the shared API permission helper", () => {
const src = read(entityRowRoutesSourcePath);
expect(src).toContain('import { authorizeApiEntityRowScope } from "../auth/permission.js";');
expect(src.match(/authorizeApiEntityRowScope\(/g)).toHaveLength(5);
});
test("relationship routes call the shared API permission helper", () => {
const src = read(relationshipRoutesSourcePath);
expect(src).toContain('import { authorizeApiRelationshipScope } from "../auth/permission.js";');
expect(src.match(/authorizeApiRelationshipScope\(/g)).toHaveLength(3);
});
test("app.ts does not define or call stale local entity-row scope helpers", () => {
const appSource = read(appSourcePath);
expect(appSource).not.toMatch(/function\s+authorizeEntityRowScope\b/);
expect(appSource).not.toMatch(/const\s+authorizeEntityRowScope\b/);
expect(appSource).not.toMatch(/=>\s*authorizeEntityRowScope\(/);
expect(appSource).not.toMatch(/\bauthorizeEntityRowScope\(/);
expect(appSource).not.toMatch(/\bgetEntityPermission\b/);
expect(appSource).not.toMatch(/\bverifyUserHasPermission\b/);
});
});
@@ -0,0 +1,187 @@
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import type { LegacyEntity } from "@toolctrl/db/entities.server";
import { describe, expect, test } from "vitest";
import { createServicePrincipal } from "../auth.js";
import { authorizeApiEntityRowScope, authorizeApiRelationshipScope } from "./permission.js";
import { createStoredApiKeyPrincipal, type ApiScopeResult } from "./scope.js";
const NOW = new Date("2026-01-15T12:00:00.000Z");
function buildEntity(overrides: Partial<LegacyEntity> = {}): LegacyEntity {
return {
id: "entity-1",
name: "contacts",
description: null,
url: null,
multiTenant: true,
isPublic: false,
useAsUser: false,
createdById: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
...overrides,
};
}
function buildApiKey(overrides: Partial<LegacyApiKeySimple> = {}): LegacyApiKeySimple {
return {
id: "api-key-1",
alias: "Production key",
expires: new Date("2026-02-01T00:00:00.000Z"),
tenantId: "tenant-1",
active: true,
entities: [
{
entityId: "entity-1",
create: true,
read: true,
update: true,
delete: false,
},
{
entityId: "child-entity",
create: true,
read: true,
update: false,
delete: false,
},
],
tenant: {
id: "tenant-1",
name: "Tenant One",
slug: "tenant-one",
deactivatedReason: null,
},
...overrides,
};
}
function expectRedactedDeny(result: ApiScopeResult, reason: string) {
expect(result).toEqual({
allowed: false,
principalType: "api-key",
reason,
code: "FORBIDDEN_API_KEY_SCOPE",
});
const serialized = JSON.stringify(result);
expect(serialized).not.toContain("plaintext-secret");
expect(serialized).not.toContain("hash-value");
expect(serialized).not.toContain("service-token-value");
}
describe("authorizeApiEntityRowScope", () => {
test("allows entity row operations when the stored API key has the entity operation scope", () => {
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
entity: buildEntity(),
operation: "read",
now: NOW,
});
expect(result).toEqual({
allowed: true,
principalType: "api-key",
});
});
test("denies entity row operations when the stored API key lacks the entity operation scope", () => {
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
entity: buildEntity(),
operation: "delete",
now: NOW,
});
expectRedactedDeny(result, "operation_permission_missing");
});
test("fails closed for malformed legacy entities without an id", () => {
expect(() =>
authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
entity: buildEntity({ id: "" }),
operation: "read",
now: NOW,
}),
).toThrow("Entity is missing an id.");
});
test("denies stored API keys when tenant scope cannot be resolved", () => {
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: null,
entity: buildEntity(),
operation: "read",
now: NOW,
});
expectRedactedDeny(result, "tenant_mismatch");
});
});
describe("authorizeApiRelationshipScope", () => {
test("allows service-token principals for relationship operations without entity scopes", () => {
const result = authorizeApiRelationshipScope(createServicePrincipal(), {
tenantId: "tenant-1",
parentEntityId: "missing-parent",
childEntityId: "missing-child",
operation: "delete",
});
expect(result).toEqual({
allowed: true,
principalType: "service-token",
});
});
test("denies relationship operations when the parent entity lacks the requested operation", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
parentEntityId: "missing-parent",
childEntityId: "child-entity",
operation: "read",
now: NOW,
});
expectRedactedDeny(result, "entity_permission_missing");
});
test("denies relationship operations when the child entity lacks the requested operation", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
parentEntityId: "entity-1",
childEntityId: "child-entity",
operation: "update",
now: NOW,
});
expectRedactedDeny(result, "operation_permission_missing");
});
test("allows relationship operations when parent and child entities both include the requested operation", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
parentEntityId: "entity-1",
childEntityId: "child-entity",
operation: "create",
now: NOW,
});
expect(result).toEqual({
allowed: true,
principalType: "api-key",
});
});
test("denies stored API keys for relationship operations when tenant scope cannot be resolved", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: null,
parentEntityId: "entity-1",
childEntityId: "child-entity",
operation: "read",
now: NOW,
});
expectRedactedDeny(result, "tenant_mismatch");
});
});
@@ -0,0 +1,54 @@
import type { LegacyEntity } from "@toolctrl/db/entities.server";
import { authorizeApiScope, type ApiKeyScopeOperation, type ApiScopedPrincipal, type ApiScopeResult } from "./scope.js";
export type ApiEntityRowScopeRequest = {
tenantId: string | null;
entity: LegacyEntity;
operation: ApiKeyScopeOperation;
now?: Date;
};
export type ApiRelationshipScopeRequest = {
tenantId: string | null;
parentEntityId: string;
childEntityId: string;
operation: ApiKeyScopeOperation;
now?: Date;
};
export function authorizeApiEntityRowScope(principal: ApiScopedPrincipal, request: ApiEntityRowScopeRequest): ApiScopeResult {
return authorizeApiScope(principal, {
tenantId: request.tenantId ?? "",
entityId: getLegacyEntityId(request.entity),
operation: request.operation,
now: request.now,
});
}
export function authorizeApiRelationshipScope(principal: ApiScopedPrincipal, request: ApiRelationshipScopeRequest): ApiScopeResult {
const parentScope = authorizeApiScope(principal, {
tenantId: request.tenantId ?? "",
entityId: request.parentEntityId,
operation: request.operation,
now: request.now,
});
if (!parentScope.allowed) {
return parentScope;
}
return authorizeApiScope(principal, {
tenantId: request.tenantId ?? "",
entityId: request.childEntityId,
operation: request.operation,
now: request.now,
});
}
function getLegacyEntityId(entity: LegacyEntity) {
if (entity && typeof entity === "object" && "id" in entity && typeof entity.id === "string" && entity.id) {
return entity.id;
}
throw new Error("Entity is missing an id.");
}
@@ -0,0 +1,130 @@
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import { describe, expect, test } from "vitest";
import { createServicePrincipal } from "../auth.js";
import { authorizeApiScope, createStoredApiKeyPrincipal, type ApiScopeResult } from "./scope.js";
const NOW = new Date("2026-01-15T12:00:00.000Z");
function buildApiKey(overrides: Partial<LegacyApiKeySimple> = {}): LegacyApiKeySimple {
return {
id: "api-key-1",
alias: "Production key",
expires: new Date("2026-02-01T00:00:00.000Z"),
tenantId: "tenant-1",
active: true,
entities: [
{
entityId: "entity-1",
create: true,
read: true,
update: true,
delete: false,
},
],
tenant: {
id: "tenant-1",
name: "Tenant One",
slug: "tenant-one",
deactivatedReason: null,
},
...overrides,
};
}
function authorize(apiKey: LegacyApiKeySimple, overrides: Partial<Parameters<typeof authorizeApiScope>[1]> = {}): ApiScopeResult {
return authorizeApiScope(createStoredApiKeyPrincipal(apiKey), {
tenantId: "tenant-1",
entityId: "entity-1",
operation: "read",
now: NOW,
...overrides,
});
}
function expectRedactedDeny(result: ApiScopeResult, reason: string) {
expect(result).toEqual({
allowed: false,
principalType: "api-key",
reason,
code: "FORBIDDEN_API_KEY_SCOPE",
});
const serialized = JSON.stringify(result);
expect(serialized).not.toContain("plaintext-secret");
expect(serialized).not.toContain("hash-value");
expect(serialized).not.toContain("service-token");
}
describe("authorizeApiScope", () => {
test("allows service-token principals for every scoped operation", () => {
const principal = createServicePrincipal();
expect(
authorizeApiScope(principal, {
tenantId: "other-tenant",
entityId: "unknown-entity",
operation: "delete",
now: NOW,
}),
).toEqual({
allowed: true,
principalType: "service-token",
});
});
test("allows active stored API keys with matching tenant, entity, and CRUD permission", () => {
expect(authorize(buildApiKey(), { operation: "create" })).toEqual({
allowed: true,
principalType: "api-key",
});
});
test("denies inactive stored API keys", () => {
expectRedactedDeny(authorize(buildApiKey({ active: false })), "api_key_inactive");
});
test("denies expired stored API keys", () => {
expectRedactedDeny(authorize(buildApiKey({ expires: new Date("2026-01-01T00:00:00.000Z") })), "api_key_expired");
});
test("denies stored API keys for deactivated tenants", () => {
expectRedactedDeny(
authorize(
buildApiKey({
tenant: {
id: "tenant-1",
name: "Tenant One",
slug: "tenant-one",
deactivatedReason: "billing_issue",
},
}),
),
"tenant_deactivated",
);
});
test("denies stored API keys whose tenant does not match the request tenant", () => {
expectRedactedDeny(authorize(buildApiKey(), { tenantId: "tenant-2" }), "tenant_mismatch");
expectRedactedDeny(
authorize(
buildApiKey({
tenant: {
id: "tenant-2",
name: "Tenant Two",
slug: "tenant-two",
deactivatedReason: null,
},
}),
),
"tenant_mismatch",
);
});
test("denies stored API keys missing the requested entity permission", () => {
expectRedactedDeny(authorize(buildApiKey(), { entityId: "entity-2" }), "entity_permission_missing");
});
test("denies stored API keys missing the requested CRUD operation permission", () => {
expectRedactedDeny(authorize(buildApiKey(), { operation: "delete" }), "operation_permission_missing");
});
});
@@ -0,0 +1,139 @@
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import type { ServicePrincipal } from "../auth.js";
export const API_KEY_SCOPE_OPERATIONS = ["read", "create", "update", "delete"] as const;
export type ApiKeyScopeOperation = (typeof API_KEY_SCOPE_OPERATIONS)[number];
export type StoredApiKeyPrincipal = {
type: "api-key";
apiKey: LegacyApiKeySimple;
};
export type ApiScopedPrincipal = ServicePrincipal | StoredApiKeyPrincipal;
export type ApiScopeRequest = {
tenantId: string;
entityId: string;
operation: ApiKeyScopeOperation;
now?: Date;
};
export type ApiScopeDenyReason =
| "api_key_inactive"
| "api_key_expired"
| "tenant_deactivated"
| "tenant_mismatch"
| "entity_permission_missing"
| "operation_permission_missing";
export type ApiScopeAllowed = {
allowed: true;
principalType: ApiScopedPrincipal["type"];
};
export type ApiTenantScopeAllowed = ApiScopeAllowed & {
tenantId: string | null;
};
export type ApiScopeDenied = {
allowed: false;
principalType: ApiScopedPrincipal["type"];
reason: ApiScopeDenyReason;
code: "FORBIDDEN_API_KEY_SCOPE";
};
export type ApiScopeResult = ApiScopeAllowed | ApiScopeDenied;
function deny(principalType: ApiScopedPrincipal["type"], reason: ApiScopeDenyReason): ApiScopeDenied {
return {
allowed: false,
principalType,
reason,
code: "FORBIDDEN_API_KEY_SCOPE",
};
}
export function createStoredApiKeyPrincipal(apiKey: LegacyApiKeySimple): StoredApiKeyPrincipal {
return {
type: "api-key",
apiKey,
};
}
export function authorizeApiScope(principal: ApiScopedPrincipal, request: ApiScopeRequest): ApiScopeResult {
if (principal.type === "service-token") {
return {
allowed: true,
principalType: principal.type,
};
}
const { apiKey } = principal;
if (!apiKey.active) {
return deny(principal.type, "api_key_inactive");
}
if (apiKey.expires && apiKey.expires.getTime() <= (request.now ?? new Date()).getTime()) {
return deny(principal.type, "api_key_expired");
}
if (apiKey.tenant.deactivatedReason) {
return deny(principal.type, "tenant_deactivated");
}
if (apiKey.tenantId !== request.tenantId || apiKey.tenant.id !== request.tenantId) {
return deny(principal.type, "tenant_mismatch");
}
const entityPermission = apiKey.entities.find((entity) => entity.entityId === request.entityId);
if (!entityPermission) {
return deny(principal.type, "entity_permission_missing");
}
if (!entityPermission[request.operation]) {
return deny(principal.type, "operation_permission_missing");
}
return {
allowed: true,
principalType: principal.type,
};
}
export function resolveApiTenantScope(principal: ApiScopedPrincipal, requestedTenantId: string | null, now = new Date()): ApiTenantScopeAllowed | ApiScopeDenied {
if (principal.type === "service-token") {
return {
allowed: true,
principalType: principal.type,
tenantId: requestedTenantId,
};
}
const { apiKey } = principal;
if (!apiKey.active) {
return deny(principal.type, "api_key_inactive");
}
if (apiKey.expires && apiKey.expires.getTime() <= now.getTime()) {
return deny(principal.type, "api_key_expired");
}
if (apiKey.tenant.deactivatedReason) {
return deny(principal.type, "tenant_deactivated");
}
if (apiKey.tenantId !== apiKey.tenant.id || (requestedTenantId && requestedTenantId !== apiKey.tenantId)) {
return deny(principal.type, "tenant_mismatch");
}
return {
allowed: true,
principalType: principal.type,
tenantId: apiKey.tenantId,
};
}
@@ -0,0 +1,154 @@
import { describe, expect, test } from "vitest";
import { createApiSessionStore } from "./session-store.js";
const START = new Date("2026-03-01T10:00:00.000Z");
function createDeterministicStore(ids: string[] = ["session-1", "session-2", "session-3"]) {
let nowMs = START.getTime();
let idIndex = 0;
return {
store: createApiSessionStore({
now: () => new Date(nowMs),
generateSessionId: () => ids[idIndex++] ?? `session-${idIndex}`,
}),
advance(ms: number) {
nowMs += ms;
},
};
}
describe("createApiSessionStore", () => {
test("creates active sessions with non-secret metadata and supports active lookup", () => {
const { store } = createDeterministicStore();
const session = store.createSession("user-1");
expect(session).toEqual({
sessionId: "session-1",
userId: "user-1",
createdAt: START,
revokedAt: undefined,
revokeReason: undefined,
});
expect(store.getActiveSession("session-1")).toEqual(session);
expect(JSON.stringify(session)).not.toContain("jwt");
expect(JSON.stringify(session)).not.toContain("cookie");
expect(JSON.stringify(session)).not.toContain("token");
});
test("returns cloned records so callers cannot mutate stored state", () => {
const { store } = createDeterministicStore();
const session = store.createSession("user-1");
session.createdAt.setUTCFullYear(2000);
session.userId = "changed";
expect(store.getSession("session-1")).toMatchObject({
sessionId: "session-1",
userId: "user-1",
createdAt: START,
});
});
test("revoke is idempotent and unknown revocation is a safe no-op", () => {
const { store, advance } = createDeterministicStore();
store.createSession("user-1");
advance(1_000);
const revoked = store.revokeSession("session-1", "logout");
advance(1_000);
const revokedAgain = store.revokeSession("session-1", "test");
expect(store.revokeSession("missing", "logout")).toBeUndefined();
expect(revoked).toMatchObject({
sessionId: "session-1",
revokedAt: new Date(START.getTime() + 1_000),
revokeReason: "logout",
});
expect(revokedAgain).toEqual(revoked);
expect(store.getActiveSession("session-1")).toBeUndefined();
});
test("rotate revokes the old session and activates the replacement", () => {
const { store, advance } = createDeterministicStore();
store.createSession("user-1");
advance(5_000);
const result = store.rotateSession("session-1", "refresh");
expect(result).toEqual({
rotated: true,
previous: {
sessionId: "session-1",
userId: "user-1",
createdAt: START,
revokedAt: new Date(START.getTime() + 5_000),
revokeReason: "refresh",
},
session: {
sessionId: "session-2",
userId: "user-1",
createdAt: new Date(START.getTime() + 5_000),
revokedAt: undefined,
revokeReason: undefined,
},
});
expect(store.getActiveSession("session-1")).toBeUndefined();
expect(result.rotated).toBe(true);
if (!result.rotated) {
throw new Error("Expected session rotation to succeed");
}
expect(store.getActiveSession("session-2")).toEqual(result.session);
});
test("unknown and revoked sessions cannot rotate", () => {
const { store } = createDeterministicStore();
store.createSession("user-1");
store.revokeSession("session-1", "logout");
expect(store.rotateSession("missing")).toEqual({ rotated: false, reason: "unknown" });
expect(store.rotateSession("session-1")).toEqual({
rotated: false,
reason: "revoked",
previous: store.getSession("session-1"),
});
});
test("happy path: createSession inserts on a single try without a retry loop", () => {
const ids: string[] = [];
const { store } = createDeterministicStore(["session-1"]);
// Wrap generateSessionId via a fresh store-spy: easier to assert call count
// through the public surface by tracking ids generated above.
const session = store.createSession("user-1");
ids.push(session.sessionId);
expect(ids).toEqual(["session-1"]);
expect(store.getActiveSession("session-1")).toMatchObject({ userId: "user-1" });
});
test("uuid collision is treated as a systemic error and throws (no retry loop)", () => {
// Force the id generator to return the same value twice; the legacy
// implementation looped to a fresh id, masking the underlying entropy bug.
const { store } = createDeterministicStore(["session-1", "session-1"]);
store.createSession("user-1");
expect(() => store.createSession("user-2")).toThrow(/UUID collision/);
// Original session must remain untouched.
expect(store.getActiveSession("session-1")).toMatchObject({ userId: "user-1" });
});
test("reset clears all sessions and isolates store state", () => {
const { store } = createDeterministicStore();
store.createSession("user-1");
store.createSession("user-2");
store.reset();
expect(store.getSession("session-1")).toBeUndefined();
expect(store.getActiveSession("session-2")).toBeUndefined();
expect(store.rotateSession("session-1")).toEqual({ rotated: false, reason: "unknown" });
});
});
@@ -0,0 +1,121 @@
import { randomUUID } from "node:crypto";
export type ApiSessionRevokeReason = "logout" | "refresh" | "replaced" | "duplicate" | "test" | (string & {});
export type ApiSessionRecord = {
sessionId: string;
userId: string;
createdAt: Date;
revokedAt?: Date;
revokeReason?: ApiSessionRevokeReason;
};
type Clock = () => Date;
type IdGenerator = () => string;
export type ApiSessionStoreOptions = {
now?: Clock;
generateSessionId?: IdGenerator;
};
export type RotateApiSessionResult =
| { rotated: true; previous: ApiSessionRecord; session: ApiSessionRecord }
| { rotated: false; reason: "unknown" | "revoked"; previous?: ApiSessionRecord };
const defaultClock: Clock = () => new Date();
const defaultIdGenerator: IdGenerator = () => randomUUID();
function cloneSession(session: ApiSessionRecord): ApiSessionRecord {
return {
sessionId: session.sessionId,
userId: session.userId,
createdAt: new Date(session.createdAt),
revokedAt: session.revokedAt ? new Date(session.revokedAt) : undefined,
revokeReason: session.revokeReason,
};
}
function isActive(session: ApiSessionRecord | undefined): session is ApiSessionRecord {
return Boolean(session && !session.revokedAt);
}
export function createApiSessionStore(options: ApiSessionStoreOptions = {}) {
const sessions = new Map<string, ApiSessionRecord>();
const now = options.now ?? defaultClock;
const generateSessionId = options.generateSessionId ?? defaultIdGenerator;
function createSession(userId: string): ApiSessionRecord {
const sessionId = generateSessionId();
// UUID-v4 has 122 bits of entropy; the birthday-paradox collision rate
// is ~10^-18 per insert. A retry loop is cargo-cult: any collision here
// signals a broken entropy source, not normal operation. Treat it as a
// systemic error so we surface the bug instead of masking it.
if (sessions.has(sessionId)) {
throw new Error(`api-session-store: refusing to overwrite session ${sessionId} (UUID collision suggests broken entropy source).`);
}
const session: ApiSessionRecord = {
sessionId,
userId,
createdAt: now(),
};
sessions.set(sessionId, session);
return cloneSession(session);
}
function getSession(sessionId: string): ApiSessionRecord | undefined {
const session = sessions.get(sessionId);
return session ? cloneSession(session) : undefined;
}
function getActiveSession(sessionId: string): ApiSessionRecord | undefined {
const session = sessions.get(sessionId);
return isActive(session) ? cloneSession(session) : undefined;
}
function revokeSession(sessionId: string, reason: ApiSessionRevokeReason = "logout"): ApiSessionRecord | undefined {
const session = sessions.get(sessionId);
if (!session) {
return undefined;
}
if (!session.revokedAt) {
session.revokedAt = now();
session.revokeReason = reason;
}
return cloneSession(session);
}
function rotateSession(sessionId: string, reason: ApiSessionRevokeReason = "refresh"): RotateApiSessionResult {
const previous = sessions.get(sessionId);
if (!previous) {
return { rotated: false, reason: "unknown" };
}
if (!isActive(previous)) {
return { rotated: false, reason: "revoked", previous: cloneSession(previous) };
}
previous.revokedAt = now();
previous.revokeReason = reason;
const session = createSession(previous.userId);
return { rotated: true, previous: cloneSession(previous), session };
}
function reset() {
sessions.clear();
}
return {
createSession,
getSession,
getActiveSession,
revokeSession,
rotateSession,
reset,
};
}
export const apiSessionStore = createApiSessionStore();