227 lines
6.8 KiB
TypeScript
227 lines
6.8 KiB
TypeScript
import {
|
|
createHash,
|
|
createHmac,
|
|
randomBytes as nodeRandomBytes,
|
|
timingSafeEqual,
|
|
} from "node:crypto";
|
|
|
|
const BCC_VERSION = "b1";
|
|
const BCC_NONCE_BYTES = 8;
|
|
const BCC_SIGNATURE_BYTES = 16;
|
|
const MIN_SECRET_LENGTH = 32;
|
|
const ADMIN_ID_PATTERN = /^[A-Za-z0-9_-]{8,40}$/u;
|
|
const DOMAIN_PATTERN =
|
|
/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/u;
|
|
|
|
export type AdminBccCapability = {
|
|
readonly adminUserId: string;
|
|
readonly localPartHash: string;
|
|
readonly normalizedAddress: string;
|
|
};
|
|
|
|
export type AdminSendingDomainDnsResult = {
|
|
readonly spfStatus: "verified" | "missing" | "mismatch" | "error";
|
|
readonly dkimStatus: "verified" | "missing" | "mismatch" | "error";
|
|
readonly status: "verified" | "degraded";
|
|
};
|
|
|
|
export function createAdminBccCapability(input: {
|
|
readonly adminUserId: string;
|
|
readonly inboundDomain: string;
|
|
readonly secret: string;
|
|
readonly randomBytes?: (size: number) => Uint8Array;
|
|
}): AdminBccCapability {
|
|
const adminUserId = normalizeAdminId(input.adminUserId);
|
|
const inboundDomain = normalizeDomain(input.inboundDomain);
|
|
validateSecret(input.secret);
|
|
const nonce = Buffer.from(
|
|
(input.randomBytes ?? nodeRandomBytes)(BCC_NONCE_BYTES)
|
|
).toString("base64url");
|
|
const payload = `${BCC_VERSION}.${adminUserId}.${nonce}`;
|
|
const signature = signBccPayload(payload, input.secret);
|
|
const localPart = `${payload}.${signature}`;
|
|
if (Buffer.byteLength(localPart, "ascii") > 64) {
|
|
throw new AdminEmailDomainError("bcc_local_part_too_long");
|
|
}
|
|
const normalizedAddress = `${localPart}@${inboundDomain}`;
|
|
return Object.freeze({
|
|
adminUserId,
|
|
localPartHash: hashAdminBccLocalPart(localPart),
|
|
normalizedAddress,
|
|
});
|
|
}
|
|
|
|
export function verifyAdminBccCapability(input: {
|
|
readonly address: string;
|
|
readonly inboundDomain: string;
|
|
readonly secret: string;
|
|
}): AdminBccCapability | null {
|
|
try {
|
|
validateSecret(input.secret);
|
|
const normalizedAddress = normalizeAddress(input.address);
|
|
const expectedDomain = normalizeDomain(input.inboundDomain);
|
|
const separator = normalizedAddress.lastIndexOf("@");
|
|
if (separator <= 0 || normalizedAddress.slice(separator + 1) !== expectedDomain) {
|
|
return null;
|
|
}
|
|
const localPart = normalizedAddress.slice(0, separator);
|
|
const parts = localPart.split(".");
|
|
if (parts.length !== 4 || parts[0] !== BCC_VERSION) return null;
|
|
const adminUserId = normalizeAdminId(parts[1] ?? "");
|
|
const nonce = parts[2] ?? "";
|
|
const signature = parts[3] ?? "";
|
|
if (!/^[A-Za-z0-9_-]{11}$/u.test(nonce)) return null;
|
|
const payload = `${BCC_VERSION}.${adminUserId}.${nonce}`;
|
|
const expected = Buffer.from(signBccPayload(payload, input.secret));
|
|
const actual = Buffer.from(signature);
|
|
if (
|
|
expected.byteLength !== actual.byteLength ||
|
|
!timingSafeEqual(expected, actual)
|
|
) {
|
|
return null;
|
|
}
|
|
return Object.freeze({
|
|
adminUserId,
|
|
localPartHash: hashAdminBccLocalPart(localPart),
|
|
normalizedAddress,
|
|
});
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function hashAdminBccLocalPart(localPart: string): string {
|
|
return createHash("sha256")
|
|
.update(localPart.trim().toLowerCase())
|
|
.digest("hex");
|
|
}
|
|
|
|
export async function verifyAdminSendingDomainDns(input: {
|
|
readonly spfRecordName: string;
|
|
readonly spfExpectedValue: string;
|
|
readonly dkimRecordName: string;
|
|
readonly dkimExpectedValue: string;
|
|
readonly resolveTxt: (
|
|
hostname: string
|
|
) => Promise<readonly (readonly string[])[]>;
|
|
}): Promise<AdminSendingDomainDnsResult> {
|
|
const [spfStatus, dkimStatus] = await Promise.all([
|
|
verifyTxtRecord(
|
|
normalizeDnsName(input.spfRecordName),
|
|
normalizeTxtValue(input.spfExpectedValue),
|
|
input.resolveTxt
|
|
),
|
|
verifyTxtRecord(
|
|
normalizeDnsName(input.dkimRecordName),
|
|
normalizeTxtValue(input.dkimExpectedValue),
|
|
input.resolveTxt
|
|
),
|
|
]);
|
|
return Object.freeze({
|
|
spfStatus,
|
|
dkimStatus,
|
|
status:
|
|
spfStatus === "verified" && dkimStatus === "verified"
|
|
? "verified"
|
|
: "degraded",
|
|
});
|
|
}
|
|
|
|
async function verifyTxtRecord(
|
|
name: string,
|
|
expected: string,
|
|
resolveTxt: (
|
|
hostname: string
|
|
) => Promise<readonly (readonly string[])[]>
|
|
): Promise<AdminSendingDomainDnsResult["spfStatus"]> {
|
|
try {
|
|
const answers = await resolveTxt(name);
|
|
if (answers.length === 0) return "missing";
|
|
const normalized = answers.map((chunks) =>
|
|
normalizeTxtValue(chunks.join(""))
|
|
);
|
|
return normalized.includes(expected) ? "verified" : "mismatch";
|
|
} catch (error) {
|
|
return isDnsNotFound(error) ? "missing" : "error";
|
|
}
|
|
}
|
|
|
|
function signBccPayload(payload: string, secret: string): string {
|
|
return createHmac("sha256", secret)
|
|
.update(payload)
|
|
.digest()
|
|
.subarray(0, BCC_SIGNATURE_BYTES)
|
|
.toString("base64url");
|
|
}
|
|
|
|
function normalizeAdminId(value: string): string {
|
|
const normalized = value.trim();
|
|
if (!ADMIN_ID_PATTERN.test(normalized)) {
|
|
throw new AdminEmailDomainError("invalid_admin_user_id");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeDomain(value: string): string {
|
|
const normalized = value.trim().toLowerCase().replace(/\.$/u, "");
|
|
if (!DOMAIN_PATTERN.test(normalized)) {
|
|
throw new AdminEmailDomainError("invalid_domain");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeDnsName(value: string): string {
|
|
const normalized = value.trim().toLowerCase().replace(/\.$/u, "");
|
|
if (
|
|
normalized.length > 253 ||
|
|
!/^(?:[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?\.)+[a-z0-9_][a-z0-9_-]{0,62}$/u.test(
|
|
normalized
|
|
)
|
|
) {
|
|
throw new AdminEmailDomainError("invalid_domain");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeAddress(value: string): string {
|
|
const trimmed = value.trim();
|
|
if (
|
|
trimmed.length > 320 ||
|
|
/[\u0000-\u001f\u007f\s]/u.test(trimmed)
|
|
) {
|
|
throw new AdminEmailDomainError("invalid_bcc_address");
|
|
}
|
|
const separator = trimmed.lastIndexOf("@");
|
|
if (separator <= 0) throw new AdminEmailDomainError("invalid_bcc_address");
|
|
return `${trimmed.slice(0, separator)}@${trimmed
|
|
.slice(separator + 1)
|
|
.toLowerCase()}`;
|
|
}
|
|
|
|
function normalizeTxtValue(value: string): string {
|
|
const normalized = value.trim().replace(/^"(.*)"$/u, "$1");
|
|
if (!normalized || normalized.length > 4_096) {
|
|
throw new AdminEmailDomainError("invalid_dns_record");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function validateSecret(secret: string): void {
|
|
if (Buffer.byteLength(secret, "utf8") < MIN_SECRET_LENGTH) {
|
|
throw new AdminEmailDomainError("bcc_secret_not_configured");
|
|
}
|
|
}
|
|
|
|
function isDnsNotFound(error: unknown): boolean {
|
|
if (!error || typeof error !== "object") return false;
|
|
const code = "code" in error ? String(error.code) : "";
|
|
return ["ENODATA", "ENOTFOUND", "ENODOMAIN", "NXDOMAIN"].includes(code);
|
|
}
|
|
|
|
export class AdminEmailDomainError extends Error {
|
|
constructor(readonly code: string) {
|
|
super(code);
|
|
this.name = "AdminEmailDomainError";
|
|
}
|
|
}
|