thumbgate 1.39.0 → 1.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/.agents/skills/craft-playbook-gate/SKILL.md +51 -0
  2. package/.agents/skills/qwenwork-policy-group-honesty-not-clone/SKILL.md +36 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.well-known/llms.txt +2 -2
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +11 -5
  7. package/adapters/claude/.mcp.json +6 -2
  8. package/adapters/codex/config.toml +5 -0
  9. package/adapters/forge/forge.yaml +4 -4
  10. package/adapters/future-agi/.mcp.json +1 -1
  11. package/adapters/future-agi/config.toml +1 -1
  12. package/adapters/future-agi/opencode.json +1 -1
  13. package/adapters/herdr/herdr-plugin.toml +2 -2
  14. package/adapters/mcp/server-stdio.js +104 -7
  15. package/adapters/opencode/opencode.json +1 -1
  16. package/adapters/strands/strands-middleware.js +31 -4
  17. package/bin/cli.js +191 -54
  18. package/config/brand-standards.json +131 -0
  19. package/config/gates/default.json +18 -1
  20. package/config/github-about.json +1 -1
  21. package/config/mcp-allowlists.json +16 -3
  22. package/config/merge-quality-checks.json +3 -1
  23. package/config/post-deploy-marketing-pages.json +4 -4
  24. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  25. package/hooks/hooks.json +24 -0
  26. package/openapi/openapi.yaml +7 -3
  27. package/package.json +87 -33
  28. package/public/about.html +2 -2
  29. package/public/admin.html +771 -0
  30. package/public/agent-manager.html +3 -3
  31. package/public/agents-cost-savings.html +1 -1
  32. package/public/ai-malpractice-prevention.html +12 -12
  33. package/public/architecture.html +0 -1
  34. package/public/assets/diagrams/decision.svg +3 -3
  35. package/public/assets/diagrams/hero-thumbs.svg +2 -4
  36. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  37. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  38. package/public/blog/git-at-agent-scale.html +2 -2
  39. package/public/blog/inside-your-boundary.html +1 -1
  40. package/public/blog/process-over-outcome-gates.html +1 -1
  41. package/public/case-studies.html +5 -6
  42. package/public/codex-enterprise.html +1 -1
  43. package/public/codex-plugin.html +1 -1
  44. package/public/dashboard.html +775 -483
  45. package/public/diagnostic.html +15 -10
  46. package/public/enterprise-governance.html +26 -174
  47. package/public/eval-scorecard.html +3 -4
  48. package/public/eval-scorecard.json +2 -2
  49. package/public/evaluations.html +0 -1
  50. package/public/founders.html +3 -3
  51. package/public/gaming-playbook.html +4 -4
  52. package/public/guide.html +3 -5
  53. package/public/index.html +302 -97
  54. package/public/install.html +16 -10
  55. package/public/js/buyer-intent.js +49 -8
  56. package/public/lessons.html +246 -83
  57. package/public/numbers.html +32 -33
  58. package/public/operator-framework.html +44 -72
  59. package/public/peter.html +3 -3
  60. package/public/platform-partners.html +1 -1
  61. package/public/pricing.html +163 -66
  62. package/public/pro.html +3 -1
  63. package/public/project-switcher.js +76 -0
  64. package/public/whitepaper.html +1 -2
  65. package/scripts/action-receipts.js +393 -0
  66. package/scripts/activation-quickstart.js +15 -3
  67. package/scripts/activation-tracker.js +280 -3
  68. package/scripts/agent-action-inventory.js +235 -143
  69. package/scripts/agent-operations-planner.js +1 -1
  70. package/scripts/agent-readiness.js +36 -6
  71. package/scripts/agentic-prompt-pipelines.js +901 -0
  72. package/scripts/analytics-window.js +7 -1
  73. package/scripts/async-job-runner.js +66 -11
  74. package/scripts/audit-trail.js +37 -24
  75. package/scripts/auto-promote-gates.js +37 -27
  76. package/scripts/auto-wire-hooks.js +64 -25
  77. package/scripts/backfill-lesson-scopes.js +122 -0
  78. package/scripts/billing.js +889 -132
  79. package/scripts/bot-detection.js +112 -0
  80. package/scripts/brand-standards-gate.js +571 -0
  81. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  82. package/scripts/cli-demo.js +5 -27
  83. package/scripts/cli-schema.js +25 -1
  84. package/scripts/commercial-offer.js +2 -2
  85. package/scripts/contextfs.js +9 -3
  86. package/scripts/craft-playbook-gate.js +550 -0
  87. package/scripts/cross-encoder-reranker.js +4 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +574 -167
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/docker-sandbox-planner.js +3 -3
  92. package/scripts/export-dpo-pairs.js +12 -7
  93. package/scripts/failure-diagnostics.js +11 -0
  94. package/scripts/feedback-aggregate.js +4 -0
  95. package/scripts/feedback-attribution.js +6 -4
  96. package/scripts/feedback-history-distiller.js +18 -6
  97. package/scripts/feedback-loop.js +255 -89
  98. package/scripts/feedback-paths.js +8 -1
  99. package/scripts/feedback-sanitizer.js +5 -0
  100. package/scripts/feedback-scope.js +106 -0
  101. package/scripts/feedback-session.js +8 -2
  102. package/scripts/filesystem-search.js +13 -8
  103. package/scripts/financial-control-plane.js +707 -45
  104. package/scripts/gate-stats.js +38 -5
  105. package/scripts/gates-engine.js +1326 -240
  106. package/scripts/generate-eval-scorecard.js +0 -1
  107. package/scripts/gitlab-sdlc-prompts.js +397 -0
  108. package/scripts/harness-tool-names.js +31 -5
  109. package/scripts/hook-runtime.js +10 -0
  110. package/scripts/hybrid-feedback-context.js +7 -2
  111. package/scripts/intervention-policy.js +2 -1
  112. package/scripts/lesson-canonical.js +2 -2
  113. package/scripts/lesson-db.js +55 -14
  114. package/scripts/lesson-graph.js +2 -1
  115. package/scripts/lesson-retrieval.js +95 -9
  116. package/scripts/lesson-search.js +86 -22
  117. package/scripts/lesson-synthesis.js +21 -5
  118. package/scripts/mabl-failure-honesty.js +273 -0
  119. package/scripts/mailer/index.js +17 -1
  120. package/scripts/mailer/resend-mailer.js +213 -179
  121. package/scripts/migrate-project-scope.js +209 -0
  122. package/scripts/model-distress-detector.js +3 -3
  123. package/scripts/operational-integrity.js +436 -3
  124. package/scripts/override-audit.js +2 -0
  125. package/scripts/owner-admin.js +338 -0
  126. package/scripts/pr-manager.js +194 -1
  127. package/scripts/product-feedback.js +35 -0
  128. package/scripts/progressive-signoff.js +260 -0
  129. package/scripts/project-catalog.js +243 -0
  130. package/scripts/project-dashboard.js +61 -0
  131. package/scripts/project-evidence.js +172 -0
  132. package/scripts/project-identity.js +182 -0
  133. package/scripts/project-scope.js +381 -0
  134. package/scripts/prompt-eval.js +1 -1
  135. package/scripts/prompt-guard.js +446 -52
  136. package/scripts/proof-report.js +232 -0
  137. package/scripts/provider-action-normalizer.js +14 -6
  138. package/scripts/qwenwork-policy-group.js +413 -0
  139. package/scripts/rate-limiter.js +41 -0
  140. package/scripts/secret-redaction.js +171 -25
  141. package/scripts/secret-scanner.js +101 -42
  142. package/scripts/self-protection.js +2 -2
  143. package/scripts/seo-gsd.js +14 -14
  144. package/scripts/session-context-dedupe.js +66 -0
  145. package/scripts/settings-hierarchy.js +4 -2
  146. package/scripts/statusline-meta.js +34 -23
  147. package/scripts/tailscale-october-access.js +416 -0
  148. package/scripts/task-outcomes.js +58 -2
  149. package/scripts/telemetry-analytics.js +260 -16
  150. package/scripts/thumbgate-search.js +23 -9
  151. package/scripts/tool-kpi-tracker.js +5 -2
  152. package/scripts/tool-registry.js +42 -1
  153. package/scripts/triage-savings-calculator.js +1 -1
  154. package/scripts/vector-store.js +4 -1
  155. package/scripts/verified-lessons.js +270 -0
  156. package/scripts/verify-marketing-pages-deployed.js +2 -2
  157. package/scripts/workflow-sentinel.js +29 -10
  158. package/server.json +2 -2
  159. package/src/api/server.js +2478 -470
  160. package/src/feedback.js +21 -0
  161. package/src/hermes-sync-plane.js +2 -1
  162. package/src/index.js +2 -0
  163. package/src/lesson-search.js +9 -0
  164. package/src/mckinsey-top-company-ai-coding.js +493 -0
  165. package/src/mcp/email-triage-server/index.js +973 -0
  166. package/src/mcp/email-triage-server/package.json +12 -0
  167. package/src/mcp/server.js +3 -0
  168. package/src/mcp-writeguard.js +772 -11
  169. package/src/openshell-lovable-engine.js +1475 -0
  170. package/src/task-outcome.js +3 -0
  171. package/config/evals/agent-safety-eval.json +0 -447
  172. package/config/evals/retrieval-ranking-golden.json +0 -522
  173. package/config/progressive/01-wire-only.json +0 -11
  174. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  175. package/config/progressive/03-one-lesson.json +0 -10
  176. package/config/progressive/04-warn-fires.json +0 -11
  177. package/config/progressive/05-strict-optional.json +0 -11
  178. package/config/progressive/README.md +0 -15
  179. package/public/assets/diagrams/agent-integration.png +0 -0
  180. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
@@ -1,83 +1,477 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- const { scanText, buildSafeSummary, redactText } = require('./secret-scanner');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const crypto = require('node:crypto');
7
+ const { scanText } = require('./secret-scanner');
8
+ const { SECRET_REDACTION_PATTERNS } = require('./secret-redaction');
9
+ const { resolveFeedbackDir } = require('./feedback-paths');
5
10
 
6
- function getFeedbackLoopModule() {
11
+ const PROMPT_SECRET_LEDGER_FILENAME = 'prompt-secret-ledger.jsonl';
12
+
13
+ const PROMPT_SECRET_BLOCK_REASON =
14
+ 'That message contains a password or key, so it was not sent to the agent. Put it in your password manager or macOS Keychain instead; if you already pasted it anywhere else, change it.';
15
+
16
+ const PEM_HEADER_REGEX = /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP |ENCRYPTED )?PRIVATE KEY-----/;
17
+ const PASSWORD_LINE_HINT_REGEX = /\b(?:password|passwd|passcode|pwd|pw)\b/i;
18
+
19
+ const SERVICE_BY_ID = {
20
+ anthropic_api_key: 'anthropic',
21
+ openai_api_key: 'openai',
22
+ openai_project_key: 'openai',
23
+ stripe_live_secret: 'stripe',
24
+ stripe_test_secret: 'stripe',
25
+ stripe_restricted_live: 'stripe',
26
+ stripe_restricted_test: 'stripe',
27
+ stripe_webhook_secret: 'stripe',
28
+ github_pat: 'github',
29
+ github_fine_grained_pat: 'github',
30
+ aws_access_key: 'aws',
31
+ google_api_key: 'google',
32
+ slack_token: 'slack',
33
+ pem_private_key: 'ssh_or_tls',
34
+ private_key_block: 'ssh_or_tls',
35
+ };
36
+
37
+ const PASSWORD_KEYWORDS = new Set(['password', 'passwd', 'passcode', 'pwd', 'pw']);
38
+ const COPULA_PASSWORD_KEYWORDS = new Set(['password', 'passwd', 'passcode']);
39
+ const SHORTHAND_PW_KEYWORDS = new Set(['pw', 'pwd']);
40
+ const DETERMINER_WORDS = new Set('my our the new current temp temporary updated'.split(' '));
41
+ const PREFIX_FILLER_WORDS = new Set(
42
+ 'my our your his her their its the a an this that new old current temp temporary updated changed reset real live test dev local prod production staging personal work company team shared account login signin user admin root master app service site portal dashboard here is was use using with and for on in to of'.split(' ')
43
+ );
44
+ const NON_SECRET_VALUE_WORDS = new Set(
45
+ 'string number boolean object null undefined true false none empty blank required optional redacted hidden masked secret password passwd passcode placeholder example todo tbd n/a na yes no on off'.split(' ')
46
+ );
47
+ const PROSE_WORDS_AFTER_KEYWORD = new Set(
48
+ 'reset resets resetting change changes changed changing update updates updated updating rotate rotated rotation manager managers vault vaults keychain store stored saved kept hashed hashing hash hashes salt encrypted encryption leaked exposed blocked redacted field fields input inputs prompt prompts policy policies check checks column columns form forms flow flows auth login logout signin signup page modal dialog screen button link error errors issue issues bug bugs fix test tests testing spec file files path env var vars config guard gate hook rule rules less only protection protected strength validation validator generator recovery forgot forgotten expired missing invalid incorrect rejected wrong broken safe strong weak short long good bad fine ok okay working fixed same different not still already never always now here in on at by of for from to with without before after into onto over under and or a an the my your our their this that what which who must should can will would could may might does did has have had is was are be'.split(' ')
49
+ );
50
+
51
+ function tryRequire(modPath) {
7
52
  try {
8
- return require('./feedback-loop');
53
+ return require(modPath);
9
54
  } catch {
10
55
  return null;
11
56
  }
12
57
  }
13
58
 
14
- function buildPromptGuardOutput(scanResult) {
59
+ function isAsciiAlpha(code) {
60
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
61
+ }
62
+
63
+ function isAsciiAlnum(code) {
64
+ return isAsciiAlpha(code) || (code >= 48 && code <= 57);
65
+ }
66
+
67
+ function isServiceBodyChar(code) {
68
+ return isAsciiAlnum(code) || code === 46 || code === 95 || code === 45;
69
+ }
70
+
71
+ function isTrailingSentencePunct(code) {
72
+ return code === 46 || code === 44 || code === 59 || code === 33 || code === 63;
73
+ }
74
+
75
+ function trimByCode(str, trimLeadFn, trimTrailFn) {
76
+ let start = 0;
77
+ let end = str.length;
78
+ while (start < end && trimLeadFn(str.codePointAt(start))) start += 1;
79
+ while (end > start && trimTrailFn(str.codePointAt(end - 1))) end -= 1;
80
+ return str.slice(start, end);
81
+ }
82
+
83
+ function lettersOnlyLower(raw) {
84
+ const input = String(raw || '').slice(0, 64);
85
+ let out = '';
86
+ for (let i = 0; i < input.length; i += 1) {
87
+ const code = input.codePointAt(i);
88
+ if (isAsciiAlpha(code)) out += input[i].toLowerCase();
89
+ }
90
+ return out;
91
+ }
92
+
93
+ function normalizeWordToken(raw) {
94
+ const input = String(raw || '').slice(0, 64);
95
+ const trimmed = trimByCode(input, (c) => !isAsciiAlnum(c), (c) => !isAsciiAlnum(c));
96
+ return trimmed.toLowerCase();
97
+ }
98
+
99
+ function sanitizeMetricId(raw) {
100
+ const input = String(raw || 'secret_material').slice(0, 64);
101
+ let out = '';
102
+ for (let i = 0; i < input.length; i += 1) {
103
+ const c = input.codePointAt(i);
104
+ out += isServiceBodyChar(c) ? input[i] : '_';
105
+ }
106
+ return out || 'secret_material';
107
+ }
108
+
109
+ function isPromptSecretGuardEnabled(options = {}) {
110
+ if (options.enabled === false) return false;
111
+ if (options.enabled === true) return true;
112
+ const env = options.env || process.env;
113
+ const raw = String(env.THUMBGATE_PROMPT_SECRET_GUARD ?? 'on').trim().toLowerCase();
114
+ return !['off', '0', 'false', 'no', 'disable', 'disabled'].includes(raw);
115
+ }
116
+
117
+ function sanitizeServiceToken(raw) {
118
+ const input = String(raw || '').trim();
119
+ if (!input || input.length > 64) return null;
120
+ const cleaned = trimByCode(input, (c) => !isAsciiAlnum(c), (c) => !isServiceBodyChar(c)).toLowerCase();
121
+ if (cleaned.length < 2 || cleaned.length > 32 || !isAsciiAlpha(cleaned.codePointAt(0))) return null;
122
+ for (let i = 1; i < cleaned.length; i += 1) {
123
+ if (!isServiceBodyChar(cleaned.codePointAt(i))) return null;
124
+ }
125
+ if (PREFIX_FILLER_WORDS.has(cleaned) || PASSWORD_KEYWORDS.has(cleaned) || PROSE_WORDS_AFTER_KEYWORD.has(cleaned)) {
126
+ return null;
127
+ }
128
+ return cleaned;
129
+ }
130
+
131
+ function extractServiceGuessFromWords(wordsBeforeKeyword, explicitForTarget = null) {
132
+ const fromFor = sanitizeServiceToken(explicitForTarget);
133
+ if (fromFor) return fromFor;
134
+ for (let i = wordsBeforeKeyword.length - 1; i >= 0; i -= 1) {
135
+ const candidate = sanitizeServiceToken(wordsBeforeKeyword[i]);
136
+ if (candidate) return candidate;
137
+ }
138
+ return 'unknown';
139
+ }
140
+
141
+ function stripMatchingQuotes(rawToken) {
142
+ let token = String(rawToken || '').trim();
143
+ while (token.length >= 2) {
144
+ const first = token[0];
145
+ const last = token[token.length - 1];
146
+ if ((first === '"' && last === '"') || (first === "'" && last === "'") || (first === '`' && last === '`')) {
147
+ token = token.slice(1, -1).trim();
148
+ } else {
149
+ break;
150
+ }
151
+ }
152
+ return token;
153
+ }
154
+
155
+ function isAllMaskChars(value) {
156
+ for (let i = 0; i < value.length; i += 1) {
157
+ const ch = value[i];
158
+ if (ch !== '*' && ch !== '.' && ch !== '-' && ch !== 'x' && ch !== 'X' && ch !== '•') return false;
159
+ }
160
+ return true;
161
+ }
162
+
163
+ function hasDisallowedPrefix(token, mode) {
164
+ if (token.startsWith('$') || token.startsWith('<') || token.startsWith('[')) return true;
165
+ if (mode === 'delimited') return false;
166
+ return token.startsWith('-') || token.startsWith('/') || token.startsWith('./') || token.startsWith('~/');
167
+ }
168
+
169
+ function isEnvironmentLookupValue(lower) {
170
+ return lower.startsWith('process.env') || lower.startsWith('os.environ') || lower.startsWith('env.');
171
+ }
172
+
173
+ function isAlphaOnlyWord(token) {
174
+ for (let i = 0; i < token.length; i += 1) {
175
+ if (!isAsciiAlpha(token.codePointAt(i))) return false;
176
+ }
177
+ return token.length > 0;
178
+ }
179
+
180
+ function isLikelySecretValue(rawToken, mode = 'delimited') {
181
+ const token = stripMatchingQuotes(rawToken);
182
+ if (token.length < 4 || hasDisallowedPrefix(token, mode)) return false;
183
+ const trimmedPunct = trimByCode(token, () => false, isTrailingSentencePunct);
184
+ const lower = trimmedPunct.toLowerCase();
185
+ if (lower.length < 4 || NON_SECRET_VALUE_WORDS.has(lower) || isAllMaskChars(lower) || isEnvironmentLookupValue(lower)) {
186
+ return false;
187
+ }
188
+ if (mode !== 'delimited') return !PROSE_WORDS_AFTER_KEYWORD.has(lower);
189
+ return !(PROSE_WORDS_AFTER_KEYWORD.has(lower) && isAlphaOnlyWord(trimmedPunct));
190
+ }
191
+
192
+ function splitWords(segment) {
193
+ return String(segment || '').trim().split(/\s+/).filter(Boolean);
194
+ }
195
+
196
+ function parseDelimitedLhs(lhsWords) {
197
+ if (lhsWords.length === 0) return null;
198
+ let endIdx = lhsWords.length;
199
+ if (lettersOnlyLower(lhsWords[endIdx - 1]) === 'is') endIdx -= 1;
200
+ if (endIdx === 0) return null;
201
+
202
+ const tailWord = lettersOnlyLower(lhsWords[endIdx - 1]);
203
+ if (PASSWORD_KEYWORDS.has(tailWord)) {
204
+ return { beforeWords: lhsWords.slice(0, endIdx - 1), explicitService: null };
205
+ }
206
+ if (endIdx >= 3 && lhsWords[endIdx - 2].toLowerCase() === 'for') {
207
+ const kw = lettersOnlyLower(lhsWords[endIdx - 3]);
208
+ if (PASSWORD_KEYWORDS.has(kw)) {
209
+ return { beforeWords: lhsWords.slice(0, endIdx - 3), explicitService: lhsWords[endIdx - 1] };
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+
215
+ function detectDelimitedOnLine(line) {
216
+ for (let i = 0; i < line.length; i += 1) {
217
+ const ch = line[i];
218
+ if ((ch !== ':' && ch !== '=') || (ch === ':' && line.slice(i, i + 3) === '://')) continue;
219
+ const lhsParsed = parseDelimitedLhs(splitWords(line.slice(0, i)));
220
+ if (!lhsParsed) continue;
221
+ const rhsWords = splitWords(line.slice(i + 1));
222
+ if (rhsWords.length > 0 && isLikelySecretValue(rhsWords[0], 'delimited')) {
223
+ return {
224
+ id: 'password_phrase',
225
+ label: 'Password phrase',
226
+ serviceGuess: extractServiceGuessFromWords(lhsParsed.beforeWords, lhsParsed.explicitService),
227
+ };
228
+ }
229
+ }
230
+ return null;
231
+ }
232
+
233
+ function hasCopulaContext(priorWords) {
234
+ return priorWords.some((w) => {
235
+ const lw = normalizeWordToken(w);
236
+ return DETERMINER_WORDS.has(lw) || Boolean(sanitizeServiceToken(w));
237
+ });
238
+ }
239
+
240
+ function hasShorthandPrefix(priorWords) {
241
+ return priorWords.every((w) => {
242
+ const lw = normalizeWordToken(w);
243
+ return PREFIX_FILLER_WORDS.has(lw) || Boolean(sanitizeServiceToken(w));
244
+ });
245
+ }
246
+
247
+ function checkCopulaPasswordAt(words, index) {
248
+ if (index + 2 >= words.length) return null;
249
+ const kw = normalizeWordToken(words[index]);
250
+ if (!COPULA_PASSWORD_KEYWORDS.has(kw) || normalizeWordToken(words[index + 1]) !== 'is') return null;
251
+ const prior = words.slice(Math.max(0, index - 4), index);
252
+ if (!hasCopulaContext(prior) || !isLikelySecretValue(words[index + 2], 'copula')) return null;
253
+ return { id: 'password_phrase', label: 'Password phrase', serviceGuess: extractServiceGuessFromWords(prior) };
254
+ }
255
+
256
+ function checkShorthandPwAt(words, index) {
257
+ if (index > 3 || index + 1 >= words.length) return null;
258
+ const kw = normalizeWordToken(words[index]);
259
+ if (!SHORTHAND_PW_KEYWORDS.has(kw)) return null;
260
+ const prior = words.slice(0, index);
261
+ if (!hasShorthandPrefix(prior) || !isLikelySecretValue(words[index + 1], 'shorthand')) return null;
262
+ return { id: 'password_phrase', label: 'Password phrase', serviceGuess: extractServiceGuessFromWords(prior) };
263
+ }
264
+
265
+ function detectUnpunctuatedClause(clause) {
266
+ const words = splitWords(clause);
267
+ for (let i = 0; i < words.length - 1; i += 1) {
268
+ const hit = checkCopulaPasswordAt(words, i) || checkShorthandPwAt(words, i);
269
+ if (hit) return hit;
270
+ }
271
+ return null;
272
+ }
273
+
274
+ function detectPasswordPhrase(text) {
275
+ const lines = String(text || '').split(/\r?\n/);
276
+ for (const line of lines) {
277
+ if (!line || !PASSWORD_LINE_HINT_REGEX.test(line)) continue;
278
+ const delimitedHit = detectDelimitedOnLine(line);
279
+ if (delimitedHit) return delimitedHit;
280
+ for (const clause of line.split(/[;|,()]+/)) {
281
+ const clauseHit = detectUnpunctuatedClause(clause);
282
+ if (clauseHit) return clauseHit;
283
+ }
284
+ }
285
+ return null;
286
+ }
287
+
288
+ function matchRedactionPattern(pattern, text) {
289
+ if (pattern.id === 'secret_assignment' || pattern.id === 'private_key_block') return null;
290
+ pattern.regex.lastIndex = 0;
291
+ const match = pattern.regex.exec(text);
292
+ if (!match) return null;
293
+ const id = pattern.id === 'jwt' ? 'jwt_token' : pattern.id;
294
+ const prefixWords = splitWords(text.slice(Math.max(0, match.index - 80), match.index)).slice(-5);
15
295
  return {
16
- continue: false,
17
- suppressOutput: true,
18
- stopReason: buildSafeSummary(
19
- scanResult.findings,
20
- 'Prompt blocked because it appears to contain secret material'
21
- ),
296
+ id,
297
+ label: pattern.label,
298
+ serviceGuess: SERVICE_BY_ID[id] || extractServiceGuessFromWords(prefixWords),
299
+ source: 'prompt',
22
300
  };
23
301
  }
24
302
 
25
- function evaluatePromptGuard(prompt, options = {}) {
26
- const text = String(prompt || '');
27
- if (!text.trim()) {
28
- return null;
303
+ function collectKnownKeyFindings(text) {
304
+ const findings = [];
305
+ if (text.includes('PRIVATE KEY-----') && PEM_HEADER_REGEX.test(text)) {
306
+ findings.push({ id: 'private_key_block', label: 'Private key block', serviceGuess: 'ssh_or_tls', source: 'prompt' });
29
307
  }
308
+ for (const pattern of SECRET_REDACTION_PATTERNS) {
309
+ const hit = matchRedactionPattern(pattern, text);
310
+ if (hit) findings.push(hit);
311
+ }
312
+ return findings;
313
+ }
30
314
 
31
- const scanResult = scanText(text, { provider: options.provider, source: 'prompt' });
32
- if (!scanResult.detected) {
33
- return null;
315
+ function collectFallbackScanFindings(text, provider) {
316
+ const scanResult = scanText(text, { provider: provider || 'heuristic', source: 'prompt' });
317
+ if (!scanResult.detected || !Array.isArray(scanResult.findings)) return [];
318
+ return scanResult.findings.map((f) => {
319
+ const id = f.id || 'secret_material';
320
+ return { id, label: f.label || 'Secret material', serviceGuess: SERVICE_BY_ID[id] || 'unknown', source: 'prompt' };
321
+ });
322
+ }
323
+
324
+ function detectPromptSecrets(prompt, options = {}) {
325
+ const text = String(prompt || '');
326
+ if (!text.trim()) return { detected: false, findings: [] };
327
+
328
+ const findings = collectKnownKeyFindings(text);
329
+ const passwordHit = detectPasswordPhrase(text);
330
+ if (passwordHit) findings.push({ ...passwordHit, source: 'prompt' });
331
+
332
+ if (findings.length === 0) {
333
+ findings.push(...collectFallbackScanFindings(text, options.provider));
34
334
  }
335
+ return { detected: findings.length > 0, findings };
336
+ }
35
337
 
36
- const feedbackLoop = getFeedbackLoopModule();
37
- if (feedbackLoop && typeof feedbackLoop.appendDiagnosticRecord === 'function') {
38
- feedbackLoop.appendDiagnosticRecord({
39
- source: 'secret_guard',
40
- step: 'user_prompt_submit',
41
- context: redactText(text).slice(0, 400),
42
- metadata: {
43
- provider: scanResult.provider,
44
- promptLength: text.length,
45
- },
46
- diagnosis: {
47
- diagnosed: true,
48
- rootCauseCategory: 'guardrail_triggered',
49
- criticalFailureStep: 'user_prompt_submit',
50
- violations: scanResult.findings.map((finding) => ({
51
- constraintId: `security:${finding.id || 'secret_exfiltration'}`,
52
- description: finding.reason || finding.label || 'Secret exposure blocked',
53
- metadata: {
54
- label: finding.label || finding.id || 'secret',
55
- line: finding.line || null,
56
- source: finding.source || null,
57
- },
58
- })),
59
- evidence: scanResult.findings.map((finding) => finding.label || finding.id || 'secret'),
60
- },
338
+ function buildDiagnosticRecord(safeType, safeService, timestamp) {
339
+ return {
340
+ source: 'secret_guard',
341
+ step: 'user_prompt_submit',
342
+ timestamp,
343
+ context: 'Redacted user prompt blocked before model submission',
344
+ metadata: { type: safeType, serviceGuess: safeService, time: timestamp },
345
+ diagnosis: {
346
+ diagnosed: true,
347
+ rootCauseCategory: 'guardrail_triggered',
348
+ criticalFailureStep: 'user_prompt_submit',
349
+ violations: [
350
+ {
351
+ constraintId: `security:${safeType}`,
352
+ description: 'Secret in user prompt blocked before model submission',
353
+ metadata: { type: safeType, serviceGuess: safeService, time: timestamp },
354
+ },
355
+ ],
356
+ evidence: [safeType],
357
+ },
358
+ };
359
+ }
360
+
361
+ function persistDiagnosticRecord(resolvedDir, feedbackDir, diagnosticRecord) {
362
+ const feedbackLoop = feedbackDir ? null : tryRequire('./feedback-loop');
363
+ try {
364
+ if (typeof feedbackLoop?.appendDiagnosticRecord === 'function') {
365
+ feedbackLoop.appendDiagnosticRecord(diagnosticRecord);
366
+ return;
367
+ }
368
+ fs.mkdirSync(resolvedDir, { recursive: true });
369
+ fs.appendFileSync(path.join(resolvedDir, 'diagnostic-log.jsonl'), `${JSON.stringify(diagnosticRecord)}\n`);
370
+ } catch { /* best-effort diagnostic write */ }
371
+ }
372
+
373
+ function persistAuditRecord(feedbackDir, safeType, safeService) {
374
+ if (feedbackDir) return;
375
+ const auditTrail = tryRequire('./audit-trail');
376
+ if (typeof auditTrail?.recordAuditEvent !== 'function') return;
377
+ try {
378
+ const rec = auditTrail.recordAuditEvent({
379
+ toolName: 'UserPromptSubmit',
380
+ toolInput: { type: safeType, serviceGuess: safeService },
381
+ decision: 'deny',
382
+ gateId: 'prompt-secret-guard',
383
+ message: 'Blocked secret in user prompt before model submission',
384
+ severity: 'critical',
385
+ source: 'secret-guard',
61
386
  });
62
- }
387
+ auditTrail.auditToFeedback?.(rec);
388
+ } catch { /* best-effort audit write */ }
389
+ }
63
390
 
64
- return buildPromptGuardOutput(scanResult);
391
+ function recordPromptSecretEvent({ type, serviceGuess, time, feedbackDir }) {
392
+ const resolvedDir = feedbackDir || resolveFeedbackDir();
393
+ const timestamp = time || new Date().toISOString();
394
+ const safeType = sanitizeMetricId(type);
395
+ const safeService = sanitizeServiceToken(serviceGuess) || SERVICE_BY_ID[safeType] || 'unknown';
396
+ const ledgerEntry = {
397
+ id: `psg_${crypto.randomUUID()}`,
398
+ event: 'prompt_secret_blocked',
399
+ type: safeType,
400
+ serviceGuess: safeService,
401
+ time: timestamp,
402
+ timestamp,
403
+ };
404
+
405
+ try {
406
+ fs.mkdirSync(resolvedDir, { recursive: true });
407
+ fs.appendFileSync(path.join(resolvedDir, PROMPT_SECRET_LEDGER_FILENAME), `${JSON.stringify(ledgerEntry)}\n`);
408
+ } catch { /* best-effort ledger write */ }
409
+
410
+ persistDiagnosticRecord(resolvedDir, feedbackDir, buildDiagnosticRecord(safeType, safeService, timestamp));
411
+ persistAuditRecord(feedbackDir, safeType, safeService);
412
+ return ledgerEntry;
65
413
  }
66
414
 
67
- function main() {
68
- const prompt = process.env.CLAUDE_USER_PROMPT || process.env.THUMBGATE_USER_PROMPT || '';
69
- const result = evaluatePromptGuard(prompt);
70
- if (!result) {
71
- return;
415
+ function buildPromptGuardOutput() {
416
+ return {
417
+ decision: 'block',
418
+ reason: PROMPT_SECRET_BLOCK_REASON,
419
+ continue: false,
420
+ suppressOutput: true,
421
+ stopReason: PROMPT_SECRET_BLOCK_REASON,
422
+ };
423
+ }
424
+
425
+ function evaluatePromptGuard(prompt, options = {}) {
426
+ if (!isPromptSecretGuardEnabled(options)) return null;
427
+ const detection = detectPromptSecrets(prompt, options);
428
+ if (!detection.detected || detection.findings.length === 0) return null;
429
+
430
+ const primary = detection.findings[0];
431
+ recordPromptSecretEvent({
432
+ type: primary.id,
433
+ serviceGuess: primary.serviceGuess,
434
+ time: options.now || new Date().toISOString(),
435
+ feedbackDir: options.feedbackDir,
436
+ });
437
+ return buildPromptGuardOutput();
438
+ }
439
+
440
+ function readPromptFromStdinSync() {
441
+ try {
442
+ if (process.stdin.isTTY) return '';
443
+ const raw = fs.readFileSync(0, 'utf8');
444
+ if (!raw?.trim()) return '';
445
+ const sanitizer = tryRequire('./feedback-sanitizer');
446
+ const envelopePrompt = sanitizer?.extractPromptEnvelope?.(raw)?.prompt;
447
+ if (typeof envelopePrompt === 'string') return envelopePrompt;
448
+ const parsed = JSON.parse(raw);
449
+ return typeof parsed?.prompt === 'string' ? parsed.prompt : raw;
450
+ } catch {
451
+ return '';
72
452
  }
73
- process.stdout.write(`${JSON.stringify(result)}\n`);
74
453
  }
75
454
 
76
- if (require.main === module) {
77
- main();
455
+ function main() {
456
+ const prompt =
457
+ process.env.CLAUDE_USER_PROMPT ||
458
+ process.env.THUMBGATE_USER_PROMPT ||
459
+ process.env.CODEX_USER_PROMPT ||
460
+ process.env.USER_PROMPT ||
461
+ readPromptFromStdinSync();
462
+ const result = evaluatePromptGuard(prompt);
463
+ if (result) process.stdout.write(`${JSON.stringify(result)}\n`);
78
464
  }
79
465
 
466
+ if (require.main === module) main();
467
+
80
468
  module.exports = {
469
+ PROMPT_SECRET_BLOCK_REASON,
470
+ PROMPT_SECRET_LEDGER_FILENAME,
81
471
  buildPromptGuardOutput,
472
+ detectPasswordPhrase,
473
+ detectPromptSecrets,
82
474
  evaluatePromptGuard,
475
+ isPromptSecretGuardEnabled,
476
+ recordPromptSecretEvent,
83
477
  };