@opencode/browse 0.0.17-dev.185 → 0.0.17-dev.186

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 (39) hide show
  1. package/dist/{Runtime-xss8qan1.mjs → Runtime-hmy7zww1.mjs} +1 -1
  2. package/dist/{cli-fk82qmwb.mjs → cli-7289awyd.mjs} +39 -222
  3. package/dist/cli.mjs +19 -16
  4. package/dist/{helpers-v2zmfak2.mjs → helpers-21yzw670.mjs} +1 -1
  5. package/dist/{index-gjq7chrk.mjs → index-4tw494gw.mjs} +2 -2
  6. package/dist/{legacy-runtime-rvfsgmzn.mjs → legacy-runtime-ytvtb4p6.mjs} +10 -8
  7. package/dist/{main-m45zegrn.mjs → main-0h387a1q.mjs} +1 -6
  8. package/dist/{main-1b344j42.mjs → main-3ymzbg04.mjs} +30 -47
  9. package/dist/{main-z32979g4.mjs → main-7y134fzj.mjs} +26 -157
  10. package/dist/{main-x7takqns.mjs → main-81fht5nj.mjs} +18 -16
  11. package/dist/{main-6hvv25x8.mjs → main-8xd753k5.mjs} +1 -1
  12. package/dist/{main-qwf4vk41.mjs → main-97vjgp95.mjs} +2 -2
  13. package/dist/{main-xjskgtdr.mjs → main-czz5kqq9.mjs} +2 -2
  14. package/dist/{main-xct4r41x.mjs → main-ghh2tvn1.mjs} +3 -3
  15. package/dist/{main-akpa411k.mjs → main-gmhbkamn.mjs} +118 -2
  16. package/dist/{main-2wrvr3gc.mjs → main-gnfmgnwj.mjs} +15 -18
  17. package/dist/{main-t2jyedkv.mjs → main-hv8t6206.mjs} +8 -6
  18. package/dist/{main-9frwnsnf.mjs → main-j4kq90pw.mjs} +1 -1
  19. package/dist/{main-ndmgt6k5.mjs → main-ns026dfw.mjs} +5 -46
  20. package/dist/{main-jeta10c6.mjs → main-qjr69cgp.mjs} +8 -8
  21. package/dist/{main-sbqypb33.mjs → main-vw7jwd0n.mjs} +2 -2
  22. package/dist/main-wq3rxzcg.mjs +141 -0
  23. package/dist/main-xz6gd1xb.mjs +4 -0
  24. package/dist/main-y3h7b6gd.mjs +17 -0
  25. package/dist/{main-3ewrhbqw.mjs → main-z3txr4wt.mjs} +6 -6
  26. package/dist/{mcp-2xkjfnqz.mjs → mcp-gqnkhtt0.mjs} +121 -230
  27. package/dist/{migrate-fygxtp2g.mjs → migrate-der69rr4.mjs} +14 -7
  28. package/dist/{relay-mbjgxbtr.mjs → relay-32ed2ae2.mjs} +617 -354
  29. package/dist/remove-stored-secrets-58r3xd1b.mjs +6 -0
  30. package/dist/{runtime-update-ngg3m888.mjs → runtime-update-3v5znrk0.mjs} +13 -11
  31. package/dist/{setup-t0pbhmzh.mjs → setup-tzttzgb4.mjs} +25 -47
  32. package/dist/{skill-text-1rg5b5np.mjs → skill-text-0ndr12dz.mjs} +7 -31
  33. package/dist/{supervisor-wrrnbfhw.mjs → supervisor-84gbxv46.mjs} +8 -6
  34. package/dist/{update-heze6vjn.mjs → update-exnjhpqb.mjs} +3 -3
  35. package/dist/{version-x1kkvpqn.mjs → version-h0n5h8j4.mjs} +1 -1
  36. package/package.json +1 -1
  37. package/skills/browse/SKILL.md +7 -31
  38. package/dist/main-6my7bmf1.mjs +0 -1324
  39. package/dist/main-ew8jna3e.mjs +0 -4
@@ -1,1324 +0,0 @@
1
- import {
2
- isNodeError,
3
- writeJsonFileAtomically
4
- } from "./main-ndmgt6k5.mjs";
5
- import {
6
- decodeUnknownEffect2,
7
- decodeUnknownSync,
8
- optionalKey,
9
- Literal,
10
- String3,
11
- Struct,
12
- ArraySchema,
13
- Literals,
14
- makeFilter,
15
- isPattern,
16
- Defect,
17
- TaggedError2
18
- } from "./main-6hvv25x8.mjs";
19
- import {
20
- isString,
21
- isNumber,
22
- isBoolean,
23
- isObject,
24
- withFiber,
25
- getCurrentFiber,
26
- succeed2,
27
- sync,
28
- suspend,
29
- succeedNone,
30
- void_,
31
- callback,
32
- asSome,
33
- flatMap2,
34
- onExitPrimitive,
35
- uninterruptibleMask,
36
- promise,
37
- tryPromise,
38
- succeed6,
39
- callback2,
40
- gen,
41
- fail6,
42
- try_2,
43
- option2,
44
- catchIf,
45
- mapError2,
46
- acquireUseRelease,
47
- fnUntraced,
48
- fn
49
- } from "./main-m45zegrn.mjs";
50
- import {
51
- dataRoot,
52
- cliCommand
53
- } from "./main-z32979g4.mjs";
54
-
55
- // node_modules/effect/dist/Semaphore.js
56
- var makeUnsafe = (permits) => new SemaphoreImpl(permits);
57
- var waitForPermits = (self, n, effect) => callback((resume) => {
58
- if (self.free >= n)
59
- return resume(effect);
60
- const observer = () => {
61
- if (self.free < n)
62
- return;
63
- self.waiters.delete(observer);
64
- resume(effect);
65
- };
66
- self.waiters.add(observer);
67
- return sync(() => {
68
- self.waiters.delete(observer);
69
- });
70
- });
71
-
72
- class SemaphoreImpl {
73
- waiters = /* @__PURE__ */ new Set;
74
- taken = 0;
75
- permits;
76
- constructor(permits) {
77
- this.permits = permits;
78
- }
79
- get free() {
80
- return this.permits - this.taken;
81
- }
82
- take(n) {
83
- const take = suspend(() => {
84
- if (this.free < n) {
85
- return waitForPermits(this, n, take);
86
- }
87
- this.taken += n;
88
- return succeed2(n);
89
- });
90
- return take;
91
- }
92
- takeIfAvailable(n) {
93
- return suspend(() => {
94
- if (this.free < n)
95
- return succeed2(false);
96
- this.taken += n;
97
- return succeed2(true);
98
- });
99
- }
100
- releaseUnsafe(fiber, n) {
101
- this.taken -= n;
102
- if (this.waiters.size > 0) {
103
- fiber.currentDispatcher.scheduleTask(() => {
104
- for (const observer of this.waiters) {
105
- if (this.free <= 0)
106
- break;
107
- observer();
108
- }
109
- }, 0);
110
- }
111
- return this.free;
112
- }
113
- resize(permits) {
114
- return withFiber((fiber) => {
115
- this.permits = permits;
116
- if (this.free < 0)
117
- return void_;
118
- this.releaseUnsafe(fiber, 0);
119
- return void_;
120
- });
121
- }
122
- release(n) {
123
- return withFiber((fiber) => succeed2(this.releaseUnsafe(fiber, n)));
124
- }
125
- get releaseAll() {
126
- return withFiber((fiber) => succeed2(this.releaseUnsafe(fiber, this.taken)));
127
- }
128
- withPermits(n) {
129
- return (self) => uninterruptibleMask((restore) => {
130
- const acquire = suspend(() => {
131
- if (this.free < n) {
132
- const wait = waitForPermits(this, n, void_);
133
- return flatMap2(restore(wait), () => acquire);
134
- }
135
- this.taken += n;
136
- return onExitPrimitive(restore(self), () => {
137
- this.releaseUnsafe(getCurrentFiber(), n);
138
- return;
139
- }, true);
140
- });
141
- return acquire;
142
- });
143
- }
144
- withPermit = /* @__PURE__ */ this.withPermits(1);
145
- withPermitsIfAvailable(n) {
146
- return (self) => uninterruptibleMask((restore) => {
147
- if (this.free < n)
148
- return succeedNone;
149
- this.taken += n;
150
- return onExitPrimitive(restore(asSome(self)), () => {
151
- this.releaseUnsafe(getCurrentFiber(), n);
152
- return;
153
- }, true);
154
- });
155
- }
156
- }
157
- var make3 = (permits) => sync(() => new SemaphoreImpl(permits));
158
-
159
- // src/auth/site-secrets.ts
160
- import crypto from "node:crypto";
161
- import fs2 from "node:fs/promises";
162
- import path2 from "node:path";
163
-
164
- // src/auth/profile.ts
165
- import { spawn } from "node:child_process";
166
- import fs from "node:fs/promises";
167
- import path from "node:path";
168
-
169
- // src/update/child-process.ts
170
- async function terminateChildProcess(options) {
171
- const isExited = options.isExited ?? (() => options.child.exitCode !== null || options.child.signalCode !== null);
172
- if (isExited())
173
- return;
174
- signalChildProcess(options.child, "SIGTERM");
175
- let timeout;
176
- await Promise.race([
177
- options.exit,
178
- new Promise((resolve) => {
179
- timeout = setTimeout(resolve, options.graceMs);
180
- })
181
- ]);
182
- if (timeout)
183
- clearTimeout(timeout);
184
- if (isExited())
185
- return;
186
- signalChildProcess(options.child, "SIGKILL");
187
- await options.exit;
188
- }
189
- function signalChildProcess(child, signal) {
190
- if (process.platform !== "win32" && child.pid !== undefined) {
191
- try {
192
- process.kill(-child.pid, signal);
193
- return;
194
- } catch {}
195
- }
196
- child.kill(signal);
197
- }
198
-
199
- // src/network-capture/redaction.ts
200
- var secretNamePattern = /auth(?:orization)?|cookie|credential|csrf|xsrf|token|secret|session|password|passwd|pwd|passcode|otp|(?:^|[-_.])code(?:$|[-_.])|(?:api|access|refresh)[-_.]?key|signature|(?:^|[-_.])sig(?:$|[-_.])/i;
201
- var oneTimeFieldPattern = /pass(?:word|wd|code|phrase)|(?:^|[-_.])pwd(?:$|[-_.])|otp|totp|(?:^|[-_.])(?:mfa_?|2fa_?|verification_?|auth_?)?code(?:$|[-_.])|(?:^|[-_.])pin(?:$|[-_.])/i;
202
- var referencePattern = String.raw`BC_(?:SECRET|REDACTED)_\d+`;
203
- var minimumKnownSubstringLength = 8;
204
- var secretHeaders = new Set([
205
- "authorization",
206
- "proxy-authorization",
207
- "x-api-key",
208
- "api-key",
209
- "x-csrf-token",
210
- "csrf-token",
211
- "x-xsrf-token"
212
- ]);
213
- var nonSecretHeaders = new Set([
214
- ":authority",
215
- ":method",
216
- ":scheme",
217
- ":status",
218
- ":protocol",
219
- "access-control-allow-credentials",
220
- "access-control-allow-origin",
221
- "access-control-allow-methods",
222
- "access-control-allow-headers",
223
- "access-control-expose-headers",
224
- "access-control-max-age",
225
- "access-control-request-method",
226
- "access-control-request-headers",
227
- "access-control-allow-private-network",
228
- "access-control-request-private-network"
229
- ]);
230
-
231
- class SecretCollector {
232
- slotsByRef = new Map;
233
- refsByValue = new Map;
234
- refsBySource = new Map;
235
- retiredRefsByValue = new Map;
236
- redactedRefsByValue = new Map;
237
- alwaysRedacted = new Set;
238
- nextRedactedRef = 1;
239
- nextRef = 1;
240
- updated = new Set;
241
- observed = new Set;
242
- constructor(existing = []) {
243
- for (const slot of existing) {
244
- const copy = {
245
- ref: slot.ref,
246
- value: slot.value,
247
- sources: [...slot.sources],
248
- ...slot.expiresAt ? { expiresAt: slot.expiresAt } : {}
249
- };
250
- this.slotsByRef.set(copy.ref, copy);
251
- this.refsByValue.set(copy.value, copy.ref);
252
- this.alwaysRedacted.add(copy.value);
253
- for (const source of copy.sources) {
254
- this.refsBySource.set(source, copy.ref);
255
- }
256
- const number = /^BC_SECRET_(\d+)$/.exec(copy.ref)?.[1];
257
- if (number)
258
- this.nextRef = Math.max(this.nextRef, Number(number) + 1);
259
- }
260
- }
261
- protectHeaders(headers, location, requestScope = "") {
262
- const occurrences = new Map;
263
- return headers.map(({ name, value }) => {
264
- const lowerName = name.toLowerCase();
265
- const occurrence = occurrences.get(lowerName) ?? 0;
266
- occurrences.set(lowerName, occurrence + 1);
267
- return {
268
- name,
269
- value: this.protectHeader(name, value, sourceName(requestScope, `${location}.header.${lowerName}`, occurrence), requestScope)
270
- };
271
- });
272
- }
273
- protectUrl(rawUrl, requestScope = "") {
274
- const fragmentStart = rawUrl.indexOf("#");
275
- const base = fragmentStart < 0 ? rawUrl : rawUrl.slice(0, fragmentStart);
276
- const protectQuery = (name, value, occurrence) => this.reference(value, sourceName(requestScope, `query.${name}`, occurrence));
277
- const protectPath = (pathname) => protectPathSegments(pathname, (segment) => this.redactionReference(segment));
278
- let protectedUrl;
279
- try {
280
- const url = new URL(base);
281
- url.pathname = protectPath(url.pathname);
282
- url.search = protectSearchParams(url.searchParams, protectQuery).toString();
283
- protectedUrl = restoreReferencePlaceholders(url.toString());
284
- } catch {
285
- protectedUrl = protectRelativeUrl(base, protectQuery, protectPath);
286
- }
287
- if (fragmentStart < 0)
288
- return protectedUrl;
289
- const fragment = protectFragment(rawUrl.slice(fragmentStart + 1), (name, value, occurrence) => this.reference(value, sourceName(requestScope, `fragment.${name}`, occurrence)));
290
- return `${protectedUrl}#${fragment}`;
291
- }
292
- protectBody(body, contentType, location, requestScope = "") {
293
- const type = contentType?.toLowerCase() ?? "";
294
- if (type.includes("json")) {
295
- try {
296
- return JSON.stringify(this.protectJson(JSON.parse(body), sourceName(requestScope, location), location));
297
- } catch {
298
- return;
299
- }
300
- }
301
- if (type.includes("application/x-www-form-urlencoded")) {
302
- const protectedParams = protectSearchParams(new URLSearchParams(body), (name, value, occurrence) => this.reference(value, sourceName(requestScope, `${location}.form.${name}`, occurrence)));
303
- return restoreReferencePlaceholders(protectedParams.toString());
304
- }
305
- if (type.includes("multipart/form-data")) {
306
- return this.protectMultipart(body, contentType ?? "", location, requestScope);
307
- }
308
- return;
309
- }
310
- slots() {
311
- return Array.from(this.slotsByRef.values()).sort((left, right) => left.ref.localeCompare(right.ref, undefined, { numeric: true })).map((slot) => ({ ...slot, sources: [...slot.sources] }));
312
- }
313
- updatedRefs() {
314
- return Array.from(this.updated).sort();
315
- }
316
- observedRefs() {
317
- return Array.from(this.observed).sort();
318
- }
319
- redactText(text) {
320
- return redactOutputText(text, this.redactionSlots(), this.alwaysRedacted);
321
- }
322
- redactValue(value) {
323
- return redactOutputValue(value, this.redactionSlots(), this.alwaysRedacted);
324
- }
325
- redactExactValue(value, minimumLength) {
326
- if (!isString(value) && !isNumber(value) && !isBoolean(value))
327
- return value;
328
- const serialized = String(value);
329
- if (serialized.length < minimumLength)
330
- return value;
331
- const ref = this.refsByValue.get(serialized) ?? this.retiredRefsByValue.get(serialized) ?? this.redactedRefsByValue.get(serialized);
332
- return ref ? `\${${ref}}` : value;
333
- }
334
- redactKnownSubstrings(text, minimumLength) {
335
- const slots = this.redactionSlots().filter((slot) => slot.value.length >= minimumLength);
336
- const encoded = slots.flatMap((slot) => {
337
- const variant = encodeURIComponent(slot.value);
338
- return variant === slot.value ? [] : [{ ref: slot.ref, value: variant }];
339
- });
340
- return redactKnownValues(text, [...slots, ...encoded]);
341
- }
342
- redactionSlots() {
343
- return [
344
- ...this.slotsByRef.values(),
345
- ...Array.from(this.retiredRefsByValue, ([value, ref]) => ({ ref, value })),
346
- ...Array.from(this.redactedRefsByValue, ([value, ref]) => ({ ref, value }))
347
- ];
348
- }
349
- addRedactionOnly(value) {
350
- if (value) {
351
- this.alwaysRedacted.add(value);
352
- this.redactionReference(value);
353
- }
354
- }
355
- redactValuesEverywhere(text, values) {
356
- const slots = [];
357
- for (const value of values) {
358
- if (!value)
359
- continue;
360
- const ref = /^\$\{(.+)\}$/.exec(this.redactionReference(value))?.[1] ?? "BC_REDACTED_0";
361
- for (const variant of new Set([value, encodeURIComponent(value), new URLSearchParams({ v: value }).toString().slice(2)])) {
362
- slots.push({ ref, value: variant });
363
- }
364
- }
365
- return redactKnownValues(text, slots);
366
- }
367
- redactionReference(value) {
368
- const persisted = this.refsByValue.get(value);
369
- if (persisted) {
370
- this.observed.add(persisted);
371
- return `\${${persisted}}`;
372
- }
373
- let ref = this.redactedRefsByValue.get(value);
374
- if (!ref) {
375
- ref = `BC_REDACTED_${this.nextRedactedRef++}`;
376
- this.redactedRefsByValue.set(value, ref);
377
- }
378
- return `\${${ref}}`;
379
- }
380
- protectHeader(name, value, source, requestScope = "") {
381
- if (!value)
382
- return value;
383
- const lower = name.toLowerCase();
384
- if (lower === ":path")
385
- return this.protectUrl(value, requestScope);
386
- if (nonSecretHeaders.has(lower))
387
- return value;
388
- if (lower === "cookie" || lower === "set-cookie") {
389
- const cookieOccurrences = new Map;
390
- const protectLine = (line) => line.split(/;\s*/).map((part, index) => {
391
- const separator = part.indexOf("=");
392
- if (separator < 1)
393
- return part;
394
- const cookieName = part.slice(0, separator).trim();
395
- const cookieValue = part.slice(separator + 1);
396
- if (lower === "set-cookie" && index > 0 && /^(domain|path|expires|max-age|samesite|priority|partitioned|secure|httponly)$/i.test(cookieName)) {
397
- return part;
398
- }
399
- if (!cookieValue)
400
- return part;
401
- const occurrence = cookieOccurrences.get(cookieName) ?? 0;
402
- cookieOccurrences.set(cookieName, occurrence + 1);
403
- return `${cookieName}=${this.reference(cookieValue, sourceName("", `${source}.${cookieName}`, occurrence))}`;
404
- }).join("; ");
405
- return lower === "set-cookie" ? value.split(`
406
- `).map(protectLine).join(`
407
- `) : protectLine(value);
408
- }
409
- if (lower === "location" || lower === "referer" || lower === "referrer") {
410
- return this.protectUrl(value, `${source}.url`);
411
- }
412
- if (lower === "authorization" || lower === "proxy-authorization") {
413
- const match = /^(\S+)\s+(.+)$/.exec(value);
414
- if (match)
415
- return `${match[1]} ${this.reference(match[2] ?? "", source)}`;
416
- }
417
- if (secretHeaders.has(lower) || secretNamePattern.test(lower)) {
418
- return this.reference(value, source);
419
- }
420
- return value;
421
- }
422
- protectJson(value, location, role, path = [], field = "open") {
423
- if (Array.isArray(value)) {
424
- if (field === "codeListing") {
425
- return value.map((item, index) => isString(item) ? item : this.protectJson(item, location, role, [...path, String(index)], "secret"));
426
- }
427
- return value.map((item, index) => this.protectJson(item, location, role, [...path, String(index)], field));
428
- }
429
- if (isObject(value)) {
430
- const inherited = field === "codeListing" || field === "codeVoice" ? "secret" : field;
431
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [
432
- key,
433
- this.protectJson(item, location, role, [...path, key], jsonField(key, inherited, role, value.type, item))
434
- ]));
435
- }
436
- if (field === "open" || value === null || value === "")
437
- return value;
438
- if (field === "codeVoice" && isString(value))
439
- return value;
440
- return this.reference(String(value), `${location}.json.${path.join(".")}`);
441
- }
442
- protectMultipart(body, contentType, location, requestScope) {
443
- const boundary = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType)?.slice(1).find(Boolean);
444
- if (!boundary)
445
- return;
446
- const delimiter = `--${boundary}`;
447
- const parts = body.split(delimiter);
448
- if (parts.length < 3)
449
- return;
450
- const occurrences = new Map;
451
- for (let index = 1;index < parts.length - 1; index += 1) {
452
- const part = parts[index];
453
- if (!part?.startsWith(`\r
454
- `))
455
- return;
456
- const headerEnd = part.indexOf(`\r
457
- \r
458
- `);
459
- if (headerEnd < 0 || !part.endsWith(`\r
460
- `))
461
- return;
462
- const headers = part.slice(2, headerEnd);
463
- const disposition = headers.split(`\r
464
- `).find((line) => /^content-disposition:/i.test(line));
465
- if (!disposition || /;\s*filename\*?=/i.test(disposition))
466
- return;
467
- const name = /;\s*name="([^"]+)"/i.exec(disposition)?.[1];
468
- if (!name)
469
- return;
470
- const valueStart = headerEnd + 4;
471
- const valueEnd = part.length - 2;
472
- const value = part.slice(valueStart, valueEnd);
473
- if (!value || !secretNamePattern.test(name))
474
- continue;
475
- const occurrence = occurrences.get(name) ?? 0;
476
- occurrences.set(name, occurrence + 1);
477
- const reference = this.reference(value, sourceName(requestScope, `${location}.multipart.${name}`, occurrence));
478
- parts[index] = `${part.slice(0, valueStart)}${reference}${part.slice(valueEnd)}`;
479
- }
480
- return parts.join(delimiter);
481
- }
482
- reference(value, source) {
483
- if (oneTimeFieldPattern.test(sourceFieldName(source))) {
484
- this.alwaysRedacted.add(value);
485
- return this.redactionReference(value);
486
- }
487
- const sourceRef = this.refsBySource.get(source);
488
- if (sourceRef) {
489
- const slot = this.slotsByRef.get(sourceRef);
490
- if (slot) {
491
- if (slot.value === value) {
492
- this.observed.add(sourceRef);
493
- return `\${${sourceRef}}`;
494
- }
495
- if (slot.sources.length === 1) {
496
- this.retiredRefsByValue.set(slot.value, slot.ref);
497
- if (this.refsByValue.get(slot.value) === sourceRef)
498
- this.refsByValue.delete(slot.value);
499
- slot.value = value;
500
- const expiresAt = jwtExpiration(value);
501
- if (expiresAt)
502
- slot.expiresAt = expiresAt;
503
- else
504
- delete slot.expiresAt;
505
- this.refsByValue.set(value, sourceRef);
506
- this.updated.add(sourceRef);
507
- this.observed.add(sourceRef);
508
- return `\${${sourceRef}}`;
509
- }
510
- const sourceIndex = slot.sources.indexOf(source);
511
- if (sourceIndex >= 0)
512
- slot.sources.splice(sourceIndex, 1);
513
- const replacementRef = this.refsByValue.get(value);
514
- if (replacementRef) {
515
- this.refsBySource.set(source, replacementRef);
516
- this.addSource(replacementRef, source);
517
- this.updated.add(replacementRef);
518
- this.observed.add(replacementRef);
519
- return `\${${replacementRef}}`;
520
- }
521
- }
522
- }
523
- const valueRef = this.refsByValue.get(value);
524
- if (valueRef) {
525
- this.observed.add(valueRef);
526
- this.addSource(valueRef, source);
527
- return `\${${valueRef}}`;
528
- }
529
- const ref = `BC_SECRET_${this.nextRef++}`;
530
- const expiresAt = jwtExpiration(value);
531
- this.slotsByRef.set(ref, { ref, value, sources: [source], ...expiresAt ? { expiresAt } : {} });
532
- this.refsByValue.set(value, ref);
533
- this.refsBySource.set(source, ref);
534
- this.updated.add(ref);
535
- this.observed.add(ref);
536
- return `\${${ref}}`;
537
- }
538
- addSource(ref, source) {
539
- const slot = this.slotsByRef.get(ref);
540
- if (!slot || slot.sources.includes(source))
541
- return;
542
- slot.sources.push(source);
543
- this.refsBySource.set(source, ref);
544
- }
545
- }
546
- function restoreReferencePlaceholders(value) {
547
- return value.replace(/(?:%24|\$)%7B(BC_(?:SECRET|REDACTED)_\d+)%7D/gi, (_match, ref) => `\${${ref}}`);
548
- }
549
- function sourceFieldName(source) {
550
- const segments = source.split(".");
551
- for (let index = segments.length - 1;index >= 0; index -= 1) {
552
- const segment = segments[index] ?? "";
553
- if (!/^\d+$/.test(segment))
554
- return segment;
555
- }
556
- return "";
557
- }
558
- var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
559
- function jsonField(key, inherited, role, type, value) {
560
- if (inherited === "secret")
561
- return "secret";
562
- if (!secretNamePattern.test(key))
563
- return inherited;
564
- if (key !== "code" || role !== "response")
565
- return "secret";
566
- if (type === "codeListing" && Array.isArray(value))
567
- return "codeListing";
568
- if (type === "codeVoice" && isString(value))
569
- return "codeVoice";
570
- return "secret";
571
- }
572
- function looksLikeTokenSegment(segment) {
573
- if (segment.length < 24 || uuidPattern.test(segment) || segment.includes("${"))
574
- return false;
575
- if (/^eyJ[\w-]+\.[\w-]+\.[\w-]*$/.test(segment))
576
- return true;
577
- if (/^[0-9a-f]{32,}$/i.test(segment))
578
- return true;
579
- if (!/^[A-Za-z0-9_~+/-]+={0,2}$/.test(segment))
580
- return false;
581
- if (/^[a-z]+(?:[-_][a-z]+)+$/i.test(segment))
582
- return false;
583
- const hasDigit = /\d/.test(segment);
584
- const hasLower = /[a-z]/.test(segment);
585
- const hasUpper = /[A-Z]/.test(segment);
586
- return new Set(segment).size >= 12 && hasDigit && (hasLower || hasUpper) && (hasLower && hasUpper || segment.length >= 32);
587
- }
588
- function protectPathSegments(pathname, protect) {
589
- return pathname.split("/").map((segment) => {
590
- let decoded;
591
- try {
592
- decoded = decodeURIComponent(segment);
593
- } catch {
594
- decoded = segment;
595
- }
596
- return looksLikeTokenSegment(decoded) ? protect(decoded) : segment;
597
- }).join("/");
598
- }
599
- function protectRelativeUrl(rawUrl, protect, protectPath) {
600
- const queryStart = rawUrl.indexOf("?");
601
- if (queryStart < 0)
602
- return protectPath(rawUrl);
603
- const protectedQuery = protectSearchParams(new URLSearchParams(rawUrl.slice(queryStart + 1)), protect).toString();
604
- return restoreReferencePlaceholders(`${protectPath(rawUrl.slice(0, queryStart))}?${protectedQuery}`);
605
- }
606
- function protectSearchParams(params, protect) {
607
- const result = new URLSearchParams;
608
- const occurrences = new Map;
609
- for (const [name, value] of params) {
610
- const occurrence = occurrences.get(name) ?? 0;
611
- occurrences.set(name, occurrence + 1);
612
- result.append(name, value && secretNamePattern.test(name) ? protect(name, value, occurrence) : value);
613
- }
614
- return result;
615
- }
616
- function protectFragment(fragment, protect) {
617
- const occurrences = new Map;
618
- return fragment.split("&").map((part) => {
619
- const separator = part.indexOf("=");
620
- if (separator < 1)
621
- return part;
622
- const entry = new URLSearchParams(part).entries().next().value;
623
- if (!entry)
624
- return part;
625
- const [name, value] = entry;
626
- if (!/^[\w.-]+$/.test(name) || !secretNamePattern.test(name))
627
- return part;
628
- const occurrence = occurrences.get(name) ?? 0;
629
- occurrences.set(name, occurrence + 1);
630
- return value ? `${part.slice(0, separator + 1)}${protect(name, value, occurrence)}` : part;
631
- }).join("&");
632
- }
633
- function sourceName(requestScope, location, occurrence = 0) {
634
- const base = requestScope ? `${requestScope}.${location}` : location;
635
- return occurrence === 0 ? base : `${base}.${occurrence}`;
636
- }
637
- function redactKnownValues(text, slots) {
638
- return [...slots].sort((left, right) => right.value.length - left.value.length).reduce((output, slot) => replaceOutsideReferences(output, slot.value, `\${${slot.ref}}`), text);
639
- }
640
- function redactOutputText(text, slots, alwaysRedacted) {
641
- return outputStringRedactor(slots, alwaysRedacted)(text);
642
- }
643
- function redactOutputValue(value, slots, alwaysRedacted) {
644
- return redactValueWith(value, slots, outputStringRedactor(slots, alwaysRedacted));
645
- }
646
- function outputStringRedactor(slots, alwaysRedacted) {
647
- const exact = new Map;
648
- for (const slot of slots) {
649
- if (slot.value && !exact.has(slot.value))
650
- exact.set(slot.value, slot);
651
- }
652
- const referenceText = new RegExp(String.raw`^\$\{${referencePattern}\}$`);
653
- const substringSlots = slots.filter((slot) => slot.value.length >= minimumKnownSubstringLength || alwaysRedacted.has(slot.value));
654
- return (text) => {
655
- const match = text && !referenceText.test(text) ? exact.get(text) : undefined;
656
- return match ? `\${${match.ref}}` : redactKnownValues(text, substringSlots);
657
- };
658
- }
659
- function redactValueWith(value, slots, redactString) {
660
- if (isString(value))
661
- return redactString(value);
662
- if (isNumber(value) || isBoolean(value)) {
663
- const slot = slots.find((candidate) => candidate.value === String(value));
664
- return slot ? `\${${slot.ref}}` : value;
665
- }
666
- if (Array.isArray(value))
667
- return value.map((item) => redactValueWith(item, slots, redactString));
668
- if (!isObject(value))
669
- return value;
670
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [
671
- key,
672
- secretNamePattern.test(key) ? redactSecretValue(item) : redactValueWith(item, slots, redactString)
673
- ]));
674
- }
675
- function redactSecretValue(value) {
676
- if (Array.isArray(value))
677
- return value.map(redactSecretValue);
678
- if (isObject(value)) {
679
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactSecretValue(item)]));
680
- }
681
- return value === null || value === "" ? value : "[REDACTED]";
682
- }
683
- function replaceOutsideReferences(text, value, replacement) {
684
- if (!value)
685
- return text;
686
- const references = new RegExp(String.raw`\$\{${referencePattern}\}`, "g");
687
- let output = "";
688
- let offset = 0;
689
- for (const match of text.matchAll(references)) {
690
- const index = match.index ?? 0;
691
- output += text.slice(offset, index).split(value).join(replacement);
692
- output += match[0];
693
- offset = index + match[0].length;
694
- }
695
- return output + text.slice(offset).split(value).join(replacement);
696
- }
697
- function jwtExpiration(value) {
698
- const parts = value.split(".");
699
- if (parts.length !== 3 || !parts[1])
700
- return;
701
- try {
702
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
703
- return isNumber(payload.exp) ? new Date(payload.exp * 1000).toISOString() : undefined;
704
- } catch {
705
- return;
706
- }
707
- }
708
-
709
- // src/auth/profile.ts
710
- var StoredCredentialSlot = Struct({
711
- ref: String3.check(isPattern(/^BC_SECRET_[1-9][0-9]*$/)),
712
- value: String3,
713
- sources: ArraySchema(String3),
714
- expiresAt: optionalKey(String3)
715
- });
716
- var StoredAuthProfile = Struct({
717
- version: Literal(1),
718
- name: String3,
719
- createdAt: String3,
720
- updatedAt: String3,
721
- slots: ArraySchema(StoredCredentialSlot)
722
- }).check(makeFilter((profile) => {
723
- const refs = profile.slots.map((slot) => slot.ref);
724
- if (new Set(refs).size !== refs.length)
725
- return "Auth profile refs must be unique";
726
- const sources = profile.slots.flatMap((slot) => slot.sources);
727
- return new Set(sources).size === sources.length ? undefined : "Auth profile sources must be unique";
728
- }));
729
-
730
- class AuthProfileError extends TaggedError2()("AuthProfile.Error", {
731
- message: String3,
732
- operation: String3,
733
- reason: Literals(["invalid-name", "not-found", "read-failed", "invalid-json", "invalid-profile", "write-failed", "run-failed"]),
734
- cause: optionalKey(Defect())
735
- }) {
736
- }
737
- var defaultBaseDir = () => path.join(dataRoot(), "secrets");
738
- var writeLock = makeUnsafe(1);
739
- var profileLockTimeoutMs = 30000;
740
- var staleProfileLockMs = 60000;
741
- var maximumRunOutputBytes = 1e7;
742
- var maximumTimeoutMs = 2147483647;
743
- var read = fn("AuthProfile.read")(function* (name, options = {}) {
744
- const filePath = yield* profilePath(options.baseDir ?? defaultBaseDir(), name);
745
- const text = yield* tryPromise({
746
- try: () => fs.readFile(filePath, "utf8"),
747
- catch: (cause) => isNodeError(cause) && cause.code === "ENOENT" ? new AuthProfileError({ message: `Auth profile not found: ${name}`, operation: "read", reason: "not-found", cause }) : new AuthProfileError({ message: `Could not read auth profile: ${name}`, operation: "read", reason: "read-failed", cause })
748
- });
749
- return yield* decodeUnknownEffect2(StoredAuthProfile)(yield* try_2({
750
- try: () => JSON.parse(text),
751
- catch: (cause) => new AuthProfileError({ message: `Auth profile is not valid JSON: ${name}`, operation: "read", reason: "invalid-json", cause })
752
- })).pipe(mapError2((cause) => cause instanceof AuthProfileError ? cause : new AuthProfileError({ message: `Auth profile has an invalid shape: ${name}`, operation: "read", reason: "invalid-profile", cause })));
753
- });
754
- var readOptional = fn("AuthProfile.readOptional")(function* (name, options = {}) {
755
- return yield* read(name, options).pipe(catchIf((error) => error.reason === "not-found", () => succeed6(undefined)));
756
- });
757
- function withLock(name, options, effect) {
758
- const baseDir = options.baseDir ?? defaultBaseDir();
759
- const acquire = gen(function* () {
760
- const filePath = yield* profilePath(baseDir, name);
761
- const lockPath = `${filePath}.lock`;
762
- yield* tryPromise({
763
- try: async () => {
764
- await fs.mkdir(baseDir, { recursive: true, mode: 448 });
765
- await fs.chmod(baseDir, 448);
766
- const deadline = Date.now() + profileLockTimeoutMs;
767
- while (true) {
768
- try {
769
- const handle = await fs.open(lockPath, "wx", 384);
770
- let written = false;
771
- try {
772
- await handle.writeFile(`${process.pid}
773
- `);
774
- written = true;
775
- } finally {
776
- await handle.close();
777
- if (!written)
778
- await fs.unlink(lockPath).catch(() => {});
779
- }
780
- return;
781
- } catch (cause) {
782
- if (!isNodeError(cause) || cause.code !== "EEXIST")
783
- throw cause;
784
- const stat = await fs.stat(lockPath).catch(() => {
785
- return;
786
- });
787
- if (stat && Date.now() - stat.mtimeMs > staleProfileLockMs) {
788
- await fs.unlink(lockPath).catch(() => {});
789
- continue;
790
- }
791
- if (Date.now() >= deadline)
792
- throw new Error(`Timed out waiting for auth profile lock: ${name}`);
793
- await new Promise((resolve) => setTimeout(resolve, 25));
794
- }
795
- }
796
- },
797
- catch: (cause) => new AuthProfileError({ message: `Could not lock auth profile: ${name}`, operation: "lock", reason: "write-failed", cause })
798
- });
799
- return lockPath;
800
- });
801
- return acquireUseRelease(acquire, () => effect, (lockPath) => tryPromise({
802
- try: () => fs.unlink(lockPath).catch(() => {}).then(() => {}),
803
- catch: (cause) => new AuthProfileError({ message: `Could not release auth profile lock: ${name}`, operation: "lock", reason: "write-failed", cause })
804
- }));
805
- }
806
- var writeProfile = fnUntraced(function* (options) {
807
- const baseDir = options.baseDir ?? defaultBaseDir();
808
- const filePath = yield* profilePath(baseDir, options.name);
809
- const existing = yield* readOptional(options.name, { baseDir });
810
- const now = new Date().toISOString();
811
- const profile = {
812
- version: 1,
813
- name: options.name,
814
- createdAt: existing?.createdAt ?? now,
815
- updatedAt: now,
816
- slots: options.slots.map((slot) => ({
817
- ref: slot.ref,
818
- value: slot.value,
819
- sources: [...slot.sources],
820
- ...slot.expiresAt ? { expiresAt: slot.expiresAt } : {}
821
- }))
822
- };
823
- yield* decodeUnknownEffect2(StoredAuthProfile)(profile).pipe(mapError2((cause) => new AuthProfileError({ message: `Auth profile has an invalid shape: ${options.name}`, operation: "write", reason: "invalid-profile", cause })));
824
- if (existing && sameSlots(existing.slots, profile.slots))
825
- return summary(existing);
826
- yield* tryPromise({
827
- try: () => writeJsonFileAtomically(filePath, profile, { dirMode: 448 }),
828
- catch: (cause) => new AuthProfileError({ message: `Could not write auth profile: ${options.name}`, operation: "write", reason: "write-failed", cause })
829
- });
830
- return summary(profile);
831
- });
832
- var write = fn("AuthProfile.write")(function* (options) {
833
- return yield* writeLock.withPermit(writeProfile(options));
834
- });
835
- var status = fn("AuthProfile.status")(function* (name, options = {}) {
836
- return summary(yield* read(name, options));
837
- });
838
- var run = fn("AuthProfile.run")(function* (options) {
839
- if (!options.command.trim()) {
840
- return yield* new AuthProfileError({ message: "Auth command must not be empty", operation: "run", reason: "run-failed" });
841
- }
842
- const timeoutMs = options.timeoutMs ?? 120000;
843
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > maximumTimeoutMs) {
844
- return yield* new AuthProfileError({ message: `Auth command timeout must be an integer between 1 and ${maximumTimeoutMs} milliseconds`, operation: "run", reason: "run-failed" });
845
- }
846
- const maxOutputBytes = options.maxOutputBytes ?? 1e6;
847
- if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0 || maxOutputBytes > maximumRunOutputBytes) {
848
- return yield* new AuthProfileError({ message: `Auth command output limit must be an integer between 0 and ${maximumRunOutputBytes} bytes`, operation: "run", reason: "run-failed" });
849
- }
850
- const profile = yield* read(options.name, { ...options.baseDir ? { baseDir: options.baseDir } : {} });
851
- const startedAt = Date.now();
852
- const maxSecretBytes = profile.slots.reduce((max, slot) => Math.max(max, Buffer.byteLength(slot.value)), 0);
853
- const result = yield* runChild({
854
- command: options.command,
855
- args: options.args ?? [],
856
- ...options.cwd ? { cwd: options.cwd } : {},
857
- timeoutMs,
858
- maxOutputBytes: maxOutputBytes + maxSecretBytes,
859
- env: Object.fromEntries(profile.slots.map((slot) => [slot.ref, slot.value]))
860
- }).pipe(mapError2((cause) => new AuthProfileError({ message: `Could not run command with auth profile ${options.name}`, operation: "run", reason: "run-failed", cause })));
861
- const stdout = redactOutput(result.stdout, profile.slots, maxOutputBytes);
862
- const stderr = redactOutput(result.stderr, profile.slots, maxOutputBytes);
863
- return {
864
- ...result,
865
- stdout: stdout.text,
866
- stderr: stderr.text,
867
- stdoutTruncated: result.stdoutTruncated || stdout.truncated,
868
- stderrTruncated: result.stderrTruncated || stderr.truncated,
869
- durationMs: Date.now() - startedAt
870
- };
871
- });
872
- function summary(profile) {
873
- const now = Date.now();
874
- return {
875
- name: profile.name,
876
- createdAt: profile.createdAt,
877
- updatedAt: profile.updatedAt,
878
- slotCount: profile.slots.length,
879
- slots: profile.slots.map((slot) => ({
880
- ref: slot.ref,
881
- sources: [...slot.sources],
882
- ...slot.expiresAt ? { expiresAt: slot.expiresAt } : {},
883
- expired: slot.expiresAt ? Date.parse(slot.expiresAt) <= now : false
884
- }))
885
- };
886
- }
887
- var profileNamePattern = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
888
- function profilePath(baseDir, name) {
889
- return profileNamePattern.test(name) ? succeed6(path.join(baseDir, `${name}.json`)) : fail6(new AuthProfileError({ message: `Invalid auth profile name: ${name}`, operation: "path", reason: "invalid-name" }));
890
- }
891
- function sameSlots(left, right) {
892
- return JSON.stringify(left) === JSON.stringify(right);
893
- }
894
- function redactOutput(text, slots, maxBytes) {
895
- const bytes = Buffer.from(text);
896
- let cutoff = Math.min(bytes.length, maxBytes);
897
- let changed = true;
898
- while (changed) {
899
- changed = false;
900
- for (const slot of slots) {
901
- if (!slot.value)
902
- continue;
903
- const secret = Buffer.from(slot.value);
904
- let start = bytes.indexOf(secret);
905
- while (start >= 0 && start < cutoff) {
906
- if (start + secret.length > cutoff) {
907
- cutoff = start;
908
- changed = true;
909
- break;
910
- }
911
- start = bytes.indexOf(secret, start + secret.length);
912
- }
913
- }
914
- }
915
- return {
916
- text: redactKnownValues(bytes.subarray(0, cutoff).toString("utf8"), slots),
917
- truncated: cutoff < bytes.length
918
- };
919
- }
920
- function runChild(options) {
921
- return callback2((resume) => {
922
- const child = spawn(options.command, [...options.args], {
923
- ...options.cwd ? { cwd: options.cwd } : {},
924
- env: childEnvironment(options.env),
925
- detached: process.platform !== "win32",
926
- stdio: ["ignore", "pipe", "pipe"]
927
- });
928
- const stdout = [];
929
- const stderr = [];
930
- let stdoutBytes = 0;
931
- let stderrBytes = 0;
932
- let stdoutTruncated = false;
933
- let stderrTruncated = false;
934
- const append = (chunks, chunk, currentBytes) => {
935
- const remaining = options.maxOutputBytes - currentBytes;
936
- if (remaining <= 0)
937
- return currentBytes;
938
- chunks.push(chunk.subarray(0, remaining));
939
- return currentBytes + Math.min(chunk.length, remaining);
940
- };
941
- child.stdout.on("data", (chunk) => {
942
- const next = append(stdout, chunk, stdoutBytes);
943
- stdoutTruncated ||= next - stdoutBytes < chunk.length;
944
- stdoutBytes = next;
945
- });
946
- child.stderr.on("data", (chunk) => {
947
- const next = append(stderr, chunk, stderrBytes);
948
- stderrTruncated ||= next - stderrBytes < chunk.length;
949
- stderrBytes = next;
950
- });
951
- let closed = false;
952
- let settled = false;
953
- let closePromiseResolve;
954
- const closePromise = new Promise((resolve) => {
955
- closePromiseResolve = resolve;
956
- });
957
- const timeout = setTimeout(() => {
958
- terminateChildProcess({ child, exit: closePromise, graceMs: 1000, isExited: () => closed });
959
- }, options.timeoutMs);
960
- child.once("error", (cause) => {
961
- clearTimeout(timeout);
962
- closed = true;
963
- closePromiseResolve?.();
964
- if (settled)
965
- return;
966
- settled = true;
967
- resume(fail6(cause));
968
- });
969
- child.once("close", (code, signal) => {
970
- clearTimeout(timeout);
971
- closed = true;
972
- closePromiseResolve?.();
973
- if (settled)
974
- return;
975
- settled = true;
976
- resume(succeed6({
977
- exitCode: code ?? 1,
978
- signal,
979
- stdout: Buffer.concat(stdout).toString("utf8"),
980
- stderr: Buffer.concat(stderr).toString("utf8"),
981
- stdoutTruncated,
982
- stderrTruncated
983
- }));
984
- });
985
- return promise(() => terminateChildProcess({ child, exit: closePromise, graceMs: 1000, isExited: () => closed }));
986
- });
987
- }
988
- function childEnvironment(profile) {
989
- const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^BC_SECRET_[1-9][0-9]*$/.test(name)));
990
- return { ...inherited, ...profile };
991
- }
992
-
993
- // src/auth/domain-policy.ts
994
- import dns from "node:dns/promises";
995
- import net from "node:net";
996
-
997
- class OriginPatternError extends Error {
998
- name = "OriginPatternError";
999
- }
1000
- var maxPatterns = 100;
1001
- function parseOriginPattern(raw) {
1002
- const pattern = raw.trim();
1003
- if (!pattern)
1004
- throw new OriginPatternError("Empty origin pattern");
1005
- if (pattern === "*" || pattern === "*.*")
1006
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} allows every site; leave the allowlist unset instead`);
1007
- const schemeMatch = /^([a-z][a-z0-9+.-]*):\/\//i.exec(pattern);
1008
- const scheme = schemeMatch?.[1]?.toLowerCase();
1009
- if (scheme !== undefined && scheme !== "http" && scheme !== "https") {
1010
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: only http and https origins can be allowed`);
1011
- }
1012
- let rest = schemeMatch ? pattern.slice(schemeMatch[0].length) : pattern;
1013
- if (/[/?#]/.test(rest.replace(/\/$/, "")))
1014
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} must be a host or origin, without a path`);
1015
- rest = rest.replace(/\/$/, "");
1016
- const wildcard = rest.startsWith("*.");
1017
- if (wildcard)
1018
- rest = rest.slice(2);
1019
- if (rest.includes("*"))
1020
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: a wildcard is only allowed as a leading "*."`);
1021
- let parsed;
1022
- try {
1023
- parsed = new URL(`${scheme ?? "http"}://${rest}`);
1024
- } catch {
1025
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} is not a valid host or origin`);
1026
- }
1027
- if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || !parsed.hostname) {
1028
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} must be a host or origin`);
1029
- }
1030
- const host = unbracket(parsed.hostname.toLowerCase());
1031
- if (wildcard && net.isIP(host))
1032
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: wildcards don't apply to IP addresses`);
1033
- if (wildcard && !host.includes("."))
1034
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: "*." needs a domain with a dot, like *.example.com`);
1035
- const port = parsed.port || (scheme ? scheme === "https" ? "443" : "80" : undefined);
1036
- return {
1037
- pattern,
1038
- ...scheme ? { scheme: `${scheme}:` } : {},
1039
- host,
1040
- wildcard,
1041
- ...port ? { port } : {}
1042
- };
1043
- }
1044
- function parseOriginPatterns(raw) {
1045
- if (raw.length > maxPatterns)
1046
- throw new OriginPatternError(`At most ${maxPatterns} origin patterns are allowed`);
1047
- return raw.map(parseOriginPattern);
1048
- }
1049
- function normalizeOriginPatterns(raw) {
1050
- return Array.from(new Set(parseOriginPatterns(raw.flatMap((entry) => entry.split(",")).map((entry) => entry.trim()).filter(Boolean)).map((rule) => rule.pattern.toLowerCase())));
1051
- }
1052
- function unbracket(host) {
1053
- return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
1054
- }
1055
- function ipv4ToNumber(ip) {
1056
- return ip.split(".").reduce((value, part) => value * 256 + Number(part), 0);
1057
- }
1058
- var privateIpv4Ranges = [
1059
- ["0.0.0.0", 8],
1060
- ["10.0.0.0", 8],
1061
- ["100.64.0.0", 10],
1062
- ["127.0.0.0", 8],
1063
- ["169.254.0.0", 16],
1064
- ["172.16.0.0", 12],
1065
- ["192.0.0.0", 24],
1066
- ["192.0.2.0", 24],
1067
- ["192.168.0.0", 16],
1068
- ["198.18.0.0", 15],
1069
- ["198.51.100.0", 24],
1070
- ["203.0.113.0", 24],
1071
- ["224.0.0.0", 4],
1072
- ["240.0.0.0", 4]
1073
- ];
1074
- function isPrivateAddress(address) {
1075
- const ip = unbracket(address.toLowerCase()).replace(/%.*$/, "");
1076
- if (net.isIPv4(ip)) {
1077
- const value = ipv4ToNumber(ip);
1078
- return privateIpv4Ranges.some(([base, bits]) => {
1079
- const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
1080
- return (value & mask) >>> 0 === (ipv4ToNumber(base) & mask) >>> 0;
1081
- });
1082
- }
1083
- if (net.isIPv6(ip)) {
1084
- if (ip === "::" || ip === "::1")
1085
- return true;
1086
- const mapped = /^(?:0*:)*:?ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip) ?? /^::(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
1087
- if (mapped?.[1])
1088
- return isPrivateAddress(mapped[1]);
1089
- const hexMapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(ip);
1090
- if (hexMapped?.[1] && hexMapped[2]) {
1091
- const high = parseInt(hexMapped[1], 16);
1092
- const low = parseInt(hexMapped[2], 16);
1093
- return isPrivateAddress(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
1094
- }
1095
- const first = parseInt(ip.split(":")[0] || "0", 16);
1096
- if ((first & 65024) === 64512 || (first & 65472) === 65152 || (first & 65280) === 65280)
1097
- return true;
1098
- if (ip.startsWith("64:ff9b::"))
1099
- return true;
1100
- return false;
1101
- }
1102
- return false;
1103
- }
1104
- function isLocalhostName(host) {
1105
- return host === "localhost" || host.endsWith(".localhost") || host === "localhost.localdomain";
1106
- }
1107
- function isPrivateHost(host) {
1108
- const bare = unbracket(host.toLowerCase());
1109
- return isLocalhostName(bare) || net.isIP(bare) !== 0 && isPrivateAddress(bare);
1110
- }
1111
- function defaultPort(protocol) {
1112
- return protocol === "https:" ? "443" : "80";
1113
- }
1114
- function ruleMatches(rule, url, host, options) {
1115
- if (rule.scheme !== undefined && rule.scheme !== url.protocol)
1116
- return false;
1117
- if (rule.scheme === undefined && options.httpsOnlyWithoutScheme && url.protocol !== "https:" && !isPrivateHost(host))
1118
- return false;
1119
- if (rule.port !== undefined && rule.port !== (url.port || defaultPort(url.protocol)))
1120
- return false;
1121
- if (rule.wildcard)
1122
- return host === rule.host || host.endsWith(`.${rule.host}`);
1123
- return host === rule.host;
1124
- }
1125
- function explicitlyAllowsHost(rules, url) {
1126
- try {
1127
- const parsed = new URL(url);
1128
- const host = unbracket(parsed.hostname.toLowerCase());
1129
- return rules.some((rule) => !rule.wildcard && ruleMatches(rule, parsed, host, {}));
1130
- } catch {
1131
- return false;
1132
- }
1133
- }
1134
- var neutralSchemes = new Set(["about:", "data:", "blob:"]);
1135
- function checkUrl(rawUrl, rules, options = {}) {
1136
- let url;
1137
- try {
1138
- url = new URL(rawUrl);
1139
- } catch {
1140
- return { allowed: false, reason: `${JSON.stringify(rawUrl.slice(0, 200))} is not a valid URL` };
1141
- }
1142
- if (neutralSchemes.has(url.protocol))
1143
- return { allowed: true };
1144
- if (url.protocol !== "http:" && url.protocol !== "https:") {
1145
- return { allowed: false, reason: `${url.protocol} URLs are not allowed for this session` };
1146
- }
1147
- const host = unbracket(url.hostname.toLowerCase());
1148
- const matching = rules.filter((rule) => ruleMatches(rule, url, host, options));
1149
- if (matching.length === 0) {
1150
- return { allowed: false, reason: `${url.host} is not in the allowed origins (${rules.map((rule) => rule.pattern).join(", ") || "none"})` };
1151
- }
1152
- const explicit = matching.some((rule) => !rule.wildcard);
1153
- if (isPrivateHost(host) && !explicit) {
1154
- return { allowed: false, reason: `${url.host} is a private, loopback or local address; allow it by naming that exact host` };
1155
- }
1156
- return { allowed: true, host, explicit };
1157
- }
1158
- async function resolvesToPrivateAddress(host, timeoutMs = 2000) {
1159
- const bare = unbracket(host);
1160
- if (net.isIP(bare) || isLocalhostName(bare))
1161
- return isPrivateHost(bare) ? bare : undefined;
1162
- let timer;
1163
- try {
1164
- const addresses = await Promise.race([
1165
- dns.lookup(bare, { all: true, verbatim: true }),
1166
- new Promise((_, reject) => {
1167
- timer = setTimeout(() => reject(new Error("DNS lookup timed out")), timeoutMs);
1168
- })
1169
- ]);
1170
- return addresses.find((entry) => isPrivateAddress(entry.address))?.address;
1171
- } catch {
1172
- return;
1173
- } finally {
1174
- if (timer)
1175
- clearTimeout(timer);
1176
- }
1177
- }
1178
- async function checkNavigationUrl(rawUrl, rules) {
1179
- const decision = checkUrl(rawUrl, rules);
1180
- if (!decision.allowed || decision.host === undefined || decision.explicit)
1181
- return decision;
1182
- const privateAddress = await resolvesToPrivateAddress(decision.host);
1183
- if (privateAddress) {
1184
- return { allowed: false, reason: `${decision.host} resolves to the private address ${privateAddress}; allow it by naming that exact host` };
1185
- }
1186
- return decision;
1187
- }
1188
-
1189
- // src/auth/site-secrets.ts
1190
- var StoredSiteSecret = Struct({
1191
- version: Literal(1),
1192
- name: String3,
1193
- kind: Literals(["password", "totp"]),
1194
- value: String3,
1195
- allowedOrigins: ArraySchema(String3),
1196
- createdAt: String3,
1197
- updatedAt: String3
1198
- });
1199
-
1200
- class SiteSecretError extends TaggedError2()("SiteSecret.Error", {
1201
- message: String3,
1202
- reason: Literals(["invalid-name", "invalid-origins", "invalid-value", "not-found", "read-failed", "write-failed"]),
1203
- cause: optionalKey(Defect())
1204
- }) {
1205
- }
1206
- var defaultSiteSecretsDir = () => path2.join(dataRoot(), "site-secrets");
1207
- function secretPath(baseDir, name) {
1208
- return profileNamePattern.test(name) ? succeed6(path2.join(baseDir, `${name}.json`)) : fail6(new SiteSecretError({ message: `Invalid secret name: ${name} (letters, digits, ".", "_" and "-", up to 64)`, reason: "invalid-name" }));
1209
- }
1210
- function summary2(secret) {
1211
- return { name: secret.name, kind: secret.kind, allowedOrigins: [...secret.allowedOrigins], createdAt: secret.createdAt, updatedAt: secret.updatedAt };
1212
- }
1213
- var readSecret = fn("SiteSecrets.read")(function* (name, options = {}) {
1214
- const filePath = yield* secretPath(options.baseDir ?? defaultSiteSecretsDir(), name);
1215
- const text = yield* tryPromise({
1216
- try: () => fs2.readFile(filePath, "utf8"),
1217
- catch: (cause) => isNodeError(cause) && cause.code === "ENOENT" ? new SiteSecretError({ message: `Secret not found: ${name}. Ask the user to add it with \`${cliCommand(`secrets add ${name} --origin <origin>`)}\`.`, reason: "not-found" }) : new SiteSecretError({ message: `Could not read secret ${name}`, reason: "read-failed", cause })
1218
- });
1219
- return yield* try_2({
1220
- try: () => decodeUnknownSync(StoredSiteSecret)(JSON.parse(text)),
1221
- catch: (cause) => new SiteSecretError({ message: `Secret ${name} is not a valid secret file`, reason: "read-failed", cause })
1222
- });
1223
- });
1224
- var addSecret = fn("SiteSecrets.add")(function* (options) {
1225
- const baseDir = options.baseDir ?? defaultSiteSecretsDir();
1226
- const filePath = yield* secretPath(baseDir, options.name);
1227
- const kind = options.kind ?? "password";
1228
- const allowedOrigins = yield* try_2({
1229
- try: () => normalizeOriginPatterns(options.allowedOrigins),
1230
- catch: (cause) => new SiteSecretError({ message: cause instanceof Error ? cause.message : "Invalid origins", reason: "invalid-origins", cause })
1231
- });
1232
- if (allowedOrigins.length === 0) {
1233
- return yield* new SiteSecretError({ message: "A secret needs at least one allowed origin (--origin https://example.com)", reason: "invalid-origins" });
1234
- }
1235
- const value = kind === "totp" ? options.value.trim() : options.value.replace(/\r?\n$/, "");
1236
- if (!value)
1237
- return yield* new SiteSecretError({ message: "The secret value is empty", reason: "invalid-value" });
1238
- if (kind === "totp")
1239
- yield* try_2({
1240
- try: () => totpCode(value),
1241
- catch: (cause) => new SiteSecretError({ message: `Not a TOTP seed or otpauth:// URI: ${cause instanceof Error ? cause.message : "invalid"}`, reason: "invalid-value", cause })
1242
- });
1243
- const write = gen(function* () {
1244
- const existing = yield* readSecret(options.name, { baseDir }).pipe(catchIf((error) => error.reason === "not-found", () => succeed6(undefined)));
1245
- const now = new Date().toISOString();
1246
- const secret = { version: 1, name: options.name, kind, value, allowedOrigins: [...allowedOrigins], createdAt: existing?.createdAt ?? now, updatedAt: now };
1247
- yield* tryPromise({
1248
- try: () => writeJsonFileAtomically(filePath, secret, { dirMode: 448 }),
1249
- catch: (cause) => new SiteSecretError({ message: `Could not write secret ${options.name}`, reason: "write-failed", cause })
1250
- });
1251
- return summary2(secret);
1252
- });
1253
- return yield* withLock(options.name, { baseDir }, write).pipe(mapError2((error) => error instanceof SiteSecretError ? error : new SiteSecretError({ message: error.message, reason: "write-failed", cause: error })));
1254
- });
1255
- var listSecrets = fn("SiteSecrets.list")(function* (options = {}) {
1256
- const baseDir = options.baseDir ?? defaultSiteSecretsDir();
1257
- const names = yield* tryPromise({
1258
- try: () => fs2.readdir(baseDir).catch((cause) => isNodeError(cause) && cause.code === "ENOENT" ? [] : Promise.reject(cause)),
1259
- catch: (cause) => new SiteSecretError({ message: "Could not list secrets", reason: "read-failed", cause })
1260
- });
1261
- const secrets = [];
1262
- for (const file of names.filter((entry) => entry.endsWith(".json")).sort()) {
1263
- const secret = yield* readSecret(file.slice(0, -".json".length), { baseDir }).pipe(option2);
1264
- if (secret._tag === "Some")
1265
- secrets.push(summary2(secret.value));
1266
- }
1267
- return secrets;
1268
- });
1269
- var removeSecret = fn("SiteSecrets.remove")(function* (name, options = {}) {
1270
- const baseDir = options.baseDir ?? defaultSiteSecretsDir();
1271
- const filePath = yield* secretPath(baseDir, name);
1272
- return yield* withLock(name, { baseDir }, tryPromise({
1273
- try: () => fs2.rm(filePath).then(() => true, (cause) => isNodeError(cause) && cause.code === "ENOENT" ? false : Promise.reject(cause)),
1274
- catch: (cause) => new SiteSecretError({ message: `Could not remove secret ${name}`, reason: "write-failed", cause })
1275
- })).pipe(mapError2((error) => error instanceof SiteSecretError ? error : new SiteSecretError({ message: error.message, reason: "write-failed", cause: error })));
1276
- });
1277
- function base32Decode(input) {
1278
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
1279
- const clean = input.toUpperCase().replace(/[\s=-]/g, "");
1280
- if (!clean || /[^A-Z2-7]/.test(clean))
1281
- throw new Error("the seed must be base32");
1282
- let bits = 0;
1283
- let value = 0;
1284
- const bytes = [];
1285
- for (const char of clean) {
1286
- value = value << 5 | alphabet.indexOf(char);
1287
- bits += 5;
1288
- if (bits >= 8) {
1289
- bytes.push(value >>> bits - 8 & 255);
1290
- bits -= 8;
1291
- }
1292
- }
1293
- return Buffer.from(bytes);
1294
- }
1295
- function totpParameters(seed) {
1296
- if (/^otpauth:\/\//i.test(seed)) {
1297
- const url = new URL(seed);
1298
- const secret = url.searchParams.get("secret");
1299
- if (!secret)
1300
- throw new Error("the otpauth URI has no secret");
1301
- const digits = Number(url.searchParams.get("digits") ?? 6);
1302
- const period = Number(url.searchParams.get("period") ?? 30);
1303
- const algorithm = (url.searchParams.get("algorithm") ?? "SHA1").toLowerCase();
1304
- if (![6, 7, 8].includes(digits) || !Number.isInteger(period) || period <= 0 || !["sha1", "sha256", "sha512"].includes(algorithm)) {
1305
- throw new Error("unsupported otpauth parameters");
1306
- }
1307
- return { key: base32Decode(secret), digits, period, algorithm };
1308
- }
1309
- return { key: base32Decode(seed), digits: 6, period: 30, algorithm: "sha1" };
1310
- }
1311
- function totpCode(seed, now = Date.now()) {
1312
- const { key, digits, period, algorithm } = totpParameters(seed);
1313
- const counter = Buffer.alloc(8);
1314
- counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / period)));
1315
- const hmac = crypto.createHmac(algorithm, key).update(counter).digest();
1316
- const offset = hmac[hmac.length - 1] & 15;
1317
- const binary = (hmac.readUInt32BE(offset) & 2147483647) % 10 ** digits;
1318
- return String(binary).padStart(digits, "0");
1319
- }
1320
- function secretText(secret) {
1321
- return secret.kind === "totp" ? totpCode(secret.value) : secret.value;
1322
- }
1323
-
1324
- export { makeUnsafe, make3, terminateChildProcess, minimumKnownSubstringLength, SecretCollector, looksLikeTokenSegment, AuthProfileError, read, readOptional, withLock, write, status, run, OriginPatternError, parseOriginPatterns, normalizeOriginPatterns, isPrivateAddress, explicitlyAllowsHost, checkUrl, checkNavigationUrl, defaultSiteSecretsDir, readSecret, addSecret, listSecrets, removeSecret, secretText };