Repository Public
1import test from "node:test";2import assert from "node:assert/strict";3import { randomBytes } from "node:crypto";4import { Client, SoftAuthenticator, device, makeApp } from "./helpers.ts";5import { sha256 } from "../src/util.ts";67const payload = (text: string) => Buffer.from(text).toString("base64");89async function bootstrap(client: Client, proof = "proof-" + randomBytes(8).toString("hex")) {10 const r = await client.call("POST", "/api/sync/keys/bootstrap", { keyProof: Buffer.from(proof).toString("base64"), recoveryBlob: payload("sealed-account-key"), recoveryAuth: "recovery-auth-secret-0123456789abcdef0123" });11 assert.equal(r.status, 200);12 return Buffer.from(proof).toString("base64");13}1415test("passkey registration, sign-in on a second device, sessions and revocation", async () => {16 const app = makeApp();17 const passkey = new SoftAuthenticator();18 const mac = new Client(app);19 const macDevice = device("Mac A");20 const created = await mac.register(passkey, macDevice, "Simon");21 assert.equal(created.status, 200);22 assert.match(created.json.sessionToken, /^spb_/);23 assert.equal(created.json.sync.initialized, false);24 // Only the hash of the session token is stored.25 assert.equal((app.db.prepare("SELECT COUNT(*) AS n FROM sessions WHERE token_hash = ?").get(sha256(mac.token)) as any).n, 1);26 assert.equal((app.db.prepare("SELECT COUNT(*) AS n FROM sessions WHERE token_hash = ?").get(mac.token) as any).n, 0);2728 const phone = new Client(app);29 const signedIn = await phone.login(passkey, device("iPhone", "ios"));30 assert.equal(signedIn.status, 200);31 assert.equal(signedIn.json.user.id, created.json.user.id);32 assert.notEqual(signedIn.json.deviceId, created.json.deviceId);3334 const account = await mac.call("GET", "/api/account");35 assert.equal(account.json.devices.length, 2);36 assert.equal(account.json.passkeys.length, 1);37 assert.equal(account.json.devices.find((d: any) => d.isCurrent).name, "Mac A");3839 // Signing in again from the same device (same id + key) reuses the device and replaces its session.40 const oldToken = mac.token;41 const again = await mac.login(passkey, { ...macDevice, id: created.json.deviceId });42 assert.equal(again.json.deviceId, created.json.deviceId);43 mac.token = oldToken;44 assert.equal((await mac.call("GET", "/api/account")).status, 401);45 mac.token = again.json.sessionToken;4647 // Removing the phone ends its session immediately.48 assert.equal((await mac.call("DELETE", `/api/devices/${signedIn.json.deviceId}`)).status, 200);49 assert.equal((await phone.call("GET", "/api/account")).status, 401);50 assert.equal((await mac.call("GET", "/api/account")).json.devices.length, 1);5152 // Sign out of all devices.53 await phone.login(passkey, device("iPhone", "ios"));54 assert.equal((await mac.call("POST", "/api/auth/logout-all")).json.revoked, 2);55 assert.equal((await mac.call("GET", "/api/account")).status, 401);56 assert.equal((await phone.call("GET", "/api/account")).status, 401);57 await app.server.close();58});5960test("WebAuthn checks: wrong origin, replayed challenge, unknown passkey, expired session", async () => {61 const app = makeApp();62 const passkey = new SoftAuthenticator();63 const client = new Client(app);64 await client.register(passkey, device("Mac"));6566 let options = await client.call("POST", "/api/auth/login/options", {});67 const phished = passkey.assert(options.json.options, { origin: "https://evil.example" });68 assert.equal((await client.call("POST", "/api/auth/login/verify", { challengeId: options.json.challengeId, credential: phished, device: device("X") })).status, 401);6970 options = await client.call("POST", "/api/auth/login/options", {});71 const good = passkey.assert(options.json.options);72 assert.equal((await client.call("POST", "/api/auth/login/verify", { challengeId: options.json.challengeId, credential: good, device: device("X") })).status, 200);73 const replay = await client.call("POST", "/api/auth/login/verify", { challengeId: options.json.challengeId, credential: good, device: device("X") });74 assert.equal(replay.status, 400);75 assert.equal(replay.json.error.code, "challenge_expired");7677 const stranger = new SoftAuthenticator();78 const other = makeApp();79 await new Client(other).register(stranger, device("Other"));80 options = await client.call("POST", "/api/auth/login/options", {});81 const unknown = await client.call("POST", "/api/auth/login/verify", { challengeId: options.json.challengeId, credential: stranger.assert(options.json.options), device: device("X") });82 assert.equal(unknown.json.error.code, "unknown_passkey");83 await other.server.close();8485 const fresh = new Client(app);86 await fresh.login(passkey, device("Mac 2"));87 app.db.prepare("UPDATE sessions SET expires_at = ? WHERE token_hash = ?").run(Date.now() - 1000, sha256(fresh.token));88 assert.equal((await fresh.call("GET", "/api/account")).status, 401);89 assert.equal((await new Client(app).call("GET", "/api/account")).status, 401);90 await app.server.close();91});9293test("invitation codes gate account creation and are single use", async () => {94 const app = makeApp({ openRegistration: false });95 const refused = await new Client(app).register(new SoftAuthenticator(), device("Mac"), "A", "WRONGCODE");96 assert.equal(refused.status, 403);97 app.db.prepare("INSERT INTO invites(code_hash, note, created_at) VALUES(?,?,?)").run(sha256("ABCD1234"), "test", Date.now());98 assert.equal((await new Client(app).register(new SoftAuthenticator(), device("Mac"), "A", "abcd-1234")).status, 200);99 assert.equal((await new Client(app).register(new SoftAuthenticator(), device("Mac"), "B", "ABCD-1234")).status, 403);100 await app.server.close();101});102103test("additional passkey, step-up for destructive actions, recovery with the recovery key", async () => {104 const app = makeApp();105 const first = new SoftAuthenticator(), second = new SoftAuthenticator();106 const client = new Client(app);107 const created = await client.register(first, device("Mac"));108 await bootstrap(client);109110 const options = await client.call("POST", "/api/auth/passkeys/options", {});111 assert.equal(options.json.options.excludeCredentials.length, 1);112 assert.equal((await client.call("POST", "/api/auth/passkeys/verify", { challengeId: options.json.challengeId, credential: second.register(options.json.options), label: "Security key" })).status, 200);113 const account = await client.call("GET", "/api/account");114 assert.equal(account.json.passkeys.length, 2);115 assert.equal(account.json.user.hasRecovery, true);116117 // Removing a passkey needs a recent passkey confirmation.118 app.db.prepare("UPDATE sessions SET reauth_at = NULL").run();119 const target = account.json.passkeys[1].id;120 assert.equal((await client.call("DELETE", `/api/auth/passkeys/${target}`)).json.error.code, "reauth_required");121 assert.equal((await client.reauth(first)).status, 200);122 assert.equal((await client.call("DELETE", `/api/auth/passkeys/${target}`)).status, 200);123 assert.equal((await client.call("DELETE", `/api/auth/passkeys/${account.json.passkeys[0].id}`)).json.error.code, "last_passkey");124125 // Recovery: wrong key refused (same answer for an unknown account), right key registers a new passkey.126 const lost = new Client(app);127 const userId = created.json.user.id;128 assert.equal((await lost.call("POST", "/api/auth/recover/options", { userId, recoveryAuth: "wrong-wrong-wrong-wrong-wrong-wrong-wrong" })).status, 403);129 assert.equal((await lost.call("POST", "/api/auth/recover/options", { userId: "nobody", recoveryAuth: "recovery-auth-secret-0123456789abcdef0123" })).status, 403);130 const recover = await lost.call("POST", "/api/auth/recover/options", { userId, recoveryAuth: "recovery-auth-secret-0123456789abcdef0123" });131 assert.equal(recover.status, 200);132 const replacement = new SoftAuthenticator();133 const verified = await lost.call("POST", "/api/auth/recover/verify", { challengeId: recover.json.challengeId, credential: replacement.register(recover.json.options), device: device("New Mac") });134 assert.equal(verified.status, 200);135 assert.equal(verified.json.user.id, userId);136 assert.equal(verified.json.sync.initialized, true);137 lost.token = verified.json.sessionToken;138 assert.equal((await lost.call("GET", "/api/sync/keys/recovery")).json.recoveryBlob, payload("sealed-account-key"));139140 // Account deletion removes everything, after step-up.141 app.db.prepare("UPDATE sessions SET reauth_at = NULL").run();142 assert.equal((await lost.call("DELETE", "/api/account")).status, 403);143 await lost.reauth(replacement);144 assert.equal((await lost.call("DELETE", "/api/account")).status, 200);145 for (const table of ["users", "credentials", "devices", "sessions", "sync_records", "account_keys"]) {146 assert.equal((app.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as any).n, 0, table);147 }148 await app.server.close();149});150151test("sync: key enrollment of a second device, change feed, conflicts, deletion propagation", async () => {152 const app = makeApp();153 const passkey = new SoftAuthenticator();154 const mac = new Client(app), phone = new Client(app);155 await mac.register(passkey, device("Mac A"));156 assert.equal((await mac.call("GET", "/api/sync/pull?since=0")).json.error.code, "sync_not_initialized");157 const proof = await bootstrap(mac);158 assert.equal((await mac.call("POST", "/api/sync/keys/bootstrap", { keyProof: proof, recoveryBlob: payload("x"), recoveryAuth: "y".repeat(40) })).json.error.code, "sync_already_initialized");159160 const phoneDevice = device("iPhone", "ios");161 const signedIn = await phone.login(passkey, phoneDevice);162 assert.equal(signedIn.json.sync.initialized, true);163 assert.equal(signedIn.json.sync.hasEnvelope, false);164 assert.equal((await phone.call("GET", "/api/sync/keys")).json.envelope, null);165166 // The Mac sees the waiting device and hands over the key sealed to its public key.167 const pending = await mac.call("GET", "/api/sync/keys/pending");168 assert.deepEqual(pending.json.devices.map((d: any) => [d.name, d.encPublicKey]), [["iPhone", phoneDevice.encPublicKey]]);169 const target = pending.json.devices[0];170 assert.equal((await phone.call("POST", "/api/sync/keys/approve", { deviceId: target.id, encPublicKey: target.encPublicKey, envelope: payload("sealed"), keyProof: payload("guess") })).status, 403);171 assert.equal((await mac.call("POST", "/api/sync/keys/approve", { deviceId: target.id, encPublicKey: "tampered" + target.encPublicKey, envelope: payload("sealed"), keyProof: proof })).json.error.code, "device_key_changed");172 assert.equal((await mac.call("POST", "/api/sync/keys/approve", { deviceId: target.id, encPublicKey: target.encPublicKey, envelope: payload("sealed-for-phone"), keyProof: proof })).status, 200);173 const keys = await phone.call("GET", "/api/sync/keys");174 assert.equal(keys.json.envelope.sealed, payload("sealed-for-phone"));175 assert.equal(keys.json.envelope.fromDeviceName, "Mac A");176 assert.equal(keys.json.keyCheck, sha256(proof));177 assert.equal((await mac.call("GET", "/api/sync/keys/pending")).json.devices.length, 0);178179 // Mac pushes; phone pulls incrementally.180 const push = await mac.call("POST", "/api/sync/push", { changes: [181 { collection: "history", id: "h1", baseSeq: 0, payload: payload("visit-1"), keyVersion: 1 },182 { collection: "bookmarks", id: "b1", baseSeq: 0, payload: payload("bookmark-1"), keyVersion: 1 },183 { collection: "tabs", id: "macTabs", baseSeq: 0, payload: payload("tabs-of-mac"), keyVersion: 1 },184 ] });185 assert.deepEqual(push.json.applied.map((a: any) => a.seq), [1, 2, 3]);186 let pull = await phone.call("GET", "/api/sync/pull?since=0&limit=2");187 assert.equal(pull.json.changes.length, 2);188 assert.equal(pull.json.more, true);189 pull = await phone.call("GET", `/api/sync/pull?since=${pull.json.next}`);190 assert.deepEqual(pull.json.changes.map((c: any) => c.id), ["macTabs"]);191 assert.equal(pull.json.more, false);192 assert.equal((await phone.call("GET", `/api/sync/pull?since=${pull.json.next}`)).json.changes.length, 0);193194 // Concurrent edit of the same bookmark: the phone wins the race, the Mac gets a conflict with the winning version.195 assert.equal((await phone.call("POST", "/api/sync/push", { changes: [{ collection: "bookmarks", id: "b1", baseSeq: 2, payload: payload("bookmark-phone"), keyVersion: 1 }] })).json.applied[0].seq, 4);196 const conflict = await mac.call("POST", "/api/sync/push", { changes: [{ collection: "bookmarks", id: "b1", baseSeq: 2, payload: payload("bookmark-mac"), keyVersion: 1 }] });197 assert.equal(conflict.json.applied.length, 0);198 assert.deepEqual([conflict.json.conflicts[0].seq, conflict.json.conflicts[0].payload], [4, payload("bookmark-phone")]);199 // After merging, the Mac writes on top of the version it has now seen.200 assert.equal((await mac.call("POST", "/api/sync/push", { changes: [{ collection: "bookmarks", id: "b1", baseSeq: 4, payload: payload("bookmark-merged"), keyVersion: 1 }] })).json.applied[0].seq, 5);201202 // Deletion propagates as a tombstone with no payload; no duplicate rows ever exist for one record.203 await mac.call("POST", "/api/sync/push", { changes: [{ collection: "history", id: "h1", baseSeq: 1, deleted: true }] });204 const after = await phone.call("GET", "/api/sync/pull?since=5");205 assert.deepEqual(after.json.changes.map((c: any) => [c.collection, c.id, c.deleted, c.payload]), [["history", "h1", true, ""]]);206 assert.equal((app.db.prepare("SELECT COUNT(*) AS n FROM sync_records WHERE collection = 'bookmarks'").get() as any).n, 1);207208 // SP Browser 3.0 collections are accepted like the others and stay opaque to the server.209 const aura = await mac.call("POST", "/api/sync/push", { changes: [210 { collection: "canvas", id: "c1", baseSeq: 0, payload: payload("canvas-card"), keyVersion: 1 },211 { collection: "handoff", id: "ho1", baseSeq: 0, payload: payload("handoff"), keyVersion: 1 },212 ] });213 assert.equal(aura.status, 200);214 assert.deepEqual(aura.json.applied.map((a: any) => a.collection), ["canvas", "handoff"]);215 const auraSeq = aura.json.applied[1].seq;216 await mac.call("POST", "/api/sync/push", { changes: [{ collection: "canvas", id: "c1", baseSeq: aura.json.applied[0].seq, deleted: true }, { collection: "handoff", id: "ho1", baseSeq: auraSeq, deleted: true }] });217218 // Validation.219 const bad = [220 { collection: "passwords", id: "x", baseSeq: 0, payload: payload("x"), keyVersion: 1 },221 { collection: "history", id: "bad id!", baseSeq: 0, payload: payload("x"), keyVersion: 1 },222 { collection: "history", id: "x", baseSeq: 0, payload: "not base64 !!", keyVersion: 1 },223 { collection: "history", id: "x", baseSeq: 0, payload: payload("x"), keyVersion: 9 },224 ];225 for (const change of bad) assert.ok([400, 409].includes((await mac.call("POST", "/api/sync/push", { changes: [change] })).status));226227 // Another account never sees these records.228 const stranger = new Client(app);229 await stranger.register(new SoftAuthenticator(), device("Stranger"));230 await bootstrap(stranger);231 assert.equal((await stranger.call("GET", "/api/sync/pull?since=0")).json.changes.length, 0);232233 // Removing the Mac tombstones its open-tabs record for the other devices.234 const macId = (await mac.call("GET", "/api/account")).json.currentDeviceId;235 await mac.call("POST", "/api/sync/push", { changes: [{ collection: "tabs", id: macId, baseSeq: 0, payload: payload("tabs"), keyVersion: 1 }] });236 const before = (await phone.call("GET", "/api/sync/pull?since=0")).json.latest;237 await phone.call("DELETE", `/api/devices/${macId}`);238 const tomb = await phone.call("GET", `/api/sync/pull?since=${before}`);239 assert.deepEqual(tomb.json.changes.map((c: any) => [c.collection, c.id, c.deleted]), [["tabs", macId, true]]);240241 // Erasing synchronized data needs proof of the key and leaves the account usable.242 assert.equal((await phone.call("DELETE", "/api/sync/data", undefined, { "x-sp-key-proof": payload("nope") })).status, 403);243 assert.equal((await phone.call("DELETE", "/api/sync/data", undefined, { "x-sp-key-proof": proof })).status, 200);244 assert.equal((await phone.call("GET", "/api/sync/keys")).json.initialized, false);245 assert.equal((await phone.call("GET", "/api/account")).status, 200);246 await app.server.close();247});248249test("operations: health, association file, admin overview is protected and holds no queries", async () => {250 const app = makeApp({ tavilyBase: "http://127.0.0.1:1" });251 const client = new Client(app);252 assert.equal((await client.call("GET", "/api/health")).json.ok, true);253 assert.deepEqual((await client.call("GET", "/.well-known/apple-app-site-association")).json, { webcredentials: { apps: ["TEAM.app.test"] } });254 await client.call("POST", "/api/search", { query: "very private query zebra" });255 assert.equal((await client.call("GET", "/api/admin/overview")).status, 401);256 assert.equal((await client.call("GET", "/api/admin/overview", undefined, { authorization: "Bearer wrong" })).status, 401);257 const overview = await client.call("GET", "/api/admin/overview", undefined, { authorization: "Bearer admin-test" });258 assert.equal(overview.status, 200);259 assert.equal(overview.json.errors.last24h, 1);260 assert.ok(!JSON.stringify(overview.json).includes("zebra"));261 assert.ok(!JSON.stringify(overview.json).includes("tvly-test"));262 assert.equal((await client.call("GET", "/admin")).status, 200);263 await app.server.close();264});265