import type { Result } from '@private.me/shared';
import type { DIDStateCheckpoint } from './checkpoint.js';
/**
 * Rate limiter for DID registration endpoints.
 *
 * Implements sliding window algorithm with:
 * - Per-IP limit: 10 registrations/hour
 * - Global limit: 1000 registrations/hour
 *
 * Prevents DID registration spam attacks (SCALE-1).
 */
export declare class RegistrationRateLimiter {
    private readonly perIPTimestamps;
    private readonly globalTimestamps;
    private readonly perIPLimit;
    private readonly globalLimit;
    private readonly windowMs;
    private cleanupInterval;
    /**
     * Create a new registration rate limiter.
     *
     * @param perIPLimit - Maximum registrations per IP in time window (default: 10)
     * @param globalLimit - Maximum global registrations in time window (default: 1000)
     * @param windowMs - Time window in milliseconds (default: 3600000 = 1 hour)
     */
    constructor(perIPLimit?: number, globalLimit?: number, windowMs?: number);
    /**
     * Check if registration is allowed for the given IP.
     *
     * @param ip - Client IP address
     * @returns True if allowed, false if rate limited
     */
    checkLimit(ip: string): boolean;
    /**
     * Record a registration attempt.
     *
     * Call this AFTER successful registration to avoid counting failures.
     *
     * @param ip - Client IP address
     */
    recordRegistration(ip: string): void;
    /**
     * Get remaining registrations for an IP.
     *
     * @param ip - Client IP address
     * @returns Remaining registrations allowed
     */
    getRemainingForIP(ip: string): number;
    /**
     * Get remaining global registrations.
     *
     * @returns Remaining global registrations allowed
     */
    getRemainingGlobal(): number;
    /**
     * Get reset time for an IP's rate limit.
     *
     * @param ip - Client IP address
     * @returns Unix timestamp (ms) when limit resets, or null if not rate limited
     */
    getResetTimeForIP(ip: string): number | null;
    /**
     * Cleanup old timestamps to prevent memory leaks.
     *
     * Removes entries with no requests in the last window period.
     */
    cleanup(): void;
    /**
     * Stop cleanup interval (for testing or shutdown).
     */
    destroy(): void;
    /**
     * Reset all rate limits (for testing).
     */
    reset(): void;
}
/** Trust registry error codes. */
export type RegistryError = 'NOT_FOUND' | 'ALREADY_REGISTERED' | 'REVOKED' | 'EXPIRED' | 'NETWORK_ERROR' | 'RATE_LIMIT_EXCEEDED';
/** Metadata stored for a registered DID. */
export interface RegistryEntry {
    readonly did: string;
    readonly publicKey: Uint8Array;
    readonly name: string;
    readonly scopes: ReadonlySet<string>;
    /** Scopes this agent accepts for incoming messages. Undefined = defaults to send scopes. */
    readonly receiveScopes?: ReadonlySet<string>;
    readonly revoked: boolean;
    /** Optional X25519 public key for ECDH forward secrecy. */
    readonly x25519PublicKey?: Uint8Array;
    /** Optional ML-KEM-768 public key for hybrid post-quantum KEM (1184 bytes). */
    readonly mlKemPublicKey?: Uint8Array;
    /** Optional ML-DSA-65 public key for hybrid post-quantum signatures (1952 bytes). */
    readonly mlDsaPublicKey?: Uint8Array;
    /** Whether this agent supports Xchange (XorIDA key transport). */
    readonly xchange?: boolean;
    /** Current rotation sequence for this DID (prevents rollback attacks). */
    readonly rotation_sequence: number;
    /** SDK version (semver format, e.g., "1.2.3"). Optional for backward compatibility. */
    readonly sdkVersion?: string;
    /** Minimum supported envelope version. Optional for backward compatibility. */
    readonly minEnvelopeVersion?: number;
    /** Maximum supported envelope version. Optional for backward compatibility. */
    readonly maxEnvelopeVersion?: number;
    /** Unix timestamp (milliseconds) when this entry expires. Undefined = never expires. */
    readonly expiresAt?: number;
}
/** Trust event types for real-time registry updates. */
export interface TrustEvent {
    /** Event type: 'revocation' (DID revoked) or 'succession' (key rotated). */
    readonly type: 'revocation' | 'succession';
    /** DID that triggered the event. */
    readonly did: string;
    /** Unix timestamp (milliseconds) when the event occurred. */
    readonly timestamp: number;
    /** Cryptographic proof for succession events (e.g., signature from old key). */
    readonly proof?: Uint8Array;
}
/** Options for registering a DID with the trust registry. */
export interface RegistrationOptions {
    /** DID to register. */
    readonly did: string;
    /** Ed25519 public key bytes. */
    readonly publicKey: Uint8Array;
    /** Display name for the agent. */
    readonly name: string;
    /** Scopes this agent requests. */
    readonly scopes?: string[];
    /** Optional X25519 public key for ECDH forward secrecy. */
    readonly x25519PublicKey?: Uint8Array;
    /** Optional ML-KEM-768 public key for hybrid post-quantum KEM (1184 bytes). */
    readonly mlKemPublicKey?: Uint8Array;
    /** Optional ML-DSA-65 public key for hybrid post-quantum signatures (1952 bytes). */
    readonly mlDsaPublicKey?: Uint8Array;
    /** Whether this agent supports Xchange (XorIDA key transport). */
    readonly xchange?: boolean;
    /** Scopes this agent accepts for incoming messages. Undefined = defaults to send scopes. */
    readonly receiveScopes?: string[];
    /** SDK version (semver format, e.g., "1.2.3"). Optional for backward compatibility. */
    readonly sdkVersion?: string;
    /** Minimum supported envelope version. Optional for backward compatibility. */
    readonly minEnvelopeVersion?: number;
    /** Maximum supported envelope version. Optional for backward compatibility. */
    readonly maxEnvelopeVersion?: number;
    /** Time-to-live in milliseconds. Undefined = never expires. */
    readonly ttlMs?: number;
    /** Client IP address (for rate limiting). */
    readonly clientIP?: string;
    /** Cryptographic signature (proof-of-possession). */
    readonly signature?: string;
}
/**
 * Trust registry for DID registration, resolution, and scope validation.
 *
 * MemoryTrustRegistry for development, HttpTrustRegistry for production.
 */
export interface TrustRegistry {
    /** Register a DID with its public key, name, and scopes. */
    register(opts: RegistrationOptions): Promise<Result<void, RegistryError>>;
    /** Resolve a DID to its raw public key bytes. */
    resolve(did: string): Promise<Result<Uint8Array, RegistryError>>;
    /** Check if a DID has a specific scope permission. */
    hasScope(did: string, scope: string): Promise<boolean>;
    /** Check if a DID accepts a specific scope for incoming messages. */
    hasReceiveScope(did: string, scope: string): Promise<boolean>;
    /** Revoke a DID immediately. */
    revoke(did: string): Promise<Result<void, RegistryError>>;
    /** Get the full registry entry for a DID. */
    getEntry(did: string): Promise<Result<RegistryEntry, RegistryError>>;
    /**
     * Rotate the public key for a DID (key succession).
     * Optional method - not all implementations support key rotation.
     *
     * @param did - DID to update
     * @param newPublicKey - New public key bytes
     * @param proof - Cryptographic proof (e.g., signature from old key authorizing rotation)
     * @param rotationSequence - New rotation sequence number (must be > current)
     */
    rotate?(did: string, newPublicKey: Uint8Array, proof: Uint8Array, rotationSequence: number): Promise<void>;
    /**
     * Subscribe to real-time trust events (revocations, key rotations).
     * Optional method - not all implementations support subscriptions.
     *
     * @param dids - Array of DIDs to watch
     * @param callback - Function called when events occur
     * @returns Unsubscribe function to stop watching
     */
    subscribe?(dids: string[], callback: (event: TrustEvent) => void): Promise<() => void>;
    /**
     * Update scopes for existing DID without revoking.
     * @param did - DID to update
     * @param scopes - New scopes (replaces existing)
     */
    updateScopes?(did: string, scopes: string[]): Promise<Result<void, RegistryError>>;
    /**
     * Remove all expired entries from the registry.
     * Optional method - not all implementations support cleanup.
     *
     * @returns Number of entries removed.
     */
    cleanup?(): Promise<number>;
}
/**
 * In-memory trust registry for development and testing.
 */
export declare class MemoryTrustRegistry implements TrustRegistry {
    private readonly entries;
    private readonly rateLimiter?;
    constructor(opts?: {
        enableRateLimiting?: boolean;
        rateLimiter?: RegistrationRateLimiter;
    });
    register(opts: RegistrationOptions): Promise<Result<void, RegistryError>>;
    resolve(did: string): Promise<Result<Uint8Array, RegistryError>>;
    hasScope(did: string, scope: string): Promise<boolean>;
    hasReceiveScope(did: string, scope: string): Promise<boolean>;
    revoke(did: string): Promise<Result<void, RegistryError>>;
    getEntry(did: string): Promise<Result<RegistryEntry, RegistryError>>;
    updateScopes(did: string, scopes: string[]): Promise<Result<void, RegistryError>>;
    /** Remove all expired entries from the registry. */
    cleanup(): Promise<number>;
    /** Number of entries (for testing). */
    get size(): number;
}
/** Options for HttpTrustRegistry. */
export interface HttpTrustRegistryOptions {
    /** Base URL of the trust registry server (e.g. https://atelier.xail.io). */
    readonly baseUrl: string;
    /** Custom fetch implementation (for testing). */
    readonly fetch?: typeof globalThis.fetch;
    /** Cache TTL in ms for resolve/getEntry results. Default: 30000 (30s). Set to 0 to disable. */
    readonly cacheTtlMs?: number;
    /** Cache failure behavior. Default: 'fail-secure' */
    readonly cacheFailureMode?: 'fail-secure' | 'fail-open';
    /** Enable push notification subscription. Default: false */
    readonly enablePush?: boolean;
    /** Bloom filter size for push filtering. Default: 10000 */
    readonly bloomFilterSize?: number;
    /** Bloom filter false positive rate. Default: 0.01 */
    readonly bloomFilterFpr?: number;
}
/**
 * HTTP-backed trust registry for production use.
 * Delegates to a remote atelier.xail.io service.
 */
export declare class HttpTrustRegistry implements TrustRegistry {
    private readonly baseUrl;
    private readonly fetchFn;
    private readonly cacheTtlMs;
    private readonly cacheFailureMode;
    private readonly enablePush;
    private readonly bloomFilterSize;
    private readonly bloomFilterFpr;
    private readonly resolveCache;
    private readonly entryCache;
    private readonly accessTokens;
    constructor(opts: HttpTrustRegistryOptions);
    /** Clear all cached entries. Call after registration or revocation. */
    clearCache(): void;
    register(opts: RegistrationOptions): Promise<Result<void, RegistryError>>;
    resolve(did: string): Promise<Result<Uint8Array, RegistryError>>;
    hasScope(did: string, scope: string): Promise<boolean>;
    hasReceiveScope(did: string, scope: string): Promise<boolean>;
    revoke(did: string): Promise<Result<void, RegistryError>>;
    getEntry(did: string): Promise<Result<RegistryEntry, RegistryError>>;
    /**
     * Rotate a DID to a new public key with cryptographic proof.
     *
     * Sends rotation request to gateway and invalidates local cache.
     *
     * @param did - DID being rotated (old key)
     * @param newPublicKey - New public key bytes
     * @param proof - Succession announcement (dual signatures from old and new keys)
     * @param rotationSequence - Monotonically increasing sequence number (prevents rollback)
     */
    rotate(did: string, newPublicKey: Uint8Array, proof: Uint8Array, rotationSequence: number): Promise<void>;
    /**
     * Subscribe to real-time trust events (revocation, key rotation).
     *
     * Creates a bloom filter from DIDs and connects WebSocket to gateway.
     * Events matching subscribed DIDs trigger the callback and invalidate cache.
     *
     * @param dids - Array of DIDs to monitor
     * @param callback - Function called when trust events occur
     * @returns Unsubscribe function to stop watching
     *
     * @throws Error if push notifications not enabled (enablePush: true)
     */
    subscribe(dids: string[], callback: (event: TrustEvent) => void): Promise<() => void>;
    /**
     * Simple hash function for bloom filter (DID → number).
     * Production implementation would use proper bloom filter hashing.
     */
    private hashDid;
    /**
     * Resume subscriptions on this gateway using proofs from another gateway.
     *
     * Allows clients to migrate between gateways without re-subscribing.
     * Validates proofs and restores subscription state.
     *
     * @param proofs - Array of subscription proofs from previous gateway.
     * @returns Success or error.
     *
     * @example
     * ```typescript
     * const registry = new HttpTrustRegistry({ baseUrl: 'https://atelier2.xail.io' });
     * const result = await registry.resumeSubscriptions([proof1, proof2]);
     * ```
     */
    resumeSubscriptions(proofs: Array<{
        peer_did: string;
        bloom_filter_hash: string;
        peer_signature: string;
    }>): Promise<Result<void, RegistryError>>;
    /**
     * Fetch signed checkpoint for a DID (freshness primitive).
     *
     * Checkpoints provide cryptographic proof of DID state at a specific timestamp.
     * Clients verify checkpoint signature and compare rotation_sequence to detect staleness.
     *
     * @param did - DID to fetch checkpoint for
     * @returns Signed checkpoint or error
     *
     * @example
     * ```typescript
     * const checkpoint = await registry.fetchCheckpoint('did:key:z6Mk...');
     * if (checkpoint.ok) {
     *   const verified = await verifyCheckpoint(checkpoint.value, gatewayPubKey);
     *   if (verified.ok && verified.value) {
     *     // Use checkpoint for staleness detection
     *     if (isCacheStale(localCache, checkpoint.value)) {
     *       // Refresh cache
     *     }
     *   }
     * }
     * ```
     */
    fetchCheckpoint(did: string): Promise<Result<DIDStateCheckpoint, RegistryError>>;
    updateScopes(did: string, scopes: string[]): Promise<Result<void, RegistryError>>;
}
/** Options for FileTrustRegistry. */
export interface FileTrustRegistryOptions {
    /** Path to JSONL file for persistent storage. */
    readonly path: string;
}
/**
 * File-based trust registry using JSONL append-only log.
 * Replays all entries on initialization, keeps in-memory Map for fast access.
 * Suitable for production deployments with local persistence.
 */
export declare class FileTrustRegistry implements TrustRegistry {
    private readonly path;
    private readonly entries;
    private initialized;
    constructor(opts: FileTrustRegistryOptions);
    /** Initialize by replaying JSONL log. Called automatically on first operation. */
    private init;
    /** Append record to JSONL file. */
    private append;
    register(opts: RegistrationOptions): Promise<Result<void, RegistryError>>;
    resolve(did: string): Promise<Result<Uint8Array, RegistryError>>;
    hasScope(did: string, scope: string): Promise<boolean>;
    hasReceiveScope(did: string, scope: string): Promise<boolean>;
    revoke(did: string): Promise<Result<void, RegistryError>>;
    getEntry(did: string): Promise<Result<RegistryEntry, RegistryError>>;
    updateScopes(did: string, scopes: string[]): Promise<Result<void, RegistryError>>;
    /** Remove all expired entries from the registry. */
    cleanup(): Promise<number>;
    /**
     * Rotate a DID to a new public key with rollback protection.
     *
     * Validates that rotationSequence is greater than current sequence to prevent
     * rollback attacks. Appends rotation event to JSONL and updates in-memory state.
     *
     * @param did - DID being rotated
     * @param newPublicKey - New public key bytes
     * @param proof - Cryptographic proof (e.g., signature from old key)
     * @param rotationSequence - Monotonically increasing sequence number
     * @throws Error if DID not found or sequence validation fails
     */
    rotate(did: string, newPublicKey: Uint8Array, proof: Uint8Array, rotationSequence: number): Promise<void>;
    /** Number of entries (for testing). */
    get size(): number;
}
/**
 * Create an enterprise trust registry with optional pre-population.
 * Suitable for corporate deployments with centralized trust management.
 *
 * @example
 * ```typescript
 * const registry = await TrustRegistry.enterprise({
 *   storage: 'file',
 *   path: '/opt/corp/trust.jsonl',
 *   preload: [
 *     { did: 'did:web:corp.example.com', publicKey: ..., name: 'Corporate Gateway' }
 *   ]
 * });
 * ```
 */
export declare function createEnterpriseTrustRegistry(opts: {
    /** Storage backend: 'memory', 'file', or 'http'. */
    readonly storage: 'memory' | 'file' | 'http';
    /** File path (required if storage='file'). */
    readonly path?: string;
    /** HTTP base URL (required if storage='http'). */
    readonly baseUrl?: string;
    /** Pre-populate with these entries. */
    readonly preload?: Array<{
        did: string;
        publicKey: Uint8Array;
        name: string;
        scopes?: string[];
        receiveScopes?: string[];
        x25519PublicKey?: Uint8Array;
        mlKemPublicKey?: Uint8Array;
        mlDsaPublicKey?: Uint8Array;
        xchange?: boolean;
        sdkVersion?: string;
        minEnvelopeVersion?: number;
        maxEnvelopeVersion?: number;
    }>;
}): Promise<TrustRegistry>;
