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.
@@ -1,4 +1,4 @@
1
- import { type CtgrDecoded } from 'cursedbelt-core/ctgr/types';
1
+ import type { CtgrDecoded } from 'cursedbelt-core/ctgr/types';
2
2
  import type { Env, Hono } from 'hono';
3
3
  /**
4
4
  * What the tunnel needs of an accumulator: a {@link ChunkStore}, or one whose partials every
@@ -12,14 +12,18 @@
12
12
  * {@link ChunkStore} (an intermediate chunk answers 202). Legacy `_cv`-absent twins
13
13
  * fall through the v0 decoder. The middleware decodes and re-dispatches only; whatever
14
14
  * gate stands in front of the app (Access, a session cookie, a getOnly claim) is
15
- * unchanged and still runs on the real handler.
15
+ * unchanged and still runs on the real handler. The decoding itself is `./ctgrTwin.ts`,
16
+ * which the master-lock guard shares for its own `/__lock/` twins.
17
+ *
18
+ * 🔴 A twin's query IS its body (`_d`, `_c*`). Nothing here logs it, and `requestLogger`
19
+ * records the route only (`middleware/requestLogger.spec.ts` holds it, forge task 5157).
20
+ * Cloudflare's own invocation logs keep a Worker request's full URL for seven days; they
21
+ * stay on because `autopilot/src/d1Watch.ts` reads them for the requests around a D1 reset.
16
22
  */
17
23
  import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
18
- import { ABBREV_TO_METHOD, } from 'cursedbelt-core/ctgr/types';
19
24
  import { V0ChunkStore } from 'cursedbelt-core/ctgr/v0compat';
20
25
  import { CTGR_ROUTE_PATTERN } from './ctgr.js';
21
- /** Query keys the codec adds to a twin URL — dropped when rebuilding the real request. */
22
- const isCtgrParam = (key) => key === '_d' || key === '_sha' || key.startsWith('_c');
26
+ import { decodeCtgrTwin } from './ctgrTwin.js';
23
27
  /**
24
28
  * Mount the GET-only tunnel on `app`. Call once, on the Hono app whose real routes sit
25
29
  * at the paths the twins mirror (a twin path is `/ctgr<xx>` + the real path). Returns
@@ -29,27 +33,9 @@ export function mountCtgrTunnel(app, options = {}) {
29
33
  const store = options.store ?? new ChunkStore();
30
34
  const legacy = new V0ChunkStore();
31
35
  app.use(CTGR_ROUTE_PATTERN, async (c) => {
32
- const url = new URL(c.req.url);
33
- const params = Object.fromEntries(url.searchParams);
34
- // The twin path is `/ctgr<xx>...`; the abbreviation is the two chars after `ctgr`.
35
- const pathMethod = ABBREV_TO_METHOD[c.req.path.slice(5, 7)];
36
- if (!pathMethod) {
37
- return c.json({ error: 'not found', code: 'NOT_FOUND' }, 404);
38
- }
39
- let result;
40
- try {
41
- result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
42
- }
43
- catch (error) {
44
- console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
45
- return c.json({ error: 'ctgr: the chunk store could not answer — send it again', code: 'CTGR_STORE_UNAVAILABLE' }, 503);
46
- }
47
- if (result === false)
48
- return c.json({ acknowledged: true }, 202);
49
- if (result instanceof Error) {
50
- return c.json({ error: result.message, code: 'BAD_REQUEST' }, 400);
51
- }
52
- const realReq = rebuildRequest(c.req.raw, c.req.path, url, result);
36
+ const decoded = await decodeCtgrTwin(c.req.raw, c.req.path, store, legacy);
37
+ if (decoded instanceof Response)
38
+ return decoded;
53
39
  // Re-enter the app at the real route. The real path never starts with `/ctgr`, so
54
40
  // this middleware does not re-match — no recursion.
55
41
  let executionCtx;
@@ -59,40 +45,7 @@ export function mountCtgrTunnel(app, options = {}) {
59
45
  catch {
60
46
  executionCtx = undefined;
61
47
  }
62
- return app.fetch(realReq, c.env, executionCtx);
48
+ return app.fetch(decoded, c.env, executionCtx);
63
49
  });
64
50
  return store;
65
51
  }
66
- /** Build the real Request the decoded twin stands in for. */
67
- function rebuildRequest(raw, twinPath, url, decoded) {
68
- // Strip the `/ctgr<xx>` prefix and the codec's own query params; keep the rest.
69
- const realPath = twinPath.replace(/^\/ctgr../, '') || '/';
70
- const kept = new URLSearchParams();
71
- for (const [key, value] of url.searchParams) {
72
- if (!isCtgrParam(key))
73
- kept.set(key, value);
74
- }
75
- const search = kept.toString();
76
- const realUrl = `${url.origin}${realPath}${search ? `?${search}` : ''}`;
77
- const headers = new Headers(raw.headers);
78
- headers.delete('content-length');
79
- let body;
80
- if (decoded.files && decoded.files.length > 0) {
81
- const form = new FormData();
82
- const fields = (decoded.body ?? {});
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
- }
93
- else if (decoded.body !== undefined) {
94
- body = JSON.stringify(decoded.body);
95
- headers.set('content-type', 'application/json');
96
- }
97
- return new Request(realUrl, { method: decoded.method, headers, body });
98
- }
@@ -0,0 +1,8 @@
1
+ import type { V0ChunkStore } from 'cursedbelt-core/ctgr/v0compat';
2
+ import type { CtgrChunkSink } from './ctgrTunnel.js';
3
+ /**
4
+ * Decode `raw`, a twin whose path is `twinPath` (`/ctgr<xx>` + the real path). A Request is the
5
+ * real request, ready to dispatch; a Response is the whole answer (a cross-site twin 403, an
6
+ * unknown verb 404, an intermediate chunk 202, a bad payload 400, a store that could not answer 503).
7
+ */
8
+ export declare function decodeCtgrTwin(raw: Request, twinPath: string, store: CtgrChunkSink, legacy: V0ChunkStore): Promise<Request | Response>;
@@ -0,0 +1,79 @@
1
+ import { ABBREV_TO_METHOD } from 'cursedbelt-core/ctgr/types';
2
+ /** Query keys the codec adds to a twin URL — dropped when rebuilding the real request. */
3
+ const isCtgrParam = (key) => key === '_d' || key === '_sha' || key.startsWith('_c');
4
+ const json = (body, status) => Response.json(body, { status });
5
+ /**
6
+ * Decode `raw`, a twin whose path is `twinPath` (`/ctgr<xx>` + the real path). A Request is the
7
+ * real request, ready to dispatch; a Response is the whole answer (a cross-site twin 403, an
8
+ * unknown verb 404, an intermediate chunk 202, a bad payload 400, a store that could not answer 503).
9
+ */
10
+ export async function decodeCtgrTwin(raw, twinPath, store, legacy) {
11
+ // 🔴 A twin is a GET, and a GET is what SameSite=Lax sends another site's cookie on: a link
12
+ // on any page would otherwise become a signed-in write the real POST could never make
13
+ // (found wiring vault, forge task 4807). The page's own twins are same-origin fetches.
14
+ if (isCrossSiteTwin(raw)) {
15
+ return json({ error: "ctgr: a write twin is accepted from this app's own pages only", code: 'CTGR_CROSS_SITE' }, 403);
16
+ }
17
+ const url = new URL(raw.url);
18
+ const params = Object.fromEntries(url.searchParams);
19
+ // The twin path is `/ctgr<xx>...`; the abbreviation is the two chars after `ctgr`.
20
+ const pathMethod = ABBREV_TO_METHOD[twinPath.slice(5, 7)];
21
+ if (!pathMethod)
22
+ return json({ error: 'not found', code: 'NOT_FOUND' }, 404);
23
+ let result;
24
+ try {
25
+ result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
26
+ }
27
+ catch (error) {
28
+ console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
29
+ return json({ error: 'ctgr: the chunk store could not answer — send it again', code: 'CTGR_STORE_UNAVAILABLE' }, 503);
30
+ }
31
+ if (result === false)
32
+ return json({ acknowledged: true }, 202);
33
+ if (result instanceof Error)
34
+ return json({ error: result.message, code: 'BAD_REQUEST' }, 400);
35
+ return rebuildRequest(raw, twinPath, url, result);
36
+ }
37
+ /**
38
+ * Did a browser say this twin came from somewhere else? `Sec-Fetch-Site` is set by the browser
39
+ * and no page can forge it: only `same-origin` is the app's own `installCtgrFetch`. `none` (a
40
+ * typed URL or bookmark), `same-site` and `cross-site` are refused. A browser too old to send it
41
+ * passes, because the GET-only devices this exists for may be that old; the gate still applies.
42
+ */
43
+ function isCrossSiteTwin(request) {
44
+ const site = request.headers.get('sec-fetch-site');
45
+ return site !== null && site !== 'same-origin';
46
+ }
47
+ /** Build the real Request the decoded twin stands in for. */
48
+ function rebuildRequest(raw, twinPath, url, decoded) {
49
+ // Strip the `/ctgr<xx>` prefix and the codec's own query params; keep the rest.
50
+ const realPath = twinPath.replace(/^\/ctgr../, '') || '/';
51
+ const kept = new URLSearchParams();
52
+ for (const [key, value] of url.searchParams) {
53
+ if (!isCtgrParam(key))
54
+ kept.set(key, value);
55
+ }
56
+ const search = kept.toString();
57
+ const realUrl = `${url.origin}${realPath}${search ? `?${search}` : ''}`;
58
+ const headers = new Headers(raw.headers);
59
+ headers.delete('content-length');
60
+ let body;
61
+ if (decoded.files && decoded.files.length > 0) {
62
+ const form = new FormData();
63
+ const fields = (decoded.body ?? {});
64
+ for (const [key, value] of Object.entries(fields)) {
65
+ form.append(key, typeof value === 'string' ? value : JSON.stringify(value));
66
+ }
67
+ for (const file of decoded.files) {
68
+ form.append(file.fieldname, new File([new Uint8Array(file.buffer)], file.originalname, { type: file.mimetype }));
69
+ }
70
+ body = form;
71
+ // Let the runtime set the multipart content-type + boundary.
72
+ headers.delete('content-type');
73
+ }
74
+ else if (decoded.body !== undefined) {
75
+ body = JSON.stringify(decoded.body);
76
+ headers.set('content-type', 'application/json');
77
+ }
78
+ return new Request(realUrl, { method: decoded.method, headers, body });
79
+ }
@@ -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, withRevealToggles } from "./lockPage.js";
36
+ import { MASTER_LOCK_DERIVE_SOURCE, MASTER_LOCK_MIN_PASSWORD_LENGTH, MASTER_LOCK_REVEAL_SOURCE, MASTER_LOCK_WRITE_SOURCE, withRevealToggles } from "./lockPage.js";
37
37
  /**
38
38
  * The page's own two assets.
39
39
  *
@@ -211,6 +211,7 @@ const MIN_LENGTH = ${MASTER_LOCK_MIN_PASSWORD_LENGTH};
211
211
 
212
212
  // ── derivation ───────────────────────────────────────────────────────────────
213
213
  ${MASTER_LOCK_DERIVE_SOURCE}
214
+ ${MASTER_LOCK_WRITE_SOURCE}
214
215
 
215
216
  // ── show / hide ──────────────────────────────────────────────────────────────
216
217
  ${MASTER_LOCK_REVEAL_SOURCE}
@@ -232,12 +233,7 @@ function say(form, message, tone) {
232
233
  }
233
234
 
234
235
  async function post(path, body, method) {
235
- const res = await fetch(path, {
236
- method: method || "POST",
237
- credentials: "same-origin",
238
- headers: { "content-type": "application/json" },
239
- body: JSON.stringify(body),
240
- });
236
+ const res = await lockWrite(path, body, method);
241
237
  const parsed = await res.json().catch(() => ({}));
242
238
  return { ok: res.ok, status: res.status, body: parsed || {} };
243
239
  }
@@ -13,6 +13,10 @@
13
13
  */
14
14
  import { MASTER_LOCK_PATHS, MASTER_LOCK_PREFIX, MASTER_LOCK_STATE_HEADER, masterLockCookieName, } from "cursedbelt-core/master-lock";
15
15
  import { MASTER_LOCK_ACCOUNTS_PAGE_PATHS, MASTER_LOCK_ACCOUNTS_SCRIPT, MASTER_LOCK_ACCOUNTS_STYLE, accountsPageHtml, } from "./accountsPage.js";
16
+ import { ChunkStore } from "cursedbelt-core/ctgr/chunk-store";
17
+ import { isCtgrTwinOf } from "cursedbelt-core/ctgr/types";
18
+ import { V0ChunkStore } from "cursedbelt-core/ctgr/v0compat";
19
+ import { decodeCtgrTwin } from "../ctgrTwin.js";
16
20
  import { LOCK_SCRIPT, LOCK_STYLE, lockPageHtml } from "./lockPage.js";
17
21
  const noStore = { "cache-control": "no-store, no-cache, must-revalidate", pragma: "no-cache" };
18
22
  /**
@@ -232,36 +236,50 @@ export function createMasterLockGuard(options) {
232
236
  }
233
237
  return new Response("not found", { status: 404, headers: noStore });
234
238
  }
239
+ // A lock write is one small JSON body, so its twin is one chunk; the store only holds the rare split.
240
+ const twinStore = new ChunkStore();
241
+ const twinLegacy = new V0ChunkStore();
242
+ async function handle(req) {
243
+ const url = new URL(req.url);
244
+ // 🔴 The twin is DECODED here and the real request judged by the very rule below, so the
245
+ // wall decides an unlock's twin exactly as it decides the POST, whichever of this guard and
246
+ // `mountCtgrTunnel` an app mounts first — and in a bare `Bun.serve` app that has no tunnel.
247
+ // A GET-only device's twin of a lock write: `/ctgr<xx>/__lock/…` (forge task 5158). Its writes —
248
+ // unlock, enroll, ping, lock — would otherwise reach the wall as a GET to a path that is not the
249
+ // lock's, and be refused, so such a device could never get in. Core says what a twin is (task 5162).
250
+ if (isCtgrTwinOf(url.pathname, MASTER_LOCK_PREFIX)) {
251
+ const decoded = await decodeCtgrTwin(req, url.pathname, twinStore, twinLegacy);
252
+ return decoded instanceof Response ? decoded : handle(decoded);
253
+ }
254
+ const own = url.pathname === MASTER_LOCK_PREFIX || url.pathname.startsWith(`${MASTER_LOCK_PREFIX}/`);
255
+ const lock = resolve(req);
256
+ if (!lock) {
257
+ // No principal. On the app's own paths the caller is not signed in and the
258
+ // app's sign-in owns the request; on `/__lock/*` there is nobody to unlock
259
+ // FOR, and answering the ordinary refusal keeps that indistinguishable from
260
+ // being locked.
261
+ return own ? refuse() : null;
262
+ }
263
+ if (own)
264
+ return handleOwnRoute(req, url, lock);
265
+ if (options.allow?.(url, req))
266
+ return null;
267
+ if (opens(lock, req))
268
+ return null;
269
+ // A document request is answered IN PLACE with the lock page — same URL, status
270
+ // 200 — so unlocking reloads to where they were going instead of dumping them at
271
+ // the root. Everything else gets the uniform refusal.
272
+ if (wantsDocument(req))
273
+ return lockPage(options, lock);
274
+ return refuse();
275
+ }
235
276
  return {
277
+ handle,
236
278
  accountFor(req) {
237
279
  // The SAME resolution the guard itself uses, so an app can never be told a
238
280
  // different tenant from the one the wall admitted.
239
281
  return resolve(req)?.accountFor(req) ?? null;
240
282
  },
241
- async handle(req) {
242
- const url = new URL(req.url);
243
- const own = url.pathname === MASTER_LOCK_PREFIX || url.pathname.startsWith(`${MASTER_LOCK_PREFIX}/`);
244
- const lock = resolve(req);
245
- if (!lock) {
246
- // No principal. On the app's own paths the caller is not signed in and the
247
- // app's sign-in owns the request; on `/__lock/*` there is nobody to unlock
248
- // FOR, and answering the ordinary refusal keeps that indistinguishable from
249
- // being locked.
250
- return own ? refuse() : null;
251
- }
252
- if (own)
253
- return handleOwnRoute(req, url, lock);
254
- if (options.allow?.(url, req))
255
- return null;
256
- if (opens(lock, req))
257
- return null;
258
- // A document request is answered IN PLACE with the lock page — same URL, status
259
- // 200 — so unlocking reloads to where they were going instead of dumping them at
260
- // the root. Everything else gets the uniform refusal.
261
- if (wantsDocument(req))
262
- return lockPage(options, lock);
263
- return refuse();
264
- },
265
283
  };
266
284
  }
267
285
  function lockPage(options, lock) {
@@ -52,6 +52,18 @@ export declare const MASTER_LOCK_REVEAL_SOURCE = "function wireMasterLockReveal(
52
52
  * out through and the seam the accounts page's script calls it back through.
53
53
  */
54
54
  export declare const MASTER_LOCK_DERIVE_SOURCE = "function unb64u(text) {\n const padded = text.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);\n return out;\n}\nfunction b64u(bytes) {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\nasync function pbkdf2(material, salt, iterations) {\n const key = await crypto.subtle.importKey(\"raw\", material, \"PBKDF2\", false, [\"deriveBits\"]);\n const bits = await crypto.subtle.deriveBits(\n { name: \"PBKDF2\", salt: salt, iterations: iterations, hash: \"SHA-256\" }, key, 256);\n return new Uint8Array(bits);\n}\nasync function deriveVerifier(password, kdf) {\n const salt = unb64u(kdf.salt);\n const bytes = new TextEncoder().encode(password);\n const kek = await pbkdf2(bytes, salt, kdf.iter);\n const joined = new Uint8Array(kek.length + bytes.length);\n joined.set(kek, 0);\n joined.set(bytes, kek.length);\n return b64u(await pbkdf2(joined, salt, 1));\n}\nglobalThis.__masterLockDerive = deriveVerifier;";
55
+ /**
56
+ * 🔴 The lock pages' ONE way to send a write — `lockWrite(path, body, method)` — and a GET-only
57
+ * device's way in (forge task 5158). A locked app answers its own document with the lock page, so
58
+ * the app's `installCtgrFetch` never runs here: this page reads `?ctgr=` itself (the same intent
59
+ * words and `localStorage` key as `cursedbelt-core/ctgr-client`) and, while the mode is on, sends
60
+ * the write as its one-chunk v1 `/ctgr<xx>` GET twin, which the guard decodes and judges as the
61
+ * POST it carries. A lock body is a few hundred bytes, so it is never gzipped or split.
62
+ *
63
+ * Interpolates {@link MASTER_LOCK_DERIVE_SOURCE}'s `b64u`, so it follows it in a script. Pinned by
64
+ * `lockPage.spec.ts`, which evaluates it and decodes what it sends with core's own codec.
65
+ */
66
+ export declare const MASTER_LOCK_WRITE_SOURCE: string;
55
67
  /**
56
68
  * The page's script.
57
69
  *
@@ -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
  * The shortest master password the wall accepts — every `minlength` on both pages and both
@@ -234,6 +235,63 @@ async function deriveVerifier(password, kdf) {
234
235
  return b64u(await pbkdf2(joined, salt, 1));
235
236
  }
236
237
  globalThis.__masterLockDerive = deriveVerifier;`;
238
+ /**
239
+ * 🔴 The lock pages' ONE way to send a write — `lockWrite(path, body, method)` — and a GET-only
240
+ * device's way in (forge task 5158). A locked app answers its own document with the lock page, so
241
+ * the app's `installCtgrFetch` never runs here: this page reads `?ctgr=` itself (the same intent
242
+ * words and `localStorage` key as `cursedbelt-core/ctgr-client`) and, while the mode is on, sends
243
+ * the write as its one-chunk v1 `/ctgr<xx>` GET twin, which the guard decodes and judges as the
244
+ * POST it carries. A lock body is a few hundred bytes, so it is never gzipped or split.
245
+ *
246
+ * Interpolates {@link MASTER_LOCK_DERIVE_SOURCE}'s `b64u`, so it follows it in a script. Pinned by
247
+ * `lockPage.spec.ts`, which evaluates it and decodes what it sends with core's own codec.
248
+ */
249
+ export const MASTER_LOCK_WRITE_SOURCE = `const CTGR_ABBREV = ${JSON.stringify(METHOD_TO_ABBREV)};
250
+ function ctgrModeOn() {
251
+ try {
252
+ const intent = new URLSearchParams(location.search).get("ctgr");
253
+ const word = intent === null ? "" : intent.trim().toLowerCase();
254
+ if (["t", "on", "1", "yes", "true"].indexOf(word) >= 0) localStorage.setItem("ctgr", "on");
255
+ else if (["f", "off", "0", "no", "false"].indexOf(word) >= 0) localStorage.removeItem("ctgr");
256
+ return localStorage.getItem("ctgr") === "on";
257
+ } catch (e) {
258
+ return false;
259
+ }
260
+ }
261
+ function ctgrCrc32(bytes) {
262
+ let crc = 0xffffffff;
263
+ for (let i = 0; i < bytes.length; i += 1) {
264
+ crc ^= bytes[i];
265
+ for (let k = 0; k < 8; k += 1) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
266
+ }
267
+ return (crc ^ 0xffffffff) >>> 0;
268
+ }
269
+ async function lockWrite(path, body, method) {
270
+ const verb = (method || "POST").toUpperCase();
271
+ const text = JSON.stringify(body === undefined ? null : body);
272
+ if (!ctgrModeOn()) {
273
+ return fetch(path, {
274
+ method: verb,
275
+ credentials: "same-origin",
276
+ headers: { "content-type": "application/json" },
277
+ body: text,
278
+ });
279
+ }
280
+ const raw = new TextEncoder().encode(text);
281
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", raw));
282
+ let sha = "";
283
+ for (const byte of digest) sha += byte.toString(16).padStart(2, "0");
284
+ // The id keys the chunk accumulator for one in-flight payload, and a one-chunk twin completes
285
+ // on arrival, so the body's hash and the clock make it. No randomness: the accounts page proves
286
+ // its script cannot mint a kdf by holding none (accountsPage.spec.ts).
287
+ const query = new URLSearchParams({
288
+ _cv: ${JSON.stringify(CTGR_WIRE_VERSION)}, _cm: CTGR_ABBREV[verb], _cg: "0", _ci: "0", _ct: "1",
289
+ _cl: String(raw.length), _cid: sha.slice(0, 16) + Date.now().toString(36),
290
+ _crc: String(ctgrCrc32(raw)), _d: b64u(raw), _sha: sha,
291
+ });
292
+ return fetch("/ctgr" + CTGR_ABBREV[verb] + path + "?" + query.toString(), { credentials: "same-origin" });
293
+ }
294
+ globalThis.__masterLockWrite = lockWrite;`;
237
295
  /**
238
296
  * The page's script.
239
297
  *
@@ -248,6 +306,9 @@ export const LOCK_SCRIPT = `const paths = ${JSON.stringify(MASTER_LOCK_PATHS)};
248
306
  // ── derivation ───────────────────────────────────────────────────────────────
249
307
  ${MASTER_LOCK_DERIVE_SOURCE}
250
308
 
309
+ // ── writes (a GET-only device's twins) ───────────────────────────────────────
310
+ ${MASTER_LOCK_WRITE_SOURCE}
311
+
251
312
  // ── show / hide ──────────────────────────────────────────────────────────────
252
313
  ${MASTER_LOCK_REVEAL_SOURCE}
253
314
  wireMasterLockReveal(document);
@@ -317,15 +378,10 @@ function newKdf() {
317
378
  async function doEnroll(password) {
318
379
  const params = newKdf();
319
380
  const verifier = await deriveVerifier(password, params);
320
- const res = await fetch(paths.enroll, {
321
- method: "POST",
322
- credentials: "same-origin",
323
- headers: { "content-type": "application/json" },
324
- body: JSON.stringify({
325
- kdf: params,
326
- verifier: verifier,
327
- hint: hintInput ? hintInput.value : "",
328
- }),
381
+ const res = await lockWrite(paths.enroll, {
382
+ kdf: params,
383
+ verifier: verifier,
384
+ hint: hintInput ? hintInput.value : "",
329
385
  });
330
386
  if (res.ok) { say("Master password set."); location.reload(); return true; }
331
387
  // The server collapses every enrollment refusal into one, so this cannot say more
@@ -336,12 +392,7 @@ async function doEnroll(password) {
336
392
 
337
393
  async function doUnlock(password) {
338
394
  const verifier = await deriveVerifier(password, kdf);
339
- const res = await fetch(paths.unlock, {
340
- method: "POST",
341
- credentials: "same-origin",
342
- headers: { "content-type": "application/json" },
343
- body: JSON.stringify({ verifier: verifier }),
344
- });
395
+ const res = await lockWrite(paths.unlock, { verifier: verifier });
345
396
  if (res.ok) { say("Unlocked."); location.reload(); return true; }
346
397
  const body = await res.json().catch(() => ({}));
347
398
  input.value = "";
@@ -1,3 +1,4 @@
1
+ import { ABBREV_TO_METHOD, ctgrTwinTarget } from 'cursedbelt-core/ctgr/types';
1
2
  /**
2
3
  * Turn a request into a stable, low-cardinality route label for metric aggregation
3
4
  * (e.g. `/api/v1/notes/:id`). The method is tracked separately.
@@ -11,9 +12,6 @@
11
12
  */
12
13
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
14
  const LONG_HEX_RE = /^[0-9a-f]{16,}$/i;
14
- // The ctgr twin URL is `/ctgr<last-2-of-method><url>`, so the two-letter suffix
15
- // recovers the original verb (POST→st, PUT→ut, PATCH→ch, DELETE→te).
16
- const CTGR_METHOD = { st: 'POST', ut: 'PUT', ch: 'PATCH', te: 'DELETE' };
17
15
  function collapseSegment(seg) {
18
16
  if (!seg)
19
17
  return seg;
@@ -50,13 +48,16 @@ export function normalizeRoute(c) {
50
48
  const path = c.req.path.split('?')[0];
51
49
  let route = pattern ?? (collapsePath(path) || '/');
52
50
  let unmatchedPath = pattern ? undefined : path;
53
- // Map a ctgr GET-twin back to its real verb + url:
54
- // /api/ctgrch/notes/:id → PATCH /api/notes/:id
55
- const ctgr = route.match(/\/ctgr([a-z]{2})(?=\/|$)/i);
56
- if (ctgr) {
57
- method = CTGR_METHOD[ctgr[1].toLowerCase()] ?? method;
58
- route = route.replace(/\/ctgr[a-z]{2}/i, '') || '/';
59
- unmatchedPath = unmatchedPath?.replace(/\/ctgr[a-z]{2}/i, '') || unmatchedPath;
51
+ // Map a ctgr GET-twin back to its real verb + url: `/ctgrpa/api/notes/n1` → PATCH /api/notes/:id.
52
+ // Which paths are twins, and which verb each stands for, is core's one answer (forge task 5162) —
53
+ // this file's own table once held abbreviations no client sends, so every twin counted as a GET.
54
+ const twin = ctgrTwinTarget(path);
55
+ if (twin !== null) {
56
+ method = ABBREV_TO_METHOD[path.slice(5, 7)];
57
+ // A route registered at the twin itself is still a real pattern; the tunnel's catch-all is not.
58
+ const realPattern = pattern === undefined ? null : ctgrTwinTarget(pattern);
59
+ route = realPattern ?? (collapsePath(twin) || '/');
60
+ unmatchedPath = realPattern === null ? twin : undefined;
60
61
  }
61
62
  return { method, route, ...(unmatchedPath === undefined ? {} : { unmatchedPath }) };
62
63
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.71.0",
3
+ "version": "4.73.1",
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.",
@@ -400,7 +400,7 @@
400
400
  },
401
401
  "dependencies": {
402
402
  "argon2id": "1.0.1",
403
- "cursedbelt-core": "^2.18.0",
403
+ "cursedbelt-core": "^2.20.0",
404
404
  "cursedops": ">=0.8.1 <1.0.0",
405
405
  "cwip": "^4.6.0",
406
406
  "jose": "^6.2.3"
@@ -441,7 +441,7 @@
441
441
  "@node-rs/argon2": "^2.0.2",
442
442
  "@types/bun": "^1.3.14",
443
443
  "@types/node": "^24",
444
- "cursedbelt": "^6.1.0",
444
+ "cursedbelt": "^6.2.0",
445
445
  "hono": "4.12.28",
446
446
  "kysely": "^0.28.17",
447
447
  "kysely-bun-sqlite": "^0.4.0",
@@ -44,6 +44,18 @@ const fetchTwin = (app: Hono<CursedbeltEnv>, url: string) =>
44
44
  app.fetch(new Request(ORIGIN + url));
45
45
 
46
46
  describe('mountCtgrTunnel — re-dispatch, zero handler changes', () => {
47
+ test('🔴 a twin another site sent is refused before it is decoded — Lax cookies ride a cross-site GET (forge task 4807)', async () => {
48
+ const { app } = makeApp();
49
+ const { chunks } = await encodeRequest('DELETE', '/api/v1/notes/abc', undefined);
50
+ for (const site of ['cross-site', 'same-site', 'none']) {
51
+ const res = await app.fetch(new Request(ORIGIN + chunks[0].url, { headers: { 'sec-fetch-site': site } }));
52
+ expect(res.status).toBe(403);
53
+ expect(((await res.json()) as { code: string }).code).toBe('CTGR_CROSS_SITE');
54
+ }
55
+ const own = await app.fetch(new Request(ORIGIN + chunks[0].url, { headers: { 'sec-fetch-site': 'same-origin' } }));
56
+ expect(await own.json()).toMatchObject({ ok: true, id: 'abc', method: 'DELETE' });
57
+ });
58
+
47
59
  test('a single-chunk POST twin reaches the real handler with the decoded body', async () => {
48
60
  const { app } = makeApp();
49
61
  const { chunks } = await encodeRequest('POST', '/api/v1/notes', { title: 'hi', n: 1 });
@@ -12,21 +12,20 @@
12
12
  * {@link ChunkStore} (an intermediate chunk answers 202). Legacy `_cv`-absent twins
13
13
  * fall through the v0 decoder. The middleware decodes and re-dispatches only; whatever
14
14
  * gate stands in front of the app (Access, a session cookie, a getOnly claim) is
15
- * unchanged and still runs on the real handler.
15
+ * unchanged and still runs on the real handler. The decoding itself is `./ctgrTwin.ts`,
16
+ * which the master-lock guard shares for its own `/__lock/` twins.
17
+ *
18
+ * 🔴 A twin's query IS its body (`_d`, `_c*`). Nothing here logs it, and `requestLogger`
19
+ * records the route only (`middleware/requestLogger.spec.ts` holds it, forge task 5157).
20
+ * Cloudflare's own invocation logs keep a Worker request's full URL for seven days; they
21
+ * stay on because `autopilot/src/d1Watch.ts` reads them for the requests around a D1 reset.
16
22
  */
17
23
  import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
18
- import {
19
- ABBREV_TO_METHOD,
20
- type CtgrAbbrev,
21
- type CtgrDecoded,
22
- } from 'cursedbelt-core/ctgr/types';
24
+ import type { CtgrDecoded } from 'cursedbelt-core/ctgr/types';
23
25
  import { V0ChunkStore } from 'cursedbelt-core/ctgr/v0compat';
24
26
  import type { Env, ExecutionContext, Hono } from 'hono';
25
27
  import { CTGR_ROUTE_PATTERN } from './ctgr.js';
26
-
27
- /** Query keys the codec adds to a twin URL — dropped when rebuilding the real request. */
28
- const isCtgrParam = (key: string): boolean =>
29
- key === '_d' || key === '_sha' || key.startsWith('_c');
28
+ import { decodeCtgrTwin } from './ctgrTwin.js';
30
29
 
31
30
  /**
32
31
  * What the tunnel needs of an accumulator: a {@link ChunkStore}, or one whose partials every
@@ -64,28 +63,8 @@ export function mountCtgrTunnel<E extends Env = Env>(
64
63
  const legacy = new V0ChunkStore();
65
64
 
66
65
  app.use(CTGR_ROUTE_PATTERN, async (c) => {
67
- const url = new URL(c.req.url);
68
- const params = Object.fromEntries(url.searchParams);
69
- // The twin path is `/ctgr<xx>...`; the abbreviation is the two chars after `ctgr`.
70
- const pathMethod = ABBREV_TO_METHOD[c.req.path.slice(5, 7) as CtgrAbbrev];
71
- if (!pathMethod) {
72
- return c.json({ error: 'not found', code: 'NOT_FOUND' }, 404);
73
- }
74
-
75
- let result: CtgrDecoded | false | Error;
76
- try {
77
- result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
78
- } catch (error) {
79
- console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
80
- return c.json({ error: 'ctgr: the chunk store could not answer — send it again', code: 'CTGR_STORE_UNAVAILABLE' }, 503);
81
- }
82
-
83
- if (result === false) return c.json({ acknowledged: true }, 202);
84
- if (result instanceof Error) {
85
- return c.json({ error: result.message, code: 'BAD_REQUEST' }, 400);
86
- }
87
-
88
- const realReq = rebuildRequest(c.req.raw, c.req.path, url, result);
66
+ const decoded = await decodeCtgrTwin(c.req.raw, c.req.path, store, legacy);
67
+ if (decoded instanceof Response) return decoded;
89
68
  // Re-enter the app at the real route. The real path never starts with `/ctgr`, so
90
69
  // this middleware does not re-match — no recursion.
91
70
  let executionCtx: ExecutionContext | undefined;
@@ -94,46 +73,8 @@ export function mountCtgrTunnel<E extends Env = Env>(
94
73
  } catch {
95
74
  executionCtx = undefined;
96
75
  }
97
- return app.fetch(realReq, c.env as never, executionCtx);
76
+ return app.fetch(decoded, c.env as never, executionCtx);
98
77
  });
99
78
 
100
79
  return store;
101
80
  }
102
-
103
- /** Build the real Request the decoded twin stands in for. */
104
- function rebuildRequest(raw: Request, twinPath: string, url: URL, decoded: CtgrDecoded): Request {
105
- // Strip the `/ctgr<xx>` prefix and the codec's own query params; keep the rest.
106
- const realPath = twinPath.replace(/^\/ctgr../, '') || '/';
107
- const kept = new URLSearchParams();
108
- for (const [key, value] of url.searchParams) {
109
- if (!isCtgrParam(key)) kept.set(key, value);
110
- }
111
- const search = kept.toString();
112
- const realUrl = `${url.origin}${realPath}${search ? `?${search}` : ''}`;
113
-
114
- const headers = new Headers(raw.headers);
115
- headers.delete('content-length');
116
-
117
- let body: BodyInit | undefined;
118
- if (decoded.files && decoded.files.length > 0) {
119
- const form = new FormData();
120
- const fields = (decoded.body ?? {}) as Record<string, unknown>;
121
- for (const [key, value] of Object.entries(fields)) {
122
- form.append(key, typeof value === 'string' ? value : JSON.stringify(value));
123
- }
124
- for (const file of decoded.files) {
125
- form.append(
126
- file.fieldname,
127
- new File([new Uint8Array(file.buffer)], file.originalname, { type: file.mimetype }),
128
- );
129
- }
130
- body = form;
131
- // Let the runtime set the multipart content-type + boundary.
132
- headers.delete('content-type');
133
- } else if (decoded.body !== undefined) {
134
- body = JSON.stringify(decoded.body);
135
- headers.set('content-type', 'application/json');
136
- }
137
-
138
- return new Request(realUrl, { method: decoded.method, headers, body });
139
- }