browse 0.11.3 → 0.11.4

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 (81) hide show
  1. package/README.md +56 -25
  2. package/bin/run.js +2 -5
  3. package/dist/commands/click.js +1 -1
  4. package/dist/commands/cloud/contexts/get.js +1 -1
  5. package/dist/commands/cloud/contexts/list.js +2 -5
  6. package/dist/commands/cloud/extensions/get.js +1 -1
  7. package/dist/commands/cloud/extensions/upload.js +34 -8
  8. package/dist/commands/cloud/projects/get.js +1 -1
  9. package/dist/commands/cloud/projects/list.js +2 -5
  10. package/dist/commands/cloud/projects/usage.js +1 -1
  11. package/dist/commands/cloud/search.js +2 -2
  12. package/dist/commands/cloud/secrets/list.js +1 -1
  13. package/dist/commands/cloud/sessions/create.js +2 -7
  14. package/dist/commands/cloud/sessions/debug.js +1 -1
  15. package/dist/commands/cloud/sessions/get.js +1 -1
  16. package/dist/commands/cloud/sessions/list.js +2 -2
  17. package/dist/commands/cloud/sessions/logs.js +2 -4
  18. package/dist/commands/cloud/sessions/uploads/create.js +1 -3
  19. package/dist/commands/cursor.js +2 -5
  20. package/dist/commands/doctor.js +1 -1
  21. package/dist/commands/eval.js +1 -1
  22. package/dist/commands/fill.js +1 -1
  23. package/dist/commands/functions/secrets/list.js +1 -1
  24. package/dist/commands/get.js +1 -1
  25. package/dist/commands/highlight.js +1 -1
  26. package/dist/commands/is.js +1 -1
  27. package/dist/commands/network/clear.js +2 -5
  28. package/dist/commands/network/off.js +2 -5
  29. package/dist/commands/network/on.js +2 -5
  30. package/dist/commands/network/path.js +2 -5
  31. package/dist/commands/press.js +2 -6
  32. package/dist/commands/select.js +1 -1
  33. package/dist/commands/skills/find.js +1 -1
  34. package/dist/commands/skills/list.js +2 -2
  35. package/dist/commands/skills/show.js +3 -1
  36. package/dist/commands/snapshot.js +1 -1
  37. package/dist/commands/status.js +1 -4
  38. package/dist/commands/tab/close.js +1 -1
  39. package/dist/commands/tab/list.js +2 -5
  40. package/dist/commands/tab/new.js +1 -1
  41. package/dist/commands/tab/switch.js +1 -1
  42. package/dist/commands/templates/find.js +1 -1
  43. package/dist/commands/templates/list.js +1 -1
  44. package/dist/commands/type.js +1 -1
  45. package/dist/commands/upload.js +1 -1
  46. package/dist/hooks/command-not-found.js +2 -6
  47. package/dist/lib/child-process.js +22 -0
  48. package/dist/lib/cloud/api.js +1 -2
  49. package/dist/lib/cloud/reduce-logs.js +3 -6
  50. package/dist/lib/driver/cdp-tail.js +4 -15
  51. package/dist/lib/driver/command-cli.js +21 -12
  52. package/dist/lib/driver/commands/elements.js +2 -6
  53. package/dist/lib/driver/commands/navigation.js +2 -4
  54. package/dist/lib/driver/commands/page-info.js +1 -3
  55. package/dist/lib/driver/commands/runtime.js +2 -5
  56. package/dist/lib/driver/commands/selectors.js +2 -6
  57. package/dist/lib/driver/commands/tabs.js +3 -8
  58. package/dist/lib/driver/daemon/client.js +30 -20
  59. package/dist/lib/driver/daemon/paths.js +131 -9
  60. package/dist/lib/driver/daemon/server.js +3 -5
  61. package/dist/lib/driver/doctor.js +19 -8
  62. package/dist/lib/driver/local-cdp-discovery.js +1 -1
  63. package/dist/lib/driver/network-capture.js +1 -1
  64. package/dist/lib/driver/network-cdp-sidecar.js +14 -11
  65. package/dist/lib/driver/remote.js +1 -1
  66. package/dist/lib/driver/runtime.js +7 -3
  67. package/dist/lib/driver/session-manager.js +7 -5
  68. package/dist/lib/functions/dev.js +21 -18
  69. package/dist/lib/functions/init.js +8 -8
  70. package/dist/lib/functions/publish.js +6 -9
  71. package/dist/lib/functions/shared.js +4 -2
  72. package/dist/lib/secrets/seal.js +1 -4
  73. package/dist/lib/skills/catalog.js +1 -2
  74. package/dist/lib/skills/install.js +11 -39
  75. package/dist/lib/telemetry.js +5 -17
  76. package/dist/lib/templates/api.js +1 -2
  77. package/dist/lib/templates/scaffold.js +5 -7
  78. package/dist/lib/update.js +2 -5
  79. package/oclif.manifest.json +198 -191
  80. package/package.json +79 -66
  81. package/skills/browse/SKILL.md +1 -0
@@ -1,17 +1,17 @@
1
- import { promises as fs } from "node:fs";
1
+ import { constants, promises as fs } from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { fail } from "../../errors.js";
5
6
  export const PRIVATE_DIR_MODE = 0o700;
6
7
  export const PRIVATE_FILE_MODE = 0o600;
7
8
  export function runtimeDir() {
8
- return (process.env.BROWSE_DAEMON_DIR ??
9
- path.join(os.tmpdir(), defaultRuntimeDirName()));
9
+ const dir = process.env.BROWSE_DAEMON_DIR ?? path.join(os.tmpdir(), defaultRuntimeDirName());
10
+ assertNonEmptyDir(dir);
11
+ return dir;
10
12
  }
11
13
  export function sanitizeSessionName(session) {
12
- const sanitized = session
13
- .replace(/[^A-Za-z0-9._-]/g, "-")
14
- .replace(/^[.-]+|[.-]+$/g, "");
14
+ const sanitized = session.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[.-]+|[.-]+$/g, "");
15
15
  const base = sanitized || "default";
16
16
  if (base === session)
17
17
  return base;
@@ -24,8 +24,125 @@ export async function ensureRuntimeDir() {
24
24
  return dir;
25
25
  }
26
26
  export async function ensurePrivateDir(dir) {
27
- await fs.mkdir(dir, { mode: PRIVATE_DIR_MODE, recursive: true });
28
- await chmodIfSupported(dir, PRIVATE_DIR_MODE);
27
+ assertNonEmptyDir(dir);
28
+ // Strip trailing separators so O_NOFOLLOW also rejects "symlink/".
29
+ const resolvedDir = path.resolve(dir);
30
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
31
+ if (process.platform !== "win32" && uid !== undefined) {
32
+ await ensureTrustedParents(resolvedDir, uid);
33
+ }
34
+ try {
35
+ await fs.mkdir(resolvedDir, { mode: PRIVATE_DIR_MODE, recursive: true });
36
+ }
37
+ catch (error) {
38
+ const code = error.code;
39
+ if (code !== "EEXIST" && code !== "ENOENT")
40
+ throw error;
41
+ // mkdir can report ENOENT for a dangling symlink. Inspect the entry below;
42
+ // if it really is missing, opening it will fail without changing anything.
43
+ }
44
+ if (process.platform === "win32") {
45
+ if (!(await fs.lstat(resolvedDir)).isDirectory())
46
+ failInvalidDirectory(dir);
47
+ return;
48
+ }
49
+ const handle = await fs
50
+ .open(resolvedDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
51
+ .catch((error) => {
52
+ if (error.code === "ELOOP" || error.code === "ENOTDIR")
53
+ failInvalidDirectory(dir);
54
+ throw error;
55
+ });
56
+ try {
57
+ // Inspect and chmod the same directory, even if its pathname is replaced.
58
+ const entry = await handle.stat();
59
+ if (!entry.isDirectory())
60
+ failInvalidDirectory(dir);
61
+ // Root must also reject foreign ownership: chmod does not change the owner.
62
+ if (uid !== undefined && entry.uid !== uid) {
63
+ fail(`Refusing to use ${dir}: it is owned by another user. Set BROWSE_DAEMON_DIR to a directory you own.`, 1, { resultCode: "daemon_dir_not_owned" });
64
+ }
65
+ await handle.chmod(PRIVATE_DIR_MODE);
66
+ }
67
+ finally {
68
+ await handle.close();
69
+ }
70
+ }
71
+ /**
72
+ * Check from the root downward so each entry is protected before we inspect it
73
+ * or create a child. A trusted sticky directory (such as /tmp) protects entries
74
+ * owned by us or root; a foreign owner can replace children even with that bit.
75
+ * Never realpath first: that would hide replaceable symlink ancestors.
76
+ */
77
+ async function ensureTrustedParents(dir, uid) {
78
+ let symlinksRemaining = 40;
79
+ const reject = (parent, reason) => {
80
+ fail(`Refusing to use ${dir}: parent ${parent} ${reason}. Choose a runtime directory beneath trusted parents owned by you or the system.`, 1, { resultCode: "daemon_dir_unsafe_parent" });
81
+ };
82
+ const inspect = async (parent, createMissing) => {
83
+ const entry = await fs.lstat(parent).catch(async (error) => {
84
+ if (error.code !== "ENOENT" || !createMissing)
85
+ throw error;
86
+ // The ancestor is already trusted. Inspect even an entry created by a
87
+ // concurrent process instead of assuming mkdir established ownership.
88
+ await fs.mkdir(parent, { mode: PRIVATE_DIR_MODE }).catch((error) => {
89
+ if (error.code !== "EEXIST")
90
+ throw error;
91
+ });
92
+ return fs.lstat(parent);
93
+ });
94
+ if (entry.uid !== 0 && entry.uid !== uid)
95
+ reject(parent, "is owned by another user");
96
+ if (!entry.isSymbolicLink()) {
97
+ if (!entry.isDirectory())
98
+ reject(parent, "is not a directory");
99
+ if ((entry.mode & 0o022) !== 0 && (entry.mode & 0o1000) === 0) {
100
+ reject(parent, "is writable by other users without sticky-bit protection");
101
+ }
102
+ }
103
+ return entry;
104
+ };
105
+ const root = path.parse(dir).root;
106
+ await inspect(root, false);
107
+ const walk = async (start, parts, createMissing) => {
108
+ let current = start;
109
+ for (const part of parts) {
110
+ if (part === "" || part === ".")
111
+ continue;
112
+ if (part === "..") {
113
+ current = path.dirname(current);
114
+ continue;
115
+ }
116
+ const next = path.join(current, part);
117
+ const entry = await inspect(next, createMissing);
118
+ if (entry.isSymbolicLink()) {
119
+ if (symlinksRemaining-- === 0)
120
+ reject(next, "has too many symbolic links");
121
+ const target = await fs.readlink(next);
122
+ // Resolve each target component before processing '..', just as the
123
+ // kernel does. Normalizing the target first could check the wrong path.
124
+ // Never create missing targets of dangling ancestor links.
125
+ current = await walk(path.isAbsolute(target) ? root : current, target.split(path.sep), false);
126
+ }
127
+ else {
128
+ current = next;
129
+ }
130
+ }
131
+ return current;
132
+ };
133
+ await walk(root, path.relative(root, path.dirname(dir)).split(path.sep), true);
134
+ }
135
+ function assertNonEmptyDir(dir) {
136
+ if (dir === "") {
137
+ fail("Refusing to use an empty directory path. Unset BROWSE_DAEMON_DIR or set a non-empty path.", 1, {
138
+ resultCode: "daemon_dir_invalid",
139
+ });
140
+ }
141
+ }
142
+ function failInvalidDirectory(dir) {
143
+ fail(`Refusing to use ${dir}: it must be a directory, not a symlink or other file.`, 1, {
144
+ resultCode: "daemon_dir_invalid",
145
+ });
29
146
  }
30
147
  export async function writePrivateFile(file, contents) {
31
148
  await fs.writeFile(file, contents, { mode: PRIVATE_FILE_MODE });
@@ -48,7 +165,12 @@ export async function cleanupDaemonFiles(session, { includeLock = true } = {}) {
48
165
  const files = [getSocketPath(session), getPidPath(session)];
49
166
  if (includeLock)
50
167
  files.push(getLockPath(session));
51
- await Promise.allSettled(files.map((file) => fs.unlink(file)));
168
+ for (const file of files) {
169
+ // Keep validation outside the best-effort unlink handler. Ownership loss
170
+ // must abort cleanup, including when it happens between artifact deletions.
171
+ await ensureRuntimeDir();
172
+ await fs.unlink(file).catch(() => undefined);
173
+ }
52
174
  }
53
175
  export function getNetworkDir(session) {
54
176
  return path.join(runtimeDir(), `${sanitizeSessionName(session)}-network`);
@@ -3,8 +3,8 @@ import readline from "node:readline";
3
3
  import { DriverError } from "../errors.js";
4
4
  import { DriverSessionManager } from "../session-manager.js";
5
5
  import { cleanupDaemonFiles, ensureRuntimeDir, getPidPath, getSocketPath, writePrivateFile, } from "./paths.js";
6
- import { parseRequest, serializeResponse, } from "./protocol.js";
7
- export async function runDriverDaemon({ session, target, }) {
6
+ import { parseRequest, serializeResponse } from "./protocol.js";
7
+ export async function runDriverDaemon({ session, target }) {
8
8
  await ensureRuntimeDir();
9
9
  await cleanupDaemonFiles(session, { includeLock: false });
10
10
  await writePrivateFile(getPidPath(session), String(process.pid));
@@ -169,9 +169,7 @@ function formatError(error) {
169
169
  return {
170
170
  code: error.code,
171
171
  error: message,
172
- ...(error.httpStatus !== undefined
173
- ? { httpStatus: error.httpStatus }
174
- : {}),
172
+ ...(error.httpStatus !== undefined ? { httpStatus: error.httpStatus } : {}),
175
173
  };
176
174
  }
177
175
  return { error: message };
@@ -1,9 +1,9 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import { CommandFailure } from "../errors.js";
3
3
  import { getDriverStatus } from "./daemon/client.js";
4
- import { getLockPath, getPidPath, getSocketPath, runtimeDir, } from "./daemon/paths.js";
4
+ import { getLockPath, getPidPath, getSocketPath, runtimeDir } from "./daemon/paths.js";
5
5
  import { isProcessAlive } from "./daemon/process.js";
6
- import { discoverLocalCdp, } from "./local-cdp-discovery.js";
6
+ import { discoverLocalCdp } from "./local-cdp-discovery.js";
7
7
  import { hasExplicitDriverTarget } from "./command-cli.js";
8
8
  import { resolveConnectionTarget, targetsCompatible } from "./mode.js";
9
9
  import { getRemote } from "./remote-binding.js";
@@ -116,6 +116,14 @@ export async function buildDoctorReport(options, deps = {}) {
116
116
  if (modeCheck)
117
117
  checks.push(modeCheck);
118
118
  }
119
+ else if (status?.initError) {
120
+ checks.push({
121
+ details: { error: status.initError },
122
+ message: `last start failed: ${status.initError.split("\n")[0]}`,
123
+ name: targetCheckName(status.target),
124
+ status: "fail",
125
+ });
126
+ }
119
127
  const verdict = reportVerdict(checks);
120
128
  return {
121
129
  checks,
@@ -287,9 +295,7 @@ function nextStep(verdict, checks, target, flags, session, status) {
287
295
  if (verdict !== "ok" || !target)
288
296
  return undefined;
289
297
  if (status && !hasExplicitDriverTarget(flags)) {
290
- return session === "default"
291
- ? "browse status"
292
- : `browse status --session ${session}`;
298
+ return session === "default" ? "browse status" : `browse status --session ${session}`;
293
299
  }
294
300
  const parts = ["browse open", DEFAULT_URL];
295
301
  if (target.kind === "remote") {
@@ -313,13 +319,18 @@ function nextStep(verdict, checks, target, flags, session, status) {
313
319
  }
314
320
  if (session !== "default")
315
321
  parts.push("--session", session);
316
- if (checks.some((check) => check.name === "browser" ||
317
- check.name === "browserbase" ||
318
- check.name === "cdp")) {
322
+ if (checks.some((check) => check.name === "browser" || check.name === "browserbase" || check.name === "cdp")) {
319
323
  return parts.join(" ");
320
324
  }
321
325
  return undefined;
322
326
  }
327
+ function targetCheckName(target) {
328
+ if (target.kind === "managed-local")
329
+ return "browser";
330
+ if (target.kind === "remote")
331
+ return "browserbase";
332
+ return "cdp";
333
+ }
323
334
  function formatTarget(target) {
324
335
  if (target.kind === "managed-local")
325
336
  return `managed-local, ${target.headless ? "headless" : "headed"}`;
@@ -117,7 +117,7 @@ async function isDevToolsActivePortFresh(info, probe = probeJsonVersion) {
117
117
  if (!liveWsUrl)
118
118
  return false;
119
119
  const expectedPathname = wsPathname(buildDevToolsWsUrl(info.port, info.wsPath));
120
- return (expectedPathname !== null && wsPathname(liveWsUrl) === expectedPathname);
120
+ return expectedPathname !== null && wsPathname(liveWsUrl) === expectedPathname;
121
121
  }
122
122
  async function verifyCdpWebSocket(wsUrl) {
123
123
  return new Promise((resolve) => {
@@ -1,7 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { ensurePrivateDir, ensureRuntimeDir, getNetworkDir, writePrivateFile, } from "./daemon/paths.js";
4
- import { NetworkCdpSidecar, } from "./network-cdp-sidecar.js";
4
+ import { NetworkCdpSidecar } from "./network-cdp-sidecar.js";
5
5
  /**
6
6
  * The V3 Browse network writer, adapted only at the CDP-session boundary.
7
7
  * Keeping request correlation and the on-disk request/response schema here
@@ -20,7 +20,10 @@ export class NetworkCdpSidecar {
20
20
  }
21
21
  async attach(websocketUrl, targetId) {
22
22
  await this.ensureConnected(websocketUrl);
23
- const { sessionId } = await this.sendCommand("Target.attachToTarget", { flatten: true, targetId });
23
+ const { sessionId } = await this.sendCommand("Target.attachToTarget", {
24
+ flatten: true,
25
+ targetId,
26
+ });
24
27
  this.sessions.set(sessionId, new Map());
25
28
  return new AttachedNetworkCdpSession(this, sessionId);
26
29
  }
@@ -30,13 +33,12 @@ export class NetworkCdpSidecar {
30
33
  code: "network_sidecar_closed",
31
34
  }));
32
35
  if (socket &&
33
- (socket.readyState === WebSocket.OPEN ||
34
- socket.readyState === WebSocket.CONNECTING)) {
36
+ (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) {
35
37
  socket.close();
36
38
  }
37
39
  }
38
40
  hasSession(sessionId) {
39
- return (this.socket?.readyState === WebSocket.OPEN && this.sessions.has(sessionId));
41
+ return this.socket?.readyState === WebSocket.OPEN && this.sessions.has(sessionId);
40
42
  }
41
43
  on(sessionId, event, listener) {
42
44
  const listeners = this.sessions.get(sessionId);
@@ -70,7 +72,9 @@ export class NetworkCdpSidecar {
70
72
  async ensureConnected(websocketUrl) {
71
73
  if (this.socket?.readyState === WebSocket.OPEN) {
72
74
  if (this.websocketUrl !== websocketUrl) {
73
- throw new DriverError("The browser CDP endpoint changed during the Browse session.", { code: "network_sidecar_endpoint_changed" });
75
+ throw new DriverError("The browser CDP endpoint changed during the Browse session.", {
76
+ code: "network_sidecar_endpoint_changed",
77
+ });
74
78
  }
75
79
  return;
76
80
  }
@@ -110,7 +114,9 @@ export class NetworkCdpSidecar {
110
114
  reject(failure);
111
115
  });
112
116
  socket.on("close", () => {
113
- const error = new DriverError("Network capture CDP sidecar disconnected.", { code: "network_sidecar_disconnected" });
117
+ const error = new DriverError("Network capture CDP sidecar disconnected.", {
118
+ code: "network_sidecar_disconnected",
119
+ });
114
120
  this.disconnect(socket, error);
115
121
  if (!opened)
116
122
  reject(connectionError(error));
@@ -129,9 +135,7 @@ export class NetworkCdpSidecar {
129
135
  }));
130
136
  }
131
137
  const id = this.nextId++;
132
- const message = sessionId
133
- ? { id, method, params, sessionId }
134
- : { id, method, params };
138
+ const message = sessionId ? { id, method, params, sessionId } : { id, method, params };
135
139
  return new Promise((resolve, reject) => {
136
140
  this.pending.set(id, {
137
141
  method,
@@ -171,8 +175,7 @@ export class NetworkCdpSidecar {
171
175
  return;
172
176
  }
173
177
  if (message.method === "Target.detachedFromTarget") {
174
- const detachedSessionId = message.params
175
- ?.sessionId;
178
+ const detachedSessionId = message.params?.sessionId;
176
179
  if (detachedSessionId)
177
180
  this.sessions.delete(detachedSessionId);
178
181
  return;
@@ -1,7 +1,7 @@
1
1
  import Browserbase from "@browserbasehq/sdk";
2
2
  import { browserbase } from "@browserbasehq/stagehand";
3
3
  import { StatusCodes } from "http-status-codes";
4
- import { getCliVersion, resolveInstallId, toMetadataValue, } from "../identity.js";
4
+ import { getCliVersion, resolveInstallId, toMetadataValue } from "../identity.js";
5
5
  import { DriverError } from "./errors.js";
6
6
  /**
7
7
  * Real Browserbase capability. This is the ONLY module that reads
@@ -1,6 +1,10 @@
1
- import { ensureDriverDaemon, openViaDaemon, runDriverCommandViaDaemon, } from "./daemon/client.js";
2
- export async function runDriverCommandWithTarget(session, target, command, params) {
3
- await ensureDriverDaemon({ session, target });
1
+ import { ensureDriverDaemon, openViaDaemon, runDriverCommandViaDaemon } from "./daemon/client.js";
2
+ export async function runDriverCommand(session, selection, command, params) {
3
+ if (selection.kind === "create") {
4
+ await ensureDriverDaemon({ session, target: selection.target });
5
+ }
6
+ // Reusing a session never starts a daemon. If it vanished after selection,
7
+ // propagate the connection error instead of recreating it from its reply.
4
8
  if (command === "open" && isOpenCommandParams(params)) {
5
9
  return openViaDaemon(session, params.url, params);
6
10
  }
@@ -1,7 +1,7 @@
1
- import { localBrowser, Stagehand, } from "@browserbasehq/stagehand";
1
+ import { localBrowser, Stagehand } from "@browserbasehq/stagehand";
2
2
  import { emptyRefMaps, resolveSelector as resolveCachedSelector, } from "./commands/selectors.js";
3
3
  import { executeDriverCommand } from "./commands/registry.js";
4
- import { forwardedEnvSignature, } from "./daemon/forwarded-env.js";
4
+ import { forwardedEnvSignature } from "./daemon/forwarded-env.js";
5
5
  import { DriverError } from "./errors.js";
6
6
  import { discoverLocalCdp } from "./local-cdp-discovery.js";
7
7
  import { NetworkCapture } from "./network-capture.js";
@@ -24,6 +24,9 @@ export function initFailureBackoffMs(consecutiveFailures) {
24
24
  const attempt = Math.max(1, consecutiveFailures);
25
25
  return Math.min(INIT_FAILURE_RETRY_MS * 2 ** (attempt - 1), INIT_FAILURE_RETRY_MAX_MS);
26
26
  }
27
+ function initFailureMessage(error) {
28
+ return error instanceof Error ? error.message : String(error);
29
+ }
27
30
  export function isChromeNotFoundError(error) {
28
31
  const code = error?.code;
29
32
  if (typeof code === "string" && CHROME_NOT_FOUND_ERROR_CODES.has(code)) {
@@ -119,6 +122,7 @@ export class DriverSessionManager {
119
122
  if (!this.stagehand || !this.context) {
120
123
  return {
121
124
  browserConnected: false,
125
+ ...(this.initFailure ? { initError: initFailureMessage(this.initFailure.error) } : {}),
122
126
  initialized: false,
123
127
  mode: this.target.kind,
124
128
  pages: [],
@@ -309,9 +313,7 @@ export class DriverSessionManager {
309
313
  }
310
314
  else if (resolvedTarget.kind === "managed-local") {
311
315
  browser = await localBrowser.launch({
312
- ...(resolvedTarget.chromeArgs?.length
313
- ? { args: resolvedTarget.chromeArgs }
314
- : {}),
316
+ ...(resolvedTarget.chromeArgs?.length ? { args: resolvedTarget.chromeArgs } : {}),
315
317
  ...(resolvedTarget.ignoreDefaultArgs === undefined
316
318
  ? {}
317
319
  : { ignoreDefaultArgs: resolvedTarget.ignoreDefaultArgs }),
@@ -1,11 +1,12 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawn } from "node:child_process";
3
- import { createServer, } from "node:http";
3
+ import { createServer } from "node:http";
4
4
  import { mkdir, readdir, readFile } from "node:fs/promises";
5
5
  import { existsSync } from "node:fs";
6
6
  import { join } from "node:path";
7
- import { randomUUID } from "node:crypto";
7
+ import { randomBytes, randomUUID } from "node:crypto";
8
8
  import { fail } from "../errors.js";
9
+ import { terminateChild } from "../child-process.js";
9
10
  import { functionsRequest, resolveEntrypoint, resolveFunctionsApiConfig, } from "./shared.js";
10
11
  const DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS = 10_000;
11
12
  class InvocationBridge {
@@ -219,14 +220,14 @@ class RuntimeProcess {
219
220
  }
220
221
  await new Promise((resolvePromise) => {
221
222
  const forceKillTimer = setTimeout(() => {
222
- child.kill("SIGKILL");
223
+ terminateChild(child, "SIGKILL");
223
224
  }, 5_000);
224
225
  const finish = () => {
225
226
  clearTimeout(forceKillTimer);
226
227
  resolvePromise();
227
228
  };
228
229
  child.once("exit", finish);
229
- if (!child.kill("SIGTERM")) {
230
+ if (!terminateChild(child)) {
230
231
  child.off("exit", finish);
231
232
  finish();
232
233
  }
@@ -236,13 +237,13 @@ class RuntimeProcess {
236
237
  }
237
238
  export async function startFunctionsDevServer(options) {
238
239
  const entrypoint = await resolveEntrypoint(options.entrypoint);
239
- if (!Number.isInteger(options.port) ||
240
- options.port < 1 ||
241
- options.port > 65_535) {
240
+ if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65_535) {
242
241
  fail("Port must be an integer between 1 and 65535.");
243
242
  }
244
243
  const config = resolveFunctionsApiConfig(options);
245
- const runtimeApi = `${options.host}:${options.port}`;
244
+ // Only the spawned runtime receives this prefix; the public invoke URL stays unchanged.
245
+ const runtimeToken = randomBytes(32).toString("hex");
246
+ const runtimeApi = `${options.host}:${options.port}/${runtimeToken}`;
246
247
  const bridge = new InvocationBridge();
247
248
  const sessionManager = new BrowserSessionManager(config);
248
249
  const manifestStore = new ManifestStore();
@@ -252,7 +253,7 @@ export async function startFunctionsDevServer(options) {
252
253
  await mkdir(join(process.cwd(), ".browserbase", "functions", "manifests"), {
253
254
  recursive: true,
254
255
  });
255
- const server = await startServer(options.host, options.port, bridge, manifestStore, sessionManager);
256
+ const server = await startServer(options.host, options.port, bridge, manifestStore, sessionManager, runtimeToken);
256
257
  const runtime = new RuntimeProcess(entrypoint, runtimeApi, options.verbose);
257
258
  await runtime.start();
258
259
  const runtimeConnected = await waitForRuntime(bridge, manifestStore, getRuntimeStartupTimeoutMs());
@@ -281,9 +282,9 @@ export async function startFunctionsDevServer(options) {
281
282
  process.exit(0);
282
283
  });
283
284
  }
284
- async function startServer(host, port, bridge, manifestStore, sessionManager) {
285
+ async function startServer(host, port, bridge, manifestStore, sessionManager, runtimeToken) {
285
286
  const server = createServer((request, response) => {
286
- routeRequest(request, response, bridge, manifestStore, sessionManager).catch((error) => {
287
+ routeRequest(request, response, bridge, manifestStore, sessionManager, runtimeToken).catch((error) => {
287
288
  handleRouteError(response, error);
288
289
  });
289
290
  });
@@ -327,10 +328,14 @@ function getRuntimeStartupTimeoutMs() {
327
328
  }
328
329
  return parsed;
329
330
  }
330
- async function routeRequest(request, response, bridge, manifestStore, sessionManager) {
331
+ async function routeRequest(request, response, bridge, manifestStore, sessionManager, runtimeToken) {
331
332
  const method = request.method || "GET";
332
333
  const url = new URL(request.url || "/", `http://${request.headers.host || "127.0.0.1"}`);
333
334
  const path = url.pathname;
335
+ // Authenticate runtime routes before accepting a poll or completing an invocation.
336
+ const runtimePath = path.startsWith(`/${runtimeToken}/`)
337
+ ? path.slice(runtimeToken.length + 1)
338
+ : "";
334
339
  const corsHeaders = corsHeadersForRequest(request);
335
340
  if (!corsHeaders) {
336
341
  sendForbiddenOrigin(response);
@@ -344,7 +349,7 @@ async function routeRequest(request, response, bridge, manifestStore, sessionMan
344
349
  sendJson(response, 200, { ok: true }, corsHeaders);
345
350
  return;
346
351
  }
347
- if (method === "GET" && path === "/2018-06-01/runtime/invocation/next") {
352
+ if (method === "GET" && runtimePath === "/2018-06-01/runtime/invocation/next") {
348
353
  bridge.holdNextConnection(response, corsHeaders);
349
354
  return;
350
355
  }
@@ -386,7 +391,7 @@ async function routeRequest(request, response, bridge, manifestStore, sessionMan
386
391
  }
387
392
  return;
388
393
  }
389
- const responseMatch = path.match(/^\/2018-06-01\/runtime\/invocation\/([^/]+)\/response$/);
394
+ const responseMatch = runtimePath.match(/^\/2018-06-01\/runtime\/invocation\/([^/]+)\/response$/);
390
395
  if (method === "POST" && responseMatch?.[1]) {
391
396
  const requestId = responseMatch[1];
392
397
  let payload;
@@ -407,7 +412,7 @@ async function routeRequest(request, response, bridge, manifestStore, sessionMan
407
412
  sendJson(response, completed ? 202 : 400, completed ? { ok: true } : { error: "Request ID mismatch." }, corsHeaders);
408
413
  return;
409
414
  }
410
- const errorMatch = path.match(/^\/2018-06-01\/runtime\/invocation\/([^/]+)\/error$/);
415
+ const errorMatch = runtimePath.match(/^\/2018-06-01\/runtime\/invocation\/([^/]+)\/error$/);
411
416
  if (method === "POST" && errorMatch?.[1]) {
412
417
  const requestId = errorMatch[1];
413
418
  let payload;
@@ -512,9 +517,7 @@ function isAllowedLoopbackOrigin(origin) {
512
517
  const url = new URL(origin);
513
518
  if (url.protocol !== "http:" && url.protocol !== "https:")
514
519
  return false;
515
- return (url.hostname === "localhost" ||
516
- url.hostname === "127.0.0.1" ||
517
- url.hostname === "[::1]");
520
+ return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
518
521
  }
519
522
  catch {
520
523
  return false;
@@ -1,4 +1,4 @@
1
- import { spawnSync } from "node:child_process";
1
+ import spawn from "cross-spawn";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { mkdir, writeFile } from "node:fs/promises";
4
4
  import { join, resolve } from "node:path";
@@ -52,7 +52,7 @@ defineFn(
52
52
  },
53
53
  {
54
54
  // Upload the Stagehand extension once, then paste its ID here:
55
- // browse cloud extensions upload node_modules/@browserbasehq/stagehand/dist/assets/stagehand-extension.zip
55
+ // browse cloud extensions upload --stagehand
56
56
  sessionConfig: { extensionId: "your-extension-id" },
57
57
  },
58
58
  );
@@ -107,7 +107,7 @@ export async function initFunctionsProject({ packageManager, projectName, }) {
107
107
  runPackageManager(packageManager, [...install, zodVersion ? `zod@${zodVersion}` : "zod"], projectRoot);
108
108
  runPackageManager(packageManager, [...installDev, "typescript", "@types/node"], projectRoot);
109
109
  if (!existsSync(join(projectRoot, ".git"))) {
110
- spawnSync("git", ["init"], {
110
+ spawn.sync("git", ["init"], {
111
111
  cwd: projectRoot,
112
112
  stdio: "ignore",
113
113
  });
@@ -119,7 +119,7 @@ export async function initFunctionsProject({ packageManager, projectName, }) {
119
119
  nextSteps: [
120
120
  `cd ${projectName}`,
121
121
  "Edit .env with your Browserbase API key",
122
- "browse cloud extensions upload node_modules/@browserbasehq/stagehand/dist/assets/stagehand-extension.zip",
122
+ "browse cloud extensions upload --stagehand",
123
123
  "Paste the uploaded extension ID into index.ts",
124
124
  "browse functions dev index.ts",
125
125
  "browse functions publish index.ts",
@@ -128,7 +128,7 @@ export async function initFunctionsProject({ packageManager, projectName, }) {
128
128
  }, null, 2));
129
129
  }
130
130
  function ensureCommand(command) {
131
- const result = spawnSync(command, ["--version"], { stdio: "ignore" });
131
+ const result = spawn.sync(command, ["--version"], { stdio: "ignore" });
132
132
  if (result.error || result.status !== 0) {
133
133
  fail(`${command} is required but was not found on PATH.`);
134
134
  }
@@ -143,14 +143,14 @@ function readStagehandZodVersion(projectRoot) {
143
143
  }
144
144
  }
145
145
  function runPackageManager(packageManager, args, cwd) {
146
- const result = spawnSync(packageManager, args, {
146
+ const result = spawn.sync(packageManager, args, {
147
147
  cwd,
148
148
  stdio: ["ignore", "pipe", "pipe"],
149
149
  });
150
- if (result.stdout.length > 0) {
150
+ if (result.stdout?.length > 0) {
151
151
  process.stderr.write(result.stdout);
152
152
  }
153
- if (result.stderr.length > 0) {
153
+ if (result.stderr?.length > 0) {
154
154
  process.stderr.write(result.stderr);
155
155
  }
156
156
  if (result.error || result.status !== 0) {
@@ -1,8 +1,8 @@
1
- import archiver from "archiver";
1
+ import { TarArchive } from "archiver";
2
2
  import ignore from "ignore";
3
3
  import { copyFileSync, createWriteStream, existsSync, mkdirSync, readFileSync, rmSync, } from "node:fs";
4
4
  import { readFile, readdir, stat } from "node:fs/promises";
5
- import { spawnSync } from "node:child_process";
5
+ import spawn from "cross-spawn";
6
6
  import { tmpdir } from "node:os";
7
7
  import { dirname, join, relative } from "node:path";
8
8
  import { randomUUID } from "node:crypto";
@@ -79,7 +79,7 @@ async function createArchive(root) {
79
79
  try {
80
80
  await new Promise((resolvePromise, reject) => {
81
81
  const output = createWriteStream(archivePath);
82
- const archive = archiver("tar", {
82
+ const archive = new TarArchive({
83
83
  gzip: true,
84
84
  gzipOptions: { level: 9 },
85
85
  });
@@ -116,8 +116,7 @@ async function listPublishEntries(root) {
116
116
  return await listArchiveEntries(root, root, ignoreMatcher);
117
117
  }
118
118
  function ensureArchiveLockfile(root, entries) {
119
- if (!entries.includes("package.json") ||
120
- entries.includes("package-lock.json")) {
119
+ if (!entries.includes("package.json") || entries.includes("package-lock.json")) {
121
120
  return { entries };
122
121
  }
123
122
  const tempDir = join(tmpdir(), `bb-functions-lockgen-${randomUUID()}`);
@@ -129,15 +128,13 @@ function ensureArchiveLockfile(root, entries) {
129
128
  copyFileSync(join(root, entry), target);
130
129
  }
131
130
  // Omit resolved URLs so the builder installs from its own registry rather than the one on your machine.
132
- const result = spawnSync("npm", ["install", "--package-lock-only", "--omit-lockfile-registry-resolved"], {
131
+ const result = spawn.sync("npm", ["install", "--package-lock-only", "--omit-lockfile-registry-resolved"], {
133
132
  cwd: tempDir,
134
133
  stdio: "pipe",
135
134
  });
136
135
  if (result.status !== 0) {
137
136
  rmSync(tempDir, { recursive: true, force: true });
138
- const npmOutput = result.error
139
- ? result.error.message
140
- : result.stderr.toString().trim();
137
+ const npmOutput = result.error ? result.error.message : result.stderr.toString().trim();
141
138
  fail(`Failed to generate package-lock.json for the Functions build archive.${npmOutput ? `\n${npmOutput}` : ""}`);
142
139
  }
143
140
  return {
@@ -1,7 +1,7 @@
1
1
  import { stat } from "node:fs/promises";
2
2
  import { extname, resolve } from "node:path";
3
3
  import { CommandFailure, fail } from "../errors.js";
4
- import { classifyCommandHttpFailure, readBrowserbaseError, resolveApiKey, } from "../cloud/api.js";
4
+ import { classifyCommandHttpFailure, readBrowserbaseError, resolveApiKey } from "../cloud/api.js";
5
5
  import { setRunTelemetryCompletion } from "../run-telemetry.js";
6
6
  const defaultFunctionsBaseUrl = "https://api.browserbase.com";
7
7
  export function resolveFunctionsApiConfig(args) {
@@ -70,7 +70,9 @@ export async function pollUntil(loader, options) {
70
70
  }
71
71
  await new Promise((resolvePromise) => setTimeout(resolvePromise, intervalMs));
72
72
  }
73
- fail("Timed out while waiting for the Browserbase Functions operation to complete.", 1, { resultCode: "functions_timeout" });
73
+ fail("Timed out while waiting for the Browserbase Functions operation to complete.", 1, {
74
+ resultCode: "functions_timeout",
75
+ });
74
76
  }
75
77
  export async function resolveEntrypoint(entrypoint) {
76
78
  const absolutePath = resolve(entrypoint);