device-manifest.test.ts

10.9 KB · raw

1import { beforeAll, describe, expect, it } from "vitest";2import {3  buildSignedDeviceManifest,4  canonicalise,5  type DeviceManifestError,6  verifyDeviceManifest,7} from "./device-manifest";8import { deriveSyncSigningKeypair } from "./legacy-identity-derivation.test-support";9import {10  DEVICE_MANIFEST_FRESHNESS_MS,11  DEVICE_MANIFEST_VERSION,12  DEVICE_REVOCATION_RECORD_VERSION,13  type ManifestDeviceEntry,14} from "./sync-types";1516const MASTER_KEY = new Uint8Array(32).fill(0xab);17const ISSUER_DEVICE_ID = "11111111-1111-4111-8111-111111111111";18const PEER_DEVICE_ID = "22222222-2222-4222-8222-222222222222";1920function entry(): ManifestDeviceEntry {21  return {22    deviceId: PEER_DEVICE_ID,23    deviceName: "June's Pixel 9",24    deviceType: "android",25    longTermPublicKeyHex: "a".repeat(64),26    signingPublicKeyHex: "b".repeat(64),27    relayUrl: "wss://relay.peachpasswords.com",28    pairedAt: 1_700_000_000_000,29    vouchDepth: 0,30  };31}3233describe("canonicalise", () => {34  it("sorts object keys deterministically", () => {35    const a = canonicalise({ b: 2, a: 1 });36    const b = canonicalise({ a: 1, b: 2 });37    expect(a).toBe(b);38    expect(a).toBe('{"a":1,"b":2}');39  });4041  it("serialises nested arrays of objects in order", () => {42    expect(canonicalise([{ y: 2, x: 1 }, { z: 3 }])).toBe('[{"x":1,"y":2},{"z":3}]');43  });44});4546describe("device manifest sign+verify round trip", () => {47  let signingPrivateKey: CryptoKey;48  let signingPubkey: Uint8Array;4950  beforeAll(async () => {51    const kp = await deriveSyncSigningKeypair(MASTER_KEY, ISSUER_DEVICE_ID);52    signingPrivateKey = kp.privateKey;53    signingPubkey = kp.publicKeyRaw;54  });5556  it("derives a stable 32-byte Ed25519 public key", () => {57    expect(signingPubkey.length).toBe(32);58  });5960  it("signs and verifies a fresh manifest", async () => {61    const m = await buildSignedDeviceManifest(62      ISSUER_DEVICE_ID,63      [entry()],64      signingPrivateKey,65    );66    expect(m.body.manifestVersion).toBe(DEVICE_MANIFEST_VERSION);67    expect(m.body.issuerDeviceId).toBe(ISSUER_DEVICE_ID);68    expect(m.signatureHex).toMatch(/^[0-9a-f]{128}$/);69    const body = await verifyDeviceManifest(m, signingPubkey);70    expect(body.devices).toHaveLength(1);71    expect(body.devices[0].deviceId).toBe(PEER_DEVICE_ID);72  });7374  it("rejects a stale manifest", async () => {75    const now = Date.now();76    const m = await buildSignedDeviceManifest(77      ISSUER_DEVICE_ID,78      [entry()],79      signingPrivateKey,80      { now: now - DEVICE_MANIFEST_FRESHNESS_MS - 1_000 },81    );82    await expect(verifyDeviceManifest(m, signingPubkey, { now })).rejects.toMatchObject({83      kind: "freshness",84    } as DeviceManifestError);85  });8687  it("rejects a forged signature", async () => {88    const m = await buildSignedDeviceManifest(89      ISSUER_DEVICE_ID,90      [entry()],91      signingPrivateKey,92    );93    // Flip one byte of the signature — must fail verification.94    const sig = m.signatureHex;95    const flipped =96      sig.slice(0, 2) +97      ((parseInt(sig.slice(2, 4), 16) ^ 0xff).toString(16).padStart(2, "0")) +98      sig.slice(4);99    await expect(100      verifyDeviceManifest({ ...m, signatureHex: flipped }, signingPubkey),101    ).rejects.toMatchObject({ kind: "signature" } as DeviceManifestError);102  });103104  it("rejects a body tampered after signing", async () => {105    const m = await buildSignedDeviceManifest(106      ISSUER_DEVICE_ID,107      [entry()],108      signingPrivateKey,109    );110    const tampered = {111      ...m,112      body: {113        ...m.body,114        devices: [{ ...entry(), deviceName: "different-name" }],115      },116    };117    await expect(verifyDeviceManifest(tampered, signingPubkey)).rejects.toMatchObject({118      kind: "signature",119    } as DeviceManifestError);120  });121122  it("rejects an unknown manifest version", async () => {123    const m = await buildSignedDeviceManifest(124      ISSUER_DEVICE_ID,125      [entry()],126      signingPrivateKey,127    );128    const future = { ...m, body: { ...m.body, manifestVersion: 0x99 } };129    await expect(verifyDeviceManifest(future, signingPubkey)).rejects.toMatchObject({130      kind: "version",131    } as DeviceManifestError);132  });133134  it("rejects oversized revocation identifiers", async () => {135    const m = await buildSignedDeviceManifest(136      ISSUER_DEVICE_ID,137      [entry()],138      signingPrivateKey,139      {140        revoked: [141          {142            deviceId: "x".repeat(257),143            longTermPublicKeyHex: "c".repeat(64),144            revokedAt: Date.now(),145            revokedByDeviceId: ISSUER_DEVICE_ID,146            recordVersion: DEVICE_REVOCATION_RECORD_VERSION,147          },148        ],149      },150    );151    await expect(verifyDeviceManifest(m, signingPubkey)).rejects.toMatchObject({152      kind: "malformed",153    } as DeviceManifestError);154  });155156  it("rejects oversized revocation issuer identifiers", async () => {157    const m = await buildSignedDeviceManifest(158      ISSUER_DEVICE_ID,159      [entry()],160      signingPrivateKey,161      {162        revoked: [163          {164            deviceId: PEER_DEVICE_ID,165            longTermPublicKeyHex: "c".repeat(64),166            revokedAt: Date.now(),167            revokedByDeviceId: "x".repeat(257),168            recordVersion: DEVICE_REVOCATION_RECORD_VERSION,169          },170        ],171      },172    );173    await expect(verifyDeviceManifest(m, signingPubkey)).rejects.toMatchObject({174      kind: "malformed",175    } as DeviceManifestError);176  });177  it("derives the same keypair across calls (determinism)", async () => {178    const kp2 = await deriveSyncSigningKeypair(MASTER_KEY, ISSUER_DEVICE_ID);179    expect(Array.from(kp2.publicKeyRaw)).toEqual(Array.from(signingPubkey));180  });181});182183describe("manifest canonical form — cross-platform KAT", () => {184  // Pinned byte-for-byte against peach-android's185  // `canonicalDeviceManifestBody`. If either side reorders a key, renames a186  // field, or changes number formatting, this string moves and the two stop187  // verifying each other's signatures — the exact silent divergence the188  // manifest version guards. Keep this identical to the Android vector.189  const CANONICAL =190    '{"devices":[{"deviceId":"peer-1","deviceName":"Peer One","deviceType":"android",' +191    '"longTermPublicKeyHex":"' + "aa".repeat(32) + '","pairedAt":1700000000001,' +192    '"relayUrl":"wss://relay.peachpasswords.com",' +193    '"signingPublicKeyHex":"' + "bb".repeat(32) + '","vouchDepth":0,"wsPort":49142}],' +194    '"issuedAt":1700000000000,"issuerDeviceId":"issuer-1","manifestVersion":5,' +195    '"revoked":[{"deviceId":"gone-1","longTermPublicKeyHex":"' + "cc".repeat(32) + '",' +196    '"recordVersion":2,"revokedAt":1700000000002,"revokedByDeviceId":"issuer-1",' +197    '"signatureHex":""}]}';198199  it("canonicalises a manifest body carrying a revocation to the pinned string", () => {200    expect(201      canonicalise({202        manifestVersion: DEVICE_MANIFEST_VERSION,203        issuerDeviceId: "issuer-1",204        issuedAt: 1_700_000_000_000,205        devices: [206          {207            deviceId: "peer-1",208            deviceName: "Peer One",209            deviceType: "android",210            longTermPublicKeyHex: "aa".repeat(32),211            signingPublicKeyHex: "bb".repeat(32),212            pairedAt: 1_700_000_000_001,213            relayUrl: "wss://relay.peachpasswords.com",214            wsPort: 49142,215            vouchDepth: 0,216          },217        ],218        revoked: [219          {220            deviceId: "gone-1",221            longTermPublicKeyHex: "cc".repeat(32),222            recordVersion: DEVICE_REVOCATION_RECORD_VERSION,223            revokedAt: 1_700_000_000_002,224            revokedByDeviceId: "issuer-1",225            signatureHex: "",226          },227        ],228      }),229    ).toBe(CANONICAL);230  });231232});233describe("canonicalise — null fields are omitted (cross-platform parity)", () => {234  // Android's manifestEntryMap only inserts wsPort / relayUrl when they are235  // non-null. Match that on the browser side so the manifest signed by236  // Android verifies against the canonical bytes the browser recomputes.237  // Without this, the wire would carry "wsPort":null and the browser would238  // include it in the canonical bytes while Android would omit it — the239  // two signatures would never agree even on a legitimate manifest.240  it("omits null wsPort and null relayUrl at the device-entry level", () => {241    const a = canonicalise({242      deviceId: "peer-1",243      deviceName: "Peer One",244      deviceType: "extension",245      longTermPublicKeyHex: "aa".repeat(32),246      signingPublicKeyHex: "bb".repeat(32),247      pairedAt: 1_700_000_000_000,248      wsPort: null,249      relayUrl: null,250    });251    const b = canonicalise({252      deviceId: "peer-1",253      deviceName: "Peer One",254      deviceType: "extension",255      longTermPublicKeyHex: "aa".repeat(32),256      signingPublicKeyHex: "bb".repeat(32),257      pairedAt: 1_700_000_000_000,258    });259    expect(a).toBe(b);260    expect(a).not.toContain("wsPort");261    expect(a).not.toContain("relayUrl");262  });263264  it("keeps non-null wsPort and relayUrl", () => {265    const got = canonicalise({266      deviceId: "peer-1",267      deviceName: "Peer One",268      deviceType: "extension",269      longTermPublicKeyHex: "aa".repeat(32),270      signingPublicKeyHex: "bb".repeat(32),271      pairedAt: 1_700_000_000_000,272      wsPort: 49142,273      relayUrl: "wss://relay.peachpasswords.com",274    });275    expect(got).toContain('"wsPort":49142');276    expect(got).toContain('"relayUrl":"wss://relay.peachpasswords.com"');277  });278279  it("preserves wsPort:0 in canonical bytes (Android sends 0 as no-port sentinel)", () => {280    const got = canonicalise({281      deviceId: "peer-1",282      deviceName: "Peer One",283      deviceType: "extension",284      longTermPublicKeyHex: "aa".repeat(32),285      signingPublicKeyHex: "bb".repeat(32),286      pairedAt: 1_700_000_000_000,287      wsPort: 0,288    });289    expect(got).toContain('"wsPort":0');290  });291});292293describe("verifyDeviceManifest accepts wsPort:null", () => {294  it("does not reject wsPort:null on the wire (Android nullable Int → JSON null)", async () => {295    const kp = await deriveSyncSigningKeypair(MASTER_KEY, ISSUER_DEVICE_ID);296    // Build a valid manifest first, then inject wsPort:null into the body297    // to simulate what Android puts on the wire (nullable Int serialised as298    // JSON null). The canonicaliser strips null, so the signature still299    // verifies — but the validator must not throw on the raw parsed body.300    const m = await buildSignedDeviceManifest(ISSUER_DEVICE_ID, [entry()], kp.privateKey);301    (m.body.devices[0] as unknown as Record<string, unknown>).wsPort = null;302    const body = await verifyDeviceManifest(m, kp.publicKeyRaw);303    expect(body.devices).toHaveLength(1);304  });305});306307describe("device name bound", () => {308  it("caps oversized device names during build/normalise", async () => {309    const kp = await deriveSyncSigningKeypair(MASTER_KEY, ISSUER_DEVICE_ID);310    const m = await buildSignedDeviceManifest(311      ISSUER_DEVICE_ID,312      [{ ...entry(), deviceName: "D".repeat(200) }],313      kp.privateKey,314    );315    const body = await verifyDeviceManifest(m, kp.publicKeyRaw);316    expect(body.devices[0].deviceName).toBe("D".repeat(64));317  });318});