@phnx-labs/artifacts-cli 0.6.1 → 0.8.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.
@@ -1,6 +1,7 @@
1
1
  import { buildSync } from 'esbuild';
2
2
  import { dirname } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { BODY_REVISION_META, normalizeSharePath } from '../collab.js';
4
5
  let bundledWorker;
5
6
  let nodeWorkerScript;
6
7
  /** Bundle the Worker renderer into an ES module plus workerd-compiled WASM modules. */
@@ -100,6 +101,7 @@ export default {
100
101
  }
101
102
 
102
103
  const firstSeg = path.split('/').filter(Boolean)[0] || '';
104
+ if (firstSeg === '__collab' && collabConfig(env)) return handleCollab(request, env, url, path);
103
105
  if ((request.method === 'GET' || request.method === 'HEAD') && firstSeg.startsWith('__')) {
104
106
  return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
105
107
  }
@@ -114,7 +116,7 @@ export default {
114
116
  if (request.method === 'POST' && firstSeg === '__ticket') {
115
117
  const auth = await authorizeWrite(request, env);
116
118
  if (auth.error) return auth.error;
117
- const ticket = await signSelfTicket({ userId: auth.owner, email: auth.email || '' }, env);
119
+ const ticket = await signSelfTicket({ userId: auth.owner, email: auth.email || '', name: auth.name || '' }, env);
118
120
  if (!ticket) return json({ error: 'ticket minting is not configured' }, 501);
119
121
  return json({ ticket: ticket }, 200);
120
122
  }
@@ -150,6 +152,12 @@ export default {
150
152
  if (!rawToken) return json({ error: 'visibility private requires a viewer token' }, 400);
151
153
  viewerTokenHash = await sha256Hex(rawToken);
152
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
+ }
153
161
  const segments = path.split('/').filter(Boolean);
154
162
  if (auth.kind === 'phoenix') {
155
163
  // The caller's handle is normally derived from the email local-part. An
@@ -266,6 +274,7 @@ export default {
266
274
  if (labelSource) customMetadata['label-source'] = labelSource;
267
275
  if (ogTitle) customMetadata['og-title'] = ogTitle;
268
276
  if (ogDescription) customMetadata['og-description'] = ogDescription;
277
+ if (commentsHeader !== null) customMetadata['comment-policy'] = commentsHeader;
269
278
 
270
279
  // Revision retention (RUSH-2683): R2 has no native object versioning, so a
271
280
  // republish over an EXISTING key first copies the current object to
@@ -312,6 +321,23 @@ export default {
312
321
  realBytes = read.size;
313
322
  putBody = read.bytes;
314
323
  }
324
+ // A comment-enabled endpoint stamps the page's body revision (the hash
325
+ // comment anchors are checked against) in the same write, so it needs the
326
+ // bytes first. Managed bytes are buffered above; a WRITE_TOKEN HTML
327
+ // publish is buffered here, bounded, and only when collaboration is bound.
328
+ const collab = collabConfig(env);
329
+ const isHtmlPage = contentType.toLowerCase().indexOf('text/html') !== -1;
330
+ if (collab && isHtmlPage && auth.kind !== 'phoenix') {
331
+ const read = await readBodyBounded(request, COLLAB_HTML_MAX_BYTES);
332
+ if (read.oversize) {
333
+ return json({ error: 'file too large for a comment-enabled endpoint: max ' + COLLAB_HTML_MAX_BYTES + ' bytes', maxBytes: COLLAB_HTML_MAX_BYTES, gotBytes: read.size }, 413);
334
+ }
335
+ putBody = read.bytes;
336
+ }
337
+ if (collab && isHtmlPage) {
338
+ const revision = extractBodyRevision(putBody);
339
+ if (revision) customMetadata['body-revision'] = revision;
340
+ }
315
341
 
316
342
  // Revision retention + quota charge + canonical write as a BOUNDED
317
343
  // compare-and-swap loop (PHNX-3547). The old code read the current object,
@@ -334,6 +360,7 @@ export default {
334
360
  let chargedAlready = 0;
335
361
  let chargedNewCanonical = false;
336
362
  let putResult = null;
363
+ let replaced = null;
337
364
  for (let attempt = 0; attempt < MAX_PUT_ATTEMPTS; attempt++) {
338
365
  // The current object is needed for BOTH the revision copy and the charge
339
366
  // math, and even a first/no-revision publish must read before its
@@ -381,7 +408,10 @@ export default {
381
408
  if (existing && existing.etag) putOpts.onlyIf = { etagMatches: existing.etag };
382
409
  else putOpts.onlyIf = { etagDoesNotMatch: '*' };
383
410
  putResult = await env.BUCKET.put(path, putBody, putOpts);
384
- if (putResult !== null) break;
411
+ if (putResult !== null) {
412
+ replaced = existing;
413
+ break;
414
+ }
385
415
  // A failed create-only condition means another first publisher won.
386
416
  // Do not turn that loser into a republish: the caller must see the race.
387
417
  if (!existing) break;
@@ -400,7 +430,29 @@ export default {
400
430
  // its generated sibling so the next crawler receives a fresh card; BYO
401
431
  // publishes send no OG metadata and keep their explicitly uploaded cover.
402
432
  if (ogTitle) await env.BUCKET.delete(path + '.png');
403
- return json({ ok: true, url: url.origin + '/' + path, expiresAt: expiresAt || null, unlisted: visibility === 'unlisted', visibility }, 200);
433
+ // Register only a page comments can anchor to. A failed registration
434
+ // never fails the publish: the page is stored, and the caller is told.
435
+ // Threads carry over only from a live registered page at this address.
436
+ // Anything else (a free slug, an expired page nobody read since, a raw
437
+ // page) clears whatever Rush still holds there first, so a new page never
438
+ // inherits another page's comments. A raw page that replaces a registered
439
+ // one closes its threads, and the caller hears why.
440
+ const replacedMeta = (replaced && replaced.customMetadata) || {};
441
+ const replacedRevision = replacedMeta['body-revision'] || '';
442
+ const replacedExpiry = replacedMeta['expires-at'];
443
+ const continuesThreads = !!replacedRevision && !(replacedExpiry && Date.now() > Date.parse(replacedExpiry));
444
+ let registration = null;
445
+ if (collab && customMetadata['body-revision']) {
446
+ registration = continuesThreads
447
+ ? await registerShare(env, collab, url, path, customMetadata)
448
+ : await registerFreshShare(env, collab, url, path, customMetadata);
449
+ } else if (collab && continuesThreads) {
450
+ registration = { registered: false, error: 'the new page has no ' + BODY_REVISION_META + ' meta, so its review threads are closed' };
451
+ }
452
+ return withCollabStatus(
453
+ json({ ok: true, url: url.origin + '/' + path, expiresAt: expiresAt || null, unlisted: visibility === 'unlisted', visibility }, 200),
454
+ registration,
455
+ );
404
456
  }
405
457
 
406
458
  if (request.method === 'PATCH') {
@@ -484,6 +536,15 @@ export default {
484
536
  if (visibility === 'org') metadata.org_domain = emailDomain(auth.email);
485
537
  else delete metadata.org_domain;
486
538
  }
539
+ // Comment policy is a first-class field for the same reason: a reserved
540
+ // key, editable only here. null returns it to the visibility's default.
541
+ const previousPolicy = commentPolicyOf(existing.customMetadata || {});
542
+ if (Object.prototype.hasOwnProperty.call(edit, 'comments')) {
543
+ if (edit.comments === null) delete metadata['comment-policy'];
544
+ else if (isCommentPolicy(edit.comments)) metadata['comment-policy'] = edit.comments;
545
+ else return json({ error: 'comments must be off, audience, signed_in, or null' }, 400);
546
+ }
547
+ const policyChanged = commentPolicyOf(metadata) !== previousPolicy;
487
548
  const mode = edit.metaMode || 'merge';
488
549
  if (mode !== 'merge' && mode !== 'replace') return json({ error: 'metaMode must be merge or replace' }, 400);
489
550
  const incoming = edit.meta || {};
@@ -527,7 +588,16 @@ export default {
527
588
  await env.BUCKET.delete(path + '.png');
528
589
  }
529
590
  }
530
- return json({ ok: true, url: url.origin + '/' + path, label: metadata.label || null, meta: extraMetaOf(metadata), visibility: metadata.visibility || 'public', previousVisibility: previousVisibility }, 200);
591
+ // Rush keys anchor checks and comment gating off its registry, so a
592
+ // visibility or policy change re-registers the share.
593
+ const collab = collabConfig(env);
594
+ const registration = collab && metadata['body-revision'] && (visibilityChanged || policyChanged)
595
+ ? await registerShare(env, collab, url, path, metadata)
596
+ : null;
597
+ return withCollabStatus(
598
+ 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
+ registration,
600
+ );
531
601
  }
532
602
 
533
603
  if (request.method === 'GET' || request.method === 'HEAD') {
@@ -691,6 +761,12 @@ export default {
691
761
  // best-effort: serving the expiry 410 must never depend on the refund
692
762
  }
693
763
  }
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));
769
+ }
694
770
  return new Response('gone — this link has expired', { status: 410, headers: { 'content-type': 'text/plain' } });
695
771
  }
696
772
  // Resolve the viewer ONCE — needed both to gate me/org reads AND to decide
@@ -824,20 +900,31 @@ export default {
824
900
  // a .png cover) refunds both bytes and the object count; a retained
825
901
  // revision (3+ segments) refunds bytes only; a server-generated .png cover
826
902
  // was never charged, so it is skipped entirely.
903
+ // A registered page (one carrying a body revision) also purges its review
904
+ // threads, so a reused slug never inherits an old page's comments.
827
905
  let doomed = null;
828
906
  const isCover = path.endsWith('.png');
829
- if (auth.kind === 'phoenix' && !isCover && !firstSeg.startsWith('__')) {
907
+ const collab = collabConfig(env);
908
+ if ((auth.kind === 'phoenix' || collab) && !isCover && !firstSeg.startsWith('__')) {
830
909
  doomed = typeof env.BUCKET.head === 'function' ? await env.BUCKET.head(path) : await env.BUCKET.get(path);
831
910
  }
832
911
  await env.BUCKET.delete(path);
833
- if (doomed) {
912
+ if (doomed && auth.kind === 'phoenix') {
834
913
  const delSegs = path.split('/').filter(Boolean);
835
914
  await refundShareWrite(env, auth.owner, {
836
915
  refund: typeof doomed.size === 'number' ? doomed.size : 0,
837
916
  freeCanonical: delSegs.length === 2,
838
917
  });
839
918
  }
840
- return json({ ok: true, deleted: path }, 200);
919
+ const purge = collab && doomed && doomed.customMetadata && doomed.customMetadata['body-revision'] && path.split('/').filter(Boolean).length === 2
920
+ ? await purgeShare(collab, url, path)
921
+ : null;
922
+ const deleted = json({ ok: true, deleted: path }, 200);
923
+ if (purge) {
924
+ deleted.headers.set('x-collab-purged', purge.purged ? 'true' : 'false');
925
+ if (purge.error) deleted.headers.set('x-collab-error', headerSafe(purge.error));
926
+ }
927
+ return deleted;
841
928
  }
842
929
 
843
930
  return new Response('method not allowed', { status: 405 });
@@ -1035,7 +1122,7 @@ async function renderRevisions(bucket, origin, key, method, identityGated) {
1035
1122
  // before it ever reaches this Worker; see RESERVED_META_KEYS in publish.ts).
1036
1123
  // One list, reused both to strip a same-named --meta collision on write and
1037
1124
  // to split arbitrary --meta entries back out on read.
1038
- var RESERVED_METADATA_KEYS = ['expires-at', 'published-at', 'visibility', 'viewer-token-hash', 'owner', 'org_domain', 'agent', 'session', 'host', 'repo', 'date', 'avatar', 'label', 'label-source', 'og-title', 'og-description', 'og-generated', 'og-source-etag'];
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'];
1039
1126
  var PUBLIC_INBOX_DOMAINS = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'icloud.com', 'me.com'];
1040
1127
  var SHARE_COOKIE = '__Host-phoenix_share';
1041
1128
  var SHARE_COOKIE_MAX_AGE = 604800;
@@ -1293,6 +1380,10 @@ function renderAttributionBar(meta, handle, opts) {
1293
1380
  'style="background:#0b0b0c !important;color:#e8e8e8 !important">' +
1294
1381
  '<style>' +
1295
1382
  'html{padding-top:38px !important}' +
1383
+ // The review rail (collab.ts) is fixed to the viewport top on desktop; start
1384
+ // it below this bar so its header and Close button stay reachable. Below
1385
+ // 981px it is a bottom sheet and needs nothing.
1386
+ '@media(min-width:981px){.collab-rail{top:38px !important;height:calc(100vh - 38px) !important}}' +
1296
1387
  '.agents-share-bar{all:initial;position:fixed !important;top:0 !important;left:0 !important;right:0 !important;width:100% !important;z-index:2147483647 !important;box-sizing:border-box;display:flex !important;align-items:center;gap:12px;flex-wrap:nowrap;' +
1297
1388
  'padding:8px 16px !important;background:#0b0b0c !important;color:#e8e8e8 !important;border-bottom:1px solid #23232a !important;box-shadow:0 1px 3px rgba(0,0,0,.35) !important;' +
1298
1389
  'font:13px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,system-ui,sans-serif !important}' +
@@ -1398,6 +1489,345 @@ function renderAssetViewer(pathname, kind, meta, handle, opts) {
1398
1489
  '</style></head><body>' + bar + '<div class="ashv">' + media + '</div></body></html>';
1399
1490
  }
1400
1491
 
1492
+ // --- Hosted review threads (PHNX-3835) ---------------------------------------
1493
+ // The Worker is the only party Rush Cloud trusts for review threads: it knows
1494
+ // the reader (resolveViewer), applies the page's own visibility gate plus the
1495
+ // comment policy, and forwards to Rush's /internal/artifact-collab with the
1496
+ // service token and the X-Collab-* headers Rush acts on. Rush never sees a
1497
+ // browser credential. Both env values unset = none of this runs.
1498
+ var COLLAB_POLICIES = ['off', 'audience', 'signed_in'];
1499
+ var COLLAB_HTML_MAX_BYTES = 25 * MiB;
1500
+ var COLLAB_BODY_MAX_BYTES = 64 * 1024;
1501
+ var COLLAB_REGISTRY_TIMEOUT_MS = 5000;
1502
+ var COLLAB_REVISION_SCAN_BYTES = 16 * 1024;
1503
+ var BODY_REVISION_META = ${JSON.stringify(BODY_REVISION_META)};
1504
+ // The viewer's own normalizer, so /u/plan, /u/plan/ and /u/plan/index.html are
1505
+ // one share on both sides of the wire.
1506
+ var normalizeSharePath = ${normalizeSharePath};
1507
+
1508
+ function collabConfig(env) {
1509
+ const base = typeof env.COLLAB_API_BASE === 'string' ? env.COLLAB_API_BASE.trim().replace(/\\/+$/, '') : '';
1510
+ const token = typeof env.COLLAB_SERVICE_TOKEN === 'string' ? env.COLLAB_SERVICE_TOKEN.trim() : '';
1511
+ if (!base || !token) return null;
1512
+ return { endpoint: base + '/internal/artifact-collab', token: token };
1513
+ }
1514
+
1515
+ function isCommentPolicy(value) {
1516
+ return typeof value === 'string' && COLLAB_POLICIES.indexOf(value) !== -1;
1517
+ }
1518
+
1519
+ // An explicit policy wins; otherwise the visibility decides. An audience page
1520
+ // (me, org) lets its audience comment, a capability link lets any signed-in
1521
+ // reader, and a public page starts with comments off.
1522
+ function commentPolicyOf(meta) {
1523
+ const stored = meta && meta['comment-policy'];
1524
+ if (isCommentPolicy(stored)) return stored;
1525
+ const visibility = (meta && meta.visibility) || 'public';
1526
+ if (visibility === 'me' || visibility === 'org') return 'audience';
1527
+ if (visibility === 'unlisted' || visibility === 'private') return 'signed_in';
1528
+ return 'off';
1529
+ }
1530
+
1531
+ // read is decided by the page's own gate before this runs. Commenting needs a
1532
+ // signed-in reader, a policy other than off, and, under audience, membership:
1533
+ // the owner for me, the stamped email domain for org, any signed-in reader
1534
+ // for a link or public page. Resolving needs exactly what commenting needs.
1535
+ function collabGrant(meta, identity, owner) {
1536
+ const visibility = meta.visibility || 'public';
1537
+ const policy = commentPolicyOf(meta);
1538
+ let inAudience = true;
1539
+ if (visibility === 'me') inAudience = owner;
1540
+ else if (visibility === 'org') inAudience = !!identity && !!meta.org_domain && emailDomain(identity.email) === String(meta.org_domain).toLowerCase();
1541
+ const comment = !!identity && policy !== 'off' && (policy === 'signed_in' || inAudience);
1542
+ return { read: true, comment: comment, resolve: comment };
1543
+ }
1544
+
1545
+ // The rendered page's <meta name="artifacts-body-revision">, the hash every
1546
+ // comment anchor carries. '' for a page the renderer did not produce. The
1547
+ // renderer writes it in the first lines of <head>, so only a bounded prefix
1548
+ // is decoded and scanned, linearly: a publish body is attacker-controlled, and
1549
+ // a regex over all of it backtracks quadratically on '<meta' with no '>'.
1550
+ function extractBodyRevision(bytes) {
1551
+ const head = new TextDecoder().decode(bytes.subarray(0, COLLAB_REVISION_SCAN_BYTES));
1552
+ const opener = /<meta/gi;
1553
+ let found;
1554
+ while ((found = opener.exec(head)) !== null) {
1555
+ const end = head.indexOf('>', found.index);
1556
+ if (end === -1) return '';
1557
+ const tag = head.slice(found.index, end + 1);
1558
+ opener.lastIndex = end + 1;
1559
+ if (tag.length > 1024) continue;
1560
+ const name = /\\bname\\s*=\\s*["']([^"']*)["']/i.exec(tag);
1561
+ if (!name || name[1] !== BODY_REVISION_META) continue;
1562
+ const content = /\\bcontent\\s*=\\s*["']([^"']*)["']/i.exec(tag);
1563
+ const value = content ? content[1].trim() : '';
1564
+ return /^sha256:[0-9a-f]{64}$/.test(value) ? value : '';
1565
+ }
1566
+ return '';
1567
+ }
1568
+
1569
+ function collabShareId(url, key) {
1570
+ return url.host + normalizeSharePath('/' + key);
1571
+ }
1572
+
1573
+ function collabJson(body, status) {
1574
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } });
1575
+ }
1576
+
1577
+ function headerSafe(text) {
1578
+ return String(text).replace(/[^\\x20-\\x7e]/g, '?').slice(0, 300);
1579
+ }
1580
+
1581
+ function withCollabStatus(response, registration) {
1582
+ if (!registration) return response;
1583
+ response.headers.set('x-collab-registered', registration.registered ? 'true' : 'false');
1584
+ if (registration.error) response.headers.set('x-collab-error', headerSafe(registration.error));
1585
+ return response;
1586
+ }
1587
+
1588
+ // Registry calls ride the publish/delete response, so they are bounded and
1589
+ // report rather than throw. Both are mutations: Rush requires an
1590
+ // Idempotency-Key and an X-Collab-Share naming the same share as the call.
1591
+ async function collabRegistryCall(collab, method, path, shareId, body) {
1592
+ const headers = {
1593
+ authorization: 'Bearer ' + collab.token,
1594
+ accept: 'application/json',
1595
+ 'idempotency-key': crypto.randomUUID(),
1596
+ 'x-collab-share': shareId,
1597
+ };
1598
+ if (body !== undefined) headers['content-type'] = 'application/json';
1599
+ let res;
1600
+ try {
1601
+ res = await fetch(collab.endpoint + path, {
1602
+ method: method,
1603
+ headers: headers,
1604
+ body: body === undefined ? undefined : JSON.stringify(body),
1605
+ signal: AbortSignal.timeout(COLLAB_REGISTRY_TIMEOUT_MS),
1606
+ });
1607
+ } catch (error) {
1608
+ return { error: 'collaboration service unreachable: ' + (error && error.message ? error.message : String(error)) };
1609
+ }
1610
+ let detail = '';
1611
+ try {
1612
+ const parsed = await res.json();
1613
+ if (parsed && typeof parsed.error === 'string') detail = parsed.error;
1614
+ } catch {
1615
+ // a non-JSON body carries no detail worth surfacing
1616
+ }
1617
+ if (!res.ok) return { status: res.status, error: 'collaboration service answered ' + res.status + (detail ? ': ' + detail : '') };
1618
+ return { status: res.status };
1619
+ }
1620
+
1621
+ async function registerShare(env, collab, url, key, meta) {
1622
+ const shareId = collabShareId(url, key);
1623
+ const result = await collabRegistryCall(collab, 'PUT', '/shares', shareId, {
1624
+ share_id: shareId,
1625
+ owner_actor_id: meta.owner || '',
1626
+ org_domain: meta.org_domain || null,
1627
+ visibility: meta.visibility || 'public',
1628
+ comment_policy: commentPolicyOf(meta),
1629
+ current_revision: meta['body-revision'],
1630
+ title: meta.label || meta['og-title'] || null,
1631
+ producer: {
1632
+ agent: meta.agent || null,
1633
+ session: meta.session || null,
1634
+ host: meta.host || null,
1635
+ repo: meta.repo || null,
1636
+ },
1637
+ });
1638
+ return result.error ? { registered: false, error: result.error } : { registered: true };
1639
+ }
1640
+
1641
+ // A share Rush never heard of has nothing to purge.
1642
+ async function purgeShare(collab, url, key) {
1643
+ const shareId = collabShareId(url, key);
1644
+ const result = await collabRegistryCall(collab, 'DELETE', '/shares?share_id=' + encodeURIComponent(shareId), shareId);
1645
+ return result.error && result.status !== 404 ? { purged: false, error: result.error } : { purged: true };
1646
+ }
1647
+
1648
+ async function registerFreshShare(env, collab, url, key, meta) {
1649
+ const purge = await purgeShare(collab, url, key);
1650
+ if (!purge.purged) return { registered: false, error: 'could not clear review threads left at this address: ' + purge.error };
1651
+ return registerShare(env, collab, url, key, meta);
1652
+ }
1653
+
1654
+ // Browser route -> Rush route, and the capability a write needs.
1655
+ function collabRoute(method, rest) {
1656
+ if (method === 'GET' && rest === 'context') return { op: 'context' };
1657
+ if (method === 'GET' && rest === 'threads') return { op: 'read', upstream: '/threads' };
1658
+ if (method === 'GET' && rest === 'events') return { op: 'events', upstream: '/events' };
1659
+ if (method === 'POST' && rest === 'threads') return { op: 'write', need: 'comment', upstream: '/threads', fields: ['anchor', 'body'] };
1660
+ let match = /^threads\\/([^/]+)\\/replies$/.exec(rest);
1661
+ if (method === 'POST' && match) return { op: 'write', need: 'comment', upstream: '/threads/' + encodeURIComponent(match[1]) + '/replies', fields: ['body'] };
1662
+ match = /^threads\\/([^/]+)$/.exec(rest);
1663
+ if (method === 'PATCH' && match) return { op: 'write', need: 'resolve', upstream: '/threads/' + encodeURIComponent(match[1]), fields: ['status'] };
1664
+ match = /^comments\\/([^/]+)$/.exec(rest);
1665
+ if (method === 'PATCH' && match) return { op: 'write', need: 'comment', upstream: '/comments/' + encodeURIComponent(match[1]), fields: ['body', 'deleted'] };
1666
+ return null;
1667
+ }
1668
+
1669
+ // A token-gated (private) page's key rides its own URL, not the same-origin
1670
+ // collab call. The browser's Referer for that call names the page, key
1671
+ // included; accepting it there is no weaker than ?k= itself, since the key is
1672
+ // the secret either way.
1673
+ function refererViewerKey(request, url, sharePath) {
1674
+ const referer = request.headers.get('referer');
1675
+ if (!referer) return '';
1676
+ try {
1677
+ const page = new URL(referer);
1678
+ if (page.origin !== url.origin) return '';
1679
+ if (normalizeSharePath(decodeURIComponent(page.pathname)) !== sharePath) return '';
1680
+ return page.searchParams.get('k') || '';
1681
+ } catch {
1682
+ return '';
1683
+ }
1684
+ }
1685
+
1686
+ function collabDisplayName(identity) {
1687
+ if (identity.name) return identity.name;
1688
+ const local = String(identity.email || '').split('@')[0];
1689
+ return local || identity.userId;
1690
+ }
1691
+
1692
+ function collabAgentName(raw) {
1693
+ const value = String(raw || '').trim().toLowerCase();
1694
+ return /^[a-z0-9][a-z0-9._-]{0,63}$/.test(value) ? value : '';
1695
+ }
1696
+
1697
+ async function handleCollab(request, env, url, path) {
1698
+ const collab = collabConfig(env);
1699
+ const route = collabRoute(request.method, path.slice('__collab/'.length));
1700
+ if (!route) return collabJson({ error: 'not found' }, 404);
1701
+
1702
+ // Writes name their share in the JSON body (the viewer's contract), so the
1703
+ // small body is read before anything is forwarded.
1704
+ let payload = null;
1705
+ if (route.op === 'write') {
1706
+ const read = await readBodyBounded(request, COLLAB_BODY_MAX_BYTES);
1707
+ if (read.oversize) return collabJson({ error: 'request body too large' }, 413);
1708
+ try {
1709
+ payload = JSON.parse(new TextDecoder().decode(read.bytes) || '{}');
1710
+ } catch {
1711
+ return collabJson({ error: 'body must be JSON' }, 400);
1712
+ }
1713
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return collabJson({ error: 'body must be a JSON object' }, 400);
1714
+ }
1715
+ const rawShare = url.searchParams.get('share') || (payload && typeof payload.share === 'string' ? payload.share : '');
1716
+ if (!rawShare) return collabJson({ error: 'share is required' }, 400);
1717
+ let sharePath;
1718
+ try {
1719
+ sharePath = normalizeSharePath(decodeURIComponent(rawShare));
1720
+ } catch {
1721
+ return collabJson({ error: 'share is not a valid path' }, 400);
1722
+ }
1723
+ const key = sharePath.replace(/^\\/+/, '');
1724
+ if (!key || key.split('/')[0].startsWith('__')) return collabJson({ error: 'unknown share' }, 404);
1725
+ const obj = await env.BUCKET.head(key);
1726
+ const meta = (obj && obj.customMetadata) || {};
1727
+ const expiresAt = meta['expires-at'];
1728
+ // A page without a body revision was never registered (or its threads were
1729
+ // closed by a raw republish): there is nothing to anchor to.
1730
+ if (!obj || (expiresAt && Date.now() > Date.parse(expiresAt)) || !meta['body-revision']) return collabJson({ error: 'unknown share' }, 404);
1731
+
1732
+ // Read = may open the page: the same visibility and viewer-key gates the
1733
+ // page GET applies, evaluated against the page's own URL.
1734
+ const pageUrl = new URL(url.origin);
1735
+ pageUrl.pathname = '/' + key;
1736
+ const viewerKey = url.searchParams.get('k') || refererViewerKey(request, url, sharePath);
1737
+ if (viewerKey) pageUrl.searchParams.set('k', viewerKey);
1738
+ const viewer = await resolveViewer(request, env, url);
1739
+ const identity = viewer.identity || null;
1740
+ const readable = !(await gateVisibility(pageUrl, env, obj, identity)) && !(await gateTokenRead(request, pageUrl, obj, identity));
1741
+ if (!readable) return collabJson({ error: 'forbidden' }, 403);
1742
+ const owner = !!identity && (meta.owner === identity.userId || (await holdsHandleClaim(env.BUCKET, key.split('/')[0], identity.userId)));
1743
+ const grant = collabGrant(meta, identity, owner);
1744
+
1745
+ // An agent acts with its owner's login and is labelled as an agent. Only a
1746
+ // Phoenix bearer from the share's owner may claim that; a browser cookie
1747
+ // never can, so a page script cannot pass itself off as the owner's agent.
1748
+ const claimedKind = (request.headers.get('x-collab-actor-kind') || '').trim().toLowerCase();
1749
+ if (claimedKind && claimedKind !== 'human' && claimedKind !== 'agent') return collabJson({ error: 'x-collab-actor-kind must be human or agent' }, 400);
1750
+ let agent = '';
1751
+ if (claimedKind === 'agent') {
1752
+ if (viewer.via !== 'bearer' || !owner) return collabJson({ error: "only the share owner's Phoenix login may act as an agent" }, 403);
1753
+ agent = collabAgentName(request.headers.get('x-collab-agent'));
1754
+ if (!agent) return collabJson({ error: 'x-collab-agent must name the agent harness ([a-z0-9._-], up to 64)' }, 400);
1755
+ }
1756
+
1757
+ if (route.op === 'context') {
1758
+ const producer = {};
1759
+ for (const field of ['agent', 'session', 'host', 'repo']) if (meta[field]) producer[field] = meta[field];
1760
+ return collabJson({
1761
+ share: sharePath,
1762
+ visibility: meta.visibility || 'public',
1763
+ revision: meta['body-revision'],
1764
+ viewer: identity ? { id: identity.userId, name: collabDisplayName(identity) } : null,
1765
+ permissions: grant,
1766
+ producer: Object.keys(producer).length ? producer : null,
1767
+ }, 200);
1768
+ }
1769
+
1770
+ if (route.op === 'write' && !grant[route.need]) return collabJson({ error: 'forbidden' }, 403);
1771
+ const idempotencyKey = request.headers.get('idempotency-key') || '';
1772
+ if (route.op === 'write' && (!idempotencyKey || idempotencyKey.length > 255)) {
1773
+ return collabJson({ error: 'Idempotency-Key is required (up to 255 characters)' }, 400);
1774
+ }
1775
+
1776
+ const headers = new Headers({
1777
+ authorization: 'Bearer ' + collab.token,
1778
+ accept: route.op === 'events' ? 'text/event-stream' : 'application/json',
1779
+ 'x-collab-share': collabShareId(url, key),
1780
+ 'x-collab-can': ['read', 'comment', 'resolve'].filter((cap) => grant[cap]).join(','),
1781
+ });
1782
+ if (identity) {
1783
+ const name = collabDisplayName(identity);
1784
+ headers.set('x-collab-actor-id', identity.userId);
1785
+ // Headers are latin1 on the wire. A name outside printable ASCII travels
1786
+ // percent-encoded and says so, rather than being folded or dropped.
1787
+ if (/^[\\x20-\\x7e]*$/.test(name)) headers.set('x-collab-actor-name', name);
1788
+ else {
1789
+ headers.set('x-collab-actor-name', encodeURIComponent(name));
1790
+ headers.set('x-collab-actor-name-encoding', 'percent');
1791
+ }
1792
+ headers.set('x-collab-actor-kind', agent ? 'agent' : 'human');
1793
+ if (agent) headers.set('x-collab-agent', agent);
1794
+ }
1795
+ let body;
1796
+ if (route.op === 'write') {
1797
+ // Only the fields Rush's route takes; the viewer's share key and anything
1798
+ // else stay at the Worker.
1799
+ const forward = {};
1800
+ for (const field of route.fields) if (Object.prototype.hasOwnProperty.call(payload, field)) forward[field] = payload[field];
1801
+ body = JSON.stringify(forward);
1802
+ headers.set('content-type', 'application/json');
1803
+ headers.set('idempotency-key', idempotencyKey);
1804
+ }
1805
+ const query = new URLSearchParams();
1806
+ const after = url.searchParams.get('after');
1807
+ if (after !== null && route.op !== 'write') query.set('after', after);
1808
+ const lastEventId = request.headers.get('last-event-id');
1809
+ if (route.op === 'events' && lastEventId) headers.set('last-event-id', lastEventId);
1810
+ const target = collab.endpoint + route.upstream + (query.toString() ? '?' + query.toString() : '');
1811
+
1812
+ let upstream;
1813
+ try {
1814
+ upstream = await fetch(target, { method: request.method, headers: headers, body: body });
1815
+ } catch (error) {
1816
+ return collabJson({ error: 'collaboration service unreachable' }, 502);
1817
+ }
1818
+ // A 401 here is Rush refusing the Worker's service token, never the reader:
1819
+ // surface it as the deployment fault it is.
1820
+ if (upstream.status === 401) {
1821
+ try { await upstream.body?.cancel(); } catch { /* nothing left to release */ }
1822
+ return collabJson({ error: 'collaboration service rejected the share Worker' }, 502);
1823
+ }
1824
+ // Pass the body through as a stream: an SSE response must reach the reader
1825
+ // event by event, not when Rush closes it.
1826
+ const out = new Headers({ 'cache-control': 'no-store' });
1827
+ out.set('content-type', upstream.headers.get('content-type') || 'application/json');
1828
+ return new Response(upstream.body, { status: upstream.status, headers: out });
1829
+ }
1830
+
1401
1831
  function json(body, status) {
1402
1832
  return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
1403
1833
  }
@@ -1893,11 +2323,41 @@ async function hmacHex(secret, data) {
1893
2323
  return bufToHex(sig);
1894
2324
  }
1895
2325
 
2326
+ // The signed identity payload shared by the cookie and the self-ticket:
2327
+ // userId|email|exp, plus |n:<base64url display name> when the identity has one
2328
+ // (PHNX-3835, for review-thread bylines). A payload minted before the name
2329
+ // suffix still verifies and simply carries no name.
2330
+ function identityPayload(identity, exp) {
2331
+ const payload = identity.userId + '|' + (identity.email || '') + '|' + exp;
2332
+ return identity.name ? payload + '|n:' + toB64Url(identity.name) : payload;
2333
+ }
2334
+
2335
+ function parseIdentityPayload(payload) {
2336
+ let name = '';
2337
+ const cut = payload.lastIndexOf('|n:');
2338
+ if (cut >= 0) {
2339
+ try {
2340
+ name = fromB64Url(payload.slice(cut + 3));
2341
+ } catch {
2342
+ return null;
2343
+ }
2344
+ payload = payload.slice(0, cut);
2345
+ }
2346
+ const first = payload.indexOf('|');
2347
+ const last = payload.lastIndexOf('|');
2348
+ if (first < 0 || last <= first) return null;
2349
+ const userId = payload.slice(0, first);
2350
+ const email = payload.slice(first + 1, last);
2351
+ const exp = Number(payload.slice(last + 1));
2352
+ if (!userId || !Number.isFinite(exp) || Math.floor(Date.now() / 1000) > exp) return null;
2353
+ return name ? { userId: userId, email: email, name: name } : { userId: userId, email: email };
2354
+ }
2355
+
1896
2356
  async function signShareCookie(identity, env) {
1897
2357
  const secret = typeof env.WRITE_TOKEN === 'string' ? env.WRITE_TOKEN : '';
1898
2358
  if (!secret) return '';
1899
2359
  const exp = Math.floor(Date.now() / 1000) + SHARE_COOKIE_MAX_AGE;
1900
- const payload = identity.userId + '|' + (identity.email || '') + '|' + exp;
2360
+ const payload = identityPayload(identity, exp);
1901
2361
  const sig = await hmacHex(secret, payload);
1902
2362
  const value = toB64Url(payload) + '.' + sig;
1903
2363
  return SHARE_COOKIE + '=' + value + '; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=' + SHARE_COOKIE_MAX_AGE;
@@ -1915,7 +2375,7 @@ async function signSelfTicket(identity, env) {
1915
2375
  const secret = typeof env.WRITE_TOKEN === 'string' ? env.WRITE_TOKEN : '';
1916
2376
  if (!secret || !identity || !identity.userId) return '';
1917
2377
  const exp = Math.floor(Date.now() / 1000) + SELF_TICKET_MAX_AGE;
1918
- const payload = identity.userId + '|' + (identity.email || '') + '|' + exp;
2378
+ const payload = identityPayload(identity, exp);
1919
2379
  const sig = await hmacHex(secret, 'ticket:' + payload);
1920
2380
  return toB64Url(payload) + '.' + sig;
1921
2381
  }
@@ -1934,14 +2394,7 @@ async function verifySelfTicket(ticket, env) {
1934
2394
  const sig = ticket.slice(dot + 1);
1935
2395
  const expected = await hmacHex(secret, 'ticket:' + payload);
1936
2396
  if (!safeEqual(sig, expected)) return null;
1937
- const first = payload.indexOf('|');
1938
- const last = payload.lastIndexOf('|');
1939
- if (first < 0 || last <= first) return null;
1940
- const userId = payload.slice(0, first);
1941
- const email = payload.slice(first + 1, last);
1942
- const exp = Number(payload.slice(last + 1));
1943
- if (!userId || !Number.isFinite(exp) || Math.floor(Date.now() / 1000) > exp) return null;
1944
- return { userId: userId, email: email };
2397
+ return parseIdentityPayload(payload);
1945
2398
  }
1946
2399
 
1947
2400
  // Single-use enforcement for a self-signed ticket: claim its signature the first
@@ -1979,14 +2432,7 @@ async function identityFromCookie(request, env) {
1979
2432
  const sig = raw.slice(dot + 1);
1980
2433
  const expected = await hmacHex(secret, payload);
1981
2434
  if (!safeEqual(sig, expected)) return null;
1982
- const first = payload.indexOf('|');
1983
- const last = payload.lastIndexOf('|');
1984
- if (first < 0 || last <= first) return null;
1985
- const userId = payload.slice(0, first);
1986
- const email = payload.slice(first + 1, last);
1987
- const cookieExp = Number(payload.slice(last + 1));
1988
- if (!userId || !Number.isFinite(cookieExp) || Math.floor(Date.now() / 1000) > cookieExp) return null;
1989
- return { userId: userId, email: email };
2435
+ return parseIdentityPayload(payload);
1990
2436
  }
1991
2437
 
1992
2438
  async function redeemTicket(ticket, env) {
@@ -2009,17 +2455,27 @@ async function redeemTicket(ticket, env) {
2009
2455
  } catch {
2010
2456
  return null;
2011
2457
  }
2458
+ return phoenixIdentity(body);
2459
+ }
2460
+
2461
+ // {userId, email, name?} from a Phoenix identity body (/auth/me, /auth/ticket,
2462
+ // or a test hook's claims). name is optional: Phoenix sends it when the account
2463
+ // has one, and review threads fall back to the email local part without it.
2464
+ function phoenixIdentity(body) {
2012
2465
  if (!body || typeof body.userId !== 'string' || !body.userId) return null;
2013
- return { userId: body.userId, email: typeof body.email === 'string' ? body.email : '' };
2466
+ const identity = { userId: body.userId, email: typeof body.email === 'string' ? body.email : '' };
2467
+ if (typeof body.name === 'string' && body.name.trim()) identity.name = body.name.trim();
2468
+ return identity;
2014
2469
  }
2015
2470
 
2471
+ // via records HOW the reader proved who they are: 'bearer' (a Phoenix token,
2472
+ // what the CLI and agents send) or 'cookie' (a browser). Only a bearer may act
2473
+ // as an agent on review threads.
2016
2474
  async function resolveViewer(request, env, url) {
2017
- const claims = await hooks.verifyPhoenixToken(request, env);
2018
- if (claims && typeof claims.userId === 'string' && claims.userId) {
2019
- return { identity: { userId: claims.userId, email: typeof claims.email === 'string' ? claims.email : '' } };
2020
- }
2475
+ const claims = phoenixIdentity(await hooks.verifyPhoenixToken(request, env));
2476
+ if (claims) return { identity: claims, via: 'bearer' };
2021
2477
  const cookieId = await identityFromCookie(request, env);
2022
- if (cookieId) return { identity: cookieId };
2478
+ if (cookieId) return { identity: cookieId, via: 'cookie' };
2023
2479
  const ticket = url.searchParams.get('phoenix_ticket');
2024
2480
  if (!ticket) return {};
2025
2481
  // Prefer the locally-verifiable self-signed ticket (PHNX-3370, no network), and
@@ -2120,8 +2576,7 @@ async function defaultVerifyPhoenixToken(request, env) {
2120
2576
  } catch {
2121
2577
  return null;
2122
2578
  }
2123
- if (!body || typeof body.userId !== 'string' || !body.userId) return null;
2124
- return { userId: body.userId, email: typeof body.email === 'string' ? body.email : '' };
2579
+ return phoenixIdentity(body);
2125
2580
  }
2126
2581
 
2127
2582
  // Write principals, in order: WRITE_TOKEN equality (admin/BYO), then a Phoenix
@@ -2138,14 +2593,12 @@ async function authorizeWrite(request, env) {
2138
2593
  if (env.WRITE_TOKEN && safeEqual(presented, env.WRITE_TOKEN)) {
2139
2594
  return { kind: 'byo', owner: env.SHARE_NAMESPACE || 'byo' };
2140
2595
  }
2141
- const claims = await hooks.verifyPhoenixToken(request, env);
2142
- if (claims && typeof claims.userId === 'string' && claims.userId) {
2143
- return { kind: 'phoenix', owner: claims.userId, email: typeof claims.email === 'string' ? claims.email : '' };
2144
- }
2596
+ const claims = phoenixIdentity(await hooks.verifyPhoenixToken(request, env));
2597
+ if (claims) return { kind: 'phoenix', owner: claims.userId, email: claims.email, name: claims.name || '' };
2145
2598
  }
2146
2599
  const cookieId = await identityFromCookie(request, env);
2147
2600
  if (cookieId && cookieId.userId) {
2148
- return { kind: 'phoenix', owner: cookieId.userId, email: typeof cookieId.email === 'string' ? cookieId.email : '' };
2601
+ return { kind: 'phoenix', owner: cookieId.userId, email: typeof cookieId.email === 'string' ? cookieId.email : '', name: cookieId.name || '' };
2149
2602
  }
2150
2603
  return { error: json({ error: 'unauthorized' }, 401) };
2151
2604
  }