SPB Git

Repository Public

protocol.test.ts 18.0 KB 214 lines typescript

1// Unit and property tests: AEAD binding, corruption, wrong keys, nonce handling, generator, URL matching, parsers.2import test from "node:test";3import assert from "node:assert/strict";4import { readFileSync } from "node:fs";5import fc from "fast-check";6import * as P from "../src/index.ts";78const words = readFileSync(new URL("../data/eff-large-wordlist.txt", import.meta.url), "utf8").trim().split("\n");9const ref = { vaultId: P.uuid(), recordId: P.uuid(), type: "item" as const, rev: 1 };10const vk = P.random(32);11const AUTH = /authentication failed/;1213test("record envelope: every associated-data field is bound", async () => {14  const e = await P.sealRecord(vk, 1, ref, { a: 1 });15  assert.deepEqual(await P.openRecord(() => vk, ref, e), { a: 1 });16  await assert.rejects(P.openRecord(() => vk, { ...ref, vaultId: P.uuid() }, e), AUTH);17  await assert.rejects(P.openRecord(() => vk, { ...ref, recordId: P.uuid() }, e), AUTH);18  await assert.rejects(P.openRecord(() => vk, { ...ref, type: "vault-meta" }, e), AUTH);19  await assert.rejects(P.openRecord(() => vk, { ...ref, rev: 2 }, e), AUTH);20  await assert.rejects(P.openRecord((k) => (k === 2 ? vk : undefined), ref, { ...e, kid: 2 }), AUTH);21  await assert.rejects(P.openRecord(() => P.random(32), ref, e), AUTH);22  await assert.rejects(P.openRecord(() => undefined, ref, e), /unavailable/);23});2425test("record envelope: any single-bit corruption is detected; nonces and salts are never reused", async () => {26  const e = await P.sealRecord(vk, 1, ref, { secret: "x".repeat(300) });27  for (const field of ["salt", "nonce", "ct"] as const) {28    const raw = P.unb64u(e[field]);29    for (const i of [0, raw.length >> 1, raw.length - 1]) { const b = raw.slice(); b[i]! ^= 1; await assert.rejects(P.openRecord(() => vk, ref, { ...e, [field]: P.b64u(b) }), AUTH); }30  }31  const seen = new Set<string>();32  for (let i = 0; i < 500; i++) { const x = await P.sealRecord(vk, 1, ref, { i }); assert.ok(!seen.has(x.nonce) && !seen.has(x.salt)); seen.add(x.nonce); seen.add(x.salt); }33  // identical plaintexts give unrelated ciphertexts34  const [a, b] = [await P.sealRecord(vk, 1, ref, { same: true }), await P.sealRecord(vk, 1, ref, { same: true })];35  assert.notEqual(a.ct, b.ct);36});3738test("record envelope: padding hides length within 256-byte buckets; malformed envelopes are rejected before any crypto", async () => {39  const len = async (n: number) => P.unb64u((await P.sealRecord(vk, 1, ref, { s: "a".repeat(n) })).ct).length;40  assert.equal(await len(1), await len(200)); assert.notEqual(await len(1), await len(300));41  await fc.assert(fc.asyncProperty(fc.anything(), async (x) => { await assert.rejects(P.openRecord(() => vk, ref, x)); }), { numRuns: 300 });42  await fc.assert(fc.asyncProperty(fc.record({ v: fc.constantFrom(1, 2, "1"), alg: fc.constantFrom(1, 0), kid: fc.integer(), salt: fc.string(), nonce: fc.string(), ct: fc.string() }), async (x) => { await assert.rejects(P.openRecord(() => vk, ref, x)); }), { numRuns: 300 });43  await fc.assert(fc.asyncProperty(fc.jsonValue(), async (value) => { assert.deepEqual(await P.openRecord(() => vk, ref, await P.sealRecord(vk, 1, ref, value)), JSON.parse(JSON.stringify(value))); }), { numRuns: 100 });44});4546test("key hierarchy: wrong device, wrong account, wrong epoch, forged certificates and grants", async () => {47  const acc = P.uuid(), dev = P.uuid(), ark = P.random(32);48  const account = await P.generateAccountKeys(), other = await P.generateAccountKeys(), d = await P.generateDeviceKeys(), d2 = await P.generateDeviceKeys();49  const env = await P.wrapArkForDevice(ark, acc, dev, d.enc.pub);50  assert.deepEqual(await P.unwrapArk(d, acc, dev, env), ark);51  await assert.rejects(P.unwrapArk(d2, acc, dev, env), AUTH);52  await assert.rejects(P.unwrapArk(d, P.uuid(), dev, env), AUTH);53  await assert.rejects(P.unwrapArk(d, acc, P.uuid(), env), AUTH);54  const pub = { deviceId: dev, encPub: P.b64u(d.enc.pub), sigPub: P.b64u(d.sig.pub), createdAt: new Date().toISOString() };55  const cert = await P.signDeviceCert(account, acc, pub);56  assert.ok(await P.verifyDeviceCert(account.sig.pub, acc, { ...pub, cert }));57  assert.ok(!(await P.verifyDeviceCert(other.sig.pub, acc, { ...pub, cert })));58  assert.ok(!(await P.verifyDeviceCert(account.sig.pub, acc, { ...pub, encPub: P.b64u(d2.enc.pub), cert })), "the server cannot swap a device's encryption key");59  assert.ok(!(await P.verifyDeviceCert(account.sig.pub, acc, { ...pub, cert: "garbage" })));60  const ks = await P.sealKeyset(ark, acc, account);61  await assert.rejects(P.openKeyset(P.random(32), acc, ks), AUTH); await assert.rejects(P.openKeyset(ark, P.uuid(), ks), AUTH);62  const vault = P.uuid(), g = await P.grantVaultKey(account, acc, vk, vault, 1, acc, account.enc.pub, "owner");63  assert.deepEqual(await P.acceptVaultGrant(account, g, account.sig.pub), vk);64  await assert.rejects(P.acceptVaultGrant(account, { ...g, role: "reader" }, account.sig.pub), /signature/);65  await assert.rejects(P.acceptVaultGrant(account, { ...g, epoch: 2 }, account.sig.pub), /signature/);66  await assert.rejects(P.acceptVaultGrant(account, g, other.sig.pub), /signature/);67  const forged = await P.grantVaultKey(other, acc, P.random(32), vault, 1, acc, account.enc.pub, "owner");68  await assert.rejects(P.acceptVaultGrant(account, forged, account.sig.pub), /signature/, "a grant signed by someone else is refused");69});7071test("recovery key: round-trip, typo detection, tolerant input", async () => {72  await fc.assert(fc.asyncProperty(fc.uint8Array({ minLength: 32, maxLength: 32 }), async (rk) => {73    const t = await P.encodeRecoveryKey(rk);74    assert.deepEqual(await P.decodeRecoveryKey(t), rk);75    assert.deepEqual(await P.decodeRecoveryKey(t.toLowerCase().replace(/-/g, " ")), rk);76  }), { numRuns: 50 });77  const t = await P.encodeRecoveryKey(P.random(32));78  let caught = 0;79  for (let i = 5; i < t.length; i++) { if (t[i] === "-") continue; const c = t[i] === "7" ? "8" : "7"; try { await P.decodeRecoveryKey(t.slice(0, i) + c + t.slice(i + 1)); } catch { caught++; } }80  assert.equal(caught, 56, "every single-character typo is caught by the checksum");81  await assert.rejects(P.decodeRecoveryKey("SPV1-AAAA"), /malformed/);82  assert.deepEqual(await P.decodeRecoveryKey(t.replace("SPV1", "spvl")), await P.decodeRecoveryKey(t));83  assert.deepEqual(await P.decodeRecoveryKey(t.slice(5)), await P.decodeRecoveryKey(t), "prefix optional");84  const withO = "SPV1-" + "0".repeat(56).match(/.{4}/g)!.join("-");85  await assert.rejects(P.decodeRecoveryKey(withO), /checksum/); await assert.rejects(P.decodeRecoveryKey(withO.replace(/0/g, "O")), /checksum/);86});8788test("generator: unbiased sampling, classes, lengths, entropy", () => {89  // rejection sampling: values at or above the largest multiple of n are discarded, never folded90  const feed = (vals: number[]) => { let i = 0; return (len: number) => { const v = vals[i++]!; const b = new Uint8Array(len); new DataView(b.buffer).setUint32(0, v); return b; }; };91  assert.equal(P.uniform(6, feed([0xffff_fffe, 5])), 5); // 0xfffffffe ≥ floor(2^32/6)*6 → rejected92  assert.equal(P.uniform(6, feed([0xffff_fffb])), 0xffff_fffb % 6);93  const counts = new Array(6).fill(0); for (let i = 0; i < 60000; i++) counts[P.uniform(6)]++;94  const chi = counts.reduce((s, c) => s + (c - 10000) ** 2 / 10000, 0);95  assert.ok(chi < 25, `chi-square ${chi}`); // df=5, p≈0.000196  fc.assert(fc.property(fc.integer({ min: 4, max: 128 }), fc.boolean(), fc.boolean(), fc.boolean(), fc.boolean(), fc.boolean(), (length, lower, upper, digits, symbols, avoidAmbiguous) => {97    const o = { length, lower, upper, digits, symbols, avoidAmbiguous };98    if (!lower && !upper && !digits && !symbols) { assert.throws(() => P.generatePassword(o)); return; }99    const pw = P.generatePassword(o);100    assert.equal(pw.length, length);101    if (lower) assert.match(pw, /[a-z]/); else assert.doesNotMatch(pw, /[a-z]/);102    if (upper) assert.match(pw, /[A-Z]/); else assert.doesNotMatch(pw, /[A-Z]/);103    if (digits) assert.match(pw, /[0-9]/); else assert.doesNotMatch(pw, /[0-9]/);104    if (!symbols) assert.match(pw, /^[A-Za-z0-9]+$/);105    if (avoidAmbiguous) assert.doesNotMatch(pw, /[Il1O0o|`'"]/);106  }), { numRuns: 300 });107  assert.equal(words.length, 7776); assert.equal(new Set(words).size, 7776);108  const pp = P.generatePassphrase(words, { words: 6, separator: "-", capitalize: true, number: true });109  assert.equal(pp.split("-").length, 6); assert.match(pp, /\d/);110  assert.ok(Math.abs(P.passphraseEntropyBits({ words: 6, separator: "-", capitalize: false, number: false }) - 77.55) < 0.01);111  assert.ok(Math.abs(P.passwordEntropyBits({ length: 20, lower: true, upper: true, digits: true, symbols: false }) - 20 * Math.log2(62)) < 1e-9);112  assert.ok(!/Math\.random/.test(readFileSync(new URL("../src/generator.ts", import.meta.url), "utf8").replace(/\/\/.*|\/\*[\s\S]*?\*\//g, "")), "Math.random is never used");113});114115test("TOTP: otpauth parsing and validation", async () => {116  const p = P.parseTotp("otpauth://totp/ACME:alice@example.com?secret=JBSWY3DPEHPK3PXP&issuer=ACME&digits=8&period=60&algorithm=SHA256");117  assert.deepEqual([p.digits, p.period, p.algorithm, p.issuer, p.account], [8, 60, "SHA-256", "ACME", "alice@example.com"]);118  assert.equal((await P.totp(P.parseTotp("jbsw y3dp ehpk 3pxp"), 0)).code.length, 6);119  for (const bad of ["otpauth://hotp/x?secret=JBSWY3DPEHPK3PXP", "otpauth://totp/x?secret=JBSWY3DPEHPK3PXP&digits=12", "not base32 !!!", "otpauth://totp/x?secret=JBSWY3DPEHPK3PXP&algorithm=MD5", ""]) assert.throws(() => P.parseTotp(bad));120});121122test("URL matching: registrable domains, schemes, IDN, phishing lookalikes", () => {123  const u = (url: string, match: P.UrlMatch = "domain") => ({ url, match });124  assert.equal(P.matchUrl(u("https://accounts.example.com/login"), "https://www.example.com/"), "match");125  assert.equal(P.matchUrl(u("https://example.com"), "https://example.com.evil.test/"), "no");126  assert.equal(P.matchUrl(u("https://example.com"), "https://evil-example.com/"), "no");127  assert.equal(P.matchUrl(u("https://example.co.uk"), "https://other.co.uk/"), "no", "public suffix is not a registrable domain");128  assert.equal(P.matchUrl(u("https://alice.github.io"), "https://mallory.github.io/"), "no", "private suffixes separate tenants");129  assert.equal(P.matchUrl(u("https://example.com"), "http://example.com/"), "no", "never fill an https login on http");130  assert.equal(P.matchUrl(u("http://intranet.example.com"), "http://intranet.example.com/"), "insecure");131  assert.equal(P.matchUrl(u("http://localhost:3000"), "http://localhost:3000/x"), "match");132  assert.equal(P.matchUrl(u("https://example.com"), "https://example.com@evil.test/"), "no", "userinfo trick");133  assert.equal(P.matchUrl(u("https://example.com"), "https://evil.test/?u=https://example.com"), "no");134  assert.equal(P.matchUrl(u("https://a.example.com", "host"), "https://b.example.com/"), "no");135  assert.equal(P.matchUrl(u("https://a.example.com:8443", "host"), "https://a.example.com/"), "no");136  assert.equal(P.matchUrl(u("https://example.com/login", "exact"), "https://example.com/login/"), "match");137  assert.equal(P.matchUrl(u("https://example.com/login", "exact"), "https://example.com/other"), "no");138  assert.equal(P.matchUrl(u("https://example.com", "never"), "https://example.com/"), "no");139  assert.equal(P.matchUrl(u("https://192.168.1.10"), "https://192.168.1.11/"), "no");140  for (const junk of ["javascript:alert(1)", "data:text/html,x", "file:///etc/passwd", "", "https://"]) assert.equal(P.matchUrl(u("https://example.com"), junk), "no");141  const saved = ["paypal.com", "github.com", "desjardins.com", "apple.com"];142  assert.equal(P.lookalike("https://paypal.com/signin", saved), null);143  assert.deepEqual(P.lookalike("https://paypa1.com/", saved)?.resembles, "paypal.com");144  assert.equal(P.lookalike("https://xn--pypal-4ve.com/", saved)?.resembles, "paypal.com", "Cyrillic а homograph");145  assert.equal(P.lookalike("https://githuh.com/", saved)?.resembles, "github.com");146  assert.equal(P.lookalike("https://github.co/", saved)?.resembles, "github.com", "same name, other TLD");147  assert.equal(P.lookalike("https://rnicrosoft.com/", ["microsoft.com"])?.resembles, "microsoft.com");148  assert.equal(P.lookalike("https://wikipedia.org/", saved), null);149  const o = P.parseOrigin("https://xn--pypal-4ve.com/")!;150  assert.ok(o.mixedScript); assert.equal(o.display, "xn--pypal-4ve.com", "mixed-script names are displayed in punycode");151  assert.equal(P.parseOrigin("https://bücher.example/")!.host, "xn--bcher-kva.example");152  fc.assert(fc.property(fc.string(), (s) => { P.parseOrigin(s); P.lookalike(s, saved); P.matchUrl(u("https://example.com"), s); }), { numRuns: 1000 });153});154155test("analysis: weak, reused, duplicate, insecure, expiring", () => {156  const mk = (id: string, title: string, pw: string, url = `https://${title}.test`, user = "u") => { const item = P.newItem("login", title); item.fields = { username: user, password: pw }; item.urls = [{ url, match: "domain" as const }]; return { id, item }; };157  const expiring = mk("5", "cert", P.generatePassword()); expiring.item.expiresAt = new Date(Date.now() + 5 * 86400_000).toISOString();158  const f = P.analyze([mk("1", "a", "password1"), mk("2", "b", "Tr0ub4dor&3-long-unique-A"), mk("3", "c", "Tr0ub4dor&3-long-unique-A"), mk("4", "a", P.generatePassword(), "http://a.test"), expiring, mk("6", "aaa", "aaaaaaaaaaaaaaaa")]);159  assert.ok(f.some((x) => x.kind === "weak" && x.id === "1")); assert.ok(f.some((x) => x.kind === "weak" && x.id === "6"), "repetition is weak");160  assert.ok(!f.some((x) => x.kind === "weak" && x.id === "2"));161  assert.deepEqual(f.find((x) => x.kind === "reused"), { kind: "reused", ids: ["2", "3"] });162  assert.ok(f.some((x) => x.kind === "duplicate")); assert.ok(f.some((x) => x.kind === "insecure-url" && x.id === "4")); assert.ok(f.some((x) => x.kind === "expiring" && x.id === "5"));163  assert.ok(P.estimateBits(P.generatePassword()) > 100);164});165166test("breach check sends only a 5-character hash prefix", async () => {167  const { prefix, suffix } = await P.breachPrefix("password");168  assert.equal(prefix + suffix, "5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8"); assert.equal(prefix.length, 5);169  assert.equal(P.breachCount(`0018A45C4D1DEF81644B54AB7F969B88D65:1\r\n${suffix}:9545824\r\nFFF:2`, suffix), 9545824);170  assert.equal(P.breachCount("AAA:1", suffix), 0);171});172173test("import parsers: formats, quoting, hostile input", () => {174  assert.deepEqual(P.parseCsv('a,b\r\n"x,1","y ""q"""\n"multi\nline",z\n'), [["a", "b"], ["x,1", 'y "q"'], ["multi\nline", "z"]]);175  assert.throws(() => P.parseCsv('a,"unterminated'), /unterminated/);176  assert.equal(P.importCsv("name,url,username,password\nGoogle,https://google.com,me,pw\n").format, "chrome");177  assert.equal(P.importCsv("folder,favorite,type,name,notes,fields,reprompt,login_uri,login_username,login_password,login_totp\nWork,1,login,Git,,,0,https://git.test,me,pw,\n,,note,Memo,hello,,,,,,\n").items.length, 2);178  const op = P.importCsv("Title,Url,Username,Password,OTPAuth,Favorite,Archived,Tags,Notes\nBank,https://bank.test,me,pw,,true,false,finance;home,n\n");179  assert.equal(op.format, "1password"); assert.ok(op.items[0]!.favorite); assert.deepEqual(op.items[0]!.tags, ["finance", "home"]);180  const bw = P.importBitwardenJson(JSON.stringify({ encrypted: false, folders: [{ id: "f", name: "Perso" }], items: [181    { type: 1, name: "L", folderId: "f", favorite: true, login: { username: "u", password: "p", totp: "JBSWY3DPEHPK3PXP", uris: [{ uri: "https://l.test", match: 3 }] }, fields: [{ name: "pin", value: "1234", type: 1 }] },182    { type: 2, name: "N", notes: "secret note" }, { type: 3, name: "C", card: { cardholderName: "A", number: "4111", code: "123", expMonth: "3", expYear: "2030" } }, { type: 9, name: "?" }] }));183  assert.equal(bw.items.length, 3); assert.equal(bw.skipped, 1); assert.equal(bw.items[0]!.urls[0]!.match, "exact"); assert.equal(bw.items[0]!.custom[0]!.kind, "secret"); assert.equal(bw.items[2]!.fields.expiry, "03/30");184  assert.throws(() => P.importBitwardenJson('{"encrypted":true,"items":[]}'), /encrypted/);185  assert.equal(P.normalizeItem({ type: "toString", title: "x" }).type, "note", "prototype names are not item types");186  assert.equal(P.primarySecret(P.normalizeItem({ type: "constructor" })), undefined);187  assert.throws(() => P.importCsv("foo,bar\n1,2\n"), /no password column/);188  fc.assert(fc.property(fc.string(), (s) => { try { P.importAny("x.csv", s); } catch (e) { assert.ok(e instanceof Error); } }), { numRuns: 500 });189  fc.assert(fc.property(fc.anything(), (x) => { try { P.normalizeItem(x); } catch (e) { assert.ok(e instanceof Error); } }), { numRuns: 500 });190  const rt = P.importCsv(P.exportCsv(bw.items));191  assert.equal(rt.items[0]!.fields.password, "p"); assert.equal(rt.items[0]!.fields.totp, "JBSWY3DPEHPK3PXP");192});193194test("attachments: truncation, extension, reordering, cross-file substitution", async () => {195  const data = new Uint8Array(P.CHUNK + 100).fill(7), id = P.uuid();196  const { ref: r, chunks } = await P.newAttachment(id, "n", "m", data);197  assert.deepEqual(await P.openAttachment(r, chunks), data);198  await assert.rejects(P.openAttachment({ ...r, chunks: 1 }, [chunks[0]!]), AUTH);199  await assert.rejects(P.openAttachment(r, [chunks[1]!, chunks[0]!]), /authentication|size/);200  await assert.rejects(P.openAttachment({ ...r, id: P.uuid() }, chunks), AUTH);201  const other = await P.newAttachment(id, "n", "m", data);202  await assert.rejects(P.openAttachment(r, [chunks[0]!, other.chunks[1]!]), AUTH);203  const empty = await P.newAttachment(P.uuid(), "e", "m", new Uint8Array(0));204  assert.equal((await P.openAttachment(empty.ref, empty.chunks)).length, 0);205});206207test("constant-time comparison and encodings", () => {208  assert.ok(P.ctEqual(P.utf8("abc"), P.utf8("abc"))); assert.ok(!P.ctEqual(P.utf8("abc"), P.utf8("abd"))); assert.ok(!P.ctEqual(P.utf8("abc"), P.utf8("ab")));209  fc.assert(fc.property(fc.uint8Array(), (b) => { assert.deepEqual(P.unb64u(P.b64u(b)), b); assert.deepEqual(P.unhex(P.hex(b)), b); }));210  for (const bad of ["a+b", "a/b", "a=", "a", "ab cd"]) assert.throws(() => P.unb64u(bad));211  assert.notDeepEqual(P.ctx("a", "bc"), P.ctx("ab", "c"), "length-prefixed fields cannot be shifted");212  assert.equal(P.canonicalJson({ b: 1, a: { d: [2, { z: 1, y: 2 }], c: null } }), '{"a":{"c":null,"d":[2,{"y":2,"z":1}]},"b":1}');213});214
Files main
Menu

Theme