cursedbelt-server 4.70.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/dist/server/youtube/youtubeApi.d.ts +5 -0
- package/dist/server/youtube/youtubeApi.js +10 -0
- 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
- package/src/server/youtube/youtubeApi.spec.ts +27 -3
- package/src/server/youtube/youtubeApi.ts +15 -0
|
@@ -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
|
+
});
|
|
@@ -21,9 +21,9 @@ const fakeGoogle = (handler: Handler) => {
|
|
|
21
21
|
return { seen, api: createYouTubeApi(fetchImpl) };
|
|
22
22
|
};
|
|
23
23
|
|
|
24
|
-
const item = (videoId: string, title = `Video ${videoId}
|
|
25
|
-
snippet: { title, videoOwnerChannelTitle: "Chan", thumbnails: {} },
|
|
26
|
-
contentDetails: { videoId },
|
|
24
|
+
const item = (videoId: string, title = `Video ${videoId}`, videoPublishedAt?: string) => ({
|
|
25
|
+
snippet: { title, videoOwnerChannelTitle: "Chan", thumbnails: {}, publishedAt: "2030-01-01T00:00:00Z" },
|
|
26
|
+
contentDetails: { videoId, ...(videoPublishedAt ? { videoPublishedAt } : {}) },
|
|
27
27
|
});
|
|
28
28
|
|
|
29
29
|
describe("createYouTubeApi", () => {
|
|
@@ -43,6 +43,7 @@ describe("createYouTubeApi", () => {
|
|
|
43
43
|
channelTitle: "Chan",
|
|
44
44
|
thumbnail: youtubeThumbnailUrl("a1"),
|
|
45
45
|
url: "https://www.youtube.com/watch?v=a1",
|
|
46
|
+
publishedAt: null,
|
|
46
47
|
},
|
|
47
48
|
],
|
|
48
49
|
},
|
|
@@ -51,6 +52,29 @@ describe("createYouTubeApi", () => {
|
|
|
51
52
|
expect(seen[0]?.searchParams.get("playlistId")).toBe("PL1");
|
|
52
53
|
});
|
|
53
54
|
|
|
55
|
+
test("a video's date is when IT went up (contentDetails), never when it joined the playlist (snippet)", async () => {
|
|
56
|
+
const { api } = fakeGoogle(() => ({
|
|
57
|
+
body: { items: [item("d1", "Dated", "2019-06-01T12:00:00Z"), item("d2", "Undated"), item("d3", "Garbled", "soon")] },
|
|
58
|
+
}));
|
|
59
|
+
const page = await api.playlistItems("tok", "PL1");
|
|
60
|
+
expect(page.status === "ok" ? page.value.items.map((v) => v.publishedAt) : []).toEqual([
|
|
61
|
+
Date.UTC(2019, 5, 1, 12),
|
|
62
|
+
null,
|
|
63
|
+
null,
|
|
64
|
+
]);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("a liked video's date is its own snippet's — on a videos row the snippet is the video", async () => {
|
|
68
|
+
const { api, seen } = fakeGoogle(() => ({
|
|
69
|
+
body: { items: [{ id: "L1", snippet: { title: "Liked", channelTitle: "C", publishedAt: "2021-02-03T00:00:00Z" } }] },
|
|
70
|
+
}));
|
|
71
|
+
const page = await api.liked("tok");
|
|
72
|
+
expect(page.status === "ok" ? page.value.items.map((v) => [v.videoId, v.publishedAt]) : []).toEqual([
|
|
73
|
+
["L1", Date.UTC(2021, 1, 3)],
|
|
74
|
+
]);
|
|
75
|
+
expect(seen[0]?.searchParams.get("myRating")).toBe("like");
|
|
76
|
+
});
|
|
77
|
+
|
|
54
78
|
test("🔴 every page is walked, and a list stopped at the cap SAYS so", async () => {
|
|
55
79
|
const { api } = fakeGoogle((url) => {
|
|
56
80
|
const at = Number(url.searchParams.get("pageToken") ?? "0");
|