/**
 * Identity System - Authentication and Signature Verification
 *
 * The identity system manages entity authentication and verification, supporting
 * both soft (name-based) and cryptographic (key-based) identity models.
 *
 * Features:
 * - Identity mode configuration (soft, cryptographic, hybrid)
 * - Ed25519 signature generation and verification
 * - Signed request validation with time tolerance
 * - Actor context management
 */
import { Timestamp } from '@stoneforge/core';
/**
 * Identity mode determines the level of verification required
 */
export declare const IdentityMode: {
    /** Name-based identity without verification (default) */
    readonly SOFT: "soft";
    /** Key-based identity with signature verification */
    readonly CRYPTOGRAPHIC: "cryptographic";
    /** Mixed mode - accepts both verified and unverified actors */
    readonly HYBRID: "hybrid";
};
export type IdentityMode = (typeof IdentityMode)[keyof typeof IdentityMode];
/**
 * Base64-encoded Ed25519 signature (88 characters for 64 bytes)
 */
declare const SignatureBrand: unique symbol;
export type Signature = string & {
    readonly [SignatureBrand]: typeof SignatureBrand;
};
/**
 * Base64-encoded Ed25519 public key (44 characters for 32 bytes)
 */
declare const PublicKeyBrand: unique symbol;
export type PublicKey = string & {
    readonly [PublicKeyBrand]: typeof PublicKeyBrand;
};
/**
 * Signed request fields included in cryptographic requests
 */
export interface SignedRequestFields {
    /** Base64 Ed25519 signature */
    readonly signature: Signature;
    /** Timestamp when the request was signed (ISO 8601) */
    readonly signedAt: Timestamp;
    /** Entity name making the request */
    readonly actor: string;
}
/**
 * Input for signing a request
 */
export interface SigningInput {
    /** Entity name making the request */
    actor: string;
    /** Hash of the request body (SHA256, hex encoded) */
    requestHash: string;
}
/**
 * Signed data format: actor|signedAt|requestHash
 */
export interface SignedData {
    readonly actor: string;
    readonly signedAt: Timestamp;
    readonly requestHash: string;
}
/**
 * Result of signature verification
 */
export declare const VerificationStatus: {
    /** Signature is valid */
    readonly VALID: "valid";
    /** Signature is invalid or doesn't match */
    readonly INVALID: "invalid";
    /** Signature has expired (outside time tolerance) */
    readonly EXPIRED: "expired";
    /** Entity not found for verification */
    readonly ACTOR_NOT_FOUND: "actor_not_found";
    /** Entity has no public key */
    readonly NO_PUBLIC_KEY: "no_public_key";
    /** Signature was not provided */
    readonly NOT_SIGNED: "not_signed";
};
export type VerificationStatus = (typeof VerificationStatus)[keyof typeof VerificationStatus];
/**
 * Full verification result with details
 */
export interface VerificationResult {
    /** Overall verification status */
    readonly status: VerificationStatus;
    /** Whether the request should be allowed */
    readonly allowed: boolean;
    /** Actor name if verified */
    readonly actor?: string;
    /** Error message if verification failed */
    readonly error?: string;
    /** Additional details about the verification */
    readonly details?: {
        /** How old the signature is in milliseconds */
        signatureAgeMs?: number;
        /** Whether the entity was found */
        entityFound?: boolean;
        /** Whether the entity has a public key */
        hasPublicKey?: boolean;
    };
}
/**
 * Identity system configuration
 */
export interface IdentityConfig {
    /** Identity verification mode */
    mode: IdentityMode;
    /** Time tolerance for signature expiry in milliseconds (default: 5 minutes) */
    timeTolerance: number;
    /** Whether to allow unregistered actors in soft mode */
    allowUnregisteredActors: boolean;
}
/** Default time tolerance: 5 minutes in milliseconds */
export declare const DEFAULT_TIME_TOLERANCE: number;
/**
 * Default identity configuration
 */
export declare const DEFAULT_IDENTITY_CONFIG: IdentityConfig;
/**
 * Validates an identity mode value
 */
export declare function isValidIdentityMode(value: unknown): value is IdentityMode;
/**
 * Validates identity mode and throws if invalid
 */
export declare function validateIdentityMode(value: unknown): IdentityMode;
/**
 * Validates a base64-encoded Ed25519 public key format
 */
export declare function isValidPublicKey(value: unknown): value is PublicKey;
/**
 * Validates a public key and throws if invalid format
 */
export declare function validatePublicKey(value: unknown): PublicKey;
/**
 * Validates a base64-encoded Ed25519 signature format
 */
export declare function isValidSignature(value: unknown): value is Signature;
/**
 * Validates a signature and throws if invalid format
 */
export declare function validateSignature(value: unknown): Signature;
/**
 * Validates a request hash (SHA256 hex)
 */
export declare function isValidRequestHash(value: unknown): value is string;
/**
 * Validates a request hash and throws if invalid
 */
export declare function validateRequestHash(value: unknown): string;
/**
 * Validates time tolerance value
 */
export declare function isValidTimeTolerance(value: unknown): value is number;
/**
 * Validates time tolerance and throws if invalid
 */
export declare function validateTimeTolerance(value: unknown): number;
/**
 * Type guard for SignedRequestFields
 */
export declare function isSignedRequestFields(value: unknown): value is SignedRequestFields;
/**
 * Validates SignedRequestFields and throws detailed errors
 */
export declare function validateSignedRequestFields(value: unknown): SignedRequestFields;
/**
 * Type guard for VerificationResult
 */
export declare function isVerificationResult(value: unknown): value is VerificationResult;
/**
 * Type guard for IdentityConfig
 */
export declare function isIdentityConfig(value: unknown): value is IdentityConfig;
/**
 * Validates IdentityConfig and throws detailed errors
 */
export declare function validateIdentityConfig(value: unknown): IdentityConfig;
/**
 * Constructs the signed data string from components
 * Format: actor|signedAt|requestHash
 */
export declare function constructSignedData(data: SignedData): string;
/**
 * Parses a signed data string into components
 * Format: actor|signedAt|requestHash
 */
export declare function parseSignedData(signedDataString: string): SignedData;
/**
 * Checks if a signature timestamp is within the allowed time tolerance
 *
 * @param signedAt - The timestamp when the request was signed
 * @param tolerance - Time tolerance in milliseconds (default: 5 minutes)
 * @param now - Current timestamp for testing (defaults to now)
 * @returns Object with validity and age information
 */
export declare function checkTimeTolerance(signedAt: Timestamp, tolerance?: number, now?: Date): {
    valid: boolean;
    ageMs: number;
    expiredBy?: number;
};
/**
 * Checks time tolerance and throws if expired
 */
export declare function validateTimeTolerance2(signedAt: Timestamp, tolerance?: number, now?: Date): void;
/**
 * Creates a successful verification result
 */
export declare function verificationSuccess(actor: string, ageMs?: number): VerificationResult;
/**
 * Creates a failed verification result
 */
export declare function verificationFailure(status: VerificationStatus, error: string, details?: VerificationResult['details']): VerificationResult;
/**
 * Creates a "not signed" result (may be allowed in soft/hybrid mode)
 */
export declare function verificationNotSigned(allowed: boolean, actor?: string): VerificationResult;
/**
 * Verifies an Ed25519 signature using Bun's native crypto
 *
 * @param publicKey - Base64-encoded Ed25519 public key
 * @param signature - Base64-encoded Ed25519 signature
 * @param data - The data that was signed (as string or Uint8Array)
 * @returns true if signature is valid, false otherwise
 */
export declare function verifyEd25519Signature(publicKey: PublicKey, signature: Signature, data: string | Uint8Array): Promise<boolean>;
/**
 * Signs data using Ed25519 (for testing purposes)
 * In production, signing should be done by the entity externally
 *
 * @param privateKey - Base64-encoded Ed25519 private key in PKCS8 format
 * @param data - The data to sign
 * @returns Base64-encoded signature
 */
export declare function signEd25519(privateKey: string, data: string | Uint8Array): Promise<Signature>;
/**
 * Generates a new Ed25519 keypair (for testing purposes)
 *
 * @returns Object with base64-encoded public and private keys (PKCS8 format for private)
 */
export declare function generateEd25519Keypair(): Promise<{
    publicKey: PublicKey;
    privateKey: string;
}>;
/**
 * Entity lookup function type for verification
 */
export type EntityLookup = (actor: string) => Promise<{
    publicKey?: string;
} | null>;
/**
 * Full verification options
 */
export interface VerifySignatureOptions {
    /** The signed request fields */
    signedRequest: SignedRequestFields;
    /** The hash of the request body */
    requestHash: string;
    /** Function to look up entity by name */
    lookupEntity: EntityLookup;
    /** Identity configuration */
    config?: Partial<IdentityConfig>;
    /** Current time for testing */
    now?: Date;
}
/**
 * Performs full signature verification pipeline
 *
 * 1. Validates signature format
 * 2. Looks up entity's public key
 * 3. Constructs signed data
 * 4. Checks time tolerance
 * 5. Verifies signature cryptographically
 */
export declare function verifySignature(options: VerifySignatureOptions): Promise<VerificationResult>;
/**
 * Determines if a request should be allowed based on identity mode
 */
export declare function shouldAllowRequest(mode: IdentityMode, verificationResult: VerificationResult): boolean;
/**
 * Creates a SHA256 hash of the request body for signing
 */
export declare function hashRequestBody(body: string | object): Promise<string>;
/**
 * Creates a signed request from signing input
 */
export declare function createSignedRequest(input: SigningInput, privateKey: string, signedAt?: Timestamp): Promise<SignedRequestFields>;
/**
 * Merges partial config with defaults
 */
export declare function createIdentityConfig(partial?: Partial<IdentityConfig>): IdentityConfig;
/**
 * Sources from which actor identity can be determined
 */
export declare const ActorSource: {
    /** Explicitly provided in the operation */
    readonly EXPLICIT: "explicit";
    /** From CLI --actor flag */
    readonly CLI_FLAG: "cli_flag";
    /** From configuration file */
    readonly CONFIG: "config";
    /** From element's createdBy field (fallback) */
    readonly ELEMENT: "element";
    /** System-generated operations */
    readonly SYSTEM: "system";
};
export type ActorSource = (typeof ActorSource)[keyof typeof ActorSource];
/**
 * Actor context for tracking who is performing an operation
 */
export interface ActorContext {
    /** The actor's entity ID or name */
    readonly actor: string;
    /** Where the actor identity came from */
    readonly source: ActorSource;
    /** Whether the actor has been verified (always false in soft mode) */
    readonly verified: boolean;
    /** Optional entity ID if the actor was looked up and exists */
    readonly entityId?: string;
}
/**
 * Options for resolving actor context
 */
export interface ActorResolutionOptions {
    /** Explicitly provided actor (highest priority) */
    explicitActor?: string;
    /** Actor from CLI flag */
    cliActor?: string;
    /** Actor from configuration */
    configActor?: string;
    /** Fallback actor from element's createdBy (lowest priority) */
    elementCreatedBy?: string;
    /** Identity configuration */
    config?: Partial<IdentityConfig>;
    /** Function to look up entity by name */
    lookupEntity?: EntityLookup;
}
/**
 * Result of actor validation
 */
export interface ActorValidationResult {
    /** Whether the actor is valid */
    valid: boolean;
    /** The resolved actor context if valid */
    context?: ActorContext;
    /** Error message if invalid */
    error?: string;
    /** Whether the actor entity exists (only checked in soft mode with lookupEntity) */
    entityExists?: boolean;
}
/**
 * Resolves actor context from multiple sources
 *
 * Priority order (highest to lowest):
 * 1. Explicit actor (provided in operation)
 * 2. CLI actor (--actor flag)
 * 3. Config actor (default actor in config)
 * 4. Element's createdBy (fallback for updates/deletes)
 *
 * @param options - Resolution options with actor sources
 * @returns The resolved actor context
 * @throws ValidationError if no actor can be resolved
 */
export declare function resolveActor(options: ActorResolutionOptions): ActorContext;
/**
 * Validates an actor in soft identity mode
 *
 * In soft mode:
 * - Accepts any non-empty string as actor
 * - Optionally checks if entity exists (if lookupEntity provided and allowUnregisteredActors is false)
 * - Always returns verified: false
 *
 * @param actor - The actor name/ID to validate
 * @param options - Validation options
 * @returns Validation result with context if valid
 */
export declare function validateSoftActor(actor: string, options?: {
    lookupEntity?: EntityLookup;
    config?: Partial<IdentityConfig>;
}): Promise<ActorValidationResult>;
/**
 * Type guard for ActorContext
 */
export declare function isActorContext(value: unknown): value is ActorContext;
/**
 * Creates an actor context for system operations
 */
export declare function createSystemActorContext(): ActorContext;
/**
 * Creates an actor context from an explicit actor string
 */
export declare function createActorContext(actor: string, source?: ActorSource): ActorContext;
/**
 * Middleware context for request verification
 */
export interface MiddlewareContext {
    /** The actor making the request (if authenticated) */
    actor?: string;
    /** Whether the request was verified cryptographically */
    verified: boolean;
    /** The verification result (if verification was attempted) */
    verificationResult?: VerificationResult;
    /** The identity mode used */
    mode: IdentityMode;
}
/**
 * Request object that may contain signed fields
 */
export interface SignableRequest {
    /** Optional signed request fields for cryptographic verification */
    signedRequest?: SignedRequestFields;
    /** The request body (used to compute hash for verification) */
    body?: string | object;
}
/**
 * Middleware result
 */
export interface MiddlewareResult {
    /** Whether the request is allowed to proceed */
    allowed: boolean;
    /** The middleware context with authentication info */
    context: MiddlewareContext;
    /** Error message if not allowed */
    error?: string;
}
/**
 * Options for verification middleware
 */
export interface VerificationMiddlewareOptions {
    /** Identity configuration */
    config?: Partial<IdentityConfig>;
    /** Function to look up entity by actor name */
    lookupEntity: EntityLookup;
    /** Current time (for testing) */
    now?: Date;
}
/**
 * Creates a verification middleware function
 *
 * The middleware:
 * 1. Checks identity mode from config
 * 2. In soft mode: allows all requests, extracts actor if provided
 * 3. In cryptographic mode: requires valid signature
 * 4. In hybrid mode: allows unsigned or validly signed requests
 *
 * @param options - Middleware options
 * @returns A middleware function that verifies requests
 *
 * @example
 * ```typescript
 * const middleware = createVerificationMiddleware({
 *   lookupEntity: (actor) => api.lookupEntityByName(actor),
 *   config: { mode: IdentityMode.CRYPTOGRAPHIC }
 * });
 *
 * const result = await middleware(request);
 * if (!result.allowed) {
 *   throw new Error(result.error);
 * }
 * // Use result.context.actor for the verified actor
 * ```
 */
export declare function createVerificationMiddleware(options: VerificationMiddlewareOptions): (request: SignableRequest) => Promise<MiddlewareResult>;
/**
 * Creates middleware context for an unsigned request in soft mode
 */
export declare function createSoftModeContext(actor?: string): MiddlewareContext;
/**
 * Creates middleware context for a verified request
 */
export declare function createVerifiedContext(actor: string, verificationResult: VerificationResult): MiddlewareContext;
export {};
//# sourceMappingURL=identity.d.ts.map