示例工程 46-csp-navigation-integrity

46-csp-navigation-integrity/demo-02-integrity-hash/integrity.ts

typescript · 1.7 KB

import crypto from "node:crypto";

type Entry = { fileName: string; sha256: string };
type Manifest = { version: number; algorithm: "sha256"; files: Entry[] };

function hash(text: string): string {
  return crypto.createHash("sha256").update(text, "utf8").digest("hex");
}

function verify(manifest: Manifest, file: { name: string; content: string }) {
  const entry = manifest.files.find((row) => row.fileName === file.name);
  const actual = hash(file.content);
  return {
    fileName: file.name,
    expected: entry?.sha256 ?? "",
    actual,
    ok: entry !== undefined && entry.sha256 === actual,
    reason: entry === undefined ? "NOT_IN_MANIFEST" : "CHECKED",
  };
}

const original = "XWRT Tutorials · 资源完整性示例\n";
const tampered = `${original}攻击者追加的一行\n`;

const manifest: Manifest = {
  version: 1,
  algorithm: "sha256",
  files: [{ fileName: "notice.txt", sha256: hash(original) }],
};

const good = verify(manifest, { name: "notice.txt", content: original });
const bad = verify(manifest, { name: "notice.txt", content: tampered });
const missing = verify(manifest, { name: "extra.txt", content: original });

const ok =
  good.ok &&
  good.actual === manifest.files[0]?.sha256 &&
  !bad.ok &&
  bad.expected === good.expected &&
  bad.actual !== good.actual &&
  !missing.ok &&
  missing.reason === "NOT_IN_MANIFEST";

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    manifestVersion: manifest.version,
    good: {
      expected: good.expected.slice(0, 12),
      actual: good.actual.slice(0, 12),
      ok: good.ok,
    },
    bad: {
      expected: bad.expected.slice(0, 12),
      actual: bad.actual.slice(0, 12),
      ok: bad.ok,
    },
    missing: { reason: missing.reason, ok: missing.ok },
  }),
);