Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -6,7 +6,10 @@
"sideEffects": false,
"exports": {
".": "./src/index.ts",
"./spreadsheet-safety": "./src/spreadsheet-safety.ts",
"./trusted-client-ip": "./src/trusted-client-ip.ts",
"./outbound-http": "./src/outbound-http.ts",
"./marketing-token": "./src/marketing-token.ts",
"./crypto": "./src/crypto/index.ts"
},
"scripts": {
@@ -15,7 +18,6 @@
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@hivegrid/i18n": "workspace:*",
"undici": "^7.28.0"
},
"devDependencies": {
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { PortalActorAttributionError, requireExactlyOneActor, requirePortalUserActor } from "./customer-portal-actor.js";
describe("customer portal actor attribution", () => {
it("normalizes one internal actor", () => {
expect(requireExactlyOneActor({ createdByUserId: " user_1 " })).toEqual({
actorKind: "user",
actorId: "user_1",
createdByUserId: "user_1",
createdByPortalUserId: null,
});
});
it("normalizes one portal actor without a TenantUser fallback", () => {
expect(requirePortalUserActor({ createdByPortalUserId: " portal_user_1 " })).toEqual({
actorKind: "portal_user",
actorId: "portal_user_1",
createdByUserId: null,
createdByPortalUserId: "portal_user_1",
});
});
it.each([
{},
{ createdByUserId: "", createdByPortalUserId: " " },
{ createdByUserId: "user_1", createdByPortalUserId: "portal_user_1" },
])("rejects missing or ambiguous actors: %o", (input) => {
expect(() => requireExactlyOneActor(input)).toThrow(PortalActorAttributionError);
});
it("rejects an internal actor at the portal mutation boundary", () => {
expect(() => requirePortalUserActor({ createdByUserId: "synthetic-user" })).toThrowError(
expect.objectContaining({ code: "portal_actor_exactly_one_required" }),
);
});
});
@@ -0,0 +1,62 @@
export type PortalActorAttributionInput = {
readonly createdByUserId?: string | null;
readonly createdByPortalUserId?: string | null;
};
export type PortalActorAttribution =
| {
readonly actorKind: "user";
readonly actorId: string;
readonly createdByUserId: string;
readonly createdByPortalUserId: null;
}
| {
readonly actorKind: "portal_user";
readonly actorId: string;
readonly createdByUserId: null;
readonly createdByPortalUserId: string;
};
export class PortalActorAttributionError extends Error {
readonly code = "portal_actor_exactly_one_required";
constructor() {
super("Exactly one internal or portal actor is required");
this.name = "PortalActorAttributionError";
}
}
function normalizedId(value: string | null | undefined): string | null {
const normalized = value?.trim() ?? "";
return normalized.length > 0 ? normalized : null;
}
/**
* Mirrors the merge-migration CHECK for File, FileUpload, FileEntityLink and
* authenticated FormSubmission writes. Portal services call this before any
* Prisma mutation so feature-branch db-push databases fail closed too.
*/
export function requireExactlyOneActor(input: PortalActorAttributionInput): PortalActorAttribution {
const createdByUserId = normalizedId(input.createdByUserId);
const createdByPortalUserId = normalizedId(input.createdByPortalUserId);
if ((createdByUserId === null) === (createdByPortalUserId === null)) {
throw new PortalActorAttributionError();
}
if (createdByPortalUserId !== null) {
return { actorKind: "portal_user", actorId: createdByPortalUserId, createdByUserId: null, createdByPortalUserId };
}
const actorId = createdByUserId!;
return { actorKind: "user", actorId, createdByUserId: actorId, createdByPortalUserId: null };
}
/** Portal mutations must never smuggle in a synthetic TenantUser actor. */
export function requirePortalUserActor(input: PortalActorAttributionInput): Extract<PortalActorAttribution, { actorKind: "portal_user" }> {
const actor = requireExactlyOneActor(input);
if (actor.actorKind !== "portal_user") {
throw new PortalActorAttributionError();
}
return actor;
}
@@ -12,35 +12,41 @@ type StoredRow = {
/** In-memory idempotency client backed by a Map, mirroring the Prisma contract. */
function memoryClient() {
const rows = new Map<string, StoredRow>();
const keyOf = (scope: string, key: string) => `${scope}:${key}`;
const keyOf = (partitionKey: string, scope: string, key: string) => `${partitionKey}:${scope}:${key}`;
const client: IdempotencyClient = {
idempotencyKey: {
findUnique: vi.fn(async ({ where }) => rows.get(keyOf(where.idempotency_key_scope_key.scope, where.idempotency_key_scope_key.key)) ?? null),
findUnique: vi.fn(async ({ where }) => {
const key = where.idempotency_key_partition_scope_key;
return rows.get(keyOf(key.partitionKey, key.scope, key.key)) ?? null;
}),
create: vi.fn(async ({ data }) => {
const k = keyOf(data.scope, data.key);
const k = keyOf(data.partitionKey, data.scope, data.key);
if (rows.has(k)) throw Object.assign(new Error("unique"), { code: "P2002" });
rows.set(k, { requestHash: data.requestHash, responseStatus: data.responseStatus, responseBody: data.responseBody ?? null, responseHeaders: data.responseHeaders ?? null });
}),
update: vi.fn(async ({ where, data }) => {
const k = keyOf(where.idempotency_key_scope_key.scope, where.idempotency_key_scope_key.key);
const key = where.idempotency_key_partition_scope_key;
const k = keyOf(key.partitionKey, key.scope, key.key);
const existing = rows.get(k);
if (!existing) throw new Error("missing reservation");
rows.set(k, { ...existing, responseStatus: data.responseStatus, responseBody: data.responseBody ?? null, responseHeaders: data.responseHeaders ?? null });
}),
deleteMany: vi.fn(async ({ where } = {}) => {
if (where?.scope && where.key) rows.delete(keyOf(where.scope, where.key));
if (where?.partitionKey && where.scope && where.key) rows.delete(keyOf(where.partitionKey, where.scope, where.key));
}),
},
};
return { client, rows };
}
const tenantOwnership = { tenantId: "tenant_1" } as const;
describe("withIdempotency key handling", () => {
test("runs the operation directly when no idempotency key is supplied", async () => {
const { client } = memoryClient();
const operation = vi.fn(async () => ({ status: 200, body: { ok: true } }));
await expect(withIdempotency({ key: undefined, fingerprint: { a: 1 } }, client, operation)).resolves.toEqual({ status: 200, body: { ok: true }, replayed: false });
await expect(withIdempotency({ ...tenantOwnership, key: undefined, fingerprint: { a: 1 } }, client, operation)).resolves.toEqual({ status: 200, body: { ok: true }, replayed: false });
expect(operation).toHaveBeenCalledTimes(1);
expect(client.idempotencyKey.findUnique).not.toHaveBeenCalled();
});
@@ -49,7 +55,7 @@ describe("withIdempotency key handling", () => {
const { client } = memoryClient();
const operation = vi.fn(async () => ({ status: 201 }));
await expect(withIdempotency({ key: " ", fingerprint: 1 }, client, operation)).resolves.toMatchObject({ status: 201, replayed: false });
await expect(withIdempotency({ ...tenantOwnership, key: " ", fingerprint: 1 }, client, operation)).resolves.toMatchObject({ status: 201, replayed: false });
expect(client.idempotencyKey.create).not.toHaveBeenCalled();
});
});
@@ -59,8 +65,8 @@ describe("withIdempotency fingerprinting", () => {
const { client } = memoryClient();
const operation = vi.fn(async () => ({ status: 201, body: { ok: true } }));
await withIdempotency({ key: "k1", fingerprint: { a: 1, b: [2, 3] } }, client, operation);
const replay = await withIdempotency({ key: "k1", fingerprint: { b: [2, 3], a: 1 } }, client, operation);
await withIdempotency({ ...tenantOwnership, key: "k1", fingerprint: { a: 1, b: [2, 3] } }, client, operation);
const replay = await withIdempotency({ ...tenantOwnership, key: "k1", fingerprint: { b: [2, 3], a: 1 } }, client, operation);
expect(replay).toMatchObject({ replayed: true, status: 201, body: { ok: true } });
expect(operation).toHaveBeenCalledTimes(1);
@@ -68,35 +74,35 @@ describe("withIdempotency fingerprinting", () => {
test("replays stored response headers as well as the body", async () => {
const { client } = memoryClient();
await withIdempotency({ key: "kh", fingerprint: "a" }, client, async () => ({ status: 200, body: { ok: true }, headers: { "x-trace": "abc" } }));
const replay = await withIdempotency({ key: "kh", fingerprint: "a" }, client, async () => ({ status: 500 }));
await withIdempotency({ ...tenantOwnership, key: "kh", fingerprint: "a" }, client, async () => ({ status: 200, body: { ok: true }, headers: { "x-trace": "abc" } }));
const replay = await withIdempotency({ ...tenantOwnership, key: "kh", fingerprint: "a" }, client, async () => ({ status: 500 }));
expect(replay).toEqual({ status: 200, body: { ok: true }, headers: { "x-trace": "abc" }, replayed: true });
});
test("replays a stored no-content response without a body", async () => {
const { client } = memoryClient();
await withIdempotency({ key: "kn", fingerprint: "a" }, client, async () => ({ status: 204 }));
const replay = await withIdempotency({ key: "kn", fingerprint: "a" }, client, async () => ({ status: 500 }));
await withIdempotency({ ...tenantOwnership, key: "kn", fingerprint: "a" }, client, async () => ({ status: 204 }));
const replay = await withIdempotency({ ...tenantOwnership, key: "kn", fingerprint: "a" }, client, async () => ({ status: 500 }));
expect(replay).toEqual({ status: 204, body: undefined, headers: undefined, replayed: true });
});
test("rejects a replay whose fingerprint changed", async () => {
const { client } = memoryClient();
await withIdempotency({ key: "k2", fingerprint: "a" }, client, async () => ({ status: 200 }));
await withIdempotency({ ...tenantOwnership, key: "k2", fingerprint: "a" }, client, async () => ({ status: 200 }));
await expect(withIdempotency({ key: "k2", fingerprint: "b" }, client, async () => ({ status: 200 }))).rejects.toMatchObject({ code: "foundation.idempotency_conflict" });
await expect(withIdempotency({ ...tenantOwnership, key: "k2", fingerprint: "b" }, client, async () => ({ status: 200 }))).rejects.toMatchObject({ code: "foundation.idempotency_conflict" });
});
});
describe("withIdempotency reservation states", () => {
test("surfaces an in-progress error when a matching reservation has no response yet", async () => {
const { rows, client } = memoryClient();
rows.set("default:k3", { requestHash: JSON.stringify("a"), responseStatus: 0, responseBody: null, responseHeaders: null });
rows.set("tenant:tenant_1:default:k3", { requestHash: JSON.stringify("a"), responseStatus: 0, responseBody: null, responseHeaders: null });
const operation = vi.fn(async () => ({ status: 200 }));
await expect(withIdempotency({ key: "k3", fingerprint: "a" }, client, operation)).rejects.toMatchObject({ code: "foundation.idempotency_in_progress" });
await expect(withIdempotency({ ...tenantOwnership, key: "k3", fingerprint: "a" }, client, operation)).rejects.toMatchObject({ code: "foundation.idempotency_in_progress" });
expect(operation).not.toHaveBeenCalled();
});
@@ -115,7 +121,7 @@ describe("withIdempotency reservation states", () => {
};
const operation = vi.fn(async () => ({ status: 500 }));
await expect(withIdempotency({ key: "race", fingerprint: "a" }, client, operation)).resolves.toMatchObject({ replayed: true, status: 201, body: { ok: true } });
await expect(withIdempotency({ ...tenantOwnership, key: "race", fingerprint: "a" }, client, operation)).resolves.toMatchObject({ replayed: true, status: 201, body: { ok: true } });
expect(operation).not.toHaveBeenCalled();
});
@@ -132,7 +138,7 @@ describe("withIdempotency reservation states", () => {
},
};
await expect(withIdempotency({ key: "race2", fingerprint: "a" }, client, async () => ({ status: 200 }))).rejects.toBe(p2002);
await expect(withIdempotency({ ...tenantOwnership, key: "race2", fingerprint: "a" }, client, async () => ({ status: 200 }))).rejects.toBe(p2002);
});
test("rethrows non-unique-constraint create failures untouched", async () => {
@@ -147,7 +153,7 @@ describe("withIdempotency reservation states", () => {
},
};
await expect(withIdempotency({ key: "boom", fingerprint: "a" }, client, async () => ({ status: 200 }))).rejects.toThrow("db unavailable");
await expect(withIdempotency({ ...tenantOwnership, key: "boom", fingerprint: "a" }, client, async () => ({ status: 200 }))).rejects.toThrow("db unavailable");
});
});
@@ -157,14 +163,14 @@ describe("withIdempotency operation failures", () => {
const error = new Error("operation failed");
await expect(
withIdempotency({ key: "k4", fingerprint: "a" }, client, async () => {
withIdempotency({ ...tenantOwnership, key: "k4", fingerprint: "a" }, client, async () => {
throw error;
}),
).rejects.toBe(error);
expect(client.idempotencyKey.deleteMany).toHaveBeenCalledWith({ where: { scope: "default", key: "k4" } });
expect(client.idempotencyKey.deleteMany).toHaveBeenCalledWith({ where: { partitionKey: "tenant:tenant_1", scope: "default", key: "k4" } });
// After rollback the same key can be reserved again (no lingering reservation).
await expect(withIdempotency({ key: "k4", fingerprint: "a" }, client, async () => ({ status: 200 }))).resolves.toMatchObject({ status: 200, replayed: false });
await expect(withIdempotency({ ...tenantOwnership, key: "k4", fingerprint: "a" }, client, async () => ({ status: 200 }))).resolves.toMatchObject({ status: 200, replayed: false });
});
test("rethrows even when the client cannot delete the reservation", async () => {
@@ -178,7 +184,7 @@ describe("withIdempotency operation failures", () => {
};
await expect(
withIdempotency({ key: "k5", fingerprint: "a" }, client, async () => {
withIdempotency({ ...tenantOwnership, key: "k5", fingerprint: "a" }, client, async () => {
throw new Error("late failure");
}),
).rejects.toThrow("late failure");
@@ -6,9 +6,24 @@ export type IdempotencyResponse = {
headers?: Record<string, string>;
};
export const SYSTEM_IDEMPOTENCY_PARTITION = "system";
export type IdempotencyOwnership =
| { tenantId: string; systemOwned?: never }
| { tenantId?: never; systemOwned: true };
export type IdempotencyInput = IdempotencyOwnership & {
scope?: string;
key?: string | null;
fingerprint: JsonValue;
expiresAt?: Date | null;
};
export type IdempotencyClient = {
idempotencyKey: {
findUnique(args: { where: { idempotency_key_scope_key: { scope: string; key: string } } }): Promise<{
findUnique(args: {
where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } };
}): Promise<{
requestHash: string;
responseStatus: number;
responseBody: JsonValue | null;
@@ -17,6 +32,9 @@ export type IdempotencyClient = {
} | null>;
create(args: {
data: {
tenantId: string | null;
partitionKey: string;
systemOwned: boolean;
scope: string;
key: string;
requestHash: string;
@@ -27,7 +45,7 @@ export type IdempotencyClient = {
};
}): Promise<unknown>;
update(args: {
where: { idempotency_key_scope_key: { scope: string; key: string } };
where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } };
data: {
responseStatus: number;
responseBody?: JsonValue | null;
@@ -35,14 +53,16 @@ export type IdempotencyClient = {
expiresAt?: Date | null;
};
}): Promise<unknown>;
deleteMany?(args?: { where?: { scope?: string; key?: string; expiresAt?: { lte?: Date } } }): Promise<unknown>;
deleteMany?(args?: {
where?: { tenantId?: string | null; partitionKey?: string; systemOwned?: boolean; scope?: string; key?: string; expiresAt?: { lte?: Date } };
}): Promise<unknown>;
};
};
const idempotencyLockTails = new Map<string, Promise<void>>();
export async function withIdempotency(
input: { scope?: string; key?: string | null; fingerprint: JsonValue; expiresAt?: Date | null },
input: IdempotencyInput,
client: IdempotencyClient,
operation: () => Promise<IdempotencyResponse>,
): Promise<IdempotencyResponse & { replayed: boolean }> {
@@ -50,17 +70,29 @@ export async function withIdempotency(
if (!key) return { ...(await operation()), replayed: false };
const scope = input.scope ?? "default";
return runWithIdempotencyLock(`${scope}:${key}`, async () => runIdempotencyOperation({ ...input, scope, key }, client, operation));
const ownership = resolveIdempotencyOwnership(input);
return runWithIdempotencyLock(`${ownership.partitionKey}:${scope}:${key}`, async () =>
runIdempotencyOperation({ ...input, ...ownership, scope, key }, client, operation),
);
}
async function runIdempotencyOperation(
input: { scope: string; key: string; fingerprint: JsonValue; expiresAt?: Date | null },
input: {
tenantId: string | null;
partitionKey: string;
systemOwned: boolean;
scope: string;
key: string;
fingerprint: JsonValue;
expiresAt?: Date | null;
},
client: IdempotencyClient,
operation: () => Promise<IdempotencyResponse>,
): Promise<IdempotencyResponse & { replayed: boolean }> {
const { scope, key } = input;
const { partitionKey, scope, key } = input;
const requestHash = stableStringify(input.fingerprint);
const existing = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope, key } } });
const where = { idempotency_key_partition_scope_key: { partitionKey, scope, key } };
const existing = await client.idempotencyKey.findUnique({ where });
if (existing) {
return replayExistingIdempotencyResponse(existing, requestHash);
@@ -69,6 +101,9 @@ async function runIdempotencyOperation(
try {
await client.idempotencyKey.create({
data: {
tenantId: input.tenantId,
partitionKey,
systemOwned: input.systemOwned,
scope,
key,
requestHash,
@@ -82,7 +117,7 @@ async function runIdempotencyOperation(
if (!isUniqueConstraintError(error)) {
throw error;
}
const reserved = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope, key } } });
const reserved = await client.idempotencyKey.findUnique({ where });
if (reserved) {
return replayExistingIdempotencyResponse(reserved, requestHash);
}
@@ -92,7 +127,7 @@ async function runIdempotencyOperation(
try {
const response = await operation();
await client.idempotencyKey.update({
where: { idempotency_key_scope_key: { scope, key } },
where,
data: {
responseStatus: response.status,
responseBody: response.body ?? null,
@@ -102,11 +137,28 @@ async function runIdempotencyOperation(
});
return { ...response, replayed: false };
} catch (error) {
await client.idempotencyKey.deleteMany?.({ where: { scope, key } });
await client.idempotencyKey.deleteMany?.({ where: { partitionKey, scope, key } });
throw error;
}
}
export function resolveIdempotencyOwnership(input: IdempotencyOwnership): {
tenantId: string | null;
partitionKey: string;
systemOwned: boolean;
} {
if (input.systemOwned === true) {
return { tenantId: null, partitionKey: SYSTEM_IDEMPOTENCY_PARTITION, systemOwned: true };
}
const tenantId = input.tenantId.trim();
if (!tenantId) {
throw new Error("Tenant idempotency requires a non-empty tenantId.");
}
return { tenantId, partitionKey: `tenant:${tenantId}`, systemOwned: false };
}
function replayExistingIdempotencyResponse(
existing: {
requestHash: string;
@@ -87,9 +87,12 @@ describe("@hivegrid/foundation", () => {
const rows = new Map<string, { requestHash: string; responseStatus: number; responseBody: { ok: boolean } | null; responseHeaders: null }>();
const client = {
idempotencyKey: {
findUnique: vi.fn(async ({ where }) => rows.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`) ?? null),
findUnique: vi.fn(async ({ where }) => {
const key = where.idempotency_key_partition_scope_key;
return rows.get(`${key.partitionKey}:${key.scope}:${key.key}`) ?? null;
}),
create: vi.fn(async ({ data }) => {
const key = `${data.scope}:${data.key}`;
const key = `${data.partitionKey}:${data.scope}:${data.key}`;
if (rows.has(key)) throw Object.assign(new Error("unique"), { code: "P2002" });
rows.set(key, {
requestHash: data.requestHash,
@@ -99,7 +102,8 @@ describe("@hivegrid/foundation", () => {
});
}),
update: vi.fn(async ({ where, data }) => {
const key = `${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`;
const unique = where.idempotency_key_partition_scope_key;
const key = `${unique.partitionKey}:${unique.scope}:${unique.key}`;
const existing = rows.get(key);
if (!existing) throw new Error("missing reservation");
rows.set(key, {
@@ -110,16 +114,16 @@ describe("@hivegrid/foundation", () => {
});
}),
deleteMany: vi.fn(async ({ where }) => {
rows.delete(`${where.scope}:${where.key}`);
rows.delete(`${where.partitionKey}:${where.scope}:${where.key}`);
}),
},
};
const first = await withIdempotency({ key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 201, body: { ok: true } }));
const replay = await withIdempotency({ key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 500 }));
const first = await withIdempotency({ tenantId: "tenant_1", key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 201, body: { ok: true } }));
const replay = await withIdempotency({ tenantId: "tenant_1", key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 500 }));
expect(first.replayed).toBe(false);
expect(replay).toMatchObject({ replayed: true, status: 201, body: { ok: true } });
await expect(withIdempotency({ key: "key_1", fingerprint: { body: "b" } }, client, async () => ({ status: 200 }))).rejects.toThrow(CatalogError);
await expect(withIdempotency({ tenantId: "tenant_1", key: "key_1", fingerprint: { body: "b" } }, client, async () => ({ status: 200 }))).rejects.toThrow(CatalogError);
});
test("serializes concurrent idempotent operations for the same scope and key", async () => {
@@ -134,9 +138,12 @@ describe("@hivegrid/foundation", () => {
});
const client = {
idempotencyKey: {
findUnique: vi.fn(async ({ where }) => rows.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`) ?? null),
findUnique: vi.fn(async ({ where }) => {
const key = where.idempotency_key_partition_scope_key;
return rows.get(`${key.partitionKey}:${key.scope}:${key.key}`) ?? null;
}),
create: vi.fn(async ({ data }) => {
const key = `${data.scope}:${data.key}`;
const key = `${data.partitionKey}:${data.scope}:${data.key}`;
if (rows.has(key)) throw Object.assign(new Error("unique"), { code: "P2002" });
rows.set(key, {
requestHash: data.requestHash,
@@ -146,7 +153,8 @@ describe("@hivegrid/foundation", () => {
});
}),
update: vi.fn(async ({ where, data }) => {
const key = `${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`;
const unique = where.idempotency_key_partition_scope_key;
const key = `${unique.partitionKey}:${unique.scope}:${unique.key}`;
const existing = rows.get(key);
if (!existing) throw new Error("missing reservation");
rows.set(key, {
@@ -157,13 +165,13 @@ describe("@hivegrid/foundation", () => {
});
}),
deleteMany: vi.fn(async ({ where }) => {
rows.delete(`${where.scope}:${where.key}`);
rows.delete(`${where.partitionKey}:${where.scope}:${where.key}`);
}),
},
};
const first = withIdempotency({ scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation);
const second = withIdempotency({ scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation);
const first = withIdempotency({ tenantId: "tenant_1", scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation);
const second = withIdempotency({ tenantId: "tenant_1", scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation);
releaseOperation();
await expect(Promise.all([first, second])).resolves.toEqual([
@@ -256,7 +264,7 @@ describe("@hivegrid/foundation", () => {
expect(client.notificationDelivery.upsert).toHaveBeenCalledWith({
where: {
tenantId_userId_channel_sourceKey: {
notification_delivery_source_key: {
tenantId: "tenant_1",
userId: "user_1",
channel: "EMAIL",
@@ -9,3 +9,5 @@ export * from "./notifications.js";
export * from "./workflows.js";
export * from "./concurrency.js";
export * from "./mass-action.js";
export * from "./portal-status-mail.js";
export * from "./customer-portal-actor.js";
@@ -0,0 +1,122 @@
import { createHmac, timingSafeEqual } from "node:crypto";
type EnvRecord = Record<string, string | undefined>;
export type MarketingTokenPurpose = "unsub" | "optin";
export interface MarketingTokenPayload {
readonly purpose: MarketingTokenPurpose;
readonly tenantId: string;
readonly kontaktId: string;
readonly campaignId: string | null;
readonly iat: number;
}
export interface SignMarketingTokenInput {
readonly purpose: MarketingTokenPurpose;
readonly tenantId: string;
readonly kontaktId: string;
readonly campaignId?: string | null;
readonly now?: () => Date;
readonly secret?: string;
readonly env?: EnvRecord;
}
export interface VerifyMarketingTokenOptions {
readonly secret?: string;
readonly env?: EnvRecord;
readonly expectedPurpose?: MarketingTokenPurpose;
}
export class MarketingTokenSecretMissingError extends Error {
override readonly name = "MarketingTokenSecretMissingError";
constructor() {
super("MARKETING_TOKEN_SECRET env var is not set; cannot sign or verify marketing tokens.");
}
}
const TOKEN_VERSION = "m1";
const MIN_SECRET_BYTES = 32;
function getSecret(override?: string, env?: EnvRecord): Buffer {
const raw = override ?? env?.MARKETING_TOKEN_SECRET ?? env?.LEAD_CONVERSION_SECRET;
if (!raw || raw.length < MIN_SECRET_BYTES) throw new MarketingTokenSecretMissingError();
return Buffer.from(raw, "utf8");
}
function b64uEncode(input: Buffer | string): string {
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input, "utf8");
return buf.toString("base64url");
}
function b64uDecode(input: string): Buffer | null {
if (!/^[A-Za-z0-9_-]+$/u.test(input)) return null;
try {
return Buffer.from(input, "base64url");
} catch {
return null;
}
}
function nowSec(now?: () => Date): number {
return Math.floor((now ? now() : new Date()).getTime() / 1000);
}
export function signMarketingToken(input: SignMarketingTokenInput): string {
if (!input.tenantId || !input.kontaktId) {
throw new TypeError("signMarketingToken: tenantId and kontaktId required");
}
const secret = getSecret(input.secret, input.env);
const payload: MarketingTokenPayload = {
purpose: input.purpose,
tenantId: input.tenantId,
kontaktId: input.kontaktId,
campaignId: input.campaignId ?? null,
iat: nowSec(input.now),
};
const payloadB64 = b64uEncode(JSON.stringify(payload));
const sig = createHmac("sha256", secret).update(`${TOKEN_VERSION}.${payloadB64}`).digest();
return `${TOKEN_VERSION}.${payloadB64}.${b64uEncode(sig)}`;
}
export function verifyMarketingToken(token: string | null | undefined, options: VerifyMarketingTokenOptions = {}): MarketingTokenPayload | null {
if (!token || typeof token !== "string") return null;
const parts = token.split(".");
if (parts.length !== 3) return null;
const [version, payloadB64, sigB64] = parts;
if (version !== TOKEN_VERSION) return null;
let secret: Buffer;
try {
secret = getSecret(options.secret, options.env);
} catch {
return null;
}
const expected = createHmac("sha256", secret).update(`${version}.${payloadB64}`).digest();
const actual = b64uDecode(sigB64);
if (!actual || actual.length !== expected.length) return null;
if (!timingSafeEqual(actual, expected)) return null;
const payloadBuf = b64uDecode(payloadB64);
if (!payloadBuf) return null;
let parsed: unknown;
try {
parsed = JSON.parse(payloadBuf.toString("utf8"));
} catch {
return null;
}
if (!parsed || typeof parsed !== "object") return null;
const rec = parsed as Record<string, unknown>;
const purpose = rec.purpose;
if (purpose !== "unsub" && purpose !== "optin") return null;
if (options.expectedPurpose && purpose !== options.expectedPurpose) return null;
if (typeof rec.tenantId !== "string" || rec.tenantId.length === 0) return null;
if (typeof rec.kontaktId !== "string" || rec.kontaktId.length === 0) return null;
return {
purpose,
tenantId: rec.tenantId,
kontaktId: rec.kontaktId,
campaignId: typeof rec.campaignId === "string" ? rec.campaignId : null,
iat: typeof rec.iat === "number" ? rec.iat : 0,
};
}
@@ -1,7 +1,7 @@
import { CatalogError, type CatalogErrorDefinition, type JsonValue } from "./errors.js";
/**
* Mass-action guard (M005 / Pflichtenheft A.10.1).
* Mass-action guard (M005 contract).
*
* A bulk action that touches many records is "never armed directly": the user
* first sees a preview with the concrete impact ("würde 1.400 Personen betreffen,
@@ -3,10 +3,14 @@ import { describe, expect, test, vi } from "vitest";
import {
assertI18nKey,
bundleNotifications,
CRITICAL_NOTIFICATION_CATEGORIES,
isCriticalNotificationCategory,
isNotificationEnabled,
notify,
notifyPlatform,
type NotificationClient,
type NotificationInput,
type PlatformNotificationClient,
} from "./notifications.js";
function createClient() {
@@ -18,6 +22,23 @@ function createClient() {
} satisfies NotificationClient;
}
function createPlatformClient() {
const findFirst = vi.fn(async (): Promise<unknown | null> => null);
const create = vi.fn(
async (args: Parameters<PlatformNotificationClient["notificationDelivery"]["create"]>[0]): Promise<unknown> => ({
id: "platform_delivery_1",
...args.data,
})
);
return {
notificationDelivery: {
findFirst,
create,
},
} satisfies PlatformNotificationClient;
}
describe("assertI18nKey", () => {
test("returns valid dotted/dashed lowercase keys", () => {
expect(assertI18nKey("foundation.errors.not-found")).toBe("foundation.errors.not-found");
@@ -42,7 +63,7 @@ describe("notify payload sanitization", () => {
messageKey: "foundation.notifications.flags",
payloadMetadata: { active: true, dismissed: false, cleared: null, " ": "ignored" },
},
client,
client
);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
@@ -59,7 +80,7 @@ describe("notify payload sanitization", () => {
messageKey: "foundation.notifications.empty",
payloadMetadata: { nested: { deep: 1 }, infinite: Number.POSITIVE_INFINITY, broken: Number.NaN },
},
client,
client
);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ payloadMetadata: null }) });
@@ -67,10 +88,7 @@ describe("notify payload sanitization", () => {
test("truncates over-long string metadata to the configured maximum", async () => {
const client = createClient();
await notify(
{ tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.long", payloadMetadata: { note: "x".repeat(600) } },
client,
);
await notify({ tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.long", payloadMetadata: { note: "x".repeat(600) } }, client);
const call = client.notificationDelivery.create.mock.calls[0][0] as { data: { payloadMetadata: { note: string } } };
expect(call.data.payloadMetadata.note).toHaveLength(500);
@@ -89,11 +107,9 @@ describe("notify status mapping", () => {
test("marks deliveries SKIPPED when a preference disables the channel", async () => {
const client = createClient();
await notify(
{ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", messageKey: "foundation.notifications.invoice" },
client,
[{ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", enabled: false }],
);
await notify({ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", messageKey: "foundation.notifications.invoice" }, client, [
{ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", enabled: false },
]);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: expect.objectContaining({ status: "SKIPPED", attemptsMade: 0, lastError: "preference_disabled", sentAt: null }),
@@ -112,12 +128,178 @@ describe("notify status mapping", () => {
test("rejects an unscoped tenant before any write", async () => {
const client = createClient();
await expect(notify({ tenantId: " ", userId: "user_1", messageKey: "foundation.notifications.x" }, client)).rejects.toThrow(
"Notification delivery tenant scope is required.",
"Notification delivery tenant scope is required."
);
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
});
});
describe("notifyPlatform", () => {
test("persists a tenantless PENDING delivery with a mandatory recipient and source key", async () => {
const client = createPlatformClient();
await notifyPlatform(
{
userId: "user_haris",
channel: "EMAIL",
category: "Leads",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:email",
payloadMetadata: {
leadId: "lead_1",
sourceId: "hivegrid-website",
deeplink: "/leads/lead_1",
replay: false,
},
},
client
);
expect(client.notificationDelivery.findFirst).toHaveBeenCalledWith({
where: {
tenantId: null,
userId: "user_haris",
channel: "EMAIL",
sourceKey: "platform-lead:lead_1:email",
},
});
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: null,
userId: "user_haris",
channel: "EMAIL",
category: "leads",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:email",
status: "PENDING",
attemptsMade: 0,
payloadMetadata: {
leadId: "lead_1",
sourceId: "hivegrid-website",
deeplink: "/leads/lead_1",
replay: false,
},
}),
});
});
test("returns an existing logical delivery instead of creating a duplicate", async () => {
const client = createPlatformClient();
vi.mocked(client.notificationDelivery.findFirst).mockResolvedValue({ id: "existing_delivery" });
await expect(
notifyPlatform(
{
userId: "user_haris",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:in-app",
},
client
)
).resolves.toEqual({ id: "existing_delivery" });
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
});
test("returns the concurrent winner when the partial unique index rejects a racing insert", async () => {
const client = createPlatformClient();
vi.mocked(client.notificationDelivery.findFirst)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "concurrent_delivery" });
vi.mocked(client.notificationDelivery.create).mockRejectedValueOnce(new Error("unique constraint"));
await expect(
notifyPlatform(
{
userId: "user_haris",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:in-app",
},
client
)
).resolves.toEqual({ id: "concurrent_delivery" });
expect(client.notificationDelivery.findFirst).toHaveBeenCalledTimes(2);
});
test("does not hide an unrelated database failure when no concurrent delivery exists", async () => {
const client = createPlatformClient();
const databaseError = new Error("database unavailable");
vi.mocked(client.notificationDelivery.create).mockRejectedValueOnce(databaseError);
await expect(
notifyPlatform(
{
userId: "user_haris",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:in-app",
},
client
)
).rejects.toBe(databaseError);
expect(client.notificationDelivery.findFirst).toHaveBeenCalledTimes(2);
});
test("rejects tenant scope, empty recipients and unstable source keys before a write", async () => {
const client = createPlatformClient();
await expect(
notifyPlatform(
{
tenantId: null,
userId: "user_haris",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:in-app",
} as never,
client
)
).rejects.toThrow("must not accept a tenant scope");
await expect(notifyPlatform({ userId: " ", messageKey: "platform.leads.captured", sourceKey: "platform-lead:lead_1:in-app" }, client)).rejects.toThrow(
"userId must be a stable non-secret identifier"
);
await expect(notifyPlatform({ userId: "user_haris", messageKey: "platform.leads.captured", sourceKey: "Bearer secret/value" }, client)).rejects.toThrow(
"sourceKey must be a stable non-secret identifier"
);
await expect(
notifyPlatform(
{
userId: "user_haris",
channel: "SMS" as never,
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:sms",
},
client
)
).rejects.toThrow("channel must be IN_APP or EMAIL");
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
});
test("persists only allowlisted PII-minimized metadata", async () => {
const client = createPlatformClient();
await notifyPlatform(
{
userId: "user_haris",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:in-app",
payloadMetadata: {
leadId: "lead_1",
email: "person@example.test",
phone: "+491701234567",
message: "private lead message",
token: "secret-token",
deeplink: "/leads/lead_1?email=person@example.test",
},
},
client
);
const call = client.notificationDelivery.create.mock.calls[0]?.[0];
expect(call?.data.payloadMetadata).toEqual({ leadId: "lead_1" });
expect(JSON.stringify(call)).not.toContain("person@example.test");
expect(JSON.stringify(call)).not.toContain("private lead message");
expect(JSON.stringify(call)).not.toContain("secret-token");
});
});
describe("isNotificationEnabled", () => {
test("defaults to enabled when no preference exists for the scope", () => {
expect(isNotificationEnabled({ tenantId: "tenant_1", userId: "user_1", messageKey: "k" }, [])).toBe(true);
@@ -132,6 +314,35 @@ describe("isNotificationEnabled", () => {
const input: NotificationInput = { tenantId: "tenant_1", userId: null, channel: "IN_APP", category: "ops", messageKey: "k" };
expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", enabled: false }])).toBe(true);
});
test("critical categories stay enabled even with an explicit disabled preference", () => {
const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "critical", messageKey: "k" };
expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "critical", enabled: false }])).toBe(true);
});
test("critical categories ignore a disabled default fallback", () => {
const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: " Critical ", messageKey: "k" };
expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false }])).toBe(true);
});
test("a non-critical category still falls back to the disabled default", () => {
const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "system", messageKey: "k" };
expect(isNotificationEnabled(input, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false }])).toBe(false);
});
});
describe("isCriticalNotificationCategory", () => {
test("recognizes the critical category regardless of casing/whitespace", () => {
expect(isCriticalNotificationCategory("critical")).toBe(true);
expect(isCriticalNotificationCategory(" Critical ")).toBe(true);
expect(isCriticalNotificationCategory("system")).toBe(false);
expect(isCriticalNotificationCategory(null)).toBe(false);
expect(isCriticalNotificationCategory(undefined)).toBe(false);
});
test("exposes the critical set for the settings UI to mirror", () => {
expect([...CRITICAL_NOTIFICATION_CATEGORIES]).toContain("critical");
});
});
describe("bundleNotifications", () => {
@@ -10,6 +10,25 @@ export type NotificationInput = {
payloadMetadata?: Record<string, JsonValue> | null;
};
/**
* Operator-wide notifications are deliberately a separate contract from
* tenant notifications. Callers cannot provide a tenant scope, and both the
* recipient and the producer-stable source key are mandatory.
*
* `notifyPlatform()` persists the durable delivery intent as PENDING. The
* notification worker performs both IN_APP and EMAIL delivery after the
* surrounding transaction has committed.
*/
export type PlatformNotificationInput = {
tenantId?: never;
userId: string;
channel?: NotificationPreferenceChannel;
category?: string | null;
messageKey: string;
sourceKey: string;
payloadMetadata?: Record<string, JsonValue> | null;
};
export type NotificationPreferenceChannel = "IN_APP" | "EMAIL";
export type NotificationDeliveryStatus = "PENDING" | "SENT" | "FAILED" | "SKIPPED" | "READ";
export type NotificationPayloadMetadata = Record<string, string | number | boolean | null>;
@@ -52,7 +71,7 @@ export type NotificationClient = {
}): Promise<unknown>;
upsert?(args: {
where: {
tenantId_userId_channel_sourceKey: {
notification_delivery_source_key: {
tenantId: string;
userId: string;
channel: NotificationPreferenceChannel;
@@ -89,6 +108,36 @@ export type NotificationClient = {
};
};
export type PlatformNotificationClient = {
notificationDelivery: {
findFirst(args: {
where: {
tenantId: null;
userId: string;
channel: NotificationPreferenceChannel;
sourceKey: string;
};
}): Promise<unknown | null>;
create(args: {
data: {
tenantId: null;
userId: string;
channel: NotificationPreferenceChannel;
category: string;
messageKey: string;
sourceKey: string;
status: "PENDING";
attemptsMade: 0;
providerMessageId: null;
lastError: null;
payloadMetadata: NotificationPayloadMetadata | null;
sentAt: null;
readAt: null;
};
}): Promise<unknown>;
};
};
export async function notify(input: NotificationInput, client: NotificationClient, preferences: readonly NotificationPreference[] = []): Promise<unknown> {
const tenantId = requireNotificationTenantScope(input.tenantId);
const enabled = isNotificationEnabled(input, preferences);
@@ -102,7 +151,7 @@ export async function notify(input: NotificationInput, client: NotificationClien
category: normalizeNotificationCategory(input.category),
messageKey: input.messageKey,
sourceKey,
status: enabled ? channel === "IN_APP" ? "SENT" as const : "PENDING" as const : "SKIPPED" as const,
status: enabled ? (channel === "IN_APP" ? ("SENT" as const) : ("PENDING" as const)) : ("SKIPPED" as const),
attemptsMade: enabled && channel === "IN_APP" ? 1 : 0,
providerMessageId: null,
lastError: enabled ? null : "preference_disabled",
@@ -114,7 +163,7 @@ export async function notify(input: NotificationInput, client: NotificationClien
if (sourceKey && userId && client.notificationDelivery.upsert) {
return client.notificationDelivery.upsert({
where: {
tenantId_userId_channel_sourceKey: {
notification_delivery_source_key: {
tenantId,
userId,
channel,
@@ -139,19 +188,90 @@ export async function notify(input: NotificationInput, client: NotificationClien
return client.notificationDelivery.create({ data });
}
export async function notifyPlatform(input: PlatformNotificationInput, client: PlatformNotificationClient): Promise<unknown> {
if (Object.prototype.hasOwnProperty.call(input, "tenantId")) {
throw new Error("Platform notifications must not accept a tenant scope.");
}
const userId = requirePlatformNotificationIdentifier(input.userId, "userId");
const sourceKey = requirePlatformNotificationSourceKey(input.sourceKey);
const channel = requirePlatformNotificationChannel(input.channel ?? "IN_APP");
const messageKey = assertI18nKey(input.messageKey.trim());
const where = { tenantId: null, userId, channel, sourceKey } as const;
const existing = await client.notificationDelivery.findFirst({ where });
if (existing) {
return existing;
}
try {
return await client.notificationDelivery.create({
data: {
tenantId: null,
userId,
channel,
category: normalizeNotificationCategory(input.category),
messageKey,
sourceKey,
status: "PENDING",
attemptsMade: 0,
providerMessageId: null,
lastError: null,
payloadMetadata: sanitizePlatformNotificationPayloadMetadata(input.payloadMetadata),
sentAt: null,
readAt: null,
},
});
} catch (error) {
// The merge migration's partial unique index closes the race between the
// lookup above and this insert. Re-read after any failed insert so a
// concurrent winner is returned; unrelated database failures still
// propagate unchanged.
const concurrentDelivery = await client.notificationDelivery.findFirst({ where });
if (concurrentDelivery) {
return concurrentDelivery;
}
throw error;
}
}
/**
* Critical notification categories signal a functional-dependency failure the
* recipient must act on — a broken integration halts that tenant's sync, a
* failed billing charge, an expiring certificate. They are delivered regardless
* of the user's notification preferences, the same way a password-reset mail is
* never opt-out: suppressing them would hide that something the user relies on
* stopped working. Keep this set tiny and reserved for genuine "your stuff
* broke" alerts, never routine activity.
*
* This is the behavioral source of truth. The settings UI mirrors it as a
* locked, always-on group via @hivegrid/view-models
* NOTIFICATION_LOCKED_CATEGORY_REGISTRY — that display list MUST list the same
* category strings (guarded by its own vm test).
*/
export const CRITICAL_NOTIFICATION_CATEGORIES: ReadonlySet<string> = new Set(["critical"]);
/** True when the category is delivered regardless of user preferences. */
export function isCriticalNotificationCategory(category: string | null | undefined): boolean {
return CRITICAL_NOTIFICATION_CATEGORIES.has(normalizeNotificationCategory(category));
}
export function isNotificationEnabled(input: NotificationInput, preferences: readonly NotificationPreference[]): boolean {
const tenantId = requireNotificationTenantScope(input.tenantId);
const userId = input.userId ?? null;
const channel = input.channel ?? "IN_APP";
const category = normalizeNotificationCategory(input.category);
const scopedPreferences = preferences.filter(
(candidate) =>
candidate.tenantId === tenantId &&
candidate.userId === userId &&
candidate.channel === channel,
);
const preference = scopedPreferences.find((candidate) => candidate.category === category) ?? scopedPreferences.find((candidate) => candidate.category === "default");
// Critical categories are never suppressed by a user preference (functional
// dependency alerts). Checked before any preference lookup so even an explicit
// disabled row cannot switch them off.
if (isCriticalNotificationCategory(category)) {
return true;
}
const scopedPreferences = preferences.filter((candidate) => candidate.tenantId === tenantId && candidate.userId === userId && candidate.channel === channel);
const preference =
scopedPreferences.find((candidate) => candidate.category === category) ?? scopedPreferences.find((candidate) => candidate.category === "default");
return preference?.enabled ?? true;
}
@@ -165,16 +285,14 @@ export function bundleNotifications(inputs: readonly NotificationInput[]): reado
const channel = input.channel ?? "IN_APP";
const category = normalizeNotificationCategory(input.category);
const key = [tenantId ?? "", userId ?? "", channel, category].join(":");
const existing =
bundles.get(key) ??
{
tenantId,
userId,
channel,
category,
messageKeys: [],
payloadMetadata: {},
};
const existing = bundles.get(key) ?? {
tenantId,
userId,
channel,
category,
messageKeys: [],
payloadMetadata: {},
};
existing.messageKeys.push(input.messageKey);
if (input.payloadMetadata) {
@@ -210,6 +328,79 @@ function requireNotificationTenantScope(tenantId: string | null | undefined): st
const SENSITIVE_NOTIFICATION_METADATA_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i;
const NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH = 500;
const PLATFORM_NOTIFICATION_IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/u;
const PLATFORM_NOTIFICATION_DEEPLINK_PATTERN = /^\/[A-Za-z0-9/_-]{1,239}$/u;
const PLATFORM_NOTIFICATION_METADATA_IDENTIFIER_KEYS = new Set(["deliveryId", "eventId", "leadId", "requestId", "sourceId"]);
const PLATFORM_NOTIFICATION_METADATA_EVENT_KEYS = new Set(["eventType"]);
function requirePlatformNotificationIdentifier(value: string, field: string): string {
const normalized = value?.trim();
if (!normalized || !PLATFORM_NOTIFICATION_IDENTIFIER_PATTERN.test(normalized)) {
throw new Error(`Platform notification ${field} must be a stable non-secret identifier.`);
}
return normalized;
}
function requirePlatformNotificationSourceKey(value: string): string {
return requirePlatformNotificationIdentifier(value, "sourceKey");
}
function requirePlatformNotificationChannel(value: string): NotificationPreferenceChannel {
if (value !== "IN_APP" && value !== "EMAIL") {
throw new Error("Platform notification channel must be IN_APP or EMAIL.");
}
return value;
}
/**
* Platform delivery diagnostics use a positive allowlist. Contact data,
* message bodies and arbitrary producer payloads therefore never reach the
* NotificationDelivery metadata column or worker diagnostics.
*/
export function sanitizePlatformNotificationPayloadMetadata(payloadMetadata?: Record<string, JsonValue> | null): NotificationPayloadMetadata | null {
if (!payloadMetadata) {
return null;
}
const sanitized: NotificationPayloadMetadata = {};
for (const [rawKey, value] of Object.entries(payloadMetadata)) {
const key = rawKey.trim();
if (PLATFORM_NOTIFICATION_METADATA_IDENTIFIER_KEYS.has(key) && typeof value === "string") {
const normalized = value.trim();
if (PLATFORM_NOTIFICATION_IDENTIFIER_PATTERN.test(normalized)) {
sanitized[key] = normalized;
}
continue;
}
if (PLATFORM_NOTIFICATION_METADATA_EVENT_KEYS.has(key) && typeof value === "string") {
const normalized = value.trim();
if (/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(normalized)) {
sanitized[key] = normalized;
}
continue;
}
if (key === "deeplink" && typeof value === "string") {
const normalized = value.trim();
if (PLATFORM_NOTIFICATION_DEEPLINK_PATTERN.test(normalized)) {
sanitized[key] = normalized;
}
continue;
}
if (key === "replay" && typeof value === "boolean") {
sanitized[key] = value;
}
}
return Object.keys(sanitized).length > 0 ? sanitized : null;
}
function sanitizeNotificationPayloadMetadata(payloadMetadata?: Record<string, JsonValue> | null): NotificationPayloadMetadata | null {
if (!payloadMetadata) {
@@ -240,7 +431,7 @@ function sanitizeNotificationPayloadMetadata(payloadMetadata?: Record<string, Js
export async function notifyMany(
inputs: readonly NotificationInput[],
client: NotificationClient,
preferences: readonly NotificationPreference[] = [],
preferences: readonly NotificationPreference[] = []
): Promise<unknown[]> {
return Promise.all(inputs.map((input) => notify(input, client, preferences)));
}
@@ -83,6 +83,32 @@ describe("validateOutboundHttpUrl IPv6 SSRF ranges", () => {
});
describe("fetchOutboundHttpWithRedirects redirect handling", () => {
test("applies a feature-specific URL policy before every redirect hop", async () => {
const fetchImpl = vi.fn(async () => new Response(null, { status: 302, headers: { location: "https://hooks.example.com:8443/private" } }));
const urlValidator = vi.fn((value: string) => {
const url = new URL(validateOutboundHttpUrl(value));
if (url.port) throw new Error("feature policy rejected non-default port");
return url.toString();
});
await expect(
fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver: publicResolver, urlValidator })
).rejects.toThrow("feature policy rejected non-default port");
expect(fetchImpl).toHaveBeenCalledTimes(1);
expect(urlValidator).toHaveBeenNthCalledWith(1, "https://api.example.com/start");
expect(urlValidator).toHaveBeenNthCalledWith(2, "https://hooks.example.com:8443/private");
});
test("does not let a feature-specific validator weaken the foundation SSRF policy", async () => {
const fetchImpl = vi.fn(async () => new Response("unexpected", { status: 200 }));
await expect(fetchOutboundHttpWithRedirects("http://127.0.0.1/private", { method: "GET" }, { fetchImpl, urlValidator: (value) => value })).rejects.toThrow(
"Outbound HTTP endpoint host is not allowed."
);
expect(fetchImpl).not.toHaveBeenCalled();
});
test("returns the redirect response unchanged when no location header is present", async () => {
const fetchImpl = vi.fn(async () => new Response("redirect-without-location", { status: 302 }));
const result = await fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver: publicResolver });
@@ -95,7 +121,7 @@ describe("fetchOutboundHttpWithRedirects redirect handling", () => {
const fetchImpl = vi.fn(async () => new Response(null, { status: 302, headers: { location: "https://hooks.example.com/loop" } }));
await expect(
fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver: publicResolver, redirectLimit: 0 }),
fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver: publicResolver, redirectLimit: 0 })
).rejects.toThrow("Outbound HTTP redirect limit exceeded.");
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
@@ -110,8 +136,8 @@ describe("fetchOutboundHttpWithRedirects redirect handling", () => {
fetchOutboundHttpWithRedirects(
"https://api.example.com/start",
{ method: "POST", body: "payload", headers: { "content-type": "application/json", "content-length": "7", "x-trace": "keep" } },
{ fetchImpl, addressResolver: publicResolver },
),
{ fetchImpl, addressResolver: publicResolver }
)
).resolves.toMatchObject({ status: 200 });
const secondInit = fetchImpl.mock.calls[1][1] as RequestInit & { headers: Headers };
@@ -135,12 +161,89 @@ describe("fetchOutboundHttpWithRedirects redirect handling", () => {
expect(secondInit.body).toBe("payload");
});
test.each([307, 308])("strips target-bound credentials on a cross-origin %s redirect", async (status) => {
const fetchImpl = vi
.fn()
.mockResolvedValueOnce(new Response(null, { status, headers: { location: "https://receiver.example/again" } }))
.mockResolvedValueOnce(new Response("ok", { status: 200 }));
await fetchOutboundHttpWithRedirects(
"https://hooks.example.com/start",
{
method: "POST",
body: "payload",
headers: {
authorization: "Bearer auth-secret",
cookie: "session=cookie-secret",
"proxy-authorization": "Basic proxy-secret",
"x-api-key": "api-secret",
"x-client-credential": "client-secret",
"x-custom-secret": "custom-secret",
"x-hook-hmac": "hook-secret",
"x-hivegrid-signature": "webhook-secret",
"x-webhook-key": "opaque-secret",
"content-type": "application/json",
"x-idempotency-key": "delivery-1",
"x-trace-id": "trace-1",
},
},
{ fetchImpl, addressResolver: publicResolver }
);
const secondInit = fetchImpl.mock.calls[1][1] as RequestInit;
const redirectedHeaders = new Headers(secondInit.headers);
expect(secondInit.method).toBe("POST");
expect(secondInit.body).toBe("payload");
expect(redirectedHeaders.get("authorization")).toBeNull();
expect(redirectedHeaders.get("cookie")).toBeNull();
expect(redirectedHeaders.get("proxy-authorization")).toBeNull();
expect(redirectedHeaders.get("x-api-key")).toBeNull();
expect(redirectedHeaders.get("x-client-credential")).toBeNull();
expect(redirectedHeaders.get("x-custom-secret")).toBeNull();
expect(redirectedHeaders.get("x-hook-hmac")).toBeNull();
expect(redirectedHeaders.get("x-hivegrid-signature")).toBeNull();
expect(redirectedHeaders.get("x-webhook-key")).toBeNull();
expect(redirectedHeaders.get("content-type")).toBe("application/json");
expect(redirectedHeaders.get("x-idempotency-key")).toBe("delivery-1");
expect(redirectedHeaders.get("x-trace-id")).toBe("trace-1");
});
test("keeps target-bound credentials on a same-origin redirect", async () => {
const fetchImpl = vi
.fn()
.mockResolvedValueOnce(new Response(null, { status: 307, headers: { location: "/again" } }))
.mockResolvedValueOnce(new Response("ok", { status: 200 }));
await fetchOutboundHttpWithRedirects(
"https://hooks.example.com/start",
{ method: "POST", body: "payload", headers: { authorization: "Bearer secret", "x-hivegrid-signature": "sha256=secret" } },
{ fetchImpl, addressResolver: publicResolver }
);
const redirectedHeaders = new Headers(fetchImpl.mock.calls[1][1]?.headers);
expect(redirectedHeaders.get("authorization")).toBe("Bearer secret");
expect(redirectedHeaders.get("x-hivegrid-signature")).toBe("sha256=secret");
});
test("can reject cross-origin redirects before target-bound credentials are forwarded", async () => {
const fetchImpl = vi.fn(async () => new Response(null, { status: 307, headers: { location: "https://attacker.example/steal" } }));
await expect(
fetchOutboundHttpWithRedirects(
"https://hooks.example.com/start",
{ method: "POST", headers: { "x-hivegrid-signature": "secret" }, body: "payload" },
{ fetchImpl, addressResolver: publicResolver, allowCrossOriginRedirects: false }
)
).rejects.toThrow("cross-origin redirect is not allowed");
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
test("rejects a redirect to a literal private IPv4 target", async () => {
const fetchImpl = vi.fn(async () => new Response(null, { status: 301, headers: { location: "http://192.168.0.5/internal" } }));
await expect(fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver: publicResolver })).rejects.toThrow(
"Outbound HTTP endpoint host is not allowed.",
);
await expect(
fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver: publicResolver })
).rejects.toThrow("Outbound HTTP endpoint host is not allowed.");
});
test("surfaces a resolver failure as an unresolved-host error", async () => {
@@ -150,7 +253,7 @@ describe("fetchOutboundHttpWithRedirects redirect handling", () => {
});
await expect(fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver })).rejects.toThrow(
"Outbound HTTP endpoint host could not be resolved.",
"Outbound HTTP endpoint host could not be resolved."
);
expect(fetchImpl).not.toHaveBeenCalled();
});
@@ -160,7 +263,7 @@ describe("fetchOutboundHttpWithRedirects redirect handling", () => {
const addressResolver = vi.fn(async () => []);
await expect(fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver })).rejects.toThrow(
"Outbound HTTP endpoint host could not be resolved.",
"Outbound HTTP endpoint host could not be resolved."
);
});
@@ -7,6 +7,8 @@ describe("outbound HTTP guard", () => {
test("blocks private and internal targets", () => {
expect(() => validateOutboundHttpUrl("http://127.0.0.1/metadata")).toThrow("Outbound HTTP endpoint host is not allowed.");
expect(() => validateOutboundHttpUrl("http://[fec0::1]/internal")).toThrow("Outbound HTTP endpoint host is not allowed.");
expect(() => validateOutboundHttpUrl("http://[ff02::1]/multicast")).toThrow("Outbound HTTP endpoint host is not allowed.");
expect(() => validateOutboundHttpUrl("https://service.internal/hook")).toThrow("Outbound HTTP endpoint host is not allowed.");
expect(validateOutboundHttpUrl("https://hooks.example.com/workflow")).toBe("https://hooks.example.com/workflow");
});
@@ -59,7 +61,11 @@ describe("outbound HTTP guard", () => {
});
test("pins the connection to the DNS-validated address to defeat rebinding", async () => {
const fetchImpl = vi.fn(async () => new Response("ok", { status: 200 }));
const fetchImpl = vi.fn(async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
void input;
void init;
return new Response("ok", { status: 200 });
});
const addressResolver = vi.fn(async () => ["93.184.216.34"]);
await fetchOutboundHttpWithRedirects(
@@ -74,8 +80,38 @@ describe("outbound HTTP guard", () => {
expect(init?.dispatcher).toBeDefined();
});
test("closes every pinned dispatcher after redirect and final-response hops", async () => {
const { Agent } = await import("undici");
const closeSpy = vi.spyOn(Agent.prototype, "close");
const fetchImpl = vi
.fn()
.mockResolvedValueOnce(new Response(null, { status: 307, headers: { location: "https://hooks.example.com/final" } }))
.mockResolvedValueOnce(new Response("ok", { status: 200 }));
try {
const response = await fetchOutboundHttpWithRedirects(
"https://hooks.example.com/start",
{ method: "POST", body: "payload" },
{ fetchImpl, addressResolver: publicResolver, pinResolvedAddress: true }
);
await response.text();
expect(fetchImpl).toHaveBeenCalledTimes(2);
const hopDispatchers = fetchImpl.mock.calls.map((call) => (call[1] as RequestInit & { dispatcher?: unknown }).dispatcher);
expect(new Set(hopDispatchers).size).toBe(2);
const closedDispatchers = new Set<unknown>(closeSpy.mock.instances);
expect(hopDispatchers.every((dispatcher) => closedDispatchers.has(dispatcher))).toBe(true);
} finally {
closeSpy.mockRestore();
}
});
test("does not pin when a custom fetchImpl is used without opting in", async () => {
const fetchImpl = vi.fn(async () => new Response("ok", { status: 200 }));
const fetchImpl = vi.fn(async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
void input;
void init;
return new Response("ok", { status: 200 });
});
const addressResolver = vi.fn(async () => ["93.184.216.34"]);
await fetchOutboundHttpWithRedirects("https://hooks.example.com/webhook", { method: "GET" }, { fetchImpl, addressResolver });
@@ -4,6 +4,31 @@ const DEFAULT_OUTBOUND_HTTP_TIMEOUT_MS = 10_000;
const DEFAULT_OUTBOUND_HTTP_REDIRECT_LIMIT = 5;
const DEFAULT_OUTBOUND_HTTP_RESPONSE_LIMIT_BYTES = 16_384;
const INTERNAL_OUTBOUND_HOST_SUFFIXES = [".localhost", ".local", ".internal", ".lan", ".home", ".corp", ".intranet", ".svc"] as const;
const SENSITIVE_REDIRECT_HEADER_NAMES = new Set(["authorization", "cookie", "cookie2", "proxy-authorization"]);
const SENSITIVE_REDIRECT_HEADER_SEGMENTS = new Set([
"apikey",
"auth",
"authentication",
"bearer",
"credential",
"credentials",
"csrf",
"hmac",
"jwt",
"key",
"nonce",
"password",
"passphrase",
"session",
"secret",
"secrets",
"sig",
"signature",
"signatures",
"token",
"tokens",
"xsrf",
]);
export class OutboundHttpUrlValidationError extends Error {
constructor(message: string) {
@@ -15,8 +40,15 @@ export class OutboundHttpUrlValidationError extends Error {
export type OutboundHttpFetchOptions = {
fetchImpl?: typeof fetch;
addressResolver?: OutboundHttpAddressResolver;
/**
* Optional feature-specific URL policy. It is applied to the initial URL
* and every redirect before DNS resolution or network I/O for that hop.
*/
urlValidator?: OutboundHttpUrlValidator;
timeoutMs?: number;
redirectLimit?: number;
/** Reject redirects to a different origin. Sensitive headers are always stripped when redirects are allowed. */
allowCrossOriginRedirects?: boolean;
/**
* Pin the TCP connection to the DNS-validated IP so a low-TTL hostname cannot
* answer a public address to the guard and an internal one to the connect
@@ -33,6 +65,7 @@ export type LimitedResponseBody = {
};
export type OutboundHttpAddressResolver = (hostname: string) => Promise<ReadonlyArray<string>>;
export type OutboundHttpUrlValidator = (endpoint: string) => string;
export async function fetchOutboundHttpWithRedirects(input: string, init: RequestInit, options: OutboundHttpFetchOptions = {}): Promise<Response> {
const usingDefaultFetch = !options.fetchImpl;
@@ -43,33 +76,48 @@ export async function fetchOutboundHttpWithRedirects(input: string, init: Reques
const fetchImpl = options.fetchImpl ?? (pin ? await getUndiciFetch() : fetch);
const addressResolver = options.addressResolver ?? resolveOutboundHttpAddresses;
const redirectLimit = options.redirectLimit ?? DEFAULT_OUTBOUND_HTTP_REDIRECT_LIMIT;
let currentUrl = validateOutboundHttpUrl(input);
// A feature policy may only narrow the foundation policy, never replace it.
// Applying the generic guard to its result prevents a custom validator from
// accidentally reintroducing private/link-local targets.
const validateUrl: OutboundHttpUrlValidator = (endpoint) => validateOutboundHttpUrl(options.urlValidator ? options.urlValidator(endpoint) : endpoint);
let currentUrl = validateUrl(input);
let currentInit = init;
for (let redirects = 0; redirects <= redirectLimit; redirects += 1) {
const validatedAddresses = await assertOutboundHttpResolvedAddresses(currentUrl, addressResolver);
const response = await fetchOutboundHttpWithTimeout(
const hop = await fetchOutboundHttpWithTimeout(
fetchImpl,
currentUrl,
currentInit,
options.timeoutMs ?? DEFAULT_OUTBOUND_HTTP_TIMEOUT_MS,
pin ? validatedAddresses : null,
pin ? validatedAddresses : null
);
const response = hop.response;
if (!isRedirectResponse(response.status)) {
beginPinnedDispatcherClose(hop.closeDispatcher);
return response;
}
const location = response.headers.get("location");
if (!location) {
beginPinnedDispatcherClose(hop.closeDispatcher);
return response;
}
await response.body?.cancel().catch(() => undefined);
await hop.closeDispatcher().catch(() => undefined);
if (redirects === redirectLimit) {
throw new OutboundHttpUrlValidationError("Outbound HTTP redirect limit exceeded.");
}
currentUrl = resolveOutboundHttpRedirect(currentUrl, location);
currentInit = buildRedirectRequestInit(currentInit, response.status);
const redirectUrl = resolveOutboundHttpRedirect(currentUrl, location, validateUrl);
const isCrossOrigin = new URL(redirectUrl).origin !== new URL(currentUrl).origin;
if (options.allowCrossOriginRedirects === false && isCrossOrigin) {
throw new OutboundHttpUrlValidationError("Outbound HTTP cross-origin redirect is not allowed.");
}
currentUrl = redirectUrl;
currentInit = buildRedirectRequestInit(currentInit, response.status, isCrossOrigin);
}
throw new OutboundHttpUrlValidationError("Outbound HTTP redirect limit exceeded.");
@@ -131,7 +179,10 @@ export function validateOutboundHttpUrl(endpoint: string): string {
async function assertOutboundHttpResolvedAddresses(endpoint: string, addressResolver: OutboundHttpAddressResolver): Promise<ReadonlyArray<string>> {
const url = new URL(endpoint);
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
const hostname = url.hostname
.toLowerCase()
.replace(/^\[|\]$/g, "")
.replace(/\.$/, "");
// An IP literal has already been vetted by validateOutboundHttpUrl and needs
// no DNS resolution — return it so the connection pins to exactly that IP.
if (parseIpv4Address(hostname) || parseIpv6Address(hostname)) {
@@ -167,24 +218,25 @@ async function fetchOutboundHttpWithTimeout(
input: Parameters<typeof fetch>[0],
init: RequestInit,
timeoutMs: number,
pinnedAddresses: ReadonlyArray<string> | null,
): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const baseInit = { ...init, redirect: "manual" as const, signal: controller.signal };
if (pinnedAddresses && pinnedAddresses.length > 0) {
// `dispatcher` is a Node/undici extension to RequestInit; the pinned Agent
// forces the socket to the DNS-validated IP while undici keeps the URL
// hostname as the TLS SNI/servername.
const dispatcher = await buildPinnedDispatcher(pinnedAddresses);
return await fetchImpl(input, { ...baseInit, dispatcher } as RequestInit);
pinnedAddresses: ReadonlyArray<string> | null
): Promise<{ response: Response; closeDispatcher: () => Promise<void> }> {
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
const baseInit = { ...init, redirect: "manual" as const, signal };
if (pinnedAddresses && pinnedAddresses.length > 0) {
// `dispatcher` is a Node/undici extension to RequestInit; the pinned Agent
// forces the socket to the DNS-validated IP while undici keeps the URL
// hostname as the TLS SNI/servername.
const dispatcher = await buildPinnedDispatcher(pinnedAddresses);
try {
const response = await fetchImpl(input, { ...baseInit, dispatcher: dispatcher.value } as RequestInit);
return { response, closeDispatcher: dispatcher.close };
} catch (error) {
await dispatcher.destroy(error instanceof Error ? error : undefined).catch(() => undefined);
throw error;
}
return await fetchImpl(input, baseInit);
} finally {
clearTimeout(timeout);
}
return { response: await fetchImpl(input, baseInit), closeDispatcher: async () => undefined };
}
let undiciModulePromise: Promise<typeof import("undici")> | null = null;
@@ -205,7 +257,11 @@ async function getUndiciFetch(): Promise<typeof fetch> {
* closes the rebinding TOCTOU: the connection can only reach an address the
* blocklist already cleared.
*/
async function buildPinnedDispatcher(addresses: ReadonlyArray<string>): Promise<unknown> {
async function buildPinnedDispatcher(addresses: ReadonlyArray<string>): Promise<{
value: unknown;
close: () => Promise<void>;
destroy: (error?: Error) => Promise<void>;
}> {
const { Agent } = await loadUndici();
const vetted = addresses.map((address) => ({ address, family: address.includes(":") ? 6 : 4 }));
const [primary] = vetted;
@@ -216,36 +272,78 @@ async function buildPinnedDispatcher(addresses: ReadonlyArray<string>): Promise<
}
callback(null, primary?.address ?? "", primary?.family ?? 4);
};
return new Agent({ connect: { lookup } });
const agent = new Agent({ connect: { lookup } });
let shutdown: Promise<void> | null = null;
return {
value: agent,
close: () => (shutdown ??= agent.close()),
destroy: (error) => (shutdown ??= agent.destroy(error ?? null)),
};
}
function resolveOutboundHttpRedirect(currentUrl: string, location: string): string {
function beginPinnedDispatcherClose(closeDispatcher: () => Promise<void>): void {
// `Agent.close()` stops accepting work immediately and resolves after the
// returned response body finishes. Starting it before returning prevents a
// forgotten per-request Agent from retaining idle sockets indefinitely.
void closeDispatcher().catch(() => undefined);
}
function resolveOutboundHttpRedirect(currentUrl: string, location: string, validateUrl: OutboundHttpUrlValidator): string {
let redirectUrl: URL;
try {
redirectUrl = new URL(location, currentUrl);
} catch {
throw new OutboundHttpUrlValidationError("Outbound HTTP redirect location must be a valid URL.");
}
return validateOutboundHttpUrl(redirectUrl.toString());
return validateUrl(redirectUrl.toString());
}
function isRedirectResponse(status: number): boolean {
return status >= 300 && status < 400;
}
function buildRedirectRequestInit(init: RequestInit, status: number): RequestInit {
function buildRedirectRequestInit(init: RequestInit, status: number, isCrossOrigin: boolean): RequestInit {
const method = typeof init.method === "string" ? init.method.toUpperCase() : undefined;
let redirectedInit = init;
if (status === 303 || ((status === 301 || status === 302) && method === "POST")) {
const headers = new Headers(init.headers);
headers.delete("content-type");
headers.delete("content-length");
return { ...init, method: "GET", body: undefined, headers };
redirectedInit = { ...init, method: "GET", body: undefined, headers };
}
return init;
if (!isCrossOrigin) {
return redirectedInit;
}
const headers = new Headers(redirectedInit.headers);
// Snapshot first: deleting while iterating a Headers list can skip the entry
// that shifts into the current slot (notably Proxy-Authorization).
for (const name of [...headers.keys()]) {
if (isSensitiveCrossOriginRedirectHeader(name)) {
headers.delete(name);
}
}
return { ...redirectedInit, headers };
}
function isSensitiveCrossOriginRedirectHeader(name: string): boolean {
const normalized = name.toLowerCase();
if (SENSITIVE_REDIRECT_HEADER_NAMES.has(normalized)) {
return true;
}
if (normalized === "idempotency-key" || normalized.endsWith("-idempotency-key")) {
return false;
}
const segments = normalized.split(/[-_]+/u);
return segments.some((segment) => SENSITIVE_REDIRECT_HEADER_SEGMENTS.has(segment));
}
function isBlockedOutboundHostname(hostname: string): boolean {
const normalizedHostname = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
const normalizedHostname = hostname
.toLowerCase()
.replace(/^\[|\]$/g, "")
.replace(/\.$/, "");
if (!normalizedHostname) {
return true;
}
@@ -331,10 +429,12 @@ function isBlockedIpv6Address(hextets: number[]): boolean {
const isLoopback = hextets.slice(0, 7).every((part) => part === 0) && hextets[7] === 1;
const isUniqueLocal = (first & 0xfe00) === 0xfc00;
const isLinkLocal = (first & 0xffc0) === 0xfe80;
const isDeprecatedSiteLocal = (first & 0xffc0) === 0xfec0;
const isMulticast = (first & 0xff00) === 0xff00;
const isIpv4Mapped = hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 0xffff;
const isIpv4Compatible = hextets.slice(0, 6).every((part) => part === 0);
if (isUnspecified || isLoopback || isUniqueLocal || isLinkLocal) {
if (isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isDeprecatedSiteLocal || isMulticast) {
return true;
}
@@ -35,7 +35,11 @@ describe("withPermission", () => {
const handler = vi.fn((a: number, b: number) => a + b);
const guarded = withPermission(
"calc.run",
() => ({ permissions: ["calc.run"] }),
(a: number, b: number) => {
void a;
void b;
return { permissions: ["calc.run"] };
},
handler,
);
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import {
buildPortalStatusMailDeliveryMetadata,
buildPortalStatusMailOutboxEvent,
parsePortalStatusMailDeliveryMetadata,
parsePortalStatusMailOutboxEnvelope,
PORTAL_STATUS_MAIL_DEBOUNCE_MS,
PORTAL_STATUS_MAIL_EVENT_TYPE,
} from "./portal-status-mail.js";
const payload = {
tenantId: "tenant_1",
projectId: "project_1",
previousStageId: "stage_old",
expectedStageId: "stage_new",
stageChangeId: "change_1",
};
describe("portal status mail contract", () => {
it("builds a PII-free, five-minute delayed and idempotent outbox event", () => {
const now = new Date("2026-07-15T10:00:00.000Z");
const event = buildPortalStatusMailOutboxEvent(payload, { now });
expect(event).toEqual({
tenantId: "tenant_1",
type: PORTAL_STATUS_MAIL_EVENT_TYPE,
dispatchKey: "portal-status:change_1",
scheduledAt: new Date(now.getTime() + PORTAL_STATUS_MAIL_DEBOUNCE_MS),
payload: { version: 1, ...payload },
});
expect(JSON.stringify(event)).not.toMatch(/@|customer|recipient|email/iu);
});
it("validates the dispatcher envelope and rejects tenant/key drift or extra payload fields", () => {
const event = buildPortalStatusMailOutboxEvent(payload);
const envelope = {
outboxEventId: "outbox_1",
tenantId: event.tenantId,
eventType: event.type,
dispatchKey: event.dispatchKey,
payload: event.payload,
};
expect(parsePortalStatusMailOutboxEnvelope(envelope)).toEqual(envelope);
expect(() => parsePortalStatusMailOutboxEnvelope({ ...envelope, tenantId: "tenant_2" })).toThrow(/tenant scope/iu);
expect(() => parsePortalStatusMailOutboxEnvelope({ ...envelope, dispatchKey: "portal-status:change_2" })).toThrow(/dispatch key/iu);
expect(() => parsePortalStatusMailOutboxEnvelope({ ...envelope, payload: { ...event.payload, email: "secret@example.test" } })).toThrow(
/unsupported shape/iu
);
});
it("keeps permanent-failure metadata bound to an internal user id", () => {
const metadata = buildPortalStatusMailDeliveryMetadata({
stageChangeId: "change_1",
projectId: "project_1",
expectedStageId: "stage_new",
internalRecipientUserId: "tenant_user_1",
});
expect(parsePortalStatusMailDeliveryMetadata(metadata)).toEqual(metadata);
expect(parsePortalStatusMailDeliveryMetadata({ ...metadata, internalRecipientUserId: "contains spaces" })).toBeNull();
});
});
@@ -0,0 +1,155 @@
/**
* Shared, PII-free contract between the project stage mutation and the mail
* worker. The outbox row is delayed for five minutes; the worker then reloads
* all mutable portal state before it decides whether any mail is eligible.
*/
export const PORTAL_STATUS_MAIL_EVENT_TYPE = "mail.portal-status.stage-changed" as const;
export const PORTAL_STATUS_MAIL_OUTBOX_QUEUE = "outbox.portal-status-mail" as const;
export const PORTAL_STATUS_MAIL_DEBOUNCE_MS = 5 * 60 * 1_000;
export const PORTAL_STATUS_MAIL_PAYLOAD_VERSION = 1 as const;
const OPAQUE_ID_PATTERN = /^[A-Za-z0-9_-]{1,191}$/u;
export type PortalStatusMailPayload = {
readonly version: typeof PORTAL_STATUS_MAIL_PAYLOAD_VERSION;
readonly tenantId: string;
readonly projectId: string;
readonly previousStageId: string;
readonly expectedStageId: string;
readonly stageChangeId: string;
};
export type PortalStatusMailOutboxEvent = {
readonly tenantId: string;
readonly type: typeof PORTAL_STATUS_MAIL_EVENT_TYPE;
readonly payload: PortalStatusMailPayload;
readonly dispatchKey: string;
readonly scheduledAt: Date;
};
export type PortalStatusMailOutboxEnvelope = {
readonly outboxEventId: string;
readonly tenantId: string;
readonly eventType: typeof PORTAL_STATUS_MAIL_EVENT_TYPE;
readonly dispatchKey: string;
readonly payload: PortalStatusMailPayload;
};
export type PortalStatusMailDeliveryMetadata = {
readonly version: typeof PORTAL_STATUS_MAIL_PAYLOAD_VERSION;
readonly stageChangeId: string;
readonly projectId: string;
readonly expectedStageId: string;
readonly internalRecipientUserId: string | null;
};
export class PortalStatusMailContractError extends Error {
override readonly name = "PortalStatusMailContractError";
readonly code: "INVALID_EVENT_TYPE" | "INVALID_PAYLOAD" | "TENANT_MISMATCH" | "DISPATCH_KEY_MISMATCH";
constructor(message: string, code: PortalStatusMailContractError["code"]) {
super(message);
this.code = code;
}
}
export function buildPortalStatusMailOutboxEvent(
input: Omit<PortalStatusMailPayload, "version">,
options: { readonly now?: Date; readonly debounceMs?: number } = {}
): PortalStatusMailOutboxEvent {
const payload = normalizePayload({ version: PORTAL_STATUS_MAIL_PAYLOAD_VERSION, ...input });
const now = options.now ?? new Date();
const debounceMs = options.debounceMs ?? PORTAL_STATUS_MAIL_DEBOUNCE_MS;
if (!Number.isSafeInteger(debounceMs) || debounceMs < 0) {
throw new PortalStatusMailContractError("portal status mail debounce must be a non-negative integer", "INVALID_PAYLOAD");
}
return {
tenantId: payload.tenantId,
type: PORTAL_STATUS_MAIL_EVENT_TYPE,
payload,
dispatchKey: portalStatusMailDispatchKey(payload.stageChangeId),
scheduledAt: new Date(now.getTime() + debounceMs),
};
}
export function parsePortalStatusMailOutboxEnvelope(value: unknown): PortalStatusMailOutboxEnvelope {
if (!isRecord(value)) {
throw new PortalStatusMailContractError("portal status mail job is missing its envelope", "INVALID_PAYLOAD");
}
if (value.eventType !== PORTAL_STATUS_MAIL_EVENT_TYPE) {
throw new PortalStatusMailContractError("portal status mail job has an invalid eventType", "INVALID_EVENT_TYPE");
}
const outboxEventId = requireOpaqueId(value.outboxEventId, "outboxEventId");
const tenantId = requireOpaqueId(value.tenantId, "tenantId");
const payload = normalizePayload(value.payload);
if (payload.tenantId !== tenantId) {
throw new PortalStatusMailContractError("portal status mail tenant scope does not match its payload", "TENANT_MISMATCH");
}
const dispatchKey = typeof value.dispatchKey === "string" ? value.dispatchKey : "";
if (dispatchKey !== portalStatusMailDispatchKey(payload.stageChangeId)) {
throw new PortalStatusMailContractError("portal status mail dispatch key does not match its stage change", "DISPATCH_KEY_MISMATCH");
}
return { outboxEventId, tenantId, eventType: PORTAL_STATUS_MAIL_EVENT_TYPE, dispatchKey, payload };
}
export function buildPortalStatusMailDeliveryMetadata(input: Omit<PortalStatusMailDeliveryMetadata, "version">): PortalStatusMailDeliveryMetadata {
return {
version: PORTAL_STATUS_MAIL_PAYLOAD_VERSION,
stageChangeId: requireOpaqueId(input.stageChangeId, "stageChangeId"),
projectId: requireOpaqueId(input.projectId, "projectId"),
expectedStageId: requireOpaqueId(input.expectedStageId, "expectedStageId"),
internalRecipientUserId: input.internalRecipientUserId === null ? null : requireOpaqueId(input.internalRecipientUserId, "internalRecipientUserId"),
};
}
export function parsePortalStatusMailDeliveryMetadata(value: unknown): PortalStatusMailDeliveryMetadata | null {
if (!isRecord(value) || value.version !== PORTAL_STATUS_MAIL_PAYLOAD_VERSION) return null;
try {
return buildPortalStatusMailDeliveryMetadata({
stageChangeId: value.stageChangeId as string,
projectId: value.projectId as string,
expectedStageId: value.expectedStageId as string,
internalRecipientUserId: value.internalRecipientUserId === null ? null : (value.internalRecipientUserId as string),
});
} catch {
return null;
}
}
export function portalStatusMailDispatchKey(stageChangeId: string): string {
return `portal-status:${requireOpaqueId(stageChangeId, "stageChangeId")}`;
}
function normalizePayload(value: unknown): PortalStatusMailPayload {
if (!isRecord(value)) {
throw new PortalStatusMailContractError("portal status mail payload must be an object", "INVALID_PAYLOAD");
}
const allowedKeys = new Set(["version", "tenantId", "projectId", "previousStageId", "expectedStageId", "stageChangeId"]);
if (Object.keys(value).some((key) => !allowedKeys.has(key)) || value.version !== PORTAL_STATUS_MAIL_PAYLOAD_VERSION) {
throw new PortalStatusMailContractError("portal status mail payload has an unsupported shape", "INVALID_PAYLOAD");
}
return {
version: PORTAL_STATUS_MAIL_PAYLOAD_VERSION,
tenantId: requireOpaqueId(value.tenantId, "tenantId"),
projectId: requireOpaqueId(value.projectId, "projectId"),
previousStageId: requireOpaqueId(value.previousStageId, "previousStageId"),
expectedStageId: requireOpaqueId(value.expectedStageId, "expectedStageId"),
stageChangeId: requireOpaqueId(value.stageChangeId, "stageChangeId"),
};
}
function requireOpaqueId(value: unknown, field: string): string {
if (typeof value !== "string" || !OPAQUE_ID_PATTERN.test(value)) {
throw new PortalStatusMailContractError(`portal status mail ${field} is invalid`, "INVALID_PAYLOAD");
}
return value;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { neutralizeSpreadsheetFormula } from "./spreadsheet-safety.js";
describe("neutralizeSpreadsheetFormula", () => {
it.each(["=1+1", "+cmd", "-2+3", "@SUM(A1:A2)", " =1+1", "\tformula", "\rformula", "\nformula"])(
"neutralizes unsafe spreadsheet cell %j",
(value) => {
expect(neutralizeSpreadsheetFormula(value)).toBe(`'${value}`);
},
);
it.each(["", "plain text", " plain text", "1+1", "mailto:user@example.test"])("keeps safe cell %j unchanged", (value) => {
expect(neutralizeSpreadsheetFormula(value)).toBe(value);
});
});
@@ -0,0 +1,28 @@
const FORMULA_NEUTRALIZER = "'";
const FORMULA_PREFIXES = new Set(["=", "+", "-", "@"]);
const CONTROL_PREFIXES = new Set(["\t", "\r", "\n"]);
/**
* Keep untrusted spreadsheet cells literal when a CSV/XLSX file is opened.
* Spreadsheet programs may ignore leading whitespace before formula sigils,
* so the first meaningful character is inspected instead of only value[0].
*/
export function neutralizeSpreadsheetFormula(value: string): string {
return hasUnsafeSpreadsheetPrefix(value) ? `${FORMULA_NEUTRALIZER}${value}` : value;
}
function hasUnsafeSpreadsheetPrefix(value: string): boolean {
for (const char of value) {
if (FORMULA_PREFIXES.has(char) || CONTROL_PREFIXES.has(char)) {
return true;
}
if (char.trim() === "") {
continue;
}
return false;
}
return false;
}
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import { getTrustedProxyClientIp, trustedClientIpNetworkCount } from "./trusted-client-ip.js";
function lookup(headers: Record<string, string | undefined>) {
return (name: string) => headers[name];
}
describe("getTrustedProxyClientIp", () => {
it("accepts Cloudflare's client header only behind a published Cloudflare peer", () => {
expect(
getTrustedProxyClientIp(
lookup({
"x-forwarded-for": "198.51.100.250, 173.245.48.10",
"cf-connecting-ip": "203.0.113.7",
}),
),
).toBe("203.0.113.7");
expect(
getTrustedProxyClientIp(
lookup({
"x-forwarded-for": "2001:db8::250, 2400:cb00::10",
"cf-connecting-ip": "2001:db8::7",
}),
),
).toBe("2001:db8::7");
});
it("ignores spoofed client-IP headers on direct traffic", () => {
expect(
getTrustedProxyClientIp(
lookup({
"x-forwarded-for": "1.2.3.4, 198.51.100.9",
"cf-connecting-ip": "5.6.7.8",
"true-client-ip": "9.9.9.9",
}),
),
).toBe("198.51.100.9");
});
it("uses a validated socket or Traefik peer when no forwarding chain exists", () => {
expect(getTrustedProxyClientIp(lookup({ "cf-connecting-ip": "5.6.7.8" }), "::ffff:198.51.100.12")).toBe(
"198.51.100.12",
);
expect(getTrustedProxyClientIp(lookup({ "x-real-ip": "198.51.100.13" }))).toBe("198.51.100.13");
expect(getTrustedProxyClientIp(lookup({ "x-real-ip": "not-an-ip" }))).toBeNull();
});
it("keeps the reviewed Cloudflare IPv4 and IPv6 range set complete", () => {
expect(trustedClientIpNetworkCount).toBe(22);
});
});
@@ -0,0 +1,78 @@
import { BlockList, isIP } from "node:net";
type HeaderLookup = (name: string) => string | null | undefined;
// Source: https://www.cloudflare.com/ips-v4/ and
// https://www.cloudflare.com/ips-v6/ (reviewed 2026-07-22).
// Cloudflare documents that only these networks connect to customer origins.
const CLOUDFLARE_CIDRS = Object.freeze([
"173.245.48.0/20",
"103.21.244.0/22",
"103.22.200.0/22",
"103.31.4.0/22",
"141.101.64.0/18",
"108.162.192.0/18",
"190.93.240.0/20",
"188.114.96.0/20",
"197.234.240.0/22",
"198.41.128.0/17",
"162.158.0.0/15",
"104.16.0.0/13",
"104.24.0.0/14",
"172.64.0.0/13",
"131.0.72.0/22",
"2400:cb00::/32",
"2606:4700::/32",
"2803:f800::/32",
"2405:b500::/32",
"2405:8100::/32",
"2a06:98c0::/29",
"2c0f:f248::/32",
] as const);
const cloudflareNetworks = new BlockList();
for (const cidr of CLOUDFLARE_CIDRS) {
const separator = cidr.lastIndexOf("/");
const address = cidr.slice(0, separator);
const prefix = Number(cidr.slice(separator + 1));
cloudflareNetworks.addSubnet(address, prefix, isIP(address) === 4 ? "ipv4" : "ipv6");
}
function normalizeIp(value: string | null | undefined): string | null {
const normalized = value?.trim();
if (!normalized) return null;
const mappedIpv4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/iu.exec(normalized)?.[1];
if (mappedIpv4 && isIP(mappedIpv4) === 4) return mappedIpv4;
return isIP(normalized) === 0 ? null : normalized;
}
function rightmostForwardedPeer(lookup: HeaderLookup): string | null {
const forwardedFor = lookup("x-forwarded-for");
if (!forwardedFor) return null;
return normalizeIp(forwardedFor.split(",").at(-1));
}
function isCloudflareAddress(address: string): boolean {
const family = isIP(address);
return family !== 0 && cloudflareNetworks.check(address, family === 4 ? "ipv4" : "ipv6");
}
/**
* Resolve a security-sensitive client IP behind the HiveGrid edge.
*
* Traefik appends the immediate TCP peer to the right of X-Forwarded-For.
* Only when that non-client-controlled hop belongs to Cloudflare do we accept
* CF-Connecting-IP. Direct requests therefore cannot rotate a rate-limit or
* audit identity by forging Cloudflare, True-Client-IP, or the leftmost XFF.
*/
export function getTrustedProxyClientIp(lookup: HeaderLookup, immediatePeerIp?: string | null): string | null {
const proxyPeer =
rightmostForwardedPeer(lookup) ?? normalizeIp(immediatePeerIp) ?? normalizeIp(lookup("x-real-ip"));
if (!proxyPeer) return null;
if (!isCloudflareAddress(proxyPeer)) return proxyPeer;
return normalizeIp(lookup("cf-connecting-ip")) ?? proxyPeer;
}
export const trustedClientIpNetworkCount = CLOUDFLARE_CIDRS.length;