Public: anyone can read this; the crew can change it.

Crash reports from the Apple app are kept and shown to the app's owner #18018

opened this in answer to

Parked 1h 11m ago

mason/forge:mason/18006-crash-reports-from-the-apple-app-are-kep → main 6 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
16 files changed +602 −20
docs/features/apple-usage.md +15
@@ -16,4 +16,19 @@ People opt in once in the forge Apple app (and can change it in its Settings). W
1616 - **Read it:** a site admin opens `/admin/telemetry` (`src/web/pages/admin-telemetry.ts`, linked from Limits; the last 14 days: summaries a day, and per version the counts and the p50 and p90 of the summaries' own timings: a p50 there is the middle of the devices' daily p50s) or `App usage` in the terminal (`src/tui/screens/appleusage.ts`). Both read `readAppleUsage` in `src/actions/apple_usage.ts`.
1717 - **Other forges:** a person signed in to their own forge sends to that forge only. Nothing is forwarded.
1818
19 ## Crash reports (#18006)
20
21 When a person chooses to send one after a crash, the app posts a report to the same route (`kind: "crash"`, no token), and only to the forge they are signed in to.
22
23 ```json
24 {"v":1,"kind":"crash","app":{"version":"0.1","build":"34"},"os":"iOS 26.1","device":"iPhone","at":"2026-12-03T12:00:09Z",
25 "previousRun":{"launchedAt":"2026-12-03T12:00:00Z","breadcrumbs":["12:00:01 tab repos"]},
26 "findings":[{"kind":"crash","date":"...","signal":"5","exception":"6","termination":"Namespace SIGNAL","version":"0.1","frames":["Forge +1445064","SwiftUI +7"]}]}
27 ```
28
29 - **Strict:** an unknown field or a wrong type is a 400 naming it; at most 200 breadcrumb lines, 12 frames a finding and 10 findings; a longer line is cut. 64 KB a body (413 above), 5 a minute from one address. Answers 204. No address, account or device id is kept.
30 - **Kept:** in `apple_crash_group` (`src/core/apple_crash.ts`), apart from the usage rows: reports with the same build and top three frames are one group with a count and the latest report's detail; 200 groups at most: once 200 exist, a report of a new group is not kept, while a report of a known group still counts. Nothing is deleted on its own.
outdated

This says the least recently seen group goes first at 200, but src/core/apple_crash.ts never evicts: a report of a new group is dropped at the cap. Correct the sentence to match.

31 - **Told:** a group's first report wakes the notifier (`apple.crash_group`), and each admin with a notification URL is told once per group (`crashLines` in `src/actions/apple_crash.ts`), never per report.
32 - **Read it:** the same page and terminal screen as above, newest group first with its frames and breadcrumbs (`readAppleCrashes`). `/privacy` says what a report holds.
33
1934 Not done: a switch for the owner to refuse summaries (the app stays dormant until the route answers 2xx), and the MetricKit payload is not kept.
src/actions/apple_crash.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * The Apple app's crash reports (#18006) in the forge: keeping one (which tells the notifier when
3 * it opens a new group) and reading them for a forge admin, the one gate the page
4 * (/admin/telemetry), the terminal screen and the notifier's lines share. Anyone else, an agent
5 * included, is told the same as for a page that is not there.
6 */
7
8 import type { App } from "../app.ts";
9 import { type CrashGroup, type CrashReport, readCrashGroups, recordCrash } from "../core/apple_crash.ts";
10 import type { User } from "../core/users.ts";
11 import { mayReadApple } from "./apple_usage.ts";
12
13 /** How long a new group is news to the notifier. */
14 const NEWS_MS = 7 * 86_400_000;
15
16 /** Keep a report. A group's first report is an event the notifier wakes on; later ones are not. */
17 export function keepCrash(app: App, report: CrashReport): void {
18 const first = recordCrash(app.db, report);
19 if (first !== undefined) app.bus.append({ kind: "apple.crash_group", payload: { group: first } });
20 }
21
22 export function readAppleCrashes(app: App, user: User | null | undefined): { ok: true; value: CrashGroup[] } | { ok: false; error: "not_found" } {
23 if (!mayReadApple(user)) return { ok: false, error: "not_found" };
24 return { ok: true, value: readCrashGroups(app.db) };
25 }
26
27 /**
28 * What the notifier says for an admin: one line for all the groups first seen this week, never one
29 * per report or per group. A group is kept for good (`recordCrash` never deletes one), so the same
30 * build and frames are told once; the line's items are the groups, so a new group is news once.
31 */
32 export function crashLines(app: App, user: User, now: number = Date.now()): { line: string; items: readonly string[]; link: string }[] {
33 if (!mayReadApple(user) || user.kind !== "user") return [];
34 const since = new Date(now - NEWS_MS).toISOString();
35 const fresh = readCrashGroups(app.db).filter((g) => g.firstSeen >= since);
36 if (fresh.length === 0) return [];
37 const first = fresh[0]!;
38 const line =
39 fresh.length === 1
40 ? `New crash in the Apple app ${first.build}: ${first.top[0] ?? "no frames"}`
41 : `${fresh.length} new crashes in the Apple app, latest ${first.build}: ${first.top[0] ?? "no frames"}`;
42 return [{ line, items: fresh.map((g) => `crash:${g.id}`), link: "/admin/telemetry" }];
43 }
src/actions/apple_usage.ts +4 −1
@@ -10,7 +10,10 @@ import type { User } from "../core/users.ts";
1010
1111 export const USAGE_DAYS = 14;
1212
13 /** A forge admin who is a person: the only reader of anything the Apple app sent. */
14 export const mayReadApple = (user: User | null | undefined): user is User => user?.isAdmin === true && user.kind !== "agent";
15
1316 export function readAppleUsage(app: App, user: User | null | undefined): { ok: true; value: UsageRead } | { ok: false; error: "not_found" } {
14 if (user?.isAdmin !== true || user.kind === "agent") return { ok: false, error: "not_found" };
17 if (!mayReadApple(user)) return { ok: false, error: "not_found" };
1518 return { ok: true, value: readUsage(app.db, USAGE_DAYS) };
1619 }
src/contract/openapi/routes/postApiV1TelemetryApple.ts +9 −4
@@ -3,12 +3,17 @@ import type { Route } from "../shared.ts";
33 export const route: Route = {
44 method: "post",
55 path: "/api/v1/telemetry/apple",
6 summary: "The Apple app's anonymous daily usage summary; open to signed-out callers",
7 detail: "Body `{v: 1, day: \"YYYY-MM-DD\", app: {version, build}, os, device, counts: {name: whole number}, timings: {name: ms}, metrickit?: {}}`. Nothing about the sender is kept: no account, address or device id. `os` and `metrickit` are checked and dropped. At most 8 KB and 10 summaries a minute from one address. Answers 204.",
6 summary: "The Apple app's daily usage summary or crash report; open to signed-out callers",
7 detail: "Body `{v: 1, day: \"YYYY-MM-DD\", app: {version, build}, os, device, counts: {name: whole number}, timings: {name: ms}, metrickit?: {}}`. Nothing about the sender is kept: no account, address or device id. `os` and `metrickit` are checked and dropped. At most 8 KB and 10 summaries a minute from one address. A body with `kind: \"crash\"` is a crash report, sent only when the user chooses: `{v: 1, kind: \"crash\", app: {version, build}, os, device: iPhone|iPad|Mac, at, previousRun?: {launchedAt, breadcrumbs: up to 200 lines}, findings?: [{kind: crash|hang|cpu|disk, date?, signal?, exception?, termination?, version?, frames: up to 12}]}`. It is strict: an unknown field or a wrong type is a 400 naming it. At most 64 KB (413 above) and 5 reports a minute from one address. Reports with the same build and top frames are grouped with a count for the forge owner. No address is stored. Answers 204.",
88 auth: false,
99 role: "anonymous",
1010 status: 204,
11 body: { v: "integer", day: "string", app: "object", os: "string", device: "string", counts: "object?", timings: "object?", metrickit: "object?" },
12 refusals: { invalid_body: "the body is not a JSON object (422)", invalid_v: "v is not 1 (422)", invalid_day: "day is not a UTC date from two days ago to tomorrow (422)", invalid_app: "app is not {version, build} (422)", invalid_os: "os is not a string of 1 to 40 characters (422)", invalid_device: "device is not a string of 1 to 20 characters (422)", invalid_counts: "counts holds more than 64 names, a malformed name or a value that is not a whole number up to a billion (422)", invalid_timings: "timings holds more than 64 names, a malformed name or a value that is not 0 to 86400000 ms (422)", invalid_metrickit: "metrickit is not an object (422)", too_large: "the body is over 8 KB (413)", rate_limited: "429: too many summaries from one address or in all" },
11 body: { v: "integer", kind: "string?", day: "string?", app: "object", os: "string", device: "string", at: "string?", previousRun: "object?", findings: "array?", counts: "object?", timings: "object?", metrickit: "object?" },
12 refusals: { invalid_body: "the body is not a JSON object (422)", invalid_v: "v is not 1 (422)", invalid_day: "day is not a UTC date from two days ago to tomorrow (422)", invalid_app: "app is not {version, build} (422)", invalid_os: "os is not a string of 1 to 40 characters (422)", invalid_device: "device is not a string of 1 to 20 characters (422)", invalid_counts: "counts holds more than 64 names, a malformed name or a value that is not a whole number up to a billion (422)", invalid_timings: "timings holds more than 64 names, a malformed name or a value that is not 0 to 86400000 ms (422)", invalid_metrickit: "metrickit is not an object (422)", invalid_crash: "a crash report (kind crash) has a field that is not named, a wrong type, or too many lines or frames (400)", too_large: "a summary is over 8 KB or a crash report over 64 KB (413)", rate_limited: "429: too many summaries from one address or in all" },
1313 refuses: [422],

refuses: [422] omits the 400 (invalid_crash) and 413 this change adds. Declare them, and contract-test the crash path.

14 errorStatus: {
15 400: "`invalid_crash`: a crash report (kind `crash`) has a field that is not named, a wrong type, or too many lines or frames; `message` names it",
16 413: "`too_large`: a summary is over 8 KB or a crash report over 64 KB",
17 429: "`rate_limited`: too many summaries or crash reports from one address or in all",
18 },
1419 };
src/core/apple_crash.ts added +202
@@ -0,0 +1,202 @@
1 /**
2 * The Apple app's crash reports (#18006): what is accepted, what is kept and how it reads.
3 *
4 * A report is sent only when the person chooses. It holds the app's version and build, the OS
5 * string, the device kind, when it was sent, the previous run's launch time and breadcrumb lines,
6 * and findings (kind, date, signal, exception, termination, version, frames). Nothing about who
7 * sent it is ever an argument here: no account, no address, no device id.
8 *
9 * Reports with the same build and the same top frames (`TOP_FRAMES` of the first finding) are one
10 * group: a count, when the first and the latest came, and the latest one's detail. At most
11 * `MAX_GROUPS` groups are kept: once that many exist a report of a new group is not kept, while one
12 * of a known group still counts. Nothing is deleted behind the owner's back. The shape is strict: a
13 * field that is not named, a wrong type, or more than `MAX_BREADCRUMBS` lines or `MAX_FRAMES`
14 * frames is refused in words; a line longer than `LINE_MAX` is cut.
15 */
16
17 import type { Database } from "bun:sqlite";
18
19 export const CRASH_SCHEMA = 1;
20 export const MAX_BREADCRUMBS = 200;
21 export const MAX_FRAMES = 12;
22 export const MAX_FINDINGS = 10;
23 export const MAX_GROUPS = 200;
24 const TOP_FRAMES = 3;
25 const LINE_MAX = 200;
26 const VERSION = /^\d{1,4}(\.\d{1,4}){0,3}$/;
27 const BUILD = /^[0-9A-Za-z.]{1,16}$/;
28 const DEVICES = new Set(["iPhone", "iPad", "Mac"]);
29 const FINDING_KINDS = new Set(["crash", "hang", "cpu", "disk"]);
30
31 export interface CrashFinding {
32 readonly kind: string;
33 readonly date: string;
34 readonly signal: string;
35 readonly exception: string;
36 readonly termination: string;
37 readonly version: string;
38 readonly frames: readonly string[];
39 }
40 export interface CrashReport {
41 /** `0.1 (34)`: the version and its build. */
42 readonly build: string;
43 readonly os: string;
44 readonly device: string;
45 readonly at: string;
46 readonly launchedAt: string;
47 readonly breadcrumbs: readonly string[];
48 readonly findings: readonly CrashFinding[];
49 }
50
51 const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
52 // eslint-disable-next-line no-control-regex
53 const clean = (s: string): string => s.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, LINE_MAX);
54
55 type Parsed<T> = { ok: true; value: T } | { ok: false; message: string };
56 const fail = (message: string): { ok: false; message: string } => ({ ok: false, message });
57
58 /** Only these keys; the first one that is not named is the refusal. */
59 function onlyKeys(o: Record<string, unknown>, allowed: readonly string[], where: string): string | undefined {
60 const extra = Object.keys(o).find((k) => !allowed.includes(k));
61 return extra === undefined ? undefined : `${where} has a field that is not part of a crash report: ${clean(extra).slice(0, 40)}`;
62 }
63
64 function text(v: unknown, where: string, max = 40, optional = false): Parsed<string> {
65 if (v === undefined && optional) return { ok: true, value: "" };
66 if (typeof v !== "string" || v.length < 1 || v.length > max) return fail(`${where} is a string of 1 to ${max} characters`);
67 return { ok: true, value: clean(v) };
68 }
69
70 function lines(v: unknown, where: string, max: number): Parsed<string[]> {
71 if (v === undefined) return { ok: true, value: [] };
72 if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) return fail(`${where} is a list of strings`);
73 if (v.length > max) return fail(`${where} holds at most ${max} lines`);
74 return { ok: true, value: v.map((x: string) => clean(x)) };
75 }
76
77 function finding(v: unknown, i: number): Parsed<CrashFinding> {
78 const where = `findings[${i}]`;
79 if (!isObject(v)) return fail(`${where} is an object`);
80 const extra = onlyKeys(v, ["kind", "date", "signal", "exception", "termination", "version", "frames"], where);
81 if (extra !== undefined) return fail(extra);
82 if (typeof v.kind !== "string" || !FINDING_KINDS.has(v.kind)) return fail(`${where}.kind is crash, hang, cpu or disk`);
83 const strings: Record<string, string> = {};
84 for (const [k, max] of [["date", 40], ["signal", 16], ["exception", 16], ["termination", 120], ["version", 16]] as const) {
85 const t = text(v[k], `${where}.${k}`, max, true);
86 if (!t.ok) return t;
87 strings[k] = t.value;
88 }
89 const frames = lines(v.frames, `${where}.frames`, MAX_FRAMES);
90 if (!frames.ok) return frames;
91 return {
92 ok: true,
93 value: {
94 kind: v.kind,
95 date: strings.date!,
96 signal: strings.signal!,
97 exception: strings.exception!,
98 termination: strings.termination!,
99 version: strings.version!,
100 frames: frames.value,
101 },
102 };
103 }
104
105 /** Whether a body says it is a crash report; the route's fork between this and a usage summary. */
106 export const isCrash = (input: unknown): boolean => isObject(input) && input.kind === "crash";
107
108 /** A body, read at the boundary: the report to keep, or the first thing wrong with it, in words. */
109 export function parseCrash(input: unknown): Parsed<CrashReport> {
110 if (!isObject(input)) return fail("the body is a JSON object");
111 const extra = onlyKeys(input, ["v", "kind", "app", "os", "device", "at", "previousRun", "findings"], "the report");
112 if (extra !== undefined) return fail(extra);
113 if (input.v !== CRASH_SCHEMA) return fail(`v is ${CRASH_SCHEMA}`);
114 const app = input.app;
115 if (!isObject(app)) return fail("app is {version, build}");
116 const appExtra = onlyKeys(app, ["version", "build"], "app");
117 if (appExtra !== undefined) return fail(appExtra);
118 const build = typeof app.build === "number" ? String(app.build) : app.build;
119 if (typeof app.version !== "string" || !VERSION.test(app.version) || typeof build !== "string" || !BUILD.test(build)) {
120 return fail("app is {version, build}: a dotted number and a short build");
121 }
122 const os = text(input.os, "os");
123 if (!os.ok) return os;
124 if (typeof input.device !== "string" || !DEVICES.has(input.device)) return fail("device is iPhone, iPad or Mac");
125 const at = text(input.at, "at");
126 if (!at.ok) return at;
127 let launchedAt = "";
128 let breadcrumbs: string[] = [];
129 if (input.previousRun !== undefined) {
130 const p = input.previousRun;
131 if (!isObject(p)) return fail("previousRun is {launchedAt, breadcrumbs}");
132 const pe = onlyKeys(p, ["launchedAt", "breadcrumbs"], "previousRun");
133 if (pe !== undefined) return fail(pe);
134 const l = text(p.launchedAt, "previousRun.launchedAt", 40, true);
135 if (!l.ok) return l;
136 launchedAt = l.value;
137 const b = lines(p.breadcrumbs, "previousRun.breadcrumbs", MAX_BREADCRUMBS);
138 if (!b.ok) return b;
139 breadcrumbs = b.value;
140 }
141 const rawFindings = input.findings ?? [];
142 if (!Array.isArray(rawFindings)) return fail("findings is a list");
143 if (rawFindings.length > MAX_FINDINGS) return fail(`findings holds at most ${MAX_FINDINGS}`);
144 const findings: CrashFinding[] = [];
145 for (const [i, f] of rawFindings.entries()) {
146 const one = finding(f, i);
147 if (!one.ok) return one;
148 findings.push(one.value);
149 }
150 return {
151 ok: true,
152 value: { build: `${app.version} (${build})`, os: os.value, device: input.device, at: at.value, launchedAt, breadcrumbs, findings },
153 };
154 }
155
156 const topOf = (r: CrashReport): string[] => (r.findings[0]?.frames ?? []).slice(0, TOP_FRAMES);
157
158 /** Keep one report in its group; the group's id when it is the group's first, else undefined. */
159 export function recordCrash(db: Database, r: CrashReport, now: Date = new Date()): string | undefined {
160 const top = topOf(r);
161 const id = new Bun.CryptoHasher("sha256").update(JSON.stringify([r.build, top])).digest("hex").slice(0, 16);
162 const stamp = now.toISOString();
163 const run = db.transaction((): boolean => {
164 const known = db.query<{ id: string }, [string]>("SELECT id FROM apple_crash_group WHERE id = ?1").get(id) !== null;
165 if (!known && db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM apple_crash_group").get()!.n >= MAX_GROUPS) return false;
166 db.query(
167 `INSERT INTO apple_crash_group (id, build, top, n, first_seen, last_seen, latest) VALUES (?1, ?2, ?3, 1, ?4, ?4, ?5)
168 ON CONFLICT (id) DO UPDATE SET n = n + 1, last_seen = ?4, latest = ?5`,
169 ).run(id, r.build, JSON.stringify(top), stamp, JSON.stringify(r));
170 return !known;
171 });
172 return run() ? id : undefined;
173 }
174
175 export interface CrashGroup {
176 readonly id: string;
177 readonly build: string;
178 readonly top: readonly string[];
179 readonly n: number;
180 readonly firstSeen: string;
181 readonly lastSeen: string;
182 /** The latest report in the group. */
183 readonly latest: CrashReport;
184 }
185
186 /** The groups, the most recently seen first. */
187 export function readCrashGroups(db: Database, limit = MAX_GROUPS): CrashGroup[] {
188 return db
189 .query<{ id: string; build: string; top: string; n: number; first_seen: string; last_seen: string; latest: string }, [number]>(
190 "SELECT * FROM apple_crash_group ORDER BY last_seen DESC LIMIT ?1",
191 )
192 .all(limit)
193 .map((r) => ({
194 id: r.id,
195 build: r.build,
196 top: JSON.parse(r.top) as string[],
197 n: r.n,
198 firstSeen: r.first_seen,
199 lastSeen: r.last_seen,
200 latest: JSON.parse(r.latest) as CrashReport,
201 }));
202 }
src/core/event_audience.ts +3
@@ -259,6 +259,9 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
259259 kind.startsWith("secret.") ||
260260 // The forge's mail ceiling is its owner's to hear (`actions/mail.ts`).
261261 kind.startsWith("mail.") ||
262 // A new group of the Apple app's crash reports is the forge owner's to hear
263 // (`actions/apple_crash.ts`).
264 kind === "apple.crash_group" ||
262265 // A restore drill's verdict is the forge owner's (`snapshot/service.ts`).
263266 kind.startsWith("drill.") ||
264267 // Which machines take this forge's checks is its admin's (`actions/runners.ts`).
src/core/migration-pins/20261204025950-apple-crash.pin added +1
@@ -0,0 +1,1 @@
1 50913d596f6129c250c402031a0901cfbb7a6e1318ff498f11f42acd160e28c1
src/core/migrations/20261204025950-apple-crash.ts added +16
@@ -0,0 +1,16 @@
1 // The Apple app's crash reports (#18006), kept apart from the daily usage rows: one row per group,
2 // reports with the same build and top frames, with how many came and the latest one's detail.
3 // No account, address or device identifier is a column. Bounded by `recordCrash`
4 // (src/core/apple_crash.ts). Additive: a new table.
5 export default `
6 CREATE TABLE IF NOT EXISTS apple_crash_group (
7 id TEXT NOT NULL PRIMARY KEY,
8 build TEXT NOT NULL,
9 top TEXT NOT NULL,
10 n INTEGER NOT NULL DEFAULT 1,
11 first_seen TEXT NOT NULL,
12 last_seen TEXT NOT NULL,
13 latest TEXT NOT NULL
14 ) WITHOUT ROWID;
15 CREATE INDEX IF NOT EXISTS apple_crash_group_last ON apple_crash_group (last_seen DESC);
16 `;
src/crew/notify.ts +4
@@ -24,6 +24,7 @@ import { watchNeeds } from "../cloud/watch.ts";
2424 import { blockedLines } from "../actions/egress_refused.ts";
2525 import { scheduleLines } from "../actions/schedules.ts";
2626 import { newAccountLines } from "../actions/accounts.ts";
27 import { crashLines } from "../actions/apple_crash.ts";
2728 import { contributorLines } from "../actions/invites.ts";
2829 import { requestLines } from "../actions/requests.ts";
2930 import { mailCeilingLines } from "../actions/mail.ts";
@@ -87,6 +88,8 @@ const WAKES = new Set([
8788 "app.egress.refused",
8889 "app.egress.ignored",
8990 "app.egress.allowed",
91 // The Apple app's first crash report of a new group (#18006).
92 "apple.crash_group",
9093 ]);
9194
9295 export type NotifyUrlError =
@@ -553,6 +556,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
553556 ...blockedLines(app, user, now()),
554557 ...scheduleLines(app, user),
555558 ...contributorLines(app, user, now()),
559 ...crashLines(app, user, now()),
556560 ];
557561 const before = seen.get(userId);
558562 // What is gone may ask again later, and then it is new again. Seen by
src/http/api/telemetry_apple.ts +31 −7
@@ -3,9 +3,13 @@
33 * signed in or not; whoever sends it is never read: no account, no address, no device id reaches
44 * `recordUsage` (src/core/apple_usage.ts). The address is used only to count a minute's tries in
55 * memory (30 a minute would be the page-view beacon's; here `RATE_CAPS.appleUsage`), and is
6 * dropped with the request. At most `BODY_CAPS.appleUsage` bytes. Answers 204.
6 * dropped with the request. A body whose `kind` is `crash` is a crash report (#18006,
7 * src/core/apple_crash.ts): strict, up to `BODY_CAPS.appleCrash` bytes, a 400 in words when its
8 * shape is wrong. Any other body is a summary, at most `BODY_CAPS.appleUsage` bytes. Answers 204.
79 */
810
11 import { keepCrash } from "../../actions/apple_crash.ts";
12 import { isCrash, parseCrash } from "../../core/apple_crash.ts";
913 import { USAGE_ERRORS, parseUsage, recordUsage } from "../../core/apple_usage.ts";
1014 import { RateLimiter } from "../../core/ratelimit.ts";
1115 import type { App } from "../../app.ts";
@@ -16,14 +20,21 @@ import { apiError, tryAgain } from "../respond.ts";
1620 import type { Router } from "../router.ts";
1721
1822 const limiter = (perMinute: number) => new RateLimiter({ perMinute, adminPerMinute: perMinute, enabled: true });
19 const limits = new WeakMap<App, { client: RateLimiter; forge: RateLimiter }>();
23 const limits = new WeakMap<App, { client: RateLimiter; forge: RateLimiter; crashClient: RateLimiter; crashForge: RateLimiter }>();
24
25 const tooLarge = (what: string, cap: number): Response => apiError("too_large", 413, `${what} too large: at most ${cap / 1024} KB (${cap} bytes)`);
2026
2127 export function appleTelemetryRoutes(router: Router<Handler>): void {
2228 router.add("POST", "/api/v1/telemetry/apple", async (ctx) => {
2329 const { request, app } = ctx;
2430 let pair = limits.get(app);
2531 if (pair === undefined) {
26 pair = { client: limiter(RATE_CAPS.appleUsage.perClient), forge: limiter(RATE_CAPS.appleUsage.perForge) };
32 pair = {
33 client: limiter(RATE_CAPS.appleUsage.perClient),
34 forge: limiter(RATE_CAPS.appleUsage.perForge),
35 crashClient: limiter(RATE_CAPS.appleCrash.perClient),
36 crashForge: limiter(RATE_CAPS.appleCrash.perForge),
37 };
2738 limits.set(app, pair);
2839 }
2940 const verdicts = [
@@ -35,15 +46,28 @@ export function appleTelemetryRoutes(router: Router<Handler>): void {
3546 return tryAgain("rate_limited", 429, `too many summaries: at most ${of}`, Math.max(1, v.retryAfter));
3647 }
3748 }
38 const cap = BODY_CAPS.appleUsage.bytes;
39 const bytes = await readBounded(request, cap);
40 if (bytes === "too_large") return apiError("too_large", 413, `summary too large: at most ${cap / 1024} KB (${cap} bytes)`);
49 const bytes = await readBounded(request, BODY_CAPS.appleCrash.bytes);
50 if (bytes === "too_large") return tooLarge("crash report", BODY_CAPS.appleCrash.bytes);
4151 let input: unknown;
4252 try {
4353 input = JSON.parse(new TextDecoder().decode(bytes));
4454 } catch {
45 return apiError("invalid_body", 422, USAGE_ERRORS.invalid_body);
55 return bytes.length > BODY_CAPS.appleUsage.bytes ? tooLarge("summary", BODY_CAPS.appleUsage.bytes) : apiError("invalid_body", 422, USAGE_ERRORS.invalid_body);
4656 }
57 if (isCrash(input)) {
58 const crash = parseCrash(input);
59 if (!crash.ok) return apiError("invalid_crash", 400, crash.message);
60 for (const [taker, key, of] of [
61 [pair.crashClient, clientBucket(request), `${RATE_CAPS.appleCrash.perClient} crash reports a minute from one address`],
62 [pair.crashForge, "forge", `${RATE_CAPS.appleCrash.perForge} crash reports a minute in all`],
63 ] as const) {
64 const v = taker.take(key, "ro");
65 if (!v.allowed) return tryAgain("rate_limited", 429, `too many crash reports: at most ${of}`, Math.max(1, v.retryAfter));
66 }
67 keepCrash(app, crash.value);
68 return new Response(null, { status: 204, headers: { "cache-control": "no-store" } });
69 }
70 if (bytes.length > BODY_CAPS.appleUsage.bytes) return tooLarge("summary", BODY_CAPS.appleUsage.bytes);
4771 const read = parseUsage(input);
4872 if (!read.ok) return apiError(read.error, 422, USAGE_ERRORS[read.error]);
4973 recordUsage(app.db, read.value);
src/http/limits.ts +5
@@ -52,6 +52,11 @@ export const RATE_CAPS = {
5252 perForge: 300,
5353 reason: "the app sends one summary a day; ten a minute from one address leaves room for retries and a shared network",
5454 },
55 appleCrash: {
56 perClient: 5,
57 perForge: 60,
58 reason: "a person sends a crash report by choice, a few times at most; more from one address is a flood",
59 },
5560 } as const satisfies Record<string, { perClient: number; perForge: number; reason: string }>;
5661
5762 const closing = new WeakSet<Request>();
src/kernel/body_caps.ts +4
@@ -67,6 +67,10 @@ export const BODY_CAPS = {
6767 bytes: 8 * KIB,
6868 reason: "the Apple app's anonymous daily summary: a few dozen named counts and timings, so this is generous",
6969 },
70 appleCrash: {
71 bytes: 64 * KIB,
72 reason: "the Apple app's crash report: up to 200 breadcrumb lines and 12 frames for each of a few findings, each line cut short",
73 },
7074 gameSync: {
7175 bytes: 2 * MIB,
7276 reason: "a game box agent's sync: up to 200 log lines for each of its services, their stats and command results",
src/tui/screens/appleusage.ts +28 −5
@@ -4,6 +4,8 @@
44 * one gate). Read-only; `j`/`k` move.
55 */
66
7 import { readAppleCrashes } from "../../actions/apple_crash.ts";
8 import type { CrashGroup } from "../../core/apple_crash.ts";
79 import { USAGE_DAYS, readAppleUsage } from "../../actions/apple_usage.ts";
810 import type { UsageRead } from "../../core/apple_usage.ts";
911 import type { Ctx, Screen } from "../app/app.ts";
@@ -30,6 +32,28 @@ export function usageRows(read: UsageRead): ListRow[] {
3032 return [...versions, ...days];
3133 }
3234
35 /**
36 * The crash groups, newest first: a count and the top frame, the latest report's frames and
37 * breadcrumbs under it.
38 */
39 export function crashRows(groups: readonly CrashGroup[]): ListRow[] {
40 return groups.map((g): ListRow => ({
41 title: `crash ${g.build}`,
42 secondary: `${g.n} ${g.n === 1 ? "report" : "reports"}`,
43 meta: `${g.top[0] ?? "no frames"} · ${g.latest.device} · ${g.lastSeen.slice(0, 16).replace("T", " ")}`,
44 below: [
45 ...g.latest.findings.flatMap((x) => [`${x.kind} ${x.termination}`.trim(), ...x.frames.map((fr) => ` ${fr}`)]),
46 ...g.latest.breadcrumbs.slice(-12).map((b) => `» ${b}`),
47 ],
48 }));
49 }
50
51 const allRows = (f: Session): ListRow[] => {
52 const r = readAppleUsage(f.app, f.user);
53 const c = readAppleCrashes(f.app, f.user);
54 return [...(c.ok ? crashRows(c.value) : []), ...(r.ok ? usageRows(r.value) : [])];
55 };
56
3357 export function appleUsageScreen(f: Session, ctx: Ctx): Screen {
3458 const state = new ListState();
3559 return {
@@ -41,15 +65,14 @@ export function appleUsageScreen(f: Session, ctx: Ctx): Screen {
4165 const r = readAppleUsage(f.app, f.user);
4266 const text = !r.ok
4367 ? "App usage is for a forge admin."
44 : r.value.versions.length === 0
68 : allRows(f).length === 0
4569 ? "Nothing yet: summaries come when people opt in in the Apple app."
46 : `Anonymous summaries from the Apple app, the last ${USAGE_DAYS} days, per version then per day.`;
70 : `Crash reports people chose to send, then anonymous summaries from the Apple app, the last ${USAGE_DAYS} days.`;
4771 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
48 drawList(s, list!, c, state, r.ok ? usageRows(r.value) : []);
72 drawList(s, list!, c, state, allRows(f));
4973 },
5074 key(e) {
51 const r = readAppleUsage(f.app, f.user);
52 return state.key(e, r.ok ? usageRows(r.value).length : 0);
75 return state.key(e, allRows(f).length);
5376 },
5477 };
5578 }
src/view/policy.ts +5
@@ -48,6 +48,11 @@ export function privacyRows(contact: string): PolicyRow[] {
4848 words:
4949 "Only if you opt in (one question after you sign in; change it in the app's Settings), the app sends the forge you are signed in to one summary a day: counts of what was used and timings. It is kept as totals per day, app version and device kind. No account, address or device identifier is stored, and it goes to no other forge. Usage Data and Diagnostics, not linked to you, not used for tracking.",
5050 },
51 {
52 label: "Crash reports in the Apple app",
53 words:
54 "Only when you choose to send one, after a crash, the app sends the forge you are signed in to a report. It holds the app's version and build, the OS version, the device kind (iPhone, iPad or Mac), when you sent it, the previous run's launch time and up to 200 short breadcrumb lines (such as the tabs you opened), and for each finding its kind, date, signal, exception, termination reason and up to 12 code frames. No account, address or device identifier is stored, and it goes to no other forge. The forge's owner reads it, grouped with identical reports.",
55 },
5156 {
5257 label: "Tracking and ads",
5358 words: "No ads. No tracking across sites. Nothing about you is sold or shared.",
src/web/pages/admin-telemetry.ts +32 −3
@@ -5,6 +5,8 @@
55 * the not-found page. The terminal's door is `src/tui/screens/appleusage.ts`.
66 */
77
8 import { readAppleCrashes } from "../../actions/apple_crash.ts";
9 import type { CrashGroup } from "../../core/apple_crash.ts";
810 import { USAGE_DAYS, readAppleUsage } from "../../actions/apple_usage.ts";
911 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1012 import type { Ctx } from "../../http/context.ts";
@@ -15,17 +17,44 @@ import { statusRow } from "./security.ts";
1517
1618 const TOP = 12;
1719
20 const stamp = (iso: string): string => `${iso.slice(0, 16).replace("T", " ")} UTC`;
21
22 /**
23 * A crash group as one row: its build, the count and top frame, then the latest report's frames and
24 * breadcrumbs.
25 */
outdated

Principles 6 and 7: a settings-block section per group with an h3 and details blocks is a box per thing. Use dl status rows, as the usage section does.

26 function crashGroup(g: CrashGroup): Html {
27 const detail = [
28 ...g.latest.findings.flatMap((x) => [`${x.kind} ${x.signal === "" ? "" : `signal ${x.signal} `}${x.exception === "" ? "" : `exception ${x.exception}`}`.trim(), ...x.frames]),
29 ...(g.latest.breadcrumbs.length === 0 ? [] : [`-- ${g.latest.breadcrumbs.length} breadcrumbs before it`, ...g.latest.breadcrumbs]),
30 ].join("\n");
31 return statusRow(
32 g.build,
33 html`${String(g.n)} ${g.n === 1 ? "report" : "reports"} · <span class="mono">${g.top[0] ?? "no frames"}</span>
34 <span class="muted">${g.latest.device} · ${g.latest.os} · first ${stamp(g.firstSeen)} · latest ${stamp(g.lastSeen)}</span>
35 <pre class="mono">${detail}</pre>`,
36 null,
37 `crash-${g.id}`,
38 );
39 }
40
1841 export function telemetryPage(ctx: Ctx): Response {
1942 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2043 const read = timePhase(ctx.request, "usage", () => readAppleUsage(ctx.app, ctx.auth.user));
2144 if (!read.ok) return notFoundPage(ctx);
2245 const { days, versions } = read.value;
outdated

Principle 1: 'Sent by people who chose to. Grouped by build and top frames, newest first.' explains what the rows already show. Cut it.

46 const crashes = readAppleCrashes(ctx.app, ctx.auth.user);
47 const groups = crashes.ok ? crashes.value : [];
2348 const rendering = performance.now();
2449 const rows = (items: Html[]): Html => html`<dl class="status-rows">${items}</dl>`;
50 const crashBody =
51 groups.length === 0
52 ? ""
53 : html`<section class="settings-block" id="crashes"><h2>Crash reports</h2>${rows(groups.map(crashGroup))}</section>`;
2554 const body =
26 versions.length === 0
55 versions.length === 0 && groups.length === 0
2756 ? html`<p class="muted" id="telemetry-none">Nothing yet. Summaries arrive when people opt in to share usage in the Apple app.</p>`
28 : html`<section class="settings-block">
57 : html`${crashBody}${versions.length === 0 ? "" : html`<section class="settings-block">
2958 <h2>By day</h2>
3059 ${rows(
3160 days.map((d) =>
@@ -52,7 +81,7 @@ export function telemetryPage(ctx: Ctx): Response {
5281 ),
5382 )}
5483 </section>`,
55 )}`;
84 )}`}`;
5685 const out = page({
5786 ctx,
5887 title: "App usage",
test/apple-crash.test.ts added +200
@@ -0,0 +1,200 @@
1 // The Apple app's crash reports (#18006): strict shape, grouped, shown to the owner, told once per
2 // group.
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { crashLines, keepCrash, readAppleCrashes } from "../src/actions/apple_crash.ts";
9 import { MAX_GROUPS, parseCrash, recordCrash, type CrashReport } from "../src/core/apple_crash.ts";
10 import { openapi } from "../src/contract/openapi.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { startNotifier, setNotifyUrl, type Notifier } from "../src/crew/notify.ts";
14 import { BODY_CAPS } from "../src/http/limits.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { crashRows } from "../src/tui/screens/appleusage.ts";
17 import { privacyRows } from "../src/view/policy.ts";
18
19 let dir = "";
20 let app: App;
21 let servers: Servers;
22 let base = "";
23 let admin = "";
24 let owner: User;
25 let notifier: Notifier;
26 const posts: { url: string; body: string }[] = [];
27
28 beforeAll(async () => {
29 dir = await mkdtemp(join(tmpdir(), "apple-crash-"));
30 app = createApp({ dataDir: dir, port: 0 });
31 servers = await serve(app);
32 base = `http://127.0.0.1:${servers.port}`;
33 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
34 if (!u.ok) throw new Error(u.error);
35 owner = u.value;
36 admin = createToken(app.db, owner.id, "a", "admin").token;
37 expect(setNotifyUrl(app.db, owner.id, "https://ntfy.example.test/topic").ok).toBe(true);
38 notifier = startNotifier(app, {
39 forgeUrl: "https://forge.example.test",
40 send: async (url, body) => {
41 posts.push({ url, body });
42 return true;
43 },
44 });
45 await notifier.settled();
46 }, 30_000);
47 afterAll(async () => {
48 await notifier.close();
49 await servers.stop();
50 app.close();
51 await rm(dir, { recursive: true, force: true });
52 });
53
54 const crash = (over: Record<string, unknown> = {}, frames = ["Forge +1445064", "SwiftUI +7", "UIKit +9", "dyld +1"]) => ({
55 v: 1,
56 kind: "crash",
57 app: { version: "0.1", build: "34" },
58 os: "iOS 26.1",
59 device: "iPhone",
60 at: "2026-12-03T12:00:09Z",
61 previousRun: { launchedAt: "2026-12-03T12:00:00Z", breadcrumbs: ["12:00:01 tab repos", "12:00:05 tab <b>now</b>"] },
62 findings: [{ kind: "crash", date: "2026-12-03T12:00:08Z", signal: "5", exception: "6", termination: "Namespace SIGNAL", version: "0.1", frames }],
63 ...over,
64 });
65 const send = (body: unknown) =>
66 fetch(`${base}/api/v1/telemetry/apple`, { method: "POST", headers: { "content-type": "application/json" }, body: typeof body === "string" ? body : JSON.stringify(body) });
67 const groupCount = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM apple_crash_group").get()!.n;
68
69 test("two reports with the same frames and one different are two groups, counted 2 and 1, told once each", async () => {
70 expect((await send(crash())).status).toBe(204);
71 await notifier.settled();
72 expect(posts).toHaveLength(1);
73 expect((await send(crash())).status).toBe(204);
74 expect((await send(crash({}, ["Forge +99", "SwiftUI +7"]))).status).toBe(204);
75 await notifier.settled();
76 expect(posts).toHaveLength(2);
77 expect(posts[0]!.url).toBe("https://ntfy.example.test/topic");
78 expect(posts[0]!.body).toContain("Forge +1445064");
79 expect(posts[0]!.body).toContain("https://forge.example.test/admin/telemetry");
80
81 const read = readAppleCrashes(app, owner);
82 expect(read.ok).toBe(true);
83 if (!read.ok) return;
84 expect(read.value.map((g) => g.n).sort()).toEqual([1, 2]);
85 expect(crashRows(read.value).map((r) => r.secondary).sort()).toEqual(["1 report", "2 reports"]);
86
87 const page = await fetch(`${base}/admin/telemetry`, { headers: { authorization: `Bearer ${admin}` } });
88 expect(page.status).toBe(200);
89 const text = await page.text();
90 expect(text).toContain("2 reports");
91 for (const g of read.value) expect(text).toContain(`id="crash-${g.id}"`);
92 expect(text).toContain("Forge +1445064");
93 expect(text).toContain("12:00:01 tab repos");
94 expect(text).toContain("tab &lt;b&gt;now&lt;/b&gt;");
95 expect(text).not.toContain("<b>now</b>");
96 expect(text.indexOf("Forge +99")).toBeLessThan(text.indexOf("Forge +1445064"));
97 });
98
99 test("nothing about the sender is kept, and a stranger and an agent read nothing", async () => {
100 const kept = JSON.stringify(app.db.query("SELECT * FROM apple_crash_group").all());
101 expect(kept).not.toContain("127.0.0.1");
102 expect(kept).not.toContain(owner.id);
103 expect(readAppleCrashes(app, null)).toEqual({ ok: false, error: "not_found" });
104 expect(readAppleCrashes(app, { ...owner, kind: "agent" })).toEqual({ ok: false, error: "not_found" });
105 });
106
107 test("a planted extra field or a wrong type is a 400 in words, and keeps nothing", async () => {
108 const before = groupCount();
109 const extra = await send(crash({ deviceId: "abc" }));
110 expect(extra.status).toBe(400);
111 expect(((await extra.json()) as { message: string }).message).toContain("deviceId");
112 const nested = await send(crash({ app: { version: "0.1", build: "34", udid: "x" } }));
113 expect(nested.status).toBe(400);
114 const wrong = await send(crash({ previousRun: { launchedAt: "x", breadcrumbs: "nope" } }));
115 expect(wrong.status).toBe(400);
116 expect(((await wrong.json()) as { message: string }).message).toContain("breadcrumbs");
117 expect(groupCount()).toBe(before);
118 });
119
120 test("more than 200 breadcrumbs or 12 frames is a 400", async () => {
121 const crumbs = Array.from({ length: 201 }, (_, i) => `line ${i}`);
122 expect((await send(crash({ previousRun: { launchedAt: "x", breadcrumbs: crumbs } }))).status).toBe(400);
123 expect((await send(crash({}, Array.from({ length: 13 }, (_, i) => `F +${i}`)))).status).toBe(400);
124 });
125
126 test("a body over 64 KB is a 413 naming the limit", async () => {
127 expect(BODY_CAPS.appleCrash.bytes).toBe(64 * 1024);
128 const res = await send(crash({ os: "x".repeat(BODY_CAPS.appleCrash.bytes) }));
129 expect(res.status).toBe(413);
130 expect(await res.text()).toContain("64 KB");
131 });
132
133 test("/privacy says what a crash report holds and that it is sent only by choice", () => {
134 const row = privacyRows("x").find((r) => r.label === "Crash reports in the Apple app");
135 expect(row?.words).toContain("Only when you choose");
136 expect(row?.words).toContain("200");
137 expect(row?.words).toContain("No account, address or device identifier");
138 });
139
140 const report = (frames: string[], over: Partial<CrashReport> = {}): CrashReport => {
141 const p = parseCrash(crash({}, frames));
142 if (!p.ok) throw new Error(p.message);
143 return { ...p.value, ...over };
144 };
145
146 test("a line over 200 characters is cut and control characters are stripped", () => {
147 const p = parseCrash(crash({ previousRun: { launchedAt: "x", breadcrumbs: ["a".repeat(500), "x\u0000y\u001b[31mz\ttab"] } }));
148 expect(p.ok).toBe(true);
149 if (!p.ok) return;
150 expect(p.value.breadcrumbs[0]).toHaveLength(200);
151 expect(p.value.breadcrumbs[1]).toBe("x y [31mz tab");
152 expect(/[\u0000-\u001f\u007f]/.test(p.value.breadcrumbs.join(""))).toBe(false);
153 });
154
155 test("a usage summary over 8 KB is still a 413 now the read cap is 64 KB", async () => {
156 const res = await send({ v: 1, day: "2026-12-03", app: { version: "0.1", build: "34" }, os: "iOS", device: "iPhone", counts: {}, timings: {}, pad: "x".repeat(9 * 1024) });
157 expect(res.status).toBe(413);
158 expect(await res.text()).toContain("8 KB");
159 });
160
161 test("the contract declares the crash path's 400, 413 and 429", () => {
162 const op = (openapi("https://forge.example.test", "test", "admin") as { paths: Record<string, { post: { responses: Record<string, { description?: string }> } }> }).paths["/api/v1/telemetry/apple"]!.post;
163 expect(op.responses["400"]?.description).toContain("invalid_crash");
164 expect(op.responses["413"]?.description).toContain("64 KB");
165 expect(op.responses["429"]?.description).toContain("rate_limited");
166 });
167
168 test("groups past the cap are not kept and none is deleted; a known group still counts", () => {
169 const before = groupCount();
170 for (let i = before; i < MAX_GROUPS; i++) recordCrash(app.db, report([`Fill +${i}`]));
171 expect(groupCount()).toBe(MAX_GROUPS);
172 const oldest = app.db.query<{ id: string }, []>("SELECT id FROM apple_crash_group ORDER BY last_seen ASC LIMIT 1").get()!.id;
173 expect(recordCrash(app.db, report(["Brand new +1"]))).toBeUndefined();
174 expect(groupCount()).toBe(MAX_GROUPS);
175 expect(app.db.query("SELECT 1 FROM apple_crash_group WHERE id = ?1").get(oldest)).not.toBeNull();
176 const n = app.db.query<{ n: number }, []>("SELECT n FROM apple_crash_group WHERE top LIKE '%Fill +5\"%'").get()!.n;
177 expect(recordCrash(app.db, report(["Fill +5"]))).toBeUndefined();
178 expect(app.db.query<{ n: number }, []>("SELECT n FROM apple_crash_group WHERE top LIKE '%Fill +5\"%'").get()!.n).toBe(n + 1);
179 });
180
181 test("a flood of new groups is one line per pass, and a re-sent group is not told again", async () => {
182 const told = posts.length;
183 for (let i = 0; i < 30; i++) keepCrash(app, report([`Flood +${i}`], { build: `9.${i} (1)` }));
184 await notifier.settled();
185 const lines = crashLines(app, owner);
186 expect(lines).toHaveLength(1);
187 expect(lines[0]!.items.length).toBeGreaterThan(30);
188 expect(posts.length - told).toBeLessThanOrEqual(1);
189 const after = posts.length;
190 for (let i = 0; i < 30; i++) keepCrash(app, report([`Flood +${i}`], { build: `9.${i} (1)` }));
191 await notifier.settled();
192 expect(posts.length).toBe(after);
193 });
194
195 test("more than 5 crash reports a minute from one address is a 429", async () => {
196 const codes: number[] = [];
197 for (let i = 0; i < 8; i++) codes.push((await send(crash({}, [`Rate +${i}`]))).status);
198 expect(codes).toContain(429);
199 expect(codes.indexOf(429)).toBeLessThanOrEqual(5);
200 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs