cursedbelt-server 4.71.0 → 4.73.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/ctgrTunnel.d.ts +1 -1
- package/dist/server/ctgrTunnel.js +12 -59
- package/dist/server/ctgrTwin.d.ts +8 -0
- package/dist/server/ctgrTwin.js +79 -0
- package/dist/server/master-lock/accountsPage.js +3 -7
- package/dist/server/master-lock/guard.js +44 -24
- package/dist/server/master-lock/lockPage.d.ts +12 -0
- package/dist/server/master-lock/lockPage.js +66 -15
- package/package.json +2 -2
- package/src/server/ctgrTunnel.spec.ts +12 -0
- package/src/server/ctgrTunnel.ts +12 -71
- package/src/server/ctgrTwin.ts +98 -0
- package/src/server/master-lock/accountsPage.ts +3 -7
- package/src/server/master-lock/ctgrLockTwin.spec.ts +151 -0
- package/src/server/master-lock/guard.ts +45 -22
- package/src/server/master-lock/lockPage.ts +67 -15
- package/src/server/middleware/requestLogger.spec.ts +95 -0
|
@@ -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
|
-
|
|
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
|
|
33
|
-
|
|
34
|
-
|
|
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(
|
|
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
|
|
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,8 +13,17 @@
|
|
|
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 { V0ChunkStore } from "cursedbelt-core/ctgr/v0compat";
|
|
18
|
+
import { decodeCtgrTwin } from "../ctgrTwin.js";
|
|
16
19
|
import { LOCK_SCRIPT, LOCK_STYLE, lockPageHtml } from "./lockPage.js";
|
|
17
20
|
const noStore = { "cache-control": "no-store, no-cache, must-revalidate", pragma: "no-cache" };
|
|
21
|
+
/**
|
|
22
|
+
* A GET-only device's twin of a lock write: `/ctgr<xx>/__lock/…` (forge task 5158). Its writes —
|
|
23
|
+
* unlock, enroll, ping, lock — would otherwise reach the wall as a GET to a path that is not the
|
|
24
|
+
* lock's, and be refused, so such a device could never get in.
|
|
25
|
+
*/
|
|
26
|
+
const LOCK_TWIN = new RegExp(`^/ctgr[a-z]{2}${MASTER_LOCK_PREFIX}(?:/|$)`, "i");
|
|
18
27
|
/**
|
|
19
28
|
* The lock page's own CSP. Strict enough to stand in front of `apps/vault`'s wall without
|
|
20
29
|
* loosening it: nothing loads from anywhere but this origin, the form posts nowhere (the
|
|
@@ -232,36 +241,47 @@ export function createMasterLockGuard(options) {
|
|
|
232
241
|
}
|
|
233
242
|
return new Response("not found", { status: 404, headers: noStore });
|
|
234
243
|
}
|
|
244
|
+
// A lock write is one small JSON body, so its twin is one chunk; the store only holds the rare split.
|
|
245
|
+
const twinStore = new ChunkStore();
|
|
246
|
+
const twinLegacy = new V0ChunkStore();
|
|
247
|
+
async function handle(req) {
|
|
248
|
+
const url = new URL(req.url);
|
|
249
|
+
// 🔴 The twin is DECODED here and the real request judged by the very rule below, so the
|
|
250
|
+
// wall decides an unlock's twin exactly as it decides the POST, whichever of this guard and
|
|
251
|
+
// `mountCtgrTunnel` an app mounts first — and in a bare `Bun.serve` app that has no tunnel.
|
|
252
|
+
if (LOCK_TWIN.test(url.pathname)) {
|
|
253
|
+
const decoded = await decodeCtgrTwin(req, url.pathname, twinStore, twinLegacy);
|
|
254
|
+
return decoded instanceof Response ? decoded : handle(decoded);
|
|
255
|
+
}
|
|
256
|
+
const own = url.pathname === MASTER_LOCK_PREFIX || url.pathname.startsWith(`${MASTER_LOCK_PREFIX}/`);
|
|
257
|
+
const lock = resolve(req);
|
|
258
|
+
if (!lock) {
|
|
259
|
+
// No principal. On the app's own paths the caller is not signed in and the
|
|
260
|
+
// app's sign-in owns the request; on `/__lock/*` there is nobody to unlock
|
|
261
|
+
// FOR, and answering the ordinary refusal keeps that indistinguishable from
|
|
262
|
+
// being locked.
|
|
263
|
+
return own ? refuse() : null;
|
|
264
|
+
}
|
|
265
|
+
if (own)
|
|
266
|
+
return handleOwnRoute(req, url, lock);
|
|
267
|
+
if (options.allow?.(url, req))
|
|
268
|
+
return null;
|
|
269
|
+
if (opens(lock, req))
|
|
270
|
+
return null;
|
|
271
|
+
// A document request is answered IN PLACE with the lock page — same URL, status
|
|
272
|
+
// 200 — so unlocking reloads to where they were going instead of dumping them at
|
|
273
|
+
// the root. Everything else gets the uniform refusal.
|
|
274
|
+
if (wantsDocument(req))
|
|
275
|
+
return lockPage(options, lock);
|
|
276
|
+
return refuse();
|
|
277
|
+
}
|
|
235
278
|
return {
|
|
279
|
+
handle,
|
|
236
280
|
accountFor(req) {
|
|
237
281
|
// The SAME resolution the guard itself uses, so an app can never be told a
|
|
238
282
|
// different tenant from the one the wall admitted.
|
|
239
283
|
return resolve(req)?.accountFor(req) ?? null;
|
|
240
284
|
},
|
|
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
285
|
};
|
|
266
286
|
}
|
|
267
287
|
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
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
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
|
|
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 = "";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.73.0",
|
|
4
4
|
"license": "ISC",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
|
|
@@ -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.
|
|
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 });
|
package/src/server/ctgrTunnel.ts
CHANGED
|
@@ -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
|
|
68
|
-
|
|
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(
|
|
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
|
-
}
|
|
@@ -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
|
+
}
|
|
@@ -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
|
|
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,151 @@
|
|
|
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("a twin of an app path is not the guard's to decode — it is walled like any request", async () => {
|
|
146
|
+
const guard = build();
|
|
147
|
+
const res = await guard.handle(await twin("POST", "/api/thing", { a: 1 }));
|
|
148
|
+
expect(res?.status).not.toBe(200);
|
|
149
|
+
expect(res?.status).not.toBe(403);
|
|
150
|
+
});
|
|
151
|
+
});
|
|
@@ -23,6 +23,9 @@ 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 { V0ChunkStore } from "cursedbelt-core/ctgr/v0compat";
|
|
28
|
+
import { decodeCtgrTwin } from "../ctgrTwin.js";
|
|
26
29
|
import { LOCK_SCRIPT, LOCK_STYLE, type LockPageOptions, lockPageHtml } from "./lockPage.js";
|
|
27
30
|
import type { MasterLock } from "./masterLock.js";
|
|
28
31
|
|
|
@@ -75,6 +78,13 @@ export interface MasterLockGuardOptions extends LockPageOptions {
|
|
|
75
78
|
|
|
76
79
|
const noStore = { "cache-control": "no-store, no-cache, must-revalidate", pragma: "no-cache" } as const;
|
|
77
80
|
|
|
81
|
+
/**
|
|
82
|
+
* A GET-only device's twin of a lock write: `/ctgr<xx>/__lock/…` (forge task 5158). Its writes —
|
|
83
|
+
* unlock, enroll, ping, lock — would otherwise reach the wall as a GET to a path that is not the
|
|
84
|
+
* lock's, and be refused, so such a device could never get in.
|
|
85
|
+
*/
|
|
86
|
+
const LOCK_TWIN = new RegExp(`^/ctgr[a-z]{2}${MASTER_LOCK_PREFIX}(?:/|$)`, "i");
|
|
87
|
+
|
|
78
88
|
/**
|
|
79
89
|
* The lock page's own CSP. Strict enough to stand in front of `apps/vault`'s wall without
|
|
80
90
|
* loosening it: nothing loads from anywhere but this origin, the form posts nowhere (the
|
|
@@ -334,34 +344,47 @@ export function createMasterLockGuard(options: MasterLockGuardOptions): MasterLo
|
|
|
334
344
|
return new Response("not found", { status: 404, headers: noStore });
|
|
335
345
|
}
|
|
336
346
|
|
|
347
|
+
// A lock write is one small JSON body, so its twin is one chunk; the store only holds the rare split.
|
|
348
|
+
const twinStore = new ChunkStore();
|
|
349
|
+
const twinLegacy = new V0ChunkStore();
|
|
350
|
+
|
|
351
|
+
async function handle(req: Request): Promise<Response | null> {
|
|
352
|
+
const url = new URL(req.url);
|
|
353
|
+
// 🔴 The twin is DECODED here and the real request judged by the very rule below, so the
|
|
354
|
+
// wall decides an unlock's twin exactly as it decides the POST, whichever of this guard and
|
|
355
|
+
// `mountCtgrTunnel` an app mounts first — and in a bare `Bun.serve` app that has no tunnel.
|
|
356
|
+
if (LOCK_TWIN.test(url.pathname)) {
|
|
357
|
+
const decoded = await decodeCtgrTwin(req, url.pathname, twinStore, twinLegacy);
|
|
358
|
+
return decoded instanceof Response ? decoded : handle(decoded);
|
|
359
|
+
}
|
|
360
|
+
const own =
|
|
361
|
+
url.pathname === MASTER_LOCK_PREFIX || url.pathname.startsWith(`${MASTER_LOCK_PREFIX}/`);
|
|
362
|
+
const lock = resolve(req);
|
|
363
|
+
if (!lock) {
|
|
364
|
+
// No principal. On the app's own paths the caller is not signed in and the
|
|
365
|
+
// app's sign-in owns the request; on `/__lock/*` there is nobody to unlock
|
|
366
|
+
// FOR, and answering the ordinary refusal keeps that indistinguishable from
|
|
367
|
+
// being locked.
|
|
368
|
+
return own ? refuse() : null;
|
|
369
|
+
}
|
|
370
|
+
if (own) return handleOwnRoute(req, url, lock);
|
|
371
|
+
if (options.allow?.(url, req)) return null;
|
|
372
|
+
if (opens(lock, req)) return null;
|
|
373
|
+
|
|
374
|
+
// A document request is answered IN PLACE with the lock page — same URL, status
|
|
375
|
+
// 200 — so unlocking reloads to where they were going instead of dumping them at
|
|
376
|
+
// the root. Everything else gets the uniform refusal.
|
|
377
|
+
if (wantsDocument(req)) return lockPage(options, lock);
|
|
378
|
+
return refuse();
|
|
379
|
+
}
|
|
380
|
+
|
|
337
381
|
return {
|
|
382
|
+
handle,
|
|
338
383
|
accountFor(req: Request): string | null {
|
|
339
384
|
// The SAME resolution the guard itself uses, so an app can never be told a
|
|
340
385
|
// different tenant from the one the wall admitted.
|
|
341
386
|
return resolve(req)?.accountFor(req) ?? null;
|
|
342
387
|
},
|
|
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
388
|
};
|
|
366
389
|
}
|
|
367
390
|
|
|
@@ -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
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
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
|
|
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 = "";
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import { describe, expect, test } from 'bun:test';
|
|
3
|
+
import { encodeRequest } from 'cursedbelt-core/ctgr';
|
|
4
|
+
import { Hono } from 'hono';
|
|
5
|
+
import type { CursedbeltEnv } from '../context.js';
|
|
6
|
+
import { mountCtgrTunnel } from '../ctgrTunnel.js';
|
|
7
|
+
import { ApiError } from '../errors.js';
|
|
8
|
+
import type { TelemetryEvent, TelemetrySink } from '../metrics/telemetrySink.js';
|
|
9
|
+
import { correlationId } from './correlationId.js';
|
|
10
|
+
import { errorEnvelope } from './errorEnvelope.js';
|
|
11
|
+
import { requestLogger } from './requestLogger.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 🔴 A GET-only write carries its whole body in its URL (forge task 5157): a `/ctgr<xx>` twin's
|
|
15
|
+
* `_d=` and `_c*` params are the payload — vault's are its ciphertext and unlock verifier. The
|
|
16
|
+
* request log is backed up, so what it keeps must be the route and never the query. Every row this
|
|
17
|
+
* logger can write — the telemetry event and both kinds of `event_logs` row — is checked here for
|
|
18
|
+
* the twin's own query text.
|
|
19
|
+
*/
|
|
20
|
+
const ORIGIN = 'http://localhost';
|
|
21
|
+
|
|
22
|
+
function setup() {
|
|
23
|
+
const db = new Database(':memory:');
|
|
24
|
+
db.run(
|
|
25
|
+
`CREATE TABLE event_logs (id TEXT PRIMARY KEY, correlation_id TEXT, event_name TEXT NOT NULL,
|
|
26
|
+
type TEXT NOT NULL DEFAULT 'info', message TEXT, details TEXT, duration_ms REAL, user_id TEXT,
|
|
27
|
+
created_at TEXT NOT NULL)`,
|
|
28
|
+
);
|
|
29
|
+
const recorded: TelemetryEvent[] = [];
|
|
30
|
+
const sink: TelemetrySink = {
|
|
31
|
+
record: (event) => {
|
|
32
|
+
recorded.push(event);
|
|
33
|
+
},
|
|
34
|
+
flush: () => {},
|
|
35
|
+
stop: () => {},
|
|
36
|
+
size: 0,
|
|
37
|
+
};
|
|
38
|
+
const app = new Hono<CursedbeltEnv>().use('*', correlationId());
|
|
39
|
+
// slowMs 0: every request also writes an `event_logs` row, so the slow path is checked too.
|
|
40
|
+
app.use('*', requestLogger(db, { sink, slowMs: 0 }));
|
|
41
|
+
mountCtgrTunnel(app);
|
|
42
|
+
app.post('/api/vault/items', async (c) => c.json({ ok: true, got: await c.req.json() }));
|
|
43
|
+
app.post('/api/vault/refuse', () => {
|
|
44
|
+
throw new ApiError(400, 'refused');
|
|
45
|
+
});
|
|
46
|
+
app.onError(errorEnvelope);
|
|
47
|
+
const stored = () =>
|
|
48
|
+
[
|
|
49
|
+
...recorded.map((e) => JSON.stringify(e)),
|
|
50
|
+
...(db.query('SELECT * FROM event_logs').all() as Record<string, unknown>[]).map((r) => JSON.stringify(r)),
|
|
51
|
+
].join('\n');
|
|
52
|
+
return { app, recorded, stored };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A real twin, as `installCtgrFetch` would send it, and the query text that must never be kept. */
|
|
56
|
+
async function twin(path: string, body: unknown): Promise<{ url: string; secrets: string[] }> {
|
|
57
|
+
const { chunks } = await encodeRequest('POST', path, body);
|
|
58
|
+
const url = chunks[0].url;
|
|
59
|
+
const params = new URL(ORIGIN + url).searchParams;
|
|
60
|
+
const d = params.get('_d');
|
|
61
|
+
expect(d && d.length > 16).toBe(true);
|
|
62
|
+
return { url, secrets: [d as string, '_d=', '?_', url.slice(url.indexOf('?'))] };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
describe('requestLogger: a ctgr twin\'s body never reaches a stored row (forge task 5157)', () => {
|
|
66
|
+
test('a delivered twin is recorded by its route, without its query', async () => {
|
|
67
|
+
const { app, recorded, stored } = setup();
|
|
68
|
+
const { url, secrets } = await twin('/api/vault/items', { ciphertext: 'c'.repeat(64), verifier: 'v'.repeat(64) });
|
|
69
|
+
const res = await app.fetch(new Request(ORIGIN + url, { headers: { 'sec-fetch-site': 'same-origin' } }));
|
|
70
|
+
expect(res.status).toBe(200);
|
|
71
|
+
expect(recorded.some((e) => e.method === 'POST' && e.route === '/api/vault/items')).toBe(true);
|
|
72
|
+
const kept = stored();
|
|
73
|
+
for (const s of secrets) expect(kept).not.toContain(s);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('a refused twin\'s error row carries no query either', async () => {
|
|
77
|
+
const { app, recorded, stored } = setup();
|
|
78
|
+
const { url, secrets } = await twin('/api/vault/refuse', { verifier: 'v'.repeat(64) });
|
|
79
|
+
const res = await app.fetch(new Request(ORIGIN + url));
|
|
80
|
+
expect(res.status).toBe(400);
|
|
81
|
+
expect(recorded.some((e) => e.status === 400)).toBe(true);
|
|
82
|
+
const kept = stored();
|
|
83
|
+
expect(kept).toContain('http_error');
|
|
84
|
+
for (const s of secrets) expect(kept).not.toContain(s);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('a twin no route matches (a 404) is recorded unplaced, without its query', async () => {
|
|
88
|
+
const { app, stored } = setup();
|
|
89
|
+
const { url, secrets } = await twin('/api/vault/no-such-route', { verifier: 'v'.repeat(64) });
|
|
90
|
+
const res = await app.fetch(new Request(ORIGIN + url));
|
|
91
|
+
expect(res.status).toBe(404);
|
|
92
|
+
const kept = stored();
|
|
93
|
+
for (const s of secrets) expect(kept).not.toContain(s);
|
|
94
|
+
});
|
|
95
|
+
});
|