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

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-5ezftnv2.mjs} +39 -222
  3. package/dist/cli.mjs +18 -18
  4. package/dist/{helpers-v2zmfak2.mjs → helpers-k5ybc61c.mjs} +1 -1
  5. package/dist/{index-gjq7chrk.mjs → index-37ssbv86.mjs} +2 -2
  6. package/dist/{legacy-runtime-rvfsgmzn.mjs → legacy-runtime-j0sw664c.mjs} +10 -9
  7. package/dist/{main-m45zegrn.mjs → main-0h387a1q.mjs} +1 -6
  8. package/dist/{main-jeta10c6.mjs → main-3514h33n.mjs} +11 -11
  9. package/dist/{main-qwf4vk41.mjs → main-4qq4n32k.mjs} +2 -2
  10. package/dist/{main-1b344j42.mjs → main-66fy08h5.mjs} +8 -25
  11. package/dist/{main-x7takqns.mjs → main-7h3v45ag.mjs} +26 -17
  12. package/dist/{main-t2jyedkv.mjs → main-7v4scg8t.mjs} +8 -6
  13. package/dist/{main-6hvv25x8.mjs → main-8xd753k5.mjs} +1 -1
  14. package/dist/{main-akpa411k.mjs → main-9q9919e3.mjs} +118 -2
  15. package/dist/{main-2wrvr3gc.mjs → main-ba028a85.mjs} +34 -27
  16. package/dist/{main-sbqypb33.mjs → main-d8km89cz.mjs} +2 -2
  17. package/dist/main-dab23et4.mjs +17 -0
  18. package/dist/{main-9frwnsnf.mjs → main-j4kq90pw.mjs} +1 -1
  19. package/dist/{main-3ewrhbqw.mjs → main-kzcrfvmh.mjs} +4 -4
  20. package/dist/{main-z32979g4.mjs → main-m9n50a86.mjs} +41 -162
  21. package/dist/{main-ndmgt6k5.mjs → main-mvjg1jye.mjs} +5 -46
  22. package/dist/{main-xjskgtdr.mjs → main-pqxrvknr.mjs} +2 -2
  23. package/dist/main-qrqem3fy.mjs +4 -0
  24. package/dist/{main-xct4r41x.mjs → main-svhdexdh.mjs} +4 -4
  25. package/dist/main-tryp3jph.mjs +141 -0
  26. package/dist/{mcp-2xkjfnqz.mjs → mcp-jh4atts2.mjs} +37 -140
  27. package/dist/{migrate-fygxtp2g.mjs → migrate-r433scvg.mjs} +14 -7
  28. package/dist/{relay-mbjgxbtr.mjs → relay-1epy67be.mjs} +648 -372
  29. package/dist/remove-stored-secrets-wy3pakjj.mjs +6 -0
  30. package/dist/{runtime-update-ngg3m888.mjs → runtime-update-ww2pejn2.mjs} +13 -11
  31. package/dist/{setup-t0pbhmzh.mjs → setup-n1hpbkz2.mjs} +27 -49
  32. package/dist/{skill-text-1rg5b5np.mjs → skill-text-0ndr12dz.mjs} +7 -31
  33. package/dist/{update-heze6vjn.mjs → update-z7qvagkc.mjs} +3 -3
  34. package/dist/{version-x1kkvpqn.mjs → version-2123c138.mjs} +1 -1
  35. package/package.json +1 -1
  36. package/skills/browse/SKILL.md +7 -31
  37. package/dist/main-6my7bmf1.mjs +0 -1324
  38. package/dist/main-ew8jna3e.mjs +0 -4
  39. package/dist/supervisor-wrrnbfhw.mjs +0 -269
@@ -4,23 +4,8 @@ import {
4
4
  import {
5
5
  opencodeBrowserVersion2,
6
6
  opencodeBrowserBuildId2
7
- } from "./main-ew8jna3e.mjs";
7
+ } from "./main-qrqem3fy.mjs";
8
8
  import {
9
- defaultRoots,
10
- configRoot2,
11
- dataRoot,
12
- stateRoot,
13
- cacheRoot,
14
- installedBinaryPath,
15
- installerBinaryPath,
16
- oldStoreMarker,
17
- fromCheckout,
18
- cliCommand,
19
- PUBLIC_STORE_ID,
20
- storeConfig,
21
- devExtension,
22
- storeUrl,
23
- installCommand,
24
9
  extensionProtocolVersion,
25
10
  minExtensionProtocolVersion,
26
11
  browserUnresponsive,
@@ -41,7 +26,7 @@ import {
41
26
  setStoredMode,
42
27
  autoUpdateStatus,
43
28
  createAutoUpdater
44
- } from "./main-z32979g4.mjs";
29
+ } from "./main-m9n50a86.mjs";
45
30
  import {
46
31
  isNodeError,
47
32
  isUnsupportedDirectorySyncError,
@@ -60,9 +45,6 @@ import {
60
45
  NetworkStartRequest,
61
46
  NetworkSessionRequest,
62
47
  NetworkStopRequest,
63
- AuthProfileRequest,
64
- AuthRefreshRequest,
65
- AuthRunRequest,
66
48
  RecordingTargetRequest,
67
49
  RecordingStartRequest,
68
50
  FlightRecorderStartRequest,
@@ -95,7 +77,7 @@ import {
95
77
  isRestrictedTarget2,
96
78
  isRestrictedUrl2,
97
79
  dataUrlDocument2
98
- } from "./main-ndmgt6k5.mjs";
80
+ } from "./main-mvjg1jye.mjs";
99
81
  import {
100
82
  context,
101
83
  pendingPairingCodeKeys,
@@ -113,39 +95,16 @@ import {
113
95
  pairingSessionKey,
114
96
  sessionProof,
115
97
  wrapToken
116
- } from "./main-sbqypb33.mjs";
117
- import {
118
- makeUnsafe,
119
- terminateChildProcess,
120
- minimumKnownSubstringLength,
121
- SecretCollector,
122
- looksLikeTokenSegment,
123
- AuthProfileError,
124
- read,
125
- readOptional,
126
- withLock,
127
- write,
128
- status,
129
- run,
130
- OriginPatternError,
131
- parseOriginPatterns,
132
- normalizeOriginPatterns,
133
- isPrivateAddress,
134
- explicitlyAllowsHost,
135
- checkUrl,
136
- checkNavigationUrl,
137
- readSecret,
138
- secretText
139
- } from "./main-6my7bmf1.mjs";
98
+ } from "./main-d8km89cz.mjs";
140
99
  import {
141
100
  defaultJournalBaseDir,
142
101
  makeJournalEntry,
143
102
  appendJournalEntry,
144
103
  startJournalRetention
145
- } from "./main-3ewrhbqw.mjs";
104
+ } from "./main-kzcrfvmh.mjs";
146
105
  import {
147
106
  createUpdateWatcher2
148
- } from "./main-t2jyedkv.mjs";
107
+ } from "./main-7v4scg8t.mjs";
149
108
  import {
150
109
  SettingsInputError,
151
110
  parseSettingChanges,
@@ -153,20 +112,7 @@ import {
153
112
  settingsToExtension,
154
113
  describeSettings,
155
114
  describeChanges
156
- } from "./main-1b344j42.mjs";
157
- import {
158
- relayHostname,
159
- isLocalPeer,
160
- installedDevExtension,
161
- syncDevExtension
162
- } from "./main-xct4r41x.mjs";
163
- import {
164
- currentTimeMillis,
165
- value,
166
- when,
167
- orElse,
168
- exhaustive
169
- } from "./main-akpa411k.mjs";
115
+ } from "./main-66fy08h5.mjs";
170
116
  import {
171
117
  map,
172
118
  withDefault,
@@ -176,18 +122,27 @@ import {
176
122
  Boolean2,
177
123
  appendManagedRelayProcessLog,
178
124
  relayLog
179
- } from "./main-2wrvr3gc.mjs";
125
+ } from "./main-ba028a85.mjs";
126
+ import {
127
+ currentTimeMillis,
128
+ makeUnsafe,
129
+ value,
130
+ when,
131
+ orElse,
132
+ exhaustive
133
+ } from "./main-9q9919e3.mjs";
134
+ import {
135
+ installedDevExtension,
136
+ syncDevExtension,
137
+ relayHostname,
138
+ isLocalPeer
139
+ } from "./main-svhdexdh.mjs";
180
140
  import {
181
141
  relayTokenQueryParam,
182
142
  relayToken,
183
143
  secretsEqual,
184
144
  ensurePrivateDirectory
185
- } from "./main-xjskgtdr.mjs";
186
- import {
187
- join,
188
- interrupt,
189
- makeUnsafe2
190
- } from "./main-jeta10c6.mjs";
145
+ } from "./main-pqxrvknr.mjs";
191
146
  import {
192
147
  configuredRelayPort,
193
148
  relayPortPinned,
@@ -195,7 +150,29 @@ import {
195
150
  writeRelayState,
196
151
  removeRelayState,
197
152
  chooseRelayPort
198
- } from "./main-qwf4vk41.mjs";
153
+ } from "./main-4qq4n32k.mjs";
154
+ import {
155
+ defaultRoots,
156
+ configRoot2,
157
+ dataRoot,
158
+ stateRoot,
159
+ cacheRoot,
160
+ installedBinaryPath,
161
+ installerBinaryPath,
162
+ oldStoreMarker,
163
+ fromCheckout,
164
+ cliCommand,
165
+ PUBLIC_STORE_ID,
166
+ storeConfig,
167
+ devExtension,
168
+ storeUrl,
169
+ installCommand
170
+ } from "./main-tryp3jph.mjs";
171
+ import {
172
+ join,
173
+ interrupt,
174
+ makeUnsafe2
175
+ } from "./main-3514h33n.mjs";
199
176
  import {
200
177
  taggedEnum,
201
178
  is2,
@@ -216,7 +193,7 @@ import {
216
193
  Int2,
217
194
  Defect,
218
195
  TaggedError2
219
- } from "./main-6hvv25x8.mjs";
196
+ } from "./main-8xd753k5.mjs";
220
197
  import {
221
198
  isString,
222
199
  isNumber,
@@ -303,7 +280,7 @@ import {
303
280
  runSync,
304
281
  fnUntraced,
305
282
  fn
306
- } from "./main-m45zegrn.mjs";
283
+ } from "./main-0h387a1q.mjs";
307
284
 
308
285
  // src/relay.ts
309
286
  import crypto10 from "node:crypto";
@@ -7145,8 +7122,7 @@ var sandboxGlobalKeys = [
7145
7122
  "handoff",
7146
7123
  "demonstrate",
7147
7124
  "network",
7148
- "pageConsole",
7149
- "secrets"
7125
+ "pageConsole"
7150
7126
  ];
7151
7127
  async function runUserCode({ code, globals, realm, onUnhandledRejection }) {
7152
7128
  const logCapture = createExecuteLogCapture();
@@ -8103,7 +8079,7 @@ function formatDemonstrationCode(options) {
8103
8079
  ...options.steps.map((step) => value(step).pipe(when({ kind: "navigation" }, ({ url }) => `// Navigated to ${url}`), when({ kind: "click" }, ({ selector, role, name }) => {
8104
8080
  const description = role && name ? ` // ${role} ${JSON.stringify(name)}` : "";
8105
8081
  return `await page.locator(${JSON.stringify(selector)}).click()${description}`;
8106
- }), when({ kind: "fill" }, ({ selector, value: value2, redacted }) => redacted ? `// Fill ${JSON.stringify(selector)} from an approved secret source.` : `await page.locator(${JSON.stringify(selector)}).fill(${JSON.stringify(value2)})`), when({ kind: "check" }, ({ selector, checked }) => `await page.locator(${JSON.stringify(selector)}).${checked ? "check" : "uncheck"}()`), when({ kind: "select" }, ({ selector, value: value2 }) => `await page.locator(${JSON.stringify(selector)}).selectOption(${JSON.stringify(value2)})`), exhaustive)),
8082
+ }), when({ kind: "fill" }, ({ selector, value: value2, redacted }) => redacted ? `// Fill ${JSON.stringify(selector)} from an approved credential source.` : `await page.locator(${JSON.stringify(selector)}).fill(${JSON.stringify(value2)})`), when({ kind: "check" }, ({ selector, checked }) => `await page.locator(${JSON.stringify(selector)}).${checked ? "check" : "uncheck"}()`), when({ kind: "select" }, ({ selector, value: value2 }) => `await page.locator(${JSON.stringify(selector)}).selectOption(${JSON.stringify(value2)})`), exhaustive)),
8107
8083
  "return { url: page.url(), title: await page.title() }"
8108
8084
  ];
8109
8085
  return lines.join(`
@@ -10837,55 +10813,111 @@ function buildSandboxGlobals(deps) {
10837
10813
  start: (target) => start(target ?? page),
10838
10814
  stop: (target) => stop(target ?? page)
10839
10815
  },
10840
- secrets: {
10841
- type: (target, name, typeOptions) => deps.secrets.typeSecret(page, target, name, typeOptions)
10842
- },
10843
10816
  handoffTracker
10844
10817
  };
10845
10818
  }
10846
10819
 
10847
- // src/execute/secrets-bridge.ts
10848
- var isOpaqueDocumentUrl = (url) => /^(?:about|data|blob):/i.test(url);
10849
- var frameOrigin = (url) => {
10850
- try {
10851
- return new URL(url).origin;
10852
- } catch {
10853
- return url.slice(0, 200);
10854
- }
10855
- };
10856
- var elementHasFocus = (handle) => handle.evaluate((node) => {
10857
- const element = node;
10858
- return element.ownerDocument.activeElement === element || element.contains(element.ownerDocument.activeElement);
10859
- });
10820
+ // src/network-capture.ts
10821
+ import path7 from "node:path";
10822
+
10823
+ // src/network-capture/har-redaction.ts
10824
+ import path6 from "node:path";
10860
10825
 
10861
- class ExecuteSecretsBridge {
10862
- deps;
10863
- typedSecrets = new Map;
10864
- constructor(deps) {
10865
- this.deps = deps;
10826
+ // src/network-capture/redaction.ts
10827
+ var redactedPlaceholder = "[redacted]";
10828
+ var redactionSentinel = "__browse_redacted__";
10829
+ var secretNamePattern = /auth(?:orization)?|cookie|credential|csrf|xsrf|token|secret|session|password|passwd|pwd|passcode|otp|(?:^|[-_.])code(?:$|[-_.])|(?:api|access|refresh)[-_.]?key|signature|(?:^|[-_.])sig(?:$|[-_.])/i;
10830
+ var oneTimeFieldPattern = /pass(?:word|wd|code|phrase)|(?:^|[-_.])pwd(?:$|[-_.])|otp|totp|(?:^|[-_.])(?:mfa_?|2fa_?|verification_?|auth_?)?code(?:$|[-_.])|(?:^|[-_.])pin(?:$|[-_.])/i;
10831
+ var minimumKnownSubstringLength = 8;
10832
+ var secretHeaders = new Set([
10833
+ "authorization",
10834
+ "proxy-authorization",
10835
+ "x-api-key",
10836
+ "api-key",
10837
+ "x-csrf-token",
10838
+ "csrf-token",
10839
+ "x-xsrf-token"
10840
+ ]);
10841
+ var nonSecretHeaders = new Set([
10842
+ ":authority",
10843
+ ":method",
10844
+ ":scheme",
10845
+ ":status",
10846
+ ":protocol",
10847
+ "access-control-allow-credentials",
10848
+ "access-control-allow-origin",
10849
+ "access-control-allow-methods",
10850
+ "access-control-allow-headers",
10851
+ "access-control-expose-headers",
10852
+ "access-control-max-age",
10853
+ "access-control-request-method",
10854
+ "access-control-request-headers",
10855
+ "access-control-allow-private-network",
10856
+ "access-control-request-private-network"
10857
+ ]);
10858
+
10859
+ class SecretRedactor {
10860
+ knownValues = new Set;
10861
+ alwaysRedacted = new Set;
10862
+ protectHeaders(headers) {
10863
+ return headers.map(({ name, value }) => ({ name, value: restoreRedactionPlaceholders(this.protectHeader(name, value)) }));
10864
+ }
10865
+ protectUrl(rawUrl) {
10866
+ const fragmentStart = rawUrl.indexOf("#");
10867
+ const base = fragmentStart < 0 ? rawUrl : rawUrl.slice(0, fragmentStart);
10868
+ const protectQuery = (name, value) => value ? this.scrub(value, name) : value;
10869
+ const protectPath = (pathname) => protectPathSegments(pathname, (segment) => this.scrub(segment));
10870
+ let protectedUrl;
10871
+ try {
10872
+ const url = new URL(base);
10873
+ url.pathname = protectPath(url.pathname);
10874
+ url.search = protectSearchParams(url.searchParams, protectQuery).toString();
10875
+ protectedUrl = url.toString();
10876
+ } catch {
10877
+ protectedUrl = protectRelativeUrl(base, protectQuery, protectPath);
10878
+ }
10879
+ protectedUrl = restoreRedactionPlaceholders(protectedUrl);
10880
+ if (fragmentStart < 0)
10881
+ return protectedUrl;
10882
+ const fragment = restoreRedactionPlaceholders(protectFragment(rawUrl.slice(fragmentStart + 1), (name, value) => value ? this.scrub(value, name) : value));
10883
+ return `${protectedUrl}#${fragment}`;
10866
10884
  }
10867
- redactTypedSecrets(text) {
10868
- let output = text;
10869
- for (const [value, name] of [...this.typedSecrets].sort(([left], [right]) => right.length - left.length)) {
10870
- output = output.split(value).join(`[secret ${name}]`);
10885
+ protectBody(body, contentType) {
10886
+ const type = contentType?.toLowerCase() ?? "";
10887
+ if (type.includes("json")) {
10888
+ try {
10889
+ return restoreRedactionPlaceholders(JSON.stringify(this.protectJson(JSON.parse(body), "open")));
10890
+ } catch {
10891
+ return;
10892
+ }
10871
10893
  }
10872
- return output;
10894
+ if (type.includes("application/x-www-form-urlencoded")) {
10895
+ const protectedParams = protectSearchParams(new URLSearchParams(body), (name, value) => value ? this.scrub(value, name) : value);
10896
+ return restoreRedactionPlaceholders(protectedParams.toString());
10897
+ }
10898
+ if (type.includes("multipart/form-data")) {
10899
+ const protectedBody = this.protectMultipart(body, contentType ?? "");
10900
+ return protectedBody === undefined ? undefined : restoreRedactionPlaceholders(protectedBody);
10901
+ }
10902
+ return;
10873
10903
  }
10874
- redactOutputText(text) {
10875
- return this.redactTypedSecrets(this.deps.networkCapture.redactText(text));
10904
+ redactText(text) {
10905
+ if (this.knownValues.has(text))
10906
+ return redactedPlaceholder;
10907
+ return this.redactKnown(text, (value) => value.length >= minimumKnownSubstringLength || this.alwaysRedacted.has(value));
10876
10908
  }
10877
- redactOutputUrl(url) {
10878
- return this.redactTypedSecrets(this.deps.networkCapture.redactUrl(url));
10909
+ redactUrl(url) {
10910
+ return this.redactText(this.protectUrl(url));
10879
10911
  }
10880
- redactOutputValue(value) {
10881
- const redacted = this.deps.networkCapture.redactValue(value);
10882
- if (this.typedSecrets.size === 0)
10883
- return redacted;
10912
+ redactValue(value) {
10913
+ const redactString = (text) => this.redactText(text);
10884
10914
  const visit = (item, depth) => {
10885
- if (typeof item === "string")
10886
- return this.redactTypedSecrets(item);
10887
- if (typeof item === "number" && this.typedSecrets.has(String(item)))
10888
- return `[secret ${this.typedSecrets.get(String(item))}]`;
10915
+ if (isString(item))
10916
+ return redactString(item);
10917
+ if (isNumber(item) || isBoolean(item)) {
10918
+ const text = String(item);
10919
+ return this.knownValues.has(text) || this.alwaysRedacted.has(text) ? redactedPlaceholder : item;
10920
+ }
10889
10921
  if (depth > 32 || item === null || typeof item !== "object" || Buffer.isBuffer(item))
10890
10922
  return item;
10891
10923
  if (Array.isArray(item))
@@ -10893,92 +10925,218 @@ class ExecuteSecretsBridge {
10893
10925
  const prototype = Object.getPrototypeOf(item);
10894
10926
  if (prototype !== Object.prototype && prototype !== null)
10895
10927
  return item;
10896
- return Object.fromEntries(Object.entries(item).map(([key, entry]) => [key, visit(entry, depth + 1)]));
10928
+ return Object.fromEntries(Object.entries(item).map(([key, entry]) => [
10929
+ key,
10930
+ secretNamePattern.test(key) ? redactSecretValue(entry) : visit(entry, depth + 1)
10931
+ ]));
10897
10932
  };
10898
- return visit(redacted, 0);
10933
+ return visit(value, 0);
10899
10934
  }
10900
- redactCaptureLogs(logs) {
10901
- return logs.map((log) => ({
10902
- ...log,
10903
- text: this.redactOutputText(log.text),
10904
- ...log.location ? {
10905
- location: { ...log.location, url: this.redactOutputUrl(log.location.url) }
10906
- } : {}
10907
- }));
10935
+ redactKnownSubstrings(text, minimumLength) {
10936
+ return this.redactKnown(text, (value) => value.length >= minimumLength || this.alwaysRedacted.has(value));
10908
10937
  }
10909
- redactCaptureAftermath(aftermath) {
10910
- return {
10911
- ...aftermath,
10912
- startUrl: aftermath.startUrl ? this.redactOutputUrl(aftermath.startUrl) : aftermath.startUrl,
10913
- endUrl: aftermath.endUrl ? this.redactOutputUrl(aftermath.endUrl) : aftermath.endUrl,
10914
- navigations: aftermath.navigations.map((url) => this.redactOutputUrl(url)),
10915
- ...aftermath.challenge ? { challenge: { ...aftermath.challenge, url: this.redactOutputUrl(aftermath.challenge.url) } } : {}
10916
- };
10938
+ addRedactionOnly(value) {
10939
+ if (value) {
10940
+ this.alwaysRedacted.add(value);
10941
+ this.knownValues.add(value);
10942
+ }
10917
10943
  }
10918
- async typeSecret(page, target, name, options = {}) {
10919
- if (typeof name !== "string" || !name)
10920
- throw new Error("secrets.type(target, name): name must be the name of a stored secret");
10921
- const secret = await runPromise(readSecret(name)).catch((error) => {
10922
- throw new Error(`secrets.type: ${error instanceof Error ? error.message : "could not read the secret"}`);
10923
- });
10924
- const secretRules = parseOriginPatterns(secret.allowedOrigins);
10925
- const sessionPatterns = this.deps.allowedOrigins();
10926
- const sessionRules = sessionPatterns && sessionPatterns.length > 0 ? parseOriginPatterns(sessionPatterns) : undefined;
10927
- const locator = typeof target === "string" ? page.locator(target) : target;
10928
- if (!locator || typeof locator.elementHandle !== "function") {
10929
- throw new Error("secrets.type(target, name): target must be a selector string or a Locator");
10930
- }
10931
- const handle = await locator.elementHandle({ timeout: options.timeout ?? 1e4 });
10932
- try {
10933
- const frame = await handle.ownerFrame();
10934
- if (!frame)
10935
- throw new Error(`secrets.type: target_not_editable: the element for ${JSON.stringify(name)} is not in a frame`);
10936
- const checkOrigin = () => {
10937
- const url = frame.url();
10938
- const origin = frameOrigin(url);
10939
- const decision = checkUrl(url, secretRules, { httpsOnlyWithoutScheme: true });
10940
- if (!decision.allowed || isOpaqueDocumentUrl(url)) {
10941
- throw new Error(`secrets.type: domain_not_allowed: the field's frame is ${origin}, which is not an allowed origin of secret ${JSON.stringify(name)} (${secret.allowedOrigins.join(", ")}). Nothing was typed.`);
10942
- }
10943
- if (sessionRules && !checkUrl(url, sessionRules).allowed) {
10944
- throw new Error(`secrets.type: domain_not_allowed: the field's frame is ${origin}, which is outside this session's domain allowlist. Nothing was typed.`);
10944
+ redactKnown(text, include) {
10945
+ const entries = [];
10946
+ for (const value of this.knownValues) {
10947
+ if (!include(value))
10948
+ continue;
10949
+ entries.push({ value });
10950
+ const encoded = encodeURIComponent(value);
10951
+ if (encoded !== value)
10952
+ entries.push({ value: encoded });
10953
+ }
10954
+ return entries.sort((left, right) => right.value.length - left.value.length).reduce((output, entry) => output.split(entry.value).join(redactedPlaceholder), text);
10955
+ }
10956
+ scrub(value, fieldName = "") {
10957
+ if (!value)
10958
+ return value;
10959
+ this.knownValues.add(value);
10960
+ if (oneTimeFieldPattern.test(fieldName))
10961
+ this.alwaysRedacted.add(value);
10962
+ return redactionSentinel;
10963
+ }
10964
+ protectHeader(name, value) {
10965
+ if (!value)
10966
+ return value;
10967
+ const lower = name.toLowerCase();
10968
+ if (lower === ":path")
10969
+ return this.protectUrl(value);
10970
+ if (nonSecretHeaders.has(lower))
10971
+ return value;
10972
+ if (lower === "cookie" || lower === "set-cookie") {
10973
+ const protectLine = (line) => line.split(/;\s*/).map((part, index) => {
10974
+ const separator = part.indexOf("=");
10975
+ if (separator < 1)
10976
+ return part;
10977
+ const cookieName = part.slice(0, separator).trim();
10978
+ const cookieValue = part.slice(separator + 1);
10979
+ if (lower === "set-cookie" && index > 0 && /^(domain|path|expires|max-age|samesite|priority|partitioned|secure|httponly)$/i.test(cookieName)) {
10980
+ return part;
10945
10981
  }
10946
- return origin;
10947
- };
10948
- checkOrigin();
10949
- if (!await handle.isEditable().catch(() => false)) {
10950
- throw new Error(`secrets.type: target_not_editable: the target is not an editable field. Nothing was typed.`);
10951
- }
10952
- if (options.clear !== false)
10953
- await handle.fill("");
10954
- await handle.focus();
10955
- if (!await elementHasFocus(handle)) {
10956
- throw new Error("secrets.type: target_not_editable: the field did not keep focus. Nothing was typed.");
10957
- }
10958
- const origin = checkOrigin();
10959
- const urlBefore = frame.url();
10960
- const text = secretText(secret);
10961
- this.typedSecrets.set(text, name);
10962
- this.deps.networkCapture.addRedaction(text);
10963
- await frame.page().keyboard.insertText(text);
10964
- if (frame.url() !== urlBefore) {
10965
- this.deps.addWarningOnce(`secrets.type: the field's frame navigated while ${JSON.stringify(name)} was typed; check where it went before submitting.`);
10966
- }
10967
- if (!sessionRules) {
10968
- this.deps.addWarningOnce(`secrets.type typed ${JSON.stringify(name)} in a session without a domain allowlist. A prompt-injected page could steer this session elsewhere after the value is in the page: set one with session_allowlist (or \`session allow\`) before using secrets.`);
10969
- }
10970
- return { typed: true, name, origin, kind: secret.kind };
10971
- } finally {
10972
- await handle.dispose().catch(() => {});
10982
+ if (!cookieValue)
10983
+ return part;
10984
+ return `${cookieName}=${this.scrub(cookieValue)}`;
10985
+ }).join("; ");
10986
+ return lower === "set-cookie" ? value.split(`
10987
+ `).map(protectLine).join(`
10988
+ `) : protectLine(value);
10989
+ }
10990
+ if (lower === "location" || lower === "referer" || lower === "referrer") {
10991
+ return this.protectUrl(value);
10992
+ }
10993
+ if (lower === "authorization" || lower === "proxy-authorization") {
10994
+ const match = /^(\S+)\s+(.+)$/.exec(value);
10995
+ if (match)
10996
+ return `${match[1]} ${this.scrub(match[2] ?? "")}`;
10997
+ }
10998
+ if (secretHeaders.has(lower) || secretNamePattern.test(lower)) {
10999
+ return this.scrub(value);
11000
+ }
11001
+ return value;
11002
+ }
11003
+ protectJson(value, field, fieldName = "") {
11004
+ if (Array.isArray(value)) {
11005
+ if (field === "codeListing") {
11006
+ return value.map((item) => isString(item) ? item : this.protectJson(item, "secret", fieldName));
11007
+ }
11008
+ return value.map((item) => this.protectJson(item, field, fieldName));
11009
+ }
11010
+ if (isObject(value)) {
11011
+ const inherited = field === "codeListing" || field === "codeVoice" ? "secret" : field;
11012
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
11013
+ key,
11014
+ this.protectJson(item, jsonField(key, inherited, value.type, item), key)
11015
+ ]));
10973
11016
  }
11017
+ if (field === "open" || value === null || value === "")
11018
+ return value;
11019
+ if (field === "codeVoice" && isString(value))
11020
+ return value;
11021
+ return this.scrub(String(value), fieldName);
10974
11022
  }
11023
+ protectMultipart(body, contentType) {
11024
+ const boundary = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType)?.slice(1).find(Boolean);
11025
+ if (!boundary)
11026
+ return;
11027
+ const delimiter = `--${boundary}`;
11028
+ const parts = body.split(delimiter);
11029
+ if (parts.length < 3)
11030
+ return;
11031
+ for (let index = 1;index < parts.length - 1; index += 1) {
11032
+ const part = parts[index];
11033
+ if (!part?.startsWith(`\r
11034
+ `))
11035
+ return;
11036
+ const headerEnd = part.indexOf(`\r
11037
+ \r
11038
+ `);
11039
+ if (headerEnd < 0 || !part.endsWith(`\r
11040
+ `))
11041
+ return;
11042
+ const headers = part.slice(2, headerEnd);
11043
+ const disposition = headers.split(`\r
11044
+ `).find((line) => /^content-disposition:/i.test(line));
11045
+ if (!disposition || /;\s*filename\*?=/i.test(disposition))
11046
+ return;
11047
+ const name = /;\s*name="([^"]+)"/i.exec(disposition)?.[1];
11048
+ if (!name)
11049
+ return;
11050
+ const valueStart = headerEnd + 4;
11051
+ const valueEnd = part.length - 2;
11052
+ const value = part.slice(valueStart, valueEnd);
11053
+ if (!value || !secretNamePattern.test(name))
11054
+ continue;
11055
+ parts[index] = `${part.slice(0, valueStart)}${this.scrub(value, name)}${part.slice(valueEnd)}`;
11056
+ }
11057
+ return parts.join(delimiter);
11058
+ }
11059
+ }
11060
+ function restoreRedactionPlaceholders(value) {
11061
+ return value.replaceAll(redactionSentinel, redactedPlaceholder);
11062
+ }
11063
+ var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11064
+ function jsonField(key, inherited, type, value) {
11065
+ if (inherited === "secret")
11066
+ return "secret";
11067
+ if (!secretNamePattern.test(key))
11068
+ return inherited;
11069
+ if (key !== "code")
11070
+ return "secret";
11071
+ if (type === "codeListing" && Array.isArray(value))
11072
+ return "codeListing";
11073
+ if (type === "codeVoice" && isString(value))
11074
+ return "codeVoice";
11075
+ return "secret";
11076
+ }
11077
+ function looksLikeTokenSegment(segment) {
11078
+ if (segment.length < 24 || uuidPattern.test(segment) || segment.includes("${"))
11079
+ return false;
11080
+ if (/^eyJ[\w-]+\.[\w-]+\.[\w-]*$/.test(segment))
11081
+ return true;
11082
+ if (/^[0-9a-f]{32,}$/i.test(segment))
11083
+ return true;
11084
+ if (!/^[A-Za-z0-9_~+/-]+={0,2}$/.test(segment))
11085
+ return false;
11086
+ if (/^[a-z]+(?:[-_][a-z]+)+$/i.test(segment))
11087
+ return false;
11088
+ const hasDigit = /\d/.test(segment);
11089
+ const hasLower = /[a-z]/.test(segment);
11090
+ const hasUpper = /[A-Z]/.test(segment);
11091
+ return new Set(segment).size >= 12 && hasDigit && (hasLower || hasUpper) && (hasLower && hasUpper || segment.length >= 32);
11092
+ }
11093
+ function protectPathSegments(pathname, protect) {
11094
+ return pathname.split("/").map((segment) => {
11095
+ let decoded;
11096
+ try {
11097
+ decoded = decodeURIComponent(segment);
11098
+ } catch {
11099
+ decoded = segment;
11100
+ }
11101
+ return looksLikeTokenSegment(decoded) ? protect(decoded) : segment;
11102
+ }).join("/");
11103
+ }
11104
+ function protectRelativeUrl(rawUrl, protect, protectPath) {
11105
+ const queryStart = rawUrl.indexOf("?");
11106
+ if (queryStart < 0)
11107
+ return protectPath(rawUrl);
11108
+ const protectedQuery = protectSearchParams(new URLSearchParams(rawUrl.slice(queryStart + 1)), protect).toString();
11109
+ return restoreRedactionPlaceholders(`${protectPath(rawUrl.slice(0, queryStart))}?${protectedQuery}`);
11110
+ }
11111
+ function protectSearchParams(params, protect) {
11112
+ const result = new URLSearchParams;
11113
+ for (const [name, value] of params) {
11114
+ result.append(name, value && secretNamePattern.test(name) ? protect(name, value) : value);
11115
+ }
11116
+ return result;
11117
+ }
11118
+ function protectFragment(fragment, protect) {
11119
+ return fragment.split("&").map((part) => {
11120
+ const separator = part.indexOf("=");
11121
+ if (separator < 1)
11122
+ return part;
11123
+ const entry = new URLSearchParams(part).entries().next().value;
11124
+ if (!entry)
11125
+ return part;
11126
+ const [name, value] = entry;
11127
+ if (!/^[\w.-]+$/.test(name) || !secretNamePattern.test(name))
11128
+ return part;
11129
+ return value ? `${part.slice(0, separator + 1)}${protect(name, value)}` : part;
11130
+ }).join("&");
11131
+ }
11132
+ function redactSecretValue(value) {
11133
+ if (Array.isArray(value))
11134
+ return value.map(redactSecretValue);
11135
+ if (isObject(value)) {
11136
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactSecretValue(item)]));
11137
+ }
11138
+ return value === null || value === "" ? value : redactedPlaceholder;
10975
11139
  }
10976
-
10977
- // src/network-capture.ts
10978
- import path7 from "node:path";
10979
-
10980
- // src/network-capture/har-redaction.ts
10981
- import path6 from "node:path";
10982
11140
 
10983
11141
  // src/network-capture/types.ts
10984
11142
  var defaultNetworkCaptureMaxDurationMs = 30 * 60000;
@@ -11029,22 +11187,10 @@ function validateLimit(name, value, maximum) {
11029
11187
  }
11030
11188
 
11031
11189
  // src/network-capture/har-redaction.ts
11032
- function finishCapture(active, options, secrets, profileOptions) {
11190
+ function finishCapture(active, options) {
11033
11191
  return gen(function* () {
11034
- const existingProfile = secrets ? yield* readOptional(secrets, profileOptions) : undefined;
11035
- const collector = new SecretCollector(existingProfile?.slots ?? []);
11036
- for (const value of active.extraRedactions)
11037
- collector.addRedactionOnly(value);
11038
- const structurallyProtected = active.entries.map((entry) => protectEntry(entry, collector));
11039
- const protectedEntries = structurallyProtected.map((entry) => redactEntryKnownValues(entry, collector)).map((entry) => redactEntryTypedSecrets(entry, active.extraRedactions, collector));
11040
- if (options.requireObservedSecrets && collector.observedRefs().length === 0) {
11041
- return yield* new NetworkCaptureError({
11042
- message: `Auth refresh did not observe credentials for profile ${secrets ?? "unknown"}`,
11043
- operation: "auth-profile",
11044
- reason: "persistence-failed"
11045
- });
11046
- }
11047
- const authProfile = secrets ? yield* write({ name: secrets, slots: collector.slots(), ...profileOptions }) : undefined;
11192
+ const redactor = new SecretRedactor;
11193
+ const protectedEntries = active.entries.map((entry) => protectEntry(entry, redactor)).map((entry) => redactEntryKnownValues(entry, redactor));
11048
11194
  if (options.outputPath) {
11049
11195
  yield* writeArtifact(options.outputPath, {
11050
11196
  log: {
@@ -11055,9 +11201,6 @@ function finishCapture(active, options, secrets, profileOptions) {
11055
11201
  });
11056
11202
  }
11057
11203
  return {
11058
- ...authProfile ? { authProfile } : {},
11059
- updatedSecretRefs: collector.updatedRefs(),
11060
- observedSecretRefs: collector.observedRefs(),
11061
11204
  redactionOmissionCount: options.outputPath ? countRedactionOmissions(active.entries, protectedEntries) : 0,
11062
11205
  endpoints: summarizeEndpoints(protectedEntries)
11063
11206
  };
@@ -11091,7 +11234,7 @@ function summarizeEndpoints(entries) {
11091
11234
  const lower = h.name.toLowerCase();
11092
11235
  if (lower === "x-client-data" || lower.startsWith("sec-ch-"))
11093
11236
  return false;
11094
- return h.value.includes("${BC_SECRET_") || lower === "authorization" || lower.startsWith("x-");
11237
+ return h.value.includes("[redacted]") || lower === "authorization" || lower.startsWith("x-");
11095
11238
  }).slice(0, 8).map((h) => `${h.name}: ${h.value.slice(0, 80)}`);
11096
11239
  const requestKeys = extractTopLevelJsonKeys(entry.request.body);
11097
11240
  const responseKeys = extractTopLevelJsonKeys(entry.response?.body);
@@ -11162,20 +11305,19 @@ function truncatedBody(mimeType, active, size = 0) {
11162
11305
  active.truncatedBodyCount += 1;
11163
11306
  return { size, mimeType: mimeType ?? "application/octet-stream", truncated: true };
11164
11307
  }
11165
- function protectEntry(entry, collector) {
11166
- const scope = requestScope(entry.request.method, entry.request.url);
11167
- const requestHeaders = collector.protectHeaders(entry.request.headers, "request", scope);
11168
- const responseHeaders = entry.response ? collector.protectHeaders(entry.response.headers, "response", scope) : undefined;
11169
- const requestBody = protectCapturedBody(entry.request.body, collector, "request", scope);
11170
- const responseBody = protectCapturedBody(entry.response?.body, collector, "response", scope);
11308
+ function protectEntry(entry, redactor) {
11309
+ const requestHeaders = redactor.protectHeaders(entry.request.headers);
11310
+ const responseHeaders = entry.response ? redactor.protectHeaders(entry.response.headers) : undefined;
11311
+ const requestBody = protectCapturedBody(entry.request.body, redactor);
11312
+ const responseBody = protectCapturedBody(entry.response?.body, redactor);
11171
11313
  return {
11172
11314
  ...entry,
11173
11315
  request: {
11174
11316
  ...entry.request,
11175
- url: collector.protectUrl(entry.request.url, scope),
11317
+ url: redactor.protectUrl(entry.request.url),
11176
11318
  headers: requestHeaders,
11177
11319
  ...requestBody ? { body: requestBody } : {},
11178
- ...entry.request.redirectedFrom ? { redirectedFrom: collector.protectUrl(entry.request.redirectedFrom, scope) } : {}
11320
+ ...entry.request.redirectedFrom ? { redirectedFrom: redactor.protectUrl(entry.request.redirectedFrom) } : {}
11179
11321
  },
11180
11322
  ...entry.response ? {
11181
11323
  response: {
@@ -11186,18 +11328,18 @@ function protectEntry(entry, collector) {
11186
11328
  } : {}
11187
11329
  };
11188
11330
  }
11189
- function protectCapturedBody(body, collector, location, scope) {
11331
+ function protectCapturedBody(body, redactor) {
11190
11332
  if (!body)
11191
11333
  return;
11192
11334
  if (!body.text) {
11193
11335
  return { size: body.size, mimeType: body.mimeType, truncated: true };
11194
11336
  }
11195
- const text = collector.protectBody(body.text, body.mimeType, location, scope);
11337
+ const text = redactor.protectBody(body.text, body.mimeType);
11196
11338
  return text === undefined ? { size: body.size, mimeType: body.mimeType, truncated: true } : { ...body, text };
11197
11339
  }
11198
11340
  var minimumKnownBodySubstringLength = 16;
11199
- function redactEntryKnownValues(entry, collector) {
11200
- const redactText = (text) => collector.redactKnownSubstrings(text, minimumKnownSubstringLength);
11341
+ function redactEntryKnownValues(entry, redactor) {
11342
+ const redactText = (text) => redactor.redactKnownSubstrings(text, minimumKnownSubstringLength);
11201
11343
  const redactHeaders = (headers) => headers.map((item) => ({ ...item, value: redactText(item.value) }));
11202
11344
  return {
11203
11345
  ...entry,
@@ -11206,62 +11348,35 @@ function redactEntryKnownValues(entry, collector) {
11206
11348
  url: redactText(entry.request.url),
11207
11349
  headers: redactHeaders(entry.request.headers),
11208
11350
  ...entry.request.redirectedFrom ? { redirectedFrom: redactText(entry.request.redirectedFrom) } : {},
11209
- ...entry.request.body?.text ? { body: redactStructuredBody(entry.request.body, collector) } : {}
11351
+ ...entry.request.body?.text ? { body: redactStructuredBody(entry.request.body, redactor) } : {}
11210
11352
  },
11211
11353
  ...entry.response ? {
11212
11354
  response: {
11213
11355
  ...entry.response,
11214
11356
  headers: redactHeaders(entry.response.headers),
11215
- ...entry.response.body?.text ? { body: redactStructuredBody(entry.response.body, collector) } : {}
11357
+ ...entry.response.body?.text ? { body: redactStructuredBody(entry.response.body, redactor) } : {}
11216
11358
  }
11217
11359
  } : {}
11218
11360
  };
11219
11361
  }
11220
- function redactEntryTypedSecrets(entry, values, collector) {
11221
- if (values.size === 0)
11222
- return entry;
11223
- const redact = (text) => collector.redactValuesEverywhere(text, values);
11224
- const redactBody = (body) => body?.text ? { ...body, text: redact(body.text) } : body;
11225
- const redactHeaders = (headers) => headers.map((item) => ({ ...item, value: redact(item.value) }));
11226
- const requestBody = redactBody(entry.request.body);
11227
- const responseBody = redactBody(entry.response?.body);
11228
- return {
11229
- ...entry,
11230
- request: {
11231
- ...entry.request,
11232
- url: redact(entry.request.url),
11233
- headers: redactHeaders(entry.request.headers),
11234
- ...entry.request.redirectedFrom ? { redirectedFrom: redact(entry.request.redirectedFrom) } : {},
11235
- ...requestBody ? { body: requestBody } : {}
11236
- },
11237
- ...entry.response ? {
11238
- response: {
11239
- ...entry.response,
11240
- headers: redactHeaders(entry.response.headers),
11241
- ...responseBody ? { body: responseBody } : {}
11242
- }
11243
- } : {}
11244
- };
11245
- }
11246
- function redactStructuredBody(body, collector) {
11362
+ function redactStructuredBody(body, redactor) {
11247
11363
  if (!body.text || !body.mimeType.toLowerCase().includes("json"))
11248
11364
  return body;
11249
11365
  try {
11250
- return { ...body, text: JSON.stringify(redactKnownScalars(JSON.parse(body.text), collector)) };
11366
+ return { ...body, text: JSON.stringify(redactKnownScalars(JSON.parse(body.text), redactor)) };
11251
11367
  } catch {
11252
11368
  return { size: body.size, mimeType: body.mimeType, truncated: true };
11253
11369
  }
11254
11370
  }
11255
- function redactKnownScalars(value, collector) {
11371
+ function redactKnownScalars(value, redactor) {
11256
11372
  if (Array.isArray(value))
11257
- return value.map((item) => redactKnownScalars(item, collector));
11373
+ return value.map((item) => redactKnownScalars(item, redactor));
11258
11374
  if (isObject(value)) {
11259
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactKnownScalars(item, collector)]));
11375
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactKnownScalars(item, redactor)]));
11260
11376
  }
11261
- const exact = collector.redactExactValue(value, 8);
11262
- if (exact !== value || !isString(value))
11263
- return exact;
11264
- return collector.redactKnownSubstrings(value, minimumKnownBodySubstringLength);
11377
+ if (isString(value))
11378
+ return redactor.redactKnownSubstrings(value, minimumKnownBodySubstringLength);
11379
+ return redactor.redactValue(value);
11265
11380
  }
11266
11381
  function toHarEntry(entry) {
11267
11382
  return {
@@ -11366,24 +11481,6 @@ function safeValue(read, fallback) {
11366
11481
  return fallback;
11367
11482
  }
11368
11483
  }
11369
- function requestScope(method, rawUrl) {
11370
- let base;
11371
- try {
11372
- const url = new URL(rawUrl);
11373
- base = `${url.origin}${url.pathname}`;
11374
- } catch {
11375
- base = rawUrl.split("?", 1)[0] ?? rawUrl;
11376
- }
11377
- const scrubbed = base.split("/").map((segment) => looksLikeTokenSegment(safeDecode(segment)) ? ":token" : segment).join("/");
11378
- return `${method.toUpperCase()} ${scrubbed}`;
11379
- }
11380
- function safeDecode(segment) {
11381
- try {
11382
- return decodeURIComponent(segment);
11383
- } catch {
11384
- return segment;
11385
- }
11386
- }
11387
11484
  function contentType(headers) {
11388
11485
  return header(headers, "content-type")?.trim();
11389
11486
  }
@@ -11410,7 +11507,6 @@ class Recorder {
11410
11507
  page;
11411
11508
  pageEpoch = 0;
11412
11509
  transition = makeUnsafe(1);
11413
- extraRedactions = new Set;
11414
11510
  constructor(recorderOptions = {}) {
11415
11511
  this.recorderOptions = recorderOptions;
11416
11512
  }
@@ -11437,8 +11533,7 @@ class Recorder {
11437
11533
  entries: [],
11438
11534
  finalizeQueue: [],
11439
11535
  finalizeWaiters: new Set,
11440
- liveCollector: new SecretCollector,
11441
- extraRedactions: capture.extraRedactions,
11536
+ liveRedactor: new SecretRedactor,
11442
11537
  finalizeWorkers: 0,
11443
11538
  finalizeGeneration: 0,
11444
11539
  capturedBodyBytes: 0,
@@ -11448,8 +11543,6 @@ class Recorder {
11448
11543
  cancelled: false,
11449
11544
  outputUnsafe: false
11450
11545
  };
11451
- for (const value of capture.extraRedactions)
11452
- capture.active.liveCollector.addRedactionOnly(value);
11453
11546
  capture.bindPage(page);
11454
11547
  const active = capture.active;
11455
11548
  clearTimeout(capture.expiry);
@@ -11535,23 +11628,16 @@ class Recorder {
11535
11628
  active.droppedEntryCount += active.pending.size;
11536
11629
  capture.discardFinalizers(active);
11537
11630
  }
11538
- const secrets = options.secrets;
11539
- const profileOptions = capture.recorderOptions.authProfileBaseDir ? { baseDir: capture.recorderOptions.authProfileBaseDir } : {};
11540
- const finish = finishCapture(active, options, secrets, profileOptions);
11541
- const finished = yield* (secrets ? withLock(secrets, profileOptions, finish) : finish).pipe(mapError2((cause) => cause instanceof NetworkCaptureError ? cause : new NetworkCaptureError({ message: cause.message, operation: "auth-profile", reason: "persistence-failed", cause })));
11631
+ const finished = yield* finishCapture(active, options);
11542
11632
  const { endsAt: _endsAt, ...finalStatus } = capture.status();
11543
11633
  capture.active = undefined;
11544
11634
  clearTimeout(capture.expiry);
11545
11635
  return {
11546
11636
  ...finalStatus,
11547
- ...secrets ? { secrets } : {},
11548
11637
  truncatedBodyCount: finalStatus.truncatedBodyCount + finished.redactionOmissionCount,
11549
11638
  active: false,
11550
11639
  stoppedAt: new Date().toISOString(),
11551
11640
  ...options.outputPath ? { outputPath: path7.resolve(options.outputPath) } : {},
11552
- ...finished.authProfile ? { authProfile: finished.authProfile } : {},
11553
- updatedSecretRefs: finished.updatedSecretRefs,
11554
- observedSecretRefs: finished.observedSecretRefs,
11555
11641
  ...finished.endpoints.length > 0 ? { endpoints: finished.endpoints } : {}
11556
11642
  };
11557
11643
  }).pipe(tapError(() => sync2(() => {
@@ -11610,23 +11696,17 @@ class Recorder {
11610
11696
  return;
11611
11697
  active.outputUnsafe = !await settleFinalizers(active, this.recorderOptions.outputSettleTimeoutMs ?? 5000);
11612
11698
  }
11613
- addRedaction(value) {
11614
- if (!value)
11615
- return;
11616
- this.extraRedactions.add(value);
11617
- this.active?.liveCollector.addRedactionOnly(value);
11618
- }
11619
11699
  redactText(text) {
11620
11700
  const active = this.active;
11621
11701
  if (!active)
11622
11702
  return text;
11623
- return active.outputUnsafe ? "[REDACTED: network capture finalization pending]" : active.liveCollector.redactText(text);
11703
+ return active.outputUnsafe ? "[REDACTED: network capture finalization pending]" : active.liveRedactor.redactText(text);
11624
11704
  }
11625
11705
  redactValue(value) {
11626
11706
  const active = this.active;
11627
11707
  if (!active)
11628
11708
  return value;
11629
- return active.outputUnsafe ? "[REDACTED: network capture finalization pending]" : active.liveCollector.redactValue(value);
11709
+ return active.outputUnsafe ? "[REDACTED: network capture finalization pending]" : active.liveRedactor.redactValue(value);
11630
11710
  }
11631
11711
  redactUrl(url) {
11632
11712
  const active = this.active;
@@ -11634,7 +11714,25 @@ class Recorder {
11634
11714
  return url;
11635
11715
  if (active.outputUnsafe)
11636
11716
  return "[REDACTED: network capture finalization pending]";
11637
- return active.liveCollector.redactText(active.liveCollector.protectUrl(url, "execute"));
11717
+ return active.liveRedactor.redactUrl(url);
11718
+ }
11719
+ redactCaptureLogs(logs) {
11720
+ return logs.map((log) => ({
11721
+ ...log,
11722
+ text: this.redactText(log.text),
11723
+ ...log.location ? {
11724
+ location: { ...log.location, url: this.redactUrl(log.location.url) }
11725
+ } : {}
11726
+ }));
11727
+ }
11728
+ redactCaptureAftermath(aftermath) {
11729
+ return {
11730
+ ...aftermath,
11731
+ startUrl: aftermath.startUrl ? this.redactUrl(aftermath.startUrl) : aftermath.startUrl,
11732
+ endUrl: aftermath.endUrl ? this.redactUrl(aftermath.endUrl) : aftermath.endUrl,
11733
+ navigations: aftermath.navigations.map((url) => this.redactUrl(url)),
11734
+ ...aftermath.challenge ? { challenge: { ...aftermath.challenge, url: this.redactUrl(aftermath.challenge.url) } } : {}
11735
+ };
11638
11736
  }
11639
11737
  onRequest = (request) => {
11640
11738
  const active = this.active;
@@ -11765,7 +11863,7 @@ class Recorder {
11765
11863
  if (active.cancelled || generation !== active.finalizeGeneration)
11766
11864
  return;
11767
11865
  active.entries.push(entry);
11768
- protectEntry(entry, active.liveCollector);
11866
+ protectEntry(entry, active.liveRedactor);
11769
11867
  }
11770
11868
  unbindPage() {
11771
11869
  const page = this.page;
@@ -11822,7 +11920,6 @@ class ExecuteSandbox extends DefaultPageHost {
11822
11920
  snapshotRefs = { selectors: new Map };
11823
11921
  networkCapture = new Recorder;
11824
11922
  viewportGuardContexts = new WeakSet;
11825
- secrets;
11826
11923
  actionTimeoutContext;
11827
11924
  realm;
11828
11925
  state;
@@ -11832,11 +11929,6 @@ class ExecuteSandbox extends DefaultPageHost {
11832
11929
  ...options.pageHealthCheckTimeoutMs === undefined ? {} : { pageHealthCheckTimeoutMs: options.pageHealthCheckTimeoutMs }
11833
11930
  });
11834
11931
  this.options = options;
11835
- this.secrets = new ExecuteSecretsBridge({
11836
- networkCapture: this.networkCapture,
11837
- allowedOrigins: () => this.options.allowedOrigins?.(),
11838
- addWarningOnce: (warning) => this.addWarningOnce(warning)
11839
- });
11840
11932
  this.realm = this.allowNode ? undefined : this.createRealm();
11841
11933
  this.state = this.realm?.state ?? {};
11842
11934
  }
@@ -11882,7 +11974,7 @@ class ExecuteSandbox extends DefaultPageHost {
11882
11974
  });
11883
11975
  await this.networkCapture.settleForOutput();
11884
11976
  const extracted = extractExecuteMedia(result);
11885
- const redactedValue = this.secrets.redactOutputValue(extracted.value);
11977
+ const redactedValue = this.networkCapture.redactValue(extracted.value);
11886
11978
  const jsonSafeResult = toJsonSafeValue(redactedValue);
11887
11979
  const bounded = boundExecuteResult(stringifyResult(redactedValue), jsonSafeResult.serializable ? jsonSafeResult.value : undefined, jsonSafeResult.serializable);
11888
11980
  const warnings = this.finalizeWarnings(logSummary, jsonValueWarning(redactedValue, jsonSafeResult), bounded.warning);
@@ -11891,10 +11983,10 @@ class ExecuteSandbox extends DefaultPageHost {
11891
11983
  ...bounded.hasValue ? { value: bounded.value } : {},
11892
11984
  ...extracted.media.length > 0 ? { media: extracted.media } : {},
11893
11985
  isError: false,
11894
- logs: this.secrets.redactCaptureLogs(logs),
11986
+ logs: this.networkCapture.redactCaptureLogs(logs),
11895
11987
  logSummary,
11896
11988
  warnings,
11897
- aftermath: this.secrets.redactCaptureAftermath(aftermath)
11989
+ aftermath: this.networkCapture.redactCaptureAftermath(aftermath)
11898
11990
  };
11899
11991
  }
11900
11992
  });
@@ -11921,13 +12013,13 @@ class ExecuteSandbox extends DefaultPageHost {
11921
12013
  const closedUnderScript = (this.closedDefaultPage !== undefined || this.pendingTargetRebind === "replaced") && /has been closed/i.test(error.message);
11922
12014
  const warnings = this.finalizeWarnings(logSummary, closedUnderScript ? `${defaultPageReattachedWarning} The tab kept any navigation it made; continue from it in the next execute.` : undefined, diagnostic === protectedExtensionUiDiagnostic ? protectedExtensionUiWarning : undefined, error instanceof ExecuteCodeError ? formatNodeContextWarning(error.originalError) : undefined, error instanceof ExecuteCodeError ? formatPointerInterceptionWarning(error.originalError) : formatPointerInterceptionWarning(error), diagnostic === protectedExtensionUiDiagnostic ? undefined : formatLocatorFailurePageWarning(error instanceof ExecuteCodeError ? error.originalError : error, aftermath, this.recreatedFromClosedUrl));
11923
12015
  return {
11924
- text: this.secrets.redactOutputText(error instanceof ExecuteCodeError ? userCodeStack(error) : error.message),
12016
+ text: this.networkCapture.redactText(error instanceof ExecuteCodeError ? userCodeStack(error) : error.message),
11925
12017
  isError: true,
11926
- logs: this.secrets.redactCaptureLogs(error instanceof ExecuteCodeError ? error.logs : []),
12018
+ logs: this.networkCapture.redactCaptureLogs(error instanceof ExecuteCodeError ? error.logs : []),
11927
12019
  logSummary,
11928
12020
  warnings,
11929
- ...diagnostic ? { diagnostic: this.secrets.redactOutputText(diagnostic) } : {},
11930
- ...aftermath ? { aftermath: this.secrets.redactCaptureAftermath(aftermath) } : {},
12021
+ ...diagnostic ? { diagnostic: this.networkCapture.redactText(diagnostic) } : {},
12022
+ ...aftermath ? { aftermath: this.networkCapture.redactCaptureAftermath(aftermath) } : {},
11931
12023
  ...error instanceof ExecuteCodeError ? {} : { setupFailed: true }
11932
12024
  };
11933
12025
  },
@@ -12001,10 +12093,10 @@ class ExecuteSandbox extends DefaultPageHost {
12001
12093
  if (logCompactionWarning) {
12002
12094
  warnings.push(logCompactionWarning);
12003
12095
  }
12004
- return warnings.map((warning) => this.secrets.redactOutputText(warning));
12096
+ return warnings.map((warning) => this.networkCapture.redactText(warning));
12005
12097
  }
12006
12098
  redactNetworkCaptureText(text) {
12007
- return this.secrets.redactOutputText(text);
12099
+ return this.networkCapture.redactText(text);
12008
12100
  }
12009
12101
  stopRealm() {
12010
12102
  this.realm?.dispose(new Error("Execute stopped: the session was stopped, deleted or reset"));
@@ -12198,7 +12290,6 @@ class ExecuteSandbox extends DefaultPageHost {
12198
12290
  realm: this.realm,
12199
12291
  snapshotRefs: this.snapshotRefs,
12200
12292
  networkCapture: this.networkCapture,
12201
- secrets: this.secrets,
12202
12293
  requestHandoff: this.options.requestHandoff,
12203
12294
  isRecordingTarget: this.options.isRecordingTarget,
12204
12295
  isDefaultPage: (candidate) => candidate === this.page,
@@ -12244,27 +12335,6 @@ class ExecuteSandbox extends DefaultPageHost {
12244
12335
  networkEnd(reason) {
12245
12336
  return this.networkCapture.end(reason);
12246
12337
  }
12247
- authRefresh(options) {
12248
- const sandbox = this;
12249
- return gen(function* () {
12250
- const page = yield* sandbox.ensureSessionPage("Set up page for auth refresh");
12251
- yield* read(options.name).pipe(asVoid2);
12252
- yield* sandbox.networkCapture.start(page, {
12253
- ...options.urlFilter ? { urlFilter: options.urlFilter } : {}
12254
- });
12255
- return yield* gen(function* () {
12256
- yield* tryPromise({
12257
- try: () => page.reload({ waitUntil: "domcontentloaded", timeout: options.timeoutMs ?? 30000 }),
12258
- catch: (cause) => cause instanceof Error ? cause : new Error("Refresh auth profile", { cause })
12259
- });
12260
- yield* tryPromise({
12261
- try: () => page.waitForLoadState("networkidle", { timeout: Math.min(options.timeoutMs ?? 30000, 5000) }).catch(() => {}),
12262
- catch: (cause) => cause instanceof Error ? cause : new Error("Wait for auth refresh network", { cause })
12263
- });
12264
- return yield* sandbox.networkCapture.stop({ secrets: options.name, requireObservedSecrets: true });
12265
- }).pipe(ensuring(sandbox.networkCapture.cancel()));
12266
- }).pipe(uninterruptible);
12267
- }
12268
12338
  warnSyntheticInput() {
12269
12339
  this.addWarningOnce(syntheticInputWarning);
12270
12340
  }
@@ -12281,6 +12351,36 @@ import crypto6 from "node:crypto";
12281
12351
  import { once } from "node:events";
12282
12352
  import fs8 from "node:fs/promises";
12283
12353
 
12354
+ // src/update/child-process.ts
12355
+ async function terminateChildProcess(options) {
12356
+ const isExited = options.isExited ?? (() => options.child.exitCode !== null || options.child.signalCode !== null);
12357
+ if (isExited())
12358
+ return;
12359
+ signalChildProcess(options.child, "SIGTERM");
12360
+ let timeout;
12361
+ await Promise.race([
12362
+ options.exit,
12363
+ new Promise((resolve) => {
12364
+ timeout = setTimeout(resolve, options.graceMs);
12365
+ })
12366
+ ]);
12367
+ if (timeout)
12368
+ clearTimeout(timeout);
12369
+ if (isExited())
12370
+ return;
12371
+ signalChildProcess(options.child, "SIGKILL");
12372
+ await options.exit;
12373
+ }
12374
+ function signalChildProcess(child, signal) {
12375
+ if (process.platform !== "win32" && child.pid !== undefined) {
12376
+ try {
12377
+ process.kill(-child.pid, signal);
12378
+ return;
12379
+ } catch {}
12380
+ }
12381
+ child.kill(signal);
12382
+ }
12383
+
12284
12384
  // src/recording-relay/mjpeg-matroska.ts
12285
12385
  var ebml = Buffer.from("1A45DFA3", "hex");
12286
12386
  var ebmlVersion = Buffer.from("4286", "hex");
@@ -13234,6 +13334,202 @@ function resolveExactHandoffTarget(options) {
13234
13334
  return target;
13235
13335
  }
13236
13336
 
13337
+ // src/auth/domain-policy.ts
13338
+ import dns3 from "node:dns/promises";
13339
+ import net2 from "node:net";
13340
+
13341
+ class OriginPatternError extends Error {
13342
+ name = "OriginPatternError";
13343
+ }
13344
+ var maxPatterns = 100;
13345
+ function parseOriginPattern(raw) {
13346
+ const pattern = raw.trim();
13347
+ if (!pattern)
13348
+ throw new OriginPatternError("Empty origin pattern");
13349
+ if (pattern === "*" || pattern === "*.*")
13350
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} allows every site; leave the allowlist unset instead`);
13351
+ const schemeMatch = /^([a-z][a-z0-9+.-]*):\/\//i.exec(pattern);
13352
+ const scheme = schemeMatch?.[1]?.toLowerCase();
13353
+ if (scheme !== undefined && scheme !== "http" && scheme !== "https") {
13354
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: only http and https origins can be allowed`);
13355
+ }
13356
+ let rest = schemeMatch ? pattern.slice(schemeMatch[0].length) : pattern;
13357
+ if (/[/?#]/.test(rest.replace(/\/$/, "")))
13358
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} must be a host or origin, without a path`);
13359
+ rest = rest.replace(/\/$/, "");
13360
+ const wildcard = rest.startsWith("*.");
13361
+ if (wildcard)
13362
+ rest = rest.slice(2);
13363
+ if (rest.includes("*"))
13364
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: a wildcard is only allowed as a leading "*."`);
13365
+ let parsed;
13366
+ try {
13367
+ parsed = new URL(`${scheme ?? "http"}://${rest}`);
13368
+ } catch {
13369
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} is not a valid host or origin`);
13370
+ }
13371
+ if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || !parsed.hostname) {
13372
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} must be a host or origin`);
13373
+ }
13374
+ const host = unbracket(parsed.hostname.toLowerCase());
13375
+ if (wildcard && net2.isIP(host))
13376
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: wildcards don't apply to IP addresses`);
13377
+ if (wildcard && !host.includes("."))
13378
+ throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: "*." needs a domain with a dot, like *.example.com`);
13379
+ const port = parsed.port || (scheme ? scheme === "https" ? "443" : "80" : undefined);
13380
+ return {
13381
+ pattern,
13382
+ ...scheme ? { scheme: `${scheme}:` } : {},
13383
+ host,
13384
+ wildcard,
13385
+ ...port ? { port } : {}
13386
+ };
13387
+ }
13388
+ function parseOriginPatterns(raw) {
13389
+ if (raw.length > maxPatterns)
13390
+ throw new OriginPatternError(`At most ${maxPatterns} origin patterns are allowed`);
13391
+ return raw.map(parseOriginPattern);
13392
+ }
13393
+ function normalizeOriginPatterns(raw) {
13394
+ return Array.from(new Set(parseOriginPatterns(raw.flatMap((entry) => entry.split(",")).map((entry) => entry.trim()).filter(Boolean)).map((rule) => rule.pattern.toLowerCase())));
13395
+ }
13396
+ function unbracket(host) {
13397
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
13398
+ }
13399
+ function ipv4ToNumber(ip) {
13400
+ return ip.split(".").reduce((value, part) => value * 256 + Number(part), 0);
13401
+ }
13402
+ var privateIpv4Ranges = [
13403
+ ["0.0.0.0", 8],
13404
+ ["10.0.0.0", 8],
13405
+ ["100.64.0.0", 10],
13406
+ ["127.0.0.0", 8],
13407
+ ["169.254.0.0", 16],
13408
+ ["172.16.0.0", 12],
13409
+ ["192.0.0.0", 24],
13410
+ ["192.0.2.0", 24],
13411
+ ["192.168.0.0", 16],
13412
+ ["198.18.0.0", 15],
13413
+ ["198.51.100.0", 24],
13414
+ ["203.0.113.0", 24],
13415
+ ["224.0.0.0", 4],
13416
+ ["240.0.0.0", 4]
13417
+ ];
13418
+ function isPrivateAddress(address) {
13419
+ const ip = unbracket(address.toLowerCase()).replace(/%.*$/, "");
13420
+ if (net2.isIPv4(ip)) {
13421
+ const value = ipv4ToNumber(ip);
13422
+ return privateIpv4Ranges.some(([base, bits]) => {
13423
+ const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
13424
+ return (value & mask) >>> 0 === (ipv4ToNumber(base) & mask) >>> 0;
13425
+ });
13426
+ }
13427
+ if (net2.isIPv6(ip)) {
13428
+ if (ip === "::" || ip === "::1")
13429
+ return true;
13430
+ const mapped = /^(?:0*:)*:?ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip) ?? /^::(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
13431
+ if (mapped?.[1])
13432
+ return isPrivateAddress(mapped[1]);
13433
+ const hexMapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(ip);
13434
+ if (hexMapped?.[1] && hexMapped[2]) {
13435
+ const high = parseInt(hexMapped[1], 16);
13436
+ const low = parseInt(hexMapped[2], 16);
13437
+ return isPrivateAddress(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
13438
+ }
13439
+ const first = parseInt(ip.split(":")[0] || "0", 16);
13440
+ if ((first & 65024) === 64512 || (first & 65472) === 65152 || (first & 65280) === 65280)
13441
+ return true;
13442
+ if (ip.startsWith("64:ff9b::"))
13443
+ return true;
13444
+ return false;
13445
+ }
13446
+ return false;
13447
+ }
13448
+ function isLocalhostName(host) {
13449
+ return host === "localhost" || host.endsWith(".localhost") || host === "localhost.localdomain";
13450
+ }
13451
+ function isPrivateHost(host) {
13452
+ const bare = unbracket(host.toLowerCase());
13453
+ return isLocalhostName(bare) || net2.isIP(bare) !== 0 && isPrivateAddress(bare);
13454
+ }
13455
+ function defaultPort(protocol) {
13456
+ return protocol === "https:" ? "443" : "80";
13457
+ }
13458
+ function ruleMatches(rule, url, host, options) {
13459
+ if (rule.scheme !== undefined && rule.scheme !== url.protocol)
13460
+ return false;
13461
+ if (rule.scheme === undefined && options.httpsOnlyWithoutScheme && url.protocol !== "https:" && !isPrivateHost(host))
13462
+ return false;
13463
+ if (rule.port !== undefined && rule.port !== (url.port || defaultPort(url.protocol)))
13464
+ return false;
13465
+ if (rule.wildcard)
13466
+ return host === rule.host || host.endsWith(`.${rule.host}`);
13467
+ return host === rule.host;
13468
+ }
13469
+ function explicitlyAllowsHost(rules, url) {
13470
+ try {
13471
+ const parsed = new URL(url);
13472
+ const host = unbracket(parsed.hostname.toLowerCase());
13473
+ return rules.some((rule) => !rule.wildcard && ruleMatches(rule, parsed, host, {}));
13474
+ } catch {
13475
+ return false;
13476
+ }
13477
+ }
13478
+ var neutralSchemes = new Set(["about:", "data:", "blob:"]);
13479
+ function checkUrl(rawUrl, rules, options = {}) {
13480
+ let url;
13481
+ try {
13482
+ url = new URL(rawUrl);
13483
+ } catch {
13484
+ return { allowed: false, reason: `${JSON.stringify(rawUrl.slice(0, 200))} is not a valid URL` };
13485
+ }
13486
+ if (neutralSchemes.has(url.protocol))
13487
+ return { allowed: true };
13488
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
13489
+ return { allowed: false, reason: `${url.protocol} URLs are not allowed for this session` };
13490
+ }
13491
+ const host = unbracket(url.hostname.toLowerCase());
13492
+ const matching = rules.filter((rule) => ruleMatches(rule, url, host, options));
13493
+ if (matching.length === 0) {
13494
+ return { allowed: false, reason: `${url.host} is not in the allowed origins (${rules.map((rule) => rule.pattern).join(", ") || "none"})` };
13495
+ }
13496
+ const explicit = matching.some((rule) => !rule.wildcard);
13497
+ if (isPrivateHost(host) && !explicit) {
13498
+ return { allowed: false, reason: `${url.host} is a private, loopback or local address; allow it by naming that exact host` };
13499
+ }
13500
+ return { allowed: true, host, explicit };
13501
+ }
13502
+ async function resolvesToPrivateAddress(host, timeoutMs = 2000) {
13503
+ const bare = unbracket(host);
13504
+ if (net2.isIP(bare) || isLocalhostName(bare))
13505
+ return isPrivateHost(bare) ? bare : undefined;
13506
+ let timer;
13507
+ try {
13508
+ const addresses = await Promise.race([
13509
+ dns3.lookup(bare, { all: true, verbatim: true }),
13510
+ new Promise((_, reject) => {
13511
+ timer = setTimeout(() => reject(new Error("DNS lookup timed out")), timeoutMs);
13512
+ })
13513
+ ]);
13514
+ return addresses.find((entry) => isPrivateAddress(entry.address))?.address;
13515
+ } catch {
13516
+ return;
13517
+ } finally {
13518
+ if (timer)
13519
+ clearTimeout(timer);
13520
+ }
13521
+ }
13522
+ async function checkNavigationUrl(rawUrl, rules) {
13523
+ const decision = checkUrl(rawUrl, rules);
13524
+ if (!decision.allowed || decision.host === undefined || decision.explicit)
13525
+ return decision;
13526
+ const privateAddress = await resolvesToPrivateAddress(decision.host);
13527
+ if (privateAddress) {
13528
+ return { allowed: false, reason: `${decision.host} resolves to the private address ${privateAddress}; allow it by naming that exact host` };
13529
+ }
13530
+ return decision;
13531
+ }
13532
+
13237
13533
  // src/relay/lifecycle-log.ts
13238
13534
  import fs10 from "node:fs";
13239
13535
  import path10 from "node:path";
@@ -14366,9 +14662,6 @@ class OpenCodeBrowserSessions {
14366
14662
  networkCancel(id) {
14367
14663
  return this.withSessionOperation(id, "network cancel", (session) => session.sandbox.networkCancel());
14368
14664
  }
14369
- authRefresh(id, options) {
14370
- return this.withSessionOperation(id, "auth refresh", (session) => session.sandbox.authRefresh(options));
14371
- }
14372
14665
  withSessionOperation(id, operation, use, beforePermit) {
14373
14666
  const manager = this;
14374
14667
  return this.admission.withAdmission(id, suspend2(() => {
@@ -14723,10 +15016,6 @@ function relayHttpError(error) {
14723
15016
  const [status, code] = value(error.reason).pipe(when("invalid-options", () => [400, "invalid-request"]), when("already-active", () => [409, "capture-conflict"]), when("inactive", () => [409, "capture-conflict"]), orElse(() => [500, "internal"]));
14724
15017
  return routeError(error.message, status, code);
14725
15018
  }
14726
- if (error instanceof AuthProfileError) {
14727
- const [status, code] = value(error.reason).pipe(when("invalid-name", () => [400, "invalid-request"]), when("not-found", () => [404, "auth-profile-not-found"]), orElse(() => [500, "internal"]));
14728
- return routeError(error.message, status, code);
14729
- }
14730
15019
  if (error instanceof AuthenticatedOriginError) {
14731
15020
  return routeError(error.message, error.reason === "invalid-request" ? 400 : 500, error.reason === "invalid-request" ? "invalid-request" : "setup-failed");
14732
15021
  }
@@ -15767,27 +16056,6 @@ function handleNetworkRequest(options) {
15767
16056
  sendNotFound(options.response);
15768
16057
  });
15769
16058
  }
15770
- function handleAuthRequest(options) {
15771
- return gen(function* () {
15772
- if (options.pathname === "/auth/status" && options.request.method === "POST") {
15773
- const request = yield* decodeRequest(AuthProfileRequest, yield* readJsonBody2(options.request), "auth status");
15774
- sendJson2(options.response, yield* status(request.name));
15775
- return;
15776
- }
15777
- if (options.pathname === "/auth/refresh" && options.request.method === "POST") {
15778
- const request = yield* decodeRequest(AuthRefreshRequest, yield* readJsonBody2(options.request), "auth refresh");
15779
- const { sessionId, ...refreshOptions } = request;
15780
- sendJson2(options.response, yield* options.sessions.authRefresh(sessionId, refreshOptions));
15781
- return;
15782
- }
15783
- if (options.pathname === "/auth/run" && options.request.method === "POST") {
15784
- const request = yield* decodeRequest(AuthRunRequest, yield* readJsonBody2(options.request), "auth run");
15785
- sendJson2(options.response, yield* run(request));
15786
- return;
15787
- }
15788
- sendNotFound(options.response);
15789
- });
15790
- }
15791
16059
  function handleCliRequest(options) {
15792
16060
  return gen(function* () {
15793
16061
  if (options.pathname === "/cli/sessions" && options.request.method === "GET") {
@@ -16023,10 +16291,6 @@ function createHttpRequestHandler(options) {
16023
16291
  run(handleNetworkRequest({ request, response, pathname, sessions: options.sessions }));
16024
16292
  return;
16025
16293
  }
16026
- if (pathname.startsWith("/auth/")) {
16027
- run(handleAuthRequest({ request, response, pathname, sessions: options.sessions }), pathname === "/auth/run");
16028
- return;
16029
- }
16030
16294
  if (pathname.startsWith("/v1/")) {
16031
16295
  run(handleClientRequest({
16032
16296
  request,
@@ -17327,6 +17591,7 @@ function createExtensionEventHandler(options) {
17327
17591
  sendDebuggerCommand,
17328
17592
  sendExtensionBestEffort,
17329
17593
  applyExtensionSettings,
17594
+ relaySettingsReady,
17330
17595
  hasUpdateNotice,
17331
17596
  sendUpdateNotice,
17332
17597
  announceTab,
@@ -17514,6 +17779,7 @@ function createExtensionEventHandler(options) {
17514
17779
  if (known.browser === link.key)
17515
17780
  ownersAcrossReconnect.delete(targetId);
17516
17781
  link.rpc.markReady();
17782
+ relaySettingsReady(link);
17517
17783
  if (hasUpdateNotice())
17518
17784
  sendUpdateNotice();
17519
17785
  for (const target of registry.listRootTargets())
@@ -18459,9 +18725,9 @@ function createRelaySettingsSync(options) {
18459
18725
  ...human === undefined ? {} : { humanInput: human ? "on" : "off" }
18460
18726
  };
18461
18727
  };
18462
- const sendRelaySettings = () => {
18728
+ const sendRelaySettings = (only) => {
18463
18729
  for (const link of browsers.list()) {
18464
- if (!link.rpc.connected)
18730
+ if (only && link !== only || !link.rpc.connected)
18465
18731
  continue;
18466
18732
  sendExtensionBestEffort({
18467
18733
  method: "relay.settings",
@@ -18483,7 +18749,16 @@ function createRelaySettingsSync(options) {
18483
18749
  }
18484
18750
  relayLog("extension.settings", { browser: link.id, cursor: ghostCursorEnv ?? link.cursor ? "always" : "off", humanInput: humanInputEnabled(link.humanInput) ? "on" : "off" });
18485
18751
  ghostCursor.refresh();
18486
- sendRelaySettings();
18752
+ if (link.rpc.connected)
18753
+ sendRelaySettings();
18754
+ else
18755
+ link.pendingRelaySettings = true;
18756
+ };
18757
+ const relaySettingsReady = (link) => {
18758
+ if (!link.pendingRelaySettings)
18759
+ return;
18760
+ link.pendingRelaySettings = false;
18761
+ sendRelaySettings(link);
18487
18762
  };
18488
18763
  const httpSettings = {
18489
18764
  get: () => extensionSettings("settings.get").pipe(map6((stored) => describeSettings(withRelaySettings(stored), userSettingOverrides()))),
@@ -18509,6 +18784,7 @@ function createRelaySettingsSync(options) {
18509
18784
  };
18510
18785
  return {
18511
18786
  applyExtensionSettings,
18787
+ relaySettingsReady,
18512
18788
  sendRelaySettings,
18513
18789
  httpSettings
18514
18790
  };
@@ -19742,7 +20018,6 @@ var makeRelay = fnUntraced(function* (options = {}) {
19742
20018
  authToken,
19743
20019
  sessionId: id,
19744
20020
  onDefaultTargetChange,
19745
- allowedOrigins: () => sessions.allowedOrigins(id),
19746
20021
  drainGuardWarnings: () => navigationGuard.drainWarnings(id),
19747
20022
  cpuScheduler: sessions.cpuScheduler,
19748
20023
  isRecordingTarget: (targetId) => {
@@ -20129,6 +20404,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
20129
20404
  sendDebuggerCommand,
20130
20405
  sendExtensionBestEffort,
20131
20406
  applyExtensionSettings: settingsSync.applyExtensionSettings,
20407
+ relaySettingsReady: settingsSync.relaySettingsReady,
20132
20408
  hasUpdateNotice: () => updates.current !== undefined,
20133
20409
  sendUpdateNotice,
20134
20410
  announceTab,