neurastream 0.2.86 → 0.3.2

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,1008 @@
1
+ // Team queue server (plan 20261027_1305 P2a; claims P2b). Binds the tailnet address only.
2
+ // Every route, health included, checks Host, then the peer, then whois membership,
3
+ // then Origin on every write. Plan text is stored only when its header is Queue: team.
4
+
5
+ import { Database } from "bun:sqlite";
6
+ import { createHash, randomBytes } from "node:crypto";
7
+ import { chmodSync, mkdirSync } from "node:fs";
8
+ import { dirname } from "node:path";
9
+ import { claimExpired } from "./claims.ts";
10
+ import { nowSec, strftime } from "./clock.ts";
11
+ import { MAIN_ID_RE } from "./guards.ts";
12
+ import { ANSWER_MAX, fieldsOf, hostAllowlist, isLoopback, isTailnet, jsonFail, jsonSent, originIsHost, pageCsp, renderTeamPage, teamSection, textRes, type UiHttpServer } from "./owner-ui.ts";
13
+ import { headerField, parsePlan, sha } from "./queue/lib.ts";
14
+ import { remotePath } from "./mr-sweep.ts";
15
+ import type { Tailscale } from "./tailscale.ts";
16
+ import { viewPlanRows } from "./team-client.ts";
17
+ import { remoteListed } from "./team-labels.ts";
18
+
19
+ const BODY_MAX = 1024 * 1024;
20
+ const PLAN_MAX = 256 * 1024;
21
+ const WRITES_PER_MIN = 60;
22
+ const WRITE_METHOD: Record<string, true> = { PUT: true, POST: true, DELETE: true };
23
+
24
+ export interface TeamServerConfig {
25
+ team: string;
26
+ admin: string;
27
+ leader: string;
28
+ repos: string[];
29
+ members: string[];
30
+ }
31
+
32
+ export interface TeamServerOptions {
33
+ tailscale: Tailscale;
34
+ config: TeamServerConfig;
35
+ /** SQLite file. Tests pass a temp path; nothing here touches a home directory. */
36
+ dbPath: string;
37
+ /** Bind port. Tests pass 0. */
38
+ port: number;
39
+ /** Bind address. Default: tailscale.ip4(). Tests bind a loopback address. */
40
+ hostname?: string;
41
+ peerOf?: (req: Request, server: UiHttpServer) => string;
42
+ clock?: () => number;
43
+ /** Minutes without a heartbeat before a claim may be taken over (`queue.claim_ttl_min`). Required: this server has no default. */
44
+ claimTtlMin: number;
45
+ }
46
+
47
+ export interface TeamServer {
48
+ stop(): void;
49
+ hostname: string;
50
+ port: number;
51
+ }
52
+
53
+ /** Stable id for a plan file: hash of the normalized origin plus the relative path. Null when the origin does not parse. */
54
+ export function teamPlanId(remote: string, relPath: string): string | null {
55
+ const path = remotePath(remote);
56
+ if (!path || !relPath) return null;
57
+ return createHash("sha256").update(`${path}\n${relPath}`).digest("hex");
58
+ }
59
+
60
+ function bindsEveryInterface(hostname: string): boolean {
61
+ const octets = hostname.split(".");
62
+ return octets.length === 4 && octets.every(octet => /^0+$/.test(octet));
63
+ }
64
+
65
+ function json(body: unknown, status: number): Response {
66
+ return Response.json(body, { status });
67
+ }
68
+
69
+ function relPathOk(relPath: string): boolean {
70
+ if (!relPath || relPath.startsWith("/") || relPath.includes("\\") || relPath.includes("\0")) return false;
71
+ return relPath.split("/").every(seg => seg !== "" && seg !== "..");
72
+ }
73
+
74
+ /** Body bytes, or "too-big" before any JSON parse. A declared length over the cap is refused without reading. */
75
+ async function readBody(req: Request): Promise<Uint8Array | "too-big"> {
76
+ const declared = req.headers.get("content-length");
77
+ if (declared !== null) {
78
+ const n = Number(declared);
79
+ if (!Number.isFinite(n) || n < 0 || n > BODY_MAX) return "too-big";
80
+ }
81
+ if (!req.body) return new Uint8Array();
82
+ const bytes = new Uint8Array(await req.arrayBuffer());
83
+ if (bytes.byteLength > BODY_MAX) return "too-big";
84
+ return bytes;
85
+ }
86
+
87
+ interface PlanRow {
88
+ sha: string;
89
+ text: string;
90
+ remote: string;
91
+ rel_path: string;
92
+ updated_by: string;
93
+ updated_at: number;
94
+ }
95
+
96
+ interface PutArgs {
97
+ id: string;
98
+ remote: string;
99
+ relPath: string;
100
+ text: string;
101
+ nextSha: string;
102
+ base: string | null;
103
+ login: string;
104
+ now: number;
105
+ route: string;
106
+ note: string | null;
107
+ }
108
+
109
+ /** One claim row. `id` is the plan id; `login` is the whois login that holds it. */
110
+ interface ClaimRow {
111
+ id: string;
112
+ team: string;
113
+ main: string;
114
+ host: string;
115
+ pid: number;
116
+ since: number;
117
+ beat: number;
118
+ login: string;
119
+ }
120
+
121
+ interface AuditRow {
122
+ id: number;
123
+ login: string;
124
+ time: number;
125
+ route: string;
126
+ plan_id: string | null;
127
+ }
128
+
129
+ interface ApprovalRow {
130
+ plan: string;
131
+ login: string;
132
+ time: number;
133
+ }
134
+
135
+ type ClaimOutcome = { status: 200; claim: ClaimRow } | { status: 404 } | { status: 403 } | { status: 409; held: ClaimRow };
136
+ type BeatOutcome = { status: 200; claim: ClaimRow } | { status: 404 } | { status: 403 };
137
+ type ReleaseOutcome = { status: 200 } | { status: 404 } | { status: 403 };
138
+ type ApproveOutcome = { status: 200; approval: ApprovalRow | null } | { status: 404 } | { status: 403 };
139
+
140
+ /** A claim is the caller's own when both the login and the Main id match. */
141
+ function isOwn(row: ClaimRow, login: string, main: string): boolean {
142
+ return row.login === login && row.main === main;
143
+ }
144
+
145
+ /** A claim as the wire shows it. `mine` is true when the caller's login holds it. */
146
+ export interface ClaimView {
147
+ plan: string;
148
+ main: string;
149
+ host: string;
150
+ pid: number;
151
+ since: number;
152
+ beat: number;
153
+ login: string;
154
+ mine: boolean;
155
+ }
156
+
157
+ function wireClaim(row: ClaimRow, login: string): ClaimView {
158
+ return {
159
+ plan: row.id,
160
+ main: row.main,
161
+ host: row.host,
162
+ pid: row.pid,
163
+ since: row.since,
164
+ beat: row.beat,
165
+ login: row.login,
166
+ mine: row.login === login,
167
+ };
168
+ }
169
+
170
+ /** The body as a JSON object, or null when it is not one. */
171
+ function jsonObject(body: Uint8Array): Record<string, unknown> | null {
172
+ let parsed: unknown;
173
+ try {
174
+ parsed = JSON.parse(new TextDecoder().decode(body));
175
+ } catch {
176
+ return null;
177
+ }
178
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
179
+ return parsed as Record<string, unknown>;
180
+ }
181
+
182
+ /** The form fields of a POST whose body the write gate has already read. */
183
+ function formOf(req: Request, body: Uint8Array): Promise<Record<string, string>> {
184
+ return fieldsOf(new Request(req.url, { method: "POST", headers: req.headers, body: new TextDecoder().decode(body) }));
185
+ }
186
+
187
+ /** A JSON client (Accept asks for application/json) gets JSON; the page's scriptless forms get a 303 back to the page. */
188
+ function wantsJson(req: Request): boolean {
189
+ return (req.headers.get("accept") ?? "").includes("application/json");
190
+ }
191
+
192
+ function pageDone(req: Request, sent: string): Response {
193
+ return wantsJson(req) ? jsonSent(sent) : new Response(null, { status: 303, headers: { location: "/" } });
194
+ }
195
+
196
+ function pageRefused(req: Request, error: string, status: number): Response {
197
+ return wantsJson(req) ? jsonFail(error, status) : textRes(error, status);
198
+ }
199
+
200
+ /** The reply when an earlier answer to the same question already won: the new answer is kept, and the sender is told who won. */
201
+ function earlierReply(req: Request, earlier: FirstAnswer): Response {
202
+ const note = `answer kept; an earlier answer by ${earlier.login} at ${strftime(earlier.time, "%H:%M")} won: "${earlier.answer}"`;
203
+ return wantsJson(req) ? jsonSent(note) : textRes(note, 200);
204
+ }
205
+
206
+ /** A path segment decoded, or null when its percent-encoding is bad. */
207
+ function decodeSegment(raw: string): string | null {
208
+ try {
209
+ return decodeURIComponent(raw);
210
+ } catch {
211
+ return null;
212
+ }
213
+ }
214
+
215
+ const LOGIN_RE = /^[^\s\p{Cc}]{1,256}$/u;
216
+ const LOGIN_ERROR = "login must be 1 to 256 characters with no whitespace or control character";
217
+ const ADMIN_REMOVE = "the admin login cannot be removed";
218
+ const NO_MEMBER = "no such member";
219
+ const CROSS_REVIEW = "forbidden: cross review: you last claimed this plan; another member approves it";
220
+
221
+ function validLogin(login: unknown): login is string {
222
+ return typeof login === "string" && LOGIN_RE.test(login);
223
+ }
224
+
225
+ /** True once the first start has seeded the members table. Before that the team is not initialised. */
226
+ function initialised(db: Database): boolean {
227
+ return db.query("SELECT 1 FROM meta WHERE key = 'members_seeded'").get() !== null;
228
+ }
229
+
230
+ function writeAudit(db: Database, login: string, now: number, route: string, planId: string | null): void {
231
+ db.query("INSERT INTO audit (login, time, route, plan_id) VALUES (?, ?, ?, ?)").run(login, now, route, planId);
232
+ }
233
+
234
+ /** Adds a member and audits it. POST /members and addTeamMember both run this. */
235
+ function addMemberTx(db: Database, login: string, actor: string, now: number): { added: boolean } {
236
+ return db.transaction((): { added: boolean } => {
237
+ const added = db.query("INSERT OR IGNORE INTO members (login) VALUES (?)").run(login).changes > 0;
238
+ writeAudit(db, actor, now, `POST /members/${login}`, null);
239
+ return { added };
240
+ }).immediate();
241
+ }
242
+
243
+ type RemoveOutcome = { status: 200; claimsFreed: number } | { status: 404 } | { status: 409 };
244
+
245
+ /** Removes a member with the claims, votes and pause that the login holds for this team. Approvals stay. The admin login is never removed. DELETE /members/:login and removeTeamMember both run this. */
246
+ function removeMemberTx(db: Database, config: TeamServerConfig, login: string, actor: string, now: number): RemoveOutcome {
247
+ return db.transaction((): RemoveOutcome => {
248
+ if (login === config.admin) {
249
+ writeAudit(db, actor, now, `refused DELETE /members/${login}`, null);
250
+ return { status: 409 };
251
+ }
252
+ if (!db.query("SELECT 1 FROM members WHERE login = ?").get(login)) return { status: 404 };
253
+ const claimsFreed = db.query("DELETE FROM claims WHERE login = ? AND team = ?").run(login, config.team).changes;
254
+ db.query("DELETE FROM vote_ranks WHERE login = ?").run(login);
255
+ db.query("DELETE FROM paused WHERE login = ?").run(login);
256
+ db.query("DELETE FROM members WHERE login = ?").run(login);
257
+ writeAudit(db, actor, now, `DELETE /members/${login}`, null);
258
+ return { status: 200, claimsFreed };
259
+ }).immediate();
260
+ }
261
+
262
+ /** Adds one column to a table when it is absent. CREATE TABLE IF NOT EXISTS never alters a table an earlier start made, so new columns arrive this way. The check and the ALTER share one write lock: two servers starting on one database must not both see the column missing. */
263
+ function addColumn(db: Database, table: string, column: string, decl: string): void {
264
+ db.transaction((): void => {
265
+ const have = db.query<{ name: string }, []>(`PRAGMA table_info(${table})`).all();
266
+ if (have.some(row => row.name === column)) return;
267
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${decl}`);
268
+ }).immediate();
269
+ }
270
+
271
+ /** Opens the team database and creates its tables. busy_timeout makes a second writer wait for the lock instead of failing with SQLITE_BUSY. */
272
+ export function openTeamDb(dbPath: string): Database {
273
+ mkdirSync(dirname(dbPath), { recursive: true, mode: 0o700 });
274
+ const db = new Database(dbPath);
275
+ chmodSync(dbPath, 0o600);
276
+ db.exec("PRAGMA busy_timeout = 5000;");
277
+ db.exec(`
278
+ CREATE TABLE IF NOT EXISTS plans (
279
+ id TEXT PRIMARY KEY,
280
+ team TEXT NOT NULL,
281
+ remote TEXT NOT NULL,
282
+ rel_path TEXT NOT NULL,
283
+ sha TEXT NOT NULL,
284
+ text TEXT NOT NULL,
285
+ updated_by TEXT NOT NULL,
286
+ updated_at INTEGER NOT NULL
287
+ );
288
+ CREATE TABLE IF NOT EXISTS members (
289
+ login TEXT PRIMARY KEY
290
+ );
291
+ CREATE TABLE IF NOT EXISTS audit (
292
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
293
+ login TEXT NOT NULL,
294
+ time INTEGER NOT NULL,
295
+ route TEXT NOT NULL,
296
+ plan_id TEXT
297
+ );
298
+ CREATE TABLE IF NOT EXISTS claims (
299
+ id TEXT PRIMARY KEY,
300
+ team TEXT NOT NULL,
301
+ main TEXT NOT NULL,
302
+ host TEXT NOT NULL,
303
+ pid INTEGER NOT NULL,
304
+ since INTEGER NOT NULL,
305
+ beat INTEGER NOT NULL,
306
+ login TEXT NOT NULL
307
+ );
308
+ CREATE TABLE IF NOT EXISTS meta (
309
+ key TEXT PRIMARY KEY,
310
+ value TEXT NOT NULL
311
+ );
312
+ CREATE TABLE IF NOT EXISTS approvals (
313
+ plan_id TEXT NOT NULL,
314
+ login TEXT NOT NULL,
315
+ time INTEGER NOT NULL,
316
+ PRIMARY KEY (plan_id, login)
317
+ );
318
+ CREATE TABLE IF NOT EXISTS vote_ranks (
319
+ login TEXT NOT NULL,
320
+ plan_id TEXT NOT NULL,
321
+ rank INTEGER NOT NULL CHECK (rank >= 1),
322
+ time INTEGER NOT NULL,
323
+ PRIMARY KEY (login, plan_id)
324
+ );
325
+ CREATE TABLE IF NOT EXISTS paused (
326
+ login TEXT PRIMARY KEY,
327
+ time INTEGER NOT NULL
328
+ );
329
+ CREATE TABLE IF NOT EXISTS answers (
330
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
331
+ plan_id TEXT NOT NULL,
332
+ login TEXT NOT NULL,
333
+ time INTEGER NOT NULL,
334
+ sha TEXT NOT NULL,
335
+ answer TEXT NOT NULL
336
+ );
337
+ `);
338
+ addColumn(db, "answers", "waiting_key", "TEXT");
339
+ addColumn(db, "audit", "note", "TEXT");
340
+ addColumn(db, "plans", "last_claimer", "TEXT");
341
+ return db;
342
+ }
343
+
344
+ interface AnswerRow {
345
+ id: number;
346
+ plan: string;
347
+ login: string;
348
+ time: number;
349
+ sha: string;
350
+ answer: string;
351
+ }
352
+
353
+ interface FirstAnswer {
354
+ plan: string;
355
+ login: string;
356
+ time: number;
357
+ answer: string;
358
+ }
359
+
360
+ interface PausedRow {
361
+ login: string;
362
+ time: number;
363
+ }
364
+
365
+ interface VoteRow {
366
+ login: string;
367
+ plan_id: string;
368
+ rank: number;
369
+ time: number;
370
+ }
371
+
372
+ interface OverrideRow {
373
+ plan_ids: string[];
374
+ login: string;
375
+ time: number;
376
+ }
377
+
378
+ /** The one read the team page and P4's client render: every plan with its text, the team's claims and P2c's four tables. */
379
+ export interface TeamView {
380
+ plans: ({ id: string } & PlanRow)[];
381
+ claims: ClaimView[];
382
+ approvals: ApprovalRow[];
383
+ votes: VoteRow[];
384
+ override: OverrideRow | null;
385
+ paused: PausedRow[];
386
+ answers: AnswerRow[];
387
+ first: FirstAnswer[];
388
+ me_paused: boolean;
389
+ }
390
+
391
+ /** The hash of a plan's current WAITING line: the question an answer is for. Null when the plan waits on nothing. */
392
+ function waitingKeyOf(text: string, id: string): string | null {
393
+ const line = parsePlan(".", id, text, undefined, [], false).waitingLine;
394
+ return line === null ? null : sha(line);
395
+ }
396
+
397
+ /** The earliest answer to a plan's current WAITING question, by its waiting key. */
398
+ const FIRST_ANSWER_SQL = "SELECT plan_id AS plan, login, time, answer FROM answers WHERE plan_id = ? AND waiting_key = ? ORDER BY id LIMIT 1";
399
+
400
+ /** Reads a team view in one deferred transaction: one snapshot, nothing written. P5's page calls this in process. */
401
+ export function readTeamView(db: Database, team: string, login: string): TeamView {
402
+ return db.transaction((): TeamView => {
403
+ const plans = db
404
+ .query<{ id: string } & PlanRow, [string]>("SELECT id, remote, rel_path, sha, text, updated_by, updated_at FROM plans WHERE team = ? ORDER BY rel_path, id")
405
+ .all(team);
406
+ const claims = db
407
+ .query<ClaimRow, [string]>("SELECT id, team, main, host, pid, since, beat, login FROM claims WHERE team = ? ORDER BY id")
408
+ .all(team)
409
+ .map(row => wireClaim(row, login));
410
+ const approvals = db.query<ApprovalRow, []>("SELECT plan_id AS plan, login, time FROM approvals ORDER BY plan_id, time").all();
411
+ const votes = db.query<VoteRow, []>("SELECT login, plan_id, rank, time FROM vote_ranks ORDER BY login, plan_id").all();
412
+ const override = db.query<{ value: string }, []>("SELECT value FROM meta WHERE key = 'order_override'").get();
413
+ const paused = db.query<PausedRow, []>("SELECT login, time FROM paused ORDER BY login").all();
414
+ const answers = db.query<AnswerRow, []>("SELECT id, plan_id AS plan, login, time, sha, answer FROM answers ORDER BY id DESC LIMIT 500").all();
415
+ const mePaused = db.query<{ ok: number }, [string]>("SELECT 1 AS ok FROM paused WHERE login = ?").get(login) !== null;
416
+ const first: FirstAnswer[] = [];
417
+ for (const plan of plans) {
418
+ const key = waitingKeyOf(plan.text, plan.id);
419
+ const row = key === null ? null : db.query<FirstAnswer, [string, string]>(FIRST_ANSWER_SQL).get(plan.id, key);
420
+ if (row) first.push(row);
421
+ }
422
+ return {
423
+ plans,
424
+ claims,
425
+ approvals,
426
+ votes,
427
+ override: override ? (JSON.parse(override.value) as OverrideRow) : null,
428
+ paused,
429
+ answers,
430
+ first,
431
+ me_paused: mePaused,
432
+ };
433
+ })();
434
+ }
435
+
436
+ /** Starts the queue server. Refuses to start with no tailnet address, and never binds every interface. */
437
+ export function startTeamServer(opts: TeamServerOptions): TeamServer {
438
+ const { tailscale, config } = opts;
439
+ const ownAddress = tailscale.ip4();
440
+ const hostname = opts.hostname ?? ownAddress;
441
+ if (!hostname) throw new Error("team server: tailscale ip -4 did not answer — is tailscale up?");
442
+ if (bindsEveryInterface(hostname)) throw new Error("team server: refuses to bind every interface");
443
+ const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
444
+ const clock = opts.clock ?? nowSec;
445
+ const hostAllowed = hostAllowlist(tailscale);
446
+ const db = openTeamDb(opts.dbPath);
447
+ // Step A seeds config.members once, on the first start only (marked by the members_seeded row). Step B upserts config.admin on every start.
448
+ const seed = db.transaction(() => {
449
+ if (!initialised(db)) {
450
+ const addMember = db.prepare("INSERT OR IGNORE INTO members (login) VALUES (?)");
451
+ for (const login of config.members) addMember.run(login);
452
+ db.run("INSERT INTO meta (key, value) VALUES ('members_seeded', '1')");
453
+ }
454
+ db.query("INSERT OR IGNORE INTO members (login) VALUES (?)").run(config.admin);
455
+ });
456
+ seed.immediate();
457
+ const isMember = db.query<{ ok: number }, [string]>("SELECT 1 AS ok FROM members WHERE login = ?");
458
+ const selectPlan = db.query<PlanRow, [string, string]>("SELECT sha, text, remote, rel_path, updated_by, updated_at FROM plans WHERE id = ? AND team = ?");
459
+ const listPlans = db.query<Omit<PlanRow, "text"> & { id: string }, [string]>(
460
+ "SELECT id, remote, rel_path, sha, updated_by, updated_at FROM plans WHERE team = ? ORDER BY rel_path, id",
461
+ );
462
+ const insertPlan = db.prepare(
463
+ "INSERT INTO plans (id, team, remote, rel_path, sha, text, updated_by, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
464
+ );
465
+ const updatePlan = db.prepare(
466
+ "UPDATE plans SET remote = ?, rel_path = ?, sha = ?, text = ?, updated_by = ?, updated_at = ? WHERE id = ? AND team = ?",
467
+ );
468
+ // Audit is insert-only: no update and no delete statement exists for this table.
469
+ const insertAudit = db.prepare("INSERT INTO audit (login, time, route, plan_id) VALUES (?, ?, ?, ?)");
470
+ const insertNoteAudit = db.prepare("INSERT INTO audit (login, time, route, plan_id, note) VALUES (?, ?, ?, ?, ?)");
471
+ const writePlan = db.transaction((args: PutArgs): { status: 200; sha: string } | { status: 409; sha: string | null } => {
472
+ const existing = selectPlan.get(args.id, config.team);
473
+ if (!existing) {
474
+ if (args.base !== null) return { status: 409, sha: null };
475
+ insertPlan.run(args.id, config.team, args.remote, args.relPath, args.nextSha, args.text, args.login, args.now);
476
+ } else if (args.base === null || existing.sha !== args.base) {
477
+ return { status: 409, sha: existing.sha };
478
+ } else {
479
+ updatePlan.run(args.remote, args.relPath, args.nextSha, args.text, args.login, args.now, args.id, config.team);
480
+ }
481
+ insertNoteAudit.run(args.login, args.now, args.route, args.id, args.note);
482
+ return { status: 200, sha: args.nextSha };
483
+ });
484
+ const planExists = db.query<{ ok: number }, [string, string]>("SELECT 1 AS ok FROM plans WHERE id = ? AND team = ?");
485
+ const selectClaim = db.query<ClaimRow, [string]>("SELECT id, team, main, host, pid, since, beat, login FROM claims WHERE id = ?");
486
+ const pausedOf = db.query<{ ok: number }, [string]>("SELECT 1 AS ok FROM paused WHERE login = ?");
487
+ const setClaimer = db.prepare("UPDATE plans SET last_claimer = ? WHERE id = ?");
488
+ const claimerOf = db.query<{ last_claimer: string | null }, [string]>("SELECT last_claimer FROM plans WHERE id = ?");
489
+ const memberCount = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM members");
490
+ const listClaims = db.query<ClaimRow, [string]>("SELECT id, team, main, host, pid, since, beat, login FROM claims WHERE team = ? ORDER BY id");
491
+ const replaceClaim = db.prepare("INSERT OR REPLACE INTO claims (id, team, main, host, pid, since, beat, login) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
492
+ const beatClaim = db.prepare("UPDATE claims SET beat = ? WHERE id = ?");
493
+ const deleteClaim = db.prepare("DELETE FROM claims WHERE id = ?");
494
+ // Claim writes run with .immediate (BEGIN IMMEDIATE): the read and the write take the write lock together. Refusals return a status instead of throwing, so their audit row still commits.
495
+ const claimOf = db.transaction((args: { id: string; main: string; host: string; pid: number; login: string; now: number; route: string }): ClaimOutcome => {
496
+ if (!planExists.get(args.id, config.team)) return { status: 404 };
497
+ if (pausedOf.get(args.login)) {
498
+ insertAudit.run(args.login, args.now, `refused ${args.route}`, args.id);
499
+ return { status: 403 };
500
+ }
501
+ const cur = selectClaim.get(args.id);
502
+ if (cur && isOwn(cur, args.login, args.main)) {
503
+ beatClaim.run(args.now, args.id);
504
+ setClaimer.run(args.login, args.id);
505
+ insertAudit.run(args.login, args.now, args.route, args.id);
506
+ return { status: 200, claim: { ...cur, beat: args.now } };
507
+ }
508
+ if (cur && !claimExpired(cur, args.now, opts.claimTtlMin)) {
509
+ insertAudit.run(args.login, args.now, `refused ${args.route}`, args.id);
510
+ return { status: 409, held: cur };
511
+ }
512
+ const fresh: ClaimRow = { id: args.id, team: config.team, main: args.main, host: args.host, pid: args.pid, since: args.now, beat: args.now, login: args.login };
513
+ replaceClaim.run(fresh.id, fresh.team, fresh.main, fresh.host, fresh.pid, fresh.since, fresh.beat, fresh.login);
514
+ setClaimer.run(args.login, args.id);
515
+ insertAudit.run(args.login, args.now, args.route, args.id);
516
+ return { status: 200, claim: fresh };
517
+ });
518
+ const beatOf = db.transaction((args: { id: string; main: string; login: string; now: number; route: string }): BeatOutcome => {
519
+ const cur = selectClaim.get(args.id);
520
+ if (!cur) return { status: 404 };
521
+ if (!isOwn(cur, args.login, args.main)) {
522
+ insertAudit.run(args.login, args.now, `refused ${args.route}`, args.id);
523
+ return { status: 403 };
524
+ }
525
+ beatClaim.run(args.now, args.id);
526
+ return { status: 200, claim: { ...cur, beat: args.now } };
527
+ });
528
+ const releaseOf = db.transaction((args: { id: string; main: string; login: string; now: number; route: string }): ReleaseOutcome => {
529
+ const cur = selectClaim.get(args.id);
530
+ if (!cur) return { status: 404 };
531
+ if (!isOwn(cur, args.login, args.main)) {
532
+ insertAudit.run(args.login, args.now, `refused ${args.route}`, args.id);
533
+ return { status: 403 };
534
+ }
535
+ deleteClaim.run(args.id);
536
+ insertAudit.run(args.login, args.now, args.route, args.id);
537
+ return { status: 200 };
538
+ });
539
+ const writes = new Map<string, number[]>();
540
+ function takeWriteSlot(login: string, now: number): boolean {
541
+ const recent = (writes.get(login) ?? []).filter(t => now - t < 60);
542
+ writes.set(login, recent);
543
+ if (recent.length >= WRITES_PER_MIN) return false;
544
+ recent.push(now);
545
+ return true;
546
+ }
547
+
548
+ const listAudit = db.query<AuditRow, []>("SELECT id, login, time, route, plan_id FROM audit ORDER BY id DESC LIMIT 200");
549
+ const listMembers = db.query<{ login: string }, []>("SELECT login FROM members ORDER BY login");
550
+ const insertApproval = db.prepare("INSERT OR IGNORE INTO approvals (plan_id, login, time) VALUES (?, ?, ?)");
551
+ const selectApproval = db.query<ApprovalRow, [string, string]>("SELECT plan_id AS plan, login, time FROM approvals WHERE plan_id = ? AND login = ?");
552
+ const deleteVotes = db.prepare("DELETE FROM vote_ranks WHERE login = ?");
553
+ const insertVote = db.prepare("INSERT INTO vote_ranks (login, plan_id, rank, time) VALUES (?, ?, ?, ?)");
554
+ const setOverride = db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('order_override', ?)");
555
+ const replacePause = db.prepare("INSERT OR REPLACE INTO paused (login, time) VALUES (?, ?)");
556
+ const deletePause = db.prepare("DELETE FROM paused WHERE login = ?");
557
+ // P2c writes run with .immediate, as the claim writes do: each reads, decides, writes and audits in one step.
558
+ const approveOf = db.transaction((id: string, login: string, now: number): ApproveOutcome => {
559
+ if (!planExists.get(id, config.team)) return { status: 404 };
560
+ const last = claimerOf.get(id)?.last_claimer;
561
+ const solo = (memberCount.get()?.n ?? 0) < 2;
562
+ if (last === login && !solo) {
563
+ insertAudit.run(login, now, `refused POST /approve/${id}`, id);
564
+ return { status: 403 };
565
+ }
566
+ insertApproval.run(id, login, now);
567
+ if (last === login) insertNoteAudit.run(login, now, `POST /approve/${id}`, id, "solo");
568
+ else insertAudit.run(login, now, `POST /approve/${id}`, id);
569
+ return { status: 200, approval: selectApproval.get(id, login) };
570
+ });
571
+ // A vote is the member's whole rank map: the old map goes, the new one lands, and one audit row is written, all in one step.
572
+ const voteOf = db.transaction((ranks: [string, number][], login: string, now: number) => {
573
+ deleteVotes.run(login);
574
+ for (const [planId, rank] of ranks) insertVote.run(login, planId, rank, now);
575
+ insertAudit.run(login, now, "POST /order", null);
576
+ return { login, ranks: Object.fromEntries(ranks), time: now };
577
+ });
578
+ const overrideOf = db.transaction((planIds: string[], login: string, now: number) => {
579
+ const override = { plan_ids: planIds, login, time: now };
580
+ setOverride.run(JSON.stringify(override));
581
+ insertAudit.run(login, now, "POST /order/override", null);
582
+ return override;
583
+ });
584
+ const pauseOf = db.transaction((login: string, paused: boolean, now: number) => {
585
+ if (paused) replacePause.run(login, now);
586
+ else deletePause.run(login);
587
+ insertAudit.run(login, now, paused ? "POST /pause" : "POST /resume", null);
588
+ });
589
+ const insertAnswer = db.prepare("INSERT INTO answers (plan_id, login, time, sha, answer, waiting_key) VALUES (?, ?, ?, ?, ?, ?)");
590
+ // The answer keeps the plan's sha when it landed, so a reader can tell an answer to an older version. A `login` in the body is ignored: the whois login is stored, as approve does.
591
+ // Answers are keyed by the WAITING line they answer: the first one to a question is the one that counts. A later answer is still stored; `earlier` names the one that won.
592
+ const answerOf = db.transaction((id: string, login: string, now: number, answer: string) => {
593
+ const plan = selectPlan.get(id, config.team);
594
+ if (!plan) return null;
595
+ const key = waitingKeyOf(plan.text, id);
596
+ const earlier = key === null ? null : db.query<FirstAnswer, [string, string]>(FIRST_ANSWER_SQL).get(id, key);
597
+ const { lastInsertRowid } = insertAnswer.run(id, login, now, plan.sha, answer, key);
598
+ insertAudit.run(login, now, `POST /answer/${id}`, id);
599
+ return { answer: { id: Number(lastInsertRowid), plan: id, login, time: now, sha: plan.sha, answer }, earlier };
600
+ });
601
+
602
+ /** plan_ids as a checked list: 1 to 500 distinct ids, each a stored plan of this team. The first bad entry is named. */
603
+ function planIdList(raw: unknown): { ids: string[] } | { error: string } {
604
+ if (!Array.isArray(raw) || raw.length < 1 || raw.length > 500) return { error: "plan_ids must be an array of 1 to 500 plan ids" };
605
+ const seen = new Set<string>();
606
+ for (const [i, id] of raw.entries()) {
607
+ if (typeof id !== "string") return { error: `plan_ids[${i}] must be a string` };
608
+ if (seen.has(id)) return { error: `plan_ids[${i}] repeats ${id}` };
609
+ if (!planExists.get(id, config.team)) return { error: `plan_ids[${i}] is not a stored plan: ${id}` };
610
+ seen.add(id);
611
+ }
612
+ return { ids: raw as string[] };
613
+ }
614
+
615
+ /** `ranks` as a checked map: 1 to 500 entries, each key a stored plan of this team and each value a whole number from 1 to 500. The first bad entry is named. */
616
+ function rankList(raw: unknown): { ranks: [string, number][] } | { error: string } {
617
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: "ranks must be an object of plan id to rank" };
618
+ const entries = Object.entries(raw);
619
+ if (entries.length < 1 || entries.length > 500) return { error: "ranks must hold 1 to 500 plan ids" };
620
+ for (const [id, rank] of entries) {
621
+ if (!planExists.get(id, config.team)) return { error: `ranks.${id} is not a stored plan` };
622
+ if (typeof rank !== "number" || !Number.isInteger(rank) || rank < 1 || rank > 500) return { error: `ranks.${id} must be a whole number from 1 to 500` };
623
+ }
624
+ return { ranks: entries as [string, number][] };
625
+ }
626
+
627
+ /** Head of every POST and DELETE in P2c, in the claim routes' order: body size, write slot, role check (a refusal is audited, body not parsed). The caller parses the body when its route takes one. */
628
+ async function writeGate(req: Request, login: string, need: "admin" | "leader" | "member", refused: string): Promise<{ body: Uint8Array; now: number } | { res: Response }> {
629
+ const body = await readBody(req);
630
+ if (body === "too-big") return { res: json({ error: "body too large" }, 413) };
631
+ const now = clock();
632
+ if (!takeWriteSlot(login, now)) return { res: json({ error: "too many writes" }, 429) };
633
+ const allowed = need === "admin" ? login === config.admin : need === "leader" ? login === config.leader : true;
634
+ if (!allowed) {
635
+ insertAudit.run(login, now, `refused ${refused}`, null);
636
+ return { res: json({ error: `forbidden: ${need} only` }, 403) };
637
+ }
638
+ return { body, now };
639
+ }
640
+
641
+ /** P2c routes: audit read, members, approvals, plan order, pause. Null when the request matches none of them. */
642
+ async function memberRoute(req: Request, path: string, login: string): Promise<Response | null> {
643
+ if (req.method === "GET" && path === "/audit") {
644
+ if (login !== config.admin) return json({ error: "forbidden: admin only" }, 403);
645
+ return json({ audit: listAudit.all() }, 200);
646
+ }
647
+ if (req.method === "POST" && path === "/members") {
648
+ const gate = await writeGate(req, login, "admin", "POST /members");
649
+ if ("res" in gate) return gate.res;
650
+ const fields = jsonObject(gate.body);
651
+ if (!fields) return json({ error: "body must be a JSON object" }, 400);
652
+ const member = fields.login;
653
+ if (!validLogin(member)) return json({ error: LOGIN_ERROR }, 400);
654
+ return json({ login: member, added: addMemberTx(db, member, login, gate.now).added }, 200);
655
+ }
656
+ const memberPath = /^\/members\/([^/]+)$/.exec(path);
657
+ if (req.method === "DELETE" && memberPath?.[1]) {
658
+ const target = decodeSegment(memberPath[1]);
659
+ if (target === null) return json({ error: "bad login" }, 400);
660
+ if (!validLogin(target)) return json({ error: LOGIN_ERROR }, 400);
661
+ const gate = await writeGate(req, login, "admin", `DELETE /members/${target}`);
662
+ if ("res" in gate) return gate.res;
663
+ const out = removeMemberTx(db, config, target, login, gate.now);
664
+ if (out.status === 409) return json({ error: ADMIN_REMOVE }, 409);
665
+ if (out.status === 404) return json({ error: NO_MEMBER }, 404);
666
+ return json({ removed: target, claimsFreed: out.claimsFreed }, 200);
667
+ }
668
+ const approvePath = /^\/approve\/([^/]+)$/.exec(path);
669
+ if (req.method === "POST" && approvePath?.[1]) {
670
+ const id = decodeSegment(approvePath[1]);
671
+ if (id === null) return json({ error: "bad plan id" }, 400);
672
+ const gate = await writeGate(req, login, "member", `POST /approve/${id}`);
673
+ if ("res" in gate) return gate.res;
674
+ if (!jsonObject(gate.body)) return json({ error: "body must be a JSON object" }, 400);
675
+ const out = approveOf.immediate(id, login, gate.now);
676
+ if (out.status === 404) return json({ error: "no such plan" }, 404);
677
+ if (out.status === 403) return json({ error: CROSS_REVIEW }, 403);
678
+ return json({ approval: out.approval }, 200);
679
+ }
680
+ const answerPath = /^\/answer\/([^/]+)$/.exec(path);
681
+ if (req.method === "POST" && answerPath?.[1]) {
682
+ const id = decodeSegment(answerPath[1]);
683
+ if (id === null) return json({ error: "bad plan id" }, 400);
684
+ const gate = await writeGate(req, login, "member", `POST /answer/${id}`);
685
+ if ("res" in gate) return gate.res;
686
+ const fields = jsonObject(gate.body);
687
+ if (!fields) return json({ error: "body must be a JSON object" }, 400);
688
+ const text = typeof fields.answer === "string" ? fields.answer.trim() : "";
689
+ if (text.length < 1 || text.length > ANSWER_MAX) return json({ error: `answer must be 1 to ${ANSWER_MAX} characters` }, 400);
690
+ const result = answerOf.immediate(id, login, gate.now, text);
691
+ if (!result) return json({ error: "no such plan" }, 404);
692
+ return json({ answer: result.answer, earlier: result.earlier }, 200);
693
+ }
694
+ if (req.method === "POST" && (path === "/order" || path === "/order/override")) {
695
+ const override = path === "/order/override";
696
+ const gate = await writeGate(req, login, override ? "leader" : "member", `POST ${path}`);
697
+ if ("res" in gate) return gate.res;
698
+ const fields = jsonObject(gate.body);
699
+ if (!fields) return json({ error: "body must be a JSON object" }, 400);
700
+ if (override) {
701
+ const checked = planIdList(fields.plan_ids);
702
+ if ("error" in checked) return json({ error: checked.error }, 400);
703
+ return json({ override: overrideOf.immediate(checked.ids, login, gate.now) }, 200);
704
+ }
705
+ const checked = rankList(fields.ranks);
706
+ if ("error" in checked) return json({ error: checked.error }, 400);
707
+ return json({ vote: voteOf.immediate(checked.ranks, login, gate.now) }, 200);
708
+ }
709
+ if (req.method === "POST" && (path === "/pause" || path === "/resume")) {
710
+ const paused = path === "/pause";
711
+ const gate = await writeGate(req, login, "member", `POST ${path}`);
712
+ if ("res" in gate) return gate.res;
713
+ if (!jsonObject(gate.body)) return json({ error: "body must be a JSON object" }, 400);
714
+ pauseOf.immediate(login, paused, gate.now);
715
+ return json({ paused }, 200);
716
+ }
717
+ return null;
718
+ }
719
+
720
+ /** The team page's plain forms (P5, P6b1): exact paths /approve, /answer, /member, /vote and /override. Success answers 303 back to the page, or JSON when Accept asks for it. Auth chain and Origin run before this. */
721
+ async function pageRoute(req: Request, path: string, login: string): Promise<Response | null> {
722
+ if (req.method !== "POST") return null;
723
+ if (path === "/approve") {
724
+ const gate = await writeGate(req, login, "member", "POST /approve");
725
+ if ("res" in gate) return gate.res;
726
+ const form = await formOf(req, gate.body);
727
+ const out = approveOf.immediate(form.plan ?? "", login, gate.now);
728
+ if (out.status === 404) return pageRefused(req, "no such plan", 404);
729
+ if (out.status === 403) return pageRefused(req, CROSS_REVIEW, 403);
730
+ return pageDone(req, "approve");
731
+ }
732
+ if (path === "/answer") {
733
+ const gate = await writeGate(req, login, "member", "POST /answer");
734
+ if ("res" in gate) return gate.res;
735
+ const form = await formOf(req, gate.body);
736
+ const text = (form.answer_text ?? form.answer ?? "").trim();
737
+ if (text.length < 1 || text.length > ANSWER_MAX) return pageRefused(req, `answer must be 1 to ${ANSWER_MAX} characters`, 400);
738
+ const result = answerOf.immediate(form.plan ?? "", login, gate.now, text);
739
+ if (!result) return pageRefused(req, "no such plan", 404);
740
+ if (result.earlier) return earlierReply(req, result.earlier);
741
+ return pageDone(req, "answer");
742
+ }
743
+ if (path === "/member") {
744
+ const gate = await writeGate(req, login, "admin", "POST /member");
745
+ if ("res" in gate) return gate.res;
746
+ const form = await formOf(req, gate.body);
747
+ const member = form.login ?? "";
748
+ if (!validLogin(member)) return pageRefused(req, LOGIN_ERROR, 400);
749
+ if (form.op === "add") {
750
+ addMemberTx(db, member, login, gate.now);
751
+ return pageDone(req, "add");
752
+ }
753
+ if (form.op === "remove") {
754
+ const out = removeMemberTx(db, config, member, login, gate.now);
755
+ if (out.status === 409) return pageRefused(req, ADMIN_REMOVE, 409);
756
+ if (out.status === 404) return pageRefused(req, NO_MEMBER, 404);
757
+ return pageDone(req, "remove");
758
+ }
759
+ return pageRefused(req, "op must be add or remove", 400);
760
+ }
761
+ if (path === "/vote") {
762
+ const gate = await writeGate(req, login, "member", "POST /vote");
763
+ if ("res" in gate) return gate.res;
764
+ const form = await formOf(req, gate.body);
765
+ const ranks = Object.fromEntries(Object.entries(form).filter(([key, value]) => key.startsWith("rank:") && value.trim() !== "").map(([key, value]) => [key.slice("rank:".length), Number(value.trim())]));
766
+ const checked = rankList(ranks);
767
+ if ("error" in checked) return pageRefused(req, checked.error, 400);
768
+ voteOf.immediate(checked.ranks, login, gate.now);
769
+ return pageDone(req, "vote");
770
+ }
771
+ if (path === "/override") {
772
+ const gate = await writeGate(req, login, "leader", "POST /override");
773
+ if ("res" in gate) return gate.res;
774
+ const form = await formOf(req, gate.body);
775
+ const picked: [string, number][] = [];
776
+ for (const [key, value] of Object.entries(form)) {
777
+ if (!key.startsWith("pos:") || value.trim() === "") continue;
778
+ const pos = Number(value.trim());
779
+ if (!Number.isInteger(pos)) return pageRefused(req, `${key} must be a whole number`, 400);
780
+ picked.push([key.slice("pos:".length), pos]);
781
+ }
782
+ const ids = picked.toSorted(([idA, posA], [idB, posB]) => posA - posB || (idA < idB ? -1 : idA > idB ? 1 : 0)).map(([id]) => id);
783
+ const checked = planIdList(ids);
784
+ if ("error" in checked) return pageRefused(req, checked.error, 400);
785
+ overrideOf.immediate(checked.ids, login, gate.now);
786
+ return pageDone(req, "override");
787
+ }
788
+ return null;
789
+ }
790
+
791
+ /** The team page (P5): one read of the team view, rendered in process. Auth chain only, no write slot, not audited. Audit rows go to the admin only. */
792
+ function teamPage(req: Request, login: string): Response {
793
+ const admin = login === config.admin;
794
+ const rows = viewPlanRows(readTeamView(db, config.team, login), opts.claimTtlMin, clock(), id => id);
795
+ const html = renderTeamPage({
796
+ team: config.team,
797
+ login,
798
+ admin,
799
+ leader: login === config.leader,
800
+ adminLogin: config.admin,
801
+ section: teamSection(config.team, req.headers.get("host") ?? "", rows),
802
+ plans: rows.map(row => ({ id: row.id, relPath: row.relPath, title: row.plan.title, approvals: row.approvals })),
803
+ members: listMembers.all().map(row => row.login),
804
+ audit: admin ? listAudit.all().map(row => ({ at: strftime(row.time, "%H:%M"), login: row.login, route: row.route })) : null,
805
+ });
806
+ return new Response(html, { status: 200, headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": pageCsp(randomBytes(16).toString("base64")) } });
807
+ }
808
+
809
+ /** Claim routes: POST /claims/:id takes or refreshes, POST /claims/:id/beat heartbeats, DELETE /claims/:id releases, GET /claims/:id reads. */
810
+ async function claimRoute(req: Request, id: string, beat: boolean, login: string): Promise<Response> {
811
+ if (req.method === "GET") {
812
+ if (beat) return json({ error: "not found" }, 404);
813
+ if (!planExists.get(id, config.team)) return json({ error: "no such plan" }, 404);
814
+ const row = selectClaim.get(id);
815
+ if (!row || claimExpired(row, clock(), opts.claimTtlMin)) return json({ claim: null }, 200);
816
+ return json({ claim: wireClaim(row, login) }, 200);
817
+ }
818
+ let op: "claim" | "beat" | "release";
819
+ if (req.method === "POST") op = beat ? "beat" : "claim";
820
+ else if (req.method === "DELETE" && !beat) op = "release";
821
+ else return json({ error: "not found" }, 404);
822
+ const body = await readBody(req);
823
+ if (body === "too-big") return json({ error: "body too large" }, 413);
824
+ const now = clock();
825
+ if (!takeWriteSlot(login, now)) return json({ error: "too many writes" }, 429);
826
+ const fields = jsonObject(body);
827
+ if (!fields) return json({ error: "body must be a JSON object" }, 400);
828
+ const main = fields.main;
829
+ if (typeof main !== "string" || !MAIN_ID_RE.test(main)) return json({ error: "main must be a valid main id" }, 400);
830
+ if (op === "claim") {
831
+ const { host, pid } = fields;
832
+ if (typeof host !== "string" || host.length < 1 || host.length > 253) return json({ error: "host must be 1 to 253 characters" }, 400);
833
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return json({ error: "pid must be a positive integer" }, 400);
834
+ const out = claimOf.immediate({ id, main, host, pid, login, now, route: `POST /claims/${id}` });
835
+ if (out.status === 404) return json({ error: "no such plan" }, 404);
836
+ if (out.status === 403) return json({ error: "paused: this member takes no claims on this team" }, 403);
837
+ if (out.status === 409) return json({ heldBy: wireClaim(out.held, login) }, 409);
838
+ return json({ claim: wireClaim(out.claim, login) }, 200);
839
+ }
840
+ if (op === "beat") {
841
+ const out = beatOf.immediate({ id, main, login, now, route: `POST /claims/${id}/beat` });
842
+ if (out.status === 404) return json({ error: "no such claim" }, 404);
843
+ if (out.status === 403) return json({ error: "forbidden: claim belongs to another main" }, 403);
844
+ return json({ claim: wireClaim(out.claim, login) }, 200);
845
+ }
846
+ const out = releaseOf.immediate({ id, main, login, now, route: `DELETE /claims/${id}` });
847
+ if (out.status === 404) return json({ error: "no such claim" }, 404);
848
+ if (out.status === 403) return json({ error: "forbidden: claim belongs to another main" }, 403);
849
+ return json({ ok: true }, 200);
850
+ }
851
+ let server: { stop(closeActiveConnections?: boolean): void; port?: number };
852
+ try {
853
+ server = Bun.serve({
854
+ hostname,
855
+ port: opts.port,
856
+ maxRequestBodySize: BODY_MAX + 1,
857
+ fetch: async (req, srv) => {
858
+ const hostHeader = req.headers.get("host") ?? "";
859
+ try {
860
+ const url = new URL(req.url);
861
+ if (!hostAllowed(hostHeader, srv.port)) return json({ error: "forbidden: host is not this server" }, 403);
862
+ const peer = peerOf(req, srv);
863
+ if (isLoopback(peer)) return json({ error: "forbidden: loopback peer" }, 403);
864
+ if (!isTailnet(peer)) return json({ error: "forbidden: peer is not a tailnet address" }, 403);
865
+ if (peer === ownAddress) return json({ error: "forbidden: this machine's own tailnet address" }, 403);
866
+ const login = tailscale.whois(peer);
867
+ if (!login) return json({ error: "forbidden: tailscale whois failed" }, 403);
868
+ if (!isMember.get(login)) return json({ error: "forbidden: not a team member" }, 403);
869
+ if (WRITE_METHOD[req.method] && !originIsHost(req.headers.get("origin"), hostHeader)) {
870
+ return json({ error: "forbidden: origin is not this server" }, 403);
871
+ }
872
+ if (req.method === "GET" && url.pathname === "/health") return json({ ok: true }, 200);
873
+ if (req.method === "GET" && url.pathname === "/plans") return json({ plans: listPlans.all(config.team) }, 200);
874
+ const idMatch = /^\/plans\/([^/]+)$/.exec(url.pathname);
875
+ let planId: string | null = null;
876
+ if (idMatch?.[1]) {
877
+ planId = decodeSegment(idMatch[1]);
878
+ if (planId === null) return json({ error: "bad plan id" }, 400);
879
+ }
880
+ if (req.method === "GET" && planId !== null) {
881
+ const row = selectPlan.get(planId, config.team);
882
+ if (!row) return json({ error: "not found" }, 404);
883
+ return json({ id: planId, ...row }, 200);
884
+ }
885
+ if (req.method === "GET" && url.pathname === "/claims") {
886
+ return json({ claims: listClaims.all(config.team).map(row => wireClaim(row, login)) }, 200);
887
+ }
888
+ if (req.method === "GET" && url.pathname === "/") return teamPage(req, login);
889
+ // One read for P4/P5: plan text, claims and P2c's tables together. Auth chain only, no write slot, not audited.
890
+ if (req.method === "GET" && url.pathname === "/view") return json(readTeamView(db, config.team, login), 200);
891
+ const claimMatch = /^\/claims\/([^/]+)(\/beat)?$/.exec(url.pathname);
892
+ if (claimMatch?.[1]) {
893
+ const claimId = decodeSegment(claimMatch[1]);
894
+ if (claimId === null) return json({ error: "bad plan id" }, 400);
895
+ return await claimRoute(req, claimId, claimMatch[2] !== undefined, login);
896
+ }
897
+ const memberResponse = await memberRoute(req, url.pathname, login);
898
+ if (memberResponse) return memberResponse;
899
+ const pageResponse = await pageRoute(req, url.pathname, login);
900
+ if (pageResponse) return pageResponse;
901
+ if (!WRITE_METHOD[req.method] || planId === null || req.method !== "PUT") return json({ error: "not found" }, 404);
902
+ const body = await readBody(req);
903
+ if (body === "too-big") return json({ error: "body too large" }, 413);
904
+ const now = clock();
905
+ if (!takeWriteSlot(login, now)) return json({ error: "too many writes" }, 429);
906
+ let parsed: unknown;
907
+ try {
908
+ parsed = JSON.parse(new TextDecoder().decode(body));
909
+ } catch {
910
+ return json({ error: "body is not json" }, 400);
911
+ }
912
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return json({ error: "body must be an object" }, 400);
913
+ const fields = parsed as Record<string, unknown>;
914
+ const remote = fields.remote;
915
+ const relPath = fields.rel_path;
916
+ const text = fields.text;
917
+ if (typeof remote !== "string" || typeof relPath !== "string" || typeof text !== "string") {
918
+ return json({ error: "remote, rel_path and text are required" }, 400);
919
+ }
920
+ let base: string | null;
921
+ if (!("base_sha" in fields) || fields.base_sha === null || fields.base_sha === "") base = null;
922
+ else if (typeof fields.base_sha !== "string") return json({ error: "base_sha must be a string or null" }, 400);
923
+ else base = fields.base_sha;
924
+ let note: string | null = null;
925
+ if (fields.distinct !== undefined) {
926
+ if (typeof fields.distinct !== "string" || fields.distinct.trim() === "" || fields.distinct.length > 200) {
927
+ return json({ error: "distinct must be a reason of 1 to 200 characters" }, 400);
928
+ }
929
+ note = fields.distinct;
930
+ }
931
+ if (!relPathOk(relPath)) return json({ error: "rel_path must be a relative path" }, 400);
932
+ if (new TextEncoder().encode(text).byteLength > PLAN_MAX) return json({ error: "plan too large" }, 413);
933
+ if (headerField(text, "Queue") !== "team") return json({ error: "forbidden: plan is not Queue: team" }, 403);
934
+ const storedRemote = remotePath(remote);
935
+ if (!storedRemote || !remoteListed(remote, config.repos)) return json({ error: "forbidden: remote is not in this team's repos" }, 403);
936
+ const id = teamPlanId(remote, relPath);
937
+ if (id === null || id !== planId) return json({ error: "plan id does not match remote and path" }, 400);
938
+ const written = writePlan.immediate({
939
+ id,
940
+ remote: storedRemote,
941
+ relPath,
942
+ text,
943
+ nextSha: sha(text),
944
+ base,
945
+ login,
946
+ now,
947
+ route: `PUT /plans/${id}`,
948
+ note,
949
+ });
950
+ if (written.status === 409) return json({ error: "stale base", sha: written.sha }, 409);
951
+ return json({ id, sha: written.sha }, 200);
952
+ } catch {
953
+ return json({ error: "internal error" }, 500);
954
+ }
955
+ },
956
+ });
957
+ } catch (err) {
958
+ db.close();
959
+ throw err;
960
+ }
961
+ let stopped = false;
962
+ return {
963
+ stop() {
964
+ if (stopped) return;
965
+ stopped = true;
966
+ server.stop(true);
967
+ db.close();
968
+ },
969
+ hostname,
970
+ port: Number(server.port),
971
+ };
972
+ }
973
+
974
+ /** Members of this team on the database, sorted. Before the first start the members table is empty, so this returns []. Opens through openTeamDb and closes again. */
975
+ export function listTeamMembers(dbPath: string): string[] {
976
+ const db = openTeamDb(dbPath);
977
+ try {
978
+ return db.query<{ login: string }, []>("SELECT login FROM members ORDER BY login").all().map(row => row.login);
979
+ } finally {
980
+ db.close();
981
+ }
982
+ }
983
+
984
+ /** Adds a member from the host, acting as the admin. No write slot and no role check. Refuses until the team has started once. */
985
+ export function addTeamMember(dbPath: string, config: TeamServerConfig, login: string): { ok: true; added: boolean } | { ok: false; error: string } {
986
+ const db = openTeamDb(dbPath);
987
+ try {
988
+ if (!initialised(db)) return { ok: false, error: `team ${config.team} not initialised: its server has never started on this database; start it once, then retry` };
989
+ if (!validLogin(login)) return { ok: false, error: LOGIN_ERROR };
990
+ return { ok: true, added: addMemberTx(db, login, config.admin, nowSec()).added };
991
+ } finally {
992
+ db.close();
993
+ }
994
+ }
995
+
996
+ /** Removes a member from the host, acting as the admin. Refuses exactly as DELETE /members/:login does. Refuses until the team has started once. */
997
+ export function removeTeamMember(dbPath: string, config: TeamServerConfig, login: string): { ok: true; claimsFreed: number } | { ok: false; error: string } {
998
+ const db = openTeamDb(dbPath);
999
+ try {
1000
+ if (!initialised(db)) return { ok: false, error: `team ${config.team} not initialised: its server has never started on this database; start it once, then retry` };
1001
+ const out = removeMemberTx(db, config, login, config.admin, nowSec());
1002
+ if (out.status === 409) return { ok: false, error: ADMIN_REMOVE };
1003
+ if (out.status === 404) return { ok: false, error: NO_MEMBER };
1004
+ return { ok: true, claimsFreed: out.claimsFreed };
1005
+ } finally {
1006
+ db.close();
1007
+ }
1008
+ }