/**
 * CF Access service-token resolver (CLI mirror — Phase H h2).
 *
 * Mirrors packages/auth-client/src/cf-access-service-token.ts so the CLI
 * stays a self-contained published bundle (no new workspace dependency in
 * the publish path). The auth-client copy is the canonical one consumed by
 * host-cp; this copy backs `olam auth issue/list-anthropic-tokens`.
 *
 * A CF Access *service token* is a non-interactive (client-id + client-secret)
 * credential the Cloudflare edge validates and converts into a
 * `Cf-Access-Jwt-Assertion` JWT before the request reaches the auth-worker —
 * replacing the manual "paste your CF_Authorization cookie" step.
 *
 * Resolution priority (first hit wins):
 *   1. env CF_ACCESS_CLIENT_ID + CF_ACCESS_CLIENT_SECRET
 *   2. ~/.olam/cf-access-service-token.json  ({clientId, clientSecret}, chmod 600)
 *
 * See docs/runbooks/cf-access-service-token.md for provisioning.
 */
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
/** Default on-disk location for the service-token credential file. */
export function defaultServiceTokenPath() {
    return path.join(os.homedir(), '.olam', 'cf-access-service-token.json');
}
/**
 * Resolve a CF Access service token from env, then from disk.
 * Returns null when neither source supplies BOTH a non-empty clientId and
 * clientSecret.
 */
export function resolveCfAccessServiceToken(env = process.env, filePath = defaultServiceTokenPath()) {
    const envId = env['CF_ACCESS_CLIENT_ID'];
    const envSecret = env['CF_ACCESS_CLIENT_SECRET'];
    if (envId && envId.trim().length > 0 && envSecret && envSecret.trim().length > 0) {
        return { clientId: envId.trim(), clientSecret: envSecret.trim() };
    }
    try {
        const raw = fs.readFileSync(filePath, 'utf-8');
        const parsed = JSON.parse(raw);
        const clientId = typeof parsed.clientId === 'string' ? parsed.clientId.trim() : '';
        const clientSecret = typeof parsed.clientSecret === 'string' ? parsed.clientSecret.trim() : '';
        if (clientId.length > 0 && clientSecret.length > 0) {
            return { clientId, clientSecret };
        }
    }
    catch {
        // File absent / unreadable / malformed JSON → no token.
    }
    return null;
}
//# sourceMappingURL=cf-access-token.js.map