@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
@@ -3,7 +3,7 @@
3
3
  * metadata vocabulary (`lib/share/worker-template.ts`). Three levels an author
4
4
  * ever chooses between:
5
5
  *
6
- * - PUBLIC = `public` — THE DEFAULT (see {@link MANAGED_DEFAULT_VISIBILITY}).
6
+ * - PUBLIC = `public` — THE DEFAULT (see {@link DEFAULT_VISIBILITY}).
7
7
  * Listed in the gallery and given an OG cover, so the
8
8
  * link unfurls into a preview card in Slack/iMessage/
9
9
  * Twitter/Discord. `artifacts share` exists to hand a
@@ -20,8 +20,7 @@
20
20
  * Two capability-URL levels cover the rest: `unlisted` (obscurity — noindex,
21
21
  * gallery-hidden, no cover, still world-readable; this is what `--unlisted` /
22
22
  * `--private` select) and `private` token-gated (`--protected`: a `?k=` key the
23
- * Worker checks, 404 without it). `me`/`org` require a Phoenix session; the
24
- * Worker refuses them for a bare WRITE_TOKEN (BYO) publish.
23
+ * Worker checks, 404 without it).
25
24
  */
26
25
  /** The levels a publish (`share <file> --visibility`) may select. */
27
26
  export const PUBLISH_VISIBILITY_LEVELS = [
@@ -41,8 +40,8 @@ export const EDITABLE_VISIBILITY_LEVELS = [
41
40
  'org',
42
41
  ];
43
42
  /**
44
- * The default for a MANAGED (signed-in) share on this surface: `public` — listed
45
- * in the gallery with an auto OG cover.
43
+ * The default for `artifacts share` on this surface: `public` — listed in the
44
+ * gallery with an auto OG cover.
46
45
  *
47
46
  * This deliberately differs from a session-sync surface, where the same level set
48
47
  * defaults to owner-only. `artifacts share <file>` is an explicit act of handing a
@@ -51,18 +50,7 @@ export const EDITABLE_VISIBILITY_LEVELS = [
51
50
  * careless publish and a leak, and `--visibility me|org`, `--unlisted`, and
52
51
  * `--protected` are one flag away.
53
52
  */
54
- export const MANAGED_DEFAULT_VISIBILITY = 'public';
55
- /**
56
- * The default for a BYO (bring-your-own bucket) publish. `me`/`org` are refused
57
- * server-side for a WRITE_TOKEN publish — there is no Phoenix owner to gate on —
58
- * so a BYO share with no flag is `public` too.
59
- */
60
- export const BYO_DEFAULT_VISIBILITY = 'public';
61
- /** The no-flags default for a given backend. Both are `public` on this surface —
62
- * see {@link MANAGED_DEFAULT_VISIBILITY}. */
63
- export function defaultVisibilityForBackend(kind) {
64
- return kind === 'managed' ? MANAGED_DEFAULT_VISIBILITY : BYO_DEFAULT_VISIBILITY;
65
- }
53
+ export const DEFAULT_VISIBILITY = 'public';
66
54
  /**
67
55
  * The visibility the caller EXPLICITLY asked for, or `undefined` when they
68
56
  * passed no visibility signal at all. `--protected` wins over `--unlisted`
@@ -86,24 +74,9 @@ export function explicitVisibility(opts = {}) {
86
74
  }
87
75
  return undefined;
88
76
  }
89
- /**
90
- * Resolve visibility from the caller's flags, falling back to `fallback` when no
91
- * explicit signal was given. The library fallback stays `public` so a caller
92
- * that hasn't opted into the managed private default (e.g. an existing lib
93
- * consumer) is never silently flipped; the surface applies the product default
94
- * itself via {@link defaultVisibilityForBackend}.
95
- */
96
- export function resolveVisibility(opts = {}, fallback = 'public') {
97
- return explicitVisibility(opts) ?? fallback;
98
- }
99
- /**
100
- * The visibility a PUBLISH should stamp: the caller's explicit flag if any, else
101
- * the default for the resolved backend. This is the one call the publishing
102
- * surface makes, so "what does a bare `artifacts share <file>` mean" is decided
103
- * in exactly one place.
104
- */
105
- export function publishVisibility(opts, kind) {
106
- return explicitVisibility(opts) ?? defaultVisibilityForBackend(kind);
77
+ /** The visibility a publish stamps: the caller's explicit flag, else {@link DEFAULT_VISIBILITY}. */
78
+ export function resolveVisibility(opts = {}) {
79
+ return explicitVisibility(opts) ?? DEFAULT_VISIBILITY;
107
80
  }
108
81
  /** The `--comments` values, in the CLI's hyphenated spelling. */
109
82
  export const COMMENT_POLICY_FLAGS = ['off', 'audience', 'signed-in'];
@@ -1 +1 @@
1
- {"version":3,"file":"visibility.js","sourceRoot":"","sources":["../../../src/lib/share/visibility.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAOH,qEAAqE;AACrE,MAAM,CAAC,MAAM,yBAAyB,GAA+B;IACnE,QAAQ;IACR,UAAU;IACV,SAAS;IACT,IAAI;IACJ,KAAK;CACN,CAAC;AAEF;;gFAEgF;AAChF,MAAM,CAAC,MAAM,0BAA0B,GAA+B;IACpE,QAAQ;IACR,UAAU;IACV,IAAI;IACJ,KAAK;CACN,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAoB,QAAQ,CAAC;AAEpE;;;;GAIG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAoB,QAAQ,CAAC;AAMhE;6CAC6C;AAC7C,MAAM,UAAU,2BAA2B,CAAC,IAAsB;IAChE,OAAO,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,sBAAsB,CAAC;AAClF,CAAC;AAWD;;;;;;;;GAQG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAwB,EAAE;IAC3D,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAC9C,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI;QAAE,OAAO,UAAU,CAAC;IAC9C,IACE,IAAI,CAAC,UAAU,KAAK,QAAQ;QAC5B,IAAI,CAAC,UAAU,KAAK,UAAU;QAC9B,IAAI,CAAC,UAAU,KAAK,SAAS;QAC7B,IAAI,CAAC,UAAU,KAAK,IAAI;QACxB,IAAI,CAAC,UAAU,KAAK,KAAK,EACzB,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAwB,EAAE,EAC1B,WAA4B,QAAQ;IAEpC,OAAO,kBAAkB,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC;AAC9C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAqB,EAAE,IAAsB;IAC7E,OAAO,kBAAkB,CAAC,IAAI,CAAC,IAAI,2BAA2B,CAAC,IAAI,CAAC,CAAC;AACvE,CAAC;AAiBD,iEAAiE;AACjE,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,CAAU,CAAC;AAE9E,8DAA8D;AAC9D,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,IAAI,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC;IACvD,IAAI,IAAI,KAAK,WAAW;QAAE,OAAO,WAAW,CAAC;IAC7C,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,qCAAqC,CAAC,CAAC;AACpF,CAAC"}
1
+ {"version":3,"file":"visibility.js","sourceRoot":"","sources":["../../../src/lib/share/visibility.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAOH,qEAAqE;AACrE,MAAM,CAAC,MAAM,yBAAyB,GAA+B;IACnE,QAAQ;IACR,UAAU;IACV,SAAS;IACT,IAAI;IACJ,KAAK;CACN,CAAC;AAEF;;gFAEgF;AAChF,MAAM,CAAC,MAAM,0BAA0B,GAA+B;IACpE,QAAQ;IACR,UAAU;IACV,IAAI;IACJ,KAAK;CACN,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAoB,QAAQ,CAAC;AAW5D;;;;;;;;GAQG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAwB,EAAE;IAC3D,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAC9C,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI;QAAE,OAAO,UAAU,CAAC;IAC9C,IACE,IAAI,CAAC,UAAU,KAAK,QAAQ;QAC5B,IAAI,CAAC,UAAU,KAAK,UAAU;QAC9B,IAAI,CAAC,UAAU,KAAK,SAAS;QAC7B,IAAI,CAAC,UAAU,KAAK,IAAI;QACxB,IAAI,CAAC,UAAU,KAAK,KAAK,EACzB,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,oGAAoG;AACpG,MAAM,UAAU,iBAAiB,CAAC,OAAwB,EAAE;IAC1D,OAAO,kBAAkB,CAAC,IAAI,CAAC,IAAI,kBAAkB,CAAC;AACxD,CAAC;AAoBD,iEAAiE;AACjE,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,CAAU,CAAC;AAE9E,8DAA8D;AAC9D,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,IAAI,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC;IACvD,IAAI,IAAI,KAAK,WAAW;QAAE,OAAO,WAAW,CAAC;IAC7C,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,qCAAqC,CAAC,CAAC;AACpF,CAAC"}
@@ -649,7 +649,7 @@ async function handleMediaRoute(request, env, url, path, action, ctx) {
649
649
  const notOwner = await assertNamespaceOwner(env, auth, segments);
650
650
  if (notOwner) return notOwner;
651
651
  const cfg = mediaConfig(env);
652
- if (!cfg) return json({ error: 'media processing is not configured on this endpoint; bind it with artifacts share update --media-keys' }, 501);
652
+ if (!cfg) return json({ error: 'media processing is not configured on this endpoint; bind DEEPGRAM_API_KEY, OPENROUTER_API_KEY and MEDIA_JOB_SECRET as Worker secrets' }, 501);
653
653
  const video = await env.BUCKET.head(path);
654
654
  if (!video || isMediaDerived(video)) return json({ error: 'share not found', key: path }, 404);
655
655
  if (!isVideoObject(video)) return json({ error: 'media processing needs a video' }, 415);
@@ -0,0 +1 @@
1
+ export declare const SHARE_PEOPLE_WORKER_SOURCE = "\nvar PEOPLE_MAX = 50;\nvar PEOPLE_BODY_MAX_BYTES = 16 * 1024;\n// Per identity, in the usage ledger's fixed 1h windows: newly added addresses\n// per page owner (each may be emailed), and exact-address lookups per caller.\nvar PEOPLE_ADDED_PER_HOUR = 20;\nvar PEOPLE_LOOKUPS_PER_HOUR = 60;\nvar PEOPLE_TITLE_MAX = 200;\n// /__mine and /__shared answer one bounded page at a time; follow next_cursor.\nvar PEOPLE_PAGE_SIZE = 25;\nvar PEOPLE_MINE_MAX_HANDLES = 20;\nvar PEOPLE_MINE_PER_HOUR = 240;\nvar PEOPLE_EMAIL = /^[^\\s@\\/,;<>\"]+@[^\\s@\\/,;<>\"]+\\.[^\\s@\\/,;<>\"]+$/;\n\nfunction peopleKey(path) {\n return '__people/' + path;\n}\n\nfunction inboxKey(email, path) {\n return '__inbox/' + email + '/' + path;\n}\n\nfunction peopleJson(body, status) {\n return new Response(JSON.stringify(body), {\n status: status,\n headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'X-Robots-Tag': 'noindex' },\n });\n}\n\nfunction accessCheckUnavailable() {\n return new Response(JSON.stringify({ error: 'access_check_unavailable' }), {\n status: 503,\n headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'private, no-store', 'X-Robots-Tag': 'noindex', 'retry-after': '5' },\n });\n}\n\n// One address, lowercased, or '' when it is not one.\nfunction normalizePersonEmail(raw) {\n if (typeof raw !== 'string') return '';\n const email = raw.trim().toLowerCase();\n return email.length <= 254 && PEOPLE_EMAIL.test(email) ? email : '';\n}\n\nfunction isExpiredObject(obj) {\n const expiresAt = obj && obj.customMetadata && obj.customMetadata['expires-at'];\n return !!expiresAt && Date.now() > Date.parse(expiresAt);\n}\n\nfunction pageTitle(meta, path) {\n return String((meta && (meta.label || meta['og-title'])) || path.split('/').pop()).slice(0, PEOPLE_TITLE_MAX);\n}\n\nfunction pageKind(contentType) {\n const ct = String(contentType || '').toLowerCase();\n if (ct.indexOf('text/html') !== -1) return 'page';\n return viewableAssetKind(ct) || 'file';\n}\n\n// The page's list and its version: the sidecar's R2 etag, '' when there is\n// none. Throws when it cannot be read or parsed, so every caller fails closed\n// rather than treating an unreadable list as an empty one.\nasync function readPeopleRecord(env, path) {\n const object = await env.BUCKET.get(peopleKey(path));\n if (!object) return { people: [], version: '' };\n const parsed = JSON.parse(await object.text());\n if (!parsed || !Array.isArray(parsed.people) || parsed.people.some(function (email) { return typeof email !== 'string'; })) {\n throw new Error('malformed people list for ' + path);\n }\n return { people: parsed.people, version: object.etag || '' };\n}\n\nasync function readPeople(env, path) {\n return (await readPeopleRecord(env, path)).people;\n}\n\n// Replace the list only if it is still at version. Returns the new version\n// ('' once emptied), or null when another write got there first. Callers hold\n// the page's path lock, which also covers the delete R2 cannot make conditional.\nasync function writePeople(env, path, people, version) {\n if (!people.length) {\n await env.BUCKET.delete(peopleKey(path));\n return '';\n }\n const written = await env.BUCKET.put(peopleKey(path), JSON.stringify({ people: people, updated_at: new Date().toISOString() }), {\n httpMetadata: { contentType: 'application/json' },\n onlyIf: version ? { etagMatches: version } : { etagDoesNotMatch: '*' },\n });\n return written === null ? null : (written.etag || '');\n}\n\n// The version a PUT was based on, from If-Match: \"<version>\" (or bare), with\n// \"\" meaning \"there is no list yet\". null when the header is absent.\nfunction ifMatchVersion(request) {\n const raw = request.headers.get('if-match');\n if (raw === null) return null;\n return raw.trim().replace(/^W\\//, '').replace(/^\"(.*)\"$/, '$1');\n}\n\nfunction peopleChanged(record) {\n return peopleJson({ error: 'people_changed', people: record.people, version: record.version }, 412);\n}\n\n// A page that goes away takes its list and inbox entries with it. A list that\n// cannot be parsed still goes; its inbox entries are dropped by the next\n// /__shared that finds no list behind them.\nasync function clearPeople(env, path) {\n let people = [];\n try {\n people = await readPeople(env, path);\n } catch (error) {\n people = [];\n }\n for (const email of people) await env.BUCKET.delete(inboxKey(email, path));\n await env.BUCKET.delete(peopleKey(path));\n}\n\n// Called under the path's mutation lock before a publish writes: current is\n// what sits at the path now. Only a live page keeps its people.\nasync function clearStalePeople(env, path, current) {\n if (current && !isExpiredObject(current)) return;\n await clearPeople(env, path);\n}\n\n// Names and avatars for exact addresses, from Rush's users. An address with no\n// account is absent from byEmail. error is set when Rush could not answer, so\n// a missing name is never mistaken for \"no Rush account\".\nasync function lookupPeopleNames(env, emails) {\n if (!emails.length) return { byEmail: {} };\n const collab = collabConfig(env);\n if (!collab) return { byEmail: {}, error: true };\n const result = await collabRegistryCall(collab, 'POST', '/people', '', { emails: emails });\n if (result.error || !result.body || !Array.isArray(result.body.people)) return { byEmail: {}, error: true };\n const byEmail = {};\n for (const person of result.body.people) {\n if (!person || typeof person.email !== 'string') continue;\n byEmail[person.email.toLowerCase()] = {\n name: typeof person.name === 'string' && person.name ? person.name : null,\n avatar_url: typeof person.avatar_url === 'string' && person.avatar_url ? person.avatar_url : null,\n };\n }\n return { byEmail: byEmail };\n}\n\nfunction describePerson(email, names, callerEmail) {\n const found = names.byEmail[email];\n return {\n email: email,\n name: found ? found.name : null,\n avatar_url: found ? found.avatar_url : null,\n external: emailDomain(email) !== emailDomain(callerEmail),\n };\n}\n\n// The caller for these routes: a Phoenix bearer and nothing else. Published\n// pages run on this origin, so the browser's __share cookie (or a ticket it\n// redeems) would let any page's script list a visitor's pages and add itself\n// to them. The CLI and the console proxy both send the bearer.\nasync function peopleCaller(request, env) {\n const identity = phoenixIdentity(await hooks.verifyPhoenixToken(request, env));\n if (!identity) return { error: peopleJson({ error: 'unauthorized' }, 401) };\n return { identity: identity };\n}\n\nasync function handlePeopleRoute(request, env, url, path) {\n const isRead = request.method === 'GET' || request.method === 'HEAD';\n if (path === '__lookup' || path === '__mine' || path === '__shared') {\n if (!isRead) return peopleJson({ error: 'method not allowed' }, 405);\n const caller = await peopleCaller(request, env);\n if (caller.error) return caller.error;\n if (path === '__lookup') return lookupPerson(env, url, caller.identity);\n if (path === '__mine') return listMine(env, url, caller.identity);\n return listShared(env, url, caller.identity);\n }\n if (!isRead && request.method !== 'PUT') return peopleJson({ error: 'method not allowed' }, 405);\n const key = path.slice('__people/'.length);\n const segments = key.split('/');\n const notFound = peopleJson({ error: 'not found' }, 404);\n if (segments.length !== 2 || !segments[0] || !segments[1] || segments[0].startsWith('__') || key.endsWith('.png')) return notFound;\n const caller = await peopleCaller(request, env);\n if (caller.error) return caller.error;\n const identity = caller.identity;\n // The same authority PATCH visibility uses: the namespace's handle claim.\n const auth = { kind: 'phoenix', owner: identity.userId, email: identity.email || '', name: identity.name || '' };\n if (await assertNamespaceOwner(env, auth, segments)) return notFound;\n const page = await env.BUCKET.head(key);\n if (!page || isExpiredObject(page) || isMediaDerived(page)) return notFound;\n if (request.method === 'PUT') return replacePeople(request, env, url, key, auth);\n\n let record;\n try {\n record = await readPeopleRecord(env, key);\n } catch (error) {\n return accessCheckUnavailable();\n }\n const meta = page.customMetadata || {};\n const names = await lookupPeopleNames(env, record.people);\n const body = {\n visibility: meta.visibility || 'public',\n org_domain: meta.org_domain || null,\n people: record.people.map(function (email) { return describePerson(email, names, auth.email); }),\n version: record.version,\n };\n if (names.error) body.names_error = 'names_unavailable';\n return peopleJson(body, 200);\n}\n\nasync function replacePeople(request, env, url, key, auth) {\n const read = await readBodyBounded(request, PEOPLE_BODY_MAX_BYTES);\n if (read.oversize) return peopleJson({ error: 'too_many_people' }, 400);\n let input;\n try {\n input = JSON.parse(new TextDecoder().decode(read.bytes) || '{}');\n } catch {\n return peopleJson({ error: 'invalid_request' }, 400);\n }\n if (!input || typeof input !== 'object' || !Array.isArray(input.people)) return peopleJson({ error: 'invalid_request' }, 400);\n if (input.notify !== undefined && typeof input.notify !== 'boolean') return peopleJson({ error: 'invalid_request' }, 400);\n const notify = input.notify !== false;\n const next = [];\n for (const raw of input.people) {\n const email = normalizePersonEmail(raw);\n if (!email) return peopleJson({ error: 'invalid_email', email: typeof raw === 'string' ? raw.slice(0, 254) : null }, 400);\n if (next.indexOf(email) === -1) next.push(email);\n }\n if (next.length > PEOPLE_MAX) return peopleJson({ error: 'too_many_people', max: PEOPLE_MAX }, 400);\n const ownerEmail = String(auth.email || '').toLowerCase();\n if (ownerEmail && next.indexOf(ownerEmail) !== -1) return peopleJson({ error: 'owner_in_list' }, 400);\n // The whole list is replaced, so a write must name the version it was based\n // on: a client holding an old read cannot silently drop someone.\n const basedOn = ifMatchVersion(request);\n if (basedOn === null) return peopleJson({ error: 'people_version_required' }, 428);\n\n // The page's lock: a delete or a fresh publish at this address cannot land\n // between reading the page and writing its list.\n const holder = 'people:' + crypto.randomUUID();\n if (!(await acquirePathMutationLock(env.BUCKET, key, holder, 'mutation'))) {\n return peopleJson({ error: 'conflict', detail: 'another write is active for this page' }, 409);\n }\n let added;\n let removed;\n let title;\n let version;\n try {\n const page = await env.BUCKET.head(key);\n if (!page || isExpiredObject(page) || isMediaDerived(page)) return peopleJson({ error: 'not found' }, 404);\n const meta = page.customMetadata || {};\n if ((meta.visibility || 'public') === 'private' && next.length) return peopleJson({ error: 'people_need_sign_in' }, 400);\n let current;\n try {\n current = await readPeopleRecord(env, key);\n } catch (error) {\n return accessCheckUnavailable();\n }\n if (current.version !== basedOn) return peopleChanged(current);\n const previous = current.people;\n added = next.filter(function (email) { return previous.indexOf(email) === -1; });\n removed = previous.filter(function (email) { return next.indexOf(email) === -1; });\n title = pageTitle(meta, key);\n if (added.length) {\n const limited = await chargeHourly(env, auth.owner, 'people', PEOPLE_ADDED_PER_HOUR, added.length);\n if (limited) return limited;\n }\n if (!(await pathMutationLockOwned(env.BUCKET, key, holder))) {\n return peopleJson({ error: 'conflict', detail: 'the page lock changed; retry' }, 409);\n }\n // The list first: a removal is in force before any index catches up.\n version = await writePeople(env, key, next, current.version);\n if (version === null) {\n try {\n return peopleChanged(await readPeopleRecord(env, key));\n } catch (error) {\n return accessCheckUnavailable();\n }\n }\n for (const email of removed) await env.BUCKET.delete(inboxKey(email, key));\n // Every listed address gets an inbox entry, not only the added ones, so an\n // entry a failed save never wrote is repaired by the next one. An existing\n // entry keeps its added_at.\n const addedAt = new Date().toISOString();\n for (const email of next) {\n if (added.indexOf(email) === -1 && (await env.BUCKET.head(inboxKey(email, key)))) continue;\n await env.BUCKET.put(inboxKey(email, key), '', {\n customMetadata: { owner_email: ownerEmail, owner_name: collabDisplayName({ name: auth.name, email: ownerEmail, userId: auth.owner }), title: title, added_at: addedAt },\n });\n }\n // A generated cover was rendered for the old audience; drop it the way a\n // visibility change does.\n if (added.length || removed.length) {\n const cover = await env.BUCKET.head(key + '.png');\n if (cover && cover.customMetadata && cover.customMetadata['og-generated'] === 'true') await env.BUCKET.delete(key + '.png');\n }\n } finally {\n await releasePathMutationLock(env.BUCKET, key, holder);\n }\n\n const body = { people: next, version: version, added: added, removed: removed, notified: [] };\n if (notify && added.length) {\n const outcome = await sendInvites(env, url, key, title, auth, added);\n body.notified = outcome.sent;\n if (outcome.unsent.length) {\n body.notify_error = 'email_unavailable';\n body.notify_failed = outcome.unsent;\n }\n }\n return peopleJson(body, 200);\n}\n\n// Email the newly added addresses a link. The owner's name and address are the\n// verified identity's, never anything the request carried. Rush answers\n// {sent, failed (permanent), retryable}; anything not in sent is unsent. A\n// transport failure or 5xx is retried once with the same Idempotency-Key, so\n// Rush never sends a second copy of an invitation it already sent.\nasync function sendInvites(env, url, key, title, auth, recipients) {\n const collab = collabConfig(env);\n if (!collab) return { sent: [], unsent: recipients };\n const ownerEmail = String(auth.email || '').toLowerCase();\n const payload = {\n url: url.origin + '/' + key,\n title: title,\n owner_name: collabDisplayName({ name: auth.name, email: ownerEmail, userId: auth.owner }),\n owner_email: ownerEmail,\n recipients: recipients,\n };\n const idempotencyKey = 'invite:' + crypto.randomUUID();\n let result = await collabRegistryCall(collab, 'POST', '/invites', collabShareId(url, key), payload, idempotencyKey);\n if (result.error && (!result.status || result.status >= 500)) {\n result = await collabRegistryCall(collab, 'POST', '/invites', collabShareId(url, key), payload, idempotencyKey);\n }\n const answered = !result.error && result.body && Array.isArray(result.body.sent) ? result.body.sent : [];\n const sent = recipients.filter(function (email) { return answered.indexOf(email) !== -1; });\n return { sent: sent, unsent: recipients.filter(function (email) { return sent.indexOf(email) === -1; }) };\n}\n\nasync function lookupPerson(env, url, identity) {\n const email = normalizePersonEmail(url.searchParams.get('email') || '');\n if (!email) return peopleJson({ error: 'invalid_email' }, 400);\n const limited = await chargeHourly(env, identity.userId, 'lookup', PEOPLE_LOOKUPS_PER_HOUR, 1);\n if (limited) return limited;\n const names = await lookupPeopleNames(env, [email]);\n const body = describePerson(email, names, identity.email);\n if (names.error) body.names_error = 'names_unavailable';\n return peopleJson(body, 200);\n}\n\n// Opaque paging position: the handle being listed and the last key returned.\nfunction encodePeopleCursor(position) {\n return toB64Url(JSON.stringify(position));\n}\n\nfunction decodePeopleCursor(raw) {\n if (!raw) return { h: '', a: '' };\n try {\n const parsed = JSON.parse(fromB64Url(raw));\n if (parsed && typeof parsed.h === 'string' && typeof parsed.a === 'string') return parsed;\n } catch {\n // not one of ours\n }\n return null;\n}\n\n// The handles whose claim the caller holds: the per-user index claimHandle\n// keeps, plus the caller's derived handle for a claim written before the index.\nasync function ownedHandles(env, identity) {\n const prefix = handleIndexPrefix(identity.userId);\n const list = await env.BUCKET.list({ prefix: prefix, limit: PEOPLE_MINE_MAX_HANDLES });\n const handles = (list.objects || []).map(function (o) { return o.key.slice(prefix.length); });\n const derived = handleFromEmail(identity.email);\n if (derived && handles.indexOf(derived) === -1 && (await holdsHandleClaim(env.BUCKET, derived, identity.userId))) handles.push(derived);\n return handles.sort();\n}\n\n// One page of the live pages under the caller's handles, in key order.\nasync function listMine(env, url, identity) {\n const position = decodePeopleCursor(url.searchParams.get('cursor'));\n if (!position) return peopleJson({ error: 'invalid_cursor' }, 400);\n const limited = await chargeHourly(env, identity.userId, 'mine', PEOPLE_MINE_PER_HOUR, 1);\n if (limited) return limited;\n const handles = await ownedHandles(env, identity);\n let index = position.h ? handles.indexOf(position.h) : 0;\n if (index === -1) return peopleJson({ pages: [], next_cursor: null }, 200);\n const handle = handles[index];\n if (!handle) return peopleJson({ pages: [], next_cursor: null }, 200);\n // The delimiter leaves out retained revisions (<handle>/<slug>/rev-*).\n const listing = await env.BUCKET.list({\n prefix: handle + '/', delimiter: '/', limit: PEOPLE_PAGE_SIZE, include: ['httpMetadata', 'customMetadata'],\n ...(position.a ? { startAfter: position.a } : {}),\n });\n const objects = listing.objects || [];\n const last = objects.length ? objects[objects.length - 1].key : '';\n const sidecars = {};\n if (objects.length) {\n const listed = await env.BUCKET.list({ prefix: peopleKey(handle + '/'), limit: 1000, ...(position.a ? { startAfter: peopleKey(position.a) } : {}) });\n for (const sidecar of listed.objects || []) {\n const path = sidecar.key.slice('__people/'.length);\n if (path <= last) sidecars[path] = true;\n }\n }\n const pages = [];\n for (const o of objects) {\n if (o.key.endsWith('.png') || isMediaDerived(o) || isExpiredObject(o)) continue;\n const meta = o.customMetadata || {};\n let people = [];\n if (sidecars[o.key]) {\n try {\n people = await readPeople(env, o.key);\n } catch (error) {\n return accessCheckUnavailable();\n }\n }\n pages.push({\n url: url.origin + '/' + o.key,\n path: o.key,\n title: pageTitle(meta, o.key),\n visibility: meta.visibility || 'public',\n org_domain: meta.org_domain || null,\n kind: pageKind(o.httpMetadata && o.httpMetadata.contentType),\n size: typeof o.size === 'number' ? o.size : 0,\n uploaded: new Date(publishedAtOf(o)).toISOString(),\n people: people,\n });\n }\n let next = null;\n if (listing.truncated && last) next = { h: handle, a: last };\n else if (index + 1 < handles.length) next = { h: handles[index + 1], a: '' };\n return peopleJson({ pages: pages, next_cursor: next ? encodePeopleCursor(next) : null }, 200);\n}\n\n// One page of the caller's inbox, keeping only pages they can open because of\n// the list right now: a live me or org page whose list still names them. The\n// inbox is an index, never an authority, so a stale entry is skipped here and\n// left for the owner's next save or the page's delete to clear.\nasync function listShared(env, url, identity) {\n const position = decodePeopleCursor(url.searchParams.get('cursor'));\n if (!position) return peopleJson({ error: 'invalid_cursor' }, 400);\n const email = normalizePersonEmail(identity.email || '');\n if (!email) return peopleJson({ pages: [], next_cursor: null }, 200);\n const prefix = inboxKey(email, '');\n const listing = await env.BUCKET.list({ prefix: prefix, limit: PEOPLE_PAGE_SIZE, include: ['customMetadata'], ...(position.a ? { startAfter: prefix + position.a } : {}) });\n const entries = listing.objects || [];\n const pages = [];\n for (const entry of entries) {\n const path = entry.key.slice(prefix.length);\n const page = await env.BUCKET.head(path);\n const pageMeta = (page && page.customMetadata) || {};\n if (!page || isExpiredObject(page) || !isIdentityGated(pageMeta.visibility || 'public')) continue;\n let people;\n try {\n people = await readPeople(env, path);\n } catch (error) {\n return accessCheckUnavailable();\n }\n if (people.indexOf(email) === -1) continue;\n const meta = entry.customMetadata || {};\n pages.push({\n url: url.origin + '/' + path,\n path: path,\n title: pageTitle(pageMeta, path),\n kind: pageKind(page.httpMetadata && page.httpMetadata.contentType),\n owner_email: meta.owner_email || null,\n owner_name: meta.owner_name || null,\n added_at: meta.added_at || null,\n });\n }\n const last = entries.length ? entries[entries.length - 1].key.slice(prefix.length) : '';\n return peopleJson({ pages: pages, next_cursor: listing.truncated && last ? encodePeopleCursor({ h: '', a: last }) : null }, 200);\n}\n";
@@ -0,0 +1,491 @@
1
+ // Sharing a page with specific people by email (PHNX-4394), injected into the
2
+ // generated share Worker beside the publish and media sources.
3
+ //
4
+ // __people/<user>/<slug> {"people":["a@x.com",...],"updated_at":"<iso>"}
5
+ // The authority: gateVisibility reads it on
6
+ // every me/org read by someone who is neither
7
+ // the owner nor in the stamped domain.
8
+ // __inbox/<email>/<user>/<slug> empty, customMetadata {owner_email,
9
+ // owner_name, title, added_at}. An index for
10
+ // "Shared with me", never an authority: every
11
+ // listing re-checks the page's list.
12
+ //
13
+ // Routes (JSON, cache-control: no-store):
14
+ // GET|PUT /__people/<user>/<slug> the page owner (PATCH's authority); anyone
15
+ // else gets 404. GET returns the list's
16
+ // version; PUT replaces the whole list and
17
+ // needs If-Match: "<version>", else 412.
18
+ // GET /__lookup?email=<exact> any signed-in identity
19
+ // GET /__mine pages under the handles the caller holds
20
+ // GET /__shared pages shared to the caller's email
21
+ //
22
+ // Names come from Rush (POST /internal/artifact-collab/people, exact email
23
+ // match) and invitation emails go out through POST .../invites.
24
+ export const SHARE_PEOPLE_WORKER_SOURCE = `
25
+ var PEOPLE_MAX = 50;
26
+ var PEOPLE_BODY_MAX_BYTES = 16 * 1024;
27
+ // Per identity, in the usage ledger's fixed 1h windows: newly added addresses
28
+ // per page owner (each may be emailed), and exact-address lookups per caller.
29
+ var PEOPLE_ADDED_PER_HOUR = 20;
30
+ var PEOPLE_LOOKUPS_PER_HOUR = 60;
31
+ var PEOPLE_TITLE_MAX = 200;
32
+ // /__mine and /__shared answer one bounded page at a time; follow next_cursor.
33
+ var PEOPLE_PAGE_SIZE = 25;
34
+ var PEOPLE_MINE_MAX_HANDLES = 20;
35
+ var PEOPLE_MINE_PER_HOUR = 240;
36
+ var PEOPLE_EMAIL = /^[^\\s@\\/,;<>"]+@[^\\s@\\/,;<>"]+\\.[^\\s@\\/,;<>"]+$/;
37
+
38
+ function peopleKey(path) {
39
+ return '__people/' + path;
40
+ }
41
+
42
+ function inboxKey(email, path) {
43
+ return '__inbox/' + email + '/' + path;
44
+ }
45
+
46
+ function peopleJson(body, status) {
47
+ return new Response(JSON.stringify(body), {
48
+ status: status,
49
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'X-Robots-Tag': 'noindex' },
50
+ });
51
+ }
52
+
53
+ function accessCheckUnavailable() {
54
+ return new Response(JSON.stringify({ error: 'access_check_unavailable' }), {
55
+ status: 503,
56
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'private, no-store', 'X-Robots-Tag': 'noindex', 'retry-after': '5' },
57
+ });
58
+ }
59
+
60
+ // One address, lowercased, or '' when it is not one.
61
+ function normalizePersonEmail(raw) {
62
+ if (typeof raw !== 'string') return '';
63
+ const email = raw.trim().toLowerCase();
64
+ return email.length <= 254 && PEOPLE_EMAIL.test(email) ? email : '';
65
+ }
66
+
67
+ function isExpiredObject(obj) {
68
+ const expiresAt = obj && obj.customMetadata && obj.customMetadata['expires-at'];
69
+ return !!expiresAt && Date.now() > Date.parse(expiresAt);
70
+ }
71
+
72
+ function pageTitle(meta, path) {
73
+ return String((meta && (meta.label || meta['og-title'])) || path.split('/').pop()).slice(0, PEOPLE_TITLE_MAX);
74
+ }
75
+
76
+ function pageKind(contentType) {
77
+ const ct = String(contentType || '').toLowerCase();
78
+ if (ct.indexOf('text/html') !== -1) return 'page';
79
+ return viewableAssetKind(ct) || 'file';
80
+ }
81
+
82
+ // The page's list and its version: the sidecar's R2 etag, '' when there is
83
+ // none. Throws when it cannot be read or parsed, so every caller fails closed
84
+ // rather than treating an unreadable list as an empty one.
85
+ async function readPeopleRecord(env, path) {
86
+ const object = await env.BUCKET.get(peopleKey(path));
87
+ if (!object) return { people: [], version: '' };
88
+ const parsed = JSON.parse(await object.text());
89
+ if (!parsed || !Array.isArray(parsed.people) || parsed.people.some(function (email) { return typeof email !== 'string'; })) {
90
+ throw new Error('malformed people list for ' + path);
91
+ }
92
+ return { people: parsed.people, version: object.etag || '' };
93
+ }
94
+
95
+ async function readPeople(env, path) {
96
+ return (await readPeopleRecord(env, path)).people;
97
+ }
98
+
99
+ // Replace the list only if it is still at version. Returns the new version
100
+ // ('' once emptied), or null when another write got there first. Callers hold
101
+ // the page's path lock, which also covers the delete R2 cannot make conditional.
102
+ async function writePeople(env, path, people, version) {
103
+ if (!people.length) {
104
+ await env.BUCKET.delete(peopleKey(path));
105
+ return '';
106
+ }
107
+ const written = await env.BUCKET.put(peopleKey(path), JSON.stringify({ people: people, updated_at: new Date().toISOString() }), {
108
+ httpMetadata: { contentType: 'application/json' },
109
+ onlyIf: version ? { etagMatches: version } : { etagDoesNotMatch: '*' },
110
+ });
111
+ return written === null ? null : (written.etag || '');
112
+ }
113
+
114
+ // The version a PUT was based on, from If-Match: "<version>" (or bare), with
115
+ // "" meaning "there is no list yet". null when the header is absent.
116
+ function ifMatchVersion(request) {
117
+ const raw = request.headers.get('if-match');
118
+ if (raw === null) return null;
119
+ return raw.trim().replace(/^W\\//, '').replace(/^"(.*)"$/, '$1');
120
+ }
121
+
122
+ function peopleChanged(record) {
123
+ return peopleJson({ error: 'people_changed', people: record.people, version: record.version }, 412);
124
+ }
125
+
126
+ // A page that goes away takes its list and inbox entries with it. A list that
127
+ // cannot be parsed still goes; its inbox entries are dropped by the next
128
+ // /__shared that finds no list behind them.
129
+ async function clearPeople(env, path) {
130
+ let people = [];
131
+ try {
132
+ people = await readPeople(env, path);
133
+ } catch (error) {
134
+ people = [];
135
+ }
136
+ for (const email of people) await env.BUCKET.delete(inboxKey(email, path));
137
+ await env.BUCKET.delete(peopleKey(path));
138
+ }
139
+
140
+ // Called under the path's mutation lock before a publish writes: current is
141
+ // what sits at the path now. Only a live page keeps its people.
142
+ async function clearStalePeople(env, path, current) {
143
+ if (current && !isExpiredObject(current)) return;
144
+ await clearPeople(env, path);
145
+ }
146
+
147
+ // Names and avatars for exact addresses, from Rush's users. An address with no
148
+ // account is absent from byEmail. error is set when Rush could not answer, so
149
+ // a missing name is never mistaken for "no Rush account".
150
+ async function lookupPeopleNames(env, emails) {
151
+ if (!emails.length) return { byEmail: {} };
152
+ const collab = collabConfig(env);
153
+ if (!collab) return { byEmail: {}, error: true };
154
+ const result = await collabRegistryCall(collab, 'POST', '/people', '', { emails: emails });
155
+ if (result.error || !result.body || !Array.isArray(result.body.people)) return { byEmail: {}, error: true };
156
+ const byEmail = {};
157
+ for (const person of result.body.people) {
158
+ if (!person || typeof person.email !== 'string') continue;
159
+ byEmail[person.email.toLowerCase()] = {
160
+ name: typeof person.name === 'string' && person.name ? person.name : null,
161
+ avatar_url: typeof person.avatar_url === 'string' && person.avatar_url ? person.avatar_url : null,
162
+ };
163
+ }
164
+ return { byEmail: byEmail };
165
+ }
166
+
167
+ function describePerson(email, names, callerEmail) {
168
+ const found = names.byEmail[email];
169
+ return {
170
+ email: email,
171
+ name: found ? found.name : null,
172
+ avatar_url: found ? found.avatar_url : null,
173
+ external: emailDomain(email) !== emailDomain(callerEmail),
174
+ };
175
+ }
176
+
177
+ // The caller for these routes: a Phoenix bearer and nothing else. Published
178
+ // pages run on this origin, so the browser's __share cookie (or a ticket it
179
+ // redeems) would let any page's script list a visitor's pages and add itself
180
+ // to them. The CLI and the console proxy both send the bearer.
181
+ async function peopleCaller(request, env) {
182
+ const identity = phoenixIdentity(await hooks.verifyPhoenixToken(request, env));
183
+ if (!identity) return { error: peopleJson({ error: 'unauthorized' }, 401) };
184
+ return { identity: identity };
185
+ }
186
+
187
+ async function handlePeopleRoute(request, env, url, path) {
188
+ const isRead = request.method === 'GET' || request.method === 'HEAD';
189
+ if (path === '__lookup' || path === '__mine' || path === '__shared') {
190
+ if (!isRead) return peopleJson({ error: 'method not allowed' }, 405);
191
+ const caller = await peopleCaller(request, env);
192
+ if (caller.error) return caller.error;
193
+ if (path === '__lookup') return lookupPerson(env, url, caller.identity);
194
+ if (path === '__mine') return listMine(env, url, caller.identity);
195
+ return listShared(env, url, caller.identity);
196
+ }
197
+ if (!isRead && request.method !== 'PUT') return peopleJson({ error: 'method not allowed' }, 405);
198
+ const key = path.slice('__people/'.length);
199
+ const segments = key.split('/');
200
+ const notFound = peopleJson({ error: 'not found' }, 404);
201
+ if (segments.length !== 2 || !segments[0] || !segments[1] || segments[0].startsWith('__') || key.endsWith('.png')) return notFound;
202
+ const caller = await peopleCaller(request, env);
203
+ if (caller.error) return caller.error;
204
+ const identity = caller.identity;
205
+ // The same authority PATCH visibility uses: the namespace's handle claim.
206
+ const auth = { kind: 'phoenix', owner: identity.userId, email: identity.email || '', name: identity.name || '' };
207
+ if (await assertNamespaceOwner(env, auth, segments)) return notFound;
208
+ const page = await env.BUCKET.head(key);
209
+ if (!page || isExpiredObject(page) || isMediaDerived(page)) return notFound;
210
+ if (request.method === 'PUT') return replacePeople(request, env, url, key, auth);
211
+
212
+ let record;
213
+ try {
214
+ record = await readPeopleRecord(env, key);
215
+ } catch (error) {
216
+ return accessCheckUnavailable();
217
+ }
218
+ const meta = page.customMetadata || {};
219
+ const names = await lookupPeopleNames(env, record.people);
220
+ const body = {
221
+ visibility: meta.visibility || 'public',
222
+ org_domain: meta.org_domain || null,
223
+ people: record.people.map(function (email) { return describePerson(email, names, auth.email); }),
224
+ version: record.version,
225
+ };
226
+ if (names.error) body.names_error = 'names_unavailable';
227
+ return peopleJson(body, 200);
228
+ }
229
+
230
+ async function replacePeople(request, env, url, key, auth) {
231
+ const read = await readBodyBounded(request, PEOPLE_BODY_MAX_BYTES);
232
+ if (read.oversize) return peopleJson({ error: 'too_many_people' }, 400);
233
+ let input;
234
+ try {
235
+ input = JSON.parse(new TextDecoder().decode(read.bytes) || '{}');
236
+ } catch {
237
+ return peopleJson({ error: 'invalid_request' }, 400);
238
+ }
239
+ if (!input || typeof input !== 'object' || !Array.isArray(input.people)) return peopleJson({ error: 'invalid_request' }, 400);
240
+ if (input.notify !== undefined && typeof input.notify !== 'boolean') return peopleJson({ error: 'invalid_request' }, 400);
241
+ const notify = input.notify !== false;
242
+ const next = [];
243
+ for (const raw of input.people) {
244
+ const email = normalizePersonEmail(raw);
245
+ if (!email) return peopleJson({ error: 'invalid_email', email: typeof raw === 'string' ? raw.slice(0, 254) : null }, 400);
246
+ if (next.indexOf(email) === -1) next.push(email);
247
+ }
248
+ if (next.length > PEOPLE_MAX) return peopleJson({ error: 'too_many_people', max: PEOPLE_MAX }, 400);
249
+ const ownerEmail = String(auth.email || '').toLowerCase();
250
+ if (ownerEmail && next.indexOf(ownerEmail) !== -1) return peopleJson({ error: 'owner_in_list' }, 400);
251
+ // The whole list is replaced, so a write must name the version it was based
252
+ // on: a client holding an old read cannot silently drop someone.
253
+ const basedOn = ifMatchVersion(request);
254
+ if (basedOn === null) return peopleJson({ error: 'people_version_required' }, 428);
255
+
256
+ // The page's lock: a delete or a fresh publish at this address cannot land
257
+ // between reading the page and writing its list.
258
+ const holder = 'people:' + crypto.randomUUID();
259
+ if (!(await acquirePathMutationLock(env.BUCKET, key, holder, 'mutation'))) {
260
+ return peopleJson({ error: 'conflict', detail: 'another write is active for this page' }, 409);
261
+ }
262
+ let added;
263
+ let removed;
264
+ let title;
265
+ let version;
266
+ try {
267
+ const page = await env.BUCKET.head(key);
268
+ if (!page || isExpiredObject(page) || isMediaDerived(page)) return peopleJson({ error: 'not found' }, 404);
269
+ const meta = page.customMetadata || {};
270
+ if ((meta.visibility || 'public') === 'private' && next.length) return peopleJson({ error: 'people_need_sign_in' }, 400);
271
+ let current;
272
+ try {
273
+ current = await readPeopleRecord(env, key);
274
+ } catch (error) {
275
+ return accessCheckUnavailable();
276
+ }
277
+ if (current.version !== basedOn) return peopleChanged(current);
278
+ const previous = current.people;
279
+ added = next.filter(function (email) { return previous.indexOf(email) === -1; });
280
+ removed = previous.filter(function (email) { return next.indexOf(email) === -1; });
281
+ title = pageTitle(meta, key);
282
+ if (added.length) {
283
+ const limited = await chargeHourly(env, auth.owner, 'people', PEOPLE_ADDED_PER_HOUR, added.length);
284
+ if (limited) return limited;
285
+ }
286
+ if (!(await pathMutationLockOwned(env.BUCKET, key, holder))) {
287
+ return peopleJson({ error: 'conflict', detail: 'the page lock changed; retry' }, 409);
288
+ }
289
+ // The list first: a removal is in force before any index catches up.
290
+ version = await writePeople(env, key, next, current.version);
291
+ if (version === null) {
292
+ try {
293
+ return peopleChanged(await readPeopleRecord(env, key));
294
+ } catch (error) {
295
+ return accessCheckUnavailable();
296
+ }
297
+ }
298
+ for (const email of removed) await env.BUCKET.delete(inboxKey(email, key));
299
+ // Every listed address gets an inbox entry, not only the added ones, so an
300
+ // entry a failed save never wrote is repaired by the next one. An existing
301
+ // entry keeps its added_at.
302
+ const addedAt = new Date().toISOString();
303
+ for (const email of next) {
304
+ if (added.indexOf(email) === -1 && (await env.BUCKET.head(inboxKey(email, key)))) continue;
305
+ await env.BUCKET.put(inboxKey(email, key), '', {
306
+ customMetadata: { owner_email: ownerEmail, owner_name: collabDisplayName({ name: auth.name, email: ownerEmail, userId: auth.owner }), title: title, added_at: addedAt },
307
+ });
308
+ }
309
+ // A generated cover was rendered for the old audience; drop it the way a
310
+ // visibility change does.
311
+ if (added.length || removed.length) {
312
+ const cover = await env.BUCKET.head(key + '.png');
313
+ if (cover && cover.customMetadata && cover.customMetadata['og-generated'] === 'true') await env.BUCKET.delete(key + '.png');
314
+ }
315
+ } finally {
316
+ await releasePathMutationLock(env.BUCKET, key, holder);
317
+ }
318
+
319
+ const body = { people: next, version: version, added: added, removed: removed, notified: [] };
320
+ if (notify && added.length) {
321
+ const outcome = await sendInvites(env, url, key, title, auth, added);
322
+ body.notified = outcome.sent;
323
+ if (outcome.unsent.length) {
324
+ body.notify_error = 'email_unavailable';
325
+ body.notify_failed = outcome.unsent;
326
+ }
327
+ }
328
+ return peopleJson(body, 200);
329
+ }
330
+
331
+ // Email the newly added addresses a link. The owner's name and address are the
332
+ // verified identity's, never anything the request carried. Rush answers
333
+ // {sent, failed (permanent), retryable}; anything not in sent is unsent. A
334
+ // transport failure or 5xx is retried once with the same Idempotency-Key, so
335
+ // Rush never sends a second copy of an invitation it already sent.
336
+ async function sendInvites(env, url, key, title, auth, recipients) {
337
+ const collab = collabConfig(env);
338
+ if (!collab) return { sent: [], unsent: recipients };
339
+ const ownerEmail = String(auth.email || '').toLowerCase();
340
+ const payload = {
341
+ url: url.origin + '/' + key,
342
+ title: title,
343
+ owner_name: collabDisplayName({ name: auth.name, email: ownerEmail, userId: auth.owner }),
344
+ owner_email: ownerEmail,
345
+ recipients: recipients,
346
+ };
347
+ const idempotencyKey = 'invite:' + crypto.randomUUID();
348
+ let result = await collabRegistryCall(collab, 'POST', '/invites', collabShareId(url, key), payload, idempotencyKey);
349
+ if (result.error && (!result.status || result.status >= 500)) {
350
+ result = await collabRegistryCall(collab, 'POST', '/invites', collabShareId(url, key), payload, idempotencyKey);
351
+ }
352
+ const answered = !result.error && result.body && Array.isArray(result.body.sent) ? result.body.sent : [];
353
+ const sent = recipients.filter(function (email) { return answered.indexOf(email) !== -1; });
354
+ return { sent: sent, unsent: recipients.filter(function (email) { return sent.indexOf(email) === -1; }) };
355
+ }
356
+
357
+ async function lookupPerson(env, url, identity) {
358
+ const email = normalizePersonEmail(url.searchParams.get('email') || '');
359
+ if (!email) return peopleJson({ error: 'invalid_email' }, 400);
360
+ const limited = await chargeHourly(env, identity.userId, 'lookup', PEOPLE_LOOKUPS_PER_HOUR, 1);
361
+ if (limited) return limited;
362
+ const names = await lookupPeopleNames(env, [email]);
363
+ const body = describePerson(email, names, identity.email);
364
+ if (names.error) body.names_error = 'names_unavailable';
365
+ return peopleJson(body, 200);
366
+ }
367
+
368
+ // Opaque paging position: the handle being listed and the last key returned.
369
+ function encodePeopleCursor(position) {
370
+ return toB64Url(JSON.stringify(position));
371
+ }
372
+
373
+ function decodePeopleCursor(raw) {
374
+ if (!raw) return { h: '', a: '' };
375
+ try {
376
+ const parsed = JSON.parse(fromB64Url(raw));
377
+ if (parsed && typeof parsed.h === 'string' && typeof parsed.a === 'string') return parsed;
378
+ } catch {
379
+ // not one of ours
380
+ }
381
+ return null;
382
+ }
383
+
384
+ // The handles whose claim the caller holds: the per-user index claimHandle
385
+ // keeps, plus the caller's derived handle for a claim written before the index.
386
+ async function ownedHandles(env, identity) {
387
+ const prefix = handleIndexPrefix(identity.userId);
388
+ const list = await env.BUCKET.list({ prefix: prefix, limit: PEOPLE_MINE_MAX_HANDLES });
389
+ const handles = (list.objects || []).map(function (o) { return o.key.slice(prefix.length); });
390
+ const derived = handleFromEmail(identity.email);
391
+ if (derived && handles.indexOf(derived) === -1 && (await holdsHandleClaim(env.BUCKET, derived, identity.userId))) handles.push(derived);
392
+ return handles.sort();
393
+ }
394
+
395
+ // One page of the live pages under the caller's handles, in key order.
396
+ async function listMine(env, url, identity) {
397
+ const position = decodePeopleCursor(url.searchParams.get('cursor'));
398
+ if (!position) return peopleJson({ error: 'invalid_cursor' }, 400);
399
+ const limited = await chargeHourly(env, identity.userId, 'mine', PEOPLE_MINE_PER_HOUR, 1);
400
+ if (limited) return limited;
401
+ const handles = await ownedHandles(env, identity);
402
+ let index = position.h ? handles.indexOf(position.h) : 0;
403
+ if (index === -1) return peopleJson({ pages: [], next_cursor: null }, 200);
404
+ const handle = handles[index];
405
+ if (!handle) return peopleJson({ pages: [], next_cursor: null }, 200);
406
+ // The delimiter leaves out retained revisions (<handle>/<slug>/rev-*).
407
+ const listing = await env.BUCKET.list({
408
+ prefix: handle + '/', delimiter: '/', limit: PEOPLE_PAGE_SIZE, include: ['httpMetadata', 'customMetadata'],
409
+ ...(position.a ? { startAfter: position.a } : {}),
410
+ });
411
+ const objects = listing.objects || [];
412
+ const last = objects.length ? objects[objects.length - 1].key : '';
413
+ const sidecars = {};
414
+ if (objects.length) {
415
+ const listed = await env.BUCKET.list({ prefix: peopleKey(handle + '/'), limit: 1000, ...(position.a ? { startAfter: peopleKey(position.a) } : {}) });
416
+ for (const sidecar of listed.objects || []) {
417
+ const path = sidecar.key.slice('__people/'.length);
418
+ if (path <= last) sidecars[path] = true;
419
+ }
420
+ }
421
+ const pages = [];
422
+ for (const o of objects) {
423
+ if (o.key.endsWith('.png') || isMediaDerived(o) || isExpiredObject(o)) continue;
424
+ const meta = o.customMetadata || {};
425
+ let people = [];
426
+ if (sidecars[o.key]) {
427
+ try {
428
+ people = await readPeople(env, o.key);
429
+ } catch (error) {
430
+ return accessCheckUnavailable();
431
+ }
432
+ }
433
+ pages.push({
434
+ url: url.origin + '/' + o.key,
435
+ path: o.key,
436
+ title: pageTitle(meta, o.key),
437
+ visibility: meta.visibility || 'public',
438
+ org_domain: meta.org_domain || null,
439
+ kind: pageKind(o.httpMetadata && o.httpMetadata.contentType),
440
+ size: typeof o.size === 'number' ? o.size : 0,
441
+ uploaded: new Date(publishedAtOf(o)).toISOString(),
442
+ people: people,
443
+ });
444
+ }
445
+ let next = null;
446
+ if (listing.truncated && last) next = { h: handle, a: last };
447
+ else if (index + 1 < handles.length) next = { h: handles[index + 1], a: '' };
448
+ return peopleJson({ pages: pages, next_cursor: next ? encodePeopleCursor(next) : null }, 200);
449
+ }
450
+
451
+ // One page of the caller's inbox, keeping only pages they can open because of
452
+ // the list right now: a live me or org page whose list still names them. The
453
+ // inbox is an index, never an authority, so a stale entry is skipped here and
454
+ // left for the owner's next save or the page's delete to clear.
455
+ async function listShared(env, url, identity) {
456
+ const position = decodePeopleCursor(url.searchParams.get('cursor'));
457
+ if (!position) return peopleJson({ error: 'invalid_cursor' }, 400);
458
+ const email = normalizePersonEmail(identity.email || '');
459
+ if (!email) return peopleJson({ pages: [], next_cursor: null }, 200);
460
+ const prefix = inboxKey(email, '');
461
+ const listing = await env.BUCKET.list({ prefix: prefix, limit: PEOPLE_PAGE_SIZE, include: ['customMetadata'], ...(position.a ? { startAfter: prefix + position.a } : {}) });
462
+ const entries = listing.objects || [];
463
+ const pages = [];
464
+ for (const entry of entries) {
465
+ const path = entry.key.slice(prefix.length);
466
+ const page = await env.BUCKET.head(path);
467
+ const pageMeta = (page && page.customMetadata) || {};
468
+ if (!page || isExpiredObject(page) || !isIdentityGated(pageMeta.visibility || 'public')) continue;
469
+ let people;
470
+ try {
471
+ people = await readPeople(env, path);
472
+ } catch (error) {
473
+ return accessCheckUnavailable();
474
+ }
475
+ if (people.indexOf(email) === -1) continue;
476
+ const meta = entry.customMetadata || {};
477
+ pages.push({
478
+ url: url.origin + '/' + path,
479
+ path: path,
480
+ title: pageTitle(pageMeta, path),
481
+ kind: pageKind(page.httpMetadata && page.httpMetadata.contentType),
482
+ owner_email: meta.owner_email || null,
483
+ owner_name: meta.owner_name || null,
484
+ added_at: meta.added_at || null,
485
+ });
486
+ }
487
+ const last = entries.length ? entries[entries.length - 1].key.slice(prefix.length) : '';
488
+ return peopleJson({ pages: pages, next_cursor: listing.truncated && last ? encodePeopleCursor({ h: '', a: last }) : null }, 200);
489
+ }
490
+ `;
491
+ //# sourceMappingURL=worker-people-template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-people-template.js","sourceRoot":"","sources":["../../../src/lib/share/worker-people-template.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,+DAA+D;AAC/D,EAAE;AACF,mFAAmF;AACnF,6EAA6E;AAC7E,+EAA+E;AAC/E,wEAAwE;AACxE,uEAAuE;AACvE,8EAA8E;AAC9E,+EAA+E;AAC/E,sEAAsE;AACtE,EAAE;AACF,0CAA0C;AAC1C,gFAAgF;AAChF,2EAA2E;AAC3E,8EAA8E;AAC9E,4EAA4E;AAC5E,4DAA4D;AAC5D,8EAA8E;AAC9E,wEAAwE;AACxE,EAAE;AACF,2EAA2E;AAC3E,gEAAgE;AAChE,MAAM,CAAC,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkdzC,CAAC"}