@aglyn/plugins-marketplace 1.0.0-beta.287 → 1.0.0-beta.288

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 (33) hide show
  1. package/package.json +14 -14
  2. package/src/lib/declarations.d.ts +26 -0
  3. package/src/lib/declarations.js +37 -0
  4. package/src/lib/declarations.js.map +1 -0
  5. package/src/lib/model/marketplace-site-permissions.d.ts +26 -0
  6. package/src/lib/model/marketplace-site-permissions.js +62 -0
  7. package/src/lib/model/marketplace-site-permissions.js.map +1 -0
  8. package/src/lib/server/install-email-starter.js +7 -4
  9. package/src/lib/server/install-email-starter.js.map +1 -1
  10. package/src/lib/server/install-email-template.js +8 -5
  11. package/src/lib/server/install-email-template.js.map +1 -1
  12. package/src/lib/server/install-layout.js +7 -4
  13. package/src/lib/server/install-layout.js.map +1 -1
  14. package/src/lib/server/install-plugin.js +8 -8
  15. package/src/lib/server/install-plugin.js.map +1 -1
  16. package/src/lib/server/install-template.js +7 -4
  17. package/src/lib/server/install-template.js.map +1 -1
  18. package/src/lib/server/install-theme.js +10 -7
  19. package/src/lib/server/install-theme.js.map +1 -1
  20. package/src/lib/server/install.js +7 -4
  21. package/src/lib/server/install.js.map +1 -1
  22. package/src/lib/server/publish-email-starter.js +8 -5
  23. package/src/lib/server/publish-email-starter.js.map +1 -1
  24. package/src/lib/server/publish-email-template.js +8 -5
  25. package/src/lib/server/publish-email-template.js.map +1 -1
  26. package/src/lib/server/publish-layout.js +8 -5
  27. package/src/lib/server/publish-layout.js.map +1 -1
  28. package/src/lib/server/publish-template.js +9 -6
  29. package/src/lib/server/publish-template.js.map +1 -1
  30. package/src/lib/server/publish-theme.js +8 -5
  31. package/src/lib/server/publish-theme.js.map +1 -1
  32. package/src/lib/server/publish.js +8 -5
  33. package/src/lib/server/publish.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-theme.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 { describeTheme } from '@aglyn/aglyn/app-utils/site-theme'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { runThemeLibraryAction } from '@aglyn/tenant-data-admin/server/theme-library-write'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n isPrivateListing,\n listingArtifactType,\n} from '../model/marketplace'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs a marketplace theme onto a site (AGL-1020).\n *\n * Themes are the exception to \"installing never changes a running site\". A\n * template or a layout can land inert in a library because it is one thing\n * among many; a theme IS the site's appearance, and installing one into a\n * library where it does nothing would be a control that appears to work and\n * does not. So this writes `hosts/{hostId}.theme` and the site repaints.\n *\n * Which makes reversibility the requirement, not a nicety. Two things provide\n * it, and neither is a confirmation dialog:\n *\n * * The theme being replaced is kept verbatim in `themeReplaced`, so `revert`\n * restores exactly what was there — including a hand-built theme that was\n * never a marketplace artifact and exists nowhere else.\n * * `reset` clears the theme entirely, which is the \"use the default theme\"\n * the issue asks to keep first-class. It is a distinct action from revert\n * because \"back to how it was\" and \"back to stock\" are different intents and\n * guessing between them is how people lose work.\n *\n * `preview` changes nothing and returns what the swap would do, so the\n * confirmation can name it rather than showing a JSON blob.\n *\n * Every action that writes the theme then drops the site's cached pages\n * (AGL-3386). The theme styles every page and nothing publishes it, so\n * without the drop \"the site repaints\" meant \"within the hour\".\n */\nexport const installThemeHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const action = ['revert', 'reset', 'preview', 'clear-overrides'].includes(\n req.body?.action,\n )\n ? (req.body.action as\n | 'revert'\n | 'reset'\n | 'preview'\n | 'clear-overrides')\n : 'install'\n const listingId = String(req.body?.listingId ?? '')\n if (!hostId || (action === 'install' && !listingId)) {\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 const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error:\n '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 const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const currentTheme = hostSnapshot.get('theme') ?? null\n // Awaited before the response, because a serverless function may be\n // frozen once it has answered. Never throws: a drop that fails leaves the\n // theme saved and the hour-long cache as the backstop.\n const repaintLiveSite = (action: string) =>\n dropPluginSiteCache({\n hostIds: [hostId],\n reason: `marketplace theme ${action}`,\n })\n\n // ---- reset: back to the platform default ----\n // Picking the default from the site's theme library (AGL-3404): the theme\n // being left is filed in the library, edits and all, so resetting stays\n // reversible without a second copy of it on the host.\n if (action === 'reset') {\n const plan = await firestore.runTransaction((tx) =>\n runThemeLibraryAction(tx, hostRef, {\n action: 'select',\n target: { kind: 'default' },\n }),\n )\n if (plan.ok === false) return res.status(plan.status).json({ error: plan.error })\n await repaintLiveSite('reset')\n return res.status(200).json({ reset: true })\n }\n\n // ---- clear-overrides: drop this site's changes, keep the theme ----\n // The third way back, and the narrowest: \"reset to the publisher's\n // version\" is deleting the patch — the whole point of owning the patch\n // rather than the copy (AGL-1019). The theme itself is untouched.\n //\n // The library's `restore`, which keeps the site's own dark-scheme setting\n // (AGL-3404): that is a decision about the site, not an edit to the theme.\n if (action === 'clear-overrides') {\n const plan = await firestore.runTransaction((tx) =>\n runThemeLibraryAction(tx, hostRef, { action: 'restore' }),\n )\n if (plan.ok === false) return res.status(plan.status).json({ error: plan.error })\n await repaintLiveSite('overrides cleared')\n return res.status(200).json({ cleared: true })\n }\n\n // ---- revert: back to whatever this site had before the last swap ----\n if (action === 'revert') {\n const replaced = hostSnapshot.get('themeReplaced')\n if (!replaced) {\n return res.status(409).json({\n error: 'There is no previous theme to go back to on this site.',\n })\n }\n await hostRef.set(\n {\n theme: replaced.theme ?? firebaseAdmin.firestore.FieldValue.delete(),\n ...(replaced.installedFrom\n ? { themeInstalledFrom: replaced.installedFrom }\n : { themeInstalledFrom: firebaseAdmin.firestore.FieldValue.delete() }),\n // The overrides that were live alongside that theme come back with\n // it. Reverting the base and keeping a patch authored against the\n // theme being reverted FROM is the one combination nobody asked for.\n ...(replaced.override\n ? { themeOverride: replaced.override }\n : { themeOverride: firebaseAdmin.firestore.FieldValue.delete() }),\n themeReplaced: firebaseAdmin.firestore.FieldValue.delete(),\n // A `themeReplaced` predates the library (every library switch\n // clears it), so the theme it restores is read the way a\n // pre-library site's is — from the fields above, not a selection.\n themeSelection: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n await repaintLiveSite('reverted')\n return res.status(200).json({ reverted: true })\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 listingArtifactType(listing) !== 'theme'\n ) {\n return res.status(404).json({ error: 'Unknown theme' })\n }\n\n const priceUsd = Number(listing.priceUsd ?? 0)\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n // Private listings install ONLY for the owning org (AGL-2290).\n //\n // `install-plugin.ts` has carried this since AGL-968; the other six never\n // did, so a private component, theme, template, layout, email template or\n // dataset schema was installable by anyone who knew its listing id. Browse\n // hides them and the detail page 404s, but neither is a control — the\n // route is.\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A FULLY refunded purchase stops entitling (AGL-1546), and until\n // AGL-1699 only the component route knew that: this one asked whether a\n // purchase doc EXISTED, so buy/install/refund kept the artifact. The\n // predicate lives in one place now so the next route cannot miss it.\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,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n const theme = versionSnapshot.get('theme')\n if (!theme || !Object.keys(theme).length) {\n return res.status(500).json({ error: 'Theme version missing' })\n }\n\n // ---- preview: say what the swap changes, change nothing ----\n if (action === 'preview') {\n return res.status(200).json({\n incoming: describeTheme(theme),\n current: describeTheme(currentTheme),\n // A site with no theme is on the platform default, so there is nothing\n // to lose and the confirmation should not imply there is.\n replaces: Boolean(currentTheme && Object.keys(currentTheme).length),\n version: listing.latestVersion ?? null,\n })\n }\n\n // ---- install ----\n // Replacing a theme the workspace has edited destroys those edits (AGL-1018).\n // Unlike a component this is not recoverable by looking in a library — the\n // theme lives on one field on one document — so the refusal matters more.\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: hostSnapshot.get('themeInstalledFrom.sha256'),\n current: currentTheme,\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'This site’s theme has been edited since it was installed. Review ' +\n 'the update to see what would change.',\n diverged: true,\n })\n }\n\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'theme',\n content: theme,\n })\n const previousVersion =\n hostSnapshot.get('themeInstalledFrom.version') ?? null\n\n // The theme joins the site's library and is picked (AGL-3404). The theme\n // it replaces is filed in the library with its edits, so installing is\n // reversible by picking it again — the job `themeReplaced` used to do\n // for one theme, for every theme.\n //\n // Edits belong to the theme they were made on. They used to SURVIVE a\n // swap (AGL-1021), because the theme being replaced was about to exist\n // nowhere and carrying its patch forward was the lesser loss. With the\n // library keeping it, a patch tuned for one design no longer lands on\n // another: each theme gets its own back when it is picked again. An\n // UPDATE of the theme already picked keeps its patch exactly as stored,\n // hash included, so the editor can still say it predates this version.\n const plan = await firestore.runTransaction((tx) =>\n runThemeLibraryAction(tx, hostRef, {\n action: 'install',\n listingId,\n name: String(listing.displayName ?? '') || 'Marketplace theme',\n theme,\n installedFrom: { ...provenance.installedFrom },\n }),\n )\n if (plan.ok === false) return res.status(plan.status).json({ error: plan.error })\n\n await repaintLiveSite('installed')\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'theme',\n from: previousVersion,\n to: listing.latestVersion,\n })\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n\n return res.status(200).json({\n installed: true,\n version: listing.latestVersion ?? null,\n baseStored: provenance.baseStored,\n applied: describeTheme(theme),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Theme install failed' })\n }\n}\n\nexport default installThemeHandler\n"],"names":["describeTheme","dropPluginSiteCache","firebaseAdmin","runThemeLibraryAction","resolveOrgPermissions","isPrivateListing","listingArtifactType","canActAsPublisher","requirePurchase","hasDivergedFromBase","recordInstallProvenance","recordVersionMove","isPublisherSecurityLocked","installThemeHandler","req","res","method","status","json","error","hostId","String","body","action","includes","listingId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","now","FieldValue","serverTimestamp","currentTheme","repaintLiveSite","hostIds","reason","plan","runTransaction","tx","target","kind","ok","reset","cleared","replaced","set","theme","delete","installedFrom","themeInstalledFrom","override","themeOverride","themeReplaced","themeSelection","updatedAt","merge","reverted","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","ownsListing","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","Object","keys","incoming","current","replaces","Boolean","version","diverged","sha256","mode","provenance","artifactType","content","previousVersion","name","displayName","from","to","update","installCount","increment","catch","installed","baseStored","applied","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,oCAAmC;AACjE,SAASC,mBAAmB,QAAQ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BgC;YACAmC;YACA0B,cAAc;YACdK,MAAMH;YACNI,IAAI5E,QAAQ0D,aAAa;QAC3B;QACA,MAAMd,WACHiC,MAAM,CAAC;YACNC,cAAc9G,cAAcyC,SAAS,CAACQ,UAAU,CAAC8D,SAAS,CAAC;QAC7D,GACCC,KAAK,CAAC,IAAMlF;QAEf,OAAOjB,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BiG,WAAW;YACXhB,OAAO,GAAEjE,yBAAAA,QAAQ0D,aAAa,YAArB1D,yBAAyB;YAClCkF,YAAYb,WAAWa,UAAU;YACjCC,SAASrH,cAAcmE;QACzB;IACF,EAAE,OAAOhD,OAAO;QACdmG,QAAQnG,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAuB;IAC9D;AACF,EAAC;AAED,eAAeN,oBAAmB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-theme.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 { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { describeTheme } from '@aglyn/aglyn/app-utils/site-theme'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { runThemeLibraryAction } from '@aglyn/tenant-data-admin/server/theme-library-write'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n isPrivateListing,\n listingArtifactType,\n} from '../model/marketplace'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs a marketplace theme onto a site (AGL-1020).\n *\n * Themes are the exception to \"installing never changes a running site\". A\n * template or a layout can land inert in a library because it is one thing\n * among many; a theme IS the site's appearance, and installing one into a\n * library where it does nothing would be a control that appears to work and\n * does not. So this writes `hosts/{hostId}.theme` and the site repaints.\n *\n * Which makes reversibility the requirement, not a nicety. Two things provide\n * it, and neither is a confirmation dialog:\n *\n * * The theme being replaced is kept verbatim in `themeReplaced`, so `revert`\n * restores exactly what was there — including a hand-built theme that was\n * never a marketplace artifact and exists nowhere else.\n * * `reset` clears the theme entirely, which is the \"use the default theme\"\n * the issue asks to keep first-class. It is a distinct action from revert\n * because \"back to how it was\" and \"back to stock\" are different intents and\n * guessing between them is how people lose work.\n *\n * `preview` changes nothing and returns what the swap would do, so the\n * confirmation can name it rather than showing a JSON blob.\n *\n * Every action that writes the theme then drops the site's cached pages\n * (AGL-3386). The theme styles every page and nothing publishes it, so\n * without the drop \"the site repaints\" meant \"within the hour\".\n */\nexport const installThemeHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const action = ['revert', 'reset', 'preview', 'clear-overrides'].includes(\n req.body?.action,\n )\n ? (req.body.action as\n | 'revert'\n | 'reset'\n | 'preview'\n | 'clear-overrides')\n : 'install'\n const listingId = String(req.body?.listingId ?? '')\n if (!hostId || (action === 'install' && !listingId)) {\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 const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error:\n '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 // \"Install marketplace items into a site\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.siteInstall', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.siteInstall') })\n }\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const currentTheme = hostSnapshot.get('theme') ?? null\n // Awaited before the response, because a serverless function may be\n // frozen once it has answered. Never throws: a drop that fails leaves the\n // theme saved and the hour-long cache as the backstop.\n const repaintLiveSite = (action: string) =>\n dropPluginSiteCache({\n hostIds: [hostId],\n reason: `marketplace theme ${action}`,\n })\n\n // ---- reset: back to the platform default ----\n // Picking the default from the site's theme library (AGL-3404): the theme\n // being left is filed in the library, edits and all, so resetting stays\n // reversible without a second copy of it on the host.\n if (action === 'reset') {\n const plan = await firestore.runTransaction((tx) =>\n runThemeLibraryAction(tx, hostRef, {\n action: 'select',\n target: { kind: 'default' },\n }),\n )\n if (plan.ok === false) return res.status(plan.status).json({ error: plan.error })\n await repaintLiveSite('reset')\n return res.status(200).json({ reset: true })\n }\n\n // ---- clear-overrides: drop this site's changes, keep the theme ----\n // The third way back, and the narrowest: \"reset to the publisher's\n // version\" is deleting the patch — the whole point of owning the patch\n // rather than the copy (AGL-1019). The theme itself is untouched.\n //\n // The library's `restore`, which keeps the site's own dark-scheme setting\n // (AGL-3404): that is a decision about the site, not an edit to the theme.\n if (action === 'clear-overrides') {\n const plan = await firestore.runTransaction((tx) =>\n runThemeLibraryAction(tx, hostRef, { action: 'restore' }),\n )\n if (plan.ok === false) return res.status(plan.status).json({ error: plan.error })\n await repaintLiveSite('overrides cleared')\n return res.status(200).json({ cleared: true })\n }\n\n // ---- revert: back to whatever this site had before the last swap ----\n if (action === 'revert') {\n const replaced = hostSnapshot.get('themeReplaced')\n if (!replaced) {\n return res.status(409).json({\n error: 'There is no previous theme to go back to on this site.',\n })\n }\n await hostRef.set(\n {\n theme: replaced.theme ?? firebaseAdmin.firestore.FieldValue.delete(),\n ...(replaced.installedFrom\n ? { themeInstalledFrom: replaced.installedFrom }\n : { themeInstalledFrom: firebaseAdmin.firestore.FieldValue.delete() }),\n // The overrides that were live alongside that theme come back with\n // it. Reverting the base and keeping a patch authored against the\n // theme being reverted FROM is the one combination nobody asked for.\n ...(replaced.override\n ? { themeOverride: replaced.override }\n : { themeOverride: firebaseAdmin.firestore.FieldValue.delete() }),\n themeReplaced: firebaseAdmin.firestore.FieldValue.delete(),\n // A `themeReplaced` predates the library (every library switch\n // clears it), so the theme it restores is read the way a\n // pre-library site's is — from the fields above, not a selection.\n themeSelection: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n await repaintLiveSite('reverted')\n return res.status(200).json({ reverted: true })\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 listingArtifactType(listing) !== 'theme'\n ) {\n return res.status(404).json({ error: 'Unknown theme' })\n }\n\n const priceUsd = Number(listing.priceUsd ?? 0)\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n // Private listings install ONLY for the owning org (AGL-2290).\n //\n // `install-plugin.ts` has carried this since AGL-968; the other six never\n // did, so a private component, theme, template, layout, email template or\n // dataset schema was installable by anyone who knew its listing id. Browse\n // hides them and the detail page 404s, but neither is a control — the\n // route is.\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A FULLY refunded purchase stops entitling (AGL-1546), and until\n // AGL-1699 only the component route knew that: this one asked whether a\n // purchase doc EXISTED, so buy/install/refund kept the artifact. The\n // predicate lives in one place now so the next route cannot miss it.\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,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n const theme = versionSnapshot.get('theme')\n if (!theme || !Object.keys(theme).length) {\n return res.status(500).json({ error: 'Theme version missing' })\n }\n\n // ---- preview: say what the swap changes, change nothing ----\n if (action === 'preview') {\n return res.status(200).json({\n incoming: describeTheme(theme),\n current: describeTheme(currentTheme),\n // A site with no theme is on the platform default, so there is nothing\n // to lose and the confirmation should not imply there is.\n replaces: Boolean(currentTheme && Object.keys(currentTheme).length),\n version: listing.latestVersion ?? null,\n })\n }\n\n // ---- install ----\n // Replacing a theme the workspace has edited destroys those edits (AGL-1018).\n // Unlike a component this is not recoverable by looking in a library — the\n // theme lives on one field on one document — so the refusal matters more.\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: hostSnapshot.get('themeInstalledFrom.sha256'),\n current: currentTheme,\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'This site’s theme has been edited since it was installed. Review ' +\n 'the update to see what would change.',\n diverged: true,\n })\n }\n\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'theme',\n content: theme,\n })\n const previousVersion =\n hostSnapshot.get('themeInstalledFrom.version') ?? null\n\n // The theme joins the site's library and is picked (AGL-3404). The theme\n // it replaces is filed in the library with its edits, so installing is\n // reversible by picking it again — the job `themeReplaced` used to do\n // for one theme, for every theme.\n //\n // Edits belong to the theme they were made on. They used to SURVIVE a\n // swap (AGL-1021), because the theme being replaced was about to exist\n // nowhere and carrying its patch forward was the lesser loss. With the\n // library keeping it, a patch tuned for one design no longer lands on\n // another: each theme gets its own back when it is picked again. An\n // UPDATE of the theme already picked keeps its patch exactly as stored,\n // hash included, so the editor can still say it predates this version.\n const plan = await firestore.runTransaction((tx) =>\n runThemeLibraryAction(tx, hostRef, {\n action: 'install',\n listingId,\n name: String(listing.displayName ?? '') || 'Marketplace theme',\n theme,\n installedFrom: { ...provenance.installedFrom },\n }),\n )\n if (plan.ok === false) return res.status(plan.status).json({ error: plan.error })\n\n await repaintLiveSite('installed')\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'theme',\n from: previousVersion,\n to: listing.latestVersion,\n })\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n\n return res.status(200).json({\n installed: true,\n version: listing.latestVersion ?? null,\n baseStored: provenance.baseStored,\n applied: describeTheme(theme),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Theme install failed' })\n }\n}\n\nexport default installThemeHandler\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","describeTheme","dropPluginSiteCache","firebaseAdmin","runThemeLibraryAction","resolveOrgPermissions","isPrivateListing","listingArtifactType","canActAsPublisher","requirePurchase","hasDivergedFromBase","recordInstallProvenance","recordVersionMove","isPublisherSecurityLocked","installThemeHandler","req","res","method","status","json","error","hostId","String","body","action","includes","listingId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","now","FieldValue","serverTimestamp","currentTheme","repaintLiveSite","hostIds","reason","plan","runTransaction","tx","target","kind","ok","reset","cleared","replaced","set","theme","delete","installedFrom","themeInstalledFrom","override","themeOverride","themeReplaced","themeSelection","updatedAt","merge","reverted","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","ownsListing","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","Object","keys","incoming","current","replaces","Boolean","version","diverged","sha256","mode","provenance","artifactType","content","previousVersion","name","displayName","from","to","update","installCount","increment","catch","installed","baseStored","applied","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AAEtH,SAASC,aAAa,QAAQ,oCAAmC;AACjE,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,sDAAqD;AAC3F,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,gBAAgB,EAChBC,mBAAmB,QACd,0BAAsB;AAC7B,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,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AAA,QAAQyD,aAAa,YAArBzD,yBAAyB;YAClCiF,YAAYb,WAAWa,UAAU;YACjCC,SAASpH,cAAckE;QACzB;IACF,EAAE,OAAO/C,OAAO;QACdkG,QAAQlG,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAuB;IAC9D;AACF,EAAC;AAED,eAAeN,oBAAmB"}
@@ -17,6 +17,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  */ // The leaf module, not the server barrel: the list keys every artifact
18
18
  // create stamps (AGL-3321), which the install specs' closed-world barrel
19
19
  // mocks have no reason to stage.
20
+ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
21
+ import { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from "../model/marketplace-site-permissions.js";
20
22
  import { artifactCreateListKeys } from "@aglyn/aglyn/app-utils/artifact-list-keys";
21
23
  import { checkQuota, createResourceUid, decodeStoredNodes, encodeStoredNodes } from "@aglyn/aglyn/server";
22
24
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
@@ -57,7 +59,7 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
57
59
  error: 'Unauthenticated'
58
60
  });
59
61
  try {
60
- var _hostSnapshot_get, _listing_priceUsd, _membership_orgId, _version_nodes, _existing_docs__get, _existing_docs__get1;
62
+ var _listing_priceUsd, _membership_orgId, _version_nodes, _existing_docs__get, _existing_docs__get1;
61
63
  var _this;
62
64
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
63
65
  // Org-role permission gate (AGL-238).
@@ -77,10 +79,11 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
77
79
  error: 'Unknown site'
78
80
  });
79
81
  }
80
- const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
81
- if (memberRole !== 'admin' && memberRole !== 'editor') {
82
+ // "Install marketplace items into a site" (AGL-4047): the site's stamp, else
83
+ // the preset of the member's site role, the Admin and Editor this asked for.
84
+ if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.siteInstall', MARKETPLACE_SITE_ROLE_PRESET)) {
82
85
  return res.status(403).json({
83
- error: 'Not a site admin or editor'
86
+ error: marketplaceSitePermissionRefusal('marketplace.siteInstall')
84
87
  });
85
88
  }
86
89
  // The SAME gate the console's own create path applies to this exact
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install.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 checkQuota,\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { isPrivateListing } from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { canActAsPublisher } from './publisher-profile'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs (or updates) a marketplace listing into a host (AGL-44/46).\n * Server-side because version snapshots are not client-readable — paid\n * content would otherwise be free to anyone who read the subcollection.\n * Access: the listing is free, the caller bought it (webhook-written\n * purchase record), or the caller published it. Installing copies the\n * latest version into `hosts/{hostId}/components` with `marketplace` source\n * metadata; re-installing updates the same component doc in place.\n */\nexport const installHandler: 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 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 // Org-role permission gate (AGL-238).\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\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 const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n // The SAME gate the console's own create path applies to this exact\n // document (AGL-2072). `/api/hosts/resources` creates\n // `hosts/{hostId}/components` and refuses past the plan's allowance,\n // because a reusable component renders on the LIVE SITE and the gate has\n // to be server-enforced rather than merely hidden in the console\n // (AGL-473). This route writes a byte-for-byte equivalent doc into the\n // same collection, so it asks the same question: before AGL-2072 it asked\n // nothing, and a free org got the working feature its own console would\n // have refused.\n //\n // The question is a COUNT since AGL-3615: `componentsPerHost`, Free 1 and\n // every paid plan unlimited, no longer the `reusableComponents` flag. A\n // re-install lands on the copy the site already holds, so it creates\n // nothing and is not counted; only a first install of the listing is.\n //\n // Ahead of `requirePurchase`, deliberately, and matching\n // `install-dataset-schema.ts:89`: refusing on plan AFTER taking someone's\n // money for the listing would be the worse order. The whole org doc is\n // read (`getOrgDoc` projects nothing), so `resolveEffectivePlan` sees the\n // subscription status and a LAPSED org is counted exactly as a free one\n // is — the gate is re-asked per install, never inherited from whatever\n // plan was in force when an earlier copy was installed.\n const org = (await getOrgForHost(hostId))?.org\n const componentsRef = hostRef.collection('components')\n const existing = await componentsRef\n .where('marketplace.listingId', '==', listingId)\n .limit(1)\n .get()\n if (existing.empty) {\n // LIVE components only, as `/api/hosts/resources` counts them: a\n // deletion stamps `deletedAt` and keeps the document. Nothing is read\n // on a plan whose allowance is unlimited.\n const limit = checkQuota(org as any, 'componentsPerHost', 0).limit\n const used = Number.isFinite(limit)\n ? (await componentsRef.select('deletedAt').get()).docs.filter(\n (entry) => entry.get('deletedAt') == null,\n ).length\n : 0\n const quota = checkQuota(org as any, 'componentsPerHost', used)\n if (!quota.allowed) {\n return res.status(403).json({\n error:\n `Your plan includes ${quota.limit} reusable component${quota.limit === 1 ? '' : 's'} — ` +\n 'upgrade in Billing for more',\n })\n }\n }\n\n const listingRef = firestore\n .collection('marketplaceListings')\n .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\n const priceUsd = Number(listing.priceUsd ?? 0)\n // The publisher installs their own listing for free. Org-owned now\n // (AGL-652), so this is a role check — comparing a uid to an org id\n // would never match and would charge publishers for their own work.\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n // Private listings install ONLY for the owning org (AGL-2290).\n //\n // `install-plugin.ts` has carried this since AGL-968; the other six never\n // did, so a private component, theme, template, layout, email template or\n // dataset schema was installable by anyone who knew its listing id. Browse\n // hides them and the detail page 404s, but neither is a control — the\n // route is.\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A FULLY refunded purchase no longer entitles (AGL-1546). The gate this\n // route once inlined is now shared (AGL-1699): it was the only one of\n // eight paid-content paths that had learned the refund rule.\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,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n const version = versionSnapshot.data() as any\n if (!version?.nodes || !version?.rootId) {\n return res.status(500).json({ error: 'Listing version missing' })\n }\n\n // The properties the tree binds to (AGL-2933), held to the sanitizer again\n // on the way in. `undefined` for a version published before they were\n // carried, which leaves a re-installed copy's own properties in place.\n const props = readPublishedProps(version.props)\n\n const componentRef = existing.empty\n ? componentsRef.doc(createResourceUid())\n : existing.docs[0].ref\n // Re-installing over a copy the workspace has EDITED is the silent\n // destructive overwrite AGL-1018 exists to stop. The install still happens\n // when it is asked for explicitly (`mode: 'replace'`, which the update\n // dialog sends after showing what goes), but it is never the default.\n if (!existing.empty) {\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: existing.docs[0].get('installedFrom.sha256'),\n current: {\n rootId: existing.docs[0].get('rootId'),\n // DECODED, because the comparison is by value: the base snapshot\n // recorded at install is a node map and `hasDivergedFromBase`\n // hashes a stable stringification of both sides. A stored `Bytes`\n // matches no map, so an untouched copy would read as edited and\n // every re-install would 409 (AGL-1151).\n nodes: decodeStoredNodes(existing.docs[0].get('nodes')),\n },\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'Your copy of this component has been edited since it was ' +\n 'installed. Review the update to see what would change.',\n diverged: true,\n })\n }\n }\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n // Provenance + base snapshot (AGL-1015). The snapshot holds only the\n // vendored tree — the display name and description come from the listing\n // and the user may rename their copy, so including them would make every\n // rename read as a diverged component.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'component',\n content: { rootId: version.rootId, nodes: version.nodes },\n })\n await componentRef.set(\n {\n displayName: listing.displayName,\n ...(listing.description && { description: listing.description }),\n rootId: version.rootId,\n // Compressed at rest, matching what a promote writes onto this same\n // document (AGL-1151). The provenance base above keeps the decoded\n // map: it is compared by value, never rendered.\n nodes: Buffer.from(encodeStoredNodes(version.nodes ?? {})!),\n // Beside the tree, as a publish writes them onto this document. The\n // first version the console mints for this component copies them\n // from here (AGL-2932).\n ...(props && { props }),\n deletedAt: null,\n // The keys the components list finds it by (AGL-3321): the listing's\n // name, and — on a first install — the stored kind; a re-install\n // keeps the kind the copy already has.\n ...artifactCreateListKeys('components', {\n displayName: listing.displayName,\n // The description written above — or, on a re-install (a merge),\n // the one the copy already has — so the stored-null default\n // (AGL-3680) never overwrites it.\n description:\n listing.description ||\n (existing.empty ? null : (existing.docs[0].get('description') ?? null)),\n kind: existing.empty ? undefined : existing.docs[0].get('kind'),\n }),\n marketplace: {\n listingId,\n profileId: listing.profileId,\n version: listing.latestVersion,\n },\n installedFrom: provenance.installedFrom,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n },\n { merge: true },\n )\n // Per-version tally (AGL-1036): a re-install moves this copy off whatever\n // version it was on and onto the latest.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'component',\n from: existing.empty\n ? null\n : (existing.docs[0].get('installedFrom.version') ??\n existing.docs[0].get('marketplace.version')),\n to: listing.latestVersion,\n })\n // First installs count toward the browse \"Most installed\" sort\n // (AGL-95); updates don't inflate it.\n if (existing.empty) {\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n }\n return res.status(200).json({\n installed: true,\n updated: !existing.empty,\n version: listing.latestVersion,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Install failed' })\n }\n}\n"],"names":["artifactCreateListKeys","checkQuota","createResourceUid","decodeStoredNodes","encodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","isPrivateListing","readPublishedProps","canActAsPublisher","hasDivergedFromBase","recordInstallProvenance","requirePurchase","recordVersionMove","isPublisherSecurityLocked","installHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","version","existing","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","org","componentsRef","where","limit","empty","used","Number","isFinite","select","docs","filter","entry","quota","allowed","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","ownsListing","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","nodes","rootId","props","componentRef","ref","diverged","sha256","current","mode","now","FieldValue","serverTimestamp","provenance","artifactType","content","set","displayName","description","Buffer","from","kind","marketplace","installedFrom","createdAt","updatedAt","merge","to","update","installCount","increment","catch","installed","updated","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;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AAM9E;QACjB;QACA,OAAOf,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1B2F,WAAW;YACXC,SAAS,CAAC3E,SAASmB,KAAK;YACxBpB,SAASF,QAAQ6C,aAAa;YAC9BkC,YAAYrB,WAAWqB,UAAU;QACnC;IACF,EAAE,OAAO5F,OAAO;QACd6F,QAAQ7F,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install.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 { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport {\n checkQuota,\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { isPrivateListing } from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { canActAsPublisher } from './publisher-profile'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs (or updates) a marketplace listing into a host (AGL-44/46).\n * Server-side because version snapshots are not client-readable — paid\n * content would otherwise be free to anyone who read the subcollection.\n * Access: the listing is free, the caller bought it (webhook-written\n * purchase record), or the caller published it. Installing copies the\n * latest version into `hosts/{hostId}/components` with `marketplace` source\n * metadata; re-installing updates the same component doc in place.\n */\nexport const installHandler: 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 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 // Org-role permission gate (AGL-238).\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\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 // \"Install marketplace items into a site\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.siteInstall', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.siteInstall') })\n }\n\n // The SAME gate the console's own create path applies to this exact\n // document (AGL-2072). `/api/hosts/resources` creates\n // `hosts/{hostId}/components` and refuses past the plan's allowance,\n // because a reusable component renders on the LIVE SITE and the gate has\n // to be server-enforced rather than merely hidden in the console\n // (AGL-473). This route writes a byte-for-byte equivalent doc into the\n // same collection, so it asks the same question: before AGL-2072 it asked\n // nothing, and a free org got the working feature its own console would\n // have refused.\n //\n // The question is a COUNT since AGL-3615: `componentsPerHost`, Free 1 and\n // every paid plan unlimited, no longer the `reusableComponents` flag. A\n // re-install lands on the copy the site already holds, so it creates\n // nothing and is not counted; only a first install of the listing is.\n //\n // Ahead of `requirePurchase`, deliberately, and matching\n // `install-dataset-schema.ts:89`: refusing on plan AFTER taking someone's\n // money for the listing would be the worse order. The whole org doc is\n // read (`getOrgDoc` projects nothing), so `resolveEffectivePlan` sees the\n // subscription status and a LAPSED org is counted exactly as a free one\n // is — the gate is re-asked per install, never inherited from whatever\n // plan was in force when an earlier copy was installed.\n const org = (await getOrgForHost(hostId))?.org\n const componentsRef = hostRef.collection('components')\n const existing = await componentsRef\n .where('marketplace.listingId', '==', listingId)\n .limit(1)\n .get()\n if (existing.empty) {\n // LIVE components only, as `/api/hosts/resources` counts them: a\n // deletion stamps `deletedAt` and keeps the document. Nothing is read\n // on a plan whose allowance is unlimited.\n const limit = checkQuota(org as any, 'componentsPerHost', 0).limit\n const used = Number.isFinite(limit)\n ? (await componentsRef.select('deletedAt').get()).docs.filter(\n (entry) => entry.get('deletedAt') == null,\n ).length\n : 0\n const quota = checkQuota(org as any, 'componentsPerHost', used)\n if (!quota.allowed) {\n return res.status(403).json({\n error:\n `Your plan includes ${quota.limit} reusable component${quota.limit === 1 ? '' : 's'} — ` +\n 'upgrade in Billing for more',\n })\n }\n }\n\n const listingRef = firestore\n .collection('marketplaceListings')\n .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\n const priceUsd = Number(listing.priceUsd ?? 0)\n // The publisher installs their own listing for free. Org-owned now\n // (AGL-652), so this is a role check — comparing a uid to an org id\n // would never match and would charge publishers for their own work.\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n // Private listings install ONLY for the owning org (AGL-2290).\n //\n // `install-plugin.ts` has carried this since AGL-968; the other six never\n // did, so a private component, theme, template, layout, email template or\n // dataset schema was installable by anyone who knew its listing id. Browse\n // hides them and the detail page 404s, but neither is a control — the\n // route is.\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A FULLY refunded purchase no longer entitles (AGL-1546). The gate this\n // route once inlined is now shared (AGL-1699): it was the only one of\n // eight paid-content paths that had learned the refund rule.\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,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n const version = versionSnapshot.data() as any\n if (!version?.nodes || !version?.rootId) {\n return res.status(500).json({ error: 'Listing version missing' })\n }\n\n // The properties the tree binds to (AGL-2933), held to the sanitizer again\n // on the way in. `undefined` for a version published before they were\n // carried, which leaves a re-installed copy's own properties in place.\n const props = readPublishedProps(version.props)\n\n const componentRef = existing.empty\n ? componentsRef.doc(createResourceUid())\n : existing.docs[0].ref\n // Re-installing over a copy the workspace has EDITED is the silent\n // destructive overwrite AGL-1018 exists to stop. The install still happens\n // when it is asked for explicitly (`mode: 'replace'`, which the update\n // dialog sends after showing what goes), but it is never the default.\n if (!existing.empty) {\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: existing.docs[0].get('installedFrom.sha256'),\n current: {\n rootId: existing.docs[0].get('rootId'),\n // DECODED, because the comparison is by value: the base snapshot\n // recorded at install is a node map and `hasDivergedFromBase`\n // hashes a stable stringification of both sides. A stored `Bytes`\n // matches no map, so an untouched copy would read as edited and\n // every re-install would 409 (AGL-1151).\n nodes: decodeStoredNodes(existing.docs[0].get('nodes')),\n },\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'Your copy of this component has been edited since it was ' +\n 'installed. Review the update to see what would change.',\n diverged: true,\n })\n }\n }\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n // Provenance + base snapshot (AGL-1015). The snapshot holds only the\n // vendored tree — the display name and description come from the listing\n // and the user may rename their copy, so including them would make every\n // rename read as a diverged component.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'component',\n content: { rootId: version.rootId, nodes: version.nodes },\n })\n await componentRef.set(\n {\n displayName: listing.displayName,\n ...(listing.description && { description: listing.description }),\n rootId: version.rootId,\n // Compressed at rest, matching what a promote writes onto this same\n // document (AGL-1151). The provenance base above keeps the decoded\n // map: it is compared by value, never rendered.\n nodes: Buffer.from(encodeStoredNodes(version.nodes ?? {})!),\n // Beside the tree, as a publish writes them onto this document. The\n // first version the console mints for this component copies them\n // from here (AGL-2932).\n ...(props && { props }),\n deletedAt: null,\n // The keys the components list finds it by (AGL-3321): the listing's\n // name, and — on a first install — the stored kind; a re-install\n // keeps the kind the copy already has.\n ...artifactCreateListKeys('components', {\n displayName: listing.displayName,\n // The description written above — or, on a re-install (a merge),\n // the one the copy already has — so the stored-null default\n // (AGL-3680) never overwrites it.\n description:\n listing.description ||\n (existing.empty ? null : (existing.docs[0].get('description') ?? null)),\n kind: existing.empty ? undefined : existing.docs[0].get('kind'),\n }),\n marketplace: {\n listingId,\n profileId: listing.profileId,\n version: listing.latestVersion,\n },\n installedFrom: provenance.installedFrom,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n },\n { merge: true },\n )\n // Per-version tally (AGL-1036): a re-install moves this copy off whatever\n // version it was on and onto the latest.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'component',\n from: existing.empty\n ? null\n : (existing.docs[0].get('installedFrom.version') ??\n existing.docs[0].get('marketplace.version')),\n to: listing.latestVersion,\n })\n // First installs count toward the browse \"Most installed\" sort\n // (AGL-95); updates don't inflate it.\n if (existing.empty) {\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n }\n return res.status(200).json({\n installed: true,\n updated: !existing.empty,\n version: listing.latestVersion,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Install failed' })\n }\n}\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","artifactCreateListKeys","checkQuota","createResourceUid","decodeStoredNodes","encodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","isPrivateListing","readPublishedProps","canActAsPublisher","hasDivergedFromBase","recordInstallProvenance","requirePurchase","recordVersionMove","isPublisherSecurityLocked","installHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","listing","membership","version","existing","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","hostSnapshot","get","exists","org","componentsRef","where","limit","empty","used","Number","isFinite","select","docs","filter","entry","quota","allowed","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","ownsListing","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","nodes","rootId","props","componentRef","ref","diverged","sha256","current","mode","now","FieldValue","serverTimestamp","provenance","artifactType","content","set","displayName","description","Buffer","from","kind","marketplace","installedFrom","createdAt","updatedAt","merge","to","update","installCount","increment","catch","installed","updated","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AACtH,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SACEC,UAAU,EACVC,iBAAiB,EACjBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAC5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AAEvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,gBAAgB,QAAQ,0BAAsB;AACvD,SAASC,kBAAkB,QAAQ,gCAA4B;AAC/D,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,mBAAmB,EAAEC,uBAAuB,QAAQ,kBAAc;AAC3E,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,yBAAyB,QAAQ,iBAAa;AAEvD;;;;;;;;CAQC,GACD,OAAO,MAAMC,iBAAmC,OAAOC,KAAKC;qBAS7BD;QALJA,WACHA;IAJtB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,YAAYC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,SAAS,mBAAI;IAChD,MAAMG,SAASF,iBAAOP,aAAAA,IA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QACCnB,uBAAAA,SAASwB,IAAI,CAAC,EAAE,CAACX,GAAG,CAAC,oCAArBb,uBACDA,SAASwB,IAAI,CAAC,EAAE,CAACX,GAAG,CAAC;YACzBwD,IAAIxE,QAAQ6C,aAAa;QAC3B;QACA,+DAA+D;QAC/D,sCAAsC;QACtC,IAAI1C,SAASmB,KAAK,EAAE;YAClB,MAAMU,WACHyC,MAAM,CAAC;gBACNC,cAAcvG,cAAcwC,SAAS,CAAC6C,UAAU,CAACmB,SAAS,CAAC;YAC7D,GACCC,KAAK,CAAC,IAAM7E;QACjB;QACA,OAAOf,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1B0F,WAAW;YACXC,SAAS,CAAC3E,SAASmB,KAAK;YACxBpB,SAASF,QAAQ6C,aAAa;YAC9BkC,YAAYrB,WAAWqB,UAAU;QACnC;IACF,EAAE,OAAO3F,OAAO;QACd4F,QAAQ5F,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC"}
@@ -14,7 +14,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
17
+ */ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
18
+ import { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from "../model/marketplace-site-permissions.js";
19
+ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
18
20
  import { CANVAS_ROOT_ELEMENT_ID, checkEntitlement, createResourceUid } from "@aglyn/aglyn/server";
19
21
  import { decodeStoredNodes } from "@aglyn/aglyn/app-utils/stored-nodes";
20
22
  import { inlineReusableBlocks } from "./publish-email-blocks.js";
@@ -78,7 +80,7 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
78
80
  error: 'Unauthenticated'
79
81
  });
80
82
  try {
81
- var _hostSnapshot_get, _ref6, _existing_docs__get, _orgForHost_org, _screen_emailSubject, _screen_emailPreheader;
83
+ var _ref6, _existing_docs__get, _orgForHost_org, _screen_emailSubject, _screen_emailPreheader;
82
84
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
83
85
  const membership = await resolveOrgPermissions(decoded.uid, {
84
86
  hostId
@@ -96,10 +98,11 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
96
98
  error: 'Unknown site'
97
99
  });
98
100
  }
99
- const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
100
- if (memberRole !== 'admin' && memberRole !== 'editor') {
101
+ // "Publish a site’s items to the marketplace" (AGL-4047): the site's stamp, else
102
+ // the preset of the member's site role, the Admin and Editor this asked for.
103
+ if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {
101
104
  return res.status(403).json({
102
- error: 'Not a site admin or editor'
105
+ error: marketplaceSitePermissionRefusal('marketplace.sitePublish')
103
106
  });
104
107
  }
105
108
  const orgForHost = await getOrgForHost(hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-starter.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 { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's campaign email design as a marketplace starter.\n *\n * The source is a `kind: 'email'` SCREEN — the document `createEmailScreen`\n * writes and the screen besigner edits — not an entry in the transactional\n * catalog. That is the whole difference from `publish-email-template`, and it\n * is why the two exist separately: a transactional design is a design FOR a\n * fixed key and installs onto that same key; a starter belongs to no key and\n * installs as a new email of the buyer's own.\n *\n * ## Two things this reads that the transactional publisher does not\n *\n * **The nodes are compressed.** A screen version is written through\n * `screenVersionConverter`, so `nodes` comes back from the Admin SDK as a\n * msgpack `Buffer`. `publish-email-template.ts` reads its `nodes` raw and says\n * why — its besigner saves with a bare `setDoc` and no converter — and copying\n * that line here would publish a Buffer: truthy, non-empty by `Object.keys`\n * (those are byte indices), and scanning as a design with no blocks in it.\n *\n * **The tree is inspected, not just sanitized.** `sanitizeMarketplaceDefinition`\n * DROPS an unsafe URL and publishes what is left, which is right for a page.\n * Here the URL rules are the product: a remote image in an email is a read\n * receipt for whoever hosts it, and quietly removing one teaches the publisher\n * nothing. So `inspectEmailStarter` runs first and REFUSES.\n */\nexport const publishEmailStarterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const screenId = String(req.body?.screenId ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) return res.status(400).json({ error: priceRefusal })\n if (!hostId || !screenId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, screenId, or displayName' })\n }\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 const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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 const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const screenRef = hostRef.collection('screens').doc(screenId)\n const screenSnapshot = await screenRef.get()\n const screen = screenSnapshot.data() as Record<string, unknown> | undefined\n if (!screen || screen['deletedAt']) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n if (screen['kind'] !== 'email') {\n return res\n .status(422)\n .json({ error: 'That design is not an email' })\n }\n const activeVersionId = screen['versionId']\n if (!activeVersionId) {\n return res\n .status(404)\n .json({ error: 'This email has no saved design yet — design and save it first' })\n }\n const versionSnapshot = await screenRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n\n /*\n * The site's reusable blocks INLINED before anything is judged (AGL-3287).\n * A buyer's org has none of this site's components, so a placement has to\n * travel as the blocks it renders — and inlining first is what puts a\n * shared footer's links and images in front of the inspection below, as\n * the send path would mail them. An undecodable payload is left as stored,\n * so the inspection still refuses it by name.\n */\n const stored = versionSnapshot.get('nodes')\n const readable = decodeStoredNodes<Record<string, unknown>>(stored)\n let design: unknown = stored\n if (readable && typeof readable === 'object' && !Array.isArray(readable)) {\n const inlined = await inlineReusableBlocks(readable, {\n firestore,\n hostId,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n design = inlined.nodes\n }\n // The inspection decodes, so it is also the guard against publishing a\n // node map nothing could read — it refuses rather than reporting a\n // compressed payload as a clean design.\n const inspection = inspectEmailStarter(design)\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res.status(422).json({\n error: violation,\n violations: inspection.violations,\n })\n }\n if (!inspection.nodes || !Object.keys(inspection.nodes).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n // Runs after the inspection and over the same decoded map. It enforces the\n // component-id allowlist and trims node keys; the URL rules it also carries\n // can no longer fire, because a design that would have tripped them was\n // refused above rather than silently trimmed.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: inspection.nodes },\n { componentIds: MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (publisher org, source screen). Re-publishing the same\n // email bumps its version rather than minting a second listing, which is\n // what makes \"update available\" mean anything to everyone who installed it.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('sourceScreenId', '==', screenId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailStarter',\n sourceHostId: hostId,\n sourceScreenId: screenId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n // Copy is part of the design and travels with it.\n subject: String(screen['emailSubject'] ?? ''),\n preheader: String(screen['emailPreheader'] ?? ''),\n // The hosts this design would send a recipient to, recorded at publish\n // so the listing page can show them BEFORE somebody installs. A tenant\n // about to mail their own customers under their own name is entitled to\n // see the domains a stranger's template points them at, and no\n // allowlist can make that judgment for them.\n linkHosts: inspection.linkHosts,\n // Absent `reviewState` is the un-reviewed default, and it is written\n // NOWHERE here on purpose: a publisher who could stamp their own\n // version approved would make the field decorative. Staff write it.\n publishedAt: now,\n })\n\n return res\n .status(200)\n .json({ listingId: listingRef.id, version, linkHosts: inspection.linkHosts })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter publish failed' })\n }\n}\n\nexport default publishEmailStarterHandler\n"],"names":["displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailStarterHandler","req","res","method","status","json","error","hostId","String","body","screenId","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","existing","orgForHost","screen","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","org","orgId","publisher","refusal","sells","screenRef","screenSnapshot","data","activeVersionId","versionSnapshot","stored","readable","design","Array","isArray","inlined","rootId","ok","nodes","inspection","violation","violations","Object","keys","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","sourceScreenId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","linkHosts","listingId","id","console"],"mappings":";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
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-starter.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 { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's campaign email design as a marketplace starter.\n *\n * The source is a `kind: 'email'` SCREEN — the document `createEmailScreen`\n * writes and the screen besigner edits — not an entry in the transactional\n * catalog. That is the whole difference from `publish-email-template`, and it\n * is why the two exist separately: a transactional design is a design FOR a\n * fixed key and installs onto that same key; a starter belongs to no key and\n * installs as a new email of the buyer's own.\n *\n * ## Two things this reads that the transactional publisher does not\n *\n * **The nodes are compressed.** A screen version is written through\n * `screenVersionConverter`, so `nodes` comes back from the Admin SDK as a\n * msgpack `Buffer`. `publish-email-template.ts` reads its `nodes` raw and says\n * why — its besigner saves with a bare `setDoc` and no converter — and copying\n * that line here would publish a Buffer: truthy, non-empty by `Object.keys`\n * (those are byte indices), and scanning as a design with no blocks in it.\n *\n * **The tree is inspected, not just sanitized.** `sanitizeMarketplaceDefinition`\n * DROPS an unsafe URL and publishes what is left, which is right for a page.\n * Here the URL rules are the product: a remote image in an email is a read\n * receipt for whoever hosts it, and quietly removing one teaches the publisher\n * nothing. So `inspectEmailStarter` runs first and REFUSES.\n */\nexport const publishEmailStarterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const screenId = String(req.body?.screenId ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) return res.status(400).json({ error: priceRefusal })\n if (!hostId || !screenId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, screenId, or displayName' })\n }\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 const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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 // \"Publish a site’s items to the marketplace\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.sitePublish') })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const screenRef = hostRef.collection('screens').doc(screenId)\n const screenSnapshot = await screenRef.get()\n const screen = screenSnapshot.data() as Record<string, unknown> | undefined\n if (!screen || screen['deletedAt']) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n if (screen['kind'] !== 'email') {\n return res\n .status(422)\n .json({ error: 'That design is not an email' })\n }\n const activeVersionId = screen['versionId']\n if (!activeVersionId) {\n return res\n .status(404)\n .json({ error: 'This email has no saved design yet — design and save it first' })\n }\n const versionSnapshot = await screenRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n\n /*\n * The site's reusable blocks INLINED before anything is judged (AGL-3287).\n * A buyer's org has none of this site's components, so a placement has to\n * travel as the blocks it renders — and inlining first is what puts a\n * shared footer's links and images in front of the inspection below, as\n * the send path would mail them. An undecodable payload is left as stored,\n * so the inspection still refuses it by name.\n */\n const stored = versionSnapshot.get('nodes')\n const readable = decodeStoredNodes<Record<string, unknown>>(stored)\n let design: unknown = stored\n if (readable && typeof readable === 'object' && !Array.isArray(readable)) {\n const inlined = await inlineReusableBlocks(readable, {\n firestore,\n hostId,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n design = inlined.nodes\n }\n // The inspection decodes, so it is also the guard against publishing a\n // node map nothing could read — it refuses rather than reporting a\n // compressed payload as a clean design.\n const inspection = inspectEmailStarter(design)\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res.status(422).json({\n error: violation,\n violations: inspection.violations,\n })\n }\n if (!inspection.nodes || !Object.keys(inspection.nodes).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n // Runs after the inspection and over the same decoded map. It enforces the\n // component-id allowlist and trims node keys; the URL rules it also carries\n // can no longer fire, because a design that would have tripped them was\n // refused above rather than silently trimmed.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: inspection.nodes },\n { componentIds: MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (publisher org, source screen). Re-publishing the same\n // email bumps its version rather than minting a second listing, which is\n // what makes \"update available\" mean anything to everyone who installed it.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('sourceScreenId', '==', screenId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailStarter',\n sourceHostId: hostId,\n sourceScreenId: screenId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n // Copy is part of the design and travels with it.\n subject: String(screen['emailSubject'] ?? ''),\n preheader: String(screen['emailPreheader'] ?? ''),\n // The hosts this design would send a recipient to, recorded at publish\n // so the listing page can show them BEFORE somebody installs. A tenant\n // about to mail their own customers under their own name is entitled to\n // see the domains a stranger's template points them at, and no\n // allowlist can make that judgment for them.\n linkHosts: inspection.linkHosts,\n // Absent `reviewState` is the un-reviewed default, and it is written\n // NOWHERE here on purpose: a publisher who could stamp their own\n // version approved would make the field decorative. Staff write it.\n publishedAt: now,\n })\n\n return res\n .status(200)\n .json({ listingId: listingRef.id, version, linkHosts: inspection.linkHosts })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter publish failed' })\n }\n}\n\nexport default publishEmailStarterHandler\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailStarterHandler","req","res","method","status","json","error","hostId","String","body","screenId","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","authorization","headers","idToken","startsWith","length","undefined","existing","orgForHost","screen","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","hostSnapshot","get","exists","org","orgId","publisher","refusal","sells","screenRef","screenSnapshot","data","activeVersionId","versionSnapshot","stored","readable","design","Array","isArray","inlined","rootId","ok","nodes","inspection","violation","violations","Object","keys","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","sourceScreenId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","linkHosts","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AACtH,SAASC,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gDAAgD,EAChDC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,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;QAChC,MAAMA,WACHjC,UAAU,CAAC,YACXC,GAAG,CAACjC,OAAOqE,UACXU,GAAG,CAAC;YACH1B,QAAQQ,UAAUR,MAAM;YACxBE,OAAOM,UAAUN,KAAK;YACtB,kDAAkD;YAClDsC,SAAS7F,QAAOqB,uBAAAA,MAAM,CAAC,eAAe,YAAtBA,uBAA0B;YAC1CyE,WAAW9F,QAAOqB,yBAAAA,MAAM,CAAC,iBAAiB,YAAxBA,yBAA4B;YAC9C,uEAAuE;YACvE,uEAAuE;YACvE,wEAAwE;YACxE,+DAA+D;YAC/D,6CAA6C;YAC7C0E,WAAWvC,WAAWuC,SAAS;YAC/B,qEAAqE;YACrE,iEAAiE;YACjE,oEAAoE;YACpEL,aAAapB;QACf;QAEF,OAAO5E,IACJE,MAAM,CAAC,KACPC,IAAI,CAAC;YAAEmG,WAAW/B,WAAWgC,EAAE;YAAE5B;YAAS0B,WAAWvC,WAAWuC,SAAS;QAAC;IAC/E,EAAE,OAAOjG,OAAO;QACdoG,QAAQpG,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
@@ -14,7 +14,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
17
+ */ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
18
+ import { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from "../model/marketplace-site-permissions.js";
19
+ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
18
20
  import { checkEntitlement, createResourceUid, decodeStoredNodes } from "@aglyn/aglyn/server";
19
21
  import { inlineReusableBlocks } from "./publish-email-blocks.js";
20
22
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
@@ -80,7 +82,7 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
80
82
  error: 'Unauthenticated'
81
83
  });
82
84
  try {
83
- var _hostSnapshot_get, _ref6, _versionSnapshot_get, _existing_docs__get, _orgForHost_org, _templateSnapshot_get, _templateSnapshot_get1;
85
+ var _ref6, _versionSnapshot_get, _existing_docs__get, _orgForHost_org, _templateSnapshot_get, _templateSnapshot_get1;
84
86
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
85
87
  const membership = await resolveOrgPermissions(decoded.uid, {
86
88
  hostId
@@ -98,10 +100,11 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
98
100
  error: 'Unknown site'
99
101
  });
100
102
  }
101
- const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
102
- if (memberRole !== 'admin' && memberRole !== 'editor') {
103
+ // "Publish a site’s items to the marketplace" (AGL-4047): the site's stamp, else
104
+ // the preset of the member's site role, the Admin and Editor this asked for.
105
+ if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {
103
106
  return res.status(403).json({
104
- error: 'Not a site admin or editor'
107
+ error: marketplaceSitePermissionRefusal('marketplace.sitePublish')
105
108
  });
106
109
  }
107
110
  const orgForHost = await getOrgForHost(hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-template.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 { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n EMAIL_NODE_ROOT_ID,\n getTenantEmail,\n isTenantEmailEditable,\n TENANT_EMAIL_COLLECTION,\n} from '@aglyn/shared-util-email'\nimport {\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's designed transactional email to the marketplace\n * (AGL-657).\n *\n * An email design is a node tree like any other artifact, but it does NOT live\n * in the host's screen routing map — which is exactly why `publish-template`\n * could never capture one (it only sees `hostSnapshot.get('screens')`). The\n * tree lives at `hosts/{h}/emailTemplates/{key}/versions/{versionId}`, so this\n * reads it directly.\n *\n * `templateKey` is a fixed catalog key ('booking-confirmed', …), not a free\n * id: a published email means \"a design FOR this transactional email\", so the\n * key travels with the listing and the installer lands on the same key.\n */\nexport const publishEmailTemplateHandler: PluginApiHandler = async (\n req,\n res,\n) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const templateKey = String(req.body?.templateKey ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n // The price floor and ceiling, from ONE validator (AGL-2343): a paid listing\n // under `MARKETPLACE_MIN_PRICE_USD` loses money on every sale, because\n // marketplace checkout is a destination charge whose Stripe fee is debited\n // from the platform's balance. Also enforced in `publishPreconditionRefusal`\n // below, so a door that drops this line is still covered.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n if (!hostId || !templateKey || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, templateKey, or displayName' })\n }\n const entry = getTenantEmail(templateKey)\n if (!entry || !isTenantEmailEditable(entry)) {\n return res.status(400).json({ error: 'Not a designable email template' })\n }\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 const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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 const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const templateRef = hostRef\n .collection(TENANT_EMAIL_COLLECTION)\n .doc(templateKey)\n const templateSnapshot = await templateRef.get()\n const activeVersionId = templateSnapshot.get('versionId')\n if (!templateSnapshot.exists || !activeVersionId) {\n return res.status(404).json({\n error: 'This email has no published design yet — design and save it first',\n })\n }\n const versionSnapshot = await templateRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n // Decoded, like the screen and layout publish paths (AGL-1395): the email\n // besigner now compresses through a converter as those do, and versions\n // written before it did are still plain maps, which come back unchanged.\n //\n // `sanitizeMarketplaceDefinition` below would refuse an undecoded tree\n // rather than publish garbage, so this is the difference between the\n // feature working and a publish that always says the design is invalid.\n const stored = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!stored || !Object.keys(stored).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n const rootId = versionSnapshot.get('rootId') ?? EMAIL_NODE_ROOT_ID\n // The site's reusable blocks INLINED (AGL-3287): a listing is installed\n // into another org, which has none of this site's components, and the\n // sanitizer below refuses a component reference outright.\n const inlined = await inlineReusableBlocks(stored, {\n firestore,\n hostId,\n rootId,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n const nodes = inlined.nodes\n // Emails are built from `plugins-email` blocks only, so the page allowlist\n // is REPLACED rather than extended — see MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST\n // for why `emailHtml` is not on the list.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n { componentIds: MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (source site, template key).\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('emailTemplateKey', '==', templateKey)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailTemplate',\n sourceHostId: hostId,\n emailTemplateKey: templateKey,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n emailTemplateKey: templateKey,\n // The copy fields are part of the design, not the tree.\n subject: String(templateSnapshot.get('subject') ?? ''),\n preheader: String(templateSnapshot.get('preheader') ?? ''),\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Publish failed' })\n }\n}\n\nexport default publishEmailTemplateHandler\n"],"names":["displayNameSearchFields","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","EMAIL_NODE_ROOT_ID","getTenantEmail","isTenantEmailEditable","TENANT_EMAIL_COLLECTION","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailTemplateHandler","req","res","method","status","json","error","hostId","String","body","templateKey","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","entry","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","versionSnapshot","existing","orgForHost","templateSnapshot","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","org","orgId","publisher","refusal","sells","templateRef","activeVersionId","stored","Object","keys","rootId","inlined","ok","nodes","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","emailTemplateKey","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,EACrBC,uBAAuB,QAClB,2BAA0B;AACjC,SACEC,wCAAwC,EACxCC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC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WAAWvF,QAAOwB,yBAAAA,iBAAiBa,GAAG,CAAC,wBAArBb,yBAAqC;YACvD2D,aAAapB;QACf;QAEF,OAAOrE,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAE2F,WAAW9B,WAAW+B,EAAE;YAAE3B;QAAQ;IAClE,EAAE,OAAOhE,OAAO;QACd4F,QAAQ5F,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC;AAED,eAAeN,4BAA2B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-template.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 { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n EMAIL_NODE_ROOT_ID,\n getTenantEmail,\n isTenantEmailEditable,\n TENANT_EMAIL_COLLECTION,\n} from '@aglyn/shared-util-email'\nimport {\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's designed transactional email to the marketplace\n * (AGL-657).\n *\n * An email design is a node tree like any other artifact, but it does NOT live\n * in the host's screen routing map — which is exactly why `publish-template`\n * could never capture one (it only sees `hostSnapshot.get('screens')`). The\n * tree lives at `hosts/{h}/emailTemplates/{key}/versions/{versionId}`, so this\n * reads it directly.\n *\n * `templateKey` is a fixed catalog key ('booking-confirmed', …), not a free\n * id: a published email means \"a design FOR this transactional email\", so the\n * key travels with the listing and the installer lands on the same key.\n */\nexport const publishEmailTemplateHandler: PluginApiHandler = async (\n req,\n res,\n) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const templateKey = String(req.body?.templateKey ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n // The price floor and ceiling, from ONE validator (AGL-2343): a paid listing\n // under `MARKETPLACE_MIN_PRICE_USD` loses money on every sale, because\n // marketplace checkout is a destination charge whose Stripe fee is debited\n // from the platform's balance. Also enforced in `publishPreconditionRefusal`\n // below, so a door that drops this line is still covered.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n if (!hostId || !templateKey || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, templateKey, or displayName' })\n }\n const entry = getTenantEmail(templateKey)\n if (!entry || !isTenantEmailEditable(entry)) {\n return res.status(400).json({ error: 'Not a designable email template' })\n }\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 const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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 // \"Publish a site’s items to the marketplace\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.sitePublish') })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const templateRef = hostRef\n .collection(TENANT_EMAIL_COLLECTION)\n .doc(templateKey)\n const templateSnapshot = await templateRef.get()\n const activeVersionId = templateSnapshot.get('versionId')\n if (!templateSnapshot.exists || !activeVersionId) {\n return res.status(404).json({\n error: 'This email has no published design yet — design and save it first',\n })\n }\n const versionSnapshot = await templateRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n // Decoded, like the screen and layout publish paths (AGL-1395): the email\n // besigner now compresses through a converter as those do, and versions\n // written before it did are still plain maps, which come back unchanged.\n //\n // `sanitizeMarketplaceDefinition` below would refuse an undecoded tree\n // rather than publish garbage, so this is the difference between the\n // feature working and a publish that always says the design is invalid.\n const stored = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!stored || !Object.keys(stored).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n const rootId = versionSnapshot.get('rootId') ?? EMAIL_NODE_ROOT_ID\n // The site's reusable blocks INLINED (AGL-3287): a listing is installed\n // into another org, which has none of this site's components, and the\n // sanitizer below refuses a component reference outright.\n const inlined = await inlineReusableBlocks(stored, {\n firestore,\n hostId,\n rootId,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n const nodes = inlined.nodes\n // Emails are built from `plugins-email` blocks only, so the page allowlist\n // is REPLACED rather than extended — see MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST\n // for why `emailHtml` is not on the list.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n { componentIds: MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (source site, template key).\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('emailTemplateKey', '==', templateKey)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailTemplate',\n sourceHostId: hostId,\n emailTemplateKey: templateKey,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n emailTemplateKey: templateKey,\n // The copy fields are part of the design, not the tree.\n subject: String(templateSnapshot.get('subject') ?? ''),\n preheader: String(templateSnapshot.get('preheader') ?? ''),\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Publish failed' })\n }\n}\n\nexport default publishEmailTemplateHandler\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","displayNameSearchFields","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","EMAIL_NODE_ROOT_ID","getTenantEmail","isTenantEmailEditable","TENANT_EMAIL_COLLECTION","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailTemplateHandler","req","res","method","status","json","error","hostId","String","body","templateKey","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","entry","authorization","headers","idToken","startsWith","length","undefined","versionSnapshot","existing","orgForHost","templateSnapshot","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","hostSnapshot","get","exists","org","orgId","publisher","refusal","sells","templateRef","activeVersionId","stored","Object","keys","rootId","inlined","ok","nodes","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","emailTemplateKey","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AACtH,SAASC,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,EACrBC,uBAAuB,QAClB,2BAA0B;AACjC,SACEC,wCAAwC,EACxCC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,8BAAgD,OAC3DC,KACAC;iDA8B6BD;QAzBPA,WACKA,YACAA,YACAA,YACHA,YACWA;IARnC,IAA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