@aglyn/plugins-marketplace 1.0.0-beta.202 → 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.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @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
+ * A LOCKED PUBLISHER, ON THE MARKETPLACE (AGL-3365).
18
+ *
19
+ * Two parts of a workspace lock reach into the marketplace, through the
20
+ * core seams in `plugin-org-lockdown.ts`:
21
+ *
22
+ * 1. THE PUBLISHER'S PAYOUT ACCOUNT. `publisherProfiles/{orgId}` holds the
23
+ * connected account marketplace sales pay out through, separate from the
24
+ * storefront account core already knows. Declared as a payout-account
25
+ * source, so a lock that pauses payouts pauses it too, and saves and
26
+ * restores its schedule on its own record.
27
+ *
28
+ * 2. THE LISTINGS. A locked workspace's listings leave browse, search and
29
+ * their pages, whatever the lock's reason. Browse is a client query over
30
+ * a field the server derives (`browseAudience`), and a client cannot read
31
+ * another workspace's lock, so a read-time check would cost a lock read
32
+ * per card. Instead the lock stamps `workspaceLockedAt` on the
33
+ * workspace's listings, `isListingBrowsable` refuses a stamped one, and
34
+ * the lift removes exactly the stamps. The flag sits BESIDE every
35
+ * visibility field rather than overwriting one, so a listing the
36
+ * publisher had unpublished, made private, or that staff took down is
37
+ * still exactly that after the lift. Nothing is published by a lift.
38
+ *=========================================*/ import { registerOrgLockdownParticipant, registerPayoutAccountSource } from "@aglyn/aglyn/plugin-manager/plugin-org-lockdown";
39
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
40
+ import { BUNDLE_ID } from "../constants/bundle-common.js";
41
+ import { refreshListingQueryFields } from "./listing-query-fields.js";
42
+ /** How many of one workspace's listings a lock stamps. */ const MAX_LISTINGS = 1000;
43
+ /** The publisher's own connected account, if it has one. */ export async function publisherPayoutAccounts(firestore, orgId) {
44
+ var _get;
45
+ if (!orgId) return [];
46
+ const accountId = String((_get = (await firestore.collection('publisherProfiles').doc(orgId).get()).get('stripeAccountId')) != null ? _get : '');
47
+ return accountId ? [
48
+ {
49
+ accountId,
50
+ label: 'marketplace publisher'
51
+ }
52
+ ] : [];
53
+ }
54
+ /**
55
+ * Stamp (lock) or clear (lift) `workspaceLockedAt` on the workspace's
56
+ * listings, and re-derive what browse queries by. Only the stamp moves: a
57
+ * lift clears it from the listings that carry it and touches nothing else.
58
+ */ export async function setPublisherListingsLocked(firestore, orgId, locked) {
59
+ const snapshot = await firestore.collection('marketplaceListings').where('profileId', '==', orgId).limit(MAX_LISTINGS + 1).get();
60
+ const docs = snapshot.docs.slice(0, MAX_LISTINGS);
61
+ let changed = 0;
62
+ for (const doc of docs){
63
+ const stamped = Boolean(doc.get('workspaceLockedAt'));
64
+ if (stamped === locked) continue;
65
+ await doc.ref.set({
66
+ workspaceLockedAt: locked ? firebaseAdmin.firestore.FieldValue.serverTimestamp() : firebaseAdmin.firestore.FieldValue.delete()
67
+ }, {
68
+ merge: true
69
+ });
70
+ await refreshListingQueryFields(doc.ref);
71
+ changed += 1;
72
+ }
73
+ return {
74
+ changed,
75
+ total: docs.length,
76
+ truncated: snapshot.docs.length > MAX_LISTINGS
77
+ };
78
+ }
79
+ /** Declares the marketplace's part in a workspace lock. */ export function registerMarketplaceLockdown() {
80
+ registerPayoutAccountSource({
81
+ listPayoutAccounts: ({ orgId })=>publisherPayoutAccounts(firebaseAdmin.app().firestore(), orgId)
82
+ }, {
83
+ pluginId: BUNDLE_ID
84
+ });
85
+ registerOrgLockdownParticipant({
86
+ onOrgLockChange: async ({ orgId, locked })=>{
87
+ const result = await setPublisherListingsLocked(firebaseAdmin.app().firestore(), orgId, locked);
88
+ return {
89
+ summary: `${locked ? 'Hid' : 'Restored'} ${result.changed} marketplace listing(s) ` + `of ${result.total}` + (result.truncated ? '; more exist and were not reached' : ''),
90
+ confirmed: !result.truncated
91
+ };
92
+ }
93
+ }, {
94
+ pluginId: BUNDLE_ID
95
+ });
96
+ }
97
+
98
+ //# sourceMappingURL=publisher-lockdown.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publisher-lockdown.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 LOCKED PUBLISHER, ON THE MARKETPLACE (AGL-3365).\n *\n * Two parts of a workspace lock reach into the marketplace, through the\n * core seams in `plugin-org-lockdown.ts`:\n *\n * 1. THE PUBLISHER'S PAYOUT ACCOUNT. `publisherProfiles/{orgId}` holds the\n * connected account marketplace sales pay out through, separate from the\n * storefront account core already knows. Declared as a payout-account\n * source, so a lock that pauses payouts pauses it too, and saves and\n * restores its schedule on its own record.\n *\n * 2. THE LISTINGS. A locked workspace's listings leave browse, search and\n * their pages, whatever the lock's reason. Browse is a client query over\n * a field the server derives (`browseAudience`), and a client cannot read\n * another workspace's lock, so a read-time check would cost a lock read\n * per card. Instead the lock stamps `workspaceLockedAt` on the\n * workspace's listings, `isListingBrowsable` refuses a stamped one, and\n * the lift removes exactly the stamps. The flag sits BESIDE every\n * visibility field rather than overwriting one, so a listing the\n * publisher had unpublished, made private, or that staff took down is\n * still exactly that after the lift. Nothing is published by a lift.\n *=========================================*/\n\nimport {\n registerOrgLockdownParticipant,\n registerPayoutAccountSource,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-lockdown'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/** How many of one workspace's listings a lock stamps. */\nconst MAX_LISTINGS = 1000\n\n/** The publisher's own connected account, if it has one. */\nexport async function publisherPayoutAccounts(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<Array<{ accountId: string; label: string }>> {\n if (!orgId) return []\n const accountId = String(\n (await firestore.collection('publisherProfiles').doc(orgId).get()).get('stripeAccountId') ?? '',\n )\n return accountId ? [{ accountId, label: 'marketplace publisher' }] : []\n}\n\n/**\n * Stamp (lock) or clear (lift) `workspaceLockedAt` on the workspace's\n * listings, and re-derive what browse queries by. Only the stamp moves: a\n * lift clears it from the listings that carry it and touches nothing else.\n */\nexport async function setPublisherListingsLocked(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n locked: boolean,\n): Promise<{ changed: number; total: number; truncated: boolean }> {\n const snapshot = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', orgId)\n .limit(MAX_LISTINGS + 1)\n .get()\n const docs = snapshot.docs.slice(0, MAX_LISTINGS)\n let changed = 0\n for (const doc of docs) {\n const stamped = Boolean(doc.get('workspaceLockedAt'))\n if (stamped === locked) continue\n await doc.ref.set(\n {\n workspaceLockedAt: locked\n ? firebaseAdmin.firestore.FieldValue.serverTimestamp()\n : firebaseAdmin.firestore.FieldValue.delete(),\n },\n { merge: true },\n )\n await refreshListingQueryFields(doc.ref)\n changed += 1\n }\n return { changed, total: docs.length, truncated: snapshot.docs.length > MAX_LISTINGS }\n}\n\n/** Declares the marketplace's part in a workspace lock. */\nexport function registerMarketplaceLockdown(): void {\n registerPayoutAccountSource(\n {\n listPayoutAccounts: ({ orgId }) =>\n publisherPayoutAccounts(firebaseAdmin.app().firestore(), orgId),\n },\n { pluginId: BUNDLE_ID },\n )\n registerOrgLockdownParticipant(\n {\n onOrgLockChange: async ({ orgId, locked }) => {\n const result = await setPublisherListingsLocked(\n firebaseAdmin.app().firestore(),\n orgId,\n locked,\n )\n return {\n summary:\n `${locked ? 'Hid' : 'Restored'} ${result.changed} marketplace listing(s) ` +\n `of ${result.total}` +\n (result.truncated ? '; more exist and were not reached' : ''),\n confirmed: !result.truncated,\n }\n },\n },\n { pluginId: BUNDLE_ID },\n )\n}\n"],"names":["registerOrgLockdownParticipant","registerPayoutAccountSource","firebaseAdmin","BUNDLE_ID","refreshListingQueryFields","MAX_LISTINGS","publisherPayoutAccounts","firestore","orgId","accountId","String","collection","doc","get","label","setPublisherListingsLocked","locked","snapshot","where","limit","docs","slice","changed","stamped","Boolean","ref","set","workspaceLockedAt","FieldValue","serverTimestamp","delete","merge","total","length","truncated","registerMarketplaceLockdown","listPayoutAccounts","app","pluginId","onOrgLockChange","result","summary","confirmed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,SACEA,8BAA8B,EAC9BC,2BAA2B,QACtB,kDAAiD;AACxD,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE,wDAAwD,GACxD,MAAMC,eAAe;AAErB,0DAA0D,GAC1D,OAAO,eAAeC,wBACpBC,SAAsC,EACtCC,KAAa;QAIX;IAFF,IAAI,CAACA,OAAO,OAAO,EAAE;IACrB,MAAMC,YAAYC,QAChB,OAAA,AAAC,CAAA,MAAMH,UAAUI,UAAU,CAAC,qBAAqBC,GAAG,CAACJ,OAAOK,GAAG,EAAC,EAAGA,GAAG,CAAC,8BAAvE,OAA6F;IAE/F,OAAOJ,YAAY;QAAC;YAAEA;YAAWK,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,KAAK,EAAE,GACnBQ,CAAAA,OAAON,SAAS,GAAG,sCAAsC,EAAC;gBAC7DQ,WAAW,CAACF,OAAON,SAAS;YAC9B;QACF;IACF,GACA;QAAEI,UAAUnC;IAAU;AAE1B"}
@@ -49,7 +49,7 @@ export declare function applyPublisherPayoutPolicy(input: {
49
49
  ageDays: number | null;
50
50
  stripeKey: string | undefined;
51
51
  nowMs?: number;
52
- }): Promise<'applied' | 'current' | 'skipped' | 'failed'>;
52
+ }): Promise<'applied' | 'current' | 'held-by-lock' | 'skipped' | 'failed'>;
53
53
  /** Tell staff a sale was flagged (AGL-3365), once per row. Never throws. */
54
54
  export declare function notifyStaffOfSaleRisk(notify: (payload: {
55
55
  type: 'system.abuseReportUrgent';
@@ -38,6 +38,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
38
38
  *=========================================*/ import { createHash } from "crypto";
39
39
  import { ABUSE_REPORT_COLLECTION } from "@aglyn/aglyn/app-utils/abuse-report";
40
40
  import { normalizeOrgLockdown } from "@aglyn/aglyn/app-utils/lockdown";
41
+ import { LOCKDOWN_BILLING_PAUSES_COLLECTION, lockdownPayoutPauseRecordId } from "@aglyn/aglyn/plugin-manager/plugin-org-lockdown";
41
42
  import { firebaseAdmin, notifyOrgAdmins } from "@aglyn/tenant-data-admin";
42
43
  import { orgAgeDays } from "@aglyn/tenant-data-admin/server/org-age";
43
44
  import { describeSaleRiskSignals, isYoungPublisher, publisherPayoutDelayDays, YOUNG_PUBLISHER_REVIEW_SALE_CENTS } from "../model/publisher-risk.js";
@@ -107,6 +108,13 @@ async function stripeRequest(path, stripeKey, params) {
107
108
  const profile = await profileRef.get();
108
109
  const accountId = String((_profile_get = profile.get('stripeAccountId')) != null ? _profile_get : '');
109
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';
110
118
  const desired = publisherPayoutDelayDays(input.ageDays);
111
119
  const stored = profile.get('payoutDelayDays');
112
120
  if (stored === desired) return 'current';
@@ -1 +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 { 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' | '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 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","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","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;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,oBAAoB,QAAQ,kCAAiC;AACtE,SAASC,aAAa,EAAEC,eAAe,QAAQ,2BAA0B;AACzE,SAASC,UAAU,QAAQ,0CAAyC;AACpE,SACEC,uBAAuB,EACvBC,gBAAgB,EAChBC,wBAAwB,EAExBC,iCAAiC,QAC5B,6BAAyB;AAEhC,8DAA8D,GAC9D,MAAMC,uBAAuB;AAC7B,2DAA2D,GAC3D,MAAMC,mBAAmB;AAEzB;;;;CAIC,GACD,OAAO,eAAeC,YACpBC,SAAsC,EACtCC,KAAa,EACbC,GAAW;IAEX,IAAI,CAACD,SAAS,CAACC,KAAK,OAAO;IAC3B,MAAMC,SAAS,MAAMH,UAClBI,UAAU,CAAC,QACXC,GAAG,CAACJ,OACJG,UAAU,CAAC,WACXC,GAAG,CAACH,KACJI,GAAG;IACN,OAAOH,OAAOI,MAAM;AACtB;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeC,0BACpBR,SAAsC,EACtCS,cA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O;YACT,MAAM9C,sBAAsBiB,KAAKhB,MAAM,EAAE;gBAAEM;gBAAWF;YAAQ;YAC9D,MAAMI,+BAA+BtC,MAAMiD,WAAW,EAAE;gBAAEb;YAAU;QACtE;QACA,OAAO;YAAEF;YAASqC,OAAOnC;QAAU;IACrC,EAAE,OAAOvB,OAAO;QACdD,QAAQC,KAAK,CAAC,8CAA8CA;QAC5D,OAAO;YAAEqB;YAASqC,OAAO;QAAK;IAChC;AACF"}
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;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,oBAAoB,QAAQ,kCAAiC;AACtE,SACEC,kCAAkC,EAClCC,2BAA2B,QACtB,kDAAiD;AACxD,SAASC,aAAa,EAAEC,eAAe,QAA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AAM0D,QAAQ,GAAG1D,MAAM2D,UAAU,GAAG,CAAC,eAAe,EAAE3D,MAAM2D,UAAU,EAAE,GAAG,IAAI,GAC5F3D,CAAAA,MAAMqF,QAAQ,GAAG,KAAK,cAAa,IACpC;mBACC9H,wBAAwB4E;gBAC3B;gBACA,mGACE;aACH,CACEC,IAAI,CAAC,MACLS,KAAK,CAAC,GAAG;YACZyC,eAAe;YACfC,cAAc;YACdC,MAAM;YACNC,aAAa;YACbC,UAAU;gBACRhD,WAAW1C,MAAM0C,SAAS;gBAC1BjB,iBAAiBzB,MAAMyB,eAAe,IAAI;gBAC1CyB,aAAalD,MAAMkD,WAAW;gBAC9BS,YAAY3D,MAAM2D,UAAU;gBAC5BD,UAAU1D,MAAM0D,QAAQ;gBACxBN,aAAapD,MAAMoD,WAAW;gBAC9BjB;gBACAkD,UAAUrF,MAAMqF,QAAQ;YAC1B;YACAM,WAAWvI,cAAcU,SAAS,CAAC8H,UAAU,CAACC,eAAe;WACzDjB,QACA;YAAEkB,QAAQ;YAAQ3C,WAAW/F,cAAcU,SAAS,CAAC8H,UAAU,CAACC,eAAe;QAAG,IAClF,CAAC,IAEP;YAAEvE,OAAO;QAAK;QAEhB,IAAIsD,OAAO;YACT,MAAM9C,sBAAsBiB,KAAKhB,MAAM,EAAE;gBAAEM;gBAAWF;YAAQ;YAC9D,MAAMI,+BAA+BvC,MAAMkD,WAAW,EAAE;gBAAEb;YAAU;QACtE;QACA,OAAO;YAAEF;YAASqC,OAAOnC;QAAU;IACrC,EAAE,OAAOvB,OAAO;QACdD,QAAQC,KAAK,CAAC,8CAA8CA;QAC5D,OAAO;YAAEqB;YAASqC,OAAO;QAAK;IAChC;AACF"}
package/src/lib/server.js CHANGED
@@ -20,6 +20,7 @@ import { registerPluginRouteMetadata } from "@aglyn/aglyn/plugin-manager/plugin-
20
20
  import { registerPluginArtifactInventory } from "@aglyn/aglyn/plugin-manager/plugin-artifact-inventory";
21
21
  import { BUNDLE_ID } from "./constants/bundle-common.js";
22
22
  import { marketplaceBillingWebhookHandler } from "./server/billing-webhook.js";
23
+ import { registerMarketplaceLockdown } from "./server/publisher-lockdown.js";
23
24
  import { publishPluginHandler } from "./server/publish-plugin.js";
24
25
  import { verificationRequestHandler } from "./server/verification-request.js";
25
26
  import { checkoutHandler } from "./server/checkout.js";
@@ -157,6 +158,9 @@ import { updateArtifactHandler } from "./server/update-artifact.js";
157
158
  registerPluginApiRoute('marketplace/publish-plugin', publishPluginHandler);
158
159
  // Marketplace purchases ride the platform Stripe webhook (AGL-418).
159
160
  registerBillingWebhookHandler(marketplaceBillingWebhookHandler);
161
+ // A workspace lock reaches the publisher's payout account and its
162
+ // listings (AGL-3365).
163
+ registerMarketplaceLockdown();
160
164
  }
161
165
 
162
166
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/marketplace/src/lib/server.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 registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerCustomFieldType,\n} from '@aglyn/aglyn/server'\n// Its own subpath, never the plugin-manager barrel: what a published page\n// does not need, it must not import.\nimport { registerPluginRouteMetadata } from '@aglyn/aglyn/plugin-manager/plugin-route-metadata'\nimport { registerPluginArtifactInventory } from '@aglyn/aglyn/plugin-manager/plugin-artifact-inventory'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { marketplaceBillingWebhookHandler } from './server/billing-webhook'\nimport { publishPluginHandler } from './server/publish-plugin'\nimport { verificationRequestHandler } from './server/verification-request'\nimport { checkoutHandler } from './server/checkout'\nimport { connectHandler } from './server/connect'\nimport { installHandler } from './server/install'\nimport { installPluginHandler } from './server/install-plugin'\nimport { listingVersionsHandler } from './server/listing-versions'\nimport { RATING_FIELD } from './model/rating-field'\nimport { installDatasetSchemaHandler } from './server/install-dataset-schema'\nimport { installEmailStarterHandler } from './server/install-email-starter'\nimport { installEmailTemplateHandler } from './server/install-email-template'\nimport { installLayoutHandler } from './server/install-layout'\nimport { installTemplateHandler } from './server/install-template'\nimport { installThemeHandler } from './server/install-theme'\nimport { previewImageHandler } from './server/preview-image'\nimport { publishHandler } from './server/publish'\nimport { marketplaceArtifactInventory } from './server/artifact-inventory'\nimport { marketplaceAdminReports } from './server/admin-reports'\nimport { marketplaceAdminReviews } from './server/admin-reviews'\nimport { marketplaceAdminTrust } from './server/admin-trust'\nimport { reportHandler } from './server/report'\nimport { reviewsHandler } from './server/reviews'\nimport { publisherProfileSaveHandler } from './server/publisher-profile-save'\nimport { publishDatasetSchemaHandler } from './server/publish-dataset-schema'\nimport { publishEmailStarterHandler } from './server/publish-email-starter'\nimport { publishEmailTemplateHandler } from './server/publish-email-template'\nimport { publishLayoutHandler } from './server/publish-layout'\nimport { publishTemplateHandler } from './server/publish-template'\nimport { publishThemeHandler } from './server/publish-theme'\nimport { updateArtifactHandler } from './server/update-artifact'\n\n/**\n * Registers the marketplace plugin's console-side API routes (AGL-396):\n * marketplace publish/install of templates and plugins, and the Stripe\n * Connect + checkout flows for paid listings.\n *\n * Upload-bodied routes register here too. The note that used to sit here —\n * that they had to stay as named console routes because the dispatcher\n * \"can't grant per-route bodyParser limits\" — was a Pages Router leftover:\n * `runLegacyHandler` reads the request through the same\n * `pluginRequestFromWeb` a named App Router route would, and imposes no\n * limit of its own. publish-plugin's 8 MB bundle has been going through the\n * dispatcher the whole time.\n */\nexport function registerMarketplaceConsoleApi(): void {\n // Server side of the rating custom field (AGL-434): validators run\n // on import/write paths even when no client loaded the plugin.\n registerCustomFieldType(RATING_FIELD)\n /*\n * What a listing link unfurls as (AGL-876, handed to the platform by\n * AGL-3080).\n *\n * The card used to be built by a hand-written console route with a server\n * layout of its own, which is what kept that route out of the generic\n * plugin route — moving it would have dropped every listing's card with\n * nothing red. The shell asks this instead, so the card survives the move\n * and no console file reads `marketplaceListings` to build a head.\n *\n * One segment and one only: `/{org}/marketplace/{listingId}`. The hub, the\n * publish page and every other address under this route answer `null`,\n * which leaves the shell's own title exactly as it was.\n */\n registerPluginRouteMetadata(\n {\n route: 'marketplace',\n resolve: async (segments) => {\n if (segments.length !== 1) return null\n const { readListingForSocialCard } = await import(\n './server/listing-social-card.server'\n )\n const { listingSocialCard } = await import('./model/listing-social-card')\n return listingSocialCard(await readListingForSocialCard(segments[0]))\n },\n },\n // Named, because this registrar is called directly by the app's server\n // loader rather than from inside a plugin `register` fn, where the\n // loader's owner marker would be set.\n { pluginId: BUNDLE_ID },\n )\n /*\n * Who claims the bytes in the artifacts bucket (AGL-3080).\n *\n * The platform's two scheduled sweeps run from `/api/admin` routes that\n * used to walk `pluginVersions` and `marketplaceListings` themselves. They\n * ask here now — and an unregistered inventory REFUSES both runs rather\n * than reporting an empty bucket, which is the whole point of the\n * contract's shape.\n */\n registerPluginArtifactInventory(marketplaceArtifactInventory, {\n pluginId: BUNDLE_ID,\n })\n registerPluginApiRoute('marketplace/checkout', checkoutHandler)\n registerPluginApiRoute('marketplace/connect', connectHandler)\n registerPluginApiRoute('marketplace/install', installHandler)\n registerPluginApiRoute('marketplace/install-plugin', installPluginHandler)\n registerPluginApiRoute('marketplace/install-layout', installLayoutHandler)\n registerPluginApiRoute('marketplace/install-template', installTemplateHandler)\n // A theme install DOES change the running site (AGL-1020) — it is the site's\n // appearance — so this route also owns the ways back: `revert` and `reset`.\n registerPluginApiRoute('marketplace/install-theme', installThemeHandler)\n registerPluginApiRoute(\n 'marketplace/install-dataset-schema',\n installDatasetSchemaHandler,\n )\n registerPluginApiRoute(\n 'marketplace/install-email-starter',\n installEmailStarterHandler,\n )\n registerPluginApiRoute(\n 'marketplace/install-email-template',\n installEmailTemplateHandler,\n )\n // Updating a copied artifact is its own route (AGL-1018), not a flag on\n // install: install writes the publisher's version, this one reconciles it\n // with a copy that has diverged and refuses to overwrite silently.\n registerPluginApiRoute('marketplace/update-artifact', updateArtifactHandler)\n registerPluginApiRoute('marketplace/listing-versions', listingVersionsHandler)\n registerPluginApiRoute('marketplace/preview-image', previewImageHandler)\n registerPluginApiRoute('marketplace/publish', publishHandler)\n registerPluginApiRoute('marketplace/report', reportHandler)\n /*\n * The staff end of that button (AGL-2310), moved out of\n * `apps/console/app/api/admin/` by AGL-3080. `web:` because it is a plain\n * fetch from this plugin's own staff page, not a plugin-request handler —\n * the same shape the AI plugin's `ai/admin/*` routes use, and for the same\n * reason: a staff route names no host, so there is no subject to resolve.\n */\n registerPluginApiRoute('marketplace/admin/reports', {\n web: marketplaceAdminReports,\n })\n // The review queue (AGL-432, moved by AGL-3080). Same shape and the same\n // reason: a staff route names no host, so there is no subject to resolve.\n registerPluginApiRoute('marketplace/admin/reviews', {\n web: marketplaceAdminReviews,\n })\n // Realm trust (AGL-420, moved by AGL-3080). Super-staff only, and the\n // SIGNATURE comes from the shell — the key is the console's and stays\n // there. See `server/admin-trust.ts`.\n registerPluginApiRoute('marketplace/admin/trust', {\n web: marketplaceAdminTrust,\n })\n registerPluginApiRoute('marketplace/reviews', reviewsHandler)\n registerPluginApiRoute(\n 'marketplace/publisher-profile',\n publisherProfileSaveHandler,\n )\n registerPluginApiRoute(\n 'marketplace/verification-request',\n verificationRequestHandler,\n )\n registerPluginApiRoute('marketplace/publish-layout', publishLayoutHandler)\n registerPluginApiRoute('marketplace/publish-template', publishTemplateHandler)\n registerPluginApiRoute('marketplace/publish-theme', publishThemeHandler)\n registerPluginApiRoute(\n 'marketplace/publish-dataset-schema',\n publishDatasetSchemaHandler,\n )\n registerPluginApiRoute(\n 'marketplace/publish-email-starter',\n publishEmailStarterHandler,\n )\n registerPluginApiRoute(\n 'marketplace/publish-email-template',\n publishEmailTemplateHandler,\n )\n // Relocated console routes (AGL-418): URLs preserved via the dispatcher.\n registerPluginApiRoute('marketplace/publish-plugin', publishPluginHandler)\n // Marketplace purchases ride the platform Stripe webhook (AGL-418).\n registerBillingWebhookHandler(marketplaceBillingWebhookHandler)\n}\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerCustomFieldType","registerPluginRouteMetadata","registerPluginArtifactInventory","BUNDLE_ID","marketplaceBillingWebhookHandler","publishPluginHandler","verificationRequestHandler","checkoutHandler","connectHandler","installHandler","installPluginHandler","listingVersionsHandler","RATING_FIELD","installDatasetSchemaHandler","installEmailStarterHandler","installEmailTemplateHandler","installLayoutHandler","installTemplateHandler","installThemeHandler","previewImageHandler","publishHandler","marketplaceArtifactInventory","marketplaceAdminReports","marketplaceAdminReviews","marketplaceAdminTrust","reportHandler","reviewsHandler","publisherProfileSaveHandler","publishDatasetSchemaHandler","publishEmailStarterHandler","publishEmailTemplateHandler","publishLayoutHandler","publishTemplateHandler","publishThemeHandler","updateArtifactHandler","registerMarketplaceConsoleApi","route","resolve","segments","length","readListingForSocialCard","listingSocialCard","pluginId","web"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,uBAAuB,QAClB,sBAAqB;AAC5B,0EAA0E;AAC1E,qCAAqC;AACrC,SAASC,2BAA2B,QAAQ,oDAAmD;AAC/F,SAASC,+BAA+B,QAAQ,wDAAuD;AACvG,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,gCAAgC,QAAQ,8BAA0B;AAC3E,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,0BAA0B,QAAQ,mCAA+B;AAC1E,SAASC,eAAe,QAAQ,uBAAmB;AACnD,SAASC,cAAc,QAAQ,sBAAkB;AACjD,SAASC,cAAc,QAAQ,sBAAkB;AACjD,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,sBAAsB,Q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QACrE;IACF,GACA,uEAAuE;IACvE,mEAAmE;IACnE,sCAAsC;IACtC;QAAEI,UAAUvC;IAAU;IAExB;;;;;;;;GAQC,GACDD,gCAAgCmB,8BAA8B;QAC5DqB,UAAUvC;IACZ;IACAJ,uBAAuB,wBAAwBQ;IAC/CR,uBAAuB,uBAAuBS;IAC9CT,uBAAuB,uBAAuBU;IAC9CV,uBAAuB,8BAA8BW;IACrDX,uBAAuB,8BAA8BiB;IACrDjB,uBAAuB,gCAAgCkB;IACvD,6EAA6E;IAC7E,4EAA4E;IAC5ElB,uBAAuB,6BAA6BmB;IACpDnB,uBACE,sCACAc;IAEFd,uBACE,qCACAe;IAEFf,uBACE,sCACAgB;IAEF,wEAAwE;IACxE,0EAA0E;IAC1E,mEAAmE;IACnEhB,uBAAuB,+BAA+BmC;IACtDnC,uBAAuB,gCAAgCY;IACvDZ,uBAAuB,6BAA6BoB;IACpDpB,uBAAuB,uBAAuBqB;IAC9CrB,uBAAuB,sBAAsB0B;IAC7C;;;;;;GAMC,GACD1B,uBAAuB,6BAA6B;QAClD4C,KAAKrB;IACP;IACA,yEAAyE;IACzE,0EAA0E;IAC1EvB,uBAAuB,6BAA6B;QAClD4C,KAAKpB;IACP;IACA,sEAAsE;IACtE,sEAAsE;IACtE,sCAAsC;IACtCxB,uBAAuB,2BAA2B;QAChD4C,KAAKnB;IACP;IACAzB,uBAAuB,uBAAuB2B;IAC9C3B,uBACE,iCACA4B;IAEF5B,uBACE,oCACAO;IAEFP,uBAAuB,8BAA8BgC;IACrDhC,uBAAuB,gCAAgCiC;IACvDjC,uBAAuB,6BAA6BkC;IACpDlC,uBACE,sCACA6B;IAEF7B,uBACE,qCACA8B;IAEF9B,uBACE,sCACA+B;IAEF,yEAAyE;IACzE/B,uBAAuB,8BAA8BM;IACrD,oEAAoE;IACpEP,8BAA8BM;AAChC"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/marketplace/src/lib/server.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 registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerCustomFieldType,\n} from '@aglyn/aglyn/server'\n// Its own subpath, never the plugin-manager barrel: what a published page\n// does not need, it must not import.\nimport { registerPluginRouteMetadata } from '@aglyn/aglyn/plugin-manager/plugin-route-metadata'\nimport { registerPluginArtifactInventory } from '@aglyn/aglyn/plugin-manager/plugin-artifact-inventory'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { marketplaceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerMarketplaceLockdown } from './server/publisher-lockdown'\nimport { publishPluginHandler } from './server/publish-plugin'\nimport { verificationRequestHandler } from './server/verification-request'\nimport { checkoutHandler } from './server/checkout'\nimport { connectHandler } from './server/connect'\nimport { installHandler } from './server/install'\nimport { installPluginHandler } from './server/install-plugin'\nimport { listingVersionsHandler } from './server/listing-versions'\nimport { RATING_FIELD } from './model/rating-field'\nimport { installDatasetSchemaHandler } from './server/install-dataset-schema'\nimport { installEmailStarterHandler } from './server/install-email-starter'\nimport { installEmailTemplateHandler } from './server/install-email-template'\nimport { installLayoutHandler } from './server/install-layout'\nimport { installTemplateHandler } from './server/install-template'\nimport { installThemeHandler } from './server/install-theme'\nimport { previewImageHandler } from './server/preview-image'\nimport { publishHandler } from './server/publish'\nimport { marketplaceArtifactInventory } from './server/artifact-inventory'\nimport { marketplaceAdminReports } from './server/admin-reports'\nimport { marketplaceAdminReviews } from './server/admin-reviews'\nimport { marketplaceAdminTrust } from './server/admin-trust'\nimport { reportHandler } from './server/report'\nimport { reviewsHandler } from './server/reviews'\nimport { publisherProfileSaveHandler } from './server/publisher-profile-save'\nimport { publishDatasetSchemaHandler } from './server/publish-dataset-schema'\nimport { publishEmailStarterHandler } from './server/publish-email-starter'\nimport { publishEmailTemplateHandler } from './server/publish-email-template'\nimport { publishLayoutHandler } from './server/publish-layout'\nimport { publishTemplateHandler } from './server/publish-template'\nimport { publishThemeHandler } from './server/publish-theme'\nimport { updateArtifactHandler } from './server/update-artifact'\n\n/**\n * Registers the marketplace plugin's console-side API routes (AGL-396):\n * marketplace publish/install of templates and plugins, and the Stripe\n * Connect + checkout flows for paid listings.\n *\n * Upload-bodied routes register here too. The note that used to sit here —\n * that they had to stay as named console routes because the dispatcher\n * \"can't grant per-route bodyParser limits\" — was a Pages Router leftover:\n * `runLegacyHandler` reads the request through the same\n * `pluginRequestFromWeb` a named App Router route would, and imposes no\n * limit of its own. publish-plugin's 8 MB bundle has been going through the\n * dispatcher the whole time.\n */\nexport function registerMarketplaceConsoleApi(): void {\n // Server side of the rating custom field (AGL-434): validators run\n // on import/write paths even when no client loaded the plugin.\n registerCustomFieldType(RATING_FIELD)\n /*\n * What a listing link unfurls as (AGL-876, handed to the platform by\n * AGL-3080).\n *\n * The card used to be built by a hand-written console route with a server\n * layout of its own, which is what kept that route out of the generic\n * plugin route — moving it would have dropped every listing's card with\n * nothing red. The shell asks this instead, so the card survives the move\n * and no console file reads `marketplaceListings` to build a head.\n *\n * One segment and one only: `/{org}/marketplace/{listingId}`. The hub, the\n * publish page and every other address under this route answer `null`,\n * which leaves the shell's own title exactly as it was.\n */\n registerPluginRouteMetadata(\n {\n route: 'marketplace',\n resolve: async (segments) => {\n if (segments.length !== 1) return null\n const { readListingForSocialCard } = await import(\n './server/listing-social-card.server'\n )\n const { listingSocialCard } = await import('./model/listing-social-card')\n return listingSocialCard(await readListingForSocialCard(segments[0]))\n },\n },\n // Named, because this registrar is called directly by the app's server\n // loader rather than from inside a plugin `register` fn, where the\n // loader's owner marker would be set.\n { pluginId: BUNDLE_ID },\n )\n /*\n * Who claims the bytes in the artifacts bucket (AGL-3080).\n *\n * The platform's two scheduled sweeps run from `/api/admin` routes that\n * used to walk `pluginVersions` and `marketplaceListings` themselves. They\n * ask here now — and an unregistered inventory REFUSES both runs rather\n * than reporting an empty bucket, which is the whole point of the\n * contract's shape.\n */\n registerPluginArtifactInventory(marketplaceArtifactInventory, {\n pluginId: BUNDLE_ID,\n })\n registerPluginApiRoute('marketplace/checkout', checkoutHandler)\n registerPluginApiRoute('marketplace/connect', connectHandler)\n registerPluginApiRoute('marketplace/install', installHandler)\n registerPluginApiRoute('marketplace/install-plugin', installPluginHandler)\n registerPluginApiRoute('marketplace/install-layout', installLayoutHandler)\n registerPluginApiRoute('marketplace/install-template', installTemplateHandler)\n // A theme install DOES change the running site (AGL-1020) — it is the site's\n // appearance — so this route also owns the ways back: `revert` and `reset`.\n registerPluginApiRoute('marketplace/install-theme', installThemeHandler)\n registerPluginApiRoute(\n 'marketplace/install-dataset-schema',\n installDatasetSchemaHandler,\n )\n registerPluginApiRoute(\n 'marketplace/install-email-starter',\n installEmailStarterHandler,\n )\n registerPluginApiRoute(\n 'marketplace/install-email-template',\n installEmailTemplateHandler,\n )\n // Updating a copied artifact is its own route (AGL-1018), not a flag on\n // install: install writes the publisher's version, this one reconciles it\n // with a copy that has diverged and refuses to overwrite silently.\n registerPluginApiRoute('marketplace/update-artifact', updateArtifactHandler)\n registerPluginApiRoute('marketplace/listing-versions', listingVersionsHandler)\n registerPluginApiRoute('marketplace/preview-image', previewImageHandler)\n registerPluginApiRoute('marketplace/publish', publishHandler)\n registerPluginApiRoute('marketplace/report', reportHandler)\n /*\n * The staff end of that button (AGL-2310), moved out of\n * `apps/console/app/api/admin/` by AGL-3080. `web:` because it is a plain\n * fetch from this plugin's own staff page, not a plugin-request handler —\n * the same shape the AI plugin's `ai/admin/*` routes use, and for the same\n * reason: a staff route names no host, so there is no subject to resolve.\n */\n registerPluginApiRoute('marketplace/admin/reports', {\n web: marketplaceAdminReports,\n })\n // The review queue (AGL-432, moved by AGL-3080). Same shape and the same\n // reason: a staff route names no host, so there is no subject to resolve.\n registerPluginApiRoute('marketplace/admin/reviews', {\n web: marketplaceAdminReviews,\n })\n // Realm trust (AGL-420, moved by AGL-3080). Super-staff only, and the\n // SIGNATURE comes from the shell — the key is the console's and stays\n // there. See `server/admin-trust.ts`.\n registerPluginApiRoute('marketplace/admin/trust', {\n web: marketplaceAdminTrust,\n })\n registerPluginApiRoute('marketplace/reviews', reviewsHandler)\n registerPluginApiRoute(\n 'marketplace/publisher-profile',\n publisherProfileSaveHandler,\n )\n registerPluginApiRoute(\n 'marketplace/verification-request',\n verificationRequestHandler,\n )\n registerPluginApiRoute('marketplace/publish-layout', publishLayoutHandler)\n registerPluginApiRoute('marketplace/publish-template', publishTemplateHandler)\n registerPluginApiRoute('marketplace/publish-theme', publishThemeHandler)\n registerPluginApiRoute(\n 'marketplace/publish-dataset-schema',\n publishDatasetSchemaHandler,\n )\n registerPluginApiRoute(\n 'marketplace/publish-email-starter',\n publishEmailStarterHandler,\n )\n registerPluginApiRoute(\n 'marketplace/publish-email-template',\n publishEmailTemplateHandler,\n )\n // Relocated console routes (AGL-418): URLs preserved via the dispatcher.\n registerPluginApiRoute('marketplace/publish-plugin', publishPluginHandler)\n // Marketplace purchases ride the platform Stripe webhook (AGL-418).\n registerBillingWebhookHandler(marketplaceBillingWebhookHandler)\n // A workspace lock reaches the publisher's payout account and its\n // listings (AGL-3365).\n registerMarketplaceLockdown()\n}\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerCustomFieldType","registerPluginRouteMetadata","registerPluginArtifactInventory","BUNDLE_ID","marketplaceBillingWebhookHandler","registerMarketplaceLockdown","publishPluginHandler","verificationRequestHandler","checkoutHandler","connectHandler","installHandler","installPluginHandler","listingVersionsHandler","RATING_FIELD","installDatasetSchemaHandler","installEmailStarterHandler","installEmailTemplateHandler","installLayoutHandler","installTemplateHandler","installThemeHandler","previewImageHandler","publishHandler","marketplaceArtifactInventory","marketplaceAdminReports","marketplaceAdminReviews","marketplaceAdminTrust","reportHandler","reviewsHandler","publisherProfileSaveHandler","publishDatasetSchemaHandler","publishEmailStarterHandler","publishEmailTemplateHandler","publishLayoutHandler","publishTemplateHandler","publishThemeHandler","updateArtifactHandler","registerMarketplaceConsoleApi","route","resolve","segments","length","readListingForSocialCard","listingSocialCard","pluginId","web"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,uBAAuB,QAClB,sBAAqB;AAC5B,0EAA0E;AAC1E,qCAAqC;AACrC,SAASC,2BAA2B,QAAQ,oDAAmD;AAC/F,SAASC,+BAA+B,QAAQ,wDAAuD;AACvG,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,gCAAgC,QAAQ,8BAA0B;AAC3E,SAASC,2BAA2B,QAAQ,iCAA6B;AACzE,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,0BAA0B,QAAQ,mCAA+B;AAC1E,SAASC,eAAe,QAAQ,uBAAmB;AACnD,SAASC,cAAc,QAAQ,sBAAkB;AACjD,SAASC,cAAc,QAAQ,sBAAkB;AACjD,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,sBAAsB,QAAQ,+BAA2B;AAClE,SAASC,YAAY,QAAQ,0BAAsB;AACnD,SAASC,2BAA2B,QAAQ,qCAAiC;AAC7E,SAASC,0BAA0B,QAAQ,oCAAgC;AAC3E,SAASC,2BAA2B,QAAQ,qCAAiC;AAC7E,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,sBAAsB,QAAQ,+BAA2B;AAClE,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SAASC,cAAc,QAAQ,sBAAkB;AACjD,SAASC,4BAA4B,QAAQ,iCAA6B;AAC1E,SAASC,uBAAuB,QAAQ,4BAAwB;AAChE,SAASC,uBAAuB,QAAQ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