"use strict";
/**
 * RED-GREEN tests for the insurance certificate signer.
 *
 * @connexum/ai-governance  Insurance Certificate
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const node_test_1 = require("node:test");
const assert = __importStar(require("node:assert/strict"));
const insurance_certificate_1 = require("./insurance-certificate");
const signed_manifest_1 = require("./signed-manifest");
const agent_trust_report_1 = require("./agent-trust-report");
const trust_score_three_dim_1 = require("./trust-score-three-dim");
const owasp_agentic_scanner_1 = require("./owasp-agentic-scanner");
const improvement_recommendations_1 = require("./improvement-recommendations");
const cleanManifest = () => ({
    agentId: 'agent-x',
    tools: [],
    hooks: { preToolUse: true, postToolUse: true, postResponse: true },
    llmProvider: 'connexum-proxy/anthropic',
    pluginIntegrityVerified: true,
    rateLimitsConfigured: true,
    declaredApprovalGates: [],
    declaredForbiddenCapabilities: [],
});
function makeReport() {
    const dim = (c) => ({
        scope_adherence: c, policy_compliance: c, anomaly_rate: c,
        incident_history: c, behavioral_consistency: c, composite: c,
    });
    const opDim = (c) => ({
        out_of_scope_ingestion: c, scope_violation_by_team: c,
        scope_violation_by_data_class: c, human_override_frequency: c, composite: c,
    });
    const bDim = (c) => ({
        owasp_agentic_score: c, hook_coverage_count: 3,
        declared_capability_class_count: 4, has_human_in_loop: true,
        plugin_integrity_verified: true, proxy_routed: true, composite: c,
    });
    const scan = (0, owasp_agentic_scanner_1.scanAgent)(cleanManifest());
    return (0, agent_trust_report_1.generateAgentTrustReport)({
        agentId: 'agent-x',
        orgId: 'subject-org',
        period: { from: '2026-05-01T00:00:00.000Z', to: '2026-05-12T00:00:00.000Z' },
        packBindings: ['hipaa'],
        score: (0, trust_score_three_dim_1.composeThreeDimensionalScore)({
            agent_activity: dim(90),
            operator_activity: opDim(90),
            agent_build_structure: bDim(90),
        }),
        scanReport: scan,
        recommendations: (0, improvement_recommendations_1.buildRecommendationSet)({ agentId: 'agent-x', buildScan: scan }),
    });
}
(0, node_test_1.describe)('insurance certificate signer', () => {
    (0, node_test_1.it)('issues a certificate and verifies it with the issuer public key', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
        });
        const payload = (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, publicKey);
        assert.equal(payload.issuerOrgId, 'issuer-org');
        assert.equal(payload.subjectOrgId, 'subject-org');
        assert.equal(payload.class, 'standard');
        assert.equal(payload.report.agentId, 'agent-x');
    });
    (0, node_test_1.it)('subjectOrgId defaults to the report.orgId when not supplied', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
        });
        const payload = (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, publicKey);
        assert.equal(payload.subjectOrgId, 'subject-org'); // from report.orgId
    });
    (0, node_test_1.it)('explicit certClass is preserved', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            certClass: 'attested',
            privateKey,
        });
        const payload = (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, publicKey);
        assert.equal(payload.class, 'attested');
    });
    (0, node_test_1.it)('verification rejects a tampered payload', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
        });
        const tampered = {
            ...cert,
            payload: { ...cert.payload, class: 'attested' },
        };
        assert.throws(() => (0, insurance_certificate_1.verifyInsuranceCertificate)(tampered, publicKey), (e) => e.code === 'INVALID_SIGNATURE');
    });
    (0, node_test_1.it)('verification rejects signature from a different private key', () => {
        const { privateKey: pkA } = (0, signed_manifest_1.generateOrgKeyPair)();
        const { publicKey: pubB } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey: pkA,
        });
        assert.throws(() => (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, pubB), (e) => e.code === 'INVALID_SIGNATURE');
    });
    (0, node_test_1.it)('expectedIssuerOrgId mismatch is rejected (confused-deputy guard)', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
        });
        assert.throws(() => (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, publicKey, {
            expectedIssuerOrgId: 'a-different-issuer',
        }), (e) => e.code === 'ISSUER_MISMATCH');
    });
    (0, node_test_1.it)('expired certificate is rejected (default max-age 90 days)', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const old = new Date(Date.now() - (insurance_certificate_1.DEFAULT_CERT_MAX_AGE_DAYS + 5) * 24 * 60 * 60 * 1000).toISOString();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
            nowIso: old,
        });
        assert.throws(() => (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, publicKey), (e) => e.code === 'EXPIRED');
    });
    (0, node_test_1.it)('explicit expiresAt overrides the default max-age window', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const now = new Date().toISOString();
        const future = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
            nowIso: now,
            expiresAt: future,
        });
        const payload = (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, publicKey);
        assert.equal(payload.expiresAt, future);
    });
    (0, node_test_1.it)('certificate issued at a future timestamp beyond skew is rejected', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const future = new Date(Date.now() + 60 * 60 * 1000).toISOString();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
            nowIso: future,
        });
        assert.throws(() => (0, insurance_certificate_1.verifyInsuranceCertificate)(cert, publicKey), (e) => e.code === 'NOT_YET_VALID');
    });
    (0, node_test_1.it)('missing issuerOrgId throws', () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        assert.throws(() => (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: '',
            privateKey,
        }));
    });
    (0, node_test_1.it)('certificateFingerprint produces a stable 16-char base64url id', () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert1 = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
            nowIso: '2026-05-12T00:00:00.000Z',
        });
        const fp = (0, insurance_certificate_1.certificateFingerprint)(cert1);
        assert.equal(fp.length, 16);
        assert.match(fp, /^[A-Za-z0-9_-]+$/);
        // Same cert -> same fingerprint
        assert.equal((0, insurance_certificate_1.certificateFingerprint)(cert1), fp);
    });
    (0, node_test_1.it)('different reports produce different fingerprints', () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const c1 = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: { ...makeReport(), id: 'cr-1' },
            issuerOrgId: 'issuer-org',
            privateKey,
        });
        const c2 = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: { ...makeReport(), id: 'cr-2' },
            issuerOrgId: 'issuer-org',
            privateKey,
        });
        assert.notEqual((0, insurance_certificate_1.certificateFingerprint)(c1), (0, insurance_certificate_1.certificateFingerprint)(c2));
    });
    (0, node_test_1.it)('alg field is locked to ed25519; mismatched alg fails verification', () => {
        const { publicKey, privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const cert = (0, insurance_certificate_1.issueInsuranceCertificate)({
            report: makeReport(),
            issuerOrgId: 'issuer-org',
            privateKey,
        });
        const bad = { ...cert, alg: 'hmac-sha256' };
        assert.throws(() => (0, insurance_certificate_1.verifyInsuranceCertificate)(bad, publicKey), (e) => e.code === 'MALFORMED');
    });
});
//# sourceMappingURL=insurance-certificate.test.js.map