thumbgate 1.40.2 → 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 (49) 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 +4 -2
  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 +30 -7
  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 +8 -1
  32. package/scripts/first-block-upsell.js +187 -0
  33. package/scripts/gates-engine.js +37 -108
  34. package/scripts/human-feedback.js +42 -0
  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 +132 -0
  41. package/scripts/statusline-links.js +13 -3
  42. package/scripts/statusline-local-stats.js +5 -3
  43. package/scripts/statusline.sh +31 -3
  44. package/scripts/telemetry-analytics.js +4 -0
  45. package/scripts/tool-contract-validator.js +13 -3
  46. package/scripts/tool-registry.js +1 -1
  47. package/scripts/utm-source-summary.js +88 -0
  48. package/server.json +2 -2
  49. package/src/api/server.js +613 -107
package/src/api/server.js CHANGED
@@ -3,6 +3,7 @@ const { withDataScope, withoutDataScope, currentDataScope, tenantDataScope, asse
3
3
  const { parseProjectSelection, projectForCapture, projectForRecord, matchesProject, validProjectKey } = require('../../scripts/project-identity');
4
4
  const { readProjectRows, buildProjectCatalog } = require('../../scripts/project-catalog');
5
5
  const ownerAdmin = require('../../scripts/owner-admin');
6
+ const opsLog = require('../../scripts/ops-log');
6
7
  const http = require('http');
7
8
  const https = require('https');
8
9
  const fs = require('fs');
@@ -121,6 +122,67 @@ const {
121
122
  } = require('../../scripts/bot-detection');
122
123
 
123
124
  const rapidCheckoutGuard = createRapidCheckoutGuard();
125
+
126
+ const { createHumanGate } = require('../../scripts/checkout-human-gate');
127
+ const { getUtmSourceSummary } = require('../../scripts/utm-source-summary');
128
+
129
+ // A stable signing value keeps click tokens valid across instances and restarts:
130
+ // THUMBGATE_CHECKOUT_TOKEN_SECRET, else derived from THUMBGATE_API_KEY, else random per process.
131
+ function resolveCheckoutTokenSecret(env = process.env) {
132
+ if (env.THUMBGATE_CHECKOUT_TOKEN_SECRET) return env.THUMBGATE_CHECKOUT_TOKEN_SECRET;
133
+ if (env.THUMBGATE_API_KEY) {
134
+ return crypto.createHmac('sha256', env.THUMBGATE_API_KEY).update('checkout-click-token-v1').digest('hex');
135
+ }
136
+ return crypto.randomBytes(32).toString('hex');
137
+ }
138
+
139
+ // THUMBGATE_CHECKOUT_BURST_MAX (default 2 per minute per IP) and
140
+ // THUMBGATE_CHECKOUT_GLOBAL_MAX (default 60 per hour, whole site) are only for tests
141
+ // and load checks; production leaves them unset.
142
+ function positiveIntFromEnv(name, env = process.env) {
143
+ const value = Number.parseInt(String(env[name] || ''), 10);
144
+ return Number.isFinite(value) && value > 0 ? value : undefined;
145
+ }
146
+
147
+ function buildHumanGate() {
148
+ return createHumanGate({
149
+ secret: resolveCheckoutTokenSecret(),
150
+ max: positiveIntFromEnv('THUMBGATE_CHECKOUT_BURST_MAX'),
151
+ globalMax: positiveIntFromEnv('THUMBGATE_CHECKOUT_GLOBAL_MAX'),
152
+ });
153
+ }
154
+
155
+ // Replaced on each createApiServer() so every server starts with empty limits.
156
+ let humanGate = buildHumanGate();
157
+
158
+ function admitCheckoutClick(req, token) {
159
+ return humanGate.admit({
160
+ method: req.method,
161
+ headers: req.headers,
162
+ remoteAddress: req.socket && req.socket.remoteAddress,
163
+ token,
164
+ });
165
+ }
166
+
167
+ function checkoutClickTokenFrom(req, form = null) {
168
+ const headerToken = req.headers['x-thumbgate-click-token'];
169
+ return String((form && form.click_token) || (Array.isArray(headerToken) ? headerToken[0] : headerToken) || '').trim();
170
+ }
171
+
172
+ function isSameOriginCheckoutRequest(req, appOrigin) {
173
+ const origin = String(req.headers.origin || '').trim();
174
+ if (origin) {
175
+ try {
176
+ const host = new URL(origin).host.toLowerCase();
177
+ const allowed = new Set([String(req.headers.host || '').toLowerCase()]);
178
+ if (appOrigin) allowed.add(new URL(appOrigin).host.toLowerCase());
179
+ return allowed.has(host);
180
+ } catch {
181
+ return false;
182
+ }
183
+ }
184
+ return String(req.headers['sec-fetch-site'] || '').toLowerCase() === 'same-origin';
185
+ }
124
186
  const {
125
187
  recordCheckoutFunnelEvent,
126
188
  } = require('../../scripts/plausible-server-events');
@@ -163,6 +225,7 @@ const {
163
225
  getBillingSummary,
164
226
  getBillingSummaryLive,
165
227
  getBillingSummariesLive,
228
+ verifyPaidCheckoutSession,
166
229
  } = require('../../scripts/billing');
167
230
  const {
168
231
  ensureProductionSearchCorpus,
@@ -370,6 +433,8 @@ const FOUNDERS_PAGE_PATH = path.resolve(__dirname, '../../public/founders.html')
370
433
  const PARTNER_INTAKE_PAGE_PATH = path.resolve(__dirname, '../../public/partner-intake.html');
371
434
  const PETER_PAGE_PATH = path.resolve(__dirname, '../../public/peter.html');
372
435
  const INSTALL_PAGE_PATH = path.resolve(__dirname, '../../public/install.html');
436
+ const PREVIEW_PAGE_PATH = path.resolve(__dirname, '../../public/preview.html');
437
+ const CONNECT_PANEL_SCRIPT_PATH = path.resolve(__dirname, '../../public/js/connect-panel.js');
373
438
  const ONBOARDING_PAGE_PATH = path.resolve(__dirname, '../../public/onboarding.html');
374
439
  const LEARN_DIR = path.resolve(__dirname, '../../public/learn');
375
440
  const GUIDES_DIR = path.resolve(__dirname, '../../public/guides');
@@ -381,6 +446,8 @@ const PUBLIC_ASSETS_DIR = path.resolve(__dirname, '../../public/assets');
381
446
  const LEARN_PAGE_PATHS_BY_SLUG = buildPublicHtmlFileMap(LEARN_DIR);
382
447
  const GUIDE_PAGE_PATHS_BY_SLUG = buildPublicHtmlFileMap(GUIDES_DIR);
383
448
  const COMPARE_PAGE_PATHS_BY_SLUG = buildPublicHtmlFileMap(COMPARE_DIR);
449
+ const REPORTS_DIR = path.resolve(__dirname, '../../public/reports');
450
+ const REPORT_PAGE_PATHS_BY_SLUG = buildPublicHtmlFileMap(REPORTS_DIR);
384
451
  const USE_CASE_PAGE_PATHS_BY_SLUG = buildPublicHtmlFileMap(USE_CASES_DIR);
385
452
  const BLOG_PAGE_PATHS_BY_SLUG = buildPublicHtmlFileMap(BLOG_DIR);
386
453
  const BUYER_INTENT_SCRIPT_PATH = path.resolve(__dirname, '../../public/js/buyer-intent.js');
@@ -480,7 +547,26 @@ function deleteLessonJsonlRecord(filePath, recordId, options) {
480
547
  return getLessonSynthesisModule().deleteRecordFromJsonl(filePath, recordId, options);
481
548
  }
482
549
 
483
- function serveStaticFile(res, filePath, { headOnly = false, cacheSeconds = 86400 } = {}) {
550
+ // Single-range "bytes=a-b" only; iOS Safari will not play a <video> unless the server answers 206.
551
+ function parseByteRange(header, size) {
552
+ const match = /^bytes=(\d*)-(\d*)$/.exec(String(header || '').trim());
553
+ if (!match || (match[1] === '' && match[2] === '')) return null;
554
+ let start;
555
+ let end;
556
+ if (match[1] === '') {
557
+ const suffix = Number(match[2]);
558
+ if (suffix === 0) return 'invalid';
559
+ start = Math.max(size - suffix, 0);
560
+ end = size - 1;
561
+ } else {
562
+ start = Number(match[1]);
563
+ end = match[2] === '' ? size - 1 : Math.min(Number(match[2]), size - 1);
564
+ }
565
+ if (start >= size || start > end) return 'invalid';
566
+ return { start, end };
567
+ }
568
+
569
+ function serveStaticFile(res, filePath, { headOnly = false, cacheSeconds = 86400, rangeHeader = null } = {}) {
484
570
  const ext = path.extname(filePath).toLowerCase();
485
571
  const contentType = STATIC_MIME_BY_EXT[ext] || 'application/octet-stream';
486
572
  let stat;
@@ -498,11 +584,30 @@ function serveStaticFile(res, filePath, { headOnly = false, cacheSeconds = 86400
498
584
  res.end(JSON.stringify({ error: 'Not found' }));
499
585
  return;
500
586
  }
501
- res.statusCode = 200;
502
587
  res.setHeader('Content-Type', contentType);
503
- res.setHeader('Content-Length', stat.size);
504
588
  res.setHeader('Cache-Control', `public, max-age=${cacheSeconds}, immutable`);
505
589
  res.setHeader('Referrer-Policy', 'same-origin');
590
+ res.setHeader('Accept-Ranges', 'bytes');
591
+ const range = rangeHeader ? parseByteRange(rangeHeader, stat.size) : null;
592
+ if (range === 'invalid') {
593
+ res.statusCode = 416;
594
+ res.setHeader('Content-Range', `bytes */${stat.size}`);
595
+ res.end();
596
+ return;
597
+ }
598
+ if (range) {
599
+ res.statusCode = 206;
600
+ res.setHeader('Content-Range', `bytes ${range.start}-${range.end}/${stat.size}`);
601
+ res.setHeader('Content-Length', range.end - range.start + 1);
602
+ if (headOnly) {
603
+ res.end();
604
+ return;
605
+ }
606
+ fs.createReadStream(filePath, { start: range.start, end: range.end }).pipe(res);
607
+ return;
608
+ }
609
+ res.statusCode = 200;
610
+ res.setHeader('Content-Length', stat.size);
506
611
  if (headOnly) {
507
612
  res.end();
508
613
  return;
@@ -512,6 +617,9 @@ function serveStaticFile(res, filePath, { headOnly = false, cacheSeconds = 86400
512
617
  const VISITOR_COOKIE_NAME = 'thumbgate_visitor_id';
513
618
  const SESSION_COOKIE_NAME = 'thumbgate_session_id';
514
619
  const ACQUISITION_COOKIE_NAME = 'thumbgate_acquisition_id';
620
+ const UTM_COOKIE_NAME = 'thumbgate_utm';
621
+ const UTM_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
622
+ const LANDING_UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
515
623
  const VISITOR_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 90;
516
624
  const BUILD_METADATA = resolveBuildMetadata();
517
625
  const TERMINAL_JOB_STATUSES = new Set(['completed', 'failed', 'cancelled']);
@@ -1626,7 +1734,13 @@ function inferSearchSurface(referrerHost) {
1626
1734
  return null;
1627
1735
  }
1628
1736
 
1737
+ function isLinkedInHost(referrerHost) {
1738
+ const host = String(normalizeNullableText(referrerHost) || '').toLowerCase();
1739
+ return /(^|\.)linkedin\.com$/.test(host) || host === 'lnkd.in';
1740
+ }
1741
+
1629
1742
  function inferSource(referrerHost) {
1743
+ if (isLinkedInHost(referrerHost)) return 'linkedin';
1630
1744
  const surface = inferSearchSurface(referrerHost);
1631
1745
  if (surface === 'reddit') return 'reddit';
1632
1746
  if (surface && /_search$/.test(surface)) return 'organic_search';
@@ -1702,6 +1816,39 @@ function isSecureRequest(req) {
1702
1816
  return forwardedProto === 'https' || Boolean(req.socket && req.socket.encrypted);
1703
1817
  }
1704
1818
 
1819
+ function sanitizeUtmValue(value) {
1820
+ const text = String(value ?? '').trim().slice(0, 100);
1821
+ return /^[\w.\-:+~ /]+$/.test(text) ? text : '';
1822
+ }
1823
+
1824
+ function readLandingUtm(source) {
1825
+ const out = {};
1826
+ for (const key of LANDING_UTM_KEYS) {
1827
+ const value = sanitizeUtmValue(typeof source.get === 'function' ? source.get(key) : source[key]);
1828
+ if (value) out[key] = value;
1829
+ }
1830
+ return out.utm_source ? out : {};
1831
+ }
1832
+
1833
+ function parseLandingUtmCookie(raw) {
1834
+ try {
1835
+ const decoded = JSON.parse(String(raw || ''));
1836
+ return decoded && typeof decoded === 'object' ? readLandingUtm(decoded) : {};
1837
+ } catch {
1838
+ return {};
1839
+ }
1840
+ }
1841
+
1842
+ // The landing visit's utm_* survive to checkout in a first-party cookie, so the
1843
+ // Stripe session can say which post or campaign brought the buyer.
1844
+ function applyLandingUtm(parsed, journeyState) {
1845
+ const params = parsed?.searchParams;
1846
+ if (!params || params.get('utm_source') || !journeyState?.landingUtm) return;
1847
+ for (const [key, value] of Object.entries(journeyState.landingUtm)) {
1848
+ if (!params.get(key)) params.set(key, value);
1849
+ }
1850
+ }
1851
+
1705
1852
  function resolveJourneyState(req, parsed) {
1706
1853
  const params = parsed ? parsed.searchParams : new URLSearchParams();
1707
1854
  const cookies = parseCookies(req.headers.cookie);
@@ -1735,10 +1882,21 @@ function resolveJourneyState(req, parsed) {
1735
1882
  setCookieHeaders.push(serializeCookie(ACQUISITION_COOKIE_NAME, acquisitionId, { secure }));
1736
1883
  }
1737
1884
 
1885
+ const queryUtm = readLandingUtm(params);
1886
+ const cookieUtm = parseLandingUtmCookie(cookies[UTM_COOKIE_NAME]);
1887
+ const landingUtm = queryUtm.utm_source ? queryUtm : cookieUtm;
1888
+ if (queryUtm.utm_source && JSON.stringify(queryUtm) !== JSON.stringify(cookieUtm)) {
1889
+ setCookieHeaders.push(serializeCookie(UTM_COOKIE_NAME, JSON.stringify(queryUtm), {
1890
+ maxAge: UTM_COOKIE_MAX_AGE_SECONDS,
1891
+ secure,
1892
+ }));
1893
+ }
1894
+
1738
1895
  return {
1739
1896
  visitorId,
1740
1897
  sessionId,
1741
1898
  acquisitionId,
1899
+ landingUtm,
1742
1900
  setCookieHeaders,
1743
1901
  };
1744
1902
  }
@@ -2942,14 +3100,30 @@ function getOauthAuthorizeParamsFromForm(form, hostedConfig) {
2942
3100
  };
2943
3101
  }
2944
3102
 
2945
- function resolveCheckoutIntentPlanView(parsed) {
3103
+ function withLandingUtm(directFields, parsed, includeAttribution) {
3104
+ const params = parsed?.searchParams;
3105
+ // Crawler-visible HTML never carries attribution values.
3106
+ if (!includeAttribution || !params || !params.get('utm_source')) return directFields;
3107
+ const out = { ...directFields };
3108
+ for (const key of LANDING_UTM_KEYS) {
3109
+ const value = sanitizeUtmValue(params.get(key));
3110
+ if (value) out[key] = value;
3111
+ }
3112
+ return out;
3113
+ }
3114
+
3115
+ function resolveCheckoutIntentPlanView(parsed, includeAttribution = false) {
2946
3116
  const requestedCycle = String(parsed?.searchParams?.get('billing_cycle') || 'monthly').trim().toLowerCase();
2947
3117
  if (requestedCycle === 'annual') {
2948
3118
  return {
2949
3119
  title: 'Start ThumbGate Pro Annual',
2950
3120
  price: '$149',
2951
3121
  unit: '/yr',
2952
- directHref: '/go/pro-annual?utm_source=website&amp;utm_medium=checkout_interstitial&amp;utm_campaign=pro_annual_149&amp;utm_content=skip_form&amp;cta_id=pro_checkout_direct_stripe&amp;cta_placement=checkout_interstitial&amp;plan_id=pro&amp;billing_cycle=annual',
3122
+ directAction: '/go/pro-annual',
3123
+ directFields: withLandingUtm({
3124
+ utm_source: 'website', utm_medium: 'checkout_interstitial', utm_campaign: 'pro_annual_149', utm_content: 'skip_form',
3125
+ cta_id: 'pro_checkout_direct_stripe', cta_placement: 'checkout_interstitial',
3126
+ }, parsed, includeAttribution),
2953
3127
  ctaLabel: 'Pay $149/yr with Stripe →',
2954
3128
  };
2955
3129
  }
@@ -2957,7 +3131,11 @@ function resolveCheckoutIntentPlanView(parsed) {
2957
3131
  title: 'Start ThumbGate Pro',
2958
3132
  price: '$19',
2959
3133
  unit: '/mo',
2960
- directHref: '/go/pro-direct?utm_source=website&amp;utm_medium=checkout_interstitial&amp;utm_campaign=pro_upgrade&amp;utm_content=skip_form&amp;cta_id=pro_checkout_direct_stripe&amp;cta_placement=checkout_interstitial',
3134
+ directAction: '/go/pro-direct',
3135
+ directFields: withLandingUtm({
3136
+ utm_source: 'website', utm_medium: 'checkout_interstitial', utm_campaign: 'pro_upgrade', utm_content: 'skip_form',
3137
+ cta_id: 'pro_checkout_direct_stripe', cta_placement: 'checkout_interstitial',
3138
+ }, parsed, includeAttribution),
2961
3139
  ctaLabel: 'Pay $19/mo with Stripe →',
2962
3140
  };
2963
3141
  }
@@ -2968,7 +3146,7 @@ function renderCheckoutIntentPage(prefilledEmail = '', parsed = null, options =
2968
3146
  const hiddenInputs = includeHiddenAttribution
2969
3147
  ? buildCheckoutHiddenAttributionInputs(parsed)
2970
3148
  : '';
2971
- const planView = resolveCheckoutIntentPlanView(parsed);
3149
+ const planView = resolveCheckoutIntentPlanView(parsed, includeHiddenAttribution);
2972
3150
  return `<!doctype html>
2973
3151
  <html lang="en">
2974
3152
  <head>
@@ -2995,6 +3173,7 @@ a{display:block;text-decoration:none}a.secondary,button.secondary{box-sizing:bor
2995
3173
  .objection-grid button{border:1px solid #374151;background:#111827;color:#e5e7eb;border-radius:8px;padding:10px 12px;text-align:left;cursor:pointer}
2996
3174
  .objection-grid button:hover,.objection-grid button:focus{border-color:#22d3ee;outline:none}
2997
3175
  .feedback-saved{display:none;color:#22d3ee;font-size:13px;margin-top:10px}
3176
+ .more-options{margin:16px 0 0}.more-options>summary{cursor:pointer;color:#94a3b8;font-size:13px;text-align:center}
2998
3177
  .back{text-align:center;color:#64748b;font-size:12px;margin-top:24px}.back a{color:#64748b;display:inline}
2999
3178
  </style>
3000
3179
  </head>
@@ -3004,8 +3183,19 @@ a{display:block;text-decoration:none}a.secondary,button.secondary{box-sizing:bor
3004
3183
  <h1>${planView.title}</h1>
3005
3184
  <div class="price">${planView.price}<small>${planView.unit}</small></div>
3006
3185
  <p>The npm package runs your gates locally. <strong>Pro</strong> removes solo caps and adds personal recall, proof, exports, and adapter maintenance. Your Pro API key is provisioned on the next screen immediately after payment.</p>
3007
- <a class="primary" data-i="pro_checkout_direct_stripe" rel="nofollow" href="${planView.directHref}">${planView.ctaLabel}</a>
3186
+ <form action="${planView.directAction}" method="POST" class="direct" data-i="pro_checkout_direct_stripe">
3187
+ ${Object.entries(planView.directFields).map(([k, v]) => `<input type="hidden" name="${k}" value="${escapeHtmlAttribute(v)}">`).join('')}
3188
+ <input type="hidden" name="customer_email" value="">
3189
+ <input type="hidden" name="click_token" value="">
3190
+ <button type="submit" class="primary" rel="nofollow">${planView.ctaLabel}</button>
3191
+ </form>
3192
+ <p class="gate-note" id="gate-note" role="status" style="display:none"></p>
3193
+ <noscript><p class="gate-note">Checkout needs JavaScript so we can tell a person from a crawler.</p></noscript>
3194
+ <p class="choice-note">Stripe asks for your email and card on the next page. Cancel anytime. 7-day refund, no questions.</p>
3195
+ <details class="more-options" data-i="pro_checkout_more_options">
3196
+ <summary>Other ways to buy</summary>
3008
3197
  <form action="/checkout/pro" method="POST" data-i="pro_checkout_confirmed">
3198
+ <input type="hidden" name="click_token" value="">
3009
3199
  ${hiddenInputs}
3010
3200
  <input type="hidden" name="confirm" value="1">
3011
3201
  <input type="email" name="customer_email" value="${escapeHtmlAttribute(prefilledEmail)}" placeholder="you@company.com" autocomplete="email" required>
@@ -3016,7 +3206,7 @@ ${hiddenInputs}
3016
3206
  <a class="secondary" data-i="pro_checkout_playbook_999" rel="nofollow" href="/go/playbook-999?utm_source=website&amp;utm_medium=checkout_interstitial&amp;utm_campaign=playbook_999&amp;cta_id=pro_checkout_playbook_999&amp;cta_placement=checkout_interstitial">Buy the $9.99 playbook, once</a>
3017
3207
  <a class="secondary" data-i="pro_checkout_bundle_49" rel="nofollow" href="/go/bundle-49?utm_source=website&amp;utm_medium=checkout_interstitial&amp;utm_campaign=bundle_49&amp;cta_id=pro_checkout_bundle_49&amp;cta_placement=checkout_interstitial">Buy the $49 bundle, once</a>
3018
3208
  <a class="secondary" data-i="workflow_sprint_intake" href="/#workflow-sprint-intake">Not sure yet? Send the workflow first</a>
3019
- <p class="choice-note">Cancel anytime. 7-day refund, no questions.</p>
3209
+ </details>
3020
3210
  <details class="objection-box" aria-label="Checkout feedback">
3021
3211
  <summary style="cursor:pointer;font-weight:600;color:#cbd5e1">Not buying today? Tell us what to fix (optional)</summary>
3022
3212
  <p class="objection-note">Tap one reason so we know what to fix. This does not sign you up.</p>
@@ -3074,44 +3264,76 @@ ${hiddenInputs}
3074
3264
  }
3075
3265
  fetch('/v1/telemetry/ping', { method:'POST', headers:{ 'content-type':'application/json' }, body: body, keepalive: true }).catch(function(){});
3076
3266
  }
3077
- var emailInput = document.querySelector('input[name=customer_email]');
3078
- var skipLink = document.querySelector('a[data-i=pro_checkout_direct_stripe]');
3079
- function updateSkipLink() {
3080
- if (!skipLink) return;
3081
- try {
3082
- var u = new URL(skipLink.href, window.location.origin);
3083
- var email = emailInput ? emailInput.value.trim() : '';
3084
- if (email && email.length <= 320 && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {
3085
- u.searchParams.set('customer_email', email);
3086
- } else {
3087
- u.searchParams.delete('customer_email');
3088
- }
3089
- skipLink.href = u.toString();
3090
- } catch(_) {}
3267
+ var emailInput = document.querySelector('form[data-i=pro_checkout_confirmed] input[name=customer_email]');
3268
+ var directForm = document.querySelector('form[data-i=pro_checkout_direct_stripe]');
3269
+ var confirmForm = document.querySelector('form[data-i=pro_checkout_confirmed]');
3270
+ var gateNote = document.getElementById('gate-note');
3271
+ var gestureSeen = false;
3272
+ function markGesture(ev) { if (ev && ev.isTrusted) gestureSeen = true; }
3273
+ document.addEventListener('pointerdown', markGesture, true);
3274
+ document.addEventListener('keydown', markGesture, true);
3275
+ function syncDirectEmail() {
3276
+ if (!directForm) return;
3277
+ var email = emailInput ? emailInput.value.trim() : '';
3278
+ var field = directForm.querySelector('input[name=customer_email]');
3279
+ if (!field) return;
3280
+ field.value = (email && email.length <= 320 && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) ? email : '';
3091
3281
  }
3092
3282
  if (emailInput) {
3093
- emailInput.addEventListener('input', updateSkipLink);
3094
- emailInput.addEventListener('change', updateSkipLink);
3095
- updateSkipLink();
3096
- }
3097
- if (skipLink) {
3098
- skipLink.addEventListener('click', function(){
3283
+ emailInput.addEventListener('input', syncDirectEmail);
3284
+ emailInput.addEventListener('change', syncDirectEmail);
3285
+ syncDirectEmail();
3286
+ }
3287
+ function showGateNote(text) {
3288
+ if (!gateNote) return;
3289
+ gateNote.style.display = 'block';
3290
+ gateNote.textContent = text;
3291
+ }
3292
+ // A checkout session opens only after a trusted pointer or keyboard event and a
3293
+ // single-use token from the server. The submit button is disabled after the first
3294
+ // submit so a double click cannot spend a second token.
3295
+ function guardForm(form, buttonId, telemetry) {
3296
+ if (!form) return;
3297
+ form.addEventListener('submit', function(ev) {
3298
+ if (form.getAttribute('data-ready') === '1') return;
3299
+ ev.preventDefault();
3300
+ if (!gestureSeen) {
3301
+ showGateNote('Please click or press a key on the page, then try again.');
3302
+ return;
3303
+ }
3304
+ if (form.getAttribute('data-busy') === '1') return;
3305
+ form.setAttribute('data-busy', '1');
3099
3306
  submitted = true;
3100
- sendTelemetry('checkout_interstitial_cta_clicked', {
3101
- ctaId: 'pro_checkout_direct_stripe',
3102
- ctaPlacement: 'checkout_interstitial'
3307
+ if (form === directForm) syncDirectEmail();
3308
+ sendTelemetry('checkout_interstitial_cta_clicked', telemetry(form));
3309
+ var buttons = form.querySelectorAll('button[type=submit]');
3310
+ buttons.forEach(function(btn) { btn.disabled = true; });
3311
+ fetch('/v1/checkout/click-token', {
3312
+ method: 'POST',
3313
+ credentials: 'same-origin',
3314
+ headers: { 'content-type': 'application/json' },
3315
+ body: JSON.stringify({ buttonId: buttonId, landingPage: pick('landing_path') || window.location.pathname })
3316
+ }).then(function(r) {
3317
+ if (!r.ok) throw new Error('token ' + r.status);
3318
+ return r.json();
3319
+ }).then(function(data) {
3320
+ form.querySelector('input[name=click_token]').value = data.token;
3321
+ form.setAttribute('data-ready', '1');
3322
+ form.submit();
3323
+ }).catch(function() {
3324
+ form.removeAttribute('data-busy');
3325
+ buttons.forEach(function(btn) { btn.disabled = false; });
3326
+ showGateNote('Could not confirm the click. Please try again.');
3103
3327
  });
3104
3328
  });
3105
3329
  }
3106
- document.querySelector('form').addEventListener('submit', function(){
3107
- submitted = true;
3108
- var emailInput = document.querySelector('input[name=customer_email]');
3109
- sendTelemetry('checkout_interstitial_cta_clicked', {
3110
- ctaId: 'pro_checkout_confirmed',
3111
- ctaPlacement: 'checkout_interstitial',
3112
- customerEmail: emailInput ? emailInput.value : null
3113
- });
3330
+ guardForm(directForm, 'pro_checkout_direct_stripe', function() {
3331
+ return { ctaId: 'pro_checkout_direct_stripe', ctaPlacement: 'checkout_interstitial' };
3332
+ });
3333
+ guardForm(confirmForm, 'pro_checkout_confirmed', function() {
3334
+ var field = confirmForm.querySelector('input[name=customer_email]');
3114
3335
  try { window.plausible && window.plausible('Checkout Pro Email Submitted', { props: { page:'/checkout/pro', source:'interstitial' } }); } catch(_) {}
3336
+ return { ctaId: 'pro_checkout_confirmed', ctaPlacement: 'checkout_interstitial', customerEmail: field ? field.value : null };
3115
3337
  });
3116
3338
  document.querySelectorAll('[data-reason]').forEach(function(button) {
3117
3339
  button.addEventListener('click', function(){
@@ -3160,6 +3382,7 @@ ${hiddenInputs}
3160
3382
  }).catch(function(){
3161
3383
  if (saved) saved.textContent = 'Feedback saved.';
3162
3384
  });
3385
+ });
3163
3386
  });
3164
3387
  window.addEventListener('pagehide', function(){
3165
3388
  if (!submitted && !feedbackSent) {
@@ -3402,6 +3625,12 @@ function isDirectProSessionSlug(slug) {
3402
3625
  return slug === 'pro-direct' || slug === 'pro-annual' || slug === 'founding-100';
3403
3626
  }
3404
3627
 
3628
+ // Pro subscription links never send a bare GET to a Stripe payment link: a
3629
+ // payment link creates a live session the moment it is opened.
3630
+ function isProSubscriptionSlug(slug) {
3631
+ return isDirectProSessionSlug(slug) || slug === 'operator-pro';
3632
+ }
3633
+
3405
3634
  /**
3406
3635
  * Creates an attributable dynamic Stripe Checkout Session for human 1-click Pro
3407
3636
  * redirects (`/go/pro-direct`, `/go/pro-annual`, `/go/founding-100`) when live
@@ -3415,6 +3644,7 @@ async function tryCreateDirectProCheckoutRedirect({
3415
3644
  hostedConfig,
3416
3645
  journeyState,
3417
3646
  feedbackDir,
3647
+ humanClick,
3418
3648
  }) {
3419
3649
  if (!isDirectProSessionSlug(target.slug) || !process.env.STRIPE_SECRET_KEY || isSyntheticProbeQuery(parsed)) {
3420
3650
  return null;
@@ -3450,6 +3680,7 @@ async function tryCreateDirectProCheckoutRedirect({
3450
3680
  traceId,
3451
3681
  metadata: analyticsMetadata,
3452
3682
  appOrigin: hostedConfig.appOrigin,
3683
+ humanClick,
3453
3684
  });
3454
3685
  if (!sessionResult || !sessionResult.url) {
3455
3686
  return null;
@@ -3471,7 +3702,7 @@ async function tryCreateDirectProCheckoutRedirect({
3471
3702
  return sessionResult.url;
3472
3703
  }
3473
3704
 
3474
- async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadRequest, slug }) {
3705
+ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadRequest, slug, clickToken = '' }) {
3475
3706
  const target = getTrackedLinkTarget(slug);
3476
3707
  if (!target) {
3477
3708
  sendJson(res, 404, {
@@ -3510,6 +3741,7 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3510
3741
 
3511
3742
  const { FEEDBACK_DIR } = getFeedbackPaths();
3512
3743
  const journeyState = resolveJourneyState(req, parsed);
3744
+ applyLandingUtm(parsed, journeyState);
3513
3745
  const isProbeQuery = isSyntheticProbeQuery(parsed);
3514
3746
  const requesterClassification = classifyRequester(req.headers);
3515
3747
  let botClassification = isProbeQuery
@@ -3519,6 +3751,7 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3519
3751
  : { isBot: true, reason: 'no_browser_navigation' });
3520
3752
  if (
3521
3753
  target.botDeflectPath
3754
+ && !isProSubscriptionSlug(target.slug) // these never open a session on GET; the human-click gate limits POSTs
3522
3755
  && !botClassification.isBot
3523
3756
  && !isHeadRequest
3524
3757
  && rapidCheckoutGuard.hit(checkoutRequesterKey(req.headers))
@@ -3556,6 +3789,45 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3556
3789
  res.end();
3557
3790
  return;
3558
3791
  }
3792
+ let proHumanClick = null;
3793
+ if (isProSubscriptionSlug(target.slug)) {
3794
+ const admission = !isHeadRequest && isDirectProSessionSlug(target.slug)
3795
+ ? admitCheckoutClick(req, clickToken)
3796
+ : { ok: false, status: 405, reason: 'method_not_post' };
3797
+ if (admission.ok) {
3798
+ proHumanClick = admission.humanClick;
3799
+ } else {
3800
+ const confirmUrl = new URL('/checkout/pro', hostedConfig.appOrigin);
3801
+ appendTrackedLinkQueryParams(confirmUrl, parsed, { ...target, allowCustomerEmail: false });
3802
+ if (!isHeadRequest && req.method === 'POST') {
3803
+ appendBestEffortTelemetry(
3804
+ FEEDBACK_DIR,
3805
+ {
3806
+ eventType: 'checkout_human_gate_refused',
3807
+ clientType: 'web',
3808
+ page: `/go/${target.slug}`,
3809
+ reason: admission.reason,
3810
+ destinationSlug: target.slug,
3811
+ acquisitionId: journeyState.acquisitionId,
3812
+ visitorId: journeyState.visitorId,
3813
+ sessionId: journeyState.sessionId,
3814
+ },
3815
+ req.headers,
3816
+ `tracked_link_human_gate_refused:${target.slug}`
3817
+ );
3818
+ }
3819
+ res.writeHead(302, {
3820
+ ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
3821
+ 'Cache-Control': 'no-store',
3822
+ 'X-Robots-Tag': 'noindex,nofollow',
3823
+ 'X-ThumbGate-Link-Slug': target.slug,
3824
+ 'X-ThumbGate-Gate-Reason': String(admission.reason || '').replace(/[^a-z_]/g, ''),
3825
+ Location: confirmUrl.toString(),
3826
+ });
3827
+ res.end();
3828
+ return;
3829
+ }
3830
+ }
3559
3831
  if (!isHeadRequest && isDirectProSessionSlug(target.slug) && process.env.STRIPE_SECRET_KEY) {
3560
3832
  try {
3561
3833
  const dynamicSessionUrl = await tryCreateDirectProCheckoutRedirect({
@@ -3565,6 +3837,7 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3565
3837
  hostedConfig,
3566
3838
  journeyState,
3567
3839
  feedbackDir: FEEDBACK_DIR,
3840
+ humanClick: proHumanClick,
3568
3841
  });
3569
3842
  if (dynamicSessionUrl) {
3570
3843
  res.writeHead(req.method === 'POST' ? 303 : 302, {
@@ -3592,9 +3865,25 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3592
3865
  res.end();
3593
3866
  return;
3594
3867
  }
3595
- // Fall back cleanly to static Payment Link if dynamic session creation fails
3868
+ // Dynamic session creation failed: Pro slugs go to the confirm page below.
3869
+ console.warn('[checkout] dynamic session creation failed', target.slug, err && (err.code || err.message));
3596
3870
  }
3597
3871
  }
3872
+ if (isProSubscriptionSlug(target.slug)) {
3873
+ // Admitted, but no session could be made (no key, or Stripe refused): send
3874
+ // the visitor to the confirm page, never to a payment link.
3875
+ const confirmUrl = new URL('/checkout/pro', hostedConfig.appOrigin);
3876
+ appendTrackedLinkQueryParams(confirmUrl, parsed, { ...target, allowCustomerEmail: false });
3877
+ res.writeHead(302, {
3878
+ ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
3879
+ 'Cache-Control': 'no-store',
3880
+ 'X-Robots-Tag': 'noindex,nofollow',
3881
+ 'X-ThumbGate-Link-Slug': target.slug,
3882
+ Location: confirmUrl.toString(),
3883
+ });
3884
+ res.end();
3885
+ return;
3886
+ }
3598
3887
  const destinationUrl = buildTrackedLinkDestination(target, hostedConfig, parsed);
3599
3888
  if (
3600
3889
  target.external
@@ -4081,6 +4370,10 @@ function loadInstallPageHtml(runtimeConfig, pageContext = {}) {
4081
4370
  return loadPublicMarketingTemplateHtml(INSTALL_PAGE_PATH, runtimeConfig, pageContext);
4082
4371
  }
4083
4372
 
4373
+ function loadPreviewPageHtml(runtimeConfig, pageContext = {}) {
4374
+ return loadPublicMarketingTemplateHtml(PREVIEW_PAGE_PATH, runtimeConfig, pageContext);
4375
+ }
4376
+
4084
4377
  function loadPricingPageHtml(runtimeConfig, pageContext = {}) {
4085
4378
  return loadPublicMarketingTemplateHtml(PRICING_PAGE_PATH, runtimeConfig, pageContext);
4086
4379
  }
@@ -4823,6 +5116,7 @@ function renderSitemapXml(runtimeConfig) {
4823
5116
  { dir: 'compare', route: '/compare', priority: '0.85' },
4824
5117
  { dir: 'guides', route: '/guides', priority: '0.85' },
4825
5118
  { dir: 'blog', route: '/blog', priority: '0.8' },
5119
+ { dir: 'reports', route: '/reports', priority: '0.8' },
4826
5120
  ];
4827
5121
  for (const catalog of seoDirectories) {
4828
5122
  const files = fs.readdirSync(path.join(PUBLIC_DIR, catalog.dir)).sort((a, b) => a.localeCompare(b));
@@ -6042,13 +6336,29 @@ function pruneSsoPendingStates(nowMs = Date.now()) {
6042
6336
  }
6043
6337
  }
6044
6338
 
6045
- function issueSsoPendingState(provider, redirectUri, nowMs = Date.now()) {
6339
+ // Where to send someone after sign-in. Only a same-site path that starts with exactly one "/" is accepted;
6340
+ // anything else (//host, https://host, /\host, control characters) falls back, so it can never be an open redirect.
6341
+ function safeNextPath(raw, fallback = '/dashboard') {
6342
+ const value = typeof raw === 'string' ? raw.trim() : '';
6343
+ if (!value || value.length > 300 || !value.startsWith('/') || value.startsWith('//') || /[\\\u0000-\u001f\u007f]/.test(value)) return fallback;
6344
+ let parsedNext;
6345
+ try {
6346
+ const decoded = decodeURIComponent(value);
6347
+ if (decoded.startsWith('//') || /[\\\u0000-\u001f\u007f]/.test(decoded)) return fallback;
6348
+ parsedNext = new URL(value, 'https://next.invalid');
6349
+ } catch { return fallback; }
6350
+ if (parsedNext.origin !== 'https://next.invalid') return fallback;
6351
+ return parsedNext.pathname + parsedNext.search;
6352
+ }
6353
+
6354
+ function issueSsoPendingState(provider, redirectUri, nowMs = Date.now(), next = '/dashboard') {
6046
6355
  pruneSsoPendingStates(nowMs);
6047
6356
  const stateNonce = `st_${crypto.randomBytes(24).toString('hex')}`;
6048
6357
  const oidcNonce = `nc_${crypto.randomBytes(16).toString('hex')}`;
6049
6358
  ssoPendingStates.set(stateNonce, {
6050
6359
  provider,
6051
6360
  redirectUri,
6361
+ next: safeNextPath(next),
6052
6362
  nonce: oidcNonce,
6053
6363
  createdAt: nowMs,
6054
6364
  expiresAt: nowMs + SSO_OAUTH_STATE_TTL_MS,
@@ -6074,6 +6384,7 @@ function ssoError(ssoReason, message) {
6074
6384
  function redirectSsoError(res, reason, statusCode = 302) {
6075
6385
  const raw = String(reason || '').trim().toLowerCase();
6076
6386
  const safeReason = /^[a-z0-9_]{1,48}$/.test(raw) ? raw : 'sso_failed';
6387
+ opsLog.recordSignInFailure(safeReason);
6077
6388
  res.writeHead(statusCode, { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', Location: `/dashboard?sso_error=${safeReason}` });
6078
6389
  res.end();
6079
6390
  }
@@ -6398,7 +6709,7 @@ function resolveOwnerEnterpriseSessionAuth() {
6398
6709
  return { apiKey: 'tg_op_dev_session', subjectType: 'dev_enterprise' };
6399
6710
  }
6400
6711
 
6401
- async function completeSsoSessionAndRedirect(res, { provider, email, ssoName = null, redirectStatus = 302 }) {
6712
+ async function completeSsoSessionAndRedirect(res, { provider, email, ssoName = null, redirectStatus = 302, next = '/dashboard' }) {
6402
6713
  const isOwner = isConfiguredOwnerEmail(email);
6403
6714
  const entitlement = isOwner ? null : await resolvePaidEntitlementForEmail(email);
6404
6715
  const hasPaidKey = !isOwner && Boolean(entitlement?.entitled && entitlement?.apiKey);
@@ -6451,12 +6762,49 @@ async function completeSsoSessionAndRedirect(res, { provider, email, ssoName = n
6451
6762
  'X-Content-Type-Options': 'nosniff',
6452
6763
  'Cache-Control': 'no-store',
6453
6764
  'Set-Cookie': provider === 'google' ? [setCookie, clearStateCookie] : setCookie,
6454
- Location: '/dashboard',
6765
+ Location: safeNextPath(next),
6455
6766
  });
6456
6767
  res.end();
6457
6768
  }
6458
6769
 
6459
- const DEFAULT_HOSTED_OWNER_EMAILS = ['iganapolsky@gmail.com', 'igor.ganapolsky@gmail.com', 'igor@thumbgate.ai'];
6770
+ // Plain sign-in page for owner-only pages. Kept inline so it adds no file to the npm bundle.
6771
+ function renderSigninPage(nextPath, ssoError) {
6772
+ const next = encodeURIComponent(safeNextPath(nextPath));
6773
+ const reason = /^[a-z0-9_]{1,48}$/.test(String(ssoError || '')) ? String(ssoError).replaceAll('_', ' ') : '';
6774
+ const notice = reason ? `<p role="alert" style="color:#f87171">Sign-in did not finish (${reason}). Please try again.</p>` : '';
6775
+ return `<!doctype html>
6776
+ <html lang="en">
6777
+ <head>
6778
+ <meta charset="utf-8">
6779
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6780
+ <meta name="robots" content="noindex, nofollow">
6781
+ <title>Sign in - ThumbGate</title>
6782
+ <style>
6783
+ :root { color-scheme: light dark; --bg: #0b1220; --fg: #e6edf7; --muted: #9fb0c8; --card: #121b2e; --line: #243049; --accent: #22d3ee; }
6784
+ @media (prefers-color-scheme: light) { :root { --bg: #f6f8fb; --fg: #0f172a; --muted: #475569; --card: #fff; --line: #d6dde8; --accent: #0e7490; } }
6785
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: var(--bg); color: var(--fg); font: 16px/1.5 system-ui, -apple-system, Segoe UI, sans-serif; }
6786
+ main { width: min(420px, calc(100vw - 32px)); background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 28px; }
6787
+ h1 { margin: 0 0 6px; font-size: 22px; }
6788
+ p { margin: 0 0 18px; color: var(--muted); }
6789
+ a.btn { display: flex; align-items: center; justify-content: center; min-height: 44px; margin-top: 10px; border-radius: 8px; border: 1px solid var(--line); color: var(--fg); text-decoration: none; font-weight: 600; }
6790
+ a.btn:focus-visible, a.btn:hover { border-color: var(--accent); outline: none; }
6791
+ small { display: block; margin-top: 18px; color: var(--muted); }
6792
+ </style>
6793
+ </head>
6794
+ <body>
6795
+ <main>
6796
+ <h1>Sign in to ThumbGate</h1>
6797
+ <p>Use your Google or Apple account. ThumbGate never asks for a typed email address.</p>
6798
+ ${notice}
6799
+ <a class="btn" id="signinGoogle" href="/v1/cloud/sso/authorize?provider=google&amp;next=${next}">Continue with Google</a>
6800
+ <a class="btn" id="signinApple" href="/v1/cloud/sso/authorize?provider=apple&amp;next=${next}">Continue with Apple</a>
6801
+ </main>
6802
+ </body>
6803
+ </html>
6804
+ `;
6805
+ }
6806
+
6807
+ const DEFAULT_HOSTED_OWNER_EMAILS =['iganapolsky@gmail.com', 'igor.ganapolsky@gmail.com', 'igor@thumbgate.ai'];
6460
6808
 
6461
6809
  function ensureHostedActivationsReady(baseFeedbackDir, extraOpts = {}) {
6462
6810
  const { backfillHostedAccountActivations } = require('../../scripts/dashboard');
@@ -6693,6 +7041,7 @@ async function handleAppleSsoCallback(req, res) {
6693
7041
  email: claims.email,
6694
7042
  ssoName: firstSignInUser?.name || null,
6695
7043
  redirectStatus: 303,
7044
+ next: stateEntry.next,
6696
7045
  });
6697
7046
  } catch (err) {
6698
7047
  redirectSsoError(res, err?.ssoReason || 'callback_failed', 303);
@@ -6981,6 +7330,7 @@ function isBillingSummaryAuthorized(req, expectedAdminKey, expectedOperatorKey)
6981
7330
  const OPERATOR_READONLY_GET_PATHS = new Set([
6982
7331
  '/v1/billing/summary',
6983
7332
  '/v1/analytics/funnel',
7333
+ '/v1/analytics/sources',
6984
7334
  '/v1/dashboard',
6985
7335
  '/v1/dashboard/render-spec',
6986
7336
  '/v1/dashboard/ai-inventory',
@@ -7148,7 +7498,10 @@ function resolveDocumentImportFilePath(inputPath, options = {}) {
7148
7498
  const CONTINUE_DATA_SCOPE = Symbol('trustedDataScopeContinuation');
7149
7499
 
7150
7500
  function createApiServer({ ownerAdminDependencies = {} } = {}) {
7501
+ humanGate = buildHumanGate();
7151
7502
  const server = withoutDataScope(() => createUnscopedApiServer({ ownerAdminDependencies }));
7503
+ // The once-a-minute heartbeat the owner console's uptime figure counts gaps in. Not under the test runner.
7504
+ if (!process.env.NODE_TEST_CONTEXT) server.once('listening', () => opsLog.startHeartbeat(withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR)));
7152
7505
  const [listener] = server.listeners('request');
7153
7506
  server.removeListener('request', listener);
7154
7507
  server.on('request', (req, res) => {
@@ -7177,7 +7530,12 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7177
7530
  : pathname === '/health' ? 'health' : pathname.startsWith('/v1/') ? 'api' : 'page';
7178
7531
  if (!observedRequests.has(req)) {
7179
7532
  observedRequests.add(req);
7180
- res.once('finish', () => adminRuntime.recordResponse(res.statusCode, category));
7533
+ const startedNs = process.hrtime.bigint();
7534
+ res.once('finish', () => {
7535
+ adminRuntime.recordResponse(res.statusCode, category);
7536
+ adminRuntime.recordTiming(category, Number(process.hrtime.bigint() - startedNs) / 1e6);
7537
+ if (res.statusCode >= 500 && res.statusCode <= 599) opsLog.recordError(pathname, res.statusCode);
7538
+ });
7181
7539
  }
7182
7540
  if (privatePath.matched) {
7183
7541
  const headers = ownerAdmin.PRIVATE_HEADERS;
@@ -7187,8 +7545,20 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7187
7545
  };
7188
7546
  const feedbackDir = withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR);
7189
7547
  const cookies = parseCookies(req.headers?.cookie || '');
7190
- const identity = ownerAdmin.readOwnerIdentity({ feedbackDir, token: cookies[PAID_AUTH_COOKIE_NAME], isOwner: isConfiguredOwnerEmail });
7191
- if (!identity || !privatePath.pathname) { respond(404, { error: 'Not found' }); return; }
7548
+ const session = ownerAdmin.readSessionState({ feedbackDir, token: cookies[PAID_AUTH_COOKIE_NAME], isOwner: isConfiguredOwnerEmail });
7549
+ const identity = session.state === 'owner' ? { provider: session.provider } : null;
7550
+ if (!privatePath.pathname) { respond(404, { error: 'Not found' }); return; }
7551
+ if (!identity && session.state === 'non_owner') {
7552
+ console.warn(`[admin] 403 signed-in session is not on THUMBGATE_OWNER_EMAILS (provider=${session.provider})`);
7553
+ respond(403, { error: 'Forbidden' });
7554
+ return;
7555
+ }
7556
+ if (!identity && ['/admin', '/admin/', '/admin.html'].includes(privatePath.pathname) && ['GET', 'HEAD'].includes(req.method)) {
7557
+ res.writeHead(302, { ...headers, Location: '/signin?next=%2Fadmin' });
7558
+ res.end();
7559
+ return;
7560
+ }
7561
+ if (!identity) { respond(404, { error: 'Not found' }); return; }
7192
7562
  let route;
7193
7563
  try { route = ownerAdmin.parseAdminRoute(privatePath.pathname, parsed.searchParams); }
7194
7564
  catch { respond(400, { error: 'Invalid query' }); return; }
@@ -7211,6 +7581,8 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7211
7581
  feedbackDir, buildMetadata: BUILD_METADATA, runtime: adminRuntime,
7212
7582
  hashDataIdentity, buildHostedTenantIdentity,
7213
7583
  health: () => ({ version: pkg.version, buildSha: BUILD_METADATA.buildSha, uptime: process.uptime() }),
7584
+ // The commit title comes from GitHub's public API; tests never reach the network.
7585
+ lookupCommitTitle: process.env.NODE_TEST_CONTEXT ? undefined : (sha, signal) => ownerAdmin.githubCommitTitle(sha, signal),
7214
7586
  ...ownerAdminDependencies,
7215
7587
  }, cancellation.signal));
7216
7588
  const body = JSON.stringify(result);
@@ -7506,6 +7878,43 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7506
7878
  return;
7507
7879
  }
7508
7880
 
7881
+ if (isGetLikeRequest && pathname === '/js/connect-panel.js') {
7882
+ try {
7883
+ const script = fs.readFileSync(CONNECT_PANEL_SCRIPT_PATH, 'utf-8');
7884
+ res.writeHead(200, {
7885
+ 'Content-Type': 'application/javascript; charset=utf-8',
7886
+ 'Cache-Control': 'public, max-age=300',
7887
+ });
7888
+ if (!isHeadRequest) {
7889
+ res.end(script);
7890
+ } else {
7891
+ res.end();
7892
+ }
7893
+ } catch {
7894
+ sendJson(res, 404, { error: 'Connect panel script not found' });
7895
+ }
7896
+ return;
7897
+ }
7898
+
7899
+ if (isGetLikeRequest && (pathname === '/preview' || pathname === '/preview.html')) {
7900
+ try {
7901
+ servePublicMarketingPage({
7902
+ req,
7903
+ res,
7904
+ parsed,
7905
+ hostedConfig,
7906
+ isHeadRequest,
7907
+ renderHtml: loadPreviewPageHtml,
7908
+ extraTelemetry: {
7909
+ pageType: 'preview',
7910
+ },
7911
+ });
7912
+ } catch (err) {
7913
+ sendText(res, 500, err.message || 'Preview page unavailable');
7914
+ }
7915
+ return;
7916
+ }
7917
+
7509
7918
  if (isGetLikeRequest && pathname === '/js/buyer-intent.js') {
7510
7919
  try {
7511
7920
  const script = fs.readFileSync(BUYER_INTENT_SCRIPT_PATH, 'utf-8');
@@ -7759,9 +8168,10 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7759
8168
  const trackedLinkMatch = pathname.match(/^\/go\/([^/]+)$/);
7760
8169
  if ((isGetLikeRequest || req.method === 'POST') && trackedLinkMatch) {
7761
8170
  let trackedParsed = parsed;
8171
+ let trackedClickToken = '';
7762
8172
  if (req.method === 'POST') {
7763
8173
  const target = getTrackedLinkTarget(trackedLinkMatch[1]);
7764
- if (!target?.requiresPost) {
8174
+ if (!target?.requiresPost && !(target && isDirectProSessionSlug(target.slug))) {
7765
8175
  sendJson(res, target ? 405 : 404, target
7766
8176
  ? { error: 'POST is not supported for this tracked link' }
7767
8177
  : { error: 'Tracked link not found', allowed: Object.keys(TRACKED_LINK_TARGETS) }, {
@@ -7778,6 +8188,7 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7778
8188
  return;
7779
8189
  }
7780
8190
  const form = await parseFormBody(req, 16 * 1024);
8191
+ trackedClickToken = checkoutClickTokenFrom(req, form);
7781
8192
  trackedParsed = new URL(parsed.toString());
7782
8193
  for (const [key, value] of Object.entries(form)) {
7783
8194
  if (key === 'customer_email' || TRACKED_LINK_QUERY_KEYS.has(key)) {
@@ -7792,6 +8203,7 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7792
8203
  hostedConfig,
7793
8204
  isHeadRequest,
7794
8205
  slug: trackedLinkMatch[1],
8206
+ clickToken: trackedClickToken,
7795
8207
  });
7796
8208
  return;
7797
8209
  }
@@ -7881,7 +8293,13 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7881
8293
  feedbackDir: requestSafeDataDir,
7882
8294
  limit: 10,
7883
8295
  });
8296
+ // Attribute the click to the project the status line was showing.
8297
+ const quickProject = projectForCapture({}, {
8298
+ hosted: !isLoopbackHost(getRequestHostHeader(req)),
8299
+ cwd: resolveRequestProjectDir(req, parsed),
8300
+ });
7884
8301
  const result = captureFeedback({
8302
+ ...quickProject,
7885
8303
  signal,
7886
8304
  context: 'Quick capture from Claude Code statusline',
7887
8305
  chatHistory,
@@ -7994,7 +8412,23 @@ async function addContext(){
7994
8412
 
7995
8413
  if (isGetLikeRequest && (pathname === '/dashboard' || pathname === '/cloud')) {
7996
8414
  try {
7997
- const html = loadDashboardPageHtml(req, expectedApiKey);
8415
+ const dashCookies = parseCookies(req.headers?.cookie || '');
8416
+ const dashSession = getPaidAuthSessionEntry(dashCookies[PAID_AUTH_COOKIE_NAME], expectedApiKey, expectedOperatorKey);
8417
+ const dashProviders = getConfiguredSsoProviders();
8418
+ const dashForwarded = req.headers['x-forwarded-host'];
8419
+ const dashHost = Array.isArray(dashForwarded) ? dashForwarded[0] : dashForwarded || req.headers.host || '';
8420
+ // One sign-in page only: a signed-out visitor on the hosted site goes to /signin. Local dashboards
8421
+ // (loopback host, bootstrap key) and servers with no sign-in provider keep serving the dashboard.
8422
+ if (!dashSession && !isLoopbackHost(dashHost) && !resolveLocalPageBootstrap(req, expectedApiKey).bootstrapActive && (dashProviders.google || dashProviders.apple)) {
8423
+ const ssoErr = parsed.searchParams.get('sso_error');
8424
+ const errPart = /^[a-z0-9_]{1,48}$/.test(String(ssoErr || '')) ? `&sso_error=${ssoErr}` : '';
8425
+ res.writeHead(302, { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', Location: `/signin?next=${encodeURIComponent(pathname)}${errPart}` });
8426
+ res.end();
8427
+ return;
8428
+ }
8429
+ let html = loadDashboardPageHtml(req, expectedApiKey);
8430
+ const dashOwner = ownerAdmin.readSessionState({ feedbackDir: withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR), token: dashCookies[PAID_AUTH_COOKIE_NAME], isOwner: isConfiguredOwnerEmail }).state === 'owner';
8431
+ if (dashOwner) html = html.replace(/(<a href="\/lessons"[^>]*>Lessons<\/a>)/, '$1<a href="/admin" class="nav-tab" id="navAdmin">Admin</a>');
7998
8432
  sendHtml(res, 200, html, {}, { headOnly: isHeadRequest });
7999
8433
  } catch {
8000
8434
  sendJson(res, 404, { error: 'Dashboard page not found' });
@@ -8007,10 +8441,11 @@ async function addContext(){
8007
8441
  const provider = ['google', 'apple'].includes(rawProvider) ? rawProvider : 'invalid';
8008
8442
  const appOrigin = hostedConfig.appOrigin || 'https://thumbgate.ai';
8009
8443
  const callbackUrl = `${appOrigin}/v1/cloud/sso/callback?provider=${encodeURIComponent(provider)}`;
8444
+ const nextPath = safeNextPath(parsed.searchParams.get('next'));
8010
8445
  const googleClientId = String(process.env.GOOGLE_CLIENT_ID || '').trim();
8011
8446
  const appleClientId = String(process.env.APPLE_CLIENT_ID || '').trim();
8012
8447
  if (provider === 'google' && googleClientId) {
8013
- const stateNonce = issueSsoPendingState('google', callbackUrl);
8448
+ const stateNonce = issueSsoPendingState('google', callbackUrl, Date.now(), nextPath);
8014
8449
  const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${encodeURIComponent(googleClientId)}&redirect_uri=${encodeURIComponent(callbackUrl)}&response_type=code&scope=openid%20email%20profile&state=${encodeURIComponent(stateNonce)}`;
8015
8450
  const ssoStateCookie = serializeCookie(SSO_STATE_COOKIE_NAME, stateNonce, {
8016
8451
  maxAge: Math.floor(SSO_OAUTH_STATE_TTL_MS / 1000),
@@ -8029,7 +8464,7 @@ async function addContext(){
8029
8464
  }
8030
8465
  if (provider === 'apple' && appleClientId) {
8031
8466
  const appleCallbackUrl = `${appOrigin.replace(/^http:\/\//i, 'https://')}/v1/cloud/sso/apple/callback`;
8032
- const stateNonce = issueSsoPendingState('apple', appleCallbackUrl);
8467
+ const stateNonce = issueSsoPendingState('apple', appleCallbackUrl, Date.now(), nextPath);
8033
8468
  const pendingNonce = ssoPendingStates.get(stateNonce)?.nonce || stateNonce;
8034
8469
  const appleAuthUrl = `https://appleid.apple.com/auth/authorize?client_id=${encodeURIComponent(appleClientId)}&redirect_uri=${encodeURIComponent(appleCallbackUrl)}&response_type=code&scope=name%20email&response_mode=form_post&state=${encodeURIComponent(stateNonce)}&nonce=${encodeURIComponent(pendingNonce)}`;
8035
8470
  if (parsed.searchParams.get('format') === 'json') {
@@ -8120,6 +8555,7 @@ async function addContext(){
8120
8555
  provider: 'google',
8121
8556
  email: claims.email,
8122
8557
  redirectStatus: 302,
8558
+ next: stateEntry.next,
8123
8559
  });
8124
8560
  } catch (err) {
8125
8561
  redirectSsoError(res, err?.ssoReason || 'callback_failed');
@@ -8892,6 +9328,17 @@ async function addContext(){
8892
9328
  return;
8893
9329
  }
8894
9330
 
9331
+ if (isGetLikeRequest && pathname.startsWith('/reports/')) {
9332
+ try {
9333
+ const reportPath = resolvePublicHtmlFile(REPORT_PAGE_PATHS_BY_SLUG, pathname.replace('/reports/', ''));
9334
+ if (!reportPath) { sendJson(res, 404, { error: 'Report not found' }); return; }
9335
+ const requestHost = getSafePublicRequestHost(req);
9336
+ const html = normalizePublicMarketingHtml(fs.readFileSync(reportPath, 'utf-8'), hostedConfig, requestHost);
9337
+ sendHtml(res, 200, html, {}, { headOnly: isHeadRequest });
9338
+ } catch { sendJson(res, 404, { error: 'Report not found' }); }
9339
+ return;
9340
+ }
9341
+
8895
9342
  if (isGetLikeRequest && pathname.startsWith('/use-cases/')) {
8896
9343
  try {
8897
9344
  const useCasePath = resolvePublicHtmlFile(USE_CASE_PAGE_PATHS_BY_SLUG, pathname.replace('/use-cases/', ''));
@@ -8922,7 +9369,7 @@ async function addContext(){
8922
9369
  sendJson(res, 403, { error: 'Forbidden' });
8923
9370
  return;
8924
9371
  }
8925
- serveStaticFile(res, resolved, { headOnly: isHeadRequest });
9372
+ serveStaticFile(res, resolved, { headOnly: isHeadRequest, rangeHeader: req.headers.range });
8926
9373
  return;
8927
9374
  }
8928
9375
 
@@ -8958,7 +9405,9 @@ async function addContext(){
8958
9405
  parsed,
8959
9406
  hostedConfig,
8960
9407
  isHeadRequest,
8961
- renderHtml: loadLandingPageHtml,
9408
+ renderHtml: parsed.searchParams.get('signed_out') === '1'
9409
+ ? (...renderArgs) => String(loadLandingPageHtml(...renderArgs)).replace(/(<body[^>]*>)/i, '$1<p role="status" id="signedOutNote" style="margin:0;padding:10px 16px;text-align:center;font:14px system-ui,sans-serif;background:#0f172a;color:#e2e8f0">You\'re signed out.</p>')
9410
+ : loadLandingPageHtml,
8962
9411
  extraTelemetry: {
8963
9412
  pageType: 'homepage',
8964
9413
  },
@@ -8982,6 +9431,7 @@ async function addContext(){
8982
9431
  return;
8983
9432
  }
8984
9433
 
9434
+ let postedClickToken = '';
8985
9435
  if (req.method === 'POST') {
8986
9436
  const contentType = String(req.headers['content-type'] || '').toLowerCase();
8987
9437
  if (!contentType.includes('application/x-www-form-urlencoded')) {
@@ -8991,6 +9441,7 @@ async function addContext(){
8991
9441
  return;
8992
9442
  }
8993
9443
  const form = await parseFormBody(req, 16 * 1024);
9444
+ postedClickToken = checkoutClickTokenFrom(req, form);
8994
9445
  for (const [key, value] of Object.entries(form)) {
8995
9446
  if (
8996
9447
  key === 'confirm'
@@ -9004,6 +9455,7 @@ async function addContext(){
9004
9455
 
9005
9456
  const { FEEDBACK_DIR } = getFeedbackPaths();
9006
9457
  const journeyState = resolveJourneyState(req, parsed);
9458
+ applyLandingUtm(parsed, journeyState);
9007
9459
  const bootstrapBody = buildCheckoutBootstrapBody(parsed, req, journeyState);
9008
9460
  const traceId = bootstrapBody.traceId || createJourneyId('checkout');
9009
9461
  const analyticsMetadata = buildCheckoutAttributionMetadata(bootstrapBody, req, traceId);
@@ -9031,15 +9483,11 @@ async function addContext(){
9031
9483
  // confirmation and form POST. This prevents browser-shaped monitors
9032
9484
  // from minting anonymous sessions while preserving a one-field path to
9033
9485
  // Stripe for real buyers.
9034
- const isConfirmedCheckout = (
9035
- (req.method === 'POST' && hasValidCustomerEmailHint)
9036
- || (hasConfirmFlag && hasValidCustomerEmailHint)
9037
- ) && botShouldBypass;
9038
- // Legacy env-gated bypass. It is default-off and still requires a valid
9039
- // email plus a non-bot request; enabling it must never re-open anonymous
9040
- // Stripe-session creation. Attribution is preserved via
9041
- // buildCheckoutFallbackUrl.
9042
- const interstitialBypassEnabled = process.env.THUMBGATE_CHECKOUT_INTERSTITIAL_BYPASS === '1';
9486
+ // Only a POST can confirm. A GET, even with confirm=1 and an email, shows
9487
+ // the page: a session opens only after a confirmed human click.
9488
+ const isConfirmedCheckout = (req.method === 'POST' && hasValidCustomerEmailHint) && botShouldBypass;
9489
+ // The old env-gated interstitial bypass (a 302 straight to a Stripe payment
9490
+ // link on a GET) is removed: a bare GET must never reach Stripe.
9043
9491
  const interstitialSampleRate = normalizeCheckoutInterstitialSampleRate(
9044
9492
  process.env.THUMBGATE_CHECKOUT_INTERSTITIAL_SAMPLE_RATE
9045
9493
  );
@@ -9048,47 +9496,6 @@ async function addContext(){
9048
9496
  traceId,
9049
9497
  analyticsMetadata,
9050
9498
  });
9051
- if (
9052
- !isConfirmedCheckout
9053
- && interstitialBypassEnabled
9054
- && req.method !== 'POST'
9055
- && botShouldBypass
9056
- && hasValidCustomerEmailHint
9057
- && !interstitialSampled
9058
- ) {
9059
- // Always target the pro Stripe Payment Link directly. The
9060
- // hostedConfig.checkoutFallbackUrl (e.g. https://thumbgate.ai/go/pro)
9061
- // is a router that 302s back to /checkout/pro, which would create a
9062
- // redirect loop when bypass is on. Env override via
9063
- // THUMBGATE_CHECKOUT_PRO_STRIPE_URL is supported for future
9064
- // price-link rotation without a redeploy.
9065
- const bypassTarget = process.env.THUMBGATE_CHECKOUT_PRO_STRIPE_URL
9066
- || PRO_CHECKOUT_URL;
9067
- appendBestEffortTelemetry(FEEDBACK_DIR, {
9068
- eventType: 'checkout_interstitial_bypass_redirect',
9069
- clientType: 'web',
9070
- traceId,
9071
- acquisitionId: analyticsMetadata.acquisitionId,
9072
- visitorId: analyticsMetadata.visitorId,
9073
- sessionId: analyticsMetadata.sessionId,
9074
- utmSource: analyticsMetadata.utmSource,
9075
- utmMedium: analyticsMetadata.utmMedium,
9076
- utmCampaign: analyticsMetadata.utmCampaign,
9077
- utmContent: analyticsMetadata.utmContent,
9078
- utmTerm: analyticsMetadata.utmTerm,
9079
- referrer: analyticsMetadata.referrer,
9080
- referrerHost: analyticsMetadata.referrerHost,
9081
- page: '/checkout/pro',
9082
- planId: analyticsMetadata.planId,
9083
- interstitialSampleRate,
9084
- }, req.headers, 'checkout_interstitial_bypass_redirect');
9085
- res.writeHead(302, {
9086
- ...responseHeaders,
9087
- Location: buildCheckoutFallbackUrl(bypassTarget, analyticsMetadata),
9088
- });
9089
- res.end();
9090
- return;
9091
- }
9092
9499
  // Plausible funnel event #1 of 3: page view. Fired before interstitial
9093
9500
  // deflection so we get the full top-of-funnel count, with isBot as a
9094
9501
  // prop so the dashboard can filter human vs. crawler traffic. Fire-and-forget.
@@ -9158,6 +9565,27 @@ async function addContext(){
9158
9565
  return;
9159
9566
  }
9160
9567
 
9568
+ const checkoutAdmission = admitCheckoutClick(req, postedClickToken);
9569
+ if (!checkoutAdmission.ok) {
9570
+ appendBestEffortTelemetry(FEEDBACK_DIR, {
9571
+ eventType: 'checkout_human_gate_refused',
9572
+ clientType: 'web',
9573
+ traceId,
9574
+ page: '/checkout/pro',
9575
+ reason: checkoutAdmission.reason,
9576
+ planId: analyticsMetadata.planId,
9577
+ }, req.headers, 'checkout_human_gate_refused');
9578
+ const refusedHtml = renderCheckoutIntentPage(normalizedCheckoutEmail || '', parsed, {
9579
+ includeHiddenAttribution: true,
9580
+ });
9581
+ sendHtml(res, checkoutAdmission.status, refusedHtml, {
9582
+ ...responseHeaders,
9583
+ 'Cache-Control': 'no-store',
9584
+ ...(checkoutAdmission.status === 429 ? { 'Retry-After': '60' } : {}),
9585
+ });
9586
+ return;
9587
+ }
9588
+
9161
9589
  bootstrapBody.customerEmail = normalizedCheckoutEmail || undefined;
9162
9590
 
9163
9591
  appendBestEffortTelemetry(FEEDBACK_DIR, {
@@ -9227,6 +9655,7 @@ async function addContext(){
9227
9655
  traceId,
9228
9656
  metadata: analyticsMetadata,
9229
9657
  appOrigin: hostedConfig.appOrigin,
9658
+ humanClick: checkoutAdmission.humanClick,
9230
9659
  });
9231
9660
 
9232
9661
  if (result.url) {
@@ -9374,10 +9803,15 @@ async function addContext(){
9374
9803
 
9375
9804
  const { FEEDBACK_DIR } = getFeedbackPaths();
9376
9805
  const journeyState = resolveJourneyState(req, parsed);
9806
+ // Any GET reaches this page (bots, probes, our own agents). It only counts
9807
+ // as a success when Stripe reports the session_id as paid.
9808
+ const successCheck = await verifyPaidCheckoutSession(parsed.searchParams.get('session_id'));
9809
+ const successEventType = successCheck.verified ? 'checkout_success_page_view' : 'checkout_success_unverified';
9377
9810
  appendBestEffortTelemetry(FEEDBACK_DIR, {
9378
- eventType: 'checkout_success_page_view',
9811
+ eventType: successEventType,
9379
9812
  ...buildCheckoutPageTelemetryMetadata(parsed, req, journeyState, '/success'),
9380
- }, req.headers, 'checkout_success_page_view');
9813
+ ...(successCheck.verified ? {} : { reasonCode: successCheck.reason }),
9814
+ }, req.headers, successEventType);
9381
9815
  sendHtml(
9382
9816
  res,
9383
9817
  200,
@@ -10537,6 +10971,25 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
10537
10971
  // Public terms of service — required by Stripe / Stripe Checkout for the
10538
10972
  // "Terms of service URL" field in Business → Public details. Mirrors the
10539
10973
  // /privacy + /support pages: thin HTML, no external deps, no DB hit.
10974
+ if (isGetLikeRequest && (pathname === '/signin' || pathname === '/signin.html')) {
10975
+ sendHtml(res, 200, renderSigninPage(parsed.searchParams.get('next'), parsed.searchParams.get('sso_error')), { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }, { headOnly: isHeadRequest });
10976
+ return;
10977
+ }
10978
+
10979
+ // Log out: end the session, clear the cookie, and land on the public landing page with a short note.
10980
+ if (req.method === 'POST' && pathname === '/logout') {
10981
+ const logoutCookies = parseCookies(req.headers?.cookie || '');
10982
+ if (logoutCookies[PAID_AUTH_COOKIE_NAME]) deletePaidAuthSession(logoutCookies[PAID_AUTH_COOKIE_NAME]);
10983
+ res.writeHead(303, {
10984
+ 'X-Content-Type-Options': 'nosniff',
10985
+ 'Cache-Control': 'no-store',
10986
+ 'Set-Cookie': serializeCookie(PAID_AUTH_COOKIE_NAME, '', { maxAge: 0, httpOnly: true, sameSite: 'Lax', secure: true }),
10987
+ Location: '/?signed_out=1',
10988
+ });
10989
+ res.end();
10990
+ return;
10991
+ }
10992
+
10540
10993
  if (isGetLikeRequest && (pathname === '/terms' || pathname === '/terms.html' || pathname === '/eula' || pathname === '/eula.html')) {
10541
10994
  try {
10542
10995
  const termsHtml = fs.readFileSync(path.join(PUBLIC_DIR, 'terms.html'), 'utf-8');
@@ -10780,6 +11233,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10780
11233
 
10781
11234
  const sig = req.headers['stripe-signature'] || '';
10782
11235
  if (!verifyWebhookSignature(rawBody, sig)) {
11236
+ opsLog.recordWebhook(false, 400);
10783
11237
  sendProblem(res, {
10784
11238
  type: PROBLEM_TYPES.WEBHOOK_INVALID,
10785
11239
  title: 'Invalid webhook signature',
@@ -10790,6 +11244,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10790
11244
  }
10791
11245
 
10792
11246
  const result = await handleWebhook(rawBody, sig);
11247
+ opsLog.recordWebhook(!(result && (result.reason === 'invalid_signature' || result.retryable === true)), result?.retryable === true ? 503 : result?.reason === 'invalid_signature' ? 400 : 200);
10793
11248
  if (result && result.reason === 'invalid_signature') {
10794
11249
  sendProblem(res, {
10795
11250
  type: PROBLEM_TYPES.WEBHOOK_INVALID,
@@ -10811,6 +11266,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10811
11266
  sendJson(res, 200, result);
10812
11267
 
10813
11268
  } catch (err) {
11269
+ opsLog.recordWebhook(false, err.statusCode || 500);
10814
11270
  sendProblem(res, {
10815
11271
  type: !err.statusCode || err.statusCode >= 500 ? PROBLEM_TYPES.INTERNAL : PROBLEM_TYPES.BAD_REQUEST,
10816
11272
  title: !err.statusCode || err.statusCode >= 500 ? 'Internal Server Error' : 'Request Error',
@@ -11043,6 +11499,38 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11043
11499
  return;
11044
11500
  }
11045
11501
 
11502
+ // Short-lived single-use token for the human-click gate. Page JS calls this
11503
+ // only after a trusted pointer or keyboard event (see renderCheckoutIntentPage).
11504
+ if (pathname === '/v1/checkout/click-token') {
11505
+ const tokenHeaders = { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex,nofollow' };
11506
+ if (req.method !== 'POST') {
11507
+ sendJson(res, 405, { error: 'POST required' }, { ...tokenHeaders, Allow: 'POST' });
11508
+ return;
11509
+ }
11510
+ if (!isSameOriginCheckoutRequest(req, hostedConfig.appOrigin)) {
11511
+ sendJson(res, 403, { error: 'Same-origin request required', code: 'HUMAN_CLICK_REQUIRED' }, tokenHeaders);
11512
+ return;
11513
+ }
11514
+ let tokenBody = {};
11515
+ try {
11516
+ tokenBody = await readProjectBody(req);
11517
+ } catch {
11518
+ tokenBody = {};
11519
+ }
11520
+ const token = humanGate.issueToken({
11521
+ headers: req.headers,
11522
+ remoteAddress: req.socket && req.socket.remoteAddress,
11523
+ buttonId: tokenBody && tokenBody.buttonId,
11524
+ landingPage: tokenBody && tokenBody.landingPage,
11525
+ });
11526
+ if (!token) {
11527
+ sendJson(res, 403, { error: 'Browser request required', code: 'HUMAN_CLICK_REQUIRED' }, tokenHeaders);
11528
+ return;
11529
+ }
11530
+ sendJson(res, 200, { token, expiresInSeconds: 120 }, tokenHeaders);
11531
+ return;
11532
+ }
11533
+
11046
11534
  // Public checkout session creation for top-of-funnel acquisition.
11047
11535
  if (req.method === 'POST' && pathname === '/v1/billing/checkout') {
11048
11536
  try {
@@ -11061,6 +11549,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11061
11549
  throw createHttpError(400, 'customerEmail must be a valid email address');
11062
11550
  }
11063
11551
 
11552
+ // Checked after the cheap validation so a typo does not burn the token.
11553
+ const admission = admitCheckoutClick(req, checkoutClickTokenFrom(req, { click_token: body.clickToken }));
11554
+ if (!admission.ok) {
11555
+ const err = createHttpError(admission.status === 405 ? 403 : admission.status, `A confirmed human click is required (${admission.reason}).`);
11556
+ err.code = 'HUMAN_CLICK_REQUIRED';
11557
+ throw err;
11558
+ }
11559
+
11064
11560
  const result = await createCheckoutSession({
11065
11561
  successUrl: body.successUrl || buildCheckoutFallbackUrl(
11066
11562
  buildHostedSuccessUrl(hostedConfig.appOrigin, traceId),
@@ -11075,6 +11571,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11075
11571
  traceId,
11076
11572
  metadata: analyticsMetadata,
11077
11573
  appOrigin: hostedConfig.appOrigin,
11574
+ humanClick: admission.humanClick,
11078
11575
  });
11079
11576
  sendJson(res, 200, {
11080
11577
  ...result,
@@ -11093,6 +11590,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11093
11590
  title: !err.statusCode || err.statusCode >= 500 ? 'Internal Server Error' : 'Request Error',
11094
11591
  status: err.statusCode || 500,
11095
11592
  detail: err.message || 'An unexpected error occurred.',
11593
+ ...(err.code === 'HUMAN_CLICK_REQUIRED' ? { code: 'HUMAN_CLICK_REQUIRED' } : {}),
11096
11594
  }, getPublicBillingHeaders(fallbackTraceId));
11097
11595
  }
11098
11596
  return;
@@ -12972,6 +13470,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
12972
13470
  return;
12973
13471
  }
12974
13472
 
13473
+ // GET /v1/analytics/sources -- visits, installs and checkout starts by utm_source, last 7 and 30 days
13474
+ if (req.method === 'GET' && pathname === '/v1/analytics/sources') {
13475
+ if (!isBillingSummaryAuthorized(req, expectedApiKey, expectedOperatorKey)) throw createHttpError(403, 'Admin or operator API key required for this endpoint.');
13476
+ sendJson(res, 200, getUtmSourceSummary(requestFeedbackDir), { 'Cache-Control': 'no-store' });
13477
+ return;
13478
+ }
13479
+
12975
13480
  // GET /v1/analytics/losses -- explain where buyer dollars are falling out of the funnel
12976
13481
  if (req.method === 'GET' && pathname === '/v1/analytics/losses') {
12977
13482
  const dashboardResult = await loadLiveDashboardDataOrRespondProblem(
@@ -13593,6 +14098,7 @@ module.exports = {
13593
14098
  createApiServer,
13594
14099
  startServer,
13595
14100
  __test__: {
14101
+ inferSource,
13596
14102
  PRO_CHECKOUT_URL,
13597
14103
  escapeHtmlAttribute,
13598
14104
  renderCheckoutIntentPage,