diff --git a/packages/tabbit/README.md b/packages/tabbit/README.md index 3927616..9501256 100644 --- a/packages/tabbit/README.md +++ b/packages/tabbit/README.md @@ -1,7 +1,7 @@ # Tabbit for magpie [Tabbit](https://web.tabbit.com) as a provider in [magpie](https://usemagpie.ai) -(and OpenCode). It signs in with the Tabbit Browser account already on this +(and OpenCode). It signs in with the Tabbit account already on this computer, lists the account's real model catalog, and answers turns through Tabbit's own chat API — so an agent behind magpie can pick `tabbit/Default`, `tabbit/DeepSeek-V4.1-Flash`, `tabbit/GLM-5.3-Flash` and the rest like any @@ -12,7 +12,7 @@ other provider, with the account's allowance, fallbacks and usage card. ```sh magpie plugin add @magpie-community/opencode-tabbit-auth # from the community list # from this source tree instead: magpie plugin add . -magpie plugin login tabbit # pick “Read Tabbit Browser sign-in (macOS)” +magpie plugin login tabbit # pick “Read the Tabbit app's sign-in (macOS)” magpie provider test tabbit # ✓ chat · Default ``` @@ -42,7 +42,7 @@ Tabbit's sign-in is a `token` cookie: an RS256 JWT issued by | Method | What it does | |---|---| -| **Read Tabbit Browser sign-in** (macOS) | Finds the cookie store Tabbit Browser keeps (`~/Library/Application Support/Tabbit Browser/Default/Cookies`), reads the `token` cookie, and decrypts it with the password in the login keychain under `Tabbit Browser Safe Storage`. Nothing is copied by hand; the browser does not have to be closed — the database is copied before it is read. | +| **Read the Tabbit app's sign-in** (macOS) | Finds the cookie store Tabbit keeps, reads the `token` cookie, and decrypts it with the password in the login keychain. The international build (Tabbit.app) keeps its store in `~/Library/Application Support/Tabbit` and the password under `Tabbit Safe Storage`; the China build (Tabbit Browser.app) in `~/Library/Application Support/Tabbit Browser`, under `Tabbit Browser Safe Storage`. Each store is read with its own build's item first, then the other's. macOS asks once for Keychain access: click Allow (or Always Allow). Nothing is copied by hand; the browser does not have to be closed — the database is copied before it is read. | | **Paste Tabbit token** | For anything the first method can't reach (Windows or Linux, a browser profile kept somewhere else). In Tabbit Browser, open `web.tabbit.com` (or `web.tabbit.ai` for an international account) and read the `token` cookie from the developer tools; paste it whole. | A pasted value may be the bare JWT or a whole `name=value; name=value` cookie diff --git a/packages/tabbit/index.mjs b/packages/tabbit/index.mjs index d9b7017..3242a46 100644 --- a/packages/tabbit/index.mjs +++ b/packages/tabbit/index.mjs @@ -476,14 +476,14 @@ function createPlugin() { methods: [ { type: "oauth", - label: "Read Tabbit Browser sign-in (macOS)", + label: "Read the Tabbit app's sign-in (macOS)", authorize: () => ({ url: "", - instructions: "Reads the sign-in Tabbit Browser already has on this computer. Nothing is copied by hand.", + instructions: "Reads the sign-in the Tabbit app already has on this computer. When macOS asks for Keychain access, click Allow. Nothing is copied by hand.", method: "auto", callback: async () => { try { - const sign = desktopSignIn() + const sign = await desktopSignIn() return { type: "success", key: sign.key, accountId: sign.userId, metadata: { userId: sign.userId, source: "desktop", site: sign.site } } } catch (error) { return { type: "failed", error: String(error?.message ?? error) } diff --git a/packages/tabbit/package.json b/packages/tabbit/package.json index 5557760..d58f30e 100644 --- a/packages/tabbit/package.json +++ b/packages/tabbit/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-tabbit-auth", - "version": "0.1.2", + "version": "0.1.3", "description": "Tabbit (web.tabbit.com and web.tabbit.ai) as a magpie / OpenCode provider: live model catalog, cookie sign-in, chat completions, cycle usage and the daily check-in", "type": "module", "main": "./opencode.mjs", diff --git a/packages/tabbit/src/cookie.mjs b/packages/tabbit/src/cookie.mjs index 2fb3a73..af2c6d5 100644 --- a/packages/tabbit/src/cookie.mjs +++ b/packages/tabbit/src/cookie.mjs @@ -1,15 +1,23 @@ // Reading the sign-in out of the Tabbit desktop app, without opening it. // -// Tabbit Browser keeps the same Chromium cookie store every Chromium does: -// macOS ~/Library/Application Support/Tabbit Browser/Default/Cookies -// and protects the value with the platform's own key. The database is copied -// before it is read: a running browser holds a lock on a WAL, and reading the -// live file gives a half-written row. The copy is removed again in a finally: -// it holds every site's cookies, and a copy left behind each sign-in would -// leave that in the temp folder. +// Tabbit ships as two macOS builds, each a Chromium fork with its own data +// directory and its own Keychain item (read out of 1.16.27's framework: both +// builds carry the same code, and a flag set at start-up picks the names): +// Tabbit.app com.tabbit-ai.Tabbit (international, tabbit.ai) +// ~/Library/Application Support/Tabbit/Default/Cookies +// Keychain service "Tabbit Safe Storage", account "Tabbit" +// Tabbit Browser.app com.tab-browser.Tabbit (China, tabbit.com) +// ~/Library/Application Support/Tabbit Browser/Default/Cookies +// Keychain service "Tabbit Browser Safe Storage", account "Tabbit Browser" +// Each store is read with its own build's item first and the other's after, +// so a store in a place this doesn't know still finds its key. // -// macOS: `Tabbit Browser Safe Storage` in the login keychain holds the -// password, and a Chromium cookie is AES-128-CBC under +// The database is copied before it is read: a running browser holds a lock +// on a WAL, and reading the live file gives a half-written row. The copy is +// removed again in a finally: it holds every site's cookies, and a copy left +// behind each sign-in would leave that in the temp folder. +// +// A Chromium cookie on macOS is AES-128-CBC under // PBKDF2-HMAC-SHA1(password, "saltysalt", 1003, 16 bytes) with a sixteen-space // IV, prefixed `v10`, padded PKCS#7, and (on Chromium 24 and later) a 32-byte // SHA-256 of the host in front of the plaintext. @@ -22,18 +30,19 @@ import fs from "node:fs" import os from "node:os" import path from "node:path" import crypto from "node:crypto" -import { execFileSync } from "node:child_process" +import { execFile } from "node:child_process" // The two sites a Tabbit account can belong to (see SITES in api.mjs), the // Chinese one first. A browser signed in to either keeps the token under // that site's host, so the host it was found under names the account's site. export const HOSTS = ["web.tabbit.com", "web.tabbit.ai"] export const HOST = HOSTS[0] -const SAFE_STORAGE = "Tabbit Browser Safe Storage" +// The Keychain services the two builds keep their storage password under. +export const SAFE_STORAGE = { intl: "Tabbit Safe Storage", cn: "Tabbit Browser Safe Storage" } -// profileDirs are the places Tabbit Browser has kept its profile, newest -// name first. The browser's own data directory is not the same as the -// user-data directory the old Tabbit client used, so both are listed. +// profileDirs are the places Tabbit keeps its profile: the China build's +// "Tabbit Browser" and the international build's "Tabbit" (with the old +// client's "Tabbit/User Data"). export function profileDirs(env = process.env, home = os.homedir()) { const roots = [env.TABBIT_PROFILE_DIR, env.TABBIT_USER_DATA_DIR].filter(Boolean) if (process.platform === "darwin") { @@ -52,15 +61,33 @@ export function profileDirs(env = process.env, home = os.homedir()) { return [...new Set(roots)] } -// cookieStore finds the SQLite file, preferring a profile called Default. -export function cookieStore(dirs = profileDirs()) { +// cookieStores lists every SQLite file found, one per profile root, each +// preferring a profile called Default. +export function cookieStores(dirs = profileDirs()) { + const found = [] for (const dir of dirs) { for (const rel of [path.join("Default", "Cookies"), path.join("Network", "Cookies"), "Cookies"]) { const file = path.join(dir, rel) - if (fs.existsSync(file)) return file + if (fs.existsSync(file)) { + found.push(file) + break + } } } - return null + return [...new Set(found)] +} + +// cookieStore is the first of them. +export function cookieStore(dirs = profileDirs()) { + return cookieStores(dirs)[0] ?? null +} + +// safeStorageNames is the Keychain services to try for one store, its own +// build's first: a path through a "Tabbit Browser" folder is the China +// build's, anything else the international one's. +export function safeStorageNames(store = "") { + const parts = String(store).split(/[\\/]+/) + return parts.includes("Tabbit Browser") ? [SAFE_STORAGE.cn, SAFE_STORAGE.intl] : [SAFE_STORAGE.intl, SAFE_STORAGE.cn] } // copyStore copies the database (and its WAL, when present) to a temporary @@ -74,18 +101,59 @@ export function copyStore(file, tmp = fs.mkdtempSync(path.join(os.tmpdir(), "tab return copy } -// keychainPassword asks the login keychain for the browser's storage -// password. A keychain that is locked, or a prompt the user dismisses, -// makes this throw and the caller falls back to a pasted value. -export function keychainPassword(service = SAFE_STORAGE) { - const out = execFileSync("security", ["find-generic-password", "-s", service, "-w"], { - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - timeout: 15_000, +// runSecurity runs macOS's `security` with the arguments as separate argv +// entries (no shell, so a name with spaces is one argument). It never +// rejects: the caller reads the exit status. The timeout leaves the user time +// to answer the Keychain prompt; magpie waits ten minutes for a sign-in. +export function runSecurity(args, { timeout = 120_000 } = {}) { + return new Promise((resolve) => { + execFile("security", args, { encoding: "utf8", timeout, maxBuffer: 1 << 20 }, (error, stdout, stderr) => { + resolve({ + status: error ? (typeof error.code === "number" ? error.code : null) : 0, + timedOut: Boolean(error?.killed), + stdout: String(stdout ?? ""), + stderr: String(stderr ?? "").trim(), + error: error && typeof error.code !== "number" && !error.killed ? String(error.message ?? error) : "", + }) + }) }) - const password = String(out).replace(/\r?\n$/, "") - if (!password) throw new Error(`the keychain holds no password under "${service}"`) - return password +} + +// What `security` exits with is the low byte of the OSStatus. +const NOT_FOUND = 44 // errSecItemNotFound (-25300) +const CANCELED = 128 // errSecUserCanceled (-128) +const AUTH_FAILED = 51 // errSecAuthFailed (-25293): the prompt was denied +const NO_UI = 36 // errSecInteractionNotAllowed (-25308): locked, no prompt possible + +const PASTE = "or use “Paste Tabbit token” instead" + +// keychainPassword asks the login keychain for the browser's storage +// password, trying each service in turn. An item that isn't there moves on +// to the next name; a prompt the user turned down stops at once and says so. +export async function keychainPassword(names = [SAFE_STORAGE.intl, SAFE_STORAGE.cn], { run = runSecurity } = {}) { + for (const service of names) { + const r = await run(["find-generic-password", "-s", service, "-w"]) + if (r.status === 0) { + const password = String(r.stdout).replace(/\r?\n$/, "") + if (password) return password + continue + } + if (r.status === NOT_FOUND) continue + if (r.timedOut) { + throw new Error(`macOS asked for Keychain access to “${service}” and got no answer in time; try again and click Allow (or Always Allow), ${PASTE}`) + } + if (r.status === CANCELED || r.status === AUTH_FAILED) { + throw new Error(`Keychain access to “${service}” was denied; try again and click Allow (or Always Allow) when macOS asks, ${PASTE}`) + } + if (r.status === NO_UI) { + throw new Error(`the login keychain is locked and macOS can't ask for “${service}” right now; unlock it and try again, ${PASTE}`) + } + const why = r.stderr || r.error || `security exited with ${r.status}` + throw new Error(`reading “${service}” from the login keychain failed (${why}), ${PASTE}`) + } + throw new Error( + `Tabbit's password isn't in the login keychain (looked for ${names.map((n) => `“${n}”`).join(" and ")}); open Tabbit, sign in there, and try again, ${PASTE}`, + ) } // decryptValue turns one `encrypted_value` blob into text. @@ -132,34 +200,44 @@ function require_node_sqlite() { } // desktopSignIn returns the cookie header and what it belongs to, or throws -// with the reason a caller can show. +// with the reason a caller can show, and what to do about it. // -// `platform` and `tmpParent` are for the tests: the same code path runs with a -// fixture store under a temp parent the test can look into afterwards. -export function desktopSignIn({ dirs = profileDirs(), hosts = HOSTS, store, password, tmpParent, platform = process.platform } = {}) { +// `platform`, `tmpParent` and `run` are for the tests: the same code path +// runs with a fixture store under a temp parent the test can look into +// afterwards, and a fake `security`. +export async function desktopSignIn({ dirs = profileDirs(), hosts = HOSTS, store, password, tmpParent, platform = process.platform, run } = {}) { if (platform !== "darwin") { - throw new Error(`reading Tabbit Browser's cookies is macOS-only; on ${platform} paste the token instead`) + throw new Error(`reading Tabbit's cookies is macOS-only; on ${platform} paste the token instead`) } - const file = store || cookieStore(dirs) - if (!file) throw new Error(`no Tabbit Browser cookie store found; looked in ${dirs.join(", ")}`) + const files = store ? [store] : cookieStores(dirs) + if (!files.length) throw new Error(`Tabbit isn't installed here, or hasn't been opened yet (looked in ${dirs.join(", ")}); open Tabbit, sign in there, and try again, ${PASTE}`) + for (const file of files) { + const found = readToken(file, hosts, tmpParent) + if (!found) continue + const { rows, host } = found + const token = rows.find((r) => r.name === "token") + const uid = rows.find((r) => r.name === "user_id") + const plain = token.value?.startsWith("ey") && (!uid || uid.value || !uid.encrypted?.length) + const secret = plain ? "" : (password ?? (await keychainPassword(safeStorageNames(file), run ? { run } : undefined))) + const value = token.value?.startsWith("ey") ? token.value : decryptValue(token.encrypted, { password: secret, host }) + const uidValue = uid?.value || (uid?.encrypted?.length ? safeDecrypt(uid.encrypted, secret, host) : "") + const header = [`token=${value}`, uidValue && `user_id=${uidValue}`, uidValue && `SAPISID=${uidValue}`, "managed=tab_browser"].filter(Boolean).join("; ") + return { key: header, userId: uidValue, store: file, site: `https://${host}` } + } + throw new Error(`Tabbit is not signed in to ${hosts.join(" or ")}; open Tabbit, sign in there, and try again, ${PASTE}`) +} + +// readToken reads one store's token and user_id rows from a temporary copy, +// trying each host, and removes the copy before it returns. +function readToken(file, hosts, tmpParent) { const dir = fs.mkdtempSync(path.join(tmpParent ?? os.tmpdir(), "tabbit-cookies-")) try { const copy = copyStore(file, dir) - let host = hosts[0] - let rows = [] - for (const candidate of hosts) { - rows = readCookies(copy, { host: candidate }) - host = candidate - if (rows.some((r) => r.name === "token")) break + for (const host of hosts) { + const rows = readCookies(copy, { host }) + if (rows.some((r) => r.name === "token")) return { rows, host } } - const token = rows.find((r) => r.name === "token") - if (!token) throw new Error(`Tabbit Browser is not signed in to ${hosts.join(" or ")}`) - const secret = password ?? keychainPassword() - const value = token.value?.startsWith("ey") ? token.value : decryptValue(token.encrypted, { password: secret, host }) - const uid = rows.find((r) => r.name === "user_id") - const uidValue = uid?.value || (uid?.encrypted ? safeDecrypt(uid.encrypted, secret, host) : "") - const header = [`token=${value}`, uidValue && `user_id=${uidValue}`, uidValue && `SAPISID=${uidValue}`, "managed=tab_browser"].filter(Boolean).join("; ") - return { key: header, userId: uidValue, store: file, site: `https://${host}` } + return null } finally { fs.rmSync(dir, { recursive: true, force: true }) } diff --git a/packages/tabbit/tests/cookie.test.mjs b/packages/tabbit/tests/cookie.test.mjs index bef9861..27b4ba6 100644 --- a/packages/tabbit/tests/cookie.test.mjs +++ b/packages/tabbit/tests/cookie.test.mjs @@ -11,7 +11,7 @@ import crypto from "node:crypto" import fs from "node:fs" import os from "node:os" import path from "node:path" -import { decryptValue, cookieStore, copyStore, profileDirs, readCookies, desktopSignIn } from "../src/cookie.mjs" +import { decryptValue, cookieStore, cookieStores, copyStore, profileDirs, readCookies, desktopSignIn, keychainPassword, safeStorageNames, SAFE_STORAGE } from "../src/cookie.mjs" const HOST = "web.tabbit.com" const PASSWORD = "test-password" @@ -127,27 +127,27 @@ function storeWith(token) { return file } -withCleanup("a successful desktop sign-in leaves no copy of the cookie store", () => { +withCleanup("a successful desktop sign-in leaves no copy of the cookie store", async () => { const file = storeWith("tok-desktop") if (!file) return const parent = tmp("tabbit-parent-") - const sign = desktopSignIn({ store: file, password: PASSWORD, tmpParent: parent, platform: "darwin" }) + const sign = await desktopSignIn({ store: file, password: PASSWORD, tmpParent: parent, platform: "darwin" }) assert.match(sign.key, /token=tok-desktop/) assert.equal(sign.userId, "u-9") assert.deepEqual(fs.readdirSync(parent), []) }) -withCleanup("a failed desktop sign-in leaves no copy either", () => { +withCleanup("a failed desktop sign-in leaves no copy either", async () => { const file = storeWith(null) if (!file) return const parent = tmp("tabbit-parent-") - assert.throws(() => desktopSignIn({ store: file, password: PASSWORD, tmpParent: parent, platform: "darwin" }), /not signed in/) + await assert.rejects(() => desktopSignIn({ store: file, password: PASSWORD, tmpParent: parent, platform: "darwin" }), /not signed in/) assert.deepEqual(fs.readdirSync(parent), []) }) // An international account's browser keeps the token under web.tabbit.ai, // sealed with that host's hash (#833). -withCleanup("a browser signed in to web.tabbit.ai signs in there, and says so", () => { +withCleanup("a browser signed in to web.tabbit.ai signs in there, and says so", async () => { let DatabaseSync try { DatabaseSync = globalThis.process.getBuiltinModule("node:sqlite").DatabaseSync @@ -162,21 +162,146 @@ withCleanup("a browser signed in to web.tabbit.ai signs in there, and says so", db.prepare("insert into cookies values (?,?,?,?)").run(AI, "token", "", seal("tok-intl", { host: AI })) db.prepare("insert into cookies values (?,?,?,?)").run(AI, "user_id", "", seal("u-intl", { host: AI })) db.close() - const sign = desktopSignIn({ store: file, password: PASSWORD, tmpParent: tmp("tabbit-parent-"), platform: "darwin" }) + const sign = await desktopSignIn({ store: file, password: PASSWORD, tmpParent: tmp("tabbit-parent-"), platform: "darwin" }) assert.match(sign.key, /^token=tok-intl; user_id=u-intl;/) assert.equal(sign.userId, "u-intl") assert.equal(sign.site, "https://web.tabbit.ai") }) -withCleanup("a browser signed in to web.tabbit.com still signs in there", () => { +withCleanup("a browser signed in to web.tabbit.com still signs in there", async () => { const file = storeWith("tok-com") if (!file) return - const sign = desktopSignIn({ store: file, password: PASSWORD, tmpParent: tmp("tabbit-parent-"), platform: "darwin" }) + const sign = await desktopSignIn({ store: file, password: PASSWORD, tmpParent: tmp("tabbit-parent-"), platform: "darwin" }) assert.match(sign.key, /token=tok-com/) assert.equal(sign.site, "https://web.tabbit.com") }) -test("the desktop method is macOS-only, and says so elsewhere", () => { - assert.throws(() => desktopSignIn({ store: "/nonexistent/Cookies", platform: "linux" }), /macOS-only/) - assert.throws(() => desktopSignIn({ store: "/nonexistent/Cookies", platform: "win32" }), /macOS-only/) +test("the desktop method is macOS-only, and says so elsewhere", async () => { + await assert.rejects(() => desktopSignIn({ store: "/nonexistent/Cookies", platform: "linux" }), /macOS-only/) + await assert.rejects(() => desktopSignIn({ store: "/nonexistent/Cookies", platform: "win32" }), /macOS-only/) +}) + +// ---- The Keychain (shiqi_40904 on Discord: "Command failed: security +// find-generic-password -s Tabbit Browser Safe Storage -w"). The +// international build, Tabbit.app, keeps its password under "Tabbit Safe +// Storage"; only the China build, Tabbit Browser.app, uses "Tabbit Browser +// Safe Storage". A fake `security` stands in for the Keychain: nothing here +// reads this machine's. + +// fakeSecurity answers like macOS's `security`: the password for a service it +// holds, exit 44 (errSecItemNotFound) for one it doesn't, or a fixed answer. +function fakeSecurity(items, { answer } = {}) { + const calls = [] + const run = async (args) => { + calls.push(args) + const service = args[args.indexOf("-s") + 1] + if (answer) return { stdout: "", stderr: "", error: "", timedOut: false, ...answer(service) } + if (service in items) return { status: 0, stdout: items[service] + "\n", stderr: "", error: "", timedOut: false } + return { status: 44, stdout: "", stderr: "security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.", error: "", timedOut: false } + } + return { run, calls } +} + +// layoutStore builds a store where a build keeps it: `//Default/Cookies`. +function layoutStore(dir, token, { host = HOST, password = PASSWORD } = {}) { + let DatabaseSync + try { + DatabaseSync = globalThis.process.getBuiltinModule("node:sqlite").DatabaseSync + } catch { + return null + } + const root = tmp("tabbit-layout-") + const profile = path.join(root, dir) + fs.mkdirSync(path.join(profile, "Default"), { recursive: true }) + const file = path.join(profile, "Default", "Cookies") + const db = new DatabaseSync(file) + db.exec("create table cookies(host_key text, name text, value text, encrypted_value blob)") + if (token) { + db.prepare("insert into cookies values (?,?,?,?)").run(host, "token", "", seal(token, { host, password })) + db.prepare("insert into cookies values (?,?,?,?)").run(host, "user_id", "", seal("u-" + token, { host, password })) + } + db.close() + return { profile, file } +} + +test("each build's store asks its own Keychain item first", () => { + assert.deepEqual(safeStorageNames("/Users/u/Library/Application Support/Tabbit/Default/Cookies"), ["Tabbit Safe Storage", "Tabbit Browser Safe Storage"]) + assert.deepEqual(safeStorageNames("/Users/u/Library/Application Support/Tabbit Browser/Default/Cookies"), ["Tabbit Browser Safe Storage", "Tabbit Safe Storage"]) + assert.deepEqual(SAFE_STORAGE, { intl: "Tabbit Safe Storage", cn: "Tabbit Browser Safe Storage" }) +}) + +test("the service name reaches security as one argument", async () => { + const { run, calls } = fakeSecurity({ "Tabbit Browser Safe Storage": "pw" }) + assert.equal(await keychainPassword(["Tabbit Browser Safe Storage"], { run }), "pw") + assert.deepEqual(calls[0], ["find-generic-password", "-s", "Tabbit Browser Safe Storage", "-w"]) +}) + +test("a service the Keychain doesn't hold moves on to the next name", async () => { + const { run, calls } = fakeSecurity({ "Tabbit Safe Storage": "intl-pw" }) + assert.equal(await keychainPassword(["Tabbit Browser Safe Storage", "Tabbit Safe Storage"], { run }), "intl-pw") + assert.equal(calls.length, 2) +}) + +test("no item under any name says to open Tabbit and sign in", async () => { + const { run } = fakeSecurity({}) + await assert.rejects( + () => keychainPassword(["Tabbit Safe Storage", "Tabbit Browser Safe Storage"], { run }), + (e) => /isn't in the login keychain/.test(e.message) && /“Tabbit Safe Storage” and “Tabbit Browser Safe Storage”/.test(e.message) && /open Tabbit, sign in there/.test(e.message) && /Paste Tabbit token/.test(e.message) && !/Command failed/.test(e.message), + ) +}) + +for (const [status, name] of [[128, "cancelled"], [51, "denied"]]) { + test(`a Keychain prompt the user ${name} says to click Allow, and asks nothing more`, async () => { + const { run, calls } = fakeSecurity({}, { answer: () => ({ status, stderr: "security: SecKeychainSearchCopyNext: User canceled the operation." }) }) + await assert.rejects(() => keychainPassword(["Tabbit Safe Storage", "Tabbit Browser Safe Storage"], { run }), /was denied; try again and click Allow/) + assert.equal(calls.length, 1) + }) +} + +test("an unanswered prompt, a locked keychain and anything else each say what happened", async () => { + let r = fakeSecurity({}, { answer: () => ({ status: null, timedOut: true }) }) + await assert.rejects(() => keychainPassword(["Tabbit Safe Storage"], { run: r.run }), /got no answer in time/) + r = fakeSecurity({}, { answer: () => ({ status: 36 }) }) + await assert.rejects(() => keychainPassword(["Tabbit Safe Storage"], { run: r.run }), /keychain is locked/) + r = fakeSecurity({}, { answer: () => ({ status: 1, stderr: "security: something odd" }) }) + await assert.rejects(() => keychainPassword(["Tabbit Safe Storage"], { run: r.run }), /reading “Tabbit Safe Storage” from the login keychain failed \(security: something odd\)/) +}) + +withCleanup("the international build signs in with its Tabbit Safe Storage item (the report)", async () => { + const s = layoutStore("Tabbit", "tok-intl-app", { host: "web.tabbit.ai", password: "intl-pw" }) + if (!s) return + const { run, calls } = fakeSecurity({ "Tabbit Safe Storage": "intl-pw" }) + const sign = await desktopSignIn({ dirs: [s.profile], run, tmpParent: tmp("tabbit-parent-"), platform: "darwin" }) + assert.match(sign.key, /^token=tok-intl-app; user_id=u-tok-intl-app;/) + assert.equal(sign.site, "https://web.tabbit.ai") + assert.equal(calls[0][2], "Tabbit Safe Storage") +}) + +withCleanup("the China build signs in with its Tabbit Browser Safe Storage item", async () => { + const s = layoutStore("Tabbit Browser", "tok-cn-app", { password: "cn-pw" }) + if (!s) return + const { run, calls } = fakeSecurity({ "Tabbit Browser Safe Storage": "cn-pw" }) + const sign = await desktopSignIn({ dirs: [s.profile], run, tmpParent: tmp("tabbit-parent-"), platform: "darwin" }) + assert.match(sign.key, /^token=tok-cn-app;/) + assert.equal(calls.length, 1) + assert.equal(calls[0][2], "Tabbit Browser Safe Storage") +}) + +withCleanup("with both builds installed, the one that is signed in is read", async () => { + const cn = layoutStore("Tabbit Browser", null) + const intl = layoutStore("Tabbit", "tok-second", { host: "web.tabbit.ai", password: "intl-pw" }) + if (!cn || !intl) return + assert.deepEqual(cookieStores([cn.profile, intl.profile]), [cn.file, intl.file]) + const { run } = fakeSecurity({ "Tabbit Safe Storage": "intl-pw" }) + const sign = await desktopSignIn({ dirs: [cn.profile, intl.profile], run, tmpParent: tmp("tabbit-parent-"), platform: "darwin" }) + assert.match(sign.key, /^token=tok-second;/) + assert.equal(sign.store, intl.file) +}) + +withCleanup("no store and no sign-in each say to open Tabbit and sign in", async () => { + const missing = path.join(tmp("tabbit-none-"), "Tabbit") + await assert.rejects(() => desktopSignIn({ dirs: [missing], platform: "darwin", run: fakeSecurity({}).run }), /open Tabbit, sign in there, and try again/) + const s = layoutStore("Tabbit", null) + if (!s) return + await assert.rejects(() => desktopSignIn({ dirs: [s.profile], platform: "darwin", run: fakeSecurity({}).run, tmpParent: tmp("tabbit-parent-") }), /not signed in to web\.tabbit\.com or web\.tabbit\.ai; open Tabbit, sign in there/) })