@edlsh/browse-core 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,20 @@ const output = await browser.run(browserParameters.parse({ action: "start", back
24
24
 
25
25
  Stagehand is pinned to 4.4.0 and used unmodified. zod is pinned to 4.6.6, the exact version Stagehand pins, so one copy is installed; a second copy fails the typecheck on the schema passed to `stagehand.extract`. An attached browser needs Chrome 137 or newer and the Stagehand extension shipped with 4.4.0. Run both real-browser suites before upgrading Stagehand.
26
26
 
27
+ ## HTTP sign-in in a managed browser
28
+
29
+ Start an isolated browser for a site that uses a browser-native username and password prompt.
30
+
31
+ ```js
32
+ { action: "start", backend: "local", httpAuth: true, url: "https://example.com/" }
33
+ ```
34
+
35
+ Enable the installed browser credential helper with `BROWSE_HTTP_AUTH_USE_STORE=true`. The helper looks up the starting URL's exact origin in the user's private credential mapping. Set `BROWSE_HTTP_AUTH_ORIGIN` to restrict this profile's lookups to one origin. Alternatively, supply `BROWSE_HTTP_AUTH_ORIGIN`, `BROWSE_HTTP_AUTH_USERNAME` and `BROWSE_HTTP_AUTH_PASSWORD` through the host's configured secrets manager. Keep these values out of tool arguments. Custom host resolvers receive `scope.httpAuth === true` at this start and may return profile-specific `httpAuthStore: {}` or `httpAuth: {origin, username, password}`.
36
+
37
+ The browser answers a server's HTTP Basic challenge at that scheme, host and port. Authentication requires HTTPS or loopback HTTP. Closing the browser discards its auth cache. An authenticated start uses a fresh profile even where the host normally shares a persistent profile. HAR capture is unavailable during this session.
38
+
39
+ For a fresh Browserbase session, choose `backend: "browserbase"` and grant the host permission with `BROWSE_HTTP_AUTH_HOSTED=true` or `hosted: true` in the selected credential configuration. Browserbase processes the credentials for that session. The launch disables session logging, recording and keep-alive.
40
+
27
41
  ## Shared browsers
28
42
 
29
43
  New browsers start locally unless the host or the profile's `/browse backend` setting chooses Browserbase.
@@ -51,6 +65,7 @@ Stagehand cannot attach to this browser, so what it does elsewhere runs here on
51
65
  ```sh
52
66
  bun install --frozen-lockfile --ignore-scripts
53
67
  bun run check # tests, types, build, package contents
68
+ CHROME_PATH=/path/to/chrome bun run test:http-auth # local HTTP Basic challenge, exact origin and rejected credentials
54
69
  CHROME_PATH=/path/to/chrome bun run test:local # real local browser
55
70
  CHROME_PATH=/path/to/chrome bun run test:shared # two processes on one persistent profile
56
71
  bun run test:hosted # needs BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID
@@ -174,7 +174,8 @@ export class BrokerConnection {
174
174
  throw new Error("The conversation this request belongs to has ended.");
175
175
  let value;
176
176
  if (request.kind === "config") {
177
- value = await handlers.resolveConfig({ ...request.context, signal: AbortSignal.timeout(60_000) });
177
+ const { httpAuth: _privateCredentials, httpAuthStore: _privateCredentialStore, ...sharedConfig } = await handlers.resolveConfig({ ...request.context, signal: AbortSignal.timeout(60_000) });
178
+ value = sharedConfig;
178
179
  }
179
180
  else if (request.kind === "generate") {
180
181
  if (!handlers.generate)
@@ -0,0 +1,18 @@
1
+ /** A flattened browser DevTools connection. Responses resolve the command that sent them. */
2
+ export interface CdpEvent {
3
+ method: string;
4
+ params: any;
5
+ sessionId?: string;
6
+ }
7
+ export declare class CdpConnection {
8
+ private readonly socket;
9
+ private nextId;
10
+ private readonly pending;
11
+ onEvent?: (event: CdpEvent) => void;
12
+ private constructor();
13
+ static open(url: string, signal: AbortSignal): Promise<CdpConnection>;
14
+ get closed(): boolean;
15
+ send(method: string, params?: Record<string, unknown>, sessionId?: string): Promise<any>;
16
+ private rejectPending;
17
+ close(): void;
18
+ }
@@ -0,0 +1,59 @@
1
+ export class CdpConnection {
2
+ socket;
3
+ nextId = 0;
4
+ pending = new Map();
5
+ onEvent;
6
+ constructor(socket) {
7
+ this.socket = socket;
8
+ socket.addEventListener("message", event => {
9
+ const message = JSON.parse(String(event.data));
10
+ if (message.id === undefined) {
11
+ this.onEvent?.(message);
12
+ return;
13
+ }
14
+ const reply = this.pending.get(message.id);
15
+ if (!reply)
16
+ return;
17
+ this.pending.delete(message.id);
18
+ if (message.error)
19
+ reply.reject(new Error(message.error.message));
20
+ else
21
+ reply.resolve(message.result);
22
+ });
23
+ socket.addEventListener("close", () => this.rejectPending());
24
+ }
25
+ static async open(url, signal) {
26
+ signal.throwIfAborted();
27
+ const socket = new WebSocket(url);
28
+ const client = new CdpConnection(socket);
29
+ const abort = () => client.close();
30
+ try {
31
+ signal.addEventListener("abort", abort, { once: true });
32
+ await new Promise((resolve, reject) => {
33
+ socket.addEventListener("open", () => resolve(), { once: true });
34
+ socket.addEventListener("error", () => reject(new Error("Could not open a DevTools connection.")), { once: true });
35
+ socket.addEventListener("close", () => reject(new Error("DevTools connection closed.")), { once: true });
36
+ });
37
+ signal.throwIfAborted();
38
+ return client;
39
+ }
40
+ finally {
41
+ signal.removeEventListener("abort", abort);
42
+ }
43
+ }
44
+ get closed() { return this.socket.readyState !== this.socket.OPEN; }
45
+ send(method, params = {}, sessionId) {
46
+ if (this.closed)
47
+ return Promise.reject(new Error("DevTools connection closed."));
48
+ const id = ++this.nextId;
49
+ const result = new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
50
+ this.socket.send(JSON.stringify({ id, method, params, sessionId }));
51
+ return result;
52
+ }
53
+ rejectPending() {
54
+ for (const { reject } of this.pending.values())
55
+ reject(new Error("DevTools connection closed."));
56
+ this.pending.clear();
57
+ }
58
+ close() { this.socket.close(); this.rejectPending(); }
59
+ }
package/dist/har.d.ts CHANGED
@@ -52,10 +52,8 @@ export declare function writeCaptureHar(capture: NetworkCapture, path: string, c
52
52
  * response bodies are kept. Nothing is returned to the caller but counts: the HAR goes only to the file stop writes.
53
53
  */
54
54
  export declare class HarRecorder {
55
- private readonly socket;
55
+ private readonly client;
56
56
  private readonly include?;
57
- private readonly pending;
58
- private nextId;
59
57
  private readonly drafts;
60
58
  /** ExtraInfo events can arrive before the event they belong to. */
61
59
  private readonly early;
@@ -64,7 +62,6 @@ export declare class HarRecorder {
64
62
  private readonly tabs;
65
63
  /** setDiscoverTargets also reports targets that already exist: each is attached once. */
66
64
  private readonly attached;
67
- private closed;
68
65
  private constructor();
69
66
  /**
70
67
  * Connects to a browser-level DevTools WebSocket and starts recording every existing and new tab, or with `include`
@@ -75,8 +72,6 @@ export declare class HarRecorder {
75
72
  stop(path: string, creator: string): Promise<HarSummary>;
76
73
  /** Ends recording without writing anything. */
77
74
  close(): void;
78
- private fail;
79
- private send;
80
75
  /** stop waits for reads in flight, such as response bodies, before writing. */
81
76
  private track;
82
77
  private attach;
package/dist/har.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { chmod, mkdir, writeFile } from "node:fs/promises";
2
+ import { CdpConnection } from "./cdp-connection.js";
2
3
  import { dirname } from "node:path";
3
4
  // Stagehand 4.3 forwards only console events from CDP, so network capture uses its own connection to the browser target.
4
5
  /** A response body larger than this (base64 or text characters) is left out of the HAR and counted instead. */
@@ -62,10 +63,8 @@ function responseCookies(headers) {
62
63
  * response bodies are kept. Nothing is returned to the caller but counts: the HAR goes only to the file stop writes.
63
64
  */
64
65
  export class HarRecorder {
65
- socket;
66
+ client;
66
67
  include;
67
- pending = new Map();
68
- nextId = 0;
69
68
  drafts = new Map();
70
69
  /** ExtraInfo events can arrive before the event they belong to. */
71
70
  early = new Map();
@@ -74,9 +73,8 @@ export class HarRecorder {
74
73
  tabs = new Map();
75
74
  /** setDiscoverTargets also reports targets that already exist: each is attached once. */
76
75
  attached = new Set();
77
- closed = false;
78
- constructor(socket, include) {
79
- this.socket = socket;
76
+ constructor(client, include) {
77
+ this.client = client;
80
78
  this.include = include;
81
79
  }
82
80
  /**
@@ -84,19 +82,12 @@ export class HarRecorder {
84
82
  * only the tabs it accepts, the popups they open, and tabs passed to follow().
85
83
  */
86
84
  static async start(browserUrl, signal, include) {
87
- const socket = new WebSocket(browserUrl);
88
- const recorder = new HarRecorder(socket, include);
89
- socket.addEventListener("message", event => recorder.receive(JSON.parse(String(event.data))));
90
- socket.addEventListener("close", () => recorder.fail());
91
- await new Promise((resolve, reject) => {
92
- const abort = () => { socket.close(); reject(signal.reason); };
93
- signal.addEventListener("abort", abort, { once: true });
94
- socket.addEventListener("open", () => { signal.removeEventListener("abort", abort); resolve(); }, { once: true });
95
- socket.addEventListener("error", () => { signal.removeEventListener("abort", abort); reject(new Error("Could not open a DevTools connection for recording.")); }, { once: true });
96
- });
85
+ const client = await CdpConnection.open(browserUrl, signal);
86
+ const recorder = new HarRecorder(client, include);
87
+ client.onEvent = event => recorder.receive(event);
97
88
  try {
98
- await recorder.send("Target.setDiscoverTargets", { discover: true });
99
- const { targetInfos } = await recorder.send("Target.getTargets");
89
+ await client.send("Target.setDiscoverTargets", { discover: true });
90
+ const { targetInfos } = await client.send("Target.getTargets");
100
91
  await Promise.all(targetInfos
101
92
  .filter(target => target.type === "page" && (!include || include(target.targetId))).map(target => recorder.attach(target.targetId)));
102
93
  }
@@ -125,24 +116,7 @@ export class HarRecorder {
125
116
  }
126
117
  /** Ends recording without writing anything. */
127
118
  close() {
128
- if (this.closed)
129
- return;
130
- this.socket.close();
131
- this.fail();
132
- }
133
- fail() {
134
- this.closed = true;
135
- for (const { reject } of this.pending.values())
136
- reject(new Error("The recording connection closed."));
137
- this.pending.clear();
138
- }
139
- send(method, params = {}, sessionId) {
140
- if (this.closed)
141
- return Promise.reject(new Error("The recording connection closed."));
142
- const id = ++this.nextId;
143
- const reply = new Promise((resolve, reject) => this.pending.set(id, { resolve, reject }));
144
- this.socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
145
- return reply;
119
+ this.client.close();
146
120
  }
147
121
  /** stop waits for reads in flight, such as response bodies, before writing. */
148
122
  track(read) {
@@ -153,30 +127,16 @@ export class HarRecorder {
153
127
  if (this.attached.has(targetId))
154
128
  return;
155
129
  this.attached.add(targetId);
156
- const { sessionId } = await this.send("Target.attachToTarget", { targetId, flatten: true });
130
+ const { sessionId } = await this.client.send("Target.attachToTarget", { targetId, flatten: true });
157
131
  this.tabs.set(sessionId, targetId);
158
- await this.send("Network.enable", { maxPostDataSize: 1_000_000 }, sessionId);
132
+ await this.client.send("Network.enable", { maxPostDataSize: 1_000_000 }, sessionId);
159
133
  }
160
134
  /** Records a tab opened after start; a recorder without a tab filter already does. */
161
135
  async follow(targetId) {
162
- if (!this.closed)
136
+ if (!this.client.closed)
163
137
  await this.attach(targetId);
164
138
  }
165
- receive(message) {
166
- if (message.id !== undefined) {
167
- const entry = this.pending.get(message.id);
168
- if (!entry)
169
- return;
170
- this.pending.delete(message.id);
171
- if (message.error)
172
- entry.reject(new Error(message.error.message));
173
- else
174
- entry.resolve(message.result);
175
- return;
176
- }
177
- if (this.closed || !message.method)
178
- return;
179
- const { method, params, sessionId } = message;
139
+ receive({ method, params, sessionId }) {
180
140
  // A new tab starts on Stagehand's extension page before it navigates, so every page target is attached.
181
141
  // With a tab filter, a new tab is recorded when it is a popup of a recorded one; follow() adds the rest.
182
142
  if (method === "Target.targetCreated" && params.targetInfo.type === "page"
@@ -205,7 +165,7 @@ export class HarRecorder {
205
165
  };
206
166
  this.drafts.set(key, next);
207
167
  if (next.request.hasPostData && next.request.postData === undefined) {
208
- this.track(this.send("Network.getRequestPostData", { requestId: params.requestId }, sessionId)
168
+ this.track(this.client.send("Network.getRequestPostData", { requestId: params.requestId }, sessionId)
209
169
  .then(({ postData }) => { next.request.postData = postData; }));
210
170
  }
211
171
  return;
@@ -239,7 +199,7 @@ export class HarRecorder {
239
199
  draft.encodedDataLength = params.encodedDataLength;
240
200
  this.drafts.delete(key);
241
201
  this.early.delete(key);
242
- this.track(this.send("Network.getResponseBody", { requestId: params.requestId }, sessionId)
202
+ this.track(this.client.send("Network.getResponseBody", { requestId: params.requestId }, sessionId)
243
203
  .then(({ body, base64Encoded }) => {
244
204
  if (body.length > MAX_BODY_CHARS)
245
205
  draft.bodyOmitted = true;
@@ -0,0 +1,14 @@
1
+ import { CdpConnection } from "./cdp-connection.ts";
2
+ export interface HttpAuth {
3
+ origin: string;
4
+ username: string;
5
+ password: string;
6
+ /** Also allow this credential to be used in an isolated Browserbase session. */
7
+ hosted?: boolean;
8
+ }
9
+ export declare function resolveHttpAuth(credentials: HttpAuth | undefined, store: {
10
+ hosted?: boolean;
11
+ origin?: string;
12
+ } | undefined, initialUrl: string | undefined, hosted: boolean, signal: AbortSignal): Promise<HttpAuth>;
13
+ /** Listens before the first navigation. Chrome's auth cache belongs to the isolated browser until it closes. */
14
+ export declare function answerHttpAuth(browserUrl: string, config: HttpAuth, signal: AbortSignal): Promise<CdpConnection>;
@@ -0,0 +1,114 @@
1
+ import { execFile } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { CdpConnection } from "./cdp-connection.js";
5
+ function authenticationOrigin(value, hosted) {
6
+ const url = URL.canParse(value) ? new URL(value) : undefined;
7
+ const loopback = !hosted && url?.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
8
+ if (!url || url.username || url.password || url.href !== url.origin + "/" || !(url.protocol === "https:" || loopback)) {
9
+ throw new Error("HTTP authentication requires an exact HTTPS origin. Local loopback HTTP is supported for testing.");
10
+ }
11
+ return url.origin;
12
+ }
13
+ /** Read one explicitly allowed origin through the installed native helper's local stdin/stdout protocol. */
14
+ async function fromStore(origin, signal) {
15
+ const executable = join(homedir(), ".local", "lib", "browse-http-auth", "host.py");
16
+ return new Promise((resolve, reject) => {
17
+ const denied = () => reject(new Error("The configured credential store did not return a login for this origin."));
18
+ const child = execFile(executable, ["--resolve"], { signal, timeout: 30_000, maxBuffer: 64 * 1024, encoding: "utf8" }, (error, stdout) => {
19
+ if (error) {
20
+ denied();
21
+ return;
22
+ }
23
+ try {
24
+ const result = JSON.parse(stdout);
25
+ if (typeof result?.username !== "string" || typeof result?.password !== "string") {
26
+ denied();
27
+ return;
28
+ }
29
+ resolve({ origin, username: result.username, password: result.password });
30
+ }
31
+ catch {
32
+ denied();
33
+ }
34
+ });
35
+ child.stdin?.on("error", denied);
36
+ child.stdin?.end(JSON.stringify({ origin }));
37
+ });
38
+ }
39
+ export async function resolveHttpAuth(credentials, store, initialUrl, hosted, signal) {
40
+ if (hosted && !(credentials ?? store)?.hosted)
41
+ throw new Error("This profile has not enabled HTTP authentication on Browserbase.");
42
+ if (!credentials && store) {
43
+ if (!initialUrl)
44
+ throw new Error("A start using the credential store needs a URL to select the site's login.");
45
+ const url = new URL(initialUrl);
46
+ if (url.username || url.password)
47
+ throw new Error("Supply the site's URL without credentials.");
48
+ const origin = authenticationOrigin(url.origin, hosted);
49
+ if (store.origin !== undefined && origin !== authenticationOrigin(store.origin, hosted)) {
50
+ throw new Error("The starting URL is outside the origin allowed by this profile's credential store.");
51
+ }
52
+ credentials = await fromStore(origin, signal);
53
+ }
54
+ if (!credentials || !credentials.username || credentials.username.includes(":") || !credentials.password) {
55
+ throw new Error("Configure an HTTP authentication origin, username and password or enable the credential store for this profile.");
56
+ }
57
+ return { ...credentials, origin: authenticationOrigin(credentials.origin, hosted) };
58
+ }
59
+ /** Listens before the first navigation. Chrome's auth cache belongs to the isolated browser until it closes. */
60
+ export async function answerHttpAuth(browserUrl, config, signal) {
61
+ const client = await CdpConnection.open(browserUrl, signal);
62
+ const attempted = new Map();
63
+ const enabling = new Set();
64
+ const close = () => client.close();
65
+ signal.addEventListener("abort", close, { once: true });
66
+ try {
67
+ signal.throwIfAborted();
68
+ client.onEvent = ({ method, params, sessionId }) => {
69
+ if (method === "Target.detachedFromTarget") {
70
+ attempted.delete(params.sessionId);
71
+ }
72
+ else if (method === "Target.attachedToTarget") {
73
+ const targetSession = params.sessionId;
74
+ attempted.set(targetSession, new Set());
75
+ const ready = client.send("Fetch.enable", { handleAuthRequests: true, patterns: [{ urlPattern: config.origin + "/*" }] }, targetSession)
76
+ .finally(async () => { if (params.waitingForDebugger)
77
+ await client.send("Runtime.runIfWaitingForDebugger", {}, targetSession); });
78
+ enabling.add(ready);
79
+ void ready.catch(() => { if (attempted.has(targetSession))
80
+ close(); }).finally(() => enabling.delete(ready));
81
+ }
82
+ else if (method === "Fetch.requestPaused") {
83
+ void client.send("Fetch.continueRequest", { requestId: params.requestId }, sessionId).catch(() => undefined);
84
+ }
85
+ else if (method === "Fetch.authRequired" && sessionId) {
86
+ const { requestId, request, authChallenge } = params;
87
+ const attempts = attempted.get(sessionId);
88
+ const eligible = attempts && authChallenge.source === "Server" && authChallenge.scheme.toLowerCase() === "basic"
89
+ && authChallenge.origin === config.origin && URL.canParse(request.url) && new URL(request.url).origin === config.origin;
90
+ const provide = eligible && !attempts.has(requestId);
91
+ if (provide)
92
+ attempts.add(requestId);
93
+ const authChallengeResponse = provide
94
+ ? { response: "ProvideCredentials", username: config.username, password: config.password }
95
+ : { response: eligible ? "CancelAuth" : "Default" };
96
+ void client.send("Fetch.continueWithAuth", { requestId, authChallengeResponse }, sessionId).catch(() => undefined);
97
+ }
98
+ };
99
+ // Pause new page targets until their challenge listener is installed, including tabs opened by a site.
100
+ await client.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true, filter: [{ type: "page" }, { exclude: true }] });
101
+ await Promise.all(enabling);
102
+ signal.throwIfAborted();
103
+ if (client.closed)
104
+ throw new Error("DevTools disconnected during setup.");
105
+ return client;
106
+ }
107
+ catch {
108
+ close();
109
+ throw new Error("Could not enable HTTP authentication on the isolated browser.");
110
+ }
111
+ finally {
112
+ signal.removeEventListener("abort", close);
113
+ }
114
+ }
package/dist/schema.d.ts CHANGED
@@ -43,6 +43,7 @@ declare const batchStepFields: z.ZodObject<{
43
43
  export type BatchStep = z.infer<typeof batchStepFields>;
44
44
  /** The browse tool's parameters without batch: what a host that has not adopted batch registers. */
45
45
  export declare const browserParameters: z.ZodObject<{
46
+ httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
46
47
  backend: z.ZodOptional<z.ZodEnum<{
47
48
  browserbase: "browserbase";
48
49
  local: "local";
@@ -157,6 +158,7 @@ export declare const browserParameters: z.ZodObject<{
157
158
  * prompts and approval rules a batch needs: one call can navigate, act, and run page script.
158
159
  */
159
160
  export declare const browserBatchParameters: z.ZodObject<{
161
+ httpAuth: z.ZodOptional<z.ZodLiteral<true>>;
160
162
  backend: z.ZodOptional<z.ZodEnum<{
161
163
  browserbase: "browserbase";
162
164
  local: "local";
package/dist/schema.js CHANGED
@@ -48,6 +48,7 @@ const ACTIONS = [
48
48
  ];
49
49
  /** Every action's arguments. A batch step reuses the direct controls' definitions from here instead of redefining them. */
50
50
  const browserFields = {
51
+ httpAuth: z.literal(true).optional().describe("Start a fresh isolated browser that answers HTTP Basic authentication challenges for the origin configured by the user. Requires an explicit local or browserbase backend."),
51
52
  backend: z.enum(["browserbase", "local"]).optional().describe("Only for start. Default local (or the profile's /browse backend setting); choose browserbase for clean-slate isolation, proxyCountry, a saved contextId, or at the user's request. Close before changing backends."),
52
53
  cdpUrl: z.url({ protocol: /^(?:https?|wss?)$/ }).refine(value => {
53
54
  if (!URL.canParse(value))
@@ -176,6 +177,12 @@ function checkCall(p, ctx) {
176
177
  ctx.addIssue({ code: "custom", path: ["fields"], message: "fields is only supported for ask, with 1 to 20 entries" });
177
178
  }
178
179
  const attach = p.cdpUrl !== undefined || p.endpoint !== undefined;
180
+ if (p.httpAuth && p.url && URL.canParse(p.url) && (new URL(p.url).username || new URL(p.url).password)) {
181
+ ctx.addIssue({ code: "custom", path: ["url"], message: "Use a URL without credentials when starting HTTP authentication" });
182
+ }
183
+ if (p.httpAuth && (p.action !== "start" || !p.backend || attach || p.contextId)) {
184
+ ctx.addIssue({ code: "custom", path: ["httpAuth"], message: "httpAuth requires start with an explicit backend and a fresh browser, without an endpoint, cdpUrl or contextId" });
185
+ }
179
186
  if (p.action !== "start" && (p.backend !== undefined || attach || p.headless !== undefined || p.headers !== undefined || p.extensionCdpUrl !== undefined)) {
180
187
  ctx.addIssue({ code: "custom", message: "backend, cdpUrl, endpoint, headers, extensionCdpUrl, and headless are only supported for start" });
181
188
  }
package/dist/session.d.ts CHANGED
@@ -1,8 +1,16 @@
1
1
  import type { Stagehand } from "@browserbasehq/stagehand";
2
2
  import type { AIParams, BrowserParams } from "./schema.ts";
3
+ import { type HttpAuth } from "./http-auth.ts";
3
4
  import { type CookieProvider } from "./browser-cookies.ts";
4
5
  import { type HostClassify } from "./classifier.ts";
5
6
  export interface BrowseConfig {
7
+ /** One exact origin and its credentials, resolved for an explicit isolated HTTP-auth start. */
8
+ httpAuth?: HttpAuth;
9
+ /** Allow this profile to read the initial URL's exact origin from the locally installed native helper. */
10
+ httpAuthStore?: {
11
+ hosted?: boolean;
12
+ origin?: string;
13
+ };
6
14
  apiKey?: string;
7
15
  projectId?: string;
8
16
  model?: string;
@@ -101,6 +109,8 @@ export interface AnsweredDialog {
101
109
  answer: "ok" | "cancel";
102
110
  }
103
111
  export interface ConfigurationContext {
112
+ /** Resolve origin credentials for an explicitly requested isolated launch. */
113
+ httpAuth?: true;
104
114
  sessionId: string;
105
115
  profile: string;
106
116
  cwd: string;
@@ -115,7 +125,7 @@ export interface ConfigurationContext {
115
125
  classifier?: string;
116
126
  }
117
127
  export type ConfigResolver = (context: ConfigurationContext) => BrowseConfig | Promise<BrowseConfig>;
118
- export declare function environmentConfig(): BrowseConfig;
128
+ export declare function environmentConfig(scope?: Pick<ConfigurationContext, "httpAuth">): BrowseConfig;
119
129
  /** How far a batch got. */
120
130
  export interface BatchProgress {
121
131
  total: number;
@@ -287,6 +297,8 @@ export declare class BrowseSession {
287
297
  private ownedByOther;
288
298
  /** The tabs this conversation may use: all of them, except in a shared browser the ones another conversation uses. */
289
299
  private visiblePages;
300
+ /** Browser-level DevTools endpoint of a browser we launched or the provider hosts. */
301
+ private devToolsUrl;
290
302
  /** Starts recording every tab's network traffic over a DevTools connection of its own. */
291
303
  private harStart;
292
304
  private closeOwned;
package/dist/session.js CHANGED
@@ -7,6 +7,7 @@ import { setTimeout as delay } from "node:timers/promises";
7
7
  import { z } from "zod";
8
8
  import { askNeeds, askPage, DECIDE_TEXT } from "./ask.js";
9
9
  import { guardEndpoint } from "./cdp-guard.js";
10
+ import { answerHttpAuth, resolveHttpAuth } from "./http-auth.js";
10
11
  import { HarRecorder, writeCaptureHar } from "./har.js";
11
12
  import { nameChromeProfile, refreshExtensionWorkers } from "./chrome-profile.js";
12
13
  import { BrokerConnection } from "./broker-client.js";
@@ -341,8 +342,14 @@ function domainList(value) {
341
342
  const domains = value?.split(/[\s,]+/).filter(Boolean);
342
343
  return domains?.length ? domains : undefined;
343
344
  }
344
- export function environmentConfig() {
345
+ export function environmentConfig(scope) {
345
346
  return {
347
+ ...(scope?.httpAuth && (process.env.BROWSE_HTTP_AUTH_USERNAME || process.env.BROWSE_HTTP_AUTH_PASSWORD) ? { httpAuth: {
348
+ origin: process.env.BROWSE_HTTP_AUTH_ORIGIN ?? "", username: process.env.BROWSE_HTTP_AUTH_USERNAME ?? "",
349
+ password: process.env.BROWSE_HTTP_AUTH_PASSWORD ?? "", hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true",
350
+ } } : {}),
351
+ ...(scope?.httpAuth && process.env.BROWSE_HTTP_AUTH_USE_STORE === "true"
352
+ ? { httpAuthStore: { hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true", origin: process.env.BROWSE_HTTP_AUTH_ORIGIN } } : {}),
346
353
  apiKey: process.env.BROWSERBASE_API_KEY ?? "",
347
354
  projectId: process.env.BROWSERBASE_PROJECT_ID ?? "",
348
355
  model: process.env.STAGEHAND_MODEL,
@@ -606,6 +613,8 @@ export class BrowseSession {
606
613
  if (this.delegate && !ai && params.action === "cookie_import" && this.cookies !== localCookieProvider) {
607
614
  throw new BrowseToolError("unsupported_backend", "This host's cookie source imports into Browserbase sessions only. Close, start with backend \"browserbase\", then cookie_import.");
608
615
  }
616
+ if (this.delegate && !ai && params.action === "start" && params.httpAuth)
617
+ throw new BrowseToolError("browser_change", "Close the shared browser before starting an isolated HTTP-auth session.");
609
618
  if (this.delegate)
610
619
  return this.forward(params, context, ai);
611
620
  const attempt = () => ai ? this.ai(params, context) : this.browse(params, context);
@@ -624,7 +633,7 @@ export class BrowseSession {
624
633
  }
625
634
  /** The shared browser a call would open, as the broker keys it: an attached browser or a persistent profile; else none. */
626
635
  async sharedKey(p, context) {
627
- if ((p.backend ?? this.defaultBackend) !== "local")
636
+ if (p.httpAuth || (p.backend ?? this.defaultBackend) !== "local")
628
637
  return undefined;
629
638
  if (p.cdpUrl)
630
639
  return `attach:${p.cdpUrl}`;
@@ -637,7 +646,7 @@ export class BrowseSession {
637
646
  }
638
647
  /** The real-browser session a call would open: a local start that asks for no browser of its own, in a profile that configures one. */
639
648
  async realBrowser(p, context) {
640
- if ((p.backend ?? this.defaultBackend) !== "local" || p.cdpUrl || p.endpoint || p.headless !== undefined)
649
+ if (p.httpAuth || (p.backend ?? this.defaultBackend) !== "local" || p.cdpUrl || p.endpoint || p.headless !== undefined)
641
650
  return undefined;
642
651
  // The real browser has the person's logins already; an import is for a browser this tool launches.
643
652
  if (p.action === "cookie_import")
@@ -658,7 +667,7 @@ export class BrowseSession {
658
667
  if (ai)
659
668
  return this.aiInRealBrowser(real, params, context);
660
669
  const p = params;
661
- if (p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
670
+ if (p.httpAuth || p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
662
671
  throw new BrowseToolError("browser_change", "Close the current browser before changing its backend, endpoint, or launch settings.");
663
672
  }
664
673
  // Listing the cookie sources needs no browser.
@@ -1001,6 +1010,8 @@ export class BrowseSession {
1001
1010
  if (!this.session || this.session.closing || this.session.browser.closed || !this.session.stagehand) {
1002
1011
  throw new BrowseToolError("no_session", "No usable browser session. Call close, then start or open to begin a fresh session.");
1003
1012
  }
1013
+ if (this.session.httpAuth?.closed)
1014
+ throw new BrowseToolError("http_auth_disconnected", "The browser's HTTP authentication connection ended. Close it and start a new isolated browser.");
1004
1015
  return this.session;
1005
1016
  }
1006
1017
  async start(context, p) {
@@ -1010,6 +1021,8 @@ export class BrowseSession {
1010
1021
  throw new BrowseToolError("unsupported_backend", "contextId and proxyCountry are Browserbase-only options. Close the local browser before starting a hosted one.");
1011
1022
  }
1012
1023
  if (this.session) {
1024
+ if (p.httpAuth && !this.session.httpAuth)
1025
+ throw new BrowseToolError("browser_change", "Close the current browser before starting an isolated HTTP-auth session.");
1013
1026
  if (backend !== this.session.backend || (cdpUrl !== undefined && cdpUrl !== this.session.cdpUrl)
1014
1027
  || (p.endpoint !== undefined && p.endpoint !== this.session.endpoint)
1015
1028
  || (headless !== undefined && (this.session.cdpUrl !== undefined || headless !== this.session.headless))) {
@@ -1026,7 +1039,20 @@ export class BrowseSession {
1026
1039
  }
1027
1040
  return this.current();
1028
1041
  }
1029
- const config = await this.config(context, backend);
1042
+ const config = await this.config(p.httpAuth ? { ...context, httpAuth: true } : context, backend);
1043
+ if (p.httpAuth) {
1044
+ try {
1045
+ config.httpAuth = await resolveHttpAuth(config.httpAuth, config.httpAuthStore, p.url, backend === "browserbase", context.signal);
1046
+ }
1047
+ catch (error) {
1048
+ throw new BrowseToolError("configuration", messageOf(error));
1049
+ }
1050
+ const { username, password } = config.httpAuth;
1051
+ this.secrets.add(Buffer.from(username + ":" + password).toString("base64"));
1052
+ this.secrets.add(password).add(JSON.stringify(password).slice(1, -1));
1053
+ }
1054
+ else
1055
+ delete config.httpAuth;
1030
1056
  const domainPolicy = domainLists(config, p);
1031
1057
  if (backend === "local") {
1032
1058
  const attach = p.endpoint ? config.remoteBrowsers?.[p.endpoint]
@@ -1038,7 +1064,7 @@ export class BrowseSession {
1038
1064
  for (const secret of [attach.cdpUrl, attach.extensionCdpUrl, ...Object.values(attach.headers ?? {}).filter(value => value.length >= 8)])
1039
1065
  if (secret)
1040
1066
  this.secrets.add(secret);
1041
- const userDataDir = attach ? undefined : config.localUserDataDir || undefined;
1067
+ const userDataDir = attach || p.httpAuth ? undefined : config.localUserDataDir || undefined;
1042
1068
  if (attach || userDataDir)
1043
1069
  return this.joinShared(context, config, p, domainPolicy, attach, userDataDir);
1044
1070
  // A temporary profile belongs to this conversation alone.
@@ -1072,6 +1098,7 @@ export class BrowseSession {
1072
1098
  const create = (keepAlive) => browserbase.launch({
1073
1099
  apiKey: config.apiKey, projectId: config.projectId, region: config.region, extensionId: extension.id, api_timeout: SESSION_LIFETIME_SECONDS, keepAlive,
1074
1100
  browserSettings: {
1101
+ ...(p.httpAuth ? { logSession: false, recordSession: false } : {}),
1075
1102
  viewport: { width: 1280, height: 800 }, ...(contextId ? { context: { id: contextId, persist: true } } : {}),
1076
1103
  ...(config.navigationPolicyId ? { riskPolicyId: config.navigationPolicyId } : {}),
1077
1104
  },
@@ -1094,7 +1121,7 @@ export class BrowseSession {
1094
1121
  return create(keepAlive);
1095
1122
  }
1096
1123
  };
1097
- let keepAlive = this.keepAliveAllowed;
1124
+ let keepAlive = !p.httpAuth && this.keepAliveAllowed;
1098
1125
  let browser;
1099
1126
  try {
1100
1127
  browser = await launch(keepAlive);
@@ -1126,6 +1153,16 @@ export class BrowseSession {
1126
1153
  const [, active] = await Promise.all([browser.context.addInitScript(DIALOG_GUARD), browser.context.activePage(),
1127
1154
  session.domainPolicy ? browser.context.setDomainPolicy(stagehandPolicy(session.domainPolicy)) : undefined]);
1128
1155
  session.tabId = active?.pageId;
1156
+ if (session.config.httpAuth) {
1157
+ const signal = AbortSignal.any([context.signal, AbortSignal.timeout(15_000)]);
1158
+ const url = await this.devToolsUrl(session, signal);
1159
+ const handler = await answerHttpAuth(url, session.config.httpAuth, signal);
1160
+ if (this.session !== session || session.closing || signal.aborted) {
1161
+ await handler.close();
1162
+ throw abortError();
1163
+ }
1164
+ session.httpAuth = handler;
1165
+ }
1129
1166
  return session;
1130
1167
  }
1131
1168
  catch (error) {
@@ -1325,24 +1362,27 @@ export class BrowseSession {
1325
1362
  const pages = await session.browser.context.pages();
1326
1363
  return session.shared ? pages.filter(page => !this.ownedByOther(session, page.pageId)) : pages;
1327
1364
  }
1365
+ /** Browser-level DevTools endpoint of a browser we launched or the provider hosts. */
1366
+ async devToolsUrl(session, signal) {
1367
+ if (session.backend === "local") {
1368
+ if (!session.debugPort)
1369
+ throw new BrowseToolError("unsupported_backend", "This local browser has no DevTools port.");
1370
+ const version = await fetch(`http://127.0.0.1:${session.debugPort}/json/version`, { signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) });
1371
+ return (await version.json()).webSocketDebuggerUrl;
1372
+ }
1373
+ const remote = await session.client.sessions.retrieve(session.browser.sessionId, { signal, timeout: 5000, maxRetries: 0 });
1374
+ if (!remote.connectUrl)
1375
+ throw new BrowseToolError("connection_failed", "Browserbase returned no DevTools URL for this session.");
1376
+ this.secrets.add(remote.connectUrl);
1377
+ return remote.connectUrl;
1378
+ }
1328
1379
  /** Starts recording every tab's network traffic over a DevTools connection of its own. */
1329
1380
  async harStart(session, context) {
1330
1381
  if (session.har)
1331
1382
  throw new BrowseToolError("har_active", "A recording is already running. Call har_stop to write it first.");
1332
- let browserUrl;
1333
- if (session.backend === "local") {
1334
- if (!session.debugPort)
1335
- throw new BrowseToolError("unsupported_backend", "This local browser has no DevTools port to record through. Close it and start again.");
1336
- const version = await fetch(`http://127.0.0.1:${session.debugPort}/json/version`, { signal: AbortSignal.any([context.signal, AbortSignal.timeout(5000)]) });
1337
- browserUrl = (await version.json()).webSocketDebuggerUrl;
1338
- }
1339
- else {
1340
- const remote = await session.client.sessions.retrieve(session.browser.sessionId, { timeout: 5000, maxRetries: 0 });
1341
- if (!remote.connectUrl)
1342
- throw new BrowseToolError("har_failed", "Browserbase returned no DevTools URL for this session to record through.");
1343
- browserUrl = remote.connectUrl;
1344
- this.secrets.add(browserUrl);
1345
- }
1383
+ if (session.config.httpAuth)
1384
+ throw new BrowseToolError("unsupported_backend", "HAR recording is unavailable in a browser started with HTTP authentication.");
1385
+ const browserUrl = await this.devToolsUrl(session, context.signal);
1346
1386
  context.signal.throwIfAborted();
1347
1387
  // A shared browser holds other conversations' tabs: record only this one's, and the popups they open.
1348
1388
  const include = session.shared ? (targetId) => session.ownedTabs.has(targetId) : undefined;
@@ -1363,6 +1403,7 @@ export class BrowseSession {
1363
1403
  session.har?.close();
1364
1404
  session.har = undefined;
1365
1405
  session.closing = (async () => {
1406
+ await session.httpAuth?.close();
1366
1407
  const shared = session.shared;
1367
1408
  if (shared) {
1368
1409
  if (this.session === session)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edlsh/browse-core",
3
- "version": "0.6.3",
3
+ "version": "0.7.0",
4
4
  "description": "Host-neutral browser core (Browserbase, local Chrome, remote CDP, Stagehand) shared by omp-browse, pi-browse, and hermes-browse",
5
5
  "keywords": [
6
6
  "browser",
@@ -43,6 +43,7 @@
43
43
  "check:package": "node scripts/check-package.mjs",
44
44
  "check": "bun run test && bun run typecheck && bun run build && bun run check:package",
45
45
  "prepublishOnly": "bun run build",
46
+ "test:http-auth": "bun test/http-auth.integration.ts",
46
47
  "test:local": "bun test/local-browser.integration.ts",
47
48
  "test:hosted": "bun test/hosted-browser.integration.ts",
48
49
  "test:shared": "bun test/shared-profile.integration.ts",
@@ -53,14 +54,14 @@
53
54
  "bun": ">=1.3.14"
54
55
  },
55
56
  "dependencies": {
56
- "@browserbasehq/sdk": "2.26.0",
57
+ "@browserbasehq/sdk": "2.29.0",
57
58
  "@browserbasehq/stagehand": "4.4.0",
58
- "tldts": "7.5.1",
59
+ "tldts": "7.5.5",
59
60
  "ws": "8.23.0",
60
61
  "zod": "4.6.6"
61
62
  },
62
63
  "devDependencies": {
63
- "@types/bun": "1.4.4",
64
+ "@types/bun": "1.4.5",
64
65
  "@types/ws": "8.18.2",
65
66
  "typescript": "7.0.2"
66
67
  }