import { createHash } from "node:crypto"; import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; import { SpritesClient } from "@fly/sprites"; const DEFAULT_BASE_URL = "https://api.sprites.dev"; const FLY_GRAPHQL_URL = "https://api.fly.io/graphql"; const REQUEST_TIMEOUT_MS = 15_000; interface PersistedSpritesTokenCache { keyHash: string; baseUrl: string; orgSlug: string; token: string; createdAt: string; } function cacheFilePath(): string { const base = process.env.PASEO_HOME || path.join(homedir(), ".paseo"); return path.join(base, "plugin-data", "fly-sprites-workers", "sprites-token-cache.json"); } function computeKeyHash(macaroon: string, baseUrl: string, orgSlugHint: string): string { return createHash("sha256") .update(`${baseUrl}|${orgSlugHint}|${macaroon}`) .digest("hex"); } export function extractFlyMacaroon(rawToken: string): string | null { const trimmed = rawToken.trim(); if (!trimmed) return null; if (/^FlyV1\s+/i.test(trimmed)) { const rest = trimmed.replace(/^FlyV1\s+/i, "").trim(); return rest || null; } if (trimmed.startsWith("fm2_") || trimmed.startsWith("fm1r_")) { return trimmed; } return null; } async function resolveFlyOrgSlug(macaroon: string, preferredOrgSlug?: string): Promise { const explicit = preferredOrgSlug?.trim(); if (explicit) return explicit; const res = await fetch(FLY_GRAPHQL_URL, { method: "POST", headers: { Authorization: `FlyV1 ${macaroon}`, "Content-Type": "application/json", }, body: JSON.stringify({ query: "{ organizations { nodes { slug type } } }", }), signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) as unknown as NonNullable, }); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error( `Failed to resolve Fly organization for FlyV1 token (HTTP ${res.status}${text ? `: ${text}` : ""}).`, ); } const payload = (await res.json()) as { data?: { organizations?: { nodes?: Array<{ slug?: string; type?: string }> } }; errors?: Array<{ message?: string }>; }; if (Array.isArray(payload.errors) && payload.errors.length > 0) { const msg = payload.errors.map((e) => e.message).filter(Boolean).join("; "); throw new Error(`Fly GraphQL error while resolving organization: ${msg || "unknown error"}`); } const nodes = payload.data?.organizations?.nodes ?? []; const personal = nodes.find((node) => node.type === "PERSONAL" && node.slug); const chosen = personal?.slug ?? nodes.find((node) => node.slug)?.slug; if (!chosen) { throw new Error( "Could not determine a Fly organization slug for this FlyV1 token. Set Fly organization slug in Fly Sprites Workers settings.", ); } return chosen; } async function mintSpritesToken( macaroon: string, orgSlug: string, baseUrl: string, ): Promise { const cleanBase = baseUrl.trim().replace(/\/+$/, "") || DEFAULT_BASE_URL; if (cleanBase === DEFAULT_BASE_URL) { return await SpritesClient.createToken(macaroon, orgSlug); } const res = await fetch( `${cleanBase}/v1/organizations/${encodeURIComponent(orgSlug)}/tokens`, { method: "POST", headers: { Authorization: `FlyV1 ${macaroon}`, "Content-Type": "application/json", }, body: JSON.stringify({ description: "Sprite SDK Token" }), signal: AbortSignal.timeout(30_000) as unknown as NonNullable, }, ); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error( `Failed to exchange FlyV1 token for Sprites token (HTTP ${res.status}${text ? `: ${text}` : ""}).`, ); } const data = (await res.json()) as { token?: string }; if (!data.token) { throw new Error("Sprites token exchange did not return a token."); } return data.token; } export class FlyTokenExchange { private memoryCache: PersistedSpritesTokenCache | null = null; private diskLoaded = false; private readonly inFlight = new Map>(); private async loadFromDisk(): Promise { if (this.diskLoaded) return this.memoryCache; this.diskLoaded = true; try { const raw = await readFile(cacheFilePath(), "utf8"); const parsed = JSON.parse(raw) as PersistedSpritesTokenCache; if (parsed && typeof parsed.keyHash === "string" && typeof parsed.token === "string" && parsed.token) { this.memoryCache = parsed; } } catch { this.memoryCache = null; } return this.memoryCache; } private async saveToDisk(entry: PersistedSpritesTokenCache | null): Promise { this.diskLoaded = true; this.memoryCache = entry; const filePath = cacheFilePath(); if (!entry) { await rm(filePath, { force: true }).catch(() => undefined); return; } await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 }); await writeFile(filePath, JSON.stringify(entry, null, 2), { mode: 0o600 }); } async exchange( macaroon: string, options: { baseUrl: string; orgSlug?: string; forceRefresh?: boolean }, ): Promise { const cleanBase = options.baseUrl.trim().replace(/\/+$/, "") || DEFAULT_BASE_URL; const orgHint = options.orgSlug?.trim() || ""; const keyHash = computeKeyHash(macaroon, cleanBase, orgHint); if (!options.forceRefresh) { const cached = await this.loadFromDisk(); if (cached && cached.keyHash === keyHash && cached.token) { return cached.token; } const pending = this.inFlight.get(keyHash); if (pending) { return await pending; } } const work = (async () => { const orgSlug = await resolveFlyOrgSlug(macaroon, orgHint); const token = await mintSpritesToken(macaroon, orgSlug, cleanBase); await this.saveToDisk({ keyHash, baseUrl: cleanBase, orgSlug, token, createdAt: new Date().toISOString(), }); return token; })(); this.inFlight.set(keyHash, work); try { return await work; } finally { if (this.inFlight.get(keyHash) === work) { this.inFlight.delete(keyHash); } } } async clear(): Promise { await this.saveToDisk(null); } }