cursedbelt-server 4.73.0 β 4.74.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/clientIssues/d1.d.ts +18 -4
- package/dist/server/clientIssues/d1.js +11 -2
- package/dist/server/ctgrChunkD1.d.ts +12 -0
- package/dist/server/ctgrChunkD1.js +37 -8
- package/dist/server/ctgrTunnel.d.ts +9 -1
- package/dist/server/ctgrTwin.d.ts +6 -0
- package/dist/server/ctgrTwin.js +19 -1
- package/dist/server/master-lock/guard.js +5 -7
- package/dist/server/metrics/normalizeRoute.js +11 -10
- package/package.json +3 -3
- package/src/server/clientIssues/d1.spec.ts +23 -0
- package/src/server/clientIssues/d1.ts +25 -7
- package/src/server/ctgrChunkD1.spec.ts +61 -0
- package/src/server/ctgrChunkD1.ts +42 -8
- package/src/server/ctgrTunnel.ts +9 -1
- package/src/server/ctgrTwin.ts +19 -1
- package/src/server/events/actions.spec.ts +6 -6
- package/src/server/master-lock/ctgrLockTwin.spec.ts +13 -0
- package/src/server/master-lock/guard.ts +5 -8
- package/src/server/metrics/normalizeRoute.spec.ts +22 -6
- package/src/server/metrics/normalizeRoute.ts +11 -11
|
@@ -16,9 +16,13 @@
|
|
|
16
16
|
* π΄ The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
|
|
17
17
|
* ({@link REDACTED_QUERY_KEY}, cursedbelt-core's, the copy `cursedbelt`'s reporter imports too) runs again
|
|
18
18
|
* here, and the account is the session's, never the body's. It may be mounted outside the session
|
|
19
|
-
* gate (a page that cannot sign in is exactly the page with a problem), so
|
|
20
|
-
* calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app,
|
|
21
|
-
*
|
|
19
|
+
* gate (a page that cannot sign in is exactly the page with a problem), so three bounds hold whoever
|
|
20
|
+
* calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, of which rows with
|
|
21
|
+
* no session's account (a stranger's as much as the sign-in page's) may be at most
|
|
22
|
+
* {@link ClientIssuesOptions.maxAnonymousRowsPerHour} β so a flood of anonymous posts cannot starve
|
|
23
|
+
* the signed-in reports out of the hour (forge task 5304) β and rows older than
|
|
24
|
+
* {@link ClientIssuesOptions.retentionMs} are purged on every write. An anonymous row's every field is
|
|
25
|
+
* a stranger's words: autopilot's reader fences them as such.
|
|
22
26
|
*
|
|
23
27
|
* π΄ Worker-safe: nothing reachable from here at runtime imports `bun:*`.
|
|
24
28
|
*/
|
|
@@ -80,12 +84,22 @@ export interface ClientIssuesOptions {
|
|
|
80
84
|
retentionMs?: number;
|
|
81
85
|
/** Reports past this many in the last hour are refused (429). Default 600. */
|
|
82
86
|
maxRowsPerHour?: number;
|
|
87
|
+
/**
|
|
88
|
+
* The share of {@link maxRowsPerHour} that rows with no session account may take; an anonymous
|
|
89
|
+
* report past it is refused (429) while signed-in reports still land. Default 100 (forge task 5304).
|
|
90
|
+
*/
|
|
91
|
+
maxAnonymousRowsPerHour?: number;
|
|
83
92
|
now?: () => number;
|
|
84
93
|
}
|
|
85
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Write one row, purge the expired ones, refuse past the hourly bound β and an anonymous row (no
|
|
96
|
+
* `user_key`) past the anonymous share of it, so strangers can fill only their own share. `"capped"`
|
|
97
|
+
* when refused.
|
|
98
|
+
*/
|
|
86
99
|
export declare function recordClientIssueD1(db: D1LikeDatabase, row: ClientIssueRow, bounds: {
|
|
87
100
|
retentionMs: number;
|
|
88
101
|
maxRowsPerHour: number;
|
|
102
|
+
maxAnonymousRowsPerHour?: number;
|
|
89
103
|
}): Promise<"recorded" | "capped">;
|
|
90
104
|
/**
|
|
91
105
|
* The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
|
|
@@ -89,14 +89,22 @@ const COLUMNS = [
|
|
|
89
89
|
"facts",
|
|
90
90
|
"report",
|
|
91
91
|
];
|
|
92
|
-
/**
|
|
92
|
+
/** The anonymous share of the hourly bound, when an app names none (forge task 5304). */
|
|
93
|
+
const DEFAULT_ANONYMOUS_ROWS_PER_HOUR = 100;
|
|
94
|
+
/**
|
|
95
|
+
* Write one row, purge the expired ones, refuse past the hourly bound β and an anonymous row (no
|
|
96
|
+
* `user_key`) past the anonymous share of it, so strangers can fill only their own share. `"capped"`
|
|
97
|
+
* when refused.
|
|
98
|
+
*/
|
|
93
99
|
export async function recordClientIssueD1(db, row, bounds) {
|
|
94
100
|
const recent = await db
|
|
95
|
-
.prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
|
|
101
|
+
.prepare("SELECT COUNT(*) AS n, COALESCE(SUM(CASE WHEN user_key = '' THEN 1 ELSE 0 END), 0) AS anonymous FROM client_issues WHERE at > ?")
|
|
96
102
|
.bind(row.at - 3_600_000)
|
|
97
103
|
.first();
|
|
98
104
|
if ((recent?.n ?? 0) >= bounds.maxRowsPerHour)
|
|
99
105
|
return "capped";
|
|
106
|
+
if (!row.user_key && (recent?.anonymous ?? 0) >= (bounds.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR))
|
|
107
|
+
return "capped";
|
|
100
108
|
await db.batch([
|
|
101
109
|
db
|
|
102
110
|
.prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
|
|
@@ -115,6 +123,7 @@ export function clientIssuesHandler(options) {
|
|
|
115
123
|
const bounds = {
|
|
116
124
|
retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
|
|
117
125
|
maxRowsPerHour: options.maxRowsPerHour ?? 600,
|
|
126
|
+
maxAnonymousRowsPerHour: options.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR,
|
|
118
127
|
};
|
|
119
128
|
return async (c) => {
|
|
120
129
|
let body;
|
|
@@ -27,6 +27,13 @@
|
|
|
27
27
|
* here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
|
|
28
28
|
* (β 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
|
|
29
29
|
* A payload over `maxPayloadBytes` is refused as a bad one (β 400), and its rows dropped.
|
|
30
|
+
*
|
|
31
|
+
* π΄ ONE caller may hold at most `maxRowsPerCaller` of those rows (forge task 5306). With only the
|
|
32
|
+
* table-wide cap, one stranger sending "chunk 1 of 2" under fresh cids kept the table full and every
|
|
33
|
+
* real GET-only device's bulk write 503'd. Each row's `cid` is stored as `<caller hash>~<cid>`, the
|
|
34
|
+
* caller being the tunnel's `context.caller` (the edge's client address, IPv6 by /64), so a caller's
|
|
35
|
+
* rows are one PRIMARY KEY range to count β no schema change on the eight apps' D1s β and one caller's
|
|
36
|
+
* chunks can never join another's set. A caller over its share is refused like a full table (503).
|
|
30
37
|
*/
|
|
31
38
|
import { type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
|
|
32
39
|
import type { D1LikeDatabase } from './d1/types.js';
|
|
@@ -40,6 +47,11 @@ export declare const CTGR_CHUNKS_DDL: readonly string[];
|
|
|
40
47
|
export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
|
|
41
48
|
/** Rows the whole table may hold before a new chunk is refused (β 503). Default 4,000 (~10 MB). */
|
|
42
49
|
maxRows?: number;
|
|
50
|
+
/**
|
|
51
|
+
* Rows ONE caller (the tunnel's `context.caller`) may hold before its next chunk is refused (β 503).
|
|
52
|
+
* Default 400 β a tenth of the table, and ~700 KB of payload: far past any real bulk write.
|
|
53
|
+
*/
|
|
54
|
+
maxRowsPerCaller?: number;
|
|
43
55
|
}
|
|
44
56
|
/**
|
|
45
57
|
* A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
|
|
@@ -27,6 +27,13 @@
|
|
|
27
27
|
* here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
|
|
28
28
|
* (β 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
|
|
29
29
|
* A payload over `maxPayloadBytes` is refused as a bad one (β 400), and its rows dropped.
|
|
30
|
+
*
|
|
31
|
+
* π΄ ONE caller may hold at most `maxRowsPerCaller` of those rows (forge task 5306). With only the
|
|
32
|
+
* table-wide cap, one stranger sending "chunk 1 of 2" under fresh cids kept the table full and every
|
|
33
|
+
* real GET-only device's bulk write 503'd. Each row's `cid` is stored as `<caller hash>~<cid>`, the
|
|
34
|
+
* caller being the tunnel's `context.caller` (the edge's client address, IPv6 by /64), so a caller's
|
|
35
|
+
* rows are one PRIMARY KEY range to count β no schema change on the eight apps' D1s β and one caller's
|
|
36
|
+
* chunks can never join another's set. A caller over its share is refused like a full table (503).
|
|
30
37
|
*/
|
|
31
38
|
import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
|
|
32
39
|
import { parseChunk } from 'cursedbelt-core/ctgr';
|
|
@@ -43,6 +50,20 @@ export const CTGR_CHUNKS_DDL = [
|
|
|
43
50
|
const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
|
|
44
51
|
const DEFAULT_TTL_MS = 30_000;
|
|
45
52
|
const DEFAULT_MAX_ROWS = 4_000;
|
|
53
|
+
const DEFAULT_MAX_ROWS_PER_CALLER = 400;
|
|
54
|
+
const CID = /^[A-Za-z0-9-]{1,64}$/;
|
|
55
|
+
/**
|
|
56
|
+
* The caller's namespace in `cid`: an FNV-1a hash of its address, so the table holds no address. A
|
|
57
|
+
* collision only makes two callers share one share.
|
|
58
|
+
*/
|
|
59
|
+
function callerKey(caller) {
|
|
60
|
+
let h = 0x811c9dc5;
|
|
61
|
+
for (let i = 0; i < caller.length; i++) {
|
|
62
|
+
h ^= caller.charCodeAt(i);
|
|
63
|
+
h = Math.imul(h, 0x01000193);
|
|
64
|
+
}
|
|
65
|
+
return (h >>> 0).toString(36).padStart(7, '0');
|
|
66
|
+
}
|
|
46
67
|
/**
|
|
47
68
|
* A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
|
|
48
69
|
* Cheap to build β build it per request over the request's D1 handle.
|
|
@@ -51,11 +72,12 @@ export function createD1ChunkStore(db, options = {}) {
|
|
|
51
72
|
const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
|
|
52
73
|
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
53
74
|
const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
|
|
75
|
+
const maxRowsPerCaller = options.maxRowsPerCaller ?? DEFAULT_MAX_ROWS_PER_CALLER;
|
|
54
76
|
const now = options.now ?? Date.now;
|
|
55
77
|
// The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
|
|
56
78
|
const decodeOpts = { maxPayloadBytes };
|
|
57
79
|
return {
|
|
58
|
-
async add(input) {
|
|
80
|
+
async add(input, context) {
|
|
59
81
|
const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
|
|
60
82
|
let chunk;
|
|
61
83
|
try {
|
|
@@ -69,22 +91,29 @@ export function createD1ChunkStore(db, options = {}) {
|
|
|
69
91
|
return new ChunkStore(decodeOpts).add(params);
|
|
70
92
|
if (chunk.payloadLength > maxPayloadBytes)
|
|
71
93
|
return new Error('ctgr: payload exceeds size cap');
|
|
94
|
+
// The codec's cid is a UUID. Anything past ASCII would sort outside the caller's counted range.
|
|
95
|
+
if (!CID.test(chunk.cid))
|
|
96
|
+
return new Error('ctgr: a chunk id is a short token of letters, digits and dashes');
|
|
72
97
|
const at = now();
|
|
98
|
+
const owner = callerKey(context?.caller ?? '');
|
|
99
|
+
// A cid is [A-Za-z0-9-], all below `\x7f`, so `<owner>~<cid>` sorts inside [from, to): the caller's rows.
|
|
100
|
+
const cid = `${owner}~${chunk.cid}`;
|
|
101
|
+
const [from, to] = [`${owner}~`, `${owner}\x7f`];
|
|
73
102
|
const [, , counted] = await db.batch([
|
|
74
103
|
db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
|
|
75
104
|
db
|
|
76
|
-
.prepare(`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`)
|
|
77
|
-
.bind(
|
|
105
|
+
.prepare(`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ? AND (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE} WHERE cid >= ? AND cid < ?) < ?`)
|
|
106
|
+
.bind(cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows, from, to, maxRowsPerCaller),
|
|
78
107
|
db
|
|
79
108
|
.prepare(`SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`)
|
|
80
|
-
.bind(chunk.index,
|
|
109
|
+
.bind(chunk.index, cid),
|
|
81
110
|
]);
|
|
82
111
|
const row = counted?.results[0];
|
|
83
|
-
// Neither inserted now nor held from before: the table is at `maxRows
|
|
112
|
+
// Neither inserted now nor held from before: the table is at `maxRows`, or this caller at its share.
|
|
84
113
|
if (!row?.mine)
|
|
85
|
-
throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
|
|
114
|
+
throw new Error(`ctgr: the chunk table is full (${maxRows} rows, ${maxRowsPerCaller} a caller)`);
|
|
86
115
|
if (row.b > maxPayloadBytes) {
|
|
87
|
-
await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(
|
|
116
|
+
await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(cid).run();
|
|
88
117
|
return new Error('ctgr: payload exceeds size cap');
|
|
89
118
|
}
|
|
90
119
|
if (row.n < chunk.total)
|
|
@@ -92,7 +121,7 @@ export function createD1ChunkStore(db, options = {}) {
|
|
|
92
121
|
// Complete: claim the set. Only one request's DELETE can return its rows.
|
|
93
122
|
const claimed = await db
|
|
94
123
|
.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
|
|
95
|
-
.bind(
|
|
124
|
+
.bind(cid)
|
|
96
125
|
.all();
|
|
97
126
|
if (claimed.results.length < chunk.total)
|
|
98
127
|
return false;
|
|
@@ -8,7 +8,15 @@ import type { Env, Hono } from 'hono';
|
|
|
8
8
|
* a THROW means the store itself could not answer (β 503).
|
|
9
9
|
*/
|
|
10
10
|
export interface CtgrChunkSink {
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* `context.caller` is who sent the chunk (`callerOfTwin` β the edge's client address, an IPv6 one by
|
|
13
|
+
* its /64), so a store shared by every caller can give each its own share (forge task 5306).
|
|
14
|
+
*/
|
|
15
|
+
add(params: Record<string, string> | URLSearchParams,
|
|
16
|
+
/** `caller`: the edge's client address (`cf-connecting-ip`), an IPv6 one cut to its /64; `''` when none was sent. */
|
|
17
|
+
context?: {
|
|
18
|
+
caller?: string;
|
|
19
|
+
}): Promise<CtgrDecoded | false | Error>;
|
|
12
20
|
}
|
|
13
21
|
export interface CtgrTunnelOptions {
|
|
14
22
|
/**
|
|
@@ -6,3 +6,9 @@ import type { CtgrChunkSink } from './ctgrTunnel.js';
|
|
|
6
6
|
* unknown verb 404, an intermediate chunk 202, a bad payload 400, a store that could not answer 503).
|
|
7
7
|
*/
|
|
8
8
|
export declare function decodeCtgrTwin(raw: Request, twinPath: string, store: CtgrChunkSink, legacy: V0ChunkStore): Promise<Request | Response>;
|
|
9
|
+
/**
|
|
10
|
+
* Who sent this twin, as one network: Cloudflare's `cf-connecting-ip` (the edge sets it and a client
|
|
11
|
+
* cannot), an IPv6 address cut to its /64 β one subscriber holds a whole /64, so a per-address share
|
|
12
|
+
* would be no share at all. `''` when the header is absent (a test, a host with no edge in front).
|
|
13
|
+
*/
|
|
14
|
+
export declare function callerOfTwin(request: Request): string;
|
package/dist/server/ctgrTwin.js
CHANGED
|
@@ -22,7 +22,7 @@ export async function decodeCtgrTwin(raw, twinPath, store, legacy) {
|
|
|
22
22
|
return json({ error: 'not found', code: 'NOT_FOUND' }, 404);
|
|
23
23
|
let result;
|
|
24
24
|
try {
|
|
25
|
-
result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
|
|
25
|
+
result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params, { caller: callerOfTwin(raw) });
|
|
26
26
|
}
|
|
27
27
|
catch (error) {
|
|
28
28
|
console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -34,6 +34,24 @@ export async function decodeCtgrTwin(raw, twinPath, store, legacy) {
|
|
|
34
34
|
return json({ error: result.message, code: 'BAD_REQUEST' }, 400);
|
|
35
35
|
return rebuildRequest(raw, twinPath, url, result);
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Who sent this twin, as one network: Cloudflare's `cf-connecting-ip` (the edge sets it and a client
|
|
39
|
+
* cannot), an IPv6 address cut to its /64 β one subscriber holds a whole /64, so a per-address share
|
|
40
|
+
* would be no share at all. `''` when the header is absent (a test, a host with no edge in front).
|
|
41
|
+
*/
|
|
42
|
+
export function callerOfTwin(request) {
|
|
43
|
+
const ip = (request.headers.get('cf-connecting-ip') ?? '').trim().toLowerCase();
|
|
44
|
+
if (!ip.includes(':'))
|
|
45
|
+
return ip;
|
|
46
|
+
const [head = '', tail = ''] = ip.split('::');
|
|
47
|
+
const left = head ? head.split(':') : [];
|
|
48
|
+
const right = tail ? tail.split(':') : [];
|
|
49
|
+
const groups = ip.includes('::') ? [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right] : left;
|
|
50
|
+
return `${groups
|
|
51
|
+
.slice(0, 4)
|
|
52
|
+
.map((g) => g.replace(/^0+(?=.)/, ''))
|
|
53
|
+
.join(':')}::/64`;
|
|
54
|
+
}
|
|
37
55
|
/**
|
|
38
56
|
* Did a browser say this twin came from somewhere else? `Sec-Fetch-Site` is set by the browser
|
|
39
57
|
* and no page can forge it: only `same-origin` is the app's own `installCtgrFetch`. `none` (a
|
|
@@ -14,16 +14,11 @@
|
|
|
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
16
|
import { ChunkStore } from "cursedbelt-core/ctgr/chunk-store";
|
|
17
|
+
import { isCtgrTwinOf } from "cursedbelt-core/ctgr/types";
|
|
17
18
|
import { V0ChunkStore } from "cursedbelt-core/ctgr/v0compat";
|
|
18
19
|
import { decodeCtgrTwin } from "../ctgrTwin.js";
|
|
19
20
|
import { LOCK_SCRIPT, LOCK_STYLE, lockPageHtml } from "./lockPage.js";
|
|
20
21
|
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");
|
|
27
22
|
/**
|
|
28
23
|
* The lock page's own CSP. Strict enough to stand in front of `apps/vault`'s wall without
|
|
29
24
|
* loosening it: nothing loads from anywhere but this origin, the form posts nowhere (the
|
|
@@ -249,7 +244,10 @@ export function createMasterLockGuard(options) {
|
|
|
249
244
|
// π΄ The twin is DECODED here and the real request judged by the very rule below, so the
|
|
250
245
|
// wall decides an unlock's twin exactly as it decides the POST, whichever of this guard and
|
|
251
246
|
// `mountCtgrTunnel` an app mounts first β and in a bare `Bun.serve` app that has no tunnel.
|
|
252
|
-
|
|
247
|
+
// A GET-only device's twin of a lock write: `/ctgr<xx>/__lock/β¦` (forge task 5158). Its writes β
|
|
248
|
+
// unlock, enroll, ping, lock β would otherwise reach the wall as a GET to a path that is not the
|
|
249
|
+
// lock's, and be refused, so such a device could never get in. Core says what a twin is (task 5162).
|
|
250
|
+
if (isCtgrTwinOf(url.pathname, MASTER_LOCK_PREFIX)) {
|
|
253
251
|
const decoded = await decodeCtgrTwin(req, url.pathname, twinStore, twinLegacy);
|
|
254
252
|
return decoded instanceof Response ? decoded : handle(decoded);
|
|
255
253
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ABBREV_TO_METHOD, ctgrTwinTarget } from 'cursedbelt-core/ctgr/types';
|
|
1
2
|
/**
|
|
2
3
|
* Turn a request into a stable, low-cardinality route label for metric aggregation
|
|
3
4
|
* (e.g. `/api/v1/notes/:id`). The method is tracked separately.
|
|
@@ -11,9 +12,6 @@
|
|
|
11
12
|
*/
|
|
12
13
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13
14
|
const LONG_HEX_RE = /^[0-9a-f]{16,}$/i;
|
|
14
|
-
// The ctgr twin URL is `/ctgr<last-2-of-method><url>`, so the two-letter suffix
|
|
15
|
-
// recovers the original verb (POSTβst, PUTβut, PATCHβch, DELETEβte).
|
|
16
|
-
const CTGR_METHOD = { st: 'POST', ut: 'PUT', ch: 'PATCH', te: 'DELETE' };
|
|
17
15
|
function collapseSegment(seg) {
|
|
18
16
|
if (!seg)
|
|
19
17
|
return seg;
|
|
@@ -50,13 +48,16 @@ export function normalizeRoute(c) {
|
|
|
50
48
|
const path = c.req.path.split('?')[0];
|
|
51
49
|
let route = pattern ?? (collapsePath(path) || '/');
|
|
52
50
|
let unmatchedPath = pattern ? undefined : path;
|
|
53
|
-
// Map a ctgr GET-twin back to its real verb + url:
|
|
54
|
-
//
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
51
|
+
// Map a ctgr GET-twin back to its real verb + url: `/ctgrpa/api/notes/n1` β PATCH /api/notes/:id.
|
|
52
|
+
// Which paths are twins, and which verb each stands for, is core's one answer (forge task 5162) β
|
|
53
|
+
// this file's own table once held abbreviations no client sends, so every twin counted as a GET.
|
|
54
|
+
const twin = ctgrTwinTarget(path);
|
|
55
|
+
if (twin !== null) {
|
|
56
|
+
method = ABBREV_TO_METHOD[path.slice(5, 7)];
|
|
57
|
+
// A route registered at the twin itself is still a real pattern; the tunnel's catch-all is not.
|
|
58
|
+
const realPattern = pattern === undefined ? null : ctgrTwinTarget(pattern);
|
|
59
|
+
route = realPattern ?? (collapsePath(twin) || '/');
|
|
60
|
+
unmatchedPath = realPattern === null ? twin : undefined;
|
|
60
61
|
}
|
|
61
62
|
return { method, route, ...(unmatchedPath === undefined ? {} : { unmatchedPath }) };
|
|
62
63
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.74.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.",
|
|
@@ -400,7 +400,7 @@
|
|
|
400
400
|
},
|
|
401
401
|
"dependencies": {
|
|
402
402
|
"argon2id": "1.0.1",
|
|
403
|
-
"cursedbelt-core": "^2.
|
|
403
|
+
"cursedbelt-core": "^2.20.0",
|
|
404
404
|
"cursedops": ">=0.8.1 <1.0.0",
|
|
405
405
|
"cwip": "^4.6.0",
|
|
406
406
|
"jose": "^6.2.3"
|
|
@@ -441,7 +441,7 @@
|
|
|
441
441
|
"@node-rs/argon2": "^2.0.2",
|
|
442
442
|
"@types/bun": "^1.3.14",
|
|
443
443
|
"@types/node": "^24",
|
|
444
|
-
"cursedbelt": "^6.
|
|
444
|
+
"cursedbelt": "^6.9.0",
|
|
445
445
|
"hono": "4.12.28",
|
|
446
446
|
"kysely": "^0.28.17",
|
|
447
447
|
"kysely-bun-sqlite": "^0.4.0",
|
|
@@ -113,6 +113,29 @@ describe('π΄ the door is bounded whoever calls it', () => {
|
|
|
113
113
|
expect(sqlite.query('SELECT COUNT(*) AS n FROM client_issues').get()).toEqual({ n: 2 });
|
|
114
114
|
});
|
|
115
115
|
|
|
116
|
+
test('π΄ strangers fill only their own share: past maxAnonymousRowsPerHour a signed-in report still lands (forge task 5304)', async () => {
|
|
117
|
+
const { sqlite, db } = fresh();
|
|
118
|
+
let signedIn = false;
|
|
119
|
+
const app = createD1ClientIssuesRecorder({ db, maxRowsPerHour: 5, maxAnonymousRowsPerHour: 2, resolveUser: () => (signedIn ? 'acct-1' : null), now: () => 5_000_000 });
|
|
120
|
+
expect((await post(app, report({ id: 'flood-1' }))).status).toBe(204);
|
|
121
|
+
expect((await post(app, report({ id: 'flood-2' }))).status).toBe(204);
|
|
122
|
+
expect((await post(app, report({ id: 'flood-3' }))).status).toBe(429);
|
|
123
|
+
signedIn = true;
|
|
124
|
+
expect((await post(app, report({ id: 'real-1' }))).status).toBe(204);
|
|
125
|
+
expect((await post(app, report({ id: 'real-2' }))).status).toBe(204);
|
|
126
|
+
expect((await post(app, report({ id: 'real-3' }))).status).toBe(204);
|
|
127
|
+
expect((await post(app, report({ id: 'real-4' }))).status).toBe(429);
|
|
128
|
+
expect(sqlite.query("SELECT COUNT(*) AS n FROM client_issues WHERE user_key = ''").get()).toEqual({ n: 2 });
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('the anonymous share defaults to 100 of the hour', async () => {
|
|
132
|
+
const { sqlite, db } = fresh();
|
|
133
|
+
const app = createD1ClientIssuesRecorder({ db, now: () => 5_000_000 });
|
|
134
|
+
const insert = sqlite.prepare("INSERT INTO client_issues (at, change, issue_id, area, stem, tone, outlook, title, started_at) VALUES (4999000, 'raised', 'x', 'a', 's', 'warning', '', 't', 0)");
|
|
135
|
+
for (let i = 0; i < 100; i++) insert.run();
|
|
136
|
+
expect((await post(app, report())).status).toBe(429);
|
|
137
|
+
});
|
|
138
|
+
|
|
116
139
|
test('a write purges the rows older than the retention', async () => {
|
|
117
140
|
const { sqlite, db } = fresh();
|
|
118
141
|
let clock = 1_000;
|
|
@@ -16,9 +16,13 @@
|
|
|
16
16
|
* π΄ The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
|
|
17
17
|
* ({@link REDACTED_QUERY_KEY}, cursedbelt-core's, the copy `cursedbelt`'s reporter imports too) runs again
|
|
18
18
|
* here, and the account is the session's, never the body's. It may be mounted outside the session
|
|
19
|
-
* gate (a page that cannot sign in is exactly the page with a problem), so
|
|
20
|
-
* calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app,
|
|
21
|
-
*
|
|
19
|
+
* gate (a page that cannot sign in is exactly the page with a problem), so three bounds hold whoever
|
|
20
|
+
* calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, of which rows with
|
|
21
|
+
* no session's account (a stranger's as much as the sign-in page's) may be at most
|
|
22
|
+
* {@link ClientIssuesOptions.maxAnonymousRowsPerHour} β so a flood of anonymous posts cannot starve
|
|
23
|
+
* the signed-in reports out of the hour (forge task 5304) β and rows older than
|
|
24
|
+
* {@link ClientIssuesOptions.retentionMs} are purged on every write. An anonymous row's every field is
|
|
25
|
+
* a stranger's words: autopilot's reader fences them as such.
|
|
22
26
|
*
|
|
23
27
|
* π΄ Worker-safe: nothing reachable from here at runtime imports `bun:*`.
|
|
24
28
|
*/
|
|
@@ -144,6 +148,9 @@ const COLUMNS = [
|
|
|
144
148
|
"report",
|
|
145
149
|
] as const satisfies readonly (keyof ClientIssueRow)[];
|
|
146
150
|
|
|
151
|
+
/** The anonymous share of the hourly bound, when an app names none (forge task 5304). */
|
|
152
|
+
const DEFAULT_ANONYMOUS_ROWS_PER_HOUR = 100;
|
|
153
|
+
|
|
147
154
|
export interface ClientIssuesOptions {
|
|
148
155
|
/** The app's D1, or how to find it on the request. */
|
|
149
156
|
db: D1LikeDatabase | ((c: Context) => D1LikeDatabase);
|
|
@@ -158,20 +165,30 @@ export interface ClientIssuesOptions {
|
|
|
158
165
|
retentionMs?: number;
|
|
159
166
|
/** Reports past this many in the last hour are refused (429). Default 600. */
|
|
160
167
|
maxRowsPerHour?: number;
|
|
168
|
+
/**
|
|
169
|
+
* The share of {@link maxRowsPerHour} that rows with no session account may take; an anonymous
|
|
170
|
+
* report past it is refused (429) while signed-in reports still land. Default 100 (forge task 5304).
|
|
171
|
+
*/
|
|
172
|
+
maxAnonymousRowsPerHour?: number;
|
|
161
173
|
now?: () => number;
|
|
162
174
|
}
|
|
163
175
|
|
|
164
|
-
/**
|
|
176
|
+
/**
|
|
177
|
+
* Write one row, purge the expired ones, refuse past the hourly bound β and an anonymous row (no
|
|
178
|
+
* `user_key`) past the anonymous share of it, so strangers can fill only their own share. `"capped"`
|
|
179
|
+
* when refused.
|
|
180
|
+
*/
|
|
165
181
|
export async function recordClientIssueD1(
|
|
166
182
|
db: D1LikeDatabase,
|
|
167
183
|
row: ClientIssueRow,
|
|
168
|
-
bounds: { retentionMs: number; maxRowsPerHour: number },
|
|
184
|
+
bounds: { retentionMs: number; maxRowsPerHour: number; maxAnonymousRowsPerHour?: number },
|
|
169
185
|
): Promise<"recorded" | "capped"> {
|
|
170
186
|
const recent = await db
|
|
171
|
-
.prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
|
|
187
|
+
.prepare("SELECT COUNT(*) AS n, COALESCE(SUM(CASE WHEN user_key = '' THEN 1 ELSE 0 END), 0) AS anonymous FROM client_issues WHERE at > ?")
|
|
172
188
|
.bind(row.at - 3_600_000)
|
|
173
|
-
.first<{ n: number }>();
|
|
189
|
+
.first<{ n: number; anonymous: number }>();
|
|
174
190
|
if ((recent?.n ?? 0) >= bounds.maxRowsPerHour) return "capped";
|
|
191
|
+
if (!row.user_key && (recent?.anonymous ?? 0) >= (bounds.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR)) return "capped";
|
|
175
192
|
await db.batch([
|
|
176
193
|
db
|
|
177
194
|
.prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
|
|
@@ -191,6 +208,7 @@ export function clientIssuesHandler(options: ClientIssuesOptions): (c: Context)
|
|
|
191
208
|
const bounds = {
|
|
192
209
|
retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
|
|
193
210
|
maxRowsPerHour: options.maxRowsPerHour ?? 600,
|
|
211
|
+
maxAnonymousRowsPerHour: options.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR,
|
|
194
212
|
};
|
|
195
213
|
return async (c) => {
|
|
196
214
|
let body: unknown;
|
|
@@ -128,6 +128,43 @@ describe('createD1ChunkStore β two isolates, one database', () => {
|
|
|
128
128
|
expect(await store.add(chunks[0].params)).toBe(false);
|
|
129
129
|
});
|
|
130
130
|
|
|
131
|
+
test('π΄ one caller flooding "chunk 1 of 2" under fresh cids cannot starve another caller (forge task 5306)', async () => {
|
|
132
|
+
const db = database();
|
|
133
|
+
const { chunks, body } = await multiChunk();
|
|
134
|
+
const share = chunks.length;
|
|
135
|
+
const store = createD1ChunkStore(db.handle(), { maxRows: share * 3, maxRowsPerCaller: share });
|
|
136
|
+
let refused = 0;
|
|
137
|
+
for (let n = 0; n < share * 4; n++) {
|
|
138
|
+
try {
|
|
139
|
+
await store.add({ ...chunks[0].params, _cid: `junk-${n}` }, { caller: '203.0.113.9' });
|
|
140
|
+
} catch {
|
|
141
|
+
refused++;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
expect(refused).toBe(share * 3);
|
|
145
|
+
expect(db.rows()).toBe(share);
|
|
146
|
+
// Another caller's whole multi-chunk write still lands.
|
|
147
|
+
let result: unknown = false;
|
|
148
|
+
for (const chunk of chunks) result = await store.add(chunk.params, { caller: '198.51.100.4' });
|
|
149
|
+
expect(bodyOf(result)).toEqual(body);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test('one caller\'s chunks never join another caller\'s set of the same cid', async () => {
|
|
153
|
+
const db = database();
|
|
154
|
+
const store = createD1ChunkStore(db.handle());
|
|
155
|
+
const { chunks } = await multiChunk();
|
|
156
|
+
for (const chunk of chunks.slice(0, -1)) expect(await store.add(chunk.params, { caller: '198.51.100.4' })).toBe(false);
|
|
157
|
+
expect(await store.add(chunks.at(-1)!.params, { caller: '203.0.113.9' })).toBe(false);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test('a cid that is not a short ASCII token is refused as a bad payload, and writes nothing', async () => {
|
|
161
|
+
const db = database();
|
|
162
|
+
const store = createD1ChunkStore(db.handle());
|
|
163
|
+
const { chunks } = await multiChunk();
|
|
164
|
+
expect(await store.add({ ...chunks[0].params, _cid: '\u00ffescape' })).toBeInstanceOf(Error);
|
|
165
|
+
expect(db.rows()).toBe(0);
|
|
166
|
+
});
|
|
167
|
+
|
|
131
168
|
test('a payload over its size cap is refused as a bad one, and its rows dropped', async () => {
|
|
132
169
|
const db = database();
|
|
133
170
|
const { chunks } = await multiChunk();
|
|
@@ -164,6 +201,30 @@ describe('createD1ChunkStore behind mountCtgrTunnel', () => {
|
|
|
164
201
|
expect(seen).toEqual([body]);
|
|
165
202
|
});
|
|
166
203
|
|
|
204
|
+
test('π΄ the tunnel names the caller by the edge\'s address, IPv6 by its /64 β a flood from one network leaves another\'s write green', async () => {
|
|
205
|
+
const db = database();
|
|
206
|
+
const seen: unknown[] = [];
|
|
207
|
+
const app = new Hono();
|
|
208
|
+
const { chunks, body } = await multiChunk();
|
|
209
|
+
// The table holds the flood's share plus one real write.
|
|
210
|
+
const share = chunks.length;
|
|
211
|
+
mountCtgrTunnel(app, { store: createD1ChunkStore(db.handle(), { maxRows: share * 2, maxRowsPerCaller: share }) });
|
|
212
|
+
app.post('/api/v1/notes', async (c) => {
|
|
213
|
+
seen.push(await c.req.json());
|
|
214
|
+
return c.json({ saved: true }, 201);
|
|
215
|
+
});
|
|
216
|
+
const statuses: number[] = [];
|
|
217
|
+
for (let n = 0; n < share * 2; n++) {
|
|
218
|
+
// Every address in ONE /64 is one caller.
|
|
219
|
+
const url = chunks[0].url.replace(/_cid=[^&]+/, `_cid=junk-${n}`);
|
|
220
|
+
const res = await app.fetch(new Request(`https://music.test${url}`, { headers: { 'cf-connecting-ip': `2001:0db8:1:2:${(n + 1).toString(16)}::1` } }));
|
|
221
|
+
statuses.push(res.status);
|
|
222
|
+
}
|
|
223
|
+
expect(statuses).toEqual([...Array(share).fill(202), ...Array(share).fill(503)]);
|
|
224
|
+
for (const chunk of chunks) await app.fetch(new Request(`https://music.test${chunk.url}`, { headers: { 'cf-connecting-ip': '2001:db8:1:3::1' } }));
|
|
225
|
+
expect(seen).toEqual([body]);
|
|
226
|
+
});
|
|
227
|
+
|
|
167
228
|
test('a full table answers 503 CTGR_STORE_UNAVAILABLE, not 202', async () => {
|
|
168
229
|
const db = database();
|
|
169
230
|
const app = new Hono();
|
|
@@ -27,6 +27,13 @@
|
|
|
27
27
|
* here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
|
|
28
28
|
* (β 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
|
|
29
29
|
* A payload over `maxPayloadBytes` is refused as a bad one (β 400), and its rows dropped.
|
|
30
|
+
*
|
|
31
|
+
* π΄ ONE caller may hold at most `maxRowsPerCaller` of those rows (forge task 5306). With only the
|
|
32
|
+
* table-wide cap, one stranger sending "chunk 1 of 2" under fresh cids kept the table full and every
|
|
33
|
+
* real GET-only device's bulk write 503'd. Each row's `cid` is stored as `<caller hash>~<cid>`, the
|
|
34
|
+
* caller being the tunnel's `context.caller` (the edge's client address, IPv6 by /64), so a caller's
|
|
35
|
+
* rows are one PRIMARY KEY range to count β no schema change on the eight apps' D1s β and one caller's
|
|
36
|
+
* chunks can never join another's set. A caller over its share is refused like a full table (503).
|
|
30
37
|
*/
|
|
31
38
|
import { ChunkStore, type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
|
|
32
39
|
import { parseChunk, type ParsedChunk } from 'cursedbelt-core/ctgr';
|
|
@@ -48,12 +55,32 @@ export const CTGR_CHUNKS_DDL: readonly string[] = [
|
|
|
48
55
|
export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
|
|
49
56
|
/** Rows the whole table may hold before a new chunk is refused (β 503). Default 4,000 (~10 MB). */
|
|
50
57
|
maxRows?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Rows ONE caller (the tunnel's `context.caller`) may hold before its next chunk is refused (β 503).
|
|
60
|
+
* Default 400 β a tenth of the table, and ~700 KB of payload: far past any real bulk write.
|
|
61
|
+
*/
|
|
62
|
+
maxRowsPerCaller?: number;
|
|
51
63
|
}
|
|
52
64
|
|
|
53
65
|
/** 2 MB: about 1,100 chunks β a bulk edit of thousands of ids is a few dozen. */
|
|
54
66
|
const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
|
|
55
67
|
const DEFAULT_TTL_MS = 30_000;
|
|
56
68
|
const DEFAULT_MAX_ROWS = 4_000;
|
|
69
|
+
const DEFAULT_MAX_ROWS_PER_CALLER = 400;
|
|
70
|
+
const CID = /^[A-Za-z0-9-]{1,64}$/;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The caller's namespace in `cid`: an FNV-1a hash of its address, so the table holds no address. A
|
|
74
|
+
* collision only makes two callers share one share.
|
|
75
|
+
*/
|
|
76
|
+
function callerKey(caller: string): string {
|
|
77
|
+
let h = 0x811c9dc5;
|
|
78
|
+
for (let i = 0; i < caller.length; i++) {
|
|
79
|
+
h ^= caller.charCodeAt(i);
|
|
80
|
+
h = Math.imul(h, 0x01000193);
|
|
81
|
+
}
|
|
82
|
+
return (h >>> 0).toString(36).padStart(7, '0');
|
|
83
|
+
}
|
|
57
84
|
|
|
58
85
|
interface CountRow {
|
|
59
86
|
n: number;
|
|
@@ -69,12 +96,13 @@ export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts
|
|
|
69
96
|
const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
|
|
70
97
|
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
71
98
|
const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
|
|
99
|
+
const maxRowsPerCaller = options.maxRowsPerCaller ?? DEFAULT_MAX_ROWS_PER_CALLER;
|
|
72
100
|
const now = options.now ?? Date.now;
|
|
73
101
|
// The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
|
|
74
102
|
const decodeOpts: ChunkStoreOpts = { maxPayloadBytes };
|
|
75
103
|
|
|
76
104
|
return {
|
|
77
|
-
async add(input) {
|
|
105
|
+
async add(input, context) {
|
|
78
106
|
const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
|
|
79
107
|
let chunk: ParsedChunk;
|
|
80
108
|
try {
|
|
@@ -85,26 +113,32 @@ export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts
|
|
|
85
113
|
// One chunk needs no rendezvous β decode it here, in this isolate.
|
|
86
114
|
if (chunk.total === 1) return new ChunkStore(decodeOpts).add(params);
|
|
87
115
|
if (chunk.payloadLength > maxPayloadBytes) return new Error('ctgr: payload exceeds size cap');
|
|
116
|
+
// The codec's cid is a UUID. Anything past ASCII would sort outside the caller's counted range.
|
|
117
|
+
if (!CID.test(chunk.cid)) return new Error('ctgr: a chunk id is a short token of letters, digits and dashes');
|
|
88
118
|
|
|
89
119
|
const at = now();
|
|
120
|
+
const owner = callerKey(context?.caller ?? '');
|
|
121
|
+
// A cid is [A-Za-z0-9-], all below `\x7f`, so `<owner>~<cid>` sorts inside [from, to): the caller's rows.
|
|
122
|
+
const cid = `${owner}~${chunk.cid}`;
|
|
123
|
+
const [from, to] = [`${owner}~`, `${owner}\x7f`];
|
|
90
124
|
const [, , counted] = await db.batch<CountRow>([
|
|
91
125
|
db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
|
|
92
126
|
db
|
|
93
127
|
.prepare(
|
|
94
|
-
`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`,
|
|
128
|
+
`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ? AND (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE} WHERE cid >= ? AND cid < ?) < ?`,
|
|
95
129
|
)
|
|
96
|
-
.bind(
|
|
130
|
+
.bind(cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows, from, to, maxRowsPerCaller),
|
|
97
131
|
db
|
|
98
132
|
.prepare(
|
|
99
133
|
`SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`,
|
|
100
134
|
)
|
|
101
|
-
.bind(chunk.index,
|
|
135
|
+
.bind(chunk.index, cid),
|
|
102
136
|
]);
|
|
103
137
|
const row = counted?.results[0];
|
|
104
|
-
// Neither inserted now nor held from before: the table is at `maxRows
|
|
105
|
-
if (!row?.mine) throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
|
|
138
|
+
// Neither inserted now nor held from before: the table is at `maxRows`, or this caller at its share.
|
|
139
|
+
if (!row?.mine) throw new Error(`ctgr: the chunk table is full (${maxRows} rows, ${maxRowsPerCaller} a caller)`);
|
|
106
140
|
if (row.b > maxPayloadBytes) {
|
|
107
|
-
await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(
|
|
141
|
+
await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(cid).run();
|
|
108
142
|
return new Error('ctgr: payload exceeds size cap');
|
|
109
143
|
}
|
|
110
144
|
if (row.n < chunk.total) return false;
|
|
@@ -112,7 +146,7 @@ export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts
|
|
|
112
146
|
// Complete: claim the set. Only one request's DELETE can return its rows.
|
|
113
147
|
const claimed = await db
|
|
114
148
|
.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
|
|
115
|
-
.bind(
|
|
149
|
+
.bind(cid)
|
|
116
150
|
.all<{ idx: number; params: string }>();
|
|
117
151
|
if (claimed.results.length < chunk.total) return false;
|
|
118
152
|
|
package/src/server/ctgrTunnel.ts
CHANGED
|
@@ -35,7 +35,15 @@ import { decodeCtgrTwin } from './ctgrTwin.js';
|
|
|
35
35
|
* a THROW means the store itself could not answer (β 503).
|
|
36
36
|
*/
|
|
37
37
|
export interface CtgrChunkSink {
|
|
38
|
-
|
|
38
|
+
/**
|
|
39
|
+
* `context.caller` is who sent the chunk (`callerOfTwin` β the edge's client address, an IPv6 one by
|
|
40
|
+
* its /64), so a store shared by every caller can give each its own share (forge task 5306).
|
|
41
|
+
*/
|
|
42
|
+
add(
|
|
43
|
+
params: Record<string, string> | URLSearchParams,
|
|
44
|
+
/** `caller`: the edge's client address (`cf-connecting-ip`), an IPv6 one cut to its /64; `''` when none was sent. */
|
|
45
|
+
context?: { caller?: string },
|
|
46
|
+
): Promise<CtgrDecoded | false | Error>;
|
|
39
47
|
}
|
|
40
48
|
|
|
41
49
|
export interface CtgrTunnelOptions {
|
package/src/server/ctgrTwin.ts
CHANGED
|
@@ -41,7 +41,7 @@ export async function decodeCtgrTwin(
|
|
|
41
41
|
|
|
42
42
|
let result: CtgrDecoded | false | Error;
|
|
43
43
|
try {
|
|
44
|
-
result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
|
|
44
|
+
result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params, { caller: callerOfTwin(raw) });
|
|
45
45
|
} catch (error) {
|
|
46
46
|
console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
|
|
47
47
|
return json({ error: 'ctgr: the chunk store could not answer β send it again', code: 'CTGR_STORE_UNAVAILABLE' }, 503);
|
|
@@ -51,6 +51,24 @@ export async function decodeCtgrTwin(
|
|
|
51
51
|
return rebuildRequest(raw, twinPath, url, result);
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Who sent this twin, as one network: Cloudflare's `cf-connecting-ip` (the edge sets it and a client
|
|
56
|
+
* cannot), an IPv6 address cut to its /64 β one subscriber holds a whole /64, so a per-address share
|
|
57
|
+
* would be no share at all. `''` when the header is absent (a test, a host with no edge in front).
|
|
58
|
+
*/
|
|
59
|
+
export function callerOfTwin(request: Request): string {
|
|
60
|
+
const ip = (request.headers.get('cf-connecting-ip') ?? '').trim().toLowerCase();
|
|
61
|
+
if (!ip.includes(':')) return ip;
|
|
62
|
+
const [head = '', tail = ''] = ip.split('::');
|
|
63
|
+
const left = head ? head.split(':') : [];
|
|
64
|
+
const right = tail ? tail.split(':') : [];
|
|
65
|
+
const groups = ip.includes('::') ? [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right] : left;
|
|
66
|
+
return `${groups
|
|
67
|
+
.slice(0, 4)
|
|
68
|
+
.map((g) => g.replace(/^0+(?=.)/, ''))
|
|
69
|
+
.join(':')}::/64`;
|
|
70
|
+
}
|
|
71
|
+
|
|
54
72
|
/**
|
|
55
73
|
* Did a browser say this twin came from somewhere else? `Sec-Fetch-Site` is set by the browser
|
|
56
74
|
* and no page can forge it: only `same-origin` is the app's own `installCtgrFetch`. `none` (a
|
|
@@ -100,9 +100,9 @@ describe("serverActions β the API seam that names a state-changing act", () =>
|
|
|
100
100
|
const dataset = fakeDataset();
|
|
101
101
|
const events = createEventSink(dataset, { app: "music" });
|
|
102
102
|
const app = new Hono();
|
|
103
|
-
app.use("
|
|
104
|
-
app.get("/api/
|
|
105
|
-
await app.request("https://music.cursedalchemy.com/api/
|
|
103
|
+
app.use("*", serverActions(events, RULES, { actorOf: () => ({ id: "curt@example.com" }) }));
|
|
104
|
+
app.get("/ctgrde/api/playlists/:id", (c) => c.json({ ok: true }));
|
|
105
|
+
await app.request("https://music.cursedalchemy.com/ctgrde/api/playlists/7", { headers: { "user-agent": BROWSER } });
|
|
106
106
|
expect(dataset.points[0]?.indexes).toEqual(["action:playlist.delete"]);
|
|
107
107
|
});
|
|
108
108
|
|
|
@@ -138,8 +138,8 @@ describe("serverActions β the API seam that names a state-changing act", () =>
|
|
|
138
138
|
const events = createEventSink(dataset, { app: "lists" });
|
|
139
139
|
const app = new Hono();
|
|
140
140
|
// A known actor writes at once; the anonymous hash would make every assertion wait on Web Crypto.
|
|
141
|
-
app.use("
|
|
142
|
-
app.use("
|
|
141
|
+
app.use("*", serverActions(events, GATED, { actorOf: () => ({ id: "curt@example.com" }) }));
|
|
142
|
+
app.use("*", async (c) => c.json({ error: "sign in" }, status as 401));
|
|
143
143
|
return {
|
|
144
144
|
names: () => dataset.points.map((p) => [p.blobs?.[3], p.blobs?.[13]]),
|
|
145
145
|
blobs: () => JSON.stringify(dataset.points),
|
|
@@ -178,7 +178,7 @@ describe("serverActions β the API seam that names a state-changing act", () =>
|
|
|
178
178
|
|
|
179
179
|
test("a ctgr GET-twin refused by the gate counts as its real verb", async () => {
|
|
180
180
|
const { names, send } = refused();
|
|
181
|
-
await send("GET", "/api/
|
|
181
|
+
await send("GET", "/ctgrde/api/playlists/my-mix");
|
|
182
182
|
expect(names()).toEqual([["playlist.delete", "refused"]]);
|
|
183
183
|
});
|
|
184
184
|
|
|
@@ -142,6 +142,19 @@ describe("the guard decodes a lock twin and judges the POST it carries", () => {
|
|
|
142
142
|
expect(res?.headers.get("set-cookie")).toBeNull();
|
|
143
143
|
});
|
|
144
144
|
|
|
145
|
+
test.each(["/ctgrPO", "/ctgrzz"])(
|
|
146
|
+
"only core's verbs make a lock twin: the right password at %s/__lock/β¦ is not decoded, so it unlocks nothing",
|
|
147
|
+
async (head) => {
|
|
148
|
+
const guard = build();
|
|
149
|
+
const real = await twin("POST", MASTER_LOCK_PATHS.unlock, { verifier: VERIFIER });
|
|
150
|
+
const url = new URL(real.url);
|
|
151
|
+
url.pathname = head + url.pathname.slice(7);
|
|
152
|
+
const res = await guard.handle(new Request(url, { headers: real.headers }));
|
|
153
|
+
expect(res?.status).not.toBe(200);
|
|
154
|
+
expect(res?.headers.get("set-cookie") ?? null).toBeNull();
|
|
155
|
+
},
|
|
156
|
+
);
|
|
157
|
+
|
|
145
158
|
test("a twin of an app path is not the guard's to decode β it is walled like any request", async () => {
|
|
146
159
|
const guard = build();
|
|
147
160
|
const res = await guard.handle(await twin("POST", "/api/thing", { a: 1 }));
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
accountsPageHtml,
|
|
25
25
|
} from "./accountsPage.js";
|
|
26
26
|
import { ChunkStore } from "cursedbelt-core/ctgr/chunk-store";
|
|
27
|
+
import { isCtgrTwinOf } from "cursedbelt-core/ctgr/types";
|
|
27
28
|
import { V0ChunkStore } from "cursedbelt-core/ctgr/v0compat";
|
|
28
29
|
import { decodeCtgrTwin } from "../ctgrTwin.js";
|
|
29
30
|
import { LOCK_SCRIPT, LOCK_STYLE, type LockPageOptions, lockPageHtml } from "./lockPage.js";
|
|
@@ -78,13 +79,6 @@ export interface MasterLockGuardOptions extends LockPageOptions {
|
|
|
78
79
|
|
|
79
80
|
const noStore = { "cache-control": "no-store, no-cache, must-revalidate", pragma: "no-cache" } as const;
|
|
80
81
|
|
|
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
|
-
|
|
88
82
|
/**
|
|
89
83
|
* The lock page's own CSP. Strict enough to stand in front of `apps/vault`'s wall without
|
|
90
84
|
* loosening it: nothing loads from anywhere but this origin, the form posts nowhere (the
|
|
@@ -353,7 +347,10 @@ export function createMasterLockGuard(options: MasterLockGuardOptions): MasterLo
|
|
|
353
347
|
// π΄ The twin is DECODED here and the real request judged by the very rule below, so the
|
|
354
348
|
// wall decides an unlock's twin exactly as it decides the POST, whichever of this guard and
|
|
355
349
|
// `mountCtgrTunnel` an app mounts first β and in a bare `Bun.serve` app that has no tunnel.
|
|
356
|
-
|
|
350
|
+
// A GET-only device's twin of a lock write: `/ctgr<xx>/__lock/β¦` (forge task 5158). Its writes β
|
|
351
|
+
// unlock, enroll, ping, lock β would otherwise reach the wall as a GET to a path that is not the
|
|
352
|
+
// lock's, and be refused, so such a device could never get in. Core says what a twin is (task 5162).
|
|
353
|
+
if (isCtgrTwinOf(url.pathname, MASTER_LOCK_PREFIX)) {
|
|
357
354
|
const decoded = await decodeCtgrTwin(req, url.pathname, twinStore, twinLegacy);
|
|
358
355
|
return decoded instanceof Response ? decoded : handle(decoded);
|
|
359
356
|
}
|
|
@@ -48,23 +48,39 @@ describe('normalizeRoute', () => {
|
|
|
48
48
|
return c.text('');
|
|
49
49
|
};
|
|
50
50
|
app.get('/api/notes/:id', gate);
|
|
51
|
-
app.use('
|
|
51
|
+
app.use('*', async (c, next) => {
|
|
52
52
|
await next();
|
|
53
53
|
if (c.req.path.includes('gated')) seen.push(normalizeRoute(c).unmatchedPath);
|
|
54
54
|
});
|
|
55
|
-
app.use('
|
|
55
|
+
app.use('*', async (c, next) => (c.req.path.includes('gated') ? c.text('no', 401) : next()));
|
|
56
56
|
await app.request('http://x/api/notes/n1');
|
|
57
57
|
await app.request('http://x/api/gated/my-slug');
|
|
58
|
-
await app.request('http://x/api/
|
|
58
|
+
await app.request('http://x/ctgrde/api/gated/my-slug');
|
|
59
59
|
expect(seen).toEqual([undefined, '/api/gated/my-slug', '/api/gated/my-slug']);
|
|
60
60
|
});
|
|
61
61
|
|
|
62
62
|
test('maps a ctgr GET-twin back to its real verb + path', async () => {
|
|
63
63
|
const label = await labelFor(
|
|
64
|
-
(app) => app.get('/api/
|
|
65
|
-
new Request('http://x/api/
|
|
64
|
+
(app) => app.get('/ctgrpa/api/notes/:id', probe),
|
|
65
|
+
new Request('http://x/ctgrpa/api/notes/n1'),
|
|
66
66
|
);
|
|
67
|
-
// /
|
|
67
|
+
// /ctgrpa = PATCH twin β aggregates with the real PATCH /api/notes/:id
|
|
68
68
|
expect(label).toBe('PATCH /api/notes/:id');
|
|
69
69
|
});
|
|
70
|
+
|
|
71
|
+
test.each([
|
|
72
|
+
['/ctgrpo/api/notes', 'POST /api/notes'],
|
|
73
|
+
['/ctgrpu/api/notes/42', 'PUT /api/notes/:id'],
|
|
74
|
+
['/ctgrde/api/notes/42', 'DELETE /api/notes/:id'],
|
|
75
|
+
])('a twin the tunnel catches (%s) counts as the verb the client sent, with its own path collapsed', async (twin, want) => {
|
|
76
|
+
const label = await labelFor((app) => app.get('/:ctgrTwin{ctgr.+}', probe), new Request(`http://x${twin}`));
|
|
77
|
+
expect(label).toBe(want);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('only core\'s verbs make a twin: /ctgrzz/ and a twin buried mid-path stay the GET they are', async () => {
|
|
81
|
+
const zz = await labelFor((app) => app.get('*', probe), new Request('http://x/ctgrzz/api/notes'));
|
|
82
|
+
expect(zz).toBe('GET /ctgrzz/api/notes');
|
|
83
|
+
const buried = await labelFor((app) => app.get('*', probe), new Request('http://x/api/ctgrpo/notes'));
|
|
84
|
+
expect(buried).toBe('GET /api/ctgrpo/notes');
|
|
85
|
+
});
|
|
70
86
|
});
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ABBREV_TO_METHOD, type CtgrAbbrev, ctgrTwinTarget } from 'cursedbelt-core/ctgr/types';
|
|
1
2
|
import type { Context } from 'hono';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -15,10 +16,6 @@ import type { Context } from 'hono';
|
|
|
15
16
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
17
|
const LONG_HEX_RE = /^[0-9a-f]{16,}$/i;
|
|
17
18
|
|
|
18
|
-
// The ctgr twin URL is `/ctgr<last-2-of-method><url>`, so the two-letter suffix
|
|
19
|
-
// recovers the original verb (POSTβst, PUTβut, PATCHβch, DELETEβte).
|
|
20
|
-
const CTGR_METHOD: Record<string, string> = { st: 'POST', ut: 'PUT', ch: 'PATCH', te: 'DELETE' };
|
|
21
|
-
|
|
22
19
|
function collapseSegment(seg: string): string {
|
|
23
20
|
if (!seg) return seg;
|
|
24
21
|
if (/^\d+$/.test(seg)) return ':id';
|
|
@@ -64,13 +61,16 @@ export function normalizeRoute(c: Context): NormalizedRoute {
|
|
|
64
61
|
let route = pattern ?? (collapsePath(path) || '/');
|
|
65
62
|
let unmatchedPath = pattern ? undefined : path;
|
|
66
63
|
|
|
67
|
-
// Map a ctgr GET-twin back to its real verb + url:
|
|
68
|
-
//
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
64
|
+
// Map a ctgr GET-twin back to its real verb + url: `/ctgrpa/api/notes/n1` β PATCH /api/notes/:id.
|
|
65
|
+
// Which paths are twins, and which verb each stands for, is core's one answer (forge task 5162) β
|
|
66
|
+
// this file's own table once held abbreviations no client sends, so every twin counted as a GET.
|
|
67
|
+
const twin = ctgrTwinTarget(path);
|
|
68
|
+
if (twin !== null) {
|
|
69
|
+
method = ABBREV_TO_METHOD[path.slice(5, 7) as CtgrAbbrev];
|
|
70
|
+
// A route registered at the twin itself is still a real pattern; the tunnel's catch-all is not.
|
|
71
|
+
const realPattern = pattern === undefined ? null : ctgrTwinTarget(pattern);
|
|
72
|
+
route = realPattern ?? (collapsePath(twin) || '/');
|
|
73
|
+
unmatchedPath = realPattern === null ? twin : undefined;
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
return { method, route, ...(unmatchedPath === undefined ? {} : { unmatchedPath }) };
|