thumbgate 1.39.1 → 1.40.2

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 (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -13,6 +13,7 @@ function withTimeout(promise, ms = STRIPE_TIMEOUT_MS) {
13
13
  });
14
14
  }
15
15
 
16
+ const { withoutDataScope } = require('./feedback-scope');
16
17
  const fs = require('fs');
17
18
  const path = require('path');
18
19
  const crypto = require('crypto');
@@ -30,6 +31,7 @@ const {
30
31
  resolveFallbackArtifactPath,
31
32
  } = require('./feedback-paths');
32
33
  const { getTelemetryAnalytics, getTelemetrySourceDiagnostics } = require('./telemetry-analytics');
34
+ const { getOwnerEmails } = require('./bot-detection');
33
35
  const { normalizeCampaignId } = require('./growth-campaigns');
34
36
  const {
35
37
  PRO_MONTHLY_PRICE_ID,
@@ -78,7 +80,7 @@ const CONFIG = {
78
80
  STRIPE_PRICE_ID_TEAM_MONTHLY: process.env.STRIPE_PRICE_ID_TEAM_MONTHLY || TEAM_MONTHLY_PRICE_ID,
79
81
  STRIPE_PRODUCT_ID: process.env.STRIPE_PRODUCT_ID || '',
80
82
  get API_KEYS_PATH() {
81
- return process.env._TEST_API_KEYS_PATH || path.join(getFeedbackPaths().FEEDBACK_DIR, 'api-keys.json');
83
+ return process.env._TEST_API_KEYS_PATH || withoutDataScope(() => path.join(getFeedbackPaths().FEEDBACK_DIR, 'api-keys.json'));
82
84
  },
83
85
  get FUNNEL_LEDGER_PATH() {
84
86
  return process.env._TEST_FUNNEL_LEDGER_PATH || process.env.THUMBGATE_FUNNEL_LEDGER_PATH || path.join(getFeedbackPaths().FEEDBACK_DIR, 'funnel-events.jsonl');
@@ -111,7 +113,22 @@ const CONFIG = {
111
113
  RESEND_API_KEY: process.env.RESEND_API_KEY || process.env.THUMBGATE_RESEND_API_KEY || '',
112
114
  TRIAL_EMAIL_FROM: process.env.THUMBGATE_TRIAL_EMAIL_FROM || process.env.RESEND_FROM_EMAIL || process.env.RESEND_FROM || 'onboarding@resend.dev',
113
115
  TRIAL_EMAIL_REPLY_TO: process.env.THUMBGATE_TRIAL_EMAIL_REPLY_TO || 'support@thumbgate.ai',
114
- CREDIT_PACKS: {}
116
+ CREDIT_PACKS: {
117
+ bundle_49: {
118
+ id: 'bundle_49',
119
+ name: 'Corporate-Expense Reliability Kit',
120
+ currency: 'USD',
121
+ amountCents: 4900,
122
+ credits: 10000,
123
+ },
124
+ playbook_999: {
125
+ id: 'playbook_999',
126
+ name: 'Agent Safeguards Playbook',
127
+ currency: 'USD',
128
+ amountCents: 999,
129
+ credits: 1000,
130
+ },
131
+ }
115
132
  };
116
133
 
117
134
  const DEFAULT_DIAGNOSTIC_PAYMENT_LINK_ID = 'plink_1TsO6lGGBpd520QYsFToXuRC';
@@ -205,21 +222,36 @@ function appendJsonlRecord(filePath, payload) {
205
222
  }
206
223
  }
207
224
 
225
+ function resolveJsonlReadPaths(filePath, legacyPath = null) {
226
+ const primaryExists = Boolean(filePath && fs.existsSync(filePath));
227
+ const legacyExists = Boolean(legacyPath && legacyPath !== filePath && fs.existsSync(legacyPath));
228
+ if (primaryExists) return [filePath, ...(legacyExists && shouldMergeLegacyBillingData() ? [legacyPath] : [])];
229
+ return legacyExists ? [legacyPath] : [];
230
+ }
231
+
232
+ function resolveKeyStoreReadPath() {
233
+ return IS_TEST || fs.existsSync(CONFIG.API_KEYS_PATH) ? CONFIG.API_KEYS_PATH : resolveLegacyBillingPath('api-keys.json');
234
+ }
235
+
236
+ function getBillingAnalyticsReadPaths() {
237
+ const root = getFeedbackPaths().FEEDBACK_DIR;
238
+ const ledgers = [
239
+ [CONFIG.FUNNEL_LEDGER_PATH, 'funnel-events.jsonl'],
240
+ [CONFIG.REVENUE_LEDGER_PATH, 'revenue-events.jsonl'],
241
+ [CONFIG.NEWSLETTER_SUBSCRIBERS_PATH, 'newsletter-subscribers.jsonl'],
242
+ [CONFIG.TRIAL_EMAIL_LEDGER_PATH, 'trial-emails.jsonl'],
243
+ ];
244
+ return [...new Set([
245
+ ...ledgers.flatMap(([primary, file]) => resolveJsonlReadPaths(primary, resolveLegacyBillingPath(file))),
246
+ resolveKeyStoreReadPath(),
247
+ ...getTelemetrySourceDiagnostics(root).activePaths,
248
+ ...['auth-sessions.json', 'cloud-sso-sessions.json', 'workflow-sprint-leads.jsonl'].map((file) => path.join(root, file)),
249
+ ])];
250
+ }
251
+
208
252
  function loadJsonlRecords(filePath, legacyPath = null) {
209
253
  try {
210
- const paths = [];
211
- const primaryExists = Boolean(filePath && fs.existsSync(filePath));
212
- const legacyExists = Boolean(legacyPath && legacyPath !== filePath && fs.existsSync(legacyPath));
213
-
214
- if (primaryExists) {
215
- paths.push(filePath);
216
- if (legacyExists && shouldMergeLegacyBillingData()) {
217
- paths.push(legacyPath);
218
- }
219
- } else if (legacyExists) {
220
- paths.push(legacyPath);
221
- }
222
-
254
+ const paths = resolveJsonlReadPaths(filePath, legacyPath);
223
255
  const merged = [];
224
256
  const seen = new Set();
225
257
 
@@ -438,7 +470,6 @@ function resolveCheckoutBrandUrls(appOrigin) {
438
470
  };
439
471
  }
440
472
 
441
- // Resolve the per-tier product image used by Stripe Checkout.
442
473
  function resolveTierIconUrl(planId, appOrigin) {
443
474
  const brandUrls = resolveCheckoutBrandUrls(appOrigin);
444
475
  const normalized = typeof planId === 'string' ? planId.toLowerCase() : '';
@@ -513,7 +544,9 @@ function buildSubscriptionPriceData(checkoutSelection, appOrigin) {
513
544
  name: isTeam ? 'ThumbGate Team' : 'ThumbGate Pro',
514
545
  description: isTeam
515
546
  ? 'Shared Pre-Action Checks, team governance, and workflow hardening for AI coding agents.'
516
- : 'Local dashboard, DPO export, and Pre-Action Checks for AI coding agents.',
547
+ : annual
548
+ ? 'Annual Pro (save $79/yr): unlimited learned gates, multi-hop recall, visual debugger, DPO export, and instant Pro API key. 7-day refund.'
549
+ : 'Unlimited learned gates (removes 3-rule free cap), multi-hop recall, visual debugger, DPO export, and instant Pro API key. Cancel anytime · 7-day refund.',
517
550
  appOrigin,
518
551
  planId: isTeam ? 'team' : 'pro',
519
552
  }),
@@ -721,7 +754,8 @@ async function sendTrialActivationEmail(params = {}, options = {}) {
721
754
  : null;
722
755
  const transport = options.transport || sendResendEmail;
723
756
  const planId = normalizeText(params.planId);
724
- const idempotencyKey = `trial-${crypto.createHash('sha256').update(`${sessionId}:${customerEmail}`).digest('hex')}`;
757
+ const sessionDigestInput = `${sessionId}:${customerEmail}`;
758
+ const idempotencyKey = `trial-${crypto.createHash('sha256').update(sessionDigestInput).digest('hex')}`;
725
759
 
726
760
  if (!customerEmail) {
727
761
  return { status: 'skipped', reason: 'missing_customer_email' };
@@ -869,7 +903,7 @@ function isDiagnosticCheckoutSession(session = {}) {
869
903
  .filter((value) => /^plink_[A-Za-z0-9]+$/.test(value));
870
904
  const paymentLinkId = typeof session.payment_link === 'string'
871
905
  ? session.payment_link
872
- : normalizeText(session.payment_link && session.payment_link.id);
906
+ : normalizeText(session.payment_link?.id);
873
907
  return session.mode === 'payment'
874
908
  && configuredIds.includes(paymentLinkId);
875
909
  }
@@ -882,12 +916,18 @@ function resolveCheckoutProvisioningGrant(session = {}) {
882
916
  return { allowed: false, kind: 'unknown', credits: null };
883
917
  }
884
918
 
885
- const packId = normalizeText(session.metadata && session.metadata.packId);
886
- const configuredPack = packId && CONFIG.CREDIT_PACKS[packId];
887
- const credits = normalizeInteger(session.metadata && session.metadata.credits);
888
- if (configuredPack && credits === configuredPack.credits) {
919
+ const packId = normalizeText(session.metadata?.packId);
920
+ const configuredPack = packId ? CONFIG.CREDIT_PACKS[packId] : null;
921
+ const credits = normalizeInteger(session.metadata?.credits);
922
+ if (configuredPack?.credits !== undefined && credits === configuredPack.credits) {
889
923
  return { allowed: true, kind: 'credit_pack', credits };
890
924
  }
925
+ if (session.payment_link === 'plink_1UYSOcGGBpd520QY6NK9tcnJ') {
926
+ return { allowed: true, kind: 'credit_pack', credits: 10000 };
927
+ }
928
+ if (session.payment_link === 'plink_1UYSOZGGBpd520QYsB3S18JB') {
929
+ return { allowed: true, kind: 'credit_pack', credits: 1000 };
930
+ }
891
931
  return { allowed: false, kind: 'service_order', credits: null };
892
932
  }
893
933
 
@@ -913,8 +953,7 @@ function findOrderEmailRecord({ sessionId, kind } = {}) {
913
953
  const normalizedKind = normalizeText(kind);
914
954
  if (!normalizedSessionId || !normalizedKind) return null;
915
955
  return loadJsonlRecords(CONFIG.ORDER_EMAIL_LEDGER_PATH).find((row) => (
916
- row
917
- && row.sessionId === normalizedSessionId
956
+ row?.sessionId === normalizedSessionId
918
957
  && row.kind === normalizedKind
919
958
  && row.status === 'sent'
920
959
  )) || null;
@@ -1230,6 +1269,101 @@ function resolveAcquisitionLeadKey(entry = {}) {
1230
1269
  );
1231
1270
  }
1232
1271
 
1272
+ const EMAIL_ACCOUNT_FIXTURE_DOMAINS = new Set([
1273
+ 'example.com',
1274
+ 'example.org',
1275
+ 'example.net',
1276
+ 'test.com',
1277
+ 'acmedev.io',
1278
+ 'mailinator.com',
1279
+ 'invalid',
1280
+ 'localhost',
1281
+ ]);
1282
+
1283
+ function ownerEmailSet() {
1284
+ return new Set([
1285
+ ...getOwnerEmails(),
1286
+ 'iganapolsky@gmail.com',
1287
+ 'igor.ganapolsky@gmail.com',
1288
+ 'igor@igorganapolsky.com',
1289
+ 'igor@thumbgate.ai',
1290
+ ].map((entry) => String(entry || '').trim().toLowerCase()).filter(Boolean));
1291
+ }
1292
+
1293
+ function isFixtureEmailAccount(email) {
1294
+ const at = email.lastIndexOf('@');
1295
+ const local = email.slice(0, at);
1296
+ const domain = email.slice(at + 1);
1297
+ if (EMAIL_ACCOUNT_FIXTURE_DOMAINS.has(domain) || domain.endsWith('.test') || domain.endsWith('.local') || domain.endsWith('.example.com')) {
1298
+ return true;
1299
+ }
1300
+ return /^(?:test|testing|qa|bot|agent|demo|admin|noreply|no-reply)(?:[+._-]|$)/i.test(local);
1301
+ }
1302
+
1303
+ function readJsonObject(filePath) {
1304
+ try {
1305
+ if (!filePath || !fs.existsSync(filePath)) return null;
1306
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
1307
+ return parsed && typeof parsed === 'object' ? parsed : null;
1308
+ } catch {
1309
+ return null;
1310
+ }
1311
+ }
1312
+
1313
+ function accountStampInWindow(stamp, analyticsWindow) {
1314
+ if (!stamp) return true;
1315
+ const iso = Number.isFinite(Number(stamp)) ? new Date(Number(stamp)).toISOString() : stamp;
1316
+ return eventOccursInWindow(iso, analyticsWindow);
1317
+ }
1318
+
1319
+ function collectEmailAccountSignups(analyticsWindow) {
1320
+ const { FEEDBACK_DIR } = getFeedbackPaths();
1321
+ const owners = ownerEmailSet();
1322
+ const emails = new Set();
1323
+ let rawRecords = 0;
1324
+
1325
+ function consider(rawEmail, stamp) {
1326
+ const email = normalizeEmail(rawEmail);
1327
+ if (!email) return;
1328
+ rawRecords += 1;
1329
+ if (!accountStampInWindow(stamp, analyticsWindow)) return;
1330
+ if (owners.has(email) || email.endsWith('@igorganapolsky.com') || email.endsWith('@thumbgate.ai') || isFixtureEmailAccount(email)) return;
1331
+ emails.add(email);
1332
+ }
1333
+
1334
+ for (const row of loadNewsletterSubscribers()) {
1335
+ consider(row && row.email, row && row.subscribedAt);
1336
+ }
1337
+ for (const row of loadJsonlRecords(CONFIG.TRIAL_EMAIL_LEDGER_PATH, resolveLegacyBillingPath('trial-emails.jsonl'))) {
1338
+ if (row && row.status && row.status !== 'sent' && row.status !== 'already_sent') continue;
1339
+ consider(row && (row.customerEmail || row.email), row && row.timestamp);
1340
+ }
1341
+ const authSessions = readJsonObject(path.join(FEEDBACK_DIR, 'auth-sessions.json')) || {};
1342
+ for (const entry of Object.values(authSessions)) {
1343
+ if (!entry || typeof entry !== 'object') continue;
1344
+ if (entry.subjectType === 'admin' || entry.subjectType === 'operator' || entry.ssoProvider === 'admin' || entry.ssoProvider === 'admin_created') continue;
1345
+ consider(entry.ssoEmail || entry.email, entry.createdAt);
1346
+ }
1347
+ const legacySso = readJsonObject(path.join(FEEDBACK_DIR, 'cloud-sso-sessions.json'));
1348
+ const legacyRows = Array.isArray(legacySso)
1349
+ ? legacySso
1350
+ : Object.values((legacySso && (legacySso.sessions || legacySso)) || {});
1351
+ for (const entry of legacyRows) {
1352
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
1353
+ if (entry.provider === 'admin' || entry.provider === 'admin_created' || entry.subjectType === 'admin') continue;
1354
+ consider(entry.email || entry.ssoEmail, entry.createdAt);
1355
+ }
1356
+ const keys = loadKeyStore();
1357
+ for (const meta of Object.values((keys && keys.keys) || {})) {
1358
+ consider(meta && meta.customerEmail, meta && meta.createdAt);
1359
+ }
1360
+
1361
+ return {
1362
+ emailSignups: emails.size,
1363
+ emailRecords: rawRecords,
1364
+ };
1365
+ }
1366
+
1233
1367
  function buildProviderEventFallbackKey(entry = {}, metadata = {}, attribution = {}) {
1234
1368
  const provider = normalizeText(metadata.provider || entry.provider || attribution.source || entry.source) || 'unknown';
1235
1369
  const customerId = normalizeText(metadata.customerId || entry.customerId);
@@ -1471,9 +1605,13 @@ function loadResolvedRevenueEvents(options = {}) {
1471
1605
  for (const entry of paidProviderEvents) {
1472
1606
  const derived = deriveRevenueEventFromPaidProviderEvent(entry);
1473
1607
  if (!derived) continue;
1474
- if (hasRevenueEventMatch(resolved, derived)) continue;
1608
+ const index = resolved.findIndex((existing) => hasRevenueEventMatch([existing], derived));
1609
+ if (index >= 0) {
1610
+ resolved[index] = retainRevenueEvidence({ ...resolved[index] }, resolved[index], derived, entry);
1611
+ continue;
1612
+ }
1475
1613
  const priced = resolveGithubMarketplaceRevenueEntry(derived, { annotate: false }).entry;
1476
- resolved.push(priced);
1614
+ resolved.push(retainRevenueEvidence(priced, priced, derived, entry));
1477
1615
  }
1478
1616
 
1479
1617
  return mergeRevenueEvents(resolved, extraRevenueEvents);
@@ -1879,12 +2017,44 @@ function parseTestStripeReconciledRevenueEvents() {
1879
2017
  }
1880
2018
  }
1881
2019
 
2020
+ // Duplicate rows still carry identity and payment aliases. Keep that evidence in
2021
+ // memory without adding fields to the ledger or changing its existing counts.
2022
+ const revenueEvidence = new WeakMap();
2023
+
2024
+ function revenueEvidenceFor(entry) {
2025
+ return revenueEvidence.get(entry) || [entry];
2026
+ }
2027
+
2028
+ function retainRevenueEvidence(result, ...entries) {
2029
+ revenueEvidence.set(result, [...new Set(entries.flatMap(revenueEvidenceFor))]);
2030
+ return result;
2031
+ }
2032
+
1882
2033
  function mergeRevenueEvents(entries = [], extraEntries = []) {
1883
2034
  const merged = [...entries];
1884
2035
 
1885
2036
  for (const entry of extraEntries) {
1886
2037
  if (!entry || typeof entry !== 'object') continue;
1887
- if (hasRevenueEventMatch(merged, entry)) continue;
2038
+ const index = merged.findIndex((existing) => hasRevenueEventMatch([existing], entry)
2039
+ || (entry.metadata?.paymentIntentId && existing.metadata?.paymentIntentId === entry.metadata.paymentIntentId)
2040
+ || (entry.metadata?.chargeId && (existing.orderId === entry.metadata.chargeId || existing.metadata?.chargeId === entry.metadata.chargeId)));
2041
+ if (index >= 0) {
2042
+ const existing = merged[index];
2043
+ if (entry.metadata?.stripeReconciled) {
2044
+ merged[index] = {
2045
+ ...merged[index], ...entry,
2046
+ customerEmail: normalizeText(entry.customerEmail) || merged[index].customerEmail || null,
2047
+ identityClassification: [classifyRevenueRecord(merged[index]), classifyRevenueRecord(entry)].includes('internal') ? 'internal'
2048
+ : [classifyRevenueRecord(merged[index]), classifyRevenueRecord(entry)].includes('test') ? 'test' : null,
2049
+ identityEmails: [...new Set([...revenueIdentityEmails(merged[index]), ...revenueIdentityEmails(entry)])],
2050
+ metadata: { ...merged[index].metadata, ...entry.metadata },
2051
+ };
2052
+ } else {
2053
+ merged[index] = { ...existing };
2054
+ }
2055
+ merged[index] = retainRevenueEvidence(merged[index], existing, entry);
2056
+ continue;
2057
+ }
1888
2058
  merged.push(entry);
1889
2059
  }
1890
2060
 
@@ -1989,6 +2159,120 @@ function matchStripeChargeFromSubscriptions(priceCatalog, charge, subscriptions
1989
2159
  return description.toLowerCase().startsWith('subscription') ? matches[0] : null;
1990
2160
  }
1991
2161
 
2162
+ function revenueIdentityEmails(record = {}) {
2163
+ const scopes = [record, record.customer, record.charge, record.charge?.customer].filter((value) => value && typeof value === 'object');
2164
+ return [...new Set(scopes.flatMap((value) => [value.customerEmail, value.email, value.receipt_email,
2165
+ value.billing_details?.email, value.metadata?.customerEmail, value.metadata?.email,
2166
+ ...(Array.isArray(value.identityEmails) ? value.identityEmails : [])])
2167
+ .filter((value) => typeof value === 'string' && canonicalizeEmailAddress(value))
2168
+ .map((value) => value.trim().toLowerCase()))];
2169
+ }
2170
+
2171
+ function classifyRevenueRecord(record = {}, env = process.env) {
2172
+ const scopes = [record, record.customer, record.charge, record.charge?.customer].filter((value) => value && typeof value === 'object');
2173
+ const emails = revenueIdentityEmails(record);
2174
+ const owners = String(env.THUMBGATE_OWNER_EMAILS || '').split(',').map((email) => canonicalizeEmailAddress(email)).filter(Boolean);
2175
+ if (record.identityClassification === 'internal' || emails.some((email) => owners.includes(canonicalizeEmailAddress(email)))) return 'internal';
2176
+ if (scopes.some((value) => [true, 'true'].includes(value.metadata?.internal) || [true, 'true'].includes(value.metadata?.owner))) return 'internal';
2177
+ if (record.identityClassification === 'test' || scopes.some((value) => value.livemode === false || [false, 'false'].includes(value.metadata?.livemode)
2178
+ || [true, 'true'].includes(value.metadata?.test) || isAutomatedCheckoutRequest(value.metadata || {}))
2179
+ || emails.some(isSyntheticOrOwnerCheckoutEmail)) return 'test';
2180
+ return emails.length ? 'external' : 'unknown';
2181
+ }
2182
+
2183
+ let activeStripeReads = 0;
2184
+ async function withStripeReadSlot(request, { signal } = {}) {
2185
+ if (signal?.aborted) throw Object.assign(new Error('Stripe reconciliation timeout'), { code: 'reconciliation_timeout' });
2186
+ if (activeStripeReads >= 2) throw Object.assign(new Error('Stripe read capacity unavailable'), { code: 'provider_busy' });
2187
+ activeStripeReads += 1;
2188
+ try { return await request(); }
2189
+ finally { activeStripeReads -= 1; }
2190
+ }
2191
+
2192
+ function groupRevenuePayments(entries) {
2193
+ const paid = entries.filter((entry) => entry && entry.status === 'paid');
2194
+ const parents = paid.map((_, index) => index);
2195
+ const aliases = new Map();
2196
+ const root = (index) => {
2197
+ while (parents[index] !== index) {
2198
+ parents[index] = parents[parents[index]];
2199
+ index = parents[index];
2200
+ }
2201
+ return index;
2202
+ };
2203
+ paid.forEach((entry, index) => {
2204
+ for (const evidence of revenueEvidenceFor(entry)) {
2205
+ const metadata = evidence.metadata || {};
2206
+ const identities = [evidence.orderId, metadata.chargeId, metadata.paymentIntentId, metadata.orderId,
2207
+ metadata.sessionId, metadata.marketplaceOrderId, resolveRevenueEventKey(evidence)].filter(Boolean);
2208
+ for (const alias of identities) {
2209
+ if (aliases.has(alias)) parents[root(index)] = root(aliases.get(alias));
2210
+ else aliases.set(alias, index);
2211
+ }
2212
+ }
2213
+ });
2214
+ const groups = new Map();
2215
+ paid.forEach((entry, index) => {
2216
+ const key = root(index);
2217
+ if (!groups.has(key)) groups.set(key, { records: 0, evidence: new Set() });
2218
+ const group = groups.get(key);
2219
+ group.records += 1;
2220
+ for (const evidence of revenueEvidenceFor(entry)) group.evidence.add(evidence);
2221
+ });
2222
+ return [...groups.values()];
2223
+ }
2224
+
2225
+ function hasKnownRevenueAmount(entry) {
2226
+ return entry.amountKnown && Number.isSafeInteger(entry.amountCents) && /^[A-Z]{3}$/.test(String(entry.currency || '').toUpperCase());
2227
+ }
2228
+
2229
+ function comparePaymentAmountEvidence(a, b) {
2230
+ // Prefer provider reconciliation and explicit refund state, then the newest
2231
+ // snapshot. Stable tie-breaks make the total independent of input order.
2232
+ return Number(Boolean(b.metadata?.stripeReconciled)) - Number(Boolean(a.metadata?.stripeReconciled))
2233
+ || Number(Number.isSafeInteger(b.amountRefundedCents)) - Number(Number.isSafeInteger(a.amountRefundedCents))
2234
+ || (Date.parse(b.timestamp) || 0) - (Date.parse(a.timestamp) || 0)
2235
+ || (b.amountRefundedCents || 0) - (a.amountRefundedCents || 0)
2236
+ || String(a.currency).localeCompare(String(b.currency))
2237
+ || a.amountCents - b.amountCents;
2238
+ }
2239
+
2240
+ function refundedCentsOf(entry) {
2241
+ return Number.isSafeInteger(entry && entry.amountRefundedCents) && entry.amountRefundedCents > 0 ? entry.amountRefundedCents : 0;
2242
+ }
2243
+
2244
+ // A fully refunded payment is not revenue; a partial refund books only the net amount.
2245
+ function isFullyRefundedRevenue(entry) {
2246
+ return hasKnownRevenueAmount(entry) && entry.amountCents > 0 && refundedCentsOf(entry) >= entry.amountCents;
2247
+ }
2248
+
2249
+ function netOfRefund(entry) {
2250
+ const refunded = refundedCentsOf(entry);
2251
+ return refunded && hasKnownRevenueAmount(entry) ? { ...entry, amountCents: entry.amountCents - refunded } : entry;
2252
+ }
2253
+
2254
+ function summarizeExternalRevenue(entries = [], env = process.env) {
2255
+ const totals = { paidOrders: 0, bookedRevenueByCurrency: {}, refundedByCurrency: {}, excluded: { internal: 0, test: 0, unknown: 0 }, duplicates: 0, amountUnknownOrders: 0 };
2256
+ for (const group of groupRevenuePayments(entries)) {
2257
+ totals.duplicates += group.records - 1;
2258
+ const evidence = [...group.evidence];
2259
+ const classifications = new Set(evidence.map((entry) => classifyRevenueRecord(entry, env)));
2260
+ const classification = ['internal', 'test', 'external', 'unknown'].find((value) => classifications.has(value));
2261
+ if (classification !== 'external') { totals.excluded[classification] += 1; continue; }
2262
+ const entry = evidence.filter(hasKnownRevenueAmount).sort(comparePaymentAmountEvidence)[0];
2263
+ if (entry) {
2264
+ const currency = String(entry.currency).toUpperCase();
2265
+ if (Number.isSafeInteger(entry.amountRefundedCents)) {
2266
+ totals.refundedByCurrency[currency] = (totals.refundedByCurrency[currency] || 0) + entry.amountRefundedCents;
2267
+ }
2268
+ if (isFullyRefundedRevenue(entry)) continue;
2269
+ totals.paidOrders += 1;
2270
+ totals.bookedRevenueByCurrency[currency] = (totals.bookedRevenueByCurrency[currency] || 0) + netOfRefund(entry).amountCents;
2271
+ } else { totals.paidOrders += 1; totals.amountUnknownOrders += 1; }
2272
+ }
2273
+ return totals;
2274
+ }
2275
+
1992
2276
  function buildStripeReconciledRevenueEvent(charge, match = {}) {
1993
2277
  const timestampMs = Number(charge.created) * 1000;
1994
2278
  const timestamp = Number.isFinite(timestampMs)
@@ -2000,10 +2284,15 @@ function buildStripeReconciledRevenueEvent(charge, match = {}) {
2000
2284
  timestamp,
2001
2285
  provider: 'stripe',
2002
2286
  event: 'stripe_charge_reconciled',
2287
+ livemode: charge.livemode,
2288
+ customerEmail: charge.customer?.email || charge.billing_details?.email || charge.receipt_email || null,
2289
+ identityEmails: revenueIdentityEmails(charge),
2290
+ identityClassification: classifyRevenueRecord(charge),
2291
+ amountRefundedCents: normalizeInteger(charge.amount_refunded),
2003
2292
  status: 'paid',
2004
2293
  orderId: normalizeText(charge.id),
2005
2294
  evidence: normalizeText(charge.id) || 'stripe_charge_reconciled',
2006
- customerId: normalizeText(charge.customer) || `stripe_charge_${normalizeText(charge.id) || 'unknown'}`,
2295
+ customerId: normalizeText(typeof charge.customer === 'object' ? charge.customer?.id : charge.customer) || `stripe_charge_${normalizeText(charge.id) || 'unknown'}`,
2007
2296
  installId: null,
2008
2297
  traceId: null,
2009
2298
  amountCents,
@@ -2014,6 +2303,7 @@ function buildStripeReconciledRevenueEvent(charge, match = {}) {
2014
2303
  source: 'stripe_reconciled',
2015
2304
  },
2016
2305
  metadata: {
2306
+ ...sanitizeMetadata(charge.metadata),
2017
2307
  stripeReconciled: true,
2018
2308
  chargeId: normalizeText(charge.id),
2019
2309
  paymentIntentId: normalizeText(charge.payment_intent),
@@ -2026,43 +2316,57 @@ function buildStripeReconciledRevenueEvent(charge, match = {}) {
2026
2316
  };
2027
2317
  }
2028
2318
 
2029
- async function listStripeReconciledRevenueEvents() {
2319
+ async function listStripeReconciledRevenueEvents({ signal, deadline = Infinity } = {}) {
2320
+ const diagnostics = { status: 'ok', complete: true };
2321
+ const result = (events, status = diagnostics.status) => Object.defineProperty(events, 'reconciliation', { value: { ...diagnostics, status }, enumerable: false });
2322
+ const checkDeadline = () => {
2323
+ if (signal?.aborted || Date.now() >= deadline) throw Object.assign(new Error('Stripe reconciliation timeout'), { code: 'reconciliation_timeout' });
2324
+ };
2325
+ const request = async (fn) => {
2326
+ checkDeadline();
2327
+ const timeout = Math.max(1, Math.min(8000, deadline - Date.now()));
2328
+ const value = await withTimeout(withStripeReadSlot(() => fn({ timeout, maxNetworkRetries: 0 }), { signal }), timeout);
2329
+ checkDeadline();
2330
+ if (value?.has_more || value?.lines?.has_more) diagnostics.complete = false;
2331
+ return value;
2332
+ };
2030
2333
  const testEvents = parseTestStripeReconciledRevenueEvents();
2031
2334
  if (testEvents.length > 0) {
2032
- return testEvents;
2335
+ return result(testEvents);
2033
2336
  }
2034
2337
 
2035
2338
  if (!CONFIG.STRIPE_SECRET_KEY || !CONFIG.STRIPE_PRICE_ID) {
2036
- return [];
2339
+ return result([], 'unconfigured');
2037
2340
  }
2038
2341
 
2039
2342
  let stripe;
2040
2343
  try {
2041
2344
  stripe = getStripeClient();
2042
2345
  } catch {
2043
- return [];
2346
+ return result([], 'unavailable');
2044
2347
  }
2045
2348
 
2046
- const currentPrice = await withTimeout(stripe.prices.retrieve(CONFIG.STRIPE_PRICE_ID));
2047
- const relatedPrices = await withTimeout(stripe.prices.list({
2349
+ const currentPrice = await request((options) => stripe.prices.retrieve(CONFIG.STRIPE_PRICE_ID, options));
2350
+ const relatedPrices = await request((options) => stripe.prices.list({
2048
2351
  product: CONFIG.STRIPE_PRODUCT_ID || currentPrice.product,
2049
2352
  limit: 100,
2050
- }));
2353
+ }, options));
2051
2354
  const priceCatalog = buildStripePriceCatalog(
2052
2355
  currentPrice,
2053
2356
  relatedPrices && Array.isArray(relatedPrices.data) ? relatedPrices.data : []
2054
2357
  );
2055
2358
  if (!priceCatalog.productId) {
2056
- return [];
2359
+ return result([], 'unavailable');
2057
2360
  }
2058
2361
 
2059
- const charges = await withTimeout(stripe.charges.list({ limit: 100 }));
2362
+ const charges = await request((options) => stripe.charges.list({ limit: 100, expand: ['data.customer'] }, options));
2060
2363
  const reconciled = [];
2061
2364
  const invoiceCache = new Map();
2062
2365
  const subscriptionCache = new Map();
2063
2366
 
2064
2367
  for (const charge of charges.data || []) {
2065
- if (!charge || !charge.paid || charge.status !== 'succeeded' || charge.refunded) {
2368
+ checkDeadline();
2369
+ if (!charge || !charge.paid || charge.status !== 'succeeded') {
2066
2370
  continue;
2067
2371
  }
2068
2372
 
@@ -2073,7 +2377,7 @@ async function listStripeReconciledRevenueEvents() {
2073
2377
  if (invoiceId) {
2074
2378
  let invoice = invoiceCache.get(invoiceId);
2075
2379
  if (!invoice) {
2076
- invoice = await withTimeout(stripe.invoices.retrieve(invoiceId, { expand: ['lines.data.price'] }));
2380
+ invoice = await request((options) => stripe.invoices.retrieve(invoiceId, { expand: ['lines.data.price'] }, options));
2077
2381
  invoiceCache.set(invoiceId, invoice);
2078
2382
  }
2079
2383
  const lines = invoice && invoice.lines && Array.isArray(invoice.lines.data) ? invoice.lines.data : [];
@@ -2082,15 +2386,15 @@ async function listStripeReconciledRevenueEvents() {
2082
2386
  }
2083
2387
 
2084
2388
  if (!match && charge.customer) {
2085
- const customerId = normalizeText(charge.customer);
2389
+ const customerId = normalizeText(typeof charge.customer === 'object' ? charge.customer?.id : charge.customer);
2086
2390
  if (customerId) {
2087
2391
  let subscriptions = subscriptionCache.get(customerId);
2088
2392
  if (!subscriptions) {
2089
- const listed = await withTimeout(stripe.subscriptions.list({
2393
+ const listed = await request((options) => stripe.subscriptions.list({
2090
2394
  customer: customerId,
2091
2395
  status: 'all',
2092
2396
  limit: 100,
2093
- }));
2397
+ }, options));
2094
2398
  subscriptions = listed && Array.isArray(listed.data) ? listed.data : [];
2095
2399
  subscriptionCache.set(customerId, subscriptions);
2096
2400
  }
@@ -2105,18 +2409,22 @@ async function listStripeReconciledRevenueEvents() {
2105
2409
  reconciled.push(buildStripeReconciledRevenueEvent(charge, match));
2106
2410
  }
2107
2411
 
2108
- return reconciled;
2412
+ return result(reconciled, diagnostics.complete ? 'ok' : 'partial');
2109
2413
  }
2110
2414
 
2111
2415
  function getFunnelAnalytics(options = {}) {
2112
2416
  const analyticsWindow = resolveAnalyticsWindow(options);
2113
2417
  const extraRevenueEvents = Array.isArray(options.extraRevenueEvents) ? options.extraRevenueEvents : [];
2114
- const events = filterEntriesForWindow(
2115
- loadFunnelLedger(),
2116
- analyticsWindow,
2117
- (entry) => entry && entry.timestamp
2118
- );
2119
- const paidOrders = loadResolvedRevenueEvents({ ...analyticsWindow, extraRevenueEvents }).filter((entry) => entry && entry.status === 'paid');
2418
+ const rawEvents = Array.isArray(options._rawFunnelEvents)
2419
+ ? options._rawFunnelEvents
2420
+ : filterEntriesForWindow(
2421
+ loadFunnelLedger(),
2422
+ analyticsWindow,
2423
+ (entry) => entry && entry.timestamp
2424
+ );
2425
+ const { events, excludedSyntheticCheckoutSessions } = options._filteredFunnel
2426
+ || filterQualifiedCheckoutFunnelEvents(rawEvents);
2427
+ const paidOrders = loadResolvedRevenueEvents({ ...analyticsWindow, extraRevenueEvents }).filter((entry) => entry && entry.status === 'paid' && !isFullyRefundedRevenue(entry));
2120
2428
  const stageCounts = { acquisition: 0, activation: 0, paid: 0 };
2121
2429
  const eventCounts = {};
2122
2430
  for (const entry of events) {
@@ -2129,6 +2437,7 @@ function getFunnelAnalytics(options = {}) {
2129
2437
  return {
2130
2438
  window: serializeAnalyticsWindow(analyticsWindow),
2131
2439
  totalEvents: events.length,
2440
+ excludedSyntheticCheckoutSessions,
2132
2441
  stageCounts,
2133
2442
  eventCounts,
2134
2443
  conversionRates: {
@@ -2146,11 +2455,13 @@ function getBusinessAnalytics(options = {}) {
2146
2455
  const { FEEDBACK_DIR } = getFeedbackPaths();
2147
2456
  const telemetry = getTelemetryAnalytics(FEEDBACK_DIR, analyticsWindow);
2148
2457
  const sourceDiagnostics = buildBillingSourceDiagnostics(FEEDBACK_DIR);
2149
- const events = filterEntriesForWindow(
2458
+ const rawEvents = filterEntriesForWindow(
2150
2459
  loadFunnelLedger(),
2151
2460
  analyticsWindow,
2152
2461
  (entry) => entry && entry.timestamp
2153
2462
  );
2463
+ const filteredFunnel = filterQualifiedCheckoutFunnelEvents(rawEvents);
2464
+ const { events } = filteredFunnel;
2154
2465
  const revenueEvents = loadResolvedRevenueEvents({ ...analyticsWindow, extraRevenueEvents });
2155
2466
  const workflowSprintIntake = loadWorkflowSprintIntakeModule();
2156
2467
  const workflowSprintLeads = filterEntriesForWindow(
@@ -2163,10 +2474,17 @@ function getBusinessAnalytics(options = {}) {
2163
2474
  analyticsWindow,
2164
2475
  (entry) => entry && entry.subscribedAt
2165
2476
  );
2166
- const funnel = getFunnelAnalytics({ ...analyticsWindow, extraRevenueEvents });
2477
+ const funnel = getFunnelAnalytics({
2478
+ ...analyticsWindow,
2479
+ extraRevenueEvents,
2480
+ _rawFunnelEvents: rawEvents,
2481
+ _filteredFunnel: filteredFunnel,
2482
+ });
2167
2483
  const acquisitionEvents = events.filter((entry) => entry && entry.stage === 'acquisition');
2484
+ const emailAccountSignups = collectEmailAccountSignups(analyticsWindow);
2168
2485
  const paidEvents = events.filter((entry) => entry && entry.stage === 'paid');
2169
- const paidOrders = revenueEvents.filter((entry) => entry && entry.status === 'paid');
2486
+ const paidEventsGross = revenueEvents.filter((entry) => entry && entry.status === 'paid');
2487
+ const paidOrders = paidEventsGross.filter((entry) => !isFullyRefundedRevenue(entry)).map(netOfRefund);
2170
2488
  const firstPaid = paidEvents[0] || null;
2171
2489
  const lastPaid = paidEvents[paidEvents.length - 1] || null;
2172
2490
 
@@ -2481,7 +2799,7 @@ function getBusinessAnalytics(options = {}) {
2481
2799
  const unreconciledPaidEvents = paidEvents.filter((entry) => {
2482
2800
  const eventKey = resolvePaidProviderEventKey(entry);
2483
2801
  if (!eventKey) return true;
2484
- return !paidOrders.some((order) => resolveRevenueEventKey(order) === eventKey);
2802
+ return !paidEventsGross.some((order) => resolveRevenueEventKey(order) === eventKey);
2485
2803
  }).length;
2486
2804
 
2487
2805
  const trafficMetrics = {
@@ -2489,9 +2807,9 @@ function getBusinessAnalytics(options = {}) {
2489
2807
  sessions: telemetry.visitors ? telemetry.visitors.uniqueSessions || 0 : 0,
2490
2808
  pageViews: telemetry.visitors ? telemetry.visitors.pageViews || 0 : 0,
2491
2809
  ctaClicks: telemetry.ctas ? telemetry.ctas.totalClicks || 0 : 0,
2492
- checkoutStarts: telemetry.ctas ? telemetry.ctas.checkoutStarts || 0 : 0,
2810
+ checkoutStarts: telemetry.ctas ? (telemetry.ctas.qualifiedCheckoutStarts ?? telemetry.ctas.checkoutStarts ?? 0) : 0,
2493
2811
  checkoutSuccessPageViews: telemetry.ctas ? telemetry.ctas.successPageViews || 0 : 0,
2494
- checkoutCancelPageViews: telemetry.ctas ? telemetry.ctas.cancelPageViews || 0 : 0,
2812
+ checkoutCancelPageViews: telemetry.ctas ? (telemetry.ctas.qualifiedCancelPageViews ?? telemetry.ctas.cancelPageViews ?? 0) : 0,
2495
2813
  checkoutPaidConfirmations: telemetry.ctas ? telemetry.ctas.paidConfirmations || 0 : 0,
2496
2814
  checkoutPendingSessions: telemetry.ctas ? telemetry.ctas.sessionPending || 0 : 0,
2497
2815
  checkoutLookupFailures: telemetry.ctas ? telemetry.ctas.lookupFailures || 0 : 0,
@@ -2506,6 +2824,14 @@ function getBusinessAnalytics(options = {}) {
2506
2824
  bySource: operatorGeneratedAcquisitionBySource,
2507
2825
  };
2508
2826
 
2827
+ const telemetryWindowMeta = telemetry?.window ?? null;
2828
+ const telemetryLogTruncated = Boolean(
2829
+ telemetryWindowMeta?.truncated || telemetry?.telemetrySource?.truncated
2830
+ );
2831
+ const telemetryWindowComplete = typeof telemetryWindowMeta?.complete === 'boolean'
2832
+ ? telemetryWindowMeta.complete
2833
+ : !telemetryLogTruncated;
2834
+
2509
2835
  const dataQuality = {
2510
2836
  telemetryCoverage: Number(((
2511
2837
  (telemetry.visitors ? telemetry.visitors.visitorIdCoverageRate || 0 : 0) +
@@ -2515,11 +2841,17 @@ function getBusinessAnalytics(options = {}) {
2515
2841
  attributionCoverage: telemetry.visitors ? telemetry.visitors.attributionCoverageRate || 0 : 0,
2516
2842
  amountKnownCoverage: paidOrders.length ? safeRate(amountKnownOrders, paidOrders.length) : 0,
2517
2843
  unreconciledPaidEvents,
2844
+ telemetryLogTruncated,
2845
+ telemetryWindowComplete,
2518
2846
  };
2519
2847
 
2520
2848
  return {
2521
2849
  generatedAt: new Date().toISOString(),
2522
- window: serializeAnalyticsWindow(analyticsWindow),
2850
+ window: {
2851
+ ...serializeAnalyticsWindow(analyticsWindow),
2852
+ truncated: telemetryLogTruncated,
2853
+ complete: telemetryWindowComplete,
2854
+ },
2523
2855
  coverage: {
2524
2856
  source: 'funnel_ledger+revenue_ledger+workflow_sprint_leads',
2525
2857
  tracksBookedRevenue: true,
@@ -2550,6 +2882,10 @@ function getBusinessAnalytics(options = {}) {
2550
2882
  signups: {
2551
2883
  total: acquisitionEvents.length,
2552
2884
  uniqueLeads: acquisitionLeadKeys.size,
2885
+ checkoutSessionsCreated: acquisitionEvents.length,
2886
+ emailSignups: emailAccountSignups.emailSignups,
2887
+ emailRecords: emailAccountSignups.emailRecords,
2888
+ metricKind: 'checkout_sessions_are_not_email_accounts',
2553
2889
  bySource: signupsBySource,
2554
2890
  byCampaign: signupsByCampaign,
2555
2891
  byCreator: signupsByCreator,
@@ -2560,6 +2896,7 @@ function getBusinessAnalytics(options = {}) {
2560
2896
  byOfferCode: signupsByOfferCode,
2561
2897
  },
2562
2898
  revenue: {
2899
+ external: summarizeExternalRevenue(paidEventsGross),
2563
2900
  paidProviderEvents: paidEvents.length,
2564
2901
  paidOrders: paidOrders.length,
2565
2902
  paidCustomers: paidCustomerIds.size,
@@ -2761,10 +3098,10 @@ function getBillingSummary(options = {}) {
2761
3098
  }
2762
3099
 
2763
3100
  function buildBillingSummaryFailure(error) {
2764
- const isTimeout = error && error.message && error.message.includes('Stripe API timeout');
3101
+ const isTimeout = Boolean(error?.message?.includes('Stripe API timeout'));
2765
3102
  return {
2766
3103
  error: isTimeout ? 'stripe_timeout' : 'billing_summary_error',
2767
- message: error && error.message ? error.message : 'Unknown error',
3104
+ message: error?.message || 'Unknown error',
2768
3105
  revenue: { total: 0, mrr: 0, events: [] },
2769
3106
  usage: { totalUsage: 0, bySource: {}, activeBySource: {} },
2770
3107
  customers: [],
@@ -2773,28 +3110,36 @@ function buildBillingSummaryFailure(error) {
2773
3110
 
2774
3111
  async function getBillingSummariesLive(optionsByWindow = {}, {
2775
3112
  listStripeReconciledRevenueEventsFn = listStripeReconciledRevenueEvents,
3113
+ signal,
2776
3114
  } = {}) {
2777
3115
  const entries = Object.entries(optionsByWindow || {});
2778
- if (entries.length === 0) return {};
2779
-
3116
+ if (!entries.length) return {};
3117
+ const reconciliationTimeoutMs = entries.map(([, options]) => normalizeInteger(options?.stripeReconciliationTimeoutMs))
3118
+ .find((value) => value !== null) || STRIPE_RECONCILIATION_SUMMARY_TIMEOUT_MS;
3119
+ const controller = new AbortController();
3120
+ const abort = () => controller.abort();
3121
+ signal?.addEventListener('abort', abort, { once: true });
3122
+ if (signal?.aborted) abort();
3123
+ let extraRevenueEvents = [];
3124
+ let reconciliation = { status: 'ok', complete: true };
2780
3125
  try {
2781
- const reconciliationTimeoutMs = entries
2782
- .map(([, options]) => normalizeInteger(options && options.stripeReconciliationTimeoutMs))
2783
- .find((value) => value !== null)
2784
- || STRIPE_RECONCILIATION_SUMMARY_TIMEOUT_MS;
2785
- const extraRevenueEvents = await withTimeout(
2786
- listStripeReconciledRevenueEventsFn(),
2787
- reconciliationTimeoutMs
2788
- ).catch(() => []);
2789
- return Object.fromEntries(entries.map(([key, options]) => [
2790
- key,
2791
- getBillingSummary({
2792
- ...(options || {}),
2793
- extraRevenueEvents,
2794
- }),
2795
- ]));
2796
- } catch (err) {
2797
- return Object.fromEntries(entries.map(([key]) => [key, buildBillingSummaryFailure(err)]));
3126
+ extraRevenueEvents = await withTimeout(listStripeReconciledRevenueEventsFn({
3127
+ signal: controller.signal, deadline: Date.now() + reconciliationTimeoutMs,
3128
+ }), reconciliationTimeoutMs);
3129
+ reconciliation = extraRevenueEvents.reconciliation || reconciliation;
3130
+ } catch (error) {
3131
+ reconciliation = { status: /timeout/i.test(error?.message || '') ? 'timeout' : 'unavailable', complete: false };
3132
+ } finally {
3133
+ controller.abort();
3134
+ signal?.removeEventListener('abort', abort);
3135
+ }
3136
+ if (signal?.aborted) throw Object.assign(new Error('Collection stopped'), { code: 'collection_timeout' });
3137
+ try {
3138
+ return Object.fromEntries(entries.map(([key, options]) => [key, {
3139
+ ...getBillingSummary({ ...options, extraRevenueEvents }), reconciliation,
3140
+ }]));
3141
+ } catch (error) {
3142
+ return Object.fromEntries(entries.map(([key]) => [key, { ...buildBillingSummaryFailure(error), reconciliation }]));
2798
3143
  }
2799
3144
  }
2800
3145
 
@@ -2805,9 +3150,7 @@ async function getBillingSummaryLive(options = {}, runtime = {}) {
2805
3150
 
2806
3151
  function loadKeyStore() {
2807
3152
  try {
2808
- const primary = CONFIG.API_KEYS_PATH;
2809
- const legacy = resolveLegacyBillingPath('api-keys.json');
2810
- const target = (IS_TEST || fs.existsSync(primary)) ? primary : legacy;
3153
+ const target = resolveKeyStoreReadPath();
2811
3154
  if (!fs.existsSync(target)) return { keys: {}, canceledSubscriptions: {}, customerRevocations: {} };
2812
3155
  const parsed = JSON.parse(fs.readFileSync(target, 'utf-8'));
2813
3156
  if (!parsed || typeof parsed.keys !== 'object') {
@@ -2876,6 +3219,174 @@ function withKeyStoreLock(mutator) {
2876
3219
  }
2877
3220
  }
2878
3221
 
3222
+ // Probes, audits and health checks mark themselves with one of these. They must
3223
+ // never open live Checkout sessions: each one shows up as an abandoned checkout.
3224
+ const AUTOMATED_CHECKOUT_SOURCES = new Set([
3225
+ 'internal_audit', 'probe', 'health_check', 'smoke_test', 'codex_audit', 'synthetic', 'e2e_probe',
3226
+ ]);
3227
+ const AUTOMATED_CHECKOUT_MARKER_PATTERN = /(?:^|[^a-z0-9])(?:internal[-_]audit|smoke[-_]test|health[-_]check|codex[-_]verification|codex[-_]audit|e2e[-_]probe|checkout[-_]probe|money-v\d+-audit)(?:$|[^a-z0-9])/i;
3228
+ const SYNTHETIC_CHECKOUT_EMAIL_PATTERN = /^(?:[^@\s]+@(?:example\.(?:com|org|net)|formtests\.info|mailinator\.com|acme\.(?:io|com)|invalid)|test@test\.com|founder@agent-startup\.io|audit@thumbgate\.ai|(?:e2e[-_]?probe|test[-_]?checkout[-_]?probe|probe|smoke[-_]?test)@[^@\s]+)$/i;
3229
+
3230
+ function canonicalizeEmailAddress(rawEmail = '') {
3231
+ const email = String(rawEmail || '').trim().toLowerCase();
3232
+ const atIdx = email.indexOf('@');
3233
+ if (atIdx <= 0 || atIdx !== email.lastIndexOf('@') || atIdx === email.length - 1) return '';
3234
+ const localPart = email.slice(0, atIdx).replace(/\+.*$/, '');
3235
+ const domainPart = email.slice(atIdx + 1);
3236
+ return localPart && domainPart ? `${localPart}@${domainPart}` : '';
3237
+ }
3238
+
3239
+ function isSyntheticOrOwnerCheckoutEmail(rawEmail = '') {
3240
+ const email = String(rawEmail || '').trim().toLowerCase();
3241
+ if (!email) return false;
3242
+ const canonical = canonicalizeEmailAddress(email);
3243
+ if (canonical && SYNTHETIC_CHECKOUT_EMAIL_PATTERN.test(canonical)) return true;
3244
+ if (SYNTHETIC_CHECKOUT_EMAIL_PATTERN.test(email)) return true;
3245
+ if (!canonical) return false;
3246
+ return getOwnerEmails().some((ownerEmail) => canonicalizeEmailAddress(ownerEmail) === canonical);
3247
+ }
3248
+
3249
+ function isAutomatedCheckoutRequest(metadata = {}, customerEmail = '') {
3250
+ const source = String(metadata.source || metadata.utmSource || '').toLowerCase();
3251
+ const installId = String(metadata.installId || '').toLowerCase();
3252
+ if (AUTOMATED_CHECKOUT_SOURCES.has(source)) return true;
3253
+ if (installId.endsWith('_probe') || installId.startsWith('probe_')) return true;
3254
+ if (metadata.probe === true || metadata.probe === '1' || metadata.probe === 'true'
3255
+ || metadata.isBot === true || metadata.isBot === 'true') {
3256
+ return true;
3257
+ }
3258
+ const markerText = [
3259
+ installId,
3260
+ metadata.utmCampaign,
3261
+ metadata.campaign,
3262
+ metadata.ctaId,
3263
+ metadata.traceId,
3264
+ metadata.visitorId,
3265
+ metadata.sessionId,
3266
+ ].filter(Boolean).join(' ');
3267
+ if (AUTOMATED_CHECKOUT_MARKER_PATTERN.test(markerText)) return true;
3268
+ const email = customerEmail || metadata.customerEmail || metadata.email || '';
3269
+ return isSyntheticOrOwnerCheckoutEmail(email);
3270
+ }
3271
+
3272
+ function filterQualifiedCheckoutFunnelEvents(entries = []) {
3273
+ if (!Array.isArray(entries) || entries.length === 0) {
3274
+ return { events: [], excludedSyntheticCheckoutSessions: 0 };
3275
+ }
3276
+ const excludedIndices = new Set();
3277
+ const checkoutRows = [];
3278
+ const identityEventTotals = new Map();
3279
+
3280
+ for (const entry of entries) {
3281
+ if (!entry) continue;
3282
+ const metadata = sanitizeMetadata(entry.metadata);
3283
+ const key = (
3284
+ entry.visitorId || entry.sessionId || entry.acquisitionId ||
3285
+ metadata.visitorId || metadata.sessionId || metadata.acquisitionId || metadata.customerId ||
3286
+ (entry.installId && entry.installId !== 'unknown' ? entry.installId : '')
3287
+ );
3288
+ if (key) identityEventTotals.set(key, (identityEventTotals.get(key) || 0) + 1);
3289
+ }
3290
+
3291
+ entries.forEach((entry, idx) => {
3292
+ if (!entry || entry.stage !== 'acquisition' || entry.event !== 'checkout_session_created') return;
3293
+ const metadata = sanitizeMetadata(entry.metadata);
3294
+ const merged = { ...metadata, ...sanitizeMetadata(entry) };
3295
+ const email = entry.customerEmail || entry.email || metadata.customerEmail || metadata.email || '';
3296
+ if (isAutomatedCheckoutRequest(merged, email)) {
3297
+ excludedIndices.add(idx);
3298
+ return;
3299
+ }
3300
+ const ms = Date.parse(entry.timestamp || '');
3301
+ const identityKey = (
3302
+ entry.visitorId || entry.sessionId || entry.acquisitionId ||
3303
+ metadata.visitorId || metadata.sessionId || metadata.acquisitionId || metadata.customerId ||
3304
+ (entry.installId && entry.installId !== 'unknown' ? entry.installId : '')
3305
+ ) || '__anon__';
3306
+ const hasCustomer = Boolean(metadata.customerId);
3307
+ const hasBuyerEmail = Boolean(String(email || '').trim()) && !isSyntheticOrOwnerCheckoutEmail(email);
3308
+ const totalIdentityEvents = identityKey === '__anon__' ? 0 : (identityEventTotals.get(identityKey) || 0);
3309
+ const offerKey = [
3310
+ metadata.packId || '',
3311
+ metadata.planId || '',
3312
+ metadata.billingCycle || '',
3313
+ metadata.ctaId || '',
3314
+ ].join(':');
3315
+ checkoutRows.push({
3316
+ idx,
3317
+ ms,
3318
+ identityKey,
3319
+ hasCustomer,
3320
+ hasBuyerEmail,
3321
+ totalIdentityEvents,
3322
+ offerKey,
3323
+ });
3324
+ });
3325
+
3326
+ const validTimed = checkoutRows
3327
+ .filter((row) => Number.isFinite(row.ms))
3328
+ .sort((a, b) => a.ms - b.ms);
3329
+ const byIdentity = new Map();
3330
+ for (const row of validTimed) {
3331
+ if (!byIdentity.has(row.identityKey)) byIdentity.set(row.identityKey, []);
3332
+ byIdentity.get(row.identityKey).push(row);
3333
+ }
3334
+
3335
+ for (const [identityKey, rows] of byIdentity.entries()) {
3336
+ for (let i = 0; i < rows.length; i += 1) {
3337
+ const base = rows[i];
3338
+ const window60 = [base];
3339
+ const window30Anon = identityKey === '__anon__' ? [base] : [];
3340
+ for (let j = i + 1; j < rows.length; j += 1) {
3341
+ const delta = rows[j].ms - base.ms;
3342
+ if (delta > 60 * 1000) break;
3343
+ window60.push(rows[j]);
3344
+ if (delta <= 30 * 1000 && identityKey === '__anon__') {
3345
+ window30Anon.push(rows[j]);
3346
+ }
3347
+ }
3348
+ const distinctOffers = new Set(window60.map((row) => row.offerKey).filter(Boolean));
3349
+ if (window60.length >= 3 && (distinctOffers.size >= 2 || identityKey === '__anon__')) {
3350
+ for (const row of window60) excludedIndices.add(row.idx);
3351
+ }
3352
+ if (window30Anon.length >= 2) {
3353
+ for (const row of window30Anon) excludedIndices.add(row.idx);
3354
+ }
3355
+ }
3356
+ }
3357
+
3358
+ const ephemeralSingleHits = validTimed.filter((row) => (
3359
+ !excludedIndices.has(row.idx) &&
3360
+ !row.hasCustomer &&
3361
+ !row.hasBuyerEmail &&
3362
+ row.totalIdentityEvents <= 1 &&
3363
+ (byIdentity.get(row.identityKey)?.length || 0) <= 1
3364
+ ));
3365
+ for (let i = 0; i < ephemeralSingleHits.length; i += 1) {
3366
+ const sweep60 = [ephemeralSingleHits[i]];
3367
+ for (let j = i + 1; j < ephemeralSingleHits.length; j += 1) {
3368
+ if (ephemeralSingleHits[j].ms - ephemeralSingleHits[i].ms > 60 * 1000) break;
3369
+ sweep60.push(ephemeralSingleHits[j]);
3370
+ }
3371
+ const distinctOffers = new Set(sweep60.map((row) => row.offerKey).filter(Boolean));
3372
+ if (sweep60.length >= 3 && distinctOffers.size >= 3) {
3373
+ for (const row of sweep60) excludedIndices.add(row.idx);
3374
+ }
3375
+ }
3376
+ if (excludedIndices.size === 0) {
3377
+ return { events: entries, excludedSyntheticCheckoutSessions: 0 };
3378
+ }
3379
+ return {
3380
+ events: entries.filter((_entry, idx) => !excludedIndices.has(idx)),
3381
+ excludedSyntheticCheckoutSessions: excludedIndices.size,
3382
+ };
3383
+ }
3384
+
3385
+ // Secret (sk_live_) and restricted (rk_live_) keys are both live.
3386
+ function isLiveStripeKey(key) {
3387
+ return /^(sk|rk)_live_/.test(String(key || ''));
3388
+ }
3389
+
2879
3390
  async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, installId, traceId, packId = null, metadata = {}, appOrigin } = {}) {
2880
3391
  const resolvedTraceId = traceId || metadata.traceId || createTraceId('checkout');
2881
3392
  const baseCheckoutMetadata = sanitizeMetadata({
@@ -2923,6 +3434,13 @@ async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, ins
2923
3434
  return { sessionId: localSessionId, url: null, localMode: true, traceId: resolvedTraceId, metadata: checkoutMetadata };
2924
3435
  }
2925
3436
 
3437
+ if (isAutomatedCheckoutRequest(checkoutMetadata, customerEmail) && isLiveStripeKey(CONFIG.STRIPE_SECRET_KEY)) {
3438
+ const blockedErr = new Error('Refusing to open a live Stripe Checkout session for a probe or test request. Use a test-mode key.');
3439
+ blockedErr.statusCode = 403;
3440
+ blockedErr.code = 'AUTOMATED_CHECKOUT_BLOCKED';
3441
+ throw blockedErr;
3442
+ }
3443
+
2926
3444
  const stripe = getStripeClient();
2927
3445
 
2928
3446
  if (!packId) {
@@ -2937,17 +3455,7 @@ async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, ins
2937
3455
  packId,
2938
3456
  appOrigin,
2939
3457
  });
2940
- let session;
2941
- try {
2942
- session = await stripe.checkout.sessions.create(sessionPayload);
2943
- } catch (err) {
2944
- if (!sessionPayload.branding_settings || !String(err && err.message).includes('branding_settings')) {
2945
- throw err;
2946
- }
2947
- const fallbackPayload = { ...sessionPayload };
2948
- delete fallbackPayload.branding_settings;
2949
- session = await stripe.checkout.sessions.create(fallbackPayload);
2950
- }
3458
+ const session = await createSessionDroppingRejectedOptionals(stripe, sessionPayload);
2951
3459
 
2952
3460
  appendFunnelEvent({
2953
3461
  stage: 'acquisition',
@@ -2960,6 +3468,23 @@ async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, ins
2960
3468
  return { sessionId: session.id, url: session.url, localMode: false, traceId: resolvedTraceId, metadata: checkoutMetadata };
2961
3469
  }
2962
3470
 
3471
+ // Optional fields Stripe can refuse for account-level reasons (branding not set
3472
+ // up; Checkout promotional-consent terms not yet accepted in the Dashboard).
3473
+ // Dropping one must never block a buyer from reaching checkout.
3474
+ const OPTIONAL_CHECKOUT_FIELDS = ['branding_settings', 'consent_collection'];
3475
+
3476
+ async function createSessionDroppingRejectedOptionals(stripe, payload) {
3477
+ try {
3478
+ return await stripe.checkout.sessions.create(payload);
3479
+ } catch (err) {
3480
+ const message = String(err?.message || '');
3481
+ const rejected = OPTIONAL_CHECKOUT_FIELDS.find((field) => field in payload && message.includes(field));
3482
+ if (!rejected) throw err;
3483
+ const { [rejected]: _dropped, ...rest } = payload;
3484
+ return createSessionDroppingRejectedOptionals(stripe, rest);
3485
+ }
3486
+ }
3487
+
2963
3488
  function buildCheckoutSessionPayload({ successUrl, cancelUrl, customerEmail, checkoutMetadata, packId = null, appOrigin } = {}) {
2964
3489
  const pack = packId ? CONFIG.CREDIT_PACKS[packId] : null;
2965
3490
  const checkoutSelection = pack ? null : resolveSubscriptionCheckoutSelection(checkoutMetadata);
@@ -3007,7 +3532,12 @@ function buildCheckoutSessionPayload({ successUrl, cancelUrl, customerEmail, che
3007
3532
  mode: pack ? 'payment' : 'subscription',
3008
3533
  line_items: lineItems,
3009
3534
  allow_promotion_codes: true,
3535
+ billing_address_collection: 'auto',
3536
+ tax_id_collection: { enabled: true },
3010
3537
  after_expiration: { recovery: { enabled: true, allow_promotion_codes: true } },
3538
+ // Stripe only emails an abandoned-cart recovery link to buyers who gave
3539
+ // promotional consent; without this, recovery above never reaches anyone.
3540
+ consent_collection: { promotions: 'auto' },
3011
3541
  branding_settings: buildCheckoutBrandingSettings(appOrigin),
3012
3542
  metadata: serializeStripeMetadata({
3013
3543
  ...checkoutMetadata,
@@ -3038,10 +3568,12 @@ async function getCheckoutSessionStatus(sessionId) {
3038
3568
  const session = store.sessions[sessionId];
3039
3569
  if (!session) return { found: false };
3040
3570
  const diagnosticOrder = isDiagnosticCheckoutSession(session);
3571
+ const customerEmail = session.customer_details?.email || session.customer_email || '';
3041
3572
  const provisioningGrant = resolveCheckoutProvisioningGrant(session);
3042
3573
  const provisioned = provisioningGrant.allowed
3043
3574
  ? provisionApiKey(session.customer, {
3044
3575
  installId: session.metadata?.installId,
3576
+ customerEmail,
3045
3577
  credits: provisioningGrant.credits,
3046
3578
  orderId: session.id,
3047
3579
  subscriptionId: session.subscription,
@@ -3051,7 +3583,6 @@ async function getCheckoutSessionStatus(sessionId) {
3051
3583
  source: 'local_checkout_lookup'
3052
3584
  })
3053
3585
  : null;
3054
- const customerEmail = session.customer_details?.email || session.customer_email || '';
3055
3586
  const customerName = session.customer_details?.name || null;
3056
3587
  const trialEndAt = computeTrialEndAt(session);
3057
3588
  const trialEmail = !provisioned || !provisioned.key
@@ -3119,6 +3650,7 @@ async function getCheckoutSessionStatus(sessionId) {
3119
3650
  const provisioned = provisioningGrant.allowed
3120
3651
  ? provisionApiKey(customerId, {
3121
3652
  installId,
3653
+ customerEmail,
3122
3654
  credits: provisioningGrant.credits,
3123
3655
  orderId: session.id,
3124
3656
  subscriptionId: session.subscription,
@@ -3179,6 +3711,90 @@ async function getCheckoutSessionStatus(sessionId) {
3179
3711
  }
3180
3712
  }
3181
3713
 
3714
+ async function createBillingPortalSession({ customerId, apiKey, sessionId, customerEmail, returnUrl } = {}) {
3715
+ let resolvedCustomerId = normalizeText(customerId);
3716
+
3717
+ if (!resolvedCustomerId && apiKey) {
3718
+ const keyInfo = validateApiKey(apiKey);
3719
+ if (keyInfo && keyInfo.valid && keyInfo.customerId) {
3720
+ resolvedCustomerId = normalizeText(keyInfo.customerId);
3721
+ }
3722
+ }
3723
+
3724
+ if (!resolvedCustomerId && sessionId) {
3725
+ if (LOCAL_MODE()) {
3726
+ const store = loadLocalCheckoutSessions();
3727
+ const localSession = store.sessions?.[sessionId] || store[sessionId];
3728
+ if (localSession && localSession.customer) {
3729
+ resolvedCustomerId = normalizeText(localSession.customer);
3730
+ }
3731
+ } else {
3732
+ try {
3733
+ const stripe = getStripeClient();
3734
+ const checkoutSession = await stripe.checkout.sessions.retrieve(sessionId);
3735
+ if (checkoutSession && checkoutSession.customer) {
3736
+ resolvedCustomerId = normalizeText(checkoutSession.customer);
3737
+ }
3738
+ } catch {
3739
+ // Continue to other lookup methods
3740
+ }
3741
+ }
3742
+ }
3743
+
3744
+ if (!resolvedCustomerId && customerEmail) {
3745
+ const normalizedEmail = normalizeEmail(customerEmail);
3746
+ const store = loadKeyStore();
3747
+ for (const meta of Object.values(store.keys || {})) {
3748
+ if (meta && normalizeEmail(meta.customerEmail || meta.email) === normalizedEmail && meta.customerId) {
3749
+ resolvedCustomerId = normalizeText(meta.customerId);
3750
+ break;
3751
+ }
3752
+ }
3753
+ }
3754
+
3755
+ if (resolvedCustomerId && resolvedCustomerId.startsWith('stripe:')) {
3756
+ resolvedCustomerId = resolvedCustomerId.slice(7);
3757
+ }
3758
+
3759
+ const effectiveReturnUrl = returnUrl || `${process.env.THUMBGATE_PUBLIC_APP_ORIGIN || 'https://thumbgate.ai'}/`;
3760
+
3761
+ if (LOCAL_MODE()) {
3762
+ if (!resolvedCustomerId && (apiKey || sessionId || customerEmail)) {
3763
+ resolvedCustomerId = 'cus_mock_local';
3764
+ }
3765
+ if (!resolvedCustomerId) {
3766
+ const err = new Error('A valid license key, session ID, or customer ID is required to access the billing portal.');
3767
+ err.statusCode = 400;
3768
+ throw err;
3769
+ }
3770
+ return {
3771
+ url: `${effectiveReturnUrl}?billing=portal&customer=${encodeURIComponent(resolvedCustomerId)}`,
3772
+ id: `bps_mock_${crypto.randomBytes(8).toString('hex')}`,
3773
+ customerId: resolvedCustomerId,
3774
+ localMode: true,
3775
+ };
3776
+ }
3777
+
3778
+ if (!resolvedCustomerId || !resolvedCustomerId.startsWith('cus_')) {
3779
+ const err = new Error('A valid Stripe customer ID (cus_...) is required to access the billing portal.');
3780
+ err.statusCode = 400;
3781
+ throw err;
3782
+ }
3783
+
3784
+ const stripe = getStripeClient();
3785
+ const portalSession = await stripe.billingPortal.sessions.create({
3786
+ customer: resolvedCustomerId,
3787
+ return_url: effectiveReturnUrl,
3788
+ });
3789
+
3790
+ return {
3791
+ url: portalSession.url,
3792
+ id: portalSession.id,
3793
+ customerId: resolvedCustomerId,
3794
+ localMode: false,
3795
+ };
3796
+ }
3797
+
3182
3798
  function provisionApiKey(customerId, opts = {}) {
3183
3799
  if (!customerId || typeof customerId !== 'string') throw new Error('customerId is required');
3184
3800
  return withKeyStoreLock(() => {
@@ -3258,13 +3874,19 @@ function provisionApiKey(customerId, opts = {}) {
3258
3874
  }
3259
3875
 
3260
3876
  const creditsToAdd = normalizeInteger(opts.credits);
3877
+ const normalizedCustomerEmail = normalizeEmail(opts.customerEmail);
3261
3878
  if (activeCustomerKey) {
3262
3879
  const key = activeCustomerKey[0];
3263
3880
  const meta = activeCustomerKey[1];
3264
3881
  if (opts.installId && !meta.installId) meta.installId = opts.installId;
3882
+ if (normalizedCustomerEmail && !meta.customerEmail) meta.customerEmail = normalizedCustomerEmail;
3883
+ if (opts.plan) meta.plan = normalizeText(opts.plan);
3884
+ if (opts.tier) meta.tier = normalizeText(opts.tier);
3265
3885
  if (opts.entitlementKind === 'subscription') {
3266
3886
  meta.remainingCredits = null;
3267
3887
  meta.entitlementKind = 'subscription';
3888
+ if (String(meta.plan || '').toLowerCase() === 'free') meta.plan = normalizeText(opts.plan) || 'pro';
3889
+ if (String(meta.tier || '').toLowerCase() === 'free') meta.tier = normalizeText(opts.tier) || 'Pro';
3268
3890
  if (subscriptionId) meta.subscriptionId = subscriptionId;
3269
3891
  } else if (creditsToAdd !== null && meta.remainingCredits !== null) {
3270
3892
  meta.remainingCredits = (meta.remainingCredits || 0) + creditsToAdd;
@@ -3282,11 +3904,15 @@ function provisionApiKey(customerId, opts = {}) {
3282
3904
  const createdAt = new Date().toISOString();
3283
3905
  store.keys[key] = {
3284
3906
  customerId,
3907
+ customerEmail: normalizedCustomerEmail || null,
3285
3908
  active: true,
3286
3909
  usageCount: 0,
3287
3910
  createdAt,
3288
3911
  installId: opts.installId || null,
3289
3912
  source: opts.source || 'provision',
3913
+ plan: normalizeText(opts.plan) || null,
3914
+ tier: normalizeText(opts.tier) || null,
3915
+ firstBlockAt: normalizeText(opts.firstBlockAt) || null,
3290
3916
  subscriptionId: subscriptionId || null,
3291
3917
  entitlementKind: opts.entitlementKind || null,
3292
3918
  remainingCredits: creditsToAdd, // null means unlimited (standard subscription)
@@ -3311,12 +3937,16 @@ function rotateApiKey(oldKey) {
3311
3937
  const newKey = `tg_${crypto.randomBytes(16).toString('hex')}`;
3312
3938
  store.keys[newKey] = {
3313
3939
  customerId: meta.customerId,
3940
+ customerEmail: meta.customerEmail || null,
3314
3941
  active: true,
3315
3942
  usageCount: 0,
3316
3943
  createdAt: new Date().toISOString(),
3317
3944
  installId: meta.installId,
3318
3945
  source: 'rotation',
3319
3946
  replacedKey: oldKey,
3947
+ plan: meta.plan || null,
3948
+ tier: meta.tier || null,
3949
+ firstBlockAt: meta.firstBlockAt || null,
3320
3950
  subscriptionId: meta.subscriptionId || null,
3321
3951
  entitlementKind: meta.entitlementKind || null,
3322
3952
  remainingCredits: meta.remainingCredits,
@@ -3327,6 +3957,56 @@ function rotateApiKey(oldKey) {
3327
3957
  });
3328
3958
  }
3329
3959
 
3960
+ async function resolvePaidEntitlementForEmail(email) {
3961
+ const normalizedEmail = normalizeEmail(email);
3962
+ if (!normalizedEmail) return { entitled: false, apiKey: null, customerId: null };
3963
+ const store = loadKeyStore();
3964
+ const customerIds = new Set([normalizedEmail]);
3965
+ const orderIds = new Set();
3966
+ for (const ledgerPath of [CONFIG.TRIAL_EMAIL_LEDGER_PATH, CONFIG.ORDER_EMAIL_LEDGER_PATH]) {
3967
+ for (const row of loadJsonlRecords(ledgerPath)) {
3968
+ if (row && normalizeEmail(row.customerEmail) === normalizedEmail) {
3969
+ if (row.customerId) customerIds.add(String(row.customerId).trim());
3970
+ if (row.sessionId) orderIds.add(String(row.sessionId).trim());
3971
+ }
3972
+ }
3973
+ }
3974
+ for (const sess of Object.values(store.sessions || {})) {
3975
+ if (normalizeEmail(sess && (sess.customer_details?.email || sess.customer_email)) === normalizedEmail) {
3976
+ if (sess.customer) customerIds.add(String(sess.customer).trim());
3977
+ if (sess.id) orderIds.add(String(sess.id).trim());
3978
+ }
3979
+ }
3980
+ for (const [key, meta] of Object.entries(store.keys || {})) {
3981
+ if (!meta || !meta.active || (meta.remainingCredits != null && meta.remainingCredits <= 0)) continue;
3982
+ const match = normalizeEmail(meta.customerEmail) === normalizedEmail
3983
+ || (meta.customerId && customerIds.has(String(meta.customerId).trim()))
3984
+ || (Array.isArray(meta.fulfilledOrderIds) && meta.fulfilledOrderIds.some((id) => orderIds.has(String(id).trim())));
3985
+ if (match) return { entitled: true, apiKey: key, customerId: meta.customerId };
3986
+ }
3987
+ try {
3988
+ const stripe = getStripeClient();
3989
+ if (stripe) {
3990
+ const listed = await withTimeout(stripe.customers.list({ email: normalizedEmail, limit: 5 }), 3000);
3991
+ for (const customer of listed?.data || []) {
3992
+ if (!customer?.id) continue;
3993
+ const subs = await withTimeout(stripe.subscriptions.list({ customer: customer.id, status: 'all', limit: 10 }), 3000);
3994
+ const activeSub = (subs?.data || []).find((s) => s && (s.status === 'active' || s.status === 'trialing'));
3995
+ if (activeSub) {
3996
+ const p = provisionApiKey(customer.id, {
3997
+ customerEmail: normalizedEmail,
3998
+ entitlementKind: 'subscription',
3999
+ subscriptionId: activeSub.id,
4000
+ source: 'google_sso_stripe_entitlement',
4001
+ });
4002
+ if (p?.key) return { entitled: true, apiKey: p.key, customerId: customer.id };
4003
+ }
4004
+ }
4005
+ }
4006
+ } catch {}
4007
+ return { entitled: false, apiKey: null, customerId: null };
4008
+ }
4009
+
3330
4010
  function validateApiKey(key) {
3331
4011
  if (!key) return { valid: false };
3332
4012
  const store = loadKeyStore();
@@ -3340,13 +4020,68 @@ function validateApiKey(key) {
3340
4020
  return {
3341
4021
  valid: true,
3342
4022
  customerId: meta.customerId,
4023
+ customerEmail: meta.customerEmail || null,
3343
4024
  usageCount: meta.usageCount || 0,
3344
4025
  installId: meta.installId || null,
4026
+ plan: meta.plan || null,
4027
+ tier: meta.tier || null,
4028
+ firstBlockAt: meta.firstBlockAt || null,
3345
4029
  createdAt: meta.createdAt,
3346
4030
  metadata: meta,
3347
4031
  };
3348
4032
  }
3349
4033
 
4034
+ function pickEarlierIso(a, b) {
4035
+ if (!a) return b || null;
4036
+ if (!b) return a;
4037
+ const ta = Date.parse(a);
4038
+ const tb = Date.parse(b);
4039
+ if (!Number.isFinite(ta)) return b;
4040
+ if (!Number.isFinite(tb)) return a;
4041
+ return ta <= tb ? a : b;
4042
+ }
4043
+
4044
+ function recordAccountFirstBlock(selector = {}, options = {}) {
4045
+ const stamp = normalizeText(options.firstBlockAt) || new Date().toISOString();
4046
+ const targetEmail = normalizeEmail(selector.email);
4047
+ const targetCustomerId = normalizeText(selector.customerId);
4048
+ const targetInstallId = selector.allowInstallIdOnly === true ? normalizeText(selector.installId) : null;
4049
+ const targetKey = normalizeText(selector.apiKey);
4050
+ return withKeyStoreLock(() => {
4051
+ const store = loadKeyStore();
4052
+ let updatedCount = 0;
4053
+ let resolvedFirstBlockAt = stamp;
4054
+ const customerIds = [];
4055
+ const customerEmails = [];
4056
+ for (const [key, meta] of Object.entries(store.keys || {})) {
4057
+ if (!meta) continue;
4058
+ const planLower = String(meta.plan || '').toLowerCase();
4059
+ const tierLower = String(meta.tier || '').toLowerCase();
4060
+ const matches = (targetKey && key === targetKey)
4061
+ || (targetCustomerId && meta.customerId === targetCustomerId)
4062
+ || (targetEmail && normalizeEmail(meta.customerEmail) === targetEmail)
4063
+ || (targetInstallId && meta.installId === targetInstallId)
4064
+ || (selector.allActivePaid === true && meta.active && planLower !== 'free' && tierLower !== 'free');
4065
+ if (!matches) continue;
4066
+ const createdMs = meta.createdAt ? Date.parse(meta.createdAt) : NaN;
4067
+ const stampMs = Date.parse(stamp);
4068
+ const boundedStamp = (Number.isFinite(createdMs) && Number.isFinite(stampMs) && stampMs < createdMs)
4069
+ ? meta.createdAt
4070
+ : stamp;
4071
+ const nextAt = pickEarlierIso(meta.firstBlockAt, boundedStamp);
4072
+ if (meta.firstBlockAt !== nextAt || (options.installId && !meta.installId)) {
4073
+ meta.firstBlockAt = nextAt;
4074
+ if (options.installId && !meta.installId) meta.installId = normalizeText(options.installId);
4075
+ updatedCount += 1;
4076
+ }
4077
+ resolvedFirstBlockAt = pickEarlierIso(resolvedFirstBlockAt, meta.firstBlockAt);
4078
+ if (meta.customerId) customerIds.push(meta.customerId);
4079
+ if (meta.customerEmail) customerEmails.push(normalizeEmail(meta.customerEmail));
4080
+ }
4081
+ if (updatedCount > 0) saveKeyStore(store);
4082
+ return { updatedCount, firstBlockAt: resolvedFirstBlockAt, customerIds, customerEmails };
4083
+ });
4084
+ }
3350
4085
  function recordUsage(key) {
3351
4086
  return withKeyStoreLock(() => {
3352
4087
  const store = loadKeyStore();
@@ -3494,6 +4229,7 @@ async function handleWebhook(rawBody, signature) {
3494
4229
  const result = provisioningGrant.allowed
3495
4230
  ? provisionApiKey(customerId, {
3496
4231
  installId,
4232
+ customerEmail,
3497
4233
  credits: provisioningGrant.credits,
3498
4234
  orderId: session.id,
3499
4235
  subscriptionId: session.subscription,
@@ -3806,61 +4542,76 @@ async function readPayPalJsonResponse(response) {
3806
4542
  }
3807
4543
  }
3808
4544
 
3809
- async function verifyPayPalWebhookSignature({
3810
- rawBody,
3811
- headers,
3812
- fetchImpl = globalThis.fetch,
3813
- now = new Date().toISOString(),
3814
- ...configOverrides
3815
- } = {}) {
3816
- const config = resolvePayPalWebhookVerifierConfig(configOverrides);
3817
- if (!config.configured) return { verified: false, reason: config.reason };
3818
- if (typeof fetchImpl !== 'function') return { verified: false, reason: 'paypal_verification_fetch_unavailable' };
4545
+ function parseAndValidatePayPalWebhookEvent(rawBody) {
3819
4546
  const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody || '');
3820
- if (body.length === 0) return { verified: false, reason: 'missing_paypal_webhook_body' };
3821
- if (body.length > PAYPAL_WEBHOOK_MAX_BYTES) return { verified: false, reason: 'paypal_webhook_body_too_large' };
4547
+ if (body.length === 0) return { ok: false, reason: 'missing_paypal_webhook_body' };
4548
+ if (body.length > PAYPAL_WEBHOOK_MAX_BYTES) return { ok: false, reason: 'paypal_webhook_body_too_large' };
3822
4549
 
3823
4550
  let event;
3824
4551
  try {
3825
4552
  event = JSON.parse(body.toString('utf8'));
3826
4553
  } catch {
3827
- return { verified: false, reason: 'invalid_paypal_webhook_json' };
4554
+ return { ok: false, reason: 'invalid_paypal_webhook_json' };
3828
4555
  }
3829
- const eventId = normalizeText(event && event.id);
3830
- const eventType = normalizeText(event && event.event_type);
3831
- const eventCreatedAt = normalizeText(event && event.create_time);
4556
+ const eventId = normalizeText(event?.id);
4557
+ const eventType = normalizeText(event?.event_type);
4558
+ const eventCreatedAt = normalizeText(event?.create_time);
3832
4559
  const eventCreatedMs = new Date(eventCreatedAt || '').getTime();
3833
- if (!eventId || eventId.length > 128 || !Number.isFinite(eventCreatedMs) ||
3834
- !event.resource || typeof event.resource !== 'object' || Array.isArray(event.resource) ||
3835
- !PAYPAL_REVENUE_WEBHOOK_EVENT_TYPES.has(eventType)) {
3836
- return { verified: false, reason: 'invalid_or_unsupported_paypal_webhook_event' };
4560
+ const resourceValid = Boolean(event?.resource && typeof event.resource === 'object' && !Array.isArray(event.resource));
4561
+ if (!eventId || eventId.length > 128 || !Number.isFinite(eventCreatedMs) || !resourceValid || !PAYPAL_REVENUE_WEBHOOK_EVENT_TYPES.has(eventType)) {
4562
+ return { ok: false, reason: 'invalid_or_unsupported_paypal_webhook_event' };
3837
4563
  }
4564
+ return { ok: true, event, eventId, eventType, eventCreatedAt };
4565
+ }
3838
4566
 
4567
+ function validatePayPalTransmission(headers, now) {
3839
4568
  const transmission = normalizePayPalTransmissionHeaders(headers);
3840
4569
  if (Object.values(transmission).some((value) => !value)) {
3841
- return { verified: false, reason: 'missing_paypal_transmission_headers' };
4570
+ return { ok: false, reason: 'missing_paypal_transmission_headers' };
3842
4571
  }
3843
4572
  let certUrl;
3844
4573
  try {
3845
4574
  certUrl = new URL(transmission.certUrl);
3846
4575
  } catch {
3847
- return { verified: false, reason: 'invalid_paypal_cert_url' };
4576
+ return { ok: false, reason: 'invalid_paypal_cert_url' };
3848
4577
  }
3849
- if (certUrl.protocol !== 'https:') return { verified: false, reason: 'invalid_paypal_cert_url' };
4578
+ if (certUrl.protocol !== 'https:') return { ok: false, reason: 'invalid_paypal_cert_url' };
3850
4579
  const nowMs = new Date(now).getTime();
3851
4580
  const transmissionMs = new Date(transmission.transmissionTime).getTime();
3852
4581
  if (!Number.isFinite(nowMs) || !Number.isFinite(transmissionMs) ||
3853
4582
  transmissionMs > nowMs + PAYPAL_WEBHOOK_FUTURE_SKEW_MS ||
3854
4583
  nowMs - transmissionMs > PAYPAL_WEBHOOK_REPLAY_WINDOW_MS) {
3855
- return { verified: false, reason: 'stale_or_future_paypal_transmission' };
4584
+ return { ok: false, reason: 'stale_or_future_paypal_transmission' };
3856
4585
  }
4586
+ return { ok: true, transmission };
4587
+ }
4588
+
4589
+ async function verifyPayPalWebhookSignature({
4590
+ rawBody,
4591
+ headers,
4592
+ fetchImpl = globalThis.fetch,
4593
+ now = new Date().toISOString(),
4594
+ ...configOverrides
4595
+ } = {}) {
4596
+ const config = resolvePayPalWebhookVerifierConfig(configOverrides);
4597
+ if (!config.configured) return { verified: false, reason: config.reason };
4598
+ if (typeof fetchImpl !== 'function') return { verified: false, reason: 'paypal_verification_fetch_unavailable' };
4599
+
4600
+ const parsedEvent = parseAndValidatePayPalWebhookEvent(rawBody);
4601
+ if (!parsedEvent.ok) return { verified: false, reason: parsedEvent.reason };
4602
+ const { event, eventId, eventType, eventCreatedAt } = parsedEvent;
3857
4603
 
4604
+ const parsedTransmission = validatePayPalTransmission(headers, now);
4605
+ if (!parsedTransmission.ok) return { verified: false, reason: parsedTransmission.reason };
4606
+ const { transmission } = parsedTransmission;
4607
+
4608
+ const basicCredentials = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString('base64');
3858
4609
  let tokenResponse;
3859
4610
  try {
3860
4611
  tokenResponse = await withTimeout(fetchImpl(new URL('/v1/oauth2/token', config.apiBaseUrl), {
3861
4612
  method: 'POST',
3862
4613
  headers: {
3863
- Authorization: `Basic ${Buffer.from(`${config.clientId}:${config.clientSecret}`).toString('base64')}`,
4614
+ Authorization: `Basic ${basicCredentials}`,
3864
4615
  Accept: 'application/json',
3865
4616
  'Content-Type': 'application/x-www-form-urlencoded',
3866
4617
  },
@@ -3870,7 +4621,7 @@ async function verifyPayPalWebhookSignature({
3870
4621
  return { verified: false, reason: 'paypal_oauth_request_failed' };
3871
4622
  }
3872
4623
  const tokenPayload = await readPayPalJsonResponse(tokenResponse);
3873
- if (!tokenResponse.ok || !normalizeText(tokenPayload && tokenPayload.access_token)) {
4624
+ if (!tokenResponse.ok || !normalizeText(tokenPayload?.access_token)) {
3874
4625
  return { verified: false, reason: 'paypal_oauth_rejected' };
3875
4626
  }
3876
4627
 
@@ -3897,13 +4648,11 @@ async function verifyPayPalWebhookSignature({
3897
4648
  return { verified: false, reason: 'paypal_signature_verification_request_failed' };
3898
4649
  }
3899
4650
  const verificationPayload = await readPayPalJsonResponse(verificationResponse);
3900
- const verificationStatus = (normalizeText(verificationPayload && verificationPayload.verification_status) || '').toUpperCase();
4651
+ const verificationStatus = (normalizeText(verificationPayload?.verification_status) || '').toUpperCase();
3901
4652
  if (!verificationResponse.ok || verificationStatus !== 'SUCCESS') {
3902
4653
  return { verified: false, reason: 'invalid_paypal_webhook_signature' };
3903
4654
  }
3904
- const paypalDebugId = normalizeText(verificationResponse.headers && verificationResponse.headers.get
3905
- ? verificationResponse.headers.get('paypal-debug-id')
3906
- : null);
4655
+ const paypalDebugId = normalizeText(verificationResponse.headers?.get?.('paypal-debug-id') || null);
3907
4656
  return {
3908
4657
  verified: true,
3909
4658
  reason: null,
@@ -3915,6 +4664,7 @@ async function verifyPayPalWebhookSignature({
3915
4664
  verificationStatus,
3916
4665
  paypalDebugId: paypalDebugId || null,
3917
4666
  webhookId: config.webhookId,
4667
+ apiBaseUrl: config.apiBaseUrl,
3918
4668
  };
3919
4669
  }
3920
4670
 
@@ -4050,7 +4800,7 @@ function recordGithubMarketplaceWebhookDelivery({
4050
4800
  } catch {
4051
4801
  return { verified: false, recorded: false, reason: 'invalid_github_webhook_json' };
4052
4802
  }
4053
- if (!event || !event.action || !event.marketplace_purchase) {
4803
+ if (!event?.action || !event?.marketplace_purchase) {
4054
4804
  return { verified: false, recorded: false, reason: 'invalid_github_marketplace_payload' };
4055
4805
  }
4056
4806
 
@@ -4093,18 +4843,19 @@ function recordGithubMarketplaceWebhookDelivery({
4093
4843
  };
4094
4844
  }
4095
4845
 
4096
- function buildGithubMarketplaceRevenueMetadata(marketplacePurchase = {}, marketplaceOrderId, planPricing = {}, provenance = {}) {
4097
- const plan = marketplacePurchase && typeof marketplacePurchase.plan === 'object'
4098
- ? marketplacePurchase.plan
4846
+ function buildGithubMarketplaceRevenueMetadata(marketplacePurchase, marketplaceOrderId, planPricing = {}, provenance = {}) {
4847
+ const purchase = marketplacePurchase || {};
4848
+ const plan = purchase && typeof purchase.plan === 'object'
4849
+ ? purchase.plan
4099
4850
  : {};
4100
4851
  return {
4101
- accountId: normalizeText(marketplacePurchase.account && marketplacePurchase.account.id),
4102
- accountType: normalizeText(marketplacePurchase.account && marketplacePurchase.account.type),
4852
+ accountId: normalizeText(purchase.account?.id),
4853
+ accountType: normalizeText(purchase.account?.type),
4103
4854
  planId: normalizeText(plan.id),
4104
4855
  planName: normalizeText(plan.name),
4105
4856
  marketplaceOrderId: normalizeText(marketplaceOrderId),
4106
- billingCycle: normalizeText(marketplacePurchase.billing_cycle ?? marketplacePurchase.billingCycle),
4107
- unitCount: normalizeInteger(marketplacePurchase.unit_count ?? marketplacePurchase.unitCount),
4857
+ billingCycle: normalizeText(purchase.billing_cycle ?? purchase.billingCycle),
4858
+ unitCount: normalizeInteger(purchase.unit_count ?? purchase.unitCount),
4108
4859
  priceModel: normalizeText(plan.price_model ?? plan.priceModel),
4109
4860
  monthlyPriceInCents: normalizeInteger(plan.monthly_price_in_cents ?? plan.monthlyPriceInCents),
4110
4861
  yearlyPriceInCents: normalizeInteger(plan.yearly_price_in_cents ?? plan.yearlyPriceInCents),
@@ -4219,8 +4970,14 @@ function handleGithubWebhook(event, provenance = {}) {
4219
4970
  }
4220
4971
 
4221
4972
  module.exports = {
4222
- CONFIG, createCheckoutSession, getCheckoutSessionStatus, provisionApiKey, rotateApiKey, validateApiKey, recordUsage, disableCustomerKeys, handleWebhook, verifyWebhookSignature, verifyGithubWebhookSignature, verifyPayPalWebhookSignature, recordGithubMarketplaceWebhookDelivery, recordPayPalWebhookDelivery, handleGithubWebhook, loadKeyStore, appendFunnelEvent, appendRevenueEvent, loadFunnelLedger, loadRevenueLedger, loadGithubMarketplaceWebhookLedger, loadPayPalWebhookLedger, loadNewsletterSubscribers, loadResolvedRevenueEvents, getFunnelAnalytics, getBusinessAnalytics, getBillingSummary, getBillingSummaryLive, getBillingSummariesLive, listStripeReconciledRevenueEvents, repairGithubMarketplaceRevenueLedger,
4973
+ getStripeClient, classifyRevenueRecord, summarizeExternalRevenue, buildBillingSourceDiagnostics,
4974
+ withStripeReadSlot, getBillingAnalyticsReadPaths,
4975
+ _mergeRevenueEvents: mergeRevenueEvents,
4976
+ _buildStripeReconciledRevenueEvent: buildStripeReconciledRevenueEvent,
4977
+ CONFIG, createCheckoutSession, isAutomatedCheckoutRequest, isSyntheticOrOwnerCheckoutEmail, createBillingPortalSession, getCheckoutSessionStatus, provisionApiKey, resolvePaidEntitlementForEmail, rotateApiKey, validateApiKey, recordUsage, recordAccountFirstBlock, disableCustomerKeys, handleWebhook, verifyWebhookSignature, verifyGithubWebhookSignature, verifyPayPalWebhookSignature, recordGithubMarketplaceWebhookDelivery, recordPayPalWebhookDelivery, handleGithubWebhook, loadKeyStore, appendFunnelEvent, appendRevenueEvent, loadFunnelLedger, loadRevenueLedger, loadGithubMarketplaceWebhookLedger, loadPayPalWebhookLedger, loadNewsletterSubscribers, loadResolvedRevenueEvents, getFunnelAnalytics, getBusinessAnalytics, getBillingSummary, getBillingSummaryLive, getBillingSummariesLive, listStripeReconciledRevenueEvents, repairGithubMarketplaceRevenueLedger,
4223
4978
  _buildCheckoutSessionPayload: buildCheckoutSessionPayload,
4979
+ _filterQualifiedCheckoutFunnelEvents: filterQualifiedCheckoutFunnelEvents,
4980
+ _createSessionDroppingRejectedOptionals: createSessionDroppingRejectedOptionals,
4224
4981
  _buildTrialActivationEmail: buildTrialActivationEmail,
4225
4982
  _sendTrialActivationEmail: sendTrialActivationEmail,
4226
4983
  _isDiagnosticCheckoutSession: isDiagnosticCheckoutSession,