cursedbelt-server 4.67.0 → 4.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `cursedbelt-server/client-issues/d1` — the server half of the page's issue record (forge task 4500).
3
+ *
4
+ * `cursedbelt/react/notifications`' `installIssueReporter` beacons every `raised` and `resolved`
5
+ * problem a page sees (a stuck video, a failing API, an uncaught error) to {@link CLIENT_ISSUES_PATH};
6
+ * this door writes one row per report into the app's own D1 `client_issues`, and autopilot's watch
7
+ * reads that table to file the work. Before it, a problem reached a fix only when the owner copied
8
+ * a report off his phone by hand.
9
+ *
10
+ * ```ts
11
+ * import { CLIENT_ISSUES_DDL, createD1ClientIssuesRecorder } from "cursedbelt-server/client-issues/d1";
12
+ * app.route("/api/client-issues", createD1ClientIssuesRecorder({ db: (c) => c.env.DB, resolveUser }));
13
+ * // and CLIENT_ISSUES_DDL in the app's schema
14
+ * ```
15
+ *
16
+ * 🔴 The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
17
+ * ({@link REDACTED_QUERY_KEY}, byte-identical to `cursedbelt`'s — the spec compares them) runs again
18
+ * here, and the account is the session's, never the body's. It may be mounted outside the session
19
+ * gate (a page that cannot sign in is exactly the page with a problem), so two bounds hold whoever
20
+ * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, and rows older
21
+ * than {@link ClientIssuesOptions.retentionMs} are purged on every write.
22
+ *
23
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`.
24
+ */
25
+ import type { Context } from "hono";
26
+ import { Hono } from "hono";
27
+ import type { D1LikeDatabase } from "../d1/types.js";
28
+ export declare const CLIENT_ISSUES_PATH = "/api/client-issues";
29
+ /** The table and its index, as one-line DDL for the app's schema. */
30
+ export declare const CLIENT_ISSUES_DDL: readonly string[];
31
+ /** 🔴 Must equal `cursedbelt/react/notifications`' `REDACTED_QUERY_KEY` — `d1.spec.ts` compares them. */
32
+ export declare const REDACTED_QUERY_KEY: RegExp;
33
+ /** Every `key=value` whose key is a {@link REDACTED_QUERY_KEY}, its value replaced by `…`. */
34
+ export declare function redactQueryValues(text: string): string;
35
+ /**
36
+ * The words of a title with what varies between occurrences taken out — numbers, ids, hosts,
37
+ * quoted names — so "Video 42 is stuck" and "Video 97 is stuck" are one group for autopilot.
38
+ */
39
+ export declare function issueStem(title: string): string;
40
+ export interface ClientIssueRow {
41
+ at: number;
42
+ change: "raised" | "resolved";
43
+ issue_id: string;
44
+ area: string;
45
+ stem: string;
46
+ tone: string;
47
+ outlook: string;
48
+ title: string;
49
+ occurrences: number;
50
+ started_at: number;
51
+ ended_at: number | null;
52
+ resolution: string;
53
+ page: string;
54
+ build: string;
55
+ user_agent: string;
56
+ user_key: string;
57
+ facts: string;
58
+ report: string;
59
+ }
60
+ /** One posted report as the row it becomes, or why it is refused. Pure, so the door is tested without a server. */
61
+ export declare function clientIssueDoor(body: unknown, context: {
62
+ now: number;
63
+ userAgent?: string;
64
+ userKey?: string | null;
65
+ }): {
66
+ row: ClientIssueRow;
67
+ } | {
68
+ error: string;
69
+ };
70
+ export interface ClientIssuesOptions {
71
+ /** The app's D1, or how to find it on the request. */
72
+ db: D1LikeDatabase | ((c: Context) => D1LikeDatabase);
73
+ /** The session's account, when there is one. Never read from the body. */
74
+ resolveUser?: (c: Context) => string | null;
75
+ /** Rows older than this are deleted on each write. Default 14 days. */
76
+ retentionMs?: number;
77
+ /** Reports past this many in the last hour are refused (429). Default 600. */
78
+ maxRowsPerHour?: number;
79
+ now?: () => number;
80
+ }
81
+ /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
82
+ export declare function recordClientIssueD1(db: D1LikeDatabase, row: ClientIssueRow, bounds: {
83
+ retentionMs: number;
84
+ maxRowsPerHour: number;
85
+ }): Promise<"recorded" | "capped">;
86
+ /**
87
+ * The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
88
+ * For an app that declares its routes as literals (`app.post("/api/client-issues", handler)`, so a
89
+ * route census can read them); {@link createD1ClientIssuesRecorder} is the same handler as a sub-app.
90
+ */
91
+ export declare function clientIssuesHandler(options: ClientIssuesOptions): (c: Context) => Promise<Response>;
92
+ /** The Hono app to mount at {@link CLIENT_ISSUES_PATH}: `POST /` takes one report, answers 204. */
93
+ export declare function createD1ClientIssuesRecorder(options: ClientIssuesOptions): Hono;
@@ -0,0 +1,149 @@
1
+ import { Hono } from "hono";
2
+ export const CLIENT_ISSUES_PATH = "/api/client-issues";
3
+ /** The table and its index, as one-line DDL for the app's schema. */
4
+ export const CLIENT_ISSUES_DDL = [
5
+ "CREATE TABLE IF NOT EXISTS client_issues ( id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, change TEXT NOT NULL, issue_id TEXT NOT NULL, area TEXT NOT NULL, stem TEXT NOT NULL, tone TEXT NOT NULL, outlook TEXT NOT NULL, title TEXT NOT NULL, occurrences INTEGER NOT NULL DEFAULT 1, started_at INTEGER NOT NULL, ended_at INTEGER, resolution TEXT NOT NULL DEFAULT '', page TEXT NOT NULL DEFAULT '', build TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '', user_key TEXT NOT NULL DEFAULT '', facts TEXT NOT NULL DEFAULT '[]', report TEXT NOT NULL DEFAULT '' )",
6
+ "CREATE INDEX IF NOT EXISTS idx_client_issues_at ON client_issues (at)",
7
+ ];
8
+ /** 🔴 Must equal `cursedbelt/react/notifications`' `REDACTED_QUERY_KEY` — `d1.spec.ts` compares them. */
9
+ export const REDACTED_QUERY_KEY = /token|sig|signature|key|secret|password|code|exp/i;
10
+ /** Every `key=value` whose key is a {@link REDACTED_QUERY_KEY}, its value replaced by `…`. */
11
+ export function redactQueryValues(text) {
12
+ return text.replace(/([?&;]([^=&#\s]+)=)([^&#;\s]*)/g, (whole, head, key) => REDACTED_QUERY_KEY.test(key) ? `${head}…` : whole);
13
+ }
14
+ /**
15
+ * The words of a title with what varies between occurrences taken out — numbers, ids, hosts,
16
+ * quoted names — so "Video 42 is stuck" and "Video 97 is stuck" are one group for autopilot.
17
+ */
18
+ export function issueStem(title) {
19
+ return title
20
+ .toLowerCase()
21
+ .replace(/https?:\/\/\S+/g, "<url>")
22
+ .replace(/["“'‘][^"”'’]*["”'’]/g, "<name>")
23
+ .replace(/\b[0-9a-f]{8,}\b/g, "#")
24
+ .replace(/\d+(?:[.,:]\d+)*/g, "#")
25
+ .replace(/\s+/g, " ")
26
+ .trim()
27
+ .slice(0, 160);
28
+ }
29
+ const cap = (value, max) => (typeof value === "string" ? redactQueryValues(value).slice(0, max) : "");
30
+ const whole = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : null;
31
+ /** One posted report as the row it becomes, or why it is refused. Pure, so the door is tested without a server. */
32
+ export function clientIssueDoor(body, context) {
33
+ if (!body || typeof body !== "object")
34
+ return { error: "expected a json object" };
35
+ const b = body;
36
+ if (b.v !== 1)
37
+ return { error: "unknown report version" };
38
+ if (b.change !== "raised" && b.change !== "resolved")
39
+ return { error: "change must be raised or resolved" };
40
+ const issueId = cap(b.id, 160);
41
+ const title = cap(b.title, 240);
42
+ const area = cap(b.area, 40);
43
+ if (!issueId || !title || !area)
44
+ return { error: "id, area and title are required" };
45
+ const startedAt = whole(b.startedAt) ?? context.now;
46
+ const facts = Array.isArray(b.facts)
47
+ ? b.facts
48
+ .slice(0, 20)
49
+ .filter((f) => !!f && typeof f === "object")
50
+ .map((f) => ({ label: cap(f.label, 80), value: cap(f.value, 400) }))
51
+ : [];
52
+ return {
53
+ row: {
54
+ at: context.now,
55
+ change: b.change,
56
+ issue_id: issueId,
57
+ area,
58
+ stem: issueStem(title),
59
+ tone: cap(b.tone, 16) || "warning",
60
+ outlook: cap(b.outlook, 300),
61
+ title,
62
+ occurrences: Math.max(1, whole(b.occurrences) ?? 1),
63
+ started_at: startedAt,
64
+ ended_at: whole(b.endedAt),
65
+ resolution: cap(b.resolution, 300),
66
+ page: cap(b.page, 400),
67
+ build: cap(b.build, 80),
68
+ user_agent: cap(context.userAgent, 300),
69
+ user_key: context.userKey ?? "",
70
+ facts: JSON.stringify(facts),
71
+ report: cap(b.report, 12_000),
72
+ },
73
+ };
74
+ }
75
+ const COLUMNS = [
76
+ "at",
77
+ "change",
78
+ "issue_id",
79
+ "area",
80
+ "stem",
81
+ "tone",
82
+ "outlook",
83
+ "title",
84
+ "occurrences",
85
+ "started_at",
86
+ "ended_at",
87
+ "resolution",
88
+ "page",
89
+ "build",
90
+ "user_agent",
91
+ "user_key",
92
+ "facts",
93
+ "report",
94
+ ];
95
+ /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
96
+ export async function recordClientIssueD1(db, row, bounds) {
97
+ const recent = await db
98
+ .prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
99
+ .bind(row.at - 3_600_000)
100
+ .first();
101
+ if ((recent?.n ?? 0) >= bounds.maxRowsPerHour)
102
+ return "capped";
103
+ await db.batch([
104
+ db
105
+ .prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
106
+ .bind(...COLUMNS.map((k) => row[k])),
107
+ db.prepare("DELETE FROM client_issues WHERE at < ?").bind(row.at - bounds.retentionMs),
108
+ ]);
109
+ return "recorded";
110
+ }
111
+ /**
112
+ * The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
113
+ * For an app that declares its routes as literals (`app.post("/api/client-issues", handler)`, so a
114
+ * route census can read them); {@link createD1ClientIssuesRecorder} is the same handler as a sub-app.
115
+ */
116
+ export function clientIssuesHandler(options) {
117
+ const now = options.now ?? (() => Date.now());
118
+ const bounds = {
119
+ retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
120
+ maxRowsPerHour: options.maxRowsPerHour ?? 600,
121
+ };
122
+ return async (c) => {
123
+ let body;
124
+ try {
125
+ body = JSON.parse(await c.req.text());
126
+ }
127
+ catch {
128
+ return c.json({ error: "expected a json body" }, 400);
129
+ }
130
+ const door = clientIssueDoor(body, {
131
+ now: now(),
132
+ userAgent: c.req.header("user-agent") ?? "",
133
+ userKey: options.resolveUser?.(c) ?? null,
134
+ });
135
+ if ("error" in door)
136
+ return c.json({ error: door.error }, 400);
137
+ const db = typeof options.db === "function" ? options.db(c) : options.db;
138
+ const outcome = await recordClientIssueD1(db, door.row, bounds);
139
+ if (outcome === "capped")
140
+ return c.json({ error: "too many reports this hour" }, 429);
141
+ return c.body(null, 204);
142
+ };
143
+ }
144
+ /** The Hono app to mount at {@link CLIENT_ISSUES_PATH}: `POST /` takes one report, answers 204. */
145
+ export function createD1ClientIssuesRecorder(options) {
146
+ const app = new Hono();
147
+ app.post("/", clientIssuesHandler(options));
148
+ return app;
149
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.67.0",
3
+ "version": "4.68.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -120,6 +120,12 @@
120
120
  "source": "./src/server/middleware/bodyLimit.ts",
121
121
  "import": "./dist/server/middleware/bodyLimit.js"
122
122
  },
123
+ "./client-issues/d1": {
124
+ "types": "./dist/server/clientIssues/d1.d.ts",
125
+ "bun": "./src/server/clientIssues/d1.ts",
126
+ "source": "./src/server/clientIssues/d1.ts",
127
+ "import": "./dist/server/clientIssues/d1.js"
128
+ },
123
129
  "./d1": {
124
130
  "types": "./dist/server/d1/index.d.ts",
125
131
  "bun": "./src/server/d1/index.ts",
@@ -435,7 +441,7 @@
435
441
  "@node-rs/argon2": "^2.0.2",
436
442
  "@types/bun": "^1.3.14",
437
443
  "@types/node": "^24",
438
- "cursedbelt": "^5.135.1",
444
+ "cursedbelt": "^5.138.0",
439
445
  "hono": "4.12.28",
440
446
  "kysely": "^0.28.17",
441
447
  "kysely-bun-sqlite": "^0.4.0",
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The page's issue reports land in the app's D1 as one row each, redacted, bounded and purged
3
+ * (forge task 4500).
4
+ */
5
+ import { Database } from 'bun:sqlite';
6
+ import { describe, expect, test } from 'bun:test';
7
+ import { readFileSync } from 'node:fs';
8
+ import { createRequire } from 'node:module';
9
+ import { Hono } from 'hono';
10
+ import { createLocalD1 } from '../d1/local.js';
11
+ import {
12
+ CLIENT_ISSUES_DDL,
13
+ REDACTED_QUERY_KEY,
14
+ clientIssueDoor,
15
+ clientIssuesHandler,
16
+ createD1ClientIssuesRecorder,
17
+ issueStem,
18
+ redactQueryValues,
19
+ } from './d1.js';
20
+
21
+ const fresh = () => {
22
+ const sqlite = new Database(':memory:');
23
+ for (const ddl of CLIENT_ISSUES_DDL) sqlite.run(ddl);
24
+ return { sqlite, db: createLocalD1(sqlite) };
25
+ };
26
+
27
+ const report = (over: Record<string, unknown> = {}) => ({
28
+ v: 1,
29
+ app: 'collections',
30
+ build: 'abc1234',
31
+ change: 'raised',
32
+ id: 'video:42',
33
+ area: 'video',
34
+ tone: 'warning',
35
+ title: 'Video 42 is stuck loading',
36
+ outlook: 'Needs a code fix.',
37
+ occurrences: 2,
38
+ startedAt: 900,
39
+ page: '/watch/42?token=SECRET',
40
+ facts: [{ label: 'Segment', value: 'https://media.test/s.ts?sig=SIG&n=1' }],
41
+ report: 'Video 42 is stuck loading\n GET https://media.test/s.ts?exp=1&sig=SIG → 503',
42
+ ...over,
43
+ });
44
+
45
+ const post = (app: ReturnType<typeof createD1ClientIssuesRecorder>, body: unknown) =>
46
+ app.request('/', { method: 'POST', body: typeof body === 'string' ? body : JSON.stringify(body), headers: { 'user-agent': 'iPhone' } });
47
+
48
+ describe('🔴 a posted report is one redacted row (forge task 4500)', () => {
49
+ test('a raise and its end are two rows, nothing secret in either', async () => {
50
+ const { sqlite, db } = fresh();
51
+ let clock = 1_000;
52
+ const app = createD1ClientIssuesRecorder({ db, resolveUser: () => 'u1', now: () => clock });
53
+ expect((await post(app, report())).status).toBe(204);
54
+ clock = 2_000;
55
+ expect((await post(app, report({ change: 'resolved', endedAt: 1_900, resolution: 'Played' }))).status).toBe(204);
56
+ const rows = sqlite.query('SELECT * FROM client_issues ORDER BY id').all() as Record<string, unknown>[];
57
+ expect(rows.map((r) => r.change)).toEqual(['raised', 'resolved']);
58
+ expect(rows[0]).toMatchObject({ at: 1_000, issue_id: 'video:42', area: 'video', stem: 'video # is stuck loading', user_agent: 'iPhone', user_key: 'u1', build: 'abc1234', ended_at: null });
59
+ expect(rows[1]).toMatchObject({ ended_at: 1_900, resolution: 'Played' });
60
+ expect(JSON.stringify(rows)).not.toMatch(/SECRET|SIG/);
61
+ expect(rows[0]?.page).toBe('/watch/42?token=…');
62
+ });
63
+
64
+ test('a malformed body is a 400 and writes nothing', async () => {
65
+ const { sqlite, db } = fresh();
66
+ const app = createD1ClientIssuesRecorder({ db });
67
+ for (const body of ['not json', report({ v: 2 }), report({ change: 'updated' }), report({ title: '' })]) {
68
+ expect((await post(app, body)).status).toBe(400);
69
+ }
70
+ expect(sqlite.query('SELECT COUNT(*) AS n FROM client_issues').get()).toEqual({ n: 0 });
71
+ });
72
+
73
+ test('the account is the session’s, never the body’s, and every string is capped', () => {
74
+ const door = clientIssueDoor(report({ user_key: 'forged', title: 'x'.repeat(5_000), report: 'y'.repeat(50_000) }), { now: 1, userKey: null });
75
+ if ('error' in door) throw new Error(door.error);
76
+ expect(door.row.user_key).toBe('');
77
+ expect(door.row.title.length).toBe(240);
78
+ expect(door.row.report.length).toBe(12_000);
79
+ });
80
+ });
81
+
82
+ describe('clientIssuesHandler is the same door, for a literal route', () => {
83
+ test('app.post(path, handler) records the row', async () => {
84
+ const { sqlite, db } = fresh();
85
+ const app = new Hono().post('/api/client-issues', clientIssuesHandler({ db, now: () => 7 }));
86
+ const res = await app.request('/api/client-issues', { method: 'POST', body: JSON.stringify(report()) });
87
+ expect(res.status).toBe(204);
88
+ expect(sqlite.query('SELECT at FROM client_issues').all()).toEqual([{ at: 7 }]);
89
+ });
90
+ });
91
+
92
+ describe('🔴 the door is bounded whoever calls it', () => {
93
+ test('past maxRowsPerHour it answers 429 and writes nothing more', async () => {
94
+ const { sqlite, db } = fresh();
95
+ const app = createD1ClientIssuesRecorder({ db, maxRowsPerHour: 2, now: () => 5_000_000 });
96
+ expect((await post(app, report())).status).toBe(204);
97
+ expect((await post(app, report())).status).toBe(204);
98
+ expect((await post(app, report())).status).toBe(429);
99
+ expect(sqlite.query('SELECT COUNT(*) AS n FROM client_issues').get()).toEqual({ n: 2 });
100
+ });
101
+
102
+ test('a write purges the rows older than the retention', async () => {
103
+ const { sqlite, db } = fresh();
104
+ let clock = 1_000;
105
+ const app = createD1ClientIssuesRecorder({ db, retentionMs: 10_000, now: () => clock });
106
+ await post(app, report({ id: 'old' }));
107
+ clock = 20_000;
108
+ await post(app, report({ id: 'new' }));
109
+ expect(sqlite.query('SELECT issue_id FROM client_issues').all()).toEqual([{ issue_id: 'new' }]);
110
+ });
111
+ });
112
+
113
+ describe('issueStem groups what varies between occurrences', () => {
114
+ test('numbers, hashes, urls and quoted names drop out', () => {
115
+ expect(issueStem('Video 42 is stuck')).toBe(issueStem('Video 97 is stuck'));
116
+ expect(issueStem('“Holiday” failed: https://x.test/a/b')).toBe('<name> failed: <url>');
117
+ expect(issueStem('Chunk 3fa9c2d1e0 failed to load')).toBe('chunk # failed to load');
118
+ expect(issueStem('The server is failing (HTTP 503)')).toBe('the server is failing (http #)');
119
+ });
120
+ test('redactQueryValues leaves what is not a secret', () => {
121
+ expect(redactQueryValues('a?sig=1&n=2;exp=3')).toBe('a?sig=…&n=2;exp=…');
122
+ });
123
+ });
124
+
125
+ describe('🔴 the redaction is the page’s own rule, not a second copy that drifts', () => {
126
+ test('equals cursedbelt’s REDACTED_QUERY_KEY once the installed cursedbelt exports it', async () => {
127
+ const require = createRequire(import.meta.url);
128
+ const manifest = require.resolve('cursedbelt/package.json');
129
+ const version = (JSON.parse(readFileSync(manifest, 'utf8')) as { version: string }).version;
130
+ const belt = (await import('cursedbelt/react/notifications')) as { REDACTED_QUERY_KEY?: RegExp };
131
+ const [major = 0, minor = 0] = version.split('.').map(Number);
132
+ // 5.140.0 is the first cursedbelt with the export; the publish bumps this devDependency past it.
133
+ if (major > 5 || (major === 5 && minor >= 140)) expect(belt.REDACTED_QUERY_KEY).toBeDefined();
134
+ if (belt.REDACTED_QUERY_KEY) {
135
+ expect(REDACTED_QUERY_KEY.source).toBe(belt.REDACTED_QUERY_KEY.source);
136
+ expect(REDACTED_QUERY_KEY.flags).toBe(belt.REDACTED_QUERY_KEY.flags);
137
+ }
138
+ });
139
+ });
@@ -0,0 +1,221 @@
1
+ /**
2
+ * `cursedbelt-server/client-issues/d1` — the server half of the page's issue record (forge task 4500).
3
+ *
4
+ * `cursedbelt/react/notifications`' `installIssueReporter` beacons every `raised` and `resolved`
5
+ * problem a page sees (a stuck video, a failing API, an uncaught error) to {@link CLIENT_ISSUES_PATH};
6
+ * this door writes one row per report into the app's own D1 `client_issues`, and autopilot's watch
7
+ * reads that table to file the work. Before it, a problem reached a fix only when the owner copied
8
+ * a report off his phone by hand.
9
+ *
10
+ * ```ts
11
+ * import { CLIENT_ISSUES_DDL, createD1ClientIssuesRecorder } from "cursedbelt-server/client-issues/d1";
12
+ * app.route("/api/client-issues", createD1ClientIssuesRecorder({ db: (c) => c.env.DB, resolveUser }));
13
+ * // and CLIENT_ISSUES_DDL in the app's schema
14
+ * ```
15
+ *
16
+ * 🔴 The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
17
+ * ({@link REDACTED_QUERY_KEY}, byte-identical to `cursedbelt`'s — the spec compares them) runs again
18
+ * here, and the account is the session's, never the body's. It may be mounted outside the session
19
+ * gate (a page that cannot sign in is exactly the page with a problem), so two bounds hold whoever
20
+ * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, and rows older
21
+ * than {@link ClientIssuesOptions.retentionMs} are purged on every write.
22
+ *
23
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`.
24
+ */
25
+ import type { Context } from "hono";
26
+ import { Hono } from "hono";
27
+ import type { D1LikeDatabase } from "../d1/types.js";
28
+
29
+ export const CLIENT_ISSUES_PATH = "/api/client-issues";
30
+
31
+ /** The table and its index, as one-line DDL for the app's schema. */
32
+ export const CLIENT_ISSUES_DDL: readonly string[] = [
33
+ "CREATE TABLE IF NOT EXISTS client_issues ( id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, change TEXT NOT NULL, issue_id TEXT NOT NULL, area TEXT NOT NULL, stem TEXT NOT NULL, tone TEXT NOT NULL, outlook TEXT NOT NULL, title TEXT NOT NULL, occurrences INTEGER NOT NULL DEFAULT 1, started_at INTEGER NOT NULL, ended_at INTEGER, resolution TEXT NOT NULL DEFAULT '', page TEXT NOT NULL DEFAULT '', build TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '', user_key TEXT NOT NULL DEFAULT '', facts TEXT NOT NULL DEFAULT '[]', report TEXT NOT NULL DEFAULT '' )",
34
+ "CREATE INDEX IF NOT EXISTS idx_client_issues_at ON client_issues (at)",
35
+ ];
36
+
37
+ /** 🔴 Must equal `cursedbelt/react/notifications`' `REDACTED_QUERY_KEY` — `d1.spec.ts` compares them. */
38
+ export const REDACTED_QUERY_KEY = /token|sig|signature|key|secret|password|code|exp/i;
39
+
40
+ /** Every `key=value` whose key is a {@link REDACTED_QUERY_KEY}, its value replaced by `…`. */
41
+ export function redactQueryValues(text: string): string {
42
+ return text.replace(/([?&;]([^=&#\s]+)=)([^&#;\s]*)/g, (whole, head: string, key: string) =>
43
+ REDACTED_QUERY_KEY.test(key) ? `${head}…` : whole,
44
+ );
45
+ }
46
+
47
+ /**
48
+ * The words of a title with what varies between occurrences taken out — numbers, ids, hosts,
49
+ * quoted names — so "Video 42 is stuck" and "Video 97 is stuck" are one group for autopilot.
50
+ */
51
+ export function issueStem(title: string): string {
52
+ return title
53
+ .toLowerCase()
54
+ .replace(/https?:\/\/\S+/g, "<url>")
55
+ .replace(/["“'‘][^"”'’]*["”'’]/g, "<name>")
56
+ .replace(/\b[0-9a-f]{8,}\b/g, "#")
57
+ .replace(/\d+(?:[.,:]\d+)*/g, "#")
58
+ .replace(/\s+/g, " ")
59
+ .trim()
60
+ .slice(0, 160);
61
+ }
62
+
63
+ export interface ClientIssueRow {
64
+ at: number;
65
+ change: "raised" | "resolved";
66
+ issue_id: string;
67
+ area: string;
68
+ stem: string;
69
+ tone: string;
70
+ outlook: string;
71
+ title: string;
72
+ occurrences: number;
73
+ started_at: number;
74
+ ended_at: number | null;
75
+ resolution: string;
76
+ page: string;
77
+ build: string;
78
+ user_agent: string;
79
+ user_key: string;
80
+ facts: string;
81
+ report: string;
82
+ }
83
+
84
+ const cap = (value: unknown, max: number): string => (typeof value === "string" ? redactQueryValues(value).slice(0, max) : "");
85
+ const whole = (value: unknown): number | null =>
86
+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : null;
87
+
88
+ /** One posted report as the row it becomes, or why it is refused. Pure, so the door is tested without a server. */
89
+ export function clientIssueDoor(
90
+ body: unknown,
91
+ context: { now: number; userAgent?: string; userKey?: string | null },
92
+ ): { row: ClientIssueRow } | { error: string } {
93
+ if (!body || typeof body !== "object") return { error: "expected a json object" };
94
+ const b = body as Record<string, unknown>;
95
+ if (b.v !== 1) return { error: "unknown report version" };
96
+ if (b.change !== "raised" && b.change !== "resolved") return { error: "change must be raised or resolved" };
97
+ const issueId = cap(b.id, 160);
98
+ const title = cap(b.title, 240);
99
+ const area = cap(b.area, 40);
100
+ if (!issueId || !title || !area) return { error: "id, area and title are required" };
101
+ const startedAt = whole(b.startedAt) ?? context.now;
102
+ const facts = Array.isArray(b.facts)
103
+ ? b.facts
104
+ .slice(0, 20)
105
+ .filter((f): f is { label: unknown; value: unknown } => !!f && typeof f === "object")
106
+ .map((f) => ({ label: cap(f.label, 80), value: cap(f.value, 400) }))
107
+ : [];
108
+ return {
109
+ row: {
110
+ at: context.now,
111
+ change: b.change,
112
+ issue_id: issueId,
113
+ area,
114
+ stem: issueStem(title),
115
+ tone: cap(b.tone, 16) || "warning",
116
+ outlook: cap(b.outlook, 300),
117
+ title,
118
+ occurrences: Math.max(1, whole(b.occurrences) ?? 1),
119
+ started_at: startedAt,
120
+ ended_at: whole(b.endedAt),
121
+ resolution: cap(b.resolution, 300),
122
+ page: cap(b.page, 400),
123
+ build: cap(b.build, 80),
124
+ user_agent: cap(context.userAgent, 300),
125
+ user_key: context.userKey ?? "",
126
+ facts: JSON.stringify(facts),
127
+ report: cap(b.report, 12_000),
128
+ },
129
+ };
130
+ }
131
+
132
+ const COLUMNS = [
133
+ "at",
134
+ "change",
135
+ "issue_id",
136
+ "area",
137
+ "stem",
138
+ "tone",
139
+ "outlook",
140
+ "title",
141
+ "occurrences",
142
+ "started_at",
143
+ "ended_at",
144
+ "resolution",
145
+ "page",
146
+ "build",
147
+ "user_agent",
148
+ "user_key",
149
+ "facts",
150
+ "report",
151
+ ] as const satisfies readonly (keyof ClientIssueRow)[];
152
+
153
+ export interface ClientIssuesOptions {
154
+ /** The app's D1, or how to find it on the request. */
155
+ db: D1LikeDatabase | ((c: Context) => D1LikeDatabase);
156
+ /** The session's account, when there is one. Never read from the body. */
157
+ resolveUser?: (c: Context) => string | null;
158
+ /** Rows older than this are deleted on each write. Default 14 days. */
159
+ retentionMs?: number;
160
+ /** Reports past this many in the last hour are refused (429). Default 600. */
161
+ maxRowsPerHour?: number;
162
+ now?: () => number;
163
+ }
164
+
165
+ /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
166
+ export async function recordClientIssueD1(
167
+ db: D1LikeDatabase,
168
+ row: ClientIssueRow,
169
+ bounds: { retentionMs: number; maxRowsPerHour: number },
170
+ ): Promise<"recorded" | "capped"> {
171
+ const recent = await db
172
+ .prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
173
+ .bind(row.at - 3_600_000)
174
+ .first<{ n: number }>();
175
+ if ((recent?.n ?? 0) >= bounds.maxRowsPerHour) return "capped";
176
+ await db.batch([
177
+ db
178
+ .prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
179
+ .bind(...COLUMNS.map((k) => row[k])),
180
+ db.prepare("DELETE FROM client_issues WHERE at < ?").bind(row.at - bounds.retentionMs),
181
+ ]);
182
+ return "recorded";
183
+ }
184
+
185
+ /**
186
+ * The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
187
+ * For an app that declares its routes as literals (`app.post("/api/client-issues", handler)`, so a
188
+ * route census can read them); {@link createD1ClientIssuesRecorder} is the same handler as a sub-app.
189
+ */
190
+ export function clientIssuesHandler(options: ClientIssuesOptions): (c: Context) => Promise<Response> {
191
+ const now = options.now ?? (() => Date.now());
192
+ const bounds = {
193
+ retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
194
+ maxRowsPerHour: options.maxRowsPerHour ?? 600,
195
+ };
196
+ return async (c) => {
197
+ let body: unknown;
198
+ try {
199
+ body = JSON.parse(await c.req.text());
200
+ } catch {
201
+ return c.json({ error: "expected a json body" }, 400);
202
+ }
203
+ const door = clientIssueDoor(body, {
204
+ now: now(),
205
+ userAgent: c.req.header("user-agent") ?? "",
206
+ userKey: options.resolveUser?.(c) ?? null,
207
+ });
208
+ if ("error" in door) return c.json({ error: door.error }, 400);
209
+ const db = typeof options.db === "function" ? options.db(c) : options.db;
210
+ const outcome = await recordClientIssueD1(db, door.row, bounds);
211
+ if (outcome === "capped") return c.json({ error: "too many reports this hour" }, 429);
212
+ return c.body(null, 204);
213
+ };
214
+ }
215
+
216
+ /** The Hono app to mount at {@link CLIENT_ISSUES_PATH}: `POST /` takes one report, answers 204. */
217
+ export function createD1ClientIssuesRecorder(options: ClientIssuesOptions): Hono {
218
+ const app = new Hono();
219
+ app.post("/", clientIssuesHandler(options));
220
+ return app;
221
+ }
@@ -139,6 +139,18 @@ describe('🔴 cursedbelt-server/engagement/d1 — a Worker mounts it (task 2096
139
139
  });
140
140
  });
141
141
 
142
+ describe('🔴 cursedbelt-server/client-issues/d1 — a Worker mounts it (forge task 4500)', () => {
143
+ test('reaches no `bun:` module at runtime, and its export map points at the real module', () => {
144
+ const { files, bunImports } = runtimeGraph(join(import.meta.dir, 'clientIssues', 'd1.ts'));
145
+ expect(bunImports).toEqual([]);
146
+ expect(files.some((f) => f.endsWith('clientIssues/d1.ts'))).toBe(true);
147
+ const pkg = JSON.parse(readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')) as {
148
+ exports: Record<string, { import?: string }>;
149
+ };
150
+ expect(pkg.exports['./client-issues/d1']?.import).toBe('./dist/server/clientIssues/d1.js');
151
+ });
152
+ });
153
+
142
154
  /**
143
155
  * The three D1 halves `apps/family`'s Worker port needs (task 393). Each sits beside a sync
144
156
  * store that is `bun:sqlite` by construction, so the walk also proves the split held: the