diff --git a/client/settings-screen.tsx b/client/settings-screen.tsx index df55d5d..4961bd2 100644 --- a/client/settings-screen.tsx +++ b/client/settings-screen.tsx @@ -1,5 +1,4 @@ -import type { PluginSurfaceProps } from "@getpaseo/plugin/client"; -import { useRpc, useSettings } from "@getpaseo/plugin/client"; +import { openExternalUrl, type PluginSurfaceProps, useRpc, useSettings } from "@getpaseo/plugin/client"; import { ScrollView, SettingsAction, @@ -19,6 +18,7 @@ import { flySpritesSettings, type FlySpritesSettings, } from "../shared/settings"; +import { useOpenBaoAuth } from "./use-openbao-auth"; const MODE_OPTIONS: readonly { label: string; value: FlySpritesSettings["defaultProviderMode"] }[] = [ { label: "Remote Shell Worker (bash -lc)", value: "shell" }, @@ -29,6 +29,7 @@ export function FlySpritesSettingsScreen({ theme, layout, host }: PluginSurfaceP const settings = useSettings(flySpritesSettings); const testConnection = useRpc(testConnectionRpc); const toast = useToast(); + const openbao = useOpenBaoAuth(); const [draft, setDraft] = useState(defaultFlySpritesSettings); const [testing, setTesting] = useState(false); @@ -118,11 +119,37 @@ export function FlySpritesSettingsScreen({ theme, layout, host }: PluginSurfaceP } } + async function handleStartZitadel() { + if (isDirty) { + await settings.save(draft, revision); + } + await openbao.startLogin(); + } + + async function handlePullOpenBao() { + if (isDirty) { + await settings.save(draft, revision); + } + await openbao.pullNow(); + } + + const baoStatus = openbao.status; + const pendingFlow = baoStatus?.pendingAuth?.status === "pending" ? baoStatus.pendingAuth : null; + const baoSummary = baoStatus?.authenticated + ? `Signed in as ${baoStatus.displayName ?? "Zitadel user"}${ + baoStatus.tokenPresent ? " · Token loaded" : " · Token not loaded" + }` + : "Not signed in"; + return ( Host settings for {host.label}. Leave token blank to use SPRITES_TOKEN.} + info={ + + Host settings for {host.label}. Leave Sprites API token blank to pull from OpenBao or host env. + + } > {isInvalid ? ( @@ -133,9 +160,9 @@ export function FlySpritesSettingsScreen({ theme, layout, host }: PluginSurfaceP { @@ -164,6 +191,162 @@ export function FlySpritesSettingsScreen({ theme, layout, host }: PluginSurfaceP + + Pulls {draft.openbaoSecretKey || "FLY_TOKEN"} from {draft.openbaoKvMount || "secret"}/ + {draft.openbaoSecretPath || "paseo"} via Zitadel Device Code auth. + + } + > + + { + const next = { ...draft, openbaoEnabled }; + setDraft(next); + void saveDraft(next); + }} + /> + + {pendingFlow ? ( + + void openExternalUrl(pendingFlow.verificationUriComplete || pendingFlow.verificationUri) + } + /> + ) : null} + void handleStartZitadel()} + /> + {baoStatus?.authenticated ? ( + <> + void handlePullOpenBao()} + /> + void openbao.logout()} + /> + + ) : null} + { + setStatusMessage(null); + setDraft((prev) => ({ ...prev, openbaoAddr })); + }} + /> + { + setStatusMessage(null); + setDraft((prev) => ({ ...prev, openbaoKvMount })); + }} + /> + { + setStatusMessage(null); + setDraft((prev) => ({ ...prev, openbaoSecretPath })); + }} + /> + { + setStatusMessage(null); + setDraft((prev) => ({ ...prev, openbaoSecretKey })); + }} + /> + { + const [mount, role] = val.split(":"); + setStatusMessage(null); + setDraft((prev) => ({ + ...prev, + openbaoAuthMount: (mount ?? "jwt").trim() || "jwt", + openbaoRole: (role ?? "admin").trim() || "admin", + })); + }} + /> + { + setStatusMessage(null); + setDraft((prev) => ({ ...prev, zitadelIssuer })); + }} + /> + { + setStatusMessage(null); + setDraft((prev) => ({ ...prev, zitadelClientId })); + }} + /> + { + setStatusMessage(null); + setDraft((prev) => ({ ...prev, zitadelScope })); + }} + /> + + + void | Promise; +} + +export function useOpenBaoAuth(options: UseOpenBaoAuthOptions = {}) { + const { onConnected } = options; + const toast = useToast(); + const fetchStatus = useRpc(openbaoStatusRpc); + const startAuth = useRpc(openbaoAuthStartRpc); + const pullRpc = useRpc(openbaoPullRpc); + const logoutRpc = useRpc(openbaoLogoutRpc); + + const [status, setStatus] = useState(null); + const [busy, setBusy] = useState(false); + + const refreshStatus = useCallback(async () => { + try { + const next = await fetchStatus({}); + setStatus(next); + return next; + } catch { + return null; + } + }, [fetchStatus]); + + useEffect(() => { + void refreshStatus(); + }, [refreshStatus]); + + const pendingStatus = status?.pendingAuth?.status; + useEffect(() => { + if (pendingStatus !== "pending") return; + let cancelled = false; + const timer = setInterval(() => { + void (async () => { + const next = await refreshStatus(); + if (cancelled || !next) return; + const flow = next.pendingAuth; + if (flow?.status === "complete") { + toast.show( + next.tokenPresent + ? `Connected to OpenBao as ${next.displayName ?? "Zitadel user"} and loaded token.` + : `Signed in as ${next.displayName ?? "Zitadel user"}, but token pull failed.`, + { variant: next.tokenPresent ? "success" : "error" }, + ); + await onConnected?.(); + } else if (flow?.status === "error" && flow.error) { + toast.error(flow.error); + } + })(); + }, 2000); + return () => { + cancelled = true; + clearInterval(timer); + }; + }, [pendingStatus, refreshStatus, onConnected, toast]); + + const startLogin = useCallback(async () => { + setBusy(true); + try { + const res = await startAuth({}); + if (!res.ok) { + toast.error(res.error); + return null; + } + await refreshStatus(); + if (res.pendingAuth.verificationUriComplete) { + await openExternalUrl(res.pendingAuth.verificationUriComplete).catch(() => undefined); + } + return res.pendingAuth; + } catch (error) { + toast.error(error instanceof Error ? error.message : String(error)); + return null; + } finally { + setBusy(false); + } + }, [startAuth, refreshStatus, toast]); + + const pullNow = useCallback(async () => { + setBusy(true); + try { + const res = await pullRpc({}); + if (!res.ok) { + toast.error(res.error); + await refreshStatus(); + return false; + } + setStatus(res.status); + toast.show("Pulled Fly token from OpenBao.", { variant: "success" }); + await onConnected?.(); + return true; + } catch (error) { + toast.error(error instanceof Error ? error.message : String(error)); + return false; + } finally { + setBusy(false); + } + }, [pullRpc, refreshStatus, onConnected, toast]); + + const logout = useCallback(async () => { + setBusy(true); + try { + await logoutRpc({}); + await refreshStatus(); + toast.show("Signed out of OpenBao."); + await onConnected?.(); + } catch (error) { + toast.error(error instanceof Error ? error.message : String(error)); + } finally { + setBusy(false); + } + }, [logoutRpc, refreshStatus, onConnected, toast]); + + return { + status, + busy, + refreshStatus, + startLogin, + pullNow, + logout, + }; +} diff --git a/client/workers-screen.tsx b/client/workers-screen.tsx index af72e73..35be8f7 100644 --- a/client/workers-screen.tsx +++ b/client/workers-screen.tsx @@ -1,5 +1,6 @@ import { type PluginHostProps, + openExternalUrl, useRpc, useSubscription, } from "@getpaseo/plugin/client"; @@ -9,6 +10,7 @@ import { Pressable, Text, View } from "react-native"; import { type CheckpointSummary, type SpriteSummary, + type TokenSource, type WorkerSummary, createCheckpointRpc, createSpriteRpc, @@ -22,6 +24,7 @@ import { watchWorkersSub, workerLogsRpc, } from "../shared/contracts"; +import { useOpenBaoAuth } from "./use-openbao-auth"; interface WorkersScreenProps extends PluginHostProps { workspaceName?: string; @@ -49,7 +52,7 @@ export function FlySpritesWorkersScreen({ const restoreCheckpoint = useRpc(restoreCheckpointRpc); const [configured, setConfigured] = useState(false); - const [tokenSource, setTokenSource] = useState<"settings" | "env" | "none">("none"); + const [tokenSource, setTokenSource] = useState("none"); const [remoteError, setRemoteError] = useState(null); const [sprites, setSprites] = useState([]); const [workers, setWorkers] = useState([]); @@ -98,6 +101,10 @@ export function FlySpritesWorkersScreen({ void refresh(); }, [refresh]); + const openbao = useOpenBaoAuth({ onConnected: refresh }); + const pendingFlow = + openbao.status?.pendingAuth?.status === "pending" ? openbao.status.pendingAuth : null; + const selectedWorker = useMemo( () => workers.find((w) => w.workerId === selectedWorkerId) ?? null, [workers, selectedWorkerId], @@ -357,8 +364,61 @@ export function FlySpritesWorkersScreen({ {!configured ? ( - No Fly Sprites API token configured. Open Settings → Fly Sprites Workers or set SPRITES_TOKEN on the host. + No Fly Sprites API token loaded. Sign in with Zitadel to pull FLY_TOKEN from OpenBao, or configure a token in Settings → Fly Sprites Workers. + {openbao.status?.lastError ? ( + OpenBao: {openbao.status.lastError} + ) : null} + {pendingFlow ? ( + + + Waiting for Zitadel approval · Code: {pendingFlow.userCode} + + + + void openExternalUrl( + pendingFlow.verificationUriComplete || pendingFlow.verificationUri, + ) + } + > + Open Zitadel Login + + void copyText(pendingFlow.userCode)} + > + Copy Code + + + + ) : ( + + void openbao.startLogin()} + disabled={openbao.busy} + > + + {openbao.busy + ? "Starting…" + : openbao.status?.authenticated + ? "Re-authenticate Zitadel" + : "Sign in with Zitadel"} + + + {openbao.status?.authenticated ? ( + void openbao.pullNow()} + disabled={openbao.busy} + > + Pull from OpenBao + + ) : null} + + )} ) : null} diff --git a/index.server.ts b/index.server.ts index adfa631..24ccf53 100644 --- a/index.server.ts +++ b/index.server.ts @@ -2,6 +2,7 @@ import "./server/sprites-cjs-shim"; import type { PluginServerContext } from "@getpaseo/plugin/server"; import { createSpriteAgentTools } from "./server/agent-tools"; +import { OpenBaoClient } from "./server/openbao-client"; import { createFlySpritesProvider } from "./server/provider"; import { SpritesManager } from "./server/sprites-manager"; import { @@ -9,6 +10,10 @@ import { createSpriteRpc, destroySpriteRpc, listCheckpointsRpc, + openbaoAuthStartRpc, + openbaoLogoutRpc, + openbaoPullRpc, + openbaoStatusRpc, restoreCheckpointRpc, spawnWorkerRpc, statusRpc, @@ -36,7 +41,8 @@ export default function contribute(server: PluginServerContext) { return state.status === "ready" ? state.values : defaultFlySpritesSettings; } - const manager = new SpritesManager(readSettings); + const openbao = new OpenBaoClient(readSettings); + const manager = new SpritesManager(readSettings, openbao); const provider = createFlySpritesProvider(manager, readSettings); const agentTools = createSpriteAgentTools(manager); @@ -62,6 +68,33 @@ export default function contribute(server: PluginServerContext) { await manager.deleteSprite(spriteName).catch(() => undefined); }); + server.handle(openbaoStatusRpc, async () => { + return await openbao.getStatus(); + }); + + server.handle(openbaoAuthStartRpc, async () => { + try { + const pendingAuth = await openbao.startDeviceAuth(); + return { ok: true as const, pendingAuth }; + } catch (error) { + return { ok: false as const, error: errMsg(error) }; + } + }); + + server.handle(openbaoPullRpc, async () => { + try { + const status = await openbao.pullNow(); + return { ok: true as const, status }; + } catch (error) { + return { ok: false as const, error: errMsg(error) }; + } + }); + + server.handle(openbaoLogoutRpc, async () => { + await openbao.logout(); + return { ok: true as const }; + }); + server.handle(testConnectionRpc, async () => { try { const { client, source } = await manager.getClient(); @@ -226,6 +259,7 @@ export default function contribute(server: PluginServerContext) { return () => { removeOpenHook(); removeArchiveHook(); + openbao.dispose(); manager.dispose(); }; } diff --git a/server/openbao-client.ts b/server/openbao-client.ts new file mode 100644 index 0000000..ac4ff7e --- /dev/null +++ b/server/openbao-client.ts @@ -0,0 +1,704 @@ +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 CachedSecret { + cacheKey: string; + token: string; + pulledAt: string; + expiresAtMs: number; +} + +const SECRET_CACHE_TTL_MS = 5 * 60_000; +const DISCOVERY_CACHE_TTL_MS = 60 * 60_000; +const REQUEST_TIMEOUT_MS = 15_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}`; +} + +export class OpenBaoClient { + private readonly getSettings: () => Promise; + private sessionLoaded = false; + private session: PersistedOpenBaoSession | null = null; + private cachedSecret: CachedSecret | null = null; + private discoveryCache = new Map(); + private pendingFlow: PendingFlowInternal | null = null; + private lastError: string | null = null; + private pullInFlight: Promise | 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), + settings.openbaoSecretKey.trim() || "FLY_TOKEN", + ].join("|"); + } + + async getSecretToken(forceRefresh = false): Promise { + const settings = await this.getSettings(); + if (!settings.openbaoEnabled) { + return ""; + } + + const cacheKey = this.secretCacheKey(settings); + if ( + !forceRefresh && + this.cachedSecret && + this.cachedSecret.cacheKey === cacheKey && + this.cachedSecret.expiresAtMs > Date.now() + ) { + return this.cachedSecret.token; + } + + if (!forceRefresh && this.pullInFlight) { + return await this.pullInFlight; + } + + const work = this.fetchSecretFromOpenBao(settings, cacheKey); + this.pullInFlight = work; + try { + return await work; + } finally { + if (this.pullInFlight === work) { + this.pullInFlight = null; + } + } + } + + private async fetchSecretFromOpenBao( + settings: FlySpritesSettings, + cacheKey: string, + ): Promise { + let sess = await this.ensureValidBaoToken(settings); + if (!sess) { + return ""; + } + + const kvMount = settings.openbaoKvMount.trim().replace(/^\/+|\/+$/g, "") || "secret"; + const secretPath = normalizeKvPath(settings.openbaoSecretPath, kvMount); + if (!secretPath) { + this.lastError = "OpenBao secret path is empty."; + return ""; + } + + 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 ""; + } + + const outerData = (res.body.data ?? {}) as Record; + const secretData = (outerData.data ?? {}) as Record; + const preferredKey = settings.openbaoSecretKey.trim() || "FLY_TOKEN"; + const candidateKeys = + preferredKey === "FLY_TOKEN" + ? ["FLY_TOKEN", "SPRITES_TOKEN", "FLY_API_TOKEN"] + : [preferredKey]; + + let found = ""; + for (const key of candidateKeys) { + const value = secretData[key]; + if (typeof value === "string" && value.trim()) { + found = value.trim(); + break; + } + } + + if (!found) { + this.lastError = `Key "${preferredKey}" not found at ${kvMount}/${secretPath}.`; + return ""; + } + + this.lastError = null; + this.cachedSecret = { + cacheKey, + token: found, + pulledAt: new Date().toISOString(), + expiresAtMs: Date.now() + SECRET_CACHE_TTL_MS, + }; + return found; + } + + 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(), + ); + + 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; + } + } +} diff --git a/server/provider.ts b/server/provider.ts index 5b6d6dc..ba9f3c0 100644 --- a/server/provider.ts +++ b/server/provider.ts @@ -625,7 +625,8 @@ export function createFlySpritesProvider( if (source === "none") { return { available: false, - diagnostic: "Configure a Fly Sprites token in Fly Sprites Workers settings or set SPRITES_TOKEN.", + diagnostic: + "Sign in with Zitadel (OpenBao) or configure a token in Fly Sprites Workers settings.", }; } return { available: true }; diff --git a/server/sprites-manager.ts b/server/sprites-manager.ts index 701c70d..46adb15 100644 --- a/server/sprites-manager.ts +++ b/server/sprites-manager.ts @@ -15,15 +15,17 @@ import { import type { CheckpointSummary, SpriteSummary, + TokenSource, WorkerSummary, } from "../shared/contracts"; import type { FlySpritesSettings } from "../shared/settings"; +import type { OpenBaoClient } from "./openbao-client"; const execFileAsync = promisify(nodeExecFile); const MAX_OUTPUT_BYTES = 256 * 1024; const TAIL_CHARS = 4000; -export type TokenSource = "settings" | "env" | "none"; +export type { TokenSource }; export interface TrackedWorker { workerId: string; @@ -93,13 +95,15 @@ function formatCheckpointStreamMessage(msg: StreamMessage): string { export class SpritesManager { private readonly getSettings: () => Promise; + private readonly openbao: OpenBaoClient; private cachedClient: { key: string; client: SpritesClient } | null = null; private readonly workers = new Map(); private readonly listeners = new Set<(workers: WorkerSummary[]) => void>(); private notifyTimer: ReturnType | null = null; - constructor(getSettings: () => Promise) { + constructor(getSettings: () => Promise, openbao: OpenBaoClient) { this.getSettings = getSettings; + this.openbao = openbao; } async resolveToken(): Promise<{ token: string; source: TokenSource; baseUrl: string }> { @@ -109,6 +113,12 @@ export class SpritesManager { if (fromSettings) { return { token: fromSettings, source: "settings", baseUrl }; } + if (settings.openbaoEnabled) { + const fromOpenBao = await this.openbao.getSecretToken(); + if (fromOpenBao) { + return { token: fromOpenBao, source: "openbao", baseUrl }; + } + } const fromEnv = process.env.SPRITES_TOKEN?.trim() || process.env.FLY_TOKEN?.trim() || @@ -120,12 +130,12 @@ export class SpritesManager { return { token: "", source: "none", baseUrl }; } - async getClient(): Promise<{ client: SpritesClient; source: "settings" | "env"; settings: FlySpritesSettings }> { + async getClient(): Promise<{ client: SpritesClient; source: Exclude; settings: FlySpritesSettings }> { const settings = await this.getSettings(); const { token, source, baseUrl } = await this.resolveToken(); if (!token || source === "none") { throw new Error( - "Fly Sprites token is not configured. Set it in Fly Sprites Workers settings or SPRITES_TOKEN.", + "Fly Sprites token is not configured. Sign in with Zitadel (OpenBao), set it in Fly Sprites Workers settings, or export FLY_TOKEN / SPRITES_TOKEN.", ); } const key = `${baseUrl}::${token}`; diff --git a/shared/contracts.ts b/shared/contracts.ts index dcab6d3..37c272c 100644 --- a/shared/contracts.ts +++ b/shared/contracts.ts @@ -41,6 +41,34 @@ export const CheckpointSummarySchema = z.object({ export type CheckpointSummary = z.output; +export const TokenSourceSchema = z.enum(["settings", "openbao", "env", "none"]); +export type TokenSource = z.output; + +export const OpenBaoPendingAuthSchema = z.object({ + flowId: z.string(), + userCode: z.string(), + verificationUri: z.string(), + verificationUriComplete: z.string(), + expiresAt: z.string(), + status: z.enum(["pending", "complete", "error"]), + error: z.string().nullable(), +}); + +export type OpenBaoPendingAuth = z.output; + +export const OpenBaoStatusSchema = z.object({ + enabled: z.boolean(), + authenticated: z.boolean(), + displayName: z.string().nullable(), + policies: z.array(z.string()), + tokenPresent: z.boolean(), + lastPulledAt: z.string().nullable(), + lastError: z.string().nullable(), + pendingAuth: OpenBaoPendingAuthSchema.nullable(), +}); + +export type OpenBaoStatus = z.output; + export const testConnectionRpc = defineRpc({ name: "sprites.test", input: z.object({}), @@ -48,7 +76,7 @@ export const testConnectionRpc = defineRpc({ z.object({ ok: z.literal(true), spriteCount: z.number(), - source: z.enum(["settings", "env"]), + source: z.enum(["settings", "openbao", "env"]), }), z.object({ ok: z.literal(false), @@ -64,13 +92,57 @@ export const statusRpc = defineRpc({ }), output: z.object({ configured: z.boolean(), - tokenSource: z.enum(["settings", "env", "none"]), + tokenSource: TokenSourceSchema, remoteError: z.string().nullable(), sprites: z.array(SpriteSummarySchema), workers: z.array(WorkerSummarySchema), }), }); +export const openbaoStatusRpc = defineRpc({ + name: "openbao.status", + input: z.object({}), + output: OpenBaoStatusSchema, +}); + +export const openbaoAuthStartRpc = defineRpc({ + name: "openbao.auth.start", + input: z.object({}), + output: z.discriminatedUnion("ok", [ + z.object({ + ok: z.literal(true), + pendingAuth: OpenBaoPendingAuthSchema, + }), + z.object({ + ok: z.literal(false), + error: z.string(), + }), + ]), +}); + +export const openbaoPullRpc = defineRpc({ + name: "openbao.pull", + input: z.object({}), + output: z.discriminatedUnion("ok", [ + z.object({ + ok: z.literal(true), + status: OpenBaoStatusSchema, + }), + z.object({ + ok: z.literal(false), + error: z.string(), + }), + ]), +}); + +export const openbaoLogoutRpc = defineRpc({ + name: "openbao.logout", + input: z.object({}), + output: z.object({ + ok: z.literal(true), + }), +}); + export const createSpriteRpc = defineRpc({ name: "sprites.create", input: z.object({ diff --git a/shared/settings.ts b/shared/settings.ts index 6d28715..31db9b7 100644 --- a/shared/settings.ts +++ b/shared/settings.ts @@ -4,6 +4,16 @@ import { z } from "zod"; export const flySpritesSettingsSchema = z.object({ token: z.string().default(""), baseUrl: z.string().default("https://api.sprites.dev"), + openbaoEnabled: z.boolean().default(true), + openbaoAddr: z.string().default("https://bao.site.latha.org"), + openbaoAuthMount: z.string().default("jwt"), + openbaoRole: z.string().default("admin"), + openbaoKvMount: z.string().default("secret"), + openbaoSecretPath: z.string().default("paseo"), + openbaoSecretKey: z.string().default("FLY_TOKEN"), + zitadelIssuer: z.string().default("https://auth.site.latha.org"), + zitadelClientId: z.string().default("400222693598691513"), + zitadelScope: z.string().default("openid profile email"), spritePrefix: z.string().default("paseo-worker-"), defaultRegion: z.string().default(""), defaultRamMB: z.number().int().nonnegative().default(0), @@ -28,6 +38,16 @@ export const flySpritesSettings = defineSettings({ export const defaultFlySpritesSettings: FlySpritesSettings = { token: "", baseUrl: "https://api.sprites.dev", + openbaoEnabled: true, + openbaoAddr: "https://bao.site.latha.org", + openbaoAuthMount: "jwt", + openbaoRole: "admin", + openbaoKvMount: "secret", + openbaoSecretPath: "paseo", + openbaoSecretKey: "FLY_TOKEN", + zitadelIssuer: "https://auth.site.latha.org", + zitadelClientId: "400222693598691513", + zitadelScope: "openid profile email", spritePrefix: "paseo-worker-", defaultRegion: "", defaultRamMB: 0,