thumbgate 1.40.3 → 1.40.5

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 (47) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/mcp/server-card.json +1 -1
  3. package/README.md +2 -2
  4. package/adapters/claude/.mcp.json +3 -3
  5. package/adapters/forge/forge.yaml +3 -3
  6. package/adapters/future-agi/.mcp.json +1 -1
  7. package/adapters/future-agi/config.toml +1 -1
  8. package/adapters/future-agi/opencode.json +1 -1
  9. package/adapters/herdr/herdr-plugin.toml +2 -2
  10. package/adapters/mcp/server-stdio.js +1 -1
  11. package/adapters/opencode/opencode.json +1 -1
  12. package/config/github-about.json +1 -1
  13. package/config/post-deploy-marketing-pages.json +1 -1
  14. package/package.json +27 -6
  15. package/public/about.html +2 -2
  16. package/public/admin.html +329 -47
  17. package/public/case-studies.html +1 -0
  18. package/public/dashboard.html +7 -6
  19. package/public/diagnostic.html +15 -12
  20. package/public/index.html +210 -78
  21. package/public/install.html +9 -8
  22. package/public/js/connect-panel.js +437 -0
  23. package/public/numbers.html +2 -2
  24. package/public/preview.html +42 -0
  25. package/public/pricing.html +55 -10
  26. package/scripts/auto-promote-gates.js +16 -1
  27. package/scripts/billing.js +189 -4
  28. package/scripts/cap-hit-counter.js +47 -0
  29. package/scripts/checkout-human-gate.js +248 -0
  30. package/scripts/checkout-session-count.js +115 -0
  31. package/scripts/feedback-loop.js +4 -0
  32. package/scripts/first-block-upsell.js +187 -0
  33. package/scripts/gates-engine.js +37 -108
  34. package/scripts/human-feedback.js +20 -1
  35. package/scripts/ops-log.js +91 -0
  36. package/scripts/ops-report.js +174 -0
  37. package/scripts/owner-admin.js +373 -26
  38. package/scripts/owner-telemetry.js +142 -0
  39. package/scripts/rate-limiter.js +8 -2
  40. package/scripts/statusline-human-counts.js +71 -8
  41. package/scripts/statusline.sh +15 -2
  42. package/scripts/telemetry-analytics.js +4 -0
  43. package/scripts/tool-contract-validator.js +13 -3
  44. package/scripts/tool-registry.js +1 -1
  45. package/scripts/utm-source-summary.js +88 -0
  46. package/server.json +2 -2
  47. package/src/api/server.js +607 -107
@@ -625,6 +625,7 @@ function promote(feedbackLogPath, options) {
625
625
  ...inertRemoved.map((e) => ({ type: 'quarantined-inert-prose', gateId: e.id, pattern: e.pattern })),
626
626
  ];
627
627
 
628
+ let upgradeLine;
628
629
  for (const group of Object.values(groups)) {
629
630
  if (group.count < WARN_THRESHOLD) continue;
630
631
 
@@ -659,6 +660,10 @@ function promote(feedbackLogPath, options) {
659
660
  }
660
661
  // Update occurrence count even if no action change
661
662
  data.gates[existingIdx].occurrences = group.count;
663
+ // The deny text quotes the count; keep it in step so a block does not say "1 occurrences".
664
+ if (String(data.gates[existingIdx].message || '').startsWith('Auto-promoted ')) {
665
+ data.gates[existingIdx].message = buildGateRule(group, data.gates[existingIdx].action).message;
666
+ }
662
667
  continue;
663
668
  }
664
669
 
@@ -717,6 +722,16 @@ function promote(feedbackLogPath, options) {
717
722
  occurrences: group.count,
718
723
  ...(gate.quarantined ? { falseBlocks: regression.falseBlocks, allowSampleSize: regression.allowSampleSize } : {}),
719
724
  });
725
+
726
+ // Free tier enforces only the first FREE_TIER_MAX_GATES learned rules (see gates-engine
727
+ // loadGates). A rule past that is stored but not enforced: count it and say so once.
728
+ const rateLimiter = require('./rate-limiter');
729
+ if (data.gates.length > rateLimiter.FREE_TIER_MAX_GATES && !rateLimiter.isProTier()) {
730
+ const line = rateLimiter.capUpgradeLine(group.latestContext || gate.id);
731
+ promotions.push({ type: 'cap-hit', gateId: gate.id, enforced: false, cap: rateLimiter.FREE_TIER_MAX_GATES, activeGates: data.gates.length });
732
+ require('./cap-hit-counter').recordCapHit({ feedbackDir: opts.feedbackDir, cap: rateLimiter.FREE_TIER_MAX_GATES, activeGates: data.gates.length });
733
+ if (line) upgradeLine = line;
734
+ }
720
735
  }
721
736
 
722
737
  // Log promotions
@@ -727,7 +742,7 @@ function promote(feedbackLogPath, options) {
727
742
 
728
743
  saveAutoGates(data, opts);
729
744
 
730
- return { promotions, totalGates: data.gates.length, data };
745
+ return { promotions, totalGates: data.gates.length, data, ...(upgradeLine ? { upgradeLine } : {}) };
731
746
  }
732
747
 
733
748
  function runCli(argv = process.argv.slice(2)) {
@@ -155,6 +155,11 @@ function getStripeConstructor() {
155
155
  }
156
156
  }
157
157
 
158
+ // Test seam: lets tests inject a fake Stripe client (null restores the real one).
159
+ function setStripeClientForTests(client) {
160
+ _stripeClient = client || null;
161
+ }
162
+
158
163
  function getStripeClient() {
159
164
  if (!_stripeClient) {
160
165
  if (!CONFIG.STRIPE_SECRET_KEY) {
@@ -2412,6 +2417,144 @@ async function listStripeReconciledRevenueEvents({ signal, deadline = Infinity }
2412
2417
  return result(reconciled, diagnostics.complete ? 'ok' : 'partial');
2413
2418
  }
2414
2419
 
2420
+ // How far a Stripe Checkout session got. A raw session (nobody typed an email,
2421
+ // no payment attempt) is what crawlers and probes create, so it is not a
2422
+ // qualified checkout start.
2423
+ function classifyCheckoutSessionDepth(session) {
2424
+ if (!session || typeof session !== 'object') return 'raw';
2425
+ if (session.payment_status === 'paid' || session.status === 'complete') return 'paid';
2426
+ if (normalizeText(session.payment_intent) || normalizeText(session.setup_intent)) return 'payment_attempt';
2427
+ const email = normalizeText(session.customer_details?.email) || normalizeText(session.customer_email);
2428
+ if (email && !isSyntheticOrOwnerCheckoutEmail(email)) return 'identified';
2429
+ return 'raw';
2430
+ }
2431
+
2432
+ const CHECKOUT_DEPTH_CACHE_MS = 5 * 60 * 1000;
2433
+ const CHECKOUT_DEPTH_PARTIAL_CACHE_MS = 60 * 1000;
2434
+ const CHECKOUT_DEPTH_LOOKBACK_SECONDS = 35 * 24 * 60 * 60;
2435
+ let checkoutDepthCache = null;
2436
+
2437
+ async function listStripeCheckoutSessionDepth({
2438
+ signal, deadline = Date.now() + 6000, stripeClient = null, maxPages = 12, nowMs = Date.now(),
2439
+ } = {}) {
2440
+ const empty = (status) => ({ status, complete: false, byId: {} });
2441
+ if (!stripeClient && !CONFIG.STRIPE_SECRET_KEY) return empty('unconfigured');
2442
+ const sinceEpochSeconds = Math.floor(nowMs / 1000) - CHECKOUT_DEPTH_LOOKBACK_SECONDS;
2443
+ if (!stripeClient && checkoutDepthCache && nowMs < checkoutDepthCache.expiresAt) return checkoutDepthCache.value;
2444
+ let stripe = stripeClient;
2445
+ if (!stripe) {
2446
+ try {
2447
+ stripe = getStripeClient();
2448
+ } catch {
2449
+ return empty('unavailable');
2450
+ }
2451
+ }
2452
+ const byId = {};
2453
+ let complete = true;
2454
+ let startingAfter = null;
2455
+ try {
2456
+ for (let page = 0; page < maxPages; page += 1) {
2457
+ if (signal?.aborted || Date.now() >= deadline) { complete = false; break; }
2458
+ const timeout = Math.max(1, Math.min(8000, deadline - Date.now()));
2459
+ const params = { limit: 100, created: { gte: sinceEpochSeconds } };
2460
+ if (startingAfter) params.starting_after = startingAfter;
2461
+ const listed = await withTimeout(withStripeReadSlot(
2462
+ () => stripe.checkout.sessions.list(params, { timeout, maxNetworkRetries: 0 }),
2463
+ { signal }
2464
+ ), timeout);
2465
+ const rows = Array.isArray(listed?.data) ? listed.data : [];
2466
+ for (const row of rows) {
2467
+ if (row?.id) byId[row.id] = classifyCheckoutSessionDepth(row);
2468
+ }
2469
+ if (!listed?.has_more || rows.length === 0) break;
2470
+ startingAfter = rows[rows.length - 1].id;
2471
+ if (page === maxPages - 1) complete = false;
2472
+ }
2473
+ } catch {
2474
+ complete = false;
2475
+ }
2476
+ const value = { status: complete ? 'ok' : 'partial', complete, byId };
2477
+ if (!stripeClient) {
2478
+ checkoutDepthCache = {
2479
+ value,
2480
+ expiresAt: nowMs + (complete ? CHECKOUT_DEPTH_CACHE_MS : CHECKOUT_DEPTH_PARTIAL_CACHE_MS),
2481
+ };
2482
+ }
2483
+ return value;
2484
+ }
2485
+
2486
+ // Counts the window's checkout_session_created rows by how far each Stripe
2487
+ // session got. Only when every session was found does it replace the
2488
+ // telemetry-based count of qualified checkout starts.
2489
+ function summarizeCheckoutSessionDepth(acquisitionEvents = [], depthLookup = null) {
2490
+ const counts = { raw: 0, identified: 0, payment_attempt: 0, paid: 0 };
2491
+ const byId = depthLookup && typeof depthLookup.byId === 'object' ? depthLookup.byId : null;
2492
+ let sessionsCreated = 0;
2493
+ let unresolved = 0;
2494
+ for (const entry of acquisitionEvents) {
2495
+ if (!entry || entry.event !== 'checkout_session_created') continue;
2496
+ sessionsCreated += 1;
2497
+ const depth = byId ? byId[normalizeText(entry.evidence)] : null;
2498
+ if (depth && Object.hasOwn(counts, depth)) counts[depth] += 1;
2499
+ else unresolved += 1;
2500
+ }
2501
+ const available = Boolean(byId) && unresolved === 0;
2502
+ return {
2503
+ basis: available ? 'stripe_session_lookup' : 'telemetry_heuristic',
2504
+ lookupStatus: depthLookup?.status || 'not_requested',
2505
+ sessionsCreated,
2506
+ raw: counts.raw,
2507
+ identified: counts.identified,
2508
+ paymentAttempt: counts.payment_attempt,
2509
+ paid: counts.paid,
2510
+ unresolved,
2511
+ qualifiedCheckoutStarts: counts.identified + counts.payment_attempt + counts.paid,
2512
+ };
2513
+ }
2514
+
2515
+ // Read-only check that a /success visit carries a real, paid Checkout session.
2516
+ // Bots, probes and our own agents can GET /success with any query string, so a
2517
+ // visit only counts when Stripe says the session id is paid.
2518
+ const SUCCESS_VERIFY_CACHE_MS = 5 * 60 * 1000;
2519
+ const SUCCESS_VERIFY_FAIL_CACHE_MS = 60 * 1000;
2520
+ const SUCCESS_VERIFY_CACHE_MAX = 500;
2521
+ const successVerifyCache = new Map();
2522
+
2523
+ async function verifyPaidCheckoutSession(sessionId, { stripeClient = null } = {}) {
2524
+ const id = normalizeText(sessionId);
2525
+ if (!id) return { verified: false, reason: 'missing_session_id' };
2526
+ if (!/^cs_(?:live|test)_[A-Za-z0-9]{8,}$/.test(id)) return { verified: false, reason: 'malformed_session_id' };
2527
+ const cached = !stripeClient ? successVerifyCache.get(id) : null;
2528
+ if (cached && Date.now() < cached.expiresAt) return cached.result;
2529
+ let session = null;
2530
+ let result;
2531
+ try {
2532
+ if (!stripeClient && LOCAL_MODE()) {
2533
+ session = loadLocalCheckoutSessions().sessions[id] || null;
2534
+ } else {
2535
+ const stripe = stripeClient || getStripeClient();
2536
+ session = await withTimeout(withStripeReadSlot(() => stripe.checkout.sessions.retrieve(id)));
2537
+ }
2538
+ if (!session) {
2539
+ result = { verified: false, reason: 'unknown_session' };
2540
+ } else {
2541
+ const paid = session.payment_status === 'paid'
2542
+ || (session.mode === 'subscription' && session.payment_status === 'no_payment_required');
2543
+ result = paid ? { verified: true, reason: 'paid' } : { verified: false, reason: 'not_paid' };
2544
+ }
2545
+ } catch (error) {
2546
+ result = { verified: false, reason: /no such/i.test(error?.message || '') ? 'unknown_session' : 'lookup_failed' };
2547
+ }
2548
+ if (!stripeClient) {
2549
+ if (successVerifyCache.size >= SUCCESS_VERIFY_CACHE_MAX) successVerifyCache.clear();
2550
+ successVerifyCache.set(id, {
2551
+ result,
2552
+ expiresAt: Date.now() + (result.verified ? SUCCESS_VERIFY_CACHE_MS : SUCCESS_VERIFY_FAIL_CACHE_MS),
2553
+ });
2554
+ }
2555
+ return result;
2556
+ }
2557
+
2415
2558
  function getFunnelAnalytics(options = {}) {
2416
2559
  const analyticsWindow = resolveAnalyticsWindow(options);
2417
2560
  const extraRevenueEvents = Array.isArray(options.extraRevenueEvents) ? options.extraRevenueEvents : [];
@@ -2802,12 +2945,19 @@ function getBusinessAnalytics(options = {}) {
2802
2945
  return !paidEventsGross.some((order) => resolveRevenueEventKey(order) === eventKey);
2803
2946
  }).length;
2804
2947
 
2948
+ const checkoutSessionDepth = summarizeCheckoutSessionDepth(acquisitionEvents, options.checkoutSessionDepth);
2949
+ const telemetryCheckoutStarts = telemetry.ctas ? (telemetry.ctas.qualifiedCheckoutStarts ?? telemetry.ctas.checkoutStarts ?? 0) : 0;
2805
2950
  const trafficMetrics = {
2806
2951
  visitors: telemetry.visitors ? telemetry.visitors.uniqueVisitors || 0 : 0,
2807
2952
  sessions: telemetry.visitors ? telemetry.visitors.uniqueSessions || 0 : 0,
2808
2953
  pageViews: telemetry.visitors ? telemetry.visitors.pageViews || 0 : 0,
2809
2954
  ctaClicks: telemetry.ctas ? telemetry.ctas.totalClicks || 0 : 0,
2810
- checkoutStarts: telemetry.ctas ? (telemetry.ctas.qualifiedCheckoutStarts ?? telemetry.ctas.checkoutStarts ?? 0) : 0,
2955
+ // Qualified = the Stripe session got past raw (an email entered or a payment
2956
+ // attempted). Falls back to the telemetry heuristic when Stripe was not asked.
2957
+ checkoutStarts: checkoutSessionDepth.basis === 'stripe_session_lookup'
2958
+ ? checkoutSessionDepth.qualifiedCheckoutStarts
2959
+ : telemetryCheckoutStarts,
2960
+ checkoutStartsBasis: checkoutSessionDepth.basis,
2811
2961
  checkoutSuccessPageViews: telemetry.ctas ? telemetry.ctas.successPageViews || 0 : 0,
2812
2962
  checkoutCancelPageViews: telemetry.ctas ? (telemetry.ctas.qualifiedCancelPageViews ?? telemetry.ctas.cancelPageViews ?? 0) : 0,
2813
2963
  checkoutPaidConfirmations: telemetry.ctas ? telemetry.ctas.paidConfirmations || 0 : 0,
@@ -2991,6 +3141,7 @@ function getBusinessAnalytics(options = {}) {
2991
3141
  conversionByOfferCode,
2992
3142
  },
2993
3143
  trafficMetrics,
3144
+ checkoutSessionDepth,
2994
3145
  ctas: telemetry.ctas || {},
2995
3146
  operatorGeneratedAcquisition,
2996
3147
  dataQuality,
@@ -3078,6 +3229,7 @@ function getBillingSummary(options = {}) {
3078
3229
  newsletter: business.newsletter,
3079
3230
  attribution: business.attribution,
3080
3231
  trafficMetrics: business.trafficMetrics,
3232
+ checkoutSessionDepth: business.checkoutSessionDepth,
3081
3233
  ctas: business.ctas,
3082
3234
  operatorGeneratedAcquisition: business.operatorGeneratedAcquisition,
3083
3235
  dataQuality: business.dataQuality,
@@ -3110,6 +3262,7 @@ function buildBillingSummaryFailure(error) {
3110
3262
 
3111
3263
  async function getBillingSummariesLive(optionsByWindow = {}, {
3112
3264
  listStripeReconciledRevenueEventsFn = listStripeReconciledRevenueEvents,
3265
+ listStripeCheckoutSessionDepthFn = listStripeCheckoutSessionDepth,
3113
3266
  signal,
3114
3267
  } = {}) {
3115
3268
  const entries = Object.entries(optionsByWindow || {});
@@ -3122,6 +3275,9 @@ async function getBillingSummariesLive(optionsByWindow = {}, {
3122
3275
  if (signal?.aborted) abort();
3123
3276
  let extraRevenueEvents = [];
3124
3277
  let reconciliation = { status: 'ok', complete: true };
3278
+ const depthPromise = Promise.resolve()
3279
+ .then(() => listStripeCheckoutSessionDepthFn({ signal: controller.signal }))
3280
+ .catch(() => null);
3125
3281
  try {
3126
3282
  extraRevenueEvents = await withTimeout(listStripeReconciledRevenueEventsFn({
3127
3283
  signal: controller.signal, deadline: Date.now() + reconciliationTimeoutMs,
@@ -3129,6 +3285,10 @@ async function getBillingSummariesLive(optionsByWindow = {}, {
3129
3285
  reconciliation = extraRevenueEvents.reconciliation || reconciliation;
3130
3286
  } catch (error) {
3131
3287
  reconciliation = { status: /timeout/i.test(error?.message || '') ? 'timeout' : 'unavailable', complete: false };
3288
+ }
3289
+ let checkoutSessionDepth = null;
3290
+ try {
3291
+ checkoutSessionDepth = await depthPromise;
3132
3292
  } finally {
3133
3293
  controller.abort();
3134
3294
  signal?.removeEventListener('abort', abort);
@@ -3136,7 +3296,7 @@ async function getBillingSummariesLive(optionsByWindow = {}, {
3136
3296
  if (signal?.aborted) throw Object.assign(new Error('Collection stopped'), { code: 'collection_timeout' });
3137
3297
  try {
3138
3298
  return Object.fromEntries(entries.map(([key, options]) => [key, {
3139
- ...getBillingSummary({ ...options, extraRevenueEvents }), reconciliation,
3299
+ ...getBillingSummary({ ...options, extraRevenueEvents, checkoutSessionDepth }), reconciliation,
3140
3300
  }]));
3141
3301
  } catch (error) {
3142
3302
  return Object.fromEntries(entries.map(([key]) => [key, { ...buildBillingSummaryFailure(error), reconciliation }]));
@@ -3387,10 +3547,25 @@ function isLiveStripeKey(key) {
3387
3547
  return /^(sk|rk)_live_/.test(String(key || ''));
3388
3548
  }
3389
3549
 
3390
- async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, installId, traceId, packId = null, metadata = {}, appOrigin } = {}) {
3550
+ // Where a session came from. Always present on a session our server creates; a
3551
+ // missing value is the word "unknown" so the key is never absent.
3552
+ const CLICK_METADATA_KEYS = ['landingPage', 'referrer', 'uaClass', 'buttonId'];
3553
+
3554
+ function resolveClickMetadata(humanClick) {
3555
+ const given = humanClick && typeof humanClick.metadata === 'object' && humanClick.metadata ? humanClick.metadata : {};
3556
+ const resolved = {};
3557
+ for (const key of CLICK_METADATA_KEYS) {
3558
+ const value = String(given[key] == null ? '' : given[key]).trim();
3559
+ resolved[key] = value ? value.slice(0, 200) : 'unknown';
3560
+ }
3561
+ return resolved;
3562
+ }
3563
+
3564
+ async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, installId, traceId, packId = null, metadata = {}, appOrigin, humanClick = null } = {}) {
3391
3565
  const resolvedTraceId = traceId || metadata.traceId || createTraceId('checkout');
3392
3566
  const baseCheckoutMetadata = sanitizeMetadata({
3393
3567
  ...metadata,
3568
+ ...resolveClickMetadata(humanClick),
3394
3569
  installId: installId || metadata.installId || 'unknown',
3395
3570
  traceId: resolvedTraceId,
3396
3571
  });
@@ -3441,6 +3616,15 @@ async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, ins
3441
3616
  throw blockedErr;
3442
3617
  }
3443
3618
 
3619
+ // A Stripe session opens only for a request the human-click gate admitted
3620
+ // (scripts/checkout-human-gate.js). Refused before any Stripe call.
3621
+ if (!(humanClick && humanClick.admitted === true)) {
3622
+ const refused = new Error('Refusing to open a Stripe Checkout session without a confirmed human click.');
3623
+ refused.statusCode = 403;
3624
+ refused.code = 'HUMAN_CLICK_REQUIRED';
3625
+ throw refused;
3626
+ }
3627
+
3444
3628
  const stripe = getStripeClient();
3445
3629
 
3446
3630
  if (!packId) {
@@ -4974,8 +5158,9 @@ module.exports = {
4974
5158
  withStripeReadSlot, getBillingAnalyticsReadPaths,
4975
5159
  _mergeRevenueEvents: mergeRevenueEvents,
4976
5160
  _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,
5161
+ 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, listStripeCheckoutSessionDepth, classifyCheckoutSessionDepth, summarizeCheckoutSessionDepth, verifyPaidCheckoutSession, repairGithubMarketplaceRevenueLedger,
4978
5162
  _buildCheckoutSessionPayload: buildCheckoutSessionPayload,
5163
+ _setStripeClient: setStripeClientForTests,
4979
5164
  _filterQualifiedCheckoutFunnelEvents: filterQualifiedCheckoutFunnelEvents,
4980
5165
  _createSessionDroppingRejectedOptionals: createSessionDroppingRejectedOptionals,
4981
5166
  _buildTrialActivationEmail: buildTrialActivationEmail,
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+ // Local, opt-in counter for the moment a free install hits the learned-rule cap.
3
+ // - Off unless THUMBGATE_LOCAL_COUNTERS=1.
4
+ // - Writes one JSON line to <feedbackDir>/local-counters.jsonl: event, ts, cap, activeGates.
5
+ // No rule text, command, path or id. Nothing is sent anywhere; this module has no network code.
6
+ // - Never throws: a counter must not break feedback capture.
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { resolveFeedbackDir } = require('./feedback-paths');
11
+
12
+ const COUNTER_FILE = 'local-counters.jsonl';
13
+ const EVENT = 'rule_cap_hit';
14
+
15
+ function countersEnabled() {
16
+ return process.env.THUMBGATE_LOCAL_COUNTERS === '1';
17
+ }
18
+
19
+ function counterPath(options = {}) {
20
+ return path.join(options.feedbackDir || resolveFeedbackDir(options), COUNTER_FILE);
21
+ }
22
+
23
+ function recordCapHit({ feedbackDir, cap, activeGates, enabled = countersEnabled() } = {}) {
24
+ if (!enabled) return false;
25
+ try {
26
+ const file = counterPath({ feedbackDir });
27
+ fs.mkdirSync(path.dirname(file), { recursive: true });
28
+ fs.appendFileSync(file, `${JSON.stringify({ event: EVENT, ts: new Date().toISOString(), cap, activeGates })}\n`);
29
+ return true;
30
+ } catch (_) {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ function readCapHitCount(options = {}) {
36
+ try {
37
+ return fs.readFileSync(counterPath(options), 'utf8')
38
+ .split('\n')
39
+ .filter((line) => {
40
+ try { return JSON.parse(line).event === EVENT; } catch (_) { return false; }
41
+ }).length;
42
+ } catch (_) {
43
+ return 0;
44
+ }
45
+ }
46
+
47
+ module.exports = { COUNTER_FILE, EVENT, countersEnabled, recordCapHit, readCapHitCount };
@@ -0,0 +1,248 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * checkout-human-gate.js: decides whether a request may open a Stripe Checkout
5
+ * Session. A session is created only for a POST that carries a short-lived,
6
+ * single-use token fetched by page JS after a trusted pointer or keyboard
7
+ * event, from a browser-class user agent, with at most 2 admissions per IP per
8
+ * minute and a site-wide ceiling. Spec: docs/designs/2026-11-18-human-click-checkout.md.
9
+ *
10
+ * What this does not stop: a script that rotates IPs and calls the token
11
+ * endpoint itself. The ceiling bounds that, it does not prevent it.
12
+ */
13
+
14
+ const crypto = require('node:crypto');
15
+ const { classifyRequester } = require('./bot-detection');
16
+
17
+ const TOKEN_TTL_MS = 120 * 1000;
18
+ const BURST_MAX = 2;
19
+ const BURST_WINDOW_MS = 60 * 1000;
20
+ const BURST_MAX_KEYS = 5000;
21
+ const GLOBAL_MAX = 60;
22
+ const GLOBAL_WINDOW_MS = 60 * 60 * 1000;
23
+ const META_VALUE_MAX = 200;
24
+ const BUTTON_ID_PATTERN = /^[A-Za-z0-9_:.-]{1,80}$/;
25
+ const LANDING_PATH_PATTERN = /^\/[A-Za-z0-9/_.~%-]{0,199}$/;
26
+
27
+ function headerValue(headers, name) {
28
+ const value = headers && headers[name];
29
+ if (Array.isArray(value)) return value.join(',');
30
+ return typeof value === 'string' ? value : '';
31
+ }
32
+
33
+ function shortHash(value) {
34
+ return crypto.createHash('sha256').update(String(value || '')).digest('base64url').slice(0, 22);
35
+ }
36
+
37
+ // Same trust rule the intake alert limiter uses (buildIntakeAlertRateLimitKey in
38
+ // src/api/server.js): behind Railway, x-real-ip is overwritten at the ingress and
39
+ // can be trusted; anywhere else every forwarding header is caller controlled and
40
+ // is ignored. cf-connecting-ip and x-forwarded-for are never used: no Cloudflare
41
+ // fronts this site, so a client can set both.
42
+ function clientIpKey(headers = {}, remoteAddress = '', env = process.env) {
43
+ const behindRailway = Boolean(env && (env.RAILWAY_ENVIRONMENT_ID || env.RAILWAY_PROJECT_ID));
44
+ const realIp = headerValue(headers, 'x-real-ip').trim();
45
+ if (behindRailway && /^[0-9a-f:.]{3,64}$/i.test(realIp)) return realIp;
46
+ return String(remoteAddress || '').trim() || 'no-ip';
47
+ }
48
+
49
+ function classifyUserAgentClass(headers = {}) {
50
+ if (!headerValue(headers, 'user-agent').trim()) return 'unknown';
51
+ return classifyRequester(headers).isBot ? 'bot' : 'browser';
52
+ }
53
+
54
+ function createTokenService({ secret, now = Date.now, ttlMs = TOKEN_TTL_MS } = {}) {
55
+ if (!secret) throw new Error('createTokenService needs a signing value');
56
+ const used = new Map();
57
+
58
+ function sign(payload) {
59
+ return crypto.createHmac('sha256', secret).update(payload).digest('base64url');
60
+ }
61
+ function prune(at) {
62
+ for (const [nonce, expiresAt] of used) {
63
+ if (expiresAt > at) break;
64
+ used.delete(nonce);
65
+ }
66
+ }
67
+
68
+ function issue({ ipKey, userAgent, buttonId, landingPage }) {
69
+ const at = now();
70
+ const claims = {
71
+ iat: at,
72
+ exp: at + ttlMs,
73
+ ip: shortHash(ipKey),
74
+ ua: shortHash(userAgent),
75
+ btn: String(buttonId || '').slice(0, META_VALUE_MAX),
76
+ lp: String(landingPage || '').slice(0, META_VALUE_MAX),
77
+ n: crypto.randomBytes(12).toString('base64url'),
78
+ };
79
+ const payload = Buffer.from(JSON.stringify(claims)).toString('base64url');
80
+ return `${payload}.${sign(payload)}`;
81
+ }
82
+
83
+ // consume=false lets the caller check other limits first and burn the token last.
84
+ function verify(token, { ipKey, userAgent } = {}, { consume = true } = {}) {
85
+ if (!token || typeof token !== 'string') return { ok: false, reason: 'missing' };
86
+ const parts = token.split('.');
87
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return { ok: false, reason: 'malformed' };
88
+ const expected = Buffer.from(sign(parts[0]));
89
+ const given = Buffer.from(parts[1]);
90
+ if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {
91
+ return { ok: false, reason: 'bad_signature' };
92
+ }
93
+ let claims;
94
+ try {
95
+ claims = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
96
+ } catch {
97
+ return { ok: false, reason: 'malformed' };
98
+ }
99
+ const at = now();
100
+ if (!claims || typeof claims.exp !== 'number' || claims.exp < at) return { ok: false, reason: 'expired' };
101
+ if (claims.ip !== shortHash(ipKey)) return { ok: false, reason: 'ip_mismatch' };
102
+ if (claims.ua !== shortHash(userAgent)) return { ok: false, reason: 'ua_mismatch' };
103
+ prune(at);
104
+ if (used.has(claims.n)) return { ok: false, reason: 'replayed' };
105
+ if (consume) used.set(claims.n, claims.exp);
106
+ return { ok: true, claims };
107
+ }
108
+
109
+ function consume(claims) {
110
+ if (claims && claims.n) used.set(claims.n, claims.exp);
111
+ }
112
+
113
+ return { issue, verify, consume };
114
+ }
115
+
116
+ function createBurstLimiter({ max = BURST_MAX, windowMs = BURST_WINDOW_MS, maxKeys = BURST_MAX_KEYS } = {}) {
117
+ const hits = new Map();
118
+ function recent(key, at) {
119
+ return (hits.get(key) || []).filter((stamp) => at - stamp <= windowMs);
120
+ }
121
+ return {
122
+ wouldAdmit(key, at = Date.now()) {
123
+ return recent(key, at).length < max;
124
+ },
125
+ // Records an admission and returns true, or returns false without recording
126
+ // when the key already used its allowance inside the window.
127
+ admit(key, at = Date.now()) {
128
+ const live = recent(key, at);
129
+ if (live.length >= max) {
130
+ hits.set(key, live);
131
+ return false;
132
+ }
133
+ live.push(at);
134
+ hits.delete(key);
135
+ hits.set(key, live);
136
+ while (hits.size > maxKeys) hits.delete(hits.keys().next().value);
137
+ return true;
138
+ },
139
+ size() {
140
+ return hits.size;
141
+ },
142
+ };
143
+ }
144
+
145
+ function cleanReferrer(raw) {
146
+ const text = String(raw || '').trim();
147
+ if (!text) return '';
148
+ let cut = text;
149
+ try {
150
+ const url = new URL(text);
151
+ cut = `${url.origin}${url.pathname}`;
152
+ } catch {
153
+ cut = text.split(/[?#]/)[0];
154
+ }
155
+ return cut.slice(0, META_VALUE_MAX);
156
+ }
157
+
158
+ // landingPage and buttonId come from the browser, so they are recorded as
159
+ // untrusted: only values shaped like a path or an id are kept.
160
+ function cleanLandingPage(raw) {
161
+ const text = String(raw || '').trim();
162
+ if (!text) return '';
163
+ let path = text;
164
+ try {
165
+ path = new URL(text, 'https://thumbgate.invalid').pathname;
166
+ } catch {
167
+ path = text.split(/[?#]/)[0];
168
+ }
169
+ return LANDING_PATH_PATTERN.test(path) ? path : '';
170
+ }
171
+
172
+ function cleanButtonId(raw) {
173
+ const text = String(raw || '').trim();
174
+ return BUTTON_ID_PATTERN.test(text) ? text : '';
175
+ }
176
+
177
+ // Always returns the four keys; a missing or invalid value is the word "unknown".
178
+ function buildClickMetadata({ headers = {}, claims = null } = {}) {
179
+ return {
180
+ landingPage: cleanLandingPage(claims && claims.lp) || 'unknown',
181
+ referrer: cleanReferrer(headerValue(headers, 'referer') || headerValue(headers, 'referrer')) || 'unknown',
182
+ uaClass: classifyUserAgentClass(headers),
183
+ buttonId: cleanButtonId(claims && claims.btn) || 'unknown',
184
+ };
185
+ }
186
+
187
+ function createHumanGate({
188
+ secret,
189
+ now = Date.now,
190
+ ttlMs,
191
+ max,
192
+ windowMs,
193
+ globalMax = GLOBAL_MAX,
194
+ globalWindowMs = GLOBAL_WINDOW_MS,
195
+ env = process.env,
196
+ } = {}) {
197
+ const tokens = createTokenService({ secret, now, ttlMs });
198
+ const limiter = createBurstLimiter({ max, windowMs });
199
+ const ceiling = createBurstLimiter({ max: globalMax, windowMs: globalWindowMs, maxKeys: 1 });
200
+
201
+ // Gives a token only to a browser-class user agent.
202
+ function issueToken({ headers = {}, remoteAddress = '', buttonId = '', landingPage = '' } = {}) {
203
+ if (classifyUserAgentClass(headers) !== 'browser') return null;
204
+ return tokens.issue({
205
+ ipKey: clientIpKey(headers, remoteAddress, env),
206
+ userAgent: headerValue(headers, 'user-agent'),
207
+ buttonId,
208
+ landingPage,
209
+ });
210
+ }
211
+
212
+ function admit({ method, headers = {}, remoteAddress = '', token } = {}) {
213
+ const refuse = (status, reason) => ({ ok: false, status, reason });
214
+ if (String(method || '').toUpperCase() !== 'POST') return refuse(405, 'method_not_post');
215
+ const uaClass = classifyUserAgentClass(headers);
216
+ if (uaClass !== 'browser') return refuse(403, `ua_${uaClass}`);
217
+ const ipKey = clientIpKey(headers, remoteAddress, env);
218
+ const checked = tokens.verify(token, { ipKey, userAgent: headerValue(headers, 'user-agent') }, { consume: false });
219
+ if (!checked.ok) return refuse(403, `token_${checked.reason}`);
220
+ const at = now();
221
+ if (!limiter.wouldAdmit(ipKey, at)) return refuse(429, 'burst_limit');
222
+ if (!ceiling.wouldAdmit('all', at)) return refuse(429, 'global_ceiling');
223
+ limiter.admit(ipKey, at);
224
+ ceiling.admit('all', at);
225
+ tokens.consume(checked.claims);
226
+ return {
227
+ ok: true,
228
+ status: 200,
229
+ reason: null,
230
+ humanClick: { admitted: true, metadata: buildClickMetadata({ headers, claims: checked.claims }) },
231
+ };
232
+ }
233
+
234
+ return { issueToken, admit, tokens, limiter, ceiling };
235
+ }
236
+
237
+ module.exports = {
238
+ TOKEN_TTL_MS,
239
+ BURST_MAX,
240
+ BURST_WINDOW_MS,
241
+ GLOBAL_MAX,
242
+ clientIpKey,
243
+ classifyUserAgentClass,
244
+ createTokenService,
245
+ createBurstLimiter,
246
+ buildClickMetadata,
247
+ createHumanGate,
248
+ };