diff --git a/README.md b/README.md index 831d8e2..c96a89d 100644 --- a/README.md +++ b/README.md @@ -174,19 +174,23 @@ values) and prints a ready-to-post link. To post the text report instead, add If you use [Toolstile](https://www.toolstile.com) ([free account](https://app.toolstile.com/auth/sign-up)), the CLI can also sign in -and set up the agents on a machine for you: +and set up the agents on a machine for you, in one command: ```sh -npx toolstile auth login -npx toolstile mcp setup +npx toolstile mcp setup --enable claude-code ``` -`auth login` prints a link and a code. Open the link on any device with a -browser (your laptop or phone) and sign in. The page fills in the code and this -machine's name; edit the name if you like, check the code matches and approve. -The machine appears under that name in the Toolstile dashboard. Nothing has to -reach the machine you are signing in, so it works over SSH, in containers and on -servers without a browser. +If the machine is not signed in yet, `mcp setup` first prints a link and a code. +Open the link on any device with a browser (your laptop or phone) and sign in. +The page fills in the code and this machine's name; edit the name if you like, +check the code matches and approve. Setup then carries on by itself. The machine +appears under that name in the Toolstile dashboard. Nothing has to reach the +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. `mcp setup` lists the agents it finds (Claude Code, Claude Desktop, Cursor, Codex, VS Code, Windsurf, Devin Desktop, Gemini CLI, Cline, Grok Build, OpenCode, @@ -225,8 +229,8 @@ dashboard. | Option | Command | Meaning | | --- | --- | --- | -| `--server ` | `auth login` | Toolstile address (default `https://app.toolstile.com`, or `TOOLSTILE_URL`) | -| `--no-browser` | `auth login` | Do not try to open a browser on this machine | +| `--server ` | `auth login`, `mcp setup` | Toolstile address (default `https://app.toolstile.com`, or `TOOLSTILE_URL`) | +| `--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) | diff --git a/src/cli.ts b/src/cli.ts index 7042d91..b786029 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -83,16 +83,21 @@ Usage npx toolstile mcp proxy --agent setup lists the agents found here and lets you turn each one on or off. -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. +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 +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. 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) --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 + --no-browser Do not try to open a browser when signing in Agents: claude-code, claude-desktop, cursor, codex, vscode, windsurf, devin, gemini, cline, grok, opencode, kiro, antigravity @@ -252,7 +257,7 @@ async function command(argv: string[]): Promise { : action === "logout" ? parseFlags(rest, [], []) : action === "setup" - ? parseFlags(rest, ["enable", "disable", "workspace", "device-name"], []) + ? parseFlags(rest, ["enable", "disable", "workspace", "device-name", "server"], ["no-browser"]) : parseFlags(rest, ["agent"], []); if (flags === "help") { process.stdout.write(help); @@ -267,6 +272,8 @@ async function command(argv: string[]): Promise { disable: value("disable"), workspace: value("workspace"), deviceName: value("device-name"), + server: value("server"), + browser: !flags["no-browser"], }); return await proxy(ctx, value("agent")); } catch (error) { diff --git a/src/commands.ts b/src/commands.ts index 531a2c5..eddebbf 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -3,7 +3,7 @@ import { hostname } from "node:os"; 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 Api, ApiError, type Workspace } from "./api.js"; +import { type Account, type Api, ApiError, type Workspace } from "./api.js"; import { checklist } from "./prompt.js"; import { runProxy } from "./proxy.js"; import { type Style, tildify } from "./report.js"; @@ -117,17 +117,33 @@ const machineName = (ctx: Context) => (ctx.hostname ?? hostname)().replace(/\.lo const formatCode = (code: string) => (code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code); -export async function login(ctx: Context, options: { server?: string; browser: boolean }): Promise { +/** 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; + /** Set when `mcp setup` signs in and then carries on by itself. */ + next?: "setup"; + /** Prefilled on the approval page instead of the hostname. */ + deviceName?: string; +} + +/** + * 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. + */ +async function signIn(ctx: Context, state: State, server: string, options: SignInOptions): Promise { const s = ctx.style; - const state = loadState(stateEnv(ctx)); - const server = normalizeServer(options.server ?? ctx.env.TOOLSTILE_URL ?? state.server); const api = ctx.api(server); const code = await api.deviceCode(); // The page fills in the code and this machine's name; the name can be edited there and // becomes the device this machine's agents are listed under. const link = signInUrl(code.verification_uri_complete, server); if (link) { - link.searchParams.set("device_name", machineName(ctx)); + link.searchParams.set("device_name", options.deviceName ?? machineName(ctx)); + // Tells the page the terminal goes on with setup by itself once this is approved. + if (options.next) link.searchParams.set("next", options.next); print(ctx, `Open this link on any device with a browser and approve the sign-in:`); print(ctx); print(ctx, ` ${s.bold(link.href)}`); @@ -170,10 +186,9 @@ export async function login(ctx: Context, options: { server?: string; browser: b } const previous = state.session; const previousServer = previous?.server ?? state.server; - let deviceLabel: string | undefined; + let account: Account; try { - const account = await api.account(token); - deviceLabel = account.device?.label; + account = await api.account(token); if (server !== state.server || (previous && previous.email !== account.email)) { // Another account's workspace and device do not apply; agents keep their own access. delete state.workspace; @@ -184,7 +199,7 @@ export async function login(ctx: Context, options: { server?: string; browser: b if (account.device) state.device = account.device; saveState(state, stateEnv(ctx)); } catch (error) { - await compensate(error, async () => { + 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); @@ -193,12 +208,18 @@ export async function login(ctx: Context, options: { server?: string; browser: b // 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); - const account = state.session!; + const deviceLabel = account.device?.label; print(ctx); print( ctx, - `Signed in as ${s.bold(account.email)}${deviceLabel ? ` on ${s.bold(deviceLabel)}` : ""}. Next: ${s.bold("toolstile mcp setup")}`, + `Signed in as ${s.bold(state.session!.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 { + const state = loadState(stateEnv(ctx)); + await signIn(ctx, state, signInServer(ctx, state, options.server), { browser: options.browser }); return 0; } @@ -247,8 +268,16 @@ export interface SetupOptions { 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; } +/** "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) { if (wanted) { const value = wanted.toLowerCase(); @@ -272,19 +301,38 @@ async function chooseWorkspace(ctx: Context, state: State, workspaces: Workspace export async function setup(ctx: Context, options: SetupOptions): Promise { const s = ctx.style; - const state = loadState(stateEnv(ctx)); - const session = state.session; - if (!session) throw new UserError("Sign in first: toolstile auth login"); - const api = ctx.api(session.server ?? state.server); - const account = await api.account(session.token).catch((error: unknown) => { - if (error instanceof ApiError && error.status === 401) - throw new UserError("Your sign-in has expired. Run toolstile auth login again."); - throw error; - }); + // Check the flags before any sign-in, so a typo does not cost a trip to the browser. const enable = parseClients(options.enable, "--enable"); const disable = parseClients(options.disable, "--disable"); const both = enable.find((c) => 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; + 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); + // 401: the saved session has expired, so sign in again below. + account = await candidate.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); // The gateway can be on another host; only an HTTPS URL from this server is used. const endpoint = gatewayUrl(account.mcpUrl) ?? `${state.server}/mcp`; @@ -361,6 +409,7 @@ export async function setup(ctx: Context, options: SetupOptions): Promise writeEntry(target, proxyCommand(target.client, ctx.version, ctx.platform))); - if (!live(target.client) || result !== "unchanged") changes.push(`${s.bold("+")} ${target.name} ${s.dim(tildify(target.path, ctx.home))}`); + if (!live(target.client) || result !== "unchanged") { + changes.push(`${s.bold("+")} ${target.name} ${s.dim(tildify(target.path, ctx.home))}`); + turnedOn.push(target.name); + } if (result === "replaced") replaced.push(target.name); } catch (error) { @@ -433,7 +485,12 @@ export async function setup(ctx: Context, options: SetupOptions): Promise { expect(await logout(ctx)).toBe(0); expect(loadState({ home, env: env() }).session).toBeUndefined(); - await expect(setup(ctx, {})).rejects.toThrow(/auth login/); + // Setup signs in again by itself instead of failing. + expect(await setup(ctx, {})).toBe(0); + expect(loadState({ home, env: env() }).session?.token).toBe("session"); }); it("keeps tokens on the server that issued them", async () => { @@ -639,6 +642,207 @@ describe("auth and setup", () => { }); }); +describe("setup signs in when needed", () => { + const cli = join(import.meta.dirname, "..", "dist", "cli.js"); + + /** An API per server that links to its own approval page and records device-code requests. */ + function servers(api: Api) { + const used: string[] = []; + const codes: string[] = []; + const forServer = (server: string): Api => { + used.push(server); + return { + ...api, + deviceCode: async () => { + codes.push(server); + return { + ...(await api.deviceCode()), + verification_uri: `${server}/device`, + verification_uri_complete: `${server}/device?user_code=ABCDEFGH`, + }; + }, + }; + }; + return { forServer, used, codes }; + } + + it("signs in, then enables the agent and writes its config in the same run", async () => { + mkdirSync(join(home, ".claude")); + const { api, calls } = fakeApi(); + const { ctx, output } = context(api); + const opened: string[] = []; + ctx.openBrowser = (url) => opened.push(url); + expect(await setup(ctx, { enable: "claude-code" })).toBe(0); + expect(opened).toEqual(["https://app.toolstile.com/device?user_code=ABCDEFGH&device_name=build-mac&next=setup"]); + expect(output()).toContain("https://app.toolstile.com/device?user_code=ABCDEFGH&device_name=build-mac&next=setup"); + expect(output()).toContain("Signed in as me@test.invalid.\n"); + expect(output()).not.toContain("Next:"); + 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.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"]); + }); + + it("honors --no-browser and prefills --device-name", async () => { + const { api } = fakeApi(); + const { ctx, output } = context(api); + const opened: string[] = []; + ctx.openBrowser = (url) => opened.push(url); + expect(await setup(ctx, { enable: "cursor", browser: false, deviceName: "box" })).toBe(0); + expect(opened).toEqual([]); + expect(output()).toContain("https://app.toolstile.com/device?user_code=ABCDEFGH&device_name=box&next=setup"); + }); + + it("signs in again when the saved session has expired", async () => { + const { api, calls } = fakeApi(); + const { ctx, output } = context(api); + await login(ctx, { browser: false }); + const account = api.account; + api.account = async (token) => { + if (token === "session") throw new ApiError(401, "Unauthorized"); + return account(token); + }; + api.deviceToken = async () => ({ access_token: "fresh", expires_in: 1 }); + const revoked: string[] = []; + 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(loadState({ home, env: env() }).agents.cursor?.id).toBe("a1"); + expect(revoked).toEqual(["session"]); + expect(calls).toContain("add:Cursor"); + }); + + it("signs in to a different --server and sets up the agent there", async () => { + const { api } = fakeApi(); + const { ctx } = context(api); + const { forServer, used, codes } = servers(api); + ctx.api = forServer; + await login(ctx, { browser: false }); + const revoked: string[] = []; + api.signOut = async (token) => { revoked.push(token); }; + 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"]); + 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.agents.cursor?.server).toBe("https://other.example"); + }); + + it("does not sign in when already signed in to the requested server", async () => { + mkdirSync(join(home, ".cursor")); + const { api } = fakeApi(); + const { ctx, output } = context(api); + 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. + ctx.env = { ...ctx.env, TOOLSTILE_URL: "https://other.example" }; + expect(await setup(ctx, { enable: "cursor" })).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); + expect(output()).toContain("Restart Cursor to pick up the change."); + // Only removals keep the generic line. + 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 () => { + const { api } = fakeApi(); + const { ctx } = context(api); + const { forServer, codes } = servers(api); + ctx.api = forServer; + ctx.env = { ...ctx.env, TOOLSTILE_URL: "https://other.example" }; + expect(await setup(ctx, { enable: "cursor" })).toBe(0); + expect(codes).toEqual(["https://other.example"]); + expect(loadState({ home, env: env() }).agents.cursor?.server).toBe("https://other.example"); + }); + + it("stops on a denied sign-in and changes nothing", async () => { + mkdirSync(join(home, ".cursor")); + const { api, calls } = fakeApi({ + deviceToken: async () => { + throw new ApiError(400, "denied", "access_denied"); + }, + }); + const { ctx } = context(api); + await expect(setup(ctx, { enable: "cursor" })).rejects.toThrow("Sign-in was denied in the browser."); + expect(calls).toEqual([]); + expect(readEntry(target("cursor"))).toBeUndefined(); + expect(() => statSync(statePath({ home, env: env() }))).toThrow(); + }); + + it("checks the agent flags before signing in", async () => { + const { api } = fakeApi(); + const { ctx } = context(api); + let asked = false; + api.deviceCode = async () => { + asked = true; + throw new Error("unexpected"); + }; + await expect(setup(ctx, { enable: "nope" })).rejects.toThrow(/unknown agent/); + expect(asked).toBe(false); + }); + + it("names every agent it turned on in the restart line", async () => { + const { api } = fakeApi(); + const { ctx, output } = context(api); + await login(ctx, { browser: false }); + await setup(ctx, { enable: "claude-code,codex" }); + expect(output()).toContain("Restart Claude Code and Codex to pick up the change."); + await setup(ctx, { enable: "cursor,windsurf,gemini" }); + expect(output()).toContain("Restart Cursor, Windsurf and Gemini CLI to pick up the change."); + }); + + it("keeps auth login's link and closing line as before", async () => { + const { api } = fakeApi(); + const { ctx, output } = context(api); + const opened: string[] = []; + ctx.openBrowser = (url) => opened.push(url); + await login(ctx, { browser: true }); + expect(opened).toEqual(["https://app.toolstile.com/device?user_code=ABCDEFGH&device_name=build-mac"]); + expect(output()).not.toContain("next="); + expect(output()).toBe( + [ + "Open this link on any device with a browser and approve the sign-in:", + "", + " https://app.toolstile.com/device?user_code=ABCDEFGH&device_name=build-mac", + "", + "Check that the page shows this code: ABCD-EFGH", + "Waiting for approval. The code expires in 10 minutes.", + "", + "Signed in as me@test.invalid. Next: toolstile mcp setup", + "", + ].join("\n"), + ); + }); + + it("accepts --server and --no-browser on the command line", () => { + const { TOOLSTILE_URL: _, ...inherited } = process.env; + const run = (...args: string[]) => + spawnSync(process.execPath, [cli, "mcp", "setup", ...args], { + env: { ...inherited, TOOLSTILE_CONFIG_DIR: join(home, "cfg"), HOME: home }, + encoding: "utf8", + }); + // Nothing listens on port 9, so the sign-in it starts fails to connect, after parsing. + const result = run("--enable", "cursor", "--server", "http://127.0.0.1:9", "--no-browser"); + expect(result.status).toBe(1); + expect(result.stderr).toContain("Could not reach http://127.0.0.1:9"); + expect(run("--server=http://127.0.0.1:9", "--no-browser", "--enable=cursor").stderr).toContain("Could not reach"); + expect(run("--server").stderr).toContain("--server needs a value"); + expect(run("--no-browser=1").stderr).toContain("Unknown option"); + expect(run("--server", "http://example.com").stderr).toContain("--server must use https://"); + expect(run("--help").stdout).toContain("--no-browser"); + }); +}); + describe("stdio proxy", () => { async function run(responses: ((init: RequestInit) => Response)[], lines: string[]) { const input = new PassThrough();