thumbgate 1.39.0 → 1.40.1

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 (180) hide show
  1. package/.agents/skills/craft-playbook-gate/SKILL.md +51 -0
  2. package/.agents/skills/qwenwork-policy-group-honesty-not-clone/SKILL.md +36 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.well-known/llms.txt +2 -2
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +11 -5
  7. package/adapters/claude/.mcp.json +6 -2
  8. package/adapters/codex/config.toml +5 -0
  9. package/adapters/forge/forge.yaml +4 -4
  10. package/adapters/future-agi/.mcp.json +1 -1
  11. package/adapters/future-agi/config.toml +1 -1
  12. package/adapters/future-agi/opencode.json +1 -1
  13. package/adapters/herdr/herdr-plugin.toml +2 -2
  14. package/adapters/mcp/server-stdio.js +104 -7
  15. package/adapters/opencode/opencode.json +1 -1
  16. package/adapters/strands/strands-middleware.js +31 -4
  17. package/bin/cli.js +191 -54
  18. package/config/brand-standards.json +131 -0
  19. package/config/gates/default.json +18 -1
  20. package/config/github-about.json +1 -1
  21. package/config/mcp-allowlists.json +16 -3
  22. package/config/merge-quality-checks.json +3 -1
  23. package/config/post-deploy-marketing-pages.json +4 -4
  24. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  25. package/hooks/hooks.json +24 -0
  26. package/openapi/openapi.yaml +7 -3
  27. package/package.json +87 -33
  28. package/public/about.html +2 -2
  29. package/public/admin.html +771 -0
  30. package/public/agent-manager.html +3 -3
  31. package/public/agents-cost-savings.html +1 -1
  32. package/public/ai-malpractice-prevention.html +12 -12
  33. package/public/architecture.html +0 -1
  34. package/public/assets/diagrams/decision.svg +3 -3
  35. package/public/assets/diagrams/hero-thumbs.svg +2 -4
  36. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  37. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  38. package/public/blog/git-at-agent-scale.html +2 -2
  39. package/public/blog/inside-your-boundary.html +1 -1
  40. package/public/blog/process-over-outcome-gates.html +1 -1
  41. package/public/case-studies.html +5 -6
  42. package/public/codex-enterprise.html +1 -1
  43. package/public/codex-plugin.html +1 -1
  44. package/public/dashboard.html +775 -483
  45. package/public/diagnostic.html +15 -10
  46. package/public/enterprise-governance.html +26 -174
  47. package/public/eval-scorecard.html +3 -4
  48. package/public/eval-scorecard.json +2 -2
  49. package/public/evaluations.html +0 -1
  50. package/public/founders.html +3 -3
  51. package/public/gaming-playbook.html +4 -4
  52. package/public/guide.html +3 -5
  53. package/public/index.html +302 -97
  54. package/public/install.html +16 -10
  55. package/public/js/buyer-intent.js +49 -8
  56. package/public/lessons.html +246 -83
  57. package/public/numbers.html +32 -33
  58. package/public/operator-framework.html +44 -72
  59. package/public/peter.html +3 -3
  60. package/public/platform-partners.html +1 -1
  61. package/public/pricing.html +163 -66
  62. package/public/pro.html +3 -1
  63. package/public/project-switcher.js +76 -0
  64. package/public/whitepaper.html +1 -2
  65. package/scripts/action-receipts.js +393 -0
  66. package/scripts/activation-quickstart.js +15 -3
  67. package/scripts/activation-tracker.js +280 -3
  68. package/scripts/agent-action-inventory.js +235 -143
  69. package/scripts/agent-operations-planner.js +1 -1
  70. package/scripts/agent-readiness.js +36 -6
  71. package/scripts/agentic-prompt-pipelines.js +901 -0
  72. package/scripts/analytics-window.js +7 -1
  73. package/scripts/async-job-runner.js +66 -11
  74. package/scripts/audit-trail.js +37 -24
  75. package/scripts/auto-promote-gates.js +37 -27
  76. package/scripts/auto-wire-hooks.js +64 -25
  77. package/scripts/backfill-lesson-scopes.js +122 -0
  78. package/scripts/billing.js +889 -132
  79. package/scripts/bot-detection.js +112 -0
  80. package/scripts/brand-standards-gate.js +571 -0
  81. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  82. package/scripts/cli-demo.js +5 -27
  83. package/scripts/cli-schema.js +25 -1
  84. package/scripts/commercial-offer.js +2 -2
  85. package/scripts/contextfs.js +9 -3
  86. package/scripts/craft-playbook-gate.js +550 -0
  87. package/scripts/cross-encoder-reranker.js +4 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +574 -167
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/docker-sandbox-planner.js +3 -3
  92. package/scripts/export-dpo-pairs.js +12 -7
  93. package/scripts/failure-diagnostics.js +11 -0
  94. package/scripts/feedback-aggregate.js +4 -0
  95. package/scripts/feedback-attribution.js +6 -4
  96. package/scripts/feedback-history-distiller.js +18 -6
  97. package/scripts/feedback-loop.js +255 -89
  98. package/scripts/feedback-paths.js +8 -1
  99. package/scripts/feedback-sanitizer.js +5 -0
  100. package/scripts/feedback-scope.js +106 -0
  101. package/scripts/feedback-session.js +8 -2
  102. package/scripts/filesystem-search.js +13 -8
  103. package/scripts/financial-control-plane.js +707 -45
  104. package/scripts/gate-stats.js +38 -5
  105. package/scripts/gates-engine.js +1326 -240
  106. package/scripts/generate-eval-scorecard.js +0 -1
  107. package/scripts/gitlab-sdlc-prompts.js +397 -0
  108. package/scripts/harness-tool-names.js +31 -5
  109. package/scripts/hook-runtime.js +10 -0
  110. package/scripts/hybrid-feedback-context.js +7 -2
  111. package/scripts/intervention-policy.js +2 -1
  112. package/scripts/lesson-canonical.js +2 -2
  113. package/scripts/lesson-db.js +55 -14
  114. package/scripts/lesson-graph.js +2 -1
  115. package/scripts/lesson-retrieval.js +95 -9
  116. package/scripts/lesson-search.js +86 -22
  117. package/scripts/lesson-synthesis.js +21 -5
  118. package/scripts/mabl-failure-honesty.js +273 -0
  119. package/scripts/mailer/index.js +17 -1
  120. package/scripts/mailer/resend-mailer.js +213 -179
  121. package/scripts/migrate-project-scope.js +209 -0
  122. package/scripts/model-distress-detector.js +3 -3
  123. package/scripts/operational-integrity.js +436 -3
  124. package/scripts/override-audit.js +2 -0
  125. package/scripts/owner-admin.js +338 -0
  126. package/scripts/pr-manager.js +194 -1
  127. package/scripts/product-feedback.js +35 -0
  128. package/scripts/progressive-signoff.js +260 -0
  129. package/scripts/project-catalog.js +243 -0
  130. package/scripts/project-dashboard.js +61 -0
  131. package/scripts/project-evidence.js +172 -0
  132. package/scripts/project-identity.js +182 -0
  133. package/scripts/project-scope.js +381 -0
  134. package/scripts/prompt-eval.js +1 -1
  135. package/scripts/prompt-guard.js +446 -52
  136. package/scripts/proof-report.js +232 -0
  137. package/scripts/provider-action-normalizer.js +14 -6
  138. package/scripts/qwenwork-policy-group.js +413 -0
  139. package/scripts/rate-limiter.js +41 -0
  140. package/scripts/secret-redaction.js +171 -25
  141. package/scripts/secret-scanner.js +101 -42
  142. package/scripts/self-protection.js +2 -2
  143. package/scripts/seo-gsd.js +14 -14
  144. package/scripts/session-context-dedupe.js +66 -0
  145. package/scripts/settings-hierarchy.js +4 -2
  146. package/scripts/statusline-meta.js +34 -23
  147. package/scripts/tailscale-october-access.js +416 -0
  148. package/scripts/task-outcomes.js +58 -2
  149. package/scripts/telemetry-analytics.js +260 -16
  150. package/scripts/thumbgate-search.js +23 -9
  151. package/scripts/tool-kpi-tracker.js +5 -2
  152. package/scripts/tool-registry.js +42 -1
  153. package/scripts/triage-savings-calculator.js +1 -1
  154. package/scripts/vector-store.js +4 -1
  155. package/scripts/verified-lessons.js +270 -0
  156. package/scripts/verify-marketing-pages-deployed.js +2 -2
  157. package/scripts/workflow-sentinel.js +29 -10
  158. package/server.json +2 -2
  159. package/src/api/server.js +2478 -470
  160. package/src/feedback.js +21 -0
  161. package/src/hermes-sync-plane.js +2 -1
  162. package/src/index.js +2 -0
  163. package/src/lesson-search.js +9 -0
  164. package/src/mckinsey-top-company-ai-coding.js +493 -0
  165. package/src/mcp/email-triage-server/index.js +973 -0
  166. package/src/mcp/email-triage-server/package.json +12 -0
  167. package/src/mcp/server.js +3 -0
  168. package/src/mcp-writeguard.js +772 -11
  169. package/src/openshell-lovable-engine.js +1475 -0
  170. package/src/task-outcome.js +3 -0
  171. package/config/evals/agent-safety-eval.json +0 -447
  172. package/config/evals/retrieval-ranking-golden.json +0 -522
  173. package/config/progressive/01-wire-only.json +0 -11
  174. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  175. package/config/progressive/03-one-lesson.json +0 -10
  176. package/config/progressive/04-warn-fires.json +0 -11
  177. package/config/progressive/05-strict-optional.json +0 -11
  178. package/config/progressive/README.md +0 -15
  179. package/public/assets/diagrams/agent-integration.png +0 -0
  180. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
package/src/api/server.js CHANGED
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ const { withDataScope, withoutDataScope, currentDataScope, tenantDataScope, assertScopedDataPath, dataScopeKey } = require('../../scripts/feedback-scope');
3
+ const { parseProjectSelection, projectForCapture, projectForRecord, matchesProject, validProjectKey } = require('../../scripts/project-identity');
4
+ const { readProjectRows, buildProjectCatalog } = require('../../scripts/project-catalog');
5
+ const ownerAdmin = require('../../scripts/owner-admin');
2
6
  const http = require('http');
3
7
  const https = require('https');
4
8
  const fs = require('fs');
@@ -111,7 +115,12 @@ const {
111
115
  } = require('../../scripts/internal-agent-bootstrap');
112
116
  const {
113
117
  classifyRequester,
118
+ isHumanCheckoutNavigation,
119
+ checkoutRequesterKey,
120
+ createRapidCheckoutGuard,
114
121
  } = require('../../scripts/bot-detection');
122
+
123
+ const rapidCheckoutGuard = createRapidCheckoutGuard();
115
124
  const {
116
125
  recordCheckoutFunnelEvent,
117
126
  } = require('../../scripts/plausible-server-events');
@@ -132,12 +141,18 @@ const {
132
141
  samplePosteriors,
133
142
  } = require('../../scripts/thompson-sampling');
134
143
  const {
144
+ CONFIG: billingConfig,
135
145
  appendFunnelEvent,
136
146
  createCheckoutSession,
147
+ isSyntheticOrOwnerCheckoutEmail,
148
+ createBillingPortalSession,
137
149
  getCheckoutSessionStatus,
138
150
  provisionApiKey,
151
+ resolvePaidEntitlementForEmail,
139
152
  validateApiKey,
140
153
  recordUsage,
154
+ recordAccountFirstBlock,
155
+ loadKeyStore,
141
156
  rotateApiKey,
142
157
  handleWebhook,
143
158
  verifyWebhookSignature,
@@ -164,6 +179,7 @@ const {
164
179
  generateSkills,
165
180
  } = require('../../scripts/skill-generator');
166
181
  const {
182
+ evaluateGates,
167
183
  satisfyCondition,
168
184
  loadStats: loadGateStats,
169
185
  setConstraint,
@@ -174,6 +190,9 @@ const {
174
190
  getBranchGovernanceState,
175
191
  approveProtectedAction,
176
192
  } = require('../../scripts/gates-engine');
193
+ const {
194
+ summarizeFirstBlockEvents,
195
+ } = require('../../scripts/activation-tracker');
177
196
  const {
178
197
  evaluateOperationalIntegrity,
179
198
  } = require('../../scripts/operational-integrity');
@@ -279,6 +298,7 @@ const {
279
298
  } = require('../../scripts/telemetry-analytics');
280
299
  const {
281
300
  buildProductIssueTitle,
301
+ composeChipFeedback,
282
302
  submitProductIssue,
283
303
  } = require('../../scripts/product-feedback');
284
304
  const {
@@ -294,6 +314,9 @@ const {
294
314
  } = require('../../scripts/document-intake');
295
315
  const {
296
316
  checkLimit,
317
+ isProTier,
318
+ proWouldHaveBlockedSentence,
319
+ droppedRepeatFromRulesMarkdown,
297
320
  UPGRADE_MESSAGE: RATE_LIMIT_MESSAGE,
298
321
  } = require('../../scripts/rate-limiter');
299
322
  const { sendProblem, PROBLEM_TYPES } = require('../../scripts/problem-detail');
@@ -449,12 +472,12 @@ function readLessonJsonl(filePath, options) {
449
472
  return getLessonSynthesisModule().readJSONLLocal(filePath, options);
450
473
  }
451
474
 
452
- function updateLessonJsonlRecord(filePath, recordId, record) {
453
- return getLessonSynthesisModule().updateRecordInJsonl(filePath, recordId, record);
475
+ function updateLessonJsonlRecord(filePath, recordId, record, options) {
476
+ return getLessonSynthesisModule().updateRecordInJsonl(filePath, recordId, record, options);
454
477
  }
455
478
 
456
- function deleteLessonJsonlRecord(filePath, recordId) {
457
- return getLessonSynthesisModule().deleteRecordFromJsonl(filePath, recordId);
479
+ function deleteLessonJsonlRecord(filePath, recordId, options) {
480
+ return getLessonSynthesisModule().deleteRecordFromJsonl(filePath, recordId, options);
458
481
  }
459
482
 
460
483
  function serveStaticFile(res, filePath, { headOnly = false, cacheSeconds = 86400 } = {}) {
@@ -569,6 +592,89 @@ const TRACKED_LINK_TARGETS = Object.freeze({
569
592
  allowCustomerEmail: true,
570
593
  prefillStripeEmail: true,
571
594
  },
595
+ 'pro-annual': {
596
+ fallbackHref: PRO_CHECKOUT_URL,
597
+ external: true,
598
+ botDeflectPath: '/checkout/pro',
599
+ ctaId: 'pro_checkout_annual_stripe',
600
+ ctaPlacement: 'checkout_interstitial',
601
+ eventType: 'pro_checkout_direct_stripe',
602
+ defaults: {
603
+ utm_source: 'website',
604
+ utm_medium: 'checkout_interstitial',
605
+ utm_campaign: 'pro_annual_149',
606
+ plan_id: 'pro',
607
+ billing_cycle: 'annual',
608
+ },
609
+ allowCustomerEmail: true,
610
+ prefillStripeEmail: true,
611
+ },
612
+ 'bundle-49': {
613
+ fallbackHref: 'https://buy.stripe.com/dRm3cv1M85v819v6i73sJ12',
614
+ external: true,
615
+ botDeflectPath: '/checkout/pro',
616
+ ctaId: 'pro_checkout_bundle_49',
617
+ ctaPlacement: 'checkout_interstitial',
618
+ eventType: 'cta_click',
619
+ defaults: {
620
+ utm_source: 'website',
621
+ utm_medium: 'checkout_interstitial',
622
+ utm_campaign: 'bundle_49',
623
+ plan_id: 'bundle_49',
624
+ billing_cycle: 'one_time',
625
+ },
626
+ allowCustomerEmail: true,
627
+ prefillStripeEmail: true,
628
+ },
629
+ 'playbook-10': {
630
+ fallbackHref: 'https://buy.stripe.com/8x2fZh3UgbTw19v21R3sJ11',
631
+ external: true,
632
+ botDeflectPath: '/checkout/pro',
633
+ ctaId: 'pro_checkout_playbook_10',
634
+ ctaPlacement: 'checkout_interstitial',
635
+ eventType: 'cta_click',
636
+ defaults: {
637
+ utm_source: 'website',
638
+ utm_medium: 'checkout_interstitial',
639
+ utm_campaign: 'playbook_10',
640
+ plan_id: 'playbook_10',
641
+ billing_cycle: 'one_time',
642
+ },
643
+ allowCustomerEmail: true,
644
+ prefillStripeEmail: true,
645
+ },
646
+ 'playbook-999': {
647
+ fallbackHref: 'https://buy.stripe.com/8x2fZh3UgbTw19v21R3sJ11',
648
+ external: true,
649
+ botDeflectPath: '/checkout/pro',
650
+ ctaId: 'pro_checkout_playbook_999',
651
+ ctaPlacement: 'checkout_interstitial',
652
+ eventType: 'cta_click',
653
+ defaults: {
654
+ utm_source: 'website',
655
+ utm_medium: 'checkout_interstitial',
656
+ utm_campaign: 'playbook_999',
657
+ plan_id: 'playbook_999',
658
+ billing_cycle: 'one_time',
659
+ },
660
+ allowCustomerEmail: true,
661
+ prefillStripeEmail: true,
662
+ },
663
+ 'founding-100': {
664
+ fallbackHref: PRO_CHECKOUT_URL,
665
+ external: true,
666
+ botDeflectPath: '/checkout/pro',
667
+ ctaId: 'pro_checkout_founding_100',
668
+ ctaPlacement: 'checkout_interstitial',
669
+ eventType: 'pro_checkout_direct_stripe',
670
+ defaults: {
671
+ utm_source: 'website',
672
+ utm_medium: 'checkout_interstitial',
673
+ utm_campaign: 'founding_100',
674
+ plan_id: 'pro',
675
+ billing_cycle: 'annual',
676
+ },
677
+ },
572
678
  // Operator Framework offers (/operator-framework). Same-origin hop keeps
573
679
  // buy.stripe.com out of public HTML; bots are deflected to the page.
574
680
  'operator-diagnostic': {
@@ -666,6 +772,30 @@ const TRACKED_LINK_TARGETS = Object.freeze({
666
772
  plan_id: 'sprint_diagnostic',
667
773
  },
668
774
  },
775
+ 'diagnostic-499': {
776
+ path: '/diagnostic',
777
+ ctaId: 'diagnostic_499',
778
+ ctaPlacement: 'link_router',
779
+ eventType: 'diagnostic_intent_open',
780
+ defaults: {
781
+ utm_source: 'github',
782
+ utm_medium: 'link_router',
783
+ utm_campaign: 'sprint_diagnostic',
784
+ plan_id: 'sprint_diagnostic',
785
+ },
786
+ },
787
+ 'diagnostic-direct': {
788
+ path: '/diagnostic',
789
+ ctaId: 'diagnostic_direct',
790
+ ctaPlacement: 'link_router',
791
+ eventType: 'diagnostic_intent_open',
792
+ defaults: {
793
+ utm_source: 'newsletter',
794
+ utm_medium: 'link_router',
795
+ utm_campaign: 'sprint_diagnostic',
796
+ plan_id: 'sprint_diagnostic',
797
+ },
798
+ },
669
799
  'diagnostic-pay': {
670
800
  configUrlKey: 'sprintDiagnosticCheckoutUrl',
671
801
  fallbackHref: SPRINT_DIAGNOSTIC_CHECKOUT_URL,
@@ -918,10 +1048,10 @@ function computeConversionStats(events) {
918
1048
 
919
1049
  function getRequestedProjectSelection(req, parsed) {
920
1050
  const projectFromQuery = parsed && parsed.searchParams
921
- ? parsed.searchParams.get('project')
1051
+ ? parsed.searchParams.get('projectDir')
922
1052
  : null;
923
1053
  const projectFromHeaders = req && req.headers
924
- ? req.headers['x-thumbgate-project-dir'] || req.headers['x-thumbgate-project']
1054
+ ? req.headers['x-thumbgate-project-dir']
925
1055
  : null;
926
1056
  return projectFromQuery || projectFromHeaders || null;
927
1057
  }
@@ -939,6 +1069,7 @@ function isProjectSelectionAllowed(req, parsed) {
939
1069
  }
940
1070
 
941
1071
  function resolveRequestProjectDir(req, parsed) {
1072
+ if (tenantDataScope()) return tenantDataScope().feedbackDir;
942
1073
  const explicitProject = getEffectiveRequestedProjectSelection(req, parsed);
943
1074
  return resolveProjectDir({
944
1075
  projectDir: explicitProject,
@@ -964,6 +1095,7 @@ function extractEnvValue(content, names) {
964
1095
  function readProjectChatSettings(req, parsed) {
965
1096
  const settings = {
966
1097
  geminiKey: '',
1098
+ subqKey: '',
967
1099
  perplexityKey: '',
968
1100
  localEndpoint: '',
969
1101
  localModel: '',
@@ -976,6 +1108,7 @@ function readProjectChatSettings(req, parsed) {
976
1108
  const content = fs.readFileSync(envPath, 'utf8');
977
1109
  settings.geminiKey = extractEnvValue(content, ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'THUMBGATE_GEMINI_API_KEY']);
978
1110
  settings.perplexityKey = extractEnvValue(content, ['PERPLEXITY_API_KEY', 'THUMBGATE_PERPLEXITY_API_KEY']);
1111
+ settings.subqKey = extractEnvValue(content, ['SUBQ_API_KEY', 'THUMBGATE_SUBQ_API_KEY']);
979
1112
  settings.localEndpoint = extractEnvValue(content, ['THUMBGATE_LOCAL_LLM_ENDPOINT']);
980
1113
  settings.localModel = extractEnvValue(content, ['THUMBGATE_LOCAL_LLM_MODEL']);
981
1114
  }
@@ -1069,25 +1202,37 @@ function partitionFeedbackPaths(paths, dataIdentity) {
1069
1202
  });
1070
1203
  }
1071
1204
 
1205
+ function projectEvidenceForRequest(req, parsed, feedbackDir, dataIdentity) {
1206
+ const hostedEvidenceSource = Boolean(tenantDataScope() || dataIdentity?.partition || process.env.RAILWAY_PROJECT_ID || process.env.RAILWAY_ENVIRONMENT || process.env.RENDER || process.env.K_SERVICE || process.env.THUMBGATE_HOSTED === '1')
1207
+ || !isLoopbackHost(getRequestHostHeader(req)) || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket.remoteAddress) // NOSONAR: loopback peer check, not a connection target
1208
+ || Boolean(getRequestedProjectSelection(req, parsed));
1209
+ return require('../../scripts/project-evidence').localRuntimeEvidenceOptions({
1210
+ feedbackDir, sourceRoot: process.env.THUMBGATE_FEEDBACK_DIR || path.join(require('node:os').homedir(), '.thumbgate'), hosted: hostedEvidenceSource,
1211
+ });
1212
+ }
1213
+
1072
1214
  function getSafeDataDir(req, parsed) {
1073
1215
  const { FEEDBACK_LOG_PATH } = getRequestFeedbackPaths(req, parsed);
1074
1216
  return path.resolve(path.dirname(FEEDBACK_LOG_PATH));
1075
1217
  }
1076
1218
 
1077
- function findRecordById(id, feedbackDir) {
1219
+ function findRecordById(id, feedbackDir, options = {}) {
1078
1220
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
1079
1221
  const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
1080
1222
  let memoryRecord = null;
1081
1223
  let feedbackEvent = null;
1082
- const memoryRecords = readLessonJsonl(memoryLogPath, { maxLines: 0 });
1224
+ const memoryRecords = readProjectRows(feedbackDir, 'memory-log.jsonl', options);
1083
1225
  for (const rec of memoryRecords) {
1084
1226
  if (rec.id === id) { memoryRecord = rec; break; }
1085
1227
  }
1086
- const feedbackRecords = readLessonJsonl(feedbackLogPath, { maxLines: 0 });
1228
+ const feedbackRecords = readProjectRows(feedbackDir, 'feedback-log.jsonl', options);
1087
1229
  for (const rec of feedbackRecords) {
1088
1230
  if (rec.id === id) { feedbackEvent = rec; break; }
1089
1231
  }
1090
1232
  if (!memoryRecord && !feedbackEvent) return null;
1233
+ if (options.projectKey == null && new Set([...memoryRecords, ...feedbackRecords].filter((row) => row.id === id).map((row) => row.projectKey)).size > 1) {
1234
+ const error = new Error('Select a project for this lesson ID'); error.statusCode = 409; throw error;
1235
+ }
1091
1236
  return { feedbackEvent, memoryRecord };
1092
1237
  }
1093
1238
 
@@ -1100,17 +1245,17 @@ function mergeFollowUpDetail(existingDetail, followUpText) {
1100
1245
  return `${existing}\n\nFollow-up: ${next}`;
1101
1246
  }
1102
1247
 
1103
- function updateLessonRecord(feedbackDir, lessonId, updater) {
1104
- const record = findRecordById(lessonId, feedbackDir);
1248
+ function updateLessonRecord(feedbackDir, lessonId, updater, options = {}) {
1249
+ const record = findRecordById(lessonId, feedbackDir, options);
1105
1250
  if (!record) return null;
1106
1251
  const existing = { ...(record.feedbackEvent || {}), ...(record.memoryRecord || {}) };
1107
1252
  const updated = updater({ ...existing });
1108
1253
  if (!updated) return null;
1109
- const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
1110
- const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
1111
- const updatedMemory = updateLessonJsonlRecord(memoryLogPath, lessonId, updated);
1112
- const updatedFeedback = updateLessonJsonlRecord(feedbackLogPath, lessonId, updated);
1113
- if (!updatedMemory && !updatedFeedback) return null;
1254
+ const { signalPaths, accountAttribution } = require('../../scripts/project-catalog');
1255
+ const writeOptions = { ...options, projectKey: existing.projectKey, attribution: accountAttribution(feedbackDir, options) };
1256
+ let changed = false;
1257
+ for (const name of ['memory-log.jsonl', 'feedback-log.jsonl']) for (const file of signalPaths(feedbackDir, name)) changed = updateLessonJsonlRecord(file, lessonId, updated, writeOptions) || changed;
1258
+ if (!changed) return null;
1114
1259
  return updated;
1115
1260
  }
1116
1261
 
@@ -1174,7 +1319,7 @@ function getMcpSkillManifests(hostedConfig) {
1174
1319
  },
1175
1320
  {
1176
1321
  name: 'workflow-hardening-sprint',
1177
- title: 'Workflow Hardening Sprint',
1322
+ title: 'Setup Sprint',
1178
1323
  description: 'Turn one repeated agent failure into an enforced gate with proof and rollout evidence.',
1179
1324
  triggers: ['workflow hardening', 'team rollout', 'agent governance', 'approval boundary', 'audit trail'],
1180
1325
  recommendedFlow: [
@@ -1278,7 +1423,7 @@ function getMcpSkillManifests(hostedConfig) {
1278
1423
  recommendedFlow: [
1279
1424
  'Submit advertiser interest when eligible.',
1280
1425
  'Cluster high-intent conversational queries around agent governance and repeated workflow failures.',
1281
- 'Route self-serve intent to the guide and team pain to Workflow Hardening Sprint intake.',
1426
+ 'Route self-serve intent to the guide and team pain to Setup Sprint intake.',
1282
1427
  'Block unsupported ad and landing-page claims before spend scales.',
1283
1428
  ],
1284
1429
  contextUrl: buildPublicUrl(hostedConfig, '/llm-context.md'),
@@ -1312,7 +1457,7 @@ function getMcpApplications(hostedConfig) {
1312
1457
  },
1313
1458
  {
1314
1459
  name: 'workflow-sprint-intake',
1315
- title: 'Workflow Hardening Sprint Intake',
1460
+ title: 'Setup Sprint Intake',
1316
1461
  description: 'Submit a repeated agent failure for a proof-backed sprint.',
1317
1462
  url: buildPublicUrl(hostedConfig, '/#workflow-sprint-intake'),
1318
1463
  useWhen: 'Ready to convert mistakes into gates.',
@@ -1545,7 +1690,8 @@ function serializeCookie(name, value, options = {}) {
1545
1690
  const parts = [`${name}=${encodeURIComponent(String(value))}`];
1546
1691
  parts.push(`Path=${options.path || '/'}`);
1547
1692
  parts.push(`SameSite=${options.sameSite || 'Lax'}`);
1548
- if (options.maxAge) parts.push(`Max-Age=${options.maxAge}`);
1693
+ if (Number.isInteger(options.maxAge) && options.maxAge >= 0) parts.push(`Max-Age=${options.maxAge}`);
1694
+ else if (options.maxAge) parts.push(`Max-Age=${options.maxAge}`);
1549
1695
  if (options.httpOnly !== false) parts.push('HttpOnly');
1550
1696
  if (options.secure) parts.push('Secure');
1551
1697
  return parts.join('; ');
@@ -2012,6 +2158,9 @@ function resolveBillingSummaryOptionsOrRespondProblem(res, parsed, invalidTitle)
2012
2158
 
2013
2159
  async function buildLiveDashboardData(parsed, feedbackDir) {
2014
2160
  const summaryOptions = resolveBillingSummaryOptions(parsed);
2161
+ if (tenantDataScope()) {
2162
+ return { summaryOptions, data: generateDashboard(feedbackDir, { analyticsWindow: summaryOptions, billingSummary: {}, billingSource: 'tenant', humanOnly: true, authContext: { tier: 'pro' } }) };
2163
+ }
2015
2164
  // Stripe/live billing can hang longer than the authenticated deploy proof
2016
2165
  // timeout (12s). Prefer live, but fail closed to local summary so /v1/dashboard
2017
2166
  // remains usable for operational proof.
@@ -2032,8 +2181,10 @@ async function buildLiveDashboardData(parsed, feedbackDir) {
2032
2181
  }
2033
2182
  const data = generateDashboard(feedbackDir, {
2034
2183
  analyticsWindow: summaryOptions,
2184
+ projectKey: parseProjectSelection(parsed.searchParams),
2035
2185
  billingSummary,
2036
2186
  billingSource,
2187
+ humanOnly: true,
2037
2188
  authContext: { tier: 'pro' },
2038
2189
  });
2039
2190
  return { summaryOptions, data };
@@ -2051,7 +2202,7 @@ function parseNonNegativeInteger(value, fallback) {
2051
2202
  function buildLiveDashboardCacheKey(parsed, feedbackDir) {
2052
2203
  const query = new URLSearchParams(parsed.searchParams);
2053
2204
  query.sort();
2054
- return `${path.resolve(feedbackDir)}?${query.toString()}`;
2205
+ return `${dataScopeKey()}:${path.resolve(feedbackDir)}?${query.toString()}`;
2055
2206
  }
2056
2207
 
2057
2208
  async function loadCachedLiveDashboardData(parsed, feedbackDir, options = {}) {
@@ -2491,6 +2642,8 @@ async function trySendLocalDashboardChat(res, parsed, feedbackDir, prompt, suffi
2491
2642
  topic: localChat.topic,
2492
2643
  provider: 'local-data',
2493
2644
  llm: 'none',
2645
+ model: 'Deterministic local data',
2646
+ privacyRoute: 'Local, no cloud',
2494
2647
  grounded: true,
2495
2648
  });
2496
2649
  return true;
@@ -2561,6 +2714,9 @@ async function answerEnterpriseDataChat({ prompt, feedbackDir, parsed }) {
2561
2714
  evaluation: guarded.evaluation,
2562
2715
  response: guarded.response,
2563
2716
  },
2717
+ provider: 'local-data',
2718
+ model: 'Deterministic local data',
2719
+ privacyRoute: 'Local, no cloud',
2564
2720
  sources: chat.sources,
2565
2721
  };
2566
2722
  }
@@ -2786,12 +2942,33 @@ function getOauthAuthorizeParamsFromForm(form, hostedConfig) {
2786
2942
  };
2787
2943
  }
2788
2944
 
2945
+ function resolveCheckoutIntentPlanView(parsed) {
2946
+ const requestedCycle = String(parsed?.searchParams?.get('billing_cycle') || 'monthly').trim().toLowerCase();
2947
+ if (requestedCycle === 'annual') {
2948
+ return {
2949
+ title: 'Start ThumbGate Pro Annual',
2950
+ price: '$149',
2951
+ unit: '/yr',
2952
+ directHref: '/go/pro-annual?utm_source=website&utm_medium=checkout_interstitial&utm_campaign=pro_annual_149&utm_content=skip_form&cta_id=pro_checkout_direct_stripe&cta_placement=checkout_interstitial&plan_id=pro&billing_cycle=annual',
2953
+ ctaLabel: 'Pay $149/yr with Stripe →',
2954
+ };
2955
+ }
2956
+ return {
2957
+ title: 'Start ThumbGate Pro',
2958
+ price: '$19',
2959
+ unit: '/mo',
2960
+ directHref: '/go/pro-direct?utm_source=website&utm_medium=checkout_interstitial&utm_campaign=pro_upgrade&utm_content=skip_form&cta_id=pro_checkout_direct_stripe&cta_placement=checkout_interstitial',
2961
+ ctaLabel: 'Pay $19/mo with Stripe →',
2962
+ };
2963
+ }
2964
+
2789
2965
  function renderCheckoutIntentPage(prefilledEmail = '', parsed = null, options = {}) {
2790
2966
  const plausibleDomain = escapeHtmlAttribute(resolvePlausibleDataDomain({ host: 'thumbgate.ai' }));
2791
2967
  const includeHiddenAttribution = options.includeHiddenAttribution === true;
2792
2968
  const hiddenInputs = includeHiddenAttribution
2793
2969
  ? buildCheckoutHiddenAttributionInputs(parsed)
2794
2970
  : '';
2971
+ const planView = resolveCheckoutIntentPlanView(parsed);
2795
2972
  return `<!doctype html>
2796
2973
  <html lang="en">
2797
2974
  <head>
@@ -2809,8 +2986,8 @@ h1{font-size:24px;margin:0 0 8px;color:#fff}.price{font-size:32px;font-weight:70
2809
2986
  p{color:#cbd5e1;margin:8px 0}form{margin:0}
2810
2987
  input[type=email]{width:100%;box-sizing:border-box;padding:14px 16px;border:1px solid #374151;border-radius:8px;background:#111827;color:#fff;font-size:15px;margin:16px 0 0;outline:none}
2811
2988
  input[type=email]:focus{border-color:#22d3ee}input[type=email]::placeholder{color:#64748b}
2812
- button.primary{background:#22d3ee;color:#000;padding:16px;text-align:center;border-radius:8px;font-weight:700;font-size:16px;margin:10px 0;border:none;cursor:pointer;width:100%}
2813
- a{display:block;text-decoration:none}a.secondary{border:1px solid #374151;color:#cbd5e1;padding:12px;text-align:center;border-radius:8px;margin:8px 0 0;font-size:14px}
2989
+ button.primary,a.primary{box-sizing:border-box;background:#22d3ee;color:#000;padding:16px;text-align:center;border-radius:8px;font-weight:700;font-size:16px;margin:10px 0;border:none;cursor:pointer;width:100%}
2990
+ a{display:block;text-decoration:none}a.secondary,button.secondary{box-sizing:border-box;display:block;width:100%;border:1px solid #374151;color:#cbd5e1;background:transparent;padding:12px;text-align:center;border-radius:8px;margin:8px 0 0;font-size:14px;cursor:pointer}
2814
2991
  .trust,.objection-box{margin:24px 0;padding:16px;border:1px solid #1f2937;border-radius:8px;background:#0f172a}
2815
2992
  .trust-item{font-size:13px;color:#cbd5e1;padding:4px 0;display:flex;gap:8px}.trust-item::before{content:"✓";color:#22d3ee;font-weight:700}
2816
2993
  .choice-note,.email-note,.objection-note{font-size:13px;color:#94a3b8;margin-top:10px}
@@ -2824,21 +3001,24 @@ a{display:block;text-decoration:none}a.secondary{border:1px solid #374151;color:
2824
3001
  <body>
2825
3002
  <main>
2826
3003
  <div class="brand"><span class="brand-mark"></span><span>ThumbGate</span></div>
2827
- <h1>Start ThumbGate Pro</h1>
2828
- <div class="price">$19<small>/mo</small></div>
2829
- <p>The npm package runs your gates locally. <strong>Pro</strong> removes solo caps and adds personal recall, proof, exports, and adapter maintenance. Enterprise service work is qualified after intake; hosted team sync and a hosted org dashboard are not generally available.</p>
3004
+ <h1>${planView.title}</h1>
3005
+ <div class="price">${planView.price}<small>${planView.unit}</small></div>
3006
+ <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>
2830
3008
  <form action="/checkout/pro" method="POST" data-i="pro_checkout_confirmed">
2831
3009
  ${hiddenInputs}
2832
3010
  <input type="hidden" name="confirm" value="1">
2833
3011
  <input type="email" name="customer_email" value="${escapeHtmlAttribute(prefilledEmail)}" placeholder="you@company.com" autocomplete="email" required>
2834
3012
  <p class="email-note">Required so the checkout has attributable buyer intent and your receipt can be recovered.</p>
2835
- <button type="submit" class="primary">Pay $19/mo with Stripe →</button>
3013
+ <button type="submit" class="secondary">Email a receipt, then pay →</button>
2836
3014
  </form>
2837
- <a class="secondary" data-i="pro_checkout_direct_stripe" rel="nofollow" href="/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">Skip form — open Stripe checkout directly →</a>
3015
+ <p class="choice-note">If a monthly plan is not the buy, these are one-time.</p>
3016
+ <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
+ <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>
2838
3018
  <a class="secondary" data-i="workflow_sprint_intake" href="/#workflow-sprint-intake">Not sure yet? Send the workflow first</a>
2839
- <p class="choice-note">Cancel anytime. 7-day refund, no questions. Diagnostics and sprints have their own pages. Email path keeps receipts attributable; skip uses a same-origin hop that bot-deflects crawlers.</p>
2840
- <div class="objection-box" aria-label="Checkout feedback">
2841
- <strong>Not buying today?</strong>
3019
+ <p class="choice-note">Cancel anytime. 7-day refund, no questions.</p>
3020
+ <details class="objection-box" aria-label="Checkout feedback">
3021
+ <summary style="cursor:pointer;font-weight:600;color:#cbd5e1">Not buying today? Tell us what to fix (optional)</summary>
2842
3022
  <p class="objection-note">Tap one reason so we know what to fix. This does not sign you up.</p>
2843
3023
  <div class="objection-grid">
2844
3024
  <button type="button" data-reason="price_unclear">Price or scope is unclear</button>
@@ -2847,7 +3027,7 @@ ${hiddenInputs}
2847
3027
  <button type="button" data-reason="not_urgent">Not urgent right now</button>
2848
3028
  </div>
2849
3029
  <div class="feedback-saved" id="feedback-saved">Feedback saved.</div>
2850
- </div>
3030
+ </details>
2851
3031
  <div class="trust"><div class="trust-item">Personal recall and proof exports without free-tier caps</div><div class="trust-item">Adapter matrix kept current for Claude Code, Cursor, Codex, Gemini, Amp, Cline, OpenCode</div><div class="trust-item">Personal dashboard: gate stats, rule evidence, DPO export</div><div class="trust-item">Enterprise service work is qualified after intake; hosted team sync and a hosted org dashboard are not generally available</div></div>
2852
3032
  <p class="back"><a href="/">← Back to thumbgate.ai</a></p>
2853
3033
  </main>
@@ -2901,7 +3081,7 @@ ${hiddenInputs}
2901
3081
  try {
2902
3082
  var u = new URL(skipLink.href, window.location.origin);
2903
3083
  var email = emailInput ? emailInput.value.trim() : '';
2904
- if (email && email.length <= 320 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
3084
+ if (email && email.length <= 320 && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {
2905
3085
  u.searchParams.set('customer_email', email);
2906
3086
  } else {
2907
3087
  u.searchParams.delete('customer_email');
@@ -2914,6 +3094,15 @@ ${hiddenInputs}
2914
3094
  emailInput.addEventListener('change', updateSkipLink);
2915
3095
  updateSkipLink();
2916
3096
  }
3097
+ if (skipLink) {
3098
+ skipLink.addEventListener('click', function(){
3099
+ submitted = true;
3100
+ sendTelemetry('checkout_interstitial_cta_clicked', {
3101
+ ctaId: 'pro_checkout_direct_stripe',
3102
+ ctaPlacement: 'checkout_interstitial'
3103
+ });
3104
+ });
3105
+ }
2917
3106
  document.querySelector('form').addEventListener('submit', function(){
2918
3107
  submitted = true;
2919
3108
  var emailInput = document.querySelector('input[name=customer_email]');
@@ -2935,8 +3124,42 @@ ${hiddenInputs}
2935
3124
  });
2936
3125
  try { window.plausible && window.plausible('Checkout Pro Reason Not Buying', { props: { page:'/checkout/pro', reasonCode: reason } }); } catch(_) {}
2937
3126
  var saved = document.getElementById('feedback-saved');
2938
- if (saved) saved.style.display = 'block';
2939
- });
3127
+ if (saved) {
3128
+ saved.style.display = 'block';
3129
+ saved.textContent = 'Finding the best fit...';
3130
+ }
3131
+ fetch('/v1/billing/recommend-offer', {
3132
+ method: 'POST',
3133
+ headers: { 'content-type': 'application/json' },
3134
+ body: JSON.stringify({ reasonCode: reason, page: '/checkout/pro', currentPlan: pick('plan_id') || 'pro' })
3135
+ }).then(function(r){ return r.ok ? r.json() : null; }).then(function(rec){
3136
+ if (!saved || !rec || !rec.checkoutPath) return;
3137
+ saved.innerHTML = '';
3138
+ var title = document.createElement('strong');
3139
+ title.style.display = 'block';
3140
+ title.style.marginBottom = '4px';
3141
+ title.textContent = rec.headline || 'Recommended option';
3142
+ var note = document.createElement('span');
3143
+ note.style.display = 'block';
3144
+ note.style.marginBottom = '8px';
3145
+ note.textContent = rec.rationale || '';
3146
+ var cta = document.createElement('a');
3147
+ cta.href = rec.checkoutPath;
3148
+ cta.style.cssText = 'display:inline-block;padding:8px 12px;border-radius:6px;background:#22d3ee;color:#0f172a;font-weight:700;text-decoration:none;margin-right:8px';
3149
+ cta.textContent = rec.ctaLabel || 'Continue with Stripe →';
3150
+ saved.appendChild(title);
3151
+ saved.appendChild(note);
3152
+ saved.appendChild(cta);
3153
+ if (rec.proofPath) {
3154
+ var proof = document.createElement('a');
3155
+ proof.href = rec.proofPath;
3156
+ proof.style.cssText = 'color:#93c5fd;text-decoration:underline;font-size:13px';
3157
+ proof.textContent = 'Inspect live benchmark proof';
3158
+ saved.appendChild(proof);
3159
+ }
3160
+ }).catch(function(){
3161
+ if (saved) saved.textContent = 'Feedback saved.';
3162
+ });
2940
3163
  });
2941
3164
  window.addEventListener('pagehide', function(){
2942
3165
  if (!submitted && !feedbackSent) {
@@ -3067,10 +3290,27 @@ function applyTrackedLinkQueryKeys(destinationUrl, params) {
3067
3290
  }
3068
3291
  }
3069
3292
 
3293
+ function trackedLinkQueryEmail(params) {
3294
+ return normalizeCheckoutCustomerEmail(
3295
+ params.get('customer_email') || params.get('prefilled_email')
3296
+ );
3297
+ }
3298
+
3299
+ function isLiveTrackedPaymentLink(destinationUrl) {
3300
+ if (!destinationUrl) return false;
3301
+ const host = String(destinationUrl.hostname || '').toLowerCase();
3302
+ if (host !== 'buy.stripe.com' && host !== 'checkout.stripe.com') return false;
3303
+ const urlPath = String(destinationUrl.pathname || '').toLowerCase();
3304
+ if (urlPath.startsWith('/test_') || urlPath.endsWith('-test')) return false;
3305
+ const configuredStripeKey = String(process.env.STRIPE_SECRET_KEY || billingConfig.STRIPE_SECRET_KEY || '').trim();
3306
+ return /^(?:sk|rk)_live_/i.test(configuredStripeKey);
3307
+ }
3308
+
3070
3309
  function applyTrackedLinkCustomerEmail(destinationUrl, params, target) {
3071
3310
  if (!target.allowCustomerEmail) return;
3072
- const customerEmail = normalizeCheckoutCustomerEmail(params.get('customer_email'));
3311
+ const customerEmail = trackedLinkQueryEmail(params);
3073
3312
  if (!customerEmail) return;
3313
+ if (isSyntheticOrOwnerCheckoutEmail(customerEmail) && isLiveTrackedPaymentLink(destinationUrl)) return;
3074
3314
  appendQueryParam(
3075
3315
  destinationUrl,
3076
3316
  target.prefillStripeEmail ? 'prefilled_email' : 'customer_email',
@@ -3153,7 +3393,85 @@ function buildTrackedLinkAttribution(target, parsed, req, journeyState, destinat
3153
3393
  };
3154
3394
  }
3155
3395
 
3156
- function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadRequest, slug }) {
3396
+ function isSyntheticProbeQuery(parsed) {
3397
+ const probe = String(parsed?.searchParams?.get('probe') || '').trim().toLowerCase();
3398
+ return probe === '1' || probe === 'true';
3399
+ }
3400
+
3401
+ function isDirectProSessionSlug(slug) {
3402
+ return slug === 'pro-direct' || slug === 'pro-annual' || slug === 'founding-100';
3403
+ }
3404
+
3405
+ /**
3406
+ * Creates an attributable dynamic Stripe Checkout Session for human 1-click Pro
3407
+ * redirects (`/go/pro-direct`, `/go/pro-annual`, `/go/founding-100`) when live
3408
+ * Stripe credentials are present, ensuring `/success` key provisioning, `/cancel`
3409
+ * recovery downsells, promotion codes, and exact `$19/mo` vs `$149/yr` pricing.
3410
+ */
3411
+ async function tryCreateDirectProCheckoutRedirect({
3412
+ target,
3413
+ parsed,
3414
+ req,
3415
+ hostedConfig,
3416
+ journeyState,
3417
+ feedbackDir,
3418
+ }) {
3419
+ if (!isDirectProSessionSlug(target.slug) || !process.env.STRIPE_SECRET_KEY || isSyntheticProbeQuery(parsed)) {
3420
+ return null;
3421
+ }
3422
+ const requestedCycle = String(parsed.searchParams.get('billing_cycle') || '').trim().toLowerCase();
3423
+ const billingCycle = (
3424
+ target.slug === 'pro-annual'
3425
+ || target.slug === 'founding-100'
3426
+ || requestedCycle === 'annual'
3427
+ ) ? 'annual' : 'monthly';
3428
+ const customerEmail = normalizeCheckoutCustomerEmail(
3429
+ parsed.searchParams.get('customer_email') || parsed.searchParams.get('prefilled_email')
3430
+ ) || undefined;
3431
+ const traceId = createJourneyId('checkout');
3432
+ const bootstrapBody = buildCheckoutBootstrapBody(parsed, req, journeyState);
3433
+ const defaults = target.defaults || {};
3434
+ if (!parsed.searchParams.get('utm_source') && defaults.utm_source) bootstrapBody.utmSource = defaults.utm_source;
3435
+ if (!parsed.searchParams.get('utm_medium') && defaults.utm_medium) bootstrapBody.utmMedium = defaults.utm_medium;
3436
+ if (!parsed.searchParams.get('utm_campaign') && defaults.utm_campaign) bootstrapBody.utmCampaign = defaults.utm_campaign;
3437
+ if (!parsed.searchParams.get('cta_id') && target.ctaId) bootstrapBody.ctaId = target.ctaId;
3438
+ if (!parsed.searchParams.get('cta_placement') && target.ctaPlacement) bootstrapBody.ctaPlacement = target.ctaPlacement;
3439
+ bootstrapBody.planId = 'pro';
3440
+ bootstrapBody.billingCycle = billingCycle;
3441
+ const analyticsMetadata = {
3442
+ ...buildCheckoutAttributionMetadata(bootstrapBody, req, traceId),
3443
+ entryRoute: `go:${target.slug}`,
3444
+ };
3445
+ const sessionResult = await createCheckoutSession({
3446
+ successUrl: buildCheckoutFallbackUrl(buildHostedSuccessUrl(hostedConfig.appOrigin, traceId), analyticsMetadata),
3447
+ cancelUrl: buildCheckoutFallbackUrl(buildHostedCancelUrl(hostedConfig.appOrigin, traceId), analyticsMetadata),
3448
+ customerEmail,
3449
+ installId: bootstrapBody.installId,
3450
+ traceId,
3451
+ metadata: analyticsMetadata,
3452
+ appOrigin: hostedConfig.appOrigin,
3453
+ });
3454
+ if (!sessionResult || !sessionResult.url) {
3455
+ return null;
3456
+ }
3457
+ const dynamicDestinationUrl = new URL(sessionResult.url);
3458
+ const dynamicAttribution = buildTrackedLinkAttribution(target, parsed, req, journeyState, dynamicDestinationUrl);
3459
+ appendBestEffortTelemetry(
3460
+ feedbackDir,
3461
+ {
3462
+ ...dynamicAttribution,
3463
+ traceId,
3464
+ stripeSessionId: sessionResult.sessionId || null,
3465
+ planId: 'pro',
3466
+ billingCycle,
3467
+ },
3468
+ req.headers,
3469
+ `tracked_link_redirect:${target.slug}`
3470
+ );
3471
+ return sessionResult.url;
3472
+ }
3473
+
3474
+ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadRequest, slug }) {
3157
3475
  const target = getTrackedLinkTarget(slug);
3158
3476
  if (!target) {
3159
3477
  sendJson(res, 404, {
@@ -3192,9 +3510,24 @@ function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadReques
3192
3510
 
3193
3511
  const { FEEDBACK_DIR } = getFeedbackPaths();
3194
3512
  const journeyState = resolveJourneyState(req, parsed);
3195
- const botClassification = classifyRequester(req.headers);
3196
- if (target.botDeflectPath && botClassification.isBot) {
3197
- const deflectUrl = new URL(target.botDeflectPath, hostedConfig.appOrigin);
3513
+ const isProbeQuery = isSyntheticProbeQuery(parsed);
3514
+ const requesterClassification = classifyRequester(req.headers);
3515
+ let botClassification = isProbeQuery
3516
+ ? { isBot: true, reason: 'synthetic_probe_query' }
3517
+ : (requesterClassification.isBot || isHumanCheckoutNavigation(req.headers, hostedConfig.appOrigin)
3518
+ ? requesterClassification
3519
+ : { isBot: true, reason: 'no_browser_navigation' });
3520
+ if (
3521
+ target.botDeflectPath
3522
+ && !botClassification.isBot
3523
+ && !isHeadRequest
3524
+ && rapidCheckoutGuard.hit(checkoutRequesterKey(req.headers))
3525
+ ) {
3526
+ botClassification = { isBot: true, reason: 'rapid_multi_checkout' };
3527
+ }
3528
+ const deflectPath = target.botDeflectPath || (isProbeQuery && target.external ? '/checkout/pro' : null);
3529
+ if (deflectPath && botClassification.isBot) {
3530
+ const deflectUrl = new URL(deflectPath, hostedConfig.appOrigin);
3198
3531
  appendTrackedLinkQueryParams(deflectUrl, parsed, target);
3199
3532
  if (!isHeadRequest) {
3200
3533
  appendBestEffortTelemetry(
@@ -3223,7 +3556,63 @@ function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadReques
3223
3556
  res.end();
3224
3557
  return;
3225
3558
  }
3559
+ if (!isHeadRequest && isDirectProSessionSlug(target.slug) && process.env.STRIPE_SECRET_KEY) {
3560
+ try {
3561
+ const dynamicSessionUrl = await tryCreateDirectProCheckoutRedirect({
3562
+ target,
3563
+ parsed,
3564
+ req,
3565
+ hostedConfig,
3566
+ journeyState,
3567
+ feedbackDir: FEEDBACK_DIR,
3568
+ });
3569
+ if (dynamicSessionUrl) {
3570
+ res.writeHead(req.method === 'POST' ? 303 : 302, {
3571
+ ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
3572
+ 'Cache-Control': 'no-store',
3573
+ 'Referrer-Policy': 'strict-origin-when-cross-origin',
3574
+ 'X-Robots-Tag': 'noindex,nofollow',
3575
+ 'X-ThumbGate-Link-Slug': target.slug,
3576
+ Location: dynamicSessionUrl,
3577
+ });
3578
+ res.end();
3579
+ return;
3580
+ }
3581
+ } catch (err) {
3582
+ if (err && err.code === 'AUTOMATED_CHECKOUT_BLOCKED') {
3583
+ const deflectUrl = new URL(target.botDeflectPath || '/checkout/pro', hostedConfig.appOrigin);
3584
+ appendTrackedLinkQueryParams(deflectUrl, parsed, { ...target, allowCustomerEmail: false });
3585
+ res.writeHead(302, {
3586
+ ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
3587
+ 'Cache-Control': 'no-store',
3588
+ 'X-Robots-Tag': 'noindex,nofollow',
3589
+ 'X-ThumbGate-Link-Slug': target.slug,
3590
+ Location: deflectUrl.toString(),
3591
+ });
3592
+ res.end();
3593
+ return;
3594
+ }
3595
+ // Fall back cleanly to static Payment Link if dynamic session creation fails
3596
+ }
3597
+ }
3226
3598
  const destinationUrl = buildTrackedLinkDestination(target, hostedConfig, parsed);
3599
+ if (
3600
+ target.external
3601
+ && isLiveTrackedPaymentLink(destinationUrl)
3602
+ && isSyntheticOrOwnerCheckoutEmail(trackedLinkQueryEmail(parsed.searchParams))
3603
+ ) {
3604
+ const deflectUrl = new URL(target.botDeflectPath || '/checkout/pro', hostedConfig.appOrigin);
3605
+ appendTrackedLinkQueryParams(deflectUrl, parsed, { ...target, allowCustomerEmail: false });
3606
+ res.writeHead(302, {
3607
+ ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
3608
+ 'Cache-Control': 'no-store',
3609
+ 'X-Robots-Tag': 'noindex,nofollow',
3610
+ 'X-ThumbGate-Link-Slug': target.slug,
3611
+ Location: deflectUrl.toString(),
3612
+ });
3613
+ res.end();
3614
+ return;
3615
+ }
3227
3616
  const attribution = buildTrackedLinkAttribution(target, parsed, req, journeyState, destinationUrl);
3228
3617
  if (target.external) {
3229
3618
  appendQueryParam(
@@ -3326,11 +3715,22 @@ function sendText(res, statusCode, text, extraHeaders = {}, options = {}) {
3326
3715
  res.end(headOnly ? '' : text);
3327
3716
  }
3328
3717
 
3718
+ function extractOriginTrialTokens(html) {
3719
+ if (typeof html !== 'string' || !html.includes('http-equiv="origin-trial"')) return [];
3720
+ const matches = html.matchAll(/<meta\s+http-equiv="origin-trial"\s+content="([^"]+)"/gi);
3721
+ return Array.from(matches, (m) => m[1].trim()).filter(Boolean);
3722
+ }
3723
+
3329
3724
  function sendHtml(res, statusCode, html, extraHeaders = {}, options = {}) {
3330
3725
  const { headOnly = false } = options;
3726
+ const originTrialTokens = extractOriginTrialTokens(html);
3727
+ const originTrialHeader = originTrialTokens.length > 0
3728
+ ? { 'Origin-Trial': originTrialTokens.join(', ') }
3729
+ : {};
3331
3730
  res.writeHead(statusCode, {
3332
3731
  'Content-Type': 'text/html; charset=utf-8',
3333
3732
  'Content-Length': Buffer.byteLength(html),
3733
+ ...originTrialHeader,
3334
3734
  ...extraHeaders,
3335
3735
  });
3336
3736
  res.end(headOnly ? '' : html);
@@ -3343,8 +3743,9 @@ function getPublicBillingHeaders(traceId = '') {
3343
3743
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-ThumbGate-Trace-Id',
3344
3744
  'Access-Control-Expose-Headers': 'X-ThumbGate-Trace-Id',
3345
3745
  };
3346
- if (traceId) {
3347
- headers['X-ThumbGate-Trace-Id'] = traceId;
3746
+ const cleanTrace = typeof traceId === 'string' && /^[a-zA-Z0-9._:-]{1,128}$/.test(traceId.trim()) ? traceId.trim() : '';
3747
+ if (cleanTrace) {
3748
+ headers['X-ThumbGate-Trace-Id'] = cleanTrace;
3348
3749
  }
3349
3750
  return headers;
3350
3751
  }
@@ -3543,6 +3944,38 @@ function normalizePublicMarketingHtml(html, runtimeConfig, requestHost) {
3543
3944
  return output;
3544
3945
  }
3545
3946
 
3947
+ function getConfiguredSsoProviders(env = process.env) {
3948
+ return {
3949
+ google: Boolean(String((env && env.GOOGLE_CLIENT_ID) || '').trim()),
3950
+ apple: Boolean(String((env && env.APPLE_CLIENT_ID) || '').trim()),
3951
+ };
3952
+ }
3953
+
3954
+ const SSO_GOOGLE_ICON_SVG = '<svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" style="flex-shrink:0;background:#fff;border-radius:999px;padding:1px;"><path fill="#4285F4" d="M23.49 12.27c0-.79-.07-1.54-.19-2.27H12v4.51h6.47c-.29 1.48-1.14 2.73-2.4 3.58v2.98h3.88c2.27-2.09 3.54-5.17 3.54-8.8z"/><path fill="#34A853" d="M12 24c3.24 0 5.95-1.08 7.93-2.91l-3.88-2.98c-1.08.72-2.45 1.16-4.05 1.16-3.12 0-5.77-2.11-6.72-4.96H1.29v3.09C3.26 21.3 7.31 24 12 24z"/><path fill="#FBBC05" d="M5.28 14.31c-.24-.72-.38-1.49-.38-2.31s.14-1.59.38-2.31V6.6H1.29C.47 8.23 0 10.06 0 12s.47 3.77 1.29 5.4l3.99-3.09z"/><path fill="#EA4335" d="M12 4.75c1.77 0 3.35.61 4.6 1.8l3.42-3.42C17.95 1.19 15.24 0 12 0 7.31 0 3.26 2.7 1.29 6.6l3.99 3.09c.95-2.85 3.6-4.94 6.72-4.94z"/></svg>';
3955
+ const SSO_APPLE_ICON_SVG = '<svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" style="flex-shrink:0;"><path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/></svg>';
3956
+
3957
+ function buildDashboardSsoButtonsHtml(providers = getConfiguredSsoProviders()) {
3958
+ const parts = [];
3959
+ if (providers.google) {
3960
+ parts.push(`<a class="btn" id="ssoGoogleBtn" href="/v1/cloud/sso/authorize?provider=google" style="min-height:44px;min-width:44px;padding:10px 16px;font-size:13px;font-weight:700;text-decoration:none;display:flex;align-items:center;justify-content:center;gap:8px;width:100%;box-sizing:border-box;">${SSO_GOOGLE_ICON_SVG}<span>Continue with Google</span></a>`);
3961
+ }
3962
+ if (providers.apple) {
3963
+ parts.push(`<a class="btn" id="ssoAppleBtn" href="/v1/cloud/sso/authorize?provider=apple" style="min-height:44px;min-width:44px;padding:10px 16px;font-size:13px;background:#f8fafc;color:#090d16;font-weight:700;text-decoration:none;display:flex;align-items:center;justify-content:center;gap:8px;width:100%;box-sizing:border-box;">${SSO_APPLE_ICON_SVG}<span>Continue with Apple</span></a>`);
3964
+ }
3965
+ return parts.join('\n ');
3966
+ }
3967
+
3968
+ function buildLandingSsoButtonsHtml(providers = getConfiguredSsoProviders()) {
3969
+ const parts = [];
3970
+ if (providers.google) {
3971
+ parts.push(`<a href="/v1/cloud/sso/authorize?provider=google" id="googleCloudLoginLink" style="display:flex;align-items:center;justify-content:center;gap:8px;min-height:44px;min-width:44px;padding:0 16px;border-radius:8px;border:1px solid var(--cyan);background:var(--cyan);color:#041016;font:800 13px/1 inherit;text-decoration:none;width:100%;box-sizing:border-box;">${SSO_GOOGLE_ICON_SVG}<span>Continue with Google</span></a>`);
3972
+ }
3973
+ if (providers.apple) {
3974
+ parts.push(`<a href="/v1/cloud/sso/authorize?provider=apple" id="appleSsoLoginLink" style="display:flex;align-items:center;justify-content:center;gap:8px;min-height:44px;min-width:44px;padding:0 16px;border-radius:8px;border:1px solid #f8fafc;background:#f8fafc;color:#090d16;font:800 13px/1 inherit;text-decoration:none;width:100%;box-sizing:border-box;">${SSO_APPLE_ICON_SVG}<span>Continue with Apple</span></a>`);
3975
+ }
3976
+ return parts.join('\n ');
3977
+ }
3978
+
3546
3979
  function loadPublicMarketingTemplateHtml(templatePath, runtimeConfig, pageContext = {}) {
3547
3980
  const template = fs.readFileSync(templatePath, 'utf-8');
3548
3981
  const googleSiteVerificationMeta = runtimeConfig.googleSiteVerification
@@ -3589,6 +4022,7 @@ function loadPublicMarketingTemplateHtml(templatePath, runtimeConfig, pageContex
3589
4022
  '__GTM_PLAN_URL__': 'https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/GO_TO_MARKET_REVENUE_WEDGE_2026-03.md',
3590
4023
  '__GITHUB_URL__': 'https://github.com/IgorGanapolsky/ThumbGate',
3591
4024
  '__POSTHOG_API_KEY__': runtimeConfig.posthogApiKey || '',
4025
+ '<!-- __LANDING_SSO_BUTTONS__ -->': buildLandingSsoButtonsHtml(getConfiguredSsoProviders()),
3592
4026
  });
3593
4027
  const normalized = normalizePublicMarketingHtml(rendered, runtimeConfig, pageContext.requestHost);
3594
4028
  if (!privacyOptOut) return normalized;
@@ -3788,15 +4222,66 @@ window.THUMBGATE_LESSONS_BOOTSTRAP = { enabled: ${bootstrapActive ? 'true' : 'fa
3788
4222
  </html>`;
3789
4223
  }
3790
4224
 
4225
+ const SIGNED_IN_APP_NAV_MARKER_START = '<!-- __SIGNED_IN_APP_NAV_START__ -->';
4226
+ const SIGNED_IN_APP_NAV_MARKER_END = '<!-- __SIGNED_IN_APP_NAV_END__ -->';
4227
+ const GITHUB_MARK_SVG = '<svg viewBox="0 0 16 16" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z"/></svg>';
4228
+ const SIGNED_IN_APP_NAV_CSS = [
4229
+ 'nav.app-top-nav { position: sticky; top: 0; z-index: 50; background: rgba(8, 11, 16, 0.88); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); border-bottom: 1px solid rgba(39, 50, 70, 0.75); padding: 8px 0; }',
4230
+ 'nav.app-top-nav .container { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: nowrap; }',
4231
+ 'nav.app-top-nav .nav-logo { font-weight: 700; font-size: 16px; letter-spacing: -0.02em; color: #f5f7fb; text-decoration: none; display: inline-flex; align-items: center; gap: 10px; min-height: 44px; flex-shrink: 0; white-space: nowrap; }',
4232
+ 'nav.app-top-nav .nav-logo:hover { color: #ffffff; }',
4233
+ 'nav.app-top-nav .nav-logo .logo-mark { width: 28px; height: 28px; display: block; flex-shrink: 0; }',
4234
+ 'nav.app-top-nav .nav-links { display: flex; gap: 6px; align-items: center; flex-wrap: nowrap; }',
4235
+ 'nav.app-top-nav .nav-tab { color: #9ca8ba; text-decoration: none; font-size: 14px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; min-height: 44px; min-width: 44px; padding: 0 14px; border-radius: 999px; border: 1px solid transparent; transition: color 0.16s ease, background 0.16s ease, border-color 0.16s ease; white-space: nowrap; }',
4236
+ 'nav.app-top-nav .nav-tab:hover { color: #f5f7fb; background: rgba(255, 255, 255, 0.05); }',
4237
+ 'nav.app-top-nav .nav-tab.active { color: #f5f7fb; background: rgba(56, 215, 255, 0.12); border-color: rgba(56, 215, 255, 0.34); }',
4238
+ 'nav.app-top-nav .nav-github { color: #9ca8ba; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; min-width: 44px; min-height: 44px; border-radius: 999px; border: 1px solid rgba(39, 50, 70, 0.65); background: rgba(17, 22, 31, 0.55); transition: color 0.16s ease, border-color 0.16s ease, background 0.16s ease; flex-shrink: 0; }',
4239
+ 'nav.app-top-nav .nav-github:hover { color: #f5f7fb; border-color: rgba(56, 215, 255, 0.45); background: rgba(56, 215, 255, 0.1); }',
4240
+ '@media (max-width: 640px) { nav.app-top-nav .container { padding-left: 14px; padding-right: 14px; gap: 8px; } nav.app-top-nav .nav-logo { font-size: 15px; gap: 8px; } nav.app-top-nav .nav-links { gap: 4px; } nav.app-top-nav .nav-tab { font-size: 13px; padding: 0 10px; } }',
4241
+ ].join('\n');
4242
+
4243
+ function renderSignedInAppNav({ activeTab = 'dashboard' } = {}) {
4244
+ const dashboardActive = activeTab === 'dashboard';
4245
+ const lessonsActive = activeTab === 'lessons';
4246
+ return `<nav class="app-top-nav" aria-label="Primary navigation">
4247
+ <div class="container">
4248
+ <a href="/" class="nav-logo" aria-label="ThumbGate home"><img src="/assets/brand/thumbgate-mark-inline-v3.svg" alt="" class="logo-mark" width="28" height="28"><span class="logo-text">ThumbGate</span></a>
4249
+ <div class="nav-links">
4250
+ <a href="/dashboard" class="nav-tab${dashboardActive ? ' active' : ''}"${dashboardActive ? ' aria-current="page"' : ''}>Dashboard</a>
4251
+ <a href="/lessons" class="nav-tab${lessonsActive ? ' active' : ''}"${lessonsActive ? ' aria-current="page"' : ''}>Lessons</a>
4252
+ <a href="https://github.com/IgorGanapolsky/ThumbGate" class="nav-github" target="_blank" rel="noopener" aria-label="GitHub" title="GitHub">${GITHUB_MARK_SVG}</a>
4253
+ </div>
4254
+ </div>
4255
+ </nav>`;
4256
+ }
4257
+
4258
+ function injectSignedInAppNav(html, { activeTab }) {
4259
+ const start = html.indexOf(SIGNED_IN_APP_NAV_MARKER_START);
4260
+ const end = html.indexOf(SIGNED_IN_APP_NAV_MARKER_END);
4261
+ if (start === -1 || end === -1 || end < start) return html;
4262
+ return (
4263
+ html.slice(0, start) +
4264
+ SIGNED_IN_APP_NAV_MARKER_START +
4265
+ '\n' +
4266
+ renderSignedInAppNav({ activeTab }) +
4267
+ '\n' +
4268
+ html.slice(end)
4269
+ );
4270
+ }
4271
+
3791
4272
  function loadDashboardPageHtml(req, expectedApiKey) {
3792
4273
  const bootstrap = resolveLocalPageBootstrap(req, expectedApiKey);
3793
4274
  const template = readOptionalPublicTemplate(DASHBOARD_PAGE_PATH);
3794
4275
  if (!template) return renderPackagedDashboardHtml(bootstrap);
3795
4276
 
3796
- return fillTemplate(template, {
3797
- '__DASHBOARD_BOOTSTRAP_KEY__': bootstrap.serializedBootstrapKey,
3798
- '__DASHBOARD_BOOTSTRAP_ENABLED__': bootstrap.bootstrapActive ? 'true' : 'false',
3799
- });
4277
+ return injectSignedInAppNav(
4278
+ fillTemplate(template, {
4279
+ '__DASHBOARD_BOOTSTRAP_KEY__': bootstrap.serializedBootstrapKey,
4280
+ '__DASHBOARD_BOOTSTRAP_ENABLED__': bootstrap.bootstrapActive ? 'true' : 'false',
4281
+ '<!-- __DASHBOARD_SSO_BUTTONS__ -->': buildDashboardSsoButtonsHtml(getConfiguredSsoProviders()),
4282
+ }),
4283
+ { activeTab: 'dashboard' },
4284
+ );
3800
4285
  }
3801
4286
 
3802
4287
  function loadLessonsPageHtml(req, expectedApiKey) {
@@ -3804,10 +4289,13 @@ function loadLessonsPageHtml(req, expectedApiKey) {
3804
4289
  const template = readOptionalPublicTemplate(LESSONS_PAGE_PATH);
3805
4290
  if (!template) return renderPackagedLessonsHtml(bootstrap);
3806
4291
 
3807
- return fillTemplate(template, {
3808
- '__LESSONS_BOOTSTRAP_KEY__': bootstrap.serializedBootstrapKey,
3809
- '__LESSONS_BOOTSTRAP_ENABLED__': bootstrap.bootstrapActive ? 'true' : 'false',
3810
- });
4292
+ return injectSignedInAppNav(
4293
+ fillTemplate(template, {
4294
+ '__LESSONS_BOOTSTRAP_KEY__': bootstrap.serializedBootstrapKey,
4295
+ '__LESSONS_BOOTSTRAP_ENABLED__': bootstrap.bootstrapActive ? 'true' : 'false',
4296
+ }),
4297
+ { activeTab: 'lessons' },
4298
+ );
3811
4299
  }
3812
4300
 
3813
4301
  function esc(s) { return String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
@@ -4062,13 +4550,7 @@ a{color:#22d3ee;text-decoration:none}</style></head><body>
4062
4550
  }
4063
4551
  body { font-family: var(--font); background: var(--bg); color: var(--text); line-height: 1.6; -webkit-font-smoothing: antialiased; }
4064
4552
  .container { max-width: 860px; margin: 0 auto; padding: 0 24px; }
4065
- nav { position: sticky; top: 0; z-index: 50; background: rgba(10,10,11,0.85); backdrop-filter: blur(12px); border-bottom: 1px solid var(--border); padding: 14px 0; }
4066
- nav .container { display: flex; justify-content: space-between; align-items: center; }
4067
- .nav-logo { font-weight: 700; font-size: 15px; color: var(--text); text-decoration: none; display: inline-flex; align-items: center; gap: 8px; }
4068
- .nav-logo .logo-mark { width: 28px; height: 28px; display: block; }
4069
- .nav-links { display: flex; gap: 16px; align-items: center; }
4070
- .nav-links a { color: var(--text-muted); text-decoration: none; font-size: 13px; }
4071
- .nav-links a:hover { color: var(--text); }
4553
+ ${SIGNED_IN_APP_NAV_CSS}
4072
4554
  .header-card { margin: 32px 0 24px; padding: 28px; background: var(--bg-card); border: 1px solid var(--border); border-radius: 14px; }
4073
4555
  .header-top { display: flex; align-items: center; gap: 14px; margin-bottom: 12px; }
4074
4556
  .signal-badge { font-size: 40px; }
@@ -4109,14 +4591,7 @@ nav .container { display: flex; justify-content: space-between; align-items: cen
4109
4591
  <script defer data-domain="thumbgate-production.up.railway.app" src="https://plausible.io/js/script.js"></script>
4110
4592
  </head>
4111
4593
  <body>
4112
- <nav><div class="container">
4113
- <a href="/dashboard" class="nav-logo"><img src="/assets/brand/thumbgate-mark-inline-v3.svg" alt="ThumbGate" class="logo-mark" width="28" height="28"><span class="logo-text">ThumbGate</span></a>
4114
- <div class="nav-links">
4115
- <a href="/dashboard">Dashboard</a>
4116
- <a href="/lessons">Lessons</a>
4117
- <a href="/">Landing Page</a>
4118
- </div>
4119
- </div></nav>
4594
+ ${renderSignedInAppNav({ activeTab: 'lessons' })}
4120
4595
 
4121
4596
  <div class="container">
4122
4597
  <div class="header-card">
@@ -4191,7 +4666,7 @@ async function saveChanges() {
4191
4666
  var detailVal = document.getElementById('editDetail').value;
4192
4667
  if ('${signal}' === 'down') { body.whatWentWrong = detailVal; } else { body.whatWorked = detailVal; }
4193
4668
  try {
4194
- var resp = await fetch('/lessons/${encodeURIComponent(lessonId)}/update', {
4669
+ var resp = await fetch(ThumbGateProjects.url('/lessons/${encodeURIComponent(lessonId)}/update'), {
4195
4670
  method: 'POST',
4196
4671
  headers: { 'Content-Type': 'application/json' },
4197
4672
  body: JSON.stringify(body)
@@ -4206,7 +4681,7 @@ async function saveChanges() {
4206
4681
  async function deleteLesson() {
4207
4682
  if (!confirm('Delete this lesson permanently?')) return;
4208
4683
  try {
4209
- var resp = await fetch('/lessons/${encodeURIComponent(lessonId)}/delete', {
4684
+ var resp = await fetch(ThumbGateProjects.url('/lessons/${encodeURIComponent(lessonId)}/delete'), {
4210
4685
  method: 'POST',
4211
4686
  headers: { 'Content-Type': 'application/json' }
4212
4687
  });
@@ -4287,7 +4762,6 @@ function renderRobotsTxt(runtimeConfig) {
4287
4762
  function renderSitemapXml(runtimeConfig) {
4288
4763
  const entries = [
4289
4764
  { path: '/', changefreq: 'weekly', priority: '1.0' },
4290
- { path: '/pro', changefreq: 'weekly', priority: '0.9' },
4291
4765
  { path: '/diagnostic', changefreq: 'weekly', priority: '0.9' },
4292
4766
  { path: '/founders', changefreq: 'weekly', priority: '0.95' },
4293
4767
  { path: '/operator-framework', changefreq: 'weekly', priority: '0.9' },
@@ -4316,7 +4790,6 @@ function renderSitemapXml(runtimeConfig) {
4316
4790
  { path: '/eval-scorecard', changefreq: 'weekly', priority: '0.9' },
4317
4791
  { path: '/evaluations', changefreq: 'weekly', priority: '0.85' },
4318
4792
  { path: '/case-studies', changefreq: 'weekly', priority: '0.9' },
4319
- { path: '/numbers', changefreq: 'weekly', priority: '0.8' },
4320
4793
  { path: '/yt', changefreq: 'weekly', priority: '0.8' },
4321
4794
  { path: '/learn/background-agent-control-layer', changefreq: 'weekly', priority: '0.85' },
4322
4795
  { path: '/learn/ac-dc-runtime-enforcement', changefreq: 'weekly', priority: '0.85' },
@@ -4687,11 +5160,12 @@ function renderCheckoutSuccessPage(runtimeConfig) {
4687
5160
  <ol>
4688
5161
  <li>Copy the environment block below into your CI or server environment.</li>
4689
5162
  <li>Use the curl example to confirm the hosted API captures an event end-to-end.</li>
4690
- <li>Treat the key like any other API secret &mdash; rotate via your billing portal if it leaks.</li>
5163
+ <li>Treat the key like any other API secret &mdash; rotate via your <a href="/portal" id="billing-portal-link" style="color:var(--accent,#22d3ee);text-decoration:underline;">billing portal</a> if it leaks.</li>
4691
5164
  </ol>
4692
5165
  <pre id="env-block">Waiting for provisioning...</pre>
4693
5166
  <pre id="curl-block">Waiting for provisioning...</pre>
4694
5167
  <div class="actions">
5168
+ <a class="button secondary" id="manage-portal-btn" href="/portal">Manage subscription &rarr;</a>
4695
5169
  <a class="button" href="/">Back to landing page</a>
4696
5170
  <a class="button secondary" href="https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/VERIFICATION_EVIDENCE.md" target="_blank" rel="noreferrer">Verification evidence</a>
4697
5171
  </div>
@@ -4848,6 +5322,15 @@ function renderCheckoutSuccessPage(runtimeConfig) {
4848
5322
  : 'Key not available yet — refresh this page.';
4849
5323
  envBlock.textContent = body.nextSteps && body.nextSteps.env ? body.nextSteps.env : 'Environment snippet unavailable.';
4850
5324
  curlBlock.textContent = body.nextSteps && body.nextSteps.curl ? body.nextSteps.curl : 'curl snippet unavailable.';
5325
+ const portalUrl = '/portal?key=' + encodeURIComponent(body.apiKey || '') + (sessionId ? '&session_id=' + encodeURIComponent(sessionId) : '');
5326
+ const manageBtn = document.getElementById('manage-portal-btn');
5327
+ if (manageBtn) {
5328
+ manageBtn.href = portalUrl;
5329
+ }
5330
+ const portalLink = document.getElementById('billing-portal-link');
5331
+ if (portalLink) {
5332
+ portalLink.href = portalUrl;
5333
+ }
4851
5334
  } catch (err) {
4852
5335
  sendTelemetryOnce('checkout_session_lookup_failed', {
4853
5336
  failureCode: err?.message ? err.message : 'checkout_session_lookup_failed',
@@ -4869,10 +5352,16 @@ function renderCheckoutSuccessPage(runtimeConfig) {
4869
5352
  function renderCheckoutCancelledPage(runtimeConfig) {
4870
5353
  const sprintDiagnosticPriceDollars = runtimeConfig.sprintDiagnosticPriceDollars || 499;
4871
5354
  const workflowSprintPriceDollars = runtimeConfig.workflowSprintPriceDollars || 1500;
5355
+ const proDirectUrl = escapeHtmlAttribute(new URL('/go/pro-direct?utm_source=website&utm_medium=checkout_cancel_recovery&utm_campaign=pro_upgrade', runtimeConfig.appOrigin).toString());
5356
+ const playbookUrl = escapeHtmlAttribute(new URL('/go/playbook-999?utm_source=website&utm_medium=checkout_cancel_recovery&utm_campaign=playbook_999', runtimeConfig.appOrigin).toString());
5357
+ const bundle49Url = escapeHtmlAttribute(new URL('/go/bundle-49?utm_source=website&utm_medium=checkout_cancel_recovery&utm_campaign=bundle_49', runtimeConfig.appOrigin).toString());
4872
5358
  const diagnosticUrl = escapeHtmlAttribute(new URL('/diagnostic', runtimeConfig.appOrigin).toString());
4873
5359
  const workflowSprintUrl = escapeHtmlAttribute(new URL('/go/sprint', runtimeConfig.appOrigin).toString());
4874
5360
  const workflowSprintIntakeUrl = escapeHtmlAttribute(new URL('/#workflow-sprint-intake', runtimeConfig.appOrigin).toString());
4875
5361
  const recoveryOfferLinks = [
5362
+ `<a href="${playbookUrl}" data-recovery-offer="playbook_999" data-offer-price="9.99">Buy $9.99 Playbook (One-Time, No Subscription)</a>`,
5363
+ `<a href="${bundle49Url}" data-recovery-offer="bundle_49" data-offer-price="49">Buy $49 Production Bundle (One-Time Expense)</a>`,
5364
+ `<a href="${proDirectUrl}" data-recovery-offer="pro_direct" data-offer-price="19">1-Click Stripe Pro ($19/mo)</a>`,
4876
5365
  `<a id="send-workflow-first" href="${workflowSprintIntakeUrl}" data-recovery-offer="workflow_sprint_intake" data-offer-price="0">Send workflow first</a>`,
4877
5366
  `<a href="${diagnosticUrl}" data-recovery-offer="sprint_diagnostic" data-offer-price="${sprintDiagnosticPriceDollars}">Review $${sprintDiagnosticPriceDollars} diagnostic</a>`,
4878
5367
  `<a href="${workflowSprintUrl}" data-recovery-offer="workflow_sprint" data-offer-price="${workflowSprintPriceDollars}">Scope $${workflowSprintPriceDollars} sprint</a>`,
@@ -5097,6 +5586,21 @@ function renderCheckoutCancelledPage(runtimeConfig) {
5097
5586
  statusEl.textContent = selectedReason
5098
5587
  ? 'Feedback saved: ' + selectedReason.replaceAll('_', ' ') + '.'
5099
5588
  : 'Feedback saved.';
5589
+ fetch('/v1/billing/recommend-offer', {
5590
+ method: 'POST',
5591
+ headers: { 'content-type': 'application/json' },
5592
+ body: JSON.stringify({ reasonCode: selectedReason || 'unspecified', reasonText: noteEl.value || '', page: '/cancel', currentPlan: 'pro' })
5593
+ }).then(function (r) { return r.ok ? r.json() : null; }).then(function (rec) {
5594
+ if (!rec || !rec.checkoutPath) return;
5595
+ statusEl.textContent = '';
5596
+ var strong = document.createElement('strong');
5597
+ strong.textContent = rec.headline + ' — ';
5598
+ var link = document.createElement('a');
5599
+ link.href = rec.checkoutPath;
5600
+ link.textContent = rec.ctaLabel || 'Open Stripe checkout →';
5601
+ statusEl.appendChild(strong);
5602
+ statusEl.appendChild(link);
5603
+ }).catch(function () {});
5100
5604
  });
5101
5605
 
5102
5606
  document.querySelectorAll('[data-recovery-offer]').forEach(function (link) {
@@ -5126,91 +5630,170 @@ function renderCheckoutCancelledPage(runtimeConfig) {
5126
5630
  </html>`;
5127
5631
  }
5128
5632
 
5129
- function renderWorkflowSprintIntakeResultPage(runtimeConfig, { title, detail, leadId = null }) {
5130
- const safeTitle = escapeHtmlAttribute(title || 'Sprint intake received');
5131
- const safeDetail = escapeHtmlAttribute(detail || 'We have your workflow details and will review the proof path next.');
5132
- const proofPackUrl = 'https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/VERIFICATION_EVIDENCE.md';
5133
- const sprintBriefUrl = 'https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/WORKFLOW_HARDENING_SPRINT.md';
5134
- const safeLeadId = leadId ? `<p><strong>Lead ID:</strong> ${escapeHtmlAttribute(leadId)}</p>` : '';
5633
+ function renderManageSubscriptionPage(runtimeConfig = {}, { error, enteredKey } = {}) {
5634
+ const appOrigin = runtimeConfig.appOrigin || DEFAULT_PUBLIC_APP_ORIGIN;
5635
+ const safeError = error ? escapeHtml(String(error)) : '';
5636
+ const safeEnteredKey = enteredKey ? escapeHtmlAttribute(String(enteredKey)) : '';
5637
+
5135
5638
  return `<!DOCTYPE html>
5136
5639
  <html lang="en">
5137
5640
  <head>
5138
5641
  <meta charset="UTF-8" />
5139
5642
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
5140
- <title>${safeTitle}</title>
5643
+ <title>Manage Subscription — ThumbGate</title>
5141
5644
  <meta name="robots" content="noindex,nofollow" />
5142
5645
  <style>
5143
5646
  :root {
5144
- --bg: #f6f1e8;
5145
- --ink: #1d1b18;
5146
- --muted: #625a4d;
5147
- --line: #d7cfbf;
5148
- --accent: #b85c2d;
5149
- --surface: #fffdf9;
5647
+ --bg: #09090b;
5648
+ --card: #18181b;
5649
+ --ink: #f4f4f5;
5650
+ --muted: #a1a1aa;
5651
+ --line: #27272a;
5652
+ --accent: #22d3ee;
5653
+ --error-bg: #450a0a;
5654
+ --error-border: #7f1d1d;
5655
+ --error-text: #fca5a5;
5656
+ --radius: 14px;
5150
5657
  }
5151
5658
  body {
5152
5659
  margin: 0;
5153
- font-family: Georgia, 'Times New Roman', serif;
5660
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
5154
5661
  background: var(--bg);
5155
5662
  color: var(--ink);
5156
- line-height: 1.6;
5663
+ line-height: 1.5;
5157
5664
  }
5158
5665
  main {
5159
- max-width: 720px;
5666
+ max-width: 640px;
5160
5667
  margin: 0 auto;
5161
- padding: 64px 20px 80px;
5668
+ padding: 60px 20px 80px;
5669
+ }
5670
+ .brand-header {
5671
+ display: flex;
5672
+ align-items: center;
5673
+ gap: 10px;
5674
+ margin-bottom: 28px;
5675
+ text-decoration: none;
5676
+ color: var(--ink);
5677
+ font-weight: 700;
5678
+ font-size: 16px;
5679
+ }
5680
+ .brand-header .logo-mark { width: 32px; height: 32px; display: block; }
5681
+ h1 {
5682
+ font-size: clamp(28px, 5vw, 40px);
5683
+ line-height: 1.15;
5684
+ margin: 0 0 12px;
5685
+ font-weight: 800;
5686
+ letter-spacing: -0.03em;
5687
+ }
5688
+ p.lead {
5689
+ font-size: 17px;
5690
+ color: var(--muted);
5691
+ margin: 0 0 24px;
5162
5692
  }
5163
5693
  .card {
5164
- background: var(--surface);
5694
+ background: var(--card);
5165
5695
  border: 1px solid var(--line);
5166
- border-radius: 16px;
5696
+ border-radius: var(--radius);
5167
5697
  padding: 24px;
5168
- margin-top: 18px;
5698
+ margin-top: 20px;
5699
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
5700
+ }
5701
+ .error-notice {
5702
+ background: var(--error-bg);
5703
+ border: 1px solid var(--error-border);
5704
+ color: var(--error-text);
5705
+ padding: 12px 16px;
5706
+ border-radius: 10px;
5707
+ margin-bottom: 18px;
5708
+ font-size: 14px;
5709
+ }
5710
+ label {
5711
+ display: block;
5712
+ font-weight: 600;
5713
+ font-size: 14px;
5714
+ margin-bottom: 8px;
5715
+ color: var(--ink);
5716
+ }
5717
+ input[type="text"], input[type="email"] {
5718
+ width: 100%;
5719
+ box-sizing: border-box;
5720
+ padding: 12px 14px;
5721
+ background: #09090b;
5722
+ border: 1px solid var(--line);
5723
+ border-radius: 8px;
5724
+ color: var(--ink);
5725
+ font-family: 'SFMono-Regular', Consolas, monospace;
5726
+ font-size: 14px;
5727
+ margin-bottom: 16px;
5728
+ }
5729
+ input[type="text"]:focus, input[type="email"]:focus {
5730
+ outline: none;
5731
+ border-color: var(--accent);
5169
5732
  }
5170
5733
  .actions {
5171
5734
  display: flex;
5172
- flex-wrap: wrap;
5173
5735
  gap: 12px;
5174
- margin-top: 18px;
5736
+ flex-wrap: wrap;
5737
+ margin-top: 20px;
5175
5738
  }
5176
- a {
5739
+ button.button, a.button {
5177
5740
  display: inline-block;
5178
5741
  text-decoration: none;
5179
5742
  background: var(--accent);
5180
- color: white;
5181
- padding: 12px 18px;
5182
- border-radius: 10px;
5743
+ color: #09090b;
5744
+ padding: 12px 20px;
5745
+ border-radius: 8px;
5183
5746
  font-weight: 700;
5747
+ font-size: 14px;
5748
+ border: none;
5749
+ cursor: pointer;
5184
5750
  }
5185
- a.secondary {
5751
+ a.button.secondary {
5186
5752
  background: transparent;
5187
5753
  color: var(--ink);
5188
5754
  border: 1px solid var(--line);
5189
5755
  }
5756
+ .muted {
5757
+ color: var(--muted);
5758
+ font-size: 13px;
5759
+ margin-top: 14px;
5760
+ }
5190
5761
  </style>
5191
- <script defer data-domain="thumbgate-production.up.railway.app" src="https://plausible.io/js/script.js"></script>
5762
+ <link rel="icon" type="image/png" href="/thumbgate-icon.png">
5192
5763
  </head>
5193
5764
  <body>
5194
5765
  <main>
5195
- <h1>${safeTitle}</h1>
5196
- <p>${safeDetail}</p>
5766
+ <a href="/" class="brand-header">
5767
+ <img src="/assets/brand/thumbgate-mark-inline-v3.svg" alt="ThumbGate" class="logo-mark" width="32" height="32">
5768
+ <span class="logo-text">ThumbGate</span>
5769
+ </a>
5770
+ <h1>Manage Your Subscription</h1>
5771
+ <p class="lead">Open your Stripe customer portal to manage payment methods, download invoices, upgrade seats, or cancel your subscription.</p>
5772
+
5197
5773
  <div class="card">
5198
- <p>Your workflow intake is now in the sprint queue. Review the proof pack and sprint scope while we assess the rollout blocker.</p>
5199
- ${safeLeadId}
5200
- <div class="actions">
5201
- <a href="${proofPackUrl}">Review Proof Pack</a>
5202
- <a class="secondary" href="${sprintBriefUrl}">Review Sprint Brief</a>
5203
- <a class="secondary" href="${runtimeConfig.appOrigin}/#workflow-sprint-intake">Return to Context Gateway</a>
5204
- </div>
5774
+ ${safeError ? `<div class="error-notice">${safeError}</div>` : ''}
5775
+ <form method="GET" action="/portal">
5776
+ <label for="key">License Key or Checkout Session ID</label>
5777
+ <input type="text" id="key" name="key" value="${safeEnteredKey}" placeholder="tg_live_... or cs_live_..." required autofocus />
5778
+ <button type="submit" class="button">Open Stripe Customer Portal &rarr;</button>
5779
+ </form>
5780
+ <p class="muted">Need to look up your key? Check your activation email or <code>~/.thumbgate/license.json</code> on your machine.</p>
5781
+ </div>
5782
+
5783
+ <div class="actions">
5784
+ <a class="button secondary" href="/">Back to Home</a>
5785
+ <a class="button secondary" href="mailto:support@thumbgate.ai">Contact Support</a>
5205
5786
  </div>
5206
5787
  </main>
5207
5788
  </body>
5208
5789
  </html>`;
5209
5790
  }
5210
5791
 
5211
- function renderBrokerAuditIntakeResultPage(runtimeConfig, { title, detail, leadId = null }) {
5212
- const safeTitle = escapeHtmlAttribute(title || 'Broker audit request received');
5213
- const safeDetail = escapeHtmlAttribute(detail || 'Your broker lead-flow audit request is in the queue.');
5792
+ function renderWorkflowSprintIntakeResultPage(runtimeConfig, { title, detail, leadId = null }) {
5793
+ const safeTitle = escapeHtmlAttribute(title || 'Sprint intake received');
5794
+ const safeDetail = escapeHtmlAttribute(detail || 'We have your workflow details and will review the proof path next.');
5795
+ const proofPackUrl = 'https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/VERIFICATION_EVIDENCE.md';
5796
+ const sprintBriefUrl = 'https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/WORKFLOW_HARDENING_SPRINT.md';
5214
5797
  const safeLeadId = leadId ? `<p><strong>Lead ID:</strong> ${escapeHtmlAttribute(leadId)}</p>` : '';
5215
5798
  return `<!DOCTYPE html>
5216
5799
  <html lang="en">
@@ -5220,21 +5803,68 @@ function renderBrokerAuditIntakeResultPage(runtimeConfig, { title, detail, leadI
5220
5803
  <title>${safeTitle}</title>
5221
5804
  <meta name="robots" content="noindex,nofollow" />
5222
5805
  <style>
5223
- body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: #0b1220; color: #e5edf8; line-height: 1.6; }
5224
- main { max-width: 680px; margin: 0 auto; padding: 72px 20px; }
5225
- .card { border: 1px solid #26354f; border-radius: 14px; padding: 24px; background: #111a2b; }
5226
- h1 { margin: 0 0 10px; font-size: 30px; }
5227
- p { color: #b8c5d8; }
5228
- a { color: #7dd3fc; font-weight: 700; text-decoration: none; }
5806
+ :root {
5807
+ --bg: #f6f1e8;
5808
+ --ink: #1d1b18;
5809
+ --muted: #625a4d;
5810
+ --line: #d7cfbf;
5811
+ --accent: #b85c2d;
5812
+ --surface: #fffdf9;
5813
+ }
5814
+ body {
5815
+ margin: 0;
5816
+ font-family: Georgia, 'Times New Roman', serif;
5817
+ background: var(--bg);
5818
+ color: var(--ink);
5819
+ line-height: 1.6;
5820
+ }
5821
+ main {
5822
+ max-width: 720px;
5823
+ margin: 0 auto;
5824
+ padding: 64px 20px 80px;
5825
+ }
5826
+ .card {
5827
+ background: var(--surface);
5828
+ border: 1px solid var(--line);
5829
+ border-radius: 16px;
5830
+ padding: 24px;
5831
+ margin-top: 18px;
5832
+ }
5833
+ .actions {
5834
+ display: flex;
5835
+ flex-wrap: wrap;
5836
+ gap: 12px;
5837
+ margin-top: 18px;
5838
+ }
5839
+ a {
5840
+ display: inline-block;
5841
+ text-decoration: none;
5842
+ background: var(--accent);
5843
+ color: white;
5844
+ padding: 12px 18px;
5845
+ border-radius: 10px;
5846
+ font-weight: 700;
5847
+ }
5848
+ a.secondary {
5849
+ background: transparent;
5850
+ color: var(--ink);
5851
+ border: 1px solid var(--line);
5852
+ }
5229
5853
  </style>
5854
+ <script defer data-domain="thumbgate-production.up.railway.app" src="https://plausible.io/js/script.js"></script>
5230
5855
  </head>
5231
5856
  <body>
5232
5857
  <main>
5858
+ <h1>${safeTitle}</h1>
5859
+ <p>${safeDetail}</p>
5233
5860
  <div class="card">
5234
- <h1>${safeTitle}</h1>
5235
- <p>${safeDetail}</p>
5861
+ <p>Your workflow intake is now in the sprint queue. Review the proof pack and sprint scope while we assess the rollout blocker.</p>
5236
5862
  ${safeLeadId}
5237
- <p><a href="${escapeHtmlAttribute(runtimeConfig.appOrigin)}/broker-audit">Back to broker audit page</a></p>
5863
+ <div class="actions">
5864
+ <a href="${proofPackUrl}">Review Proof Pack</a>
5865
+ <a class="secondary" href="${sprintBriefUrl}">Review Sprint Brief</a>
5866
+ <a class="secondary" href="${runtimeConfig.appOrigin}/#workflow-sprint-intake">Return to Context Gateway</a>
5867
+ </div>
5238
5868
  </div>
5239
5869
  </main>
5240
5870
  </body>
@@ -5277,7 +5907,9 @@ async function parseJsonBody(req, maxBytes = 1024 * 1024) {
5277
5907
  const body = await readBodyBuffer(req, maxBytes);
5278
5908
  if (!body.length) return {};
5279
5909
  try {
5280
- return JSON.parse(body.toString('utf-8'));
5910
+ const value = JSON.parse(body.toString('utf-8'));
5911
+ parseProjectSelection(new URL(req.url, 'http://localhost').searchParams, req.headers, value);
5912
+ return value;
5281
5913
  } catch {
5282
5914
  throw createHttpError(400, 'Invalid JSON body');
5283
5915
  }
@@ -5290,14 +5922,6 @@ async function parseFormBody(req, maxBytes = 1024 * 1024) {
5290
5922
  return Object.fromEntries(params.entries());
5291
5923
  }
5292
5924
 
5293
- function normalizeLeadEmail(value) {
5294
- const email = normalizeNullableText(value);
5295
- if (!email || !/^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{1,63}$/.test(email)) {
5296
- throw createHttpError(400, 'A valid email is required');
5297
- }
5298
- return email.toLowerCase();
5299
- }
5300
-
5301
5925
  function buildIntakeAlertRateLimitKey(req, env = process.env) {
5302
5926
  const transportPeer = String(req.socket?.remoteAddress || 'unknown');
5303
5927
  const railwayRealIp = String(req.headers['x-real-ip'] || '').trim();
@@ -5311,64 +5935,6 @@ function buildIntakeAlertRateLimitKey(req, env = process.env) {
5311
5935
  return crypto.createHash('sha256').update(clientAddress).digest('hex');
5312
5936
  }
5313
5937
 
5314
- function normalizeHttpUrl(value, fieldName) {
5315
- const raw = normalizeNullableText(value);
5316
- if (!raw) throw createHttpError(400, `${fieldName} is required`);
5317
- try {
5318
- const parsedUrl = new URL(raw);
5319
- if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
5320
- throw new Error('unsupported protocol');
5321
- }
5322
- return parsedUrl.toString();
5323
- } catch {
5324
- throw createHttpError(400, `${fieldName} must be an http(s) URL`);
5325
- }
5326
- }
5327
-
5328
- function appendBrokerAuditLead(feedbackDir, payload) {
5329
- const lead = {
5330
- leadId: createTraceId('broker_audit_lead'),
5331
- status: 'new',
5332
- offer: 'broker_lead_flow_audit_free',
5333
- requestedAt: new Date().toISOString(),
5334
- contact: {
5335
- name: normalizeNullableText(payload.name),
5336
- email: normalizeLeadEmail(payload.email),
5337
- brokerage: normalizeNullableText(payload.brokerage),
5338
- website: normalizeHttpUrl(payload.website, 'website'),
5339
- },
5340
- qualification: {
5341
- suspectedLeak: normalizeNullableText(payload.suspected_leak || payload.suspectedLeak),
5342
- },
5343
- attribution: {
5344
- traceId: payload.traceId,
5345
- acquisitionId: payload.acquisitionId,
5346
- visitorId: payload.visitorId,
5347
- sessionId: payload.sessionId,
5348
- source: payload.source,
5349
- utmSource: payload.utmSource,
5350
- utmMedium: payload.utmMedium,
5351
- utmCampaign: payload.utmCampaign,
5352
- utmContent: payload.utmContent,
5353
- utmTerm: payload.utmTerm,
5354
- ctaId: payload.ctaId,
5355
- ctaPlacement: payload.ctaPlacement,
5356
- page: payload.page,
5357
- landingPath: payload.landingPath,
5358
- referrer: payload.referrer,
5359
- referrerHost: payload.referrerHost,
5360
- },
5361
- };
5362
-
5363
- if (!lead.contact.name) throw createHttpError(400, 'name is required');
5364
- if (!lead.contact.brokerage) throw createHttpError(400, 'brokerage is required');
5365
-
5366
- const leadsPath = path.join(feedbackDir, 'broker-audit-leads.jsonl');
5367
- fs.mkdirSync(path.dirname(leadsPath), { recursive: true });
5368
- fs.appendFileSync(leadsPath, `${JSON.stringify(lead)}\n`, 'utf8');
5369
- return lead;
5370
- }
5371
-
5372
5938
  function parseOptionalObject(input, name) {
5373
5939
  if (input == null) return {};
5374
5940
  if (typeof input === 'object' && !Array.isArray(input)) return input;
@@ -5434,22 +6000,900 @@ function extractBearerToken(req) {
5434
6000
  return auth.startsWith('Bearer ') ? auth.slice(7) : '';
5435
6001
  }
5436
6002
 
6003
+ const PAID_AUTH_COOKIE_NAME = 'thumbgate_auth_session';
6004
+ const PAID_AUTH_SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;
6005
+ const PAID_AUTH_MAX_SESSIONS = 4096;
6006
+ const SSO_STATE_COOKIE_NAME = 'thumbgate_sso_state';
6007
+ const paidAuthSessions = new Map();
6008
+ const GOOGLE_OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
6009
+ const GOOGLE_OAUTH_JWKS_URL = 'https://www.googleapis.com/oauth2/v3/certs';
6010
+ const GOOGLE_VALID_ISSUERS = new Set(['accounts.google.com', 'https://accounts.google.com']);
6011
+ const APPLE_OAUTH_TOKEN_URL = 'https://appleid.apple.com/auth/token';
6012
+ const APPLE_OAUTH_JWKS_URL = 'https://appleid.apple.com/auth/keys';
6013
+ const APPLE_ISSUER = 'https://appleid.apple.com';
6014
+ const APPLE_CLIENT_SECRET_TTL_SECONDS = 3600;
6015
+ const SSO_OAUTH_STATE_TTL_MS = 10 * 60 * 1000;
6016
+ const SSO_OAUTH_MAX_PENDING_STATES = 2048;
6017
+ const OIDC_JWKS_CACHE_TTL_MS = 5 * 60 * 1000;
6018
+ const ssoPendingStates = new Map();
6019
+ let googleOAuthFetch = (...args) => fetch(...args);
6020
+ let googleJwksCache = { keys: [], expiresAt: 0 };
6021
+ let appleOAuthFetch = (...args) => fetch(...args);
6022
+ let appleJwksCache = { keys: [], expiresAt: 0 };
6023
+
6024
+ function setGoogleOAuthFetchForTests(fn) {
6025
+ googleOAuthFetch = typeof fn === 'function' ? fn : ((...args) => fetch(...args));
6026
+ googleJwksCache = { keys: [], expiresAt: 0 };
6027
+ }
6028
+
6029
+ function setAppleOAuthFetchForTests(fn) {
6030
+ appleOAuthFetch = typeof fn === 'function' ? fn : ((...args) => fetch(...args));
6031
+ appleJwksCache = { keys: [], expiresAt: 0 };
6032
+ }
6033
+
6034
+ function pruneSsoPendingStates(nowMs = Date.now()) {
6035
+ for (const [token, entry] of ssoPendingStates.entries()) {
6036
+ if (!entry || entry.expiresAt <= nowMs) ssoPendingStates.delete(token);
6037
+ }
6038
+ while (ssoPendingStates.size >= SSO_OAUTH_MAX_PENDING_STATES) {
6039
+ const oldestKey = ssoPendingStates.keys().next().value;
6040
+ if (!oldestKey) break;
6041
+ ssoPendingStates.delete(oldestKey);
6042
+ }
6043
+ }
6044
+
6045
+ function issueSsoPendingState(provider, redirectUri, nowMs = Date.now()) {
6046
+ pruneSsoPendingStates(nowMs);
6047
+ const stateNonce = `st_${crypto.randomBytes(24).toString('hex')}`;
6048
+ const oidcNonce = `nc_${crypto.randomBytes(16).toString('hex')}`;
6049
+ ssoPendingStates.set(stateNonce, {
6050
+ provider,
6051
+ redirectUri,
6052
+ nonce: oidcNonce,
6053
+ createdAt: nowMs,
6054
+ expiresAt: nowMs + SSO_OAUTH_STATE_TTL_MS,
6055
+ });
6056
+ return stateNonce;
6057
+ }
6058
+
6059
+ function consumeSsoPendingState(stateNonce, expectedProvider, nowMs = Date.now()) {
6060
+ pruneSsoPendingStates(nowMs);
6061
+ const key = String(stateNonce || '').trim();
6062
+ if (!key) return null;
6063
+ const entry = ssoPendingStates.get(key);
6064
+ if (!entry) return null;
6065
+ ssoPendingStates.delete(key);
6066
+ if (entry.provider !== expectedProvider || entry.expiresAt <= nowMs) return null;
6067
+ return entry;
6068
+ }
6069
+
6070
+ function ssoError(ssoReason, message) {
6071
+ return Object.assign(new Error(message), { ssoReason });
6072
+ }
6073
+
6074
+ function redirectSsoError(res, reason, statusCode = 302) {
6075
+ const raw = String(reason || '').trim().toLowerCase();
6076
+ const safeReason = /^[a-z0-9_]{1,48}$/.test(raw) ? raw : 'sso_failed';
6077
+ res.writeHead(statusCode, { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', Location: `/dashboard?sso_error=${safeReason}` });
6078
+ res.end();
6079
+ }
6080
+
6081
+ async function loadOidcJwks(fetchFn, jwksUrl, cacheRef, nowMs = Date.now(), forceRefresh = false) {
6082
+ if (!forceRefresh && cacheRef.expiresAt > nowMs && cacheRef.keys.length > 0) return cacheRef.keys;
6083
+ const jwksRes = await fetchFn(jwksUrl, {
6084
+ method: 'GET',
6085
+ headers: { Accept: 'application/json' },
6086
+ signal: AbortSignal.timeout(8000),
6087
+ });
6088
+ if (!jwksRes || !jwksRes.ok) throw ssoError('jwks_unavailable', 'Failed to load OIDC JWKS');
6089
+ const body = await jwksRes.json();
6090
+ cacheRef.keys = Array.isArray(body?.keys) ? body.keys : [];
6091
+ cacheRef.expiresAt = nowMs + OIDC_JWKS_CACHE_TTL_MS;
6092
+ return cacheRef.keys;
6093
+ }
6094
+
6095
+ function parseJwtSegments(idToken) {
6096
+ const parts = String(idToken || '').split('.');
6097
+ if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
6098
+ throw ssoError('invalid_id_token', 'Malformed id_token');
6099
+ }
6100
+ try {
6101
+ return {
6102
+ parts,
6103
+ header: JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8')),
6104
+ payload: JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')),
6105
+ };
6106
+ } catch {
6107
+ throw ssoError('invalid_id_token', 'Unparseable id_token');
6108
+ }
6109
+ }
6110
+
6111
+ function verifyJwsWithJwk(signingInput, signatureB64Url, alg, jwk) {
6112
+ try {
6113
+ const publicKey = crypto.createPublicKey({ key: jwk, format: 'jwk' });
6114
+ const data = Buffer.from(signingInput);
6115
+ const sig = Buffer.from(signatureB64Url, 'base64url');
6116
+ if (alg === 'RS256' && jwk.kty === 'RSA') return crypto.verify('RSA-SHA256', data, publicKey, sig);
6117
+ if (alg === 'ES256' && jwk.kty === 'EC') return crypto.verify('sha256', data, { key: publicKey, dsaEncoding: 'ieee-p1363' }, sig);
6118
+ return false;
6119
+ } catch {
6120
+ return false;
6121
+ }
6122
+ }
6123
+
6124
+ async function findMatchingOidcJwk(fetchFn, jwksUrl, cacheRef, kid, expectedKty, nowMs) {
6125
+ let keys = await loadOidcJwks(fetchFn, jwksUrl, cacheRef, nowMs, false);
6126
+ let jwk = keys.find((k) => k && k.kid === kid && k.kty === expectedKty);
6127
+ if (!jwk) {
6128
+ keys = await loadOidcJwks(fetchFn, jwksUrl, cacheRef, nowMs, true);
6129
+ jwk = keys.find((k) => k && k.kid === kid && k.kty === expectedKty);
6130
+ }
6131
+ if (!jwk) throw ssoError('unknown_signing_key', 'Signing key not found');
6132
+ return jwk;
6133
+ }
6134
+
6135
+ function assertCommonIdTokenClaims(payload, expectedClientId, nowMs) {
6136
+ const aud = payload?.aud;
6137
+ const audMatches = aud === expectedClientId || (Array.isArray(aud) && aud.includes(expectedClientId));
6138
+ if (!audMatches) throw ssoError('wrong_audience', 'id_token audience mismatch');
6139
+ const expSec = Number(payload?.exp);
6140
+ if (!Number.isFinite(expSec) || expSec * 1000 <= nowMs) throw ssoError('expired_token', 'id_token expired');
6141
+ }
6142
+
6143
+ async function verifyGoogleIdToken(idToken, expectedClientId, nowMs = Date.now()) {
6144
+ const { parts, header, payload } = parseJwtSegments(idToken);
6145
+ if (!header || header.alg !== 'RS256' || typeof header.kid !== 'string' || !header.kid) {
6146
+ throw ssoError('invalid_id_token', 'Unsupported id_token header');
6147
+ }
6148
+ const jwk = await findMatchingOidcJwk(googleOAuthFetch, GOOGLE_OAUTH_JWKS_URL, googleJwksCache, header.kid, 'RSA', nowMs);
6149
+ if (!verifyJwsWithJwk(`${parts[0]}.${parts[1]}`, parts[2], 'RS256', jwk)) {
6150
+ throw ssoError('invalid_signature', 'Invalid id_token signature');
6151
+ }
6152
+ assertCommonIdTokenClaims(payload, expectedClientId, nowMs);
6153
+ if (!GOOGLE_VALID_ISSUERS.has(String(payload.iss || ''))) throw ssoError('invalid_issuer', 'id_token issuer mismatch');
6154
+ const email = String(payload.email || '').trim().toLowerCase();
6155
+ const sub = String(payload.sub || '').trim();
6156
+ const emailVerified = payload.email_verified === true || payload.email_verified === 'true';
6157
+ if (!emailVerified || !email || !sub) throw ssoError('unverified_email', 'Email not verified');
6158
+ return { sub, email };
6159
+ }
6160
+
6161
+ function readAppleOAuthEnv(env = process.env) {
6162
+ const clientId = String((env && env.APPLE_CLIENT_ID) || '').trim();
6163
+ const teamId = String((env && env.APPLE_TEAM_ID) || '').trim();
6164
+ const keyId = String((env && env.APPLE_KEY_ID) || '').trim();
6165
+ const privateKeyPem = String((env && env.APPLE_PRIVATE_KEY) || '').trim();
6166
+ if (!clientId || !teamId || !keyId || !privateKeyPem) return null;
6167
+ return { clientId, teamId, keyId, privateKeyPem };
6168
+ }
6169
+
6170
+ function normalizeApplePrivateKeyPem(privateKeyPem) {
6171
+ let raw = String(privateKeyPem || '').trim();
6172
+ if (raw.length >= 2 && ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'")))) {
6173
+ raw = raw.slice(1, -1);
6174
+ }
6175
+ return raw.replaceAll('\\n', '\n').trim();
6176
+ }
6177
+
6178
+ function buildAppleClientSecret({ clientId, teamId, keyId, privateKeyPem }, nowMs = Date.now()) {
6179
+ const pem = normalizeApplePrivateKeyPem(privateKeyPem);
6180
+ let keyObj;
6181
+ try {
6182
+ keyObj = crypto.createPrivateKey({ key: pem, format: 'pem' });
6183
+ } catch {
6184
+ throw ssoError('sso_not_configured', 'Invalid Apple private key');
6185
+ }
6186
+ if (keyObj.asymmetricKeyType !== 'ec') throw ssoError('sso_not_configured', 'Apple private key must be EC');
6187
+ const iat = Math.floor(nowMs / 1000);
6188
+ const header = Buffer.from(JSON.stringify({ alg: 'ES256', kid: keyId, typ: 'JWT' })).toString('base64url');
6189
+ const payload = Buffer.from(JSON.stringify({
6190
+ iss: teamId,
6191
+ iat,
6192
+ exp: iat + APPLE_CLIENT_SECRET_TTL_SECONDS,
6193
+ aud: APPLE_ISSUER,
6194
+ sub: clientId,
6195
+ })).toString('base64url');
6196
+ const signingInput = `${header}.${payload}`;
6197
+ const sig = crypto.sign('sha256', Buffer.from(signingInput), { key: keyObj, dsaEncoding: 'ieee-p1363' }).toString('base64url');
6198
+ return `${signingInput}.${sig}`;
6199
+ }
6200
+
6201
+ async function verifyAppleIdToken(idToken, expectedClientId, expectedNonce, nowMs = Date.now()) {
6202
+ const { parts, header, payload } = parseJwtSegments(idToken);
6203
+ const alg = header?.alg;
6204
+ if ((alg !== 'RS256' && alg !== 'ES256') || typeof header?.kid !== 'string' || !header.kid) {
6205
+ throw ssoError('invalid_id_token', 'Unsupported id_token header');
6206
+ }
6207
+ const expectedKty = alg === 'ES256' ? 'EC' : 'RSA';
6208
+ const jwk = await findMatchingOidcJwk(appleOAuthFetch, APPLE_OAUTH_JWKS_URL, appleJwksCache, header.kid, expectedKty, nowMs);
6209
+ if (!verifyJwsWithJwk(`${parts[0]}.${parts[1]}`, parts[2], alg, jwk)) {
6210
+ throw ssoError('invalid_signature', 'Invalid id_token signature');
6211
+ }
6212
+ if (String(payload?.iss || '') !== APPLE_ISSUER) throw ssoError('invalid_issuer', 'id_token issuer mismatch');
6213
+ assertCommonIdTokenClaims(payload, expectedClientId, nowMs);
6214
+ if (!expectedNonce || String(payload?.nonce || '') !== expectedNonce) {
6215
+ throw ssoError('invalid_nonce', 'id_token nonce mismatch');
6216
+ }
6217
+ const email = String(payload?.email || '').trim().toLowerCase();
6218
+ const sub = String(payload?.sub || '').trim();
6219
+ const explicitlyUnverified = payload?.email_verified === false || payload?.email_verified === 'false';
6220
+ if (explicitlyUnverified || !email || !sub) throw ssoError('unverified_email', 'Email not verified');
6221
+ return { sub, email };
6222
+ }
6223
+
6224
+ function sanitizeAppleNamePart(value) {
6225
+ let out = '';
6226
+ for (const ch of String(value || '')) {
6227
+ const code = ch.codePointAt(0) || 0;
6228
+ if (code >= 32 && code !== 127 && ch !== '<' && ch !== '>') out += ch;
6229
+ if (out.length >= 60) break;
6230
+ }
6231
+ return out.trim();
6232
+ }
6233
+
6234
+ function parseAppleFirstSignInUser(rawUser) {
6235
+ if (typeof rawUser !== 'string' || !rawUser.trim()) return null;
6236
+ try {
6237
+ const parsed = JSON.parse(rawUser);
6238
+ const first = sanitizeAppleNamePart(parsed?.name?.firstName);
6239
+ const last = sanitizeAppleNamePart(parsed?.name?.lastName);
6240
+ const name = [first, last].filter(Boolean).join(' ');
6241
+ return name ? { name } : null;
6242
+ } catch {
6243
+ return null;
6244
+ }
6245
+ }
6246
+
6247
+ function hashSessionToken(token) {
6248
+ return crypto.createHash('sha256').update(String(token || '')).digest('hex');
6249
+ }
6250
+
6251
+ function resolveAuthSessionsStorePath() {
6252
+ return withoutDataScope(() => path.join(getFeedbackPaths().FEEDBACK_DIR, 'auth-sessions.json'));
6253
+ }
6254
+
6255
+ function readPersistedAuthSessions(nowMs = Date.now()) {
6256
+ const storePath = resolveAuthSessionsStorePath();
6257
+ try {
6258
+ if (!fs.existsSync(storePath)) return {};
6259
+ const raw = JSON.parse(fs.readFileSync(storePath, 'utf8'));
6260
+ if (!raw || typeof raw !== 'object') return {};
6261
+ return Object.fromEntries(Object.entries(raw).filter(([, entry]) => entry && typeof entry === 'object' && Number(entry.expiresAt) > nowMs));
6262
+ } catch {
6263
+ return {};
6264
+ }
6265
+ }
6266
+
6267
+ function writePersistedAuthSessions(records) {
6268
+ const storePath = resolveAuthSessionsStorePath();
6269
+ try {
6270
+ fs.mkdirSync(path.dirname(storePath), { recursive: true });
6271
+ const tmpPath = `${storePath}.${process.pid}.${Date.now()}.tmp`;
6272
+ fs.writeFileSync(tmpPath, JSON.stringify(records), { mode: 0o600 });
6273
+ fs.renameSync(tmpPath, storePath);
6274
+ } catch {}
6275
+ }
6276
+
6277
+ function persistPaidAuthSession(sessionToken, entry, nowMs = Date.now()) {
6278
+ prunePaidAuthSessions(nowMs);
6279
+ paidAuthSessions.set(sessionToken, entry);
6280
+ const persisted = readPersistedAuthSessions(nowMs);
6281
+ const hashes = Object.keys(persisted);
6282
+ while (hashes.length >= PAID_AUTH_MAX_SESSIONS) delete persisted[hashes.shift()];
6283
+ persisted[hashSessionToken(sessionToken)] = {
6284
+ subjectType: entry.subjectType || 'customer',
6285
+ customerId: entry.customerId || null,
6286
+ ssoProvider: entry.ssoProvider || null,
6287
+ ssoEmail: entry.ssoEmail || null,
6288
+ ...(entry.ssoName ? { ssoName: entry.ssoName } : {}),
6289
+ createdAt: entry.createdAt,
6290
+ expiresAt: entry.expiresAt,
6291
+ };
6292
+ writePersistedAuthSessions(persisted);
6293
+ }
6294
+
6295
+ function deletePaidAuthSession(sessionToken, nowMs = Date.now()) {
6296
+ if (!sessionToken) return;
6297
+ paidAuthSessions.delete(sessionToken);
6298
+ const persisted = readPersistedAuthSessions(nowMs);
6299
+ const tokenHash = hashSessionToken(sessionToken);
6300
+ if (Object.prototype.hasOwnProperty.call(persisted, tokenHash)) {
6301
+ delete persisted[tokenHash];
6302
+ writePersistedAuthSessions(persisted);
6303
+ }
6304
+ }
6305
+
6306
+ function clearInMemoryAuthSessionsForTests() {
6307
+ paidAuthSessions.clear();
6308
+ }
6309
+
6310
+ function prunePaidAuthSessions(nowMs) {
6311
+ for (const [token, entry] of paidAuthSessions.entries()) {
6312
+ if (!entry || entry.expiresAt <= nowMs) paidAuthSessions.delete(token);
6313
+ }
6314
+ while (paidAuthSessions.size >= PAID_AUTH_MAX_SESSIONS) {
6315
+ const oldestKey = paidAuthSessions.keys().next().value;
6316
+ if (!oldestKey) break;
6317
+ paidAuthSessions.delete(oldestKey);
6318
+ }
6319
+ }
6320
+ function getPaidAuthSessionEntry(sessionToken, expectedApiKey = getExpectedApiKey(), expectedOperatorKey = getExpectedOperatorKey()) {
6321
+ if (!sessionToken) return null;
6322
+ const nowMs = Date.now();
6323
+ const inMemory = paidAuthSessions.get(sessionToken);
6324
+ if (inMemory) {
6325
+ if (inMemory.expiresAt <= nowMs) {
6326
+ deletePaidAuthSession(sessionToken, nowMs);
6327
+ return null;
6328
+ }
6329
+ return inMemory;
6330
+ }
6331
+ const persisted = readPersistedAuthSessions(nowMs);
6332
+ const record = persisted[hashSessionToken(sessionToken)];
6333
+ if (!record || record.expiresAt <= nowMs) return null;
6334
+ if (record.subjectType === 'sso_free') {
6335
+ const hydratedFree = { ...record, apiKey: '' };
6336
+ paidAuthSessions.set(sessionToken, hydratedFree);
6337
+ return hydratedFree;
6338
+ }
6339
+ const restores = {
6340
+ admin: () => expectedApiKey || '',
6341
+ operator: () => expectedOperatorKey || '',
6342
+ customer: () => (record.customerId ? (provisionApiKey(record.customerId, { source: record.ssoProvider || 'session_restore' })?.key || '') : ''),
6343
+ dev_enterprise: () => 'tg_op_dev_session',
6344
+ dev_pro: () => 'tg_dev_session',
6345
+ };
6346
+ const apiKey = restores[record.subjectType] ? restores[record.subjectType]() : '';
6347
+ if (!apiKey) return null;
6348
+ const hydrated = { ...record, apiKey };
6349
+ paidAuthSessions.set(sessionToken, hydrated);
6350
+ return hydrated;
6351
+ }
6352
+
6353
+ function resolvePaidAuthSessionKey(req) {
6354
+ const cookies = parseCookies(req && req.headers ? req.headers.cookie : '');
6355
+ const entry = getPaidAuthSessionEntry(cookies[PAID_AUTH_COOKIE_NAME]);
6356
+ return entry ? (entry.apiKey || '') : '';
6357
+ }
6358
+
6359
+ function resolvePaidSessionTier(candidate, expectedApiKey, expectedOperatorKey) {
6360
+ const key = String(candidate || '').trim();
6361
+ if (!key) return null;
6362
+ if (expectedApiKey && safeKeyEqual(key, expectedApiKey)) return 'Enterprise';
6363
+ if (expectedOperatorKey && safeKeyEqual(key, expectedOperatorKey)) return 'Enterprise';
6364
+ const validation = validateApiKey(key);
6365
+ if (validation && validation.valid === true) {
6366
+ const planLower = String(validation.plan || '').toLowerCase();
6367
+ const tierLower = String(validation.tier || '').toLowerCase();
6368
+ if (planLower === 'free' || tierLower === 'free') return 'Free';
6369
+ if (planLower === 'team' || tierLower === 'team') return 'Team';
6370
+ return tierLower === 'enterprise' ? 'Enterprise' : 'Pro';
6371
+ }
6372
+ if (!expectedApiKey && !expectedOperatorKey) {
6373
+ return key.startsWith('tg_op_') || key.startsWith('tg_creator_') ? 'Enterprise' : 'Pro';
6374
+ }
6375
+ return null;
6376
+ }
6377
+
6378
+ function parseConfiguredOwnerEmails(raw = process.env.THUMBGATE_OWNER_EMAILS) {
6379
+ return new Set(
6380
+ String(raw || '')
6381
+ .split(',')
6382
+ .map((entry) => entry.trim().toLowerCase())
6383
+ .filter(Boolean),
6384
+ );
6385
+ }
6386
+
6387
+ function isConfiguredOwnerEmail(email, env = process.env) {
6388
+ const normalized = String(email || '').trim().toLowerCase();
6389
+ if (!normalized) return false;
6390
+ return parseConfiguredOwnerEmails(env?.THUMBGATE_OWNER_EMAILS).has(normalized);
6391
+ }
6392
+
6393
+ function resolveOwnerEnterpriseSessionAuth() {
6394
+ const adminKey = getExpectedApiKey();
6395
+ if (adminKey) return { apiKey: adminKey, subjectType: 'admin' };
6396
+ const operatorKey = getExpectedOperatorKey();
6397
+ if (operatorKey) return { apiKey: operatorKey, subjectType: 'operator' };
6398
+ return { apiKey: 'tg_op_dev_session', subjectType: 'dev_enterprise' };
6399
+ }
6400
+
6401
+ async function completeSsoSessionAndRedirect(res, { provider, email, ssoName = null, redirectStatus = 302 }) {
6402
+ const isOwner = isConfiguredOwnerEmail(email);
6403
+ const entitlement = isOwner ? null : await resolvePaidEntitlementForEmail(email);
6404
+ const hasPaidKey = !isOwner && Boolean(entitlement?.entitled && entitlement?.apiKey);
6405
+ const ownerAuth = isOwner ? resolveOwnerEnterpriseSessionAuth() : null;
6406
+ let sessionApiKey = '';
6407
+ let sessionSubjectType = 'sso_free';
6408
+ if (isOwner) {
6409
+ sessionApiKey = ownerAuth.apiKey;
6410
+ sessionSubjectType = ownerAuth.subjectType;
6411
+ } else if (hasPaidKey) {
6412
+ sessionApiKey = entitlement.apiKey;
6413
+ sessionSubjectType = 'customer';
6414
+ }
6415
+ const nowMs = Date.now();
6416
+ const sessionToken = crypto.randomBytes(32).toString('hex');
6417
+ persistPaidAuthSession(sessionToken, {
6418
+ apiKey: sessionApiKey,
6419
+ subjectType: sessionSubjectType,
6420
+ customerId: hasPaidKey ? entitlement.customerId : null,
6421
+ ssoProvider: provider,
6422
+ ssoEmail: email,
6423
+ ...(ssoName ? { ssoName } : {}),
6424
+ createdAt: nowMs,
6425
+ expiresAt: nowMs + PAID_AUTH_SESSION_TTL_SECONDS * 1000,
6426
+ }, nowMs);
6427
+ if (!hasPaidKey && email) {
6428
+ Promise.resolve()
6429
+ .then(() => resendMailer.dispatchSignupWelcomeEmail({
6430
+ to: email,
6431
+ customerName: ssoName,
6432
+ source: `sso_${provider}`,
6433
+ feedbackDir: getFeedbackPaths().FEEDBACK_DIR,
6434
+ }))
6435
+ .catch(() => { /* best-effort welcome dispatch */ });
6436
+ }
6437
+ const setCookie = serializeCookie(PAID_AUTH_COOKIE_NAME, sessionToken, {
6438
+ maxAge: PAID_AUTH_SESSION_TTL_SECONDS,
6439
+ httpOnly: true,
6440
+ sameSite: 'Lax',
6441
+ secure: true,
6442
+ });
6443
+ const clearStateCookie = serializeCookie(SSO_STATE_COOKIE_NAME, '', {
6444
+ maxAge: 0,
6445
+ path: '/v1/cloud/sso',
6446
+ httpOnly: true,
6447
+ sameSite: 'Lax',
6448
+ secure: true,
6449
+ });
6450
+ res.writeHead(redirectStatus, {
6451
+ 'X-Content-Type-Options': 'nosniff',
6452
+ 'Cache-Control': 'no-store',
6453
+ 'Set-Cookie': provider === 'google' ? [setCookie, clearStateCookie] : setCookie,
6454
+ Location: '/dashboard',
6455
+ });
6456
+ res.end();
6457
+ }
6458
+
6459
+ const DEFAULT_HOSTED_OWNER_EMAILS = ['iganapolsky@gmail.com', 'igor.ganapolsky@gmail.com', 'igor@thumbgate.ai'];
6460
+
6461
+ function ensureHostedActivationsReady(baseFeedbackDir, extraOpts = {}) {
6462
+ const { backfillHostedAccountActivations } = require('../../scripts/dashboard');
6463
+ const { getOwnerEmails } = require('../../scripts/bot-detection');
6464
+ const ownerEmails = Array.from(new Set([...DEFAULT_HOSTED_OWNER_EMAILS, ...getOwnerEmails()]));
6465
+ return backfillHostedAccountActivations(baseFeedbackDir, {
6466
+ keyStore: loadKeyStore(),
6467
+ recordKeyFirstBlock: recordAccountFirstBlock,
6468
+ hashEmail: (email) => hashDataIdentity('sso_free', email),
6469
+ hashCustomerTenant: (cid) => hashDataIdentity('tenant', cid),
6470
+ ownerEmails,
6471
+ includeActivePaidKeys: true,
6472
+ ...extraOpts,
6473
+ });
6474
+ }
6475
+
6476
+ function resolveAccountSetupOptions(req, { tier, sessionEntry, expectedApiKey, expectedOperatorKey, baseFeedbackDir }) {
6477
+ const { loadAccountActivations } = require('../../scripts/dashboard');
6478
+ ensureHostedActivationsReady(baseFeedbackDir);
6479
+ const activations = loadAccountActivations(baseFeedbackDir);
6480
+ const resolvedSession = sessionEntry
6481
+ || getPaidAuthSessionEntry(parseCookies(req?.headers?.cookie || '')[PAID_AUTH_COOKIE_NAME], expectedApiKey, expectedOperatorKey);
6482
+ const token = extractApiKey(req);
6483
+ const isAdmin = Boolean(token && (
6484
+ (expectedApiKey && safeKeyEqual(token, expectedApiKey))
6485
+ || (expectedOperatorKey && safeKeyEqual(token, expectedOperatorKey))
6486
+ ));
6487
+ const validation = (!isAdmin && token) ? validateApiKey(token) : null;
6488
+ const validKey = validation && validation.valid === true ? validation : null;
6489
+ const useCookieIdentity = !isAdmin && !validKey;
6490
+ const email = String(validKey?.customerEmail || (useCookieIdentity ? resolvedSession?.ssoEmail : '') || '').trim().toLowerCase();
6491
+ const emailHash = email ? hashDataIdentity('sso_free', email) : null;
6492
+ const customerId = validKey?.customerId || (useCookieIdentity ? resolvedSession?.customerId : null) || null;
6493
+ const installId = validKey?.installId || null;
6494
+ const firstBlockAt = validKey?.firstBlockAt
6495
+ || (customerId && activations.byCustomerId[customerId]?.firstBlockAt)
6496
+ || (emailHash && activations.byEmailHash[emailHash]?.firstBlockAt)
6497
+ || (installId && activations.byInstallId[installId]?.firstBlockAt)
6498
+ || (isAdmin ? activations.adminFirstBlockAt : null)
6499
+ || null;
6500
+ const activationRecorded = Boolean(
6501
+ firstBlockAt
6502
+ || (customerId && activations.byCustomerId[customerId])
6503
+ || (emailHash && activations.byEmailHash[emailHash]),
6504
+ );
6505
+ const cliHeartbeat = Boolean(installId && activations.byInstallId[installId]);
6506
+ return { tier: tier || null, firstBlockAt, activationRecorded, cliHeartbeat, setupSignalKnown: Boolean(tier) };
6507
+ }
6508
+
6509
+ function resolveSessionSetupOverview(req, tier, sessionEntry, expectedApiKey, expectedOperatorKey) {
6510
+ if (!tier) return { firstBlockRecorded: null, firstBlockAt: null, upNext: null };
6511
+ try {
6512
+ const { computeTodayOverview } = require('../../scripts/dashboard');
6513
+ const basePaths = getFeedbackPaths();
6514
+ const scopedDir = tier === 'Free' && sessionEntry?.ssoEmail
6515
+ ? path.join(basePaths.FEEDBACK_DIR, 'tenants', hashDataIdentity('sso_free', sessionEntry.ssoEmail))
6516
+ : partitionFeedbackPaths(basePaths, resolveRequestDataIdentity(req, expectedApiKey)).FEEDBACK_DIR;
6517
+ const setupOpts = resolveAccountSetupOptions(req, { tier, sessionEntry, expectedApiKey, expectedOperatorKey, baseFeedbackDir: basePaths.FEEDBACK_DIR });
6518
+ const overview = computeTodayOverview(scopedDir, setupOpts);
6519
+ return { firstBlockRecorded: Boolean(overview.firstBlockRecorded), firstBlockAt: overview.firstBlockAt || null, upNext: overview.upNext };
6520
+ } catch (error) {
6521
+ debugApiFallback('session setup overview unavailable', error);
6522
+ return { firstBlockRecorded: null, firstBlockAt: null, upNext: null };
6523
+ }
6524
+ }
6525
+
6526
+ async function handleFirstBlockActivationRoute(req, res, expectedApiKey, expectedOperatorKey) {
6527
+ const corsHeaders = {
6528
+ 'Access-Control-Allow-Origin': '*',
6529
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
6530
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-API-Key',
6531
+ 'Cache-Control': 'no-store',
6532
+ };
6533
+ if (req.method === 'OPTIONS') {
6534
+ res.writeHead(204, corsHeaders);
6535
+ res.end();
6536
+ return;
6537
+ }
6538
+ let body = {};
6539
+ try {
6540
+ body = await parseJsonBody(req, 8 * 1024);
6541
+ } catch {
6542
+ sendJson(res, 400, { ok: false, error: 'invalid_json' }, corsHeaders);
6543
+ return;
6544
+ }
6545
+ const cookies = parseCookies(req.headers?.cookie || '');
6546
+ const sessionEntry = getPaidAuthSessionEntry(cookies[PAID_AUTH_COOKIE_NAME], expectedApiKey, expectedOperatorKey);
6547
+ const token = extractApiKey(req);
6548
+ const isAdmin = Boolean(token && expectedApiKey && safeKeyEqual(token, expectedApiKey));
6549
+ const isOperator = Boolean(!isAdmin && token && expectedOperatorKey && safeKeyEqual(token, expectedOperatorKey));
6550
+ const validation = (!isAdmin && !isOperator && token) ? validateApiKey(token) : null;
6551
+ const validKey = validation && validation.valid === true ? validation : null;
6552
+ let signedClaims = null;
6553
+ if (!isAdmin && !isOperator && !validKey && token && token.includes('.')) {
6554
+ try {
6555
+ const { verifyLicense: verifySignedEntitlement } = require('../../scripts/entitlement');
6556
+ const verified = verifySignedEntitlement(token);
6557
+ if (verified && verified.valid && verified.tier !== 'free') signedClaims = verified;
6558
+ } catch { /* ignore invalid signed license */ }
6559
+ }
6560
+ if (!isAdmin && !isOperator && !validKey && !signedClaims && !sessionEntry) {
6561
+ sendJson(res, 401, { ok: false, error: 'Unauthorized' }, corsHeaders);
6562
+ return;
6563
+ }
6564
+ const { FEEDBACK_DIR } = getFeedbackPaths();
6565
+ const { recordHostedFirstBlock } = require('../../scripts/dashboard');
6566
+ const nowMs = Date.now();
6567
+ const minValidMs = Date.parse('2025-01-01T00:00:00.000Z');
6568
+ const parsedTs = typeof body?.firstBlockAt === 'string' ? Date.parse(body.firstBlockAt) : NaN;
6569
+ const rawStamp = (Number.isFinite(parsedTs) && parsedTs >= minValidMs && parsedTs <= nowMs + 60_000)
6570
+ ? new Date(parsedTs).toISOString()
6571
+ : new Date(nowMs).toISOString();
6572
+ const rawInstall = typeof body?.installId === 'string' ? body.installId.trim() : '';
6573
+ const safeBodyInstallId = /^[A-Za-z0-9._:-]{1,128}$/.test(rawInstall) ? rawInstall : null;
6574
+ const installId = validKey?.installId || safeBodyInstallId || null;
6575
+ const useCookieTarget = !isAdmin && !isOperator && !validKey && !signedClaims;
6576
+ const targetEmail = String((isAdmin && body?.email) || validKey?.customerEmail || (useCookieTarget ? sessionEntry?.ssoEmail : '') || '').trim().toLowerCase();
6577
+ const targetCustomerId = (isAdmin && body?.customerId ? String(body.customerId).trim() : null)
6578
+ || validKey?.customerId || signedClaims?.customerId || (useCookieTarget ? sessionEntry?.customerId : null) || null;
6579
+ const emailHash = targetEmail ? hashDataIdentity('sso_free', targetEmail) : null;
6580
+ const tenantDir = targetCustomerId
6581
+ ? path.join(FEEDBACK_DIR, 'tenants', hashDataIdentity('tenant', targetCustomerId))
6582
+ : (emailHash ? path.join(FEEDBACK_DIR, 'tenants', emailHash) : null);
6583
+ const keyUpdate = recordAccountFirstBlock(
6584
+ { apiKey: validKey ? token : null, customerId: targetCustomerId, email: targetEmail },
6585
+ { firstBlockAt: rawStamp, installId: validKey ? installId : null },
6586
+ );
6587
+ const trustedInstallId = (isAdmin || isOperator || validKey) ? installId : null;
6588
+ const recorded = recordHostedFirstBlock(FEEDBACK_DIR, {
6589
+ firstBlockAt: keyUpdate.updatedCount > 0 ? keyUpdate.firstBlockAt : rawStamp,
6590
+ customerId: targetCustomerId,
6591
+ emailHash,
6592
+ installId: trustedInstallId,
6593
+ tenantDir,
6594
+ isAdmin: (isAdmin || isOperator) && !body?.customerId && !body?.email,
6595
+ source: 'cli_first_block',
6596
+ });
6597
+ let backfill = null;
6598
+ if (isAdmin && body?.backfill === true) {
6599
+ backfill = ensureHostedActivationsReady(FEEDBACK_DIR, {
6600
+ force: true,
6601
+ includeAdmin: true,
6602
+ includeActivePaidKeys: Boolean(body?.includeActivePaidKeys),
6603
+ });
6604
+ }
6605
+ if (trustedInstallId) {
6606
+ try {
6607
+ appendTelemetryPing(FEEDBACK_DIR, {
6608
+ eventType: 'first_block',
6609
+ clientType: 'cli',
6610
+ installId: trustedInstallId,
6611
+ firstBlockAt: recorded.firstBlockAt,
6612
+ ...(typeof body?.gateId === 'string' ? { gateId: body.gateId.slice(0, 120) } : {}),
6613
+ }, req.headers);
6614
+ } catch { /* telemetry best-effort */ }
6615
+ }
6616
+ liveDashboardCache.clear();
6617
+ sendJson(res, 200, {
6618
+ ok: true,
6619
+ event: 'first_block',
6620
+ firstBlockAt: recorded.firstBlockAt,
6621
+ firstBlockRecorded: true,
6622
+ ...(backfill ? { backfill } : {}),
6623
+ }, corsHeaders);
6624
+ }
6625
+
6626
+ async function handleAppleSsoCallback(req, res) {
6627
+ try {
6628
+ const form = await parseFormBody(req, 64 * 1024);
6629
+ const reqOrigin = String(req.headers.origin || '').trim().toLowerCase();
6630
+ const secFetchSite = String(req.headers['sec-fetch-site'] || '').trim().toLowerCase();
6631
+ const publicOrigin = String(getPublicOrigin(req) || '').toLowerCase();
6632
+ const isLoopbackServer = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?$/.test(publicOrigin);
6633
+ const isLoopbackOrigin = isLoopbackServer && /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?$/.test(reqOrigin);
6634
+ const allowedPostOrigins = new Set([APPLE_ISSUER, publicOrigin]);
6635
+ if (!reqOrigin || (!allowedPostOrigins.has(reqOrigin) && !isLoopbackOrigin) || (secFetchSite === 'cross-site' && reqOrigin !== APPLE_ISSUER && !isLoopbackOrigin)) {
6636
+ consumeSsoPendingState(form.state, 'apple');
6637
+ redirectSsoError(res, 'invalid_origin', 303);
6638
+ return;
6639
+ }
6640
+ if (form.error) {
6641
+ consumeSsoPendingState(form.state, 'apple');
6642
+ redirectSsoError(res, 'oauth_denied', 303);
6643
+ return;
6644
+ }
6645
+ const code = String(form.code || '').trim();
6646
+ if (!code) {
6647
+ consumeSsoPendingState(form.state, 'apple');
6648
+ redirectSsoError(res, 'missing_code', 303);
6649
+ return;
6650
+ }
6651
+ const stateEntry = consumeSsoPendingState(form.state, 'apple');
6652
+ if (!stateEntry) {
6653
+ redirectSsoError(res, 'invalid_state', 303);
6654
+ return;
6655
+ }
6656
+ const appleEnv = readAppleOAuthEnv();
6657
+ if (!appleEnv) {
6658
+ redirectSsoError(res, 'sso_not_configured', 303);
6659
+ return;
6660
+ }
6661
+ const clientSecret = buildAppleClientSecret(appleEnv);
6662
+ const tokenParams = new URLSearchParams({
6663
+ client_id: appleEnv.clientId,
6664
+ client_secret: clientSecret,
6665
+ code,
6666
+ grant_type: 'authorization_code',
6667
+ redirect_uri: stateEntry.redirectUri,
6668
+ });
6669
+ const tokenRes = await appleOAuthFetch(APPLE_OAUTH_TOKEN_URL, {
6670
+ method: 'POST',
6671
+ headers: {
6672
+ 'Content-Type': 'application/x-www-form-urlencoded',
6673
+ Accept: 'application/json',
6674
+ 'User-Agent': 'ThumbGate-SSO/1.0',
6675
+ },
6676
+ body: tokenParams.toString(),
6677
+ signal: AbortSignal.timeout(8000),
6678
+ });
6679
+ if (!tokenRes?.ok) {
6680
+ redirectSsoError(res, 'token_exchange_failed', 303);
6681
+ return;
6682
+ }
6683
+ const tokenBody = await tokenRes.json();
6684
+ const idToken = String(tokenBody?.id_token || '').trim();
6685
+ if (!idToken) {
6686
+ redirectSsoError(res, 'missing_id_token', 303);
6687
+ return;
6688
+ }
6689
+ const claims = await verifyAppleIdToken(idToken, appleEnv.clientId, stateEntry.nonce);
6690
+ const firstSignInUser = parseAppleFirstSignInUser(form.user);
6691
+ await completeSsoSessionAndRedirect(res, {
6692
+ provider: 'apple',
6693
+ email: claims.email,
6694
+ ssoName: firstSignInUser?.name || null,
6695
+ redirectStatus: 303,
6696
+ });
6697
+ } catch (err) {
6698
+ redirectSsoError(res, err?.ssoReason || 'callback_failed', 303);
6699
+ }
6700
+ }
6701
+
6702
+
6703
+ async function handlePaidAuthSessionRoute(req, res, expectedApiKey, expectedOperatorKey) {
6704
+ const noStoreHeaders = { 'Cache-Control': 'no-store' };
6705
+ if (req.method === 'GET') {
6706
+ const cookies = parseCookies(req && req.headers ? req.headers.cookie : '');
6707
+ const sessionEntry = getPaidAuthSessionEntry(cookies[PAID_AUTH_COOKIE_NAME], expectedApiKey, expectedOperatorKey);
6708
+ const tier = resolvePaidSessionTier(extractApiKey(req), expectedApiKey, expectedOperatorKey)
6709
+ || (sessionEntry && sessionEntry.subjectType === 'sso_free' ? 'Free' : null);
6710
+ const { firstBlockRecorded, firstBlockAt, upNext } = resolveSessionSetupOverview(req, tier, sessionEntry, expectedApiKey, expectedOperatorKey);
6711
+ sendJson(res, 200, {
6712
+ ok: true,
6713
+ authenticated: Boolean(tier),
6714
+ tier: tier || null,
6715
+ firstBlockRecorded,
6716
+ firstBlockAt,
6717
+ upNext,
6718
+ ssoProviders: getConfiguredSsoProviders(),
6719
+ ssoProvider: sessionEntry?.ssoProvider || null,
6720
+ ssoEmail: sessionEntry?.ssoEmail || null,
6721
+ }, noStoreHeaders);
6722
+ return;
6723
+ }
6724
+ if (req.method === 'DELETE') {
6725
+ const cookies = parseCookies(req.headers.cookie);
6726
+ if (cookies[PAID_AUTH_COOKIE_NAME]) {
6727
+ deletePaidAuthSession(cookies[PAID_AUTH_COOKIE_NAME]);
6728
+ }
6729
+ const clearCookie = serializeCookie(PAID_AUTH_COOKIE_NAME, '', {
6730
+ maxAge: 0,
6731
+ httpOnly: true,
6732
+ sameSite: 'Lax',
6733
+ secure: true,
6734
+ });
6735
+ sendJson(res, 200, { ok: true, authenticated: false }, { ...noStoreHeaders, 'Set-Cookie': clearCookie });
6736
+ return;
6737
+ }
6738
+ if (req.method === 'POST') {
6739
+ let body = {};
6740
+ try {
6741
+ body = await parseJsonBody(req);
6742
+ } catch {
6743
+ sendJson(res, 400, { ok: false, authenticated: false, error: 'Invalid JSON request body' }, noStoreHeaders);
6744
+ return;
6745
+ }
6746
+ const candidate = extractBearerToken(req) || String((body && body.apiKey) || '').trim();
6747
+ const tier = resolvePaidSessionTier(candidate, expectedApiKey, expectedOperatorKey);
6748
+ if (!tier) {
6749
+ sendJson(res, 401, { ok: false, authenticated: false, error: 'Invalid API key' }, noStoreHeaders);
6750
+ return;
6751
+ }
6752
+ let subjectType = 'dev_pro';
6753
+ let customerId = null;
6754
+ if (expectedApiKey && safeKeyEqual(candidate, expectedApiKey)) {
6755
+ subjectType = 'admin';
6756
+ } else if (expectedOperatorKey && safeKeyEqual(candidate, expectedOperatorKey)) {
6757
+ subjectType = 'operator';
6758
+ } else {
6759
+ const validation = validateApiKey(candidate);
6760
+ if (validation && validation.valid === true && validation.customerId) {
6761
+ subjectType = 'customer';
6762
+ customerId = validation.customerId;
6763
+ } else if (tier === 'Enterprise') {
6764
+ subjectType = 'dev_enterprise';
6765
+ }
6766
+ }
6767
+ const nowMs = Date.now();
6768
+ const sessionToken = crypto.randomBytes(32).toString('hex');
6769
+ persistPaidAuthSession(sessionToken, {
6770
+ apiKey: candidate,
6771
+ subjectType,
6772
+ customerId,
6773
+ createdAt: nowMs,
6774
+ expiresAt: nowMs + PAID_AUTH_SESSION_TTL_SECONDS * 1000,
6775
+ }, nowMs);
6776
+ const setCookie = serializeCookie(PAID_AUTH_COOKIE_NAME, sessionToken, {
6777
+ maxAge: PAID_AUTH_SESSION_TTL_SECONDS,
6778
+ httpOnly: true,
6779
+ sameSite: 'Lax',
6780
+ secure: true,
6781
+ });
6782
+ sendJson(res, 200, { ok: true, authenticated: true, tier }, { ...noStoreHeaders, 'Set-Cookie': setCookie });
6783
+ return;
6784
+ }
6785
+ sendJson(res, 405, { ok: false, error: 'Method Not Allowed' }, noStoreHeaders);
6786
+ }
6787
+
6788
+ const DEFAULT_ONBOARDING_GATES_PATH = path.join(__dirname, '../../config/gates/default.json');
6789
+ const ONBOARDING_CORS_HEADERS = { 'Access-Control-Allow-Origin': '*' };
6790
+
6791
+ function resolveOnboardingSignupMs(body, sessionToken, expectedApiKey, expectedOperatorKey) {
6792
+ const rawTs = typeof body?.signupTimestamp === 'number' ? body.signupTimestamp : Date.parse(String(body?.signupTimestamp || ''));
6793
+ if (Number.isFinite(rawTs) && rawTs > 0) return Math.max(0, Date.now() - rawTs);
6794
+ if (!sessionToken) return null;
6795
+ const entry = getPaidAuthSessionEntry(sessionToken, expectedApiKey, expectedOperatorKey);
6796
+ const created = typeof entry?.createdAt === 'number' ? entry.createdAt : Date.parse(String(entry?.createdAt || ''));
6797
+ return Number.isFinite(created) && created > 0 ? Math.max(0, Date.now() - created) : null;
6798
+ }
6799
+
6800
+ function recordOnboardingFirstBlockPing(req, gateId, latencyMs, signupToFirstBlockMs, elapsedSinceOpenMs, sessionToken) {
6801
+ const { FEEDBACK_DIR } = getFeedbackPaths();
6802
+ const bd = require('../../scripts/bot-detection');
6803
+ const ua = String(req.headers?.['user-agent'] || '').slice(0, 160);
6804
+ const cls = bd.classifyVisitor({ headers: { 'user-agent': ua } });
6805
+ const ip = String(req.headers?.['x-forwarded-for'] || req.socket?.remoteAddress || 'ip').split(',')[0].trim().slice(0, 64);
6806
+ const key = sessionToken ? `sess_${hashSessionToken(sessionToken).slice(0, 24)}` : `${ip}_${ua}`;
6807
+ if (!global.__onboardingFirstBlockSeen) global.__onboardingFirstBlockSeen = new Set();
6808
+ if (global.__onboardingFirstBlockSeen.has(key)) return;
6809
+ if (global.__onboardingFirstBlockSeen.size >= 4096) {
6810
+ global.__onboardingFirstBlockSeen.delete(global.__onboardingFirstBlockSeen.values().next().value);
6811
+ }
6812
+ global.__onboardingFirstBlockSeen.add(key);
6813
+ const durationMs = signupToFirstBlockMs ?? elapsedSinceOpenMs;
6814
+ appendTelemetryPing(FEEDBACK_DIR, {
6815
+ eventType: 'first_blocked_tool_call',
6816
+ source: 'dashboard_onboarding_sandbox',
6817
+ gateId: gateId || 'unknown',
6818
+ latencyMs,
6819
+ signupToFirstBlockMs,
6820
+ minutesToFirstBlock: durationMs === null ? null : Math.round((durationMs / 60000) * 10) / 10,
6821
+ elapsedSinceOpenMs,
6822
+ visitorType: cls.type,
6823
+ }, req.headers);
6824
+ delete global._metricsRealCache;
6825
+ }
6826
+
6827
+ async function handleOnboardingTryBlock(req, res, expectedApiKey, expectedOperatorKey) {
6828
+ if (req.method === 'OPTIONS') {
6829
+ res.writeHead(204, { ...ONBOARDING_CORS_HEADERS, 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' });
6830
+ res.end();
6831
+ return;
6832
+ }
6833
+ const startTime = Date.now();
6834
+ let body;
6835
+ try {
6836
+ body = await parseJsonBody(req, 8 * 1024);
6837
+ } catch { /* malformed json */
6838
+ sendJson(res, 400, { error: 'invalid_json', message: 'Malformed JSON payload' }, ONBOARDING_CORS_HEADERS);
6839
+ return;
6840
+ }
6841
+ const command = typeof body?.command === 'string' ? body.command.trim() : '';
6842
+ if (!command || command.length > 2048) {
6843
+ const code = command ? 'command_too_long' : 'missing_command';
6844
+ sendJson(res, 400, { error: code, message: command ? 'Command exceeds 2048 characters' : 'Command is required' }, ONBOARDING_CORS_HEADERS);
6845
+ return;
6846
+ }
6847
+ let gateResult = null;
6848
+ const prevSandbox = process.env.THUMBGATE_SANDBOX_EVAL;
6849
+ process.env.THUMBGATE_SANDBOX_EVAL = '1';
6850
+ try {
6851
+ gateResult = evaluateGates('Bash', { command }, DEFAULT_ONBOARDING_GATES_PATH);
6852
+ } catch { /* fallback to allow on internal error */
6853
+ gateResult = null;
6854
+ } finally {
6855
+ if (prevSandbox === undefined) delete process.env.THUMBGATE_SANDBOX_EVAL;
6856
+ else process.env.THUMBGATE_SANDBOX_EVAL = prevSandbox;
6857
+ }
6858
+ const latencyMs = Math.max(1, Date.now() - startTime);
6859
+ const isBlocked = gateResult?.decision === 'deny' || gateResult?.decision === 'block';
6860
+ const sessionToken = req.headers?.cookie ? (parseCookies(req.headers.cookie)[PAID_AUTH_COOKIE_NAME] || '') : '';
6861
+ const signupToFirstBlockMs = resolveOnboardingSignupMs(body, sessionToken, expectedApiKey, expectedOperatorKey);
6862
+ const elapsedSinceOpenMs = typeof body?.elapsedSinceOpenMs === 'number' && Number.isFinite(body.elapsedSinceOpenMs) && body.elapsedSinceOpenMs >= 0
6863
+ ? Math.min(Math.trunc(body.elapsedSinceOpenMs), 86_400_000)
6864
+ : null;
6865
+ if (isBlocked) {
6866
+ try {
6867
+ recordOnboardingFirstBlockPing(req, gateResult?.gate, latencyMs, signupToFirstBlockMs, elapsedSinceOpenMs, sessionToken);
6868
+ } catch { /* telemetry best-effort */ }
6869
+ }
6870
+ const fallbackMsg = isBlocked ? 'Blocked by ThumbGate policy.' : 'Command permitted. No dangerous patterns detected.';
6871
+ sendJson(res, 200, {
6872
+ ok: true,
6873
+ decision: isBlocked ? 'block' : 'allow',
6874
+ gateId: gateResult?.gate || null,
6875
+ message: gateResult?.message || fallbackMsg,
6876
+ latencyMs,
6877
+ elapsedSinceOpenMs,
6878
+ signupToFirstBlockMs,
6879
+ }, ONBOARDING_CORS_HEADERS);
6880
+ }
6881
+
5437
6882
  function extractApiKey(req) {
5438
6883
  const bearerToken = extractBearerToken(req);
5439
6884
  if (bearerToken) {
5440
6885
  return bearerToken;
5441
6886
  }
5442
6887
 
5443
- const alternateHeader = req.headers['x-api-key'];
6888
+ const alternateHeader = req.headers['x-api-key'] || req.headers['x-thumbgate-key'];
5444
6889
  if (Array.isArray(alternateHeader)) {
5445
- return String(alternateHeader[0] || '').trim();
5446
- }
5447
-
5448
- if (typeof alternateHeader === 'string') {
6890
+ const first = String(alternateHeader[0] || '').trim();
6891
+ if (first) return first;
6892
+ } else if (typeof alternateHeader === 'string' && alternateHeader.trim()) {
5449
6893
  return alternateHeader.trim();
5450
6894
  }
5451
6895
 
5452
- return '';
6896
+ return resolvePaidAuthSessionKey(req);
5453
6897
  }
5454
6898
 
5455
6899
  /**
@@ -5536,10 +6980,13 @@ function isBillingSummaryAuthorized(req, expectedAdminKey, expectedOperatorKey)
5536
6980
  /** Read-only paths the operator key may access (CLI dashboard / CFO / north-star). */
5537
6981
  const OPERATOR_READONLY_GET_PATHS = new Set([
5538
6982
  '/v1/billing/summary',
6983
+ '/v1/analytics/funnel',
5539
6984
  '/v1/dashboard',
5540
6985
  '/v1/dashboard/render-spec',
5541
6986
  '/v1/dashboard/ai-inventory',
5542
6987
  '/v1/dashboard/review-state',
6988
+ '/v1/dashboard/agent-register',
6989
+ '/v1/feedback/stats',
5543
6990
  '/v1/intake/workflow-sprint/queue',
5544
6991
  '/v1/task-outcomes/monitor',
5545
6992
  ]);
@@ -5562,8 +7009,8 @@ function extractTags(input) {
5562
7009
  }
5563
7010
 
5564
7011
  function resolveSafePath(inputPath, { mustExist = false, safeDataDir } = {}) {
5565
- const allowExternal = process.env.THUMBGATE_ALLOW_EXTERNAL_PATHS === 'true';
5566
- const resolved = path.resolve(String(inputPath || ''));
7012
+ const allowExternal = !tenantDataScope() && process.env.THUMBGATE_ALLOW_EXTERNAL_PATHS === 'true';
7013
+ const resolved = assertScopedDataPath(path.resolve(String(inputPath || '')));
5567
7014
  const SAFE_DATA_DIR = safeDataDir || getSafeDataDir();
5568
7015
  const inSafeRoot = resolved === SAFE_DATA_DIR || resolved.startsWith(`${SAFE_DATA_DIR}${path.sep}`);
5569
7016
 
@@ -5698,17 +7145,113 @@ function resolveDocumentImportFilePath(inputPath, options = {}) {
5698
7145
  return resolved;
5699
7146
  }
5700
7147
 
5701
- function createApiServer() {
7148
+ const CONTINUE_DATA_SCOPE = Symbol('trustedDataScopeContinuation');
7149
+
7150
+ function createApiServer({ ownerAdminDependencies = {} } = {}) {
7151
+ const server = withoutDataScope(() => createUnscopedApiServer({ ownerAdminDependencies }));
7152
+ const [listener] = server.listeners('request');
7153
+ server.removeListener('request', listener);
7154
+ server.on('request', (req, res) => {
7155
+ req[CONTINUE_DATA_SCOPE] = (scope) => withDataScope(scope, () => listener(req, res));
7156
+ return withoutDataScope(() => listener(req, res));
7157
+ });
7158
+ return server;
7159
+ }
7160
+
7161
+ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
5702
7162
  const expectedApiKey = getExpectedApiKey();
5703
7163
  const expectedOperatorKey = getExpectedOperatorKey();
5704
7164
  const humanReviewerConfig = getHumanReviewerConfig(expectedApiKey, expectedOperatorKey);
5705
7165
 
7166
+ const adminRuntime = ownerAdmin.createRuntimeObservations();
7167
+ const observedRequests = new WeakSet();
5706
7168
  const eventBus = new EventEmitter();
5707
7169
  eventBus.setMaxListeners(200);
7170
+ const publishEvent = (payload) => eventBus.emit('broadcast', { scopeKey: dataScopeKey(), payload });
5708
7171
 
5709
7172
  return http.createServer(async (req, res) => {
5710
7173
  const parsed = new URL(req.url, 'http://localhost');
5711
7174
  const pathname = parsed.pathname;
7175
+ const privatePath = ownerAdmin.adminPath(pathname);
7176
+ const category = privatePath.matched ? 'admin' : pathname === '/v1/telemetry/ping' ? 'telemetry'
7177
+ : pathname === '/health' ? 'health' : pathname.startsWith('/v1/') ? 'api' : 'page';
7178
+ if (!observedRequests.has(req)) {
7179
+ observedRequests.add(req);
7180
+ res.once('finish', () => adminRuntime.recordResponse(res.statusCode, category));
7181
+ }
7182
+ if (privatePath.matched) {
7183
+ const headers = ownerAdmin.PRIVATE_HEADERS;
7184
+ const respond = (status, payload) => {
7185
+ res.writeHead(status, { ...headers, 'Content-Type': 'application/json; charset=utf-8' });
7186
+ res.end(req.method === 'HEAD' ? undefined : JSON.stringify(payload));
7187
+ };
7188
+ const feedbackDir = withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR);
7189
+ 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; }
7192
+ let route;
7193
+ try { route = ownerAdmin.parseAdminRoute(privatePath.pathname, parsed.searchParams); }
7194
+ catch { respond(400, { error: 'Invalid query' }); return; }
7195
+ if (!route) { respond(404, { error: 'Not found' }); return; }
7196
+ if (!['GET', 'HEAD'].includes(req.method)) { respond(405, { error: 'Method not allowed' }); return; }
7197
+ if (req.method === 'HEAD') { respond(200, {}); return; }
7198
+ if (route.page) {
7199
+ try {
7200
+ const nonce = crypto.randomBytes(24).toString('base64');
7201
+ const html = fs.readFileSync(path.join(PUBLIC_DIR, 'admin.html'), 'utf8').replaceAll('__ADMIN_NONCE__', nonce);
7202
+ res.writeHead(200, { ...headers, 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'` });
7203
+ res.end(html);
7204
+ } catch { respond(503, { error: 'Page unavailable' }); }
7205
+ return;
7206
+ }
7207
+ const cancellation = new AbortController();
7208
+ res.once('close', () => { if (!res.writableEnded) cancellation.abort(); });
7209
+ try {
7210
+ const result = await withoutDataScope(() => ownerAdmin.collectAdminSection(route, {
7211
+ feedbackDir, buildMetadata: BUILD_METADATA, runtime: adminRuntime,
7212
+ hashDataIdentity, buildHostedTenantIdentity,
7213
+ health: () => ({ version: pkg.version, buildSha: BUILD_METADATA.buildSha, uptime: process.uptime() }),
7214
+ ...ownerAdminDependencies,
7215
+ }, cancellation.signal));
7216
+ const body = JSON.stringify(result);
7217
+ if (Buffer.byteLength(body) > ownerAdmin.RESPONSE_LIMIT) { respond(503, { error: 'Response limit exceeded' }); return; }
7218
+ res.writeHead(200, { ...headers, 'Content-Type': 'application/json; charset=utf-8' });
7219
+ res.end(body);
7220
+ } catch (error) {
7221
+ respond(error.code === 'collection_busy' ? 429 : 503, { error: error.code === 'collection_busy' ? 'Collection busy' : 'Collection unavailable' });
7222
+ }
7223
+ return;
7224
+ }
7225
+ const earlyPrivateRoute = (req.method === 'POST' && pathname.startsWith('/feedback/quick')) || /^\/lessons\/[^/]+(?:\/[^/]+)?$/.test(pathname);
7226
+ if (earlyPrivateRoute && !currentDataScope()) {
7227
+ if (!isAuthorized(req, expectedApiKey)) {
7228
+ sendJson(res, 401, { error: 'Authentication required' });
7229
+ return;
7230
+ }
7231
+ const identity = resolveRequestDataIdentity(req, expectedApiKey);
7232
+ if (identity.invalidHostedIdentity) { sendJson(res, 403, { error: 'Invalid customer identity' }); return; }
7233
+ const roots = partitionFeedbackPaths(identity.partition ? getFeedbackPaths() : getRequestFeedbackPaths(req, parsed), identity);
7234
+ try {
7235
+ return await req[CONTINUE_DATA_SCOPE]({ kind: identity.partition ? 'tenant' : 'legacy', feedbackDir: roots.FEEDBACK_DIR, tenantId: identity.partition, principalId: identity.accessContext?.principalId });
7236
+ } catch (error) {
7237
+ sendJson(res, error.statusCode || 500, { error: error.statusCode ? error.message : 'Request failed' });
7238
+ return;
7239
+ }
7240
+ }
7241
+ let requestProjectKey;
7242
+ const projectOptions = {};
7243
+ const unavailableProjectRoutes = ['/v1/documents', '/v1/dashboard/ai-inventory', '/v1/dashboard/render-spec', '/v1/analytics/databricks/export', '/v1/feedback/rules', '/v1/skills/generate', '/v1/decisions/metrics', '/v1/settings/status'];
7244
+ async function readProjectBody(request, maxBytes) {
7245
+ const value = await parseJsonBody(request, maxBytes);
7246
+ requestProjectKey = parseProjectSelection(parsed.searchParams, request.headers, value);
7247
+ projectOptions.projectKey = requestProjectKey;
7248
+ if (requestProjectKey) parsed.searchParams.set('project', requestProjectKey);
7249
+ if (requestProjectKey != null && unavailableProjectRoutes.includes(pathname)) throw createHttpError(409, 'Unavailable for this project');
7250
+ return value;
7251
+ }
7252
+ try { requestProjectKey = parseProjectSelection(parsed.searchParams, req.headers); }
7253
+ catch (error) { sendJson(res, 400, { error: error.message }); return; }
7254
+ if (requestProjectKey && !parsed.searchParams.has('project')) parsed.searchParams.set('project', requestProjectKey);
5712
7255
  const isHeadRequest = req.method === 'HEAD';
5713
7256
  const isGetLikeRequest = req.method === 'GET' || isHeadRequest;
5714
7257
  const publicOrigin = getPublicOrigin(req);
@@ -5724,6 +7267,7 @@ function createApiServer() {
5724
7267
 
5725
7268
  // PostHog reverse proxy -- bypasses ad blockers.
5726
7269
  // Only allow known PostHog API paths to prevent SSRF (CodeQL js/request-forgery).
7270
+ if (isGetLikeRequest && pathname === '/project-switcher.js') { serveStaticFile(res, path.join(__dirname, '../../public/project-switcher.js'), { headOnly: isHeadRequest }); return; }
5727
7271
  if (pathname.startsWith('/ingest')) {
5728
7272
  const posthogPath = getPosthogProxyPath(pathname);
5729
7273
  if (!isAllowedPosthogProxyPath(posthogPath)) {
@@ -6009,7 +7553,16 @@ function createApiServer() {
6009
7553
  req.on('end', async () => {
6010
7554
  try {
6011
7555
  const body = JSON.parse(Buffer.concat(chunks).toString());
6012
- const { category, message } = body;
7556
+ let { category, message } = body;
7557
+ if (Array.isArray(body.reasons)) {
7558
+ const composed = composeChipFeedback({ reasons: body.reasons, details: body.details });
7559
+ if (!composed.ok) {
7560
+ sendJson(res, 400, { error: composed.reason });
7561
+ return;
7562
+ }
7563
+ category = composed.category;
7564
+ message = composed.message;
7565
+ }
6013
7566
  if (!message || message.length < 5) {
6014
7567
  sendJson(res, 400, { error: 'message too short' });
6015
7568
  return;
@@ -6101,7 +7654,11 @@ function createApiServer() {
6101
7654
  // throws — the mailer returns a structured result even on failure, so
6102
7655
  // the signup still succeeds if Resend is down or RESEND_API_KEY is unset.
6103
7656
  Promise.resolve()
6104
- .then(() => resendMailer.sendNewsletterWelcomeEmail({ to: email }))
7657
+ .then(() => resendMailer.dispatchSignupWelcomeEmail({
7658
+ to: email,
7659
+ source: attribution.source || 'newsletter',
7660
+ feedbackDir: getFeedbackPaths().FEEDBACK_DIR,
7661
+ }))
6105
7662
  .then((result) => {
6106
7663
  if (!result || result.sent !== true) {
6107
7664
  console.warn('[newsletter] welcome email not sent:', email, result && result.reason);
@@ -6228,7 +7785,7 @@ function createApiServer() {
6228
7785
  }
6229
7786
  }
6230
7787
  }
6231
- serveTrackedLinkRedirect({
7788
+ await serveTrackedLinkRedirect({
6232
7789
  req,
6233
7790
  res,
6234
7791
  parsed: trackedParsed,
@@ -6380,7 +7937,7 @@ async function addContext(){
6380
7937
  sendJson(res, 401, { error: 'Authentication required to update human feedback' });
6381
7938
  return;
6382
7939
  }
6383
- const body = await parseJsonBody(req);
7940
+ const body = await readProjectBody(req);
6384
7941
  const signal = body.signal;
6385
7942
  const context = typeof body.context === 'string' ? body.context.trim() : '';
6386
7943
  const relatedFeedbackId = typeof body.relatedFeedbackId === 'string' ? body.relatedFeedbackId.trim() : '';
@@ -6411,7 +7968,7 @@ async function addContext(){
6411
7968
  tags: nextTags,
6412
7969
  [detailField]: mergeFollowUpDetail(existing[detailField], context),
6413
7970
  };
6414
- });
7971
+ }, { projectKey: requestProjectKey });
6415
7972
  if (!updated) {
6416
7973
  sendJson(res, 404, { error: 'Related lesson not found' });
6417
7974
  return;
@@ -6435,7 +7992,7 @@ async function addContext(){
6435
7992
  return;
6436
7993
  }
6437
7994
 
6438
- if (isGetLikeRequest && pathname === '/dashboard') {
7995
+ if (isGetLikeRequest && (pathname === '/dashboard' || pathname === '/cloud')) {
6439
7996
  try {
6440
7997
  const html = loadDashboardPageHtml(req, expectedApiKey);
6441
7998
  sendHtml(res, 200, html, {}, { headOnly: isHeadRequest });
@@ -6445,13 +8002,158 @@ async function addContext(){
6445
8002
  return;
6446
8003
  }
6447
8004
 
8005
+ if (isGetLikeRequest && pathname === '/v1/cloud/sso/authorize') {
8006
+ const rawProvider = String(parsed.searchParams.get('provider') || 'google').trim().toLowerCase();
8007
+ const provider = ['google', 'apple'].includes(rawProvider) ? rawProvider : 'invalid';
8008
+ const appOrigin = hostedConfig.appOrigin || 'https://thumbgate.ai';
8009
+ const callbackUrl = `${appOrigin}/v1/cloud/sso/callback?provider=${encodeURIComponent(provider)}`;
8010
+ const googleClientId = String(process.env.GOOGLE_CLIENT_ID || '').trim();
8011
+ const appleClientId = String(process.env.APPLE_CLIENT_ID || '').trim();
8012
+ if (provider === 'google' && googleClientId) {
8013
+ const stateNonce = issueSsoPendingState('google', callbackUrl);
8014
+ const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${encodeURIComponent(googleClientId)}&redirect_uri=${encodeURIComponent(callbackUrl)}&response_type=code&scope=openid%20email%20profile&state=${encodeURIComponent(stateNonce)}`;
8015
+ const ssoStateCookie = serializeCookie(SSO_STATE_COOKIE_NAME, stateNonce, {
8016
+ maxAge: Math.floor(SSO_OAUTH_STATE_TTL_MS / 1000),
8017
+ path: '/v1/cloud/sso',
8018
+ httpOnly: true,
8019
+ sameSite: 'Lax',
8020
+ secure: true,
8021
+ });
8022
+ if (parsed.searchParams.get('format') === 'json') {
8023
+ sendJson(res, 200, { ok: true, mode: 'oauth_redirect', provider, redirectUrl: googleAuthUrl }, { 'Cache-Control': 'no-store', 'Set-Cookie': ssoStateCookie });
8024
+ return;
8025
+ }
8026
+ res.writeHead(302, { 'X-Content-Type-Options': 'nosniff', Location: googleAuthUrl, 'Cache-Control': 'no-store', 'Set-Cookie': ssoStateCookie });
8027
+ res.end();
8028
+ return;
8029
+ }
8030
+ if (provider === 'apple' && appleClientId) {
8031
+ const appleCallbackUrl = `${appOrigin.replace(/^http:\/\//i, 'https://')}/v1/cloud/sso/apple/callback`;
8032
+ const stateNonce = issueSsoPendingState('apple', appleCallbackUrl);
8033
+ const pendingNonce = ssoPendingStates.get(stateNonce)?.nonce || stateNonce;
8034
+ const appleAuthUrl = `https://appleid.apple.com/auth/authorize?client_id=${encodeURIComponent(appleClientId)}&redirect_uri=${encodeURIComponent(appleCallbackUrl)}&response_type=code&scope=name%20email&response_mode=form_post&state=${encodeURIComponent(stateNonce)}&nonce=${encodeURIComponent(pendingNonce)}`;
8035
+ if (parsed.searchParams.get('format') === 'json') {
8036
+ sendJson(res, 200, { ok: true, mode: 'oauth_redirect', provider, redirectUrl: appleAuthUrl }, { 'Cache-Control': 'no-store' });
8037
+ return;
8038
+ }
8039
+ res.writeHead(302, { 'X-Content-Type-Options': 'nosniff', Location: appleAuthUrl, 'Cache-Control': 'no-store' });
8040
+ res.end();
8041
+ return;
8042
+ }
8043
+ sendJson(
8044
+ res,
8045
+ 404,
8046
+ {
8047
+ ok: false,
8048
+ error: 'sso_provider_not_configured',
8049
+ provider: rawProvider || 'google',
8050
+ },
8051
+ { 'Cache-Control': 'no-store' },
8052
+ );
8053
+ return;
8054
+ }
8055
+
8056
+ if (isGetLikeRequest && pathname === '/v1/cloud/sso/callback') {
8057
+ try {
8058
+ const rawProvider = String(parsed.searchParams.get('provider') || 'google').trim().toLowerCase();
8059
+ if (rawProvider !== 'google') {
8060
+ redirectSsoError(res, 'unsupported_provider');
8061
+ return;
8062
+ }
8063
+ if (parsed.searchParams.get('error')) {
8064
+ consumeSsoPendingState(parsed.searchParams.get('state'), 'google');
8065
+ redirectSsoError(res, 'oauth_denied');
8066
+ return;
8067
+ }
8068
+ const code = String(parsed.searchParams.get('code') || '').trim();
8069
+ if (!code) {
8070
+ consumeSsoPendingState(parsed.searchParams.get('state'), 'google');
8071
+ redirectSsoError(res, 'missing_code');
8072
+ return;
8073
+ }
8074
+ const stateParam = parsed.searchParams.get('state');
8075
+ const reqCookies = parseCookies(req?.headers?.cookie || '');
8076
+ if (!stateParam || !safeKeyEqual(String(reqCookies[SSO_STATE_COOKIE_NAME] || ''), String(stateParam))) {
8077
+ consumeSsoPendingState(stateParam, 'google');
8078
+ redirectSsoError(res, 'invalid_state');
8079
+ return;
8080
+ }
8081
+ const stateEntry = consumeSsoPendingState(parsed.searchParams.get('state'), 'google');
8082
+ if (!stateEntry) {
8083
+ redirectSsoError(res, 'invalid_state');
8084
+ return;
8085
+ }
8086
+ const googleClientId = String(process.env.GOOGLE_CLIENT_ID || '').trim();
8087
+ const googleClientSecret = String(process.env.GOOGLE_CLIENT_SECRET || '').trim();
8088
+ if (!googleClientId || !googleClientSecret) {
8089
+ redirectSsoError(res, 'sso_not_configured');
8090
+ return;
8091
+ }
8092
+ const tokenParams = new URLSearchParams({
8093
+ code,
8094
+ client_id: googleClientId,
8095
+ client_secret: googleClientSecret,
8096
+ redirect_uri: stateEntry.redirectUri,
8097
+ grant_type: 'authorization_code',
8098
+ });
8099
+ const tokenRes = await googleOAuthFetch(GOOGLE_OAUTH_TOKEN_URL, {
8100
+ method: 'POST',
8101
+ headers: {
8102
+ 'Content-Type': 'application/x-www-form-urlencoded',
8103
+ Accept: 'application/json',
8104
+ },
8105
+ body: tokenParams.toString(),
8106
+ signal: AbortSignal.timeout(8000),
8107
+ });
8108
+ if (!tokenRes || !tokenRes.ok) {
8109
+ redirectSsoError(res, 'token_exchange_failed');
8110
+ return;
8111
+ }
8112
+ const tokenBody = await tokenRes.json();
8113
+ const idToken = String((tokenBody && tokenBody.id_token) || '').trim();
8114
+ if (!idToken) {
8115
+ redirectSsoError(res, 'missing_id_token');
8116
+ return;
8117
+ }
8118
+ const claims = await verifyGoogleIdToken(idToken, googleClientId);
8119
+ await completeSsoSessionAndRedirect(res, {
8120
+ provider: 'google',
8121
+ email: claims.email,
8122
+ redirectStatus: 302,
8123
+ });
8124
+ } catch (err) {
8125
+ redirectSsoError(res, err?.ssoReason || 'callback_failed');
8126
+ }
8127
+ return;
8128
+ }
8129
+
8130
+ if (pathname === '/v1/cloud/sso/apple/callback') {
8131
+ if (req.method !== 'POST') {
8132
+ sendJson(res, 405, { ok: false, error: 'Method Not Allowed' }, { Allow: 'POST', 'Cache-Control': 'no-store' });
8133
+ return;
8134
+ }
8135
+ await handleAppleSsoCallback(req, res);
8136
+ return;
8137
+ }
8138
+
8139
+ if (/^\/lessons\/[^/]+/.test(pathname)) {
8140
+ if (!isAuthorized(req, expectedApiKey)) { sendJson(res, 401, { error: 'Unauthorized' }); return; }
8141
+ const identity = resolveRequestDataIdentity(req, expectedApiKey);
8142
+ if (identity.invalidHostedIdentity) { sendJson(res, 403, { error: 'Unauthorized' }); return; }
8143
+ requestFeedbackPaths = currentDataScope()
8144
+ ? getFeedbackPaths({ feedbackDir: currentDataScope().lexicalRoot })
8145
+ : partitionFeedbackPaths(requestFeedbackPaths, identity);
8146
+ requestFeedbackDir = requestFeedbackPaths.FEEDBACK_DIR;
8147
+ requestSafeDataDir = path.resolve(requestFeedbackDir);
8148
+ Object.assign(projectOptions, { projectKey: requestProjectKey, feedbackDir: requestFeedbackDir }, projectEvidenceForRequest(req, parsed, requestFeedbackDir, identity));
8149
+ }
6448
8150
  // --- Lesson detail: POST /lessons/:id/update ---
6449
8151
  const lessonUpdateMatch = pathname.match(/^\/lessons\/([^/]+)\/update$/);
6450
8152
  if (req.method === 'POST' && lessonUpdateMatch) {
6451
8153
  const lessonId = decodeURIComponent(lessonUpdateMatch[1]);
6452
8154
  const feedbackDir = requestSafeDataDir;
6453
- const body = await parseJsonBody(req);
6454
- const record = findRecordById(lessonId, feedbackDir);
8155
+ const body = await readProjectBody(req);
8156
+ const record = findRecordById(lessonId, feedbackDir, projectOptions);
6455
8157
  if (!record) {
6456
8158
  sendJson(res, 404, { error: 'Record not found' });
6457
8159
  return;
@@ -6468,7 +8170,7 @@ async function addContext(){
6468
8170
  if (body.whatWentWrong !== undefined) next.whatWentWrong = body.whatWentWrong;
6469
8171
  if (body.whatWorked !== undefined) next.whatWorked = body.whatWorked;
6470
8172
  return next;
6471
- });
8173
+ }, projectOptions);
6472
8174
  if (!updated) {
6473
8175
  sendJson(res, 404, { error: 'Record not found' });
6474
8176
  return;
@@ -6484,9 +8186,12 @@ async function addContext(){
6484
8186
  const feedbackDir = requestSafeDataDir;
6485
8187
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
6486
8188
  const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
6487
- const deletedMemory = deleteLessonJsonlRecord(memoryLogPath, lessonId);
6488
- const deletedFeedback = deleteLessonJsonlRecord(feedbackLogPath, lessonId);
6489
- if (!deletedMemory && !deletedFeedback) {
8189
+ if (!findRecordById(lessonId, feedbackDir, projectOptions)) { sendJson(res, 404, { error: 'Record not found' }); return; }
8190
+ const { signalPaths, accountAttribution } = require('../../scripts/project-catalog');
8191
+ const writeOptions = { ...projectOptions, attribution: accountAttribution(feedbackDir, projectOptions) };
8192
+ let deleted = false;
8193
+ for (const name of ['memory-log.jsonl', 'feedback-log.jsonl']) for (const file of signalPaths(feedbackDir, name)) deleted = deleteLessonJsonlRecord(file, lessonId, writeOptions) || deleted;
8194
+ if (!deleted) {
6490
8195
  sendJson(res, 404, { error: 'Record not found' });
6491
8196
  return;
6492
8197
  }
@@ -6499,12 +8204,12 @@ async function addContext(){
6499
8204
  if (isGetLikeRequest && lessonDetailMatch && lessonDetailMatch[1] !== '') {
6500
8205
  const lessonId = decodeURIComponent(lessonDetailMatch[1]);
6501
8206
  const feedbackDir = requestSafeDataDir;
6502
- const record = findRecordById(lessonId, feedbackDir);
8207
+ const record = findRecordById(lessonId, feedbackDir, projectOptions);
6503
8208
  if (!record) {
6504
8209
  sendHtml(res, 404, renderLessonDetailHtml(null, lessonId));
6505
8210
  return;
6506
8211
  }
6507
- sendHtml(res, 200, renderLessonDetailHtml(record, lessonId), {}, { headOnly: isHeadRequest });
8212
+ sendHtml(res, 200, renderLessonDetailHtml(record, lessonId).replace('</head>', '<script src="/project-switcher.js"></script></head>'), {}, { headOnly: isHeadRequest });
6508
8213
  return;
6509
8214
  }
6510
8215
 
@@ -6875,22 +8580,12 @@ async function addContext(){
6875
8580
  }
6876
8581
 
6877
8582
  if (isGetLikeRequest && (pathname === '/numbers' || pathname === '/numbers.html')) {
6878
- // Route through servePublicMarketingPage so landing_page_view telemetry
6879
- // + funnel-events.jsonl `discovery/landing_view` get captured with UTM
6880
- // attribution — critical for Zernio social CTAs that target /numbers.
6881
- try {
6882
- servePublicMarketingPage({
6883
- req,
6884
- res,
6885
- parsed,
6886
- hostedConfig,
6887
- isHeadRequest,
6888
- renderHtml: () => fs.readFileSync(NUMBERS_PAGE_PATH, 'utf-8'),
6889
- extraTelemetry: { pageType: 'numbers' },
6890
- });
6891
- } catch {
6892
- sendJson(res, 404, { error: 'Numbers page not found' });
6893
- }
8583
+ res.writeHead(301, {
8584
+ Location: `/eval-scorecard${parsed.search || ''}`,
8585
+ 'Cache-Control': 'public, max-age=3600',
8586
+ 'X-Content-Type-Options': 'nosniff',
8587
+ });
8588
+ res.end();
6894
8589
  return;
6895
8590
  }
6896
8591
 
@@ -7517,6 +9212,7 @@ async function addContext(){
7517
9212
  }
7518
9213
 
7519
9214
  try {
9215
+ analyticsMetadata.entryRoute = 'checkout_pro_confirm';
7520
9216
  const result = await createCheckoutSession({
7521
9217
  successUrl: buildCheckoutFallbackUrl(
7522
9218
  buildHostedSuccessUrl(hostedConfig.appOrigin, traceId),
@@ -7623,6 +9319,15 @@ async function addContext(){
7623
9319
  });
7624
9320
  res.end();
7625
9321
  } catch (err) {
9322
+ if (err && err.code === 'AUTOMATED_CHECKOUT_BLOCKED') {
9323
+ sendProblem(res, {
9324
+ type: PROBLEM_TYPES.BAD_REQUEST,
9325
+ title: 'Checkout blocked',
9326
+ status: 403,
9327
+ detail: err.message,
9328
+ }, responseHeaders);
9329
+ return;
9330
+ }
7626
9331
  appendBestEffortTelemetry(FEEDBACK_DIR, {
7627
9332
  eventType: 'checkout_api_failed',
7628
9333
  clientType: 'web',
@@ -7705,26 +9410,71 @@ async function addContext(){
7705
9410
  return;
7706
9411
  }
7707
9412
 
7708
- if (isGetLikeRequest && pathname === '/broker-audit') {
7709
- // Public-facing broker lead-flow audit landing page. Wedge for the
7710
- // real-estate broker outreach. Static HTML served from src/api/static.
7711
- try {
7712
- const host = getSafePublicRequestHost(req);
7713
- const html = normalizePublicMarketingHtml(fillTemplate(fs.readFileSync(
7714
- path.resolve(__dirname, '../../assets/static/broker-audit.html'),
7715
- 'utf8'
7716
- ), {
7717
- '__POSTHOG_API_KEY__': hostedConfig.posthogApiKey || '',
7718
- }), hostedConfig, host);
7719
- if (isHeadRequest) {
7720
- sendHtml(res, 200, html, {}, { headOnly: true });
9413
+ if (isGetLikeRequest && (pathname === '/portal' || pathname === '/billing' || pathname === '/billing/portal')) {
9414
+ const apiKeyParam = parsed.searchParams.get('key')
9415
+ || parsed.searchParams.get('apiKey')
9416
+ || parsed.searchParams.get('license_key')
9417
+ || '';
9418
+ const sessionIdParam = parsed.searchParams.get('session_id')
9419
+ || parsed.searchParams.get('sessionId')
9420
+ || '';
9421
+ // Only proof of ownership opens the portal: an API key or a Stripe checkout
9422
+ // session id. A bare email or customer id is public/guessable and would let
9423
+ // anyone manage someone else's subscription, so those params are ignored.
9424
+ const authHeader = req.headers['authorization'] || '';
9425
+ const bearerKey = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
9426
+ const effectiveKey = apiKeyParam || bearerKey;
9427
+
9428
+ const wantsJson = (req.headers['accept'] && req.headers['accept'].includes('application/json'))
9429
+ || parsed.searchParams.get('format') === 'json';
9430
+
9431
+ if (effectiveKey || sessionIdParam) {
9432
+ try {
9433
+ const portalSession = await createBillingPortalSession({
9434
+ apiKey: effectiveKey,
9435
+ sessionId: sessionIdParam,
9436
+ returnUrl: hostedConfig.appOrigin ? `${hostedConfig.appOrigin}/` : undefined,
9437
+ });
9438
+
9439
+ if (wantsJson) {
9440
+ sendJson(res, 200, {
9441
+ url: portalSession.url,
9442
+ id: portalSession.id,
9443
+ customerId: portalSession.customerId,
9444
+ });
9445
+ return;
9446
+ }
9447
+
9448
+ res.writeHead(302, {
9449
+ Location: portalSession.url,
9450
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
9451
+ });
9452
+ res.end();
9453
+ return;
9454
+ } catch (err) {
9455
+ if (wantsJson) {
9456
+ sendProblem(res, {
9457
+ type: PROBLEM_TYPES.BAD_REQUEST,
9458
+ title: 'Billing Portal Error',
9459
+ status: err.statusCode || 400,
9460
+ detail: err.message || 'Unable to open billing portal session.',
9461
+ });
9462
+ return;
9463
+ }
9464
+ sendHtml(res, 400, renderManageSubscriptionPage(hostedConfig, {
9465
+ error: err.message || 'Unable to locate customer billing record for the provided license key.',
9466
+ enteredKey: effectiveKey,
9467
+ }));
7721
9468
  return;
7722
9469
  }
7723
- sendHtml(res, 200, html);
7724
- } catch (err) {
7725
- console.error('broker-audit page read failed:', err?.message);
7726
- sendJson(res, 500, { error: 'broker-audit page unavailable' });
7727
9470
  }
9471
+
9472
+ if (isHeadRequest) {
9473
+ sendHtml(res, 200, renderManageSubscriptionPage(hostedConfig), {}, { headOnly: true });
9474
+ return;
9475
+ }
9476
+
9477
+ sendHtml(res, 200, renderManageSubscriptionPage(hostedConfig));
7728
9478
  return;
7729
9479
  }
7730
9480
 
@@ -8075,8 +9825,9 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8075
9825
  if (req.method === 'POST' && pathname === '/v1/telemetry/ping') {
8076
9826
  const { FEEDBACK_DIR } = getFeedbackPaths();
8077
9827
  try {
8078
- const payload = await parseJsonBody(req, 16 * 1024);
8079
- appendTelemetryPing(FEEDBACK_DIR, payload, req.headers);
9828
+ const payload = await readProjectBody(req, 16 * 1024);
9829
+ const persisted = appendTelemetryPing(FEEDBACK_DIR, payload, req.headers);
9830
+ adminRuntime.recordTelemetry(Boolean(persisted));
8080
9831
  } catch (err) {
8081
9832
  try {
8082
9833
  appendDiagnosticRecord({
@@ -8123,7 +9874,14 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8123
9874
  res.end();
8124
9875
  return;
8125
9876
  }
8126
-
9877
+ if (pathname === '/v1/activation/first-block' && (req.method === 'POST' || req.method === 'OPTIONS')) {
9878
+ await handleFirstBlockActivationRoute(req, res, expectedApiKey, expectedOperatorKey);
9879
+ return;
9880
+ }
9881
+ if (pathname === '/v1/onboarding/try-block' && (req.method === 'POST' || req.method === 'OPTIONS')) {
9882
+ await handleOnboardingTryBlock(req, res, expectedApiKey, expectedOperatorKey);
9883
+ return;
9884
+ }
8127
9885
  if (req.method === 'GET' && pathname === '/v1/metrics/real') {
8128
9886
  const bd = require('../../scripts/bot-detection');
8129
9887
  const { FEEDBACK_DIR: metricsDir } = getFeedbackPaths();
@@ -8187,6 +9945,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8187
9945
  const ACTIVE_EVENTS = new Set([
8188
9946
  'cli_capture', 'cli_recall', 'cli_stats',
8189
9947
  'activation_first_rule_promoted',
9948
+ 'first_blocked_tool_call',
8190
9949
  ]);
8191
9950
  const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1000;
8192
9951
  const last30 = classified.filter(e => {
@@ -8230,11 +9989,13 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8230
9989
  ci: classified.filter(e => e.visitorType === 'ci').length,
8231
9990
  uniqueInstalls: uniqueInstallIds.size,
8232
9991
  activeInstalls: allTimeActiveInstalls.size,
9992
+ firstBlockedToolCall: summarizeFirstBlockEvents(classified),
8233
9993
  },
8234
9994
  last30Days: {
8235
9995
  uniqueInstalls: new Set(last30.filter(e => e.installId).map(e => e.installId)).size,
8236
9996
  activeInstalls: activeInstalls30d.size,
8237
9997
  uniqueSessions: uniqueSessions30d.size,
9998
+ firstBlockedToolCall: summarizeFirstBlockEvents(last30),
8238
9999
  },
8239
10000
  last7Days: {
8240
10001
  total: recent.length,
@@ -8245,6 +10006,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8245
10006
  uniqueInstalls: recentInstallIds.size,
8246
10007
  activeInstalls: activeInstalls7d.size,
8247
10008
  uniqueSessions: uniqueSessions7d.size,
10009
+ firstBlockedToolCall: summarizeFirstBlockEvents(recent),
8248
10010
  },
8249
10011
  byEventType,
8250
10012
  byVisitorType,
@@ -8539,130 +10301,6 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8539
10301
  return;
8540
10302
  }
8541
10303
 
8542
- if (req.method === 'OPTIONS' && pathname === '/v1/intake/broker-audit') {
8543
- sendPublicBillingPreflight(res);
8544
- return;
8545
- }
8546
-
8547
- if (req.method === 'POST' && pathname === '/v1/intake/broker-audit') {
8548
- const { FEEDBACK_DIR } = getFeedbackPaths();
8549
- const traceId = createTraceId('broker_audit');
8550
- const journeyState = resolveJourneyState(req, parsed);
8551
- const referrerAttribution = buildReferrerAttribution(req);
8552
- const contentType = String(req.headers['content-type'] || '').toLowerCase();
8553
- const isFormSubmission = contentType.includes('application/x-www-form-urlencoded');
8554
- try {
8555
- const body = isFormSubmission
8556
- ? await parseFormBody(req, 16 * 1024)
8557
- : await parseJsonBody(req, 16 * 1024);
8558
- const lead = appendBrokerAuditLead(FEEDBACK_DIR, {
8559
- ...body,
8560
- traceId: body.traceId || traceId,
8561
- acquisitionId: body.acquisitionId || journeyState.acquisitionId,
8562
- visitorId: body.visitorId || journeyState.visitorId,
8563
- sessionId: body.sessionId || journeyState.sessionId,
8564
- page: body.page || referrerAttribution.page || '/broker-audit',
8565
- landingPath: body.landingPath || referrerAttribution.landingPath || '/broker-audit',
8566
- ctaId: body.ctaId || 'broker_audit_form',
8567
- ctaPlacement: body.ctaPlacement || 'broker_audit',
8568
- source: body.source || body.utmSource || referrerAttribution.source || 'website',
8569
- utmSource: body.utmSource || body.source || referrerAttribution.utmSource || 'website',
8570
- utmMedium: body.utmMedium || referrerAttribution.utmMedium || 'broker_audit',
8571
- utmCampaign: body.utmCampaign || referrerAttribution.utmCampaign || 'broker_audit_free',
8572
- utmContent: body.utmContent || referrerAttribution.utmContent || null,
8573
- utmTerm: body.utmTerm || referrerAttribution.utmTerm || null,
8574
- referrerHost: body.referrerHost || referrerAttribution.referrerHost || null,
8575
- referrer: body.referrer || referrerAttribution.referrer || null,
8576
- });
8577
-
8578
- appendBestEffortTelemetry(FEEDBACK_DIR, {
8579
- eventType: 'broker_audit_lead_submitted',
8580
- clientType: 'web',
8581
- traceId: lead.attribution.traceId,
8582
- acquisitionId: lead.attribution.acquisitionId,
8583
- visitorId: lead.attribution.visitorId,
8584
- sessionId: lead.attribution.sessionId,
8585
- source: lead.attribution.source,
8586
- utmSource: lead.attribution.utmSource,
8587
- utmMedium: lead.attribution.utmMedium,
8588
- utmCampaign: lead.attribution.utmCampaign,
8589
- utmContent: lead.attribution.utmContent,
8590
- utmTerm: lead.attribution.utmTerm,
8591
- ctaId: lead.attribution.ctaId,
8592
- ctaPlacement: lead.attribution.ctaPlacement,
8593
- page: lead.attribution.page,
8594
- landingPath: lead.attribution.landingPath,
8595
- referrerHost: lead.attribution.referrerHost,
8596
- referrer: lead.attribution.referrer,
8597
- }, req.headers, 'broker_audit_lead_submitted');
8598
-
8599
- if (isFormSubmission && !wantsJson(req, parsed)) {
8600
- sendHtml(
8601
- res,
8602
- 201,
8603
- renderBrokerAuditIntakeResultPage(hostedConfig, {
8604
- title: 'Broker audit request received',
8605
- detail: 'Your free broker lead-flow audit request is captured. The next step is the 1-page PDF with the specific lead leaks.',
8606
- leadId: lead.leadId,
8607
- }),
8608
- journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}
8609
- );
8610
- return;
8611
- }
8612
-
8613
- sendJson(res, 201, {
8614
- ok: true,
8615
- leadId: lead.leadId,
8616
- status: lead.status,
8617
- offer: lead.offer,
8618
- nextStep: 'deliver_1_page_pdf',
8619
- }, {
8620
- ...getPublicBillingHeaders(lead.attribution.traceId),
8621
- ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
8622
- });
8623
- } catch (err) {
8624
- appendBestEffortTelemetry(FEEDBACK_DIR, {
8625
- eventType: 'broker_audit_lead_failed',
8626
- clientType: 'web',
8627
- traceId,
8628
- acquisitionId: journeyState.acquisitionId,
8629
- visitorId: journeyState.visitorId,
8630
- sessionId: journeyState.sessionId,
8631
- source: referrerAttribution.source || 'website',
8632
- utmSource: referrerAttribution.utmSource || 'website',
8633
- utmMedium: referrerAttribution.utmMedium || 'broker_audit',
8634
- utmCampaign: referrerAttribution.utmCampaign || 'broker_audit_free',
8635
- ctaId: 'broker_audit_form',
8636
- ctaPlacement: 'broker_audit',
8637
- page: referrerAttribution.page || '/broker-audit',
8638
- landingPath: referrerAttribution.landingPath || '/broker-audit',
8639
- referrerHost: referrerAttribution.referrerHost,
8640
- referrer: referrerAttribution.referrer,
8641
- failureCode: err?.message ? err.message : 'broker_audit_lead_failed',
8642
- httpStatus: err && err.statusCode ? err.statusCode : null,
8643
- }, req.headers, 'broker_audit_lead_failed');
8644
- if (isFormSubmission && !wantsJson(req, parsed)) {
8645
- sendHtml(
8646
- res,
8647
- err.statusCode || 500,
8648
- renderBrokerAuditIntakeResultPage(hostedConfig, {
8649
- title: 'Broker audit request failed',
8650
- detail: err.message || 'Unable to capture broker audit request.',
8651
- }),
8652
- journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}
8653
- );
8654
- return;
8655
- }
8656
- sendProblem(res, {
8657
- type: !err.statusCode || err.statusCode >= 500 ? PROBLEM_TYPES.INTERNAL : PROBLEM_TYPES.BAD_REQUEST,
8658
- title: !err.statusCode || err.statusCode >= 500 ? 'Internal Server Error' : 'Request Error',
8659
- status: err.statusCode || 500,
8660
- detail: err.message || 'Unable to capture broker audit request.',
8661
- }, getPublicBillingHeaders(traceId));
8662
- }
8663
- return;
8664
- }
8665
-
8666
10304
  if (req.method === 'POST' && pathname === '/v1/intake/workflow-sprint') {
8667
10305
  const { FEEDBACK_DIR } = getFeedbackPaths();
8668
10306
  const traceId = createTraceId('sprint_intake');
@@ -8674,10 +10312,16 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8674
10312
  try {
8675
10313
  const body = isFormSubmission
8676
10314
  ? await parseFormBody(req, 24 * 1024)
8677
- : await parseJsonBody(req, 24 * 1024);
10315
+ : await readProjectBody(req, 24 * 1024);
8678
10316
  const workflowSprintIntake = requirePrivateApiModule('workflowSprintIntake', 'Workflow sprint intake');
10317
+ const reqCookies = parseCookies(req?.headers?.cookie || '');
10318
+ const ssoEntry = getPaidAuthSessionEntry(reqCookies[PAID_AUTH_COOKIE_NAME], expectedApiKey, expectedOperatorKey);
10319
+ const isFreeTierLimitLead = body.ctaPlacement === 'free_tier_limit' || body.freeTierLimit === true || body.freeTierLimit === '1';
8679
10320
  const leadPayload = {
8680
10321
  ...body,
10322
+ email: body.email || ssoEntry?.ssoEmail || undefined,
10323
+ name: body.name || ssoEntry?.ssoName || undefined,
10324
+ workflow: body.workflow || (isFreeTierLimitLead ? 'Free-tier limit inquiry (Talk to us)' : undefined),
8681
10325
  traceId: body.traceId || traceId,
8682
10326
  acquisitionId: body.acquisitionId || journeyState.acquisitionId,
8683
10327
  visitorId: body.visitorId || journeyState.visitorId,
@@ -8686,7 +10330,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8686
10330
  landingPath: body.landingPath || referrerAttribution.landingPath || '/',
8687
10331
  ctaId: body.ctaId || 'workflow_sprint_intake',
8688
10332
  ctaPlacement: body.ctaPlacement || 'workflow_sprint',
8689
- planId: body.planId || 'sprint',
10333
+ planId: body.planId || (isFreeTierLimitLead ? 'diagnostic' : 'sprint'),
8690
10334
  source: body.source || body.utmSource || referrerAttribution.source || 'website',
8691
10335
  utmSource: body.utmSource || body.source || referrerAttribution.utmSource || 'website',
8692
10336
  utmMedium: body.utmMedium || referrerAttribution.utmMedium || 'workflow_sprint_intake',
@@ -8702,6 +10346,15 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8702
10346
  referrerHost: body.referrerHost || referrerAttribution.referrerHost || null,
8703
10347
  referrer: body.referrer || referrerAttribution.referrer || null,
8704
10348
  };
10349
+ if (isFreeTierLimitLead && !leadPayload.email) {
10350
+ sendProblem(res, {
10351
+ type: PROBLEM_TYPES.BAD_REQUEST,
10352
+ title: 'Request Error',
10353
+ status: 400,
10354
+ detail: 'Work email is required to queue a request.',
10355
+ }, getPublicBillingHeaders(traceId));
10356
+ return;
10357
+ }
8705
10358
  const intakeReservation = workflowSprintIntake.reserveWorkflowSprintIntake(leadPayload, {
8706
10359
  feedbackDir: FEEDBACK_DIR,
8707
10360
  rateLimitKey: buildIntakeAlertRateLimitKey(req),
@@ -8713,8 +10366,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8713
10366
  }
8714
10367
  const lead = workflowSprintIntake.appendWorkflowSprintLead(leadPayload, { feedbackDir: FEEDBACK_DIR });
8715
10368
 
8716
- appendBestEffortTelemetry(FEEDBACK_DIR, {
8717
- eventType: 'workflow_sprint_lead_submitted',
10369
+ const leadTelemetryBase = {
8718
10370
  clientType: 'web',
8719
10371
  traceId: lead.attribution.traceId,
8720
10372
  acquisitionId: lead.attribution.acquisitionId,
@@ -8740,8 +10392,11 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8740
10392
  landingPath: lead.attribution.landingPath,
8741
10393
  referrerHost: lead.attribution.referrerHost,
8742
10394
  referrer: lead.attribution.referrer,
8743
- }, req.headers, 'workflow_sprint_lead_submitted');
8744
-
10395
+ };
10396
+ appendBestEffortTelemetry(FEEDBACK_DIR, { eventType: 'workflow_sprint_lead_submitted', ...leadTelemetryBase }, req.headers, 'workflow_sprint_lead_submitted');
10397
+ if (isFreeTierLimitLead && lead.attribution.ctaId === 'workflow_sprint_intake') {
10398
+ appendBestEffortTelemetry(FEEDBACK_DIR, { eventType: 'checkout_interstitial_cta_clicked', ...leadTelemetryBase, ctaId: 'workflow_sprint_intake' }, req.headers, 'checkout_interstitial_cta_clicked');
10399
+ }
8745
10400
  const leadNotification = await workflowSprintIntake.notifyWorkflowSprintLead(lead, {
8746
10401
  sendEmailImpl: resendMailer.sendEmail,
8747
10402
  rateLimitKey: buildIntakeAlertRateLimitKey(req),
@@ -9267,20 +10922,145 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9267
10922
  return;
9268
10923
  }
9269
10924
 
9270
- if (req.method === 'OPTIONS' && (pathname === '/v1/billing/checkout' || pathname === '/v1/billing/session')) {
10925
+ if (req.method === 'OPTIONS' && (pathname === '/v1/billing/checkout' || pathname === '/v1/billing/session' || pathname === '/v1/billing/portal' || pathname === '/v1/billing/recommend-offer' || pathname === '/v1/design/self-correct' || pathname === '/v1/boost/evaluate' || pathname === '/v1/decisions/subq-snap')) {
9271
10926
  sendPublicBillingPreflight(res);
9272
10927
  return;
9273
10928
  }
9274
10929
 
10930
+ if (req.method === 'POST' && pathname === '/v1/design/self-correct') {
10931
+ try {
10932
+ const body = await readProjectBody(req);
10933
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
10934
+ throw createHttpError(400, 'JSON object body is required');
10935
+ }
10936
+ const rawTrace = typeof body.traceId === 'string' ? body.traceId.trim() : '';
10937
+ const traceId = /^[a-zA-Z0-9._:-]{1,128}$/.test(rawTrace) ? rawTrace : createTraceId('design');
10938
+ const sourceCode = typeof body.sourceCode === 'string' ? body.sourceCode : '';
10939
+ if (!sourceCode && !Array.isArray(body.visualFindings)) {
10940
+ throw createHttpError(400, 'sourceCode (string) or visualFindings (array) is required');
10941
+ }
10942
+ if (sourceCode.length > 262144) {
10943
+ throw createHttpError(413, 'sourceCode exceeds 256 KiB limit');
10944
+ }
10945
+ const { runDesignSelfCorrectionPipeline } = require('../openshell-lovable-engine');
10946
+ const result = runDesignSelfCorrectionPipeline({
10947
+ sourceCode,
10948
+ visualFindings: Array.isArray(body.visualFindings) ? body.visualFindings : [],
10949
+ minContrast: typeof body.minContrast === 'number' ? body.minContrast : 4.5,
10950
+ defaultBgHex: typeof body.defaultBgHex === 'string' ? body.defaultBgHex : '#0f172a',
10951
+ allowTailwind: body.allowTailwind !== false,
10952
+ });
10953
+ sendJson(res, 200, { ...result, traceId }, getPublicBillingHeaders(traceId));
10954
+ } catch (err) {
10955
+ sendProblem(res, {
10956
+ type: PROBLEM_TYPES.BAD_REQUEST,
10957
+ title: 'Request Error',
10958
+ status: err.statusCode || 400,
10959
+ detail: err.statusCode ? err.message : 'Unable to process design self-correction request.',
10960
+ }, getPublicBillingHeaders(''));
10961
+ }
10962
+ return;
10963
+ }
10964
+
10965
+ if (req.method === 'POST' && pathname === '/v1/boost/evaluate') {
10966
+ try {
10967
+ const body = await readProjectBody(req);
10968
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
10969
+ throw createHttpError(400, 'JSON object body is required');
10970
+ }
10971
+ const rawTrace = typeof body.traceId === 'string' ? body.traceId.trim() : '';
10972
+ const traceId = /^[a-zA-Z0-9._:-]{1,128}$/.test(rawTrace) ? rawTrace : createTraceId('boost');
10973
+ const { evaluateComputeBoostLane } = require('../openshell-lovable-engine');
10974
+ const result = evaluateComputeBoostLane(body);
10975
+ sendJson(res, 200, { ...result, traceId }, getPublicBillingHeaders(traceId));
10976
+ } catch (err) {
10977
+ sendProblem(res, {
10978
+ type: PROBLEM_TYPES.BAD_REQUEST,
10979
+ title: 'Request Error',
10980
+ status: err.statusCode || 400,
10981
+ detail: err.statusCode ? err.message : 'Unable to evaluate compute boost lane.',
10982
+ }, getPublicBillingHeaders(''));
10983
+ }
10984
+ return;
10985
+ }
10986
+
10987
+ if (req.method === 'POST' && pathname === '/v1/decisions/subq-snap') {
10988
+ try {
10989
+ const body = await readProjectBody(req);
10990
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
10991
+ throw createHttpError(400, 'JSON object body is required');
10992
+ }
10993
+ const rawTrace = typeof body.traceId === 'string' ? body.traceId.trim() : '';
10994
+ const traceId = /^[a-zA-Z0-9._:-]{1,128}$/.test(rawTrace) ? rawTrace : createTraceId('subq');
10995
+ const isAuthedCaller = Boolean(resolvePaidSessionTier(extractApiKey(req), expectedApiKey, expectedOperatorKey));
10996
+ const { callSubQSnapSystemOneApi } = require('../openshell-lovable-engine');
10997
+ const result = await callSubQSnapSystemOneApi(body, {
10998
+ confidenceThreshold: body.confidenceThreshold,
10999
+ apiKey: isAuthedCaller ? undefined : '',
11000
+ });
11001
+ sendJson(res, result.ok ? 200 : 422, { ...result, traceId }, getPublicBillingHeaders(traceId));
11002
+ } catch (err) {
11003
+ sendProblem(res, {
11004
+ type: PROBLEM_TYPES.BAD_REQUEST,
11005
+ title: 'Request Error',
11006
+ status: err.statusCode || 400,
11007
+ detail: err.statusCode ? err.message : 'Unable to evaluate SubQ Snap decision.',
11008
+ }, getPublicBillingHeaders(''));
11009
+ }
11010
+ return;
11011
+ }
11012
+
11013
+ if (req.method === 'POST' && pathname === '/v1/billing/recommend-offer') {
11014
+ try {
11015
+ const body = await readProjectBody(req);
11016
+ const traceId = body.traceId || createTraceId('offer');
11017
+ const forwardedList = req.headers['x-forwarded-for']
11018
+ ? String(req.headers['x-forwarded-for']).split(',').map((s) => s.trim()).filter(Boolean)
11019
+ : [];
11020
+ const clientIp = String(
11021
+ (forwardedList.length > 0 ? forwardedList[forwardedList.length - 1] : '')
11022
+ || (req.socket && req.socket.remoteAddress)
11023
+ || ''
11024
+ ).trim();
11025
+ const { recommendCheckoutOfferDecision } = require('../mcp-writeguard');
11026
+ const recommendation = await recommendCheckoutOfferDecision({
11027
+ reasonCode: body.reasonCode,
11028
+ reasonText: body.reasonText,
11029
+ page: body.page,
11030
+ currentPlan: body.currentPlan,
11031
+ provider: body.provider || undefined,
11032
+ clientIp,
11033
+ });
11034
+ sendJson(res, 200, { ...recommendation, traceId }, getPublicBillingHeaders(traceId));
11035
+ } catch (err) {
11036
+ sendProblem(res, {
11037
+ type: PROBLEM_TYPES.BAD_REQUEST,
11038
+ title: 'Request Error',
11039
+ status: err.statusCode || 400,
11040
+ detail: 'Unable to process offer recommendation request.',
11041
+ }, getPublicBillingHeaders(''));
11042
+ }
11043
+ return;
11044
+ }
11045
+
9275
11046
  // Public checkout session creation for top-of-funnel acquisition.
9276
11047
  if (req.method === 'POST' && pathname === '/v1/billing/checkout') {
9277
11048
  try {
9278
- const body = await parseJsonBody(req);
11049
+ const body = await readProjectBody(req);
9279
11050
  const traceId = body.traceId || createTraceId('checkout');
9280
11051
  const responseHeaders = getPublicBillingHeaders(traceId);
9281
- const analyticsMetadata = buildCheckoutAttributionMetadata(body, req, traceId);
11052
+ const analyticsMetadata = {
11053
+ ...buildCheckoutAttributionMetadata(body, req, traceId),
11054
+ entryRoute: 'api_billing_checkout',
11055
+ };
9282
11056
  const offerSummary = resolveCheckoutOfferSummary(analyticsMetadata);
9283
-
11057
+ // A session without an email can't be followed up and almost always
11058
+ // expires unpaid; most of the 30-day emailless sessions came from here.
11059
+ const customerEmail = normalizeCheckoutCustomerEmail(body.customerEmail);
11060
+ if (!customerEmail) {
11061
+ throw createHttpError(400, 'customerEmail must be a valid email address');
11062
+ }
11063
+
9284
11064
  const result = await createCheckoutSession({
9285
11065
  successUrl: body.successUrl || buildCheckoutFallbackUrl(
9286
11066
  buildHostedSuccessUrl(hostedConfig.appOrigin, traceId),
@@ -9290,7 +11070,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9290
11070
  buildHostedCancelUrl(hostedConfig.appOrigin, traceId),
9291
11071
  analyticsMetadata,
9292
11072
  ),
9293
- customerEmail: body.customerEmail,
11073
+ customerEmail,
9294
11074
  installId: body.installId,
9295
11075
  traceId,
9296
11076
  metadata: analyticsMetadata,
@@ -9364,6 +11144,45 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9364
11144
  return;
9365
11145
  }
9366
11146
 
11147
+ if (req.method === 'POST' && pathname === '/v1/billing/portal') {
11148
+ try {
11149
+ const body = await readProjectBody(req);
11150
+ const traceId = body.traceId || createTraceId('billing_portal');
11151
+ const responseHeaders = getPublicBillingHeaders(traceId);
11152
+ const authHeader = req.headers['authorization'] || '';
11153
+ const bearerKey = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
11154
+
11155
+ const portalSession = await createBillingPortalSession({
11156
+ apiKey: body.apiKey || body.key || bearerKey,
11157
+ sessionId: body.sessionId || body.session_id,
11158
+ // customerId/email are not proof of ownership and returnUrl is caller-controlled:
11159
+ // accept neither from an unauthenticated public route.
11160
+ returnUrl: hostedConfig.appOrigin ? `${hostedConfig.appOrigin}/` : undefined,
11161
+ });
11162
+
11163
+ sendJson(res, 200, {
11164
+ url: portalSession.url,
11165
+ id: portalSession.id,
11166
+ customerId: portalSession.customerId,
11167
+ traceId,
11168
+ }, responseHeaders);
11169
+ } catch (err) {
11170
+ const fallbackTraceId = createTraceId('billing_portal_error');
11171
+ sendProblem(res, {
11172
+ type: PROBLEM_TYPES.BAD_REQUEST,
11173
+ title: 'Billing Portal Error',
11174
+ status: err.statusCode || 400,
11175
+ detail: err.message || 'Unable to open billing portal session.',
11176
+ }, getPublicBillingHeaders(fallbackTraceId));
11177
+ }
11178
+ return;
11179
+ }
11180
+
11181
+ if (pathname === '/v1/auth/session') {
11182
+ await handlePaidAuthSessionRoute(req, res, expectedApiKey, expectedOperatorKey);
11183
+ return;
11184
+ }
11185
+
9367
11186
  // Catch non-API GET requests that didn't match any public page route above.
9368
11187
  // Without this, /about, /docs, /demo etc. fall through to the API auth gate
9369
11188
  // and return a raw JSON 401 instead of a user-friendly 404.
@@ -9397,38 +11216,64 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9397
11216
  });
9398
11217
  return;
9399
11218
  }
9400
- requestFeedbackPaths = partitionFeedbackPaths(requestFeedbackPaths, requestDataIdentity);
11219
+ const baseFeedbackPaths = requestDataIdentity.partition ? getFeedbackPaths() : requestFeedbackPaths;
11220
+ requestFeedbackPaths = currentDataScope()
11221
+ ? getFeedbackPaths({ feedbackDir: currentDataScope().lexicalRoot })
11222
+ : partitionFeedbackPaths(baseFeedbackPaths, requestDataIdentity);
9401
11223
  requestFeedbackDir = requestFeedbackPaths.FEEDBACK_DIR;
9402
11224
  requestSafeDataDir = path.resolve(requestFeedbackDir);
9403
11225
  requestDocumentAccessContext = requestDataIdentity.accessContext;
9404
11226
 
9405
- // Usage metering — record request for billing keys (not static THUMBGATE_API_KEY)
9406
- const _token = extractBearerToken(req);
9407
- if (_token && _token !== expectedApiKey) {
9408
- recordUsage(_token);
9409
- }
9410
-
9411
11227
  try {
11228
+ if (!currentDataScope()) {
11229
+ return await req[CONTINUE_DATA_SCOPE]({ kind: requestDataIdentity.partition ? 'tenant' : 'legacy', feedbackDir: requestFeedbackDir, tenantId: requestDataIdentity.partition, principalId: requestDocumentAccessContext?.principalId });
11230
+ }
11231
+ // Usage metering runs only on the scoped dispatch pass.
11232
+ const _token = extractBearerToken(req);
11233
+ if (_token && _token !== expectedApiKey) recordUsage(_token);
11234
+ Object.assign(projectOptions, { projectKey: requestProjectKey, feedbackDir: requestFeedbackDir }, projectEvidenceForRequest(req, parsed, requestFeedbackDir, requestDataIdentity));
11235
+ if (req.method === 'GET' && pathname === '/v1/projects') { sendJson(res, 200, buildProjectCatalog(requestFeedbackDir, projectOptions)); return; }
11236
+ if (requestProjectKey != null && req.method === 'GET' && ['/v1/dashboard', '/v1/feedback/stats'].includes(pathname)) {
11237
+ const data = generateDashboard(requestFeedbackDir, {
11238
+ projectKey: requestProjectKey, ...projectOptions, humanOnly: true });
11239
+ const tier = resolvePaidSessionTier(extractApiKey(req), expectedApiKey, expectedOperatorKey) || 'pro';
11240
+ if (pathname === '/v1/dashboard') sendJson(res, 200, { ...data, tier });
11241
+ else sendJson(res, 200, { ...data.feedbackAnalysis, projectKey: requestProjectKey, tier, gateStats: data.gateStats, activeGateCount: data.gateStats.totalGates, todayOverview: data.todayOverview });
11242
+ return;
11243
+ }
11244
+ if (requestProjectKey != null && unavailableProjectRoutes.includes(pathname)) {
11245
+ sendJson(res, 409, { error: 'Unavailable for this project', unavailableSources: [pathname] }); return;
11246
+ }
9412
11247
  if (req.method === 'GET' && pathname === '/v1/feedback/stats') {
9413
11248
  const stats = shouldAggregateFeedback()
9414
11249
  ? computeAggregateFeedbackStats({ feedbackDir: requestFeedbackPaths.FEEDBACK_DIR })
9415
11250
  : analyzeFeedback(requestFeedbackPaths.FEEDBACK_LOG_PATH, { humanOnly: true });
11251
+ const requestToken = extractApiKey(req);
11252
+ const authenticatedTier = requestToken
11253
+ ? resolvePaidSessionTier(requestToken, expectedApiKey, expectedOperatorKey)
11254
+ : null;
9416
11255
  try {
9417
11256
  const { getStatuslineMeta } = require('../../scripts/statusline-meta');
9418
11257
  const meta = getStatuslineMeta({ env: process.env });
9419
- stats.tier = meta.tier;
11258
+ stats.tier = authenticatedTier || meta.tier;
9420
11259
  } catch (error) {
9421
11260
  debugApiFallback('statusline meta unavailable', error);
9422
- stats.tier = 'Pro';
11261
+ stats.tier = authenticatedTier || 'Pro';
9423
11262
  }
9424
11263
 
9425
- // Active gates for the dashboard hero cards. Connect only fetches
9426
- // /v1/feedback/stats first; without these fields Active Gates stays
9427
- // stuck on the HTML placeholder "—" until a later /v1/dashboard call
9428
- // succeeds (and never updates if that call fails).
9429
11264
  try {
9430
- const { computeGateStats } = require('../../scripts/dashboard');
9431
- const gateStats = computeGateStats();
11265
+ const { computeGateStats, computeTodayOverview } = require('../../scripts/dashboard');
11266
+ const gateStats = computeGateStats(requestFeedbackPaths.FEEDBACK_DIR);
11267
+ const setupOpts = resolveAccountSetupOptions(req, {
11268
+ tier: stats.tier,
11269
+ expectedApiKey,
11270
+ expectedOperatorKey,
11271
+ baseFeedbackDir: getFeedbackPaths().FEEDBACK_DIR,
11272
+ });
11273
+ const todayOverview = computeTodayOverview(requestFeedbackPaths.FEEDBACK_DIR, {
11274
+ gateStats,
11275
+ ...setupOpts,
11276
+ });
9432
11277
  stats.activeGateCount = Number(gateStats.totalGates) || 0;
9433
11278
  stats.gateStats = {
9434
11279
  totalGates: Number(gateStats.totalGates) || 0,
@@ -9436,7 +11281,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9436
11281
  autoCount: Number(gateStats.autoCount) || 0,
9437
11282
  blocked: Number(gateStats.blocked) || 0,
9438
11283
  warned: Number(gateStats.warned) || 0,
11284
+ blockedToday: todayOverview.gateStatusChips.blockedToday,
11285
+ warnedToday: todayOverview.gateStatusChips.warnedToday,
9439
11286
  };
11287
+ stats.todayOverview = todayOverview;
9440
11288
  } catch (error) {
9441
11289
  debugApiFallback('gate stats unavailable for feedback/stats', error);
9442
11290
  stats.activeGateCount = 0;
@@ -9446,6 +11294,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9446
11294
  autoCount: 0,
9447
11295
  blocked: 0,
9448
11296
  warned: 0,
11297
+ blockedToday: 0,
11298
+ warnedToday: 0,
9449
11299
  };
9450
11300
  }
9451
11301
 
@@ -9485,7 +11335,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9485
11335
  // Only open-ended/qualitative questions fall through to lesson retrieval +
9486
11336
  // the user's configured LOCAL model (a BYO cloud key is optional, not required).
9487
11337
  if (req.method === 'POST' && pathname === '/v1/chat') {
9488
- const body = await parseJsonBody(req);
11338
+ const body = await readProjectBody(req);
9489
11339
  const question = body.question || body.q || body.message;
9490
11340
  const normalizedChatPrompt = normalizeEnterpriseChatPrompt(question);
9491
11341
  const chatFeedbackDir = requestFeedbackPaths.FEEDBACK_DIR;
@@ -9507,6 +11357,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9507
11357
 
9508
11358
  const result = await answerDataQuestion(question, {
9509
11359
  feedbackDir: chatFeedbackDir,
11360
+ ...(requestProjectKey != null ? { projectKey: requestProjectKey } : {}),
9510
11361
  model: typeof body.model === 'string' ? body.model : undefined,
9511
11362
  apiKey: projectChatSettings.perplexityKey || projectChatSettings.geminiKey || process.env.PERPLEXITY_API_KEY || process.env.THUMBGATE_PERPLEXITY_API_KEY || process.env.GEMINI_API_KEY || process.env.THUMBGATE_GEMINI_API_KEY || process.env.GOOGLE_API_KEY || '',
9512
11363
  localEndpoint: projectChatSettings.localEndpoint || process.env.THUMBGATE_LOCAL_LLM_ENDPOINT || '',
@@ -9529,7 +11380,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9529
11380
 
9530
11381
  // Save Gemini API key from the dashboard UI
9531
11382
  if (req.method === 'POST' && pathname === '/v1/settings/gemini-key') {
9532
- const body = await parseJsonBody(req);
11383
+ const body = await readProjectBody(req);
9533
11384
  const key = String(body.key || '').trim();
9534
11385
  if (!key) {
9535
11386
  sendJson(res, 400, { ok: false, error: 'missing_key', message: 'No API key provided.' });
@@ -9629,8 +11480,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9629
11480
  }
9630
11481
  };
9631
11482
 
9632
- const onEvent = (payload) => {
9633
- safeWrite(`event: ${payload.type}\ndata: ${JSON.stringify(payload)}\n\n`);
11483
+ const subscriberKey = dataScopeKey();
11484
+ const onEvent = (envelope) => {
11485
+ if (envelope.scopeKey !== subscriberKey) return;
11486
+ const payload = envelope.payload;
11487
+ if (!matchesProject(payload, requestProjectKey)) return;
11488
+ const { accountRoot, ...publicPayload } = payload;
11489
+ safeWrite(`event: ${payload.type}\ndata: ${JSON.stringify(publicPayload)}\n\n`);
9634
11490
  };
9635
11491
  eventBus.on('broadcast', onEvent);
9636
11492
 
@@ -9662,10 +11518,11 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9662
11518
  pathname === '/v1/enterprise/data-chat/chat'
9663
11519
  || pathname === '/v1/enterprise/dialogflow/chat'
9664
11520
  )) {
9665
- const body = await parseJsonBody(req, 16 * 1024);
11521
+ const body = await readProjectBody(req, 16 * 1024);
9666
11522
  const result = await answerEnterpriseDataChat({
9667
11523
  prompt: body.prompt || body.message || body.query,
9668
11524
  feedbackDir: requestFeedbackDir,
11525
+ projectKey: requestProjectKey,
9669
11526
  parsed,
9670
11527
  });
9671
11528
  sendJson(res, 200, result);
@@ -9687,7 +11544,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9687
11544
  }
9688
11545
 
9689
11546
  if (req.method === 'POST' && pathname === '/v1/intents/plan') {
9690
- const body = await parseJsonBody(req);
11547
+ const body = await readProjectBody(req);
9691
11548
  try {
9692
11549
  const intentRouter = requirePrivateApiModule('intentRouter', 'Intent planning');
9693
11550
  const plan = intentRouter.planIntent({
@@ -9709,7 +11566,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9709
11566
  }
9710
11567
 
9711
11568
  if (req.method === 'POST' && pathname === '/v1/handoffs/start') {
9712
- const body = await parseJsonBody(req);
11569
+ const body = await readProjectBody(req);
9713
11570
  try {
9714
11571
  const intentRouter = requirePrivateApiModule('intentRouter', 'Handoff planning');
9715
11572
  const delegationRuntime = requirePrivateApiModule('delegationRuntime', 'Sequential handoffs');
@@ -9740,7 +11597,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9740
11597
  }
9741
11598
 
9742
11599
  if (req.method === 'POST' && pathname === '/v1/handoffs/complete') {
9743
- const body = await parseJsonBody(req);
11600
+ const body = await readProjectBody(req);
9744
11601
  try {
9745
11602
  const delegationRuntime = requirePrivateApiModule('delegationRuntime', 'Sequential handoffs');
9746
11603
  const result = delegationRuntime.completeHandoff({
@@ -9761,7 +11618,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9761
11618
  }
9762
11619
 
9763
11620
  if (req.method === 'POST' && pathname === '/v1/internal-agent/bootstrap') {
9764
- const body = await parseJsonBody(req);
11621
+ const body = await readProjectBody(req);
9765
11622
  try {
9766
11623
  const result = bootstrapInternalAgent({
9767
11624
  source: body.source,
@@ -9788,7 +11645,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9788
11645
  }
9789
11646
 
9790
11647
  if (req.method === 'POST' && pathname === '/v1/hosted/sandbox/dispatch') {
9791
- const body = await parseJsonBody(req);
11648
+ const body = await readProjectBody(req);
9792
11649
  try {
9793
11650
  const result = buildCloudflareSandboxPlan({
9794
11651
  source: body.source,
@@ -9827,7 +11684,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9827
11684
  }
9828
11685
 
9829
11686
  if (req.method === 'POST' && pathname === '/v1/jobs/harness') {
9830
- const body = await parseJsonBody(req);
11687
+ if (tenantDataScope()) throw createHttpError(403, 'Hosted tenant harness execution requires an execution sandbox');
11688
+ const body = await readProjectBody(req);
9831
11689
  const identifier = body.harness || body.harnessId;
9832
11690
  if (!identifier) {
9833
11691
  throw createHttpError(400, 'harness is required');
@@ -9884,7 +11742,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9884
11742
  const jobId = normalizeJobIdFromPath(pathname, '/control');
9885
11743
  if (req.method === 'POST' && jobId) {
9886
11744
  const state = readHostedJobOrThrow(jobId);
9887
- const body = await parseJsonBody(req);
11745
+ const body = await readProjectBody(req);
9888
11746
  const action = normalizeNullableText(body.action);
9889
11747
  if (!action || !JOB_CONTROL_ACTIONS.has(action)) {
9890
11748
  throw createHttpError(400, 'action must be one of pause, cancel, or resume');
@@ -9934,8 +11792,42 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9934
11792
  }
9935
11793
  }
9936
11794
 
11795
+ if (req.method === 'POST' && pathname === '/v1/gates/decide') {
11796
+ const body = await readProjectBody(req);
11797
+ if (!body.toolName) {
11798
+ throw createHttpError(400, 'Missing toolName');
11799
+ }
11800
+ const projectChatSettings = readProjectChatSettings(req, parsed);
11801
+ const { evaluateToolCallDecision } = require('../mcp-writeguard');
11802
+ const verdict = await evaluateToolCallDecision({
11803
+ toolName: body.toolName,
11804
+ toolArgs: body.toolArgs || {},
11805
+ contextText: body.contextText || '',
11806
+ rulesText: body.rulesText || '',
11807
+ images: Array.isArray(body.images) ? body.images : undefined,
11808
+ apiKey: projectChatSettings.geminiKey || undefined,
11809
+ subqApiKey: projectChatSettings.subqKey || undefined,
11810
+ provider: body.provider || undefined,
11811
+ confidenceFloor: typeof body.confidenceFloor === 'number' && Number.isFinite(body.confidenceFloor)
11812
+ ? body.confidenceFloor
11813
+ : 0.7,
11814
+ });
11815
+ const uiTarget = String((body.toolArgs && (body.toolArgs.file_path || body.toolArgs.filePath)) || '');
11816
+ const uiSource = String((body.toolArgs && (body.toolArgs.content ?? body.toolArgs.new_string ?? body.toolArgs.sourceCode)) || '');
11817
+ const hasVisual = Array.isArray(body.visualFindings) && body.visualFindings.length > 0;
11818
+ if (uiSource.length <= 262144 && ((/\.(?:html?|jsx|tsx|css)$/i.test(uiTarget) && Boolean(uiSource)) || hasVisual)) {
11819
+ const { runDesignSelfCorrectionPipeline } = require('../openshell-lovable-engine');
11820
+ verdict.designSelfCorrection = runDesignSelfCorrectionPipeline({
11821
+ sourceCode: uiSource,
11822
+ visualFindings: body.visualFindings,
11823
+ });
11824
+ }
11825
+ sendJson(res, 200, verdict);
11826
+ return;
11827
+ }
11828
+
9937
11829
  if (req.method === 'POST' && pathname === '/v1/gates/constraint') {
9938
- const body = await parseJsonBody(req);
11830
+ const body = await readProjectBody(req);
9939
11831
  if (!body.key || body.value === undefined) {
9940
11832
  throw createHttpError(400, 'Missing key or value');
9941
11833
  }
@@ -9950,7 +11842,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9950
11842
  }
9951
11843
 
9952
11844
  if (req.method === 'POST' && pathname === '/v1/gates/task-scope') {
9953
- const body = await parseJsonBody(req);
11845
+ const body = await readProjectBody(req);
9954
11846
  const scope = setTaskScope({
9955
11847
  taskId: body.taskId,
9956
11848
  summary: body.summary,
@@ -9972,7 +11864,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9972
11864
  }
9973
11865
 
9974
11866
  if (req.method === 'POST' && pathname === '/v1/gates/branch-governance') {
9975
- const body = await parseJsonBody(req);
11867
+ const body = await readProjectBody(req);
9976
11868
  const branchGovernance = setBranchGovernance({
9977
11869
  branchName: body.branchName,
9978
11870
  baseBranch: body.baseBranch,
@@ -9996,7 +11888,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9996
11888
  }
9997
11889
 
9998
11890
  if (req.method === 'POST' && pathname === '/v1/gates/protected-approval') {
9999
- const body = await parseJsonBody(req);
11891
+ const body = await readProjectBody(req);
10000
11892
  const approval = approveProtectedAction({
10001
11893
  pathGlobs: body.pathGlobs,
10002
11894
  reason: body.reason,
@@ -10009,9 +11901,9 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10009
11901
  }
10010
11902
 
10011
11903
  if (req.method === 'POST' && pathname === '/v1/task-outcomes') {
10012
- const body = await parseJsonBody(req);
11904
+ const body = await readProjectBody(req);
10013
11905
  try {
10014
- const result = recordTaskOutcome(body, { feedbackDir: requestFeedbackDir });
11906
+ const result = recordTaskOutcome(body, { feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10015
11907
  sendJson(res, result.recorded ? 201 : 200, result);
10016
11908
  } catch (error) {
10017
11909
  throw createHttpError(400, error.message);
@@ -10023,34 +11915,34 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10023
11915
  const taskId = parsed.searchParams.get('taskId');
10024
11916
  const limit = Math.max(1, Math.min(100, Number(parsed.searchParams.get('limit') || 20)));
10025
11917
  if (taskId) {
10026
- const outcome = getTaskOutcome(taskId, { feedbackDir: requestFeedbackDir });
11918
+ const outcome = getTaskOutcome(taskId, { feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10027
11919
  if (!outcome) throw createHttpError(404, `Task outcome not found: ${taskId}`);
10028
11920
  sendJson(res, 200, outcome);
10029
11921
  } else {
10030
11922
  sendJson(res, 200, {
10031
- outcomes: readTaskOutcomes({ feedbackDir: requestFeedbackDir }).slice(-limit),
11923
+ outcomes: readTaskOutcomes({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey }).slice(-limit),
10032
11924
  });
10033
11925
  }
10034
11926
  return;
10035
11927
  }
10036
11928
 
10037
11929
  if (req.method === 'GET' && pathname === '/v1/task-outcomes/metrics') {
10038
- const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir });
11930
+ const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10039
11931
  sendJson(res, 200, calculateTaskOutcomeMetrics(outcomes));
10040
11932
  return;
10041
11933
  }
10042
11934
 
10043
11935
  if (req.method === 'GET' && pathname === '/v1/task-outcomes/monitor') {
10044
- const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir });
10045
- const toolKpis = computeToolKpis({ feedbackDir: requestFeedbackDir });
11936
+ const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
11937
+ const toolKpis = computeToolKpis({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10046
11938
  sendJson(res, 200, monitorProductionSignals(outcomes, toolKpis));
10047
11939
  return;
10048
11940
  }
10049
11941
 
10050
11942
  if (req.method === 'POST' && pathname === '/v1/escalations') {
10051
- const body = await parseJsonBody(req);
11943
+ const body = await readProjectBody(req);
10052
11944
  try {
10053
- const result = requestEscalation(body, { feedbackDir: requestFeedbackDir });
11945
+ const result = requestEscalation(body, { feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10054
11946
  sendJson(res, result.recorded ? 201 : 200, result);
10055
11947
  } catch (error) {
10056
11948
  throw createHttpError(400, error.message);
@@ -10060,7 +11952,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10060
11952
 
10061
11953
  if (req.method === 'GET' && pathname === '/v1/escalations') {
10062
11954
  const status = parsed.searchParams.get('status') || undefined;
10063
- const escalations = listEscalations({ feedbackDir: requestFeedbackDir, status });
11955
+ const escalations = listEscalations({ feedbackDir: requestFeedbackDir,
11956
+ projectKey: requestProjectKey, status });
10064
11957
  sendJson(res, 200, {
10065
11958
  escalations,
10066
11959
  metrics: calculateEscalationMetrics(escalations),
@@ -10071,7 +11964,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10071
11964
  if (req.method === 'POST' && /^\/v1\/escalations\/[^/]+\/decision$/.test(pathname)) {
10072
11965
  const escalationId = decodeURIComponent(pathname.split('/')[3]);
10073
11966
  const authenticatedActor = authenticateHumanReviewer(req, humanReviewerConfig);
10074
- const body = await parseJsonBody(req);
11967
+ const body = await readProjectBody(req);
10075
11968
  try {
10076
11969
  sendJson(res, 200, decideEscalation({
10077
11970
  ...body,
@@ -10080,6 +11973,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10080
11973
  authenticatedActor,
10081
11974
  approvalSigningKey: humanReviewerConfig.key,
10082
11975
  feedbackDir: requestFeedbackDir,
11976
+ projectKey: requestProjectKey,
10083
11977
  }));
10084
11978
  } catch (error) {
10085
11979
  throw createHttpError(400, error.message);
@@ -10107,7 +12001,9 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10107
12001
  if (req.method === 'GET' && pathname === '/v1/feedback/summary') {
10108
12002
  const recent = Number(parsed.searchParams.get('recent') || 20);
10109
12003
  const summary = feedbackSummary(Number.isFinite(recent) ? recent : 20, {
12004
+ ...projectOptions,
10110
12005
  feedbackDir: requestFeedbackDir,
12006
+ projectKey: requestProjectKey,
10111
12007
  });
10112
12008
  sendJson(res, 200, { summary });
10113
12009
  return;
@@ -10128,10 +12024,12 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10128
12024
  .filter(Boolean);
10129
12025
  const lessonSearch = requirePrivateApiModule('lessonSearch', 'Lesson search');
10130
12026
  const results = lessonSearch.searchLessons(query, {
12027
+ ...projectOptions,
10131
12028
  limit: Number.isFinite(limit) ? limit : 10,
10132
12029
  category,
10133
12030
  tags,
10134
12031
  feedbackDir: requestFeedbackDir,
12032
+ projectKey: requestProjectKey,
10135
12033
  });
10136
12034
  sendJson(res, 200, results);
10137
12035
  return;
@@ -10150,11 +12048,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10150
12048
  let results;
10151
12049
  try {
10152
12050
  results = await searchThumbgateAsync({
12051
+ ...projectOptions,
10153
12052
  query,
10154
12053
  limit: Number.isFinite(limit) ? limit : 10,
10155
12054
  source,
10156
12055
  signal,
10157
12056
  feedbackDir: requestFeedbackDir,
12057
+ projectKey: requestProjectKey,
10158
12058
  metadataFilters: {
10159
12059
  tags: (parsed.searchParams.get('tags') || '').split(',').map((tag) => tag.trim()).filter(Boolean),
10160
12060
  sourceFormat: parsed.searchParams.get('sourceFormat') || undefined,
@@ -10176,7 +12076,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10176
12076
  sendJson(res, 429, { error: 'Free tier: search requires Pro. Upgrade at /pricing', code: 'PRO_REQUIRED' });
10177
12077
  return;
10178
12078
  }
10179
- const body = await parseJsonBody(req);
12079
+ const body = await readProjectBody(req);
10180
12080
  let results;
10181
12081
  try {
10182
12082
  results = await searchThumbgateAsync({
@@ -10185,6 +12085,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10185
12085
  source: body.source,
10186
12086
  signal: body.signal,
10187
12087
  feedbackDir: requestFeedbackDir,
12088
+ projectKey: requestProjectKey,
10188
12089
  metadataFilters: body.filters,
10189
12090
  queryRewrite: body.queryRewrite !== false,
10190
12091
  accessContext: requestDocumentAccessContext,
@@ -10202,6 +12103,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10202
12103
  const tag = parsed.searchParams.get('tag') || '';
10203
12104
  const results = listImportedDocuments({
10204
12105
  feedbackDir: requestFeedbackDir,
12106
+ projectKey: requestProjectKey,
10205
12107
  limit: Number.isFinite(limit) ? limit : 20,
10206
12108
  query,
10207
12109
  tag,
@@ -10219,6 +12121,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10219
12121
  }
10220
12122
  const document = readImportedDocument(documentId, {
10221
12123
  feedbackDir: requestFeedbackDir,
12124
+ projectKey: requestProjectKey,
10222
12125
  accessContext: requestDocumentAccessContext,
10223
12126
  });
10224
12127
  if (!document) {
@@ -10230,28 +12133,35 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10230
12133
  }
10231
12134
 
10232
12135
  if (req.method === 'POST' && pathname === '/v1/feedback/capture') {
12136
+ const body = await readProjectBody(req);
10233
12137
  const captureLimit = checkLimit('capture_feedback');
10234
12138
  if (!captureLimit.allowed) {
12139
+ const sentence = proWouldHaveBlockedSentence(body.whatWentWrong || body.context || '');
10235
12140
  sendProblem(res, {
10236
12141
  type: PROBLEM_TYPES.RATE_LIMIT,
10237
12142
  title: 'Free tier limit reached',
10238
12143
  status: 429,
10239
- detail: RATE_LIMIT_MESSAGE,
12144
+ detail: sentence || RATE_LIMIT_MESSAGE,
10240
12145
  });
10241
12146
  return;
10242
12147
  }
10243
- const body = await parseJsonBody(req);
10244
- // Auto-include conversation window when caller doesn't provide one
12148
+ const captureProject = projectForCapture({ ...body, projectKey: body.projectKey || requestProjectKey || undefined }, { hosted: Boolean(requestDataIdentity.partition) || !isLoopbackHost(getRequestHostHeader(req)), cwd: resolveRequestProjectDir(req, parsed) });
12149
+ // Auto-include only conversation events attributed to this project
10245
12150
  let chatHistory = Array.isArray(body.chatHistory) ? body.chatHistory : body.messages;
10246
12151
  if (!chatHistory || chatHistory.length === 0) {
10247
12152
  try {
10248
12153
  chatHistory = readRecentConversationWindow({
10249
- feedbackDir: getSafeDataDir(),
12154
+ feedbackDir: requestFeedbackDir,
12155
+ projectKey: captureProject.projectKey,
10250
12156
  limit: 10,
10251
12157
  });
10252
12158
  } catch { /* best-effort — conversation window is optional */ }
10253
12159
  }
12160
+
10254
12161
  const result = captureFeedback({
12162
+ ...captureProject,
12163
+ cwd: body.cwd,
12164
+ scope: body.scope,
10255
12165
  signal: body.signal,
10256
12166
  context: body.context || '',
10257
12167
  relatedFeedbackId: body.relatedFeedbackId,
@@ -10275,9 +12185,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10275
12185
  }
10276
12186
  : undefined,
10277
12187
  reviewOrigin: 'human',
10278
- });
12188
+ }, { feedbackDir: requestFeedbackDir, hosted: true });
10279
12189
  const actionIntegration = inferActionIntegration(body, req.headers);
10280
12190
  appendBestEffortTelemetry(requestFeedbackDir, {
12191
+ ...captureProject,
10281
12192
  eventType: chatgptActionEventType(actionIntegration, 'capture_feedback'),
10282
12193
  clientType: 'api',
10283
12194
  source: actionIntegration,
@@ -10292,8 +12203,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10292
12203
  // Fan out to any connected dashboard clients so they re-render
10293
12204
  // without polling. Non-sensitive summary only (no chat history,
10294
12205
  // no evidence blobs).
10295
- eventBus.emit('broadcast', {
12206
+ publishEvent({
10296
12207
  type: 'feedback',
12208
+ ...captureProject,
12209
+ accountRoot: requestSafeDataDir,
10297
12210
  signal: body.signal,
10298
12211
  tags: Array.isArray(body.tags) ? body.tags.slice(0, 8) : [],
10299
12212
  feedbackId: result.feedbackId,
@@ -10307,7 +12220,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10307
12220
  }
10308
12221
 
10309
12222
  if (req.method === 'POST' && pathname === '/v1/feedback/rules') {
10310
- const body = await parseJsonBody(req);
12223
+ const body = await readProjectBody(req);
10311
12224
  const minOccurrences = Number(body.minOccurrences || 2);
10312
12225
  const outputPath = body.outputPath
10313
12226
  ? resolveSafePath(body.outputPath, { safeDataDir: requestSafeDataDir })
@@ -10315,8 +12228,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10315
12228
  const result = writePreventionRules(outputPath, Number.isFinite(minOccurrences) ? minOccurrences : 2);
10316
12229
  // Tell live dashboard clients the rules file just changed so they can
10317
12230
  // re-fetch the summary without waiting on a poll tick.
10318
- eventBus.emit('broadcast', {
12231
+ publishEvent({
10319
12232
  type: 'rules-updated',
12233
+ projectKey: requestProjectKey || 'unassigned',
12234
+ accountRoot: requestSafeDataDir,
10320
12235
  path: result.path,
10321
12236
  ts: Date.now(),
10322
12237
  });
@@ -10328,7 +12243,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10328
12243
  }
10329
12244
 
10330
12245
  if (req.method === 'POST' && pathname === '/v1/skills/generate') {
10331
- const body = await parseJsonBody(req);
12246
+ const body = await readProjectBody(req);
10332
12247
  const minOccurrences = Number(body.minOccurrences || 3);
10333
12248
  const tags = Array.isArray(body.tags) ? body.tags : [];
10334
12249
  let skills = generateSkills({
@@ -10343,7 +12258,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10343
12258
  }
10344
12259
 
10345
12260
  if (req.method === 'POST' && pathname === '/v1/documents/import') {
10346
- const body = await parseJsonBody(req, 2 * 1024 * 1024);
12261
+ const body = await readProjectBody(req, 2 * 1024 * 1024);
10347
12262
  const document = importDocument({
10348
12263
  filePath: body.filePath
10349
12264
  ? resolveDocumentImportFilePath(body.filePath, {
@@ -10359,6 +12274,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10359
12274
  tags: extractTags(body.tags),
10360
12275
  proposeGates: body.proposeGates !== false,
10361
12276
  feedbackDir: requestFeedbackDir,
12277
+ projectKey: requestProjectKey,
10362
12278
  accessContext: requestDocumentAccessContext,
10363
12279
  visibility: body.visibility === 'private' ? 'private' : 'tenant',
10364
12280
  allowedPrincipals: Array.isArray(body.allowedPrincipals)
@@ -10378,13 +12294,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10378
12294
  sendJson(res, 429, { error: 'Free tier: DPO export requires Pro. Upgrade at /pricing', code: 'PRO_REQUIRED' });
10379
12295
  return;
10380
12296
  }
10381
- const body = await parseJsonBody(req);
12297
+ const body = await readProjectBody(req);
10382
12298
  const paths = resolveDpoExportPaths(body, {
10383
12299
  safeDataDir: requestSafeDataDir,
10384
12300
  fallbackMemoryLogPath: requestFeedbackPaths.MEMORY_LOG_PATH,
10385
12301
  });
10386
12302
  const wantsAsync = body.async === true || normalizeNullableText(body.mode) === 'async';
10387
12303
 
12304
+ if (wantsAsync && requestProjectKey != null) throw createHttpError(409, 'Async export is unavailable for this project');
10388
12305
  if (wantsAsync) {
10389
12306
  try {
10390
12307
  const hostedJobLauncher = requirePrivateApiModule('hostedJobLauncher', 'Hosted DPO export jobs');
@@ -10407,8 +12324,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10407
12324
  return;
10408
12325
  }
10409
12326
 
10410
- const memories = loadDpoExportMemories(paths);
10411
- const result = exportDpoFromMemories(memories);
12327
+ const memories = body.inputPath ? loadDpoExportMemories(paths).map((row) => ({ ...row, ...projectForRecord(row) })) : readProjectRows(requestFeedbackDir, 'memory-log.jsonl', projectOptions);
12328
+ const result = exportDpoFromMemories(memories, projectOptions);
10412
12329
  if (paths.outputPath) {
10413
12330
  fs.mkdirSync(path.dirname(paths.outputPath), { recursive: true });
10414
12331
  fs.writeFileSync(paths.outputPath, result.jsonl);
@@ -10432,23 +12349,23 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10432
12349
 
10433
12350
  // --- Team Lesson Export: POST /v1/lessons/export ---
10434
12351
  if (req.method === 'POST' && pathname === '/v1/lessons/export') {
10435
- const body = await parseJsonBody(req);
12352
+ const body = await readProjectBody(req);
10436
12353
  const feedbackDir = requestSafeDataDir;
10437
12354
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
10438
12355
  const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
10439
- const memories = readLessonJsonl(memoryLogPath, { maxLines: 0 });
10440
- const feedbacks = readLessonJsonl(feedbackLogPath, { maxLines: 0 });
12356
+ const memories = readProjectRows(feedbackDir, 'memory-log.jsonl', projectOptions);
12357
+ const feedbacks = readProjectRows(feedbackDir, 'feedback-log.jsonl', projectOptions);
10441
12358
 
10442
12359
  // Merge into unified lesson records
10443
12360
  const lessonMap = new Map();
10444
12361
  for (const rec of feedbacks) {
10445
- if (rec.id) lessonMap.set(rec.id, { feedbackEvent: rec, memoryRecord: null });
12362
+ if (rec.id) lessonMap.set(rec.projectKey + ':' + rec.id, { feedbackEvent: rec, memoryRecord: null });
10446
12363
  }
10447
12364
  for (const rec of memories) {
10448
12365
  if (rec.id) {
10449
- const existing = lessonMap.get(rec.id);
12366
+ const existing = lessonMap.get(rec.projectKey + ':' + rec.id);
10450
12367
  if (existing) { existing.memoryRecord = rec; }
10451
- else { lessonMap.set(rec.id, { feedbackEvent: null, memoryRecord: rec }); }
12368
+ else { lessonMap.set(rec.projectKey + ':' + rec.id, { feedbackEvent: null, memoryRecord: rec }); }
10452
12369
  }
10453
12370
  }
10454
12371
 
@@ -10474,13 +12391,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10474
12391
  version: '1.0.0',
10475
12392
  exportedAt: new Date().toISOString(),
10476
12393
  source: {
10477
- project: path.basename(feedbackDir),
10478
- hostname: require('os').hostname(),
12394
+ projectKey: requestProjectKey,
12395
+ label: requestProjectKey ? 'Project export' : 'Account export',
10479
12396
  },
10480
12397
  lessonCount: lessons.length,
10481
12398
  lessons: lessons.map((l) => {
10482
12399
  const merged = { ...(l.feedbackEvent || {}), ...(l.memoryRecord || {}) };
10483
12400
  return {
12401
+ ...projectForRecord(merged),
10484
12402
  id: merged.id,
10485
12403
  signal: normalizeLessonSignal(merged.signal),
10486
12404
  title: merged.title || merged.context || '',
@@ -10516,8 +12434,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10516
12434
 
10517
12435
  // --- Team Lesson Import: POST /v1/lessons/import ---
10518
12436
  if (req.method === 'POST' && pathname === '/v1/lessons/import') {
10519
- const body = await parseJsonBody(req);
12437
+ const body = await readProjectBody(req);
10520
12438
  const bundle = body.bundle || body;
12439
+ if (Array.isArray(bundle.lessons)) {
12440
+ for (const lesson of bundle.lessons) {
12441
+ if ((lesson.projectKey != null && !validProjectKey(lesson.projectKey)) || (requestProjectKey != null && lesson.projectKey !== requestProjectKey)) throw createHttpError(400, 'Every imported lesson must explicitly match the selected project');
12442
+ }
12443
+ }
10521
12444
  if (!bundle.lessons || !Array.isArray(bundle.lessons)) {
10522
12445
  sendJson(res, 400, { error: 'Invalid bundle: missing lessons array' });
10523
12446
  return;
@@ -10528,12 +12451,12 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10528
12451
 
10529
12452
  // Load existing IDs for dedup
10530
12453
  const existing = readLessonJsonl(feedbackLogPath, { maxLines: 0 });
10531
- const existingIds = new Set(existing.map((r) => r.id).filter(Boolean));
12454
+ const existingIds = new Set(existing.map((r) => projectForRecord(r).projectKey + ':' + (r.provenance?.originalId || r.id)));
10532
12455
  // Also dedup by title+signal content hash
10533
12456
  const existingHashes = new Set(existing.map((r) => {
10534
12457
  const t = (r.title || r.context || '').trim().toLowerCase();
10535
12458
  const s = normalizeLessonSignal(r.signal);
10536
- return `${s}|${t}`;
12459
+ return `${projectForRecord(r).projectKey}|${s}|${t}`;
10537
12460
  }).filter((h) => h !== '|'));
10538
12461
 
10539
12462
  let imported = 0;
@@ -10542,12 +12465,12 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10542
12465
 
10543
12466
  for (const lesson of bundle.lessons) {
10544
12467
  // Skip if exact ID exists
10545
- if (lesson.id && existingIds.has(lesson.id)) {
12468
+ if (lesson.id && existingIds.has(projectForRecord(lesson).projectKey + ':' + lesson.id)) {
10546
12469
  skippedDuplicate++;
10547
12470
  continue;
10548
12471
  }
10549
12472
  // Skip if same title+signal already exists (content dedup)
10550
- const contentHash = `${normalizeLessonSignal(lesson.signal)}|${(lesson.title || lesson.context || '').trim().toLowerCase()}`;
12473
+ const contentHash = `${projectForRecord(lesson).projectKey}|${normalizeLessonSignal(lesson.signal)}|${(lesson.title || lesson.context || '').trim().toLowerCase()}`;
10551
12474
  if (contentHash !== '|' && existingHashes.has(contentHash)) {
10552
12475
  skippedDuplicate++;
10553
12476
  continue;
@@ -10555,6 +12478,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10555
12478
 
10556
12479
  // Create imported record with provenance
10557
12480
  const importedRecord = {
12481
+ ...projectForRecord(lesson),
10558
12482
  id: `imported_${Date.now()}_${require("crypto").randomBytes(4).toString("hex")}`,
10559
12483
  signal: lesson.signal || 'down',
10560
12484
  title: lesson.title || '',
@@ -10576,8 +12500,9 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10576
12500
  },
10577
12501
  };
10578
12502
 
12503
+ fs.mkdirSync(feedbackDir, { recursive: true });
10579
12504
  fs.appendFileSync(feedbackLogPath, JSON.stringify(importedRecord) + '\n', 'utf8');
10580
- existingIds.add(importedRecord.id);
12505
+ existingIds.add(importedRecord.projectKey + ':' + (lesson.id || importedRecord.id));
10581
12506
  existingHashes.add(contentHash);
10582
12507
  importedIds.push(importedRecord.id);
10583
12508
  imported++;
@@ -10594,7 +12519,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10594
12519
  }
10595
12520
 
10596
12521
  if (req.method === 'POST' && pathname === '/v1/analytics/databricks/export') {
10597
- const body = await parseJsonBody(req);
12522
+ const body = await readProjectBody(req);
10598
12523
  const outputPath = body.outputPath
10599
12524
  ? resolveSafePath(body.outputPath, { safeDataDir: requestSafeDataDir })
10600
12525
  : undefined;
@@ -10604,7 +12529,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10604
12529
  }
10605
12530
 
10606
12531
  if (req.method === 'POST' && pathname === '/v1/context/construct') {
10607
- const body = await parseJsonBody(req);
12532
+ const body = await readProjectBody(req);
10608
12533
  ensureContextFs();
10609
12534
  let namespaces = [];
10610
12535
  try {
@@ -10634,7 +12559,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10634
12559
  }
10635
12560
 
10636
12561
  if (req.method === 'POST' && pathname === '/v1/context/evaluate') {
10637
- const body = await parseJsonBody(req);
12562
+ const body = await readProjectBody(req);
10638
12563
  if (!body.packId || !body.outcome) {
10639
12564
  throw createHttpError(400, 'packId and outcome are required');
10640
12565
  }
@@ -10782,7 +12707,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10782
12707
  return;
10783
12708
  }
10784
12709
 
10785
- const body = await parseJsonBody(req);
12710
+ const body = await readProjectBody(req);
10786
12711
  const keyFingerprint = fingerprintProKey(token);
10787
12712
  const alert = await sendProActivationAlert({
10788
12713
  key: token,
@@ -10822,7 +12747,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10822
12747
  return;
10823
12748
  }
10824
12749
 
10825
- const body = await parseJsonBody(req);
12750
+ const body = await readProjectBody(req);
10826
12751
  if (!body.customerId) {
10827
12752
  throw createHttpError(400, 'customerId is required');
10828
12753
  }
@@ -10947,7 +12872,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10947
12872
 
10948
12873
  const { FEEDBACK_DIR } = getFeedbackPaths();
10949
12874
  try {
10950
- const body = await parseJsonBody(req, 24 * 1024);
12875
+ const body = await readProjectBody(req, 24 * 1024);
10951
12876
  const workflowSprintIntake = requirePrivateApiModule('workflowSprintIntake', 'Workflow sprint intake');
10952
12877
  const result = workflowSprintIntake.advanceWorkflowSprintLead(body, { feedbackDir: FEEDBACK_DIR });
10953
12878
 
@@ -11041,6 +12966,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11041
12966
 
11042
12967
  // GET /v1/analytics/funnel — aggregate acquisition/activation/paid funnel metrics
11043
12968
  if (req.method === 'GET' && pathname === '/v1/analytics/funnel') {
12969
+ if (!isBillingSummaryAuthorized(req, expectedApiKey, expectedOperatorKey)) throw createHttpError(403, 'Admin or operator API key required for this endpoint.');
11044
12970
  const summary = getFunnelAnalytics();
11045
12971
  sendJson(res, 200, summary);
11046
12972
  return;
@@ -11075,8 +13001,44 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11075
13001
  return;
11076
13002
  }
11077
13003
  const { data } = dashboardResult;
11078
-
11079
- sendJson(res, 200, data);
13004
+ const reqToken = extractApiKey(req);
13005
+ let dashTier = reqToken ? resolvePaidSessionTier(reqToken, expectedApiKey, expectedOperatorKey) : null;
13006
+ if (!dashTier) {
13007
+ try {
13008
+ const { getStatuslineMeta } = require('../../scripts/statusline-meta');
13009
+ dashTier = getStatuslineMeta({ env: process.env }).tier;
13010
+ } catch {
13011
+ dashTier = 'Pro';
13012
+ }
13013
+ }
13014
+ let proWouldHaveBlocked;
13015
+ if (!isProTier() && (!reqToken || dashTier === 'Free')) {
13016
+ try {
13017
+ const { getFeedbackPaths: getScopedFeedbackPaths } = require('../../scripts/feedback-loop');
13018
+ const { PREVENTION_RULES_PATH } = getScopedFeedbackPaths({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
13019
+ if (PREVENTION_RULES_PATH && fs.existsSync(PREVENTION_RULES_PATH)) {
13020
+ const dropped = droppedRepeatFromRulesMarkdown(fs.readFileSync(PREVENTION_RULES_PATH, 'utf8'));
13021
+ const sentence = proWouldHaveBlockedSentence(dropped);
13022
+ if (sentence) proWouldHaveBlocked = sentence;
13023
+ }
13024
+ } catch (_) {}
13025
+ }
13026
+ let scopedDashboard = proWouldHaveBlocked ? { ...data, proWouldHaveBlocked } : data;
13027
+ try {
13028
+ const { computeTodayOverview } = require('../../scripts/dashboard');
13029
+ const setupOpts = resolveAccountSetupOptions(req, { tier: dashTier, expectedApiKey, expectedOperatorKey, baseFeedbackDir: getFeedbackPaths().FEEDBACK_DIR });
13030
+ scopedDashboard = {
13031
+ ...data,
13032
+ ...(proWouldHaveBlocked ? { proWouldHaveBlocked } : {}),
13033
+ tier: dashTier,
13034
+ todayOverview: computeTodayOverview(requestFeedbackDir, {
13035
+ gateStats: data.gateStats,
13036
+ gateAudit: data.gateAudit,
13037
+ ...setupOpts,
13038
+ }),
13039
+ };
13040
+ } catch { /* fallback to cached data */ }
13041
+ sendJson(res, 200, scopedDashboard);
11080
13042
  return;
11081
13043
  }
11082
13044
 
@@ -11116,9 +13078,11 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11116
13078
 
11117
13079
  // GET /v1/dashboard/review-state -- incremental review baseline and deltas
11118
13080
  if (req.method === 'GET' && pathname === '/v1/dashboard/review-state') {
11119
- const reviewState = readDashboardReviewState(requestFeedbackDir);
13081
+ const reviewState = readDashboardReviewState(requestFeedbackDir, projectOptions);
11120
13082
  const data = generateDashboard(requestFeedbackDir, {
13083
+ projectKey: requestProjectKey,
11121
13084
  reviewBaseline: reviewState,
13085
+ humanOnly: true,
11122
13086
  authContext: { tier: 'pro' },
11123
13087
  });
11124
13088
  sendJson(res, 200, {
@@ -11130,15 +13094,17 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11130
13094
 
11131
13095
  // POST /v1/dashboard/review-state -- mark current dashboard state as reviewed
11132
13096
  if (req.method === 'POST' && pathname === '/v1/dashboard/review-state') {
11133
- const body = await parseJsonBody(req);
11134
- const snapshot = buildReviewSnapshot(requestFeedbackDir);
13097
+ const body = await readProjectBody(req);
13098
+ const snapshot = buildReviewSnapshot(requestFeedbackDir, { humanOnly: true, feedbackEntries: readProjectRows(requestFeedbackDir, 'feedback-log.jsonl', projectOptions), memoryEntries: readProjectRows(requestFeedbackDir, 'memory-log.jsonl', projectOptions), auditEntries: readProjectRows(requestFeedbackDir, 'audit-trail.jsonl', projectOptions), projectRoot: null });
11135
13099
  // Override snapshot timestamp with client-provided one if available
11136
13100
  if (body?.reviewedAt) {
11137
13101
  snapshot.reviewedAt = body.reviewedAt;
11138
13102
  }
11139
- writeDashboardReviewState(requestFeedbackDir, snapshot);
13103
+ writeDashboardReviewState(requestFeedbackDir, snapshot, projectOptions);
11140
13104
  const data = generateDashboard(requestFeedbackDir, {
13105
+ projectKey: requestProjectKey,
11141
13106
  reviewBaseline: snapshot,
13107
+ humanOnly: true,
11142
13108
  authContext: { tier: 'pro' },
11143
13109
  });
11144
13110
  sendJson(res, 200, {
@@ -11148,6 +13114,38 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11148
13114
  });
11149
13115
  return;
11150
13116
  }
13117
+ // GET /v1/dashboard/agent-register -- 30-day AI governance system of record
13118
+ if (req.method === 'GET' && pathname === '/v1/dashboard/agent-register') {
13119
+ const { buildAgentRegister } = require('../../scripts/agent-action-inventory');
13120
+ const windowDays = parsed.searchParams.get('days') || 30;
13121
+ sendJson(res, 200, buildAgentRegister({ ...projectOptions, dataDir: requestFeedbackDir, windowDays, projectKey: requestProjectKey }));
13122
+ return;
13123
+ }
13124
+
13125
+ // POST /v1/dashboard/agent-register -- edit agent owner or registration status
13126
+ if (req.method === 'POST' && pathname === '/v1/dashboard/agent-register') {
13127
+ if (requestProjectKey != null) throw createHttpError(409, 'Agent ownership is an account setting; edit it in All projects');
13128
+ const body = await readProjectBody(req);
13129
+ const { isSafeKey, updateAgentRegisterEntry, buildAgentRegister } = require('../../scripts/agent-action-inventory');
13130
+ const id = typeof body?.id === 'string' ? body.id.trim() : '';
13131
+ if (!isSafeKey(id)) {
13132
+ sendJson(res, 400, { error: 'invalid_agent_id', message: 'Valid agent or surface id is required.' });
13133
+ return;
13134
+ }
13135
+ if (body?.owner !== undefined && body.owner !== null && typeof body.owner !== 'string') {
13136
+ sendJson(res, 400, { error: 'invalid_owner', message: 'Owner must be a string or null.' });
13137
+ return;
13138
+ }
13139
+ updateAgentRegisterEntry({
13140
+ dataDir: requestFeedbackDir,
13141
+ id,
13142
+ owner: body?.owner !== undefined ? body.owner : undefined,
13143
+ registered: typeof body?.registered === 'boolean' ? body.registered : undefined,
13144
+ });
13145
+ sendJson(res, 200, { ok: true, agentRegister: buildAgentRegister({ ...projectOptions, dataDir: requestFeedbackDir, projectKey: requestProjectKey }) });
13146
+ return;
13147
+ }
13148
+
11151
13149
 
11152
13150
  // GET /v1/dashboard/render-spec -- Constrained hosted dashboard JSON spec
11153
13151
  if (req.method === 'GET' && pathname === '/v1/dashboard/render-spec') {
@@ -11180,7 +13178,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11180
13178
  }
11181
13179
 
11182
13180
  if (req.method === 'POST' && pathname === '/v1/decisions/evaluate') {
11183
- const body = await parseJsonBody(req);
13181
+ const body = await readProjectBody(req);
11184
13182
  const normalizedRequestAction = normalizeProviderAction(body);
11185
13183
  const hasProviderNativeAction = Boolean(
11186
13184
  body.providerToolCall
@@ -11249,6 +13247,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11249
13247
  : scopeState.branchGovernance,
11250
13248
  },
11251
13249
  feedbackDir: requestFeedbackDir,
13250
+ projectKey: requestProjectKey,
11252
13251
  });
11253
13252
  const evaluation = recordDecisionEvaluation(report, {
11254
13253
  source: 'api',
@@ -11265,6 +13264,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11265
13264
  changedFiles,
11266
13265
  }, {
11267
13266
  feedbackDir: requestFeedbackDir,
13267
+ projectKey: requestProjectKey,
11268
13268
  });
11269
13269
  report.actionId = evaluation.actionId;
11270
13270
  if (report.decisionControl) report.decisionControl.actionId = evaluation.actionId;
@@ -11285,7 +13285,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11285
13285
  }
11286
13286
 
11287
13287
  if (req.method === 'POST' && pathname === '/v1/decisions/outcome') {
11288
- const body = await parseJsonBody(req);
13288
+ const body = await readProjectBody(req);
11289
13289
  if (!body.actionId || !body.outcome) {
11290
13290
  sendProblem(res, {
11291
13291
  type: PROBLEM_TYPES.BAD_REQUEST,
@@ -11306,6 +13306,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11306
13306
  source: 'api',
11307
13307
  }, {
11308
13308
  feedbackDir: requestFeedbackDir,
13309
+ projectKey: requestProjectKey,
11309
13310
  });
11310
13311
  sendJson(res, 200, outcome);
11311
13312
  return;
@@ -11324,14 +13325,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11324
13325
 
11325
13326
  // GET /v1/gates/stats -- Gate enforcement statistics
11326
13327
  if (req.method === 'GET' && pathname === '/v1/gates/stats') {
11327
- const stats = loadGateStats();
13328
+ const stats = requestProjectKey != null ? require('../../scripts/project-dashboard').generateProjectDashboard(requestFeedbackDir, projectOptions).gateStats : loadGateStats({ feedbackDir: requestFeedbackDir });
11328
13329
  sendJson(res, 200, stats);
11329
13330
  return;
11330
13331
  }
11331
13332
 
11332
13333
  // POST /v1/gates/satisfy -- Record evidence that a gate condition is satisfied
11333
13334
  if (req.method === 'POST' && pathname === '/v1/gates/satisfy') {
11334
- const body = await parseJsonBody(req);
13335
+ const body = await readProjectBody(req);
11335
13336
  if (!body.gateId || !body.evidence) {
11336
13337
  sendProblem(res, {
11337
13338
  type: PROBLEM_TYPES.BAD_REQUEST,
@@ -11345,6 +13346,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11345
13346
  // source the record defaults to 'cli' and the audit summary cannot
11346
13347
  // tell an HTTP unlock from a local one.
11347
13348
  const entry = satisfyCondition(body.gateId, body.evidence, null, {
13349
+ ...projectOptions,
11348
13350
  source: 'api',
11349
13351
  actor: body.actor || 'api-client',
11350
13352
  });
@@ -11354,7 +13356,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11354
13356
 
11355
13357
  // POST /v1/hermes/initialize — Bind a connectionId before turn start/end
11356
13358
  if (req.method === 'POST' && pathname === '/v1/hermes/initialize') {
11357
- const body = await parseJsonBody(req);
13359
+ const body = await readProjectBody(req);
11358
13360
  const { protocol } = getHostedHermes(requestDataIdentity);
11359
13361
  const result = protocol.initialize({
11360
13362
  connectionId: body.connectionId,
@@ -11376,7 +13378,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11376
13378
  // POST /v1/hermes/turn/start — Start turn under Hermes Platform Protocol
11377
13379
  // Fail closed until POST /v1/hermes/initialize registers the connectionId.
11378
13380
  if (req.method === 'POST' && pathname === '/v1/hermes/turn/start') {
11379
- const body = await parseJsonBody(req);
13381
+ const body = await readProjectBody(req);
11380
13382
  const { protocol } = getHostedHermes(requestDataIdentity);
11381
13383
  const result = protocol.startTurn(body);
11382
13384
  if (!result.ok) {
@@ -11395,7 +13397,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11395
13397
 
11396
13398
  // POST /v1/hermes/turn/end — End active turn under Hermes Platform Protocol
11397
13399
  if (req.method === 'POST' && pathname === '/v1/hermes/turn/end') {
11398
- const body = await parseJsonBody(req);
13400
+ const body = await readProjectBody(req);
11399
13401
  const { protocol } = getHostedHermes(requestDataIdentity);
11400
13402
  const result = protocol.endTurn(body);
11401
13403
  if (!result.ok) {
@@ -11414,7 +13416,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11414
13416
 
11415
13417
  // POST /v1/hermes/action/approve — Record human/operator approval for consequential action
11416
13418
  if (req.method === 'POST' && pathname === '/v1/hermes/action/approve') {
11417
- const body = await parseJsonBody(req);
13419
+ const body = await readProjectBody(req);
11418
13420
  const boundApproverId = resolveHermesApproverId(
11419
13421
  req,
11420
13422
  humanReviewerConfig,
@@ -11621,6 +13623,12 @@ module.exports = {
11621
13623
  partitionFeedbackPaths,
11622
13624
  buildLiveDashboardCacheKey,
11623
13625
  loadCachedLiveDashboardData,
13626
+ setGoogleOAuthFetchForTests,
13627
+ setAppleOAuthFetchForTests,
13628
+ buildAppleClientSecret,
13629
+ issueSsoPendingState,
13630
+ consumeSsoPendingState,
13631
+ clearInMemoryAuthSessionsForTests,
11624
13632
  },
11625
13633
  };
11626
13634