@aglyn/plugins-marketplace 1.11.0 → 1.12.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 (81) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/listing-content.component.js +78 -36
  3. package/src/lib/components/listing-content.component.js.map +1 -1
  4. package/src/lib/components/listing-detail-page.component.js +22 -9
  5. package/src/lib/components/listing-detail-page.component.js.map +1 -1
  6. package/src/lib/components/listing-review-status.component.d.ts +8 -0
  7. package/src/lib/components/listing-review-status.component.js +23 -3
  8. package/src/lib/components/listing-review-status.component.js.map +1 -1
  9. package/src/lib/components/listing-verification-request.component.d.ts +8 -0
  10. package/src/lib/components/listing-verification-request.component.js +12 -5
  11. package/src/lib/components/listing-verification-request.component.js.map +1 -1
  12. package/src/lib/components/marketplace-hub.component.js +2 -1
  13. package/src/lib/components/marketplace-hub.component.js.map +1 -1
  14. package/src/lib/components/org-seller-panel.component.d.ts +10 -0
  15. package/src/lib/components/org-seller-panel.component.js +26 -4
  16. package/src/lib/components/org-seller-panel.component.js.map +1 -1
  17. package/src/lib/components/starter-picker-shelf.component.js +13 -8
  18. package/src/lib/components/starter-picker-shelf.component.js.map +1 -1
  19. package/src/lib/declarations.d.ts +2 -1
  20. package/src/lib/declarations.js +5 -1
  21. package/src/lib/declarations.js.map +1 -1
  22. package/src/lib/model/marketplace-publisher-permissions.d.ts +26 -0
  23. package/src/lib/model/marketplace-publisher-permissions.js +64 -0
  24. package/src/lib/model/marketplace-publisher-permissions.js.map +1 -0
  25. package/src/lib/model/marketplace.js +2 -1
  26. package/src/lib/model/marketplace.js.map +1 -1
  27. package/src/lib/model/own-listing.d.ts +52 -0
  28. package/src/lib/model/own-listing.js +72 -0
  29. package/src/lib/model/own-listing.js.map +1 -0
  30. package/src/lib/model/starter-query.js +2 -0
  31. package/src/lib/model/starter-query.js.map +1 -1
  32. package/src/lib/server/connect.js +11 -5
  33. package/src/lib/server/connect.js.map +1 -1
  34. package/src/lib/server/install-dataset-schema.js +10 -2
  35. package/src/lib/server/install-dataset-schema.js.map +1 -1
  36. package/src/lib/server/install-email-starter.js +8 -2
  37. package/src/lib/server/install-email-starter.js.map +1 -1
  38. package/src/lib/server/install-email-template.js +8 -2
  39. package/src/lib/server/install-email-template.js.map +1 -1
  40. package/src/lib/server/install-layout.js +8 -2
  41. package/src/lib/server/install-layout.js.map +1 -1
  42. package/src/lib/server/install-plugin.js +24 -20
  43. package/src/lib/server/install-plugin.js.map +1 -1
  44. package/src/lib/server/install-template.js +8 -5
  45. package/src/lib/server/install-template.js.map +1 -1
  46. package/src/lib/server/install-theme.js +8 -2
  47. package/src/lib/server/install-theme.js.map +1 -1
  48. package/src/lib/server/install.js +10 -5
  49. package/src/lib/server/install.js.map +1 -1
  50. package/src/lib/server/listing-versions.js +24 -9
  51. package/src/lib/server/listing-versions.js.map +1 -1
  52. package/src/lib/server/own-listing.d.ts +46 -0
  53. package/src/lib/server/own-listing.js +52 -0
  54. package/src/lib/server/own-listing.js.map +1 -0
  55. package/src/lib/server/preview-image.d.ts +1 -1
  56. package/src/lib/server/preview-image.js +9 -8
  57. package/src/lib/server/preview-image.js.map +1 -1
  58. package/src/lib/server/publish-plugin.js +17 -19
  59. package/src/lib/server/publish-plugin.js.map +1 -1
  60. package/src/lib/server/publisher-permissions.d.ts +63 -0
  61. package/src/lib/server/publisher-permissions.js +51 -0
  62. package/src/lib/server/publisher-permissions.js.map +1 -0
  63. package/src/lib/server/publisher-profile-save.d.ts +4 -2
  64. package/src/lib/server/publisher-profile-save.js +12 -5
  65. package/src/lib/server/publisher-profile-save.js.map +1 -1
  66. package/src/lib/server/publisher-profile.d.ts +18 -6
  67. package/src/lib/server/publisher-profile.js +19 -8
  68. package/src/lib/server/publisher-profile.js.map +1 -1
  69. package/src/lib/server/reviews.js +6 -5
  70. package/src/lib/server/reviews.js.map +1 -1
  71. package/src/lib/server/sale-risk.d.ts +0 -6
  72. package/src/lib/server/sale-risk.js +0 -9
  73. package/src/lib/server/sale-risk.js.map +1 -1
  74. package/src/lib/server/sale.js +10 -9
  75. package/src/lib/server/sale.js.map +1 -1
  76. package/src/lib/server/site-starter-source.js +43 -17
  77. package/src/lib/server/site-starter-source.js.map +1 -1
  78. package/src/lib/server/update-artifact.js +11 -4
  79. package/src/lib/server/update-artifact.js.map +1 -1
  80. package/src/lib/server/verification-request.js +23 -7
  81. package/src/lib/server/verification-request.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/update-artifact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The leaf module, not the server barrel: the list keys every artifact\n// create stamps (AGL-3321), which the install specs' closed-world barrel\n// mocks have no reason to stage.\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport {\n installedEntryId,\n THEME_LIBRARY_COLLECTION,\n} from '@aglyn/aglyn/app-utils/theme-library'\nimport {\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n newResourceScopeFields,\n type PluginApiHandler,\n type ScopeToken,\n} from '@aglyn/aglyn/server'\nimport {\n applyArtifactUpdate,\n planArtifactUpdate,\n type ArtifactChange,\n type ArtifactUpdatePlan,\n} from '../model/artifact-merge'\nimport { ARTIFACT_BASE_COLLECTION } from '@aglyn/aglyn/app-utils/artifact-provenance'\nimport {\n declaredArtifactTypeOwner,\n type InstalledArtifactCopy,\n} from '@aglyn/aglyn/plugin-manager/plugin-artifact-types'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { listingArtifactType } from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { artifactTypeOwnerOrRefusal, marketplaceInstallStamp } from './artifact-owner'\nimport { recordInstallProvenance } from './provenance'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Updating a COPIED marketplace artifact (AGL-1018).\n *\n * The install routes update by overwriting: a component re-install writes the\n * publisher's tree straight over the workspace's copy, and a template or layout\n * re-install soft-deletes the previous bundle. Both are silent, and both throw\n * away work the customer did after installing.\n *\n * This route never overwrites without saying what will be lost. `preview`\n * classifies every field against AGL-1015's base snapshot and returns the plan;\n * `apply` writes only what the plan (and, for conflicts, the caller) chose.\n * There are two ways to take a new version and both are safe:\n *\n * * **merge** — take the publisher's changes to fields nobody here edited, keep\n * this workspace's edits, and overwrite a contested field only when it was\n * explicitly picked.\n * * **copy** — install the new version fresh and DETACH the customised copy,\n * which keeps it as an ordinary workspace artifact rather than deleting it.\n *\n * Without a base snapshot only `copy` is offered. Inventing an origin to diff\n * against is how a merge becomes confidently wrong.\n *\n * A copy that lives in ANOTHER plugin's storage (a dataset schema's dataset)\n * is found and written by the plugin that keeps its type (AGL-3080), through\n * `plugin-manager/plugin-artifact-types`: this route diffs what the owner\n * hands back and asks it to apply the result, and never reads its collection.\n * Such a copy updates by merge only.\n */\n\ntype Mode = 'merge' | 'copy'\n\n/** What a preview tells the client, and what the dialog renders. */\ninterface UpdatePreview {\n artifactType: string\n installedVersion: string | null\n availableVersion: string | null\n /** A three-way merge is possible: a base snapshot exists and the type supports it. */\n mergeable: boolean\n /** Why not, when it isn't. */\n reason?: string\n safe: ArtifactChange[]\n kept: ArtifactChange[]\n conflicts: ArtifactChange[]\n unchanged: number\n identical: boolean\n}\n\n/** Everything the route needs to diff and write one copied artifact. */\ninterface Target {\n ref: FirebaseFirestore.DocumentReference\n /** The copy as it is now, in the same shape the base snapshot holds. */\n current: unknown\n /** Fields to write alongside merged content. */\n write: (content: any) => Record<string, unknown>\n /** Fields that detach this copy from its listing, for `copy` mode. */\n detach?: Record<string, unknown>\n /**\n * The AGL-1037 scope the FORKED copy is created with, or `null` when the\n * destination collection is not scoped (AGL-1478).\n *\n * Required, and required on purpose. `copy` mode writes a brand-new\n * document into `target.ref.parent` — whatever collection that turns out\n * to be — from a spread of carried fields, and a spread cannot carry a\n * field the source never had. For a scoped collection that is the\n * AGL-1466 bug exactly: an unstamped document is not \"unrestricted\", it is\n * matched by no `array-contains-any` reader in the product, so it renders\n * on no site and is missing from every scoped list even for an org-wide\n * member.\n *\n * Making it optional with a sensible default would have been the smaller\n * diff and is the thing that fails: the two `mediaFolders` creators that\n * each forgot `visibleTo` were both written by people who had the field\n * in front of them. A sixth artifact type cannot be added here without\n * answering this, which is the only guarantee that survives a stranger.\n *\n * `null` is a real answer, not an escape hatch: components live in\n * `hosts/{hostId}/components` and layouts in `hosts/{hostId}/templates`,\n * both private to their host by construction and neither carrying a scope.\n */\n forkScope: readonly ScopeToken[] | null\n /**\n * The declared properties the new version carries (AGL-2933), for a\n * component or layout, sanitized; `undefined` when the version was published\n * before properties were carried, or the type declares none.\n *\n * Not part of the merged content. Every base snapshot recorded before this\n * field existed holds only the tree, so diffing properties three ways would\n * read each installed copy's declarations as a local edit to keep. They are\n * the publisher's contract with the tree instead: whatever the merge takes\n * of the nodes binds to them, so the incoming list replaces the installed\n * one, in both modes.\n */\n props?: ReturnType<typeof readPublishedProps>\n}\n\nconst trimChanges = (changes: ArtifactChange[]): ArtifactChange[] =>\n // The dialog lists changes; a 400-node tree that changed wholesale would\n // otherwise ship its entire content twice through a JSON response.\n changes.slice(0, 200)\n\nexport const updateArtifactHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n const action = req.body?.action === 'apply' ? 'apply' : 'preview'\n const mode: Mode = req.body?.mode === 'copy' ? 'copy' : 'merge'\n const takePaths: string[] = Array.isArray(req.body?.takePaths)\n ? req.body.takePaths.map((path: unknown) => String(path))\n : []\n const confirmDestructive = Boolean(req.body?.confirmDestructive)\n if (!listingId || !hostId) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n // The same gate installing uses: taking a new version of something is\n // installing it, and a role that cannot install must not be able to\n // rewrite an installed artifact through a different door.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error: 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n // Staff takedown blocks new installs on EVERY artifact type\n // (AGL-2290). AGL-948 extended takedown past plugins in the browse\n // predicate and in `resolveMarketplacePluginVersion`, but the gate that\n // decides whether content is HANDED OVER was only ever added to\n // `install-plugin.ts`. So a component, theme, template, layout, email\n // template or dataset schema that staff had taken down stayed\n // installable by anyone holding its listing id — which makes takedown a\n // suggestion for six of the seven artifact types.\n //\n // No owner exemption, matching `install-plugin.ts`: a takedown is a\n // moderation decision about the artifact, not about who is asking.\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId))\n ) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // Taking a NEW version of a paid listing is buying content, and this\n // route never asked whether the caller still owned it (AGL-1699). The\n // install routes gate; this one only checked the org ROLE, so a buyer\n // who was refunded — and even in `copy` mode, which installs the new\n // version fresh — kept pulling every future paid release through here.\n //\n // Deliberately not a regression for anyone legitimate: a live purchase,\n // a free listing, or the publisher's own listing all pass, and nobody\n // without one of those could have had an installed copy to update.\n // The `priceUsd > 0` test is out here rather than left to the helper so\n // a free listing — most of them — does not pay for a publisher lookup.\n const priceUsd = Number(listing.priceUsd ?? 0)\n if (priceUsd > 0) {\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n // THE ORG THE LICENCE HAS TO COVER (AGL-2331). `membership.orgId` is\n // resolved server-side from the caller's own membership by the\n // permission gate above — never a request-body field — so this is the\n // workspace the install actually lands in, and the only one a purchase\n // can entitle here.\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing: await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n ),\n })\n if (unpaid) return res.status(402).json(unpaid)\n }\n\n const artifactType = listingArtifactType(listing)\n if (artifactType === 'plugin') {\n // Plugins are pinned, not copied: an update moves a pointer at immutable\n // bytes (AGL-1017) and has nothing to merge.\n return res.status(400).json({\n error: 'Plugins update by re-pinning — use the install route',\n })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(404).json({ error: 'Listing version missing' })\n }\n const availableVersion =\n listing.latestVersion == null ? null : String(listing.latestVersion)\n\n const orgId = (await getOrgForHost(hostId))?.orgId ?? ''\n\n /** The installed copy, the base it was installed from, and the offer. */\n let target: Target | null = null\n /** A copy another plugin keeps, as its owner found it. */\n let owned: InstalledArtifactCopy | null = null\n let incoming: unknown = null\n let installedVersion: string | null = null\n let baseSha: string | null = null\n let notMergeable: string | undefined\n\n if (artifactType === 'component') {\n const existing = await hostRef\n .collection('components')\n .where('marketplace.listingId', '==', listingId)\n .limit(1)\n .get()\n const doc = existing.docs.find((entry) => !entry.get('deletedAt'))\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const version = versionSnapshot.data() as any\n incoming = { rootId: version.rootId, nodes: version.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('marketplace.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n // Detaching keeps the customised component as an ordinary one: it stays\n // on every page that uses it, and only stops being tracked against the\n // listing — which is what makes \"install as a new copy\" non-destructive\n // without leaving two documents claiming to be the same install.\n detach: {\n marketplace: firebaseAdmin.firestore.FieldValue.delete(),\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/components` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(version.props),\n }\n } else if (artifactType === 'layout') {\n const existing = await hostRef\n .collection('templates')\n .where('source.listingId', '==', listingId)\n .get()\n const doc = existing.docs.find(\n (entry) => !entry.get('deletedAt') && entry.get('kind') === 'layout',\n )\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const layout = versionSnapshot.get('layout') as any\n incoming = { rootId: layout?.rootId, nodes: layout?.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('source.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n detach: {\n // The customer's own from here on: `authored`, the provenance the\n // templates library's Source filter calls \"Saved here\" (AGL-3321).\n source: { type: 'authored' },\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/templates` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(layout?.props),\n }\n } else if (artifactType === 'theme') {\n // A theme lives on the host document itself, so there is no artifact doc\n // to look up and no \"not installed on this site\" — the site either runs\n // this listing's theme or it does not.\n if (hostSnapshot.get('themeInstalledFrom.listingId') !== listingId) {\n return res.status(404).json({ error: 'Not installed on this site' })\n }\n incoming = versionSnapshot.get('theme') ?? {}\n installedVersion =\n String(hostSnapshot.get('themeInstalledFrom.version') ?? '') || null\n baseSha = hostSnapshot.get('themeInstalledFrom.sha256') ?? null\n target = {\n ref: hostRef,\n current: hostSnapshot.get('theme') ?? {},\n write: (content) => ({ theme: content ?? {} }),\n // No `detach`: a site has exactly one theme, so \"install as a separate\n // copy\" has nowhere to put the second one. Merge is the only safe way\n // to take a theme update, and the preview says so.\n //\n // A theme is a FIELD on the host document, so there is no document to\n // scope even if it could fork.\n forkScope: null,\n }\n } else if (artifactType === 'template') {\n // A published template bundle's screens carry no stable identity — only a\n // displayName and a slug — so there is nothing to pair an old screen to a\n // new one by. Any merge would be a guess dressed up as a diff.\n notMergeable =\n 'Template bundles have no stable per-page identity, so their pages ' +\n 'cannot be matched across versions. Installing the new version replaces ' +\n 'this bundle in your Templates library — pages you already created from ' +\n 'the old templates stand on their own and are untouched.'\n } else if (artifactType === 'emailTemplate') {\n // Already safe by construction: an email template installs as an inactive\n // draft version, so taking a new one changes nothing that is being sent.\n notMergeable =\n 'Email templates install as a draft version and never replace what your ' +\n 'site is sending. Add the new version as another draft, then activate ' +\n 'it when you are ready.'\n } else if (declaredArtifactTypeOwner(artifactType)) {\n // A copy another plugin keeps (a dataset schema's dataset): its owner\n // finds it in the site's organization, makes the version on offer this\n // workspace's exactly as an install would, and says what taking it\n // does. With the declared owner missing, the update refuses whole.\n const resolved = await artifactTypeOwnerOrRefusal(artifactType)\n if (resolved.ok === false) {\n return res.status(resolved.status).json({ error: resolved.error })\n }\n const located = await resolved.owner.locate({\n orgId: orgId || null,\n hostId,\n listingId,\n published: versionSnapshot.get(artifactType),\n })\n if (located.ok === false) {\n return res.status(located.status).json({ error: located.error })\n }\n owned = located\n incoming = located.incoming\n installedVersion = located.installedVersion\n baseSha = located.baseSha\n }\n\n if (notMergeable) {\n const preview: UpdatePreview = {\n artifactType,\n installedVersion: null,\n availableVersion,\n mergeable: false,\n reason: notMergeable,\n safe: [],\n kept: [],\n conflicts: [],\n unchanged: 0,\n identical: false,\n }\n return res.status(200).json({ preview })\n }\n const copy: { current: unknown } | null = owned ?? target\n if (!copy) {\n return res.status(404).json({ error: 'Nothing installed to update' })\n }\n\n const baseSnapshot = baseSha\n ? await firestore\n .collection(ARTIFACT_BASE_COLLECTION)\n .doc(baseSha)\n .get()\n .catch(() => null)\n : null\n const base = baseSnapshot?.exists ? baseSnapshot.get('content') : undefined\n const mergeable = base !== undefined\n\n let plan: ArtifactUpdatePlan | null = null\n if (mergeable) plan = planArtifactUpdate(base, copy.current, incoming)\n\n if (action === 'preview') {\n const preview: UpdatePreview & Readonly<Record<string, unknown>> = {\n artifactType,\n installedVersion,\n availableVersion,\n mergeable,\n ...(mergeable\n ? {}\n : {\n reason:\n 'This was installed before update tracking recorded an ' +\n 'original, so there is no way to tell your changes from the ' +\n 'publisher’s. Installing the new version as a separate copy ' +\n 'keeps yours intact.',\n }),\n safe: trimChanges(plan?.safe ?? []),\n kept: trimChanges(plan?.kept ?? []),\n conflicts: trimChanges(plan?.conflicts ?? []),\n unchanged: plan?.unchanged ?? 0,\n identical: plan?.identical ?? false,\n // What the owner of a copy it keeps says taking it does (a dataset's\n // `schema`: the fields it adds, removes and retypes, over how many\n // records), shown as it is.\n ...(owned?.impact?.preview ?? {}),\n }\n return res.status(200).json({ preview })\n }\n\n // ---- apply ----\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n if (mode === 'merge') {\n if (!plan) {\n return res.status(409).json({\n error:\n 'No original snapshot for this install — it can only be taken as a new copy',\n })\n }\n // An update that reinterprets something the copy already holds (a\n // schema change that removes or retypes a field over existing rows) is\n // applicable, but never without the caller having been told what it\n // costs and said yes to it specifically.\n if (owned?.impact?.destructive && !confirmDestructive) {\n return res.status(409).json({\n error: owned.impact.refusal,\n needsConfirmation: true,\n ...owned.impact.preview,\n })\n }\n const merged = applyArtifactUpdate(plan, copy.current, { takePaths })\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n // The base for NEXT time is the publisher's version, not the merged\n // result: the base answers \"what did the publisher ship\", and seeding\n // it with the merge would quietly launder this update's kept edits into\n // the publisher's column, where the next update could take them away.\n content: incoming,\n })\n if (owned) {\n // The owner writes its own copy: the merged content, with the\n // marketplace's stamp.\n await owned.apply({\n content: merged.content,\n stamp: marketplaceInstallStamp({\n installedFrom: provenance.installedFrom,\n listingId,\n version: listing.latestVersion,\n }),\n })\n } else if (target) {\n await target.ref.set(\n {\n ...target.write(merged.content),\n ...(target.props && { props: target.props }),\n // A theme is a FIELD on the host document, not a document of its own,\n // so it namespaces its provenance (`themeInstalledFrom`) and has no\n // legacy `source`/`marketplace` pair — writing those here would put a\n // stray marketplace stamp on the host itself, where `resolveProvenance`\n // would later read it as the host being an installed artifact.\n ...(artifactType === 'theme'\n ? { themeInstalledFrom: provenance.installedFrom }\n : {\n installedFrom: provenance.installedFrom,\n // The legacy per-type version fields the console still reads.\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n }),\n updatedAt: now,\n },\n { merge: true },\n )\n }\n // A merged THEME repaints every page of the site the moment it lands,\n // and nothing publishes it — so the site's cached pages go now rather\n // than within the hour (AGL-3386). Awaited before the response, and it\n // never throws: a failed drop leaves the update applied.\n if (artifactType === 'theme') {\n // The library's copy of this theme moves with it (AGL-3404), or\n // picking it again after switching away would bring back the version\n // this update just replaced.\n const entryRef = hostRef\n .collection(THEME_LIBRARY_COLLECTION)\n .doc(installedEntryId(listingId))\n const entry = await entryRef.get()\n if (entry.exists) {\n await entryRef.update({\n theme: merged.content ?? {},\n installedFrom: provenance.installedFrom,\n updatedAt: now,\n })\n } else {\n await entryRef.set({\n kind: 'installed',\n name: String(listing.displayName ?? '') || 'Marketplace theme',\n theme: merged.content ?? {},\n installedFrom: provenance.installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n }\n await dropPluginSiteCache({\n hostIds: [hostId],\n reason: 'marketplace theme updated',\n })\n }\n // Per-version tally (AGL-1036): this install just moved versions, which\n // is the whole reason the per-version count exists.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n applied: merged.applied.length,\n keptLocal: plan.kept.length,\n skipped: merged.skipped,\n baseStored: provenance.baseStored,\n })\n }\n\n // ---- copy ----\n if (!target?.detach) {\n // Only types with a detachable link get a copy from here. A copy\n // another plugin keeps never does: its \"new copy\" (a dataset schema's\n // is a whole new dataset, which consumes org quota and lands empty) is\n // exactly what the install route already does, with the checks only\n // its owner can make, and this route never writes that plugin's\n // storage. `Target.forkScope` is what keeps the fork below stamped\n // for every type that does reach it.\n return res.status(400).json({\n error:\n artifactType === 'theme'\n ? // A site has one theme, so there is no second place to put a\n // copy. Merging keeps this site's edits; the way back to the\n // previous theme is the install route's `revert`.\n 'A site has only one theme, so this update can only be merged. ' +\n 'Your edits to fields the publisher did not touch are kept.'\n : 'Install a fresh copy of this from the listing instead',\n })\n }\n // The customised copy is detached rather than deleted or overwritten: it\n // keeps working everywhere it is used, and only stops being the document\n // this listing updates. Without the detach two documents would claim the\n // same install and the next update would pick between them arbitrarily.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n content: incoming,\n })\n const batch = firestore.batch()\n if (target.detach) {\n batch.set(target.ref, { ...target.detach, updatedAt: now }, { merge: true })\n }\n const collectionRef = target.ref.parent\n const freshRef = collectionRef.doc(createResourceUid())\n const carried = (await target.ref.get()).data() ?? {}\n const freshName = String(listing.displayName ?? carried.displayName ?? 'Untitled')\n batch.set(freshRef, {\n // Everything that is not content travels from the copy being replaced —\n // the display name, description and kind — so the new one lands in the\n // same place in the same library rather than as an unrecognisable stub.\n ...(carried.kind ? { kind: carried.kind } : {}),\n displayName: freshName,\n ...(listing.description ? { description: listing.description } : {}),\n // Not part of the `carried` spread above, deliberately: a spread\n // cannot carry a field the source is missing, and \"the source had one\"\n // is not the question a scoped collection asks. `Target.forkScope`\n // makes every artifact type answer it (AGL-1478), and this throws\n // rather than storing a scope nobody can see through.\n ...newResourceScopeFields(target.forkScope),\n ...target.write(incoming),\n ...(target.props\n ? { props: target.props }\n : Array.isArray(carried.props)\n ? { props: carried.props }\n : {}),\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n installedFrom: provenance.installedFrom,\n deletedAt: null,\n // The keys the fresh copy's list finds it by (AGL-3321), for whichever\n // artifact collection it lands in.\n ...artifactCreateListKeys(collectionRef.id, {\n kind: carried.kind,\n displayName: freshName,\n // The description written above, so the stored-null default\n // (AGL-3680) never overwrites it.\n description: listing.description || null,\n source: { type: 'marketplace' },\n }),\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n // Per-version tally (AGL-1036). Still a move, not a second install: the\n // detached copy stops being tracked against the listing, so the version it\n // held is genuinely vacated.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n newId: freshRef.id,\n detached: Boolean(target.detach),\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Update failed' })\n }\n}\n\nexport default updateArtifactHandler\n"],"names":["artifactCreateListKeys","installedEntryId","THEME_LIBRARY_COLLECTION","createResourceUid","decodeStoredNodes","encodeStoredNodes","newResourceScopeFields","applyArtifactUpdate","planArtifactUpdate","ARTIFACT_BASE_COLLECTION","declaredArtifactTypeOwner","dropPluginSiteCache","firebaseAdmin","getOrgForHost","resolveOrgPermissions","listingArtifactType","readPublishedProps","artifactTypeOwnerOrRefusal","marketplaceInstallStamp","recordInstallProvenance","canActAsPublisher","requirePurchase","recordVersionMove","isPublisherSecurityLocked","trimChanges","changes","slice","updateArtifactHandler","req","res","method","status","json","error","listingId","String","body","hostId","action","mode","takePaths","Array","isArray","map","path","confirmDestructive","Boolean","authorization","headers","idToken","startsWith","length","undefined","listing","decoded","app","auth","verifyIdToken","membership","uid","permissions","installPlugins","firestore","hostRef","collection","doc","hostSnapshot","get","exists","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","ownsListing","artifactType","versionSnapshot","latestVersion","availableVersion","target","owned","incoming","installedVersion","baseSha","notMergeable","existing","where","limit","docs","find","entry","version","rootId","nodes","ref","current","write","content","Buffer","from","detach","marketplace","FieldValue","delete","detachedFrom","forkScope","props","layout","source","type","theme","resolved","ok","located","owner","locate","published","preview","mergeable","reason","safe","kept","conflicts","unchanged","identical","copy","baseSnapshot","catch","base","plan","impact","now","serverTimestamp","destructive","refusal","needsConfirmation","merged","provenance","apply","stamp","installedFrom","set","themeInstalledFrom","updatedAt","merge","entryRef","update","kind","name","displayName","createdAt","hostIds","to","updated","applied","keptLocal","skipped","baseStored","batch","collectionRef","parent","freshRef","carried","freshName","description","id","commit","newId","detached","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SACEC,gBAAgB,EAChBC,wBAAwB,QACnB,uCAAsC;AAC7C,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,iBAAiB,EACjBC,sBAAsB,QAGjB,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,kBAAkB,QAGb,6BAAyB;AAChC,SAASC,wBAAwB,QAAQ,6CAA4C;AACrF,SACEC,yBAAyB,QAEpB,oDAAmD;AAC1D,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,kBAAkB,QAAQ,gCAA4B;AAC/D,SAASC,0BAA0B,EAAEC,uBAAuB,QAAQ,sBAAkB;AACtF,SAASC,uBAAuB,QAAQ,kBAAc;AACtD,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,yBAAyB,QAAQ,iBAAa;AAiGvD,MAAMC,cAAc,CAACC,UACnB,yEAAyE;IACzE,mEAAmE;IACnEA,QAAQC,KAAK,CAAC,GAAG;AAEnB,OAAO,MAAMC,wBAA0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+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/update-artifact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The leaf module, not the server barrel: the list keys every artifact\n// create stamps (AGL-3321), which the install specs' closed-world barrel\n// mocks have no reason to stage.\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport {\n installedEntryId,\n THEME_LIBRARY_COLLECTION,\n} from '@aglyn/aglyn/app-utils/theme-library'\nimport {\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n newResourceScopeFields,\n type PluginApiHandler,\n type ScopeToken,\n} from '@aglyn/aglyn/server'\nimport {\n applyArtifactUpdate,\n planArtifactUpdate,\n type ArtifactChange,\n type ArtifactUpdatePlan,\n} from '../model/artifact-merge'\nimport { ARTIFACT_BASE_COLLECTION } from '@aglyn/aglyn/app-utils/artifact-provenance'\nimport {\n declaredArtifactTypeOwner,\n type InstalledArtifactCopy,\n} from '@aglyn/aglyn/plugin-manager/plugin-artifact-types'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { listingArtifactType } from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { artifactTypeOwnerOrRefusal, marketplaceInstallStamp } from './artifact-owner'\nimport { recordInstallProvenance } from './provenance'\nimport { ownsListingHere } from './own-listing'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Updating a COPIED marketplace artifact (AGL-1018).\n *\n * The install routes update by overwriting: a component re-install writes the\n * publisher's tree straight over the workspace's copy, and a template or layout\n * re-install soft-deletes the previous bundle. Both are silent, and both throw\n * away work the customer did after installing.\n *\n * This route never overwrites without saying what will be lost. `preview`\n * classifies every field against AGL-1015's base snapshot and returns the plan;\n * `apply` writes only what the plan (and, for conflicts, the caller) chose.\n * There are two ways to take a new version and both are safe:\n *\n * * **merge** — take the publisher's changes to fields nobody here edited, keep\n * this workspace's edits, and overwrite a contested field only when it was\n * explicitly picked.\n * * **copy** — install the new version fresh and DETACH the customised copy,\n * which keeps it as an ordinary workspace artifact rather than deleting it.\n *\n * Without a base snapshot only `copy` is offered. Inventing an origin to diff\n * against is how a merge becomes confidently wrong.\n *\n * A copy that lives in ANOTHER plugin's storage (a dataset schema's dataset)\n * is found and written by the plugin that keeps its type (AGL-3080), through\n * `plugin-manager/plugin-artifact-types`: this route diffs what the owner\n * hands back and asks it to apply the result, and never reads its collection.\n * Such a copy updates by merge only.\n */\n\ntype Mode = 'merge' | 'copy'\n\n/** What a preview tells the client, and what the dialog renders. */\ninterface UpdatePreview {\n artifactType: string\n installedVersion: string | null\n availableVersion: string | null\n /** A three-way merge is possible: a base snapshot exists and the type supports it. */\n mergeable: boolean\n /** Why not, when it isn't. */\n reason?: string\n safe: ArtifactChange[]\n kept: ArtifactChange[]\n conflicts: ArtifactChange[]\n unchanged: number\n identical: boolean\n}\n\n/** Everything the route needs to diff and write one copied artifact. */\ninterface Target {\n ref: FirebaseFirestore.DocumentReference\n /** The copy as it is now, in the same shape the base snapshot holds. */\n current: unknown\n /** Fields to write alongside merged content. */\n write: (content: any) => Record<string, unknown>\n /** Fields that detach this copy from its listing, for `copy` mode. */\n detach?: Record<string, unknown>\n /**\n * The AGL-1037 scope the FORKED copy is created with, or `null` when the\n * destination collection is not scoped (AGL-1478).\n *\n * Required, and required on purpose. `copy` mode writes a brand-new\n * document into `target.ref.parent` — whatever collection that turns out\n * to be — from a spread of carried fields, and a spread cannot carry a\n * field the source never had. For a scoped collection that is the\n * AGL-1466 bug exactly: an unstamped document is not \"unrestricted\", it is\n * matched by no `array-contains-any` reader in the product, so it renders\n * on no site and is missing from every scoped list even for an org-wide\n * member.\n *\n * Making it optional with a sensible default would have been the smaller\n * diff and is the thing that fails: the two `mediaFolders` creators that\n * each forgot `visibleTo` were both written by people who had the field\n * in front of them. A sixth artifact type cannot be added here without\n * answering this, which is the only guarantee that survives a stranger.\n *\n * `null` is a real answer, not an escape hatch: components live in\n * `hosts/{hostId}/components` and layouts in `hosts/{hostId}/templates`,\n * both private to their host by construction and neither carrying a scope.\n */\n forkScope: readonly ScopeToken[] | null\n /**\n * The declared properties the new version carries (AGL-2933), for a\n * component or layout, sanitized; `undefined` when the version was published\n * before properties were carried, or the type declares none.\n *\n * Not part of the merged content. Every base snapshot recorded before this\n * field existed holds only the tree, so diffing properties three ways would\n * read each installed copy's declarations as a local edit to keep. They are\n * the publisher's contract with the tree instead: whatever the merge takes\n * of the nodes binds to them, so the incoming list replaces the installed\n * one, in both modes.\n */\n props?: ReturnType<typeof readPublishedProps>\n}\n\nconst trimChanges = (changes: ArtifactChange[]): ArtifactChange[] =>\n // The dialog lists changes; a 400-node tree that changed wholesale would\n // otherwise ship its entire content twice through a JSON response.\n changes.slice(0, 200)\n\nexport const updateArtifactHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n const action = req.body?.action === 'apply' ? 'apply' : 'preview'\n const mode: Mode = req.body?.mode === 'copy' ? 'copy' : 'merge'\n const takePaths: string[] = Array.isArray(req.body?.takePaths)\n ? req.body.takePaths.map((path: unknown) => String(path))\n : []\n const confirmDestructive = Boolean(req.body?.confirmDestructive)\n if (!listingId || !hostId) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n // The same gate installing uses: taking a new version of something is\n // installing it, and a role that cannot install must not be able to\n // rewrite an installed artifact through a different door.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error: 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n // Staff takedown blocks new installs on EVERY artifact type\n // (AGL-2290). AGL-948 extended takedown past plugins in the browse\n // predicate and in `resolveMarketplacePluginVersion`, but the gate that\n // decides whether content is HANDED OVER was only ever added to\n // `install-plugin.ts`. So a component, theme, template, layout, email\n // template or dataset schema that staff had taken down stayed\n // installable by anyone holding its listing id — which makes takedown a\n // suggestion for six of the seven artifact types.\n //\n // No owner exemption, matching `install-plugin.ts`: a takedown is a\n // moderation decision about the artifact, not about who is asking.\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId))\n ) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // Taking a NEW version of a paid listing is buying content, and this\n // route never asked whether the caller still owned it (AGL-1699). The\n // install routes gate; this one only checked the org ROLE, so a buyer\n // who was refunded — and even in `copy` mode, which installs the new\n // version fresh — kept pulling every future paid release through here.\n //\n // Deliberately not a regression for anyone legitimate: a live purchase,\n // a free listing, or the publisher's own listing on the publisher's own\n // site all pass, and nobody without one of those could have had an\n // installed copy to update. A publisher's member taking a new version on\n // ANOTHER workspace's site needs that workspace's licence, as installing\n // it there does (AGL-2484, AGL-4047).\n // The `priceUsd > 0` test is out here rather than left to the helper so\n // a free listing — most of them — does not pay for a publisher lookup.\n const priceUsd = Number(listing.priceUsd ?? 0)\n if (priceUsd > 0) {\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n // THE ORG THE LICENCE HAS TO COVER (AGL-2331). `membership.orgId` is\n // resolved server-side from the caller's own membership by the\n // permission gate above — never a request-body field — so this is the\n // workspace the install actually lands in, and the only one a purchase\n // can entitle here.\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing: await ownsListingHere(firestore, {\n uid: decoded.uid,\n publisherOrgId: listing.profileId,\n targetOrgId: membership.orgId,\n }),\n })\n if (unpaid) return res.status(402).json(unpaid)\n }\n\n const artifactType = listingArtifactType(listing)\n if (artifactType === 'plugin') {\n // Plugins are pinned, not copied: an update moves a pointer at immutable\n // bytes (AGL-1017) and has nothing to merge.\n return res.status(400).json({\n error: 'Plugins update by re-pinning — use the install route',\n })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(404).json({ error: 'Listing version missing' })\n }\n const availableVersion =\n listing.latestVersion == null ? null : String(listing.latestVersion)\n\n const orgId = (await getOrgForHost(hostId))?.orgId ?? ''\n\n /** The installed copy, the base it was installed from, and the offer. */\n let target: Target | null = null\n /** A copy another plugin keeps, as its owner found it. */\n let owned: InstalledArtifactCopy | null = null\n let incoming: unknown = null\n let installedVersion: string | null = null\n let baseSha: string | null = null\n let notMergeable: string | undefined\n\n if (artifactType === 'component') {\n const existing = await hostRef\n .collection('components')\n .where('marketplace.listingId', '==', listingId)\n .limit(1)\n .get()\n const doc = existing.docs.find((entry) => !entry.get('deletedAt'))\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const version = versionSnapshot.data() as any\n incoming = { rootId: version.rootId, nodes: version.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('marketplace.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n // Detaching keeps the customised component as an ordinary one: it stays\n // on every page that uses it, and only stops being tracked against the\n // listing — which is what makes \"install as a new copy\" non-destructive\n // without leaving two documents claiming to be the same install.\n detach: {\n marketplace: firebaseAdmin.firestore.FieldValue.delete(),\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/components` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(version.props),\n }\n } else if (artifactType === 'layout') {\n const existing = await hostRef\n .collection('templates')\n .where('source.listingId', '==', listingId)\n .get()\n const doc = existing.docs.find(\n (entry) => !entry.get('deletedAt') && entry.get('kind') === 'layout',\n )\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const layout = versionSnapshot.get('layout') as any\n incoming = { rootId: layout?.rootId, nodes: layout?.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('source.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n detach: {\n // The customer's own from here on: `authored`, the provenance the\n // templates library's Source filter calls \"Saved here\" (AGL-3321).\n source: { type: 'authored' },\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/templates` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(layout?.props),\n }\n } else if (artifactType === 'theme') {\n // A theme lives on the host document itself, so there is no artifact doc\n // to look up and no \"not installed on this site\" — the site either runs\n // this listing's theme or it does not.\n if (hostSnapshot.get('themeInstalledFrom.listingId') !== listingId) {\n return res.status(404).json({ error: 'Not installed on this site' })\n }\n incoming = versionSnapshot.get('theme') ?? {}\n installedVersion =\n String(hostSnapshot.get('themeInstalledFrom.version') ?? '') || null\n baseSha = hostSnapshot.get('themeInstalledFrom.sha256') ?? null\n target = {\n ref: hostRef,\n current: hostSnapshot.get('theme') ?? {},\n write: (content) => ({ theme: content ?? {} }),\n // No `detach`: a site has exactly one theme, so \"install as a separate\n // copy\" has nowhere to put the second one. Merge is the only safe way\n // to take a theme update, and the preview says so.\n //\n // A theme is a FIELD on the host document, so there is no document to\n // scope even if it could fork.\n forkScope: null,\n }\n } else if (artifactType === 'template') {\n // A published template bundle's screens carry no stable identity — only a\n // displayName and a slug — so there is nothing to pair an old screen to a\n // new one by. Any merge would be a guess dressed up as a diff.\n notMergeable =\n 'Template bundles have no stable per-page identity, so their pages ' +\n 'cannot be matched across versions. Installing the new version replaces ' +\n 'this bundle in your Templates library — pages you already created from ' +\n 'the old templates stand on their own and are untouched.'\n } else if (artifactType === 'emailTemplate') {\n // Already safe by construction: an email template installs as an inactive\n // draft version, so taking a new one changes nothing that is being sent.\n notMergeable =\n 'Email templates install as a draft version and never replace what your ' +\n 'site is sending. Add the new version as another draft, then activate ' +\n 'it when you are ready.'\n } else if (declaredArtifactTypeOwner(artifactType)) {\n // A copy another plugin keeps (a dataset schema's dataset): its owner\n // finds it in the site's organization, makes the version on offer this\n // workspace's exactly as an install would, and says what taking it\n // does. With the declared owner missing, the update refuses whole.\n const resolved = await artifactTypeOwnerOrRefusal(artifactType)\n if (resolved.ok === false) {\n return res.status(resolved.status).json({ error: resolved.error })\n }\n const located = await resolved.owner.locate({\n orgId: orgId || null,\n hostId,\n listingId,\n published: versionSnapshot.get(artifactType),\n })\n if (located.ok === false) {\n return res.status(located.status).json({ error: located.error })\n }\n owned = located\n incoming = located.incoming\n installedVersion = located.installedVersion\n baseSha = located.baseSha\n }\n\n if (notMergeable) {\n const preview: UpdatePreview = {\n artifactType,\n installedVersion: null,\n availableVersion,\n mergeable: false,\n reason: notMergeable,\n safe: [],\n kept: [],\n conflicts: [],\n unchanged: 0,\n identical: false,\n }\n return res.status(200).json({ preview })\n }\n const copy: { current: unknown } | null = owned ?? target\n if (!copy) {\n return res.status(404).json({ error: 'Nothing installed to update' })\n }\n\n const baseSnapshot = baseSha\n ? await firestore\n .collection(ARTIFACT_BASE_COLLECTION)\n .doc(baseSha)\n .get()\n .catch(() => null)\n : null\n const base = baseSnapshot?.exists ? baseSnapshot.get('content') : undefined\n const mergeable = base !== undefined\n\n let plan: ArtifactUpdatePlan | null = null\n if (mergeable) plan = planArtifactUpdate(base, copy.current, incoming)\n\n if (action === 'preview') {\n const preview: UpdatePreview & Readonly<Record<string, unknown>> = {\n artifactType,\n installedVersion,\n availableVersion,\n mergeable,\n ...(mergeable\n ? {}\n : {\n reason:\n 'This was installed before update tracking recorded an ' +\n 'original, so there is no way to tell your changes from the ' +\n 'publisher’s. Installing the new version as a separate copy ' +\n 'keeps yours intact.',\n }),\n safe: trimChanges(plan?.safe ?? []),\n kept: trimChanges(plan?.kept ?? []),\n conflicts: trimChanges(plan?.conflicts ?? []),\n unchanged: plan?.unchanged ?? 0,\n identical: plan?.identical ?? false,\n // What the owner of a copy it keeps says taking it does (a dataset's\n // `schema`: the fields it adds, removes and retypes, over how many\n // records), shown as it is.\n ...(owned?.impact?.preview ?? {}),\n }\n return res.status(200).json({ preview })\n }\n\n // ---- apply ----\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n if (mode === 'merge') {\n if (!plan) {\n return res.status(409).json({\n error:\n 'No original snapshot for this install — it can only be taken as a new copy',\n })\n }\n // An update that reinterprets something the copy already holds (a\n // schema change that removes or retypes a field over existing rows) is\n // applicable, but never without the caller having been told what it\n // costs and said yes to it specifically.\n if (owned?.impact?.destructive && !confirmDestructive) {\n return res.status(409).json({\n error: owned.impact.refusal,\n needsConfirmation: true,\n ...owned.impact.preview,\n })\n }\n const merged = applyArtifactUpdate(plan, copy.current, { takePaths })\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n // The base for NEXT time is the publisher's version, not the merged\n // result: the base answers \"what did the publisher ship\", and seeding\n // it with the merge would quietly launder this update's kept edits into\n // the publisher's column, where the next update could take them away.\n content: incoming,\n })\n if (owned) {\n // The owner writes its own copy: the merged content, with the\n // marketplace's stamp.\n await owned.apply({\n content: merged.content,\n stamp: marketplaceInstallStamp({\n installedFrom: provenance.installedFrom,\n listingId,\n version: listing.latestVersion,\n }),\n })\n } else if (target) {\n await target.ref.set(\n {\n ...target.write(merged.content),\n ...(target.props && { props: target.props }),\n // A theme is a FIELD on the host document, not a document of its own,\n // so it namespaces its provenance (`themeInstalledFrom`) and has no\n // legacy `source`/`marketplace` pair — writing those here would put a\n // stray marketplace stamp on the host itself, where `resolveProvenance`\n // would later read it as the host being an installed artifact.\n ...(artifactType === 'theme'\n ? { themeInstalledFrom: provenance.installedFrom }\n : {\n installedFrom: provenance.installedFrom,\n // The legacy per-type version fields the console still reads.\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n }),\n updatedAt: now,\n },\n { merge: true },\n )\n }\n // A merged THEME repaints every page of the site the moment it lands,\n // and nothing publishes it — so the site's cached pages go now rather\n // than within the hour (AGL-3386). Awaited before the response, and it\n // never throws: a failed drop leaves the update applied.\n if (artifactType === 'theme') {\n // The library's copy of this theme moves with it (AGL-3404), or\n // picking it again after switching away would bring back the version\n // this update just replaced.\n const entryRef = hostRef\n .collection(THEME_LIBRARY_COLLECTION)\n .doc(installedEntryId(listingId))\n const entry = await entryRef.get()\n if (entry.exists) {\n await entryRef.update({\n theme: merged.content ?? {},\n installedFrom: provenance.installedFrom,\n updatedAt: now,\n })\n } else {\n await entryRef.set({\n kind: 'installed',\n name: String(listing.displayName ?? '') || 'Marketplace theme',\n theme: merged.content ?? {},\n installedFrom: provenance.installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n }\n await dropPluginSiteCache({\n hostIds: [hostId],\n reason: 'marketplace theme updated',\n })\n }\n // Per-version tally (AGL-1036): this install just moved versions, which\n // is the whole reason the per-version count exists.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n applied: merged.applied.length,\n keptLocal: plan.kept.length,\n skipped: merged.skipped,\n baseStored: provenance.baseStored,\n })\n }\n\n // ---- copy ----\n if (!target?.detach) {\n // Only types with a detachable link get a copy from here. A copy\n // another plugin keeps never does: its \"new copy\" (a dataset schema's\n // is a whole new dataset, which consumes org quota and lands empty) is\n // exactly what the install route already does, with the checks only\n // its owner can make, and this route never writes that plugin's\n // storage. `Target.forkScope` is what keeps the fork below stamped\n // for every type that does reach it.\n return res.status(400).json({\n error:\n artifactType === 'theme'\n ? // A site has one theme, so there is no second place to put a\n // copy. Merging keeps this site's edits; the way back to the\n // previous theme is the install route's `revert`.\n 'A site has only one theme, so this update can only be merged. ' +\n 'Your edits to fields the publisher did not touch are kept.'\n : 'Install a fresh copy of this from the listing instead',\n })\n }\n // The customised copy is detached rather than deleted or overwritten: it\n // keeps working everywhere it is used, and only stops being the document\n // this listing updates. Without the detach two documents would claim the\n // same install and the next update would pick between them arbitrarily.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n content: incoming,\n })\n const batch = firestore.batch()\n if (target.detach) {\n batch.set(target.ref, { ...target.detach, updatedAt: now }, { merge: true })\n }\n const collectionRef = target.ref.parent\n const freshRef = collectionRef.doc(createResourceUid())\n const carried = (await target.ref.get()).data() ?? {}\n const freshName = String(listing.displayName ?? carried.displayName ?? 'Untitled')\n batch.set(freshRef, {\n // Everything that is not content travels from the copy being replaced —\n // the display name, description and kind — so the new one lands in the\n // same place in the same library rather than as an unrecognisable stub.\n ...(carried.kind ? { kind: carried.kind } : {}),\n displayName: freshName,\n ...(listing.description ? { description: listing.description } : {}),\n // Not part of the `carried` spread above, deliberately: a spread\n // cannot carry a field the source is missing, and \"the source had one\"\n // is not the question a scoped collection asks. `Target.forkScope`\n // makes every artifact type answer it (AGL-1478), and this throws\n // rather than storing a scope nobody can see through.\n ...newResourceScopeFields(target.forkScope),\n ...target.write(incoming),\n ...(target.props\n ? { props: target.props }\n : Array.isArray(carried.props)\n ? { props: carried.props }\n : {}),\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n installedFrom: provenance.installedFrom,\n deletedAt: null,\n // The keys the fresh copy's list finds it by (AGL-3321), for whichever\n // artifact collection it lands in.\n ...artifactCreateListKeys(collectionRef.id, {\n kind: carried.kind,\n displayName: freshName,\n // The description written above, so the stored-null default\n // (AGL-3680) never overwrites it.\n description: listing.description || null,\n source: { type: 'marketplace' },\n }),\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n // Per-version tally (AGL-1036). Still a move, not a second install: the\n // detached copy stops being tracked against the listing, so the version it\n // held is genuinely vacated.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n newId: freshRef.id,\n detached: Boolean(target.detach),\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Update failed' })\n }\n}\n\nexport default updateArtifactHandler\n"],"names":["artifactCreateListKeys","installedEntryId","THEME_LIBRARY_COLLECTION","createResourceUid","decodeStoredNodes","encodeStoredNodes","newResourceScopeFields","applyArtifactUpdate","planArtifactUpdate","ARTIFACT_BASE_COLLECTION","declaredArtifactTypeOwner","dropPluginSiteCache","firebaseAdmin","getOrgForHost","resolveOrgPermissions","listingArtifactType","readPublishedProps","artifactTypeOwnerOrRefusal","marketplaceInstallStamp","recordInstallProvenance","ownsListingHere","requirePurchase","recordVersionMove","isPublisherSecurityLocked","trimChanges","changes","slice","updateArtifactHandler","req","res","method","status","json","error","listingId","String","body","hostId","action","mode","takePaths","Array","isArray","map","path","confirmDestructive","Boolean","authorization","headers","idToken","startsWith","length","undefined","listing","decoded","app","auth","verifyIdToken","membership","uid","permissions","installPlugins","firestore","hostRef","collection","doc","hostSnapshot","get","exists","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","ownsListing","publisherOrgId","targetOrgId","artifactType","versionSnapshot","latestVersion","availableVersion","target","owned","incoming","installedVersion","baseSha","notMergeable","existing","where","limit","docs","find","entry","version","rootId","nodes","ref","current","write","content","Buffer","from","detach","marketplace","FieldValue","delete","detachedFrom","forkScope","props","layout","source","type","theme","resolved","ok","located","owner","locate","published","preview","mergeable","reason","safe","kept","conflicts","unchanged","identical","copy","baseSnapshot","catch","base","plan","impact","now","serverTimestamp","destructive","refusal","needsConfirmation","merged","provenance","apply","stamp","installedFrom","set","themeInstalledFrom","updatedAt","merge","entryRef","update","kind","name","displayName","createdAt","hostIds","to","updated","applied","keptLocal","skipped","baseStored","batch","collectionRef","parent","freshRef","carried","freshName","description","id","commit","newId","detached","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SACEC,gBAAgB,EAChBC,wBAAwB,QACnB,uCAAsC;AAC7C,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,iBAAiB,EACjBC,sBAAsB,QAGjB,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,kBAAkB,QAGb,6BAAyB;AAChC,SAASC,wBAAwB,QAAQ,6CAA4C;AACrF,SACEC,yBAAyB,QAEpB,oDAAmD;AAC1D,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,kBAAkB,QAAQ,gCAA4B;AAC/D,SAASC,0BAA0B,EAAEC,uBAAuB,QAAQ,sBAAkB;AACtF,SAASC,uBAAuB,QAAQ,kBAAc;AACtD,SAASC,eAAe,QAAQ,mBAAe;AAC/C,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,yBAAyB,QAAQ,iBAAa;AAiGvD,MAAMC,cAAc,CAACC,UACnB,yEAAyE;IACzE,mEAAmE;IACnEA,QAAQC,KAAK,CAAC,GAAG;AAEnB,OAAO,MAAMC,wBAA0C,OAAOC,KAAKC;qBAepCD;QAXJA,WACHA,YACPA,YACIA,YACuBA,YAGPA;IAVnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;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edIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
19
19
  import { FieldValue } from "firebase-admin/firestore";
20
20
  import { VERIFICATION_BLOCK_MESSAGES, verificationRequestBlock } from "../model/marketplace.js";
21
- import { canActAsPublisher } from "./publisher-profile.js";
21
+ import { MARKETPLACE_PUBLISHER_PROFILE_PERMISSION, marketplacePublisherPermissionRefusal } from "../model/marketplace-publisher-permissions.js";
22
+ import { publisherPermissionVerdict } from "./publisher-permissions.js";
22
23
  import { recordPublisherAgreementAcceptance } from "./publisher-agreement-acceptance.js";
23
24
  import { publisherAgreementConsentRefusal } from "../model/publisher-agreement.js";
24
25
  /**
@@ -81,17 +82,32 @@ import { publisherAgreementConsentRefusal } from "../model/publisher-agreement.j
81
82
  if (!listing) return res.status(404).json({
82
83
  error: 'Unknown listing'
83
84
  });
84
- // Membership of the PUBLISHING org, resolved from the listing rather than
85
- // from anything the caller sent. A client-supplied orgId here would let a
86
- // publisher of one listing act on another.
85
+ // The PUBLISHING org, resolved from the listing rather than from anything
86
+ // the caller sent. A client-supplied orgId here would let a publisher of
87
+ // one listing act on another.
88
+ //
89
+ // Asking for the badge is a claim about the publisher, so it asks "Edit
90
+ // the publisher profile" (`marketplace.publisherProfile`, AGL-4047) of a
91
+ // member of that org. Its default is the owner and admins this asked for
92
+ // by role before, so nobody's access moved.
87
93
  const publisherOrgId = String((_listing_profileId = listing.profileId) != null ? _listing_profileId : '');
88
- if (!publisherOrgId || !await canActAsPublisher(firestore, decoded.uid, publisherOrgId)) {
94
+ const verdict = await publisherPermissionVerdict(decoded.uid, publisherOrgId, MARKETPLACE_PUBLISHER_PROFILE_PERMISSION);
95
+ if (verdict === 'not-a-member') {
89
96
  // 404, not 403: a listing the caller does not publish should not be
90
97
  // confirmed to exist by the shape of the refusal.
91
98
  return res.status(404).json({
92
99
  error: 'Unknown listing'
93
100
  });
94
101
  }
102
+ if (verdict === 'refused') {
103
+ // A member already sees the listing in their own workspace, so the
104
+ // refusal names the permission they are missing.
105
+ return res.status(403).json({
106
+ error: marketplacePublisherPermissionRefusal(MARKETPLACE_PUBLISHER_PROFILE_PERMISSION),
107
+ reason: 'permission',
108
+ permission: MARKETPLACE_PUBLISHER_PROFILE_PERMISSION
109
+ });
110
+ }
95
111
  // The agreement this save was sent with, recorded before it writes
96
112
  // (AGL-4105).
97
113
  await recordPublisherAgreementAcceptance({
@@ -140,8 +156,8 @@ import { publisherAgreementConsentRefusal } from "../model/publisher-agreement.j
140
156
  };
141
157
  // `viewerOrgId` is fed the listing's own `profileId` on purpose, which
142
158
  // makes the `not-publisher` branch unreachable here. That is NOT the
143
- // authorization check — `canActAsPublisher` above is, and it ran against
144
- // the caller's uid. This call is asking the remaining question: is the
159
+ // authorization check — the permission verdict above is, and it ran
160
+ // against the caller's uid. This call is asking the remaining question: is the
145
161
  // listing in a state that can carry a request right now.
146
162
  const blocked = verificationRequestBlock({
147
163
  listing: fresh,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/verification-request.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n VERIFICATION_BLOCK_MESSAGES,\n verificationRequestBlock,\n} from '../model/marketplace'\nimport { canActAsPublisher } from './publisher-profile'\nimport { recordPublisherAgreementAcceptance } from './publisher-agreement-acceptance'\nimport { publisherAgreementConsentRefusal } from '../model/publisher-agreement'\nimport type { DecodedIdToken } from 'firebase-admin/auth'\n\n/**\n * A publisher asking for — or taking back — the Verified badge (AGL-1217).\n *\n * Asking grants nothing. This route only ever moves the request between\n * `pending` and `withdrawn`; the checklist gate on the staff `verify` action\n * stays the single route to the badge itself. That separation is the whole\n * safety property here, because this endpoint is reachable by any publisher.\n *\n * Eligibility is decided by `verificationRequestBlock`, the same function the\n * button calls. Sharing it is the point: a client-side rule the server does\n * not enforce is decoration, and a server rule the client does not know\n * produces a button that fails with no explanation.\n */\nexport const verificationRequestHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const listingId = String(req.body?.listingId ?? '').trim()\n const action = String(req.body?.action ?? 'request')\n if (!listingId) return res.status(400).json({ error: 'Missing listingId' })\n if (action !== 'request' && action !== 'withdraw') {\n return res.status(400).json({ error: 'Unknown action' })\n }\n // The publisher agreement, agreed to on this save (AGL-4105): asking for\n // the badge, and taking the ask back, are publisher saves like any other.\n const agreementRefusal = publisherAgreementConsentRefusal(req.body?.agreement)\n if (agreementRefusal) {\n return res.status(agreementRefusal.status).json(agreementRefusal.body)\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n let decoded: DecodedIdToken\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // Only a refused credential is the caller's 401; failing to check it is\n // ours and keeps the dispatcher's 5xx (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n\n const listing = (await listingRef.get()).data()\n if (!listing) return res.status(404).json({ error: 'Unknown listing' })\n\n // Membership of the PUBLISHING org, resolved from the listing rather than\n // from anything the caller sent. A client-supplied orgId here would let a\n // publisher of one listing act on another.\n const publisherOrgId = String(listing.profileId ?? '')\n if (\n !publisherOrgId ||\n !(await canActAsPublisher(firestore, decoded.uid, publisherOrgId))\n ) {\n // 404, not 403: a listing the caller does not publish should not be\n // confirmed to exist by the shape of the refusal.\n return res.status(404).json({ error: 'Unknown listing' })\n }\n\n // The agreement this save was sent with, recorded before it writes\n // (AGL-4105).\n await recordPublisherAgreementAcceptance({\n firestore,\n request: req,\n orgId: publisherOrgId,\n uid: decoded.uid,\n staff: decoded['staff'] === true,\n action: action === 'withdraw' ? 'withdraw-verification' : 'request-verification',\n targetId: listingId,\n })\n\n if (action === 'withdraw') {\n if (listing.verificationRequest?.state !== 'pending') {\n return res.status(409).json({ error: 'No request is waiting' })\n }\n await listingRef.set(\n {\n verificationRequest: {\n ...listing.verificationRequest,\n state: 'withdrawn',\n decidedAt: FieldValue.serverTimestamp(),\n // The publisher decided this one, so `decidedBy` is them. Staff\n // uids and publisher uids share the field because the question it\n // answers — who ended this request — has one answer either way.\n decidedBy: decoded.uid,\n },\n },\n { merge: true },\n )\n return res.status(200).json({ ok: true, state: 'withdrawn' })\n }\n\n // Re-checked in a transaction rather than trusting the read above: two\n // tabs pressing the button together would otherwise both pass the check\n // and the second would overwrite the first request's timestamp, resetting\n // its place in the queue.\n const outcome = await firestore.runTransaction(async (tx) => {\n const fresh = (await tx.get(listingRef)).data()\n if (!fresh) return { error: 'Unknown listing', status: 404 } as const\n // `viewerOrgId` is fed the listing's own `profileId` on purpose, which\n // makes the `not-publisher` branch unreachable here. That is NOT the\n // authorization check — `canActAsPublisher` above is, and it ran against\n // the caller's uid. This call is asking the remaining question: is the\n // listing in a state that can carry a request right now.\n const blocked = verificationRequestBlock({\n listing: fresh as never,\n viewerOrgId: String(fresh.profileId ?? ''),\n nowMs: Date.now(),\n })\n if (blocked) {\n return {\n error: VERIFICATION_BLOCK_MESSAGES[blocked],\n reason: blocked,\n status: 409,\n } as const\n }\n tx.set(\n listingRef,\n {\n verificationRequest: {\n state: 'pending',\n requestedAt: FieldValue.serverTimestamp(),\n requestedBy: decoded.uid,\n // Explicitly cleared, because `merge: true` deep-merges MAPS.\n // Without these a re-request after a decline would keep the old\n // `declineReason` and `decidedBy`, and the staff queue would show\n // a brand-new pending request already carrying a verdict.\n decidedAt: FieldValue.delete(),\n decidedBy: FieldValue.delete(),\n declineReason: FieldValue.delete(),\n },\n },\n { merge: true },\n )\n return { ok: true } as const\n })\n\n if ('error' in outcome) {\n return res\n .status(outcome.status)\n .json({ error: outcome.error, reason: outcome.reason })\n }\n return res.status(200).json({ ok: true, state: 'pending' })\n } catch (error) {\n // Reading the listing and running the transaction: a failure here is ours\n // and keeps a 5xx, so it pages (AGL-2852).\n console.error('verification-request failed', error)\n return res.status(500).json({ error: 'The verification request could not be saved' })\n }\n}\n"],"names":["firebaseAdmin","isRefusedIdToken","FieldValue","VERIFICATION_BLOCK_MESSAGES","verificationRequestBlock","canActAsPublisher","recordPublisherAgreementAcceptance","publisherAgreementConsentRefusal","verificationRequestHandler","req","res","method","status","json","error","listingId","String","body","trim","action","agreementRefusal","agreement","authorization","headers","idToken","startsWith","slice","length","decoded","app","auth","verifyIdToken","listing","firestore","listingRef","collection","doc","get","data","publisherOrgId","profileId","uid","request","orgId","staff","targetId","verificationRequest","state","set","decidedAt","serverTimestamp","decidedBy","merge","ok","outcome","runTransaction","tx","fresh","blocked","viewerOrgId","nowMs","Date","now","reason","requestedAt","requestedBy","delete","declineReason","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,2BAA2B,EAC3BC,wBAAwB,QACnB,0BAAsB;AAC7B,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,kCAAkC,QAAQ,sCAAkC;AACrF,SAASC,gCAAgC,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AS;YACtB,OAAO5C,IACJE,MAAM,CAAC0C,QAAQ1C,MAAM,EACrBC,IAAI,CAAC;gBAAEC,OAAOwC,QAAQxC,KAAK;gBAAEiD,QAAQT,QAAQS,MAAM;YAAC;QACzD;QACA,OAAOrD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEwC,IAAI;YAAMN,OAAO;QAAU;IAC3D,EAAE,OAAOjC,OAAO;QACd,0EAA0E;QAC1E,2CAA2C;QAC3CsD,QAAQtD,KAAK,CAAC,+BAA+BA;QAC7C,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA8C;IACrF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/verification-request.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n VERIFICATION_BLOCK_MESSAGES,\n verificationRequestBlock,\n} from '../model/marketplace'\nimport {\n MARKETPLACE_PUBLISHER_PROFILE_PERMISSION,\n marketplacePublisherPermissionRefusal,\n} from '../model/marketplace-publisher-permissions'\nimport { publisherPermissionVerdict } from './publisher-permissions'\nimport { recordPublisherAgreementAcceptance } from './publisher-agreement-acceptance'\nimport { publisherAgreementConsentRefusal } from '../model/publisher-agreement'\nimport type { DecodedIdToken } from 'firebase-admin/auth'\n\n/**\n * A publisher asking for — or taking back — the Verified badge (AGL-1217).\n *\n * Asking grants nothing. This route only ever moves the request between\n * `pending` and `withdrawn`; the checklist gate on the staff `verify` action\n * stays the single route to the badge itself. That separation is the whole\n * safety property here, because this endpoint is reachable by any publisher.\n *\n * Eligibility is decided by `verificationRequestBlock`, the same function the\n * button calls. Sharing it is the point: a client-side rule the server does\n * not enforce is decoration, and a server rule the client does not know\n * produces a button that fails with no explanation.\n */\nexport const verificationRequestHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const listingId = String(req.body?.listingId ?? '').trim()\n const action = String(req.body?.action ?? 'request')\n if (!listingId) return res.status(400).json({ error: 'Missing listingId' })\n if (action !== 'request' && action !== 'withdraw') {\n return res.status(400).json({ error: 'Unknown action' })\n }\n // The publisher agreement, agreed to on this save (AGL-4105): asking for\n // the badge, and taking the ask back, are publisher saves like any other.\n const agreementRefusal = publisherAgreementConsentRefusal(req.body?.agreement)\n if (agreementRefusal) {\n return res.status(agreementRefusal.status).json(agreementRefusal.body)\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n let decoded: DecodedIdToken\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // Only a refused credential is the caller's 401; failing to check it is\n // ours and keeps the dispatcher's 5xx (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n\n const listing = (await listingRef.get()).data()\n if (!listing) return res.status(404).json({ error: 'Unknown listing' })\n\n // The PUBLISHING org, resolved from the listing rather than from anything\n // the caller sent. A client-supplied orgId here would let a publisher of\n // one listing act on another.\n //\n // Asking for the badge is a claim about the publisher, so it asks \"Edit\n // the publisher profile\" (`marketplace.publisherProfile`, AGL-4047) of a\n // member of that org. Its default is the owner and admins this asked for\n // by role before, so nobody's access moved.\n const publisherOrgId = String(listing.profileId ?? '')\n const verdict = await publisherPermissionVerdict(\n decoded.uid,\n publisherOrgId,\n MARKETPLACE_PUBLISHER_PROFILE_PERMISSION,\n )\n if (verdict === 'not-a-member') {\n // 404, not 403: a listing the caller does not publish should not be\n // confirmed to exist by the shape of the refusal.\n return res.status(404).json({ error: 'Unknown listing' })\n }\n if (verdict === 'refused') {\n // A member already sees the listing in their own workspace, so the\n // refusal names the permission they are missing.\n return res.status(403).json({\n error: marketplacePublisherPermissionRefusal(\n MARKETPLACE_PUBLISHER_PROFILE_PERMISSION,\n ),\n reason: 'permission',\n permission: MARKETPLACE_PUBLISHER_PROFILE_PERMISSION,\n })\n }\n\n // The agreement this save was sent with, recorded before it writes\n // (AGL-4105).\n await recordPublisherAgreementAcceptance({\n firestore,\n request: req,\n orgId: publisherOrgId,\n uid: decoded.uid,\n staff: decoded['staff'] === true,\n action: action === 'withdraw' ? 'withdraw-verification' : 'request-verification',\n targetId: listingId,\n })\n\n if (action === 'withdraw') {\n if (listing.verificationRequest?.state !== 'pending') {\n return res.status(409).json({ error: 'No request is waiting' })\n }\n await listingRef.set(\n {\n verificationRequest: {\n ...listing.verificationRequest,\n state: 'withdrawn',\n decidedAt: FieldValue.serverTimestamp(),\n // The publisher decided this one, so `decidedBy` is them. Staff\n // uids and publisher uids share the field because the question it\n // answers — who ended this request — has one answer either way.\n decidedBy: decoded.uid,\n },\n },\n { merge: true },\n )\n return res.status(200).json({ ok: true, state: 'withdrawn' })\n }\n\n // Re-checked in a transaction rather than trusting the read above: two\n // tabs pressing the button together would otherwise both pass the check\n // and the second would overwrite the first request's timestamp, resetting\n // its place in the queue.\n const outcome = await firestore.runTransaction(async (tx) => {\n const fresh = (await tx.get(listingRef)).data()\n if (!fresh) return { error: 'Unknown listing', status: 404 } as const\n // `viewerOrgId` is fed the listing's own `profileId` on purpose, which\n // makes the `not-publisher` branch unreachable here. That is NOT the\n // authorization check — the permission verdict above is, and it ran\n // against the caller's uid. This call is asking the remaining question: is the\n // listing in a state that can carry a request right now.\n const blocked = verificationRequestBlock({\n listing: fresh as never,\n viewerOrgId: String(fresh.profileId ?? ''),\n nowMs: Date.now(),\n })\n if (blocked) {\n return {\n error: VERIFICATION_BLOCK_MESSAGES[blocked],\n reason: blocked,\n status: 409,\n } as const\n }\n tx.set(\n listingRef,\n {\n verificationRequest: {\n state: 'pending',\n requestedAt: FieldValue.serverTimestamp(),\n requestedBy: decoded.uid,\n // Explicitly cleared, because `merge: true` deep-merges MAPS.\n // Without these a re-request after a decline would keep the old\n // `declineReason` and `decidedBy`, and the staff queue would show\n // a brand-new pending request already carrying a verdict.\n decidedAt: FieldValue.delete(),\n decidedBy: FieldValue.delete(),\n declineReason: FieldValue.delete(),\n },\n },\n { merge: true },\n )\n return { ok: true } as const\n })\n\n if ('error' in outcome) {\n return res\n .status(outcome.status)\n .json({ error: outcome.error, reason: outcome.reason })\n }\n return res.status(200).json({ ok: true, state: 'pending' })\n } catch (error) {\n // Reading the listing and running the transaction: a failure here is ours\n // and keeps a 5xx, so it pages (AGL-2852).\n console.error('verification-request failed', error)\n return res.status(500).json({ error: 'The verification request could not be saved' })\n }\n}\n"],"names":["firebaseAdmin","isRefusedIdToken","FieldValue","VERIFICATION_BLOCK_MESSAGES","verificationRequestBlock","MARKETPLACE_PUBLISHER_PROFILE_PERMISSION","marketplacePublisherPermissionRefusal","publisherPermissionVerdict","recordPublisherAgreementAcceptance","publisherAgreementConsentRefusal","verificationRequestHandler","req","res","method","status","json","error","listingId","String","body","trim","action","agreementRefusal","agreement","authorization","headers","idToken","startsWith","slice","length","decoded","app","auth","verifyIdToken","listing","firestore","listingRef","collection","doc","get","data","publisherOrgId","profileId","verdict","uid","reason","permission","request","orgId","staff","targetId","verificationRequest","state","set","decidedAt","serverTimestamp","decidedBy","merge","ok","outcome","runTransaction","tx","fresh","blocked","viewerOrgId","nowMs","Date","now","requestedAt","requestedBy","delete","declineReason","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,2BAA2B,EAC3BC,wBAAwB,QACnB,0BAAsB;AAC7B,SACEC,wCAAwC,EACxCC,qCAAqC,QAChC,gDAA4C;AACnD,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,kCAAkC,QAAQ,sCAAkC;AACrF,SAASC,gCAAgC,QAAQ,kCAA8B;AAG/E;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,6BAA+C,OAAOC,KAAKC;qBAkBzCD;QAbJA,WACHA,YAOoCA;IAZ1D,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IAEA,MAAMC,YAAYC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,SAAS,mBAAI,IAAIG,IAAI;IACxD,MAAMC,SAASH,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUU,MAAM,oBAAI;IAC1C,IAAI,CAACJ,WAAW,OAAOL,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEC,OAAO;IAAoB;IACzE,IAAIK,WAAW,aAAaA,WAAW,YAAY;QACjD,OAAOT,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;IACA,yEAAyE;IACzE,0EAA0E;IAC1E,MAAMM,mBAAmBb,kCAAiCE,aAAAA,IAAIQ,IAAI,qBAARR,WAAUY,SAAS;IAC7E,IAAID,kBAAkB;QACpB,OAAOV,IAAIE,MAAM,CAACQ,iBAAiBR,MAAM,EAAEC,IAAI,CAACO,iB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