import { User } from './server/entities/users.js';
import { Role } from './server/entities/roles.js';
import { Invitation, InvitationWithDetails, InvitationStatus } from './server/entities/invitations.js';
import { SessionPayload } from './lib/types/api.js';
import { Context, Next } from 'hono';
import 'drizzle-orm/pg-core';

/**
 * @spfn/auth - RBAC Type Definitions
 *
 * Type definitions for role and permission configuration
 */
interface RoleConfig {
    name: string;
    displayName: string;
    description?: string;
    priority?: number;
    isSystem?: boolean;
    isBuiltin?: boolean;
}
interface PermissionConfig {
    name: string;
    displayName: string;
    description?: string;
    category?: string;
    isSystem?: boolean;
    isBuiltin?: boolean;
}
interface AuthInitOptions {
    /**
     * Additional roles to create
     * Built-in roles (user, admin, superadmin) are automatically included
     */
    roles?: RoleConfig[];
    /**
     * Additional permissions to create
     * Built-in permissions are automatically included
     */
    permissions?: PermissionConfig[];
    /**
     * Role-Permission mappings
     * Built-in mappings are automatically included
     * You can extend built-in roles or define mappings for custom roles
     *
     * @example
     * ```typescript
     * {
     *   // Extend built-in admin role
     *   admin: ['project:create', 'project:delete'],
     *
     *   // Define custom role permissions
     *   'project-manager': ['project:create', 'task:assign'],
     * }
     * ```
     */
    rolePermissions?: Record<string, string[]>;
    /**
     * Default role name for new users
     * Must be a valid role name that exists after initialization
     * @default 'user'
     */
    defaultRole?: string;
    /**
     * Default session TTL (Time To Live)
     *
     * Supports:
     * - Number: seconds (e.g., 2592000)
     * - String: duration format ('30d', '12h', '45m', '3600s')
     *
     * Can be overridden at runtime with `remember` parameter.
     *
     * @default '7d' (7 days)
     *
     * @example
     * ```typescript
     * {
     *   sessionTtl: '30d',  // 30 days
     * }
     * ```
     */
    sessionTtl?: string | number;
}

/**
 * @spfn/auth - Built-in Roles and Permissions
 *
 * Core roles and permissions required by the auth package
 * These cannot be deleted and are automatically created on initialization
 */

/**
 * Built-in roles (required by package)
 * These roles are always created and cannot be deleted
 */
declare const BUILTIN_ROLES: Record<string, RoleConfig>;
/**
 * Built-in permissions (required by package)
 * These permissions are always created and cannot be deleted
 */
declare const BUILTIN_PERMISSIONS: Record<string, PermissionConfig>;
/**
 * Built-in role-permission mappings
 * Defines default permissions for each built-in role
 */
declare const BUILTIN_ROLE_PERMISSIONS: Record<string, string[]>;
type BuiltinRoleName = keyof typeof BUILTIN_ROLE_PERMISSIONS;
type BuiltinPermissionName = typeof BUILTIN_PERMISSIONS[keyof typeof BUILTIN_PERMISSIONS]['name'];

/**
 * @spfn/auth - Auth Service
 *
 * Core authentication logic: registration, login, logout, password management
 */
interface CheckAccountExistsParams {
    email?: string;
    phone?: string;
}
interface CheckAccountExistsResult {
    exists: boolean;
    identifier: string;
    identifierType: 'email' | 'phone';
}
interface RegisterParams {
    email?: string;
    phone?: string;
    verificationToken: string;
    password: string;
    publicKey: string;
    keyId: string;
    fingerprint: string;
    algorithm?: 'ES256' | 'RS256';
}
interface RegisterResult {
    userId: string;
    email?: string;
    phone?: string;
}
interface LoginParams {
    email?: string;
    phone?: string;
    password: string;
    publicKey: string;
    keyId: string;
    fingerprint: string;
    oldKeyId?: string;
    algorithm?: 'ES256' | 'RS256';
}
interface LoginResult {
    userId: string;
    email?: string;
    phone?: string;
    passwordChangeRequired: boolean;
}
interface LogoutParams {
    userId: number;
    keyId: string;
}
interface ChangePasswordParams {
    userId: number;
    currentPassword: string;
    newPassword: string;
    passwordHash?: string;
}
/**
 * Check if an account exists by email or phone
 */
declare function checkAccountExistsService(params: CheckAccountExistsParams): Promise<CheckAccountExistsResult>;
/**
 * Register a new user account
 */
declare function registerService(params: RegisterParams): Promise<RegisterResult>;
/**
 * Authenticate user and create session
 */
declare function loginService(params: LoginParams): Promise<LoginResult>;
/**
 * Logout user (revoke current key)
 */
declare function logoutService(params: LogoutParams): Promise<void>;
/**
 * Change user password
 */
declare function changePasswordService(params: ChangePasswordParams): Promise<void>;

/**
 * @spfn/auth - Verification Service
 *
 * Handles OTP code generation, validation, and delivery
 */
interface SendVerificationCodeParams {
    target: string;
    targetType: 'email' | 'phone';
    purpose: 'registration' | 'login' | 'password_reset';
}
interface SendVerificationCodeResult {
    success: boolean;
    expiresAt: string;
}
interface VerifyCodeParams {
    target: string;
    targetType: 'email' | 'phone';
    code: string;
    purpose: 'registration' | 'login' | 'password_reset';
}
interface VerifyCodeResult {
    valid: boolean;
    verificationToken: string;
}
/**
 * Send verification code via email or SMS
 */
declare function sendVerificationCodeService(params: SendVerificationCodeParams): Promise<SendVerificationCodeResult>;
/**
 * Verify OTP code and return verification token
 */
declare function verifyCodeService(params: VerifyCodeParams): Promise<VerifyCodeResult>;

/**
 * @spfn/auth - Key Service
 *
 * Handles public key registration, rotation, and revocation
 */
interface RegisterPublicKeyParams {
    userId: number;
    keyId: string;
    publicKey: string;
    fingerprint: string;
    algorithm?: 'ES256' | 'RS256';
}
interface RotateKeyParams {
    userId: number;
    oldKeyId: string;
    newKeyId: string;
    newPublicKey: string;
    fingerprint: string;
    algorithm?: 'ES256' | 'RS256';
}
interface RotateKeyResult {
    success: boolean;
    keyId: string;
}
interface RevokeKeyParams {
    userId: number;
    keyId: string;
    reason: string;
}
/**
 * Register a new public key for a user
 */
declare function registerPublicKeyService(params: RegisterPublicKeyParams): Promise<void>;
/**
 * Rotate user's public key (revoke old, register new)
 */
declare function rotateKeyService(params: RotateKeyParams): Promise<RotateKeyResult>;
/**
 * Revoke a user's public key
 */
declare function revokeKeyService(params: RevokeKeyParams): Promise<void>;

/**
 * @spfn/auth - User Service
 *
 * Handles user CRUD operations
 */

/**
 * Get user by ID
 */
declare function getUserByIdService(userId: number): Promise<User | null>;
/**
 * Get user by email
 */
declare function getUserByEmailService(email: string): Promise<User | null>;
/**
 * Get user by phone
 */
declare function getUserByPhoneService(phone: string): Promise<User | null>;
/**
 * Update user's last login timestamp
 */
declare function updateLastLoginService(userId: number): Promise<void>;
/**
 * Update user data
 */
declare function updateUserService(userId: number, updates: Partial<Omit<User, 'id' | 'createdAt'>>): Promise<void>;

/**
 * @spfn/auth - Me Service
 *
 * Service for retrieving current user information
 */
interface GetMeResult {
    userId: string;
    email?: string;
    phone?: string;
    role: {
        id: number;
        name: string;
        displayName: string;
        priority: number;
    };
    permissions: Array<{
        id: number;
        name: string;
        displayName: string;
        category?: string;
    }>;
}
/**
 * Get current user information including role and permissions
 *
 * @param userId - User ID (string, number, or bigint)
 * @returns User info with role and permissions
 *
 * @example
 * ```typescript
 * const userInfo = await getMeService('123');
 * console.log(userInfo.role.name); // 'admin'
 * console.log(userInfo.permissions.length); // 15
 * ```
 */
declare function getMeService(userId: string | number | bigint): Promise<GetMeResult>;

/**
 * @spfn/auth - RBAC Initialization Service
 *
 * Initialize roles, permissions, and their mappings
 */

/**
 * Initialize auth package with RBAC system
 *
 * Creates built-in roles, permissions, and custom configurations
 *
 * @param options - Initialization options
 *
 * @example
 * ```typescript
 * // Minimal - only built-in roles (user, admin, superadmin)
 * await initializeAuth();
 *
 * // Custom roles and permissions
 * await initializeAuth({
 *   roles: [
 *     { name: 'project-manager', displayName: 'Project Manager', priority: 50 },
 *     { name: 'developer', displayName: 'Developer', priority: 30 },
 *   ],
 *   permissions: [
 *     { name: 'project:create', displayName: 'Create Project', category: 'project' },
 *     { name: 'task:assign', displayName: 'Assign Task', category: 'task' },
 *   ],
 *   rolePermissions: {
 *     'project-manager': ['project:create', 'task:assign'],
 *     'developer': ['task:complete'],
 *   },
 * });
 * ```
 */
declare function initializeAuth(options?: AuthInitOptions): Promise<void>;

/**
 * @spfn/auth - Permission Service
 *
 * Permission checking and validation logic
 */
/**
 * Get all permissions for a user
 *
 * Combines role-based permissions with user-specific overrides
 * Handles expiration of temporary permissions
 *
 * @param userId - User ID (string, number, or bigint)
 * @returns Array of permission names
 *
 * @example
 * ```typescript
 * const perms = await getUserPermissions('123');
 * // ['auth:self:manage', 'user:read', 'post:create']
 * ```
 */
declare function getUserPermissions(userId: string | number | bigint): Promise<string[]>;
/**
 * Check if user has a specific permission
 *
 * @param userId - User ID
 * @param permissionName - Permission name (e.g., 'user:delete')
 * @returns true if user has permission
 *
 * @example
 * ```typescript
 * if (await hasPermission('123', 'user:delete')) {
 *   // User can delete users
 * }
 * ```
 */
declare function hasPermission(userId: string | number | bigint, permissionName: string): Promise<boolean>;
/**
 * Check if user has any of the specified permissions
 *
 * @param userId - User ID
 * @param permissionNames - Array of permission names
 * @returns true if user has at least one permission
 *
 * @example
 * ```typescript
 * if (await hasAnyPermission('123', ['post:read', 'admin:access'])) {
 *   // User can access content
 * }
 * ```
 */
declare function hasAnyPermission(userId: string | number | bigint, permissionNames: string[]): Promise<boolean>;
/**
 * Check if user has all of the specified permissions
 *
 * @param userId - User ID
 * @param permissionNames - Array of permission names
 * @returns true if user has all permissions
 *
 * @example
 * ```typescript
 * if (await hasAllPermissions('123', ['post:write', 'post:publish'])) {
 *   // User can write AND publish
 * }
 * ```
 */
declare function hasAllPermissions(userId: string | number | bigint, permissionNames: string[]): Promise<boolean>;
/**
 * Check if user has a specific role
 *
 * @param userId - User ID
 * @param roleName - Role name (e.g., 'admin', 'superadmin')
 * @returns true if user has role
 *
 * @example
 * ```typescript
 * if (await hasRole('123', 'admin')) {
 *   // User is admin
 * }
 * ```
 */
declare function hasRole(userId: string | number | bigint, roleName: string): Promise<boolean>;
/**
 * Check if user has any of the specified roles
 *
 * @param userId - User ID
 * @param roleNames - Array of role names
 * @returns true if user has at least one role
 */
declare function hasAnyRole(userId: string | number | bigint, roleNames: string[]): Promise<boolean>;

/**
 * @spfn/auth - Role Service
 *
 * Role management functions for runtime role creation and modification
 */

/**
 * Create a new custom role
 *
 * @param data - Role configuration
 * @returns Created role
 * @throws Error if role name already exists
 *
 * @example
 * ```typescript
 * const role = await createRole({
 *   name: 'content-creator',
 *   displayName: 'Content Creator',
 *   description: 'Can create and publish content',
 *   priority: 20,
 *   permissionIds: [1n, 2n, 3n],
 * });
 * ```
 */
declare function createRole(data: {
    name: string;
    displayName: string;
    description?: string;
    priority?: number;
    permissionIds?: number[];
}): Promise<Role>;
/**
 * Update an existing role
 *
 * @param roleId - Role ID
 * @param data - Update data
 * @returns Updated role
 * @throws Error if role is built-in (cannot modify)
 *
 * @example
 * ```typescript
 * await updateRole(1n, {
 *   displayName: 'Senior Content Creator',
 *   priority: 25,
 * });
 * ```
 */
declare function updateRole(roleId: number, data: {
    displayName?: string;
    description?: string;
    priority?: number;
    isActive?: boolean;
}): Promise<Role>;
/**
 * Delete a role
 *
 * @param roleId - Role ID
 * @throws Error if role is built-in or system role
 *
 * @example
 * ```typescript
 * await deleteRole(5n);  // Delete custom role
 * ```
 */
declare function deleteRole(roleId: number): Promise<void>;
/**
 * Add permission to role
 *
 * @param roleId - Role ID
 * @param permissionId - Permission ID
 *
 * @example
 * ```typescript
 * await addPermissionToRole(1n, 5n);
 * ```
 */
declare function addPermissionToRole(roleId: number, permissionId: number): Promise<void>;
/**
 * Remove permission from role
 *
 * @param roleId - Role ID
 * @param permissionId - Permission ID
 *
 * @example
 * ```typescript
 * await removePermissionFromRole(1n, 5n);
 * ```
 */
declare function removePermissionFromRole(roleId: number, permissionId: number): Promise<void>;
/**
 * Set permissions for a role (replaces all existing permissions)
 *
 * @param roleId - Role ID
 * @param permissionIds - Array of permission IDs
 *
 * @example
 * ```typescript
 * await setRolePermissions(1n, [1n, 2n, 3n]);
 * ```
 */
declare function setRolePermissions(roleId: number, permissionIds: number[]): Promise<void>;
/**
 * Get all roles
 *
 * @param includeInactive - Include inactive roles
 * @returns Array of roles
 *
 * @example
 * ```typescript
 * const roles = await getAllRoles();
 * ```
 */
declare function getAllRoles(includeInactive?: boolean): Promise<Role[]>;
/**
 * Get role by name
 *
 * @param name - Role name
 * @returns Role or null
 *
 * @example
 * ```typescript
 * const role = await getRoleByName('admin');
 * ```
 */
declare function getRoleByName(name: string): Promise<Role | null>;
/**
 * Get role permissions
 *
 * @param roleId - Role ID
 * @returns Array of permission names
 *
 * @example
 * ```typescript
 * const perms = await getRolePermissions(1n);
 * // ['user:read', 'user:write']
 * ```
 */
declare function getRolePermissions(roleId: number): Promise<string[]>;

/**
 * @spfn/auth - Invitation Service
 *
 * User invitation management for invite-only registration
 */

/**
 * Create a new invitation
 *
 * @param params - Invitation parameters
 * @returns Created invitation
 * @throws Error if validation fails
 *
 * @example
 * ```typescript
 * const invitation = await createInvitation({
 *   email: 'newuser@example.com',
 *   roleId: 2n,
 *   invitedBy: 1n,
 *   expiresInDays: 7,
 *   metadata: { message: 'Welcome!' }
 * });
 * ```
 */
declare function createInvitation(params: {
    email: string;
    roleId: number;
    invitedBy: number;
    expiresInDays?: number;
    metadata?: Record<string, any>;
}): Promise<Invitation>;
/**
 * Get invitation by token
 *
 * @param token - Invitation token (UUID)
 * @returns Invitation or null if not found
 */
declare function getInvitationByToken(token: string): Promise<Invitation | null>;
/**
 * Get invitation with role and inviter details
 *
 * @param token - Invitation token
 * @returns Invitation with joined data or null
 */
declare function getInvitationWithDetails(token: string): Promise<InvitationWithDetails | null>;
/**
 * Validate invitation
 *
 * Checks if invitation is valid for acceptance
 *
 * @param token - Invitation token
 * @returns Validation result
 */
declare function validateInvitation(token: string): Promise<{
    valid: boolean;
    invitation?: Invitation;
    error?: string;
}>;
/**
 * Accept invitation and create user account
 *
 * @param params - Acceptance parameters
 * @returns Created user info
 * @throws Error if invitation is invalid or user creation fails
 *
 * @example
 * ```typescript
 * const user = await acceptInvitation({
 *   token: 'uuid-v4',
 *   password: 'SecurePass123!',
 *   publicKey: 'base64-der...',
 *   keyId: 'uuid-v4',
 *   fingerprint: 'sha256-hex',
 *   algorithm: 'ES256'
 * });
 * ```
 */
declare function acceptInvitation(params: {
    token: string;
    password: string;
    publicKey: string;
    keyId: string;
    fingerprint: string;
    algorithm: 'ES256' | 'RS256';
}): Promise<{
    userId: number;
    email: string;
    role: string;
}>;
/**
 * List invitations with filtering and pagination
 *
 * @param params - Query parameters
 * @returns Paginated invitations
 *
 * @example
 * ```typescript
 * const result = await listInvitations({
 *   status: 'pending',
 *   invitedBy: 1n,
 *   page: 1,
 *   limit: 20
 * });
 * ```
 */
declare function listInvitations(params: {
    status?: InvitationStatus;
    invitedBy?: number;
    page?: number;
    limit?: number;
}): Promise<{
    invitations: InvitationWithDetails[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
}>;
/**
 * Cancel invitation
 *
 * Only pending invitations can be cancelled
 *
 * @param id - Invitation ID
 * @param cancelledBy - User ID who cancelled
 * @param reason - Optional cancellation reason
 * @throws Error if invitation cannot be cancelled
 */
declare function cancelInvitation(id: number, cancelledBy: number, reason?: string): Promise<void>;
/**
 * Delete invitation
 *
 * Permanently removes invitation record
 * Typically only for superadmin cleanup
 *
 * @param id - Invitation ID
 */
declare function deleteInvitation(id: number): Promise<void>;
/**
 * Expire old invitations (cron job)
 *
 * Updates status of expired pending invitations
 *
 * @returns Number of invitations expired
 */
declare function expireOldInvitations(): Promise<number>;
/**
 * Resend invitation email
 *
 * Extends expiration and triggers email resend
 *
 * @param id - Invitation ID
 * @param expiresInDays - New expiration period (default: 7)
 * @returns Updated invitation
 * @throws Error if invitation cannot be resent
 */
declare function resendInvitation(id: number, expiresInDays?: number): Promise<Invitation>;

/**
 * @spfn/auth - Password Helpers
 *
 * Password hashing and verification using bcrypt
 *
 * Security:
 * - Adaptive hashing (configurable rounds)
 * - Automatic salt generation (per-password)
 * - Constant-time comparison (timing attack protection)
 * - Rainbow table protection
 */
/**
 * Hash a plain text password using bcrypt
 *
 * Algorithm:
 * 1. Generate random salt (128-bit)
 * 2. Apply bcrypt key derivation (2^rounds iterations)
 * 3. Return $2b$rounds$[salt][hash] (60 chars)
 *
 * @param password - Plain text password to hash
 * @returns Bcrypt hash string (includes salt)
 * @throws Error if password is empty or invalid
 *
 * @example
 * ```typescript
 * const hash = await hashPassword('mySecurePassword123');
 * // Returns: "$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"
 * ```
 */
declare function hashPassword(password: string): Promise<string>;
/**
 * Verify a password against a bcrypt hash
 *
 * Uses constant-time comparison to prevent timing attacks
 * Automatically extracts salt from hash for verification
 *
 * @param password - Plain text password to verify
 * @param hash - Bcrypt hash string (from hashPassword)
 * @returns True if password matches hash
 * @throws Error if inputs are invalid
 *
 * @example
 * ```typescript
 * const isValid = await verifyPassword(
 *     'mySecurePassword123',
 *     '$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy'
 * );
 * // Returns: true
 * ```
 */
declare function verifyPassword(password: string, hash: string): Promise<boolean>;
/**
 * Validate password strength
 *
 * Requirements:
 * - Minimum 8 characters
 * - At least one uppercase letter
 * - At least one lowercase letter
 * - At least one number
 * - At least one special character
 *
 * @param password - Password to validate
 * @returns Validation result with error messages
 *
 * @example
 * ```typescript
 * const result = validatePasswordStrength('weak');
 * // Returns: { valid: false, errors: ['Too short', 'Missing uppercase', ...] }
 *
 * const result = validatePasswordStrength('SecurePass123!');
 * // Returns: { valid: true, errors: [] }
 * ```
 */
declare function validatePasswordStrength(password: string): {
    valid: boolean;
    errors: string[];
};

/**
 * @spfn/auth - JWT Helpers
 *
 * JWT token generation and verification
 * Supports both server-signed (legacy) and client-signed (asymmetric) tokens
 *
 * Architecture:
 * - Legacy: Server signs/verifies with SPFN_AUTH_JWT_SECRET (symmetric HMAC)
 * - New: Client signs with privateKey, server verifies with publicKey (asymmetric)
 */

interface TokenPayload extends SessionPayload {
    exp?: number;
    iat?: number;
    iss?: string;
    keyId?: string;
    timestamp?: number;
    [key: string]: any;
}
/**
 * Generate a JWT token (legacy server-signed)
 *
 * @deprecated Use client-side signing with private keys instead
 * This method uses symmetric HMAC which requires sharing the secret
 *
 * @param payload - Token payload
 * @returns JWT token string
 */
declare function generateToken(payload: SessionPayload): string;
/**
 * Verify and decode a JWT token (legacy server-signed)
 *
 * @deprecated Use verifyClientToken for client-signed tokens
 * This method uses symmetric HMAC verification
 *
 * @param token - JWT token to verify
 * @returns Decoded payload
 * @throws Error if verification fails
 */
declare function verifyToken(token: string): TokenPayload;
/**
 * Verify client-signed JWT token with public key (DER format)
 *
 * Flow:
 * 1. Decode Base64 DER to Buffer
 * 2. Create KeyObject from DER
 * 3. Verify JWT signature with public key
 * 4. Validate issuer claim
 *
 * @param token - JWT token signed by client's private key
 * @param publicKeyB64 - Base64 encoded DER public key (SPKI format)
 * @param algorithm - Algorithm used for signing (ES256 or RS256)
 * @returns Decoded token payload
 * @throws Error if verification fails
 *
 * @example
 * ```typescript
 * const payload = verifyClientToken(
 *     token,
 *     'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...',
 *     'ES256'
 * );
 * ```
 */
declare function verifyClientToken(token: string, publicKeyB64: string, algorithm: 'ES256' | 'RS256'): TokenPayload;
/**
 * Decode a JWT token without verification (for debugging)
 *
 * WARNING: Does not verify signature! Only use for debugging/logging.
 * Never trust decoded data without verification.
 *
 * @param token - JWT token to decode
 * @returns Decoded payload or null if invalid
 */
declare function decodeToken(token: string): TokenPayload | null;
/**
 * Verify public key fingerprint matches
 *
 * Used during registration/login to ensure the public key wasn't tampered with
 * during transmission.
 *
 * Security:
 * - Client sends: publicKey + fingerprint
 * - Server calculates: SHA-256(publicKey)
 * - Server compares: calculated === received
 *
 * @param publicKeyB64 - Base64 encoded DER public key
 * @param expectedFingerprint - SHA-256 hex fingerprint (64 chars)
 * @returns True if fingerprint matches
 *
 * @example
 * ```typescript
 * const isValid = verifyKeyFingerprint(
 *     publicKey,
 *     'a1b2c3d4e5f6...' // 64-char hex string
 * );
 * if (!isValid) {
 *     throw new Error('Public key fingerprint mismatch');
 * }
 * ```
 */
declare function verifyKeyFingerprint(publicKeyB64: string, expectedFingerprint: string): boolean;

/**
 * @spfn/auth - Verification Code Helpers
 *
 * Helper functions for email/phone verification codes
 */
/**
 * Verification token payload
 */
interface VerificationTokenPayload {
    target: string;
    targetType: 'email' | 'phone';
    purpose: 'registration' | 'login' | 'password_reset';
    codeId: number;
}
/**
 * Generate a random 6-digit verification code
 *
 * @returns 6-digit code as string
 */
declare function generateVerificationCode(): string;
/**
 * Store verification code in database
 *
 * @param target - Email or phone number
 * @param targetType - Type of target (email or phone)
 * @param code - 6-digit verification code
 * @param purpose - Purpose of verification
 * @returns Created verification code record
 */
declare function storeVerificationCode(target: string, targetType: 'email' | 'phone', code: string, purpose: 'registration' | 'login' | 'password_reset'): Promise<{
    id: number;
    createdAt: Date;
    updatedAt: Date;
    expiresAt: Date;
    target: string;
    targetType: "email" | "phone";
    code: string;
    purpose: "registration" | "login" | "password_reset" | "email_change" | "phone_change";
    usedAt: Date | null;
    attempts: string;
}>;
/**
 * Validate verification code
 *
 * @param target - Email or phone number
 * @param targetType - Type of target
 * @param code - 6-digit code to validate
 * @param purpose - Purpose of verification
 * @returns Validation result with code ID if valid
 */
declare function validateVerificationCode(target: string, targetType: 'email' | 'phone', code: string, purpose: 'registration' | 'login' | 'password_reset'): Promise<{
    valid: boolean;
    codeId?: number;
    error?: string;
}>;
/**
 * Mark verification code as used
 *
 * @param codeId - Verification code ID
 */
declare function markCodeAsUsed(codeId: number): Promise<void>;
/**
 * Create verification token (JWT)
 *
 * @param payload - Token payload
 * @returns Signed JWT token
 */
declare function createVerificationToken(payload: VerificationTokenPayload): string;
/**
 * Validate verification token (JWT)
 *
 * @param token - JWT token to validate
 * @returns Decoded payload if valid, null otherwise
 */
declare function validateVerificationToken(token: string): VerificationTokenPayload | null;
/**
 * Send verification code via email
 *
 * @param email - Email address
 * @param code - 6-digit verification code
 * @param purpose - Purpose of verification
 */
declare function sendVerificationEmail(email: string, code: string, purpose: string): Promise<void>;
/**
 * Send verification code via SMS
 *
 * @param phone - Phone number in E.164 format
 * @param code - 6-digit verification code
 * @param purpose - Purpose of verification
 */
declare function sendVerificationSMS(phone: string, code: string, purpose: string): Promise<void>;

/**
 * @spfn/auth - Authentication Middleware
 *
 * Verify client-signed JWT token with public key
 *
 * Flow:
 * 1. Extract Authorization header
 * 2. Decode JWT to extract keyId
 * 3. Fetch public key from database
 * 4. Check key expiration
 * 5. Verify JWT signature with public key
 * 6. Validate user status
 * 7. Update last used timestamp
 * 8. Attach user to context
 *
 * Security Checks:
 * - Token signature verification
 * - Key expiration check
 * - User status check (active/inactive/suspended)
 * - Key revocation check (isActive flag)
 */

interface AuthContext {
    user: User;
    userId: string;
    keyId: string;
}
declare module 'hono' {
    interface ContextVariableMap {
        auth: AuthContext;
    }
}
/**
 * Authentication middleware
 *
 * Verifies client-signed JWT token using stored public key
 * Must be applied to routes that require authentication
 *
 * @example
 * ```typescript
 * // In route file
 * app.bind(logoutContract, [authenticate], async (c) => {
 *     const auth = c.raw.get('auth');  // Get auth context
 *     const { user, userId, keyId } = auth;
 *     // Or access directly: c.raw.get('auth').user
 * });
 * ```
 */
declare function authenticate(c: Context, next: Next): Promise<Response | void>;

/**
 * Auth Context Helpers
 *
 * Helper functions to access authenticated user data from route context
 */

/**
 * Get auth context from route context
 *
 * Accepts both raw Hono Context and RouteContext with raw property
 *
 * @example
 * ```typescript
 * // With RouteContext (RPC routes)
 * app.bind(logoutContract, [authenticate], async (c) => {
 *     const { user, userId, keyId } = getAuth(c);
 *     // Use authenticated data...
 * });
 *
 * // With raw Context (middleware)
 * const auth = getAuth(c);
 * ```
 */
declare function getAuth(c: Context | {
    raw: Context;
}): AuthContext;
/**
 * Get authenticated user from route context
 *
 * @example
 * ```typescript
 * app.bind(profileContract, [authenticate], async (c) => {
 *     const user = getUser(c);
 *     return c.success({ email: user.email });
 * });
 * ```
 */
declare function getUser(c: Context | {
    raw: Context;
}): {
    id: number;
    createdAt: Date;
    updatedAt: Date;
    email: string | null;
    phone: string | null;
    passwordHash: string | null;
    passwordChangeRequired: boolean;
    roleId: number;
    status: "active" | "inactive" | "suspended";
    emailVerifiedAt: Date | null;
    phoneVerifiedAt: Date | null;
    lastLoginAt: Date | null;
};
/**
 * Get authenticated user ID from route context
 *
 * @example
 * ```typescript
 * app.bind(postsContract, [authenticate], async (c) => {
 *     const userId = getUserId(c);
 *     const posts = await findPosts({ authorId: userId });
 * });
 * ```
 */
declare function getUserId(c: Context | {
    raw: Context;
}): string;
/**
 * Get current key ID from route context
 *
 * @example
 * ```typescript
 * app.bind(rotateKeyContract, [authenticate], async (c) => {
 *     const oldKeyId = getKeyId(c);
 *     // Revoke old key...
 * });
 * ```
 */
declare function getKeyId(c: Context | {
    raw: Context;
}): string;

/**
 * @spfn/auth - Permission Middleware
 *
 * Middleware functions for permission-based access control
 */

/**
 * Require user to have all specified permissions
 *
 * Must be used after authenticate middleware
 *
 * @param permissionNames - Permission names (e.g., 'user:delete', 'post:publish')
 * @returns Middleware function
 *
 * @example
 * ```typescript
 * app.bind(
 *   deleteUserContract,
 *   [authenticate, requirePermissions('user:delete')],
 *   async (c) => {
 *     // Only users with user:delete permission
 *   }
 * );
 *
 * // Multiple permissions (all required)
 * app.bind(
 *   publishPostContract,
 *   [authenticate, requirePermissions('post:write', 'post:publish')],
 *   async (c) => {
 *     // Needs both permissions
 *   }
 * );
 * ```
 */
declare function requirePermissions(...permissionNames: string[]): (c: Context, next: Next) => Promise<void>;
/**
 * Require user to have at least one of the specified permissions
 *
 * Must be used after authenticate middleware
 *
 * @param permissionNames - Permission names
 * @returns Middleware function
 *
 * @example
 * ```typescript
 * app.bind(
 *   viewContentContract,
 *   [authenticate, requireAnyPermission('content:read', 'admin:access')],
 *   async (c) => {
 *     // User has either content:read OR admin:access
 *   }
 * );
 * ```
 */
declare function requireAnyPermission(...permissionNames: string[]): (c: Context, next: Next) => Promise<void>;

/**
 * @spfn/auth - Role Middleware
 *
 * Middleware functions for role-based access control
 */

/**
 * Require user to have one of the specified roles
 *
 * Must be used after authenticate middleware
 *
 * @param roleNames - Role names (e.g., 'admin', 'superadmin')
 * @returns Middleware function
 *
 * @example
 * ```typescript
 * app.bind(
 *   adminDashboardContract,
 *   [authenticate, requireRole('admin', 'superadmin')],
 *   async (c) => {
 *     // Only admin or superadmin
 *   }
 * );
 *
 * // Single role
 * app.bind(
 *   systemConfigContract,
 *   [authenticate, requireRole('superadmin')],
 *   async (c) => {
 *     // Only superadmin
 *   }
 * );
 * ```
 */
declare function requireRole(...roleNames: string[]): (c: Context, next: Next) => Promise<void>;

/**
 * @spfn/auth - Setup Functions
 *
 * Initial setup and admin account creation
 */
/**
 * Ensure admin accounts exist from environment variables
 *
 * Supports multiple admin account creation via three formats:
 * 1. JSON format (SPFN_AUTH_ADMIN_ACCOUNTS)
 * 2. Comma-separated format (SPFN_AUTH_ADMIN_EMAILS + SPFN_AUTH_ADMIN_PASSWORDS + SPFN_AUTH_ADMIN_ROLES)
 * 3. Single account format (SPFN_AUTH_ADMIN_EMAIL + SPFN_AUTH_ADMIN_PASSWORD) - legacy
 *
 * Default behavior for created accounts:
 * - emailVerifiedAt: current timestamp (auto-verified)
 * - passwordChangeRequired: true (must change on first login)
 * - status: 'active'
 *
 * @example
 * ```typescript
 * // In your server startup code:
 * import { ensureAdminExists } from '@spfn/auth/server';
 *
 * await ensureAdminExists();
 * ```
 */
declare function ensureAdminExists(): Promise<void>;

export { type AuthContext, type AuthInitOptions, BUILTIN_PERMISSIONS, BUILTIN_ROLES, BUILTIN_ROLE_PERMISSIONS, type BuiltinPermissionName, type BuiltinRoleName, type ChangePasswordParams, type CheckAccountExistsParams, type CheckAccountExistsResult, type GetMeResult, type LoginParams, type LoginResult, type LogoutParams, type PermissionConfig, type RegisterParams, type RegisterPublicKeyParams, type RegisterResult, type RevokeKeyParams, type RoleConfig, type RotateKeyParams, type RotateKeyResult, type SendVerificationCodeParams, type SendVerificationCodeResult, type TokenPayload, type VerificationTokenPayload, type VerifyCodeParams, type VerifyCodeResult, acceptInvitation, addPermissionToRole, authenticate, cancelInvitation, changePasswordService, checkAccountExistsService, createInvitation, createRole, createVerificationToken, decodeToken, deleteInvitation, deleteRole, ensureAdminExists, expireOldInvitations, generateToken, generateVerificationCode, getAllRoles, getAuth, getInvitationByToken, getInvitationWithDetails, getKeyId, getMeService, getRoleByName, getRolePermissions, getUser, getUserByEmailService, getUserByIdService, getUserByPhoneService, getUserId, getUserPermissions, hasAllPermissions, hasAnyPermission, hasAnyRole, hasPermission, hasRole, hashPassword, initializeAuth, listInvitations, loginService, logoutService, markCodeAsUsed, registerPublicKeyService, registerService, removePermissionFromRole, requireAnyPermission, requirePermissions, requireRole, resendInvitation, revokeKeyService, rotateKeyService, sendVerificationCodeService, sendVerificationEmail, sendVerificationSMS, setRolePermissions, storeVerificationCode, updateLastLoginService, updateRole, updateUserService, validateInvitation, validatePasswordStrength, validateVerificationCode, validateVerificationToken, verifyClientToken, verifyCodeService, verifyKeyFingerprint, verifyPassword, verifyToken };
