@smthrs/journal 0.0.0-stage → 1.0.0-rc.13

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 (257) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/LICENSE +21 -0
  3. package/README.md +208 -2
  4. package/dist/cjs/CallFact.d.ts +129 -0
  5. package/dist/cjs/CallFact.d.ts.map +1 -0
  6. package/dist/cjs/CallFact.js +106 -0
  7. package/dist/cjs/CallFact.js.map +7 -0
  8. package/dist/cjs/Consensus.d.ts +492 -0
  9. package/dist/cjs/Consensus.d.ts.map +1 -0
  10. package/dist/cjs/Consensus.js +314 -0
  11. package/dist/cjs/Consensus.js.map +7 -0
  12. package/dist/cjs/EngineEvent.d.ts +890 -0
  13. package/dist/cjs/EngineEvent.d.ts.map +1 -0
  14. package/dist/cjs/EngineEvent.js +383 -0
  15. package/dist/cjs/EngineEvent.js.map +7 -0
  16. package/dist/cjs/ExecutionFact.d.ts +216 -0
  17. package/dist/cjs/ExecutionFact.d.ts.map +1 -0
  18. package/dist/cjs/ExecutionFact.js +303 -0
  19. package/dist/cjs/ExecutionFact.js.map +7 -0
  20. package/dist/cjs/Journal.d.ts +617 -0
  21. package/dist/cjs/Journal.d.ts.map +1 -0
  22. package/dist/cjs/Journal.js +190 -0
  23. package/dist/cjs/Journal.js.map +7 -0
  24. package/dist/cjs/JournalEvent.d.ts +421 -0
  25. package/dist/cjs/JournalEvent.d.ts.map +1 -0
  26. package/dist/cjs/JournalEvent.js +281 -0
  27. package/dist/cjs/JournalEvent.js.map +7 -0
  28. package/dist/cjs/JournalGeneration.d.ts +34 -0
  29. package/dist/cjs/JournalGeneration.d.ts.map +1 -0
  30. package/dist/cjs/JournalGeneration.js +73 -0
  31. package/dist/cjs/JournalGeneration.js.map +7 -0
  32. package/dist/cjs/JournalMetrics.d.ts +72 -0
  33. package/dist/cjs/JournalMetrics.d.ts.map +1 -0
  34. package/dist/cjs/JournalMetrics.js +55 -0
  35. package/dist/cjs/JournalMetrics.js.map +7 -0
  36. package/dist/cjs/Migrations.d.ts +42 -0
  37. package/dist/cjs/Migrations.d.ts.map +1 -0
  38. package/dist/cjs/Migrations.js +58 -0
  39. package/dist/cjs/Migrations.js.map +7 -0
  40. package/dist/cjs/OwnerId.d.ts +40 -0
  41. package/dist/cjs/OwnerId.d.ts.map +1 -0
  42. package/dist/cjs/OwnerId.js +40 -0
  43. package/dist/cjs/OwnerId.js.map +7 -0
  44. package/dist/cjs/Projection.d.ts +29 -0
  45. package/dist/cjs/Projection.d.ts.map +1 -0
  46. package/dist/cjs/Projection.js +25 -0
  47. package/dist/cjs/Projection.js.map +7 -0
  48. package/dist/cjs/RedactedLogger.d.ts +121 -0
  49. package/dist/cjs/RedactedLogger.d.ts.map +1 -0
  50. package/dist/cjs/RedactedLogger.js +235 -0
  51. package/dist/cjs/RedactedLogger.js.map +7 -0
  52. package/dist/cjs/Redaction.d.ts +350 -0
  53. package/dist/cjs/Redaction.d.ts.map +1 -0
  54. package/dist/cjs/Redaction.js +962 -0
  55. package/dist/cjs/Redaction.js.map +7 -0
  56. package/dist/cjs/SqlConsensus.d.ts +44 -0
  57. package/dist/cjs/SqlConsensus.d.ts.map +1 -0
  58. package/dist/cjs/SqlConsensus.js +273 -0
  59. package/dist/cjs/SqlConsensus.js.map +7 -0
  60. package/dist/cjs/SqlJournal.d.ts +173 -0
  61. package/dist/cjs/SqlJournal.d.ts.map +1 -0
  62. package/dist/cjs/SqlJournal.js +1568 -0
  63. package/dist/cjs/SqlJournal.js.map +7 -0
  64. package/dist/cjs/StepFact.d.ts +66 -0
  65. package/dist/cjs/StepFact.d.ts.map +1 -0
  66. package/dist/cjs/StepFact.js +68 -0
  67. package/dist/cjs/StepFact.js.map +7 -0
  68. package/dist/cjs/index.d.ts +95 -0
  69. package/dist/cjs/index.d.ts.map +1 -0
  70. package/dist/cjs/index.js +63 -0
  71. package/dist/cjs/index.js.map +7 -0
  72. package/dist/cjs/internal/JournalInternalFault.d.ts +37 -0
  73. package/dist/cjs/internal/JournalInternalFault.d.ts.map +1 -0
  74. package/dist/cjs/internal/JournalInternalFault.js +43 -0
  75. package/dist/cjs/internal/JournalInternalFault.js.map +7 -0
  76. package/dist/cjs/migrations/0001_initial.d.ts +15 -0
  77. package/dist/cjs/migrations/0001_initial.d.ts.map +1 -0
  78. package/dist/cjs/migrations/0001_initial.js +54 -0
  79. package/dist/cjs/migrations/0001_initial.js.map +7 -0
  80. package/dist/cjs/migrations/0002_checkpoints.d.ts +27 -0
  81. package/dist/cjs/migrations/0002_checkpoints.d.ts.map +1 -0
  82. package/dist/cjs/migrations/0002_checkpoints.js +48 -0
  83. package/dist/cjs/migrations/0002_checkpoints.js.map +7 -0
  84. package/dist/cjs/migrations/0003_startup_index.d.ts +15 -0
  85. package/dist/cjs/migrations/0003_startup_index.d.ts.map +1 -0
  86. package/dist/cjs/migrations/0003_startup_index.js +40 -0
  87. package/dist/cjs/migrations/0003_startup_index.js.map +7 -0
  88. package/dist/cjs/migrations/0004_dedup.d.ts +15 -0
  89. package/dist/cjs/migrations/0004_dedup.d.ts.map +1 -0
  90. package/dist/cjs/migrations/0004_dedup.js +57 -0
  91. package/dist/cjs/migrations/0004_dedup.js.map +7 -0
  92. package/dist/cjs/migrations/0005_run_event_type.d.ts +15 -0
  93. package/dist/cjs/migrations/0005_run_event_type.d.ts.map +1 -0
  94. package/dist/cjs/migrations/0005_run_event_type.js +40 -0
  95. package/dist/cjs/migrations/0005_run_event_type.js.map +7 -0
  96. package/dist/cjs/migrations/0006_consensus.d.ts +22 -0
  97. package/dist/cjs/migrations/0006_consensus.d.ts.map +1 -0
  98. package/dist/cjs/migrations/0006_consensus.js +84 -0
  99. package/dist/cjs/migrations/0006_consensus.js.map +7 -0
  100. package/dist/cjs/package.json +1 -0
  101. package/dist/cjs/test/Notifying.d.ts +65 -0
  102. package/dist/cjs/test/Notifying.d.ts.map +1 -0
  103. package/dist/cjs/test/Notifying.js +62 -0
  104. package/dist/cjs/test/Notifying.js.map +7 -0
  105. package/dist/cjs/test/TestJournal.d.ts +43 -0
  106. package/dist/cjs/test/TestJournal.d.ts.map +1 -0
  107. package/dist/cjs/test/TestJournal.js +43 -0
  108. package/dist/cjs/test/TestJournal.js.map +7 -0
  109. package/dist/esm/CallFact.d.ts +129 -0
  110. package/dist/esm/CallFact.d.ts.map +1 -0
  111. package/dist/esm/CallFact.js +96 -0
  112. package/dist/esm/CallFact.js.map +1 -0
  113. package/dist/esm/Consensus.d.ts +492 -0
  114. package/dist/esm/Consensus.d.ts.map +1 -0
  115. package/dist/esm/Consensus.js +548 -0
  116. package/dist/esm/Consensus.js.map +1 -0
  117. package/dist/esm/EngineEvent.d.ts +890 -0
  118. package/dist/esm/EngineEvent.d.ts.map +1 -0
  119. package/dist/esm/EngineEvent.js +614 -0
  120. package/dist/esm/EngineEvent.js.map +1 -0
  121. package/dist/esm/ExecutionFact.d.ts +216 -0
  122. package/dist/esm/ExecutionFact.d.ts.map +1 -0
  123. package/dist/esm/ExecutionFact.js +374 -0
  124. package/dist/esm/ExecutionFact.js.map +1 -0
  125. package/dist/esm/Journal.d.ts +617 -0
  126. package/dist/esm/Journal.d.ts.map +1 -0
  127. package/dist/esm/Journal.js +323 -0
  128. package/dist/esm/Journal.js.map +1 -0
  129. package/dist/esm/JournalEvent.d.ts +421 -0
  130. package/dist/esm/JournalEvent.d.ts.map +1 -0
  131. package/dist/esm/JournalEvent.js +517 -0
  132. package/dist/esm/JournalEvent.js.map +1 -0
  133. package/dist/esm/JournalGeneration.d.ts +34 -0
  134. package/dist/esm/JournalGeneration.d.ts.map +1 -0
  135. package/dist/esm/JournalGeneration.js +71 -0
  136. package/dist/esm/JournalGeneration.js.map +1 -0
  137. package/dist/esm/JournalMetrics.d.ts +72 -0
  138. package/dist/esm/JournalMetrics.d.ts.map +1 -0
  139. package/dist/esm/JournalMetrics.js +79 -0
  140. package/dist/esm/JournalMetrics.js.map +1 -0
  141. package/dist/esm/Migrations.d.ts +42 -0
  142. package/dist/esm/Migrations.d.ts.map +1 -0
  143. package/dist/esm/Migrations.js +59 -0
  144. package/dist/esm/Migrations.js.map +1 -0
  145. package/dist/esm/OwnerId.d.ts +40 -0
  146. package/dist/esm/OwnerId.d.ts.map +1 -0
  147. package/dist/esm/OwnerId.js +33 -0
  148. package/dist/esm/OwnerId.js.map +1 -0
  149. package/dist/esm/Projection.d.ts +29 -0
  150. package/dist/esm/Projection.d.ts.map +1 -0
  151. package/dist/esm/Projection.js +13 -0
  152. package/dist/esm/Projection.js.map +1 -0
  153. package/dist/esm/RedactedLogger.d.ts +121 -0
  154. package/dist/esm/RedactedLogger.d.ts.map +1 -0
  155. package/dist/esm/RedactedLogger.js +445 -0
  156. package/dist/esm/RedactedLogger.js.map +1 -0
  157. package/dist/esm/Redaction.d.ts +350 -0
  158. package/dist/esm/Redaction.d.ts.map +1 -0
  159. package/dist/esm/Redaction.js +1628 -0
  160. package/dist/esm/Redaction.js.map +1 -0
  161. package/dist/esm/SqlConsensus.d.ts +44 -0
  162. package/dist/esm/SqlConsensus.d.ts.map +1 -0
  163. package/dist/esm/SqlConsensus.js +273 -0
  164. package/dist/esm/SqlConsensus.js.map +1 -0
  165. package/dist/esm/SqlJournal.d.ts +173 -0
  166. package/dist/esm/SqlJournal.d.ts.map +1 -0
  167. package/dist/esm/SqlJournal.js +1858 -0
  168. package/dist/esm/SqlJournal.js.map +1 -0
  169. package/dist/esm/StepFact.d.ts +66 -0
  170. package/dist/esm/StepFact.d.ts.map +1 -0
  171. package/dist/esm/StepFact.js +50 -0
  172. package/dist/esm/StepFact.js.map +1 -0
  173. package/dist/esm/index.d.ts +95 -0
  174. package/dist/esm/index.d.ts.map +1 -0
  175. package/dist/esm/index.js +95 -0
  176. package/dist/esm/index.js.map +1 -0
  177. package/dist/esm/internal/JournalInternalFault.d.ts +37 -0
  178. package/dist/esm/internal/JournalInternalFault.d.ts.map +1 -0
  179. package/dist/esm/internal/JournalInternalFault.js +28 -0
  180. package/dist/esm/internal/JournalInternalFault.js.map +1 -0
  181. package/dist/esm/migrations/0001_initial.d.ts +15 -0
  182. package/dist/esm/migrations/0001_initial.d.ts.map +1 -0
  183. package/dist/esm/migrations/0001_initial.js +32 -0
  184. package/dist/esm/migrations/0001_initial.js.map +1 -0
  185. package/dist/esm/migrations/0002_checkpoints.d.ts +27 -0
  186. package/dist/esm/migrations/0002_checkpoints.d.ts.map +1 -0
  187. package/dist/esm/migrations/0002_checkpoints.js +38 -0
  188. package/dist/esm/migrations/0002_checkpoints.js.map +1 -0
  189. package/dist/esm/migrations/0003_startup_index.d.ts +15 -0
  190. package/dist/esm/migrations/0003_startup_index.d.ts.map +1 -0
  191. package/dist/esm/migrations/0003_startup_index.js +18 -0
  192. package/dist/esm/migrations/0003_startup_index.js.map +1 -0
  193. package/dist/esm/migrations/0004_dedup.d.ts +15 -0
  194. package/dist/esm/migrations/0004_dedup.d.ts.map +1 -0
  195. package/dist/esm/migrations/0004_dedup.js +38 -0
  196. package/dist/esm/migrations/0004_dedup.js.map +1 -0
  197. package/dist/esm/migrations/0005_run_event_type.d.ts +15 -0
  198. package/dist/esm/migrations/0005_run_event_type.d.ts.map +1 -0
  199. package/dist/esm/migrations/0005_run_event_type.js +18 -0
  200. package/dist/esm/migrations/0005_run_event_type.js.map +1 -0
  201. package/dist/esm/migrations/0006_consensus.d.ts +22 -0
  202. package/dist/esm/migrations/0006_consensus.d.ts.map +1 -0
  203. package/dist/esm/migrations/0006_consensus.js +69 -0
  204. package/dist/esm/migrations/0006_consensus.js.map +1 -0
  205. package/dist/esm/test/Notifying.d.ts +65 -0
  206. package/dist/esm/test/Notifying.d.ts.map +1 -0
  207. package/dist/esm/test/Notifying.js +62 -0
  208. package/dist/esm/test/Notifying.js.map +1 -0
  209. package/dist/esm/test/TestJournal.d.ts +43 -0
  210. package/dist/esm/test/TestJournal.d.ts.map +1 -0
  211. package/dist/esm/test/TestJournal.js +27 -0
  212. package/dist/esm/test/TestJournal.js.map +1 -0
  213. package/docs/README.md +166 -0
  214. package/docs/api.md +650 -0
  215. package/docs/concepts/compaction.md +157 -0
  216. package/docs/concepts/idempotency.md +127 -0
  217. package/docs/concepts/owner-fence.md +128 -0
  218. package/docs/concepts/redaction.md +222 -0
  219. package/docs/concepts/state-event-authority.md +159 -0
  220. package/docs/concepts/two-channels.md +167 -0
  221. package/docs/guides/commit-state-and-entry.md +114 -0
  222. package/docs/guides/compact-a-run.md +134 -0
  223. package/docs/guides/fold-a-projection.md +106 -0
  224. package/docs/guides/read-a-run.md +139 -0
  225. package/docs/guides/redact-log-output.md +94 -0
  226. package/docs/guides/testing.md +124 -0
  227. package/docs/guides/write-lifecycle-events.md +110 -0
  228. package/docs/installation.md +137 -0
  229. package/docs/quickstart.md +146 -0
  230. package/docs/troubleshooting.md +214 -0
  231. package/package.json +263 -3
  232. package/src/CallFact.ts +117 -0
  233. package/src/Consensus.ts +814 -0
  234. package/src/EngineEvent.ts +823 -0
  235. package/src/ExecutionFact.ts +433 -0
  236. package/src/Journal.ts +688 -0
  237. package/src/JournalEvent.ts +654 -0
  238. package/src/JournalGeneration.ts +83 -0
  239. package/src/JournalMetrics.ts +89 -0
  240. package/src/Migrations.ts +62 -0
  241. package/src/OwnerId.ts +42 -0
  242. package/src/Projection.ts +31 -0
  243. package/src/RedactedLogger.ts +483 -0
  244. package/src/Redaction.ts +1828 -0
  245. package/src/SqlConsensus.ts +384 -0
  246. package/src/SqlJournal.ts +2732 -0
  247. package/src/StepFact.ts +69 -0
  248. package/src/index.ts +109 -0
  249. package/src/internal/JournalInternalFault.ts +40 -0
  250. package/src/migrations/0001_initial.ts +41 -0
  251. package/src/migrations/0002_checkpoints.ts +46 -0
  252. package/src/migrations/0003_startup_index.ts +19 -0
  253. package/src/migrations/0004_dedup.ts +43 -0
  254. package/src/migrations/0005_run_event_type.ts +19 -0
  255. package/src/migrations/0006_consensus.ts +83 -0
  256. package/src/test/Notifying.ts +101 -0
  257. package/src/test/TestJournal.ts +52 -0
@@ -0,0 +1,1628 @@
1
+ /**
2
+ * Payload redaction for durable journal writes.
3
+ *
4
+ * The journal is permanent and broadly readable: every entry is replayed to
5
+ * sync subscribers and to time-travel consumers. A secret that reaches
6
+ * `payload_json` is therefore not a transient leak, so redaction happens once,
7
+ * on the journal write path, rather than at each reader.
8
+ *
9
+ * Redaction is an **observability** concern and is confined to journal events
10
+ * and export/display surfaces. It is deliberately not applied to executable
11
+ * state, `flows_runs.state_json`, attempt checkpoints, errors, outcomes, and
12
+ * cache results, because those are decoded and re-entered on resume: a
13
+ * placeholder there resumes the flow with the wrong data, and replacing a
14
+ * non-string value with a placeholder string makes the persisted state fail
15
+ * schema decode outright, leaving the run undrivable (issue #72). A value
16
+ * that must never reach durable executable state is a `Redacted` field in the
17
+ * caller's own schema, not a name-suffix guess made at the storage seam.
18
+ *
19
+ * The rule set is a best-effort textual net over credential shapes seen in
20
+ * real bug reports, plus structural redaction by sensitive field name. It is
21
+ * finite, so a value that must never persist belongs in a `Redacted` field of
22
+ * the caller's own schema. See https://journal.smithers.sh/concepts/redaction/
23
+ * for the rule set and how to replace it.
24
+ *
25
+ * @since 0.1.0
26
+ */
27
+ import * as Result from "effect/Result";
28
+ import * as Schema from "effect/Schema";
29
+ /** JSON text carrying an arbitrary decoded value. */
30
+ const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
31
+ /**
32
+ * The placeholder written in place of a redacted value.
33
+ *
34
+ * @since 0.1.0
35
+ * @category constants
36
+ */
37
+ export const placeholder = "[REDACTED]";
38
+ const isQuote = (char) => char === "\"" || char === "'" || char === "`";
39
+ const closers = { "{": "}", "[": "]", "(": ")" };
40
+ /**
41
+ * Whether the last {@link skipQuoted} or {@link skipContainer} found its
42
+ * closer. Both return the end of the text for a value that never closes, and
43
+ * for one that closes on the text's last character, so the end alone cannot
44
+ * say which.
45
+ */
46
+ let lastClosed = false;
47
+ /**
48
+ * The index just past the quote that closes the string opened at `open`. A
49
+ * quote nested n strings deep sits behind `depth` = 2^n - 1 backslashes, and
50
+ * the quote that closes it has that count modulo 2^(n+1). A string that is
51
+ * never closed, cut by a bound or by its producer, runs to the end of the
52
+ * text. A caller that knows the backslashes were doubled again passes a larger
53
+ * `modulus`.
54
+ */
55
+ const skipQuoted = (text, open, depth, modulus = 2 * (depth + 1), limit = text.length) => {
56
+ let end = open + 1;
57
+ while (end < limit) {
58
+ if (text[end] === text[open]) {
59
+ let slashes = 0;
60
+ for (let i = end - 1; i > open && text[i] === "\\"; i--)
61
+ slashes++;
62
+ if (slashes % modulus === depth) {
63
+ lastClosed = true;
64
+ return end + 1;
65
+ }
66
+ }
67
+ end++;
68
+ }
69
+ lastClosed = false;
70
+ return end;
71
+ };
72
+ /**
73
+ * The index just past the bracket that balances the one at `open`, skipping
74
+ * quoted strings at any escape depth. An unbalanced container runs to the end
75
+ * of the text.
76
+ */
77
+ const skipContainer = (text, open, limit = text.length) => {
78
+ const pending = [];
79
+ let end = open;
80
+ while (end < limit) {
81
+ const char = text[end];
82
+ if (isQuote(char)) {
83
+ let depth = 0;
84
+ while (text[end - 1 - depth] === "\\")
85
+ depth++;
86
+ end = skipQuoted(text, end, depth, 2 * (depth + 1), limit);
87
+ if (!lastClosed)
88
+ return end;
89
+ continue;
90
+ }
91
+ const closer = closers[char];
92
+ if (closer !== undefined)
93
+ pending.push(closer);
94
+ else if (char === pending.at(-1)) {
95
+ pending.pop();
96
+ if (pending.length === 0) {
97
+ lastClosed = true;
98
+ return end + 1;
99
+ }
100
+ }
101
+ end++;
102
+ }
103
+ lastClosed = false;
104
+ return end;
105
+ };
106
+ /**
107
+ * The escape depth of a quote behind `slashes` backslashes: 2^k - 1 for its k
108
+ * trailing escaped levels, so `\\"` (an escaped backslash, then a quote) is
109
+ * depth 0 and `\\\"` is depth 1.
110
+ */
111
+ const escapeDepth = (slashes) => (slashes ^ (slashes + 1)) >> 1;
112
+ const innermostString = (stack) => stack.at(-1)?.string ?? -1;
113
+ /**
114
+ * Updates `stack` with the brackets and strings that `text[from, to)` opens
115
+ * and closes. A quote closes the innermost open string it can close at that
116
+ * string's escape depth, and otherwise opens a string at its own depth. The
117
+ * other quote characters inside a string are content (`"don't"`).
118
+ */
119
+ const track = (stack, text, from, to) => {
120
+ for (let i = from; i < to; i++) {
121
+ const char = text[i];
122
+ if (isQuote(char)) {
123
+ let slashes = 0;
124
+ while (text[i - 1 - slashes] === "\\")
125
+ slashes++;
126
+ const inner = innermostString(stack);
127
+ if (inner === -1) {
128
+ stack.push({ close: char, depth: escapeDepth(slashes), string: stack.length });
129
+ continue;
130
+ }
131
+ if (stack[inner].close !== char)
132
+ continue;
133
+ // Only strings can close, so walk the strings alone, innermost first.
134
+ let closes = inner;
135
+ while (closes !== -1) {
136
+ const depth = stack[closes].depth;
137
+ if (slashes % (2 * (depth + 1)) === depth)
138
+ break;
139
+ closes = closes === 0 ? -1 : stack[closes - 1].string;
140
+ }
141
+ if (closes === -1)
142
+ stack.push({ close: char, depth: escapeDepth(slashes), string: stack.length });
143
+ else
144
+ stack.length = closes;
145
+ continue;
146
+ }
147
+ const closer = closers[char];
148
+ if (closer !== undefined)
149
+ stack.push({ close: closer, string: innermostString(stack) });
150
+ else if (stack.at(-1)?.depth === undefined && char === stack.at(-1)?.close)
151
+ stack.pop();
152
+ }
153
+ };
154
+ /**
155
+ * Whether the closer at `end` closes the bracket open before the name: it and
156
+ * any closers right after it balance the enclosing brackets, and a separator
157
+ * or the end of the text follows (`[{token:abc}]`, not `Tr0ub4dor)]&3`).
158
+ */
159
+ const closesEnclosing = (text, end, stack) => {
160
+ let at = end;
161
+ for (let k = stack.length - 1; k >= 0 && stack[k].depth === undefined && text[at] === stack[k].close; k--)
162
+ at++;
163
+ return at > end && /^(?:[\s,;"'`]|\\+["'`]|$)/.test(text.slice(at, at + 2));
164
+ };
165
+ /** Credential words a name ends in. */
166
+ const credentialWord = "(?:KEY|TOKEN|SECRET|PASSWORD|PASSPHRASE|CREDENTIAL)S?";
167
+ /**
168
+ * A name's separator: `=`, `:` or `=>`, after any quote that closes the name.
169
+ * In a durable row it stays on the name's line; a diagnostic also reads a
170
+ * value on the next line (`password:` then the value), which is how a stream
171
+ * redactor sees it arrive.
172
+ */
173
+ const separator = (space) => String.raw `(?:\\*["'\x60])?${space}(?:=>|[=:])${space}`;
174
+ /**
175
+ * A credential name and its separator. Start once per identifier, including
176
+ * leading underscores, so a name containing many underscores cannot force
177
+ * repeated scans of its suffix. The name may close a quote of its own
178
+ * (`'password':`, `\"token\":`), so a key in a Python repr, an inspected
179
+ * `Map` or escaped JSON meets the rule too.
180
+ */
181
+ const credentialName = String.raw `(?<![A-Za-z0-9_-])([A-Za-z0-9_-]*${credentialWord})`;
182
+ const credentialNames = new RegExp(credentialName + separator("[ \\t]*"), "gi");
183
+ const diagnosticNames = new RegExp(credentialName + separator(String.raw `\s*`), "gi");
184
+ /** Case-insensitive authorization names, without making scheme words prose matches. */
185
+ const authorizationName = "(?:proxy-)?authorization".replace(/[a-z]/g, (char) => `[${char}${char.toUpperCase()}]`);
186
+ /** Complete header names whose whole value is a credential whatever its scheme. */
187
+ const headerWord = String.raw `${authorizationName}|${"(?:set-)?cookies?".replace(/[a-z]/g, (char) => `[${char}${char.toUpperCase()}]`)}`;
188
+ // Apostrophes and backticks open quoted names only outside a header token.
189
+ const headerName = String
190
+ .raw `(?<![A-Za-z0-9!#$%&*+.^_|~-])(?<![A-Za-z0-9!#$%&'*+.^_\x60|~-]['\x60])(${headerWord})`;
191
+ const headerNames = new RegExp(String.raw `((?:proxy-)?authorization|(?:set-)?cookies?)${separator(String.raw `\s*`)}`, "gi");
192
+ /** Whitespace headers require a scheme spelling, so ordinary authorization prose survives. */
193
+ const diagnosticHeaderNames = new RegExp(
194
+ // A trailing token quote requires an opener; double quotes are never token characters.
195
+ `${headerName}(?:` +
196
+ String.raw `(?:(?<=["'\x60](?:${headerWord}))|(?!\\*['\x60]))${separator(String.raw `\s*`)}|` +
197
+ String.raw `(?<=${authorizationName})\s+(?=(?:Token|TOKEN|[Bb]earer|BEARER|Basic|BASIC)[ \t]+\S))`, "g");
198
+ /** Any credential or header name, to stop a bare value before the next pair. */
199
+ const anyName = new RegExp(`${credentialNames.source}|${headerNames.source}`, "gi");
200
+ /** A credential or header name and its separator ending the text before a quote. */
201
+ const nameBefore = new RegExp(`(?:${credentialNames.source}|${headerNames.source})$`, "i");
202
+ /**
203
+ * The index of the next credential or header name at or after `from`; with
204
+ * `quoted`, only a name written right after a quote.
205
+ */
206
+ const nextName = (text, from, quoted) => {
207
+ // No name starts between a search's start and what it found, so a later
208
+ // search from inside that span has the same answer. Values are read left to
209
+ // right, so this keeps every search over one text linear in total.
210
+ const cached = nameSearches[quoted ? 1 : 0];
211
+ if (cached.text === text && from >= cached.from && from <= cached.found)
212
+ return cached.found;
213
+ let found = text.length;
214
+ anyName.lastIndex = from;
215
+ for (let match = anyName.exec(text); match !== null; match = anyName.exec(text)) {
216
+ if (!quoted || isQuote(text[match.index - 1])) {
217
+ found = match.index;
218
+ break;
219
+ }
220
+ }
221
+ nameSearches[quoted ? 1 : 0] = { text, from, found };
222
+ return found;
223
+ };
224
+ /** The last search for any name and for a quoted name. */
225
+ const nameSearches = [{ text: "", from: 0, found: 0 }, { text: "", from: 0, found: 0 }];
226
+ /** The end of the line `index` is on. */
227
+ const lineEnd = (text, index) => {
228
+ // Every index up to a line's end shares that end, so the last answer serves
229
+ // each later value on the same line.
230
+ if (lastLine.text === text && index >= lastLine.from && index <= lastLine.end)
231
+ return lastLine.end;
232
+ newline.lastIndex = index;
233
+ const end = newline.exec(text)?.index ?? text.length;
234
+ lastLine = { text, from: index, end };
235
+ return end;
236
+ };
237
+ const newline = /[\r\n]/g;
238
+ let lastLine = { text: "", from: 0, end: 0 };
239
+ /**
240
+ * Whether the whitespace at `end` continues the one-token value that began at
241
+ * `start`: `util.inspect` separates a constructor or a marker from its
242
+ * contents (`Foo {`, `Map(1) {`, `[Object: null prototype] {`, `<ref *1> {`,
243
+ * `new Password(`).
244
+ */
245
+ const continuesAcrossSpace = (text, start, end) => {
246
+ const run = text.slice(start, end);
247
+ let next = end;
248
+ while (text[next] === " " || text[next] === "\t")
249
+ next++;
250
+ if (run === "new")
251
+ return next;
252
+ const prefix = /^[\w$.]+$/.test(run) || /[)\]>]$/.test(run);
253
+ return prefix && closers[text[next] ?? ""] !== undefined ? next : undefined;
254
+ };
255
+ /**
256
+ * Whether the `,`, `;` or `&` at `end` separates pairs rather than sitting
257
+ * inside a value (`Zq7;Syn,thetic`, `Tr0ub(4dor)&3`): a space or another name
258
+ * follows it, and for `&`, a query parameter (`&page=2`).
259
+ */
260
+ const separatesPairs = (text, end) => text[end] === "&"
261
+ ? /^&[A-Za-z_][\w.-]*=/.test(text.slice(end, end + 64))
262
+ : /^[,;](?:\s|$|\s*\\*["'`]?[A-Za-z_][\w.-]*\\*["'`]?\s*(?:=>|[=:]))/.test(text.slice(end, end + 64));
263
+ /**
264
+ * How far past its line every durable container may read, whatever the
265
+ * {@link Budget} has left: a pretty-printed credential object of this size
266
+ * is read whole on any row.
267
+ */
268
+ const containerWindow = 4096;
269
+ const containerBudget = 4;
270
+ /**
271
+ * The end of the bare value at `start`, read as a run of tokens: words,
272
+ * balanced containers anywhere in it (`{bcrypt}$2a$...`, `Tr0ub(4dor)&3`,
273
+ * `Some("x")`), inspect markers (`<Buffer 73 65>`, `<ref *1>`), and quoted
274
+ * parts. `stack` is what is open before the name: the value stops at a quote
275
+ * that closes the enclosing string, at a closer that closes the enclosing
276
+ * bracket, and before the next credential name.
277
+ */
278
+ const bareValueEnd = (text, start, scope, stack, budget) => {
279
+ const inner = stack[innermostString(stack)];
280
+ // A durable value never reads an unclosed quote past its line, and one it
281
+ // cannot close stops at its line. A bracket reads past 4 KiB only while
282
+ // the text's scan budget lasts: each unbalanced bracket costs a bounded
283
+ // scan, and all of them together a bounded multiple of the text.
284
+ const bound = scope.diagnostic ? text.length : lineEnd(text, start);
285
+ const window = scope.diagnostic
286
+ ? text.length
287
+ : Math.min(text.length, start + Math.max(containerWindow, budget.remaining));
288
+ // Never before the opener: a closed container may already have carried the
289
+ // value past its first line.
290
+ const unclosed = (open, end) => Math.max(open, Math.min(end, bound));
291
+ // A durable container first reads its own line. A pretty-printer only
292
+ // continues one on the next line after the opener or a member's comma
293
+ // (`apiKey: {`, `credentials: { a: 1,`), so only then does the scan read on
294
+ // through the window.
295
+ const container = (open) => {
296
+ if (scope.diagnostic)
297
+ return skipContainer(text, open, window);
298
+ const end = skipContainer(text, open, bound);
299
+ if (lastClosed || !/[[{(,]\s*$/.test(text.slice(open, bound)))
300
+ return end;
301
+ const past = skipContainer(text, open, window);
302
+ budget.remaining -= past - open;
303
+ return past;
304
+ };
305
+ let end = start;
306
+ // The value's own first token is never the next name: in
307
+ // `api_key=lowercase-secret:end` the value only looks like a `name:` pair.
308
+ let limit = nextName(text, start + 1, scope.header);
309
+ // A header value that is one container ends with it: `"cookie":["sid=a"],`.
310
+ if (scope.header && closers[text[start]] !== undefined) {
311
+ end = container(start);
312
+ if (!/^[^\s,;"'`\\)\]}]/.test(text[end] ?? " "))
313
+ return lastClosed ? end : unclosed(start, end);
314
+ }
315
+ while (end < text.length) {
316
+ if (end >= limit) {
317
+ if (end === limit)
318
+ break;
319
+ limit = nextName(text, end, scope.header);
320
+ continue;
321
+ }
322
+ const char = text[end];
323
+ if (closers[char] !== undefined) {
324
+ const open = end;
325
+ end = container(open);
326
+ // An unbalanced container runs on, spaces included.
327
+ if (!lastClosed)
328
+ return unclosed(open, end);
329
+ continue;
330
+ }
331
+ if (char === "<") {
332
+ angleClose.lastIndex = end;
333
+ const close = angleClose.exec(text)?.index;
334
+ if (close !== undefined && text[close] === ">") {
335
+ end = close + 1;
336
+ continue;
337
+ }
338
+ }
339
+ let depth = 0;
340
+ while (text[end + depth] === "\\")
341
+ depth++;
342
+ const quote = text[end + depth];
343
+ if (isQuote(quote)) {
344
+ // A quote at the enclosing string's depth or shallower closes it,
345
+ // whatever precedes it (`Basic abc=`), unless a credential name and
346
+ // separator precede it (`credential:"`). Inside a bracket, a field's
347
+ // value ends at a quote (`{\"token\":abc\"}`). Any other quote opens a
348
+ // quoted part of the value (`username="admin"`, `it's`).
349
+ const closesString = inner !== undefined && quote === inner.close &&
350
+ depth % (2 * (inner.depth + 1)) <= inner.depth &&
351
+ !nameBefore.test(text.slice(Math.max(start, end - 256), end));
352
+ if (closesString || (!scope.header && inner === undefined && stack.length > 0))
353
+ break;
354
+ // A quote between two word characters is an apostrophe (`it's`).
355
+ if (depth === 0 && /\w/.test(text[end - 1] ?? "") && /\w/.test(text[end + 1] ?? "")) {
356
+ end++;
357
+ continue;
358
+ }
359
+ const open = end;
360
+ end = skipQuoted(text, end + depth, depth, 2 * (depth + 1), bound);
361
+ if (!lastClosed)
362
+ return unclosed(open, end);
363
+ continue;
364
+ }
365
+ if (char === "\r" || char === "\n")
366
+ break;
367
+ // Inside a bracket a `,` or `;` separates members; in raw text it does
368
+ // when a space or another name follows.
369
+ if (!scope.header &&
370
+ ((char === "&" && separatesPairs(text, end)) ||
371
+ ((char === "," || char === ";") && (stack.length > 0 || separatesPairs(text, end)))))
372
+ break;
373
+ if (!scope.header && !scope.diagnostic && (char === " " || char === "\t")) {
374
+ const next = continuesAcrossSpace(text, start, end);
375
+ if (next === undefined)
376
+ break;
377
+ end = next;
378
+ continue;
379
+ }
380
+ if (closesEnclosing(text, end, stack))
381
+ break;
382
+ end++;
383
+ }
384
+ while (end > start && /\s/.test(text[end - 1]))
385
+ end--;
386
+ return end;
387
+ };
388
+ /**
389
+ * Whether a name ending in `key` or `keys` is not a credential's: it counts
390
+ * only where {@link isSensitiveKey} agrees, as it does for the same name as an
391
+ * object key (`apiKeys` counts; `keys`, `sortKeys`, `idempotencyKey` and
392
+ * `monkey` do not).
393
+ */
394
+ const plainKeyName = (name) => /keys?$/i.test(name) && !isSensitiveKey(name);
395
+ /**
396
+ * The end of a credential that is a URL's password (`//x-access-token:secret@`):
397
+ * the `@` that closes the userinfo, so the host and path stay readable. Any
398
+ * other bare value keeps its end.
399
+ */
400
+ const userinfoEnd = (text, start, end) => {
401
+ if (!/\/\/[^\s/@?#]*[:=]$/.test(text.slice(Math.max(0, start - 128), start)))
402
+ return end;
403
+ const value = text.slice(start, end);
404
+ const authority = value.search(/[/?#]/);
405
+ const at = value.lastIndexOf("@", authority < 0 ? value.length : authority);
406
+ return at > 0 ? start + at : end;
407
+ };
408
+ /**
409
+ * Whether a name that matched a credential word names a credential: not a
410
+ * {@link plainKeyName}, and not a count under a plural `tokens` name
411
+ * (`max_tokens: 4096`), which is accounting.
412
+ */
413
+ const namesCredential = (name, value) => !plainKeyName(name) &&
414
+ !(/tokens$/i.test(name) && /^["'`]?\d+(?![\w.])/.test(value));
415
+ /** The `>` that closes an inspect marker, or the line end that means there is none. */
416
+ const angleClose = /[>\r\n]/g;
417
+ /**
418
+ * The `+` with which `util.inspect` continues a long string on the next line,
419
+ * its newline raw or escaped (`\\n`) when the inspected text was itself
420
+ * written into a string.
421
+ */
422
+ const continuation = /(?:\s|\\+[nrt])*\+(?:\s|\\+[nrt])*/y;
423
+ /** A value an earlier pass already replaced. */
424
+ const alreadyRedacted = /^\[REDACTED\]$/;
425
+ /**
426
+ * Redacts the value after each name `names` matches. A quoted value is
427
+ * consumed whole at any string-escape depth, with the pieces `util.inspect`
428
+ * joins with `+` across lines, and its quotes are kept around the
429
+ * placeholder; a bare value is consumed as a run of tokens. A name that ends
430
+ * in `key` counts only where {@link isSensitiveKey} agrees, so `sortKey` and
431
+ * `idempotencyKey` keep their values, and a count under a plural `tokens`
432
+ * name, `max_tokens: 4096`, is accounting and is kept too.
433
+ */
434
+ const redactValues = (text, names, scope) => {
435
+ const keys = new RegExp(names.source, names.flags);
436
+ let output = "";
437
+ let position = 0;
438
+ // What is open before the current value. Values are skipped, so a bracket
439
+ // or quote inside a credential never counts.
440
+ const stack = [];
441
+ const budget = { remaining: containerBudget * text.length };
442
+ let scanned = 0;
443
+ for (let match = keys.exec(text); match !== null; match = keys.exec(text)) {
444
+ const name = match[1];
445
+ if (!scope.header && plainKeyName(name))
446
+ continue;
447
+ track(stack, text, scanned, keys.lastIndex);
448
+ scanned = keys.lastIndex;
449
+ // A call's `key=` naming a function (`sorted(xs, key=lambda m: m[0])`)
450
+ // is code: a literal credential there would be quoted.
451
+ if (!scope.diagnostic && name === "key" && text[keys.lastIndex - 1] === "=" &&
452
+ stack.at(-1)?.close === ")" && stack.at(-1)?.depth === undefined &&
453
+ /^[A-Za-z_][\w.]*(?=[\s(),])/.test(text.slice(keys.lastIndex, keys.lastIndex + 256)))
454
+ continue;
455
+ let start = keys.lastIndex;
456
+ let depth = 0;
457
+ while (text[start + depth] === "\\")
458
+ depth++;
459
+ const opener = text[start + depth];
460
+ const quote = isQuote(opener) ? opener : undefined;
461
+ let end;
462
+ if (quote !== undefined) {
463
+ start += depth;
464
+ const inner = stack[innermostString(stack)];
465
+ if (inner !== undefined) {
466
+ // Inside a string written with another quote character, every
467
+ // backslash is doubled again: `inspect` renders `"a\"b"` as
468
+ // `'"a\\"b"'`.
469
+ end = skipQuoted(text, start, depth, (inner.close === quote ? 1 : 2 * (inner.depth + 1)) * 2 * (depth + 1));
470
+ }
471
+ else {
472
+ // No enclosing string is visible: raw text, or a string `track` cannot
473
+ // see. Close no earlier than a doubled string would, but never past the
474
+ // next credential name: at the undoubled close when only separators
475
+ // precede that name (`"abc\\", password=`), else at the name.
476
+ const undoubled = skipQuoted(text, start, depth);
477
+ end = skipQuoted(text, start, depth, Math.max(4, 2 * (depth + 1)));
478
+ const next = nextName(text, undoubled, false);
479
+ if (next < end)
480
+ end = /^[\s,;&]*$/.test(text.slice(undoubled, next)) ? undoubled : next;
481
+ }
482
+ const closed = end - start > 1 && text[end - 1] === quote;
483
+ if (!closed && !scope.diagnostic)
484
+ end = Math.min(end, lineEnd(text, start));
485
+ // `util.inspect` continues a long string on the next line with `+`.
486
+ if (depth === 0) {
487
+ for (continuation.lastIndex = end; continuation.test(text); continuation.lastIndex = end) {
488
+ const piece = continuation.lastIndex;
489
+ if (!isQuote(text[piece]))
490
+ break;
491
+ end = skipQuoted(text, piece, 0);
492
+ }
493
+ }
494
+ if (alreadyRedacted.test(text.slice(start + 1, end - (text[end - 1] === quote ? 1 + depth : 0))))
495
+ continue;
496
+ }
497
+ else {
498
+ end = bareValueEnd(text, start, scope, stack, budget);
499
+ end = userinfoEnd(text, start, end);
500
+ // In a journal row a placeholder then a space is a value an earlier pass
501
+ // already bounded: what follows it is the next part of the line,
502
+ // `{"statusCode":401}`. A diagnostic value runs over several words, so
503
+ // there the words after a placeholder are still the value.
504
+ const bounded = !scope.diagnostic && text.startsWith(placeholder, start) &&
505
+ /\s/.test(text[start + placeholder.length] ?? "");
506
+ const kept = end === start || bounded || alreadyRedacted.test(text.slice(start, end)) ||
507
+ (/tokens$/i.test(name) && /^\d+(?![\w.])/.test(text.slice(start, end))) ||
508
+ // A Bearer or Basic value the default rules already replaced keeps its scheme.
509
+ (scope.header && /^(?:bearer|basic)\s+\[REDACTED/i.test(text.slice(start, start + 24)));
510
+ if (kept)
511
+ continue;
512
+ }
513
+ const escape = quote === undefined ? "" : "\\".repeat(depth);
514
+ const closed = quote !== undefined && end - start > 1 && text[end - 1] === quote;
515
+ output += text.slice(position, keys.lastIndex) + escape + (quote ?? "") + placeholder +
516
+ (closed ? escape + quote : "");
517
+ position = end;
518
+ scanned = end;
519
+ keys.lastIndex = end;
520
+ }
521
+ return output + text.slice(position);
522
+ };
523
+ /**
524
+ * What separates a flag from its value: whitespace on a command line, or
525
+ * `", "` between two elements of a JSON or inspected array.
526
+ */
527
+ const argumentSeparator = String.raw `(?:\s+|["'\x60]\s*,\s*["'\x60])`;
528
+ /** A credential flag and the separator before its value. */
529
+ const credentialFlag = new RegExp(String.raw `(?<![A-Za-z0-9_-])(--?[A-Za-z0-9_-]*${credentialWord})${argumentSeparator}`, "gi");
530
+ /** `-p` and the separator before its value, unless the value is a path or a long option. */
531
+ const shortPasswordFlag = new RegExp(String.raw `(?<![^\s"'\x60,[(])-p${argumentSeparator}(?!(?:\.{0,2}|~)\/|--)`, "g");
532
+ /**
533
+ * A flag that always takes a password, and the separator before it: `plink
534
+ * -pw`, openssl's `-pass`, `-passin` and `-passout` (`pass:secret`), `-passwd`.
535
+ */
536
+ const passwordFlag = new RegExp(String.raw `(?<![^\s"'\x60,[(])-p(?:w|ass(?:in|out|wd)?)${argumentSeparator}`, "g");
537
+ /** `-p` with a value attached, unless the word is a known single-dash option. */
538
+ const attachedPasswordFlag = new RegExp(String
539
+ .raw `(?<![^\s"'\x60,[(])-p(?!(?:rint\w*|rune|erm|ath|threads?|edantic[\w-]*|ipe|ie|g|retty|lain|rogress|rofile|arents|reserve|ass(?:in|out|wd)?|w)(?![^\s"'\x60,\]]))(?=[^\s,\]])`, "g");
540
+ /** `-u` or `--user` and the separator before its value, or `-u` with its value attached (`-uadmin:pw`). */
541
+ const userFlag = new RegExp(String.raw `(?<![^\s"'\x60,[(])(?:(?:-u|--user)(?:=|${argumentSeparator})|-u(?=[^\s=-]))`, "g");
542
+ /**
543
+ * A flag that takes a password only under one command, and the separator
544
+ * before its value: `zip -P` (a port to `ssh` and `mysql`) and `redis-cli -a`
545
+ * or `--pass`. The command is looked for at most 256 characters back on the
546
+ * same command line.
547
+ */
548
+ const commandPasswordFlag = new RegExp(String
549
+ .raw `\b(?:(?:(?:un)?zip|zipcloak)\b[^\r\n|;&]{0,256}?[\s"'\x60,[(]-P|redis-cli\b[^\r\n|;&]{0,256}?[\s"'\x60,[(](?:-a|--pass))${argumentSeparator}`, "g");
550
+ /**
551
+ * An HTTP header written as a name and value pair of an array
552
+ * (`[['Authorization', 'Token x']]`), the shape `Headers` entries and many
553
+ * clients log, up to the quote that opens the value.
554
+ */
555
+ const headerPair = /(?<![A-Za-z0-9_-])(?:(?:proxy-)?authorization|(?:set-)?cookies?)\\*["'`]\s*,\s*(?=\\*["'`])/gi;
556
+ /** Redacts the quoted value of each {@link headerPair}, keeping its quotes. */
557
+ const redactHeaderPairs = (text) => {
558
+ const pattern = new RegExp(headerPair.source, headerPair.flags);
559
+ let output = "";
560
+ let position = 0;
561
+ for (let match = pattern.exec(text); match !== null; match = pattern.exec(text)) {
562
+ let depth = 0;
563
+ while (text[pattern.lastIndex + depth] === "\\")
564
+ depth++;
565
+ const open = pattern.lastIndex + depth;
566
+ const end = skipQuoted(text, open, depth);
567
+ const close = lastClosed ? end - 1 - depth : end;
568
+ if (alreadyRedacted.test(text.slice(open + 1, close)))
569
+ continue;
570
+ output += text.slice(position, open + 1) + placeholder;
571
+ position = close;
572
+ pattern.lastIndex = end;
573
+ }
574
+ return output + text.slice(position);
575
+ };
576
+ /** The placeholder alone, bare, quoted or escaped: a second pass leaves it alone. */
577
+ const redactedArgument = /^(?:\\*(["'`]))?\[REDACTED\](?:\\*\1)?$/;
578
+ /**
579
+ * The end of the unquoted argument at `start`. It runs to whitespace or a
580
+ * quote, and on through a quoted part written against it (`abc'def'`, which a
581
+ * shell reads as one argument) when that part closes before any whitespace
582
+ * and holds none of `,:{}[]`. Any other quote ends it: the close of a string
583
+ * the command line sits in (`{"cmd":"mysql -p abc","next":1}`).
584
+ */
585
+ const wordEnd = (text, start) => {
586
+ let end = start;
587
+ while (end < text.length && !/\s/.test(text[end])) {
588
+ const quote = text[end];
589
+ if (!isQuote(quote)) {
590
+ end++;
591
+ continue;
592
+ }
593
+ let close = end + 1;
594
+ while (close < text.length && !/[\s"'`,:{}[\]]/.test(text[close]))
595
+ close++;
596
+ if (close === end + 1 || text[close] !== quote)
597
+ break;
598
+ end = close + 1;
599
+ }
600
+ return end;
601
+ };
602
+ /**
603
+ * Redacts the value after each flag `flags` matches: a quoted value, or one
604
+ * argv word, which ends at whitespace or a quote, so the same rule reads a
605
+ * command line joined by spaces, a JSON array and an inspected array. A comma
606
+ * or a `]` is part of a password on a command line (`-p abc,def`); in an
607
+ * array the element's closing quote ends it first.
608
+ */
609
+ const redactArguments = (text, flags,
610
+ /** Whether this flag and value are a credential at all. */
611
+ accept) => {
612
+ const pattern = new RegExp(flags.source, flags.flags);
613
+ let output = "";
614
+ let position = 0;
615
+ for (let match = pattern.exec(text); match !== null; match = pattern.exec(text)) {
616
+ const start = pattern.lastIndex;
617
+ let depth = 0;
618
+ while (text[start + depth] === "\\")
619
+ depth++;
620
+ let end = start;
621
+ if (isQuote(text[start + depth]))
622
+ end = skipQuoted(text, start + depth, depth);
623
+ else
624
+ end = wordEnd(text, start);
625
+ const value = text.slice(start, end);
626
+ if (end === start || redactedArgument.test(value) || accept?.(match, value) === false)
627
+ continue;
628
+ output += text.slice(position, start) + placeholder;
629
+ position = end;
630
+ pattern.lastIndex = end;
631
+ }
632
+ return output + text.slice(position);
633
+ };
634
+ const durable = { header: false, diagnostic: false };
635
+ /**
636
+ * Best-effort textual rules for credential shapes observed in real reports.
637
+ * Every replacement reaches a fixed point so replaying or exporting an entry
638
+ * cannot mutate it again.
639
+ *
640
+ * @since 0.1.0
641
+ * @category constants
642
+ */
643
+ export const defaultRules = [
644
+ {
645
+ id: "private-key-block",
646
+ // Stop an unterminated block at the next header so repeated headers cannot
647
+ // each rescan the remaining input. A valid PEM body contains no headers.
648
+ // A block with no footer is a key a bound or a producer truncated, and its
649
+ // body is as secret as a whole one's, so it runs to the next header or to
650
+ // the end of the text. It runs first: a block inside URL userinfo, once
651
+ // replaced, is userinfo the URL rule then reads whole, so a second pass
652
+ // finds nothing left to change.
653
+ pattern: /-----BEGIN[^-]*PRIVATE KEY(?: BLOCK)?-----(?:(?!-----BEGIN)[\s\S])*?(?:-----END[^-]*-----|(?=-----BEGIN)|$)/g
654
+ },
655
+ // Git HTTPS OAuth credentials place the secret in the username. Match
656
+ // before password rewriting removes the x-oauth-basic marker.
657
+ {
658
+ id: "git-oauth-userinfo",
659
+ pattern: /(https?:\/\/)[^\s/@:"'\\]+:x-oauth-basic@/gi,
660
+ replace: "$1[REDACTED]@"
661
+ },
662
+ {
663
+ id: "url-credentials",
664
+ // The scheme is bounded rather than open. `-` is not a word character, so
665
+ // `\b[a-z][a-z0-9+.-]*` starts a fresh scan after every hyphen, and on a
666
+ // long run of that shape the rule rescanned the tail from each one: 400 kB
667
+ // of `aaaaaaaa-` cost 11 seconds, on the path every journal write and every
668
+ // log line takes. A scheme longer than 30 characters is not one this net is
669
+ // for, and the cap makes each start position cost a constant.
670
+ //
671
+ // The username may be empty (`redis://:password@host`), and the password
672
+ // runs to the LAST `@` before the authority ends, as a URL parser reads
673
+ // it: RFC 3986 allows `:` in a password and a raw `@` is common in
674
+ // connection strings. Stopping at the first `:` or `@` left the tail of
675
+ // such a password in the row. Quotes and backslashes end the scan so a
676
+ // URL inside JSON text never swallows the next string.
677
+ pattern: /\b([a-z][a-z0-9+.-]{0,30}:\/\/[^\s:@/]*):(?!\[REDACTED\]@)[^\s/?#"'`\\]*@/gi,
678
+ replace: "$1:[REDACTED]@"
679
+ },
680
+ {
681
+ id: "bearer-token",
682
+ pattern: /\bBearer\s+[A-Za-z0-9._~+/-]{4,}=*/gi,
683
+ replace: "Bearer [REDACTED_TOKEN]"
684
+ },
685
+ {
686
+ id: "basic-authorization",
687
+ // HTTP schemes are case-insensitive. For prose spellings, require an
688
+ // encoded user:password pair so `a basic example` and module imports survive.
689
+ pattern: /\bbasic\s+[A-Za-z0-9+/]{4,}={0,2}/gi,
690
+ rewrite: (text) => text.replace(/\b(basic)\s+([A-Za-z0-9+/]{4,}={0,2})/gi, (match, scheme, token) => {
691
+ if (scheme === "Basic" || scheme === "BASIC")
692
+ return "Basic [REDACTED_TOKEN]";
693
+ try {
694
+ return atob(token).includes(":") ? "Basic [REDACTED_TOKEN]" : match;
695
+ }
696
+ catch {
697
+ return match;
698
+ }
699
+ })
700
+ },
701
+ {
702
+ id: "jwt",
703
+ // Check the three segments once per token before looking for a header.
704
+ // Starting at every `-eyJ` would rescan a malformed token's entire tail.
705
+ // Preserve any prefix so a JWT following a hyphen still gets redacted.
706
+ pattern: /(?<![A-Za-z0-9_-])(?=[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-])([A-Za-z0-9_-]*?)\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,
707
+ replace: "$1[REDACTED_TOKEN]"
708
+ },
709
+ {
710
+ id: "api-key",
711
+ // Not `\b`, for the reason the assignment rule below gives: an underscore
712
+ // is a word character, so `\bsk` never fires after `ANTHROPIC_` or after
713
+ // Effect's log-span sanitizer folds `token=` into `token_`. The lookbehind
714
+ // excludes only letters and digits, so a key still reads as a key when an
715
+ // underscore or a hyphen runs into it.
716
+ pattern: /(?<![A-Za-z0-9])(?:sk|pk)[-_][A-Za-z0-9][A-Za-z0-9_-]{7,}/g,
717
+ replace: "[REDACTED_API_KEY]"
718
+ },
719
+ {
720
+ id: "github-token",
721
+ pattern: /\bgh[pousr]_[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
722
+ replace: "[REDACTED]"
723
+ },
724
+ {
725
+ id: "github-fine-grained-token",
726
+ pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}(?![A-Za-z0-9_])/g,
727
+ replace: "[REDACTED]"
728
+ },
729
+ {
730
+ id: "aws-access-key",
731
+ pattern: /\bAKIA[0-9A-Z]{16}\b/g,
732
+ replace: "[REDACTED]"
733
+ },
734
+ {
735
+ id: "slack-token",
736
+ pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}(?![A-Za-z0-9-])/g,
737
+ replace: "[REDACTED]"
738
+ },
739
+ {
740
+ id: "google-api-key",
741
+ pattern: /\bAIza[0-9A-Za-z_-]{35,}(?![0-9A-Za-z_-])/g,
742
+ replace: "[REDACTED]"
743
+ },
744
+ {
745
+ id: "gitlab-token",
746
+ pattern: /\bglpat-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
747
+ replace: "[REDACTED]"
748
+ },
749
+ {
750
+ id: "npm-token",
751
+ pattern: /\bnpm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g,
752
+ replace: "[REDACTED]"
753
+ },
754
+ {
755
+ // The webhook path is the whole credential: anyone holding it can post
756
+ // to the channel. The host stays so a failed delivery is still readable.
757
+ id: "slack-webhook",
758
+ pattern: /(\bhooks\.slack\.com\/services\/)T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,
759
+ replace: "$1[REDACTED]"
760
+ },
761
+ {
762
+ id: "assignment",
763
+ // A credential name, `:`, `=` or `=>`, and its whole value: quoted at any
764
+ // escape depth, a container, or several bare words. See `redactValues`.
765
+ pattern: credentialNames,
766
+ rewrite: (text) => redactValues(text, credentialNames, durable)
767
+ },
768
+ {
769
+ id: "credential-flag",
770
+ // `--password hunter2`, `--api-key "a b"`, or the same pair as two argv
771
+ // elements. `--token=x` is an assignment above; this is the spelling a
772
+ // command line separates with a space. The next word is the value even
773
+ // when it starts with `-`: a credential flag always takes one.
774
+ pattern: credentialFlag,
775
+ rewrite: (text) => redactArguments(text, credentialFlag, (match, value) => namesCredential(match[1].replace(/^-+/, ""), value))
776
+ },
777
+ {
778
+ id: "cookie-session-assignment",
779
+ pattern: /(?<![A-Za-z0-9-])((?:COOKIE|SESSION)S?)(\s*=\s*)(?!\[REDACTED\])("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|(?!["'])[^\s;,]+)/gi,
780
+ replace: "$1$2[REDACTED]"
781
+ }
782
+ ];
783
+ /**
784
+ * The rules for a diagnostic: {@link defaultRules} and the spellings too broad
785
+ * for a durable row.
786
+ *
787
+ * A log line, a stderr message, and an error handed to a remote caller are
788
+ * read once, so a false positive costs a word of context. A journal row is
789
+ * permanent, so the same false positive destroys data. These rules sit on the
790
+ * diagnostic side of that line: an authorization header in any scheme, bare
791
+ * URL userinfo (`https://token@host`), a signed query parameter, and the value
792
+ * of a `-p` flag, which is a password to `mysql` and `sshpass` and a path to
793
+ * `mkdir`. A path, a port and a lowercase word attached to `-p` (`-print`,
794
+ * `-path`) are left alone.
795
+ *
796
+ * @since 1.0.0
797
+ * @category constants
798
+ */
799
+ export const diagnosticRules = [
800
+ ...defaultRules.map((rule) => rule.id === "assignment"
801
+ ? {
802
+ id: "assignment",
803
+ pattern: diagnosticNames,
804
+ rewrite: (text) => redactValues(text, diagnosticNames, { header: false, diagnostic: true })
805
+ }
806
+ : rule),
807
+ {
808
+ id: "authorization-header",
809
+ // The header value is a credential whatever its scheme (`Token`, a cookie
810
+ // list, `Digest` with quoted parameters), so the value runs to the end of
811
+ // its line or the close of the string it was written in.
812
+ // A lookbehind-free superset lets the compiled prefilter skip ordinary prose.
813
+ pattern: /(?:proxy-)?authorization|(?:set-)?cookies?/gi,
814
+ rewrite: (text) => redactValues(text, diagnosticHeaderNames, { header: true, diagnostic: true })
815
+ },
816
+ {
817
+ id: "bearer-or-basic",
818
+ // A token shorter than the default rules' minimum. A lowercase `basic` is
819
+ // prose ("a basic example"), so only the scheme's own spellings count.
820
+ pattern: /(\b(?:[Bb]earer|BEARER|Basic|BASIC)\s+)(?!\[REDACTED)[^\s,;"'\\]+/g,
821
+ replace: "$1[REDACTED]"
822
+ },
823
+ {
824
+ id: "password-flag",
825
+ // The whole next argument, a path or a leading `-` included.
826
+ pattern: passwordFlag,
827
+ rewrite: (text) => redactArguments(text, passwordFlag)
828
+ },
829
+ {
830
+ id: "sshpass-password",
831
+ // `sshpass -p` always takes a value, even one that starts with `--`,
832
+ // which `mysql -p --database x` reads as the next option.
833
+ pattern: /(\bsshpass(?:\s+-[^\sp]\S*){0,8}\s+-p\s+)--(?!\[REDACTED\])[^\s"'`]*/g,
834
+ replace: "$1[REDACTED]"
835
+ },
836
+ {
837
+ id: "user-flag",
838
+ // `curl -u user:pass`, `--user=user:pass`, quoted or not: the whole
839
+ // argument, commas included, when it carries a `:`.
840
+ pattern: userFlag,
841
+ rewrite: (text) => redactArguments(text, userFlag, (_match, value) => value.includes(":"))
842
+ },
843
+ {
844
+ id: "header-pair",
845
+ pattern: headerPair,
846
+ rewrite: redactHeaderPairs
847
+ },
848
+ {
849
+ id: "command-password-flag",
850
+ // The whole next argument, whatever it starts with.
851
+ pattern: commandPasswordFlag,
852
+ rewrite: (text) => redactArguments(text, commandPasswordFlag)
853
+ },
854
+ {
855
+ id: "url-userinfo",
856
+ pattern: /(\/\/)(?!\[REDACTED\]@)(?![^/@\s"'\\]*:\[REDACTED\]@)[^/@\s"'\\]+@/g,
857
+ replace: "$1[REDACTED]@"
858
+ },
859
+ {
860
+ id: "signed-query",
861
+ pattern: /([?&][\w.-]*(?:key|sig|signature|auth|credential)=)(?!\[REDACTED\])[^&#\s"'\\]+/gi,
862
+ replace: "$1[REDACTED]"
863
+ },
864
+ {
865
+ id: "short-password-flag",
866
+ // A path is kept, and so is a flag: `mysql -p --database x` prompts for
867
+ // the password rather than taking one.
868
+ pattern: shortPasswordFlag,
869
+ rewrite: (text) => redactArguments(text, shortPasswordFlag)
870
+ },
871
+ {
872
+ id: "attached-password-flag",
873
+ // `-psecret`. The single-dash words that start with `p` and are not a
874
+ // password, `find -print` and the compilers' `-pthread` among them, are kept.
875
+ pattern: attachedPasswordFlag,
876
+ rewrite: (text) => redactArguments(text, attachedPasswordFlag)
877
+ }
878
+ ];
879
+ /**
880
+ * Redacts one diagnostic value with {@link diagnosticRules}: a log line, a
881
+ * stderr message, an error handed back to a caller.
882
+ *
883
+ * Every diagnostic path shares this one function, and it runs on the value
884
+ * before anything renders or bounds it. Redacting a rendering line by line, or
885
+ * after a bound, is how a secret escaped: `util.inspect` splits a long string
886
+ * over several lines, and a bound cuts a quoted value before its closing
887
+ * quote. A value past {@link maxDepth} is named rather than thrown.
888
+ *
889
+ * @since 1.0.0
890
+ * @category redaction
891
+ */
892
+ export const redactDiagnostic = (value) => redact(value, { rules: diagnosticRules, onTooDeep: "name" });
893
+ /**
894
+ * Credential names this module refuses to persist, matched as suffixes of the
895
+ * separator-free lowercase form of a key.
896
+ *
897
+ * The list is the union of the names `packages/smithers/src/Bug.ts` redacts
898
+ * structurally, because the journal is the PERMANENT side of that pair: a bug
899
+ * report is one upload an operator reviews before it leaves the machine, while
900
+ * `flows_journal_events.payload_json` is replayed verbatim to every sync
901
+ * subscriber and time-travel consumer forever. The journal redacting less than
902
+ * the report inverts the risk, and it did: `credential`, `credentials`, `dsn`,
903
+ * and `connectionString` all round-tripped through a durable row in clear.
904
+ *
905
+ * Two families are spelled out rather than reduced to a shorter word, because
906
+ * these are SUFFIX tests: `connectionString` does not end in `connection`, and
907
+ * `secretKey` does not end in `secret`. A bare `key` suffix is not on the list
908
+ * for the opposite reason: it would redact `monkey` and `turkey`.
909
+ *
910
+ * `signature` stays, and a field it costs is renamed rather than excused. A
911
+ * name test cannot tell a MAC computed with a secret from a digest over public
912
+ * input, and both are called `signature`: `WorkspaceShare` signs its claims
913
+ * with `ShareSigner.signHmac` and that value IS the share's authorization,
914
+ * `GrantStore` carries envelope signatures, and the GitHub, Linear and
915
+ * Telegram webhook readers all verify a header by that name. Against those, a
916
+ * digest whose whole purpose is to be reconciled costs nothing to rename and
917
+ * everything to leave unreadable -- see
918
+ * `AgentEvent.VacuousVerificationObserved.callDigest`, which was `signature`
919
+ * and reached durable rows as the placeholder.
920
+ */
921
+ const sensitiveKeySuffixes = [
922
+ "auth",
923
+ "authorization",
924
+ "cookie",
925
+ "apikey",
926
+ "token",
927
+ "password",
928
+ "passphrase",
929
+ "secret",
930
+ "secretaccesskey",
931
+ "credential",
932
+ "dsn",
933
+ "connection",
934
+ "connectionstring",
935
+ "connectionuri",
936
+ "connectionurl",
937
+ "secretkey",
938
+ "privatekey",
939
+ "sshkey",
940
+ "signingkey",
941
+ "signature",
942
+ "encryptionkey",
943
+ "session",
944
+ "sessionkey"
945
+ ];
946
+ /**
947
+ * A trailing `key` that is a word of its own.
948
+ *
949
+ * Read against the ORIGINAL key, where the separators that make `key` a word
950
+ * still exist: `key`, `api_key`, `x-api-key`, `signing-key`. This is the shape
951
+ * `packages/smithers/src/Bug.ts` matches, and stopping here is deliberate. Treating
952
+ * a camel-case hump as a separator too, `/[a-z0-9]Key$/`, looks equivalent and
953
+ * is not: it redacted `idempotencyKey`, the durable identity an effect boundary
954
+ * replays on, out of `@smthrs/engine-store`'s journal rows. A credential-named
955
+ * key is covered by {@link sensitiveKeySuffixes} instead, where the word before
956
+ * `key` has to be one that names a secret.
957
+ */
958
+ const trailingKeyWord = /(?:^|[^A-Za-z0-9])key$/i;
959
+ const canonicalKey = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "").replace(/s$/, "");
960
+ /** Numeric accounting fields that contain counts, never bearer material. */
961
+ const tokenCounterKeys = new Set([
962
+ "inputtoken",
963
+ "outputtoken",
964
+ "cachedinputtoken",
965
+ "reasoningtoken",
966
+ "totaltoken"
967
+ ]);
968
+ /**
969
+ * Any name ending in a plural `tokens` holds a count too, the rule the textual
970
+ * pass applies in {@link namesCredential}: `Envelope.budget.tokens` is the
971
+ * run's token ceiling, and `usage.cacheWriteTokens`, `maxTokens`, and
972
+ * `contextWindowTokens` are accounting; redacting them erased every journaled
973
+ * budget and cache-write count (#3846). A bare singular `token` stays bearer
974
+ * material even when it is numeric.
975
+ */
976
+ const isTokenCount = (key, value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 &&
977
+ (tokenCounterKeys.has(canonicalKey(key)) || /tokens$/i.test(key));
978
+ /**
979
+ * Whether a field name names a credential.
980
+ *
981
+ * Case and separators are ignored, so `api_key`, `apiKey`, and `x-api-key` are
982
+ * all recognised, one trailing plural `s` is stripped so `credentials` reads as
983
+ * `credential`, and a trailing `key` counts where it is a word of its own or
984
+ * where the word before it names a secret.
985
+ *
986
+ * The rule is a suffix test, not a substring test. `tokenizer`, `secretary`,
987
+ * `monkey`, and `idempotencyKey` are ordinary field names, and replacing their
988
+ * values would destroy data in a permanent row without protecting anything.
989
+ * That is the one place this rule is deliberately narrower than
990
+ * `packages/smithers/src/Bug.ts`'s substring form, which can afford the false
991
+ * positives because its output is a single report an operator reads once.
992
+ *
993
+ * @since 0.1.0
994
+ * @category predicates
995
+ */
996
+ export const isSensitiveKey = (key) => {
997
+ if (trailingKeyWord.test(key))
998
+ return true;
999
+ const canonical = canonicalKey(key);
1000
+ return sensitiveKeySuffixes.some((suffix) => canonical.endsWith(suffix));
1001
+ };
1002
+ const redactMember = (key, value, walk) => isSensitiveKey(key) && !isTokenCount(key, value) ? placeholder : walk(value);
1003
+ /**
1004
+ * A field name with a credential in it replaced outright, not rewritten in place.
1005
+ *
1006
+ * Redacting part of a key changes what the key reads as. `secret=sk-` rewrites
1007
+ * to `secret=[REDACTED]`, which now ENDS in a sensitive name, so a second
1008
+ * application would replace a value the first one left alone and redaction
1009
+ * would stop being a fixed point. Naming the whole key holds the verdict still:
1010
+ * `[REDACTED]` matches no rule and names no credential. Two such keys collapse
1011
+ * into one and the later member wins, which is the fidelity trade every other
1012
+ * marker here makes.
1013
+ */
1014
+ const redactKey = (key, rules) => {
1015
+ const redacted = redactString(key, rules);
1016
+ return redacted === key ? key : placeholder;
1017
+ };
1018
+ /**
1019
+ * How many times {@link redactString} re-applies the rules to reach a fixed
1020
+ * point. Rules feed each other: an assignment redacted inside URL userinfo
1021
+ * leaves userinfo the URL rule only then matches. Text no rule touches costs
1022
+ * one pass, and the default rules settle within three. Text that has not
1023
+ * settled after the last pass is replaced whole.
1024
+ */
1025
+ const fixedPointPasses = 8;
1026
+ /**
1027
+ * A copy of `pattern` that matches wherever `pattern` does, with no
1028
+ * lookbehind, or `null`. JavaScriptCore runs a pattern that has a lookbehind
1029
+ * in its interpreter, 30 to 70 times slower than compiled: 40 kB of prose cost
1030
+ * a Bun process 300 ms per diagnostic, where Node took 1 ms. Text the copy
1031
+ * never matches is text the rule cannot change, so the rule is skipped.
1032
+ *
1033
+ * Only a one-character negative lookbehind that starts the pattern is
1034
+ * rewritten, as a character the copy consumes, which keeps a name scan
1035
+ * starting once per identifier. Anywhere else, after `\b` or inside a
1036
+ * repeated group, the consumed character would make the copy stricter than
1037
+ * the rule, so any other lookbehind or a backreference leaves the rule
1038
+ * unfiltered.
1039
+ */
1040
+ const candidate = (pattern) => {
1041
+ const cached = candidates.get(pattern);
1042
+ if (cached !== undefined)
1043
+ return cached;
1044
+ const leading = /^\(\?<!\[(\^?)((?:\\.|[^\]\\])*)\]\)/.exec(pattern.source);
1045
+ const rest = leading === null ? pattern.source : pattern.source.slice(leading[0].length);
1046
+ const compiled = /\(\?<[!=]|\\(?:[1-9]|k<)/.test(rest)
1047
+ ? null
1048
+ : new RegExp(leading === null ? rest : `(?:^|[${leading[1] === "" ? "^" : ""}${leading[2]}])${rest}`, pattern.flags.replace(/[gy]/g, ""));
1049
+ candidates.set(pattern, compiled);
1050
+ return compiled;
1051
+ };
1052
+ const candidates = new WeakMap();
1053
+ const applyRule = (text, rule) => {
1054
+ if (candidate(rule.pattern)?.test(text) === false)
1055
+ return text;
1056
+ return rule.rewrite === undefined ? text.replace(rule.pattern, rule.replace ?? placeholder) : rule.rewrite(text);
1057
+ };
1058
+ const redactString = (value, rules) => {
1059
+ let text = value;
1060
+ for (let pass = 0; pass < fixedPointPasses; pass++) {
1061
+ const next = rules.reduce(applyRule, text);
1062
+ if (next === text)
1063
+ return text;
1064
+ text = next;
1065
+ }
1066
+ // Rules that never settle would let an exported row keep changing, and
1067
+ // what they left may still hold a credential. Fail closed.
1068
+ return placeholder;
1069
+ };
1070
+ /**
1071
+ * Maximum number of container edges traversed from a redaction root.
1072
+ *
1073
+ * Journal event schemas never approach 256 nested containers. This bound is
1074
+ * far above practical payloads while keeping traversal safely below Node's
1075
+ * call-stack limit for hostile input.
1076
+ *
1077
+ * @since 1.0.0
1078
+ * @category constants
1079
+ */
1080
+ export const maxDepth = 256;
1081
+ /**
1082
+ * A payload nested deeper than {@link maxDepth}, under `onTooDeep: "throw"`.
1083
+ * `code` is always `depth_exceeded`; `maxDepth` is the bound that was crossed.
1084
+ *
1085
+ * @since 1.0.0
1086
+ * @category errors
1087
+ */
1088
+ export class RedactionDepthError extends Schema.TaggedError()("@smthrs/journal/RedactionDepthError", { code: Schema.Literal("depth_exceeded"), maxDepth: Schema.Number, message: Schema.String }) {
1089
+ name = "RedactionDepthError";
1090
+ }
1091
+ /**
1092
+ * How many bytes a view may hold, and how many own members {@link redact} reads
1093
+ * off it, before it stops reading them.
1094
+ *
1095
+ * Enumerating a view's own properties materialises one pair per byte, so the
1096
+ * walk costs the buffer's size even though the rendering does not. Both halves
1097
+ * of the bound carry load, and neither is a bound on its own. A size alone is
1098
+ * not, because `byteLength` was read as an ordinary property and an ordinary
1099
+ * property can be shadowed: a pooled chunk that reports the bytes it has used
1100
+ * rather than the bytes it holds is a plain pattern, not an adversarial one,
1101
+ * and a 4 MB chunk reporting 12 walked one property per byte anyway. A count
1102
+ * alone is not, because a caller can hang a million properties on a ten-byte
1103
+ * view. So the size is read from the value's own internal slot, where nothing
1104
+ * a caller writes can answer for it, and the members are counted as they are
1105
+ * walked.
1106
+ *
1107
+ * @since 0.1.0
1108
+ * @category redaction
1109
+ */
1110
+ export const binaryWalkLimit = 65_536;
1111
+ /**
1112
+ * The byte-length getters, taken from the prototypes rather than from a value.
1113
+ *
1114
+ * `%TypedArray%.prototype`, `DataView.prototype` and `ArrayBuffer.prototype`
1115
+ * each define `byteLength` as an accessor over an internal slot, and applying
1116
+ * one to a value that has no such slot throws. Reading the size this way is
1117
+ * therefore a brand check as well as a measurement: a caller's own `byteLength`
1118
+ * property, accessor or not, never answers it.
1119
+ */
1120
+ const byteLengthGetters = [
1121
+ Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get,
1122
+ Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get,
1123
+ Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get
1124
+ ];
1125
+ /** A value's byte length from its own internal slot, or `undefined` when it has none. */
1126
+ const byteLength = (node) => {
1127
+ for (const getter of byteLengthGetters) {
1128
+ try {
1129
+ return Reflect.apply(getter, node, []);
1130
+ }
1131
+ catch {
1132
+ // Not that kind of view. Another getter answers, or none does and the
1133
+ // bytes are named without the members being read.
1134
+ }
1135
+ }
1136
+ return undefined;
1137
+ };
1138
+ /** The prototypes every binary view inherits from. */
1139
+ const binaryPrototypes = new Set([
1140
+ Object.getPrototypeOf(Uint8Array.prototype),
1141
+ DataView.prototype,
1142
+ ArrayBuffer.prototype
1143
+ ]);
1144
+ /** How many prototypes {@link isBinary} climbs before it stops asking. */
1145
+ const prototypeWalkLimit = 64;
1146
+ /**
1147
+ * Whether `node` is a binary view, including one held behind a proxy.
1148
+ *
1149
+ * `ArrayBuffer.isView` reads an internal slot, and a proxy has none of its own,
1150
+ * so it answers `false` for a proxy over a view. That sent a proxied 2 MB
1151
+ * buffer to the object branch, which rebuilt it one key per byte: 2,000 ms and
1152
+ * 22.9 million characters for one logged value. A proxy forwards
1153
+ * `getPrototypeOf` to its target, so the prototype chain answers where the
1154
+ * brand check cannot. The climb is capped because a proxy is free to hand back
1155
+ * a fresh object every time it is asked, which is an endless chain.
1156
+ */
1157
+ const isBinary = (node) => {
1158
+ if (ArrayBuffer.isView(node) || node instanceof ArrayBuffer)
1159
+ return true;
1160
+ try {
1161
+ let prototype = Object.getPrototypeOf(node);
1162
+ for (let step = 0; prototype !== null && step < prototypeWalkLimit; step++) {
1163
+ if (binaryPrototypes.has(prototype))
1164
+ return true;
1165
+ prototype = Object.getPrototypeOf(prototype);
1166
+ }
1167
+ }
1168
+ catch {
1169
+ // A revoked proxy refuses to be asked. It is not a view, and the object
1170
+ // branch names it.
1171
+ }
1172
+ return false;
1173
+ };
1174
+ /** Own keys of a binary view that name one of its bytes rather than a property. */
1175
+ const indexKey = /^(?:0|[1-9][0-9]*)$/;
1176
+ /** `Uint8Array 1024 bytes`, or the bare marker when the value will not say. */
1177
+ const describeBinary = (node, size) => {
1178
+ if (size === undefined)
1179
+ return binaryMarker;
1180
+ try {
1181
+ return `${node.constructor.name} ${size} bytes`;
1182
+ }
1183
+ catch {
1184
+ return binaryMarker;
1185
+ }
1186
+ };
1187
+ /**
1188
+ * The key {@link redact} files a binary view's size under.
1189
+ *
1190
+ * @since 0.1.0
1191
+ * @category redaction
1192
+ */
1193
+ export const binaryMarker = "[Binary]";
1194
+ /**
1195
+ * What {@link redact} writes in place of a function or a class object.
1196
+ *
1197
+ * @since 0.1.0
1198
+ * @category redaction
1199
+ */
1200
+ export const functionMarker = "[Function]";
1201
+ /**
1202
+ * What {@link redact} writes in place of a symbol.
1203
+ *
1204
+ * @since 0.1.0
1205
+ * @category redaction
1206
+ */
1207
+ export const symbolMarker = "[Symbol]";
1208
+ /**
1209
+ * What {@link redact} writes past {@link maxDepth} under `onTooDeep: "name"`.
1210
+ *
1211
+ * @since 0.1.0
1212
+ * @category redaction
1213
+ */
1214
+ export const depthMarker = "[Deep]";
1215
+ /**
1216
+ * Returns `value` with credentials removed.
1217
+ *
1218
+ * Objects and arrays are rebuilt: a field whose name {@link isSensitiveKey}
1219
+ * is replaced wholesale, every other string is run through the textual rules,
1220
+ * and a cycle is collapsed to `"[Circular]"` so the result always encodes.
1221
+ * A number, a boolean, `null` and `undefined` are returned untouched, because
1222
+ * redacting one destroys data without protecting anything. A function and a
1223
+ * symbol are NAMED, {@link functionMarker} and {@link symbolMarker}: a body, an
1224
+ * own property and a description are all text a renderer prints, and none of it
1225
+ * can be rewritten in place.
1226
+ *
1227
+ * Traversal accepts at most {@link maxDepth} container edges. A deeper value
1228
+ * throws by default, so the journal boundary can report a typed `invalid_event`
1229
+ * instead of overflowing the runtime stack. {@link Options.onTooDeep} set to
1230
+ * `"name"` writes {@link depthMarker} in its place instead, which is what a
1231
+ * logger wants.
1232
+ *
1233
+ * @since 0.1.0
1234
+ * @category redaction
1235
+ */
1236
+ export const redact = (value, options) => {
1237
+ const onTooDeep = options?.onTooDeep ?? "throw";
1238
+ const rules = globalRules(options?.rules ?? defaultRules);
1239
+ /**
1240
+ * A binary view named by its type and size, with its own properties walked.
1241
+ *
1242
+ * Its bytes are not text the rules can read, and rebuilding it from its
1243
+ * entries wrote one key per byte: a 100 kB buffer rendered 1.4 MB. Handing
1244
+ * the view back untouched is not the answer either, because `redact` is the
1245
+ * journal's own write path, so a caller's `apiKey` property hung on a buffer
1246
+ * went into a durable row in clear. Name the bytes, keep walking the text.
1247
+ */
1248
+ const binary = (node, ancestors, depth) => {
1249
+ const size = byteLength(node);
1250
+ // The description is text read off the value, so it meets the rules like
1251
+ // any other text: a class name is caller data, and a view whose
1252
+ // constructor is named after a credential wrote it into a durable row.
1253
+ const entries = [[binaryMarker, redactString(describeBinary(node, size), rules)]];
1254
+ // `Object.entries` on a view materialises one pair per byte before the
1255
+ // index filter can discard them, which cost 312 ms for 1 MB on the journal
1256
+ // write path. Past the bound the bytes are named and nothing else is read,
1257
+ // so a member a caller hung on a large view is dropped rather than shown.
1258
+ // A value that will not answer from its internal slot, such as a proxy over
1259
+ // a view, is named and never enumerated at all.
1260
+ if (size !== undefined && size <= binaryWalkLimit) {
1261
+ let walked = 0;
1262
+ for (const [key, field] of Object.entries(node)) {
1263
+ // An index is one of the bytes just named, not a property a caller set.
1264
+ if (indexKey.test(key))
1265
+ continue;
1266
+ // The size bounds the bytes, not the properties: a caller can hang a
1267
+ // million members on a ten-byte view, and each one costs three rule
1268
+ // scans over its name and a walk of its value.
1269
+ if (walked >= binaryWalkLimit)
1270
+ break;
1271
+ walked++;
1272
+ entries.push([
1273
+ redactKey(key, rules),
1274
+ redactMember(key, field, (value) => walk(value, ancestors, depth + 1, key))
1275
+ ]);
1276
+ }
1277
+ }
1278
+ // `Object.fromEntries`, not `named[key] = …`, for the reason the object
1279
+ // branch below gives: a literal `__proto__` key would route through the
1280
+ // inherited setter and the member would vanish from the row.
1281
+ return Object.fromEntries(entries);
1282
+ };
1283
+ const walk = (node, ancestors, depth, key) => {
1284
+ if (depth > maxDepth) {
1285
+ if (onTooDeep === "name")
1286
+ return depthMarker;
1287
+ throw new RedactionDepthError({
1288
+ code: "depth_exceeded",
1289
+ maxDepth,
1290
+ message: `redaction depth exceeds ${maxDepth}`
1291
+ });
1292
+ }
1293
+ if (typeof node === "string")
1294
+ return redactString(node, rules);
1295
+ // A function, a class object or a symbol carries text a walk never reaches
1296
+ // (own properties, a description, a body), and the renderer prints it. None
1297
+ // of it can be redacted in place, so the value is named instead.
1298
+ if (typeof node === "function")
1299
+ return functionMarker;
1300
+ if (typeof node === "symbol")
1301
+ return symbolMarker;
1302
+ if (node === null || typeof node !== "object")
1303
+ return node;
1304
+ if (isBinary(node))
1305
+ return binary(node, ancestors, depth);
1306
+ if (ancestors.has(node))
1307
+ return "[Circular]";
1308
+ // A journal row is bounded by its schema, but a LOGGED value is arbitrary:
1309
+ // the logger sends every non-Error value here, and a chain deep enough to
1310
+ // exhaust the stack would throw while the line is rendering, killing the
1311
+ // run the line describes. Past the cap the value is named, the way a cycle
1312
+ // is named.
1313
+ ancestors.add(node);
1314
+ try {
1315
+ const toJSON = node.toJSON;
1316
+ // JSON.stringify passes the containing key (or "" at the root) to toJSON.
1317
+ // Reuse it when walking the replacement; siblings may share this object.
1318
+ if (typeof toJSON === "function")
1319
+ return walk(toJSON.call(node, key), ancestors, depth, key);
1320
+ if (Array.isArray(node)) {
1321
+ // `map` invokes the input's species constructor, which can restore
1322
+ // credential fields and inspection hooks after the elements are walked.
1323
+ // Rebuild a plain array, preserving the original length and holes.
1324
+ const length = node.length;
1325
+ const result = new Array(length);
1326
+ const elements = new Array(length);
1327
+ for (let index = 0; index < length; index++) {
1328
+ if (!(index in node))
1329
+ continue;
1330
+ elements[index] = node[index];
1331
+ result[index] = walk(elements[index], ancestors, depth + 1, String(index));
1332
+ }
1333
+ // An argv keeps a flag and its value in two elements, so no rule sees
1334
+ // `--password hunter2` whole. The element after a flag is a credential
1335
+ // when its name says so (`--token=x` carries its own, and a count under
1336
+ // `--max-tokens` is kept), or when the active rules redact it read
1337
+ // after the flag and the elements before it (`-p`, `-pw`, `-passin`,
1338
+ // `sshpass -p`) differently than alone.
1339
+ for (let index = 0; index + 1 < length; index++) {
1340
+ // The values the first loop read, never a second read: a proxy may
1341
+ // answer a second `get` differently.
1342
+ const flag = elements[index];
1343
+ const value = elements[index + 1];
1344
+ if (typeof flag !== "string" || typeof value !== "string" || !/^-[^=\s]+$/.test(flag))
1345
+ continue;
1346
+ const name = flag.replace(/^-+/, "");
1347
+ const before = elements.slice(Math.max(0, index - 3), index + 1).filter((element) => typeof element === "string").join(" ");
1348
+ const consumes = (isSensitiveKey(name) && namesCredential(name, value)) ||
1349
+ redactString(`${before} ${value}`, rules) !== `${redactString(before, rules)} ${redactString(value, rules)}`;
1350
+ if (consumes)
1351
+ result[index + 1] = placeholder;
1352
+ }
1353
+ return result;
1354
+ }
1355
+ // `result[key] = …` routes a literal `__proto__` key through the
1356
+ // inherited setter, so the field would silently become the result's
1357
+ // prototype instead of a member: the payload loses data and redaction
1358
+ // stops being a fixed point. `Object.fromEntries` defines own data
1359
+ // properties and has no such hole.
1360
+ return Object.fromEntries(Object.entries(node).map(([key, field]) => [
1361
+ // The KEY is text too. Rewriting only values let a credential used as
1362
+ // a log annotation key reach the operator, since Effect renders an
1363
+ // annotation as `key=value`, and become an OTLP span attribute name.
1364
+ redactKey(key, rules),
1365
+ redactMember(key, field, (value) => walk(value, ancestors, depth + 1, key))
1366
+ ]));
1367
+ }
1368
+ finally {
1369
+ ancestors.delete(node);
1370
+ }
1371
+ };
1372
+ return walk(value, new WeakSet(), 0, "");
1373
+ };
1374
+ /**
1375
+ * Builds a redactor over a rule set.
1376
+ *
1377
+ * @since 0.1.0
1378
+ * @category constructors
1379
+ */
1380
+ export const make = (options) => (value) => redact(value, options);
1381
+ /**
1382
+ * Applies a redactor to an already-encoded JSON string, returning the
1383
+ * re-encoded result.
1384
+ *
1385
+ * For export and display surfaces that hold a column verbatim, a rendered
1386
+ * `state_json`, a support bundle, where the value is already encoded and must
1387
+ * not be decoded into the executable path. A string that does not parse is
1388
+ * returned untouched: validation is the caller's, and rejecting here would
1389
+ * turn a redaction concern into a schema error. Once parsing succeeds, a
1390
+ * throwing redactor or an encoding failure returns the valid JSON string
1391
+ * `"[REDACTED]"`; the original parsed text is never returned.
1392
+ *
1393
+ * @since 0.1.0
1394
+ * @category redaction
1395
+ */
1396
+ export const redactJsonString = (json, redactor) => {
1397
+ const decoded = Schema.decodeUnknownResult(UnknownFromJsonString)(json);
1398
+ if (Result.isFailure(decoded))
1399
+ return json;
1400
+ const attempted = Result.try(() => Schema.encodeUnknownResult(UnknownFromJsonString)(redactor(decoded.success)));
1401
+ if (Result.isFailure(attempted))
1402
+ return JSON.stringify(placeholder);
1403
+ return Result.isSuccess(attempted.success) ? attempted.success.success : JSON.stringify(placeholder);
1404
+ };
1405
+ /**
1406
+ * Lines a {@link lineRedactor} holds for one open value. Past this, or past
1407
+ * 64 KiB, it stops holding: it emits what it held, redacted, and withholds
1408
+ * every later line until the stream ends, when one placeholder stands for
1409
+ * them. Dropping lines from the middle instead changed which brackets and
1410
+ * quotes were open, and released a later secret in clear.
1411
+ *
1412
+ * @since 1.0.0
1413
+ * @category constants
1414
+ */
1415
+ export const maxHeldLines = 256;
1416
+ const maxHeldBytes = 64 * 1024;
1417
+ /** Held lines a {@link lineRedactor} asks about one by one before it asks only as the block grows by half. */
1418
+ const eagerHeldLines = 16;
1419
+ /**
1420
+ * The most brackets and strings the dropped middle of an overlong line may
1421
+ * leave open before a {@link lineRedactor} stops reading it and treats the
1422
+ * line as leaving a value open. Without it the middle's state grew by one
1423
+ * entry per bracket: 32 MiB of `[` held 1.7 GB (#3088).
1424
+ */
1425
+ const maxDroppedDepth = 1024;
1426
+ /**
1427
+ * The longest line a {@link lineRedactor} reads whole. A longer line keeps
1428
+ * its first and last 16 KiB; its middle is scanned for what it leaves open
1429
+ * and dropped.
1430
+ *
1431
+ * @since 1.0.0
1432
+ * @category constants
1433
+ */
1434
+ export const maxPartialLine = 32 * 1024;
1435
+ /**
1436
+ * What a {@link lineRedactor} emits in place of a line longer than
1437
+ * {@link maxPartialLine}.
1438
+ *
1439
+ * @since 1.0.0
1440
+ * @category constants
1441
+ */
1442
+ export const omittedLine = "[overlong line omitted]";
1443
+ /**
1444
+ * A next line no rule redacts alone, which an open value swallows. The value
1445
+ * is open when the redacted text no longer ENDS with it: text before it may
1446
+ * contain the same word.
1447
+ */
1448
+ const continuationProbe = "\n'probe'";
1449
+ /** Rules with the global flag each rule needs to replace every match. */
1450
+ const globalRules = (rules) => rules.map((rule) => rule.pattern.flags.includes("g")
1451
+ ? rule
1452
+ : { ...rule, pattern: new RegExp(rule.pattern.source, `${rule.pattern.flags}g`) });
1453
+ /**
1454
+ * A redactor for a stream that must be emitted line by line: a live build
1455
+ * log, a child's stderr.
1456
+ *
1457
+ * Redacting each line alone is the flaw that leaked a private key's body, and
1458
+ * the tail of every string `util.inspect` split over several lines: only the
1459
+ * line holding the name was redacted. This one asks the rules themselves
1460
+ * whether a line leaves a value open, by checking whether the value swallows
1461
+ * a probe placed on the next line, and holds lines until it closes. The held
1462
+ * block is then redacted whole, exactly as {@link redact} redacts a string.
1463
+ *
1464
+ * A line longer than {@link maxPartialLine} is read as its first and last
1465
+ * 16 KiB. Its middle is dropped, but a bracket, quote or key block the middle
1466
+ * leaves open would have opened a value the kept ends cannot show, so then
1467
+ * the rest of the stream is withheld. Such a line is never emitted, only
1468
+ * {@link omittedLine}, and neither is any block it was held in.
1469
+ *
1470
+ * Its state is bounded whatever the stream does: the line still arriving is
1471
+ * a 16 KiB head, a 16 KiB tail and at most 1024 open brackets or strings of
1472
+ * its middle, a middle nested deeper counting as one left open; the held
1473
+ * block is bounded by {@link maxHeldLines} and 64 KiB. Its cost is linear:
1474
+ * past the first 16 held lines the block is re-read only once it has grown
1475
+ * by half, on Node and on Bun alike (#3088).
1476
+ *
1477
+ * `rules` defaults to {@link diagnosticRules}. The array is read on every
1478
+ * line, so a caller may add a rule, a session secret, as the stream runs.
1479
+ *
1480
+ * @since 1.0.0
1481
+ * @category constructors
1482
+ */
1483
+ export const lineRedactor = (rules = diagnosticRules) => {
1484
+ const held = [];
1485
+ let heldBytes = 0;
1486
+ let askAt = 0;
1487
+ let heldOverlong = false;
1488
+ let withheld = false;
1489
+ // The line still arriving: whole up to the bound, then a head, a rolling
1490
+ // tail, and what the dropped middle leaves open.
1491
+ const edge = maxPartialLine / 2;
1492
+ let head = "";
1493
+ let tail = "";
1494
+ let overlong = false;
1495
+ let middle = [];
1496
+ let middleDeep = false;
1497
+ let middleKey = false;
1498
+ let carry = "";
1499
+ const resetPartial = () => {
1500
+ head = "";
1501
+ tail = "";
1502
+ overlong = false;
1503
+ middle = [];
1504
+ middleDeep = false;
1505
+ middleKey = false;
1506
+ carry = "";
1507
+ };
1508
+ const scanDropped = (dropped) => {
1509
+ // What the middle leaves open is read in slices, and once it is nested
1510
+ // past `maxDroppedDepth` it is not read at all: the line is then already
1511
+ // risky, and the stack held one entry per bracket of a line of any length.
1512
+ for (let from = 0; from < dropped.length && !middleDeep; from += edge) {
1513
+ track(middle, dropped, from, Math.min(dropped.length, from + edge));
1514
+ if (middle.length > maxDroppedDepth) {
1515
+ middleDeep = true;
1516
+ middle = [];
1517
+ }
1518
+ }
1519
+ const seen = carry + dropped;
1520
+ const begin = seen.search(/-----BEGIN[^-]*PRIVATE KEY/);
1521
+ const lastBegin = seen.lastIndexOf("-----BEGIN");
1522
+ const lastEnd = seen.lastIndexOf("-----END");
1523
+ if (begin !== -1 || lastEnd !== -1)
1524
+ middleKey = lastBegin > lastEnd;
1525
+ carry = seen.slice(-64);
1526
+ };
1527
+ const redacted = (text) => redactString(text, globalRules(rules));
1528
+ const release = () => {
1529
+ const text = redacted(held.join("\n"));
1530
+ const overlongBlock = heldOverlong;
1531
+ held.length = 0;
1532
+ heldBytes = 0;
1533
+ askAt = 0;
1534
+ heldOverlong = false;
1535
+ return overlongBlock ? [omittedLine] : text.split("\n");
1536
+ };
1537
+ const part = (text) => {
1538
+ if (withheld)
1539
+ return;
1540
+ if (!overlong) {
1541
+ head += text;
1542
+ if (head.length <= maxPartialLine)
1543
+ return;
1544
+ overlong = true;
1545
+ tail = head.slice(edge);
1546
+ head = head.slice(0, edge);
1547
+ }
1548
+ else
1549
+ tail += text;
1550
+ if (tail.length > edge) {
1551
+ scanDropped(tail.slice(0, tail.length - edge));
1552
+ tail = tail.slice(-edge);
1553
+ }
1554
+ };
1555
+ const line = (rest) => {
1556
+ if (withheld) {
1557
+ resetPartial();
1558
+ return [];
1559
+ }
1560
+ part(rest);
1561
+ let text = head;
1562
+ if (overlong) {
1563
+ const risky = middle.length > 0 || middleDeep || middleKey;
1564
+ text = `${head} ${tail}`;
1565
+ resetPartial();
1566
+ if (risky) {
1567
+ const before = held.length === 0 ? [] : [placeholder];
1568
+ held.length = 0;
1569
+ heldBytes = 0;
1570
+ askAt = 0;
1571
+ heldOverlong = false;
1572
+ withheld = true;
1573
+ return [...before, omittedLine];
1574
+ }
1575
+ heldOverlong = true;
1576
+ }
1577
+ else
1578
+ resetPartial();
1579
+ held.push(text);
1580
+ heldBytes += text.length + 1;
1581
+ // Asking after every line re-redacted the whole block per line, so a
1582
+ // block of n bytes cost n² (#3088). Past the first lines the question is
1583
+ // asked again only once the block has grown by half, which keeps the
1584
+ // cost linear; a block that closed in between is released with the
1585
+ // lines after it, redacted as one block, which hides no less.
1586
+ if (held.length <= eagerHeldLines || heldBytes >= askAt) {
1587
+ if (redacted(held.join("\n") + continuationProbe).endsWith(continuationProbe))
1588
+ return release();
1589
+ askAt = heldBytes + (heldBytes >> 1);
1590
+ }
1591
+ if (held.length <= maxHeldLines && heldBytes <= maxHeldBytes)
1592
+ return [];
1593
+ withheld = true;
1594
+ return release();
1595
+ };
1596
+ const peek = () => {
1597
+ if (withheld)
1598
+ return [placeholder];
1599
+ const pending = overlong ? [omittedLine] : head === "" ? [] : [head];
1600
+ if (heldOverlong)
1601
+ return [omittedLine];
1602
+ const text = [...held, ...(overlong ? [] : pending)];
1603
+ const out = text.length === 0 ? [] : redacted(text.join("\n")).split("\n");
1604
+ return overlong ? [...out, omittedLine] : out;
1605
+ };
1606
+ return {
1607
+ line,
1608
+ part,
1609
+ peek,
1610
+ flush: () => {
1611
+ const out = head !== "" || overlong ? [...line("")] : [];
1612
+ if (withheld) {
1613
+ withheld = false;
1614
+ return [...out, placeholder];
1615
+ }
1616
+ return held.length === 0 ? out : [...out, ...release()];
1617
+ }
1618
+ };
1619
+ };
1620
+ /**
1621
+ * The identity redactor, for a caller that persists payloads verbatim by
1622
+ * choice: a trusted single-tenant store, or a suite asserting on raw input.
1623
+ *
1624
+ * @since 0.1.0
1625
+ * @category constructors
1626
+ */
1627
+ export const makeNoop = () => (value) => value;
1628
+ //# sourceMappingURL=Redaction.js.map