"use strict";

const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const test = require("node:test");
const { collectChangedFiles, validManifestPath, validRequest, verifySignature } = require("../receiver");

test("verifies Forgejo HMAC signatures", () => {
  const secret = "a".repeat(32);
  const body = Buffer.from('{"ok":true}');
  const signature = crypto.createHmac("sha256", secret).update(body).digest("hex");
  assert.equal(verifySignature(secret, body, signature), true);
  assert.equal(verifySignature(secret, body, "0".repeat(64)), false);
});

test("accepts only safe manifest paths", () => {
  assert.equal(validManifestPath("deployment/requests/REQ-001.json", "deployment/requests/"), true);
  assert.equal(validManifestPath("deployment/requests/../../secret.json", "deployment/requests/"), false);
  assert.equal(validManifestPath("deployment/requests/REQ 001.json", "deployment/requests/"), false);
});

test("rejects arbitrary command fields", () => {
  assert.equal(validRequest({ request_id: "REQ-20260713-001", module: "gatekeeper", action: "inspect-gatekeeper", approved: true }), true);
  assert.equal(validRequest({ request_id: "REQ-20260713-001", module: "gatekeeper", action: "inspect-gatekeeper", approved: true, cmd: "rm -rf /" }), false);
});

test("collects only added and modified files", () => {
  assert.deepEqual(collectChangedFiles({ commits: [{ added: ["a"], modified: ["b"], removed: ["c"] }] }).sort(), ["a", "b"]);
});
