UNPKG

run402-mcp

Version:

MCP server for Run402 — full-stack backend infrastructure for AI agents: Postgres, auth, storage, serverless functions and atomic deploys. Paid with x402/MPP. Includes $0.03 image generation.

438 lines • 19.1 kB
/** * The dev session: a real project user's sign-in for a local dev server * (`run402 dev --login <email>`), owned here once. * * `run402 dev` signs the user in through the project's own emailed code and * stores what the token endpoint answered under the config base directory * (never the project directory), one file per project and email, mode 0600. * The dev server (`@run402/astro` under `astro dev`) is handed the file's * path and keeps it fresh itself, because it can outlive the `run402 dev` * that started it and an access token lives an hour. Both sides call this * module, so the file's format and the refresh have one implementation. * * Refresh tokens are single-use. Two dev servers of one project share one * file, so a refresh runs under a lock file and re-reads the session first: * whoever comes second finds it fresh and spends nothing. * * What the dev server forwards to the data plane is never the user's own * access token: a project admin's carries the `project_admin` role, which a * deployed site never reads the database as. It is the token the gateway * mints for a deployed function (`r.auth.actorToken`), asked for each minute. * * Nothing here is minted with a service key, and nothing reaches a browser. */ import { createHash } from "node:crypto"; import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs"; import { dirname, join } from "node:path"; import { getConfigBaseDir } from "../../core-dist/config.js"; import { LocalError } from "../errors.js"; /** The variable `run402 dev --login` sets for the dev server: the session file's path, never a token. */ export const DEV_SESSION_FILE_ENV = "RUN402_DEV_SESSION_FILE"; /** The variable naming this module's URL, so the dev server runs the very code that wrote the file. */ export const DEV_SESSION_MODULE_ENV = "RUN402_DEV_SESSION_MODULE"; /** The one reusable branch `run402 dev --branch` runs against. */ export const DEV_BRANCH_NAME = "dev"; const CONTEXT = "signing in for local dev"; /** Refresh when the access token has less than this left. */ const REFRESH_AHEAD_MS = 120_000; /** A lock file older than this belonged to a server that died mid-refresh. */ const STALE_LOCK_MS = 30_000; const LOCK_WAIT_MS = 10_000; const LOCK_POLL_MS = 50; /** Ask for the next actor token when the cached one has less than this left. */ const ACTOR_TOKEN_AHEAD_MS = 15_000; const emailKey = (email) => createHash("sha256").update(email.trim().toLowerCase()).digest("hex").slice(0, 16); const sameEmail = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase(); function sessionsRoot() { return join(getConfigBaseDir(), "dev-sessions"); } /** Where a project's dev sign-ins are kept. */ export function devSessionsDir(projectId) { return join(sessionsRoot(), projectId); } /** The file of one project user's dev sign-in. */ export function devSessionPath(projectId, email) { return join(devSessionsDir(projectId), `${emailKey(email)}.json`); } function pendingPath(projectId, email) { return join(devSessionsDir(projectId), `${emailKey(email)}.pending.json`); } /** Parse a stored sign-in; `null` for anything this module did not write. */ export function parseDevSignIn(raw) { let value; try { value = JSON.parse(raw); } catch { return null; } const v = value; const ok = !!v && v.version === 1 && typeof v.project_id === "string" && typeof v.api_base === "string" && (v.target === "live" || v.target === "branch") && typeof v.user?.id === "string" && typeof v.user.email === "string" && typeof v.access_token === "string" && typeof v.refresh_token === "string" && typeof v.access_expires_at === "string" && !Number.isNaN(Date.parse(v.access_expires_at)); return ok ? v : null; } function readDevSignIn(path) { try { return parseDevSignIn(readFileSync(path, "utf8")); } catch { return null; } } function writePrivate(path, value) { mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); const tmp = `${path}.${process.pid}.tmp`; writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 }); renameSync(tmp, path); } /** Write the session beside itself and rename over it, so a reader never sees half a file. */ export function writeDevSignIn(path, signIn) { writePrivate(path, signIn); } function fromTokens(base, tokens, now, signedInAt) { return { version: 1, project_id: base.project_id, ...(base.parent_project_id ? { parent_project_id: base.parent_project_id } : {}), api_base: base.api_base, target: base.target, user: { id: tokens.user.id, email: tokens.user.email, email_verified: tokens.user.email_verified_at != null }, access_token: tokens.access_token, refresh_token: tokens.refresh_token, access_expires_at: new Date(now + (tokens.expires_in ?? 3600) * 1000).toISOString(), signed_in_at: signedInAt ?? new Date(now).toISOString(), }; } const refused = (err) => { const status = err?.status; return status === 400 || status === 401; }; /** The command that completes or repeats a sign-in, for hints and next actions. */ export function devLoginCommand(opts) { const where = opts.target === "branch" ? (opts.branchProjectId ? `--branch ${opts.branchProjectId}` : "--branch") : "--live"; return `run402 dev --login ${opts.email} ${where}${opts.code ? ` --code ${opts.code}` : ""}`; } /** * Sign in, or reuse a stored sign-in. `signed_in`: the dev server can start * with `path`. `code_sent`: there was no terminal; run `command` with the * emailed code. Never returns a token. */ export async function devSignIn(opts) { const now = opts.now ?? Date.now(); const { auth, projectId, email, target } = opts; const path = devSessionPath(projectId, email); const pending = pendingPath(projectId, email); const base = { project_id: projectId, parent_project_id: opts.parentProjectId, api_base: opts.apiBase, target }; const done = (session, reused) => { writeDevSignIn(path, session); return { status: "signed_in", path, user: session.user, target, reused }; }; if (!opts.code) { const kept = readDevSignIn(path); if (kept && kept.project_id === projectId && sameEmail(kept.user.email, email)) { if (Date.parse(kept.access_expires_at) - now > REFRESH_AHEAD_MS) return done({ ...kept, target }, true); try { return done(fromTokens(base, await auth.refreshSession(projectId, kept.refresh_token), now, kept.signed_in_at), true); } catch (err) { // The stored session is over (expired, revoked, or spent): a new ceremony replaces it. if (!refused(err)) throw err; rmSync(path, { force: true }); } } } let challengeId; let code = opts.code; if (code) { let waiting = null; try { waiting = JSON.parse(readFileSync(pending, "utf8")); } catch { waiting = null; } if (typeof waiting?.challenge_id !== "string") { const command = devLoginCommand({ email, target, branchProjectId: opts.branchProjectId }); throw new LocalError(`No code is waiting for ${email} on ${projectId}.`, CONTEXT, { code: "DEV_LOGIN_NO_PENDING_CODE", hint: `Send one first: ${command}`, next_actions: [{ type: "authenticate", command, why: "Sends the sign-in code to the address." }], }); } challengeId = waiting.challenge_id; } else { const sent = await auth.requestMagicLink(projectId, { email, delivery: "code" }); if (!sent.challengeId) { throw new LocalError(`The project did not send a sign-in code to ${email}.`, CONTEXT, { code: "DEV_LOGIN_CODE_UNAVAILABLE", // The gateway accepts every request the same way, sent or not, so that an // address cannot be probed; no challenge means it could not send. hint: `The gateway accepted the request and sent nothing. The usual cause is that ${projectId} has no active mailbox to send sign-in mail from: ` + `check with \`run402 email mailboxes --project ${projectId}\` and make one with \`run402 email create <slug> --project ${projectId}\`, then run the command again.`, }); } challengeId = sent.challengeId; writePrivate(pending, { challenge_id: challengeId, email, requested_at: new Date(now).toISOString() }); if (!opts.prompt) { return { status: "code_sent", email, command: devLoginCommand({ email, target, branchProjectId: opts.branchProjectId, code: "<code>" }) }; } code = (await opts.prompt(`Code sent to ${email}: `)).trim(); } const tokens = await auth.verifyEmailCode(projectId, { challengeId, code }); rmSync(pending, { force: true }); return done(fromTokens(base, tokens, now), false); } /** * End the stored sign-ins of a project and of its branches (one email, or * all): the refresh token stops working at the gateway and the file is * deleted. `authFor(projectId)` gives `r.auth` of a client holding that * project's keys. */ export async function devSignOut(opts) { const root = sessionsRoot(); const ended = []; for (const dir of existsSync(root) ? readdirSync(root) : []) { for (const name of readdirSync(join(root, dir)).filter((n) => n.endsWith(".json") && !n.endsWith(".pending.json"))) { const path = join(root, dir, name); const session = readDevSignIn(path); if (!session || session.project_id !== dir) continue; if (session.project_id !== opts.projectId && session.parent_project_id !== opts.projectId) continue; if (opts.email && !sameEmail(session.user.email, opts.email)) continue; let revoked = true; try { await opts.authFor(session.project_id).endSession(session.project_id, session.refresh_token); } catch { revoked = false; } rmSync(path, { force: true }); rmSync(`${path}.lock`, { force: true }); ended.push({ project_id: session.project_id, email: session.user.email, target: session.target, revoked }); } } if (opts.email) rmSync(pendingPath(opts.projectId, opts.email), { force: true }); return ended; } /** * The branch `run402 dev --branch` runs against. With no id it is the * project's `dev` branch, found or created by the gateway in one call * (`reuse: true`), which also renews it near expiry and answers its keys. * With an id it is that active branch, with the keys this machine holds. */ export async function ensureDevBranch(opts) { const { parentProjectId, branchProjectId } = opts; if (!branchProjectId) { const b = await opts.branches.create(parentProjectId, { name: DEV_BRANCH_NAME, reuse: true, ...(opts.copySecrets ? { copySecrets: true } : {}), }); return { branch_project_id: b.branch_project_id, parent_project_id: parentProjectId, name: b.name, expires_at: b.expires_at, email_mode: b.email_mode, created: b.reused !== true, ...(b.carries ? { carries: b.carries } : {}), keys: { anon_key: b.anon_key, service_key: b.service_key }, }; } const { branches } = await opts.branches.list(parentProjectId); const branch = branches.find((b) => b.status === "active" && b.branch_project_id === branchProjectId); if (!branch) { throw new LocalError(`${branchProjectId} is not an active branch of ${parentProjectId}.`, "choosing the dev branch", { code: "DEV_BRANCH_NOT_FOUND", hint: `List them with 'run402 branches list --project ${parentProjectId}', or run 'run402 dev --branch' to use the '${DEV_BRANCH_NAME}' branch.`, }); } const keys = (await opts.keysFor?.(branchProjectId)) ?? null; if (!keys?.anon_key || !keys.service_key) { throw new LocalError(`This machine does not hold the keys of branch ${branchProjectId}.`, "choosing the dev branch", { code: "DEV_BRANCH_KEYS_MISSING", hint: `Export them with 'run402 credentials project-keys export --project ${branchProjectId} --reveal', or run 'run402 dev --branch' (no id) to use the '${DEV_BRANCH_NAME}' branch, whose keys the gateway answers.`, }); } return { branch_project_id: branch.branch_project_id, parent_project_id: parentProjectId, name: branch.name, expires_at: branch.expires_at, email_mode: branch.email_mode, created: false, ...(branch.carries ? { carries: branch.carries } : {}), keys: { anon_key: keys.anon_key, service_key: keys.service_key }, }; } const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); /** * The session file as a source that keeps itself fresh, for the dev server. * `auth` is `r.auth` of a client holding the project's keys; `now` and `wait` * are passed in so the refresh and its lock can be tested without a clock. */ export function createDevSessionSource(opts) { const now = opts.now ?? Date.now; const wait = opts.wait ?? sleep; const lockPath = `${opts.path}.lock`; let refreshing = null; /** The refresh token the gateway refused; a new sign-in writes a different one. */ let refusedToken = null; let actor = null; let asking = null; const fresh = (s) => Date.parse(s.access_expires_at) - now() > REFRESH_AHEAD_MS; const usable = (s) => (Date.parse(s.access_expires_at) > now() ? s : null); async function lock() { const deadline = now() + LOCK_WAIT_MS; for (;;) { try { closeSync(openSync(lockPath, "wx", 0o600)); return () => { try { unlinkSync(lockPath); } catch { // already gone } }; } catch { let stale; try { stale = now() - statSync(lockPath).mtimeMs > STALE_LOCK_MS; } catch { // the holder released between our open and our stat: try again continue; } if (stale || now() >= deadline) { try { unlinkSync(lockPath); } catch { // someone else took it over } continue; } await wait(LOCK_POLL_MS); } } } async function refresh() { const release = await lock(); try { const stored = readDevSignIn(opts.path); if (!stored) return null; // Another dev server of this project refreshed while we waited for the lock. if (fresh(stored)) return stored; if (stored.refresh_token === refusedToken) return usable(stored); let tokens; try { tokens = await opts.auth.refreshSession(stored.project_id, stored.refresh_token); } catch (err) { // A refusal ends the session when its access token does; anything else is the network. if (refused(err)) refusedToken = stored.refresh_token; return usable(stored); } const next = fromTokens(stored, { ...tokens, user: { ...tokens.user, email: stored.user.email } }, now(), stored.signed_in_at); writeDevSignIn(opts.path, next); return next; } finally { release(); } } async function ask(signIn) { try { const answer = await opts.auth.actorToken(signIn.project_id, signIn.access_token); actor = { for: signIn.access_token, token: answer.actor_token, expiresAtMs: now() + (answer.expires_in ?? 60) * 1000 }; return answer.actor_token; } catch { return null; } } function actorTokenFor(signIn) { if (actor && actor.for === signIn.access_token && actor.expiresAtMs - now() > ACTOR_TOKEN_AHEAD_MS) { return Promise.resolve(actor.token); } if (!asking || asking.for !== signIn.access_token) { const promise = ask(signIn).finally(() => { if (asking?.promise === promise) asking = null; }); asking = { for: signIn.access_token, promise }; } return asking.promise; } return { async current() { const stored = readDevSignIn(opts.path); if (!stored) return null; let signIn = stored; if (!fresh(stored)) { refreshing ??= refresh().finally(() => { refreshing = null; }); signIn = await refreshing; } if (!signIn) return null; const actorToken = await actorTokenFor(signIn); if (!actorToken) { return { unavailable: `the gateway gave no data-plane token for ${signIn.user.email} (POST /auth/v1/actor-token)` }; } return { signIn, actorToken }; }, }; } /** * The dev server's door: the session file as a self-refreshing source, with a * client built from the file's own API base and the project's anon key (the * only credential a user's own auth routes take). */ export function openDevSession(opts) { let source = null; return { async current() { if (!source) { const stored = readDevSignIn(opts.path); if (!stored) return null; const { Run402 } = await import("../index.js"); const keys = { anon_key: opts.anonKey, service_key: opts.serviceKey ?? "" }; const client = new Run402({ apiBase: stored.api_base, credentials: { getAuth: async () => null, getProjectCredentials: async () => keys, }, }); source = createDevSessionSource({ path: opts.path, auth: client.auth }); } return source.current(); }, }; } //# sourceMappingURL=dev-session.js.map