@phnx-labs/artifacts-cli 0.8.3-pre.1 → 0.9.1

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.
@@ -2,6 +2,8 @@ import { buildSync } from 'esbuild';
2
2
  import { dirname } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { BODY_REVISION_META, normalizeSharePath } from '../collab.js';
5
+ import { SHARE_PUBLISH_WORKER_SOURCE } from './worker-publish-template.js';
6
+ import { SHARE_MEDIA_WORKER_SOURCE } from './worker-media-template.js';
5
7
  let bundledWorker;
6
8
  let nodeWorkerScript;
7
9
  /** Bundle the Worker renderer into an ES module plus workerd-compiled WASM modules. */
@@ -102,6 +104,10 @@ export default {
102
104
 
103
105
  const firstSeg = path.split('/').filter(Boolean)[0] || '';
104
106
  if (firstSeg === '__collab' && collabConfig(env)) return handleCollab(request, env, url, path);
107
+ // Deepgram's side of the media job (PHNX-4287): the single-use source link
108
+ // and the signed callback. Both 404 unless the media keys are bound.
109
+ if (path === '__media/source') return handleMediaSource(request, env, url);
110
+ if (path === '__media/callback') return handleMediaCallback(request, env, url, ctx);
105
111
  if ((request.method === 'GET' || request.method === 'HEAD') && firstSeg.startsWith('__')) {
106
112
  return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
107
113
  }
@@ -121,160 +127,28 @@ export default {
121
127
  return json({ ticket: ticket }, 200);
122
128
  }
123
129
 
130
+ const multipartAction = url.searchParams.get('multipart');
131
+ if (multipartAction) {
132
+ const uploaded = await handleMultipartUpload(request, env, url, path, multipartAction);
133
+ // A finished video upload starts its transcript + summary job in the
134
+ // background; a replayed complete finds the job already claimed.
135
+ if (multipartAction === 'complete' && uploaded.status === 200 && ctx && typeof ctx.waitUntil === 'function') {
136
+ ctx.waitUntil(startMediaAfterUpload(env, url.origin, path));
137
+ }
138
+ return uploaded;
139
+ }
140
+
141
+ const mediaAction = url.searchParams.get('media');
142
+ if (mediaAction === 'status' || mediaAction === 'retry') {
143
+ return handleMediaRoute(request, env, url, path, mediaAction, ctx);
144
+ }
145
+
124
146
  if (request.method === 'PUT') {
125
147
  const auth = await authorizeWrite(request, env);
126
148
  if (auth.error) return auth.error;
127
- const vis = normalizeVisibility(request.headers.get('x-share-visibility'));
128
- if (vis.error) return vis.error;
129
- const visibility = vis.value;
130
- if (visibility === 'me' || visibility === 'org') {
131
- const phoenixBase = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
132
- if (auth.kind !== 'phoenix' || !phoenixBase) {
133
- return json({ error: 'visibility me/org requires Phoenix identity' }, 400);
134
- }
135
- if (visibility === 'org') {
136
- const domain = emailDomain(auth.email);
137
- if (!domain) return json({ error: 'org visibility requires a verified email domain' }, 400);
138
- if (PUBLIC_INBOX_DOMAINS.indexOf(domain) !== -1) {
139
- return json({ error: 'org visibility cannot use a public email domain', domain: domain }, 400);
140
- }
141
- }
142
- }
143
- // Token-gated read auth (PHNX-3654). A 'private' page is served only to a
144
- // request carrying the matching viewer key; we store just its SHA-256 hash
145
- // so the secret never lands in R2 metadata. Any write principal (Phoenix or
146
- // BYO WRITE_TOKEN) may publish 'private' — the gate is the token, not an
147
- // identity, unlike me/org. The token is mandatory: a private page with no
148
- // stored hash fails closed on read, so refuse the write instead.
149
- let viewerTokenHash = '';
150
- if (visibility === 'private') {
151
- const rawToken = request.headers.get('x-share-viewer-token') || '';
152
- if (!rawToken) return json({ error: 'visibility private requires a viewer token' }, 400);
153
- viewerTokenHash = await sha256Hex(rawToken);
154
- }
155
- // Who may comment (PHNX-3835). Absent means the visibility's default,
156
- // resolved at read time, so a later visibility change moves it too.
157
- const commentsHeader = request.headers.get('x-share-comments');
158
- if (commentsHeader !== null && !isCommentPolicy(commentsHeader)) {
159
- return json({ error: 'comments must be off, audience, or signed_in' }, 400);
160
- }
161
- const segments = path.split('/').filter(Boolean);
162
- if (auth.kind === 'phoenix') {
163
- // The caller's handle is normally derived from the email local-part. An
164
- // explicit x-share-handle (the CLI's --handle, PHNX-3547) lets a Phoenix
165
- // user choose a DIFFERENT free handle — the escape hatch when their
166
- // derived handle is taken or they want a vanity namespace. Sanitized to
167
- // the same [a-z0-9-] shape; claim rules below bind it first-writer-writes,
168
- // exactly like a derived handle.
169
- const requestedRaw = request.headers.get('x-share-handle') || '';
170
- const requested = sanitizeNamespace(requestedRaw);
171
- if (requestedRaw && (!requested || requested.length > 63)) {
172
- return json({ error: 'invalid handle', handle: requestedRaw }, 400);
173
- }
174
- const expected = requested || phoenixHandle(auth);
175
- if (!expected || segments[0] !== expected) {
176
- return json({ error: 'namespace mismatch', owner: expected }, 403);
177
- }
178
- const claimed = await claimHandle(env.BUCKET, expected, auth.owner, auth.email || '');
179
- if (claimed.error) return claimed.error;
180
- }
181
- const expiresAt = request.headers.get('x-share-expires-at') || '';
182
- // 'unlisted' hides the page from the public gallery + JSON listing while
183
- // keeping the direct URL world-readable (capability URL, not secret).
184
- // me/org are also hidden from gallery/listing; GET is identity-gated
185
- // and always sends X-Robots-Tag: noindex (same as unlisted).
186
- const contentType = request.headers.get('content-type') || 'text/html; charset=utf-8';
187
- // Provenance (RUSH-2683): captured client-side from the exec env/git/clock,
188
- // never invented here — a header is simply absent when the CLI had nothing
189
- // to say. --meta entries ride one JSON header; reserved keys are stripped
190
- // from that JSON UNCONDITIONALLY (not just overwritten when a provenance
191
- // header happens to be present) so a same-named x-share-meta entry can
192
- // never smuggle through on a publish that carries no agent/session/host/
193
- // repo/date at all — e.g. a human publishing outside an agent session, or
194
- // outside a git checkout.
195
- // Full-Unicode headers (PHNX-2786): the CLI always sends the latin1-safe
196
- // x-share-<field> (what a pre-Unicode Worker read), and when the fold was
197
- // lossy ALSO a percent-encoded x-share-<field>-u companion plus an
198
- // x-share-encoding: percent opt-in. Prefer the decoded companion when the
199
- // opt-in is present, so a Japanese/emoji title/label/--meta renders in full
200
- // instead of (unnamed) or a dropped glyph; a malformed companion falls
201
- // back to the folded value rather than failing the publish.
202
- const usePercent = (request.headers.get('x-share-encoding') || '') === 'percent';
203
- const readText = (name) => {
204
- const folded = request.headers.get('x-share-' + name) || '';
205
- if (usePercent) {
206
- const encoded = request.headers.get('x-share-' + name + '-u');
207
- if (encoded) {
208
- try {
209
- return decodeURIComponent(encoded);
210
- } catch (e) {
211
- return folded;
212
- }
213
- }
214
- }
215
- return folded;
216
- };
217
- const agent = readText('agent');
218
- const session = readText('session');
219
- const host = readText('host');
220
- const repo = readText('repo');
221
- const date = readText('date');
222
- const avatar = readText('avatar');
223
- const label = readText('label');
224
- const ogTitle = readText('og-title');
225
- const ogDescription = readText('og-description');
226
- const labelSource = request.headers.get('x-share-label-source') || '';
227
- let extraMeta = {};
228
- // The -u meta companion carries the whole raw object percent-encoded, so a
229
- // single decode+parse recovers full-Unicode keys and values; fall back to
230
- // the per-value-folded x-share-meta when it is absent or malformed.
231
- const metaEncoded = usePercent ? request.headers.get('x-share-meta-u') : null;
232
- if (metaEncoded) {
233
- try {
234
- const parsed = JSON.parse(decodeURIComponent(metaEncoded));
235
- if (parsed && typeof parsed === 'object') extraMeta = parsed;
236
- } catch (e) {
237
- // malformed unicode meta companion — fall through to the folded header
238
- }
239
- }
240
- if (!Object.keys(extraMeta).length) {
241
- const metaHeader = request.headers.get('x-share-meta');
242
- if (metaHeader) {
243
- try {
244
- const parsed = JSON.parse(metaHeader);
245
- if (parsed && typeof parsed === 'object') extraMeta = parsed;
246
- } catch {
247
- // malformed --meta header — ignore rather than fail the whole publish
248
- }
249
- }
250
- }
251
- const customMetadata = { ...extraMeta };
252
- // Strip every reserved key UNCONDITIONALLY before re-applying the real
253
- // provenance below — an if(value)-guarded overwrite alone leaves a
254
- // same-named --meta entry in place whenever the real header is absent.
255
- for (const reservedKey of RESERVED_METADATA_KEYS) {
256
- delete customMetadata[reservedKey];
257
- }
258
- if (expiresAt) customMetadata['expires-at'] = expiresAt;
259
- customMetadata['visibility'] = visibility;
260
- if (viewerTokenHash) customMetadata['viewer-token-hash'] = viewerTokenHash;
261
- const owner =
262
- auth.kind === 'phoenix'
263
- ? auth.owner
264
- : (env.SHARE_NAMESPACE || segments[0] || 'byo');
265
- if (owner) customMetadata['owner'] = owner;
266
- if (visibility === 'org') customMetadata['org_domain'] = emailDomain(auth.email);
267
- if (agent) customMetadata['agent'] = agent;
268
- if (session) customMetadata['session'] = session;
269
- if (host) customMetadata['host'] = host;
270
- if (repo) customMetadata['repo'] = repo;
271
- if (date) customMetadata['date'] = date;
272
- if (avatar) customMetadata['avatar'] = avatar;
273
- if (label) customMetadata['label'] = label;
274
- if (labelSource) customMetadata['label-source'] = labelSource;
275
- if (ogTitle) customMetadata['og-title'] = ogTitle;
276
- if (ogDescription) customMetadata['og-description'] = ogDescription;
277
- if (commentsHeader !== null) customMetadata['comment-policy'] = commentsHeader;
149
+ const publish = await preparePublish(request, env, path, auth);
150
+ if (publish.error) return publish.error;
151
+ const { visibility, commentsHeader, segments, expiresAt, contentType, customMetadata } = publish;
278
152
 
279
153
  // Revision retention (RUSH-2683): R2 has no native object versioning, so a
280
154
  // republish over an EXISTING key first copies the current object to
@@ -339,6 +213,14 @@ export default {
339
213
  if (revision) customMetadata['body-revision'] = revision;
340
214
  }
341
215
 
216
+ // R2 multipart completion is an unconditional canonical write. Serialize
217
+ // every canonical mutation through the same per-path CAS lock so a normal
218
+ // PUT cannot land between multipart complete's final check and its write.
219
+ const mutationHolder = 'put:' + crypto.randomUUID();
220
+ const mutationLock = await acquirePathMutationLock(env.BUCKET, path, mutationHolder, 'mutation');
221
+ if (!mutationLock) return json({ error: 'another write is active for this path' }, 409);
222
+ try {
223
+
342
224
  // Revision retention + quota charge + canonical write as a BOUNDED
343
225
  // compare-and-swap loop (PHNX-3547). The old code read the current object,
344
226
  // archived it, then overwrote the canonical key UNCONDITIONALLY: two
@@ -391,11 +273,13 @@ export default {
391
273
  if (chargeNewCanonical) chargedNewCanonical = true;
392
274
  }
393
275
 
276
+ let attemptRevisionKey = '';
394
277
  if (!noRevision && existing) {
395
278
  const existingHeaders = new Headers();
396
- if (typeof existing.writeHttpMetadata === 'function') existing.writeHttpMetadata(existingHeaders);
279
+ existing.writeHttpMetadata(existingHeaders);
397
280
  const existingContentType = existingHeaders.get('content-type');
398
281
  const revKey = path + '/rev-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
282
+ attemptRevisionKey = revKey;
399
283
  await env.BUCKET.put(revKey, existing.body, {
400
284
  httpMetadata: existingContentType ? { contentType: existingContentType } : undefined,
401
285
  customMetadata: existing.customMetadata || {},
@@ -403,6 +287,13 @@ export default {
403
287
  }
404
288
 
405
289
  const putOpts = { httpMetadata: { contentType }, customMetadata };
290
+ if (!(await pathMutationLockOwned(env.BUCKET, path, mutationHolder))) {
291
+ if (attemptRevisionKey) await env.BUCKET.delete(attemptRevisionKey);
292
+ if (auth.kind === 'phoenix' && (chargedAlready || chargedNewCanonical)) {
293
+ await refundShareWrite(env, auth.owner, { refund: chargedAlready, freeCanonical: chargedNewCanonical });
294
+ }
295
+ return json({ error: 'publish conflict: path lock changed, retry the publish' }, 409);
296
+ }
406
297
  // Existing objects use the bare R2Object#etag for CAS; missing objects
407
298
  // use R2's create-only condition so a concurrent first writer wins loud.
408
299
  if (existing && existing.etag) putOpts.onlyIf = { etagMatches: existing.etag };
@@ -426,10 +317,15 @@ export default {
426
317
  }
427
318
  return json({ error: 'publish conflict: another write landed first, retry the publish' }, 409);
428
319
  }
320
+ // A video published in one request (under the multipart threshold) gets the
321
+ // same transcript + summary job a multipart upload does.
322
+ if (auth.kind === 'phoenix' && String(contentType).toLowerCase().startsWith('video/') && ctx && typeof ctx.waitUntil === 'function') {
323
+ ctx.waitUntil(startMediaAfterUpload(env, url.origin, path));
324
+ }
429
325
  // A managed republish may change the title/description. Invalidate only
430
326
  // its generated sibling so the next crawler receives a fresh card; BYO
431
327
  // publishes send no OG metadata and keep their explicitly uploaded cover.
432
- if (ogTitle) await env.BUCKET.delete(path + '.png');
328
+ if (customMetadata['og-title']) await env.BUCKET.delete(path + '.png');
433
329
  // Register only a page comments can anchor to. A failed registration
434
330
  // never fails the publish: the page is stored, and the caller is told.
435
331
  // Threads carry over only from a live registered page at this address.
@@ -453,6 +349,9 @@ export default {
453
349
  json({ ok: true, url: url.origin + '/' + path, expiresAt: expiresAt || null, unlisted: visibility === 'unlisted', visibility }, 200),
454
350
  registration,
455
351
  );
352
+ } finally {
353
+ await releasePathMutationLock(env.BUCKET, path, mutationHolder);
354
+ }
456
355
  }
457
356
 
458
357
  if (request.method === 'PATCH') {
@@ -460,21 +359,12 @@ export default {
460
359
  if (auth.error) return auth.error;
461
360
  const segments = path.split('/').filter(Boolean);
462
361
  if (segments.length < 2) return json({ error: 'metadata edit requires /<username>/<slug>' }, 400);
463
- if (auth.kind === 'phoenix') {
464
- const expected = phoenixHandle(auth);
465
- const handle = segments[0];
466
- if (!expected || handle !== expected) {
467
- // An alternate handle must already have a claim; unlike PUT, PATCH
468
- // cannot create a new namespace as a side effect.
469
- const claim = handle ? await env.BUCKET.get('__handles/' + handle) : null;
470
- if (!claim) return json({ error: 'namespace mismatch', owner: expected }, 403);
471
- }
472
- // Use the same ownership path as PUT/DELETE so the same verified email
473
- // under a new userId transfers the claim and re-stamps old pages before
474
- // the per-object ownership check below.
475
- const owned = await assertHandleOwner(env.BUCKET, handle, auth.owner, auth.email || '');
476
- if (owned.error) return json({ error: 'forbidden' }, 403);
477
- }
362
+ const notOwner = await assertNamespaceOwner(env, auth, segments);
363
+ if (notOwner) return notOwner;
364
+ const mutationHolder = 'patch:' + crypto.randomUUID();
365
+ const mutationLock = await acquirePathMutationLock(env.BUCKET, path, mutationHolder, 'mutation');
366
+ if (!mutationLock) return json({ error: 'conflict', key: path, detail: 'another write is active for this path' }, 409);
367
+ try {
478
368
  const existing = await env.BUCKET.get(path);
479
369
  if (!existing) return json({ error: 'share not found', key: path }, 404);
480
370
  // Ownership was settled above, the same way DELETE settles it: WRITE_TOKEN
@@ -569,13 +459,16 @@ export default {
569
459
  // ordering and list JSON do not pretend the page was republished today.
570
460
  if (!metadata['published-at']) metadata['published-at'] = new Date(existing.uploaded).toISOString();
571
461
  const httpHeaders = new Headers();
572
- if (typeof existing.writeHttpMetadata === 'function') existing.writeHttpMetadata(httpHeaders);
462
+ existing.writeHttpMetadata(httpHeaders);
573
463
  const putOpts = { httpMetadata: httpHeaders, customMetadata: metadata };
574
464
  // onlyIf.etagMatches wants the bare hash (R2Object#etag), not the
575
465
  // quoted HTTP header form (R2Object#httpEtag) — passing httpEtag 500s
576
466
  // on a real Workers R2 binding ("Conditional ETag should not be
577
467
  // wrapped in quotes"), a defect only a real R2 backend surfaces.
578
468
  if (existing.etag) putOpts.onlyIf = { etagMatches: existing.etag };
469
+ if (!(await pathMutationLockOwned(env.BUCKET, path, mutationHolder))) {
470
+ return json({ error: 'conflict: path lock changed', key: path }, 409);
471
+ }
579
472
  const putResult = await env.BUCKET.put(path, existing.body, putOpts);
580
473
  if (putResult === null) return json({ error: 'conflict', key: path }, 409);
581
474
  // A generated cover copies the canonical visibility gate into its own R2
@@ -598,6 +491,9 @@ export default {
598
491
  json({ ok: true, url: url.origin + '/' + path, label: metadata.label || null, meta: extraMetaOf(metadata), visibility: metadata.visibility || 'public', previousVisibility: previousVisibility, comments: commentPolicyOf(metadata) }, 200),
599
492
  registration,
600
493
  );
494
+ } finally {
495
+ await releasePathMutationLock(env.BUCKET, path, mutationHolder);
496
+ }
601
497
  }
602
498
 
603
499
  if (request.method === 'GET' || request.method === 'HEAD') {
@@ -616,7 +512,7 @@ export default {
616
512
  if (url.searchParams.get('format') === 'json') {
617
513
  const scope = await resolveListingScope(request, env, segments[0]);
618
514
  if (scope.error) return scope.error;
619
- return renderListing(env.BUCKET, url.origin, segments[0], request.method, scope.includeHidden);
515
+ return renderListing(env, url.origin, segments[0], request.method, scope.includeHidden);
620
516
  }
621
517
  return renderGallery(env.BUCKET, url.origin, segments[0], request.method);
622
518
  }
@@ -740,34 +636,86 @@ export default {
740
636
  }
741
637
  }
742
638
 
743
- const obj = await env.BUCKET.get(path);
744
- if (!obj) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
745
- const expiresAt = obj.customMetadata && obj.customMetadata['expires-at'];
639
+ // Metadata-only lookup first. Visibility, token, and expiry all decide
640
+ // whether a caller may read before R2 is asked for any object bytes.
641
+ const gateObj = typeof env.BUCKET.head === 'function'
642
+ ? await env.BUCKET.head(path)
643
+ : await env.BUCKET.get(path);
644
+ if (!gateObj) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
645
+ // A video's transcript, captions, and summary answer to the video's gate.
646
+ if (isMediaDerived(gateObj)) return serveMediaDerived(request, env, url, path, gateObj);
647
+ const expiresAt = gateObj.customMetadata && gateObj.customMetadata['expires-at'];
746
648
  if (expiresAt && Date.now() > Date.parse(expiresAt)) {
747
- await env.BUCKET.delete(path);
748
- // PHNX-3542: expiry is a lazy delete with no auth context. Refund the
749
- // stamped owner's quota (bytes + object count) best-effort — a refund
750
- // failure must never break serving the 410. A canonical page is 2
751
- // segments; covers are excluded (never charged) so refund is safe here
752
- // because only canonical pages ever carry an expires-at.
753
- const expiredOwner = obj.customMetadata && obj.customMetadata['owner'];
754
- if (expiredOwner && !path.endsWith('.png')) {
755
- try {
756
- await refundShareWrite(env, expiredOwner, {
757
- refund: typeof obj.size === 'number' ? obj.size : 0,
758
- freeCanonical: path.split('/').filter(Boolean).length === 2,
759
- });
760
- } catch (e) {
761
- // best-effort: serving the expiry 410 must never depend on the refund
649
+ const expiredVisibility = (gateObj.customMetadata && gateObj.customMetadata.visibility) || 'public';
650
+ const expiredHeaders = function (retry) {
651
+ const headers = new Headers({ 'content-type': 'text/plain' });
652
+ if (retry) { headers.set('cache-control', 'no-store'); headers.set('retry-after', '1'); }
653
+ if (isIdentityGated(expiredVisibility) || expiredVisibility === 'private') {
654
+ headers.set('cache-control', 'private, no-store');
655
+ headers.set('X-Robots-Tag', 'noindex');
762
656
  }
657
+ return headers;
658
+ };
659
+ const expiryHolder = 'expiry:' + crypto.randomUUID();
660
+ const expiryLock = await acquirePathMutationLock(env.BUCKET, path, expiryHolder, 'mutation');
661
+ if (!expiryLock) {
662
+ return new Response('expired object is changing; retry', {
663
+ status: 409,
664
+ headers: expiredHeaders(true),
665
+ });
763
666
  }
764
- // An expired slug is reusable, so its threads go with it, off the
765
- // response path like the view counter.
766
- const expiredCollab = collabConfig(env);
767
- if (expiredCollab && obj.customMetadata && obj.customMetadata['body-revision'] && path.split('/').filter(Boolean).length === 2 && ctx && typeof ctx.waitUntil === 'function') {
768
- ctx.waitUntil(purgeShare(expiredCollab, url, path));
667
+ try {
668
+ // Re-read under the shared canonical lock. An etag mismatch means a
669
+ // predecessor changed the path after the metadata gate; never delete or
670
+ // refund against that stale snapshot, and never serve its expired bytes.
671
+ const current = typeof env.BUCKET.head === 'function'
672
+ ? await env.BUCKET.head(path)
673
+ : await env.BUCKET.get(path);
674
+ if (!current) {
675
+ return new Response('gone — this link has expired', { status: 410, headers: expiredHeaders(false) });
676
+ }
677
+ const currentExpiry = current.customMetadata && current.customMetadata['expires-at'];
678
+ if (current.etag !== gateObj.etag || !currentExpiry || Date.now() <= Date.parse(currentExpiry)) {
679
+ return new Response('object changed; retry', {
680
+ status: 409,
681
+ headers: expiredHeaders(true),
682
+ });
683
+ }
684
+ if (!(await pathMutationLockOwned(env.BUCKET, path, expiryHolder))) {
685
+ return new Response('expired object is changing; retry', {
686
+ status: 409,
687
+ headers: expiredHeaders(true),
688
+ });
689
+ }
690
+ await env.BUCKET.delete(path);
691
+ // PHNX-3542: expiry is a lazy delete with no auth context. Refund the
692
+ // stamped owner's quota (bytes + object count) best-effort — a refund
693
+ // failure must never break serving the 410. A canonical page is 2
694
+ // segments; covers are excluded (never charged) so refund is safe here
695
+ // because only canonical pages ever carry an expires-at.
696
+ const expiredOwner = current.customMetadata && current.customMetadata['owner'];
697
+ if (expiredOwner && !path.endsWith('.png')) {
698
+ try {
699
+ await refundShareWrite(env, expiredOwner, {
700
+ refund: typeof current.size === 'number' ? current.size : 0,
701
+ freeCanonical: path.split('/').filter(Boolean).length === 2,
702
+ });
703
+ } catch (e) {
704
+ // best-effort: serving the expiry 410 must never depend on the refund
705
+ }
706
+ }
707
+ // An expired video's derived files go with it (best-effort, after the refund).
708
+ if (path.split('/').filter(Boolean).length === 2) await deleteMediaDerived(env, path);
709
+ // An expired slug is reusable, so its threads go with it, off the
710
+ // response path like the view counter.
711
+ const expiredCollab = collabConfig(env);
712
+ if (expiredCollab && current.customMetadata && current.customMetadata['body-revision'] && path.split('/').filter(Boolean).length === 2 && ctx && typeof ctx.waitUntil === 'function') {
713
+ ctx.waitUntil(purgeShare(expiredCollab, url, path));
714
+ }
715
+ return new Response('gone — this link has expired', { status: 410, headers: expiredHeaders(false) });
716
+ } finally {
717
+ await releasePathMutationLock(env.BUCKET, path, expiryHolder);
769
718
  }
770
- return new Response('gone — this link has expired', { status: 410, headers: { 'content-type': 'text/plain' } });
771
719
  }
772
720
  // Resolve the viewer ONCE — needed both to gate me/org reads AND to decide
773
721
  // whether THIS viewer OWNS this namespace (the interactive visibility
@@ -776,27 +724,81 @@ export default {
776
724
  // FAILURE (expired/consumed/unreachable) must only gate a page that needs
777
725
  // identity — a public/unlisted page never invoked ticket redemption before
778
726
  // this refactor, so a stale ticket there must serve anonymously, not 401.
779
- const visibility = (obj.customMetadata && obj.customMetadata.visibility) || 'public';
727
+ const visibility = (gateObj.customMetadata && gateObj.customMetadata.visibility) || 'public';
780
728
  const viewer = await resolveViewer(request, env, url);
781
- if (viewer.redirect) return viewer.redirect;
782
- if (viewer.error && isIdentityGated(visibility)) return viewer.error;
729
+ if (viewer.redirect) {
730
+ if (isIdentityGated(visibility)) {
731
+ viewer.redirect.headers.set('cache-control', 'private, no-store');
732
+ viewer.redirect.headers.set('X-Robots-Tag', 'noindex');
733
+ }
734
+ return viewer.redirect;
735
+ }
736
+ if (viewer.error && isIdentityGated(visibility)) {
737
+ viewer.error.headers.set('cache-control', 'private, no-store');
738
+ viewer.error.headers.set('X-Robots-Tag', 'noindex');
739
+ return viewer.error;
740
+ }
783
741
  const identity = viewer.identity || null;
784
- const denied = await gateVisibility(url, env, obj, identity);
785
- if (denied) return denied;
742
+ const denied = await gateVisibility(url, env, gateObj, identity);
743
+ if (denied) {
744
+ denied.headers.set('cache-control', 'private, no-store');
745
+ denied.headers.set('X-Robots-Tag', 'noindex');
746
+ return denied;
747
+ }
786
748
  // Token-gated read auth (PHNX-3654): a 'private' page is served only to a
787
749
  // request carrying the matching viewer key (?k= or Bearer), or to its owner.
788
750
  // A miss returns 404 — never leaking that the page exists — exactly like a
789
751
  // wrong me/org viewer.
790
- const tokenDenied = await gateTokenRead(request, url, obj, identity);
791
- if (tokenDenied) return tokenDenied;
752
+ const tokenDenied = await gateTokenRead(request, url, gateObj, identity);
753
+ if (tokenDenied) {
754
+ tokenDenied.headers.set('cache-control', 'private, no-store');
755
+ tokenDenied.headers.set('X-Robots-Tag', 'noindex');
756
+ return tokenDenied;
757
+ }
792
758
  // The owner of the namespace (their handle === the first path segment) gets
793
759
  // an interactive visibility control; everyone else keeps the static cue.
794
760
  const isOwner = !!identity && handleFromEmail(identity.email) === firstSeg;
795
761
  const ownerDomain = identity ? emailDomain(identity.email) : '';
762
+ let range = null;
763
+ const requestedRange = request.method === 'GET' ? request.headers.get('range') : null;
764
+ if (requestedRange) range = parseByteRange(requestedRange, gateObj.size);
765
+ if (requestedRange && !range) {
766
+ const invalidHeaders = new Headers({
767
+ 'accept-ranges': 'bytes',
768
+ 'content-range': 'bytes */' + gateObj.size,
769
+ 'content-length': '0',
770
+ });
771
+ if (isIdentityGated(visibility) || visibility === 'private') {
772
+ invalidHeaders.set('cache-control', 'private, no-store');
773
+ invalidHeaders.set('X-Robots-Tag', 'noindex');
774
+ }
775
+ return new Response(null, { status: 416, headers: invalidHeaders });
776
+ }
777
+ // HTML is transformed to inject attribution, so byte offsets no longer
778
+ // describe the served representation. Ignore Range and serve the complete
779
+ // attributed page; media/assets retain normal byte-range semantics.
780
+ if (range) {
781
+ const gateHeaders = new Headers();
782
+ gateObj.writeHttpMetadata(gateHeaders);
783
+ if ((gateHeaders.get('content-type') || '').indexOf('text/html') !== -1) range = null;
784
+ }
785
+ let obj = await env.BUCKET.get(path, range ? { range: { offset: range.offset, length: range.length } } : undefined);
786
+ if (!obj) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
787
+ // Do not serve bytes authorized against stale metadata if a concurrent
788
+ // publish changed the object between head() and get().
789
+ if (gateObj.etag && obj.etag && gateObj.etag !== obj.etag) {
790
+ const conflictHeaders = new Headers({ 'content-type': 'text/plain', 'retry-after': '1' });
791
+ if (isIdentityGated(visibility) || visibility === 'private') {
792
+ conflictHeaders.set('cache-control', 'private, no-store');
793
+ conflictHeaders.set('X-Robots-Tag', 'noindex');
794
+ }
795
+ return new Response('object changed; retry', { status: 409, headers: conflictHeaders });
796
+ }
796
797
  const headers = new Headers();
797
798
  obj.writeHttpMetadata(headers);
798
799
  headers.set('etag', obj.httpEtag);
799
800
  if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8');
801
+ headers.set('accept-ranges', 'bytes');
800
802
  if (visibility === 'me' || visibility === 'org' || visibility === 'private') {
801
803
  // Token-gated + identity-gated reads must never be cached by a shared
802
804
  // proxy, and never indexed.
@@ -808,13 +810,30 @@ export default {
808
810
  }
809
811
  if (request.method === 'HEAD') return new Response(null, { status: 200, headers });
810
812
  const ctype = headers.get('content-type') || '';
813
+ const wantsRaw = url.searchParams.get('raw') != null;
814
+ const kind = viewableAssetKind(ctype);
815
+ // Navigation to a media viewer needs metadata, not the media bytes. Return
816
+ // it before the R2 body read just like an authorization denial does.
817
+ if (!range && ctype.indexOf('text/html') === -1 && !wantsRaw && kind && acceptsHtml(request) && visibility !== 'private') {
818
+ const viewerPage = renderAssetViewer(url.pathname, kind, gateObj.customMetadata || {}, firstSeg, {
819
+ isOwner,
820
+ ownerDomain,
821
+ media: kind === 'video' ? await mediaViewData(env, ctx, gateObj, path, isOwner) : null,
822
+ canRetry: isOwner && !!mediaConfig(env),
823
+ });
824
+ const vheaders = new Headers(headers);
825
+ vheaders.set('content-type', 'text/html; charset=utf-8');
826
+ vheaders.delete('etag');
827
+ return new Response(viewerPage, { status: 200, headers: vheaders });
828
+ }
829
+
811
830
  // HTML pages ALWAYS get the attribution bar injected at serve time (who
812
831
  // shared it, what made it, when, and — the point — a visual VISIBILITY cue),
813
832
  // all from stamped metadata. This is unconditional: ?raw does NOT strip the
814
833
  // bar from a shared page (the always-on cue from #3122/#3140 is not
815
834
  // defeatable with a query param). The body changes, so the R2 etag no
816
835
  // longer matches — drop it rather than serve a lying validator.
817
- if (ctype.indexOf('text/html') !== -1) {
836
+ if (ctype.indexOf('text/html') !== -1 && !range) {
818
837
  const rawHtml = await obj.text();
819
838
  // Per-slug view counter (RUSH view stats). Stored as a SEPARATE R2 object
820
839
  // (__views/<path>) so it never rewrites the page object — a rewrite would
@@ -825,7 +844,6 @@ export default {
825
844
  // view, and never HEAD (which returned above). The write rides
826
845
  // ctx.waitUntil so it never blocks the response; the displayed count folds
827
846
  // in the current view so the visitor sees themselves included.
828
- const wantsRaw = url.searchParams.get('raw') != null;
829
847
  const counting = !wantsRaw && !isOwner;
830
848
  const storedViews = await readViews(env, path);
831
849
  const views = storedViews + (counting ? 1 : 0);
@@ -847,23 +865,11 @@ export default {
847
865
  // navigating directly to a viewable asset (image/video/audio/pdf) gets a
848
866
  // lightweight viewer page carrying the same bar; a non-browser fetch (Accept
849
867
  // without text/html) falls through to raw bytes so embedding is never broken.
850
- const wantsRaw = url.searchParams.get('raw') != null;
851
- const kind = viewableAssetKind(ctype);
852
- // A token-gated (private) asset is served as raw bytes, NOT wrapped in the
853
- // viewer page (PHNX-3654): the viewer's inner <img src=…?raw> would drop the
854
- // ?k= key and 404 (there's no cookie to carry it, unlike me/org), breaking the
855
- // media. The gate already passed above, so the raw bytes are safe to serve.
856
- if (!wantsRaw && kind && acceptsHtml(request) && visibility !== 'private') {
857
- const viewerPage = renderAssetViewer(url.pathname, kind, obj.customMetadata || {}, firstSeg, {
858
- isOwner,
859
- ownerDomain,
860
- });
861
- const vheaders = new Headers(headers);
862
- vheaders.set('content-type', 'text/html; charset=utf-8');
863
- vheaders.delete('etag');
864
- return new Response(viewerPage, { status: 200, headers: vheaders });
868
+ if (range) {
869
+ headers.set('content-range', 'bytes ' + range.offset + '-' + (range.offset + range.length - 1) + '/' + gateObj.size);
870
+ headers.set('content-length', String(range.length));
865
871
  }
866
- return new Response(obj.body, { status: 200, headers });
872
+ return new Response(obj.body, { status: range ? 206 : 200, headers });
867
873
  }
868
874
 
869
875
  if (request.method === 'DELETE') {
@@ -895,6 +901,10 @@ export default {
895
901
  return json({ error: 'namespace mismatch', owner: handle || uid }, 403);
896
902
  }
897
903
  }
904
+ const mutationHolder = 'delete:' + crypto.randomUUID();
905
+ const mutationLock = await acquirePathMutationLock(env.BUCKET, path, mutationHolder, 'mutation');
906
+ if (!mutationLock) return json({ error: 'another write is active for this path' }, 409);
907
+ try {
898
908
  // PHNX-3542: capture the object's size BEFORE deleting so a managed
899
909
  // Phoenix owner's quota can be refunded. A canonical page (2 segments, not
900
910
  // a .png cover) refunds both bytes and the object count; a retained
@@ -908,14 +918,21 @@ export default {
908
918
  if ((auth.kind === 'phoenix' || collab) && !isCover && !firstSeg.startsWith('__')) {
909
919
  doomed = typeof env.BUCKET.head === 'function' ? await env.BUCKET.head(path) : await env.BUCKET.get(path);
910
920
  }
921
+ if (!(await pathMutationLockOwned(env.BUCKET, path, mutationHolder))) {
922
+ return json({ error: 'delete conflict: path lock changed', key: path }, 409);
923
+ }
911
924
  await env.BUCKET.delete(path);
912
- if (doomed && auth.kind === 'phoenix') {
925
+ // Derived transcript files were never charged, so deleting one directly
926
+ // refunds nothing.
927
+ if (doomed && auth.kind === 'phoenix' && !isMediaDerived(doomed)) {
913
928
  const delSegs = path.split('/').filter(Boolean);
914
929
  await refundShareWrite(env, auth.owner, {
915
930
  refund: typeof doomed.size === 'number' ? doomed.size : 0,
916
931
  freeCanonical: delSegs.length === 2,
917
932
  });
918
933
  }
934
+ // A video takes its derived files with it (best-effort, after the refund).
935
+ if (!isMediaDerived(doomed) && path.split('/').filter(Boolean).length === 2) await deleteMediaDerived(env, path);
919
936
  const purge = collab && doomed && doomed.customMetadata && doomed.customMetadata['body-revision'] && path.split('/').filter(Boolean).length === 2
920
937
  ? await purgeShare(collab, url, path)
921
938
  : null;
@@ -925,6 +942,9 @@ export default {
925
942
  if (purge.error) deleted.headers.set('x-collab-error', headerSafe(purge.error));
926
943
  }
927
944
  return deleted;
945
+ } finally {
946
+ await releasePathMutationLock(env.BUCKET, path, mutationHolder);
947
+ }
928
948
  }
929
949
 
930
950
  return new Response('method not allowed', { status: 405 });
@@ -957,6 +977,7 @@ async function renderGallery(bucket, origin, user, method) {
957
977
  const activeObjects = objects.filter(o => {
958
978
  if (isRevisionKey(o.key)) return false;
959
979
  if (o.key.endsWith('.png')) return false;
980
+ if (isMediaDerived(o)) return false;
960
981
  // Unlisted / me / org pages are reachable by direct URL only — never on the gallery.
961
982
  if (isHiddenFromGallery(o.customMetadata && o.customMetadata.visibility)) return false;
962
983
  const expiresAt = o.customMetadata && o.customMetadata['expires-at'];
@@ -998,7 +1019,8 @@ async function renderGallery(bucket, origin, user, method) {
998
1019
  return new Response(html, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'public, max-age=60' } });
999
1020
  }
1000
1021
 
1001
- async function renderListing(bucket, origin, user, method, includeHidden) {
1022
+ async function renderListing(env, origin, user, method, includeHidden) {
1023
+ const bucket = env.BUCKET;
1002
1024
  const objects = [];
1003
1025
  let cursor;
1004
1026
  do {
@@ -1017,17 +1039,24 @@ async function renderListing(bucket, origin, user, method, includeHidden) {
1017
1039
  }
1018
1040
 
1019
1041
  const now = Date.now();
1020
- const items = objects
1021
- .filter(o => {
1042
+ const activeObjects = objects.filter(o => {
1022
1043
  // Revisions and sibling .png OG covers are always hidden. Hidden-visibility
1023
1044
  // pages are included ONLY when an authenticated owner requested scope=mine.
1024
1045
  if (isRevisionKey(o.key)) return false;
1025
1046
  if (o.key.endsWith('.png')) return false;
1047
+ // A video's transcript, captions, and summary belong to its row.
1048
+ if (isMediaDerived(o)) return false;
1026
1049
  if (isHiddenFromGallery(o.customMetadata && o.customMetadata.visibility) && !includeHidden) return false;
1027
1050
  const expiresAt = o.customMetadata && o.customMetadata['expires-at'];
1028
1051
  return !(expiresAt && now > Date.parse(expiresAt));
1029
- })
1030
- .map(o => ({
1052
+ });
1053
+ const mediaStates = await mediaListingStates(env, user, activeObjects);
1054
+ const items = activeObjects.map(o => {
1055
+ const meta = extraMetaOf(o.customMetadata);
1056
+ // media is reserved against user writes, but intentionally exposed in
1057
+ // listing meta so share list --meta media=failed|ready remains useful.
1058
+ if (mediaStates[o.key]) meta.media = mediaStates[o.key];
1059
+ return {
1031
1060
  slug: o.key.slice(o.key.indexOf('/') + 1),
1032
1061
  url: origin + '/' + o.key,
1033
1062
  size: typeof o.size === 'number' ? o.size : 0,
@@ -1041,8 +1070,9 @@ async function renderListing(bucket, origin, user, method, includeHidden) {
1041
1070
  host: (o.customMetadata && o.customMetadata['host']) || null,
1042
1071
  repo: (o.customMetadata && o.customMetadata['repo']) || null,
1043
1072
  revisionCount: revisionCounts[o.key] || 0,
1044
- meta: extraMetaOf(o.customMetadata),
1045
- }));
1073
+ meta: meta,
1074
+ };
1075
+ });
1046
1076
  // Newest first, so the human table and any script reads the freshest share top.
1047
1077
  items.sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0));
1048
1078
 
@@ -1122,7 +1152,7 @@ async function renderRevisions(bucket, origin, key, method, identityGated) {
1122
1152
  // before it ever reaches this Worker; see RESERVED_META_KEYS in publish.ts).
1123
1153
  // One list, reused both to strip a same-named --meta collision on write and
1124
1154
  // to split arbitrary --meta entries back out on read.
1125
- 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', 'comment-policy', 'body-revision'];
1155
+ 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', 'comment-policy', 'body-revision', 'multipart-token', 'media', 'media-error', 'media-job', 'media-derived', 'media-source'];
1126
1156
  var PUBLIC_INBOX_DOMAINS = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'icloud.com', 'me.com'];
1127
1157
  var SHARE_COOKIE = '__Host-phoenix_share';
1128
1158
  var SHARE_COOKIE_MAX_AGE = 604800;
@@ -1141,7 +1171,7 @@ var SHARE_PLANS = {
1141
1171
  var DEFAULT_SHARE_PLAN = 'free';
1142
1172
  var RATE_WINDOW_MS = 3600 * 1000; // fixed 1h publish-rate window
1143
1173
  function planLimits(plan) { return Object.prototype.hasOwnProperty.call(SHARE_PLANS, plan) ? SHARE_PLANS[plan] : SHARE_PLANS[DEFAULT_SHARE_PLAN]; }
1144
- function freshUsage() { return { bytes: 0, count: 0, plan: DEFAULT_SHARE_PLAN, rlStart: 0, rlUsed: 0 }; }
1174
+ function freshUsage() { return { bytes: 0, count: 0, plan: DEFAULT_SHARE_PLAN, rlStart: 0, rlUsed: 0, multipartCharges: [] }; }
1145
1175
  function usageNumber(v, fallback) { return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback; }
1146
1176
 
1147
1177
  // Everything in customMetadata that ISN'T one of the reserved provenance/label
@@ -1467,11 +1497,23 @@ function viewableAssetKind(contentType) {
1467
1497
  // below. The media element points back at THIS url with ?raw so it loads the
1468
1498
  // stored bytes (not the viewer recursively) — and that ?raw fetch re-runs the
1469
1499
  // same me/org gate, so a private asset stays private inside its own viewer.
1500
+ //
1501
+ // A video with a media job (opts.media, PHNX-4287) gets the full video page
1502
+ // instead: captions track, chapter ticks, summary, action items, and the
1503
+ // transcript rail, or the processing / failed state while there is none.
1470
1504
  function renderAssetViewer(pathname, kind, meta, handle, opts) {
1471
1505
  var rawUrl = escapeHtml(pathname + '?raw=1');
1472
1506
  var name = '';
1473
1507
  try { name = decodeURIComponent(pathname.split('/').pop() || 'file'); } catch (e) { name = pathname.split('/').pop() || 'file'; }
1474
1508
  var bar = renderAttributionBar(meta, handle, opts);
1509
+ if (kind === 'video' && opts && opts.media) {
1510
+ var title = opts.media.summary && opts.media.summary.title ? opts.media.summary.title : name;
1511
+ return '<!doctype html><html><head><meta charset="utf-8">' +
1512
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
1513
+ '<title>' + escapeHtml(title) + '</title>' +
1514
+ '<style>' + MEDIA_VIEWER_CSS + '</style></head><body>' + bar +
1515
+ renderMediaPanels(pathname, opts.media, { canRetry: !!opts.canRetry }) + '</body></html>';
1516
+ }
1475
1517
  var media = '';
1476
1518
  if (kind === 'image') media = '<img src="' + rawUrl + '" alt="' + escapeHtml(name) + '">';
1477
1519
  else if (kind === 'video') media = '<video src="' + rawUrl + '" controls playsinline></video>';
@@ -1828,37 +1870,25 @@ async function handleCollab(request, env, url, path) {
1828
1870
  return new Response(upstream.body, { status: upstream.status, headers: out });
1829
1871
  }
1830
1872
 
1831
- function json(body, status) {
1832
- return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
1833
- }
1834
-
1835
- // Length-independent constant-time-ish compare (Workers has no timingSafeEqual).
1836
- function safeEqual(a, b) {
1837
- if (typeof a !== 'string' || typeof b !== 'string') return false;
1838
- const la = a.length, lb = b.length;
1839
- let out = la ^ lb;
1840
- for (let i = 0; i < la; i++) out |= a.charCodeAt(i) ^ b.charCodeAt(i % lb || 0);
1841
- return out === 0 && la === lb;
1842
- }
1843
-
1844
- // URL-safety, not collision-resistance. Two values that differ only in
1845
- // case/punctuation share a prefix.
1846
- function sanitizeNamespace(s) {
1847
- return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
1848
- }
1849
-
1850
- // Public handle: email local-part, plus-tag stripped. Must match CLI handleFromEmail.
1851
- function handleFromEmail(email) {
1852
- if (!email) return '';
1853
- const local = String(email).split('@')[0] || '';
1854
- const beforePlus = local.split('+')[0] || local;
1855
- return sanitizeNamespace(beforePlus);
1856
- }
1857
-
1858
- function phoenixHandle(auth) {
1859
- return handleFromEmail(auth.email) || sanitizeNamespace(auth.owner);
1873
+ ${SHARE_PUBLISH_WORKER_SOURCE}
1874
+ ${SHARE_MEDIA_WORKER_SOURCE}
1875
+ // Ownership for an edit of an existing <handle>/<slug>: WRITE_TOKEN is the
1876
+ // endpoint admin; a Phoenix caller must own the handle the way PUT and DELETE
1877
+ // decide it (the __handles claim, transferring it on a same-email account
1878
+ // move). An alternate handle must already be claimed: an edit never creates a
1879
+ // namespace. Returns an error Response, or null when the caller owns it.
1880
+ async function assertNamespaceOwner(env, auth, segments) {
1881
+ if (auth.kind !== 'phoenix') return null;
1882
+ const expected = phoenixHandle(auth);
1883
+ const handle = segments[0];
1884
+ if (!expected || handle !== expected) {
1885
+ const claim = handle ? await env.BUCKET.get('__handles/' + handle) : null;
1886
+ if (!claim) return json({ error: 'namespace mismatch', owner: expected }, 403);
1887
+ }
1888
+ const owned = await assertHandleOwner(env.BUCKET, handle, auth.owner, auth.email || '');
1889
+ if (owned.error) return json({ error: 'forbidden' }, 403);
1890
+ return null;
1860
1891
  }
1861
-
1862
1892
  // First writer of a handle owns it. Later PUTs from the same userId are fine;
1863
1893
  // a different userId whose email local-part collides gets 409, not a silent
1864
1894
  // overwrite — EXCEPT when the verified Phoenix email matches the claim's
@@ -1927,7 +1957,7 @@ async function transferHandle(bucket, handle, oldUserId, newUserId, email) {
1927
1957
  const obj = await bucket.get(o.key);
1928
1958
  if (!obj) continue;
1929
1959
  const headers = new Headers();
1930
- if (typeof obj.writeHttpMetadata === 'function') obj.writeHttpMetadata(headers);
1960
+ obj.writeHttpMetadata(headers);
1931
1961
  const customMetadata = { ...(obj.customMetadata || {}), owner: newUserId };
1932
1962
  await bucket.put(o.key, obj.body, {
1933
1963
  httpMetadata: headers.get('content-type') ? { contentType: headers.get('content-type') } : undefined,
@@ -1976,6 +2006,30 @@ function isIdentityGated(visibility) {
1976
2006
  return visibility === 'me' || visibility === 'org';
1977
2007
  }
1978
2008
 
2009
+ // One RFC 9110 byte range. R2 accepts offset/length; multipart ranges are not
2010
+ // useful for media playback and would require a multipart/byteranges encoder,
2011
+ // so reject them explicitly instead of returning the wrong bytes.
2012
+ function parseByteRange(value, size) {
2013
+ if (typeof value !== 'string' || !Number.isSafeInteger(size) || size < 0) return null;
2014
+ const match = /^bytes=(\\d*)-(\\d*)$/.exec(value.trim());
2015
+ if (!match || (!match[1] && !match[2]) || size === 0) return null;
2016
+ let start;
2017
+ let end;
2018
+ if (!match[1]) {
2019
+ const suffix = Number(match[2]);
2020
+ if (!Number.isSafeInteger(suffix) || suffix <= 0) return null;
2021
+ start = Math.max(0, size - suffix);
2022
+ end = size - 1;
2023
+ } else {
2024
+ start = Number(match[1]);
2025
+ if (!Number.isSafeInteger(start) || start < 0 || start >= size) return null;
2026
+ end = match[2] ? Number(match[2]) : size - 1;
2027
+ if (!Number.isSafeInteger(end) || end < start) return null;
2028
+ end = Math.min(end, size - 1);
2029
+ }
2030
+ return { offset: start, length: end - start + 1 };
2031
+ }
2032
+
1979
2033
  function managedCoverHeaders(visibility) {
1980
2034
  const headers = new Headers({ 'content-type': 'image/png' });
1981
2035
  // Token-gated (private) + identity-gated (me/org) covers must never be
@@ -2122,6 +2176,9 @@ async function readUsage(env, owner) {
2122
2176
  plan: typeof parsed.plan === 'string' ? parsed.plan : DEFAULT_SHARE_PLAN,
2123
2177
  rlStart: usageNumber(parsed.rlStart, 0),
2124
2178
  rlUsed: usageNumber(parsed.rlUsed, 0),
2179
+ multipartCharges: Array.isArray(parsed.multipartCharges)
2180
+ ? parsed.multipartCharges.filter(function (id) { return typeof id === 'string'; })
2181
+ : [],
2125
2182
  };
2126
2183
  }
2127
2184
  } catch (e) {
@@ -2142,11 +2199,12 @@ async function writeUsageCas(env, owner, prevEtag, usage) {
2142
2199
  const res = await env.BUCKET.put(usageKey(owner), body, opts);
2143
2200
  return res !== null;
2144
2201
  }
2145
- // Fresh key: plain create. Neither R2 nor the test harness exposes a
2146
- // conditional-create predicate, so the only race is two simultaneous
2147
- // first-creates of the same owner's ledger — a benign, one-time bounded loss.
2148
- await env.BUCKET.put(usageKey(owner), body, opts);
2149
- return true;
2202
+ // Fresh ledger creation must also be atomic. Two first-ever publishes may
2203
+ // both read a miss; exactly one conditional create wins and the loser returns
2204
+ // false so withUsage re-reads the committed ledger and applies its mutation.
2205
+ opts.onlyIf = { etagDoesNotMatch: '*' };
2206
+ const res = await env.BUCKET.put(usageKey(owner), body, opts);
2207
+ return res !== null;
2150
2208
  }
2151
2209
 
2152
2210
  // CAS retry loop. fn(usage) returns { reject: Response } to fail loud without
@@ -2180,6 +2238,13 @@ async function chargeShareWrite(env, auth, params) {
2180
2238
  const now = Date.now();
2181
2239
  const out = await withUsage(env, auth.owner, function (usage) {
2182
2240
  const limits = planLimits(usage.plan);
2241
+ // Completing the same upload twice must not double-charge quota or rate.
2242
+ // The durable receipt set lives in the same CAS-protected ledger mutation as
2243
+ // the charge, so a crash cannot leave one committed without the other. Never
2244
+ // evict receipts: an old lost-response retry must remain exactly-once too.
2245
+ if (params.idempotencyKey && usage.multipartCharges.indexOf(params.idempotencyKey) !== -1) {
2246
+ return { commit: usage, result: { limits: limits, alreadyCharged: true } };
2247
+ }
2183
2248
  // Rate limit — only a user-initiated page PUT counts (countRate). A fixed 1h
2184
2249
  // window: reset when the window has rolled over, otherwise reject at the cap.
2185
2250
  if (params.countRate) {
@@ -2191,7 +2256,8 @@ async function chargeShareWrite(env, auth, params) {
2191
2256
  usage.rlUsed += 1;
2192
2257
  }
2193
2258
  // Per-file size cap.
2194
- if (typeof params.fileBytes === 'number' && params.fileBytes > limits.maxFileBytes) {
2259
+ const bypassFileCap = !!params.unlimitedVideoMultipart && unlimited;
2260
+ if (!bypassFileCap && typeof params.fileBytes === 'number' && params.fileBytes > limits.maxFileBytes) {
2195
2261
  return { reject: json({ error: 'file too large', maxBytes: limits.maxFileBytes, gotBytes: params.fileBytes }, 413) };
2196
2262
  }
2197
2263
  // Object (canonical page) count.
@@ -2206,6 +2272,9 @@ async function chargeShareWrite(env, auth, params) {
2206
2272
  return { reject: json({ error: 'storage limit reached', maxBytes: limits.maxBytes, usedBytes: usage.bytes }, 413) };
2207
2273
  }
2208
2274
  usage.bytes = Math.max(0, usage.bytes + params.charge);
2275
+ if (params.idempotencyKey) {
2276
+ usage.multipartCharges.push(params.idempotencyKey);
2277
+ }
2209
2278
  return { commit: usage, result: { limits: limits } };
2210
2279
  });
2211
2280
  if (out instanceof Response) return { error: out };