codex.adversarial.test.ts

23.4 KB · raw

1/**2 * codex.adversarial.test.ts — Layer 3 §3.4 adversarial Codex tests.3 *4 * Exercises ChunkBuffer, parseRawScan, encodeWithErasure/decodeWithErasure,5 * and the reconstruction pipeline with adversarial inputs: tampered chunks,6 * wrong verify codes, parity-only sets, out-of-range indices, malformed7 * envelopes. Parameterized for >=200 tests.8 */910import { beforeEach, describe, expect, it } from "vitest";11import { deflate } from "pako";1213import {14  CodexError,15  CHUNK_SIZE,16  computeParityShards,17  deriveShardCounts,18  type ChunkEnvelope,19  type CodexPayload,20} from "../../shared/codex-types";21import {22  bytesToBase64Url,23  buildChunkEnvelope,24  sha256Hex,25  verifyChunkIntegrity,26} from "./helpers";27import { encodeWithErasure, decodeWithErasure } from "./erasure";28import { _resetReedSolomonCacheForTest } from "./rs-loader";29import { ChunkBuffer, parseRawScan, reconstructAndVerify } from "./restore";3031beforeEach(() => {32  _resetReedSolomonCacheForTest();33});3435const VERIFY_CODE = "PX-TEST-1234";3637async function makeEnv(opts: {38  index: number;39  total: number;40  isParity?: boolean;41  verifyCode?: string;42  bytes?: Uint8Array;43}): Promise<ChunkEnvelope> {44  return buildChunkEnvelope(45    opts.bytes ?? new Uint8Array([1, 2, 3, 4, 5]),46    opts.index,47    opts.total,48    opts.isParity ?? false,49    opts.verifyCode ?? VERIFY_CODE50  );51}5253async function makePayload(seedLength = 12_000): Promise<CodexPayload> {54  const blobBytes = new Uint8Array(seedLength);55  let s = 0x9e3779b9;56  for (let i = 0; i < seedLength; i++) {57    s = (s ^ (s << 13)) >>> 0;58    s = (s ^ (s >>> 17)) >>> 0;59    s = (s ^ (s << 5)) >>> 0;60    blobBytes[i] = s & 0xff;61  }62  const vaultBlob = bytesToBase64Url(blobBytes);63  const vaultFingerprint = (64    await sha256Hex(new TextEncoder().encode(vaultBlob))65  )66    .slice(0, 16)67    .toUpperCase();68  return {69    version: 2,70    verifyCode: VERIFY_CODE,71    vaultBlob,72    timestamp: 1_700_000_000_000,73    entryCount: 42,74    vaultFingerprint,75    generatedAt: 1_700_000_001_000,76  };77}7879async function buildEnvelopesForPayload(80  payload: CodexPayload81): Promise<ChunkEnvelope[]> {82  const json = JSON.stringify(payload);83  const compressed = deflate(new TextEncoder().encode(json), { level: 9 });84  const { dataChunks, parityChunks, totalChunks } =85    await encodeWithErasure(compressed);86  const all = [...dataChunks, ...parityChunks];87  return Promise.all(88    all.map((bytes, i) =>89      buildChunkEnvelope(90        bytes,91        i,92        totalChunks,93        i >= dataChunks.length,94        payload.verifyCode95      )96    )97  );98}99100// ── parseRawScan adversarial ────────────────────────────────────────────────101102describe("parseRawScan adversarial", () => {103  const garbageInputs = [104    "",105    " ",106    "\n",107    "not json at all",108    "{not_valid_json",109    "null",110    "true",111    "42",112    '"a string"',113    "[]",114    "[1,2,3]",115  ];116  for (const raw of garbageInputs) {117    it(`returns parse_error for ${JSON.stringify(raw)}`, () => {118      const result = parseRawScan(raw);119      expect(result).toHaveProperty("error");120    });121  }122123  const wrongVersionInputs = [124    JSON.stringify({ v: 1, c: VERIFY_CODE, i: 0, t: 5 }),125    JSON.stringify({ v: 4, c: VERIFY_CODE, i: 0, t: 5 }),126    JSON.stringify({ v: 0, c: VERIFY_CODE, i: 0, t: 5 }),127    JSON.stringify({ v: "2", c: VERIFY_CODE, i: 0, t: 5 }),128    JSON.stringify({ v: -1 }),129    JSON.stringify({ v: 99 }),130  ];131  for (const raw of wrongVersionInputs) {132    it(`reports wrong_version for ${JSON.stringify(raw).slice(0, 40)}`, () => {133      const result = parseRawScan(raw);134      expect(result).toMatchObject({ error: "wrong_version" });135    });136  }137138  const missingFieldInputs = [139    JSON.stringify({ v: 2 }),140    JSON.stringify({ v: 2, c: VERIFY_CODE }),141    JSON.stringify({ v: 2, c: VERIFY_CODE, i: 0 }),142    JSON.stringify({ v: 2, c: VERIFY_CODE, i: 0, t: 5 }),143    JSON.stringify({ v: 2, c: VERIFY_CODE, i: 0, t: 5, p: false }),144    JSON.stringify({ v: 2, c: VERIFY_CODE, i: 0, t: 5, p: false, d: "x" }),145  ];146  for (const raw of missingFieldInputs) {147    it(`parse_error for missing fields: ${raw.slice(0, 60)}`, () => {148      const result = parseRawScan(raw);149      expect(result).toMatchObject({ error: "parse_error" });150    });151  }152153  it("returns envelope for a valid envelope JSON", async () => {154    const env = await makeEnv({ index: 0, total: 5 });155    const result = parseRawScan(JSON.stringify(env));156    expect(result).toMatchObject({ v: 3, c: VERIFY_CODE, i: 0, t: 5 });157  });158159  it("extra unknown fields do not break parseRawScan", async () => {160    const env = await makeEnv({ index: 0, total: 5 });161    const raw = JSON.stringify({ ...env, extra: "field", more: 42 });162    const result = parseRawScan(raw);163    expect(result).toMatchObject({ v: 3, c: VERIFY_CODE });164  });165});166167// ── ChunkBuffer adversarial ────────────────────────────────────────────────168169describe("ChunkBuffer adversarial", () => {170  it("foreign verifyCode is rejected as foreign_codex", async () => {171    const buf = new ChunkBuffer();172    await buf.add(await makeEnv({ index: 0, total: 5 }));173    const res = await buf.add(174      await makeEnv({ index: 1, total: 5, verifyCode: "PX-OTHR-XXXX" })175    );176    expect(res).toEqual({ accepted: false, reason: "foreign_codex" });177  });178179  it("tampered hash is rejected as bad_integrity", async () => {180    const buf = new ChunkBuffer();181    const env = await makeEnv({ index: 0, total: 5 });182    const tampered = { ...env, h: "00000000" };183    const res = await buf.add(tampered);184    expect(res).toEqual({ accepted: false, reason: "bad_integrity" });185  });186187  it("data tampered without rehashing is rejected", async () => {188    const buf = new ChunkBuffer();189    const env = await makeEnv({ index: 0, total: 5 });190    const tampered: ChunkEnvelope = {191      ...env,192      d: bytesToBase64Url(new Uint8Array([99, 99, 99])),193    };194    const res = await buf.add(tampered);195    expect(res).toEqual({ accepted: false, reason: "bad_integrity" });196  });197198  it("wrong envelope version is rejected as parse_error", async () => {199    const buf = new ChunkBuffer();200    const env = await makeEnv({ index: 0, total: 5 });201    const wrong = { ...env, v: 1 } as unknown as ChunkEnvelope;202    const res = await buf.add(wrong);203    expect(res).toEqual({ accepted: false, reason: "parse_error" });204  });205206  it("duplicate chunk index is dedup'd", async () => {207    const buf = new ChunkBuffer();208    const env = await makeEnv({ index: 2, total: 5 });209    expect((await buf.add(env)).accepted).toBe(true);210    const second = await buf.add(env);211    expect(second).toEqual({ accepted: false, reason: "duplicate" });212    expect(buf.size()).toBe(1);213  });214215  for (const idx of [0, 1, 2, 3, 4]) {216    it(`accepts chunk at index ${idx}`, async () => {217      const buf = new ChunkBuffer();218      const env = await makeEnv({ index: idx, total: 5 });219      const res = await buf.add(env);220      expect(res.accepted).toBe(true);221    });222  }223224  for (const total of [3, 5, 7, 10, 20]) {225    it(`context dataShards matches deriveShardCounts at total=${total}`, async () => {226      const buf = new ChunkBuffer();227      await buf.add(await makeEnv({ index: 0, total }));228      const ctx = buf.getContext();229      expect(ctx?.dataShards).toBe(deriveShardCounts(total).dataShards);230    });231  }232233  it("reconstructAndVerify on empty buffer throws CodexError", async () => {234    const buf = new ChunkBuffer();235    await expect(reconstructAndVerify(buf)).rejects.toThrow(CodexError);236  });237238  // PCH-01-010: computeParityShards saturates at 35, so without an upper bound on239  // dataShards the inversion accepts absurd totals and wedges a stripe.240  it("derive_shard_counts_rejects_absurd_total", () => {241    expect(() => deriveShardCounts(1_000_000_000)).toThrow(CodexError);242  });243244  it("derive_shard_counts_accepts_real_max", () => {245    // dataShards = 200 (MAX_DATA_SHARDS_PER_STRIPE) with its saturated parity (35).246    const total = 200 + computeParityShards(200);247    const counts = deriveShardCounts(total);248    expect(counts.dataShards).toBe(200);249  });250251  // PCH-01-011: a crafted stripe count S must be rejected before it pins252  // this.stripeCount and drives O(S) allocation on the popup's render path.253  it("chunk_buffer_rejects_oversized_stripe_count", async () => {254    const buf = new ChunkBuffer();255    const env = await buildChunkEnvelope(new Uint8Array([1, 2, 3, 4, 5]), 0, 5, false, VERIFY_CODE, 0, 2 ** 31);256    const res = await buf.add(env);257    expect(res).toEqual({ accepted: false, reason: "parse_error" });258    expect(buf.getContext()).toBeNull();259  });260261  it("chunk_buffer_accepts_max_stripe_count", async () => {262    const buf = new ChunkBuffer();263    const env = await buildChunkEnvelope(new Uint8Array([1, 2, 3, 4, 5]), 0, 5, false, VERIFY_CODE, 0, 64);264    const res = await buf.add(env);265    expect(res.accepted).toBe(true);266  });267268  // PCH-01-012: fractional i/t/s/S must be rejected by parseRawScan (NaN/Infinity269  // are not JSON-representable, so fractional is the reachable hostile case).270  it("parse_raw_scan_rejects_non_integer_index", async () => {271    const env = await makeEnv({ index: 0, total: 5 });272    expect(parseRawScan(JSON.stringify({ ...env, i: 1.5 }))).toEqual({ error: "parse_error" });273    expect(parseRawScan(JSON.stringify({ ...env, t: 5.5 }))).toEqual({ error: "parse_error" });274    expect(parseRawScan(JSON.stringify({ ...env, s: 0.5 }))).toEqual({ error: "parse_error" });275    expect(parseRawScan(JSON.stringify({ ...env, S: 1.5 }))).toEqual({ error: "parse_error" });276  });277});278279// ── verifyChunkIntegrity adversarial ────────────────────────────────────────280281describe("verifyChunkIntegrity adversarial", () => {282  it("correct envelope verifies true", async () => {283    const env = await makeEnv({ index: 0, total: 5 });284    expect(await verifyChunkIntegrity(env)).toBe(true);285  });286287  const corruptHashes = [288    "00000000",289    "FFFFFFFF",290    "ZZZZZZZZ",291    "abcdef12",292    "",293  ];294  for (const h of corruptHashes) {295    it(`tampered hash ${JSON.stringify(h)} verifies false`, async () => {296      const env = await makeEnv({ index: 0, total: 5 });297      const tampered = { ...env, h };298      expect(await verifyChunkIntegrity(tampered)).toBe(false);299    });300  }301302  for (let i = 0; i < 5; i++) {303    it(`random data tamper #${i} verifies false`, async () => {304      const env = await makeEnv({ index: 0, total: 5 });305      const bytes = new Uint8Array([306        Math.floor(Math.random() * 256),307        Math.floor(Math.random() * 256),308        Math.floor(Math.random() * 256),309      ]);310      const tampered = { ...env, d: bytesToBase64Url(bytes) };311      // The new data hash will almost certainly differ from env.h.312      const recomputed = (await sha256Hex(bytes)).slice(0, 16);313      if (recomputed === env.h) return; // 1-in-2^64 lottery; skip.314      expect(await verifyChunkIntegrity(tampered)).toBe(false);315    });316  }317});318319// ── encodeWithErasure / decodeWithErasure adversarial ───────────────────────320321describe("encodeWithErasure / decodeWithErasure adversarial", () => {322  it("encoding empty input still produces at least 1 data shard", async () => {323    const { dataChunks, parityChunks, totalChunks, dataShards, parityShards } =324      await encodeWithErasure(new Uint8Array());325    expect(dataShards).toBeGreaterThanOrEqual(1);326    expect(parityShards).toBe(computeParityShards(dataShards));327    expect(totalChunks).toBe(dataShards + parityShards);328    expect(dataChunks.length).toBe(dataShards);329    expect(parityChunks.length).toBe(parityShards);330  });331332  for (const size of [1, 100, 1023, 1024, 1025, 5000, 10000]) {333    it(`encode/decode round-trips data of size ${size}`, async () => {334      const data = crypto.getRandomValues(new Uint8Array(size));335      const { dataChunks, parityChunks, dataShards, totalChunks } =336        await encodeWithErasure(data);337      const map = new Map<number, Uint8Array>();338      [...dataChunks, ...parityChunks].forEach((c, i) => map.set(i, c));339      const decoded = await decodeWithErasure(map, dataShards, totalChunks);340      expect(decoded.length).toBe(dataShards * CHUNK_SIZE);341      // First `size` bytes of decoded should equal original.342      for (let i = 0; i < size; i++) {343        expect(decoded[i]).toBe(data[i]);344      }345    });346  }347348  it("decoding with empty chunk map throws CodexError", async () => {349    await expect(350      decodeWithErasure(new Map(), 5, 7)351    ).rejects.toThrow(CodexError);352  });353354  it("decoding with fewer chunks than dataShards throws CodexError", async () => {355    const data = crypto.getRandomValues(new Uint8Array(5000));356    const { dataChunks, dataShards, totalChunks } = await encodeWithErasure(357      data358    );359    // Use only one data chunk — less than dataShards.360    const map = new Map<number, Uint8Array>();361    map.set(0, dataChunks[0]!);362    await expect(363      decodeWithErasure(map, dataShards, totalChunks)364    ).rejects.toThrow(CodexError);365  });366367  it("chunk index out of range throws CodexError", async () => {368    const data = crypto.getRandomValues(new Uint8Array(2048));369    const { dataChunks, dataShards, totalChunks } = await encodeWithErasure(370      data371    );372    const map = new Map<number, Uint8Array>();373    map.set(999, dataChunks[0]!);374    await expect(375      decodeWithErasure(map, dataShards, totalChunks)376    ).rejects.toThrow(CodexError);377  });378379  it("chunk with wrong size throws CodexError", async () => {380    const data = crypto.getRandomValues(new Uint8Array(2048));381    const { dataChunks, dataShards, totalChunks } = await encodeWithErasure(382      data383    );384    const map = new Map<number, Uint8Array>();385    // Stuff a wrong-size chunk at index 0.386    map.set(0, new Uint8Array(100));387    for (let i = 1; i < dataShards; i++) map.set(i, dataChunks[i]!);388    await expect(389      decodeWithErasure(map, dataShards, totalChunks)390    ).rejects.toThrow(CodexError);391  });392393  it("dropping 1 data chunk (within parity budget) reconstructs", async () => {394    const data = crypto.getRandomValues(new Uint8Array(8000));395    const { dataChunks, parityChunks, dataShards, totalChunks } =396      await encodeWithErasure(data);397    const map = new Map<number, Uint8Array>();398    // Drop dataChunks[0]; rely on parity.399    for (let i = 1; i < dataShards; i++) map.set(i, dataChunks[i]!);400    parityChunks.forEach((c, j) => map.set(dataShards + j, c));401    const decoded = await decodeWithErasure(map, dataShards, totalChunks);402    expect(decoded.length).toBe(dataShards * CHUNK_SIZE);403    for (let i = 0; i < data.length; i++) {404      expect(decoded[i]).toBe(data[i]);405    }406  });407408  it("dropping all data chunks (only parity present) fails when k < dataShards", async () => {409    const data = crypto.getRandomValues(new Uint8Array(8000));410    const { parityChunks, dataShards, totalChunks } = await encodeWithErasure(411      data412    );413    // Only parity present; with parity < dataShards the decoder must refuse.414    if (parityChunks.length >= dataShards) return;415    const map = new Map<number, Uint8Array>();416    parityChunks.forEach((c, j) => map.set(dataShards + j, c));417    await expect(418      decodeWithErasure(map, dataShards, totalChunks)419    ).rejects.toThrow(CodexError);420  });421422  it("dropping too many data chunks (more than parity) fails cleanly", async () => {423    const data = crypto.getRandomValues(new Uint8Array(20000));424    const { dataChunks, parityChunks, dataShards, parityShards, totalChunks } =425      await encodeWithErasure(data);426    if (dataShards <= parityShards + 1) return; // need enough shards to test.427    const map = new Map<number, Uint8Array>();428    // Drop parityShards + 1 data chunks (one more than the budget allows).429    for (let i = parityShards + 1; i < dataShards; i++) {430      map.set(i, dataChunks[i]!);431    }432    parityChunks.forEach((c, j) => map.set(dataShards + j, c));433    await expect(434      decodeWithErasure(map, dataShards, totalChunks)435    ).rejects.toThrow(CodexError);436  });437});438439// ── reconstructAndVerify with full pipeline ────────────────────────────────440441describe("reconstructAndVerify adversarial", () => {442  it("round-trips a payload via ChunkBuffer + reconstructAndVerify", async () => {443    const payload = await makePayload(2000);444    const envs = await buildEnvelopesForPayload(payload);445    const buf = new ChunkBuffer();446    for (const e of envs) await buf.add(e);447    const reconstructed = await reconstructAndVerify(buf);448    expect(reconstructed.vaultFingerprint).toBe(payload.vaultFingerprint);449    expect(reconstructed.entryCount).toBe(payload.entryCount);450  });451452  it("missing chunks but enough parity still reconstructs", async () => {453    const payload = await makePayload(5000);454    const envs = await buildEnvelopesForPayload(payload);455    if (envs.length <= 3) return; // need room to drop one and still have parity456    const buf = new ChunkBuffer();457    // Skip the first data chunk (index 0). Fill the rest.458    for (let i = 1; i < envs.length; i++) await buf.add(envs[i]!);459    const reconstructed = await reconstructAndVerify(buf);460    expect(reconstructed.vaultFingerprint).toBe(payload.vaultFingerprint);461  });462463  it("tampered chunk data (after acceptance) does not round-trip", async () => {464    const payload = await makePayload(3000);465    const envs = await buildEnvelopesForPayload(payload);466    const buf = new ChunkBuffer();467    // Tamper one envelope's `d` field by replacing with random bytes plus468    // recomputed hash so the integrity check passes.469    const evil = envs[0]!;470    const fakeBytes = crypto.getRandomValues(new Uint8Array(CHUNK_SIZE));471    const fakeHash = (await sha256Hex(fakeBytes)).slice(0, 16);472    const fakeEnv: ChunkEnvelope = {473      ...evil,474      d: bytesToBase64Url(fakeBytes),475      h: fakeHash,476    };477    await buf.add(fakeEnv);478    for (let i = 1; i < envs.length; i++) await buf.add(envs[i]!);479    // Reconstruction should fail fingerprint check.480    await expect(reconstructAndVerify(buf)).rejects.toThrow(CodexError);481  });482});483484// ── Aztec-decoded raw payload adversarial ──────────────────────────────────485486describe("parseRawScan with adversarial raw strings (no-crash)", () => {487  const inputs = [488    "{}",489    '{"a":1,"b":2}',490    '{"v":2}',491    '{"v":2,"c":""}',492    '{"v":2,"c":"' + "A".repeat(10000) + '"}',493    '{"v":2,"c":"PX-XXXX-XXXX","i":-1,"t":5,"p":false,"d":"","h":""}',494    '{"v":2,"c":"PX-XXXX-XXXX","i":99,"t":5,"p":false,"d":"","h":""}',495    '{"v":2,"c":"PX-XXXX-XXXX","i":0,"t":-5,"p":false,"d":"","h":""}',496    '{"v":2,"c":"PX-XXXX-XXXX","i":0,"t":5,"p":"yes","d":"","h":""}',497    '{"v":2,"c":"PX-XXXX-XXXX","i":0,"t":5,"p":false,"d":null,"h":null}',498  ];499  for (const raw of inputs) {500    it(`parseRawScan does not crash on ${raw.slice(0, 50)}`, () => {501      const result = parseRawScan(raw);502      expect(result).toBeDefined();503    });504  }505});506507// ── Verify code matching ────────────────────────────────────────────────────508509describe("ChunkBuffer verify code adversarial", () => {510  const foreignCodes = [511    "PX-OTHR-1234",512    "PX-AAAA-AAAA",513    "PX-1111-1111",514    "PX-9999-9999",515    "PX-ABCD-EFGH",516  ];517  for (const code of foreignCodes) {518    it(`buffer rejects foreign code ${code}`, async () => {519      const buf = new ChunkBuffer();520      await buf.add(await makeEnv({ index: 0, total: 5 }));521      const foreign = await makeEnv({ index: 1, total: 5, verifyCode: code });522      const res = await buf.add(foreign);523      expect(res.accepted).toBe(false);524      expect(res.reason).toBe("foreign_codex");525    });526  }527});528529// ── Round-trip fuzz across data sizes ───────────────────────────────────────530531describe("erasure round-trip size sweep", () => {532  for (const size of [533    0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 1024, 1025, 1500, 2048,534    3000, 4096, 5000, 7500, 10000,535  ]) {536    it(`size ${size} round-trips correctly`, async () => {537      const data = crypto.getRandomValues(new Uint8Array(size));538      const { dataChunks, parityChunks, dataShards, totalChunks } =539        await encodeWithErasure(data);540      const map = new Map<number, Uint8Array>();541      [...dataChunks, ...parityChunks].forEach((c, i) => map.set(i, c));542      const decoded = await decodeWithErasure(map, dataShards, totalChunks);543      for (let i = 0; i < size; i++) {544        expect(decoded[i]).toBe(data[i]);545      }546    });547548    it(`size ${size} drop-first-parity still decodes`, async () => {549      const data = crypto.getRandomValues(new Uint8Array(size));550      const { dataChunks, dataShards, totalChunks } = await encodeWithErasure(551        data552      );553      const map = new Map<number, Uint8Array>();554      dataChunks.forEach((c, i) => map.set(i, c));555      // No parity present, but all data; decode succeeds.556      const decoded = await decodeWithErasure(map, dataShards, totalChunks);557      for (let i = 0; i < size; i++) {558        expect(decoded[i]).toBe(data[i]);559      }560    });561  }562});563564// ── Boundary: many envelopes ────────────────────────────────────────────────565566describe("ChunkBuffer scale", () => {567  for (const total of [3, 5, 10]) {568    const dataShards = deriveShardCounts(total).dataShards;569    it(`buffer accepts ${dataShards} data chunks and reports ready`, async () => {570      const buf = new ChunkBuffer();571      for (let i = 0; i < dataShards; i++) {572        const res = await buf.add(await makeEnv({ index: i, total }));573        expect(res.accepted).toBe(true);574      }575      expect(buf.isReady()).toBe(true);576    });577  }578});579580// ── AUD-004: 128-bit integrity prefixes ────────────────────────────────────581582describe("Codex integrity prefix length (AUD-004)", () => {583  it("chunk hash is 32 hex chars (128 bits)", async () => {584    const bytes = new Uint8Array([1, 2, 3, 4, 5]);585    const env = await buildChunkEnvelope(bytes, 0, 10, false, "PX-TEST-1234");586    expect(env.h).toHaveLength(32);587    expect(env.h).toMatch(/^[0-9A-F]{32}$/);588  });589590  it("verifyChunkIntegrity passes for current 32-char hash", async () => {591    const bytes = new Uint8Array([1, 2, 3]);592    const env = await buildChunkEnvelope(bytes, 0, 5, false, "PX-TEST-1234");593    expect(env.h).toHaveLength(32);594    expect(await verifyChunkIntegrity(env)).toBe(true);595  });596597  it("verifyChunkIntegrity still passes for legacy 16-char hash", async () => {598    const bytes = new Uint8Array([1, 2, 3]);599    const fullHash = await sha256Hex(bytes);600    const env = await buildChunkEnvelope(bytes, 0, 5, false, "PX-TEST-1234");601    const legacy = { ...env, h: fullHash.slice(0, 16) };602    expect(await verifyChunkIntegrity(legacy)).toBe(true);603  });604605  it("verifyChunkIntegrity rejects tampered 32-char hash", async () => {606    const bytes = new Uint8Array([1, 2, 3]);607    const env = await buildChunkEnvelope(bytes, 0, 5, false, "PX-TEST-1234");608    const tampered = { ...env, h: "X".repeat(32) };609    expect(await verifyChunkIntegrity(tampered)).toBe(false);610  });611612  it("verifyChunkIntegrity rejects tampered 16-char legacy hash", async () => {613    const bytes = new Uint8Array([1, 2, 3]);614    const env = await buildChunkEnvelope(bytes, 0, 5, false, "PX-TEST-1234");615    const tampered = { ...env, h: "X".repeat(16) };616    expect(await verifyChunkIntegrity(tampered)).toBe(false);617  });618});