thumbgate 1.18.0 → 1.19.0

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.
package/src/api/server.js CHANGED
@@ -13,11 +13,17 @@ const {
13
13
  const POSTHOG_API_PATHS = new Set(['/capture', '/batch', '/decide', '/e', '/engage']);
14
14
  const POSTHOG_INGEST_HOST = 'us.i.posthog.com';
15
15
  const POSTHOG_STATIC_PATH_PREFIX = '/static/';
16
- const FIRST_FAILURE_RULE_CHECKOUT_URL = 'https://buy.stripe.com/4gM6oHgH2bTw4lH6i73sI0z';
17
- const QUICK_READ_CHECKOUT_URL = 'https://buy.stripe.com/aFa8wPgH29Lo4lH35V3sI0w';
18
- const WORKFLOW_TEARDOWN_CHECKOUT_URL = 'https://buy.stripe.com/7sYfZhgH29LodWhdKz3sI0v';
19
- const SPRINT_DIAGNOSTIC_CHECKOUT_URL = 'https://buy.stripe.com/3cI7sLgH25v8dWh5e33sI0o';
20
- const WORKFLOW_SPRINT_CHECKOUT_URL = 'https://buy.stripe.com/8x25kDcqMaPs9G15e33sI0p';
16
+ // Payment Links generated by scripts/stripe-bootstrap-saas-catalog.js
17
+ // (2026-05-14 dispatch run 25883541719). These are tied to the
18
+ // ThumbGate-branded persistent products (metadata.thumbgate_tier=*) in the
19
+ // Stripe catalog, with the per-tier thumbnails wired in. Re-run the
20
+ // bootstrap workflow to regenerate; the new URLs surface in the workflow
21
+ // summary log.
22
+ const FIRST_FAILURE_RULE_CHECKOUT_URL = 'https://buy.stripe.com/fZu28rfCY6zcbO99uj3sI2G';
23
+ const QUICK_READ_CHECKOUT_URL = 'https://buy.stripe.com/5kQ7sL76s1eSaK55e33sI2H';
24
+ const WORKFLOW_TEARDOWN_CHECKOUT_URL = 'https://buy.stripe.com/8x214n2Qc4r44lHayn3sI2I';
25
+ const SPRINT_DIAGNOSTIC_CHECKOUT_URL = 'https://buy.stripe.com/28E00j3Uge1E2dzgWL3sI2J';
26
+ const WORKFLOW_SPRINT_CHECKOUT_URL = 'https://buy.stripe.com/6oU00j8aw2iWdWh9uj3sI2K';
21
27
 
22
28
  function getPosthogProxyPath(pathname) {
23
29
  return pathname.slice('/ingest'.length) || '/';
@@ -87,6 +93,9 @@ const {
87
93
  const {
88
94
  classifyRequester,
89
95
  } = require('../../scripts/bot-detection');
96
+ const {
97
+ recordCheckoutFunnelEvent,
98
+ } = require('../../scripts/plausible-server-events');
90
99
  const {
91
100
  buildCloudflareSandboxPlan,
92
101
  } = require('../../scripts/cloudflare-dynamic-sandbox');
@@ -209,6 +218,7 @@ const CODEX_PLUGIN_PAGE_PATH = path.resolve(__dirname, '../../public/codex-plugi
209
218
  const COMPARE_PAGE_PATH = path.resolve(__dirname, '../../public/compare.html');
210
219
  const LEARN_PAGE_PATH = path.resolve(__dirname, '../../public/learn.html');
211
220
  const NUMBERS_PAGE_PATH = path.resolve(__dirname, '../../public/numbers.html');
221
+ const FEDERAL_PAGE_PATH = path.resolve(__dirname, '../../public/federal.html');
212
222
  const LEARN_DIR = path.resolve(__dirname, '../../public/learn');
213
223
  const GUIDES_DIR = path.resolve(__dirname, '../../public/guides');
214
224
  const COMPARE_DIR = path.resolve(__dirname, '../../public/compare');
@@ -2488,10 +2498,19 @@ function renderRobotsTxt(runtimeConfig) {
2488
2498
  return [
2489
2499
  'User-agent: *',
2490
2500
  'Allow: /',
2501
+ // 2026-05-12: every crawler GET on /checkout/pro creates a live Stripe
2502
+ // session even when no human is on the other end. Stripe sees 50 sessions
2503
+ // in 24h, 0 paid, 0 email captured. Disallow so non-human fetchers stop
2504
+ // inflating the "checkout starts" metric and creating zombie sessions.
2505
+ // Real humans still reach checkout via JS-driven clicks (not crawled).
2506
+ 'Disallow: /checkout/',
2507
+ 'Disallow: /v1/billing/',
2491
2508
  '',
2492
2509
  '# AI crawler access — allow all major LLM crawlers',
2493
2510
  'User-agent: GPTBot',
2494
2511
  'Allow: /',
2512
+ 'Disallow: /checkout/',
2513
+ 'Disallow: /v1/billing/',
2495
2514
  '',
2496
2515
  'User-agent: ClaudeBot',
2497
2516
  'Allow: /',
@@ -4373,6 +4392,28 @@ async function addContext(){
4373
4392
  return;
4374
4393
  }
4375
4394
 
4395
+ if (isGetLikeRequest && (pathname === '/federal' || pathname === '/federal.html' || pathname === '/government' || pathname === '/gov')) {
4396
+ // Federal lead-gen page. Routed through servePublicMarketingPage so agency
4397
+ // arrivals via SBIR / GSA / outbound channels capture UTM attribution and
4398
+ // landing_page_view telemetry for downstream pilot-pipeline analysis.
4399
+ // /government and /gov redirect-friendly aliases serve the same page so
4400
+ // common search queries land correctly.
4401
+ try {
4402
+ servePublicMarketingPage({
4403
+ req,
4404
+ res,
4405
+ parsed,
4406
+ hostedConfig,
4407
+ isHeadRequest,
4408
+ renderHtml: () => fs.readFileSync(FEDERAL_PAGE_PATH, 'utf-8'),
4409
+ extraTelemetry: { pageType: 'federal' },
4410
+ });
4411
+ } catch {
4412
+ sendJson(res, 404, { error: 'Federal page not found' });
4413
+ }
4414
+ return;
4415
+ }
4416
+
4376
4417
  if (isGetLikeRequest && pathname === '/learn/learn.css') {
4377
4418
  try {
4378
4419
  const cssPath = path.join(LEARN_DIR, 'learn.css');
@@ -4511,8 +4552,43 @@ async function addContext(){
4511
4552
  const isConfirmedCheckout = confirmParam === '1'
4512
4553
  || confirmParam === 'true'
4513
4554
  || req.method === 'POST';
4514
- if (!isConfirmedCheckout && botClassification.isBot) {
4515
- const eventType = 'checkout_bot_deflected';
4555
+ // Plausible funnel event #1 of 3: page view. Fired before interstitial
4556
+ // deflection so we get the full top-of-funnel count, with isBot as a
4557
+ // prop so the dashboard can filter human vs. crawler traffic. Fire-and-forget.
4558
+ recordCheckoutFunnelEvent('view', {
4559
+ page: '/checkout/pro',
4560
+ referrer: req.headers.referer || req.headers.referrer,
4561
+ forwardedFor: req.headers['x-forwarded-for'],
4562
+ remoteAddr: req.socket?.remoteAddress,
4563
+ userAgent: req.headers['user-agent'],
4564
+ props: {
4565
+ traceId,
4566
+ isBot: botClassification.isBot ? 'true' : 'false',
4567
+ botReason: botClassification.isBot ? botClassification.reason : undefined,
4568
+ isConfirmed: isConfirmedCheckout ? 'true' : 'false',
4569
+ utmSource: analyticsMetadata.utmSource,
4570
+ utmMedium: analyticsMetadata.utmMedium,
4571
+ utmCampaign: analyticsMetadata.utmCampaign,
4572
+ planId: analyticsMetadata.planId,
4573
+ },
4574
+ }).catch(() => {});
4575
+ // Render the interstitial for ALL non-confirmed GETs (bot or human),
4576
+ // not just bot traffic. Rationale: a raw GET on /checkout/pro currently
4577
+ // 302s straight to a fresh Stripe `cs_live_*` session, regardless of
4578
+ // whether the visitor is a search crawler, a link-preview fetcher, or
4579
+ // a confused human who doesn't yet know what they're paying for.
4580
+ // That created the 50-zombie-sessions / 0-paid pattern the CEO flagged
4581
+ // 2026-05-13. Every visitor now sees the $19/mo confirmation page first
4582
+ // and must click "Pay $19/mo with Stripe →" (which sets confirm=1) to
4583
+ // trigger the Stripe-session creation + redirect. Counter-risk: one
4584
+ // extra click on the human path. Mitigated because the interstitial
4585
+ // also serves as a value-preview ("6 paying customers, MIT open source,
4586
+ // cancel anytime"), which typically lifts conversion more than the
4587
+ // click-friction costs.
4588
+ if (!isConfirmedCheckout) {
4589
+ const eventType = botClassification.isBot
4590
+ ? 'checkout_bot_deflected'
4591
+ : 'checkout_interstitial_view';
4516
4592
  appendBestEffortTelemetry(FEEDBACK_DIR, {
4517
4593
  eventType,
4518
4594
  clientType: 'web',
@@ -4531,6 +4607,7 @@ async function addContext(){
4531
4607
  ctaId: analyticsMetadata.ctaId,
4532
4608
  ctaPlacement: analyticsMetadata.ctaPlacement,
4533
4609
  planId: analyticsMetadata.planId,
4610
+ isBot: botClassification.isBot ? 'true' : 'false',
4534
4611
  reason: botClassification.reason,
4535
4612
  }, req.headers, eventType);
4536
4613
  const workflowIntakeHref = buildCheckoutIntentHref(`${hostedConfig.appOrigin}/#workflow-sprint-intake`, analyticsMetadata, {
@@ -4651,6 +4728,26 @@ async function addContext(){
4651
4728
  referrer: analyticsMetadata.referrer,
4652
4729
  referrerHost: analyticsMetadata.referrerHost,
4653
4730
  }, req.headers, 'checkout_bootstrap');
4731
+ // Plausible funnel event #2 of 3: email submitted (bootstrap fired with
4732
+ // a valid email present — the user has supplied the Stripe-receipt
4733
+ // address). Only fires when normalizedCheckoutEmail was non-empty.
4734
+ if (normalizedCheckoutEmail) {
4735
+ recordCheckoutFunnelEvent('emailSubmitted', {
4736
+ page: '/checkout/pro',
4737
+ referrer: req.headers.referer || req.headers.referrer,
4738
+ forwardedFor: req.headers['x-forwarded-for'],
4739
+ remoteAddr: req.socket?.remoteAddress,
4740
+ userAgent: req.headers['user-agent'],
4741
+ props: {
4742
+ traceId,
4743
+ utmSource: analyticsMetadata.utmSource,
4744
+ utmMedium: analyticsMetadata.utmMedium,
4745
+ utmCampaign: analyticsMetadata.utmCampaign,
4746
+ planId: analyticsMetadata.planId,
4747
+ billingCycle: analyticsMetadata.billingCycle,
4748
+ },
4749
+ }).catch(() => {});
4750
+ }
4654
4751
 
4655
4752
  try {
4656
4753
  const result = await createCheckoutSession({
@@ -4670,6 +4767,56 @@ async function addContext(){
4670
4767
  });
4671
4768
 
4672
4769
  if (result.url) {
4770
+ // Plausible funnel event #3 of 3: Stripe redirect started. Fires
4771
+ // before the 302 so the event reaches Plausible even if the
4772
+ // browser leaves the origin immediately. Fire-and-forget.
4773
+ recordCheckoutFunnelEvent('stripeRedirect', {
4774
+ page: '/checkout/pro',
4775
+ referrer: req.headers.referer || req.headers.referrer,
4776
+ forwardedFor: req.headers['x-forwarded-for'],
4777
+ remoteAddr: req.socket?.remoteAddress,
4778
+ userAgent: req.headers['user-agent'],
4779
+ props: {
4780
+ traceId,
4781
+ stripeSessionId: result.sessionId,
4782
+ utmSource: analyticsMetadata.utmSource,
4783
+ utmMedium: analyticsMetadata.utmMedium,
4784
+ utmCampaign: analyticsMetadata.utmCampaign,
4785
+ planId: analyticsMetadata.planId,
4786
+ billingCycle: analyticsMetadata.billingCycle,
4787
+ },
4788
+ }).catch(() => {});
4789
+ appendBestEffortTelemetry(FEEDBACK_DIR, {
4790
+ eventType: 'stripe_redirect_started',
4791
+ clientType: 'web',
4792
+ installId: bootstrapBody.installId,
4793
+ acquisitionId: analyticsMetadata.acquisitionId,
4794
+ visitorId: analyticsMetadata.visitorId,
4795
+ sessionId: analyticsMetadata.sessionId,
4796
+ traceId,
4797
+ stripeSessionId: result.sessionId,
4798
+ source: analyticsMetadata.source,
4799
+ utmSource: analyticsMetadata.utmSource,
4800
+ utmMedium: analyticsMetadata.utmMedium,
4801
+ utmCampaign: analyticsMetadata.utmCampaign,
4802
+ utmContent: analyticsMetadata.utmContent,
4803
+ utmTerm: analyticsMetadata.utmTerm,
4804
+ creator: analyticsMetadata.creator,
4805
+ community: analyticsMetadata.community,
4806
+ postId: analyticsMetadata.postId,
4807
+ commentId: analyticsMetadata.commentId,
4808
+ campaignVariant: analyticsMetadata.campaignVariant,
4809
+ offerCode: analyticsMetadata.offerCode,
4810
+ landingPath: analyticsMetadata.landingPath,
4811
+ page: '/checkout/pro',
4812
+ ctaId: analyticsMetadata.ctaId,
4813
+ ctaPlacement: analyticsMetadata.ctaPlacement,
4814
+ planId: analyticsMetadata.planId,
4815
+ billingCycle: analyticsMetadata.billingCycle,
4816
+ seatCount: analyticsMetadata.seatCount,
4817
+ referrer: analyticsMetadata.referrer,
4818
+ referrerHost: analyticsMetadata.referrerHost,
4819
+ }, req.headers, 'stripe_redirect_started');
4673
4820
  res.writeHead(302, {
4674
4821
  ...responseHeaders,
4675
4822
  Location: result.url,
@@ -4905,11 +5052,49 @@ async function addContext(){
4905
5052
  }
4906
5053
 
4907
5054
  if (isGetLikeRequest && pathname === '/health') {
4908
- sendJson(res, 200, {
4909
- status: 'ok',
5055
+ // History (2026-05-12): /health used to return status: 'ok' unconditionally
5056
+ // with zero downstream checks. Uptime monitors saw "healthy" when Stripe
5057
+ // was down, when feedback-dir was unwritable, when env was misconfigured.
5058
+ // The fix is shallow but meaningful: probe each critical subsystem and
5059
+ // surface failures with HTTP 503 + a per-check breakdown.
5060
+ const checks = {};
5061
+ let allOk = true;
5062
+
5063
+ // Check 1: feedback dir exists and is writable.
5064
+ try {
5065
+ const { FEEDBACK_DIR } = getFeedbackPaths();
5066
+ fs.accessSync(FEEDBACK_DIR, fs.constants.W_OK);
5067
+ checks.feedbackDir = { ok: true };
5068
+ } catch (err) {
5069
+ checks.feedbackDir = { ok: false, error: err?.code || 'inaccessible' };
5070
+ allOk = false;
5071
+ }
5072
+
5073
+ // Check 2: hosted config resolves the canonical app origin.
5074
+ // If appOrigin is missing/empty, redirects + checkout flow break silently.
5075
+ if (hostedConfig?.appOrigin) {
5076
+ checks.hostedConfig = { ok: true };
5077
+ } else {
5078
+ checks.hostedConfig = { ok: false, error: 'missing_appOrigin' };
5079
+ allOk = false;
5080
+ }
5081
+
5082
+ // Check 3: build metadata loaded. If BUILD_METADATA.buildSha is empty,
5083
+ // Railway didn't inject the deploy SHA — observability is degraded.
5084
+ if (BUILD_METADATA?.buildSha) {
5085
+ checks.buildMetadata = { ok: true };
5086
+ } else {
5087
+ checks.buildMetadata = { ok: false, error: 'missing_buildSha' };
5088
+ allOk = false;
5089
+ }
5090
+
5091
+ const statusCode = allOk ? 200 : 503;
5092
+ sendJson(res, statusCode, {
5093
+ status: allOk ? 'ok' : 'degraded',
4910
5094
  version: pkg.version,
4911
5095
  buildSha: BUILD_METADATA.buildSha,
4912
5096
  uptime: process.uptime(),
5097
+ checks,
4913
5098
  deployment: {
4914
5099
  appOrigin: hostedConfig.appOrigin,
4915
5100
  billingApiBaseUrl: hostedConfig.billingApiBaseUrl,
@@ -4921,11 +5106,26 @@ async function addContext(){
4921
5106
  }
4922
5107
 
4923
5108
  if (isGetLikeRequest && pathname === '/healthz') {
5109
+ // /healthz is the deeper internal probe — verifies feedback log + memory log
5110
+ // paths exist and are writable. Returns 503 when either check fails.
4924
5111
  const { FEEDBACK_LOG_PATH, MEMORY_LOG_PATH } = requestFeedbackPaths;
4925
- sendJson(res, 200, {
4926
- status: 'ok',
5112
+ const checks = {};
5113
+ let allOk = true;
5114
+ for (const [label, p] of [['feedbackLog', FEEDBACK_LOG_PATH], ['memoryLog', MEMORY_LOG_PATH]]) {
5115
+ try {
5116
+ const dir = path.dirname(p);
5117
+ fs.accessSync(dir, fs.constants.W_OK);
5118
+ checks[label] = { ok: true };
5119
+ } catch (err) {
5120
+ checks[label] = { ok: false, error: err?.code || 'inaccessible' };
5121
+ allOk = false;
5122
+ }
5123
+ }
5124
+ sendJson(res, allOk ? 200 : 503, {
5125
+ status: allOk ? 'ok' : 'degraded',
4927
5126
  feedbackLogPath: FEEDBACK_LOG_PATH,
4928
5127
  memoryLogPath: MEMORY_LOG_PATH,
5128
+ checks,
4929
5129
  }, {}, {
4930
5130
  headOnly: isHeadRequest,
4931
5131
  });
@@ -5048,6 +5248,114 @@ async function addContext(){
5048
5248
  return;
5049
5249
  }
5050
5250
 
5251
+ // GET /v1/telemetry/export — raw recent telemetry-pings + funnel-events
5252
+ // for the unified-revenue-rollup join. Operator-key gated because the raw
5253
+ // event stream may include user-agent strings and other low-PII data
5254
+ // that we never expose unauthenticated. Returns a bounded window
5255
+ // (default last 24h, capped at 10000 rows per stream) so a misbehaving
5256
+ // caller cannot pull the entire local ledger.
5257
+ if (req.method === 'GET' && pathname === '/v1/telemetry/export') {
5258
+ // Strict auth: raw telemetry export exposes user-agent strings and
5259
+ // first-party event payloads. Unlike /v1/billing/summary (which
5260
+ // returns aggregates only), this endpoint must NEVER fall through
5261
+ // to unauthenticated access when both keys happen to be unset —
5262
+ // that would silently turn an unconfigured dev/preview server into
5263
+ // a public ledger reader. Require BOTH a configured key on the
5264
+ // server AND a token on the request that matches one of them.
5265
+ const requestToken = extractApiKey(req);
5266
+ const adminMatches = !!expectedApiKey && requestToken === expectedApiKey;
5267
+ const operatorMatches = !!expectedOperatorKey && requestToken === expectedOperatorKey;
5268
+ const anyKeyConfigured = !!expectedApiKey || !!expectedOperatorKey;
5269
+ if (!anyKeyConfigured) {
5270
+ sendJson(res, 503, {
5271
+ error: 'Telemetry export disabled — neither THUMBGATE_API_KEY nor THUMBGATE_OPERATOR_KEY is configured on this server',
5272
+ });
5273
+ return;
5274
+ }
5275
+ if (!adminMatches && !operatorMatches) {
5276
+ sendJson(res, 401, { error: 'Unauthorized — operator or admin key required' });
5277
+ return;
5278
+ }
5279
+
5280
+ // Reuse the already-parsed URL object from line ~3654 instead of
5281
+ // re-requiring the legacy 'url' module.
5282
+ const params = parsed.searchParams;
5283
+ const sinceRaw = String(params.get('since') || '').trim();
5284
+ const sinceMs = sinceRaw
5285
+ ? Date.parse(sinceRaw)
5286
+ : Date.now() - 24 * 60 * 60 * 1000;
5287
+ const since = Number.isFinite(sinceMs) ? sinceMs : Date.now() - 24 * 60 * 60 * 1000;
5288
+
5289
+ const limitRaw = Number(params.get('limit'));
5290
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0
5291
+ ? Math.min(Math.floor(limitRaw), 10000)
5292
+ : 1000;
5293
+
5294
+ const sourceRaw = String(params.get('source') || '');
5295
+ const source = ['telemetry', 'funnel', 'both'].includes(sourceRaw) ? sourceRaw : 'both';
5296
+
5297
+ const { FEEDBACK_DIR: exportDir } = getFeedbackPaths();
5298
+ const wantTelemetry = source === 'telemetry' || source === 'both';
5299
+ const wantFunnel = source === 'funnel' || source === 'both';
5300
+
5301
+ const result = {
5302
+ generatedAt: new Date().toISOString(),
5303
+ since: new Date(since).toISOString(),
5304
+ limit,
5305
+ source,
5306
+ telemetry: { rows: [], truncated: false, totalAfterSince: 0 },
5307
+ funnel: { rows: [], truncated: false, totalAfterSince: 0 },
5308
+ };
5309
+
5310
+ function readJsonlSince(p) {
5311
+ try {
5312
+ if (!fs.existsSync(p)) return [];
5313
+ const text = fs.readFileSync(p, 'utf8');
5314
+ const rows = [];
5315
+ for (const line of text.split('\n')) {
5316
+ if (!line) continue;
5317
+ let obj;
5318
+ try { obj = JSON.parse(line); } catch { continue; }
5319
+ const ts = obj.timestamp || obj.receivedAt || obj.ts || null;
5320
+ const parsed = ts ? Date.parse(ts) : NaN;
5321
+ if (Number.isFinite(parsed) && parsed >= since) {
5322
+ rows.push(obj);
5323
+ }
5324
+ }
5325
+ return rows;
5326
+ } catch { return []; }
5327
+ }
5328
+
5329
+ if (wantTelemetry) {
5330
+ const tp = path.join(exportDir, 'telemetry-pings.jsonl');
5331
+ const all = readJsonlSince(tp);
5332
+ result.telemetry.totalAfterSince = all.length;
5333
+ result.telemetry.rows = all.slice(-limit);
5334
+ result.telemetry.truncated = all.length > limit;
5335
+ }
5336
+
5337
+ if (wantFunnel) {
5338
+ // Use the canonical funnel ledger path from scripts/billing.js so
5339
+ // any test override (THUMBGATE_FUNNEL_LEDGER_PATH / _TEST_FUNNEL_LEDGER_PATH)
5340
+ // resolves correctly. Falls back to the feedback dir's funnel-events.jsonl.
5341
+ let funnelPath;
5342
+ try {
5343
+ const billing = require('../../scripts/billing');
5344
+ funnelPath = (billing._FUNNEL_LEDGER_PATH && billing._FUNNEL_LEDGER_PATH())
5345
+ || path.join(exportDir, 'funnel-events.jsonl');
5346
+ } catch {
5347
+ funnelPath = path.join(exportDir, 'funnel-events.jsonl');
5348
+ }
5349
+ const all = readJsonlSince(funnelPath);
5350
+ result.funnel.totalAfterSince = all.length;
5351
+ result.funnel.rows = all.slice(-limit);
5352
+ result.funnel.truncated = all.length > limit;
5353
+ }
5354
+
5355
+ sendJson(res, 200, result);
5356
+ return;
5357
+ }
5358
+
5051
5359
  if (req.method === 'OPTIONS' && pathname === '/v1/intake/workflow-sprint') {
5052
5360
  sendPublicBillingPreflight(res);
5053
5361
  return;
@@ -5240,6 +5548,222 @@ async function addContext(){
5240
5548
  return;
5241
5549
  }
5242
5550
 
5551
+ // Public terms of service — required by Stripe / Stripe Checkout for the
5552
+ // "Terms of service URL" field in Business → Public details. Mirrors the
5553
+ // /privacy + /support pages: thin HTML, no external deps, no DB hit.
5554
+ if (isGetLikeRequest && pathname === '/terms') {
5555
+ sendHtml(res, 200, `<!DOCTYPE html><html><head><title>Terms of Service — ThumbGate</title></head><body>
5556
+ <h1>Terms of Service</h1>
5557
+ <p><strong>ThumbGate</strong> (npm: thumbgate)</p>
5558
+ <p>Last updated: 2026-05-12</p>
5559
+ <h2>The Service</h2>
5560
+ <p>ThumbGate provides pre-action gates for AI coding agents: a local CLI (MIT-licensed) and an optional hosted tier at thumbgate-production.up.railway.app. By installing the CLI or paying for a subscription, you agree to these terms.</p>
5561
+ <h2>Payment</h2>
5562
+ <p>Paid tiers are billed through Stripe. Subscriptions auto-renew until cancelled. One-off purchases (Sprint Diagnostic, Workflow Sprint, Quick Read, Workflow Teardown, First Failure Rule) are charged once.</p>
5563
+ <h2>Refunds</h2>
5564
+ <p>Pro and Team subscriptions: cancel anytime; we issue a full refund within 7 days of the first charge, prorated thereafter. One-off purchases: refund on request if we cannot deliver the scoped artifact.</p>
5565
+ <h2>Acceptable Use</h2>
5566
+ <p>You may not use ThumbGate to (a) circumvent the safety controls of other AI providers, (b) generate malware or content that violates third-party terms, or (c) resell the hosted tier without written permission.</p>
5567
+ <h2>Disclaimer of Warranty</h2>
5568
+ <p>The service is provided "as is", without warranty of any kind. ThumbGate is a guard rail, not a guarantee. We do not warrant that every AI-agent mistake will be prevented.</p>
5569
+ <h2>Limitation of Liability</h2>
5570
+ <p>Total liability for any claim is limited to the amount you paid in the 12 months preceding the claim.</p>
5571
+ <h2>Governing Law</h2>
5572
+ <p>These terms are governed by the laws of the State of New York, United States.</p>
5573
+ <h2>Changes</h2>
5574
+ <p>We may update these terms; material changes will be announced via the email on file at least 14 days before they take effect.</p>
5575
+ <h2>Contact</h2><p>igor.ganapolsky@gmail.com</p>
5576
+ <p><a href="https://github.com/IgorGanapolsky/ThumbGate">GitHub</a> · <a href="/privacy">Privacy</a> · <a href="/support">Support</a></p>
5577
+ </body></html>`, {}, {
5578
+ headOnly: isHeadRequest,
5579
+ });
5580
+ return;
5581
+ }
5582
+
5583
+ // Public case studies — proof surface for buyers. Conversion-optimization
5584
+ // surface that was missing: thumbgate.ai had no /case-studies, so visitors
5585
+ // landed on CLI install commands without seeing whether anyone actually
5586
+ // got value. First entry is the Aiventyx Teams listing integration: real
5587
+ // third-party CTR signal (5/8 clicks before the /go/teams fix, end-to-end
5588
+ // verified after).
5589
+ if (isGetLikeRequest && pathname === '/case-studies') {
5590
+ sendHtml(res, 200, `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Case Studies — ThumbGate</title><meta name="description" content="Real integrations of ThumbGate's pre-action checks for AI coding agents. Proof, not promises."><style>body{font-family:system-ui,-apple-system,sans-serif;max-width:780px;margin:0 auto;padding:32px 20px;line-height:1.55;color:#1f2937}h1{font-size:32px;margin:0 0 8px}.lede{color:#6b7280;font-size:18px;margin:0 0 32px}article{border:1px solid #e5e7eb;border-radius:12px;padding:24px;margin-bottom:24px;background:#fff}article h2{margin:0 0 4px;font-size:22px}.meta{color:#6b7280;font-size:13px;margin-bottom:16px}h3{font-size:15px;margin:20px 0 8px;color:#374151;text-transform:uppercase;letter-spacing:0.5px}.metric{display:inline-block;background:#0f172a;color:#fff;padding:4px 10px;border-radius:6px;font-weight:600;font-size:14px;margin:0 4px 4px 0}p{margin:8px 0}a{color:#0066cc}code{background:#f3f4f6;padding:1px 6px;border-radius:4px;font-size:13.5px}footer{margin-top:48px;padding-top:24px;border-top:1px solid #e5e7eb;color:#6b7280;font-size:14px}</style></head><body>
5591
+ <h1>Case Studies</h1>
5592
+ <p class="lede">Real integrations. No fabricated logos, no aspirational numbers — every claim below is reproducible.</p>
5593
+
5594
+ <article>
5595
+ <h2>Aiventyx marketplace — Teams listing CTR recovery</h2>
5596
+ <p class="meta">Integration partner: <a href="https://www.aiventyx.com">Aiventyx</a> · Reported by: Qaiser Mehdi · Verified: 2026-05-13</p>
5597
+
5598
+ <h3>The problem</h3>
5599
+ <p>Aiventyx is a marketplace for AI tools. ThumbGate's Teams listing was their highest-CTR external surface — <span class="metric">62% CTR</span> (5 clicks on 8 views, May 7–9 window). When their integrator rolled out canonical tracked URLs, every Teams click started landing on:</p>
5600
+ <p><code>{"error":"Tracked link not found","allowed":["gpt","pro","install","reddit","linkedin","x","github"]}</code></p>
5601
+ <p>The <code>/go/teams</code> slug wasn't registered in our redirector — a 404 was eating every paid-intent click from their strongest external surface.</p>
5602
+
5603
+ <h3>The fix</h3>
5604
+ <p>Added <code>teams</code> to <code>TRACKED_LINK_TARGETS</code>: HTTP 302 redirect to <code>/checkout/pro?plan_id=team&seat_count=3&billing_cycle=monthly</code> — the 3-seat $147/mo self-serve Stripe Team checkout. Caller-supplied UTMs flow through to Stripe metadata end-to-end.</p>
5605
+
5606
+ <h3>The verification</h3>
5607
+ <p>Qaiser's own incognito test, May 13 6:04 AM (full email on record):</p>
5608
+ <p><code>https://thumbgate.ai/go/teams?utm_source=aiventyx</code><br>
5609
+ → 302 to Stripe checkout<br>
5610
+ → "Subscribe to ThumbGate Team" page loads<br>
5611
+ → $147/mo, 3-seat Team plan confirmed<br>
5612
+ → Aiventyx UTMs intact in URL</p>
5613
+
5614
+ <h3>What this proves</h3>
5615
+ <p>End-to-end attribution from a third-party marketplace through ThumbGate's redirector into Stripe checkout, with the caller's UTM chain preserved. Two regression tests pin the redirect contract so it can't silently break.</p>
5616
+
5617
+ <p><a href="/go/teams?utm_source=case-study">Try the live redirect →</a></p>
5618
+ </article>
5619
+
5620
+ <footer>
5621
+ <p>Want to be the next case study? The product is real, the integration is 30 seconds: <code>npx thumbgate init</code>. If you ship something with ThumbGate and want it documented here, email <a href="mailto:igor.ganapolsky@gmail.com">igor.ganapolsky@gmail.com</a>.</p>
5622
+ <p><a href="https://thumbgate.ai">Home</a> · <a href="/pricing">Pricing</a> · <a href="/privacy">Privacy</a> · <a href="/terms">Terms</a> · <a href="/support">Support</a></p>
5623
+ </footer>
5624
+ </body></html>`, {}, {
5625
+ headOnly: isHeadRequest,
5626
+ });
5627
+ return;
5628
+ }
5629
+
5630
+ // Public canonical pricing page. The audit flagged "pricing schizophrenia":
5631
+ // sales/pricing.json said $49 / $299, COMMERCIAL_TRUTH.md said $19 / $149,
5632
+ // and there was no buyer-facing surface to reconcile the two. This is now
5633
+ // the single source of truth for what ThumbGate sells, in priority order:
5634
+ // Sprint (proof-pack, sales-led) → Pro (self-serve recurring) → Team
5635
+ // (after qualification). Every paid CTA across the site should funnel
5636
+ // here OR directly into Stripe checkout — never a different price.
5637
+ if (isGetLikeRequest && pathname === '/pricing') {
5638
+ sendHtml(res, 200, `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Pricing — ThumbGate</title><meta name="description" content="ThumbGate pricing: free CLI, $19/mo Pro, $49/seat Team, $499 Sprint Diagnostic, $1500 full Workflow Hardening Sprint. Single source of truth across the site."><style>body{font-family:system-ui,-apple-system,sans-serif;max-width:980px;margin:0 auto;padding:32px 20px;line-height:1.55;color:#1f2937}h1{font-size:36px;margin:0 0 8px;text-align:center}.lede{color:#6b7280;font-size:18px;margin:0 0 32px;text-align:center}.grid{display:grid;grid-template-columns:1fr;gap:20px;margin-bottom:24px}@media(min-width:720px){.grid{grid-template-columns:repeat(2,1fr)}.hero{grid-column:1/-1}}.card{border:1px solid #e5e7eb;border-radius:12px;padding:24px;background:#fff;display:flex;flex-direction:column}.hero{border:2px solid #0f172a;background:linear-gradient(135deg,#fef3c7,#fff)}.tag{display:inline-block;background:#0f172a;color:#fff;padding:3px 10px;border-radius:6px;font-size:12px;font-weight:600;letter-spacing:0.5px;margin-bottom:12px}.tag-free{background:#10b981}.tag-pro{background:#3b82f6}.tag-team{background:#8b5cf6}.tag-diag{background:#0f172a}.tag-sprint{background:#b91c1c}h2{margin:0 0 4px;font-size:22px}.price{font-size:30px;font-weight:700;margin:8px 0 12px}.price small{font-size:14px;color:#6b7280;font-weight:400}.tagline{color:#374151;margin:0 0 16px;font-size:15px}ul{margin:0 0 20px;padding-left:18px}li{margin:6px 0;font-size:14px}.cta{display:inline-block;background:#0f172a;color:#fff;padding:12px 24px;border-radius:8px;font-weight:600;text-decoration:none;text-align:center;margin-top:auto}.cta-secondary{background:#fff;color:#0f172a;border:1px solid #0f172a}.cta-free{background:#10b981}.micro{border-top:1px solid #e5e7eb;padding-top:24px;margin-top:16px}.micro-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin:16px 0}.micro-card{border:1px solid #e5e7eb;border-radius:8px;padding:14px;text-align:center;background:#fafafa}.micro-card .mp{font-size:20px;font-weight:700;color:#0f172a}.micro-card .ml{font-size:13px;color:#6b7280;margin:4px 0 8px}.micro-card a{color:#0066cc;font-size:13px;text-decoration:none}footer{margin-top:32px;padding-top:24px;border-top:1px solid #e5e7eb;color:#6b7280;font-size:14px;text-align:center}footer a{color:#0066cc}</style></head><body>
5639
+ <h1>Pricing</h1>
5640
+ <p class="lede">Six paths to ThumbGate. Pick by what you need: an install, a subscription, a team rollout, or a stakeholder-visible artifact.</p>
5641
+
5642
+ <div class="grid">
5643
+
5644
+ <div class="card hero">
5645
+ <span class="tag tag-sprint">Sprint — Full engagement</span>
5646
+ <h2>Workflow Hardening Sprint</h2>
5647
+ <div class="price">$1,500 <small>· one-time</small></div>
5648
+ <p class="tagline">The full hardening engagement for a single AI-agent workflow. Built on top of the Sprint Diagnostic — we apply the diagnostic findings into a shipped Pre-Action Check pack, deploy hooks into your repo, and run the rollout review. Two weeks calendar-time, single fixed price.</p>
5649
+ <ul>
5650
+ <li>Diagnostic + applied rules + deployed PreToolUse hooks</li>
5651
+ <li>Best path if you need the workflow actually fixed, not just diagnosed</li>
5652
+ <li>Refund if we can't extract or apply a rule</li>
5653
+ </ul>
5654
+ <a class="cta" href="mailto:igor.ganapolsky@gmail.com?subject=ThumbGate%20Workflow%20Hardening%20Sprint%20-%20Intake&body=Stack%20(Claude%20Code%2FCursor%2Fother)%3A%0AOne%20repeated%20agent%20failure%20you%20want%20to%20kill%3A%0ATimeline%3A%0A">Email to start the full sprint →</a>
5655
+ </div>
5656
+
5657
+ <div class="card">
5658
+ <span class="tag tag-diag">Diagnostic — Proof first</span>
5659
+ <h2>Sprint Diagnostic</h2>
5660
+ <div class="price">$499 <small>· one-time</small></div>
5661
+ <p class="tagline">Two-day diagnostic on one workflow. Top-5 prevention rules ranked by impact, scoped Pre-Action Check pack delivered as a PR, 60-minute findings review. The lightweight on-ramp to the full sprint.</p>
5662
+ <ul>
5663
+ <li>Best if you need a stakeholder-visible artifact (PR, doc, briefing)</li>
5664
+ <li>Two days fixed scope — no scope creep</li>
5665
+ <li>Refund if we can't extract a rule from your failure trace</li>
5666
+ </ul>
5667
+ <a class="cta" href="https://buy.stripe.com/28E00j3Uge1E2dzgWL3sI2J">Pay $499 diagnostic →</a>
5668
+ </div>
5669
+
5670
+ <div class="card">
5671
+ <span class="tag tag-free">Free — Forever</span>
5672
+ <h2>ThumbGate CLI</h2>
5673
+ <div class="price">$0</div>
5674
+ <p class="tagline">MIT-licensed CLI + local PreToolUse hook. Unlimited captures, 5 active prevention rules, local lesson DB. Works with Claude Code, Cursor, Codex, Gemini, Amp, Cline, OpenCode.</p>
5675
+ <ul>
5676
+ <li>30-second install: <code>npx thumbgate init</code></li>
5677
+ <li>No account, no signup, no data leaves your machine</li>
5678
+ <li>Hit 5 active rules → upgrade to Pro for unlimited</li>
5679
+ </ul>
5680
+ <a class="cta cta-free" href="/go/install?utm_source=pricing">Install free CLI →</a>
5681
+ </div>
5682
+
5683
+ <div class="card">
5684
+ <span class="tag tag-pro">Pro — Self-serve recurring</span>
5685
+ <h2>ThumbGate Pro</h2>
5686
+ <div class="price">$19 <small>/ month</small> · $149 / year</div>
5687
+ <p class="tagline">For developers running multiple AI agents who hit the 5-rule wall. Unlimited prevention rules, local dashboard, DPO export for offline preference fine-tuning, lesson search across sessions.</p>
5688
+ <ul>
5689
+ <li>Unlimited active prevention rules</li>
5690
+ <li>Local dashboard + lesson recall</li>
5691
+ <li>7-day refund window. Cancel anytime.</li>
5692
+ </ul>
5693
+ <a class="cta cta-secondary" href="/go/pro?utm_source=pricing">Start Pro →</a>
5694
+ </div>
5695
+
5696
+ <div class="card">
5697
+ <span class="tag tag-team">Team — After qualification</span>
5698
+ <h2>ThumbGate Team</h2>
5699
+ <div class="price">$49 <small>/ seat / month</small> · 3-seat min ($147/mo)</div>
5700
+ <p class="tagline">For engineering teams with shared AI-agent workflows. Shared lesson DB so one engineer's save protects the whole team, org-level policy rollout, audit-ready evidence.</p>
5701
+ <ul>
5702
+ <li>Shared prevention-rule policy across seats</li>
5703
+ <li>Self-serve checkout — no sales call required</li>
5704
+ <li>Most teams start with a Sprint first, then scale to seats</li>
5705
+ </ul>
5706
+ <a class="cta cta-secondary" href="/go/teams?utm_source=pricing">Start Team →</a>
5707
+ </div>
5708
+
5709
+ </div>
5710
+
5711
+ <div class="micro">
5712
+ <h2 style="text-align:center;font-size:20px;margin:0 0 4px;">Micro-purchases — pay for one piece</h2>
5713
+ <p style="text-align:center;color:#6b7280;font-size:14px;margin:0 0 8px;">For evaluators who want to validate one specific surface before subscribing.</p>
5714
+ <div class="micro-grid">
5715
+ <div class="micro-card">
5716
+ <div class="mp">$1</div>
5717
+ <div class="ml">First Failure Rule</div>
5718
+ <a href="https://buy.stripe.com/fZu28rfCY6zcbO99uj3sI2G">Pay $1 →</a>
5719
+ </div>
5720
+ <div class="micro-card">
5721
+ <div class="mp">$19</div>
5722
+ <div class="ml">AI Agent Failure Quick Read</div>
5723
+ <a href="https://buy.stripe.com/5kQ7sL76s1eSaK55e33sI2H">Pay $19 →</a>
5724
+ </div>
5725
+ <div class="micro-card">
5726
+ <div class="mp">$99</div>
5727
+ <div class="ml">Workflow Teardown</div>
5728
+ <a href="https://buy.stripe.com/8x214n2Qc4r44lHayn3sI2I">Pay $99 →</a>
5729
+ </div>
5730
+ </div>
5731
+ </div>
5732
+
5733
+ <footer>
5734
+ <p>One source of truth for ThumbGate pricing. Numbers here override anything stale elsewhere on the site.</p>
5735
+ <p><a href="/">Home</a> · <a href="/case-studies">Case Studies</a> · <a href="/support">Support</a> · <a href="/privacy">Privacy</a> · <a href="/terms">Terms</a></p>
5736
+ </footer>
5737
+ </body></html>`, {}, {
5738
+ headOnly: isHeadRequest,
5739
+ });
5740
+ return;
5741
+ }
5742
+
5743
+ // Public support / contact page — required for Stripe Business → Public
5744
+ // details "Customer support URL" field. Single source of truth for how
5745
+ // customers reach us (email, GitHub issues, status page).
5746
+ if (isGetLikeRequest && pathname === '/support') {
5747
+ sendHtml(res, 200, `<!DOCTYPE html><html><head><title>Support — ThumbGate</title></head><body>
5748
+ <h1>Support</h1>
5749
+ <p><strong>ThumbGate</strong> support, billing, and contact paths.</p>
5750
+ <h2>Email</h2>
5751
+ <p>For billing questions, refunds, subscription changes, or technical issues with the hosted tier: <a href="mailto:igor.ganapolsky@gmail.com">igor.ganapolsky@gmail.com</a>. We reply within one business day.</p>
5752
+ <h2>GitHub Issues</h2>
5753
+ <p>For bugs, CLI questions, and feature requests in the open-source CLI: <a href="https://github.com/IgorGanapolsky/ThumbGate/issues">github.com/IgorGanapolsky/ThumbGate/issues</a>.</p>
5754
+ <h2>Status</h2>
5755
+ <p>Hosted-tier status: check <a href="https://thumbgate-production.up.railway.app/health">/health</a> for current health. Railway-hosted; rebuilds take 2-5 minutes.</p>
5756
+ <h2>Refunds</h2>
5757
+ <p>Pro / Team subscriptions: 7-day full refund window from first charge. One-off purchases: refund on request if we cannot deliver. Email the address above.</p>
5758
+ <h2>Security</h2>
5759
+ <p>Disclose vulnerabilities by email; please do not post to public GitHub issues. We acknowledge within 48 hours.</p>
5760
+ <p><a href="https://github.com/IgorGanapolsky/ThumbGate">GitHub</a> · <a href="/privacy">Privacy</a> · <a href="/terms">Terms</a></p>
5761
+ </body></html>`, {}, {
5762
+ headOnly: isHeadRequest,
5763
+ });
5764
+ return;
5765
+ }
5766
+
5243
5767
  // Public privacy policy — required for GPT Store and marketplace listings
5244
5768
  if (isGetLikeRequest && pathname === '/privacy') {
5245
5769
  sendHtml(res, 200, `<!DOCTYPE html><html><head><title>Privacy Policy — ThumbGate</title></head><body>