/**
 * PIV/CAC Smart Card Authentication Types
 *
 * Type definitions for Personal Identity Verification (PIV) and
 * Common Access Card (CAC) smart card authentication.
 *
 * Supports:
 * - X.509 certificate authentication
 * - OCSP/CRL certificate validation
 * - Certificate-to-user mapping (UPN/SAN)
 * - Card removal session termination
 * - DoD PKI compatibility
 *
 * @packageDocumentation
 */
import { z } from 'zod';
// =============================================================================
// Enums
// =============================================================================
/**
 * Certificate validation status
 */
export var CertificateValidationStatus;
(function (CertificateValidationStatus) {
    /** Certificate is valid */
    CertificateValidationStatus["VALID"] = "valid";
    /** Certificate has been revoked */
    CertificateValidationStatus["REVOKED"] = "revoked";
    /** Certificate has expired */
    CertificateValidationStatus["EXPIRED"] = "expired";
    /** Certificate is not yet valid */
    CertificateValidationStatus["NOT_YET_VALID"] = "not_yet_valid";
    /** Certificate chain is incomplete or invalid */
    CertificateValidationStatus["CHAIN_INVALID"] = "chain_invalid";
    /** Certificate signature verification failed */
    CertificateValidationStatus["SIGNATURE_INVALID"] = "signature_invalid";
    /** Unable to verify certificate status */
    CertificateValidationStatus["UNKNOWN"] = "unknown";
})(CertificateValidationStatus || (CertificateValidationStatus = {}));
export const certificateValidationStatusSchema = z.nativeEnum(CertificateValidationStatus);
/**
 * Certificate revocation check method
 */
export var RevocationCheckMethod;
(function (RevocationCheckMethod) {
    /** Online Certificate Status Protocol */
    RevocationCheckMethod["OCSP"] = "ocsp";
    /** Certificate Revocation List */
    RevocationCheckMethod["CRL"] = "crl";
    /** Both OCSP and CRL */
    RevocationCheckMethod["BOTH"] = "both";
    /** OCSP with CRL fallback */
    RevocationCheckMethod["OCSP_WITH_CRL_FALLBACK"] = "ocsp_with_crl_fallback";
    /** No revocation checking (not recommended) */
    RevocationCheckMethod["NONE"] = "none";
})(RevocationCheckMethod || (RevocationCheckMethod = {}));
export const revocationCheckMethodSchema = z.nativeEnum(RevocationCheckMethod);
/**
 * PIV key usage types
 */
export var PIVKeyUsage;
(function (PIVKeyUsage) {
    /** PIV Authentication key */
    PIVKeyUsage["PIV_AUTHENTICATION"] = "piv_authentication";
    /** Card Authentication key */
    PIVKeyUsage["CARD_AUTHENTICATION"] = "card_authentication";
    /** Digital Signature key */
    PIVKeyUsage["DIGITAL_SIGNATURE"] = "digital_signature";
    /** Key Management key */
    PIVKeyUsage["KEY_MANAGEMENT"] = "key_management";
})(PIVKeyUsage || (PIVKeyUsage = {}));
export const pivKeyUsageSchema = z.nativeEnum(PIVKeyUsage);
/**
 * Certificate mapping strategy
 */
export var CertificateMappingStrategy;
(function (CertificateMappingStrategy) {
    /** Map using Subject Alternative Name (SAN) */
    CertificateMappingStrategy["SAN"] = "san";
    /** Map using User Principal Name (UPN) from SAN */
    CertificateMappingStrategy["UPN"] = "upn";
    /** Map using email address from SAN or Subject */
    CertificateMappingStrategy["EMAIL"] = "email";
    /** Map using Subject Distinguished Name */
    CertificateMappingStrategy["SUBJECT_DN"] = "subject_dn";
    /** Map using certificate serial number + issuer */
    CertificateMappingStrategy["SERIAL_ISSUER"] = "serial_issuer";
    /** Custom mapping function */
    CertificateMappingStrategy["CUSTOM"] = "custom";
})(CertificateMappingStrategy || (CertificateMappingStrategy = {}));
export const certificateMappingStrategySchema = z.nativeEnum(CertificateMappingStrategy);
/**
 * Card event types
 */
export var CardEventType;
(function (CardEventType) {
    /** Card inserted into reader */
    CardEventType["CARD_INSERTED"] = "card_inserted";
    /** Card removed from reader */
    CardEventType["CARD_REMOVED"] = "card_removed";
    /** Card reader connected */
    CardEventType["READER_CONNECTED"] = "reader_connected";
    /** Card reader disconnected */
    CardEventType["READER_DISCONNECTED"] = "reader_disconnected";
    /** PIN entry required */
    CardEventType["PIN_REQUIRED"] = "pin_required";
    /** PIN verified successfully */
    CardEventType["PIN_VERIFIED"] = "pin_verified";
    /** PIN verification failed */
    CardEventType["PIN_FAILED"] = "pin_failed";
    /** Card locked due to failed PIN attempts */
    CardEventType["CARD_LOCKED"] = "card_locked";
})(CardEventType || (CardEventType = {}));
export const cardEventTypeSchema = z.nativeEnum(CardEventType);
export const x509ExtensionSchema = z.object({
    oid: z.string(),
    critical: z.boolean(),
    value: z.string(),
    parsed: z.record(z.unknown()).optional(),
});
export const subjectAltNameSchema = z.object({
    type: z.enum(['email', 'dns', 'uri', 'ip', 'upn', 'other']),
    value: z.string(),
    oid: z.string().optional(),
});
export const distinguishedNameSchema = z.object({
    CN: z.string().optional(),
    O: z.string().optional(),
    OU: z.string().optional(),
    C: z.string().optional(),
    ST: z.string().optional(),
    L: z.string().optional(),
    E: z.string().optional(),
    serialNumber: z.string().optional(),
    full: z.string(),
});
export const parsedCertificateSchema = z.object({
    version: z.number(),
    serialNumber: z.string(),
    signatureAlgorithm: z.string(),
    issuer: distinguishedNameSchema,
    subject: distinguishedNameSchema,
    notBefore: z.coerce.date(),
    notAfter: z.coerce.date(),
    publicKeyAlgorithm: z.string(),
    publicKey: z.string(),
    subjectAltNames: z.array(subjectAltNameSchema),
    keyUsage: z.array(z.string()).optional(),
    extendedKeyUsage: z.array(z.string()).optional(),
    extensions: z.array(x509ExtensionSchema),
    authorityInfoAccess: z
        .object({
        ocsp: z.array(z.string()).optional(),
        caIssuers: z.array(z.string()).optional(),
    })
        .optional(),
    crlDistributionPoints: z.array(z.string()).optional(),
    fingerprint: z.string(),
    publicKeyFingerprint: z.string(),
    pem: z.string(),
    der: z.string(),
});
export const certificateChainSchema = z.object({
    endEntity: parsedCertificateSchema,
    intermediates: z.array(parsedCertificateSchema),
    root: parsedCertificateSchema.optional(),
});
export const ocspResponseSchema = z.object({
    status: z.enum(['good', 'revoked', 'unknown']),
    revocationTime: z.coerce.date().optional(),
    revocationReason: z.string().optional(),
    producedAt: z.coerce.date(),
    thisUpdate: z.coerce.date(),
    nextUpdate: z.coerce.date().optional(),
    responderId: z.string(),
    fromCache: z.boolean(),
    responderUrl: z.string(),
});
export const crlEntrySchema = z.object({
    serialNumber: z.string(),
    revocationDate: z.coerce.date(),
    reasonCode: z.number().optional(),
    reason: z.string().optional(),
});
export const crlDataSchema = z.object({
    issuer: distinguishedNameSchema,
    thisUpdate: z.coerce.date(),
    nextUpdate: z.coerce.date().optional(),
    revokedCertificates: z.array(crlEntrySchema),
    crlNumber: z.string().optional(),
    isDelta: z.boolean(),
    distributionPoint: z.string(),
    fromCache: z.boolean(),
});
export const certificateValidationResultSchema = z.object({
    status: certificateValidationStatusSchema,
    isValid: z.boolean(),
    errors: z.array(z.string()),
    warnings: z.array(z.string()),
    chainValidation: z
        .object({
        valid: z.boolean(),
        depth: z.number(),
        errors: z.array(z.string()),
    })
        .optional(),
    ocspResult: ocspResponseSchema.optional(),
    crlResult: crlDataSchema.optional(),
    validatedAt: z.coerce.date(),
    expiresAt: z.coerce.date(),
    trustAnchor: z.string().optional(),
});
export const mappedUserIdentitySchema = z.object({
    userId: z.string(),
    username: z.string().optional(),
    email: z.string().optional(),
    upn: z.string().optional(),
    edipi: z.string().optional(),
    tenantId: z.string().optional(),
    attributes: z.record(z.string()),
    mappingStrategy: certificateMappingStrategySchema,
    certificateFingerprint: z.string(),
});
export const certificateMappingRuleSchema = z.object({
    name: z.string(),
    priority: z.number(),
    issuerPattern: z.string().optional(),
    subjectPattern: z.string().optional(),
    requiredPolicyOid: z.string().optional(),
    strategy: certificateMappingStrategySchema,
    userIdAttribute: z.string().optional(),
    tenantId: z.string().optional(),
    attributeMappings: z.record(z.string()).optional(),
});
export const cardEventSchema = z.object({
    type: cardEventTypeSchema,
    readerName: z.string(),
    timestamp: z.coerce.date(),
    atr: z.string().optional(),
    sessionId: z.string().optional(),
    userId: z.string().optional(),
});
export const cardSessionBindingSchema = z.object({
    sessionId: z.string(),
    userId: z.string(),
    certificateFingerprint: z.string(),
    readerName: z.string(),
    atr: z.string(),
    createdAt: z.coerce.date(),
    lastActivity: z.coerce.date(),
    expiresAt: z.coerce.date(),
});
export const trustedCAConfigSchema = z.object({
    name: z.string(),
    certificate: z.string(),
    isRoot: z.boolean(),
    trustedPolicies: z.array(z.string()).optional(),
    maxPathLength: z.number().optional(),
});
export const ocspConfigSchema = z.object({
    enabled: z.boolean().default(true),
    responderUrl: z.string().url().optional(),
    timeout: z.number().default(5000),
    cacheTtl: z.number().default(3600000), // 1 hour
    signRequests: z.boolean().default(false),
    signingCertificate: z.string().optional(),
    signingKey: z.string().optional(),
    softFail: z.boolean().default(false),
    useNonce: z.boolean().default(true),
});
export const crlConfigSchema = z.object({
    enabled: z.boolean().default(true),
    distributionPointUrl: z.string().url().optional(),
    timeout: z.number().default(30000),
    cacheTtl: z.number().optional(),
    refreshBefore: z.number().default(300000), // 5 minutes
    maxSize: z.number().default(10 * 1024 * 1024), // 10MB
    softFail: z.boolean().default(false),
    checkDelta: z.boolean().default(true),
});
export const pkcs11ConfigSchema = z.object({
    libraryPath: z.string(),
    slotId: z.number().optional(),
    tokenLabel: z.string().optional(),
    pin: z.string().optional(),
    initializeToken: z.boolean().default(false),
    pollingInterval: z.number().default(1000),
});
export const cardRemovalPolicySchema = z.object({
    terminateSession: z.boolean().default(true),
    gracePeriod: z.number().default(0),
    allowReauthentication: z.boolean().default(false),
    reauthenticationTimeout: z.number().default(60000),
    notificationWebhook: z.string().url().optional(),
});
export const pivCacConfigSchema = z.object({
    enabled: z.boolean().default(false),
    trustedCAs: z.array(trustedCAConfigSchema).default([]),
    revocationMethod: revocationCheckMethodSchema.default(RevocationCheckMethod.OCSP_WITH_CRL_FALLBACK),
    ocsp: ocspConfigSchema.default({
        enabled: true,
        timeout: 5000,
        cacheTtl: 3600000,
        signRequests: false,
        softFail: false,
        useNonce: true,
    }),
    crl: crlConfigSchema.default({
        enabled: true,
        timeout: 30000,
        refreshBefore: 300000,
        maxSize: 10 * 1024 * 1024,
        softFail: false,
        checkDelta: true,
    }),
    pkcs11: pkcs11ConfigSchema.optional(),
    cardRemovalPolicy: cardRemovalPolicySchema.default({
        terminateSession: true,
        gracePeriod: 0,
        allowReauthentication: false,
        reauthenticationTimeout: 60000,
    }),
    mappingRules: z.array(certificateMappingRuleSchema).default([]),
    requiredKeyUsage: z.array(pivKeyUsageSchema).default([PIVKeyUsage.PIV_AUTHENTICATION]),
    requiredExtendedKeyUsage: z.array(z.string()).optional(),
    requiredPolicies: z.array(z.string()).optional(),
    allowExpired: z.boolean().default(false),
    maxChainDepth: z.number().default(5),
    sessionTtl: z.number().default(28800000), // 8 hours
    dodPkiCompatibility: z.boolean().default(false),
    fips201Compliance: z.boolean().default(false),
    cacheValidation: z.boolean().default(true),
    validationCacheTtl: z.number().default(300000), // 5 minutes
});
export const pivAuthRequestSchema = z.object({
    clientCertificate: z.string(),
    certificateChain: z.string().optional(),
    pin: z.string().optional(),
    challenge: z.string().optional(),
    signedChallenge: z.string().optional(),
});
export const pivAuthResultSchema = z.object({
    success: z.boolean(),
    error: z.string().optional(),
    errorCode: z.string().optional(),
    user: mappedUserIdentitySchema.optional(),
    sessionId: z.string().optional(),
    expiresAt: z.coerce.date().optional(),
    validation: certificateValidationResultSchema.optional(),
    accessToken: z.string().optional(),
    refreshToken: z.string().optional(),
});
export const pivAuthContextSchema = z.object({
    isPIVAuthenticated: z.boolean(),
    user: mappedUserIdentitySchema.optional(),
    certificate: parsedCertificateSchema.optional(),
    validation: certificateValidationResultSchema.optional(),
    sessionBinding: cardSessionBindingSchema.optional(),
});
export const pivMiddlewareOptionsSchema = z.object({
    skipPaths: z.array(z.string()).optional(),
    requiredPaths: z.array(z.string()).optional(),
    certificateHeader: z.string().default('x-client-certificate'),
    certificateChainHeader: z.string().default('x-client-certificate-chain'),
    // Function options cannot be validated with zod
});
// =============================================================================
// Default Configuration
// =============================================================================
/**
 * Default PIV/CAC configuration
 */
export const DEFAULT_PIVCAC_CONFIG = {
    enabled: false,
    trustedCAs: [],
    revocationMethod: RevocationCheckMethod.OCSP_WITH_CRL_FALLBACK,
    ocsp: {
        enabled: true,
        timeout: 5000,
        cacheTtl: 3600000,
        signRequests: false,
        softFail: false,
        useNonce: true,
    },
    crl: {
        enabled: true,
        timeout: 30000,
        refreshBefore: 300000,
        maxSize: 10 * 1024 * 1024,
        softFail: false,
        checkDelta: true,
    },
    cardRemovalPolicy: {
        terminateSession: true,
        gracePeriod: 0,
        allowReauthentication: false,
        reauthenticationTimeout: 60000,
    },
    mappingRules: [],
    requiredKeyUsage: [PIVKeyUsage.PIV_AUTHENTICATION],
    allowExpired: false,
    maxChainDepth: 5,
    sessionTtl: 28800000,
    dodPkiCompatibility: false,
    fips201Compliance: false,
    cacheValidation: true,
    validationCacheTtl: 300000,
};
/**
 * DoD PKI compatible configuration preset
 */
export const DOD_PKI_CONFIG = {
    dodPkiCompatibility: true,
    fips201Compliance: true,
    revocationMethod: RevocationCheckMethod.OCSP_WITH_CRL_FALLBACK,
    requiredKeyUsage: [PIVKeyUsage.PIV_AUTHENTICATION],
    requiredExtendedKeyUsage: [
        '1.3.6.1.5.5.7.3.2', // id-kp-clientAuth
        '1.3.6.1.4.1.311.20.2.2', // Microsoft Smart Card Logon
    ],
    requiredPolicies: [
        '2.16.840.1.101.2.1.11.19', // DoD ID SW
        '2.16.840.1.101.2.1.11.20', // DoD ID HW
    ],
    maxChainDepth: 6,
    ocsp: {
        enabled: true,
        timeout: 10000,
        cacheTtl: 3600000,
        signRequests: false,
        softFail: false,
        useNonce: true,
    },
    crl: {
        enabled: true,
        timeout: 60000,
        refreshBefore: 600000,
        maxSize: 50 * 1024 * 1024,
        softFail: false,
        checkDelta: true,
    },
};
// =============================================================================
// Error Types
// =============================================================================
/**
 * PIV authentication error codes
 */
export var PIVErrorCode;
(function (PIVErrorCode) {
    /** Certificate not provided */
    PIVErrorCode["CERTIFICATE_MISSING"] = "CERTIFICATE_MISSING";
    /** Certificate parsing failed */
    PIVErrorCode["CERTIFICATE_PARSE_ERROR"] = "CERTIFICATE_PARSE_ERROR";
    /** Certificate expired */
    PIVErrorCode["CERTIFICATE_EXPIRED"] = "CERTIFICATE_EXPIRED";
    /** Certificate not yet valid */
    PIVErrorCode["CERTIFICATE_NOT_YET_VALID"] = "CERTIFICATE_NOT_YET_VALID";
    /** Certificate revoked */
    PIVErrorCode["CERTIFICATE_REVOKED"] = "CERTIFICATE_REVOKED";
    /** Certificate chain invalid */
    PIVErrorCode["CERTIFICATE_CHAIN_INVALID"] = "CERTIFICATE_CHAIN_INVALID";
    /** Certificate signature invalid */
    PIVErrorCode["CERTIFICATE_SIGNATURE_INVALID"] = "CERTIFICATE_SIGNATURE_INVALID";
    /** Certificate key usage invalid */
    PIVErrorCode["CERTIFICATE_KEY_USAGE_INVALID"] = "CERTIFICATE_KEY_USAGE_INVALID";
    /** Certificate policy invalid */
    PIVErrorCode["CERTIFICATE_POLICY_INVALID"] = "CERTIFICATE_POLICY_INVALID";
    /** OCSP check failed */
    PIVErrorCode["OCSP_CHECK_FAILED"] = "OCSP_CHECK_FAILED";
    /** CRL check failed */
    PIVErrorCode["CRL_CHECK_FAILED"] = "CRL_CHECK_FAILED";
    /** User mapping failed */
    PIVErrorCode["USER_MAPPING_FAILED"] = "USER_MAPPING_FAILED";
    /** User not found */
    PIVErrorCode["USER_NOT_FOUND"] = "USER_NOT_FOUND";
    /** Card removed */
    PIVErrorCode["CARD_REMOVED"] = "CARD_REMOVED";
    /** Card locked */
    PIVErrorCode["CARD_LOCKED"] = "CARD_LOCKED";
    /** PIN required */
    PIVErrorCode["PIN_REQUIRED"] = "PIN_REQUIRED";
    /** PIN invalid */
    PIVErrorCode["PIN_INVALID"] = "PIN_INVALID";
    /** PKCS#11 error */
    PIVErrorCode["PKCS11_ERROR"] = "PKCS11_ERROR";
    /** Session expired */
    PIVErrorCode["SESSION_EXPIRED"] = "SESSION_EXPIRED";
    /** Configuration error */
    PIVErrorCode["CONFIGURATION_ERROR"] = "CONFIGURATION_ERROR";
    /** Internal error */
    PIVErrorCode["INTERNAL_ERROR"] = "INTERNAL_ERROR";
})(PIVErrorCode || (PIVErrorCode = {}));
export const pivErrorCodeSchema = z.nativeEnum(PIVErrorCode);
//# sourceMappingURL=types.js.map