@opencode/browse 0.0.17-dev.184 → 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-c7zk5z3d.mjs → cli-7289awyd.mjs} +39 -222
  3. package/dist/cli.mjs +19 -16
  4. package/dist/{helpers-2z6753nv.mjs → helpers-21yzw670.mjs} +1 -1
  5. package/dist/{index-gjq7chrk.mjs → index-4tw494gw.mjs} +2 -2
  6. package/dist/{legacy-runtime-ywz3g2n8.mjs → legacy-runtime-ytvtb4p6.mjs} +10 -8
  7. package/dist/{main-m45zegrn.mjs → main-0h387a1q.mjs} +1 -6
  8. package/dist/{main-b3n584bp.mjs → main-3ymzbg04.mjs} +30 -47
  9. package/dist/{main-pweq8vqv.mjs → main-7y134fzj.mjs} +26 -157
  10. package/dist/{main-8sn293dr.mjs → main-81fht5nj.mjs} +18 -16
  11. package/dist/{main-6hvv25x8.mjs → main-8xd753k5.mjs} +1 -1
  12. package/dist/{main-t29t4z9q.mjs → main-97vjgp95.mjs} +2 -2
  13. package/dist/{main-5p5ccmye.mjs → main-czz5kqq9.mjs} +2 -2
  14. package/dist/{main-62n1hcda.mjs → main-ghh2tvn1.mjs} +3 -3
  15. package/dist/{main-akpa411k.mjs → main-gmhbkamn.mjs} +118 -2
  16. package/dist/{main-jy92xsx2.mjs → main-gnfmgnwj.mjs} +15 -18
  17. package/dist/{main-4y0ebwtf.mjs → main-hv8t6206.mjs} +8 -6
  18. package/dist/{main-9frwnsnf.mjs → main-j4kq90pw.mjs} +1 -1
  19. package/dist/{main-a65k2jvs.mjs → main-ns026dfw.mjs} +5 -46
  20. package/dist/{main-jeta10c6.mjs → main-qjr69cgp.mjs} +8 -8
  21. package/dist/{main-wk9g7869.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-bprn8bde.mjs → main-z3txr4wt.mjs} +6 -6
  26. package/dist/{mcp-qhe69x59.mjs → mcp-gqnkhtt0.mjs} +121 -230
  27. package/dist/{migrate-8b015c1q.mjs → migrate-der69rr4.mjs} +14 -7
  28. package/dist/{relay-x5bbrs68.mjs → relay-32ed2ae2.mjs} +763 -368
  29. package/dist/remove-stored-secrets-58r3xd1b.mjs +6 -0
  30. package/dist/{runtime-update-07b127we.mjs → runtime-update-3v5znrk0.mjs} +13 -11
  31. package/dist/{setup-7a2dr5pd.mjs → setup-tzttzgb4.mjs} +25 -47
  32. package/dist/{skill-text-1rg5b5np.mjs → skill-text-0ndr12dz.mjs} +7 -31
  33. package/dist/{supervisor-sjxe3hda.mjs → supervisor-84gbxv46.mjs} +8 -6
  34. package/dist/{update-ya63f9v3.mjs → update-exnjhpqb.mjs} +3 -3
  35. package/dist/{version-p0229yf3.mjs → version-h0n5h8j4.mjs} +1 -1
  36. package/package.json +1 -1
  37. package/skills/browse/SKILL.md +7 -31
  38. package/dist/main-ayhsjnxa.mjs +0 -1324
  39. package/dist/main-yp8nt4dh.mjs +0 -4
@@ -4,23 +4,8 @@ import {
4
4
  import {
5
5
  opencodeBrowserVersion2,
6
6
  opencodeBrowserBuildId2
7
- } from "./main-yp8nt4dh.mjs";
7
+ } from "./main-xz6gd1xb.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-pweq8vqv.mjs";
29
+ } from "./main-7y134fzj.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-a65k2jvs.mjs";
80
+ } from "./main-ns026dfw.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-wk9g7869.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-ayhsjnxa.mjs";
98
+ } from "./main-vw7jwd0n.mjs";
140
99
  import {
141
100
  defaultJournalBaseDir,
142
101
  makeJournalEntry,
143
102
  appendJournalEntry,
144
103
  startJournalRetention
145
- } from "./main-bprn8bde.mjs";
104
+ } from "./main-z3txr4wt.mjs";
146
105
  import {
147
106
  createUpdateWatcher2
148
- } from "./main-4y0ebwtf.mjs";
107
+ } from "./main-hv8t6206.mjs";
149
108
  import {
150
109
  SettingsInputError,
151
110
  parseSettingChanges,
@@ -153,20 +112,21 @@ import {
153
112
  settingsToExtension,
154
113
  describeSettings,
155
114
  describeChanges
156
- } from "./main-b3n584bp.mjs";
115
+ } from "./main-3ymzbg04.mjs";
157
116
  import {
158
117
  relayHostname,
159
118
  isLocalPeer,
160
119
  installedDevExtension,
161
120
  syncDevExtension
162
- } from "./main-62n1hcda.mjs";
121
+ } from "./main-ghh2tvn1.mjs";
163
122
  import {
164
123
  currentTimeMillis,
124
+ makeUnsafe,
165
125
  value,
166
126
  when,
167
127
  orElse,
168
128
  exhaustive
169
- } from "./main-akpa411k.mjs";
129
+ } from "./main-gmhbkamn.mjs";
170
130
  import {
171
131
  map,
172
132
  withDefault,
@@ -176,18 +136,18 @@ import {
176
136
  Boolean2,
177
137
  appendManagedRelayProcessLog,
178
138
  relayLog
179
- } from "./main-jy92xsx2.mjs";
139
+ } from "./main-gnfmgnwj.mjs";
180
140
  import {
181
141
  relayTokenQueryParam,
182
142
  relayToken,
183
143
  secretsEqual,
184
144
  ensurePrivateDirectory
185
- } from "./main-5p5ccmye.mjs";
145
+ } from "./main-czz5kqq9.mjs";
186
146
  import {
187
147
  join,
188
148
  interrupt,
189
149
  makeUnsafe2
190
- } from "./main-jeta10c6.mjs";
150
+ } from "./main-qjr69cgp.mjs";
191
151
  import {
192
152
  configuredRelayPort,
193
153
  relayPortPinned,
@@ -195,7 +155,7 @@ import {
195
155
  writeRelayState,
196
156
  removeRelayState,
197
157
  chooseRelayPort
198
- } from "./main-t29t4z9q.mjs";
158
+ } from "./main-97vjgp95.mjs";
199
159
  import {
200
160
  taggedEnum,
201
161
  is2,
@@ -216,7 +176,7 @@ import {
216
176
  Int2,
217
177
  Defect,
218
178
  TaggedError2
219
- } from "./main-6hvv25x8.mjs";
179
+ } from "./main-8xd753k5.mjs";
220
180
  import {
221
181
  isString,
222
182
  isNumber,
@@ -303,7 +263,24 @@ import {
303
263
  runSync,
304
264
  fnUntraced,
305
265
  fn
306
- } from "./main-m45zegrn.mjs";
266
+ } from "./main-0h387a1q.mjs";
267
+ import {
268
+ defaultRoots,
269
+ configRoot2,
270
+ dataRoot,
271
+ stateRoot,
272
+ cacheRoot,
273
+ installedBinaryPath,
274
+ installerBinaryPath,
275
+ oldStoreMarker,
276
+ fromCheckout,
277
+ cliCommand,
278
+ PUBLIC_STORE_ID,
279
+ storeConfig,
280
+ devExtension,
281
+ storeUrl,
282
+ installCommand
283
+ } from "./main-wq3rxzcg.mjs";
307
284
 
308
285
  // src/relay.ts
309
286
  import crypto10 from "node:crypto";
@@ -695,12 +672,15 @@ var ClientCdpSessionAlias = taggedEnum();
695
672
  class CdpClientPool {
696
673
  send;
697
674
  retired;
675
+ onInterceptionEmpty;
698
676
  states = new Map;
677
+ interceptionOwners = new Map;
699
678
  nextAliasId = 1;
700
679
  connectionGeneration = 0;
701
- constructor(send, retired) {
680
+ constructor(send, retired, onInterceptionEmpty = () => {}) {
702
681
  this.send = send;
703
682
  this.retired = retired;
683
+ this.onInterceptionEmpty = onInterceptionEmpty;
704
684
  }
705
685
  register(client, opencodeBrowserSessionId, kind = "raw") {
706
686
  if (this.states.has(client))
@@ -714,10 +694,47 @@ class CdpClientPool {
714
694
  this.connectionGeneration += 1;
715
695
  }
716
696
  unregister(client) {
717
- if (!this.states.delete(client) || this.states.size !== 0)
697
+ const registered = this.states.delete(client);
698
+ this.dropClientInterceptions(client);
699
+ if (!registered || this.states.size !== 0)
718
700
  return;
719
701
  return ++this.connectionGeneration;
720
702
  }
703
+ markInterceptionOwner(client, tabId, sessionId) {
704
+ if (!this.states.has(client))
705
+ return;
706
+ const sessions = this.interceptionOwners.get(tabId) ?? new Map;
707
+ const owners = sessions.get(sessionId) ?? new Set;
708
+ owners.add(client);
709
+ sessions.set(sessionId, owners);
710
+ this.interceptionOwners.set(tabId, sessions);
711
+ }
712
+ hasInterceptionOwner(tabId, sessionId) {
713
+ return (this.interceptionOwners.get(tabId)?.get(sessionId)?.size ?? 0) > 0;
714
+ }
715
+ hasInterceptionOwners(tabId) {
716
+ const sessions = this.interceptionOwners.get(tabId);
717
+ if (!sessions)
718
+ return false;
719
+ for (const owners of sessions.values())
720
+ if (owners.size > 0)
721
+ return true;
722
+ return false;
723
+ }
724
+ clearInterceptionOwner(client, tabId, sessionId, releaseTab = true) {
725
+ const sessions = this.interceptionOwners.get(tabId);
726
+ const owners = sessions?.get(sessionId);
727
+ if (!sessions || !owners?.delete(client))
728
+ return;
729
+ if (owners.size === 0)
730
+ sessions.delete(sessionId);
731
+ if (sessions.size > 0)
732
+ return;
733
+ if (releaseTab)
734
+ this.dropInterceptionTab(tabId);
735
+ else
736
+ this.interceptionOwners.delete(tabId);
737
+ }
721
738
  get size() {
722
739
  return this.states.size;
723
740
  }
@@ -771,12 +788,14 @@ class CdpClientPool {
771
788
  this.detachSession(client, state, announced.sessionId, options);
772
789
  }
773
790
  }
791
+ this.dropInterceptionTab(tabId);
774
792
  }
775
793
  detachTarget(target, options = {}) {
776
794
  for (const [client, state] of this.states) {
777
795
  this.removeTargetAliases(state, (alias) => alias.targetId === target.targetInfo.targetId);
778
796
  this.detachSession(client, state, target.sessionId, options);
779
797
  }
798
+ this.dropInterceptionSession(target.tabId, target.sessionId);
780
799
  }
781
800
  pruneInvisible(client, canSeeTab) {
782
801
  const state = this.requireState(client);
@@ -833,6 +852,8 @@ class CdpClientPool {
833
852
  if (!announced)
834
853
  return;
835
854
  state.announcements.delete(sessionId);
855
+ if (announced.parentSessionId === undefined)
856
+ this.dropClientTabInterception(client, announced.tabId);
836
857
  this.removeTargetAliases(state, (alias) => alias.targetId === announced.targetId);
837
858
  for (const child of state.announcements.values()) {
838
859
  if (child.parentSessionId === sessionId)
@@ -850,6 +871,34 @@ class CdpClientPool {
850
871
  params: { sessionId, targetId: announced.targetId }
851
872
  });
852
873
  }
874
+ dropClientTabInterception(client, tabId) {
875
+ const sessions = this.interceptionOwners.get(tabId);
876
+ if (!sessions)
877
+ return;
878
+ for (const [sessionId, owners] of sessions) {
879
+ owners.delete(client);
880
+ if (owners.size === 0)
881
+ sessions.delete(sessionId);
882
+ }
883
+ if (sessions.size === 0)
884
+ this.dropInterceptionTab(tabId);
885
+ }
886
+ dropClientInterceptions(client) {
887
+ for (const tabId of Array.from(this.interceptionOwners.keys()))
888
+ this.dropClientTabInterception(client, tabId);
889
+ }
890
+ dropInterceptionSession(tabId, sessionId) {
891
+ const sessions = this.interceptionOwners.get(tabId);
892
+ if (!sessions?.delete(sessionId))
893
+ return;
894
+ if (sessions.size === 0)
895
+ this.dropInterceptionTab(tabId);
896
+ }
897
+ dropInterceptionTab(tabId) {
898
+ if (!this.interceptionOwners.delete(tabId))
899
+ return;
900
+ this.onInterceptionEmpty(tabId);
901
+ }
853
902
  removeTargetAliases(state, matches) {
854
903
  for (const [aliasId, alias] of state.aliases) {
855
904
  if (ClientCdpSessionAlias.$is("Target")(alias) && matches(alias))
@@ -1583,6 +1632,8 @@ function errorCauses(cause) {
1583
1632
 
1584
1633
  // src/cdp/runtime.ts
1585
1634
  var maxCachedContexts = 512;
1635
+ var interceptionReleaseTimeout = "3 seconds";
1636
+ var interceptionReleaseConcurrency = 4;
1586
1637
  var routeSessionId = (route) => route.chromeSessionId ?? route.rootSessionId;
1587
1638
  var disableKey = (tabId, chromeSessionId) => `${tabId}:${chromeSessionId ?? "root"}`;
1588
1639
  var contextAux = (event) => getObject2(getObject2(event.params?.context)?.auxData);
@@ -1757,20 +1808,37 @@ class CdpRuntime {
1757
1808
  return first.result;
1758
1809
  });
1759
1810
  disableIdle = fn("CdpRuntime.disableIdle")(function* (stillIdle) {
1760
- const { registry } = this.options;
1761
- const routes = registry.listRootTargets().map((target) => ({ tabId: target.tabId, rootSessionId: target.sessionId }));
1762
- for (const target of registry.childTargets.values()) {
1763
- const root = registry.tabTargets.get(target.tabId);
1764
- if (root)
1765
- routes.push({ tabId: target.tabId, rootSessionId: root.sessionId, chromeSessionId: target.sessionId });
1766
- }
1767
- const targets = routes.map((route) => ({ route, current: this.capture(route) }));
1811
+ const targets = this.routes().map((route) => ({ route, current: this.capture(route) }));
1768
1812
  for (const { route, current } of targets) {
1769
1813
  if (!stillIdle())
1770
1814
  break;
1771
1815
  yield* this.reset(route, "Runtime.disable", {}, () => stillIdle() && current());
1772
1816
  }
1773
1817
  });
1818
+ releaseInterception = fn("CdpRuntime.releaseInterception")(function* (tabIds, shouldRelease) {
1819
+ yield* forEach(Array.from(new Set(tabIds)), (tabId) => suspend2(() => {
1820
+ if (!shouldRelease(tabId))
1821
+ return void_3;
1822
+ const targets = this.routes(new Set([tabId])).map((route) => ({ route, current: this.capture(route) }));
1823
+ return forEach(targets, ({ route, current }) => {
1824
+ if (!shouldRelease(tabId))
1825
+ return void_3;
1826
+ return this.reset(route, "Fetch.disable", {}, () => shouldRelease(tabId) && current()).pipe(timeoutOption(interceptionReleaseTimeout));
1827
+ }, { concurrency: "unbounded", discard: true });
1828
+ }), { concurrency: interceptionReleaseConcurrency, discard: true });
1829
+ });
1830
+ routes(tabIds) {
1831
+ const { registry } = this.options;
1832
+ const routes = registry.listRootTargets().filter((target) => tabIds === undefined || tabIds.has(target.tabId)).map((target) => ({ tabId: target.tabId, rootSessionId: target.sessionId }));
1833
+ for (const target of registry.childTargets.values()) {
1834
+ if (tabIds !== undefined && !tabIds.has(target.tabId))
1835
+ continue;
1836
+ const root = registry.tabTargets.get(target.tabId);
1837
+ if (root)
1838
+ routes.push({ tabId: target.tabId, rootSessionId: root.sessionId, chromeSessionId: target.sessionId });
1839
+ }
1840
+ return routes;
1841
+ }
1774
1842
  replayCached(client, route, frameId) {
1775
1843
  const cache = this.contexts.get(routeSessionId(route));
1776
1844
  const contexts = cache?.current() ? cache.contexts : undefined;
@@ -1812,10 +1880,11 @@ class CdpRuntime {
1812
1880
  return suspend2(() => {
1813
1881
  if (!current())
1814
1882
  return void_3;
1815
- this.trace(route, `runtime-reset command=${method}`);
1883
+ const trace = method === "Fetch.disable" ? "fetch-release" : "runtime-reset";
1884
+ this.trace(route, `${trace} command=${method}`);
1816
1885
  return this.options.send({ tabId: route.tabId, method, params, ...route.chromeSessionId === undefined ? {} : { sessionId: route.chromeSessionId } }).pipe(match4({
1817
- onFailure: (error) => this.trace(route, `runtime-reset command=${method} outcome=failed failure=${runtimeFailureKind(error)}`),
1818
- onSuccess: () => this.trace(route, `runtime-reset command=${method} outcome=ok`)
1886
+ onFailure: (error) => this.trace(route, `${trace} command=${method} outcome=failed failure=${runtimeFailureKind(error)}`),
1887
+ onSuccess: () => this.trace(route, `${trace} command=${method} outcome=ok`)
1819
1888
  }));
1820
1889
  });
1821
1890
  }
@@ -7053,8 +7122,7 @@ var sandboxGlobalKeys = [
7053
7122
  "handoff",
7054
7123
  "demonstrate",
7055
7124
  "network",
7056
- "pageConsole",
7057
- "secrets"
7125
+ "pageConsole"
7058
7126
  ];
7059
7127
  async function runUserCode({ code, globals, realm, onUnhandledRejection }) {
7060
7128
  const logCapture = createExecuteLogCapture();
@@ -8011,7 +8079,7 @@ function formatDemonstrationCode(options) {
8011
8079
  ...options.steps.map((step) => value(step).pipe(when({ kind: "navigation" }, ({ url }) => `// Navigated to ${url}`), when({ kind: "click" }, ({ selector, role, name }) => {
8012
8080
  const description = role && name ? ` // ${role} ${JSON.stringify(name)}` : "";
8013
8081
  return `await page.locator(${JSON.stringify(selector)}).click()${description}`;
8014
- }), 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)),
8015
8083
  "return { url: page.url(), title: await page.title() }"
8016
8084
  ];
8017
8085
  return lines.join(`
@@ -10745,55 +10813,111 @@ function buildSandboxGlobals(deps) {
10745
10813
  start: (target) => start(target ?? page),
10746
10814
  stop: (target) => stop(target ?? page)
10747
10815
  },
10748
- secrets: {
10749
- type: (target, name, typeOptions) => deps.secrets.typeSecret(page, target, name, typeOptions)
10750
- },
10751
10816
  handoffTracker
10752
10817
  };
10753
10818
  }
10754
10819
 
10755
- // src/execute/secrets-bridge.ts
10756
- var isOpaqueDocumentUrl = (url) => /^(?:about|data|blob):/i.test(url);
10757
- var frameOrigin = (url) => {
10758
- try {
10759
- return new URL(url).origin;
10760
- } catch {
10761
- return url.slice(0, 200);
10762
- }
10763
- };
10764
- var elementHasFocus = (handle) => handle.evaluate((node) => {
10765
- const element = node;
10766
- return element.ownerDocument.activeElement === element || element.contains(element.ownerDocument.activeElement);
10767
- });
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";
10768
10825
 
10769
- class ExecuteSecretsBridge {
10770
- deps;
10771
- typedSecrets = new Map;
10772
- constructor(deps) {
10773
- 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}`;
10774
10884
  }
10775
- redactTypedSecrets(text) {
10776
- let output = text;
10777
- for (const [value, name] of [...this.typedSecrets].sort(([left], [right]) => right.length - left.length)) {
10778
- 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
+ }
10779
10893
  }
10780
- 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;
10781
10903
  }
10782
- redactOutputText(text) {
10783
- 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));
10784
10908
  }
10785
- redactOutputUrl(url) {
10786
- return this.redactTypedSecrets(this.deps.networkCapture.redactUrl(url));
10909
+ redactUrl(url) {
10910
+ return this.redactText(this.protectUrl(url));
10787
10911
  }
10788
- redactOutputValue(value) {
10789
- const redacted = this.deps.networkCapture.redactValue(value);
10790
- if (this.typedSecrets.size === 0)
10791
- return redacted;
10912
+ redactValue(value) {
10913
+ const redactString = (text) => this.redactText(text);
10792
10914
  const visit = (item, depth) => {
10793
- if (typeof item === "string")
10794
- return this.redactTypedSecrets(item);
10795
- if (typeof item === "number" && this.typedSecrets.has(String(item)))
10796
- 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
+ }
10797
10921
  if (depth > 32 || item === null || typeof item !== "object" || Buffer.isBuffer(item))
10798
10922
  return item;
10799
10923
  if (Array.isArray(item))
@@ -10801,92 +10925,218 @@ class ExecuteSecretsBridge {
10801
10925
  const prototype = Object.getPrototypeOf(item);
10802
10926
  if (prototype !== Object.prototype && prototype !== null)
10803
10927
  return item;
10804
- 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
+ ]));
10805
10932
  };
10806
- return visit(redacted, 0);
10933
+ return visit(value, 0);
10807
10934
  }
10808
- redactCaptureLogs(logs) {
10809
- return logs.map((log) => ({
10810
- ...log,
10811
- text: this.redactOutputText(log.text),
10812
- ...log.location ? {
10813
- location: { ...log.location, url: this.redactOutputUrl(log.location.url) }
10814
- } : {}
10815
- }));
10935
+ redactKnownSubstrings(text, minimumLength) {
10936
+ return this.redactKnown(text, (value) => value.length >= minimumLength || this.alwaysRedacted.has(value));
10816
10937
  }
10817
- redactCaptureAftermath(aftermath) {
10818
- return {
10819
- ...aftermath,
10820
- startUrl: aftermath.startUrl ? this.redactOutputUrl(aftermath.startUrl) : aftermath.startUrl,
10821
- endUrl: aftermath.endUrl ? this.redactOutputUrl(aftermath.endUrl) : aftermath.endUrl,
10822
- navigations: aftermath.navigations.map((url) => this.redactOutputUrl(url)),
10823
- ...aftermath.challenge ? { challenge: { ...aftermath.challenge, url: this.redactOutputUrl(aftermath.challenge.url) } } : {}
10824
- };
10938
+ addRedactionOnly(value) {
10939
+ if (value) {
10940
+ this.alwaysRedacted.add(value);
10941
+ this.knownValues.add(value);
10942
+ }
10825
10943
  }
10826
- async typeSecret(page, target, name, options = {}) {
10827
- if (typeof name !== "string" || !name)
10828
- throw new Error("secrets.type(target, name): name must be the name of a stored secret");
10829
- const secret = await runPromise(readSecret(name)).catch((error) => {
10830
- throw new Error(`secrets.type: ${error instanceof Error ? error.message : "could not read the secret"}`);
10831
- });
10832
- const secretRules = parseOriginPatterns(secret.allowedOrigins);
10833
- const sessionPatterns = this.deps.allowedOrigins();
10834
- const sessionRules = sessionPatterns && sessionPatterns.length > 0 ? parseOriginPatterns(sessionPatterns) : undefined;
10835
- const locator = typeof target === "string" ? page.locator(target) : target;
10836
- if (!locator || typeof locator.elementHandle !== "function") {
10837
- throw new Error("secrets.type(target, name): target must be a selector string or a Locator");
10838
- }
10839
- const handle = await locator.elementHandle({ timeout: options.timeout ?? 1e4 });
10840
- try {
10841
- const frame = await handle.ownerFrame();
10842
- if (!frame)
10843
- throw new Error(`secrets.type: target_not_editable: the element for ${JSON.stringify(name)} is not in a frame`);
10844
- const checkOrigin = () => {
10845
- const url = frame.url();
10846
- const origin = frameOrigin(url);
10847
- const decision = checkUrl(url, secretRules, { httpsOnlyWithoutScheme: true });
10848
- if (!decision.allowed || isOpaqueDocumentUrl(url)) {
10849
- 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.`);
10850
- }
10851
- if (sessionRules && !checkUrl(url, sessionRules).allowed) {
10852
- 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;
10853
10981
  }
10854
- return origin;
10855
- };
10856
- checkOrigin();
10857
- if (!await handle.isEditable().catch(() => false)) {
10858
- throw new Error(`secrets.type: target_not_editable: the target is not an editable field. Nothing was typed.`);
10859
- }
10860
- if (options.clear !== false)
10861
- await handle.fill("");
10862
- await handle.focus();
10863
- if (!await elementHasFocus(handle)) {
10864
- throw new Error("secrets.type: target_not_editable: the field did not keep focus. Nothing was typed.");
10865
- }
10866
- const origin = checkOrigin();
10867
- const urlBefore = frame.url();
10868
- const text = secretText(secret);
10869
- this.typedSecrets.set(text, name);
10870
- this.deps.networkCapture.addRedaction(text);
10871
- await frame.page().keyboard.insertText(text);
10872
- if (frame.url() !== urlBefore) {
10873
- this.deps.addWarningOnce(`secrets.type: the field's frame navigated while ${JSON.stringify(name)} was typed; check where it went before submitting.`);
10874
- }
10875
- if (!sessionRules) {
10876
- 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.`);
10877
- }
10878
- return { typed: true, name, origin, kind: secret.kind };
10879
- } finally {
10880
- 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));
10881
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
+ ]));
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);
10882
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;
10883
11139
  }
10884
-
10885
- // src/network-capture.ts
10886
- import path7 from "node:path";
10887
-
10888
- // src/network-capture/har-redaction.ts
10889
- import path6 from "node:path";
10890
11140
 
10891
11141
  // src/network-capture/types.ts
10892
11142
  var defaultNetworkCaptureMaxDurationMs = 30 * 60000;
@@ -10937,22 +11187,10 @@ function validateLimit(name, value, maximum) {
10937
11187
  }
10938
11188
 
10939
11189
  // src/network-capture/har-redaction.ts
10940
- function finishCapture(active, options, secrets, profileOptions) {
11190
+ function finishCapture(active, options) {
10941
11191
  return gen(function* () {
10942
- const existingProfile = secrets ? yield* readOptional(secrets, profileOptions) : undefined;
10943
- const collector = new SecretCollector(existingProfile?.slots ?? []);
10944
- for (const value of active.extraRedactions)
10945
- collector.addRedactionOnly(value);
10946
- const structurallyProtected = active.entries.map((entry) => protectEntry(entry, collector));
10947
- const protectedEntries = structurallyProtected.map((entry) => redactEntryKnownValues(entry, collector)).map((entry) => redactEntryTypedSecrets(entry, active.extraRedactions, collector));
10948
- if (options.requireObservedSecrets && collector.observedRefs().length === 0) {
10949
- return yield* new NetworkCaptureError({
10950
- message: `Auth refresh did not observe credentials for profile ${secrets ?? "unknown"}`,
10951
- operation: "auth-profile",
10952
- reason: "persistence-failed"
10953
- });
10954
- }
10955
- 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));
10956
11194
  if (options.outputPath) {
10957
11195
  yield* writeArtifact(options.outputPath, {
10958
11196
  log: {
@@ -10963,9 +11201,6 @@ function finishCapture(active, options, secrets, profileOptions) {
10963
11201
  });
10964
11202
  }
10965
11203
  return {
10966
- ...authProfile ? { authProfile } : {},
10967
- updatedSecretRefs: collector.updatedRefs(),
10968
- observedSecretRefs: collector.observedRefs(),
10969
11204
  redactionOmissionCount: options.outputPath ? countRedactionOmissions(active.entries, protectedEntries) : 0,
10970
11205
  endpoints: summarizeEndpoints(protectedEntries)
10971
11206
  };
@@ -10999,7 +11234,7 @@ function summarizeEndpoints(entries) {
10999
11234
  const lower = h.name.toLowerCase();
11000
11235
  if (lower === "x-client-data" || lower.startsWith("sec-ch-"))
11001
11236
  return false;
11002
- return h.value.includes("${BC_SECRET_") || lower === "authorization" || lower.startsWith("x-");
11237
+ return h.value.includes("[redacted]") || lower === "authorization" || lower.startsWith("x-");
11003
11238
  }).slice(0, 8).map((h) => `${h.name}: ${h.value.slice(0, 80)}`);
11004
11239
  const requestKeys = extractTopLevelJsonKeys(entry.request.body);
11005
11240
  const responseKeys = extractTopLevelJsonKeys(entry.response?.body);
@@ -11070,20 +11305,19 @@ function truncatedBody(mimeType, active, size = 0) {
11070
11305
  active.truncatedBodyCount += 1;
11071
11306
  return { size, mimeType: mimeType ?? "application/octet-stream", truncated: true };
11072
11307
  }
11073
- function protectEntry(entry, collector) {
11074
- const scope = requestScope(entry.request.method, entry.request.url);
11075
- const requestHeaders = collector.protectHeaders(entry.request.headers, "request", scope);
11076
- const responseHeaders = entry.response ? collector.protectHeaders(entry.response.headers, "response", scope) : undefined;
11077
- const requestBody = protectCapturedBody(entry.request.body, collector, "request", scope);
11078
- 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);
11079
11313
  return {
11080
11314
  ...entry,
11081
11315
  request: {
11082
11316
  ...entry.request,
11083
- url: collector.protectUrl(entry.request.url, scope),
11317
+ url: redactor.protectUrl(entry.request.url),
11084
11318
  headers: requestHeaders,
11085
11319
  ...requestBody ? { body: requestBody } : {},
11086
- ...entry.request.redirectedFrom ? { redirectedFrom: collector.protectUrl(entry.request.redirectedFrom, scope) } : {}
11320
+ ...entry.request.redirectedFrom ? { redirectedFrom: redactor.protectUrl(entry.request.redirectedFrom) } : {}
11087
11321
  },
11088
11322
  ...entry.response ? {
11089
11323
  response: {
@@ -11094,18 +11328,18 @@ function protectEntry(entry, collector) {
11094
11328
  } : {}
11095
11329
  };
11096
11330
  }
11097
- function protectCapturedBody(body, collector, location, scope) {
11331
+ function protectCapturedBody(body, redactor) {
11098
11332
  if (!body)
11099
11333
  return;
11100
11334
  if (!body.text) {
11101
11335
  return { size: body.size, mimeType: body.mimeType, truncated: true };
11102
11336
  }
11103
- const text = collector.protectBody(body.text, body.mimeType, location, scope);
11337
+ const text = redactor.protectBody(body.text, body.mimeType);
11104
11338
  return text === undefined ? { size: body.size, mimeType: body.mimeType, truncated: true } : { ...body, text };
11105
11339
  }
11106
11340
  var minimumKnownBodySubstringLength = 16;
11107
- function redactEntryKnownValues(entry, collector) {
11108
- const redactText = (text) => collector.redactKnownSubstrings(text, minimumKnownSubstringLength);
11341
+ function redactEntryKnownValues(entry, redactor) {
11342
+ const redactText = (text) => redactor.redactKnownSubstrings(text, minimumKnownSubstringLength);
11109
11343
  const redactHeaders = (headers) => headers.map((item) => ({ ...item, value: redactText(item.value) }));
11110
11344
  return {
11111
11345
  ...entry,
@@ -11114,62 +11348,35 @@ function redactEntryKnownValues(entry, collector) {
11114
11348
  url: redactText(entry.request.url),
11115
11349
  headers: redactHeaders(entry.request.headers),
11116
11350
  ...entry.request.redirectedFrom ? { redirectedFrom: redactText(entry.request.redirectedFrom) } : {},
11117
- ...entry.request.body?.text ? { body: redactStructuredBody(entry.request.body, collector) } : {}
11118
- },
11119
- ...entry.response ? {
11120
- response: {
11121
- ...entry.response,
11122
- headers: redactHeaders(entry.response.headers),
11123
- ...entry.response.body?.text ? { body: redactStructuredBody(entry.response.body, collector) } : {}
11124
- }
11125
- } : {}
11126
- };
11127
- }
11128
- function redactEntryTypedSecrets(entry, values, collector) {
11129
- if (values.size === 0)
11130
- return entry;
11131
- const redact = (text) => collector.redactValuesEverywhere(text, values);
11132
- const redactBody = (body) => body?.text ? { ...body, text: redact(body.text) } : body;
11133
- const redactHeaders = (headers) => headers.map((item) => ({ ...item, value: redact(item.value) }));
11134
- const requestBody = redactBody(entry.request.body);
11135
- const responseBody = redactBody(entry.response?.body);
11136
- return {
11137
- ...entry,
11138
- request: {
11139
- ...entry.request,
11140
- url: redact(entry.request.url),
11141
- headers: redactHeaders(entry.request.headers),
11142
- ...entry.request.redirectedFrom ? { redirectedFrom: redact(entry.request.redirectedFrom) } : {},
11143
- ...requestBody ? { body: requestBody } : {}
11351
+ ...entry.request.body?.text ? { body: redactStructuredBody(entry.request.body, redactor) } : {}
11144
11352
  },
11145
11353
  ...entry.response ? {
11146
11354
  response: {
11147
11355
  ...entry.response,
11148
11356
  headers: redactHeaders(entry.response.headers),
11149
- ...responseBody ? { body: responseBody } : {}
11357
+ ...entry.response.body?.text ? { body: redactStructuredBody(entry.response.body, redactor) } : {}
11150
11358
  }
11151
11359
  } : {}
11152
11360
  };
11153
11361
  }
11154
- function redactStructuredBody(body, collector) {
11362
+ function redactStructuredBody(body, redactor) {
11155
11363
  if (!body.text || !body.mimeType.toLowerCase().includes("json"))
11156
11364
  return body;
11157
11365
  try {
11158
- return { ...body, text: JSON.stringify(redactKnownScalars(JSON.parse(body.text), collector)) };
11366
+ return { ...body, text: JSON.stringify(redactKnownScalars(JSON.parse(body.text), redactor)) };
11159
11367
  } catch {
11160
11368
  return { size: body.size, mimeType: body.mimeType, truncated: true };
11161
11369
  }
11162
11370
  }
11163
- function redactKnownScalars(value, collector) {
11371
+ function redactKnownScalars(value, redactor) {
11164
11372
  if (Array.isArray(value))
11165
- return value.map((item) => redactKnownScalars(item, collector));
11373
+ return value.map((item) => redactKnownScalars(item, redactor));
11166
11374
  if (isObject(value)) {
11167
- 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)]));
11168
11376
  }
11169
- const exact = collector.redactExactValue(value, 8);
11170
- if (exact !== value || !isString(value))
11171
- return exact;
11172
- return collector.redactKnownSubstrings(value, minimumKnownBodySubstringLength);
11377
+ if (isString(value))
11378
+ return redactor.redactKnownSubstrings(value, minimumKnownBodySubstringLength);
11379
+ return redactor.redactValue(value);
11173
11380
  }
11174
11381
  function toHarEntry(entry) {
11175
11382
  return {
@@ -11274,24 +11481,6 @@ function safeValue(read, fallback) {
11274
11481
  return fallback;
11275
11482
  }
11276
11483
  }
11277
- function requestScope(method, rawUrl) {
11278
- let base;
11279
- try {
11280
- const url = new URL(rawUrl);
11281
- base = `${url.origin}${url.pathname}`;
11282
- } catch {
11283
- base = rawUrl.split("?", 1)[0] ?? rawUrl;
11284
- }
11285
- const scrubbed = base.split("/").map((segment) => looksLikeTokenSegment(safeDecode(segment)) ? ":token" : segment).join("/");
11286
- return `${method.toUpperCase()} ${scrubbed}`;
11287
- }
11288
- function safeDecode(segment) {
11289
- try {
11290
- return decodeURIComponent(segment);
11291
- } catch {
11292
- return segment;
11293
- }
11294
- }
11295
11484
  function contentType(headers) {
11296
11485
  return header(headers, "content-type")?.trim();
11297
11486
  }
@@ -11318,7 +11507,6 @@ class Recorder {
11318
11507
  page;
11319
11508
  pageEpoch = 0;
11320
11509
  transition = makeUnsafe(1);
11321
- extraRedactions = new Set;
11322
11510
  constructor(recorderOptions = {}) {
11323
11511
  this.recorderOptions = recorderOptions;
11324
11512
  }
@@ -11345,8 +11533,7 @@ class Recorder {
11345
11533
  entries: [],
11346
11534
  finalizeQueue: [],
11347
11535
  finalizeWaiters: new Set,
11348
- liveCollector: new SecretCollector,
11349
- extraRedactions: capture.extraRedactions,
11536
+ liveRedactor: new SecretRedactor,
11350
11537
  finalizeWorkers: 0,
11351
11538
  finalizeGeneration: 0,
11352
11539
  capturedBodyBytes: 0,
@@ -11356,8 +11543,6 @@ class Recorder {
11356
11543
  cancelled: false,
11357
11544
  outputUnsafe: false
11358
11545
  };
11359
- for (const value of capture.extraRedactions)
11360
- capture.active.liveCollector.addRedactionOnly(value);
11361
11546
  capture.bindPage(page);
11362
11547
  const active = capture.active;
11363
11548
  clearTimeout(capture.expiry);
@@ -11443,23 +11628,16 @@ class Recorder {
11443
11628
  active.droppedEntryCount += active.pending.size;
11444
11629
  capture.discardFinalizers(active);
11445
11630
  }
11446
- const secrets = options.secrets;
11447
- const profileOptions = capture.recorderOptions.authProfileBaseDir ? { baseDir: capture.recorderOptions.authProfileBaseDir } : {};
11448
- const finish = finishCapture(active, options, secrets, profileOptions);
11449
- 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);
11450
11632
  const { endsAt: _endsAt, ...finalStatus } = capture.status();
11451
11633
  capture.active = undefined;
11452
11634
  clearTimeout(capture.expiry);
11453
11635
  return {
11454
11636
  ...finalStatus,
11455
- ...secrets ? { secrets } : {},
11456
11637
  truncatedBodyCount: finalStatus.truncatedBodyCount + finished.redactionOmissionCount,
11457
11638
  active: false,
11458
11639
  stoppedAt: new Date().toISOString(),
11459
11640
  ...options.outputPath ? { outputPath: path7.resolve(options.outputPath) } : {},
11460
- ...finished.authProfile ? { authProfile: finished.authProfile } : {},
11461
- updatedSecretRefs: finished.updatedSecretRefs,
11462
- observedSecretRefs: finished.observedSecretRefs,
11463
11641
  ...finished.endpoints.length > 0 ? { endpoints: finished.endpoints } : {}
11464
11642
  };
11465
11643
  }).pipe(tapError(() => sync2(() => {
@@ -11518,23 +11696,17 @@ class Recorder {
11518
11696
  return;
11519
11697
  active.outputUnsafe = !await settleFinalizers(active, this.recorderOptions.outputSettleTimeoutMs ?? 5000);
11520
11698
  }
11521
- addRedaction(value) {
11522
- if (!value)
11523
- return;
11524
- this.extraRedactions.add(value);
11525
- this.active?.liveCollector.addRedactionOnly(value);
11526
- }
11527
11699
  redactText(text) {
11528
11700
  const active = this.active;
11529
11701
  if (!active)
11530
11702
  return text;
11531
- 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);
11532
11704
  }
11533
11705
  redactValue(value) {
11534
11706
  const active = this.active;
11535
11707
  if (!active)
11536
11708
  return value;
11537
- 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);
11538
11710
  }
11539
11711
  redactUrl(url) {
11540
11712
  const active = this.active;
@@ -11542,7 +11714,25 @@ class Recorder {
11542
11714
  return url;
11543
11715
  if (active.outputUnsafe)
11544
11716
  return "[REDACTED: network capture finalization pending]";
11545
- 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
+ };
11546
11736
  }
11547
11737
  onRequest = (request) => {
11548
11738
  const active = this.active;
@@ -11673,7 +11863,7 @@ class Recorder {
11673
11863
  if (active.cancelled || generation !== active.finalizeGeneration)
11674
11864
  return;
11675
11865
  active.entries.push(entry);
11676
- protectEntry(entry, active.liveCollector);
11866
+ protectEntry(entry, active.liveRedactor);
11677
11867
  }
11678
11868
  unbindPage() {
11679
11869
  const page = this.page;
@@ -11730,7 +11920,6 @@ class ExecuteSandbox extends DefaultPageHost {
11730
11920
  snapshotRefs = { selectors: new Map };
11731
11921
  networkCapture = new Recorder;
11732
11922
  viewportGuardContexts = new WeakSet;
11733
- secrets;
11734
11923
  actionTimeoutContext;
11735
11924
  realm;
11736
11925
  state;
@@ -11740,11 +11929,6 @@ class ExecuteSandbox extends DefaultPageHost {
11740
11929
  ...options.pageHealthCheckTimeoutMs === undefined ? {} : { pageHealthCheckTimeoutMs: options.pageHealthCheckTimeoutMs }
11741
11930
  });
11742
11931
  this.options = options;
11743
- this.secrets = new ExecuteSecretsBridge({
11744
- networkCapture: this.networkCapture,
11745
- allowedOrigins: () => this.options.allowedOrigins?.(),
11746
- addWarningOnce: (warning) => this.addWarningOnce(warning)
11747
- });
11748
11932
  this.realm = this.allowNode ? undefined : this.createRealm();
11749
11933
  this.state = this.realm?.state ?? {};
11750
11934
  }
@@ -11790,7 +11974,7 @@ class ExecuteSandbox extends DefaultPageHost {
11790
11974
  });
11791
11975
  await this.networkCapture.settleForOutput();
11792
11976
  const extracted = extractExecuteMedia(result);
11793
- const redactedValue = this.secrets.redactOutputValue(extracted.value);
11977
+ const redactedValue = this.networkCapture.redactValue(extracted.value);
11794
11978
  const jsonSafeResult = toJsonSafeValue(redactedValue);
11795
11979
  const bounded = boundExecuteResult(stringifyResult(redactedValue), jsonSafeResult.serializable ? jsonSafeResult.value : undefined, jsonSafeResult.serializable);
11796
11980
  const warnings = this.finalizeWarnings(logSummary, jsonValueWarning(redactedValue, jsonSafeResult), bounded.warning);
@@ -11799,10 +11983,10 @@ class ExecuteSandbox extends DefaultPageHost {
11799
11983
  ...bounded.hasValue ? { value: bounded.value } : {},
11800
11984
  ...extracted.media.length > 0 ? { media: extracted.media } : {},
11801
11985
  isError: false,
11802
- logs: this.secrets.redactCaptureLogs(logs),
11986
+ logs: this.networkCapture.redactCaptureLogs(logs),
11803
11987
  logSummary,
11804
11988
  warnings,
11805
- aftermath: this.secrets.redactCaptureAftermath(aftermath)
11989
+ aftermath: this.networkCapture.redactCaptureAftermath(aftermath)
11806
11990
  };
11807
11991
  }
11808
11992
  });
@@ -11829,13 +12013,13 @@ class ExecuteSandbox extends DefaultPageHost {
11829
12013
  const closedUnderScript = (this.closedDefaultPage !== undefined || this.pendingTargetRebind === "replaced") && /has been closed/i.test(error.message);
11830
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));
11831
12015
  return {
11832
- text: this.secrets.redactOutputText(error instanceof ExecuteCodeError ? userCodeStack(error) : error.message),
12016
+ text: this.networkCapture.redactText(error instanceof ExecuteCodeError ? userCodeStack(error) : error.message),
11833
12017
  isError: true,
11834
- logs: this.secrets.redactCaptureLogs(error instanceof ExecuteCodeError ? error.logs : []),
12018
+ logs: this.networkCapture.redactCaptureLogs(error instanceof ExecuteCodeError ? error.logs : []),
11835
12019
  logSummary,
11836
12020
  warnings,
11837
- ...diagnostic ? { diagnostic: this.secrets.redactOutputText(diagnostic) } : {},
11838
- ...aftermath ? { aftermath: this.secrets.redactCaptureAftermath(aftermath) } : {},
12021
+ ...diagnostic ? { diagnostic: this.networkCapture.redactText(diagnostic) } : {},
12022
+ ...aftermath ? { aftermath: this.networkCapture.redactCaptureAftermath(aftermath) } : {},
11839
12023
  ...error instanceof ExecuteCodeError ? {} : { setupFailed: true }
11840
12024
  };
11841
12025
  },
@@ -11909,10 +12093,10 @@ class ExecuteSandbox extends DefaultPageHost {
11909
12093
  if (logCompactionWarning) {
11910
12094
  warnings.push(logCompactionWarning);
11911
12095
  }
11912
- return warnings.map((warning) => this.secrets.redactOutputText(warning));
12096
+ return warnings.map((warning) => this.networkCapture.redactText(warning));
11913
12097
  }
11914
12098
  redactNetworkCaptureText(text) {
11915
- return this.secrets.redactOutputText(text);
12099
+ return this.networkCapture.redactText(text);
11916
12100
  }
11917
12101
  stopRealm() {
11918
12102
  this.realm?.dispose(new Error("Execute stopped: the session was stopped, deleted or reset"));
@@ -12106,7 +12290,6 @@ class ExecuteSandbox extends DefaultPageHost {
12106
12290
  realm: this.realm,
12107
12291
  snapshotRefs: this.snapshotRefs,
12108
12292
  networkCapture: this.networkCapture,
12109
- secrets: this.secrets,
12110
12293
  requestHandoff: this.options.requestHandoff,
12111
12294
  isRecordingTarget: this.options.isRecordingTarget,
12112
12295
  isDefaultPage: (candidate) => candidate === this.page,
@@ -12152,27 +12335,6 @@ class ExecuteSandbox extends DefaultPageHost {
12152
12335
  networkEnd(reason) {
12153
12336
  return this.networkCapture.end(reason);
12154
12337
  }
12155
- authRefresh(options) {
12156
- const sandbox = this;
12157
- return gen(function* () {
12158
- const page = yield* sandbox.ensureSessionPage("Set up page for auth refresh");
12159
- yield* read(options.name).pipe(asVoid2);
12160
- yield* sandbox.networkCapture.start(page, {
12161
- ...options.urlFilter ? { urlFilter: options.urlFilter } : {}
12162
- });
12163
- return yield* gen(function* () {
12164
- yield* tryPromise({
12165
- try: () => page.reload({ waitUntil: "domcontentloaded", timeout: options.timeoutMs ?? 30000 }),
12166
- catch: (cause) => cause instanceof Error ? cause : new Error("Refresh auth profile", { cause })
12167
- });
12168
- yield* tryPromise({
12169
- try: () => page.waitForLoadState("networkidle", { timeout: Math.min(options.timeoutMs ?? 30000, 5000) }).catch(() => {}),
12170
- catch: (cause) => cause instanceof Error ? cause : new Error("Wait for auth refresh network", { cause })
12171
- });
12172
- return yield* sandbox.networkCapture.stop({ secrets: options.name, requireObservedSecrets: true });
12173
- }).pipe(ensuring(sandbox.networkCapture.cancel()));
12174
- }).pipe(uninterruptible);
12175
- }
12176
12338
  warnSyntheticInput() {
12177
12339
  this.addWarningOnce(syntheticInputWarning);
12178
12340
  }
@@ -12189,6 +12351,36 @@ import crypto6 from "node:crypto";
12189
12351
  import { once } from "node:events";
12190
12352
  import fs8 from "node:fs/promises";
12191
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
+
12192
12384
  // src/recording-relay/mjpeg-matroska.ts
12193
12385
  var ebml = Buffer.from("1A45DFA3", "hex");
12194
12386
  var ebmlVersion = Buffer.from("4286", "hex");
@@ -13142,6 +13334,202 @@ function resolveExactHandoffTarget(options) {
13142
13334
  return target;
13143
13335
  }
13144
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
+
13145
13533
  // src/relay/lifecycle-log.ts
13146
13534
  import fs10 from "node:fs";
13147
13535
  import path10 from "node:path";
@@ -14274,9 +14662,6 @@ class OpenCodeBrowserSessions {
14274
14662
  networkCancel(id) {
14275
14663
  return this.withSessionOperation(id, "network cancel", (session) => session.sandbox.networkCancel());
14276
14664
  }
14277
- authRefresh(id, options) {
14278
- return this.withSessionOperation(id, "auth refresh", (session) => session.sandbox.authRefresh(options));
14279
- }
14280
14665
  withSessionOperation(id, operation, use, beforePermit) {
14281
14666
  const manager = this;
14282
14667
  return this.admission.withAdmission(id, suspend2(() => {
@@ -14631,10 +15016,6 @@ function relayHttpError(error) {
14631
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"]));
14632
15017
  return routeError(error.message, status, code);
14633
15018
  }
14634
- if (error instanceof AuthProfileError) {
14635
- const [status, code] = value(error.reason).pipe(when("invalid-name", () => [400, "invalid-request"]), when("not-found", () => [404, "auth-profile-not-found"]), orElse(() => [500, "internal"]));
14636
- return routeError(error.message, status, code);
14637
- }
14638
15019
  if (error instanceof AuthenticatedOriginError) {
14639
15020
  return routeError(error.message, error.reason === "invalid-request" ? 400 : 500, error.reason === "invalid-request" ? "invalid-request" : "setup-failed");
14640
15021
  }
@@ -15675,27 +16056,6 @@ function handleNetworkRequest(options) {
15675
16056
  sendNotFound(options.response);
15676
16057
  });
15677
16058
  }
15678
- function handleAuthRequest(options) {
15679
- return gen(function* () {
15680
- if (options.pathname === "/auth/status" && options.request.method === "POST") {
15681
- const request = yield* decodeRequest(AuthProfileRequest, yield* readJsonBody2(options.request), "auth status");
15682
- sendJson2(options.response, yield* status(request.name));
15683
- return;
15684
- }
15685
- if (options.pathname === "/auth/refresh" && options.request.method === "POST") {
15686
- const request = yield* decodeRequest(AuthRefreshRequest, yield* readJsonBody2(options.request), "auth refresh");
15687
- const { sessionId, ...refreshOptions } = request;
15688
- sendJson2(options.response, yield* options.sessions.authRefresh(sessionId, refreshOptions));
15689
- return;
15690
- }
15691
- if (options.pathname === "/auth/run" && options.request.method === "POST") {
15692
- const request = yield* decodeRequest(AuthRunRequest, yield* readJsonBody2(options.request), "auth run");
15693
- sendJson2(options.response, yield* run(request));
15694
- return;
15695
- }
15696
- sendNotFound(options.response);
15697
- });
15698
- }
15699
16059
  function handleCliRequest(options) {
15700
16060
  return gen(function* () {
15701
16061
  if (options.pathname === "/cli/sessions" && options.request.method === "GET") {
@@ -15931,10 +16291,6 @@ function createHttpRequestHandler(options) {
15931
16291
  run(handleNetworkRequest({ request, response, pathname, sessions: options.sessions }));
15932
16292
  return;
15933
16293
  }
15934
- if (pathname.startsWith("/auth/")) {
15935
- run(handleAuthRequest({ request, response, pathname, sessions: options.sessions }), pathname === "/auth/run");
15936
- return;
15937
- }
15938
16294
  if (pathname.startsWith("/v1/")) {
15939
16295
  run(handleClientRequest({
15940
16296
  request,
@@ -17046,7 +17402,19 @@ function createCdpDispatcher(options) {
17046
17402
  catch: (error) => error instanceof Error ? error : new Error(String(error))
17047
17403
  });
17048
17404
  const { tabId } = route;
17405
+ if (message.method === "Fetch.enable") {
17406
+ const rootSessionId = registry.tabTargets.get(tabId)?.sessionId;
17407
+ if (!rootSessionId || !cdpClients.hasSession(socket, rootSessionId)) {
17408
+ return yield* fail6(new Error("Fetch.enable requires this client to be attached to the tab's root target; attach the tab before enabling request interception."));
17409
+ }
17410
+ cdpClients.markInterceptionOwner(socket, tabId, route.chromeSessionId);
17411
+ }
17049
17412
  tabActivity.touch(tabId);
17413
+ if (message.method === "Fetch.disable") {
17414
+ cdpClients.clearInterceptionOwner(socket, tabId, route.chromeSessionId, false);
17415
+ if (cdpClients.hasInterceptionOwner(tabId, route.chromeSessionId))
17416
+ return {};
17417
+ }
17050
17418
  const executingSession = cdpClients.sessionId(socket);
17051
17419
  if (executingSession && sessions.isExecuting(executingSession)) {
17052
17420
  yield* tabActivity.focus(tabId, executingSession);
@@ -19526,7 +19894,12 @@ var makeRelay = fnUntraced(function* (options = {}) {
19526
19894
  sendEvent: sendCdpEvent2,
19527
19895
  ...contextDebugLog ? { trace: contextDebugLog } : {}
19528
19896
  });
19529
- const cdpClients = new CdpClientPool((client, event) => cdpRuntime.deliver(client, event), (client, sessionId) => cdpRuntime.detach(client, sessionId));
19897
+ let releaseIdleInterception = () => {
19898
+ return;
19899
+ };
19900
+ const pendingInterceptionReleases = new Set;
19901
+ let interceptionReleaseScheduled = false;
19902
+ const cdpClients = new CdpClientPool((client, event) => cdpRuntime.deliver(client, event), (client, sessionId) => cdpRuntime.detach(client, sessionId), (tabId) => releaseIdleInterception(tabId));
19530
19903
  const mainFrameIdsByTab = new Map;
19531
19904
  const blankNavigationWaiters = new Map;
19532
19905
  const suppressedChildSessions = new Map;
@@ -19633,7 +20006,6 @@ var makeRelay = fnUntraced(function* (options = {}) {
19633
20006
  authToken,
19634
20007
  sessionId: id,
19635
20008
  onDefaultTargetChange,
19636
- allowedOrigins: () => sessions.allowedOrigins(id),
19637
20009
  drainGuardWarnings: () => navigationGuard.drainWarnings(id),
19638
20010
  cpuScheduler: sessions.cpuScheduler,
19639
20011
  isRecordingTarget: (targetId) => {
@@ -19825,6 +20197,28 @@ var makeRelay = fnUntraced(function* (options = {}) {
19825
20197
  audit
19826
20198
  });
19827
20199
  const { shutdown: shutdownControl, updates, sendUpdateNotice, releaseRelayTarget, browserIdle, startTimers, stopTimers } = housekeeping;
20200
+ releaseIdleInterception = (tabId) => {
20201
+ if (shutdownControl.stopping)
20202
+ return;
20203
+ pendingInterceptionReleases.add(tabId);
20204
+ if (interceptionReleaseScheduled)
20205
+ return;
20206
+ interceptionReleaseScheduled = true;
20207
+ queueMicrotask(() => {
20208
+ interceptionReleaseScheduled = false;
20209
+ if (shutdownControl.stopping) {
20210
+ pendingInterceptionReleases.clear();
20211
+ return;
20212
+ }
20213
+ const tabs = Array.from(pendingInterceptionReleases).filter((id) => !cdpClients.hasInterceptionOwners(id));
20214
+ pendingInterceptionReleases.clear();
20215
+ if (tabs.length === 0)
20216
+ return;
20217
+ runPromise(shutdownControl.trackTransport(cdpRuntime.releaseInterception(tabs, (id) => !cdpClients.hasInterceptionOwners(id)).pipe(timeoutOption("3 seconds"), ignore))).catch((error) => {
20218
+ console.error("Failed to release request interception", error);
20219
+ });
20220
+ });
20221
+ };
19828
20222
  const toggleTab = fnUntraced(function* (tabId) {
19829
20223
  if (registry.tabTargets.has(tabId))
19830
20224
  return yield* detachTab(tabId);
@@ -20085,6 +20479,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
20085
20479
  waitedMs: defaultShutdownTimeoutMs
20086
20480
  })
20087
20481
  });
20482
+ yield* cdpRuntime.releaseInterception(registry.listRootTargets().map((target) => target.tabId), () => true).pipe(timeoutOption("5 seconds"), ignore);
20088
20483
  yield* rootLifecycle.close();
20089
20484
  if (managed) {
20090
20485
  yield* audit(RelayLifecycleEvent.cases.Closed.make({ instanceId: browserId })).pipe(catch_(() => sync2(() => console.error("Failed to record relay shutdown lifecycle event"))));