From 8c861b1197ce77fdbcb38ecfdabcaf8a4eba6ffb Mon Sep 17 00:00:00 2001 From: Mehar Khanna Date: Thu, 19 Nov 2026 18:28:48 -0500 Subject: [PATCH] Collector: an unsubscribe page for email written by hand (genclass.dev/unsubscribe) A form with one field. A post saves the address (lower case) in a new table, unsubscribes (migration 0024), and answers the same whether or not it was already there. No sign-in; nothing is sent to the typed address; no account or report setting changes. A new address sends one notice to UNSUBSCRIBE_NOTIFY through the EMAIL binding, at most 50 a day. AUTH_LIMIT per network. The link in a signature was a mailto before. Co-Authored-By: Claude Fable 5.2 --- telemetry-worker/README.md | 1 + .../migrations/0024_unsubscribes.sql | 11 ++ telemetry-worker/src/collector.ts | 6 + telemetry-worker/src/unsubscribe.ts | 146 +++++++++++++++++ telemetry-worker/test/unsubscribe.test.ts | 154 ++++++++++++++++++ telemetry-worker/wrangler.toml | 5 + 6 files changed, 323 insertions(+) create mode 100644 telemetry-worker/migrations/0024_unsubscribes.sql create mode 100644 telemetry-worker/src/unsubscribe.ts create mode 100644 telemetry-worker/test/unsubscribe.test.ts diff --git a/telemetry-worker/README.md b/telemetry-worker/README.md index 928a7ab1..c12fd762 100644 --- a/telemetry-worker/README.md +++ b/telemetry-worker/README.md @@ -92,6 +92,7 @@ genclass.dev/dashboard/ --> dashboard page --GET /api/projects/? | `GET /api/projects/?range=24h\|7d\|30d` | dashboard stats JSON (every plan includes the dashboard; a plan file that left it out would answer 402 `{ ok:false, error, locked:true }`) (default `7d`): `name, token, created, lastEvent, range, from, generated, totals, breakdowns{metric: [{key,count}]}` (top 25 each; 200 for `detect_issue`, `possible_issue` and `check_issue`), `distinct{metric: n}` (distinct keys before that cut, e.g. pages with a problem), `series` (24 hourly or 7/30 daily buckets: sessions, decisions, detections, acted, possible, checks, ix_views, ix_sessions), `typeSeries` and `checkSeries` (per bucket, detections by diagnosis and measured checks by kind), `recent` (last 50 detections/interventions in the window; possible ones are not listed). `totals` also has `latencyAvgMs`, `modelLoadAvgMs`, `failOpens`, `modelErrors`, `interventions`, `actionLimits`, `detectionsWithPage`, `possibleWithPage` and `checksWithPage`. Apps that turned on interaction analytics (runtime `interactions` events, [docs/runtime/ANALYTICS.md](../docs/runtime/ANALYTICS.md)) also get `ix_views`, `ix_engaged_ms`, `ix_click`, `ix_rage` and `ix_dead` totals and breakdowns (by route, or route TAB element key; `ix_scroll` by route TAB milestone; top 200 each), counted with their own per-batch budget; and per visit `ix_sessions`, `ix_ref`, `ix_utm_source`, `ix_utm_medium`, `ix_utm_campaign`, `ix_device`, `ix_browser`, `ix_os`, `ix_country`, `ix_returning`, plus `visits` (`sessions, pages, bounces, entry[], exit[]` over the visits that started in the period) and `funnels` (`[{ name, steps, counts }]`; docs/runtime/ANALYTICS.md section 3.1); with navigation paths (ANALYTICS.md section 11) also `ix_entry` and `ix_exit` (totals and by route), `ix_nav` and `ix_nav_ms` (from TAB to), `ix_arrive` (by `nav`, and route TAB `nav`), `ix_first` (route TAB element key), `ix_first_n` and `ix_first_ms` (by route) and `ix_path` (the first 5 routes of a page load, joined with ` > `). 404 `{ ok:false, error:"not found" }` for an unknown or malformed secret. Same-origin only (no CORS). | | `PUT /api/projects//funnels` | body `{ funnels: [{ name, steps }] }` (application/json, at most 4 KB): replaces the app's funnels (at most 5, 2 to 6 routes each; a step ending in `*` matches every route under it). 200 `{ ok, funnels }`, 400 with the reason, 403 for the sample. Account mode: `PUT /api/account/projects//funnels` with the browser session and the site's Origin | | `GET /start` | "Get a token" page | +| `GET /unsubscribe`, `POST /unsubscribe` | the unsubscribe page for email a person at GenClass writes by hand, linked from their signature (`src/unsubscribe.ts`): a form with one field. A post (the form, or JSON `{ email }`) saves the address, lower case, in `unsubscribes` (migration 0024) and shows "You are unsubscribed"; the answer is the same for an address already there. No sign-in. Nothing is sent to the typed address, and no account or report setting changes (reports have their own signed link, `/api/report/unsubscribe`). A new address sends one notice to `UNSUBSCRIBE_NOTIFY` through the `EMAIL` binding, at most 50 a day. `AUTH_LIMIT` per network; 400 for something that is not an address, 503 with a contact when the table is missing | | `GET /start/open-source` | "Use GenClass without an account": the open-source parts only (the runtime, the agent link, the MCP server and the local page check, all Apache-2.0), with no account and no token to paste: the runtime's anonymous diagnostics stay on and `init` makes the app's free dashboard link (it sends the package name, nothing else, and keeps the link in `.genclass.local`); for teams that cannot sign up for a hosted dashboard. Choices (Guard and Heal, both ticked by default: the heal mode, `mode: "heal"`, `data-mode="heal"`, `init --mode heal`, both off observe; Findings in our own logs: the `console-json` sink; Serve the model ourselves: `fetch-model`; Nothing sent to genclass.dev: `telemetry: false`, `data-telemetry="off"` and `init --no-telemetry`, so no token and no dashboard link either, for teams that may send nothing; Deploy when done) rewrite one copied prompt (`openSourcePrompt`, run from its own source in the page, as `installPrompt` is); the page sends no request. Linked from `/start` and under the sign-in ways on `/login` and `/signup` | | `POST /api/projects//agent` | the MCP server's log of the closed loop, mirrored, when the developer sets `GENCLASS_REPORT` for `@genclass/mcp` (docs/runtime/AGENT.md section 4.5): `{ schema: "genclass-agent/1", events: [{ t: "found" \| "explain" \| "armed" \| "replay" \| "test" \| "explore" \| "cleared", at, id?, kind?, route?, reproduced?, runs?, races?, what? }] }`, at most 50 events and 16 KB a request, rate limited per token (`SESSION_LIMIT`). Every accepted event is one row of `agent_log` (at most 500 per app, the oldest go first; unknown types are dropped); the ones about a finding also update `agent_reports` (kind, normalised route, found, explained, last replay and verdict, how many replays reproduced it, tested, proven: a replay that stops reproducing after one that did). 90 days; the stats carry them as `agent` (`findings`, `counts`, `stages`: found, explained, reproduced, fixed, closed, open, continued; `log`, the last 50) and the dashboard's Closed-loop development view shows them. The sample and unknown secrets 404; other methods 405. Ids, kinds, routes, verdicts, counts and times only, never page text | | `GET /dashboard/` | the dashboard (for an app with no account too: it is on Free), in the Supabase Studio frame (`src/studio.ts`), in views the rail switches between: Project overview (the name and status, the summary, four stats, the problems chart, usage cards per hour or day, Get connected, the problems that need attention with a Copy prompt each and Fix them all, and Getting started until the first event), Problems (each kind with its pages, its fix and a Copy prompt for a coding agent; Fix them all copies one prompt for every kind and the dev page's checks, in which the agent says what to do on the page and waits for the loads itself), Pages and Actions, Activity, Visitors (without interaction data, under the copy-prompt button, the runtime analytics need, `ANALYTICS_RUNTIME` 0.3.0-beta.1, with the install line and the app's older versions from the `runtime` breakdown; the Connect dialog says the same), Health, MCP (the @genclass/mcp setup per coding agent, with GENCLASS_DASHBOARD set to the agent link, a Copy prompt, the tools, the JSON address), Closed loop (Closed-loop development: Fig. 3, every issue's path, found, reproduced, fix proven, closed, or round again, with the period's counts from the agent's reports; Table 15, the agent's log mirrored from `@genclass/mcp`; Fig. 6, the app's problems and what the agent does with each), Integrations (forwarding, account mode) and Project Settings (general, the key, agent access; Export in account mode). Problems, Visitors and Project Settings have Studio's product menu. The header's Connect opens the Connect dialog (also `#connect`); its Framework tab's prompt (`installPrompt`: the runtime, or the script tags of a site with no build step, the state in one atom per response, the agent link, the MCP server) follows the choices above it, Guard (and Heal, both ticked by default: the heal mode, `mode: "heal"`, `data-mode="heal"` and `init --mode heal`; guard alone is guard, both off observe), Badge on the live site, Connect my coding agent to production (makes the agent link, or names a private link) and Deploy when done, by running `installPrompt`'s own source in the page; the hash names the view (`#found`, `#recent-s`, `#mcp`); every data view copies as Markdown; and without the script every section shows. On a private link the page's own address is the agent link. With a plan file that left the dashboard out, the locked page (sign in, add the app to the account, see the plans; `src/locked.ts`). 404 page for an unknown secret; `GET /dashboard` redirects to `/start`. `/dashboard/sample` stays open | diff --git a/telemetry-worker/migrations/0024_unsubscribes.sql b/telemetry-worker/migrations/0024_unsubscribes.sql new file mode 100644 index 00000000..b3d7cc2d --- /dev/null +++ b/telemetry-worker/migrations/0024_unsubscribes.sql @@ -0,0 +1,11 @@ +-- The unsubscribe page (owner request, 2026-11-19; src/unsubscribe.ts): genclass.dev/unsubscribe, linked from the +-- signature of email a person at GenClass writes by hand. One row per address that asked for no more of that email. +-- Nothing else reads it: GenClass reports and alerts keep their own switch (accounts.report_every, migration 0020). +-- The sender checks this list before writing to anyone. Rows are kept for as long as GenClass sends such email: a +-- deleted row is an address that could be written to again. +-- (0023 is the partner API's number, pull request #242.) +CREATE TABLE IF NOT EXISTS unsubscribes ( + email TEXT PRIMARY KEY, -- as typed, trimmed and lower case + created TEXT NOT NULL -- ISO time of the first request +) WITHOUT ROWID; +CREATE INDEX IF NOT EXISTS unsubscribes_created ON unsubscribes (created); diff --git a/telemetry-worker/src/collector.ts b/telemetry-worker/src/collector.ts index 21c3ca75..61e36ab0 100644 --- a/telemetry-worker/src/collector.ts +++ b/telemetry-worker/src/collector.ts @@ -51,6 +51,7 @@ import { import { routeBilling } from "./billing.js"; import { routeTeam } from "./team-routes.js"; import { routeReport } from "./report-routes.js"; +import { routeUnsubscribe } from "./unsubscribe.js"; import type { EmailBinding } from "./report.js"; import type { GithubEnv } from "./github/config.js"; import { routeGithub } from "./github/http.js"; @@ -141,6 +142,8 @@ export interface Env extends GithubEnv { /** Cloudflare Email Sending (`[[send_email]]` in wrangler.toml): GenClass reports and alerts (src/report.ts). Without * it nothing is emailed and the report settings page says so. */ EMAIL?: EmailBinding; + /** Where a short notice goes when someone unsubscribes on /unsubscribe (src/unsubscribe.ts); none when unset. */ + UNSUBSCRIBE_NOTIFY?: string; /** Optional https URL that gets short JSON notices: a Custom purchase, a duplicate subscription, a plan switch * that needs a refund by hand, a billing record holding something that is not GenClass's. */ NOTIFY_WEBHOOK?: string; @@ -259,6 +262,9 @@ export async function handle(request: Request, env: Env, opts: HandleOptions = { // email reports (src/report-routes.ts): /account/report*, /api/account/report*, /api/report/*, before the account routes const report = await routeReport(request, url, path, env, opts); if (report) return report; + // the unsubscribe page for email written by hand (src/unsubscribe.ts): /unsubscribe + const unsubscribe = await routeUnsubscribe(request, path, env, opts); + if (unsubscribe) return unsubscribe; const account = await routeAuth(request, url, path, env, opts); if (account) return account; const site = await routeSite(request, url, path, env, opts); diff --git a/telemetry-worker/src/unsubscribe.ts b/telemetry-worker/src/unsubscribe.ts new file mode 100644 index 00000000..5e2b6d63 --- /dev/null +++ b/telemetry-worker/src/unsubscribe.ts @@ -0,0 +1,146 @@ +// The unsubscribe page for email a person at GenClass writes by hand (genclass.dev/unsubscribe, the link in their +// signature). GenClass reports and alerts are not turned off here: each of those carries its own link +// (src/report-routes.ts), which is signed for one account. +// +// GET /unsubscribe the form: an email address and one button +// POST /unsubscribe the form's post (or JSON { email }): the address is saved, and the page says so +// +// Invariants: +// - No sign-in and no link token: the link in a signature is the same for everyone, so the person types the address. +// - Nothing is ever sent to the typed address: a form anyone can fill must not be a way to mail a stranger. +// - The answer is the same for an address that was already on the list and one that was not. +// - The request does nothing else: no account, report setting or app is read or changed. +// - A new address sends one short notice to UNSUBSCRIBE_NOTIFY (when that and the EMAIL binding are set), at most +// NOTIFY_DAILY_CAP a day, so the form cannot fill that inbox. The row is saved either way. +// - AUTH_LIMIT per network, like the sign-in routes. + +import { ACCOUNT_CSS } from "./account-pages.js"; +import { cleanEmail, fail, page, RECOVERY_CONTACT } from "./auth.js"; +import type { Env, HandleOptions } from "./collector.js"; +import { sha256Hex } from "./dashboard.js"; +import { esc } from "./escape.js"; +import { json, mediaType, readCapped } from "./http.js"; +import { LOGO, shell } from "./pages.js"; +import { FROM } from "./report.js"; + +/** Notices to UNSUBSCRIBE_NOTIFY in one UTC day; past it the rows are still saved. */ +export const NOTIFY_DAILY_CAP = 50; +const MAX_BODY = 2048; + +const PAGE_CSS = ` +.un{display:grid;gap:14px;max-width:420px} +.un label{font-size:14px;font-weight:500} +.un-note{color:var(--ink3);font-size:13px;margin:0} +.un-err{color:var(--warn-f,#e5484d);font-size:14px;margin:0}`; + +function barePage(nonce: string, title: string, inner: string): string { + return shell(nonce, `${title} | GenClass`, `
${LOGO}${inner}
`, "", { bare: true, account: true }); +} + +function formPage(nonce: string, o: { error?: string; typed?: string } = {}): string { + return barePage( + nonce, + "Unsubscribe", + `

Unsubscribe

+

Enter your email address and we will not write to you again.

+
+
+
+ ${o.error ? `` : ""} + +
+

Reports from your own GenClass account are turned off with the link at the bottom of each report.

`, + ); +} + +const donePage = (nonce: string, email: string): string => + barePage(nonce, "You are unsubscribed", `

You are unsubscribed

\n

We will not write to ${esc(email)} again.

`); + +const failedPage = (nonce: string): string => + barePage( + nonce, + "That did not save", + `

That did not save

\n

Something went wrong on our side. Write to ${esc(RECOVERY_CONTACT)} and we will take you off the list by hand.

`, + ); + +/** The address a form post or a JSON body carries, as typed (a string, possibly not an email), or a response to send. */ +async function typedEmail(request: Request): Promise { + const raw = await readCapped(request, MAX_BODY); + if (raw === null) return fail(413, "body too large"); + const text = new TextDecoder().decode(raw); + if (mediaType(request) === "application/json") { + try { + const v: unknown = JSON.parse(text); + const e = v && typeof v === "object" ? (v as { email?: unknown }).email : undefined; + return typeof e === "string" ? e : ""; + } catch { + return ""; + } + } + return new URLSearchParams(text).get("email") ?? ""; +} + +async function overLimit(env: Env, request: Request): Promise { + const lim = env.AUTH_LIMIT; + if (!lim) return false; + const ip = request.headers.get("cf-connecting-ip") ?? "unknown"; + try { + return !(await lim.limit({ key: (await sha256Hex(`unsubscribe:${ip}`)).slice(0, 32) })).success; + } catch { + return false; // the limiter is best effort + } +} + +/** The notice for a newly saved address. Never throws; never mails the typed address. */ +async function notify(env: Env, email: string, now: Date): Promise { + const to = cleanEmail(env.UNSUBSCRIBE_NOTIFY); + if (!env.EMAIL || !env.DB || !to) return; + try { + const day = `${now.toISOString().slice(0, 10)}T00:00:00.000Z`; + const row = await env.DB.prepare("SELECT COUNT(*) AS n FROM unsubscribes WHERE created >= ?").bind(day).first<{ n: number }>(); + if ((row?.n ?? 0) > NOTIFY_DAILY_CAP) return; + const line = `${email} asked for no more email from GenClass (genclass.dev/unsubscribe, ${now.toISOString()}). Do not write to this address again.`; + await env.EMAIL.send({ to, from: FROM, subject: `Unsubscribe: ${email}`, text: line, html: `

${esc(line)}

` }); + } catch (e) { + const code = e && typeof e === "object" && "code" in e ? String((e as { code: unknown }).code).slice(0, 40) : "error"; + console.log(`unsubscribe: the notice was not sent (${code})`); + } +} + +/** The unsubscribe page's route. Returns null for any other path (the caller continues routing). */ +export async function routeUnsubscribe(request: Request, path: string, env: Env, opts: HandleOptions): Promise { + if (path !== "/unsubscribe") return null; + const m = request.method; + if (m === "GET" || m === "HEAD") return page(200, (n) => formPage(n)); + if (m !== "POST") return fail(405, "method not allowed", { allow: "GET, POST" }); + const wantsJson = mediaType(request) === "application/json"; + if (await overLimit(env, request)) { + if (wantsJson) return fail(429, "too many requests from your network; try again in a minute", { "retry-after": "60" }); + const r = page(429, (n) => formPage(n, { error: "Too many requests came from your network. Wait a minute, then try again." })); + r.headers.set("retry-after", "60"); + return r; + } + const typed = await typedEmail(request); + if (typed instanceof Response) return typed; + const email = cleanEmail(typed)?.toLowerCase() ?? null; + if (!email) { + if (wantsJson) return fail(400, "email must be an email address"); + return page(400, (n) => formPage(n, { error: "That does not look like an email address.", typed: typed.slice(0, 254) })); + } + const now = (opts.now ?? (() => new Date()))(); + let added = false; + try { + if (!env.DB) throw new Error("no database"); + added = !(await env.DB.prepare("SELECT 1 AS x FROM unsubscribes WHERE email = ?").bind(email).first<{ x: number }>()); + if (added) await env.DB.prepare("INSERT OR IGNORE INTO unsubscribes (email, created) VALUES (?, ?)").bind(email, now.toISOString()).run(); + } catch { + // no database, or migration 0024 not applied: say so, with a way to reach a person + return wantsJson ? fail(503, "unsubscribe is unavailable") : page(503, (n) => failedPage(n)); + } + if (added) { + const task = notify(env, email, now); + if (opts.waitUntil) opts.waitUntil(task); + else await task; + } + return wantsJson ? json(200, { ok: true }) : page(200, (n) => donePage(n, email)); +} diff --git a/telemetry-worker/test/unsubscribe.test.ts b/telemetry-worker/test/unsubscribe.test.ts new file mode 100644 index 00000000..3c0bda59 --- /dev/null +++ b/telemetry-worker/test/unsubscribe.test.ts @@ -0,0 +1,154 @@ +// The unsubscribe page for email written by hand (src/unsubscribe.ts, migration 0024): the form, what a post saves, +// the same answer twice, the notice (never to the typed address, capped a day), the limiter, and that nothing else +// about an account changes. +import { readFileSync } from "node:fs"; +import { beforeEach, describe, expect, it } from "vitest"; +import type { Env } from "../src/collector.js"; +import type { EmailMessage } from "../src/report.js"; +import { NOTIFY_DAILY_CAP } from "../src/unsubscribe.js"; +import { call, resetClock, setup, signedIn } from "./account-helpers.js"; + +function world(over: Partial = {}) { + const sent: EmailMessage[] = []; + const w = setup({ EMAIL: { async send(m: EmailMessage) { sent.push(m); return { messageId: `m${sent.length}` }; } }, UNSUBSCRIBE_NOTIFY: "sarah@genclass.dev", ...over }); + return { ...w, sent }; +} + +const FORM = { "content-type": "application/x-www-form-urlencoded" }; +const post = (env: Env, email: string, headers: Record = FORM) => call(env, "POST", "/unsubscribe", { body: `email=${encodeURIComponent(email)}`, headers, origin: null }); +const rows = (w: ReturnType) => w.sql.rows("SELECT email, created FROM unsubscribes ORDER BY email"); + +describe("the unsubscribe page (/unsubscribe)", () => { + beforeEach(() => { + resetClock(); + }); + + it("GET shows a form that posts an email address back to the page, and is not indexed", async () => { + const w = world(); + const r = await call(w.env, "GET", "/unsubscribe", { origin: null }); + expect(r.status).toBe(200); + expect(r.headers.get("content-type")).toContain("text/html"); + expect(r.headers.get("content-security-policy")).toContain("form-action 'self'"); + const html = await r.text(); + expect(html).toContain('
'); + expect(html).toContain('name="email" type="email"'); + expect(html).toContain("

Unsubscribe

"); + expect(rows(w)).toEqual([]); + }); + + it("a post saves the address in lower case and says so; a second post answers the same and adds nothing", async () => { + const w = world(); + const first = await post(w.env, " Ada@Example.COM "); + expect(first.status).toBe(200); + const html = await first.text(); + expect(html).toContain("You are unsubscribed"); + expect(html).toContain("ada@example.com"); + expect(rows(w)).toEqual([{ email: "ada@example.com", created: "2026-10-13T12:00:00.000Z" }]); + const again = await post(w.env, "ada@example.com"); + expect(again.status).toBe(200); + expect(await again.text()).toContain("You are unsubscribed"); + expect(rows(w)).toHaveLength(1); + }); + + it("the answer for a known address is the page a new one gets (apart from the nonce)", async () => { + const w = world(); + const strip = (s: string) => s.replace(/nonce="[^"]*"/g, 'nonce=""'); + const a = strip(await (await post(w.env, "ada@example.com")).text()); + const b = strip(await (await post(w.env, "ada@example.com")).text()); + expect(b).toBe(a); + }); + + it("something that is not an email address saves nothing and shows the form again with what was typed, escaped", async () => { + const w = world(); + for (const bad of ["", "not an address", "a@b", '">@x.io']) { + const r = await post(w.env, bad); + expect(r.status).toBe(400); + const html = await r.text(); + expect(html).toContain("That does not look like an email address."); + expect(html).not.toContain(""); + } + expect(rows(w)).toEqual([]); + expect(w.sent).toEqual([]); + }); + + it("a new address sends one notice to UNSUBSCRIBE_NOTIFY and nothing to the typed address; a repeat sends none", async () => { + const w = world(); + await post(w.env, "ada@example.com"); + await post(w.env, "ada@example.com"); + expect(w.sent).toHaveLength(1); + expect(w.sent[0]!.to).toBe("sarah@genclass.dev"); + expect(w.sent[0]!.from.email).toBe("report@genclass.dev"); + expect(w.sent[0]!.subject).toBe("Unsubscribe: ada@example.com"); + expect(w.sent[0]!.text).toContain("ada@example.com asked for no more email from GenClass"); + expect(w.sent.some((m) => m.to === "ada@example.com")).toBe(false); + }); + + it("no notice without UNSUBSCRIBE_NOTIFY or without the EMAIL binding, and the row is saved all the same", async () => { + const a = world({ UNSUBSCRIBE_NOTIFY: undefined }); + expect((await post(a.env, "ada@example.com")).status).toBe(200); + expect(a.sent).toEqual([]); + expect(rows(a)).toHaveLength(1); + const b = world({ EMAIL: undefined }); + expect((await post(b.env, "ada@example.com")).status).toBe(200); + expect(rows(b)).toHaveLength(1); + }); + + it("a notice that fails to send does not fail the request", async () => { + const w = world({ EMAIL: { async send() { throw Object.assign(new Error("refused"), { code: "E_REFUSED" }); } } }); + expect((await post(w.env, "ada@example.com")).status).toBe(200); + expect(rows(w)).toHaveLength(1); + }); + + it(`at most ${NOTIFY_DAILY_CAP} notices a day; later addresses are still saved`, async () => { + const w = world(); + for (let i = 0; i < NOTIFY_DAILY_CAP + 3; i++) expect((await post(w.env, `p${i}@example.com`)).status).toBe(200); + expect(w.sent).toHaveLength(NOTIFY_DAILY_CAP); + expect(rows(w)).toHaveLength(NOTIFY_DAILY_CAP + 3); + }); + + it("over the network's budget: 429 with Retry-After, nothing saved", async () => { + const w = world({ AUTH_LIMIT: { limit: async () => ({ success: false }) } }); + const r = await post(w.env, "ada@example.com"); + expect(r.status).toBe(429); + expect(r.headers.get("retry-after")).toBe("60"); + expect(rows(w)).toEqual([]); + }); + + it("JSON in, JSON out", async () => { + const w = world(); + const ok = await call(w.env, "POST", "/unsubscribe", { body: { email: "Ada@example.com" }, origin: null }); + expect(ok.status).toBe(200); + expect(await ok.json()).toEqual({ ok: true }); + expect(rows(w).map((r) => r.email)).toEqual(["ada@example.com"]); + const bad = await call(w.env, "POST", "/unsubscribe", { body: { email: 7 }, origin: null }); + expect(bad.status).toBe(400); + }); + + it("an account with that address keeps its report settings and its sign-in", async () => { + const w = world(); + const s = await signedIn(w.env, "ada@example.com"); + const before = w.sql.rows("SELECT * FROM accounts"); + expect((await post(w.env, "ada@example.com")).status).toBe(200); + expect(w.sql.rows("SELECT * FROM accounts")).toEqual(before); + expect((await call(w.env, "GET", "/api/me", { cookie: s.cookie })).status).toBe(200); + }); + + it("without the table (migration 0024 not applied) the page says it did not save and whom to write to", async () => { + const w = world(); + w.sql.db.exec("DROP TABLE unsubscribes"); + const r = await post(w.env, "ada@example.com"); + expect(r.status).toBe(503); + expect(await r.text()).toContain("mailto:mehar@genclass.dev?subject=Unsubscribe"); + expect(w.sent).toEqual([]); + }); + + it("other methods are refused, and other paths are not this route's", async () => { + const w = world(); + expect((await call(w.env, "DELETE", "/unsubscribe", { origin: null })).status).toBe(405); + expect((await call(w.env, "GET", "/unsubscribe/x", { origin: null })).status).toBe(404); + }); + + it("production routes genclass.dev/unsubscribe to the collector", () => { + expect(readFileSync(new URL("../wrangler.toml", import.meta.url), "utf8")).toMatch(/^\s*\{ pattern = "genclass\.dev\/unsubscribe\*", zone_name = "genclass\.dev" \},$/m); + }); +}); diff --git a/telemetry-worker/wrangler.toml b/telemetry-worker/wrangler.toml index 7f3ce462..bf9fc62c 100644 --- a/telemetry-worker/wrangler.toml +++ b/telemetry-worker/wrangler.toml @@ -23,6 +23,8 @@ routes = [ # The GitHub App (src/github/*): its public page, the page GitHub sends people to after installing, and "Connect # GitHub". Its webhook (/api/github/webhook) and the account page (/account/github) are under the routes above. { pattern = "genclass.dev/github*", zone_name = "genclass.dev" }, + # The unsubscribe page for email a person at GenClass writes by hand (src/unsubscribe.ts). + { pattern = "genclass.dev/unsubscribe*", zone_name = "genclass.dev" }, ] # Account settings. Production uses the defaults in src/auth.ts (AUTH_ORIGIN https://genclass.dev, AUTH_RP_ID @@ -37,6 +39,9 @@ routes = [ # (with RUNTIME_PKG). [vars] RUNTIME_ON_NPM = "0.3.0-beta.7" +# Where a one-line notice goes when someone unsubscribes on genclass.dev/unsubscribe (src/unsubscribe.ts): the inbox +# of whoever writes that email, so they see it before they write again. Unset: the row is saved and no notice is sent. +UNSUBSCRIBE_NOTIFY = "sarah@genclass.dev" # "on" sells the plans marked managed_payments in billing/plans.json through Stripe Managed Payments (Stripe, through # Link, is the merchant of record, for 3.5% of each payment on top of Stripe's fees). No plan is marked today # (Team is sold on standard Checkout), so it stays "off"; README "Paid plans".