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 #18010
Closed 11h 18m ago
scout/forge:scout/18006-crash-reports-from-the-apple-app-are-kep → main 4 commits fork
15 files
changed +581
−28
- docs/features/apple-usage.md
- src/actions/apple_usage.ts
- src/contract/openapi/routes/postApiV1TelemetryApple.ts
- src/core/apple_crash.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261204023342-apple-crash.pin
- src/core/migrations/20261204023342-apple-crash.ts
- src/crew/notify.ts
- src/http/api/telemetry_apple.ts
- src/http/limits.ts
- src/kernel/body_caps.ts
- src/tui/screens/appleusage.ts
- src/view/policy.ts
- src/web/pages/admin-telemetry.ts
- test/apple-crash.test.ts
docs/features/apple-usage.md +16
| @@ -17,3 +17,19 @@ People opt in once in the forge Apple app (and can change it in its Settings). W | ||
| 17 | 17 | - **Other forges:** a person signed in to their own forge sends to that forge only. Nothing is forwarded. |
| 18 | 18 | |
| 19 | 19 | 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. |
| 20 | ||
| 21 | ## Crash reports (#18006) | |
| 22 | ||
| 23 | The same door, `POST /api/v1/telemetry/apple`, takes a crash report when the person chooses to send one (`"kind":"crash"`): | |
| 24 | ||
| 25 | json | |
| 26 | {"v":1,"kind":"crash","app":{"version":"0.1","build":"34"},"os":"iOS 26.1","device":"iPhone","at":"2026-12-04T10:00:00Z", | |
| 27 | "previousRun":{"launchedAt":"...","breadcrumbs":["12:00:01 tab repos"]}, | |
| 28 | "findings":[{"kind":"crash","date":"...","signal":"5","exception":"6","termination":"Namespace SIGNAL","version":"0.1","frames":["Forge +1445064","SwiftUI +7"]}]} | |
| 29 | ||
| 30 | ||
| 31 | - **Strict:** an unknown field or a wrong type is a 400 that names it; at most 200 breadcrumb lines, 10 findings and 12 frames a finding, each line 160 characters, no control characters. 64 KB a body (413 above), 6 a minute from one address (in memory only; no address is stored). Answers 204. | |
| 32 | - **Kept** in its own tables (`apple_crash_group`, `apple_crash`, `src/core/apple_crash.ts`), apart from the usage rows. Reports with the same build and the same top five frames of their first finding are one group with a count; 500 groups and 20 reports a group are kept. | |
| 33 | - **Read it:** `/admin/telemetry` lists the groups first, newest first, with the frames and the newest report's breadcrumbs; `App usage` in the terminal shows the same rows (`crashRows`). Both read `readAppleCrashes` in `src/actions/apple_usage.ts`. | |
| 34 | - **Told once:** the first report of a group appends an `apple.crash_group` event, and the notifier (`newCrashLines` in `src/crew/notify.ts`) sends the forge's admins one line per group, never per report. | |
| 35 | - `/privacy` says what a report holds and that it is sent only when the user chooses. |
src/actions/apple_usage.ts +7
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { App } from "../app.ts"; |
| 8 | import { type CrashGroup, readCrashGroups } from "../core/apple_crash.ts"; | |
| 8 | 9 | import { type UsageRead, readUsage } from "../core/apple_usage.ts"; |
| 9 | 10 | import type { User } from "../core/users.ts"; |
| 10 | 11 | |
| @@ -14,3 +15,9 @@ export function readAppleUsage(app: App, user: User | null | undefined): { ok: t | ||
| 14 | 15 | if (user?.isAdmin !== true || user.kind === "agent") return { ok: false, error: "not_found" }; |
| 15 | 16 | return { ok: true, value: readUsage(app.db, USAGE_DAYS) }; |
| 16 | 17 | } |
| 18 | ||
| 19 | /** The Apple app's crash reports (#18006), grouped, newest first: the same gate as the usage. */ | |
| 20 | export function readAppleCrashes(app: App, user: User | null | undefined): { ok: true; value: CrashGroup[] } | { ok: false; error: "not_found" } { | |
| 21 | if (user?.isAdmin !== true || user.kind === "agent") return { ok: false, error: "not_found" }; | |
| 22 | return { ok: true, value: readCrashGroups(app.db) }; | |
| 23 | } |
src/contract/openapi/routes/postApiV1TelemetryApple.ts +4 −4
| @@ -3,12 +3,12 @@ import type { Route } from "../shared.ts"; | ||
| 3 | 3 | export const route: Route = { |
| 4 | 4 | method: "post", |
| 5 | 5 | 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 anonymous daily usage summary, or a crash report it sends when the user chooses; 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. A body with `kind: \"crash\"` is a crash report instead: `{v: 1, kind: \"crash\", app: {version, build}, os, device, at, previousRun?: {launchedAt?, breadcrumbs: [string, at most 200]}, findings?: [{kind: crash|hang|cpu|disk, date?, signal?, exception?, termination?, version?, frames?: [string, at most 12]}]}`. Its shape is strict: an unknown field or a wrong type is a 400 in words. At most 64 KB and 6 reports a minute from one address; it is kept apart from the summaries, grouped by build and top frames with a count, and the owner is told once per new group. No address or account is kept.", | |
| 8 | 8 | auth: false, |
| 9 | 9 | role: "anonymous", |
| 10 | 10 | 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?", at: "string?", previousRun: "object?", findings: "array?", app: "object", os: "string", device: "string", counts: "object?", timings: "object?", metrickit: "object?" }, | |
| 12 | refusals: { invalid_body: "the body is not a JSON object (422); a crash report with an unknown field, a wrong type or a line over its cap is 400, in words", 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: "a summary is over 8 KB, a crash report over 64 KB (413)", rate_limited: "429: too many summaries from one address or in all" }, | |
| 13 | 13 | refuses: [422], |
| 14 | 14 | }; |
src/core/apple_crash.ts added +270
| @@ -0,0 +1,270 @@ | ||
| 1 | /** | |
| 2 | * The Apple app's crash reports (#18006): what is accepted, how reports are grouped and what is | |
| 3 | * kept. | |
| 4 | * | |
| 5 | * The user chooses to send one. The shape is strict: an unknown field or a wrong type is refused in | |
| 6 | * words, at most `MAX_BREADCRUMBS` breadcrumb lines and `MAX_FRAMES` frames a finding, every line | |
| 7 | * length-capped and free of control characters. Reports with the same build and the same top | |
| 8 | * `GROUP_FRAMES` frames of their first finding are one group with a count. Nothing about who sent | |
| 9 | * one is an argument here: no account, no address, no device id. At most `MAX_GROUPS` groups | |
| 10 | * (the least recently seen is dropped) and `KEEP_PER_GROUP` reports a group, newest kept. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | ||
| 15 | export const CRASH_SCHEMA = 1; | |
| 16 | export const MAX_BREADCRUMBS = 200; | |
| 17 | export const MAX_FRAMES = 12; | |
| 18 | export const MAX_FINDINGS = 10; | |
| 19 | export const MAX_LINE = 160; | |
| 20 | export const GROUP_FRAMES = 5; | |
| 21 | export const MAX_GROUPS = 500; | |
| 22 | export const KEEP_PER_GROUP = 20; | |
| 23 | const DEVICES = new Set(["iPhone", "iPad", "Mac", "Watch", "Vision", "TV"]); | |
| 24 | const FINDING_KINDS = new Set(["crash", "hang", "cpu", "disk"]); | |
| 25 | const VERSION = /^\d{1,4}(\.\d{1,4}){0,3}$/; | |
| 26 | const BUILD = /^[0-9A-Za-z.]{1,16}$/; | |
| 27 | // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is refused | |
| 28 | const CONTROL = /[\u0000-\u001f\u007f]/; | |
| 29 | ||
| 30 | export interface CrashFinding { | |
| 31 | readonly kind: string; | |
| 32 | readonly date?: string; | |
| 33 | readonly signal?: string; | |
| 34 | readonly exception?: string; | |
| 35 | readonly termination?: string; | |
| 36 | readonly version?: string; | |
| 37 | readonly frames: readonly string[]; | |
| 38 | } | |
| 39 | export interface CrashReport { | |
| 40 | readonly version: string; | |
| 41 | readonly os: string; | |
| 42 | readonly device: string; | |
| 43 | /** When the user sent it, as the app said. */ | |
| 44 | readonly at: string; | |
| 45 | readonly previousRun?: { readonly launchedAt?: string; readonly breadcrumbs: readonly string[] }; | |
| 46 | readonly findings: readonly CrashFinding[]; | |
| 47 | } | |
| 48 | ||
| 49 | const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v); | |
| 50 | ||
| 51 | /** Whether a body says it is a crash report: the one door's other kind is the daily summary. */ | |
| 52 | export const isCrashBody = (input: unknown): boolean => isObject(input) && input.kind === "crash"; | |
| 53 | ||
| 54 | type Fail = { ok: false; message: string }; | |
| 55 | const fail = (message: string): Fail => ({ ok: false, message }); | |
| 56 | ||
| 57 | function only(o: Record<string, unknown>, allowed: readonly string[], where: string): string | undefined { | |
| 58 | for (const k of Object.keys(o)) if (!allowed.includes(k)) return `${where} has an unknown field "${k.slice(0, 40)}": it holds only ${allowed.join(", ")}`; | |
| 59 | return undefined; | |
| 60 | } | |
| 61 | ||
| 62 | function line(v: unknown, where: string, max = MAX_LINE): string | Fail { | |
| 63 | if (typeof v !== "string") return fail(`${where} is a string`); | |
| 64 | if (v.length > max) return fail(`${where} is at most ${max} characters`); | |
| 65 | if (CONTROL.test(v)) return fail(`${where} has a control character`); | |
| 66 | return v; | |
| 67 | } | |
| 68 | ||
| 69 | function lines(v: unknown, where: string, most: number): string[] | Fail { | |
| 70 | if (!Array.isArray(v)) return fail(`${where} is an array of strings`); | |
| 71 | if (v.length > most) return fail(`${where} holds at most ${most} lines`); | |
| 72 | const out: string[] = []; | |
| 73 | for (const [i, x] of v.entries()) { | |
| 74 | const l = line(x, `${where}[${i}]`); | |
| 75 | if (typeof l !== "string") return l; | |
| 76 | out.push(l); | |
| 77 | } | |
| 78 | return out; | |
| 79 | } | |
| 80 | ||
| 81 | function when(v: unknown, where: string): string | Fail { | |
| 82 | const s = line(v, where, 40); | |
| 83 | if (typeof s !== "string") return s; | |
| 84 | return Number.isNaN(Date.parse(s)) ? fail(`${where} is a date and time, ISO 8601`) : s; | |
| 85 | } | |
| 86 | ||
| 87 | function finding(v: unknown, where: string): CrashFinding | Fail { | |
| 88 | if (!isObject(v)) return fail(`${where} is an object`); | |
| 89 | const extra = only(v, ["kind", "date", "signal", "exception", "termination", "version", "frames"], where); | |
| 90 | if (extra !== undefined) return fail(extra); | |
| 91 | if (typeof v.kind !== "string" || !FINDING_KINDS.has(v.kind)) return fail(`${where}.kind is one of crash, hang, cpu, disk`); | |
| 92 | const out: { -readonly [K in keyof CrashFinding]: CrashFinding[K] } = { kind: v.kind, frames: [] }; | |
| 93 | if (v.date !== undefined) { | |
| 94 | const d = when(v.date, `${where}.date`); | |
| 95 | if (typeof d !== "string") return d; | |
| 96 | out.date = d; | |
| 97 | } | |
| 98 | for (const k of ["signal", "exception", "termination"] as const) { | |
| 99 | if (v[k] === undefined) continue; | |
| 100 | const s = line(v[k], `${where}.${k}`, 80); | |
| 101 | if (typeof s !== "string") return s; | |
| 102 | out[k] = s; | |
| 103 | } | |
| 104 | if (v.version !== undefined) { | |
| 105 | if (typeof v.version !== "string" || !VERSION.test(v.version)) return fail(`${where}.version is a dotted number`); | |
| 106 | out.version = v.version; | |
| 107 | } | |
| 108 | if (v.frames !== undefined) { | |
| 109 | const f = lines(v.frames, `${where}.frames`, MAX_FRAMES); | |
| 110 | if (!Array.isArray(f)) return f; | |
| 111 | out.frames = f; | |
| 112 | } | |
| 113 | return out; | |
| 114 | } | |
| 115 | ||
| 116 | /** A body, read at the boundary: the report to keep, or the first thing wrong with it, in words. */ | |
| 117 | export function parseCrash(input: unknown): { ok: true; value: CrashReport } | Fail { | |
| 118 | if (!isObject(input)) return fail("the body is a JSON object"); | |
| 119 | const extra = only(input, ["v", "kind", "app", "os", "device", "at", "previousRun", "findings"], "the report"); | |
| 120 | if (extra !== undefined) return fail(extra); | |
| 121 | if (input.v !== CRASH_SCHEMA) return fail(`v is ${CRASH_SCHEMA}`); | |
| 122 | if (input.kind !== "crash") return fail('kind is "crash"'); | |
| 123 | const app = input.app; | |
| 124 | if (!isObject(app)) return fail("app is {version, build}"); | |
| 125 | const appExtra = only(app, ["version", "build"], "app"); | |
| 126 | if (appExtra !== undefined) return fail(appExtra); | |
| 127 | if (typeof app.version !== "string" || !VERSION.test(app.version)) return fail("app.version is a dotted number"); | |
| 128 | const build = typeof app.build === "number" ? String(app.build) : app.build; | |
| 129 | if (typeof build !== "string" || !BUILD.test(build)) return fail("app.build is a short build number or name"); | |
| 130 | const os = line(input.os, "os", 40); | |
| 131 | if (typeof os !== "string") return os; | |
| 132 | if (os.length < 1) return fail("os is at least 1 character"); | |
| 133 | const device = line(input.device, "device", 20); | |
| 134 | if (typeof device !== "string") return device; | |
| 135 | if (device.length < 1) return fail("device is at least 1 character"); | |
| 136 | const at = when(input.at, "at"); | |
| 137 | if (typeof at !== "string") return at; | |
| 138 | let previousRun: CrashReport["previousRun"]; | |
| 139 | if (input.previousRun !== undefined) { | |
| 140 | const p = input.previousRun; | |
| 141 | if (!isObject(p)) return fail("previousRun is {launchedAt, breadcrumbs}"); | |
| 142 | const pe = only(p, ["launchedAt", "breadcrumbs"], "previousRun"); | |
| 143 | if (pe !== undefined) return fail(pe); | |
| 144 | let launchedAt: string | undefined; | |
| 145 | if (p.launchedAt !== undefined) { | |
| 146 | const l = when(p.launchedAt, "previousRun.launchedAt"); | |
| 147 | if (typeof l !== "string") return l; | |
| 148 | launchedAt = l; | |
| 149 | } | |
| 150 | const crumbs = p.breadcrumbs === undefined ? [] : lines(p.breadcrumbs, "previousRun.breadcrumbs", MAX_BREADCRUMBS); | |
| 151 | if (!Array.isArray(crumbs)) return crumbs; | |
| 152 | previousRun = launchedAt === undefined ? { breadcrumbs: crumbs } : { launchedAt, breadcrumbs: crumbs }; | |
| 153 | } | |
| 154 | const found: CrashFinding[] = []; | |
| 155 | if (input.findings !== undefined) { | |
| 156 | if (!Array.isArray(input.findings)) return fail("findings is an array"); | |
| 157 | if (input.findings.length > MAX_FINDINGS) return fail(`findings holds at most ${MAX_FINDINGS}`); | |
| 158 | for (const [i, f] of input.findings.entries()) { | |
| 159 | const r = finding(f, `findings[${i}]`); | |
| 160 | if ("ok" in r) return r; | |
| 161 | found.push(r); | |
| 162 | } | |
| 163 | } | |
| 164 | const value: CrashReport = { | |
| 165 | version: `${app.version} (${build})`, | |
| 166 | os, | |
| 167 | device: DEVICES.has(device) ? device : "other", | |
| 168 | at, | |
| 169 | ...(previousRun === undefined ? {} : { previousRun }), | |
| 170 | findings: found, | |
| 171 | }; | |
| 172 | return { ok: true, value }; | |
| 173 | } | |
| 174 | ||
| 175 | /** The frames that name a group: the first finding that has any, at most `GROUP_FRAMES`. */ | |
| 176 | export const topFrames = (r: CrashReport): { kind: string; frames: string[] } => { | |
| 177 | const f = r.findings.find((x) => x.frames.length > 0) ?? r.findings[0]; | |
| 178 | return { kind: f?.kind ?? "crash", frames: (f?.frames ?? []).slice(0, GROUP_FRAMES) }; | |
| 179 | }; | |
| 180 | ||
| 181 | const groupKey = (version: string, kind: string, frames: readonly string[]): string => | |
| 182 | new Bun.CryptoHasher("sha256").update(JSON.stringify([version, kind, frames])).digest("hex").slice(0, 16); | |
| 183 | ||
| 184 | /** | |
| 185 | * Keep one report. `isNew` is true for the first of its group: the one that is told to the owner. | |
| 186 | */ | |
| 187 | export function recordCrash(db: Database, r: CrashReport, now: Date = new Date()): { key: string; isNew: boolean; version: string; top: string } { | |
| 188 | const { kind, frames } = topFrames(r); | |
| 189 | const key = groupKey(r.version, kind, frames); | |
| 190 | const at = now.toISOString(); | |
| 191 | const top = frames[0] ?? "(no frames)"; | |
| 192 | let isNew = false; | |
| 193 | db.transaction(() => { | |
| 194 | const had = db.query<{ n: number }, [string]>("SELECT n FROM apple_crash_group WHERE key = ?1").get(key); | |
| 195 | if (had === null) { | |
| 196 | isNew = true; | |
| 197 | const groups = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM apple_crash_group").get()!.n; | |
| 198 | if (groups >= MAX_GROUPS) { | |
| 199 | const old = db.query<{ key: string }, []>("SELECT key FROM apple_crash_group ORDER BY last_at ASC LIMIT 1").get(); | |
| 200 | if (old !== null) { | |
| 201 | db.query("DELETE FROM apple_crash WHERE group_key = ?1").run(old.key); | |
| 202 | db.query("DELETE FROM apple_crash_group WHERE key = ?1").run(old.key); | |
| 203 | } | |
| 204 | } | |
| 205 | db.query("INSERT INTO apple_crash_group (key, version, top, kind, n, first_at, last_at) VALUES (?1, ?2, ?3, ?4, 1, ?5, ?5)").run( | |
| 206 | key, | |
| 207 | r.version, | |
| 208 | JSON.stringify(frames), | |
| 209 | kind, | |
| 210 | at, | |
| 211 | ); | |
| 212 | } else { | |
| 213 | db.query("UPDATE apple_crash_group SET n = n + 1, last_at = ?2 WHERE key = ?1").run(key, at); | |
| 214 | } | |
| 215 | db.query("INSERT INTO apple_crash (group_key, received_at, body) VALUES (?1, ?2, ?3)").run(key, at, JSON.stringify(r)); | |
| 216 | db.query( | |
| 217 | "DELETE FROM apple_crash WHERE group_key = ?1 AND id NOT IN (SELECT id FROM apple_crash WHERE group_key = ?1 ORDER BY id DESC LIMIT ?2)", | |
| 218 | ).run(key, KEEP_PER_GROUP); | |
| 219 | })(); | |
| 220 | return { key, isNew, version: r.version, top }; | |
| 221 | } | |
| 222 | ||
| 223 | export interface CrashGroup { | |
| 224 | readonly key: string; | |
| 225 | readonly version: string; | |
| 226 | readonly kind: string; | |
| 227 | readonly frames: readonly string[]; | |
| 228 | readonly count: number; | |
| 229 | readonly firstAt: string; | |
| 230 | readonly lastAt: string; | |
| 231 | /** The newest report kept for it. */ | |
| 232 | readonly latest: (CrashReport & { receivedAt: string }) | undefined; | |
| 233 | } | |
| 234 | ||
| 235 | /** Groups, the most recently seen first, each with its newest report. */ | |
| 236 | export function readCrashGroups(db: Database, limit = 50): CrashGroup[] { | |
| 237 | const groups = db | |
| 238 | .query<{ key: string; version: string; top: string; kind: string; n: number; first_at: string; last_at: string }, [number]>( | |
| 239 | "SELECT * FROM apple_crash_group ORDER BY last_at DESC, key LIMIT ?1", | |
| 240 | ) | |
| 241 | .all(limit); | |
| 242 | return groups.map((g) => { | |
| 243 | const row = db | |
| 244 | .query<{ body: string; received_at: string }, [string]>("SELECT body, received_at FROM apple_crash WHERE group_key = ?1 ORDER BY id DESC LIMIT 1") | |
| 245 | .get(g.key); | |
| 246 | return { | |
| 247 | key: g.key, | |
| 248 | version: g.version, | |
| 249 | kind: g.kind, | |
| 250 | frames: JSON.parse(g.top) as string[], | |
| 251 | count: g.n, | |
| 252 | firstAt: g.first_at, | |
| 253 | lastAt: g.last_at, | |
| 254 | latest: row === null ? undefined : { ...(JSON.parse(row.body) as CrashReport), receivedAt: row.received_at }, | |
| 255 | }; | |
| 256 | }); | |
| 257 | } | |
| 258 | ||
| 259 | /** Groups first seen in the last week, for the notifier: one id per group, never per report. */ | |
| 260 | export function newCrashLines(db: Database, now: number = Date.now()): { id: string; line: string; items: readonly string[] }[] { | |
| 261 | const since = new Date(now - 7 * 86_400_000).toISOString(); | |
| 262 | return db | |
| 263 | .query<{ key: string; version: string; top: string; kind: string }, [string]>("SELECT key, version, top, kind FROM apple_crash_group WHERE first_at >= ?1 ORDER BY first_at") | |
| 264 | .all(since) | |
| 265 | .map((g) => { | |
| 266 | const id = `apple-crash:${g.key}`; | |
| 267 | const frame = (JSON.parse(g.top) as string[])[0]; | |
| 268 | return { id, line: `New ${g.kind} in the Apple app ${g.version}${frame === undefined ? "" : `: ${frame}`}`, items: [id] }; | |
| 269 | }); | |
| 270 | } |
src/core/event_audience.ts +2
| @@ -400,6 +400,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 400 | 400 | // An erased account's counts, and why one was held (`maintain/duties/account_purge.ts`, |
| 401 | 401 | // #15620). |
| 402 | 402 | kind === "account.purged" || |
| 403 | // A crash group of the Apple app seen for the first time is the forge admins' to hear (#18006). | |
| 404 | kind === "apple.crash_group" || | |
| 403 | 405 | kind === "account.purge_failed" |
| 404 | 406 | ) |
| 405 | 407 | return "admins"; |
src/core/migration-pins/20261204023342-apple-crash.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 071ccc6dd741d7b9d39ecd419c1640f51a851c8a1f8127d1c7e738af904138d4 |
src/core/migrations/20261204023342-apple-crash.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | // The Apple app's crash reports (#18006), kept apart from the daily usage rows: one row per group | |
| 2 | // (the same build and the same top frames) with its count, and the reports under it, newest kept up | |
| 3 | // to a bound per group by `recordCrash` (src/core/apple_crash.ts). No account, address or device id | |
| 4 | // is a column. Additive: new tables. | |
| 5 | export default ` | |
| 6 | CREATE TABLE IF NOT EXISTS apple_crash_group ( | |
| 7 | key TEXT PRIMARY KEY, | |
| 8 | version TEXT NOT NULL, | |
| 9 | top TEXT NOT NULL, | |
| 10 | kind TEXT NOT NULL, | |
| 11 | n INTEGER NOT NULL DEFAULT 0, | |
| 12 | first_at TEXT NOT NULL, | |
| 13 | last_at TEXT NOT NULL | |
| 14 | ) WITHOUT ROWID; | |
| 15 | CREATE INDEX IF NOT EXISTS apple_crash_group_last ON apple_crash_group (last_at DESC); | |
| 16 | CREATE TABLE IF NOT EXISTS apple_crash ( | |
| 17 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 18 | group_key TEXT NOT NULL, | |
| 19 | received_at TEXT NOT NULL, | |
| 20 | body TEXT NOT NULL | |
| 21 | ); | |
| 22 | CREATE INDEX IF NOT EXISTS apple_crash_group_id ON apple_crash (group_key, id DESC); | |
| 23 | `; |
src/crew/notify.ts +4
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | import { watchNeeds } from "../cloud/watch.ts"; |
| 24 | 24 | import { blockedLines } from "../actions/egress_refused.ts"; |
| 25 | 25 | import { scheduleLines } from "../actions/schedules.ts"; |
| 26 | import { newCrashLines } from "../core/apple_crash.ts"; | |
| 26 | 27 | import { newAccountLines } from "../actions/accounts.ts"; |
| 27 | 28 | import { contributorLines } from "../actions/invites.ts"; |
| 28 | 29 | import { requestLines } from "../actions/requests.ts"; |
| @@ -87,6 +88,8 @@ const WAKES = new Set([ | ||
| 87 | 88 | "app.egress.refused", |
| 88 | 89 | "app.egress.ignored", |
| 89 | 90 | "app.egress.allowed", |
| 91 | // A crash report of a group not seen before (`core/apple_crash.ts`, #18006). | |
| 92 | "apple.crash_group", | |
| 90 | 93 | ]); |
| 91 | 94 | |
| 92 | 95 | export type NotifyUrlError = |
| @@ -540,6 +543,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 540 | 543 | ...askLinesFor(app.db, user).map((a) => ({ line: a.line, items: a.items })), |
| 541 | 544 | ...requestLines(app.db, user), |
| 542 | 545 | ...newAccountLines(app.db, user, now()), |
| 546 | ...(user.isAdmin && user.kind === "user" ? newCrashLines(app.db, now()) : []), | |
| 543 | 547 | ...landedLines(app.db, user, now()), |
| 544 | 548 | ...mailCeilingLines(app, user, now()), |
| 545 | 549 | ...drillLines(app, user, now()), |
src/http/api/telemetry_apple.ts +46 −17
| @@ -4,8 +4,14 @@ | ||
| 4 | 4 | * `recordUsage` (src/core/apple_usage.ts). The address is used only to count a minute's tries in |
| 5 | 5 | * memory (30 a minute would be the page-view beacon's; here `RATE_CAPS.appleUsage`), and is |
| 6 | 6 | * dropped with the request. At most `BODY_CAPS.appleUsage` bytes. Answers 204. |
| 7 | * | |
| 8 | * The same door takes the app's crash report (#18006), `kind: "crash"`, when the user chooses to | |
| 9 | * send one: at most `BODY_CAPS.appleCrash` bytes, a strict shape (a 400 in words), its own rate | |
| 10 | * limit, kept in its own table and grouped (src/core/apple_crash.ts); a group not seen before | |
| 11 | * is one event, which the notifier tells the owner once. | |
| 7 | 12 | */ |
| 8 | 13 | |
| 14 | import { isCrashBody, parseCrash, recordCrash } from "../../core/apple_crash.ts"; | |
| 9 | 15 | import { USAGE_ERRORS, parseUsage, recordUsage } from "../../core/apple_usage.ts"; |
| 10 | 16 | import { RateLimiter } from "../../core/ratelimit.ts"; |
| 11 | 17 | import type { App } from "../../app.ts"; |
| @@ -16,34 +22,57 @@ import { apiError, tryAgain } from "../respond.ts"; | ||
| 16 | 22 | import type { Router } from "../router.ts"; |
| 17 | 23 | |
| 18 | 24 | const limiter = (perMinute: number) => new RateLimiter({ perMinute, adminPerMinute: perMinute, enabled: true }); |
| 19 | const limits = new WeakMap<App, { client: RateLimiter; forge: RateLimiter }>(); | |
| 25 | type Pair = { client: RateLimiter; forge: RateLimiter }; | |
| 26 | const limits = new WeakMap<App, { usage: Pair; crash: Pair }>(); | |
| 27 | ||
| 28 | /** The minute's two limits for one kind of body: this address, and the forge in all. */ | |
| 29 | function refused(app: App, request: Request, kind: "usage" | "crash"): Response | undefined { | |
| 30 | let both = limits.get(app); | |
| 31 | if (both === undefined) { | |
| 32 | const make = (c: { perClient: number; perForge: number }): Pair => ({ client: limiter(c.perClient), forge: limiter(c.perForge) }); | |
| 33 | both = { usage: make(RATE_CAPS.appleUsage), crash: make(RATE_CAPS.appleCrash) }; | |
| 34 | limits.set(app, both); | |
| 35 | } | |
| 36 | const caps = kind === "crash" ? RATE_CAPS.appleCrash : RATE_CAPS.appleUsage; | |
| 37 | const what = kind === "crash" ? "crash reports" : "summaries"; | |
| 38 | const pair = both[kind]; | |
| 39 | const verdicts = [ | |
| 40 | { v: pair.client.take(clientBucket(request), "ro"), of: `${caps.perClient} ${what} a minute from one address` }, | |
| 41 | { v: pair.forge.take("forge", "ro"), of: `${caps.perForge} ${what} a minute in all` }, | |
| 42 | ]; | |
| 43 | for (const { v, of } of verdicts) { | |
| 44 | if (!v.allowed) return tryAgain("rate_limited", 429, `too many ${what}: at most ${of}`, Math.max(1, v.retryAfter)); | |
| 45 | } | |
| 46 | return undefined; | |
| 47 | } | |
| 20 | 48 | |
| 21 | 49 | export function appleTelemetryRoutes(router: Router<Handler>): void { |
| 22 | 50 | router.add("POST", "/api/v1/telemetry/apple", async (ctx) => { |
| 23 | 51 | const { request, app } = ctx; |
| 24 | let pair = limits.get(app); | |
| 25 | if (pair === undefined) { | |
| 26 | pair = { client: limiter(RATE_CAPS.appleUsage.perClient), forge: limiter(RATE_CAPS.appleUsage.perForge) }; | |
| 27 | limits.set(app, pair); | |
| 28 | } | |
| 29 | const verdicts = [ | |
| 30 | { v: pair.client.take(clientBucket(request), "ro"), of: `${RATE_CAPS.appleUsage.perClient} summaries a minute from one address` }, | |
| 31 | { v: pair.forge.take("forge", "ro"), of: `${RATE_CAPS.appleUsage.perForge} summaries a minute in all` }, | |
| 32 | ]; | |
| 33 | for (const { v, of } of verdicts) { | |
| 34 | if (!v.allowed) { | |
| 35 | return tryAgain("rate_limited", 429, `too many summaries: at most ${of}`, Math.max(1, v.retryAfter)); | |
| 36 | } | |
| 37 | } | |
| 38 | const cap = BODY_CAPS.appleUsage.bytes; | |
| 52 | const cap = BODY_CAPS.appleCrash.bytes; | |
| 53 | const small = BODY_CAPS.appleUsage.bytes; | |
| 39 | 54 | 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)`); | |
| 55 | if (bytes === "too_large") { | |
| 56 | return apiError("too_large", 413, `too large: at most ${cap / 1024} KB for a crash report, ${small / 1024} KB for a summary`); | |
| 57 | } | |
| 41 | 58 | let input: unknown; |
| 42 | 59 | try { |
| 43 | 60 | input = JSON.parse(new TextDecoder().decode(bytes)); |
| 44 | 61 | } catch { |
| 45 | 62 | return apiError("invalid_body", 422, USAGE_ERRORS.invalid_body); |
| 46 | 63 | } |
| 64 | if (isCrashBody(input)) { | |
| 65 | const limit = refused(app, request, "crash"); | |
| 66 | if (limit !== undefined) return limit; | |
| 67 | const crash = parseCrash(input); | |
| 68 | if (!crash.ok) return apiError("invalid_body", 400, crash.message); | |
| 69 | const kept = recordCrash(app.db, crash.value); | |
| 70 | if (kept.isNew) app.bus.append({ kind: "apple.crash_group", payload: { key: kept.key, version: kept.version, top: kept.top } }); | |
| 71 | return new Response(null, { status: 204, headers: { "cache-control": "no-store" } }); | |
| 72 | } | |
| 73 | const limit = refused(app, request, "usage"); | |
| 74 | if (limit !== undefined) return limit; | |
| 75 | if (bytes.length > small) return apiError("too_large", 413, `summary too large: at most ${small / 1024} KB (${small} bytes)`); | |
| 47 | 76 | const read = parseUsage(input); |
| 48 | 77 | if (!read.ok) return apiError(read.error, 422, USAGE_ERRORS[read.error]); |
| 49 | 78 | recordUsage(app.db, read.value); |
src/http/limits.ts +5
| @@ -52,6 +52,11 @@ export const RATE_CAPS = { | ||
| 52 | 52 | perForge: 300, |
| 53 | 53 | reason: "the app sends one summary a day; ten a minute from one address leaves room for retries and a shared network", |
| 54 | 54 | }, |
| 55 | appleCrash: { | |
| 56 | perClient: 6, | |
| 57 | perForge: 120, | |
| 58 | reason: "a crash report is sent by a person's choice, a few if the app keeps crashing; six a minute from one address leaves room for a shared network", | |
| 59 | }, | |
| 55 | 60 | } as const satisfies Record<string, { perClient: number; perForge: number; reason: string }>; |
| 56 | 61 | |
| 57 | 62 | const closing = new WeakSet<Request>(); |
src/kernel/body_caps.ts +4
| @@ -67,6 +67,10 @@ export const BODY_CAPS = { | ||
| 67 | 67 | bytes: 8 * KIB, |
| 68 | 68 | reason: "the Apple app's anonymous daily summary: a few dozen named counts and timings, so this is generous", |
| 69 | 69 | }, |
| 70 | appleCrash: { | |
| 71 | bytes: 64 * KIB, | |
| 72 | reason: "the Apple app's crash report, sent when the user chooses: up to 200 breadcrumb lines and ten findings of 12 frames, each line capped", | |
| 73 | }, | |
| 70 | 74 | gameSync: { |
| 71 | 75 | bytes: 2 * MIB, |
| 72 | 76 | 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 +21 −6
| @@ -4,7 +4,8 @@ | ||
| 4 | 4 | * one gate). Read-only; `j`/`k` move. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { USAGE_DAYS, readAppleUsage } from "../../actions/apple_usage.ts"; | |
| 7 | import { USAGE_DAYS, readAppleCrashes, readAppleUsage } from "../../actions/apple_usage.ts"; | |
| 8 | import type { CrashGroup } from "../../core/apple_crash.ts"; | |
| 8 | 9 | import type { UsageRead } from "../../core/apple_usage.ts"; |
| 9 | 10 | import type { Ctx, Screen } from "../app/app.ts"; |
| 10 | 11 | import { binding } from "../app/keys.ts"; |
| @@ -15,6 +16,18 @@ import { fill, len, split } from "../ui/layout.ts"; | ||
| 15 | 16 | import { ListState, drawList, type ListRow } from "./common.ts"; |
| 16 | 17 | import type { PaletteEntry } from "./entries.ts"; |
| 17 | 18 | |
| 19 | /** | |
| 20 | * The crash groups' rows, as the page shows them: the count, the frames, the breadcrumbs under it. | |
| 21 | */ | |
| 22 | export function crashRows(groups: readonly CrashGroup[]): ListRow[] { | |
| 23 | return groups.map((g): ListRow => ({ | |
| 24 | title: `${g.kind} in ${g.version}`, | |
| 25 | secondary: `${g.count} ${g.count === 1 ? "report" : "reports"}`, | |
| 26 | meta: `last ${g.lastAt.slice(0, 16).replace("T", " ")}`, | |
| 27 | below: [...(g.frames.length === 0 ? ["(no frames)"] : g.frames), ...(g.latest?.previousRun?.breadcrumbs ?? []).slice(-8).map((b) => `· ${b}`)], | |
| 28 | })); | |
| 29 | } | |
| 30 | ||
| 18 | 31 | /** The rows: each version with its counts and timings under it, then each day's summaries. */ |
| 19 | 32 | export function usageRows(read: UsageRead): ListRow[] { |
| 20 | 33 | const versions = read.versions.map((v): ListRow => ({ |
| @@ -39,17 +52,19 @@ export function appleUsageScreen(f: Session, ctx: Ctx): Screen { | ||
| 39 | 52 | const c = ctx.theme.c; |
| 40 | 53 | const [head, list] = split(area, "v", [len(1), fill(1)]); |
| 41 | 54 | const r = readAppleUsage(f.app, f.user); |
| 55 | const crashes = readAppleCrashes(f.app, f.user); | |
| 42 | 56 | const text = !r.ok |
| 43 | 57 | ? "App usage is for a forge admin." |
| 44 | : r.value.versions.length === 0 | |
| 45 | ? "Nothing yet: summaries come when people opt in in the Apple app." | |
| 58 | : r.value.versions.length === 0 && !(crashes.ok && crashes.value.length > 0) | |
| 59 | ? "Nothing yet: summaries come when people opt in in the Apple app; crash reports when they choose to send one." | |
| 46 | 60 | : `Anonymous summaries from the Apple app, the last ${USAGE_DAYS} days, per version then per day.`; |
| 47 | 61 | 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) : []); | |
| 62 | drawList(s, list!, c, state, [...(crashes.ok ? crashRows(crashes.value) : []), ...(r.ok ? usageRows(r.value) : [])]); | |
| 49 | 63 | }, |
| 50 | 64 | key(e) { |
| 51 | 65 | const r = readAppleUsage(f.app, f.user); |
| 52 | return state.key(e, r.ok ? usageRows(r.value).length : 0); | |
| 66 | const crashes = readAppleCrashes(f.app, f.user); | |
| 67 | return state.key(e, (r.ok ? usageRows(r.value).length : 0) + (crashes.ok ? crashes.value.length : 0)); | |
| 53 | 68 | }, |
| 54 | 69 | }; |
| 55 | 70 | } |
| @@ -58,7 +73,7 @@ export const entry: PaletteEntry = { | ||
| 58 | 73 | rank: 535, |
| 59 | 74 | id: "app-usage", |
| 60 | 75 | title: "App usage", |
| 61 | hint: "the Apple app's anonymous usage: counts and timings per version", | |
| 76 | hint: "the Apple app's crash reports, grouped, and its anonymous usage per version", | |
| 62 | 77 | after: ["limits"], |
| 63 | 78 | offered: (session) => session.user?.isAdmin === true && session.user.kind !== "agent", |
| 64 | 79 | run: (session, ctx) => ctx.push(appleUsageScreen(session, ctx)), |
src/view/policy.ts +5
| @@ -48,6 +48,11 @@ export function privacyRows(contact: string): PolicyRow[] { | ||
| 48 | 48 | words: |
| 49 | 49 | "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.", |
| 50 | 50 | }, |
| 51 | { | |
| 52 | label: "Crash reports in the Apple app", | |
| 53 | words: | |
| 54 | "Only when you choose to send one, after a crash or a hang, the app sends the forge you are signed in to: the app version and build, your OS version, the device kind (iPhone, iPad or Mac), when you sent it, what the app logged in its last run (screen names and times, at most 200 short lines), and the system's crash diagnostics: kind, date, signal, exception, termination reason and at most 12 code frames of each. It holds no account, address, device identifier, file content or text you typed. It is kept apart from usage totals, grouped with reports of the same crash, and shown to this forge's owner, who is told once of each new kind of crash. It goes to no other forge.", | |
| 55 | }, | |
| 51 | 56 | { |
| 52 | 57 | label: "Tracking and ads", |
| 53 | 58 | words: "No ads. No tracking across sites. Nothing about you is sold or shared.", |
src/web/pages/admin-telemetry.ts +31 −1
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | * the not-found page. The terminal's door is `src/tui/screens/appleusage.ts`. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { USAGE_DAYS, readAppleUsage } from "../../actions/apple_usage.ts"; | |
| 8 | import { USAGE_DAYS, readAppleCrashes, readAppleUsage } from "../../actions/apple_usage.ts"; | |
| 9 | import type { CrashGroup } from "../../core/apple_crash.ts"; | |
| 9 | 10 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 10 | 11 | import type { Ctx } from "../../http/context.ts"; |
| 11 | 12 | import { notFoundPage, pageHead } from "../chrome.ts"; |
| @@ -15,11 +16,34 @@ import { statusRow } from "./security.ts"; | ||
| 15 | 16 | |
| 16 | 17 | const TOP = 12; |
| 17 | 18 | |
| 19 | /** | |
| 20 | * One group of crash reports: its count, its frames and its newest report's breadcrumbs, readable. | |
| 21 | */ | |
| 22 | const crashGroup = (g: CrashGroup): Html => { | |
| 23 | const r = g.latest; | |
| 24 | const finding = r?.findings.find((f) => f.frames.length > 0) ?? r?.findings[0]; | |
| 25 | const crumbs = r?.previousRun?.breadcrumbs ?? []; | |
| 26 | return html`<section class="settings-block crash-group"> | |
| 27 | <h3>${g.kind} in ${g.version} <span class="muted">· ${String(g.count)} ${g.count === 1 ? "report" : "reports"}</span></h3> | |
| 28 | <p class="small muted">first ${g.firstAt.slice(0, 16).replace("T", " ")} · last ${g.lastAt.slice(0, 16).replace("T", " ")}${ | |
| 29 | r === undefined ? "" : ` · ${r.device}, ${r.os}` | |
| 30 | }${finding?.termination === undefined ? "" : ` · ${finding.termination}`}${finding?.signal === undefined ? "" : ` · signal ${finding.signal}`}${ | |
| 31 | finding?.exception === undefined ? "" : ` · exception ${finding.exception}` | |
| 32 | }</p> | |
| 33 | <pre class="mono">${g.frames.length === 0 ? "(no frames)" : g.frames.join("\n")}</pre> | |
| 34 | ${crumbs.length === 0 | |
| 35 | ? null | |
| 36 | : html`<details><summary>${String(crumbs.length)} breadcrumbs before it</summary><pre class="mono">${crumbs.join("\n")}</pre></details>`} | |
| 37 | </section>`; | |
| 38 | }; | |
| 39 | ||
| 18 | 40 | export function telemetryPage(ctx: Ctx): Response { |
| 19 | 41 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 20 | 42 | const read = timePhase(ctx.request, "usage", () => readAppleUsage(ctx.app, ctx.auth.user)); |
| 21 | 43 | if (!read.ok) return notFoundPage(ctx); |
| 22 | 44 | const { days, versions } = read.value; |
| 45 | const crashes = readAppleCrashes(ctx.app, ctx.auth.user); | |
| 46 | const groups = crashes.ok ? crashes.value : []; | |
| 23 | 47 | const rendering = performance.now(); |
| 24 | 48 | const rows = (items: Html[]): Html => html`<dl class="status-rows">${items}</dl>`; |
| 25 | 49 | const body = |
| @@ -59,6 +83,12 @@ export function telemetryPage(ctx: Ctx): Response { | ||
| 59 | 83 | body: html`${pageHead("App usage", { |
| 60 | 84 | sub: `What the Apple app's opted-in people used, per day and per version, the last ${USAGE_DAYS} days.`, |
| 61 | 85 | })} |
| 86 | <section id="crashes"> | |
| 87 | <h2>Crash reports</h2> | |
| 88 | ${groups.length === 0 | |
| 89 | ? html`<p class="muted" id="crashes-none">None. A report arrives only when someone chooses to send it from the Apple app.</p>` | |
| 90 | : html`<p class="small muted">Grouped by build and top frames, most recent first.</p>${groups.map(crashGroup)}`} | |
| 91 | </section> | |
| 62 | 92 | ${body}`, |
| 63 | 93 | }); |
| 64 | 94 | notePhase(ctx.request, "render", performance.now() - rendering); |
test/apple-crash.test.ts added +142
| @@ -0,0 +1,142 @@ | ||
| 1 | // The Apple app's crash reports (#18006): kept, grouped, shown to the owner and 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 { readAppleCrashes } from "../src/actions/apple_usage.ts"; | |
| 9 | import { createToken } from "../src/core/tokens.ts"; | |
| 10 | import { createUser, type User } from "../src/core/users.ts"; | |
| 11 | import { setNotifyUrl, startNotifier, type Notifier } from "../src/crew/notify.ts"; | |
| 12 | import { parseCrash } from "../src/core/apple_crash.ts"; | |
| 13 | import { BODY_CAPS } from "../src/http/limits.ts"; | |
| 14 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 15 | import { crashRows } from "../src/tui/screens/appleusage.ts"; | |
| 16 | import { privacyRows } from "../src/view/policy.ts"; | |
| 17 | ||
| 18 | let dir = ""; | |
| 19 | let app: App; | |
| 20 | let servers: Servers; | |
| 21 | let base = ""; | |
| 22 | let admin = ""; | |
| 23 | let owner: User; | |
| 24 | let bob: User; | |
| 25 | let notifier: Notifier; | |
| 26 | const posts: 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 mk = async (username: string, extra: Record<string, unknown> = {}) => { | |
| 34 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", ...extra }); | |
| 35 | if (!u.ok) throw new Error(u.error); | |
| 36 | return u.value; | |
| 37 | }; | |
| 38 | owner = await mk("alice", { adminIfFirst: true }); | |
| 39 | bob = await mk("bob"); | |
| 40 | admin = createToken(app.db, owner.id, "a", "admin").token; | |
| 41 | expect(setNotifyUrl(app.db, owner.id, "https://ntfy.example.test/alice-topic").ok).toBe(true); | |
| 42 | notifier = startNotifier(app, { | |
| 43 | forgeUrl: "https://forge.example.test", | |
| 44 | send: async (_url, body) => { | |
| 45 | posts.push(body); | |
| 46 | return true; | |
| 47 | }, | |
| 48 | }); | |
| 49 | await notifier.settled(); | |
| 50 | }, 30_000); | |
| 51 | afterAll(async () => { | |
| 52 | await notifier.close(); | |
| 53 | await servers.stop(); | |
| 54 | app.close(); | |
| 55 | await rm(dir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | const report = (frames: string[], over: Record<string, unknown> = {}) => ({ | |
| 59 | v: 1, | |
| 60 | kind: "crash", | |
| 61 | app: { version: "0.1", build: "34" }, | |
| 62 | os: "iOS 26.1", | |
| 63 | device: "iPhone", | |
| 64 | at: "2026-12-04T10:00:00Z", | |
| 65 | previousRun: { launchedAt: "2026-12-04T09:59:00Z", breadcrumbs: ["12:00:01 tab repos", "12:00:02 <b>open</b>"] }, | |
| 66 | findings: [{ kind: "crash", date: "2026-12-04T09:59:50Z", signal: "5", exception: "6", termination: "Namespace SIGNAL", version: "0.1", frames }], | |
| 67 | ...over, | |
| 68 | }); | |
| 69 | const send = (body: unknown) => | |
| 70 | fetch(`${base}/api/v1/telemetry/apple`, { method: "POST", headers: { "content-type": "application/json" }, body: typeof body === "string" ? body : JSON.stringify(body) }); | |
| 71 | ||
| 72 | test("two reports with the same frames and one different are two groups, 2 and 1, one notification each", async () => { | |
| 73 | const a = ["Forge +1445064", "SwiftUI +7"]; | |
| 74 | expect((await send(report(a))).status).toBe(204); | |
| 75 | expect((await send(report(a))).status).toBe(204); | |
| 76 | expect((await send(report(["Forge +99", "UIKit +1"]))).status).toBe(204); | |
| 77 | await notifier.settled(); | |
| 78 | const read = readAppleCrashes(app, owner); | |
| 79 | expect(read.ok).toBe(true); | |
| 80 | if (!read.ok) return; | |
| 81 | expect(read.value.map((g) => g.count).sort()).toEqual([1, 2]); | |
| 82 | expect(posts).toHaveLength(2); | |
| 83 | expect(posts.filter((p) => p.includes("Forge +1445064"))).toHaveLength(1); | |
| 84 | ||
| 85 | const page = await (await fetch(`${base}/admin/telemetry`, { headers: { authorization: `Bearer ${admin}` } })).text(); | |
| 86 | expect(page).toContain("2 reports"); | |
| 87 | expect(page).toContain("1 report"); | |
| 88 | expect(page).toContain("Forge +1445064"); | |
| 89 | expect(page).toContain("12:00:01 tab repos"); | |
| 90 | expect(page).toContain("<b>open</b>"); | |
| 91 | expect(page).not.toContain("<b>open</b>"); | |
| 92 | expect(crashRows(read.value).map((r) => r.secondary).sort()).toEqual(["1 report", "2 reports"]); | |
| 93 | }); | |
| 94 | ||
| 95 | test("nothing about the sender is kept, and usage rows are apart", async () => { | |
| 96 | const all = JSON.stringify([app.db.query("SELECT * FROM apple_crash").all(), app.db.query("SELECT * FROM apple_crash_group").all()]); | |
| 97 | expect(all).not.toContain("127.0.0.1"); | |
| 98 | expect(all).not.toContain(bob.id); | |
| 99 | expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM apple_usage").get()!.n).toBe(0); | |
| 100 | }); | |
| 101 | ||
| 102 | test("a planted extra field is a 400 in words over HTTP, and nothing is kept", async () => { | |
| 103 | const before = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM apple_crash").get()!.n; | |
| 104 | const res = await send({ ...report(["A +1"]), extra: 1 }); | |
| 105 | expect(res.status).toBe(400); | |
| 106 | expect(((await res.json()) as { message: string }).message).toContain('unknown field "extra"'); | |
| 107 | expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM apple_crash").get()!.n).toBe(before); | |
| 108 | }); | |
| 109 | ||
| 110 | test("the shape is strict at every level, and capped", () => { | |
| 111 | const bad = (body: unknown, words: string) => { | |
| 112 | const r = parseCrash(body); | |
| 113 | expect(r.ok).toBe(false); | |
| 114 | if (!r.ok) expect(r.message).toContain(words); | |
| 115 | }; | |
| 116 | bad(report(["A +1"], { app: { version: "0.1", build: "1", udid: "x" } }), "app has an unknown field"); | |
| 117 | const deep = report(["A +1"]); | |
| 118 | (deep.findings[0] as Record<string, unknown>).secret = "x"; | |
| 119 | bad(deep, "findings[0] has an unknown field"); | |
| 120 | bad(report(["A +1"], { previousRun: { breadcrumbs: [], extra: 1 } }), "previousRun has an unknown field"); | |
| 121 | bad(report(["A +1"], { device: 5 }), "device is a string"); | |
| 122 | bad(report(["A +1"], { at: "yesterday" }), "at is a date"); | |
| 123 | bad(report(Array.from({ length: 13 }, (_, i) => `F +${i}`)), "at most 12"); | |
| 124 | bad(report(["A +1"], { previousRun: { breadcrumbs: Array.from({ length: 201 }, () => "x") } }), "at most 200"); | |
| 125 | bad(report(["A +1"], { previousRun: { breadcrumbs: ["y".repeat(500)] } }), "at most 160 characters"); | |
| 126 | bad(report(["A\u0000 +1"]), "control character"); | |
| 127 | expect(parseCrash(report(["A +1"], { previousRun: { breadcrumbs: Array.from({ length: 200 }, () => "ok") } })).ok).toBe(true); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a body over 64 KB is a 413", async () => { | |
| 131 | expect(BODY_CAPS.appleCrash.bytes).toBe(64 * 1024); | |
| 132 | const res = await send(report(["A +1"], { os: "x".repeat(BODY_CAPS.appleCrash.bytes) })); | |
| 133 | expect(res.status).toBe(413); | |
| 134 | expect(await res.text()).toContain("64 KB"); | |
| 135 | }); | |
| 136 | ||
| 137 | test("only the owner reads them, and /privacy says what a report holds", async () => { | |
| 138 | expect(readAppleCrashes(app, bob)).toEqual({ ok: false, error: "not_found" }); | |
| 139 | expect(readAppleCrashes(app, null)).toEqual({ ok: false, error: "not_found" }); | |
| 140 | const row = privacyRows("x").find((r) => r.label === "Crash reports in the Apple app"); | |
| 141 | expect(row?.words).toContain("Only when you choose to send one"); | |
| 142 | }); |
new above
offline