@phnx-labs/artifacts-cli 0.9.13 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +7 -9
  3. package/dist/cli.d.ts +1 -2
  4. package/dist/cli.js +34 -190
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/auth.d.ts +3 -1
  7. package/dist/commands/auth.js +17 -18
  8. package/dist/commands/auth.js.map +1 -1
  9. package/dist/commands/comments.js +2 -2
  10. package/dist/commands/comments.js.map +1 -1
  11. package/dist/commands/new.js +3 -3
  12. package/dist/commands/new.js.map +1 -1
  13. package/dist/commands/share.d.ts +58 -111
  14. package/dist/commands/share.js +314 -638
  15. package/dist/commands/share.js.map +1 -1
  16. package/dist/lib/collab.d.ts +3 -3
  17. package/dist/lib/collab.js +183 -13
  18. package/dist/lib/collab.js.map +1 -1
  19. package/dist/lib/components.js +0 -1
  20. package/dist/lib/components.js.map +1 -1
  21. package/dist/lib/config.d.ts +0 -17
  22. package/dist/lib/config.js.map +1 -1
  23. package/dist/lib/embedded-html.d.ts +1 -1
  24. package/dist/lib/embedded-html.js +0 -15
  25. package/dist/lib/embedded-html.js.map +1 -1
  26. package/dist/lib/freshness.d.ts +2 -6
  27. package/dist/lib/freshness.js +4 -33
  28. package/dist/lib/freshness.js.map +1 -1
  29. package/dist/lib/header-actions.d.ts +10 -37
  30. package/dist/lib/header-actions.js +19 -94
  31. package/dist/lib/header-actions.js.map +1 -1
  32. package/dist/lib/metadata-menu.d.ts +10 -33
  33. package/dist/lib/metadata-menu.js +12 -51
  34. package/dist/lib/metadata-menu.js.map +1 -1
  35. package/dist/lib/reader-anchors.d.ts +3 -3
  36. package/dist/lib/reader-anchors.js +7 -4
  37. package/dist/lib/reader-anchors.js.map +1 -1
  38. package/dist/lib/render.d.ts +2 -19
  39. package/dist/lib/render.js +37 -321
  40. package/dist/lib/render.js.map +1 -1
  41. package/dist/lib/section-collapse.d.ts +1 -2
  42. package/dist/lib/section-collapse.js +1 -2
  43. package/dist/lib/section-collapse.js.map +1 -1
  44. package/dist/lib/selection-toolbar.d.ts +9 -0
  45. package/dist/lib/selection-toolbar.js +49 -0
  46. package/dist/lib/selection-toolbar.js.map +1 -0
  47. package/dist/lib/share/backend.d.ts +8 -75
  48. package/dist/lib/share/backend.js +11 -123
  49. package/dist/lib/share/backend.js.map +1 -1
  50. package/dist/lib/share/config.d.ts +0 -79
  51. package/dist/lib/share/config.js +3 -175
  52. package/dist/lib/share/config.js.map +1 -1
  53. package/dist/lib/share/delete.d.ts +3 -14
  54. package/dist/lib/share/delete.js +8 -12
  55. package/dist/lib/share/delete.js.map +1 -1
  56. package/dist/lib/share/http-error.d.ts +12 -0
  57. package/dist/lib/share/http-error.js +32 -0
  58. package/dist/lib/share/http-error.js.map +1 -1
  59. package/dist/lib/share/media.d.ts +1 -6
  60. package/dist/lib/share/media.js +9 -17
  61. package/dist/lib/share/media.js.map +1 -1
  62. package/dist/lib/share/og.d.ts +0 -3
  63. package/dist/lib/share/og.js +2 -4
  64. package/dist/lib/share/og.js.map +1 -1
  65. package/dist/lib/share/people.d.ts +56 -0
  66. package/dist/lib/share/people.js +139 -0
  67. package/dist/lib/share/people.js.map +1 -0
  68. package/dist/lib/share/provision.d.ts +7 -120
  69. package/dist/lib/share/provision.js +30 -290
  70. package/dist/lib/share/provision.js.map +1 -1
  71. package/dist/lib/share/publish.d.ts +21 -63
  72. package/dist/lib/share/publish.js +44 -131
  73. package/dist/lib/share/publish.js.map +1 -1
  74. package/dist/lib/share/visibility.d.ts +13 -36
  75. package/dist/lib/share/visibility.js +8 -35
  76. package/dist/lib/share/visibility.js.map +1 -1
  77. package/dist/lib/share/worker-media-template.js +1 -1
  78. package/dist/lib/share/worker-people-template.d.ts +1 -0
  79. package/dist/lib/share/worker-people-template.js +491 -0
  80. package/dist/lib/share/worker-people-template.js.map +1 -0
  81. package/dist/lib/share/worker-publish-template.d.ts +1 -1
  82. package/dist/lib/share/worker-publish-template.js +5 -0
  83. package/dist/lib/share/worker-publish-template.js.map +1 -1
  84. package/dist/lib/share/worker-template.d.ts +2 -14
  85. package/dist/lib/share/worker-template.js +303 -52
  86. package/dist/lib/share/worker-template.js.map +1 -1
  87. package/dist/lib/templates.d.ts +1 -2
  88. package/dist/lib/templates.js +1 -19
  89. package/dist/lib/templates.js.map +1 -1
  90. package/dist/lib/validate.js +1 -29
  91. package/dist/lib/validate.js.map +1 -1
  92. package/package.json +1 -4
  93. package/dist/commands/answers.d.ts +0 -6
  94. package/dist/commands/answers.js +0 -91
  95. package/dist/commands/answers.js.map +0 -1
  96. package/dist/commands/favorite.d.ts +0 -9
  97. package/dist/commands/favorite.js +0 -59
  98. package/dist/commands/favorite.js.map +0 -1
  99. package/dist/commands/history.d.ts +0 -4
  100. package/dist/commands/history.js +0 -29
  101. package/dist/commands/history.js.map +0 -1
  102. package/dist/commands/notes.d.ts +0 -5
  103. package/dist/commands/notes.js +0 -28
  104. package/dist/commands/notes.js.map +0 -1
  105. package/dist/lib/browser-detect.d.ts +0 -28
  106. package/dist/lib/browser-detect.js +0 -126
  107. package/dist/lib/browser-detect.js.map +0 -1
  108. package/dist/lib/favorites.d.ts +0 -73
  109. package/dist/lib/favorites.js +0 -180
  110. package/dist/lib/favorites.js.map +0 -1
  111. package/dist/lib/github.d.ts +0 -14
  112. package/dist/lib/github.js +0 -36
  113. package/dist/lib/github.js.map +0 -1
  114. package/dist/lib/highlights.d.ts +0 -11
  115. package/dist/lib/highlights.js +0 -116
  116. package/dist/lib/highlights.js.map +0 -1
  117. package/dist/lib/link-previews.d.ts +0 -67
  118. package/dist/lib/link-previews.js +0 -427
  119. package/dist/lib/link-previews.js.map +0 -1
  120. package/dist/lib/notes.d.ts +0 -22
  121. package/dist/lib/notes.js +0 -22
  122. package/dist/lib/notes.js.map +0 -1
  123. package/dist/lib/pdf.d.ts +0 -13
  124. package/dist/lib/pdf.js +0 -66
  125. package/dist/lib/pdf.js.map +0 -1
  126. package/dist/lib/revisions.d.ts +0 -102
  127. package/dist/lib/revisions.js +0 -445
  128. package/dist/lib/revisions.js.map +0 -1
  129. package/dist/lib/share/analytics.d.ts +0 -13
  130. package/dist/lib/share/analytics.js +0 -46
  131. package/dist/lib/share/analytics.js.map +0 -1
  132. package/dist/lib/share/capture.d.ts +0 -31
  133. package/dist/lib/share/capture.js +0 -175
  134. package/dist/lib/share/capture.js.map +0 -1
  135. package/dist/lib/tokens.d.ts +0 -12
  136. package/dist/lib/tokens.js +0 -28
  137. package/dist/lib/tokens.js.map +0 -1
  138. package/dist/lib/worksheet.d.ts +0 -94
  139. package/dist/lib/worksheet.js +0 -394
  140. package/dist/lib/worksheet.js.map +0 -1
@@ -1,9 +1,100 @@
1
1
  import { buildSync } from 'esbuild';
2
+ import { readFileSync } from 'node:fs';
2
3
  import { dirname } from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
4
- import { BODY_REVISION_META, normalizeSharePath } from '../collab.js';
5
+ import { BODY_REVISION_META, COLLAB_SCRIPT, normalizeSharePath } from '../collab.js';
6
+ import { SELECTION_TOOLBAR_SCRIPT } from '../selection-toolbar.js';
7
+ import { READER_ANCHORS_SCRIPT } from '../reader-anchors.js';
5
8
  import { SHARE_PUBLISH_WORKER_SOURCE } from './worker-publish-template.js';
6
9
  import { SHARE_MEDIA_WORKER_SOURCE } from './worker-media-template.js';
10
+ import { SHARE_PEOPLE_WORKER_SOURCE } from './worker-people-template.js';
11
+ // The Cloudflare Worker that fronts the R2 share bucket.
12
+ //
13
+ // One tiny Worker does both sides:
14
+ // - PUT /<username>/<slug> — write-gated by authorizeWrite's THREE principals
15
+ // (not a fallback chain — each is a distinct legitimate identity):
16
+ // 1. Static WRITE_TOKEN (BYO Cloudflare) — checked first when the presented
17
+ // bearer equals env.WRITE_TOKEN. owner = env.SHARE_NAMESPACE or the
18
+ // path's first segment.
19
+ // 2. Phoenix bearer — otherwise GET ${env.PHOENIX_ID_BASE}/api/v1/auth/me
20
+ // with that bearer → {userId,email}; 401 if absent/invalid.
21
+ // customMetadata.owner = userId (stable). The path's first segment MUST
22
+ // equal handleFromEmail(email) (the public handle, e.g. muqsitnawaz),
23
+ // or an explicit x-share-handle the caller chose (--handle), so one user
24
+ // cannot write another's prefix (403 namespace mismatch).
25
+ // A __handles/<handle> claim binds the handle to the first userId that
26
+ // writes it and records the verified email; a different userId gets 409
27
+ // handle taken, EXCEPT when its verified email matches the claim's — the
28
+ // same human re-authenticated under a new userId — in which case the
29
+ // claim and the old account's objects transfer instead of dead-ending
30
+ // (PHNX-3547).
31
+ // 3. __share HMAC cookie — the signed-in viewer's identity cookie (same
32
+ // {userId,email} identityFromCookie verifies for GET). Lets the shared
33
+ // page's inline visibility control PATCH with credentials:'include' and
34
+ // no bearer; SameSite=Lax blocks it cross-site, and the same namespace/
35
+ // owner checks confine it to the holder's own pages. Applies to PUT,
36
+ // PATCH, and DELETE alike, since all three share authorizeWrite.
37
+ // A managed deployment sets PHOENIX_ID_BASE; BYO sets WRITE_TOKEN; the
38
+ // platform endpoint may set both. Fail loud (401) when none authenticates.
39
+ // Writes the body to R2 via the BUCKET binding, storing visibility
40
+ // (public|unlisted|me|org), owner, org_domain (org only), an optional
41
+ // expires-at, plus provenance (agent/session/host/repo/date), a label, and
42
+ // any `--meta` entries in object metadata. me/org require a Phoenix
43
+ // identity (BYO WRITE_TOKEN cannot publish them). org from a public inbox
44
+ // domain is 400. Overwriting an existing slug first copies the current
45
+ // object to <slug>/rev-<ts>-<rand> (revision history) unless
46
+ // x-share-no-revision is set.
47
+ // - PATCH /<username>/<slug> — authenticated metadata-only edit. Rewrites the
48
+ // exact existing body with all HTTP/custom metadata preserved except the
49
+ // explicitly requested label/arbitrary metadata changes; never revisions.
50
+ // Conditional put (onlyIf etagMatches) so a concurrent republish 409s
51
+ // instead of rolling the body back. Ownership is the handle claim's call,
52
+ // exactly as on DELETE (assertHandleOwner: the __handles/<handle> claim, or
53
+ // the pre-claim rival-userId scan) — there is no per-object owner compare,
54
+ // and the stamp is left untouched; WRITE_TOKEN is the admin repair path.
55
+ // - GET /<username>/<slug> — public|unlisted are anonymous; me requires the
56
+ // Phoenix owner (the stamped owner, or the holder of the namespace's
57
+ // __handles claim), org requires a same-domain Phoenix identity (Bearer, then
58
+ // HMAC cookie, then phoenix_ticket). Unauthenticated me/org 302s to
59
+ // Phoenix login (or 401 JSON if PHOENIX_ID_BASE is unset). 410s (and lazily
60
+ // deletes) once its expiry has passed. A bucket lifecycle rule is the durable
61
+ // sweeper; this is the immediate gate.
62
+ // - GET /<username>/<slug>?revisions=json — machine-readable history of the
63
+ // retained prior versions under that slug, newest first.
64
+ // - GET /<username> — public gallery of that user's shares (HTML).
65
+ // - GET /<username>?format=json — public machine-readable listing of that user's
66
+ // ACTIVE shares (`artifacts share list`). Same single-segment path as the HTML
67
+ // gallery and gated on the SAME "does <username>/ hold any object" check, so it
68
+ // only intercepts a genuine namespace — a legacy flat slug with ?format=json
69
+ // still serves its real content, never a fake empty listing.
70
+ // - GET /<slug> — backward-compat flat slug (legacy shares before
71
+ // per-user namespaces).
72
+ // - /__collab/* — hosted review threads (PHNX-3835), answered only
73
+ // when COLLAB_API_BASE and COLLAB_SERVICE_TOKEN are both bound. The Worker
74
+ // identifies the reader, applies visibility + comment policy, answers
75
+ // /__collab/context itself, and forwards everything else to Rush Cloud's
76
+ // /internal/artifact-collab with the service token and trusted X-Collab-*
77
+ // headers, streaming bodies (SSE included). Publish, visibility/policy
78
+ // PATCH, and delete keep Rush's share registry in step. Unbound, every
79
+ // /__collab request takes exactly the pre-collab path (GET 404s). Any HTML
80
+ // page can be commented on: one that artifacts render did not make is
81
+ // revisioned by the SHA-256 of its bytes and gets the review scripts
82
+ // injected when served.
83
+ //
84
+ // - /__people/<user>/<slug>, /__lookup, /__mine, /__shared — the people a
85
+ // page is shared with by email, and the pages a signed-in person owns or
86
+ // was given (PHNX-4394, worker-people-template.ts). The list widens a
87
+ // me/org page's audience inside gateVisibility.
88
+ //
89
+ // - GET /__version — {"version": "<artifacts-cli version that built
90
+ // this Worker>"}. The release workflow checks it after each deploy, and the
91
+ // CLI compares it with its own version to explain a missing route.
92
+ //
93
+ // Emitted as a string, so it compiles into `dist/**` and ships with no
94
+ // package.json#files change. `provision.ts` uploads
95
+ // this verbatim as an ES-module Worker with a BUCKET (R2) binding + a WRITE_TOKEN secret.
96
+ /** The artifacts-cli version this Worker is built from, served at `/__version`. */
97
+ export const SHARE_WORKER_VERSION = JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')).version;
7
98
  let bundledWorker;
8
99
  let nodeWorkerScript;
9
100
  /** Bundle the Worker renderer into an ES module plus workerd-compiled WASM modules. */
@@ -87,8 +178,10 @@ import barInter from '../../../fonts/InterVariable.woff2';
87
178
  import barJost from '../../../fonts/Jost-wght.woff2';
88
179
  import barPhoenix from '../../../brand/phoenix-gold.webp';
89
180
 
90
- // GENERATED by agents-cli agents share setup — do not edit here; edit
91
- // src/lib/share/worker-template.ts and re-run setup.
181
+ // GENERATED from src/lib/share/worker-template.ts — do not edit here; edit
182
+ // that file and deploy with artifacts share update.
183
+ const WORKER_VERSION = ${JSON.stringify(SHARE_WORKER_VERSION)};
184
+
92
185
  export const hooks = {
93
186
  verifyPhoenixToken: defaultVerifyPhoenixToken,
94
187
  renderOgCard: renderOgCard,
@@ -105,6 +198,12 @@ export default {
105
198
  });
106
199
  }
107
200
 
201
+ if (path === '__version' && (request.method === 'GET' || request.method === 'HEAD')) {
202
+ return new Response(request.method === 'HEAD' ? null : JSON.stringify({ version: WORKER_VERSION }), {
203
+ status: 200, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
204
+ });
205
+ }
206
+
108
207
  const firstSeg = path.split('/').filter(Boolean)[0] || '';
109
208
  if (firstSeg === '__collab' && collabConfig(env)) return handleCollab(request, env, url, path);
110
209
  // Deepgram's side of the media job (PHNX-4287): the single-use source link
@@ -114,6 +213,8 @@ export default {
114
213
  // The share bar's two faces (Inter, Jost), served from this origin so a
115
214
  // shared page never calls a third-party font host.
116
215
  if ((request.method === 'GET' || request.method === 'HEAD') && Object.prototype.hasOwnProperty.call(BAR_ASSETS, path)) return handleBarAsset(request, path);
216
+ // Who a page is shared with, and the pages a person owns or was given (PHNX-4394).
217
+ if (firstSeg === '__people' || path === '__lookup' || path === '__mine' || path === '__shared') return handlePeopleRoute(request, env, url, path);
117
218
  if ((request.method === 'GET' || request.method === 'HEAD') && firstSeg.startsWith('__')) {
118
219
  return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
119
220
  }
@@ -215,8 +316,7 @@ export default {
215
316
  putBody = read.bytes;
216
317
  }
217
318
  if (collab && isHtmlPage) {
218
- const revision = extractBodyRevision(putBody);
219
- if (revision) customMetadata['body-revision'] = revision;
319
+ customMetadata['body-revision'] = extractBodyRevision(putBody) || await bytesRevision(putBody);
220
320
  }
221
321
 
222
322
  // R2 multipart completion is an unconditional canonical write. Serialize
@@ -254,6 +354,10 @@ export default {
254
354
  // math, and even a first/no-revision publish must read before its
255
355
  // conditional write so two concurrent creates cannot both report 200.
256
356
  const existing = await env.BUCKET.get(path);
357
+ // A new page at a free or expired address starts with nobody on its
358
+ // people list; a republish of the live page keeps it. The path lock
359
+ // holds every later attempt to the same answer.
360
+ if (attempt === 0 && segments.length === 2) await clearStalePeople(env, path, existing);
257
361
  if (auth.kind === 'phoenix') {
258
362
  const existingSize = existing && typeof existing.size === 'number' ? existing.size : 0;
259
363
  const newCanonical = !existing;
@@ -335,10 +439,10 @@ export default {
335
439
  // Register only a page comments can anchor to. A failed registration
336
440
  // never fails the publish: the page is stored, and the caller is told.
337
441
  // Threads carry over only from a live registered page at this address.
338
- // Anything else (a free slug, an expired page nobody read since, a raw
339
- // page) clears whatever Rush still holds there first, so a new page never
340
- // inherits another page's comments. A raw page that replaces a registered
341
- // one closes its threads, and the caller hears why.
442
+ // Anything else (a free slug, an expired page nobody read since) clears
443
+ // whatever Rush still holds there first, so a new page never inherits
444
+ // another page's comments. A non-HTML file that replaces a registered
445
+ // page closes its threads, and the caller hears why.
342
446
  const replacedMeta = (replaced && replaced.customMetadata) || {};
343
447
  const replacedRevision = replacedMeta['body-revision'] || '';
344
448
  const replacedExpiry = replacedMeta['expires-at'];
@@ -349,7 +453,7 @@ export default {
349
453
  ? await registerShare(env, collab, url, path, customMetadata)
350
454
  : await registerFreshShare(env, collab, url, path, customMetadata);
351
455
  } else if (collab && continuesThreads) {
352
- registration = { registered: false, error: 'the new page has no ' + BODY_REVISION_META + ' meta, so its review threads are closed' };
456
+ registration = { registered: false, error: 'the new file is not an HTML page, so its review threads are closed' };
353
457
  }
354
458
  return withCollabStatus(
355
459
  json({ ok: true, url: url.origin + '/' + path, expiresAt: expiresAt || null, unlisted: visibility === 'unlisted', visibility }, 200),
@@ -583,7 +687,7 @@ export default {
583
687
  const pageVisibility = (page.customMetadata && page.customMetadata.visibility) || 'public';
584
688
  if (viewer.error && isIdentityGated(pageVisibility)) return viewer.error;
585
689
  const denied = await gateVisibility(url, env, page, viewer.identity || null);
586
- if (denied) return isIdentityGated(pageVisibility) ? sealedCover(request, url, page, segments[0], pagePath) : denied;
690
+ if (denied) return isIdentityGated(pageVisibility) && denied.status !== 503 ? sealedCover(request, url, page, segments[0], pagePath) : denied;
587
691
  // A token-gated page's cover is token-gated too (PHNX-3654): a crawler
588
692
  // fetching <slug>.png without the key gets 404, so no preview leaks.
589
693
  const coverTokenDenied = await gateTokenRead(request, url, page, viewer.identity || null);
@@ -712,6 +816,11 @@ export default {
712
816
  }
713
817
  // An expired video's derived files go with it (best-effort, after the refund).
714
818
  if (path.split('/').filter(Boolean).length === 2) await deleteMediaDerived(env, path);
819
+ // So do its people list and inbox entries. Best-effort: a list left
820
+ // behind grants nothing, since the next page here clears it first.
821
+ if (path.split('/').filter(Boolean).length === 2) {
822
+ try { await clearPeople(env, path); } catch (e) { /* cleared again by the next publish here */ }
823
+ }
715
824
  // An expired slug is reusable, so its threads go with it, off the
716
825
  // response path like the view counter.
717
826
  const expiredCollab = collabConfig(env);
@@ -747,7 +856,7 @@ export default {
747
856
  const identity = viewer.identity || null;
748
857
  const denied = await gateVisibility(url, env, gateObj, identity);
749
858
  if (denied) {
750
- if (isIdentityGated(visibility) && wantsSealedPage(request)) {
859
+ if (isIdentityGated(visibility) && denied.status !== 503 && wantsSealedPage(request)) {
751
860
  const sealed = renderSealedPage(url, env, gateObj, identity);
752
861
  if (sealed) return sealed;
753
862
  }
@@ -844,7 +953,13 @@ export default {
844
953
  // defeatable with a query param). The body changes, so the R2 etag no
845
954
  // longer matches — drop it rather than serve a lying validator.
846
955
  if (ctype.indexOf('text/html') !== -1 && !range) {
847
- const rawHtml = await obj.text();
956
+ const rawBytes = new Uint8Array(await obj.arrayBuffer());
957
+ let rawHtml = new TextDecoder().decode(rawBytes);
958
+ if (collabConfig(env) && !extractBodyRevision(rawBytes)) {
959
+ const stored = (obj.customMetadata || {})['body-revision'];
960
+ const revision = stored || (await storedPageRevision(env, path, obj, rawBytes)).revision;
961
+ rawHtml = injectReviewScripts(rawHtml, revision);
962
+ }
848
963
  // Per-slug view counter (RUSH view stats). Stored as a SEPARATE R2 object
849
964
  // (__views/<path>) so it never rewrites the page object — a rewrite would
850
965
  // reset obj.uploaded and corrupt "last updated". The __-prefix key is GET-
@@ -943,6 +1058,7 @@ export default {
943
1058
  }
944
1059
  // A video takes its derived files with it (best-effort, after the refund).
945
1060
  if (!isMediaDerived(doomed) && path.split('/').filter(Boolean).length === 2) await deleteMediaDerived(env, path);
1061
+ if (!isMediaDerived(doomed) && !isCover && path.split('/').filter(Boolean).length === 2) await clearPeople(env, path);
946
1062
  const purge = collab && doomed && doomed.customMetadata && doomed.customMetadata['body-revision'] && path.split('/').filter(Boolean).length === 2
947
1063
  ? await purgeShare(collab, url, path)
948
1064
  : null;
@@ -1181,7 +1297,7 @@ var SHARE_PLANS = {
1181
1297
  var DEFAULT_SHARE_PLAN = 'free';
1182
1298
  var RATE_WINDOW_MS = 3600 * 1000; // fixed 1h publish-rate window
1183
1299
  function planLimits(plan) { return Object.prototype.hasOwnProperty.call(SHARE_PLANS, plan) ? SHARE_PLANS[plan] : SHARE_PLANS[DEFAULT_SHARE_PLAN]; }
1184
- function freshUsage() { return { bytes: 0, count: 0, plan: DEFAULT_SHARE_PLAN, rlStart: 0, rlUsed: 0, multipartCharges: [] }; }
1300
+ function freshUsage() { return { bytes: 0, count: 0, plan: DEFAULT_SHARE_PLAN, rlStart: 0, rlUsed: 0, multipartCharges: [], peopleStart: 0, peopleUsed: 0, lookupStart: 0, lookupUsed: 0, mineStart: 0, mineUsed: 0 }; }
1185
1301
  function usageNumber(v, fallback) { return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback; }
1186
1302
 
1187
1303
  // Everything in customMetadata that ISN'T one of the reserved provenance/label
@@ -1648,6 +1764,11 @@ var ASH_RAIL_CSS =
1648
1764
  ASH_RAIL + ' textarea{min-height:72px;margin-top:10px;border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:10px 12px;background:rgba(255,255,255,.04);color:#fafafa;font:13.5px/1.5 ' + ASH_RAIL_FONT + '}' +
1649
1765
  ASH_RAIL + ' textarea::placeholder{color:#71717a}' +
1650
1766
  ASH_RAIL + ' textarea:focus-visible{outline:0;border-color:rgba(201,169,98,.6)}' +
1767
+ ASH_RAIL + ' .collab-mentions{margin:6px 0 0;border:1px solid rgba(255,255,255,.1);border-radius:10px;background:rgba(24,24,27,.98);box-shadow:0 12px 32px rgba(0,0,0,.45)}' +
1768
+ ASH_RAIL + ' .collab-mention[aria-selected="true"]{background:rgba(201,169,98,.16)}' +
1769
+ ASH_RAIL + ' .collab-mention-avatar{background:rgba(255,255,255,.08);color:#a1a1aa;font:600 10px/1 ' + ASH_RAIL_FONT + '}' +
1770
+ ASH_RAIL + ' .collab-mention-name{color:#fafafa}' +
1771
+ ASH_RAIL + ' .collab-mention-email{color:#71717a}' +
1651
1772
  ASH_RAIL + ' .collab-empty{margin:28px 16px;color:#71717a;text-align:center}' +
1652
1773
  ASH_RAIL + ' .collab-error{font:400 12px/1.4 ' + ASH_RAIL_FONT + ';color:#ff6b6b}' +
1653
1774
  ASH_RAIL + ' .collab-provenance{padding:10px 16px;border-top:1px solid rgba(255,255,255,.07);color:#52525b;font:11px/1.5 ' + ASH_RAIL_FONT + '}' +
@@ -2050,7 +2171,9 @@ function isCommentPolicy(value) {
2050
2171
 
2051
2172
  // An explicit policy wins; otherwise the visibility decides. An audience page
2052
2173
  // (me, org) lets its audience comment, a capability link lets any signed-in
2053
- // reader, and a public page starts with comments off.
2174
+ // reader, and a public page with no stored policy keeps comments off. A public
2175
+ // page published now has signed_in stamped at publish (preparePublish), so a
2176
+ // page published before that never opens retroactively.
2054
2177
  function commentPolicyOf(meta) {
2055
2178
  const stored = meta && meta['comment-policy'];
2056
2179
  if (isCommentPolicy(stored)) return stored;
@@ -2060,18 +2183,20 @@ function commentPolicyOf(meta) {
2060
2183
  return 'off';
2061
2184
  }
2062
2185
 
2063
- // read is decided by the page's own gate before this runs. Commenting needs a
2064
- // signed-in reader, a policy other than off, and, under audience, membership:
2065
- // the owner for me, the stamped email domain for org, any signed-in reader
2066
- // for a link or public page. Resolving needs exactly what commenting needs.
2186
+ // read is decided by the page's own gate before this runs, and on a me or org
2187
+ // page that gate admits exactly the audience: the owner, the stamped email
2188
+ // domain, and the people the owner listed. Commenting needs a signed-in
2189
+ // reader and a policy other than off; any reader of a link or public page is
2190
+ // in its audience. Resolving needs exactly what commenting needs.
2067
2191
  function collabGrant(meta, identity, owner) {
2068
2192
  const visibility = meta.visibility || 'public';
2069
2193
  const policy = commentPolicyOf(meta);
2070
- let inAudience = true;
2071
- if (visibility === 'me') inAudience = owner;
2072
- else if (visibility === 'org') inAudience = !!identity && !!meta.org_domain && emailDomain(identity.email) === String(meta.org_domain).toLowerCase();
2073
- const comment = !!identity && policy !== 'off' && (policy === 'signed_in' || inAudience);
2074
- return { read: true, comment: comment, resolve: comment };
2194
+ // A page with no owner cannot be registered with Rush, so it takes no comments.
2195
+ const comment = !!identity && !!meta.owner && policy !== 'off';
2196
+ // Resolving closes a thread for everyone. A me/org page's audience may; on any
2197
+ // other page only the owner may, so a signed-in stranger cannot close threads.
2198
+ const resolve = comment && (owner || visibility === 'me' || visibility === 'org');
2199
+ return { read: true, comment: comment, resolve: resolve };
2075
2200
  }
2076
2201
 
2077
2202
  // The rendered page's <meta name="artifacts-body-revision">, the hash every
@@ -2098,6 +2223,56 @@ function extractBodyRevision(bytes) {
2098
2223
  return '';
2099
2224
  }
2100
2225
 
2226
+ // The revision of a page artifacts render did not make: the SHA-256 of its
2227
+ // stored bytes, in the same form as the renderer's meta.
2228
+ async function bytesRevision(bytes) {
2229
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
2230
+ let hex = '';
2231
+ for (let i = 0; i < digest.length; i++) hex += digest[i].toString(16).padStart(2, '0');
2232
+ return 'sha256:' + hex;
2233
+ }
2234
+
2235
+ // The renderer's anchor runtime, selection toolbar and review rail, for a page
2236
+ // that carries none of them. Each one stands down when the page already runs it.
2237
+ var PAGE_REVIEW_SCRIPTS = ${JSON.stringify(READER_ANCHORS_SCRIPT + SELECTION_TOOLBAR_SCRIPT + COLLAB_SCRIPT)};
2238
+
2239
+ // Before the last </body>, unless that tag sits inside a script or a comment;
2240
+ // then at the end. A page whose CSP forbids inline scripts is left alone.
2241
+ function injectReviewScripts(html, revision) {
2242
+ const lower = html.toLowerCase();
2243
+ const csp = /<meta[^>]+http-equiv\s*=\s*["']?content-security-policy[^>]*>/i.exec(html);
2244
+ if (csp && /script-src|default-src/i.test(csp[0]) && !/unsafe-inline/i.test(csp[0])) return html;
2245
+ const tail = '<meta name="' + BODY_REVISION_META + '" content="' + revision + '">' + PAGE_REVIEW_SCRIPTS;
2246
+ const at = lower.lastIndexOf('</body');
2247
+ const before = lower.slice(0, Math.max(at, 0));
2248
+ const inside = before.lastIndexOf('<script') > before.lastIndexOf('</script') || before.lastIndexOf('<!--') > before.lastIndexOf('-->');
2249
+ return at === -1 || inside ? html + tail : html.slice(0, at) + tail + html.slice(at);
2250
+ }
2251
+
2252
+ // A page stored before every HTML publish recorded a revision. Its revision
2253
+ // (the render meta, else the bytes' hash, as at publish) and whether Rush has
2254
+ // it registered live in __revisions/<key>, keyed to the object's etag, so the
2255
+ // page object is never rewritten (that would move its "Updated" time) and the
2256
+ // hash and registration happen once per stored version.
2257
+ async function storedPageRevision(env, key, obj, bytes) {
2258
+ const side = await env.BUCKET.get('__revisions/' + key);
2259
+ if (side) {
2260
+ try {
2261
+ const record = JSON.parse(await side.text());
2262
+ if (record && record.etag === obj.etag && typeof record.revision === 'string') return record;
2263
+ } catch { /* an unreadable record is recomputed below */ }
2264
+ }
2265
+ let page = bytes;
2266
+ if (!page) {
2267
+ const full = await env.BUCKET.get(key);
2268
+ if (!full) return null;
2269
+ page = new Uint8Array(await full.arrayBuffer());
2270
+ }
2271
+ const record = { etag: obj.etag, revision: extractBodyRevision(page) || await bytesRevision(page), registered: false };
2272
+ await env.BUCKET.put('__revisions/' + key, JSON.stringify(record), { httpMetadata: { contentType: 'application/json' } });
2273
+ return record;
2274
+ }
2275
+
2101
2276
  function collabShareId(url, key) {
2102
2277
  return url.host + normalizeSharePath('/' + key);
2103
2278
  }
@@ -2117,17 +2292,18 @@ function withCollabStatus(response, registration) {
2117
2292
  return response;
2118
2293
  }
2119
2294
 
2120
- // Registry calls ride the publish/delete response, so they are bounded and
2121
- // report rather than throw. Both are mutations: Rush requires an
2122
- // Idempotency-Key and an X-Collab-Share naming the same share as the call.
2123
- async function collabRegistryCall(collab, method, path, shareId, body) {
2295
+ // Calls to Rush's internal routes ride a Worker response, so they are bounded
2296
+ // and report rather than throw. Registry mutations need an Idempotency-Key and
2297
+ // an X-Collab-Share naming the same share as the call; the people lookup is
2298
+ // about no share and sends none. A success carries Rush's parsed JSON body.
2299
+ async function collabRegistryCall(collab, method, path, shareId, body, idempotencyKey) {
2124
2300
  const headers = {
2125
2301
  authorization: 'Bearer ' + collab.token,
2126
2302
  'user-agent': COLLAB_USER_AGENT,
2127
2303
  accept: 'application/json',
2128
- 'idempotency-key': crypto.randomUUID(),
2129
- 'x-collab-share': shareId,
2304
+ 'idempotency-key': idempotencyKey || crypto.randomUUID(),
2130
2305
  };
2306
+ if (shareId) headers['x-collab-share'] = shareId;
2131
2307
  if (body !== undefined) headers['content-type'] = 'application/json';
2132
2308
  let res;
2133
2309
  try {
@@ -2141,17 +2317,18 @@ async function collabRegistryCall(collab, method, path, shareId, body) {
2141
2317
  return { error: 'collaboration service unreachable: ' + (error && error.message ? error.message : String(error)) };
2142
2318
  }
2143
2319
  let detail = '';
2320
+ let parsed = null;
2144
2321
  try {
2145
- const parsed = await res.json();
2322
+ parsed = await res.json();
2146
2323
  if (parsed && typeof parsed.error === 'string') detail = parsed.error;
2147
2324
  } catch {
2148
2325
  // a non-JSON body carries no detail worth surfacing
2149
2326
  }
2150
2327
  if (!res.ok) return { status: res.status, error: 'collaboration service answered ' + res.status + (detail ? ': ' + detail : '') };
2151
- return { status: res.status };
2328
+ return { status: res.status, body: parsed };
2152
2329
  }
2153
2330
 
2154
- async function registerShare(env, collab, url, key, meta) {
2331
+ async function registerShare(env, collab, url, key, meta, idempotencyKey) {
2155
2332
  const shareId = collabShareId(url, key);
2156
2333
  const result = await collabRegistryCall(collab, 'PUT', '/shares', shareId, {
2157
2334
  share_id: shareId,
@@ -2167,7 +2344,7 @@ async function registerShare(env, collab, url, key, meta) {
2167
2344
  host: meta.host || null,
2168
2345
  repo: meta.repo || null,
2169
2346
  },
2170
- });
2347
+ }, idempotencyKey);
2171
2348
  return result.error ? { registered: false, error: result.error } : { registered: true };
2172
2349
  }
2173
2350
 
@@ -2189,9 +2366,10 @@ function collabRoute(method, rest) {
2189
2366
  if (method === 'GET' && rest === 'context') return { op: 'context' };
2190
2367
  if (method === 'GET' && rest === 'threads') return { op: 'read', upstream: '/threads' };
2191
2368
  if (method === 'GET' && rest === 'events') return { op: 'events', upstream: '/events' };
2192
- if (method === 'POST' && rest === 'threads') return { op: 'write', need: 'comment', upstream: '/threads', fields: ['anchor', 'body'] };
2369
+ if (method === 'GET' && rest === 'members') return { op: 'members', need: 'comment', upstream: '/members' };
2370
+ if (method === 'POST' && rest === 'threads') return { op: 'write', need: 'comment', upstream: '/threads', fields: ['anchor', 'body', 'mentions'] };
2193
2371
  let match = /^threads\\/([^/]+)\\/replies$/.exec(rest);
2194
- if (method === 'POST' && match) return { op: 'write', need: 'comment', upstream: '/threads/' + encodeURIComponent(match[1]) + '/replies', fields: ['body'] };
2372
+ if (method === 'POST' && match) return { op: 'write', need: 'comment', upstream: '/threads/' + encodeURIComponent(match[1]) + '/replies', fields: ['body', 'mentions'] };
2195
2373
  match = /^threads\\/([^/]+)$/.exec(rest);
2196
2374
  if (method === 'PATCH' && match) return { op: 'write', need: 'resolve', upstream: '/threads/' + encodeURIComponent(match[1]), fields: ['status'] };
2197
2375
  match = /^comments\\/([^/]+)$/.exec(rest);
@@ -2258,9 +2436,10 @@ async function handleCollab(request, env, url, path) {
2258
2436
  const obj = await env.BUCKET.head(key);
2259
2437
  const meta = (obj && obj.customMetadata) || {};
2260
2438
  const expiresAt = meta['expires-at'];
2261
- // A page without a body revision was never registered (or its threads were
2262
- // closed by a raw republish): there is nothing to anchor to.
2263
- if (!obj || (expiresAt && Date.now() > Date.parse(expiresAt)) || !meta['body-revision']) return collabJson({ error: 'unknown share' }, 404);
2439
+ const isHtml = String((obj && obj.httpMetadata && obj.httpMetadata.contentType) || '').toLowerCase().indexOf('text/html') !== -1;
2440
+ // Only a page has anything to anchor to. One stored before any HTML got a
2441
+ // revision at publish has none recorded; its bytes give it one below.
2442
+ if (!obj || (expiresAt && Date.now() > Date.parse(expiresAt)) || !(meta['body-revision'] || isHtml)) return collabJson({ error: 'unknown share' }, 404);
2264
2443
 
2265
2444
  // Read = may open the page: the same visibility and viewer-key gates the
2266
2445
  // page GET applies, evaluated against the page's own URL.
@@ -2270,8 +2449,9 @@ async function handleCollab(request, env, url, path) {
2270
2449
  if (viewerKey) pageUrl.searchParams.set('k', viewerKey);
2271
2450
  const viewer = await resolveViewer(request, env, url);
2272
2451
  const identity = viewer.identity || null;
2273
- const readable = !(await gateVisibility(pageUrl, env, obj, identity)) && !(await gateTokenRead(request, pageUrl, obj, identity));
2274
- if (!readable) return collabJson({ error: 'forbidden' }, 403);
2452
+ const readDenied = (await gateVisibility(pageUrl, env, obj, identity)) || (await gateTokenRead(request, pageUrl, obj, identity));
2453
+ if (readDenied && readDenied.status === 503) return collabJson({ error: 'access_check_unavailable' }, 503);
2454
+ if (readDenied) return collabJson({ error: 'forbidden' }, 403);
2275
2455
  const owner = !!identity && (meta.owner === identity.userId || (await holdsHandleClaim(env.BUCKET, key.split('/')[0], identity.userId)));
2276
2456
  const grant = collabGrant(meta, identity, owner);
2277
2457
 
@@ -2288,19 +2468,36 @@ async function handleCollab(request, env, url, path) {
2288
2468
  }
2289
2469
 
2290
2470
  if (route.op === 'context') {
2471
+ let revision = meta['body-revision'];
2472
+ let unavailable = null;
2473
+ if (!revision) {
2474
+ // A page Rush never heard of. One that takes no comments (policy off, or
2475
+ // no owner to register it under) gets no review UI at all.
2476
+ if (commentPolicyOf(meta) === 'off' || !meta.owner) return collabJson({ error: 'unknown share' }, 404);
2477
+ const record = await storedPageRevision(env, key, obj, null);
2478
+ if (!record) return collabJson({ error: 'unknown share' }, 404);
2479
+ revision = record.revision;
2480
+ if (!record.registered) {
2481
+ const idempotencyKey = 'register:' + (await bytesRevision(new TextEncoder().encode(collabShareId(url, key) + '|' + revision))).slice(7);
2482
+ const registration = await registerShare(env, collab, url, key, { ...meta, 'body-revision': revision }, idempotencyKey);
2483
+ if (registration.registered) await env.BUCKET.put('__revisions/' + key, JSON.stringify({ ...record, registered: true }), { httpMetadata: { contentType: 'application/json' } });
2484
+ else unavailable = registration.error;
2485
+ }
2486
+ }
2291
2487
  const producer = {};
2292
2488
  for (const field of ['agent', 'session', 'host', 'repo']) if (meta[field]) producer[field] = meta[field];
2293
2489
  return collabJson({
2294
2490
  share: sharePath,
2295
2491
  visibility: meta.visibility || 'public',
2296
- revision: meta['body-revision'],
2492
+ revision: revision,
2297
2493
  viewer: identity ? { id: identity.userId, name: collabDisplayName(identity) } : null,
2298
- permissions: grant,
2494
+ permissions: unavailable ? { read: true, comment: false, resolve: false } : grant,
2299
2495
  producer: Object.keys(producer).length ? producer : null,
2496
+ ...(unavailable ? { unavailable: 'comments are unavailable on this page: ' + unavailable } : {}),
2300
2497
  }, 200);
2301
2498
  }
2302
2499
 
2303
- if (route.op === 'write' && !grant[route.need]) return collabJson({ error: 'forbidden' }, 403);
2500
+ if (route.need && !grant[route.need]) return collabJson({ error: 'forbidden' }, 403);
2304
2501
  const idempotencyKey = request.headers.get('idempotency-key') || '';
2305
2502
  if (route.op === 'write' && (!idempotencyKey || idempotencyKey.length > 255)) {
2306
2503
  return collabJson({ error: 'Idempotency-Key is required (up to 255 characters)' }, 400);
@@ -2338,7 +2535,9 @@ async function handleCollab(request, env, url, path) {
2338
2535
  }
2339
2536
  const query = new URLSearchParams();
2340
2537
  const after = url.searchParams.get('after');
2341
- if (after !== null && route.op !== 'write') query.set('after', after);
2538
+ if (after !== null && (route.op === 'read' || route.op === 'events')) query.set('after', after);
2539
+ const q = url.searchParams.get('q');
2540
+ if (q !== null && route.op === 'members') query.set('q', q.slice(0, 100));
2342
2541
  const lastEventId = request.headers.get('last-event-id');
2343
2542
  if (route.op === 'events' && lastEventId) headers.set('last-event-id', lastEventId);
2344
2543
  const target = collab.endpoint + route.upstream + (query.toString() ? '?' + query.toString() : '');
@@ -2364,6 +2563,7 @@ async function handleCollab(request, env, url, path) {
2364
2563
 
2365
2564
  ${SHARE_PUBLISH_WORKER_SOURCE}
2366
2565
  ${SHARE_MEDIA_WORKER_SOURCE}
2566
+ ${SHARE_PEOPLE_WORKER_SOURCE}
2367
2567
  // Ownership for an edit of an existing <handle>/<slug>: WRITE_TOKEN is the
2368
2568
  // endpoint admin; a Phoenix caller must own the handle the way PUT and DELETE
2369
2569
  // decide it (the __handles claim, transferring it on a same-email account
@@ -2440,6 +2640,8 @@ async function transferHandle(bucket, handle, oldUserId, newUserId, email) {
2440
2640
  httpMetadata: { contentType: 'application/json' },
2441
2641
  customMetadata: { userId: newUserId, email: email, visibility: 'unlisted' },
2442
2642
  });
2643
+ await bucket.put(handleIndexPrefix(newUserId) + handle, '', { customMetadata: { visibility: 'unlisted' } });
2644
+ await bucket.delete(handleIndexPrefix(oldUserId) + handle);
2443
2645
  let cursor;
2444
2646
  do {
2445
2647
  const list = await bucket.list({ prefix: handle + '/', cursor: cursor, include: ['customMetadata'] });
@@ -2473,9 +2675,16 @@ async function claimHandle(bucket, handle, userId, email) {
2473
2675
  httpMetadata: { contentType: 'application/json' },
2474
2676
  customMetadata: { userId: userId, email: email || '', visibility: 'unlisted' },
2475
2677
  });
2678
+ await bucket.put(handleIndexPrefix(userId) + handle, '', { customMetadata: { visibility: 'unlisted' } });
2476
2679
  return {};
2477
2680
  }
2478
2681
 
2682
+ // The handles a user holds, one empty key each, so /__mine finds an account's
2683
+ // alternate handles without scanning every claim. Written with the claim.
2684
+ function handleIndexPrefix(userId) {
2685
+ return '__handles-by-user/' + sanitizeNamespace(userId) + '/';
2686
+ }
2687
+
2479
2688
  function normalizeVisibility(raw) {
2480
2689
  const v = (raw || '').trim().toLowerCase();
2481
2690
  if (!v || v === 'public') return { value: 'public' };
@@ -2538,9 +2747,11 @@ function managedCoverHeaders(visibility) {
2538
2747
  return headers;
2539
2748
  }
2540
2749
 
2541
- // Gate a me/org read given the ALREADY-RESOLVED viewer identity. Pure/sync: the
2542
- // caller resolves the viewer once (it also needs the identity for the ownership
2543
- // check) and both the page GET and the ?revisions=json path share this gate.
2750
+ // Gate a me/org read given the ALREADY-RESOLVED viewer identity: the owner and
2751
+ // the stamped domain (viewerMayRead), the handle-claim holder, then the page's
2752
+ // people list. Every read of a page or anything derived from it (bytes, ranges,
2753
+ // covers, transcripts, review threads, revisions) answers to this one gate.
2754
+ // A 503 means the people list could not be read; callers pass it through.
2544
2755
  async function gateVisibility(url, env, obj, identity) {
2545
2756
  const visibility = (obj.customMetadata && obj.customMetadata.visibility) || 'public';
2546
2757
  if (!isIdentityGated(visibility)) return null;
@@ -2555,6 +2766,19 @@ async function gateVisibility(url, env, obj, identity) {
2555
2766
  // has to consult the claim rather than the stamp.
2556
2767
  const handle = decodeURIComponent(url.pathname).split('/').filter(Boolean)[0] || '';
2557
2768
  if (visibility === 'me' && handle && (await holdsHandleClaim(env.BUCKET, handle, identity.userId))) return null;
2769
+ // The people the owner listed (PHNX-4394) widen the audience. The list is
2770
+ // read on every request, so a removal takes effect at once, and a list
2771
+ // that cannot be read refuses the viewer instead of guessing.
2772
+ const email = String(identity.email || '').toLowerCase();
2773
+ if (email) {
2774
+ let people;
2775
+ try {
2776
+ people = await readPeople(env, obj.key);
2777
+ } catch (error) {
2778
+ return accessCheckUnavailable();
2779
+ }
2780
+ if (people.indexOf(email) !== -1) return null;
2781
+ }
2558
2782
  return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
2559
2783
  }
2560
2784
  return null;
@@ -2671,6 +2895,12 @@ async function readUsage(env, owner) {
2671
2895
  multipartCharges: Array.isArray(parsed.multipartCharges)
2672
2896
  ? parsed.multipartCharges.filter(function (id) { return typeof id === 'string'; })
2673
2897
  : [],
2898
+ peopleStart: usageNumber(parsed.peopleStart, 0),
2899
+ peopleUsed: usageNumber(parsed.peopleUsed, 0),
2900
+ lookupStart: usageNumber(parsed.lookupStart, 0),
2901
+ lookupUsed: usageNumber(parsed.lookupUsed, 0),
2902
+ mineStart: usageNumber(parsed.mineStart, 0),
2903
+ mineUsed: usageNumber(parsed.mineUsed, 0),
2674
2904
  };
2675
2905
  }
2676
2906
  } catch (e) {
@@ -2713,13 +2943,30 @@ async function withUsage(env, owner, fn) {
2713
2943
  return json({ error: 'usage ledger contended, retry' }, 503);
2714
2944
  }
2715
2945
 
2716
- function rateLimited(retryAfterSec, ratePerHour) {
2946
+ function rateLimited(retryAfterSec, ratePerHour, error) {
2717
2947
  return new Response(
2718
- JSON.stringify({ error: 'rate limit: too many publishes, retry later', retryAfterSec: retryAfterSec, ratePerHour: ratePerHour }),
2719
- { status: 429, headers: { 'content-type': 'application/json', 'retry-after': String(retryAfterSec) } },
2948
+ JSON.stringify({ error: error || 'rate limit: too many publishes, retry later', retryAfterSec: retryAfterSec, ratePerHour: ratePerHour }),
2949
+ { status: 429, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'retry-after': String(retryAfterSec) } },
2720
2950
  );
2721
2951
  }
2722
2952
 
2953
+ // Count amount against one of the ledger's fixed 1h windows (field + 'Start' /
2954
+ // field + 'Used', e.g. people, lookup) for owner. Returns a 429
2955
+ // {error:'rate_limited'} Response past perHour, or null once counted.
2956
+ async function chargeHourly(env, owner, field, perHour, amount) {
2957
+ const now = Date.now();
2958
+ const out = await withUsage(env, owner, function (usage) {
2959
+ if (now - usage[field + 'Start'] >= RATE_WINDOW_MS) { usage[field + 'Start'] = now; usage[field + 'Used'] = 0; }
2960
+ if (usage[field + 'Used'] + amount > perHour) {
2961
+ const retryAfterSec = Math.max(1, Math.ceil((usage[field + 'Start'] + RATE_WINDOW_MS - now) / 1000));
2962
+ return { reject: rateLimited(retryAfterSec, perHour, 'rate_limited') };
2963
+ }
2964
+ usage[field + 'Used'] += amount;
2965
+ return { commit: usage, result: null };
2966
+ });
2967
+ return out;
2968
+ }
2969
+
2723
2970
  // Charge one authed PUT against the owner's ledger. Rate → per-file cap → object
2724
2971
  // count → byte quota, each failing loud (429 / 413) before anything is written.
2725
2972
  // Returns { error: Response } on any rejection, else { limits } (the resolved
@@ -3022,9 +3269,13 @@ async function redeemTicket(ticket, env) {
3022
3269
  // {userId, email, name?} from a Phoenix identity body (/auth/me, /auth/ticket,
3023
3270
  // or a test hook's claims). name is optional: Phoenix sends it when the account
3024
3271
  // has one, and review threads fall back to the email local part without it.
3272
+ // Phoenix stores only Google-verified (or operator-confirmed) addresses and
3273
+ // does not send the flag; an answer that does say unverified carries no email,
3274
+ // so it can match neither a domain nor a people list.
3025
3275
  function phoenixIdentity(body) {
3026
3276
  if (!body || typeof body.userId !== 'string' || !body.userId) return null;
3027
- const identity = { userId: body.userId, email: typeof body.email === 'string' ? body.email : '' };
3277
+ const unverified = body.email_verified === false || body.emailVerified === false;
3278
+ const identity = { userId: body.userId, email: typeof body.email === 'string' && !unverified ? body.email : '' };
3028
3279
  if (typeof body.name === 'string' && body.name.trim()) identity.name = body.name.trim();
3029
3280
  return identity;
3030
3281
  }