@mainwp/control 1.1.0-beta.1 → 2.0.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 (172) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/README.md +162 -518
  3. package/dist/chat/chat-engine.d.ts +24 -54
  4. package/dist/chat/chat-engine.d.ts.map +1 -1
  5. package/dist/chat/chat-engine.js +367 -166
  6. package/dist/chat/chat-engine.js.map +1 -1
  7. package/dist/chat/context-window.d.ts +57 -0
  8. package/dist/chat/context-window.d.ts.map +1 -0
  9. package/dist/chat/context-window.js +94 -0
  10. package/dist/chat/context-window.js.map +1 -0
  11. package/dist/chat/providers/anthropic.d.ts +0 -4
  12. package/dist/chat/providers/anthropic.d.ts.map +1 -1
  13. package/dist/chat/providers/anthropic.js +67 -45
  14. package/dist/chat/providers/anthropic.js.map +1 -1
  15. package/dist/chat/providers/gemini.d.ts +2 -2
  16. package/dist/chat/providers/gemini.d.ts.map +1 -1
  17. package/dist/chat/providers/gemini.js +67 -43
  18. package/dist/chat/providers/gemini.js.map +1 -1
  19. package/dist/chat/providers/openai-compatible.d.ts +1 -1
  20. package/dist/chat/providers/openai-compatible.d.ts.map +1 -1
  21. package/dist/chat/providers/openai-compatible.js +91 -29
  22. package/dist/chat/providers/openai-compatible.js.map +1 -1
  23. package/dist/chat/providers/provider-fetch.d.ts +11 -0
  24. package/dist/chat/providers/provider-fetch.d.ts.map +1 -1
  25. package/dist/chat/providers/provider-fetch.js +86 -4
  26. package/dist/chat/providers/provider-fetch.js.map +1 -1
  27. package/dist/chat/providers/provider.d.ts +74 -1
  28. package/dist/chat/providers/provider.d.ts.map +1 -1
  29. package/dist/chat/providers/provider.js +112 -2
  30. package/dist/chat/providers/provider.js.map +1 -1
  31. package/dist/chat/providers/sse-reader.d.ts +3 -0
  32. package/dist/chat/providers/sse-reader.d.ts.map +1 -1
  33. package/dist/chat/providers/sse-reader.js +75 -15
  34. package/dist/chat/providers/sse-reader.js.map +1 -1
  35. package/dist/chat/system-prompt.d.ts +0 -2
  36. package/dist/chat/system-prompt.d.ts.map +1 -1
  37. package/dist/chat/system-prompt.js +10 -6
  38. package/dist/chat/system-prompt.js.map +1 -1
  39. package/dist/chat/tool-envelope.d.ts +3 -0
  40. package/dist/chat/tool-envelope.d.ts.map +1 -1
  41. package/dist/chat/tool-envelope.js +156 -10
  42. package/dist/chat/tool-envelope.js.map +1 -1
  43. package/dist/commands/abilities/info.d.ts.map +1 -1
  44. package/dist/commands/abilities/info.js +6 -3
  45. package/dist/commands/abilities/info.js.map +1 -1
  46. package/dist/commands/abilities/list.js +2 -2
  47. package/dist/commands/abilities/list.js.map +1 -1
  48. package/dist/commands/abilities/run.d.ts.map +1 -1
  49. package/dist/commands/abilities/run.js +147 -48
  50. package/dist/commands/abilities/run.js.map +1 -1
  51. package/dist/commands/chat.d.ts +12 -0
  52. package/dist/commands/chat.d.ts.map +1 -1
  53. package/dist/commands/chat.js +67 -42
  54. package/dist/commands/chat.js.map +1 -1
  55. package/dist/commands/config/show.d.ts.map +1 -1
  56. package/dist/commands/config/show.js +59 -47
  57. package/dist/commands/config/show.js.map +1 -1
  58. package/dist/commands/doctor.d.ts +0 -8
  59. package/dist/commands/doctor.d.ts.map +1 -1
  60. package/dist/commands/doctor.js +22 -36
  61. package/dist/commands/doctor.js.map +1 -1
  62. package/dist/commands/jobs/watch.d.ts +4 -0
  63. package/dist/commands/jobs/watch.d.ts.map +1 -1
  64. package/dist/commands/jobs/watch.js +66 -27
  65. package/dist/commands/jobs/watch.js.map +1 -1
  66. package/dist/commands/login.d.ts.map +1 -1
  67. package/dist/commands/login.js +59 -10
  68. package/dist/commands/login.js.map +1 -1
  69. package/dist/commands/profile/delete.d.ts.map +1 -1
  70. package/dist/commands/profile/delete.js +19 -3
  71. package/dist/commands/profile/delete.js.map +1 -1
  72. package/dist/commands/profile/list.d.ts.map +1 -1
  73. package/dist/commands/profile/list.js +6 -2
  74. package/dist/commands/profile/list.js.map +1 -1
  75. package/dist/commands/profile/use.d.ts.map +1 -1
  76. package/dist/commands/profile/use.js +4 -1
  77. package/dist/commands/profile/use.js.map +1 -1
  78. package/dist/config/fs-utils.d.ts.map +1 -1
  79. package/dist/config/fs-utils.js +19 -6
  80. package/dist/config/fs-utils.js.map +1 -1
  81. package/dist/config/keychain.d.ts +78 -6
  82. package/dist/config/keychain.d.ts.map +1 -1
  83. package/dist/config/keychain.js +194 -27
  84. package/dist/config/keychain.js.map +1 -1
  85. package/dist/config/profile-store.d.ts +11 -3
  86. package/dist/config/profile-store.d.ts.map +1 -1
  87. package/dist/config/profile-store.js +53 -19
  88. package/dist/config/profile-store.js.map +1 -1
  89. package/dist/core/abilities-executor.d.ts +42 -6
  90. package/dist/core/abilities-executor.d.ts.map +1 -1
  91. package/dist/core/abilities-executor.js +264 -67
  92. package/dist/core/abilities-executor.js.map +1 -1
  93. package/dist/core/batch-manager.d.ts +10 -5
  94. package/dist/core/batch-manager.d.ts.map +1 -1
  95. package/dist/core/batch-manager.js +78 -22
  96. package/dist/core/batch-manager.js.map +1 -1
  97. package/dist/core/execute-ability-with-policy.d.ts +8 -0
  98. package/dist/core/execute-ability-with-policy.d.ts.map +1 -0
  99. package/dist/core/execute-ability-with-policy.js +19 -0
  100. package/dist/core/execute-ability-with-policy.js.map +1 -0
  101. package/dist/core/http-client.d.ts +5 -1
  102. package/dist/core/http-client.d.ts.map +1 -1
  103. package/dist/core/http-client.js +118 -46
  104. package/dist/core/http-client.js.map +1 -1
  105. package/dist/core/job-id.d.ts +2 -0
  106. package/dist/core/job-id.d.ts.map +1 -0
  107. package/dist/core/job-id.js +22 -0
  108. package/dist/core/job-id.js.map +1 -0
  109. package/dist/core/preview-plan.d.ts +5 -0
  110. package/dist/core/preview-plan.d.ts.map +1 -0
  111. package/dist/core/preview-plan.js +247 -0
  112. package/dist/core/preview-plan.js.map +1 -0
  113. package/dist/core/safety-controller.d.ts +29 -10
  114. package/dist/core/safety-controller.d.ts.map +1 -1
  115. package/dist/core/safety-controller.js +154 -41
  116. package/dist/core/safety-controller.js.map +1 -1
  117. package/dist/lib/base-command.d.ts +20 -0
  118. package/dist/lib/base-command.d.ts.map +1 -1
  119. package/dist/lib/base-command.js +92 -35
  120. package/dist/lib/base-command.js.map +1 -1
  121. package/dist/output/formatter.d.ts +37 -1
  122. package/dist/output/formatter.d.ts.map +1 -1
  123. package/dist/output/formatter.js +111 -16
  124. package/dist/output/formatter.js.map +1 -1
  125. package/dist/output/json-envelope.d.ts.map +1 -1
  126. package/dist/output/json-envelope.js +8 -5
  127. package/dist/output/json-envelope.js.map +1 -1
  128. package/dist/utils/audit-logger.d.ts +26 -8
  129. package/dist/utils/audit-logger.d.ts.map +1 -1
  130. package/dist/utils/audit-logger.js +93 -20
  131. package/dist/utils/audit-logger.js.map +1 -1
  132. package/dist/utils/error-sanitizer.d.ts +6 -0
  133. package/dist/utils/error-sanitizer.d.ts.map +1 -0
  134. package/dist/utils/error-sanitizer.js +120 -0
  135. package/dist/utils/error-sanitizer.js.map +1 -0
  136. package/dist/utils/errors.d.ts +12 -0
  137. package/dist/utils/errors.d.ts.map +1 -1
  138. package/dist/utils/errors.js +14 -0
  139. package/dist/utils/errors.js.map +1 -1
  140. package/dist/utils/format.d.ts +68 -0
  141. package/dist/utils/format.d.ts.map +1 -1
  142. package/dist/utils/format.js +668 -0
  143. package/dist/utils/format.js.map +1 -1
  144. package/dist/utils/prompt.d.ts.map +1 -1
  145. package/dist/utils/prompt.js +28 -23
  146. package/dist/utils/prompt.js.map +1 -1
  147. package/dist/utils/redaction.d.ts +21 -0
  148. package/dist/utils/redaction.d.ts.map +1 -0
  149. package/dist/utils/redaction.js +85 -0
  150. package/dist/utils/redaction.js.map +1 -0
  151. package/dist/utils/retry.d.ts +0 -4
  152. package/dist/utils/retry.d.ts.map +1 -1
  153. package/dist/utils/retry.js +0 -9
  154. package/dist/utils/retry.js.map +1 -1
  155. package/dist/utils/terminal-sanitizer.d.ts +21 -0
  156. package/dist/utils/terminal-sanitizer.d.ts.map +1 -1
  157. package/dist/utils/terminal-sanitizer.js +80 -14
  158. package/dist/utils/terminal-sanitizer.js.map +1 -1
  159. package/dist/validation/input-sanitizer.d.ts +0 -4
  160. package/dist/validation/input-sanitizer.d.ts.map +1 -1
  161. package/dist/validation/input-sanitizer.js +15 -64
  162. package/dist/validation/input-sanitizer.js.map +1 -1
  163. package/dist/validation/sanitize-schema.d.ts +31 -0
  164. package/dist/validation/sanitize-schema.d.ts.map +1 -0
  165. package/dist/validation/sanitize-schema.js +158 -0
  166. package/dist/validation/sanitize-schema.js.map +1 -0
  167. package/dist/validation/schema-validator.d.ts +10 -0
  168. package/dist/validation/schema-validator.d.ts.map +1 -1
  169. package/dist/validation/schema-validator.js +50 -5
  170. package/dist/validation/schema-validator.js.map +1 -1
  171. package/oclif.manifest.json +96 -74
  172. package/package.json +25 -8
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Provides consistent secret masking across all commands.
5
5
  */
6
+ import { isSensitiveKey } from './redaction.js';
6
7
  /**
7
8
  * Masks a secret value by showing only the first and last few characters.
8
9
  *
@@ -66,4 +67,671 @@ export function maskApiKey(apiKey) {
66
67
  minLength: 10,
67
68
  });
68
69
  }
70
+ /**
71
+ * Mask userinfo (username/password) embedded in a URL.
72
+ *
73
+ * SECURITY: Profiles saved before userinfo rejection was added may still carry
74
+ * `user:pass@` in the stored dashboard URL; every display path must mask it.
75
+ *
76
+ * Returns the input unchanged when it is not a parseable URL or has no
77
+ * userinfo. String replacement (not URL re-serialization) keeps the rest of
78
+ * the URL byte-for-byte identical — no trailing-slash normalization.
79
+ *
80
+ * @param url - The URL to mask
81
+ * @returns The URL with userinfo replaced by `***:***@`, the input unchanged
82
+ * when it has no userinfo, or `[URL_WITH_CREDENTIALS_REDACTED]` when userinfo
83
+ * was detected but could not be isolated in the raw string
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * maskUrlUserinfo('https://admin:secret@example.com') // 'https://***:***@example.com'
88
+ * maskUrlUserinfo('https://example.com/path') // unchanged
89
+ * ```
90
+ */
91
+ /** The placeholder both userinfo components are replaced with. */
92
+ const MASKED_USERINFO = '***';
93
+ const REDACTED_SENTINEL = '[URL_WITH_CREDENTIALS_REDACTED]';
94
+ export function maskUrlUserinfo(url) {
95
+ let parsed;
96
+ try {
97
+ parsed = new URL(url);
98
+ }
99
+ catch {
100
+ return url;
101
+ }
102
+ if (!parsed.username && !parsed.password) {
103
+ return url;
104
+ }
105
+ // Already masked. Re-masking would produce a byte-identical string, which
106
+ // the fail-closed check below reads as "credentials the regex could not
107
+ // isolate" and replaces with the sentinel. Masking must be idempotent: the
108
+ // debug redactor applies it centrally, so a value can arrive here twice.
109
+ // There is nothing to leak either way, since the userinfo is literally `***`.
110
+ if (parsed.username === MASKED_USERINFO && parsed.password === MASKED_USERINFO) {
111
+ return url;
112
+ }
113
+ // Greedy through the LAST @ in the authority: a password containing "@"
114
+ // must not leak its tail. `?`/`#`/`/` bound the authority section.
115
+ const masked = url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#\s]*@/i, '$1***:***@');
116
+ // The parser saw userinfo the regex could not isolate: WHATWG parsing
117
+ // strips tab/newline and trims C0 controls before detecting credentials,
118
+ // so a raw string containing them slips past the whitespace-excluding
119
+ // regex. Fail closed rather than echo the credentials.
120
+ if (masked === url) {
121
+ return REDACTED_SENTINEL;
122
+ }
123
+ return masked;
124
+ }
125
+ /**
126
+ * Query and fragment parameters, for sensitive-key redaction.
127
+ *
128
+ * `#` is a separator alongside `?`/`&` and is excluded from the key and value
129
+ * classes: without that, a harmless leading parameter's value swallows
130
+ * `#api_key=...` and the fragment is never examined.
131
+ */
132
+ const URL_PARAMETER = /([?&#])([^=&#\s]+)=([^&#\s]*)/g;
133
+ /**
134
+ * Classify a URL parameter key by its decoded spelling.
135
+ *
136
+ * The raw key is what a reader sees, but not what the parameter is named:
137
+ * `api%5Fkey` normalizes to `api%5fkey`, matches nothing on the shared
138
+ * sensitive list, and the secret goes out in full. Decoding cannot hide a term
139
+ * the raw key already showed — it only collapses `%XX` triplets, never inserts
140
+ * characters between literals — so the decoded form is the stricter test on its
141
+ * own.
142
+ *
143
+ * An undecodable key (lone `%`, truncated escape, invalid UTF-8 sequence)
144
+ * counts as sensitive. Redacting a value that was not a credential costs
145
+ * display fidelity; failing open costs the credential.
146
+ */
147
+ export function isSensitiveParameterKey(key) {
148
+ let decoded;
149
+ try {
150
+ decoded = decodeURIComponent(key);
151
+ }
152
+ catch {
153
+ return true;
154
+ }
155
+ return isSensitiveKey(decoded);
156
+ }
157
+ /**
158
+ * Mask everything credential-shaped in a URL for display: userinfo, plus the
159
+ * value of any query or fragment parameter whose key — percent-decoded first —
160
+ * is on the shared sensitive list.
161
+ *
162
+ * SECURITY: userinfo is rejected at intake, but profiles saved before that
163
+ * check — and before query strings were rejected — can still carry
164
+ * `?access_token=` or `#api_key=` in the stored dashboard URL. Every display
165
+ * path must mask both forms.
166
+ *
167
+ * @param url - The URL to mask
168
+ * @returns The URL with userinfo masked as `***:***@` and sensitive parameter
169
+ * values replaced by `[REDACTED]`, or the userinfo sentinel when credentials
170
+ * were detected but could not be isolated
171
+ */
172
+ export function maskUrlCredentials(url) {
173
+ const masked = maskUrlUserinfo(url);
174
+ if (masked === REDACTED_SENTINEL) {
175
+ return masked;
176
+ }
177
+ // The original key spelling is preserved in the output; only classification
178
+ // sees the decoded form.
179
+ return masked.replace(URL_PARAMETER, (match, separator, key) => isSensitiveParameterKey(key) ? `${separator}${key}=[REDACTED]` : match);
180
+ }
181
+ /**
182
+ * Schemes the WHATWG parser gives an authority even without `//`, so
183
+ * `https:user:pass@host` carries real userinfo. `file:` is excluded on purpose:
184
+ * it takes no credentials, and treating it as special rewrote `file:u:p@h/x`,
185
+ * which is a local path.
186
+ */
187
+ const SPECIAL_SCHEMES = new Set(['http', 'https', 'ws', 'wss', 'ftp']);
188
+ /**
189
+ * Characters that end an authority: only those the parser itself treats as
190
+ * structural.
191
+ *
192
+ * Nothing else belongs here. `" < > ` { } | ^` were briefly included on the
193
+ * grounds that RFC 3986 forbids them, which is true but irrelevant: the WHATWG
194
+ * parser percent-encodes them inside userinfo rather than rejecting, so
195
+ * `https://user:pa"ss@host` really does carry a password and ending the
196
+ * authority at the quote walked straight past its `@`. Sub-delimiters are out
197
+ * for the same reason. Deciding what is credentialed is left to the parser
198
+ * below; this set only finds candidates.
199
+ */
200
+ const AUTHORITY_TERMINATORS = new Set(['/', '?', '#', ' ', '\t', '\n', '\r']);
201
+ function isSchemeChar(code) {
202
+ const isAlpha = (code >= 97 && code <= 122) || (code >= 65 && code <= 90);
203
+ const isDigit = code >= 48 && code <= 57;
204
+ return isAlpha || isDigit || code === 43 || code === 46 || code === 45; // + . -
205
+ }
206
+ function isAlphaCode(code) {
207
+ return (code >= 97 && code <= 122) || (code >= 65 && code <= 90);
208
+ }
209
+ /**
210
+ * True for a character that can appear in a host.
211
+ *
212
+ * The bracket characters are excluded: they belong to a host only around an
213
+ * IPv6 literal, which `hostEnd` handles separately, and treating a stray `]` as
214
+ * a host character made `[https://u:p@h.t]` ask the parser about the host
215
+ * `h.t]`, which it rejects outright.
216
+ *
217
+ * Anything above ASCII counts, because the parser punycodes internationalized
218
+ * hosts rather than rejecting them. Stopping at the first such character
219
+ * truncated `https://u:p@\u043f\u0440\u0438\u043c\u0435\u0440.example.com`
220
+ * to `https://u:p@`, which does not parse, and the credential stayed visible.
221
+ */
222
+ function isHostChar(char) {
223
+ const code = char.charCodeAt(0);
224
+ if (code > 127)
225
+ return true;
226
+ const isAlpha = (code >= 97 && code <= 122) || (code >= 65 && code <= 90);
227
+ const isDigit = code >= 48 && code <= 57;
228
+ return (isAlpha ||
229
+ isDigit ||
230
+ code === 46 || // .
231
+ code === 95 || // _
232
+ code === 126 || // ~
233
+ code === 37 || // %
234
+ code === 58 || // :
235
+ code === 45 // -
236
+ );
237
+ }
238
+ /**
239
+ * True when `candidate` parses as a URL carrying a username or password, and
240
+ * what it parsed as the host could be one.
241
+ *
242
+ * The parser decides whether userinfo is present, because no character table
243
+ * gets that right: it percent-encodes `"` inside userinfo, so
244
+ * `https://user:pa"ss@host` really does carry a password. But it is equally
245
+ * happy to read `h.test","user":"a` as userinfo and `b"}` as the host when a URL
246
+ * sits inside a JSON error body, so the host it produced has to be believable
247
+ * before the match counts.
248
+ */
249
+ /**
250
+ * How far past the last `@` the adjudicator will look for the end of an
251
+ * authority. No credible URL carries a kilobyte of host and port, and without a
252
+ * bound every candidate is sliced and parsed out to the next structural
253
+ * character, which is where two separate quadratic blowups lived (repeated
254
+ * scheme opens in terminator-free text, and an unclosed IPv6 bracket scanning
255
+ * to end of input). Past the bound the scan fails closed and masks: for a real
256
+ * oversized URL the verdict would have been "mask" anyway, and for oversized
257
+ * junk over-masking is the documented safe direction.
258
+ */
259
+ const MAX_AUTHORITY_SPAN = 1024;
260
+ /** Where the authority starting at `from` ends, bounded by `limit`. */
261
+ function authorityEnd(text, from, limit) {
262
+ let end = from;
263
+ while (end < limit && !AUTHORITY_TERMINATORS.has(text[end]))
264
+ end++;
265
+ return end;
266
+ }
267
+ /** Where the host starting at `from` stops, bounded by `limit`. */
268
+ function hostEnd(text, from, limit) {
269
+ let end = from;
270
+ // An IPv6 literal is the one place brackets belong; take the whole `[...]`.
271
+ if (text[end] === '[') {
272
+ while (end < limit && text[end] !== ']')
273
+ end++;
274
+ if (end < limit)
275
+ end++;
276
+ }
277
+ while (end < limit && isHostChar(text[end]))
278
+ end++;
279
+ return end;
280
+ }
281
+ /**
282
+ * How many single-character steps are offered as extra candidate extents, in
283
+ * each direction, when the table-derived ones fail.
284
+ *
285
+ * Backward from the structural end, for a host made entirely of characters
286
+ * outside the host table with a wrapper after it (`<https://u:p@!>`): the
287
+ * conservative and trimmed extents collapse to nothing and the structural
288
+ * extent swallows the `>`.
289
+ *
290
+ * Forward from the host start, for a host whose opening characters make every
291
+ * longer extent unparseable: `https:/u:p@!>>>https://…` (a one-character host
292
+ * glued to the next URL, where the structural end runs into that URL) and
293
+ * `https:/u:p@xn--e1.ex/x` (a label the parser rejects as invalid punycode, so
294
+ * only a prefix of the host parses). Both leaked until the short extents were
295
+ * offered. The parser still decides; these only propose where to cut.
296
+ */
297
+ const MAX_TRIM_STEPS = 8;
298
+ function hasCredentials(scan, schemeStart, hostStart) {
299
+ const limit = Math.min(scan.length, hostStart + MAX_AUTHORITY_SPAN);
300
+ const structEnd = authorityEnd(scan, hostStart, limit);
301
+ // No structural end within the window: fail closed (see MAX_AUTHORITY_SPAN).
302
+ // The window has to be the thing that stopped the scan — running out of
303
+ // input is a genuine end, not an oversized authority — and a terminator
304
+ // sitting exactly at the window's edge is genuine too; both adjudicate.
305
+ const stoppedByWindow = structEnd === limit && limit === hostStart + MAX_AUTHORITY_SPAN;
306
+ const terminatorAtEdge = limit < scan.length && AUTHORITY_TERMINATORS.has(scan[limit]);
307
+ if (stoppedByWindow && !terminatorAtEdge) {
308
+ return true;
309
+ }
310
+ // Three candidate extents, cheapest first. The conservative host stops at the
311
+ // first character that is definitely not one, which separates
312
+ // `one.t,https://…` into two URLs. The structural end accepts the many host
313
+ // characters the parser allows and a character set keeps getting wrong
314
+ // (`!example`, `%21example`, `,example`). But when both a weird host AND a
315
+ // trailing wrapper are present — `<https://u:p@!host>` — the conservative
316
+ // extent is empty and the structural one swallows the `>` and fails to
317
+ // parse, so a third extent trims trailing non-host characters off the
318
+ // structural end. The table still only finds candidates; the parser decides.
319
+ let trimmedEnd = structEnd;
320
+ while (trimmedEnd > hostStart && !isHostChar(scan[trimmedEnd - 1]))
321
+ trimmedEnd--;
322
+ const ends = [hostEnd(scan, hostStart, structEnd), trimmedEnd, structEnd];
323
+ for (let step = 1; step <= MAX_TRIM_STEPS; step++) {
324
+ ends.push(structEnd - step, Math.min(hostStart + step, structEnd));
325
+ }
326
+ let anyParsed = false;
327
+ for (let i = 0; i < ends.length; i++) {
328
+ const end = ends[i];
329
+ if (end <= hostStart || ends.indexOf(end) !== i)
330
+ continue;
331
+ try {
332
+ const parsed = new URL(scan.slice(schemeStart, end));
333
+ anyParsed = true;
334
+ if (parsed.username || parsed.password)
335
+ return true;
336
+ }
337
+ catch {
338
+ // This extent is not a URL; another may be.
339
+ }
340
+ }
341
+ // Nothing parsed at any extent, so the parser never got to rule on the
342
+ // credential — an unterminated IPv6 host (`https://u:p@[`) rejects every
343
+ // candidate. The text still shows userinfo before an `@` inside an
344
+ // authority this scan opened, and "no verdict" is not "no credential", so
345
+ // this fails closed exactly as an oversized authority does.
346
+ return !anyParsed;
347
+ }
348
+ function parsesWithCredentials(candidate) {
349
+ try {
350
+ const parsed = new URL(candidate);
351
+ return Boolean(parsed.username || parsed.password);
352
+ }
353
+ catch {
354
+ return false;
355
+ }
356
+ }
357
+ /**
358
+ * How many `@` positions the spaced-userinfo look-ahead will offer the parser.
359
+ * A WordPress Application Password contains spaces but no `@`, so one is the
360
+ * realistic count; the bound keeps hostile text from turning each look-ahead
361
+ * into an unbounded run of candidate parses.
362
+ */
363
+ const MAX_LOOKAHEAD_ATS = 8;
364
+ /**
365
+ * A WordPress Application Password is printed as six groups of four
366
+ * alphanumeric characters separated by spaces. Used only to decide whether to
367
+ * ask the parser about extending an *ambiguous* token — one that already
368
+ * parses as a URL on its own — never to decide whether something is a
369
+ * credential. See spacedUserinfoEnd.
370
+ */
371
+ const APP_PASSWORD_GROUP = /^[A-Za-z0-9]{4}$/;
372
+ /**
373
+ * The scan treats a space as the end of a URL, because in free text it almost
374
+ * always is — but the parser percent-encodes spaces inside userinfo, and a
375
+ * WordPress Application Password contains them, so `https://admin:AbCD 1234
376
+ * efGH@host/x` is a credential the plain scan cannot see. When an authority
377
+ * closes at a space with no `@` seen, this decides whether the token continues
378
+ * through the space as userinfo.
379
+ *
380
+ * The discriminator is the parser, not a character rule: the look-ahead runs
381
+ * unconditionally when the closed token alone does NOT parse as a URL.
382
+ * `https://admin:AbCD` does not parse (its "port" is not a number), so the
383
+ * text after the space is offered to the parser as userinfo continuation.
384
+ *
385
+ * When the token DOES parse alone the reading is ambiguous, because
386
+ * `https://admin:1234` (a username and the first chunk of a spaced password)
387
+ * and `https://host.test:8443` (a real host and port) are the same shape to
388
+ * the parser. Declining outright leaked every digit-first spaced password
389
+ * whenever a wrapper kept the whole-value fallback from firing
390
+ * (`[https://u:1234 5678@h/x]`), so the extension is still offered when
391
+ * either signal says the token is not a whole URL:
392
+ *
393
+ * - the parsed "host" carries no dot and is no IP literal, so it is far more
394
+ * likely a username than a public host (`https://admin:1234` → host
395
+ * `admin`), or
396
+ * - every chunk after the space has the Application Password group shape,
397
+ * which covers a dotted username paired with the credential format this CLI
398
+ * actually stores (`https://user.name:1234 5678 abcd@h`).
399
+ *
400
+ * Ordinary prose matches neither: `https://host.test:8443 failed for
401
+ * admin@e.com` has a dotted host and the chunks `failed`, `for`, `admin`. The
402
+ * gate only decides whether to ask; the parser still decides credentials.
403
+ * Residual, documented in REVIEW_DECISIONS.md: a dotted username whose spaced
404
+ * password is neither group-shaped nor digit-free stays unmasked when it is
405
+ * not the whole value. Candidates stop at `/?#`
406
+ * (raw slashes cannot sit in userinfo) and at MAX_AUTHORITY_SPAN. The first
407
+ * credentialed `@` decides — so a bare-host credential followed by prose and
408
+ * an email never swallows the email — and the span then extends through the
409
+ * rest of that whitespace-free run exactly as the main scan's greedy-to-last-@
410
+ * rule would on a second pass, so the output is a fixed point. Residuals
411
+ * accepted and documented in REVIEW_DECISIONS.md: a password whose first
412
+ * chunk is all digits parses as a valid port and is indistinguishable from
413
+ * `host:port`, a spaced password containing `@ ` (at plus space) masks only
414
+ * its first credentialed extent, and a URL with an unparseable port followed
415
+ * by prose and an email over-masks.
416
+ *
417
+ * @returns The scan index of the `@` ending the spaced userinfo, or -1.
418
+ */
419
+ function spacedUserinfoEnd(scan, schemeStart, authorityStart, closePos) {
420
+ // An empty authority (`https:// admin@e.com`) offers nothing to continue.
421
+ if (closePos <= authorityStart)
422
+ return -1;
423
+ // A token that parses alone is ambiguous rather than settled; see above.
424
+ let requireGroupShape = false;
425
+ try {
426
+ const { hostname } = new URL(scan.slice(schemeStart, closePos));
427
+ // A dot or an IP literal means the token's host is believable as a real
428
+ // host, so only a credential-shaped continuation justifies extending it.
429
+ requireGroupShape = hostname.includes('.') || hostname.startsWith('[');
430
+ }
431
+ catch {
432
+ // Not a URL alone — the space may sit inside its userinfo.
433
+ }
434
+ // Inclusive of the position exactly MAX_AUTHORITY_SPAN past the space: an
435
+ // exclusive bound skipped a credentialed `@` sitting precisely there.
436
+ const limit = Math.min(scan.length, closePos + 1 + MAX_AUTHORITY_SPAN);
437
+ let tried = 0;
438
+ for (let i = closePos + 1; i < limit; i++) {
439
+ const char = scan[i];
440
+ if (char === '/' || char === '?' || char === '#')
441
+ break;
442
+ if (char !== '@')
443
+ continue;
444
+ if (++tried > MAX_LOOKAHEAD_ATS)
445
+ break;
446
+ if (requireGroupShape) {
447
+ const chunks = scan.slice(closePos + 1, i).split(' ');
448
+ // Every later `@` spans this text too, so a failure here ends the search.
449
+ if (!chunks.every((chunk) => APP_PASSWORD_GROUP.test(chunk)))
450
+ break;
451
+ }
452
+ if (hasCredentials(scan, schemeStart, i + 1)) {
453
+ // Greedy through the rest of this whitespace-free run: `1234@chunk@host`
454
+ // re-parses as one authority whose userinfo ends at the LAST @, so
455
+ // stopping here would make the second pass mask further than the first.
456
+ //
457
+ // Deliberately bounded by the run, not by the candidate window: a span
458
+ // that stops early is not merely a shorter mask, it is a mask whose
459
+ // replaced range excludes part of the credential the parser read, which
460
+ // both leaks those bytes and breaks idempotency. The run is walked once
461
+ // and the caller resumes past it, so this stays linear.
462
+ let end = i;
463
+ for (let j = i + 1; j < scan.length && !AUTHORITY_TERMINATORS.has(scan[j]); j++) {
464
+ if (scan[j] === '@')
465
+ end = j;
466
+ }
467
+ return end;
468
+ }
469
+ }
470
+ return -1;
471
+ }
472
+ /**
473
+ * Mask userinfo in any URLs embedded within arbitrary text.
474
+ *
475
+ * SECURITY: Error messages (e.g. fetch failures) can echo a full request URL
476
+ * including embedded credentials from a legacy profile.
477
+ *
478
+ * Implemented as a linear scan rather than a pattern, after three regex
479
+ * attempts each missed a case. The scan runs over a copy with tab/CR/LF
480
+ * removed, because the URL parser discards those characters anywhere —
481
+ * including inside `://` — so `https:\n//user:pass@host` is credentialed even
482
+ * though no pattern anchored on a literal `://` can see it. Offsets are mapped
483
+ * back so only the matching span is rewritten and surrounding lines survive.
484
+ *
485
+ * @param text - Text that may contain credentialed URLs
486
+ * @returns The text with each URL's userinfo replaced by `***:***@`. The
487
+ * replacement is uniform on purpose: it re-parses as ordinary userinfo, so
488
+ * masking is idempotent without trusting any marker string that hostile text
489
+ * could also contain.
490
+ */
491
+ export function maskUrlUserinfoInText(text) {
492
+ if (!text.includes('@')) {
493
+ return text;
494
+ }
495
+ // Strip what the parser ignores, keeping a map back to the original offsets.
496
+ // `boundary` marks scan positions that had a stripped character immediately
497
+ // before them: those are where a second reading of a token can start.
498
+ let scan = '';
499
+ const sourceIndex = [];
500
+ const boundary = [];
501
+ let stripped = false;
502
+ for (let index = 0; index < text.length; index++) {
503
+ const char = text[index];
504
+ if (char === '\t' || char === '\n' || char === '\r') {
505
+ stripped = true;
506
+ continue;
507
+ }
508
+ scan += char;
509
+ sourceIndex.push(index);
510
+ boundary.push(stripped);
511
+ stripped = false;
512
+ }
513
+ const spans = [];
514
+ // One forward pass. Authority state is carried in these, so each character is
515
+ // visited once: a per-colon loop with a backward lastIndexOf for the `@` is
516
+ // quadratic when many short authorities sit after a distant `@`.
517
+ //
518
+ // An authority can be open under more than one reading of its scheme.
519
+ // Stripping a newline glues the preceding word to it, and the glued scheme
520
+ // is a different URL to the parser: `PRE\nftp:/u:p@h` reads as scheme
521
+ // `preftp`, which is not special, takes no authority after a single slash,
522
+ // and reports no credentials — while the text plainly shows one. Both
523
+ // readings are kept and the parser adjudicates each; the span comes from
524
+ // whichever reading it confirms.
525
+ let openings = [];
526
+ let authorityStart = -1;
527
+ let lastAt = -1;
528
+ // Most recent scan position preceded by a stripped character.
529
+ let lastBoundary = -1;
530
+ // First alphabetic character of the current token run, tracked forward so a
531
+ // digit-led run still offers the scheme inside it without a backward walk.
532
+ let firstAlpha = -1;
533
+ // Start of the current run of scheme-legal characters, maintained forward so
534
+ // a scheme of any length is recognised in O(1); a bounded backward walk
535
+ // missed schemes longer than its limit, and an unbounded one is quadratic.
536
+ let tokenStart = 0;
537
+ const closeAuthority = () => {
538
+ // `lastAt > authorityStart`, not `>= 0`: an empty userinfo (`https://@host`,
539
+ // or one the parser emptied by dropping control characters) carries no
540
+ // credentials, so masking it would claim one had been there.
541
+ for (const opening of openings) {
542
+ if (lastAt <= opening.authorityStart)
543
+ continue;
544
+ // Ask the parser, not the scan, whether this is a credential. Several
545
+ // candidate extents are offered (see hasCredentials); any verdict is
546
+ // safe, because only the userinfo is rewritten, so the host extent
547
+ // affects the decision, never the output.
548
+ if (!hasCredentials(scan, opening.schemeStart, lastAt + 1))
549
+ continue;
550
+ // Only the userinfo is rewritten. Replacing from the scheme instead let a
551
+ // span whose offsets had shifted swallow the prose in front of it, so
552
+ // `PRE\nhttps://u:p@h` lost `PRE` as well as the credential.
553
+ const start = sourceIndex[opening.authorityStart];
554
+ const stop = sourceIndex[lastAt] + 1;
555
+ // Rewriting in place is complete even when the parser dropped characters
556
+ // inside this userinfo: the original span runs from the first userinfo
557
+ // character through the `@`, so every credential byte — dropped controls
558
+ // included — sits inside [start, stop). A distinct sentinel marker here
559
+ // needed guards to stay idempotent, and those guards keyed on a string
560
+ // hostile text can also contain, which suppressed masking outright.
561
+ // `***:***@` re-parses as ordinary userinfo, so a second pass reproduces
562
+ // it byte for byte with no marker trusted anywhere.
563
+ spans.push({ start, end: stop });
564
+ break;
565
+ }
566
+ openings = [];
567
+ authorityStart = -1;
568
+ lastAt = -1;
569
+ };
570
+ let index = 0;
571
+ while (index < scan.length) {
572
+ const char = scan[index];
573
+ if (boundary[index])
574
+ lastBoundary = index;
575
+ if (firstAlpha < tokenStart && isAlphaCode(scan.charCodeAt(index)))
576
+ firstAlpha = index;
577
+ if (char === ':') {
578
+ // Every reading of this token that could start a URL: as scanned, from a
579
+ // stripped character's boundary inside it (see `openings`), and from a
580
+ // special scheme name it ends with. The last one matters because a
581
+ // special scheme opens an authority after one slash or none, so text
582
+ // running straight into it hides the URL completely: `…/xhttps:/u:p@h`
583
+ // reads as scheme `xhttps`, which takes no authority after one slash.
584
+ // Generic schemes need `//`, which parses as an authority under any
585
+ // prefix, so they need no equivalent.
586
+ const starts = [tokenStart];
587
+ if (lastBoundary > tokenStart && lastBoundary < index)
588
+ starts.push(lastBoundary);
589
+ // A scheme must start with a letter, so a run beginning with a digit or
590
+ // `+.-` is not one under its own start — but the letter inside it can
591
+ // begin a real scheme: `9a1111://u:p@h` hid the URL completely.
592
+ if (firstAlpha > tokenStart && firstAlpha < index)
593
+ starts.push(firstAlpha);
594
+ for (const scheme of SPECIAL_SCHEMES) {
595
+ const start = index - scheme.length;
596
+ if (start <= tokenStart)
597
+ continue;
598
+ if (scan.slice(start, index).toLowerCase() === scheme)
599
+ starts.push(start);
600
+ }
601
+ const opened = [];
602
+ let firstAuthority = -1;
603
+ for (const start of starts) {
604
+ if (start >= index || !isAlphaCode(scan.charCodeAt(start)))
605
+ continue;
606
+ const scheme = scan.slice(start, index).toLowerCase();
607
+ const special = SPECIAL_SCHEMES.has(scheme);
608
+ // A special scheme treats backslashes as slashes; others do not, so
609
+ // `custom:\\u:p@h` is a path and carries no userinfo.
610
+ let after = index + 1;
611
+ while (after < scan.length &&
612
+ (scan[after] === '/' || (special && scan[after] === '\\'))) {
613
+ after++;
614
+ }
615
+ const slashes = after - (index + 1);
616
+ // Special schemes get an authority after any slash run, and after none
617
+ // at all — but only when no authority is already open, or `http:` sitting
618
+ // inside a password would close the URL it belongs to. Other schemes
619
+ // need a real `//`; `custom:/u:p@h` is a path, not an authority.
620
+ const opensAuthority = special ? slashes > 0 || authorityStart < 0 : slashes >= 2;
621
+ if (!opensAuthority)
622
+ continue;
623
+ opened.push({ schemeStart: start, authorityStart: after, special });
624
+ if (firstAuthority < 0 || after < firstAuthority)
625
+ firstAuthority = after;
626
+ }
627
+ if (opened.length > 0) {
628
+ // A new URL begins, so whatever authority was open ends here. This is
629
+ // what keeps `https://safe,https://u:p@h` from swallowing the second.
630
+ closeAuthority();
631
+ openings = opened;
632
+ // Scan state follows the earliest reading, so no `@` inside any
633
+ // reading's authority is missed; each reading keeps its own start.
634
+ authorityStart = firstAuthority;
635
+ index = firstAuthority;
636
+ tokenStart = firstAuthority;
637
+ continue;
638
+ }
639
+ index++;
640
+ tokenStart = index;
641
+ continue;
642
+ }
643
+ // A special scheme's parser treats `\` as `/`, so it ends the authority
644
+ // there. Leaving it out let `lastAt` advance to an `@` in the path, and
645
+ // the span then replaced the real host and part of the path along with
646
+ // the userinfo: `https://u:p@h\path@x` collapsed to `https://***:***@x`.
647
+ // Only for a reading whose authority has actually begun: a backslash still
648
+ // inside another reading's slash run (`PRE\nhttps://\u:p@h`, where the
649
+ // glued scheme takes `//` and the real one takes `//\`) is not a
650
+ // terminator, and closing there dropped the credential entirely.
651
+ const endsAuthority = AUTHORITY_TERMINATORS.has(char) ||
652
+ (char === '\\' &&
653
+ openings.some((opening) => opening.special && opening.authorityStart <= index));
654
+ if (authorityStart >= 0 && endsAuthority) {
655
+ const sawAt = lastAt > authorityStart;
656
+ const openReadings = openings;
657
+ closeAuthority();
658
+ // A space-closed authority with no @ may be a URL whose userinfo
659
+ // contains spaces (a WordPress Application Password). Tab/CR/LF never
660
+ // reach here — they are stripped from the scan — so the space is the
661
+ // only whitespace close that can sit inside userinfo.
662
+ if (!sawAt && char === ' ') {
663
+ let matched = false;
664
+ for (const opening of openReadings) {
665
+ const at = spacedUserinfoEnd(scan, opening.schemeStart, opening.authorityStart, index);
666
+ if (at < 0)
667
+ continue;
668
+ spans.push({ start: sourceIndex[opening.authorityStart], end: sourceIndex[at] + 1 });
669
+ index = at + 1;
670
+ tokenStart = index;
671
+ matched = true;
672
+ break;
673
+ }
674
+ if (matched)
675
+ continue;
676
+ }
677
+ index++;
678
+ tokenStart = index;
679
+ continue;
680
+ }
681
+ if (authorityStart >= 0 && char === '@')
682
+ lastAt = index;
683
+ if (!isSchemeChar(scan.charCodeAt(index)))
684
+ tokenStart = index + 1;
685
+ index++;
686
+ }
687
+ closeAuthority();
688
+ if (spans.length === 0) {
689
+ // Nothing found by token. Before giving up, check whether the whole value
690
+ // is itself one URL: the scan has to treat a space as the end of a URL,
691
+ // because in free text it almost always is, but the parser percent-encodes
692
+ // spaces inside userinfo and a WordPress Application Password contains
693
+ // them. `https://admin:AbCD 1234@host` is a credential the scan cannot see,
694
+ // and a stored dashboardUrl reaching the debug redactor is that shape.
695
+ // Running this only as a fallback keeps multi-URL text with the scan, which
696
+ // masks every URL rather than just the first.
697
+ const trimmed = text.trim();
698
+ if (trimmed && parsesWithCredentials(trimmed)) {
699
+ const at = text.indexOf(trimmed);
700
+ return text.slice(0, at) + maskUrlUserinfo(trimmed) + text.slice(at + trimmed.length);
701
+ }
702
+ return text;
703
+ }
704
+ let output = '';
705
+ let cursor = 0;
706
+ for (const span of spans) {
707
+ // Defensive: never let a span reach back over text already emitted.
708
+ if (span.start < cursor)
709
+ continue;
710
+ output += text.slice(cursor, span.start);
711
+ output += '***:***@';
712
+ cursor = span.end;
713
+ }
714
+ return output + text.slice(cursor);
715
+ }
716
+ /**
717
+ * Mask everything credential-shaped in arbitrary text: embedded userinfo, plus
718
+ * the value of any query or fragment parameter whose key — percent-decoded
719
+ * first — is on the shared sensitive list.
720
+ *
721
+ * SECURITY: this is the free-text counterpart of maskUrlCredentials. A URL
722
+ * reaching a display path inside a longer string carries the same legacy
723
+ * credential forms as a bare one, so both `user:pass@` and `?access_token=`
724
+ * have to be masked wherever the string is emitted.
725
+ *
726
+ * @param text - Text that may contain credentialed URLs
727
+ * @returns The text with userinfo replaced by `***:***@` and sensitive
728
+ * parameter values replaced by `[REDACTED]`, with the original key spelling
729
+ * preserved
730
+ */
731
+ export function maskUrlCredentialsInText(text) {
732
+ const masked = maskUrlUserinfoInText(text);
733
+ // The original key spelling is preserved in the output; only classification
734
+ // sees the decoded form.
735
+ return masked.replace(URL_PARAMETER, (match, separator, key) => isSensitiveParameterKey(key) ? `${separator}${key}=[REDACTED]` : match);
736
+ }
69
737
  //# sourceMappingURL=format.js.map