173 lines
4.9 KiB
TypeScript
173 lines
4.9 KiB
TypeScript
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
|
|
const MAX_CLOCK_SKEW_MS = 5 * 60 * 1_000;
|
|
const MIN_SECRET_LENGTH = 32;
|
|
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/u;
|
|
const ALLOWED_EVENT_KEYS = new Set([
|
|
"adminUserId",
|
|
"scheduledEmailId",
|
|
"type",
|
|
"eventId",
|
|
"occurredAt",
|
|
"recipient",
|
|
"metadata",
|
|
]);
|
|
|
|
export type AdminEmailProviderEvent = {
|
|
readonly adminUserId: string;
|
|
readonly scheduledEmailId: string;
|
|
readonly type: "delivered" | "bounced";
|
|
readonly eventId: string;
|
|
readonly occurredAt: Date;
|
|
readonly recipient: string | null;
|
|
readonly metadata: Record<string, string | number | boolean | null> | null;
|
|
};
|
|
|
|
export function signAdminEmailProviderEvent(input: {
|
|
readonly body: string;
|
|
readonly timestamp: string;
|
|
readonly secret: string;
|
|
}): string {
|
|
validateSecret(input.secret);
|
|
return `sha256=${createHmac("sha256", input.secret)
|
|
.update(`${input.timestamp}.${input.body}`)
|
|
.digest("hex")}`;
|
|
}
|
|
|
|
export function verifyAdminEmailProviderEvent(input: {
|
|
readonly body: string;
|
|
readonly timestamp: string | null | undefined;
|
|
readonly signature: string | null | undefined;
|
|
readonly secret: string;
|
|
readonly now?: Date;
|
|
}):
|
|
| { readonly ok: true; readonly event: AdminEmailProviderEvent }
|
|
| {
|
|
readonly ok: false;
|
|
readonly reason:
|
|
| "not_configured"
|
|
| "invalid_signature"
|
|
| "expired"
|
|
| "invalid_payload";
|
|
} {
|
|
try {
|
|
validateSecret(input.secret);
|
|
} catch {
|
|
return { ok: false, reason: "not_configured" };
|
|
}
|
|
const timestampMs = Number(input.timestamp);
|
|
if (
|
|
!Number.isSafeInteger(timestampMs) ||
|
|
Math.abs((input.now ?? new Date()).getTime() - timestampMs) >
|
|
MAX_CLOCK_SKEW_MS
|
|
) {
|
|
return { ok: false, reason: "expired" };
|
|
}
|
|
const expected = Buffer.from(
|
|
signAdminEmailProviderEvent({
|
|
body: input.body,
|
|
timestamp: String(input.timestamp),
|
|
secret: input.secret,
|
|
})
|
|
);
|
|
const actual = Buffer.from(input.signature ?? "");
|
|
if (
|
|
expected.byteLength !== actual.byteLength ||
|
|
!timingSafeEqual(expected, actual)
|
|
) {
|
|
return { ok: false, reason: "invalid_signature" };
|
|
}
|
|
try {
|
|
const raw = JSON.parse(input.body) as Record<string, unknown>;
|
|
const type =
|
|
raw.type === "delivered" || raw.type === "bounced" ? raw.type : null;
|
|
const occurredAt = new Date(
|
|
typeof raw.occurredAt === "string" ? raw.occurredAt : ""
|
|
);
|
|
const metadata = normalizeMetadata(raw.metadata);
|
|
const adminUserId = normalizeIdentifier(raw.adminUserId);
|
|
const scheduledEmailId = normalizeIdentifier(raw.scheduledEmailId);
|
|
const eventId =
|
|
typeof raw.eventId === "string" &&
|
|
raw.eventId.trim().length > 0 &&
|
|
raw.eventId.trim().length <= 500 &&
|
|
!/[\u0000-\u001f\u007f]/u.test(raw.eventId)
|
|
? raw.eventId.trim()
|
|
: null;
|
|
const recipientIsValid =
|
|
raw.recipient === undefined ||
|
|
raw.recipient === null ||
|
|
typeof raw.recipient === "string";
|
|
if (
|
|
Object.keys(raw).some((key) => !ALLOWED_EVENT_KEYS.has(key)) ||
|
|
!adminUserId ||
|
|
!scheduledEmailId ||
|
|
!eventId ||
|
|
!type ||
|
|
Number.isNaN(occurredAt.getTime()) ||
|
|
!recipientIsValid ||
|
|
metadata === undefined
|
|
) {
|
|
return { ok: false, reason: "invalid_payload" };
|
|
}
|
|
return {
|
|
ok: true,
|
|
event: {
|
|
adminUserId,
|
|
scheduledEmailId,
|
|
type,
|
|
eventId,
|
|
occurredAt,
|
|
recipient:
|
|
typeof raw.recipient === "string"
|
|
? raw.recipient.trim().toLowerCase().slice(0, 320) || null
|
|
: null,
|
|
metadata,
|
|
},
|
|
};
|
|
} catch {
|
|
return { ok: false, reason: "invalid_payload" };
|
|
}
|
|
}
|
|
|
|
function normalizeIdentifier(value: unknown): string | null {
|
|
const normalized = typeof value === "string" ? value.trim() : "";
|
|
return IDENTIFIER_PATTERN.test(normalized) ? normalized : null;
|
|
}
|
|
|
|
function normalizeMetadata(
|
|
value: unknown
|
|
): Record<string, string | number | boolean | null> | null | undefined {
|
|
if (value === null || value === undefined) return null;
|
|
if (typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
const entries = Object.entries(value as Record<string, unknown>);
|
|
if (
|
|
entries.length > 20 ||
|
|
entries.some(
|
|
([key, entry]) =>
|
|
key.length > 80 ||
|
|
!/^[a-zA-Z0-9_.-]+$/u.test(key) ||
|
|
!(
|
|
entry === null ||
|
|
typeof entry === "string" ||
|
|
typeof entry === "number" ||
|
|
typeof entry === "boolean"
|
|
)
|
|
)
|
|
) {
|
|
return undefined;
|
|
}
|
|
return Object.fromEntries(
|
|
entries.map(([key, entry]) => [
|
|
key,
|
|
typeof entry === "string" ? entry.slice(0, 500) : entry,
|
|
])
|
|
) as Record<string, string | number | boolean | null>;
|
|
}
|
|
|
|
function validateSecret(secret: string): void {
|
|
if (Buffer.byteLength(secret, "utf8") < MIN_SECRET_LENGTH) {
|
|
throw new Error("admin_email_event_webhook_secret_too_short");
|
|
}
|
|
}
|