import { randomBytes } from "node:crypto"; import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; import type { OpenBaoPendingAuth, OpenBaoStatus } from "../shared/contracts"; import type { FlySpritesSettings } from "../shared/settings"; interface OidcDiscovery { issuer?: string; device_authorization_endpoint: string; token_endpoint: string; userinfo_endpoint?: string; } interface PersistedOpenBaoSession { baoAddr: string; authMount: string; role: string; zitadelIssuer: string; zitadelClientId: string; displayName: string; policies: string[]; baoToken: string; baoTokenExpiresAt: number | null; baoRenewable: boolean; idToken?: string; refreshToken?: string; updatedAt: string; } interface PendingFlowInternal { flowId: string; deviceCode: string; userCode: string; verificationUri: string; verificationUriComplete: string; expiresAtMs: number; intervalSec: number; status: "pending" | "complete" | "error"; error: string | null; abortController: AbortController; } interface CachedSecretMap { cacheKey: string; data: Record; pulledAt: string; expiresAtMs: number; } const SECRET_CACHE_TTL_COLD_MS = 30 * 60_000; const DISCOVERY_CACHE_TTL_MS = 60 * 60_000; const REQUEST_TIMEOUT_MS = 8_000; function sessionFilePath(): string { const base = process.env.PASEO_HOME || path.join(homedir(), ".paseo"); return path.join(base, "plugin-data", "fly-sprites-workers", "openbao-session.json"); } function normalizeKvPath(rawPath: string, kvMount: string): string { let clean = rawPath.trim().replace(/^\/+|\/+$/g, ""); const mount = kvMount.trim().replace(/^\/+|\/+$/g, ""); if (mount && clean.startsWith(`${mount}/data/`)) { clean = clean.slice(mount.length + "/data/".length); } else if (mount && clean.startsWith(`${mount}/`)) { clean = clean.slice(mount.length + 1); } return clean.replace(/^\/+|\/+$/g, ""); } function decodeJwtClaims(token: string): Record { const parts = token.split("."); if (parts.length !== 3) return {}; try { return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as Record; } catch { return {}; } } function sleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal.aborted) { reject(new Error("aborted")); return; } const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(timer); reject(new Error("aborted")); }; signal.addEventListener("abort", onAbort, { once: true }); }); } async function fetchJson( url: string, init: RequestInit = {}, ): Promise<{ status: number; body: Record }> { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); try { const res = await fetch(url, { ...init, signal: controller.signal as unknown as NonNullable, headers: { Accept: "application/json", ...(init.headers ?? {}), }, }); const text = await res.text(); let body: Record = {}; if (text) { try { body = JSON.parse(text) as Record; } catch { body = { error: text }; } } return { status: res.status, body }; } finally { clearTimeout(timeout); } } function extractBaoError(body: Record, status: number): string { const errors = body.errors; if (Array.isArray(errors) && errors.length > 0) { return errors.map((e) => String(e)).join("; "); } if (typeof body.error === "string" && body.error) { return body.error; } return `OpenBao returned HTTP ${status}`; } function pickFirstString(data: Record, candidateKeys: readonly string[]): string { for (const key of candidateKeys) { const value = data[key]; if (typeof value === "string" && value.trim()) { return value.trim(); } } return ""; } function primaryCandidateKeys(settings: FlySpritesSettings): string[] { const preferredKey = settings.openbaoSecretKey.trim() || "FLY_TOKEN"; return preferredKey === "FLY_TOKEN" ? ["FLY_TOKEN", "SPRITES_TOKEN", "FLY_API_TOKEN"] : [preferredKey]; } export class OpenBaoClient { private readonly getSettings: () => Promise; private sessionLoaded = false; private session: PersistedOpenBaoSession | null = null; private cachedSecret: CachedSecretMap | null = null; private discoveryCache = new Map(); private pendingFlow: PendingFlowInternal | null = null; private lastError: string | null = null; private pullInFlight: Promise | null> | null = null; constructor(getSettings: () => Promise) { this.getSettings = getSettings; } private async ensureSessionLoaded(): Promise { if (this.sessionLoaded) return this.session; this.sessionLoaded = true; try { const raw = await readFile(sessionFilePath(), "utf8"); const parsed = JSON.parse(raw) as PersistedOpenBaoSession; if (parsed && typeof parsed.baoToken === "string" && parsed.baoToken) { this.session = parsed; } } catch { this.session = null; } return this.session; } private async saveSession(next: PersistedOpenBaoSession | null): Promise { this.sessionLoaded = true; this.session = next; const filePath = sessionFilePath(); if (!next) { await rm(filePath, { force: true }).catch(() => undefined); return; } await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 }); await writeFile(filePath, JSON.stringify(next, null, 2), { mode: 0o600 }); } private async discoverOidc(issuer: string): Promise { const clean = issuer.trim().replace(/\/+$/, ""); const now = Date.now(); const cached = this.discoveryCache.get(clean); if (cached && cached.expiresAtMs > now) { return cached.value; } const { status, body } = await fetchJson(`${clean}/.well-known/openid-configuration`); if (status !== 200) { const err = (typeof body.error_description === "string" && body.error_description) || (typeof body.error === "string" && body.error) || `HTTP ${status}`; throw new Error(`OIDC discovery failed (${clean}): ${err}`); } const discovery: OidcDiscovery = { issuer: typeof body.issuer === "string" ? body.issuer : clean, device_authorization_endpoint: typeof body.device_authorization_endpoint === "string" ? body.device_authorization_endpoint : `${clean}/oauth/v2/device_authorization`, token_endpoint: typeof body.token_endpoint === "string" ? body.token_endpoint : `${clean}/oauth/v2/token`, userinfo_endpoint: typeof body.userinfo_endpoint === "string" ? body.userinfo_endpoint : undefined, }; this.discoveryCache.set(clean, { expiresAtMs: now + DISCOVERY_CACHE_TTL_MS, value: discovery, }); return discovery; } private async loginBaoWithJwt( settings: FlySpritesSettings, jwtToken: string, displayName: string, refreshToken?: string, ): Promise { const baoAddr = settings.openbaoAddr.trim().replace(/\/+$/, ""); const authMount = settings.openbaoAuthMount.trim().replace(/^\/+|\/+$/g, "") || "jwt"; const role = settings.openbaoRole.trim() || "admin"; const { status, body } = await fetchJson(`${baoAddr}/v1/auth/${authMount}/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ role, jwt: jwtToken }), }); const auth = (body.auth ?? {}) as Record; const clientToken = typeof auth.client_token === "string" ? auth.client_token : ""; if (status !== 200 || !clientToken) { throw new Error(extractBaoError(body, status)); } const leaseDuration = typeof auth.lease_duration === "number" ? auth.lease_duration : 0; const renewable = Boolean(auth.renewable); const policies = Array.isArray(auth.policies) ? auth.policies.map((p) => String(p)) : []; const next: PersistedOpenBaoSession = { baoAddr, authMount, role, zitadelIssuer: settings.zitadelIssuer.trim().replace(/\/+$/, ""), zitadelClientId: settings.zitadelClientId.trim(), displayName, policies, baoToken: clientToken, baoTokenExpiresAt: leaseDuration > 0 ? Date.now() + leaseDuration * 1000 : null, baoRenewable: renewable, idToken: jwtToken, refreshToken, updatedAt: new Date().toISOString(), }; await this.saveSession(next); return next; } private async ensureValidBaoToken(settings: FlySpritesSettings): Promise { const sess = await this.ensureSessionLoaded(); if (!sess) return null; const targetBao = settings.openbaoAddr.trim().replace(/\/+$/, ""); if (sess.baoAddr !== targetBao) { return null; } const now = Date.now(); const nearExpiry = sess.baoTokenExpiresAt !== null && sess.baoTokenExpiresAt - now < 60_000; if (!nearExpiry) { return sess; } if (sess.baoRenewable) { try { const { status, body } = await fetchJson(`${sess.baoAddr}/v1/auth/token/renew-self`, { method: "POST", headers: { "X-Vault-Token": sess.baoToken }, }); const auth = (body.auth ?? {}) as Record; if (status === 200 && typeof auth.client_token === "string") { const leaseDuration = typeof auth.lease_duration === "number" ? auth.lease_duration : 0; const renewed: PersistedOpenBaoSession = { ...sess, baoToken: auth.client_token, baoTokenExpiresAt: leaseDuration > 0 ? Date.now() + leaseDuration * 1000 : null, updatedAt: new Date().toISOString(), }; await this.saveSession(renewed); return renewed; } } catch { // Fall through to OIDC refresh / JWT re-login. } } return await this.reauthenticateSession(settings, sess); } private async reauthenticateSession( settings: FlySpritesSettings, sess: PersistedOpenBaoSession, ): Promise { if (sess.refreshToken) { try { const discovery = await this.discoverOidc(settings.zitadelIssuer); const form = new URLSearchParams({ grant_type: "refresh_token", refresh_token: sess.refreshToken, client_id: settings.zitadelClientId.trim(), }); const { status, body } = await fetchJson(discovery.token_endpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: form.toString(), }); const jwt = (typeof body.id_token === "string" && body.id_token) || (typeof body.access_token === "string" && body.access_token) || ""; if (status === 200 && jwt) { const nextRefresh = typeof body.refresh_token === "string" && body.refresh_token ? body.refresh_token : sess.refreshToken; return await this.loginBaoWithJwt(settings, jwt, sess.displayName, nextRefresh); } } catch { // Fall through to cached JWT check. } } if (sess.idToken) { const claims = decodeJwtClaims(sess.idToken); const expSec = typeof claims.exp === "number" ? claims.exp : 0; if (expSec * 1000 > Date.now() + 30_000) { try { return await this.loginBaoWithJwt(settings, sess.idToken, sess.displayName, sess.refreshToken); } catch { // Fall through to clearing expired session. } } } return null; } private secretCacheKey(settings: FlySpritesSettings): string { return [ settings.openbaoAddr.trim().replace(/\/+$/, ""), settings.openbaoKvMount.trim().replace(/^\/+|\/+$/g, "") || "secret", normalizeKvPath(settings.openbaoSecretPath, settings.openbaoKvMount), ].join("|"); } private async getSecretData( forceRefresh = false, settingsOverride?: FlySpritesSettings, ): Promise | null> { const settings = settingsOverride ?? (await this.getSettings()); if (!settings.openbaoEnabled) { return null; } const cacheKey = this.secretCacheKey(settings); if ( !forceRefresh && this.cachedSecret && this.cachedSecret.cacheKey === cacheKey && this.cachedSecret.expiresAtMs > Date.now() ) { return this.cachedSecret.data; } if (!forceRefresh && this.pullInFlight) { return await this.pullInFlight; } const work = this.fetchSecretMapFromOpenBao(settings, cacheKey); this.pullInFlight = work; try { return await work; } finally { if (this.pullInFlight === work) { this.pullInFlight = null; } } } async getSecretToken(forceRefresh = false, settingsOverride?: FlySpritesSettings): Promise { const settings = settingsOverride ?? (await this.getSettings()); const data = await this.getSecretData(forceRefresh, settings); if (!data) { return ""; } const found = pickFirstString(data, primaryCandidateKeys(settings)); if (!found) { const kvMount = settings.openbaoKvMount.trim().replace(/^\/+|\/+$/g, "") || "secret"; const secretPath = normalizeKvPath(settings.openbaoSecretPath, kvMount); const preferredKey = settings.openbaoSecretKey.trim() || "FLY_TOKEN"; this.lastError = `Key "${preferredKey}" not found at ${kvMount}/${secretPath}.`; return ""; } this.lastError = null; return found; } async getOptionalSecretKey( candidateKeys: readonly string[], forceRefresh = false, settingsOverride?: FlySpritesSettings, ): Promise { const data = await this.getSecretData(forceRefresh, settingsOverride); if (!data) { return ""; } return pickFirstString(data, candidateKeys); } private async fetchSecretMapFromOpenBao( settings: FlySpritesSettings, cacheKey: string, ): Promise | null> { let sess = await this.ensureValidBaoToken(settings); if (!sess) { return null; } const kvMount = settings.openbaoKvMount.trim().replace(/^\/+|\/+$/g, "") || "secret"; const secretPath = normalizeKvPath(settings.openbaoSecretPath, kvMount); if (!secretPath) { this.lastError = "OpenBao secret path is empty."; return null; } const encodedPath = secretPath .split("/") .map((part) => encodeURIComponent(part)) .join("/"); const url = `${sess.baoAddr}/v1/${encodeURIComponent(kvMount)}/data/${encodedPath}`; let res = await fetchJson(url, { method: "GET", headers: { "X-Vault-Token": sess.baoToken }, }); if (res.status === 401 || res.status === 403) { const refreshed = await this.reauthenticateSession(settings, sess); if (refreshed) { sess = refreshed; res = await fetchJson(url, { method: "GET", headers: { "X-Vault-Token": sess.baoToken }, }); } } if (res.status !== 200) { this.lastError = extractBaoError(res.body, res.status); if (res.status === 401 || res.status === 403) { await this.saveSession(null); } return null; } const outerData = (res.body.data ?? {}) as Record; const rawSecretData = (outerData.data ?? {}) as Record; const normalized: Record = {}; for (const [key, value] of Object.entries(rawSecretData)) { if (typeof value === "string") { normalized[key] = value; } else if (value && typeof value === "object") { try { normalized[key] = JSON.stringify(value); } catch { // Ignore non-serializable values. } } } this.cachedSecret = { cacheKey, data: normalized, pulledAt: new Date().toISOString(), expiresAtMs: Date.now() + SECRET_CACHE_TTL_COLD_MS, }; return normalized; } private serializePendingFlow(): OpenBaoPendingAuth | null { if (!this.pendingFlow) return null; if (this.pendingFlow.status === "pending" && this.pendingFlow.expiresAtMs < Date.now()) { this.pendingFlow.status = "error"; this.pendingFlow.error = "Device code expired. Start Zitadel sign-in again."; } return { flowId: this.pendingFlow.flowId, userCode: this.pendingFlow.userCode, verificationUri: this.pendingFlow.verificationUri, verificationUriComplete: this.pendingFlow.verificationUriComplete, expiresAt: new Date(this.pendingFlow.expiresAtMs).toISOString(), status: this.pendingFlow.status, error: this.pendingFlow.error, }; } async getStatus(): Promise { const settings = await this.getSettings(); const sess = await this.ensureSessionLoaded(); const cacheKey = this.secretCacheKey(settings); const hasFreshToken = Boolean( this.cachedSecret && this.cachedSecret.cacheKey === cacheKey && this.cachedSecret.expiresAtMs > Date.now() && pickFirstString(this.cachedSecret.data, primaryCandidateKeys(settings)), ); return { enabled: settings.openbaoEnabled, authenticated: Boolean(sess?.baoToken), displayName: sess?.displayName ?? null, policies: sess?.policies ?? [], tokenPresent: hasFreshToken, lastPulledAt: this.cachedSecret?.cacheKey === cacheKey ? this.cachedSecret.pulledAt : null, lastError: this.lastError, pendingAuth: this.serializePendingFlow(), }; } async startDeviceAuth(): Promise { const settings = await this.getSettings(); const clientId = settings.zitadelClientId.trim(); if (!clientId) { throw new Error("Zitadel client ID is not configured."); } if (this.pendingFlow) { this.pendingFlow.abortController.abort(); this.pendingFlow = null; } const discovery = await this.discoverOidc(settings.zitadelIssuer); const scope = settings.zitadelScope.trim() || "openid profile email"; const form = new URLSearchParams({ client_id: clientId, scope }); const { status, body } = await fetchJson(discovery.device_authorization_endpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: form.toString(), }); const deviceCode = typeof body.device_code === "string" ? body.device_code : ""; if (status !== 200 || !deviceCode || body.error) { const err = (typeof body.error_description === "string" && body.error_description) || (typeof body.error === "string" && body.error) || `HTTP ${status}`; throw new Error(`Zitadel device authorization failed: ${err}`); } const expiresInSec = typeof body.expires_in === "number" ? body.expires_in : 300; const intervalSec = Math.max(1, typeof body.interval === "number" ? body.interval : 5); const verificationUri = typeof body.verification_uri === "string" ? body.verification_uri : ""; const verificationUriComplete = (typeof body.verification_uri_complete === "string" && body.verification_uri_complete) || verificationUri; const flow: PendingFlowInternal = { flowId: randomBytes(12).toString("hex"), deviceCode, userCode: typeof body.user_code === "string" ? body.user_code : "", verificationUri, verificationUriComplete, expiresAtMs: Date.now() + expiresInSec * 1000, intervalSec, status: "pending", error: null, abortController: new AbortController(), }; this.pendingFlow = flow; this.lastError = null; void this.pollDeviceFlow(flow, discovery, clientId); return this.serializePendingFlow()!; } private async pollDeviceFlow( flow: PendingFlowInternal, discovery: OidcDiscovery, clientId: string, ): Promise { let intervalMs = flow.intervalSec * 1000; const signal = flow.abortController.signal; try { while (!signal.aborted && Date.now() < flow.expiresAtMs) { await sleep(intervalMs, signal); if (signal.aborted) return; const form = new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: flow.deviceCode, client_id: clientId, }); const { status, body } = await fetchJson(discovery.token_endpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: form.toString(), }); const errCode = typeof body.error === "string" ? body.error : ""; if (errCode === "authorization_pending") { continue; } if (errCode === "slow_down") { intervalMs = Math.min(intervalMs + 5000, 30_000); continue; } if (status !== 200 || errCode) { const msg = (typeof body.error_description === "string" && body.error_description) || errCode || `HTTP ${status}`; flow.status = "error"; flow.error = `Zitadel device login failed: ${msg}`; this.lastError = flow.error; return; } const idToken = typeof body.id_token === "string" ? body.id_token : ""; const accessToken = typeof body.access_token === "string" ? body.access_token : ""; const refreshToken = typeof body.refresh_token === "string" && body.refresh_token ? body.refresh_token : undefined; const jwtForBao = idToken || accessToken; if (!jwtForBao) { flow.status = "error"; flow.error = "Zitadel token response did not include an id_token or access_token."; this.lastError = flow.error; return; } const claims = idToken ? decodeJwtClaims(idToken) : {}; let userinfo: Record = {}; if (accessToken && discovery.userinfo_endpoint) { const uRes = await fetchJson(discovery.userinfo_endpoint, { method: "GET", headers: { Authorization: `Bearer ${accessToken}` }, }).catch(() => null); if (uRes && uRes.status === 200) { userinfo = uRes.body; } } const displayName = String( userinfo.preferred_username || userinfo.email || userinfo.name || claims.preferred_username || claims.email || claims.name || claims.sub || "zitadel-user", ); const settings = await this.getSettings(); await this.loginBaoWithJwt(settings, jwtForBao, displayName, refreshToken); this.cachedSecret = null; await this.getSecretToken(true); flow.status = "complete"; flow.error = null; return; } if (!signal.aborted && flow.status === "pending") { flow.status = "error"; flow.error = "Device code expired. Start Zitadel sign-in again."; this.lastError = flow.error; } } catch (error) { if (signal.aborted) return; const msg = error instanceof Error ? error.message : String(error); flow.status = "error"; flow.error = msg; this.lastError = msg; } } async pullNow(): Promise { const sess = await this.ensureSessionLoaded(); if (!sess) { throw new Error("Not signed in to OpenBao. Sign in with Zitadel first."); } this.cachedSecret = null; const token = await this.getSecretToken(true); if (!token) { throw new Error(this.lastError || "Could not pull Fly token from OpenBao."); } return await this.getStatus(); } async logout(): Promise { if (this.pendingFlow) { this.pendingFlow.abortController.abort(); this.pendingFlow = null; } const sess = await this.ensureSessionLoaded(); if (sess?.baoToken) { await fetchJson(`${sess.baoAddr}/v1/auth/token/revoke-self`, { method: "POST", headers: { "X-Vault-Token": sess.baoToken }, }).catch(() => undefined); } this.cachedSecret = null; this.lastError = null; await this.saveSession(null); } dispose(): void { if (this.pendingFlow) { this.pendingFlow.abortController.abort(); this.pendingFlow = null; } } }