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

@@ -0,0 +1,209 @@
import { createHash } from "node:crypto";
import {
hashPortalSetupMailContent,
PORTAL_SETUP_TOKEN_PLACEHOLDER,
} from "@hivegrid/db/portal-setup-mail-contract.server";
import { describe, expect, it, vi } from "vitest";
import {
hasValidPortalSetupInvitationMailContract,
isEncryptedPortalSetupInvitationMailPayload,
isMaterializedPortalSetupInvitationMailPayload,
isRedactedPortalSetupInvitationMailPayload,
isTerminalPortalSetupInvitationMailPayload,
materializePortalSetupMailContent,
redactCompletedPortalSetupInvitationJob,
redactPortalSetupInvitationError,
redactPortalSetupInvitationMailPayload,
redactTerminalFailedPortalSetupInvitationJob,
} from "./portal-setup-invitation-secret.js";
const RAW_TOKEN = "p".repeat(43);
const RAW_TOKEN_HASH = createHash("sha256").update(RAW_TOKEN).digest("hex");
const ENCRYPTED_CAPABILITY = `portal-capability:v1:${"c".repeat(96)}`;
const OUTBOX_EVENT_ID = "outbox_portal_setup_1";
const DISPATCH_KEY = "portal-setup:portal_token_1";
function encryptedMailPayload() {
const subject = "Kundenportal einrichten";
const text = `Richten Sie Ihr Portal ein: https://portal.example.test/setup/${PORTAL_SETUP_TOKEN_PLACEHOLDER}`;
const html = `<a href="https://portal.example.test/setup/${PORTAL_SETUP_TOKEN_PLACEHOLDER}">Portal einrichten</a>`;
return {
kind: "mail.transactional",
tenantId: "tenant_1",
to: ["kunde@example.test"],
subject,
priorityOverride: "critical",
text,
html,
metadata: {
source: "portal_setup_invite",
invitationSource: "project_detail",
portalId: "portal_1",
portalUserId: "portal_user_1",
portalTokenId: "portal_token_1",
setupTokenHash: RAW_TOKEN_HASH,
expiresAt: "2099-01-01T00:00:00.000Z",
mailContentHash: hashPortalSetupMailContent({
recipient: "kunde@example.test",
subject,
text,
html,
}),
encryptedCapability: ENCRYPTED_CAPABILITY,
outboxEventId: OUTBOX_EVENT_ID,
dispatchKey: DISPATCH_KEY,
},
};
}
function materializedMailPayload() {
return materializePortalSetupMailContent(encryptedMailPayload(), RAW_TOKEN);
}
describe("portal setup invitation secret retention", () => {
it("recognizes only the exact encrypted, materialized, and redacted mail contracts", () => {
const encrypted = encryptedMailPayload();
const materialized = materializedMailPayload();
const redacted = redactPortalSetupInvitationMailPayload(materialized);
expect(isEncryptedPortalSetupInvitationMailPayload(encrypted)).toBe(true);
expect(isMaterializedPortalSetupInvitationMailPayload(encrypted)).toBe(false);
expect(isRedactedPortalSetupInvitationMailPayload(encrypted)).toBe(false);
expect(isEncryptedPortalSetupInvitationMailPayload(materialized)).toBe(false);
expect(isMaterializedPortalSetupInvitationMailPayload(materialized)).toBe(true);
expect(JSON.stringify(materialized)).toContain(RAW_TOKEN);
expect(JSON.stringify(materialized)).not.toContain(ENCRYPTED_CAPABILITY);
expect(isRedactedPortalSetupInvitationMailPayload(redacted)).toBe(true);
expect(hasValidPortalSetupInvitationMailContract(redacted)).toBe(true);
expect(redacted).toEqual({
kind: "mail.transactional",
tenantId: "tenant_1",
to: ["kunde@example.test"],
subject: "Kundenportal einrichten",
metadata: {
source: "portal_setup_invite",
invitationSource: "project_detail",
portalId: "portal_1",
portalUserId: "portal_user_1",
portalTokenId: "portal_token_1",
setupTokenHash: RAW_TOKEN_HASH,
expiresAt: "2099-01-01T00:00:00.000Z",
mailContentHash: encrypted.metadata.mailContentHash,
outboxEventId: OUTBOX_EVENT_ID,
dispatchKey: DISPATCH_KEY,
secretBodyRedacted: true,
},
});
expect(JSON.stringify(redacted)).not.toContain(RAW_TOKEN);
expect(JSON.stringify(redacted)).not.toContain(ENCRYPTED_CAPABILITY);
expect(hasValidPortalSetupInvitationMailContract({ ...encrypted, rawToken: RAW_TOKEN })).toBe(false);
expect(hasValidPortalSetupInvitationMailContract({ ...materialized, headers: { authorization: RAW_TOKEN } })).toBe(false);
expect(
hasValidPortalSetupInvitationMailContract({
...(redacted as Record<string, unknown>),
text: `https://portal.example.test/setup/${RAW_TOKEN}`,
}),
).toBe(false);
});
it("scrubs encrypted capability, raw token, rendered bodies, and decrypted envelope diagnostics", () => {
const encrypted = encryptedMailPayload();
const materialized = materializedMailPayload();
const renderedText = materialized.text as string;
const renderedHtml = materialized.html as string;
const decryptedEnvelope = `decrypted-capability-envelope:${RAW_TOKEN}:${"s".repeat(32)}`;
const providerError = Object.assign(
new Error(
`ciphertext=${ENCRYPTED_CAPABILITY} token=${RAW_TOKEN} text=${renderedText} html=${renderedHtml} envelope=${decryptedEnvelope}`,
),
{
name: RAW_TOKEN,
responseBody: { encryptedCapability: ENCRYPTED_CAPABILITY, rawToken: RAW_TOKEN },
},
);
const encryptedError = redactPortalSetupInvitationError(providerError, encrypted, [decryptedEnvelope, RAW_TOKEN]);
const materializedError = redactPortalSetupInvitationError(providerError, materialized, [
decryptedEnvelope,
ENCRYPTED_CAPABILITY,
]);
for (const redacted of [encryptedError, materializedError]) {
const serialized = JSON.stringify(redacted, Object.getOwnPropertyNames(redacted));
expect(redacted).not.toBe(providerError);
expect(redacted.name).toBe("Error");
expect(redacted.message.length).toBeLessThanOrEqual(1_000);
expect(serialized).not.toContain(ENCRYPTED_CAPABILITY);
expect(serialized).not.toContain(RAW_TOKEN);
expect(serialized).not.toContain(decryptedEnvelope);
expect(redacted).not.toHaveProperty("responseBody");
expect(redacted.message).toContain("[redacted");
}
});
it("redacts a completed BullMQ payload while retaining its safe outbox identity", async () => {
const data = {
outboxEventId: OUTBOX_EVENT_ID,
tenantId: "tenant_1",
eventType: "mail.transactional.send",
dispatchKey: DISPATCH_KEY,
payload: materializedMailPayload(),
};
const updateData = vi.fn(async (_data: unknown) => undefined);
await expect(redactCompletedPortalSetupInvitationJob({ data, updateData })).resolves.toBe(true);
const retained = updateData.mock.calls[0]?.[0] as Record<string, unknown>;
expect(retained).toMatchObject({
outboxEventId: OUTBOX_EVENT_ID,
tenantId: "tenant_1",
eventType: "mail.transactional.send",
dispatchKey: DISPATCH_KEY,
});
expect(isRedactedPortalSetupInvitationMailPayload(retained.payload)).toBe(true);
expect(JSON.stringify(retained)).not.toContain(RAW_TOKEN);
expect(JSON.stringify(retained)).not.toContain(ENCRYPTED_CAPABILITY);
});
it("stores only a terminal redacted payload for a terminally failed BullMQ job", async () => {
const data = {
outboxEventId: OUTBOX_EVENT_ID,
tenantId: "tenant_1",
eventType: "mail.transactional.send",
dispatchKey: DISPATCH_KEY,
payload: encryptedMailPayload(),
};
const updateData = vi.fn(async (_data: unknown) => undefined);
await expect(redactTerminalFailedPortalSetupInvitationJob({ data, updateData })).resolves.toBe(true);
const retained = updateData.mock.calls[0]?.[0] as Record<string, unknown>;
expect(isTerminalPortalSetupInvitationMailPayload(retained.payload)).toBe(true);
expect(isRedactedPortalSetupInvitationMailPayload(retained.payload)).toBe(true);
expect(JSON.stringify(retained)).not.toContain(RAW_TOKEN);
expect(JSON.stringify(retained)).not.toContain(ENCRYPTED_CAPABILITY);
});
it("fails loudly if a sensitive completed or terminal job cannot persist its scrubbed data", async () => {
await expect(redactCompletedPortalSetupInvitationJob({ data: materializedMailPayload() })).rejects.toThrow(/cannot redact/u);
await expect(redactTerminalFailedPortalSetupInvitationJob({ data: encryptedMailPayload() })).rejects.toThrow(/cannot redact/u);
});
it("leaves unrelated completed jobs untouched", async () => {
const data = {
...materializedMailPayload(),
metadata: { source: "ordinary-transactional-mail" },
};
const updateData = vi.fn(async (_data: unknown) => undefined);
await expect(redactCompletedPortalSetupInvitationJob({ data, updateData })).resolves.toBe(false);
expect(updateData).not.toHaveBeenCalled();
expect(JSON.stringify(data)).toContain(RAW_TOKEN);
});
});
@@ -0,0 +1,270 @@
import {
findPortalSetupRawToken,
hasValidEncryptedPortalSetupMailContent,
hasValidMaterializedPortalSetupMailContent,
hasValidRedactedPortalSetupMailContent,
isPortalSetupMailIntent,
materializePortalSetupMailContent,
PORTAL_SETUP_DELIVERY_STARTED,
PORTAL_SETUP_DELIVERY_STATUS_KEY,
PORTAL_SETUP_MAIL_SOURCE,
PORTAL_SETUP_PROVIDER_ACCEPTED,
PORTAL_SETUP_ROTATION_REQUIRED,
PORTAL_SETUP_SECRET_REDACTED_MARKER,
readPortalSetupMailMetadata,
} from "@hivegrid/db/portal-setup-mail-contract.server";
type CompletedJobDataWriter = {
readonly data?: unknown;
updateData?: (data: never) => Promise<void>;
};
export type PortalSetupInvitationOutboxBinding = {
tenantId: string;
outboxEventId: string;
dispatchKey: string;
};
export { isPortalSetupMailIntent, materializePortalSetupMailContent };
export function isPortalSetupInvitationMailPayload(payload: unknown): boolean {
return readPortalSetupMailMetadata(payload) !== null;
}
export function hasValidPortalSetupInvitationMailContract(payload: unknown): boolean {
return (
hasValidEncryptedPortalSetupMailContent(payload) ||
hasValidMaterializedPortalSetupMailContent(payload) ||
hasValidRedactedPortalSetupMailContent(payload)
);
}
export function isEncryptedPortalSetupInvitationMailPayload(payload: unknown): boolean {
return hasValidEncryptedPortalSetupMailContent(payload);
}
export function isMaterializedPortalSetupInvitationMailPayload(payload: unknown): boolean {
return hasValidMaterializedPortalSetupMailContent(payload);
}
export function isRedactedPortalSetupInvitationMailPayload(payload: unknown): boolean {
return hasValidRedactedPortalSetupMailContent(payload);
}
export function redactPortalSetupInvitationMailPayload(payload: unknown): unknown {
if (!isPortalSetupMailIntent(payload)) return payload;
if (isRedactedPortalSetupInvitationMailPayload(payload)) return payload;
const record = asRecord(payload);
const metadata = readPortalSetupMailMetadata(payload);
if (!record || !metadata) {
return { metadata: { source: PORTAL_SETUP_MAIL_SOURCE, [PORTAL_SETUP_SECRET_REDACTED_MARKER]: true } };
}
const rawMetadata = asRecord(record.metadata);
const deliveryStatus = rawMetadata?.[PORTAL_SETUP_DELIVERY_STATUS_KEY];
const safeMetadata: Record<string, unknown> = {
source: PORTAL_SETUP_MAIL_SOURCE,
invitationSource: metadata.invitationSource,
portalId: metadata.portalId,
portalUserId: metadata.portalUserId,
portalTokenId: metadata.portalTokenId,
setupTokenHash: metadata.setupTokenHash,
expiresAt: metadata.expiresAt,
mailContentHash: metadata.mailContentHash,
...(metadata.outboxEventId ? { outboxEventId: metadata.outboxEventId } : {}),
...(metadata.dispatchKey ? { dispatchKey: metadata.dispatchKey } : {}),
[PORTAL_SETUP_SECRET_REDACTED_MARKER]: true,
};
if (
deliveryStatus === PORTAL_SETUP_DELIVERY_STARTED ||
deliveryStatus === PORTAL_SETUP_PROVIDER_ACCEPTED ||
deliveryStatus === PORTAL_SETUP_ROTATION_REQUIRED
) {
safeMetadata[PORTAL_SETUP_DELIVERY_STATUS_KEY] = deliveryStatus;
}
return {
...(record.kind === "mail.transactional" ? { kind: record.kind } : {}),
...(typeof record.tenantId === "string" ? { tenantId: record.tenantId } : {}),
...(Array.isArray(record.to) ? { to: record.to.filter((entry): entry is string => typeof entry === "string") } : {}),
...(typeof record.subject === "string" ? { subject: record.subject } : {}),
metadata: safeMetadata,
};
}
export function markPortalSetupInvitationDeliveryStarted(payload: unknown): unknown {
return markDeliveryStatus(payload, PORTAL_SETUP_DELIVERY_STARTED);
}
export function markPortalSetupInvitationProviderAccepted(payload: unknown): unknown {
return markDeliveryStatus(payload, PORTAL_SETUP_PROVIDER_ACCEPTED);
}
export function redactTerminalPortalSetupInvitationMailPayload(payload: unknown): unknown {
const redacted = redactPortalSetupInvitationMailPayload(payload);
const record = asRecord(redacted);
const metadata = asRecord(record?.metadata);
if (!record || !metadata || metadata.source !== PORTAL_SETUP_MAIL_SOURCE) return redacted;
return {
...record,
metadata: { ...metadata, [PORTAL_SETUP_DELIVERY_STATUS_KEY]: PORTAL_SETUP_ROTATION_REQUIRED },
};
}
export function isPortalSetupInvitationDeliveryStarted(payload: unknown): boolean {
return hasDeliveryStatus(payload, PORTAL_SETUP_DELIVERY_STARTED);
}
export function isPortalSetupInvitationProviderAccepted(payload: unknown): boolean {
return hasDeliveryStatus(payload, PORTAL_SETUP_PROVIDER_ACCEPTED);
}
export function isTerminalPortalSetupInvitationMailPayload(payload: unknown): boolean {
return hasDeliveryStatus(payload, PORTAL_SETUP_ROTATION_REQUIRED);
}
export function bindTerminalPortalSetupInvitationMailPayload(
payload: unknown,
binding: PortalSetupInvitationOutboxBinding,
): unknown {
const redacted = redactTerminalPortalSetupInvitationMailPayload(payload);
const record = asRecord(redacted);
const metadata = readPortalSetupMailMetadata(redacted);
if (!record || !metadata || !isTerminalPortalSetupInvitationMailPayload(redacted)) {
throw new Error("Portal setup invitation recovery binding requires an exact mail contract.");
}
const tenantId = normalizeIdentifier(binding.tenantId, "tenantId");
const outboxEventId = normalizeIdentifier(binding.outboxEventId, "outboxEventId");
const dispatchKey = normalizeIdentifier(binding.dispatchKey, "dispatchKey", 256);
if (
record.tenantId !== tenantId ||
dispatchKey !== portalSetupDispatchKey(metadata.portalTokenId) ||
(metadata.outboxEventId !== undefined && metadata.outboxEventId !== outboxEventId) ||
(metadata.dispatchKey !== undefined && metadata.dispatchKey !== dispatchKey)
) {
throw new Error("Portal setup invitation recovery binding does not match its mail contract.");
}
return {
...record,
metadata: { ...(record.metadata as Record<string, unknown>), outboxEventId, dispatchKey },
};
}
export function readPortalSetupInvitationOutboxBinding(payload: unknown): PortalSetupInvitationOutboxBinding | null {
const record = asRecord(payload);
const metadata = readPortalSetupMailMetadata(payload);
if (!record || !metadata) return null;
try {
const tenantId = normalizeIdentifier(record.tenantId, "tenantId");
const outboxEventId = normalizeIdentifier(metadata.outboxEventId, "outboxEventId");
const dispatchKey = normalizeIdentifier(metadata.dispatchKey, "dispatchKey", 256);
if (dispatchKey !== portalSetupDispatchKey(metadata.portalTokenId)) return null;
return { tenantId, outboxEventId, dispatchKey };
} catch {
return null;
}
}
export function readPortalSetupInvitationRecoveryBinding(payload: unknown): PortalSetupInvitationOutboxBinding | null {
return isTerminalPortalSetupInvitationMailPayload(payload) ? readPortalSetupInvitationOutboxBinding(payload) : null;
}
export function redactPortalSetupInvitationJobData(data: unknown): unknown {
if (isPortalSetupInvitationMailPayload(data)) return redactPortalSetupInvitationMailPayload(data);
const record = asRecord(data);
if (!record || !isPortalSetupInvitationMailPayload(record.payload)) return data;
const payload = redactPortalSetupInvitationMailPayload(record.payload);
return payload === record.payload ? data : { ...record, payload };
}
export function redactTerminalPortalSetupInvitationJobData(data: unknown): unknown {
if (isPortalSetupInvitationMailPayload(data)) return redactTerminalPortalSetupInvitationMailPayload(data);
const record = asRecord(data);
if (!record || !isPortalSetupInvitationMailPayload(record.payload)) return data;
return { ...record, payload: redactTerminalPortalSetupInvitationMailPayload(record.payload) };
}
export function redactPortalSetupInvitationError(error: unknown, payload: unknown, sensitiveValues: readonly string[] = []): Error {
const source = error instanceof Error ? error : new Error(String(error));
if (!isPortalSetupMailIntent(payload)) return source;
const record = asRecord(payload);
const metadata = readPortalSetupMailMetadata(payload);
const rawMetadata = asRecord(record?.metadata);
const text = typeof record?.text === "string" ? record.text : "";
const html = typeof record?.html === "string" ? record.html : "";
const rawToken = metadata ? findPortalSetupRawToken(text, html, metadata.setupTokenHash) : null;
const encryptedCapability = typeof rawMetadata?.encryptedCapability === "string" ? rawMetadata.encryptedCapability : null;
const explicitRawToken = typeof record?.rawToken === "string" ? record.rawToken : null;
let message = (source.message || source.name).slice(0, 16_384);
for (const body of [text, html]) {
if (!body) continue;
message = message.replaceAll(body, "[redacted-portal-setup-mail-body]").replaceAll(JSON.stringify(body), '"[redacted-portal-setup-mail-body]"');
}
if (rawToken) message = message.replaceAll(rawToken, "[redacted-portal-setup-token]");
if (explicitRawToken) message = message.replaceAll(explicitRawToken, "[redacted-portal-setup-token]");
if (encryptedCapability) {
message = message
.replaceAll(encryptedCapability, "[redacted-portal-setup-ciphertext]")
.replaceAll(JSON.stringify(encryptedCapability), '"[redacted-portal-setup-ciphertext]"');
}
for (const sensitiveValue of sensitiveValues) {
if (typeof sensitiveValue !== "string" || sensitiveValue.length < 16) continue;
message = message
.replaceAll(sensitiveValue, "[redacted-portal-setup-secret]")
.replaceAll(JSON.stringify(sensitiveValue), '"[redacted-portal-setup-secret]"');
}
message = message
.replace(/("(?:encryptedCapability|rawToken)"\s*:\s*")[^"]+/giu, "$1[redacted]")
.replace(/(ciphertext\s*[=:]\s*)\S+/giu, "$1[redacted]")
.replace(/(\/setup\/)[A-Za-z0-9_-]{32,512}/gu, "$1[redacted]")
.replace(/([?&](?:access_token|api_key|client_secret|password|secret|token)=)[^&\s]+/giu, "$1[redacted]")
.replace(/(authorization\s*:\s*Bearer\s+)\S+/giu, "$1[redacted]")
.replace(/(body|html|token|secret|password)(\s*[=:]\s*)\S+/giu, "$1$2[redacted]")
.slice(0, 1_000);
const safe = new Error(message);
safe.name = "Error";
return safe;
}
export async function redactCompletedPortalSetupInvitationJob(job: CompletedJobDataWriter): Promise<boolean> {
const redacted = redactPortalSetupInvitationJobData(job.data);
if (redacted === job.data) return false;
if (!job.updateData) throw new Error("Completed portal setup invitation job cannot redact its retained payload.");
await job.updateData(redacted as never);
return true;
}
export async function redactTerminalFailedPortalSetupInvitationJob(job: CompletedJobDataWriter): Promise<boolean> {
const redacted = redactTerminalPortalSetupInvitationJobData(job.data);
if (redacted === job.data) return false;
if (!job.updateData) throw new Error("Terminal portal setup invitation job cannot redact its retained payload.");
await job.updateData(redacted as never);
return true;
}
function markDeliveryStatus(payload: unknown, status: string): unknown {
const redacted = redactPortalSetupInvitationMailPayload(payload);
const record = asRecord(redacted);
if (!record || !hasValidRedactedPortalSetupMailContent(redacted) || !asRecord(record.metadata)) {
throw new Error("Portal setup invitation delivery status requires an exact mail contract.");
}
return { ...record, metadata: { ...(record.metadata as Record<string, unknown>), [PORTAL_SETUP_DELIVERY_STATUS_KEY]: status } };
}
function hasDeliveryStatus(payload: unknown, status: string): boolean {
const record = asRecord(payload);
return hasValidRedactedPortalSetupMailContent(payload) && asRecord(record?.metadata)?.[PORTAL_SETUP_DELIVERY_STATUS_KEY] === status;
}
function portalSetupDispatchKey(portalTokenId: string): string {
return `portal-setup:${portalTokenId}`;
}
function normalizeIdentifier(value: unknown, field: string, maxLength = 191): string {
if (typeof value !== "string" || !value || value.trim() !== value || value.length > maxLength || value.includes("\u0000")) {
throw new Error(`Portal setup invitation recovery ${field} is invalid.`);
}
return value;
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
}
@@ -0,0 +1,566 @@
import { createHash } from "node:crypto";
import {
hashPortalSetupMailContent,
PORTAL_SETUP_TOKEN_PLACEHOLDER,
} from "@hivegrid/db/portal-setup-mail-contract.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { describe, expect, it, vi } from "vitest";
import {
bindTerminalPortalSetupInvitationMailPayload,
isPortalSetupInvitationDeliveryStarted,
isPortalSetupInvitationProviderAccepted,
isTerminalPortalSetupInvitationMailPayload,
markPortalSetupInvitationDeliveryStarted,
materializePortalSetupMailContent,
} from "./portal-setup-invitation-secret.js";
import {
acceptPortalSetupInvitationDelivery,
claimPortalSetupInvitationDelivery,
schedulePortalSetupInvitationTerminalRecovery,
terminalizePortalSetupInvitationDelivery,
} from "./portal-setup-invitation-terminalization.js";
const RAW_TOKEN = "p".repeat(43);
const RAW_TOKEN_HASH = createHash("sha256").update(RAW_TOKEN).digest("hex");
const OUTBOX_EVENT_ID = "outbox_portal_setup_1";
const DISPATCH_KEY = "portal-setup:portal_token_1";
const EXPIRES_AT = new Date("2099-01-01T00:00:00.000Z");
const LEASE_UNTIL = new Date("2026-07-18T12:05:00.000Z");
type PortalTokenRow = {
id: string;
tenantId: string;
portalUserId: string;
purpose: string;
tokenHash: string;
expiresAt: Date;
consumedAt: Date | null;
revokedAt: Date | null;
portalUser: {
portalId: string;
status: string;
archivedAt: Date | null;
};
};
type PortalTokenOverrides = Partial<Omit<PortalTokenRow, "portalUser">> & {
portalUser?: Partial<PortalTokenRow["portalUser"]>;
};
function encryptedMailPayload(expiresAt = EXPIRES_AT) {
const subject = "Kundenportal einrichten";
const text = `Richten Sie Ihr Portal ein: https://portal.example.test/setup/${PORTAL_SETUP_TOKEN_PLACEHOLDER}`;
const html = `<a href="https://portal.example.test/setup/${PORTAL_SETUP_TOKEN_PLACEHOLDER}">Portal einrichten</a>`;
return {
kind: "mail.transactional",
tenantId: "tenant_1",
to: ["kunde@example.test"],
subject,
priorityOverride: "critical",
text,
html,
metadata: {
source: "portal_setup_invite",
invitationSource: "project_detail",
portalId: "portal_1",
portalUserId: "portal_user_1",
portalTokenId: "portal_token_1",
setupTokenHash: RAW_TOKEN_HASH,
expiresAt: expiresAt.toISOString(),
mailContentHash: hashPortalSetupMailContent({
recipient: "kunde@example.test",
subject,
text,
html,
}),
encryptedCapability: `portal-capability:v1:${"c".repeat(96)}`,
outboxEventId: OUTBOX_EVENT_ID,
dispatchKey: DISPATCH_KEY,
},
};
}
function materializedMailPayload(expiresAt = EXPIRES_AT) {
return materializePortalSetupMailContent(encryptedMailPayload(expiresAt), RAW_TOKEN);
}
function terminalMailPayload() {
return bindTerminalPortalSetupInvitationMailPayload(materializedMailPayload(), {
tenantId: "tenant_1",
outboxEventId: OUTBOX_EVENT_ID,
dispatchKey: DISPATCH_KEY,
});
}
function portalToken(overrides: PortalTokenOverrides = {}): PortalTokenRow {
return {
id: "portal_token_1",
tenantId: "tenant_1",
portalUserId: "portal_user_1",
purpose: "setup",
tokenHash: RAW_TOKEN_HASH,
expiresAt: EXPIRES_AT,
consumedAt: null,
revokedAt: null,
...overrides,
portalUser: {
portalId: "portal_1",
status: "invited",
archivedAt: null,
...overrides.portalUser,
},
};
}
function payloadWithMetadata(payload: unknown, metadata: Record<string, unknown>): unknown {
const record = payload as Record<string, unknown>;
return {
...record,
metadata: {
...(record.metadata as Record<string, unknown>),
...metadata,
},
};
}
function harness(
options: {
token?: PortalTokenRow;
outboxPayload?: unknown;
outboxStatus?: string;
deliveryGeneration?: number;
lockedUntil?: Date | null;
portalTokenUpdateCount?: number;
outboxUpdateCount?: number;
} = {},
) {
const tokenRow = options.token ?? portalToken();
const outboxRow: {
payload: unknown;
status: string;
deliveryGeneration: number;
lockedUntil: Date | null;
} = {
payload: options.outboxPayload ?? materializedMailPayload(),
status: options.outboxStatus ?? "DONE",
deliveryGeneration: options.deliveryGeneration ?? 4,
lockedUntil: options.lockedUntil === undefined ? LEASE_UNTIL : options.lockedUntil,
};
const tx = {
$executeRaw: vi.fn(async () => 1),
portalToken: {
findFirst: vi.fn(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
return { ...tokenRow, portalUser: { ...tokenRow.portalUser } };
}),
updateMany: vi.fn(async ({ data }: { data: Partial<PortalTokenRow> }) => {
const count = options.portalTokenUpdateCount ?? 1;
if (count === 1) Object.assign(tokenRow, data);
return { count };
}),
},
outboxEvent: {
findFirst: vi.fn(async ({ where }: { where: Record<string, unknown> }) => {
if (
(where.deliveryGeneration !== undefined && where.deliveryGeneration !== outboxRow.deliveryGeneration) ||
(where.lockedUntil !== undefined && where.lockedUntil !== outboxRow.lockedUntil)
) {
return null;
}
return { ...outboxRow };
}),
updateMany: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
const count = options.outboxUpdateCount ?? 1;
if (count === 1) {
if (data.payload !== undefined) outboxRow.payload = data.payload;
if (typeof data.status === "string") outboxRow.status = data.status;
if ("lockedUntil" in data) outboxRow.lockedUntil = data.lockedUntil as Date | null;
}
return { count };
}),
},
};
const client = {
$transaction: vi.fn(async (callback: (transaction: typeof tx) => Promise<unknown>) => callback(tx)),
};
return { client, tokenRow, outboxRow, tx };
}
describe("portal setup invitation delivery claim", () => {
it("claims one live capability, persists a token-free started marker, and makes provider acceptance stable", async () => {
const payload = materializedMailPayload();
const { client, outboxRow, tx } = harness({ outboxPayload: payload });
await expect(
claimPortalSetupInvitationDelivery(
{ tenantId: "tenant_1", payload, now: new Date("2026-07-18T12:00:00.000Z") },
client as never,
),
).resolves.toMatchObject({ state: "claimed" });
expect(isPortalSetupInvitationDeliveryStarted(outboxRow.payload)).toBe(true);
expect(JSON.stringify(outboxRow.payload)).not.toContain(RAW_TOKEN);
expect(tx.outboxEvent.updateMany).toHaveBeenCalledWith({
where: {
id: OUTBOX_EVENT_ID,
tenantId: "tenant_1",
eventType: "mail.transactional.send",
dispatchKey: DISPATCH_KEY,
status: "DONE",
},
data: { payload: outboxRow.payload },
});
await expect(acceptPortalSetupInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).resolves.toSatisfy(
isPortalSetupInvitationProviderAccepted,
);
expect(isPortalSetupInvitationProviderAccepted(outboxRow.payload)).toBe(true);
await expect(claimPortalSetupInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).resolves.toMatchObject({
state: "provider_accepted",
});
});
it("treats a prior delivery-started marker as uncertain instead of allowing another provider attempt", async () => {
const payload = materializedMailPayload();
const started = markPortalSetupInvitationDeliveryStarted(payload);
const { client, tx } = harness({ outboxPayload: started });
await expect(claimPortalSetupInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).resolves.toEqual({
state: "uncertain",
payload: started,
});
expect(tx.portalToken.findFirst).not.toHaveBeenCalled();
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it.each([
["consumed", { consumedAt: new Date("2026-07-18T11:00:00.000Z") }],
["revoked", { revokedAt: new Date("2026-07-18T11:00:00.000Z") }],
["non-invited portal user", { portalUser: { status: "active" } }],
["archived portal user", { portalUser: { archivedAt: new Date("2026-07-18T11:00:00.000Z") } }],
] as const)("returns inactive for a %s setup capability", async (_label, overrides) => {
const payload = materializedMailPayload();
const { client, tx } = harness({ token: portalToken(overrides as PortalTokenOverrides), outboxPayload: payload });
await expect(
claimPortalSetupInvitationDelivery(
{ tenantId: "tenant_1", payload, now: new Date("2026-07-18T12:00:00.000Z") },
client as never,
),
).resolves.toEqual({ state: "inactive", payload });
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it("returns inactive for an expired setup capability whose persisted expiry still matches the mail identity", async () => {
const expiresAt = new Date("2026-07-18T11:59:59.999Z");
const payload = materializedMailPayload(expiresAt);
const { client, tx } = harness({ token: portalToken({ expiresAt }), outboxPayload: payload });
await expect(
claimPortalSetupInvitationDelivery(
{ tenantId: "tenant_1", payload, now: new Date("2026-07-18T12:00:00.000Z") },
client as never,
),
).resolves.toEqual({ state: "inactive", payload });
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it("requires the caller tenant to match the exact bound mail tenant before opening a transaction", async () => {
const payload = materializedMailPayload();
const { client } = harness({ outboxPayload: payload });
await expect(claimPortalSetupInvitationDelivery({ tenantId: "tenant_other", payload }, client as never)).rejects.toThrow(
/binding is invalid/u,
);
expect(client.$transaction).not.toHaveBeenCalled();
});
it.each([
["token hash", { tokenHash: "f".repeat(64) }],
["token purpose", { purpose: "magic_link" }],
["portal user", { portalUserId: "portal_user_other" }],
["portal", { portalUser: { portalId: "portal_other" } }],
["expiry", { expiresAt: new Date("2099-01-02T00:00:00.000Z") }],
])("fails closed on an exact persisted %s identity mismatch", async (_label, overrides) => {
const payload = materializedMailPayload();
const { client, tx } = harness({ token: portalToken(overrides as PortalTokenOverrides), outboxPayload: payload });
await expect(claimPortalSetupInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).rejects.toThrow(
/cannot prove its persisted capability/u,
);
expect(tx.portalToken.updateMany).not.toHaveBeenCalled();
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it.each([
["tenant", (payload: unknown) => ({ ...(payload as Record<string, unknown>), tenantId: "tenant_other" })],
["portal", (payload: unknown) => payloadWithMetadata(payload, { portalId: "portal_other" })],
["portal user", (payload: unknown) => payloadWithMetadata(payload, { portalUserId: "portal_user_other" })],
["token", (payload: unknown) => payloadWithMetadata(payload, { portalTokenId: "portal_token_other" })],
["mail content", (payload: unknown) => payloadWithMetadata(payload, { mailContentHash: "f".repeat(64) })],
])("rejects an outbox row with a different %s delivery identity", async (_label, mutate) => {
const payload = materializedMailPayload();
const { client, tx } = harness({ outboxPayload: mutate(payload) });
await expect(claimPortalSetupInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).rejects.toThrow(
/outbox row does not match/u,
);
expect(tx.portalToken.findFirst).not.toHaveBeenCalled();
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
});
describe("portal setup invitation terminalization and recovery", () => {
it("atomically revokes the exact setup token and fences the FAILED outbox transition by lease and generation", async () => {
const payload = materializedMailPayload();
const redactedPayload = terminalMailPayload();
const now = new Date("2026-07-18T12:00:00.000Z");
const { client, tokenRow, tx } = harness({
outboxPayload: payload,
outboxStatus: "PROCESSING",
deliveryGeneration: 4,
lockedUntil: LEASE_UNTIL,
});
await expect(
terminalizePortalSetupInvitationDelivery(
{
tenantId: "tenant_1",
payload,
lastError: "Portal setup provider delivery failed after its final retry.",
now,
outboxFailure: {
eventId: OUTBOX_EVENT_ID,
deliveryGeneration: 4,
lockedUntil: LEASE_UNTIL,
redactedPayload: redactedPayload as never,
retries: 7,
lastError: "Portal setup provider delivery failed after its final retry.",
processedAt: now,
},
},
client as never,
),
).resolves.toEqual({ portalTokenId: "portal_token_1", state: "invalidated" });
expect(tokenRow.revokedAt).toEqual(now);
expect(tx.portalToken.updateMany).toHaveBeenCalledWith({
where: {
id: "portal_token_1",
tenantId: "tenant_1",
portalUserId: "portal_user_1",
purpose: "setup",
tokenHash: RAW_TOKEN_HASH,
consumedAt: null,
revokedAt: null,
},
data: { revokedAt: now },
});
expect(tx.outboxEvent.findFirst).toHaveBeenCalledWith({
where: {
id: OUTBOX_EVENT_ID,
tenantId: "tenant_1",
eventType: "mail.transactional.send",
dispatchKey: DISPATCH_KEY,
status: "PROCESSING",
deliveryGeneration: 4,
lockedUntil: LEASE_UNTIL,
},
select: { payload: true },
});
expect(tx.outboxEvent.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
id: OUTBOX_EVENT_ID,
tenantId: "tenant_1",
dispatchKey: DISPATCH_KEY,
status: "PROCESSING",
deliveryGeneration: 4,
lockedUntil: LEASE_UNTIL,
}),
data: expect.objectContaining({
status: "FAILED",
payload: redactedPayload,
retries: 7,
processedAt: now,
lockedUntil: null,
}),
});
const terminalTransition = tx.outboxEvent.updateMany.mock.calls[0]?.[0] as
| { data: Record<string, unknown> }
| undefined;
expect(isTerminalPortalSetupInvitationMailPayload(terminalTransition?.data.payload)).toBe(true);
expect(JSON.stringify(tx.outboxEvent.updateMany.mock.calls)).not.toContain(RAW_TOKEN);
});
it.each([
["generation", 3, LEASE_UNTIL],
["lease", 4, new Date("2026-07-18T12:06:00.000Z")],
])("fails the transaction when the claimed outbox %s no longer matches", async (_label, deliveryGeneration, lockedUntil) => {
const payload = materializedMailPayload();
const redactedPayload = terminalMailPayload();
const { client, tx } = harness({
outboxPayload: payload,
outboxStatus: "PROCESSING",
deliveryGeneration: 4,
lockedUntil: LEASE_UNTIL,
});
await expect(
terminalizePortalSetupInvitationDelivery(
{
tenantId: "tenant_1",
payload,
outboxFailure: {
eventId: OUTBOX_EVENT_ID,
deliveryGeneration,
lockedUntil,
redactedPayload: redactedPayload as never,
retries: 7,
lastError: "provider unavailable",
processedAt: new Date("2026-07-18T12:00:00.000Z"),
},
},
client as never,
),
).rejects.toThrow(/outbox row does not match/u);
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it("reports a lost terminal outbox transition instead of accepting a stale lease race", async () => {
const payload = materializedMailPayload();
const { client, tx } = harness({
outboxPayload: payload,
outboxStatus: "PROCESSING",
outboxUpdateCount: 0,
});
await expect(
terminalizePortalSetupInvitationDelivery(
{
tenantId: "tenant_1",
payload,
outboxFailure: {
eventId: OUTBOX_EVENT_ID,
deliveryGeneration: 4,
lockedUntil: LEASE_UNTIL,
redactedPayload: terminalMailPayload() as never,
retries: 7,
lastError: "provider unavailable",
processedAt: new Date("2026-07-18T12:00:00.000Z"),
},
},
client as never,
),
).rejects.toThrow(/terminal outbox transition lost its race/u);
expect(tx.outboxEvent.updateMany).toHaveBeenCalledTimes(1);
});
it("retries revocation from the durable terminal marker without retaining the raw capability", async () => {
const redactedPayload = terminalMailPayload();
const { client, tokenRow, tx } = harness({ outboxPayload: redactedPayload, outboxStatus: "FAILED" });
await expect(
terminalizePortalSetupInvitationDelivery(
{ tenantId: "tenant_1", payload: redactedPayload, now: new Date("2026-07-18T12:30:00.000Z") },
client as never,
),
).resolves.toEqual({ portalTokenId: "portal_token_1", state: "invalidated" });
expect(tokenRow.revokedAt).toEqual(new Date("2026-07-18T12:30:00.000Z"));
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
expect(JSON.stringify(redactedPayload)).not.toContain(RAW_TOKEN);
});
it("rearms the originating outbox row with the same terminal redacted identity", async () => {
const redactedPayload = terminalMailPayload();
const now = new Date("2026-07-18T12:45:00.000Z");
const { client, tx } = harness({ outboxPayload: redactedPayload, outboxStatus: "FAILED" });
await expect(
schedulePortalSetupInvitationTerminalRecovery(
{
tenantId: "tenant_1",
outboxEventId: OUTBOX_EVENT_ID,
redactedPayload,
lastError: "Portal setup capability revocation requires retry.",
now,
},
client as never,
),
).resolves.toBeUndefined();
expect(tx.outboxEvent.updateMany).toHaveBeenCalledWith({
where: {
id: OUTBOX_EVENT_ID,
tenantId: "tenant_1",
eventType: "mail.transactional.send",
dispatchKey: DISPATCH_KEY,
status: { in: ["DONE", "FAILED", "PENDING"] },
},
data: {
status: "PENDING",
payload: redactedPayload,
lastError: "Portal setup capability revocation requires retry.",
scheduledAt: now,
processedAt: null,
lockedUntil: null,
},
});
expect(JSON.stringify(tx.outboxEvent.updateMany.mock.calls)).not.toContain(RAW_TOKEN);
});
it("rejects recovery when tenant, embedded event, or selected outbox identity differs", async () => {
const redactedPayload = terminalMailPayload() as Record<string, unknown>;
const wrongEvent = payloadWithMetadata(redactedPayload, { outboxEventId: "outbox_other" });
const wrongOutboxIdentity = payloadWithMetadata(redactedPayload, { portalUserId: "portal_user_other" });
const correctHarness = harness({ outboxPayload: redactedPayload, outboxStatus: "FAILED" });
const mismatchHarness = harness({ outboxPayload: wrongOutboxIdentity, outboxStatus: "FAILED" });
await expect(
schedulePortalSetupInvitationTerminalRecovery(
{
tenantId: "tenant_other",
outboxEventId: OUTBOX_EVENT_ID,
redactedPayload,
lastError: "database retry",
},
correctHarness.client as never,
),
).rejects.toThrow(/contract is invalid/u);
await expect(
schedulePortalSetupInvitationTerminalRecovery(
{
tenantId: "tenant_1",
outboxEventId: OUTBOX_EVENT_ID,
redactedPayload: wrongEvent,
lastError: "database retry",
},
correctHarness.client as never,
),
).rejects.toThrow(/contract is invalid/u);
await expect(
schedulePortalSetupInvitationTerminalRecovery(
{
tenantId: "tenant_1",
outboxEventId: OUTBOX_EVENT_ID,
redactedPayload,
lastError: "database retry",
},
mismatchHarness.client as never,
),
).rejects.toThrow(/outbox row does not match/u);
expect(correctHarness.tx.outboxEvent.updateMany).not.toHaveBeenCalled();
expect(mismatchHarness.tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,456 @@
import { getDbClient, type DbClient } from "@hivegrid/db/client.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import {
findPortalSetupRawToken,
portalSetupMailHashesEqual,
readPortalSetupMailMetadata,
} from "@hivegrid/db/portal-setup-mail-contract.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import {
bindTerminalPortalSetupInvitationMailPayload,
hasValidPortalSetupInvitationMailContract,
isMaterializedPortalSetupInvitationMailPayload,
isPortalSetupInvitationDeliveryStarted,
isPortalSetupInvitationProviderAccepted,
isTerminalPortalSetupInvitationMailPayload,
markPortalSetupInvitationDeliveryStarted,
markPortalSetupInvitationProviderAccepted,
readPortalSetupInvitationOutboxBinding,
readPortalSetupInvitationRecoveryBinding,
type PortalSetupInvitationOutboxBinding,
} from "./portal-setup-invitation-secret.js";
export type PortalSetupInvitationOutboxTerminalFailure = {
eventId: string;
deliveryGeneration: number;
lockedUntil: Date | null;
redactedPayload: Prisma.InputJsonValue;
retries: number;
lastError: string;
processedAt: Date;
};
export type PortalSetupInvitationDeliveryClaimResult =
| { state: "claimed"; payload: unknown }
| { state: "provider_accepted"; payload: unknown }
| { state: "uncertain"; payload: unknown }
| { state: "inactive"; payload: unknown }
| { state: "not_ready" };
export type PortalSetupInvitationTerminalizationResult = {
portalTokenId: string;
state: "invalidated" | "already_inactive";
};
export type PortalSetupInvitationTerminalizationInput = {
tenantId: string;
payload: unknown;
lastError?: string;
now?: Date;
outboxFailure?: PortalSetupInvitationOutboxTerminalFailure;
};
export async function claimPortalSetupInvitationDelivery(
input: { tenantId: string; payload: unknown; now?: Date },
client: Pick<DbClient, "$transaction"> = getDbClient(),
): Promise<PortalSetupInvitationDeliveryClaimResult> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
if (!isMaterializedPortalSetupInvitationMailPayload(input.payload)) {
throw new Error("Portal setup invitation delivery requires a materialized exact mail contract.");
}
const binding = requireDeliveryBinding(input.payload, tenantId);
const metadata = readPortalSetupMailMetadata(input.payload)!;
const payload = asRecord(input.payload)!;
const rawToken = findPortalSetupRawToken(payload.text as string, payload.html as string, metadata.setupTokenHash);
if (!rawToken) throw new Error("Portal setup invitation delivery cannot prove its capability.");
const claimedPayload = markPortalSetupInvitationDeliveryStarted(input.payload);
const now = input.now ?? new Date();
return bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${deliveryLockKey(tenantId, binding.outboxEventId)}, 0))`;
const outbox = await tx.outboxEvent.findFirst({
where: { id: binding.outboxEventId, tenantId, eventType: "mail.transactional.send", dispatchKey: binding.dispatchKey },
select: { payload: true, status: true },
});
if (!outbox) throw new Error("Portal setup invitation delivery outbox row is missing.");
assertExactOutboxIdentity(outbox.payload, input.payload, binding);
if (outbox.status === "PROCESSING") return { state: "not_ready" };
if (outbox.status !== "DONE") throw new Error("Portal setup invitation delivery outbox row is not dispatch-complete.");
if (isPortalSetupInvitationProviderAccepted(outbox.payload)) return { state: "provider_accepted", payload: outbox.payload };
if (isPortalSetupInvitationDeliveryStarted(outbox.payload) || isTerminalPortalSetupInvitationMailPayload(outbox.payload)) {
return { state: "uncertain", payload: outbox.payload };
}
const token = await tx.portalToken.findFirst({
where: { id: metadata.portalTokenId, tenantId },
select: {
id: true,
tenantId: true,
portalUserId: true,
purpose: true,
tokenHash: true,
expiresAt: true,
consumedAt: true,
revokedAt: true,
portalUser: { select: { portalId: true, status: true, archivedAt: true } },
},
});
assertExactTokenIdentity(token, metadata, tenantId);
if (!isLiveSetupCapability(token, now)) {
return { state: "inactive", payload: input.payload };
}
const transition = await tx.outboxEvent.updateMany({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
data: { payload: claimedPayload as Prisma.InputJsonValue },
});
if (transition.count !== 1) throw new Error("Portal setup invitation delivery claim lost its race.");
return { state: "claimed", payload: claimedPayload };
}),
);
}
export async function acceptPortalSetupInvitationDelivery(
input: { tenantId: string; payload: unknown },
client: Pick<DbClient, "$transaction"> = getDbClient(),
): Promise<unknown> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const binding = requireDeliveryBinding(input.payload, tenantId);
const acceptedPayload = markPortalSetupInvitationProviderAccepted(input.payload);
return bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${deliveryLockKey(tenantId, binding.outboxEventId)}, 0))`;
const outbox = await tx.outboxEvent.findFirst({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
select: { payload: true },
});
assertExactOutboxIdentity(outbox?.payload, input.payload, binding);
if (isPortalSetupInvitationProviderAccepted(outbox?.payload)) return outbox!.payload;
if (!isPortalSetupInvitationDeliveryStarted(outbox?.payload)) {
throw new Error("Portal setup invitation provider acknowledgement has no active delivery claim.");
}
const transition = await tx.outboxEvent.updateMany({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
data: { payload: acceptedPayload as Prisma.InputJsonValue },
});
if (transition.count !== 1) throw new Error("Portal setup invitation provider acknowledgement lost its race.");
return acceptedPayload;
}),
);
}
export async function terminalizePortalSetupInvitationDelivery(
input: PortalSetupInvitationTerminalizationInput,
client: Pick<DbClient, "$transaction"> = getDbClient(),
): Promise<PortalSetupInvitationTerminalizationResult> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
if (!hasValidPortalSetupInvitationMailContract(input.payload)) {
throw new Error("Portal setup invitation terminalization requires an exact mail contract.");
}
const metadata = readPortalSetupMailMetadata(input.payload);
const payload = asRecord(input.payload);
if (!metadata || !payload || payload.tenantId !== tenantId) {
throw new Error("Portal setup invitation terminalization tenant contract mismatch.");
}
const binding = input.outboxFailure
? readPortalSetupInvitationRecoveryBinding(input.outboxFailure.redactedPayload)
: readPortalSetupInvitationOutboxBinding(input.payload);
if (!binding || binding.tenantId !== tenantId) {
throw new Error("Portal setup invitation terminalization outbox binding is missing.");
}
const safeError = normalizeSafeError(input.lastError ?? "Portal setup invitation delivery requires capability rotation.");
const terminalPayload = bindTerminalPortalSetupInvitationMailPayload(input.payload, binding);
const now = input.now ?? new Date();
return bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${deliveryLockKey(tenantId, binding.outboxEventId)}, 0))`;
const token = await tx.portalToken.findFirst({
where: { id: metadata.portalTokenId, tenantId },
select: {
id: true,
tenantId: true,
portalUserId: true,
purpose: true,
tokenHash: true,
expiresAt: true,
consumedAt: true,
revokedAt: true,
portalUser: { select: { portalId: true, status: true, archivedAt: true } },
},
});
assertExactTokenIdentity(token, metadata, tenantId);
let state: PortalSetupInvitationTerminalizationResult["state"] = "already_inactive";
if (token.consumedAt === null && token.revokedAt === null) {
const revoked = await tx.portalToken.updateMany({
where: {
id: metadata.portalTokenId,
tenantId,
portalUserId: metadata.portalUserId,
purpose: "setup",
tokenHash: metadata.setupTokenHash,
consumedAt: null,
revokedAt: null,
},
data: { revokedAt: now },
});
if (revoked.count !== 1) throw new Error("Portal setup invitation terminalization lost its capability race.");
state = "invalidated";
}
if (input.outboxFailure) {
const failure = input.outboxFailure;
assertOutboxFailure(failure, binding);
const outbox = await tx.outboxEvent.findFirst({
where: {
id: failure.eventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "PROCESSING",
deliveryGeneration: failure.deliveryGeneration,
lockedUntil: failure.lockedUntil,
},
select: { payload: true },
});
assertExactOutboxIdentity(outbox?.payload, input.payload, binding);
const transition = await tx.outboxEvent.updateMany({
where: {
id: failure.eventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "PROCESSING",
deliveryGeneration: failure.deliveryGeneration,
lockedUntil: failure.lockedUntil,
},
data: {
status: "FAILED",
payload: terminalPayload as Prisma.InputJsonValue,
retries: failure.retries,
lastError: safeError,
processedAt: failure.processedAt,
lockedUntil: null,
},
});
if (transition.count !== 1) throw new Error("Portal setup invitation terminal outbox transition lost its race.");
} else {
const outbox = await tx.outboxEvent.findFirst({
where: { id: binding.outboxEventId, tenantId, eventType: "mail.transactional.send", dispatchKey: binding.dispatchKey },
select: { payload: true, status: true },
});
assertExactOutboxIdentity(outbox?.payload, input.payload, binding);
if (outbox?.status !== "FAILED") {
const transition = await tx.outboxEvent.updateMany({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: { in: ["DONE", "PENDING", "PROCESSING"] },
},
data: {
status: "FAILED",
payload: terminalPayload as Prisma.InputJsonValue,
lastError: safeError,
processedAt: now,
lockedUntil: null,
},
});
if (transition.count !== 1) throw new Error("Portal setup invitation terminalization lost its outbox race.");
}
}
return { portalTokenId: metadata.portalTokenId, state };
}),
);
}
export async function schedulePortalSetupInvitationTerminalRecovery(
input: { tenantId: string; outboxEventId: string; redactedPayload: unknown; lastError: string; now?: Date },
client: Pick<DbClient, "$transaction"> = getDbClient(),
): Promise<void> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const outboxEventId = normalizeIdentifier(input.outboxEventId, "outboxEventId");
const binding = readPortalSetupInvitationRecoveryBinding(input.redactedPayload);
if (!binding || binding.tenantId !== tenantId || binding.outboxEventId !== outboxEventId) {
throw new Error("Portal setup invitation recovery schedule contract is invalid.");
}
const safeError = normalizeSafeError(input.lastError);
const now = input.now ?? new Date();
await bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${deliveryLockKey(tenantId, outboxEventId)}, 0))`;
const outbox = await tx.outboxEvent.findFirst({
where: {
id: outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: { in: ["DONE", "FAILED", "PENDING"] },
},
select: { payload: true },
});
assertExactOutboxIdentity(outbox?.payload, input.redactedPayload, binding);
const transition = await tx.outboxEvent.updateMany({
where: {
id: outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: { in: ["DONE", "FAILED", "PENDING"] },
},
data: {
status: "PENDING",
payload: input.redactedPayload as Prisma.InputJsonValue,
lastError: safeError,
scheduledAt: now,
processedAt: null,
lockedUntil: null,
},
});
if (transition.count !== 1) throw new Error("Portal setup invitation recovery schedule lost its outbox race.");
}),
);
}
function requireDeliveryBinding(payload: unknown, tenantId: string): PortalSetupInvitationOutboxBinding {
const binding = readPortalSetupInvitationOutboxBinding(payload);
if (!binding || binding.tenantId !== tenantId) throw new Error("Portal setup invitation delivery binding is invalid.");
return binding;
}
function assertExactOutboxIdentity(
actualPayload: unknown,
expectedPayload: unknown,
binding: PortalSetupInvitationOutboxBinding,
): void {
const actual = readPortalSetupMailMetadata(actualPayload);
const expected = readPortalSetupMailMetadata(expectedPayload);
const actualRecord = asRecord(actualPayload);
const expectedRecord = asRecord(expectedPayload);
if (
!actual ||
!expected ||
!actualRecord ||
!expectedRecord ||
actualRecord.tenantId !== expectedRecord.tenantId ||
actual.portalId !== expected.portalId ||
actual.portalUserId !== expected.portalUserId ||
actual.portalTokenId !== expected.portalTokenId ||
actual.invitationSource !== expected.invitationSource ||
actual.expiresAt !== expected.expiresAt ||
!portalSetupMailHashesEqual(actual.setupTokenHash, expected.setupTokenHash) ||
!portalSetupMailHashesEqual(actual.mailContentHash, expected.mailContentHash) ||
(actual.outboxEventId !== undefined && actual.outboxEventId !== binding.outboxEventId) ||
(actual.dispatchKey !== undefined && actual.dispatchKey !== binding.dispatchKey)
) {
throw new Error("Portal setup invitation outbox row does not match its delivery identity.");
}
}
type PortalTokenIdentity = {
id: string;
tenantId: string;
portalUserId: string;
purpose: string;
tokenHash: string;
expiresAt: Date;
consumedAt: Date | null;
revokedAt: Date | null;
portalUser: { portalId: string; status: string; archivedAt: Date | null };
};
function assertExactTokenIdentity(
token: PortalTokenIdentity | null,
metadata: NonNullable<ReturnType<typeof readPortalSetupMailMetadata>>,
tenantId: string,
): asserts token is PortalTokenIdentity {
if (
!token ||
token.id !== metadata.portalTokenId ||
token.tenantId !== tenantId ||
token.portalUserId !== metadata.portalUserId ||
token.purpose !== "setup" ||
!portalSetupMailHashesEqual(token.tokenHash, metadata.setupTokenHash) ||
token.expiresAt.toISOString() !== metadata.expiresAt ||
token.portalUser.portalId !== metadata.portalId
) {
throw new Error("Portal setup invitation cannot prove its persisted capability.");
}
}
function isLiveSetupCapability(token: PortalTokenIdentity, now: Date): boolean {
return (
token.consumedAt === null &&
token.revokedAt === null &&
token.expiresAt.getTime() > now.getTime() &&
token.portalUser.status === "invited" &&
token.portalUser.archivedAt === null
);
}
function assertOutboxFailure(failure: PortalSetupInvitationOutboxTerminalFailure, binding: PortalSetupInvitationOutboxBinding): void {
if (
failure.eventId !== binding.outboxEventId ||
!Number.isSafeInteger(failure.deliveryGeneration) ||
failure.deliveryGeneration < 0 ||
(failure.lockedUntil !== null && !(failure.lockedUntil instanceof Date)) ||
!Number.isSafeInteger(failure.retries) ||
failure.retries < 1 ||
!(failure.processedAt instanceof Date)
) {
throw new Error("Portal setup invitation terminal outbox contract is invalid.");
}
}
function normalizeSafeError(value: string): string {
const normalized = value.trim();
if (!normalized || normalized.length > 1_000 || /<[a-z][^>]*>/iu.test(normalized) || /\/setup\/[A-Za-z0-9_-]{32,512}/u.test(normalized)) {
throw new Error("Portal setup invitation terminal error is unsafe.");
}
return normalized;
}
function deliveryLockKey(tenantId: string, outboxEventId: string): string {
return `tenant-portal-setup-delivery:${tenantId}:${outboxEventId}`;
}
function bindTenantContext<T>(tenantId: string, callback: () => T): T {
const current = getRlsExecutionContext();
if (current?.tenantId && current.tenantId !== tenantId) {
throw new Error("Portal setup invitation terminalization cannot switch tenant context.");
}
return current?.tenantId === tenantId ? callback() : runWithRlsContext({ tenantId }, callback);
}
function normalizeIdentifier(value: string, field: string): string {
const normalized = value.trim();
if (!normalized || normalized !== value || normalized.length > 191 || normalized.includes("\u0000")) {
throw new Error(`Portal setup invitation ${field} is invalid.`);
}
return normalized;
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
}
@@ -0,0 +1,170 @@
import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import { hashWorkspaceOwnerInvitationMailContent } from "@hivegrid/db/workspace-owner-invite-mail-contract.server";
import {
isRedactedWorkspaceOwnerInvitationMailPayload,
redactCompletedWorkspaceOwnerInvitationJob,
redactWorkspaceOwnerInvitationMailPayload,
redactWorkspaceOwnerInvitationError,
} from "./workspace-owner-invitation-secret.js";
const RAW_TOKEN = "m".repeat(43);
const RAW_TOKEN_HASH = createHash("sha256").update(RAW_TOKEN).digest("hex");
function ownerMailPayload() {
const subject = "Workspace invitation";
const html = `<a href="https://app.example.test/invitation/${RAW_TOKEN}">Accept</a>`;
return {
kind: "mail.transactional",
tenantId: "tenant_1",
to: ["owner@example.test"],
subject,
html,
metadata: {
source: "workspace-owner-invitation",
invitationId: "invite_1",
invitationTokenHash: RAW_TOKEN_HASH,
issuanceKeyHash: "b".repeat(64),
mailContentHash: hashWorkspaceOwnerInvitationMailContent({
recipient: "owner@example.test",
subject,
html,
rawToken: RAW_TOKEN,
invitationTokenHash: RAW_TOKEN_HASH,
}),
},
};
}
describe("workspace-owner invitation completed-job redaction", () => {
it("redacts a retained final transactional-mail job without removing its safe idempotency metadata", async () => {
const data = {
...ownerMailPayload(),
headers: { "x-debug-capability": RAW_TOKEN },
metadata: { ...ownerMailPayload().metadata, debugToken: RAW_TOKEN },
};
const updateData = vi.fn(async (_data: unknown) => undefined);
await expect(redactCompletedWorkspaceOwnerInvitationJob({ data, updateData })).resolves.toBe(true);
const redacted = updateData.mock.calls[0]?.[0] as Record<string, unknown>;
expect(JSON.stringify(redacted)).not.toContain(RAW_TOKEN);
expect(isRedactedWorkspaceOwnerInvitationMailPayload(redacted)).toBe(true);
expect(redacted.metadata).toMatchObject({
source: "workspace-owner-invitation",
invitationId: "invite_1",
invitationTokenHash: RAW_TOKEN_HASH,
issuanceKeyHash: "b".repeat(64),
secretBodyRedacted: true,
});
expect(redacted).not.toHaveProperty("headers");
expect(redacted.metadata).not.toHaveProperty("debugToken");
});
it("redacts the nested payload of a retained outbox.mail job and keeps the envelope id", async () => {
const data = {
outboxEventId: "outbox_1",
tenantId: "tenant_1",
eventType: "mail.transactional.send",
dispatchKey: "mail:workspace-owner-invite:invite_1",
payload: ownerMailPayload(),
};
const updateData = vi.fn(async (_data: unknown) => undefined);
await expect(redactCompletedWorkspaceOwnerInvitationJob({ data, updateData })).resolves.toBe(true);
const redacted = updateData.mock.calls[0]?.[0] as Record<string, unknown>;
expect(redacted.outboxEventId).toBe("outbox_1");
expect(JSON.stringify(redacted)).not.toContain(RAW_TOKEN);
expect(isRedactedWorkspaceOwnerInvitationMailPayload(redacted.payload)).toBe(true);
});
it("does not touch normal completed mail jobs", async () => {
const data = {
...ownerMailPayload(),
metadata: { source: "outbox-mail" },
};
const updateData = vi.fn(async (_data: unknown) => undefined);
await expect(redactCompletedWorkspaceOwnerInvitationJob({ data, updateData })).resolves.toBe(false);
expect(updateData).not.toHaveBeenCalled();
expect(JSON.stringify(data)).toContain(RAW_TOKEN);
});
it("does not trust a source label without the exact invitation proof metadata", async () => {
const data = {
...ownerMailPayload(),
metadata: { source: "workspace-owner-invitation", secretBodyRedacted: true },
};
const updateData = vi.fn(async (_data: unknown) => undefined);
await expect(redactCompletedWorkspaceOwnerInvitationJob({ data, updateData })).resolves.toBe(false);
expect(updateData).not.toHaveBeenCalled();
expect(JSON.stringify(data)).toContain(RAW_TOKEN);
});
it("fails loudly when a completed sensitive job cannot persist redacted data", async () => {
await expect(redactCompletedWorkspaceOwnerInvitationJob({ data: ownerMailPayload() })).rejects.toThrow(/cannot redact/u);
});
it("removes an echoed OWNER HTML body and bare capability from provider diagnostics", () => {
const token = "z".repeat(43);
const html = `<a href="https://app.example.test/invitation/${token}">Accept</a>`;
const payload = {
...ownerMailPayload(),
html,
metadata: {
...(ownerMailPayload().metadata as Record<string, unknown>),
invitationTokenHash: createHash("sha256").update(token).digest("hex"),
},
};
const providerError = Object.assign(new Error(`provider rejected html=${html} retry token=${token}`), {
name: `Provider${token}`,
responseBody: { html, token },
});
const redacted = redactWorkspaceOwnerInvitationError(providerError, payload);
expect(redacted).not.toBe(providerError);
expect(JSON.stringify(redacted, Object.getOwnPropertyNames(redacted))).not.toContain(token);
expect(redacted.message).not.toContain(html);
expect(redacted.message).toContain("[redacted");
expect(redacted.name).toBe("Error");
expect(redacted).not.toHaveProperty("responseBody");
});
it("bounds provider-controlled diagnostics before running global redaction", () => {
const payload = ownerMailPayload();
const hugeError = new Error(`provider ${"x".repeat(100_000)} ${RAW_TOKEN}`);
const redacted = redactWorkspaceOwnerInvitationError(hugeError, payload);
expect(redacted.message.length).toBeLessThanOrEqual(1_000);
expect(redacted.message).not.toContain(RAW_TOKEN);
});
it("redacts source-marked OWNER intent even when its proof hashes are corrupted", () => {
const payload = {
...ownerMailPayload(),
metadata: {
source: "workspace-owner-invitation",
invitationId: "invite_corrupt",
invitationTokenHash: "broken",
issuanceKeyHash: "broken",
},
};
const error = Object.assign(new Error(`provider echoed ${RAW_TOKEN}`), { name: RAW_TOKEN });
const redactedError = redactWorkspaceOwnerInvitationError(error, payload);
const redactedPayload = redactWorkspaceOwnerInvitationMailPayload(payload);
expect(redactedError.name).toBe("Error");
expect(redactedError.message).not.toContain(RAW_TOKEN);
expect(JSON.stringify(redactedPayload)).not.toContain(RAW_TOKEN);
expect(redactedPayload).not.toHaveProperty("html");
});
});
@@ -0,0 +1,335 @@
import {
findWorkspaceOwnerInvitationRawToken,
hasValidRedactedWorkspaceOwnerInvitationMailContent,
hasValidWorkspaceOwnerInvitationMailContent,
isWorkspaceOwnerInvitationMailIntent,
WORKSPACE_OWNER_INVITATION_DELIVERY_STARTED,
WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY,
WORKSPACE_OWNER_INVITATION_MAIL_SOURCE,
WORKSPACE_OWNER_INVITATION_PROVIDER_ACCEPTED,
WORKSPACE_OWNER_INVITATION_ROTATION_REQUIRED,
WORKSPACE_OWNER_INVITATION_SECRET_REDACTED_MARKER,
} from "@hivegrid/db/workspace-owner-invite-mail-contract.server";
type CompletedJobDataWriter = {
readonly data?: unknown;
updateData?: (data: never) => Promise<void>;
};
export type WorkspaceOwnerInvitationRecoveryBinding = {
tenantId: string;
outboxEventId: string;
dispatchKey: string;
};
export { isWorkspaceOwnerInvitationMailIntent };
/**
* Returns a copy of a workspace-owner invitation mail payload without fields
* that can carry the raw capability token. Other transactional mail payloads
* are returned unchanged.
*/
export function redactWorkspaceOwnerInvitationMailPayload(payload: unknown): unknown {
if (!isWorkspaceOwnerInvitationMailIntent(payload)) return payload;
if (isRedactedWorkspaceOwnerInvitationMailPayload(payload)) return payload;
const record = payload as Record<string, unknown>;
const metadata = record.metadata as Record<string, unknown>;
const capabilityValues = findPotentialCapabilityValues(record.html);
const safeMetadata: Record<string, unknown> = { source: WORKSPACE_OWNER_INVITATION_MAIL_SOURCE };
for (const key of ["invitationId", "invitationTokenHash", "issuanceKeyHash", "outboxEventId", "dispatchKey"] as const) {
if (typeof metadata[key] === "string") safeMetadata[key] = scrubPotentialCapabilities(metadata[key], capabilityValues);
}
safeMetadata[WORKSPACE_OWNER_INVITATION_SECRET_REDACTED_MARKER] = true;
if (isSha256(metadata.mailContentHash)) safeMetadata.mailContentHash = metadata.mailContentHash;
if (metadata.alias === "user-invitation") safeMetadata.alias = metadata.alias;
const deliveryStatus = metadata[WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY];
if (
deliveryStatus === WORKSPACE_OWNER_INVITATION_DELIVERY_STARTED ||
deliveryStatus === WORKSPACE_OWNER_INVITATION_PROVIDER_ACCEPTED ||
deliveryStatus === WORKSPACE_OWNER_INVITATION_ROTATION_REQUIRED
) {
safeMetadata[WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY] = deliveryStatus;
}
return {
...(record.kind === "mail.transactional" ? { kind: record.kind } : {}),
...(typeof record.tenantId === "string" ? { tenantId: scrubPotentialCapabilities(record.tenantId, capabilityValues) } : {}),
...(Array.isArray(record.to)
? { to: record.to.filter((entry): entry is string => typeof entry === "string").map((entry) => scrubPotentialCapabilities(entry, capabilityValues)) }
: {}),
...(typeof record.subject === "string" ? { subject: scrubPotentialCapabilities(record.subject, capabilityValues) } : {}),
...(record.priorityOverride === "critical" ? { priorityOverride: record.priorityOverride } : {}),
metadata: safeMetadata,
};
}
/** Records the at-most-once claim before the provider can observe the mail. */
export function markWorkspaceOwnerInvitationDeliveryStarted(payload: unknown): unknown {
return markWorkspaceOwnerInvitationDeliveryStatus(payload, WORKSPACE_OWNER_INVITATION_DELIVERY_STARTED);
}
/** Records that the provider accepted the one claimed delivery attempt. */
export function markWorkspaceOwnerInvitationProviderAccepted(payload: unknown): unknown {
return markWorkspaceOwnerInvitationDeliveryStatus(payload, WORKSPACE_OWNER_INVITATION_PROVIDER_ACCEPTED);
}
export function isWorkspaceOwnerInvitationDeliveryStarted(payload: unknown): boolean {
return hasWorkspaceOwnerInvitationDeliveryStatus(payload, WORKSPACE_OWNER_INVITATION_DELIVERY_STARTED);
}
export function isWorkspaceOwnerInvitationProviderAccepted(payload: unknown): boolean {
return hasWorkspaceOwnerInvitationDeliveryStatus(payload, WORKSPACE_OWNER_INVITATION_PROVIDER_ACCEPTED);
}
/** Redacts a terminal failure and records that only a fresh capability may be queued. */
export function redactTerminalWorkspaceOwnerInvitationMailPayload(payload: unknown): unknown {
const redacted = redactWorkspaceOwnerInvitationMailPayload(payload);
if (!isWorkspaceOwnerInvitationMailIntent(redacted) || !isRecord(redacted) || !isRecord(redacted.metadata)) return redacted;
const record = redacted as Record<string, unknown>;
const metadata = record.metadata as Record<string, unknown>;
if (metadata[WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY] === WORKSPACE_OWNER_INVITATION_ROTATION_REQUIRED) return redacted;
return {
...record,
metadata: {
...metadata,
[WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY]: WORKSPACE_OWNER_INVITATION_ROTATION_REQUIRED,
},
};
}
/**
* Adds the non-secret identity required to recover a terminal OWNER delivery.
* The deterministic dispatch key prevents an outbox id from being paired with
* a different invitation inside the same tenant.
*/
export function bindTerminalWorkspaceOwnerInvitationMailPayload(
payload: unknown,
binding: WorkspaceOwnerInvitationRecoveryBinding
): unknown {
const redacted = redactTerminalWorkspaceOwnerInvitationMailPayload(payload);
if (!isTerminalWorkspaceOwnerInvitationMailPayload(redacted) || !isRecord(redacted) || !isRecord(redacted.metadata)) {
throw new Error("Workspace-owner invitation recovery binding requires an exact terminal mail contract.");
}
const tenantId = normalizeRecoveryIdentifier(binding.tenantId, "tenantId", 191);
const outboxEventId = normalizeRecoveryIdentifier(binding.outboxEventId, "outboxEventId", 191);
const metadata = redacted.metadata;
const invitationId = normalizeRecoveryIdentifier(metadata.invitationId, "invitationId", 191);
const expectedDispatchKey = workspaceOwnerInvitationDispatchKey(invitationId);
const dispatchKey = normalizeRecoveryIdentifier(binding.dispatchKey, "dispatchKey", 256);
if (
redacted.tenantId !== tenantId ||
dispatchKey !== expectedDispatchKey ||
(metadata.outboxEventId !== undefined && metadata.outboxEventId !== outboxEventId) ||
(metadata.dispatchKey !== undefined && metadata.dispatchKey !== dispatchKey)
) {
throw new Error("Workspace-owner invitation recovery binding does not match its mail contract.");
}
return {
...redacted,
metadata: {
...metadata,
outboxEventId,
dispatchKey,
},
};
}
/** Reads only a fully-bound, token-free terminal recovery marker. */
export function readWorkspaceOwnerInvitationRecoveryBinding(payload: unknown): WorkspaceOwnerInvitationRecoveryBinding | null {
if (!isTerminalWorkspaceOwnerInvitationMailPayload(payload)) return null;
return readWorkspaceOwnerInvitationOutboxBinding(payload);
}
/** Reads the exact non-secret outbox identity used by the delivery claim. */
export function readWorkspaceOwnerInvitationOutboxBinding(payload: unknown): WorkspaceOwnerInvitationRecoveryBinding | null {
if (!isWorkspaceOwnerInvitationMailPayload(payload) || !isRecord(payload) || !isRecord(payload.metadata)) return null;
const metadata = payload.metadata;
try {
const tenantId = normalizeRecoveryIdentifier(payload.tenantId, "tenantId", 191);
const outboxEventId = normalizeRecoveryIdentifier(metadata.outboxEventId, "outboxEventId", 191);
const invitationId = normalizeRecoveryIdentifier(metadata.invitationId, "invitationId", 191);
const dispatchKey = normalizeRecoveryIdentifier(metadata.dispatchKey, "dispatchKey", 256);
if (dispatchKey !== workspaceOwnerInvitationDispatchKey(invitationId)) return null;
return { tenantId, outboxEventId, dispatchKey };
} catch {
return null;
}
}
/**
* Redacts either a direct `mail.transactional` payload or the nested payload
* stored in an `outbox.mail` envelope. The surrounding job id and safe
* metadata remain intact so completed-job deduplication keeps working.
*/
export function redactWorkspaceOwnerInvitationJobData(data: unknown): unknown {
if (isWorkspaceOwnerInvitationMailPayload(data)) {
return redactWorkspaceOwnerInvitationMailPayload(data);
}
if (!isRecord(data) || !isWorkspaceOwnerInvitationMailPayload(data.payload)) {
return data;
}
const redactedPayload = redactWorkspaceOwnerInvitationMailPayload(data.payload);
if (redactedPayload === data.payload) return data;
return {
...data,
payload: redactedPayload,
};
}
export function redactTerminalWorkspaceOwnerInvitationJobData(data: unknown): unknown {
if (isWorkspaceOwnerInvitationMailPayload(data)) {
return redactTerminalWorkspaceOwnerInvitationMailPayload(data);
}
if (!isRecord(data) || !isWorkspaceOwnerInvitationMailPayload(data.payload)) {
return data;
}
const redactedPayload = redactTerminalWorkspaceOwnerInvitationMailPayload(data.payload);
if (redactedPayload === data.payload) return data;
return { ...data, payload: redactedPayload };
}
export function isWorkspaceOwnerInvitationMailPayload(payload: unknown): boolean {
if (!isWorkspaceOwnerInvitationMailIntent(payload) || !isRecord(payload) || !isRecord(payload.metadata)) return false;
const metadata = payload.metadata;
return (
metadata.source === WORKSPACE_OWNER_INVITATION_MAIL_SOURCE &&
typeof metadata.invitationId === "string" &&
metadata.invitationId.trim().length > 0 &&
isSha256(metadata.invitationTokenHash) &&
isSha256(metadata.issuanceKeyHash)
);
}
export function isRedactedWorkspaceOwnerInvitationMailPayload(payload: unknown): boolean {
if (!isWorkspaceOwnerInvitationMailPayload(payload)) return false;
const record = payload as Record<string, unknown>;
const metadata = record.metadata as Record<string, unknown>;
return (
hasValidRedactedWorkspaceOwnerInvitationMailContent(payload) &&
metadata[WORKSPACE_OWNER_INVITATION_SECRET_REDACTED_MARKER] === true &&
!("html" in record) &&
!("text" in record) &&
!("templateData" in record) &&
!("attachments" in record)
);
}
export function isTerminalWorkspaceOwnerInvitationMailPayload(payload: unknown): boolean {
if (!isRedactedWorkspaceOwnerInvitationMailPayload(payload)) return false;
const metadata = (payload as Record<string, unknown>).metadata as Record<string, unknown>;
return metadata[WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY] === WORKSPACE_OWNER_INVITATION_ROTATION_REQUIRED;
}
export function hasValidWorkspaceOwnerInvitationMailContract(payload: unknown): boolean {
if (isRedactedWorkspaceOwnerInvitationMailPayload(payload)) {
return hasValidRedactedWorkspaceOwnerInvitationMailContent(payload);
}
return isWorkspaceOwnerInvitationMailPayload(payload) && hasValidWorkspaceOwnerInvitationMailContent(payload);
}
/** Drops provider-specific fields and scrubs the exact capability/body from diagnostics. */
export function redactWorkspaceOwnerInvitationError(error: unknown, payload: unknown): Error {
const source = error instanceof Error ? error : new Error(String(error));
if (!isWorkspaceOwnerInvitationMailIntent(payload)) return source;
const record = payload as Record<string, unknown>;
const metadata = record.metadata as Record<string, unknown>;
const html = typeof record.html === "string" ? record.html : null;
const tokenHash = typeof metadata.invitationTokenHash === "string" ? metadata.invitationTokenHash : "";
const rawToken = html ? findWorkspaceOwnerInvitationRawToken(html, tokenHash) : null;
// Bound provider-controlled diagnostics before any global regex work.
let message = (source.message || source.name).slice(0, 16_384);
if (html) {
const serializedHtml = JSON.stringify(html);
message = message
.replaceAll(html, "[redacted-owner-invitation-mail-body]")
.replaceAll(serializedHtml, '"[redacted-owner-invitation-mail-body]"')
.replaceAll(serializedHtml.slice(1, -1), "[redacted-owner-invitation-mail-body]");
for (const capability of findPotentialCapabilityValues(html)) {
message = message.replaceAll(capability, "[redacted-owner-invitation-token]");
}
}
if (rawToken) message = message.replaceAll(rawToken, "[redacted-owner-invitation-token]");
message = message
.replace(/<(?:a|html|body)\b[^>]*>[\s\S]*?<\/(?:a|html|body)>/giu, "[redacted-owner-invitation-mail-body]")
.replace(/(\/invitation\/)[A-Za-z0-9_-]{32,512}/gu, "$1[redacted]")
.replace(/([?&](?:access_token|api_key|client_secret|password|secret|token)=)[^&\s]+/giu, "$1[redacted]")
.replace(/(authorization\s*:\s*Bearer\s+)\S+/giu, "$1[redacted]")
.replace(/(body|html|token|secret|password)(\s*[=:]\s*)\S+/giu, "$1$2[redacted]")
.slice(0, 1_000);
const redacted = new Error(message);
redacted.name = "Error";
return redacted;
}
/**
* Replaces secret-bearing data only after BullMQ has declared a job
* completed. Failed and retryable jobs keep their body so delivery can retry.
*/
export async function redactCompletedWorkspaceOwnerInvitationJob(job: CompletedJobDataWriter): Promise<boolean> {
const redacted = redactWorkspaceOwnerInvitationJobData(job.data);
if (redacted === job.data) return false;
if (!job.updateData) {
throw new Error("Completed workspace-owner invitation job cannot redact its retained payload.");
}
await job.updateData(redacted as never);
return true;
}
export async function redactTerminalFailedWorkspaceOwnerInvitationJob(job: CompletedJobDataWriter): Promise<boolean> {
const redacted = redactTerminalWorkspaceOwnerInvitationJobData(job.data);
if (redacted === job.data) return false;
if (!job.updateData) {
throw new Error("Terminal workspace-owner invitation job cannot redact its retained payload.");
}
await job.updateData(redacted as never);
return true;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function isSha256(value: unknown): value is string {
return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
}
function findPotentialCapabilityValues(html: unknown): string[] {
return typeof html === "string" ? [...new Set(html.match(/[A-Za-z0-9_-]{32,512}/gu) ?? [])] : [];
}
function scrubPotentialCapabilities(value: string, capabilities: readonly string[]): string {
return capabilities.reduce((safe, capability) => safe.replaceAll(capability, "[redacted]"), value);
}
function markWorkspaceOwnerInvitationDeliveryStatus(payload: unknown, status: string): unknown {
const redacted = redactWorkspaceOwnerInvitationMailPayload(payload);
if (!isRedactedWorkspaceOwnerInvitationMailPayload(redacted) || !isRecord(redacted) || !isRecord(redacted.metadata)) {
throw new Error("Workspace-owner invitation delivery status requires an exact mail contract.");
}
return {
...redacted,
metadata: {
...redacted.metadata,
[WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY]: status,
},
};
}
function hasWorkspaceOwnerInvitationDeliveryStatus(payload: unknown, status: string): boolean {
if (!isRedactedWorkspaceOwnerInvitationMailPayload(payload) || !isRecord(payload) || !isRecord(payload.metadata)) return false;
return payload.metadata[WORKSPACE_OWNER_INVITATION_DELIVERY_STATUS_KEY] === status;
}
function workspaceOwnerInvitationDispatchKey(invitationId: string): string {
return `mail:workspace-owner-invite:${invitationId}`;
}
function normalizeRecoveryIdentifier(value: unknown, field: string, maxLength: number): string {
if (typeof value !== "string" || !value || value.trim() !== value || value.length > maxLength || value.includes("\u0000")) {
throw new Error(`Workspace-owner invitation recovery ${field} is invalid.`);
}
return value;
}
@@ -0,0 +1,369 @@
import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import type { TenantUserInvitation } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { hashWorkspaceOwnerInvitationMailContent } from "@hivegrid/db/workspace-owner-invite-mail-contract.server";
import {
bindTerminalWorkspaceOwnerInvitationMailPayload,
isTerminalWorkspaceOwnerInvitationMailPayload,
isWorkspaceOwnerInvitationDeliveryStarted,
isWorkspaceOwnerInvitationProviderAccepted,
markWorkspaceOwnerInvitationDeliveryStarted,
} from "./workspace-owner-invitation-secret.js";
import {
abandonWorkspaceOwnerInvitationDelivery,
acceptWorkspaceOwnerInvitationDelivery,
claimWorkspaceOwnerInvitationDelivery,
scheduleWorkspaceOwnerInvitationTerminalRecovery,
terminalizeWorkspaceOwnerInvitationDelivery,
} from "./workspace-owner-invitation-terminalization.js";
const TOKEN = "t".repeat(43);
const TOKEN_HASH = createHash("sha256").update(TOKEN).digest("hex");
function mailPayload(bound = false) {
const subject = "Workspace invitation";
const html = `<a href="https://app.example.test/invitation/${TOKEN}">Accept</a>`;
return {
tenantId: "tenant_1",
to: ["owner@example.test"],
subject,
html,
metadata: {
source: "workspace-owner-invitation",
invitationId: "invite_1",
invitationTokenHash: TOKEN_HASH,
issuanceKeyHash: "b".repeat(64),
...(bound
? {
outboxEventId: "outbox_1",
dispatchKey: "mail:workspace-owner-invite:invite_1",
}
: {}),
mailContentHash: hashWorkspaceOwnerInvitationMailContent({
recipient: "owner@example.test",
subject,
html,
rawToken: TOKEN,
invitationTokenHash: TOKEN_HASH,
}),
},
};
}
function invitation(overrides: Partial<TenantUserInvitation> = {}): TenantUserInvitation {
return {
id: "invite_1",
tenantId: "tenant_1",
email: "owner@example.test",
firstName: "Mara",
lastName: "König",
type: 0,
pending: true,
status: "pending",
tokenHash: TOKEN_HASH,
tokenPrefix: TOKEN.slice(0, 12),
expiresAt: new Date("2099-01-01T00:00:00.000Z"),
acceptedAt: null,
revokedAt: null,
createdUserId: null,
fromUserId: "operator_1",
acceptedByUserId: null,
revokedByUserId: null,
...overrides,
};
}
function boundTerminalPayload(overrides: { tenantId?: string; outboxEventId?: string; dispatchKey?: string } = {}) {
return bindTerminalWorkspaceOwnerInvitationMailPayload(mailPayload(), {
tenantId: overrides.tenantId ?? "tenant_1",
outboxEventId: overrides.outboxEventId ?? "outbox_1",
dispatchKey: overrides.dispatchKey ?? "mail:workspace-owner-invite:invite_1",
});
}
function harness(initial = invitation(), outboxPayload: unknown = mailPayload(), outboxStatus = "PROCESSING") {
const row = { ...initial };
const outboxRow = { payload: outboxPayload, status: outboxStatus };
const tx = {
$executeRaw: vi.fn(async () => 1),
tenantUserInvitation: {
findFirst: vi.fn(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
return { ...row };
}),
updateMany: vi.fn(async ({ data }: { data: Partial<TenantUserInvitation> }) => {
if (row.status !== "pending" || !row.pending) return { count: 0 };
Object.assign(row, data);
return { count: 1 };
}),
},
outboxEvent: {
findFirst: vi.fn(async () => ({ ...outboxRow })),
updateMany: vi.fn(async ({ data }: { data: { payload?: unknown; status?: string } }) => {
if (data.payload !== undefined) outboxRow.payload = data.payload;
if (data.status !== undefined) outboxRow.status = data.status;
return { count: 1 };
}),
},
};
const client = {
$transaction: vi.fn(async (callback: (transaction: typeof tx) => Promise<unknown>) => callback(tx)),
};
return { client, row, outboxRow, tx };
}
describe("workspace-owner invitation terminalization", () => {
it("claims one provider attempt and makes its accepted receipt stable across a BullMQ retry", async () => {
const payload = mailPayload(true);
const { client, outboxRow } = harness(invitation(), payload, "DONE");
await expect(claimWorkspaceOwnerInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).resolves.toMatchObject({ state: "claimed" });
expect(isWorkspaceOwnerInvitationDeliveryStarted(outboxRow.payload)).toBe(true);
expect(JSON.stringify(outboxRow.payload)).not.toContain(TOKEN);
await expect(acceptWorkspaceOwnerInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).resolves.toSatisfy(
isWorkspaceOwnerInvitationProviderAccepted
);
expect(isWorkspaceOwnerInvitationProviderAccepted(outboxRow.payload)).toBe(true);
await expect(claimWorkspaceOwnerInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).resolves.toMatchObject({
state: "provider_accepted",
});
});
it("treats a prior started claim as ambiguous and rotates instead of permitting a second send", async () => {
const payload = mailPayload(true);
const started = markWorkspaceOwnerInvitationDeliveryStarted(payload);
const { client, row, outboxRow } = harness(invitation(), started, "DONE");
await expect(claimWorkspaceOwnerInvitationDelivery({ tenantId: "tenant_1", payload }, client as never)).resolves.toMatchObject({ state: "uncertain" });
await expect(
abandonWorkspaceOwnerInvitationDelivery(
{
tenantId: "tenant_1",
payload,
lastError: "Workspace-owner invitation delivery outcome was ambiguous; capability rotation is required.",
now: new Date("2026-07-15T13:00:00.000Z"),
},
client as never
)
).resolves.toEqual({ invitationId: "invite_1", state: "invalidated" });
expect(row).toMatchObject({ pending: false, status: "delivery_failed" });
expect(outboxRow.status).toBe("FAILED");
expect(isTerminalWorkspaceOwnerInvitationMailPayload(outboxRow.payload)).toBe(true);
expect(JSON.stringify(outboxRow.payload)).not.toContain(TOKEN);
});
it("atomically invalidates a pending capability and stores only the redacted FAILED outbox", async () => {
const { client, row, tx } = harness();
const payload = mailPayload();
const redacted = boundTerminalPayload();
await expect(
terminalizeWorkspaceOwnerInvitationDelivery(
{
tenantId: "tenant_1",
payload,
now: new Date("2026-07-15T12:00:00.000Z"),
outboxFailure: {
eventId: "outbox_1",
deliveryGeneration: 0,
lockedUntil: new Date("2026-07-15T12:05:00.000Z"),
redactedPayload: redacted as never,
retries: 7,
lastError: "provider unavailable",
processedAt: new Date("2026-07-15T12:00:00.000Z"),
},
},
client as never
)
).resolves.toEqual({ invitationId: "invite_1", state: "invalidated" });
expect(row).toMatchObject({ pending: false, status: "delivery_failed", revokedByUserId: null });
expect(row.revokedAt).toEqual(new Date("2026-07-15T12:00:00.000Z"));
expect(tx.outboxEvent.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
id: "outbox_1",
tenantId: "tenant_1",
status: "PROCESSING",
deliveryGeneration: 0,
lockedUntil: new Date("2026-07-15T12:05:00.000Z"),
}),
data: expect.objectContaining({ status: "FAILED", payload: redacted, retries: 7 }),
});
expect(JSON.stringify(tx.outboxEvent.updateMany.mock.calls)).not.toContain(TOKEN);
});
it("is idempotent for the same already-invalidated capability", async () => {
const { client, tx } = harness(
invitation({
pending: false,
status: "delivery_failed",
revokedAt: new Date("2026-07-15T12:00:00.000Z"),
})
);
await expect(terminalizeWorkspaceOwnerInvitationDelivery({ tenantId: "tenant_1", payload: mailPayload() }, client as never)).resolves.toEqual({
invitationId: "invite_1",
state: "already_inactive",
});
expect(tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
});
it("retries invalidation from the durable redacted outbox marker without needing the raw capability", async () => {
const { client, row, tx } = harness();
const redacted = boundTerminalPayload();
await expect(
terminalizeWorkspaceOwnerInvitationDelivery(
{
tenantId: "tenant_1",
payload: redacted,
outboxFailure: {
eventId: "outbox_1",
deliveryGeneration: 0,
lockedUntil: new Date("2026-07-15T12:35:00.000Z"),
redactedPayload: redacted as never,
retries: 8,
lastError: "database transition temporarily unavailable",
processedAt: new Date("2026-07-15T12:30:00.000Z"),
},
},
client as never
)
).resolves.toEqual({ invitationId: "invite_1", state: "invalidated" });
expect(row).toMatchObject({ pending: false, status: "delivery_failed", revokedByUserId: null });
expect(tx.outboxEvent.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
id: "outbox_1",
status: "PROCESSING",
deliveryGeneration: 0,
lockedUntil: new Date("2026-07-15T12:35:00.000Z"),
}),
data: expect.objectContaining({ status: "FAILED", payload: redacted, retries: 8 }),
});
});
it("rearms the originating DONE outbox row with only the redacted rotation marker", async () => {
const { client, tx } = harness();
const redacted = boundTerminalPayload();
await expect(
scheduleWorkspaceOwnerInvitationTerminalRecovery(
{
tenantId: "tenant_1",
outboxEventId: "outbox_1",
redactedPayload: redacted,
lastError: "Workspace-owner invitation database invalidation requires retry.",
now: new Date("2026-07-15T12:45:00.000Z"),
},
client as never
)
).resolves.toBeUndefined();
expect(tx.outboxEvent.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({ id: "outbox_1", tenantId: "tenant_1", status: { in: ["DONE", "FAILED", "PENDING"] } }),
data: expect.objectContaining({ status: "PENDING", payload: redacted, processedAt: null, lockedUntil: null }),
});
expect(JSON.stringify(tx.outboxEvent.updateMany.mock.calls)).not.toContain(TOKEN);
});
it("rejects recovery when the embedded outbox id or tenant does not match the caller", async () => {
const { client, tx } = harness();
const wrongEvent = boundTerminalPayload({ outboxEventId: "outbox_other" });
const correct = boundTerminalPayload();
await expect(
scheduleWorkspaceOwnerInvitationTerminalRecovery(
{
tenantId: "tenant_1",
outboxEventId: "outbox_1",
redactedPayload: wrongEvent,
lastError: "database retry",
},
client as never
)
).rejects.toThrow(/contract is invalid/u);
await expect(
scheduleWorkspaceOwnerInvitationTerminalRecovery(
{
tenantId: "tenant_other",
outboxEventId: "outbox_1",
redactedPayload: correct,
lastError: "database retry",
},
client as never
)
).rejects.toThrow(/contract is invalid/u);
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it("rejects recovery when the selected outbox row belongs to another invitation identity", async () => {
const mismatchedOutboxPayload = {
...mailPayload(),
metadata: { ...mailPayload().metadata, invitationId: "invite_other" },
};
const { client, tx } = harness(invitation(), mismatchedOutboxPayload);
await expect(
scheduleWorkspaceOwnerInvitationTerminalRecovery(
{
tenantId: "tenant_1",
outboxEventId: "outbox_1",
redactedPayload: boundTerminalPayload(),
lastError: "database retry",
},
client as never
)
).rejects.toThrow(/does not match its recovery identity/u);
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it("fails closed on a token-hash mismatch without changing the invitation", async () => {
const { client, tx } = harness(invitation({ tokenHash: "c".repeat(64) }));
await expect(terminalizeWorkspaceOwnerInvitationDelivery({ tenantId: "tenant_1", payload: mailPayload() }, client as never)).rejects.toThrow(
/could not prove/u
);
expect(tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
it("rejects a terminal outbox transition whose redacted fields or lastError still contain the capability", async () => {
const { client, tx } = harness();
const payload = mailPayload();
const unsafeRedacted = {
...(boundTerminalPayload() as Record<string, unknown>),
headers: { "x-debug-capability": TOKEN },
};
await expect(
terminalizeWorkspaceOwnerInvitationDelivery(
{
tenantId: "tenant_1",
payload,
outboxFailure: {
eventId: "outbox_1",
deliveryGeneration: 0,
lockedUntil: new Date("2026-07-15T12:05:00.000Z"),
redactedPayload: unsafeRedacted as never,
retries: 7,
lastError: `provider echoed ${TOKEN}`,
processedAt: new Date("2026-07-15T12:00:00.000Z"),
},
},
client as never
)
).rejects.toThrow(/redaction contract is invalid/u);
expect(tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
expect(tx.outboxEvent.updateMany).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,584 @@
import { timingSafeEqual } from "node:crypto";
import { getDbClient, type DbClient } from "@hivegrid/db/client.server";
import type { Prisma, TenantUserInvitation } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import {
WORKSPACE_INVITE_STATUS_ACCEPTED,
WORKSPACE_INVITE_STATUS_DELIVERY_FAILED,
WORKSPACE_INVITE_STATUS_EXPIRED,
WORKSPACE_INVITE_STATUS_PENDING,
WORKSPACE_INVITE_STATUS_REVOKED,
} from "@hivegrid/db/workspace-invites.server";
import {
findWorkspaceOwnerInvitationRawToken,
readWorkspaceOwnerInvitationMailMetadata,
workspaceOwnerInvitationHashesEqual,
} from "@hivegrid/db/workspace-owner-invite-mail-contract.server";
import {
bindTerminalWorkspaceOwnerInvitationMailPayload,
hasValidWorkspaceOwnerInvitationMailContract,
isWorkspaceOwnerInvitationDeliveryStarted,
isWorkspaceOwnerInvitationProviderAccepted,
markWorkspaceOwnerInvitationDeliveryStarted,
markWorkspaceOwnerInvitationProviderAccepted,
readWorkspaceOwnerInvitationOutboxBinding,
isTerminalWorkspaceOwnerInvitationMailPayload,
readWorkspaceOwnerInvitationRecoveryBinding,
} from "./workspace-owner-invitation-secret.js";
const WORKSPACE_OWNER_TYPE = 0;
export type WorkspaceOwnerInvitationOutboxTerminalFailure = {
eventId: string;
deliveryGeneration: number;
lockedUntil: Date | null;
redactedPayload: Prisma.InputJsonValue;
retries: number;
lastError: string;
processedAt: Date;
};
export type WorkspaceOwnerInvitationTerminalizationInput = {
tenantId: string;
payload: unknown;
now?: Date;
outboxFailure?: WorkspaceOwnerInvitationOutboxTerminalFailure;
};
export type WorkspaceOwnerInvitationTerminalizationResult = {
invitationId: string;
state: "invalidated" | "already_inactive";
};
export type WorkspaceOwnerInvitationRecoveryScheduleInput = {
tenantId: string;
outboxEventId: string;
redactedPayload: unknown;
lastError: string;
now?: Date;
};
export type WorkspaceOwnerInvitationDeliveryClaimResult =
| { state: "claimed"; payload: unknown }
| { state: "provider_accepted"; payload: unknown }
| { state: "uncertain"; payload: unknown }
| { state: "not_ready" };
export type WorkspaceOwnerInvitationDeliveryClaimInput = {
tenantId: string;
payload: unknown;
};
export type WorkspaceOwnerInvitationDeliveryAbandonInput = WorkspaceOwnerInvitationDeliveryClaimInput & {
lastError: string;
now?: Date;
};
/**
* Claims the single OWNER provider attempt in the originating DB outbox row.
* A previous `delivery_started` marker is deliberately ambiguous: a crashed
* worker may already have reached the provider, so callers must rotate rather
* than attempt a second delivery.
*/
export async function claimWorkspaceOwnerInvitationDelivery(
input: WorkspaceOwnerInvitationDeliveryClaimInput,
client: Pick<DbClient, "$transaction"> = getDbClient()
): Promise<WorkspaceOwnerInvitationDeliveryClaimResult> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const binding = requireDeliveryBinding(input.payload, tenantId);
const claimedPayload = markWorkspaceOwnerInvitationDeliveryStarted(input.payload);
return bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation-delivery:${tenantId}:${binding.outboxEventId}`}, 0))`;
const outbox = await tx.outboxEvent.findFirst({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
},
select: { payload: true, status: true },
});
if (!outbox) throw new Error("Workspace-owner invitation delivery outbox row is missing.");
assertExactOutboxMailIdentity(outbox.payload, input.payload, binding);
if (outbox.status === "PROCESSING") return { state: "not_ready" };
if (outbox.status !== "DONE") throw new Error("Workspace-owner invitation delivery outbox row is not dispatch-complete.");
if (isWorkspaceOwnerInvitationProviderAccepted(outbox.payload)) {
return { state: "provider_accepted", payload: outbox.payload };
}
if (isWorkspaceOwnerInvitationDeliveryStarted(outbox.payload) || isTerminalWorkspaceOwnerInvitationMailPayload(outbox.payload)) {
return { state: "uncertain", payload: outbox.payload };
}
const transition = await tx.outboxEvent.updateMany({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
data: { payload: claimedPayload as Prisma.InputJsonValue },
});
if (transition.count !== 1) throw new Error("Workspace-owner invitation delivery claim lost its race.");
return { state: "claimed", payload: claimedPayload };
})
);
}
/** Persists the provider acknowledgement before BullMQ may retry the job. */
export async function acceptWorkspaceOwnerInvitationDelivery(
input: WorkspaceOwnerInvitationDeliveryClaimInput,
client: Pick<DbClient, "$transaction"> = getDbClient()
): Promise<unknown> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const binding = requireDeliveryBinding(input.payload, tenantId);
const acceptedPayload = markWorkspaceOwnerInvitationProviderAccepted(input.payload);
return bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation-delivery:${tenantId}:${binding.outboxEventId}`}, 0))`;
const outbox = await tx.outboxEvent.findFirst({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
select: { payload: true },
});
assertExactOutboxMailIdentity(outbox?.payload, input.payload, binding);
if (isWorkspaceOwnerInvitationProviderAccepted(outbox?.payload)) return outbox!.payload;
if (!isWorkspaceOwnerInvitationDeliveryStarted(outbox?.payload)) {
throw new Error("Workspace-owner invitation provider acknowledgement has no active delivery claim.");
}
const transition = await tx.outboxEvent.updateMany({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
data: { payload: acceptedPayload as Prisma.InputJsonValue },
});
if (transition.count !== 1) throw new Error("Workspace-owner invitation provider acknowledgement lost its race.");
return acceptedPayload;
})
);
}
/** Invalidates an ambiguous claimed delivery and durably requires rotation. */
export async function abandonWorkspaceOwnerInvitationDelivery(
input: WorkspaceOwnerInvitationDeliveryAbandonInput,
client: Pick<DbClient, "$transaction"> = getDbClient()
): Promise<WorkspaceOwnerInvitationTerminalizationResult> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const binding = requireDeliveryBinding(input.payload, tenantId);
if (!input.lastError || input.lastError.length > 1_000 || /<[a-z][^>]*>/iu.test(input.lastError)) {
throw new Error("Workspace-owner invitation delivery abandonment error is unsafe.");
}
const terminalPayload = bindTerminalWorkspaceOwnerInvitationMailPayload(input.payload, binding);
const metadata = readWorkspaceOwnerInvitationMailMetadata(input.payload)!;
const now = input.now ?? new Date();
return bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation-delivery:${tenantId}:${binding.outboxEventId}`}, 0))`;
const outbox = await tx.outboxEvent.findFirst({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
select: { payload: true },
});
assertExactOutboxMailIdentity(outbox?.payload, input.payload, binding);
if (!isWorkspaceOwnerInvitationDeliveryStarted(outbox?.payload) && !isTerminalWorkspaceOwnerInvitationMailPayload(outbox?.payload)) {
throw new Error("Workspace-owner invitation delivery abandonment has no ambiguous claim.");
}
const invitation = await tx.tenantUserInvitation.findFirst({
where: { id: metadata.invitationId, tenantId },
orderBy: { id: "asc" },
});
assertExactOwnerInvitation(invitation, tenantId, metadata.invitationTokenHash);
let state: WorkspaceOwnerInvitationTerminalizationResult["state"] = "already_inactive";
if (isActiveInvitation(invitation)) {
const invitationTransition = await tx.tenantUserInvitation.updateMany({
where: {
id: invitation.id,
tenantId,
type: WORKSPACE_OWNER_TYPE,
tokenHash: metadata.invitationTokenHash,
pending: true,
status: WORKSPACE_INVITE_STATUS_PENDING,
createdUserId: null,
acceptedAt: null,
revokedAt: null,
acceptedByUserId: null,
revokedByUserId: null,
},
data: { pending: false, status: WORKSPACE_INVITE_STATUS_DELIVERY_FAILED, revokedAt: now, revokedByUserId: null },
});
if (invitationTransition.count !== 1) throw new Error("Workspace-owner invitation delivery abandonment lost its capability race.");
state = "invalidated";
} else if (!isSafelyInactive(invitation)) {
throw new Error("Workspace-owner invitation delivery abandonment found an ambiguous capability state.");
}
const outboxTransition = await tx.outboxEvent.updateMany({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "DONE",
},
data: {
status: "FAILED",
payload: terminalPayload as Prisma.InputJsonValue,
lastError: input.lastError,
processedAt: now,
lockedUntil: null,
},
});
if (outboxTransition.count !== 1) throw new Error("Workspace-owner invitation delivery abandonment lost its outbox race.");
return { invitationId: invitation.id, state };
})
);
}
/**
* Invalidates the capability proven by the exact mail contract. When the DB
* outbox itself is terminal, its token-free FAILED transition is committed in
* the same transaction as the invitation transition.
*/
export async function terminalizeWorkspaceOwnerInvitationDelivery(
input: WorkspaceOwnerInvitationTerminalizationInput,
client: Pick<DbClient, "$transaction"> = getDbClient()
): Promise<WorkspaceOwnerInvitationTerminalizationResult> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
if (!hasValidWorkspaceOwnerInvitationMailContract(input.payload)) {
throw new Error("Workspace-owner invitation terminalization requires an exact mail contract.");
}
const payload = asRecord(input.payload);
const metadata = readWorkspaceOwnerInvitationMailMetadata(input.payload);
if (!payload || !metadata || payload.tenantId !== tenantId) {
throw new Error("Workspace-owner invitation terminalization tenant contract mismatch.");
}
if (input.outboxFailure) {
assertSafeOutboxFailure(input.outboxFailure, payload, metadata);
}
const now = input.now ?? new Date();
return bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation:${tenantId}`}, 0))`;
if (input.outboxFailure) {
const binding = readWorkspaceOwnerInvitationRecoveryBinding(input.outboxFailure.redactedPayload);
const outbox = binding
? await tx.outboxEvent.findFirst({
where: {
id: binding.outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "PROCESSING",
deliveryGeneration: input.outboxFailure.deliveryGeneration,
lockedUntil: input.outboxFailure.lockedUntil,
},
select: { payload: true },
})
: null;
assertExactOutboxMailIdentity(outbox?.payload, input.outboxFailure.redactedPayload, binding);
}
const invitation = await tx.tenantUserInvitation.findFirst({
where: { id: metadata.invitationId, tenantId },
orderBy: { id: "asc" },
});
assertExactOwnerInvitation(invitation, tenantId, metadata.invitationTokenHash);
let state: WorkspaceOwnerInvitationTerminalizationResult["state"] = "already_inactive";
if (isActiveInvitation(invitation)) {
const transition = await tx.tenantUserInvitation.updateMany({
where: {
id: invitation.id,
tenantId,
type: WORKSPACE_OWNER_TYPE,
tokenHash: metadata.invitationTokenHash,
pending: true,
status: WORKSPACE_INVITE_STATUS_PENDING,
createdUserId: null,
acceptedAt: null,
revokedAt: null,
acceptedByUserId: null,
revokedByUserId: null,
},
data: {
pending: false,
status: WORKSPACE_INVITE_STATUS_DELIVERY_FAILED,
revokedAt: now,
revokedByUserId: null,
},
});
if (transition.count !== 1) {
throw new Error("Workspace-owner invitation terminalization lost its capability transition race.");
}
state = "invalidated";
} else if (!isSafelyInactive(invitation)) {
throw new Error("Workspace-owner invitation terminalization found an ambiguous capability state.");
}
if (input.outboxFailure) {
const failure = input.outboxFailure;
const binding = readWorkspaceOwnerInvitationRecoveryBinding(failure.redactedPayload);
if (!binding || binding.outboxEventId !== normalizeIdentifier(failure.eventId, "outboxEventId")) {
throw new Error("Workspace-owner invitation terminal outbox binding is invalid.");
}
if (!Number.isSafeInteger(failure.retries) || failure.retries < 1) {
throw new Error("Workspace-owner invitation terminal outbox retry count is invalid.");
}
const outboxTransition = await tx.outboxEvent.updateMany({
where: {
id: failure.eventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: "PROCESSING",
deliveryGeneration: failure.deliveryGeneration,
lockedUntil: failure.lockedUntil,
},
data: {
status: "FAILED",
payload: failure.redactedPayload,
retries: failure.retries,
lastError: failure.lastError,
processedAt: failure.processedAt,
lockedUntil: null,
},
});
if (outboxTransition.count !== 1) {
throw new Error("Workspace-owner invitation terminal outbox transition lost its race.");
}
}
return { invitationId: invitation.id, state };
})
);
}
/** Rearms the original DB outbox row as a token-free durable invalidation retry. */
export async function scheduleWorkspaceOwnerInvitationTerminalRecovery(
input: WorkspaceOwnerInvitationRecoveryScheduleInput,
client: Pick<DbClient, "$transaction"> = getDbClient()
): Promise<void> {
const tenantId = normalizeIdentifier(input.tenantId, "tenantId");
const outboxEventId = normalizeIdentifier(input.outboxEventId, "outboxEventId");
const payload = asRecord(input.redactedPayload);
const metadata = readWorkspaceOwnerInvitationMailMetadata(input.redactedPayload);
const binding = readWorkspaceOwnerInvitationRecoveryBinding(input.redactedPayload);
if (
!payload ||
payload.tenantId !== tenantId ||
!metadata ||
!binding ||
binding.tenantId !== tenantId ||
binding.outboxEventId !== outboxEventId ||
!input.lastError ||
input.lastError.length > 1_000 ||
/<[a-z][^>]*>/iu.test(input.lastError)
) {
throw new Error("Workspace-owner invitation recovery schedule contract is invalid.");
}
const now = input.now ?? new Date();
await bindTenantContext(tenantId, () =>
client.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation:${tenantId}`}, 0))`;
const outbox = await tx.outboxEvent.findFirst({
where: {
id: outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: { in: ["DONE", "FAILED", "PENDING"] },
},
select: { payload: true },
});
assertExactOutboxMailIdentity(outbox?.payload, input.redactedPayload, binding);
const transition = await tx.outboxEvent.updateMany({
where: {
id: outboxEventId,
tenantId,
eventType: "mail.transactional.send",
dispatchKey: binding.dispatchKey,
status: { in: ["DONE", "FAILED", "PENDING"] },
},
data: {
status: "PENDING",
payload: input.redactedPayload as Prisma.InputJsonValue,
lastError: input.lastError,
scheduledAt: now,
processedAt: null,
lockedUntil: null,
},
});
if (transition.count !== 1) {
throw new Error("Workspace-owner invitation recovery schedule lost its outbox transition race.");
}
})
);
}
function assertSafeOutboxFailure(
failure: WorkspaceOwnerInvitationOutboxTerminalFailure,
payload: Record<string, unknown>,
metadata: NonNullable<ReturnType<typeof readWorkspaceOwnerInvitationMailMetadata>>
): void {
const payloadIsRedactedRecovery = isTerminalWorkspaceOwnerInvitationMailPayload(payload);
const redactedMetadata = readWorkspaceOwnerInvitationMailMetadata(failure.redactedPayload);
const redactedPayload = asRecord(failure.redactedPayload);
const recoveryBinding = readWorkspaceOwnerInvitationRecoveryBinding(failure.redactedPayload);
const html = typeof payload.html === "string" ? payload.html : "";
const rawToken = payloadIsRedactedRecovery ? null : findWorkspaceOwnerInvitationRawToken(html, metadata.invitationTokenHash);
if (
!isTerminalWorkspaceOwnerInvitationMailPayload(failure.redactedPayload) ||
!redactedPayload ||
redactedPayload.tenantId !== payload.tenantId ||
!recoveryBinding ||
recoveryBinding.outboxEventId !== failure.eventId ||
!Number.isSafeInteger(failure.deliveryGeneration) ||
failure.deliveryGeneration < 0 ||
(failure.lockedUntil !== null && !(failure.lockedUntil instanceof Date)) ||
!redactedMetadata ||
redactedMetadata.invitationId !== metadata.invitationId ||
!workspaceOwnerInvitationHashesEqual(redactedMetadata.invitationTokenHash, metadata.invitationTokenHash) ||
!workspaceOwnerInvitationHashesEqual(redactedMetadata.issuanceKeyHash, metadata.issuanceKeyHash) ||
!workspaceOwnerInvitationHashesEqual(redactedMetadata.mailContentHash, metadata.mailContentHash) ||
(!payloadIsRedactedRecovery && !rawToken) ||
(rawToken !== null && JSON.stringify(failure.redactedPayload).includes(rawToken)) ||
(rawToken !== null && failure.lastError.includes(rawToken)) ||
/<[a-z][^>]*>/iu.test(failure.lastError) ||
failure.lastError.length > 1_000
) {
throw new Error("Workspace-owner invitation terminal outbox redaction contract is invalid.");
}
}
function requireDeliveryBinding(
payload: unknown,
tenantId: string
): NonNullable<ReturnType<typeof readWorkspaceOwnerInvitationOutboxBinding>> {
const record = asRecord(payload);
const binding = readWorkspaceOwnerInvitationOutboxBinding(payload);
if (!hasValidWorkspaceOwnerInvitationMailContract(payload) || !record || record.tenantId !== tenantId || !binding || binding.tenantId !== tenantId) {
throw new Error("Workspace-owner invitation delivery claim requires an exact bound mail contract.");
}
return binding;
}
function assertExactOutboxMailIdentity(
actualPayload: unknown,
expectedPayload: unknown,
binding: ReturnType<typeof readWorkspaceOwnerInvitationOutboxBinding>
): void {
const actual = asRecord(actualPayload);
const expected = asRecord(expectedPayload);
const actualMetadata = readWorkspaceOwnerInvitationMailMetadata(actualPayload);
const expectedMetadata = readWorkspaceOwnerInvitationMailMetadata(expectedPayload);
const rawActualMetadata = asRecord(actual?.metadata);
if (
!binding ||
!actual ||
!expected ||
actual.tenantId !== binding.tenantId ||
expected.tenantId !== binding.tenantId ||
!hasValidWorkspaceOwnerInvitationMailContract(actualPayload) ||
!actualMetadata ||
!expectedMetadata ||
actualMetadata.invitationId !== expectedMetadata.invitationId ||
!workspaceOwnerInvitationHashesEqual(actualMetadata.invitationTokenHash, expectedMetadata.invitationTokenHash) ||
!workspaceOwnerInvitationHashesEqual(actualMetadata.issuanceKeyHash, expectedMetadata.issuanceKeyHash) ||
!workspaceOwnerInvitationHashesEqual(actualMetadata.mailContentHash, expectedMetadata.mailContentHash) ||
(rawActualMetadata?.outboxEventId !== undefined && rawActualMetadata.outboxEventId !== binding.outboxEventId) ||
(rawActualMetadata?.dispatchKey !== undefined && rawActualMetadata.dispatchKey !== binding.dispatchKey)
) {
throw new Error("Workspace-owner invitation outbox row does not match its recovery identity.");
}
}
function assertExactOwnerInvitation(
invitation: TenantUserInvitation | null,
tenantId: string,
invitationTokenHash: string
): asserts invitation is TenantUserInvitation {
if (
!invitation ||
invitation.tenantId !== tenantId ||
invitation.type !== WORKSPACE_OWNER_TYPE ||
!invitation.tokenHash ||
!hashesEqual(invitation.tokenHash, invitationTokenHash)
) {
throw new Error("Workspace-owner invitation terminalization could not prove its capability.");
}
}
function isActiveInvitation(invitation: TenantUserInvitation): boolean {
return (
invitation.status === WORKSPACE_INVITE_STATUS_PENDING &&
invitation.pending &&
invitation.createdUserId === null &&
invitation.acceptedAt === null &&
invitation.revokedAt === null &&
invitation.acceptedByUserId === null &&
invitation.revokedByUserId === null
);
}
function isSafelyInactive(invitation: TenantUserInvitation): boolean {
if (invitation.status === WORKSPACE_INVITE_STATUS_ACCEPTED) {
return !invitation.pending && invitation.acceptedAt !== null && invitation.acceptedByUserId !== null;
}
if (invitation.status === WORKSPACE_INVITE_STATUS_REVOKED) {
return !invitation.pending && invitation.revokedAt !== null;
}
if (invitation.status === WORKSPACE_INVITE_STATUS_EXPIRED) {
return !invitation.pending;
}
if (invitation.status === WORKSPACE_INVITE_STATUS_DELIVERY_FAILED) {
return !invitation.pending && invitation.revokedAt !== null && invitation.revokedByUserId === null;
}
return false;
}
function bindTenantContext<T>(tenantId: string, callback: () => T): T {
const current = getRlsExecutionContext();
if (current?.tenantId && current.tenantId !== tenantId) {
throw new Error("Workspace-owner invitation terminalization cannot switch tenant context.");
}
return current?.tenantId === tenantId ? callback() : runWithRlsContext({ tenantId }, callback);
}
function normalizeIdentifier(value: string, field: string): string {
const normalized = value.trim();
if (!normalized || normalized !== value || normalized.length > 191 || normalized.includes("\u0000")) {
throw new Error(`Workspace-owner invitation ${field} is invalid.`);
}
return normalized;
}
function hashesEqual(actual: string, expected: string): boolean {
if (!/^[a-f0-9]{64}$/u.test(actual) || !/^[a-f0-9]{64}$/u.test(expected)) return false;
return timingSafeEqual(Buffer.from(actual, "hex"), Buffer.from(expected, "hex"));
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
}