Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions telemetry-worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ genclass.dev/dashboard/<secret> --> dashboard page --GET /api/projects/<secret>?
| `GET /api/projects/<secret>?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/<secret>/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/<id>/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/<secret>/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/<secret>` | 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 |
Expand Down
11 changes: 11 additions & 0 deletions telemetry-worker/migrations/0024_unsubscribes.sql
Original file line number Diff line number Diff line change
@@ -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);
6 changes: 6 additions & 0 deletions telemetry-worker/src/collector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
146 changes: 146 additions & 0 deletions telemetry-worker/src/unsubscribe.ts
Original file line number Diff line number Diff line change
@@ -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`, `<style nonce="${nonce}">${ACCOUNT_CSS}${PAGE_CSS}</style><div class="auth">${LOGO}${inner}</div>`, "", { bare: true, account: true });
}

function formPage(nonce: string, o: { error?: string; typed?: string } = {}): string {
return barePage(
nonce,
"Unsubscribe",
`<h1>Unsubscribe</h1>
<p class="lead">Enter your email address and we will not write to you again.</p>
<form class="pwf un" method="post" action="/unsubscribe">
<div><label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" maxlength="254" placeholder="you@example.com" value="${esc(o.typed ?? "")}" required${o.error ? ' aria-describedby="un-err" aria-invalid="true"' : ""}></div>
${o.error ? `<p class="un-err" id="un-err" role="alert">${esc(o.error)}</p>` : ""}
<button class="btn prov green" type="submit"><span>Unsubscribe</span></button>
</form>
<p class="un-note">Reports from your own GenClass account are turned off with the link at the bottom of each report.</p>`,
);
}

const donePage = (nonce: string, email: string): string =>
barePage(nonce, "You are unsubscribed", `<h1>You are unsubscribed</h1>\n<p class="lead">We will not write to ${esc(email)} again.</p>`);

const failedPage = (nonce: string): string =>
barePage(
nonce,
"That did not save",
`<h1>That did not save</h1>\n<p class="lead">Something went wrong on our side. Write to <a href="mailto:${esc(RECOVERY_CONTACT)}?subject=Unsubscribe">${esc(RECOVERY_CONTACT)}</a> and we will take you off the list by hand.</p>`,
);

/** 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<string | Response> {
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<boolean> {
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<void> {
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: `<p>${esc(line)}</p>` });
} 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<Response | null> {
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));
}
Loading
Loading