import { createHash, timingSafeEqual } from "node:crypto"; export const PORTAL_SETUP_MAIL_SOURCE = "portal_setup_invite" as const; export const PORTAL_SETUP_TOKEN_PLACEHOLDER = "__HIVEGRID_PORTAL_SETUP_CAPABILITY__" as const; export const PORTAL_SETUP_SECRET_REDACTED_MARKER = "secretBodyRedacted" as const; export const PORTAL_SETUP_DELIVERY_STATUS_KEY = "portalSetupDeliveryStatus" as const; export const PORTAL_SETUP_DELIVERY_STARTED = "delivery_started" as const; export const PORTAL_SETUP_PROVIDER_ACCEPTED = "provider_accepted" as const; export const PORTAL_SETUP_ROTATION_REQUIRED = "rotation_required" as const; export type PortalSetupMailMetadata = { source: typeof PORTAL_SETUP_MAIL_SOURCE; invitationSource: string; portalId: string; portalUserId: string; portalTokenId: string; setupTokenHash: string; expiresAt: string; mailContentHash: string; encryptedCapability?: string; outboxEventId?: string; dispatchKey?: string; }; export type PortalSetupCapabilityPlaintextInput = { tenantId: string; rawToken: string; metadata: Omit; }; export type PortalSetupMailOutboxBinding = { outboxEventId: string; dispatchKey: string; }; export function hashPortalSetupMailContent(input: { recipient: string; subject: string; text: string; html: string; }): string { const recipient = normalizeRecipient(input.recipient); const subject = normalizeMailText(input.subject); const text = normalizeMailText(input.text); const html = normalizeMailText(input.html); if ( !recipient || !subject || !text.includes(PORTAL_SETUP_TOKEN_PLACEHOLDER) || !html.includes(PORTAL_SETUP_TOKEN_PLACEHOLDER) ) { throw new Error("Portal setup mail content is incomplete."); } return sha256(JSON.stringify({ version: 1, recipient, subject, text, html })); } export function buildPortalSetupCapabilityPlaintext(input: PortalSetupCapabilityPlaintextInput): string { const tenantId = normalizeIdentifier(input.tenantId, "tenantId"); const metadata = normalizeMetadata({ source: PORTAL_SETUP_MAIL_SOURCE, ...input.metadata }); if (!isRawToken(input.rawToken) || !hashesEqual(sha256(input.rawToken), metadata.setupTokenHash)) { throw new Error("Portal setup capability does not match its token hash."); } return JSON.stringify({ version: 1, tenantId, portalId: metadata.portalId, portalUserId: metadata.portalUserId, portalTokenId: metadata.portalTokenId, purpose: "setup", expiresAt: metadata.expiresAt, setupTokenHash: metadata.setupTokenHash, mailContentHash: metadata.mailContentHash, rawToken: input.rawToken, }); } export function readPortalSetupCapabilityPlaintext( plaintext: string, expected: { tenantId: string; metadata: PortalSetupMailMetadata }, ): string { let parsed: unknown; try { parsed = JSON.parse(plaintext); } catch { throw new Error("Portal setup capability envelope is invalid."); } const record = asRecord(parsed); const metadata = normalizeMetadata(expected.metadata); if ( !record || !hasExactKeys(record, [ "version", "tenantId", "portalId", "portalUserId", "portalTokenId", "purpose", "expiresAt", "setupTokenHash", "mailContentHash", "rawToken", ]) || record.version !== 1 || record.purpose !== "setup" || record.tenantId !== normalizeIdentifier(expected.tenantId, "tenantId") || record.portalId !== metadata.portalId || record.portalUserId !== metadata.portalUserId || record.portalTokenId !== metadata.portalTokenId || record.expiresAt !== metadata.expiresAt || record.setupTokenHash !== metadata.setupTokenHash || record.mailContentHash !== metadata.mailContentHash || typeof record.rawToken !== "string" || !isRawToken(record.rawToken) || !hashesEqual(sha256(record.rawToken), metadata.setupTokenHash) ) { throw new Error("Portal setup capability envelope does not match its mail identity."); } return record.rawToken; } export function readPortalSetupMailMetadata(payload: unknown): PortalSetupMailMetadata | null { const record = asRecord(payload); const metadata = asRecord(record?.metadata); if (metadata?.source !== PORTAL_SETUP_MAIL_SOURCE) return null; try { return normalizeMetadata(metadata); } catch { return null; } } /** * Binds the encrypted capability to the durable outbox identity before it is * materialized for the provider queue. The dispatch key is derived from the * persisted token id so an envelope cannot be paired with another event. */ export function bindEncryptedPortalSetupMailToOutbox( payload: unknown, binding: PortalSetupMailOutboxBinding, ): Record { if (!hasValidEncryptedPortalSetupMailContent(payload)) { throw new Error("Portal setup encrypted mail contract is invalid."); } const record = payload as Record; const metadata = readPortalSetupMailMetadata(payload)!; const outboxEventId = normalizeIdentifier(binding.outboxEventId, "outboxEventId"); const dispatchKey = normalizeIdentifier(binding.dispatchKey, "dispatchKey", 256); if ( dispatchKey !== portalSetupDispatchKey(metadata.portalTokenId) || (metadata.outboxEventId !== undefined && metadata.outboxEventId !== outboxEventId) || (metadata.dispatchKey !== undefined && metadata.dispatchKey !== dispatchKey) ) { throw new Error("Portal setup mail outbox binding is invalid."); } return { ...record, metadata: { ...(record.metadata as Record), outboxEventId, dispatchKey, }, }; } export function isPortalSetupMailIntent(payload: unknown): boolean { return asRecord(asRecord(payload)?.metadata)?.source === PORTAL_SETUP_MAIL_SOURCE; } export function hasValidEncryptedPortalSetupMailContent(payload: unknown): boolean { const record = asRecord(payload); const metadata = readPortalSetupMailMetadata(payload); if (!record || !metadata || !metadata.encryptedCapability) return false; if (!hasExactPayloadShape(record, "encrypted") || !hasExactMetadataShape(asRecord(record.metadata), "encrypted")) return false; if (!hasCommonMailIdentity(record, metadata) || !hasValidOptionalOutboxBinding(metadata)) return false; if (typeof record.text !== "string" || typeof record.html !== "string") return false; if (!record.text.includes(PORTAL_SETUP_TOKEN_PLACEHOLDER) || !record.html.includes(PORTAL_SETUP_TOKEN_PLACEHOLDER)) return false; try { const actual = hashPortalSetupMailContent({ recipient: (record.to as string[])[0]!, subject: record.subject as string, text: record.text, html: record.html, }); return hashesEqual(actual, metadata.mailContentHash); } catch { return false; } } export function materializePortalSetupMailContent(payload: unknown, rawToken: string): Record { if (!hasValidEncryptedPortalSetupMailContent(payload)) { throw new Error("Portal setup encrypted mail contract is invalid."); } const record = payload as Record; const metadata = readPortalSetupMailMetadata(payload)!; if (!isRawToken(rawToken) || !hashesEqual(sha256(rawToken), metadata.setupTokenHash)) { throw new Error("Portal setup decrypted capability does not match its token hash."); } const { encryptedCapability: _encryptedCapability, ...safeMetadata } = metadata; return { ...record, text: (record.text as string).replaceAll(PORTAL_SETUP_TOKEN_PLACEHOLDER, rawToken), html: (record.html as string).replaceAll(PORTAL_SETUP_TOKEN_PLACEHOLDER, rawToken), metadata: safeMetadata, }; } export function hasValidMaterializedPortalSetupMailContent(payload: unknown): boolean { const record = asRecord(payload); const metadata = readPortalSetupMailMetadata(payload); if ( !record || !metadata || metadata.encryptedCapability !== undefined || !hasExactPayloadShape(record, "materialized") || !hasExactMetadataShape(asRecord(record.metadata), "materialized") || !hasCommonMailIdentity(record, metadata) || !hasRequiredOutboxBinding(metadata) ) { return false; } if (typeof record.text !== "string" || typeof record.html !== "string") return false; const rawToken = findPortalSetupRawToken(record.text, record.html, metadata.setupTokenHash); if (!rawToken) return false; try { const actual = hashPortalSetupMailContent({ recipient: (record.to as string[])[0]!, subject: record.subject as string, text: record.text.replaceAll(rawToken, PORTAL_SETUP_TOKEN_PLACEHOLDER), html: record.html.replaceAll(rawToken, PORTAL_SETUP_TOKEN_PLACEHOLDER), }); return hashesEqual(actual, metadata.mailContentHash); } catch { return false; } } export function hasValidRedactedPortalSetupMailContent(payload: unknown): boolean { const record = asRecord(payload); const metadata = readPortalSetupMailMetadata(payload); if ( !record || !metadata || !hasExactPayloadShape(record, "redacted") || !hasExactMetadataShape(asRecord(record.metadata), "redacted") || !hasCommonMailIdentity(record, metadata) || !hasValidOptionalOutboxBinding(metadata) ) { return false; } return ( metadata.encryptedCapability === undefined && asRecord(record.metadata)?.[PORTAL_SETUP_SECRET_REDACTED_MARKER] === true && !("text" in record) && !("html" in record) && !("templateData" in record) && !("attachments" in record) ); } export function findPortalSetupRawToken(text: string, html: string, setupTokenHash: string): string | null { if (!isSha256(setupTokenHash)) return null; const candidates = new Set( `${text}\n${html}`.match(/(?:\/setup\/)([A-Za-z0-9_-]{32,512})/gu)?.map((match) => match.slice("/setup/".length)) ?? [], ); const matching = [...candidates].filter((candidate) => hashesEqual(sha256(candidate), setupTokenHash)); return matching.length === 1 ? matching[0]! : null; } export function portalSetupMailHashesEqual(actual: string, expected: string): boolean { return hashesEqual(actual, expected); } function normalizeMetadata(value: Record | PortalSetupMailMetadata): PortalSetupMailMetadata { if (value.source !== PORTAL_SETUP_MAIL_SOURCE) throw new Error("Portal setup mail source is invalid."); const invitationSource = normalizeIdentifier(value.invitationSource, "invitationSource", 80); const portalId = normalizeIdentifier(value.portalId, "portalId"); const portalUserId = normalizeIdentifier(value.portalUserId, "portalUserId"); const portalTokenId = normalizeIdentifier(value.portalTokenId, "portalTokenId"); if (!isSha256(value.setupTokenHash) || !isSha256(value.mailContentHash)) { throw new Error("Portal setup mail digest is invalid."); } const expiresAt = normalizeDate(value.expiresAt); const encryptedCapability = value.encryptedCapability === undefined ? undefined : normalizeIdentifier(value.encryptedCapability, "encryptedCapability", 16_384); const outboxEventId = value.outboxEventId === undefined ? undefined : normalizeIdentifier(value.outboxEventId, "outboxEventId"); const dispatchKey = value.dispatchKey === undefined ? undefined : normalizeIdentifier(value.dispatchKey, "dispatchKey", 256); return { source: PORTAL_SETUP_MAIL_SOURCE, invitationSource, portalId, portalUserId, portalTokenId, setupTokenHash: value.setupTokenHash, expiresAt, mailContentHash: value.mailContentHash, ...(encryptedCapability ? { encryptedCapability } : {}), ...(outboxEventId ? { outboxEventId } : {}), ...(dispatchKey ? { dispatchKey } : {}), }; } function hasCommonMailIdentity(record: Record, metadata: PortalSetupMailMetadata): boolean { return ( typeof record.tenantId === "string" && record.tenantId.trim().length > 0 && Array.isArray(record.to) && record.to.length === 1 && typeof record.to[0] === "string" && record.to[0].includes("@") && typeof record.subject === "string" && record.subject.trim().length > 0 && metadata.source === PORTAL_SETUP_MAIL_SOURCE ); } function hasExactPayloadShape(record: Record, state: "encrypted" | "materialized" | "redacted"): boolean { const allowed = new Set([ "kind", "tenantId", "to", "subject", "priorityOverride", "metadata", ...(state === "redacted" ? [] : ["text", "html"]), ]); return ( Object.keys(record).every((key) => allowed.has(key)) && (record.kind === undefined || record.kind === "mail.transactional") && typeof record.tenantId === "string" && record.tenantId.trim().length > 0 && (record.priorityOverride === undefined || record.priorityOverride === "critical") && (state === "redacted" ? !("text" in record) && !("html" in record) : typeof record.text === "string" && typeof record.html === "string") ); } function hasExactMetadataShape( metadata: Record | null, state: "encrypted" | "materialized" | "redacted", ): boolean { if (!metadata) return false; const allowed = new Set([ "source", "invitationSource", "portalId", "portalUserId", "portalTokenId", "setupTokenHash", "expiresAt", "mailContentHash", "outboxEventId", "dispatchKey", ...(state === "encrypted" ? ["encryptedCapability"] : []), ...(state === "redacted" ? [PORTAL_SETUP_SECRET_REDACTED_MARKER, PORTAL_SETUP_DELIVERY_STATUS_KEY] : []), ]); const status = metadata[PORTAL_SETUP_DELIVERY_STATUS_KEY]; return ( Object.keys(metadata).every((key) => allowed.has(key)) && (state !== "encrypted" || typeof metadata.encryptedCapability === "string") && (state !== "redacted" || (metadata[PORTAL_SETUP_SECRET_REDACTED_MARKER] === true && (status === undefined || status === PORTAL_SETUP_DELIVERY_STARTED || status === PORTAL_SETUP_PROVIDER_ACCEPTED || status === PORTAL_SETUP_ROTATION_REQUIRED))) ); } function hasValidOptionalOutboxBinding(metadata: PortalSetupMailMetadata): boolean { if (metadata.outboxEventId === undefined && metadata.dispatchKey === undefined) return true; return hasRequiredOutboxBinding(metadata); } function hasRequiredOutboxBinding(metadata: PortalSetupMailMetadata): boolean { return Boolean( metadata.outboxEventId && metadata.dispatchKey && metadata.dispatchKey === portalSetupDispatchKey(metadata.portalTokenId), ); } function portalSetupDispatchKey(portalTokenId: string): string { return `portal-setup:${portalTokenId}`; } function hasExactKeys(record: Record, expected: readonly string[]): boolean { return Object.keys(record).length === expected.length && Object.keys(record).every((key) => expected.includes(key)); } function normalizeRecipient(value: string): string { return value.trim().toLowerCase().normalize("NFC"); } function normalizeMailText(value: string): string { return value.replace(/\r\n?/gu, "\n").trim().normalize("NFC"); } 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 mail ${field} is invalid.`); } return value; } function normalizeDate(value: unknown): string { if (typeof value !== "string") throw new Error("Portal setup mail expiresAt is invalid."); const parsed = new Date(value); if (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== value) { throw new Error("Portal setup mail expiresAt is invalid."); } return value; } function isRawToken(value: string): boolean { return /^[A-Za-z0-9_-]{32,512}$/u.test(value); } function isSha256(value: unknown): value is string { return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value); } function sha256(value: string): string { return createHash("sha256").update(value, "utf8").digest("hex"); } function hashesEqual(actual: string, expected: string): boolean { if (!isSha256(actual) || !isSha256(expected)) return false; return timingSafeEqual(Buffer.from(actual, "hex"), Buffer.from(expected, "hex")); } function asRecord(value: unknown): Record | null { return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record) : null; }