cursedbelt-server 3.0.1 → 4.1.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.
Files changed (84) hide show
  1. package/dist/server/auth/jwt.d.ts +1 -1
  2. package/dist/server/auth/jwt.js +2 -2
  3. package/dist/server/master-lock/accountsPage.d.ts +39 -0
  4. package/dist/server/master-lock/accountsPage.js +455 -0
  5. package/dist/server/master-lock/guard.js +39 -1
  6. package/dist/server/master-lock/index.d.ts +10 -2
  7. package/dist/server/master-lock/index.js +10 -2
  8. package/dist/server/master-lock/lockPage.d.ts +9 -0
  9. package/dist/server/master-lock/lockPage.js +44 -36
  10. package/dist/server/media-bun/streaming.d.ts +0 -1
  11. package/dist/server/media-bun/streaming.js +1 -1
  12. package/dist/server/storage/binaryStore.d.ts +385 -0
  13. package/dist/server/storage/binaryStore.js +739 -0
  14. package/dist/server/storage/binaryStoreFake.d.ts +56 -0
  15. package/dist/server/storage/binaryStoreFake.js +63 -0
  16. package/dist/server/storage/files/catalogue.d.ts +2 -2
  17. package/dist/server/storage/files/catalogue.js +18 -208
  18. package/dist/server/storage/files/fileRoutes.d.ts +2 -20
  19. package/dist/server/storage/files/fileRoutes.js +1 -74
  20. package/dist/server/storage/files/index.d.ts +1 -1
  21. package/dist/server/storage/files/index.js +1 -1
  22. package/dist/server/storage/files/migrations.js +9 -6
  23. package/dist/server/storage/files/stack.d.ts +6 -31
  24. package/dist/server/storage/files/stack.js +0 -27
  25. package/dist/server/storage/files/types.d.ts +10 -60
  26. package/dist/server/storage/files/types.js +9 -0
  27. package/dist/server/storage/index.d.ts +2 -2
  28. package/dist/server/storage/index.js +1 -1
  29. package/dist/server/storage/mountMediaRoutes.d.ts +1 -4
  30. package/dist/server/storage/types.d.ts +0 -9
  31. package/dist/server/storage/types.js +2 -9
  32. package/package.json +14 -2
  33. package/src/leafSubpathsImportNothing.spec.ts +30 -4
  34. package/src/server/auth/jwt.ts +2 -2
  35. package/src/server/master-lock/accountsPage.spec.ts +231 -0
  36. package/src/server/master-lock/accountsPage.ts +465 -0
  37. package/src/server/master-lock/guard.ts +44 -1
  38. package/src/server/master-lock/index.ts +22 -2
  39. package/src/server/master-lock/lockPage.spec.ts +20 -16
  40. package/src/server/master-lock/lockPage.ts +45 -36
  41. package/src/server/media-bun/streaming.ts +0 -6
  42. package/src/server/storage/binaryStore.spec.ts +908 -0
  43. package/src/server/storage/binaryStore.ts +1049 -0
  44. package/src/server/storage/binaryStoreFake.ts +111 -0
  45. package/src/server/storage/fileUploadClient.integration.spec.ts +2 -21
  46. package/src/server/storage/files/adapter.photo.display.spec.ts +2 -2
  47. package/src/server/storage/files/adapter.photo.spec.ts +2 -2
  48. package/src/server/storage/files/adapter.spec.ts +0 -1
  49. package/src/server/storage/files/catalogue.media-host.spec.ts +6 -71
  50. package/src/server/storage/files/catalogue.recover.spec.ts +14 -23
  51. package/src/server/storage/files/catalogue.ts +19 -240
  52. package/src/server/storage/files/fileRoutes.replace.spec.ts +2 -2
  53. package/src/server/storage/files/fileRoutes.spec.ts +3 -97
  54. package/src/server/storage/files/fileRoutes.ts +2 -96
  55. package/src/server/storage/files/index.ts +1 -4
  56. package/src/server/storage/files/migrations.ts +9 -7
  57. package/src/server/storage/files/stack.spec.ts +11 -111
  58. package/src/server/storage/files/stack.ts +9 -61
  59. package/src/server/storage/files/types.ts +20 -68
  60. package/src/server/storage/index.ts +0 -4
  61. package/src/server/storage/mountMediaRoutes.ts +1 -7
  62. package/src/server/storage/types.ts +2 -11
  63. package/src/shippedFilesAreTracked.spec.ts +3 -2
  64. package/dist/server/private-media/crypto.d.ts +0 -37
  65. package/dist/server/private-media/crypto.js +0 -111
  66. package/dist/server/private-media/index-store.d.ts +0 -31
  67. package/dist/server/private-media/index-store.js +0 -36
  68. package/dist/server/private-media/mountPrivateRoutes.d.ts +0 -26
  69. package/dist/server/private-media/mountPrivateRoutes.js +0 -219
  70. package/dist/server/private-media/pipeline.d.ts +0 -37
  71. package/dist/server/private-media/pipeline.js +0 -97
  72. package/dist/server/private-media/unlock.d.ts +0 -52
  73. package/dist/server/private-media/unlock.js +0 -55
  74. package/src/server/private-media/blobRoute.spec.ts +0 -165
  75. package/src/server/private-media/crypto.spec.ts +0 -81
  76. package/src/server/private-media/crypto.ts +0 -155
  77. package/src/server/private-media/gatePolicy.spec.ts +0 -98
  78. package/src/server/private-media/index-store.ts +0 -83
  79. package/src/server/private-media/mountPrivateRoutes.ts +0 -265
  80. package/src/server/private-media/pipeline.spec.ts +0 -111
  81. package/src/server/private-media/pipeline.ts +0 -170
  82. package/src/server/private-media/routes.spec.ts +0 -265
  83. package/src/server/private-media/unlock.ts +0 -112
  84. package/src/server/storage/files/catalogue.private.spec.ts +0 -106
@@ -0,0 +1,739 @@
1
+ /**
2
+ * binary-server client — the ONE way an app talks to the machine's binary store
3
+ * (`apps/binary-server`, :3099 behind binary-server.cursedalchemy.com).
4
+ *
5
+ * The owner's standing decision: binary-server is THE binary/media storage spot for
6
+ * every app — local disks must not accumulate image/blob payloads. Any app that loads
7
+ * or generates images stores them through this client, behind its own app-local seam
8
+ * (an `AttachmentStore`, a box-art cache, art artifacts).
9
+ *
10
+ * Protocol (see binary-server/src/server.ts + src/tokens.ts):
11
+ * - `PUT /upload/<app>/<key>?token=` uploads whole bytes (201).
12
+ * - `GET /media/<app>/<key>?token=` downloads (Range-capable; 404 when absent).
13
+ * - `DELETE /media/<app>/<key>?token=` is gated by BOTH `x-internal-secret` AND a
14
+ * per-op delete token (`op:"delete"`, tenant-scoped like read/write). Owner ruling #10.
15
+ * - Tokens are RS256 JWTs signed with the app's PRIVATE key (bs holds only the
16
+ * public half); `iss` must exactly match the registered issuer and `k` must be
17
+ * the app-prefixed path (`<app>/<key>`). Paths are decoded whole on the server,
18
+ * so keys are encoded PER SEGMENT with `/` kept literal.
19
+ *
20
+ * ── 🔴 Why this sits beside `createBinaryServerStore` rather than replacing it ──────
21
+ * `./binaryServerStore.ts` is 102 lines: a {@link MediaStore} adapter whose RS256 signer
22
+ * is INJECTED, deliberately, so that module carries no key material. This one is the
23
+ * other half of the same wire — it MINTS the token from a PKCS8 private PEM and owns the
24
+ * whole client surface: auto-chunking, the absence memo, Range reads, the repeat-key
25
+ * counter and tenant resolution. They are not the same module and neither is a worse
26
+ * version of the other; they share one contract, {@link FileTokenClaims}, so a token
27
+ * minted here can never drift out of shape from one minted there against the same
28
+ * binary-server.
29
+ *
30
+ * 🔴 It is published as the LEAF subpath `cursedbelt-server/binary-store`, never through
31
+ * the `./storage` barrel — that barrel drags the file-catalogue and transcode graph, and
32
+ * this module's whole promise is that an app pays nothing but `node:crypto` for it.
33
+ * `src/leafSubpathsImportNothing.spec.ts` is what holds that promise.
34
+ *
35
+ * ── Where it came from (2026-09-17) ────────────────────────────────────────────────
36
+ * Five apps carried a byte-for-byte copy of this file and three of them had drifted.
37
+ * Nothing could see it: a repo's gate proves that repo, so five green gates is what
38
+ * three forks of the fleet's binary-storage client looked like from the outside. The
39
+ * divergence was measured before the move and was entirely in prose and in one stale
40
+ * import specifier (`cursedbelt/server/storage`, the pre-split package name) — no
41
+ * behavioural difference in any of the three, so nothing was dropped to land the union.
42
+ */
43
+ import { createPrivateKey, sign as cryptoSign } from 'node:crypto';
44
+ /*
45
+ * ── The process-wide repeat register (§ the repeat-key counter) ───────────────
46
+ *
47
+ * An app makes one store per tenant and a few make two, so the counter has to
48
+ * aggregate somewhere above an individual client for the answer to mean "what is
49
+ * THIS DEPLOYMENT doing". It is a module-level map for the same reason an install
50
+ * metrics recorder is module-level: the thing being measured is the process, and
51
+ * threading a collector through every `createBinaryStore` call site would make
52
+ * instrumenting an app an act of remembering.
53
+ *
54
+ * An app reports it on `/healthz`, which the fleet probe already fetches for every
55
+ * live deployment — so this reaches the incident sweep, and the owner's text channel,
56
+ * without anybody making a new request for it.
57
+ */
58
+ const repeats = new Map();
59
+ /** Bounded: a genuinely runaway app must not turn this into a leak. */
60
+ const MAX_TRACKED_REPEATS = 50;
61
+ function recordRepeat(tenant, key, count, at) {
62
+ const id = `${tenant}/${key}`;
63
+ if (!repeats.has(id) && repeats.size >= MAX_TRACKED_REPEATS)
64
+ return;
65
+ repeats.set(id, {
66
+ tenant,
67
+ key,
68
+ reads: count,
69
+ windowMs: BINARY_REPEAT_WINDOW_MS,
70
+ at,
71
+ });
72
+ }
73
+ /**
74
+ * Which keys this process has read from the wire far too often, worst first —
75
+ * empty on every healthy deployment, which is what makes it a usable alarm.
76
+ *
77
+ * Entries older than one window are dropped as they are read, so a burst that
78
+ * stopped stops being reported rather than becoming a permanent accusation.
79
+ */
80
+ export function repeatedBinaryKeys(now = Date.now) {
81
+ const at = now();
82
+ const live = [];
83
+ for (const [id, row] of repeats) {
84
+ if (at - row.at >= BINARY_REPEAT_WINDOW_MS) {
85
+ repeats.delete(id);
86
+ continue;
87
+ }
88
+ live.push({ tenant: row.tenant, key: row.key, reads: row.reads, windowMs: row.windowMs });
89
+ }
90
+ return live.sort((a, b) => b.reads - a.reads);
91
+ }
92
+ /** Test seam — the register is process-wide, so a spec must be able to clear it. */
93
+ export function resetRepeatedBinaryKeys() {
94
+ repeats.clear();
95
+ }
96
+ /**
97
+ * Did this request ask for a FRESH answer — i.e. is it a hard refresh?
98
+ *
99
+ * 🔴 The owner's first escape hatch, and the reason it is a shared function rather
100
+ * than an inline header read in each app: *"if the no is remembered an hour then I
101
+ * could fix it but not be able to tell for an hour."* A browser hard-refresh sends
102
+ * `Cache-Control: no-cache` (older ones send `Pragma`), so reloading the picture is
103
+ * the repair — as long as every app spells the check the same way.
104
+ */
105
+ export function wantsFresh(req) {
106
+ const headers = req instanceof Headers ? req : req.headers;
107
+ const cacheControl = headers.get('cache-control')?.toLowerCase() ?? '';
108
+ if (cacheControl.includes('no-cache'))
109
+ return true;
110
+ return (headers.get('pragma')?.toLowerCase() ?? '').includes('no-cache');
111
+ }
112
+ /**
113
+ * 🔴 The size at which a single-request `put` stops being safe, FLEET-WIDE.
114
+ *
115
+ * binary-server is published through a Cloudflare Tunnel, and the edge refuses a
116
+ * request body over ~100 MB with a **413 before it ever reaches the origin**. So
117
+ * the ceiling is not bs's and not the caller's — it belongs to a hop neither end
118
+ * controls, and every app that stores a large blob inherits it.
119
+ *
120
+ * `apps/roms` hit it on 2026-08-08: eight genuine DS cartridges (128–512 MB)
121
+ * came back `[binary-store] put rom/<digest>: 413` and it read as eight
122
+ * mysterious ingest failures rather than as one limit. roms fixed it locally,
123
+ * which left the trap in place for every other app's attachments and for any
124
+ * future video/media path — so the threshold lives HERE now and `put` applies it
125
+ * itself.
126
+ *
127
+ * 64 MiB, not 100: the edge's number is approximate and includes headers and any
128
+ * transfer encoding, and the chunked path costs one extra request for a blob
129
+ * that only just crosses the line. Being early is free; being late is a 413.
130
+ */
131
+ export const AUTO_CHUNK_THRESHOLD_BYTES = 64 * 1024 * 1024;
132
+ /**
133
+ * 🔴 How long "the store does not hold this key" is believed — the NEGATIVE memo.
134
+ *
135
+ * The positive one never expires and needs no constant: a key in this fleet names
136
+ * either a content digest or a timestamped upload, so the bytes under it cannot
137
+ * change and "it is there" cannot stop being true. An ABSENCE is different — it is
138
+ * a fact about right now, and art, web copies and derivatives all genuinely arrive
139
+ * later — so it has to lapse.
140
+ *
141
+ * An hour is the default because the owner named the cost of getting it wrong:
142
+ *
143
+ * > *"potentially we need a shorter time for remembering a 'no' in some
144
+ * > circumstances or at least a way to bypass it occasionally. For instance
145
+ * > collections showed a lot of missing thumbnails and images and if the no is
146
+ * > remembered an hour then I could fix it but not be able to tell for an hour."*
147
+ *
148
+ * So the hour is never the only answer. TWO bypasses ship with it, both cheap and
149
+ * both proven by {@link BinaryStore.forgetMisses}' tests:
150
+ *
151
+ * · a read with `{ fresh: true }` ignores both memos and re-asks. `wantsFresh()`
152
+ * turns a browser's hard refresh (`Cache-Control: no-cache`) into exactly that,
153
+ * so the owner's own reload IS the fix for one picture;
154
+ * · `forgetMisses(prefix?)` drops every negative memo, or a subtree of them, so an
155
+ * app can expose a one-click repair and prove it in seconds rather than in an
156
+ * hour.
157
+ */
158
+ export const BINARY_ABSENCE_TTL_MS = 60 * 60 * 1000;
159
+ /**
160
+ * The window and the count that make a key's re-reads an INCIDENT rather than traffic.
161
+ *
162
+ * 🔴 Every quota incident this fleet has had was this exact shape and nothing was
163
+ * watching for it: roms boxart at ~200 reads per key per day (20,626 failed `/media`
164
+ * fetches in one day), family portraits at 2,449 per key per day, music cover art
165
+ * doing a server-side `get` that left the Mac to read a file on the Mac. In all three
166
+ * the giveaway was one key, over and over, from a `Bun/1.3.x` user agent — visible in
167
+ * Cloudflare's top-talker list and in nobody's code.
168
+ *
169
+ * 50 in five minutes is far above any legitimate server-side pattern (a page render
170
+ * asks for a key once; a warm pass asks once) and far below the rate that spends a
171
+ * day's allowance, so it fires early and it does not fire on a normal day.
172
+ */
173
+ export const BINARY_REPEAT_WINDOW_MS = 5 * 60 * 1000;
174
+ export const BINARY_REPEAT_THRESHOLD = 50;
175
+ export const DOWNLOAD_TOKEN_TTL_SECONDS = 60;
176
+ export const UPLOAD_TOKEN_TTL_SECONDS = 600;
177
+ /** Deletes are server-to-server and near-instant; a short TTL suffices. The token proves the
178
+ * caller holds THIS tenant's private key and is authorized for THIS path — binary-server
179
+ * requires it alongside the internal secret (defense in depth, owner ruling #10). */
180
+ export const DELETE_TOKEN_TTL_SECONDS = 120;
181
+ /** register-app prints the key as base64(PKCS8 PEM); env files sometimes carry
182
+ * raw PEM or PEM with literal `\n` sequences. Accept all three. */
183
+ export function normalizePrivateKeyPem(raw) {
184
+ const trimmed = raw.trim();
185
+ if (trimmed.includes('-----BEGIN'))
186
+ return trimmed.replaceAll('\\n', '\n');
187
+ let decoded;
188
+ try {
189
+ decoded = Buffer.from(trimmed, 'base64').toString('utf8');
190
+ }
191
+ catch {
192
+ throw new Error('[binary-store] private key is neither PEM nor base64');
193
+ }
194
+ if (!decoded.includes('-----BEGIN')) {
195
+ throw new Error('[binary-store] private key decodes to something that is not a PEM');
196
+ }
197
+ return decoded;
198
+ }
199
+ const base64url = (bytes) => Buffer.from(bytes).toString('base64url');
200
+ /** Keys may contain `/` as a real separator; each SEGMENT is percent-encoded
201
+ * because the server decodes the whole path before matching it to the token. */
202
+ const encodeKeyPath = (key) => key.split('/').map(encodeURIComponent).join('/');
203
+ export function createBinaryStore(cfg) {
204
+ const baseUrl = cfg.baseUrl.replace(/\/+$/, '');
205
+ /*
206
+ * 🔴 Where THIS PROCESS fetches bytes from, which is not where a browser fetches
207
+ * them from (2026-09-08).
208
+ *
209
+ * `baseUrl` is binary-server's public name, and it has to be: a phone has no other
210
+ * way to reach it. But an app's own SERVER calling `get`/`meta` went out to that
211
+ * public name too — through Cloudflare's Worker and back — to read bytes from a
212
+ * daemon on the same Mac. Two consequences, and the fleet met both on one day:
213
+ *
214
+ * 1. Every server-side read spent a request out of the Workers FREE plan's
215
+ * 100,000/day. family alone made 15,689 of them that day.
216
+ * 2. When that ceiling was reached Cloudflare answered 429 to everything, and
217
+ * family's people page drew no faces at all — because the app could not reach a
218
+ * store sitting 20cm away. The owner: "we can't let them block our images
219
+ * without a fallback."
220
+ *
221
+ * No extra copy is needed for that fallback. The bytes are already local, and an
222
+ * R2-backed object is reachable by binary-server directly — R2 is not gated by the
223
+ * Workers limit. So a deployment sharing a machine with binary-server names its
224
+ * loopback origin here and stops leaving the box to read its own files.
225
+ *
226
+ * `mediaUrl` is deliberately NOT affected: it mints a signed URL to hand to a
227
+ * BROWSER, and a browser cannot resolve 127.0.0.1 to this Mac. Redirected media —
228
+ * videos, large downloads — therefore still goes through the edge, which is correct,
229
+ * and is named as the remaining gap.
230
+ */
231
+ const internalBaseUrl = (cfg.internalBaseUrl ?? cfg.baseUrl).replace(/\/+$/, '');
232
+ const autoChunkBytes = cfg.autoChunkBytes ?? AUTO_CHUNK_THRESHOLD_BYTES;
233
+ const now = cfg.now ?? Date.now;
234
+ const absenceTtlMs = cfg.absenceTtlMs ?? BINARY_ABSENCE_TTL_MS;
235
+ /*
236
+ * ── 🔴 The shared picture cache (2026-09-09) ───────────────────────────────
237
+ *
238
+ * Three apps had written three copies of this, each after its own outage, and a
239
+ * fourth (family) had none at all and was measured at 2,449 reads per key per day.
240
+ * It belongs here because this is the one seam every app's media passes through —
241
+ * the rule from music (remember a YES for ever) and the rule from roms (remember a
242
+ * NO for an hour) in the place that makes them true for everybody.
243
+ *
244
+ * The positive memo is a `BlobMeta`, not a bare flag, because the read it exists to
245
+ * remove is `meta()` — one index read at binary-server, but a whole Cloudflare Worker
246
+ * invocation from the outside, which is the currency the fleet actually ran out of.
247
+ *
248
+ * 🔴 What makes "for ever" safe is the KEY SHAPE, not optimism. A key here is a
249
+ * content digest (music, collections) or a timestamped upload (family portraits:
250
+ * `<space>/portrait/<id>-<base36 time>`), so a re-upload is a NEW key and nothing can
251
+ * change under an old one. The one shape that does NOT have that property is roms'
252
+ * box art, whose key hashes the game NAME — which is why `put` refreshes the memo
253
+ * rather than leaving it, and why a `get` that comes back empty DEMOTES a positive
254
+ * memo instead of trusting it. Between them, a key whose bytes were replaced or
255
+ * released out from under us self-heals on the next read that actually wanted bytes.
256
+ */
257
+ const present = new Map();
258
+ const absentUntil = new Map();
259
+ /** A live negative memo, or `false` (lapsed entries are dropped as they are met). */
260
+ const knownAbsent = (key) => {
261
+ const until = absentUntil.get(key);
262
+ if (until === undefined)
263
+ return false;
264
+ if (until > now())
265
+ return true;
266
+ absentUntil.delete(key);
267
+ return false;
268
+ };
269
+ const rememberPresent = (key, meta) => {
270
+ absentUntil.delete(key);
271
+ present.set(key, meta);
272
+ };
273
+ const rememberAbsent = (key) => {
274
+ present.delete(key);
275
+ absentUntil.set(key, now() + absenceTtlMs);
276
+ };
277
+ /** Neither memo is trustworthy for this key any more — a write, or a delete. */
278
+ const forget = (key) => {
279
+ present.delete(key);
280
+ absentUntil.delete(key);
281
+ };
282
+ /*
283
+ * The repeat-key counter (see BINARY_REPEAT_THRESHOLD). Counts WIRE reads only:
284
+ * a memo hit is the cure, so a key the memo answers has to fall silent, or the
285
+ * alarm would fire loudest on the apps that fixed themselves.
286
+ */
287
+ const reads = new Map();
288
+ const countWireRead = (key) => {
289
+ const at = now();
290
+ const seen = reads.get(key);
291
+ if (!seen || at - seen.since >= BINARY_REPEAT_WINDOW_MS) {
292
+ reads.set(key, { count: 1, since: at });
293
+ return;
294
+ }
295
+ seen.count++;
296
+ // Below the line this is ordinary traffic, and the register must stay empty on a
297
+ // healthy deployment — an alarm that lists every key is one nobody reads.
298
+ if (seen.count < BINARY_REPEAT_THRESHOLD)
299
+ return;
300
+ if (seen.count === BINARY_REPEAT_THRESHOLD) {
301
+ // Once per key per window, at the moment it crosses — a line per read would
302
+ // be the same storm in the log file.
303
+ console.warn(`[binary-store] ${cfg.appId}/${key} has been read ${seen.count} times in ` +
304
+ `${Math.round((at - seen.since) / 1000)}s. Every one of those is a request out ` +
305
+ "of the fleet's daily Cloudflare allowance for bytes that cannot have changed — " +
306
+ 'this caller should be holding the answer. See BINARY_REPEAT_THRESHOLD.');
307
+ }
308
+ recordRepeat(cfg.appId, key, seen.count, at);
309
+ };
310
+ let keyObject = null;
311
+ const privateKey = () => {
312
+ keyObject ??= createPrivateKey(normalizePrivateKeyPem(cfg.privateKey));
313
+ return keyObject;
314
+ };
315
+ const signToken = async (claims, ttlSeconds,
316
+ /** Snap `iat` down to a multiple of this so the whole token is byte-stable
317
+ * inside one window — see {@link MediaUrlOptions.stableWindowSeconds}. */
318
+ windowSeconds) => {
319
+ const clock = Math.floor(Date.now() / 1000);
320
+ const issuedAt = windowSeconds && windowSeconds > 0
321
+ ? Math.floor(clock / windowSeconds) * windowSeconds
322
+ : clock;
323
+ const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
324
+ const payload = base64url(JSON.stringify({ iss: cfg.issuer, iat: issuedAt, exp: issuedAt + ttlSeconds, ...claims }));
325
+ const signature = cryptoSign('sha256', Buffer.from(`${header}.${payload}`), privateKey());
326
+ return `${header}.${payload}.${base64url(signature)}`;
327
+ };
328
+ const appKey = (key) => `${cfg.appId}/${key}`;
329
+ const mediaUrl = async (key, opts) => {
330
+ const window = opts?.stableWindowSeconds;
331
+ // Two windows, so a URL minted in the last second of one is still valid for a
332
+ // download that starts in the next.
333
+ const ttl = window && window > 0 ? window * 2 : (opts?.ttlSeconds ?? DOWNLOAD_TOKEN_TTL_SECONDS);
334
+ const token = await signToken({ k: appKey(key), fn: opts?.filename, dl: opts?.disposition }, ttl, window);
335
+ return `${baseUrl}/media/${encodeKeyPath(appKey(key))}?token=${encodeURIComponent(token)}`;
336
+ };
337
+ /**
338
+ * A signed URL for the MASTER of a multi-object tree, authorized by PREFIX.
339
+ *
340
+ * ── 🔴 Why an exact-key token cannot work here ──────────────────────────────────────
341
+ * An HLS ladder is a tree — a master naming rung playlists naming segments — and a
342
+ * player resolves those names RELATIVE to the master's URL. A relative URI resolves
343
+ * against the base URL's PATH and discards its query string (RFC 3986, and every player
344
+ * behaves this way), so `720/index.m3u8` arrives at binary-server with no `?token=` and
345
+ * is correctly refused.
346
+ *
347
+ * binary-server solves the second half: it rewrites a playlist as it serves it, appending
348
+ * the SAME token to every URI the playlist names (`src/media/hlsPlaylist.ts`). That
349
+ * rewrite only fires for a PREFIX token, and deliberately so — copying an exact-key token
350
+ * onto a child URI produces a URL that 403s, which is the same broken video with an extra
351
+ * query parameter. So the first half has to be minted here, and this is it.
352
+ *
353
+ * 🔴 It grants nothing the bearer did not already have: the prefix is the tree, and every
354
+ * URI inside the tree resolves under it. But it IS broader than an exact key by
355
+ * construction, so it is deliberately a separate method with its own name rather than a
356
+ * flag on `mediaUrl` — a caller reaching for prefix authority should have to say so.
357
+ */
358
+ const mediaPrefixUrl = async (prefix, master, opts) => {
359
+ const window = opts?.stableWindowSeconds;
360
+ const ttl = window && window > 0 ? window * 2 : (opts?.ttlSeconds ?? DOWNLOAD_TOKEN_TTL_SECONDS);
361
+ // The claim is the PREFIX; the URL points at the master inside it.
362
+ const token = await signToken({ p: appKey(prefix) }, ttl, window);
363
+ return `${baseUrl}/media/${encodeKeyPath(appKey(master))}?token=${encodeURIComponent(token)}`;
364
+ };
365
+ /** The same signed URL, aimed at the origin THIS PROCESS should use. Never handed to
366
+ * a browser — see the note on `internalBaseUrl`. */
367
+ const internalMediaUrl = async (key, opts) => (await mediaUrl(key, opts)).replace(baseUrl, internalBaseUrl);
368
+ /** `/meta` authorizes with the same token shape as `/media` — an exact-key claim. */
369
+ const metaUrl = async (key) => {
370
+ const token = await signToken({ k: appKey(key) }, DOWNLOAD_TOKEN_TTL_SECONDS);
371
+ // `/meta` is only ever asked by a server, so it always uses the internal origin.
372
+ return `${internalBaseUrl}/meta/${encodeKeyPath(appKey(key))}?token=${encodeURIComponent(token)}`;
373
+ };
374
+ const internalHeaders = () => {
375
+ if (!cfg.internalSecret) {
376
+ throw new Error('[binary-store] remove requires internalSecret (BINARY_SERVER_INTERNAL_SECRET)');
377
+ }
378
+ return { 'x-internal-secret': cfg.internalSecret };
379
+ };
380
+ const store = {
381
+ appId: cfg.appId,
382
+ signToken,
383
+ mediaUrl,
384
+ mediaPrefixUrl,
385
+ async put(key, bytes, mime, opts) {
386
+ // 🔴 The chunked fallback, applied HERE rather than at every call site —
387
+ // the limit is the Cloudflare Tunnel's, so it is a property of this
388
+ // client's destination and not of anyone's payload. See
389
+ // AUTO_CHUNK_THRESHOLD_BYTES.
390
+ if (bytes.byteLength > autoChunkBytes) {
391
+ return await store.putLarge(key, bytes, mime, opts);
392
+ }
393
+ const token = await signToken({ k: appKey(key) }, UPLOAD_TOKEN_TTL_SECONDS);
394
+ const title = opts?.title?.trim();
395
+ const titleQs = title ? `&title=${encodeURIComponent(title)}` : '';
396
+ const immutableQs = opts?.immutable ? '&immutable=1' : '';
397
+ const res = await fetch(`${baseUrl}/upload/${encodeKeyPath(appKey(key))}?token=${encodeURIComponent(token)}${titleQs}${immutableQs}`, {
398
+ method: 'PUT',
399
+ headers: mime ? { 'content-type': mime } : undefined,
400
+ body: bytes,
401
+ });
402
+ if (!res.ok) {
403
+ // A 413 that reaches here despite the threshold above means the edge's
404
+ // real cap is lower than we think, or the caller disabled the
405
+ // fallback. Say what it is and what to do — the bare status is what
406
+ // made eight rejected DS cartridges read as eight unrelated mysteries
407
+ // on 2026-08-08.
408
+ if (res.status === 413) {
409
+ throw new Error(`[binary-store] put ${key}: 413 — ${bytes.byteLength} bytes was refused before it ` +
410
+ 'reached binary-server (the Cloudflare Tunnel in front of it caps a request body ' +
411
+ `at roughly 100 MB). Use putLarge(), or lower autoChunkBytes (currently ${autoChunkBytes}).`);
412
+ }
413
+ throw new Error(`[binary-store] put ${key}: ${res.status}`);
414
+ }
415
+ // 🔴 It exists now, and its BYTES may be new ones. Dropping both memos rather
416
+ // than asserting a presence is what keeps a name-addressed key (roms' box art
417
+ // hashes the game name, not the bytes) honest: the next reader re-asks once
418
+ // and re-learns, instead of trusting a size and mime from the previous file.
419
+ forget(key);
420
+ },
421
+ /*
422
+ * 🔴 Every chunk is READ INTO MEMORY before it is sent, and that is not a
423
+ * simplification — it is the fix for a hang that stopped the collections dropzone
424
+ * dead for a day (measured 2026-08-13, Bun 1.3.14).
425
+ *
426
+ * `Bun.file(path).slice(a, b)` is a lazy PARTIAL view of a file, and handing one to
427
+ * `fetch` as a body never sends: the request stalls until binary-server's 60s
428
+ * `idleTimeout` closes the socket, and the caller sees `EPIPE` / "socket connection
429
+ * was closed unexpectedly". Measured on one 20 MB file against the live server:
430
+ *
431
+ * Bun.file, 16 MiB chunks (2 parts) → FAIL after 56,164 ms
432
+ * Bun.file, 8 MiB chunks (3 parts) → FAIL after 60,000 ms
433
+ * Bun.file, one WHOLE-range slice → OK in 62 ms
434
+ * the same bytes already in memory → OK in 43 ms
435
+ *
436
+ * A whole-range slice works because it is not really a partial view, which is why
437
+ * every small file went through fine and only the ones that had to be split failed —
438
+ * i.e. exactly the videos this path exists for. 42 files / 35 GB failed 42/42 on
439
+ * every scheduled sweep for a day with nothing in binary-server's log, because from
440
+ * its side the request simply never arrived.
441
+ *
442
+ * The cost is one chunk resident at a time — 16 MiB — which is the bound `putLarge`
443
+ * always promised. It is NOT the bound the old code delivered: the lazy slice was
444
+ * never read at all.
445
+ */
446
+ async putLarge(key, source, mime, opts) {
447
+ const chunkBytes = Math.max(1, opts?.chunkBytes ?? 16 * 1024 * 1024);
448
+ const blob = source instanceof Blob ? source : new Blob([source]);
449
+ const total = Math.max(1, Math.ceil(blob.size / chunkBytes));
450
+ // One session id for the whole upload: bs keys the chunk scratch by it and
451
+ // assembles as soon as it has counted `tc` arrivals.
452
+ const sid = `${Date.now().toString(36)}-${Math.trunc(Math.random() * 1e9).toString(36)}`;
453
+ const title = opts?.title?.trim();
454
+ const titleQs = title ? `&title=${encodeURIComponent(title)}` : '';
455
+ const immutableQs = opts?.immutable ? '&immutable=1' : '';
456
+ for (let ci = 0; ci < total; ci++) {
457
+ const token = await signToken({ k: appKey(key), sid, ci, tc: total }, UPLOAD_TOKEN_TTL_SECONDS);
458
+ const slice = new Uint8Array(await blob
459
+ .slice(ci * chunkBytes, Math.min((ci + 1) * chunkBytes, blob.size))
460
+ .arrayBuffer());
461
+ const res = await fetch(`${baseUrl}/upload-chunk/${encodeKeyPath(appKey(key))}?token=${encodeURIComponent(token)}${titleQs}${immutableQs}`, {
462
+ method: 'PUT',
463
+ headers: mime ? { 'content-type': mime } : undefined,
464
+ body: slice,
465
+ });
466
+ if (!res.ok) {
467
+ throw new Error(`[binary-store] putLarge ${key} chunk ${ci + 1}/${total}: ${res.status}`);
468
+ }
469
+ }
470
+ forget(key); // see `put`
471
+ },
472
+ async get(key, opts) {
473
+ // 🔴 The negative memo short-circuits the BYTES too, and that is where most of
474
+ // the saving is: family drew a face by asking for bytes it had already been
475
+ // told were not there, hundreds of times a page. The positive memo cannot
476
+ // short-circuit here — we want the bytes, and only the store has them.
477
+ if (!opts?.fresh && knownAbsent(key))
478
+ return null;
479
+ countWireRead(key);
480
+ const res = await fetch(await internalMediaUrl(key));
481
+ if (res.status === 404) {
482
+ rememberAbsent(key);
483
+ return null;
484
+ }
485
+ if (!res.ok) {
486
+ // 🔴 NOT an absence. "The store could not be asked" and "the store does not
487
+ // have it" are different facts, and conflating them is the bug family met
488
+ // twice in one day — a 429 from a spent Cloudflare allowance rendering as a
489
+ // photograph that does not exist. Caching that would blank a page of faces
490
+ // for an hour, which is the one outcome this memo must never cause.
491
+ throw new Error(`[binary-store] get ${key}: ${res.status}`);
492
+ }
493
+ // A key we believed present that answers 404 is demoted above; one that
494
+ // answers bytes stays believed. See the memo header on why `put` is the
495
+ // other half of keeping a name-addressed key honest.
496
+ return new Uint8Array(await res.arrayBuffer());
497
+ },
498
+ async has(key, opts) {
499
+ return (await store.meta(key, opts)) !== null;
500
+ },
501
+ known(key) {
502
+ // Order matters: a lapsed absence is DROPPED by `knownAbsent`, so asking it
503
+ // first keeps this accessor from reporting an expiry the next real read would
504
+ // not honour. A positive memo has no expiry, so it needs no such care.
505
+ if (knownAbsent(key))
506
+ return 'absent';
507
+ return present.has(key) ? 'present' : 'unknown';
508
+ },
509
+ forgetMisses(prefix) {
510
+ if (prefix === undefined) {
511
+ const dropped = absentUntil.size;
512
+ absentUntil.clear();
513
+ return dropped;
514
+ }
515
+ let dropped = 0;
516
+ for (const key of [...absentUntil.keys()]) {
517
+ if (key.startsWith(prefix)) {
518
+ absentUntil.delete(key);
519
+ dropped++;
520
+ }
521
+ }
522
+ return dropped;
523
+ },
524
+ cacheStats() {
525
+ // Lapsed entries are dropped as they are met, so count only live ones —
526
+ // a stat that includes expired rows reads as a memo that never releases.
527
+ const at = now();
528
+ let absent = 0;
529
+ for (const until of absentUntil.values())
530
+ if (until > at)
531
+ absent++;
532
+ return { present: present.size, absent };
533
+ },
534
+ async fetchMedia(key, init) {
535
+ // A one-hour stable window, matching what apps hand to browsers: the token is part
536
+ // of the URL, so a fresh one per request would defeat every cache between here and
537
+ // the object — see MediaUrlOptions.stableWindowSeconds.
538
+ const url = await internalMediaUrl(key, { stableWindowSeconds: 60 * 60 });
539
+ return await fetch(url, {
540
+ method: init?.method ?? 'GET',
541
+ // 🔴 Only when the caller HAS one. `Range: undefined` is fine, but a literal
542
+ // empty string is a malformed header that some origins answer 416 to.
543
+ ...(init?.range ? { headers: { range: init.range } } : {}),
544
+ ...(init?.signal ? { signal: init.signal } : {}),
545
+ });
546
+ },
547
+ async meta(key, opts) {
548
+ if (!opts?.fresh) {
549
+ const memo = present.get(key);
550
+ if (memo)
551
+ return memo;
552
+ if (knownAbsent(key))
553
+ return null;
554
+ }
555
+ countWireRead(key);
556
+ const res = await fetch(await metaUrl(key));
557
+ if (res.status === 404) {
558
+ rememberAbsent(key);
559
+ return null;
560
+ }
561
+ // A throw leaves both memos untouched, deliberately — see `get`.
562
+ if (!res.ok)
563
+ throw new Error(`[binary-store] meta ${key}: ${res.status}`);
564
+ const body = (await res.json());
565
+ const meta = {
566
+ size: Number(body.size ?? 0),
567
+ mime: body.mime ?? null,
568
+ title: body.title ?? null,
569
+ checksum: body.checksum ?? null,
570
+ createdAt: body.createdAt,
571
+ updatedAt: body.updatedAt,
572
+ };
573
+ rememberPresent(key, meta);
574
+ return meta;
575
+ },
576
+ async stat(key, opts) {
577
+ // Prefer /meta: one index read on the server — no disk touch, no access-time
578
+ // bump, no body. It is the cheap answer and it is the one bs added for this.
579
+ //
580
+ // The fallback is NOT dead code, and it cannot be skipped on a null: a
581
+ // binary-server predating /meta answers 404 to /meta for an object it HAS, which
582
+ // by status alone is indistinguishable from "no such object". So a null is
583
+ // confirmed with the old Range probe, which every version supports. The extra
584
+ // round trip is paid only when the answer is "absent" or the server is old.
585
+ // 🔴 The MEMO is consulted for the whole of `stat`, not just for its `meta`
586
+ // half. Otherwise a key confirmed absent still paid the Range probe on every
587
+ // single call — which is most of what an absent key costs, and the reason
588
+ // this memo exists at all.
589
+ if (!opts?.fresh && knownAbsent(key))
590
+ return null;
591
+ try {
592
+ const m = await store.meta(key, opts);
593
+ if (m)
594
+ return { size: m.size };
595
+ }
596
+ catch {
597
+ // A transport/5xx failure — the probe below is the second opinion.
598
+ }
599
+ countWireRead(key);
600
+ const res = await fetch(await internalMediaUrl(key), { headers: { Range: 'bytes=0-0' } });
601
+ if (res.status === 404) {
602
+ rememberAbsent(key);
603
+ return null;
604
+ }
605
+ if (!res.ok)
606
+ throw new Error(`[binary-store] stat ${key}: ${res.status}`);
607
+ // 🔴 The object IS here and `/meta` said 404 — an old binary-server, which is
608
+ // the case this fallback exists for. `meta` recorded an absence on that 404 and
609
+ // it is WRONG, so it is dropped rather than left to blank the key for an hour.
610
+ // Not promoted to a positive memo either: a Range probe yields a size and
611
+ // nothing else, and a fabricated `mime: null` would be `meta()` inventing an
612
+ // answer it never received.
613
+ forget(key);
614
+ const contentRange = res.headers.get('content-range');
615
+ const totalBytes = contentRange
616
+ ? Number(contentRange.split('/')[1])
617
+ : Number(res.headers.get('content-length'));
618
+ return Number.isFinite(totalBytes) ? { size: totalBytes } : null;
619
+ },
620
+ async remove(key) {
621
+ // Sign a per-op, path-scoped delete token: bs requires it AND the internal secret
622
+ // (owner ruling #10). `internalHeaders()` throws first if no secret is configured.
623
+ const headers = internalHeaders();
624
+ const token = await signToken({ k: appKey(key), op: 'delete' }, DELETE_TOKEN_TTL_SECONDS);
625
+ const res = await fetch(`${baseUrl}/media/${encodeKeyPath(appKey(key))}?token=${encodeURIComponent(token)}`, { method: 'DELETE', headers });
626
+ if (!res.ok && res.status !== 404) {
627
+ throw new Error(`[binary-store] remove ${key}: ${res.status}`);
628
+ }
629
+ // Gone, and we know it — a positive memo that survived a delete would hand out
630
+ // a URL to a 404 for the life of the process.
631
+ rememberAbsent(key);
632
+ },
633
+ async removePrefix(prefix) {
634
+ // The token's exact-key claim is the container's own path; bs derives the tree from it
635
+ // and the `?container=1` flag. Same two-barrier gate as remove().
636
+ const headers = internalHeaders();
637
+ const token = await signToken({ k: appKey(prefix), op: 'delete' }, DELETE_TOKEN_TTL_SECONDS);
638
+ const res = await fetch(`${baseUrl}/media/${encodeKeyPath(appKey(prefix))}?container=1&token=${encodeURIComponent(token)}`, { method: 'DELETE', headers });
639
+ if (!res.ok && res.status !== 404) {
640
+ throw new Error(`[binary-store] removePrefix ${prefix}: ${res.status}`);
641
+ }
642
+ // A whole tree went; every memo under it is void. NOT recorded as absences —
643
+ // the keys are not enumerable from here, and a container is routinely refilled.
644
+ for (const key of [...present.keys()])
645
+ if (key.startsWith(prefix))
646
+ forget(key);
647
+ for (const key of [...absentUntil.keys()])
648
+ if (key.startsWith(prefix))
649
+ forget(key);
650
+ },
651
+ };
652
+ return store;
653
+ }
654
+ /**
655
+ * Which binary-server TENANT this process is — the app's own key, unless the environment
656
+ * names another.
657
+ *
658
+ * 🔴 It has to be a variable, and 2026-08-21 is the day that stopped being theoretical.
659
+ * A tenant is TWO facts that must agree: the key a request is SIGNED with, and the key the
660
+ * request PATH starts with (`authorize()` in binary-server refuses when
661
+ * `path.split("/")[0] !== token.app_id`). Apps supplied the second as a literal — `const
662
+ * TENANT = "collections"` — while `FILE_TOKEN_ISSUER`/`FILE_TOKEN_PRIVATE_KEY` came from
663
+ * the environment. That is fine on production, where the two happen to match, and it makes
664
+ * an ephemeral STAGE structurally unable to store a byte: `stage up` mints it a real
665
+ * `collections-stage` tenant and hands it that keypair, and every upload then signs as
666
+ * `collections-stage` while addressing `collections/…` and comes back
667
+ * `[binary-store] put file/<sha>: 403`. The stage looked like a working app with an empty
668
+ * gallery, which is exactly what an empty stage is supposed to look like.
669
+ *
670
+ * Reading it here means an app opts in by CALLING this instead of writing a literal, and
671
+ * `BINARY_STORE_TENANT` is already inside an app's stage-env shared-store denylist
672
+ * (`/^BINARY_STORE_(?!.*URL$)/`) — so a stage cannot INHERIT production's tenant, only be
673
+ * given its own. The fallback is the app's key, so an app that never sets it is unchanged.
674
+ *
675
+ * 🔴 **A BLANK tenant now throws, and that is the whole point of the check
676
+ * (2026-08-23).** `undefined` is a perfectly good JavaScript string once it is
677
+ * template-interpolated, so a caller that forgot the argument signed a token for
678
+ * `undefined/<key>` and addressed `PUT /upload/undefined/<key>` — at which point
679
+ * binary-server's `authorize()` refuses it correctly and answers a bare
680
+ * `{"error":"forbidden"}`. That reads as a broken CREDENTIAL, and it was filed as one
681
+ * (*"family.env's FILE_TOKEN_PRIVATE_KEY does not authorize against the family tenant"*).
682
+ * The keypair was correct the whole time and a Mac-side upload works; what was missing was
683
+ * the tenant id. bs cannot tell the two apart — it sees a token for a tenant it does not
684
+ * have — so the check has to live on this side of the wire, where the mistake is legible.
685
+ */
686
+ export function binaryStoreTenant(appId, env = process.env) {
687
+ const tenant = env.BINARY_STORE_TENANT?.trim() || appId?.trim();
688
+ if (!tenant || tenant === 'undefined' || tenant === 'null') {
689
+ throw new Error("[binary-store] no tenant id — pass the app's key as the first argument " +
690
+ '(`readBinaryStoreEnv("family")` / `createBinaryStore({ appId: "family" })`), ' +
691
+ 'or set BINARY_STORE_TENANT. Without one every upload signs for ' +
692
+ `"${tenant ?? ''}/<key>" and binary-server answers 403 forbidden, which reads ` +
693
+ 'as a bad credential rather than as a missing argument.');
694
+ }
695
+ return tenant;
696
+ }
697
+ /**
698
+ * The tenant this process's binary store resolved, or `null` when it has no store.
699
+ *
700
+ * The value an app's `mediaTenant` option wants, and the reason it exists as a named
701
+ * function rather than each app writing `readBinaryStoreEnv(x)?.appId`:
702
+ *
703
+ * 🔴 **`null` and a thrown error are different answers and both are correct.**
704
+ * {@link binaryStoreTenant} throws when it cannot name a tenant, which is right at an upload
705
+ * site — signing for `"undefined/<key>"` earns a bare 403 that reads as a bad credential. It is
706
+ * wrong on `/healthz`, where the same throw would turn "this dev shell has no store" into a
707
+ * 500 and take the app's health probe down with it. So this asks the same question through the
708
+ * same resolution and answers `null` for the store-less case, which the health handler then
709
+ * reports as an explicit "no store" rather than as silence.
710
+ *
711
+ * Pass the app's OWN tenant key — the constant its store is built from (`LIFE_BINARY_TENANT`,
712
+ * `STUDIO_BINARY_TENANT`, …), never the app's display name. They are the same string for most
713
+ * apps and that is precisely why the difference goes unnoticed when it is not.
714
+ */
715
+ export function resolvedMediaTenant(appId, env = process.env) {
716
+ return readBinaryStoreEnv(appId, env)?.appId ?? null;
717
+ }
718
+ /**
719
+ * The standard env surface every tenant's secrets file carries
720
+ * (`$FORGE_STATE/secrets/<app>.env`, written at bs registration):
721
+ * `BINARY_SERVER_URL`, `FILE_TOKEN_ISSUER`, `FILE_TOKEN_PRIVATE_KEY`, and
722
+ * optionally `BINARY_SERVER_INTERNAL_SECRET`. Returns `null` unless the three
723
+ * required vars are all present — callers fall back to their local backend.
724
+ */
725
+ export function readBinaryStoreEnv(appId, env = process.env) {
726
+ const baseUrl = env.BINARY_SERVER_URL?.trim();
727
+ const issuer = env.FILE_TOKEN_ISSUER?.trim();
728
+ const privateKey = env.FILE_TOKEN_PRIVATE_KEY?.trim();
729
+ if (!baseUrl || !issuer || !privateKey)
730
+ return null;
731
+ return {
732
+ baseUrl,
733
+ appId: binaryStoreTenant(appId, env),
734
+ issuer,
735
+ privateKey,
736
+ internalSecret: env.BINARY_SERVER_INTERNAL_SECRET?.trim() || undefined,
737
+ internalBaseUrl: env.BINARY_SERVER_INTERNAL_URL?.trim() || undefined,
738
+ };
739
+ }