Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Let the desktop app import cookies into a Bot's browser

Fei2411c40ee98bdd7a
diff --git a/.gitattributes b/.gitattributes
index 477c9a46..b56425d8 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,2 +1,5 @@
# Shell scripts are copied into the Docker image as they are; CRLF breaks them.
*.sh text eol=lf
+
+# Cookie fixtures test BOM and line-ending variants; normalizing them removes what they test.
+app/test/fixtures/** -text
diff --git a/app/README.md b/app/README.md
index 0fd0bbe0..71bc0509 100644
--- a/app/README.md
+++ b/app/README.md
@@ -110,8 +110,9 @@ The script serves a releases list with one release of that version that has this
|---|---|
| `src/main.mjs` | Main process: one instance, the window, which loads the Host's loopback address as DSH Web does, and the sign-in page DSH opens, which goes to the system browser |
| `src/host-port.mjs` | The Host's port, kept between starts, since the page keeps its storage per address |
-| `src/preload.cjs` | Hands DS Bot's settings the data location and its move, and DS Bot's Bot browsers their webview leases. On Windows it marks the page for the frameless window and sends the caption buttons the colors of the surface under them |
+| `src/preload.cjs` | Hands DS Bot's settings the data location and its move, and DS Bot's Bot browsers their webview leases and cookie imports. On Windows it marks the page for the frameless window and sends the caption buttons the colors of the surface under them |
| `src/bot-browser.mjs` | The Bot browsers' webviews: only a leased one attaches, with fixed preferences; each Bot's logins stay on disk until the Bot is deleted; pages cannot reach the Host |
+| `src/cookie-parse.mjs`, `src/cookie-import.mjs`, `src/browser-sources.mjs` | Cookie imports: the cookie-file parser (Cookie-Editor JSON, Netscape, Playwright storageState), the write into a Bot's partition with read-back and flush, and the installed-browser profiles a source is cloned from — the source browser itself decrypts its own store over a CDP pipe; values never leave the main process |
| `src/window-frame.mjs`, `src/mica.css` | The frameless Windows window: the caption band, when Mica is available (Windows 11 22H2 and later), and the stylesheet that lets Mica through the sidebar |
| `src/host-process.mjs` | Starts the Host in Electron's Node mode and owns its exit |
| `src/host.mjs` | The Host: boots the profile with `runProfile()` and reports the launch URL and the page injections; for the first-run check (`DS_BOT_CHECK`), the chats it cannot read |
diff --git a/app/src/browser-sources.mjs b/app/src/browser-sources.mjs
new file mode 100644
index 00000000..9e7cd022
--- /dev/null
+++ b/app/src/browser-sources.mjs
@@ -0,0 +1,471 @@
+// Import cookies from a browser installed on this machine — ego-lite's idea adapted to an app
+// that is not its own Chromium: copy the profile's cookie files into a throwaway user-data-dir,
+// launch the source browser's own binary on that copy and let IT decrypt; the app only reads
+// plain cookies back over a debugging pipe. The real profile is never modified, and on Windows
+// a running source holds its cookie store locked, so it has to close (and is restarted with its
+// session) before the copy can happen. Firefox keeps cookies in plain sqlite, no launch needed.
+import { spawn, execFile } from 'node:child_process'
+import { existsSync, mkdirSync, readFileSync } from 'node:fs'
+import { copyFile, mkdtemp, readdir, readFile, rm } from 'node:fs/promises'
+import { DatabaseSync } from 'node:sqlite'
+import { homedir, platform, tmpdir } from 'node:os'
+import { basename, dirname, join } from 'node:path'
+
+// Kinds we can harvest: Chromium-family through their own exe, Firefox through its plain db.
+const KIND_ORDER = ['chrome', 'edge', 'brave', 'chromium', 'firefox']
+
+// ------------------------------------------------------------------ installed binaries
+
+const VERSION_DIR = /^\d+\.\d+\.\d+\.\d+$/
+
+function kindOfExe(exePath) {
+ const p = exePath.toLowerCase().replace(/\//g, '\\')
+ const base = basename(p)
+ if (base.startsWith('firefox')) return 'firefox'
+ if (base === 'msedge.exe' || p.includes('microsoft edge') || p.includes('microsoft-edge')) return 'edge'
+ if (p.includes('brave')) return 'brave'
+ if (p.includes('chromium')) return 'chromium'
+ if (p.includes('chrome')) return 'chrome'
+ return null
+}
+
+async function exeVersion(exePath) {
+ // The version-named folder next to the exe; `--version` would open a window in a running browser.
+ try {
+ const names = await readdir(dirname(exePath))
+ return names.filter((n) => VERSION_DIR.test(n)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).at(-1) ?? null
+ } catch { return null }
+}
+
+function regQuery(key, view) {
+ return new Promise((resolve) => {
+ execFile('reg', ['query', key, '/ve', `/reg:${view}`], { encoding: 'buffer', windowsHide: true, timeout: 10_000 }, (err, stdout) => {
+ if (err || !stdout) return resolve(null)
+ const m = stdout.toString('utf8').match(/REG_(?:EXPAND_)?SZ\s+(.+?)\s*$/m)
+ resolve(m ? m[1].replace(/^"|"$/g, '').replace(/%([^%]+)%/g, (all, name) => process.env[name] ?? all) : null)
+ })
+ })
+}
+
+function exeCandidates() {
+ const home = homedir()
+ if (platform() === 'win32') {
+ const roots = [process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.LOCALAPPDATA].filter(Boolean)
+ const rels = [
+ 'Google\\Chrome\\Application\\chrome.exe', 'Microsoft\\Edge\\Application\\msedge.exe',
+ 'BraveSoftware\\Brave-Browser\\Application\\brave.exe', 'Chromium\\Application\\chrome.exe',
+ 'Mozilla Firefox\\firefox.exe',
+ ]
+ return roots.flatMap((r) => rels.map((rel) => join(r, rel)))
+ }
+ if (platform() === 'darwin') {
+ const apps = [
+ 'Google Chrome.app/Contents/MacOS/Google Chrome', 'Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
+ 'Brave Browser.app/Contents/MacOS/Brave Browser', 'Chromium.app/Contents/MacOS/Chromium',
+ 'Firefox.app/Contents/MacOS/firefox',
+ ]
+ return ['/Applications', join(home, 'Applications')].flatMap((d) => apps.map((a) => join(d, a)))
+ }
+ return [
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/opt/google/chrome/chrome',
+ '/usr/bin/microsoft-edge', '/usr/bin/microsoft-edge-stable', '/opt/microsoft/msedge/msedge',
+ '/usr/bin/brave-browser', '/usr/bin/brave', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+ '/usr/bin/firefox', '/usr/lib/firefox/firefox', '/snap/bin/firefox',
+ ]
+}
+
+/** → Map<kind, { exe, version }> of installed browsers. */
+export async function findBrowserExes() {
+ const candidates = exeCandidates()
+ if (platform() === 'win32') {
+ for (const exe of ['chrome.exe', 'msedge.exe', 'brave.exe', 'firefox.exe']) {
+ for (const hive of ['HKLM', 'HKCU']) {
+ for (const view of ['64', '32']) {
+ const path = await regQuery(`${hive}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${exe}`, view)
+ if (path) candidates.unshift(path)
+ }
+ }
+ }
+ }
+ const found = new Map()
+ for (const path of candidates) {
+ const kind = kindOfExe(path)
+ if (!kind || found.has(kind)) continue
+ try {
+ const real = await (await import('node:fs/promises')).realpath(path)
+ if (existsSync(real)) found.set(kind, { exe: real, version: await exeVersion(real) })
+ } catch { /* not installed */ }
+ }
+ return found
+}
+
+// ------------------------------------------------------------------ profile enumeration
+
+function userDataRoots() {
+ const local = process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')
+ const roaming = process.env.APPDATA ?? join(homedir(), 'AppData', 'Roaming')
+ const home = homedir()
+ if (platform() === 'win32') {
+ return {
+ chrome: [join(local, 'Google', 'Chrome', 'User Data')],
+ edge: [join(local, 'Microsoft', 'Edge', 'User Data')],
+ brave: [join(local, 'BraveSoftware', 'Brave-Browser', 'User Data')],
+ chromium: [join(local, 'Chromium', 'User Data')],
+ firefox: [join(roaming, 'Mozilla', 'Firefox')],
+ }
+ }
+ if (platform() === 'darwin') {
+ const appSupport = join(home, 'Library', 'Application Support')
+ return {
+ chrome: [join(appSupport, 'Google', 'Chrome')],
+ edge: [join(appSupport, 'Microsoft Edge')],
+ brave: [join(appSupport, 'BraveSoftware', 'Brave-Browser')],
+ chromium: [join(appSupport, 'Chromium')],
+ firefox: [join(appSupport, 'Firefox')],
+ }
+ }
+ const config = process.env.XDG_CONFIG_HOME ?? join(home, '.config')
+ return {
+ chrome: [join(config, 'google-chrome'), join(config, 'google-chrome-beta')],
+ edge: [join(config, 'microsoft-edge'), join(config, 'microsoft-edge-beta')],
+ brave: [join(config, 'BraveSoftware', 'Brave-Browser')],
+ chromium: [join(config, 'chromium')],
+ firefox: [join(home, '.mozilla', 'firefox')],
+ }
+}
+
+function readJson(path) {
+ try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return null }
+}
+
+/** Chromium profiles under one user-data root: `info_cache` names + a scan for Network/Cookies. */
+export async function chromiumProfiles(root) {
+ const names = new Map()
+ for (const [dir, info] of Object.entries(readJson(join(root, 'Local State'))?.profile?.info_cache ?? {})) {
+ names.set(dir, info?.name || info?.gaia_name || dir)
+ }
+ let dirs = []
+ try { dirs = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name) } catch { return [] }
+ const profiles = []
+ for (const dir of dirs) {
+ if (dir === 'System Profile' || dir === 'Guest Profile') continue
+ const cookieDb = join(root, dir, 'Network', 'Cookies')
+ const legacy = join(root, dir, 'Cookies')
+ const hasCookies = existsSync(cookieDb) || existsSync(legacy)
+ if (!hasCookies && !names.has(dir)) continue
+ profiles.push({ dir, name: names.get(dir) ?? dir, cookieDb: existsSync(cookieDb) ? cookieDb : legacy, hasCookies })
+ }
+ profiles.sort((a, b) => (a.dir === 'Default' ? -1 : b.dir === 'Default' ? 1 : a.dir.localeCompare(b.dir, undefined, { numeric: true })))
+ return profiles
+}
+
+/** Firefox profiles from profiles.ini (sections ProfileN with Path/IsRelative/Default). */
+export async function firefoxProfiles(root) {
+ let text
+ try { text = await readFile(join(root, 'profiles.ini'), 'utf8') } catch { return [] }
+ const profiles = []
+ let current = null
+ for (const line of text.split(/\r?\n/)) {
+ const section = line.match(/^\[(.+)\]$/)
+ if (section) {
+ if (current?.path) profiles.push(current)
+ current = /^Profile\d+$/i.test(section[1]) ? { path: null, name: null, relative: true } : null
+ continue
+ }
+ if (!current) continue
+ const m = line.match(/^([^=]+)=(.*)$/)
+ if (!m) continue
+ const [, key, value] = m
+ if (key === 'Path') current.path = value.trim()
+ else if (key === 'Name') current.name = value.trim()
+ else if (key === 'IsRelative') current.relative = value.trim() !== '0'
+ }
+ if (current?.path) profiles.push(current)
+ return profiles
+ .map((p) => {
+ const dir = p.relative ? join(root, p.path) : p.path
+ return { dir, path: dir, name: p.name ?? basename(dir), hasCookies: existsSync(join(dir, 'cookies.sqlite')) }
+ })
+ .filter((p) => p.hasCookies || p.name)
+}
+
+const BROWSER_NAME = { chrome: 'Chrome', edge: 'Edge', brave: 'Brave', chromium: 'Chromium', firefox: 'Firefox' }
+
+/**
+ * Every importable profile on this machine.
+ * → [{ id, kind, label, engine:'chromium'|'firefox', profilePath, cookieDb, hasCookies, exe, exeVersion }]
+ */
+export async function listSources() {
+ const exes = await findBrowserExes()
+ const roots = userDataRoots()
+ const sources = []
+ for (const kind of KIND_ORDER) {
+ const exe = exes.get(kind)
+ // A Chromium profile without its browser cannot self-decrypt; Firefox's db is plain, so it can.
+ if (!exe && kind !== 'firefox') continue
+ for (const root of roots[kind] ?? []) {
+ if (kind === 'firefox') {
+ for (const p of await firefoxProfiles(root)) {
+ if (!p.hasCookies) continue
+ sources.push({
+ id: `firefox:${p.path}`, kind, engine: 'firefox', name: BROWSER_NAME.firefox, label: `${BROWSER_NAME.firefox} — ${p.name}`,
+ profilePath: p.path, cookieDb: join(p.path, 'cookies.sqlite'), hasCookies: true,
+ exe: exe?.exe ?? null, exeVersion: exe?.version ?? null,
+ })
+ }
+ continue
+ }
+ for (const p of await chromiumProfiles(root)) {
+ if (!p.hasCookies) continue
+ sources.push({
+ id: `${kind}:${p.dir}`, kind, engine: 'chromium', name: BROWSER_NAME[kind], label: `${BROWSER_NAME[kind]} — ${p.name}`,
+ profilePath: join(root, p.dir), cookieDb: p.cookieDb, hasCookies: p.hasCookies,
+ exe: exe?.exe ?? null, exeVersion: exe?.version ?? null,
+ })
+ }
+ }
+ }
+ return sources
+}
+
+// ------------------------------------------------------------------ the clone + harvest
+
+const LOCKED = (error) => error?.code === 'EBUSY' || error?.code === 'EPERM'
+
+/** Copy the files a harvest needs into workDir. Throws {code:'locked'} when the source is running. */
+export async function cloneCookieStore(source, workDir) {
+ const jobs = []
+ if (source.engine === 'firefox') {
+ for (const f of ['cookies.sqlite', 'cookies.sqlite-wal', 'cookies.sqlite-shm']) jobs.push({ from: join(source.profilePath, f), to: join(workDir, f), required: f === 'cookies.sqlite' })
+ } else {
+ // The OSCrypt key lives in Local State at the user-data root (the profile dir's parent).
+ const root = dirname(source.profilePath)
+ jobs.push({ from: join(root, 'Local State'), to: join(workDir, 'Local State'), required: true })
+ const profile = basename(source.profilePath)
+ for (const f of ['Cookies', 'Cookies-journal', 'Cookies-wal', 'Cookies-shm']) {
+ jobs.push({ from: join(dirname(source.cookieDb), f), to: join(workDir, profile, 'Network', f), required: f === 'Cookies' })
+ }
+ }
+ const copied = []
+ for (const job of jobs) {
+ try {
+ mkdirSync(dirname(job.to), { recursive: true })
+ await copyFile(job.from, job.to)
+ copied.push(job.from)
+ } catch (error) {
+ if (LOCKED(error)) { const e = new Error('the source browser is running'); e.code = 'locked'; throw e }
+ if (!job.required && error?.code === 'ENOENT') continue
+ if (job.required) throw error
+ }
+ }
+ return copied
+}
+
+/** A fresh throwaway dir for a clone; remove() deletes it. */
+export async function cloneWorkDir() {
+ const dir = await mkdtemp(join(tmpdir(), 'dsb-cookie-import-'))
+ return { dir, remove: () => rm(dir, { recursive: true, force: true, maxRetries: 6, retryDelay: 200 }) }
+}
+
+const QUIET_ARGS = [
+ '--headless', '--no-first-run', '--no-default-browser-check', '--disable-sync',
+ '--disable-background-networking', '--disable-component-update', '--disable-default-apps', '--disable-breakpad',
+]
+
+/** Minimal pipe CDP: commands on fd 3, events on fd 4, JSON + NUL. */
+function pipeConnection(child) {
+ const writer = child.stdio[3]
+ const reader = child.stdio[4]
+ const pending = new Map()
+ let nextId = 1
+ let chunks = []
+ reader.on('data', (buf) => {
+ let start = 0
+ for (;;) {
+ const end = buf.indexOf(0, start)
+ if (end === -1) { if (start < buf.length) chunks.push(buf.subarray(start)); break }
+ chunks.push(buf.subarray(start, end))
+ const text = Buffer.concat(chunks).toString('utf8')
+ chunks = []
+ start = end + 1
+ if (!text) continue
+ let msg
+ try { msg = JSON.parse(text) } catch { continue }
+ if (msg.id !== undefined) {
+ const p = pending.get(msg.id)
+ if (!p) continue
+ pending.delete(msg.id)
+ if (msg.error) { const e = new Error(msg.error.message); e.code = msg.error.code; p.reject(e) }
+ else p.resolve(msg.result)
+ }
+ }
+ })
+ const die = (reason) => {
+ for (const p of pending.values()) { const e = new Error(`CDP pipe closed (${reason})`); e.code = 'PIPE_CLOSED'; p.reject(e) }
+ pending.clear()
+ }
+ reader.on('close', () => die('pipe close'))
+ child.once('exit', (code) => die(`exit ${code}`))
+ return {
+ send(method, params = {}) {
+ const id = nextId++
+ return new Promise((resolve, reject) => {
+ pending.set(id, { resolve, reject })
+ // Chrome's pipe transport frames messages with a trailing NUL.
+ writer.write(`${JSON.stringify({ id, method, params })}\0`)
+ })
+ },
+ }
+}
+
+/** Harvest a Chromium clone: the source's own exe decrypts its cookies for us. */
+async function harvestChromium(source, workDir) {
+ const child = spawn(source.exe, ['--remote-debugging-pipe', `--user-data-dir=${workDir}`, ...QUIET_ARGS, 'about:blank'],
+ { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'], windowsHide: true })
+ await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject) })
+ const browser = pipeConnection(child)
+ const exited = new Promise((resolve) => child.once('exit', resolve))
+ try {
+ const { cookies } = await withTimeout(browser.send('Storage.getCookies'), 20_000, 'Storage.getCookies')
+ return cookies.map(cdpCookie)
+ } finally {
+ browser.send('Browser.close').catch(() => {})
+ const done = await Promise.race([exited, sleepMs(3000).then(() => 'timeout')])
+ if (done === 'timeout') { try { child.kill('SIGKILL') } catch { /* gone */ } await Promise.race([exited, sleepMs(5000)]) }
+ }
+}
+
+function cdpCookie(c) {
+ const cookie = {
+ name: c.name, value: c.value, domain: c.domain, path: c.path || '/',
+ secure: Boolean(c.secure), httpOnly: Boolean(c.httpOnly),
+ }
+ if (c.sameSite === 'Strict' || c.sameSite === 'Lax' || c.sameSite === 'None') cookie.sameSite = c.sameSite
+ if (!c.session && typeof c.expires === 'number' && c.expires > 0) cookie.expires = c.expires
+ if (c.partitionKey && typeof c.partitionKey === 'object' && typeof c.partitionKey.topLevelSite === 'string') {
+ cookie.partitionKey = { topLevelSite: c.partitionKey.topLevelSite, hasCrossSiteAncestor: Boolean(c.partitionKey.hasCrossSiteAncestor) }
+ }
+ return cookie
+}
+
+/** Firefox: cookies.sqlite is plain — read the copied db directly. */
+function harvestFirefox(workDir, now = Date.now() / 1000) {
+ const db = new DatabaseSync(join(workDir, 'cookies.sqlite'), { readOnly: true })
+ try {
+ const rows = db.prepare('SELECT host, name, value, path, isHttpOnly, isSecure, expiry, sameSite, rawSameSite, originAttributes FROM moz_cookies').all()
+ const cookies = []
+ const skipped = []
+ rows.forEach((row, index) => {
+ if (row.expiry <= now) { skipped.push({ where: `entry ${index + 1}`, name: row.name, domain: row.host, code: 'expired', reason: 'already expired' }); return }
+ // nsICookie: SAMESITE_UNSET 0, LAX 1, STRICT 2, NONE 3 (sameSite column, rawSameSite as fallback)
+ const ss = { 1: 'Lax', 2: 'Strict', 3: 'None' }[row.sameSite ?? row.rawSameSite] ?? undefined
+ const cookie = { name: row.name, value: row.value ?? '', domain: row.host, path: row.path || '/', secure: !!row.isSecure, httpOnly: !!row.isHttpOnly, expires: row.expiry }
+ if (ss) cookie.sameSite = ss
+ if (row.originAttributes && row.originAttributes !== '') {
+ skipped.push({ where: `entry ${index + 1}`, name: row.name, domain: row.host, code: 'container', reason: `a Firefox container cookie (${row.originAttributes}); importing it flat would mix it into the default context` })
+ return
+ }
+ cookies.push(cookie)
+ })
+ return { cookies, skipped }
+ } finally { db.close() }
+}
+
+const withTimeout = (p, ms, label) => Promise.race([p, sleepMs(ms).then(() => { throw new Error(`${label} timed out`) })])
+const sleepMs = (ms) => new Promise((r) => setTimeout(r, ms))
+
+/**
+ * Cookies from one source profile. → { cookies, skipped } in the parser's normalized shape.
+ * Throws {code:'locked'} when the source holds its store open (Windows).
+ */
+export async function harvestCookies(source, workDir) {
+ await cloneCookieStore(source, workDir)
+ if (source.engine === 'firefox') return harvestFirefox(workDir)
+ return { cookies: await harvestChromium(source, workDir), skipped: [] }
+}
+
+/**
+ * The whole live import: clone → (close the source on Windows when asked) → harvest → relaunch.
+ * → { running: true } when the source must close first, { running: false, restarted, result }.
+ */
+export async function importFromBrowser(source, { close = false } = {}) {
+ const work = await cloneWorkDir()
+ let closed = false
+ try {
+ try {
+ await cloneCookieStore(source, work.dir)
+ } catch (error) {
+ if (error?.code !== 'locked' || !close) {
+ if (error?.code === 'locked') return { running: true }
+ throw error
+ }
+ const pids = await closeBrowser(source.exe, source)
+ closed = pids.length > 0
+ await cloneCookieStore(source, work.dir) // still locked → throws 'locked' again
+ }
+ const result = await harvestCookies(source, work.dir)
+ return { running: false, restarted: closed, result }
+ } finally {
+ if (closed) relaunchBrowser(source.exe, source.kind)
+ await work.remove().catch(() => {})
+ }
+}
+
+// ------------------------------------------------------------------ closing a running source (Windows)
+
+const powershell = (script) => new Promise((resolve, reject) => {
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true, timeout: 30_000 }, (err, stdout, stderr) => {
+ if (err) reject(new Error(stderr?.trim() || err.message))
+ else resolve(stdout)
+ })
+})
+
+/** Processes (pid + command line) of one exe, Windows only. */
+export async function browserProcesses(exe) {
+ const name = basename(exe)
+ const out = await powershell(
+ `Get-CimInstance Win32_Process -Filter "Name='${name}'" | Where-Object { $_.ExecutablePath -eq '${exe.replace(/'/g, "''")}' } | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`)
+ if (!out.trim()) return []
+ const rows = JSON.parse(out)
+ return (Array.isArray(rows) ? rows : [rows]).map((r) => ({ pid: r.ProcessId, commandLine: r.CommandLine ?? '' }))
+}
+
+const userDataDirOf = (commandLine) => {
+ const m = String(commandLine).match(/--user-data-dir=(?:"([^"]+)"|(\S+))/i)
+ return m ? (m[1] ?? m[2]) : null
+}
+
+/**
+ * Does this process hold the lock on the profile's user-data root? A Chromium instance binds
+ * one user-data-dir: none given = the default root, which is where our sources live.
+ */
+export function locksProfile(process, source) {
+ const dir = userDataDirOf(process.commandLine)
+ if (dir === null) return true // standard invocation binds the standard root
+ const norm = (p) => p.replace(/[\\/]+$/, '').replace(/\//g, '\\').toLowerCase()
+ return norm(dir) === norm(dirname(source.profilePath))
+}
+
+/** Ask a running source browser to quit (graceful; its session comes back on relaunch). */
+export async function closeBrowser(exe, source) {
+ if (platform() !== 'win32') return []
+ const targets = (await browserProcesses(exe)).filter((p) => locksProfile(p, source))
+ if (!targets.length) return []
+ for (const p of targets) {
+ await new Promise((resolve) => execFile('taskkill', ['/PID', String(p.pid)], { windowsHide: true }, () => resolve()))
+ }
+ const deadline = Date.now() + 20_000
+ for (;;) {
+ const alive = (await browserProcesses(exe)).filter((p) => targets.some((t) => t.pid === p.pid))
+ if (!alive.length) return targets.map((t) => t.pid)
+ if (Date.now() > deadline) { const e = new Error('the source browser did not close'); e.code = 'still-running'; throw e }
+ await sleepMs(500)
+ }
+}
+
+/** Reopen a browser we closed, with its previous session. */
+export function relaunchBrowser(exe, kind) {
+ const args = kind === 'firefox' ? [] : ['--restore-last-session']
+ const child = spawn(exe, args, { detached: true, stdio: 'ignore', windowsHide: true })
+ child.unref()
+}
diff --git a/app/src/cookie-import.mjs b/app/src/cookie-import.mjs
new file mode 100644
index 00000000..52a08ed8
--- /dev/null
+++ b/app/src/cookie-import.mjs
@@ -0,0 +1,130 @@
+// Import cookies into a Bot's browser partition. A file or a harvested browser profile is
+// parsed first and held in memory under a pending id (cookie values never leave the main
+// process); the page sees a value-free preview, and applying writes the cookies into the
+// partition's session and verifies what the store actually kept.
+import { randomUUID } from 'node:crypto'
+import { describeCookie, summarizeBySite } from './cookie-parse.mjs'
+
+const PENDING_TTL_MS = 10 * 60_000
+const PENDING_MAX = 16
+
+const SAME_SITE = { Strict: 'strict', Lax: 'lax', None: 'no_restriction' }
+
+/** A normalized cookie → Electron's CookiesSetDetails. */
+export function toSetDetails(cookie) {
+ const host = String(cookie.domain ?? '').replace(/^\.+/, '')
+ const details = {
+ url: `${cookie.secure ? 'https' : 'http'}://${host}${cookie.path || '/'}`,
+ name: cookie.name,
+ value: cookie.value,
+ path: cookie.path || '/',
+ secure: Boolean(cookie.secure),
+ httpOnly: Boolean(cookie.httpOnly),
+ // Electron defaults to 'lax'; 'unspecified' keeps a cookie with no SameSite attribute honest.
+ sameSite: cookie.sameSite ? SAME_SITE[cookie.sameSite] : 'unspecified',
+ }
+ // A leading dot makes it a domain cookie (also sent to subdomains); host-only cookies
+ // carry no domain field and stay on the URL's host.
+ if (String(cookie.domain ?? '').startsWith('.')) details.domain = cookie.domain
+ if (typeof cookie.expires === 'number') details.expirationDate = cookie.expires
+ return details
+}
+
+const keyOf = (c) => `${c.name}${String(c.domain ?? '').replace(/^\.+/, '')}${c.path ?? '/'}`
+
+/**
+ * Write cookies into an Electron session: one `cookies.set` each so a rejected cookie cannot
+ * take the batch down; then a read-back, because a settled promise does not mean the cookie
+ * was stored; then flush, so a crash soon after cannot lose the import.
+ * → { stored, dropped, failed, flushed } with value-free per-item detail.
+ */
+export async function applyCookies(storage, cookies) {
+ const failed = []
+ for (const cookie of cookies) {
+ try {
+ await storage.cookies.set(toSetDetails(cookie))
+ } catch (error) {
+ failed.push({ ...describeCookie(cookie), reason: error?.message ?? String(error) })
+ }
+ }
+ const kept = new Map()
+ for (const stored of await storage.cookies.get({})) kept.set(keyOf(stored), stored)
+ const dropped = []
+ let storedCount = 0
+ for (const cookie of cookies) {
+ if (failed.some((item) => keyOf(item) === keyOf(cookie))) continue
+ if (kept.has(keyOf(cookie))) storedCount += 1
+ else dropped.push({ ...describeCookie(cookie), reason: 'the browser did not store it' })
+ }
+ let flushed = false
+ try { await storage.cookies.flushStore(); flushed = true } catch { /* the store flushes itself within 30 s */ }
+ return { stored: storedCount, dropped, failed, flushed }
+}
+
+/** What the page shows before and after an import — names, domains, paths and flags, never values. */
+export function previewOf(result, source) {
+ return {
+ source,
+ format: result.format ?? null,
+ flavor: result.flavor ?? null,
+ entries: result.entries ?? 0,
+ cookies: result.cookies.length,
+ sites: summarizeBySite(result),
+ warnings: groupBy(result.warnings ?? []),
+ skipped: (result.skipped ?? []).map((item) => ({ where: item.where, name: item.name, domain: item.domain, code: item.code, reason: item.reason })),
+ notes: notesOf(result),
+ }
+}
+
+function notesOf(result) {
+ const notes = []
+ if ((result.cookies ?? []).some((c) => c.expires === undefined)) notes.push('session-cookies')
+ if ((result.info?.localStorageOrigins ?? []).length > 0) notes.push('local-storage-left')
+ return notes
+}
+
+function groupBy(items) {
+ const counts = new Map()
+ for (const item of items) {
+ const k = `${item.code}${item.message}`
+ const entry = counts.get(k)
+ if (entry) entry.count += 1
+ else counts.set(k, { code: item.code, message: item.message, count: 1 })
+ }
+ return [...counts.values()]
+}
+
+/** Parsed imports waiting for the user's confirm: value-bearing, expiring, capped, one-shot. */
+export class CookieImports {
+ #pending = new Map()
+
+ store(result, source) {
+ this.sweep()
+ while (this.#pending.size >= PENDING_MAX) this.#pending.delete(this.#pending.keys().next().value)
+ const id = randomUUID()
+ this.#pending.set(id, { cookies: result.cookies, expiresAt: Date.now() + PENDING_TTL_MS })
+ return { id, preview: previewOf(result, source) }
+ }
+
+ /** The pending import, or null when it is gone or expired. Taking it leaves it for apply/drop. */
+ peek(id) {
+ const entry = this.#pending.get(id)
+ if (!entry) return null
+ if (entry.expiresAt < Date.now()) { this.#pending.delete(id); return null }
+ return entry
+ }
+
+ /** Apply consumes the pending import. */
+ take(id) {
+ const entry = this.peek(id)
+ if (entry) this.#pending.delete(id)
+ return entry
+ }
+
+ drop(id) { this.#pending.delete(id) }
+
+ sweep() {
+ const now = Date.now()
+ for (const [id, entry] of this.#pending) if (entry.expiresAt < now) this.#pending.delete(id)
+ }
+}
diff --git a/app/src/cookie-parse.mjs b/app/src/cookie-parse.mjs
new file mode 100644
index 00000000..cf219301
--- /dev/null
+++ b/app/src/cookie-parse.mjs
@@ -0,0 +1,515 @@
+// Parse an exported cookie file into normalized cookie objects. Node built-ins only; no values
+// ever go into skipped/warning entries or logs (an exported file is a sign-in credential).
+//
+// parseCookieFile(bufferOrString, opts) detects the format from the CONTENT (not the file name):
+// netscape cookies.txt: 7 tab-separated fields, '#HttpOnly_' prefix, '# Netscape HTTP Cookie File' header
+// (curl / wget / yt-dlp / "Get cookies.txt" / Cookie-Editor "Netscape" export)
+// cookie-editor JSON array of browser-extension cookie objects (Cookie-Editor, EditThisCookie, raw chrome.cookies
+// objects). The same parser tolerates Selenium arrays (`expiry`) and CDP / Puppeteer arrays (`expires`).
+// playwright Playwright storageState JSON: { cookies: [...], origins: [...] }
+// and returns
+// { ok, format, flavor, error, encoding, bom, lineEndings, entries, cookies: CookieParam[], skipped, warnings, info }
+//
+// CookieParam = { name, value, domain, path, secure, httpOnly, sameSite?: 'Strict'|'Lax'|'None', expires?: seconds,
+// partitionKey?: { topLevelSite, hasCrossSiteAncestor } }
+// - domain: host without a dot = host-only cookie; '.host' = domain cookie (also sent to subdomains).
+// - expires is omitted for session cookies (CDP treats expires 0 as 1970-01-01, i.e. already expired).
+// `skipped` / `warnings` entries carry { where, name, domain, path, code, reason|message } only — never cookie values.
+
+import { domainToASCII } from 'node:url';
+import { isIP } from 'node:net';
+
+export const FORMATS = ['netscape', 'cookie-editor', 'playwright'];
+
+const CTL_ANY = /[\x00-\x1f\x7f]/;
+const CTL_EXCEPT_TAB = /[\x00-\x08\x0a-\x1f\x7f]/;
+const MAX_NAME_VALUE_BYTES = 4096; // Chrome limit for name + value
+const MAX_ATTR_BYTES = 1024; // Chrome limit for an attribute value (path, domain)
+const DAY = 86400;
+const CHROME_MAX_AGE_DAYS = 400; // Chrome stores at most 400 days of lifetime
+const WEBKIT_EPOCH_OFFSET = 11644473600; // seconds between 1601-01-01 and 1970-01-01
+
+// ------------------------------------------------------------------ decoding
+
+/** Buffer | string → { text, encoding, bom }. Handles UTF-8 BOM, UTF-16 LE/BE (with or without BOM). */
+export function decodeInput(input) {
+ if (typeof input === 'string') {
+ const bom = input.charCodeAt(0) === 0xfeff;
+ return { text: bom ? input.slice(1) : input, encoding: 'string', bom };
+ }
+ const buf = Buffer.isBuffer(input) ? input : Buffer.from(input);
+ if (buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf) {
+ return { text: buf.subarray(3).toString('utf8'), encoding: 'utf-8', bom: true };
+ }
+ if (buf.length >= 2 && buf[0] === 0xff && buf[1] === 0xfe) {
+ return { text: buf.subarray(2).toString('utf16le'), encoding: 'utf-16le', bom: true };
+ }
+ if (buf.length >= 2 && buf[0] === 0xfe && buf[1] === 0xff) {
+ return { text: swap16(buf.subarray(2)).toString('utf16le'), encoding: 'utf-16be', bom: true };
+ }
+ // UTF-16 without BOM: ASCII text has a zero in every second byte.
+ if (buf.length >= 4 && buf[0] !== 0 && buf[1] === 0 && buf[2] !== 0 && buf[3] === 0) {
+ return { text: buf.toString('utf16le'), encoding: 'utf-16le', bom: false };
+ }
+ if (buf.length >= 4 && buf[0] === 0 && buf[1] !== 0 && buf[2] === 0 && buf[3] !== 0) {
+ return { text: swap16(buf).toString('utf16le'), encoding: 'utf-16be', bom: false };
+ }
+ try {
+ return { text: new TextDecoder('utf-8', { fatal: true }).decode(buf), encoding: 'utf-8', bom: false };
+ } catch {
+ return { text: buf.toString('latin1'), encoding: 'latin1 (not valid UTF-8)', bom: false };
+ }
+}
+
+function swap16(buf) {
+ const out = Buffer.alloc(buf.length - (buf.length % 2));
+ for (let i = 0; i + 1 < buf.length; i += 2) { out[i] = buf[i + 1]; out[i + 1] = buf[i]; }
+ return out;
+}
+
+function lineEndingsOf(text) {
+ const crlf = (text.match(/\r\n/g) || []).length;
+ const lf = (text.match(/\n/g) || []).length - crlf;
+ const cr = (text.match(/\r(?!\n)/g) || []).length;
+ const kinds = [crlf && 'CRLF', lf && 'LF', cr && 'CR'].filter(Boolean);
+ return kinds.length === 0 ? 'none' : kinds.length === 1 ? kinds[0] : `mixed (${kinds.join('+')})`;
+}
+
+// ------------------------------------------------------------------ detection
+
+/** → { format, flavor?, data?, error? }. format: one of FORMATS, or 'header-string' | 'invalid-json' | 'unknown-json' | 'empty' | 'unknown'. */
+export function detectFormat(text) {
+ const t = text.replace(/^\uFEFF/, '').trim();
+ if (!t) return { format: 'empty', error: 'the file is empty' };
+ if (t[0] === '[' || t[0] === '{') {
+ let data;
+ try { data = JSON.parse(t); } catch (e) { return { format: 'invalid-json', error: `not valid JSON: ${e.message}` }; }
+ if (Array.isArray(data)) return { format: 'cookie-editor', flavor: jsonFlavor(data), data };
+ if (data && typeof data === 'object' && Array.isArray(data.cookies)) return { format: 'playwright', flavor: 'origins' in data ? 'storageState' : 'object with cookies', data };
+ return { format: 'unknown-json', error: 'JSON, but neither an array of cookies nor an object with a "cookies" array' };
+ }
+ const lines = t.split(/\r\n|\n|\r/);
+ if (/^#\s*(netscape\s+)?http\s+cookie\s+file/i.test(lines[0].trim())) return { format: 'netscape', flavor: 'header' };
+ if (lines.some((l) => /^#HttpOnly_/i.test(l) || (!l.trimStart().startsWith('#') && l.split('\t').length >= 6))) {
+ return { format: 'netscape', flavor: 'no header' };
+ }
+ const one = t.replace(/^cookie:\s*/i, '');
+ if (!one.includes('\n') && /^[^=;\s]+=[^;]*(;\s*[^=;\s]+=[^;]*)*;?$/.test(one)) {
+ return { format: 'header-string', error: 'a Cookie header string ("a=1; b=2") has no domain, path or flags; it needs the site URL to import' };
+ }
+ return { format: 'unknown', error: 'not a known cookie export format (Netscape cookies.txt, JSON cookie array, Playwright storageState)' };
+}
+
+function jsonFlavor(arr) {
+ const objs = arr.filter((x) => x && typeof x === 'object' && !Array.isArray(x)).slice(0, 50);
+ const has = (k) => objs.some((o) => k in o);
+ if (has('hostOnly') || has('storeId') || has('expirationDate')) return 'browser-extension';
+ if (has('expiry')) return 'selenium';
+ if (has('expires') && (has('size') || has('priority') || has('session'))) return 'cdp';
+ return 'generic';
+}
+
+// ------------------------------------------------------------------ entry point
+
+/** Detect the format from the content and parse. opts: { now (seconds), sameSiteNoneInsecure: 'drop-samesite'|'skip'|'keep' } */
+export function parseCookieFile(input, opts = {}) {
+ const dec = decodeInput(input);
+ const det = detectFormat(dec.text);
+ let res;
+ if (det.format === 'netscape') res = parseNetscape(dec.text, opts);
+ else if (det.format === 'cookie-editor') res = parseCookieEditor(det.data, opts);
+ else if (det.format === 'playwright') res = parsePlaywright(det.data, opts);
+ else res = finish(newCtx(det.format, opts), det.error);
+ res.flavor = det.flavor ?? null;
+ res.encoding = dec.encoding;
+ res.bom = dec.bom;
+ res.lineEndings = lineEndingsOf(dec.text);
+ if (dec.encoding.startsWith('latin1')) res.warnings.unshift({ where: 'file', code: 'not-utf8', message: 'the file is not valid UTF-8; read as Latin-1' });
+ return res;
+}
+
+// ------------------------------------------------------------------ Netscape cookies.txt
+
+export function parseNetscape(text, opts = {}) {
+ const ctx = newCtx('netscape', opts);
+ ctx.info.commentLines = 0;
+ ctx.info.blankLines = 0;
+ const lines = String(text).replace(/^\uFEFF/, '').split(/\r\n|\n|\r/);
+ lines.forEach((rawLine, i) => {
+ const where = `line ${i + 1}`;
+ let line = rawLine;
+ if (!line.trim()) { ctx.info.blankLines++; return; }
+ let httpOnly = false;
+ const m = line.match(/^\s*#HttpOnly_/i);
+ if (m) { httpOnly = true; line = line.slice(m[0].length); } else if (line.trimStart().startsWith('#')) { ctx.info.commentLines++; return; }
+
+ ctx.buffer = []; // warnings of this line; dropped if the line is skipped
+ let fields = line.split('\t');
+ if (fields.length < 6) {
+ // Tabs turned into spaces (copy-paste): accept only if the fixed columns still look right.
+ const ws = line.trim().split(/\s+/);
+ const looksLikeCookie = (ws.length === 7 || ws.length === 6) && toBool(ws[1]) !== undefined && toBool(ws[3]) !== undefined && /^-?\d+(\.\d+)?$/.test(ws[4]);
+ if (looksLikeCookie) {
+ fields = ws;
+ warn(ctx, where, { name: ws[5], domain: ws[0] }, 'spaces-not-tabs', 'fields are separated by spaces, not tabs (copy-paste?); read them anyway');
+ } else {
+ ctx.buffer = null;
+ ctx.entries++;
+ skip(ctx, where, {}, 'field-count', `expected 7 tab-separated fields, found ${fields.length}`);
+ return;
+ }
+ }
+ const [domainF, flagF, pathF, secureF, expiryF, nameF] = fields;
+ let value = '';
+ if (fields.length >= 7) value = fields.slice(6).join('\t');
+ const raw = { name: nameF, value, domain: domainF.trim(), path: pathF.trim(), httpOnly };
+ if (fields.length === 6) warn(ctx, where, raw, 'missing-value', 'no value field; using an empty value');
+ if (fields.length > 7) warn(ctx, where, raw, 'tab-in-value', 'more than 7 fields; the extra fields were joined into the value');
+
+ const flag = toBool(flagF);
+ if (flag === undefined) warn(ctx, where, raw, 'bad-subdomain-flag', `include-subdomains flag "${clip(flagF)}" is not TRUE/FALSE; using the leading dot of the domain`);
+ else raw.includeSubdomains = flag;
+ const secure = toBool(secureF);
+ if (secure === undefined) warn(ctx, where, raw, 'bad-secure', `secure flag "${clip(secureF)}" is not TRUE/FALSE; using FALSE`);
+ raw.secure = secure ?? false;
+ raw.expires = expiryF.trim();
+ raw.expiresField = 'expiry';
+ addCookie(ctx, where, raw);
+ });
+ return finish(ctx);
+}
+
+// ------------------------------------------------------------------ JSON cookie array (Cookie-Editor & co.)
+
+export function parseCookieEditor(input, opts = {}) {
+ const ctx = newCtx('cookie-editor', opts);
+ let data = input;
+ if (typeof input === 'string') {
+ try { data = JSON.parse(input.replace(/^\uFEFF/, '')); } catch (e) { return finish(ctx, `not valid JSON: ${e.message}`); }
+ }
+ if (!Array.isArray(data)) return finish(ctx, 'expected a JSON array of cookie objects');
+ const storeIds = new Set();
+ data.forEach((e, i) => {
+ const where = `entry ${i + 1}`;
+ if (!e || typeof e !== 'object' || Array.isArray(e)) { ctx.entries++; skip(ctx, where, {}, 'not-object', 'entry is not an object'); return; }
+ if (e.storeId != null) storeIds.add(String(e.storeId));
+ ctx.buffer = [];
+ if (e.firstPartyDomain) warn(ctx, where, e, 'first-party-domain', 'Firefox first-party-isolation domain ignored');
+ addCookie(ctx, where, rawFromObject(e));
+ });
+ if (storeIds.size > 1) {
+ ctx.warnings.push({ where: 'file', code: 'mixed-stores', message: `cookies from ${storeIds.size} cookie stores are mixed (storeId ${[...storeIds].join(', ')}: e.g. normal + incognito windows or containers)` });
+ }
+ ctx.info.storeIds = [...storeIds];
+ return finish(ctx);
+}
+
+// ------------------------------------------------------------------ Playwright storageState
+
+export function parsePlaywright(input, opts = {}) {
+ const ctx = newCtx('playwright', opts);
+ let data = input;
+ if (typeof input === 'string') {
+ try { data = JSON.parse(input.replace(/^\uFEFF/, '')); } catch (e) { return finish(ctx, `not valid JSON: ${e.message}`); }
+ }
+ if (!data || typeof data !== 'object' || !Array.isArray(data.cookies)) return finish(ctx, 'expected an object with a "cookies" array');
+ data.cookies.forEach((c, i) => {
+ const where = `entry ${i + 1}`;
+ if (!c || typeof c !== 'object' || Array.isArray(c)) { ctx.entries++; skip(ctx, where, {}, 'not-object', 'entry is not an object'); return; }
+ const raw = rawFromObject(c);
+ // Playwright writes partitionKey as the top-level site string plus a non-standard _crHasCrossSiteAncestor.
+ if (typeof c.partitionKey === 'string') raw.partitionKey = { topLevelSite: c.partitionKey, hasCrossSiteAncestor: c._crHasCrossSiteAncestor ?? true };
+ addCookie(ctx, where, raw);
+ });
+ const origins = Array.isArray(data.origins) ? data.origins : [];
+ const withStorage = origins.filter((o) => Array.isArray(o?.localStorage) && o.localStorage.length);
+ ctx.info.origins = origins.length;
+ ctx.info.localStorageOrigins = withStorage.map((o) => ({ origin: String(o.origin), entries: o.localStorage.length }));
+ if (withStorage.length) {
+ ctx.warnings.push({ where: 'origins', code: 'local-storage-not-imported', message: `${withStorage.length} origin(s) with localStorage (${withStorage.reduce((s, o) => s + o.localStorage.length, 0)} entries) were not imported; only cookies are` });
+ }
+ return finish(ctx);
+}
+
+// ------------------------------------------------------------------ shared normalization
+
+/** One JSON cookie object (any of the known spellings) → raw fields for normalizeCookie(). */
+function rawFromObject(e) {
+ // Cookie-Editor / chrome.cookies: expirationDate (s); CDP / Puppeteer / Playwright: expires (s, -1 = session); Selenium: expiry (s)
+ let expires; let expiresField;
+ for (const k of ['expirationDate', 'expires', 'expiry']) {
+ if (e[k] !== undefined && e[k] !== null && e[k] !== '') { expires = e[k]; expiresField = k; break; }
+ }
+ return {
+ name: e.name, value: e.value, domain: e.domain, url: e.url,
+ hostOnly: typeof e.hostOnly === 'boolean' ? e.hostOnly : undefined,
+ path: e.path, secure: e.secure, httpOnly: e.httpOnly, sameSite: e.sameSite,
+ session: typeof e.session === 'boolean' ? e.session : undefined,
+ expires, expiresField, partitionKey: e.partitionKey,
+ hasField: (k) => k in e,
+ };
+}
+
+function newCtx(format, opts) {
+ return {
+ format,
+ now: opts.now ?? Date.now() / 1000,
+ sameSiteNoneInsecure: opts.sameSiteNoneInsecure ?? 'drop-samesite',
+ entries: 0,
+ items: [],
+ skipped: [],
+ warnings: [],
+ info: {},
+ };
+}
+
+function finish(ctx, error = null) {
+ // Duplicates (same name + domain + path) would overwrite each other in Chrome: keep the last one.
+ const byKey = new Map();
+ ctx.items.forEach((it, idx) => {
+ it.idx = idx;
+ const k = `${it.cookie.name}\u0000${it.cookie.domain}\u0000${it.cookie.path}`;
+ if (byKey.has(k)) {
+ warn(ctx, it.where, it.cookie, 'duplicate', `same name/domain/path as ${byKey.get(k).where}; the later entry is used`);
+ }
+ byKey.set(k, it);
+ });
+ const kept = [...byKey.values()].sort((a, b) => a.idx - b.idx);
+ return {
+ ok: !error,
+ format: ctx.format,
+ error,
+ entries: ctx.entries,
+ cookies: kept.map((it) => it.cookie),
+ where: kept.map((it) => it.where),
+ skipped: ctx.skipped,
+ warnings: ctx.warnings,
+ info: ctx.info,
+ };
+}
+
+function warn(ctx, where, raw, code, message) {
+ // While an entry is being read, warnings go to ctx.buffer and are kept only if the entry is imported.
+ (ctx.buffer || ctx.warnings).push({ where, name: strOrNull(raw?.name), domain: strOrNull(raw?.domain), code, message });
+}
+
+function skip(ctx, where, raw, code, reason) {
+ ctx.skipped.push({ where, name: strOrNull(raw?.name), domain: strOrNull(raw?.domain), path: strOrNull(raw?.path), code, reason });
+}
+
+function addCookie(ctx, where, raw) {
+ ctx.entries++;
+ if (!ctx.buffer) ctx.buffer = [];
+ const r = normalizeCookie(raw, ctx, where);
+ const buffered = ctx.buffer;
+ ctx.buffer = null;
+ if (r.skip) skip(ctx, where, raw, r.skip[0], r.skip[1]);
+ else { ctx.items.push({ where, cookie: r.cookie }); ctx.warnings.push(...buffered); }
+}
+
+function normalizeCookie(raw, ctx, where) {
+ const W = (code, msg) => warn(ctx, where, raw, code, msg);
+ const missing = (k) => (raw.hasField ? !raw.hasField(k) : false);
+
+ // --- name / value (Chrome rejects the WHOLE Storage.setCookies call if one cookie is invalid)
+ if (typeof raw.name !== 'string') return { skip: ['bad-name', 'name is missing or not a string'] };
+ let name = raw.name;
+ if (name !== name.trim()) { name = name.trim(); W('trimmed-name', 'whitespace around the name was removed'); }
+ let value = raw.value;
+ if (value === undefined || value === null) { value = ''; W('missing-value', 'no value; using an empty value'); } else if (typeof value === 'number' || typeof value === 'boolean') { value = String(value); W('value-not-string', 'value was not a string; converted'); } else if (typeof value !== 'string') return { skip: ['bad-value', 'value is not a string'] };
+ if (value !== value.trim()) { value = value.trim(); W('trimmed-value', 'whitespace around the value was removed (Chrome rejects it)'); }
+ if (!name && !value) return { skip: ['empty', 'name and value are both empty'] };
+ if (/[;=]/.test(name) || CTL_ANY.test(name)) return { skip: ['bad-char-name', 'name contains ";", "=" or a control character (Chrome would reject the whole import call)'] };
+ if (value.includes(';') || CTL_EXCEPT_TAB.test(value)) return { skip: ['bad-char-value', 'value contains ";" or a control character (Chrome would reject the whole import call)'] };
+ if (Buffer.byteLength(name) + Buffer.byteLength(value) > MAX_NAME_VALUE_BYTES) return { skip: ['too-long', 'name + value is longer than 4096 bytes'] };
+
+ // --- domain and host-only / domain cookie
+ let rawDomain = typeof raw.domain === 'string' ? raw.domain.trim() : '';
+ let url = null;
+ if (!rawDomain && typeof raw.url === 'string' && raw.url) {
+ try { url = new URL(raw.url); } catch { url = null; }
+ if (!url || !/^https?:$/.test(url.protocol)) return { skip: ['bad-url', 'url is not an http(s) URL'] };
+ rawDomain = url.hostname;
+ }
+ if (!rawDomain) return { skip: ['missing-domain', 'domain is missing'] };
+ const dotted = rawDomain.startsWith('.');
+ let host = rawDomain.replace(/^\.+/, '').toLowerCase();
+ if (!host) return { skip: ['bad-domain', 'domain is only dots'] };
+ const ipv6 = /^\[[0-9a-f:.]+\]$/.test(host) && isIP(host.slice(1, -1)) === 6;
+ if (!ipv6) {
+ const ascii = domainToASCII(host);
+ if (!ascii || !/^[a-z0-9._-]+$/.test(ascii) || Buffer.byteLength(ascii) > MAX_ATTR_BYTES) return { skip: ['bad-domain', `"${clip(host)}" is not a valid host name`] };
+ if (ascii !== host) W('punycode', `domain converted to ASCII (${ascii})`);
+ host = ascii;
+ }
+ const ip = ipv6 || isIP(host) !== 0;
+ // Domain cookie (also sent to subdomains) if ANY signal says so; host-only only if none does.
+ const domainSignals = [dotted && 'leading dot', raw.includeSubdomains === true && 'include-subdomains TRUE', raw.hostOnly === false && 'hostOnly false'].filter(Boolean);
+ const hostSignals = [raw.includeSubdomains === false && 'include-subdomains FALSE', raw.hostOnly === true && 'hostOnly true'].filter(Boolean);
+ let domainCookie = domainSignals.length > 0;
+ if (domainCookie && hostSignals.length && !ip) {
+ W('domain-conflict', `${domainSignals.join(' + ')} but ${hostSignals.join(' + ')}: imported as a domain cookie (sent to subdomains too)`);
+ }
+ if (domainCookie && ip) domainCookie = false; // an IP address has no subdomains; Chrome stores it host-only anyway
+ if (domainCookie && !host.includes('.')) return { skip: ['domain-tld', `domain cookie for the top-level name ".${host}" (Chrome would keep it only for the host "${host}"; no site can use it)`] };
+ const domain = domainCookie ? `.${host}` : host;
+
+ // --- path
+ let path = raw.path;
+ if (url && (path === undefined || path === null || path === '')) path = defaultPath(url.pathname);
+ if (path === undefined || path === null || path === '') { path = '/'; W('missing-path', 'no path; using "/"'); } else if (typeof path !== 'string') return { skip: ['bad-path', 'path is not a string'] };
+ path = path.trim();
+ if (!path.startsWith('/')) { W('relative-path', `path "${clip(path)}" does not start with "/"; using "/"`); path = '/'; }
+ if (path.includes(';') || CTL_ANY.test(path)) return { skip: ['bad-char-path', 'path contains ";" or a control character'] };
+ if (Buffer.byteLength(path) > MAX_ATTR_BYTES) return { skip: ['too-long-path', 'path is longer than 1024 bytes'] };
+
+ // --- flags
+ let secure = toBool(raw.secure);
+ if (secure === undefined) {
+ if (url) secure = url.protocol === 'https:';
+ else { if (raw.secure !== undefined && raw.secure !== null) W('bad-secure', `secure "${clip(String(raw.secure))}" is not a boolean; using false`); else if (missing('secure')) W('missing-field', 'no "secure" field; using false'); secure = false; }
+ }
+ let httpOnly = toBool(raw.httpOnly);
+ if (httpOnly === undefined) {
+ if (raw.httpOnly !== undefined && raw.httpOnly !== null) W('bad-httponly', `httpOnly "${clip(String(raw.httpOnly))}" is not a boolean; using false`); else if (missing('httpOnly')) W('missing-field', 'no "httpOnly" field; using false');
+ httpOnly = false;
+ }
+ const ss = normSameSite(raw.sameSite);
+ if (!ss.known) W('bad-samesite', `unknown SameSite "${clip(String(raw.sameSite))}"; left unspecified`);
+ let sameSite = ss.value;
+ if (sameSite === 'None' && !secure) {
+ if (ctx.sameSiteNoneInsecure === 'skip') return { skip: ['samesite-none-insecure', 'SameSite=None without Secure (Chrome refuses to store it)'] };
+ if (ctx.sameSiteNoneInsecure === 'drop-samesite') { sameSite = undefined; W('samesite-none-insecure', 'SameSite=None without Secure: Chrome refuses to store it, so it was imported without SameSite (Chrome default: Lax)'); }
+ }
+
+ // --- cookie name prefixes (Chrome rejects violations, which fails the whole import call)
+ const lname = name.toLowerCase();
+ if (lname.startsWith('__secure-') && !secure) return { skip: ['prefix', '__Secure- cookie without Secure'] };
+ if (lname.startsWith('__host-') && (!secure || domainCookie || path !== '/')) return { skip: ['prefix', '__Host- cookie needs Secure, host-only (no domain) and path "/"'] };
+ if ((lname.startsWith('__http-') || lname.startsWith('__host-http-')) && (!secure || !httpOnly)) return { skip: ['prefix', '__Http- / __Host-Http- cookie needs Secure and HttpOnly'] };
+
+ // --- expiry
+ const ex = normExpiry(raw, W);
+ if (ex.skip) return { skip: ex.skip };
+ if (!ex.session && ex.expires <= ctx.now) return { skip: ['expired', `expired on ${isoDay(ex.expires)}`] };
+ if (!ex.session && ex.expires > ctx.now + CHROME_MAX_AGE_DAYS * DAY) W('over-400-days', `expires ${isoDay(ex.expires)}; Chrome keeps at most 400 days`);
+
+ // --- partition key (CHIPS)
+ let partitionKey;
+ if (raw.partitionKey !== undefined && raw.partitionKey !== null && raw.partitionKey !== '') {
+ const pk = raw.partitionKey;
+ if (pk && typeof pk === 'object' && typeof pk.topLevelSite === 'string' && pk.topLevelSite) {
+ partitionKey = { topLevelSite: pk.topLevelSite, hasCrossSiteAncestor: !!pk.hasCrossSiteAncestor };
+ } else if (typeof pk === 'string') {
+ partitionKey = { topLevelSite: pk, hasCrossSiteAncestor: true };
+ } else W('bad-partition-key', 'partitionKey not understood; imported unpartitioned');
+ if (partitionKey && !secure) return { skip: ['partitioned-insecure', 'partitioned cookie without Secure'] };
+ }
+
+ const cookie = { name, value, domain, path, secure, httpOnly };
+ if (sameSite) cookie.sameSite = sameSite;
+ if (!ex.session) cookie.expires = ex.expires;
+ if (partitionKey) cookie.partitionKey = partitionKey;
+ return { cookie };
+}
+
+function normExpiry(raw, W) {
+ const v = raw.expires;
+ const present = !(v === undefined || v === null || v === '');
+ if (raw.session === true) {
+ if (present && Number(v) > 0) W('session-with-expiry', 'marked as a session cookie but also has an expiry; imported as a session cookie');
+ return { session: true };
+ }
+ if (!present) {
+ if (raw.session === false) W('no-expiry', 'session=false but no expiry; imported as a session cookie');
+ return { session: true };
+ }
+ let n;
+ if (typeof v === 'number') n = v;
+ else if (typeof v === 'string' && /^-?\d+(\.\d+)?$/.test(v.trim())) n = Number(v.trim());
+ else if (typeof v === 'string' && /\d{4}-\d{2}-\d{2}/.test(v) && !Number.isNaN(Date.parse(v))) {
+ n = Date.parse(v) / 1000;
+ W('expiry-date-string', 'expiry was a date string; converted to seconds');
+ } else return { skip: ['bad-expiry', `${raw.expiresField || 'expiry'} "${clip(String(v))}" is not a number or a date`] };
+ if (!Number.isFinite(n)) return { skip: ['bad-expiry', `${raw.expiresField || 'expiry'} is not a finite number`] };
+ if (n <= 0) return { session: true }; // Netscape 0, Playwright / CDP -1, some extension exports 0
+ if (n >= 1e14) {
+ n = n >= 1.1e16 ? n / 1e6 - WEBKIT_EPOCH_OFFSET : n / 1e6;
+ W('expiry-microseconds', 'expiry looked like microseconds; converted to seconds');
+ } else if (n >= 1e11) {
+ n /= 1000;
+ W('expiry-milliseconds', 'expiry looked like milliseconds; converted to seconds');
+ }
+ return { session: false, expires: n };
+}
+
+function normSameSite(v) {
+ if (v === undefined || v === null || v === '') return { value: undefined, known: true };
+ if (typeof v !== 'string') return { value: undefined, known: false };
+ switch (v.trim().toLowerCase().replace(/[\s_-]/g, '')) {
+ case 'strict': return { value: 'Strict', known: true };
+ case 'lax': return { value: 'Lax', known: true };
+ case 'none': case 'norestriction': return { value: 'None', known: true };
+ case 'unspecified': case 'unset': case 'default': return { value: undefined, known: true };
+ default: return { value: undefined, known: false };
+ }
+}
+
+function toBool(v) {
+ if (typeof v === 'boolean') return v;
+ if (v === 1 || v === 0) return v === 1;
+ if (typeof v === 'string') {
+ const s = v.trim().toLowerCase();
+ if (s === 'true' || s === '1') return true;
+ if (s === 'false' || s === '0') return false;
+ }
+ return undefined;
+}
+
+/** RFC 6265 default-path of a request path. */
+function defaultPath(p) {
+ if (!p || !p.startsWith('/')) return '/';
+ const i = p.lastIndexOf('/');
+ return i <= 0 ? '/' : p.slice(0, i);
+}
+
+function strOrNull(x) { return typeof x === 'string' ? x : null; }
+function clip(s, n = 40) { s = String(s ?? ''); return s.length > n ? `${s.slice(0, n)}…` : s; }
+function isoDay(sec) { try { return new Date(sec * 1000).toISOString().slice(0, 10); } catch { return String(sec); } }
+
+// ------------------------------------------------------------------ helpers for reports (no values)
+
+/** Value-free view of a CookieParam or a CDP Network.Cookie. */
+export function describeCookie(c) {
+ const d = { name: c.name, domain: c.domain ?? null, path: c.path ?? null };
+ if (!c.domain && c.url) d.url = c.url;
+ d.secure = !!c.secure;
+ d.httpOnly = !!c.httpOnly;
+ d.sameSite = c.sameSite ?? 'Unspecified';
+ d.session = typeof c.session === 'boolean' ? c.session : !(typeof c.expires === 'number' && c.expires >= 0);
+ if (typeof c.expires === 'number' && c.expires >= 0) d.expires = Math.round(c.expires * 1000) / 1000;
+ for (const k of ['priority', 'sourceScheme', 'sourcePort', 'partitionKey', 'partitionKeyOpaque']) if (c[k] !== undefined) d[k] = c[k];
+ return d;
+}
+
+/** Group cookies by site (domain without the leading dot) for a user-facing summary. */
+export function summarizeBySite(result) {
+ const sites = new Map();
+ const get = (domain) => {
+ const site = String(domain || '(no domain)').replace(/^\./, '');
+ if (!sites.has(site)) sites.set(site, { site, cookies: 0, session: 0, httpOnly: 0, skipped: 0, skippedReasons: {} });
+ return sites.get(site);
+ };
+ for (const c of result.cookies) {
+ const s = get(c.domain);
+ s.cookies++;
+ if (c.expires === undefined) s.session++;
+ if (c.httpOnly) s.httpOnly++;
+ }
+ for (const k of result.skipped) {
+ const s = get(k.domain);
+ s.skipped++;
+ s.skippedReasons[k.code] = (s.skippedReasons[k.code] || 0) + 1;
+ }
+ return [...sites.values()].sort((a, b) => b.cookies - a.cookies || a.site.localeCompare(b.site));
+}
diff --git a/app/src/main.mjs b/app/src/main.mjs
index 1490e758..cbb8e281 100644
--- a/app/src/main.mjs
+++ b/app/src/main.mjs
@@ -3,14 +3,17 @@
// origin as the address the browser comes back to, and accepts only a loopback one.
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
-import { rm } from 'node:fs/promises'
+import { readFile, rm } from 'node:fs/promises'
import { release } from 'node:os'
-import { dirname, isAbsolute, join, resolve } from 'node:path'
+import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { fileURLToPath } from 'node:url'
import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
import electronUpdater from 'electron-updater'
-import { BotBrowserGuests } from './bot-browser.mjs'
+import { BotBrowserGuests, partitionOf } from './bot-browser.mjs'
+import { importFromBrowser, listSources } from './browser-sources.mjs'
+import { applyCookies, CookieImports } from './cookie-import.mjs'
+import { parseCookieFile } from './cookie-parse.mjs'
import { canonicalExecPath } from './canonical-path.mjs'
import { chooseLocations, localeText, programFolder, saveLocations, text } from './first-run.mjs'
import { hostPort } from './host-port.mjs'
@@ -25,7 +28,12 @@ const IPC = {
caption: 'ds-bot:caption-colors', nativeTheme: 'ds-bot:native-theme', fullscreen: 'ds-bot:fullscreen',
dataLocation: 'ds-bot:data-location', moveData: 'ds-bot:move-data', teamWorkspace: 'ds-bot:team-workspace',
browserAcquire: 'ds-bot:browser-acquire', browserRelease: 'ds-bot:browser-release', browserForget: 'ds-bot:browser-forget',
+ browserImportSources: 'ds-bot:browser-import-sources', browserImportPick: 'ds-bot:browser-import-pick',
+ browserImportLive: 'ds-bot:browser-import-live', browserImportApply: 'ds-bot:browser-import-apply',
+ browserImportCancel: 'ds-bot:browser-import-cancel',
}
+// A cookie export larger than this is not a cookie export.
+const IMPORT_FILE_MAX = 32 * 1024 * 1024
const MOVE_PROBLEMS = { drive: 'moveDrive', nested: 'moveNested', workspace: 'moveWorkspace', program: 'inProgram', notEmpty: 'moveNotEmpty' }
const UPDATE_CHECK_WAIT_MS = 15_000
const UPDATE_DOWNLOAD_WAIT_MS = 15 * 60_000
@@ -54,6 +62,7 @@ let choosing
let copying
const copyAbort = new AbortController()
const browserGuests = new BotBrowserGuests({ session, origin: () => origin, devTools: !app.isPackaged })
+const cookieImports = new CookieImports()
// A packaged app started through an 8.3 short path or a junction restarts once on the
// canonical path: the lock below and every path the Host sees then agree with the long
@@ -157,6 +166,49 @@ async function start() {
assertWindow(event)
return browserGuests.forget(event.sender, key)
})
+ // Cookie imports: a file or an installed browser's profile is parsed or harvested into a
+ // pending set first; only apply (the user's confirm) writes into the Bot's partition.
+ ipcMain.handle(IPC.browserImportSources, (event) => {
+ assertWindow(event)
+ return listSources()
+ })
+ ipcMain.handle(IPC.browserImportPick, async (event) => {
+ assertWindow(event)
+ const picked = await dialog.showOpenDialog(mainWindow, {
+ properties: ['openFile'],
+ filters: [{ name: 'Cookie files', extensions: ['txt', 'json', 'cookies'] }, { name: 'All files', extensions: ['*'] }],
+ })
+ if (picked.canceled || !picked.filePaths[0]) return { canceled: true }
+ const buffer = await readFile(picked.filePaths[0])
+ if (buffer.length > IMPORT_FILE_MAX) return { error: 'too-large' }
+ const parsed = parseCookieFile(buffer)
+ if (!parsed.ok) return { error: parsed.error ?? 'unreadable', format: parsed.format }
+ return cookieImports.store(parsed, { kind: 'file', label: basename(picked.filePaths[0]) })
+ })
+ ipcMain.handle(IPC.browserImportLive, async (event, sourceId, close) => {
+ assertWindow(event)
+ const source = (await listSources()).find((item) => item.id === sourceId)
+ if (!source) throw new Error('DeepSeek Bot: an unknown browser profile')
+ const outcome = await importFromBrowser(source, { close: close === true })
+ if (outcome.running) return { running: true, label: source.label, kind: source.kind }
+ const result = {
+ format: 'live', entries: outcome.result.cookies.length + outcome.result.skipped.length,
+ cookies: outcome.result.cookies, skipped: outcome.result.skipped, warnings: [], info: {},
+ }
+ return { ...cookieImports.store(result, { kind: source.kind, label: source.label }), restarted: outcome.restarted }
+ })
+ ipcMain.handle(IPC.browserImportApply, async (event, key, id) => {
+ assertWindow(event)
+ if (typeof key !== 'string' || !key.startsWith('bot:')) throw new Error('DeepSeek Bot: a Bot storage key is required')
+ const pending = cookieImports.take(typeof id === 'string' ? id : '')
+ if (!pending) throw new Error('DeepSeek Bot: this import is no longer pending')
+ const storage = session.fromPartition(partitionOf(key))
+ return applyCookies(storage, pending.cookies)
+ })
+ ipcMain.handle(IPC.browserImportCancel, (event, id) => {
+ assertWindow(event)
+ if (typeof id === 'string') cookieImports.drop(id)
+ })
// The plugin keeps the team workspace; the app remembers it for its own checks.
ipcMain.on(IPC.teamWorkspace, (event, path) => {
if (fixed || !fromWindow(event) || typeof path !== 'string' || !isAbsolute(path)) return
diff --git a/app/src/preload.cjs b/app/src/preload.cjs
index 6993f330..1a83abb5 100644
--- a/app/src/preload.cjs
+++ b/app/src/preload.cjs
@@ -43,6 +43,12 @@ function browserBridge() {
acquire: key => ipcRenderer.invoke('ds-bot:browser-acquire', String(key)),
release: lease => ipcRenderer.invoke('ds-bot:browser-release', String(lease)),
forget: key => ipcRenderer.invoke('ds-bot:browser-forget', String(key)),
+ // Cookie imports, only in the app: sources and a two-step pick/harvest → preview → apply.
+ importSources: () => ipcRenderer.invoke('ds-bot:browser-import-sources'),
+ importPick: () => ipcRenderer.invoke('ds-bot:browser-import-pick'),
+ importLive: (source, close) => ipcRenderer.invoke('ds-bot:browser-import-live', String(source), close === true),
+ importApply: (key, pending) => ipcRenderer.invoke('ds-bot:browser-import-apply', String(key), String(pending)),
+ importCancel: (pending) => ipcRenderer.invoke('ds-bot:browser-import-cancel', String(pending)),
onOpenRequested(lease, listener) {
const id = String(lease)
let set = listeners.get(id)
diff --git a/app/test/browser-sources.test.mjs b/app/test/browser-sources.test.mjs
new file mode 100644
index 00000000..2f68473b
--- /dev/null
+++ b/app/test/browser-sources.test.mjs
@@ -0,0 +1,103 @@
+// Browser profile enumeration (Chromium user-data roots, Firefox profiles.ini), the clone
+// layout a harvest needs, and the process match for closing a running source on Windows.
+import assert from 'node:assert/strict'
+import { existsSync } from 'node:fs'
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import test from 'node:test'
+import { chromiumProfiles, cloneCookieStore, cloneWorkDir, firefoxProfiles, locksProfile } from '../src/browser-sources.mjs'
+
+async function tempRoot() {
+ const dir = await mkdtemp(join(tmpdir(), 'dsb-sources-test-'))
+ return { dir, remove: () => rm(dir, { recursive: true, force: true }) }
+}
+
+test('chromiumProfiles reads info_cache names and skips profiles without cookies', async () => {
+ const root = await tempRoot()
+ try {
+ await mkdir(join(root.dir, 'Default', 'Network'), { recursive: true })
+ await writeFile(join(root.dir, 'Default', 'Network', 'Cookies'), 'x')
+ await mkdir(join(root.dir, 'Profile 1', 'Network'), { recursive: true })
+ await writeFile(join(root.dir, 'Profile 1', 'Network', 'Cookies'), 'x')
+ await mkdir(join(root.dir, 'Profile 2'), { recursive: true }) // no cookie db: not listed
+ await mkdir(join(root.dir, 'System Profile', 'Network'), { recursive: true })
+ await writeFile(join(root.dir, 'System Profile', 'Network', 'Cookies'), 'x')
+ await writeFile(join(root.dir, 'Local State'), JSON.stringify({
+ profile: { info_cache: { Default: { name: 'Person 1' }, 'Profile 1': { name: 'Work' } } },
+ }))
+ const profiles = await chromiumProfiles(root.dir)
+ assert.deepEqual(profiles.map((p) => p.dir), ['Default', 'Profile 1'])
+ assert.deepEqual(profiles.map((p) => p.name), ['Person 1', 'Work'])
+ assert.equal(profiles[0].cookieDb, join(root.dir, 'Default', 'Network', 'Cookies'))
+ assert.equal(profiles[0].hasCookies, true)
+ } finally { await root.remove() }
+})
+
+test('firefoxProfiles reads profiles.ini', async () => {
+ const root = await tempRoot()
+ try {
+ await mkdir(join(root.dir, 'Profiles', 'abc.default-release'), { recursive: true })
+ await writeFile(join(root.dir, 'Profiles', 'abc.default-release', 'cookies.sqlite'), 'x')
+ await writeFile(join(root.dir, 'profiles.ini'), [
+ '[Profile0]', 'Name=default-release', 'IsRelative=1', 'Path=Profiles/abc.default-release', 'Default=1',
+ '[Profile1]', 'Name=other', 'IsRelative=0', `Path=${join(root.dir, 'elsewhere')}`,
+ ].join('\n'))
+ const profiles = await firefoxProfiles(root.dir)
+ assert.equal(profiles.length, 2)
+ assert.equal(profiles[0].name, 'default-release')
+ assert.equal(profiles[0].path, join(root.dir, 'Profiles', 'abc.default-release'))
+ assert.equal(profiles[0].hasCookies, true)
+ assert.equal(profiles[1].path, join(root.dir, 'elsewhere'))
+ assert.equal(profiles[1].hasCookies, false)
+ } finally { await root.remove() }
+})
+
+test('cloneCookieStore lays out Local State plus the profile cookie db', async () => {
+ const root = await tempRoot()
+ const work = await cloneWorkDir()
+ try {
+ await mkdir(join(root.dir, 'Default', 'Network'), { recursive: true })
+ await writeFile(join(root.dir, 'Default', 'Network', 'Cookies'), 'db')
+ await writeFile(join(root.dir, 'Default', 'Network', 'Cookies-wal'), 'wal')
+ await writeFile(join(root.dir, 'Local State'), '{}')
+ const source = { engine: 'chromium', profilePath: join(root.dir, 'Default'), cookieDb: join(root.dir, 'Default', 'Network', 'Cookies') }
+ const copied = await cloneCookieStore(source, work.dir)
+ assert.equal(copied.length, 3)
+ assert.ok(existsSync(join(work.dir, 'Local State')))
+ assert.ok(existsSync(join(work.dir, 'Default', 'Network', 'Cookies')))
+ assert.ok(existsSync(join(work.dir, 'Default', 'Network', 'Cookies-wal')))
+ } finally { await work.remove(); await root.remove() }
+})
+
+test('cloneCookieStore needs Local State: without it the clone cannot decrypt', async () => {
+ const root = await tempRoot()
+ const work = await cloneWorkDir()
+ try {
+ await mkdir(join(root.dir, 'Default', 'Network'), { recursive: true })
+ await writeFile(join(root.dir, 'Default', 'Network', 'Cookies'), 'db')
+ const source = { engine: 'chromium', profilePath: join(root.dir, 'Default'), cookieDb: join(root.dir, 'Default', 'Network', 'Cookies') }
+ await assert.rejects(() => cloneCookieStore(source, work.dir))
+ } finally { await work.remove(); await root.remove() }
+})
+
+test('cloneCookieStore for Firefox copies the sqlite family', async () => {
+ const root = await tempRoot()
+ const work = await cloneWorkDir()
+ try {
+ const profile = join(root.dir, 'Profiles', 'abc.default')
+ await mkdir(profile, { recursive: true })
+ await writeFile(join(profile, 'cookies.sqlite'), 'db')
+ const source = { engine: 'firefox', profilePath: profile }
+ const copied = await cloneCookieStore(source, work.dir)
+ assert.deepEqual(copied, [join(profile, 'cookies.sqlite')])
+ assert.ok(existsSync(join(work.dir, 'cookies.sqlite')))
+ } finally { await work.remove(); await root.remove() }
+})
+
+test('locksProfile matches a browser process to the user-data root it locks', () => {
+ const source = { profilePath: 'C:\\Users\\u\\AppData\\Local\\Google\\Chrome\\User Data\\Default' }
+ assert.equal(locksProfile({ commandLine: '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"' }, source), true)
+ assert.equal(locksProfile({ commandLine: 'chrome.exe --user-data-dir="C:\\Users\\u\\AppData\\Local\\Google\\Chrome\\User Data" --restore' }, source), true)
+ assert.equal(locksProfile({ commandLine: 'chrome.exe --user-data-dir=D:\\other\\dir' }, source), false)
+})
diff --git a/app/test/cookie-import.test.mjs b/app/test/cookie-import.test.mjs
new file mode 100644
index 00000000..dc5d7e6c
--- /dev/null
+++ b/app/test/cookie-import.test.mjs
@@ -0,0 +1,103 @@
+// Writing parsed cookies into a partition session: the details mapping, the per-cookie
+// apply with read-back verification and flush, the pending-import store, and the
+// value-free preview the page confirms.
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import test from 'node:test'
+import { applyCookies, CookieImports, previewOf, toSetDetails } from '../src/cookie-import.mjs'
+import { parseCookieFile } from '../src/cookie-parse.mjs'
+
+const fixtures = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'cookies')
+const parse = (name) => parseCookieFile(readFileSync(join(fixtures, name)))
+
+test('toSetDetails maps a normalized cookie to the Electron set call', () => {
+ const domain = toSetDetails({ name: 'n', value: 'v', domain: '.example.com', path: '/', secure: true, httpOnly: true, sameSite: 'Strict', expires: 1893456000 })
+ assert.equal(domain.url, 'https://example.com/')
+ assert.equal(domain.domain, '.example.com')
+ assert.equal(domain.sameSite, 'strict')
+ assert.equal(domain.expirationDate, 1893456000)
+
+ const hostOnly = toSetDetails({ name: 'n', value: 'v', domain: 'example.com', path: '/app', secure: false, httpOnly: false })
+ assert.equal(hostOnly.url, 'http://example.com/app')
+ assert.equal(hostOnly.domain, undefined, 'no leading dot means host-only: no domain field')
+ assert.equal(hostOnly.sameSite, 'unspecified', 'no SameSite attribute stays unspecified')
+ assert.equal(hostOnly.expirationDate, undefined, 'a session cookie carries no expiry')
+
+ assert.equal(toSetDetails({ name: 'n', value: 'v', domain: 'x.io', path: '/', sameSite: 'None' }).sameSite, 'no_restriction')
+ assert.equal(toSetDetails({ name: 'n', value: 'v', domain: 'x.io', path: '/', sameSite: 'Lax' }).sameSite, 'lax')
+})
+
+/** A session.cookies stand-in: store what set accepts, refuse and drop what we are told to. */
+function fakeSession({ reject = [], drop = [] } = {}) {
+ const stored = new Map()
+ const key = (c) => `${c.name}${String(c.domain ?? '').replace(/^\.+/, '')}${c.path ?? '/'}`
+ return {
+ stored,
+ flushed: false,
+ cookies: {
+ set: async (details) => {
+ if (reject.includes(details.name)) throw new Error('Invalid cookie fields')
+ if (!drop.includes(details.name)) {
+ const host = new URL(details.url).host
+ stored.set(key({ name: details.name, domain: details.domain ?? host, path: details.path }), {
+ name: details.name, domain: details.domain ?? host, path: details.path, value: details.value,
+ secure: details.secure, httpOnly: details.httpOnly,
+ })
+ }
+ },
+ get: async () => [...stored.values()],
+ flushStore: async function () { this.flushed = true },
+ },
+ }
+}
+
+test('applyCookies stores, verifies by read-back and flushes the store', async () => {
+ const ses = fakeSession()
+ const parsed = parse('cookie-editor.json')
+ const report = await applyCookies(ses, parsed.cookies)
+ assert.equal(report.stored, 8)
+ assert.equal(report.dropped.length, 0)
+ assert.equal(report.failed.length, 0)
+ assert.equal(report.flushed, true)
+ assert.equal(ses.stored.size, 8)
+})
+
+test('applyCookies reports rejects and silent drops per cookie', async () => {
+ const ses = fakeSession({ reject: ['p_none'], drop: ['p_strict'] })
+ const parsed = parse('cookie-editor.json')
+ const report = await applyCookies(ses, parsed.cookies)
+ assert.equal(report.stored, 6)
+ assert.equal(report.failed.length, 1)
+ assert.equal(report.failed[0].name, 'p_none')
+ assert.match(report.failed[0].reason, /Invalid cookie fields/)
+ assert.equal(report.dropped.length, 1)
+ assert.equal(report.dropped[0].name, 'p_strict')
+ // Reports never carry values.
+ for (const item of [...report.failed, ...report.dropped]) assert.equal(item.value, undefined)
+})
+
+test('a pending import is value-bearing, one-shot and capped', () => {
+ const imports = new CookieImports()
+ const parsed = parse('cookies.txt')
+ const { id, preview } = imports.store(parsed, { kind: 'file', label: 'cookies.txt' })
+ assert.equal(preview.cookies, 8)
+ assert.equal(preview.source.kind, 'file')
+ assert.equal(preview.sites.length, 1) // all eight share 127.0.0.1
+ assert.ok(preview.notes.includes('session-cookies'))
+ assert.equal(imports.peek(id).cookies.length, 8)
+ assert.equal(imports.take(id).cookies.length, 8)
+ assert.equal(imports.take(id), null, 'taken once')
+ for (let i = 0; i < 20; i += 1) imports.store(parsed, { kind: 'file', label: String(i) })
+ assert.equal(imports.peek(id), null, 'older pendings were evicted past the cap')
+})
+
+test('preview groups by site and reports skipped and adjusted entries', () => {
+ const parsed = parse('malformed.cookies.txt')
+ const preview = previewOf(parsed, { kind: 'file', label: 'malformed.cookies.txt' })
+ assert.equal(preview.cookies, 5)
+ assert.equal(preview.skipped.length, 7)
+ assert.ok(preview.warnings.length > 0)
+ assert.ok(preview.warnings.every((w) => w.count >= 1 && w.message))
+})
diff --git a/app/test/cookie-parse.test.mjs b/app/test/cookie-parse.test.mjs
new file mode 100644
index 00000000..ceadafc2
--- /dev/null
+++ b/app/test/cookie-parse.test.mjs
@@ -0,0 +1,125 @@
+// The cookie-file parser: format detection by content, decoding variants, normalization,
+// and per-entry skip reporting. Fixtures are the P0 sample set (fake data only).
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import test from 'node:test'
+import { parseCookieFile } from '../src/cookie-parse.mjs'
+
+const fixtures = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'cookies')
+const parse = (name) => parseCookieFile(readFileSync(join(fixtures, name)))
+
+// Every file carries the same eight fake cookies in a different spelling; all of them
+// must parse to 8 entries with none skipped, and carry the warnings the spelling costs.
+const CASES = [
+ ['cookies.txt', 'netscape', 'utf-8', []],
+ ['cookie-editor.json', 'cookie-editor', 'utf-8', []],
+ ['playwright-storage-state.json', 'playwright', 'utf-8', []],
+ ['cookies.crlf-bom.txt', 'netscape', 'utf-8', []],
+ ['cookies.utf16le-bom.txt', 'netscape', 'utf-16le', []],
+ ['cookies.spaces.txt', 'netscape', 'utf-8', ['spaces-not-tabs']],
+ ['cookies.no-header.txt', 'netscape', 'utf-8', []],
+ ['cookies.dotted.txt', 'netscape', 'utf-8', []],
+ ['cookies.cookie-editor-export.txt', 'netscape', 'utf-8', []],
+ ['cookie-editor.current.json', 'cookie-editor', 'utf-8', []],
+ ['cookie-editor.ms-expiry.json', 'cookie-editor', 'utf-8', ['expiry-milliseconds']],
+ ['cookie-editor.minimal.json', 'cookie-editor', 'utf-8', ['missing-field']],
+ ['playwright.crlf-bom.json', 'playwright', 'utf-8', []],
+ ['selenium.json', 'cookie-editor', 'utf-8', []],
+]
+
+test('every format and encoding variant parses all eight cookies', () => {
+ for (const [file, format, encoding, warningCodes] of CASES) {
+ const parsed = parse(file)
+ assert.equal(parsed.ok, true, `${file}: ${parsed.error}`)
+ assert.equal(parsed.format, format, file)
+ assert.equal(parsed.encoding, encoding, file)
+ assert.equal(parsed.cookies.length, 8, file)
+ assert.equal(parsed.skipped.length, 0, file)
+ const codes = new Set(parsed.warnings.map((w) => w.code))
+ for (const code of warningCodes) assert.ok(codes.has(code), `${file}: warning ${code}`)
+ }
+})
+
+test('flags survive: HttpOnly prefix, Secure, SameSite, session', () => {
+ const byName = (parsed, name) => parsed.cookies.find((c) => c.name === name)
+ const editor = parse('cookie-editor.json')
+ assert.equal(byName(editor, 'p_http').httpOnly, true)
+ assert.equal(byName(editor, 'p_none').sameSite, 'None')
+ assert.equal(byName(editor, 'p_none').secure, true)
+ assert.equal(byName(editor, 'p_session').expires, undefined)
+ const txt = parse('cookies.txt')
+ assert.equal(byName(txt, 'p_http').httpOnly, true, '#HttpOnly_ is data, not a comment')
+ assert.equal(byName(txt, 'p_session').expires, undefined, 'expiry 0 is a session cookie')
+ const pw = parse('playwright-storage-state.json')
+ assert.equal(byName(pw, 'p_session').expires, undefined, 'expires -1 is a session cookie')
+ assert.equal(byName(pw, 'p_persist').sameSite, 'Lax')
+})
+
+test('a cookie header string is recognized and refused: it has no domain or path', () => {
+ const parsed = parse('header-string.txt')
+ assert.equal(parsed.ok, false)
+ assert.equal(parsed.format, 'header-string')
+ assert.match(parsed.error, /no domain/i)
+})
+
+test('malformed lines are skipped with reasons; the good ones still parse', () => {
+ const parsed = parse('malformed.cookies.txt')
+ assert.equal(parsed.ok, true)
+ assert.equal(parsed.format, 'netscape')
+ assert.equal(parsed.cookies.length, 5)
+ const codes = parsed.skipped.map((s) => s.code)
+ for (const code of ['field-count', 'bad-expiry', 'missing-domain', 'bad-char-name', 'prefix', 'expired']) {
+ assert.ok(codes.includes(code), `missing skip code ${code}`)
+ }
+ // A skipped entry names where it was and why; never the value.
+ for (const item of parsed.skipped) {
+ assert.ok(item.where)
+ assert.ok(item.reason)
+ assert.equal(item.value, undefined)
+ }
+})
+
+test('malformed JSON entries are skipped with reasons', () => {
+ const parsed = parse('malformed.cookie-editor.json')
+ assert.equal(parsed.ok, true)
+ assert.ok(parsed.cookies.length > 0)
+ assert.ok(parsed.skipped.length > 0)
+})
+
+test('truncated JSON reports unreadable', () => {
+ const parsed = parse('truncated.json')
+ assert.equal(parsed.ok, false)
+})
+
+test('duplicates resolve last-entry-wins with a warning', () => {
+ const parsed = parseCookieFile(JSON.stringify([
+ { name: 'n', value: 'one', domain: 'example.com', path: '/' },
+ { name: 'n', value: 'two', domain: 'example.com', path: '/' },
+ ]))
+ assert.equal(parsed.ok, true)
+ assert.equal(parsed.cookies.length, 1)
+ assert.equal(parsed.cookies[0].value, 'two')
+ assert.ok(parsed.warnings.some((w) => w.code === 'duplicate'))
+})
+
+test('SameSite=None without Secure is dropped to unspecified with a warning, not skipped', () => {
+ const parsed = parseCookieFile(JSON.stringify([{ name: 'n', value: 'v', domain: 'example.com', path: '/', secure: false, httpOnly: false, sameSite: 'None', expirationDate: 1893456000 }]))
+ assert.equal(parsed.cookies.length, 1)
+ assert.equal(parsed.cookies[0].sameSite, undefined)
+ assert.ok(parsed.warnings.some((w) => w.code === 'samesite-none-insecure'))
+})
+
+test('prefix rules and expired entries are refused before they can fail the store', () => {
+ const parsed = parseCookieFile(JSON.stringify([
+ { name: '__Host-x', value: 'v', domain: 'example.com', path: '/app', secure: true, httpOnly: false, expirationDate: 1893456000 },
+ { name: 'old', value: 'v', domain: 'example.com', path: '/', expirationDate: 1000000000 },
+ { name: 'semi;name', value: 'v', domain: 'example.com', path: '/', expirationDate: 1893456000 },
+ { name: 'good', value: 'v', domain: 'example.com', path: '/', secure: true, httpOnly: true, sameSite: 'Strict', expirationDate: 1893456000 },
+ ]))
+ assert.equal(parsed.cookies.length, 1)
+ assert.equal(parsed.cookies[0].name, 'good')
+ const codes = parsed.skipped.map((s) => s.code)
+ assert.ok(codes.includes('prefix') && codes.includes('expired') && codes.includes('bad-char-name'))
+})
diff --git a/app/test/fixtures/cookies/cookie-editor.current.json b/app/test/fixtures/cookies/cookie-editor.current.json
new file mode 100644
index 00000000..e230b53a
--- /dev/null
+++ b/app/test/fixtures/cookies/cookie-editor.current.json
@@ -0,0 +1,105 @@
+[
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": null,
+ "session": true,
+ "storeId": null
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": null,
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": null
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": true,
+ "sameSite": null,
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": null
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "lax",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": null
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "strict",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": null
+ },
+ {
+ "name": "p_none",
+ "value": "dummy-p_none",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": "no_restriction",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": null
+ },
+ {
+ "name": "p_secure",
+ "value": "dummy-p_secure",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": null,
+ "session": false,
+ "expirationDate": 1824209292.813,
+ "storeId": null
+ },
+ {
+ "name": "p_path",
+ "value": "dummy-p_path",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": null,
+ "session": false,
+ "expirationDate": 1824209292.813,
+ "storeId": null
+ }
+]
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/cookie-editor.json b/app/test/fixtures/cookies/cookie-editor.json
new file mode 100644
index 00000000..6b32b942
--- /dev/null
+++ b/app/test/fixtures/cookies/cookie-editor.json
@@ -0,0 +1,105 @@
+[
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": true,
+ "storeId": "0"
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": true,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "lax",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "strict",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_none",
+ "value": "dummy-p_none",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": "no_restriction",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_secure",
+ "value": "dummy-p_secure",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292.813,
+ "storeId": "0"
+ },
+ {
+ "name": "p_path",
+ "value": "dummy-p_path",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292.813,
+ "storeId": "0"
+ }
+]
diff --git a/app/test/fixtures/cookies/cookie-editor.minimal.json b/app/test/fixtures/cookies/cookie-editor.minimal.json
new file mode 100644
index 00000000..89bb3ffc
--- /dev/null
+++ b/app/test/fixtures/cookies/cookie-editor.minimal.json
@@ -0,0 +1,50 @@
+[
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ },
+ {
+ "name": "p_none",
+ "value": "dummy-p_none",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ },
+ {
+ "name": "p_secure",
+ "value": "dummy-p_secure",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ },
+ {
+ "name": "p_path",
+ "value": "dummy-p_path",
+ "domain": "127.0.0.1",
+ "path": "/cookies"
+ }
+]
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/cookie-editor.ms-expiry.json b/app/test/fixtures/cookies/cookie-editor.ms-expiry.json
new file mode 100644
index 00000000..34b2183f
--- /dev/null
+++ b/app/test/fixtures/cookies/cookie-editor.ms-expiry.json
@@ -0,0 +1,105 @@
+[
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": true,
+ "storeId": "0"
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": true,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "lax",
+ "session": false,
+ "expirationDate": 1824209292812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "strict",
+ "session": false,
+ "expirationDate": 1824209292812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_none",
+ "value": "dummy-p_none",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": "no_restriction",
+ "session": false,
+ "expirationDate": 1824209292812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_secure",
+ "value": "dummy-p_secure",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292813,
+ "storeId": "0"
+ },
+ {
+ "name": "p_path",
+ "value": "dummy-p_path",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292813,
+ "storeId": "0"
+ }
+]
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/cookies.cookie-editor-export.txt b/app/test/fixtures/cookies/cookies.cookie-editor-export.txt
new file mode 100644
index 00000000..3e78e666
--- /dev/null
+++ b/app/test/fixtures/cookies/cookies.cookie-editor-export.txt
@@ -0,0 +1,11 @@
+# Netscape HTTP Cookie File
+# http://curl.haxx.se/rfc/cookie_spec.html
+# This file was generated by Cookie-Editor
+127.0.0.1 FALSE /cookies FALSE 1792759694 p_session dummy-p_session
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_persist dummy-p_persist
+#HttpOnly_127.0.0.1 FALSE /cookies FALSE 1824209292 p_http dummy-p_http
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_lax dummy-p_lax
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_strict dummy-p_strict
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_none dummy-p_none
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_secure dummy-p_secure
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_path dummy-p_path
diff --git a/app/test/fixtures/cookies/cookies.crlf-bom.txt b/app/test/fixtures/cookies/cookies.crlf-bom.txt
new file mode 100644
index 00000000..762efa12
--- /dev/null
+++ b/app/test/fixtures/cookies/cookies.crlf-bom.txt
@@ -0,0 +1,12 @@
+# Netscape HTTP Cookie File
+# https://curl.se/docs/http-cookies.html
+# Dummy test data for a local test server (bot-browser-p0 T5). Not real cookies.
+
+127.0.0.1 FALSE /cookies FALSE 0 p_session dummy-p_session
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_persist dummy-p_persist
+#HttpOnly_127.0.0.1 FALSE /cookies FALSE 1824209292 p_http dummy-p_http
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_lax dummy-p_lax
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_strict dummy-p_strict
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_none dummy-p_none
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_secure dummy-p_secure
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_path dummy-p_path
diff --git a/app/test/fixtures/cookies/cookies.dotted.txt b/app/test/fixtures/cookies/cookies.dotted.txt
new file mode 100644
index 00000000..34256b69
--- /dev/null
+++ b/app/test/fixtures/cookies/cookies.dotted.txt
@@ -0,0 +1,12 @@
+# Netscape HTTP Cookie File
+# https://curl.se/docs/http-cookies.html
+# Dummy test data for a local test server (bot-browser-p0 T5). Not real cookies.
+
+.127.0.0.1 TRUE /cookies FALSE 0 p_session dummy-p_session
+.127.0.0.1 TRUE /cookies FALSE 1824209292 p_persist dummy-p_persist
+#HttpOnly_.127.0.0.1 TRUE /cookies FALSE 1824209292 p_http dummy-p_http
+.127.0.0.1 TRUE /cookies FALSE 1824209292 p_lax dummy-p_lax
+.127.0.0.1 TRUE /cookies FALSE 1824209292 p_strict dummy-p_strict
+.127.0.0.1 TRUE /cookies TRUE 1824209292 p_none dummy-p_none
+.127.0.0.1 TRUE /cookies TRUE 1824209292 p_secure dummy-p_secure
+.127.0.0.1 TRUE /cookies FALSE 1824209292 p_path dummy-p_path
diff --git a/app/test/fixtures/cookies/cookies.no-header.txt b/app/test/fixtures/cookies/cookies.no-header.txt
new file mode 100644
index 00000000..6f223cf9
--- /dev/null
+++ b/app/test/fixtures/cookies/cookies.no-header.txt
@@ -0,0 +1,17 @@
+
+127.0.0.1 FALSE /cookies FALSE 0 p_session dummy-p_session
+
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_persist dummy-p_persist
+
+#HttpOnly_127.0.0.1 FALSE /cookies FALSE 1824209292 p_http dummy-p_http
+
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_lax dummy-p_lax
+
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_strict dummy-p_strict
+
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_none dummy-p_none
+
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_secure dummy-p_secure
+
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_path dummy-p_path
+
diff --git a/app/test/fixtures/cookies/cookies.spaces.txt b/app/test/fixtures/cookies/cookies.spaces.txt
new file mode 100644
index 00000000..11b2c74c
--- /dev/null
+++ b/app/test/fixtures/cookies/cookies.spaces.txt
@@ -0,0 +1,12 @@
+# Netscape HTTP Cookie File
+# https://curl.se/docs/http-cookies.html
+# Dummy test data for a local test server (bot-browser-p0 T5). Not real cookies.
+
+127.0.0.1 FALSE /cookies FALSE 0 p_session dummy-p_session
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_persist dummy-p_persist
+#HttpOnly_127.0.0.1 FALSE /cookies FALSE 1824209292 p_http dummy-p_http
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_lax dummy-p_lax
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_strict dummy-p_strict
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_none dummy-p_none
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_secure dummy-p_secure
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_path dummy-p_path
diff --git a/app/test/fixtures/cookies/cookies.txt b/app/test/fixtures/cookies/cookies.txt
new file mode 100644
index 00000000..d8abb634
--- /dev/null
+++ b/app/test/fixtures/cookies/cookies.txt
@@ -0,0 +1,12 @@
+# Netscape HTTP Cookie File
+# https://curl.se/docs/http-cookies.html
+# Dummy test data for a local test server (bot-browser-p0 T5). Not real cookies.
+
+127.0.0.1 FALSE /cookies FALSE 0 p_session dummy-p_session
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_persist dummy-p_persist
+#HttpOnly_127.0.0.1 FALSE /cookies FALSE 1824209292 p_http dummy-p_http
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_lax dummy-p_lax
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_strict dummy-p_strict
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_none dummy-p_none
+127.0.0.1 FALSE /cookies TRUE 1824209292 p_secure dummy-p_secure
+127.0.0.1 FALSE /cookies FALSE 1824209292 p_path dummy-p_path
diff --git a/app/test/fixtures/cookies/cookies.utf16le-bom.txt b/app/test/fixtures/cookies/cookies.utf16le-bom.txt
new file mode 100644
index 00000000..d3ae1966
Binary files /dev/null and b/app/test/fixtures/cookies/cookies.utf16le-bom.txt differ
diff --git a/app/test/fixtures/cookies/header-string.txt b/app/test/fixtures/cookies/header-string.txt
new file mode 100644
index 00000000..d2413d70
--- /dev/null
+++ b/app/test/fixtures/cookies/header-string.txt
@@ -0,0 +1 @@
+p_session=dummy-p_session; p_persist=dummy-p_persist; p_http=dummy-p_http; p_lax=dummy-p_lax; p_strict=dummy-p_strict; p_none=dummy-p_none; p_secure=dummy-p_secure; p_path=dummy-p_path
diff --git a/app/test/fixtures/cookies/malformed.cookie-editor.json b/app/test/fixtures/cookies/malformed.cookie-editor.json
new file mode 100644
index 00000000..21dbf1ef
--- /dev/null
+++ b/app/test/fixtures/cookies/malformed.cookie-editor.json
@@ -0,0 +1,136 @@
+[
+ {
+ "name": "m_ok1",
+ "value": "dummy-m_ok1",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": true,
+ "storeId": "0"
+ },
+ "not an object",
+ null,
+ {
+ "value": "dummy-m_noname",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies"
+ },
+ {
+ "name": "m_nodomain",
+ "value": "dummy-m_nodomain",
+ "path": "/cookies"
+ },
+ {
+ "name": 42,
+ "value": "dummy-m_numname",
+ "domain": "127.0.0.1"
+ },
+ {
+ "name": "m_badexpiry",
+ "value": "dummy-m_badexpiry",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "storeId": "0",
+ "expirationDate": "soon"
+ },
+ {
+ "name": "m_weirdsamesite",
+ "value": "dummy-m_weirdsamesite",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "sometimes",
+ "session": true,
+ "storeId": "0"
+ },
+ {
+ "name": "m_minimal",
+ "value": "dummy-m_minimal",
+ "domain": "127.0.0.1"
+ },
+ {
+ "name": "m_none_insecure",
+ "value": "dummy-m_none_insecure",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "no_restriction",
+ "session": true,
+ "storeId": "0"
+ },
+ {
+ "name": "m_expired",
+ "value": "dummy-m_expired",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "storeId": "0",
+ "expirationDate": 1792586894
+ },
+ {
+ "name": "m_ms",
+ "value": "dummy-m_ms",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "storeId": "0",
+ "expirationDate": 1795265294000
+ },
+ {
+ "name": "m_dup",
+ "value": "dummy-m_dup",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": true,
+ "storeId": "0"
+ },
+ {
+ "name": "m_dup",
+ "value": "dummy-m_dup",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": true,
+ "sameSite": "unspecified",
+ "session": true,
+ "storeId": "0"
+ },
+ {
+ "name": "m_ok2",
+ "value": "dummy-m_ok2",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": true,
+ "storeId": "0"
+ }
+]
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/malformed.cookies.txt b/app/test/fixtures/cookies/malformed.cookies.txt
new file mode 100644
index 00000000..5a0dfe22
--- /dev/null
+++ b/app/test/fixtures/cookies/malformed.cookies.txt
@@ -0,0 +1,14 @@
+# Netscape HTTP Cookie File
+# Lines below are malformed on purpose (T5 edge case). Dummy data.
+127.0.0.1 FALSE /cookies FALSE 0 m_ok1 dummy-m_ok1
+127.0.0.1 FALSE /cookies FALSE m_fivefields
+127.0.0.1 FALSE /cookies FALSE soon m_badexpiry dummy-m_badexpiry
+ FALSE /cookies FALSE 0 m_nodomain dummy-m_nodomain
+127.0.0.1 FALSE /cookies FALSE 0 m_bad;name dummy-m_badname
+127.0.0.1 FALSE /cookies FALSE 0 __Host-m_prefix dummy-m_prefix
+127.0.0.1 MAYBE /cookies FALSE 0 m_badflag dummy-m_badflag
+127.0.0.1 FALSE /cookies FALSE 0 m_spaces dummy-m_spaces
+127.0.0.1 FALSE /cookies FALSE 0 m_novalue
+127.0.0.1 FALSE /cookies FALSE 1000000000 m_expired dummy-m_expired
+127.0.0.1 FALSE /cookies FALSE 0 m_ok2 dummy-m_ok2
+this line is not a cookie
diff --git a/app/test/fixtures/cookies/malformed.playwright.json b/app/test/fixtures/cookies/malformed.playwright.json
new file mode 100644
index 00000000..bcbf018f
--- /dev/null
+++ b/app/test/fixtures/cookies/malformed.playwright.json
@@ -0,0 +1,59 @@
+{
+ "cookies": [
+ {
+ "name": "m_ok1",
+ "value": "dummy-m_ok1",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": -1,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "m_nodomain",
+ "value": "dummy-m_nodomain",
+ "path": "/"
+ },
+ {
+ "name": "m_badexpires",
+ "value": "dummy-m_badexpires",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": "later",
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "m_url",
+ "value": "dummy-m_url",
+ "expires": -1,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax",
+ "url": "http://127.0.0.1/cookies/page"
+ },
+ {
+ "name": "m_ok2",
+ "value": "dummy-m_ok2",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": -1,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ }
+ ],
+ "origins": [
+ {
+ "origin": "http://127.0.0.1:9",
+ "localStorage": [
+ {
+ "name": "dummy-key",
+ "value": "dummy-local-value"
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/playwright-storage-state.json b/app/test/fixtures/cookies/playwright-storage-state.json
new file mode 100644
index 00000000..61b2a61b
--- /dev/null
+++ b/app/test/fixtures/cookies/playwright-storage-state.json
@@ -0,0 +1,85 @@
+{
+ "cookies": [
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": -1,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": true,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Strict"
+ },
+ {
+ "name": "p_none",
+ "value": "dummy-p_none",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": true,
+ "sameSite": "None"
+ },
+ {
+ "name": "p_secure",
+ "value": "dummy-p_secure",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.813,
+ "httpOnly": false,
+ "secure": true,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_path",
+ "value": "dummy-p_path",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.813,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ }
+ ],
+ "origins": []
+}
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/playwright.crlf-bom.json b/app/test/fixtures/cookies/playwright.crlf-bom.json
new file mode 100644
index 00000000..0e696096
--- /dev/null
+++ b/app/test/fixtures/cookies/playwright.crlf-bom.json
@@ -0,0 +1,85 @@
+{
+ "cookies": [
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": -1,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": true,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Strict"
+ },
+ {
+ "name": "p_none",
+ "value": "dummy-p_none",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.812,
+ "httpOnly": false,
+ "secure": true,
+ "sameSite": "None"
+ },
+ {
+ "name": "p_secure",
+ "value": "dummy-p_secure",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.813,
+ "httpOnly": false,
+ "secure": true,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_path",
+ "value": "dummy-p_path",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "expires": 1824209292.813,
+ "httpOnly": false,
+ "secure": false,
+ "sameSite": "Lax"
+ }
+ ],
+ "origins": []
+}
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/selenium.json b/app/test/fixtures/cookies/selenium.json
new file mode 100644
index 00000000..2cf758c4
--- /dev/null
+++ b/app/test/fixtures/cookies/selenium.json
@@ -0,0 +1,81 @@
+[
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "Lax"
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "Lax",
+ "expiry": 1824209292
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": true,
+ "sameSite": "Lax",
+ "expiry": 1824209292
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "Lax",
+ "expiry": 1824209292
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "Strict",
+ "expiry": 1824209292
+ },
+ {
+ "name": "p_none",
+ "value": "dummy-p_none",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": "None",
+ "expiry": 1824209292
+ },
+ {
+ "name": "p_secure",
+ "value": "dummy-p_secure",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": true,
+ "httpOnly": false,
+ "sameSite": "Lax",
+ "expiry": 1824209292
+ },
+ {
+ "name": "p_path",
+ "value": "dummy-p_path",
+ "domain": "127.0.0.1",
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "Lax",
+ "expiry": 1824209292
+ }
+]
\ No newline at end of file
diff --git a/app/test/fixtures/cookies/truncated.json b/app/test/fixtures/cookies/truncated.json
new file mode 100644
index 00000000..124b9aef
--- /dev/null
+++ b/app/test/fixtures/cookies/truncated.json
@@ -0,0 +1,63 @@
+[
+ {
+ "name": "p_session",
+ "value": "dummy-p_session",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": true,
+ "storeId": "0"
+ },
+ {
+ "name": "p_persist",
+ "value": "dummy-p_persist",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_http",
+ "value": "dummy-p_http",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": true,
+ "sameSite": "unspecified",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_lax",
+ "value": "dummy-p_lax",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "lax",
+ "session": false,
+ "expirationDate": 1824209292.812,
+ "storeId": "0"
+ },
+ {
+ "name": "p_strict",
+ "value": "dummy-p_strict",
+ "domain": "127.0.0.1",
+ "hostOnly": true,
+ "path": "/cookies",
+ "secure": false,
+ "httpOnly": false,
+ "sameSite": "strict",
+ "session": false,
+ "expirationDate":
\ No newline at end of file
diff --git a/docs/plans/2026-10-08-browser-and-secrets.md b/docs/plans/2026-10-08-browser-and-secrets.md
index b7b35619..b55d2f35 100644
--- a/docs/plans/2026-10-08-browser-and-secrets.md
+++ b/docs/plans/2026-10-08-browser-and-secrets.md
@@ -67,7 +67,7 @@ Bot 要替用户在网上做事,就会碰到两类东西:网页,以及登
- 历史消息里的链接还不能直接在 Bot 浏览器里打开(#114)。
- 关掉 `auto` 搜索以后,`web_search` 可能报错,恢复方法见 #128。
- 用 opencode 路由时,原生搜索缺少 `x-opencode-session`(#184)。
-- 和[愿景](../vision.zh.md)第 7 条的差距:导入 cookie 还没做。
+- 导入 cookie 只在桌面应用里有(写进 Bot 自己的存储分区):cookie 文件(Cookie-Editor JSON、cookies.txt、Playwright storageState)和本机 Chrome/Edge/Firefox 的 profile。Chromium 系是先克隆 profile、再让原浏览器自己解密,不是直接读文件。localStorage 等其他登录状态不导。
- 密钥只防泄露到模型、记录和其他 Bot 的 shell。有权限的 Bot 在自己的 shell 里能用到值,所以给哪些 Bot 开放,要由用户判断。
## 变更
@@ -76,3 +76,4 @@ Bot 要替用户在网上做事,就会碰到两类东西:网页,以及登
- 2026-10-09:`read_browser` 读成 Markdown 并标注链接和控件;密钥卡和替换规则。
- 之后:加了多标签页、最多 6 个活着的页面、GitHub 连接器。
- 2026-10-23:桌面应用里也有 Bot 浏览器,登录保存在应用自己的目录里,#449。
+- 2026-10-23:桌面应用的 Bot 浏览器能导入 cookie(文件和本机浏览器),#458。
diff --git a/ds-bot/README.md b/ds-bot/README.md
index bf19f739..73997b83 100644
--- a/ds-bot/README.md
+++ b/ds-bot/README.md
@@ -152,6 +152,7 @@ In dsh Desktop and the desktop app, a Bot's chat header has a globe button. It o
- Read only: the Bot cannot click, type, scroll or open addresses yet.
- **Addresses**: http and https only. localhost and LAN addresses are allowed; cloud metadata addresses (such as `169.254.x.x`) and dsh's own ports are not.
- The browser panel and the details drawer share the right column; opening one closes the other. Switching chats switches the panel to that Bot. Deleting a Bot clears its browser and saved address.
+- **Cookie import (desktop app only)**: the import button in the browser bar previews the cookies of a file (Cookie-Editor JSON, Netscape `cookies.txt`, Playwright `storageState`) or of an installed Chromium/Firefox profile, then writes them into the Bot's partition. A source browser closes for a moment so its cookie store can be copied, and it reopens with its tabs. Sign-in that lives outside cookies (localStorage, passkeys) does not come along.
dsh Web has no browser panel and no `read_browser` tool.
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 6446a3d3..b3877941 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -274,6 +274,32 @@ var ZH = {
"Conversation details": "对话详情",
"Panel tabs": "面板标签页",
"Close panel": "关闭面板",
+ // Cookie imports
+ "Import cookies": "导入 cookie",
+ "From a file…": "从文件导入…",
+ "cookies.txt, JSON, storageState": "cookies.txt、JSON、storageState",
+ "Copy of its cookies": "复制它的 cookie",
+ "No browsers found": "没有找到浏览器",
+ "{name} is running": "{name} 正在运行",
+ "It must close for a moment so its cookies can be copied. It will reopen with your tabs.": "需要先把它关掉一下才能复制 cookie,之后会自动重新打开并恢复你的标签页。",
+ "Close {name} and import": "关闭 {name} 并导入",
+ "Closing…": "正在关闭…",
+ "Import {count} cookies": "导入 {count} 个 cookie",
+ "the browser was restarted": "浏览器已重新打开",
+ "{count} skipped": "跳过 {count} 个",
+ "{count} session": "{count} 个会话",
+ "{count} adjusted": "调整了 {count} 个",
+ "Cookies without an expiry stay until the app closes.": "没有过期时间的 cookie 会保留到应用关闭。",
+ "Some sites also keep sign-in outside cookies; you may need to sign in again there.": "有些网站还把登录信息存在 cookie 之外,这些网站可能要重新登录。",
+ "Importing…": "正在导入…",
+ "Import": "导入",
+ "Imported {count} cookies": "已导入 {count} 个 cookie",
+ "No cookies were stored": "没有 cookie 被写入",
+ "Reload the page": "刷新页面",
+ "Import failed": "导入失败",
+ "That file is too large to be a cookie export.": "这个文件太大了,不像是 cookie 导出文件。",
+ "That file could not be read.": "这个文件读不了。",
+ "{count}": "{count} 个",
// Bot settings
"Choose a PNG, JPEG, WebP, or GIF image": "请选择 PNG、JPEG、WebP 或 GIF 图片",
"Choose an image smaller than 25 MB": "请选择小于 25 MB 的图片",
@@ -13819,6 +13845,9 @@ var StopIcon = icon(["M5.5 5.5l9 9M14.5 5.5l-9 9"]);
var CloseIcon2 = icon(["M5.5 5.5l9 9M14.5 5.5l-9 9"]);
var PlusTabIcon = icon(["M10 5v10M5 10h10"]);
var LockIcon2 = icon(["M6.5 9V7a3.5 3.5 0 0 1 7 0v2", "M5.5 9h9v7h-9z"]);
+var ImportIcon = icon(["M10 3.5v8.5", "M6 8.5l4 4 4-4", "M4.5 14v1.5a1.5 1.5 0 0 0 1.5 1.5h8a1.5 1.5 0 0 0 1.5-1.5V14"]);
+var FileIcon = icon(["M6 3.5h5.5L14.5 6.5v10H6z", "M11 3.5v3.5h3.5"]);
+var WindowIcon = icon(["M4 5h12v9.5H4z", "M4 7.5h12"]);
function Favicon({ src, className }) {
const [failed, setFailed] = (0, import_react37.useState)(null);
if (!src || failed === src) return (0, import_react37.createElement)("span", { className: `${className} bt-ptab-globe` }, (0, import_react37.createElement)(GlobeIcon));
@@ -13994,7 +14023,60 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages })
const frame = (0, import_react37.useRef)(null);
const input = (0, import_react37.useRef)(null);
const [draft, setDraft] = (0, import_react37.useState)(null);
- const showGuest = landed && !leaving && Boolean(page.url) && !page.error;
+ const imports = actions.browserImport;
+ const [flow, setFlow] = (0, import_react37.useState)(null);
+ const flowRef = (0, import_react37.useRef)(null);
+ const [sources, setSources] = (0, import_react37.useState)(null);
+ const [busy, setBusy] = (0, import_react37.useState)(false);
+ const setFlowTracked = (next) => {
+ flowRef.current = typeof next === "function" ? next(flowRef.current) : next;
+ setFlow(flowRef.current);
+ };
+ const showGuest = landed && !leaving && Boolean(page.url) && !page.error && flow === null;
+ (0, import_react37.useEffect)(() => {
+ setFlowTracked(null);
+ return () => {
+ const id = typeof flowRef.current === "object" && flowRef.current !== null ? flowRef.current.id : null;
+ if (id) void imports?.cancel(id).catch(() => {
+ });
+ };
+ }, [tabId]);
+ const openImport = () => {
+ setFlowTracked("menu");
+ if (sources === null) void imports.sources().then(setSources, () => setSources([]));
+ };
+ const showPicked = (r) => {
+ if (r?.id) setFlowTracked({ stage: "preview", id: r.id, preview: r.preview, restarted: r.restarted === true });
+ else if (r?.error) setFlowTracked({ stage: "error", message: importError(r.error) });
+ else setFlowTracked(null);
+ };
+ const job = async (work) => {
+ setBusy(true);
+ try {
+ await work();
+ } catch (error) {
+ setFlowTracked({ stage: "error", message: String(error?.message ?? error) });
+ } finally {
+ setBusy(false);
+ }
+ };
+ const pickFile = () => job(async () => showPicked(await imports.pick()));
+ const pickSource = (source) => job(async () => {
+ const r = await imports.live(source.id);
+ if (r?.running) setFlowTracked({ stage: "running", source });
+ else showPicked(r);
+ });
+ const closeAndImport = () => job(async () => showPicked(await imports.live(flowRef.current?.source?.id, true)));
+ const applyImport = () => job(async () => {
+ const report = await imports.apply(bot.id, flowRef.current?.id);
+ setFlowTracked((current) => ({ stage: "result", report, label: current?.preview?.source?.label ?? null }));
+ });
+ const cancelImport = () => {
+ const id = typeof flow === "object" && flow !== null ? flow.id : null;
+ setFlowTracked(null);
+ if (id) void imports?.cancel(id).catch(() => {
+ });
+ };
(0, import_react37.useLayoutEffect)(() => {
const element = frame.current;
if (!element || leaving || !tabId) {
@@ -14081,12 +14163,25 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages })
}
})
),
+ imports ? (0, import_react37.createElement)("button", {
+ type: "button",
+ className: "bt-icon-btn bt-import-btn",
+ "aria-label": t("Import cookies"),
+ title: t("Import cookies"),
+ "aria-expanded": flow === "menu",
+ disabled: busy,
+ onClick: () => {
+ flow === "menu" ? setFlowTracked(null) : openImport();
+ }
+ }, (0, import_react37.createElement)(ImportIcon)) : null,
page.loading ? (0, import_react37.createElement)("span", { className: "bt-browser-progress", "aria-hidden": true }) : null
),
(0, import_react37.createElement)(
"div",
{ ref: frame, className: "bt-browser-frame", "data-guest": showGuest || void 0 },
- page.error ? (0, import_react37.createElement)(
+ flow === "menu" ? (0, import_react37.createElement)(ImportMenu, { sources, busy, onFile: pickFile, onSource: pickSource, onClose: () => setFlowTracked(null) }) : null,
+ typeof flow === "object" && flow !== null ? (0, import_react37.createElement)(ImportCard, { flow, page, busy, onApply: applyImport, onCancel: cancelImport, onCloseAndImport: closeAndImport, onDone: () => setFlowTracked(null), onReload: () => actions.browserCommand(tabId, "reload") }) : null,
+ flow === null && page.error ? (0, import_react37.createElement)(
"div",
{ className: "bt-browser-empty" },
(0, import_react37.createElement)("div", { className: "bt-browser-empty-title" }, t("This page didn’t load")),
@@ -14094,16 +14189,167 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages })
page.url ? (0, import_react37.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: () => {
void actions.browserNavigate(tabId, page.url);
} }, t("Try again")) : null
- ) : !page.url ? (0, import_react37.createElement)(
+ ) : flow === null && !page.url ? (0, import_react37.createElement)(
"div",
{ className: "bt-browser-empty" },
(0, import_react37.createElement)(BotMark, { bot, size: 48, state: "idle", live: true }),
(0, import_react37.createElement)("div", { className: "bt-browser-empty-title" }, t("{name}'s browser", { name: bot.name })),
- (0, import_react37.createElement)("div", { className: "bt-browser-empty-text" }, t("Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.", { name: bot.name }))
+ (0, import_react37.createElement)("div", { className: "bt-browser-empty-text" }, t("Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.", { name: bot.name })),
+ imports ? (0, import_react37.createElement)("button", { type: "button", className: "bt-browser-retry", onClick: openImport }, t("Import cookies")) : null
) : null
)
);
}
+function importError(error) {
+ if (error === "too-large") return t("That file is too large to be a cookie export.");
+ if (error === "unreadable") return t("That file could not be read.");
+ return String(error);
+}
+function ImportMenu({ sources, busy, onFile, onSource, onClose }) {
+ (0, import_react37.useEffect)(() => {
+ const close = (event) => {
+ if (event.key === "Escape") onClose();
+ };
+ window.addEventListener("keydown", close);
+ return () => window.removeEventListener("keydown", close);
+ }, [onClose]);
+ return (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-menu", role: "menu", "aria-label": t("Import cookies") },
+ (0, import_react37.createElement)("div", { className: "bt-import-menu-title" }, t("Import cookies")),
+ (0, import_react37.createElement)(
+ "button",
+ { type: "button", className: "bt-import-item", role: "menuitem", disabled: busy, onClick: onFile },
+ (0, import_react37.createElement)(FileIcon, { className: "bt-import-item-icon" }),
+ (0, import_react37.createElement)("span", { className: "bt-import-item-name" }, t("From a file…")),
+ (0, import_react37.createElement)("span", { className: "bt-import-item-sub" }, t("cookies.txt, JSON, storageState"))
+ ),
+ sources === null ? (0, import_react37.createElement)("div", { className: "bt-import-menu-note" }, t("Loading…")) : sources.length === 0 ? (0, import_react37.createElement)("div", { className: "bt-import-menu-note" }, t("No browsers found")) : sources.map((source) => (0, import_react37.createElement)(
+ "button",
+ {
+ key: source.id,
+ type: "button",
+ className: "bt-import-item",
+ role: "menuitem",
+ disabled: busy,
+ onClick: () => onSource(source)
+ },
+ (0, import_react37.createElement)(WindowIcon, { className: "bt-import-item-icon" }),
+ (0, import_react37.createElement)("span", { className: "bt-import-item-name" }, source.label),
+ (0, import_react37.createElement)("span", { className: "bt-import-item-sub" }, t("Copy of its cookies"))
+ ))
+ );
+}
+function ImportCard({ flow, page, busy, onApply, onCancel, onCloseAndImport, onDone, onReload }) {
+ const { stage } = flow;
+ if (stage === "running") {
+ return (0, import_react37.createElement)("div", { className: "bt-import-card" }, (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-box" },
+ (0, import_react37.createElement)("div", { className: "bt-import-title" }, t("{name} is running", { name: flow.source.name })),
+ (0, import_react37.createElement)("div", { className: "bt-import-text" }, t("It must close for a moment so its cookies can be copied. It will reopen with your tabs.")),
+ (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-actions" },
+ (0, import_react37.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onCloseAndImport }, busy ? t("Closing…") : t("Close {name} and import", { name: flow.source.name })),
+ (0, import_react37.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel"))
+ )
+ ));
+ }
+ if (stage === "error") {
+ return (0, import_react37.createElement)("div", { className: "bt-import-card" }, (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-box" },
+ (0, import_react37.createElement)("div", { className: "bt-import-title" }, t("Import failed")),
+ (0, import_react37.createElement)("div", { className: "bt-import-text" }, flow.message),
+ (0, import_react37.createElement)("div", { className: "bt-import-actions" }, (0, import_react37.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onCancel }, t("Close")))
+ ));
+ }
+ if (stage === "result") {
+ const { report } = flow;
+ const problems = [...report.dropped ?? [], ...report.failed ?? []];
+ return (0, import_react37.createElement)("div", { className: "bt-import-card" }, (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-box" },
+ (0, import_react37.createElement)("div", { className: "bt-import-title" }, report.stored > 0 ? t("Imported {count} cookies", { count: report.stored }) : t("No cookies were stored")),
+ flow.label ? (0, import_react37.createElement)("div", { className: "bt-import-sub" }, flow.label) : null,
+ problems.length ? (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-list" },
+ problems.slice(0, 8).map((item, index) => (0, import_react37.createElement)(
+ "div",
+ { key: index, className: "bt-import-line" },
+ (0, import_react37.createElement)("span", { className: "bt-import-line-name" }, item.name ?? "—"),
+ (0, import_react37.createElement)("span", { className: "bt-import-line-reason" }, item.reason)
+ )),
+ problems.length > 8 ? (0, import_react37.createElement)("div", { className: "bt-import-line" }, (0, import_react37.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: problems.length - 8 }))) : null
+ ) : null,
+ (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-actions" },
+ page.url ? (0, import_react37.createElement)("button", { type: "button", className: "bt-import-plain", onClick: onReload }, t("Reload the page")) : null,
+ (0, import_react37.createElement)("button", { type: "button", className: "bt-import-primary", onClick: onDone }, t("Done"))
+ )
+ ));
+ }
+ const { preview } = flow;
+ return (0, import_react37.createElement)("div", { className: "bt-import-card" }, (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-box" },
+ (0, import_react37.createElement)("div", { className: "bt-import-title" }, t("Import {count} cookies", { count: preview.cookies })),
+ (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-sub" },
+ preview.source?.label ?? "",
+ flow.restarted ? ` · ${t("the browser was restarted")}` : ""
+ ),
+ preview.sites.length ? (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-list" },
+ preview.sites.map((site) => (0, import_react37.createElement)(
+ "div",
+ { key: site.site, className: "bt-import-line" },
+ (0, import_react37.createElement)("span", { className: "bt-import-line-name" }, site.site),
+ (0, import_react37.createElement)(
+ "span",
+ { className: "bt-import-line-count" },
+ t("{count}", { count: site.cookies }),
+ site.session > 0 ? ` · ${t("{count} session", { count: site.session })}` : ""
+ )
+ ))
+ ) : null,
+ preview.skipped.length ? (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-list" },
+ (0, import_react37.createElement)("div", { className: "bt-import-note" }, t("{count} skipped", { count: preview.skipped.length })),
+ preview.skipped.slice(0, 5).map((item, index) => (0, import_react37.createElement)(
+ "div",
+ { key: index, className: "bt-import-line" },
+ (0, import_react37.createElement)("span", { className: "bt-import-line-name" }, item.name ?? item.where),
+ (0, import_react37.createElement)("span", { className: "bt-import-line-reason" }, item.reason)
+ )),
+ preview.skipped.length > 5 ? (0, import_react37.createElement)("div", { className: "bt-import-line" }, (0, import_react37.createElement)("span", { className: "bt-import-line-reason" }, t("and {count} more", { count: preview.skipped.length - 5 }))) : null
+ ) : null,
+ preview.warnings.length ? (0, import_react37.createElement)(
+ "details",
+ { className: "bt-import-warns" },
+ (0, import_react37.createElement)("summary", null, t("{count} adjusted", { count: preview.warnings.reduce((n, w) => n + w.count, 0) })),
+ preview.warnings.map((w, index) => (0, import_react37.createElement)(
+ "div",
+ { key: index, className: "bt-import-line" },
+ (0, import_react37.createElement)("span", { className: "bt-import-line-reason" }, `${w.count} × ${w.message}`)
+ ))
+ ) : null,
+ preview.notes.includes("session-cookies") ? (0, import_react37.createElement)("div", { className: "bt-import-note" }, t("Cookies without an expiry stay until the app closes.")) : null,
+ preview.notes.includes("local-storage-left") ? (0, import_react37.createElement)("div", { className: "bt-import-note" }, t("Some sites also keep sign-in outside cookies; you may need to sign in again there.")) : null,
+ (0, import_react37.createElement)(
+ "div",
+ { className: "bt-import-actions" },
+ (0, import_react37.createElement)("button", { type: "button", className: "bt-import-primary", disabled: busy, onClick: onApply }, busy ? t("Importing…") : t("Import")),
+ (0, import_react37.createElement)("button", { type: "button", className: "bt-import-plain", disabled: busy, onClick: onCancel }, t("Cancel"))
+ )
+ ));
+}
function BotPanel({ pane, leaving, roster, actions, useSessions, useSessionStatus, useActivity, useWork, useBrowserTabs, useBrowserPages }) {
const bot = roster.byId[pane.id];
const canBrowse = Boolean(bot && roster.browser === true && actions.browserShow);
@@ -14420,6 +14666,36 @@ var BROWSER_CSS = `
.bt-bcard-new:hover{color:var(--bt-ink);border-color:var(--bt-ink-3)}
.bt-bcard-new svg{width:14px;height:14px}
.bt-browser-empty-mark{display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center}
+/* Cookie imports */
+.bt-import-menu{position:absolute;top:6px;right:6px;z-index:6;width:236px;padding:6px;border-radius:16px;background:var(--bt-main);border:.5px solid var(--bt-line-2);box-shadow:0 10px 32px -8px rgba(0,0,0,.14),0 2px 8px rgba(0,0,0,.06);animation:bt-bcard-in .18s cubic-bezier(.16,1,.3,1) both}
+.bt-import-menu-title{padding:6px 10px 8px;font-size:11px;font-weight:500;letter-spacing:.02em;color:var(--bt-ink-3)}
+.bt-import-item{display:flex;align-items:center;gap:9px;width:100%;min-width:0;padding:8px 10px;border:0;border-radius:8px;background:none;color:var(--bt-ink);font:inherit;font-size:12.5px;text-align:left;cursor:pointer}
+.bt-import-item:hover{background:var(--bt-hover)}
+.bt-import-item:disabled{opacity:.5;cursor:default}
+.bt-import-item-icon{flex:none;color:var(--bt-ink-3)}
+.bt-import-item-icon svg,.bt-import-item svg{width:15px;height:15px}
+.bt-import-item-name{flex:none;max-width:55%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.bt-import-item-sub{flex:1;min-width:0;text-align:right;font-size:11px;color:var(--bt-ink-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.bt-import-menu-note{padding:8px 10px 10px;font-size:12px;color:var(--bt-ink-3)}
+.bt-import-card{position:absolute;inset:0;z-index:5;display:flex;align-items:center;justify-content:center;padding:20px;background:var(--bt-main);overflow:auto;animation:bt-foot-in .2s ease}
+.bt-import-box{width:100%;max-width:340px;max-height:100%;display:flex;flex-direction:column;gap:10px;padding:20px;border:.5px solid var(--bt-line-2);border-radius:16px;background:var(--bt-main);box-shadow:0 12px 36px -12px rgba(0,0,0,.14);overflow:auto}
+.bt-import-title{font-size:15px;line-height:21px;font-weight:600}
+.bt-import-sub{font-size:12px;line-height:17px;color:var(--bt-ink-3);margin-top:-6px}
+.bt-import-text{font-size:13px;line-height:19px;color:var(--bt-ink-2);overflow-wrap:anywhere}
+.bt-import-list{max-height:180px;overflow:auto;border:.5px solid var(--bt-line);border-radius:10px;padding:4px 10px}
+.bt-import-line{display:flex;align-items:baseline;gap:8px;padding:4px 0;min-width:0}
+.bt-import-line-name{flex:none;max-width:60%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;color:var(--bt-ink)}
+.bt-import-line-count{flex:1;min-width:0;text-align:right;font-size:11.5px;color:var(--bt-ink-3);white-space:nowrap}
+.bt-import-line-reason{flex:1;min-width:0;font-size:11.5px;line-height:16px;color:var(--bt-ink-3);overflow-wrap:anywhere}
+.bt-import-note{font-size:12px;line-height:17px;color:var(--bt-ink-3)}
+.bt-import-warns{font-size:12px;color:var(--bt-ink-3)}
+.bt-import-warns summary{cursor:pointer;padding:2px 0}
+.bt-import-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:4px}
+.bt-import-primary{height:32px;padding:0 16px;border:0;border-radius:999px;background:var(--bt-accent);color:var(--bt-accent-ink);font:inherit;font-size:13px;cursor:pointer}
+.bt-import-primary:disabled{opacity:.55;cursor:default}
+.bt-import-plain{height:32px;padding:0 14px;border:.5px solid var(--bt-line-2);border-radius:999px;background:var(--bt-main);color:var(--bt-ink);font:inherit;font-size:13px;cursor:pointer}
+.bt-import-plain:hover{background:var(--bt-hover)}
+.bt-import-plain:disabled{opacity:.55;cursor:default}
/* A viewport too narrow to leave the conversation its room: the panel covers it,
and its close controls get a touch-sized target. */
.bt-panel[data-overlay]{width:100vw}
@@ -16010,7 +16286,16 @@ function apply(ctx) {
browserShow: (tabId, box) => browsers.show(tabId, box),
browserNavigate: (tabId, input) => browsers.navigate(tabId, input),
browserCommand: (tabId, name) => browsers.command(tabId, name),
- browserFocus: (tabId) => browsers.focus(tabId)
+ browserFocus: (tabId) => browsers.focus(tabId),
+ // Cookie imports, only where the bridge offers them (the desktop app): a file or an
+ // installed browser's profile is previewed, then applied into the Bot's storage key.
+ browserImport: typeof bridge.importSources === "function" ? {
+ sources: () => bridge.importSources(),
+ pick: () => bridge.importPick(),
+ live: (source, close) => bridge.importLive(source, close),
+ apply: (botId, pending) => bridge.importApply(`bot:${botId}`, pending),
+ cancel: (pending) => bridge.importCancel(pending)
+ } : null
});
}
actions.signInEntry = () => ctx.slots.entries?.("settings.models.sign-in")?.[0] ?? null;
diff --git a/ds-bot/src/client/browser-pane.js b/ds-bot/src/client/browser-pane.js
index e7d1e95a..2d242ab8 100644
--- a/ds-bot/src/client/browser-pane.js
+++ b/ds-bot/src/client/browser-pane.js
@@ -48,6 +48,9 @@ const StopIcon = icon(['M5.5 5.5l9 9M14.5 5.5l-9 9'])
const CloseIcon = icon(['M5.5 5.5l9 9M14.5 5.5l-9 9'])
const PlusTabIcon = icon(['M10 5v10M5 10h10'])
const LockIcon = icon(['M6.5 9V7a3.5 3.5 0 0 1 7 0v2', 'M5.5 9h9v7h-9z'])
+const ImportIcon = icon(['M10 3.5v8.5', 'M6 8.5l4 4 4-4', 'M4.5 14v1.5a1.5 1.5 0 0 0 1.5 1.5h8a1.5 1.5 0 0 0 1.5-1.5V14'])
+const FileIcon = icon(['M6 3.5h5.5L14.5 6.5v10H6z', 'M11 3.5v3.5h3.5'])
+const WindowIcon = icon(['M4 5h12v9.5H4z', 'M4 7.5h12'])
/** A page's favicon, or the globe while there is none or it fails to load. */
export function Favicon({ src, className }) {
@@ -200,9 +203,64 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages })
const input = useRef(null)
const [draft, setDraft] = useState(null)
+ // Cookie imports (the desktop app's bridge only): 'menu' lists the sources; a card
+ // stage then runs running → preview → result | error above the guest.
+ const imports = actions.browserImport
+ const [flow, setFlow] = useState(null)
+ // A mirrored flow: the cleanup on leaving the tab or the panel can still cancel
+ // an unconfirmed pending import.
+ const flowRef = useRef(null)
+ const [sources, setSources] = useState(null)
+ const [busy, setBusy] = useState(false)
+ const setFlowTracked = (next) => {
+ flowRef.current = typeof next === 'function' ? next(flowRef.current) : next
+ setFlow(flowRef.current)
+ }
+
// The guest goes on screen once the panel has landed and settled on its width,
- // and only over a page: the empty and error states are the panel's own.
- const showGuest = landed && !leaving && Boolean(page.url) && !page.error
+ // and only over a page: the empty, error and import states are the panel's own.
+ const showGuest = landed && !leaving && Boolean(page.url) && !page.error && flow === null
+
+ // Leaving the tab or the panel abandons an unconfirmed import.
+ useEffect(() => {
+ setFlowTracked(null)
+ return () => {
+ const id = typeof flowRef.current === 'object' && flowRef.current !== null ? flowRef.current.id : null
+ if (id) void imports?.cancel(id).catch(() => {})
+ }
+ // The flow controls live in this component; the effect re-runs only per tab.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [tabId])
+
+ const openImport = () => {
+ setFlowTracked('menu')
+ if (sources === null) void imports.sources().then(setSources, () => setSources([]))
+ }
+ const showPicked = (r) => {
+ if (r?.id) setFlowTracked({ stage: 'preview', id: r.id, preview: r.preview, restarted: r.restarted === true })
+ else if (r?.error) setFlowTracked({ stage: 'error', message: importError(r.error) })
+ else setFlowTracked(null)
+ }
+ const job = async (work) => {
+ setBusy(true)
+ try { await work() } catch (error) { setFlowTracked({ stage: 'error', message: String(error?.message ?? error) }) } finally { setBusy(false) }
+ }
+ const pickFile = () => job(async () => showPicked(await imports.pick()))
+ const pickSource = (source) => job(async () => {
+ const r = await imports.live(source.id)
+ if (r?.running) setFlowTracked({ stage: 'running', source })
+ else showPicked(r)
+ })
+ const closeAndImport = () => job(async () => showPicked(await imports.live(flowRef.current?.source?.id, true)))
+ const applyImport = () => job(async () => {
+ const report = await imports.apply(bot.id, flowRef.current?.id)
+ setFlowTracked((current) => ({ stage: 'result', report, label: current?.preview?.source?.label ?? null }))
+ })
+ const cancelImport = () => {
+ const id = typeof flow === 'object' && flow !== null ? flow.id : null
+ setFlowTracked(null)
+ if (id) void imports?.cancel(id).catch(() => {})
+ }
useLayoutEffect(() => {
const element = frame.current
if (!element || leaving || !tabId) { void actions.browserShow(null); return undefined }
@@ -264,21 +322,125 @@ function BrowserView({ bot, tabId, leaving, landed, actions, useBrowserPages })
onChange: event => setDraft(event.target.value),
onKeyDown: (event) => { if (event.key === 'Escape') { event.stopPropagation(); setDraft(null); event.currentTarget.blur() } },
})),
+ imports ? h('button', {
+ type: 'button', className: 'bt-icon-btn bt-import-btn', 'aria-label': t('Import cookies'), title: t('Import cookies'),
+ 'aria-expanded': flow === 'menu', disabled: busy,
+ onClick: () => { flow === 'menu' ? setFlowTracked(null) : openImport() },
+ }, h(ImportIcon)) : null,
page.loading ? h('span', { className: 'bt-browser-progress', 'aria-hidden': true }) : null),
h('div', { ref: frame, className: 'bt-browser-frame', 'data-guest': showGuest || undefined },
- page.error
+ flow === 'menu' ? h(ImportMenu, { sources, busy, onFile: pickFile, onSource: pickSource, onClose: () => setFlowTracked(null) }) : null,
+ typeof flow === 'object' && flow !== null
+ ? h(ImportCard, { flow, page, busy, onApply: applyImport, onCancel: cancelImport, onCloseAndImport: closeAndImport, onDone: () => setFlowTracked(null), onReload: () => actions.browserCommand(tabId, 'reload') })
+ : null,
+ flow === null && page.error
? h('div', { className: 'bt-browser-empty' },
h('div', { className: 'bt-browser-empty-title' }, t('This page didn’t load')),
h('div', { className: 'bt-browser-empty-text' }, t(page.error)),
page.url ? h('button', { type: 'button', className: 'bt-browser-retry', onClick: () => { void actions.browserNavigate(tabId, page.url) } }, t('Try again')) : null)
- : !page.url
+ : flow === null && !page.url
? h('div', { className: 'bt-browser-empty' },
h(BotMark, { bot, size: 48, state: 'idle', live: true }),
h('div', { className: 'bt-browser-empty-title' }, t("{name}'s browser", { name: bot.name })),
- h('div', { className: 'bt-browser-empty-text' }, t('Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.', { name: bot.name })))
+ h('div', { className: 'bt-browser-empty-text' }, t('Open a page here and {name} can read it with you. Logins and cookies stay with {name}; other Bots never see them.', { name: bot.name })),
+ imports ? h('button', { type: 'button', className: 'bt-browser-retry', onClick: openImport }, t('Import cookies')) : null)
: null))
}
+function importError(error) {
+ if (error === 'too-large') return t('That file is too large to be a cookie export.')
+ if (error === 'unreadable') return t('That file could not be read.')
+ return String(error)
+}
+
+// The sources popover: a cookie file, then every importable browser profile.
+function ImportMenu({ sources, busy, onFile, onSource, onClose }) {
+ useEffect(() => {
+ const close = (event) => { if (event.key === 'Escape') onClose() }
+ window.addEventListener('keydown', close)
+ return () => window.removeEventListener('keydown', close)
+ }, [onClose])
+ return h('div', { className: 'bt-import-menu', role: 'menu', 'aria-label': t('Import cookies') },
+ h('div', { className: 'bt-import-menu-title' }, t('Import cookies')),
+ h('button', { type: 'button', className: 'bt-import-item', role: 'menuitem', disabled: busy, onClick: onFile },
+ h(FileIcon, { className: 'bt-import-item-icon' }),
+ h('span', { className: 'bt-import-item-name' }, t('From a file…')),
+ h('span', { className: 'bt-import-item-sub' }, t('cookies.txt, JSON, storageState'))),
+ sources === null
+ ? h('div', { className: 'bt-import-menu-note' }, t('Loading…'))
+ : sources.length === 0
+ ? h('div', { className: 'bt-import-menu-note' }, t('No browsers found'))
+ : sources.map((source) => h('button', {
+ key: source.id, type: 'button', className: 'bt-import-item', role: 'menuitem', disabled: busy,
+ onClick: () => onSource(source),
+ },
+ h(WindowIcon, { className: 'bt-import-item-icon' }),
+ h('span', { className: 'bt-import-item-name' }, source.label),
+ h('span', { className: 'bt-import-item-sub' }, t('Copy of its cookies')))))
+}
+
+// The card that runs an import: close confirmation → preview → result | error.
+function ImportCard({ flow, page, busy, onApply, onCancel, onCloseAndImport, onDone, onReload }) {
+ const { stage } = flow
+ if (stage === 'running') {
+ return h('div', { className: 'bt-import-card' }, h('div', { className: 'bt-import-box' },
+ h('div', { className: 'bt-import-title' }, t('{name} is running', { name: flow.source.name })),
+ h('div', { className: 'bt-import-text' }, t('It must close for a moment so its cookies can be copied. It will reopen with your tabs.')),
+ h('div', { className: 'bt-import-actions' },
+ h('button', { type: 'button', className: 'bt-import-primary', disabled: busy, onClick: onCloseAndImport }, busy ? t('Closing…') : t('Close {name} and import', { name: flow.source.name })),
+ h('button', { type: 'button', className: 'bt-import-plain', disabled: busy, onClick: onCancel }, t('Cancel')))))
+ }
+ if (stage === 'error') {
+ return h('div', { className: 'bt-import-card' }, h('div', { className: 'bt-import-box' },
+ h('div', { className: 'bt-import-title' }, t('Import failed')),
+ h('div', { className: 'bt-import-text' }, flow.message),
+ h('div', { className: 'bt-import-actions' }, h('button', { type: 'button', className: 'bt-import-plain', onClick: onCancel }, t('Close')))))
+ }
+ if (stage === 'result') {
+ const { report } = flow
+ const problems = [...(report.dropped ?? []), ...(report.failed ?? [])]
+ return h('div', { className: 'bt-import-card' }, h('div', { className: 'bt-import-box' },
+ h('div', { className: 'bt-import-title' }, report.stored > 0 ? t('Imported {count} cookies', { count: report.stored }) : t('No cookies were stored')),
+ flow.label ? h('div', { className: 'bt-import-sub' }, flow.label) : null,
+ problems.length ? h('div', { className: 'bt-import-list' },
+ problems.slice(0, 8).map((item, index) => h('div', { key: index, className: 'bt-import-line' },
+ h('span', { className: 'bt-import-line-name' }, item.name ?? '—'),
+ h('span', { className: 'bt-import-line-reason' }, item.reason))),
+ problems.length > 8 ? h('div', { className: 'bt-import-line' }, h('span', { className: 'bt-import-line-reason' }, t('and {count} more', { count: problems.length - 8 }))) : null) : null,
+ h('div', { className: 'bt-import-actions' },
+ page.url ? h('button', { type: 'button', className: 'bt-import-plain', onClick: onReload }, t('Reload the page')) : null,
+ h('button', { type: 'button', className: 'bt-import-primary', onClick: onDone }, t('Done')))))
+ }
+ // stage === 'preview'
+ const { preview } = flow
+ return h('div', { className: 'bt-import-card' }, h('div', { className: 'bt-import-box' },
+ h('div', { className: 'bt-import-title' }, t('Import {count} cookies', { count: preview.cookies })),
+ h('div', { className: 'bt-import-sub' },
+ preview.source?.label ?? '',
+ flow.restarted ? ` · ${t('the browser was restarted')}` : ''),
+ preview.sites.length ? h('div', { className: 'bt-import-list' },
+ preview.sites.map((site) => h('div', { key: site.site, className: 'bt-import-line' },
+ h('span', { className: 'bt-import-line-name' }, site.site),
+ h('span', { className: 'bt-import-line-count' },
+ t('{count}', { count: site.cookies }),
+ site.session > 0 ? ` · ${t('{count} session', { count: site.session })}` : '')))) : null,
+ preview.skipped.length ? h('div', { className: 'bt-import-list' },
+ h('div', { className: 'bt-import-note' }, t('{count} skipped', { count: preview.skipped.length })),
+ preview.skipped.slice(0, 5).map((item, index) => h('div', { key: index, className: 'bt-import-line' },
+ h('span', { className: 'bt-import-line-name' }, item.name ?? item.where),
+ h('span', { className: 'bt-import-line-reason' }, item.reason))),
+ preview.skipped.length > 5 ? h('div', { className: 'bt-import-line' }, h('span', { className: 'bt-import-line-reason' }, t('and {count} more', { count: preview.skipped.length - 5 }))) : null) : null,
+ preview.warnings.length ? h('details', { className: 'bt-import-warns' },
+ h('summary', null, t('{count} adjusted', { count: preview.warnings.reduce((n, w) => n + w.count, 0) })),
+ preview.warnings.map((w, index) => h('div', { key: index, className: 'bt-import-line' },
+ h('span', { className: 'bt-import-line-reason' }, `${w.count} × ${w.message}`)))) : null,
+ preview.notes.includes('session-cookies') ? h('div', { className: 'bt-import-note' }, t('Cookies without an expiry stay until the app closes.')) : null,
+ preview.notes.includes('local-storage-left') ? h('div', { className: 'bt-import-note' }, t('Some sites also keep sign-in outside cookies; you may need to sign in again there.')) : null,
+ h('div', { className: 'bt-import-actions' },
+ h('button', { type: 'button', className: 'bt-import-primary', disabled: busy, onClick: onApply }, busy ? t('Importing…') : t('Import')),
+ h('button', { type: 'button', className: 'bt-import-plain', disabled: busy, onClick: onCancel }, t('Cancel')))))
+}
+
/**
* One aside for the Bot's details and browser. `pane` is
* `{ id, view: 'details'|'browser', renaming, tab }`; `id` is the Session id the
@@ -569,6 +731,36 @@ export const BROWSER_CSS = `
.bt-bcard-new:hover{color:var(--bt-ink);border-color:var(--bt-ink-3)}
.bt-bcard-new svg{width:14px;height:14px}
.bt-browser-empty-mark{display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center}
+/* Cookie imports */
+.bt-import-menu{position:absolute;top:6px;right:6px;z-index:6;width:236px;padding:6px;border-radius:16px;background:var(--bt-main);border:.5px solid var(--bt-line-2);box-shadow:0 10px 32px -8px rgba(0,0,0,.14),0 2px 8px rgba(0,0,0,.06);animation:bt-bcard-in .18s cubic-bezier(.16,1,.3,1) both}
+.bt-import-menu-title{padding:6px 10px 8px;font-size:11px;font-weight:500;letter-spacing:.02em;color:var(--bt-ink-3)}
+.bt-import-item{display:flex;align-items:center;gap:9px;width:100%;min-width:0;padding:8px 10px;border:0;border-radius:8px;background:none;color:var(--bt-ink);font:inherit;font-size:12.5px;text-align:left;cursor:pointer}
+.bt-import-item:hover{background:var(--bt-hover)}
+.bt-import-item:disabled{opacity:.5;cursor:default}
+.bt-import-item-icon{flex:none;color:var(--bt-ink-3)}
+.bt-import-item-icon svg,.bt-import-item svg{width:15px;height:15px}
+.bt-import-item-name{flex:none;max-width:55%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.bt-import-item-sub{flex:1;min-width:0;text-align:right;font-size:11px;color:var(--bt-ink-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.bt-import-menu-note{padding:8px 10px 10px;font-size:12px;color:var(--bt-ink-3)}
+.bt-import-card{position:absolute;inset:0;z-index:5;display:flex;align-items:center;justify-content:center;padding:20px;background:var(--bt-main);overflow:auto;animation:bt-foot-in .2s ease}
+.bt-import-box{width:100%;max-width:340px;max-height:100%;display:flex;flex-direction:column;gap:10px;padding:20px;border:.5px solid var(--bt-line-2);border-radius:16px;background:var(--bt-main);box-shadow:0 12px 36px -12px rgba(0,0,0,.14);overflow:auto}
+.bt-import-title{font-size:15px;line-height:21px;font-weight:600}
+.bt-import-sub{font-size:12px;line-height:17px;color:var(--bt-ink-3);margin-top:-6px}
+.bt-import-text{font-size:13px;line-height:19px;color:var(--bt-ink-2);overflow-wrap:anywhere}
+.bt-import-list{max-height:180px;overflow:auto;border:.5px solid var(--bt-line);border-radius:10px;padding:4px 10px}
+.bt-import-line{display:flex;align-items:baseline;gap:8px;padding:4px 0;min-width:0}
+.bt-import-line-name{flex:none;max-width:60%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;color:var(--bt-ink)}
+.bt-import-line-count{flex:1;min-width:0;text-align:right;font-size:11.5px;color:var(--bt-ink-3);white-space:nowrap}
+.bt-import-line-reason{flex:1;min-width:0;font-size:11.5px;line-height:16px;color:var(--bt-ink-3);overflow-wrap:anywhere}
+.bt-import-note{font-size:12px;line-height:17px;color:var(--bt-ink-3)}
+.bt-import-warns{font-size:12px;color:var(--bt-ink-3)}
+.bt-import-warns summary{cursor:pointer;padding:2px 0}
+.bt-import-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:4px}
+.bt-import-primary{height:32px;padding:0 16px;border:0;border-radius:999px;background:var(--bt-accent);color:var(--bt-accent-ink);font:inherit;font-size:13px;cursor:pointer}
+.bt-import-primary:disabled{opacity:.55;cursor:default}
+.bt-import-plain{height:32px;padding:0 14px;border:.5px solid var(--bt-line-2);border-radius:999px;background:var(--bt-main);color:var(--bt-ink);font:inherit;font-size:13px;cursor:pointer}
+.bt-import-plain:hover{background:var(--bt-hover)}
+.bt-import-plain:disabled{opacity:.55;cursor:default}
/* A viewport too narrow to leave the conversation its room: the panel covers it,
and its close controls get a touch-sized target. */
.bt-panel[data-overlay]{width:100vw}
diff --git a/ds-bot/src/client/i18n.js b/ds-bot/src/client/i18n.js
index 740fe199..fb1d52e5 100644
--- a/ds-bot/src/client/i18n.js
+++ b/ds-bot/src/client/i18n.js
@@ -242,6 +242,33 @@ const ZH = {
'Panel tabs': '面板标签页',
'Close panel': '关闭面板',
+ // Cookie imports
+ 'Import cookies': '导入 cookie',
+ 'From a file…': '从文件导入…',
+ 'cookies.txt, JSON, storageState': 'cookies.txt、JSON、storageState',
+ 'Copy of its cookies': '复制它的 cookie',
+ 'No browsers found': '没有找到浏览器',
+ '{name} is running': '{name} 正在运行',
+ 'It must close for a moment so its cookies can be copied. It will reopen with your tabs.': '需要先把它关掉一下才能复制 cookie,之后会自动重新打开并恢复你的标签页。',
+ 'Close {name} and import': '关闭 {name} 并导入',
+ 'Closing…': '正在关闭…',
+ 'Import {count} cookies': '导入 {count} 个 cookie',
+ 'the browser was restarted': '浏览器已重新打开',
+ '{count} skipped': '跳过 {count} 个',
+ '{count} session': '{count} 个会话',
+ '{count} adjusted': '调整了 {count} 个',
+ 'Cookies without an expiry stay until the app closes.': '没有过期时间的 cookie 会保留到应用关闭。',
+ 'Some sites also keep sign-in outside cookies; you may need to sign in again there.': '有些网站还把登录信息存在 cookie 之外,这些网站可能要重新登录。',
+ 'Importing…': '正在导入…',
+ 'Import': '导入',
+ 'Imported {count} cookies': '已导入 {count} 个 cookie',
+ 'No cookies were stored': '没有 cookie 被写入',
+ 'Reload the page': '刷新页面',
+ 'Import failed': '导入失败',
+ 'That file is too large to be a cookie export.': '这个文件太大了,不像是 cookie 导出文件。',
+ 'That file could not be read.': '这个文件读不了。',
+ '{count}': '{count} 个',
+
// Bot settings
'Choose a PNG, JPEG, WebP, or GIF image': '请选择 PNG、JPEG、WebP 或 GIF 图片',
'Choose an image smaller than 25 MB': '请选择小于 25 MB 的图片',
diff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.js
index d6bf06de..952ec60e 100644
--- a/ds-bot/src/client/index.js
+++ b/ds-bot/src/client/index.js
@@ -527,6 +527,15 @@ export function apply(ctx) {
browserNavigate: (tabId, input) => browsers.navigate(tabId, input),
browserCommand: (tabId, name) => browsers.command(tabId, name),
browserFocus: (tabId) => browsers.focus(tabId),
+ // Cookie imports, only where the bridge offers them (the desktop app): a file or an
+ // installed browser's profile is previewed, then applied into the Bot's storage key.
+ browserImport: typeof bridge.importSources === 'function' ? {
+ sources: () => bridge.importSources(),
+ pick: () => bridge.importPick(),
+ live: (source, close) => bridge.importLive(source, close),
+ apply: (botId, pending) => bridge.importApply(`bot:${botId}`, pending),
+ cancel: (pending) => bridge.importCancel(pending),
+ } : null,
})
}
// Whether AccountLauncher holds the shell's settings seat; FooterAccount steps aside if so.