/**
 * Public key registry for authentication
 * Maps bearer tokens (base64url-encoded public keys) to user identities
 */
import { parseBearerToken } from "../crypto/keys.js";
// In-memory registry (in production, use persistent storage)
const publicKeyRegistry = new Map();
/** Ed25519 public key size in bytes (RFC 8032) */
const ED25519_PUBLIC_KEY_BYTES = 32;
/**
 * Register a public key (derived from bearer token).
 * Only accepts tokens that decode to exactly 32 bytes (Ed25519 public key);
 * rejects JWTs and other non-key tokens so they are validated as session tokens.
 */
export function registerPublicKey(bearerToken, userId) {
    try {
        const publicKey = parseBearerToken(bearerToken);
        if (publicKey.length !== ED25519_PUBLIC_KEY_BYTES) {
            throw new Error("Invalid key length");
        }
        publicKeyRegistry.set(bearerToken, {
            publicKey,
            userId,
            createdAt: new Date(),
            lastUsed: new Date(),
        });
    }
    catch {
        throw new Error("Invalid bearer token format");
    }
}
/**
 * Get public key from bearer token
 */
export function getPublicKey(bearerToken) {
    const entry = publicKeyRegistry.get(bearerToken);
    if (!entry) {
        return null;
    }
    // Update last used timestamp
    entry.lastUsed = new Date();
    return entry.publicKey;
}
/**
 * Verify bearer token is registered
 */
export function isBearerTokenValid(bearerToken) {
    return publicKeyRegistry.has(bearerToken);
}
/**
 * Get userId for a registered bearer token (if it was registered with userId)
 */
export function getUserIdFromBearerToken(bearerToken) {
    const entry = publicKeyRegistry.get(bearerToken);
    return entry?.userId;
}
/**
 * Auto-register public key if not exists (for first-time users)
 * Returns true if registration succeeded, false if token format is invalid
 */
export function ensurePublicKeyRegistered(bearerToken) {
    if (publicKeyRegistry.has(bearerToken)) {
        return true;
    }
    try {
        registerPublicKey(bearerToken);
        return true;
    }
    catch {
        // Invalid bearer token format - return false instead of throwing
        return false;
    }
}
/**
 * Get all registered public keys (for admin/debugging)
 */
export function getAllPublicKeys() {
    return Array.from(publicKeyRegistry.entries()).map(([token, entry]) => ({
        bearerToken: token,
        userId: entry.userId,
        createdAt: entry.createdAt,
    }));
}
//# sourceMappingURL=public_key_registry.js.map