thumbgate 1.39.1 → 1.40.2

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 (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
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');
@@ -295,6 +314,9 @@ const {
295
314
  } = require('../../scripts/document-intake');
296
315
  const {
297
316
  checkLimit,
317
+ isProTier,
318
+ proWouldHaveBlockedSentence,
319
+ droppedRepeatFromRulesMarkdown,
298
320
  UPGRADE_MESSAGE: RATE_LIMIT_MESSAGE,
299
321
  } = require('../../scripts/rate-limiter');
300
322
  const { sendProblem, PROBLEM_TYPES } = require('../../scripts/problem-detail');
@@ -450,12 +472,12 @@ function readLessonJsonl(filePath, options) {
450
472
  return getLessonSynthesisModule().readJSONLLocal(filePath, options);
451
473
  }
452
474
 
453
- function updateLessonJsonlRecord(filePath, recordId, record) {
454
- return getLessonSynthesisModule().updateRecordInJsonl(filePath, recordId, record);
475
+ function updateLessonJsonlRecord(filePath, recordId, record, options) {
476
+ return getLessonSynthesisModule().updateRecordInJsonl(filePath, recordId, record, options);
455
477
  }
456
478
 
457
- function deleteLessonJsonlRecord(filePath, recordId) {
458
- return getLessonSynthesisModule().deleteRecordFromJsonl(filePath, recordId);
479
+ function deleteLessonJsonlRecord(filePath, recordId, options) {
480
+ return getLessonSynthesisModule().deleteRecordFromJsonl(filePath, recordId, options);
459
481
  }
460
482
 
461
483
  function serveStaticFile(res, filePath, { headOnly = false, cacheSeconds = 86400 } = {}) {
@@ -570,8 +592,25 @@ const TRACKED_LINK_TARGETS = Object.freeze({
570
592
  allowCustomerEmail: true,
571
593
  prefillStripeEmail: true,
572
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
+ },
573
612
  'bundle-49': {
574
- fallbackHref: 'https://iganapolsky.gumroad.com/l/vcrho',
613
+ fallbackHref: 'https://buy.stripe.com/dRm3cv1M85v819v6i73sJ12',
575
614
  external: true,
576
615
  botDeflectPath: '/checkout/pro',
577
616
  ctaId: 'pro_checkout_bundle_49',
@@ -584,9 +623,11 @@ const TRACKED_LINK_TARGETS = Object.freeze({
584
623
  plan_id: 'bundle_49',
585
624
  billing_cycle: 'one_time',
586
625
  },
626
+ allowCustomerEmail: true,
627
+ prefillStripeEmail: true,
587
628
  },
588
629
  'playbook-10': {
589
- fallbackHref: 'https://iganapolsky.gumroad.com/l/odrkon',
630
+ fallbackHref: 'https://buy.stripe.com/8x2fZh3UgbTw19v21R3sJ11',
590
631
  external: true,
591
632
  botDeflectPath: '/checkout/pro',
592
633
  ctaId: 'pro_checkout_playbook_10',
@@ -599,9 +640,11 @@ const TRACKED_LINK_TARGETS = Object.freeze({
599
640
  plan_id: 'playbook_10',
600
641
  billing_cycle: 'one_time',
601
642
  },
643
+ allowCustomerEmail: true,
644
+ prefillStripeEmail: true,
602
645
  },
603
646
  'playbook-999': {
604
- fallbackHref: 'https://iganapolsky.gumroad.com/l/odrkon',
647
+ fallbackHref: 'https://buy.stripe.com/8x2fZh3UgbTw19v21R3sJ11',
605
648
  external: true,
606
649
  botDeflectPath: '/checkout/pro',
607
650
  ctaId: 'pro_checkout_playbook_999',
@@ -614,6 +657,8 @@ const TRACKED_LINK_TARGETS = Object.freeze({
614
657
  plan_id: 'playbook_999',
615
658
  billing_cycle: 'one_time',
616
659
  },
660
+ allowCustomerEmail: true,
661
+ prefillStripeEmail: true,
617
662
  },
618
663
  'founding-100': {
619
664
  fallbackHref: PRO_CHECKOUT_URL,
@@ -727,6 +772,30 @@ const TRACKED_LINK_TARGETS = Object.freeze({
727
772
  plan_id: 'sprint_diagnostic',
728
773
  },
729
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
+ },
730
799
  'diagnostic-pay': {
731
800
  configUrlKey: 'sprintDiagnosticCheckoutUrl',
732
801
  fallbackHref: SPRINT_DIAGNOSTIC_CHECKOUT_URL,
@@ -979,10 +1048,10 @@ function computeConversionStats(events) {
979
1048
 
980
1049
  function getRequestedProjectSelection(req, parsed) {
981
1050
  const projectFromQuery = parsed && parsed.searchParams
982
- ? parsed.searchParams.get('project')
1051
+ ? parsed.searchParams.get('projectDir')
983
1052
  : null;
984
1053
  const projectFromHeaders = req && req.headers
985
- ? req.headers['x-thumbgate-project-dir'] || req.headers['x-thumbgate-project']
1054
+ ? req.headers['x-thumbgate-project-dir']
986
1055
  : null;
987
1056
  return projectFromQuery || projectFromHeaders || null;
988
1057
  }
@@ -1000,6 +1069,7 @@ function isProjectSelectionAllowed(req, parsed) {
1000
1069
  }
1001
1070
 
1002
1071
  function resolveRequestProjectDir(req, parsed) {
1072
+ if (tenantDataScope()) return tenantDataScope().feedbackDir;
1003
1073
  const explicitProject = getEffectiveRequestedProjectSelection(req, parsed);
1004
1074
  return resolveProjectDir({
1005
1075
  projectDir: explicitProject,
@@ -1025,6 +1095,7 @@ function extractEnvValue(content, names) {
1025
1095
  function readProjectChatSettings(req, parsed) {
1026
1096
  const settings = {
1027
1097
  geminiKey: '',
1098
+ subqKey: '',
1028
1099
  perplexityKey: '',
1029
1100
  localEndpoint: '',
1030
1101
  localModel: '',
@@ -1037,6 +1108,7 @@ function readProjectChatSettings(req, parsed) {
1037
1108
  const content = fs.readFileSync(envPath, 'utf8');
1038
1109
  settings.geminiKey = extractEnvValue(content, ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'THUMBGATE_GEMINI_API_KEY']);
1039
1110
  settings.perplexityKey = extractEnvValue(content, ['PERPLEXITY_API_KEY', 'THUMBGATE_PERPLEXITY_API_KEY']);
1111
+ settings.subqKey = extractEnvValue(content, ['SUBQ_API_KEY', 'THUMBGATE_SUBQ_API_KEY']);
1040
1112
  settings.localEndpoint = extractEnvValue(content, ['THUMBGATE_LOCAL_LLM_ENDPOINT']);
1041
1113
  settings.localModel = extractEnvValue(content, ['THUMBGATE_LOCAL_LLM_MODEL']);
1042
1114
  }
@@ -1130,25 +1202,37 @@ function partitionFeedbackPaths(paths, dataIdentity) {
1130
1202
  });
1131
1203
  }
1132
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
+
1133
1214
  function getSafeDataDir(req, parsed) {
1134
1215
  const { FEEDBACK_LOG_PATH } = getRequestFeedbackPaths(req, parsed);
1135
1216
  return path.resolve(path.dirname(FEEDBACK_LOG_PATH));
1136
1217
  }
1137
1218
 
1138
- function findRecordById(id, feedbackDir) {
1219
+ function findRecordById(id, feedbackDir, options = {}) {
1139
1220
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
1140
1221
  const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
1141
1222
  let memoryRecord = null;
1142
1223
  let feedbackEvent = null;
1143
- const memoryRecords = readLessonJsonl(memoryLogPath, { maxLines: 0 });
1224
+ const memoryRecords = readProjectRows(feedbackDir, 'memory-log.jsonl', options);
1144
1225
  for (const rec of memoryRecords) {
1145
1226
  if (rec.id === id) { memoryRecord = rec; break; }
1146
1227
  }
1147
- const feedbackRecords = readLessonJsonl(feedbackLogPath, { maxLines: 0 });
1228
+ const feedbackRecords = readProjectRows(feedbackDir, 'feedback-log.jsonl', options);
1148
1229
  for (const rec of feedbackRecords) {
1149
1230
  if (rec.id === id) { feedbackEvent = rec; break; }
1150
1231
  }
1151
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
+ }
1152
1236
  return { feedbackEvent, memoryRecord };
1153
1237
  }
1154
1238
 
@@ -1161,17 +1245,17 @@ function mergeFollowUpDetail(existingDetail, followUpText) {
1161
1245
  return `${existing}\n\nFollow-up: ${next}`;
1162
1246
  }
1163
1247
 
1164
- function updateLessonRecord(feedbackDir, lessonId, updater) {
1165
- const record = findRecordById(lessonId, feedbackDir);
1248
+ function updateLessonRecord(feedbackDir, lessonId, updater, options = {}) {
1249
+ const record = findRecordById(lessonId, feedbackDir, options);
1166
1250
  if (!record) return null;
1167
1251
  const existing = { ...(record.feedbackEvent || {}), ...(record.memoryRecord || {}) };
1168
1252
  const updated = updater({ ...existing });
1169
1253
  if (!updated) return null;
1170
- const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
1171
- const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
1172
- const updatedMemory = updateLessonJsonlRecord(memoryLogPath, lessonId, updated);
1173
- const updatedFeedback = updateLessonJsonlRecord(feedbackLogPath, lessonId, updated);
1174
- 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;
1175
1259
  return updated;
1176
1260
  }
1177
1261
 
@@ -1235,7 +1319,7 @@ function getMcpSkillManifests(hostedConfig) {
1235
1319
  },
1236
1320
  {
1237
1321
  name: 'workflow-hardening-sprint',
1238
- title: 'Workflow Hardening Sprint',
1322
+ title: 'Setup Sprint',
1239
1323
  description: 'Turn one repeated agent failure into an enforced gate with proof and rollout evidence.',
1240
1324
  triggers: ['workflow hardening', 'team rollout', 'agent governance', 'approval boundary', 'audit trail'],
1241
1325
  recommendedFlow: [
@@ -1339,7 +1423,7 @@ function getMcpSkillManifests(hostedConfig) {
1339
1423
  recommendedFlow: [
1340
1424
  'Submit advertiser interest when eligible.',
1341
1425
  'Cluster high-intent conversational queries around agent governance and repeated workflow failures.',
1342
- '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.',
1343
1427
  'Block unsupported ad and landing-page claims before spend scales.',
1344
1428
  ],
1345
1429
  contextUrl: buildPublicUrl(hostedConfig, '/llm-context.md'),
@@ -1373,7 +1457,7 @@ function getMcpApplications(hostedConfig) {
1373
1457
  },
1374
1458
  {
1375
1459
  name: 'workflow-sprint-intake',
1376
- title: 'Workflow Hardening Sprint Intake',
1460
+ title: 'Setup Sprint Intake',
1377
1461
  description: 'Submit a repeated agent failure for a proof-backed sprint.',
1378
1462
  url: buildPublicUrl(hostedConfig, '/#workflow-sprint-intake'),
1379
1463
  useWhen: 'Ready to convert mistakes into gates.',
@@ -1606,7 +1690,8 @@ function serializeCookie(name, value, options = {}) {
1606
1690
  const parts = [`${name}=${encodeURIComponent(String(value))}`];
1607
1691
  parts.push(`Path=${options.path || '/'}`);
1608
1692
  parts.push(`SameSite=${options.sameSite || 'Lax'}`);
1609
- 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}`);
1610
1695
  if (options.httpOnly !== false) parts.push('HttpOnly');
1611
1696
  if (options.secure) parts.push('Secure');
1612
1697
  return parts.join('; ');
@@ -2073,6 +2158,9 @@ function resolveBillingSummaryOptionsOrRespondProblem(res, parsed, invalidTitle)
2073
2158
 
2074
2159
  async function buildLiveDashboardData(parsed, feedbackDir) {
2075
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
+ }
2076
2164
  // Stripe/live billing can hang longer than the authenticated deploy proof
2077
2165
  // timeout (12s). Prefer live, but fail closed to local summary so /v1/dashboard
2078
2166
  // remains usable for operational proof.
@@ -2093,8 +2181,10 @@ async function buildLiveDashboardData(parsed, feedbackDir) {
2093
2181
  }
2094
2182
  const data = generateDashboard(feedbackDir, {
2095
2183
  analyticsWindow: summaryOptions,
2184
+ projectKey: parseProjectSelection(parsed.searchParams),
2096
2185
  billingSummary,
2097
2186
  billingSource,
2187
+ humanOnly: true,
2098
2188
  authContext: { tier: 'pro' },
2099
2189
  });
2100
2190
  return { summaryOptions, data };
@@ -2112,7 +2202,7 @@ function parseNonNegativeInteger(value, fallback) {
2112
2202
  function buildLiveDashboardCacheKey(parsed, feedbackDir) {
2113
2203
  const query = new URLSearchParams(parsed.searchParams);
2114
2204
  query.sort();
2115
- return `${path.resolve(feedbackDir)}?${query.toString()}`;
2205
+ return `${dataScopeKey()}:${path.resolve(feedbackDir)}?${query.toString()}`;
2116
2206
  }
2117
2207
 
2118
2208
  async function loadCachedLiveDashboardData(parsed, feedbackDir, options = {}) {
@@ -2552,6 +2642,8 @@ async function trySendLocalDashboardChat(res, parsed, feedbackDir, prompt, suffi
2552
2642
  topic: localChat.topic,
2553
2643
  provider: 'local-data',
2554
2644
  llm: 'none',
2645
+ model: 'Deterministic local data',
2646
+ privacyRoute: 'Local, no cloud',
2555
2647
  grounded: true,
2556
2648
  });
2557
2649
  return true;
@@ -2622,6 +2714,9 @@ async function answerEnterpriseDataChat({ prompt, feedbackDir, parsed }) {
2622
2714
  evaluation: guarded.evaluation,
2623
2715
  response: guarded.response,
2624
2716
  },
2717
+ provider: 'local-data',
2718
+ model: 'Deterministic local data',
2719
+ privacyRoute: 'Local, no cloud',
2625
2720
  sources: chat.sources,
2626
2721
  };
2627
2722
  }
@@ -2847,12 +2942,33 @@ function getOauthAuthorizeParamsFromForm(form, hostedConfig) {
2847
2942
  };
2848
2943
  }
2849
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
+
2850
2965
  function renderCheckoutIntentPage(prefilledEmail = '', parsed = null, options = {}) {
2851
2966
  const plausibleDomain = escapeHtmlAttribute(resolvePlausibleDataDomain({ host: 'thumbgate.ai' }));
2852
2967
  const includeHiddenAttribution = options.includeHiddenAttribution === true;
2853
2968
  const hiddenInputs = includeHiddenAttribution
2854
2969
  ? buildCheckoutHiddenAttributionInputs(parsed)
2855
2970
  : '';
2971
+ const planView = resolveCheckoutIntentPlanView(parsed);
2856
2972
  return `<!doctype html>
2857
2973
  <html lang="en">
2858
2974
  <head>
@@ -2885,10 +3001,10 @@ a{display:block;text-decoration:none}a.secondary,button.secondary{box-sizing:bor
2885
3001
  <body>
2886
3002
  <main>
2887
3003
  <div class="brand"><span class="brand-mark"></span><span>ThumbGate</span></div>
2888
- <h1>Start ThumbGate Pro</h1>
2889
- <div class="price">$19<small>/mo</small></div>
2890
- <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>
2891
- <a class="primary" 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">Pay $19/mo with Stripe →</a>
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>
2892
3008
  <form action="/checkout/pro" method="POST" data-i="pro_checkout_confirmed">
2893
3009
  ${hiddenInputs}
2894
3010
  <input type="hidden" name="confirm" value="1">
@@ -2901,8 +3017,8 @@ ${hiddenInputs}
2901
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>
2902
3018
  <a class="secondary" data-i="workflow_sprint_intake" href="/#workflow-sprint-intake">Not sure yet? Send the workflow first</a>
2903
3019
  <p class="choice-note">Cancel anytime. 7-day refund, no questions.</p>
2904
- <div class="objection-box" aria-label="Checkout feedback">
2905
- <strong>Not buying today?</strong>
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>
2906
3022
  <p class="objection-note">Tap one reason so we know what to fix. This does not sign you up.</p>
2907
3023
  <div class="objection-grid">
2908
3024
  <button type="button" data-reason="price_unclear">Price or scope is unclear</button>
@@ -2911,7 +3027,7 @@ ${hiddenInputs}
2911
3027
  <button type="button" data-reason="not_urgent">Not urgent right now</button>
2912
3028
  </div>
2913
3029
  <div class="feedback-saved" id="feedback-saved">Feedback saved.</div>
2914
- </div>
3030
+ </details>
2915
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>
2916
3032
  <p class="back"><a href="/">← Back to thumbgate.ai</a></p>
2917
3033
  </main>
@@ -3008,8 +3124,42 @@ ${hiddenInputs}
3008
3124
  });
3009
3125
  try { window.plausible && window.plausible('Checkout Pro Reason Not Buying', { props: { page:'/checkout/pro', reasonCode: reason } }); } catch(_) {}
3010
3126
  var saved = document.getElementById('feedback-saved');
3011
- if (saved) saved.style.display = 'block';
3012
- });
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
+ });
3013
3163
  });
3014
3164
  window.addEventListener('pagehide', function(){
3015
3165
  if (!submitted && !feedbackSent) {
@@ -3140,10 +3290,27 @@ function applyTrackedLinkQueryKeys(destinationUrl, params) {
3140
3290
  }
3141
3291
  }
3142
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
+
3143
3309
  function applyTrackedLinkCustomerEmail(destinationUrl, params, target) {
3144
3310
  if (!target.allowCustomerEmail) return;
3145
- const customerEmail = normalizeCheckoutCustomerEmail(params.get('customer_email'));
3311
+ const customerEmail = trackedLinkQueryEmail(params);
3146
3312
  if (!customerEmail) return;
3313
+ if (isSyntheticOrOwnerCheckoutEmail(customerEmail) && isLiveTrackedPaymentLink(destinationUrl)) return;
3147
3314
  appendQueryParam(
3148
3315
  destinationUrl,
3149
3316
  target.prefillStripeEmail ? 'prefilled_email' : 'customer_email',
@@ -3226,7 +3393,85 @@ function buildTrackedLinkAttribution(target, parsed, req, journeyState, destinat
3226
3393
  };
3227
3394
  }
3228
3395
 
3229
- 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 }) {
3230
3475
  const target = getTrackedLinkTarget(slug);
3231
3476
  if (!target) {
3232
3477
  sendJson(res, 404, {
@@ -3265,9 +3510,24 @@ function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadReques
3265
3510
 
3266
3511
  const { FEEDBACK_DIR } = getFeedbackPaths();
3267
3512
  const journeyState = resolveJourneyState(req, parsed);
3268
- const botClassification = classifyRequester(req.headers);
3269
- if (target.botDeflectPath && botClassification.isBot) {
3270
- 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);
3271
3531
  appendTrackedLinkQueryParams(deflectUrl, parsed, target);
3272
3532
  if (!isHeadRequest) {
3273
3533
  appendBestEffortTelemetry(
@@ -3296,7 +3556,63 @@ function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHeadReques
3296
3556
  res.end();
3297
3557
  return;
3298
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
+ }
3299
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
+ }
3300
3616
  const attribution = buildTrackedLinkAttribution(target, parsed, req, journeyState, destinationUrl);
3301
3617
  if (target.external) {
3302
3618
  appendQueryParam(
@@ -3399,11 +3715,22 @@ function sendText(res, statusCode, text, extraHeaders = {}, options = {}) {
3399
3715
  res.end(headOnly ? '' : text);
3400
3716
  }
3401
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
+
3402
3724
  function sendHtml(res, statusCode, html, extraHeaders = {}, options = {}) {
3403
3725
  const { headOnly = false } = options;
3726
+ const originTrialTokens = extractOriginTrialTokens(html);
3727
+ const originTrialHeader = originTrialTokens.length > 0
3728
+ ? { 'Origin-Trial': originTrialTokens.join(', ') }
3729
+ : {};
3404
3730
  res.writeHead(statusCode, {
3405
3731
  'Content-Type': 'text/html; charset=utf-8',
3406
3732
  'Content-Length': Buffer.byteLength(html),
3733
+ ...originTrialHeader,
3407
3734
  ...extraHeaders,
3408
3735
  });
3409
3736
  res.end(headOnly ? '' : html);
@@ -3416,8 +3743,9 @@ function getPublicBillingHeaders(traceId = '') {
3416
3743
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-ThumbGate-Trace-Id',
3417
3744
  'Access-Control-Expose-Headers': 'X-ThumbGate-Trace-Id',
3418
3745
  };
3419
- if (traceId) {
3420
- 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;
3421
3749
  }
3422
3750
  return headers;
3423
3751
  }
@@ -3616,6 +3944,38 @@ function normalizePublicMarketingHtml(html, runtimeConfig, requestHost) {
3616
3944
  return output;
3617
3945
  }
3618
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
+
3619
3979
  function loadPublicMarketingTemplateHtml(templatePath, runtimeConfig, pageContext = {}) {
3620
3980
  const template = fs.readFileSync(templatePath, 'utf-8');
3621
3981
  const googleSiteVerificationMeta = runtimeConfig.googleSiteVerification
@@ -3662,6 +4022,7 @@ function loadPublicMarketingTemplateHtml(templatePath, runtimeConfig, pageContex
3662
4022
  '__GTM_PLAN_URL__': 'https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/GO_TO_MARKET_REVENUE_WEDGE_2026-03.md',
3663
4023
  '__GITHUB_URL__': 'https://github.com/IgorGanapolsky/ThumbGate',
3664
4024
  '__POSTHOG_API_KEY__': runtimeConfig.posthogApiKey || '',
4025
+ '<!-- __LANDING_SSO_BUTTONS__ -->': buildLandingSsoButtonsHtml(getConfiguredSsoProviders()),
3665
4026
  });
3666
4027
  const normalized = normalizePublicMarketingHtml(rendered, runtimeConfig, pageContext.requestHost);
3667
4028
  if (!privacyOptOut) return normalized;
@@ -3861,15 +4222,66 @@ window.THUMBGATE_LESSONS_BOOTSTRAP = { enabled: ${bootstrapActive ? 'true' : 'fa
3861
4222
  </html>`;
3862
4223
  }
3863
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
+
3864
4272
  function loadDashboardPageHtml(req, expectedApiKey) {
3865
4273
  const bootstrap = resolveLocalPageBootstrap(req, expectedApiKey);
3866
4274
  const template = readOptionalPublicTemplate(DASHBOARD_PAGE_PATH);
3867
4275
  if (!template) return renderPackagedDashboardHtml(bootstrap);
3868
4276
 
3869
- return fillTemplate(template, {
3870
- '__DASHBOARD_BOOTSTRAP_KEY__': bootstrap.serializedBootstrapKey,
3871
- '__DASHBOARD_BOOTSTRAP_ENABLED__': bootstrap.bootstrapActive ? 'true' : 'false',
3872
- });
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
+ );
3873
4285
  }
3874
4286
 
3875
4287
  function loadLessonsPageHtml(req, expectedApiKey) {
@@ -3877,10 +4289,13 @@ function loadLessonsPageHtml(req, expectedApiKey) {
3877
4289
  const template = readOptionalPublicTemplate(LESSONS_PAGE_PATH);
3878
4290
  if (!template) return renderPackagedLessonsHtml(bootstrap);
3879
4291
 
3880
- return fillTemplate(template, {
3881
- '__LESSONS_BOOTSTRAP_KEY__': bootstrap.serializedBootstrapKey,
3882
- '__LESSONS_BOOTSTRAP_ENABLED__': bootstrap.bootstrapActive ? 'true' : 'false',
3883
- });
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
+ );
3884
4299
  }
3885
4300
 
3886
4301
  function esc(s) { return String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
@@ -4135,13 +4550,7 @@ a{color:#22d3ee;text-decoration:none}</style></head><body>
4135
4550
  }
4136
4551
  body { font-family: var(--font); background: var(--bg); color: var(--text); line-height: 1.6; -webkit-font-smoothing: antialiased; }
4137
4552
  .container { max-width: 860px; margin: 0 auto; padding: 0 24px; }
4138
- 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; }
4139
- nav .container { display: flex; justify-content: space-between; align-items: center; }
4140
- .nav-logo { font-weight: 700; font-size: 15px; color: var(--text); text-decoration: none; display: inline-flex; align-items: center; gap: 8px; }
4141
- .nav-logo .logo-mark { width: 28px; height: 28px; display: block; }
4142
- .nav-links { display: flex; gap: 16px; align-items: center; }
4143
- .nav-links a { color: var(--text-muted); text-decoration: none; font-size: 13px; }
4144
- .nav-links a:hover { color: var(--text); }
4553
+ ${SIGNED_IN_APP_NAV_CSS}
4145
4554
  .header-card { margin: 32px 0 24px; padding: 28px; background: var(--bg-card); border: 1px solid var(--border); border-radius: 14px; }
4146
4555
  .header-top { display: flex; align-items: center; gap: 14px; margin-bottom: 12px; }
4147
4556
  .signal-badge { font-size: 40px; }
@@ -4182,14 +4591,7 @@ nav .container { display: flex; justify-content: space-between; align-items: cen
4182
4591
  <script defer data-domain="thumbgate-production.up.railway.app" src="https://plausible.io/js/script.js"></script>
4183
4592
  </head>
4184
4593
  <body>
4185
- <nav><div class="container">
4186
- <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>
4187
- <div class="nav-links">
4188
- <a href="/dashboard">Dashboard</a>
4189
- <a href="/lessons">Lessons</a>
4190
- <a href="/">Landing Page</a>
4191
- </div>
4192
- </div></nav>
4594
+ ${renderSignedInAppNav({ activeTab: 'lessons' })}
4193
4595
 
4194
4596
  <div class="container">
4195
4597
  <div class="header-card">
@@ -4264,7 +4666,7 @@ async function saveChanges() {
4264
4666
  var detailVal = document.getElementById('editDetail').value;
4265
4667
  if ('${signal}' === 'down') { body.whatWentWrong = detailVal; } else { body.whatWorked = detailVal; }
4266
4668
  try {
4267
- var resp = await fetch('/lessons/${encodeURIComponent(lessonId)}/update', {
4669
+ var resp = await fetch(ThumbGateProjects.url('/lessons/${encodeURIComponent(lessonId)}/update'), {
4268
4670
  method: 'POST',
4269
4671
  headers: { 'Content-Type': 'application/json' },
4270
4672
  body: JSON.stringify(body)
@@ -4279,7 +4681,7 @@ async function saveChanges() {
4279
4681
  async function deleteLesson() {
4280
4682
  if (!confirm('Delete this lesson permanently?')) return;
4281
4683
  try {
4282
- var resp = await fetch('/lessons/${encodeURIComponent(lessonId)}/delete', {
4684
+ var resp = await fetch(ThumbGateProjects.url('/lessons/${encodeURIComponent(lessonId)}/delete'), {
4283
4685
  method: 'POST',
4284
4686
  headers: { 'Content-Type': 'application/json' }
4285
4687
  });
@@ -4360,7 +4762,6 @@ function renderRobotsTxt(runtimeConfig) {
4360
4762
  function renderSitemapXml(runtimeConfig) {
4361
4763
  const entries = [
4362
4764
  { path: '/', changefreq: 'weekly', priority: '1.0' },
4363
- { path: '/pro', changefreq: 'weekly', priority: '0.9' },
4364
4765
  { path: '/diagnostic', changefreq: 'weekly', priority: '0.9' },
4365
4766
  { path: '/founders', changefreq: 'weekly', priority: '0.95' },
4366
4767
  { path: '/operator-framework', changefreq: 'weekly', priority: '0.9' },
@@ -4389,7 +4790,6 @@ function renderSitemapXml(runtimeConfig) {
4389
4790
  { path: '/eval-scorecard', changefreq: 'weekly', priority: '0.9' },
4390
4791
  { path: '/evaluations', changefreq: 'weekly', priority: '0.85' },
4391
4792
  { path: '/case-studies', changefreq: 'weekly', priority: '0.9' },
4392
- { path: '/numbers', changefreq: 'weekly', priority: '0.8' },
4393
4793
  { path: '/yt', changefreq: 'weekly', priority: '0.8' },
4394
4794
  { path: '/learn/background-agent-control-layer', changefreq: 'weekly', priority: '0.85' },
4395
4795
  { path: '/learn/ac-dc-runtime-enforcement', changefreq: 'weekly', priority: '0.85' },
@@ -4760,11 +5160,12 @@ function renderCheckoutSuccessPage(runtimeConfig) {
4760
5160
  <ol>
4761
5161
  <li>Copy the environment block below into your CI or server environment.</li>
4762
5162
  <li>Use the curl example to confirm the hosted API captures an event end-to-end.</li>
4763
- <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>
4764
5164
  </ol>
4765
5165
  <pre id="env-block">Waiting for provisioning...</pre>
4766
5166
  <pre id="curl-block">Waiting for provisioning...</pre>
4767
5167
  <div class="actions">
5168
+ <a class="button secondary" id="manage-portal-btn" href="/portal">Manage subscription &rarr;</a>
4768
5169
  <a class="button" href="/">Back to landing page</a>
4769
5170
  <a class="button secondary" href="https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/VERIFICATION_EVIDENCE.md" target="_blank" rel="noreferrer">Verification evidence</a>
4770
5171
  </div>
@@ -4921,6 +5322,15 @@ function renderCheckoutSuccessPage(runtimeConfig) {
4921
5322
  : 'Key not available yet — refresh this page.';
4922
5323
  envBlock.textContent = body.nextSteps && body.nextSteps.env ? body.nextSteps.env : 'Environment snippet unavailable.';
4923
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
+ }
4924
5334
  } catch (err) {
4925
5335
  sendTelemetryOnce('checkout_session_lookup_failed', {
4926
5336
  failureCode: err?.message ? err.message : 'checkout_session_lookup_failed',
@@ -5176,6 +5586,21 @@ function renderCheckoutCancelledPage(runtimeConfig) {
5176
5586
  statusEl.textContent = selectedReason
5177
5587
  ? 'Feedback saved: ' + selectedReason.replaceAll('_', ' ') + '.'
5178
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 () {});
5179
5604
  });
5180
5605
 
5181
5606
  document.querySelectorAll('[data-recovery-offer]').forEach(function (link) {
@@ -5205,6 +5630,165 @@ function renderCheckoutCancelledPage(runtimeConfig) {
5205
5630
  </html>`;
5206
5631
  }
5207
5632
 
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
+
5638
+ return `<!DOCTYPE html>
5639
+ <html lang="en">
5640
+ <head>
5641
+ <meta charset="UTF-8" />
5642
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
5643
+ <title>Manage Subscription — ThumbGate</title>
5644
+ <meta name="robots" content="noindex,nofollow" />
5645
+ <style>
5646
+ :root {
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;
5657
+ }
5658
+ body {
5659
+ margin: 0;
5660
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
5661
+ background: var(--bg);
5662
+ color: var(--ink);
5663
+ line-height: 1.5;
5664
+ }
5665
+ main {
5666
+ max-width: 640px;
5667
+ margin: 0 auto;
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;
5692
+ }
5693
+ .card {
5694
+ background: var(--card);
5695
+ border: 1px solid var(--line);
5696
+ border-radius: var(--radius);
5697
+ padding: 24px;
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);
5732
+ }
5733
+ .actions {
5734
+ display: flex;
5735
+ gap: 12px;
5736
+ flex-wrap: wrap;
5737
+ margin-top: 20px;
5738
+ }
5739
+ button.button, a.button {
5740
+ display: inline-block;
5741
+ text-decoration: none;
5742
+ background: var(--accent);
5743
+ color: #09090b;
5744
+ padding: 12px 20px;
5745
+ border-radius: 8px;
5746
+ font-weight: 700;
5747
+ font-size: 14px;
5748
+ border: none;
5749
+ cursor: pointer;
5750
+ }
5751
+ a.button.secondary {
5752
+ background: transparent;
5753
+ color: var(--ink);
5754
+ border: 1px solid var(--line);
5755
+ }
5756
+ .muted {
5757
+ color: var(--muted);
5758
+ font-size: 13px;
5759
+ margin-top: 14px;
5760
+ }
5761
+ </style>
5762
+ <link rel="icon" type="image/png" href="/thumbgate-icon.png">
5763
+ </head>
5764
+ <body>
5765
+ <main>
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
+
5773
+ <div class="card">
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>
5786
+ </div>
5787
+ </main>
5788
+ </body>
5789
+ </html>`;
5790
+ }
5791
+
5208
5792
  function renderWorkflowSprintIntakeResultPage(runtimeConfig, { title, detail, leadId = null }) {
5209
5793
  const safeTitle = escapeHtmlAttribute(title || 'Sprint intake received');
5210
5794
  const safeDetail = escapeHtmlAttribute(detail || 'We have your workflow details and will review the proof path next.');
@@ -5287,39 +5871,6 @@ function renderWorkflowSprintIntakeResultPage(runtimeConfig, { title, detail, le
5287
5871
  </html>`;
5288
5872
  }
5289
5873
 
5290
- function renderBrokerAuditIntakeResultPage(runtimeConfig, { title, detail, leadId = null }) {
5291
- const safeTitle = escapeHtmlAttribute(title || 'Broker audit request received');
5292
- const safeDetail = escapeHtmlAttribute(detail || 'Your broker lead-flow audit request is in the queue.');
5293
- const safeLeadId = leadId ? `<p><strong>Lead ID:</strong> ${escapeHtmlAttribute(leadId)}</p>` : '';
5294
- return `<!DOCTYPE html>
5295
- <html lang="en">
5296
- <head>
5297
- <meta charset="UTF-8" />
5298
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
5299
- <title>${safeTitle}</title>
5300
- <meta name="robots" content="noindex,nofollow" />
5301
- <style>
5302
- body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: #0b1220; color: #e5edf8; line-height: 1.6; }
5303
- main { max-width: 680px; margin: 0 auto; padding: 72px 20px; }
5304
- .card { border: 1px solid #26354f; border-radius: 14px; padding: 24px; background: #111a2b; }
5305
- h1 { margin: 0 0 10px; font-size: 30px; }
5306
- p { color: #b8c5d8; }
5307
- a { color: #7dd3fc; font-weight: 700; text-decoration: none; }
5308
- </style>
5309
- </head>
5310
- <body>
5311
- <main>
5312
- <div class="card">
5313
- <h1>${safeTitle}</h1>
5314
- <p>${safeDetail}</p>
5315
- ${safeLeadId}
5316
- <p><a href="${escapeHtmlAttribute(runtimeConfig.appOrigin)}/broker-audit">Back to broker audit page</a></p>
5317
- </div>
5318
- </main>
5319
- </body>
5320
- </html>`;
5321
- }
5322
-
5323
5874
  function readBodyBuffer(req, maxBytes = 1024 * 1024) {
5324
5875
  return new Promise((resolve, reject) => {
5325
5876
  let total = 0;
@@ -5356,7 +5907,9 @@ async function parseJsonBody(req, maxBytes = 1024 * 1024) {
5356
5907
  const body = await readBodyBuffer(req, maxBytes);
5357
5908
  if (!body.length) return {};
5358
5909
  try {
5359
- 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;
5360
5913
  } catch {
5361
5914
  throw createHttpError(400, 'Invalid JSON body');
5362
5915
  }
@@ -5369,14 +5922,6 @@ async function parseFormBody(req, maxBytes = 1024 * 1024) {
5369
5922
  return Object.fromEntries(params.entries());
5370
5923
  }
5371
5924
 
5372
- function normalizeLeadEmail(value) {
5373
- const email = normalizeNullableText(value);
5374
- if (!email || !/^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{1,63}$/.test(email)) {
5375
- throw createHttpError(400, 'A valid email is required');
5376
- }
5377
- return email.toLowerCase();
5378
- }
5379
-
5380
5925
  function buildIntakeAlertRateLimitKey(req, env = process.env) {
5381
5926
  const transportPeer = String(req.socket?.remoteAddress || 'unknown');
5382
5927
  const railwayRealIp = String(req.headers['x-real-ip'] || '').trim();
@@ -5390,64 +5935,6 @@ function buildIntakeAlertRateLimitKey(req, env = process.env) {
5390
5935
  return crypto.createHash('sha256').update(clientAddress).digest('hex');
5391
5936
  }
5392
5937
 
5393
- function normalizeHttpUrl(value, fieldName) {
5394
- const raw = normalizeNullableText(value);
5395
- if (!raw) throw createHttpError(400, `${fieldName} is required`);
5396
- try {
5397
- const parsedUrl = new URL(raw);
5398
- if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
5399
- throw new Error('unsupported protocol');
5400
- }
5401
- return parsedUrl.toString();
5402
- } catch {
5403
- throw createHttpError(400, `${fieldName} must be an http(s) URL`);
5404
- }
5405
- }
5406
-
5407
- function appendBrokerAuditLead(feedbackDir, payload) {
5408
- const lead = {
5409
- leadId: createTraceId('broker_audit_lead'),
5410
- status: 'new',
5411
- offer: 'broker_lead_flow_audit_free',
5412
- requestedAt: new Date().toISOString(),
5413
- contact: {
5414
- name: normalizeNullableText(payload.name),
5415
- email: normalizeLeadEmail(payload.email),
5416
- brokerage: normalizeNullableText(payload.brokerage),
5417
- website: normalizeHttpUrl(payload.website, 'website'),
5418
- },
5419
- qualification: {
5420
- suspectedLeak: normalizeNullableText(payload.suspected_leak || payload.suspectedLeak),
5421
- },
5422
- attribution: {
5423
- traceId: payload.traceId,
5424
- acquisitionId: payload.acquisitionId,
5425
- visitorId: payload.visitorId,
5426
- sessionId: payload.sessionId,
5427
- source: payload.source,
5428
- utmSource: payload.utmSource,
5429
- utmMedium: payload.utmMedium,
5430
- utmCampaign: payload.utmCampaign,
5431
- utmContent: payload.utmContent,
5432
- utmTerm: payload.utmTerm,
5433
- ctaId: payload.ctaId,
5434
- ctaPlacement: payload.ctaPlacement,
5435
- page: payload.page,
5436
- landingPath: payload.landingPath,
5437
- referrer: payload.referrer,
5438
- referrerHost: payload.referrerHost,
5439
- },
5440
- };
5441
-
5442
- if (!lead.contact.name) throw createHttpError(400, 'name is required');
5443
- if (!lead.contact.brokerage) throw createHttpError(400, 'brokerage is required');
5444
-
5445
- const leadsPath = path.join(feedbackDir, 'broker-audit-leads.jsonl');
5446
- fs.mkdirSync(path.dirname(leadsPath), { recursive: true });
5447
- fs.appendFileSync(leadsPath, `${JSON.stringify(lead)}\n`, 'utf8');
5448
- return lead;
5449
- }
5450
-
5451
5938
  function parseOptionalObject(input, name) {
5452
5939
  if (input == null) return {};
5453
5940
  if (typeof input === 'object' && !Array.isArray(input)) return input;
@@ -5513,22 +6000,900 @@ function extractBearerToken(req) {
5513
6000
  return auth.startsWith('Bearer ') ? auth.slice(7) : '';
5514
6001
  }
5515
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
+
5516
6882
  function extractApiKey(req) {
5517
6883
  const bearerToken = extractBearerToken(req);
5518
6884
  if (bearerToken) {
5519
6885
  return bearerToken;
5520
6886
  }
5521
6887
 
5522
- const alternateHeader = req.headers['x-api-key'];
6888
+ const alternateHeader = req.headers['x-api-key'] || req.headers['x-thumbgate-key'];
5523
6889
  if (Array.isArray(alternateHeader)) {
5524
- return String(alternateHeader[0] || '').trim();
5525
- }
5526
-
5527
- if (typeof alternateHeader === 'string') {
6890
+ const first = String(alternateHeader[0] || '').trim();
6891
+ if (first) return first;
6892
+ } else if (typeof alternateHeader === 'string' && alternateHeader.trim()) {
5528
6893
  return alternateHeader.trim();
5529
6894
  }
5530
6895
 
5531
- return '';
6896
+ return resolvePaidAuthSessionKey(req);
5532
6897
  }
5533
6898
 
5534
6899
  /**
@@ -5615,10 +6980,13 @@ function isBillingSummaryAuthorized(req, expectedAdminKey, expectedOperatorKey)
5615
6980
  /** Read-only paths the operator key may access (CLI dashboard / CFO / north-star). */
5616
6981
  const OPERATOR_READONLY_GET_PATHS = new Set([
5617
6982
  '/v1/billing/summary',
6983
+ '/v1/analytics/funnel',
5618
6984
  '/v1/dashboard',
5619
6985
  '/v1/dashboard/render-spec',
5620
6986
  '/v1/dashboard/ai-inventory',
5621
6987
  '/v1/dashboard/review-state',
6988
+ '/v1/dashboard/agent-register',
6989
+ '/v1/feedback/stats',
5622
6990
  '/v1/intake/workflow-sprint/queue',
5623
6991
  '/v1/task-outcomes/monitor',
5624
6992
  ]);
@@ -5641,8 +7009,8 @@ function extractTags(input) {
5641
7009
  }
5642
7010
 
5643
7011
  function resolveSafePath(inputPath, { mustExist = false, safeDataDir } = {}) {
5644
- const allowExternal = process.env.THUMBGATE_ALLOW_EXTERNAL_PATHS === 'true';
5645
- 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 || '')));
5646
7014
  const SAFE_DATA_DIR = safeDataDir || getSafeDataDir();
5647
7015
  const inSafeRoot = resolved === SAFE_DATA_DIR || resolved.startsWith(`${SAFE_DATA_DIR}${path.sep}`);
5648
7016
 
@@ -5777,17 +7145,113 @@ function resolveDocumentImportFilePath(inputPath, options = {}) {
5777
7145
  return resolved;
5778
7146
  }
5779
7147
 
5780
- 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 = {} } = {}) {
5781
7162
  const expectedApiKey = getExpectedApiKey();
5782
7163
  const expectedOperatorKey = getExpectedOperatorKey();
5783
7164
  const humanReviewerConfig = getHumanReviewerConfig(expectedApiKey, expectedOperatorKey);
5784
7165
 
7166
+ const adminRuntime = ownerAdmin.createRuntimeObservations();
7167
+ const observedRequests = new WeakSet();
5785
7168
  const eventBus = new EventEmitter();
5786
7169
  eventBus.setMaxListeners(200);
7170
+ const publishEvent = (payload) => eventBus.emit('broadcast', { scopeKey: dataScopeKey(), payload });
5787
7171
 
5788
7172
  return http.createServer(async (req, res) => {
5789
7173
  const parsed = new URL(req.url, 'http://localhost');
5790
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);
5791
7255
  const isHeadRequest = req.method === 'HEAD';
5792
7256
  const isGetLikeRequest = req.method === 'GET' || isHeadRequest;
5793
7257
  const publicOrigin = getPublicOrigin(req);
@@ -5803,6 +7267,7 @@ function createApiServer() {
5803
7267
 
5804
7268
  // PostHog reverse proxy -- bypasses ad blockers.
5805
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; }
5806
7271
  if (pathname.startsWith('/ingest')) {
5807
7272
  const posthogPath = getPosthogProxyPath(pathname);
5808
7273
  if (!isAllowedPosthogProxyPath(posthogPath)) {
@@ -6189,7 +7654,11 @@ function createApiServer() {
6189
7654
  // throws — the mailer returns a structured result even on failure, so
6190
7655
  // the signup still succeeds if Resend is down or RESEND_API_KEY is unset.
6191
7656
  Promise.resolve()
6192
- .then(() => resendMailer.sendNewsletterWelcomeEmail({ to: email }))
7657
+ .then(() => resendMailer.dispatchSignupWelcomeEmail({
7658
+ to: email,
7659
+ source: attribution.source || 'newsletter',
7660
+ feedbackDir: getFeedbackPaths().FEEDBACK_DIR,
7661
+ }))
6193
7662
  .then((result) => {
6194
7663
  if (!result || result.sent !== true) {
6195
7664
  console.warn('[newsletter] welcome email not sent:', email, result && result.reason);
@@ -6316,7 +7785,7 @@ function createApiServer() {
6316
7785
  }
6317
7786
  }
6318
7787
  }
6319
- serveTrackedLinkRedirect({
7788
+ await serveTrackedLinkRedirect({
6320
7789
  req,
6321
7790
  res,
6322
7791
  parsed: trackedParsed,
@@ -6468,7 +7937,7 @@ async function addContext(){
6468
7937
  sendJson(res, 401, { error: 'Authentication required to update human feedback' });
6469
7938
  return;
6470
7939
  }
6471
- const body = await parseJsonBody(req);
7940
+ const body = await readProjectBody(req);
6472
7941
  const signal = body.signal;
6473
7942
  const context = typeof body.context === 'string' ? body.context.trim() : '';
6474
7943
  const relatedFeedbackId = typeof body.relatedFeedbackId === 'string' ? body.relatedFeedbackId.trim() : '';
@@ -6499,7 +7968,7 @@ async function addContext(){
6499
7968
  tags: nextTags,
6500
7969
  [detailField]: mergeFollowUpDetail(existing[detailField], context),
6501
7970
  };
6502
- });
7971
+ }, { projectKey: requestProjectKey });
6503
7972
  if (!updated) {
6504
7973
  sendJson(res, 404, { error: 'Related lesson not found' });
6505
7974
  return;
@@ -6523,7 +7992,7 @@ async function addContext(){
6523
7992
  return;
6524
7993
  }
6525
7994
 
6526
- if (isGetLikeRequest && pathname === '/dashboard') {
7995
+ if (isGetLikeRequest && (pathname === '/dashboard' || pathname === '/cloud')) {
6527
7996
  try {
6528
7997
  const html = loadDashboardPageHtml(req, expectedApiKey);
6529
7998
  sendHtml(res, 200, html, {}, { headOnly: isHeadRequest });
@@ -6533,13 +8002,158 @@ async function addContext(){
6533
8002
  return;
6534
8003
  }
6535
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
+ }
6536
8150
  // --- Lesson detail: POST /lessons/:id/update ---
6537
8151
  const lessonUpdateMatch = pathname.match(/^\/lessons\/([^/]+)\/update$/);
6538
8152
  if (req.method === 'POST' && lessonUpdateMatch) {
6539
8153
  const lessonId = decodeURIComponent(lessonUpdateMatch[1]);
6540
8154
  const feedbackDir = requestSafeDataDir;
6541
- const body = await parseJsonBody(req);
6542
- const record = findRecordById(lessonId, feedbackDir);
8155
+ const body = await readProjectBody(req);
8156
+ const record = findRecordById(lessonId, feedbackDir, projectOptions);
6543
8157
  if (!record) {
6544
8158
  sendJson(res, 404, { error: 'Record not found' });
6545
8159
  return;
@@ -6556,7 +8170,7 @@ async function addContext(){
6556
8170
  if (body.whatWentWrong !== undefined) next.whatWentWrong = body.whatWentWrong;
6557
8171
  if (body.whatWorked !== undefined) next.whatWorked = body.whatWorked;
6558
8172
  return next;
6559
- });
8173
+ }, projectOptions);
6560
8174
  if (!updated) {
6561
8175
  sendJson(res, 404, { error: 'Record not found' });
6562
8176
  return;
@@ -6572,9 +8186,12 @@ async function addContext(){
6572
8186
  const feedbackDir = requestSafeDataDir;
6573
8187
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
6574
8188
  const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
6575
- const deletedMemory = deleteLessonJsonlRecord(memoryLogPath, lessonId);
6576
- const deletedFeedback = deleteLessonJsonlRecord(feedbackLogPath, lessonId);
6577
- 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) {
6578
8195
  sendJson(res, 404, { error: 'Record not found' });
6579
8196
  return;
6580
8197
  }
@@ -6587,12 +8204,12 @@ async function addContext(){
6587
8204
  if (isGetLikeRequest && lessonDetailMatch && lessonDetailMatch[1] !== '') {
6588
8205
  const lessonId = decodeURIComponent(lessonDetailMatch[1]);
6589
8206
  const feedbackDir = requestSafeDataDir;
6590
- const record = findRecordById(lessonId, feedbackDir);
8207
+ const record = findRecordById(lessonId, feedbackDir, projectOptions);
6591
8208
  if (!record) {
6592
8209
  sendHtml(res, 404, renderLessonDetailHtml(null, lessonId));
6593
8210
  return;
6594
8211
  }
6595
- 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 });
6596
8213
  return;
6597
8214
  }
6598
8215
 
@@ -6963,22 +8580,12 @@ async function addContext(){
6963
8580
  }
6964
8581
 
6965
8582
  if (isGetLikeRequest && (pathname === '/numbers' || pathname === '/numbers.html')) {
6966
- // Route through servePublicMarketingPage so landing_page_view telemetry
6967
- // + funnel-events.jsonl `discovery/landing_view` get captured with UTM
6968
- // attribution — critical for Zernio social CTAs that target /numbers.
6969
- try {
6970
- servePublicMarketingPage({
6971
- req,
6972
- res,
6973
- parsed,
6974
- hostedConfig,
6975
- isHeadRequest,
6976
- renderHtml: () => fs.readFileSync(NUMBERS_PAGE_PATH, 'utf-8'),
6977
- extraTelemetry: { pageType: 'numbers' },
6978
- });
6979
- } catch {
6980
- sendJson(res, 404, { error: 'Numbers page not found' });
6981
- }
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();
6982
8589
  return;
6983
8590
  }
6984
8591
 
@@ -7605,6 +9212,7 @@ async function addContext(){
7605
9212
  }
7606
9213
 
7607
9214
  try {
9215
+ analyticsMetadata.entryRoute = 'checkout_pro_confirm';
7608
9216
  const result = await createCheckoutSession({
7609
9217
  successUrl: buildCheckoutFallbackUrl(
7610
9218
  buildHostedSuccessUrl(hostedConfig.appOrigin, traceId),
@@ -7711,6 +9319,15 @@ async function addContext(){
7711
9319
  });
7712
9320
  res.end();
7713
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
+ }
7714
9331
  appendBestEffortTelemetry(FEEDBACK_DIR, {
7715
9332
  eventType: 'checkout_api_failed',
7716
9333
  clientType: 'web',
@@ -7793,26 +9410,71 @@ async function addContext(){
7793
9410
  return;
7794
9411
  }
7795
9412
 
7796
- if (isGetLikeRequest && pathname === '/broker-audit') {
7797
- // Public-facing broker lead-flow audit landing page. Wedge for the
7798
- // real-estate broker outreach. Static HTML served from src/api/static.
7799
- try {
7800
- const host = getSafePublicRequestHost(req);
7801
- const html = normalizePublicMarketingHtml(fillTemplate(fs.readFileSync(
7802
- path.resolve(__dirname, '../../assets/static/broker-audit.html'),
7803
- 'utf8'
7804
- ), {
7805
- '__POSTHOG_API_KEY__': hostedConfig.posthogApiKey || '',
7806
- }), hostedConfig, host);
7807
- if (isHeadRequest) {
7808
- 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
+ }));
7809
9468
  return;
7810
9469
  }
7811
- sendHtml(res, 200, html);
7812
- } catch (err) {
7813
- console.error('broker-audit page read failed:', err?.message);
7814
- sendJson(res, 500, { error: 'broker-audit page unavailable' });
7815
9470
  }
9471
+
9472
+ if (isHeadRequest) {
9473
+ sendHtml(res, 200, renderManageSubscriptionPage(hostedConfig), {}, { headOnly: true });
9474
+ return;
9475
+ }
9476
+
9477
+ sendHtml(res, 200, renderManageSubscriptionPage(hostedConfig));
7816
9478
  return;
7817
9479
  }
7818
9480
 
@@ -8163,8 +9825,9 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8163
9825
  if (req.method === 'POST' && pathname === '/v1/telemetry/ping') {
8164
9826
  const { FEEDBACK_DIR } = getFeedbackPaths();
8165
9827
  try {
8166
- const payload = await parseJsonBody(req, 16 * 1024);
8167
- 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));
8168
9831
  } catch (err) {
8169
9832
  try {
8170
9833
  appendDiagnosticRecord({
@@ -8211,7 +9874,14 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8211
9874
  res.end();
8212
9875
  return;
8213
9876
  }
8214
-
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
+ }
8215
9885
  if (req.method === 'GET' && pathname === '/v1/metrics/real') {
8216
9886
  const bd = require('../../scripts/bot-detection');
8217
9887
  const { FEEDBACK_DIR: metricsDir } = getFeedbackPaths();
@@ -8275,6 +9945,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8275
9945
  const ACTIVE_EVENTS = new Set([
8276
9946
  'cli_capture', 'cli_recall', 'cli_stats',
8277
9947
  'activation_first_rule_promoted',
9948
+ 'first_blocked_tool_call',
8278
9949
  ]);
8279
9950
  const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1000;
8280
9951
  const last30 = classified.filter(e => {
@@ -8318,11 +9989,13 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8318
9989
  ci: classified.filter(e => e.visitorType === 'ci').length,
8319
9990
  uniqueInstalls: uniqueInstallIds.size,
8320
9991
  activeInstalls: allTimeActiveInstalls.size,
9992
+ firstBlockedToolCall: summarizeFirstBlockEvents(classified),
8321
9993
  },
8322
9994
  last30Days: {
8323
9995
  uniqueInstalls: new Set(last30.filter(e => e.installId).map(e => e.installId)).size,
8324
9996
  activeInstalls: activeInstalls30d.size,
8325
9997
  uniqueSessions: uniqueSessions30d.size,
9998
+ firstBlockedToolCall: summarizeFirstBlockEvents(last30),
8326
9999
  },
8327
10000
  last7Days: {
8328
10001
  total: recent.length,
@@ -8333,6 +10006,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8333
10006
  uniqueInstalls: recentInstallIds.size,
8334
10007
  activeInstalls: activeInstalls7d.size,
8335
10008
  uniqueSessions: uniqueSessions7d.size,
10009
+ firstBlockedToolCall: summarizeFirstBlockEvents(recent),
8336
10010
  },
8337
10011
  byEventType,
8338
10012
  byVisitorType,
@@ -8627,130 +10301,6 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8627
10301
  return;
8628
10302
  }
8629
10303
 
8630
- if (req.method === 'OPTIONS' && pathname === '/v1/intake/broker-audit') {
8631
- sendPublicBillingPreflight(res);
8632
- return;
8633
- }
8634
-
8635
- if (req.method === 'POST' && pathname === '/v1/intake/broker-audit') {
8636
- const { FEEDBACK_DIR } = getFeedbackPaths();
8637
- const traceId = createTraceId('broker_audit');
8638
- const journeyState = resolveJourneyState(req, parsed);
8639
- const referrerAttribution = buildReferrerAttribution(req);
8640
- const contentType = String(req.headers['content-type'] || '').toLowerCase();
8641
- const isFormSubmission = contentType.includes('application/x-www-form-urlencoded');
8642
- try {
8643
- const body = isFormSubmission
8644
- ? await parseFormBody(req, 16 * 1024)
8645
- : await parseJsonBody(req, 16 * 1024);
8646
- const lead = appendBrokerAuditLead(FEEDBACK_DIR, {
8647
- ...body,
8648
- traceId: body.traceId || traceId,
8649
- acquisitionId: body.acquisitionId || journeyState.acquisitionId,
8650
- visitorId: body.visitorId || journeyState.visitorId,
8651
- sessionId: body.sessionId || journeyState.sessionId,
8652
- page: body.page || referrerAttribution.page || '/broker-audit',
8653
- landingPath: body.landingPath || referrerAttribution.landingPath || '/broker-audit',
8654
- ctaId: body.ctaId || 'broker_audit_form',
8655
- ctaPlacement: body.ctaPlacement || 'broker_audit',
8656
- source: body.source || body.utmSource || referrerAttribution.source || 'website',
8657
- utmSource: body.utmSource || body.source || referrerAttribution.utmSource || 'website',
8658
- utmMedium: body.utmMedium || referrerAttribution.utmMedium || 'broker_audit',
8659
- utmCampaign: body.utmCampaign || referrerAttribution.utmCampaign || 'broker_audit_free',
8660
- utmContent: body.utmContent || referrerAttribution.utmContent || null,
8661
- utmTerm: body.utmTerm || referrerAttribution.utmTerm || null,
8662
- referrerHost: body.referrerHost || referrerAttribution.referrerHost || null,
8663
- referrer: body.referrer || referrerAttribution.referrer || null,
8664
- });
8665
-
8666
- appendBestEffortTelemetry(FEEDBACK_DIR, {
8667
- eventType: 'broker_audit_lead_submitted',
8668
- clientType: 'web',
8669
- traceId: lead.attribution.traceId,
8670
- acquisitionId: lead.attribution.acquisitionId,
8671
- visitorId: lead.attribution.visitorId,
8672
- sessionId: lead.attribution.sessionId,
8673
- source: lead.attribution.source,
8674
- utmSource: lead.attribution.utmSource,
8675
- utmMedium: lead.attribution.utmMedium,
8676
- utmCampaign: lead.attribution.utmCampaign,
8677
- utmContent: lead.attribution.utmContent,
8678
- utmTerm: lead.attribution.utmTerm,
8679
- ctaId: lead.attribution.ctaId,
8680
- ctaPlacement: lead.attribution.ctaPlacement,
8681
- page: lead.attribution.page,
8682
- landingPath: lead.attribution.landingPath,
8683
- referrerHost: lead.attribution.referrerHost,
8684
- referrer: lead.attribution.referrer,
8685
- }, req.headers, 'broker_audit_lead_submitted');
8686
-
8687
- if (isFormSubmission && !wantsJson(req, parsed)) {
8688
- sendHtml(
8689
- res,
8690
- 201,
8691
- renderBrokerAuditIntakeResultPage(hostedConfig, {
8692
- title: 'Broker audit request received',
8693
- detail: 'Your free broker lead-flow audit request is captured. The next step is the 1-page PDF with the specific lead leaks.',
8694
- leadId: lead.leadId,
8695
- }),
8696
- journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}
8697
- );
8698
- return;
8699
- }
8700
-
8701
- sendJson(res, 201, {
8702
- ok: true,
8703
- leadId: lead.leadId,
8704
- status: lead.status,
8705
- offer: lead.offer,
8706
- nextStep: 'deliver_1_page_pdf',
8707
- }, {
8708
- ...getPublicBillingHeaders(lead.attribution.traceId),
8709
- ...(journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}),
8710
- });
8711
- } catch (err) {
8712
- appendBestEffortTelemetry(FEEDBACK_DIR, {
8713
- eventType: 'broker_audit_lead_failed',
8714
- clientType: 'web',
8715
- traceId,
8716
- acquisitionId: journeyState.acquisitionId,
8717
- visitorId: journeyState.visitorId,
8718
- sessionId: journeyState.sessionId,
8719
- source: referrerAttribution.source || 'website',
8720
- utmSource: referrerAttribution.utmSource || 'website',
8721
- utmMedium: referrerAttribution.utmMedium || 'broker_audit',
8722
- utmCampaign: referrerAttribution.utmCampaign || 'broker_audit_free',
8723
- ctaId: 'broker_audit_form',
8724
- ctaPlacement: 'broker_audit',
8725
- page: referrerAttribution.page || '/broker-audit',
8726
- landingPath: referrerAttribution.landingPath || '/broker-audit',
8727
- referrerHost: referrerAttribution.referrerHost,
8728
- referrer: referrerAttribution.referrer,
8729
- failureCode: err?.message ? err.message : 'broker_audit_lead_failed',
8730
- httpStatus: err && err.statusCode ? err.statusCode : null,
8731
- }, req.headers, 'broker_audit_lead_failed');
8732
- if (isFormSubmission && !wantsJson(req, parsed)) {
8733
- sendHtml(
8734
- res,
8735
- err.statusCode || 500,
8736
- renderBrokerAuditIntakeResultPage(hostedConfig, {
8737
- title: 'Broker audit request failed',
8738
- detail: err.message || 'Unable to capture broker audit request.',
8739
- }),
8740
- journeyState.setCookieHeaders.length ? { 'Set-Cookie': journeyState.setCookieHeaders } : {}
8741
- );
8742
- return;
8743
- }
8744
- sendProblem(res, {
8745
- type: !err.statusCode || err.statusCode >= 500 ? PROBLEM_TYPES.INTERNAL : PROBLEM_TYPES.BAD_REQUEST,
8746
- title: !err.statusCode || err.statusCode >= 500 ? 'Internal Server Error' : 'Request Error',
8747
- status: err.statusCode || 500,
8748
- detail: err.message || 'Unable to capture broker audit request.',
8749
- }, getPublicBillingHeaders(traceId));
8750
- }
8751
- return;
8752
- }
8753
-
8754
10304
  if (req.method === 'POST' && pathname === '/v1/intake/workflow-sprint') {
8755
10305
  const { FEEDBACK_DIR } = getFeedbackPaths();
8756
10306
  const traceId = createTraceId('sprint_intake');
@@ -8762,10 +10312,16 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8762
10312
  try {
8763
10313
  const body = isFormSubmission
8764
10314
  ? await parseFormBody(req, 24 * 1024)
8765
- : await parseJsonBody(req, 24 * 1024);
10315
+ : await readProjectBody(req, 24 * 1024);
8766
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';
8767
10320
  const leadPayload = {
8768
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),
8769
10325
  traceId: body.traceId || traceId,
8770
10326
  acquisitionId: body.acquisitionId || journeyState.acquisitionId,
8771
10327
  visitorId: body.visitorId || journeyState.visitorId,
@@ -8774,7 +10330,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8774
10330
  landingPath: body.landingPath || referrerAttribution.landingPath || '/',
8775
10331
  ctaId: body.ctaId || 'workflow_sprint_intake',
8776
10332
  ctaPlacement: body.ctaPlacement || 'workflow_sprint',
8777
- planId: body.planId || 'sprint',
10333
+ planId: body.planId || (isFreeTierLimitLead ? 'diagnostic' : 'sprint'),
8778
10334
  source: body.source || body.utmSource || referrerAttribution.source || 'website',
8779
10335
  utmSource: body.utmSource || body.source || referrerAttribution.utmSource || 'website',
8780
10336
  utmMedium: body.utmMedium || referrerAttribution.utmMedium || 'workflow_sprint_intake',
@@ -8790,6 +10346,15 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8790
10346
  referrerHost: body.referrerHost || referrerAttribution.referrerHost || null,
8791
10347
  referrer: body.referrer || referrerAttribution.referrer || null,
8792
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
+ }
8793
10358
  const intakeReservation = workflowSprintIntake.reserveWorkflowSprintIntake(leadPayload, {
8794
10359
  feedbackDir: FEEDBACK_DIR,
8795
10360
  rateLimitKey: buildIntakeAlertRateLimitKey(req),
@@ -8801,8 +10366,7 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8801
10366
  }
8802
10367
  const lead = workflowSprintIntake.appendWorkflowSprintLead(leadPayload, { feedbackDir: FEEDBACK_DIR });
8803
10368
 
8804
- appendBestEffortTelemetry(FEEDBACK_DIR, {
8805
- eventType: 'workflow_sprint_lead_submitted',
10369
+ const leadTelemetryBase = {
8806
10370
  clientType: 'web',
8807
10371
  traceId: lead.attribution.traceId,
8808
10372
  acquisitionId: lead.attribution.acquisitionId,
@@ -8828,8 +10392,11 @@ a{color:#8b9}</style></head><body><form class="card" method="post" action="/oaut
8828
10392
  landingPath: lead.attribution.landingPath,
8829
10393
  referrerHost: lead.attribution.referrerHost,
8830
10394
  referrer: lead.attribution.referrer,
8831
- }, req.headers, 'workflow_sprint_lead_submitted');
8832
-
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
+ }
8833
10400
  const leadNotification = await workflowSprintIntake.notifyWorkflowSprintLead(lead, {
8834
10401
  sendEmailImpl: resendMailer.sendEmail,
8835
10402
  rateLimitKey: buildIntakeAlertRateLimitKey(req),
@@ -9355,20 +10922,145 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9355
10922
  return;
9356
10923
  }
9357
10924
 
9358
- 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')) {
9359
10926
  sendPublicBillingPreflight(res);
9360
10927
  return;
9361
10928
  }
9362
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
+
9363
11046
  // Public checkout session creation for top-of-funnel acquisition.
9364
11047
  if (req.method === 'POST' && pathname === '/v1/billing/checkout') {
9365
11048
  try {
9366
- const body = await parseJsonBody(req);
11049
+ const body = await readProjectBody(req);
9367
11050
  const traceId = body.traceId || createTraceId('checkout');
9368
11051
  const responseHeaders = getPublicBillingHeaders(traceId);
9369
- const analyticsMetadata = buildCheckoutAttributionMetadata(body, req, traceId);
11052
+ const analyticsMetadata = {
11053
+ ...buildCheckoutAttributionMetadata(body, req, traceId),
11054
+ entryRoute: 'api_billing_checkout',
11055
+ };
9370
11056
  const offerSummary = resolveCheckoutOfferSummary(analyticsMetadata);
9371
-
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
+
9372
11064
  const result = await createCheckoutSession({
9373
11065
  successUrl: body.successUrl || buildCheckoutFallbackUrl(
9374
11066
  buildHostedSuccessUrl(hostedConfig.appOrigin, traceId),
@@ -9378,7 +11070,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9378
11070
  buildHostedCancelUrl(hostedConfig.appOrigin, traceId),
9379
11071
  analyticsMetadata,
9380
11072
  ),
9381
- customerEmail: body.customerEmail,
11073
+ customerEmail,
9382
11074
  installId: body.installId,
9383
11075
  traceId,
9384
11076
  metadata: analyticsMetadata,
@@ -9452,6 +11144,45 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9452
11144
  return;
9453
11145
  }
9454
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
+
9455
11186
  // Catch non-API GET requests that didn't match any public page route above.
9456
11187
  // Without this, /about, /docs, /demo etc. fall through to the API auth gate
9457
11188
  // and return a raw JSON 401 instead of a user-friendly 404.
@@ -9485,38 +11216,64 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9485
11216
  });
9486
11217
  return;
9487
11218
  }
9488
- requestFeedbackPaths = partitionFeedbackPaths(requestFeedbackPaths, requestDataIdentity);
11219
+ const baseFeedbackPaths = requestDataIdentity.partition ? getFeedbackPaths() : requestFeedbackPaths;
11220
+ requestFeedbackPaths = currentDataScope()
11221
+ ? getFeedbackPaths({ feedbackDir: currentDataScope().lexicalRoot })
11222
+ : partitionFeedbackPaths(baseFeedbackPaths, requestDataIdentity);
9489
11223
  requestFeedbackDir = requestFeedbackPaths.FEEDBACK_DIR;
9490
11224
  requestSafeDataDir = path.resolve(requestFeedbackDir);
9491
11225
  requestDocumentAccessContext = requestDataIdentity.accessContext;
9492
11226
 
9493
- // Usage metering — record request for billing keys (not static THUMBGATE_API_KEY)
9494
- const _token = extractBearerToken(req);
9495
- if (_token && _token !== expectedApiKey) {
9496
- recordUsage(_token);
9497
- }
9498
-
9499
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
+ }
9500
11247
  if (req.method === 'GET' && pathname === '/v1/feedback/stats') {
9501
11248
  const stats = shouldAggregateFeedback()
9502
11249
  ? computeAggregateFeedbackStats({ feedbackDir: requestFeedbackPaths.FEEDBACK_DIR })
9503
11250
  : analyzeFeedback(requestFeedbackPaths.FEEDBACK_LOG_PATH, { humanOnly: true });
11251
+ const requestToken = extractApiKey(req);
11252
+ const authenticatedTier = requestToken
11253
+ ? resolvePaidSessionTier(requestToken, expectedApiKey, expectedOperatorKey)
11254
+ : null;
9504
11255
  try {
9505
11256
  const { getStatuslineMeta } = require('../../scripts/statusline-meta');
9506
11257
  const meta = getStatuslineMeta({ env: process.env });
9507
- stats.tier = meta.tier;
11258
+ stats.tier = authenticatedTier || meta.tier;
9508
11259
  } catch (error) {
9509
11260
  debugApiFallback('statusline meta unavailable', error);
9510
- stats.tier = 'Pro';
11261
+ stats.tier = authenticatedTier || 'Pro';
9511
11262
  }
9512
11263
 
9513
- // Active gates for the dashboard hero cards. Connect only fetches
9514
- // /v1/feedback/stats first; without these fields Active Gates stays
9515
- // stuck on the HTML placeholder "—" until a later /v1/dashboard call
9516
- // succeeds (and never updates if that call fails).
9517
11264
  try {
9518
- const { computeGateStats } = require('../../scripts/dashboard');
9519
- 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
+ });
9520
11277
  stats.activeGateCount = Number(gateStats.totalGates) || 0;
9521
11278
  stats.gateStats = {
9522
11279
  totalGates: Number(gateStats.totalGates) || 0,
@@ -9524,7 +11281,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9524
11281
  autoCount: Number(gateStats.autoCount) || 0,
9525
11282
  blocked: Number(gateStats.blocked) || 0,
9526
11283
  warned: Number(gateStats.warned) || 0,
11284
+ blockedToday: todayOverview.gateStatusChips.blockedToday,
11285
+ warnedToday: todayOverview.gateStatusChips.warnedToday,
9527
11286
  };
11287
+ stats.todayOverview = todayOverview;
9528
11288
  } catch (error) {
9529
11289
  debugApiFallback('gate stats unavailable for feedback/stats', error);
9530
11290
  stats.activeGateCount = 0;
@@ -9534,6 +11294,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9534
11294
  autoCount: 0,
9535
11295
  blocked: 0,
9536
11296
  warned: 0,
11297
+ blockedToday: 0,
11298
+ warnedToday: 0,
9537
11299
  };
9538
11300
  }
9539
11301
 
@@ -9573,7 +11335,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9573
11335
  // Only open-ended/qualitative questions fall through to lesson retrieval +
9574
11336
  // the user's configured LOCAL model (a BYO cloud key is optional, not required).
9575
11337
  if (req.method === 'POST' && pathname === '/v1/chat') {
9576
- const body = await parseJsonBody(req);
11338
+ const body = await readProjectBody(req);
9577
11339
  const question = body.question || body.q || body.message;
9578
11340
  const normalizedChatPrompt = normalizeEnterpriseChatPrompt(question);
9579
11341
  const chatFeedbackDir = requestFeedbackPaths.FEEDBACK_DIR;
@@ -9595,6 +11357,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9595
11357
 
9596
11358
  const result = await answerDataQuestion(question, {
9597
11359
  feedbackDir: chatFeedbackDir,
11360
+ ...(requestProjectKey != null ? { projectKey: requestProjectKey } : {}),
9598
11361
  model: typeof body.model === 'string' ? body.model : undefined,
9599
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 || '',
9600
11363
  localEndpoint: projectChatSettings.localEndpoint || process.env.THUMBGATE_LOCAL_LLM_ENDPOINT || '',
@@ -9617,7 +11380,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9617
11380
 
9618
11381
  // Save Gemini API key from the dashboard UI
9619
11382
  if (req.method === 'POST' && pathname === '/v1/settings/gemini-key') {
9620
- const body = await parseJsonBody(req);
11383
+ const body = await readProjectBody(req);
9621
11384
  const key = String(body.key || '').trim();
9622
11385
  if (!key) {
9623
11386
  sendJson(res, 400, { ok: false, error: 'missing_key', message: 'No API key provided.' });
@@ -9717,8 +11480,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9717
11480
  }
9718
11481
  };
9719
11482
 
9720
- const onEvent = (payload) => {
9721
- 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`);
9722
11490
  };
9723
11491
  eventBus.on('broadcast', onEvent);
9724
11492
 
@@ -9750,10 +11518,11 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9750
11518
  pathname === '/v1/enterprise/data-chat/chat'
9751
11519
  || pathname === '/v1/enterprise/dialogflow/chat'
9752
11520
  )) {
9753
- const body = await parseJsonBody(req, 16 * 1024);
11521
+ const body = await readProjectBody(req, 16 * 1024);
9754
11522
  const result = await answerEnterpriseDataChat({
9755
11523
  prompt: body.prompt || body.message || body.query,
9756
11524
  feedbackDir: requestFeedbackDir,
11525
+ projectKey: requestProjectKey,
9757
11526
  parsed,
9758
11527
  });
9759
11528
  sendJson(res, 200, result);
@@ -9775,7 +11544,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9775
11544
  }
9776
11545
 
9777
11546
  if (req.method === 'POST' && pathname === '/v1/intents/plan') {
9778
- const body = await parseJsonBody(req);
11547
+ const body = await readProjectBody(req);
9779
11548
  try {
9780
11549
  const intentRouter = requirePrivateApiModule('intentRouter', 'Intent planning');
9781
11550
  const plan = intentRouter.planIntent({
@@ -9797,7 +11566,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9797
11566
  }
9798
11567
 
9799
11568
  if (req.method === 'POST' && pathname === '/v1/handoffs/start') {
9800
- const body = await parseJsonBody(req);
11569
+ const body = await readProjectBody(req);
9801
11570
  try {
9802
11571
  const intentRouter = requirePrivateApiModule('intentRouter', 'Handoff planning');
9803
11572
  const delegationRuntime = requirePrivateApiModule('delegationRuntime', 'Sequential handoffs');
@@ -9828,7 +11597,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9828
11597
  }
9829
11598
 
9830
11599
  if (req.method === 'POST' && pathname === '/v1/handoffs/complete') {
9831
- const body = await parseJsonBody(req);
11600
+ const body = await readProjectBody(req);
9832
11601
  try {
9833
11602
  const delegationRuntime = requirePrivateApiModule('delegationRuntime', 'Sequential handoffs');
9834
11603
  const result = delegationRuntime.completeHandoff({
@@ -9849,7 +11618,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9849
11618
  }
9850
11619
 
9851
11620
  if (req.method === 'POST' && pathname === '/v1/internal-agent/bootstrap') {
9852
- const body = await parseJsonBody(req);
11621
+ const body = await readProjectBody(req);
9853
11622
  try {
9854
11623
  const result = bootstrapInternalAgent({
9855
11624
  source: body.source,
@@ -9876,7 +11645,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9876
11645
  }
9877
11646
 
9878
11647
  if (req.method === 'POST' && pathname === '/v1/hosted/sandbox/dispatch') {
9879
- const body = await parseJsonBody(req);
11648
+ const body = await readProjectBody(req);
9880
11649
  try {
9881
11650
  const result = buildCloudflareSandboxPlan({
9882
11651
  source: body.source,
@@ -9915,7 +11684,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9915
11684
  }
9916
11685
 
9917
11686
  if (req.method === 'POST' && pathname === '/v1/jobs/harness') {
9918
- 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);
9919
11689
  const identifier = body.harness || body.harnessId;
9920
11690
  if (!identifier) {
9921
11691
  throw createHttpError(400, 'harness is required');
@@ -9972,7 +11742,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
9972
11742
  const jobId = normalizeJobIdFromPath(pathname, '/control');
9973
11743
  if (req.method === 'POST' && jobId) {
9974
11744
  const state = readHostedJobOrThrow(jobId);
9975
- const body = await parseJsonBody(req);
11745
+ const body = await readProjectBody(req);
9976
11746
  const action = normalizeNullableText(body.action);
9977
11747
  if (!action || !JOB_CONTROL_ACTIONS.has(action)) {
9978
11748
  throw createHttpError(400, 'action must be one of pause, cancel, or resume');
@@ -10022,8 +11792,42 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10022
11792
  }
10023
11793
  }
10024
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
+
10025
11829
  if (req.method === 'POST' && pathname === '/v1/gates/constraint') {
10026
- const body = await parseJsonBody(req);
11830
+ const body = await readProjectBody(req);
10027
11831
  if (!body.key || body.value === undefined) {
10028
11832
  throw createHttpError(400, 'Missing key or value');
10029
11833
  }
@@ -10038,7 +11842,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10038
11842
  }
10039
11843
 
10040
11844
  if (req.method === 'POST' && pathname === '/v1/gates/task-scope') {
10041
- const body = await parseJsonBody(req);
11845
+ const body = await readProjectBody(req);
10042
11846
  const scope = setTaskScope({
10043
11847
  taskId: body.taskId,
10044
11848
  summary: body.summary,
@@ -10060,7 +11864,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10060
11864
  }
10061
11865
 
10062
11866
  if (req.method === 'POST' && pathname === '/v1/gates/branch-governance') {
10063
- const body = await parseJsonBody(req);
11867
+ const body = await readProjectBody(req);
10064
11868
  const branchGovernance = setBranchGovernance({
10065
11869
  branchName: body.branchName,
10066
11870
  baseBranch: body.baseBranch,
@@ -10084,7 +11888,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10084
11888
  }
10085
11889
 
10086
11890
  if (req.method === 'POST' && pathname === '/v1/gates/protected-approval') {
10087
- const body = await parseJsonBody(req);
11891
+ const body = await readProjectBody(req);
10088
11892
  const approval = approveProtectedAction({
10089
11893
  pathGlobs: body.pathGlobs,
10090
11894
  reason: body.reason,
@@ -10097,9 +11901,9 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10097
11901
  }
10098
11902
 
10099
11903
  if (req.method === 'POST' && pathname === '/v1/task-outcomes') {
10100
- const body = await parseJsonBody(req);
11904
+ const body = await readProjectBody(req);
10101
11905
  try {
10102
- const result = recordTaskOutcome(body, { feedbackDir: requestFeedbackDir });
11906
+ const result = recordTaskOutcome(body, { feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10103
11907
  sendJson(res, result.recorded ? 201 : 200, result);
10104
11908
  } catch (error) {
10105
11909
  throw createHttpError(400, error.message);
@@ -10111,34 +11915,34 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10111
11915
  const taskId = parsed.searchParams.get('taskId');
10112
11916
  const limit = Math.max(1, Math.min(100, Number(parsed.searchParams.get('limit') || 20)));
10113
11917
  if (taskId) {
10114
- const outcome = getTaskOutcome(taskId, { feedbackDir: requestFeedbackDir });
11918
+ const outcome = getTaskOutcome(taskId, { feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10115
11919
  if (!outcome) throw createHttpError(404, `Task outcome not found: ${taskId}`);
10116
11920
  sendJson(res, 200, outcome);
10117
11921
  } else {
10118
11922
  sendJson(res, 200, {
10119
- outcomes: readTaskOutcomes({ feedbackDir: requestFeedbackDir }).slice(-limit),
11923
+ outcomes: readTaskOutcomes({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey }).slice(-limit),
10120
11924
  });
10121
11925
  }
10122
11926
  return;
10123
11927
  }
10124
11928
 
10125
11929
  if (req.method === 'GET' && pathname === '/v1/task-outcomes/metrics') {
10126
- const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir });
11930
+ const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10127
11931
  sendJson(res, 200, calculateTaskOutcomeMetrics(outcomes));
10128
11932
  return;
10129
11933
  }
10130
11934
 
10131
11935
  if (req.method === 'GET' && pathname === '/v1/task-outcomes/monitor') {
10132
- const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir });
10133
- const toolKpis = computeToolKpis({ feedbackDir: requestFeedbackDir });
11936
+ const outcomes = readTaskOutcomes({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
11937
+ const toolKpis = computeToolKpis({ feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10134
11938
  sendJson(res, 200, monitorProductionSignals(outcomes, toolKpis));
10135
11939
  return;
10136
11940
  }
10137
11941
 
10138
11942
  if (req.method === 'POST' && pathname === '/v1/escalations') {
10139
- const body = await parseJsonBody(req);
11943
+ const body = await readProjectBody(req);
10140
11944
  try {
10141
- const result = requestEscalation(body, { feedbackDir: requestFeedbackDir });
11945
+ const result = requestEscalation(body, { feedbackDir: requestFeedbackDir, projectKey: requestProjectKey });
10142
11946
  sendJson(res, result.recorded ? 201 : 200, result);
10143
11947
  } catch (error) {
10144
11948
  throw createHttpError(400, error.message);
@@ -10148,7 +11952,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10148
11952
 
10149
11953
  if (req.method === 'GET' && pathname === '/v1/escalations') {
10150
11954
  const status = parsed.searchParams.get('status') || undefined;
10151
- const escalations = listEscalations({ feedbackDir: requestFeedbackDir, status });
11955
+ const escalations = listEscalations({ feedbackDir: requestFeedbackDir,
11956
+ projectKey: requestProjectKey, status });
10152
11957
  sendJson(res, 200, {
10153
11958
  escalations,
10154
11959
  metrics: calculateEscalationMetrics(escalations),
@@ -10159,7 +11964,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10159
11964
  if (req.method === 'POST' && /^\/v1\/escalations\/[^/]+\/decision$/.test(pathname)) {
10160
11965
  const escalationId = decodeURIComponent(pathname.split('/')[3]);
10161
11966
  const authenticatedActor = authenticateHumanReviewer(req, humanReviewerConfig);
10162
- const body = await parseJsonBody(req);
11967
+ const body = await readProjectBody(req);
10163
11968
  try {
10164
11969
  sendJson(res, 200, decideEscalation({
10165
11970
  ...body,
@@ -10168,6 +11973,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10168
11973
  authenticatedActor,
10169
11974
  approvalSigningKey: humanReviewerConfig.key,
10170
11975
  feedbackDir: requestFeedbackDir,
11976
+ projectKey: requestProjectKey,
10171
11977
  }));
10172
11978
  } catch (error) {
10173
11979
  throw createHttpError(400, error.message);
@@ -10195,7 +12001,9 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10195
12001
  if (req.method === 'GET' && pathname === '/v1/feedback/summary') {
10196
12002
  const recent = Number(parsed.searchParams.get('recent') || 20);
10197
12003
  const summary = feedbackSummary(Number.isFinite(recent) ? recent : 20, {
12004
+ ...projectOptions,
10198
12005
  feedbackDir: requestFeedbackDir,
12006
+ projectKey: requestProjectKey,
10199
12007
  });
10200
12008
  sendJson(res, 200, { summary });
10201
12009
  return;
@@ -10216,10 +12024,12 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10216
12024
  .filter(Boolean);
10217
12025
  const lessonSearch = requirePrivateApiModule('lessonSearch', 'Lesson search');
10218
12026
  const results = lessonSearch.searchLessons(query, {
12027
+ ...projectOptions,
10219
12028
  limit: Number.isFinite(limit) ? limit : 10,
10220
12029
  category,
10221
12030
  tags,
10222
12031
  feedbackDir: requestFeedbackDir,
12032
+ projectKey: requestProjectKey,
10223
12033
  });
10224
12034
  sendJson(res, 200, results);
10225
12035
  return;
@@ -10238,11 +12048,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10238
12048
  let results;
10239
12049
  try {
10240
12050
  results = await searchThumbgateAsync({
12051
+ ...projectOptions,
10241
12052
  query,
10242
12053
  limit: Number.isFinite(limit) ? limit : 10,
10243
12054
  source,
10244
12055
  signal,
10245
12056
  feedbackDir: requestFeedbackDir,
12057
+ projectKey: requestProjectKey,
10246
12058
  metadataFilters: {
10247
12059
  tags: (parsed.searchParams.get('tags') || '').split(',').map((tag) => tag.trim()).filter(Boolean),
10248
12060
  sourceFormat: parsed.searchParams.get('sourceFormat') || undefined,
@@ -10264,7 +12076,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10264
12076
  sendJson(res, 429, { error: 'Free tier: search requires Pro. Upgrade at /pricing', code: 'PRO_REQUIRED' });
10265
12077
  return;
10266
12078
  }
10267
- const body = await parseJsonBody(req);
12079
+ const body = await readProjectBody(req);
10268
12080
  let results;
10269
12081
  try {
10270
12082
  results = await searchThumbgateAsync({
@@ -10273,6 +12085,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10273
12085
  source: body.source,
10274
12086
  signal: body.signal,
10275
12087
  feedbackDir: requestFeedbackDir,
12088
+ projectKey: requestProjectKey,
10276
12089
  metadataFilters: body.filters,
10277
12090
  queryRewrite: body.queryRewrite !== false,
10278
12091
  accessContext: requestDocumentAccessContext,
@@ -10290,6 +12103,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10290
12103
  const tag = parsed.searchParams.get('tag') || '';
10291
12104
  const results = listImportedDocuments({
10292
12105
  feedbackDir: requestFeedbackDir,
12106
+ projectKey: requestProjectKey,
10293
12107
  limit: Number.isFinite(limit) ? limit : 20,
10294
12108
  query,
10295
12109
  tag,
@@ -10307,6 +12121,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10307
12121
  }
10308
12122
  const document = readImportedDocument(documentId, {
10309
12123
  feedbackDir: requestFeedbackDir,
12124
+ projectKey: requestProjectKey,
10310
12125
  accessContext: requestDocumentAccessContext,
10311
12126
  });
10312
12127
  if (!document) {
@@ -10318,28 +12133,35 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10318
12133
  }
10319
12134
 
10320
12135
  if (req.method === 'POST' && pathname === '/v1/feedback/capture') {
12136
+ const body = await readProjectBody(req);
10321
12137
  const captureLimit = checkLimit('capture_feedback');
10322
12138
  if (!captureLimit.allowed) {
12139
+ const sentence = proWouldHaveBlockedSentence(body.whatWentWrong || body.context || '');
10323
12140
  sendProblem(res, {
10324
12141
  type: PROBLEM_TYPES.RATE_LIMIT,
10325
12142
  title: 'Free tier limit reached',
10326
12143
  status: 429,
10327
- detail: RATE_LIMIT_MESSAGE,
12144
+ detail: sentence || RATE_LIMIT_MESSAGE,
10328
12145
  });
10329
12146
  return;
10330
12147
  }
10331
- const body = await parseJsonBody(req);
10332
- // 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
10333
12150
  let chatHistory = Array.isArray(body.chatHistory) ? body.chatHistory : body.messages;
10334
12151
  if (!chatHistory || chatHistory.length === 0) {
10335
12152
  try {
10336
12153
  chatHistory = readRecentConversationWindow({
10337
- feedbackDir: getSafeDataDir(),
12154
+ feedbackDir: requestFeedbackDir,
12155
+ projectKey: captureProject.projectKey,
10338
12156
  limit: 10,
10339
12157
  });
10340
12158
  } catch { /* best-effort — conversation window is optional */ }
10341
12159
  }
12160
+
10342
12161
  const result = captureFeedback({
12162
+ ...captureProject,
12163
+ cwd: body.cwd,
12164
+ scope: body.scope,
10343
12165
  signal: body.signal,
10344
12166
  context: body.context || '',
10345
12167
  relatedFeedbackId: body.relatedFeedbackId,
@@ -10363,9 +12185,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10363
12185
  }
10364
12186
  : undefined,
10365
12187
  reviewOrigin: 'human',
10366
- });
12188
+ }, { feedbackDir: requestFeedbackDir, hosted: true });
10367
12189
  const actionIntegration = inferActionIntegration(body, req.headers);
10368
12190
  appendBestEffortTelemetry(requestFeedbackDir, {
12191
+ ...captureProject,
10369
12192
  eventType: chatgptActionEventType(actionIntegration, 'capture_feedback'),
10370
12193
  clientType: 'api',
10371
12194
  source: actionIntegration,
@@ -10380,8 +12203,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10380
12203
  // Fan out to any connected dashboard clients so they re-render
10381
12204
  // without polling. Non-sensitive summary only (no chat history,
10382
12205
  // no evidence blobs).
10383
- eventBus.emit('broadcast', {
12206
+ publishEvent({
10384
12207
  type: 'feedback',
12208
+ ...captureProject,
12209
+ accountRoot: requestSafeDataDir,
10385
12210
  signal: body.signal,
10386
12211
  tags: Array.isArray(body.tags) ? body.tags.slice(0, 8) : [],
10387
12212
  feedbackId: result.feedbackId,
@@ -10395,7 +12220,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10395
12220
  }
10396
12221
 
10397
12222
  if (req.method === 'POST' && pathname === '/v1/feedback/rules') {
10398
- const body = await parseJsonBody(req);
12223
+ const body = await readProjectBody(req);
10399
12224
  const minOccurrences = Number(body.minOccurrences || 2);
10400
12225
  const outputPath = body.outputPath
10401
12226
  ? resolveSafePath(body.outputPath, { safeDataDir: requestSafeDataDir })
@@ -10403,8 +12228,10 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10403
12228
  const result = writePreventionRules(outputPath, Number.isFinite(minOccurrences) ? minOccurrences : 2);
10404
12229
  // Tell live dashboard clients the rules file just changed so they can
10405
12230
  // re-fetch the summary without waiting on a poll tick.
10406
- eventBus.emit('broadcast', {
12231
+ publishEvent({
10407
12232
  type: 'rules-updated',
12233
+ projectKey: requestProjectKey || 'unassigned',
12234
+ accountRoot: requestSafeDataDir,
10408
12235
  path: result.path,
10409
12236
  ts: Date.now(),
10410
12237
  });
@@ -10416,7 +12243,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10416
12243
  }
10417
12244
 
10418
12245
  if (req.method === 'POST' && pathname === '/v1/skills/generate') {
10419
- const body = await parseJsonBody(req);
12246
+ const body = await readProjectBody(req);
10420
12247
  const minOccurrences = Number(body.minOccurrences || 3);
10421
12248
  const tags = Array.isArray(body.tags) ? body.tags : [];
10422
12249
  let skills = generateSkills({
@@ -10431,7 +12258,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10431
12258
  }
10432
12259
 
10433
12260
  if (req.method === 'POST' && pathname === '/v1/documents/import') {
10434
- const body = await parseJsonBody(req, 2 * 1024 * 1024);
12261
+ const body = await readProjectBody(req, 2 * 1024 * 1024);
10435
12262
  const document = importDocument({
10436
12263
  filePath: body.filePath
10437
12264
  ? resolveDocumentImportFilePath(body.filePath, {
@@ -10447,6 +12274,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10447
12274
  tags: extractTags(body.tags),
10448
12275
  proposeGates: body.proposeGates !== false,
10449
12276
  feedbackDir: requestFeedbackDir,
12277
+ projectKey: requestProjectKey,
10450
12278
  accessContext: requestDocumentAccessContext,
10451
12279
  visibility: body.visibility === 'private' ? 'private' : 'tenant',
10452
12280
  allowedPrincipals: Array.isArray(body.allowedPrincipals)
@@ -10466,13 +12294,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10466
12294
  sendJson(res, 429, { error: 'Free tier: DPO export requires Pro. Upgrade at /pricing', code: 'PRO_REQUIRED' });
10467
12295
  return;
10468
12296
  }
10469
- const body = await parseJsonBody(req);
12297
+ const body = await readProjectBody(req);
10470
12298
  const paths = resolveDpoExportPaths(body, {
10471
12299
  safeDataDir: requestSafeDataDir,
10472
12300
  fallbackMemoryLogPath: requestFeedbackPaths.MEMORY_LOG_PATH,
10473
12301
  });
10474
12302
  const wantsAsync = body.async === true || normalizeNullableText(body.mode) === 'async';
10475
12303
 
12304
+ if (wantsAsync && requestProjectKey != null) throw createHttpError(409, 'Async export is unavailable for this project');
10476
12305
  if (wantsAsync) {
10477
12306
  try {
10478
12307
  const hostedJobLauncher = requirePrivateApiModule('hostedJobLauncher', 'Hosted DPO export jobs');
@@ -10495,8 +12324,8 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10495
12324
  return;
10496
12325
  }
10497
12326
 
10498
- const memories = loadDpoExportMemories(paths);
10499
- 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);
10500
12329
  if (paths.outputPath) {
10501
12330
  fs.mkdirSync(path.dirname(paths.outputPath), { recursive: true });
10502
12331
  fs.writeFileSync(paths.outputPath, result.jsonl);
@@ -10520,23 +12349,23 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10520
12349
 
10521
12350
  // --- Team Lesson Export: POST /v1/lessons/export ---
10522
12351
  if (req.method === 'POST' && pathname === '/v1/lessons/export') {
10523
- const body = await parseJsonBody(req);
12352
+ const body = await readProjectBody(req);
10524
12353
  const feedbackDir = requestSafeDataDir;
10525
12354
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
10526
12355
  const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
10527
- const memories = readLessonJsonl(memoryLogPath, { maxLines: 0 });
10528
- const feedbacks = readLessonJsonl(feedbackLogPath, { maxLines: 0 });
12356
+ const memories = readProjectRows(feedbackDir, 'memory-log.jsonl', projectOptions);
12357
+ const feedbacks = readProjectRows(feedbackDir, 'feedback-log.jsonl', projectOptions);
10529
12358
 
10530
12359
  // Merge into unified lesson records
10531
12360
  const lessonMap = new Map();
10532
12361
  for (const rec of feedbacks) {
10533
- 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 });
10534
12363
  }
10535
12364
  for (const rec of memories) {
10536
12365
  if (rec.id) {
10537
- const existing = lessonMap.get(rec.id);
12366
+ const existing = lessonMap.get(rec.projectKey + ':' + rec.id);
10538
12367
  if (existing) { existing.memoryRecord = rec; }
10539
- else { lessonMap.set(rec.id, { feedbackEvent: null, memoryRecord: rec }); }
12368
+ else { lessonMap.set(rec.projectKey + ':' + rec.id, { feedbackEvent: null, memoryRecord: rec }); }
10540
12369
  }
10541
12370
  }
10542
12371
 
@@ -10562,13 +12391,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10562
12391
  version: '1.0.0',
10563
12392
  exportedAt: new Date().toISOString(),
10564
12393
  source: {
10565
- project: path.basename(feedbackDir),
10566
- hostname: require('os').hostname(),
12394
+ projectKey: requestProjectKey,
12395
+ label: requestProjectKey ? 'Project export' : 'Account export',
10567
12396
  },
10568
12397
  lessonCount: lessons.length,
10569
12398
  lessons: lessons.map((l) => {
10570
12399
  const merged = { ...(l.feedbackEvent || {}), ...(l.memoryRecord || {}) };
10571
12400
  return {
12401
+ ...projectForRecord(merged),
10572
12402
  id: merged.id,
10573
12403
  signal: normalizeLessonSignal(merged.signal),
10574
12404
  title: merged.title || merged.context || '',
@@ -10604,8 +12434,13 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10604
12434
 
10605
12435
  // --- Team Lesson Import: POST /v1/lessons/import ---
10606
12436
  if (req.method === 'POST' && pathname === '/v1/lessons/import') {
10607
- const body = await parseJsonBody(req);
12437
+ const body = await readProjectBody(req);
10608
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
+ }
10609
12444
  if (!bundle.lessons || !Array.isArray(bundle.lessons)) {
10610
12445
  sendJson(res, 400, { error: 'Invalid bundle: missing lessons array' });
10611
12446
  return;
@@ -10616,12 +12451,12 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10616
12451
 
10617
12452
  // Load existing IDs for dedup
10618
12453
  const existing = readLessonJsonl(feedbackLogPath, { maxLines: 0 });
10619
- 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)));
10620
12455
  // Also dedup by title+signal content hash
10621
12456
  const existingHashes = new Set(existing.map((r) => {
10622
12457
  const t = (r.title || r.context || '').trim().toLowerCase();
10623
12458
  const s = normalizeLessonSignal(r.signal);
10624
- return `${s}|${t}`;
12459
+ return `${projectForRecord(r).projectKey}|${s}|${t}`;
10625
12460
  }).filter((h) => h !== '|'));
10626
12461
 
10627
12462
  let imported = 0;
@@ -10630,12 +12465,12 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10630
12465
 
10631
12466
  for (const lesson of bundle.lessons) {
10632
12467
  // Skip if exact ID exists
10633
- if (lesson.id && existingIds.has(lesson.id)) {
12468
+ if (lesson.id && existingIds.has(projectForRecord(lesson).projectKey + ':' + lesson.id)) {
10634
12469
  skippedDuplicate++;
10635
12470
  continue;
10636
12471
  }
10637
12472
  // Skip if same title+signal already exists (content dedup)
10638
- 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()}`;
10639
12474
  if (contentHash !== '|' && existingHashes.has(contentHash)) {
10640
12475
  skippedDuplicate++;
10641
12476
  continue;
@@ -10643,6 +12478,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10643
12478
 
10644
12479
  // Create imported record with provenance
10645
12480
  const importedRecord = {
12481
+ ...projectForRecord(lesson),
10646
12482
  id: `imported_${Date.now()}_${require("crypto").randomBytes(4).toString("hex")}`,
10647
12483
  signal: lesson.signal || 'down',
10648
12484
  title: lesson.title || '',
@@ -10664,8 +12500,9 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10664
12500
  },
10665
12501
  };
10666
12502
 
12503
+ fs.mkdirSync(feedbackDir, { recursive: true });
10667
12504
  fs.appendFileSync(feedbackLogPath, JSON.stringify(importedRecord) + '\n', 'utf8');
10668
- existingIds.add(importedRecord.id);
12505
+ existingIds.add(importedRecord.projectKey + ':' + (lesson.id || importedRecord.id));
10669
12506
  existingHashes.add(contentHash);
10670
12507
  importedIds.push(importedRecord.id);
10671
12508
  imported++;
@@ -10682,7 +12519,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10682
12519
  }
10683
12520
 
10684
12521
  if (req.method === 'POST' && pathname === '/v1/analytics/databricks/export') {
10685
- const body = await parseJsonBody(req);
12522
+ const body = await readProjectBody(req);
10686
12523
  const outputPath = body.outputPath
10687
12524
  ? resolveSafePath(body.outputPath, { safeDataDir: requestSafeDataDir })
10688
12525
  : undefined;
@@ -10692,7 +12529,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10692
12529
  }
10693
12530
 
10694
12531
  if (req.method === 'POST' && pathname === '/v1/context/construct') {
10695
- const body = await parseJsonBody(req);
12532
+ const body = await readProjectBody(req);
10696
12533
  ensureContextFs();
10697
12534
  let namespaces = [];
10698
12535
  try {
@@ -10722,7 +12559,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10722
12559
  }
10723
12560
 
10724
12561
  if (req.method === 'POST' && pathname === '/v1/context/evaluate') {
10725
- const body = await parseJsonBody(req);
12562
+ const body = await readProjectBody(req);
10726
12563
  if (!body.packId || !body.outcome) {
10727
12564
  throw createHttpError(400, 'packId and outcome are required');
10728
12565
  }
@@ -10870,7 +12707,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10870
12707
  return;
10871
12708
  }
10872
12709
 
10873
- const body = await parseJsonBody(req);
12710
+ const body = await readProjectBody(req);
10874
12711
  const keyFingerprint = fingerprintProKey(token);
10875
12712
  const alert = await sendProActivationAlert({
10876
12713
  key: token,
@@ -10910,7 +12747,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
10910
12747
  return;
10911
12748
  }
10912
12749
 
10913
- const body = await parseJsonBody(req);
12750
+ const body = await readProjectBody(req);
10914
12751
  if (!body.customerId) {
10915
12752
  throw createHttpError(400, 'customerId is required');
10916
12753
  }
@@ -11035,7 +12872,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11035
12872
 
11036
12873
  const { FEEDBACK_DIR } = getFeedbackPaths();
11037
12874
  try {
11038
- const body = await parseJsonBody(req, 24 * 1024);
12875
+ const body = await readProjectBody(req, 24 * 1024);
11039
12876
  const workflowSprintIntake = requirePrivateApiModule('workflowSprintIntake', 'Workflow sprint intake');
11040
12877
  const result = workflowSprintIntake.advanceWorkflowSprintLead(body, { feedbackDir: FEEDBACK_DIR });
11041
12878
 
@@ -11129,6 +12966,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11129
12966
 
11130
12967
  // GET /v1/analytics/funnel — aggregate acquisition/activation/paid funnel metrics
11131
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.');
11132
12970
  const summary = getFunnelAnalytics();
11133
12971
  sendJson(res, 200, summary);
11134
12972
  return;
@@ -11163,8 +13001,44 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11163
13001
  return;
11164
13002
  }
11165
13003
  const { data } = dashboardResult;
11166
-
11167
- 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);
11168
13042
  return;
11169
13043
  }
11170
13044
 
@@ -11204,9 +13078,11 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11204
13078
 
11205
13079
  // GET /v1/dashboard/review-state -- incremental review baseline and deltas
11206
13080
  if (req.method === 'GET' && pathname === '/v1/dashboard/review-state') {
11207
- const reviewState = readDashboardReviewState(requestFeedbackDir);
13081
+ const reviewState = readDashboardReviewState(requestFeedbackDir, projectOptions);
11208
13082
  const data = generateDashboard(requestFeedbackDir, {
13083
+ projectKey: requestProjectKey,
11209
13084
  reviewBaseline: reviewState,
13085
+ humanOnly: true,
11210
13086
  authContext: { tier: 'pro' },
11211
13087
  });
11212
13088
  sendJson(res, 200, {
@@ -11218,15 +13094,17 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11218
13094
 
11219
13095
  // POST /v1/dashboard/review-state -- mark current dashboard state as reviewed
11220
13096
  if (req.method === 'POST' && pathname === '/v1/dashboard/review-state') {
11221
- const body = await parseJsonBody(req);
11222
- 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 });
11223
13099
  // Override snapshot timestamp with client-provided one if available
11224
13100
  if (body?.reviewedAt) {
11225
13101
  snapshot.reviewedAt = body.reviewedAt;
11226
13102
  }
11227
- writeDashboardReviewState(requestFeedbackDir, snapshot);
13103
+ writeDashboardReviewState(requestFeedbackDir, snapshot, projectOptions);
11228
13104
  const data = generateDashboard(requestFeedbackDir, {
13105
+ projectKey: requestProjectKey,
11229
13106
  reviewBaseline: snapshot,
13107
+ humanOnly: true,
11230
13108
  authContext: { tier: 'pro' },
11231
13109
  });
11232
13110
  sendJson(res, 200, {
@@ -11236,6 +13114,38 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11236
13114
  });
11237
13115
  return;
11238
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
+
11239
13149
 
11240
13150
  // GET /v1/dashboard/render-spec -- Constrained hosted dashboard JSON spec
11241
13151
  if (req.method === 'GET' && pathname === '/v1/dashboard/render-spec') {
@@ -11268,7 +13178,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11268
13178
  }
11269
13179
 
11270
13180
  if (req.method === 'POST' && pathname === '/v1/decisions/evaluate') {
11271
- const body = await parseJsonBody(req);
13181
+ const body = await readProjectBody(req);
11272
13182
  const normalizedRequestAction = normalizeProviderAction(body);
11273
13183
  const hasProviderNativeAction = Boolean(
11274
13184
  body.providerToolCall
@@ -11337,6 +13247,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11337
13247
  : scopeState.branchGovernance,
11338
13248
  },
11339
13249
  feedbackDir: requestFeedbackDir,
13250
+ projectKey: requestProjectKey,
11340
13251
  });
11341
13252
  const evaluation = recordDecisionEvaluation(report, {
11342
13253
  source: 'api',
@@ -11353,6 +13264,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11353
13264
  changedFiles,
11354
13265
  }, {
11355
13266
  feedbackDir: requestFeedbackDir,
13267
+ projectKey: requestProjectKey,
11356
13268
  });
11357
13269
  report.actionId = evaluation.actionId;
11358
13270
  if (report.decisionControl) report.decisionControl.actionId = evaluation.actionId;
@@ -11373,7 +13285,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11373
13285
  }
11374
13286
 
11375
13287
  if (req.method === 'POST' && pathname === '/v1/decisions/outcome') {
11376
- const body = await parseJsonBody(req);
13288
+ const body = await readProjectBody(req);
11377
13289
  if (!body.actionId || !body.outcome) {
11378
13290
  sendProblem(res, {
11379
13291
  type: PROBLEM_TYPES.BAD_REQUEST,
@@ -11394,6 +13306,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11394
13306
  source: 'api',
11395
13307
  }, {
11396
13308
  feedbackDir: requestFeedbackDir,
13309
+ projectKey: requestProjectKey,
11397
13310
  });
11398
13311
  sendJson(res, 200, outcome);
11399
13312
  return;
@@ -11412,14 +13325,14 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11412
13325
 
11413
13326
  // GET /v1/gates/stats -- Gate enforcement statistics
11414
13327
  if (req.method === 'GET' && pathname === '/v1/gates/stats') {
11415
- const stats = loadGateStats();
13328
+ const stats = requestProjectKey != null ? require('../../scripts/project-dashboard').generateProjectDashboard(requestFeedbackDir, projectOptions).gateStats : loadGateStats({ feedbackDir: requestFeedbackDir });
11416
13329
  sendJson(res, 200, stats);
11417
13330
  return;
11418
13331
  }
11419
13332
 
11420
13333
  // POST /v1/gates/satisfy -- Record evidence that a gate condition is satisfied
11421
13334
  if (req.method === 'POST' && pathname === '/v1/gates/satisfy') {
11422
- const body = await parseJsonBody(req);
13335
+ const body = await readProjectBody(req);
11423
13336
  if (!body.gateId || !body.evidence) {
11424
13337
  sendProblem(res, {
11425
13338
  type: PROBLEM_TYPES.BAD_REQUEST,
@@ -11433,6 +13346,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11433
13346
  // source the record defaults to 'cli' and the audit summary cannot
11434
13347
  // tell an HTTP unlock from a local one.
11435
13348
  const entry = satisfyCondition(body.gateId, body.evidence, null, {
13349
+ ...projectOptions,
11436
13350
  source: 'api',
11437
13351
  actor: body.actor || 'api-client',
11438
13352
  });
@@ -11442,7 +13356,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11442
13356
 
11443
13357
  // POST /v1/hermes/initialize — Bind a connectionId before turn start/end
11444
13358
  if (req.method === 'POST' && pathname === '/v1/hermes/initialize') {
11445
- const body = await parseJsonBody(req);
13359
+ const body = await readProjectBody(req);
11446
13360
  const { protocol } = getHostedHermes(requestDataIdentity);
11447
13361
  const result = protocol.initialize({
11448
13362
  connectionId: body.connectionId,
@@ -11464,7 +13378,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11464
13378
  // POST /v1/hermes/turn/start — Start turn under Hermes Platform Protocol
11465
13379
  // Fail closed until POST /v1/hermes/initialize registers the connectionId.
11466
13380
  if (req.method === 'POST' && pathname === '/v1/hermes/turn/start') {
11467
- const body = await parseJsonBody(req);
13381
+ const body = await readProjectBody(req);
11468
13382
  const { protocol } = getHostedHermes(requestDataIdentity);
11469
13383
  const result = protocol.startTurn(body);
11470
13384
  if (!result.ok) {
@@ -11483,7 +13397,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11483
13397
 
11484
13398
  // POST /v1/hermes/turn/end — End active turn under Hermes Platform Protocol
11485
13399
  if (req.method === 'POST' && pathname === '/v1/hermes/turn/end') {
11486
- const body = await parseJsonBody(req);
13400
+ const body = await readProjectBody(req);
11487
13401
  const { protocol } = getHostedHermes(requestDataIdentity);
11488
13402
  const result = protocol.endTurn(body);
11489
13403
  if (!result.ok) {
@@ -11502,7 +13416,7 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11502
13416
 
11503
13417
  // POST /v1/hermes/action/approve — Record human/operator approval for consequential action
11504
13418
  if (req.method === 'POST' && pathname === '/v1/hermes/action/approve') {
11505
- const body = await parseJsonBody(req);
13419
+ const body = await readProjectBody(req);
11506
13420
  const boundApproverId = resolveHermesApproverId(
11507
13421
  req,
11508
13422
  humanReviewerConfig,
@@ -11709,6 +13623,12 @@ module.exports = {
11709
13623
  partitionFeedbackPaths,
11710
13624
  buildLiveDashboardCacheKey,
11711
13625
  loadCachedLiveDashboardData,
13626
+ setGoogleOAuthFetchForTests,
13627
+ setAppleOAuthFetchForTests,
13628
+ buildAppleClientSecret,
13629
+ issueSsoPendingState,
13630
+ consumeSsoPendingState,
13631
+ clearInMemoryAuthSessionsForTests,
11712
13632
  },
11713
13633
  };
11714
13634