Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Browser pane: import a site's sign-in from the person's own browsers

milind-soni1839a1471136
diff --git a/electron-builder.yml b/electron-builder.yml
index b6bd25e4bb..8de9f327b0 100644
--- a/electron-builder.yml
+++ b/electron-builder.yml
@@ -73,6 +73,9 @@ extraResources:
to: licenses/models-dev-LICENSE.txt
- from: third_party/opencode/LICENSE
to: licenses/opencode-LICENSE.txt
+ # Orca (MIT): the Google cookies a sign-in import never copies.
+ - from: third_party/orca/LICENSE
+ to: licenses/orca-LICENSE.txt
# Code adapted from T3 Code (MIT): the bots' browser egress gate, the Antigravity runtime, citations.
- from: third_party/t3-code/LICENSE
to: licenses/t3-code-LICENSE.txt
diff --git a/electron/browser-pane-main.mjs b/electron/browser-pane-main.mjs
index 244b5f56c9..f4795ce66e 100644
--- a/electron/browser-pane-main.mjs
+++ b/electron/browser-pane-main.mjs
@@ -27,6 +27,18 @@ const PROFILE = /^[\w.:-]{1,128}$/;
const originOf = (url) => { try { return new URL(url).origin; } catch { return ""; } };
const isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
+/**
+ * Security: a sign-in import reads the person's own browsers, so only the app window's own top page may ask for one:
+ * not another window, and not a frame inside it. This holds while the app frames a bot's pages only from another origin
+ * or sandboxed (published apps and web panels refuse the app's own origin): a same-origin frame could call the top
+ * page's bridge.
+ */
+export function fromAppWindow(event, window) {
+ if (!window || window.isDestroyed() || event?.sender !== window.webContents || event.senderFrame !== event.sender.mainFrame) {
+ throw new Error("Sign-in import belongs to the main app window");
+ }
+}
+
const NO_PANEL = Object.freeze({ botId: null, threadId: null, profile: null, wanted: false, bounds: null, browser: null });
const samePanel = (a, b) => a.botId === b.botId && a.threadId === b.threadId && a.profile === b.profile;
@@ -42,6 +54,7 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
const identities = new Map();
const pings = new Map();
const resolving = new Map();
+ const asking = new Map();
const watched = new WeakSet();
let server = null;
let tabCount = 0;
@@ -413,9 +426,53 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
resolve?.(message.browser);
return;
}
+ case "set-cookies": return void setCookies(message);
+ case "cookie-sources-result":
+ case "cookie-import-result":
+ case "cookie-offer-result": {
+ const answer = asking.get(message.req);
+ asking.delete(message.req);
+ answer?.(message);
+ return;
+ }
}
}
+ /** An import's cookies into a pane's partition. Security: a refused cookie is counted, never named or logged. */
+ async function setCookies(message) {
+ const session = fromPartition(message.partition);
+ let written = 0;
+ let refused = 0;
+ for (const cookie of message.cookies) {
+ try {
+ await session.cookies.set(cookie);
+ written++;
+ } catch {
+ refused++;
+ }
+ }
+ post({ op: "cookies-set", req: message.req, written, refused });
+ }
+
+ /** The person's import requests, to the server and back; `fallback` when it does not answer. */
+ function askServer(op, fields, fallback, timeoutMs) {
+ if (!server) return Promise.resolve(fallback);
+ const req = ++requests;
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => { asking.delete(req); resolve(fallback); }, timeoutMs);
+ asking.set(req, (message) => { clearTimeout(timer); resolve(message); });
+ post({ op, req, ...fields });
+ });
+ }
+
+ function importInput(input) {
+ if (!isObject(input) || typeof input.botId !== "string" || !BOT.test(input.botId) || typeof input.site !== "string" || input.site.length > 2048
+ || (input.source !== undefined && (typeof input.source !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(input.source)))) {
+ throw new Error("Sign-in import input is invalid");
+ }
+ return { botId: input.botId, threadId: typeof input.threadId === "string" && BOT.test(input.threadId) ? input.threadId : null, site: input.site };
+ }
+
function resolveBrowser(botId, threadId) {
if (!server) return Promise.resolve(null);
const req = ++requests;
@@ -476,6 +533,27 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
return { shown: Boolean(panel.wanted && panel.browser && browsers.get(panel.browser)?.active) };
},
+ /** The browsers and profiles a sign-in can be imported from: names only. */
+ async cookieSources() {
+ const answer = await askServer("cookie-sources", {}, { sources: [] }, RESOLVE_MS * 2);
+ return answer.sources;
+ },
+
+ /** Whether a site's sign-in can be imported into a bot's browser, and why not. */
+ async cookieOffer(input) {
+ const answer = await askServer("cookie-offer", importInput(input), { offered: false, reason: "unreadable" }, RESOLVE_MS * 2);
+ return { offered: answer.offered, ...(answer.reason ? { reason: answer.reason } : {}) };
+ },
+
+ /** One site's sign-in from the person's own browser into a bot's: counts and a reason code come back, never a cookie. */
+ async importCookies(input) {
+ const request = importInput(input);
+ if (typeof input.source !== "string" || typeof input.profile !== "string" || !input.profile || input.profile.length > 512) throw new Error("Sign-in import input is invalid");
+ // The person may sit at a Keychain prompt for a while.
+ const answer = await askServer("cookie-import", { ...request, source: input.source, profile: input.profile }, { result: { ok: false, reason: "unreadable" } }, 180_000);
+ return answer.result;
+ },
+
closeAll() {
for (const key of browsers.keys()) closeBrowser(key);
},
diff --git a/electron/browser-pane-main.node-test.mjs b/electron/browser-pane-main.node-test.mjs
index d654e9f450..7bcd9f34d8 100644
--- a/electron/browser-pane-main.node-test.mjs
+++ b/electron/browser-pane-main.node-test.mjs
@@ -3,7 +3,7 @@ import { EventEmitter } from "node:events";
import path from "node:path";
import test from "node:test";
-import { createBrowserPanes } from "./browser-pane-main.mjs";
+import { createBrowserPanes, fromAppWindow } from "./browser-pane-main.mjs";
const PARTITION = "persist:omb-pane-0123456789abcdef01234567";
const MSG = "openmausbot:browser-pane";
@@ -75,6 +75,8 @@ function fakeElectron() {
async clearStorageData() { this.erased++; },
async clearCache() {},
async setProxy(config) { this.proxy = config; },
+ written: [],
+ cookies: { async set(details) { if (details.name === "refuse") throw new Error(`Failed to set cookie ${details.value}`); sessions.get(name).written.push(details); } },
webRequest: { onBeforeSendHeaders(handler) { sessions.get(name).headers = handler; } },
}));
}
@@ -99,13 +101,14 @@ function fakeElectron() {
function setup({ captureMs } = {}) {
const electron = fakeElectron();
let clock = 0;
- const panes = createBrowserPanes({ createView: electron.createView, createPopup: electron.createPopup, fromPartition: electron.fromPartition, owner: () => (electron.window.destroyed ? null : electron.window), chromeVersion: "146.0.7680.0", now: () => clock, ...(captureMs ? { captureMs } : {}) });
+ const logged = [];
+ const panes = createBrowserPanes({ createView: electron.createView, createPopup: electron.createPopup, fromPartition: electron.fromPartition, owner: () => (electron.window.destroyed ? null : electron.window), chromeVersion: "146.0.7680.0", now: () => clock, log: (line) => logged.push(line), ...(captureMs ? { captureMs } : {}) });
const posted = [];
const server = { postMessage: (message) => posted.push(message) };
panes.attach(server);
const send = (message) => panes.receive(server, { type: MSG, ...message });
const last = (op) => posted.filter((message) => message.op === op).at(-1);
- return { electron, panes, server, posted, send, last, advance: (ms) => { clock += ms; } };
+ return { electron, panes, server, posted, send, last, logged, advance: (ms) => { clock += ms; } };
}
test("says hello to the server it starts, again when that server asks, and ignores any other process", () => {
@@ -502,3 +505,48 @@ test("a popup the bot's click opened stays a tab, its opener kept", async () =>
assert.equal(electron.views.at(-1).options.webContents, guest);
assert.equal(posted.filter((message) => message.op === "tab").at(-1).opener, "p1");
});
+
+test("writes an import's cookies into the pane partition and counts what Chromium refused, naming none", async () => {
+ const { send, last, electron, logged, posted } = setup();
+ const cookie = { url: "https://github.com/", name: "user_session", value: "fixture-value", domain: ".github.com", path: "/", secure: true, httpOnly: true, sameSite: "lax", expirationDate: 2_000_000_000 };
+ send({ op: "set-cookies", req: 7, partition: PARTITION, cookies: [cookie, { ...cookie, name: "refuse", value: "never-logged" }] });
+ await tick();
+ assert.deepEqual(last("cookies-set"), { type: MSG, op: "cookies-set", req: 7, written: 1, refused: 1 });
+ assert.deepEqual(electron.sessions.get(PARTITION).written, [cookie]);
+ // A cookie Chromium would not hold, or another partition, never reaches cookies.set.
+ send({ op: "set-cookies", req: 8, partition: "persist:someone-else", cookies: [cookie] });
+ send({ op: "set-cookies", req: 9, partition: PARTITION, cookies: [{ ...cookie, value: "x".repeat(5000) }] });
+ await tick();
+ assert.equal(last("cookies-set").req, 7);
+ const said = JSON.stringify([logged, posted.filter((message) => message.op !== "set-cookies")]);
+ assert.ok(!said.includes("fixture-value") && !said.includes("never-logged"));
+ assert.ok(logged.length > 0);
+});
+
+test("relays the person's import requests to the server and brings back counts only", async () => {
+ const { panes, send, posted } = setup();
+ const sources = panes.cookieSources();
+ const asked = posted.at(-1);
+ assert.equal(asked.op, "cookie-sources");
+ send({ op: "cookie-sources-result", req: asked.req, sources: [{ id: "chrome", name: "Google Chrome", engine: "chromium", profiles: [{ id: "Default", name: "Person" }] }] });
+ assert.deepEqual(await sources, [{ id: "chrome", name: "Google Chrome", engine: "chromium", profiles: [{ id: "Default", name: "Person" }] }]);
+ const imported = panes.importCookies({ botId: "a", threadId: null, site: "github.com", source: "chrome", profile: "Default" });
+ const request = posted.at(-1);
+ assert.deepEqual({ op: request.op, botId: request.botId, site: request.site, source: request.source, profile: request.profile }, { op: "cookie-import", botId: "a", site: "github.com", source: "chrome", profile: "Default" });
+ send({ op: "cookie-import-result", req: request.req, result: { ok: true, site: "github.com", imported: 3, sessionOnly: 0, skipped: {} } });
+ assert.deepEqual(await imported, { ok: true, site: "github.com", imported: 3, sessionOnly: 0, skipped: {} });
+ const offered = panes.cookieOffer({ botId: "a", threadId: null, site: "google.com" });
+ send({ op: "cookie-offer-result", req: posted.at(-1).req, offered: false, reason: "google" });
+ assert.deepEqual(await offered, { offered: false, reason: "google" });
+ await assert.rejects(panes.importCookies({ botId: "a", site: "x.com", source: "../chrome", profile: "Default" }), /invalid/);
+ await assert.rejects(panes.cookieOffer({ botId: "../a", site: "x.com" }), /invalid/);
+});
+
+test("takes an import request only from the app window's own top page", () => {
+ const mainFrame = {};
+ const window = { webContents: { mainFrame }, isDestroyed: () => false };
+ fromAppWindow({ sender: window.webContents, senderFrame: mainFrame }, window);
+ assert.throws(() => fromAppWindow({ sender: window.webContents, senderFrame: {} }, window), /main app window/);
+ assert.throws(() => fromAppWindow({ sender: { mainFrame }, senderFrame: mainFrame }, window), /main app window/);
+ assert.throws(() => fromAppWindow({ sender: window.webContents, senderFrame: mainFrame }, null), /main app window/);
+});
diff --git a/electron/browser-pane-wire.d.mts b/electron/browser-pane-wire.d.mts
index 80340aecb5..715f95ca5c 100644
--- a/electron/browser-pane-wire.d.mts
+++ b/electron/browser-pane-wire.d.mts
@@ -15,8 +15,38 @@ export type PaneToMain = Base & (
| { op: "close"; browser: string }
| { op: "erase"; partition: string }
| { op: "resolved"; req: number; browser: string | null }
+ /** A sign-in import's cookies, written into a pane's partition by the main process. */
+ | { op: "set-cookies"; req: number; partition: string; cookies: PaneCookie[] }
+ | { op: "cookie-sources-result"; req: number; sources: CookieSource[] }
+ | { op: "cookie-import-result"; req: number; result: CookieImportResult }
+ | { op: "cookie-offer-result"; req: number; offered: boolean; reason?: string }
);
+/** Electron's cookies.set details. */
+export interface PaneCookie {
+ url: string;
+ name: string;
+ value: string;
+ domain?: string;
+ path: string;
+ secure: boolean;
+ httpOnly: boolean;
+ sameSite: "unspecified" | "no_restriction" | "lax" | "strict";
+ expirationDate?: number;
+}
+
+export interface CookieSource {
+ id: string;
+ name: string;
+ engine: "chromium" | "firefox" | "safari";
+ profiles: Array<{ id: string; name: string }>;
+}
+
+/** Counts and a reason code only: never a cookie. */
+export type CookieImportResult =
+ | { ok: true; site: string; imported: number; sessionOnly: number; skipped: Partial<Record<string, number>> }
+ | { ok: false; reason: string };
+
/** `target`: the page's main frame id, which a CDP client takes as its target id. */
export type PaneToServer = Base & (
| { op: "hello" }
@@ -31,6 +61,11 @@ export type PaneToServer = Base & (
| { op: "closed"; browser: string; reason: string }
| { op: "input"; browser: string; tab?: string }
| { op: "which"; req: number; botId: string; threadId: string | null }
+ | { op: "cookies-set"; req: number; written: number; refused: number }
+ /** The person, at the app's own window, asks: which browsers can be imported from, whether a site can, and to do it. */
+ | { op: "cookie-sources"; req: number }
+ | { op: "cookie-offer"; req: number; botId: string; threadId: string | null; site: string }
+ | { op: "cookie-import"; req: number; botId: string; threadId: string | null; site: string; source: string; profile: string }
| { op: "download"; browser: string; tab: string; guid: string; state: "begin" | "inProgress" | "completed" | "canceled"; url?: string; name?: string; received?: number; total?: number; path?: string }
);
diff --git a/electron/browser-pane-wire.mjs b/electron/browser-pane-wire.mjs
index 097f398cba..0c6b025465 100644
--- a/electron/browser-pane-wire.mjs
+++ b/electron/browser-pane-wire.mjs
@@ -18,13 +18,35 @@ const DOWNLOAD_STATES = new Set(["begin", "inProgress", "completed", "canceled"]
/** An absolute folder or file path, POSIX or Windows, with no parent steps. */
const ABSOLUTE = /^(?:\/|[A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))[^\0]{0,4095}$/;
-const TO_MAIN = new Set(["hello", "open", "create", "cdp", "front", "close-tab", "close", "erase", "resolved", "cancel-download"]);
-const TO_SERVER = new Set(["hello", "opened", "failed", "created", "answer", "event", "tab", "tab-gone", "closed", "input", "which", "download"]);
+const SOURCE = /^[a-z][a-z0-9-]{0,31}$/;
+const SAME_SITE = new Set(["unspecified", "no_restriction", "lax", "strict"]);
+/** Chromium's own limit on a cookie's name and value together. */
+const COOKIE_BYTES = 4096;
+const MAX_COOKIES = 2000;
+
+const TO_MAIN = new Set(["hello", "open", "create", "cdp", "front", "close-tab", "close", "erase", "resolved", "cancel-download", "set-cookies", "cookie-sources-result", "cookie-import-result", "cookie-offer-result"]);
+const TO_SERVER = new Set(["hello", "opened", "failed", "created", "answer", "event", "tab", "tab-gone", "closed", "input", "which", "download", "cookies-set", "cookie-sources", "cookie-import", "cookie-offer"]);
const isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
const text = (value, pattern) => typeof value === "string" && pattern.test(value);
const optional = (value, pattern) => value === undefined || text(value, pattern);
const count = (value) => Number.isSafeInteger(value) && value > 0;
+const tally = (value) => Number.isSafeInteger(value) && value >= 0;
+const short = (value, limit) => typeof value === "string" && value.length <= limit && !value.includes("\0");
+
+/** Electron's cookies.set details, as an import writes them into a pane's partition. */
+function cookieValid(cookie) {
+ return isObject(cookie) && short(cookie.url, 4096) && /^https?:\/\//.test(cookie.url) && short(cookie.name, COOKIE_BYTES) && short(cookie.value, COOKIE_BYTES)
+ && cookie.name.length + cookie.value.length <= COOKIE_BYTES && (cookie.domain === undefined || short(cookie.domain, 253)) && short(cookie.path, 1024)
+ && typeof cookie.secure === "boolean" && typeof cookie.httpOnly === "boolean" && SAME_SITE.has(cookie.sameSite)
+ && (cookie.expirationDate === undefined || Number.isFinite(cookie.expirationDate));
+}
+
+function sourcesValid(sources) {
+ return Array.isArray(sources) && sources.length <= 64 && sources.every((source) => isObject(source) && text(source.id, SOURCE) && short(source.name, 80)
+ && ["chromium", "firefox", "safari"].includes(source.engine) && Array.isArray(source.profiles) && source.profiles.length <= 64
+ && source.profiles.every((profile) => isObject(profile) && short(profile.id, 512) && short(profile.name, 80)));
+}
function fieldsValid(message) {
const { op } = message;
@@ -52,6 +74,15 @@ function fieldsValid(message) {
case "event": return text(message.tab, TAB) && text(message.method, METHOD) && isObject(message.params);
case "which": return count(message.req) && text(message.botId, BOT) && (message.threadId === null || text(message.threadId, BOT));
case "resolved": return count(message.req);
+ case "set-cookies": return count(message.req) && Array.isArray(message.cookies) && message.cookies.length <= MAX_COOKIES && message.cookies.every(cookieValid);
+ case "cookies-set": return count(message.req) && tally(message.written) && tally(message.refused);
+ case "cookie-sources": return count(message.req);
+ case "cookie-sources-result": return count(message.req) && sourcesValid(message.sources);
+ case "cookie-import": case "cookie-offer":
+ return count(message.req) && text(message.botId, BOT) && (message.threadId === null || text(message.threadId, BOT)) && short(message.site, 2048)
+ && (message.op === "cookie-offer" || (text(message.source, SOURCE) && short(message.profile, 512) && message.profile.length > 0));
+ case "cookie-import-result": return count(message.req) && isObject(message.result) && typeof message.result.ok === "boolean";
+ case "cookie-offer-result": return count(message.req) && typeof message.offered === "boolean" && (message.reason === undefined || short(message.reason, 32));
default: return true;
}
}
diff --git a/electron/main.mjs b/electron/main.mjs
index f28581dd9a..b1abbb5848 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -1,4 +1,4 @@
-import { launchRecord } from "./launch-record-main.mjs"; import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, Notification, net, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron"; import { createBrowserPanes } from "./browser-pane-main.mjs";
+import { launchRecord } from "./launch-record-main.mjs"; import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, Notification, net, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron"; import { createBrowserPanes, fromAppWindow } from "./browser-pane-main.mjs";
import { createRequire } from "node:module";
import { randomBytes, randomUUID } from "node:crypto";
import fs from "node:fs";
@@ -2298,7 +2298,7 @@ ipcMain.handle("desktop-workspace:layout", localOnly("desktop-workspace:layout",
const manager = desktopWorkspaceForEvent(event);
if (!manager) return false;
return manager.layout(items);
-})); ipcMain.handle("browser-pane:show", localOnly("browser-pane:show", (event, input) => { if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error("The browser pane belongs to the main app window"); return browserPanes.show(input); }));
+})); ipcMain.handle("browser-pane:show", localOnly("browser-pane:show", (event, input) => { if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error("The browser pane belongs to the main app window"); return browserPanes.show(input); })); ipcMain.handle("browser-cookies:sources", localOnly("browser-cookies:sources", (event) => { fromAppWindow(event, mainWindow); return browserPanes.cookieSources(); })); ipcMain.handle("browser-cookies:offer", localOnly("browser-cookies:offer", (event, input) => { fromAppWindow(event, mainWindow); return browserPanes.cookieOffer(input); })); ipcMain.handle("browser-cookies:import", localOnly("browser-cookies:import", (event, input) => { fromAppWindow(event, mainWindow); return browserPanes.importCookies(input); }));
ipcMain.handle("desktop-workspace:set-interactive", localOnly("desktop-workspace:set-interactive", (event, contextId) => {
const manager = desktopWorkspaceForEvent(event);
if (!manager) return contextId == null;
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 3936b85038..ebba5b43f1 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -434,6 +434,12 @@ const bridge = {
browserPane: {
show: (input) => ipcRenderer.invoke("browser-pane:show", input),
},
+ // This computer's page only: a site's sign-in from the person's own browsers into a bot's, which they start themselves.
+ browserCookies: {
+ sources: () => ipcRenderer.invoke("browser-cookies:sources"),
+ offer: (input) => ipcRenderer.invoke("browser-cookies:offer", input),
+ import: (input) => ipcRenderer.invoke("browser-cookies:import", input),
+ },
pickFolder: (current) => ipcRenderer.invoke("desktop:pick-folder", current),
exportDiagnostics: () => ipcRenderer.invoke("desktop:export-diagnostics"),
saveFile: (filePath) => invokeWithPlainError("desktop:save-file", filePath),
diff --git a/server/browser/backends.ts b/server/browser/backends.ts
index f23a3b28ea..09093d27bd 100644
--- a/server/browser/backends.ts
+++ b/server/browser/backends.ts
@@ -52,8 +52,8 @@ export interface OpenedBrowser {
close(): Promise<void>;
/** "pane" for the desktop app's native panes. */
readonly surface?: "pane";
- /** A site turned this browser away (Google's refused sign-in, a passkey it cannot serve): the person's own Chrome or
- * their imported sign-ins are the way on. */
+ /** A site turned this browser away (Google's refused sign-in, a passkey it cannot serve): the person's own Chrome is the
+ * way on. Google sign-ins are never imported, so an import is no answer to Google's refusal. */
onSiteRefusal?(listener: (refusal: SiteRefusal) => void): () => void;
/** Where the person uses the page directly: called as they press, type or scroll in it. */
onPersonInput?(listener: () => void): () => void;
diff --git a/server/browser/cookies/cookies.test.ts b/server/browser/cookies/cookies.test.ts
new file mode 100644
index 0000000000..cd207bc638
--- /dev/null
+++ b/server/browser/cookies/cookies.test.ts
@@ -0,0 +1,314 @@
+import { randomBytes } from "node:crypto";
+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
+
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { importCookies, type CookieSink } from "./importer.ts";
+import { googleCookie, importSite, writable, type WritableCookie } from "./policy.ts";
+import { decryptChromium, deriveCbcKey, readChromium } from "./readers.ts";
+import { chromiumKey, firefoxProfiles, listSources, locate, systemKeyStore } from "./sources.ts";
+import { binaryCookies, chromiumDatabase, fakeKeys, firefoxProfile, fixtureFiles, gcmValue, localState } from "./testing/fixtures.ts";
+
+const folders: string[] = [];
+afterAll(async () => { for (const folder of folders) await removeTempDir(folder); });
+const home = () => {
+ const folder = mkdtempSync(join(tmpdir(), "omb-cookie-import-"));
+ folders.push(folder);
+ return folder;
+};
+
+// Encrypted by Python's hashlib (PBKDF2) and the OpenSSL command line (AES-128-CBC, IV of 16 spaces), not by the code
+// under test: macOS (1003 rounds, the host's digest in front), Linux v10 ("peanuts", 1 round, no digest) and v11.
+const MAC_PASSWORD = "fixture-safe-storage-password";
+const MAC_VALUE = Buffer.from("76313054cf36b9ef61400c5e10dda32d23ed80240ac72f6ee76fd804a6509492e85a1e1984c1bd0148007d8ef65f218cfb46ec2fff34bb4f089089e5cc44a474e70d0b", "hex");
+const LINUX_V10 = Buffer.from("763130de80b475a05bf7a01e53e70781dbf6d5", "hex");
+const LINUX_V11 = Buffer.from("763131f17dc4093744be3d8576d56252e2b064ef557d8d7769580dfecded47bc6059248235ea94fa6c0d103cd1ad7032f21675", "hex");
+
+const NOW = 1_800_000_000;
+const LATER = NOW + 86_400 * 30;
+
+class RecordingSink implements CookieSink {
+ readonly written: WritableCookie[] = [];
+ async write(cookies: WritableCookie[]) {
+ this.written.push(...cookies);
+ return { written: cookies.length, refused: 0 };
+ }
+}
+
+function macChrome(folder: string, rows: Parameters<typeof chromiumDatabase>[1]) {
+ const root = join(folder, "Library", "Application Support", "Google", "Chrome");
+ localState(root, { Default: "Person", "Profile 1": "Work", "Profile 9": "No cookies" });
+ chromiumDatabase(join(root, "Default", "Network", "Cookies"), rows).close();
+ chromiumDatabase(join(root, "Profile 1", "Cookies"), []).close();
+ return root;
+}
+
+describe("decrypting Chromium cookie values", () => {
+ it("reads values encrypted outside this code, on macOS and Linux", () => {
+ expect(decryptChromium(MAC_VALUE, { type: "cbc", v10: deriveCbcKey(MAC_PASSWORD, 1003), v11: null }, ".example.com")).toEqual({ value: "mac-session-value" });
+ const linux = { type: "cbc" as const, v10: deriveCbcKey("peanuts", 1), v11: deriveCbcKey("fixture-keyring-password", 1) };
+ expect(decryptChromium(LINUX_V10, linux, "example.com")).toEqual({ value: "linux-value" });
+ expect(decryptChromium(LINUX_V11, linux, ".example.com")).toEqual({ value: "keyring-value" });
+ expect(decryptChromium(LINUX_V11, { ...linux, v11: null }, ".example.com")).toEqual({ error: "failed" });
+ expect(decryptChromium(MAC_VALUE, linux, ".example.com")).toEqual({ error: "failed" });
+ });
+
+ it("reads Windows' AES-GCM values with and without the host's digest, and leaves app-bound ones alone", () => {
+ const key = randomBytes(32);
+ expect(decryptChromium(gcmValue(key, ".example.com", "win-value"), { type: "gcm", key }, ".example.com")).toEqual({ value: "win-value" });
+ expect(decryptChromium(gcmValue(key, ".example.com", "old-value", false), { type: "gcm", key }, ".example.com")).toEqual({ value: "old-value" });
+ expect(decryptChromium(gcmValue(randomBytes(32), "a.test", "x"), { type: "gcm", key }, "a.test")).toEqual({ error: "failed" });
+ expect(decryptChromium(Buffer.from(`v20${"a".repeat(40)}`), { type: "gcm", key }, "a.test")).toEqual({ error: "protected" });
+ });
+
+ it("unwraps a Windows profile's key from Local State through DPAPI, and says when there is none to unwrap", async () => {
+ const folder = home();
+ const root = join(folder, "Local", "Google", "Chrome", "User Data");
+ const key = randomBytes(32);
+ localState(root, { Default: "Person" }, Buffer.from("dpapi-wrapped"));
+ chromiumDatabase(join(root, "Default", "Network", "Cookies"), []).close();
+ const files = fixtureFiles(folder, "win32", { env: { LOCALAPPDATA: join(folder, "Local") } });
+ // win32 paths over a POSIX fixture folder: only the key's lookup goes through the BrowserFiles here.
+ const located = { source: { id: "chrome", name: "Google Chrome", engine: "chromium" as const, root }, profile: { id: "Default", name: "Person", directory: join(root, "Default"), cookies: join(root, "Default", "Network", "Cookies") } };
+ const keys = fakeKeys({ windows: key });
+ expect(await chromiumKey(files, located, keys)).toEqual({ type: "gcm", key });
+ expect(keys.asked).toEqual(["windows:13"]);
+ localState(root, { Default: "Person" });
+ await expect(chromiumKey(files, located, keys)).rejects.toThrow(/keeps no key/);
+ });
+});
+
+describe("listing another browser's profiles", () => {
+ it("names browsers and profiles from Local State and profiles.ini only, and offers Safari on macOS without looking inside it", async () => {
+ const folder = home();
+ macChrome(folder, []);
+ firefoxProfile(join(folder, "Library", "Application Support", "Firefox"), "Profiles/abc.default", "default-release", []);
+ const sources = await listSources(fixtureFiles(folder, "darwin", { safari: true }));
+ expect(sources).toEqual([
+ { id: "chrome", name: "Google Chrome", engine: "chromium", profiles: [{ id: "Default", name: "Person" }, { id: "Profile 1", name: "Work" }] },
+ { id: "safari", name: "Safari", engine: "safari", profiles: [{ id: "default", name: "Default" }] },
+ { id: "firefox", name: "Firefox", engine: "firefox", profiles: [{ id: "Profiles/abc.default", name: "default-release" }] },
+ ]);
+ expect(await listSources(fixtureFiles(folder, "darwin"))).toHaveLength(2);
+ });
+
+ it("never takes a path from a profile file that climbs out of the browser's folder", () => {
+ expect(firefoxProfiles("/r", "[Profile0]\nName=a\nIsRelative=1\nPath=../../etc\n[Profile1]\nName=b\nIsRelative=1\nPath=Profiles/x\n")).toEqual([{ id: "Profiles/x", name: "b", directory: "/r/Profiles/x" }]);
+ });
+});
+
+describe("importing one site", () => {
+ const request = (folder: string, platform: NodeJS.Platform, keys: ReturnType<typeof fakeKeys>, overrides: Partial<Parameters<typeof importCookies>[0]> = {}) => ({
+ files: fixtureFiles(folder, platform, { safari: true }), keys, scratch: join(folder, "scratch"), source: "chrome", profile: "Default", site: "example.com",
+ sink: new RecordingSink(), now: NOW, ...overrides,
+ });
+
+ it("brings a macOS Chrome profile's sign-in for one site, with its attributes, and nothing of any other site", async () => {
+ const folder = home();
+ macChrome(folder, [
+ { host: ".example.com", name: "session", encrypted: MAC_VALUE, expires: LATER, secure: true, httpOnly: true, sameSite: 1 },
+ { host: "app.example.com", name: "plain", value: "visible", path: "/app", expires: LATER, sameSite: 2 },
+ { host: "example.com", name: "temp", value: "for-now", expires: 0 },
+ { host: ".example.com", name: "old", value: "gone", expires: NOW - 10 },
+ { host: ".example.com", name: "chips", value: "p", expires: LATER, secure: true, partition: "https://other.test" },
+ { host: ".example.com", name: "loose", value: "n", expires: LATER, sameSite: 0 },
+ { host: ".example.com", name: "__Host-id", value: "h", expires: LATER, secure: true },
+ // Another site's value is never read: this one would not even decrypt.
+ { host: ".other.test", name: "x", encrypted: Buffer.from("v10broken"), expires: LATER },
+ { host: "notexample.com", name: "x", value: "y", expires: LATER },
+ ]);
+ const keys = fakeKeys({ mac: MAC_PASSWORD });
+ const sink = new RecordingSink();
+ const result = await importCookies(request(folder, "darwin", keys, { sink }));
+ expect(result).toEqual({ ok: true, site: "example.com", imported: 3, sessionOnly: 1, skipped: { expired: 1, partitioned: 1, "insecure-none": 1, "host-prefix": 1 } });
+ expect(keys.asked).toEqual(["mac:Chrome Safe Storage:Chrome"]);
+ expect(sink.written).toEqual([
+ { url: "https://example.com/", name: "session", value: "mac-session-value", domain: ".example.com", path: "/", secure: true, httpOnly: true, sameSite: "lax", expirationDate: LATER },
+ { url: "http://app.example.com/app", name: "plain", value: "visible", path: "/app", secure: false, httpOnly: false, sameSite: "strict", expirationDate: LATER },
+ { url: "http://example.com/", name: "temp", value: "for-now", path: "/", secure: false, httpOnly: false, sameSite: "unspecified" },
+ ]);
+ expect(readdirSync(join(folder, "scratch"))).toEqual([]);
+ });
+
+ it("never imports Google, and says so instead of asking for a key", async () => {
+ const folder = home();
+ macChrome(folder, [{ host: ".google.com", name: "SID", value: "s", expires: LATER }]);
+ const keys = fakeKeys({ mac: MAC_PASSWORD });
+ expect(await importCookies(request(folder, "darwin", keys, { site: "accounts.google.com" }))).toEqual({ ok: false, reason: "google" });
+ expect(keys.asked).toEqual([]);
+ expect(googleCookie(".google.com", "anything")).toBe(true);
+ expect(googleCookie("mail.google.com", "x")).toBe(true);
+ expect(googleCookie(".youtube.com", "SID")).toBe(false);
+ expect(googleCookie(".notgoogle.com", "SIDCC")).toBe(false);
+ });
+
+ it("refuses what is not one site", async () => {
+ const folder = home();
+ for (const site of ["github.io", "com", "co.uk", "127.0.0.1", "localhost", "javascript:alert(1)", ""]) {
+ expect(importSite(site), site).toBeNull();
+ expect(await importCookies(request(folder, "darwin", fakeKeys({}), { site }))).toEqual({ ok: false, reason: "not-a-site" });
+ }
+ expect(importSite("https://App.GitHub.com/x")).toBe("github.com");
+ expect(importSite("me.github.io")).toBe("me.github.io");
+ expect(importSite("shop.example.co.uk")).toBe("example.co.uk");
+ });
+
+ it("says plainly when the person turns the Keychain down, and nothing of a value reaches a log or an error", async () => {
+ const folder = home();
+ macChrome(folder, [{ host: ".example.com", name: "session", encrypted: MAC_VALUE, expires: LATER }, { host: ".example.com", name: "plain", value: "secret-plain-value", expires: LATER }]);
+ const lines: string[] = [];
+ const consoles = (["log", "info", "warn", "error", "debug"] as const).map((level) => vi.spyOn(console, level).mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(" ")); }));
+ try {
+ const denied = await importCookies(request(folder, "darwin", fakeKeys({ mac: null }), { log: (line) => lines.push(line) }));
+ expect(denied).toEqual({ ok: false, reason: "key-denied" });
+ const done = await importCookies(request(folder, "darwin", fakeKeys({ mac: MAC_PASSWORD }), { log: (line) => lines.push(line) }));
+ expect(done.ok).toBe(true);
+ const said = JSON.stringify([lines, denied, done]);
+ for (const value of ["mac-session-value", "secret-plain-value", MAC_PASSWORD]) expect(said).not.toContain(value);
+ expect(lines.length).toBeGreaterThan(0);
+ } finally {
+ for (const spy of consoles) spy.mockRestore();
+ }
+ });
+
+ it("reads a database the browser still has open, from a copy with its write-ahead log, and deletes the copy", async () => {
+ const folder = home();
+ const root = join(folder, "Library", "Application Support", "Google", "Chrome");
+ localState(root, { Default: "Person" });
+ const scratch = join(folder, "scratch");
+ mkdirSync(join(scratch, "copy-left-by-a-crash"), { recursive: true });
+ writeFileSync(join(scratch, "copy-left-by-a-crash", "Cookies"), "old copy");
+ // Still open, in WAL mode, never checkpointed: the rows live only in Cookies-wal.
+ const live = chromiumDatabase(join(root, "Default", "Network", "Cookies"), [{ host: ".example.com", name: "wal", value: "in-the-log", expires: LATER }], { wal: true });
+ try {
+ const sink = new RecordingSink();
+ const result = await importCookies(request(folder, "darwin", fakeKeys({ mac: MAC_PASSWORD }), { sink }));
+ expect(result.ok).toBe(true);
+ expect(sink.written.map((cookie) => cookie.name)).toEqual(["wal"]);
+ expect(readdirSync(scratch)).toEqual([]);
+ } finally {
+ live.close();
+ }
+ });
+
+ it("imports from Linux Chromium with Chromium's fixed password and the keyring's, asking the keyring by the browser's name", async () => {
+ const folder = home();
+ const root = join(folder, ".config", "google-chrome");
+ localState(root, { Default: "Person" });
+ chromiumDatabase(join(root, "Default", "Cookies"), [
+ { host: "example.com", name: "v10", encrypted: LINUX_V10, expires: LATER },
+ { host: ".example.com", name: "v11", encrypted: LINUX_V11, expires: LATER },
+ ]).close();
+ const keys = fakeKeys({ linux: "fixture-keyring-password" });
+ const sink = new RecordingSink();
+ expect(await importCookies(request(folder, "linux", keys, { sink }))).toMatchObject({ ok: true, imported: 2 });
+ expect(sink.written.map((cookie) => cookie.value)).toEqual(["linux-value", "keyring-value"]);
+ expect(keys.asked).toEqual(["linux:chrome"]);
+ });
+
+ it("says the sign-in could not be read when no value decrypts, not that the site has none", async () => {
+ const folder = home();
+ macChrome(folder, [{ host: ".example.com", name: "session", encrypted: MAC_VALUE, expires: LATER }]);
+ expect(await importCookies(request(folder, "darwin", fakeKeys({ mac: "a-changed-password" })))).toEqual({ ok: false, reason: "unreadable" });
+ expect(await importCookies(request(folder, "darwin", fakeKeys({ mac: MAC_PASSWORD }), { site: "nowhere.test" }))).toEqual({ ok: false, reason: "nothing-found" });
+ });
+
+ it("says a browser's app-bound encryption keeps its cookies to itself", async () => {
+ const folder = home();
+ const root = join(folder, ".config", "google-chrome");
+ localState(root, { Default: "Person" });
+ chromiumDatabase(join(root, "Default", "Cookies"), [{ host: ".example.com", name: "a", encrypted: Buffer.from(`v20${"x".repeat(40)}`), expires: LATER }]).close();
+ expect(await importCookies(request(folder, "linux", fakeKeys({})))).toEqual({ ok: false, reason: "app-bound" });
+ });
+
+ it("imports from Firefox's default container only", async () => {
+ const folder = home();
+ firefoxProfile(join(folder, ".mozilla", "firefox"), "abc.default", "default", [
+ { host: ".example.com", name: "ff", value: "fox", expiry: LATER * 1000, secure: true, sameSite: 0 },
+ { host: ".example.com", name: "work", value: "container", expiry: LATER, originAttributes: "^userContextId=2" },
+ { host: ".other.test", name: "x", value: "y", expiry: LATER },
+ ]);
+ const sink = new RecordingSink();
+ const result = await importCookies(request(folder, "linux", fakeKeys({}), { source: "firefox", profile: "abc.default", sink }));
+ expect(result).toMatchObject({ ok: true, imported: 1 });
+ expect(sink.written).toEqual([{ url: "https://example.com/", name: "ff", value: "fox", domain: ".example.com", path: "/", secure: true, httpOnly: false, sameSite: "no_restriction", expirationDate: LATER }]);
+ });
+
+ it("reads Safari's binarycookies, and names Full Disk Access when macOS refuses the file", async () => {
+ const folder = home();
+ const file = join(folder, "Library", "Containers", "com.apple.Safari", "Data", "Library", "Cookies", "Cookies.binarycookies");
+ mkdirSync(join(file, ".."), { recursive: true });
+ writeFileSync(file, binaryCookies([
+ { host: ".example.com", name: "safari", value: "apple", expires: LATER, secure: true, httpOnly: true },
+ { host: ".other.test", name: "x", value: "y", expires: LATER },
+ ]));
+ const sink = new RecordingSink();
+ expect(await importCookies(request(folder, "darwin", fakeKeys({}), { source: "safari", profile: "default", sink }))).toMatchObject({ ok: true, imported: 1 });
+ expect(sink.written).toEqual([{ url: "https://example.com/", name: "safari", value: "apple", domain: ".example.com", path: "/", secure: true, httpOnly: true, sameSite: "unspecified", expirationDate: LATER }]);
+ chmodSync(file, 0o000);
+ try {
+ expect(await importCookies(request(folder, "darwin", fakeKeys({}), { source: "safari", profile: "default" }))).toEqual({ ok: false, reason: "full-disk-access" });
+ } finally {
+ chmodSync(file, 0o600);
+ }
+ });
+
+ it("finds only profiles the listing offers, never a path a caller names", async () => {
+ const folder = home();
+ macChrome(folder, []);
+ const files = fixtureFiles(folder, "darwin");
+ expect(await locate(files, "chrome", "../../Library")).toBeNull();
+ expect(await locate(files, "chrome", "Profile 9")).toBeNull();
+ expect(await importCookies(request(folder, "darwin", fakeKeys({}), { profile: "/etc" }))).toEqual({ ok: false, reason: "no-source" });
+ });
+});
+
+describe("the cookies a bot's browser can take", () => {
+ it("skips what a browser would refuse or could not keep, and maps the rest", () => {
+ const base = { host: ".example.com", name: "n", value: "v", path: "/", secure: true, httpOnly: false, expires: LATER, sameSite: "lax" as const };
+ expect(writable({ ...base, name: "__Secure-x", secure: false }, NOW)).toEqual({ skip: "secure-prefix" });
+ expect(writable({ ...base, host: "example.com", name: "__Host-x" }, NOW)).toMatchObject({ name: "__Host-x" });
+ expect(writable({ ...base, name: "", value: "" }, NOW)).toEqual({ skip: "empty" });
+ expect(writable({ ...base, host: ".mail.google.com" }, NOW)).toEqual({ skip: "google" });
+ expect(writable({ ...base, path: "x" }, NOW)).toMatchObject({ path: "/" });
+ });
+});
+
+describe("the system key stores", () => {
+ it("ask each system's own tool by its absolute path, with nothing from a caller in a shell", async () => {
+ const calls: Array<[string, readonly string[], string | undefined]> = [];
+ const run = async (command: string, args: readonly string[], input?: string) => {
+ calls.push([command, args, input]);
+ if (command.endsWith("powershell.exe")) return Buffer.from("key").toString("base64");
+ return command.includes("secret-tool") ? "" : "password\n";
+ };
+ const keys = systemKeyStore({ SystemRoot: "C:\\Windows" }, run);
+ expect(await keys.macPassword("Chrome Safe Storage", "Chrome")).toBe("password\n");
+ expect(await keys.windowsUnprotect(Buffer.from("blob"))).toEqual(Buffer.from("key"));
+ expect(await keys.linuxPassword("chrome")).toBeNull();
+ expect(calls.map(([command, args]) => [command, args[0]])).toEqual([
+ ["/usr/bin/security", "find-generic-password"],
+ ["C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "-NoProfile"],
+ ["/usr/bin/secret-tool", "lookup"],
+ ["/bin/secret-tool", "lookup"],
+ ]);
+ expect(calls[1]![2]).toBe(Buffer.from("blob").toString("base64"));
+ });
+});
+
+describe("reading Chromium's table", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("asks for the key only when a row of the site is encrypted", async () => {
+ const folder = home();
+ const file = join(folder, "Cookies");
+ chromiumDatabase(file, [{ host: ".example.com", name: "plain", value: "v", expires: LATER }, { host: ".other.test", name: "x", encrypted: MAC_VALUE }]).close();
+ const key = vi.fn(async () => ({ type: "cbc" as const, v10: deriveCbcKey(MAC_PASSWORD, 1003), v11: null }));
+ const read = await readChromium(file, join(folder, "scratch"), "example.com", key);
+ expect(read.cookies.map((cookie) => cookie.name)).toEqual(["plain"]);
+ expect(key).not.toHaveBeenCalled();
+ });
+});
+
diff --git a/server/browser/cookies/import-flow.test.ts b/server/browser/cookies/import-flow.test.ts
new file mode 100644
index 0000000000..a4893dad39
--- /dev/null
+++ b/server/browser/cookies/import-flow.test.ts
@@ -0,0 +1,110 @@
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { PANE_PARTITION } from "../../../electron/browser-pane-wire.mjs";
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { PaneBackend } from "../pane/backend.ts";
+import { PaneLink } from "../pane/link.ts";
+import { FakeMain } from "../pane/testing/fake-main.ts";
+import { cookieRequests } from "./requests.ts";
+import { CdpBrowser } from "../cdp/browser.ts";
+import { FakeChrome } from "../testing/fake-chrome.ts";
+import { cdpCookie, cdpSink } from "./sinks.ts";
+import { chromiumDatabase, fakeKeys, fixtureFiles, localState } from "./testing/fixtures.ts";
+
+const folders: string[] = [];
+afterAll(async () => { for (const folder of folders) await removeTempDir(folder); });
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+const LATER = Math.floor(Date.now() / 1000) + 86_400 * 30;
+
+function setup() {
+ const folder = mkdtempSync(join(tmpdir(), "omb-cookie-flow-"));
+ folders.push(folder);
+ const root = join(folder, ".config", "google-chrome");
+ localState(root, { Default: "Person" });
+ chromiumDatabase(join(root, "Default", "Cookies"), [
+ { host: ".github.com", name: "user_session", value: "fixture-session-value", expires: LATER, secure: true, httpOnly: true, sameSite: 1 },
+ { host: ".gitlab.com", name: "other", value: "not-this-site", expires: LATER },
+ ]).close();
+ const main = new FakeMain();
+ const link = new PaneLink(main);
+ const dataDir = join(folder, "data");
+ const backend = new PaneBackend(link, dataDir, async () => 41_000);
+ link.answerCookieRequests(cookieRequests({
+ files: () => fixtureFiles(folder, "linux"),
+ keys: () => fakeKeys({}),
+ scratch: join(dataDir, "browser", "cookie-import"),
+ destination: (botId) => (botId === "a" ? backend.cookieSink("bot:a") : null),
+ }));
+ return { main, link, backend };
+}
+
+describe("a sign-in import the person starts in the app", () => {
+ it("lists browsers, reads the chosen site only, and writes it into the bot's pane partition through the app", async () => {
+ const { main, backend } = setup();
+ await sleep(5);
+ main.post({ op: "cookie-sources", req: 1 });
+ await sleep(20);
+ expect(main.answers.at(-1)).toMatchObject({ op: "cookie-sources-result", sources: [{ id: "chrome", name: "Google Chrome", engine: "chromium", profiles: [{ id: "Default", name: "Person" }] }] });
+ expect(backend.used("bot:a")).toBe(false);
+ main.post({ op: "cookie-import", req: 2, botId: "a", threadId: null, site: "https://github.com/login", source: "chrome", profile: "Default" });
+ await sleep(50);
+ expect(main.answers.at(-1)).toEqual({ type: "openmausbot:browser-pane", op: "cookie-import-result", req: 2, result: { ok: true, site: "github.com", imported: 1, sessionOnly: 0, skipped: {} } });
+ expect(main.cookiesSet).toHaveLength(1);
+ expect(main.cookiesSet[0]!.partition).toMatch(PANE_PARTITION);
+ expect(main.cookiesSet[0]!.cookies).toEqual([{ url: "https://github.com/", name: "user_session", value: "fixture-session-value", domain: ".github.com", path: "/", secure: true, httpOnly: true, sameSite: "lax", expirationDate: LATER }]);
+ // Deleting the bot now erases the partition it was imported into, though its pane never opened.
+ expect(backend.used("bot:a")).toBe(true);
+ });
+
+ it("offers import only where it can go, never for Google, and answers a bot whose browser takes none", async () => {
+ const { main } = setup();
+ await sleep(5);
+ main.post({ op: "cookie-offer", req: 1, botId: "a", threadId: null, site: "github.com" });
+ main.post({ op: "cookie-offer", req: 2, botId: "a", threadId: null, site: "accounts.google.com" });
+ main.post({ op: "cookie-offer", req: 3, botId: "b", threadId: null, site: "github.com" });
+ main.post({ op: "cookie-offer", req: 4, botId: "a", threadId: null, site: "github.io" });
+ main.post({ op: "cookie-import", req: 5, botId: "b", threadId: null, site: "github.com", source: "chrome", profile: "Default" });
+ await sleep(20);
+ const byReq = Object.fromEntries(main.answers.map((answer) => [answer.req, answer]));
+ expect(byReq[1]).toMatchObject({ offered: true });
+ expect(byReq[2]).toMatchObject({ offered: false, reason: "google" });
+ expect(byReq[3]).toMatchObject({ offered: false, reason: "no-destination" });
+ expect(byReq[4]).toMatchObject({ offered: false, reason: "not-a-site" });
+ expect(byReq[5]).toMatchObject({ result: { ok: false, reason: "no-destination" } });
+ expect(main.cookiesSet).toEqual([]);
+ });
+});
+
+describe("writing into a launched Chrome", () => {
+ it("sends CDP cookie params, retries a refused batch one by one, and counts what Chrome refused", async () => {
+ const sent: Array<Record<string, unknown>> = [];
+ const sink = cdpSink(async (_method, params) => {
+ const cookies = params.cookies as Array<Record<string, unknown>>;
+ sent.push(params);
+ if (cookies.some((cookie) => cookie.name === "bad")) throw new Error("Invalid cookie fields");
+ });
+ const base = { path: "/", secure: true, httpOnly: false, sameSite: "lax" as const };
+ const result = await sink.write([
+ { ...base, url: "https://a.test/", name: "good", value: "1", domain: ".a.test", expirationDate: LATER },
+ { ...base, url: "https://a.test/", name: "bad", value: "2" },
+ ]);
+ expect(result).toEqual({ written: 1, refused: 1 });
+ expect(sent).toHaveLength(3);
+ expect(cdpCookie({ ...base, url: "https://a.test/x", name: "h", value: "v", sameSite: "unspecified" })).toEqual({ name: "h", value: "v", url: "https://a.test/x", path: "/", secure: true, httpOnly: false });
+ expect(cdpCookie({ ...base, url: "https://a.test/", name: "d", value: "v", domain: ".a.test", sameSite: "no_restriction", expirationDate: 5 })).toEqual({ name: "d", value: "v", domain: ".a.test", path: "/", secure: true, httpOnly: false, sameSite: "None", expires: 5 });
+ });
+});
+
+describe("the launched Chrome's driver", () => {
+ it("lets a browser-level Storage.setCookies through its method guard", async () => {
+ const chrome = new FakeChrome();
+ const browser = await CdpBrowser.connect(chrome, { headless: true, downloadDir: null, permissions: false, viewport: null });
+ const sink = cdpSink((method, params) => browser.connection.root.send(method, params));
+ expect(await sink.write([{ url: "https://a.test/", name: "n", value: "v", domain: ".a.test", path: "/", secure: true, httpOnly: true, sameSite: "lax", expirationDate: LATER }])).toEqual({ written: 1, refused: 0 });
+ expect(chrome.sent.filter((sent) => sent.method === "Storage.setCookies").map((sent) => sent.sessionId)).toEqual([null]);
+ browser.disconnect();
+ });
+});
diff --git a/server/browser/cookies/importer.ts b/server/browser/cookies/importer.ts
new file mode 100644
index 0000000000..7702e5d2e5
--- /dev/null
+++ b/server/browser/cookies/importer.ts
@@ -0,0 +1,118 @@
+// One import: a site's cookies from a profile of another browser, into a bot's browser. Started only by the person,
+// one site at a time. Security: the result, every log line and every error carry counts and reason codes only, never a
+// cookie, a value or a key.
+import { googleCookie, importSite as siteOf, writable, type SkipReason, type WritableCookie } from "./policy.ts";
+import { readChromium, readFirefox, readSafari, type SiteRead } from "./readers.ts";
+import { chromiumKey, KeyUnavailable, locate, type BrowserFiles, type KeyStore } from "./sources.ts";
+
+/** Why nothing was imported, as a code the app words for the person. */
+export type ImportRefusal =
+ /** Not a site: an address with no registrable domain, a public suffix or a shared hosting suffix. */
+ | "not-a-site"
+ /** Google ties its sign-in to the browser it was made in; it is never copied. */
+ | "google"
+ /** That browser or profile is not here (any more). */
+ | "no-source"
+ /** The person turned down the system's request for the browser's key (macOS Keychain). */
+ | "key-denied"
+ /** Safari's cookies need Full Disk Access for this app (System Settings → Privacy & Security). */
+ | "full-disk-access"
+ /** Chrome's app-bound encryption on Windows: only that browser can read them; My Chrome is the way. */
+ | "app-bound"
+ /** The browser holds its file without sharing while it runs (Windows); quit it and try again. */
+ | "locked"
+ /** The browser's files could not be read. */
+ | "unreadable"
+ /** No sign-in for that site in that profile. */
+ | "nothing-found"
+ /** This bot's browser takes no imported sign-in (temporary, or the person's own Chrome). */
+ | "no-destination";
+
+export type ImportResult =
+ | { ok: true; site: string; imported: number; sessionOnly: number; skipped: Partial<Record<SkipReason | "protected" | "failed" | "refused", number>> }
+ | { ok: false; reason: ImportRefusal };
+
+/** Where the cookies go: the pane's partition through the app, or a launched Chrome through CDP. */
+export interface CookieSink {
+ write(cookies: WritableCookie[]): Promise<{ written: number; refused: number }>;
+}
+
+export interface ImportRequest {
+ files: BrowserFiles;
+ keys: KeyStore;
+ /** A 0700 folder of the app's own for the copies of the other browser's database. */
+ scratch: string;
+ source: string;
+ profile: string;
+ site: string;
+ sink: CookieSink;
+ now?: number;
+ log?: (line: string) => void;
+}
+
+/** The key store answered no key: the person turned its prompt down, or it holds none. */
+class KeyDenied extends Error {}
+
+let running: Promise<unknown> = Promise.resolve();
+
+/** One import at a time: copies of another browser's database never sit side by side. */
+export function importCookies(request: ImportRequest): Promise<ImportResult> {
+ const next = running.then(() => run(request), () => run(request));
+ running = next.catch(() => undefined);
+ return next;
+}
+
+async function run(request: ImportRequest): Promise<ImportResult> {
+ const refused = (reason: ImportRefusal): ImportResult => {
+ request.log?.(`cookie import: ${request.source} refused: ${reason}`);
+ return { ok: false, reason };
+ };
+ const site = siteOf(request.site);
+ if (!site) return refused("not-a-site");
+ if (googleCookie(site, "")) return refused("google");
+ const located = await locate(request.files, request.source, request.profile);
+ if (!located) return refused("no-source");
+ let read: SiteRead | null;
+ try {
+ if (located.source.engine === "safari") read = await readSafari(located.profile.cookies, site);
+ else if (located.source.engine === "firefox") read = await readFirefox(located.profile.directory, request.scratch, site);
+ else read = await readChromium(located.profile.cookies, request.scratch, site, () => chromiumKey(request.files, located, request.keys).catch((error: unknown) => {
+ throw error instanceof KeyUnavailable ? error : new KeyDenied();
+ }));
+ } catch (error) {
+ return refused(failure(error, located.source.engine));
+ }
+ if (!read) return refused("unreadable");
+ const now = request.now ?? Date.now() / 1000;
+ const skipped: Partial<Record<SkipReason | "protected" | "failed" | "refused", number>> = {};
+ const count = (reason: SkipReason | "protected" | "failed" | "refused", by = 1) => { if (by) skipped[reason] = (skipped[reason] ?? 0) + by; };
+ count("protected", read.protected);
+ count("failed", read.failed);
+ const cookies: WritableCookie[] = [];
+ for (const cookie of read.cookies) {
+ const mapped = writable(cookie, now);
+ if ("skip" in mapped) count(mapped.skip);
+ else cookies.push(mapped);
+ }
+ if (!cookies.length && read.cookies.length === 0) {
+ if (read.protected > 0) return refused("app-bound");
+ // Values that would not decrypt: a wrong or changed key, not a site without a sign-in.
+ if (read.failed > 0) return refused("unreadable");
+ }
+ if (!cookies.length) return refused("nothing-found");
+ const written = await request.sink.write(cookies);
+ count("refused", written.refused);
+ const sessionOnly = cookies.filter((cookie) => cookie.expirationDate === undefined).length;
+ request.log?.(`cookie import: ${request.source} wrote ${written.written} of ${cookies.length}`);
+ return { ok: true, site, imported: written.written, sessionOnly, skipped };
+}
+
+function failure(error: unknown, engine: string): ImportRefusal {
+ if (error instanceof KeyUnavailable) return "unreadable";
+ if (error instanceof KeyDenied) return "key-denied";
+ const code = (error as NodeJS.ErrnoException | null)?.code;
+ if (code === "EBUSY") return "locked";
+ if (code === "EPERM" || code === "EACCES") return engine === "safari" ? "full-disk-access" : "unreadable";
+ if (code === "ENOENT") return "no-source";
+ return "unreadable";
+}
diff --git a/server/browser/cookies/policy.ts b/server/browser/cookies/policy.ts
new file mode 100644
index 0000000000..390cefff56
--- /dev/null
+++ b/server/browser/cookies/policy.ts
@@ -0,0 +1,110 @@
+// What may move from another browser into a bot's browser, and in what shape. Security: a cookie value never appears in
+// a message, a log line or an error made here; only counts and reason codes leave this module.
+//
+// The cookie shape and the host-only and expiry rules follow anomalyco/opencode@5ca87b9
+// packages/gui-plugins/src/browser/profile/cookie.ts (ImportedCookie, cookieDetails, cookieURL), MIT License,
+// Copyright (c) 2025 opencode (full text in third_party/opencode/LICENSE). The Google exclusion follows
+// stablyai/orca@ffadf731 src/main/browser/cookies/policy/cookie-import-exclusions.ts, MIT License, Copyright (c) 2026
+// Lovecast Inc. (full text in third_party/orca/LICENSE). Modified: one site per import, and skip reasons counted.
+import { getDomain } from "tldts";
+
+/** A cookie as another browser stores it, before it is written anywhere. */
+export interface SourceCookie {
+ /** `.github.com` for a domain cookie, `github.com` for a host-only one. */
+ host: string;
+ name: string;
+ value: string;
+ path: string;
+ secure: boolean;
+ httpOnly: boolean;
+ /** Unix seconds; undefined for a session cookie. */
+ expires: number | undefined;
+ sameSite: "unspecified" | "no_restriction" | "lax" | "strict";
+ /** Set when the cookie lives in a partition (CHIPS), which no destination here can write. */
+ partitioned?: boolean;
+}
+
+/** The shape every destination takes: Electron's `cookies.set` details, which CDP's `Storage.setCookies` maps from. */
+export interface WritableCookie {
+ url: string;
+ name: string;
+ value: string;
+ /** Absent for a host-only cookie. */
+ domain?: string;
+ path: string;
+ secure: boolean;
+ httpOnly: boolean;
+ sameSite: SourceCookie["sameSite"];
+ /** Absent for a session cookie, which lasts until the bot's browser quits. */
+ expirationDate?: number;
+}
+
+export type SkipReason = "expired" | "partitioned" | "insecure-none" | "host-prefix" | "secure-prefix" | "empty" | "google";
+
+/**
+ * Google ties these cookies to the browser that made them; a copy is flagged, and the account is signed out within the
+ * hour. Google's own sign-in is done in the bot's browser itself or in My Chrome.
+ */
+const GOOGLE_SOURCE_BOUND = new Set(["SIDCC", "__Secure-1PSIDCC", "__Secure-3PSIDCC", "__Secure-STRP", "AEC"]);
+const NOT_TRANSPLANTABLE = ["google.com"];
+
+const bare = (host: string) => host.replace(/^\./, "").toLowerCase();
+
+/** Whether a cookie of this host and name is Google's, which is never imported. */
+export function googleCookie(host: string, name: string): boolean {
+ const domain = bare(host);
+ if (NOT_TRANSPLANTABLE.some((root) => domain === root || domain.endsWith(`.${root}`))) return true;
+ return GOOGLE_SOURCE_BOUND.has(name) && domain.endsWith(".google.com");
+}
+
+/**
+ * The site a person asked for, as its registrable domain ("app.github.com" → "github.com"), or null for something that
+ * is not one: an address, a public suffix, a hosting platform's shared suffix such as github.io, or an IP literal.
+ */
+export function importSite(input: string): string | null {
+ let host = input.trim().toLowerCase();
+ if (/^[a-z][a-z0-9+.-]*:\/\//u.test(host)) {
+ try { host = new URL(host).hostname; } catch { return null; }
+ }
+ host = host.replace(/\.$/u, "");
+ if (!/^[a-z0-9.-]{1,253}$/u.test(host) || !host.includes(".")) return null;
+ const domain = getDomain(host, { allowPrivateDomains: true });
+ return domain && domain === getDomain(domain, { allowPrivateDomains: true }) ? domain : null;
+}
+
+/** Whether a cookie of `host` belongs to `site` (a registrable domain). */
+export function inSite(host: string, site: string): boolean {
+ const domain = bare(host);
+ return domain === site || domain.endsWith(`.${site}`);
+}
+
+/** The address a cookie is sent to, which Electron's `cookies.set` and CDP's `Storage.setCookies` derive it from. */
+function cookieUrl(cookie: SourceCookie): string {
+ const host = bare(cookie.host);
+ const bracketed = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
+ return `${cookie.secure ? "https" : "http"}://${bracketed}${cookie.path.startsWith("/") ? cookie.path : "/"}`;
+}
+
+/** One source cookie as a destination writes it, or why it is left behind. */
+export function writable(cookie: SourceCookie, now = Date.now() / 1000): WritableCookie | { skip: SkipReason } {
+ if (googleCookie(cookie.host, cookie.name)) return { skip: "google" };
+ if (!bare(cookie.host) || (!cookie.name && !cookie.value)) return { skip: "empty" };
+ if (cookie.partitioned) return { skip: "partitioned" };
+ if (cookie.expires !== undefined && cookie.expires <= now) return { skip: "expired" };
+ // Chromium refuses these itself; counting them here says why the number is lower.
+ if (cookie.sameSite === "no_restriction" && !cookie.secure) return { skip: "insecure-none" };
+ if (cookie.name.startsWith("__Secure-") && !cookie.secure) return { skip: "secure-prefix" };
+ if (cookie.name.startsWith("__Host-") && (!cookie.secure || cookie.path !== "/" || cookie.host.startsWith("."))) return { skip: "host-prefix" };
+ const domain = cookie.host.startsWith(".") ? cookie.host : undefined;
+ return {
+ url: cookieUrl(cookie),
+ name: cookie.name,
+ value: cookie.value,
+ ...(domain ? { domain } : {}),
+ path: cookie.path.startsWith("/") ? cookie.path : "/",
+ secure: cookie.secure,
+ httpOnly: cookie.httpOnly,
+ sameSite: cookie.sameSite,
+ ...(cookie.expires !== undefined ? { expirationDate: cookie.expires } : {}),
+ };
+}
diff --git a/server/browser/cookies/readers.ts b/server/browser/cookies/readers.ts
new file mode 100644
index 0000000000..5d2ef38d15
--- /dev/null
+++ b/server/browser/cookies/readers.ts
@@ -0,0 +1,249 @@
+// Reading one site's cookies from another browser's files: Chromium's encrypted SQLite, Firefox's plain SQLite and
+// Safari's binarycookies.
+//
+// Adapted from anomalyco/opencode@5ca87b9 packages/gui-plugins/src/browser/profile/chromium.ts (deriveCbcKey,
+// decryptChromium, readChromiumCookies), firefox.ts (readFirefoxCookies, the expiry and SameSite mapping) and safari.ts
+// (parseBinaryCookies), MIT License, Copyright (c) 2025 opencode (full text in third_party/opencode/LICENSE). Modified:
+// only the chosen site's rows are read at all.
+import { createDecipheriv, createHash, pbkdf2Sync } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import type { DatabaseSync } from "node:sqlite";
+
+import { inSite, type SourceCookie } from "./policy.ts";
+import { readCopy } from "./snapshot.ts";
+
+/**
+ * The key a Chromium profile encrypts cookie values with. `gcm`: Windows, AES-256-GCM, unwrapped from `Local State`
+ * with DPAPI. `cbc`: macOS and Linux, AES-128-CBC keys derived from the Safe Storage password; `v11` only where a Linux
+ * keyring holds one.
+ */
+export type ChromiumKey =
+ | { type: "gcm"; key: Buffer }
+ | { type: "cbc"; v10: Buffer; v11: Buffer | null };
+
+export interface SiteRead {
+ cookies: SourceCookie[];
+ /** Values only the source browser can decrypt (Chrome's app-bound encryption on Windows). */
+ protected: number;
+ /** Values that would not decrypt or parse. */
+ failed: number;
+}
+
+/** Chromium's AES-128 key from a Safe Storage password: 1003 PBKDF2 rounds on macOS, 1 on Linux. */
+export function deriveCbcKey(password: string, iterations: number): Buffer {
+ return pbkdf2Sync(password, "saltysalt", iterations, 16, "sha1");
+}
+
+/**
+ * One `encrypted_value`. Since cookie database version 24 the plain text starts with the SHA-256 of the cookie's host,
+ * which is stripped. `v20` is Chrome's app-bound encryption on Windows: only the browser's own elevation service can
+ * unwrap it, and it is not attempted.
+ */
+export function decryptChromium(encrypted: Uint8Array, key: ChromiumKey, host: string): { value: string } | { error: "protected" | "failed" } {
+ const buffer = Buffer.from(encrypted);
+ const version = buffer.subarray(0, 3).toString("latin1");
+ if (version === "v20") return { error: "protected" };
+ if ((version !== "v10" && version !== "v11") || (key.type === "gcm" && buffer.length < 3 + 12 + 16)) return { error: "failed" };
+ let plain: Buffer;
+ try {
+ if (key.type === "gcm") {
+ const gcm = createDecipheriv("aes-256-gcm", key.key, buffer.subarray(3, 15));
+ gcm.setAuthTag(buffer.subarray(-16));
+ plain = Buffer.concat([gcm.update(buffer.subarray(15, -16)), gcm.final()]);
+ } else {
+ const secret = version === "v11" ? key.v11 : key.v10;
+ if (!secret) return { error: "failed" };
+ const cbc = createDecipheriv("aes-128-cbc", secret, Buffer.alloc(16, 0x20));
+ plain = Buffer.concat([cbc.update(buffer.subarray(3)), cbc.final()]);
+ }
+ } catch {
+ return { error: "failed" };
+ }
+ const digest = createHash("sha256").update(host).digest();
+ const text = plain.length >= 32 && plain.subarray(0, 32).equals(digest) ? plain.subarray(32) : plain;
+ try {
+ return { value: new TextDecoder("utf-8", { fatal: true }).decode(text) };
+ } catch {
+ return { error: "failed" };
+ }
+}
+
+/** Seconds between 1601-01-01 (Chromium's epoch) and 1970-01-01. */
+const WINDOWS_EPOCH = 11_644_473_600;
+const chromiumTime = (value: number | bigint) => (Number(value) ? Number(value) / 1_000_000 - WINDOWS_EPOCH : undefined);
+const CHROMIUM_SAME_SITE = ["no_restriction", "lax", "strict"] as const;
+
+/** Rows of `site` and its subdomains, matched in SQL so no other site's value is ever read. */
+const SITE_ROWS = (column: string) => `(${column} = ?1 OR ${column} = ?2 OR (length(${column}) > length(?2) AND substr(${column}, -length(?2)) = ?2))`;
+
+interface ChromiumRow {
+ host_key: string;
+ name: string;
+ value: string;
+ encrypted_value: Uint8Array;
+ path: string;
+ expires_utc: bigint;
+ has_expires: bigint;
+ is_secure: bigint;
+ is_httponly: bigint;
+ samesite: bigint;
+ top_frame_site_key: string | null;
+}
+
+/** A Chromium profile's cookies of one site, decrypted with `key` (asked for only when a row needs it). */
+export async function readChromium(database: string, scratch: string, site: string, key: () => Promise<ChromiumKey>): Promise<SiteRead> {
+ const rows = await readCopy(database, scratch, (db: DatabaseSync) => {
+ const columns = new Set((db.prepare("SELECT name FROM pragma_table_info('cookies')").all() as Array<{ name: string }>).map((row) => row.name));
+ const partition = columns.has("top_frame_site_key") ? "top_frame_site_key" : "NULL AS top_frame_site_key";
+ const query = db.prepare(`SELECT host_key, name, value, encrypted_value, path, expires_utc, has_expires, is_secure, is_httponly, samesite, ${partition} FROM cookies WHERE typeof(host_key) = 'text' AND ${SITE_ROWS("host_key")}`);
+ query.setReadBigInts(true);
+ return query.all(site, `.${site}`) as unknown as ChromiumRow[];
+ });
+ const read: SiteRead = { cookies: [], protected: 0, failed: 0 };
+ let secret: ChromiumKey | null = null;
+ for (const row of rows) {
+ if (typeof row.name !== "string" || typeof row.path !== "string" || !inSite(row.host_key, site)) {
+ read.failed++;
+ continue;
+ }
+ let value = typeof row.value === "string" ? row.value : "";
+ if (!value && row.encrypted_value && row.encrypted_value.length) {
+ secret ??= await key();
+ const decrypted = decryptChromium(row.encrypted_value, secret, row.host_key);
+ if ("error" in decrypted) {
+ read[decrypted.error]++;
+ continue;
+ }
+ value = decrypted.value;
+ }
+ read.cookies.push({
+ host: row.host_key,
+ name: row.name,
+ value,
+ path: row.path,
+ secure: Boolean(Number(row.is_secure)),
+ httpOnly: Boolean(Number(row.is_httponly)),
+ expires: Number(row.has_expires) ? chromiumTime(row.expires_utc) : undefined,
+ sameSite: CHROMIUM_SAME_SITE[Number(row.samesite)] ?? "unspecified",
+ ...(row.top_frame_site_key ? { partitioned: true } : {}),
+ });
+ }
+ return read;
+}
+
+interface FirefoxRow {
+ host: string;
+ name: string;
+ value: string;
+ path: string;
+ expiry: number | bigint;
+ isSecure: number | bigint;
+ isHttpOnly: number | bigint;
+ sameSite: number | bigint;
+}
+
+// Firefox 139 stores the expiry in milliseconds; earlier versions in seconds.
+const firefoxExpiry = (value: number | bigint) => {
+ const number = Number(value);
+ return number > 0 ? (number > 1e11 ? number / 1000 : number) : undefined;
+};
+
+/**
+ * A Firefox profile's cookies of one site, from `cookies.sqlite`. Values are plain text. Cookies of containers and
+ * private windows (any `originAttributes`) stay behind: the default container is the one the person browses in.
+ */
+export async function readFirefox(profileDir: string, scratch: string, site: string): Promise<SiteRead> {
+ const rows = await readCopy(join(profileDir, "cookies.sqlite"), scratch, (db: DatabaseSync) =>
+ db.prepare(`SELECT host, name, value, path, expiry, isSecure, isHttpOnly, sameSite FROM moz_cookies WHERE originAttributes = '' AND typeof(host) = 'text' AND ${SITE_ROWS("host")}`)
+ .all(site, `.${site}`) as unknown as FirefoxRow[]);
+ return {
+ cookies: rows.filter((row) => inSite(row.host, site)).map((row) => {
+ const secure = Boolean(Number(row.isSecure));
+ const sameSite = Number(row.sameSite);
+ return {
+ host: row.host,
+ name: String(row.name),
+ value: String(row.value),
+ path: String(row.path),
+ secure,
+ httpOnly: Boolean(Number(row.isHttpOnly)),
+ expires: firefoxExpiry(row.expiry),
+ // 0 is both an explicit SameSite=None and an unset attribute; only a secure cookie can be sent as None.
+ sameSite: sameSite === 1 ? "lax" : sameSite === 2 ? "strict" : secure ? "no_restriction" : "unspecified",
+ };
+ }),
+ protected: 0,
+ failed: 0,
+ };
+}
+
+/** Seconds between 1970-01-01 and 2001-01-01, the epoch of Safari's timestamps. */
+const MAC_EPOCH = 978_307_200;
+
+/**
+ * Safari's `Cookies.binarycookies`: big-endian page sizes, then pages of little-endian records with null-terminated
+ * strings. Every count and offset is checked against the bytes there are, so a damaged file costs no more than its
+ * size. Flags: 1 secure, 4 HttpOnly; the file's SameSite bits are not documented, so it stays unspecified.
+ */
+export function parseBinaryCookies(data: Uint8Array, site: string): SiteRead | null {
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
+ if (data.byteLength < 8 || Buffer.from(data.subarray(0, 4)).toString("latin1") !== "cook") return null;
+ const pages = view.getUint32(4);
+ if (8 + pages * 4 > data.byteLength) return null;
+ const read: SiteRead = { cookies: [], protected: 0, failed: 0 };
+ let start = 8 + pages * 4;
+ for (let index = 0; index < pages; index++) {
+ const size = view.getUint32(8 + index * 4);
+ const length = Math.min(size, Math.max(0, data.byteLength - start));
+ const page = length >= 8 ? new DataView(data.buffer, data.byteOffset + start, length) : null;
+ start += size;
+ const records = page ? page.getUint32(4, true) : 0;
+ if (!page || 8 + records * 4 > page.byteLength) {
+ read.failed++;
+ continue;
+ }
+ for (let item = 0; item < records; item++) {
+ const cookie = safariCookie(page, page.getUint32(8 + item * 4, true));
+ if (!cookie) read.failed++;
+ else if (inSite(cookie.host, site)) read.cookies.push(cookie);
+ }
+ }
+ return read;
+}
+
+function safariCookie(page: DataView, offset: number): SourceCookie | null {
+ if (offset + 56 > page.byteLength) return null;
+ const size = page.getUint32(offset, true);
+ if (offset + size > page.byteLength) return null;
+ const flags = page.getUint32(offset + 8, true);
+ const text = (field: number) => cString(page, offset + page.getUint32(offset + field, true), offset + size);
+ const host = text(16);
+ const name = text(20);
+ const path = text(24);
+ const value = text(28);
+ if (host === null || name === null || path === null || value === null) return null;
+ const expiry = page.getFloat64(offset + 40, true);
+ return {
+ host,
+ name,
+ value,
+ path,
+ secure: (flags & 1) !== 0,
+ httpOnly: (flags & 4) !== 0,
+ expires: expiry > 0 ? expiry + MAC_EPOCH : undefined,
+ sameSite: "unspecified",
+ };
+}
+
+function cString(page: DataView, start: number, end: number): string | null {
+ const bytes = new Uint8Array(page.buffer, page.byteOffset, page.byteLength);
+ const stop = bytes.indexOf(0, start);
+ if (start >= end || stop < 0 || stop > end) return null;
+ return new TextDecoder().decode(bytes.subarray(start, stop));
+}
+
+/** Safari's cookie file of one site. Without Full Disk Access macOS answers EPERM: the caller says so. */
+export async function readSafari(file: string, site: string): Promise<SiteRead | null> {
+ return parseBinaryCookies(await readFile(file), site);
+}
diff --git a/server/browser/cookies/requests.ts b/server/browser/cookies/requests.ts
new file mode 100644
index 0000000000..50d5f67469
--- /dev/null
+++ b/server/browser/cookies/requests.ts
@@ -0,0 +1,37 @@
+// The person's sign-in imports, as the app's own window asks for them: which browsers, whether a site can be imported
+// for a bot, and the import itself. They arrive only through the desktop app's main process, never over HTTP, so a
+// bot's shell cannot start one; the main process takes them from the app window's top page only.
+import type { CookieImportResult, CookieSource } from "../../../electron/browser-pane-wire.mjs";
+import type { CookieRequests } from "../pane/link.ts";
+import { importCookies, type CookieSink } from "./importer.ts";
+import { googleCookie, importSite } from "./policy.ts";
+import { listSources, type BrowserFiles, type KeyStore } from "./sources.ts";
+
+export interface CookieRequestDeps {
+ files(): BrowserFiles;
+ keys(): KeyStore;
+ /** A 0700 folder of the app's own for copies of another browser's database. */
+ scratch: string;
+ /** Where a bot's browser takes an import, or null where it takes none (temporary, My Chrome, or not this engine's). */
+ destination(botId: string, threadId: string | null): CookieSink | null;
+ log?(line: string): void;
+}
+
+export function cookieRequests(deps: CookieRequestDeps): CookieRequests {
+ return {
+ async sources(): Promise<CookieSource[]> {
+ return listSources(deps.files());
+ },
+ async offer({ botId, threadId, site }) {
+ const domain = importSite(site);
+ if (!domain) return { offered: false, reason: "not-a-site" };
+ if (googleCookie(domain, "")) return { offered: false, reason: "google" };
+ return deps.destination(botId, threadId) ? { offered: true } : { offered: false, reason: "no-destination" };
+ },
+ async import({ botId, threadId, site, source, profile }): Promise<CookieImportResult> {
+ const sink = deps.destination(botId, threadId);
+ if (!sink) return { ok: false, reason: "no-destination" };
+ return importCookies({ files: deps.files(), keys: deps.keys(), scratch: deps.scratch, source, profile, site, sink, ...(deps.log ? { log: deps.log } : {}) });
+ },
+ };
+}
diff --git a/server/browser/cookies/sinks.ts b/server/browser/cookies/sinks.ts
new file mode 100644
index 0000000000..77fe7e8d51
--- /dev/null
+++ b/server/browser/cookies/sinks.ts
@@ -0,0 +1,65 @@
+// Where an imported sign-in is written: a desktop pane's partition (through the app's main process), or a launched
+// Chrome profile (through CDP). Security: a refusal is counted, never described: Chromium's message can quote a value.
+import type { CookieSink } from "./importer.ts";
+import type { WritableCookie } from "./policy.ts";
+
+const BATCH = 500;
+
+/** A pane's partition: `write` is the app's own `cookies.set`, which counts what it refused. */
+export function paneSink(write: (cookies: WritableCookie[]) => Promise<{ written: number; refused: number }>): CookieSink {
+ return {
+ async write(cookies) {
+ let written = 0;
+ let refused = 0;
+ for (let at = 0; at < cookies.length; at += BATCH) {
+ const done = await write(cookies.slice(at, at + BATCH));
+ written += done.written;
+ refused += done.refused;
+ }
+ return { written, refused };
+ },
+ };
+}
+
+const CDP_SAME_SITE = { lax: "Lax", strict: "Strict", no_restriction: "None" } as const;
+
+/** CDP's Network.CookieParam: a host-only cookie by its URL, a domain cookie by its domain. */
+export function cdpCookie(cookie: WritableCookie): Record<string, unknown> {
+ return {
+ name: cookie.name,
+ value: cookie.value,
+ ...(cookie.domain ? { domain: cookie.domain } : { url: cookie.url }),
+ path: cookie.path,
+ secure: cookie.secure,
+ httpOnly: cookie.httpOnly,
+ ...(cookie.sameSite !== "unspecified" ? { sameSite: CDP_SAME_SITE[cookie.sameSite] } : {}),
+ ...(cookie.expirationDate !== undefined ? { expires: cookie.expirationDate } : {}),
+ };
+}
+
+/** A launched Chrome, through its browser-level `Storage.setCookies`; a batch it refuses is retried cookie by cookie. */
+export function cdpSink(send: (method: string, params: Record<string, unknown>) => Promise<unknown>): CookieSink {
+ return {
+ async write(cookies) {
+ let written = 0;
+ let refused = 0;
+ for (let at = 0; at < cookies.length; at += BATCH) {
+ const batch = cookies.slice(at, at + BATCH);
+ try {
+ await send("Storage.setCookies", { cookies: batch.map(cdpCookie) });
+ written += batch.length;
+ continue;
+ } catch {}
+ for (const cookie of batch) {
+ try {
+ await send("Storage.setCookies", { cookies: [cdpCookie(cookie)] });
+ written++;
+ } catch {
+ refused++;
+ }
+ }
+ }
+ return { written, refused };
+ },
+ };
+}
diff --git a/server/browser/cookies/snapshot.ts b/server/browser/cookies/snapshot.ts
new file mode 100644
index 0000000000..3b54be16e0
--- /dev/null
+++ b/server/browser/cookies/snapshot.ts
@@ -0,0 +1,44 @@
+// Another browser's SQLite database, read from a private copy.
+//
+// Adapted from anomalyco/opencode@5ca87b9 packages/gui-plugins/src/browser/profile/database.ts (snapshotDatabase,
+// sweepSnapshots), MIT License, Copyright (c) 2025 opencode (full text in third_party/opencode/LICENSE). Modified: one
+// scratch folder of the app's own, swept of every leftover before each copy.
+import { randomUUID } from "node:crypto";
+import { copyFile, mkdir, readdir, rm } from "node:fs/promises";
+import { basename, join } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+
+const PREFIX = "copy-";
+
+/**
+ * A copy, with its write-ahead log, so the running browser keeps its lock and its file is never written. Chromium on
+ * Windows holds the database open without sharing while it runs (EBUSY), and SQLite reads a live write-ahead log only
+ * through its shared-memory file, which it would write. Security: the copy holds every value, so it lives in a 0700
+ * folder of the app's own and is deleted before this returns; copies a crash left behind go before the next one.
+ */
+export async function readCopy<T>(file: string, scratch: string, read: (db: DatabaseSync) => T): Promise<T> {
+ await mkdir(scratch, { recursive: true, mode: 0o700 });
+ await sweep(scratch);
+ const directory = join(scratch, `${PREFIX}${randomUUID()}`);
+ try {
+ await mkdir(directory, { mode: 0o700 });
+ const copy = join(directory, basename(file));
+ await copyFile(file, copy);
+ // A sidecar that does not exist is normal: the browser checkpointed or uses another journal mode.
+ await Promise.all(["-wal", "-shm", "-journal"].map((suffix) => copyFile(`${file}${suffix}`, `${copy}${suffix}`).catch(() => undefined)));
+ const db = new DatabaseSync(copy, { readOnly: false });
+ try {
+ return read(db);
+ } finally {
+ db.close();
+ }
+ } finally {
+ await rm(directory, { recursive: true, force: true, maxRetries: 2, retryDelay: 200 }).catch(() => undefined);
+ }
+}
+
+/** Every copy left in the scratch folder: only one import reads at a time. */
+export async function sweep(scratch: string): Promise<void> {
+ const entries = await readdir(scratch).catch(() => [] as string[]);
+ await Promise.all(entries.filter((entry) => entry.startsWith(PREFIX)).map((entry) => rm(join(scratch, entry), { recursive: true, force: true }).catch(() => undefined)));
+}
diff --git a/server/browser/cookies/sources.ts b/server/browser/cookies/sources.ts
new file mode 100644
index 0000000000..4c2985d98b
--- /dev/null
+++ b/server/browser/cookies/sources.ts
@@ -0,0 +1,292 @@
+// The browsers a person may import a sign-in from, where each keeps its profiles, and the key that opens a Chromium
+// profile's cookies. Nothing here reads a cookie: listing reads only `Local State` and `profiles.ini`.
+//
+// The browser table, the profile discovery and the key lookups follow anomalyco/opencode@5ca87b9
+// packages/gui-plugins/src/browser/profile/sources.ts (definitions, localStateProfiles, chromiumKey, unprotect, run),
+// MIT License, Copyright (c) 2025 opencode (full text in third_party/opencode/LICENSE). Modified: the file system, the
+// platform and the key store are passed in, and the table keeps the browsers this app names.
+import { spawn } from "node:child_process";
+import { access, readFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { posix, win32 } from "node:path";
+
+import { deriveCbcKey, type ChromiumKey } from "./readers.ts";
+
+export type Engine = "chromium" | "firefox" | "safari";
+
+export interface BrowserSource {
+ id: string;
+ name: string;
+ engine: Engine;
+ profiles: Array<{ id: string; name: string }>;
+}
+
+/** What the importer may read of this computer. Tests pass a folder of fixtures; the app passes the real home. */
+export interface BrowserFiles {
+ platform: NodeJS.Platform;
+ home: string;
+ env: Readonly<Record<string, string | undefined>>;
+ readText(path: string): Promise<string | null>;
+ exists(path: string): Promise<boolean>;
+}
+
+/**
+ * The operating system's store of each Chromium browser's cookie key. Every method may show the person a system
+ * prompt, so it is called only after they confirmed an import. Tests pass a fake: a real call raises a Keychain prompt.
+ */
+export interface KeyStore {
+ /** macOS: the browser's Safe Storage password from the login Keychain. Rejects when the person denies it. */
+ macPassword(service: string, account: string): Promise<string>;
+ /** Windows: a DPAPI blob unwrapped for the current user. */
+ windowsUnprotect(blob: Buffer): Promise<Buffer>;
+ /** Linux: the keyring's Safe Storage password for an `application` attribute, or null when it holds none. */
+ linuxPassword(application: string): Promise<string | null>;
+}
+
+interface Definition {
+ id: string;
+ name: string;
+ engine: Engine;
+ root: string;
+ keychain?: { service: string; account: string };
+ keyring?: string[];
+ /** The user data folder is the profile itself, as in Opera. */
+ flat?: boolean;
+}
+
+function definitions(files: BrowserFiles): Definition[] {
+ const { home, env, platform } = files;
+ if (platform === "win32") {
+ const join = win32.join;
+ const local = env.LOCALAPPDATA ?? join(home, "AppData", "Local");
+ const roaming = env.APPDATA ?? join(home, "AppData", "Roaming");
+ return [
+ chromium("chrome", "Google Chrome", join(local, "Google", "Chrome", "User Data")),
+ chromium("edge", "Microsoft Edge", join(local, "Microsoft", "Edge", "User Data")),
+ chromium("brave", "Brave", join(local, "BraveSoftware", "Brave-Browser", "User Data")),
+ chromium("arc", "Arc", join(local, "Packages", "TheBrowserCompany.Arc_ttt1ap7aakyb4", "LocalCache", "Local", "Arc", "User Data")),
+ chromium("vivaldi", "Vivaldi", join(local, "Vivaldi", "User Data")),
+ { ...chromium("opera", "Opera", join(roaming, "Opera Software", "Opera Stable")), flat: true },
+ chromium("chromium", "Chromium", join(local, "Chromium", "User Data")),
+ firefox("firefox", "Firefox", join(roaming, "Mozilla", "Firefox")),
+ ];
+ }
+ const join = posix.join;
+ if (platform === "darwin") {
+ const support = join(home, "Library", "Application Support");
+ const keychain = (account: string) => ({ keychain: { service: `${account} Safe Storage`, account } });
+ return [
+ { ...chromium("chrome", "Google Chrome", join(support, "Google", "Chrome")), ...keychain("Chrome") },
+ { ...chromium("edge", "Microsoft Edge", join(support, "Microsoft Edge")), ...keychain("Microsoft Edge") },
+ { ...chromium("brave", "Brave", join(support, "BraveSoftware", "Brave-Browser")), ...keychain("Brave") },
+ { ...chromium("arc", "Arc", join(support, "Arc", "User Data")), ...keychain("Arc") },
+ { ...chromium("vivaldi", "Vivaldi", join(support, "Vivaldi")), ...keychain("Vivaldi") },
+ { ...chromium("opera", "Opera", join(support, "com.operasoftware.Opera")), ...keychain("Opera"), flat: true },
+ { ...chromium("chromium", "Chromium", join(support, "Chromium")), ...keychain("Chromium") },
+ { id: "safari", name: "Safari", engine: "safari", root: join(home, "Library") },
+ firefox("firefox", "Firefox", join(support, "Firefox")),
+ ];
+ }
+ const config = env.XDG_CONFIG_HOME ?? join(home, ".config");
+ const keyring = (...names: string[]) => ({ keyring: names });
+ return [
+ { ...chromium("chrome", "Google Chrome", join(config, "google-chrome")), ...keyring("chrome") },
+ { ...chromium("edge", "Microsoft Edge", join(config, "microsoft-edge")), ...keyring("chromium") },
+ { ...chromium("brave", "Brave", join(config, "BraveSoftware", "Brave-Browser")), ...keyring("brave") },
+ { ...chromium("vivaldi", "Vivaldi", join(config, "vivaldi")), ...keyring("vivaldi", "chrome") },
+ { ...chromium("opera", "Opera", join(config, "opera")), ...keyring("chromium"), flat: true },
+ { ...chromium("chromium", "Chromium", join(config, "chromium")), ...keyring("chromium") },
+ firefox("firefox", "Firefox", join(home, ".mozilla", "firefox")),
+ firefox("firefox-snap", "Firefox (Snap)", join(home, "snap", "firefox", "common", ".mozilla", "firefox")),
+ ];
+}
+
+const chromium = (id: string, name: string, root: string): Definition => ({ id, name, engine: "chromium", root });
+const firefox = (id: string, name: string, root: string): Definition => ({ id, name, engine: "firefox", root });
+
+const pathOf = (files: BrowserFiles) => (files.platform === "win32" ? win32 : posix);
+
+/** A profile folder named by a file: one plain folder name, nothing that climbs out of the browser's own folder. */
+const PLAIN = /^[^/\\:]{1,128}$/u;
+
+async function localState(files: BrowserFiles, root: string): Promise<{ profile?: { info_cache?: Record<string, { name?: unknown }> }; os_crypt?: { encrypted_key?: unknown } } | null> {
+ const text = await files.readText(pathOf(files).join(root, "Local State"));
+ if (text === null) return null;
+ // Security: the parser's message can quote the file, which holds the wrapped key.
+ try { return JSON.parse(text) as never; } catch { return null; }
+}
+
+export interface Located {
+ source: Definition;
+ profile: { id: string; name: string; directory: string; cookies: string };
+}
+
+async function chromiumProfiles(files: BrowserFiles, source: Definition): Promise<Located["profile"][]> {
+ const join = pathOf(files).join;
+ const cookies = async (directory: string) => {
+ for (const candidate of [join(directory, "Network", "Cookies"), join(directory, "Cookies")]) if (await files.exists(candidate)) return candidate;
+ return null;
+ };
+ if (source.flat) {
+ const file = await cookies(source.root);
+ return file ? [{ id: "default", name: "Default", directory: source.root, cookies: file }] : [];
+ }
+ const state = await localState(files, source.root);
+ const names = new Map<string, string>();
+ for (const [id, info] of Object.entries(state?.profile?.info_cache ?? {})) {
+ if (PLAIN.test(id) && id !== "." && id !== "..") names.set(id, typeof info?.name === "string" && info.name ? info.name.slice(0, 80) : id);
+ }
+ if (!names.has("Default")) names.set("Default", "Default");
+ const found: Located["profile"][] = [];
+ for (const [id, name] of names) {
+ const directory = join(source.root, id);
+ const file = await cookies(directory);
+ if (file) found.push({ id, name, directory, cookies: file });
+ }
+ return found;
+}
+
+/** The profiles a Firefox `profiles.ini` lists, with their folders resolved. */
+export function firefoxProfiles(root: string, ini: string, join: (...parts: string[]) => string = posix.join): Array<{ id: string; name: string; directory: string }> {
+ return ini.split(/^\[/mu).flatMap((section) => {
+ if (!section.slice(0, section.indexOf("]")).startsWith("Profile")) return [];
+ const fields = Object.fromEntries(section.split(/\r?\n/u).slice(1).flatMap((line) => {
+ const index = line.indexOf("=");
+ return index > 0 ? [[line.slice(0, index).trim(), line.slice(index + 1).trim()]] : [];
+ }));
+ const value = fields.Path;
+ if (!value || value.length > 512) return [];
+ if (fields.IsRelative !== "0" && (value.split(/[/\\]/u).includes(".."))) return [];
+ return [{ id: value, name: (fields.Name || value).slice(0, 80), directory: fields.IsRelative === "0" ? value : join(root, value) }];
+ });
+}
+
+async function profilesOf(files: BrowserFiles, source: Definition): Promise<Located["profile"][]> {
+ const join = pathOf(files).join;
+ if (source.engine === "safari") {
+ // Listed without looking inside Safari's container: a look there can raise a system prompt before the person asked.
+ return [{ id: "default", name: "Default", directory: source.root, cookies: join(source.root, "Containers", "com.apple.Safari", "Data", "Library", "Cookies", "Cookies.binarycookies") }];
+ }
+ if (source.engine === "firefox") {
+ const ini = await files.readText(join(source.root, "profiles.ini"));
+ if (ini === null) return [];
+ const found: Located["profile"][] = [];
+ for (const profile of firefoxProfiles(source.root, ini, join)) {
+ const cookies = join(profile.directory, "cookies.sqlite");
+ if (await files.exists(cookies)) found.push({ ...profile, cookies });
+ }
+ return found;
+ }
+ return chromiumProfiles(files, source);
+}
+
+/** Every browser with at least one profile, for the person to pick from. Safari is offered on macOS whenever installed. */
+export async function listSources(files: BrowserFiles): Promise<BrowserSource[]> {
+ const sources: BrowserSource[] = [];
+ for (const source of definitions(files)) {
+ if (source.engine === "safari" && !(await files.exists("/Applications/Safari.app"))) continue;
+ const profiles = await profilesOf(files, source);
+ if (profiles.length) sources.push({ id: source.id, name: source.name, engine: source.engine, profiles: profiles.map(({ id, name }) => ({ id, name })) });
+ }
+ return sources;
+}
+
+/** A profile the listing offered, by its ids: nothing a caller sends is ever used as a path. */
+export async function locate(files: BrowserFiles, sourceId: string, profileId: string): Promise<Located | null> {
+ const source = definitions(files).find((candidate) => candidate.id === sourceId);
+ const profile = source ? (await profilesOf(files, source)).find((candidate) => candidate.id === profileId) : undefined;
+ return source && profile ? { source, profile } : null;
+}
+
+/** Windows Chrome-family browsers whose `Local State` carries no DPAPI key: their values cannot be read here. */
+export class KeyUnavailable extends Error {}
+
+/** The key of a Chromium source, asked of the key store only now. */
+export async function chromiumKey(files: BrowserFiles, located: Located, keys: KeyStore): Promise<ChromiumKey> {
+ const source = located.source;
+ if (files.platform === "win32") {
+ const wrapped = (await localState(files, source.root))?.os_crypt?.encrypted_key;
+ const blob = typeof wrapped === "string" ? Buffer.from(wrapped, "base64") : null;
+ if (!blob || blob.subarray(0, 5).toString("latin1") !== "DPAPI") throw new KeyUnavailable("This browser keeps no key this app can use.");
+ return { type: "gcm", key: await keys.windowsUnprotect(blob.subarray(5)) };
+ }
+ if (files.platform === "darwin") {
+ if (!source.keychain) throw new KeyUnavailable("This browser keeps no key this app can use.");
+ const password = await keys.macPassword(source.keychain.service, source.keychain.account);
+ return { type: "cbc", v10: deriveCbcKey(password.replace(/\r?\n$/u, ""), 1003), v11: null };
+ }
+ let keyring: string | null = null;
+ for (const application of source.keyring ?? []) {
+ keyring = await keys.linuxPassword(application).catch(() => null);
+ if (keyring) break;
+ }
+ // v10 values use Chromium's fixed password; v11 the one the desktop keyring holds.
+ return { type: "cbc", v10: deriveCbcKey("peanuts", 1), v11: keyring ? deriveCbcKey(keyring, 1) : null };
+}
+
+export type Run = (command: string, args: readonly string[], input?: string) => Promise<string>;
+
+/**
+ * A helper program by its absolute path, without a shell and in its own folder, so neither PATH nor the working folder
+ * can put another program in its place; 60 seconds. Security: its output (a key) is returned, never logged, and an
+ * error names only the program and its exit code.
+ */
+export const runProgram: Run = (command, args, input) => new Promise((resolve, reject) => {
+ if (!posix.isAbsolute(command) && !win32.isAbsolute(command)) {
+ reject(new Error(`${command} is not an absolute path`));
+ return;
+ }
+ const child = spawn(command, args, { cwd: (command.includes("\\") ? win32 : posix).dirname(command), shell: false, windowsHide: true, stdio: ["pipe", "pipe", "ignore"] });
+ const chunks: Buffer[] = [];
+ const timer = setTimeout(() => child.kill(), 60_000);
+ child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));
+ child.stdin.on("error", () => undefined);
+ child.on("error", () => { clearTimeout(timer); reject(new Error(`${command} could not start`)); });
+ child.on("close", (code) => {
+ clearTimeout(timer);
+ if (code === 0) resolve(Buffer.concat(chunks).toString("utf8"));
+ else reject(new Error(`${command} exited with ${code}`));
+ });
+ child.stdin.end(input ?? "");
+});
+
+/** Windows PowerShell in the system folder; `SystemRoot` only when it is an absolute drive path. */
+function windowsPowerShell(env: BrowserFiles["env"]): string {
+ const root = env.SystemRoot;
+ const system = root && /^[A-Za-z]:\\[^"<>|?*]*$/u.test(root) ? root : "C:\\Windows";
+ return win32.join(system, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
+}
+
+/**
+ * The operating system's key stores, through their own command-line tools. Known open risk: macOS's Keychain prompt
+ * names `security`, not this app, and "Always Allow" there lets later reads by any process through `security` go silent.
+ */
+export function systemKeyStore(env: BrowserFiles["env"], run: Run = runProgram): KeyStore {
+ return {
+ macPassword: (service, account) => run("/usr/bin/security", ["find-generic-password", "-w", "-a", account, "-s", service]),
+ async windowsUnprotect(blob) {
+ const script = "Add-Type -AssemblyName System.Security;$b=[Convert]::FromBase64String([Console]::In.ReadToEnd());"
+ + "[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser'))";
+ const output = await run(windowsPowerShell(env), ["-NoProfile", "-NonInteractive", "-Command", script], blob.toString("base64"));
+ return Buffer.from(output.trim(), "base64");
+ },
+ async linuxPassword(application) {
+ for (const tool of ["/usr/bin/secret-tool", "/bin/secret-tool"]) {
+ const value = await run(tool, ["lookup", "application", application]).then((text) => text.replace(/\r?\n$/u, ""), () => null);
+ if (value) return value;
+ }
+ return null;
+ },
+ };
+}
+
+/** This computer as the person's own account sees it: only ever read once the person asked for an import. */
+export function systemFiles(): BrowserFiles {
+ return {
+ platform: process.platform,
+ home: (process.platform !== "win32" && process.env.HOME) || homedir(),
+ env: process.env,
+ readText: (path) => readFile(path, "utf8").catch(() => null),
+ exists: (path) => access(path).then(() => true, () => false),
+ };
+}
diff --git a/server/browser/cookies/testing/fixtures.ts b/server/browser/cookies/testing/fixtures.ts
new file mode 100644
index 0000000000..8d69883e6c
--- /dev/null
+++ b/server/browser/cookies/testing/fixtures.ts
@@ -0,0 +1,149 @@
+// Synthetic browser profiles for the cookie import's tests, built in a temporary folder. Nothing here reads, copies or
+// looks at a real browser profile or a real key store: `fixtureFiles` throws for any path outside its folder.
+import { createCipheriv, createHash, randomBytes } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, relative, resolve } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+
+import type { BrowserFiles, KeyStore } from "../sources.ts";
+
+/** A BrowserFiles over `home` that refuses every path outside it, Safari's application aside when `safari` says so. */
+export function fixtureFiles(home: string, platform: NodeJS.Platform, { safari = false, env = {} }: { safari?: boolean; env?: Record<string, string> } = {}): BrowserFiles {
+ // Windows paths over a POSIX fixture folder: the separators turn back into slashes.
+ const native = (path: string) => (platform === "win32" ? path.replaceAll("\\", "/") : path);
+ const inside = (path: string) => {
+ const rel = relative(home, resolve(path));
+ if (rel.startsWith("..") || resolve(path) === resolve("/")) throw new Error(`the test touched a path outside its fixture folder: ${path}`);
+ return path;
+ };
+ return {
+ platform,
+ home,
+ env,
+ async readText(path) {
+ const file = inside(native(path));
+ try { return readFileSync(file, "utf8"); } catch { return null; }
+ },
+ async exists(path) {
+ if (path === "/Applications/Safari.app") return safari;
+ return existsSync(inside(native(path)));
+ },
+ };
+}
+
+export interface FakeKeys extends KeyStore {
+ asked: string[];
+}
+
+/** A key store that answers from fixtures, or turns the request down. */
+export function fakeKeys({ mac = null, windows = null, linux = null }: { mac?: string | null; windows?: Buffer | null; linux?: string | null }): FakeKeys {
+ const asked: string[] = [];
+ return {
+ asked,
+ async macPassword(service, account) {
+ asked.push(`mac:${service}:${account}`);
+ if (mac === null) throw new Error("User canceled the operation.");
+ return `${mac}\n`;
+ },
+ async windowsUnprotect(blob) {
+ asked.push(`windows:${blob.length}`);
+ if (windows === null) throw new Error("The data is invalid.");
+ return windows;
+ },
+ async linuxPassword(application) {
+ asked.push(`linux:${application}`);
+ return linux;
+ },
+ };
+}
+
+export interface ChromiumRowFixture {
+ host: string;
+ name: string;
+ value?: string;
+ encrypted?: Buffer;
+ path?: string;
+ /** Unix seconds; 0 for a session cookie. */
+ expires?: number;
+ secure?: boolean;
+ httpOnly?: boolean;
+ /** Chromium's column: -1 unspecified, 0 none, 1 lax, 2 strict. */
+ sameSite?: number;
+ partition?: string;
+}
+
+const WINDOWS_EPOCH = 11_644_473_600;
+
+/** A Chromium `Cookies` database with the columns the importer reads. */
+export function chromiumDatabase(file: string, rows: ChromiumRowFixture[], { wal = false }: { wal?: boolean } = {}): DatabaseSync {
+ mkdirSync(dirname(file), { recursive: true });
+ const db = new DatabaseSync(file);
+ if (wal) db.exec("PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0;");
+ db.exec("CREATE TABLE cookies (creation_utc INTEGER, host_key TEXT, top_frame_site_key TEXT, name TEXT, value TEXT, encrypted_value BLOB, path TEXT, expires_utc INTEGER, is_secure INTEGER, is_httponly INTEGER, last_access_utc INTEGER, has_expires INTEGER, is_persistent INTEGER, priority INTEGER, samesite INTEGER, source_scheme INTEGER, source_port INTEGER, last_update_utc INTEGER)");
+ const insert = db.prepare("INSERT INTO cookies (creation_utc, host_key, top_frame_site_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, last_access_utc, has_expires, is_persistent, priority, samesite, source_scheme, source_port, last_update_utc) VALUES (0, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, 1, 1, ?, 2, 443, 0)");
+ for (const row of rows) {
+ const expires = row.expires ? BigInt(Math.round((row.expires + WINDOWS_EPOCH) * 1_000_000)) : 0n;
+ insert.run(row.host, row.partition ?? "", row.name, row.value ?? "", row.encrypted ?? Buffer.alloc(0), row.path ?? "/", expires, row.secure ? 1 : 0, row.httpOnly ? 1 : 0, row.expires ? 1 : 0, row.sameSite ?? -1);
+ }
+ return db;
+}
+
+/** Chromium's Windows encryption: AES-256-GCM, a 12-byte nonce and a 16-byte tag, the host's digest in front. */
+export function gcmValue(key: Buffer, host: string, value: string, digest = true): Buffer {
+ const nonce = randomBytes(12);
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
+ const plain = Buffer.concat([digest ? createHash("sha256").update(host).digest() : Buffer.alloc(0), Buffer.from(value)]);
+ const body = Buffer.concat([cipher.update(plain), cipher.final()]);
+ return Buffer.concat([Buffer.from("v10"), nonce, body, cipher.getAuthTag()]);
+}
+
+/** A Chrome `Local State` naming profiles, with a DPAPI-wrapped key for Windows when given. */
+export function localState(root: string, profiles: Record<string, string>, wrappedKey?: Buffer): void {
+ mkdirSync(root, { recursive: true });
+ const info = Object.fromEntries(Object.entries(profiles).map(([id, name]) => [id, { name }]));
+ const state = { profile: { info_cache: info }, ...(wrappedKey ? { os_crypt: { encrypted_key: Buffer.concat([Buffer.from("DPAPI"), wrappedKey]).toString("base64") } } : {}) };
+ writeFileSync(join(root, "Local State"), JSON.stringify(state));
+}
+
+/** A Firefox profile folder with `cookies.sqlite`, listed in `profiles.ini`. */
+export function firefoxProfile(root: string, folder: string, name: string, rows: Array<{ host: string; name: string; value: string; path?: string; expiry?: number; secure?: boolean; httpOnly?: boolean; sameSite?: number; originAttributes?: string }>): string {
+ mkdirSync(join(root, folder), { recursive: true });
+ writeFileSync(join(root, "profiles.ini"), `[General]\nStartWithLastProfile=1\n\n[Profile0]\nName=${name}\nIsRelative=1\nPath=${folder}\nDefault=1\n`);
+ const db = new DatabaseSync(join(root, folder, "cookies.sqlite"));
+ db.exec("CREATE TABLE moz_cookies (id INTEGER PRIMARY KEY, originAttributes TEXT NOT NULL DEFAULT '', name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, inBrowserElement INTEGER DEFAULT 0, sameSite INTEGER DEFAULT 0, schemeMap INTEGER DEFAULT 0, isPartitionedAttributeSet INTEGER DEFAULT 0)");
+ const insert = db.prepare("INSERT INTO moz_cookies (originAttributes, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly, sameSite) VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?, ?, ?)");
+ for (const row of rows) insert.run(row.originAttributes ?? "", row.name, row.value, row.host, row.path ?? "/", row.expiry ?? 0, row.secure ? 1 : 0, row.httpOnly ? 1 : 0, row.sameSite ?? 0);
+ db.close();
+ return join(root, folder);
+}
+
+/** Safari's `Cookies.binarycookies`, one page, written as Safari lays it out. */
+export function binaryCookies(cookies: Array<{ host: string; name: string; value: string; path?: string; expires?: number; secure?: boolean; httpOnly?: boolean }>): Buffer {
+ const MAC_EPOCH = 978_307_200;
+ const records = cookies.map((cookie) => {
+ const strings = [cookie.host, cookie.name, cookie.path ?? "/", cookie.value].map((text) => Buffer.from(`${text}\0`));
+ const header = Buffer.alloc(56);
+ let offset = 56;
+ const offsets = strings.map((text) => { const at = offset; offset += text.length; return at; });
+ header.writeUInt32LE(offset, 0);
+ header.writeUInt32LE((cookie.secure ? 1 : 0) | (cookie.httpOnly ? 4 : 0), 8);
+ header.writeUInt32LE(offsets[0]!, 16);
+ header.writeUInt32LE(offsets[1]!, 20);
+ header.writeUInt32LE(offsets[2]!, 24);
+ header.writeUInt32LE(offsets[3]!, 28);
+ header.writeDoubleLE(cookie.expires ? cookie.expires - MAC_EPOCH : 0, 40);
+ return Buffer.concat([header, ...strings]);
+ });
+ const head = Buffer.alloc(8 + records.length * 4 + 4);
+ head.writeUInt32LE(0x100, 0);
+ head.writeUInt32LE(records.length, 4);
+ let at = head.length;
+ records.forEach((record, index) => { head.writeUInt32LE(at, 8 + index * 4); at += record.length; });
+ const page = Buffer.concat([head, ...records]);
+ const file = Buffer.alloc(8);
+ file.write("cook", 0, "latin1");
+ file.writeUInt32BE(1, 4);
+ const size = Buffer.alloc(4);
+ size.writeUInt32BE(page.length, 0);
+ return Buffer.concat([file, size, page]);
+}
diff --git a/server/browser/engines.ts b/server/browser/engines.ts
index 3f21cb2001..bcb5dada65 100644
--- a/server/browser/engines.ts
+++ b/server/browser/engines.ts
@@ -21,6 +21,8 @@ import { findBwrap } from "./desktop/policy.ts";
import { DesktopViews, type DesktopRequest } from "./desktop/views.ts";
import { botReason, browserInputLog, pageAction, type BotReason, type BrowserInputLog } from "./input-log.ts";
import type { PaneBackend } from "./pane/backend.ts";
+import type { CookieSink } from "./cookies/importer.ts";
+import { cdpSink } from "./cookies/sinks.ts";
import type { Download } from "./cdp/downloads.ts";
import { BrowserService, type BrowserTarget } from "./service.ts";
import { LiveV1 } from "./viewers/live-v1.ts";
@@ -152,6 +154,13 @@ export class ChromeEngine {
return { command: CHROME_ENGINE, args: [key], env: {} };
}
+ /** Where a profile's browser takes an imported sign-in: its pane partition, or its launched Chrome (started for it). */
+ cookieSink(target: BrowserTarget): CookieSink {
+ const pane = this.#options.pane;
+ if (pane && pane.wanted() && pane.backend.available) return pane.backend.cookieSink(target.key);
+ return cdpSink(async (method, params) => (await this.service.running(this.service.profile(target))).browser.connection.root.send(method, params));
+ }
+
/** Whether a session's browser runs as desktop panes now. */
onPane(spec: { command: string; args?: readonly string[] }): boolean {
const key = spec.command === CHROME_ENGINE ? spec.args?.[0] : undefined;
diff --git a/server/browser/pane/backend.ts b/server/browser/pane/backend.ts
index 0ef9a5b848..faaf05471e 100644
--- a/server/browser/pane/backend.ts
+++ b/server/browser/pane/backend.ts
@@ -7,6 +7,8 @@ import { PANE_TABS_PER_BROWSER } from "../../../electron/browser-pane-wire.mjs";
import type { Backend, BackendCaps, OpenedBrowser, OpenRequest } from "../backends.ts";
import { CdpBrowser } from "../cdp/browser.ts";
import { browserRoot, profileHash, profileKind, workspaceId } from "../chrome/profile.ts";
+import type { CookieSink } from "../cookies/importer.ts";
+import { paneSink } from "../cookies/sinks.ts";
import { PaneUnavailable, type OpenedPanes, type PaneLink } from "./link.ts";
const PANE_CAPS: BackendCaps = { persistentProfile: true, window: true, egressGate: true, identityOverride: false, ownsAllTabs: true, downloads: "local", uploads: "path", botPasskeys: false };
@@ -69,10 +71,7 @@ export class PaneBackend implements Backend {
if (error instanceof PaneUnavailable && this.#fallback) return this.#fallback.open(request);
throw error;
}
- if (profileKind(request.key) !== "temp") {
- mkdirSync(marksDir(this.#dataDir), { recursive: true, mode: 0o700 });
- writeFileSync(join(marksDir(this.#dataDir), profileHash(workspaceId(this.#dataDir), request.key)), "");
- }
+ this.#mark(request.key);
let browser: CdpBrowser;
try {
browser = await CdpBrowser.connect(opened.endpoint, { identity: null, headless: false, permissions: false, downloadDir: request.downloadDir, viewport: null, platform: this.#platform, maxPages: PANE_TABS_PER_BROWSER, handleAuth: true });
@@ -110,6 +109,20 @@ export class PaneBackend implements Backend {
};
}
+ #mark(key: string): void {
+ if (profileKind(key) === "temp") return;
+ mkdirSync(marksDir(this.#dataDir), { recursive: true, mode: 0o700 });
+ writeFileSync(join(marksDir(this.#dataDir), profileHash(workspaceId(this.#dataDir), key)), "");
+ }
+
+ /** An imported sign-in, into the profile's partition; marked, so deleting the bot erases it as well. */
+ cookieSink(key: string): CookieSink {
+ return paneSink(async (cookies) => {
+ this.#mark(key);
+ return this.#link.setCookies(panePartition(this.#dataDir, key), cookies);
+ });
+ }
+
/** A deleted bot's or profile's pane sign-ins, when its panes ever opened here. */
erase(key: string): void {
if (!this.used(key)) return;
diff --git a/server/browser/pane/link.ts b/server/browser/pane/link.ts
index 99078cc300..112eef1f0f 100644
--- a/server/browser/pane/link.ts
+++ b/server/browser/pane/link.ts
@@ -1,5 +1,5 @@
// The server's end of the desktop app's pane messages: one PaneEndpoint per profile the main process shows natively.
-import { PANE_MESSAGE, paneMessageToServer, type PaneToMain, type PaneToServer } from "../../../electron/browser-pane-wire.mjs";
+import { PANE_MESSAGE, paneMessageToServer, type CookieImportResult, type CookieSource, type PaneCookie, type PaneToMain, type PaneToServer } from "../../../electron/browser-pane-wire.mjs";
import type { Params } from "../cdp/connection.ts";
import { PaneEndpoint, type PaneChannel, type PaneEndpointOptions, type PaneTab } from "./endpoint.ts";
@@ -41,6 +41,13 @@ const REQUEST_TIMEOUT_MS = 120_000;
/** No app window can host a pane now (the window is closed); a launched Chrome can run the browser instead. */
export class PaneUnavailable extends Error {}
+/** What the person's sign-in imports ask of the server. */
+export interface CookieRequests {
+ sources(): Promise<CookieSource[]>;
+ offer(request: { botId: string; threadId: string | null; site: string }): Promise<{ offered: boolean; reason?: string }>;
+ import(request: { botId: string; threadId: string | null; site: string; source: string; profile: string }): Promise<CookieImportResult>;
+}
+
export class PaneProtocolError extends Error {
readonly code: number | undefined;
@@ -57,6 +64,7 @@ export class PaneLink {
readonly #opening = new Map<string, { resolve(answer: { version: string; userAgent: string }): void; reject(error: Error): void }>();
readonly #pending = new Map<number, Pending>();
#resolver: ((botId: string, threadId: string | null) => string | null) | null = null;
+ #cookies: CookieRequests | null = null;
#ready = false;
#next = 0;
@@ -85,6 +93,16 @@ export class PaneLink {
this.#resolver = resolver;
}
+ /** Answers the person's sign-in imports, which reach this server only from the app's own window, through its main process. */
+ answerCookieRequests(requests: CookieRequests): void {
+ this.#cookies = requests;
+ }
+
+ /** Writes an import's cookies into a pane partition, whether or not a pane of it is open. */
+ setCookies(partition: string, cookies: PaneCookie[]): Promise<{ written: number; refused: number }> {
+ return this.#request(null, (req) => ({ op: "set-cookies", req, partition, cookies })) as Promise<{ written: number; refused: number }>;
+ }
+
async open(browser: string, partition: string, egress: number, downloads: string, identity: "native" | "cleaned" = "native"): Promise<OpenedPanes> {
if (!this.available) throw new PaneUnavailable("The desktop app does not show browser panes here.");
this.close(browser);
@@ -142,8 +160,8 @@ export class PaneLink {
if (this.#port) this.#post({ op: "erase", partition });
}
- #request(browser: string, message: (req: number) => Outgoing): Promise<Params | PaneTab> {
- if (!this.#browsers.has(browser)) return Promise.reject(new PaneProtocolError("Target closed"));
+ #request(browser: string | null, message: (req: number) => Outgoing): Promise<Params | PaneTab> {
+ if (browser === null ? !this.available : !this.#browsers.has(browser)) return Promise.reject(new PaneProtocolError("Target closed"));
const req = ++this.#next;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
@@ -155,6 +173,20 @@ export class PaneLink {
});
}
+ /** Security: a failure is answered by its fixed fallback, never by its message, which could quote what was read. */
+ async #answer(req: number, answer: () => Promise<Outgoing>, fallback: () => Outgoing): Promise<void> {
+ if (!this.#cookies) {
+ this.#post(fallback());
+ return;
+ }
+ try {
+ this.#post(await answer());
+ } catch {
+ console.warn(`browser pane: a sign-in import request (${req}) failed`);
+ this.#post(fallback());
+ }
+ }
+
#fail(browser: string, reason: string): void {
for (const [req, pending] of this.#pending) {
if (pending.browser !== browser) continue;
@@ -204,6 +236,25 @@ export class PaneLink {
this.#post({ op: "resolved", req: message.req, browser });
return;
}
+ case "cookies-set": {
+ const pending = this.#pending.get(message.req);
+ if (!pending || pending.browser !== null) return;
+ this.#pending.delete(message.req);
+ pending.resolve({ written: message.written, refused: message.refused });
+ return;
+ }
+ case "cookie-sources":
+ void this.#answer(message.req, async () => ({ op: "cookie-sources-result", req: message.req, sources: await this.#cookies!.sources() }),
+ () => ({ op: "cookie-sources-result", req: message.req, sources: [] }));
+ return;
+ case "cookie-offer":
+ void this.#answer(message.req, async () => ({ op: "cookie-offer-result", req: message.req, ...(await this.#cookies!.offer(message)) }),
+ () => ({ op: "cookie-offer-result", req: message.req, offered: false, reason: "unreadable" }));
+ return;
+ case "cookie-import":
+ void this.#answer(message.req, async () => ({ op: "cookie-import-result", req: message.req, result: await this.#cookies!.import(message) }),
+ () => ({ op: "cookie-import-result", req: message.req, result: { ok: false, reason: "unreadable" } }));
+ return;
}
const open = this.#browsers.get(message.browser);
if (!open) return;
diff --git a/server/browser/pane/testing/fake-main.ts b/server/browser/pane/testing/fake-main.ts
index 6f3065bb26..a12894e3fc 100644
--- a/server/browser/pane/testing/fake-main.ts
+++ b/server/browser/pane/testing/fake-main.ts
@@ -25,6 +25,10 @@ export class FakeMain implements PanePort {
readonly partitions: string[] = [];
readonly egress: number[] = [];
readonly downloadDirs: string[] = [];
+ /** What the app wrote into each partition, as its cookies.set would. */
+ readonly cookiesSet: Array<{ partition: string; cookies: unknown[] }> = [];
+ /** Answers the server sent to the person's import requests. */
+ readonly answers: Array<Record<string, unknown>> = [];
/** No app window: opening answers that none can host a pane. */
noWindow = false;
/** Milliseconds before an open is answered. */
@@ -51,7 +55,8 @@ export class FakeMain implements PanePort {
postMessage(message: object): void {
const parsed = paneMessageToMain(message);
- if (!parsed) throw new Error(`the server sent a malformed pane message: ${JSON.stringify(message)}`);
+ // Only the op: a message may carry a cookie's value.
+ if (!parsed) throw new Error(`the server sent a malformed pane message: ${String((message as { op?: unknown }).op)}`);
this.toMain.push(parsed);
void this.#handle(parsed);
}
@@ -62,7 +67,7 @@ export class FakeMain implements PanePort {
post(message: Record<string, unknown>): void {
const data = { type: PANE_MESSAGE, ...message };
- if (!paneMessageToServer(data)) throw new Error(`the fake main sent a malformed pane message: ${JSON.stringify(data)}`);
+ if (!paneMessageToServer(data)) throw new Error(`the fake main sent a malformed pane message: ${String(message.op)}`);
queueMicrotask(() => { for (const listener of this.#listeners) listener({ data }); });
}
@@ -129,6 +134,15 @@ export class FakeMain implements PanePort {
for (const pane of this.panes.values()) if (pane.browser === message.browser) await this.#closeTab(pane.tab, false);
this.post({ op: "closed", browser: message.browser, reason: "closed by the app" });
return;
+ case "set-cookies":
+ this.cookiesSet.push({ partition: message.partition, cookies: message.cookies });
+ this.post({ op: "cookies-set", req: message.req, written: message.cookies.length, refused: 0 });
+ return;
+ case "cookie-sources-result":
+ case "cookie-import-result":
+ case "cookie-offer-result":
+ this.answers.push(message as unknown as Record<string, unknown>);
+ return;
default:
return;
}
diff --git a/server/host/browser.ts b/server/host/browser.ts
index 3f45a9ae6f..89996845b4 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -49,6 +49,9 @@ import { boxMemory } from "../box-memory.ts";
import { CHROME_BROWSER_SYSTEM_PROMPT } from "../browser/prompt.ts";
import { PaneBackend } from "../browser/pane/backend.ts";
import { desktopPaneLink } from "../browser/pane/link.ts";
+import { cookieRequests } from "../browser/cookies/requests.ts";
+import { systemFiles, systemKeyStore } from "../browser/cookies/sources.ts";
+import { sweep as sweepCookieCopies } from "../browser/cookies/snapshot.ts";
import { passkeyAnnotation } from "../browser/passkey-notice.ts";
import { LentChromeDoors, lentChromeGuidance, type ChromeLender } from "../browser/lent-chrome.ts";
import type { ChromeRoute } from "../device-links.ts";
@@ -453,6 +456,24 @@ export function createBrowserHost(deps: BrowserHostDeps) {
const { session, spec } = chromeSpec(botId, bot.browserProfile, browserAudience(threadId ?? undefined));
return chromeTarget(session, spec)?.key ?? null;
});
+ // A person's sign-in import, from their own browsers into a bot's. agent-browser keeps its profiles in its own encrypted
+ // saved state, which only its running daemon writes: it takes none, and neither do temporary browsers or My Chrome.
+ const cookieScratch = join(DATA_DIR, "browser", "cookie-import");
+ // A copy an import left when the server stopped mid-read holds another browser's cookies in plain text.
+ if (paneLink) void sweepCookieCopies(cookieScratch);
+ paneLink?.answerCookieRequests(cookieRequests({
+ files: systemFiles,
+ keys: () => systemKeyStore(process.env),
+ scratch: cookieScratch,
+ destination: (botId, threadId) => {
+ const bot = store.bot(botId);
+ if (!bot || bot.browser === false || bot.browserProfile === "guest" || !onChrome(bot.browserProfile)) return null;
+ const { session, spec } = chromeSpec(botId, bot.browserProfile, browserAudience(threadId ?? undefined));
+ const target = chromeTarget(session, spec);
+ return target ? chromeEngine.cookieSink(target) : null;
+ },
+ log: (line) => console.warn(line),
+ }));
/** Chrome for the new engine, the installed agent-browser otherwise. */
function browserReady(profile: string | undefined): boolean {
return onChrome(profile) ? chromeEngine.summary().kind === "engine" : browserEngineStatus().kind === "ready";
@@ -705,7 +726,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return { binaryPath: engine.binaryPath, session, env: browserSessionSpec(engine.binaryPath, session, profile, await browserEgress.open(session)).env, encryptionKey: browserEngineEncryptionKey() };
}
/** What Settings shows of the engine that runs bots' browsers here; My Chrome stays on agent-browser. */
- function engineSummary<T extends { kind: "engine" | "unavailable"; myChrome: boolean }>(agentBrowser: T): (T | (ReturnType<ChromeEngine["summary"]> & { myChrome: boolean })) & { engine: BrowserEngineKind; pane?: true; noChrome?: true; serverSites?: boolean; proxyConfigured?: boolean; proxySaved?: boolean } {
+ function engineSummary<T extends { kind: "engine" | "unavailable"; myChrome: boolean }>(agentBrowser: T): (T | (ReturnType<ChromeEngine["summary"]> & { myChrome: boolean })) & { engine: BrowserEngineKind; pane?: true; cookieImport?: true; noChrome?: true; serverSites?: boolean; proxyConfigured?: boolean; proxySaved?: boolean } {
const serverSites = sitesSwitch ? { serverSites: cfg.browserEngine?.egress?.localNetwork === true } : {};
const engine = browserEngineKind(cfg);
const proxyValue = cfg.browserEngine?.egress?.proxy;
@@ -714,6 +735,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return {
...(engine === "chrome" ? { ...chromeEngine.summary(), myChrome: agentBrowser.myChrome, ...lentChromeSummary(), engine } : { ...agentBrowser, engine }),
...(paneLink?.available && browserPaneWanted(cfg) ? { pane: true as const } : {}),
+ ...(paneLink?.available && engine === "chrome" ? { cookieImport: true as const } : {}),
...(engine !== "chrome" && agentBrowser.kind === "engine" && chromeLauncher.runsShellForWantOfChrome() ? { noChrome: true as const } : {}),
...serverSites,
...(proxyConfigured ? { proxyConfigured: true } : {}),
diff --git a/src/components/BrowserPanel.tsx b/src/components/BrowserPanel.tsx
index 3fbc62af65..0221971879 100644
--- a/src/components/BrowserPanel.tsx
+++ b/src/components/BrowserPanel.tsx
@@ -19,6 +19,7 @@ import { BROWSER_HELD_ELSEWHERE } from "../../shared/browser-held";
import { passkeyWallAt } from "../../shared/passkey-wall";
import { browserScope, withBrowserScope } from "@/lib/team-browser";
import { useNativeViewObscured } from "@/lib/native-view-obscured";
+import { CookieImportDialog, cookieImportAvailable, siteOfAddress } from "./browser/CookieImportDialog";
const BrowserDesktop = lazy(() => import("./browser/BrowserDesktop").then((module) => ({ default: module.BrowserDesktop })));
@@ -70,6 +71,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
const [kept, setKept] = useState(false);
const [showProfiles, setShowProfiles] = useState(false);
const [showTyping, setShowTyping] = useState(false);
+ const [showImport, setShowImport] = useState(false);
const [masked, setMasked] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const [maximized, setMaximized] = useState(false);
@@ -312,7 +314,10 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
setError("");
}, [shown]);
const typingReady = connected && you;
- const obscured = useNativeViewObscured(showProfiles || showTyping, paneMode);
+ const obscured = useNativeViewObscured(showProfiles || showTyping || showImport, paneMode);
+ const profile = state.config?.browserProfiles?.find((candidate) => candidate.id === bot.browserProfile);
+ const importable = cookieImportAvailable(state.config) && bot.browserProfile !== "guest"
+ && !(profile?.browser === "chrome" && state.config?.browserEngine?.myChrome === true);
const paneVisible = paneMode && shown && connected && !asleep && !heldElsewhere && !gone && !starting && !obscured;
const paneShown = useRef(paneVisible);
const placePane = useRef<() => void>(() => {});
@@ -386,6 +391,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
onPip={togglePip}
onType={() => { setMasked(false); setShowTyping(true); }}
onSecret={() => { setMasked(true); setShowTyping(true); }}
+ {...(importable ? { onImport: () => setShowImport(true) } : {})}
onReconnect={reconnect}
onRestart={restart}
/></>}
@@ -438,6 +444,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
{(heldElsewhere || (you && takeStatus !== "")) && <p className="mb-3 text-[12px] text-ink-secondary">{t(heldElsewhere ? "browser.profiles.heldElsewhere" : "browser.profiles.busy")}</p>}
<BrowserProfilesManager bot={bot} disabled={heldElsewhere || takeStatus === "pending" || takeStatus === "slow"} onProfileChanged={() => { setShowProfiles(false); reconnect(); }} />
</dialog>
+ {importable ? <CookieImportDialog open={showImport} botId={bot.id} botName={bot.name} threadId={scopedThread ?? null} site={siteOfAddress(nav.url)} onClose={() => setShowImport(false)} /> : null}
{/* Security: a password or code typed here goes only to the page's focused field; it is never held in state, logged or shown. */}
<dialog ref={typingDialog} onClose={() => { const field = typingDialog.current?.querySelector("input"); if (field) field.value = ""; setShowTyping(false); }} className="m-auto w-[min(420px,calc(100%-32px))] rounded-2xl border border-hairline/50 bg-card p-5 text-ink shadow-2xl backdrop:bg-black/40">
<div className="mb-3 flex items-center justify-between"><h2 className="text-[14px] font-medium">{masked ? t("browser.typeSecret.title") : t("browser.panel.typeTextTitle")}</h2><button className={button} aria-label={t("browser.panel.closeTyping")} onClick={() => setShowTyping(false)}><X size={16} /></button></div>
diff --git a/src/components/bot-panel/browser-logins.tsx b/src/components/bot-panel/browser-logins.tsx
index ad3beca957..3c3907141b 100644
--- a/src/components/bot-panel/browser-logins.tsx
+++ b/src/components/bot-panel/browser-logins.tsx
@@ -1,9 +1,12 @@
-import { Plus } from "lucide-react";
+import { LogIn, Plus } from "lucide-react";
+import { useState } from "react";
import { t } from "@/lib/i18n";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { type Bot } from "@/state/store";
import { SignedInSites } from "../SignedInSites";
+import { CookieImportDialog, cookieImportAvailable } from "../browser/CookieImportDialog";
+import { browserScope } from "@/lib/team-browser";
import { Card, ColRow, LinkRow, NoteRow } from "./rows";
import { sameFields, sameItems, useStoreSelector } from "@/state/store-select";
@@ -13,6 +16,7 @@ export function BrowserLogins({ bot, browserEnabled, onOpenBrowser }: {
onOpenBrowser: () => void;
}) {
const state = useStoreSelector((s) => ({ config: s.config }), sameFields);
+ const [importing, setImporting] = useState(false);
const ownerOrAdmin = useOwnerOrAdmin();
const profileId = bot.browserProfile ?? "";
const profile = (state.config?.browserProfiles ?? []).find((candidate) => candidate.id === profileId);
@@ -40,6 +44,12 @@ export function BrowserLogins({ bot, browserEnabled, onOpenBrowser }: {
)}
<NoteRow>{t("botSettings.simple.loginsHint", { name: bot.name })}</NoteRow>
<LinkRow data-panel-action="add-login" icon={Plus} onClick={onOpenBrowser}>{t("botSettings.simple.addLogin")}</LinkRow>
+ {cookieImportAvailable(state.config) && ownerOrAdmin !== false ? (
+ <>
+ <LinkRow data-panel-action="import-login" icon={LogIn} onClick={() => setImporting(true)}>{t("botSettings.simple.importLogin")}</LinkRow>
+ <CookieImportDialog open={importing} botId={bot.id} botName={bot.name} threadId={browserScope(state.config?.team, bot.threadId).threadId ?? null} site="" onClose={() => setImporting(false)} />
+ </>
+ ) : null}
</>
)}
</Card>
diff --git a/src/components/browser/CookieImportDialog.dom.test.ts b/src/components/browser/CookieImportDialog.dom.test.ts
new file mode 100644
index 0000000000..3daa4067ee
--- /dev/null
+++ b/src/components/browser/CookieImportDialog.dom.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { CookieImportDialog, siteOfAddress } from "./CookieImportDialog";
+import { MoreMenu } from "./MoreMenu";
+
+const SOURCES = [
+ { id: "chrome", name: "Google Chrome", engine: "chromium" as const, profiles: [{ id: "Default", name: "Person" }, { id: "Profile 1", name: "Work" }] },
+ { id: "firefox", name: "Firefox", engine: "firefox" as const, profiles: [{ id: "abc.default", name: "default-release" }] },
+];
+
+let host: HTMLDivElement;
+let root: Root;
+let bridge: { sources: ReturnType<typeof vi.fn>; offer: ReturnType<typeof vi.fn>; import: ReturnType<typeof vi.fn> };
+const settle = async () => { await act(async () => { for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0)); }); };
+const text = () => host.textContent ?? "";
+
+beforeEach(() => {
+ bridge = { sources: vi.fn(async () => SOURCES), offer: vi.fn(), import: vi.fn() };
+ (window as unknown as { ogb: unknown }).ogb = { browserCookies: bridge };
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ delete (window as unknown as { ogb?: unknown }).ogb;
+});
+
+const render = async (site = "github.com") => {
+ await act(async () => root.render(createElement(CookieImportDialog, { open: true, botId: "scout", botName: "Scout", threadId: null, site, onClose: () => {} })));
+ await settle();
+};
+const submit = async () => {
+ await act(async () => { host.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })); });
+ await settle();
+};
+
+describe("the sign-in import dialog", () => {
+ it("names the browser, profile, site and bot, then says how many cookies came over", async () => {
+ bridge.import.mockResolvedValue({ ok: true, site: "github.com", imported: 4, sessionOnly: 0, skipped: {} });
+ await render();
+ expect(host.querySelector<HTMLInputElement>("input")!.value).toBe("github.com");
+ expect(text()).toContain("Copies your sign-in for github.com from Google Chrome (Person) into Scout's browser.");
+ expect(text()).toContain("Google sign-ins are never copied");
+ await submit();
+ expect(bridge.import).toHaveBeenCalledWith({ botId: "scout", threadId: null, site: "github.com", source: "chrome", profile: "Default" });
+ expect(host.querySelector('[role="status"]')?.textContent).toBe("Imported 4 cookies for github.com.");
+ });
+
+ it("says plainly why nothing was imported", async () => {
+ bridge.import.mockResolvedValue({ ok: false, reason: "full-disk-access" });
+ await render("example.com");
+ await submit();
+ expect(host.querySelector('[role="alert"]')?.textContent).toContain("Full Disk Access");
+ bridge.import.mockResolvedValue({ ok: false, reason: "google" });
+ await submit();
+ expect(host.querySelector('[role="alert"]')?.textContent).toContain("Use My Chrome for Google");
+ });
+
+ it("names the whole site an import takes, and keeps what the person typed while the bot browses on", async () => {
+ bridge.import.mockResolvedValue({ ok: true, site: "example.com", imported: 2, sessionOnly: 0, skipped: { protected: 3 } });
+ await render("docs.example.com");
+ expect(text()).toContain("Copies your sign-in for example.com from Google Chrome (Person) into Scout's browser.");
+ const input = host.querySelector<HTMLInputElement>("input")!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "https://shop.example.co.uk/cart");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ expect(text()).toContain("Copies your sign-in for example.co.uk from");
+ // The page the bot is on moves; the form stays as the person left it.
+ await act(async () => root.render(createElement(CookieImportDialog, { open: true, botId: "scout", botName: "Scout", threadId: null, site: "other.test", onClose: () => {} })));
+ await settle();
+ expect(host.querySelector<HTMLInputElement>("input")!.value).toBe("https://shop.example.co.uk/cart");
+ await submit();
+ expect(host.querySelector('[role="status"]')?.textContent).toBe("Imported 2 cookies for example.com. 3 more couldn't be read from Google Chrome.");
+ });
+
+ it("says when no browser with sign-ins is on this computer", async () => {
+ bridge.sources.mockResolvedValue([]);
+ await render();
+ expect(text()).toContain("No browser with sign-ins was found on this computer.");
+ expect(host.querySelector("form")).toBeNull();
+ });
+});
+
+describe("the browser menu's import entry", () => {
+ const menu = (onImport?: () => void) => createElement(MoreMenu, {
+ stream: true, ready: true, typing: true, setting: { mode: "fill" }, zoom: 1, pip: null,
+ onViewport: () => {}, onZoom: () => {}, onPip: () => {}, onType: () => {}, onSecret: () => {}, onReconnect: () => {}, onRestart: () => {},
+ ...(onImport ? { onImport } : {}),
+ });
+
+ it("appears only where an import is possible, and opens the dialog", async () => {
+ await act(async () => root.render(menu()));
+ expect(text()).not.toContain("Import sign-in from your browser");
+ const onImport = vi.fn();
+ await act(async () => root.render(menu(onImport)));
+ const entry = [...host.querySelectorAll("button")].find((button) => button.textContent === "Import a sign-in…")!;
+ await act(async () => { entry.click(); });
+ expect(onImport).toHaveBeenCalledTimes(1);
+ });
+
+ it("starts the site from the page the bot is on", () => {
+ expect(siteOfAddress("https://www.github.com/login")).toBe("github.com");
+ expect(siteOfAddress("about:blank")).toBe("");
+ expect(siteOfAddress("chrome://settings")).toBe("");
+ });
+});
diff --git a/src/components/browser/CookieImportDialog.tsx b/src/components/browser/CookieImportDialog.tsx
new file mode 100644
index 0000000000..60801ce7c3
--- /dev/null
+++ b/src/components/browser/CookieImportDialog.tsx
@@ -0,0 +1,159 @@
+import { useEffect, useRef, useState } from "react";
+import { X } from "lucide-react";
+
+import { loginSite } from "../../../shared/logins";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+
+const button = "rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink";
+const field = "w-full rounded-lg bg-inset px-3 py-2 text-[13px] outline-none focus:ring-1 focus:ring-accent disabled:opacity-60";
+
+const REASONS: Record<string, LocaleKey> = {
+ "not-a-site": "browser.cookieImport.reason.notASite",
+ google: "browser.cookieImport.reason.google",
+ "no-source": "browser.cookieImport.reason.noSource",
+ "key-denied": "browser.cookieImport.reason.keyDenied",
+ "full-disk-access": "browser.cookieImport.reason.fullDiskAccess",
+ "app-bound": "browser.cookieImport.reason.appBound",
+ locked: "browser.cookieImport.reason.locked",
+ unreadable: "browser.cookieImport.reason.unreadable",
+ "nothing-found": "browser.cookieImport.reason.nothingFound",
+ "no-destination": "browser.cookieImport.reason.noDestination",
+};
+
+/** The site a page address belongs to, for the form to start from; empty for anything but a web page. */
+export function siteOfAddress(address: string): string {
+ try {
+ const url = new URL(address);
+ return url.protocol === "https:" || url.protocol === "http:" ? url.hostname.replace(/^www\./u, "") : "";
+ } catch {
+ return "";
+ }
+}
+
+/** The site an import takes, as the server reads it: the registrable domain of what was typed. */
+export function importedSite(typed: string): string {
+ const text = typed.trim().toLowerCase();
+ if (!text) return "";
+ let host = text;
+ if (/^[a-z][a-z0-9+.-]*:\/\//u.test(text)) {
+ try { host = new URL(text).hostname; } catch { return text; }
+ }
+ return loginSite(host);
+}
+
+/** Whether this app can import a sign-in for a bot here: the desktop app, with the server's import ready. */
+export function cookieImportAvailable(config: { browserEngine?: { cookieImport?: true } } | null | undefined): boolean {
+ return config?.browserEngine?.cookieImport === true && Boolean(window.ogb?.browserCookies);
+}
+
+/**
+ * A site's sign-in from one of the person's own browsers into a bot's: they pick the browser, its profile and the
+ * site, and confirm a sentence naming all three and the bot. Security: only counts and a reason come back.
+ */
+export function CookieImportDialog({ open, botId, botName, threadId, site: initialSite, onClose }: {
+ open: boolean;
+ botId: string;
+ botName: string;
+ threadId: string | null;
+ site: string;
+ onClose: () => void;
+}) {
+ const dialog = useRef<HTMLDialogElement>(null);
+ const opening = useRef(initialSite);
+ opening.current = initialSite;
+ const [sources, setSources] = useState<BrowserCookieSource[] | null>(null);
+ const [sourceId, setSourceId] = useState("");
+ const [profileId, setProfileId] = useState("");
+ const [site, setSite] = useState(initialSite);
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState<{ tone: "ok" | "error"; text: string } | null>(null);
+
+ useEffect(() => {
+ if (open) dialog.current?.showModal(); else dialog.current?.close();
+ }, [open]);
+ useEffect(() => {
+ if (!open) return;
+ let live = true;
+ setSources(null);
+ setResult(null);
+ // The site the page showed when the person opened this, not wherever the bot browses on to meanwhile.
+ setSite(opening.current);
+ void (window.ogb?.browserCookies?.sources() ?? Promise.resolve([])).then((found) => {
+ if (!live) return;
+ setSources(found);
+ setSourceId(found[0]?.id ?? "");
+ setProfileId(found[0]?.profiles[0]?.id ?? "");
+ }, () => { if (live) setSources([]); });
+ return () => { live = false; };
+ }, [open]);
+
+ const source = sources?.find((candidate) => candidate.id === sourceId);
+ const profile = source?.profiles.find((candidate) => candidate.id === profileId);
+ const shownSite = importedSite(site);
+ const ready = Boolean(source && profile && shownSite) && !busy;
+
+ const start = async () => {
+ const bridge = window.ogb?.browserCookies;
+ if (!bridge || !source || !profile) return;
+ setBusy(true);
+ setResult(null);
+ try {
+ const done = await bridge.import({ botId, threadId, site: site.trim(), source: source.id, profile: profile.id });
+ const unread = done.ok ? (done.skipped.protected ?? 0) + (done.skipped.failed ?? 0) : 0;
+ setResult(done.ok
+ ? { tone: "ok", text: t(done.imported === 1 ? "browser.cookieImport.doneOne" : "browser.cookieImport.done", { count: done.imported, site: done.site })
+ + (unread ? ` ${t("browser.cookieImport.partial", { count: unread, browser: source.name })}` : "") }
+ : { tone: "error", text: t(REASONS[done.reason] ?? "browser.cookieImport.reason.unreadable", { browser: source.name }) });
+ } catch {
+ setResult({ tone: "error", text: t("browser.cookieImport.reason.unreadable", { browser: source.name }) });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <dialog ref={dialog} onClose={onClose} aria-labelledby="cookie-import-title" data-native-view-overlay="" className="m-auto w-[min(420px,calc(100%-32px))] rounded-2xl border border-hairline/50 bg-card p-5 text-ink shadow-2xl backdrop:bg-black/40">
+ <div className="mb-3 flex items-center justify-between">
+ <h2 id="cookie-import-title" className="text-[14px] font-medium">{t("browser.cookieImport.title")}</h2>
+ <button type="button" className={button} aria-label={t("common.close")} onClick={onClose}><X size={16} /></button>
+ </div>
+ {sources === null ? (
+ <p className="text-[13px] text-ink-secondary">{t("browser.cookieImport.looking")}</p>
+ ) : sources.length === 0 ? (
+ <p className="text-[13px] text-ink-secondary">{t("browser.cookieImport.none")}</p>
+ ) : (
+ <form className="flex flex-col gap-3" onSubmit={(event) => { event.preventDefault(); if (ready) void start(); }}>
+ <div className="grid grid-cols-2 gap-2">
+ <label className="flex flex-col gap-1 text-[12px] text-ink-secondary">{t("browser.cookieImport.from")}
+ <select className={field} value={sourceId} disabled={busy} onChange={(event) => {
+ const next = sources.find((candidate) => candidate.id === event.target.value);
+ setSourceId(event.target.value);
+ setProfileId(next?.profiles[0]?.id ?? "");
+ }}>
+ {sources.map((candidate) => <option key={candidate.id} value={candidate.id}>{candidate.name}</option>)}
+ </select>
+ </label>
+ <label className="flex flex-col gap-1 text-[12px] text-ink-secondary">{t("browser.cookieImport.profile")}
+ <select className={field} value={profileId} disabled={busy} onChange={(event) => setProfileId(event.target.value)}>
+ {source?.profiles.map((candidate) => <option key={candidate.id} value={candidate.id}>{candidate.name}</option>)}
+ </select>
+ </label>
+ </div>
+ <label className="flex flex-col gap-1 text-[12px] text-ink-secondary">{t("browser.cookieImport.site")}
+ <input className={field} value={site} disabled={busy} spellCheck={false} autoComplete="off" maxLength={253} placeholder="example.com" onChange={(event) => setSite(event.target.value)} />
+ </label>
+ {source && profile && shownSite ? (
+ <p className="text-[12px] text-ink-secondary">{t("browser.cookieImport.confirm", { site: shownSite, browser: source.name, profile: profile.name, name: botName })}</p>
+ ) : null}
+ <p className="text-[12px] text-ink-tertiary">{t("browser.cookieImport.note")}</p>
+ {result ? <p role={result.tone === "error" ? "alert" : "status"} className={result.tone === "error" ? "text-[12px] text-danger" : "text-[12px] text-ink"}>{result.text}</p> : null}
+ <div className="flex justify-end gap-2">
+ <button type="button" className="rounded-lg px-4 py-2 text-[12px] text-ink-secondary hover:bg-inset" onClick={onClose}>{t(result?.tone === "ok" ? "common.close" : "common.cancel")}</button>
+ <button type="submit" disabled={!ready} className="rounded-lg bg-accent px-4 py-2 text-[12px] text-accent-ink disabled:opacity-40">{busy ? t("browser.cookieImport.importing") : t("browser.cookieImport.import")}</button>
+ </div>
+ </form>
+ )}
+ </dialog>
+ );
+}
diff --git a/src/components/browser/MoreMenu.tsx b/src/components/browser/MoreMenu.tsx
index d3ef6887b2..692491cecb 100644
--- a/src/components/browser/MoreMenu.tsx
+++ b/src/components/browser/MoreMenu.tsx
@@ -30,7 +30,7 @@ const sameSetting = (a: PreviewViewportSetting, b: PreviewViewportSetting) =>
const item = "flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left hover:bg-inset disabled:cursor-not-allowed disabled:opacity-40";
const small = "rounded-md border border-hairline p-1 text-ink-secondary hover:bg-inset hover:text-ink disabled:opacity-40";
-export function MoreMenu({ stream, ready, typing, setting, zoom, pip, onViewport, onZoom, onPip, onType, onSecret, onReconnect, onRestart }: {
+export function MoreMenu({ stream, ready, typing, setting, zoom, pip, onViewport, onZoom, onPip, onType, onSecret, onImport, onReconnect, onRestart }: {
/** Viewport sizes, zoom and picture in picture come with the v2 stream only. */
stream: boolean;
/** The person holds the browser, so its page can be sized and zoomed. */
@@ -45,6 +45,8 @@ export function MoreMenu({ stream, ready, typing, setting, zoom, pip, onViewport
onPip: () => void;
onType: () => void;
onSecret: () => void;
+ /** Only where this app can import a sign-in into this bot's browser. */
+ onImport?: () => void;
onReconnect: () => void;
onRestart: () => void;
}) {
@@ -79,6 +81,7 @@ export function MoreMenu({ stream, ready, typing, setting, zoom, pip, onViewport
{stream && pip ? <button type="button" role="menuitem" className={item} onClick={run(onPip)}>{t(pip.open ? "browser.pip.close" : "browser.pip.open")}</button> : null}
<button type="button" role="menuitem" className={item} disabled={!typing} onClick={run(onType)}>{t("browser.panel.typeTextMenu")}</button>
<button type="button" role="menuitem" className={item} disabled={!typing} onClick={run(onSecret)}>{t("browser.typeSecret")}</button>
+ {onImport ? <button type="button" role="menuitem" className={item} onClick={run(onImport)}>{t("browser.cookieImport.menu")}</button> : null}
</>)}
{section(<>
<button type="button" role="menuitem" className={item} onClick={run(onReconnect)}>{t("browser.panel.reconnectView")}</button>
diff --git a/src/locales/en.json b/src/locales/en.json
index 363192064b..37fea3fd9c 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -11405,5 +11405,30 @@
"changes.tooLarge": "These files are too large to compare here (each up to 2 MB and 20,000 sentences).",
"changes.notText": "One of these files isn't plain text.",
"changes.refused": "Couldn't open a file to compare: {reason}",
- "changes.coarse": "Some long stretches differ too much to match sentence by sentence; they show as removed and added."
+ "changes.coarse": "Some long stretches differ too much to match sentence by sentence; they show as removed and added.",
+ "browser.cookieImport.menu": "Import a sign-in…",
+ "browser.cookieImport.title": "Import a sign-in",
+ "browser.cookieImport.looking": "Looking for your browsers…",
+ "browser.cookieImport.none": "No browser with sign-ins was found on this computer.",
+ "browser.cookieImport.from": "From",
+ "browser.cookieImport.profile": "Profile",
+ "browser.cookieImport.site": "Site",
+ "browser.cookieImport.confirm": "Copies your sign-in for {site} from {browser} ({profile}) into {name}'s browser.",
+ "browser.cookieImport.note": "Only this site is copied. Google sign-ins are never copied: use My Chrome for Google.",
+ "browser.cookieImport.import": "Import",
+ "browser.cookieImport.importing": "Importing…",
+ "browser.cookieImport.done": "Imported {count} cookies for {site}.",
+ "browser.cookieImport.doneOne": "Imported 1 cookie for {site}.",
+ "browser.cookieImport.reason.notASite": "That is not a site. Enter a site such as example.com.",
+ "browser.cookieImport.reason.google": "Google sign-ins can't be copied: Google ties them to the browser they were made in. Use My Chrome for Google.",
+ "browser.cookieImport.reason.noSource": "{browser} or that profile is no longer on this computer.",
+ "browser.cookieImport.reason.keyDenied": "{browser}'s key was not given. Try again and choose Allow when your computer asks.",
+ "browser.cookieImport.reason.fullDiskAccess": "Safari's sign-ins need Full Disk Access for this app: turn it on in System Settings → Privacy & Security, then try again.",
+ "browser.cookieImport.reason.appBound": "{browser} keeps its sign-ins to itself on this computer. Use My Chrome instead.",
+ "browser.cookieImport.reason.locked": "{browser} is using its files. Quit {browser}, then try again.",
+ "browser.cookieImport.reason.unreadable": "Couldn't read {browser}'s sign-ins.",
+ "browser.cookieImport.reason.nothingFound": "{browser} has no sign-in for that site.",
+ "browser.cookieImport.reason.noDestination": "This bot's browser can't take an imported sign-in.",
+ "botSettings.simple.importLogin": "Import sign-in from your browser",
+ "browser.cookieImport.partial": "{count} more couldn't be read from {browser}."
}
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 86e872de98..dfb13258b3 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -11405,5 +11405,30 @@
"changes.tooLarge": "Estes arquivos são grandes demais para comparar aqui (até 2 MB e 20.000 frases cada).",
"changes.notText": "Um destes arquivos não é texto simples.",
"changes.refused": "Não foi possível abrir um arquivo para comparar: {reason}",
- "changes.coarse": "Alguns trechos longos diferem demais para alinhar frase por frase; aparecem como removidos e adicionados."
+ "changes.coarse": "Alguns trechos longos diferem demais para alinhar frase por frase; aparecem como removidos e adicionados.",
+ "browser.cookieImport.menu": "Importar um login…",
+ "browser.cookieImport.title": "Importar um login",
+ "browser.cookieImport.looking": "Procurando seus navegadores…",
+ "browser.cookieImport.none": "Nenhum navegador com logins foi encontrado neste computador.",
+ "browser.cookieImport.from": "De",
+ "browser.cookieImport.profile": "Perfil",
+ "browser.cookieImport.site": "Site",
+ "browser.cookieImport.confirm": "Copia seu login de {site} do {browser} ({profile}) para o navegador de {name}.",
+ "browser.cookieImport.note": "Só este site é copiado. Logins do Google nunca são copiados: use o Meu Chrome para o Google.",
+ "browser.cookieImport.import": "Importar",
+ "browser.cookieImport.importing": "Importando…",
+ "browser.cookieImport.done": "{count} cookies importados para {site}.",
+ "browser.cookieImport.doneOne": "1 cookie importado para {site}.",
+ "browser.cookieImport.reason.notASite": "Isso não é um site. Digite um site como exemplo.com.",
+ "browser.cookieImport.reason.google": "Logins do Google não podem ser copiados: o Google os prende ao navegador em que foram feitos. Use o Meu Chrome para o Google.",
+ "browser.cookieImport.reason.noSource": "{browser} ou esse perfil não está mais neste computador.",
+ "browser.cookieImport.reason.keyDenied": "A chave do {browser} não foi liberada. Tente de novo e escolha Permitir quando o computador pedir.",
+ "browser.cookieImport.reason.fullDiskAccess": "Os logins do Safari precisam de Acesso Total ao Disco para este app: ative em Ajustes do Sistema → Privacidade e Segurança e tente de novo.",
+ "browser.cookieImport.reason.appBound": "{browser} guarda os logins só para si neste computador. Use o Meu Chrome.",
+ "browser.cookieImport.reason.locked": "{browser} está usando os próprios arquivos. Feche o {browser} e tente de novo.",
+ "browser.cookieImport.reason.unreadable": "Não foi possível ler os logins do {browser}.",
+ "browser.cookieImport.reason.nothingFound": "{browser} não tem login para esse site.",
+ "browser.cookieImport.reason.noDestination": "O navegador deste bot não aceita um login importado.",
+ "botSettings.simple.importLogin": "Importar login do seu navegador",
+ "browser.cookieImport.partial": "Outros {count} não puderam ser lidos do {browser}."
}
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 46a4e2ca4d..0269896a90 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -4061,7 +4061,9 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a",
+ "server.runs.lentComputerUnconfirmed": "1e3890ae479bf06665656bc77dbe8b5128fc2a79ff579feb66b3e8203e325617"
},
"es": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -10480,7 +10482,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"fr": {
"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",
@@ -14308,7 +14311,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"hi": {
"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",
@@ -17990,7 +17994,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"ja": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -25949,7 +25954,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"pt-br": {
"voice.gemini.keyPlaceholder": "8c87ba2043a4a89d63c90cae8a6dafd5cbd193652e923b97988e381a74773e10",
@@ -37269,7 +37275,42 @@
"chat.notice.waitingPasswordElsewhere": "97cacd0a74d5204ef08cc8bc8e98a7510c0b4cc40e43a828e09c6ec945f868f2",
"chat.notice.waitingSignInElsewhere": "23128dfa673a206b5bdbebc2d7c667b294214c38b5c4d848f2efc7abfa40927b",
"chat.notice.waitingConnectElsewhere": "ea42fbcab6227c96875c990433e140b7dcec434b3431efe9edd4788925b596fb",
- "chat.notice.waitingReviewElsewhere": "bacacf6c5c87a709dce2c839ac18a57a7f87bc7f52b4afa2ab161ffb8bca66c7"
+ "chat.notice.waitingReviewElsewhere": "bacacf6c5c87a709dce2c839ac18a57a7f87bc7f52b4afa2ab161ffb8bca66c7",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a",
+ "server.runs.lentComputerUnconfirmed": "1e3890ae479bf06665656bc77dbe8b5128fc2a79ff579feb66b3e8203e325617",
+ "rail.makeHomeDataStays": "5674f7b8425f7a22d2fbbc90af3aeeb87d7f8426321960440307eb62c01b46b7",
+ "cloudSend.dataStays": "cd496182d5c1b8ca853ea48a1c57870e81adc58646e2049817c6c1dd6436967f",
+ "cloudSend.botMove.dataStays": "ac2394f2667c01fa362e1b25b5e8327116911ea2792da0db3345e346cec0aa7f",
+ "teamMove.dataStays": "96d2a93069871c6951bca2ece664d471960cbf9fc2009624da380d93b14f085a",
+ "serverError.backup.dataQueryRunning": "b412ac7ec19b026c4677d0f5697a2e1e74256a2f51cbeacd2b109c30bc696faf",
+ "serverError.backup.dataCloseFailed": "de031917c6f9b852e0941933ab277d9be4a7a677d04c5dfcff17501f1fe71d5e",
+ "serverError.backup.tooLargeData": "71d051039603fac5c541ff4c7eefbe1defdfc96948efc52860a7e59ba84f8752",
+ "serverError.backup.legacyBursts": "3cad10f97da5ce398204d1e6e483537605b1e874f4147a7e92e1e7263b5ae830",
+ "browser.cookieImport.menu": "393a0a0bd0eba38d5aea0fb392d54ea177c5cb56de4fa12f86d1eb077c252c27",
+ "browser.cookieImport.title": "688a8f9fd53e9ab8e96db962b701f756c592f6c1794d4d03642ca20e78b3db36",
+ "browser.cookieImport.looking": "59ef175b95db3ee77778799a1f91fe85945500425946502e894594063f74505b",
+ "browser.cookieImport.none": "1c122d81549bd0baf0cbafa6eec3a16451e2af75d2f857e9273d111302b2f9f7",
+ "browser.cookieImport.from": "218197693424e0154cefc0af31aed96c084b987e08136e91d5528ddbb5461e24",
+ "browser.cookieImport.profile": "d696a35bdd1883da07a8d6c41bb7a3153381b23aa197629ee273479a6eaa5a9c",
+ "browser.cookieImport.site": "fa7955814e32aed3a240ee46fcd053dd48f320d4e6e18d2b2774e491c5f75834",
+ "browser.cookieImport.confirm": "2eaef79903c000d5cc9f169fa811857b37f457908ae61b6fef2bcc2eba344d2f",
+ "browser.cookieImport.note": "bca8f0baccab08e66e371394dd5899fc8551640ac9b6fa5232368827a9df371e",
+ "browser.cookieImport.import": "2cff9baabf56ca002610e113bc94deb6ededddfc3c130365b6e88ed5195bf774",
+ "browser.cookieImport.importing": "c01c4324f1fa14fc76957936626e11a5150c24e748dbd08cc46848dfcbe37d00",
+ "browser.cookieImport.done": "e9a093bec27bf9c8ce5d8ede7a54a4aabc9a0fa7a8c5d76f8c991280115fe24b",
+ "browser.cookieImport.doneOne": "deeb5afe468b1c44f745bff78911a395a5837ba659581b8f02a4b4b909eea9f8",
+ "browser.cookieImport.reason.notASite": "f1c64ebf4386ed3de6cf47e7a7664f822fe40fb4524b1581ff7fc8ce7900f9ab",
+ "browser.cookieImport.reason.google": "e8d66781ea6d5fdbedaddcc97987ebd7abd008f502786ee348f1f3a91f993dc2",
+ "browser.cookieImport.reason.noSource": "cf5bf8a7df1099e11b35a2c015c92e4ee02c487d905a48a0ae5d08408b585a6a",
+ "browser.cookieImport.reason.keyDenied": "64ded3e8fd20e93b1ec9e40745610066e29c00d73ffe6a10b837a10f7eab05b4",
+ "browser.cookieImport.reason.fullDiskAccess": "bb068c36b5463e445b936a3ad6e19063ee4243499cf305ba7cb264165426aeac",
+ "browser.cookieImport.reason.appBound": "6276c9568cb5f01108f48970e16e4aec7627f23bd253e1c501938dabe0cd3705",
+ "browser.cookieImport.reason.locked": "b31c967ddee7f40667d78d42fa8aaf90f44c0ed2231d4c4c8c8942e3aae58446",
+ "browser.cookieImport.reason.unreadable": "43dc4f5bbfcb4c7389ecae105464fbd0e871edebb379d6d535228cfd52c4f198",
+ "browser.cookieImport.reason.nothingFound": "9b4b57337384c12e96b086bb1753e3389336dbecaf270b6afa6e7bb9cffea995",
+ "browser.cookieImport.reason.noDestination": "84270d33dcd2fac917aecf49c2d827335d5ea084c86733692a2108a2933d560a",
+ "botSettings.simple.importLogin": "da6da406a45e49ce1719c611501ad63bf8fe10e21c574a6c74c8b438aaa3cf01",
+ "browser.cookieImport.partial": "0410655b60eebff8815cad0048dbecd4eac4718f8fdad3985b28b826d52b8975"
},
"zh": {
"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",
@@ -47365,7 +47406,9 @@
"chat.notice.waitingPasswordElsewhere": "97cacd0a74d5204ef08cc8bc8e98a7510c0b4cc40e43a828e09c6ec945f868f2",
"chat.notice.waitingSignInElsewhere": "23128dfa673a206b5bdbebc2d7c667b294214c38b5c4d848f2efc7abfa40927b",
"chat.notice.waitingConnectElsewhere": "ea42fbcab6227c96875c990433e140b7dcec434b3431efe9edd4788925b596fb",
- "chat.notice.waitingReviewElsewhere": "bacacf6c5c87a709dce2c839ac18a57a7f87bc7f52b4afa2ab161ffb8bca66c7"
+ "chat.notice.waitingReviewElsewhere": "bacacf6c5c87a709dce2c839ac18a57a7f87bc7f52b4afa2ab161ffb8bca66c7",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a",
+ "server.runs.lentComputerUnconfirmed": "1e3890ae479bf06665656bc77dbe8b5128fc2a79ff579feb66b3e8203e325617"
},
"zh-tw": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -57560,7 +57603,9 @@
"chat.notice.waitingPasswordElsewhere": "97cacd0a74d5204ef08cc8bc8e98a7510c0b4cc40e43a828e09c6ec945f868f2",
"chat.notice.waitingSignInElsewhere": "23128dfa673a206b5bdbebc2d7c667b294214c38b5c4d848f2efc7abfa40927b",
"chat.notice.waitingConnectElsewhere": "ea42fbcab6227c96875c990433e140b7dcec434b3431efe9edd4788925b596fb",
- "chat.notice.waitingReviewElsewhere": "bacacf6c5c87a709dce2c839ac18a57a7f87bc7f52b4afa2ab161ffb8bca66c7"
+ "chat.notice.waitingReviewElsewhere": "bacacf6c5c87a709dce2c839ac18a57a7f87bc7f52b4afa2ab161ffb8bca66c7",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a",
+ "server.runs.lentComputerUnconfirmed": "1e3890ae479bf06665656bc77dbe8b5128fc2a79ff579feb66b3e8203e325617"
},
"uk": {
"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",
@@ -61662,7 +61707,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"vi": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -67583,7 +67629,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"tr": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -73504,7 +73551,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"pl": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -80626,7 +80674,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"ru": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -87802,7 +87851,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"it": {
"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",
@@ -94790,7 +94840,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
},
"ko": {
"connectedWorkspaces.localTitle": "7d6deafeab011d734c3fdd1bfd6f69544fbb746a004019269bdb48544b01164b",
@@ -102442,7 +102493,8 @@
"decider.provider.line": "b74959fffc682f78c90fde2eb8e8d2c0a40eebac0d11000c8def7ae4db389462",
"computer.worksOnHintServer": "2c3302d501a67067774aedcacfff8d16a80ea8238e2f14d8af97e3fd593f690b",
"composer.dictation.hintKey": "ad34499eb8ecf3174898c031bb1e45b63f46045a1105be0bffafb82368323de9",
- "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645"
+ "server.teammates.noLongerWaiting": "49259fb62a6e8687efa6a6e69da294c81bd67a19c57687d0724ee4bdd5cc4645",
+ "composer.dictation.hint": "0b7004c8459afc3af4f4509f70882ebe107951ac2c21332fe85446cd8674712a"
}
}
}
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index 086edab907..1d6f933d96 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -228,6 +228,8 @@ export interface BrowserEngineSummary {
/** browserEngine.cloudDisplay is on and this server can run it: the panel shows the browser's window as a remote
* desktop (GET /api/bots/:id/browser/desktop), and falls back to the picture view when that closes with 4415. */
desktopView?: true;
+ /** The person can import a site's sign-in from their own browsers into a bot's (the desktop app, Chrome engine). */
+ cookieImport?: true;
/** Self-hosted servers only: whether bots' browsers may open this server's own sites and its local network
* (browserEngine.egress.localNetwork, off by default). Absent on the desktop and on MausBot Cloud. */
serverSites?: boolean;
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 3a9ae83fbb..73acc9eb8d 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -65,6 +65,17 @@ const __APP_VERSION__: string;
};
};
+ interface BrowserCookieSource {
+ id: string;
+ name: string;
+ engine: "chromium" | "firefox" | "safari";
+ profiles: Array<{ id: string; name: string }>;
+ }
+
+ type BrowserCookieImportResult =
+ | { ok: true; site: string; imported: number; sessionOnly: number; skipped: Partial<Record<string, number>> }
+ | { ok: false; reason: string };
+
interface DesktopWorkspaceBounds {
x: number;
y: number;
@@ -447,6 +458,13 @@ const __APP_VERSION__: string;
browserPane?: {
show(input: { botId: string; threadId: string | null; profile: string | null; bounds: DesktopWorkspaceBounds | null; visible: boolean }): Promise<{ shown: boolean }>;
};
+ /** A site's sign-in from the person's own browsers into a bot's browser, which the person starts. Counts and a
+ * reason code come back, never a cookie. `offer` says whether a site can be imported for a bot (Google never). */
+ browserCookies?: {
+ sources(): Promise<BrowserCookieSource[]>;
+ offer(input: { botId: string; threadId: string | null; site: string }): Promise<{ offered: boolean; reason?: string }>;
+ import(input: { botId: string; threadId: string | null; site: string; source: string; profile: string }): Promise<BrowserCookieImportResult>;
+ };
/** Native folder picker; resolves null when the user cancels. */
pickFolder?(current?: string): Promise<string | null>;
/** Writes the redacted diagnostics report to a user-chosen file;
diff --git a/third_party/opencode/README.md b/third_party/opencode/README.md
index 0eb4c848a4..705a56d6d2 100644
--- a/third_party/opencode/README.md
+++ b/third_party/opencode/README.md
@@ -5,3 +5,9 @@ of OpenCode's `packages/core/src/models-dev.ts` (lines 160-258) at commit
`2fa3363c924c5c3e367b84a87ae478296a0ed59b`, https://github.com/anomalyco/opencode,
MIT License, Copyright (c) 2025 opencode. The full license text is in
[LICENSE](LICENSE) and at the top of the adapted file.
+
+`server/browser/cookies/` (the sign-in import from installed browsers) adapts OpenCode
+desktop's `packages/gui-plugins/src/browser/profile/` at commit `5ca87b9`: the browser
+table and key lookups of `sources.ts`, the Chromium decryption of `chromium.ts`, the
+readers of `firefox.ts` and `safari.ts`, the database copies of `database.ts` and the
+cookie shape of `cookie.ts`. Same license; each adapted file names its source at the top.
diff --git a/third_party/orca/LICENSE b/third_party/orca/LICENSE
new file mode 100644
index 0000000000..fbf46fc17d
--- /dev/null
+++ b/third_party/orca/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Lovecast Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/third_party/orca/README.md b/third_party/orca/README.md
new file mode 100644
index 0000000000..d3611802be
--- /dev/null
+++ b/third_party/orca/README.md
@@ -0,0 +1,7 @@
+# Orca
+
+`server/browser/cookies/policy.ts` adapts the list of Google cookies that are never
+imported from Orca's `src/main/browser/cookies/policy/cookie-import-exclusions.ts` at
+commit `ffadf731`, https://github.com/stablyai/orca, MIT License, Copyright (c) 2026
+Lovecast Inc. The full license text is in [LICENSE](LICENSE) and is named at the top
+of the adapted file.