// src/engine/oauth/state-manager.ts — In-memory OAuth state manager (SPEC-440)
import { randomBytes } from 'node:crypto';
import { generateCodeVerifier } from './pkce.js';
const STATE_TTL_MS = 5 * 60 * 1000; // 5 minutes
const stateMap = new Map();
/**
 * Create a new OAuth state entry with CSRF token, PKCE verifier, and TTL.
 */
export function createOAuthState(integration, projectPath, port) {
    const state = randomBytes(16).toString('hex');
    const codeVerifier = generateCodeVerifier();
    const now = new Date();
    const expiresAt = new Date(now.getTime() + STATE_TTL_MS);
    const entry = {
        state,
        integration,
        projectPath,
        codeVerifier,
        port,
        createdAt: now.toISOString(),
        expiresAt: expiresAt.toISOString(),
    };
    stateMap.set(state, entry);
    return entry;
}
/**
 * Validate that the state token is known and not expired, then remove it.
 * Returns null if missing or expired (consumed or never existed).
 */
export function validateAndConsumeState(state) {
    const entry = stateMap.get(state);
    if (!entry) {
        return null;
    }
    stateMap.delete(state);
    if (new Date(entry.expiresAt) < new Date()) {
        return null;
    }
    return entry;
}
/**
 * Read an active state entry without consuming it.
 * Returns null if missing or expired.
 */
export function getActiveState(state) {
    const entry = stateMap.get(state);
    if (!entry) {
        return null;
    }
    if (new Date(entry.expiresAt) < new Date()) {
        return null;
    }
    return entry;
}
//# sourceMappingURL=state-manager.js.map