diff --git a/README.md b/README.md index c96a89d..d222305 100644 --- a/README.md +++ b/README.md @@ -189,8 +189,8 @@ machine you are signing in, so it works over SSH, in containers and on servers without a browser. `npx toolstile auth login` runs only the sign-in, the same way. Setup also signs -in again when the saved sign-in has expired, or when `--server` names a -different Toolstile address than the one this machine is signed in to. +in again when the saved sign-in has expired, or when it targets a server this +machine is not signed in to yet. `mcp setup` lists the agents it finds (Claude Code, Claude Desktop, Cursor, Codex, VS Code, Windsurf, Devin Desktop, Gemini CLI, Cline, Grok Build, OpenCode, @@ -223,17 +223,61 @@ folder: `$TOOLSTILE_CONFIG_DIR` when set, otherwise `%APPDATA%\toolstile` on Windows and `$XDG_CONFIG_HOME/toolstile` (default `~/.config/toolstile`) elsewhere. -`npx toolstile auth logout` ends the CLI's sign-in. Agents you enabled keep -working until you turn them off with `mcp setup` or delete the device in the -dashboard. +`npx toolstile auth logout` ends the CLI's sign-in to the current server. Agents +you enabled keep working until you turn them off with `mcp setup` or delete the +device in the dashboard. + +### Cloud, self-hosted or local + +The `auth` and `mcp` commands work with three kinds of Toolstile server: + +| Server | How to pick it | +| --- | --- | +| Toolstile Cloud, `https://app.toolstile.com` | The default | +| A self-hosted server | `--server https://toolstile.example.com` | +| The self-hosted server on this machine | `--local` | + +`--local` uses the `origin` from the server's `instance.json`, in +`$TOOLSTILE_DATA_DIR` (default `~/.local/share/toolstile`), or +`http://127.0.0.1:4310` when there is none. The CLI reads only that field; the +file's keys are never printed or copied. Plain `http://` works only for +`localhost`, `127.0.0.0/8` and `[::1]`; every other server must use `https://`. + +The CLI keeps one sign-in per server. The last server you signed in to is the +current one. Each command uses `--server` or `--local` when given, then the +`TOOLSTILE_SERVER` environment variable (`TOOLSTILE_URL` also works), then the +current server. + +```sh +npx toolstile auth login --local # sign in to the server on this machine +npx toolstile mcp setup --enable codex # set up Codex there, the current server now +npx toolstile auth status # every saved sign-in; * marks the current one +npx toolstile whoami --server https://app.toolstile.com +npx toolstile auth logout --all # sign out everywhere +``` + +A self-hosted server has no workspaces, so setup does not ask for one and +`--workspace` is refused. Each agent uses one server, and agents on one machine +can use different servers: setup on one server leaves agents that use another +alone. Turning on an agent that uses another server moves it, so setup asks +first; without a terminal, add `--switch`. Its access on the old server is +removed when this machine is still signed in there. + +An agent's token is only ever sent to the server that issued it. `mcp proxy` +ignores `--server`, `--local` and `TOOLSTILE_SERVER`, and never follows a +redirect. | Option | Command | Meaning | | --- | --- | --- | -| `--server ` | `auth login`, `mcp setup` | Toolstile address (default `https://app.toolstile.com`, or `TOOLSTILE_URL`) | +| `--server ` | `auth login`, `auth logout`, `whoami`, `mcp setup` | Use this server (default: `TOOLSTILE_SERVER`, else the current one) | +| `--local` | `auth login`, `auth logout`, `whoami`, `mcp setup` | Use the self-hosted server on this machine | +| `--all` | `auth logout` | Sign out of every server | +| `--json` | `auth status`, `whoami` | Print JSON | | `--no-browser` | `auth login`, `mcp setup` | Do not try to open a browser on this machine | | `--enable ` | `mcp setup` | Turn these on without prompting (comma-separated) | | `--disable ` | `mcp setup` | Turn these off without prompting | -| `--workspace ` | `mcp setup` | Workspace the agents use (default: the last one, or personal) | +| `--switch` | `mcp setup` | Move agents that use another server to this one without asking | +| `--workspace ` | `mcp setup` | Toolstile Cloud workspace the agents use (default: the last one, or personal) | | `--device-name ` | `mcp setup` | Name for this machine in the dashboard (default: its hostname) | ## Use it from code diff --git a/src/api.ts b/src/api.ts index 2303c62..037a10f 100644 --- a/src/api.ts +++ b/src/api.ts @@ -23,6 +23,9 @@ export interface Account { email: string; name: string; expiresAt: string; + /** Which kind of server this is. Servers from before this field are Toolstile Cloud. */ + edition?: "cloud" | "self-hosted"; + /** Toolstile Cloud workspaces; a self-hosted server returns none. */ workspaces: Workspace[]; /** The device named when this sign-in was approved. */ device?: { id: string; label: string } | null; @@ -75,7 +78,16 @@ async function request(fetcher: Fetch, url: string, init: RequestInit = {}): }); } -/** The Toolstile endpoints the CLI uses. Session calls carry the device-flow session token. */ +/** Query parameters, leaving out the ones that are not set. */ +function query(params: Record): string { + const defined = Object.entries(params).filter((entry): entry is [string, string] => entry[1] !== undefined); + return defined.length ? `?${new URLSearchParams(defined)}` : ""; +} + +/** + * The Toolstile endpoints the CLI uses. Session calls carry the device-flow session token. + * `workspaceId` is for Toolstile Cloud; requests to a self-hosted server leave it out. + */ export function createApi(server: string, fetcher: Fetch = fetch) { const base = server.replace(/\/+$/, ""); const session = (token: string, init: RequestInit = {}): RequestInit => ({ @@ -99,28 +111,28 @@ export function createApi(server: string, fetcher: Fetch = fetch) { }), account: (token: string) => request(fetcher, `${base}/api/cli/account`, session(token)), signOut: (token: string) => request(fetcher, `${base}/api/cli/sign-out`, session(token, { method: "POST" })), - device: (token: string, input: { workspaceId: string; id?: string; label: string; rename?: boolean }) => + device: (token: string, input: { workspaceId?: string; id?: string; label: string; rename?: boolean }) => request<{ id: string; label: string }>( fetcher, `${base}/api/cli/device`, session(token, { method: "POST", body: JSON.stringify(input) }), ), - agents: (token: string, workspaceId: string, deviceId: string) => + agents: (token: string, workspaceId: string | undefined, deviceId: string) => request<{ agents: { id: string; label: string }[] }>( fetcher, - `${base}/api/cli/agents?${new URLSearchParams({ workspaceId, deviceId })}`, + `${base}/api/cli/agents${query({ workspaceId, deviceId })}`, session(token), ), - addAgent: (token: string, input: { workspaceId: string; deviceId: string; label: string }) => + addAgent: (token: string, input: { workspaceId?: string; deviceId: string; label: string }) => request<{ id: string; label: string; token: string }>( fetcher, `${base}/api/cli/agents`, session(token, { method: "POST", body: JSON.stringify(input) }), ), - removeAgent: (token: string, workspaceId: string, id: string) => + removeAgent: (token: string, workspaceId: string | undefined, id: string) => request( fetcher, - `${base}/api/cli/agents/${encodeURIComponent(id)}?${new URLSearchParams({ workspaceId })}`, + `${base}/api/cli/agents/${encodeURIComponent(id)}${query({ workspaceId })}`, session(token, { method: "DELETE" }), ), }; diff --git a/src/cli.ts b/src/cli.ts index b786029..bae361e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4,7 +4,7 @@ import { homedir } from "node:os"; import { resolve } from "node:path"; import { createApi } from "./api.js"; import { renderCard, shareText, shareUrl } from "./card.js"; -import { type Context, login, logout, proxy, setup, UserError } from "./commands.js"; +import { type Context, login, logout, proxy, setup, status, UserError, whoami } from "./commands.js"; import { runFix } from "./fix.js"; import { audit } from "./index.js"; import { redact, renderJson, renderReport, style } from "./report.js"; @@ -17,8 +17,13 @@ Usage npx toolstile audit --fix Review suggested fixes and apply the ones you pick npx toolstile auth login Sign in, from any machine, with a code npx toolstile auth logout Sign out on this machine + npx toolstile auth status List the servers this machine is signed in to + npx toolstile whoami Show the account on the current server npx toolstile mcp setup Choose which agents here use Toolstile +The auth, whoami and mcp commands work with Toolstile Cloud (the default), a +self-hosted server (--server ) or the server on this machine (--local). + Run toolstile --help for a command's options. -h, --help Show this help -v, --version Show the version @@ -64,16 +69,37 @@ Options const AUTH_HELP = `toolstile auth: sign the CLI in to Toolstile Usage - npx toolstile auth login [--server ] [--no-browser] - npx toolstile auth logout + npx toolstile auth login [--server | --local] [--no-browser] + npx toolstile auth logout [--server | --local | --all] + npx toolstile auth status [--json] + npx toolstile whoami [--server | --local] [--json] login prints a link and a code. Open the link on any device with a browser (your laptop, your phone), sign in and approve the code. Nothing has to reach this machine, so it works over SSH and on servers without a browser. +The CLI keeps one sign-in per server. The last server you signed in to is the +current one; commands use it unless --server, --local or TOOLSTILE_SERVER +picks another. logout signs out of the current server, status lists every +saved sign-in and whoami shows the account on the current server. + +Servers + Toolstile Cloud https://app.toolstile.com (the default) + Self-hosted --server https://toolstile.example.com + On this machine --local: the origin in instance.json in + TOOLSTILE_DATA_DIR (default ~/.local/share/toolstile), + else http://127.0.0.1:4310 + Plain http:// works only for localhost, 127.0.0.0/8 and [::1]. + Options - --server Toolstile address (default https://app.toolstile.com, or TOOLSTILE_URL) - --no-browser Do not try to open a browser on this machine + --server Use this Toolstile server + --local Use the self-hosted server on this machine + --no-browser login: do not try to open a browser on this machine + --all logout: sign out of every server + --json status, whoami: print JSON + +Environment + TOOLSTILE_SERVER Server to use when no flag picks one (TOOLSTILE_URL also works) `; const MCP_HELP = `toolstile mcp: connect the agents on this machine to Toolstile @@ -84,7 +110,8 @@ Usage setup lists the agents found here and lets you turn each one on or off. It signs in first, the same way as auth login, when this machine is not -signed in to the server yet. Each enabled agent gets its own access, shown +signed in to the server yet. Each agent uses one server; agents on this +machine can use different servers. Each enabled agent gets its own access, shown under this device in the Toolstile dashboard. Its config runs \`toolstile mcp proxy\`, which holds the agent's token in the CLI's own owner-only credentials file, so no secret is written into the agent's config. @@ -92,13 +119,19 @@ owner-only credentials file, so no secret is written into the agent's config. Options for setup --enable Turn these on without prompting (comma-separated) --disable Turn these off without prompting - --workspace Workspace the agents use (default: the last one, or personal) + --workspace Toolstile Cloud workspace the agents use (default: the + last one, or personal); self-hosted servers have none --device-name Name for this machine (default: its hostname) - --server Toolstile address (default https://app.toolstile.com, or - TOOLSTILE_URL); signs in again if this machine is signed - in to another one + --server Use this server (default: the current one, or + TOOLSTILE_SERVER); signs in if needed + --local Use the self-hosted server on this machine + --switch Move agents that use another server to this one + without asking (needed without a terminal) --no-browser Do not try to open a browser when signing in +proxy always talks to the server that issued the agent's token; --server, +--local and TOOLSTILE_SERVER do not change it. + Agents: claude-code, claude-desktop, cursor, codex, vscode, windsurf, devin, gemini, cline, grok, opencode, kiro, antigravity `; @@ -228,7 +261,7 @@ function parseFlags(argv: string[], valued: string[], booleans: string[]) { async function command(argv: string[]): Promise { const [group, action, ...rest] = argv; const help = group === "auth" ? AUTH_HELP : MCP_HELP; - const actions = group === "auth" ? ["login", "logout"] : ["setup", "proxy"]; + const actions = group === "auth" ? ["login", "logout", "status", "whoami"] : ["setup", "proxy"]; if (!action || action === "-h" || action === "--help" || action === "help") { process.stdout.write(help); return action ? 0 : 2; @@ -253,27 +286,35 @@ async function command(argv: string[]): Promise { try { const flags = action === "login" - ? parseFlags(rest, ["server"], ["no-browser"]) + ? parseFlags(rest, ["server"], ["local", "no-browser"]) : action === "logout" - ? parseFlags(rest, [], []) - : action === "setup" - ? parseFlags(rest, ["enable", "disable", "workspace", "device-name", "server"], ["no-browser"]) - : parseFlags(rest, ["agent"], []); + ? parseFlags(rest, ["server"], ["local", "all"]) + : action === "status" + ? parseFlags(rest, [], ["json"]) + : action === "whoami" + ? parseFlags(rest, ["server"], ["local", "json"]) + : action === "setup" + ? parseFlags(rest, ["enable", "disable", "workspace", "device-name", "server"], ["no-browser", "local", "switch"]) + : parseFlags(rest, ["agent"], []); if (flags === "help") { process.stdout.write(help); return 0; } const value = (name: string) => (typeof flags[name] === "string" ? (flags[name] as string) : undefined); - if (action === "login") return await login(ctx, { server: value("server"), browser: !flags["no-browser"] }); - if (action === "logout") return await logout(ctx); + const target = { server: value("server"), local: flags.local === true }; + if (action === "login") return await login(ctx, { ...target, browser: !flags["no-browser"] }); + if (action === "logout") return await logout(ctx, { ...target, all: flags.all === true }); + if (action === "status") return status(ctx, { json: flags.json === true }); + if (action === "whoami") return whoami(ctx, { ...target, json: flags.json === true }); if (action === "setup") return await setup(ctx, { enable: value("enable"), disable: value("disable"), workspace: value("workspace"), deviceName: value("device-name"), - server: value("server"), + ...target, browser: !flags["no-browser"], + switch: flags.switch === true, }); return await proxy(ctx, value("agent")); } catch (error) { @@ -287,6 +328,7 @@ async function command(argv: string[]): Promise { async function main(): Promise { const argv = process.argv.slice(2); + if (argv[0] === "whoami") return command(["auth", ...argv]); if (argv[0] === "auth" || argv[0] === "mcp") return command(argv); const help = argv[0] === "audit" ? AUDIT_HELP : HELP; let args: ReturnType; diff --git a/src/commands.ts b/src/commands.ts index eddebbf..f73fc00 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -4,13 +4,28 @@ import type { Readable, Writable } from "node:stream"; import type { ReadStream, WriteStream } from "node:tty"; import { ManualEditError, proxyCommand, readEntry, isProxyEntry, targets, type Target, writeEntry } from "./agents.js"; import { type Account, type Api, ApiError, type Workspace } from "./api.js"; +import { UserError } from "./errors.js"; import { checklist } from "./prompt.js"; import { runProxy } from "./proxy.js"; import { type Style, tildify } from "./report.js"; +import { chooseServer, DEFAULT_SERVER, normalizeServer, secureScheme, type ServerChoice, serverFromEnv } from "./servers.js"; import { CLIENT_NAMES } from "./sources.js"; -import { type AgentLink, loadState, saveState, withCurrentState, type State, type StateEnv } from "./state.js"; +import { + type AgentLink, + type Edition, + loadState, + saveState, + serverEntry, + type ServerState, + withCurrentState, + type State, + type StateEnv, +} from "./state.js"; import type { ClientId } from "./types.js"; +export { normalizeServer, UserError }; +export type { ServerChoice }; + export interface Context { home: string; platform: NodeJS.Platform; @@ -24,15 +39,41 @@ export interface Context { sleep?: (ms: number) => Promise; hostname?: () => string; openBrowser?: (url: string) => void; + /** The proxy's HTTP client; tests replace it. */ + fetch?: typeof fetch; + now?: () => number; } -/** A failure explained to the user; exits 1 without a stack trace. */ -export class UserError extends Error {} - const stateEnv = (ctx: Context): StateEnv => ({ home: ctx.home, env: ctx.env, platform: ctx.platform }); const print = (ctx: Context, text = "") => ctx.stdout.write(`${text}\n`); const interactive = (ctx: Context) => ctx.stdin.isTTY === true && ctx.stdout.isTTY === true; +/** The server a command uses: `--server` or `--local`, then `TOOLSTILE_SERVER`, then the current one. */ +const serverFor = (ctx: Context, state: State, choice: ServerChoice = {}) => + chooseServer({ home: ctx.home, env: ctx.env, current: state.current }, choice); + +/** Servers from before `edition` existed are Toolstile Cloud. */ +const editionOf = (account: Account): Edition => (account.edition === "self-hosted" ? "self-hosted" : "cloud"); + +/** + * Quotes an origin for the user's shell, or returns undefined when it cannot be quoted safely. + * Windows shells only get double-quoted origins whose extra characters are IPv6 brackets. + */ +const quoteOrigin = (server: string, platform: NodeJS.Platform) => { + if (/^[\w:/.-]+$/.test(server)) return server; + if (platform !== "win32") return `'${server.replaceAll("'", "'\\''")}'`; + return /^[\w:/.[\]-]+$/.test(server) ? `"${server}"` : undefined; +}; + +/** The `auth login` command that signs in to `server`; plain `auth login` uses `bare`, the server it would pick. */ +const loginCommand = (ctx: Context, server: string, bare?: string) => { + if (server === bare) return "toolstile auth login"; + const quoted = quoteOrigin(server, ctx.platform); + return quoted + ? `toolstile auth login --server ${quoted}` + : `toolstile auth login --server
, with ${server} as the address`; +}; + /** A failed local save must not silently abandon a newly issued remote credential. */ async function compensate(error: unknown, cleanup: () => Promise, remedy: string): Promise { try { await cleanup(); } @@ -43,23 +84,6 @@ async function compensate(error: unknown, cleanup: () => Promise, remedy: throw error; } -const LOOPBACK = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\])$/; - -/** HTTPS, or HTTP to a loopback host for local development. */ -const secureScheme = (url: URL) => url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.test(url.hostname)); - -/** HTTPS, except a loopback server for local development. */ -export function normalizeServer(value: string): string { - let url: URL; - try { - url = new URL(value); - } catch { - throw new UserError(`--server must be a URL, for example https://app.toolstile.com`); - } - if (!secureScheme(url)) throw new UserError("--server must use https://"); - return url.origin; -} - /** A gateway URL the server reported: HTTPS (or loopback HTTP) with no credentials, else undefined. */ export function gatewayUrl(value: unknown): string | undefined { if (typeof value !== "string") return undefined; @@ -77,6 +101,7 @@ export function gatewayUrl(value: unknown): string | undefined { /** * A sign-in page link the server sent, if it is safe to show and open: a URL on the server's * own origin (so HTTPS, or HTTP for a loopback server) with no credentials, else undefined. + * Toolstile Cloud and self-hosted servers use different paths, so only the origin is checked. */ export function signInUrl(value: unknown, server: string): URL | undefined { if (typeof value !== "string") return undefined; @@ -117,9 +142,6 @@ const machineName = (ctx: Context) => (ctx.hostname ?? hostname)().replace(/\.lo const formatCode = (code: string) => (code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code); -/** The server a new sign-in goes to: --server, else TOOLSTILE_URL, else the last one used. */ -const signInServer = (ctx: Context, state: State, server?: string) => - normalizeServer(server ?? ctx.env.TOOLSTILE_URL ?? state.server); interface SignInOptions { browser: boolean; @@ -130,8 +152,9 @@ interface SignInOptions { } /** - * The device-code sign-in shared by `auth login` and `mcp setup`. Saves the new session into - * `state` and only then signs the previous session out. + * The device-code sign-in shared by `auth login` and `mcp setup`. Saves the new session as + * `server`'s sign-in, makes `server` the current one, and only then signs out the session it + * replaced on that server. Sign-ins to other servers are kept. */ async function signIn(ctx: Context, state: State, server: string, options: SignInOptions): Promise { const s = ctx.style; @@ -152,7 +175,7 @@ async function signIn(ctx: Context, state: State, server: string, options: SignI } else { // Never show or open a link that points anywhere but the server being signed in to. const page = signInUrl(code.verification_uri, server); - if (!page) throw new UserError(`${server} sent a sign-in link for a different address. Check --server and TOOLSTILE_URL.`); + if (!page) throw new UserError(`${server} sent a sign-in link for a different address. Check --server and TOOLSTILE_SERVER.`); ctx.stderr.write(`The sign-in link from ${server} was not valid, so no browser was opened.\n`); print(ctx, `Open this page on any device with a browser, enter the code and approve the sign-in:`); print(ctx); @@ -184,64 +207,85 @@ async function signIn(ctx: Context, state: State, server: string, options: SignI throw error; } } - const previous = state.session; - const previousServer = previous?.server ?? state.server; + const entry = serverEntry(state, server); + const previous = entry.session; let account: Account; try { account = await api.account(token); - if (server !== state.server || (previous && previous.email !== account.email)) { + if (previous && previous.email !== account.email) { // Another account's workspace and device do not apply; agents keep their own access. - delete state.workspace; - delete state.device; + delete entry.workspace; + delete entry.device; } - state.server = server; - state.session = { token, email: account.email, expiresAt: account.expiresAt, server }; - if (account.device) state.device = account.device; + entry.edition = editionOf(account); + if (entry.edition === "self-hosted") delete entry.workspace; + entry.session = { token, email: account.email, expiresAt: account.expiresAt }; + if (account.device) entry.device = account.device; + state.current = server; saveState(state, stateEnv(ctx)); } catch (error) { return compensate(error, async () => { // Only discard this sign-in, never the session a concurrent command saved. - const winner = loadState(stateEnv(ctx)).session; - if (winner?.token !== token || winner.server !== server) await api.signOut(token); + const winner = loadState(stateEnv(ctx)).servers[server]?.session; + if (winner?.token !== token) await api.signOut(token); }, "Sign-in cleanup failed. Remove this new CLI session in the Toolstile dashboard."); } - // End the previous session only after the replacement was safely saved. - if (previous && (previous.token !== token || previousServer !== server)) - await ctx.api(previousServer).signOut(previous.token).catch(() => undefined); + // End the session this one replaced only after the replacement was safely saved. + if (previous && previous.token !== token) await api.signOut(previous.token).catch(() => undefined); const deviceLabel = account.device?.label; print(ctx); print( ctx, - `Signed in as ${s.bold(state.session!.email)}${deviceLabel ? ` on ${s.bold(deviceLabel)}` : ""}.${options.next ? "" : ` Next: ${s.bold("toolstile mcp setup")}`}`, + `Signed in as ${s.bold(account.email)}${deviceLabel ? ` on ${s.bold(deviceLabel)}` : ""}.${options.next ? "" : ` Next: ${s.bold("toolstile mcp setup")}`}`, ); return account; } -export async function login(ctx: Context, options: { server?: string; browser: boolean }): Promise { +export async function login(ctx: Context, options: ServerChoice & { browser: boolean }): Promise { const state = loadState(stateEnv(ctx)); - await signIn(ctx, state, signInServer(ctx, state, options.server), { browser: options.browser }); + await signIn(ctx, state, serverFor(ctx, state, options), { browser: options.browser }); return 0; } -export async function logout(ctx: Context): Promise { +export interface LogoutOptions extends ServerChoice { + /** Sign out of every saved server. */ + all?: boolean; +} + +/** Signs out of one server (the current one by default), or of all of them with `all`. */ +export async function logout(ctx: Context, options: LogoutOptions = {}): Promise { + if (options.all && (options.server !== undefined || options.local)) + throw new UserError("--all signs out of every server; leave out --server and --local."); const state = loadState(stateEnv(ctx)); - if (!state.session) { - print(ctx, "Not signed in."); + const chosen = options.all ? Object.keys(state.servers) : [serverFor(ctx, state, options)]; + const ended = chosen.flatMap((server) => { + const session = state.servers[server]?.session; + return session ? [{ server, session }] : []; + }); + if (!ended.length) { + print(ctx, options.all ? "Not signed in." : `Not signed in to ${chosen[0]}.`); return 0; } - const session = state.session; - delete state.session; + for (const { server } of ended) delete state.servers[server]!.session; saveState(state, stateEnv(ctx)); - let reached = true; - await ctx - .api(session.server ?? state.server) - .signOut(session.token) - .catch((error: unknown) => { - // 401 means the session had already ended; anything else is worth saying. - if (!(error instanceof ApiError && error.status === 401)) reached = false; - }); - print(ctx, reached ? "Signed out." : "Signed out on this machine. Toolstile could not be reached, so the session ends when it expires."); - const enabled = Object.keys(state.agents).length; + for (const { server, session } of ended) { + let reached = true; + await ctx + .api(server) + .signOut(session.token) + .catch((error: unknown) => { + // 401 means the session had already ended; anything else is worth saying. + if (!(error instanceof ApiError && error.status === 401)) reached = false; + }); + print( + ctx, + reached + ? `Signed out of ${server}.` + : `Signed out of ${server} on this machine. The server could not be reached, so the session ends when it expires.`, + ); + } + const servers = new Set(ended.map((e) => e.server)); + const enabled = Object.values(state.agents).filter((link) => link && servers.has(link.server)).length; if (enabled) print( ctx, @@ -252,6 +296,83 @@ export async function logout(ctx: Context): Promise { return 0; } +export interface SignInSummary { + server: string; + edition: Edition; + email: string; + expiresAt: string; + expired: boolean; + current: boolean; +} + +function summary(ctx: Context, state: State, server: string, current: string): SignInSummary | undefined { + const entry = state.servers[server]; + const session = entry?.session; + if (!session) return undefined; + const expires = Date.parse(session.expiresAt); + return { + server, + edition: entry.edition ?? "cloud", + email: session.email, + expiresAt: session.expiresAt, + expired: Number.isFinite(expires) && expires <= (ctx.now ?? Date.now)(), + current: server === current, + }; +} + +const signInLine = (signIn: SignInSummary) => + `${signIn.email} on ${signIn.server} (${signIn.edition}), ${signIn.expired ? "expired" : "expires"} ${signIn.expiresAt}`; + +/** Lists the saved sign-ins from the credentials file; contacts no server. */ +export function status(ctx: Context, options: { json?: boolean } = {}): number { + const state = loadState(stateEnv(ctx)); + const current = serverFor(ctx, state); + const signIns = Object.keys(state.servers).flatMap((server) => summary(ctx, state, server, current) ?? []); + if (options.json) { + print(ctx, JSON.stringify({ current, signIns }, null, 2)); + return 0; + } + const fromEnv = serverFromEnv(ctx.env); + const source = fromEnv ? ` (from ${fromEnv.name})` : ""; + if (!signIns.length) { + print(ctx, `Not signed in. Current server: ${current}${source}`); + print(ctx, `Sign in with ${loginCommand(ctx, current, current)}`); + return 0; + } + for (const signIn of signIns) print(ctx, `${signIn.current ? "*" : " "} ${signInLine(signIn)}`); + print(ctx); + print( + ctx, + signIns.some((signIn) => signIn.current) + ? ctx.style.dim(`* current server${source}`) + : `Current server: ${current}${source}, not signed in. Sign in with ${loginCommand(ctx, current, current)}`, + ); + return 0; +} + +/** Prints the sign-in for the chosen server; exits 1 when there is none or it has expired. */ +export function whoami(ctx: Context, options: ServerChoice & { json?: boolean } = {}): number { + const state = loadState(stateEnv(ctx)); + const server = serverFor(ctx, state, options); + const signIn = summary(ctx, state, server, server); + /** The server plain `auth login` would pick; undefined when TOOLSTILE_SERVER is invalid. */ + const bare = () => { + try { return serverFor(ctx, state); } + catch { return undefined; } + }; + if (options.json) { + const body = signIn + ? { signedIn: !signIn.expired, server, edition: signIn.edition, email: signIn.email, expiresAt: signIn.expiresAt, expired: signIn.expired } + : { signedIn: false, server }; + print(ctx, JSON.stringify(body, null, 2)); + } else if (!signIn) print(ctx, `Not signed in to ${server}. Sign in with ${loginCommand(ctx, server, bare())}`); + else { + print(ctx, signInLine(signIn)); + if (signIn.expired) print(ctx, `Sign in again with ${loginCommand(ctx, server, bare())}`); + } + return signIn && !signIn.expired ? 0 : 1; +} + function parseClients(list: string | undefined, flag: string): ClientId[] { if (!list) return []; const ids = Object.keys(CLIENT_NAMES) as ClientId[]; @@ -263,29 +384,32 @@ function parseClients(list: string | undefined, flag: string): ClientId[] { }); } -export interface SetupOptions { +export interface SetupOptions extends ServerChoice { enable?: string; disable?: string; workspace?: string; deviceName?: string; - /** Sign in to this server first unless the saved session is already for it. */ - server?: string; /** Whether a sign-in started here may open a browser (default true). */ browser?: boolean; + /** Move agents linked to another server to this one without asking. */ + switch?: boolean; } /** "A", "A and B", "A, B and C". */ const listNames = (names: string[]) => names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : (names[0] ?? ""); -async function chooseWorkspace(ctx: Context, state: State, workspaces: Workspace[], wanted?: string) { +const workspaceOnSelfHosted = (server: string) => + `--workspace only applies to Toolstile Cloud; ${server} is a self-hosted server and has no workspaces.`; + +async function chooseWorkspace(ctx: Context, saved: ServerState, workspaces: Workspace[], wanted?: string) { if (wanted) { const value = wanted.toLowerCase(); const match = workspaces.find((w) => w.slug === value || w.id === wanted || w.name.toLowerCase() === value); if (!match) throw new UserError(`No workspace "${wanted}". Yours: ${workspaces.map((w) => w.slug).join(", ")}.`); return match; } - const current = workspaces.find((w) => w.id === state.workspace?.id) ?? workspaces.find((w) => w.personal) ?? workspaces[0]; + const current = workspaces.find((w) => w.id === saved.workspace?.id) ?? workspaces.find((w) => w.personal) ?? workspaces[0]; if (!current) throw new UserError("Your account has no workspace yet. Open Toolstile in a browser once, then try again."); if (workspaces.length === 1 || !interactive(ctx)) return current; const picked = await checklist( @@ -299,6 +423,21 @@ async function chooseWorkspace(ctx: Context, state: State, workspaces: Workspace return workspaces[picked.indexOf(true)]!; } +/** Asks before an agent linked to another server moves to this one. */ +async function confirmSwitch(ctx: Context, name: string, from: string, to: string): Promise { + const picked = await checklist( + `${name} uses ${from}. Switch it to ${to}?`, + [ + { label: `Keep it on ${from}`, checked: true }, + { label: `Switch it to ${to}`, checked: false }, + ], + ctx.stdin as unknown as ReadStream, + ctx.stdout as unknown as WriteStream, + { single: true }, + ); + return picked?.[1] === true; +} + export async function setup(ctx: Context, options: SetupOptions): Promise { const s = ctx.style; // Check the flags before any sign-in, so a typo does not cost a trip to the browser. @@ -306,49 +445,64 @@ export async function setup(ctx: Context, options: SetupOptions): Promise disable.includes(c)); if (both) throw new UserError(`${CLIENT_NAMES[both]} is in both --enable and --disable.`); - const requested = options.server === undefined ? undefined : normalizeServer(options.server); const state = loadState(stateEnv(ctx)); - let reused: Api | undefined; + const server = serverFor(ctx, state, options); + const entry = serverEntry(state, server); + if (options.workspace !== undefined && entry.edition === "self-hosted") throw new UserError(workspaceOnSelfHosted(server)); + /** The link of an agent that uses another server, if it does. */ + const elsewhere = (client: ClientId) => { + const link = state.agents[client]; + return link && link.server !== server ? link : undefined; + }; + if (!options.switch && !interactive(ctx)) { + const moving = enable.filter((c) => elsewhere(c)); + if (moving.length) + throw new UserError( + `${moving.map((c) => `${CLIENT_NAMES[c]} uses ${elsewhere(c)!.server}`).join("; ")}. Add --switch to move ${moving.length === 1 ? "it" : "them"} to ${server}.`, + ); + } + let account: Account | undefined; - const saved = state.session; - const savedServer = saved ? (saved.server ?? state.server) : undefined; - // Only an explicit --server moves a saved session elsewhere; TOOLSTILE_URL picks the - // server for a new sign-in, as it does for auth login. - if (saved && savedServer && (!requested || requested === savedServer)) { - const candidate = ctx.api(savedServer); + const saved = entry.session; + if (saved) { // 401: the saved session has expired, so sign in again below. - account = await candidate.account(saved.token).catch((error: unknown) => { + account = await ctx.api(server).account(saved.token).catch((error: unknown) => { if (error instanceof ApiError && error.status === 401) return undefined; throw error; }); - if (account) reused = candidate; - } - if (!account) { - account = await signIn(ctx, state, signInServer(ctx, state, requested), { - browser: options.browser ?? true, - next: "setup", - deviceName: options.deviceName, - }); } - const session = state.session!; - const api = reused ?? ctx.api(session.server); + account ??= await signIn(ctx, state, server, { + browser: options.browser ?? true, + next: "setup", + deviceName: options.deviceName, + }); + const session = entry.session!; + const api = ctx.api(server); + const edition = editionOf(account); + if (edition === "self-hosted" && options.workspace !== undefined) throw new UserError(workspaceOnSelfHosted(server)); - // The gateway can be on another host; only an HTTPS URL from this server is used. - const endpoint = gatewayUrl(account.mcpUrl) ?? `${state.server}/mcp`; - const workspace = await chooseWorkspace(ctx, state, account.workspaces, options.workspace); - state.workspace = { id: workspace.id, slug: workspace.slug, name: workspace.name }; + // Toolstile Cloud's gateway is on its own host; a self-hosted gateway must share the server's origin. + const reported = gatewayUrl(account.mcpUrl); + const endpoint = + reported && (edition === "cloud" || new URL(reported).origin === server) ? reported : `${server}/mcp`; + // Toolstile Cloud keeps agents in a workspace; a self-hosted server has none. + const workspace = edition === "cloud" ? await chooseWorkspace(ctx, entry, account.workspaces, options.workspace) : undefined; + const workspaceId = workspace?.id; + entry.edition = edition; + if (workspace) entry.workspace = { id: workspace.id, slug: workspace.slug, name: workspace.name }; + else delete entry.workspace; saveState(state, stateEnv(ctx)); /** Created (or renamed) only when something needs it, so listing changes nothing. */ let device: { id: string; label: string } | undefined; const ensureDevice = async () => { device ??= await api.device(session.token, { - workspaceId: workspace.id, - id: state.device?.id, - label: options.deviceName ?? state.device?.label ?? machineName(ctx), + workspaceId, + id: entry.device?.id, + label: options.deviceName ?? entry.device?.label ?? machineName(ctx), rename: options.deviceName !== undefined, }); - state.device = device; + entry.device = device; saveState(state, stateEnv(ctx)); return device; }; @@ -356,26 +510,39 @@ export async function setup(ctx: Context, options: SetupOptions): Promise a.id) : [], + entry.device ? (await api.agents(session.token, workspaceId, entry.device.id)).agents.map((a) => a.id) : [], ); const live = (client: ClientId) => { const link = state.agents[client]; - return !!link && link.server === state.server && link.workspaceId === workspace.id && remote.has(link.id); + return !!link && link.server === server && link.workspaceId === workspaceId && remote.has(link.id); + }; + /** Servers where an old authorization could not be removed, because this machine is not signed in there. */ + const leftBehind: { name: string; server: string }[] = []; + /** + * Removes an agent's authorization on the server that issued it, using that server's sign-in. + * A 403 means this account lost access to its workspace, which revokes it; a switch, where the + * sign-in there may be another account, treats it as unconfirmed instead (`strict`). + */ + const removeRemote = async (link: AgentLink, name: string, strict = false) => { + const token = link.server === server ? session.token : state.servers[link.server]?.session?.token; + if (!token) { + leftBehind.push({ name, server: link.server }); + return; + } + await (link.server === server ? api : ctx.api(link.server)) + .removeAgent(token, link.workspaceId, link.id) + .catch((error: unknown) => { + if (!(error instanceof ApiError && (error.status === 404 || (error.status === 403 && !strict)))) throw error; + }); }; - /** Removes an agent where it was created; links from another server are just dropped. */ - const removeRemote = (link: AgentLink) => - link.server === state.server - ? api.removeAgent(session.token, link.workspaceId, link.id).catch((error: unknown) => { - if (!(error instanceof ApiError && (error.status === 404 || error.status === 403))) throw error; - }) - : Promise.resolve(); - const deviceLabel = state.device?.label ?? machineName(ctx); + const deviceLabel = entry.device?.label ?? machineName(ctx); const all = targets(ctx); const shown = all.filter((t) => t.detected || live(t.client) || state.agents[t.client] || enable.includes(t.client)); if (!shown.length) { print(ctx, "No supported agents found on this machine. Supported: " + all.map((t) => t.name).join(", ") + "."); return 0; } + const where = `${workspace ? ` · workspace ${s.bold(workspace.name)}` : ""} · device ${s.bold(deviceLabel)}`; let wanted: Set; if (enable.length || disable.length) { @@ -383,12 +550,14 @@ export async function setup(ctx: Context, options: SetupOptions): Promise ({ label: t.name, - hint: t.detected ? tildify(t.path, ctx.home) : "not found on this machine", + hint: elsewhere(t.client) + ? `uses ${elsewhere(t.client)!.server}` + : t.detected ? tildify(t.path, ctx.home) : "not found on this machine", checked: live(t.client), })), ctx.stdin as unknown as ReadStream, @@ -400,12 +569,21 @@ export async function setup(ctx: Context, options: SetupOptions): Promise picked[i]).map((t) => t.client)); } else { - print(ctx, `Workspace ${workspace.name} · device ${deviceLabel}`); - for (const t of shown) print(ctx, ` ${live(t.client) ? "enabled " : "disabled"} ${t.client.padEnd(14)} ${t.name}`); + print(ctx, `${server}${where}`); + for (const t of shown) { + const other = elsewhere(t.client); + print(ctx, ` ${live(t.client) ? "enabled " : "disabled"} ${t.client.padEnd(14)} ${t.name}${other ? ` (uses ${other.server})` : ""}`); + } print(ctx); print(ctx, "Choose agents with --enable and --disable, for example: toolstile mcp setup --enable claude-code,codex"); return 0; } + // An agent can use one server at a time; moving it here needs a yes (or --switch). + if (!options.switch) + for (const client of [...wanted]) { + const other = elsewhere(client); + if (other && !(await confirmSwitch(ctx, CLIENT_NAMES[client], other.server, server))) wanted.delete(client); + } const manual: { target: Target; error: ManualEditError; enable: boolean }[] = []; const changes: string[] = []; @@ -414,6 +592,8 @@ export async function setup(ctx: Context, options: SetupOptions): Promise { const winner = loadState(stateEnv(ctx)); const retained = Object.values(winner.agents).some((agent) => - agent?.id === created.id && agent.workspaceId === workspace.id && agent.server === state.server); - if (!retained) await api.removeAgent(session.token, workspace.id, created.id); + agent?.id === created.id && agent.workspaceId === workspaceId && agent.server === server); + if (!retained) await api.removeAgent(session.token, workspaceId, created.id); }, `Agent cleanup failed. Remove the new ${target.name} authorization (${created.id}) in the Toolstile dashboard.`); } replacedAuthorization = !!link; @@ -457,7 +637,10 @@ export async function setup(ctx: Context, options: SetupOptions): Promise undefined); + if (replacedAuthorization && link) + await removeRemote(link, target.name, true).catch(() => { + ctx.stderr.write(`Could not confirm removal of the old ${target.name} authorization (${link.id}) at ${link.server}. Check for it in that server's dashboard.\n`); + }); } } else if (link || isProxyEntry(readEntry(target))) { const removeLocal = () => { @@ -473,8 +656,8 @@ export async function setup(ctx: Context, options: SetupOptions): Promise { - throw new UserError(`Disabled locally, but remote cleanup failed. Remove ${target.name} authorization (${link.id}) in the Toolstile dashboard.`); + await removeRemote(link, target.name).catch(() => { + throw new UserError(`Disabled locally, but remote cleanup failed. Remove ${target.name} authorization (${link.id}) in the Toolstile dashboard at ${link.server}.`); }); } changes.push(`${s.bold("-")} ${target.name}`); @@ -499,6 +682,10 @@ export async function setup(ctx: Context, options: SetupOptions): Promise { const [client] = parseClients(agent, "--agent"); if (!client) throw new UserError("--agent is required"); const state = loadState(stateEnv(ctx)); const link = state.agents[client]; if (!link) throw new UserError(`${CLIENT_NAMES[client]} is not enabled on this machine. Run toolstile mcp setup.`); + const endpoint = gatewayUrl(link.endpoint ?? `${link.server}/mcp`); + if (!endpoint) + throw new UserError(`${CLIENT_NAMES[client]}'s saved gateway address is not HTTPS. Run toolstile mcp setup to enable it again.`); await runProxy({ - // The token goes only to the server that issued it, whatever the environment says. - endpoint: link.endpoint ?? `${link.server}/mcp`, + endpoint, token: link.token, input: ctx.stdin as Readable, output: ctx.stdout as Writable, log: (message) => ctx.stderr.write(`toolstile: ${message}\n`), + fetch: ctx.fetch, }); return 0; } diff --git a/src/errors.ts b/src/errors.ts new file mode 100644 index 0000000..51539c5 --- /dev/null +++ b/src/errors.ts @@ -0,0 +1,2 @@ +/** A failure explained to the user; exits 1 without a stack trace. */ +export class UserError extends Error {} diff --git a/src/servers.ts b/src/servers.ts new file mode 100644 index 0000000..ba26bc4 --- /dev/null +++ b/src/servers.ts @@ -0,0 +1,95 @@ +import { readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { UserError } from "./errors.js"; + +/** Toolstile Cloud, the managed service. */ +export const DEFAULT_SERVER = "https://app.toolstile.com"; +/** Where a self-hosted server on this machine listens unless its instance says otherwise. */ +export const DEFAULT_LOCAL_SERVER = "http://127.0.0.1:4310"; + +/** `localhost`, `127.0.0.0/8` and `[::1]`, as `URL` spells them after parsing. */ +const LOOPBACK = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\])$/; + +export const isLoopback = (hostname: string) => LOOPBACK.test(hostname); + +/** HTTPS, or HTTP to a loopback host, where nothing leaves the machine. */ +export const secureScheme = (url: URL) => url.protocol === "https:" || (url.protocol === "http:" && isLoopback(url.hostname)); + +/** + * A server origin from the command line or the environment: HTTPS, or HTTP on a loopback host. + * `source` names where the value came from, for the error message. + */ +export function normalizeServer(value: string, source = "--server"): string { + let url: URL; + try { + url = new URL(value); + } catch { + throw new UserError(`${source} must be a URL, for example ${DEFAULT_SERVER}`); + } + if (url.username || url.password) throw new UserError(`${source} must not contain a user name or password`); + if (!secureScheme(url)) + throw new UserError(`${source} must use https:// (http:// only works for localhost, 127.0.0.0/8 and [::1])`); + return url.origin; +} + +export interface LocalEnv { + home?: string; + env?: Record; +} + +/** The self-hosted server's data folder: `TOOLSTILE_DATA_DIR`, else `~/.local/share/toolstile`. */ +export function localDataDir({ home = homedir(), env = process.env }: LocalEnv = {}): string { + return env.TOOLSTILE_DATA_DIR || join(home, ".local", "share", "toolstile"); +} + +/** + * The origin of the self-hosted server on this machine. `instance.json` also holds the instance's + * secret keys, so only its `origin` field is used, and no error quotes the file. + */ +export function localServer(opts: LocalEnv = {}): string { + const path = join(localDataDir(opts), "instance.json"); + let text: string; + try { + text = readFileSync(path, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return DEFAULT_LOCAL_SERVER; + throw new UserError(`Could not read ${path}. Use --server instead of --local.`); + } + let origin: unknown; + try { + origin = (JSON.parse(text) as { origin?: unknown } | null)?.origin; + } catch { + throw new UserError(`${path} is not valid JSON. Use --server instead of --local.`); + } + if (origin === undefined) return DEFAULT_LOCAL_SERVER; + if (typeof origin !== "string") throw new UserError(`${path} has no valid origin. Use --server instead of --local.`); + try { + return normalizeServer(origin); + } catch { + throw new UserError(`${path} has no valid origin. Use --server instead of --local.`); + } +} + +/** How a command picks its server: `--server ` or `--local`. */ +export interface ServerChoice { + server?: string; + local?: boolean; +} + +/** The variable that sets the default server, and the older name it replaces. */ +export function serverFromEnv(env: Record): { name: string; value: string } | undefined { + if (env.TOOLSTILE_SERVER) return { name: "TOOLSTILE_SERVER", value: env.TOOLSTILE_SERVER }; + if (env.TOOLSTILE_URL) return { name: "TOOLSTILE_URL", value: env.TOOLSTILE_URL }; + return undefined; +} + +/** The server a command talks to: `--server` or `--local`, then `TOOLSTILE_SERVER`, then the current server. */ +export function chooseServer(opts: LocalEnv & { current: string }, choice: ServerChoice = {}): string { + if (choice.server !== undefined && choice.local) throw new UserError("Use either --server or --local, not both."); + if (choice.server !== undefined) return normalizeServer(choice.server); + if (choice.local) return localServer(opts); + const fromEnv = serverFromEnv(opts.env ?? process.env); + if (fromEnv) return normalizeServer(fromEnv.value, fromEnv.name); + return opts.current; +} diff --git a/src/state.ts b/src/state.ts index 1639629..3069016 100644 --- a/src/state.ts +++ b/src/state.ts @@ -3,18 +3,23 @@ import { randomUUID } from "node:crypto"; import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; +import { DEFAULT_SERVER, secureScheme } from "./servers.js"; import type { ClientId } from "./types.js"; -export const DEFAULT_SERVER = "https://app.toolstile.com"; +export { DEFAULT_SERVER }; /** Toolstile's gateway, on its own host since the app moved off the bare domain. */ export const DEFAULT_MCP_URL = "https://mcp.toolstile.com/mcp"; /** Where Toolstile served the app and gateway before; it now only redirects. */ const LEGACY_SERVER = "https://toolstile.com"; +/** Toolstile Cloud has workspaces; a self-hosted server has none. */ +export type Edition = "cloud" | "self-hosted"; + export interface AgentLink { - /** The agent's authorization ID in Toolstile, valid in one workspace. */ + /** The agent's authorization ID on its server. */ id: string; - workspaceId: string; + /** The Toolstile Cloud workspace it belongs to; absent on a self-hosted server. */ + workspaceId?: string; /** The Toolstile origin that issued the token; the proxy sends it nowhere else. */ server: string; /** That server's gateway URL, as it reported it; `${server}/mcp` when absent. */ @@ -24,13 +29,32 @@ export interface AgentLink { token: string; } -/** Everything `auth` and `mcp` keep on this machine, in one owner-only file. */ -export interface State { - /** The origin `auth login` last signed in to. */ - server: string; - session?: { token: string; email: string; expiresAt: string; server: string }; +export interface Session { + token: string; + email: string; + expiresAt: string; +} + +/** What the CLI keeps for one server origin. */ +export interface ServerState { + edition?: Edition; + session?: Session; + /** The Toolstile Cloud workspace setup used last. */ workspace?: { id: string; slug: string; name: string }; + /** This machine, as that server knows it. */ device?: { id: string; label: string }; +} + +/** + * Everything `auth` and `mcp` keep on this machine, in one owner-only file. `agents` keeps the + * shape earlier releases wrote, so an agent config pinned to an older CLI still finds its link. + */ +export interface State { + version: 2; + /** The server commands use when no flag or variable picks one: the last one signed in to. */ + current: string; + /** One entry per server origin. */ + servers: Record; agents: Partial>; } @@ -51,27 +75,35 @@ export const statePath = (opts?: StateEnv) => join(stateDir(opts), "credentials. const revisions = new WeakMap(); -/** - * The saved server always wins over `TOOLSTILE_URL`, which only picks the server for a new - * `auth login`: an environment variable set by a project must not redirect saved tokens. - */ +/** The entry for `server`, created when missing. */ +export function serverEntry(state: State, server: string): ServerState { + return (state.servers[server] ??= {}); +} + +/** Reads the credentials file, upgrading the single sign-in format of earlier releases in memory. */ export function loadState(opts?: StateEnv): State { - const fallback: State = { server: DEFAULT_SERVER, agents: {} }; let text: string; try { text = readFileSync(statePath(opts), "utf8"); } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { revisions.set(fallback, null); return fallback; } + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + const empty: State = { version: 2, current: DEFAULT_SERVER, servers: {}, agents: {} }; + revisions.set(empty, null); + return empty; + } throw error; } + let data: unknown; try { - const data = JSON.parse(text) as Partial; - const state = moveLegacyServer({ ...fallback, ...data, agents: data.agents ?? {} }); - revisions.set(state, text); - return state; + data = JSON.parse(text); } catch { - throw new Error(`${statePath(opts)} is not valid JSON. Delete it and run toolstile auth login again.`); + data = undefined; } + if (!isObject(data)) + throw new Error(`${statePath(opts)} is not valid JSON. Delete it and run toolstile auth login again.`); + const state = upgrade(data); + revisions.set(state, text); + return state; } /** Hold the credential revision stable during a synchronous config mutation. */ @@ -96,7 +128,8 @@ export function saveState(state: State, opts?: StateEnv, beforeWrite?: () => voi beforeWrite?.(); const temp = `${path}.${process.pid}.${randomUUID()}.tmp`; try { - writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }); + const { version, current, servers, agents } = state; + writeFileSync(temp, `${JSON.stringify({ version, current, servers, agents }, null, 2)}\n`, { mode: 0o600 }); chmodSync(temp, 0o600); renameSync(temp, path); revisions.set(state, fileText(path)); @@ -106,14 +139,61 @@ export function saveState(state: State, opts?: StateEnv, beforeWrite?: () => voi }); } -/** Sign-ins and agents saved for the old bare-domain address keep working on the new hosts. */ -function moveLegacyServer(state: State): State { - if (state.server === LEGACY_SERVER) state.server = DEFAULT_SERVER; - if (state.session?.server === LEGACY_SERVER) state.session.server = DEFAULT_SERVER; - for (const link of Object.values(state.agents)) +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** Keys of `servers` are HTTPS or loopback origins; anything else (such as `__proto__`) is dropped on load. */ +function isOrigin(value: string): boolean { + try { + const url = new URL(value); + return url.origin === value && secureScheme(url); + } catch { + return false; + } +} + +/** + * Earlier releases kept one sign-in at the top level: `server`, `session` (with its own + * `server`), `workspace` and `device`. They become that server's entry, and that server the + * current one. An older release run after this one writes those keys next to the new ones; its + * sign-in is then the newest, so it is folded in the same way. + */ +function upgrade(data: Record): State { + const servers: Record = {}; + if (isObject(data.servers)) + for (const [origin, entry] of Object.entries(data.servers)) + if (isOrigin(origin) && isObject(entry)) servers[origin] = entry as ServerState; + const agents = (isObject(data.agents) ? data.agents : {}) as State["agents"]; + let current = typeof data.current === "string" && isOrigin(data.current) ? data.current : undefined; + + const legacySession = isObject(data.session) ? (data.session as Partial & { server?: unknown }) : undefined; + const legacyServer = typeof data.server === "string" ? data.server : undefined; + if (legacySession || legacyServer !== undefined || isObject(data.workspace) || isObject(data.device)) { + const named = typeof legacySession?.server === "string" ? legacySession.server : legacyServer; + const origin = named !== undefined && isOrigin(named) ? named : DEFAULT_SERVER; + const entry = (servers[origin] ??= {}); + if (legacySession && typeof legacySession.token === "string") + entry.session = { + token: legacySession.token, + email: String(legacySession.email ?? ""), + expiresAt: String(legacySession.expiresAt ?? ""), + }; + if (isObject(data.workspace)) entry.workspace = data.workspace as ServerState["workspace"]; + if (isObject(data.device)) entry.device = data.device as ServerState["device"]; + current = origin; + } + + // Sign-ins and agents saved for the old bare-domain address keep working on the new hosts. + const legacy = servers[LEGACY_SERVER]; + if (legacy) { + servers[DEFAULT_SERVER] ??= legacy; + delete servers[LEGACY_SERVER]; + } + if (current === LEGACY_SERVER) current = DEFAULT_SERVER; + for (const link of Object.values(agents)) if (link?.server === LEGACY_SERVER) { link.server = DEFAULT_SERVER; link.endpoint ??= DEFAULT_MCP_URL; } - return state; + return { version: 2, current: current ?? DEFAULT_SERVER, servers, agents }; } diff --git a/test/connect.test.ts b/test/connect.test.ts index f6acdc1..c2ec914 100644 --- a/test/connect.test.ts +++ b/test/connect.test.ts @@ -32,9 +32,12 @@ import { style } from "../src/report.js"; import { loadState, saveState, statePath } from "../src/state.js"; let home: string; +const CLOUD = "https://app.toolstile.com"; const env = () => ({ TOOLSTILE_CONFIG_DIR: join(home, "cfg") }); const target = (client: string) => targets({ home, platform: "linux", env: {} }).find((t) => t.client === client)!; const command = (client: Parameters[0]) => proxyCommand(client, "0.2.0", "linux"); +/** The saved entry for one server. */ +const saved = (server = CLOUD) => loadState({ home, env: env() }).servers[server]; function put(path: string, text: string) { mkdirSync(dirname(path), { recursive: true }); @@ -228,16 +231,16 @@ describe("agent config entries", () => { describe("credentials file", () => { it("is owner-only and survives a round trip", () => { const state = loadState({ home, env: env() }); - expect(state.server).toBe("https://app.toolstile.com"); + expect(state.current).toBe("https://app.toolstile.com"); state.agents.cursor = { id: "a", workspaceId: "w", server: "https://app.toolstile.com", label: "Cursor", token: "ts_x" }; saveState(state, { home, env: env() }); expect(statSync(statePath({ home, env: env() })).mode & 0o777).toBe(0o600); expect(statSync(join(home, "cfg")).mode & 0o777).toBe(0o700); expect(loadState({ home, env: env() }).agents.cursor?.token).toBe("ts_x"); - // A project's environment cannot point saved tokens at another server. - expect(loadState({ home, env: { ...env(), TOOLSTILE_URL: "https://evil.example" } }).server).toBe( - "https://app.toolstile.com", - ); + // The environment picks a server for a command; it never rewrites saved links. + const elsewhere = loadState({ home, env: { ...env(), TOOLSTILE_SERVER: "https://evil.example" } }); + expect(elsewhere.current).toBe("https://app.toolstile.com"); + expect(elsewhere.agents.cursor?.server).toBe("https://app.toolstile.com"); }); it("moves a sign-in saved for the old bare-domain address to the app and gateway hosts", () => { @@ -254,8 +257,10 @@ describe("credentials file", () => { }), ); const state = loadState({ home, env: env() }); - expect(state.server).toBe("https://app.toolstile.com"); - expect(state.session?.server).toBe("https://app.toolstile.com"); + expect(state.current).toBe("https://app.toolstile.com"); + expect(state.servers).toEqual({ + "https://app.toolstile.com": { session: { token: "s", email: "me@test.invalid", expiresAt: "2030-01-01T00:00:00.000Z" } }, + }); expect(state.agents.cursor).toMatchObject({ server: "https://app.toolstile.com", endpoint: "https://mcp.toolstile.com/mcp", @@ -519,7 +524,7 @@ describe("auth and setup", () => { expect(output()).toContain("https://app.toolstile.com/device?user_code=ABCDEFGH&device_name=build-mac"); expect(output()).toContain("ABCD-EFGH"); expect(output()).toContain("ABCD-EFGH"); - expect(loadState({ home, env: env() }).session).toMatchObject({ token: "session", email: "me@test.invalid" }); + expect(saved()?.session).toMatchObject({ token: "session", email: "me@test.invalid" }); }); it("adopts the device named on the approval page", async () => { @@ -538,7 +543,7 @@ describe("auth and setup", () => { expect(output()).toContain("on Studio Mac"); await setup(ctx, { enable: "cursor" }); expect(calls).toContain("device:Studio Mac"); - expect(loadState({ home, env: env() }).device).toEqual({ id: "d9", label: "Studio Mac" }); + expect(saved()?.device).toEqual({ id: "d9", label: "Studio Mac" }); }); it("reports a denied code", async () => { @@ -558,7 +563,7 @@ describe("auth and setup", () => { await login(ctx, { browser: false }); expect(await setup(ctx, { enable: "cursor,codex", deviceName: "box" })).toBe(0); let state = loadState({ home, env: env() }); - expect(state.device).toEqual({ id: "d1", label: "box" }); + expect(state.servers[CLOUD]?.device).toEqual({ id: "d1", label: "box" }); expect(Object.keys(state.agents).sort()).toEqual(["codex", "cursor"]); expect(readEntry(target("cursor"))).toMatchObject({ args: expect.arrayContaining(["cursor"]) }); expect(calls).toEqual(["device:box", "add:Cursor", "add:Codex"]); @@ -570,10 +575,10 @@ describe("auth and setup", () => { expect(calls.at(-1)).toBe("remove:a1"); expect(await logout(ctx)).toBe(0); - expect(loadState({ home, env: env() }).session).toBeUndefined(); + expect(saved()?.session).toBeUndefined(); // Setup signs in again by itself instead of failing. expect(await setup(ctx, {})).toBe(0); - expect(loadState({ home, env: env() }).session?.token).toBe("session"); + expect(saved()?.session?.token).toBe("session"); }); it("keeps tokens on the server that issued them", async () => { @@ -591,19 +596,20 @@ describe("auth and setup", () => { }); return { ...api, deviceCode }; }; + const revoked: string[] = []; + api.signOut = async (token) => { revoked.push(token); }; await login(ctx, { browser: false }); await setup(ctx, { enable: "cursor" }); ctx.env = { ...ctx.env, TOOLSTILE_URL: "https://other.example" }; + api.deviceToken = async () => ({ access_token: "other-session", expires_in: 1 }); await login(ctx, { browser: false }); - // The old session is signed out where it was issued; the new one belongs to the new server. - expect(servers).toEqual([ - "https://app.toolstile.com", - "https://app.toolstile.com", - "https://other.example", - "https://app.toolstile.com", - ]); + // Signing in to a second server keeps the first sign-in; each session stays with its server. + expect(new Set(servers)).toEqual(new Set(["https://app.toolstile.com", "https://other.example"])); + expect(revoked).toEqual([]); const state = loadState({ home, env: ctx.env }); - expect(state.session?.server).toBe("https://other.example"); + expect(state.current).toBe("https://other.example"); + expect(state.servers[CLOUD]?.session?.token).toBe("session"); + expect(state.servers["https://other.example"]?.session?.token).toBe("other-session"); expect(state.agents.cursor?.server).toBe("https://app.toolstile.com"); }); @@ -680,7 +686,8 @@ describe("setup signs in when needed", () => { expect(output()).toContain("+ Claude Code"); expect(output()).toContain("Restart Claude Code to pick up the change."); const state = loadState({ home, env: env() }); - expect(state.session).toMatchObject({ token: "session", server: "https://app.toolstile.com" }); + expect(state.current).toBe(CLOUD); + expect(state.servers[CLOUD]).toMatchObject({ edition: "cloud", session: { token: "session" } }); expect(state.agents["claude-code"]).toMatchObject({ id: "a1", server: "https://app.toolstile.com" }); expect(readEntry(target("claude-code"))).toMatchObject(command("claude-code")); expect(calls).toEqual(["device:build-mac", "add:Claude Code"]); @@ -710,7 +717,7 @@ describe("setup signs in when needed", () => { api.signOut = async (token) => { revoked.push(token); }; expect(await setup(ctx, { enable: "cursor" })).toBe(0); expect(output()).toContain("&next=setup"); - expect(loadState({ home, env: env() }).session?.token).toBe("fresh"); + expect(saved()?.session?.token).toBe("fresh"); expect(loadState({ home, env: env() }).agents.cursor?.id).toBe("a1"); expect(revoked).toEqual(["session"]); expect(calls).toContain("add:Cursor"); @@ -727,12 +734,13 @@ describe("setup signs in when needed", () => { api.deviceToken = async () => ({ access_token: "other-session", expires_in: 1 }); expect(await setup(ctx, { enable: "cursor", server: "https://other.example/" })).toBe(0); expect(codes).toEqual(["https://app.toolstile.com", "https://other.example"]); - // The old session is signed out where it was issued. - expect(used).toContain("https://app.toolstile.com"); - expect(revoked).toEqual(["session"]); + expect(used).toContain("https://other.example"); + // The sign-in to the first server is kept, not signed out. + expect(revoked).toEqual([]); const state = loadState({ home, env: env() }); - expect(state.server).toBe("https://other.example"); - expect(state.session).toMatchObject({ token: "other-session", server: "https://other.example" }); + expect(state.current).toBe("https://other.example"); + expect(state.servers["https://other.example"]?.session?.token).toBe("other-session"); + expect(state.servers[CLOUD]?.session?.token).toBe("session"); expect(state.agents.cursor?.server).toBe("https://other.example"); }); @@ -743,9 +751,9 @@ describe("setup signs in when needed", () => { const { forServer, codes } = servers(api); ctx.api = forServer; await login(ctx, { browser: false }); - // TOOLSTILE_URL only picks the server for a new sign-in; it does not replace a saved session. + // --server wins over TOOLSTILE_URL, and the saved sign-in for that server is reused. ctx.env = { ...ctx.env, TOOLSTILE_URL: "https://other.example" }; - expect(await setup(ctx, { enable: "cursor" })).toBe(0); + expect(await setup(ctx, { enable: "cursor", server: "https://app.toolstile.com/" })).toBe(0); expect(await setup(ctx, { disable: "cursor", server: "https://app.toolstile.com" })).toBe(0); expect(codes).toEqual(["https://app.toolstile.com"]); expect(output().match(/Signed in as/g)).toHaveLength(1); @@ -754,7 +762,7 @@ describe("setup signs in when needed", () => { expect(output()).toContain("- Cursor\n\nRestart agents that are running to pick up the change."); }); - it("uses TOOLSTILE_URL for a sign-in when there is no session, like auth login", async () => { + it("uses TOOLSTILE_URL for a sign-in, like auth login", async () => { const { api } = fakeApi(); const { ctx } = context(api); const { forServer, codes } = servers(api); @@ -825,7 +833,7 @@ describe("setup signs in when needed", () => { }); it("accepts --server and --no-browser on the command line", () => { - const { TOOLSTILE_URL: _, ...inherited } = process.env; + const { TOOLSTILE_URL: _, TOOLSTILE_SERVER: __, ...inherited } = process.env; const run = (...args: string[]) => spawnSync(process.execPath, [cli, "mcp", "setup", ...args], { env: { ...inherited, TOOLSTILE_CONFIG_DIR: join(home, "cfg"), HOME: home }, @@ -1109,7 +1117,7 @@ describe("credential operation conflicts", () => { expect(agents.has("a1")).toBe(true); const created = await add(...args); const winner = loadState(opts); - winner.device!.label = "concurrent winner"; + winner.servers[CLOUD]!.device!.label = "concurrent winner"; saveState(winner, opts); return created; }; @@ -1117,7 +1125,7 @@ describe("credential operation conflicts", () => { expect([...agents.keys()]).toEqual(["a1"]); expect(calls).not.toContain("remove:a1"); expect(loadState(opts).agents.cursor?.id).toBe("a1"); - expect(loadState(opts).device?.label).toBe("concurrent winner"); + expect(loadState(opts).servers[CLOUD]?.device?.label).toBe("concurrent winner"); }); it("does not revoke a newly issued authorization that the winning state already retains", async () => { @@ -1129,7 +1137,7 @@ describe("credential operation conflicts", () => { const created = await add(...args); const winner = loadState({ home, env: env() }); winner.agents.cursor = { - ...created, workspaceId: "w1", server: winner.server, endpoint: "https://gateway.invalid/mcp", + ...created, workspaceId: "w1", server: winner.current, endpoint: "https://gateway.invalid/mcp", }; saveState(winner, { home, env: env() }); return created; @@ -1148,13 +1156,13 @@ describe("credential operation conflicts", () => { api.addAgent = async (...args) => { const created = await add(...args); const winner = loadState({ home, env: env() }); - winner.device!.label = "winner"; + winner.servers[CLOUD]!.device!.label = "winner"; saveState(winner, { home, env: env() }); return created; }; api.removeAgent = async () => { throw new ApiError(status, "fixture failure"); }; await expect(setup(ctx, { enable: "cursor" })).rejects.toThrow(status === 404 ? "changed in another command" : "Agent cleanup failed"); - expect(loadState({ home, env: env() }).device?.label).toBe("winner"); + expect(saved()?.device?.label).toBe("winner"); expect(readEntry(target("cursor"))).toBeUndefined(); }); @@ -1168,14 +1176,14 @@ describe("credential operation conflicts", () => { const account = api.account; api.account = async (token) => { const winner = loadState({ home, env: env() }); - winner.device = { id: "winner", label: "winner" }; + winner.servers[CLOUD]!.device = { id: "winner", label: "winner" }; saveState(winner, { home, env: env() }); return account(token); }; await expect(login(ctx, { browser: false })).rejects.toThrow("changed in another command"); expect(revoked).toEqual(["losing-session"]); - expect(loadState({ home, env: env() }).session?.token).toBe("session"); - expect(loadState({ home, env: env() }).device?.id).toBe("winner"); + expect(saved()?.session?.token).toBe("session"); + expect(saved()?.device?.id).toBe("winner"); }); it("cleans up an approved login if account lookup fails", async () => { @@ -1186,7 +1194,7 @@ describe("credential operation conflicts", () => { }); await expect(login(context(api).ctx, { browser: false })).rejects.toThrow("account fixture failed"); expect(revoked).toEqual(["session"]); - expect(loadState({ home, env: env() }).session).toBeUndefined(); + expect(saved()?.session).toBeUndefined(); }); }); @@ -1198,7 +1206,7 @@ describe("credential revocation order", () => { api.deviceToken = async () => ({ access_token: "replacement", expires_in: 1 }); const revoked: string[] = []; api.signOut = async (token) => { - expect(loadState({ home, env: env() }).session?.token).toBe("replacement"); + expect(saved()?.session?.token).toBe("replacement"); revoked.push(token); }; await login(ctx, { browser: false }); @@ -1211,12 +1219,12 @@ describe("credential revocation order", () => { await login(ctx, { browser: false }); const revoked: string[] = []; api.signOut = async (token) => { - expect(loadState({ home, env: env() }).session).toBeUndefined(); + expect(saved()?.session).toBeUndefined(); revoked.push(token); throw new ApiError(503, "offline fixture"); }; expect(await logout(ctx)).toBe(0); expect(revoked).toEqual(["session"]); - expect(output()).toContain("Signed out on this machine"); + expect(output()).toContain("Signed out of https://app.toolstile.com on this machine. The server could not be reached"); }); }); diff --git a/test/fixtures/process-disable-race.mjs b/test/fixtures/process-disable-race.mjs index dc7ce7a..5f77e6e 100644 --- a/test/fixtures/process-disable-race.mjs +++ b/test/fixtures/process-disable-race.mjs @@ -33,10 +33,13 @@ if (child) { try { fs.writeFileSync(remotePath, JSON.stringify(["old"])); const state = loadState(opts); - state.session = { token: "fixture", email: "fixture@example.invalid", expiresAt: "2099-01-01", server: state.server }; - state.workspace = { id: "w", slug: "fixture", name: "Fixture" }; - state.device = { id: "device", label: "Fixture" }; - state.agents.cursor = { id: "old", workspaceId: "w", server: state.server, endpoint: state.server + "/mcp", label: "Cursor", token: "fixture-old" }; + state.servers[state.current] = { + edition: "cloud", + session: { token: "fixture", email: "fixture@example.invalid", expiresAt: "2099-01-01" }, + workspace: { id: "w", slug: "fixture", name: "Fixture" }, + device: { id: "device", label: "Fixture" }, + }; + state.agents.cursor = { id: "old", workspaceId: "w", server: state.current, endpoint: state.current + "/mcp", label: "Cursor", token: "fixture-old" }; saveState(state, opts); await setup(ctx, { enable: "cursor" }); let enabling; diff --git a/test/hardening.test.ts b/test/hardening.test.ts index 3a7d809..4146c10 100644 --- a/test/hardening.test.ts +++ b/test/hardening.test.ts @@ -22,6 +22,7 @@ function proxy(fetcher: typeof fetch, output: Writable = new PassThrough()) { const done = runProxy({ input, output, fetch: fetcher, endpoint: "https://gateway.invalid/mcp", token: "fixture", log: () => {} }); return { input, done, messages: () => text.trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) }; } +const cloud = "https://app.toolstile.com"; const tick = () => new Promise((resolve) => setImmediate(resolve)); it("rejects null, primitives, empty and mixed batches without losing valid requests", async () => { @@ -73,10 +74,10 @@ it("rejects stale credentials and a competing config update", () => { const opts = { env: { TOOLSTILE_CONFIG_DIR: dir } }; try { const first = loadState(opts), second = loadState(opts); - first.device = { id: "one", label: "one" }; saveState(first, opts); - second.device = { id: "two", label: "two" }; + first.servers[cloud] = { device: { id: "one", label: "one" } }; saveState(first, opts); + second.servers[cloud] = { device: { id: "two", label: "two" } }; expect(() => saveState(second, opts)).toThrow("changed in another command"); - expect(loadState(opts).device?.id).toBe("one"); + expect(loadState(opts).servers[cloud]?.device?.id).toBe("one"); const target = { client: "cursor" as const, name: "Cursor", path: join(dir, "mcp.json"), format: "mcpServers" as const, detected: true }; withFileLock(target.path, () => { expect(() => writeEntry(target, { command: "npx", args: ["toolstile", "mcp", "proxy"] })).toThrow("Another command"); @@ -188,11 +189,11 @@ it("detects credentials saved by another process after this command loaded them" const { loadState, saveState } = await import(${JSON.stringify(module)}); const opts = { env: { TOOLSTILE_CONFIG_DIR: ${JSON.stringify(dir)} } }; const state = loadState(opts); - state.device = { id: "other-process", label: "fixture" }; + state.servers["https://app.toolstile.com"] = { device: { id: "other-process", label: "fixture" } }; saveState(state, opts); `]); expect(() => saveState(stale, opts)).toThrow("changed in another command"); - expect(loadState(opts).device?.id).toBe("other-process"); + expect(loadState(opts).servers[cloud]?.device?.id).toBe("other-process"); const config = join(dir, "config.json"); writeText(config, "first"); writeText(config, "second"); expect(() => writeText(config, "stale", "first")).toThrow("changed while"); diff --git a/test/targets.test.ts b/test/targets.test.ts new file mode 100644 index 0000000..8cea611 --- /dev/null +++ b/test/targets.test.ts @@ -0,0 +1,748 @@ +import { spawnSync } from "node:child_process"; +import { once } from "node:events"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { PassThrough } from "node:stream"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { readEntry, targets } from "../src/agents.js"; +import { createApi } from "../src/api.js"; +import { type Context, login, logout, normalizeServer, proxy, setup, status, whoami } from "../src/commands.js"; +import { style } from "../src/report.js"; +import { chooseServer, DEFAULT_LOCAL_SERVER, localDataDir, localServer } from "../src/servers.js"; +import { loadState, saveState, statePath } from "../src/state.js"; + +const CLOUD = "https://app.toolstile.com"; +const LOCAL = "http://127.0.0.1:4310"; +const SECRET = "FAKE-SECRET-do-not-print"; + +let home: string; +const env = (extra: Record = {}) => ({ TOOLSTILE_CONFIG_DIR: join(home, "cfg"), ...extra }); +const opts = () => ({ home, env: env() }); +const target = (client: string) => targets({ home, platform: "linux", env: {} }).find((t) => t.client === client)!; + +function put(path: string, text: string) { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, text); +} + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "toolstile-targets-")); +}); +afterEach(() => rmSync(home, { recursive: true, force: true })); + +interface Recorded { + method: string; + url: URL; + body: Record | undefined; + auth: string | undefined; +} + +/** + * A Toolstile server that follows the CLI contract. Self-hosted servers reject any `workspaceId`; + * Cloud servers require one. `edition: undefined` is a Cloud server from before the field existed. + */ +function fakeServer(origin: string, options: { edition?: "cloud" | "self-hosted"; email?: string; mcpUrl?: string } = {}) { + const selfHosted = options.edition === "self-hosted"; + const requests: Recorded[] = []; + const agents = new Map(); + const host = new URL(origin).host; + let issued = 0; + let next = 0; + let session = ""; + const handle = async (url: URL, init: RequestInit): Promise => { + const method = init.method ?? "GET"; + const body = init.body ? (JSON.parse(String(init.body)) as Record) : undefined; + const auth = (init.headers as Record | undefined)?.Authorization; + requests.push({ method, url, body, auth }); + const path = url.pathname; + const page = selfHosted ? "/auth/device" : "/device"; + if (path === "/api/auth/device/code") + return Response.json({ + device_code: "dc", + user_code: "ABCDEFGH", + verification_uri: `${origin}${page}`, + verification_uri_complete: `${origin}${page}?user_code=ABCDEFGH`, + expires_in: 600, + interval: 1, + }); + if (path === "/api/auth/device/token") { + session = `session-${host}-${++issued}`; + return Response.json({ access_token: session, expires_in: 3600 }); + } + if (!session || auth !== `Bearer ${session}`) return Response.json({ message: "Unauthorized" }, { status: 401 }); + const workspaceId = url.searchParams.get("workspaceId") ?? body?.workspaceId; + if (path.startsWith("/api/cli/") && path !== "/api/cli/account" && path !== "/api/cli/sign-out") { + if (selfHosted && workspaceId !== undefined && workspaceId !== null) + return Response.json({ message: "No workspaces here" }, { status: 400 }); + if (!selfHosted && workspaceId !== "w1") return Response.json({ message: "workspaceId required" }, { status: 400 }); + } + if (path === "/api/cli/account") + return Response.json({ + email: options.email ?? `me@${host}`, + name: "Me", + expiresAt: "2030-01-01T00:00:00.000Z", + ...(options.edition ? { edition: options.edition } : {}), + ...(options.mcpUrl ? { mcpUrl: options.mcpUrl } : {}), + workspaces: selfHosted ? [] : [{ id: "w1", slug: "personal", name: "Personal", personal: true }], + }); + if (path === "/api/cli/sign-out") { + session = ""; + return new Response(null, { status: 204 }); + } + if (path === "/api/cli/device") return Response.json({ id: body?.id ?? `device-${host}`, label: body?.label }); + if (path === "/api/cli/agents" && method === "GET") + return Response.json({ agents: [...agents].map(([id, label]) => ({ id, label })) }); + if (path === "/api/cli/agents" && method === "POST") { + const id = `agent-${++next}`; + agents.set(id, String(body?.label)); + return Response.json({ id, label: body?.label, token: `token-${host}-${id}` }); + } + if (path.startsWith("/api/cli/agents/") && method === "DELETE") { + const id = decodeURIComponent(path.slice("/api/cli/agents/".length)); + return agents.delete(id) ? new Response(null, { status: 204 }) : Response.json({ message: "Not found" }, { status: 404 }); + } + return Response.json({ message: "Not found" }, { status: 404 }); + }; + return { origin, requests, agents, handle, session: () => session }; +} + +type Fake = ReturnType; + +/** Routes requests to the fake servers by origin; any other address is unreachable. */ +function network(...servers: Fake[]): typeof fetch { + return (async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input)); + const server = servers.find((s) => s.origin === url.origin); + if (!server) throw new TypeError("fetch failed"); + return server.handle(url, init ?? {}); + }) as typeof fetch; +} + +function context(fetcher: typeof fetch, extraEnv: Record = {}) { + let out = ""; + let err = ""; + const stdout = new PassThrough(); + const stderr = new PassThrough(); + stdout.on("data", (chunk) => (out += chunk)); + stderr.on("data", (chunk) => (err += chunk)); + const ctx: Context = { + home, + platform: "linux", + env: env(extraEnv), + version: "0.2.0", + api: (server) => createApi(server, fetcher), + stdin: new PassThrough(), + stdout, + stderr, + style: style(false), + sleep: async () => {}, + hostname: () => "box", + openBrowser: () => {}, + }; + return { ctx, output: () => out, errors: () => err }; +} + +/** A terminal on both ends, so setup prompts. */ +function terminal(ctx: Context) { + ctx.stdin = Object.assign(new PassThrough(), { isTTY: true, isRaw: false, setRawMode() {} }); + const stdout = ctx.stdout as PassThrough; + ctx.stdout = Object.assign(stdout, { isTTY: true, columns: 120, rows: 40 }); + return ctx.stdin as PassThrough; +} + +const signOuts = (server: Fake) => server.requests.filter((r) => r.url.pathname === "/api/cli/sign-out").map((r) => r.auth); +const codes = (server: Fake) => server.requests.filter((r) => r.url.pathname === "/api/auth/device/code").length; + +describe("state file migration", () => { + /** What 0.7.1 and earlier wrote: one sign-in at the top level. */ + const previous = { + server: CLOUD, + session: { token: "saved-session", email: "me@test.invalid", expiresAt: "2030-01-01T00:00:00.000Z", server: CLOUD }, + workspace: { id: "w1", slug: "personal", name: "Personal" }, + device: { id: "saved-device", label: "Studio" }, + agents: { + cursor: { + id: "agent-old", + workspaceId: "w1", + server: CLOUD, + endpoint: "https://mcp.toolstile.com/mcp", + label: "Cursor", + token: "agent-token", + }, + }, + }; + + it("keeps the sign-in, device and agent links from the single sign-in format", () => { + put(statePath(opts()), JSON.stringify(previous)); + chmodSync(statePath(opts()), 0o600); + const state = loadState(opts()); + expect(state).toEqual({ + version: 2, + current: CLOUD, + servers: { + [CLOUD]: { + session: { token: "saved-session", email: "me@test.invalid", expiresAt: "2030-01-01T00:00:00.000Z" }, + workspace: previous.workspace, + device: previous.device, + }, + }, + agents: previous.agents, + }); + }); + + it("rewrites the file in place on the next save, owner-only and readable by older proxies", async () => { + put(statePath(opts()), JSON.stringify(previous)); + chmodSync(statePath(opts()), 0o600); + mkdirSync(join(home, ".codex")); + const cloud = fakeServer(CLOUD, { mcpUrl: "https://mcp.toolstile.com/mcp" }); + // The saved session is still valid on the server. + await cloud.handle(new URL(`${CLOUD}/api/auth/device/token`), { method: "POST" }); + const state = loadState(opts()); + state.servers[CLOUD]!.session!.token = cloud.session(); + saveState(state, opts()); + cloud.agents.set("agent-old", "Cursor"); + const { ctx } = context(network(cloud)); + expect(await setup(ctx, { enable: "codex" })).toBe(0); + // No new sign-in; the saved device and workspace were used. + expect(codes(cloud)).toBe(0); + const device = cloud.requests.find((r) => r.url.pathname === "/api/cli/device"); + expect(device?.body).toMatchObject({ id: "saved-device", workspaceId: "w1" }); + + const text = readFileSync(statePath(opts()), "utf8"); + const file = JSON.parse(text) as Record; + expect(Object.keys(file).sort()).toEqual(["agents", "current", "servers", "version"]); + expect(statSync(statePath(opts())).mode & 0o777).toBe(0o600); + // An agent config pinned to an older CLI reads `agents.` and nothing else. + expect((file.agents as Record).cursor).toEqual(previous.agents.cursor); + expect((file.agents as Record).codex?.server).toBe(CLOUD); + }); + + it("folds in a sign-in an older release wrote next to the new format", () => { + put( + statePath(opts()), + JSON.stringify({ + version: 2, + current: LOCAL, + servers: { [LOCAL]: { edition: "self-hosted", session: { token: "l", email: "l@x", expiresAt: "2030" } } }, + agents: {}, + server: CLOUD, + session: { token: "newer", email: "me@test.invalid", expiresAt: "2031", server: CLOUD }, + }), + ); + const state = loadState(opts()); + expect(state.current).toBe(CLOUD); + expect(state.servers[CLOUD]?.session?.token).toBe("newer"); + expect(state.servers[LOCAL]?.session?.token).toBe("l"); + }); + + it("drops server keys that are not HTTPS or loopback origins", () => { + put( + statePath(opts()), + JSON.stringify({ version: 2, current: "http://evil.example", servers: { "http://evil.example": {}, x: {} }, agents: {} }), + ); + const state = loadState(opts()); + expect(state.current).toBe(CLOUD); + expect(state.servers).toEqual({}); + }); +}); + +describe("server selection", () => { + const pick = (choice: { server?: string; local?: boolean }, extra: Record = {}, current = CLOUD) => + chooseServer({ home, env: { ...extra }, current }, choice); + + it("uses the flag, then TOOLSTILE_SERVER, then TOOLSTILE_URL, then the current server", () => { + const vars = { TOOLSTILE_SERVER: "https://env.example", TOOLSTILE_URL: "https://alias.example" }; + expect(pick({ server: "https://flag.example/x" }, vars)).toBe("https://flag.example"); + expect(pick({ local: true }, vars)).toBe(DEFAULT_LOCAL_SERVER); + expect(pick({}, vars)).toBe("https://env.example"); + expect(pick({}, { TOOLSTILE_URL: "https://alias.example" })).toBe("https://alias.example"); + expect(pick({}, {}, "https://current.example")).toBe("https://current.example"); + expect(() => pick({ server: CLOUD, local: true })).toThrow("Use either --server or --local, not both."); + expect(() => pick({}, { TOOLSTILE_SERVER: "http://env.example" })).toThrow(/^TOOLSTILE_SERVER must use https:\/\//); + }); + + it("accepts plain http only for loopback hosts", () => { + for (const ok of ["http://localhost:4310", "http://127.0.0.1:4310", "http://127.8.9.10", "http://[::1]:4310", "http://127.1"]) + expect(normalizeServer(ok), ok).toMatch(/^http:\/\/(localhost|127\.|\[::1\])/); + for (const bad of [ + "http://192.168.1.20:4310", + "http://10.0.0.1", + "http://toolstile.local", + "http://localhost.evil.test", + "http://127.0.0.1.nip.io", + "http://[::ffff:127.0.0.1]", + "http://0.0.0.0:4310", + ]) + expect(() => normalizeServer(bad), bad).toThrow(/https:\/\//); + expect(() => normalizeServer("https://user:pass@app.toolstile.com")).toThrow(/user name or password/); + expect(() => normalizeServer("ftp://app.toolstile.com")).toThrow(/https/); + }); + + it("keeps one sign-in per server and makes the latest one current", async () => { + const cloud = fakeServer(CLOUD); + const local = fakeServer(LOCAL, { edition: "self-hosted" }); + const { ctx } = context(network(cloud, local)); + await login(ctx, { browser: false }); + await login(ctx, { browser: false, local: true }); + let state = loadState(opts()); + expect(state.current).toBe(LOCAL); + expect(Object.keys(state.servers).sort()).toEqual([LOCAL, CLOUD].sort()); + expect(state.servers[CLOUD]).toMatchObject({ edition: "cloud", session: { email: "me@app.toolstile.com" } }); + expect(state.servers[LOCAL]).toMatchObject({ edition: "self-hosted", session: { email: "me@127.0.0.1:4310" } }); + // Signing in to the local server did not end the Cloud session. + expect(signOuts(cloud)).toEqual([]); + + // Signing in to the same server again replaces only that server's session. + await login(ctx, { browser: false, server: CLOUD }); + state = loadState(opts()); + expect(state.current).toBe(CLOUD); + expect(signOuts(cloud)).toEqual(["Bearer session-app.toolstile.com-1"]); + expect(state.servers[LOCAL]?.session?.token).toBe("session-127.0.0.1:4310-1"); + }); + + it("lets TOOLSTILE_SERVER pick a saved sign-in, and --server win over it", async () => { + const cloud = fakeServer(CLOUD); + const local = fakeServer(LOCAL, { edition: "self-hosted" }); + const { ctx, output } = context(network(cloud, local)); + await login(ctx, { browser: false, local: true }); + await login(ctx, { browser: false, server: CLOUD }); + expect(loadState(opts()).current).toBe(CLOUD); + ctx.env = env({ TOOLSTILE_SERVER: LOCAL }); + expect(whoami(ctx, {})).toBe(0); + expect(output()).toContain("me@127.0.0.1:4310 on http://127.0.0.1:4310 (self-hosted), expires 2030-01-01T00:00:00.000Z"); + expect(whoami(ctx, { server: CLOUD })).toBe(0); + expect(output()).toContain("me@app.toolstile.com on https://app.toolstile.com (cloud)"); + // The alias still works. + ctx.env = env({ TOOLSTILE_URL: LOCAL }); + expect(whoami(ctx, { json: true })).toBe(0); + expect(JSON.parse(output().slice(output().lastIndexOf("{\n")))).toEqual({ + signedIn: true, + server: LOCAL, + edition: "self-hosted", + email: "me@127.0.0.1:4310", + expiresAt: "2030-01-01T00:00:00.000Z", + expired: false, + }); + }); +}); + +describe("--local", () => { + const instance = (data: unknown) => { + const dir = join(home, "data"); + put(join(dir, "instance.json"), typeof data === "string" ? data : JSON.stringify(data)); + return { TOOLSTILE_DATA_DIR: dir }; + }; + + it("defaults to 127.0.0.1:4310 and ~/.local/share/toolstile", () => { + expect(localDataDir({ home, env: {} })).toBe(join(home, ".local", "share", "toolstile")); + expect(localServer({ home, env: {} })).toBe(DEFAULT_LOCAL_SERVER); + put(join(home, ".local", "share", "toolstile", "instance.json"), JSON.stringify({ origin: "http://127.0.0.1:4555" })); + expect(localServer({ home, env: {} })).toBe("http://127.0.0.1:4555"); + }); + + it("signs in to the origin in instance.json without reading its secrets into output or credentials", async () => { + const dataEnv = instance({ + version: 1, + origin: "http://localhost:4399", + host: "127.0.0.1", + port: 4399, + authSecret: SECRET, + encryptionKey: `${SECRET}-key`, + }); + const local = fakeServer("http://localhost:4399", { edition: "self-hosted" }); + const { ctx, output, errors } = context(network(local), dataEnv); + expect(await login(ctx, { browser: false, local: true })).toBe(0); + expect(output()).toContain("http://localhost:4399/auth/device?user_code=ABCDEFGH&device_name=box"); + expect(status(ctx, { json: true })).toBe(0); + const credentials = readFileSync(statePath(opts()), "utf8"); + for (const text of [output(), errors(), credentials]) expect(text).not.toContain(SECRET); + expect(loadState(opts()).current).toBe("http://localhost:4399"); + }); + + it("reports a broken instance.json without quoting it", () => { + for (const data of [`{"authSecret": "${SECRET}",`, { origin: `http://192.168.1.5:4310/${SECRET}`, authSecret: SECRET }, { origin: 42 }]) { + const dataEnv = instance(data); + let message = ""; + try { + localServer({ home, env: dataEnv }); + } catch (error) { + message = (error as Error).message; + } + expect(message).toMatch(/instance\.json (is not valid JSON|has no valid origin)\. Use --server instead of --local\.$/); + expect(message).not.toContain(SECRET); + } + }); + + it("works from the command line, and never prints the instance's secrets", () => { + const dataEnv = instance({ origin: "http://127.0.0.1:9", authSecret: SECRET }); + const cli = join(import.meta.dirname, "..", "dist", "cli.js"); + const { TOOLSTILE_URL: _, TOOLSTILE_SERVER: __, ...inherited } = process.env; + const run = (...args: string[]) => + spawnSync(process.execPath, [cli, ...args], { env: { ...inherited, ...env(dataEnv), HOME: home }, encoding: "utf8" }); + const setupRun = run("mcp", "setup", "--local", "--enable", "cursor", "--no-browser"); + expect(setupRun.status).toBe(1); + expect(setupRun.stderr).toContain("Could not reach http://127.0.0.1:9"); + const loginRun = run("auth", "login", "--local", "--no-browser"); + expect(loginRun.stderr).toContain("Could not reach http://127.0.0.1:9"); + for (const result of [setupRun, loginRun]) expect(result.stdout + result.stderr).not.toContain(SECRET); + expect(run("auth", "login", "--local", "--server", CLOUD).stderr).toContain("Use either --server or --local, not both."); + expect(run("auth", "logout", "--all", "--local").stderr).toContain("--all signs out of every server"); + const who = run("whoami", "--json"); + expect(who.status).toBe(1); + expect(JSON.parse(who.stdout)).toEqual({ signedIn: false, server: CLOUD }); + expect(run("auth", "status").stdout).toContain(`Not signed in. Current server: ${CLOUD}`); + expect(run("auth", "--help").stdout).toContain("--local"); + expect(run("mcp", "setup", "--help").stdout).toContain("--switch"); + }); +}); + +describe("editions", () => { + it("sends no workspaceId to a self-hosted server and asks for no workspace", async () => { + mkdirSync(join(home, ".cursor")); + const local = fakeServer(LOCAL, { edition: "self-hosted" }); + const { ctx, output } = context(network(local)); + expect(await setup(ctx, { local: true, enable: "cursor" })).toBe(0); + expect(output()).toContain(`${LOCAL}/auth/device?user_code=ABCDEFGH&device_name=box&next=setup`); + expect(output()).toContain(`Choose which MCP servers they can use in the dashboard at ${LOCAL}`); + const link = loadState(opts()).agents.cursor!; + expect(link).toEqual({ + id: "agent-1", + server: LOCAL, + endpoint: `${LOCAL}/mcp`, + label: "Cursor", + token: "token-127.0.0.1:4310-agent-1", + }); + expect(loadState(opts()).servers[LOCAL]).not.toHaveProperty("workspace"); + expect(await setup(ctx, { local: true, disable: "cursor" })).toBe(0); + expect(local.agents.size).toBe(0); + const cli = local.requests.filter((r) => r.url.pathname.startsWith("/api/cli/") && r.url.pathname !== "/api/cli/account"); + expect(cli.map((r) => `${r.method} ${r.url.pathname}`)).toEqual([ + "POST /api/cli/device", + "POST /api/cli/agents", + "GET /api/cli/agents", + "DELETE /api/cli/agents/agent-1", + ]); + for (const request of cli) { + expect(request.url.search, request.url.href).not.toContain("workspaceId"); + expect(request.body ?? {}).not.toHaveProperty("workspaceId"); + } + }); + + it("treats a server that reports no edition as Toolstile Cloud", async () => { + mkdirSync(join(home, ".cursor")); + const cloud = fakeServer(CLOUD); + const { ctx, output } = context(network(cloud)); + expect(await setup(ctx, { enable: "cursor" })).toBe(0); + expect(loadState(opts()).servers[CLOUD]).toMatchObject({ edition: "cloud", workspace: { id: "w1" } }); + expect(loadState(opts()).agents.cursor?.workspaceId).toBe("w1"); + expect(cloud.requests.find((r) => r.method === "POST" && r.url.pathname === "/api/cli/agents")?.body).toMatchObject({ + workspaceId: "w1", + }); + expect(output()).toContain(`Choose which MCP servers they can use: ${CLOUD}/personal/access`); + status(ctx, {}); + expect(output()).toContain("* me@app.toolstile.com on https://app.toolstile.com (cloud)"); + }); + + it("keeps a self-hosted gateway on the server's own origin, and Cloud's on its own host", async () => { + mkdirSync(join(home, ".cursor")); + mkdirSync(join(home, ".codex")); + const local = fakeServer(LOCAL, { edition: "self-hosted", mcpUrl: "https://elsewhere.example/mcp" }); + const cloud = fakeServer(CLOUD, { edition: "cloud", mcpUrl: "https://mcp.toolstile.com/mcp" }); + const { ctx } = context(network(local, cloud)); + expect(await setup(ctx, { local: true, enable: "cursor" })).toBe(0); + expect(loadState(opts()).agents.cursor?.endpoint).toBe(`${LOCAL}/mcp`); + expect(await setup(ctx, { server: CLOUD, enable: "codex" })).toBe(0); + expect(loadState(opts()).agents.codex?.endpoint).toBe("https://mcp.toolstile.com/mcp"); + }); + + it("rejects --workspace on a self-hosted server", async () => { + mkdirSync(join(home, ".cursor")); + const local = fakeServer(LOCAL, { edition: "self-hosted" }); + const { ctx } = context(network(local)); + const message = `--workspace only applies to Toolstile Cloud; ${LOCAL} is a self-hosted server and has no workspaces.`; + // First sign-in: the edition is only known once the server answers, and nothing is set up. + await expect(setup(ctx, { local: true, enable: "cursor", workspace: "personal" })).rejects.toThrow(message); + expect(local.agents.size).toBe(0); + expect(loadState(opts()).agents).toEqual({}); + // Afterwards the saved edition rejects it before any request. + const before = local.requests.length; + await expect(setup(ctx, { local: true, enable: "cursor", workspace: "personal" })).rejects.toThrow(message); + expect(local.requests.length).toBe(before); + expect(message).not.toContain("\n"); + }); +}); + +describe("logout", () => { + async function signedInTwice() { + const cloud = fakeServer(CLOUD); + const local = fakeServer(LOCAL, { edition: "self-hosted" }); + const { ctx, output } = context(network(cloud, local)); + await login(ctx, { browser: false }); + await login(ctx, { browser: false, local: true }); + return { cloud, local, ctx, output }; + } + + it("signs out of the current server only", async () => { + const { cloud, local, ctx, output } = await signedInTwice(); + expect(await logout(ctx)).toBe(0); + expect(output()).toContain(`Signed out of ${LOCAL}.`); + expect(signOuts(local)).toEqual(["Bearer session-127.0.0.1:4310-1"]); + expect(signOuts(cloud)).toEqual([]); + const state = loadState(opts()); + expect(state.servers[LOCAL]?.session).toBeUndefined(); + expect(state.servers[CLOUD]?.session).toBeDefined(); + expect(await logout(ctx)).toBe(0); + expect(output()).toContain(`Not signed in to ${LOCAL}.`); + }); + + it("signs out of the server named by --server or --local", async () => { + const { cloud, local, ctx } = await signedInTwice(); + expect(await logout(ctx, { server: CLOUD })).toBe(0); + expect(signOuts(cloud)).toHaveLength(1); + expect(loadState(opts()).servers[LOCAL]?.session).toBeDefined(); + ctx.env = env({ TOOLSTILE_SERVER: CLOUD }); + expect(await logout(ctx, { local: true })).toBe(0); + expect(signOuts(local)).toHaveLength(1); + }); + + it("signs out everywhere with --all, each session at its own server", async () => { + const { cloud, local, ctx, output } = await signedInTwice(); + mkdirSync(join(home, "cfg"), { recursive: true }); + expect(await logout(ctx, { all: true })).toBe(0); + expect(signOuts(cloud)).toEqual(["Bearer session-app.toolstile.com-1"]); + expect(signOuts(local)).toEqual(["Bearer session-127.0.0.1:4310-1"]); + expect(output()).toContain(`Signed out of ${CLOUD}.`); + expect(output()).toContain(`Signed out of ${LOCAL}.`); + expect(Object.values(loadState(opts()).servers).every((entry) => !entry.session)).toBe(true); + expect(await logout(ctx, { all: true })).toBe(0); + expect(output()).toContain("Not signed in."); + await expect(logout(ctx, { all: true, server: CLOUD })).rejects.toThrow("--all"); + }); + + it("names the server in the sign-in hint when it is not the one plain auth login would use", async () => { + const local = fakeServer(LOCAL, { edition: "self-hosted" }); + const { ctx, output } = context(network(local)); + await login(ctx, { browser: false, local: true }); + expect(whoami(ctx, { server: CLOUD })).toBe(1); + expect(output()).toContain(`Not signed in to ${CLOUD}. Sign in with toolstile auth login --server ${CLOUD}`); + }); + + it("quotes an IPv6 origin in the hint and ignores an invalid TOOLSTILE_SERVER when --server is given", () => { + const { ctx, output } = context(network(), { TOOLSTILE_SERVER: "not a url" }); + expect(whoami(ctx, { server: "http://[::1]:4310" })).toBe(1); + expect(output()).toContain("Sign in with toolstile auth login --server 'http://[::1]:4310'"); + expect(whoami(ctx, { server: "https://o'brien.example" })).toBe(1); + expect(output()).toContain(`Sign in with toolstile auth login --server 'https://o'\\''brien.example'`); + ctx.platform = "win32"; + expect(whoami(ctx, { server: "http://[::1]:4310" })).toBe(1); + expect(output()).toContain(`Sign in with toolstile auth login --server "http://[::1]:4310"`); + expect(whoami(ctx, { server: "https://a$b.example" })).toBe(1); + expect(output()).toContain("Sign in with toolstile auth login --server
, with https://a$b.example as the address"); + expect(whoami(ctx, { server: CLOUD, json: true })).toBe(1); + expect(output()).toContain('"signedIn": false'); + }); + + it("lists sign-ins in auth status", async () => { + const { ctx, output } = await signedInTwice(); + expect(status(ctx, { json: true })).toBe(0); + expect(JSON.parse(output().slice(output().lastIndexOf("{\n \"current\"")))).toEqual({ + current: LOCAL, + signIns: [ + { server: CLOUD, edition: "cloud", email: "me@app.toolstile.com", expiresAt: "2030-01-01T00:00:00.000Z", expired: false, current: false }, + { server: LOCAL, edition: "self-hosted", email: "me@127.0.0.1:4310", expiresAt: "2030-01-01T00:00:00.000Z", expired: false, current: true }, + ], + }); + ctx.now = () => Date.parse("2031-01-01T00:00:00.000Z"); + expect(status(ctx, {})).toBe(0); + expect(output()).toContain(` me@app.toolstile.com on ${CLOUD} (cloud), expired 2030-01-01T00:00:00.000Z`); + expect(output()).toContain(`* me@127.0.0.1:4310 on ${LOCAL} (self-hosted), expired`); + expect(whoami(ctx, {})).toBe(1); + }); +}); + +describe("agents on several servers", () => { + async function cursorOnCloud(options: { local?: boolean } = {}) { + mkdirSync(join(home, ".cursor")); + mkdirSync(join(home, ".codex")); + const cloud = fakeServer(CLOUD); + const local = fakeServer(LOCAL, { edition: "self-hosted" }); + const { ctx, output } = context(network(cloud, local)); + await setup(ctx, { enable: "cursor" }); + if (options.local) await login(ctx, { browser: false, local: true }); + return { cloud, local, ctx, output }; + } + + it("lets agents use different servers side by side", async () => { + const { cloud, local, ctx } = await cursorOnCloud(); + expect(await setup(ctx, { local: true, enable: "codex" })).toBe(0); + const { agents } = loadState(opts()); + expect(agents.cursor?.server).toBe(CLOUD); + expect(agents.codex?.server).toBe(LOCAL); + expect(readEntry(target("cursor"))).toBeDefined(); + expect(cloud.agents.size).toBe(1); + expect(local.agents.size).toBe(1); + // Setup on the local server leaves the Cloud agent alone, even when it is not selected. + expect(await setup(ctx, { local: true, disable: "codex" })).toBe(0); + expect(loadState(opts()).agents.cursor?.server).toBe(CLOUD); + expect(cloud.requests.some((r) => r.method === "DELETE")).toBe(false); + }); + + it("needs --switch to move an agent to another server without a terminal", async () => { + const { cloud, local, ctx } = await cursorOnCloud({ local: true }); + const before = local.requests.length; + await expect(setup(ctx, { local: true, enable: "cursor" })).rejects.toThrow( + `Cursor uses ${CLOUD}. Add --switch to move it to ${LOCAL}.`, + ); + expect(local.requests.length).toBe(before); + expect(loadState(opts()).agents.cursor?.server).toBe(CLOUD); + + expect(await setup(ctx, { local: true, enable: "cursor", switch: true })).toBe(0); + const link = loadState(opts()).agents.cursor!; + expect(link.server).toBe(LOCAL); + expect(link.workspaceId).toBeUndefined(); + // The Cloud authorization was removed with the Cloud sign-in. + const removal = cloud.requests.find((r) => r.method === "DELETE"); + expect(removal?.auth).toBe(`Bearer ${cloud.session()}`); + expect(removal?.url.searchParams.get("workspaceId")).toBe("w1"); + expect(cloud.agents.size).toBe(0); + }); + + it("asks before moving an agent when there is a terminal", async () => { + const { local, ctx, output } = await cursorOnCloud({ local: true }); + const keys = terminal(ctx); + const answer = async (...input: string[]) => { + await vi.waitFor(() => expect(output()).toContain(`Cursor uses ${CLOUD}. Switch it to ${LOCAL}?`)); + for (const key of input) keys.write(key); + }; + let run = setup(ctx, { local: true, enable: "cursor" }); + await answer("\r"); + expect(await run).toBe(0); + expect(loadState(opts()).agents.cursor?.server).toBe(CLOUD); + expect(local.agents.size).toBe(0); + + (ctx.stdout as PassThrough).write("\n---\n"); + run = setup(ctx, { local: true, enable: "cursor" }); + await vi.waitFor(() => expect(output().split("---").at(-1)).toContain("Switch it to")); + keys.write("j"); + keys.write("\r"); + expect(await run).toBe(0); + expect(loadState(opts()).agents.cursor?.server).toBe(LOCAL); + }); + + it("turns off an agent on another server with --disable, revoking it there", async () => { + const { cloud, ctx } = await cursorOnCloud({ local: true }); + expect(await setup(ctx, { local: true, disable: "cursor" })).toBe(0); + expect(loadState(opts()).agents.cursor).toBeUndefined(); + expect(readEntry(target("cursor"))).toBeUndefined(); + expect(cloud.agents.size).toBe(0); + }); + + it("reports an old authorization it could not remove because that server is unreachable", async () => { + const { local, ctx, cloud } = await cursorOnCloud({ local: true }); + const { ctx: offline, errors } = context(network(local)); + expect(await setup({ ...ctx, api: offline.api, stderr: offline.stderr }, { local: true, enable: "cursor", switch: true })).toBe(0); + expect(loadState(opts()).agents.cursor?.server).toBe(LOCAL); + expect(cloud.agents.size).toBe(1); + expect(errors()).toContain(`Could not confirm removal of the old Cursor authorization (agent-1) at ${CLOUD}.`); + }); + + it("warns when the old server refuses the removal during a switch", async () => { + const { local, ctx, cloud } = await cursorOnCloud({ local: true }); + const refusing = network(local, cloud); + const { ctx: other, errors } = context(((input: string | URL | Request, init?: RequestInit) => + init?.method === "DELETE" && String(input).startsWith(CLOUD) + ? Promise.resolve(Response.json({ message: "Forbidden" }, { status: 403 })) + : refusing(input, init)) as typeof fetch); + expect(await setup({ ...ctx, api: other.api, stderr: other.stderr }, { local: true, enable: "cursor", switch: true })).toBe(0); + expect(cloud.agents.size).toBe(1); + expect(errors()).toContain(`Could not confirm removal of the old Cursor authorization (agent-1) at ${CLOUD}.`); + }); + + it("says where to remove access it could not revoke", async () => { + const { cloud, ctx, output } = await cursorOnCloud({ local: true }); + await logout(ctx, { server: CLOUD }); + expect(await setup(ctx, { local: true, enable: "cursor", switch: true })).toBe(0); + expect(cloud.agents.size).toBe(1); + expect(output()).toContain(`Cursor's access on ${CLOUD} was not removed because this machine is not signed in there.`); + }); +}); + +describe("proxy pinning", () => { + function linked() { + const state = loadState(opts()); + state.agents.cursor = { id: "a", workspaceId: "w1", server: CLOUD, endpoint: "https://mcp.toolstile.com/mcp", label: "Cursor", token: "cloud-token" }; + state.agents.codex = { id: "b", server: LOCAL, endpoint: `${LOCAL}/mcp`, label: "Codex", token: "local-token" }; + saveState(state, opts()); + } + + async function relay(ctx: Context, agent: string) { + const input = new PassThrough(); + ctx.stdin = input; + const done = proxy(ctx, agent); + input.end(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })}\n`); + return done; + } + + it("sends each agent's token only to the server that issued it", async () => { + linked(); + const seen: { url: string; auth: string | undefined; redirect: RequestRedirect | undefined }[] = []; + // A project's environment and flags cannot move the proxy elsewhere. + const { ctx } = context(network(), { TOOLSTILE_SERVER: "https://evil.example" }); + ctx.fetch = (async (url: string | URL | Request, init?: RequestInit) => { + seen.push({ url: String(url), auth: (init?.headers as Record)?.Authorization, redirect: init?.redirect }); + if (init?.method === "GET" || init?.method === "DELETE") return new Response(null, { status: 405 }); + return Response.json({ jsonrpc: "2.0", id: 1, result: {} }); + }) as typeof fetch; + expect(await relay(ctx, "cursor")).toBe(0); + expect(await relay(ctx, "codex")).toBe(0); + const byToken = (token: string) => new Set(seen.filter((s) => s.auth === `Bearer ${token}`).map((s) => new URL(s.url).origin)); + expect(byToken("cloud-token")).toEqual(new Set(["https://mcp.toolstile.com"])); + expect(byToken("local-token")).toEqual(new Set([LOCAL])); + expect(seen.some((s) => s.url.includes("evil"))).toBe(false); + expect(seen.every((s) => s.redirect === "error")).toBe(true); + }); + + it("does not follow a redirect to another server", async () => { + const hits: { server: string; auth: string | undefined }[] = []; + const other = createServer((request, response) => { + hits.push({ server: "other", auth: request.headers.authorization }); + response.end(); + }); + other.listen(0, "127.0.0.1"); + await once(other, "listening"); + const otherPort = (other.address() as AddressInfo).port; + const gateway = createServer((request, response) => { + hits.push({ server: "gateway", auth: request.headers.authorization }); + response.writeHead(307, { location: `http://127.0.0.1:${otherPort}/mcp` }).end(); + }); + gateway.listen(0, "127.0.0.1"); + await once(gateway, "listening"); + const gatewayPort = (gateway.address() as AddressInfo).port; + try { + const state = loadState(opts()); + state.agents.cursor = { id: "a", server: `http://127.0.0.1:${gatewayPort}`, label: "Cursor", token: "pinned-token" }; + saveState(state, opts()); + const { ctx } = context(network()); + expect(await relay(ctx, "cursor")).toBe(0); + expect(hits.filter((h) => h.server === "gateway").every((h) => h.auth === "Bearer pinned-token")).toBe(true); + expect(hits.some((h) => h.server === "gateway")).toBe(true); + expect(hits.filter((h) => h.server === "other")).toEqual([]); + } finally { + for (const server of [gateway, other]) { + server.closeAllConnections(); + server.close(); + } + } + }); + + it("refuses a saved gateway address that is not HTTPS or loopback", async () => { + const state = loadState(opts()); + state.agents.cursor = { id: "a", server: CLOUD, endpoint: "http://gateway.example/mcp", label: "Cursor", token: "t" }; + saveState(state, opts()); + const { ctx } = context(network()); + await expect(proxy(ctx, "cursor")).rejects.toThrow("saved gateway address is not HTTPS"); + }); +});