// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Vorion LLC
/**
 * Security Hardening Types
 *
 * Type definitions for CAR ID security hardening controls including:
 * - DPoP (Demonstrating Proof-of-Possession)
 * - TEE (Trusted Execution Environment) binding
 * - Pairwise DID configuration
 * - Revocation SLA configuration
 * - Token lifetime configuration
 *
 * Based on CAR ID Security Hardening Specification v1.0.0
 *
 * @packageDocumentation
 */
/// <reference lib="dom" />
import { z } from 'zod';
// =============================================================================
// Trust Tier Types (aligned with CAR ID spec)
// =============================================================================
/**
 * Trust tiers as defined in CAR ID specification
 * Maps to security conformance levels:
 * - T0-T1: No minimum security (not recommended)
 * - T2: SH-1 (Basic) - DPoP, short-lived tokens
 * - T3: SH-2 (Standard) - SH-1 + pairwise DIDs, recursive revocation
 * - T4-T5: SH-3 (Hardened) - SH-2 + TEE binding, sync revocation checks
 */
export const TrustTier = {
    T0: 0,
    T1: 1,
    T2: 2,
    T3: 3,
    T4: 4,
    T5: 5,
    T6: 6,
    T7: 7,
};
export const trustTierSchema = z.nativeEnum(TrustTier);
/**
 * Security conformance levels
 */
export const SecurityConformanceLevel = {
    NONE: 'none',
    SH1_BASIC: 'sh-1',
    SH2_STANDARD: 'sh-2',
    SH3_HARDENED: 'sh-3',
};
export const securityConformanceLevelSchema = z.nativeEnum(SecurityConformanceLevel);
export const dpopProofSchema = z.object({
    jti: z.string().min(1),
    htm: z.string().min(1),
    htu: z.string().url(),
    iat: z.number().int().positive(),
    ath: z.string().optional(),
});
export const dpopHeaderSchema = z.object({
    typ: z.literal('dpop+jwt'),
    alg: z.enum(['ES256', 'ES384', 'ES512']),
    jwk: z.record(z.unknown()),
});
export const dpopConfigSchema = z.object({
    requiredForTiers: z.array(trustTierSchema),
    maxProofAge: z.number().int().positive().default(60),
    nonceRequired: z.boolean().default(false),
    clockSkewTolerance: z.number().int().nonnegative().default(5),
    allowedAlgorithms: z.array(z.enum(['ES256', 'ES384', 'ES512'])).default(['ES256']),
});
export const dpopVerificationResultSchema = z.object({
    valid: z.boolean(),
    keyThumbprint: z.string().optional(),
    error: z.string().optional(),
    errorCode: z.enum(['INVALID_SIGNATURE', 'EXPIRED', 'REPLAY', 'METHOD_MISMATCH', 'URI_MISMATCH', 'INVALID_FORMAT']).optional(),
    verifiedAt: z.string().datetime(),
});
// =============================================================================
// TEE (Trusted Execution Environment) Types
// =============================================================================
/**
 * Supported TEE platforms
 */
export const TEEPlatform = {
    SGX: 'sgx',
    NITRO: 'nitro',
    SEV: 'sev',
    TRUSTZONE: 'trustzone',
    SECURE_ENCLAVE: 'secure-enclave',
};
export const teePlatformSchema = z.nativeEnum(TEEPlatform);
export const teeAttestationSchema = z.object({
    platform: teePlatformSchema,
    measurementHash: z.string().min(1),
    timestamp: z.coerce.date(),
    enclaveId: z.string().min(1),
    pcrs: z.record(z.string()).optional(),
    signature: z.string().optional(),
    certificateChain: z.array(z.string()).optional(),
    attestationEndpoint: z.string().url().optional(),
    validUntil: z.coerce.date().optional(),
});
export const teeKeyBindingSchema = z.object({
    didKeyId: z.string().min(1),
    enclaveKeyId: z.string().min(1),
    bindingProof: z.string().min(1),
    boundAt: z.coerce.date(),
    validUntil: z.coerce.date().optional(),
});
export const teeConfigSchema = z.object({
    requiredForTiers: z.array(trustTierSchema).default([TrustTier.T4, TrustTier.T5]),
    allowedPlatforms: z.array(teePlatformSchema).default([TEEPlatform.SGX, TEEPlatform.NITRO]),
    maxAttestationAge: z.number().int().positive().default(86400), // 24 hours
    expectedMeasurements: z.record(z.string()).optional(),
    attestationVerificationEndpoint: z.string().url().optional(),
});
export const teeVerificationResultSchema = z.object({
    valid: z.boolean(),
    reason: z.string().optional(),
    platform: teePlatformSchema.optional(),
    measurementHash: z.string().optional(),
    verifiedAt: z.string().datetime(),
});
// =============================================================================
// Pairwise DID Types
// =============================================================================
/**
 * Data types that may require pairwise DIDs
 */
export const DataClassification = {
    PUBLIC: 'public',
    BUSINESS: 'business',
    PERSONAL: 'personal',
    SENSITIVE: 'sensitive',
    REGULATED: 'regulated',
};
export const dataClassificationSchema = z.nativeEnum(DataClassification);
/**
 * Pairwise DID derivation algorithm
 */
export const PairwiseDerivationAlgorithm = {
    SHA256: 'sha256',
    HKDF: 'hkdf',
};
export const pairwiseDerivationAlgorithmSchema = z.nativeEnum(PairwiseDerivationAlgorithm);
export const pairwiseDIDConfigSchema = z.object({
    requiredForDataTypes: z.array(dataClassificationSchema).default([
        DataClassification.PERSONAL,
        DataClassification.SENSITIVE,
        DataClassification.REGULATED,
    ]),
    derivationAlgorithm: pairwiseDerivationAlgorithmSchema.default(PairwiseDerivationAlgorithm.HKDF),
    saltLength: z.number().int().min(16).default(32),
    hkdfInfo: z.string().default('aci-pairwise-did-v1'),
});
export const pairwiseDerivationSchema = z.object({
    masterDid: z.string().min(1),
    relyingPartyDid: z.string().min(1),
    contextSalt: z.string().min(1),
    derivedDid: z.string().min(1),
    createdAt: z.coerce.date(),
});
export const revocationSLASchema = z.object({
    tier: trustTierSchema,
    maxPropagationLatencyMs: z.number().int().positive(),
    syncCheckRequired: z.boolean(),
    introspectionRequired: z.boolean(),
});
/**
 * Default revocation SLAs per CAR ID spec
 */
export const DEFAULT_REVOCATION_SLAS = [
    { tier: TrustTier.T0, maxPropagationLatencyMs: 60000, syncCheckRequired: false, introspectionRequired: false },
    { tier: TrustTier.T1, maxPropagationLatencyMs: 60000, syncCheckRequired: false, introspectionRequired: false },
    { tier: TrustTier.T2, maxPropagationLatencyMs: 30000, syncCheckRequired: false, introspectionRequired: false },
    { tier: TrustTier.T3, maxPropagationLatencyMs: 10000, syncCheckRequired: false, introspectionRequired: false },
    { tier: TrustTier.T4, maxPropagationLatencyMs: 1000, syncCheckRequired: true, introspectionRequired: true },
    { tier: TrustTier.T5, maxPropagationLatencyMs: 1000, syncCheckRequired: true, introspectionRequired: true },
];
export const revocationPropagationPolicySchema = z.object({
    terminateDescendants: z.boolean().default(true),
    gracePeriodMs: z.number().int().nonnegative().default(0),
    notifyWebhooks: z.boolean().default(true),
});
export const revocationPropagationSchema = z.object({
    revokedDid: z.string().min(1),
    reason: z.string().min(1),
    propagationPolicy: revocationPropagationPolicySchema,
});
export const revocationResultSchema = z.object({
    revocationId: z.string().uuid(),
    revokedDid: z.string().min(1),
    descendantsRevoked: z.array(z.string()),
    tokensInvalidated: z.number().int().nonnegative(),
    propagationComplete: z.boolean(),
    timestamp: z.coerce.date(),
});
/**
 * Revocation status
 */
export const RevocationStatusEnum = {
    ACTIVE: 'active',
    REVOKED: 'revoked',
    PENDING: 'pending',
};
export const revocationStatusEnumSchema = z.nativeEnum(RevocationStatusEnum);
export const revocationStatusSchema = z.object({
    did: z.string().min(1),
    status: revocationStatusEnumSchema,
    revokedAt: z.coerce.date().optional(),
    reason: z.string().optional(),
    fromCache: z.boolean(),
    cacheAgeMs: z.number().int().nonnegative().optional(),
});
export const revocationEventSchema = z.object({
    type: z.enum(['agent.revoked', 'delegation.terminated', 'token.invalidated']),
    revocationId: z.string().uuid(),
    did: z.string().min(1),
    reason: z.string().min(1),
    timestamp: z.coerce.date(),
    metadata: z.record(z.unknown()).optional(),
});
export const tokenLifetimeConfigSchema = z.object({
    accessTokenMaxTTL: z.number().int().positive().default(300),
    refreshTokenMaxTTL: z.number().int().positive().default(86400),
    idTokenMaxTTL: z.number().int().positive().default(300),
    highValueOperationTTL: z.number().int().positive().default(60),
    refreshThreshold: z.number().min(0).max(1).default(0.2), // Refresh when 20% TTL remaining
});
/**
 * Default token lifetime configuration
 */
export const DEFAULT_TOKEN_LIFETIME_CONFIG = {
    accessTokenMaxTTL: 300, // 5 minutes
    refreshTokenMaxTTL: 86400, // 24 hours
    idTokenMaxTTL: 300, // 5 minutes
    highValueOperationTTL: 60, // 1 minute
    refreshThreshold: 0.2,
};
export const introspectionResultSchema = z.object({
    active: z.boolean(),
    scope: z.string().optional(),
    clientId: z.string().optional(),
    username: z.string().optional(),
    tokenType: z.string().optional(),
    exp: z.number().int().optional(),
    iat: z.number().int().optional(),
    nbf: z.number().int().optional(),
    sub: z.string().optional(),
    aud: z.union([z.string(), z.array(z.string())]).optional(),
    iss: z.string().optional(),
    jti: z.string().optional(),
    cnf: z.object({ jkt: z.string().optional() }).optional(),
    introspectedAt: z.string().datetime(),
    fromCache: z.boolean(),
});
export const agentIdentitySchema = z.object({
    did: z.string().min(1),
    trustTier: trustTierSchema,
    capabilityLevel: z.number().int().min(0).max(5),
    didDocument: z.unknown().optional(),
    teeBinding: teeKeyBindingSchema.optional(),
    attestationChain: z.array(z.unknown()).optional(),
});
export const actionRequestSchema = z.object({
    requestId: z.string().min(1),
    method: z.string().min(1),
    uri: z.string().min(1),
    actionType: z.string().min(1),
    actionLevel: z.number().int().min(0).max(5),
    domains: z.array(z.string()).optional(),
    isHighValue: z.boolean().optional(),
    dataClassification: dataClassificationSchema.optional(),
});
export const securityContextSchema = z.object({
    agent: agentIdentitySchema,
    request: actionRequestSchema,
    accessToken: z.string().min(1),
    dpopProof: z.string().optional(),
    dpopKey: z.record(z.unknown()).optional(),
    teeAttestation: teeAttestationSchema.optional(),
    pairwiseDid: z.string().optional(),
});
export const securityValidationErrorSchema = z.object({
    code: z.string().min(1),
    message: z.string().min(1),
    component: z.enum(['dpop', 'tee', 'pairwise', 'revocation', 'token', 'introspection']),
});
export const securityValidationResultSchema = z.object({
    valid: z.boolean(),
    errors: z.array(securityValidationErrorSchema),
    securityLevel: securityConformanceLevelSchema,
    warnings: z.array(z.string()),
    validatedAt: z.string().datetime(),
});
export const preRequestResultSchema = z.object({
    allow: z.boolean(),
    requiredActions: z.array(z.enum(['dpop', 'tee_attestation', 'pairwise_did', 'introspection'])).optional(),
    requirements: z.lazy(() => securityRequirementsSchema),
    denyReason: z.string().optional(),
});
export const highValueCheckResultSchema = z.object({
    allow: z.boolean(),
    introspectionPerformed: z.boolean(),
    syncRevocationCheck: z.boolean(),
    tokenTTLRemaining: z.number().int().optional(),
    denyReason: z.string().optional(),
});
export const securityRequirementsSchema = z.object({
    tier: trustTierSchema,
    conformanceLevel: securityConformanceLevelSchema,
    dpopRequired: z.boolean(),
    teeRequired: z.boolean(),
    pairwiseRequired: z.boolean(),
    syncRevocationRequired: z.boolean(),
    maxTokenTTL: z.number().int().positive(),
    maxChainDepth: z.number().int().min(0),
});
/**
 * Get security requirements for a trust tier
 */
export function getSecurityRequirementsForTier(tier) {
    switch (tier) {
        case TrustTier.T0:
        case TrustTier.T1:
            return {
                tier,
                conformanceLevel: SecurityConformanceLevel.NONE,
                dpopRequired: false,
                teeRequired: false,
                pairwiseRequired: false,
                syncRevocationRequired: false,
                maxTokenTTL: 3600, // 1 hour
                maxChainDepth: 1, // No delegation
            };
        case TrustTier.T2:
            return {
                tier,
                conformanceLevel: SecurityConformanceLevel.SH1_BASIC,
                dpopRequired: true,
                teeRequired: false,
                pairwiseRequired: false,
                syncRevocationRequired: false,
                maxTokenTTL: 300, // 5 minutes
                maxChainDepth: 2,
            };
        case TrustTier.T3:
            return {
                tier,
                conformanceLevel: SecurityConformanceLevel.SH2_STANDARD,
                dpopRequired: true,
                teeRequired: false,
                pairwiseRequired: true,
                syncRevocationRequired: false,
                maxTokenTTL: 300, // 5 minutes
                maxChainDepth: 3,
            };
        case TrustTier.T4:
        case TrustTier.T5:
            return {
                tier,
                conformanceLevel: SecurityConformanceLevel.SH3_HARDENED,
                dpopRequired: true,
                teeRequired: true,
                pairwiseRequired: true,
                syncRevocationRequired: true,
                maxTokenTTL: 300, // 5 minutes
                maxChainDepth: tier === TrustTier.T4 ? 5 : 5,
            };
        default:
            throw new Error(`Unknown trust tier: ${tier}`);
    }
}
export const incomingRequestSchema = z.object({
    requestId: z.string().min(1),
    method: z.string().min(1),
    uri: z.string().min(1),
    authorization: z.string().optional(),
    dpop: z.string().optional(),
    headers: z.record(z.union([z.string(), z.array(z.string()), z.undefined()])),
});
export const securityPluginOptionsSchema = z.object({
    dpop: dpopConfigSchema.partial().optional(),
    tee: teeConfigSchema.partial().optional(),
    pairwiseDid: pairwiseDIDConfigSchema.partial().optional(),
    revocationSLAs: z.array(revocationSLASchema).optional(),
    tokenLifetime: tokenLifetimeConfigSchema.partial().optional(),
    introspectionEndpoint: z.string().url().optional(),
    skipPaths: z.array(z.string()).optional(),
    enableMetrics: z.boolean().optional(),
});
//# sourceMappingURL=types.js.map