@phnx-labs/artifacts-cli 0.8.3-pre.1 → 0.9.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.
@@ -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 };
@@ -429,7 +320,7 @@ export default {
429
320
  // A managed republish may change the title/description. Invalidate only
430
321
  // its generated sibling so the next crawler receives a fresh card; BYO
431
322
  // publishes send no OG metadata and keep their explicitly uploaded cover.
432
- if (ogTitle) await env.BUCKET.delete(path + '.png');
323
+ if (customMetadata['og-title']) await env.BUCKET.delete(path + '.png');
433
324
  // Register only a page comments can anchor to. A failed registration
434
325
  // never fails the publish: the page is stored, and the caller is told.
435
326
  // Threads carry over only from a live registered page at this address.
@@ -453,6 +344,9 @@ export default {
453
344
  json({ ok: true, url: url.origin + '/' + path, expiresAt: expiresAt || null, unlisted: visibility === 'unlisted', visibility }, 200),
454
345
  registration,
455
346
  );
347
+ } finally {
348
+ await releasePathMutationLock(env.BUCKET, path, mutationHolder);
349
+ }
456
350
  }
457
351
 
458
352
  if (request.method === 'PATCH') {
@@ -460,21 +354,12 @@ export default {
460
354
  if (auth.error) return auth.error;
461
355
  const segments = path.split('/').filter(Boolean);
462
356
  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
- }
357
+ const notOwner = await assertNamespaceOwner(env, auth, segments);
358
+ if (notOwner) return notOwner;
359
+ const mutationHolder = 'patch:' + crypto.randomUUID();
360
+ const mutationLock = await acquirePathMutationLock(env.BUCKET, path, mutationHolder, 'mutation');
361
+ if (!mutationLock) return json({ error: 'conflict', key: path, detail: 'another write is active for this path' }, 409);
362
+ try {
478
363
  const existing = await env.BUCKET.get(path);
479
364
  if (!existing) return json({ error: 'share not found', key: path }, 404);
480
365
  // Ownership was settled above, the same way DELETE settles it: WRITE_TOKEN
@@ -569,13 +454,16 @@ export default {
569
454
  // ordering and list JSON do not pretend the page was republished today.
570
455
  if (!metadata['published-at']) metadata['published-at'] = new Date(existing.uploaded).toISOString();
571
456
  const httpHeaders = new Headers();
572
- if (typeof existing.writeHttpMetadata === 'function') existing.writeHttpMetadata(httpHeaders);
457
+ existing.writeHttpMetadata(httpHeaders);
573
458
  const putOpts = { httpMetadata: httpHeaders, customMetadata: metadata };
574
459
  // onlyIf.etagMatches wants the bare hash (R2Object#etag), not the
575
460
  // quoted HTTP header form (R2Object#httpEtag) — passing httpEtag 500s
576
461
  // on a real Workers R2 binding ("Conditional ETag should not be
577
462
  // wrapped in quotes"), a defect only a real R2 backend surfaces.
578
463
  if (existing.etag) putOpts.onlyIf = { etagMatches: existing.etag };
464
+ if (!(await pathMutationLockOwned(env.BUCKET, path, mutationHolder))) {
465
+ return json({ error: 'conflict: path lock changed', key: path }, 409);
466
+ }
579
467
  const putResult = await env.BUCKET.put(path, existing.body, putOpts);
580
468
  if (putResult === null) return json({ error: 'conflict', key: path }, 409);
581
469
  // A generated cover copies the canonical visibility gate into its own R2
@@ -598,6 +486,9 @@ export default {
598
486
  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
487
  registration,
600
488
  );
489
+ } finally {
490
+ await releasePathMutationLock(env.BUCKET, path, mutationHolder);
491
+ }
601
492
  }
602
493
 
603
494
  if (request.method === 'GET' || request.method === 'HEAD') {
@@ -616,7 +507,7 @@ export default {
616
507
  if (url.searchParams.get('format') === 'json') {
617
508
  const scope = await resolveListingScope(request, env, segments[0]);
618
509
  if (scope.error) return scope.error;
619
- return renderListing(env.BUCKET, url.origin, segments[0], request.method, scope.includeHidden);
510
+ return renderListing(env, url.origin, segments[0], request.method, scope.includeHidden);
620
511
  }
621
512
  return renderGallery(env.BUCKET, url.origin, segments[0], request.method);
622
513
  }
@@ -740,34 +631,86 @@ export default {
740
631
  }
741
632
  }
742
633
 
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'];
634
+ // Metadata-only lookup first. Visibility, token, and expiry all decide
635
+ // whether a caller may read before R2 is asked for any object bytes.
636
+ const gateObj = typeof env.BUCKET.head === 'function'
637
+ ? await env.BUCKET.head(path)
638
+ : await env.BUCKET.get(path);
639
+ if (!gateObj) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
640
+ // A video's transcript, captions, and summary answer to the video's gate.
641
+ if (isMediaDerived(gateObj)) return serveMediaDerived(request, env, url, path, gateObj);
642
+ const expiresAt = gateObj.customMetadata && gateObj.customMetadata['expires-at'];
746
643
  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
644
+ const expiredVisibility = (gateObj.customMetadata && gateObj.customMetadata.visibility) || 'public';
645
+ const expiredHeaders = function (retry) {
646
+ const headers = new Headers({ 'content-type': 'text/plain' });
647
+ if (retry) { headers.set('cache-control', 'no-store'); headers.set('retry-after', '1'); }
648
+ if (isIdentityGated(expiredVisibility) || expiredVisibility === 'private') {
649
+ headers.set('cache-control', 'private, no-store');
650
+ headers.set('X-Robots-Tag', 'noindex');
762
651
  }
652
+ return headers;
653
+ };
654
+ const expiryHolder = 'expiry:' + crypto.randomUUID();
655
+ const expiryLock = await acquirePathMutationLock(env.BUCKET, path, expiryHolder, 'mutation');
656
+ if (!expiryLock) {
657
+ return new Response('expired object is changing; retry', {
658
+ status: 409,
659
+ headers: expiredHeaders(true),
660
+ });
763
661
  }
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));
662
+ try {
663
+ // Re-read under the shared canonical lock. An etag mismatch means a
664
+ // predecessor changed the path after the metadata gate; never delete or
665
+ // refund against that stale snapshot, and never serve its expired bytes.
666
+ const current = typeof env.BUCKET.head === 'function'
667
+ ? await env.BUCKET.head(path)
668
+ : await env.BUCKET.get(path);
669
+ if (!current) {
670
+ return new Response('gone — this link has expired', { status: 410, headers: expiredHeaders(false) });
671
+ }
672
+ const currentExpiry = current.customMetadata && current.customMetadata['expires-at'];
673
+ if (current.etag !== gateObj.etag || !currentExpiry || Date.now() <= Date.parse(currentExpiry)) {
674
+ return new Response('object changed; retry', {
675
+ status: 409,
676
+ headers: expiredHeaders(true),
677
+ });
678
+ }
679
+ if (!(await pathMutationLockOwned(env.BUCKET, path, expiryHolder))) {
680
+ return new Response('expired object is changing; retry', {
681
+ status: 409,
682
+ headers: expiredHeaders(true),
683
+ });
684
+ }
685
+ await env.BUCKET.delete(path);
686
+ // PHNX-3542: expiry is a lazy delete with no auth context. Refund the
687
+ // stamped owner's quota (bytes + object count) best-effort — a refund
688
+ // failure must never break serving the 410. A canonical page is 2
689
+ // segments; covers are excluded (never charged) so refund is safe here
690
+ // because only canonical pages ever carry an expires-at.
691
+ const expiredOwner = current.customMetadata && current.customMetadata['owner'];
692
+ if (expiredOwner && !path.endsWith('.png')) {
693
+ try {
694
+ await refundShareWrite(env, expiredOwner, {
695
+ refund: typeof current.size === 'number' ? current.size : 0,
696
+ freeCanonical: path.split('/').filter(Boolean).length === 2,
697
+ });
698
+ } catch (e) {
699
+ // best-effort: serving the expiry 410 must never depend on the refund
700
+ }
701
+ }
702
+ // An expired video's derived files go with it (best-effort, after the refund).
703
+ if (path.split('/').filter(Boolean).length === 2) await deleteMediaDerived(env, path);
704
+ // An expired slug is reusable, so its threads go with it, off the
705
+ // response path like the view counter.
706
+ const expiredCollab = collabConfig(env);
707
+ if (expiredCollab && current.customMetadata && current.customMetadata['body-revision'] && path.split('/').filter(Boolean).length === 2 && ctx && typeof ctx.waitUntil === 'function') {
708
+ ctx.waitUntil(purgeShare(expiredCollab, url, path));
709
+ }
710
+ return new Response('gone — this link has expired', { status: 410, headers: expiredHeaders(false) });
711
+ } finally {
712
+ await releasePathMutationLock(env.BUCKET, path, expiryHolder);
769
713
  }
770
- return new Response('gone — this link has expired', { status: 410, headers: { 'content-type': 'text/plain' } });
771
714
  }
772
715
  // Resolve the viewer ONCE — needed both to gate me/org reads AND to decide
773
716
  // whether THIS viewer OWNS this namespace (the interactive visibility
@@ -776,27 +719,81 @@ export default {
776
719
  // FAILURE (expired/consumed/unreachable) must only gate a page that needs
777
720
  // identity — a public/unlisted page never invoked ticket redemption before
778
721
  // this refactor, so a stale ticket there must serve anonymously, not 401.
779
- const visibility = (obj.customMetadata && obj.customMetadata.visibility) || 'public';
722
+ const visibility = (gateObj.customMetadata && gateObj.customMetadata.visibility) || 'public';
780
723
  const viewer = await resolveViewer(request, env, url);
781
- if (viewer.redirect) return viewer.redirect;
782
- if (viewer.error && isIdentityGated(visibility)) return viewer.error;
724
+ if (viewer.redirect) {
725
+ if (isIdentityGated(visibility)) {
726
+ viewer.redirect.headers.set('cache-control', 'private, no-store');
727
+ viewer.redirect.headers.set('X-Robots-Tag', 'noindex');
728
+ }
729
+ return viewer.redirect;
730
+ }
731
+ if (viewer.error && isIdentityGated(visibility)) {
732
+ viewer.error.headers.set('cache-control', 'private, no-store');
733
+ viewer.error.headers.set('X-Robots-Tag', 'noindex');
734
+ return viewer.error;
735
+ }
783
736
  const identity = viewer.identity || null;
784
- const denied = await gateVisibility(url, env, obj, identity);
785
- if (denied) return denied;
737
+ const denied = await gateVisibility(url, env, gateObj, identity);
738
+ if (denied) {
739
+ denied.headers.set('cache-control', 'private, no-store');
740
+ denied.headers.set('X-Robots-Tag', 'noindex');
741
+ return denied;
742
+ }
786
743
  // Token-gated read auth (PHNX-3654): a 'private' page is served only to a
787
744
  // request carrying the matching viewer key (?k= or Bearer), or to its owner.
788
745
  // A miss returns 404 — never leaking that the page exists — exactly like a
789
746
  // wrong me/org viewer.
790
- const tokenDenied = await gateTokenRead(request, url, obj, identity);
791
- if (tokenDenied) return tokenDenied;
747
+ const tokenDenied = await gateTokenRead(request, url, gateObj, identity);
748
+ if (tokenDenied) {
749
+ tokenDenied.headers.set('cache-control', 'private, no-store');
750
+ tokenDenied.headers.set('X-Robots-Tag', 'noindex');
751
+ return tokenDenied;
752
+ }
792
753
  // The owner of the namespace (their handle === the first path segment) gets
793
754
  // an interactive visibility control; everyone else keeps the static cue.
794
755
  const isOwner = !!identity && handleFromEmail(identity.email) === firstSeg;
795
756
  const ownerDomain = identity ? emailDomain(identity.email) : '';
757
+ let range = null;
758
+ const requestedRange = request.method === 'GET' ? request.headers.get('range') : null;
759
+ if (requestedRange) range = parseByteRange(requestedRange, gateObj.size);
760
+ if (requestedRange && !range) {
761
+ const invalidHeaders = new Headers({
762
+ 'accept-ranges': 'bytes',
763
+ 'content-range': 'bytes */' + gateObj.size,
764
+ 'content-length': '0',
765
+ });
766
+ if (isIdentityGated(visibility) || visibility === 'private') {
767
+ invalidHeaders.set('cache-control', 'private, no-store');
768
+ invalidHeaders.set('X-Robots-Tag', 'noindex');
769
+ }
770
+ return new Response(null, { status: 416, headers: invalidHeaders });
771
+ }
772
+ // HTML is transformed to inject attribution, so byte offsets no longer
773
+ // describe the served representation. Ignore Range and serve the complete
774
+ // attributed page; media/assets retain normal byte-range semantics.
775
+ if (range) {
776
+ const gateHeaders = new Headers();
777
+ gateObj.writeHttpMetadata(gateHeaders);
778
+ if ((gateHeaders.get('content-type') || '').indexOf('text/html') !== -1) range = null;
779
+ }
780
+ let obj = await env.BUCKET.get(path, range ? { range: { offset: range.offset, length: range.length } } : undefined);
781
+ if (!obj) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
782
+ // Do not serve bytes authorized against stale metadata if a concurrent
783
+ // publish changed the object between head() and get().
784
+ if (gateObj.etag && obj.etag && gateObj.etag !== obj.etag) {
785
+ const conflictHeaders = new Headers({ 'content-type': 'text/plain', 'retry-after': '1' });
786
+ if (isIdentityGated(visibility) || visibility === 'private') {
787
+ conflictHeaders.set('cache-control', 'private, no-store');
788
+ conflictHeaders.set('X-Robots-Tag', 'noindex');
789
+ }
790
+ return new Response('object changed; retry', { status: 409, headers: conflictHeaders });
791
+ }
796
792
  const headers = new Headers();
797
793
  obj.writeHttpMetadata(headers);
798
794
  headers.set('etag', obj.httpEtag);
799
795
  if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8');
796
+ headers.set('accept-ranges', 'bytes');
800
797
  if (visibility === 'me' || visibility === 'org' || visibility === 'private') {
801
798
  // Token-gated + identity-gated reads must never be cached by a shared
802
799
  // proxy, and never indexed.
@@ -808,13 +805,30 @@ export default {
808
805
  }
809
806
  if (request.method === 'HEAD') return new Response(null, { status: 200, headers });
810
807
  const ctype = headers.get('content-type') || '';
808
+ const wantsRaw = url.searchParams.get('raw') != null;
809
+ const kind = viewableAssetKind(ctype);
810
+ // Navigation to a media viewer needs metadata, not the media bytes. Return
811
+ // it before the R2 body read just like an authorization denial does.
812
+ if (!range && ctype.indexOf('text/html') === -1 && !wantsRaw && kind && acceptsHtml(request) && visibility !== 'private') {
813
+ const viewerPage = renderAssetViewer(url.pathname, kind, gateObj.customMetadata || {}, firstSeg, {
814
+ isOwner,
815
+ ownerDomain,
816
+ media: kind === 'video' ? await mediaViewData(env, ctx, gateObj, path, isOwner) : null,
817
+ canRetry: isOwner && !!mediaConfig(env),
818
+ });
819
+ const vheaders = new Headers(headers);
820
+ vheaders.set('content-type', 'text/html; charset=utf-8');
821
+ vheaders.delete('etag');
822
+ return new Response(viewerPage, { status: 200, headers: vheaders });
823
+ }
824
+
811
825
  // HTML pages ALWAYS get the attribution bar injected at serve time (who
812
826
  // shared it, what made it, when, and — the point — a visual VISIBILITY cue),
813
827
  // all from stamped metadata. This is unconditional: ?raw does NOT strip the
814
828
  // bar from a shared page (the always-on cue from #3122/#3140 is not
815
829
  // defeatable with a query param). The body changes, so the R2 etag no
816
830
  // longer matches — drop it rather than serve a lying validator.
817
- if (ctype.indexOf('text/html') !== -1) {
831
+ if (ctype.indexOf('text/html') !== -1 && !range) {
818
832
  const rawHtml = await obj.text();
819
833
  // Per-slug view counter (RUSH view stats). Stored as a SEPARATE R2 object
820
834
  // (__views/<path>) so it never rewrites the page object — a rewrite would
@@ -825,7 +839,6 @@ export default {
825
839
  // view, and never HEAD (which returned above). The write rides
826
840
  // ctx.waitUntil so it never blocks the response; the displayed count folds
827
841
  // in the current view so the visitor sees themselves included.
828
- const wantsRaw = url.searchParams.get('raw') != null;
829
842
  const counting = !wantsRaw && !isOwner;
830
843
  const storedViews = await readViews(env, path);
831
844
  const views = storedViews + (counting ? 1 : 0);
@@ -847,23 +860,11 @@ export default {
847
860
  // navigating directly to a viewable asset (image/video/audio/pdf) gets a
848
861
  // lightweight viewer page carrying the same bar; a non-browser fetch (Accept
849
862
  // 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 });
863
+ if (range) {
864
+ headers.set('content-range', 'bytes ' + range.offset + '-' + (range.offset + range.length - 1) + '/' + gateObj.size);
865
+ headers.set('content-length', String(range.length));
865
866
  }
866
- return new Response(obj.body, { status: 200, headers });
867
+ return new Response(obj.body, { status: range ? 206 : 200, headers });
867
868
  }
868
869
 
869
870
  if (request.method === 'DELETE') {
@@ -895,6 +896,10 @@ export default {
895
896
  return json({ error: 'namespace mismatch', owner: handle || uid }, 403);
896
897
  }
897
898
  }
899
+ const mutationHolder = 'delete:' + crypto.randomUUID();
900
+ const mutationLock = await acquirePathMutationLock(env.BUCKET, path, mutationHolder, 'mutation');
901
+ if (!mutationLock) return json({ error: 'another write is active for this path' }, 409);
902
+ try {
898
903
  // PHNX-3542: capture the object's size BEFORE deleting so a managed
899
904
  // Phoenix owner's quota can be refunded. A canonical page (2 segments, not
900
905
  // a .png cover) refunds both bytes and the object count; a retained
@@ -908,14 +913,21 @@ export default {
908
913
  if ((auth.kind === 'phoenix' || collab) && !isCover && !firstSeg.startsWith('__')) {
909
914
  doomed = typeof env.BUCKET.head === 'function' ? await env.BUCKET.head(path) : await env.BUCKET.get(path);
910
915
  }
916
+ if (!(await pathMutationLockOwned(env.BUCKET, path, mutationHolder))) {
917
+ return json({ error: 'delete conflict: path lock changed', key: path }, 409);
918
+ }
911
919
  await env.BUCKET.delete(path);
912
- if (doomed && auth.kind === 'phoenix') {
920
+ // Derived transcript files were never charged, so deleting one directly
921
+ // refunds nothing.
922
+ if (doomed && auth.kind === 'phoenix' && !isMediaDerived(doomed)) {
913
923
  const delSegs = path.split('/').filter(Boolean);
914
924
  await refundShareWrite(env, auth.owner, {
915
925
  refund: typeof doomed.size === 'number' ? doomed.size : 0,
916
926
  freeCanonical: delSegs.length === 2,
917
927
  });
918
928
  }
929
+ // A video takes its derived files with it (best-effort, after the refund).
930
+ if (!isMediaDerived(doomed) && path.split('/').filter(Boolean).length === 2) await deleteMediaDerived(env, path);
919
931
  const purge = collab && doomed && doomed.customMetadata && doomed.customMetadata['body-revision'] && path.split('/').filter(Boolean).length === 2
920
932
  ? await purgeShare(collab, url, path)
921
933
  : null;
@@ -925,6 +937,9 @@ export default {
925
937
  if (purge.error) deleted.headers.set('x-collab-error', headerSafe(purge.error));
926
938
  }
927
939
  return deleted;
940
+ } finally {
941
+ await releasePathMutationLock(env.BUCKET, path, mutationHolder);
942
+ }
928
943
  }
929
944
 
930
945
  return new Response('method not allowed', { status: 405 });
@@ -957,6 +972,7 @@ async function renderGallery(bucket, origin, user, method) {
957
972
  const activeObjects = objects.filter(o => {
958
973
  if (isRevisionKey(o.key)) return false;
959
974
  if (o.key.endsWith('.png')) return false;
975
+ if (isMediaDerived(o)) return false;
960
976
  // Unlisted / me / org pages are reachable by direct URL only — never on the gallery.
961
977
  if (isHiddenFromGallery(o.customMetadata && o.customMetadata.visibility)) return false;
962
978
  const expiresAt = o.customMetadata && o.customMetadata['expires-at'];
@@ -998,7 +1014,8 @@ async function renderGallery(bucket, origin, user, method) {
998
1014
  return new Response(html, { status: 200, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'public, max-age=60' } });
999
1015
  }
1000
1016
 
1001
- async function renderListing(bucket, origin, user, method, includeHidden) {
1017
+ async function renderListing(env, origin, user, method, includeHidden) {
1018
+ const bucket = env.BUCKET;
1002
1019
  const objects = [];
1003
1020
  let cursor;
1004
1021
  do {
@@ -1017,17 +1034,24 @@ async function renderListing(bucket, origin, user, method, includeHidden) {
1017
1034
  }
1018
1035
 
1019
1036
  const now = Date.now();
1020
- const items = objects
1021
- .filter(o => {
1037
+ const activeObjects = objects.filter(o => {
1022
1038
  // Revisions and sibling .png OG covers are always hidden. Hidden-visibility
1023
1039
  // pages are included ONLY when an authenticated owner requested scope=mine.
1024
1040
  if (isRevisionKey(o.key)) return false;
1025
1041
  if (o.key.endsWith('.png')) return false;
1042
+ // A video's transcript, captions, and summary belong to its row.
1043
+ if (isMediaDerived(o)) return false;
1026
1044
  if (isHiddenFromGallery(o.customMetadata && o.customMetadata.visibility) && !includeHidden) return false;
1027
1045
  const expiresAt = o.customMetadata && o.customMetadata['expires-at'];
1028
1046
  return !(expiresAt && now > Date.parse(expiresAt));
1029
- })
1030
- .map(o => ({
1047
+ });
1048
+ const mediaStates = await mediaListingStates(env, user, activeObjects);
1049
+ const items = activeObjects.map(o => {
1050
+ const meta = extraMetaOf(o.customMetadata);
1051
+ // media is reserved against user writes, but intentionally exposed in
1052
+ // listing meta so share list --meta media=failed|ready remains useful.
1053
+ if (mediaStates[o.key]) meta.media = mediaStates[o.key];
1054
+ return {
1031
1055
  slug: o.key.slice(o.key.indexOf('/') + 1),
1032
1056
  url: origin + '/' + o.key,
1033
1057
  size: typeof o.size === 'number' ? o.size : 0,
@@ -1041,8 +1065,9 @@ async function renderListing(bucket, origin, user, method, includeHidden) {
1041
1065
  host: (o.customMetadata && o.customMetadata['host']) || null,
1042
1066
  repo: (o.customMetadata && o.customMetadata['repo']) || null,
1043
1067
  revisionCount: revisionCounts[o.key] || 0,
1044
- meta: extraMetaOf(o.customMetadata),
1045
- }));
1068
+ meta: meta,
1069
+ };
1070
+ });
1046
1071
  // Newest first, so the human table and any script reads the freshest share top.
1047
1072
  items.sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0));
1048
1073
 
@@ -1122,7 +1147,7 @@ async function renderRevisions(bucket, origin, key, method, identityGated) {
1122
1147
  // before it ever reaches this Worker; see RESERVED_META_KEYS in publish.ts).
1123
1148
  // One list, reused both to strip a same-named --meta collision on write and
1124
1149
  // 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'];
1150
+ 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
1151
  var PUBLIC_INBOX_DOMAINS = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'icloud.com', 'me.com'];
1127
1152
  var SHARE_COOKIE = '__Host-phoenix_share';
1128
1153
  var SHARE_COOKIE_MAX_AGE = 604800;
@@ -1141,7 +1166,7 @@ var SHARE_PLANS = {
1141
1166
  var DEFAULT_SHARE_PLAN = 'free';
1142
1167
  var RATE_WINDOW_MS = 3600 * 1000; // fixed 1h publish-rate window
1143
1168
  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 }; }
1169
+ function freshUsage() { return { bytes: 0, count: 0, plan: DEFAULT_SHARE_PLAN, rlStart: 0, rlUsed: 0, multipartCharges: [] }; }
1145
1170
  function usageNumber(v, fallback) { return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback; }
1146
1171
 
1147
1172
  // Everything in customMetadata that ISN'T one of the reserved provenance/label
@@ -1467,11 +1492,23 @@ function viewableAssetKind(contentType) {
1467
1492
  // below. The media element points back at THIS url with ?raw so it loads the
1468
1493
  // stored bytes (not the viewer recursively) — and that ?raw fetch re-runs the
1469
1494
  // same me/org gate, so a private asset stays private inside its own viewer.
1495
+ //
1496
+ // A video with a media job (opts.media, PHNX-4287) gets the full video page
1497
+ // instead: captions track, chapter ticks, summary, action items, and the
1498
+ // transcript rail, or the processing / failed state while there is none.
1470
1499
  function renderAssetViewer(pathname, kind, meta, handle, opts) {
1471
1500
  var rawUrl = escapeHtml(pathname + '?raw=1');
1472
1501
  var name = '';
1473
1502
  try { name = decodeURIComponent(pathname.split('/').pop() || 'file'); } catch (e) { name = pathname.split('/').pop() || 'file'; }
1474
1503
  var bar = renderAttributionBar(meta, handle, opts);
1504
+ if (kind === 'video' && opts && opts.media) {
1505
+ var title = opts.media.summary && opts.media.summary.title ? opts.media.summary.title : name;
1506
+ return '<!doctype html><html><head><meta charset="utf-8">' +
1507
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
1508
+ '<title>' + escapeHtml(title) + '</title>' +
1509
+ '<style>' + MEDIA_VIEWER_CSS + '</style></head><body>' + bar +
1510
+ renderMediaPanels(pathname, opts.media, { canRetry: !!opts.canRetry }) + '</body></html>';
1511
+ }
1475
1512
  var media = '';
1476
1513
  if (kind === 'image') media = '<img src="' + rawUrl + '" alt="' + escapeHtml(name) + '">';
1477
1514
  else if (kind === 'video') media = '<video src="' + rawUrl + '" controls playsinline></video>';
@@ -1828,37 +1865,25 @@ async function handleCollab(request, env, url, path) {
1828
1865
  return new Response(upstream.body, { status: upstream.status, headers: out });
1829
1866
  }
1830
1867
 
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);
1868
+ ${SHARE_PUBLISH_WORKER_SOURCE}
1869
+ ${SHARE_MEDIA_WORKER_SOURCE}
1870
+ // Ownership for an edit of an existing <handle>/<slug>: WRITE_TOKEN is the
1871
+ // endpoint admin; a Phoenix caller must own the handle the way PUT and DELETE
1872
+ // decide it (the __handles claim, transferring it on a same-email account
1873
+ // move). An alternate handle must already be claimed: an edit never creates a
1874
+ // namespace. Returns an error Response, or null when the caller owns it.
1875
+ async function assertNamespaceOwner(env, auth, segments) {
1876
+ if (auth.kind !== 'phoenix') return null;
1877
+ const expected = phoenixHandle(auth);
1878
+ const handle = segments[0];
1879
+ if (!expected || handle !== expected) {
1880
+ const claim = handle ? await env.BUCKET.get('__handles/' + handle) : null;
1881
+ if (!claim) return json({ error: 'namespace mismatch', owner: expected }, 403);
1882
+ }
1883
+ const owned = await assertHandleOwner(env.BUCKET, handle, auth.owner, auth.email || '');
1884
+ if (owned.error) return json({ error: 'forbidden' }, 403);
1885
+ return null;
1860
1886
  }
1861
-
1862
1887
  // First writer of a handle owns it. Later PUTs from the same userId are fine;
1863
1888
  // a different userId whose email local-part collides gets 409, not a silent
1864
1889
  // overwrite — EXCEPT when the verified Phoenix email matches the claim's
@@ -1927,7 +1952,7 @@ async function transferHandle(bucket, handle, oldUserId, newUserId, email) {
1927
1952
  const obj = await bucket.get(o.key);
1928
1953
  if (!obj) continue;
1929
1954
  const headers = new Headers();
1930
- if (typeof obj.writeHttpMetadata === 'function') obj.writeHttpMetadata(headers);
1955
+ obj.writeHttpMetadata(headers);
1931
1956
  const customMetadata = { ...(obj.customMetadata || {}), owner: newUserId };
1932
1957
  await bucket.put(o.key, obj.body, {
1933
1958
  httpMetadata: headers.get('content-type') ? { contentType: headers.get('content-type') } : undefined,
@@ -1976,6 +2001,30 @@ function isIdentityGated(visibility) {
1976
2001
  return visibility === 'me' || visibility === 'org';
1977
2002
  }
1978
2003
 
2004
+ // One RFC 9110 byte range. R2 accepts offset/length; multipart ranges are not
2005
+ // useful for media playback and would require a multipart/byteranges encoder,
2006
+ // so reject them explicitly instead of returning the wrong bytes.
2007
+ function parseByteRange(value, size) {
2008
+ if (typeof value !== 'string' || !Number.isSafeInteger(size) || size < 0) return null;
2009
+ const match = /^bytes=(\\d*)-(\\d*)$/.exec(value.trim());
2010
+ if (!match || (!match[1] && !match[2]) || size === 0) return null;
2011
+ let start;
2012
+ let end;
2013
+ if (!match[1]) {
2014
+ const suffix = Number(match[2]);
2015
+ if (!Number.isSafeInteger(suffix) || suffix <= 0) return null;
2016
+ start = Math.max(0, size - suffix);
2017
+ end = size - 1;
2018
+ } else {
2019
+ start = Number(match[1]);
2020
+ if (!Number.isSafeInteger(start) || start < 0 || start >= size) return null;
2021
+ end = match[2] ? Number(match[2]) : size - 1;
2022
+ if (!Number.isSafeInteger(end) || end < start) return null;
2023
+ end = Math.min(end, size - 1);
2024
+ }
2025
+ return { offset: start, length: end - start + 1 };
2026
+ }
2027
+
1979
2028
  function managedCoverHeaders(visibility) {
1980
2029
  const headers = new Headers({ 'content-type': 'image/png' });
1981
2030
  // Token-gated (private) + identity-gated (me/org) covers must never be
@@ -2122,6 +2171,9 @@ async function readUsage(env, owner) {
2122
2171
  plan: typeof parsed.plan === 'string' ? parsed.plan : DEFAULT_SHARE_PLAN,
2123
2172
  rlStart: usageNumber(parsed.rlStart, 0),
2124
2173
  rlUsed: usageNumber(parsed.rlUsed, 0),
2174
+ multipartCharges: Array.isArray(parsed.multipartCharges)
2175
+ ? parsed.multipartCharges.filter(function (id) { return typeof id === 'string'; })
2176
+ : [],
2125
2177
  };
2126
2178
  }
2127
2179
  } catch (e) {
@@ -2142,11 +2194,12 @@ async function writeUsageCas(env, owner, prevEtag, usage) {
2142
2194
  const res = await env.BUCKET.put(usageKey(owner), body, opts);
2143
2195
  return res !== null;
2144
2196
  }
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;
2197
+ // Fresh ledger creation must also be atomic. Two first-ever publishes may
2198
+ // both read a miss; exactly one conditional create wins and the loser returns
2199
+ // false so withUsage re-reads the committed ledger and applies its mutation.
2200
+ opts.onlyIf = { etagDoesNotMatch: '*' };
2201
+ const res = await env.BUCKET.put(usageKey(owner), body, opts);
2202
+ return res !== null;
2150
2203
  }
2151
2204
 
2152
2205
  // CAS retry loop. fn(usage) returns { reject: Response } to fail loud without
@@ -2180,6 +2233,13 @@ async function chargeShareWrite(env, auth, params) {
2180
2233
  const now = Date.now();
2181
2234
  const out = await withUsage(env, auth.owner, function (usage) {
2182
2235
  const limits = planLimits(usage.plan);
2236
+ // Completing the same upload twice must not double-charge quota or rate.
2237
+ // The durable receipt set lives in the same CAS-protected ledger mutation as
2238
+ // the charge, so a crash cannot leave one committed without the other. Never
2239
+ // evict receipts: an old lost-response retry must remain exactly-once too.
2240
+ if (params.idempotencyKey && usage.multipartCharges.indexOf(params.idempotencyKey) !== -1) {
2241
+ return { commit: usage, result: { limits: limits, alreadyCharged: true } };
2242
+ }
2183
2243
  // Rate limit — only a user-initiated page PUT counts (countRate). A fixed 1h
2184
2244
  // window: reset when the window has rolled over, otherwise reject at the cap.
2185
2245
  if (params.countRate) {
@@ -2191,7 +2251,8 @@ async function chargeShareWrite(env, auth, params) {
2191
2251
  usage.rlUsed += 1;
2192
2252
  }
2193
2253
  // Per-file size cap.
2194
- if (typeof params.fileBytes === 'number' && params.fileBytes > limits.maxFileBytes) {
2254
+ const bypassFileCap = !!params.unlimitedVideoMultipart && unlimited;
2255
+ if (!bypassFileCap && typeof params.fileBytes === 'number' && params.fileBytes > limits.maxFileBytes) {
2195
2256
  return { reject: json({ error: 'file too large', maxBytes: limits.maxFileBytes, gotBytes: params.fileBytes }, 413) };
2196
2257
  }
2197
2258
  // Object (canonical page) count.
@@ -2206,6 +2267,9 @@ async function chargeShareWrite(env, auth, params) {
2206
2267
  return { reject: json({ error: 'storage limit reached', maxBytes: limits.maxBytes, usedBytes: usage.bytes }, 413) };
2207
2268
  }
2208
2269
  usage.bytes = Math.max(0, usage.bytes + params.charge);
2270
+ if (params.idempotencyKey) {
2271
+ usage.multipartCharges.push(params.idempotencyKey);
2272
+ }
2209
2273
  return { commit: usage, result: { limits: limits } };
2210
2274
  });
2211
2275
  if (out instanceof Response) return { error: out };