Files
plugins/packages/tabbit/tests/cookie.test.mjs
T
yetone 50bb3f5ad2 tabbit 0.1.1: international accounts are served by web.tabbit.ai (#833)
Tabbit runs two sites with one API: web.tabbit.com (China) and
web.tabbit.ai (international). Each site refuses the other's tokens.
The plugin only knew .com, so every international account was refused
with 401 "invalid bearer". The reporter saw this as a lost sign-in.

The site is now picked by the account, with nothing to set:
- A desktop sign-in reads the token from whichever host's cookie has
  it, web.tabbit.com or web.tabbit.ai. The host's own hash prefix
  unseals it, and the site is recorded in the account's metadata.site.
- A pasted token, or an account from before this change, starts on
  .com. If .com refuses it, the same request is sent once to .ai.
  - If .ai accepts it, the token is remembered as .ai's for the process.
  - If both sites refuse it, it stays on .com and is reported as an
    expired sign-in, as before.
  - If .ai can't be reached, nothing is settled.
  - A 429 or 5xx settles nothing either.
- The catalog answers any token, so it settles nothing. The model list
  asks usage first to learn the site, so an international account gets
  .ai's catalog.
- Origin and Referer follow the site.

Not fixed here: .ai answers a chat run with 429 code 492 ("Welcome to
Tabbit Browser"), its browser sign-in gate. Sign-in, the model list,
usage and check-in work on .ai. Turns get the 429 passed through as it
is, not marked as a lost sign-in. The README says so.

Run on mote (Bun 1.4.2, Node 22, HOME=$(mktemp -d)):
- packages/tabbit: bun test 70 pass, 0 fail; node --test 70 pass, 0 fail.
- bun scripts/check.mjs tabbit: ok.
- Repo-wide bun test: 6797 pass, 20 skip, 0 fail (6817 tests, 492 files).

The new tests use the reporter's literal bodies from #833 (the 401
"invalid bearer" and the 492 gate JSON) against a stubbed fetch, so
nothing reaches the network.
- Against the old src (the new tests kept), 8 of the 9 site tests
  fail on their assertions, and so do both new cookie tests ("not
  signed in to web.tabbit.com"). The one that passes is the .com
  regression test, as it should.

Broken by hand, each change red in exactly the test meant for it:
- (a) no learning when both sites refuse: "a token both sites refuse".
- (b) an unreachable site settles .com: "web.tabbit.ai out of reach".
- (c) no usage probe before the catalog: "an international token's
  model list".
- (d) learning on any non-refused answer: "a 5xx or the catalog
  settles no site".

Not tried:
- a real web.tabbit.ai or web.tabbit.com account;
- a real Tabbit Browser cookie store holding a web.tabbit.ai row (its
  host_key is assumed to be web.tabbit.ai);
- getting past the 492 gate on .ai.
No magpie-side change is needed: magpie has no tabbit mover or min.

Reported-by: Beyfish
2026-11-07 19:57:13 +08:00

183 lines
7.4 KiB
JavaScript

// The cookie store: a synthetic Chromium v10 blob, decrypted with a known
// password, and the store lookup that finds the file.
//
// Every temp directory a test makes is removed before the test returns: these
// build whole cookie stores, and a test run must not leave one behind — the
// same point the sign-in copy itself makes.
import test from "node:test"
import assert from "node:assert/strict"
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"
const HOST = "web.tabbit.com"
const PASSWORD = "test-password"
const made = []
function tmp(prefix) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
made.push(dir)
return dir
}
// withCleanup runs a test body and removes every temp directory it made.
function withCleanup(name, body) {
return test(name, async (ctx) => {
try {
await body(ctx)
} finally {
for (const dir of made.splice(0)) fs.rmSync(dir, { recursive: true, force: true })
}
})
}
// seal makes the blob Chromium's own macOS encryption makes: AES-128-CBC
// under the keychain password, `v10`, a 32-byte SHA-256 of the host in
// front of the plaintext, and PKCS#7 padding.
function seal(plaintext, { password = PASSWORD, host = HOST } = {}) {
const key = crypto.pbkdf2Sync(password, "saltysalt", 1003, 16, "sha1")
const body = Buffer.concat([crypto.createHash("sha256").update(host).digest(), Buffer.from(plaintext, "utf8")])
const pad = 16 - (body.length % 16)
const padded = Buffer.concat([body, Buffer.alloc(pad, pad)])
const cipher = crypto.createCipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20))
cipher.setAutoPadding(false)
return Buffer.concat([Buffer.from("v10", "latin1"), cipher.update(padded), cipher.final()])
}
test("a v10 blob decrypts to the plaintext", () => {
const token = "eyJhbGciOiJSUzI1NiJ9.payload.sig"
assert.equal(decryptValue(seal(token), { password: PASSWORD }), token)
})
test("the wrong password does not yield a plausible value", () => {
let value = null
try {
value = decryptValue(seal("hello"), { password: "wrong" })
} catch {
/* a wrong key usually throws on the padding */
}
assert.notEqual(value, "hello")
})
test("a blob that isn't v10 is refused", () => {
assert.throws(() => decryptValue(Buffer.from("v20xxxx"), { password: PASSWORD }), /unsupported cookie encryption/)
})
test("profileDirs honours an explicit override first", () => {
const dirs = profileDirs({ TABBIT_PROFILE_DIR: "/tmp/one" }, "/home/u")
assert.equal(dirs[0], "/tmp/one")
})
withCleanup("cookieStore finds Default/Cookies under a profile root", () => {
const root = tmp("tabbit-test-")
fs.mkdirSync(path.join(root, "Default"), { recursive: true })
fs.writeFileSync(path.join(root, "Default", "Cookies"), "")
assert.equal(cookieStore([root]), path.join(root, "Default", "Cookies"))
assert.equal(cookieStore([path.join(root, "missing")]), null)
})
withCleanup("copyStore copies the database and its WAL", () => {
const root = tmp("tabbit-test-")
const file = path.join(root, "Cookies")
fs.writeFileSync(file, "db")
fs.writeFileSync(file + "-wal", "wal")
const copy = copyStore(file, tmp("tabbit-copy-"))
assert.equal(fs.readFileSync(copy, "utf8"), "db")
assert.equal(fs.readFileSync(copy + "-wal", "utf8"), "wal")
})
withCleanup("readCookies reads token and user_id back out of a real sqlite file", () => {
let DatabaseSync
try {
DatabaseSync = globalThis.process.getBuiltinModule("node:sqlite").DatabaseSync
} catch {
return // older Node: the plugin says so at runtime too
}
const root = tmp("tabbit-test-")
const file = path.join(root, "Cookies")
const db = new DatabaseSync(file)
db.exec("create table cookies(host_key text, name text, value text, encrypted_value blob)")
db.prepare("insert into cookies values (?,?,?,?)").run(HOST, "token", "", seal("tok-123"))
db.prepare("insert into cookies values (?,?,?,?)").run(HOST, "user_id", "u-1", Buffer.alloc(0))
db.close()
const rows = readCookies(file)
const token = rows.find((r) => r.name === "token")
assert.equal(decryptValue(token.encrypted, { password: PASSWORD }), "tok-123")
assert.equal(rows.find((r) => r.name === "user_id").value, "u-1")
})
// storeWith builds a real cookie store holding `token` (or none), under a temp
// directory the caller's cleanup removes.
function storeWith(token) {
let DatabaseSync
try {
DatabaseSync = globalThis.process.getBuiltinModule("node:sqlite").DatabaseSync
} catch {
return null
}
const root = tmp("tabbit-store-")
const file = path.join(root, "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))
db.prepare("insert into cookies values (?,?,?,?)").run(HOST, "user_id", "u-9", Buffer.alloc(0))
db.close()
return file
}
withCleanup("a successful desktop sign-in leaves no copy of the cookie store", () => {
const file = storeWith("tok-desktop")
if (!file) return
const parent = tmp("tabbit-parent-")
const sign = 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", () => {
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/)
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", () => {
let DatabaseSync
try {
DatabaseSync = globalThis.process.getBuiltinModule("node:sqlite").DatabaseSync
} catch {
return
}
const AI = "web.tabbit.ai"
const root = tmp("tabbit-store-ai-")
const file = path.join(root, "Cookies")
const db = new DatabaseSync(file)
db.exec("create table cookies(host_key text, name text, value text, encrypted_value blob)")
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" })
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", () => {
const file = storeWith("tok-com")
if (!file) return
const sign = 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/)
})