Repository Public
1import test, { after, before } from "node:test";2import assert from "node:assert/strict";3import * as P from "../../packages/protocol/src/index.ts";4import { ApiError } from "../../apps/web/src/core/engine.ts";5import { Authenticator, device, invite, newAccount, pair, sql, startServer, stopServer } from "../harness.ts";67before(() => startServer()); after(() => stopServer());89const SECRET_TITLE = "Banque Zanzibar-7731", SECRET_PW = "correct-horse-ZQ9-battery", SECRET_USER = "alice.zq9@example.test";10const login = (title = SECRET_TITLE) => { const it = P.newItem("login", title); it.fields = { username: SECRET_USER, password: SECRET_PW, totp: "JBSWY3DPEHPK3PXP" }; it.urls = [{ url: "https://bank.zanzibar-7731.test/login", match: "domain" }]; it.notes = "note-ZQ9-secret"; it.tags = ["tag-zq9"]; return it; };11const personal = (d: any) => d.engine.vaults()[0].vaultId as string;1213test("account creation, item CRUD, and the server never receives plaintext", async () => {14 const a = await newAccount("alice");15 assert.match(a.recoveryKey, /^SPV1(-[0-9A-Z]{4}){14}$/);16 const v = personal(a);17 const id = await a.engine.saveItem(v, null, login());18 assert.equal(a.engine.get(v, id)!.item.fields.password, SECRET_PW);19 assert.equal(a.engine.syncHealth().pending, 0);20 // everything the client ever sent, and everything the database holds21 const sent = a.api.log.map((l) => l.path + l.body).join("\n");22 const dump = JSON.stringify(await Promise.all(["accounts", "devices", "records", "record_history", "vaults", "vault_grants", "audit_events", "sessions", "credentials"].map((t) => sql.unsafe(`select * from ${t}`))));23 for (const needle of [SECRET_TITLE, SECRET_PW, SECRET_USER, "zanzibar", "note-ZQ9", "tag-zq9", "JBSWY3DPEHPK3PXP", "Personal", a.recoveryKey, a.recoveryKey.replace(/-/g, "")]) {24 assert.ok(!sent.includes(needle), `client sent plaintext: ${needle}`);25 assert.ok(!dump.includes(needle), `database holds plaintext: ${needle}`);26 }27 await a.engine.saveItem(v, id, { ...a.engine.get(v, id)!.item, fields: { ...login().fields, password: "second-password-ZQ9" } });28 assert.equal(a.engine.get(v, id)!.item.passwordHistory[0]!.value, SECRET_PW);29 assert.equal((await a.engine.history(v, id)).length, 1);30 await a.engine.trashItem(v, id); assert.ok(a.engine.get(v, id)!.item.trashedAt);31 await a.engine.restoreItem(v, id); assert.ok(!a.engine.get(v, id)!.item.trashedAt);32 await a.engine.deleteItem(v, id); assert.equal(a.engine.get(v, id), undefined);33});3435test("two devices: pairing, sync both ways, lock/unlock", async () => {36 const a = await newAccount("bob");37 const v = personal(a);38 const id = await a.engine.saveItem(v, null, login("From A"));39 const b = await pair(a);40 assert.equal(b.engine.get(v, id)!.item.title, "From A");41 const id2 = await b.engine.saveItem(v, null, login("From B"));42 await a.engine.sync();43 assert.equal(a.engine.get(v, id2)!.item.fields.password, SECRET_PW);44 assert.equal(await a.engine.stateDigest(), await b.engine.stateDigest());45 const devs = await a.engine.devices();46 assert.equal(devs.length, 2); assert.ok(devs.every((d) => d.verified));47 b.engine.lock();48 assert.throws(() => b.engine.list().length || b.engine.sync(), /locked/);49 assert.equal(await b.engine.signIn(), "unlocked");50 assert.equal(b.engine.list().length, 2);51 b.engine.lock(); await b.engine.unlockOffline(); assert.equal(b.engine.list().length, 2);52});5354test("pairing: a server that substitutes the new device's keys is detected; a setup code alone enrols nothing", async () => {55 const a = await newAccount("carol");56 const b = device(a.auth);57 await b.engine.signIn();58 const { code } = await b.engine.startPairing();59 const evil = await P.generateKemKey(true);60 await sql`update pairings set enc_pub = ${P.b64u(evil.pub)}`;61 await assert.rejects(a.engine.inspectPairing(code), /SECURITY/);62 // pending session (passkey only) has no access to anything encrypted63 await assert.rejects(b.api.request("POST", "/api/v1/sync", {}), (e: ApiError) => e.status === 403);64 await assert.rejects(b.api.request("GET", "/api/v1/devices"), (e: ApiError) => e.status === 403);65 assert.equal(await b.engine.checkPairing(), "pending");66 // an attacker holding only the code (no passkey session, not a trusted device) cannot approve67 const mallory = device();68 await assert.rejects(mallory.api.request("POST", `/api/v1/pairings/${P.decodePairingCode(code).pairingId}/approve`, { cert: "A".repeat(86), arkEnvelope: "A".repeat(151) }), (e: ApiError) => e.status === 401);69});7071test("fresh-device restore with the recovery key (all devices and the passkey lost)", async () => {72 const a = await newAccount("dave");73 const v = personal(a);74 const id = await a.engine.saveItem(v, null, login("Survives"));75 const fresh = device(new Authenticator(), "Replacement");76 await assert.rejects(fresh.engine.recover("dave", a.recoveryKey.replace(/.$/, (c) => (c === "A" ? "B" : "A"))), /checksum/);77 const wrong = await P.encodeRecoveryKey(P.random(32));78 await assert.rejects(fresh.engine.recover("dave", wrong), (e: ApiError) => e.status === 401);79 await fresh.engine.recover("dave", a.recoveryKey);80 assert.equal(fresh.engine.get(v, id)!.item.title, "Survives");81 await fresh.engine.addPasskey("new");82 fresh.engine.lock(); assert.equal(await fresh.engine.signIn(), "unlocked");83 const kinds = (await fresh.engine.audit()).map((e) => e.kind);84 assert.ok(kinds.includes("recovery.started") && kinds.includes("device.enrolled"));85 // rotation: the old key stops working, the new one works86 const rk2 = await fresh.engine.rotateRecoveryKey();87 await assert.rejects(device().engine.recover("dave", a.recoveryKey), (e: ApiError) => e.status === 401);88 const again = device(); await again.engine.recover("dave", rk2);89 assert.equal(again.engine.list().length, 1);90});9192test("offline edits are queued; concurrent edits never lose data (conflict copy)", async () => {93 const a = await newAccount("erin"); const b = await pair(a);94 const v = personal(a);95 const id = await a.engine.saveItem(v, null, login("Shared item")); await b.engine.sync();96 b.api.offline = true;97 await b.engine.saveItem(v, id, { ...b.engine.get(v, id)!.item, notes: "edited offline on B" });98 const offlineNew = await b.engine.saveItem(v, null, login("Created offline"));99 assert.equal(b.engine.syncHealth().pending, 2); assert.equal(b.engine.syncHealth().online, false);100 assert.ok(b.engine.get(v, id)!.pending);101 await a.engine.saveItem(v, id, { ...a.engine.get(v, id)!.item, notes: "edited online on A" });102 b.api.offline = false;103 await b.engine.sync(); await a.engine.sync();104 assert.equal(b.engine.syncHealth().pending, 0);105 for (const d of [a, b]) {106 assert.equal(d.engine.get(v, id)!.item.notes, "edited online on A");107 const copy = d.engine.list().find((i) => i.item.conflictOf === id);108 assert.ok(copy, "conflict copy exists"); assert.equal(copy!.item.notes, "edited offline on B");109 assert.ok(d.engine.get(v, offlineNew));110 }111 assert.equal(await a.engine.stateDigest(), await b.engine.stateDigest());112});113114test("revoked device loses access and wipes itself", async () => {115 const a = await newAccount("frank"); const b = await pair(a);116 const bId = b.engine.identity!.deviceId;117 await a.engine.revokeDevice(bId);118 await assert.rejects(b.api.request("POST", "/api/v1/sync", {}), (e: ApiError) => e.status === 401);119 b.engine.lock();120 await assert.rejects(b.engine.signIn(), (e: ApiError) => e.code === "device_revoked");121 assert.equal(b.engine.identity, undefined);122 assert.equal((await sql`select ark_envelope from devices where id = ${bId}`)[0]!.ark_envelope, "");123 assert.equal((await a.engine.devices()).length, 1);124});125126test("malicious server: forged, swapped, re-labelled and rolled-back records are rejected", async () => {127 const a = await newAccount("grace"); const v = personal(a);128 const id1 = await a.engine.saveItem(v, null, login("One")), id2 = await a.engine.saveItem(v, null, login("Two"));129 await a.engine.saveItem(v, id1, { ...a.engine.get(v, id1)!.item, notes: "v2" });130 const b = await pair(a);131 const [r1] = await sql`select envelope, rev from records where id = ${id1}`, [r2] = await sql`select envelope from records where id = ${id2}`;132 const [old] = await sql`select envelope from record_history where id = ${id1} and rev = 1`;133 // (1) swap two ciphertexts, (2) flip a bit, (3) fake a deletion, (4) replay revision 1 as revision 3 — each bumps seq so clients look134 const bump = async (fn: () => Promise<unknown>) => { await fn(); await sql`update vaults set seq = seq + 1 where id = ${v}`; };135 const c = device(a.auth); // a brand-new device would also refuse136 await bump(() => sql`update records set envelope = ${sql.json(r2!.envelope)}, seq = (select seq + 1 from vaults where id = ${v}) where id = ${id1}`);137 await b.engine.sync();138 assert.equal(b.engine.get(v, id1)!.item.notes, "v2", "swapped ciphertext not applied");139 assert.ok(b.engine.syncHealth().warnings.some((w) => /failed authentication/.test(w)));140 await bump(() => sql`update records set envelope = ${sql.json(old!.envelope)}, rev = 3, seq = (select seq + 1 from vaults where id = ${v}) where id = ${id1}`);141 await b.engine.sync(); assert.equal(b.engine.get(v, id1)!.item.notes, "v2", "re-labelled old revision not applied");142 await bump(() => sql`update records set envelope = ${sql.json(old!.envelope)}, rev = 1, seq = (select seq + 1 from vaults where id = ${v}) where id = ${id1}`);143 await b.engine.sync(); assert.equal(b.engine.get(v, id1)!.item.notes, "v2");144 assert.ok(b.engine.syncHealth().warnings.some((w) => /rollback/.test(w)));145 await bump(() => sql`update records set envelope = ${sql.json(r1!.envelope)}, rev = ${r1!.rev}, deleted = true, seq = (select seq + 1 from vaults where id = ${v}) where id = ${id1}`);146 await b.engine.sync(); assert.ok(b.engine.get(v, id1), "faked deletion not applied");147 void c;148});149150test("attachments: chunked upload, resume after a partial upload, tamper detection", async () => {151 const a = await newAccount("heidi"); const v = personal(a);152 const data = P.random(2 * 1024 * 1024 + 12345 > 65536 ? 65536 : 0); // getRandomValues limit153 const big = new Uint8Array(2 * 1024 * 1024 + 12345); for (let i = 0; i < big.length; i += 65536) big.set(P.random(Math.min(65536, big.length - i)), i);154 void data;155 const ref = await a.engine.upload(v, "passeport-secret.pdf", "application/pdf", big);156 assert.equal(ref.chunks, 3);157 const it = P.newItem("document", "Passport"); it.attachments = [ref];158 const id = await a.engine.saveItem(v, null, it);159 const b = await pair(a);160 assert.deepEqual(await b.engine.download(b.engine.get(v, id)!.item.attachments[0]!), big);161 assert.ok(!JSON.stringify(await sql`select * from attachments`).includes("passeport"));162 // partial upload then resume163 const id2 = P.uuid(), { ref: ref2, chunks } = await P.newAttachment(id2, "x", "text/plain", big);164 await a.api.request("POST", `/api/v1/vaults/${v}/attachments`, { id: id2, chunks: ref2.chunks, size: ref2.size });165 await a.api.request("PUT", `/api/v1/attachments/${id2}/chunks/1`, undefined, { binary: chunks[1] });166 await assert.rejects(a.api.request("POST", `/api/v1/attachments/${id2}/complete`, {}), (e: ApiError) => e.code === "incomplete");167 const resumed = await a.api.request("POST", `/api/v1/vaults/${v}/attachments`, { id: id2, chunks: ref2.chunks, size: ref2.size });168 assert.deepEqual(resumed.uploaded, [1]);169 await assert.rejects(a.api.request("PUT", `/api/v1/attachments/${id2}/chunks/0`, undefined, { binary: chunks[0]!.slice(1) }), (e: ApiError) => e.status === 400);170 // reordered chunks fail authentication171 await assert.rejects(P.openAttachment(ref2, [chunks[1]!, chunks[0]!, chunks[2]!]), /authentication failed/);172 await assert.rejects(P.openAttachment({ ...ref2, chunks: 2 }, chunks.slice(0, 2)), /authentication failed/);173});174175test("shared vault between accounts; member removal rotates the key", async () => {176 const a = await newAccount("ivan"), b = await newAccount("judy");177 const shared = await a.engine.createVault({ name: "Famille", kind: "shared" });178 const id = await a.engine.saveItem(shared, null, login("Wi-Fi maison"));179 const judy = await a.engine.lookupAccount("judy");180 assert.match(judy.fingerprint, /^([0-9A-F]{4} ){4}[0-9A-F]{4}$/);181 await a.engine.addMember(shared, judy, "reader");182 await b.engine.sync();183 assert.equal(b.engine.get(shared, id)!.item.fields.password, SECRET_PW);184 assert.equal(b.engine.vaults().find((x) => x.vaultId === shared)!.meta.name, "Famille");185 await assert.rejects(b.engine.saveItem(shared, null, login("nope")), /read-only/);186 await assert.rejects(b.api.request("PUT", `/api/v1/vaults/${shared}/records/${P.uuid()}`, { type: "item", baseRev: 0, envelope: (await sql`select envelope from records where id = ${id}`)[0]!.envelope }), (e: ApiError) => e.code === "read_only");187 await a.engine.addMember(shared, judy, "editor"); await b.engine.sync();188 const id2 = await b.engine.saveItem(shared, null, login("Added by Judy")); await a.engine.sync();189 assert.ok(a.engine.get(shared, id2));190 // removal191 await a.engine.rotateVaultKey(shared, [judy.accountId]);192 await b.engine.sync();193 assert.equal(b.engine.vaults().find((x) => x.vaultId === shared), undefined);194 assert.equal(b.engine.get(shared, id), undefined);195 await assert.rejects(b.api.request("GET", `/api/v1/vaults/${shared}/records/${id}/history`), (e: ApiError) => e.status === 404);196 const kids = (await sql`select envelope->>'kid' as kid from records where vault_id = ${shared}`).map((r) => r.kid);197 assert.ok(kids.every((k) => k === "2"), "all records re-encrypted under the new epoch");198 await a.engine.saveItem(shared, id, { ...a.engine.get(shared, id)!.item, notes: "after removal" });199 assert.equal((await sql`select count(*)::int as n from vault_grants where vault_id = ${shared} and member_id = ${judy.accountId}`)[0]!.n, 0);200});201202test("relay: share to an account, and by link with view limit, expiry and revocation", async () => {203 const a = await newAccount("kate"), b = await newAccount("liam");204 const liam = await a.engine.lookupAccount("liam");205 const sid = await a.engine.shareWithAccount(login("Netflix"), liam, 3600, 2);206 const got = await b.engine.openShare(sid);207 assert.equal(got.item.fields.password, SECRET_PW); assert.equal(got.from, "kate");208 await b.engine.openShare(sid);209 await assert.rejects(b.engine.openShare(sid), (e: ApiError) => e.status === 404, "view limit enforced");210 assert.ok(!JSON.stringify(await sql`select * from shares`).includes("Netflix"));211 const url = await a.engine.shareByLink(login("Door code"), "https://vault.example", 3600, 1);212 const [, shareId, secret] = /#\/s\/([0-9a-f-]+)\/([A-Za-z0-9_-]+)$/.exec(url)!;213 const anon = device();214 const k = await P.linkKeys(P.unb64u(secret!), shareId!);215 await assert.rejects(anon.api.request("POST", `/api/v1/public/shares/${shareId}`, { auth: P.b64u(P.random(32)) }), (e: ApiError) => e.status === 404);216 const { box } = await anon.api.request("POST", `/api/v1/public/shares/${shareId}`, { auth: k.auth });217 assert.equal((await P.openLink<P.Item>(P.unb64u(secret!), shareId!, box)).title, "Door code");218 await assert.rejects(anon.api.request("POST", `/api/v1/public/shares/${shareId}`, { auth: k.auth }), (e: ApiError) => e.status === 410, "one-time retrieval");219 const url2 = await a.engine.shareByLink(login("Revoked"), "https://vault.example", 3600, 5);220 const m2 = /#\/s\/([0-9a-f-]+)\/([A-Za-z0-9_-]+)$/.exec(url2)!;221 await a.engine.revokeShare(m2[1]!);222 await assert.rejects(anon.api.request("POST", `/api/v1/public/shares/${m2[1]}`, { auth: (await P.linkKeys(P.unb64u(m2[2]!), m2[1]!)).auth }), (e: ApiError) => e.status === 410);223 assert.equal((await sql`select box from shares where id = ${m2[1]!}`)[0]!.box, "", "revocation erases the ciphertext");224 const kinds = (await a.engine.audit()).map((e) => e.kind);225 assert.ok(kinds.includes("share.created") && kinds.includes("share.opened") && kinds.includes("share.revoked"));226});227228test("account rekey after compromise, encrypted backup and restore", async () => {229 const a = await newAccount("mona"); const b = await pair(a); const v = personal(a);230 const id = await a.engine.saveItem(v, null, login("Before rekey"));231 const backup = await a.engine.exportBackup();232 assert.ok(!backup.includes("Before rekey") && !backup.includes(SECRET_PW));233 const oldEnvelope = (await sql`select ark_envelope from devices where id = ${b.engine.identity!.deviceId}`)[0]!.ark_envelope;234 const rk2 = await a.engine.rekeyAccount();235 assert.notEqual((await sql`select ark_envelope from devices where id = ${b.engine.identity!.deviceId}`)[0]!.ark_envelope, oldEnvelope);236 assert.ok((await sql`select envelope->>'kid' as kid from records where vault_id = ${v}`).every((r) => r.kid === "2"));237 // the other device was signed out; after signing in again it reads everything with the new keys238 b.engine.lock(); assert.equal(await b.engine.signIn(), "unlocked"); await b.engine.sync();239 assert.equal(b.engine.get(v, id)!.item.title, "Before rekey");240 await assert.rejects(device().engine.recover("mona", a.recoveryKey), (e: ApiError) => e.status === 401);241 const fresh = device(); await fresh.engine.recover("mona", rk2); assert.ok(fresh.engine.get(v, id));242 // offline backup: opens with the recovery key valid at the time, without the server243 const opened = await P.openBackup(P.parseBackup(backup), { recoveryKey: await P.decodeRecoveryKey(a.recoveryKey) });244 assert.equal(opened.payload.vaults[0]!.items[0]!.item.title, "Before rekey");245 await assert.rejects(P.openBackup(P.parseBackup(backup), { recoveryKey: await P.decodeRecoveryKey(rk2) }));246 const n = await a.engine.restoreBackup(backup, a.recoveryKey);247 assert.equal(n, 1); assert.equal(a.engine.vaults().length, 2);248 const tampered = JSON.parse(backup); tampered.ct = tampered.ct.slice(0, -4) + "AAAA";249 await assert.rejects(a.engine.restoreBackup(JSON.stringify(tampered), a.recoveryKey));250});251252test("invitations are single-use; import", async () => {253 const token = await invite();254 const a = device(); await a.engine.register(token, "nina");255 await assert.rejects(device().engine.register(token, "oscar"), (e: ApiError) => e.code === "invalid_invite");256 await assert.rejects(device().engine.register(await invite(), "nina"), (e: ApiError) => e.code === "handle_taken");257 const res = P.importAny("passwords.csv", 'Title,URL,Username,Password,Notes,OTPAuth\r\n"Ex, ample",https://example.com,u1,"p""w",,\r\nSecond,https://second.test,u2,pw2,"multi\nline",otpauth://totp/x?secret=JBSWY3DPEHPK3PXP\r\n');258 assert.equal(res.format, "apple"); assert.equal(res.items[0]!.title, "Ex, ample"); assert.equal(res.items[0]!.fields.password, 'p"w');259 assert.equal(await a.engine.importItems(personal(a), res.items), 2);260 assert.equal(a.engine.search("second u2").length, 1);261});262