Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

211 lines · 11.8 KBRaw History
1import { devAuth } from "../auth/dev.js";
2import type { Env } from "../env.js";
3import { b64url, fromB64url, hmacSha256Hex, now, safeEqual } from "../lib/util.js";
4import { hmacSha256, matchesAnyKey, signingSecrets } from "../lib/crypto.js";
5
6/**
7 * The suppression list: addresses Diffinery sends no email to at all, because mail to them
8 * bounced for good (`hard-bounce`), their owner reported an email as spam (`complaint`), or a
9 * site administrator added them (`manual`). deliver() in send.ts checks it before every send,
10 * sign-in links and account recovery included. The one exception is the verification email the
11 * address's owner asks for on Settings → Email: following its link lifts a bounce or complaint.
12 *
13 * Bounces and complaints come from Cloudflare Email Sending's Event Subscriptions (a queue,
14 * mail/events.ts), from a signed POST to /-/email/events for anything else, and from Email
15 * Sending's or the SMTP server's own answer to a send it refuses for good (sendSuppression, used by deliver()).
16 */
17
18export type SuppressionReason = "hard-bounce" | "complaint" | "manual";
19export const SUPPRESSION_REASONS: readonly SuppressionReason[] = ["hard-bounce", "complaint", "manual"];
20export type SuppressionSource = "cloudflare" | "webhook" | "send" | "admin";
21
22export interface Suppression {
23 email: string;
24 reason: SuppressionReason;
25 detail: string | null;
26 source: SuppressionSource;
27 created_by: string | null;
28 created_at: string;
29}
30
31/** Why an address is suppressed, in words that follow "Diffinery stopped sending to it because". */
32export const REASON_TEXT: Record<SuppressionReason, string> = {
33 "hard-bounce": "email to it bounced permanently",
34 complaint: "an email from Diffinery to it was reported as spam",
35 manual: "a site administrator suppressed it",
36};
37
38/** Longest detail kept, in characters. */
39export const MAX_DETAIL = 500;
40
41/** Addresses compare without case. */
42export const normalAddress = (email: string): string => email.trim().toLowerCase();
43
44/** Whether the address's owner may lift a suppression by verifying the address again (a manual one needs an administrator). */
45export const ownerCanLift = (s: Pick<Suppression, "reason">): boolean => s.reason !== "manual";
46
47const clip = (s: string | null | undefined): string | null => (s ? s.replace(/\s+/g, " ").trim().slice(0, MAX_DETAIL) || null : null);
48
49/** The suppression list in D1. */
50export class Suppressions {
51 constructor(private db: D1Database) {}
52
53 async get(email: string): Promise<Suppression | null> {
54 return this.db.prepare("SELECT * FROM email_suppressions WHERE email = ?").bind(normalAddress(email)).first<Suppression>();
55 }
56
57 /** Suppress an address; a newer event replaces an older one. */
58 async add(s: { email: string; reason: SuppressionReason; detail?: string | null; source: SuppressionSource; by?: string | null }): Promise<Suppression> {
59 const row: Suppression = { email: normalAddress(s.email), reason: s.reason, detail: clip(s.detail), source: s.source, created_by: s.by ?? null, created_at: now() };
60 await this.db
61 .prepare(
62 "INSERT INTO email_suppressions (email, reason, detail, source, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(email) DO UPDATE SET reason = excluded.reason, detail = excluded.detail, source = excluded.source, created_by = excluded.created_by, created_at = excluded.created_at",
63 )
64 .bind(row.email, row.reason, row.detail, row.source, row.created_by, row.created_at)
65 .run();
66 return row;
67 }
68
69 /** Remove an address from the list; the row that was there, or null. */
70 async remove(email: string): Promise<Suppression | null> {
71 return this.db.prepare("DELETE FROM email_suppressions WHERE email = ? RETURNING *").bind(normalAddress(email)).first<Suppression>();
72 }
73
74 async list(limit = 500): Promise<Suppression[]> {
75 return (await this.db.prepare("SELECT * FROM email_suppressions ORDER BY created_at DESC LIMIT ?").bind(Math.min(Math.max(limit, 1), 1000)).all<Suppression>()).results;
76 }
77}
78
79// ---------------------------------------------------------------- provider events
80
81/**
82 * What a provider event means for the list: a permanent (hard) bounce or a spam complaint
83 * suppresses the recipient; everything else (deliveries, soft bounces, deferrals) changes nothing.
84 *
85 * The shape is Cloudflare Email Sending's Event Subscriptions event: `type` ends in
86 * `message.bounced` or `message.complained`, and `payload` holds `recipient`, `bounce`
87 * (`type` hard or soft, `reason`) and `complaint`. The signed intake takes the same shape.
88 */
89export function suppressionFor(ev: unknown): { email: string; reason: Exclude<SuppressionReason, "manual">; detail: string | null } | null {
90 if (!ev || typeof ev !== "object") return null;
91 const e = ev as { type?: unknown; payload?: { recipient?: unknown; bounce?: { type?: unknown; reason?: unknown }; complaint?: { type?: unknown }; delivery?: { smtpResponse?: unknown } } };
92 const type = typeof e.type === "string" ? e.type : "";
93 const p = e.payload && typeof e.payload === "object" ? e.payload : null;
94 const to = typeof p?.recipient === "string" ? normalAddress(p.recipient) : "";
95 if (!p || !/^[^\s@]+@[^\s@]+$/.test(to) || to.length > 254) return null;
96 const str = (v: unknown) => (typeof v === "string" ? v : null);
97 if (type.endsWith("message.complained")) return { email: to, reason: "complaint", detail: clip(`Spam complaint${str(p.complaint?.type) ? ` (${str(p.complaint?.type)})` : ""}`) };
98 // A bounced event is permanent by definition; only an explicit soft one is left alone.
99 if (type.endsWith("message.bounced") && str(p.bounce?.type) !== "soft") return { email: to, reason: "hard-bounce", detail: clip(str(p.bounce?.reason) ?? str(p.delivery?.smtpResponse)) };
100 return null;
101}
102
103/**
104 * Error codes with which Email Sending's send() refuses a recipient for good: it is on Cloudflare's
105 * own suppression list (after a bounce or complaint there), so every later send fails the same way.
106 * Over SMTP (smtp.ts), E_SMTP_RECIPIENT_REJECTED: the server answered RCPT TO with a permanent
107 * "no such mailbox or domain". Everything else (rate limits, the daily limit, delivery and internal
108 * errors, a bad message or sender, a wrong SMTP password) is about the send, not the address, and
109 * changes nothing.
110 * https://developers.cloudflare.com/email-service/api/send-emails/workers-api/
111 */
112export const PERMANENT_SEND_CODES: ReadonlySet<string> = new Set(["E_RECIPIENT_SUPPRESSED", "E_SMTP_RECIPIENT_REJECTED"]);
113
114/**
115 * What Email Sending's answer to one send means for the list: a permanent failure for the
116 * recipient suppresses it as a hard bounce; anything else (sent, queued, temporary errors) is null.
117 * The answer is the error send() threw (`code`, `message`), or its result: the Workers binding
118 * returns only `messageId`, while the REST API also lists `permanent_bounces`, which counts too.
119 */
120export function sendSuppression(to: string, answer: { error?: unknown; result?: unknown }): { email: string; reason: "hard-bounce"; detail: string | null } | null {
121 const email = normalAddress(to);
122 if (!email) return null;
123 if (answer.error && typeof answer.error === "object") {
124 const e = answer.error as { code?: unknown; message?: unknown };
125 const code = typeof e.code === "string" ? e.code : "";
126 if (!PERMANENT_SEND_CODES.has(code)) return null;
127 return { email, reason: "hard-bounce", detail: clip(`${code.startsWith("E_SMTP_") ? "The SMTP server" : "Email Sending"} refused it: ${code}${typeof e.message === "string" && e.message ? `: ${e.message}` : ""}`) };
128 }
129 const r = answer.result && typeof answer.result === "object" ? (answer.result as { permanent_bounces?: unknown }) : null;
130 const bounced = Array.isArray(r?.permanent_bounces) ? r.permanent_bounces : [];
131 if (bounced.some((b) => typeof b === "string" && normalAddress(b) === email)) return { email, reason: "hard-bounce", detail: "Email Sending reported a permanent bounce when sending" };
132 return null;
133}
134
135type Audit = (e: { action: string; target?: string; detail?: unknown }) => Promise<void>;
136
137/** Apply provider events to the list, auditing each address suppressed. */
138export async function recordMailEvents(db: D1Database, audit: Audit, events: unknown[], source: Exclude<SuppressionSource, "admin">): Promise<{ suppressed: string[]; ignored: number }> {
139 const list = new Suppressions(db);
140 const suppressed: string[] = [];
141 for (const ev of events) {
142 const s = suppressionFor(ev);
143 if (!s) continue;
144 await list.add({ ...s, source });
145 await audit({ action: "email.suppression.add", target: s.email, detail: { reason: s.reason, source, detail: s.detail } });
146 suppressed.push(s.email);
147 }
148 return { suppressed, ignored: events.length - suppressed.length };
149}
150
151// ---------------------------------------------------------------- the signed intake
152
153/** How old a signed intake request may be, in seconds (either way, for clock skew). */
154export const SIGNATURE_TOLERANCE_S = 300;
155export const SIGNATURE_HEADER = "x-diffinery-signature";
156
157/** The signature header for a body: `t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">`. */
158export async function signEvents(secret: string, body: string, t = Math.floor(Date.now() / 1000)): Promise<string> {
159 return `t=${t},v1=${await hmacSha256Hex(secret, `${t}.${body}`)}`;
160}
161
162/** Whether a signature header is good for this body, and recent. */
163export async function checkSignature(secret: string, header: string | null | undefined, body: string, nowMs = Date.now()): Promise<boolean> {
164 if (!secret || !header || header.length > 1000) return false;
165 const parts = new Map(header.split(",").map((kv) => kv.trim().split("=", 2) as [string, string]));
166 const t = Number(parts.get("t"));
167 const v1 = parts.get("v1") ?? "";
168 if (!Number.isInteger(t) || !/^[0-9a-f]{64}$/.test(v1)) return false;
169 if (Math.abs(nowMs / 1000 - t) > SIGNATURE_TOLERANCE_S) return false;
170 return safeEqual(v1, await hmacSha256Hex(secret, `${t}.${body}`));
171}
172
173// ---------------------------------------------------------------- verifying an address again
174
175/** How long a verification link works. */
176export const VERIFY_HOURS = 24;
177/** Verification emails one account may ask for in an hour. */
178export const MAX_VERIFY_EMAILS_PER_HOUR = 3;
179
180export interface VerifyToken {
181 accountId: string;
182 email: string;
183 expiresAt: number;
184}
185
186function verifySecrets(env: Pick<Env, "MASTER_KEY" | "MASTER_KEY_PREV" | "DEV_AUTH" | "ACCESS_AUD" | "PUBLIC_URL">): string[] {
187 // Local development has no MASTER_KEY unless one is passed; production always does.
188 return signingSecrets(env, devAuth(env) ? "diffinery-dev-verify-email" : null, "MASTER_KEY is not set, so verification links can't be signed");
189}
190
191const signVerify = async (secret: string, payload: string): Promise<string> => b64url(await hmacSha256(`diffinery-verify-email-v1:${secret}`, payload));
192
193/** A signed link token: this account may lift the suppression on this address until it expires. */
194export async function verifyToken(env: Env, t: VerifyToken): Promise<string> {
195 const payload = b64url(new TextEncoder().encode(JSON.stringify({ a: t.accountId, e: normalAddress(t.email), x: t.expiresAt })));
196 return `${payload}.${await signVerify(verifySecrets(env)[0]!, payload)}`;
197}
198
199/** The token's contents when its signature is good and it hasn't expired; null otherwise. */
200export async function readVerifyToken(env: Env, token: string, nowMs = Date.now()): Promise<VerifyToken | null> {
201 const [payload, sig] = token.split(".");
202 if (!payload || !sig || token.length > 1000) return null;
203 if (!(await matchesAnyKey(verifySecrets(env), sig, (s) => signVerify(s, payload)))) return null;
204 try {
205 const v = JSON.parse(new TextDecoder().decode(fromB64url(payload))) as { a?: unknown; e?: unknown; x?: unknown };
206 if (typeof v.a !== "string" || typeof v.e !== "string" || typeof v.x !== "number" || v.x < nowMs) return null;
207 return { accountId: v.a, email: v.e, expiresAt: v.x };
208 } catch {
209 return null;
210 }
211}