@tnunamak/dalan 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +351 -0
  5. package/README.md +215 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +43 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +764 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/codex-to-muse.md +175 -0
  17. package/docs/connect-chatgpt.md +83 -0
  18. package/docs/connection-longevity.md +43 -0
  19. package/docs/dalan-upgrade.md +246 -0
  20. package/docs/deadman.md +61 -0
  21. package/docs/dot-pr-reviewer.config.example.json +9 -0
  22. package/docs/durability-audit.md +27 -0
  23. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  24. package/docs/keycloak-oauth-setup.md +30 -0
  25. package/docs/local-agent-mcp.md +41 -0
  26. package/docs/manual-setup.md +135 -0
  27. package/docs/mirror-fetch.md +97 -0
  28. package/docs/operations.md +799 -0
  29. package/docs/operator-duties.md +68 -0
  30. package/docs/owner-integrator.md +27 -0
  31. package/docs/portable-auth-profile.md +107 -0
  32. package/docs/pr-head-reviewer.md +70 -0
  33. package/docs/pr-preflight.md +28 -0
  34. package/docs/pull-queue.md +131 -0
  35. package/docs/pull-workers.md +94 -0
  36. package/docs/redaction.md +27 -0
  37. package/docs/service-setup.md +219 -0
  38. package/docs/setup-reference.md +80 -0
  39. package/docs/t3-connector-icon.png +0 -0
  40. package/docs/t3-integration.md +51 -0
  41. package/docs/t3-result-retry-delivery.md +41 -0
  42. package/docs/t3-reverse-control.md +107 -0
  43. package/docs/usage.md +443 -0
  44. package/docs/worker-clients.md +290 -0
  45. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  46. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  47. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  48. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  49. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  50. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  51. package/package.json +67 -4
  52. package/packages/job-core/README.md +18 -0
  53. package/packages/job-core/index.mjs +2 -0
  54. package/packages/job-core/package.json +8 -0
  55. package/packages/job-core/protocol/canonical.mjs +11 -0
  56. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  57. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  58. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  59. package/packages/job-core/transitions.mjs +25 -0
  60. package/scripts/daily-selfcheck.mjs +135 -0
  61. package/scripts/dalan-try-selfcheck.mjs +29 -0
  62. package/scripts/lib/expose-tailscale.mjs +408 -0
  63. package/scripts/live-trial/common.mjs +272 -0
  64. package/scripts/monitor-targets.mjs +44 -0
  65. package/scripts/upgrade-drain.mjs +39 -0
  66. package/scripts/worker-bridge-setup.mjs +925 -0
  67. package/src/ack-ledger.mjs +37 -0
  68. package/src/acp-bridge.mjs +418 -0
  69. package/src/acp-context.mjs +138 -0
  70. package/src/admin-socket.mjs +14 -0
  71. package/src/alerts.mjs +147 -0
  72. package/src/artifact-journal.mjs +75 -0
  73. package/src/as-files.mjs +347 -0
  74. package/src/as-store.mjs +456 -0
  75. package/src/as.mjs +538 -0
  76. package/src/auth.mjs +166 -0
  77. package/src/builtin-http.mjs +22 -0
  78. package/src/check-coverage.mjs +38 -0
  79. package/src/check-lint.mjs +88 -0
  80. package/src/check-readiness.mjs +112 -0
  81. package/src/check-response.mjs +19 -0
  82. package/src/child-exit.mjs +18 -0
  83. package/src/child-registry.mjs +94 -0
  84. package/src/claim-command-ledger.mjs +51 -0
  85. package/src/cli-help.mjs +186 -0
  86. package/src/cli-name.mjs +16 -0
  87. package/src/connect-cli.mjs +126 -0
  88. package/src/consumers.mjs +61 -0
  89. package/src/deadman.mjs +329 -0
  90. package/src/delivery.mjs +19 -0
  91. package/src/demo-worker.mjs +150 -0
  92. package/src/destinations/index.mjs +23 -0
  93. package/src/destinations/none.mjs +15 -0
  94. package/src/destinations/t3.mjs +109 -0
  95. package/src/diagnostic.mjs +78 -0
  96. package/src/docs-url.mjs +9 -0
  97. package/src/drain-runner.mjs +9 -0
  98. package/src/drained-owner.mjs +26 -0
  99. package/src/drained-slot.mjs +70 -0
  100. package/src/drained.mjs +40 -0
  101. package/src/durable-waiters.mjs +236 -0
  102. package/src/env.mjs +19 -0
  103. package/src/execution.mjs +112 -0
  104. package/src/failure-type.mjs +28 -0
  105. package/src/get-summary.mjs +32 -0
  106. package/src/git-env.mjs +15 -0
  107. package/src/host-budget-receipts.mjs +154 -0
  108. package/src/host-budget-seccomp.py +33 -0
  109. package/src/host-budget-service.mjs +54 -0
  110. package/src/host-budget-stop.mjs +26 -0
  111. package/src/host-budget-storage.py +259 -0
  112. package/src/host-budget.mjs +149 -0
  113. package/src/host-cgroup.mjs +23 -0
  114. package/src/host-check-allowlist.mjs +42 -0
  115. package/src/host-execution-policy.mjs +38 -0
  116. package/src/host-health.mjs +34 -0
  117. package/src/host-stop-reverify.mjs +44 -0
  118. package/src/inbox.mjs +55 -0
  119. package/src/integrator.mjs +322 -0
  120. package/src/job-retention.mjs +69 -0
  121. package/src/legacy-names.mjs +8 -0
  122. package/src/lifecycle.mjs +291 -0
  123. package/src/limits.mjs +31 -0
  124. package/src/loopback.mjs +9 -0
  125. package/src/mcp-outcome.mjs +79 -0
  126. package/src/mcp-sse.mjs +62 -0
  127. package/src/mcp-stdio.mjs +191 -0
  128. package/src/mirror-fetch-lock.py +164 -0
  129. package/src/mirror-fetch.mjs +174 -0
  130. package/src/notify-ledger.mjs +82 -0
  131. package/src/objectives.mjs +129 -0
  132. package/src/owner-report-artifact.mjs +66 -0
  133. package/src/patch-apply.mjs +84 -0
  134. package/src/path-syntax.mjs +16 -0
  135. package/src/paths.mjs +67 -0
  136. package/src/pr-head-reviewer.mjs +596 -0
  137. package/src/pr-preflight.mjs +51 -0
  138. package/src/prepared-node-modules.mjs +129 -0
  139. package/src/process-inspection.mjs +36 -0
  140. package/src/projects.mjs +480 -0
  141. package/src/protocol-artifact-commands.mjs +52 -0
  142. package/src/protocol-delivery-driver.mjs +167 -0
  143. package/src/protocol-finish.mjs +100 -0
  144. package/src/protocol-owner-command.mjs +35 -0
  145. package/src/protocol-owner-mutations.mjs +22 -0
  146. package/src/protocol-owner-waiters.mjs +67 -0
  147. package/src/protocol-retention.mjs +52 -0
  148. package/src/protocol-services.mjs +61 -0
  149. package/src/protocol-stop-observer.mjs +131 -0
  150. package/src/publish-plan.mjs +245 -0
  151. package/src/pull-queue.mjs +159 -0
  152. package/src/redaction.mjs +763 -0
  153. package/src/rejections.mjs +18 -0
  154. package/src/request-log.mjs +102 -0
  155. package/src/restore-check.mjs +90 -0
  156. package/src/result-binding.mjs +65 -0
  157. package/src/route-setting.mjs +24 -0
  158. package/src/runtime-check.mjs +13 -0
  159. package/src/sandbox-supervisor.mjs +105 -0
  160. package/src/schema-subset.mjs +186 -0
  161. package/src/scopes.mjs +15 -0
  162. package/src/server.mjs +1468 -0
  163. package/src/service-migrate-workers.mjs +113 -0
  164. package/src/service.mjs +388 -0
  165. package/src/setup.mjs +63 -0
  166. package/src/shutdown-signal.mjs +12 -0
  167. package/src/signal-sandbox-processes.py +56 -0
  168. package/src/signal.mjs +119 -0
  169. package/src/status-evidence.mjs +47 -0
  170. package/src/status-summary.mjs +54 -0
  171. package/src/store.mjs +3069 -0
  172. package/src/submission-policy.mjs +623 -0
  173. package/src/subscription-storage.mjs +64 -0
  174. package/src/t3-audit.mjs +120 -0
  175. package/src/t3-control.mjs +102 -0
  176. package/src/t3-transport.mjs +158 -0
  177. package/src/t3.mjs +209 -0
  178. package/src/terminal-safe.mjs +19 -0
  179. package/src/tool-registry.mjs +453 -0
  180. package/src/try-command.mjs +11 -0
  181. package/src/try-exposure.mjs +908 -0
  182. package/src/try-hosted-clients.mjs +46 -0
  183. package/src/try-hosted.mjs +444 -0
  184. package/src/try-selfcheck.mjs +168 -0
  185. package/src/try.mjs +635 -0
  186. package/src/webhooks.mjs +86 -0
  187. package/src/work-order.mjs +265 -0
  188. package/src/worker-instructions.mjs +26 -0
  189. package/src/worker-prompt.mjs +4 -0
  190. package/src/workers.mjs +632 -0
  191. package/src/workspace.mjs +1065 -0
  192. package/systemd/dot-bridge-heartbeat.service +18 -0
  193. package/systemd/dot-bridge-heartbeat.timer +10 -0
  194. package/systemd/dot-bridge-selfcheck.service +12 -0
  195. package/systemd/dot-bridge-selfcheck.timer +11 -0
  196. package/systemd/dot-bridge.service +17 -0
  197. package/systemd/dot-deadman.service +30 -0
  198. package/systemd/dot-pr-reviewer.service +11 -0
  199. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,763 @@
1
+ // One content policy for admission and every worker-visible text path.
2
+ // Known-prefix families match even glued to a word character; the generic shapes keep a leading word boundary.
3
+ const tokenContent=/(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{30,}|AKIA[A-Z0-9]{16}|\bsk-[A-Za-z0-9_-]{24,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|rk_live_[A-Za-z0-9]{16,}|(?:xoxe\.)?(?:xox[abposr]|xapp)-[A-Za-z0-9-]{10,}|xoxe-[A-Za-z0-9-]{10,}|AIza[A-Za-z0-9_-]{35}|whsec_[A-Za-z0-9+/=_-]{8,}|glpat-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{36}|(?:https:\/\/)?hooks\.slack\.com\/services\/T[A-Z0-9]{8,}\/B[A-Z0-9]{8,}\/[A-Za-z0-9]{20,}|\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}|GOCSPX-[A-Za-z0-9_-]{20,}|\bya29\.[A-Za-z0-9_-]{20,}|\b1\/\/[A-Za-z0-9_-]{30,}|\b\d{8,10}:[A-Za-z0-9_-]{35}|\b[A-Za-z0-9_-]{24}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27})\b|(?<![a-z0-9+.-])\b[a-z][a-z0-9+.-]*:\/\/[^\s:@\/]+:[^\s@\/]+@(?!(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|db|postgres|mysql|redis|mongo|example\.(?:com|org|net)|host\.docker\.internal)\b)[^\s\/]+/i;
4
+
5
+ function dashEnd(input,start) {
6
+ let end=start+1;
7
+ while(input[end]==='-') end++;
8
+ return end;
9
+ }
10
+
11
+ // Keep a source span for every normalized code unit: compatibility characters
12
+ // may expand, and ignored characters must still be covered by a mask.
13
+ function normalizedKeyMarkers(input) {
14
+ const normalize=text=>text.replace(/\\u00([0-7][0-9a-f])/gi,(_match,hex)=>String.fromCharCode(parseInt(hex,16))).normalize('NFKC').toUpperCase().replace(/[\p{Default_Ignorable_Code_Point}\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/gu,'').replace(/\u0399/g,'I').replace(/[\p{Dash}\u02d7\u2043\u2796]/gu,'-');
15
+ const chunks=[],starts=[],ends=[];
16
+ let marks=0,rawMarks=0,lineStart=0,lineChunks=[],sourceStarts=[],sourceEnds=[],segmenter;
17
+ const finishLine=lineEnd=>{
18
+ const source=input.slice(lineStart,lineEnd),line=normalize(source);
19
+ let exact=lineChunks.join('')===line;
20
+ if(!exact) {
21
+ segmenter??=new Intl.Segmenter('und',{granularity:'grapheme'});
22
+ const pieces=[],segmentStarts=[],segmentEnds=[];
23
+ for(const part of segmenter.segment(source)) {
24
+ const piece=normalize(part.segment);
25
+ pieces.push(piece);
26
+ for(let i=0;i<piece.length;i++) {segmentStarts.push(lineStart+part.index);segmentEnds.push(lineStart+part.index+part.segment.length);}
27
+ }
28
+ if(pieces.join('')===line) {sourceStarts=segmentStarts;sourceEnds=segmentEnds;exact=true;}
29
+ }
30
+ chunks.push(line);
31
+ for(let i=0;i<line.length;i++) {
32
+ starts.push(exact?sourceStarts[i]:lineStart);
33
+ ends.push(exact?sourceEnds[i]:lineEnd);
34
+ }
35
+ lineChunks=[];sourceStarts=[];sourceEnds=[];
36
+ };
37
+ // ASCII text without escapes already has identity source offsets. Normalize
38
+ // the whole string once instead of invoking Unicode operations for each byte.
39
+ if(/^[\t\r\n\x20-\x7e]*$/.test(input)&&!input.includes('\\')) {
40
+ chunks.push(input.toUpperCase());
41
+ for(let i=0;i<input.length;i++) {starts.push(i);ends.push(i+1);}
42
+ } else {
43
+ for(let offset=0;offset<input.length;) {
44
+ const escape=input[offset]==='\\'?/^\\u00[0-7][0-9a-f]/i.exec(input.slice(offset,offset+6)):null;
45
+ const char=escape?String.fromCharCode(parseInt(escape[0].slice(2),16)):String.fromCodePoint(input.codePointAt(offset));
46
+ const end=offset+(escape?6:char.length);
47
+ const escapedBreak=char==='\\'&&/[nN]/.test(input[offset+1]??'')?2:
48
+ char==='\\'&&/[rR]/.test(input[offset+1]??'')&&input[offset+2]==='\\'&&/[nN]/.test(input[offset+3]??'')?4:0;
49
+ if(escapedBreak) {
50
+ finishLine(offset);
51
+ for(let i=0;i<escapedBreak;i++) {chunks.push(normalize(input[offset+i]));starts.push(offset+i);ends.push(offset+i+1);}
52
+ offset+=escapedBreak;lineStart=offset;marks=0;rawMarks=0;continue;
53
+ }
54
+ if(char==='\n') {
55
+ finishLine(offset);chunks.push(char);starts.push(offset);ends.push(end);
56
+ lineStart=end;marks=0;rawMarks=0;offset=end;continue;
57
+ }
58
+ if(/\p{M}/u.test(char)) rawMarks++;
59
+ else if(!/\p{Default_Ignorable_Code_Point}/u.test(char)) rawMarks=0;
60
+ if(rawMarks>64) return [{kind:'OVERFLOW',start:0,end:input.length}];
61
+ // Count NFKC marks before case folding can turn one into a letter.
62
+ for(const unit of char.normalize('NFKC')) {
63
+ if(/\p{Default_Ignorable_Code_Point}/u.test(unit)) continue;
64
+ marks=/\p{M}/u.test(unit)?marks+1:0;
65
+ if(marks>64) return [{kind:'OVERFLOW',start:0,end:input.length}];
66
+ }
67
+ const normalized=normalize(char);
68
+ lineChunks.push(normalized);
69
+ for(let i=0;i<normalized.length;i++) {sourceStarts.push(offset);sourceEnds.push(end);}
70
+ offset=end;
71
+ }
72
+ finishLine(input.length);
73
+ }
74
+ let text=chunks.join('');
75
+ // Join line folds only inside marker words, retaining original source offsets.
76
+ const fold=String.raw`(?:\r?\n|\\R\\N|\\N)`;
77
+ const words=['BEGIN','END','PRIVATE','KEY'];
78
+ const patterns=words.flatMap(word=>Array.from({length:word.length-1},(_,required)=>
79
+ [...word].map((char,i)=>i===0?char:`${fold}${i-1===required?'+':'*'}${char}`).join('')));
80
+ const removed=[];
81
+ for(const hit of text.matchAll(new RegExp(patterns.join('|'),'g'))) {
82
+ for(const part of hit[0].matchAll(new RegExp(fold,'g'))) removed.push([hit.index+part.index,part[0].length]);
83
+ }
84
+ if(removed.length) {
85
+ const parts=[];let cursor=0,write=0;
86
+ for(const [start,length] of removed) {
87
+ parts.push(text.slice(cursor,start));
88
+ for(let i=cursor;i<start;i++) {starts[write]=starts[i];ends[write++]=ends[i];}
89
+ cursor=start+length;
90
+ }
91
+ parts.push(text.slice(cursor));
92
+ for(let i=cursor;i<text.length;i++) {starts[write]=starts[i];ends[write++]=ends[i];}
93
+ starts.length=write;ends.length=write;text=parts.join('');
94
+ }
95
+ const sep=String.raw`(?:[\s:/_\-]|\\[RN])`;
96
+ const header=new RegExp(String.raw`(BEGIN|END)(?:[\s:/\-]|\\[RN]){0,3}(?:(?:SSH2${sep}+ENCRYPTED|RSA|DSA|EC|OPENSSH|ENCRYPTED|PGP|ED25519|SSH2)${sep}+)?PRIVATE${sep}*KEY(?:[ \t]+BLOCK)?`,'g');
97
+ const label=new RegExp(String.raw`\bPRIVATE(?:[\s_\-]|\\[RN])*KEY\b`,'g');
98
+ const styleAt=position=>{
99
+ let start=position;
100
+ while(start>0&&(text[start-1]===' '||text[start-1]==='\t')) start--;
101
+ const end=start;
102
+ while(start>0&&text[start-1]==='-') start--;
103
+ if(start===end) return '';
104
+ const style=input.slice(starts[start],ends[end-1]);
105
+ return /^[-\u2010-\u2015\u2212]+$/u.test(style)?style:null;
106
+ };
107
+ let controls=[];
108
+ const labelEnd=/[ \t\-"'*]*(?=\r?\n|\\R\\N|\\N|$)/y;
109
+ for(const match of text.matchAll(header)) {
110
+ const start=match.index;let end=start+match[0].length;
111
+ const style=styleAt(start);
112
+ let left=start;
113
+ while(left>0&&(text[left-1]===' '||text[left-1]==='\t')) left--;
114
+ let dashStart=left;
115
+ while(dashStart>0&&text[dashStart-1]==='-') dashStart--;
116
+ let dashCount=left-dashStart;
117
+ if(style==='') {
118
+ // Soft hyphens are deleted by normalization but remain a dash-shaped opener.
119
+ let before=starts[start]-1;
120
+ while(before>=0&&(input[before]===' '||input[before]==='\t'||/\p{Default_Ignorable_Code_Point}/u.test(input[before]))) {
121
+ if(input[before]==='\u00ad') dashCount++;
122
+ before--;
123
+ }
124
+ if(!dashCount) continue;
125
+ }
126
+ const keyEnd=start+match[0].lastIndexOf('KEY')+3;
127
+ if(!/^-+$/.test(style??'')&&/[A-Z0-9_]/.test(text[keyEnd]??'')) continue;
128
+ const labelSeparators=match[0].slice(match[0].indexOf('PRIVATE')+7,match[0].lastIndexOf('KEY'));
129
+ if(style===''&&/[:/]/.test(labelSeparators)) continue;
130
+ while(text[end]==='-') end++;
131
+ labelEnd.lastIndex=end;
132
+ controls.push({kind:match[1],start:starts[start],end:ends[end-1],headerEnd:ends[start+match[0].length-1],style,dashCount,terminal:labelEnd.test(text),normalizedStart:start,normalizedEnd:start+match[0].length});
133
+ }
134
+ // Index line boundaries and body lines once; later labels advance monotonically.
135
+ const lineStarts=[0],breaks=/\r\n|\n|\\R\\N|\\N/g;
136
+ for(const hit of text.matchAll(breaks)) lineStarts.push(hit.index+hit[0].length);
137
+ const bodyLines=[],armorBodyLines=[],strongArmorBodyLines=[];
138
+ for(let i=0;i<lineStarts.length;i++) {
139
+ const end=i+1<lineStarts.length?lineStarts[i+1]:text.length;
140
+ const body=/^[ \t>]*(?:(?:#|\/\/)[ \t]*)?([A-Z0-9+/]{16,}={0,2})[ \t]*(?:\r?\n|\\R\\N|\\N|$)/.exec(text.slice(lineStarts[i],end));
141
+ if(body) {
142
+ armorBodyLines.push(i);
143
+ // A bare 40/64-character hex string is a Git/SHA ID, not key evidence.
144
+ if(!/^(?:[A-F0-9]{40}|[A-F0-9]{64})$/i.test(body[1])) strongArmorBodyLines.push(i);
145
+ if(body[1].length>=40&&!/^[A-F0-9]+$/.test(body[1])) bodyLines.push(i);
146
+ }
147
+ }
148
+ let controlLine=0,armorBody=0,strongBody=0;
149
+ controls=controls.filter(marker=>{
150
+ while(controlLine+1<lineStarts.length&&lineStarts[controlLine+1]<=marker.normalizedEnd) controlLine++;
151
+ while(armorBody<armorBodyLines.length&&armorBodyLines[armorBody]<=controlLine) armorBody++;
152
+ while(strongBody<strongArmorBodyLines.length&&strongArmorBodyLines[strongBody]<=controlLine) strongBody++;
153
+ // Only a label that ends its line (a canonical banner shape) may rely on a hex body.
154
+ const lines=marker.terminal?armorBodyLines:strongArmorBodyLines,at=marker.terminal?armorBody:strongBody;
155
+ const hasBody=at<lines.length&&lines[at]<=controlLine+2;
156
+ return marker.kind!=='BEGIN'||((marker.dashCount>=3||hasBody)&&(/^-+$/.test(marker.style??'')||marker.terminal||hasBody));
157
+ });
158
+ const bodyMarkers=[];let line=0,labelLine=0,body=0,control=0;
159
+ for(const match of text.matchAll(label)) {
160
+ while(control<controls.length&&controls[control].normalizedEnd<=match.index) control++;
161
+ if(control<controls.length&&controls[control].kind==='BEGIN'&&controls[control].normalizedStart<=match.index) continue;
162
+ while(labelLine+1<lineStarts.length&&lineStarts[labelLine+1]<=match.index) labelLine++;
163
+ if(!/^[ \t]*(?:(?:\/\/|[#*>"'])[ \t]*)*$/.test(text.slice(lineStarts[labelLine],match.index))) continue;
164
+ labelEnd.lastIndex=match.index+match[0].length;
165
+ if(!labelEnd.test(text)) continue;
166
+ while(line+1<lineStarts.length&&lineStarts[line+1]<=match.index+match[0].length) line++;
167
+ while(body<bodyLines.length&&bodyLines[body]<=line) body++;
168
+ if(body<bodyLines.length&&bodyLines[body]<=line+2) bodyMarkers.push({kind:'BEGIN',start:starts[match.index],end:ends[match.index+match[0].length-1],style:null,normalizedStart:match.index});
169
+ }
170
+ const markers=[];let i=0,j=0;
171
+ while(i<controls.length||j<bodyMarkers.length) {
172
+ if(j===bodyMarkers.length||(i<controls.length&&controls[i].normalizedStart<=bodyMarkers[j].normalizedStart)) markers.push(controls[i++]);
173
+ else markers.push(bodyMarkers[j++]);
174
+ }
175
+ return markers;
176
+ }
177
+ // Scan each control's label once, stopping at a closing dash line or the next
178
+ // control. Failed labels never retry the same suffix for every KEY candidate.
179
+ function* armorMarkers(input) {
180
+ // These dashes occupy one UTF-16 code unit, so marker offsets still index
181
+ // the original text that callers redact.
182
+ const original=input;
183
+ input=input.replace(/[\p{Dash}\u02d7\u2043\u2796]/gu,char=>char.length===1?'-':char);
184
+ const control=/\s*(BEGIN|END)\b/iy;
185
+ const controlAt=start=>{
186
+ control.lastIndex=start;
187
+ const match=control.exec(input);
188
+ return match?{kind:match[1].toUpperCase(),end:control.lastIndex}:null;
189
+ };
190
+ // Discover openers independently so parsing one marker cannot hide another.
191
+ const controls=[];
192
+ for(let cursor=0;cursor<input.length;) {
193
+ const start=input.indexOf('-',cursor);
194
+ if(start<0) break;
195
+ const end=dashEnd(input,start),kind=controlAt(end);
196
+ if(kind&&(input[kind.end]==='-'||/\s/.test(input[kind.end]??''))) controls.push({start,leftEnd:end,kind});
197
+ cursor=end;
198
+ }
199
+ const closing=(from,width,limit,substring)=>{
200
+ let cursor=from,hasKey=false,first=null;
201
+ const keyLabel=substring?/(?:KEY|PRIVATE)/i:/\b(?:KEY|PRIVATE)\b/i;
202
+ while(cursor<limit) {
203
+ const start=input.indexOf('-',cursor);
204
+ if(start<0||start>=limit) break;
205
+ const text=input.slice(cursor,start);
206
+ hasKey ||= keyLabel.test(text);
207
+ const end=dashEnd(input,start),right=end-start;
208
+ if(hasKey) {
209
+ const candidate={start,end,right};
210
+ first??=candidate;
211
+ if(right===width) return {close:candidate};
212
+ }
213
+ // Interior hyphens may belong to a label. Prefer equal delimiters, but
214
+ // retain the first permissive close when the marker is malformed.
215
+ if(end===input.length||input[end]==='\n'||input.startsWith('\r\n',end)) return {close:first};
216
+ cursor=end;
217
+ }
218
+ // A recognizable key label may be cut off before its closing dashes.
219
+ hasKey ||= keyLabel.test(input.slice(cursor,limit));
220
+ return {close:first??(hasKey?{start:limit,end:limit,right:0}:null)};
221
+ };
222
+ // A key label whose line is followed by a base64 (or PEM header) body line,
223
+ // across a real or a JSON-escaped line break. Searches resume monotonically,
224
+ // and the last line verdict is reused, so a long line stays linear.
225
+ const keyWord=/(?:KEY|PRIVATE)/gi,keyWordWhole=/\b(?:KEY|PRIVATE)\b/gi,lineBreak=/\r?\n|\\(?:r\\)?n/g,bodyLine=/(?:[ \t>]*(?:(?:Comment|Version):[^\r\n\\]*|Bag Attributes[^\r\n\\]*)?(?:\r?\n|\\(?:r\\)?n)){0,3}[ \t>]*(?:[A-Za-z0-9+\/]{16,}={0,2}[ \t]*(?:\\[rn]|[\r\n]|$)|(?:Proc-Type|DEK-Info):)/iy;
226
+ // The strong variant rejects a bare 40/64-character hex line (a commit ID).
227
+ const strongBodyLine=new RegExp(bodyLine.source.replace('[ \\t>]*(?:[A-Za-z0-9+','[ \\t>]*(?:(?![0-9a-f]{40}(?:[0-9a-f]{24})?={0,2}[ \\t]*(?:\\\\[rn]|[\\r\\n]|$))[A-Za-z0-9+'),'iy');
228
+ if(strongBodyLine.source===bodyLine.source) throw new Error('strong body-line pattern not derived');
229
+ const bodyVerdict=pattern=>{
230
+ const states = [0, 1].map(() => ({ lastBreak: -1, lastVerdict: false, nextKey: null, exhausted: false }));
231
+ return (from,substring)=>{
232
+ const state = states[substring ? 1 : 0];
233
+ const search=substring?keyWord:keyWordWhole;
234
+ // Callers advance from left to right. Reuse a future hit (or EOF)
235
+ // instead of searching the same suffix again for every marker.
236
+ if(!state.exhausted&&(!state.nextKey||state.nextKey.index<from)) {
237
+ search.lastIndex=from;
238
+ state.nextKey=search.exec(input);
239
+ state.exhausted=!state.nextKey;
240
+ }
241
+ const key=state.nextKey;
242
+ if(!key) return false;
243
+ if(key.index>state.lastBreak) {
244
+ lineBreak.lastIndex=key.index;
245
+ const hit=lineBreak.exec(input);
246
+ state.lastBreak=hit?hit.index:Infinity;
247
+ pattern.lastIndex=lineBreak.lastIndex;
248
+ state.lastVerdict=!!hit&&pattern.test(input);
249
+ }
250
+ return state.lastVerdict;
251
+ };
252
+ };
253
+ const bodyAfterKey=bodyVerdict(bodyLine),strongBodyAfterKey=bodyVerdict(strongBodyLine);
254
+ for(let i=0;i<controls.length;i++) {
255
+ const {start,leftEnd,kind}=controls[i],left=leftEnd-start;
256
+ const style=original.slice(start,leftEnd),substring=/^-+$/.test(style);
257
+ const limit=controls[i+1]?.start??input.length;
258
+ let parsed;
259
+ if(input[kind.end]==='-'&&kind.end<limit) {
260
+ const end=dashEnd(input,kind.end);
261
+ parsed={close:{start:kind.end,end,right:end-kind.end}};
262
+ } else parsed=closing(kind.end,left,limit,substring);
263
+ if(!parsed.close) continue;
264
+ const {end,right}=parsed.close;
265
+ const name=input.slice(kind.end,parsed.close.start).trim().replace(/\s+/g,' ').toUpperCase();
266
+ if(!substring&&!/^(?:(?:RSA|DSA|EC|OPENSSH|ENCRYPTED|PGP|ED25519|SSH2(?:[ _-]+ENCRYPTED)?)[ _-]+)?PRIVATE[ _-]+KEY$/.test(name)&&!(/\b(?:KEY|PRIVATE)\b/.test(name)&&strongBodyAfterKey(kind.end,false))) continue;
267
+ // Five or more dashes are an unmistakable delimiter. A shorter run is armor
268
+ // when it stands alone (no glued word, equal closing run, bare label) or when
269
+ // a key label is followed by a base64 body line, however the run is glued,
270
+ // paired or punctuated. Hyphenated prose such as "front-end private API" and
271
+ // markdown "- End one: ..." bullets are neither.
272
+ if(left<5) {
273
+ const bare=!/\w/.test(input[start-1]??'')&&right===left&&/^[\w\s\/+-]*$/.test(input.slice(kind.end,parsed.close.start));
274
+ const keyLabel=substring?/(?:KEY|PRIVATE)/:/\b(?:KEY|PRIVATE)\b/;
275
+ const canonical=/^(?:(?:RSA|DSA|EC|OPENSSH|ENCRYPTED|PGP|ED25519|SSH2(?:[ _-]+ENCRYPTED)?)[ _-]+)?PRIVATE[ _-]+KEY$/.test(name);
276
+ const hasBody=substring||canonical?bodyAfterKey:strongBodyAfterKey;
277
+ if(!bare&&!(keyLabel.test(name)&&hasBody(kind.end,substring))) continue;
278
+ }
279
+ if(substring?/(?:KEY|PRIVATE)/.test(name):/\b(?:KEY|PRIVATE)\b/.test(name)) yield {start,end,left,right,kind:kind.kind,name,style,closeStyle:original.slice(parsed.close.start,end)};
280
+ }
281
+ }
282
+
283
+ // Original main-branch armor scanner, retained for main-parity.
284
+ function* legacyArmorMarkers(input) {
285
+ const control=/\s*(BEGIN|END)\b/iy;
286
+ const controlAt=start=>{
287
+ control.lastIndex=start;
288
+ const match=control.exec(input);
289
+ return match?{kind:match[1].toUpperCase(),end:control.lastIndex}:null;
290
+ };
291
+ const closing=(from,width)=>{
292
+ let cursor=from,hasKey=false,first=null;
293
+ while(cursor<input.length) {
294
+ const start=input.indexOf('-',cursor);
295
+ if(start<0) break;
296
+ const text=input.slice(cursor,start);
297
+ hasKey ||= /KEY|PRIVATE/i.test(text);
298
+ const end=dashEnd(input,start),right=end-start;
299
+ if(hasKey) {
300
+ const candidate={start,end,right};
301
+ first??=candidate;
302
+ if(right===width) return {close:candidate};
303
+ }
304
+ // Interior hyphens may belong to a label. Prefer equal delimiters, but
305
+ // retain the first permissive close when the marker is malformed.
306
+ if(end===input.length||input[end]==='\n'||input.startsWith('\r\n',end)||controlAt(end)) return {close:first,resume:start};
307
+ cursor=end;
308
+ }
309
+ // A recognizable key label may be cut off before its closing dashes.
310
+ hasKey ||= /KEY|PRIVATE/i.test(input.slice(cursor));
311
+ return {close:first??(hasKey?{start:input.length,end:input.length,right:0}:null),resume:input.length};
312
+ };
313
+ let cursor=0;
314
+ while(cursor<input.length) {
315
+ const start=input.indexOf('-',cursor);
316
+ if(start<0) return;
317
+ const leftEnd=dashEnd(input,start),left=leftEnd-start,kind=controlAt(leftEnd);
318
+ if(!kind||!(input[kind.end]==='-'||/\s/.test(input[kind.end]??''))) {cursor=leftEnd;continue;}
319
+ let parsed;
320
+ if(input[kind.end]==='-') {
321
+ const end=dashEnd(input,kind.end);
322
+ parsed={close:{start:kind.end,end,right:end-kind.end}};
323
+ } else parsed=closing(kind.end,left);
324
+ if(!parsed.close) {cursor=parsed.resume;continue;}
325
+ const {end,right}=parsed.close;
326
+ const name=input.slice(kind.end,parsed.close.start).trim().replace(/\s+/g,' ').toUpperCase();
327
+ if(/KEY|PRIVATE/.test(name)) yield {start,end,left,right,kind:kind.kind,name};
328
+ cursor=end;
329
+ }
330
+ }
331
+
332
+ // Callers share a .test interface; neither detection path reintroduces the
333
+ // unbounded armor expression during admission or the final output pass.
334
+ export const privateKeyHeader=Object.freeze({test(value) {
335
+ const input=String(value);
336
+ for(const marker of normalizedKeyMarkers(input)) if(marker.kind==='BEGIN'||marker.kind==='OVERFLOW') return true;
337
+ for(const marker of armorMarkers(input)) if(marker.kind==='BEGIN') return true;
338
+ for(const marker of legacyArmorMarkers(input)) if(marker.kind==='BEGIN') return true;
339
+ return false;
340
+ }});
341
+ export const secretContent=Object.freeze({test(value) {return knownSecretRanges(String(value)).length>0||privateKeyHeader.test(value)||tokenContent.test(value);}});
342
+
343
+ // Intake refuses only known values and strong formats (armor, PEM bodies, token families, URL userinfo).
344
+ // Inspect actual string values: JSON serialization hides marker line breaks.
345
+ // Past the depth cap or on a cycle the value cannot be inspected, so fail closed.
346
+ const MAX_DEPTH=100;
347
+ export function hasSecretContent(value,depth=0,seen=new WeakSet()) {
348
+ if(typeof value==='string') return secretContent.test(value)||pemBodyRanges(value).next().done===false;
349
+ if(value&&typeof value==='object') {
350
+ if(depth>MAX_DEPTH||seen.has(value)) return true;
351
+ seen.add(value);
352
+ const found=Object.entries(value).some(([key,item])=>secretContent.test(key)||hasSecretContent(item,depth+1,seen));
353
+ seen.delete(value);
354
+ return found;
355
+ }
356
+ return false;
357
+ }
358
+
359
+ // A PEM body with its BEGIN line cut off: two or more full-width (64 or 76)
360
+ // base64 lines followed by a short tail line, or base64 lines directly above
361
+ // an END ... KEY footer. Long unwrapped base64 and code are not matched.
362
+ export function* pemBodyRanges(text) {
363
+ // A JSON-escaped newline (a literal backslash-n) also ends a line, so an escaped key body is found too.
364
+ // Quoting around a line (a JSON string) is not part of the body: the line is the base64 run inside it. `=` is not a
365
+ // delimiter here, because base64 padding ends a body.
366
+ const lines=[...String(text).matchAll(/(?:(?!\\[rn])(?<!\\)[^\r\n\u2028\u2029])+/g)].map(m=>{
367
+ const run=/^(.*?[\s"'`:,([{])??([A-Za-z0-9+/=]+)([\s"'`,)\]}]*(?:["'`]\s*:\s*[\w.+-]*[\s"'`,)\]}]*)?)$/s.exec(m[0]);
368
+ if(!run) return {start:m.index,end:m.index+m[0].length,text:m[0].trim()};
369
+ const start=m.index+(run[1]?.length??0);
370
+ return {start,end:start+run[2].length,text:run[2]};
371
+ });
372
+ const b64=line=>line&&/^[A-Za-z0-9+/]+={0,2}$/.test(line.text)&&!/^[a-f0-9]+$/i.test(line.text);
373
+ const full=line=>b64(line)&&(line.text.length===64||line.text.length===76);
374
+ const footer=line=>line&&/^-*\s*END\b[^\r\n]*KEY/i.test(line.text);
375
+ const covered=new Set();
376
+ const emit=(from,to)=>{for(let i=from;i<=to;i++) covered.add(i);};
377
+ for(let i=0;i<lines.length;) {
378
+ if(!full(lines[i])) {i++;continue;}
379
+ let j=i;
380
+ while(full(lines[j+1])&&lines[j+1].text.length===lines[i].text.length) j++;
381
+ if(j>i||footer(lines[j+1])) emit(i,j+(b64(lines[j+1])&&lines[j+1].text.length<lines[i].text.length?1:0));
382
+ i=j+1;
383
+ }
384
+ for(let i=0;i<lines.length;i++) {
385
+ if(!footer(lines[i+1])||!b64(lines[i])) continue;
386
+ let k=i;
387
+ while(b64(lines[k-1])) k--;
388
+ emit(k,i);
389
+ }
390
+ for(const i of [...covered].sort((a,b)=>a-b)) yield {start:lines[i].start,end:lines[i].end};
391
+ }
392
+
393
+ // Each scanner produces ordered ranges. Keep their matching state independent:
394
+ // main's scanner closes by label and width; the newer scanner also tracks style.
395
+ function* markerMaskRanges(input,markers,legacy) {
396
+ const lines=[],opens=new Map();
397
+ let lineStart=0,lineEnd=input.indexOf('\n');
398
+ const lineAt=position=>{
399
+ while(lineEnd>=0&&lineEnd<position) {lineStart=lineEnd+1;lineEnd=input.indexOf('\n',lineStart);}
400
+ return {start:lineStart,end:lineEnd<0?input.length:lineEnd};
401
+ };
402
+ for(const marker of markers) {
403
+ const startLine=lineAt(marker.start),endLine=lineAt(marker.end);
404
+ let bucket=lines.at(-1);
405
+ if(bucket?.start!==startLine.start) {bucket={start:startLine.start,wholeEnd:0,ranges:[]};lines.push(bucket);}
406
+ const matched=legacy?marker.left===marker.right:
407
+ marker.left===marker.right&&marker.style===marker.closeStyle&&/^[-\u2010-\u2015\u2212]+$/u.test(marker.style);
408
+ const key=matched?`${legacy?marker.left:marker.style}:${marker.name}`:null;
409
+ if(marker.kind==='BEGIN') {
410
+ const range={start:marker.start,end:input.length};bucket.ranges.push(range);
411
+ if(key!==null) (opens.get(key)??opens.set(key,[]).get(key)).push(range);
412
+ } else {
413
+ const range=opens.get(key)?.pop();
414
+ if(range) range.end=marker.end;
415
+ else bucket.wholeEnd=Math.max(bucket.wholeEnd,endLine.end);
416
+ }
417
+ }
418
+ for(const bucket of lines) {
419
+ if(bucket.wholeEnd) yield {start:bucket.start,end:bucket.wholeEnd};
420
+ yield* bucket.ranges;
421
+ }
422
+ }
423
+
424
+ // Exposes the exact armor spans for parity checks without parsing masked text.
425
+ export function* armorMaskRanges(value,includeTokens=false) {
426
+ const input=String(value),normalizedRanges=[],normalizedOpens=[];
427
+ for(const marker of normalizedKeyMarkers(input)) {
428
+ if(marker.kind==='OVERFLOW') {yield {start:0,end:input.length};return;}
429
+ if(marker.kind==='BEGIN') {
430
+ const range={start:marker.start,end:input.length,headerEnd:marker.headerEnd??marker.end,style:marker.style};
431
+ normalizedRanges.push(range);normalizedOpens.push(range);
432
+ } else {
433
+ const range=normalizedOpens.at(-1);
434
+ if(range&&range.style!==null&&range.style===marker.style&&marker.start>=range.headerEnd) {normalizedOpens.pop();range.end=marker.end;}
435
+ }
436
+ }
437
+ const streams=[markerMaskRanges(input,armorMarkers(input),false),markerMaskRanges(input,legacyArmorMarkers(input),true),normalizedRanges[Symbol.iterator]()];
438
+ if(includeTokens) streams.push((function*(){for(const match of input.matchAll(new RegExp(tokenContent.source,'gi'))) yield {start:match.index,end:match.index+match[0].length};})(),knownSecretRanges(input)[Symbol.iterator]());
439
+ const heads=streams.map(stream=>stream.next());
440
+ let pending;
441
+ while(true) {
442
+ let first=-1;
443
+ for(let i=0;i<heads.length;i++) if(!heads[i].done&&(first<0||heads[i].value.start<heads[first].value.start)) first=i;
444
+ if(first<0) break;
445
+ const {start,end}=heads[first].value;
446
+ heads[first]=streams[first].next();
447
+ if(end<=start) continue;
448
+ if(pending&&start<=pending.end) pending.end=Math.max(pending.end,end);
449
+ else {if(pending) yield pending;pending={start,end};}
450
+ }
451
+ if(pending) yield pending;
452
+ }
453
+
454
+ export function redactSecrets(value) {
455
+ let redacted=0;
456
+ const input=String(value),chunks=[];let cursor=0;
457
+ const ranges=[...armorMaskRanges(input,true),...pemBodyRanges(input)].sort((a,b)=>a.start-b.start);
458
+ for(const {start,end} of ranges) {
459
+ if(end<=cursor) continue;
460
+ chunks.push(input.slice(cursor,Math.max(cursor,start)),'[redacted secret]'+input.slice(start,end).replace(/[^\n]/g,''));cursor=end;redacted++;
461
+ }
462
+ chunks.push(input.slice(cursor));
463
+ return {text:chunks.join(''),redacted};
464
+ }
465
+
466
+ export function redactOutput(value,depth=0,seen=new WeakSet()) {
467
+ if(typeof value==='string') return maskText(value);
468
+ if(value&&typeof value==='object') {
469
+ if(depth>MAX_DEPTH) return '[depth]';
470
+ if(seen.has(value)) return '[circular]';
471
+ seen.add(value);
472
+ try {return redactContainer(value,depth,seen);} finally {seen.delete(value);}
473
+ }
474
+ return value;
475
+ }
476
+
477
+ function redactContainer(value,depth,seen) {
478
+ if(Array.isArray(value)) {
479
+ const entries=value.map((item,i)=>[i,redactOutput(item,depth+1,seen),false]);
480
+ return splitSiblings(value,entries).map(([,clean])=>clean);
481
+ }
482
+ // Admission refuses a secret held in a property name, so the output pass
483
+ // must not return one either. Masked names stay distinct so no value is lost.
484
+ const names=new Set(),nextSuffix=new Map(),entries=[],raws=[];
485
+ for(const [key,item] of Object.entries(value)) {
486
+ const base=maskText(key);
487
+ let name=base;
488
+ let n=nextSuffix.get(base)??2;
489
+ while(names.has(name)) name=`${base} (${n++})`;
490
+ nextSuffix.set(base,n);
491
+ names.add(name);
492
+ raws.push(item);
493
+ entries.push([name,redactEntry(value,key,item,depth,seen),false]);
494
+ }
495
+ return Object.fromEntries(splitSiblings(raws,entries).map(([name,clean])=>[name,clean]));
496
+ }
497
+
498
+ const MAX_TEXT = 16384;
499
+ // Field names. Exact identifier fields pass; a credential name is an exact key or a delimiter-bounded suffix.
500
+ // No substring rule: `code`, `encode`, `author`, `token_count` and `idempotency_key` are not credential names.
501
+ const correlationFields = new Set(['request_id', 'worker', 'call_id', 'claim_id', 'event_id', 'message_id', 'subscription_id']);
502
+ const safeStructuredFields = new Set(['request_id', 'worker', 'kind', 'count', 'status', 'call_id', 'subject', 'tool', 'at']);
503
+ const nonSecretKeyFields = new Set(['idempotency_key', 'cache_key', 'public_key', 'sort_key', 'dedupe_key', 'group_key', 'request_ids']);
504
+ const credentialKeys = new Set(['auth', 'authorization', 'proxy_authorization', 'cookie', 'cookies', 'set_cookie', 'credential', 'credentials',
505
+ 'password', 'passwd', 'pwd', 'pass', 'passphrase', 'passcode', 'secret', 'token', 'otp', 'jwt', 'bearer', 'session', 'refresh', 'signature',
506
+ 'apikey', 'code_verifier', 'auth_code', 'authorization_code']);
507
+ const credentialSuffix = /(?:^|_)(?:tokens?|secrets?|passwords?|passwd|api_?key|private_?key|access_?key|secret_?key|signing_?key|encryption_?key|credentials?|cookies?)$/;
508
+ const fieldName = key => String(key).replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase().replace(/[-.]/g, '_');
509
+ const isSafeField = key => {
510
+ const name = fieldName(key);
511
+ return correlationFields.has(name) || safeStructuredFields.has(name) || nonSecretKeyFields.has(name);
512
+ };
513
+ // A field name that marks its value as a credential, whatever the value looks like.
514
+ export function isCredentialField(key) {
515
+ const name = fieldName(key);
516
+ return !isSafeField(key) && (credentialKeys.has(name) || credentialSuffix.test(name));
517
+ }
518
+
519
+ // Values that are code or prose about a credential, not a credential: literals, numbers, placeholders, masks.
520
+ const placeholder = /^(?:|true|false|yes|no|on|off|null|undefined|none|nil|-?\d+(?:\.\d+)?|\[redacted.*|\$\{?[\w.]+\}?|\{\{[^{}]*\}\}|%\w|process\.env[\w.]*|<[^<>]*>|\.{3}|…|\*+|x+)$/i;
521
+ // A labelled value in free text needs 3 characters; a header value or a credential-named field is masked whatever its length.
522
+ const realValue = (raw, min = 3) => {
523
+ const value = String(raw).trim().replace(/^(["'])([\s\S]*)\1$/, '$2').replace(/^(?:Bearer|Basic|Token)\s+/i, '').trim();
524
+ return value.length >= min && !placeholder.test(value);
525
+ };
526
+ // A value under a credential-named field is explicit: no prose placeholder exemption applies, so a numeric password or
527
+ // one-time code is masked. Only an empty value or an existing mask passes.
528
+ const explicitValue = raw => { const value = String(raw).trim(); return value.length > 0 && !value.startsWith('[redacted'); };
529
+ const cookieAttributes = /^(?:path|domain|expires|max-age|samesite|secure|httponly|priority|partitioned)$/i;
530
+ const realCookie = raw => {
531
+ const parts = String(raw).trim().replace(/^["']|["']\s*[}\]]*\s*$/g, '').split(';').map(part => part.trim()).filter(Boolean);
532
+ return parts.some((part, i) => {
533
+ const eq = part.indexOf('=');
534
+ if (eq < 0) return i === 0 && realValue(part, 1);
535
+ return !cookieAttributes.test(part.slice(0, eq).trim()) && realValue(part.slice(eq + 1), 1);
536
+ });
537
+ };
538
+
539
+ // Known values: every credential the process holds, with the encoded forms it can appear in (GitHub runner, Buildkite,
540
+ // Jenkins). Raw values need at least 6 characters, derived forms 3; literals such as `true` are never registered.
541
+ const knownSecrets = new Set();
542
+ const registeredValues = new Set();
543
+ let knownPattern = null;
544
+ const base64At = (bytes, offset) => {
545
+ const text = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').replace(/=+$/, '');
546
+ return text.slice(Math.ceil(offset * 8 / 6), Math.floor((offset + bytes.length) * 8 / 6));
547
+ };
548
+ export function registerSecret(value) {
549
+ const raw = String(value ?? '');
550
+ // Explicit registration has no placeholder exemption beyond literals that occur everywhere in text.
551
+ if (raw.trim().length < 6 || /^(?:true|false|null|undefined)$/i.test(raw.trim())) return;
552
+ registeredValues.add(raw);
553
+ const forms = [raw, ...raw.split(/\r?\n/).map(line => line.trim()).filter(line => line.length >= 6)];
554
+ const bytes = Buffer.from(raw);
555
+ const hex = [...bytes].map(byte => byte.toString(16).padStart(2, '0'));
556
+ forms.push(hex.map(h => `%${h}`).join(''), hex.map(h => `%${h.toUpperCase()}`).join(''), encodeURIComponent(raw), JSON.stringify(raw).slice(1, -1), raw.replaceAll("'", `'\\''`), raw.replace(/[^\w@%+=:,./-]/g, '\\$&'));
557
+ for (const offset of [0, 1, 2]) forms.push(base64At(bytes, offset), base64At(bytes, offset).replaceAll('+', '-').replaceAll('/', '_'));
558
+ const before = knownSecrets.size;
559
+ for (const form of forms) if (form.length >= 3) knownSecrets.add(form);
560
+ if (knownSecrets.size === before) return;
561
+ // Longest first, so an encoded form that contains a shorter one is masked whole.
562
+ knownPattern = new RegExp([...knownSecrets].sort((a, b) => b.length - a.length).map(form => form.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g');
563
+ }
564
+ // A worker thread starts with its own module state; pass it these values so it masks and refuses the same secrets.
565
+ export const registeredSecrets = () => [...registeredValues];
566
+ function knownSecretRanges(input) {
567
+ if (!knownPattern) return [];
568
+ return [...input.matchAll(knownPattern)].map(match => ({ start: match.index, end: match.index + match[0].length }));
569
+ }
570
+ // Credential-named environment values are known at load time (Buildkite `*_TOKEN`-style anchored names).
571
+ for (const [name, value] of Object.entries(process.env)) {
572
+ if (/(?:^|_)(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|PRIVATE_KEY|ACCESS_KEY|CLIENT_SECRET)$/i.test(name)) registerSecret(value);
573
+ }
574
+
575
+ // Credential labels and headers in free text, matched by the same anchored field-name rule, plus the Bearer and Basic
576
+ // header shapes (Sentry Relay, GIT_TRACE_REDACT). A placeholder value is left alone.
577
+ const headerText = /((?:^|[^A-Za-z0-9_.-])(?:proxy-authorization|authorization|set-cookie|cookie))(["']?\s*:\s*)([^\r\n]*)/ig;
578
+ const labelText = /(^|[^A-Za-z0-9_.-])([A-Za-z][A-Za-z0-9_.-]*)(["']?\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|<[^<>\n]*>|(?:Bearer|Basic|Token)\s+[^\s,;"'&]+|[^\s,;"'&]+)/g;
579
+ const headerName = /^(?:proxy-authorization|authorization|set-cookie|cookie)$/i;
580
+ const bearerText = /\b(Bearer\s+)(?!\[redacted)([A-Za-z0-9._~+/=-]{16,})/gi;
581
+ const basicText = /\b(Basic\s+)([A-Za-z0-9+/]{8,}={0,2})(?![A-Za-z0-9+/=])/g;
582
+ export function maskCredentialFields(text) {
583
+ return String(text)
584
+ .replace(headerText, (match, key, _separator, value) => {
585
+ const cookie = /cookie$/i.test(key);
586
+ return (cookie ? realCookie(value) : realValue(value, 1)) ? `${key}=[redacted secret]` : match;
587
+ })
588
+ // Header names were judged by the header rule, which reads the whole header value.
589
+ .replace(labelText, (match, prefix, key, _separator, value) => !headerName.test(key) && isCredentialField(key) && realValue(value) ? `${prefix}${key}=[redacted secret]` : match)
590
+ .replace(bearerText, '$1[redacted secret]')
591
+ .replace(basicText, '$1[redacted secret]');
592
+ }
593
+ // Medium-precision hits (labels, headers, Bearer) are masked at every sink; intake only warns about them.
594
+ export function hasCredentialFieldText(text) {
595
+ return maskCredentialFields(text) !== String(text);
596
+ }
597
+ export function hasCredentialHints(value, depth = 0) {
598
+ if (typeof value === 'string') return hasCredentialFieldText(value);
599
+ if (!value || typeof value !== 'object' || depth > MAX_DEPTH) return false;
600
+ return Object.entries(value).some(([key, item]) => (typeof item === 'string' && isCredentialField(key) && explicitValue(item)) || hasCredentialHints(item, depth + 1));
601
+ }
602
+
603
+ // The text core every sink shares: known values, strong formats, then labelled values. JSON text first gets the
604
+ // structural split check, so a credential split across its fields or elements is masked like a structured one.
605
+ const maskCore = text => maskCredentialFields(redactSecrets(text).text);
606
+ export const maskText = text => maskCore(splitSafeJson(text) ?? String(text));
607
+
608
+ // A credential may be split across sibling strings ("Bearer" / value, "password=" / value). If scanning the
609
+ // siblings joined masks more than scanning each alone, none of them can be trusted.
610
+ function splitSiblings(raws, cleaned) {
611
+ const at = raws.flatMap((item, i) => typeof item === 'string' && !cleaned[i][2] ? [i] : []);
612
+ if (at.length < 2) return cleaned;
613
+ const texts = at.map(i => raws[i]);
614
+ const kept = text => text.replaceAll('[redacted secret]', '').length;
615
+ // Join the pieces after each is masked on its own: a secret that is complete in one piece is already a mask and
616
+ // cannot absorb its neighbour, so only a secret that needs two pieces is found.
617
+ const masked = texts.map(maskCore), remasked = masked.map(maskCore);
618
+ if (!['', ' ', '='].some(glue => kept(maskCore(masked.join(glue))) < kept(remasked.join(glue)))) return cleaned;
619
+ for (const i of at) cleaned[i][1] = '[redacted secret]';
620
+ return cleaned;
621
+ }
622
+
623
+ // Known values, armor and PEM bodies (armorMaskRanges), a dashless armor header, and base64 lines that continue a
624
+ // masked block. No long-run, entropy or decode-and-withhold rules: mature redactors document those as the main source
625
+ // of false positives.
626
+ function logTextRanges(text, armor = true) {
627
+ const ranges = armor ? [...armorMaskRanges(text, true), ...pemBodyRanges(text)] : [];
628
+ const dashless = /(?:^|\n)BEGIN[ \t]+PRIVATE[ \t]+KEY[ \t]*\r?\n[A-Za-z0-9+/]{16,}={0,2}/i.exec(text);
629
+ if (dashless) ranges.push({ start: dashless.index, end: text.length });
630
+ if (armor) {
631
+ const lines = [...text.matchAll(/[^\r\n\u2028\u2029]+/g)];
632
+ const masked = lines.map(line => ranges.some(range => range.start < line.index + line[0].length && range.end > line.index));
633
+ const footer = line => /END[^\r\n]*KEY/i.test(line?.[0] ?? '');
634
+ for (let i = 0; i < lines.length; i++) {
635
+ const line = lines[i];
636
+ if (/^[ \t]*[A-Za-z0-9+/]{4,}={0,2}[ \t]*$/.test(line[0]) &&
637
+ (masked[i - 1] || masked[i + 1] || footer(lines[i + 1]))) {
638
+ ranges.push({ start: line.index, end: line.index + line[0].length });
639
+ }
640
+ }
641
+ }
642
+ return ranges;
643
+ }
644
+
645
+ function redactLogText(value, keywords = true, armor = true) {
646
+ // Mask the whole input, then clip: a token or quoted value crossing the cutoff cannot leak a prefix.
647
+ const ranges = logTextRanges(value, armor).sort((a, b) => a.start - b.start);
648
+ const chunks = [];
649
+ let cursor = 0;
650
+ for (const { start, end } of ranges) {
651
+ if (end <= cursor) continue;
652
+ chunks.push(value.slice(cursor, Math.max(cursor, start)), '[redacted secret]');
653
+ cursor = end;
654
+ }
655
+ chunks.push(value.slice(cursor));
656
+ const text = keywords ? maskCredentialFields(chunks.join('')) : chunks.join('');
657
+ return text.length > MAX_TEXT ? text.slice(0, MAX_TEXT) + '…[truncated]' : text;
658
+ }
659
+
660
+ // Redact credential-bearing field values even when their contents are opaque.
661
+ export function redactLogEntry(value, seen = new WeakSet(), depth = 0, idValue = false) {
662
+ if (depth > 100) return '[depth]';
663
+ if (typeof value === 'string') return redactLogText(splitSafeJson(value) ?? value);
664
+ if (typeof value === 'function') return undefined;
665
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return `[binary ${value.byteLength} bytes]`;
666
+ if (value && typeof value === 'object') {
667
+ if (seen.has(value)) return '[circular]';
668
+ seen.add(value);
669
+ }
670
+ if (Array.isArray(value)) {
671
+ const output = Array.from(value, item => redactLogEntry(item, seen, depth + 1, idValue));
672
+ if (Array.from(value).every(item => typeof item === 'string')) {
673
+ // Empty joins catch material or markers split in the middle of a word;
674
+ // newline joins preserve the shape of arrays containing separate lines.
675
+ for (const separator of ['', '\n']) {
676
+ if (value.reduce((total, item) => total + item.length + separator.length, 0) > MAX_TEXT) {
677
+ seen.delete(value);
678
+ return value.map(() => '[redacted secret]');
679
+ }
680
+ const joined = value.join(separator);
681
+ const ranges = logTextRanges(joined);
682
+ let start = 0;
683
+ for (let i = 0; i < value.length; i++) {
684
+ const end = start + value[i].length;
685
+ if (ranges.some(range => range.start < end && range.end > start)) output[i] = '[redacted secret]';
686
+ start = end + separator.length;
687
+ }
688
+ }
689
+ }
690
+ seen.delete(value);
691
+ // A credential split across elements (['Bearer', value], ['password=', value]). Elements the join pass already
692
+ // masked take no further part, so unrelated neighbours stay readable.
693
+ if (idValue) return output;
694
+ return splitSiblings(Array.from(value), output.map((clean, i) => [i, clean, clean === '[redacted secret]'])).map(([, clean]) => clean);
695
+ }
696
+ if (value && typeof value === 'object') {
697
+ const raws = [], entries = [], names = new Set(), nextSuffix = new Map();
698
+ for (const [key, item] of Object.entries(value)) {
699
+ if (typeof item === 'function') continue;
700
+ const base = redactLogText(key);
701
+ let name = base, suffix = nextSuffix.get(base) ?? 2;
702
+ while (names.has(name)) name = `${base} (${suffix++})`;
703
+ nextSuffix.set(base, suffix);
704
+ names.add(name);
705
+ const normalized = key.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
706
+ let clean;
707
+ if (correlationFields.has(normalized) || normalized === 'request_ids') clean = redactLogEntry(item, seen, depth + 1, true);
708
+ else if (normalized === 'code') clean = typeof item === 'number' || (typeof item === 'string' && /^[A-Z0-9_]{1,40}$/.test(item)) ? (typeof item === 'string' ? redactLogText(item, false) : item) : '[redacted secret]';
709
+ else if (safeStructuredFields.has(normalized)) clean = redactLogEntry(item, seen, depth + 1);
710
+ else if (isCredentialField(key)) clean = '[redacted secret]';
711
+ else clean = redactLogEntry(item, seen, depth + 1);
712
+ raws.push(item);
713
+ // Safe names skip only the name rule: their values still take part in the split check.
714
+ entries.push([name, clean, clean === '[redacted secret]']);
715
+ }
716
+ seen.delete(value);
717
+ return Object.fromEntries(splitSiblings(raws, entries).map(([name, clean]) => [name, clean]));
718
+ }
719
+ return value;
720
+ }
721
+
722
+ // JSON text bound for a sink: only the structural split check runs here, so ordinary JSON values (identifier keys,
723
+ // long base64 fields) pass unchanged; the text core then masks the serialized text.
724
+ function splitJson(value, depth = 0) {
725
+ if (!value || typeof value !== 'object' || depth > MAX_DEPTH) return value;
726
+ const keys = Object.keys(value), raws = keys.map(key => value[key]);
727
+ const entries = keys.map((key, i) => [key, splitJson(raws[i], depth + 1), false]);
728
+ const out = Array.isArray(value) ? [] : {};
729
+ for (const [key, clean] of splitSiblings(raws, entries)) out[key] = clean;
730
+ return out;
731
+ }
732
+ // Strings that belong to one record: any that combine into a secret are masked; the others are returned unchanged.
733
+ export const splitFields = texts => splitSiblings(texts, texts.map((text, i) => [i, text, false])).map(([, clean]) => clean);
734
+ function splitSafeJson(value) {
735
+ const text = String(value);
736
+ if (!/^\s*[[{"]/.test(text)) return undefined;
737
+ let parsed;
738
+ try { parsed = JSON.parse(text); } catch { return undefined; }
739
+ if (!parsed || (typeof parsed !== 'object' && typeof parsed !== 'string')) return undefined;
740
+ const cleaned = JSON.stringify(splitJson(parsed));
741
+ // The text scans below read escape sequences literally. Serialized again, the parsed value spells every key and
742
+ // string in its decoded form, so a secret written with a \u escape is found. Clean JSON keeps its own formatting.
743
+ return cleaned === JSON.stringify(parsed) && maskCore(cleaned) === cleaned ? undefined : cleaned;
744
+ }
745
+
746
+ // Free text bound for an outside sink (alerts, owner reports, MCP error text).
747
+ export function redactSinkText(value) {
748
+ const json = splitSafeJson(value);
749
+ if (json !== undefined) value = json;
750
+ // The armor scanner runs once, first, over the whole input, so its exact spans survive and nothing is clipped before
751
+ // it is masked. The log pass then adds the encoding and label checks and clips.
752
+ return redactLogText(redactSecrets(String(value)).text, true, false);
753
+ }
754
+
755
+ function redactEntry(value,key,item,depth,seen) {
756
+ // A number under a credential name is masked like a string; plural `tokens` is a usage counter, not a credential.
757
+ if((typeof item==='string'||(typeof item==='number'&&!/(?:^|_)tokens$/.test(fieldName(key))))&&isCredentialField(key)&&explicitValue(item)) return '[redacted secret]';
758
+ // Old previews can start inside a PEM body and have no recognizable markers.
759
+ // Only bridge-generated, versioned evidence can attest a complete scan.
760
+ if(key==='diff_preview'&&typeof item==='string'&&value.output_redaction_version!==1) return '[legacy diff preview withheld; owner patch required]';
761
+ if(key==='output_preview'&&typeof item==='string'&&value.output_redaction_version!==1&&value.evidence?.output_redaction_version!==1) return '[legacy check output withheld; owner artifact required]';
762
+ return redactOutput(item,depth+1,seen);
763
+ }