"use strict";

const test = require("node:test");
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { GhdrAuthorizer } = require("./ghdr-authorizer");

test("GHDR authorizer persists a private key without exposing it and signs a two-minute capability", () => {
  const directory = fs.mkdtempSync(path.join(os.tmpdir(), "ghdr-authorizer-"));
  try {
    const privateKeyFile = path.join(directory, "authorizer.pem");
    const authorizer = new GhdrAuthorizer({ privateKeyFile, now: () => 1000 });
    const issued = authorizer.issue({
      controllerNodeId: "GH-CTRL-GZ-01",
      targetNodeId: "GH-CVM-MAIN-PROD-01",
      layoutPayloadSha256: "a".repeat(64),
      resource: `GH-CVM-MAIN-PROD-01:${"a".repeat(64)}:1`,
      workorderId: "00000000-0000-4000-8000-000000000001",
    });
    assert.equal(fs.statSync(privateKeyFile).mode & 0o777, 0o600);
    assert.equal(issued.capability.expires_at_unix, 1120);
    const publicKey = crypto.createPublicKey(authorizer.publicBinding().public_key_pem);
    assert.equal(
      crypto.verify(
        null,
        Buffer.from(JSON.stringify(issued.capability)),
        publicKey,
        Buffer.from(issued.capability_signature_base64url, "base64url"),
      ),
      true,
    );
    assert.doesNotMatch(JSON.stringify(authorizer.publicBinding()), /PRIVATE KEY/);
  } finally {
    fs.rmSync(directory, { recursive: true, force: true });
  }
});
