@aglyn/tenant-data-admin 1.0.0-beta.222 → 1.0.0-beta.223

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 (31) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/ga4-measurement-protocol.js +41 -28
  3. package/src/lib/server/ga4-measurement-protocol.js.map +1 -1
  4. package/src/lib/server/host-visitor-records.d.ts +13 -0
  5. package/src/lib/server/host-visitor-records.js +22 -4
  6. package/src/lib/server/host-visitor-records.js.map +1 -1
  7. package/src/lib/server/hosted-page-review.js +6 -3
  8. package/src/lib/server/hosted-page-review.js.map +1 -1
  9. package/src/lib/server/outbound-send-review.js +6 -3
  10. package/src/lib/server/outbound-send-review.js.map +1 -1
  11. package/src/lib/server/payment-fraud-signal.d.ts +49 -9
  12. package/src/lib/server/payment-fraud-signal.js +192 -48
  13. package/src/lib/server/payment-fraud-signal.js.map +1 -1
  14. package/src/lib/server/render-monitor.d.ts +166 -0
  15. package/src/lib/server/render-monitor.js +412 -0
  16. package/src/lib/server/render-monitor.js.map +1 -0
  17. package/src/lib/server/risk-notice.d.ts +7 -0
  18. package/src/lib/server/risk-notice.js +6 -0
  19. package/src/lib/server/risk-notice.js.map +1 -1
  20. package/src/lib/server/web-risk.d.ts +2 -0
  21. package/src/lib/server/web-risk.js +18 -21
  22. package/src/lib/server/web-risk.js.map +1 -1
  23. package/src/tenancy.d.ts +0 -2
  24. package/src/tenancy.js +0 -2
  25. package/src/tenancy.js.map +1 -1
  26. package/src/lib/server/crm-email-activity.d.ts +0 -118
  27. package/src/lib/server/crm-email-activity.js +0 -148
  28. package/src/lib/server/crm-email-activity.js.map +0 -1
  29. package/src/lib/server/crm-next-activity.d.ts +0 -74
  30. package/src/lib/server/crm-next-activity.js +0 -194
  31. package/src/lib/server/crm-next-activity.js.map +0 -1
@@ -35,7 +35,7 @@ export interface PaymentFraudCardChecks {
35
35
  }
36
36
  export interface PaymentFraudSignal {
37
37
  kind: PaymentFraudSignalKind;
38
- /** The EFW, review or dispute id: one row per signal, whatever redelivers. */
38
+ /** The EFW, review or dispute id: one entry per signal, whatever redelivers. */
39
39
  stripeObjectId: string;
40
40
  chargeId: string | null;
41
41
  paymentIntentId: string | null;
@@ -49,8 +49,25 @@ export interface PaymentFraudSignal {
49
49
  checks: PaymentFraudCardChecks | null;
50
50
  livemode: boolean;
51
51
  }
52
- /** The row id: hex, so the admin route's id pattern addresses it. */
53
- export declare function paymentFraudSignalReviewId(kind: PaymentFraudSignalKind, stripeObjectId: string): string;
52
+ /**
53
+ * The row id: one per CHARGE (AGL-3490), so every signal about one payment
54
+ * lands on the same row. The payment intent stands in for a signal that
55
+ * names no charge, and the signal itself for one that names neither. Hex,
56
+ * so the admin route's id pattern addresses it.
57
+ */
58
+ export declare function paymentFraudSignalReviewId(signal: Pick<PaymentFraudSignal, 'kind' | 'stripeObjectId' | 'chargeId' | 'paymentIntentId'>): string;
59
+ /** One signal as the row's history keeps it (AGL-3490). */
60
+ export interface PaymentFraudSignalEntry {
61
+ kind: PaymentFraudSignalKind;
62
+ stripeObjectId: string;
63
+ detail: string;
64
+ atMs: number;
65
+ /**
66
+ * The row's status when this signal arrived, if staff had already closed
67
+ * it — `actioned` or `dismissed` — else null.
68
+ */
69
+ arrivedAfter: string | null;
70
+ }
54
71
  /** The staff-facing reference, beside the intake's `AR-` and the screen's `HS-`. */
55
72
  export declare function paymentFraudSignalReference(reviewId: string): string;
56
73
  /** Where staff act on the workspace's billing: its Subscription card. */
@@ -92,23 +109,46 @@ export declare function readStripeChargeForSignal(chargeId: string, options: {
92
109
  */
93
110
  sellerAccountId: string | null;
94
111
  } | null>;
95
- /** The row's prose: what arrived, about which workspace, and what to do. */
96
- export declare function describePaymentFraudSignal(signal: PaymentFraudSignal): string;
97
112
  /**
98
- * File one signal and tell staff, once per signal.
113
+ * The row's prose: what arrived, about which workspace, and what to do.
99
114
  *
100
- * Idempotent on the Stripe object id: a redelivery bumps `reportCount` and
101
- * leaves the row's status — which staff own from the moment they touch it —
102
- * where it was. Throws only if the row write throws, which is the webhook's
115
+ * `history` is every signal on the charge, this one last; `closed` is what
116
+ * staff had decided before it arrived, if anything. The closing line says
117
+ * what THIS ALERT did — nothing to the money or the subscription — and
118
+ * never claims nothing was done at all: by the time a late warning lands,
119
+ * staff may have canceled, locked and accepted the chargeback (AGL-3490).
120
+ */
121
+ export declare function describePaymentFraudSignal(signal: PaymentFraudSignal, context?: {
122
+ history?: readonly PaymentFraudSignalEntry[];
123
+ closed?: {
124
+ status: string;
125
+ resolution: string | null;
126
+ } | null;
127
+ reopened?: boolean;
128
+ }): string;
129
+ /**
130
+ * File one signal on its charge's row, and tell the owners and staff once
131
+ * per charge (AGL-3490).
132
+ *
133
+ * The first signal on a charge opens the row. A later one — a different
134
+ * Stripe object about the same payment — is added to `paymentSignals`, and
135
+ * `paymentSignal` becomes it, so the row's Stripe link follows a dispute.
136
+ * The status is staff's from the moment they touch it and is left alone,
137
+ * except that a dispute on a DISMISSED row reopens it and notifies again. A
138
+ * redelivery of a signal already on the row adds nothing. Read and written
139
+ * in one transaction, so a warning and a dispute arriving together still
140
+ * make one row. Throws only if the row write throws, which is the webhook's
103
141
  * to answer; the notification never throws.
104
142
  */
105
143
  export declare function recordPaymentFraudSignal(signal: PaymentFraudSignal, deps: {
106
144
  firestore: FirebaseFirestore.Firestore;
107
145
  notifyRisk: RiskNotifier;
146
+ nowMs?: number;
108
147
  }): Promise<{
109
148
  reviewId: string;
110
149
  reference: string;
111
150
  first: boolean;
151
+ reopened: boolean;
112
152
  }>;
113
153
  export declare const SELLER_FRAUD_PATTERN: {
114
154
  /** Distinct charges with an early fraud warning or a dispute. */
@@ -31,6 +31,19 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
31
31
  * a refund issued before staff look can be the wrong half of a dispute. The
32
32
  * row is the prompt; staff decide.
33
33
  *
34
+ * ONE ROW PER CHARGE (AGL-3490). The three signals are separate Stripe
35
+ * objects about the same payment, and one fraudulent charge routinely draws
36
+ * two of them — a warning and then a dispute, in either order: the issuer's
37
+ * fraud report reached Stripe a day AFTER the 9/26 charge's chargeback had
38
+ * been accepted. Keyed by signal, each one opened its own urgent row and told
39
+ * the owners and staff again. So the row is keyed by the charge, and a later
40
+ * signal joins it: added to `paymentSignals`, never a second row or a second
41
+ * notice. A row staff have closed stays closed — the later signal is written
42
+ * onto it, beside what they decided — with one exception: a DISPUTE on a row
43
+ * staff DISMISSED reopens it and tells them, because the bank now says the
44
+ * cardholder did not make the payment staff judged genuine, and the evidence
45
+ * deadline is running.
46
+ *
34
47
  * Dependencies are passed in rather than imported — the Firestore handle the
35
48
  * webhook observes its writes through, and its staff notifier — so the
36
49
  * webhook's "did this delivery do anything" ledger sees the write, and a spec
@@ -45,9 +58,20 @@ const KIND_LABEL = {
45
58
  dispute: 'Card dispute opened'
46
59
  };
47
60
  /** The Stripe object type each signal arrives as, for the queue's text. */ export const PAYMENT_FRAUD_SIGNAL_LABELS = KIND_LABEL;
48
- /** The row id: hex, so the admin route's id pattern addresses it. */ export function paymentFraudSignalReviewId(kind, stripeObjectId) {
49
- return createHash('sha256').update(`stripe-fraud:${kind}:${stripeObjectId}`).digest('hex').slice(0, 40);
61
+ /**
62
+ * The row id: one per CHARGE (AGL-3490), so every signal about one payment
63
+ * lands on the same row. The payment intent stands in for a signal that
64
+ * names no charge, and the signal itself for one that names neither. Hex,
65
+ * so the admin route's id pattern addresses it.
66
+ */ export function paymentFraudSignalReviewId(signal) {
67
+ const payment = signal.chargeId || signal.paymentIntentId;
68
+ return createHash('sha256').update(payment ? `stripe-fraud:payment:${payment}` : `stripe-fraud:${signal.kind}:${signal.stripeObjectId}`).digest('hex').slice(0, 40);
50
69
  }
70
+ /** The row's history is a short list; a charge draws at most a few signals. */ const SIGNAL_HISTORY_MAX = 10;
71
+ /** The statuses that mean staff have decided the row. */ const CLOSED_STATUSES = new Set([
72
+ 'actioned',
73
+ 'dismissed'
74
+ ]);
51
75
  /** The staff-facing reference, beside the intake's `AR-` and the screen's `HS-`. */ export function paymentFraudSignalReference(reviewId) {
52
76
  return `PF-${reviewId.slice(0, 10).toUpperCase()}`;
53
77
  }
@@ -113,8 +137,17 @@ const KIND_LABEL = {
113
137
  const id = typeof value === 'string' ? value : String((_ref = value == null ? void 0 : value.id) != null ? _ref : '');
114
138
  return id.startsWith('acct_') ? id : null;
115
139
  }
116
- /** The row's prose: what arrived, about which workspace, and what to do. */ export function describePaymentFraudSignal(signal) {
117
- var _signal_orgId, _ref, _signal_chargeId;
140
+ /**
141
+ * The row's prose: what arrived, about which workspace, and what to do.
142
+ *
143
+ * `history` is every signal on the charge, this one last; `closed` is what
144
+ * staff had decided before it arrived, if anything. The closing line says
145
+ * what THIS ALERT did — nothing to the money or the subscription — and
146
+ * never claims nothing was done at all: by the time a late warning lands,
147
+ * staff may have canceled, locked and accepted the chargeback (AGL-3490).
148
+ */ export function describePaymentFraudSignal(signal, context = {}) {
149
+ var _signal_orgId, _ref, _signal_chargeId, _context_history;
150
+ var _context_closed;
118
151
  const lines = [
119
152
  `${KIND_LABEL[signal.kind]} from Stripe (${signal.stripeObjectId})` + (signal.livemode ? '' : ' — TEST MODE') + '.',
120
153
  `Workspace: ${(_signal_orgId = signal.orgId) != null ? _signal_orgId : 'none — the charge did not resolve to a workspace subscription'}.`,
@@ -126,57 +159,167 @@ const KIND_LABEL = {
126
159
  var _checks_cvcCheck, _checks_addressPostalCodeCheck, _checks_cardCountry, _checks_threeDSecure, _checks_riskLevel;
127
160
  lines.push(`Card: CVC ${(_checks_cvcCheck = checks.cvcCheck) != null ? _checks_cvcCheck : 'unknown'}, postal code ${(_checks_addressPostalCodeCheck = checks.addressPostalCodeCheck) != null ? _checks_addressPostalCodeCheck : 'unknown'}, ` + `issued in ${(_checks_cardCountry = checks.cardCountry) != null ? _checks_cardCountry : 'unknown'}, 3DS ${(_checks_threeDSecure = checks.threeDSecure) != null ? _checks_threeDSecure : 'not used'}, ` + `Radar risk ${(_checks_riskLevel = checks.riskLevel) != null ? _checks_riskLevel : 'unknown'}.`);
128
161
  }
129
- lines.push(signal.kind === 'radar-review' ? 'The payment waits in Stripe until the review is closed there.' : signal.kind === 'dispute' ? 'Answer the dispute in Stripe before its evidence deadline.' : 'An early fraud warning is not yet a chargeback; refunding now can avoid one.', 'Nothing has been refunded or canceled. Decide on the org’s Subscription card, lock the workspace if it is fraud, and close this row with what you did.');
162
+ const history = (_context_history = context.history) != null ? _context_history : [];
163
+ if (history.length > 1) {
164
+ lines.push(`Every signal on this charge, oldest first: ${history.map((entry)=>`${KIND_LABEL[entry.kind]} (${entry.stripeObjectId}` + (entry.arrivedAfter ? `, after the row was ${entry.arrivedAfter}` : '') + ')').join('; ')}.`);
165
+ }
166
+ const resolution = ((_context_closed = context.closed) == null ? void 0 : _context_closed.resolution) ? `: “${context.closed.resolution}”` : '.';
167
+ if (context.reopened && context.closed) {
168
+ lines.push(`REOPENED. Staff had dismissed this row${resolution} The cardholder’s bank has now disputed the payment. Answer or accept the dispute in Stripe before its evidence deadline, then close this row again with what you did.`);
169
+ } else if (context.closed) {
170
+ lines.push(`This signal arrived after the row was closed as ${context.closed.status}${resolution} The row stays closed and nobody was notified again. Reopen it only if that decision no longer holds.`);
171
+ } else {
172
+ lines.push(signal.kind === 'radar-review' ? 'The payment waits in Stripe until the review is closed there.' : signal.kind === 'dispute' ? 'Answer the dispute in Stripe before its evidence deadline.' : 'An early fraud warning is not yet a chargeback; refunding now can avoid one.', 'This alert refunded and canceled nothing. Decide on the org’s Subscription card, lock the workspace if it is fraud, and close this row with what you did.');
173
+ }
130
174
  return lines.join('\n').slice(0, 5000);
131
175
  }
176
+ /** The history a stored row carries, oldest first. */ function signalHistoryOf(row, fallbackAtMs) {
177
+ var _row_paymentSignal, _ref, _ref1, _ref2;
178
+ if (!row) return [];
179
+ const kinds = Object.keys(KIND_LABEL);
180
+ const stored = Array.isArray(row['paymentSignals']) ? row['paymentSignals'] : [];
181
+ const entries = stored.flatMap((value)=>{
182
+ var _entry_kind, _entry_stripeObjectId, _entry_detail;
183
+ const entry = value != null ? value : {};
184
+ const kind = String((_entry_kind = entry['kind']) != null ? _entry_kind : '');
185
+ const stripeObjectId = String((_entry_stripeObjectId = entry['stripeObjectId']) != null ? _entry_stripeObjectId : '');
186
+ if (!kinds.includes(kind) || !stripeObjectId) return [];
187
+ return [
188
+ {
189
+ kind: kind,
190
+ stripeObjectId,
191
+ detail: String((_entry_detail = entry['detail']) != null ? _entry_detail : ''),
192
+ atMs: Number(entry['atMs']) || 0,
193
+ arrivedAfter: typeof entry['arrivedAfter'] === 'string' ? entry['arrivedAfter'] : null
194
+ }
195
+ ];
196
+ });
197
+ if (entries.length) return entries;
198
+ // A row filed before the history existed carries its one signal as
199
+ // `paymentSignal`, which is where a redelivery of it is recognised.
200
+ const only = (_row_paymentSignal = row['paymentSignal']) != null ? _row_paymentSignal : null;
201
+ const kind = String((_ref = only == null ? void 0 : only['kind']) != null ? _ref : '');
202
+ const stripeObjectId = String((_ref1 = only == null ? void 0 : only['stripeObjectId']) != null ? _ref1 : '');
203
+ return kinds.includes(kind) && stripeObjectId ? [
204
+ {
205
+ kind: kind,
206
+ stripeObjectId,
207
+ detail: String((_ref2 = only == null ? void 0 : only['detail']) != null ? _ref2 : ''),
208
+ atMs: fallbackAtMs,
209
+ arrivedAfter: null
210
+ }
211
+ ] : [];
212
+ }
132
213
  /**
133
- * File one signal and tell staff, once per signal.
214
+ * File one signal on its charge's row, and tell the owners and staff once
215
+ * per charge (AGL-3490).
134
216
  *
135
- * Idempotent on the Stripe object id: a redelivery bumps `reportCount` and
136
- * leaves the row's status — which staff own from the moment they touch it —
137
- * where it was. Throws only if the row write throws, which is the webhook's
217
+ * The first signal on a charge opens the row. A later one — a different
218
+ * Stripe object about the same payment — is added to `paymentSignals`, and
219
+ * `paymentSignal` becomes it, so the row's Stripe link follows a dispute.
220
+ * The status is staff's from the moment they touch it and is left alone,
221
+ * except that a dispute on a DISMISSED row reopens it and notifies again. A
222
+ * redelivery of a signal already on the row adds nothing. Read and written
223
+ * in one transaction, so a warning and a dispute arriving together still
224
+ * make one row. Throws only if the row write throws, which is the webhook's
138
225
  * to answer; the notification never throws.
139
226
  */ export async function recordPaymentFraudSignal(signal, deps) {
140
- const reviewId = paymentFraudSignalReviewId(signal.kind, signal.stripeObjectId);
227
+ var _deps_nowMs;
228
+ const reviewId = paymentFraudSignalReviewId(signal);
141
229
  const reference = paymentFraudSignalReference(reviewId);
142
230
  const ref = deps.firestore.collection(ABUSE_REPORT_COLLECTION).doc(reviewId);
143
- const first = !(await ref.get()).exists;
144
- const subscriptionCard = signal.orgId ? staffSubscriptionCardPath(signal.orgId) : null;
145
- await ref.set(_extends({
146
- reference,
147
- // "Phishing or fraud" — the queue's urgent fraud category.
148
- category: 'phishing',
149
- severity: 'urgent',
150
- source: 'stripe-fraud-signal',
151
- url: null,
152
- reportedHostname: null,
153
- hostId: null,
154
- orgId: signal.orgId,
155
- details: describePaymentFraudSignal(signal),
156
- reporterEmail: null,
157
- reporterName: null,
158
- dmca: null,
159
- reportCount: FieldValue.increment(1),
160
- paymentSignal: {
161
- kind: signal.kind,
162
- stripeObjectId: signal.stripeObjectId,
163
- chargeId: signal.chargeId,
164
- paymentIntentId: signal.paymentIntentId,
165
- amountCents: signal.amountCents,
166
- currency: signal.currency,
167
- detail: signal.detail,
168
- checks: signal.checks,
169
- livemode: signal.livemode,
170
- subscriptionCard
171
- },
172
- updatedAt: FieldValue.serverTimestamp()
173
- }, first ? {
174
- status: 'open',
175
- createdAt: FieldValue.serverTimestamp()
176
- } : {}), {
177
- merge: true
231
+ const atMs = (_deps_nowMs = deps.nowMs) != null ? _deps_nowMs : Date.now();
232
+ const { first, reopened } = await deps.firestore.runTransaction(async (transaction)=>{
233
+ var _snapshot_data, _existing_status, _ref, _signal_orgId, _signal_amountCents, _signal_checks, _ref1;
234
+ const snapshot = await transaction.get(ref);
235
+ const existing = snapshot.exists ? (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {} : null;
236
+ const history = signalHistoryOf(existing, atMs);
237
+ if (existing && history.some((entry)=>entry.stripeObjectId === signal.stripeObjectId)) {
238
+ transaction.set(ref, {
239
+ updatedAt: FieldValue.serverTimestamp()
240
+ }, {
241
+ merge: true
242
+ });
243
+ return {
244
+ first: false,
245
+ reopened: false
246
+ };
247
+ }
248
+ const status = existing ? String((_existing_status = existing['status']) != null ? _existing_status : 'open') : 'open';
249
+ const wasClosed = CLOSED_STATUSES.has(status);
250
+ const reopen = status === 'dismissed' && signal.kind === 'dispute';
251
+ const resolution = typeof (existing == null ? void 0 : existing['resolution']) === 'string' && existing['resolution'].trim() ? existing['resolution'].trim() : null;
252
+ const nextHistory = [
253
+ ...history,
254
+ {
255
+ kind: signal.kind,
256
+ stripeObjectId: signal.stripeObjectId,
257
+ detail: signal.detail,
258
+ atMs,
259
+ arrivedAfter: wasClosed ? status : null
260
+ }
261
+ ].slice(-SIGNAL_HISTORY_MAX);
262
+ // A later signal whose charge read failed keeps what the first one
263
+ // learned rather than erasing it.
264
+ const previous = (_ref = existing == null ? void 0 : existing['paymentSignal']) != null ? _ref : null;
265
+ const orgId = (_signal_orgId = signal.orgId) != null ? _signal_orgId : typeof (existing == null ? void 0 : existing['orgId']) === 'string' ? existing['orgId'] : null;
266
+ const merged = _extends({}, signal, {
267
+ orgId,
268
+ amountCents: (_signal_amountCents = signal.amountCents) != null ? _signal_amountCents : typeof (previous == null ? void 0 : previous['amountCents']) === 'number' ? previous['amountCents'] : null,
269
+ checks: (_signal_checks = signal.checks) != null ? _signal_checks : (_ref1 = previous == null ? void 0 : previous['checks']) != null ? _ref1 : null
270
+ });
271
+ transaction.set(ref, _extends({
272
+ reference,
273
+ // "Phishing or fraud" — the queue's urgent fraud category.
274
+ category: 'phishing',
275
+ severity: 'urgent',
276
+ source: 'stripe-fraud-signal',
277
+ url: null,
278
+ reportedHostname: null,
279
+ hostId: null,
280
+ orgId,
281
+ details: describePaymentFraudSignal(merged, {
282
+ history: nextHistory,
283
+ closed: wasClosed ? {
284
+ status,
285
+ resolution
286
+ } : null,
287
+ reopened: reopen
288
+ }),
289
+ reporterEmail: null,
290
+ reporterName: null,
291
+ dmca: null,
292
+ reportCount: nextHistory.length,
293
+ paymentSignals: nextHistory,
294
+ paymentSignal: {
295
+ kind: merged.kind,
296
+ stripeObjectId: merged.stripeObjectId,
297
+ chargeId: merged.chargeId,
298
+ paymentIntentId: merged.paymentIntentId,
299
+ amountCents: merged.amountCents,
300
+ currency: merged.currency,
301
+ detail: merged.detail,
302
+ checks: merged.checks,
303
+ livemode: merged.livemode,
304
+ subscriptionCard: orgId ? staffSubscriptionCardPath(orgId) : null
305
+ },
306
+ updatedAt: FieldValue.serverTimestamp()
307
+ }, existing ? {} : {
308
+ status: 'open',
309
+ createdAt: FieldValue.serverTimestamp()
310
+ }, reopen ? {
311
+ status: 'open',
312
+ reopenedAt: FieldValue.serverTimestamp(),
313
+ resolvedAt: null
314
+ } : {}), {
315
+ merge: true
316
+ });
317
+ return {
318
+ first: !existing,
319
+ reopened: reopen
320
+ };
178
321
  });
179
- if (first) {
322
+ if (first || reopened) {
180
323
  var _RISK_PAYMENT_EVENTS_signal_kind, _ref, _signal_chargeId;
181
324
  // The workspace's owners are told their subscription payment was
182
325
  // flagged and how to confirm it; staff get the row with the evidence.
@@ -194,13 +337,14 @@ const KIND_LABEL = {
194
337
  // a fraud check. The notice says which.
195
338
  paymentEvent: (_RISK_PAYMENT_EVENTS_signal_kind = RISK_PAYMENT_EVENTS[signal.kind]) != null ? _RISK_PAYMENT_EVENTS_signal_kind : null,
196
339
  stripeUrl: stripeSignalDashboardUrl(signal),
197
- staffEvidence: `${KIND_LABEL[signal.kind]} (${signal.stripeObjectId}) on charge ` + `${(_ref = (_signal_chargeId = signal.chargeId) != null ? _signal_chargeId : signal.paymentIntentId) != null ? _ref : 'not named'}` + (signal.detail ? `; Stripe says: ${signal.detail}` : '') + (signal.livemode ? '' : ' — TEST MODE') + '.'
340
+ staffEvidence: `${KIND_LABEL[signal.kind]} (${signal.stripeObjectId}) on charge ` + `${(_ref = (_signal_chargeId = signal.chargeId) != null ? _signal_chargeId : signal.paymentIntentId) != null ? _ref : 'not named'}` + (signal.detail ? `; Stripe says: ${signal.detail}` : '') + (signal.livemode ? '' : ' — TEST MODE') + (reopened ? '; reopened a row staff had dismissed' : '') + '.'
198
341
  }).catch(()=>undefined);
199
342
  }
200
343
  return {
201
344
  reviewId,
202
345
  reference,
203
- first
346
+ first,
347
+ reopened
204
348
  };
205
349
  }
206
350
  /*==========================================
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/payment-fraud-signal.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 * STRIPE'S FRAUD SIGNALS, INTO THE ABUSE QUEUE (AGL-3356).\n *\n * The 9/26 incident paid for Pro with a card whose CVC check came back\n * unavailable and which never met 3-D Secure. Stripe had three ways to tell\n * us about a card like that — an early fraud warning from the issuer, a\n * Radar review, a dispute — and the platform webhook either did not\n * subscribe to them or filed them where nobody triages abuse.\n *\n * Each signal now files an urgent row in the abuse queue that names the\n * workspace, the charge and the amount, links the staff Subscription card\n * on the org page (AGL-3359, where billing is canceled), and notifies staff\n * once. NOTHING IS DONE TO THE MONEY OR THE SUBSCRIPTION: no refund, no\n * cancel. An early fraud warning is not a chargeback, a review may clear, and\n * a refund issued before staff look can be the wrong half of a dispute. The\n * row is the prompt; staff decide.\n *\n * Dependencies are passed in rather than imported — the Firestore handle the\n * webhook observes its writes through, and its staff notifier — so the\n * webhook's \"did this delivery do anything\" ledger sees the write, and a spec\n * substituting the admin barrel substitutes these too.\n *=========================================*/\n\nimport { createHash } from 'crypto'\nimport { ABUSE_REPORT_COLLECTION } from '@aglyn/aglyn/app-utils/abuse-report'\nimport { RISK_PAYMENT_EVENTS } from '@aglyn/shared-util-email/risk-notice-catalog'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport type { RiskEventInput } from './risk-notice'\n\n/**\n * The seam every signal here tells people through (AGL-3368): the owners\n * and admins of the workspace, and staff. Passed in, like the Firestore\n * handle, so the webhook's spec substitutes it with the barrel.\n */\nexport type RiskNotifier = (input: RiskEventInput) => Promise<unknown>\n\n/** Which Stripe signal this is. */\nexport type PaymentFraudSignalKind =\n | 'early-fraud-warning'\n | 'radar-review'\n | 'dispute'\n\nconst KIND_LABEL: Record<PaymentFraudSignalKind, string> = {\n 'early-fraud-warning': 'Early fraud warning',\n 'radar-review': 'Radar review opened',\n dispute: 'Card dispute opened',\n}\n\n/** The Stripe object type each signal arrives as, for the queue's text. */\nexport const PAYMENT_FRAUD_SIGNAL_LABELS = KIND_LABEL\n\n/** What the card's own checks said, when the charge could be read. */\nexport interface PaymentFraudCardChecks {\n cvcCheck: string | null\n addressPostalCodeCheck: string | null\n cardCountry: string | null\n riskLevel: string | null\n threeDSecure: string | null\n}\n\nexport interface PaymentFraudSignal {\n kind: PaymentFraudSignalKind\n /** The EFW, review or dispute id: one row per signal, whatever redelivers. */\n stripeObjectId: string\n chargeId: string | null\n paymentIntentId: string | null\n /** The workspace the charge billed, or null when it resolved to none. */\n orgId: string | null\n /** Smallest currency unit, or null when nothing recorded the amount. */\n amountCents: number | null\n currency: string\n /** `fraud_type`, the review's `reason`, the dispute's `reason`. */\n detail: string\n checks: PaymentFraudCardChecks | null\n livemode: boolean\n}\n\n/** The row id: hex, so the admin route's id pattern addresses it. */\nexport function paymentFraudSignalReviewId(\n kind: PaymentFraudSignalKind,\n stripeObjectId: string,\n): string {\n return createHash('sha256')\n .update(`stripe-fraud:${kind}:${stripeObjectId}`)\n .digest('hex')\n .slice(0, 40)\n}\n\n/** The staff-facing reference, beside the intake's `AR-` and the screen's `HS-`. */\nexport function paymentFraudSignalReference(reviewId: string): string {\n return `PF-${reviewId.slice(0, 10).toUpperCase()}`\n}\n\n/** Where staff act on the workspace's billing: its Subscription card. */\nexport function staffSubscriptionCardPath(orgId: string): string {\n return `/admin/orgs/${encodeURIComponent(orgId)}#subscription`\n}\n\n/**\n * The Stripe Dashboard page for a signal: the dispute itself, else the\n * payment it is about.\n */\nexport function stripeSignalDashboardUrl(signal: {\n kind: PaymentFraudSignalKind\n stripeObjectId: string\n chargeId: string | null\n paymentIntentId: string | null\n livemode: boolean\n}): string | null {\n const base = `https://dashboard.stripe.com/${signal.livemode ? '' : 'test/'}`\n if (signal.kind === 'dispute' && signal.stripeObjectId) {\n return `${base}disputes/${encodeURIComponent(signal.stripeObjectId)}`\n }\n const payment = signal.paymentIntentId || signal.chargeId\n return payment ? `${base}payments/${encodeURIComponent(payment)}` : null\n}\n\n/** `$56.00 USD`, or a sentence saying the amount is not known. */\nexport function formatSignalAmount(\n amountCents: number | null,\n currency: string,\n): string {\n if (amountCents === null || !Number.isFinite(amountCents)) {\n return 'amount not recorded'\n }\n return `${(amountCents / 100).toFixed(2)} ${String(currency || 'usd').toUpperCase()}`\n}\n\n/**\n * The one-line summary of a charge Stripe gives back, for a signal whose\n * charge is not on a platform revenue row. A READ — the only Stripe call\n * this module makes — and it answers null rather than throwing, because a\n * fraud alert that fails for want of an amount is worse than one that says\n * the amount is unknown.\n */\nexport async function readStripeChargeForSignal(\n chargeId: string,\n options: { secretKey: string | undefined; fetchImpl?: typeof fetch },\n): Promise<{\n amountCents: number | null\n currency: string\n customerId: string | null\n checks: PaymentFraudCardChecks\n /**\n * The connected account the charge paid (AGL-3360): a destination\n * charge's `transfer_data.destination`. Every sale Aglyn takes for a site\n * is a destination charge on the platform account — the facilitator\n * model (AGL-1956) — so this is the seller. Null for a charge that paid\n * only the platform, a workspace's own subscription.\n */\n sellerAccountId: string | null\n} | null> {\n if (!chargeId || !options.secretKey) return null\n try {\n const response = await (options.fetchImpl ?? fetch)(\n `https://api.stripe.com/v1/charges/${encodeURIComponent(chargeId)}`,\n { headers: { Authorization: `Bearer ${options.secretKey}` } },\n )\n if (!response.ok) return null\n const charge = (await response.json()) as Record<string, any>\n const card = charge?.['payment_method_details']?.['card'] ?? {}\n const text = (value: unknown) =>\n typeof value === 'string' && value ? value : null\n return {\n amountCents: Number.isFinite(Number(charge?.['amount']))\n ? Number(charge['amount'])\n : null,\n currency: String(charge?.['currency'] ?? 'usd'),\n customerId: text(charge?.['customer']),\n checks: {\n cvcCheck: text(card?.['checks']?.['cvc_check']),\n addressPostalCodeCheck: text(card?.['checks']?.['address_postal_code_check']),\n cardCountry: text(card?.['country']),\n riskLevel: text(charge?.['outcome']?.['risk_level']),\n threeDSecure: text(card?.['three_d_secure']?.['result']),\n },\n sellerAccountId: accountRef(charge?.['transfer_data']?.['destination']),\n }\n } catch {\n return null\n }\n}\n\n/** A Stripe account reference, expanded or not, as an id or null. */\nfunction accountRef(value: unknown): string | null {\n const id =\n typeof value === 'string'\n ? value\n : String((value as { id?: unknown } | null)?.id ?? '')\n return id.startsWith('acct_') ? id : null\n}\n\n/** The row's prose: what arrived, about which workspace, and what to do. */\nexport function describePaymentFraudSignal(signal: PaymentFraudSignal): string {\n const lines = [\n `${KIND_LABEL[signal.kind]} from Stripe (${signal.stripeObjectId})` +\n (signal.livemode ? '' : ' — TEST MODE') +\n '.',\n `Workspace: ${signal.orgId ?? 'none — the charge did not resolve to a workspace subscription'}.`,\n `Charge: ${signal.chargeId ?? signal.paymentIntentId ?? 'not named'} · ${formatSignalAmount(signal.amountCents, signal.currency)}.`,\n ]\n if (signal.detail) lines.push(`Stripe says: ${signal.detail}.`)\n const checks = signal.checks\n if (checks) {\n lines.push(\n `Card: CVC ${checks.cvcCheck ?? 'unknown'}, postal code ${checks.addressPostalCodeCheck ?? 'unknown'}, ` +\n `issued in ${checks.cardCountry ?? 'unknown'}, 3DS ${checks.threeDSecure ?? 'not used'}, ` +\n `Radar risk ${checks.riskLevel ?? 'unknown'}.`,\n )\n }\n lines.push(\n signal.kind === 'radar-review'\n ? 'The payment waits in Stripe until the review is closed there.'\n : signal.kind === 'dispute'\n ? 'Answer the dispute in Stripe before its evidence deadline.'\n : 'An early fraud warning is not yet a chargeback; refunding now can avoid one.',\n 'Nothing has been refunded or canceled. Decide on the org’s Subscription card, lock the workspace if it is fraud, and close this row with what you did.',\n )\n return lines.join('\\n').slice(0, 5000)\n}\n\n/**\n * File one signal and tell staff, once per signal.\n *\n * Idempotent on the Stripe object id: a redelivery bumps `reportCount` and\n * leaves the row's status — which staff own from the moment they touch it —\n * where it was. Throws only if the row write throws, which is the webhook's\n * to answer; the notification never throws.\n */\nexport async function recordPaymentFraudSignal(\n signal: PaymentFraudSignal,\n deps: {\n firestore: FirebaseFirestore.Firestore\n notifyRisk: RiskNotifier\n },\n): Promise<{ reviewId: string; reference: string; first: boolean }> {\n const reviewId = paymentFraudSignalReviewId(signal.kind, signal.stripeObjectId)\n const reference = paymentFraudSignalReference(reviewId)\n const ref = deps.firestore.collection(ABUSE_REPORT_COLLECTION).doc(reviewId)\n const first = !(await ref.get()).exists\n const subscriptionCard = signal.orgId\n ? staffSubscriptionCardPath(signal.orgId)\n : null\n await ref.set(\n {\n reference,\n // \"Phishing or fraud\" — the queue's urgent fraud category.\n category: 'phishing',\n severity: 'urgent',\n source: 'stripe-fraud-signal',\n url: null,\n reportedHostname: null,\n hostId: null,\n orgId: signal.orgId,\n details: describePaymentFraudSignal(signal),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n reportCount: FieldValue.increment(1),\n paymentSignal: {\n kind: signal.kind,\n stripeObjectId: signal.stripeObjectId,\n chargeId: signal.chargeId,\n paymentIntentId: signal.paymentIntentId,\n amountCents: signal.amountCents,\n currency: signal.currency,\n detail: signal.detail,\n checks: signal.checks,\n livemode: signal.livemode,\n subscriptionCard,\n },\n updatedAt: FieldValue.serverTimestamp(),\n ...(first\n ? { status: 'open', createdAt: FieldValue.serverTimestamp() }\n : {}),\n },\n { merge: true },\n )\n if (first) {\n // The workspace's owners are told their subscription payment was\n // flagged and how to confirm it; staff get the row with the evidence.\n await deps\n .notifyRisk({\n kind: 'billing-payment-flagged',\n orgId: signal.orgId,\n reviewId,\n reference,\n item: { label: 'your subscription payment', path: '/org/billing/invoices' },\n amount: formatSignalAmount(signal.amountCents, signal.currency),\n // A dispute is the bank's, already opened; a warning or a review is\n // a fraud check. The notice says which.\n paymentEvent: RISK_PAYMENT_EVENTS[signal.kind] ?? null,\n stripeUrl: stripeSignalDashboardUrl(signal),\n staffEvidence:\n `${KIND_LABEL[signal.kind]} (${signal.stripeObjectId}) on charge ` +\n `${signal.chargeId ?? signal.paymentIntentId ?? 'not named'}` +\n (signal.detail ? `; Stripe says: ${signal.detail}` : '') +\n (signal.livemode ? '' : ' — TEST MODE') +\n '.',\n })\n .catch(() => undefined)\n }\n return { reviewId, reference, first }\n}\n\n/*==========================================\n * THE SELLER PATTERN: WHEN THE MERCHANT MAY BE THE FRAUDSTER (AGL-3360).\n *\n * A site's own sales are destination charges on the platform account, so\n * Stripe's fraud signals about a shopper's card arrive here too. One of them\n * is the merchant's business — their customer, their order, their decision\n * (`payment-risk-record.ts` puts it on the record and tells them). Staff are\n * not paged for it.\n *\n * What IS staff's business is the shape a phishing actor leaves when they\n * run stolen cards through a storefront of their own: several different\n * charges on ONE connected account drawing issuer fraud reports or\n * chargebacks in a short time. So every signal on a seller's charge is kept\n * in a small per-account ledger, and one urgent abuse-queue row is filed when\n *\n * ≥ 3 DISTINCT charges carry an early fraud warning or a dispute\n * within 7 days.\n *\n * Why those numbers. An early fraud warning is an issuer's report that the\n * cardholder did not make the payment, and a dispute is a formal\n * chargeback; a legitimate small merchant sees either rarely — card-network\n * dispute monitoring starts near 0.9% of a month's transactions, single\n * digits a MONTH for a shop doing hundreds of sales. One or two in a week is\n * ordinary friendly fraud and must never page staff. Three separate charges\n * in one week is a rate a real small shop does not produce, and is what a\n * card tester or a stolen-card storefront produces within days. Counted by\n * CHARGE, because a warning is routinely followed by a dispute on the same\n * payment, and that is one bad payment, not two. Radar reviews are kept in\n * the ledger for the row's prose but never counted: a review is Stripe's\n * suspicion, not an issuer's report, and a busy shop can collect several\n * that clear.\n *\n * One row per window: once filed, the account is not filed again until 7\n * days have passed, so a burst is one row with everything in it rather than\n * a row per signal. NOTHING IS DONE TO THE ACCOUNT OR THE MONEY: staff\n * decide (lock the workspace, pause the account's payouts in Stripe).\n *=========================================*/\n\nexport const SELLER_FRAUD_PATTERN = {\n /** Distinct charges with an early fraud warning or a dispute. */\n minDistinctCharges: 3,\n /** …within this window. */\n windowMs: 7 * 24 * 60 * 60 * 1000,\n /** How long the ledger keeps an entry at all. */\n retainMs: 30 * 24 * 60 * 60 * 1000,\n} as const\n\nconst WINDOW_DAYS = SELLER_FRAUD_PATTERN.windowMs / 86_400_000\n\n/** Admin-SDK only; no client rule opens it (default deny). */\nexport const SELLER_FRAUD_LEDGER_COLLECTION = 'paymentFraudLedger'\n\nexport interface SellerFraudLedgerEntry {\n kind: PaymentFraudSignalKind\n stripeObjectId: string\n chargeId: string | null\n amountCents: number | null\n currency: string\n detail: string\n /** The sites a plugin recognised the charge as belonging to. */\n hostIds: string[]\n atMs: number\n}\n\n/** Whether a seller's ledger shows the pattern at `nowMs`. Pure. */\nexport function sellerFraudPattern(\n entries: readonly SellerFraudLedgerEntry[],\n nowMs: number,\n): { matched: boolean; chargeIds: string[] } {\n const since = nowMs - SELLER_FRAUD_PATTERN.windowMs\n const chargeIds = [\n ...new Set(\n entries\n .filter(\n (entry) =>\n (entry.kind === 'early-fraud-warning' || entry.kind === 'dispute') &&\n entry.atMs >= since,\n )\n .map((entry) => entry.chargeId || entry.stripeObjectId),\n ),\n ]\n return {\n matched: chargeIds.length >= SELLER_FRAUD_PATTERN.minDistinctCharges,\n chargeIds,\n }\n}\n\n/** The connected account's page in the Stripe Dashboard. */\nexport function stripeConnectedAccountUrl(\n accountId: string,\n livemode: boolean,\n): string {\n return `https://dashboard.stripe.com/${livemode ? '' : 'test/'}connect/accounts/${encodeURIComponent(accountId)}`\n}\n\n/**\n * Keep one signal on a seller's charge, and file the pattern row when the\n * ledger crosses the threshold. Idempotent on the Stripe object id: a\n * redelivery changes nothing and files nothing.\n */\nexport async function recordSellerFraudSignal(\n input: {\n signal: PaymentFraudSignal\n sellerAccountId: string\n /** The sites a plugin recognised the charge as belonging to. */\n hostIds: string[]\n /** Workspaces owning those sites, for the row. */\n orgIds: string[]\n },\n deps: {\n firestore: FirebaseFirestore.Firestore\n notifyRisk: RiskNotifier\n nowMs?: number\n },\n): Promise<{\n first: boolean\n matched: boolean\n filed: { reviewId: string; reference: string } | null\n}> {\n const nowMs = deps.nowMs ?? Date.now()\n const { signal, sellerAccountId } = input\n const ledgerRef = deps.firestore\n .collection(SELLER_FRAUD_LEDGER_COLLECTION)\n .doc(sellerAccountId)\n const outcome = await deps.firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(ledgerRef)\n const stored = (\n Array.isArray(fresh.get('entries')) ? fresh.get('entries') : []\n ) as SellerFraudLedgerEntry[]\n if (stored.some((entry) => entry.stripeObjectId === signal.stripeObjectId)) {\n return { first: false, matched: false, fileAtMs: 0, entries: stored }\n }\n const entries: SellerFraudLedgerEntry[] = [\n ...stored.filter(\n (entry) => entry.atMs >= nowMs - SELLER_FRAUD_PATTERN.retainMs,\n ),\n {\n kind: signal.kind,\n stripeObjectId: signal.stripeObjectId,\n chargeId: signal.chargeId,\n amountCents: signal.amountCents,\n currency: signal.currency,\n detail: signal.detail,\n hostIds: input.hostIds,\n atMs: nowMs,\n },\n ]\n const { matched } = sellerFraudPattern(entries, nowMs)\n const lastFiledAtMs = Number(fresh.get('lastFiledAtMs') ?? 0)\n const fileAtMs =\n matched &&\n !(lastFiledAtMs && nowMs - lastFiledAtMs < SELLER_FRAUD_PATTERN.windowMs)\n ? nowMs\n : 0\n transaction.set(\n ledgerRef,\n {\n sellerAccountId,\n entries,\n livemode: signal.livemode,\n updatedAtMs: nowMs,\n ...(fileAtMs ? { lastFiledAtMs: fileAtMs } : {}),\n },\n { merge: true },\n )\n return { first: true, matched, fileAtMs, entries }\n })\n if (!outcome.fileAtMs) {\n return { first: outcome.first, matched: outcome.matched, filed: null }\n }\n\n const { chargeIds } = sellerFraudPattern(outcome.entries, nowMs)\n const inWindow = outcome.entries.filter(\n (entry) => entry.atMs >= nowMs - SELLER_FRAUD_PATTERN.windowMs,\n )\n const reviewId = createHash('sha256')\n .update(`stripe-seller-pattern:${sellerAccountId}:${outcome.fileAtMs}`)\n .digest('hex')\n .slice(0, 40)\n const reference = paymentFraudSignalReference(reviewId)\n const orgId = input.orgIds[0] ?? null\n const hostIds = [...new Set(inWindow.flatMap((entry) => entry.hostIds ?? []))]\n const stripeUrl = stripeConnectedAccountUrl(sellerAccountId, signal.livemode)\n const details = [\n `${chargeIds.length} different charges paid to connected account ${sellerAccountId} drew an issuer fraud warning or a dispute within ${WINDOW_DAYS} days` +\n (signal.livemode ? '' : ' — TEST MODE') +\n '.',\n `Workspace(s): ${input.orgIds.length ? input.orgIds.join(', ') : 'not resolved'}. Site(s): ${hostIds.length ? hostIds.join(', ') : 'not resolved'}.`,\n ...inWindow.map(\n (entry) =>\n `• ${KIND_LABEL[entry.kind]} ${entry.stripeObjectId} on ${entry.chargeId ?? 'an unnamed charge'} · ${formatSignalAmount(entry.amountCents, entry.currency)}` +\n (entry.detail ? ` · ${entry.detail}` : ''),\n ),\n 'A shop taking stolen cards through its own storefront leaves this shape. Each merchant has already been shown the signal on its own order or booking.',\n `Nothing has been refunded, canceled or paused. If this is the seller's fraud, lock the workspace and pause the account's payouts in Stripe (${stripeUrl}), then close this row with what you did.`,\n ]\n .join('\\n')\n .slice(0, 5000)\n await deps.firestore\n .collection(ABUSE_REPORT_COLLECTION)\n .doc(reviewId)\n .set(\n {\n reference,\n // \"Phishing or fraud\" — the queue's urgent fraud category.\n category: 'phishing',\n severity: 'urgent',\n source: 'stripe-seller-fraud-pattern',\n url: null,\n reportedHostname: null,\n hostId: hostIds[0] ?? null,\n orgId,\n details,\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n reportCount: 1,\n sellerPattern: {\n sellerAccountId,\n stripeAccountUrl: stripeUrl,\n chargeIds,\n orgIds: input.orgIds,\n hostIds,\n threshold: SELLER_FRAUD_PATTERN.minDistinctCharges,\n windowDays: WINDOW_DAYS,\n livemode: signal.livemode,\n },\n status: 'open',\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // Staff get the pattern with its numbers; the owners get a plain \"we are\n // reviewing recent payments\" with the way to talk to us, never the count\n // or the window that opened the review.\n await deps\n .notifyRisk({\n kind: 'seller-review',\n orgId,\n hostId: hostIds[0] ?? null,\n reviewId,\n reference,\n item: { label: 'recent card payments on your store', path: '/org/settings/holds' },\n stripeUrl,\n staffEvidence:\n `Connected account ${sellerAccountId} drew fraud warnings or disputes on ` +\n `${chargeIds.length} different charges in ${WINDOW_DAYS} days` +\n (signal.livemode ? '' : ' — TEST MODE') +\n '.',\n })\n .catch(() => undefined)\n return { first: true, matched: true, filed: { reviewId, reference } }\n}\n"],"names":["createHash","ABUSE_REPORT_COLLECTION","RISK_PAYMENT_EVENTS","FieldValue","KIND_LABEL","dispute","PAYMENT_FRAUD_SIGNAL_LABELS","paymentFraudSignalReviewId","kind","stripeObjectId","update","digest","slice","paymentFraudSignalReference","reviewId","toUpperCase","staffSubscriptionCardPath","orgId","encodeURIComponent","stripeSignalDashboardUrl","signal","base","livemode","payment","paymentIntentId","chargeId","formatSignalAmount","amountCents","currency","Number","isFinite","toFixed","String","readStripeChargeForSignal","options","secretKey","charge","card","response","fetchImpl","fetch","headers","Authorization","ok","json","text","value","customerId","checks","cvcCheck","addressPostalCodeCheck","cardCountry","riskLevel","threeDSecure","sellerAccountId","accountRef","id","startsWith","describePaymentFraudSignal","lines","detail","push","join","recordPaymentFraudSignal","deps","reference","ref","firestore","collection","doc","first","get","exists","subscriptionCard","set","category","severity","source","url","reportedHostname","hostId","details","reporterEmail","reporterName","dmca","reportCount","increment","paymentSignal","updatedAt","serverTimestamp","status","createdAt","merge","notifyRisk","item","label","path","amount","paymentEvent","stripeUrl","staffEvidence","catch","undefined","SELLER_FRAUD_PATTERN","minDistinctCharges","windowMs","retainMs","WINDOW_DAYS","SELLER_FRAUD_LEDGER_COLLECTION","sellerFraudPattern","entries","nowMs","since","chargeIds","Set","filter","entry","atMs","map","matched","length","stripeConnectedAccountUrl","accountId","recordSellerFraudSignal","input","hostIds","Date","now","ledgerRef","outcome","runTransaction","transaction","fresh","stored","Array","isArray","some","fileAtMs","lastFiledAtMs","updatedAtMs","filed","inWindow","orgIds","flatMap","sellerPattern","stripeAccountUrl","threshold","windowDays"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,UAAU,QAAQ,2BAA0B;AAgBrD,MAAMC,aAAqD;IACzD,uBAAuB;IACvB,gBAAgB;IAChBC,SAAS;AACX;AAEA,yEAAyE,GACzE,OAAO,MAAMC,8BAA8BF,WAAU;AA4BrD,mEAAmE,GACnE,OAAO,SAASG,2BACdC,IAA4B,EAC5BC,cAAsB;IAEtB,OAAOT,WAAW,UACfU,MAAM,CAAC,CAAC,aAAa,EAAEF,KAAK,CAAC,EAAEC,gBAAgB,EAC/CE,MAAM,CAAC,OACPC,KAAK,CAAC,GAAG;AACd;AAEA,kFAAkF,GAClF,OAAO,SAASC,4BAA4BC,QAAgB;IAC1D,OAAO,CAAC,GAAG,EAAEA,SAASF,KAAK,CAAC,GAAG,IAAIG,WAAW,IAAI;AACp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;QAClBC,MAAM,GAAE6C,YAAAA,OAAO,CAAC,EAAE,YAAVA,YAAc;QACtB5G;QACAgE;QACAC,eAAe;QACfC,cAAc;QACdC,MAAM;QACNC,aAAa;QACb2D,eAAe;YACb1F;YACA2F,kBAAkB9C;YAClBc;YACA6B,QAAQlB,MAAMkB,MAAM;YACpBjB;YACAqB,WAAW3C,qBAAqBC,kBAAkB;YAClD2C,YAAYxC;YACZrF,UAAUF,OAAOE,QAAQ;QAC3B;QACAoE,QAAQ;QACRC,WAAWxF,WAAWsF,eAAe;QACrCD,WAAWrF,WAAWsF,eAAe;IACvC,GACA;QAAEG,OAAO;IAAK;IAElB,yEAAyE;IACzE,yEAAyE;IACzE,wCAAwC;IACxC,MAAM5B,KACH6B,UAAU,CAAC;QACVrF,MAAM;QACNS;QACA+D,MAAM,GAAE6C,aAAAA,OAAO,CAAC,EAAE,YAAVA,aAAc;QACtB/G;QACAmD;QACA6B,MAAM;YAAEC,OAAO;YAAsCC,MAAM;QAAsB;QACjFG;QACAC,eACE,CAAC,kBAAkB,EAAE9C,gBAAgB,oCAAoC,CAAC,GAC1E,GAAG2D,UAAUO,MAAM,CAAC,sBAAsB,EAAEb,YAAY,KAAK,CAAC,GAC7DvF,CAAAA,OAAOE,QAAQ,GAAG,KAAK,cAAa,IACrC;IACJ,GACC+E,KAAK,CAAC,IAAMC;IACf,OAAO;QAAEhC,OAAO;QAAMiD,SAAS;QAAMqB,OAAO;YAAE9H;YAAUmD;QAAU;IAAE;AACtE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/payment-fraud-signal.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 * STRIPE'S FRAUD SIGNALS, INTO THE ABUSE QUEUE (AGL-3356).\n *\n * The 9/26 incident paid for Pro with a card whose CVC check came back\n * unavailable and which never met 3-D Secure. Stripe had three ways to tell\n * us about a card like that — an early fraud warning from the issuer, a\n * Radar review, a dispute — and the platform webhook either did not\n * subscribe to them or filed them where nobody triages abuse.\n *\n * Each signal now files an urgent row in the abuse queue that names the\n * workspace, the charge and the amount, links the staff Subscription card\n * on the org page (AGL-3359, where billing is canceled), and notifies staff\n * once. NOTHING IS DONE TO THE MONEY OR THE SUBSCRIPTION: no refund, no\n * cancel. An early fraud warning is not a chargeback, a review may clear, and\n * a refund issued before staff look can be the wrong half of a dispute. The\n * row is the prompt; staff decide.\n *\n * ONE ROW PER CHARGE (AGL-3490). The three signals are separate Stripe\n * objects about the same payment, and one fraudulent charge routinely draws\n * two of them — a warning and then a dispute, in either order: the issuer's\n * fraud report reached Stripe a day AFTER the 9/26 charge's chargeback had\n * been accepted. Keyed by signal, each one opened its own urgent row and told\n * the owners and staff again. So the row is keyed by the charge, and a later\n * signal joins it: added to `paymentSignals`, never a second row or a second\n * notice. A row staff have closed stays closed — the later signal is written\n * onto it, beside what they decided — with one exception: a DISPUTE on a row\n * staff DISMISSED reopens it and tells them, because the bank now says the\n * cardholder did not make the payment staff judged genuine, and the evidence\n * deadline is running.\n *\n * Dependencies are passed in rather than imported — the Firestore handle the\n * webhook observes its writes through, and its staff notifier — so the\n * webhook's \"did this delivery do anything\" ledger sees the write, and a spec\n * substituting the admin barrel substitutes these too.\n *=========================================*/\n\nimport { createHash } from 'crypto'\nimport { ABUSE_REPORT_COLLECTION } from '@aglyn/aglyn/app-utils/abuse-report'\nimport { RISK_PAYMENT_EVENTS } from '@aglyn/shared-util-email/risk-notice-catalog'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport type { RiskEventInput } from './risk-notice'\n\n/**\n * The seam every signal here tells people through (AGL-3368): the owners\n * and admins of the workspace, and staff. Passed in, like the Firestore\n * handle, so the webhook's spec substitutes it with the barrel.\n */\nexport type RiskNotifier = (input: RiskEventInput) => Promise<unknown>\n\n/** Which Stripe signal this is. */\nexport type PaymentFraudSignalKind =\n | 'early-fraud-warning'\n | 'radar-review'\n | 'dispute'\n\nconst KIND_LABEL: Record<PaymentFraudSignalKind, string> = {\n 'early-fraud-warning': 'Early fraud warning',\n 'radar-review': 'Radar review opened',\n dispute: 'Card dispute opened',\n}\n\n/** The Stripe object type each signal arrives as, for the queue's text. */\nexport const PAYMENT_FRAUD_SIGNAL_LABELS = KIND_LABEL\n\n/** What the card's own checks said, when the charge could be read. */\nexport interface PaymentFraudCardChecks {\n cvcCheck: string | null\n addressPostalCodeCheck: string | null\n cardCountry: string | null\n riskLevel: string | null\n threeDSecure: string | null\n}\n\nexport interface PaymentFraudSignal {\n kind: PaymentFraudSignalKind\n /** The EFW, review or dispute id: one entry per signal, whatever redelivers. */\n stripeObjectId: string\n chargeId: string | null\n paymentIntentId: string | null\n /** The workspace the charge billed, or null when it resolved to none. */\n orgId: string | null\n /** Smallest currency unit, or null when nothing recorded the amount. */\n amountCents: number | null\n currency: string\n /** `fraud_type`, the review's `reason`, the dispute's `reason`. */\n detail: string\n checks: PaymentFraudCardChecks | null\n livemode: boolean\n}\n\n/**\n * The row id: one per CHARGE (AGL-3490), so every signal about one payment\n * lands on the same row. The payment intent stands in for a signal that\n * names no charge, and the signal itself for one that names neither. Hex,\n * so the admin route's id pattern addresses it.\n */\nexport function paymentFraudSignalReviewId(\n signal: Pick<\n PaymentFraudSignal,\n 'kind' | 'stripeObjectId' | 'chargeId' | 'paymentIntentId'\n >,\n): string {\n const payment = signal.chargeId || signal.paymentIntentId\n return createHash('sha256')\n .update(\n payment\n ? `stripe-fraud:payment:${payment}`\n : `stripe-fraud:${signal.kind}:${signal.stripeObjectId}`,\n )\n .digest('hex')\n .slice(0, 40)\n}\n\n/** One signal as the row's history keeps it (AGL-3490). */\nexport interface PaymentFraudSignalEntry {\n kind: PaymentFraudSignalKind\n stripeObjectId: string\n detail: string\n atMs: number\n /**\n * The row's status when this signal arrived, if staff had already closed\n * it — `actioned` or `dismissed` — else null.\n */\n arrivedAfter: string | null\n}\n\n/** The row's history is a short list; a charge draws at most a few signals. */\nconst SIGNAL_HISTORY_MAX = 10\n\n/** The statuses that mean staff have decided the row. */\nconst CLOSED_STATUSES: ReadonlySet<string> = new Set(['actioned', 'dismissed'])\n\n/** The staff-facing reference, beside the intake's `AR-` and the screen's `HS-`. */\nexport function paymentFraudSignalReference(reviewId: string): string {\n return `PF-${reviewId.slice(0, 10).toUpperCase()}`\n}\n\n/** Where staff act on the workspace's billing: its Subscription card. */\nexport function staffSubscriptionCardPath(orgId: string): string {\n return `/admin/orgs/${encodeURIComponent(orgId)}#subscription`\n}\n\n/**\n * The Stripe Dashboard page for a signal: the dispute itself, else the\n * payment it is about.\n */\nexport function stripeSignalDashboardUrl(signal: {\n kind: PaymentFraudSignalKind\n stripeObjectId: string\n chargeId: string | null\n paymentIntentId: string | null\n livemode: boolean\n}): string | null {\n const base = `https://dashboard.stripe.com/${signal.livemode ? '' : 'test/'}`\n if (signal.kind === 'dispute' && signal.stripeObjectId) {\n return `${base}disputes/${encodeURIComponent(signal.stripeObjectId)}`\n }\n const payment = signal.paymentIntentId || signal.chargeId\n return payment ? `${base}payments/${encodeURIComponent(payment)}` : null\n}\n\n/** `$56.00 USD`, or a sentence saying the amount is not known. */\nexport function formatSignalAmount(\n amountCents: number | null,\n currency: string,\n): string {\n if (amountCents === null || !Number.isFinite(amountCents)) {\n return 'amount not recorded'\n }\n return `${(amountCents / 100).toFixed(2)} ${String(currency || 'usd').toUpperCase()}`\n}\n\n/**\n * The one-line summary of a charge Stripe gives back, for a signal whose\n * charge is not on a platform revenue row. A READ — the only Stripe call\n * this module makes — and it answers null rather than throwing, because a\n * fraud alert that fails for want of an amount is worse than one that says\n * the amount is unknown.\n */\nexport async function readStripeChargeForSignal(\n chargeId: string,\n options: { secretKey: string | undefined; fetchImpl?: typeof fetch },\n): Promise<{\n amountCents: number | null\n currency: string\n customerId: string | null\n checks: PaymentFraudCardChecks\n /**\n * The connected account the charge paid (AGL-3360): a destination\n * charge's `transfer_data.destination`. Every sale Aglyn takes for a site\n * is a destination charge on the platform account — the facilitator\n * model (AGL-1956) — so this is the seller. Null for a charge that paid\n * only the platform, a workspace's own subscription.\n */\n sellerAccountId: string | null\n} | null> {\n if (!chargeId || !options.secretKey) return null\n try {\n const response = await (options.fetchImpl ?? fetch)(\n `https://api.stripe.com/v1/charges/${encodeURIComponent(chargeId)}`,\n { headers: { Authorization: `Bearer ${options.secretKey}` } },\n )\n if (!response.ok) return null\n const charge = (await response.json()) as Record<string, any>\n const card = charge?.['payment_method_details']?.['card'] ?? {}\n const text = (value: unknown) =>\n typeof value === 'string' && value ? value : null\n return {\n amountCents: Number.isFinite(Number(charge?.['amount']))\n ? Number(charge['amount'])\n : null,\n currency: String(charge?.['currency'] ?? 'usd'),\n customerId: text(charge?.['customer']),\n checks: {\n cvcCheck: text(card?.['checks']?.['cvc_check']),\n addressPostalCodeCheck: text(card?.['checks']?.['address_postal_code_check']),\n cardCountry: text(card?.['country']),\n riskLevel: text(charge?.['outcome']?.['risk_level']),\n threeDSecure: text(card?.['three_d_secure']?.['result']),\n },\n sellerAccountId: accountRef(charge?.['transfer_data']?.['destination']),\n }\n } catch {\n return null\n }\n}\n\n/** A Stripe account reference, expanded or not, as an id or null. */\nfunction accountRef(value: unknown): string | null {\n const id =\n typeof value === 'string'\n ? value\n : String((value as { id?: unknown } | null)?.id ?? '')\n return id.startsWith('acct_') ? id : null\n}\n\n/**\n * The row's prose: what arrived, about which workspace, and what to do.\n *\n * `history` is every signal on the charge, this one last; `closed` is what\n * staff had decided before it arrived, if anything. The closing line says\n * what THIS ALERT did — nothing to the money or the subscription — and\n * never claims nothing was done at all: by the time a late warning lands,\n * staff may have canceled, locked and accepted the chargeback (AGL-3490).\n */\nexport function describePaymentFraudSignal(\n signal: PaymentFraudSignal,\n context: {\n history?: readonly PaymentFraudSignalEntry[]\n closed?: { status: string; resolution: string | null } | null\n reopened?: boolean\n } = {},\n): string {\n const lines = [\n `${KIND_LABEL[signal.kind]} from Stripe (${signal.stripeObjectId})` +\n (signal.livemode ? '' : ' — TEST MODE') +\n '.',\n `Workspace: ${signal.orgId ?? 'none — the charge did not resolve to a workspace subscription'}.`,\n `Charge: ${signal.chargeId ?? signal.paymentIntentId ?? 'not named'} · ${formatSignalAmount(signal.amountCents, signal.currency)}.`,\n ]\n if (signal.detail) lines.push(`Stripe says: ${signal.detail}.`)\n const checks = signal.checks\n if (checks) {\n lines.push(\n `Card: CVC ${checks.cvcCheck ?? 'unknown'}, postal code ${checks.addressPostalCodeCheck ?? 'unknown'}, ` +\n `issued in ${checks.cardCountry ?? 'unknown'}, 3DS ${checks.threeDSecure ?? 'not used'}, ` +\n `Radar risk ${checks.riskLevel ?? 'unknown'}.`,\n )\n }\n const history = context.history ?? []\n if (history.length > 1) {\n lines.push(\n `Every signal on this charge, oldest first: ${history\n .map(\n (entry) =>\n `${KIND_LABEL[entry.kind]} (${entry.stripeObjectId}` +\n (entry.arrivedAfter ? `, after the row was ${entry.arrivedAfter}` : '') +\n ')',\n )\n .join('; ')}.`,\n )\n }\n const resolution = context.closed?.resolution\n ? `: “${context.closed.resolution}”`\n : '.'\n if (context.reopened && context.closed) {\n lines.push(\n `REOPENED. Staff had dismissed this row${resolution} The cardholder’s bank has now disputed the payment. Answer or accept the dispute in Stripe before its evidence deadline, then close this row again with what you did.`,\n )\n } else if (context.closed) {\n lines.push(\n `This signal arrived after the row was closed as ${context.closed.status}${resolution} The row stays closed and nobody was notified again. Reopen it only if that decision no longer holds.`,\n )\n } else {\n lines.push(\n signal.kind === 'radar-review'\n ? 'The payment waits in Stripe until the review is closed there.'\n : signal.kind === 'dispute'\n ? 'Answer the dispute in Stripe before its evidence deadline.'\n : 'An early fraud warning is not yet a chargeback; refunding now can avoid one.',\n 'This alert refunded and canceled nothing. Decide on the org’s Subscription card, lock the workspace if it is fraud, and close this row with what you did.',\n )\n }\n return lines.join('\\n').slice(0, 5000)\n}\n\n/** The history a stored row carries, oldest first. */\nfunction signalHistoryOf(\n row: Record<string, unknown> | null,\n fallbackAtMs: number,\n): PaymentFraudSignalEntry[] {\n if (!row) return []\n const kinds = Object.keys(KIND_LABEL)\n const stored = Array.isArray(row['paymentSignals']) ? row['paymentSignals'] : []\n const entries = stored.flatMap((value): PaymentFraudSignalEntry[] => {\n const entry = (value ?? {}) as Record<string, unknown>\n const kind = String(entry['kind'] ?? '')\n const stripeObjectId = String(entry['stripeObjectId'] ?? '')\n if (!kinds.includes(kind) || !stripeObjectId) return []\n return [\n {\n kind: kind as PaymentFraudSignalKind,\n stripeObjectId,\n detail: String(entry['detail'] ?? ''),\n atMs: Number(entry['atMs']) || 0,\n arrivedAfter:\n typeof entry['arrivedAfter'] === 'string' ? entry['arrivedAfter'] : null,\n },\n ]\n })\n if (entries.length) return entries\n // A row filed before the history existed carries its one signal as\n // `paymentSignal`, which is where a redelivery of it is recognised.\n const only = (row['paymentSignal'] ?? null) as Record<string, unknown> | null\n const kind = String(only?.['kind'] ?? '')\n const stripeObjectId = String(only?.['stripeObjectId'] ?? '')\n return kinds.includes(kind) && stripeObjectId\n ? [\n {\n kind: kind as PaymentFraudSignalKind,\n stripeObjectId,\n detail: String(only?.['detail'] ?? ''),\n atMs: fallbackAtMs,\n arrivedAfter: null,\n },\n ]\n : []\n}\n\n/**\n * File one signal on its charge's row, and tell the owners and staff once\n * per charge (AGL-3490).\n *\n * The first signal on a charge opens the row. A later one — a different\n * Stripe object about the same payment — is added to `paymentSignals`, and\n * `paymentSignal` becomes it, so the row's Stripe link follows a dispute.\n * The status is staff's from the moment they touch it and is left alone,\n * except that a dispute on a DISMISSED row reopens it and notifies again. A\n * redelivery of a signal already on the row adds nothing. Read and written\n * in one transaction, so a warning and a dispute arriving together still\n * make one row. Throws only if the row write throws, which is the webhook's\n * to answer; the notification never throws.\n */\nexport async function recordPaymentFraudSignal(\n signal: PaymentFraudSignal,\n deps: {\n firestore: FirebaseFirestore.Firestore\n notifyRisk: RiskNotifier\n nowMs?: number\n },\n): Promise<{\n reviewId: string\n reference: string\n first: boolean\n reopened: boolean\n}> {\n const reviewId = paymentFraudSignalReviewId(signal)\n const reference = paymentFraudSignalReference(reviewId)\n const ref = deps.firestore.collection(ABUSE_REPORT_COLLECTION).doc(reviewId)\n const atMs = deps.nowMs ?? Date.now()\n const { first, reopened } = await deps.firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(ref)\n const existing = snapshot.exists\n ? ((snapshot.data() ?? {}) as Record<string, unknown>)\n : null\n const history = signalHistoryOf(existing, atMs)\n if (\n existing &&\n history.some((entry) => entry.stripeObjectId === signal.stripeObjectId)\n ) {\n transaction.set(\n ref,\n { updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n return { first: false, reopened: false }\n }\n const status = existing ? String(existing['status'] ?? 'open') : 'open'\n const wasClosed = CLOSED_STATUSES.has(status)\n const reopen = status === 'dismissed' && signal.kind === 'dispute'\n const resolution =\n typeof existing?.['resolution'] === 'string' &&\n existing['resolution'].trim()\n ? existing['resolution'].trim()\n : null\n const nextHistory = [\n ...history,\n {\n kind: signal.kind,\n stripeObjectId: signal.stripeObjectId,\n detail: signal.detail,\n atMs,\n arrivedAfter: wasClosed ? status : null,\n },\n ].slice(-SIGNAL_HISTORY_MAX)\n // A later signal whose charge read failed keeps what the first one\n // learned rather than erasing it.\n const previous = (existing?.['paymentSignal'] ?? null) as Record<\n string,\n unknown\n > | null\n const orgId =\n signal.orgId ??\n (typeof existing?.['orgId'] === 'string' ? existing['orgId'] : null)\n const merged: PaymentFraudSignal = {\n ...signal,\n orgId,\n amountCents:\n signal.amountCents ??\n (typeof previous?.['amountCents'] === 'number'\n ? previous['amountCents']\n : null),\n checks:\n signal.checks ??\n ((previous?.['checks'] ?? null) as PaymentFraudCardChecks | null),\n }\n transaction.set(\n ref,\n {\n reference,\n // \"Phishing or fraud\" — the queue's urgent fraud category.\n category: 'phishing',\n severity: 'urgent',\n source: 'stripe-fraud-signal',\n url: null,\n reportedHostname: null,\n hostId: null,\n orgId,\n details: describePaymentFraudSignal(merged, {\n history: nextHistory,\n closed: wasClosed ? { status, resolution } : null,\n reopened: reopen,\n }),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n reportCount: nextHistory.length,\n paymentSignals: nextHistory,\n paymentSignal: {\n kind: merged.kind,\n stripeObjectId: merged.stripeObjectId,\n chargeId: merged.chargeId,\n paymentIntentId: merged.paymentIntentId,\n amountCents: merged.amountCents,\n currency: merged.currency,\n detail: merged.detail,\n checks: merged.checks,\n livemode: merged.livemode,\n subscriptionCard: orgId ? staffSubscriptionCardPath(orgId) : null,\n },\n updatedAt: FieldValue.serverTimestamp(),\n ...(existing\n ? {}\n : { status: 'open', createdAt: FieldValue.serverTimestamp() }),\n ...(reopen\n ? {\n status: 'open',\n reopenedAt: FieldValue.serverTimestamp(),\n resolvedAt: null,\n }\n : {}),\n },\n { merge: true },\n )\n return { first: !existing, reopened: reopen }\n },\n )\n if (first || reopened) {\n // The workspace's owners are told their subscription payment was\n // flagged and how to confirm it; staff get the row with the evidence.\n await deps\n .notifyRisk({\n kind: 'billing-payment-flagged',\n orgId: signal.orgId,\n reviewId,\n reference,\n item: { label: 'your subscription payment', path: '/org/billing/invoices' },\n amount: formatSignalAmount(signal.amountCents, signal.currency),\n // A dispute is the bank's, already opened; a warning or a review is\n // a fraud check. The notice says which.\n paymentEvent: RISK_PAYMENT_EVENTS[signal.kind] ?? null,\n stripeUrl: stripeSignalDashboardUrl(signal),\n staffEvidence:\n `${KIND_LABEL[signal.kind]} (${signal.stripeObjectId}) on charge ` +\n `${signal.chargeId ?? signal.paymentIntentId ?? 'not named'}` +\n (signal.detail ? `; Stripe says: ${signal.detail}` : '') +\n (signal.livemode ? '' : ' — TEST MODE') +\n (reopened ? '; reopened a row staff had dismissed' : '') +\n '.',\n })\n .catch(() => undefined)\n }\n return { reviewId, reference, first, reopened }\n}\n\n/*==========================================\n * THE SELLER PATTERN: WHEN THE MERCHANT MAY BE THE FRAUDSTER (AGL-3360).\n *\n * A site's own sales are destination charges on the platform account, so\n * Stripe's fraud signals about a shopper's card arrive here too. One of them\n * is the merchant's business — their customer, their order, their decision\n * (`payment-risk-record.ts` puts it on the record and tells them). Staff are\n * not paged for it.\n *\n * What IS staff's business is the shape a phishing actor leaves when they\n * run stolen cards through a storefront of their own: several different\n * charges on ONE connected account drawing issuer fraud reports or\n * chargebacks in a short time. So every signal on a seller's charge is kept\n * in a small per-account ledger, and one urgent abuse-queue row is filed when\n *\n * ≥ 3 DISTINCT charges carry an early fraud warning or a dispute\n * within 7 days.\n *\n * Why those numbers. An early fraud warning is an issuer's report that the\n * cardholder did not make the payment, and a dispute is a formal\n * chargeback; a legitimate small merchant sees either rarely — card-network\n * dispute monitoring starts near 0.9% of a month's transactions, single\n * digits a MONTH for a shop doing hundreds of sales. One or two in a week is\n * ordinary friendly fraud and must never page staff. Three separate charges\n * in one week is a rate a real small shop does not produce, and is what a\n * card tester or a stolen-card storefront produces within days. Counted by\n * CHARGE, because a warning is routinely followed by a dispute on the same\n * payment, and that is one bad payment, not two. Radar reviews are kept in\n * the ledger for the row's prose but never counted: a review is Stripe's\n * suspicion, not an issuer's report, and a busy shop can collect several\n * that clear.\n *\n * One row per window: once filed, the account is not filed again until 7\n * days have passed, so a burst is one row with everything in it rather than\n * a row per signal. NOTHING IS DONE TO THE ACCOUNT OR THE MONEY: staff\n * decide (lock the workspace, pause the account's payouts in Stripe).\n *=========================================*/\n\nexport const SELLER_FRAUD_PATTERN = {\n /** Distinct charges with an early fraud warning or a dispute. */\n minDistinctCharges: 3,\n /** …within this window. */\n windowMs: 7 * 24 * 60 * 60 * 1000,\n /** How long the ledger keeps an entry at all. */\n retainMs: 30 * 24 * 60 * 60 * 1000,\n} as const\n\nconst WINDOW_DAYS = SELLER_FRAUD_PATTERN.windowMs / 86_400_000\n\n/** Admin-SDK only; no client rule opens it (default deny). */\nexport const SELLER_FRAUD_LEDGER_COLLECTION = 'paymentFraudLedger'\n\nexport interface SellerFraudLedgerEntry {\n kind: PaymentFraudSignalKind\n stripeObjectId: string\n chargeId: string | null\n amountCents: number | null\n currency: string\n detail: string\n /** The sites a plugin recognised the charge as belonging to. */\n hostIds: string[]\n atMs: number\n}\n\n/** Whether a seller's ledger shows the pattern at `nowMs`. Pure. */\nexport function sellerFraudPattern(\n entries: readonly SellerFraudLedgerEntry[],\n nowMs: number,\n): { matched: boolean; chargeIds: string[] } {\n const since = nowMs - SELLER_FRAUD_PATTERN.windowMs\n const chargeIds = [\n ...new Set(\n entries\n .filter(\n (entry) =>\n (entry.kind === 'early-fraud-warning' || entry.kind === 'dispute') &&\n entry.atMs >= since,\n )\n .map((entry) => entry.chargeId || entry.stripeObjectId),\n ),\n ]\n return {\n matched: chargeIds.length >= SELLER_FRAUD_PATTERN.minDistinctCharges,\n chargeIds,\n }\n}\n\n/** The connected account's page in the Stripe Dashboard. */\nexport function stripeConnectedAccountUrl(\n accountId: string,\n livemode: boolean,\n): string {\n return `https://dashboard.stripe.com/${livemode ? '' : 'test/'}connect/accounts/${encodeURIComponent(accountId)}`\n}\n\n/**\n * Keep one signal on a seller's charge, and file the pattern row when the\n * ledger crosses the threshold. Idempotent on the Stripe object id: a\n * redelivery changes nothing and files nothing.\n */\nexport async function recordSellerFraudSignal(\n input: {\n signal: PaymentFraudSignal\n sellerAccountId: string\n /** The sites a plugin recognised the charge as belonging to. */\n hostIds: string[]\n /** Workspaces owning those sites, for the row. */\n orgIds: string[]\n },\n deps: {\n firestore: FirebaseFirestore.Firestore\n notifyRisk: RiskNotifier\n nowMs?: number\n },\n): Promise<{\n first: boolean\n matched: boolean\n filed: { reviewId: string; reference: string } | null\n}> {\n const nowMs = deps.nowMs ?? Date.now()\n const { signal, sellerAccountId } = input\n const ledgerRef = deps.firestore\n .collection(SELLER_FRAUD_LEDGER_COLLECTION)\n .doc(sellerAccountId)\n const outcome = await deps.firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(ledgerRef)\n const stored = (\n Array.isArray(fresh.get('entries')) ? fresh.get('entries') : []\n ) as SellerFraudLedgerEntry[]\n if (stored.some((entry) => entry.stripeObjectId === signal.stripeObjectId)) {\n return { first: false, matched: false, fileAtMs: 0, entries: stored }\n }\n const entries: SellerFraudLedgerEntry[] = [\n ...stored.filter(\n (entry) => entry.atMs >= nowMs - SELLER_FRAUD_PATTERN.retainMs,\n ),\n {\n kind: signal.kind,\n stripeObjectId: signal.stripeObjectId,\n chargeId: signal.chargeId,\n amountCents: signal.amountCents,\n currency: signal.currency,\n detail: signal.detail,\n hostIds: input.hostIds,\n atMs: nowMs,\n },\n ]\n const { matched } = sellerFraudPattern(entries, nowMs)\n const lastFiledAtMs = Number(fresh.get('lastFiledAtMs') ?? 0)\n const fileAtMs =\n matched &&\n !(lastFiledAtMs && nowMs - lastFiledAtMs < SELLER_FRAUD_PATTERN.windowMs)\n ? nowMs\n : 0\n transaction.set(\n ledgerRef,\n {\n sellerAccountId,\n entries,\n livemode: signal.livemode,\n updatedAtMs: nowMs,\n ...(fileAtMs ? { lastFiledAtMs: fileAtMs } : {}),\n },\n { merge: true },\n )\n return { first: true, matched, fileAtMs, entries }\n })\n if (!outcome.fileAtMs) {\n return { first: outcome.first, matched: outcome.matched, filed: null }\n }\n\n const { chargeIds } = sellerFraudPattern(outcome.entries, nowMs)\n const inWindow = outcome.entries.filter(\n (entry) => entry.atMs >= nowMs - SELLER_FRAUD_PATTERN.windowMs,\n )\n const reviewId = createHash('sha256')\n .update(`stripe-seller-pattern:${sellerAccountId}:${outcome.fileAtMs}`)\n .digest('hex')\n .slice(0, 40)\n const reference = paymentFraudSignalReference(reviewId)\n const orgId = input.orgIds[0] ?? null\n const hostIds = [...new Set(inWindow.flatMap((entry) => entry.hostIds ?? []))]\n const stripeUrl = stripeConnectedAccountUrl(sellerAccountId, signal.livemode)\n const details = [\n `${chargeIds.length} different charges paid to connected account ${sellerAccountId} drew an issuer fraud warning or a dispute within ${WINDOW_DAYS} days` +\n (signal.livemode ? '' : ' — TEST MODE') +\n '.',\n `Workspace(s): ${input.orgIds.length ? input.orgIds.join(', ') : 'not resolved'}. Site(s): ${hostIds.length ? hostIds.join(', ') : 'not resolved'}.`,\n ...inWindow.map(\n (entry) =>\n `• ${KIND_LABEL[entry.kind]} ${entry.stripeObjectId} on ${entry.chargeId ?? 'an unnamed charge'} · ${formatSignalAmount(entry.amountCents, entry.currency)}` +\n (entry.detail ? ` · ${entry.detail}` : ''),\n ),\n 'A shop taking stolen cards through its own storefront leaves this shape. Each merchant has already been shown the signal on its own order or booking.',\n `Nothing has been refunded, canceled or paused. If this is the seller's fraud, lock the workspace and pause the account's payouts in Stripe (${stripeUrl}), then close this row with what you did.`,\n ]\n .join('\\n')\n .slice(0, 5000)\n await deps.firestore\n .collection(ABUSE_REPORT_COLLECTION)\n .doc(reviewId)\n .set(\n {\n reference,\n // \"Phishing or fraud\" — the queue's urgent fraud category.\n category: 'phishing',\n severity: 'urgent',\n source: 'stripe-seller-fraud-pattern',\n url: null,\n reportedHostname: null,\n hostId: hostIds[0] ?? null,\n orgId,\n details,\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n reportCount: 1,\n sellerPattern: {\n sellerAccountId,\n stripeAccountUrl: stripeUrl,\n chargeIds,\n orgIds: input.orgIds,\n hostIds,\n threshold: SELLER_FRAUD_PATTERN.minDistinctCharges,\n windowDays: WINDOW_DAYS,\n livemode: signal.livemode,\n },\n status: 'open',\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // Staff get the pattern with its numbers; the owners get a plain \"we are\n // reviewing recent payments\" with the way to talk to us, never the count\n // or the window that opened the review.\n await deps\n .notifyRisk({\n kind: 'seller-review',\n orgId,\n hostId: hostIds[0] ?? null,\n reviewId,\n reference,\n item: { label: 'recent card payments on your store', path: '/org/settings/holds' },\n stripeUrl,\n staffEvidence:\n `Connected account ${sellerAccountId} drew fraud warnings or disputes on ` +\n `${chargeIds.length} different charges in ${WINDOW_DAYS} days` +\n (signal.livemode ? '' : ' — TEST MODE') +\n '.',\n })\n .catch(() => undefined)\n return { first: true, matched: true, filed: { reviewId, reference } }\n}\n"],"names":["createHash","ABUSE_REPORT_COLLECTION","RISK_PAYMENT_EVENTS","FieldValue","KIND_LABEL","dispute","PAYMENT_FRAUD_SIGNAL_LABELS","paymentFraudSignalReviewId","signal","payment","chargeId","paymentIntentId","update","kind","stripeObjectId","digest","slice","SIGNAL_HISTORY_MAX","CLOSED_STATUSES","Set","paymentFraudSignalReference","reviewId","toUpperCase","staffSubscriptionCardPath","orgId","encodeURIComponent","stripeSignalDashboardUrl","base","livemode","formatSignalAmount","amountCents","currency","Number","isFinite","toFixed","String","readStripeChargeForSignal","options","secretKey","charge","card","response","fetchImpl","fetch","headers","Authorization","ok","json","text","value","customerId","checks","cvcCheck","addressPostalCodeCheck","cardCountry","riskLevel","threeDSecure","sellerAccountId","accountRef","id","startsWith","describePaymentFraudSignal","context","lines","detail","push","history","length","map","entry","arrivedAfter","join","resolution","closed","reopened","status","signalHistoryOf","row","fallbackAtMs","kinds","Object","keys","stored","Array","isArray","entries","flatMap","includes","atMs","only","recordPaymentFraudSignal","deps","reference","ref","firestore","collection","doc","nowMs","Date","now","first","runTransaction","transaction","snapshot","existing","get","exists","data","some","set","updatedAt","serverTimestamp","merge","wasClosed","has","reopen","trim","nextHistory","previous","merged","category","severity","source","url","reportedHostname","hostId","details","reporterEmail","reporterName","dmca","reportCount","paymentSignals","paymentSignal","subscriptionCard","createdAt","reopenedAt","resolvedAt","notifyRisk","item","label","path","amount","paymentEvent","stripeUrl","staffEvidence","catch","undefined","SELLER_FRAUD_PATTERN","minDistinctCharges","windowMs","retainMs","WINDOW_DAYS","SELLER_FRAUD_LEDGER_COLLECTION","sellerFraudPattern","since","chargeIds","filter","matched","stripeConnectedAccountUrl","accountId","recordSellerFraudSignal","input","hostIds","ledgerRef","outcome","fresh","fileAtMs","lastFiledAtMs","updatedAtMs","filed","inWindow","orgIds","sellerPattern","stripeAccountUrl","threshold","windowDays"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAkC2C,GAE3C,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,UAAU,QAAQ,2BAA0B;AAgBrD,MAAMC,aAAqD;IACzD,uBAAuB;IACvB,gBAAgB;IAChBC,SAAS;AACX;AAEA,yEAAyE,GACzE,OAAO,MAAMC,8BAA8BF,WAAU;AA4BrD;;;;;CAKC,GACD,OAAO,SAASG,2BACdC,MAGC;IAED,MAAMC,UAAUD,OAAOE,QAAQ,IAAIF,OAAOG,eAAe;IACzD,OAAOX,WAAW,UACfY,MAAM,CACLH,UACI,CAAC,qBAAqB,EAAEA,SAAS,GACjC,CAAC,aAAa,EAAED,OAAOK,IAAI,CAAC,CAAC,EAAEL,OAAOM,cAAc,EAAE,EAE3DC,MAAM,CAAC,OACPC,KAAK,CAAC,GAAG;AACd;AAeA,6EAA6E,GAC7E,MAAMC,qBAAqB;AAE3B,uDAAuD,GACvD,MAAMC,kBAAuC,IAAIC,IAAI;IAAC;IAAY;CAAY;AAE9E,kFAAkF,GAClF,OAAO,SAASC,4BAA4BC,QAAgB;IAC1D,OAAO,CAAC,GAAG,EAAEA,SAASL,KAAK,CAAC,GAAG,IAAIM,WAAW,IAAI;AACpD;AAEA,uEAAuE,GACvE,OAAO,SAASC,0BAA0BC,KAAa;IACrD,OAAO,CAAC,YAAY,EAAEC,mBAAmBD,OAAO,aAAa,CAAC;AAChE;AAEA;;;CAGC,GACD,OAAO,SAASE,yBAAyBlB,MAMxC;IACC,MAAMmB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