thumbgate 1.40.3 → 1.40.6

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 (54) hide show
  1. package/.agents/skills/comet-session-logger/SKILL.md +8 -5
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +7 -2
  5. package/adapters/claude/.mcp.json +3 -3
  6. package/adapters/forge/forge.yaml +3 -3
  7. package/adapters/future-agi/.mcp.json +1 -1
  8. package/adapters/future-agi/config.toml +1 -1
  9. package/adapters/future-agi/opencode.json +1 -1
  10. package/adapters/herdr/herdr-plugin.toml +2 -2
  11. package/adapters/mcp/server-stdio.js +1 -1
  12. package/adapters/opencode/opencode.json +1 -1
  13. package/config/github-about.json +1 -1
  14. package/config/post-deploy-marketing-pages.json +1 -1
  15. package/package.json +35 -7
  16. package/public/about.html +2 -2
  17. package/public/admin.html +546 -50
  18. package/public/case-studies.html +1 -0
  19. package/public/dashboard.html +7 -6
  20. package/public/diagnostic.html +15 -12
  21. package/public/index.html +210 -88
  22. package/public/install.html +9 -8
  23. package/public/js/connect-panel.js +437 -0
  24. package/public/learn.html +8 -0
  25. package/public/numbers.html +2 -2
  26. package/public/preview.html +42 -0
  27. package/public/pricing.html +55 -10
  28. package/public/support.html +1 -1
  29. package/public/terms.html +1 -1
  30. package/scripts/auto-promote-gates.js +29 -4
  31. package/scripts/billing.js +189 -4
  32. package/scripts/cap-hit-counter.js +47 -0
  33. package/scripts/checkout-human-gate.js +248 -0
  34. package/scripts/checkout-session-count.js +119 -0
  35. package/scripts/claude-feedback-sync.js +4 -2
  36. package/scripts/feedback-loop.js +41 -5
  37. package/scripts/first-block-upsell.js +187 -0
  38. package/scripts/gates-engine.js +37 -108
  39. package/scripts/human-feedback.js +20 -1
  40. package/scripts/ops-log.js +91 -0
  41. package/scripts/ops-report.js +174 -0
  42. package/scripts/owner-admin.js +508 -27
  43. package/scripts/owner-telemetry.js +151 -0
  44. package/scripts/rate-limiter.js +8 -2
  45. package/scripts/statusline-human-counts.js +71 -8
  46. package/scripts/statusline.sh +15 -2
  47. package/scripts/telemetry-analytics.js +4 -0
  48. package/scripts/tool-contract-validator.js +13 -3
  49. package/scripts/tool-registry.js +1 -1
  50. package/scripts/utm-source-summary.js +88 -0
  51. package/server.json +2 -2
  52. package/skills/comet-session-logger/SKILL.md +8 -5
  53. package/src/api/server.js +649 -107
  54. package/src/mcp/email-triage-server/index.js +92 -14
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,18 +3131,43 @@ 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
  }
2964
3142
 
3143
+ // A refused click used to land the buyer on an identical page with no word on
3144
+ // why (headless run: third click in a minute from one IP, 302 back, empty
3145
+ // note). The refusal reason is mapped to one of three fixed notices; only the
3146
+ // code travels in the URL, never free text. Bots and non-browser agents get no
3147
+ // notice because they are not the audience.
3148
+ const CHECKOUT_GATE_NOTICES = Object.freeze({
3149
+ retry: "We couldn't confirm that click. Press the button again.",
3150
+ network: 'Your connection changed while we confirmed the click. Press the button again.',
3151
+ busy: 'Many checkouts are starting from your network right now. Wait a minute, then press the button again.',
3152
+ });
3153
+
3154
+ function checkoutGateNoticeCode(reason) {
3155
+ const text = String(reason || '');
3156
+ if (/^token_(ip|ua)_mismatch$/.test(text)) return 'network';
3157
+ if (/^token_(missing|malformed|bad_signature|expired|replayed)$/.test(text)) return 'retry';
3158
+ if (text === 'burst_limit' || text === 'global_ceiling') return 'busy';
3159
+ return null;
3160
+ }
3161
+
2965
3162
  function renderCheckoutIntentPage(prefilledEmail = '', parsed = null, options = {}) {
2966
3163
  const plausibleDomain = escapeHtmlAttribute(resolvePlausibleDataDomain({ host: 'thumbgate.ai' }));
3164
+ const noticeCode = String(options.gateNotice || parsed?.searchParams?.get('gate_notice') || '');
3165
+ const gateNoticeText = Object.hasOwn(CHECKOUT_GATE_NOTICES, noticeCode) ? CHECKOUT_GATE_NOTICES[noticeCode] : '';
2967
3166
  const includeHiddenAttribution = options.includeHiddenAttribution === true;
2968
3167
  const hiddenInputs = includeHiddenAttribution
2969
3168
  ? buildCheckoutHiddenAttributionInputs(parsed)
2970
3169
  : '';
2971
- const planView = resolveCheckoutIntentPlanView(parsed);
3170
+ const planView = resolveCheckoutIntentPlanView(parsed, includeHiddenAttribution);
2972
3171
  return `<!doctype html>
2973
3172
  <html lang="en">
2974
3173
  <head>
@@ -2995,6 +3194,7 @@ a{display:block;text-decoration:none}a.secondary,button.secondary{box-sizing:bor
2995
3194
  .objection-grid button{border:1px solid #374151;background:#111827;color:#e5e7eb;border-radius:8px;padding:10px 12px;text-align:left;cursor:pointer}
2996
3195
  .objection-grid button:hover,.objection-grid button:focus{border-color:#22d3ee;outline:none}
2997
3196
  .feedback-saved{display:none;color:#22d3ee;font-size:13px;margin-top:10px}
3197
+ .more-options{margin:16px 0 0}.more-options>summary{cursor:pointer;color:#94a3b8;font-size:13px;text-align:center}
2998
3198
  .back{text-align:center;color:#64748b;font-size:12px;margin-top:24px}.back a{color:#64748b;display:inline}
2999
3199
  </style>
3000
3200
  </head>
@@ -3004,8 +3204,19 @@ a{display:block;text-decoration:none}a.secondary,button.secondary{box-sizing:bor
3004
3204
  <h1>${planView.title}</h1>
3005
3205
  <div class="price">${planView.price}<small>${planView.unit}</small></div>
3006
3206
  <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>
3207
+ <form action="${planView.directAction}" method="POST" class="direct" data-i="pro_checkout_direct_stripe">
3208
+ ${Object.entries(planView.directFields).map(([k, v]) => `<input type="hidden" name="${k}" value="${escapeHtmlAttribute(v)}">`).join('')}
3209
+ <input type="hidden" name="customer_email" value="">
3210
+ <input type="hidden" name="click_token" value="">
3211
+ <button type="submit" class="primary" rel="nofollow">${planView.ctaLabel}</button>
3212
+ </form>
3213
+ <p class="gate-note" id="gate-note" role="status"${gateNoticeText ? '' : ' style="display:none"'}>${gateNoticeText}</p>
3214
+ <noscript><p class="gate-note">Checkout needs JavaScript so we can tell a person from a crawler.</p></noscript>
3215
+ <p class="choice-note">Stripe asks for your email and card on the next page. Cancel anytime. Refund within 7 days of the first charge if a documented platform defect makes ThumbGate unusable and we cannot fix it; see <a href="/terms">Terms</a>.</p>
3216
+ <details class="more-options" data-i="pro_checkout_more_options">
3217
+ <summary>Other ways to buy</summary>
3008
3218
  <form action="/checkout/pro" method="POST" data-i="pro_checkout_confirmed">
3219
+ <input type="hidden" name="click_token" value="">
3009
3220
  ${hiddenInputs}
3010
3221
  <input type="hidden" name="confirm" value="1">
3011
3222
  <input type="email" name="customer_email" value="${escapeHtmlAttribute(prefilledEmail)}" placeholder="you@company.com" autocomplete="email" required>
@@ -3016,7 +3227,7 @@ ${hiddenInputs}
3016
3227
  <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
3228
  <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
3229
  <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>
3230
+ </details>
3020
3231
  <details class="objection-box" aria-label="Checkout feedback">
3021
3232
  <summary style="cursor:pointer;font-weight:600;color:#cbd5e1">Not buying today? Tell us what to fix (optional)</summary>
3022
3233
  <p class="objection-note">Tap one reason so we know what to fix. This does not sign you up.</p>
@@ -3074,45 +3285,94 @@ ${hiddenInputs}
3074
3285
  }
3075
3286
  fetch('/v1/telemetry/ping', { method:'POST', headers:{ 'content-type':'application/json' }, body: body, keepalive: true }).catch(function(){});
3076
3287
  }
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(_) {}
3288
+ var emailInput = document.querySelector('form[data-i=pro_checkout_confirmed] input[name=customer_email]');
3289
+ var directForm = document.querySelector('form[data-i=pro_checkout_direct_stripe]');
3290
+ var confirmForm = document.querySelector('form[data-i=pro_checkout_confirmed]');
3291
+ var gateNote = document.getElementById('gate-note');
3292
+ var gestureSeen = false;
3293
+ function markGesture(ev) { if (ev && ev.isTrusted) gestureSeen = true; }
3294
+ document.addEventListener('pointerdown', markGesture, true);
3295
+ document.addEventListener('keydown', markGesture, true);
3296
+ function syncDirectEmail() {
3297
+ if (!directForm) return;
3298
+ var email = emailInput ? emailInput.value.trim() : '';
3299
+ var field = directForm.querySelector('input[name=customer_email]');
3300
+ if (!field) return;
3301
+ field.value = (email && email.length <= 320 && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) ? email : '';
3091
3302
  }
3092
3303
  if (emailInput) {
3093
- emailInput.addEventListener('input', updateSkipLink);
3094
- emailInput.addEventListener('change', updateSkipLink);
3095
- updateSkipLink();
3096
- }
3097
- if (skipLink) {
3098
- skipLink.addEventListener('click', function(){
3304
+ emailInput.addEventListener('input', syncDirectEmail);
3305
+ emailInput.addEventListener('change', syncDirectEmail);
3306
+ syncDirectEmail();
3307
+ }
3308
+ function showGateNote(text) {
3309
+ if (!gateNote) return;
3310
+ gateNote.style.display = 'block';
3311
+ gateNote.textContent = text;
3312
+ }
3313
+ // A checkout session opens only after a trusted pointer or keyboard event and a
3314
+ // single-use token from the server. The submit button is disabled after the first
3315
+ // submit so a double click cannot spend a second token.
3316
+ function guardForm(form, buttonId, telemetry) {
3317
+ if (!form) return;
3318
+ form.addEventListener('submit', function(ev) {
3319
+ if (form.getAttribute('data-ready') === '1') return;
3320
+ ev.preventDefault();
3321
+ if (!gestureSeen) {
3322
+ showGateNote('Please click or press a key on the page, then try again.');
3323
+ return;
3324
+ }
3325
+ if (form.getAttribute('data-busy') === '1') return;
3326
+ form.setAttribute('data-busy', '1');
3099
3327
  submitted = true;
3100
- sendTelemetry('checkout_interstitial_cta_clicked', {
3101
- ctaId: 'pro_checkout_direct_stripe',
3102
- ctaPlacement: 'checkout_interstitial'
3328
+ if (form === directForm) syncDirectEmail();
3329
+ sendTelemetry('checkout_interstitial_cta_clicked', telemetry(form));
3330
+ var buttons = form.querySelectorAll('button[type=submit]');
3331
+ buttons.forEach(function(btn) { btn.disabled = true; });
3332
+ fetch('/v1/checkout/click-token', {
3333
+ method: 'POST',
3334
+ credentials: 'same-origin',
3335
+ headers: { 'content-type': 'application/json' },
3336
+ body: JSON.stringify({ buttonId: buttonId, landingPage: pick('landing_path') || window.location.pathname })
3337
+ }).then(function(r) {
3338
+ if (!r.ok) throw new Error('token ' + r.status);
3339
+ return r.json();
3340
+ }).then(function(data) {
3341
+ form.querySelector('input[name=click_token]').value = data.token;
3342
+ form.setAttribute('data-ready', '1');
3343
+ form.submit();
3344
+ }).catch(function() {
3345
+ form.removeAttribute('data-busy');
3346
+ buttons.forEach(function(btn) { btn.disabled = false; });
3347
+ showGateNote('Could not confirm the click. Please try again.');
3103
3348
  });
3104
3349
  });
3105
3350
  }
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
- });
3351
+ guardForm(directForm, 'pro_checkout_direct_stripe', function() {
3352
+ return { ctaId: 'pro_checkout_direct_stripe', ctaPlacement: 'checkout_interstitial' };
3353
+ });
3354
+ guardForm(confirmForm, 'pro_checkout_confirmed', function() {
3355
+ var field = confirmForm.querySelector('input[name=customer_email]');
3114
3356
  try { window.plausible && window.plausible('Checkout Pro Email Submitted', { props: { page:'/checkout/pro', source:'interstitial' } }); } catch(_) {}
3357
+ return { ctaId: 'pro_checkout_confirmed', ctaPlacement: 'checkout_interstitial', customerEmail: field ? field.value : null };
3115
3358
  });
3359
+ // The server logs checkout_interstitial_view for every GET, including link scanners and
3360
+ // crawlers that never run this script. This beacon fires only when a browser executed it,
3361
+ // so views that ran the page are countable apart from views that did not.
3362
+ function reportShown() {
3363
+ try {
3364
+ var b = directForm && directForm.querySelector('button[type=submit]');
3365
+ var r = b ? b.getBoundingClientRect() : null;
3366
+ var inView = !!(r && r.top >= 0 && r.bottom <= window.innerHeight);
3367
+ sendTelemetry('checkout_interstitial_shown', {
3368
+ ctaId: 'pro_checkout_direct_stripe',
3369
+ sectionId: inView ? 'cta_above_fold' : 'cta_below_fold',
3370
+ sectionLabel: window.innerWidth + 'x' + window.innerHeight
3371
+ });
3372
+ } catch (_) {}
3373
+ }
3374
+ if (document.readyState === 'complete') reportShown();
3375
+ else window.addEventListener('load', reportShown);
3116
3376
  document.querySelectorAll('[data-reason]').forEach(function(button) {
3117
3377
  button.addEventListener('click', function(){
3118
3378
  var reason = button.getAttribute('data-reason');
@@ -3160,6 +3420,7 @@ ${hiddenInputs}
3160
3420
  }).catch(function(){
3161
3421
  if (saved) saved.textContent = 'Feedback saved.';
3162
3422
  });
3423
+ });
3163
3424
  });
3164
3425
  window.addEventListener('pagehide', function(){
3165
3426
  if (!submitted && !feedbackSent) {
@@ -3402,6 +3663,12 @@ function isDirectProSessionSlug(slug) {
3402
3663
  return slug === 'pro-direct' || slug === 'pro-annual' || slug === 'founding-100';
3403
3664
  }
3404
3665
 
3666
+ // Pro subscription links never send a bare GET to a Stripe payment link: a
3667
+ // payment link creates a live session the moment it is opened.
3668
+ function isProSubscriptionSlug(slug) {
3669
+ return isDirectProSessionSlug(slug) || slug === 'operator-pro';
3670
+ }
3671
+
3405
3672
  /**
3406
3673
  * Creates an attributable dynamic Stripe Checkout Session for human 1-click Pro
3407
3674
  * redirects (`/go/pro-direct`, `/go/pro-annual`, `/go/founding-100`) when live
@@ -3415,6 +3682,7 @@ async function tryCreateDirectProCheckoutRedirect({
3415
3682
  hostedConfig,
3416
3683
  journeyState,
3417
3684
  feedbackDir,
3685
+ humanClick,
3418
3686
  }) {
3419
3687
  if (!isDirectProSessionSlug(target.slug) || !process.env.STRIPE_SECRET_KEY || isSyntheticProbeQuery(parsed)) {
3420
3688
  return null;
@@ -3450,6 +3718,7 @@ async function tryCreateDirectProCheckoutRedirect({
3450
3718
  traceId,
3451
3719
  metadata: analyticsMetadata,
3452
3720
  appOrigin: hostedConfig.appOrigin,
3721
+ humanClick,
3453
3722
  });
3454
3723
  if (!sessionResult || !sessionResult.url) {
3455
3724
  return null;
@@ -3471,7 +3740,7 @@ async function tryCreateDirectProCheckoutRedirect({
3471
3740
  return sessionResult.url;
3472
3741
  }
3473
3742
 
3474
- async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadRequest, slug }) {
3743
+ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadRequest, slug, clickToken = '' }) {
3475
3744
  const target = getTrackedLinkTarget(slug);
3476
3745
  if (!target) {
3477
3746
  sendJson(res, 404, {
@@ -3510,6 +3779,7 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3510
3779
 
3511
3780
  const { FEEDBACK_DIR } = getFeedbackPaths();
3512
3781
  const journeyState = resolveJourneyState(req, parsed);
3782
+ applyLandingUtm(parsed, journeyState);
3513
3783
  const isProbeQuery = isSyntheticProbeQuery(parsed);
3514
3784
  const requesterClassification = classifyRequester(req.headers);
3515
3785
  let botClassification = isProbeQuery
@@ -3519,6 +3789,7 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3519
3789
  : { isBot: true, reason: 'no_browser_navigation' });
3520
3790
  if (
3521
3791
  target.botDeflectPath
3792
+ && !isProSubscriptionSlug(target.slug) // these never open a session on GET; the human-click gate limits POSTs
3522
3793
  && !botClassification.isBot
3523
3794
  && !isHeadRequest
3524
3795
  && rapidCheckoutGuard.hit(checkoutRequesterKey(req.headers))
@@ -3556,6 +3827,47 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3556
3827
  res.end();
3557
3828
  return;
3558
3829
  }
3830
+ let proHumanClick = null;
3831
+ if (isProSubscriptionSlug(target.slug)) {
3832
+ const admission = !isHeadRequest && isDirectProSessionSlug(target.slug)
3833
+ ? admitCheckoutClick(req, clickToken)
3834
+ : { ok: false, status: 405, reason: 'method_not_post' };
3835
+ if (admission.ok) {
3836
+ proHumanClick = admission.humanClick;
3837
+ } else {
3838
+ const confirmUrl = new URL('/checkout/pro', hostedConfig.appOrigin);
3839
+ appendTrackedLinkQueryParams(confirmUrl, parsed, { ...target, allowCustomerEmail: false });
3840
+ const refusedNotice = req.method === 'POST' ? checkoutGateNoticeCode(admission.reason) : null;
3841
+ if (refusedNotice) confirmUrl.searchParams.set('gate_notice', refusedNotice);
3842
+ if (!isHeadRequest && req.method === 'POST') {
3843
+ appendBestEffortTelemetry(
3844
+ FEEDBACK_DIR,
3845
+ {
3846
+ eventType: 'checkout_human_gate_refused',
3847
+ clientType: 'web',
3848
+ page: `/go/${target.slug}`,
3849
+ reason: admission.reason,
3850
+ destinationSlug: target.slug,
3851
+ acquisitionId: journeyState.acquisitionId,
3852
+ visitorId: journeyState.visitorId,
3853
+ sessionId: journeyState.sessionId,
3854
+ },
3855
+ req.headers,
3856
+ `tracked_link_human_gate_refused:${target.slug}`
3857
+ );
3858
+ }
3859
+ res.writeHead(302, {
3860
+ ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
3861
+ 'Cache-Control': 'no-store',
3862
+ 'X-Robots-Tag': 'noindex,nofollow',
3863
+ 'X-ThumbGate-Link-Slug': target.slug,
3864
+ 'X-ThumbGate-Gate-Reason': String(admission.reason || '').replace(/[^a-z_]/g, ''),
3865
+ Location: confirmUrl.toString(),
3866
+ });
3867
+ res.end();
3868
+ return;
3869
+ }
3870
+ }
3559
3871
  if (!isHeadRequest && isDirectProSessionSlug(target.slug) && process.env.STRIPE_SECRET_KEY) {
3560
3872
  try {
3561
3873
  const dynamicSessionUrl = await tryCreateDirectProCheckoutRedirect({
@@ -3565,6 +3877,7 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3565
3877
  hostedConfig,
3566
3878
  journeyState,
3567
3879
  feedbackDir: FEEDBACK_DIR,
3880
+ humanClick: proHumanClick,
3568
3881
  });
3569
3882
  if (dynamicSessionUrl) {
3570
3883
  res.writeHead(req.method === 'POST' ? 303 : 302, {
@@ -3592,9 +3905,25 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3592
3905
  res.end();
3593
3906
  return;
3594
3907
  }
3595
- // Fall back cleanly to static Payment Link if dynamic session creation fails
3908
+ // Dynamic session creation failed: Pro slugs go to the confirm page below.
3909
+ console.warn('[checkout] dynamic session creation failed', target.slug, err && (err.code || err.message));
3596
3910
  }
3597
3911
  }
3912
+ if (isProSubscriptionSlug(target.slug)) {
3913
+ // Admitted, but no session could be made (no key, or Stripe refused): send
3914
+ // the visitor to the confirm page, never to a payment link.
3915
+ const confirmUrl = new URL('/checkout/pro', hostedConfig.appOrigin);
3916
+ appendTrackedLinkQueryParams(confirmUrl, parsed, { ...target, allowCustomerEmail: false });
3917
+ res.writeHead(302, {
3918
+ ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
3919
+ 'Cache-Control': 'no-store',
3920
+ 'X-Robots-Tag': 'noindex,nofollow',
3921
+ 'X-ThumbGate-Link-Slug': target.slug,
3922
+ Location: confirmUrl.toString(),
3923
+ });
3924
+ res.end();
3925
+ return;
3926
+ }
3598
3927
  const destinationUrl = buildTrackedLinkDestination(target, hostedConfig, parsed);
3599
3928
  if (
3600
3929
  target.external
@@ -4081,6 +4410,10 @@ function loadInstallPageHtml(runtimeConfig, pageContext = {}) {
4081
4410
  return loadPublicMarketingTemplateHtml(INSTALL_PAGE_PATH, runtimeConfig, pageContext);
4082
4411
  }
4083
4412
 
4413
+ function loadPreviewPageHtml(runtimeConfig, pageContext = {}) {
4414
+ return loadPublicMarketingTemplateHtml(PREVIEW_PAGE_PATH, runtimeConfig, pageContext);
4415
+ }
4416
+
4084
4417
  function loadPricingPageHtml(runtimeConfig, pageContext = {}) {
4085
4418
  return loadPublicMarketingTemplateHtml(PRICING_PAGE_PATH, runtimeConfig, pageContext);
4086
4419
  }
@@ -4803,6 +5136,7 @@ function renderSitemapXml(runtimeConfig) {
4803
5136
  { path: '/learn/netflix-oci-actor-critic-process-audits', changefreq: 'weekly', priority: '0.85' },
4804
5137
  { path: '/learn/future-agi-self-healing-agent-firewall', changefreq: 'weekly', priority: '0.85' },
4805
5138
  { path: '/learn/five-walls-enterprise-agent-deployment', changefreq: 'weekly', priority: '0.85' },
5139
+ { path: '/learn/okta-mcp-governance-per-tool-call-gates', changefreq: 'weekly', priority: '0.85' },
4806
5140
  { path: '/compare/claude-code-hooks', changefreq: 'weekly', priority: '0.85' },
4807
5141
  { path: '/compare/bumblebee', changefreq: 'weekly', priority: '0.85' },
4808
5142
  { path: '/compare/anthropic-containment', changefreq: 'weekly', priority: '0.85' },
@@ -4823,6 +5157,7 @@ function renderSitemapXml(runtimeConfig) {
4823
5157
  { dir: 'compare', route: '/compare', priority: '0.85' },
4824
5158
  { dir: 'guides', route: '/guides', priority: '0.85' },
4825
5159
  { dir: 'blog', route: '/blog', priority: '0.8' },
5160
+ { dir: 'reports', route: '/reports', priority: '0.8' },
4826
5161
  ];
4827
5162
  for (const catalog of seoDirectories) {
4828
5163
  const files = fs.readdirSync(path.join(PUBLIC_DIR, catalog.dir)).sort((a, b) => a.localeCompare(b));
@@ -6042,13 +6377,29 @@ function pruneSsoPendingStates(nowMs = Date.now()) {
6042
6377
  }
6043
6378
  }
6044
6379
 
6045
- function issueSsoPendingState(provider, redirectUri, nowMs = Date.now()) {
6380
+ // Where to send someone after sign-in. Only a same-site path that starts with exactly one "/" is accepted;
6381
+ // anything else (//host, https://host, /\host, control characters) falls back, so it can never be an open redirect.
6382
+ function safeNextPath(raw, fallback = '/dashboard') {
6383
+ const value = typeof raw === 'string' ? raw.trim() : '';
6384
+ if (!value || value.length > 300 || !value.startsWith('/') || value.startsWith('//') || /[\\\u0000-\u001f\u007f]/.test(value)) return fallback;
6385
+ let parsedNext;
6386
+ try {
6387
+ const decoded = decodeURIComponent(value);
6388
+ if (decoded.startsWith('//') || /[\\\u0000-\u001f\u007f]/.test(decoded)) return fallback;
6389
+ parsedNext = new URL(value, 'https://next.invalid');
6390
+ } catch { return fallback; }
6391
+ if (parsedNext.origin !== 'https://next.invalid') return fallback;
6392
+ return parsedNext.pathname + parsedNext.search;
6393
+ }
6394
+
6395
+ function issueSsoPendingState(provider, redirectUri, nowMs = Date.now(), next = '/dashboard') {
6046
6396
  pruneSsoPendingStates(nowMs);
6047
6397
  const stateNonce = `st_${crypto.randomBytes(24).toString('hex')}`;
6048
6398
  const oidcNonce = `nc_${crypto.randomBytes(16).toString('hex')}`;
6049
6399
  ssoPendingStates.set(stateNonce, {
6050
6400
  provider,
6051
6401
  redirectUri,
6402
+ next: safeNextPath(next),
6052
6403
  nonce: oidcNonce,
6053
6404
  createdAt: nowMs,
6054
6405
  expiresAt: nowMs + SSO_OAUTH_STATE_TTL_MS,
@@ -6074,6 +6425,7 @@ function ssoError(ssoReason, message) {
6074
6425
  function redirectSsoError(res, reason, statusCode = 302) {
6075
6426
  const raw = String(reason || '').trim().toLowerCase();
6076
6427
  const safeReason = /^[a-z0-9_]{1,48}$/.test(raw) ? raw : 'sso_failed';
6428
+ opsLog.recordSignInFailure(safeReason);
6077
6429
  res.writeHead(statusCode, { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', Location: `/dashboard?sso_error=${safeReason}` });
6078
6430
  res.end();
6079
6431
  }
@@ -6398,7 +6750,7 @@ function resolveOwnerEnterpriseSessionAuth() {
6398
6750
  return { apiKey: 'tg_op_dev_session', subjectType: 'dev_enterprise' };
6399
6751
  }
6400
6752
 
6401
- async function completeSsoSessionAndRedirect(res, { provider, email, ssoName = null, redirectStatus = 302 }) {
6753
+ async function completeSsoSessionAndRedirect(res, { provider, email, ssoName = null, redirectStatus = 302, next = '/dashboard' }) {
6402
6754
  const isOwner = isConfiguredOwnerEmail(email);
6403
6755
  const entitlement = isOwner ? null : await resolvePaidEntitlementForEmail(email);
6404
6756
  const hasPaidKey = !isOwner && Boolean(entitlement?.entitled && entitlement?.apiKey);
@@ -6451,12 +6803,49 @@ async function completeSsoSessionAndRedirect(res, { provider, email, ssoName = n
6451
6803
  'X-Content-Type-Options': 'nosniff',
6452
6804
  'Cache-Control': 'no-store',
6453
6805
  'Set-Cookie': provider === 'google' ? [setCookie, clearStateCookie] : setCookie,
6454
- Location: '/dashboard',
6806
+ Location: safeNextPath(next),
6455
6807
  });
6456
6808
  res.end();
6457
6809
  }
6458
6810
 
6459
- const DEFAULT_HOSTED_OWNER_EMAILS = ['iganapolsky@gmail.com', 'igor.ganapolsky@gmail.com', 'igor@thumbgate.ai'];
6811
+ // Plain sign-in page for owner-only pages. Kept inline so it adds no file to the npm bundle.
6812
+ function renderSigninPage(nextPath, ssoError) {
6813
+ const next = encodeURIComponent(safeNextPath(nextPath));
6814
+ const reason = /^[a-z0-9_]{1,48}$/.test(String(ssoError || '')) ? String(ssoError).replaceAll('_', ' ') : '';
6815
+ const notice = reason ? `<p role="alert" style="color:#f87171">Sign-in did not finish (${reason}). Please try again.</p>` : '';
6816
+ return `<!doctype html>
6817
+ <html lang="en">
6818
+ <head>
6819
+ <meta charset="utf-8">
6820
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6821
+ <meta name="robots" content="noindex, nofollow">
6822
+ <title>Sign in - ThumbGate</title>
6823
+ <style>
6824
+ :root { color-scheme: light dark; --bg: #0b1220; --fg: #e6edf7; --muted: #9fb0c8; --card: #121b2e; --line: #243049; --accent: #22d3ee; }
6825
+ @media (prefers-color-scheme: light) { :root { --bg: #f6f8fb; --fg: #0f172a; --muted: #475569; --card: #fff; --line: #d6dde8; --accent: #0e7490; } }
6826
+ 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; }
6827
+ main { width: min(420px, calc(100vw - 32px)); background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 28px; }
6828
+ h1 { margin: 0 0 6px; font-size: 22px; }
6829
+ p { margin: 0 0 18px; color: var(--muted); }
6830
+ 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; }
6831
+ a.btn:focus-visible, a.btn:hover { border-color: var(--accent); outline: none; }
6832
+ small { display: block; margin-top: 18px; color: var(--muted); }
6833
+ </style>
6834
+ </head>
6835
+ <body>
6836
+ <main>
6837
+ <h1>Sign in to ThumbGate</h1>
6838
+ <p>Use your Google or Apple account. ThumbGate never asks for a typed email address.</p>
6839
+ ${notice}
6840
+ <a class="btn" id="signinGoogle" href="/v1/cloud/sso/authorize?provider=google&amp;next=${next}">Continue with Google</a>
6841
+ <a class="btn" id="signinApple" href="/v1/cloud/sso/authorize?provider=apple&amp;next=${next}">Continue with Apple</a>
6842
+ </main>
6843
+ </body>
6844
+ </html>
6845
+ `;
6846
+ }
6847
+
6848
+ const DEFAULT_HOSTED_OWNER_EMAILS =['iganapolsky@gmail.com', 'igor.ganapolsky@gmail.com', 'igor@thumbgate.ai'];
6460
6849
 
6461
6850
  function ensureHostedActivationsReady(baseFeedbackDir, extraOpts = {}) {
6462
6851
  const { backfillHostedAccountActivations } = require('../../scripts/dashboard');
@@ -6693,6 +7082,7 @@ async function handleAppleSsoCallback(req, res) {
6693
7082
  email: claims.email,
6694
7083
  ssoName: firstSignInUser?.name || null,
6695
7084
  redirectStatus: 303,
7085
+ next: stateEntry.next,
6696
7086
  });
6697
7087
  } catch (err) {
6698
7088
  redirectSsoError(res, err?.ssoReason || 'callback_failed', 303);
@@ -6981,6 +7371,7 @@ function isBillingSummaryAuthorized(req, expectedAdminKey, expectedOperatorKey)
6981
7371
  const OPERATOR_READONLY_GET_PATHS = new Set([
6982
7372
  '/v1/billing/summary',
6983
7373
  '/v1/analytics/funnel',
7374
+ '/v1/analytics/sources',
6984
7375
  '/v1/dashboard',
6985
7376
  '/v1/dashboard/render-spec',
6986
7377
  '/v1/dashboard/ai-inventory',
@@ -7148,7 +7539,10 @@ function resolveDocumentImportFilePath(inputPath, options = {}) {
7148
7539
  const CONTINUE_DATA_SCOPE = Symbol('trustedDataScopeContinuation');
7149
7540
 
7150
7541
  function createApiServer({ ownerAdminDependencies = {} } = {}) {
7542
+ humanGate = buildHumanGate();
7151
7543
  const server = withoutDataScope(() => createUnscopedApiServer({ ownerAdminDependencies }));
7544
+ // The once-a-minute heartbeat the owner console's uptime figure counts gaps in. Not under the test runner.
7545
+ if (!process.env.NODE_TEST_CONTEXT) server.once('listening', () => opsLog.startHeartbeat(withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR)));
7152
7546
  const [listener] = server.listeners('request');
7153
7547
  server.removeListener('request', listener);
7154
7548
  server.on('request', (req, res) => {
@@ -7177,7 +7571,12 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7177
7571
  : pathname === '/health' ? 'health' : pathname.startsWith('/v1/') ? 'api' : 'page';
7178
7572
  if (!observedRequests.has(req)) {
7179
7573
  observedRequests.add(req);
7180
- res.once('finish', () => adminRuntime.recordResponse(res.statusCode, category));
7574
+ const startedNs = process.hrtime.bigint();
7575
+ res.once('finish', () => {
7576
+ adminRuntime.recordResponse(res.statusCode, category);
7577
+ adminRuntime.recordTiming(category, Number(process.hrtime.bigint() - startedNs) / 1e6);
7578
+ if (res.statusCode >= 500 && res.statusCode <= 599) opsLog.recordError(pathname, res.statusCode);
7579
+ });
7181
7580
  }
7182
7581
  if (privatePath.matched) {
7183
7582
  const headers = ownerAdmin.PRIVATE_HEADERS;
@@ -7187,8 +7586,20 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7187
7586
  };
7188
7587
  const feedbackDir = withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR);
7189
7588
  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; }
7589
+ const session = ownerAdmin.readSessionState({ feedbackDir, token: cookies[PAID_AUTH_COOKIE_NAME], isOwner: isConfiguredOwnerEmail });
7590
+ const identity = session.state === 'owner' ? { provider: session.provider } : null;
7591
+ if (!privatePath.pathname) { respond(404, { error: 'Not found' }); return; }
7592
+ if (!identity && session.state === 'non_owner') {
7593
+ console.warn(`[admin] 403 signed-in session is not on THUMBGATE_OWNER_EMAILS (provider=${session.provider})`);
7594
+ respond(403, { error: 'Forbidden' });
7595
+ return;
7596
+ }
7597
+ if (!identity && ['/admin', '/admin/', '/admin.html'].includes(privatePath.pathname) && ['GET', 'HEAD'].includes(req.method)) {
7598
+ res.writeHead(302, { ...headers, Location: '/signin?next=%2Fadmin' });
7599
+ res.end();
7600
+ return;
7601
+ }
7602
+ if (!identity) { respond(404, { error: 'Not found' }); return; }
7192
7603
  let route;
7193
7604
  try { route = ownerAdmin.parseAdminRoute(privatePath.pathname, parsed.searchParams); }
7194
7605
  catch { respond(400, { error: 'Invalid query' }); return; }
@@ -7211,6 +7622,8 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7211
7622
  feedbackDir, buildMetadata: BUILD_METADATA, runtime: adminRuntime,
7212
7623
  hashDataIdentity, buildHostedTenantIdentity,
7213
7624
  health: () => ({ version: pkg.version, buildSha: BUILD_METADATA.buildSha, uptime: process.uptime() }),
7625
+ // The commit title comes from GitHub's public API; tests never reach the network.
7626
+ lookupCommitTitle: process.env.NODE_TEST_CONTEXT ? undefined : (sha, signal) => ownerAdmin.githubCommitTitle(sha, signal),
7214
7627
  ...ownerAdminDependencies,
7215
7628
  }, cancellation.signal));
7216
7629
  const body = JSON.stringify(result);
@@ -7506,6 +7919,43 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7506
7919
  return;
7507
7920
  }
7508
7921
 
7922
+ if (isGetLikeRequest && pathname === '/js/connect-panel.js') {
7923
+ try {
7924
+ const script = fs.readFileSync(CONNECT_PANEL_SCRIPT_PATH, 'utf-8');
7925
+ res.writeHead(200, {
7926
+ 'Content-Type': 'application/javascript; charset=utf-8',
7927
+ 'Cache-Control': 'public, max-age=300',
7928
+ });
7929
+ if (!isHeadRequest) {
7930
+ res.end(script);
7931
+ } else {
7932
+ res.end();
7933
+ }
7934
+ } catch {
7935
+ sendJson(res, 404, { error: 'Connect panel script not found' });
7936
+ }
7937
+ return;
7938
+ }
7939
+
7940
+ if (isGetLikeRequest && (pathname === '/preview' || pathname === '/preview.html')) {
7941
+ try {
7942
+ servePublicMarketingPage({
7943
+ req,
7944
+ res,
7945
+ parsed,
7946
+ hostedConfig,
7947
+ isHeadRequest,
7948
+ renderHtml: loadPreviewPageHtml,
7949
+ extraTelemetry: {
7950
+ pageType: 'preview',
7951
+ },
7952
+ });
7953
+ } catch (err) {
7954
+ sendText(res, 500, err.message || 'Preview page unavailable');
7955
+ }
7956
+ return;
7957
+ }
7958
+
7509
7959
  if (isGetLikeRequest && pathname === '/js/buyer-intent.js') {
7510
7960
  try {
7511
7961
  const script = fs.readFileSync(BUYER_INTENT_SCRIPT_PATH, 'utf-8');
@@ -7759,9 +8209,10 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7759
8209
  const trackedLinkMatch = pathname.match(/^\/go\/([^/]+)$/);
7760
8210
  if ((isGetLikeRequest || req.method === 'POST') && trackedLinkMatch) {
7761
8211
  let trackedParsed = parsed;
8212
+ let trackedClickToken = '';
7762
8213
  if (req.method === 'POST') {
7763
8214
  const target = getTrackedLinkTarget(trackedLinkMatch[1]);
7764
- if (!target?.requiresPost) {
8215
+ if (!target?.requiresPost && !(target && isDirectProSessionSlug(target.slug))) {
7765
8216
  sendJson(res, target ? 405 : 404, target
7766
8217
  ? { error: 'POST is not supported for this tracked link' }
7767
8218
  : { error: 'Tracked link not found', allowed: Object.keys(TRACKED_LINK_TARGETS) }, {
@@ -7778,6 +8229,7 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7778
8229
  return;
7779
8230
  }
7780
8231
  const form = await parseFormBody(req, 16 * 1024);
8232
+ trackedClickToken = checkoutClickTokenFrom(req, form);
7781
8233
  trackedParsed = new URL(parsed.toString());
7782
8234
  for (const [key, value] of Object.entries(form)) {
7783
8235
  if (key === 'customer_email' || TRACKED_LINK_QUERY_KEYS.has(key)) {
@@ -7792,6 +8244,7 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7792
8244
  hostedConfig,
7793
8245
  isHeadRequest,
7794
8246
  slug: trackedLinkMatch[1],
8247
+ clickToken: trackedClickToken,
7795
8248
  });
7796
8249
  return;
7797
8250
  }
@@ -8000,7 +8453,23 @@ async function addContext(){
8000
8453
 
8001
8454
  if (isGetLikeRequest && (pathname === '/dashboard' || pathname === '/cloud')) {
8002
8455
  try {
8003
- const html = loadDashboardPageHtml(req, expectedApiKey);
8456
+ const dashCookies = parseCookies(req.headers?.cookie || '');
8457
+ const dashSession = getPaidAuthSessionEntry(dashCookies[PAID_AUTH_COOKIE_NAME], expectedApiKey, expectedOperatorKey);
8458
+ const dashProviders = getConfiguredSsoProviders();
8459
+ const dashForwarded = req.headers['x-forwarded-host'];
8460
+ const dashHost = Array.isArray(dashForwarded) ? dashForwarded[0] : dashForwarded || req.headers.host || '';
8461
+ // One sign-in page only: a signed-out visitor on the hosted site goes to /signin. Local dashboards
8462
+ // (loopback host, bootstrap key) and servers with no sign-in provider keep serving the dashboard.
8463
+ if (!dashSession && !isLoopbackHost(dashHost) && !resolveLocalPageBootstrap(req, expectedApiKey).bootstrapActive && (dashProviders.google || dashProviders.apple)) {
8464
+ const ssoErr = parsed.searchParams.get('sso_error');
8465
+ const errPart = /^[a-z0-9_]{1,48}$/.test(String(ssoErr || '')) ? `&sso_error=${ssoErr}` : '';
8466
+ res.writeHead(302, { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', Location: `/signin?next=${encodeURIComponent(pathname)}${errPart}` });
8467
+ res.end();
8468
+ return;
8469
+ }
8470
+ let html = loadDashboardPageHtml(req, expectedApiKey);
8471
+ const dashOwner = ownerAdmin.readSessionState({ feedbackDir: withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR), token: dashCookies[PAID_AUTH_COOKIE_NAME], isOwner: isConfiguredOwnerEmail }).state === 'owner';
8472
+ if (dashOwner) html = html.replace(/(<a href="\/lessons"[^>]*>Lessons<\/a>)/, '$1<a href="/admin" class="nav-tab" id="navAdmin">Admin</a>');
8004
8473
  sendHtml(res, 200, html, {}, { headOnly: isHeadRequest });
8005
8474
  } catch {
8006
8475
  sendJson(res, 404, { error: 'Dashboard page not found' });
@@ -8013,10 +8482,11 @@ async function addContext(){
8013
8482
  const provider = ['google', 'apple'].includes(rawProvider) ? rawProvider : 'invalid';
8014
8483
  const appOrigin = hostedConfig.appOrigin || 'https://thumbgate.ai';
8015
8484
  const callbackUrl = `${appOrigin}/v1/cloud/sso/callback?provider=${encodeURIComponent(provider)}`;
8485
+ const nextPath = safeNextPath(parsed.searchParams.get('next'));
8016
8486
  const googleClientId = String(process.env.GOOGLE_CLIENT_ID || '').trim();
8017
8487
  const appleClientId = String(process.env.APPLE_CLIENT_ID || '').trim();
8018
8488
  if (provider === 'google' && googleClientId) {
8019
- const stateNonce = issueSsoPendingState('google', callbackUrl);
8489
+ const stateNonce = issueSsoPendingState('google', callbackUrl, Date.now(), nextPath);
8020
8490
  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)}`;
8021
8491
  const ssoStateCookie = serializeCookie(SSO_STATE_COOKIE_NAME, stateNonce, {
8022
8492
  maxAge: Math.floor(SSO_OAUTH_STATE_TTL_MS / 1000),
@@ -8035,7 +8505,7 @@ async function addContext(){
8035
8505
  }
8036
8506
  if (provider === 'apple' && appleClientId) {
8037
8507
  const appleCallbackUrl = `${appOrigin.replace(/^http:\/\//i, 'https://')}/v1/cloud/sso/apple/callback`;
8038
- const stateNonce = issueSsoPendingState('apple', appleCallbackUrl);
8508
+ const stateNonce = issueSsoPendingState('apple', appleCallbackUrl, Date.now(), nextPath);
8039
8509
  const pendingNonce = ssoPendingStates.get(stateNonce)?.nonce || stateNonce;
8040
8510
  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)}`;
8041
8511
  if (parsed.searchParams.get('format') === 'json') {
@@ -8126,6 +8596,7 @@ async function addContext(){
8126
8596
  provider: 'google',
8127
8597
  email: claims.email,
8128
8598
  redirectStatus: 302,
8599
+ next: stateEntry.next,
8129
8600
  });
8130
8601
  } catch (err) {
8131
8602
  redirectSsoError(res, err?.ssoReason || 'callback_failed');
@@ -8898,6 +9369,17 @@ async function addContext(){
8898
9369
  return;
8899
9370
  }
8900
9371
 
9372
+ if (isGetLikeRequest && pathname.startsWith('/reports/')) {
9373
+ try {
9374
+ const reportPath = resolvePublicHtmlFile(REPORT_PAGE_PATHS_BY_SLUG, pathname.replace('/reports/', ''));
9375
+ if (!reportPath) { sendJson(res, 404, { error: 'Report not found' }); return; }
9376
+ const requestHost = getSafePublicRequestHost(req);
9377
+ const html = normalizePublicMarketingHtml(fs.readFileSync(reportPath, 'utf-8'), hostedConfig, requestHost);
9378
+ sendHtml(res, 200, html, {}, { headOnly: isHeadRequest });
9379
+ } catch { sendJson(res, 404, { error: 'Report not found' }); }
9380
+ return;
9381
+ }
9382
+
8901
9383
  if (isGetLikeRequest && pathname.startsWith('/use-cases/')) {
8902
9384
  try {
8903
9385
  const useCasePath = resolvePublicHtmlFile(USE_CASE_PAGE_PATHS_BY_SLUG, pathname.replace('/use-cases/', ''));
@@ -8928,7 +9410,7 @@ async function addContext(){
8928
9410
  sendJson(res, 403, { error: 'Forbidden' });
8929
9411
  return;
8930
9412
  }
8931
- serveStaticFile(res, resolved, { headOnly: isHeadRequest });
9413
+ serveStaticFile(res, resolved, { headOnly: isHeadRequest, rangeHeader: req.headers.range });
8932
9414
  return;
8933
9415
  }
8934
9416
 
@@ -8964,7 +9446,9 @@ async function addContext(){
8964
9446
  parsed,
8965
9447
  hostedConfig,
8966
9448
  isHeadRequest,
8967
- renderHtml: loadLandingPageHtml,
9449
+ renderHtml: parsed.searchParams.get('signed_out') === '1'
9450
+ ? (...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>')
9451
+ : loadLandingPageHtml,
8968
9452
  extraTelemetry: {
8969
9453
  pageType: 'homepage',
8970
9454
  },
@@ -8988,6 +9472,7 @@ async function addContext(){
8988
9472
  return;
8989
9473
  }
8990
9474
 
9475
+ let postedClickToken = '';
8991
9476
  if (req.method === 'POST') {
8992
9477
  const contentType = String(req.headers['content-type'] || '').toLowerCase();
8993
9478
  if (!contentType.includes('application/x-www-form-urlencoded')) {
@@ -8997,6 +9482,7 @@ async function addContext(){
8997
9482
  return;
8998
9483
  }
8999
9484
  const form = await parseFormBody(req, 16 * 1024);
9485
+ postedClickToken = checkoutClickTokenFrom(req, form);
9000
9486
  for (const [key, value] of Object.entries(form)) {
9001
9487
  if (
9002
9488
  key === 'confirm'
@@ -9010,6 +9496,7 @@ async function addContext(){
9010
9496
 
9011
9497
  const { FEEDBACK_DIR } = getFeedbackPaths();
9012
9498
  const journeyState = resolveJourneyState(req, parsed);
9499
+ applyLandingUtm(parsed, journeyState);
9013
9500
  const bootstrapBody = buildCheckoutBootstrapBody(parsed, req, journeyState);
9014
9501
  const traceId = bootstrapBody.traceId || createJourneyId('checkout');
9015
9502
  const analyticsMetadata = buildCheckoutAttributionMetadata(bootstrapBody, req, traceId);
@@ -9037,15 +9524,11 @@ async function addContext(){
9037
9524
  // confirmation and form POST. This prevents browser-shaped monitors
9038
9525
  // from minting anonymous sessions while preserving a one-field path to
9039
9526
  // Stripe for real buyers.
9040
- const isConfirmedCheckout = (
9041
- (req.method === 'POST' && hasValidCustomerEmailHint)
9042
- || (hasConfirmFlag && hasValidCustomerEmailHint)
9043
- ) && botShouldBypass;
9044
- // Legacy env-gated bypass. It is default-off and still requires a valid
9045
- // email plus a non-bot request; enabling it must never re-open anonymous
9046
- // Stripe-session creation. Attribution is preserved via
9047
- // buildCheckoutFallbackUrl.
9048
- const interstitialBypassEnabled = process.env.THUMBGATE_CHECKOUT_INTERSTITIAL_BYPASS === '1';
9527
+ // Only a POST can confirm. A GET, even with confirm=1 and an email, shows
9528
+ // the page: a session opens only after a confirmed human click.
9529
+ const isConfirmedCheckout = (req.method === 'POST' && hasValidCustomerEmailHint) && botShouldBypass;
9530
+ // The old env-gated interstitial bypass (a 302 straight to a Stripe payment
9531
+ // link on a GET) is removed: a bare GET must never reach Stripe.
9049
9532
  const interstitialSampleRate = normalizeCheckoutInterstitialSampleRate(
9050
9533
  process.env.THUMBGATE_CHECKOUT_INTERSTITIAL_SAMPLE_RATE
9051
9534
  );
@@ -9054,47 +9537,6 @@ async function addContext(){
9054
9537
  traceId,
9055
9538
  analyticsMetadata,
9056
9539
  });
9057
- if (
9058
- !isConfirmedCheckout
9059
- && interstitialBypassEnabled
9060
- && req.method !== 'POST'
9061
- && botShouldBypass
9062
- && hasValidCustomerEmailHint
9063
- && !interstitialSampled
9064
- ) {
9065
- // Always target the pro Stripe Payment Link directly. The
9066
- // hostedConfig.checkoutFallbackUrl (e.g. https://thumbgate.ai/go/pro)
9067
- // is a router that 302s back to /checkout/pro, which would create a
9068
- // redirect loop when bypass is on. Env override via
9069
- // THUMBGATE_CHECKOUT_PRO_STRIPE_URL is supported for future
9070
- // price-link rotation without a redeploy.
9071
- const bypassTarget = process.env.THUMBGATE_CHECKOUT_PRO_STRIPE_URL
9072
- || PRO_CHECKOUT_URL;
9073
- appendBestEffortTelemetry(FEEDBACK_DIR, {
9074
- eventType: 'checkout_interstitial_bypass_redirect',
9075
- clientType: 'web',
9076
- traceId,
9077
- acquisitionId: analyticsMetadata.acquisitionId,
9078
- visitorId: analyticsMetadata.visitorId,
9079
- sessionId: analyticsMetadata.sessionId,
9080
- utmSource: analyticsMetadata.utmSource,
9081
- utmMedium: analyticsMetadata.utmMedium,
9082
- utmCampaign: analyticsMetadata.utmCampaign,
9083
- utmContent: analyticsMetadata.utmContent,
9084
- utmTerm: analyticsMetadata.utmTerm,
9085
- referrer: analyticsMetadata.referrer,
9086
- referrerHost: analyticsMetadata.referrerHost,
9087
- page: '/checkout/pro',
9088
- planId: analyticsMetadata.planId,
9089
- interstitialSampleRate,
9090
- }, req.headers, 'checkout_interstitial_bypass_redirect');
9091
- res.writeHead(302, {
9092
- ...responseHeaders,
9093
- Location: buildCheckoutFallbackUrl(bypassTarget, analyticsMetadata),
9094
- });
9095
- res.end();
9096
- return;
9097
- }
9098
9540
  // Plausible funnel event #1 of 3: page view. Fired before interstitial
9099
9541
  // deflection so we get the full top-of-funnel count, with isBot as a
9100
9542
  // prop so the dashboard can filter human vs. crawler traffic. Fire-and-forget.
@@ -9164,6 +9606,28 @@ async function addContext(){
9164
9606
  return;
9165
9607
  }
9166
9608
 
9609
+ const checkoutAdmission = admitCheckoutClick(req, postedClickToken);
9610
+ if (!checkoutAdmission.ok) {
9611
+ appendBestEffortTelemetry(FEEDBACK_DIR, {
9612
+ eventType: 'checkout_human_gate_refused',
9613
+ clientType: 'web',
9614
+ traceId,
9615
+ page: '/checkout/pro',
9616
+ reason: checkoutAdmission.reason,
9617
+ planId: analyticsMetadata.planId,
9618
+ }, req.headers, 'checkout_human_gate_refused');
9619
+ const refusedHtml = renderCheckoutIntentPage(normalizedCheckoutEmail || '', parsed, {
9620
+ includeHiddenAttribution: true,
9621
+ gateNotice: checkoutGateNoticeCode(checkoutAdmission.reason),
9622
+ });
9623
+ sendHtml(res, checkoutAdmission.status, refusedHtml, {
9624
+ ...responseHeaders,
9625
+ 'Cache-Control': 'no-store',
9626
+ ...(checkoutAdmission.status === 429 ? { 'Retry-After': '60' } : {}),
9627
+ });
9628
+ return;
9629
+ }
9630
+
9167
9631
  bootstrapBody.customerEmail = normalizedCheckoutEmail || undefined;
9168
9632
 
9169
9633
  appendBestEffortTelemetry(FEEDBACK_DIR, {
@@ -9233,6 +9697,7 @@ async function addContext(){
9233
9697
  traceId,
9234
9698
  metadata: analyticsMetadata,
9235
9699
  appOrigin: hostedConfig.appOrigin,
9700
+ humanClick: checkoutAdmission.humanClick,
9236
9701
  });
9237
9702
 
9238
9703
  if (result.url) {
@@ -9380,10 +9845,15 @@ async function addContext(){
9380
9845
 
9381
9846
  const { FEEDBACK_DIR } = getFeedbackPaths();
9382
9847
  const journeyState = resolveJourneyState(req, parsed);
9848
+ // Any GET reaches this page (bots, probes, our own agents). It only counts
9849
+ // as a success when Stripe reports the session_id as paid.
9850
+ const successCheck = await verifyPaidCheckoutSession(parsed.searchParams.get('session_id'));
9851
+ const successEventType = successCheck.verified ? 'checkout_success_page_view' : 'checkout_success_unverified';
9383
9852
  appendBestEffortTelemetry(FEEDBACK_DIR, {
9384
- eventType: 'checkout_success_page_view',
9853
+ eventType: successEventType,
9385
9854
  ...buildCheckoutPageTelemetryMetadata(parsed, req, journeyState, '/success'),
9386
- }, req.headers, 'checkout_success_page_view');
9855
+ ...(successCheck.verified ? {} : { reasonCode: successCheck.reason }),
9856
+ }, req.headers, successEventType);
9387
9857
  sendHtml(
9388
9858
  res,
9389
9859
  200,
@@ -10543,6 +11013,25 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
10543
11013
  // Public terms of service — required by Stripe / Stripe Checkout for the
10544
11014
  // "Terms of service URL" field in Business → Public details. Mirrors the
10545
11015
  // /privacy + /support pages: thin HTML, no external deps, no DB hit.
11016
+ if (isGetLikeRequest && (pathname === '/signin' || pathname === '/signin.html')) {
11017
+ sendHtml(res, 200, renderSigninPage(parsed.searchParams.get('next'), parsed.searchParams.get('sso_error')), { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' }, { headOnly: isHeadRequest });
11018
+ return;
11019
+ }
11020
+
11021
+ // Log out: end the session, clear the cookie, and land on the public landing page with a short note.
11022
+ if (req.method === 'POST' && pathname === '/logout') {
11023
+ const logoutCookies = parseCookies(req.headers?.cookie || '');
11024
+ if (logoutCookies[PAID_AUTH_COOKIE_NAME]) deletePaidAuthSession(logoutCookies[PAID_AUTH_COOKIE_NAME]);
11025
+ res.writeHead(303, {
11026
+ 'X-Content-Type-Options': 'nosniff',
11027
+ 'Cache-Control': 'no-store',
11028
+ 'Set-Cookie': serializeCookie(PAID_AUTH_COOKIE_NAME, '', { maxAge: 0, httpOnly: true, sameSite: 'Lax', secure: true }),
11029
+ Location: '/?signed_out=1',
11030
+ });
11031
+ res.end();
11032
+ return;
11033
+ }
11034
+
10546
11035
  if (isGetLikeRequest && (pathname === '/terms' || pathname === '/terms.html' || pathname === '/eula' || pathname === '/eula.html')) {
10547
11036
  try {
10548
11037
  const termsHtml = fs.readFileSync(path.join(PUBLIC_DIR, 'terms.html'), 'utf-8');
@@ -10786,6 +11275,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10786
11275
 
10787
11276
  const sig = req.headers['stripe-signature'] || '';
10788
11277
  if (!verifyWebhookSignature(rawBody, sig)) {
11278
+ opsLog.recordWebhook(false, 400);
10789
11279
  sendProblem(res, {
10790
11280
  type: PROBLEM_TYPES.WEBHOOK_INVALID,
10791
11281
  title: 'Invalid webhook signature',
@@ -10796,6 +11286,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10796
11286
  }
10797
11287
 
10798
11288
  const result = await handleWebhook(rawBody, sig);
11289
+ opsLog.recordWebhook(!(result && (result.reason === 'invalid_signature' || result.retryable === true)), result?.retryable === true ? 503 : result?.reason === 'invalid_signature' ? 400 : 200);
10799
11290
  if (result && result.reason === 'invalid_signature') {
10800
11291
  sendProblem(res, {
10801
11292
  type: PROBLEM_TYPES.WEBHOOK_INVALID,
@@ -10817,6 +11308,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10817
11308
  sendJson(res, 200, result);
10818
11309
 
10819
11310
  } catch (err) {
11311
+ opsLog.recordWebhook(false, err.statusCode || 500);
10820
11312
  sendProblem(res, {
10821
11313
  type: !err.statusCode || err.statusCode >= 500 ? PROBLEM_TYPES.INTERNAL : PROBLEM_TYPES.BAD_REQUEST,
10822
11314
  title: !err.statusCode || err.statusCode >= 500 ? 'Internal Server Error' : 'Request Error',
@@ -11049,6 +11541,38 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11049
11541
  return;
11050
11542
  }
11051
11543
 
11544
+ // Short-lived single-use token for the human-click gate. Page JS calls this
11545
+ // only after a trusted pointer or keyboard event (see renderCheckoutIntentPage).
11546
+ if (pathname === '/v1/checkout/click-token') {
11547
+ const tokenHeaders = { 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex,nofollow' };
11548
+ if (req.method !== 'POST') {
11549
+ sendJson(res, 405, { error: 'POST required' }, { ...tokenHeaders, Allow: 'POST' });
11550
+ return;
11551
+ }
11552
+ if (!isSameOriginCheckoutRequest(req, hostedConfig.appOrigin)) {
11553
+ sendJson(res, 403, { error: 'Same-origin request required', code: 'HUMAN_CLICK_REQUIRED' }, tokenHeaders);
11554
+ return;
11555
+ }
11556
+ let tokenBody = {};
11557
+ try {
11558
+ tokenBody = await readProjectBody(req);
11559
+ } catch {
11560
+ tokenBody = {};
11561
+ }
11562
+ const token = humanGate.issueToken({
11563
+ headers: req.headers,
11564
+ remoteAddress: req.socket && req.socket.remoteAddress,
11565
+ buttonId: tokenBody && tokenBody.buttonId,
11566
+ landingPage: tokenBody && tokenBody.landingPage,
11567
+ });
11568
+ if (!token) {
11569
+ sendJson(res, 403, { error: 'Browser request required', code: 'HUMAN_CLICK_REQUIRED' }, tokenHeaders);
11570
+ return;
11571
+ }
11572
+ sendJson(res, 200, { token, expiresInSeconds: 120 }, tokenHeaders);
11573
+ return;
11574
+ }
11575
+
11052
11576
  // Public checkout session creation for top-of-funnel acquisition.
11053
11577
  if (req.method === 'POST' && pathname === '/v1/billing/checkout') {
11054
11578
  try {
@@ -11067,6 +11591,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11067
11591
  throw createHttpError(400, 'customerEmail must be a valid email address');
11068
11592
  }
11069
11593
 
11594
+ // Checked after the cheap validation so a typo does not burn the token.
11595
+ const admission = admitCheckoutClick(req, checkoutClickTokenFrom(req, { click_token: body.clickToken }));
11596
+ if (!admission.ok) {
11597
+ const err = createHttpError(admission.status === 405 ? 403 : admission.status, `A confirmed human click is required (${admission.reason}).`);
11598
+ err.code = 'HUMAN_CLICK_REQUIRED';
11599
+ throw err;
11600
+ }
11601
+
11070
11602
  const result = await createCheckoutSession({
11071
11603
  successUrl: body.successUrl || buildCheckoutFallbackUrl(
11072
11604
  buildHostedSuccessUrl(hostedConfig.appOrigin, traceId),
@@ -11081,6 +11613,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11081
11613
  traceId,
11082
11614
  metadata: analyticsMetadata,
11083
11615
  appOrigin: hostedConfig.appOrigin,
11616
+ humanClick: admission.humanClick,
11084
11617
  });
11085
11618
  sendJson(res, 200, {
11086
11619
  ...result,
@@ -11099,6 +11632,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11099
11632
  title: !err.statusCode || err.statusCode >= 500 ? 'Internal Server Error' : 'Request Error',
11100
11633
  status: err.statusCode || 500,
11101
11634
  detail: err.message || 'An unexpected error occurred.',
11635
+ ...(err.code === 'HUMAN_CLICK_REQUIRED' ? { code: 'HUMAN_CLICK_REQUIRED' } : {}),
11102
11636
  }, getPublicBillingHeaders(fallbackTraceId));
11103
11637
  }
11104
11638
  return;
@@ -12978,6 +13512,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
12978
13512
  return;
12979
13513
  }
12980
13514
 
13515
+ // GET /v1/analytics/sources -- visits, installs and checkout starts by utm_source, last 7 and 30 days
13516
+ if (req.method === 'GET' && pathname === '/v1/analytics/sources') {
13517
+ if (!isBillingSummaryAuthorized(req, expectedApiKey, expectedOperatorKey)) throw createHttpError(403, 'Admin or operator API key required for this endpoint.');
13518
+ sendJson(res, 200, getUtmSourceSummary(requestFeedbackDir), { 'Cache-Control': 'no-store' });
13519
+ return;
13520
+ }
13521
+
12981
13522
  // GET /v1/analytics/losses -- explain where buyer dollars are falling out of the funnel
12982
13523
  if (req.method === 'GET' && pathname === '/v1/analytics/losses') {
12983
13524
  const dashboardResult = await loadLiveDashboardDataOrRespondProblem(
@@ -13599,6 +14140,7 @@ module.exports = {
13599
14140
  createApiServer,
13600
14141
  startServer,
13601
14142
  __test__: {
14143
+ inferSource,
13602
14144
  PRO_CHECKOUT_URL,
13603
14145
  escapeHtmlAttribute,
13604
14146
  renderCheckoutIntentPage,