cursedbelt-server 4.71.0 → 4.73.1

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,98 @@
1
+ /*
2
+ * One `/ctgr<xx>` GET twin → the real Request it stands in for, or the Response that answers it
3
+ * instead. The ONE decoder: `mountCtgrTunnel` re-dispatches what it returns into the app, and the
4
+ * master-lock guard (`master-lock/guard.ts`) judges a decoded `/__lock/` twin itself, so a twin of
5
+ * an unlock is decided by the same rule as the POST it carries whatever the guard and the tunnel's
6
+ * mount order (forge task 5158).
7
+ *
8
+ * Module-private: no export subpath reaches it, so the public surface does not grow.
9
+ */
10
+ import type { V0ChunkStore } from 'cursedbelt-core/ctgr/v0compat';
11
+ import { ABBREV_TO_METHOD, type CtgrAbbrev, type CtgrDecoded } from 'cursedbelt-core/ctgr/types';
12
+ import type { CtgrChunkSink } from './ctgrTunnel.js';
13
+
14
+ /** Query keys the codec adds to a twin URL — dropped when rebuilding the real request. */
15
+ const isCtgrParam = (key: string): boolean => key === '_d' || key === '_sha' || key.startsWith('_c');
16
+
17
+ const json = (body: unknown, status: number): Response => Response.json(body, { status });
18
+
19
+ /**
20
+ * Decode `raw`, a twin whose path is `twinPath` (`/ctgr<xx>` + the real path). A Request is the
21
+ * real request, ready to dispatch; a Response is the whole answer (a cross-site twin 403, an
22
+ * unknown verb 404, an intermediate chunk 202, a bad payload 400, a store that could not answer 503).
23
+ */
24
+ export async function decodeCtgrTwin(
25
+ raw: Request,
26
+ twinPath: string,
27
+ store: CtgrChunkSink,
28
+ legacy: V0ChunkStore,
29
+ ): Promise<Request | Response> {
30
+ // 🔴 A twin is a GET, and a GET is what SameSite=Lax sends another site's cookie on: a link
31
+ // on any page would otherwise become a signed-in write the real POST could never make
32
+ // (found wiring vault, forge task 4807). The page's own twins are same-origin fetches.
33
+ if (isCrossSiteTwin(raw)) {
34
+ return json({ error: "ctgr: a write twin is accepted from this app's own pages only", code: 'CTGR_CROSS_SITE' }, 403);
35
+ }
36
+ const url = new URL(raw.url);
37
+ const params = Object.fromEntries(url.searchParams);
38
+ // The twin path is `/ctgr<xx>...`; the abbreviation is the two chars after `ctgr`.
39
+ const pathMethod = ABBREV_TO_METHOD[twinPath.slice(5, 7) as CtgrAbbrev];
40
+ if (!pathMethod) return json({ error: 'not found', code: 'NOT_FOUND' }, 404);
41
+
42
+ let result: CtgrDecoded | false | Error;
43
+ try {
44
+ result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
45
+ } catch (error) {
46
+ console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
47
+ return json({ error: 'ctgr: the chunk store could not answer — send it again', code: 'CTGR_STORE_UNAVAILABLE' }, 503);
48
+ }
49
+ if (result === false) return json({ acknowledged: true }, 202);
50
+ if (result instanceof Error) return json({ error: result.message, code: 'BAD_REQUEST' }, 400);
51
+ return rebuildRequest(raw, twinPath, url, result);
52
+ }
53
+
54
+ /**
55
+ * Did a browser say this twin came from somewhere else? `Sec-Fetch-Site` is set by the browser
56
+ * and no page can forge it: only `same-origin` is the app's own `installCtgrFetch`. `none` (a
57
+ * typed URL or bookmark), `same-site` and `cross-site` are refused. A browser too old to send it
58
+ * passes, because the GET-only devices this exists for may be that old; the gate still applies.
59
+ */
60
+ function isCrossSiteTwin(request: Request): boolean {
61
+ const site = request.headers.get('sec-fetch-site');
62
+ return site !== null && site !== 'same-origin';
63
+ }
64
+
65
+ /** Build the real Request the decoded twin stands in for. */
66
+ function rebuildRequest(raw: Request, twinPath: string, url: URL, decoded: CtgrDecoded): Request {
67
+ // Strip the `/ctgr<xx>` prefix and the codec's own query params; keep the rest.
68
+ const realPath = twinPath.replace(/^\/ctgr../, '') || '/';
69
+ const kept = new URLSearchParams();
70
+ for (const [key, value] of url.searchParams) {
71
+ if (!isCtgrParam(key)) kept.set(key, value);
72
+ }
73
+ const search = kept.toString();
74
+ const realUrl = `${url.origin}${realPath}${search ? `?${search}` : ''}`;
75
+
76
+ const headers = new Headers(raw.headers);
77
+ headers.delete('content-length');
78
+
79
+ let body: BodyInit | undefined;
80
+ if (decoded.files && decoded.files.length > 0) {
81
+ const form = new FormData();
82
+ const fields = (decoded.body ?? {}) as Record<string, unknown>;
83
+ for (const [key, value] of Object.entries(fields)) {
84
+ form.append(key, typeof value === 'string' ? value : JSON.stringify(value));
85
+ }
86
+ for (const file of decoded.files) {
87
+ form.append(file.fieldname, new File([new Uint8Array(file.buffer)], file.originalname, { type: file.mimetype }));
88
+ }
89
+ body = form;
90
+ // Let the runtime set the multipart content-type + boundary.
91
+ headers.delete('content-type');
92
+ } else if (decoded.body !== undefined) {
93
+ body = JSON.stringify(decoded.body);
94
+ headers.set('content-type', 'application/json');
95
+ }
96
+
97
+ return new Request(realUrl, { method: decoded.method, headers, body });
98
+ }
@@ -100,9 +100,9 @@ describe("serverActions — the API seam that names a state-changing act", () =>
100
100
  const dataset = fakeDataset();
101
101
  const events = createEventSink(dataset, { app: "music" });
102
102
  const app = new Hono();
103
- app.use("/api/*", serverActions(events, RULES, { actorOf: () => ({ id: "curt@example.com" }) }));
104
- app.get("/api/ctgrte/playlists/:id", (c) => c.json({ ok: true }));
105
- await app.request("https://music.cursedalchemy.com/api/ctgrte/playlists/7", { headers: { "user-agent": BROWSER } });
103
+ app.use("*", serverActions(events, RULES, { actorOf: () => ({ id: "curt@example.com" }) }));
104
+ app.get("/ctgrde/api/playlists/:id", (c) => c.json({ ok: true }));
105
+ await app.request("https://music.cursedalchemy.com/ctgrde/api/playlists/7", { headers: { "user-agent": BROWSER } });
106
106
  expect(dataset.points[0]?.indexes).toEqual(["action:playlist.delete"]);
107
107
  });
108
108
 
@@ -138,8 +138,8 @@ describe("serverActions — the API seam that names a state-changing act", () =>
138
138
  const events = createEventSink(dataset, { app: "lists" });
139
139
  const app = new Hono();
140
140
  // A known actor writes at once; the anonymous hash would make every assertion wait on Web Crypto.
141
- app.use("/api/*", serverActions(events, GATED, { actorOf: () => ({ id: "curt@example.com" }) }));
142
- app.use("/api/*", async (c) => c.json({ error: "sign in" }, status as 401));
141
+ app.use("*", serverActions(events, GATED, { actorOf: () => ({ id: "curt@example.com" }) }));
142
+ app.use("*", async (c) => c.json({ error: "sign in" }, status as 401));
143
143
  return {
144
144
  names: () => dataset.points.map((p) => [p.blobs?.[3], p.blobs?.[13]]),
145
145
  blobs: () => JSON.stringify(dataset.points),
@@ -178,7 +178,7 @@ describe("serverActions — the API seam that names a state-changing act", () =>
178
178
 
179
179
  test("a ctgr GET-twin refused by the gate counts as its real verb", async () => {
180
180
  const { names, send } = refused();
181
- await send("GET", "/api/ctgrte/playlists/my-mix");
181
+ await send("GET", "/ctgrde/api/playlists/my-mix");
182
182
  expect(names()).toEqual([["playlist.delete", "refused"]]);
183
183
  });
184
184
 
@@ -33,7 +33,7 @@
33
33
  * only be watching one of them.
34
34
  */
35
35
  import { MASTER_LOCK_PATHS, MASTER_LOCK_PREFIX } from "cursedbelt-core/master-lock";
36
- import { MASTER_LOCK_DERIVE_SOURCE, MASTER_LOCK_MIN_PASSWORD_LENGTH, MASTER_LOCK_REVEAL_SOURCE, type LockPageOptions, withRevealToggles } from "./lockPage.js";
36
+ import { MASTER_LOCK_DERIVE_SOURCE, MASTER_LOCK_MIN_PASSWORD_LENGTH, MASTER_LOCK_REVEAL_SOURCE, MASTER_LOCK_WRITE_SOURCE, type LockPageOptions, withRevealToggles } from "./lockPage.js";
37
37
 
38
38
  /**
39
39
  * The page's own two assets.
@@ -221,6 +221,7 @@ const MIN_LENGTH = ${MASTER_LOCK_MIN_PASSWORD_LENGTH};
221
221
 
222
222
  // ── derivation ───────────────────────────────────────────────────────────────
223
223
  ${MASTER_LOCK_DERIVE_SOURCE}
224
+ ${MASTER_LOCK_WRITE_SOURCE}
224
225
 
225
226
  // ── show / hide ──────────────────────────────────────────────────────────────
226
227
  ${MASTER_LOCK_REVEAL_SOURCE}
@@ -242,12 +243,7 @@ function say(form, message, tone) {
242
243
  }
243
244
 
244
245
  async function post(path, body, method) {
245
- const res = await fetch(path, {
246
- method: method || "POST",
247
- credentials: "same-origin",
248
- headers: { "content-type": "application/json" },
249
- body: JSON.stringify(body),
250
- });
246
+ const res = await lockWrite(path, body, method);
251
247
  const parsed = await res.json().catch(() => ({}));
252
248
  return { ok: res.ok, status: res.status, body: parsed || {} };
253
249
  }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * A GET-only device gets past the master lock (forge task 5158).
3
+ *
4
+ * Such a device sends every write as a `/ctgr<xx>` GET twin. The lock's writes live under
5
+ * `/__lock/`, so the lock page's own script must build the twin (a locked app serves the lock page
6
+ * in place of its document, so the app's `installCtgrFetch` never runs), and the guard must decode
7
+ * it and judge the POST it carries. Both halves are tested here over the real pieces: the page's
8
+ * browser source, core's codec, and a guard over a real {@link MasterLock}.
9
+ */
10
+ import { beforeAll, describe, expect, test } from "bun:test";
11
+ import { decodeRequest, encodeRequest } from "cursedbelt-core/ctgr";
12
+ import { readCtgrIntent } from "cursedbelt-core/ctgr-client";
13
+ import { MASTER_LOCK_PATHS, type MasterLockKdfParams, deriveMasterLockVerifier } from "cursedbelt-core/master-lock";
14
+ import { MASTER_LOCK_ACCOUNTS_SCRIPT } from "./accountsPage.js";
15
+ import { createMasterLockGuard } from "./guard.js";
16
+ // A namespace import, so this file still loads against code from before the export (prove-red).
17
+ import * as lockPage from "./lockPage.js";
18
+ import { MasterLock } from "./masterLock.js";
19
+ import { createMemoryMasterLockStore } from "./store.js";
20
+
21
+ const { LOCK_SCRIPT, MASTER_LOCK_DERIVE_SOURCE } = lockPage;
22
+ const MASTER_LOCK_WRITE_SOURCE = String((lockPage as Record<string, unknown>).MASTER_LOCK_WRITE_SOURCE ?? "");
23
+
24
+ const KDF: MasterLockKdfParams = { v: 1, alg: "PBKDF2-SHA256", iter: 1, salt: "AAECAwQFBgcICQoLDA0ODw" };
25
+ let VERIFIER = "";
26
+ let SEED = "";
27
+
28
+ beforeAll(async () => {
29
+ VERIFIER = await deriveMasterLockVerifier("open sesame", KDF);
30
+ SEED = JSON.stringify({ kdf: KDF, verifierHash: await Bun.password.hash(VERIFIER, { algorithm: "argon2id" }) });
31
+ });
32
+
33
+ const ORIGIN = "http://app.test";
34
+ const build = () =>
35
+ createMasterLockGuard({
36
+ lock: new MasterLock({ store: createMemoryMasterLockStore(), seedJson: SEED }),
37
+ appLabel: "Test App",
38
+ });
39
+
40
+ type Sent = { url: string; method: string; body?: string };
41
+ type LockWrite = (path: string, body: unknown, method?: string) => Promise<unknown>;
42
+
43
+ /** The page's `lockWrite`, evaluated as the browser runs it, over a stub page at `search`. */
44
+ function pageWrite(search: string, storage = new Map<string, string>()): { write: LockWrite; sent: Sent[]; storage: Map<string, string> } {
45
+ const sent: Sent[] = [];
46
+ const localStorage = {
47
+ getItem: (k: string) => storage.get(k) ?? null,
48
+ setItem: (k: string, v: string) => void storage.set(k, v),
49
+ removeItem: (k: string) => void storage.delete(k),
50
+ };
51
+ const fetch = async (url: string, init: RequestInit = {}) => {
52
+ sent.push({ url, method: init.method ?? "GET", ...(typeof init.body === "string" ? { body: init.body } : {}) });
53
+ return new Response("{}");
54
+ };
55
+ const write = new Function(
56
+ "location",
57
+ "localStorage",
58
+ "fetch",
59
+ `${MASTER_LOCK_DERIVE_SOURCE}\n${MASTER_LOCK_WRITE_SOURCE}\nreturn lockWrite;`,
60
+ )({ search }, localStorage, fetch) as LockWrite;
61
+ return { write, sent, storage };
62
+ }
63
+
64
+ describe("the lock pages' lockWrite", () => {
65
+ test("both pages send every write through it", () => {
66
+ expect(LOCK_SCRIPT).toContain(MASTER_LOCK_WRITE_SOURCE);
67
+ expect(MASTER_LOCK_ACCOUNTS_SCRIPT).toContain(MASTER_LOCK_WRITE_SOURCE);
68
+ for (const script of [LOCK_SCRIPT, MASTER_LOCK_ACCOUNTS_SCRIPT]) {
69
+ const outside = script.replace(MASTER_LOCK_WRITE_SOURCE, "");
70
+ expect(outside).not.toMatch(/method:\s*"(POST|PATCH|PUT|DELETE)"/);
71
+ }
72
+ });
73
+
74
+ test("mode off: the write is the POST it always was", async () => {
75
+ const { write, sent } = pageWrite("");
76
+ await write(MASTER_LOCK_PATHS.unlock, { verifier: "v" });
77
+ expect(sent).toEqual([{ url: MASTER_LOCK_PATHS.unlock, method: "POST", body: '{"verifier":"v"}' }]);
78
+ });
79
+
80
+ test("?ctgr=1 turns the mode on for the device, and the write leaves as a twin core decodes", async () => {
81
+ const { write, sent, storage } = pageWrite("?ctgr=1");
82
+ await write(MASTER_LOCK_PATHS.unlock, { verifier: "v".repeat(43) });
83
+ expect(storage.get("ctgr")).toBe("on");
84
+ expect(sent).toHaveLength(1);
85
+ expect(sent[0]?.method).toBe("GET");
86
+ expect(sent[0]?.url.startsWith(`/ctgrpo${MASTER_LOCK_PATHS.unlock}?`)).toBe(true);
87
+ const decoded = await decodeRequest(new URL(ORIGIN + sent[0]?.url).searchParams);
88
+ expect(decoded).toEqual({ method: "POST", body: { verifier: "v".repeat(43) } });
89
+ });
90
+
91
+ test("a PATCH from the accounts page keeps its verb", async () => {
92
+ const { write, sent } = pageWrite("", new Map([["ctgr", "on"]]));
93
+ await write(MASTER_LOCK_PATHS.accounts, { id: "a", label: "b" }, "PATCH");
94
+ const decoded = await decodeRequest(new URL(ORIGIN + sent[0]?.url).searchParams);
95
+ expect(decoded).toEqual({ method: "PATCH", body: { id: "a", label: "b" } });
96
+ });
97
+
98
+ test("its intent words are core's: every word core reads as on or off, the page reads the same", async () => {
99
+ for (const word of ["t", "on", "1", "yes", "true", "TRUE", " On ", "f", "off", "0", "no", "false", "maybe", ""]) {
100
+ const storage = new Map([["ctgr", "on"]]);
101
+ await pageWrite(`?ctgr=${encodeURIComponent(word)}`, storage).write("/__lock/ping", null);
102
+ const core = readCtgrIntent(word);
103
+ expect({ word, on: storage.get("ctgr") === "on" }).toEqual({ word, on: core !== "off" });
104
+ }
105
+ });
106
+ });
107
+
108
+ describe("the guard decodes a lock twin and judges the POST it carries", () => {
109
+ const twin = async (method: "POST" | "PATCH", path: string, body: unknown, headers: Record<string, string> = {}) => {
110
+ const { chunks } = await encodeRequest(method, path, body);
111
+ return new Request(ORIGIN + chunks[0]?.url, { headers: { "sec-fetch-site": "same-origin", ...headers } });
112
+ };
113
+
114
+ test("the right password's twin unlocks, and the cookie it sets opens the app", async () => {
115
+ const guard = build();
116
+ const res = await guard.handle(await twin("POST", MASTER_LOCK_PATHS.unlock, { verifier: VERIFIER }));
117
+ expect(res?.status).toBe(200);
118
+ const cookie = (res?.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
119
+ expect(cookie.length).toBeGreaterThan(12);
120
+ expect(await guard.handle(new Request(`${ORIGIN}/api/thing`, { headers: { cookie } }))).toBeNull();
121
+ const ping = await guard.handle(await twin("POST", MASTER_LOCK_PATHS.ping, null, { cookie }));
122
+ expect(ping?.status).toBe(200);
123
+ });
124
+
125
+ test("a wrong password's twin is refused like the POST, and sets nothing", async () => {
126
+ const guard = build();
127
+ const res = await guard.handle(await twin("POST", MASTER_LOCK_PATHS.unlock, { verifier: "nope" }));
128
+ expect(res?.status).not.toBe(200);
129
+ expect(res?.headers.get("set-cookie")).toBeNull();
130
+ });
131
+
132
+ test("a ping's twin from a locked caller is refused — the twin grants nothing the POST would not", async () => {
133
+ const guard = build();
134
+ const res = await guard.handle(await twin("POST", MASTER_LOCK_PATHS.ping, null));
135
+ expect(res?.status).not.toBe(200);
136
+ });
137
+
138
+ test("a twin another site sent is refused before it is decoded", async () => {
139
+ const guard = build();
140
+ const res = await guard.handle(await twin("POST", MASTER_LOCK_PATHS.unlock, { verifier: VERIFIER }, { "sec-fetch-site": "cross-site" }));
141
+ expect(res?.status).toBe(403);
142
+ expect(res?.headers.get("set-cookie")).toBeNull();
143
+ });
144
+
145
+ test.each(["/ctgrPO", "/ctgrzz"])(
146
+ "only core's verbs make a lock twin: the right password at %s/__lock/… is not decoded, so it unlocks nothing",
147
+ async (head) => {
148
+ const guard = build();
149
+ const real = await twin("POST", MASTER_LOCK_PATHS.unlock, { verifier: VERIFIER });
150
+ const url = new URL(real.url);
151
+ url.pathname = head + url.pathname.slice(7);
152
+ const res = await guard.handle(new Request(url, { headers: real.headers }));
153
+ expect(res?.status).not.toBe(200);
154
+ expect(res?.headers.get("set-cookie") ?? null).toBeNull();
155
+ },
156
+ );
157
+
158
+ test("a twin of an app path is not the guard's to decode — it is walled like any request", async () => {
159
+ const guard = build();
160
+ const res = await guard.handle(await twin("POST", "/api/thing", { a: 1 }));
161
+ expect(res?.status).not.toBe(200);
162
+ expect(res?.status).not.toBe(403);
163
+ });
164
+ });
@@ -23,6 +23,10 @@ import {
23
23
  MASTER_LOCK_ACCOUNTS_STYLE,
24
24
  accountsPageHtml,
25
25
  } from "./accountsPage.js";
26
+ import { ChunkStore } from "cursedbelt-core/ctgr/chunk-store";
27
+ import { isCtgrTwinOf } from "cursedbelt-core/ctgr/types";
28
+ import { V0ChunkStore } from "cursedbelt-core/ctgr/v0compat";
29
+ import { decodeCtgrTwin } from "../ctgrTwin.js";
26
30
  import { LOCK_SCRIPT, LOCK_STYLE, type LockPageOptions, lockPageHtml } from "./lockPage.js";
27
31
  import type { MasterLock } from "./masterLock.js";
28
32
 
@@ -334,34 +338,50 @@ export function createMasterLockGuard(options: MasterLockGuardOptions): MasterLo
334
338
  return new Response("not found", { status: 404, headers: noStore });
335
339
  }
336
340
 
341
+ // A lock write is one small JSON body, so its twin is one chunk; the store only holds the rare split.
342
+ const twinStore = new ChunkStore();
343
+ const twinLegacy = new V0ChunkStore();
344
+
345
+ async function handle(req: Request): Promise<Response | null> {
346
+ const url = new URL(req.url);
347
+ // 🔴 The twin is DECODED here and the real request judged by the very rule below, so the
348
+ // wall decides an unlock's twin exactly as it decides the POST, whichever of this guard and
349
+ // `mountCtgrTunnel` an app mounts first — and in a bare `Bun.serve` app that has no tunnel.
350
+ // A GET-only device's twin of a lock write: `/ctgr<xx>/__lock/…` (forge task 5158). Its writes —
351
+ // unlock, enroll, ping, lock — would otherwise reach the wall as a GET to a path that is not the
352
+ // lock's, and be refused, so such a device could never get in. Core says what a twin is (task 5162).
353
+ if (isCtgrTwinOf(url.pathname, MASTER_LOCK_PREFIX)) {
354
+ const decoded = await decodeCtgrTwin(req, url.pathname, twinStore, twinLegacy);
355
+ return decoded instanceof Response ? decoded : handle(decoded);
356
+ }
357
+ const own =
358
+ url.pathname === MASTER_LOCK_PREFIX || url.pathname.startsWith(`${MASTER_LOCK_PREFIX}/`);
359
+ const lock = resolve(req);
360
+ if (!lock) {
361
+ // No principal. On the app's own paths the caller is not signed in and the
362
+ // app's sign-in owns the request; on `/__lock/*` there is nobody to unlock
363
+ // FOR, and answering the ordinary refusal keeps that indistinguishable from
364
+ // being locked.
365
+ return own ? refuse() : null;
366
+ }
367
+ if (own) return handleOwnRoute(req, url, lock);
368
+ if (options.allow?.(url, req)) return null;
369
+ if (opens(lock, req)) return null;
370
+
371
+ // A document request is answered IN PLACE with the lock page — same URL, status
372
+ // 200 — so unlocking reloads to where they were going instead of dumping them at
373
+ // the root. Everything else gets the uniform refusal.
374
+ if (wantsDocument(req)) return lockPage(options, lock);
375
+ return refuse();
376
+ }
377
+
337
378
  return {
379
+ handle,
338
380
  accountFor(req: Request): string | null {
339
381
  // The SAME resolution the guard itself uses, so an app can never be told a
340
382
  // different tenant from the one the wall admitted.
341
383
  return resolve(req)?.accountFor(req) ?? null;
342
384
  },
343
- async handle(req: Request): Promise<Response | null> {
344
- const url = new URL(req.url);
345
- const own =
346
- url.pathname === MASTER_LOCK_PREFIX || url.pathname.startsWith(`${MASTER_LOCK_PREFIX}/`);
347
- const lock = resolve(req);
348
- if (!lock) {
349
- // No principal. On the app's own paths the caller is not signed in and the
350
- // app's sign-in owns the request; on `/__lock/*` there is nobody to unlock
351
- // FOR, and answering the ordinary refusal keeps that indistinguishable from
352
- // being locked.
353
- return own ? refuse() : null;
354
- }
355
- if (own) return handleOwnRoute(req, url, lock);
356
- if (options.allow?.(url, req)) return null;
357
- if (opens(lock, req)) return null;
358
-
359
- // A document request is answered IN PLACE with the lock page — same URL, status
360
- // 200 — so unlocking reloads to where they were going instead of dumping them at
361
- // the root. Everything else gets the uniform refusal.
362
- if (wantsDocument(req)) return lockPage(options, lock);
363
- return refuse();
364
- },
365
385
  };
366
386
  }
367
387
 
@@ -25,6 +25,7 @@
25
25
  * second thing to keep in step, and the pinning spec would only be watching one of them. Both
26
26
  * scripts interpolate this string, and the spec asserts that they do.
27
27
  */
28
+ import { CTGR_WIRE_VERSION, METHOD_TO_ABBREV } from "cursedbelt-core/ctgr/types";
28
29
  import { MASTER_LOCK_PATHS } from "cursedbelt-core/master-lock";
29
30
 
30
31
  /**
@@ -278,6 +279,64 @@ async function deriveVerifier(password, kdf) {
278
279
  }
279
280
  globalThis.__masterLockDerive = deriveVerifier;`;
280
281
 
282
+ /**
283
+ * 🔴 The lock pages' ONE way to send a write — `lockWrite(path, body, method)` — and a GET-only
284
+ * device's way in (forge task 5158). A locked app answers its own document with the lock page, so
285
+ * the app's `installCtgrFetch` never runs here: this page reads `?ctgr=` itself (the same intent
286
+ * words and `localStorage` key as `cursedbelt-core/ctgr-client`) and, while the mode is on, sends
287
+ * the write as its one-chunk v1 `/ctgr<xx>` GET twin, which the guard decodes and judges as the
288
+ * POST it carries. A lock body is a few hundred bytes, so it is never gzipped or split.
289
+ *
290
+ * Interpolates {@link MASTER_LOCK_DERIVE_SOURCE}'s `b64u`, so it follows it in a script. Pinned by
291
+ * `lockPage.spec.ts`, which evaluates it and decodes what it sends with core's own codec.
292
+ */
293
+ export const MASTER_LOCK_WRITE_SOURCE = `const CTGR_ABBREV = ${JSON.stringify(METHOD_TO_ABBREV)};
294
+ function ctgrModeOn() {
295
+ try {
296
+ const intent = new URLSearchParams(location.search).get("ctgr");
297
+ const word = intent === null ? "" : intent.trim().toLowerCase();
298
+ if (["t", "on", "1", "yes", "true"].indexOf(word) >= 0) localStorage.setItem("ctgr", "on");
299
+ else if (["f", "off", "0", "no", "false"].indexOf(word) >= 0) localStorage.removeItem("ctgr");
300
+ return localStorage.getItem("ctgr") === "on";
301
+ } catch (e) {
302
+ return false;
303
+ }
304
+ }
305
+ function ctgrCrc32(bytes) {
306
+ let crc = 0xffffffff;
307
+ for (let i = 0; i < bytes.length; i += 1) {
308
+ crc ^= bytes[i];
309
+ for (let k = 0; k < 8; k += 1) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
310
+ }
311
+ return (crc ^ 0xffffffff) >>> 0;
312
+ }
313
+ async function lockWrite(path, body, method) {
314
+ const verb = (method || "POST").toUpperCase();
315
+ const text = JSON.stringify(body === undefined ? null : body);
316
+ if (!ctgrModeOn()) {
317
+ return fetch(path, {
318
+ method: verb,
319
+ credentials: "same-origin",
320
+ headers: { "content-type": "application/json" },
321
+ body: text,
322
+ });
323
+ }
324
+ const raw = new TextEncoder().encode(text);
325
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", raw));
326
+ let sha = "";
327
+ for (const byte of digest) sha += byte.toString(16).padStart(2, "0");
328
+ // The id keys the chunk accumulator for one in-flight payload, and a one-chunk twin completes
329
+ // on arrival, so the body's hash and the clock make it. No randomness: the accounts page proves
330
+ // its script cannot mint a kdf by holding none (accountsPage.spec.ts).
331
+ const query = new URLSearchParams({
332
+ _cv: ${JSON.stringify(CTGR_WIRE_VERSION)}, _cm: CTGR_ABBREV[verb], _cg: "0", _ci: "0", _ct: "1",
333
+ _cl: String(raw.length), _cid: sha.slice(0, 16) + Date.now().toString(36),
334
+ _crc: String(ctgrCrc32(raw)), _d: b64u(raw), _sha: sha,
335
+ });
336
+ return fetch("/ctgr" + CTGR_ABBREV[verb] + path + "?" + query.toString(), { credentials: "same-origin" });
337
+ }
338
+ globalThis.__masterLockWrite = lockWrite;`;
339
+
281
340
  /**
282
341
  * The page's script.
283
342
  *
@@ -292,6 +351,9 @@ export const LOCK_SCRIPT = `const paths = ${JSON.stringify(MASTER_LOCK_PATHS)};
292
351
  // ── derivation ───────────────────────────────────────────────────────────────
293
352
  ${MASTER_LOCK_DERIVE_SOURCE}
294
353
 
354
+ // ── writes (a GET-only device's twins) ───────────────────────────────────────
355
+ ${MASTER_LOCK_WRITE_SOURCE}
356
+
295
357
  // ── show / hide ──────────────────────────────────────────────────────────────
296
358
  ${MASTER_LOCK_REVEAL_SOURCE}
297
359
  wireMasterLockReveal(document);
@@ -361,15 +423,10 @@ function newKdf() {
361
423
  async function doEnroll(password) {
362
424
  const params = newKdf();
363
425
  const verifier = await deriveVerifier(password, params);
364
- const res = await fetch(paths.enroll, {
365
- method: "POST",
366
- credentials: "same-origin",
367
- headers: { "content-type": "application/json" },
368
- body: JSON.stringify({
369
- kdf: params,
370
- verifier: verifier,
371
- hint: hintInput ? hintInput.value : "",
372
- }),
426
+ const res = await lockWrite(paths.enroll, {
427
+ kdf: params,
428
+ verifier: verifier,
429
+ hint: hintInput ? hintInput.value : "",
373
430
  });
374
431
  if (res.ok) { say("Master password set."); location.reload(); return true; }
375
432
  // The server collapses every enrollment refusal into one, so this cannot say more
@@ -380,12 +437,7 @@ async function doEnroll(password) {
380
437
 
381
438
  async function doUnlock(password) {
382
439
  const verifier = await deriveVerifier(password, kdf);
383
- const res = await fetch(paths.unlock, {
384
- method: "POST",
385
- credentials: "same-origin",
386
- headers: { "content-type": "application/json" },
387
- body: JSON.stringify({ verifier: verifier }),
388
- });
440
+ const res = await lockWrite(paths.unlock, { verifier: verifier });
389
441
  if (res.ok) { say("Unlocked."); location.reload(); return true; }
390
442
  const body = await res.json().catch(() => ({}));
391
443
  input.value = "";
@@ -48,23 +48,39 @@ describe('normalizeRoute', () => {
48
48
  return c.text('');
49
49
  };
50
50
  app.get('/api/notes/:id', gate);
51
- app.use('/api/*', async (c, next) => {
51
+ app.use('*', async (c, next) => {
52
52
  await next();
53
53
  if (c.req.path.includes('gated')) seen.push(normalizeRoute(c).unmatchedPath);
54
54
  });
55
- app.use('/api/*', async (c, next) => (c.req.path.includes('gated') ? c.text('no', 401) : next()));
55
+ app.use('*', async (c, next) => (c.req.path.includes('gated') ? c.text('no', 401) : next()));
56
56
  await app.request('http://x/api/notes/n1');
57
57
  await app.request('http://x/api/gated/my-slug');
58
- await app.request('http://x/api/ctgrte/gated/my-slug');
58
+ await app.request('http://x/ctgrde/api/gated/my-slug');
59
59
  expect(seen).toEqual([undefined, '/api/gated/my-slug', '/api/gated/my-slug']);
60
60
  });
61
61
 
62
62
  test('maps a ctgr GET-twin back to its real verb + path', async () => {
63
63
  const label = await labelFor(
64
- (app) => app.get('/api/ctgrch/notes/:id', probe),
65
- new Request('http://x/api/ctgrch/notes/n1'),
64
+ (app) => app.get('/ctgrpa/api/notes/:id', probe),
65
+ new Request('http://x/ctgrpa/api/notes/n1'),
66
66
  );
67
- // /ctgrch = PATCH twin → aggregates with the real PATCH /api/notes/:id
67
+ // /ctgrpa = PATCH twin → aggregates with the real PATCH /api/notes/:id
68
68
  expect(label).toBe('PATCH /api/notes/:id');
69
69
  });
70
+
71
+ test.each([
72
+ ['/ctgrpo/api/notes', 'POST /api/notes'],
73
+ ['/ctgrpu/api/notes/42', 'PUT /api/notes/:id'],
74
+ ['/ctgrde/api/notes/42', 'DELETE /api/notes/:id'],
75
+ ])('a twin the tunnel catches (%s) counts as the verb the client sent, with its own path collapsed', async (twin, want) => {
76
+ const label = await labelFor((app) => app.get('/:ctgrTwin{ctgr.+}', probe), new Request(`http://x${twin}`));
77
+ expect(label).toBe(want);
78
+ });
79
+
80
+ test('only core\'s verbs make a twin: /ctgrzz/ and a twin buried mid-path stay the GET they are', async () => {
81
+ const zz = await labelFor((app) => app.get('*', probe), new Request('http://x/ctgrzz/api/notes'));
82
+ expect(zz).toBe('GET /ctgrzz/api/notes');
83
+ const buried = await labelFor((app) => app.get('*', probe), new Request('http://x/api/ctgrpo/notes'));
84
+ expect(buried).toBe('GET /api/ctgrpo/notes');
85
+ });
70
86
  });
@@ -1,3 +1,4 @@
1
+ import { ABBREV_TO_METHOD, type CtgrAbbrev, ctgrTwinTarget } from 'cursedbelt-core/ctgr/types';
1
2
  import type { Context } from 'hono';
2
3
 
3
4
  /**
@@ -15,10 +16,6 @@ import type { Context } from 'hono';
15
16
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16
17
  const LONG_HEX_RE = /^[0-9a-f]{16,}$/i;
17
18
 
18
- // The ctgr twin URL is `/ctgr<last-2-of-method><url>`, so the two-letter suffix
19
- // recovers the original verb (POST→st, PUT→ut, PATCH→ch, DELETE→te).
20
- const CTGR_METHOD: Record<string, string> = { st: 'POST', ut: 'PUT', ch: 'PATCH', te: 'DELETE' };
21
-
22
19
  function collapseSegment(seg: string): string {
23
20
  if (!seg) return seg;
24
21
  if (/^\d+$/.test(seg)) return ':id';
@@ -64,13 +61,16 @@ export function normalizeRoute(c: Context): NormalizedRoute {
64
61
  let route = pattern ?? (collapsePath(path) || '/');
65
62
  let unmatchedPath = pattern ? undefined : path;
66
63
 
67
- // Map a ctgr GET-twin back to its real verb + url:
68
- // /api/ctgrch/notes/:id → PATCH /api/notes/:id
69
- const ctgr = route.match(/\/ctgr([a-z]{2})(?=\/|$)/i);
70
- if (ctgr) {
71
- method = CTGR_METHOD[ctgr[1].toLowerCase()] ?? method;
72
- route = route.replace(/\/ctgr[a-z]{2}/i, '') || '/';
73
- unmatchedPath = unmatchedPath?.replace(/\/ctgr[a-z]{2}/i, '') || unmatchedPath;
64
+ // Map a ctgr GET-twin back to its real verb + url: `/ctgrpa/api/notes/n1` → PATCH /api/notes/:id.
65
+ // Which paths are twins, and which verb each stands for, is core's one answer (forge task 5162) —
66
+ // this file's own table once held abbreviations no client sends, so every twin counted as a GET.
67
+ const twin = ctgrTwinTarget(path);
68
+ if (twin !== null) {
69
+ method = ABBREV_TO_METHOD[path.slice(5, 7) as CtgrAbbrev];
70
+ // A route registered at the twin itself is still a real pattern; the tunnel's catch-all is not.
71
+ const realPattern = pattern === undefined ? null : ctgrTwinTarget(pattern);
72
+ route = realPattern ?? (collapsePath(twin) || '/');
73
+ unmatchedPath = realPattern === null ? twin : undefined;
74
74
  }
75
75
 
76
76
  return { method, route, ...(unmatchedPath === undefined ? {} : { unmatchedPath }) };