appCaCert.test.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { X509Certificate } from "node:crypto";
  2. import { mkdtempSync, readFileSync, statSync } from "node:fs";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { ensureAppCaCert, getAppCaCertPaths } from "../src/runtime-tools/appCaCert.js";
  7. import { setDataBaseDir } from "../src/paths.js";
  8. describe("ensureAppCaCert", () => {
  9. afterEach(() => {
  10. setDataBaseDir(null);
  11. });
  12. it("generates a self-signed CA certificate and private key on first run", () => {
  13. setDataBaseDir(mkdtempSync(join(tmpdir(), "zcode-ca-")));
  14. const certPath = ensureAppCaCert();
  15. const { keyPath } = getAppCaCertPaths();
  16. const cert = new X509Certificate(readFileSync(certPath));
  17. expect(cert.subject).toContain("ZCode Network CA");
  18. // 自签:issuer == subject
  19. expect(cert.issuer).toBe(cert.subject);
  20. expect(cert.ca).toBe(true);
  21. const keyPem = readFileSync(keyPath, "utf8");
  22. expect(keyPem).toContain("PRIVATE KEY");
  23. // 私钥权限收紧(POSIX)
  24. if (process.platform !== "win32") {
  25. expect(statSync(keyPath).mode & 0o077).toBe(0);
  26. }
  27. });
  28. it("is idempotent: reuses the existing certificate", () => {
  29. setDataBaseDir(mkdtempSync(join(tmpdir(), "zcode-ca-")));
  30. const certPath = ensureAppCaCert();
  31. const firstPem = readFileSync(certPath, "utf8");
  32. const secondPath = ensureAppCaCert();
  33. expect(secondPath).toBe(certPath);
  34. expect(readFileSync(secondPath, "utf8")).toBe(firstPem);
  35. });
  36. });