@phnx-labs/artifacts-cli 0.4.7 → 0.5.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 (122) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +125 -10
  3. package/dist/cli.d.ts +1 -6
  4. package/dist/cli.js +93 -85
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/auth.d.ts +5 -0
  7. package/dist/commands/auth.js +112 -0
  8. package/dist/commands/auth.js.map +1 -0
  9. package/dist/commands/favorite.d.ts +9 -0
  10. package/dist/commands/favorite.js +59 -0
  11. package/dist/commands/favorite.js.map +1 -0
  12. package/dist/commands/share.d.ts +297 -14
  13. package/dist/commands/share.js +1351 -71
  14. package/dist/commands/share.js.map +1 -1
  15. package/dist/lib/browser-detect.d.ts +28 -0
  16. package/dist/lib/browser-detect.js +126 -0
  17. package/dist/lib/browser-detect.js.map +1 -0
  18. package/dist/lib/config.d.ts +14 -0
  19. package/dist/lib/config.js +8 -0
  20. package/dist/lib/config.js.map +1 -1
  21. package/dist/lib/embedded-html.d.ts +1 -1
  22. package/dist/lib/embedded-html.js +12 -0
  23. package/dist/lib/embedded-html.js.map +1 -1
  24. package/dist/lib/excerpt.d.ts +48 -0
  25. package/dist/lib/excerpt.js +167 -0
  26. package/dist/lib/excerpt.js.map +1 -0
  27. package/dist/lib/favorites.d.ts +73 -0
  28. package/dist/lib/favorites.js +180 -0
  29. package/dist/lib/favorites.js.map +1 -0
  30. package/dist/lib/format.d.ts +2 -0
  31. package/dist/lib/format.js +14 -0
  32. package/dist/lib/format.js.map +1 -0
  33. package/dist/lib/github.d.ts +14 -0
  34. package/dist/lib/github.js +36 -0
  35. package/dist/lib/github.js.map +1 -0
  36. package/dist/lib/header-actions.d.ts +44 -0
  37. package/dist/lib/header-actions.js +181 -0
  38. package/dist/lib/header-actions.js.map +1 -0
  39. package/dist/lib/identity/client.d.ts +49 -0
  40. package/dist/lib/identity/client.js +97 -0
  41. package/dist/lib/identity/client.js.map +1 -0
  42. package/dist/lib/identity/index.d.ts +60 -0
  43. package/dist/lib/identity/index.js +69 -0
  44. package/dist/lib/identity/index.js.map +1 -0
  45. package/dist/lib/link-previews.d.ts +67 -0
  46. package/dist/lib/link-previews.js +427 -0
  47. package/dist/lib/link-previews.js.map +1 -0
  48. package/dist/lib/links.d.ts +2 -0
  49. package/dist/lib/links.js +21 -2
  50. package/dist/lib/links.js.map +1 -1
  51. package/dist/lib/math.d.ts +31 -0
  52. package/dist/lib/math.js +122 -0
  53. package/dist/lib/math.js.map +1 -0
  54. package/dist/lib/metadata-menu.d.ts +15 -0
  55. package/dist/lib/metadata-menu.js +23 -0
  56. package/dist/lib/metadata-menu.js.map +1 -1
  57. package/dist/lib/open.d.ts +6 -0
  58. package/dist/lib/open.js +54 -0
  59. package/dist/lib/open.js.map +1 -0
  60. package/dist/lib/render.d.ts +3 -0
  61. package/dist/lib/render.js +158 -35
  62. package/dist/lib/render.js.map +1 -1
  63. package/dist/lib/revisions.d.ts +17 -0
  64. package/dist/lib/revisions.js +6 -1
  65. package/dist/lib/revisions.js.map +1 -1
  66. package/dist/lib/share/analytics.d.ts +13 -0
  67. package/dist/lib/share/analytics.js +46 -0
  68. package/dist/lib/share/analytics.js.map +1 -0
  69. package/dist/lib/share/backend.d.ts +105 -0
  70. package/dist/lib/share/backend.js +161 -0
  71. package/dist/lib/share/backend.js.map +1 -0
  72. package/dist/lib/share/capture.d.ts +31 -0
  73. package/dist/lib/share/capture.js +175 -0
  74. package/dist/lib/share/capture.js.map +1 -0
  75. package/dist/lib/share/config.d.ts +82 -0
  76. package/dist/lib/share/config.js +181 -0
  77. package/dist/lib/share/config.js.map +1 -0
  78. package/dist/lib/share/delete.d.ts +122 -0
  79. package/dist/lib/share/delete.js +174 -0
  80. package/dist/lib/share/delete.js.map +1 -0
  81. package/dist/lib/share/html.d.ts +22 -0
  82. package/dist/lib/share/html.js +89 -0
  83. package/dist/lib/share/html.js.map +1 -0
  84. package/dist/lib/share/http-error.d.ts +52 -0
  85. package/dist/lib/share/http-error.js +66 -0
  86. package/dist/lib/share/http-error.js.map +1 -0
  87. package/dist/lib/share/og.d.ts +25 -0
  88. package/dist/lib/share/og.js +85 -0
  89. package/dist/lib/share/og.js.map +1 -0
  90. package/dist/lib/share/provision.d.ts +99 -0
  91. package/dist/lib/share/provision.js +271 -0
  92. package/dist/lib/share/provision.js.map +1 -0
  93. package/dist/lib/share/publish.d.ts +393 -0
  94. package/dist/lib/share/publish.js +829 -0
  95. package/dist/lib/share/publish.js.map +1 -0
  96. package/dist/lib/share/qr.d.ts +36 -0
  97. package/dist/lib/share/qr.js +102 -0
  98. package/dist/lib/share/qr.js.map +1 -0
  99. package/dist/lib/share/storage-policy.d.ts +9 -0
  100. package/dist/lib/share/storage-policy.js +43 -0
  101. package/dist/lib/share/storage-policy.js.map +1 -0
  102. package/dist/lib/share/visibility.d.ts +92 -0
  103. package/dist/lib/share/visibility.js +108 -0
  104. package/dist/lib/share/visibility.js.map +1 -0
  105. package/dist/lib/share/worker-template.d.ts +29 -0
  106. package/dist/lib/share/worker-template.js +2154 -0
  107. package/dist/lib/share/worker-template.js.map +1 -0
  108. package/dist/lib/status-list.d.ts +49 -0
  109. package/dist/lib/status-list.js +153 -0
  110. package/dist/lib/status-list.js.map +1 -0
  111. package/dist/lib/validate.js +122 -8
  112. package/dist/lib/validate.js.map +1 -1
  113. package/package.json +12 -3
  114. package/dist/lib/share-provision.d.ts +0 -31
  115. package/dist/lib/share-provision.js +0 -83
  116. package/dist/lib/share-provision.js.map +0 -1
  117. package/dist/lib/share-worker.d.ts +0 -1
  118. package/dist/lib/share-worker.js +0 -66
  119. package/dist/lib/share-worker.js.map +0 -1
  120. package/dist/lib/share.d.ts +0 -39
  121. package/dist/lib/share.js +0 -159
  122. package/dist/lib/share.js.map +0 -1
@@ -0,0 +1,2154 @@
1
+ import { buildSync } from 'esbuild';
2
+ import { dirname } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ let bundledWorker;
5
+ let nodeWorkerScript;
6
+ /** Bundle the Worker renderer into an ES module plus workerd-compiled WASM modules. */
7
+ export function renderWorkerBundle() {
8
+ if (bundledWorker)
9
+ return bundledWorker;
10
+ const result = buildSync({
11
+ stdin: {
12
+ contents: renderWorkerSource(),
13
+ loader: 'js',
14
+ resolveDir: dirname(fileURLToPath(import.meta.url)),
15
+ sourcefile: 'agents-share-worker.js',
16
+ },
17
+ bundle: true,
18
+ format: 'esm',
19
+ platform: 'browser',
20
+ target: 'es2022',
21
+ write: false,
22
+ outdir: 'worker-bundle',
23
+ assetNames: '[name]-[hash]',
24
+ minify: true,
25
+ // Fonts are plain data and can live in JavaScript. WASM must remain a
26
+ // compiled module: workerd deliberately forbids runtime code generation,
27
+ // so esbuild's `binary` loader produces a bundle that works in Node but
28
+ // throws "Wasm code generation disallowed by embedder" in Cloudflare.
29
+ loader: { '.wasm': 'copy', '.woff': 'binary' },
30
+ });
31
+ const script = result.outputFiles.find((output) => output.path.endsWith('.js'));
32
+ if (!script)
33
+ throw new Error('Worker bundling produced no JavaScript output.');
34
+ const modules = result.outputFiles
35
+ .filter((output) => output.path.endsWith('.wasm'))
36
+ .map((output) => ({
37
+ name: output.path.split('/').pop(),
38
+ contentType: 'application/wasm',
39
+ contents: new Uint8Array(output.contents),
40
+ }));
41
+ if (modules.length !== 2) {
42
+ throw new Error(`Worker bundling produced ${modules.length} WASM modules; expected yoga and resvg.`);
43
+ }
44
+ bundledWorker = { script: script.text, modules };
45
+ return bundledWorker;
46
+ }
47
+ /** Single-file representation for direct Node tests, which cannot import compiled WASM modules. */
48
+ export function renderWorkerScript() {
49
+ if (nodeWorkerScript)
50
+ return nodeWorkerScript;
51
+ const result = buildSync({
52
+ stdin: {
53
+ contents: renderWorkerSource(),
54
+ loader: 'js',
55
+ resolveDir: dirname(fileURLToPath(import.meta.url)),
56
+ sourcefile: 'agents-share-worker.js',
57
+ },
58
+ bundle: true,
59
+ format: 'esm',
60
+ platform: 'browser',
61
+ target: 'es2022',
62
+ write: false,
63
+ minify: true,
64
+ loader: { '.wasm': 'binary', '.woff': 'binary' },
65
+ });
66
+ const output = result.outputFiles[0];
67
+ if (!output)
68
+ throw new Error('Worker test bundling produced no JavaScript output.');
69
+ nodeWorkerScript = output.text;
70
+ return nodeWorkerScript;
71
+ }
72
+ /** Unbundled Worker source. Kept separate so esbuild can resolve npm modules. */
73
+ export function renderWorkerSource() {
74
+ return `import { hasUnlimitedStorage } from './storage-policy.js';
75
+ import satori, { init as initSatori } from 'satori/wasm';
76
+ import initYoga from 'yoga-wasm-web';
77
+ import { Resvg, initWasm as initResvg } from '@resvg/resvg-wasm';
78
+ import yogaWasm from 'yoga-wasm-web/dist/yoga.wasm';
79
+ import resvgWasm from '@resvg/resvg-wasm/index_bg.wasm';
80
+ import interRegular from '@fontsource/inter/files/inter-latin-400-normal.woff';
81
+ import interBold from '@fontsource/inter/files/inter-latin-700-normal.woff';
82
+ import jetbrainsMono from '@fontsource/jetbrains-mono/files/jetbrains-mono-latin-600-normal.woff';
83
+
84
+ // GENERATED by agents-cli agents share setup — do not edit here; edit
85
+ // src/lib/share/worker-template.ts and re-run setup.
86
+ export const hooks = {
87
+ verifyPhoenixToken: defaultVerifyPhoenixToken,
88
+ renderOgCard: renderOgCard,
89
+ };
90
+
91
+ export default {
92
+ async fetch(request, env, ctx) {
93
+ const url = new URL(request.url);
94
+ const path = decodeURIComponent(url.pathname.replace(/^\\/+/, ''));
95
+
96
+ if (!path) {
97
+ return new Response('agents share — POST is not it; PUT /<username>/<slug> to publish, GET /<username>/<slug> to view.', {
98
+ status: 200, headers: { 'content-type': 'text/plain; charset=utf-8' },
99
+ });
100
+ }
101
+
102
+ const firstSeg = path.split('/').filter(Boolean)[0] || '';
103
+ if ((request.method === 'GET' || request.method === 'HEAD') && firstSeg.startsWith('__')) {
104
+ return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
105
+ }
106
+
107
+ // POST /__ticket — mint a short-lived, single-navigation login ticket for the
108
+ // authenticated owner (PHNX-3370). The CLI (which holds the Phoenix bearer)
109
+ // calls this, then opens the owner's page with ?phoenix_ticket=<t> so the
110
+ // browser trades it for the __share cookie and the inline visibility control
111
+ // goes live. The ticket is SELF-signed with the Worker's own HMAC secret — no
112
+ // external ticket service — and carries the SAME identity authorizeWrite
113
+ // already proved, so it grants nothing the caller didn't already have.
114
+ if (request.method === 'POST' && firstSeg === '__ticket') {
115
+ const auth = await authorizeWrite(request, env);
116
+ if (auth.error) return auth.error;
117
+ const ticket = await signSelfTicket({ userId: auth.owner, email: auth.email || '' }, env);
118
+ if (!ticket) return json({ error: 'ticket minting is not configured' }, 501);
119
+ return json({ ticket: ticket }, 200);
120
+ }
121
+
122
+ if (request.method === 'PUT') {
123
+ const auth = await authorizeWrite(request, env);
124
+ if (auth.error) return auth.error;
125
+ const vis = normalizeVisibility(request.headers.get('x-share-visibility'));
126
+ if (vis.error) return vis.error;
127
+ const visibility = vis.value;
128
+ if (visibility === 'me' || visibility === 'org') {
129
+ const phoenixBase = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
130
+ if (auth.kind !== 'phoenix' || !phoenixBase) {
131
+ return json({ error: 'visibility me/org requires Phoenix identity' }, 400);
132
+ }
133
+ if (visibility === 'org') {
134
+ const domain = emailDomain(auth.email);
135
+ if (!domain) return json({ error: 'org visibility requires a verified email domain' }, 400);
136
+ if (PUBLIC_INBOX_DOMAINS.indexOf(domain) !== -1) {
137
+ return json({ error: 'org visibility cannot use a public email domain', domain: domain }, 400);
138
+ }
139
+ }
140
+ }
141
+ // Token-gated read auth (PHNX-3654). A 'private' page is served only to a
142
+ // request carrying the matching viewer key; we store just its SHA-256 hash
143
+ // so the secret never lands in R2 metadata. Any write principal (Phoenix or
144
+ // BYO WRITE_TOKEN) may publish 'private' — the gate is the token, not an
145
+ // identity, unlike me/org. The token is mandatory: a private page with no
146
+ // stored hash fails closed on read, so refuse the write instead.
147
+ let viewerTokenHash = '';
148
+ if (visibility === 'private') {
149
+ const rawToken = request.headers.get('x-share-viewer-token') || '';
150
+ if (!rawToken) return json({ error: 'visibility private requires a viewer token' }, 400);
151
+ viewerTokenHash = await sha256Hex(rawToken);
152
+ }
153
+ const segments = path.split('/').filter(Boolean);
154
+ if (auth.kind === 'phoenix') {
155
+ // The caller's handle is normally derived from the email local-part. An
156
+ // explicit x-share-handle (the CLI's --handle, PHNX-3547) lets a Phoenix
157
+ // user choose a DIFFERENT free handle — the escape hatch when their
158
+ // derived handle is taken or they want a vanity namespace. Sanitized to
159
+ // the same [a-z0-9-] shape; claim rules below bind it first-writer-writes,
160
+ // exactly like a derived handle.
161
+ const requestedRaw = request.headers.get('x-share-handle') || '';
162
+ const requested = sanitizeNamespace(requestedRaw);
163
+ if (requestedRaw && (!requested || requested.length > 63)) {
164
+ return json({ error: 'invalid handle', handle: requestedRaw }, 400);
165
+ }
166
+ const expected = requested || phoenixHandle(auth);
167
+ if (!expected || segments[0] !== expected) {
168
+ return json({ error: 'namespace mismatch', owner: expected }, 403);
169
+ }
170
+ const claimed = await claimHandle(env.BUCKET, expected, auth.owner, auth.email || '');
171
+ if (claimed.error) return claimed.error;
172
+ }
173
+ const expiresAt = request.headers.get('x-share-expires-at') || '';
174
+ // 'unlisted' hides the page from the public gallery + JSON listing while
175
+ // keeping the direct URL world-readable (capability URL, not secret).
176
+ // me/org are also hidden from gallery/listing; GET is identity-gated
177
+ // and always sends X-Robots-Tag: noindex (same as unlisted).
178
+ const contentType = request.headers.get('content-type') || 'text/html; charset=utf-8';
179
+ // Provenance (RUSH-2683): captured client-side from the exec env/git/clock,
180
+ // never invented here — a header is simply absent when the CLI had nothing
181
+ // to say. --meta entries ride one JSON header; reserved keys are stripped
182
+ // from that JSON UNCONDITIONALLY (not just overwritten when a provenance
183
+ // header happens to be present) so a same-named x-share-meta entry can
184
+ // never smuggle through on a publish that carries no agent/session/host/
185
+ // repo/date at all — e.g. a human publishing outside an agent session, or
186
+ // outside a git checkout.
187
+ // Full-Unicode headers (PHNX-2786): the CLI always sends the latin1-safe
188
+ // x-share-<field> (what a pre-Unicode Worker read), and when the fold was
189
+ // lossy ALSO a percent-encoded x-share-<field>-u companion plus an
190
+ // x-share-encoding: percent opt-in. Prefer the decoded companion when the
191
+ // opt-in is present, so a Japanese/emoji title/label/--meta renders in full
192
+ // instead of (unnamed) or a dropped glyph; a malformed companion falls
193
+ // back to the folded value rather than failing the publish.
194
+ const usePercent = (request.headers.get('x-share-encoding') || '') === 'percent';
195
+ const readText = (name) => {
196
+ const folded = request.headers.get('x-share-' + name) || '';
197
+ if (usePercent) {
198
+ const encoded = request.headers.get('x-share-' + name + '-u');
199
+ if (encoded) {
200
+ try {
201
+ return decodeURIComponent(encoded);
202
+ } catch (e) {
203
+ return folded;
204
+ }
205
+ }
206
+ }
207
+ return folded;
208
+ };
209
+ const agent = readText('agent');
210
+ const session = readText('session');
211
+ const host = readText('host');
212
+ const repo = readText('repo');
213
+ const date = readText('date');
214
+ const avatar = readText('avatar');
215
+ const label = readText('label');
216
+ const ogTitle = readText('og-title');
217
+ const ogDescription = readText('og-description');
218
+ const labelSource = request.headers.get('x-share-label-source') || '';
219
+ let extraMeta = {};
220
+ // The -u meta companion carries the whole raw object percent-encoded, so a
221
+ // single decode+parse recovers full-Unicode keys and values; fall back to
222
+ // the per-value-folded x-share-meta when it is absent or malformed.
223
+ const metaEncoded = usePercent ? request.headers.get('x-share-meta-u') : null;
224
+ if (metaEncoded) {
225
+ try {
226
+ const parsed = JSON.parse(decodeURIComponent(metaEncoded));
227
+ if (parsed && typeof parsed === 'object') extraMeta = parsed;
228
+ } catch (e) {
229
+ // malformed unicode meta companion — fall through to the folded header
230
+ }
231
+ }
232
+ if (!Object.keys(extraMeta).length) {
233
+ const metaHeader = request.headers.get('x-share-meta');
234
+ if (metaHeader) {
235
+ try {
236
+ const parsed = JSON.parse(metaHeader);
237
+ if (parsed && typeof parsed === 'object') extraMeta = parsed;
238
+ } catch {
239
+ // malformed --meta header — ignore rather than fail the whole publish
240
+ }
241
+ }
242
+ }
243
+ const customMetadata = { ...extraMeta };
244
+ // Strip every reserved key UNCONDITIONALLY before re-applying the real
245
+ // provenance below — an if(value)-guarded overwrite alone leaves a
246
+ // same-named --meta entry in place whenever the real header is absent.
247
+ for (const reservedKey of RESERVED_METADATA_KEYS) {
248
+ delete customMetadata[reservedKey];
249
+ }
250
+ if (expiresAt) customMetadata['expires-at'] = expiresAt;
251
+ customMetadata['visibility'] = visibility;
252
+ if (viewerTokenHash) customMetadata['viewer-token-hash'] = viewerTokenHash;
253
+ const owner =
254
+ auth.kind === 'phoenix'
255
+ ? auth.owner
256
+ : (env.SHARE_NAMESPACE || segments[0] || 'byo');
257
+ if (owner) customMetadata['owner'] = owner;
258
+ if (visibility === 'org') customMetadata['org_domain'] = emailDomain(auth.email);
259
+ if (agent) customMetadata['agent'] = agent;
260
+ if (session) customMetadata['session'] = session;
261
+ if (host) customMetadata['host'] = host;
262
+ if (repo) customMetadata['repo'] = repo;
263
+ if (date) customMetadata['date'] = date;
264
+ if (avatar) customMetadata['avatar'] = avatar;
265
+ if (label) customMetadata['label'] = label;
266
+ if (labelSource) customMetadata['label-source'] = labelSource;
267
+ if (ogTitle) customMetadata['og-title'] = ogTitle;
268
+ if (ogDescription) customMetadata['og-description'] = ogDescription;
269
+
270
+ // Revision retention (RUSH-2683): R2 has no native object versioning, so a
271
+ // republish over an EXISTING key first copies the current object to
272
+ // <key>/rev-<ts>-<rand> before the canonical key is overwritten. Default
273
+ // keep-all; --no-revision (x-share-no-revision) skips it. The random
274
+ // suffix guards against two rapid overwrites of the same slug colliding on
275
+ // the millisecond, and against a slug whose canonical key already sits 3+
276
+ // segments deep (an unsupported shape outside the CLI) landing on the same
277
+ // literal revision key.
278
+ const noRevision = !!request.headers.get('x-share-no-revision');
279
+ // PHNX-3542: per-user storage quota + object count + per-file size cap +
280
+ // publish rate limit, enforced ONLY for a managed Phoenix identity. A BYO
281
+ // WRITE_TOKEN publish writes to the operator's OWN bucket at their own
282
+ // cost, so it skips all four — a deliberate, documented policy, NOT a
283
+ // silent no-op.
284
+ //
285
+ // Enforcement measures the REAL request body, never a client-declared size.
286
+ // A spoofed-low content-length must NOT (a) slip an oversized body past the
287
+ // per-file cap, (b) let real bytes exceed the total quota, or — most
288
+ // dangerously — (c) reach the destructive revision-copy + canonical
289
+ // overwrite before the size is known and DESTROY the existing page. So for a
290
+ // Phoenix write we buffer the body bounded by the plan's per-file cap and
291
+ // reject on the REAL size BEFORE any write; only then do we copy the
292
+ // revision and store the buffered bytes. BYO streams unbuffered (uncapped,
293
+ // its own bucket) — which also means a BYO body cannot be re-read for a
294
+ // retry, so BYO gets a single conditional attempt below.
295
+ let putBody = request.body;
296
+ let realBytes = 0;
297
+ if (auth.kind === 'phoenix') {
298
+ const limits = planLimits((await readUsage(env, auth.owner)).usage.plan);
299
+ // Fast-reject an HONEST oversized content-length without reading the body.
300
+ // A dishonest (absent or lied-low) length falls through to the bounded
301
+ // read below, which measures the truth.
302
+ const declaredLen = parseInt(request.headers.get('content-length') || '', 10);
303
+ if (Number.isFinite(declaredLen) && declaredLen > limits.maxFileBytes) {
304
+ return json({ error: 'file too large: max ' + limits.maxFileBytes + ' bytes', maxBytes: limits.maxFileBytes, gotBytes: declaredLen }, 413);
305
+ }
306
+ // readBodyBounded aborts the moment it passes the cap, so a chunked/
307
+ // streaming body can never buffer more than the cap (+ one chunk).
308
+ const read = await readBodyBounded(request, limits.maxFileBytes);
309
+ if (read.oversize) {
310
+ return json({ error: 'file too large: max ' + limits.maxFileBytes + ' bytes', maxBytes: limits.maxFileBytes, gotBytes: read.size }, 413);
311
+ }
312
+ realBytes = read.size;
313
+ putBody = read.bytes;
314
+ }
315
+
316
+ // Revision retention + quota charge + canonical write as a BOUNDED
317
+ // compare-and-swap loop (PHNX-3547). The old code read the current object,
318
+ // archived it, then overwrote the canonical key UNCONDITIONALLY: two
319
+ // concurrent republishers both archived the same old version and the
320
+ // loser's new body ended up neither canonical nor retained — silently
321
+ // discarded. R2 has no transactions, so each attempt re-reads the canonical
322
+ // object, archives it as a revision, and overwrites ONLY while the etag
323
+ // still matches the read (onlyIf.etagMatches — the same CAS primitive the
324
+ // PATCH path at :513 and the usage ledger already rely on; R2 returns null
325
+ // on the mismatch instead of storing). A conflicted attempt therefore loses
326
+ // nothing: it re-reads the winner's body, archives THAT as the revision on
327
+ // the next attempt, and lands its own body canonical — both writers survive.
328
+ // Phoenix bytes are buffered above, so retrying is safe; the rate counter
329
+ // and object count advance once (attempt 0) and a conflicted re-charge only
330
+ // bills the growth beyond what this request already paid. A BYO stream is
331
+ // consumed by the first attempt, so it gets one conditional try and a 409
332
+ // asking the caller to retry the whole publish.
333
+ const MAX_PUT_ATTEMPTS = 3;
334
+ let chargedAlready = 0;
335
+ let chargedNewCanonical = false;
336
+ let putResult = null;
337
+ for (let attempt = 0; attempt < MAX_PUT_ATTEMPTS; attempt++) {
338
+ // The current object is needed for BOTH the revision copy and the charge
339
+ // math, and even a first/no-revision publish must read before its
340
+ // conditional write so two concurrent creates cannot both report 200.
341
+ const existing = await env.BUCKET.get(path);
342
+ if (auth.kind === 'phoenix') {
343
+ const existingSize = existing && typeof existing.size === 'number' ? existing.size : 0;
344
+ const newCanonical = !existing;
345
+ // Keeping a revision retains the old canonical bytes AND adds the new
346
+ // ones, so storage grows by the full new size. A no-revision or first
347
+ // publish grows by new minus the bytes it replaces (may be negative on a
348
+ // shrink; the ledger clamps at >= 0).
349
+ const charge = (!noRevision && existing) ? realBytes : realBytes - existingSize;
350
+ // Conflict retry: only the growth beyond what this request already
351
+ // paid. Exact accounting under a lost race is impossible without
352
+ // reconciling the bucket; this stays the ledger's documented
353
+ // best-effort, same as its >= 0 clamp.
354
+ const bill = Math.max(0, charge - chargedAlready);
355
+ chargedAlready += bill;
356
+ const chargeNewCanonical = newCanonical && attempt === 0;
357
+ const charged = await chargeShareWrite(env, auth, {
358
+ charge: bill,
359
+ newCanonical: chargeNewCanonical,
360
+ fileBytes: realBytes,
361
+ countRate: attempt === 0,
362
+ });
363
+ if (charged.error) return charged.error; // rejected BEFORE any destructive write
364
+ if (chargeNewCanonical) chargedNewCanonical = true;
365
+ }
366
+
367
+ if (!noRevision && existing) {
368
+ const existingHeaders = new Headers();
369
+ if (typeof existing.writeHttpMetadata === 'function') existing.writeHttpMetadata(existingHeaders);
370
+ const existingContentType = existingHeaders.get('content-type');
371
+ const revKey = path + '/rev-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
372
+ await env.BUCKET.put(revKey, existing.body, {
373
+ httpMetadata: existingContentType ? { contentType: existingContentType } : undefined,
374
+ customMetadata: existing.customMetadata || {},
375
+ });
376
+ }
377
+
378
+ const putOpts = { httpMetadata: { contentType }, customMetadata };
379
+ // Existing objects use the bare R2Object#etag for CAS; missing objects
380
+ // use R2's create-only condition so a concurrent first writer wins loud.
381
+ if (existing && existing.etag) putOpts.onlyIf = { etagMatches: existing.etag };
382
+ else putOpts.onlyIf = { etagDoesNotMatch: '*' };
383
+ putResult = await env.BUCKET.put(path, putBody, putOpts);
384
+ if (putResult !== null) break;
385
+ // A failed create-only condition means another first publisher won.
386
+ // Do not turn that loser into a republish: the caller must see the race.
387
+ if (!existing) break;
388
+ if (auth.kind !== 'phoenix') break; // BYO stream is spent — cannot retry
389
+ }
390
+ if (putResult === null) {
391
+ if (auth.kind === 'phoenix') {
392
+ await refundShareWrite(env, auth.owner, {
393
+ refund: chargedAlready,
394
+ freeCanonical: chargedNewCanonical,
395
+ });
396
+ }
397
+ return json({ error: 'publish conflict: another write landed first, retry the publish' }, 409);
398
+ }
399
+ // A managed republish may change the title/description. Invalidate only
400
+ // its generated sibling so the next crawler receives a fresh card; BYO
401
+ // publishes send no OG metadata and keep their explicitly uploaded cover.
402
+ if (ogTitle) await env.BUCKET.delete(path + '.png');
403
+ return json({ ok: true, url: url.origin + '/' + path, expiresAt: expiresAt || null, unlisted: visibility === 'unlisted', visibility }, 200);
404
+ }
405
+
406
+ if (request.method === 'PATCH') {
407
+ const auth = await authorizeWrite(request, env);
408
+ if (auth.error) return auth.error;
409
+ const segments = path.split('/').filter(Boolean);
410
+ if (segments.length < 2) return json({ error: 'metadata edit requires /<username>/<slug>' }, 400);
411
+ if (auth.kind === 'phoenix') {
412
+ const expected = phoenixHandle(auth);
413
+ const handle = segments[0];
414
+ if (!expected || handle !== expected) {
415
+ // An alternate handle must already have a claim; unlike PUT, PATCH
416
+ // cannot create a new namespace as a side effect.
417
+ const claim = handle ? await env.BUCKET.get('__handles/' + handle) : null;
418
+ if (!claim) return json({ error: 'namespace mismatch', owner: expected }, 403);
419
+ }
420
+ // Use the same ownership path as PUT/DELETE so the same verified email
421
+ // under a new userId transfers the claim and re-stamps old pages before
422
+ // the per-object ownership check below.
423
+ const owned = await assertHandleOwner(env.BUCKET, handle, auth.owner, auth.email || '');
424
+ if (owned.error) return json({ error: 'forbidden' }, 403);
425
+ }
426
+ const existing = await env.BUCKET.get(path);
427
+ if (!existing) return json({ error: 'share not found', key: path }, 404);
428
+ // Ownership was settled above, the same way DELETE settles it: WRITE_TOKEN
429
+ // is the endpoint owner/admin credential, and a Phoenix caller has proven
430
+ // the handle claim (or, pre-claim, that no rival userId owns the prefix).
431
+ // There is deliberately NO per-object owner comparison here. Pages in a
432
+ // claimed namespace can carry a stamp that is not the claim holder's
433
+ // userId — a BYO WRITE_TOKEN publish stamps owner = the namespace, a page
434
+ // from the same human's earlier userId that transferHandle never saw, or
435
+ // a page with no stamp at all — and the claim holder could DELETE every
436
+ // one of them yet was refused a visibility change (403 'forbidden'), which
437
+ // left confidential pages public with takedown as the only remedy. The
438
+ // claim is the authority. The stamp itself is deliberately NOT rewritten:
439
+ // the anonymous lazy-expiry path refunds the STAMPED owner's usage ledger
440
+ // (see the GET expiry branch + refundShareWrite), and a fleet/BYO page was
441
+ // never charged to a Phoenix ledger — re-stamping it to the caller would
442
+ // credit her quota with bytes and a slot she never paid for on expiry.
443
+
444
+ let edit;
445
+ try { edit = await request.json(); } catch { return json({ error: 'PATCH body must be JSON' }, 400); }
446
+ if (!edit || typeof edit !== 'object') return json({ error: 'PATCH body must be an object' }, 400);
447
+ const metadata = { ...(existing.customMetadata || {}) };
448
+ const previousVisibility = metadata.visibility || 'public';
449
+ let visibilityChanged = false;
450
+ if (Object.prototype.hasOwnProperty.call(edit, 'label')) {
451
+ if (edit.label !== null && typeof edit.label !== 'string') return json({ error: 'label must be a string or null' }, 400);
452
+ if (typeof edit.label === 'string' && (edit.label.trim() !== edit.label || !edit.label || edit.label.length > 200)) return json({ error: 'label must be 1-200 trimmed characters' }, 400);
453
+ if (edit.label === null) { delete metadata.label; delete metadata['label-source']; }
454
+ else { metadata.label = edit.label; metadata['label-source'] = 'explicit'; }
455
+ }
456
+ // Visibility is a first-class edit field (like label), not an arbitrary
457
+ // --meta entry — 'visibility' is a RESERVED key, so it can only be changed
458
+ // here, never smuggled through edit.meta. me/org require a Phoenix identity
459
+ // and org additionally requires a private (non-public-inbox) email domain,
460
+ // the SAME gate PUT enforces. This is a metadata-only rewrite: the body is
461
+ // untouched, so no revision is created (identical to a label/meta edit).
462
+ if (Object.prototype.hasOwnProperty.call(edit, 'visibility')) {
463
+ const vis = normalizeVisibility(edit.visibility);
464
+ if (vis.error) return vis.error;
465
+ const visibility = vis.value;
466
+ // 'private' can't be set via the metadata-edit route: token-gating needs a
467
+ // fresh viewer key, which only a full publish mints (PHNX-3654). Re-stamping
468
+ // visibility=private here alone would leave the page gated by a hash that
469
+ // never got stored — inaccessible to everyone. Fail loud.
470
+ if (visibility === 'private') return json({ error: 'visibility private must be set at publish time (share --protected)' }, 400);
471
+ if (visibility === 'me' || visibility === 'org') {
472
+ const phoenixBase = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
473
+ if (auth.kind !== 'phoenix' || !phoenixBase) return json({ error: 'visibility me/org requires Phoenix identity' }, 400);
474
+ if (visibility === 'org') {
475
+ const domain = emailDomain(auth.email);
476
+ if (!domain) return json({ error: 'org visibility requires a verified email domain' }, 400);
477
+ if (PUBLIC_INBOX_DOMAINS.indexOf(domain) !== -1) return json({ error: 'org visibility cannot use a public email domain', domain: domain }, 400);
478
+ }
479
+ }
480
+ metadata.visibility = visibility;
481
+ visibilityChanged = visibility !== previousVisibility;
482
+ // org_domain is meaningful only for org — set it there, drop the stale
483
+ // value on any move away from org so it can never gate a later read.
484
+ if (visibility === 'org') metadata.org_domain = emailDomain(auth.email);
485
+ else delete metadata.org_domain;
486
+ }
487
+ const mode = edit.metaMode || 'merge';
488
+ if (mode !== 'merge' && mode !== 'replace') return json({ error: 'metaMode must be merge or replace' }, 400);
489
+ const incoming = edit.meta || {};
490
+ if (!incoming || typeof incoming !== 'object' || Array.isArray(incoming)) return json({ error: 'meta must be an object' }, 400);
491
+ for (const key in incoming) {
492
+ if (RESERVED_METADATA_KEYS.indexOf(key) !== -1) return json({ error: 'reserved metadata key', key: key }, 400);
493
+ if (!/^[a-z0-9-]{1,64}$/.test(key) || typeof incoming[key] !== 'string') return json({ error: 'invalid metadata entry', key: key }, 400);
494
+ }
495
+ if (mode === 'replace') {
496
+ for (const key in metadata) if (RESERVED_METADATA_KEYS.indexOf(key) === -1) delete metadata[key];
497
+ }
498
+ for (const key in incoming) metadata[key] = incoming[key];
499
+ const remove = edit.removeMeta || [];
500
+ if (!Array.isArray(remove)) return json({ error: 'removeMeta must be an array' }, 400);
501
+ for (const key of remove) {
502
+ if (typeof key !== 'string' || RESERVED_METADATA_KEYS.indexOf(key) !== -1 || !/^[a-z0-9-]{1,64}$/.test(key)) return json({ error: 'invalid removable metadata key', key: key }, 400);
503
+ delete metadata[key];
504
+ }
505
+ if (new TextEncoder().encode(JSON.stringify(extraMetaOf(metadata))).length > 2048) return json({ error: 'metadata exceeds 2048 bytes' }, 400);
506
+ // R2 assigns a fresh uploaded timestamp to every put. Preserve the
507
+ // canonical publication time before this metadata-only rewrite so gallery
508
+ // ordering and list JSON do not pretend the page was republished today.
509
+ if (!metadata['published-at']) metadata['published-at'] = new Date(existing.uploaded).toISOString();
510
+ const httpHeaders = new Headers();
511
+ if (typeof existing.writeHttpMetadata === 'function') existing.writeHttpMetadata(httpHeaders);
512
+ const putOpts = { httpMetadata: httpHeaders, customMetadata: metadata };
513
+ // onlyIf.etagMatches wants the bare hash (R2Object#etag), not the
514
+ // quoted HTTP header form (R2Object#httpEtag) — passing httpEtag 500s
515
+ // on a real Workers R2 binding ("Conditional ETag should not be
516
+ // wrapped in quotes"), a defect only a real R2 backend surfaces.
517
+ if (existing.etag) putOpts.onlyIf = { etagMatches: existing.etag };
518
+ const putResult = await env.BUCKET.put(path, existing.body, putOpts);
519
+ if (putResult === null) return json({ error: 'conflict', key: path }, 409);
520
+ // A generated cover copies the canonical visibility gate into its own R2
521
+ // metadata. Invalidate it after a successful visibility rewrite so the
522
+ // next cover GET re-gates and renders from the canonical page. Explicitly
523
+ // uploaded BYO siblings carry no marker and remain independent assets.
524
+ if (visibilityChanged) {
525
+ const cover = await env.BUCKET.get(path + '.png');
526
+ if (cover && cover.customMetadata && cover.customMetadata['og-generated'] === 'true') {
527
+ await env.BUCKET.delete(path + '.png');
528
+ }
529
+ }
530
+ return json({ ok: true, url: url.origin + '/' + path, label: metadata.label || null, meta: extraMetaOf(metadata), visibility: metadata.visibility || 'public', previousVisibility: previousVisibility }, 200);
531
+ }
532
+
533
+ if (request.method === 'GET' || request.method === 'HEAD') {
534
+ // Single-segment path may be a user gallery/listing OR a legacy flat slug.
535
+ // The disambiguator is whether the <seg>/ prefix holds any object: only a
536
+ // genuine per-user namespace does. BOTH the HTML gallery and the
537
+ // machine-readable listing gate on it, so ?format=json on a legacy flat
538
+ // slug (an object stored at the bare key, before per-user namespaces) does
539
+ // NOT hijack it into a fake empty listing — it falls through to the object
540
+ // GET below and serves its real content, exactly as before.
541
+ const segments = path.split('/').filter(Boolean);
542
+ if (segments.length === 1) {
543
+ const list = await env.BUCKET.list({ prefix: segments[0] + '/', limit: 1 });
544
+ const isNamespace = list.objects && list.objects.length > 0;
545
+ if (isNamespace) {
546
+ if (url.searchParams.get('format') === 'json') {
547
+ const scope = await resolveListingScope(request, env, segments[0]);
548
+ if (scope.error) return scope.error;
549
+ return renderListing(env.BUCKET, url.origin, segments[0], request.method, scope.includeHidden);
550
+ }
551
+ return renderGallery(env.BUCKET, url.origin, segments[0], request.method);
552
+ }
553
+ // Not a namespace: fall through. A legacy flat-slug object resolves to its
554
+ // real content; anything else 404s (an empty/nonexistent namespace, which
555
+ // agents share list reads as "nothing published" via the template-hash
556
+ // signal rather than a missing route).
557
+ }
558
+
559
+ // Revision history for one canonical <user>/<slug> key (RUSH-2683). Checked
560
+ // before the plain object GET below so the query param routes even though
561
+ // the canonical key itself resolves to a real object. me/org use the same
562
+ // identity gate as the page GET — listing session/host/repo on an unauthed
563
+ // ?revisions=json must not leak that the page exists.
564
+ if (segments.length === 2 && url.searchParams.get('revisions') === 'json') {
565
+ const canonical = await env.BUCKET.get(path);
566
+ const canonicalVis = canonical ? ((canonical.customMetadata && canonical.customMetadata.visibility) || 'public') : 'public';
567
+ // Only a me/org canonical needs the viewer resolved — and only there does
568
+ // a phoenix_ticket failure gate the response, exactly as before this route
569
+ // shared resolveViewer with the page GET. A public/unlisted revision list
570
+ // never invoked ticket redemption, so a stale ticket must not 401 it.
571
+ if (canonical && isIdentityGated(canonicalVis)) {
572
+ const viewer = await resolveViewer(request, env, url);
573
+ if (viewer.redirect) return viewer.redirect;
574
+ if (viewer.error) return viewer.error;
575
+ const denied = await gateVisibility(url, env, canonical, viewer.identity || null);
576
+ if (denied) return denied;
577
+ }
578
+ // A private canonical gates its revision list on the viewer key too
579
+ // (PHNX-3654) — listing session/host/repo of a token-gated page to an
580
+ // unauthenticated caller would leak the very metadata the gate protects.
581
+ if (canonical && canonicalVis === 'private') {
582
+ const viewer = await resolveViewer(request, env, url);
583
+ if (viewer.redirect) return viewer.redirect;
584
+ const tokenDenied = await gateTokenRead(request, url, canonical, viewer.identity || null);
585
+ if (tokenDenied) return tokenDenied;
586
+ }
587
+ return renderRevisions(
588
+ env.BUCKET,
589
+ url.origin,
590
+ path,
591
+ request.method,
592
+ !!canonical && (isIdentityGated(canonicalVis) || canonicalVis === 'private'),
593
+ );
594
+ }
595
+
596
+ // Managed OG cover: generated siblings are caches, never visibility
597
+ // authorities. Gate every request against the current canonical page and
598
+ // bind each cached render to that page's etag. Re-read after rendering and
599
+ // after storing so a concurrent PATCH cannot publish a card from the old
600
+ // visibility/title/description snapshot. Explicit BYO siblings carry no
601
+ // generated marker and continue through the ordinary object route below.
602
+ if (segments.length === 2 && path.endsWith('.png')) {
603
+ let existingCover = await env.BUCKET.get(path);
604
+ if (!existingCover || (existingCover.customMetadata && existingCover.customMetadata['og-generated'] === 'true')) {
605
+ const pagePath = path.slice(0, -4);
606
+ const viewer = await resolveViewer(request, env, url);
607
+ if (viewer.redirect) return viewer.redirect;
608
+ for (let attempt = 0; attempt < 3; attempt += 1) {
609
+ const page = await env.BUCKET.get(pagePath);
610
+ if (!page) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
611
+ const pageVisibility = (page.customMetadata && page.customMetadata.visibility) || 'public';
612
+ if (viewer.error && isIdentityGated(pageVisibility)) return viewer.error;
613
+ const denied = await gateVisibility(url, env, page, viewer.identity || null);
614
+ if (denied) return denied;
615
+ // A token-gated page's cover is token-gated too (PHNX-3654): a crawler
616
+ // fetching <slug>.png without the key gets 404, so no preview leaks.
617
+ const coverTokenDenied = await gateTokenRead(request, url, page, viewer.identity || null);
618
+ if (coverTokenDenied) return coverTokenDenied;
619
+
620
+ if (existingCover && existingCover.customMetadata['og-source-etag'] === page.etag) {
621
+ const current = await env.BUCKET.get(pagePath);
622
+ if (!current || current.etag !== page.etag) { existingCover = null; continue; }
623
+ const currentDenied = await gateVisibility(url, env, current, viewer.identity || null);
624
+ if (currentDenied) return currentDenied;
625
+ return new Response(request.method === 'HEAD' ? null : existingCover.body, {
626
+ status: 200,
627
+ headers: managedCoverHeaders(pageVisibility),
628
+ });
629
+ }
630
+
631
+ const pageHtml = await page.text();
632
+ const meta = page.customMetadata || {};
633
+ let png;
634
+ try {
635
+ png = await hooks.renderOgCard({
636
+ title: meta['og-title'] || extractHtmlMeta(pageHtml, 'title') || meta.label || segments[1],
637
+ description: meta['og-description'] || extractHtmlMeta(pageHtml, 'description') || '',
638
+ handle: segments[0],
639
+ visibility: pageVisibility,
640
+ orgDomain: meta.org_domain || '',
641
+ });
642
+ } catch (error) {
643
+ const detail = error instanceof Error ? error.message : String(error);
644
+ return new Response('OG card render failed: ' + detail, {
645
+ status: 500,
646
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
647
+ });
648
+ }
649
+ const beforeStore = await env.BUCKET.get(pagePath);
650
+ if (!beforeStore || beforeStore.etag !== page.etag) { existingCover = null; continue; }
651
+ await env.BUCKET.put(path, png, {
652
+ httpMetadata: { contentType: 'image/png' },
653
+ customMetadata: { ...meta, 'og-generated': 'true', 'og-source-etag': page.etag },
654
+ });
655
+ const beforeServe = await env.BUCKET.get(pagePath);
656
+ if (!beforeServe || beforeServe.etag !== page.etag) {
657
+ const justStored = await env.BUCKET.get(path);
658
+ if (justStored && justStored.customMetadata && justStored.customMetadata['og-source-etag'] === page.etag) {
659
+ await env.BUCKET.delete(path);
660
+ }
661
+ existingCover = null;
662
+ continue;
663
+ }
664
+ return new Response(request.method === 'HEAD' ? null : png, {
665
+ status: 200,
666
+ headers: managedCoverHeaders(pageVisibility),
667
+ });
668
+ }
669
+ return new Response('cover changed during rendering; retry', { status: 503, headers: { 'content-type': 'text/plain', 'retry-after': '1' } });
670
+ }
671
+ }
672
+
673
+ const obj = await env.BUCKET.get(path);
674
+ if (!obj) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
675
+ const expiresAt = obj.customMetadata && obj.customMetadata['expires-at'];
676
+ if (expiresAt && Date.now() > Date.parse(expiresAt)) {
677
+ await env.BUCKET.delete(path);
678
+ // PHNX-3542: expiry is a lazy delete with no auth context. Refund the
679
+ // stamped owner's quota (bytes + object count) best-effort — a refund
680
+ // failure must never break serving the 410. A canonical page is 2
681
+ // segments; covers are excluded (never charged) so refund is safe here
682
+ // because only canonical pages ever carry an expires-at.
683
+ const expiredOwner = obj.customMetadata && obj.customMetadata['owner'];
684
+ if (expiredOwner && !path.endsWith('.png')) {
685
+ try {
686
+ await refundShareWrite(env, expiredOwner, {
687
+ refund: typeof obj.size === 'number' ? obj.size : 0,
688
+ freeCanonical: path.split('/').filter(Boolean).length === 2,
689
+ });
690
+ } catch (e) {
691
+ // best-effort: serving the expiry 410 must never depend on the refund
692
+ }
693
+ }
694
+ return new Response('gone — this link has expired', { status: 410, headers: { 'content-type': 'text/plain' } });
695
+ }
696
+ // Resolve the viewer ONCE — needed both to gate me/org reads AND to decide
697
+ // whether THIS viewer OWNS this namespace (the interactive visibility
698
+ // control below). A successful phoenix_ticket redemption (redirect: set the
699
+ // identity cookie, strip the ticket) is honored on ANY page. But a ticket
700
+ // FAILURE (expired/consumed/unreachable) must only gate a page that needs
701
+ // identity — a public/unlisted page never invoked ticket redemption before
702
+ // this refactor, so a stale ticket there must serve anonymously, not 401.
703
+ const visibility = (obj.customMetadata && obj.customMetadata.visibility) || 'public';
704
+ const viewer = await resolveViewer(request, env, url);
705
+ if (viewer.redirect) return viewer.redirect;
706
+ if (viewer.error && isIdentityGated(visibility)) return viewer.error;
707
+ const identity = viewer.identity || null;
708
+ const denied = await gateVisibility(url, env, obj, identity);
709
+ if (denied) return denied;
710
+ // Token-gated read auth (PHNX-3654): a 'private' page is served only to a
711
+ // request carrying the matching viewer key (?k= or Bearer), or to its owner.
712
+ // A miss returns 404 — never leaking that the page exists — exactly like a
713
+ // wrong me/org viewer.
714
+ const tokenDenied = await gateTokenRead(request, url, obj, identity);
715
+ if (tokenDenied) return tokenDenied;
716
+ // The owner of the namespace (their handle === the first path segment) gets
717
+ // an interactive visibility control; everyone else keeps the static cue.
718
+ const isOwner = !!identity && handleFromEmail(identity.email) === firstSeg;
719
+ const ownerDomain = identity ? emailDomain(identity.email) : '';
720
+ const headers = new Headers();
721
+ obj.writeHttpMetadata(headers);
722
+ headers.set('etag', obj.httpEtag);
723
+ if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8');
724
+ if (visibility === 'me' || visibility === 'org' || visibility === 'private') {
725
+ // Token-gated + identity-gated reads must never be cached by a shared
726
+ // proxy, and never indexed.
727
+ headers.set('cache-control', 'private, no-store');
728
+ headers.set('X-Robots-Tag', 'noindex');
729
+ } else {
730
+ headers.set('cache-control', 'public, max-age=60');
731
+ if (visibility === 'unlisted') headers.set('X-Robots-Tag', 'noindex');
732
+ }
733
+ if (request.method === 'HEAD') return new Response(null, { status: 200, headers });
734
+ const ctype = headers.get('content-type') || '';
735
+ // HTML pages ALWAYS get the attribution bar injected at serve time (who
736
+ // shared it, what made it, when, and — the point — a visual VISIBILITY cue),
737
+ // all from stamped metadata. This is unconditional: ?raw does NOT strip the
738
+ // bar from a shared page (the always-on cue from #3122/#3140 is not
739
+ // defeatable with a query param). The body changes, so the R2 etag no
740
+ // longer matches — drop it rather than serve a lying validator.
741
+ if (ctype.indexOf('text/html') !== -1) {
742
+ const rawHtml = await obj.text();
743
+ // Per-slug view counter (RUSH view stats). Stored as a SEPARATE R2 object
744
+ // (__views/<path>) so it never rewrites the page object — a rewrite would
745
+ // reset obj.uploaded and corrupt "last updated". The __-prefix key is GET-
746
+ // blocked for direct requests and lives outside every <user>/ list prefix,
747
+ // so it never leaks into the gallery/listing/revisions. Count only a real
748
+ // visitor's page view: not ?raw (an embed/OG fetch), not the owner's own
749
+ // view, and never HEAD (which returned above). The write rides
750
+ // ctx.waitUntil so it never blocks the response; the displayed count folds
751
+ // in the current view so the visitor sees themselves included.
752
+ const wantsRaw = url.searchParams.get('raw') != null;
753
+ const counting = !wantsRaw && !isOwner;
754
+ const storedViews = await readViews(env, path);
755
+ const views = storedViews + (counting ? 1 : 0);
756
+ if (counting && ctx && typeof ctx.waitUntil === 'function') {
757
+ ctx.waitUntil(writeViews(env, path, views));
758
+ }
759
+ const withBar = injectAttributionBar(rawHtml, obj.customMetadata || {}, firstSeg, {
760
+ isOwner,
761
+ ownerDomain,
762
+ views,
763
+ uploaded: obj.uploaded,
764
+ });
765
+ headers.delete('etag');
766
+ return new Response(withBar, { status: 200, headers });
767
+ }
768
+ // Non-HTML asset. ?raw returns the stored bytes untouched — the escape hatch
769
+ // for <img src>, OG crawlers, iframes, and anyone embedding the asset (the
770
+ // viewer's own media element points back at ?raw). Otherwise a BROWSER
771
+ // navigating directly to a viewable asset (image/video/audio/pdf) gets a
772
+ // lightweight viewer page carrying the same bar; a non-browser fetch (Accept
773
+ // without text/html) falls through to raw bytes so embedding is never broken.
774
+ const wantsRaw = url.searchParams.get('raw') != null;
775
+ const kind = viewableAssetKind(ctype);
776
+ // A token-gated (private) asset is served as raw bytes, NOT wrapped in the
777
+ // viewer page (PHNX-3654): the viewer's inner <img src=…?raw> would drop the
778
+ // ?k= key and 404 (there's no cookie to carry it, unlike me/org), breaking the
779
+ // media. The gate already passed above, so the raw bytes are safe to serve.
780
+ if (!wantsRaw && kind && acceptsHtml(request) && visibility !== 'private') {
781
+ const viewerPage = renderAssetViewer(url.pathname, kind, obj.customMetadata || {}, firstSeg, {
782
+ isOwner,
783
+ ownerDomain,
784
+ });
785
+ const vheaders = new Headers(headers);
786
+ vheaders.set('content-type', 'text/html; charset=utf-8');
787
+ vheaders.delete('etag');
788
+ return new Response(viewerPage, { status: 200, headers: vheaders });
789
+ }
790
+ return new Response(obj.body, { status: 200, headers });
791
+ }
792
+
793
+ if (request.method === 'DELETE') {
794
+ const auth = await authorizeWrite(request, env);
795
+ if (auth.error) return auth.error;
796
+ if (auth.kind === 'phoenix') {
797
+ const handle = phoenixHandle(auth);
798
+ const uid = sanitizeNamespace(auth.owner);
799
+ const delSegments = path.split('/').filter(Boolean);
800
+ // Handle is the public namespace; userId prefix is still deletable so
801
+ // P1 UUID-namespaced objects the same account published can be taken down.
802
+ // A colliding local-part (same handle, different userId) must not be
803
+ // able to DELETE the claimant's pages — consult the claim the same way PUT does.
804
+ if (delSegments[0] && delSegments[0] === uid) {
805
+ // own leftover UUID prefix
806
+ } else if (delSegments[0] && delSegments[0] === handle) {
807
+ const owned = await assertHandleOwner(env.BUCKET, handle, auth.owner, auth.email || '');
808
+ if (owned.error) return owned.error;
809
+ } else if (delSegments[0]) {
810
+ // An explicitly-chosen handle (the CLI's --handle, PHNX-3547): the
811
+ // caller's derived handle differs from the namespace, so the claim is
812
+ // the authority — assertHandleOwner refuses strangers (409) and
813
+ // recovers a same-email account move. No claim at all is a mismatch.
814
+ const claim = await env.BUCKET.get('__handles/' + delSegments[0]);
815
+ if (!claim) return json({ error: 'namespace mismatch', owner: handle || uid }, 403);
816
+ const owned = await assertHandleOwner(env.BUCKET, delSegments[0], auth.owner, auth.email || '');
817
+ if (owned.error) return owned.error;
818
+ } else {
819
+ return json({ error: 'namespace mismatch', owner: handle || uid }, 403);
820
+ }
821
+ }
822
+ // PHNX-3542: capture the object's size BEFORE deleting so a managed
823
+ // Phoenix owner's quota can be refunded. A canonical page (2 segments, not
824
+ // a .png cover) refunds both bytes and the object count; a retained
825
+ // revision (3+ segments) refunds bytes only; a server-generated .png cover
826
+ // was never charged, so it is skipped entirely.
827
+ let doomed = null;
828
+ const isCover = path.endsWith('.png');
829
+ if (auth.kind === 'phoenix' && !isCover && !firstSeg.startsWith('__')) {
830
+ doomed = typeof env.BUCKET.head === 'function' ? await env.BUCKET.head(path) : await env.BUCKET.get(path);
831
+ }
832
+ await env.BUCKET.delete(path);
833
+ if (doomed) {
834
+ const delSegs = path.split('/').filter(Boolean);
835
+ await refundShareWrite(env, auth.owner, {
836
+ refund: typeof doomed.size === 'number' ? doomed.size : 0,
837
+ freeCanonical: delSegs.length === 2,
838
+ });
839
+ }
840
+ return json({ ok: true, deleted: path }, 200);
841
+ }
842
+
843
+ return new Response('method not allowed', { status: 405 });
844
+ },
845
+ };
846
+
847
+ // A canonical share object's key is exactly 2 segments (<user>/<slug>, or the
848
+ // sibling <user>/<slug>.png OG cover). A retained revision lives a 3rd segment
849
+ // deeper (<user>/<slug>/rev-<ts>-<rand>) — history, not a page in its own
850
+ // right, so every gallery/listing view hides it. A raw external PUT to an
851
+ // already-3-segment-deep path is treated the same way for the same reason:
852
+ // there is no ambiguity to resolve, and the CLI never produces such a key.
853
+ function isRevisionKey(key) {
854
+ return key.split('/').length > 2;
855
+ }
856
+
857
+ function publishedAtOf(object) {
858
+ return (object.customMetadata && object.customMetadata['published-at']) || object.uploaded;
859
+ }
860
+
861
+ async function renderGallery(bucket, origin, user, method) {
862
+ const objects = [];
863
+ let cursor;
864
+ do {
865
+ const list = await bucket.list({ prefix: user + '/', limit: 1000, cursor, include: ['customMetadata'] });
866
+ objects.push(...(list.objects || []));
867
+ cursor = list.truncated ? list.cursor : undefined;
868
+ } while (cursor);
869
+
870
+ const activeObjects = objects.filter(o => {
871
+ if (isRevisionKey(o.key)) return false;
872
+ if (o.key.endsWith('.png')) return false;
873
+ // Unlisted / me / org pages are reachable by direct URL only — never on the gallery.
874
+ if (isHiddenFromGallery(o.customMetadata && o.customMetadata.visibility)) return false;
875
+ const expiresAt = o.customMetadata && o.customMetadata['expires-at'];
876
+ return !(expiresAt && Date.now() > Date.parse(expiresAt));
877
+ });
878
+ const items = activeObjects.map(o => {
879
+ const slug = o.key.slice(o.key.indexOf('/') + 1);
880
+ const url = origin + '/' + o.key;
881
+ const label = (o.customMetadata && o.customMetadata['label']) || '';
882
+ const agent = (o.customMetadata && o.customMetadata['agent']) || '';
883
+ return { slug, url, updated: publishedAtOf(o), label, agent };
884
+ });
885
+
886
+ if (method === 'HEAD') {
887
+ return new Response(null, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8' } });
888
+ }
889
+
890
+ const html =
891
+ '<!doctype html><html><head>' +
892
+ '<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">' +
893
+ '<title>' + escapeHtml(user) + ' — agents share</title>' +
894
+ '<style>' +
895
+ 'body{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;max-width:720px;margin:48px auto;padding:0 24px;color:#111;background:#fafafa}' +
896
+ 'h1{font-size:28px;margin-bottom:8px}a{color:#0a0a0a;text-decoration:none;border-bottom:1px solid #999}' +
897
+ 'a:hover{border-color:#111}ul{list-style:none;padding:0}li{margin:16px 0}' +
898
+ '.slug{font-weight:600}.title{font-weight:600}.meta{color:#666;font-size:14px}' +
899
+ '</style></head><body>' +
900
+ '<h1>@' + escapeHtml(user) + '</h1>' +
901
+ '<p class="meta">' + items.length + ' shared ' + (items.length === 1 ? 'page' : 'pages') + '</p>' +
902
+ '<ul>' +
903
+ items.map(i =>
904
+ '<li>' +
905
+ (i.label ? '<span class="title">' + escapeHtml(i.label) + '</span><br>' : '') +
906
+ '<a class="slug" href="' + escapeHtml(i.url) + '">' + escapeHtml(i.slug) + '</a>' +
907
+ '<br><span class="meta">' + new Date(i.updated).toISOString().slice(0, 10) +
908
+ (i.agent ? ' · ' + escapeHtml(i.agent) : '') + '</span></li>'
909
+ ).join('') +
910
+ '</ul></body></html>';
911
+ return new Response(html, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'public, max-age=60' } });
912
+ }
913
+
914
+ async function renderListing(bucket, origin, user, method, includeHidden) {
915
+ const objects = [];
916
+ let cursor;
917
+ do {
918
+ const list = await bucket.list({ prefix: user + '/', limit: 1000, cursor, include: ['httpMetadata', 'customMetadata'] });
919
+ objects.push(...(list.objects || []));
920
+ cursor = list.truncated ? list.cursor : undefined;
921
+ } while (cursor);
922
+
923
+ // Revisions never appear as their own listing row, but they count toward
924
+ // their canonical object's revisionCount.
925
+ const revisionCounts = {};
926
+ for (const o of objects) {
927
+ if (!isRevisionKey(o.key)) continue;
928
+ const canonicalKey = o.key.split('/').slice(0, 2).join('/');
929
+ revisionCounts[canonicalKey] = (revisionCounts[canonicalKey] || 0) + 1;
930
+ }
931
+
932
+ const now = Date.now();
933
+ const items = objects
934
+ .filter(o => {
935
+ // Revisions and sibling .png OG covers are always hidden. Hidden-visibility
936
+ // pages are included ONLY when an authenticated owner requested scope=mine.
937
+ if (isRevisionKey(o.key)) return false;
938
+ if (o.key.endsWith('.png')) return false;
939
+ if (isHiddenFromGallery(o.customMetadata && o.customMetadata.visibility) && !includeHidden) return false;
940
+ const expiresAt = o.customMetadata && o.customMetadata['expires-at'];
941
+ return !(expiresAt && now > Date.parse(expiresAt));
942
+ })
943
+ .map(o => ({
944
+ slug: o.key.slice(o.key.indexOf('/') + 1),
945
+ url: origin + '/' + o.key,
946
+ size: typeof o.size === 'number' ? o.size : 0,
947
+ contentType: (o.httpMetadata && o.httpMetadata.contentType) || null,
948
+ publishedAt: new Date(publishedAtOf(o)).toISOString(),
949
+ expiresAt: (o.customMetadata && o.customMetadata['expires-at']) || null,
950
+ label: (o.customMetadata && o.customMetadata['label']) || null,
951
+ visibility: (o.customMetadata && o.customMetadata.visibility) || 'public',
952
+ agent: (o.customMetadata && o.customMetadata['agent']) || null,
953
+ session: (o.customMetadata && o.customMetadata['session']) || null,
954
+ host: (o.customMetadata && o.customMetadata['host']) || null,
955
+ repo: (o.customMetadata && o.customMetadata['repo']) || null,
956
+ revisionCount: revisionCounts[o.key] || 0,
957
+ meta: extraMetaOf(o.customMetadata),
958
+ }));
959
+ // Newest first, so the human table and any script reads the freshest share top.
960
+ items.sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0));
961
+
962
+ const cacheHeaders = includeHidden
963
+ ? { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'private, no-store', 'X-Robots-Tag': 'noindex' }
964
+ : { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'public, max-age=30' };
965
+ if (method === 'HEAD') {
966
+ return new Response(null, { status: 200, headers: cacheHeaders });
967
+ }
968
+ return new Response(JSON.stringify({ user, count: items.length, objects: items }), {
969
+ status: 200,
970
+ headers: cacheHeaders,
971
+ });
972
+ }
973
+
974
+ // The machine-readable listing is public by default. A request with
975
+ // '?format=json&scope=mine' asks to include the owner's hidden pages
976
+ // (unlisted / me / org). We honor it ONLY after a valid owner bearer whose
977
+ // namespace matches the requested handle, so one user cannot list another's
978
+ // hidden shares. Anonymous or mismatched requests fail loud. A BYO WRITE_TOKEN
979
+ // bearer is the worker's owner, so namespace enforcement is skipped for BYO.
980
+ async function resolveListingScope(request, env, user) {
981
+ const scope = new URL(request.url).searchParams.get('scope');
982
+ if (scope !== 'mine') return { includeHidden: false };
983
+ const auth = await authorizeWrite(request, env);
984
+ if (auth.error) return { error: auth.error };
985
+ if (auth.kind === 'byo') {
986
+ return { includeHidden: true };
987
+ }
988
+ const owner = phoenixHandle(auth);
989
+ if (owner !== user) {
990
+ return { error: json({ error: 'namespace mismatch' }, 403) };
991
+ }
992
+ return { includeHidden: true };
993
+ }
994
+
995
+ async function renderRevisions(bucket, origin, key, method, identityGated) {
996
+ const objects = [];
997
+ let cursor;
998
+ do {
999
+ const list = await bucket.list({ prefix: key + '/rev-', limit: 1000, cursor, include: ['httpMetadata', 'customMetadata'] });
1000
+ objects.push(...(list.objects || []));
1001
+ cursor = list.truncated ? list.cursor : undefined;
1002
+ } while (cursor);
1003
+
1004
+ const items = objects.map(o => ({
1005
+ key: o.key,
1006
+ url: origin + '/' + o.key,
1007
+ size: typeof o.size === 'number' ? o.size : 0,
1008
+ contentType: (o.httpMetadata && o.httpMetadata.contentType) || null,
1009
+ uploadedAt: new Date(o.uploaded).toISOString(),
1010
+ expiresAt: (o.customMetadata && o.customMetadata['expires-at']) || null,
1011
+ label: (o.customMetadata && o.customMetadata['label']) || null,
1012
+ agent: (o.customMetadata && o.customMetadata['agent']) || null,
1013
+ session: (o.customMetadata && o.customMetadata['session']) || null,
1014
+ host: (o.customMetadata && o.customMetadata['host']) || null,
1015
+ repo: (o.customMetadata && o.customMetadata['repo']) || null,
1016
+ meta: extraMetaOf(o.customMetadata),
1017
+ }));
1018
+ // Newest first — the most recently replaced version leads.
1019
+ items.sort((a, b) => (a.uploadedAt < b.uploadedAt ? 1 : a.uploadedAt > b.uploadedAt ? -1 : 0));
1020
+
1021
+ const cacheHeaders = identityGated
1022
+ ? { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'private, no-store', 'X-Robots-Tag': 'noindex' }
1023
+ : { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'public, max-age=30' };
1024
+ if (method === 'HEAD') {
1025
+ return new Response(null, { status: 200, headers: cacheHeaders });
1026
+ }
1027
+ return new Response(JSON.stringify({ key, count: items.length, revisions: items }), {
1028
+ status: 200,
1029
+ headers: cacheHeaders,
1030
+ });
1031
+ }
1032
+
1033
+ // The customMetadata keys the CLI sets automatically (provenance + label) —
1034
+ // never a real \`--meta key=value\` entry (the CLI rejects a colliding key
1035
+ // before it ever reaches this Worker; see RESERVED_META_KEYS in publish.ts).
1036
+ // One list, reused both to strip a same-named --meta collision on write and
1037
+ // to split arbitrary --meta entries back out on read.
1038
+ var RESERVED_METADATA_KEYS = ['expires-at', 'published-at', 'visibility', 'viewer-token-hash', 'owner', 'org_domain', 'agent', 'session', 'host', 'repo', 'date', 'avatar', 'label', 'label-source', 'og-title', 'og-description', 'og-generated', 'og-source-etag'];
1039
+ var PUBLIC_INBOX_DOMAINS = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'icloud.com', 'me.com'];
1040
+ var SHARE_COOKIE = '__Host-phoenix_share';
1041
+ var SHARE_COOKIE_MAX_AGE = 604800;
1042
+
1043
+ // PHNX-3542 — per-user storage limits for the MANAGED share endpoint. The plan
1044
+ // map is the seam for future paid tiers: only 'free' is defined today, and a
1045
+ // ledger with no plan (or an unknown one) resolves to it via planLimits(). Paid
1046
+ // tiers and the write path that sets a user's plan arrive with billing (follow-up
1047
+ // PHNX-3569); this is a legitimately-deferred seam, not a stub — 'free' IS
1048
+ // enforced. Covers/views are server-generated overhead and excluded from the
1049
+ // quota, which counts canonical pages + their retained revisions only.
1050
+ var MiB = 1024 * 1024;
1051
+ var SHARE_PLANS = {
1052
+ free: { maxBytes: 200 * MiB, maxObjects: 150, maxFileBytes: 20 * MiB, ratePerHour: 60 },
1053
+ };
1054
+ var DEFAULT_SHARE_PLAN = 'free';
1055
+ var RATE_WINDOW_MS = 3600 * 1000; // fixed 1h publish-rate window
1056
+ function planLimits(plan) { return Object.prototype.hasOwnProperty.call(SHARE_PLANS, plan) ? SHARE_PLANS[plan] : SHARE_PLANS[DEFAULT_SHARE_PLAN]; }
1057
+ function freshUsage() { return { bytes: 0, count: 0, plan: DEFAULT_SHARE_PLAN, rlStart: 0, rlUsed: 0 }; }
1058
+ function usageNumber(v, fallback) { return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback; }
1059
+
1060
+ // Everything in customMetadata that ISN'T one of the reserved provenance/label
1061
+ // keys above — i.e. the caller's own \`--meta key=value\` entries. Surfaced on
1062
+ // every read route (listing, revisions) so a value stored with \`--meta
1063
+ // kind=plan --meta ticket=RUSH-2683\` is actually visible again, not just
1064
+ // write-only (RUSH-2683 review fix).
1065
+ function extraMetaOf(customMetadata) {
1066
+ var out = {};
1067
+ if (!customMetadata) return out;
1068
+ for (var k in customMetadata) {
1069
+ if (RESERVED_METADATA_KEYS.indexOf(k) === -1) out[k] = customMetadata[k];
1070
+ }
1071
+ return out;
1072
+ }
1073
+
1074
+ function escapeHtml(s) {
1075
+ return String(s)
1076
+ .replace(/&/g, '&amp;')
1077
+ .replace(/</g, '&lt;')
1078
+ .replace(/>/g, '&gt;')
1079
+ .replace(/"/g, '&quot;');
1080
+ }
1081
+
1082
+ // The attribution bar: a slim strip prepended to every served HTML page that
1083
+ // makes the object's stamped metadata visible — who shared it, what made it,
1084
+ // when, and (the whole point) a color-coded VISIBILITY cue Google-Drive style.
1085
+ // All values come from customMetadata; nothing new is stamped at publish time,
1086
+ // so this is a pure Worker change deployable with 'agents artifacts share update'.
1087
+ var VIS_ICON = {
1088
+ me: '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><rect x="4" y="11" width="16" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>',
1089
+ org: '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 21h18M6 21V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v17M14 9h4a1 1 0 0 1 1 1v11"/></svg>',
1090
+ unlisted: '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/></svg>',
1091
+ public: '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a15 15 0 0 1 0 18M12 3a15 15 0 0 0 0 18"/></svg>',
1092
+ };
1093
+
1094
+ // Eye glyph for the view-count stat; caret for the owner's interactive chip.
1095
+ var STAT_EYE_ICON = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>';
1096
+ var CARET_ICON = '<svg class="ash-caret" viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.4"><path d="m6 9 6 6 6-6"/></svg>';
1097
+
1098
+ // The owner-only browser script that turns the visibility chip into a live
1099
+ // control. Self-contained IIFE, namespaced under .agents-share-bar; injected only
1100
+ // when the viewer owns the namespace. It reads the current level and each level's
1101
+ // icon/color/label straight from the rendered menu DOM (no embedded config), then
1102
+ // PATCHes the SAME in-place edit route the CLI uses — method PATCH, JSON body
1103
+ // { visibility } — with credentials:'include' so the viewer's __share cookie /
1104
+ // Phoenix identity rides. Optimistic: flip the chip + spinner, then a green check
1105
+ // on 2xx or revert + the server's error text on failure (an org-on-public-inbox
1106
+ // 400 surfaces verbatim). The share page sets no CSP, so inline JS is fine.
1107
+ var ASH_OWNER_JS = \`(function(){
1108
+ var root = document.querySelector('.agents-share-bar');
1109
+ if(!root) return;
1110
+ var chip = root.querySelector('[data-ash-chip]');
1111
+ var menu = root.querySelector('[data-ash-menu]');
1112
+ var toast = root.querySelector('[data-ash-toast]');
1113
+ if(!chip || !menu || !toast) return;
1114
+ var labelEl = chip.querySelector('[data-ash-label]');
1115
+ var chipIc = chip.querySelector('[data-ash-chip-ic]');
1116
+ var busy = false;
1117
+ function opts(){ return menu.querySelectorAll('[data-ash-opt]'); }
1118
+ function currentKey(){ var s = menu.querySelector('.ash-opt.ash-sel'); return s ? s.getAttribute('data-ash-opt') : ''; }
1119
+ function labelFor(key){ var a = opts(); for(var i=0;i<a.length;i++){ if(a[i].getAttribute('data-ash-opt')===key){ var b = a[i].querySelector('b'); return b ? b.textContent : key; } } return key; }
1120
+ function open(){ menu.classList.add('ash-open'); menu.setAttribute('aria-hidden','false'); }
1121
+ function close(){ menu.classList.remove('ash-open'); menu.setAttribute('aria-hidden','true'); }
1122
+ chip.addEventListener('click', function(e){ e.stopPropagation(); if(menu.classList.contains('ash-open')) close(); else open(); });
1123
+ menu.addEventListener('click', function(e){ e.stopPropagation(); });
1124
+ document.addEventListener('click', close);
1125
+ document.addEventListener('keydown', function(e){ if(e.key==='Escape') close(); });
1126
+ function draw(key){
1127
+ var sel = null, a = opts();
1128
+ for(var i=0;i<a.length;i++){ var on = a[i].getAttribute('data-ash-opt')===key; a[i].classList.toggle('ash-sel', on); if(on) sel = a[i]; }
1129
+ if(!sel) return;
1130
+ var ic = sel.querySelector('.ash-opt-ic');
1131
+ var color = ic ? ic.style.color : '';
1132
+ if(color){ chip.style.color = color; chip.style.borderColor = color + '66'; }
1133
+ if(chipIc && ic) chipIc.innerHTML = ic.innerHTML;
1134
+ var b = sel.querySelector('b');
1135
+ if(labelEl && b) labelEl.textContent = b.textContent;
1136
+ }
1137
+ function say(inner, cls){ toast.innerHTML = inner; toast.className = 'ash-toast ash-show' + (cls ? ' ' + cls : ''); }
1138
+ function fade(ms){ setTimeout(function(){ toast.className = 'ash-toast'; }, ms); }
1139
+ function pick(key){
1140
+ close();
1141
+ var prev = currentKey();
1142
+ if(busy || !key || key===prev) return;
1143
+ busy = true;
1144
+ draw(key);
1145
+ var name = labelFor(key);
1146
+ say('<span class="ash-spin"></span> Saving…');
1147
+ fetch(location.pathname, { method:'PATCH', credentials:'include', headers:{'content-type':'application/json'}, body: JSON.stringify({ visibility: key }) })
1148
+ .then(function(res){ return res.json().then(function(j){ return { ok: res.ok, status: res.status, body: j }; }, function(){ return { ok: res.ok, status: res.status, body: {} }; }); })
1149
+ .then(function(r){
1150
+ busy = false;
1151
+ if(r.ok){ say('<span class="ash-ok">\\u2713</span> Now ' + name, 'ash-good'); fade(1600); }
1152
+ else {
1153
+ draw(prev);
1154
+ var msg = (r.body && r.body.error) ? String(r.body.error) : ('Could not update (HTTP ' + r.status + ')');
1155
+ say('<span class="ash-err">\\u2715</span> ' + msg.replace(/[<>&]/g, ' '), 'ash-bad');
1156
+ fade(4000);
1157
+ }
1158
+ }, function(){ busy = false; draw(prev); say('<span class="ash-err">\\u2715</span> Network error \\u2014 not saved', 'ash-bad'); fade(4000); });
1159
+ }
1160
+ var a = opts();
1161
+ for(var i=0;i<a.length;i++){ (function(el){ el.addEventListener('click', function(e){ e.stopPropagation(); pick(el.getAttribute('data-ash-opt')); }); })(a[i]); }
1162
+ })();\`;
1163
+
1164
+ function visibilityChip(visibility, orgDomain) {
1165
+ if (visibility === 'me') return { icon: VIS_ICON.me, label: 'Only you', color: '#f59e0b' };
1166
+ if (visibility === 'org') return { icon: VIS_ICON.org, label: 'Anyone at ' + escapeHtml(orgDomain || 'your organization'), color: '#5b9dff' };
1167
+ if (visibility === 'private') return { icon: VIS_ICON.me, label: 'Protected (link + key)', color: '#f59e0b' };
1168
+ if (visibility === 'unlisted') return { icon: VIS_ICON.unlisted, label: 'Unlisted', color: '#9aa0a6' };
1169
+ return { icon: VIS_ICON.public, label: 'Public', color: '#30a46c' };
1170
+ }
1171
+
1172
+ // A deterministic hue (0-359) from the handle, so a given sharer always gets the
1173
+ // same initials-circle colour without any stored palette.
1174
+ function avatarHue(s) {
1175
+ var h = 0;
1176
+ for (var i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) % 360;
1177
+ return h;
1178
+ }
1179
+
1180
+ // The avatar slot is ALWAYS rendered: a coloured initials circle derived from the
1181
+ // handle. When the object carries an avatar URL (a Gravatar the CLI stamps at
1182
+ // publish, or any future hosted photo), a real img is layered on top; onerror
1183
+ // removes it so the initials underneath show through when the photo 404s. There
1184
+ // is no CSP on the share page, so the inline onerror fallback is honoured.
1185
+ function renderAvatar(handle, avatarUrl) {
1186
+ var h = (handle || '').trim();
1187
+ var initial = escapeHtml((h.charAt(0) || '?').toUpperCase());
1188
+ var bg = 'hsl(' + avatarHue(h) + ',48%,42%)';
1189
+ var inner = '<span class="ash-av-i">' + initial + '</span>';
1190
+ if (avatarUrl) {
1191
+ inner += '<img class="ash-av-img" src="' + escapeHtml(avatarUrl) + '" alt="" loading="lazy" ' +
1192
+ 'referrerpolicy="no-referrer" onerror="this.remove()">';
1193
+ }
1194
+ return '<span class="ash-avatar" style="background:' + bg + ' !important" aria-hidden="true">' + inner + '</span>';
1195
+ }
1196
+
1197
+ // A compact relative time for the "last updated" stat: "just now", "2h ago",
1198
+ // "3d ago", or an ISO date once past ~30 days. Accepts a Date or a parseable
1199
+ // string (R2's obj.uploaded is a Date).
1200
+ function relativeTime(when) {
1201
+ var then = when instanceof Date ? when.getTime() : Date.parse(when);
1202
+ if (!then || isNaN(then)) return '';
1203
+ var diff = Date.now() - then;
1204
+ if (diff < 0) diff = 0;
1205
+ var minute = 60000, hour = 3600000, day = 86400000;
1206
+ if (diff < minute) return 'just now';
1207
+ if (diff < hour) return Math.floor(diff / minute) + 'm ago';
1208
+ if (diff < day) return Math.floor(diff / hour) + 'h ago';
1209
+ if (diff < 30 * day) return Math.floor(diff / day) + 'd ago';
1210
+ return new Date(then).toISOString().slice(0, 10);
1211
+ }
1212
+
1213
+ // The four visibility levels the owner can pick, in menu order. Descriptions
1214
+ // mirror the approved mockup. org always appears — a public-inbox owner still
1215
+ // sees it and lets the server's 400 drive the failure message (never a hidden
1216
+ // client-side rule). orgDomain is the owner's own email domain when known.
1217
+ function visibilityLevels(orgDomain) {
1218
+ return [
1219
+ { key: 'public', label: 'Public', color: '#30a46c', icon: VIS_ICON.public, desc: 'Anyone with the link · preview card · listed in your gallery' },
1220
+ { key: 'unlisted', label: 'Unlisted', color: '#9aa0a6', icon: VIS_ICON.unlisted, desc: 'Anyone with the link · no card · hidden from your gallery' },
1221
+ { key: 'me', label: 'Only you', color: '#f59e0b', icon: VIS_ICON.me, desc: 'Sign-in required · only your account can open it' },
1222
+ { key: 'org', label: 'Anyone at ' + escapeHtml(orgDomain || 'your org'), color: '#5b9dff', icon: VIS_ICON.org, desc: 'Anyone signed in with a ' + escapeHtml(orgDomain || 'workspace-domain') + ' account' },
1223
+ ];
1224
+ }
1225
+
1226
+ function renderVisibilityMenu(current, orgDomain) {
1227
+ var rows = visibilityLevels(orgDomain).map(function (l) {
1228
+ return '<button type="button" class="ash-opt' + (l.key === current ? ' ash-sel' : '') + '" data-ash-opt="' + l.key + '" role="menuitemradio" aria-checked="' + (l.key === current ? 'true' : 'false') + '">' +
1229
+ '<span class="ash-opt-ic" style="color:' + l.color + '">' + l.icon + '</span>' +
1230
+ '<span class="ash-opt-t"><b>' + l.label + '</b><span>' + l.desc + '</span></span>' +
1231
+ '<span class="ash-rd"></span></button>';
1232
+ }).join('');
1233
+ return '<div class="ash-menu" data-ash-menu role="menu" aria-hidden="true"><h4>Who can see this</h4>' + rows + '</div>';
1234
+ }
1235
+
1236
+ function renderOwnerScript() {
1237
+ return '<script>' + ASH_OWNER_JS + '</script>';
1238
+ }
1239
+
1240
+ // opts: { isOwner, ownerDomain, views, uploaded } — all optional. isOwner turns
1241
+ // the visibility chip into a live control (inline dropdown, Variation A) and
1242
+ // injects the owner-only CSS/JS; views/uploaded render the right-side stats
1243
+ // cluster. With no opts the bar is exactly today's static strip.
1244
+ function renderAttributionBar(meta, handle, opts) {
1245
+ var o = opts || {};
1246
+ var cm = meta || {};
1247
+ var visibility = cm.visibility || 'public';
1248
+ var chip = visibilityChip(visibility, cm.org_domain);
1249
+ var avatar = renderAvatar(handle, cm.avatar);
1250
+ var left = '';
1251
+ // The handle is already the public URL namespace, so surfacing it leaks nothing new.
1252
+ if (handle) left += 'Shared by <strong>' + escapeHtml(handle) + '</strong>';
1253
+ if (cm.agent) left += (left ? '<span class="ash-dot">·</span>' : '') + 'Made with ' + escapeHtml(cm.agent);
1254
+
1255
+ // Stats cluster (👁 <n> views · updated <rel>) — right side, left of the chip.
1256
+ var stats = '';
1257
+ var statBits = '';
1258
+ if (o.views != null) {
1259
+ statBits += STAT_EYE_ICON + '<b>' + escapeHtml(String(o.views)) + '</b> ' + (Number(o.views) === 1 ? 'view' : 'views');
1260
+ }
1261
+ if (o.uploaded) {
1262
+ var rel = relativeTime(o.uploaded);
1263
+ if (rel) statBits += (statBits ? '<span class="ash-statsep">·</span>' : '') + 'updated <b>' + escapeHtml(rel) + '</b>';
1264
+ }
1265
+ if (statBits) stats = '<span class="ash-stats" title="page stats">' + statBits + '</span>';
1266
+
1267
+ // The visibility chip: an interactive control for the owner, a static cue for
1268
+ // everyone else (unchanged from today).
1269
+ var chipHtml;
1270
+ var menu = '';
1271
+ var script = '';
1272
+ if (o.isOwner) {
1273
+ chipHtml = '<span class="ash-chip ash-chip-own" data-ash-chip tabindex="0" role="button" aria-haspopup="menu" ' +
1274
+ 'style="color:' + chip.color + ';border-color:' + chip.color + '66">' +
1275
+ '<span data-ash-chip-ic>' + chip.icon + '</span><span data-ash-label>' + chip.label + '</span>' + CARET_ICON + '</span>';
1276
+ menu = renderVisibilityMenu(visibility, o.ownerDomain);
1277
+ script = renderOwnerScript();
1278
+ } else {
1279
+ chipHtml = '<span class="ash-chip" style="color:' + chip.color + ';border-color:' + chip.color + '66">' + chip.icon + '<span>' + chip.label + '</span></span>';
1280
+ }
1281
+
1282
+ var right = stats + chipHtml;
1283
+ if (cm.date) right += '<span class="ash-date">' + escapeHtml(cm.date) + '</span>';
1284
+ // The load-bearing background + base colour ride an INLINE style so the host
1285
+ // page's own CSS can never wash the bar out (inline beats a page stylesheet);
1286
+ // the rest is a namespaced style block with !important on every colour so a
1287
+ // broad page rule (span selector to black, etc.) cannot make the text vanish.
1288
+ // FIXED, full-viewport-width chrome (not sticky-inside-body — that inherited the
1289
+ // page's max-width/margins and rendered as a floating box). html padding-top
1290
+ // pushes the whole page down by the bar's height; flex-wrap:nowrap + ellipsis on
1291
+ // the left keeps the bar exactly one line tall so the push height stays correct.
1292
+ return '<div class="agents-share-bar" role="contentinfo" aria-label="Sharing details" ' +
1293
+ 'style="background:#0b0b0c !important;color:#e8e8e8 !important">' +
1294
+ '<style>' +
1295
+ 'html{padding-top:38px !important}' +
1296
+ '.agents-share-bar{all:initial;position:fixed !important;top:0 !important;left:0 !important;right:0 !important;width:100% !important;z-index:2147483647 !important;box-sizing:border-box;display:flex !important;align-items:center;gap:12px;flex-wrap:nowrap;' +
1297
+ 'padding:8px 16px !important;background:#0b0b0c !important;color:#e8e8e8 !important;border-bottom:1px solid #23232a !important;box-shadow:0 1px 3px rgba(0,0,0,.35) !important;' +
1298
+ 'font:13px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,system-ui,sans-serif !important}' +
1299
+ '.agents-share-bar *{box-sizing:border-box;font-family:inherit}' +
1300
+ '.agents-share-bar .ash-avatar{flex:none;position:relative;width:26px;height:26px;border-radius:50% !important;overflow:hidden;display:inline-flex;align-items:center;justify-content:center;color:#fff !important;font-weight:600;font-size:12px;line-height:1;box-shadow:inset 0 0 0 1px rgba(255,255,255,.14)}' +
1301
+ '.agents-share-bar .ash-av-i{color:#fff !important}' +
1302
+ '.agents-share-bar .ash-av-img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;border-radius:50% !important}' +
1303
+ '.agents-share-bar .ash-left{flex:1 1 auto;min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:#cfd3d9 !important}' +
1304
+ '.agents-share-bar strong{color:#fff !important;font-weight:600}' +
1305
+ '.agents-share-bar .ash-dot{opacity:.4;margin:0 4px}' +
1306
+ '.agents-share-bar .ash-right{flex:none;display:flex;align-items:center;gap:12px}' +
1307
+ '.agents-share-bar .ash-date{color:#9096a0 !important}' +
1308
+ '.agents-share-bar .ash-chip{display:inline-flex;align-items:center;gap:6px;padding:3px 10px;border-radius:999px;border:1px solid;font-weight:600;font-size:12px;white-space:nowrap}' +
1309
+ '.agents-share-bar .ash-chip svg{flex:none;vertical-align:middle}' +
1310
+ '.agents-share-bar .ash-stats{display:inline-flex;align-items:center;gap:5px;color:#9aa0a6 !important;font-size:12px;white-space:nowrap}' +
1311
+ '.agents-share-bar .ash-stats b{color:#c9ced6 !important;font-weight:600}' +
1312
+ '.agents-share-bar .ash-stats svg{flex:none;opacity:.85}' +
1313
+ '.agents-share-bar .ash-statsep{opacity:.35;margin:0 3px}' +
1314
+ (o.isOwner ? OWNER_BAR_CSS : '') +
1315
+ '</style>' +
1316
+ avatar +
1317
+ '<span class="ash-left">' + left + '</span>' +
1318
+ '<span class="ash-right">' + right + '</span>' +
1319
+ menu +
1320
+ (o.isOwner ? '<div class="ash-toast" data-ash-toast></div>' : '') +
1321
+ '</div>' +
1322
+ script;
1323
+ }
1324
+
1325
+ // Owner-only chip/menu/toast styling, added to the bar's <style> only when the
1326
+ // viewer owns the namespace. Namespaced under .agents-share-bar with !important
1327
+ // so the host page's CSS can't wash it out; z-index rides the bar's own stacking.
1328
+ var OWNER_BAR_CSS =
1329
+ '.agents-share-bar .ash-chip-own{cursor:pointer;transition:background .12s}' +
1330
+ '.agents-share-bar .ash-chip-own:hover{background:rgba(255,255,255,.06)}' +
1331
+ '.agents-share-bar .ash-caret{opacity:.6;margin-left:1px;flex:none}' +
1332
+ '.agents-share-bar .ash-menu{position:absolute !important;top:calc(100% + 6px);right:12px;min-width:286px;max-width:calc(100vw - 24px);background:#151517 !important;border:1px solid #2a2a30 !important;border-radius:12px;box-shadow:0 12px 34px rgba(0,0,0,.5);padding:6px;z-index:2147483647;display:none;text-align:left}' +
1333
+ '.agents-share-bar .ash-menu.ash-open{display:block}' +
1334
+ '.agents-share-bar .ash-menu h4{margin:6px 8px 8px;font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:#7c8290 !important;font-weight:700}' +
1335
+ '.agents-share-bar .ash-opt{display:flex;width:100%;text-align:left;align-items:flex-start;gap:10px;padding:8px;border:0;background:none;border-radius:8px;cursor:pointer;color:#e8e8e8 !important;font:inherit;font-size:13px}' +
1336
+ '.agents-share-bar .ash-opt:hover{background:rgba(255,255,255,.05)}' +
1337
+ '.agents-share-bar .ash-opt-ic{flex:none;width:26px;height:26px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;background:rgba(255,255,255,.06)}' +
1338
+ '.agents-share-bar .ash-opt-t{flex:1;min-width:0}' +
1339
+ '.agents-share-bar .ash-opt-t b{display:block;font-size:13px;font-weight:600;color:#f0f1f3 !important}' +
1340
+ '.agents-share-bar .ash-opt-t span{display:block;font-size:11.5px;color:#9096a0 !important;line-height:1.35;margin-top:1px;white-space:normal}' +
1341
+ '.agents-share-bar .ash-rd{flex:none;width:16px;height:16px;border-radius:50%;border:2px solid #4a4f59;margin-top:3px}' +
1342
+ '.agents-share-bar .ash-opt.ash-sel .ash-rd{border-color:#5b9dff;background:radial-gradient(circle at center,#5b9dff 0 5px,transparent 6px)}' +
1343
+ '.agents-share-bar .ash-toast{position:absolute !important;top:calc(100% + 6px);right:12px;max-width:calc(100vw - 24px);background:#151517 !important;border:1px solid #2a2a30 !important;color:#e8e8e8 !important;font-size:12px;padding:7px 12px;border-radius:9px;display:none;align-items:center;gap:7px;z-index:2147483647}' +
1344
+ '.agents-share-bar .ash-toast.ash-show{display:inline-flex}' +
1345
+ '.agents-share-bar .ash-spin{width:12px;height:12px;border:2px solid rgba(255,255,255,.25);border-top-color:#fff;border-radius:50%;animation:ash-sp .6s linear infinite;display:inline-block;flex:none}' +
1346
+ '@keyframes ash-sp{to{transform:rotate(360deg)}}' +
1347
+ '.agents-share-bar .ash-ok{color:#30a46c;font-weight:700}' +
1348
+ '.agents-share-bar .ash-err{color:#ff6b6b;font-weight:700}';
1349
+
1350
+ function injectAttributionBar(html, meta, handle, opts) {
1351
+ var bar = renderAttributionBar(meta, handle, opts);
1352
+ var m = /<body[^>]*>/i.exec(html);
1353
+ if (m) {
1354
+ var at = m.index + m[0].length;
1355
+ return html.slice(0, at) + bar + html.slice(at);
1356
+ }
1357
+ return bar + html;
1358
+ }
1359
+
1360
+ function acceptsHtml(request) {
1361
+ return (request.headers.get('accept') || '').indexOf('text/html') !== -1;
1362
+ }
1363
+
1364
+ // Assets we can embed in a viewer page. Everything else (JSON, .txt, arbitrary
1365
+ // downloads) is served raw — there is nothing useful to wrap it in.
1366
+ function viewableAssetKind(contentType) {
1367
+ var ct = (contentType || '').toLowerCase();
1368
+ if (ct.indexOf('image/') === 0) return 'image';
1369
+ if (ct.indexOf('video/') === 0) return 'video';
1370
+ if (ct.indexOf('audio/') === 0) return 'audio';
1371
+ if (ct.indexOf('application/pdf') === 0) return 'pdf';
1372
+ return '';
1373
+ }
1374
+
1375
+ // A minimal dark viewer page: the attribution bar on top, the asset centered
1376
+ // below. The media element points back at THIS url with ?raw so it loads the
1377
+ // stored bytes (not the viewer recursively) — and that ?raw fetch re-runs the
1378
+ // same me/org gate, so a private asset stays private inside its own viewer.
1379
+ function renderAssetViewer(pathname, kind, meta, handle, opts) {
1380
+ var rawUrl = escapeHtml(pathname + '?raw=1');
1381
+ var name = '';
1382
+ try { name = decodeURIComponent(pathname.split('/').pop() || 'file'); } catch (e) { name = pathname.split('/').pop() || 'file'; }
1383
+ var bar = renderAttributionBar(meta, handle, opts);
1384
+ var media = '';
1385
+ if (kind === 'image') media = '<img src="' + rawUrl + '" alt="' + escapeHtml(name) + '">';
1386
+ else if (kind === 'video') media = '<video src="' + rawUrl + '" controls playsinline></video>';
1387
+ else if (kind === 'audio') media = '<audio src="' + rawUrl + '" controls></audio>';
1388
+ else if (kind === 'pdf') media = '<iframe src="' + rawUrl + '" title="' + escapeHtml(name) + '"></iframe>';
1389
+ return '<!doctype html><html><head><meta charset="utf-8">' +
1390
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
1391
+ '<title>' + escapeHtml(name) + '</title>' +
1392
+ '<style>html,body{margin:0;background:#0f0f11}' +
1393
+ 'body{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:16px;box-sizing:border-box}' +
1394
+ '.ashv{max-width:100%;max-height:calc(100vh - 90px);display:flex;align-items:center;justify-content:center}' +
1395
+ '.ashv img,.ashv video{max-width:100%;max-height:calc(100vh - 90px);display:block;border-radius:8px;box-shadow:0 10px 40px rgba(0,0,0,.5)}' +
1396
+ '.ashv audio{width:min(90vw,560px)}' +
1397
+ '.ashv iframe{width:min(94vw,1000px);height:calc(100vh - 90px);border:0;border-radius:8px;background:#fff}' +
1398
+ '</style></head><body>' + bar + '<div class="ashv">' + media + '</div></body></html>';
1399
+ }
1400
+
1401
+ function json(body, status) {
1402
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
1403
+ }
1404
+
1405
+ // Length-independent constant-time-ish compare (Workers has no timingSafeEqual).
1406
+ function safeEqual(a, b) {
1407
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
1408
+ const la = a.length, lb = b.length;
1409
+ let out = la ^ lb;
1410
+ for (let i = 0; i < la; i++) out |= a.charCodeAt(i) ^ b.charCodeAt(i % lb || 0);
1411
+ return out === 0 && la === lb;
1412
+ }
1413
+
1414
+ // URL-safety, not collision-resistance. Two values that differ only in
1415
+ // case/punctuation share a prefix.
1416
+ function sanitizeNamespace(s) {
1417
+ return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
1418
+ }
1419
+
1420
+ // Public handle: email local-part, plus-tag stripped. Must match CLI handleFromEmail.
1421
+ function handleFromEmail(email) {
1422
+ if (!email) return '';
1423
+ const local = String(email).split('@')[0] || '';
1424
+ const beforePlus = local.split('+')[0] || local;
1425
+ return sanitizeNamespace(beforePlus);
1426
+ }
1427
+
1428
+ function phoenixHandle(auth) {
1429
+ return handleFromEmail(auth.email) || sanitizeNamespace(auth.owner);
1430
+ }
1431
+
1432
+ // First writer of a handle owns it. Later PUTs from the same userId are fine;
1433
+ // a different userId whose email local-part collides gets 409, not a silent
1434
+ // overwrite — EXCEPT when the verified Phoenix email matches the claim's
1435
+ // recorded email exactly: that is the same human re-authenticated under a new
1436
+ // userId (an account move), and the claim transfers to them instead of
1437
+ // dead-ending (PHNX-3547). The transfer also re-stamps owner on the old
1438
+ // account's objects so PATCH/DELETE keep working.
1439
+ async function assertHandleOwner(bucket, handle, userId, email) {
1440
+ // The __handles/<handle> claim object is the authoritative first-writer record
1441
+ // of ownership. When it exists it decides ownership OUTRIGHT: the recorded
1442
+ // userId may write, anyone else is refused. Consult it FIRST — a stray page
1443
+ // under the namespace stamped with a different owner (e.g. a BYO WRITE_TOKEN
1444
+ // publish, which stamps owner = SHARE_NAMESPACE rather than a userId, or a page
1445
+ // published under the same human's earlier userId before a re-auth) must not
1446
+ // lock the rightful claim holder out of their own handle (PHNX-3291).
1447
+ const key = '__handles/' + handle;
1448
+ const existing = await bucket.get(key);
1449
+ if (existing) {
1450
+ const meta = existing.customMetadata || {};
1451
+ const claimed = meta.userId;
1452
+ if (claimed && claimed !== userId) {
1453
+ // Same verified email, different userId → account move, not a rival:
1454
+ // rebind the claim and migrate the old owner's objects. Legacy claims
1455
+ // written before the claim recorded an email cannot prove this and keep
1456
+ // the permanent 409.
1457
+ if (email && meta.email && String(meta.email).toLowerCase() === String(email).toLowerCase()) {
1458
+ await transferHandle(bucket, handle, claimed, userId, email);
1459
+ return {};
1460
+ }
1461
+ return { error: json({ error: 'handle taken', handle: handle }, 409) };
1462
+ }
1463
+ return {};
1464
+ }
1465
+ // No claim object yet — fall back to the page-owner scan so a colliding email
1466
+ // local-part cannot PUT/DELETE another account's objects in the window before
1467
+ // the claim exists. (claimHandle writes the claim on the first Phoenix PUT.)
1468
+ // Only a DIFFERENT Phoenix userId blocks: a BYO WRITE_TOKEN publish stamps
1469
+ // owner = the namespace (=== handle) rather than a userId, so it is not a rival
1470
+ // identity and must not lock the handle's first Phoenix claimant out (PHNX-3291).
1471
+ const list = await bucket.list({ prefix: handle + '/', include: ['customMetadata'] });
1472
+ for (const o of list.objects || []) {
1473
+ const owner = o.customMetadata && o.customMetadata.owner;
1474
+ if (owner && owner !== userId && owner !== handle) {
1475
+ return { error: json({ error: 'handle taken', handle: handle }, 409) };
1476
+ }
1477
+ }
1478
+ return {};
1479
+ }
1480
+
1481
+ // Account-move recovery (PHNX-3547): the claim's recorded userId held the handle;
1482
+ // the caller proves the SAME verified email under a NEW userId. Rebind the claim
1483
+ // and re-stamp owner on every object the old userId owned under this prefix, so
1484
+ // the moved account keeps full control of its shares. Objects owned by anyone
1485
+ // else (BYO namespace stamps, a pre-claim stray) are left untouched.
1486
+ async function transferHandle(bucket, handle, oldUserId, newUserId, email) {
1487
+ await bucket.put('__handles/' + handle, JSON.stringify({ userId: newUserId, email: email }), {
1488
+ httpMetadata: { contentType: 'application/json' },
1489
+ customMetadata: { userId: newUserId, email: email, visibility: 'unlisted' },
1490
+ });
1491
+ let cursor;
1492
+ do {
1493
+ const list = await bucket.list({ prefix: handle + '/', cursor: cursor, include: ['customMetadata'] });
1494
+ for (const o of list.objects || []) {
1495
+ const owner = o.customMetadata && o.customMetadata.owner;
1496
+ if (!owner || owner !== oldUserId) continue;
1497
+ const obj = await bucket.get(o.key);
1498
+ if (!obj) continue;
1499
+ const headers = new Headers();
1500
+ if (typeof obj.writeHttpMetadata === 'function') obj.writeHttpMetadata(headers);
1501
+ const customMetadata = { ...(obj.customMetadata || {}), owner: newUserId };
1502
+ await bucket.put(o.key, obj.body, {
1503
+ httpMetadata: headers.get('content-type') ? { contentType: headers.get('content-type') } : undefined,
1504
+ customMetadata: customMetadata,
1505
+ });
1506
+ }
1507
+ cursor = list.truncated ? list.cursor : undefined;
1508
+ } while (cursor);
1509
+ }
1510
+
1511
+ async function claimHandle(bucket, handle, userId, email) {
1512
+ const owned = await assertHandleOwner(bucket, handle, userId, email);
1513
+ if (owned.error) return owned;
1514
+ const key = '__handles/' + handle;
1515
+ // Write (or rewrite) so a same-user republish resets object Age against the
1516
+ // bucket's 366-day lifecycle — otherwise the claim can expire while pages stay
1517
+ // live. The claim also records the verified email: it is what lets a future
1518
+ // same-email/different-userId request prove an account move and recover the
1519
+ // handle instead of hitting the permanent 409.
1520
+ await bucket.put(key, JSON.stringify({ userId: userId, email: email }), {
1521
+ httpMetadata: { contentType: 'application/json' },
1522
+ customMetadata: { userId: userId, email: email || '', visibility: 'unlisted' },
1523
+ });
1524
+ return {};
1525
+ }
1526
+
1527
+ function normalizeVisibility(raw) {
1528
+ const v = (raw || '').trim().toLowerCase();
1529
+ if (!v || v === 'public') return { value: 'public' };
1530
+ if (v === 'unlisted' || v === 'private' || v === 'me' || v === 'org') return { value: v };
1531
+ return { error: json({ error: 'visibility must be public, unlisted, private, me, or org' }, 400) };
1532
+ }
1533
+
1534
+ function emailDomain(email) {
1535
+ if (!email) return '';
1536
+ const at = String(email).lastIndexOf('@');
1537
+ if (at < 0) return '';
1538
+ return String(email).slice(at + 1).toLowerCase();
1539
+ }
1540
+
1541
+ function isHiddenFromGallery(visibility) {
1542
+ return visibility === 'unlisted' || visibility === 'private' || visibility === 'me' || visibility === 'org';
1543
+ }
1544
+
1545
+ function isIdentityGated(visibility) {
1546
+ return visibility === 'me' || visibility === 'org';
1547
+ }
1548
+
1549
+ function managedCoverHeaders(visibility) {
1550
+ const headers = new Headers({ 'content-type': 'image/png' });
1551
+ // Token-gated (private) + identity-gated (me/org) covers must never be
1552
+ // cached by a shared proxy, and never indexed. RFC 9111: public on an
1553
+ // Authorization response authorizes reuse for later unauthenticated
1554
+ // requests keyed on /user/slug.png (PHNX-3676).
1555
+ if (isIdentityGated(visibility) || visibility === 'private') {
1556
+ headers.set('cache-control', 'private, no-store');
1557
+ headers.set('X-Robots-Tag', 'noindex');
1558
+ } else {
1559
+ headers.set('cache-control', 'public, max-age=31536000, immutable');
1560
+ if (visibility === 'unlisted') headers.set('X-Robots-Tag', 'noindex');
1561
+ }
1562
+ return headers;
1563
+ }
1564
+
1565
+ // Gate a me/org read given the ALREADY-RESOLVED viewer identity. Pure/sync: the
1566
+ // caller resolves the viewer once (it also needs the identity for the ownership
1567
+ // check) and both the page GET and the ?revisions=json path share this gate.
1568
+ async function gateVisibility(url, env, obj, identity) {
1569
+ const visibility = (obj.customMetadata && obj.customMetadata.visibility) || 'public';
1570
+ if (!isIdentityGated(visibility)) return null;
1571
+ if (!identity) return bounceToLogin(url, env);
1572
+ if (!viewerMayRead(visibility, obj.customMetadata, identity)) {
1573
+ // A 'me' page reads for its stamped owner (the fast path above) OR for the
1574
+ // holder of the namespace's handle claim — the same authority PATCH and
1575
+ // DELETE use. Without this, the claim holder who takes a fleet/BYO-stamped
1576
+ // or pre-stamp page to 'me' (owner = namespace, or none) would be locked
1577
+ // out of her own page: PATCH says 200, GET says 404. The stamp itself stays
1578
+ // untouched (expiry refunds credit the stamped ledger), so the read gate
1579
+ // has to consult the claim rather than the stamp.
1580
+ const handle = decodeURIComponent(url.pathname).split('/').filter(Boolean)[0] || '';
1581
+ if (visibility === 'me' && handle && (await holdsHandleClaim(env.BUCKET, handle, identity.userId))) return null;
1582
+ return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
1583
+ }
1584
+ return null;
1585
+ }
1586
+
1587
+ // True when userId is the recorded holder of the __handles/<handle> claim.
1588
+ // Read-only: never transfers or writes a claim (that is claimHandle /
1589
+ // assertHandleOwner's job on the write paths).
1590
+ async function holdsHandleClaim(bucket, handle, userId) {
1591
+ if (!handle || !userId) return false;
1592
+ const claim = await bucket.get('__handles/' + handle);
1593
+ if (!claim) return false;
1594
+ const claimed = claim.customMetadata && claim.customMetadata.userId;
1595
+ return !!claimed && claimed === userId;
1596
+ }
1597
+
1598
+ // SHA-256 hex of a string — the form a 'private' object's stored
1599
+ // 'viewer-token-hash' takes. Both the PUT (hash-on-store) and the read gate use
1600
+ // this, so a token minted by the CLI matches byte-for-byte (PHNX-3654).
1601
+ async function sha256Hex(text) {
1602
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(text)));
1603
+ return bufToHex(digest);
1604
+ }
1605
+
1606
+ // The viewer key a reader presents for a token-gated ('private') page: the ?k=
1607
+ // query param first (the shape the CLI emits — https://host/<u>/<s>?k=<token>),
1608
+ // then an Authorization: Bearer token as an alternative for scripted callers.
1609
+ function readViewerKey(request, url) {
1610
+ const q = url.searchParams.get('k');
1611
+ if (q) return q;
1612
+ const bearer = (request.headers.get('authorization') || '').replace(/^Bearer\\s+/i, '');
1613
+ return bearer || '';
1614
+ }
1615
+
1616
+ // Gate a 'private' (token-gated) read (PHNX-3654). Returns a 404 Response when
1617
+ // the request may NOT read, or null when it may. A miss ALWAYS 404s — never a
1618
+ // 401 and never a distinct "wrong key" — so a token-gated page never even leaks
1619
+ // that it exists, exactly like a wrong me/org viewer. The namespace owner
1620
+ // (resolved identity whose userId stamped the object) is let through without the
1621
+ // key so 'share open' and the owner's own browsing still work. Constant-time
1622
+ // compare (safeEqual) over the stored SHA-256 hash keeps the check timing-safe.
1623
+ async function gateTokenRead(request, url, obj, identity) {
1624
+ const meta = obj.customMetadata || {};
1625
+ const visibility = meta.visibility || 'public';
1626
+ if (visibility !== 'private') return null;
1627
+ const notFound = function () {
1628
+ return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
1629
+ };
1630
+ // Owner bypass: the signed-in owner of the page reads their own private page
1631
+ // without the key (mirrors 'me').
1632
+ if (identity && meta.owner && meta.owner === identity.userId) return null;
1633
+ const stored = meta['viewer-token-hash'] || '';
1634
+ // Fail closed: a private object with no stored hash can never be matched, so it
1635
+ // is unreadable rather than accidentally public.
1636
+ if (!stored) return notFound();
1637
+ const presented = readViewerKey(request, url);
1638
+ if (!presented) return notFound();
1639
+ const presentedHash = await sha256Hex(presented);
1640
+ if (!safeEqual(presentedHash, stored)) return notFound();
1641
+ return null;
1642
+ }
1643
+
1644
+ // Per-slug view counter, stored as a SEPARATE R2 object under __views/<path> so
1645
+ // counting a view never rewrites the page object (which would reset its uploaded
1646
+ // timestamp and corrupt "last updated"). Best-effort telemetry: a read/write
1647
+ // failure must never break page serving, so both degrade to a no-op rather than
1648
+ // throwing. R2 has no atomic increment, so two simultaneous views can race and
1649
+ // lose a count — acceptable for an approximate visitor count.
1650
+ async function readViews(env, path) {
1651
+ try {
1652
+ const obj = await env.BUCKET.get('__views/' + path);
1653
+ if (!obj) return 0;
1654
+ const raw = typeof obj.text === 'function' ? await obj.text() : '';
1655
+ const n = parseInt(raw, 10);
1656
+ return Number.isFinite(n) && n >= 0 ? n : 0;
1657
+ } catch {
1658
+ return 0;
1659
+ }
1660
+ }
1661
+
1662
+ async function writeViews(env, path, count) {
1663
+ try {
1664
+ await env.BUCKET.put('__views/' + path, String(count), {
1665
+ httpMetadata: { contentType: 'text/plain; charset=utf-8' },
1666
+ });
1667
+ } catch {
1668
+ // best-effort: a failed counter write must never surface to the visitor
1669
+ }
1670
+ }
1671
+
1672
+ // --- PHNX-3542 per-user usage ledger (R2 conditional-put CAS) ---------------
1673
+ // The ledger is a single R2 object at __usage/<owner> holding the running
1674
+ // { bytes, count, plan, rlStart, rlUsed } for one user. It mirrors the __views /
1675
+ // __handles precedent: a __-prefixed key, GET-blocked and outside every gallery/
1676
+ // listing/revision prefix. R2 has no atomic increment, so mutations use a
1677
+ // read → mutate → conditional-put loop (onlyIf.etagMatches), the same primitive
1678
+ // the PATCH metadata-edit path already relies on.
1679
+ function usageKey(owner) { return '__usage/' + sanitizeNamespace(owner); }
1680
+
1681
+ async function readUsage(env, owner) {
1682
+ const obj = await env.BUCKET.get(usageKey(owner));
1683
+ if (!obj) return { etag: null, usage: freshUsage() };
1684
+ let usage = freshUsage();
1685
+ try {
1686
+ const raw = typeof obj.text === 'function' ? await obj.text() : '';
1687
+ const parsed = JSON.parse(raw);
1688
+ if (parsed && typeof parsed === 'object') {
1689
+ usage = {
1690
+ bytes: usageNumber(parsed.bytes, 0),
1691
+ count: usageNumber(parsed.count, 0),
1692
+ plan: typeof parsed.plan === 'string' ? parsed.plan : DEFAULT_SHARE_PLAN,
1693
+ rlStart: usageNumber(parsed.rlStart, 0),
1694
+ rlUsed: usageNumber(parsed.rlUsed, 0),
1695
+ };
1696
+ }
1697
+ } catch (e) {
1698
+ // Malformed ledger — treat as fresh zero but KEEP the etag so the next CAS
1699
+ // put overwrites the corrupt object rather than looping against it forever.
1700
+ }
1701
+ return { etag: obj.etag || null, usage: usage };
1702
+ }
1703
+
1704
+ async function writeUsageCas(env, owner, prevEtag, usage) {
1705
+ const body = JSON.stringify(usage);
1706
+ const opts = { httpMetadata: { contentType: 'application/json' } };
1707
+ if (prevEtag) {
1708
+ // Existing object: conditional put. R2 returns null when the etag no longer
1709
+ // matches (a concurrent writer won the race) → report failure so the caller
1710
+ // re-reads and retries.
1711
+ opts.onlyIf = { etagMatches: prevEtag };
1712
+ const res = await env.BUCKET.put(usageKey(owner), body, opts);
1713
+ return res !== null;
1714
+ }
1715
+ // Fresh key: plain create. Neither R2 nor the test harness exposes a
1716
+ // conditional-create predicate, so the only race is two simultaneous
1717
+ // first-creates of the same owner's ledger — a benign, one-time bounded loss.
1718
+ await env.BUCKET.put(usageKey(owner), body, opts);
1719
+ return true;
1720
+ }
1721
+
1722
+ // CAS retry loop. fn(usage) returns { reject: Response } to fail loud without
1723
+ // committing, or { commit: usage, result } to persist and return result. On CAS
1724
+ // contention it re-reads and retries; exhausting the retries fails loud with 503.
1725
+ async function withUsage(env, owner, fn) {
1726
+ for (let attempt = 0; attempt < 6; attempt++) {
1727
+ const state = await readUsage(env, owner);
1728
+ const outcome = fn(state.usage);
1729
+ if (outcome.reject) return outcome.reject;
1730
+ const ok = await writeUsageCas(env, owner, state.etag, outcome.commit);
1731
+ if (ok) return outcome.result;
1732
+ }
1733
+ return json({ error: 'usage ledger contended, retry' }, 503);
1734
+ }
1735
+
1736
+ function rateLimited(retryAfterSec, ratePerHour) {
1737
+ return new Response(
1738
+ JSON.stringify({ error: 'rate limit: too many publishes, retry later', retryAfterSec: retryAfterSec, ratePerHour: ratePerHour }),
1739
+ { status: 429, headers: { 'content-type': 'application/json', 'retry-after': String(retryAfterSec) } },
1740
+ );
1741
+ }
1742
+
1743
+ // Charge one authed PUT against the owner's ledger. Rate → per-file cap → object
1744
+ // count → byte quota, each failing loud (429 / 413) before anything is written.
1745
+ // Returns { error: Response } on any rejection, else { limits } (the resolved
1746
+ // plan limits, reused by the post-write real-size reconcile). Managed only: the
1747
+ // caller guards on auth.kind === 'phoenix'.
1748
+ async function chargeShareWrite(env, auth, params) {
1749
+ const unlimited = hasUnlimitedStorage(env.SHARE_UNLIMITED_STORAGE, auth);
1750
+ const now = Date.now();
1751
+ const out = await withUsage(env, auth.owner, function (usage) {
1752
+ const limits = planLimits(usage.plan);
1753
+ // Rate limit — only a user-initiated page PUT counts (countRate). A fixed 1h
1754
+ // window: reset when the window has rolled over, otherwise reject at the cap.
1755
+ if (params.countRate) {
1756
+ if (now - usage.rlStart >= RATE_WINDOW_MS) { usage.rlStart = now; usage.rlUsed = 0; }
1757
+ if (usage.rlUsed >= limits.ratePerHour) {
1758
+ const retryAfterSec = Math.max(1, Math.ceil((usage.rlStart + RATE_WINDOW_MS - now) / 1000));
1759
+ return { reject: rateLimited(retryAfterSec, limits.ratePerHour) };
1760
+ }
1761
+ usage.rlUsed += 1;
1762
+ }
1763
+ // Per-file size cap.
1764
+ if (typeof params.fileBytes === 'number' && params.fileBytes > limits.maxFileBytes) {
1765
+ return { reject: json({ error: 'file too large', maxBytes: limits.maxFileBytes, gotBytes: params.fileBytes }, 413) };
1766
+ }
1767
+ // Object (canonical page) count.
1768
+ if (params.newCanonical) {
1769
+ if (!unlimited && usage.count + 1 > limits.maxObjects) {
1770
+ return { reject: json({ error: 'artifact limit reached', maxObjects: limits.maxObjects }, 413) };
1771
+ }
1772
+ usage.count += 1;
1773
+ }
1774
+ // Total byte quota. charge may be negative on a shrink — clamp at >= 0.
1775
+ if (!unlimited && usage.bytes + params.charge > limits.maxBytes) {
1776
+ return { reject: json({ error: 'storage limit reached', maxBytes: limits.maxBytes, usedBytes: usage.bytes }, 413) };
1777
+ }
1778
+ usage.bytes = Math.max(0, usage.bytes + params.charge);
1779
+ return { commit: usage, result: { limits: limits } };
1780
+ });
1781
+ if (out instanceof Response) return { error: out };
1782
+ return { limits: out.limits };
1783
+ }
1784
+
1785
+ // Read a request body fully into memory, BOUNDED: abort the moment it exceeds
1786
+ // maxBytes, so a chunked/streaming body can never buffer more than the cap (plus
1787
+ // one in-flight chunk) and OOM the Worker. Returns { oversize: true, size } once
1788
+ // the cap is passed (size is a lower bound, >= cap), else { bytes, size } with
1789
+ // the exact bytes. A body-less request yields an empty buffer. This is what lets
1790
+ // enforcement key on the REAL size instead of a spoofable declared header.
1791
+ async function readBodyBounded(request, maxBytes) {
1792
+ if (!request.body || typeof request.body.getReader !== 'function') {
1793
+ const buf = await request.arrayBuffer();
1794
+ const bytes = new Uint8Array(buf);
1795
+ if (bytes.byteLength > maxBytes) return { oversize: true, size: bytes.byteLength };
1796
+ return { bytes: bytes, size: bytes.byteLength };
1797
+ }
1798
+ const reader = request.body.getReader();
1799
+ const chunks = [];
1800
+ let size = 0;
1801
+ while (true) {
1802
+ const step = await reader.read();
1803
+ if (step.done) break;
1804
+ const chunk = step.value;
1805
+ size += chunk.byteLength;
1806
+ if (size > maxBytes) {
1807
+ try { await reader.cancel(); } catch (e) { /* best-effort */ }
1808
+ return { oversize: true, size: size };
1809
+ }
1810
+ chunks.push(chunk);
1811
+ }
1812
+ const out = new Uint8Array(size);
1813
+ let offset = 0;
1814
+ for (let i = 0; i < chunks.length; i++) { out.set(chunks[i], offset); offset += chunks[i].byteLength; }
1815
+ return { bytes: out, size: size };
1816
+ }
1817
+
1818
+ // Refund on DELETE / expiry. Never rejects, never creates a ledger: if the owner
1819
+ // was never charged (no __usage object) it is a pure no-op.
1820
+ async function refundShareWrite(env, owner, params) {
1821
+ for (let attempt = 0; attempt < 6; attempt++) {
1822
+ const state = await readUsage(env, owner);
1823
+ if (!state.etag) return; // no ledger — owner never charged, nothing to refund
1824
+ state.usage.bytes = Math.max(0, state.usage.bytes - (params.refund || 0));
1825
+ if (params.freeCanonical) state.usage.count = Math.max(0, state.usage.count - 1);
1826
+ if (await writeUsageCas(env, owner, state.etag, state.usage)) return;
1827
+ }
1828
+ }
1829
+
1830
+ function viewerMayRead(visibility, meta, identity) {
1831
+ if (visibility === 'me') {
1832
+ const owner = meta && meta.owner;
1833
+ return !!owner && owner === identity.userId;
1834
+ }
1835
+ if (visibility === 'org') {
1836
+ const stamped = meta && meta.org_domain;
1837
+ if (!stamped) return false;
1838
+ return emailDomain(identity.email) === String(stamped).toLowerCase();
1839
+ }
1840
+ return true;
1841
+ }
1842
+
1843
+ function bounceToLogin(url, env) {
1844
+ const base = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
1845
+ if (!base) return json({ error: 'phoenix login is not configured' }, 401);
1846
+ return new Response(null, {
1847
+ status: 302,
1848
+ headers: { Location: base + '/login?return=' + encodeURIComponent(url.toString()) },
1849
+ });
1850
+ }
1851
+
1852
+ function readCookie(request, name) {
1853
+ const header = request.headers.get('Cookie') || '';
1854
+ const parts = header.split(';');
1855
+ for (let i = 0; i < parts.length; i++) {
1856
+ const p = parts[i];
1857
+ const eq = p.indexOf('=');
1858
+ if (eq < 0) continue;
1859
+ if (p.slice(0, eq).trim() === name) return p.slice(eq + 1).trim();
1860
+ }
1861
+ return '';
1862
+ }
1863
+
1864
+ function toB64Url(s) {
1865
+ const bytes = new TextEncoder().encode(s);
1866
+ let bin = '';
1867
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
1868
+ return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');
1869
+ }
1870
+
1871
+ function fromB64Url(s) {
1872
+ const pad = s.length % 4 === 0 ? '' : '='.repeat(4 - (s.length % 4));
1873
+ const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + pad;
1874
+ const bin = atob(b64);
1875
+ const bytes = new Uint8Array(bin.length);
1876
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
1877
+ return new TextDecoder().decode(bytes);
1878
+ }
1879
+
1880
+ function bufToHex(buf) {
1881
+ return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
1882
+ }
1883
+
1884
+ async function hmacHex(secret, data) {
1885
+ const key = await crypto.subtle.importKey(
1886
+ 'raw',
1887
+ new TextEncoder().encode(secret),
1888
+ { name: 'HMAC', hash: 'SHA-256' },
1889
+ false,
1890
+ ['sign'],
1891
+ );
1892
+ const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(data));
1893
+ return bufToHex(sig);
1894
+ }
1895
+
1896
+ async function signShareCookie(identity, env) {
1897
+ const secret = typeof env.WRITE_TOKEN === 'string' ? env.WRITE_TOKEN : '';
1898
+ if (!secret) return '';
1899
+ const exp = Math.floor(Date.now() / 1000) + SHARE_COOKIE_MAX_AGE;
1900
+ const payload = identity.userId + '|' + (identity.email || '') + '|' + exp;
1901
+ const sig = await hmacHex(secret, payload);
1902
+ const value = toB64Url(payload) + '.' + sig;
1903
+ return SHARE_COOKIE + '=' + value + '; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=' + SHARE_COOKIE_MAX_AGE;
1904
+ }
1905
+
1906
+ // A short-lived login ticket, self-signed with the same HMAC secret as the cookie
1907
+ // but DOMAIN-SEPARATED (the signature covers a 'ticket:'-prefixed payload), so a
1908
+ // ticket value can never be replayed as a cookie value or vice versa. It rides in
1909
+ // the ?phoenix_ticket= param for exactly one navigation; resolveViewer verifies it
1910
+ // locally and exchanges it for the __share cookie. TTL is deliberately tiny — it
1911
+ // only has to survive the round-trip from CLI mint to the browser opening the URL.
1912
+ var SELF_TICKET_MAX_AGE = 120;
1913
+
1914
+ async function signSelfTicket(identity, env) {
1915
+ const secret = typeof env.WRITE_TOKEN === 'string' ? env.WRITE_TOKEN : '';
1916
+ if (!secret || !identity || !identity.userId) return '';
1917
+ const exp = Math.floor(Date.now() / 1000) + SELF_TICKET_MAX_AGE;
1918
+ const payload = identity.userId + '|' + (identity.email || '') + '|' + exp;
1919
+ const sig = await hmacHex(secret, 'ticket:' + payload);
1920
+ return toB64Url(payload) + '.' + sig;
1921
+ }
1922
+
1923
+ async function verifySelfTicket(ticket, env) {
1924
+ const secret = typeof env.WRITE_TOKEN === 'string' ? env.WRITE_TOKEN : '';
1925
+ if (!secret || !ticket) return null;
1926
+ const dot = ticket.lastIndexOf('.');
1927
+ if (dot < 1) return null;
1928
+ let payload;
1929
+ try {
1930
+ payload = fromB64Url(ticket.slice(0, dot));
1931
+ } catch {
1932
+ return null;
1933
+ }
1934
+ const sig = ticket.slice(dot + 1);
1935
+ const expected = await hmacHex(secret, 'ticket:' + payload);
1936
+ if (!safeEqual(sig, expected)) return null;
1937
+ const first = payload.indexOf('|');
1938
+ const last = payload.lastIndexOf('|');
1939
+ if (first < 0 || last <= first) return null;
1940
+ const userId = payload.slice(0, first);
1941
+ const email = payload.slice(first + 1, last);
1942
+ const exp = Number(payload.slice(last + 1));
1943
+ if (!userId || !Number.isFinite(exp) || Math.floor(Date.now() / 1000) > exp) return null;
1944
+ return { userId: userId, email: email };
1945
+ }
1946
+
1947
+ // Single-use enforcement for a self-signed ticket: claim its signature the first
1948
+ // time it is redeemed, and reject any later presentation of the same ticket. The
1949
+ // HMAC + short TTL stop forgery and bound the window, but without this a ticket the
1950
+ // CLI printed (--json / --no-open / a browser-open failure) could be replayed by
1951
+ // anyone who captured that output before it expired, minting the owner's 7-day
1952
+ // cookie a second time. Get-then-put mirrors claimHandle's one-time-claim pattern;
1953
+ // the marker rides a __-prefixed key (GET-blocked, excluded from every listing).
1954
+ async function consumeSelfTicket(env, sig) {
1955
+ if (!sig) return false;
1956
+ const key = '__ticket-used/' + sig;
1957
+ const existing = await env.BUCKET.get(key);
1958
+ if (existing) return false;
1959
+ await env.BUCKET.put(key, '1', {
1960
+ httpMetadata: { contentType: 'text/plain' },
1961
+ customMetadata: { visibility: 'unlisted' },
1962
+ });
1963
+ return true;
1964
+ }
1965
+
1966
+ async function identityFromCookie(request, env) {
1967
+ const secret = typeof env.WRITE_TOKEN === 'string' ? env.WRITE_TOKEN : '';
1968
+ if (!secret) return null;
1969
+ const raw = readCookie(request, SHARE_COOKIE);
1970
+ if (!raw) return null;
1971
+ const dot = raw.lastIndexOf('.');
1972
+ if (dot < 1) return null;
1973
+ let payload;
1974
+ try {
1975
+ payload = fromB64Url(raw.slice(0, dot));
1976
+ } catch {
1977
+ return null;
1978
+ }
1979
+ const sig = raw.slice(dot + 1);
1980
+ const expected = await hmacHex(secret, payload);
1981
+ if (!safeEqual(sig, expected)) return null;
1982
+ const first = payload.indexOf('|');
1983
+ const last = payload.lastIndexOf('|');
1984
+ if (first < 0 || last <= first) return null;
1985
+ const userId = payload.slice(0, first);
1986
+ const email = payload.slice(first + 1, last);
1987
+ const cookieExp = Number(payload.slice(last + 1));
1988
+ if (!userId || !Number.isFinite(cookieExp) || Math.floor(Date.now() / 1000) > cookieExp) return null;
1989
+ return { userId: userId, email: email };
1990
+ }
1991
+
1992
+ async function redeemTicket(ticket, env) {
1993
+ const base = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
1994
+ if (!base || !ticket) return null;
1995
+ let res;
1996
+ try {
1997
+ res = await fetch(base + '/api/v1/auth/ticket', {
1998
+ method: 'POST',
1999
+ headers: { 'content-type': 'application/json' },
2000
+ body: JSON.stringify({ ticket: ticket }),
2001
+ });
2002
+ } catch {
2003
+ return null;
2004
+ }
2005
+ if (!res.ok) return null;
2006
+ let body;
2007
+ try {
2008
+ body = await res.json();
2009
+ } catch {
2010
+ return null;
2011
+ }
2012
+ if (!body || typeof body.userId !== 'string' || !body.userId) return null;
2013
+ return { userId: body.userId, email: typeof body.email === 'string' ? body.email : '' };
2014
+ }
2015
+
2016
+ async function resolveViewer(request, env, url) {
2017
+ const claims = await hooks.verifyPhoenixToken(request, env);
2018
+ if (claims && typeof claims.userId === 'string' && claims.userId) {
2019
+ return { identity: { userId: claims.userId, email: typeof claims.email === 'string' ? claims.email : '' } };
2020
+ }
2021
+ const cookieId = await identityFromCookie(request, env);
2022
+ if (cookieId) return { identity: cookieId };
2023
+ const ticket = url.searchParams.get('phoenix_ticket');
2024
+ if (!ticket) return {};
2025
+ // Prefer the locally-verifiable self-signed ticket (PHNX-3370, no network), and
2026
+ // enforce single use by claiming its signature on first redemption — a captured
2027
+ // ticket replayed within its TTL finds it already spent. Fall back to the
2028
+ // external identity-server redeem for tickets it issued.
2029
+ let redeemed = await verifySelfTicket(ticket, env);
2030
+ if (redeemed) {
2031
+ const sig = ticket.slice(ticket.lastIndexOf('.') + 1);
2032
+ if (!(await consumeSelfTicket(env, sig))) redeemed = null;
2033
+ } else {
2034
+ redeemed = await redeemTicket(ticket, env);
2035
+ }
2036
+ if (!redeemed) return { error: json({ error: 'invalid ticket' }, 401) };
2037
+ const cookie = await signShareCookie(redeemed, env);
2038
+ if (!cookie) return { error: json({ error: 'phoenix login is not configured' }, 401) };
2039
+ url.searchParams.delete('phoenix_ticket');
2040
+ const headers = new Headers();
2041
+ headers.set('Location', url.toString());
2042
+ headers.append('Set-Cookie', cookie);
2043
+ return { redirect: new Response(null, { status: 302, headers: headers }) };
2044
+ }
2045
+
2046
+ function extractHtmlMeta(html, field) {
2047
+ const pattern = field === 'title'
2048
+ ? /<title[^>]*>([\\s\\S]*?)<\\/title>/i
2049
+ : /<meta[^>]+(?:name|property)=["'](?:description|og:description)["'][^>]+content=["']([^"']*)["'][^>]*>/i;
2050
+ const match = pattern.exec(html);
2051
+ return match ? match[1].replace(/<[^>]*>/g, '').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').trim() : '';
2052
+ }
2053
+
2054
+ let rendererReady;
2055
+ async function renderOgCard(input) {
2056
+ if (!rendererReady) {
2057
+ rendererReady = Promise.all([
2058
+ initYoga(yogaWasm).then(function (yoga) { initSatori(yoga); }),
2059
+ initResvg(resvgWasm),
2060
+ ]);
2061
+ }
2062
+ await rendererReady;
2063
+ const visibilityLabels = {
2064
+ public: 'PUBLIC',
2065
+ unlisted: 'UNLISTED',
2066
+ private: 'PROTECTED',
2067
+ me: 'ONLY YOU',
2068
+ org: input.orgDomain ? 'ANYONE AT ' + input.orgDomain.toUpperCase() : 'ORGANIZATION',
2069
+ };
2070
+ const node = {
2071
+ type: 'div',
2072
+ props: {
2073
+ style: { width: '100%', height: '100%', display: 'flex', flexDirection: 'column', background: '#0a0a0a', color: '#f5f5f5', padding: '68px 76px 58px', fontFamily: 'Inter' },
2074
+ children: [
2075
+ { type: 'div', props: { style: { display: 'flex', color: '#a3e635', fontFamily: 'JetBrains Mono', fontSize: 25, fontWeight: 600, letterSpacing: '-0.5px' }, children: 'share.getrush.ai' } },
2076
+ { type: 'div', props: { style: { display: 'flex', flexDirection: 'column', flexGrow: 1, justifyContent: 'center', maxWidth: 1050 }, children: [
2077
+ { type: 'div', props: { style: { display: 'flex', fontSize: 66, lineHeight: 1.06, fontWeight: 700, letterSpacing: '-2.8px', maxHeight: 218, overflow: 'hidden' }, children: input.title || 'Shared artifact' } },
2078
+ input.description ? { type: 'div', props: { style: { display: 'flex', marginTop: 24, color: '#a3a3a3', fontSize: 27, lineHeight: 1.35, maxHeight: 74, overflow: 'hidden' }, children: input.description } } : null,
2079
+ ].filter(Boolean) } },
2080
+ { type: 'div', props: { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderTop: '1px solid #262626', paddingTop: 25, fontSize: 21, color: '#a3a3a3' }, children: [
2081
+ { type: 'div', props: { style: { display: 'flex' }, children: [
2082
+ { type: 'span', props: { style: { color: '#737373' }, children: 'shared by ' } },
2083
+ { type: 'span', props: { style: { marginLeft: 7, color: '#f5f5f5', fontWeight: 700 }, children: '@' + input.handle } },
2084
+ ] } },
2085
+ { type: 'div', props: { style: { display: 'flex', border: '1px solid #3f3f46', borderRadius: 999, padding: '9px 17px', color: '#d4d4d8', fontFamily: 'JetBrains Mono', fontSize: 16, letterSpacing: '1px' }, children: visibilityLabels[input.visibility] || 'PUBLIC' } },
2086
+ ] } },
2087
+ ],
2088
+ },
2089
+ };
2090
+ const svg = await satori(node, {
2091
+ width: 1200,
2092
+ height: 630,
2093
+ fonts: [
2094
+ { name: 'Inter', data: interRegular, weight: 400, style: 'normal' },
2095
+ { name: 'Inter', data: interBold, weight: 700, style: 'normal' },
2096
+ { name: 'JetBrains Mono', data: jetbrainsMono, weight: 600, style: 'normal' },
2097
+ ],
2098
+ });
2099
+ return new Resvg(svg, { fitTo: { mode: 'width', value: 1200 } }).render().asPng();
2100
+ }
2101
+
2102
+ async function defaultVerifyPhoenixToken(request, env) {
2103
+ const presented = (request.headers.get('authorization') || '').replace(/^Bearer\\s+/i, '');
2104
+ if (!presented) return null;
2105
+ const base = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
2106
+ if (!base) return null;
2107
+ let res;
2108
+ try {
2109
+ res = await fetch(base + '/api/v1/auth/me', {
2110
+ method: 'GET',
2111
+ headers: { Authorization: 'Bearer ' + presented },
2112
+ });
2113
+ } catch {
2114
+ return null;
2115
+ }
2116
+ if (!res.ok) return null;
2117
+ let body;
2118
+ try {
2119
+ body = await res.json();
2120
+ } catch {
2121
+ return null;
2122
+ }
2123
+ if (!body || typeof body.userId !== 'string' || !body.userId) return null;
2124
+ return { userId: body.userId, email: typeof body.email === 'string' ? body.email : '' };
2125
+ }
2126
+
2127
+ // Write principals, in order: WRITE_TOKEN equality (admin/BYO), then a Phoenix
2128
+ // bearer, then the signed-in viewer's __share cookie. The cookie is an
2129
+ // HMAC-signed {userId,email} proof (identityFromCookie verifies it), which lets
2130
+ // the shared page's inline visibility control PATCH with credentials:'include'
2131
+ // and no bearer — the browser has the identity cookie, not a token. It cannot be
2132
+ // abused cross-site: the cookie is SameSite=Lax, which blocks it from riding a
2133
+ // cross-origin non-GET (CSRF), and namespace/owner enforcement on PUT/PATCH/
2134
+ // DELETE still confines a cookie holder to their own pages. 401 when none apply.
2135
+ async function authorizeWrite(request, env) {
2136
+ const presented = (request.headers.get('authorization') || '').replace(/^Bearer\\s+/i, '');
2137
+ if (presented) {
2138
+ if (env.WRITE_TOKEN && safeEqual(presented, env.WRITE_TOKEN)) {
2139
+ return { kind: 'byo', owner: env.SHARE_NAMESPACE || 'byo' };
2140
+ }
2141
+ const claims = await hooks.verifyPhoenixToken(request, env);
2142
+ if (claims && typeof claims.userId === 'string' && claims.userId) {
2143
+ return { kind: 'phoenix', owner: claims.userId, email: typeof claims.email === 'string' ? claims.email : '' };
2144
+ }
2145
+ }
2146
+ const cookieId = await identityFromCookie(request, env);
2147
+ if (cookieId && cookieId.userId) {
2148
+ return { kind: 'phoenix', owner: cookieId.userId, email: typeof cookieId.email === 'string' ? cookieId.email : '' };
2149
+ }
2150
+ return { error: json({ error: 'unauthorized' }, 401) };
2151
+ }
2152
+ `;
2153
+ }
2154
+ //# sourceMappingURL=worker-template.js.map