import { expect, test } from "bun:test";
import { createKeyring, generateKey, seal } from "@wrnexus/encryption";
import { createAuthSecretProtector } from "../src/protector.ts";

test("secret protector binds encrypted values to their auth purpose", async () => {
  const keyring = createKeyring([{ id: "primary", secret: await generateKey(), active: true }]);
  const protector = createAuthSecretProtector(keyring);
  const protectedValue = await protector.protect("secret-value", "totp");

  expect(await protector.reveal(protectedValue, "totp")).toBe("secret-value");
  await expect(protector.reveal(protectedValue, "oauth-access")).rejects.toThrow(
    "WRN-AUTH-SECRET-PURPOSE",
  );
});

test("secret protector can read legacy unbound ciphertext", async () => {
  const keyring = createKeyring([{ id: "primary", secret: await generateKey(), active: true }]);
  const protector = createAuthSecretProtector(keyring);
  const legacy = await seal("legacy-secret", keyring);
  expect(await protector.reveal(legacy, "oauth-refresh")).toBe("legacy-secret");
});
