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

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 (69) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/listing-content.component.d.ts +1 -0
  3. package/src/lib/components/listing-content.component.js +3 -1
  4. package/src/lib/components/listing-content.component.js.map +1 -1
  5. package/src/lib/model/listing-query.d.ts +2 -0
  6. package/src/lib/model/listing-query.js.map +1 -1
  7. package/src/lib/model/marketplace.d.ts +7 -0
  8. package/src/lib/model/marketplace.js.map +1 -1
  9. package/src/lib/model/publisher-risk.d.ts +52 -0
  10. package/src/lib/model/publisher-risk.js +74 -0
  11. package/src/lib/model/publisher-risk.js.map +1 -0
  12. package/src/lib/server/billing-webhook.js +72 -4
  13. package/src/lib/server/billing-webhook.js.map +1 -1
  14. package/src/lib/server/checkout.js +18 -1
  15. package/src/lib/server/checkout.js.map +1 -1
  16. package/src/lib/server/connect.js +15 -1
  17. package/src/lib/server/connect.js.map +1 -1
  18. package/src/lib/server/install-dataset-schema.js +3 -1
  19. package/src/lib/server/install-dataset-schema.js.map +1 -1
  20. package/src/lib/server/install-email-starter.js +3 -1
  21. package/src/lib/server/install-email-starter.js.map +1 -1
  22. package/src/lib/server/install-email-template.js +3 -1
  23. package/src/lib/server/install-email-template.js.map +1 -1
  24. package/src/lib/server/install-layout.js +3 -1
  25. package/src/lib/server/install-layout.js.map +1 -1
  26. package/src/lib/server/install-plugin.js +3 -1
  27. package/src/lib/server/install-plugin.js.map +1 -1
  28. package/src/lib/server/install-template.js +3 -1
  29. package/src/lib/server/install-template.js.map +1 -1
  30. package/src/lib/server/install-theme.js +3 -1
  31. package/src/lib/server/install-theme.js.map +1 -1
  32. package/src/lib/server/install.js +3 -1
  33. package/src/lib/server/install.js.map +1 -1
  34. package/src/lib/server/listing-screen.d.ts +83 -0
  35. package/src/lib/server/listing-screen.js +244 -0
  36. package/src/lib/server/listing-screen.js.map +1 -0
  37. package/src/lib/server/publish-dataset-schema.js +12 -0
  38. package/src/lib/server/publish-dataset-schema.js.map +1 -1
  39. package/src/lib/server/publish-email-starter.js +15 -1
  40. package/src/lib/server/publish-email-starter.js.map +1 -1
  41. package/src/lib/server/publish-email-template.js +15 -1
  42. package/src/lib/server/publish-email-template.js.map +1 -1
  43. package/src/lib/server/publish-layout.js +15 -1
  44. package/src/lib/server/publish-layout.js.map +1 -1
  45. package/src/lib/server/publish-plugin.js +41 -3
  46. package/src/lib/server/publish-plugin.js.map +1 -1
  47. package/src/lib/server/publish-template.js +15 -1
  48. package/src/lib/server/publish-template.js.map +1 -1
  49. package/src/lib/server/publish-theme.js +14 -1
  50. package/src/lib/server/publish-theme.js.map +1 -1
  51. package/src/lib/server/publish.js +15 -1
  52. package/src/lib/server/publish.js.map +1 -1
  53. package/src/lib/server/publisher-lockdown.d.ts +33 -0
  54. package/src/lib/server/publisher-lockdown.js +98 -0
  55. package/src/lib/server/publisher-lockdown.js.map +1 -0
  56. package/src/lib/server/publisher-profile-save.js +36 -0
  57. package/src/lib/server/publisher-profile-save.js.map +1 -1
  58. package/src/lib/server/publisher-review-email.js +15 -5
  59. package/src/lib/server/publisher-review-email.js.map +1 -1
  60. package/src/lib/server/reviews.d.ts +8 -0
  61. package/src/lib/server/reviews.js +43 -3
  62. package/src/lib/server/reviews.js.map +1 -1
  63. package/src/lib/server/sale-risk.d.ts +105 -0
  64. package/src/lib/server/sale-risk.js +323 -0
  65. package/src/lib/server/sale-risk.js.map +1 -0
  66. package/src/lib/server/update-artifact.js +3 -1
  67. package/src/lib/server/update-artifact.js.map +1 -1
  68. package/src/lib/server.js +4 -0
  69. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/reviews.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { canActAsPublisher } from './publisher-profile'\n\nconst MAX_COMMENT_LENGTH = 2000\n/** Orgs scanned when looking for an install pin. */\nconst MAX_ORGS_CHECKED = 25\n\n/**\n * Whether the author has actually used this listing (AGL-655).\n *\n * An install pin lives at `orgs/{orgId}/installs/{listingId}` (org-wide) or\n * `hosts/{hostId}/installs/{listingId}` (one site), and **it is one or the\n * other** — `install-plugin` reassigns its target ref to the org path for an\n * org-scoped install rather than writing both.\n *\n * This used to read the org pin alone, on the stated reasoning that \"a host\n * pin implies the org installed it somewhere, and the org mirror is what the\n * install routes write\" (AGL-1006). There is no org mirror, so a per-site\n * install left nothing to find and the workspace was refused a rating — and\n * it refused exactly the careful installers, the ones who scoped a plugin to\n * one site before rolling it out. Ratings drive marketplace ranking, so that\n * skewed the sample toward org-wide installers.\n *\n * Host pins are found through the org doc's own `hosts` map (written by\n * `registerOrgHost`), then read in ONE batched `getAll` alongside the org\n * pin. Two round trips per org, bounded and index-free — deliberately not a\n * collection-group query on `installs`, which would need a new index and\n * would match every tenant's pins for a listing, unbounded, to answer a\n * question about one org.\n */\nconst MAX_HOSTS_CHECKED = 50\n\n// Exported for the AGL-1006 regression test: it takes its firestore, so the\n// rule \"a host pin counts\" is checkable without standing up the whole\n// handler (auth, transactions, aggregate writes).\nexport async function isVerifiedInstaller(\n firestore: FirebaseFirestore.Firestore,\n uid: string,\n listingId: string,\n): Promise<{ verified: boolean; orgId?: string }> {\n const memberships = await firestore\n .collection('users')\n .doc(uid)\n .collection('orgs')\n .limit(MAX_ORGS_CHECKED)\n .get()\n for (const membership of memberships.docs) {\n const orgId = membership.id\n const orgRef = firestore.collection('orgs').doc(orgId)\n const org = await orgRef.get()\n const hostIds = Object.keys(\n (org.get('hosts') as Record<string, unknown> | undefined) ?? {},\n ).slice(0, MAX_HOSTS_CHECKED)\n const refs = [\n orgRef.collection('installs').doc(listingId),\n ...hostIds.map((hostId) =>\n firestore\n .collection('hosts')\n .doc(hostId)\n .collection('installs')\n .doc(listingId),\n ),\n ]\n const pins = await firestore.getAll(...refs)\n if (pins.some((pin) => pin.exists)) return { verified: true, orgId }\n }\n return { verified: false }\n}\n\n/**\n * Ratings and comments on a marketplace listing (AGL-655).\n *\n * One review per account, keyed by uid, so re-submitting edits rather than\n * stacking. Two rules shape everything else:\n *\n * - **Rating requires a verified email AND having installed it (AGL-865).**\n * A star rating is the signal that drives ranking, so it is reserved for\n * accounts that verified their email and actually used the thing.\n * Commenting stays open to any signed-in account — questions before\n * installing are useful, and a comment moves no numbers.\n * - **The publisher cannot review their own listing.** Org-scoped, so a\n * second account in the same org does not slip through.\n *\n * Aggregates are adjusted in the same transaction as the review, and are\n * frozen from client writes in rules. Kept as a running `ratingSum` +\n * `ratingCount` so a submission costs one read, not a scan of every review.\n */\nexport const reviewsHandler: PluginApiHandler = async (req, res) => {\n const method = req.method === 'DELETE' ? 'DELETE' : 'POST'\n if (req.method !== 'POST' && req.method !== 'DELETE') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\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 try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (!listing || listing.deletedAt) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const reviewRef = listingRef.collection('reviews').doc(decoded.uid)\n\n if (method === 'DELETE') {\n await firestore.runTransaction(async (tx) => {\n const [existing, listingNow] = await Promise.all([\n tx.get(reviewRef),\n tx.get(listingRef),\n ])\n if (!existing.exists) return\n const previousRating = Number(existing.get('rating') ?? 0) || 0\n const hadComment = !!existing.get('comment')\n tx.delete(reviewRef)\n tx.update(\n listingRef,\n nextAggregates(\n listingNow,\n -previousRating,\n previousRating ? -1 : 0,\n hadComment ? -1 : 0,\n ),\n )\n })\n return res.status(200).json({ ok: true, removed: true })\n }\n\n // Publishing org cannot review itself, however many accounts it has.\n if (await canActAsPublisher(firestore, decoded.uid, listing.profileId)) {\n return res.status(403).json({\n error: 'You cannot review your organization’s own listing',\n })\n }\n\n const rawRating = req.body?.rating\n const rating =\n rawRating == null || rawRating === ''\n ? 0\n : Math.min(5, Math.max(1, Math.round(Number(rawRating) || 0)))\n const comment = String(req.body?.comment ?? '')\n .trim()\n .slice(0, MAX_COMMENT_LENGTH)\n if (!rating && !comment) {\n return res.status(400).json({ error: 'Add a rating or a comment' })\n }\n\n // A star rating drives ranking, so it is reserved for accounts that both\n // verified their email (AGL-865/479) AND actually installed the thing.\n // Commenting stays open to any signed-in account — the checks below only\n // guard `rating`, never `comment`. Impersonation sessions are exempt from\n // the email gate the same way every other AGL-479 chokepoint is.\n if (rating && !decoded.email_verified && !isImpersonationSession(decoded)) {\n return res.status(403).json({\n error: 'Verify your email to rate — you can still leave a comment',\n reason: 'email-unverified',\n })\n }\n const installer = await isVerifiedInstaller(firestore, decoded.uid, listingId)\n if (rating && !installer.verified) {\n return res.status(403).json({\n error:\n 'Only organizations that have installed this can rate it — you ' +\n 'can still leave a comment',\n })\n }\n\n const now = Date.now()\n await firestore.runTransaction(async (tx) => {\n const [existing, listingNow] = await Promise.all([\n tx.get(reviewRef),\n tx.get(listingRef),\n ])\n const previousRating = Number(existing.get('rating') ?? 0) || 0\n const hadComment = existing.exists && !!existing.get('comment')\n tx.set(\n reviewRef,\n {\n uid: decoded.uid,\n displayName: String(decoded.name ?? 'Someone').slice(0, 80),\n ...(rating ? { rating } : { rating: null }),\n ...(comment ? { comment } : { comment: null }),\n verifiedInstaller: installer.verified,\n ...(installer.orgId ? { orgId: installer.orgId } : {}),\n // Preserved across edits: a moderator's decision must not be\n // undone by the author simply resubmitting.\n hidden: existing.get('hidden') ?? false,\n ...(existing.exists ? {} : { createdAtMs: now }),\n updatedAtMs: now,\n },\n { merge: true },\n )\n tx.update(\n listingRef,\n nextAggregates(\n listingNow,\n rating - previousRating,\n (rating ? 1 : 0) - (previousRating ? 1 : 0),\n (comment ? 1 : 0) - (hadComment ? 1 : 0),\n ),\n )\n })\n\n return res.status(200).json({\n ok: true,\n rating: rating || null,\n verifiedInstaller: installer.verified,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Review failed' })\n }\n}\n\n/**\n * Absolute aggregate values after a change.\n *\n * Written as numbers rather than `FieldValue.increment` because\n * `ratingAverage` has to be stored — browse sorts on it, and a transaction\n * cannot divide two pending increments. Reading the listing inside the\n * transaction makes the read-modify-write atomic, so concurrent reviews\n * cannot interleave and lose a vote.\n */\nfunction nextAggregates(\n current: FirebaseFirestore.DocumentSnapshot,\n ratingSumDelta: number,\n ratingCountDelta: number,\n commentCountDelta: number,\n): Record<string, unknown> {\n const ratingSum = Math.max(0, Number(current.get('ratingSum') ?? 0) + ratingSumDelta)\n const ratingCount = Math.max(\n 0,\n Number(current.get('ratingCount') ?? 0) + ratingCountDelta,\n )\n const commentCount = Math.max(\n 0,\n Number(current.get('commentCount') ?? 0) + commentCountDelta,\n )\n return {\n ratingSum,\n ratingCount,\n commentCount,\n // One decimal — enough for \"4.2\", and avoids a long float in the UI.\n ratingAverage: ratingCount\n ? Math.round((ratingSum / ratingCount) * 10) / 10\n : 0,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }\n}\n\nexport default reviewsHandler\n"],"names":["firebaseAdmin","isImpersonationSession","canActAsPublisher","MAX_COMMENT_LENGTH","MAX_ORGS_CHECKED","MAX_HOSTS_CHECKED","isVerifiedInstaller","firestore","uid","listingId","memberships","collection","doc","limit","get","membership","docs","org","orgId","id","orgRef","hostIds","Object","keys","slice","refs","map","hostId","pins","getAll","some","pin","exists","verified","reviewsHandler","req","res","method","status","json","error","String","body","authorization","headers","idToken","startsWith","length","undefined","decoded","app","auth","verifyIdToken","listingRef","listingSnapshot","listing","data","deletedAt","reviewRef","runTransaction","tx","existing","listingNow","Promise","all","previousRating","Number","hadComment","delete","update","nextAggregates","ok","removed","profileId","rawRating","rating","Math","min","max","round","comment","trim","email_verified","reason","installer","now","Date","set","displayName","name","verifiedInstaller","hidden","createdAtMs","updatedAtMs","merge","console","current","ratingSumDelta","ratingCountDelta","commentCountDelta","ratingSum","ratingCount","commentCount","ratingAverage","updatedAt","FieldValue","serverTimestamp"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AAChF,SAASC,iBAAiB,QAAQ,yBAAqB;AAEvD,MAAMC,qBAAqB;AAC3B,kDAAkD,GAClD,MAAMC,mBAAmB;AAEzB;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,MAAMC,oBAAoB;AAE1B,4EAA4E;AAC5E,sEAAsE;AACtE,kDAAkD;AAClD,OAAO,eAAeC,oBACpBC,SAAsC,EACtCC,GAAW,EACXC,SAAiB;IAEjB,MAAMC,cAAc,MAAMH,UACvBI,UAAU,CAAC,SACXC,GAAG,CAACJ,KACJG,UAAU,CAAC,QACXE,KAAK,CAACT,kBACNU,GAAG;IACN,KAAK,MAAMC,cAAcL,YAAYM,IAAI,CAAE;YAKtCC;QAJH,MAAMC,QAAQH,WAAWI,EAAE;QAC3B,MAAMC,SAASb,UAAUI,UAAU,CAAC,QAAQC,GAAG,CA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P0B,OAA2C,EAC3CC,cAAsB,EACtBC,gBAAwB,EACxBC,iBAAyB;QAEYH,cAG5BA,eAIAA;IAPT,MAAMI,YAAYxB,KAAKE,GAAG,CAAC,GAAGZ,QAAO8B,eAAAA,QAAQlF,GAAG,CAAC,wBAAZkF,eAA4B,KAAKC;IACtE,MAAMI,cAAczB,KAAKE,GAAG,CAC1B,GACAZ,QAAO8B,gBAAAA,QAAQlF,GAAG,CAAC,0BAAZkF,gBAA8B,KAAKE;IAE5C,MAAMI,eAAe1B,KAAKE,GAAG,CAC3B,GACAZ,QAAO8B,gBAAAA,QAAQlF,GAAG,CAAC,2BAAZkF,gBAA+B,KAAKG;IAE7C,OAAO;QACLC;QACAC;QACAC;QACA,qEAAqE;QACrEC,eAAeF,cACXzB,KAAKG,KAAK,CAAC,AAACqB,YAAYC,cAAe,MAAM,KAC7C;QACJG,WAAWxG,cAAcO,SAAS,CAACkG,UAAU,CAACC,eAAe;IAC/D;AACF;AAEA,eAAexE,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/reviews.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { findUserByUidAcrossPools } from '@aglyn/tenant-data-admin/server/auth-pools'\nimport { canActAsPublisher } from './publisher-profile'\nimport { isOrgMember } from './sale-risk'\n\nconst MAX_COMMENT_LENGTH = 2000\n/** Orgs scanned when looking for an install pin. */\nconst MAX_ORGS_CHECKED = 25\n\n/**\n * Whether the author has actually used this listing (AGL-655).\n *\n * An install pin lives at `orgs/{orgId}/installs/{listingId}` (org-wide) or\n * `hosts/{hostId}/installs/{listingId}` (one site), and **it is one or the\n * other** — `install-plugin` reassigns its target ref to the org path for an\n * org-scoped install rather than writing both.\n *\n * This used to read the org pin alone, on the stated reasoning that \"a host\n * pin implies the org installed it somewhere, and the org mirror is what the\n * install routes write\" (AGL-1006). There is no org mirror, so a per-site\n * install left nothing to find and the workspace was refused a rating — and\n * it refused exactly the careful installers, the ones who scoped a plugin to\n * one site before rolling it out. Ratings drive marketplace ranking, so that\n * skewed the sample toward org-wide installers.\n *\n * Host pins are found through the org doc's own `hosts` map (written by\n * `registerOrgHost`), then read in ONE batched `getAll` alongside the org\n * pin. Two round trips per org, bounded and index-free — deliberately not a\n * collection-group query on `installs`, which would need a new index and\n * would match every tenant's pins for a listing, unbounded, to answer a\n * question about one org.\n */\nconst MAX_HOSTS_CHECKED = 50\n\n// Exported for the AGL-1006 regression test: it takes its firestore, so the\n// rule \"a host pin counts\" is checkable without standing up the whole\n// handler (auth, transactions, aggregate writes).\nexport async function isVerifiedInstaller(\n firestore: FirebaseFirestore.Firestore,\n uid: string,\n listingId: string,\n): Promise<{ verified: boolean; orgId?: string }> {\n const memberships = await firestore\n .collection('users')\n .doc(uid)\n .collection('orgs')\n .limit(MAX_ORGS_CHECKED)\n .get()\n for (const membership of memberships.docs) {\n const orgId = membership.id\n const orgRef = firestore.collection('orgs').doc(orgId)\n const org = await orgRef.get()\n const hostIds = Object.keys(\n (org.get('hosts') as Record<string, unknown> | undefined) ?? {},\n ).slice(0, MAX_HOSTS_CHECKED)\n const refs = [\n orgRef.collection('installs').doc(listingId),\n ...hostIds.map((hostId) =>\n firestore\n .collection('hosts')\n .doc(hostId)\n .collection('installs')\n .doc(listingId),\n ),\n ]\n const pins = await firestore.getAll(...refs)\n if (pins.some((pin) => pin.exists)) return { verified: true, orgId }\n }\n return { verified: false }\n}\n\n/** An account younger than this may comment but not rate (AGL-3365). */\nexport const REVIEW_MIN_ACCOUNT_AGE_DAYS = 7\n\n/**\n * Whether the Firebase account is younger than\n * {@link REVIEW_MIN_ACCOUNT_AGE_DAYS}. An account whose creation time cannot\n * be read is not new — the answer that never locks an existing customer out.\n */\nexport async function isNewAccount(uid: string, nowMs = Date.now()): Promise<boolean> {\n try {\n // Across pools (AGL-1122): an SSO reviewer is not in the project pool.\n const user = (await findUserByUidAcrossPools(uid))?.record\n const createdMs = Date.parse(String(user?.metadata?.creationTime ?? ''))\n if (!Number.isFinite(createdMs)) return false\n return nowMs - createdMs < REVIEW_MIN_ACCOUNT_AGE_DAYS * 86_400_000\n } catch {\n return false\n }\n}\n\n/**\n * Ratings and comments on a marketplace listing (AGL-655).\n *\n * One review per account, keyed by uid, so re-submitting edits rather than\n * stacking. Two rules shape everything else:\n *\n * - **Rating requires a verified email AND having installed it (AGL-865).**\n * A star rating is the signal that drives ranking, so it is reserved for\n * accounts that verified their email and actually used the thing.\n * Commenting stays open to any signed-in account — questions before\n * installing are useful, and a comment moves no numbers.\n * - **The publisher cannot review their own listing.** Org-scoped, so a\n * second account in the same org does not slip through.\n *\n * Aggregates are adjusted in the same transaction as the review, and are\n * frozen from client writes in rules. Kept as a running `ratingSum` +\n * `ratingCount` so a submission costs one read, not a scan of every review.\n */\nexport const reviewsHandler: PluginApiHandler = async (req, res) => {\n const method = req.method === 'DELETE' ? 'DELETE' : 'POST'\n if (req.method !== 'POST' && req.method !== 'DELETE') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\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 try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (!listing || listing.deletedAt) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const reviewRef = listingRef.collection('reviews').doc(decoded.uid)\n\n if (method === 'DELETE') {\n await firestore.runTransaction(async (tx) => {\n const [existing, listingNow] = await Promise.all([\n tx.get(reviewRef),\n tx.get(listingRef),\n ])\n if (!existing.exists) return\n const previousRating = Number(existing.get('rating') ?? 0) || 0\n const hadComment = !!existing.get('comment')\n tx.delete(reviewRef)\n tx.update(\n listingRef,\n nextAggregates(\n listingNow,\n -previousRating,\n previousRating ? -1 : 0,\n hadComment ? -1 : 0,\n ),\n )\n })\n return res.status(200).json({ ok: true, removed: true })\n }\n\n // Publishing org cannot review itself, however many accounts it has —\n // ANY member of it (AGL-3365). `canActAsPublisher` answers only for an\n // owner or admin, so an editor of the publisher could rate its listing.\n if (\n (await canActAsPublisher(firestore, decoded.uid, listing.profileId)) ||\n (await isOrgMember(firestore, String(listing.profileId ?? ''), decoded.uid))\n ) {\n return res.status(403).json({\n error: 'You cannot review your organization’s own listing',\n })\n }\n\n const rawRating = req.body?.rating\n const rating =\n rawRating == null || rawRating === ''\n ? 0\n : Math.min(5, Math.max(1, Math.round(Number(rawRating) || 0)))\n const comment = String(req.body?.comment ?? '')\n .trim()\n .slice(0, MAX_COMMENT_LENGTH)\n if (!rating && !comment) {\n return res.status(400).json({ error: 'Add a rating or a comment' })\n }\n\n // A star rating drives ranking, so it is reserved for accounts that both\n // verified their email (AGL-865/479) AND actually installed the thing.\n // Commenting stays open to any signed-in account — the checks below only\n // guard `rating`, never `comment`. Impersonation sessions are exempt from\n // the email gate the same way every other AGL-479 chokepoint is.\n if (rating && !decoded.email_verified && !isImpersonationSession(decoded)) {\n return res.status(403).json({\n error: 'Verify your email to rate — you can still leave a comment',\n reason: 'email-unverified',\n })\n }\n // A rating from a brand-new account is refused (AGL-3365): a burst of\n // fresh accounts installing a free listing and rating it five stars is\n // the cheapest way to buy ranking. The comment stays open, and the words\n // say what to do, never where the line is.\n if (rating && (await isNewAccount(decoded.uid))) {\n return res.status(403).json({\n error:\n 'Ratings open once your account has been active for a little while — ' +\n 'you can still leave a comment',\n reason: 'account-too-new',\n })\n }\n const installer = await isVerifiedInstaller(firestore, decoded.uid, listingId)\n // The workspace that installed it must not be the publisher's own\n // (AGL-3365) — the member check above covers the reviewer, this the org\n // whose install vouches for the rating.\n if (rating && installer.orgId && installer.orgId === listing.profileId) {\n return res.status(403).json({\n error: 'You cannot review your organization’s own listing',\n })\n }\n if (rating && !installer.verified) {\n return res.status(403).json({\n error:\n 'Only organizations that have installed this can rate it — you ' +\n 'can still leave a comment',\n })\n }\n\n const now = Date.now()\n await firestore.runTransaction(async (tx) => {\n const [existing, listingNow] = await Promise.all([\n tx.get(reviewRef),\n tx.get(listingRef),\n ])\n const previousRating = Number(existing.get('rating') ?? 0) || 0\n const hadComment = existing.exists && !!existing.get('comment')\n tx.set(\n reviewRef,\n {\n uid: decoded.uid,\n displayName: String(decoded.name ?? 'Someone').slice(0, 80),\n ...(rating ? { rating } : { rating: null }),\n ...(comment ? { comment } : { comment: null }),\n verifiedInstaller: installer.verified,\n ...(installer.orgId ? { orgId: installer.orgId } : {}),\n // Preserved across edits: a moderator's decision must not be\n // undone by the author simply resubmitting.\n hidden: existing.get('hidden') ?? false,\n ...(existing.exists ? {} : { createdAtMs: now }),\n updatedAtMs: now,\n },\n { merge: true },\n )\n tx.update(\n listingRef,\n nextAggregates(\n listingNow,\n rating - previousRating,\n (rating ? 1 : 0) - (previousRating ? 1 : 0),\n (comment ? 1 : 0) - (hadComment ? 1 : 0),\n ),\n )\n })\n\n return res.status(200).json({\n ok: true,\n rating: rating || null,\n verifiedInstaller: installer.verified,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Review failed' })\n }\n}\n\n/**\n * Absolute aggregate values after a change.\n *\n * Written as numbers rather than `FieldValue.increment` because\n * `ratingAverage` has to be stored — browse sorts on it, and a transaction\n * cannot divide two pending increments. Reading the listing inside the\n * transaction makes the read-modify-write atomic, so concurrent reviews\n * cannot interleave and lose a vote.\n */\nfunction nextAggregates(\n current: FirebaseFirestore.DocumentSnapshot,\n ratingSumDelta: number,\n ratingCountDelta: number,\n commentCountDelta: number,\n): Record<string, unknown> {\n const ratingSum = Math.max(0, Number(current.get('ratingSum') ?? 0) + ratingSumDelta)\n const ratingCount = Math.max(\n 0,\n Number(current.get('ratingCount') ?? 0) + ratingCountDelta,\n )\n const commentCount = Math.max(\n 0,\n Number(current.get('commentCount') ?? 0) + commentCountDelta,\n )\n return {\n ratingSum,\n ratingCount,\n commentCount,\n // One decimal — enough for \"4.2\", and avoids a long float in the UI.\n ratingAverage: ratingCount\n ? Math.round((ratingSum / ratingCount) * 10) / 10\n : 0,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }\n}\n\nexport default reviewsHandler\n"],"names":["firebaseAdmin","isImpersonationSession","findUserByUidAcrossPools","canActAsPublisher","isOrgMember","MAX_COMMENT_LENGTH","MAX_ORGS_CHECKED","MAX_HOSTS_CHECKED","isVerifiedInstaller","firestore","uid","listingId","memberships","collection","doc","limit","get","membership","docs","org","orgId","id","orgRef","hostIds","Object","keys","slice","refs","map","hostId","pins","getAll","some","pin","exists","verified","REVIEW_MIN_ACCOUNT_AGE_DAYS","isNewAccount","nowMs","Date","now","user","record","createdMs","parse","String","metadata","creationTime","Number","isFinite","reviewsHandler","req","res","method","status","json","error","body","authorization","headers","idToken","startsWith","length","undefined","listing","decoded","app","auth","verifyIdToken","listingRef","listingSnapshot","data","deletedAt","reviewRef","runTransaction","tx","existing","listingNow","Promise","all","previousRating","hadComment","delete","update","nextAggregates","ok","removed","profileId","rawRating","rating","Math","min","max","round","comment","trim","email_verified","reason","installer","set","displayName","name","verifiedInstaller","hidden","createdAtMs","updatedAtMs","merge","console","current","ratingSumDelta","ratingCountDelta","commentCountDelta","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license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type SaleRiskSignal } from '../model/publisher-risk';
18
+ /**
19
+ * Whether `uid` is ANY member of `orgId` — not only a manager, which is all
20
+ * `canActAsPublisher` asks. A publishing workspace's editor buying its
21
+ * listing is the publisher buying it.
22
+ */
23
+ export declare function isOrgMember(firestore: FirebaseFirestore.Firestore, orgId: string, uid: string): Promise<boolean>;
24
+ /**
25
+ * Whether the publishing workspace is under a SECURITY lock (AGL-3365) — the
26
+ * install and update doors hand nothing from it over. Security only: a
27
+ * workspace locked over its own unpaid bill has not made its listings
28
+ * dangerous, and a buyer who paid for one keeps installing it. (Checkout
29
+ * refuses a sale to a workspace under ANY lock; that is money moving to it.)
30
+ *
31
+ * The shared normalizer reads the reason, so a lock written before reason
32
+ * codes existed reads as `manual`, not security. One read of the org.
33
+ */
34
+ export declare function isPublisherSecurityLocked(firestore: FirebaseFirestore.Firestore, publisherOrgId: unknown): Promise<boolean>;
35
+ /**
36
+ * Put a publisher's connected account on the payout schedule its age calls
37
+ * for (`publisherPayoutDelayDays`), and note it on the profile.
38
+ *
39
+ * Writes to Stripe only when the answer CHANGES what this code last set: a
40
+ * young publisher is moved to the delay once, and moved back to the standard
41
+ * schedule once when it ages out. An account this code never delayed is
42
+ * never written — a schedule staff set by hand in the Dashboard is theirs.
43
+ *
44
+ * Never throws: onboarding and a sale must both go on if Stripe says no.
45
+ */
46
+ export declare function applyPublisherPayoutPolicy(input: {
47
+ firestore: FirebaseFirestore.Firestore;
48
+ publisherOrgId: string;
49
+ ageDays: number | null;
50
+ stripeKey: string | undefined;
51
+ nowMs?: number;
52
+ }): Promise<'applied' | 'current' | 'held-by-lock' | 'skipped' | 'failed'>;
53
+ /** Tell staff a sale was flagged (AGL-3365), once per row. Never throws. */
54
+ export declare function notifyStaffOfSaleRisk(notify: (payload: {
55
+ type: 'system.abuseReportUrgent';
56
+ title: string;
57
+ body: string;
58
+ link: string;
59
+ }) => Promise<void>, flagged: {
60
+ reference: string;
61
+ signals: readonly SaleRiskSignal[];
62
+ }): Promise<void>;
63
+ /**
64
+ * Tell the publisher's owners and admins a sale is under review (AGL-3365).
65
+ * The outcome and the way forward only — never which shape flagged it, which
66
+ * would teach the actor it describes how to avoid it. Never throws.
67
+ */
68
+ export declare function notifyPublisherSaleUnderReview(publisherOrgId: string, flagged: {
69
+ reference: string;
70
+ }): Promise<void>;
71
+ /**
72
+ * Tell the publisher's owners and admins their payout timing changed
73
+ * (AGL-3365) — when a hold starts, and when it ends. Never the rule that set
74
+ * it. Never throws.
75
+ */
76
+ export declare function notifyPublisherPayoutSchedule(publisherOrgId: string, held: boolean): Promise<void>;
77
+ /** The sale-risk row's id: one per sale. */
78
+ export declare function saleRiskReviewId(sessionId: string): string;
79
+ /**
80
+ * Read one recorded sale for the fraud shapes above, hold a young
81
+ * publisher's payouts, and file a staff row when anything is found.
82
+ */
83
+ export declare function screenMarketplaceSale(input: {
84
+ purchaseRef: FirebaseFirestore.DocumentReference;
85
+ sessionId: string;
86
+ buyerUid: string;
87
+ buyerOrgId: string | null;
88
+ sellerOrgId: string;
89
+ amountCents: number;
90
+ paymentIntentId: string;
91
+ livemode: boolean;
92
+ }, deps: {
93
+ firestore?: FirebaseFirestore.Firestore;
94
+ stripeKey?: string;
95
+ notify: (payload: {
96
+ type: 'system.abuseReportUrgent';
97
+ title: string;
98
+ body: string;
99
+ link: string;
100
+ }) => Promise<void>;
101
+ nowMs?: number;
102
+ }): Promise<{
103
+ signals: SaleRiskSignal[];
104
+ filed: string | null;
105
+ }>;
@@ -0,0 +1,323 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ /*==========================================
18
+ * A MARKETPLACE SALE'S FRAUD SHAPE (AGL-3365).
19
+ *
20
+ * Two questions the card network cannot answer, because both sides of the
21
+ * sale are ours:
22
+ *
23
+ * 1. **Is the publisher paying itself?** A publisher that buys its own
24
+ * listing with stolen cards turns them into a payout. Checkout refuses a
25
+ * buyer who is a member of the publishing workspace; a second workspace
26
+ * that shares a member with it, or ONE card buying from one publisher for
27
+ * several workspaces, is the same actor one step removed.
28
+ * 2. **Is the publisher brand new?** See `model/publisher-risk.ts`: its
29
+ * payouts are held, and a large sale files a signal while the share can
30
+ * still be reversed.
31
+ *
32
+ * What it does is what the seller-pattern ledger does: an urgent row in the
33
+ * abuse queue, staff told once. NOTHING IS REFUNDED, REVERSED OR PAUSED
34
+ * HERE — staff decide, with the young tier's payout delay holding the money
35
+ * in reach while they do.
36
+ *
37
+ * Never throws: the sale it reads has already been recorded.
38
+ *=========================================*/ import { createHash } from "crypto";
39
+ import { ABUSE_REPORT_COLLECTION } from "@aglyn/aglyn/app-utils/abuse-report";
40
+ import { normalizeOrgLockdown } from "@aglyn/aglyn/app-utils/lockdown";
41
+ import { LOCKDOWN_BILLING_PAUSES_COLLECTION, lockdownPayoutPauseRecordId } from "@aglyn/aglyn/plugin-manager/plugin-org-lockdown";
42
+ import { firebaseAdmin, notifyOrgAdmins } from "@aglyn/tenant-data-admin";
43
+ import { orgAgeDays } from "@aglyn/tenant-data-admin/server/org-age";
44
+ import { describeSaleRiskSignals, isYoungPublisher, publisherPayoutDelayDays, YOUNG_PUBLISHER_REVIEW_SALE_CENTS } from "../model/publisher-risk.js";
45
+ /** Members read per workspace when looking for a shared one. */ const MAX_MEMBERS_COMPARED = 200;
46
+ /** Earlier purchases read when looking for the same card. */ const MAX_CARD_MATCHES = 20;
47
+ /**
48
+ * Whether `uid` is ANY member of `orgId` — not only a manager, which is all
49
+ * `canActAsPublisher` asks. A publishing workspace's editor buying its
50
+ * listing is the publisher buying it.
51
+ */ export async function isOrgMember(firestore, orgId, uid) {
52
+ if (!orgId || !uid) return false;
53
+ const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(uid).get();
54
+ return member.exists;
55
+ }
56
+ /**
57
+ * Whether the publishing workspace is under a SECURITY lock (AGL-3365) — the
58
+ * install and update doors hand nothing from it over. Security only: a
59
+ * workspace locked over its own unpaid bill has not made its listings
60
+ * dangerous, and a buyer who paid for one keeps installing it. (Checkout
61
+ * refuses a sale to a workspace under ANY lock; that is money moving to it.)
62
+ *
63
+ * The shared normalizer reads the reason, so a lock written before reason
64
+ * codes existed reads as `manual`, not security. One read of the org.
65
+ */ export async function isPublisherSecurityLocked(firestore, publisherOrgId) {
66
+ var _normalizeOrgLockdown;
67
+ const orgId = typeof publisherOrgId === 'string' ? publisherOrgId : '';
68
+ if (!orgId) return false;
69
+ const org = (await firestore.collection('orgs').doc(orgId).get()).data();
70
+ return ((_normalizeOrgLockdown = normalizeOrgLockdown(org)) == null ? void 0 : _normalizeOrgLockdown.reason) === 'security';
71
+ }
72
+ async function memberUids(firestore, orgId) {
73
+ const snapshot = await firestore.collection('orgs').doc(orgId).collection('members').limit(MAX_MEMBERS_COMPARED).get();
74
+ return snapshot.docs.map((doc)=>doc.id);
75
+ }
76
+ async function stripeRequest(path, stripeKey, params) {
77
+ const response = await fetch(`https://api.stripe.com/v1/${path}`, _extends({
78
+ method: params ? 'POST' : 'GET',
79
+ headers: _extends({
80
+ Authorization: `Bearer ${stripeKey}`
81
+ }, params ? {
82
+ 'Content-Type': 'application/x-www-form-urlencoded'
83
+ } : {})
84
+ }, params ? {
85
+ body: params.toString()
86
+ } : {}));
87
+ const body = await response.json().catch(()=>null);
88
+ return {
89
+ ok: response.ok,
90
+ body
91
+ };
92
+ }
93
+ /**
94
+ * Put a publisher's connected account on the payout schedule its age calls
95
+ * for (`publisherPayoutDelayDays`), and note it on the profile.
96
+ *
97
+ * Writes to Stripe only when the answer CHANGES what this code last set: a
98
+ * young publisher is moved to the delay once, and moved back to the standard
99
+ * schedule once when it ages out. An account this code never delayed is
100
+ * never written — a schedule staff set by hand in the Dashboard is theirs.
101
+ *
102
+ * Never throws: onboarding and a sale must both go on if Stripe says no.
103
+ */ export async function applyPublisherPayoutPolicy(input) {
104
+ try {
105
+ var _profile_get, _input_nowMs;
106
+ if (!input.stripeKey || !input.publisherOrgId) return 'skipped';
107
+ const profileRef = input.firestore.collection('publisherProfiles').doc(input.publisherOrgId);
108
+ const profile = await profileRef.get();
109
+ const accountId = String((_profile_get = profile.get('stripeAccountId')) != null ? _profile_get : '');
110
+ if (!accountId) return 'skipped';
111
+ // A workspace lock holds this account's payouts (AGL-3364/3365): its
112
+ // schedule is manual and the lock saved the one to restore. Moving it
113
+ // now would either undo the pause or leave the lift restoring a delay
114
+ // this record no longer describes, so it waits. The next sale after the
115
+ // lift sets it right.
116
+ const lockHold = await input.firestore.collection(LOCKDOWN_BILLING_PAUSES_COLLECTION).doc(lockdownPayoutPauseRecordId(accountId)).get();
117
+ if (lockHold.exists) return 'held-by-lock';
118
+ const desired = publisherPayoutDelayDays(input.ageDays);
119
+ const stored = profile.get('payoutDelayDays');
120
+ if (stored === desired) return 'current';
121
+ // Never delayed by this code and not young: leave the account alone.
122
+ if (stored === undefined && desired === null) return 'current';
123
+ const result = await stripeRequest(`accounts/${encodeURIComponent(accountId)}`, input.stripeKey, new URLSearchParams({
124
+ 'settings[payouts][schedule][delay_days]': desired === null ? 'minimum' : String(desired)
125
+ }));
126
+ if (!result.ok) {
127
+ var _result_body_error, _result_body;
128
+ console.error('[marketplace] the payout schedule could not be set', {
129
+ publisherOrgId: input.publisherOrgId,
130
+ error: (_result_body = result.body) == null ? void 0 : (_result_body_error = _result_body.error) == null ? void 0 : _result_body_error.message
131
+ });
132
+ return 'failed';
133
+ }
134
+ await profileRef.set({
135
+ payoutDelayDays: desired,
136
+ payoutPolicyAtMs: (_input_nowMs = input.nowMs) != null ? _input_nowMs : Date.now()
137
+ }, {
138
+ merge: true
139
+ });
140
+ await notifyPublisherPayoutSchedule(input.publisherOrgId, desired !== null);
141
+ return 'applied';
142
+ } catch (error) {
143
+ console.error('[marketplace] the payout schedule could not be set', error);
144
+ return 'failed';
145
+ }
146
+ }
147
+ /** The card that paid a payment intent, as Stripe fingerprints it, or null. */ async function cardFingerprintOf(paymentIntentId, stripeKey) {
148
+ var _result_body_latest_charge_payment_method_details_card, _result_body_latest_charge_payment_method_details, _result_body_latest_charge, _result_body;
149
+ const result = await stripeRequest(`payment_intents/${encodeURIComponent(paymentIntentId)}?expand[]=latest_charge`, stripeKey);
150
+ const fingerprint = (_result_body = result.body) == null ? void 0 : (_result_body_latest_charge = _result_body.latest_charge) == null ? void 0 : (_result_body_latest_charge_payment_method_details = _result_body_latest_charge.payment_method_details) == null ? void 0 : (_result_body_latest_charge_payment_method_details_card = _result_body_latest_charge_payment_method_details.card) == null ? void 0 : _result_body_latest_charge_payment_method_details_card.fingerprint;
151
+ return result.ok && typeof fingerprint === 'string' && fingerprint ? fingerprint : null;
152
+ }
153
+ /** Tell staff a sale was flagged (AGL-3365), once per row. Never throws. */ export async function notifyStaffOfSaleRisk(notify, flagged) {
154
+ await notify({
155
+ type: 'system.abuseReportUrgent',
156
+ title: 'Marketplace sale flagged — possible self-dealing or card fraud',
157
+ body: `${describeSaleRiskSignals(flagged.signals).join(' ')} Nothing has been refunded or ` + `paused. Review the sale and the publisher. Reference ${flagged.reference}.`,
158
+ link: '/admin/abuse-reports'
159
+ }).catch(()=>undefined);
160
+ }
161
+ /**
162
+ * Tell the publisher's owners and admins a sale is under review (AGL-3365).
163
+ * The outcome and the way forward only — never which shape flagged it, which
164
+ * would teach the actor it describes how to avoid it. Never throws.
165
+ */ export async function notifyPublisherSaleUnderReview(publisherOrgId, flagged) {
166
+ await notifyOrgAdmins(publisherOrgId, {
167
+ type: 'marketplace.review',
168
+ title: 'A marketplace sale is under review',
169
+ body: 'One of your recent marketplace sales is being reviewed by our team, and its payout may ' + 'take longer than usual. You do not need to do anything. To ask about it, contact ' + `support with reference ${flagged.reference}.`,
170
+ link: '/manage/marketplace'
171
+ }).catch(()=>undefined);
172
+ }
173
+ /**
174
+ * Tell the publisher's owners and admins their payout timing changed
175
+ * (AGL-3365) — when a hold starts, and when it ends. Never the rule that set
176
+ * it. Never throws.
177
+ */ export async function notifyPublisherPayoutSchedule(publisherOrgId, held) {
178
+ await notifyOrgAdmins(publisherOrgId, {
179
+ type: 'marketplace.review',
180
+ title: held ? 'Your marketplace payouts are on an extended schedule' : 'Your marketplace payouts are back on the standard schedule',
181
+ body: held ? 'Payouts to new publishers are held for a period before they reach your bank. Your ' + 'sales are recorded as usual and pay out automatically when the period ends. To ask ' + 'about it, contact support.' : 'Your marketplace sales now pay out on your payout account’s standard schedule.',
182
+ link: '/manage/marketplace'
183
+ }).catch(()=>undefined);
184
+ }
185
+ /** The sale-risk row's id: one per sale. */ export function saleRiskReviewId(sessionId) {
186
+ return createHash('sha256').update(`marketplace-sale-risk:${sessionId}`).digest('hex').slice(0, 40);
187
+ }
188
+ /**
189
+ * Read one recorded sale for the fraud shapes above, hold a young
190
+ * publisher's payouts, and file a staff row when anything is found.
191
+ */ export async function screenMarketplaceSale(input, deps) {
192
+ var _deps_nowMs;
193
+ const nowMs = (_deps_nowMs = deps.nowMs) != null ? _deps_nowMs : Date.now();
194
+ const signals = [];
195
+ try {
196
+ var _deps_firestore, _data;
197
+ const firestore = (_deps_firestore = deps.firestore) != null ? _deps_firestore : firebaseAdmin.app().firestore();
198
+ const sellerOrg = (_data = (await firestore.collection('orgs').doc(input.sellerOrgId).get()).data()) != null ? _data : {};
199
+ const ageDays = orgAgeDays(sellerOrg.createdAt, nowMs);
200
+ // 1. A young publisher: hold its payouts; a large sale is a signal.
201
+ await applyPublisherPayoutPolicy({
202
+ firestore,
203
+ publisherOrgId: input.sellerOrgId,
204
+ ageDays,
205
+ stripeKey: deps.stripeKey,
206
+ nowMs
207
+ });
208
+ if (isYoungPublisher(ageDays) && input.amountCents >= YOUNG_PUBLISHER_REVIEW_SALE_CENTS) {
209
+ signals.push({
210
+ code: 'young-publisher-large-sale',
211
+ ageDays: ageDays,
212
+ amountCents: input.amountCents
213
+ });
214
+ }
215
+ // 2. A member in both workspaces — the buyer themself included.
216
+ const sellerMembers = new Set(await memberUids(firestore, input.sellerOrgId));
217
+ const buyerSide = new Set([
218
+ input.buyerUid,
219
+ ...input.buyerOrgId && input.buyerOrgId !== input.sellerOrgId ? await memberUids(firestore, input.buyerOrgId) : []
220
+ ]);
221
+ const shared = [
222
+ ...buyerSide
223
+ ].filter((uid)=>uid && sellerMembers.has(uid)).sort();
224
+ if (shared.length || input.buyerOrgId && input.buyerOrgId === input.sellerOrgId) {
225
+ signals.push({
226
+ code: 'shared-member',
227
+ uids: shared
228
+ });
229
+ }
230
+ // 3. One card, several buyer workspaces, one publisher.
231
+ if (deps.stripeKey && input.paymentIntentId) {
232
+ const fingerprint = await cardFingerprintOf(input.paymentIntentId, deps.stripeKey);
233
+ if (fingerprint) {
234
+ await input.purchaseRef.set({
235
+ cardFingerprint: fingerprint
236
+ }, {
237
+ merge: true
238
+ });
239
+ const matches = await firestore.collection('marketplacePurchases').where('sellerOrgId', '==', input.sellerOrgId).where('cardFingerprint', '==', fingerprint).limit(MAX_CARD_MATCHES).get();
240
+ const others = [
241
+ ...new Set(matches.docs.map((doc)=>{
242
+ var _doc_get;
243
+ return String((_doc_get = doc.get('buyerOrgId')) != null ? _doc_get : '');
244
+ }).filter((orgId)=>{
245
+ var _input_buyerOrgId;
246
+ return orgId && orgId !== ((_input_buyerOrgId = input.buyerOrgId) != null ? _input_buyerOrgId : '');
247
+ }))
248
+ ].sort();
249
+ if (others.length) {
250
+ signals.push({
251
+ code: 'card-reused-across-buyers',
252
+ otherBuyerOrgIds: others
253
+ });
254
+ }
255
+ }
256
+ }
257
+ if (!signals.length) return {
258
+ signals,
259
+ filed: null
260
+ };
261
+ const reviewId = saleRiskReviewId(input.sessionId);
262
+ const reference = `MR-${reviewId.slice(0, 10).toUpperCase()}`;
263
+ const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(reviewId);
264
+ const first = !(await ref.get()).exists;
265
+ await ref.set(_extends({
266
+ reference,
267
+ category: 'phishing',
268
+ severity: 'urgent',
269
+ source: 'marketplace-sale-risk',
270
+ url: null,
271
+ reportedHostname: null,
272
+ hostId: null,
273
+ orgId: input.sellerOrgId,
274
+ details: [
275
+ `A marketplace sale (checkout ${input.sessionId}, payment ${input.paymentIntentId || 'unknown'}) ` + `paid publisher workspace ${input.sellerOrgId} $${(input.amountCents / 100).toFixed(2)} ` + `from buyer ${input.buyerUid}${input.buyerOrgId ? ` for workspace ${input.buyerOrgId}` : ''}` + (input.livemode ? '' : ' — TEST MODE') + '.',
276
+ ...describeSaleRiskSignals(signals),
277
+ 'A publisher buying its own listings with stolen cards, to cash them out as payouts, leaves this shape.',
278
+ 'Nothing has been refunded, reversed or paused. If it is the publisher, lock its workspace and ' + "refund the sale (the refund takes the publisher's share back), then close this row with what you did."
279
+ ].join('\n').slice(0, 5000),
280
+ reporterEmail: null,
281
+ reporterName: null,
282
+ dmca: null,
283
+ reportCount: 1,
284
+ saleRisk: {
285
+ sessionId: input.sessionId,
286
+ paymentIntentId: input.paymentIntentId || null,
287
+ sellerOrgId: input.sellerOrgId,
288
+ buyerOrgId: input.buyerOrgId,
289
+ buyerUid: input.buyerUid,
290
+ amountCents: input.amountCents,
291
+ signals,
292
+ livemode: input.livemode
293
+ },
294
+ updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
295
+ }, first ? {
296
+ status: 'open',
297
+ createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
298
+ } : {}), {
299
+ merge: true
300
+ });
301
+ if (first) {
302
+ await notifyStaffOfSaleRisk(deps.notify, {
303
+ reference,
304
+ signals
305
+ });
306
+ await notifyPublisherSaleUnderReview(input.sellerOrgId, {
307
+ reference
308
+ });
309
+ }
310
+ return {
311
+ signals,
312
+ filed: reference
313
+ };
314
+ } catch (error) {
315
+ console.error('[marketplace] a sale could not be screened', error);
316
+ return {
317
+ signals,
318
+ filed: null
319
+ };
320
+ }
321
+ }
322
+
323
+ //# sourceMappingURL=sale-risk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/sale-risk.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/*==========================================\n * A MARKETPLACE SALE'S FRAUD SHAPE (AGL-3365).\n *\n * Two questions the card network cannot answer, because both sides of the\n * sale are ours:\n *\n * 1. **Is the publisher paying itself?** A publisher that buys its own\n * listing with stolen cards turns them into a payout. Checkout refuses a\n * buyer who is a member of the publishing workspace; a second workspace\n * that shares a member with it, or ONE card buying from one publisher for\n * several workspaces, is the same actor one step removed.\n * 2. **Is the publisher brand new?** See `model/publisher-risk.ts`: its\n * payouts are held, and a large sale files a signal while the share can\n * still be reversed.\n *\n * What it does is what the seller-pattern ledger does: an urgent row in the\n * abuse queue, staff told once. NOTHING IS REFUNDED, REVERSED OR PAUSED\n * HERE — staff decide, with the young tier's payout delay holding the money\n * in reach while they do.\n *\n * Never throws: the sale it reads has already been recorded.\n *=========================================*/\n\nimport { createHash } from 'crypto'\nimport { ABUSE_REPORT_COLLECTION } from '@aglyn/aglyn/app-utils/abuse-report'\nimport { normalizeOrgLockdown } from '@aglyn/aglyn/app-utils/lockdown'\nimport {\n LOCKDOWN_BILLING_PAUSES_COLLECTION,\n lockdownPayoutPauseRecordId,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-lockdown'\nimport { firebaseAdmin, notifyOrgAdmins } from '@aglyn/tenant-data-admin'\nimport { orgAgeDays } from '@aglyn/tenant-data-admin/server/org-age'\nimport {\n describeSaleRiskSignals,\n isYoungPublisher,\n publisherPayoutDelayDays,\n type SaleRiskSignal,\n YOUNG_PUBLISHER_REVIEW_SALE_CENTS,\n} from '../model/publisher-risk'\n\n/** Members read per workspace when looking for a shared one. */\nconst MAX_MEMBERS_COMPARED = 200\n/** Earlier purchases read when looking for the same card. */\nconst MAX_CARD_MATCHES = 20\n\n/**\n * Whether `uid` is ANY member of `orgId` — not only a manager, which is all\n * `canActAsPublisher` asks. A publishing workspace's editor buying its\n * listing is the publisher buying it.\n */\nexport async function isOrgMember(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n uid: string,\n): Promise<boolean> {\n if (!orgId || !uid) return false\n const member = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(uid)\n .get()\n return member.exists\n}\n\n/**\n * Whether the publishing workspace is under a SECURITY lock (AGL-3365) — the\n * install and update doors hand nothing from it over. Security only: a\n * workspace locked over its own unpaid bill has not made its listings\n * dangerous, and a buyer who paid for one keeps installing it. (Checkout\n * refuses a sale to a workspace under ANY lock; that is money moving to it.)\n *\n * The shared normalizer reads the reason, so a lock written before reason\n * codes existed reads as `manual`, not security. One read of the org.\n */\nexport async function isPublisherSecurityLocked(\n firestore: FirebaseFirestore.Firestore,\n publisherOrgId: unknown,\n): Promise<boolean> {\n const orgId = typeof publisherOrgId === 'string' ? publisherOrgId : ''\n if (!orgId) return false\n const org = (await firestore.collection('orgs').doc(orgId).get()).data()\n return normalizeOrgLockdown(org as Parameters<typeof normalizeOrgLockdown>[0])?.reason === 'security'\n}\n\nasync function memberUids(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> {\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .limit(MAX_MEMBERS_COMPARED)\n .get()\n return snapshot.docs.map((doc) => doc.id)\n}\n\nasync function stripeRequest(\n path: string,\n stripeKey: string,\n params?: URLSearchParams,\n): Promise<{ ok: boolean; body: any }> {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${stripeKey}`,\n ...(params ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}),\n },\n ...(params ? { body: params.toString() } : {}),\n })\n const body = await response.json().catch(() => null)\n return { ok: response.ok, body }\n}\n\n/**\n * Put a publisher's connected account on the payout schedule its age calls\n * for (`publisherPayoutDelayDays`), and note it on the profile.\n *\n * Writes to Stripe only when the answer CHANGES what this code last set: a\n * young publisher is moved to the delay once, and moved back to the standard\n * schedule once when it ages out. An account this code never delayed is\n * never written — a schedule staff set by hand in the Dashboard is theirs.\n *\n * Never throws: onboarding and a sale must both go on if Stripe says no.\n */\nexport async function applyPublisherPayoutPolicy(input: {\n firestore: FirebaseFirestore.Firestore\n publisherOrgId: string\n ageDays: number | null\n stripeKey: string | undefined\n nowMs?: number\n}): Promise<'applied' | 'current' | 'held-by-lock' | 'skipped' | 'failed'> {\n try {\n if (!input.stripeKey || !input.publisherOrgId) return 'skipped'\n const profileRef = input.firestore.collection('publisherProfiles').doc(input.publisherOrgId)\n const profile = await profileRef.get()\n const accountId = String(profile.get('stripeAccountId') ?? '')\n if (!accountId) return 'skipped'\n // A workspace lock holds this account's payouts (AGL-3364/3365): its\n // schedule is manual and the lock saved the one to restore. Moving it\n // now would either undo the pause or leave the lift restoring a delay\n // this record no longer describes, so it waits. The next sale after the\n // lift sets it right.\n const lockHold = await input.firestore\n .collection(LOCKDOWN_BILLING_PAUSES_COLLECTION)\n .doc(lockdownPayoutPauseRecordId(accountId))\n .get()\n if (lockHold.exists) return 'held-by-lock'\n const desired = publisherPayoutDelayDays(input.ageDays)\n const stored = profile.get('payoutDelayDays') as number | null | undefined\n if (stored === desired) return 'current'\n // Never delayed by this code and not young: leave the account alone.\n if (stored === undefined && desired === null) return 'current'\n const result = await stripeRequest(\n `accounts/${encodeURIComponent(accountId)}`,\n input.stripeKey,\n new URLSearchParams({\n 'settings[payouts][schedule][delay_days]': desired === null ? 'minimum' : String(desired),\n }),\n )\n if (!result.ok) {\n console.error('[marketplace] the payout schedule could not be set', {\n publisherOrgId: input.publisherOrgId,\n error: result.body?.error?.message,\n })\n return 'failed'\n }\n await profileRef.set(\n { payoutDelayDays: desired, payoutPolicyAtMs: input.nowMs ?? Date.now() },\n { merge: true },\n )\n await notifyPublisherPayoutSchedule(input.publisherOrgId, desired !== null)\n return 'applied'\n } catch (error) {\n console.error('[marketplace] the payout schedule could not be set', error)\n return 'failed'\n }\n}\n\n/** The card that paid a payment intent, as Stripe fingerprints it, or null. */\nasync function cardFingerprintOf(\n paymentIntentId: string,\n stripeKey: string,\n): Promise<string | null> {\n const result = await stripeRequest(\n `payment_intents/${encodeURIComponent(paymentIntentId)}?expand[]=latest_charge`,\n stripeKey,\n )\n const fingerprint = result.body?.latest_charge?.payment_method_details?.card?.fingerprint\n return result.ok && typeof fingerprint === 'string' && fingerprint ? fingerprint : null\n}\n\n/** Tell staff a sale was flagged (AGL-3365), once per row. Never throws. */\nexport async function notifyStaffOfSaleRisk(\n notify: (payload: {\n type: 'system.abuseReportUrgent'\n title: string\n body: string\n link: string\n }) => Promise<void>,\n flagged: { reference: string; signals: readonly SaleRiskSignal[] },\n): Promise<void> {\n await notify({\n type: 'system.abuseReportUrgent',\n title: 'Marketplace sale flagged — possible self-dealing or card fraud',\n body:\n `${describeSaleRiskSignals(flagged.signals).join(' ')} Nothing has been refunded or ` +\n `paused. Review the sale and the publisher. Reference ${flagged.reference}.`,\n link: '/admin/abuse-reports',\n }).catch(() => undefined)\n}\n\n/**\n * Tell the publisher's owners and admins a sale is under review (AGL-3365).\n * The outcome and the way forward only — never which shape flagged it, which\n * would teach the actor it describes how to avoid it. Never throws.\n */\nexport async function notifyPublisherSaleUnderReview(\n publisherOrgId: string,\n flagged: { reference: string },\n): Promise<void> {\n await notifyOrgAdmins(publisherOrgId, {\n type: 'marketplace.review',\n title: 'A marketplace sale is under review',\n body:\n 'One of your recent marketplace sales is being reviewed by our team, and its payout may ' +\n 'take longer than usual. You do not need to do anything. To ask about it, contact ' +\n `support with reference ${flagged.reference}.`,\n link: '/manage/marketplace',\n }).catch(() => undefined)\n}\n\n/**\n * Tell the publisher's owners and admins their payout timing changed\n * (AGL-3365) — when a hold starts, and when it ends. Never the rule that set\n * it. Never throws.\n */\nexport async function notifyPublisherPayoutSchedule(\n publisherOrgId: string,\n held: boolean,\n): Promise<void> {\n await notifyOrgAdmins(publisherOrgId, {\n type: 'marketplace.review',\n title: held\n ? 'Your marketplace payouts are on an extended schedule'\n : 'Your marketplace payouts are back on the standard schedule',\n body: held\n ? 'Payouts to new publishers are held for a period before they reach your bank. Your ' +\n 'sales are recorded as usual and pay out automatically when the period ends. To ask ' +\n 'about it, contact support.'\n : 'Your marketplace sales now pay out on your payout account’s standard schedule.',\n link: '/manage/marketplace',\n }).catch(() => undefined)\n}\n\n/** The sale-risk row's id: one per sale. */\nexport function saleRiskReviewId(sessionId: string): string {\n return createHash('sha256').update(`marketplace-sale-risk:${sessionId}`).digest('hex').slice(0, 40)\n}\n\n/**\n * Read one recorded sale for the fraud shapes above, hold a young\n * publisher's payouts, and file a staff row when anything is found.\n */\nexport async function screenMarketplaceSale(\n input: {\n purchaseRef: FirebaseFirestore.DocumentReference\n sessionId: string\n buyerUid: string\n buyerOrgId: string | null\n sellerOrgId: string\n amountCents: number\n paymentIntentId: string\n livemode: boolean\n },\n deps: {\n firestore?: FirebaseFirestore.Firestore\n stripeKey?: string\n notify: (payload: {\n type: 'system.abuseReportUrgent'\n title: string\n body: string\n link: string\n }) => Promise<void>\n nowMs?: number\n },\n): Promise<{ signals: SaleRiskSignal[]; filed: string | null }> {\n const nowMs = deps.nowMs ?? Date.now()\n const signals: SaleRiskSignal[] = []\n try {\n const firestore = deps.firestore ?? firebaseAdmin.app().firestore()\n const sellerOrg = (await firestore.collection('orgs').doc(input.sellerOrgId).get()).data() ?? {}\n const ageDays = orgAgeDays((sellerOrg as { createdAt?: unknown }).createdAt, nowMs)\n\n // 1. A young publisher: hold its payouts; a large sale is a signal.\n await applyPublisherPayoutPolicy({\n firestore,\n publisherOrgId: input.sellerOrgId,\n ageDays,\n stripeKey: deps.stripeKey,\n nowMs,\n })\n if (isYoungPublisher(ageDays) && input.amountCents >= YOUNG_PUBLISHER_REVIEW_SALE_CENTS) {\n signals.push({\n code: 'young-publisher-large-sale',\n ageDays: ageDays as number,\n amountCents: input.amountCents,\n })\n }\n\n // 2. A member in both workspaces — the buyer themself included.\n const sellerMembers = new Set(await memberUids(firestore, input.sellerOrgId))\n const buyerSide = new Set([\n input.buyerUid,\n ...(input.buyerOrgId && input.buyerOrgId !== input.sellerOrgId\n ? await memberUids(firestore, input.buyerOrgId)\n : []),\n ])\n const shared = [...buyerSide].filter((uid) => uid && sellerMembers.has(uid)).sort()\n if (shared.length || (input.buyerOrgId && input.buyerOrgId === input.sellerOrgId)) {\n signals.push({ code: 'shared-member', uids: shared })\n }\n\n // 3. One card, several buyer workspaces, one publisher.\n if (deps.stripeKey && input.paymentIntentId) {\n const fingerprint = await cardFingerprintOf(input.paymentIntentId, deps.stripeKey)\n if (fingerprint) {\n await input.purchaseRef.set({ cardFingerprint: fingerprint }, { merge: true })\n const matches = await firestore\n .collection('marketplacePurchases')\n .where('sellerOrgId', '==', input.sellerOrgId)\n .where('cardFingerprint', '==', fingerprint)\n .limit(MAX_CARD_MATCHES)\n .get()\n const others = [\n ...new Set(\n matches.docs\n .map((doc) => String(doc.get('buyerOrgId') ?? ''))\n .filter((orgId) => orgId && orgId !== (input.buyerOrgId ?? '')),\n ),\n ].sort()\n if (others.length) {\n signals.push({ code: 'card-reused-across-buyers', otherBuyerOrgIds: others })\n }\n }\n }\n\n if (!signals.length) return { signals, filed: null }\n\n const reviewId = saleRiskReviewId(input.sessionId)\n const reference = `MR-${reviewId.slice(0, 10).toUpperCase()}`\n const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(reviewId)\n const first = !(await ref.get()).exists\n await ref.set(\n {\n reference,\n category: 'phishing',\n severity: 'urgent',\n source: 'marketplace-sale-risk',\n url: null,\n reportedHostname: null,\n hostId: null,\n orgId: input.sellerOrgId,\n details: [\n `A marketplace sale (checkout ${input.sessionId}, payment ${input.paymentIntentId || 'unknown'}) ` +\n `paid publisher workspace ${input.sellerOrgId} $${(input.amountCents / 100).toFixed(2)} ` +\n `from buyer ${input.buyerUid}${input.buyerOrgId ? ` for workspace ${input.buyerOrgId}` : ''}` +\n (input.livemode ? '' : ' — TEST MODE') +\n '.',\n ...describeSaleRiskSignals(signals),\n 'A publisher buying its own listings with stolen cards, to cash them out as payouts, leaves this shape.',\n 'Nothing has been refunded, reversed or paused. If it is the publisher, lock its workspace and ' +\n \"refund the sale (the refund takes the publisher's share back), then close this row with what you did.\",\n ]\n .join('\\n')\n .slice(0, 5000),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n reportCount: 1,\n saleRisk: {\n sessionId: input.sessionId,\n paymentIntentId: input.paymentIntentId || null,\n sellerOrgId: input.sellerOrgId,\n buyerOrgId: input.buyerOrgId,\n buyerUid: input.buyerUid,\n amountCents: input.amountCents,\n signals,\n livemode: input.livemode,\n },\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n ...(first\n ? { status: 'open', createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp() }\n : {}),\n },\n { merge: true },\n )\n if (first) {\n await notifyStaffOfSaleRisk(deps.notify, { reference, signals })\n await notifyPublisherSaleUnderReview(input.sellerOrgId, { reference })\n }\n return { signals, filed: reference }\n } catch (error) {\n console.error('[marketplace] a sale could not be screened', error)\n return { signals, filed: null }\n }\n}\n"],"names":["createHash","ABUSE_REPORT_COLLECTION","normalizeOrgLockdown","LOCKDOWN_BILLING_PAUSES_COLLECTION","lockdownPayoutPauseRecordId","firebaseAdmin","notifyOrgAdmins","orgAgeDays","describeSaleRiskSignals","isYoungPublisher","publisherPayoutDelayDays","YOUNG_PUBLISHER_REVIEW_SALE_CENTS","MAX_MEMBERS_COMPARED","MAX_CARD_MATCHES","isOrgMember","firestore","orgId","uid","member","collection","doc","get","exists","isPublisherSecurityLocked","publisherOrgId","org","data","reason","memberUids","snapshot","limit","docs","map","id","stripeRequest","path","stripeKey","params","response","fetch","method","headers","Authorization","body","toString","json","catch","ok","applyPublisherPayoutPolicy","input","profile","profileRef","accountId","String","lockHold","desired","ageDays","stored","undefined","result","encodeURIComponent","URLSearchParams","console","error","message","set","payoutDelayDays","payoutPolicyAtMs","nowMs","Date","now","merge","notifyPublisherPayoutSchedule","cardFingerprintOf","paymentIntentId","fingerprint","latest_charge","payment_method_details","card","notifyStaffOfSaleRisk","notify","flagged","type","title","signals","join","reference","link","notifyPublisherSaleUnderReview","held","saleRiskReviewId","sessionId","update","digest","slice","screenMarketplaceSale","deps","app","sellerOrg","sellerOrgId","createdAt","amountCents","push","code","sellerMembers","Set","buyerSide","buyerUid","buyerOrgId","shared","filter","has","sort","length","uids","purchaseRef","cardFingerprint","matches","where","others","otherBuyerOrgIds","filed","reviewId","toUpperCase","ref","first","category","severity","source","url","reportedHostname","hostId","details","toFixed","livemode","reporterEmail","reporterName","dmca","reportCount","saleRisk","updatedAt","FieldValue","serverTimestamp","status"],"mappings":";AAAA;;;;;;;;;;;;;;;CAe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C5D,OAAO;YAAEqB;YAASqC,OAAO;QAAK;IAChC;AACF"}
@@ -29,6 +29,7 @@ import { recordInstallProvenance } from "./provenance.js";
29
29
  import { canActAsPublisher } from "./publisher-profile.js";
30
30
  import { requirePurchase } from "./purchase-entitlement.js";
31
31
  import { recordVersionMove } from "./version-stats.js";
32
+ import { isPublisherSecurityLocked } from "./sale-risk.js";
32
33
  const trimChanges = (changes)=>// The dialog lists changes; a 400-node tree that changed wholesale would
33
34
  // otherwise ship its entire content twice through a JSON response.
34
35
  changes.slice(0, 200);
@@ -93,7 +94,8 @@ export const updateArtifactHandler = async (req, res)=>{
93
94
  //
94
95
  // No owner exemption, matching `install-plugin.ts`: a takedown is a
95
96
  // moderation decision about the artifact, not about who is asking.
96
- listing.hiddenAt) {
97
+ listing.hiddenAt || // A publisher under a SECURITY lock hands nothing over (AGL-3365).
98
+ await isPublisherSecurityLocked(firestore, listing.profileId)) {
97
99
  return res.status(404).json({
98
100
  error: 'Unknown listing'
99
101
  });