@aglyn/plugins-marketplace 1.0.0-beta.199 → 1.0.0-beta.201

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 (59) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/marketplace-browse.component.js +104 -169
  3. package/src/lib/components/marketplace-browse.component.js.map +1 -1
  4. package/src/lib/components/marketplace-reports-page.component.js +9 -0
  5. package/src/lib/components/marketplace-reports-page.component.js.map +1 -1
  6. package/src/lib/components/org-licences-panel.component.js +212 -170
  7. package/src/lib/components/org-licences-panel.component.js.map +1 -1
  8. package/src/lib/components/org-seller-panel.component.js +23 -5
  9. package/src/lib/components/org-seller-panel.component.js.map +1 -1
  10. package/src/lib/components/plugin-reviews-queue.component.d.ts +9 -0
  11. package/src/lib/components/plugin-reviews-queue.component.js +190 -114
  12. package/src/lib/components/plugin-reviews-queue.component.js.map +1 -1
  13. package/src/lib/hooks/use-listing-name-lookup.d.ts +34 -0
  14. package/src/lib/hooks/use-listing-name-lookup.js +131 -0
  15. package/src/lib/hooks/use-listing-name-lookup.js.map +1 -0
  16. package/src/lib/model/listing-query.d.ts +140 -0
  17. package/src/lib/model/listing-query.js +393 -0
  18. package/src/lib/model/listing-query.js.map +1 -0
  19. package/src/lib/model/marketplace.d.ts +11 -0
  20. package/src/lib/model/marketplace.js.map +1 -1
  21. package/src/lib/server/admin-reports.js +30 -12
  22. package/src/lib/server/admin-reports.js.map +1 -1
  23. package/src/lib/server/admin-reviews.js +180 -128
  24. package/src/lib/server/admin-reviews.js.map +1 -1
  25. package/src/lib/server/admin-trust.js +2 -1
  26. package/src/lib/server/admin-trust.js.map +1 -1
  27. package/src/lib/server/billing-webhook.js +13 -1
  28. package/src/lib/server/billing-webhook.js.map +1 -1
  29. package/src/lib/server/checkout.js +3 -1
  30. package/src/lib/server/checkout.js.map +1 -1
  31. package/src/lib/server/install-email-starter.js +9 -2
  32. package/src/lib/server/install-email-starter.js.map +1 -1
  33. package/src/lib/server/install-layout.js +17 -5
  34. package/src/lib/server/install-layout.js.map +1 -1
  35. package/src/lib/server/install-template.js +15 -5
  36. package/src/lib/server/install-template.js.map +1 -1
  37. package/src/lib/server/install.js +10 -2
  38. package/src/lib/server/install.js.map +1 -1
  39. package/src/lib/server/listing-query-fields.d.ts +38 -0
  40. package/src/lib/server/listing-query-fields.js +50 -0
  41. package/src/lib/server/listing-query-fields.js.map +1 -0
  42. package/src/lib/server/publish-dataset-schema.js +6 -2
  43. package/src/lib/server/publish-dataset-schema.js.map +1 -1
  44. package/src/lib/server/publish-email-starter.js +6 -2
  45. package/src/lib/server/publish-email-starter.js.map +1 -1
  46. package/src/lib/server/publish-email-template.js +6 -2
  47. package/src/lib/server/publish-email-template.js.map +1 -1
  48. package/src/lib/server/publish-layout.js +6 -2
  49. package/src/lib/server/publish-layout.js.map +1 -1
  50. package/src/lib/server/publish-plugin.js +75 -7
  51. package/src/lib/server/publish-plugin.js.map +1 -1
  52. package/src/lib/server/publish-template.js +6 -2
  53. package/src/lib/server/publish-template.js.map +1 -1
  54. package/src/lib/server/publish-theme.js +6 -2
  55. package/src/lib/server/publish-theme.js.map +1 -1
  56. package/src/lib/server/publish.js +6 -2
  57. package/src/lib/server/publish.js.map +1 -1
  58. package/src/lib/server/update-artifact.js +18 -4
  59. package/src/lib/server/update-artifact.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/checkout.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { connectLinkageIsReady } from '@aglyn/tenant-data-admin/server/stripe-account-mode'\nimport {\n buildRoute,\n checkEntitlement,\n claimAttempt,\n isListingWideRevocation,\n resolveMarketplaceFeePct,\n Route,\n type AttemptClaim,\n type PluginApiHandler,\n type PluginRevocation,\n} from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { isListingBrowsable, isPrivateListing } from '../model/marketplace'\nimport {\n canActAsPublisher,\n resolvePublisherProfile,\n} from './publisher-profile'\nimport { hasLivePurchase } from './purchase-entitlement'\n\n/**\n * THE TAX CLASSIFICATION OF A MARKETPLACE SALE (AGL-1553).\n *\n * \"Software as a service (SaaS) — business use\". Sent explicitly on the line\n * item below, because this session builds its product ad hoc from\n * `price_data` and an ad-hoc product with no `tax_code` is classified by the\n * ACCOUNT-LEVEL preset instead — a value set by hand in the Stripe Dashboard\n * for Aglyn's own subscription products (AGL-1537/1877), which happens to be\n * this same string.\n *\n * So this is not a change of tax position, and deliberately not: it is the\n * position Aglyn already collects on, already verified, and already states in\n * a signed filing. The pending Texas private letter ruling request proposes at\n * Part 6.1 that plugin charges are DATA PROCESSING SERVICES under Tax Code\n * § 151.0035, of which § 151.351 exempts 20%, so tax is due on 80% of the\n * charge; Part 4.5 ¶ 4 represents to the Comptroller that \"the payment\n * processor's tax classification applied to these charges is the\n * software-as-a-service category\" and that the 80% measure was confirmed by\n * computation. AGL-1817 ran that computation against the live account: $6.60\n * of tax on a $100.00 charge at an 8.25% Texas address — 8.25% x $80.\n *\n * What was actually broken is that none of that was expressed HERE. The\n * classification of every marketplace sale hung on a Dashboard field owned by\n * a different product line. Re-preset the account for storefront goods or\n * bookings and these sales silently re-classify, moving the Texas base off the\n * 80% the filing describes — with no diff to review, no failing test, and no\n * symptom short of reconciling a return. Naming it here is what makes the\n * filed representation survive a Dashboard edit.\n *\n * NOT merged with `PLATFORM_TAX_CODE` in `tools/scripts/lib/stripe-tax-code.mjs`,\n * which stamps Aglyn's OWN products with the same string today. They answer\n * different questions — Aglyn's first-party subscription vs. a third party's\n * sale through Aglyn's marketplace — and the ruling request itself flags at\n * Part 8 ¶ 8 that the Comptroller could characterize the two differently. One\n * shared constant would make a divergence the filing anticipates impossible to\n * express without touching the other business.\n *\n * DO NOT change this value to a downloadable-software code (`txcd_10202003`,\n * `txcd_10203001`) on the reasoning that a plugin is \"downloaded\". That is the\n * OPPOSING characterization — tangible personal property under Rule 3.308,\n * taxable in full — which Part 6.1 argues against and which the filing already\n * states against itself, in full, at Part 8 ¶¶ 1-2. Adopting\n * it here would raise the tax charged to every buyer by a quarter of the base\n * and make Part 4.5 ¶ 4 false. It is the Comptroller's call, and if the ruling\n * goes that way the change is a one-line edit at this constant plus a\n * prospective conformance — which is exactly what naming it here buys.\n */\nexport const MARKETPLACE_TAX_CODE = 'txcd_10103001'\n\n/**\n * Checkout for a paid marketplace listing (AGL-46): one-time destination\n * charge to the publisher's Express account. The platform's cut comes from\n * the seller org's ENTITLEMENTS (AGL-1543: 20%, 30% effective-free), sales\n * tax is collected platform-side per the marketplace-provider registration\n * (AGL-1544), and the seller receives a fixed transfer of their pre-tax\n * share. The webhook writes the purchase record on\n * `checkout.session.completed`; install stays gated on that record. 501\n * without Stripe env.\n */\nexport const checkoutHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Purchases are not configured (STRIPE_SECRET_KEY).' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n // The org this licence is being bought FOR (AGL-2331). Requested, never\n // trusted: it is resolved through the caller's own membership below, exactly\n // as `connect.ts` resolves the org a payout account is being set up for.\n const requestedOrgId = String(req.body?.orgId ?? '')\n // One purchase attempt, minted by the browser (AGL-1697). Node lowercases\n // incoming headers, but read both spellings — the plugin API request type\n // makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!listingId) return res.status(400).json({ error: 'Missing listingId' })\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 let claim: AttemptClaim | null = null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n // WHICH ORGANIZATION IS BUYING (AGL-2331).\n //\n // A marketplace purchase licenses an organization, not a person — see\n // `purchaseEntitlesOrg` in the model for why, and for what the published\n // Publisher Agreement §8.1 already says about it. So a Checkout session\n // that cannot name the org it licenses must not open: the purchase\n // document it produces would carry no `buyerOrgId`, and a half-populated\n // org field is a worse premise for an entitlement than an absent one —\n // the gate would have to guess whether a missing value means \"legacy,\n // grandfathered\" or \"modern, but nobody wrote it\".\n //\n // Resolved through `resolveOrgPermissions`, not from the body and not from\n // `hostIndex`. The old derivation was `hostId` → `hostIndex.orgId` with no\n // membership test at all, which is a real hole once the field grants\n // anything: post any host id and the purchase would be stamped with an org\n // the buyer has no standing in, entitling strangers. This is the same\n // resolution the seven install routes and `connect.ts` use, so the org\n // that gets the licence is by construction an org the buyer could install\n // into.\n //\n // `installPlugins` rather than a bare membership: buying is the act of\n // acquiring something to install, and a viewer who cannot install must not\n // be able to spend the workspace's money on one. It is also what keeps\n // this door and the install door agreeing about who the licence is for.\n const membership = await resolveOrgPermissions(decoded.uid, {\n orgId: requestedOrgId || null,\n hostId: requestedOrgId ? null : hostId || null,\n })\n const buyerOrgId = membership.orgId ?? ''\n if (!buyerOrgId) {\n return res.status(400).json({\n error:\n 'A purchase is licensed to an organization — open the marketplace ' +\n 'from the workspace you are buying for.',\n })\n }\n if (requestedOrgId && buyerOrgId !== requestedOrgId) {\n return res.status(403).json({ error: 'Not a member of that organization' })\n }\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 listingSnapshot = await firestore\n .collection('marketplaceListings')\n .doc(listingId)\n .get()\n const listing = listingSnapshot.data() as any\n if (!listing || listing.deletedAt) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // Review gating holds on the PAID path too (AGL-1543): browse hides\n // rejected/submitted/in_review listings, so a direct checkout call must\n // not be a side door that takes money for one. Absent = legacy = listed\n // (AGL-432), and the same 404 as an unknown listing — purchasability is\n // not a probe for review state.\n const reviewStatus = listing.reviewStatus as string | undefined\n if (reviewStatus && reviewStatus !== 'listed' && reviewStatus !== 'verified') {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A TAKEN-DOWN or PRIVATE listing is not on sale (AGL-2288).\n //\n // The check above is a hand-rolled subset of `isListingBrowsable`, and\n // the two lines it dropped are the two that matter here: `hiddenAt` and\n // `isPrivateListing`. A staff takedown does NOT set a blocking\n // `reviewStatus` — `plugin-reviews` demotes a verified listing to\n // `VERIFIED_STRIPPED_STATUS`, which is literally `'listed'` — so after a\n // takedown this route read `reviewStatus: 'listed'` and sold the listing\n // in full, while `install-plugin` refused the very same listing at\n // `hiddenAt` with a 404. The buyer was charged for something the platform\n // had already decided nobody may install, and the only way out was a\n // refund — which is Aglyn's Stripe fee, Aglyn's support time, and (until\n // the partial-refund fix) a real hole in the split.\n //\n // Both tests are kept rather than replaced by the shared predicate: for a\n // NON-plugin artifact `isListingBrowsable` returns true whatever the\n // review status says, because pre-publication review is plugin-only. This\n // route has always been stricter than that, and a sale is the wrong place\n // to loosen a gate.\n //\n // No owner exemption, unlike the install routes: `canActAsPublisher`\n // below already refuses a publisher buying their own listing, so the\n // buyer here is never the owner.\n if (!isListingBrowsable(listing) || isPrivateListing(listing)) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const priceUsd = Number(listing.priceUsd ?? 0)\n if (!(priceUsd > 0)) {\n return res.status(400).json({ error: 'Listing is free' })\n }\n // Publishing is org-owned (AGL-652): `profileId` IS the publisher org id.\n const sellerOrgId = String(listing.profileId ?? '')\n if (await canActAsPublisher(firestore, decoded.uid, sellerOrgId)) {\n return res.status(400).json({ error: 'Your organization published this listing' })\n }\n // You cannot buy the same component twice (AGL-1697).\n //\n // This route validated review status, self-purchase and the seller's\n // entitlements, and then never asked the one question the buyer cares\n // about: do they already own it. A marketplace listing is a buy-once good —\n // a second purchase buys nothing, since `requirePurchase` is satisfied by\n // the first — so a buyer who clicked Buy again from a stale tab, or came\n // back through a bookmarked checkout, was simply charged twice for it.\n //\n // Deliberately the SAME predicate the seven install routes gate on\n // (AGL-1546/1699) rather than a second query beside it: \"has this buyer\n // paid for this listing\" must have one answer, or the marketplace can take\n // money for something it will not install, or refuse to sell something it\n // will not install either. That predicate reads a fully REFUNDED purchase\n // as absent, which is exactly right here too — a refunded buyer must be\n // able to buy again, and a refunded row sitting beside a live one does not\n // veto it.\n //\n // 409 rather than 400: nothing about the request is malformed, the buyer\n // is just asking for a state that already holds.\n //\n // KEYED ON THE ORGANIZATION SINCE AGL-2331, and that is what turns this\n // guard from a blocked sale back into a real one. A licence belongs to a\n // workspace, so an agency developer who bought a component for one client\n // must be able to buy it again for the next — the person-keyed version of\n // this check answered `409 already_purchased` to exactly the second sale\n // we want. It still refuses the case it was written for: the same\n // workspace buying the same listing twice.\n //\n // A pre-AGL-2331 purchase still refuses, through the legacy grant inside\n // the shared predicate: that buyer can already install this listing\n // anywhere, so selling them a second copy would take money for nothing.\n if (\n await hasLivePurchase({\n firestore,\n buyerUid: decoded.uid,\n buyerOrgId,\n listingId,\n })\n ) {\n return res.status(409).json({\n error:\n 'This organization already owns this listing — install it from ' +\n 'your library.',\n code: 'already_purchased',\n })\n }\n // The kill switch, on the SELL side too (AGL-2288).\n //\n // `revocations/{listingId}` with `versions: 'all'` is the listing-wide\n // kill: `install-plugin` 409s on it through this same predicate, and the\n // tenant runtime renders the disabled placeholder for anything already\n // pinned. Selling into that state takes money for an artifact the\n // platform has switched off.\n //\n // Only `'all'` is consulted, deliberately. A per-version revocation\n // (AGL-1085) stops one build while other approved versions stay\n // installable, and refusing the sale for it would turn a targeted control\n // into a de-listing. Whether the newest approved version happens to be\n // the revoked one is a question `install-plugin` answers with live data;\n // duplicating that resolution here would be a second copy of it.\n //\n // One extra read on a path that already makes several Firestore and\n // Stripe round trips, and it is the cheap half of the takedown check\n // above: a hand-written revocation doc — which the rules permit any staff\n // client to write — is caught here even when `hiddenAt` was never set.\n const revocation = (\n await firestore.collection('revocations').doc(listingId).get()\n ).data() as PluginRevocation | undefined\n if (isListingWideRevocation(revocation)) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const publisher = await resolvePublisherProfile(firestore, sellerOrgId)\n const accountId = publisher?.stripeAccountId\n if (\n !connectLinkageIsReady(\n {\n accountId,\n chargesEnabled: publisher?.stripeChargesEnabled,\n accountLivemode: publisher?.stripeAccountLivemode,\n },\n { subject: `marketplace publisher org ${sellerOrgId}` },\n )\n ) {\n return res\n .status(409)\n .json({ error: 'The publisher has not enabled payouts yet' })\n }\n\n // The platform's cut comes from ENTITLEMENTS (AGL-1543), never the raw\n // `plan` field: `resolveMarketplaceFeePct` prices a dead subscription\n // as free-plan (30%) while the stale field still says pro, and honors\n // a negotiated per-org `marketplaceFeePct` override. Same read gates\n // SALE time on `marketplaceSelling` — publish already refuses without\n // it, and a publisher who downgrades must stop selling, not merely\n // stop publishing. Resolved per request; entitlements are never cached.\n const sellerOrgDoc = await firestore.collection('orgs').doc(sellerOrgId).get()\n const sellerOrg = (sellerOrgDoc.data() ?? {}) as any\n if (!checkEntitlement(sellerOrg, 'marketplaceSelling')) {\n return res.status(409).json({\n error:\n \"The publisher's current plan does not include marketplace selling\",\n })\n }\n const feePercent = resolveMarketplaceFeePct(sellerOrg)\n const amountCents = Math.round(priceUsd * 100)\n const feeCents = Math.round((amountCents * feePercent) / 100)\n\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe returns the BUYER to the org marketplace (AGL-775) — the\n // per-site marketplace page it used to land on was retired. Only the\n // buyer's org slug is needed now (`sellerOrgId` is the wrong org), and\n // it's resolved from the host here since server code cannot call\n // useConsoleHostRoute. `/manage/marketplace` is the hostless fallback.\n //\n // The slug comes off the VALIDATED buyer org resolved at the top of the\n // handler now (AGL-2331) rather than a second, unvalidated `hostIndex`\n // read: one org id decides where the buyer lands, which org the licence\n // entitles, and which org's erasure sweeps the idempotency claim, so\n // having two derivations of it was a way for those three to disagree.\n const buyerOrgSlug = (\n await firestore.collection('orgs').doc(buyerOrgId).get()\n ).get('slug') as string | undefined\n const returnPath = buyerOrgSlug\n ? buildRoute(Route.ORG_MARKETPLACE, { orgSlug: buyerOrgSlug })\n : Route.ORG_MARKETPLACE\n // Tax + funds flow (AGL-1544). Aglyn registered as a marketplace\n // provider with the Texas Comptroller: it collects and remits sales tax\n // on sellers' behalf. That is the PLATFORM's charge — no `on_behalf_of`,\n // `automatic_tax` on the platform session, tax added ON TOP of the\n // listing price (`tax_behavior: exclusive`) with a full billing address\n // to compute from. The transfer is a FIXED amount (the seller's share of\n // the pre-tax price) rather than `application_fee_amount`, because the\n // fee form makes Stripe transfer `amount_total − fee` — and amount_total\n // includes the tax, which must stay with the platform that owes it.\n const transferCents = amountCents - feeCents\n const params = new URLSearchParams({\n mode: 'payment',\n 'line_items[0][quantity]': '1',\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(amountCents),\n 'line_items[0][price_data][tax_behavior]': 'exclusive',\n 'line_items[0][price_data][product_data][name]': String(\n listing.displayName ?? 'Marketplace component',\n ).slice(0, 120),\n // The classification, stated rather than inherited (AGL-1553). See\n // MARKETPLACE_TAX_CODE above: same value the account preset carries, so\n // the tax computed is unchanged, but it no longer depends on a Dashboard\n // field owned by Aglyn's subscription products.\n 'line_items[0][price_data][product_data][tax_code]': MARKETPLACE_TAX_CODE,\n 'automatic_tax[enabled]': 'true',\n billing_address_collection: 'required',\n 'payment_intent_data[transfer_data][destination]': String(accountId),\n 'payment_intent_data[transfer_data][amount]': String(transferCents),\n // THE DISCRIMINATOR THE REFUND DOOR HAS NO OTHER WAY TO GET (AGL-2148).\n //\n // `metadata[type]` below rides on the SESSION, and `charge.refunded`\n // never sees a session — its object is the charge. The platform\n // endpoint receives `charge.refunded` for storefront orders and\n // subscription charges too, so the webhook cannot tell a marketplace\n // refund from any other one except by joining on the payment intent,\n // which is exactly the join that comes up empty during the window this\n // metadata exists to close (the purchase document is written by\n // `checkout.session.completed`, and that delivery retries).\n //\n // Stripe copies a PaymentIntent's metadata onto the charge it creates,\n // so stamping it here makes `charge.metadata.type` readable straight\n // off the refund event — no Firestore join, no Stripe round trip, and\n // no orphan record written for the commerce and subscription refunds\n // that share this endpoint.\n //\n // `listingId`/`buyerUid` ride along for forensics only: an orphan that\n // never drains is a support case, and the payment intent alone does not\n // say whose purchase of what it was.\n 'payment_intent_data[metadata][type]': 'marketplace-purchase',\n 'payment_intent_data[metadata][listingId]': listingId,\n 'payment_intent_data[metadata][buyerUid]': decoded.uid,\n 'payment_intent_data[metadata][buyerOrgId]': buyerOrgId,\n success_url: `${origin}${returnPath}?purchase=success`,\n cancel_url: `${origin}${returnPath}?purchase=canceled`,\n client_reference_id: decoded.uid,\n 'metadata[type]': 'marketplace-purchase',\n 'metadata[listingId]': listingId,\n 'metadata[buyerUid]': decoded.uid,\n // THE ORG THE LICENCE IS FOR (AGL-2331). The webhook writes the\n // purchase document from this metadata and had no buyer org to write,\n // which is why the entitlement could only ever be person-scoped: the\n // one field the gate needs was never carried across the Stripe\n // boundary. Validated above against the caller's own membership, so a\n // session can never license an org the buyer has no standing in.\n 'metadata[buyerOrgId]': buyerOrgId,\n 'metadata[sellerOrgId]': sellerOrgId,\n 'metadata[feeCents]': String(feeCents),\n 'metadata[transferCents]': String(transferCents),\n // The buyer's GA client id (AGL-1638), so the server-side `purchase`\n // the webhook sends joins the browser session that produced it. The\n // webhook has always READ `metadata.ga_client_id`; nothing wrote it,\n // so the read was dead and every marketplace sale fell through to a\n // synthesized, sessionless GA user — making plugin revenue permanently\n // unattributable to any channel.\n //\n // Carried on the SESSION rather than a subscription because this is a\n // one-time payment; `checkout.session.completed` is where it is read.\n //\n // Validated to GA's `<digits>.<digits>` shape and dropped otherwise:\n // the value is client-supplied and ends up in Stripe metadata, so it is\n // not accepted on trust. Same guard /api/billing/checkout applies.\n ...(/^\\d+\\.\\d+$/.test(String(req.body?.gaClientId ?? ''))\n ? { 'metadata[ga_client_id]': String(req.body.gaClientId) }\n : {}),\n ...(decoded.email ? { customer_email: decoded.email } : {}),\n })\n // Point of no return (AGL-1697). The purchase check above closes the\n // SEQUENTIAL duplicate — a second buy after the webhook has written the\n // first purchase — and cannot close the concurrent one, because between two\n // clicks a second apart there is no purchase record yet to find. The claim\n // is what covers that window: `create()` on a document Firestore refuses to\n // create twice.\n //\n // Scoped to the listing AND the buyer, so two people buying the same\n // component at the same moment never contend, and one person's two tabs\n // always do.\n //\n // The claim is taken here rather than at the top so that every deterministic\n // refusal above it — unknown listing, free listing, self-purchase, already\n // owned, publisher not paid out, seller cannot sell — answers without\n // burning the key. Those are all states a buyer or publisher fixes and then\n // presses the same button again.\n const claimed = await claimAttempt(firestore, {\n kind: 'marketplace-checkout',\n // Scoped to the ORG as well as the buyer since AGL-2331. The scope is\n // what decides which two attempts are allowed to contend, and a\n // licence for one workspace and a licence for another are now two\n // different goods — an agency owner buying for two clients from two\n // tabs must not have one of them read as a double-click of the other.\n scopeId: `${listingId}:${buyerOrgId}:${decoded.uid}`,\n // The BUYER's org, so `eraseOrgIdempotencyKeys` sweeps this with the\n // buyer's data (AGL-1448) — the seller keeps the sale.\n orgId: buyerOrgId,\n key: idempotencyKey,\n busyMessage: 'This purchase is already being processed',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n const response = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // The half that costs real money. Stripe replays the existing\n // session for a repeated key instead of opening a second one, which\n // covers the window where our own claim is written but the response\n // never arrives — the failure this route was most exposed to, since\n // it writes nothing of its own to reconcile against.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as { url?: string; error?: any }\n if (!response.ok || !session.url) {\n console.error('Stripe checkout error', session.error)\n // The purchase did not start — let the same key be tried again rather\n // than locking this buyer out of this listing over one flaky moment.\n await claim.release()\n return res.status(502).json({ error: 'Stripe checkout failed' })\n }\n const payload = { url: session.url }\n // A repeat of this attempt now replays the SAME session url. Better than\n // refusing it: the buyer lands back on the checkout they already had open.\n await claim.record(200, payload)\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Release on the way out so a transient failure does not strand the key\n // and lock the buyer out of this listing until they reload.\n await claim?.release()\n return res.status(500).json({ error: 'Checkout failed' })\n }\n}\n"],"names":["firebaseAdmin","connectLinkageIsReady","buildRoute","checkEntitlement","claimAttempt","isListingWideRevocation","resolveMarketplaceFeePct","Route","resolveOrgPermissions","isListingBrowsable","isPrivateListing","canActAsPublisher","resolvePublisherProfile","hasLivePurchase","MARKETPLACE_TAX_CODE","checkoutHandler","req","res","method","status","json","error","process","env","STRIPE_SECRET_KEY","listingId","String","body","hostId","requestedOrgId","orgId","idempotencyKey","headers","trim","slice","authorization","idToken","startsWith","length","undefined","claim","membership","listing","sellerOrgDoc","decoded","app","auth","verifyIdToken","uid","buyerOrgId","permissions","installPlugins","firestore","listingSnapshot","collection","doc","get","data","deletedAt","reviewStatus","priceUsd","Number","sellerOrgId","profileId","buyerUid","code","revocation","publisher","accountId","stripeAccountId","chargesEnabled","stripeChargesEnabled","accountLivemode","stripeAccountLivemode","subject","sellerOrg","feePercent","amountCents","Math","round","feeCents","origin","host","buyerOrgSlug","returnPath","ORG_MARKETPLACE","orgSlug","transferCents","params","URLSearchParams","mode","displayName","billing_address_collection","success_url","cancel_url","client_reference_id","test","gaClientId","email","customer_email","claimed","kind","scopeId","key","busyMessage","replay","response","fetch","Authorization","stripeKey","toString","session","ok","url","console","release","payload","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,sDAAqD;AAC3F,SACEC,UAAU,EACVC,gBAAgB,EAChBC,YAAY,EACZC,uBAAuB,EACvBC,wBAAwB,EACxBC,KAAK,QAIA,sBAAqB;AAC5B,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,0BAAsB;AAC3E,SACEC,iBAAiB,EACjBC,uBAAuB,QAClB,yBAAqB;AAC5B,SAASC,eAAe,QAAQ,4BAAwB;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GACD,OAAO,MAAMC,uBAAuB,gBAAe;AAEnD;;;;;;;;;CASC,GACD,OAAO,MAAMC,kBAAoC,OAAOC,KAAKC;4BAmBzDD,OAAAA,6BAM2BA;QAhBJA,WACHA,YAIQA;IAb9B,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOP,IACJE,MAAM,CAAC,KACPC,IAAI,CAAC;YAAEC,OAAO;QAAoD;IACvE;IACA,MAAMI,YAAYC,gBAAOV,YAAAA,IAAIW,IAAI,qBAARX,UAAUS,SAAS,mBAAI;IAChD,MAAMG,SAASF,iBAAOV,aAAAA,IAAIW,IAAI,qBAARX,WAAUY,MAAM,oBAAI;IAC1C,wEAAwE;IACxE,6EAA6E;IAC7E,yEAAyE;IACzE,MAAMC,iBA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A4D;QAC5D,OAAMmB,yBAAAA,MAAO2E,OAAO;QACpB,OAAOlG,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAkB;IACzD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/checkout.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { connectLinkageIsReady } from '@aglyn/tenant-data-admin/server/stripe-account-mode'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport {\n buildRoute,\n checkEntitlement,\n claimAttempt,\n isListingWideRevocation,\n resolveMarketplaceFeePct,\n Route,\n type AttemptClaim,\n type PluginApiHandler,\n type PluginRevocation,\n} from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { isListingBrowsable, isPrivateListing } from '../model/marketplace'\nimport {\n canActAsPublisher,\n resolvePublisherProfile,\n} from './publisher-profile'\nimport { hasLivePurchase } from './purchase-entitlement'\n\n/**\n * THE TAX CLASSIFICATION OF A MARKETPLACE SALE (AGL-1553).\n *\n * \"Software as a service (SaaS) — business use\". Sent explicitly on the line\n * item below, because this session builds its product ad hoc from\n * `price_data` and an ad-hoc product with no `tax_code` is classified by the\n * ACCOUNT-LEVEL preset instead — a value set by hand in the Stripe Dashboard\n * for Aglyn's own subscription products (AGL-1537/1877), which happens to be\n * this same string.\n *\n * So this is not a change of tax position, and deliberately not: it is the\n * position Aglyn already collects on, already verified, and already states in\n * a signed filing. The pending Texas private letter ruling request proposes at\n * Part 6.1 that plugin charges are DATA PROCESSING SERVICES under Tax Code\n * § 151.0035, of which § 151.351 exempts 20%, so tax is due on 80% of the\n * charge; Part 4.5 ¶ 4 represents to the Comptroller that \"the payment\n * processor's tax classification applied to these charges is the\n * software-as-a-service category\" and that the 80% measure was confirmed by\n * computation. AGL-1817 ran that computation against the live account: $6.60\n * of tax on a $100.00 charge at an 8.25% Texas address — 8.25% x $80.\n *\n * What was actually broken is that none of that was expressed HERE. The\n * classification of every marketplace sale hung on a Dashboard field owned by\n * a different product line. Re-preset the account for storefront goods or\n * bookings and these sales silently re-classify, moving the Texas base off the\n * 80% the filing describes — with no diff to review, no failing test, and no\n * symptom short of reconciling a return. Naming it here is what makes the\n * filed representation survive a Dashboard edit.\n *\n * NOT merged with `PLATFORM_TAX_CODE` in `tools/scripts/lib/stripe-tax-code.mjs`,\n * which stamps Aglyn's OWN products with the same string today. They answer\n * different questions — Aglyn's first-party subscription vs. a third party's\n * sale through Aglyn's marketplace — and the ruling request itself flags at\n * Part 8 ¶ 8 that the Comptroller could characterize the two differently. One\n * shared constant would make a divergence the filing anticipates impossible to\n * express without touching the other business.\n *\n * DO NOT change this value to a downloadable-software code (`txcd_10202003`,\n * `txcd_10203001`) on the reasoning that a plugin is \"downloaded\". That is the\n * OPPOSING characterization — tangible personal property under Rule 3.308,\n * taxable in full — which Part 6.1 argues against and which the filing already\n * states against itself, in full, at Part 8 ¶¶ 1-2. Adopting\n * it here would raise the tax charged to every buyer by a quarter of the base\n * and make Part 4.5 ¶ 4 false. It is the Comptroller's call, and if the ruling\n * goes that way the change is a one-line edit at this constant plus a\n * prospective conformance — which is exactly what naming it here buys.\n */\nexport const MARKETPLACE_TAX_CODE = 'txcd_10103001'\n\n/**\n * Checkout for a paid marketplace listing (AGL-46): one-time destination\n * charge to the publisher's Express account. The platform's cut comes from\n * the seller org's ENTITLEMENTS (AGL-1543: 20%, 30% effective-free), sales\n * tax is collected platform-side per the marketplace-provider registration\n * (AGL-1544), and the seller receives a fixed transfer of their pre-tax\n * share. The webhook writes the purchase record on\n * `checkout.session.completed`; install stays gated on that record. 501\n * without Stripe env.\n */\nexport const checkoutHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Purchases are not configured (STRIPE_SECRET_KEY).' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n // The org this licence is being bought FOR (AGL-2331). Requested, never\n // trusted: it is resolved through the caller's own membership below, exactly\n // as `connect.ts` resolves the org a payout account is being set up for.\n const requestedOrgId = String(req.body?.orgId ?? '')\n // One purchase attempt, minted by the browser (AGL-1697). Node lowercases\n // incoming headers, but read both spellings — the plugin API request type\n // makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!listingId) return res.status(400).json({ error: 'Missing listingId' })\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 let claim: AttemptClaim | null = null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n // WHICH ORGANIZATION IS BUYING (AGL-2331).\n //\n // A marketplace purchase licenses an organization, not a person — see\n // `purchaseEntitlesOrg` in the model for why, and for what the published\n // Publisher Agreement §8.1 already says about it. So a Checkout session\n // that cannot name the org it licenses must not open: the purchase\n // document it produces would carry no `buyerOrgId`, and a half-populated\n // org field is a worse premise for an entitlement than an absent one —\n // the gate would have to guess whether a missing value means \"legacy,\n // grandfathered\" or \"modern, but nobody wrote it\".\n //\n // Resolved through `resolveOrgPermissions`, not from the body and not from\n // `hostIndex`. The old derivation was `hostId` → `hostIndex.orgId` with no\n // membership test at all, which is a real hole once the field grants\n // anything: post any host id and the purchase would be stamped with an org\n // the buyer has no standing in, entitling strangers. This is the same\n // resolution the seven install routes and `connect.ts` use, so the org\n // that gets the licence is by construction an org the buyer could install\n // into.\n //\n // `installPlugins` rather than a bare membership: buying is the act of\n // acquiring something to install, and a viewer who cannot install must not\n // be able to spend the workspace's money on one. It is also what keeps\n // this door and the install door agreeing about who the licence is for.\n const membership = await resolveOrgPermissions(decoded.uid, {\n orgId: requestedOrgId || null,\n hostId: requestedOrgId ? null : hostId || null,\n })\n const buyerOrgId = membership.orgId ?? ''\n if (!buyerOrgId) {\n return res.status(400).json({\n error:\n 'A purchase is licensed to an organization — open the marketplace ' +\n 'from the workspace you are buying for.',\n })\n }\n if (requestedOrgId && buyerOrgId !== requestedOrgId) {\n return res.status(403).json({ error: 'Not a member of that organization' })\n }\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 listingSnapshot = await firestore\n .collection('marketplaceListings')\n .doc(listingId)\n .get()\n const listing = listingSnapshot.data() as any\n if (!listing || listing.deletedAt) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // Review gating holds on the PAID path too (AGL-1543): browse hides\n // rejected/submitted/in_review listings, so a direct checkout call must\n // not be a side door that takes money for one. Absent = legacy = listed\n // (AGL-432), and the same 404 as an unknown listing — purchasability is\n // not a probe for review state.\n const reviewStatus = listing.reviewStatus as string | undefined\n if (reviewStatus && reviewStatus !== 'listed' && reviewStatus !== 'verified') {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A TAKEN-DOWN or PRIVATE listing is not on sale (AGL-2288).\n //\n // The check above is a hand-rolled subset of `isListingBrowsable`, and\n // the two lines it dropped are the two that matter here: `hiddenAt` and\n // `isPrivateListing`. A staff takedown does NOT set a blocking\n // `reviewStatus` — `plugin-reviews` demotes a verified listing to\n // `VERIFIED_STRIPPED_STATUS`, which is literally `'listed'` — so after a\n // takedown this route read `reviewStatus: 'listed'` and sold the listing\n // in full, while `install-plugin` refused the very same listing at\n // `hiddenAt` with a 404. The buyer was charged for something the platform\n // had already decided nobody may install, and the only way out was a\n // refund — which is Aglyn's Stripe fee, Aglyn's support time, and (until\n // the partial-refund fix) a real hole in the split.\n //\n // Both tests are kept rather than replaced by the shared predicate: for a\n // NON-plugin artifact `isListingBrowsable` returns true whatever the\n // review status says, because pre-publication review is plugin-only. This\n // route has always been stricter than that, and a sale is the wrong place\n // to loosen a gate.\n //\n // No owner exemption, unlike the install routes: `canActAsPublisher`\n // below already refuses a publisher buying their own listing, so the\n // buyer here is never the owner.\n if (!isListingBrowsable(listing) || isPrivateListing(listing)) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const priceUsd = Number(listing.priceUsd ?? 0)\n if (!(priceUsd > 0)) {\n return res.status(400).json({ error: 'Listing is free' })\n }\n // Publishing is org-owned (AGL-652): `profileId` IS the publisher org id.\n const sellerOrgId = String(listing.profileId ?? '')\n if (await canActAsPublisher(firestore, decoded.uid, sellerOrgId)) {\n return res.status(400).json({ error: 'Your organization published this listing' })\n }\n // You cannot buy the same component twice (AGL-1697).\n //\n // This route validated review status, self-purchase and the seller's\n // entitlements, and then never asked the one question the buyer cares\n // about: do they already own it. A marketplace listing is a buy-once good —\n // a second purchase buys nothing, since `requirePurchase` is satisfied by\n // the first — so a buyer who clicked Buy again from a stale tab, or came\n // back through a bookmarked checkout, was simply charged twice for it.\n //\n // Deliberately the SAME predicate the seven install routes gate on\n // (AGL-1546/1699) rather than a second query beside it: \"has this buyer\n // paid for this listing\" must have one answer, or the marketplace can take\n // money for something it will not install, or refuse to sell something it\n // will not install either. That predicate reads a fully REFUNDED purchase\n // as absent, which is exactly right here too — a refunded buyer must be\n // able to buy again, and a refunded row sitting beside a live one does not\n // veto it.\n //\n // 409 rather than 400: nothing about the request is malformed, the buyer\n // is just asking for a state that already holds.\n //\n // KEYED ON THE ORGANIZATION SINCE AGL-2331, and that is what turns this\n // guard from a blocked sale back into a real one. A licence belongs to a\n // workspace, so an agency developer who bought a component for one client\n // must be able to buy it again for the next — the person-keyed version of\n // this check answered `409 already_purchased` to exactly the second sale\n // we want. It still refuses the case it was written for: the same\n // workspace buying the same listing twice.\n //\n // A pre-AGL-2331 purchase still refuses, through the legacy grant inside\n // the shared predicate: that buyer can already install this listing\n // anywhere, so selling them a second copy would take money for nothing.\n if (\n await hasLivePurchase({\n firestore,\n buyerUid: decoded.uid,\n buyerOrgId,\n listingId,\n })\n ) {\n return res.status(409).json({\n error:\n 'This organization already owns this listing — install it from ' +\n 'your library.',\n code: 'already_purchased',\n })\n }\n // The kill switch, on the SELL side too (AGL-2288).\n //\n // `revocations/{listingId}` with `versions: 'all'` is the listing-wide\n // kill: `install-plugin` 409s on it through this same predicate, and the\n // tenant runtime renders the disabled placeholder for anything already\n // pinned. Selling into that state takes money for an artifact the\n // platform has switched off.\n //\n // Only `'all'` is consulted, deliberately. A per-version revocation\n // (AGL-1085) stops one build while other approved versions stay\n // installable, and refusing the sale for it would turn a targeted control\n // into a de-listing. Whether the newest approved version happens to be\n // the revoked one is a question `install-plugin` answers with live data;\n // duplicating that resolution here would be a second copy of it.\n //\n // One extra read on a path that already makes several Firestore and\n // Stripe round trips, and it is the cheap half of the takedown check\n // above: a hand-written revocation doc — which the rules permit any staff\n // client to write — is caught here even when `hiddenAt` was never set.\n const revocation = (\n await firestore.collection('revocations').doc(listingId).get()\n ).data() as PluginRevocation | undefined\n if (isListingWideRevocation(revocation)) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const publisher = await resolvePublisherProfile(firestore, sellerOrgId)\n const accountId = publisher?.stripeAccountId\n if (\n !connectLinkageIsReady(\n {\n accountId,\n chargesEnabled: publisher?.stripeChargesEnabled,\n accountLivemode: publisher?.stripeAccountLivemode,\n },\n { subject: `marketplace publisher org ${sellerOrgId}` },\n )\n ) {\n return res\n .status(409)\n .json({ error: 'The publisher has not enabled payouts yet' })\n }\n\n // The platform's cut comes from ENTITLEMENTS (AGL-1543), never the raw\n // `plan` field: `resolveMarketplaceFeePct` prices a dead subscription\n // as free-plan (30%) while the stale field still says pro, and honors\n // a negotiated per-org `marketplaceFeePct` override. Same read gates\n // SALE time on `marketplaceSelling` — publish already refuses without\n // it, and a publisher who downgrades must stop selling, not merely\n // stop publishing. Resolved per request; entitlements are never cached.\n const sellerOrgDoc = await firestore.collection('orgs').doc(sellerOrgId).get()\n const sellerOrg = (sellerOrgDoc.data() ?? {}) as any\n if (!checkEntitlement(sellerOrg, 'marketplaceSelling')) {\n return res.status(409).json({\n error:\n \"The publisher's current plan does not include marketplace selling\",\n })\n }\n const feePercent = resolveMarketplaceFeePct(sellerOrg)\n const amountCents = Math.round(priceUsd * 100)\n const feeCents = Math.round((amountCents * feePercent) / 100)\n\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe returns the BUYER to the org marketplace (AGL-775) — the\n // per-site marketplace page it used to land on was retired. Only the\n // buyer's org slug is needed now (`sellerOrgId` is the wrong org), and\n // it's resolved from the host here since server code cannot call\n // useConsoleHostRoute. `/manage/marketplace` is the hostless fallback.\n //\n // The slug comes off the VALIDATED buyer org resolved at the top of the\n // handler now (AGL-2331) rather than a second, unvalidated `hostIndex`\n // read: one org id decides where the buyer lands, which org the licence\n // entitles, and which org's erasure sweeps the idempotency claim, so\n // having two derivations of it was a way for those three to disagree.\n const buyerOrgSlug = (\n await firestore.collection('orgs').doc(buyerOrgId).get()\n ).get('slug') as string | undefined\n const returnPath = buyerOrgSlug\n ? buildRoute(Route.ORG_MARKETPLACE, { orgSlug: buyerOrgSlug })\n : Route.ORG_MARKETPLACE\n // Tax + funds flow (AGL-1544). Aglyn registered as a marketplace\n // provider with the Texas Comptroller: it collects and remits sales tax\n // on sellers' behalf. That is the PLATFORM's charge — no `on_behalf_of`,\n // `automatic_tax` on the platform session, tax added ON TOP of the\n // listing price (`tax_behavior: exclusive`) with a full billing address\n // to compute from. The transfer is a FIXED amount (the seller's share of\n // the pre-tax price) rather than `application_fee_amount`, because the\n // fee form makes Stripe transfer `amount_total − fee` — and amount_total\n // includes the tax, which must stay with the platform that owes it.\n const transferCents = amountCents - feeCents\n const params = new URLSearchParams({\n mode: 'payment',\n // 3-D Secure, from the one seam every card payment shares (AGL-3360).\n ...checkoutSessionCardAuthenticationParams('payment'),\n 'line_items[0][quantity]': '1',\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(amountCents),\n 'line_items[0][price_data][tax_behavior]': 'exclusive',\n 'line_items[0][price_data][product_data][name]': String(\n listing.displayName ?? 'Marketplace component',\n ).slice(0, 120),\n // The classification, stated rather than inherited (AGL-1553). See\n // MARKETPLACE_TAX_CODE above: same value the account preset carries, so\n // the tax computed is unchanged, but it no longer depends on a Dashboard\n // field owned by Aglyn's subscription products.\n 'line_items[0][price_data][product_data][tax_code]': MARKETPLACE_TAX_CODE,\n 'automatic_tax[enabled]': 'true',\n billing_address_collection: 'required',\n 'payment_intent_data[transfer_data][destination]': String(accountId),\n 'payment_intent_data[transfer_data][amount]': String(transferCents),\n // THE DISCRIMINATOR THE REFUND DOOR HAS NO OTHER WAY TO GET (AGL-2148).\n //\n // `metadata[type]` below rides on the SESSION, and `charge.refunded`\n // never sees a session — its object is the charge. The platform\n // endpoint receives `charge.refunded` for storefront orders and\n // subscription charges too, so the webhook cannot tell a marketplace\n // refund from any other one except by joining on the payment intent,\n // which is exactly the join that comes up empty during the window this\n // metadata exists to close (the purchase document is written by\n // `checkout.session.completed`, and that delivery retries).\n //\n // Stripe copies a PaymentIntent's metadata onto the charge it creates,\n // so stamping it here makes `charge.metadata.type` readable straight\n // off the refund event — no Firestore join, no Stripe round trip, and\n // no orphan record written for the commerce and subscription refunds\n // that share this endpoint.\n //\n // `listingId`/`buyerUid` ride along for forensics only: an orphan that\n // never drains is a support case, and the payment intent alone does not\n // say whose purchase of what it was.\n 'payment_intent_data[metadata][type]': 'marketplace-purchase',\n 'payment_intent_data[metadata][listingId]': listingId,\n 'payment_intent_data[metadata][buyerUid]': decoded.uid,\n 'payment_intent_data[metadata][buyerOrgId]': buyerOrgId,\n success_url: `${origin}${returnPath}?purchase=success`,\n cancel_url: `${origin}${returnPath}?purchase=canceled`,\n client_reference_id: decoded.uid,\n 'metadata[type]': 'marketplace-purchase',\n 'metadata[listingId]': listingId,\n 'metadata[buyerUid]': decoded.uid,\n // THE ORG THE LICENCE IS FOR (AGL-2331). The webhook writes the\n // purchase document from this metadata and had no buyer org to write,\n // which is why the entitlement could only ever be person-scoped: the\n // one field the gate needs was never carried across the Stripe\n // boundary. Validated above against the caller's own membership, so a\n // session can never license an org the buyer has no standing in.\n 'metadata[buyerOrgId]': buyerOrgId,\n 'metadata[sellerOrgId]': sellerOrgId,\n 'metadata[feeCents]': String(feeCents),\n 'metadata[transferCents]': String(transferCents),\n // The buyer's GA client id (AGL-1638), so the server-side `purchase`\n // the webhook sends joins the browser session that produced it. The\n // webhook has always READ `metadata.ga_client_id`; nothing wrote it,\n // so the read was dead and every marketplace sale fell through to a\n // synthesized, sessionless GA user — making plugin revenue permanently\n // unattributable to any channel.\n //\n // Carried on the SESSION rather than a subscription because this is a\n // one-time payment; `checkout.session.completed` is where it is read.\n //\n // Validated to GA's `<digits>.<digits>` shape and dropped otherwise:\n // the value is client-supplied and ends up in Stripe metadata, so it is\n // not accepted on trust. Same guard /api/billing/checkout applies.\n ...(/^\\d+\\.\\d+$/.test(String(req.body?.gaClientId ?? ''))\n ? { 'metadata[ga_client_id]': String(req.body.gaClientId) }\n : {}),\n ...(decoded.email ? { customer_email: decoded.email } : {}),\n })\n // Point of no return (AGL-1697). The purchase check above closes the\n // SEQUENTIAL duplicate — a second buy after the webhook has written the\n // first purchase — and cannot close the concurrent one, because between two\n // clicks a second apart there is no purchase record yet to find. The claim\n // is what covers that window: `create()` on a document Firestore refuses to\n // create twice.\n //\n // Scoped to the listing AND the buyer, so two people buying the same\n // component at the same moment never contend, and one person's two tabs\n // always do.\n //\n // The claim is taken here rather than at the top so that every deterministic\n // refusal above it — unknown listing, free listing, self-purchase, already\n // owned, publisher not paid out, seller cannot sell — answers without\n // burning the key. Those are all states a buyer or publisher fixes and then\n // presses the same button again.\n const claimed = await claimAttempt(firestore, {\n kind: 'marketplace-checkout',\n // Scoped to the ORG as well as the buyer since AGL-2331. The scope is\n // what decides which two attempts are allowed to contend, and a\n // licence for one workspace and a licence for another are now two\n // different goods — an agency owner buying for two clients from two\n // tabs must not have one of them read as a double-click of the other.\n scopeId: `${listingId}:${buyerOrgId}:${decoded.uid}`,\n // The BUYER's org, so `eraseOrgIdempotencyKeys` sweeps this with the\n // buyer's data (AGL-1448) — the seller keeps the sale.\n orgId: buyerOrgId,\n key: idempotencyKey,\n busyMessage: 'This purchase is already being processed',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n const response = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // The half that costs real money. Stripe replays the existing\n // session for a repeated key instead of opening a second one, which\n // covers the window where our own claim is written but the response\n // never arrives — the failure this route was most exposed to, since\n // it writes nothing of its own to reconcile against.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as { url?: string; error?: any }\n if (!response.ok || !session.url) {\n console.error('Stripe checkout error', session.error)\n // The purchase did not start — let the same key be tried again rather\n // than locking this buyer out of this listing over one flaky moment.\n await claim.release()\n return res.status(502).json({ error: 'Stripe checkout failed' })\n }\n const payload = { url: session.url }\n // A repeat of this attempt now replays the SAME session url. Better than\n // refusing it: the buyer lands back on the checkout they already had open.\n await claim.record(200, payload)\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Release on the way out so a transient failure does not strand the key\n // and lock the buyer out of this listing until they reload.\n await claim?.release()\n return res.status(500).json({ error: 'Checkout failed' })\n }\n}\n"],"names":["firebaseAdmin","connectLinkageIsReady","checkoutSessionCardAuthenticationParams","buildRoute","checkEntitlement","claimAttempt","isListingWideRevocation","resolveMarketplaceFeePct","Route","resolveOrgPermissions","isListingBrowsable","isPrivateListing","canActAsPublisher","resolvePublisherProfile","hasLivePurchase","MARKETPLACE_TAX_CODE","checkoutHandler","req","res","method","status","json","error","process","env","STRIPE_SECRET_KEY","listingId","String","body","hostId","requestedOrgId","orgId","idempotencyKey","headers","trim","slice","authorization","idToken","startsWith","length","undefined","claim","membership","listing","sellerOrgDoc","decoded","app","auth","verifyIdToken","uid","buyerOrgId","permissions","installPlugins","firestore","listingSnapshot","collection","doc","get","data","deletedAt","reviewStatus","priceUsd","Number","sellerOrgId","profileId","buyerUid","code","revocation","publisher","accountId","stripeAccountId","chargesEnabled","stripeChargesEnabled","accountLivemode","stripeAccountLivemode","subject","sellerOrg","feePercent","amountCents","Math","round","feeCents","origin","host","buyerOrgSlug","returnPath","ORG_MARKETPLACE","orgSlug","transferCents","params","URLSearchParams","mode","displayName","billing_address_collection","success_url","cancel_url","client_reference_id","test","gaClientId","email","customer_email","claimed","kind","scopeId","key","busyMessage","replay","response","fetch","Authorization","stripeKey","toString","session","ok","url","console","release","payload","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,sDAAqD;AAC3F,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SACEC,UAAU,EACVC,gBAAgB,EAChBC,YAAY,EACZC,uBAAuB,EACvBC,wBAAwB,EACxBC,KAAK,QAIA,sBAAqB;AAC5B,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,0BAAsB;AAC3E,SACEC,iBAAiB,EACjBC,uBAAuB,QAClB,yBAAqB;AAC5B,SAASC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C,GAAG,CAACC,iBAAiB,EAAE;gBACxD,gBAAgB;eAMZgB,MAAMqE,SAAS,GAAG;gBAAE,mBAAmBrE,MAAMqE,SAAS;YAAC,IAAI,CAAC;YAElElF,MAAM6D,OAAOsB,QAAQ;QACvB;QAEF,MAAMC,UAAW,MAAML,SAAStF,IAAI;QACpC,IAAI,CAACsF,SAASM,EAAE,IAAI,CAACD,QAAQE,GAAG,EAAE;YAChCC,QAAQ7F,KAAK,CAAC,yBAAyB0F,QAAQ1F,KAAK;YACpD,sEAAsE;YACtE,qEAAqE;YACrE,MAAMmB,MAAM2E,OAAO;YACnB,OAAOlG,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAyB;QAChE;QACA,MAAM+F,UAAU;YAAEH,KAAKF,QAAQE,GAAG;QAAC;QACnC,yEAAyE;QACzE,2EAA2E;QAC3E,MAAMzE,MAAM6E,MAAM,CAAC,KAAKD;QACxB,OAAOnG,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAACgG;IAC9B,EAAE,OAAO/F,OAAO;QACd6F,QAAQ7F,KAAK,CAACA;QACd,wEAAwE;QACxE,4DAA4D;QAC5D,OAAMmB,yBAAAA,MAAO2E,OAAO;QACpB,OAAOlG,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAkB;IACzD;AACF,EAAC"}
@@ -14,7 +14,11 @@ 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 { createResourceUid, isPluginRevoked } from "@aglyn/aglyn/server";
17
+ */ // The leaf module, not the server barrel: the list keys every artifact
18
+ // create stamps (AGL-3321), which the install specs' closed-world barrel
19
+ // mocks have no reason to stage.
20
+ import { artifactCreateListKeys } from "@aglyn/aglyn/app-utils/artifact-list-keys";
21
+ import { createResourceUid, isPluginRevoked } from "@aglyn/aglyn/server";
18
22
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
23
  import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
20
24
  import { emailStarterRefusal, inspectEmailStarter, isPrivateListing, listingArtifactType, resolveEmailStarterAssurance } from "../model/index.js";
@@ -221,7 +225,10 @@ import { recordVersionMove } from "./version-stats.js";
221
225
  * the first save, and `decodeStoredNodes` is what every reader on this
222
226
  * path already goes through, so both forms are handled from the start.
223
227
  */ batch.set(screenRef, _extends({
224
- displayName,
228
+ displayName
229
+ }, artifactCreateListKeys('screens', {
230
+ displayName
231
+ }), {
225
232
  kind: 'email',
226
233
  versionId
227
234
  }, subject && {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-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 { createResourceUid, isPluginRevoked } from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport type { PluginRevocation } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n isPrivateListing,\n listingArtifactType,\n resolveEmailStarterAssurance,\n} from '../model'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\n\n/**\n * Installs a marketplace email starter as a new email on a site.\n *\n * ## The install is a COPY, and that is the versioning answer\n *\n * The published tree is written into a screen document of the tenant's own —\n * `hosts/{h}/screens/{newId}` with `kind: 'email'`, plus its first version —\n * in exactly the shape `createEmailScreen` writes, so it appears in the site's\n * Email templates list beside every email they designed themselves and opens\n * in the same besigner. From that write on, nothing reads the listing again.\n *\n * That is deliberate, and it is the property a live reference could not have:\n * a publisher pushing version 4 must not rewrite the email a tenant is\n * mailing from this afternoon. A newer version surfaces as an offer — the\n * shared `resolveUpdateState` comparison every other artifact type uses — and\n * is taken through `update-artifact`, which three-way-merges against the base\n * snapshot recorded here so the tenant's own edits survive it.\n *\n * The one thing a copy does NOT sever is a `media:` reference, which still\n * resolves against the publisher's media. Reported by the inspection rather\n * than refused: our own CDN serves it, so no third party learns who opened the\n * mail, but the bytes behind it can still change.\n *\n * ## Three refusals that are not in the other install routes\n *\n * **The kill switch, at install.** Every other copied artifact treats\n * `revocations` as a plugin concern. An installed email is mailed from the\n * shared sending domain, so a stopped version must not be handed out — and,\n * separately, must stop being sent by tenants who already have it, which is\n * `emailStarterSendBlock` on the send path.\n *\n * **A rejected version, for everybody including its publisher.** Review is not\n * a precondition for installing an email starter — they are auto-listed like\n * every other copied artifact — so most versions are honestly `unreviewed` and\n * install fine. A verdict of `rejected` is different: somebody looked and said\n * no, and the publisher's own site is on the same sending domain as everyone\n * else's.\n *\n * **The policy, re-run over the listing's own bytes.** The publish route\n * already refused a violating design. Re-running it here is not belt and\n * braces about that route — it is the gate for content that never went through\n * it: a version published before this policy existed, a document written by a\n * staff tool, an import. A tracking pixel is only refused if the refusal sits\n * where the content is HANDED OVER, which is the lesson `install-email-template`\n * records about takedown.\n */\nexport const installEmailStarterHandler: 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 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\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 listing.hiddenAt ||\n listingArtifactType(listing) !== 'emailStarter'\n ) {\n return res.status(404).json({ error: 'Unknown email starter' })\n }\n\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const priceUsd = Number(listing.priceUsd ?? 0)\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const version = listing.latestVersion\n const revocation = (\n await firestore.collection('revocations').doc(listingId).get()\n ).data() as PluginRevocation | undefined\n if (isPluginRevoked(revocation, String(version ?? ''))) {\n return res\n .status(409)\n .json({ error: 'This email design has been stopped by Aglyn' })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(version))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n /**\n * The assurance of THIS version, from THIS version's document.\n *\n * Read here rather than off the listing, and stamped rather than\n * recomputed later, because the listing's own review fields answer a\n * different question. `reviewStatus: 'verified'` is a claim about the\n * publisher; `latestVersionReviewState` describes whatever is newest. A\n * reader that consulted either would report version 7 as reviewed on the\n * strength of version 3, which is how \"reviewed\" stops meaning anything.\n */\n const assurance = resolveEmailStarterAssurance({\n reviewState: versionSnapshot.get('reviewState'),\n })\n if (assurance === 'rejected') {\n return res.status(409).json({\n error: 'This email design was turned down in review and cannot be installed',\n })\n }\n\n const inspection = inspectEmailStarter(versionSnapshot.get('nodes'), {\n hostId,\n })\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res\n .status(422)\n .json({ error: violation, violations: inspection.violations })\n }\n const nodes = inspection.nodes\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n\n const subject = String(versionSnapshot.get('subject') ?? '')\n const preheader = String(versionSnapshot.get('preheader') ?? '')\n const rootId = versionSnapshot.get('rootId') ?? null\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version,\n artifactType: 'emailStarter',\n content: { rootId, nodes, subject, preheader },\n })\n const installedFrom = { ...provenance.installedFrom, assurance }\n\n const screenId = createResourceUid()\n const versionId = createResourceUid()\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const displayName = String(listing.displayName ?? 'Installed email').slice(\n 0,\n 120,\n )\n const batch = firestore.batch()\n const screenRef = hostRef.collection('screens').doc(screenId)\n /**\n * The same document shape `createEmailScreen` writes, so the Email\n * templates list, the screen besigner and the campaign composer all find\n * it without knowing it came from anywhere.\n *\n * NOT routed, and `kind: 'email'`, which is what keeps it out of\n * `countBillableScreens` — an installed email spends the same allowance a\n * hand-made one does, which is none.\n *\n * `nodes` is written as a plain map here, exactly as the first version\n * from `/api/hosts/versions` is. The besigner's converter compresses on\n * the first save, and `decodeStoredNodes` is what every reader on this\n * path already goes through, so both forms are handled from the start.\n */\n batch.set(screenRef, {\n displayName,\n kind: 'email',\n versionId,\n ...(subject && { emailSubject: subject }),\n ...(preheader && { emailPreheader: preheader }),\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n batch.set(screenRef.collection('versions').doc(versionId), {\n screenId,\n ...(rootId ? { rootId } : {}),\n nodes,\n // Stamped on the VERSION as well as the screen, because the version is\n // what the send path renders and the send path is where the kill switch\n // has to bite. A stamp only on the parent would be one document away\n // from the bytes it describes.\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'emailStarter',\n to: version,\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 screenId,\n versionId,\n version: version ?? null,\n assurance,\n linkHosts: inspection.linkHosts,\n foreignMediaScopes: inspection.foreignMediaScopes,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter install failed' })\n }\n}\n\nexport default installEmailStarterHandler\n"],"names":["createResourceUid","isPluginRevoked","firebaseAdmin","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","isPrivateListing","listingArtifactType","resolveEmailStarterAssurance","canActAsPublisher","requirePurchase","recordInstallProvenance","recordVersionMove","installEmailStarterHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","versionSnapshot","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","listingRef","listingSnapshot","data","deletedAt","hiddenAt","ownsListing","profileId","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","version","latestVersion","revocation","assurance","reviewState","inspection","violation","violations","nodes","Object","keys","subject","preheader","rootId","provenance","artifactType","content","installedFrom","screenId","versionId","now","FieldValue","serverTimestamp","displayName","batch","screenRef","set","kind","emailSubject","emailPreheader","createdAt","updatedAt","commit","to","update","installCount","increment","catch","installed","linkHosts","foreignMediaScopes","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,eAAe,QAAQ,sBAAqB;AAGxE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gBAAgB,EAChBC,mBAAmB,EACnBC,4BAA4B,QACvB,oBAAU;AACjB,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,uBAAuB,QAAQ,kBAAc;AACtD,SAASC,iBAAiB,QAAQ,qBAAiB;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GACD,OAAO,MAAMC,6BAA+C,OAAOC,KAAKC;qBASzCD;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,IAAIQ,IAAI,qBAARR,WAAUS,MAAM,oBAAI;IAC1C,IAAI,CAACH,aAAa,CAACG,QAAQ;QACzB,OAAOR,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA8B;IACrE;IACA,MAAMK,gBAAgBH,QAAOP,6BAAAA,IAAIW,OAAO,CAACD,aAAa,YAAzBV,6BAA6B;IAC1D,MAAMY,UAAUF,cAAcG,UAAU,CAAC,aACrCH,cAAcI,KAAK,CAAC,UAAUC,MAAM,IACpCC;IACJ,IAAI,CAACJ,SAAS,OAAOX,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEC,O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ACXW,WAAWX;;QAEbI,MAAME,GAAG,CAACD,UAAU3C,UAAU,CAAC,YAAYC,GAAG,CAACoC,YAAY;YACzDD;WACIL,SAAS;YAAEA;QAAO,IAAI,CAAC;YAC3BL;YACA,uEAAuE;YACvE,wEAAwE;YACxE,qEAAqE;YACrE,+BAA+B;YAC/BS;YACAa,WAAWV;YACXW,WAAWX;;QAEb,MAAMI,MAAMQ,MAAM;QAElB,MAAMlF,kBAAkB;YACtB8B;YACAO;YACA4B,cAAc;YACdkB,IAAIjC;QACN;QACA,MAAMb,WACH+C,MAAM,CAAC;YACNC,cAAc/F,cAAcwC,SAAS,CAACyC,UAAU,CAACe,SAAS,CAAC;QAC7D,GACCC,KAAK,CAAC,IAAMrE;QAEf,OAAOf,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BkF,WAAW;YACXpB;YACAC;YACAnB,OAAO,EAAEA,kBAAAA,UAAW;YACpBG;YACAoC,WAAWlC,WAAWkC,SAAS;YAC/BC,oBAAoBnC,WAAWmC,kBAAkB;YACjDC,YAAY3B,WAAW2B,UAAU;QACnC;IACF,EAAE,OAAOpF,OAAO;QACdqF,QAAQrF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-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\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 { createResourceUid, isPluginRevoked } from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport type { PluginRevocation } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n isPrivateListing,\n listingArtifactType,\n resolveEmailStarterAssurance,\n} from '../model'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\n\n/**\n * Installs a marketplace email starter as a new email on a site.\n *\n * ## The install is a COPY, and that is the versioning answer\n *\n * The published tree is written into a screen document of the tenant's own —\n * `hosts/{h}/screens/{newId}` with `kind: 'email'`, plus its first version —\n * in exactly the shape `createEmailScreen` writes, so it appears in the site's\n * Email templates list beside every email they designed themselves and opens\n * in the same besigner. From that write on, nothing reads the listing again.\n *\n * That is deliberate, and it is the property a live reference could not have:\n * a publisher pushing version 4 must not rewrite the email a tenant is\n * mailing from this afternoon. A newer version surfaces as an offer — the\n * shared `resolveUpdateState` comparison every other artifact type uses — and\n * is taken through `update-artifact`, which three-way-merges against the base\n * snapshot recorded here so the tenant's own edits survive it.\n *\n * The one thing a copy does NOT sever is a `media:` reference, which still\n * resolves against the publisher's media. Reported by the inspection rather\n * than refused: our own CDN serves it, so no third party learns who opened the\n * mail, but the bytes behind it can still change.\n *\n * ## Three refusals that are not in the other install routes\n *\n * **The kill switch, at install.** Every other copied artifact treats\n * `revocations` as a plugin concern. An installed email is mailed from the\n * shared sending domain, so a stopped version must not be handed out — and,\n * separately, must stop being sent by tenants who already have it, which is\n * `emailStarterSendBlock` on the send path.\n *\n * **A rejected version, for everybody including its publisher.** Review is not\n * a precondition for installing an email starter — they are auto-listed like\n * every other copied artifact — so most versions are honestly `unreviewed` and\n * install fine. A verdict of `rejected` is different: somebody looked and said\n * no, and the publisher's own site is on the same sending domain as everyone\n * else's.\n *\n * **The policy, re-run over the listing's own bytes.** The publish route\n * already refused a violating design. Re-running it here is not belt and\n * braces about that route — it is the gate for content that never went through\n * it: a version published before this policy existed, a document written by a\n * staff tool, an import. A tracking pixel is only refused if the refusal sits\n * where the content is HANDED OVER, which is the lesson `install-email-template`\n * records about takedown.\n */\nexport const installEmailStarterHandler: 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 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\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 listing.hiddenAt ||\n listingArtifactType(listing) !== 'emailStarter'\n ) {\n return res.status(404).json({ error: 'Unknown email starter' })\n }\n\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const priceUsd = Number(listing.priceUsd ?? 0)\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const version = listing.latestVersion\n const revocation = (\n await firestore.collection('revocations').doc(listingId).get()\n ).data() as PluginRevocation | undefined\n if (isPluginRevoked(revocation, String(version ?? ''))) {\n return res\n .status(409)\n .json({ error: 'This email design has been stopped by Aglyn' })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(version))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n /**\n * The assurance of THIS version, from THIS version's document.\n *\n * Read here rather than off the listing, and stamped rather than\n * recomputed later, because the listing's own review fields answer a\n * different question. `reviewStatus: 'verified'` is a claim about the\n * publisher; `latestVersionReviewState` describes whatever is newest. A\n * reader that consulted either would report version 7 as reviewed on the\n * strength of version 3, which is how \"reviewed\" stops meaning anything.\n */\n const assurance = resolveEmailStarterAssurance({\n reviewState: versionSnapshot.get('reviewState'),\n })\n if (assurance === 'rejected') {\n return res.status(409).json({\n error: 'This email design was turned down in review and cannot be installed',\n })\n }\n\n const inspection = inspectEmailStarter(versionSnapshot.get('nodes'), {\n hostId,\n })\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res\n .status(422)\n .json({ error: violation, violations: inspection.violations })\n }\n const nodes = inspection.nodes\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n\n const subject = String(versionSnapshot.get('subject') ?? '')\n const preheader = String(versionSnapshot.get('preheader') ?? '')\n const rootId = versionSnapshot.get('rootId') ?? null\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version,\n artifactType: 'emailStarter',\n content: { rootId, nodes, subject, preheader },\n })\n const installedFrom = { ...provenance.installedFrom, assurance }\n\n const screenId = createResourceUid()\n const versionId = createResourceUid()\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const displayName = String(listing.displayName ?? 'Installed email').slice(\n 0,\n 120,\n )\n const batch = firestore.batch()\n const screenRef = hostRef.collection('screens').doc(screenId)\n /**\n * The same document shape `createEmailScreen` writes, so the Email\n * templates list, the screen besigner and the campaign composer all find\n * it without knowing it came from anywhere.\n *\n * NOT routed, and `kind: 'email'`, which is what keeps it out of\n * `countBillableScreens` — an installed email spends the same allowance a\n * hand-made one does, which is none.\n *\n * `nodes` is written as a plain map here, exactly as the first version\n * from `/api/hosts/versions` is. The besigner's converter compresses on\n * the first save, and `decodeStoredNodes` is what every reader on this\n * path already goes through, so both forms are handled from the start.\n */\n batch.set(screenRef, {\n displayName,\n // The keys the email templates list finds it by (AGL-3321).\n ...artifactCreateListKeys('screens', { displayName }),\n kind: 'email',\n versionId,\n ...(subject && { emailSubject: subject }),\n ...(preheader && { emailPreheader: preheader }),\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n batch.set(screenRef.collection('versions').doc(versionId), {\n screenId,\n ...(rootId ? { rootId } : {}),\n nodes,\n // Stamped on the VERSION as well as the screen, because the version is\n // what the send path renders and the send path is where the kill switch\n // has to bite. A stamp only on the parent would be one document away\n // from the bytes it describes.\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'emailStarter',\n to: version,\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 screenId,\n versionId,\n version: version ?? null,\n assurance,\n linkHosts: inspection.linkHosts,\n foreignMediaScopes: inspection.foreignMediaScopes,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter install failed' })\n }\n}\n\nexport default installEmailStarterHandler\n"],"names":["artifactCreateListKeys","createResourceUid","isPluginRevoked","firebaseAdmin","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","isPrivateListing","listingArtifactType","resolveEmailStarterAssurance","canActAsPublisher","requirePurchase","recordInstallProvenance","recordVersionMove","installEmailStarterHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","versionSnapshot","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","listingRef","listingSnapshot","data","deletedAt","hiddenAt","ownsListing","profileId","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","version","latestVersion","revocation","assurance","reviewState","inspection","violation","violations","nodes","Object","keys","subject","preheader","rootId","provenance","artifactType","content","installedFrom","screenId","versionId","now","FieldValue","serverTimestamp","displayName","batch","screenRef","set","kind","emailSubject","emailPreheader","createdAt","updatedAt","commit","to","update","installCount","increment","catch","installed","linkHosts","foreignMediaScopes","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,EAAEC,eAAe,QAAQ,sBAAqB;AAGxE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gBAAgB,EAChBC,mBAAmB,EACnBC,4BAA4B,QACvB,oBAAU;AACjB,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,uBAAuB,QAAQ,kBAAc;AACtD,SAASC,iBAAiB,QAAQ,qBAAiB;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GACD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I,CAAC;YAC1BkF,WAAW;YACXpB;YACAC;YACAnB,OAAO,EAAEA,kBAAAA,UAAW;YACpBG;YACAoC,WAAWlC,WAAWkC,SAAS;YAC/BC,oBAAoBnC,WAAWmC,kBAAkB;YACjDC,YAAY3B,WAAW2B,UAAU;QACnC;IACF,EAAE,OAAOpF,OAAO;QACdqF,QAAQrF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
@@ -14,7 +14,11 @@ 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 { checkQuota, createResourceUid, decodeStoredNodes, encodeStoredNodes } from "@aglyn/aglyn/server";
17
+ */ // The leaf module, not the server barrel: the list keys every artifact
18
+ // create stamps (AGL-3321), which the install specs' closed-world barrel
19
+ // mocks have no reason to stage.
20
+ import { artifactCreateListKeys, artifactDeleteListKeys } from "@aglyn/aglyn/app-utils/artifact-list-keys";
21
+ import { checkQuota, createResourceUid, decodeStoredNodes, encodeStoredNodes } from "@aglyn/aglyn/server";
18
22
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
19
23
  import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
20
24
  import { isPrivateListing, listingArtifactType } from "../model/marketplace.js";
@@ -252,14 +256,15 @@ import { recordVersionMove } from "./version-stats.js";
252
256
  // ALL READS BEFORE THE WRITES, which Firestore requires.
253
257
  const superseded = live.docs.filter((entry)=>!entry.get('deletedAt') && entry.get('source.listingId') === listingId);
254
258
  for (const stale of superseded){
255
- tx.update(stale.ref, {
259
+ tx.update(stale.ref, _extends({
256
260
  deletedAt: now,
257
261
  updatedAt: now
258
- });
262
+ }, artifactDeleteListKeys('templates')));
259
263
  }
264
+ const layoutName = String((_listing_displayName = listing.displayName) != null ? _listing_displayName : 'Layout').slice(0, 80);
260
265
  tx.set(templatesRef.doc(createResourceUid()), _extends({
261
266
  kind: 'layout',
262
- displayName: String((_listing_displayName = listing.displayName) != null ? _listing_displayName : 'Layout').slice(0, 80)
267
+ displayName: layoutName
263
268
  }, listing.description && {
264
269
  description: listing.description
265
270
  }, {
@@ -276,7 +281,14 @@ import { recordVersionMove } from "./version-stats.js";
276
281
  listingId,
277
282
  version: (_listing_latestVersion = listing.latestVersion) != null ? _listing_latestVersion : null
278
283
  },
279
- installedFrom: provenance.installedFrom,
284
+ installedFrom: provenance.installedFrom
285
+ }, artifactCreateListKeys('templates', {
286
+ kind: 'layout',
287
+ displayName: layoutName,
288
+ source: {
289
+ type: 'marketplace'
290
+ }
291
+ }), {
280
292
  createdAt: now,
281
293
  updatedAt: now
282
294
  }));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-layout.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 {\n checkQuota,\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n isPrivateListing,\n listingArtifactType,\n} from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\n\n/**\n * Installs a marketplace layout into a host's template library (AGL-671).\n *\n * Lands as a `kind: 'layout'` template rather than a live layout, for the\n * same reason template installs do (AGL-669): installing must never change\n * a running site. Creating the actual layout is the deliberate second step\n * in the templates library.\n *\n * Access mirrors template installs: free, purchased, or your own listing.\n */\nexport const installLayoutHandler: 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 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\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 listingArtifactType(listing) !== 'layout'\n ) {\n return res.status(404).json({ error: 'Unknown layout' })\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 layout = versionSnapshot.get('layout') as any\n if (!layout?.nodes || !Object.keys(layout.nodes).length) {\n return res.status(500).json({ error: 'Layout version missing' })\n }\n // The layout properties its tree binds to (AGL-2933), held to the\n // sanitizer again on the way in; `undefined` for a version published\n // before they were carried.\n const props = readPublishedProps(layout.props)\n\n const org = (await getOrgForHost(hostId))?.org\n const templatesRef = hostRef.collection('templates')\n /**\n * The library slots this install would spend, off a set of template docs.\n *\n * The copy this listing already installed is about to be replaced, so\n * counting it would fail the quota on an update the user is entitled to.\n *\n * A function rather than an inlined filter because the count is now taken\n * TWICE — once here as a fast refusal, once inside the transaction as the\n * authority — and two copies of a counting rule is how the rule drifts.\n */\n const slotsAfterInstall = (\n docs: Array<FirebaseFirestore.QueryDocumentSnapshot>,\n ) =>\n docs.filter(\n (entry) =>\n !entry.get('deletedAt') && entry.get('source.listingId') !== listingId,\n ).length\n const overQuota = (limit: number) =>\n `Your plan allows ${limit} templates — see Billing to upgrade.`\n const existing = await templatesRef.get()\n {\n // The fast refusal. NOT the enforcement point — see the transaction\n // below — but it keeps the base-snapshot write and the version tally off\n // the path of an install that was never going to be allowed, and it is\n // what answers a caller who is simply over their limit.\n const quota = checkQuota(\n org as any,\n 'templatesPerHost',\n slotsAfterInstall(existing.docs),\n )\n if (!quota.allowed) {\n return res.status(403).json({ error: overQuota(quota.limit) })\n }\n }\n\n // Replacing a layout the workspace has edited destroys those edits — the\n // old doc is soft-deleted, so the change is invisible until someone goes\n // looking for it. Refuse unless the caller has been shown what goes and\n // asked for a replacement anyway (AGL-1018).\n const installedLayout = existing.docs.find(\n (entry) =>\n !entry.get('deletedAt') && entry.get('source.listingId') === listingId,\n )\n if (installedLayout) {\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: installedLayout.get('installedFrom.sha256'),\n current: {\n rootId: installedLayout.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 // never matches a map, so an untouched copy would read as edited\n // and every re-install would be refused as a divergence\n // (AGL-1151).\n nodes: decodeStoredNodes(installedLayout.get('nodes')),\n },\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'Your copy of this layout has been edited since it was installed. ' +\n '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 layout tree as published,\n // without the display name the user is free to change.\n //\n // Stays OUTSIDE the transaction below: it does its own read and write, and\n // repeating those on every retry attempt is exactly what a transaction\n // body must not do. That is safe because the base collection is\n // content-addressed and shared — a race that ends in a refusal leaves at\n // most a snapshot of a published version, keyed by its own hash, which the\n // next successful install of that version reuses.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'layout',\n content: { rootId: layout.rootId, nodes: layout.nodes },\n })\n /**\n * Re-install replaces the prior copy rather than stacking (AGL-671).\n *\n * THE ENFORCEMENT POINT: the count, the decision and every write in ONE\n * transaction (AGL-2371, the AGL-2231 treatment).\n *\n * The check above ran, then `hasDivergedFromBase` awaited, then\n * `recordInstallProvenance` awaited, and only then did a `WriteBatch`\n * commit. Every await is a yield, so N concurrent installs each read the\n * same pre-count, each found room, and each landed — and nothing re-counts\n * afterwards, so the extra templates were permanent. A batch is atomic but\n * NOT conditional on a read taken before it, which is the same lesson\n * AGL-2369 paid for one route over.\n *\n * `tx.get` on the templates collection takes a pessimistic lock on every\n * document it matched, so the loser of a race retries, re-reads the higher\n * count and is refused.\n *\n * The DIVERGENCE gate above deliberately stays outside. It is not a count:\n * it asks whether this workspace edited its own copy, which no concurrent\n * install of a different listing can change, and it reads a base snapshot\n * through a helper that does its own `get`.\n *\n * A refusal comes back as data and is rendered outside. Building a response\n * inside a body that can run several times reads as if the transaction were\n * a place effects happen.\n */\n const outcome = await firestore.runTransaction<\n { error: string } | { replaced: number; from: string | number | null }\n >(async (tx) => {\n const live = await tx.get(templatesRef)\n const quota = checkQuota(\n org as any,\n 'templatesPerHost',\n slotsAfterInstall(live.docs),\n )\n if (!quota.allowed) return { error: overQuota(quota.limit) }\n\n // ALL READS BEFORE THE WRITES, which Firestore requires.\n const superseded = live.docs.filter(\n (entry) =>\n !entry.get('deletedAt') && entry.get('source.listingId') === listingId,\n )\n for (const stale of superseded) {\n tx.update(stale.ref, { deletedAt: now, updatedAt: now })\n }\n tx.set(templatesRef.doc(createResourceUid()), {\n kind: 'layout',\n displayName: String(listing.displayName ?? 'Layout').slice(0, 80),\n ...(listing.description && { description: listing.description }),\n rootId: layout.rootId,\n // Compressed at rest, matching the template converter (AGL-1151).\n // The provenance base recorded above keeps the decoded map: it is\n // compared by value, never opened as a document.\n nodes: Buffer.from(encodeStoredNodes(layout.nodes ?? {})!),\n // Use template seeds the layout's first version with these\n // (AGL-2932), so a screen using it has its layout values to set.\n ...(props && { props }),\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n installedFrom: provenance.installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n // Per-version tally input (AGL-1036): the replaced copy leaves its\n // version — read off the doc the transaction actually replaced, not off\n // the snapshot taken before it opened.\n return {\n replaced: superseded.length,\n from:\n superseded[0]?.get('installedFrom.version') ??\n superseded[0]?.get('source.version') ??\n null,\n }\n })\n if ('error' in outcome) {\n return res.status(403).json({ error: outcome.error })\n }\n const { replaced } = outcome\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'layout',\n from: outcome.from,\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 templates: 1,\n replaced,\n version: listing.latestVersion ?? null,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Layout install failed' })\n }\n}\n\nexport default installLayoutHandler\n"],"names":["checkQuota","createResourceUid","decodeStoredNodes","encodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","isPrivateListing","listingArtifactType","readPublishedProps","canActAsPublisher","requirePurchase","hasDivergedFromBase","recordInstallProvenance","recordVersionMove","installLayoutHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","listingRef","listingSnapshot","data","deletedAt","hiddenAt","priceUsd","Number","ownsListing","profileId","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","layout","nodes","Object","keys","props","org","templatesRef","slotsAfterInstall","docs","filter","entry","overQuota","limit","existing","quota","allowed","installedLayout","find","diverged","sha256","current","rootId","mode","now","FieldValue","serverTimestamp","provenance","version","artifactType","content","outcome","runTransaction","tx","superseded","live","stale","update","ref","updatedAt","set","kind","displayName","description","Buffer","from","source","type","installedFrom","createdAt","replaced","to","installCount","increment","catch","installed","templates","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,iBAAiB,EACjBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,gBAAgB,EAChBC,mBAAmB,QACd,0BAAsB;AAC7B,SAASC,kBAAkB,QAAQ,gCAA4B;AAC/D,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,mBAAmB,EAAEC,uBAAuB,QAAQ,kBAAc;AAC3E,SAASC,iBAAiB,QAAQ,qBAAiB;AAEnD;;;;;;;;;CASC,GACD,OAAO,MAAMC,uBAAyC,OAAOC,KAAKC;qBASnCD;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,IAAIQ,IAAI,qBAARR,WAAUS,MAAM,oBAAI;IAC1C,IAAI,CAACH,aAAa,CAACG,QAAQ;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O0E,QAAQ1E,KAAK;YAAC;QACrD;QACA,MAAM,EAAE6F,QAAQ,EAAE,GAAGnB;QAErB,MAAMjF,kBAAkB;YACtB6B;YACAO;YACA2C,cAAc;YACdgB,MAAMd,QAAQc,IAAI;YAClBM,IAAIjF,QAAQ8B,aAAa;QAC3B;QACA,MAAMd,WACHmD,MAAM,CAAC;YACNe,cAAchH,cAAcuC,SAAS,CAAC8C,UAAU,CAAC4B,SAAS,CAAC;QAC7D,GACCC,KAAK,CAAC,IAAMtF;QAEf,OAAOf,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BmG,WAAW;YACXC,WAAW;YACXN;YACAtB,OAAO,GAAE1D,yBAAAA,QAAQ8B,aAAa,YAArB9B,yBAAyB;YAClCuF,YAAY9B,WAAW8B,UAAU;QACnC;IACF,EAAE,OAAOpG,OAAO;QACdqG,QAAQrG,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAwB;IAC/D;AACF,EAAC;AAED,eAAeN,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-layout.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, artifactDeleteListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport {\n checkQuota,\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n isPrivateListing,\n listingArtifactType,\n} from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\n\n/**\n * Installs a marketplace layout into a host's template library (AGL-671).\n *\n * Lands as a `kind: 'layout'` template rather than a live layout, for the\n * same reason template installs do (AGL-669): installing must never change\n * a running site. Creating the actual layout is the deliberate second step\n * in the templates library.\n *\n * Access mirrors template installs: free, purchased, or your own listing.\n */\nexport const installLayoutHandler: 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 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\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 listingArtifactType(listing) !== 'layout'\n ) {\n return res.status(404).json({ error: 'Unknown layout' })\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 layout = versionSnapshot.get('layout') as any\n if (!layout?.nodes || !Object.keys(layout.nodes).length) {\n return res.status(500).json({ error: 'Layout version missing' })\n }\n // The layout properties its tree binds to (AGL-2933), held to the\n // sanitizer again on the way in; `undefined` for a version published\n // before they were carried.\n const props = readPublishedProps(layout.props)\n\n const org = (await getOrgForHost(hostId))?.org\n const templatesRef = hostRef.collection('templates')\n /**\n * The library slots this install would spend, off a set of template docs.\n *\n * The copy this listing already installed is about to be replaced, so\n * counting it would fail the quota on an update the user is entitled to.\n *\n * A function rather than an inlined filter because the count is now taken\n * TWICE — once here as a fast refusal, once inside the transaction as the\n * authority — and two copies of a counting rule is how the rule drifts.\n */\n const slotsAfterInstall = (\n docs: Array<FirebaseFirestore.QueryDocumentSnapshot>,\n ) =>\n docs.filter(\n (entry) =>\n !entry.get('deletedAt') && entry.get('source.listingId') !== listingId,\n ).length\n const overQuota = (limit: number) =>\n `Your plan allows ${limit} templates — see Billing to upgrade.`\n const existing = await templatesRef.get()\n {\n // The fast refusal. NOT the enforcement point — see the transaction\n // below — but it keeps the base-snapshot write and the version tally off\n // the path of an install that was never going to be allowed, and it is\n // what answers a caller who is simply over their limit.\n const quota = checkQuota(\n org as any,\n 'templatesPerHost',\n slotsAfterInstall(existing.docs),\n )\n if (!quota.allowed) {\n return res.status(403).json({ error: overQuota(quota.limit) })\n }\n }\n\n // Replacing a layout the workspace has edited destroys those edits — the\n // old doc is soft-deleted, so the change is invisible until someone goes\n // looking for it. Refuse unless the caller has been shown what goes and\n // asked for a replacement anyway (AGL-1018).\n const installedLayout = existing.docs.find(\n (entry) =>\n !entry.get('deletedAt') && entry.get('source.listingId') === listingId,\n )\n if (installedLayout) {\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: installedLayout.get('installedFrom.sha256'),\n current: {\n rootId: installedLayout.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 // never matches a map, so an untouched copy would read as edited\n // and every re-install would be refused as a divergence\n // (AGL-1151).\n nodes: decodeStoredNodes(installedLayout.get('nodes')),\n },\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'Your copy of this layout has been edited since it was installed. ' +\n '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 layout tree as published,\n // without the display name the user is free to change.\n //\n // Stays OUTSIDE the transaction below: it does its own read and write, and\n // repeating those on every retry attempt is exactly what a transaction\n // body must not do. That is safe because the base collection is\n // content-addressed and shared — a race that ends in a refusal leaves at\n // most a snapshot of a published version, keyed by its own hash, which the\n // next successful install of that version reuses.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'layout',\n content: { rootId: layout.rootId, nodes: layout.nodes },\n })\n /**\n * Re-install replaces the prior copy rather than stacking (AGL-671).\n *\n * THE ENFORCEMENT POINT: the count, the decision and every write in ONE\n * transaction (AGL-2371, the AGL-2231 treatment).\n *\n * The check above ran, then `hasDivergedFromBase` awaited, then\n * `recordInstallProvenance` awaited, and only then did a `WriteBatch`\n * commit. Every await is a yield, so N concurrent installs each read the\n * same pre-count, each found room, and each landed — and nothing re-counts\n * afterwards, so the extra templates were permanent. A batch is atomic but\n * NOT conditional on a read taken before it, which is the same lesson\n * AGL-2369 paid for one route over.\n *\n * `tx.get` on the templates collection takes a pessimistic lock on every\n * document it matched, so the loser of a race retries, re-reads the higher\n * count and is refused.\n *\n * The DIVERGENCE gate above deliberately stays outside. It is not a count:\n * it asks whether this workspace edited its own copy, which no concurrent\n * install of a different listing can change, and it reads a base snapshot\n * through a helper that does its own `get`.\n *\n * A refusal comes back as data and is rendered outside. Building a response\n * inside a body that can run several times reads as if the transaction were\n * a place effects happen.\n */\n const outcome = await firestore.runTransaction<\n { error: string } | { replaced: number; from: string | number | null }\n >(async (tx) => {\n const live = await tx.get(templatesRef)\n const quota = checkQuota(\n org as any,\n 'templatesPerHost',\n slotsAfterInstall(live.docs),\n )\n if (!quota.allowed) return { error: overQuota(quota.limit) }\n\n // ALL READS BEFORE THE WRITES, which Firestore requires.\n const superseded = live.docs.filter(\n (entry) =>\n !entry.get('deletedAt') && entry.get('source.listingId') === listingId,\n )\n for (const stale of superseded) {\n tx.update(stale.ref, {\n deletedAt: now,\n updatedAt: now,\n ...artifactDeleteListKeys('templates'),\n })\n }\n const layoutName = String(listing.displayName ?? 'Layout').slice(0, 80)\n tx.set(templatesRef.doc(createResourceUid()), {\n kind: 'layout',\n displayName: layoutName,\n ...(listing.description && { description: listing.description }),\n rootId: layout.rootId,\n // Compressed at rest, matching the template converter (AGL-1151).\n // The provenance base recorded above keeps the decoded map: it is\n // compared by value, never opened as a document.\n nodes: Buffer.from(encodeStoredNodes(layout.nodes ?? {})!),\n // Use template seeds the layout's first version with these\n // (AGL-2932), so a screen using it has its layout values to set.\n ...(props && { props }),\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n installedFrom: provenance.installedFrom,\n // The keys the templates library finds it by (AGL-3321).\n ...artifactCreateListKeys('templates', {\n kind: 'layout',\n displayName: layoutName,\n source: { type: 'marketplace' },\n }),\n createdAt: now,\n updatedAt: now,\n })\n // Per-version tally input (AGL-1036): the replaced copy leaves its\n // version — read off the doc the transaction actually replaced, not off\n // the snapshot taken before it opened.\n return {\n replaced: superseded.length,\n from:\n superseded[0]?.get('installedFrom.version') ??\n superseded[0]?.get('source.version') ??\n null,\n }\n })\n if ('error' in outcome) {\n return res.status(403).json({ error: outcome.error })\n }\n const { replaced } = outcome\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'layout',\n from: outcome.from,\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 templates: 1,\n replaced,\n version: listing.latestVersion ?? null,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Layout install failed' })\n }\n}\n\nexport default installLayoutHandler\n"],"names":["artifactCreateListKeys","artifactDeleteListKeys","checkQuota","createResourceUid","decodeStoredNodes","encodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","isPrivateListing","listingArtifactType","readPublishedProps","canActAsPublisher","requirePurchase","hasDivergedFromBase","recordInstallProvenance","recordVersionMove","installLayoutHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","listingRef","listingSnapshot","data","deletedAt","hiddenAt","priceUsd","Number","ownsListing","profileId","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","layout","nodes","Object","keys","props","org","templatesRef","slotsAfterInstall","docs","filter","entry","overQuota","limit","existing","quota","allowed","installedLayout","find","diverged","sha256","current","rootId","mode","now","FieldValue","serverTimestamp","provenance","version","artifactType","content","outcome","runTransaction","tx","superseded","live","stale","update","ref","updatedAt","layoutName","displayName","set","kind","description","Buffer","from","source","type","installedFrom","createdAt","replaced","to","installCount","increment","catch","installed","templates","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,sBAAsB,EAAEC,sBAAsB,QAAQ,4CAA2C;AAC1G,SACEC,UAAU,EACVC,iBAAiB,EACjBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,gBAAgB,EAChBC,mBAAmB,QACd,0BAAsB;AAC7B,SAASC,kBAAkB,QAAQ,gCAA4B;AAC/D,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AACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAwB;IAC/D;AACF,EAAC;AAED,eAAeN,qBAAoB"}
@@ -14,7 +14,11 @@ 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 { checkQuota, createResourceUid, encodeStoredNodes } from "@aglyn/aglyn/server";
17
+ */ // The leaf module, not the server barrel: the list keys every artifact
18
+ // create stamps (AGL-3321), which the install specs' closed-world barrel
19
+ // mocks have no reason to stage.
20
+ import { artifactCreateListKeys, artifactDeleteListKeys } from "@aglyn/aglyn/app-utils/artifact-list-keys";
21
+ import { checkQuota, createResourceUid, encodeStoredNodes } from "@aglyn/aglyn/server";
18
22
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
19
23
  import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
20
24
  import { canActAsPublisher } from "./publisher-profile.js";
@@ -267,18 +271,19 @@ import { isPrivateListing, listingArtifactType } from "../model/marketplace.js";
267
271
  let replaced = 0;
268
272
  for (const stale of superseded){
269
273
  if (stale.get('deletedAt')) continue;
270
- tx.update(stale.ref, {
274
+ tx.update(stale.ref, _extends({
271
275
  deletedAt: now,
272
276
  updatedAt: now
273
- });
277
+ }, artifactDeleteListKeys('templates')));
274
278
  replaced += 1;
275
279
  }
276
280
  let created = 0;
277
281
  for (const screen of screens){
278
282
  var _screen_displayName, _screen_nodes;
283
+ const pageName = String((_screen_displayName = screen.displayName) != null ? _screen_displayName : 'Page').slice(0, 80);
279
284
  tx.set(templatesRef.doc(createResourceUid()), _extends({
280
285
  kind: 'page',
281
- displayName: String((_screen_displayName = screen.displayName) != null ? _screen_displayName : 'Page').slice(0, 80)
286
+ displayName: pageName
282
287
  }, screen.description && {
283
288
  description: screen.description
284
289
  }, screen.seo && {
@@ -296,7 +301,12 @@ import { isPrivateListing, listingArtifactType } from "../model/marketplace.js";
296
301
  theme: template.theme
297
302
  } : {}, {
298
303
  source,
299
- installedFrom: provenance.installedFrom,
304
+ installedFrom: provenance.installedFrom
305
+ }, artifactCreateListKeys('templates', {
306
+ kind: 'page',
307
+ displayName: pageName,
308
+ source
309
+ }), {
300
310
  createdAt: now,
301
311
  updatedAt: now
302
312
  }));