thumbgate 1.39.1 → 1.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) 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 +62 -28
  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 +159 -69
  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 +75 -60
  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-window.js +7 -1
  67. package/scripts/async-job-runner.js +66 -11
  68. package/scripts/audit-trail.js +37 -24
  69. package/scripts/auto-promote-gates.js +37 -27
  70. package/scripts/backfill-lesson-scopes.js +122 -0
  71. package/scripts/billing.js +889 -132
  72. package/scripts/bot-detection.js +112 -0
  73. package/scripts/brand-standards-gate.js +571 -0
  74. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  75. package/scripts/cli-schema.js +1 -1
  76. package/scripts/commercial-offer.js +2 -2
  77. package/scripts/contextfs.js +9 -3
  78. package/scripts/cross-encoder-reranker.js +4 -0
  79. package/scripts/dashboard-chat.js +11 -0
  80. package/scripts/dashboard.js +574 -167
  81. package/scripts/decision-journal.js +7 -4
  82. package/scripts/docker-sandbox-planner.js +3 -3
  83. package/scripts/export-dpo-pairs.js +12 -7
  84. package/scripts/feedback-aggregate.js +4 -0
  85. package/scripts/feedback-attribution.js +6 -4
  86. package/scripts/feedback-history-distiller.js +18 -6
  87. package/scripts/feedback-loop.js +255 -89
  88. package/scripts/feedback-paths.js +8 -1
  89. package/scripts/feedback-sanitizer.js +5 -0
  90. package/scripts/feedback-scope.js +106 -0
  91. package/scripts/feedback-session.js +8 -2
  92. package/scripts/filesystem-search.js +13 -8
  93. package/scripts/financial-control-plane.js +707 -45
  94. package/scripts/gate-stats.js +8 -2
  95. package/scripts/gates-engine.js +694 -230
  96. package/scripts/generate-eval-scorecard.js +0 -1
  97. package/scripts/harness-tool-names.js +31 -5
  98. package/scripts/hybrid-feedback-context.js +5 -2
  99. package/scripts/intervention-policy.js +2 -1
  100. package/scripts/lesson-canonical.js +2 -2
  101. package/scripts/lesson-db.js +55 -14
  102. package/scripts/lesson-graph.js +2 -1
  103. package/scripts/lesson-retrieval.js +95 -9
  104. package/scripts/lesson-search.js +86 -22
  105. package/scripts/lesson-synthesis.js +21 -5
  106. package/scripts/mailer/index.js +17 -1
  107. package/scripts/mailer/resend-mailer.js +213 -179
  108. package/scripts/migrate-project-scope.js +209 -0
  109. package/scripts/operational-integrity.js +436 -3
  110. package/scripts/override-audit.js +2 -0
  111. package/scripts/owner-admin.js +338 -0
  112. package/scripts/pr-manager.js +194 -1
  113. package/scripts/progressive-signoff.js +260 -0
  114. package/scripts/project-catalog.js +243 -0
  115. package/scripts/project-dashboard.js +61 -0
  116. package/scripts/project-evidence.js +172 -0
  117. package/scripts/project-identity.js +182 -0
  118. package/scripts/project-scope.js +381 -0
  119. package/scripts/prompt-guard.js +446 -52
  120. package/scripts/proof-report.js +232 -0
  121. package/scripts/provider-action-normalizer.js +14 -6
  122. package/scripts/rate-limiter.js +41 -0
  123. package/scripts/secret-redaction.js +171 -25
  124. package/scripts/secret-scanner.js +101 -42
  125. package/scripts/self-protection.js +2 -2
  126. package/scripts/seo-gsd.js +14 -14
  127. package/scripts/session-context-dedupe.js +66 -0
  128. package/scripts/settings-hierarchy.js +4 -2
  129. package/scripts/statusline-meta.js +34 -23
  130. package/scripts/task-outcomes.js +29 -2
  131. package/scripts/telemetry-analytics.js +238 -13
  132. package/scripts/thumbgate-search.js +23 -9
  133. package/scripts/tool-kpi-tracker.js +5 -2
  134. package/scripts/tool-registry.js +42 -1
  135. package/scripts/triage-savings-calculator.js +1 -1
  136. package/scripts/vector-store.js +4 -1
  137. package/scripts/verified-lessons.js +270 -0
  138. package/scripts/verify-marketing-pages-deployed.js +2 -2
  139. package/scripts/workflow-sentinel.js +29 -10
  140. package/server.json +2 -2
  141. package/src/api/server.js +2371 -451
  142. package/src/feedback.js +21 -0
  143. package/src/hermes-sync-plane.js +2 -1
  144. package/src/index.js +2 -0
  145. package/src/lesson-search.js +9 -0
  146. package/src/mckinsey-top-company-ai-coding.js +493 -0
  147. package/src/mcp/server.js +3 -0
  148. package/src/mcp-writeguard.js +772 -11
  149. package/src/openshell-lovable-engine.js +1475 -0
  150. package/src/task-outcome.js +3 -0
  151. package/config/evals/agent-safety-eval.json +0 -447
  152. package/config/evals/retrieval-ranking-golden.json +0 -522
  153. package/config/progressive/01-wire-only.json +0 -11
  154. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  155. package/config/progressive/03-one-lesson.json +0 -10
  156. package/config/progressive/04-warn-fires.json +0 -11
  157. package/config/progressive/05-strict-optional.json +0 -11
  158. package/config/progressive/README.md +0 -15
  159. package/public/assets/diagrams/agent-integration.png +0 -0
  160. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
@@ -0,0 +1,232 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+
8
+ const PROOF_WINDOW_DAYS_DEFAULT = 30;
9
+ const MAX_EXAMPLE_CHARS = 160;
10
+
11
+ const CATEGORY_RULES = [
12
+ {
13
+ id: 'force_push',
14
+ label: 'Force push to a protected branch',
15
+ gateIds: ['force-push', 'force_push', 'protected-branch-force-push'],
16
+ pattern: /\bgit\s+push\b[^\n]{0,80}(--force\b|-f\b)/i,
17
+ },
18
+ {
19
+ id: 'secret_in_command',
20
+ label: 'Secret material in a command',
21
+ gateIds: ['secret-exfiltration', 'secret-guard', 'secret_in_command', 'credential-leak'],
22
+ pattern: /(secret|api[_-]?key|token|password|credential|exfiltration)/i,
23
+ },
24
+ {
25
+ id: 'destructive_shell',
26
+ label: 'Destructive shell command',
27
+ gateIds: ['destructive-delete', 'destructive-shell', 'rm-rf', 'hard-floor'],
28
+ pattern: /\brm\s+-[a-z]*r[a-z]*f|\bdrop\s+(database|table)\b|\btruncate\b/i,
29
+ },
30
+ {
31
+ id: 'repeated_mistake',
32
+ label: 'Repeated mistake the agent already corrected',
33
+ gateIds: ['repeated-mistake', 'lesson-repeat', 'recurring-block'],
34
+ pattern: /(repeat(ed)? mistake|already corrected|recurring)/i,
35
+ },
36
+ {
37
+ id: 'privilege_escalation',
38
+ label: 'Privilege escalation or unsafe sudo',
39
+ gateIds: ['privilege-escalation', 'unsafe-sudo'],
40
+ pattern: /\bsudo\b|\bchmod\s+777\b/i,
41
+ },
42
+ ];
43
+
44
+ const NOISE_SOURCE_PATTERN = /(test|cron|diagnostic|fixture)/i;
45
+ const NOISE_PATH_PATTERN = /(\/(?:tmp|var\/folders)\/|thumbgate-test|test-fixtures?|node_modules)/i;
46
+
47
+ function resolveProofPaths(env = process.env) {
48
+ const homeDir = env.HOME || os.homedir() || '/tmp';
49
+ const thumbgateDir = env.THUMBGATE_HOME || path.join(homeDir, '.thumbgate');
50
+ return {
51
+ thumbgateDir,
52
+ auditTrailPath: env.THUMBGATE_AUDIT_TRAIL_PATH || path.join(thumbgateDir, 'audit-trail.jsonl'),
53
+ };
54
+ }
55
+
56
+ function readJsonl(filePath) {
57
+ if (!filePath || !fs.existsSync(filePath)) return [];
58
+ const out = [];
59
+ for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
60
+ const trimmed = line.trim();
61
+ if (!trimmed) continue;
62
+ try {
63
+ out.push(JSON.parse(trimmed));
64
+ } catch {
65
+ // skip malformed line
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function isBlockedDecision(record) {
72
+ const decision = String(record?.decision || '').toLowerCase();
73
+ const mode = String(record?.mode || '').toLowerCase();
74
+ return decision === 'deny' || decision === 'block' || mode === 'block';
75
+ }
76
+
77
+ function extractCommandText(record) {
78
+ const input = record?.toolInput;
79
+ if (!input || typeof input !== 'object') return '';
80
+ return String(input.command || input.cmd || input.input || input.file_path || input.path || '').trim();
81
+ }
82
+
83
+ function classifyCategory(record) {
84
+ const gateId = String(record?.gateId || '').toLowerCase();
85
+ const reason = String(record?.reason || record?.message || '');
86
+ const command = extractCommandText(record);
87
+ const haystack = `${gateId}\n${reason}\n${command}`;
88
+ for (const rule of CATEGORY_RULES) {
89
+ if (rule.gateIds.some((id) => gateId === id || gateId.includes(id))) return rule;
90
+ if (rule.pattern.test(haystack)) return rule;
91
+ }
92
+ return { id: 'other_risky_action', label: 'Other risky action stopped' };
93
+ }
94
+
95
+ function isNoiseRecord(record) {
96
+ const source = String(record?.source || '');
97
+ const sessionId = String(record?.sessionId || '');
98
+ const identity = `${source} ${sessionId}`;
99
+ const command = extractCommandText(record);
100
+ return NOISE_SOURCE_PATTERN.test(identity) || NOISE_PATH_PATTERN.test(command);
101
+ }
102
+
103
+ function anonymizeExample(text) {
104
+ let out = String(text || '').replace(/\s+/g, ' ').trim();
105
+ out = out
106
+ .replace(/\/(?:Users|home)\/[^\s'"]+/gi, '~/<redacted-path>')
107
+ .replace(/\b[\w.-]+\/[\w./-]+/g, '<redacted-path>')
108
+ .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '<redacted-email>')
109
+ .replace(/\b(?:sk|rk|pk|ghp|gho|github_pat|xox[baprs]|AKIA|ASIA)[_-][A-Za-z0-9_\-]{8,}\b/g, '<redacted-secret>')
110
+ .replace(/\b[A-Z][A-Z0-9_]*(?:PAT|TOKEN|SECRET|PASSWORD|KEY)\b/g, '<redacted-secret>')
111
+ .replace(/\bwith-secrets\b/gi, '<redacted-secret>')
112
+ .replace(/\b(?:api[_-]?key|token|secret|password|passwd|credential|pat)\s*[:=]\s*\S+/gi, '<redacted-secret>');
113
+ if (out.length > MAX_EXAMPLE_CHARS) out = `${out.slice(0, MAX_EXAMPLE_CHARS - 1)}…`;
114
+ return out;
115
+ }
116
+
117
+ function buildProofReport(options = {}) {
118
+ const days = Math.max(1, Math.trunc(Number(options.days) || PROOF_WINDOW_DAYS_DEFAULT));
119
+ const nowMs = options.now ? new Date(options.now).getTime() : Date.now();
120
+ const windowStartMs = nowMs - days * 24 * 60 * 60 * 1000;
121
+ const paths = options.paths || resolveProofPaths(options.env);
122
+ const records = options.records || readJsonl(paths.auditTrailPath);
123
+
124
+ const realByCategory = new Map();
125
+ const excluded = { test: 0, cron: 0, diagnostic: 0, fixture: 0, other: 0 };
126
+ let realBlocked = 0;
127
+ let excludedTotal = 0;
128
+
129
+ for (const record of records) {
130
+ if (!isBlockedDecision(record)) continue;
131
+ const ts = new Date(record.timestamp || 0).getTime();
132
+ if (!Number.isFinite(ts) || ts < windowStartMs || ts > nowMs) continue;
133
+
134
+ if (isNoiseRecord(record)) {
135
+ excludedTotal += 1;
136
+ const haystack = `${record.source || ''} ${record.sessionId || ''} ${record.reason || ''} ${extractCommandText(record)}`.toLowerCase();
137
+ if (haystack.includes('cron')) excluded.cron += 1;
138
+ else if (haystack.includes('diagnostic')) excluded.diagnostic += 1;
139
+ else if (haystack.includes('fixture')) excluded.fixture += 1;
140
+ else if (haystack.includes('test')) excluded.test += 1;
141
+ else excluded.other += 1;
142
+ continue;
143
+ }
144
+
145
+ realBlocked += 1;
146
+ const category = classifyCategory(record);
147
+ const bucket = realByCategory.get(category.id) || {
148
+ id: category.id,
149
+ label: category.label,
150
+ count: 0,
151
+ example: '',
152
+ };
153
+ bucket.count += 1;
154
+ if (!bucket.example) {
155
+ const exampleSource = extractCommandText(record) || String(record.message || record.reason || '');
156
+ bucket.example = anonymizeExample(exampleSource);
157
+ }
158
+ realByCategory.set(category.id, bucket);
159
+ }
160
+
161
+ const categories = [...realByCategory.values()].sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
162
+
163
+ return {
164
+ windowDays: days,
165
+ generatedAt: new Date(nowMs).toISOString(),
166
+ source: 'founder-local-audit-trail',
167
+ realAgentToolCallsBlocked: realBlocked,
168
+ excludedNoise: {
169
+ total: excludedTotal,
170
+ ...excluded,
171
+ },
172
+ categories,
173
+ };
174
+ }
175
+
176
+ function formatProofText(report) {
177
+ const lines = [
178
+ `ThumbGate proof — last ${report.windowDays} days (founder local use, not a customer)`,
179
+ `Real agent tool calls blocked: ${report.realAgentToolCallsBlocked}`,
180
+ `Excluded noise (test/cron/diagnostic/fixture): ${report.excludedNoise.total}`,
181
+ '',
182
+ 'Top categories:',
183
+ ];
184
+ const top = report.categories.slice(0, 5);
185
+ if (!top.length) {
186
+ lines.push(' (none in window)');
187
+ } else {
188
+ for (const cat of top) {
189
+ lines.push(` - ${cat.label}: ${cat.count}`);
190
+ if (cat.example) lines.push(` example: ${cat.example}`);
191
+ }
192
+ }
193
+ return lines.join('\n');
194
+ }
195
+
196
+ function runProofCli(argv = process.argv.slice(3), options = {}) {
197
+ const args = {};
198
+ for (let i = 0; i < argv.length; i += 1) {
199
+ const arg = argv[i];
200
+ if (!arg.startsWith('--')) continue;
201
+ const [key, ...rest] = arg.slice(2).split('=');
202
+ if (rest.length) args[key] = rest.join('=');
203
+ else if (argv[i + 1] && !argv[i + 1].startsWith('--')) {
204
+ args[key] = argv[i + 1];
205
+ i += 1;
206
+ } else args[key] = true;
207
+ }
208
+ const report = buildProofReport({
209
+ days: args.days,
210
+ env: options.env,
211
+ paths: options.paths,
212
+ records: options.records,
213
+ now: options.now,
214
+ });
215
+ const out = args.json ? JSON.stringify(report, null, 2) : formatProofText(report);
216
+ if (!options.silent) process.stdout.write(`${out}\n`);
217
+ return report;
218
+ }
219
+
220
+ module.exports = {
221
+ CATEGORY_RULES,
222
+ anonymizeExample,
223
+ buildProofReport,
224
+ formatProofText,
225
+ isNoiseRecord,
226
+ resolveProofPaths,
227
+ runProofCli,
228
+ };
229
+
230
+ if (require.main === module) {
231
+ runProofCli(process.argv.slice(2));
232
+ }
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const { normalizeCommandValue } = require('./harness-tool-names');
4
5
  const DEFAULT_SOFT_TOKEN_LIMIT = 8000;
5
6
  const DEFAULT_MAX_PARALLEL_BRANCHES = 4;
6
7
 
@@ -215,13 +216,20 @@ function collectAffectedFiles(toolInput = {}, fallback = {}) {
215
216
  return uniqueStrings(files);
216
217
  }
217
218
 
219
+ function coerceCommandCandidate(candidate) {
220
+ if (Array.isArray(candidate)) {
221
+ return normalizeCommandValue(candidate);
222
+ }
223
+ return candidate;
224
+ }
225
+
218
226
  function inferCommand(toolName, toolInput = {}, fallback = {}) {
219
227
  return firstString(
220
- toolInput.command,
221
- toolInput.cmd,
222
- toolInput.shell,
223
- fallback.command,
224
- fallback.cmd
228
+ coerceCommandCandidate(toolInput.command),
229
+ coerceCommandCandidate(toolInput.cmd),
230
+ coerceCommandCandidate(toolInput.shell),
231
+ coerceCommandCandidate(fallback.command),
232
+ coerceCommandCandidate(fallback.cmd)
225
233
  );
226
234
  }
227
235
 
@@ -232,7 +240,7 @@ function inferActionType(toolName, toolInput = {}, fallback = {}) {
232
240
  if (fallback.method === 'prompts/get') return 'prompt.get';
233
241
  const normalizedTool = String(toolName || '').trim();
234
242
  const lowerTool = normalizedTool.toLowerCase();
235
- if (normalizedTool === 'Bash' || containsAny(lowerTool, ['bash', 'shell', 'terminal', 'exec', 'run_command'])) {
243
+ if (normalizedTool === 'Bash' || containsAny(lowerTool, ['bash', 'shell', 'terminal', 'exec', 'run_command', 'powershell', 'pwsh'])) {
236
244
  return 'shell.exec';
237
245
  }
238
246
  if (EDIT_TOOL_NAMES.has(normalizedTool) || containsAny(lowerTool, ['edit', 'write', 'patch', 'file'])) {
@@ -218,6 +218,44 @@ function getUsage(action, authContext) {
218
218
  return { count: lifetimeCount, limit: lifetimeLimit, remaining: Math.max(0, lifetimeLimit - lifetimeCount) };
219
219
  }
220
220
 
221
+ const PRO_REPEAT_URL = 'https://thumbgate.ai/pro';
222
+ const RULE_SECTION_SKIP = new Set([
223
+ 'High-Priority Contracts',
224
+ 'Rubric Failure Dimensions',
225
+ 'Root Cause Categories',
226
+ 'Repeated Failure Constraints',
227
+ ]);
228
+
229
+ function scrubRepeatText(value) {
230
+ return String(value || '')
231
+ .replace(/\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b/g, '[redacted]')
232
+ .replace(/\b(?:sk|ghp|github_pat|AKIA)[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
233
+ .replace(/\/Users\/[^\s]+/g, '[path]')
234
+ .replace(/\s+/g, ' ')
235
+ .trim()
236
+ .slice(0, 140);
237
+ }
238
+
239
+ function proWouldHaveBlockedSentence(mistake) {
240
+ const clean = scrubRepeatText(mistake);
241
+ if (!clean) return null;
242
+ return `Pro would have blocked this repeat: ${clean}. ${PRO_REPEAT_URL}`;
243
+ }
244
+
245
+ function droppedRepeatFromRulesMarkdown(markdown, maxActive = FREE_TIER_MAX_GATES) {
246
+ const mistakes = [];
247
+ for (const section of String(markdown || '').split(/\n## /)) {
248
+ const title = section.replace(/^## /, '').split('\n')[0].trim();
249
+ if (!title || RULE_SECTION_SKIP.has(title)) continue;
250
+ if (!/^- Rule: /m.test(section) && !/^- Latest mistake: /m.test(section)) continue;
251
+ const latest = (section.match(/^- Latest mistake: (.+)$/m) || [])[1];
252
+ const rule = (section.match(/^- Rule: (.+)$/m) || [])[1];
253
+ const text = scrubRepeatText(latest || rule || title);
254
+ if (text) mistakes.push(text);
255
+ }
256
+ return mistakes.length > maxActive ? mistakes[maxActive] : null;
257
+ }
258
+
221
259
  module.exports = {
222
260
  checkLimit,
223
261
  getUsage,
@@ -235,4 +273,7 @@ module.exports = {
235
273
  UPGRADE_MESSAGE,
236
274
  PAYWALL_MESSAGES,
237
275
  USAGE_FILE,
276
+ proWouldHaveBlockedSentence,
277
+ droppedRepeatFromRulesMarkdown,
278
+ scrubRepeatText,
238
279
  };
@@ -158,47 +158,178 @@ function redactSecretsDeep(value) {
158
158
  return value;
159
159
  }
160
160
  const crypto = require('node:crypto');
161
+ const fs = require('node:fs');
162
+ const path = require('node:path');
161
163
 
162
- /**
163
- * Capital One Databolt-style Vaultless Format-Preserving Tokenization (FPT).
164
- */
165
- function tokenizeFormatPreservingVaultless(text, { salt = process.env.THUMBGATE_FPT_KEY } = {}) {
166
- if (typeof text !== 'string' || text.length === 0) return text;
167
- if (typeof salt !== 'string' || salt.length < 16) {
168
- throw new Error('tokenizeFormatPreservingVaultless requires a secret key of at least 16 characters');
164
+ function computeLuhnCheckDigit(digitsWithoutCheck) {
165
+ let sum = 0;
166
+ let shouldDouble = true;
167
+ for (let i = digitsWithoutCheck.length - 1; i >= 0; i -= 1) {
168
+ let digit = Number(digitsWithoutCheck[i]);
169
+ if (shouldDouble) {
170
+ digit *= 2;
171
+ if (digit > 9) digit -= 9;
172
+ }
173
+ sum += digit;
174
+ shouldDouble = !shouldDouble;
175
+ }
176
+ return String((10 - (sum % 10)) % 10);
177
+ }
178
+
179
+ function formatCardToken(rawMatch, digestDigits) {
180
+ const digitsOnly = rawMatch.replaceAll(/\D/g, '');
181
+ if (digitsOnly.startsWith('9999')) return rawMatch;
182
+ const middleLen = digitsOnly.length - 5;
183
+ const payload = `9999${digestDigits(digitsOnly, middleLen)}`;
184
+ const fullDigits = `${payload}${computeLuhnCheckDigit(payload)}`;
185
+ let cursor = 0;
186
+ let formatted = '';
187
+ for (const ch of rawMatch) {
188
+ if (ch >= '0' && ch <= '9') {
189
+ formatted += fullDigits[cursor];
190
+ cursor += 1;
191
+ } else {
192
+ formatted += ch;
193
+ }
194
+ }
195
+ return formatted;
196
+ }
197
+
198
+ function tokenizeSecretsReferentially(text, digestHex) {
199
+ let out = text;
200
+ for (const pattern of SECRET_REDACTION_PATTERNS) {
201
+ pattern.regex.lastIndex = 0;
202
+ if (pattern.id === 'bearer_token') {
203
+ out = out.replaceAll(pattern.regex, (full, scheme) => {
204
+ const rawSecret = full.slice(scheme.length).trim();
205
+ return `${scheme} [FPT:bearer_token#${digestHex(rawSecret).slice(0, 8)}]`;
206
+ });
207
+ } else if (pattern.id === 'secret_assignment') {
208
+ out = out.replaceAll(pattern.regex, (match, key, pre, value, post) => (
209
+ (SECRET_KEY_NAME.test(key) && !PUBLIC_KEY_NAME.test(key))
210
+ ? `${key}${pre}[FPT:secret_assignment#${digestHex(value).slice(0, 8)}]${post}`
211
+ : match
212
+ ));
213
+ } else {
214
+ out = out.replaceAll(pattern.regex, (match) => `[FPT:${pattern.id}#${digestHex(match).slice(0, 8)}]`);
215
+ }
169
216
  }
170
- const digestHex = (val) => crypto.createHmac('sha256', String(salt)).update(String(val)).digest('hex');
217
+ return out;
218
+ }
219
+
220
+ function createVaultlessDigesters(salt) {
221
+ const digestHex = (val) => crypto.createHmac('sha256', salt).update(String(val)).digest('hex');
171
222
  const digestDigits = (val, len) => {
172
223
  const hex = digestHex(val);
173
224
  let out = '';
174
- for (let i = 0; i < hex.length && out.length < len; i += 2) {
225
+ for (let i = 0; i < len * 2; i += 2) {
175
226
  out += String(Number.parseInt(hex.slice(i, i + 2), 16) % 10);
176
227
  }
177
- return out.padEnd(len, '0').slice(0, len);
228
+ return out;
178
229
  };
230
+ return { digestHex, digestDigits };
231
+ }
179
232
 
180
- let out = redactSecrets(text);
181
- out = out.replace(/\b([A-Za-z0-9._%+-]{1,64})@([A-Za-z0-9.-]+\.[A-Za-z]{2,})\b/g, (match, _local, domain) => {
182
- if (domain.toLowerCase() === 'tokenized.local') return match;
183
- return `tok_${digestHex(match.toLowerCase()).slice(0, 8)}@tokenized.local`;
184
- });
185
- out = out.replace(/\b(?!900-)\d{3}-\d{2}-\d{4}\b/g, (match) => {
186
- const d = digestDigits(match, 6);
187
- return `900-${d.slice(0, 2)}-${d.slice(2, 6)}`;
188
- });
189
- out = out.replace(/\b(\d{3})-(\d{3})-(\d{4})\b/g, (match, a, b) => {
190
- if (a === '900' || (a === '555' && b.startsWith('01'))) return match;
191
- const d = digestDigits(match, 6);
192
- return `555-01${d.slice(0, 1)}-${d.slice(1, 5)}`;
233
+ function formatEmailToken(match, _local, domain, digestHex) {
234
+ if (domain.toLowerCase() === 'tokenized.local') return match;
235
+ return `tok_${digestHex(match.toLowerCase()).slice(0, 8)}@tokenized.local`;
236
+ }
237
+
238
+ function formatSsnToken(match, sep, digestDigits) {
239
+ const canonical = match.replaceAll(/\D/g, '');
240
+ const d = digestDigits(canonical, 6);
241
+ return `900${sep}${d.slice(0, 2)}${sep}${d.slice(2, 6)}`;
242
+ }
243
+
244
+ function formatUsPhoneToken(match, countryPrefix, area, exchange, digestDigits) {
245
+ if (area === '900' || (area === '555' && exchange.startsWith('01'))) return match;
246
+ const canonical = `${area}${exchange}${match.replaceAll(/\D/g, '').slice(-4)}`;
247
+ const d = digestDigits(canonical, 6);
248
+ const prefix = countryPrefix || '';
249
+ return `${prefix}555-01${d.slice(0, 1)}-${d.slice(1, 5)}`;
250
+ }
251
+
252
+ const FPT_EMAIL_RE = /\b([A-Za-z0-9._%+-]{1,64})@([A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24})\b/g;
253
+ const FPT_CARD_RE = /\b(?:\d{4}[ -]?){3}\d{1,7}\b/g;
254
+ const FPT_SSN_RE = /\b(?!900[-.\s])\d{3}([-.\s])\d{2}\1\d{4}\b/g;
255
+ const FPT_US_PHONE_RE = /(?:\+?1[-.\s]?)?\(?(\d{3})\)?[-.\s](\d{3})[-.\s]\d{4}\b/g;
256
+
257
+ /**
258
+ * Capital One Databolt-style Vaultless Format-Preserving Tokenization (FPT).
259
+ * Tokenizes sensitive values at ingestion while preserving format and referential integrity.
260
+ */
261
+ function tokenizeFormatPreservingVaultless(text, {
262
+ salt = process.env.THUMBGATE_FPT_KEY,
263
+ preserveSecretReferentialIntegrity = false,
264
+ } = {}) {
265
+ if (typeof text !== 'string' || text.length === 0) return text;
266
+ if (typeof salt !== 'string' || salt.length < 16) {
267
+ throw new TypeError('tokenizeFormatPreservingVaultless requires a secret key of at least 16 characters');
268
+ }
269
+ const { digestHex, digestDigits } = createVaultlessDigesters(salt);
270
+ let out = preserveSecretReferentialIntegrity
271
+ ? tokenizeSecretsReferentially(text, digestHex)
272
+ : redactSecrets(text);
273
+ out = out.replaceAll(FPT_EMAIL_RE, (m, local, dom) => formatEmailToken(m, local, dom, digestHex));
274
+ out = out.replaceAll(FPT_CARD_RE, (m) => formatCardToken(m, digestDigits));
275
+ out = out.replaceAll(FPT_SSN_RE, (m, sep) => formatSsnToken(m, sep, digestDigits));
276
+ out = out.replaceAll(FPT_US_PHONE_RE, (m, area, exch) => {
277
+ const prefixMatch = m.match(/^\+?1[-.\s]/);
278
+ return formatUsPhoneToken(m, prefixMatch ? prefixMatch[0] : '', area, exch, digestDigits);
193
279
  });
194
280
  return out;
195
281
  }
196
282
 
283
+ function tokenizeDeepAtSource(value, options = {}) {
284
+ let fieldsTokenized = 0;
285
+ function walk(node) {
286
+ if (typeof node === 'string') {
287
+ const tokenized = tokenizeFormatPreservingVaultless(node, options);
288
+ if (tokenized !== node) fieldsTokenized += 1;
289
+ return tokenized;
290
+ }
291
+ if (Array.isArray(node)) return node.map((item) => walk(item));
292
+ if (node && typeof node === 'object') {
293
+ const copy = {};
294
+ for (const [k, v] of Object.entries(node)) copy[k] = walk(v);
295
+ return copy;
296
+ }
297
+ return node;
298
+ }
299
+ return {
300
+ data: walk(value),
301
+ fieldsTokenized,
302
+ referentialIntegrity: true,
303
+ };
304
+ }
305
+
306
+ function collectFieldDetokenizationBlockers(requestedFields, allowedFields) {
307
+ if (!Array.isArray(requestedFields) || requestedFields.length === 0) return [];
308
+ if (!Array.isArray(allowedFields)) return [];
309
+ const allowedSet = new Set(allowedFields);
310
+ return requestedFields
311
+ .filter((field) => !allowedSet.has(field))
312
+ .map((field) => `unauthorized_field_detokenization:${field}`);
313
+ }
314
+
315
+ function writeDetokenizationAudit(auditEntry, { auditLogPath, onAuditEvent }) {
316
+ if (typeof onAuditEvent === 'function') onAuditEvent(auditEntry);
317
+ if (typeof auditLogPath === 'string' && auditLogPath.length > 0) {
318
+ fs.mkdirSync(path.dirname(auditLogPath), { recursive: true });
319
+ fs.appendFileSync(auditLogPath, `${JSON.stringify(auditEntry)}\n`, { mode: 0o600 });
320
+ }
321
+ }
322
+
197
323
  function enforceZeroTrustDetokenizationGate({
198
324
  authenticated = false,
199
325
  roleAuthorizedForPlaintext = false,
200
326
  explicitDetokenizePermission = false,
201
327
  crossesExternalNetwork = false,
328
+ principalId = null,
329
+ requestedFields = [],
330
+ allowedFields = null,
331
+ auditLogPath = null,
332
+ onAuditEvent = null,
202
333
  } = {}) {
203
334
  const blockers = [];
204
335
  if (authenticated !== true) blockers.push('unauthenticated_caller');
@@ -206,11 +337,24 @@ function enforceZeroTrustDetokenizationGate({
206
337
  if (roleAuthorizedForPlaintext !== true || explicitDetokenizePermission !== true) {
207
338
  blockers.push('default_tokenized_view_enforced_explicit_detokenize_permission_required');
208
339
  }
340
+ blockers.push(...collectFieldDetokenizationBlockers(requestedFields, allowedFields));
341
+ const allowed = blockers.length === 0;
342
+ const viewMode = allowed ? 'DETOKENIZED_PLAINTEXT' : 'TOKENIZED_ONLY';
343
+ const auditEntry = {
344
+ recordedAt: new Date().toISOString(),
345
+ principalId: principalId || 'anonymous',
346
+ requestedFields: Array.isArray(requestedFields) ? [...requestedFields] : [],
347
+ allowed,
348
+ viewMode,
349
+ blockers: [...blockers],
350
+ };
351
+ writeDetokenizationAudit(auditEntry, { auditLogPath, onAuditEvent });
209
352
  return {
210
- allowed: blockers.length === 0,
211
- viewMode: blockers.length === 0 ? 'DETOKENIZED_PLAINTEXT' : 'TOKENIZED_ONLY',
353
+ allowed,
354
+ viewMode,
212
355
  vaultlessInEnvironment: !crossesExternalNetwork,
213
356
  blockers,
357
+ auditEntry,
214
358
  };
215
359
  }
216
360
 
@@ -219,6 +363,8 @@ module.exports = {
219
363
  redactSecrets,
220
364
  redactSecretsDeep,
221
365
  containsSecret,
366
+ computeLuhnCheckDigit,
222
367
  tokenizeFormatPreservingVaultless,
368
+ tokenizeDeepAtSource,
223
369
  enforceZeroTrustDetokenizationGate,
224
370
  };