@capybara-hq/plugin-browser 0.1.0-rc.12 → 0.1.0-rc.14

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "name": "browser",
4
- "version": "0.1.0-rc.12",
4
+ "version": "0.1.0-rc.14",
5
5
  "publisher": "Capybara",
6
6
  "description": {
7
7
  "en": "A real browser in the conversation owner's device for agents: navigate, read and act on pages through tools, with a live view in the conversation panel and takeover by the person",
@@ -17,7 +17,7 @@
17
17
  "entry": "./dist/index.mjs",
18
18
  "manifest": {
19
19
  "name": "browser",
20
- "version": "0.1.0-rc.12",
20
+ "version": "0.1.0-rc.14",
21
21
  "sdk": "^0.1.0-rc.83",
22
22
  "provides": [],
23
23
  "requires": [],
package/README.md CHANGED
@@ -83,6 +83,12 @@ A real browser in the person's device for agents (browser use spec,
83
83
  nothing larger is downloaded). First start there: one download into the install directory (about 377 MB, 16 s on a fast
84
84
  link), one restart, then about 2 s to launch. Nothing spoofs a fingerprint, solves a CAPTCHA or
85
85
  hides automation beyond Playwright's own flags (`navigator.webdriver` stays true).
86
+ - Chromium runs with `--no-sandbox` (Playwright's default, `chromiumSandbox: false`) on Linux devices.
87
+ This is a decision (plugins#286): the device container is the isolation boundary (`CapDrop: ALL`,
88
+ `no-new-privileges`, Docker's default seccomp profile, egress through the proxy), and the agent can
89
+ already run arbitrary commands in that container, so a renderer escape gains nothing beyond what
90
+ the agent has. Chromium's sandbox would need user namespaces or a custom seccomp profile for every
91
+ command in the device (rejected), or a separate browser container (not planned now).
86
92
  - Where the browser comes from (plugins#209: never from a place the service or an agent command
87
93
  could write once it runs): the provider's install directory `CAPYBARA_SERVICE_INSTALL`
88
94
  (device-local) is filled on the first start, sealed with `.sealed`, and the daemon answers
package/dist/index.mjs CHANGED
@@ -1514,7 +1514,7 @@ function registerBrowserTools(ctx, deps) {
1514
1514
  // src/index.ts
1515
1515
  var index_default = defineExtension({
1516
1516
  name: "browser",
1517
- version: "0.1.0-rc.12",
1517
+ version: "0.1.0-rc.14",
1518
1518
  sdk: "^0.1.0-rc.83",
1519
1519
  provides: [],
1520
1520
  ui: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-browser",
3
- "version": "0.1.0-rc.12",
3
+ "version": "0.1.0-rc.14",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "A real browser in the person's device for agents: navigate, read and act on pages through tools, with a live view in the conversation and takeover by the person",
@@ -1524,6 +1524,7 @@ async function captureFitting(cdp, opts) {
1524
1524
  const area = opts.fullPage ? { x: 0, y: 0, width: content.width, height: Math.min(content.height, 16384) } : { x: vv.pageX, y: vv.pageY, width: vv.clientWidth, height: vv.clientHeight };
1525
1525
  const maxScale = Math.min(1, opts.maxScale ?? 1);
1526
1526
  const zoom = opts.fullPage === true ? 1 : vv.scale > 0 && vv.scale < 1 ? vv.scale : 1;
1527
+ const device = opts.deviceScale !== void 0 && opts.deviceScale > 0 ? opts.deviceScale : 1;
1527
1528
  for (const s of SCALES) {
1528
1529
  const scale = s * maxScale * zoom;
1529
1530
  if (scale * area.width < 16) break;
@@ -1531,7 +1532,7 @@ async function captureFitting(cdp, opts) {
1531
1532
  const shot = await cdp.send("Page.captureScreenshot", {
1532
1533
  format: "jpeg",
1533
1534
  quality,
1534
- clip: { ...area, scale },
1535
+ clip: { ...area, scale: scale / device },
1535
1536
  captureBeyondViewport: opts.fullPage === true
1536
1537
  });
1537
1538
  const bytes = Buffer.from(shot.data, "base64");
@@ -1787,8 +1788,6 @@ var BrowserSession = class {
1787
1788
  * kept in this process's memory only, never in a reply, note, log, viewer message or file.
1788
1789
  */
1789
1790
  credentials = /* @__PURE__ */ new Map();
1790
- /** Whether the credential route is installed (only while credentials exist). */
1791
- authRouted = false;
1792
1791
  /** Pages whose main frame got a sign-in challenge (a 401 with WWW-Authenticate). */
1793
1792
  challenged = /* @__PURE__ */ new WeakSet();
1794
1793
  /** Requests the route signed (a 401 to one of them means the credentials are wrong). */
@@ -1811,6 +1810,12 @@ var BrowserSession = class {
1811
1810
  profileSessions = /* @__PURE__ */ new Map();
1812
1811
  /** Every agent request waits for this (a restore to desktop after hand back). */
1813
1812
  viewportGate = Promise.resolve();
1813
+ /** The clipped captures queued or running (a profile change waits for them: see `capture`). */
1814
+ captures = /* @__PURE__ */ new Set();
1815
+ /** The profile sessions that sent device metrics (a capture through one puts them back). */
1816
+ withMetrics = /* @__PURE__ */ new WeakSet();
1817
+ /** The newest clipped capture (they run one at a time). */
1818
+ captureTail = Promise.resolve();
1814
1819
  mobileUa;
1815
1820
  /** The pages' own user agent (given back when the phone profile ends). */
1816
1821
  desktopUa;
@@ -1852,7 +1857,22 @@ var BrowserSession = class {
1852
1857
  });
1853
1858
  });
1854
1859
  for (const p of ctx.pages()) this.track(p);
1855
- this.ready = this.installPermissionReports();
1860
+ this.ready = Promise.all([this.installPermissionReports(), this.installAuthRoute()]).then(
1861
+ () => void 0
1862
+ );
1863
+ }
1864
+ /**
1865
+ * The credential route, installed for the session's lifetime (plugins#292): it signs the
1866
+ * requests {@link authHeaderFor} allows, and while any route exists Playwright answers every
1867
+ * site challenge itself, cancelling one no credentials match (the patched playwright-core,
1868
+ * patches/), so a page's fetch, XHR or subresource that gets a Basic challenge completes with
1869
+ * its 401 instead of hanging in the full build. Never fails the session.
1870
+ */
1871
+ async installAuthRoute() {
1872
+ try {
1873
+ await this.ctx.route((u) => this.credentials.has(u.origin), this.onAuthRoute);
1874
+ } catch {
1875
+ }
1856
1876
  }
1857
1877
  /**
1858
1878
  * The permission report (dialogs spec §6): an init script wraps the request APIs and calls the
@@ -2219,7 +2239,7 @@ var BrowserSession = class {
2219
2239
  const id = `t${this.nextId++}`;
2220
2240
  this.ids.set(page, id);
2221
2241
  this.pages.set(id, page);
2222
- if (this.profile === "phone") void this.applyPhone(page);
2242
+ if (this.profile === "phone") this.queueProfileChange(() => this.applyPhone(page));
2223
2243
  const refresh = () => {
2224
2244
  page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
2225
2245
  };
@@ -2501,7 +2521,7 @@ var BrowserSession = class {
2501
2521
  const origin = h.view.origin;
2502
2522
  if (origin === void 0 || typeof m.username !== "string" || typeof m.password !== "string")
2503
2523
  return;
2504
- await this.signIn(origin, m.username, m.password);
2524
+ this.signIn(origin, m.username, m.password);
2505
2525
  for (const [id, x] of [...this.held])
2506
2526
  if (x.view.kind === "auth" && x.view.origin === origin) this.clearHeld(id);
2507
2527
  this.noteTo(h.owner.owner, `The user signed in to ${origin} (HTTP auth).`);
@@ -2557,22 +2577,15 @@ var BrowserSession = class {
2557
2577
  signInAsked(page, e) {
2558
2578
  return firstLine(e).includes("ERR_INVALID_AUTH_CREDENTIALS") && this.challenged.has(page);
2559
2579
  }
2560
- /** Stores the person's credentials for exactly `origin` and routes them (memory only). */
2561
- async signIn(origin, username, password) {
2580
+ /** Stores the person's credentials for exactly `origin` (memory only; the route signs). */
2581
+ signIn(origin, username, password) {
2562
2582
  this.credentials.set(
2563
2583
  origin,
2564
2584
  `Basic ${Buffer.from(`${username}:${password}`, "utf8").toString("base64")}`
2565
2585
  );
2566
- if (this.authRouted) return;
2567
- this.authRouted = true;
2568
- await this.ctx.route((u) => this.credentials.has(u.origin), this.onAuthRoute).catch(() => {
2569
- this.authRouted = false;
2570
- });
2571
2586
  }
2572
2587
  forgetCredentials(origin) {
2573
- if (!this.credentials.delete(origin) || this.credentials.size > 0 || !this.authRouted) return;
2574
- this.authRouted = false;
2575
- void this.ctx.unroute(() => true, this.onAuthRoute).catch(() => void 0);
2588
+ this.credentials.delete(origin);
2576
2589
  }
2577
2590
  onAuthRoute = async (route) => {
2578
2591
  const r = route.request();
@@ -2586,10 +2599,13 @@ var BrowserSession = class {
2586
2599
  };
2587
2600
  /**
2588
2601
  * The Authorization value a request gets, only where a browser's own page would send it: a
2589
- * request to the signed-in origin from a page whose top-level document has that origin, or a
2590
- * top-level navigation to it that this page started from that origin or that the daemon runs
2602
+ * request to the signed-in origin from a frame whose own document has that origin inside a page
2603
+ * whose top-level document has it too (an iframe's navigation: its parent frame's document), or
2604
+ * a top-level navigation to it that this page started from that origin or that the daemon runs
2591
2605
  * (the agent's or the person's address bar, history, reload). Never a service worker's request,
2592
- * a cross-site page's request (fetch, image, form post) or a redirect into the origin.
2606
+ * a cross-site page's or embedded cross-origin frame's request (fetch, image, form post), or a
2607
+ * redirect into the origin. A redirect out of the origin drops the header on every later hop
2608
+ * (the patched playwright-core, which replays a route's headers on redirects).
2593
2609
  */
2594
2610
  authHeaderFor(r) {
2595
2611
  const origin = originOf(r.url());
@@ -2603,12 +2619,16 @@ var BrowserSession = class {
2603
2619
  }
2604
2620
  const page = frame.page();
2605
2621
  const top = originOf(page.mainFrame().url());
2606
- if (!(r.isNavigationRequest() && frame === page.mainFrame())) {
2607
- return top === origin ? value : void 0;
2608
- }
2609
2622
  let root = r;
2610
2623
  for (let f = r.redirectedFrom(); f !== null; f = f.redirectedFrom()) root = f;
2611
2624
  if (originOf(root.url()) !== origin) return void 0;
2625
+ if (!r.isNavigationRequest()) {
2626
+ return top === origin && originOf(frame.url()) === origin ? value : void 0;
2627
+ }
2628
+ if (frame !== page.mainFrame()) {
2629
+ const parent = frame.parentFrame();
2630
+ return top === origin && parent !== null && originOf(parent.url()) === origin ? value : void 0;
2631
+ }
2612
2632
  if (top === origin || (this.ownNavs.get(page) ?? 0) > 0) return value;
2613
2633
  return void 0;
2614
2634
  }
@@ -2685,13 +2705,11 @@ var BrowserSession = class {
2685
2705
  this.profile = profile;
2686
2706
  this.touchTranslator.reset();
2687
2707
  const pages = this.live().map(([, p]) => p);
2688
- const run = async () => {
2708
+ this.queueProfileChange(async () => {
2689
2709
  if (profile === "phone") await Promise.all(pages.map((p) => this.applyPhone(p)));
2690
2710
  else await this.restoreAll();
2691
2711
  if (this.profile === profile) this.applied = profile;
2692
- };
2693
- const next = this.viewportGate.then(run, run);
2694
- this.viewportGate = next.catch(() => void 0);
2712
+ });
2695
2713
  this.emit({ type: "state" });
2696
2714
  void this.viewportGate.then(() => this.emit({ type: "state" }));
2697
2715
  return this.viewportGate;
@@ -2752,6 +2770,7 @@ var BrowserSession = class {
2752
2770
  screenWidth: p.width,
2753
2771
  screenHeight: p.height
2754
2772
  });
2773
+ this.withMetrics.add(cdp);
2755
2774
  await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 });
2756
2775
  await cdp.send("Emulation.setUserAgentOverride", {
2757
2776
  userAgent: this.mobileUa ?? mobileUserAgent("")
@@ -2781,7 +2800,7 @@ var BrowserSession = class {
2781
2800
  mobile: false,
2782
2801
  screenWidth: VIEWPORT.width,
2783
2802
  screenHeight: VIEWPORT.height
2784
- }).catch(() => void 0);
2803
+ }).then(() => this.withMetrics.add(cdp)).catch(() => void 0);
2785
2804
  await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }).catch(() => void 0);
2786
2805
  if (this.desktopUa !== void 0)
2787
2806
  await cdp.send("Emulation.setUserAgentOverride", { userAgent: this.desktopUa }).catch(() => void 0);
@@ -2795,9 +2814,75 @@ var BrowserSession = class {
2795
2814
  */
2796
2815
  reapplyPhone(page) {
2797
2816
  if (this.profile !== "phone") return;
2798
- const run = () => this.applyPhone(page, true).then(() => void 0);
2817
+ this.queueProfileChange(() => this.applyPhone(page, true));
2818
+ }
2819
+ /**
2820
+ * Queues a change of the pages' device metrics in the profile chain (the viewport gate): it runs
2821
+ * after the changes before it and once the clipped captures in flight are done (bounded: a
2822
+ * capture of a page a JS dialog holds never answers).
2823
+ */
2824
+ queueProfileChange(change) {
2825
+ const run = async () => {
2826
+ await this.bounded(Promise.allSettled([...this.captures]), []);
2827
+ await change();
2828
+ };
2799
2829
  const next = this.viewportGate.then(run, run);
2800
- this.viewportGate = next.catch(() => void 0);
2830
+ this.viewportGate = next.then(
2831
+ () => void 0,
2832
+ () => void 0
2833
+ );
2834
+ }
2835
+ /**
2836
+ * A clipped capture of a page (`captureFitting`, plugins#298). Chromium captures a clip by
2837
+ * replacing the page's device emulation with a temporary one built from the capturing session's
2838
+ * own metrics and, when done, puts back that session's metrics as they were at the start: from
2839
+ * a session without metrics the page is left with none (at the view size of the start, the
2840
+ * window's on macOS), a profile change in between is lost, and a second capture meanwhile reads
2841
+ * the temporary metrics. So a capture goes through the page's metrics session, runs alone (each
2842
+ * waits for the one before, bounded: a capture of a page a JS dialog holds never answers),
2843
+ * starts once no profile change is queued, and a change waits for the captures queued before it.
2844
+ */
2845
+ async capture(page, opts) {
2846
+ for (; ; ) {
2847
+ const gate = this.viewportGate;
2848
+ await gate;
2849
+ if (gate === this.viewportGate) break;
2850
+ }
2851
+ const before = this.captureTail;
2852
+ const shot = (async () => {
2853
+ await this.bounded(before, void 0);
2854
+ const cdp = await this.metricsSession(page);
2855
+ if (cdp === void 0) throw new ActionError("failed", "The tab is gone.");
2856
+ const scale = VIEWPORT_PROFILES[this.applied].scale;
2857
+ return captureFitting(cdp, { ...opts, deviceScale: scale });
2858
+ })();
2859
+ this.captureTail = shot.catch(() => void 0);
2860
+ this.captures.add(shot);
2861
+ try {
2862
+ return await shot;
2863
+ } finally {
2864
+ this.captures.delete(shot);
2865
+ }
2866
+ }
2867
+ /**
2868
+ * The session a page's captures go through: its profile session, holding the metrics of the
2869
+ * profile applied (sent now if it never sent any). A capture puts back the metrics of its own
2870
+ * session when done, so on this one it puts back the page's real metrics.
2871
+ */
2872
+ async metricsSession(page) {
2873
+ const cdp = await this.profileSession(page);
2874
+ if (cdp === void 0 || this.withMetrics.has(cdp)) return cdp;
2875
+ const p = VIEWPORT_PROFILES[this.applied];
2876
+ await cdp.send("Emulation.setDeviceMetricsOverride", {
2877
+ width: p.width,
2878
+ height: p.height,
2879
+ deviceScaleFactor: p.scale,
2880
+ mobile: p.mobile,
2881
+ screenWidth: p.width,
2882
+ screenHeight: p.height
2883
+ });
2884
+ this.withMetrics.add(cdp);
2885
+ return cdp;
2801
2886
  }
2802
2887
  /** Every page that got the phone profile back on desktop. */
2803
2888
  async restoreAll() {
@@ -3719,25 +3804,20 @@ var BrowserSession = class {
3719
3804
  const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
3720
3805
  if (!(maxBytes > 0))
3721
3806
  throw new ActionError("failed", "screenshot needs a positive maxBytes.");
3722
- const cdp = await this.ctx.newCDPSession(page);
3723
- try {
3724
- const shot = await captureFitting(cdp, {
3725
- maxBytes,
3726
- ...req.fullPage === true ? { fullPage: true } : {}
3727
- });
3728
- if (shot === null) {
3729
- throw new ActionError(
3730
- "failed",
3731
- `The page does not fit in a ${maxBytes}-byte screenshot even at the smallest size; use snapshot instead.`
3732
- );
3733
- }
3734
- return {
3735
- image: shot.data,
3736
- text: `Screenshot ${shot.width}x${shot.height} (viewport ${VIEWPORT.width}x${VIEWPORT.height}).`
3737
- };
3738
- } finally {
3739
- await cdp.detach().catch(() => void 0);
3807
+ const shot = await this.capture(page, {
3808
+ maxBytes,
3809
+ ...req.fullPage === true ? { fullPage: true } : {}
3810
+ });
3811
+ if (shot === null) {
3812
+ throw new ActionError(
3813
+ "failed",
3814
+ `The page does not fit in a ${maxBytes}-byte screenshot even at the smallest size; use snapshot instead.`
3815
+ );
3740
3816
  }
3817
+ return {
3818
+ image: shot.data,
3819
+ text: `Screenshot ${shot.width}x${shot.height} (viewport ${VIEWPORT.width}x${VIEWPORT.height}).`
3820
+ };
3741
3821
  }
3742
3822
  }
3743
3823
  throw new ActionError(
@@ -5389,7 +5469,7 @@ var ViewerSession = class {
5389
5469
  this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
5390
5470
  let timer;
5391
5471
  const first = await Promise.race([
5392
- captureFitting(cdp, { maxBytes: this.jpegBudget, maxScale: this.scale }).catch(() => null),
5472
+ this.browser.capture(page, { maxBytes: this.jpegBudget, maxScale: this.scale }).catch(() => null),
5393
5473
  new Promise((r) => {
5394
5474
  timer = this.clock.schedule(() => r(null), FIRST_FRAME_MS);
5395
5475
  })
@@ -37903,6 +37903,11 @@ var init_crNetworkManager = __esm({
37903
37903
  } else if (credentials) {
37904
37904
  response2 = "ProvideCredentials";
37905
37905
  this._attemptedAuthentications.add(attemptKey);
37906
+ } else if (!isProxy) {
37907
+ // capybara patch (plugins#292): no site credentials match, so cancel the challenge and let
37908
+ // the request complete with its 401; "Default" leaves a subresource's challenge hanging in
37909
+ // headless Chromium
37910
+ response2 = "CancelAuth";
37906
37911
  }
37907
37912
  const { username, password } = credentials || { username: void 0, password: void 0 };
37908
37913
  sessionInfo.session._sendMayFail("Fetch.continueWithAuth", {
@@ -37926,8 +37931,12 @@ var init_crNetworkManager = __esm({
37926
37931
  const existingRequest = this._requestIdToRequest.get(requestId);
37927
37932
  const alreadyContinuedParams = existingRequest?._originalRequestRoute?._alreadyContinuedParams;
37928
37933
  if (alreadyContinuedParams && !event.redirectedRequestId) {
37934
+ // capybara patch (plugins#292 review): a redirect hop paused before its
37935
+ // requestWillBeSent lands here too (a subresource's hop carries no redirectedRequestId)
37936
+ const headers = alreadyContinuedParams.headers && crossedOrigin(existingRequest.request, event.request.url) ? alreadyContinuedParams.headers.filter((h) => h.name.toLowerCase() !== "authorization") : alreadyContinuedParams.headers;
37929
37937
  sessionInfo.session._sendMayFail("Fetch.continueRequest", {
37930
37938
  ...alreadyContinuedParams,
37939
+ headers,
37931
37940
  requestId: event.requestId
37932
37941
  });
37933
37942
  return;
@@ -37988,6 +37997,11 @@ var init_crNetworkManager = __esm({
37988
37997
  if (headersOverride) {
37989
37998
  const originalHeaders = Object.entries(requestPausedEvent.request.headers).map(([name, value2]) => ({ name, value: value2 }));
37990
37999
  headersOverride = removeCookieHeader(applyHeadersOverrides(originalHeaders, headersOverride));
38000
+ // capybara patch (plugins#292 review): the route's headers are replayed on every
38001
+ // redirect hop; once the chain leaves the origin of its first request, an
38002
+ // Authorization header is never sent again (as a browser drops it)
38003
+ if (redirectedFrom && crossedOrigin(redirectedFrom.request, requestWillBeSentEvent.request.url))
38004
+ headersOverride = headersOverride.filter((h) => h.name.toLowerCase() !== "authorization");
37991
38005
  }
37992
38006
  requestPausedSessionInfo.session._sendMayFail("Fetch.continueRequest", { requestId: requestPausedEvent.requestId, headers: headersOverride });
37993
38007
  } else {
@@ -53329,6 +53343,22 @@ function validateBrowserContextOptions(options, browserOptions) {
53329
53343
  throw new Error(`"recordVideo.fps" must be a positive number, got ${options.recordVideo.fps}`);
53330
53344
  verifyGeolocation(options.geolocation);
53331
53345
  }
53346
+ // capybara patch (plugins#292 review): whether a redirect chain (its last hop `request`, then
53347
+ // `nextUrl`) has left the origin of its first request
53348
+ function crossedOrigin(request2, nextUrl) {
53349
+ const originOf = (u) => {
53350
+ try {
53351
+ return new URL(u).origin;
53352
+ } catch {
53353
+ return void 0;
53354
+ }
53355
+ };
53356
+ const urls = [nextUrl];
53357
+ for (let r = request2; r; r = r.redirectedFrom())
53358
+ urls.push(r.url());
53359
+ const first = originOf(urls[urls.length - 1]);
53360
+ return first === void 0 || urls.some((u) => originOf(u) !== first);
53361
+ }
53332
53362
  function findMatchingHttpCredentials(credentials, url3) {
53333
53363
  const origin = new URL(url3).origin.toLowerCase();
53334
53364
  return credentials?.find((c) => !c.origin || c.origin.toLowerCase() === origin);