@zenlayer/lune-mcp 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,267 @@
1
- # Temporary Holding Version
1
+ # @zenlayer/lune-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP server for the Lune.io platform. It lets Claude, Cursor, and other AI
4
+ clients operate your Lune.io account directly: check model pricing, manage API keys, review
5
+ usage, credits and billing, set budgets, and run your organizations — workspaces, members
6
+ and invitations — and, for suppliers, manage listings and payouts.
7
+
8
+ > **Coming from `@zenlayer/tkex-mcp`?** The package, connector name, environment variables and
9
+ > server address all changed — see [Moving from @zenlayer/tkex-mcp](#moving-from-zenlayertkex-mcp).
10
+ > If you were on `@zenlayer/tkex-mcp` 1.0.2 or earlier, also read
11
+ > [Tool changes since tkex-mcp 1.0.2](#tool-changes-since-tkex-mcp-102).
12
+
13
+ ## What you can do
14
+
15
+ Once connected, just ask your AI client:
16
+
17
+ - "What does DeepSeek V4 cost per million tokens on Lune.io?"
18
+ - "Create an API key in the Production workspace that can only call qwen3.7-plus, capped at $50."
19
+ - "How much did the Production workspace spend this week, and did any requests fail?"
20
+ - "Cap the Staging workspace at $200 a month."
21
+ - "Invite alice@example.com to Acme as a member."
22
+ - "Which workspace in Acme spent the most this month?"
23
+ - Suppliers: "Show this week's net earnings — any failed payouts?"
24
+
25
+ ## Quick start
26
+
27
+ Two transports; pick either one. Both can be configured automatically with a single CLI
28
+ command, or by hand.
29
+
30
+ ### a. Remote (recommended)
31
+
32
+ The service runs at `https://www.lune.io/mcp` (Streamable HTTP). Nothing runs on your
33
+ machine — the first tool call opens a browser sign-in to authorize your Lune.io account.
34
+
35
+ **Automatic:**
36
+
37
+ ```bash
38
+ npx @zenlayer/lune-mcp install
39
+ ```
40
+
41
+ **Manual:**
42
+
43
+ - **Claude Code**: `claude mcp add --transport http lune-io https://www.lune.io/mcp`
44
+ - **claude.ai / Claude Desktop**: Settings → Connectors → Add custom connector, Name `Lune.io`, URL `https://www.lune.io/mcp`
45
+ - **Cursor**: add `"lune-io": { "url": "https://www.lune.io/mcp" }` under `mcpServers` in `~/.cursor/mcp.json`
46
+ - **VS Code**: `code --add-mcp '{"name":"lune-io","type":"http","url":"https://www.lune.io/mcp"}'`
47
+ - **Codex CLI**: `codex mcp add lune-io --url https://www.lune.io/mcp`
48
+ - **Gemini CLI**: `gemini mcp add -t http lune-io https://www.lune.io/mcp`
49
+
50
+ ### b. Local stdio
51
+
52
+ The MCP server runs on your machine via npx — for environments that cannot reach the
53
+ remote endpoint directly.
54
+
55
+ **Automatic:**
56
+
57
+ ```bash
58
+ npx @zenlayer/lune-mcp install --stdio
59
+ npx @zenlayer/lune-mcp login
60
+ ```
61
+
62
+ **Manual:**
63
+
64
+ - **Claude Code**: `claude mcp add lune-io -- npx -y @zenlayer/lune-mcp@1 mcp`
65
+ - **Codex CLI**: `codex mcp add lune-io -- npx -y @zenlayer/lune-mcp@1 mcp`
66
+ - **Gemini CLI**: `gemini mcp add lune-io npx -y @zenlayer/lune-mcp@1 mcp`
67
+ - **VS Code**: `code --add-mcp '{"name":"lune-io","command":"npx","args":["-y","@zenlayer/lune-mcp@1","mcp"]}'`
68
+ - **Cursor**: add
69
+ `"lune-io": { "command": "npx", "args": ["-y", "@zenlayer/lune-mcp@1", "mcp"] }`
70
+ under `mcpServers` in `~/.cursor/mcp.json`
71
+ - **Claude Desktop**: add the same entry as Cursor under `mcpServers` in
72
+ `claude_desktop_config.json` (macOS `~/Library/Application Support/Claude/`,
73
+ Windows `%APPDATA%\Claude\`)
74
+
75
+ On Windows, write the launch command as `cmd /c npx -y @zenlayer/lune-mcp@1 mcp`.
76
+
77
+ ## Sign-in and authorization
78
+
79
+ - Both transports authorize through browser OAuth against your Lune.io account — **no tokens
80
+ to copy and paste**.
81
+ - The remote transport asks for up to five permissions: `buyer:read`, `buyer:write` and
82
+ `buyer:admin` (members, invitations, workspaces, access policies, organization settings,
83
+ creating organizations), plus
84
+ `supplier:read` / `supplier:write` for supplier accounts. It shows only the granted tools.
85
+
86
+ ## Tools (50)
87
+
88
+ Tools marked ✏️ are write operations; every one goes through two-step confirmation (see below).
89
+
90
+ ### Public (2)
91
+
92
+ | Tool | What it does |
93
+ |---|---|
94
+ | `list_public_models` | Model catalog and public pricing |
95
+ | `search_docs` | Official platform documentation |
96
+
97
+ ### Lune.io Console (31)
98
+
99
+ Every buyer tool works in one of your contexts — your personal space or an organization you
100
+ belong to — and, where it applies, one of its workspaces. Name them with `project_id` /
101
+ `workspace_id` (an id, a Lune.io Console URL, or an exact name); with only one, it is picked
102
+ automatically, and with several the tool lists the choices instead of guessing. Each result
103
+ says which organization and workspace it covers. What you can do follows your role: asking
104
+ for something it can't do gets a plain "your role does not allow…" answer, not an error.
105
+
106
+ | Tool | What it does |
107
+ |---|---|
108
+ | `get_account` | Your profile, every context you belong to with your role and permissions, organizations you can still create |
109
+ | `list_workspaces` | Workspaces in a context, with API key counts, budgets and this month's spend |
110
+ | `get_org_settings` / `update_org_settings` ✏️ | Name, icon and access defaults of a context |
111
+ | `create_workspace` ✏️ / `update_workspace` ✏️ / `delete_workspace` ✏️ | Workspace management |
112
+ | `list_keys` / `get_key` / `create_key` ✏️ / `update_key` ✏️ / `delete_key` ✏️ | API keys in a workspace |
113
+ | `list_access_policies` / `upsert_access_policy` ✏️ / `delete_access_policy` ✏️ | Which models, regions and IPs a workspace's keys may use |
114
+ | `list_available_models` | Models available in a context |
115
+ | `get_usage` / `get_logs` | Usage totals and request-level logs for a workspace |
116
+ | `get_credits` | Balance, lifetime top-ups and spend, estimated runway, auto top-up settings |
117
+ | `get_billing` | Transactions (top-ups, refunds, promos) and monthly statements |
118
+ | `set_auto_topup` ✏️ | Turn auto top-up on or off, change its threshold and amount |
119
+ | `list_budgets` / `set_budget` ✏️ | Daily / weekly / monthly budgets on workspaces and members |
120
+ | `get_analytics` | This month's organization spend by workspace and by member (Admin, Billing) |
121
+ | `list_members` / `invite_members` ✏️ / `revoke_invite` ✏️ / `update_member_role` ✏️ / `remove_member` ✏️ | Members and invitations (Admin; Billing reads) |
122
+ | `leave_organization` ✏️ | Leave an organization |
123
+ | `create_organization` ✏️ | Create an organization (organizations can't be deleted) |
124
+
125
+ Top-ups, refunds and accepting invitations are deliberately not available as tools — use
126
+ the Lune.io Console for those.
127
+
128
+ ### Supplier (17, supplier accounts only)
129
+
130
+ | Tool | What it does |
131
+ |---|---|
132
+ | `supplier_overview` | Supply overview |
133
+ | `list_providers` / `create_provider` ✏️ / `update_provider` ✏️ | Supplier endpoint management |
134
+ | `list_provider_keys` / `add_provider_key` ✏️ / `delete_provider_key` ✏️ | Upstream key management |
135
+ | `list_listings` / `create_listing` ✏️ / `update_listing` ✏️ / `delete_listing` ✏️ | Listing management |
136
+ | `list_model_catalog` | Canonical model catalog |
137
+ | `list_upstream_models` | Upstream models synced for a supplier |
138
+ | `supplier_usage` / `supplier_logs` | Usage and logs hitting your models |
139
+ | `supplier_earnings` / `list_payouts` | Earnings and payout history |
140
+
141
+ ### Write operations = two-step confirmation
142
+
143
+ The first call to any ✏️ tool returns only a **plan summary** (what will happen, what it
144
+ affects) without executing. After you confirm, the agent calls the tool again with the
145
+ returned planId — only then does it execute.
146
+
147
+ ## CLI commands
148
+
149
+ This is the Lune.io CLI (`lune-mcp`).
150
+
151
+ ```bash
152
+ npx @zenlayer/lune-mcp <command>
153
+ ```
154
+
155
+ | Command | What it does |
156
+ |---|---|
157
+ | `mcp` | Starts the MCP server over stdio (written into client configs; rarely typed by hand) |
158
+ | `login [--no-browser]` | OAuth sign-in, **stdio only** (the remote transport is authorized by your MCP client automatically — this command is not needed there); `--no-browser` prints the authorization URL instead of opening a browser (SSH sessions) |
159
+ | `logout` | Revokes and clears local credentials (**stdio only**; for remote, disconnect in your MCP client) |
160
+ | `install [clients...] [--all] [--stdio] [--url <url>] [--scope user\|project]` | Writes the Lune.io server entry (named `lune-io`) into client MCP configs: remote by default, `--stdio` for local, `--url` overrides the remote URL; prompts interactively when clients or scope are not specified. **Re-running install keeps only the last configuration**: before writing, stale `lune-io` entries in the client's other scopes and transports are removed (switching stdio↔remote or user↔project leaves no shadow config) |
161
+ | `doctor` | Ten self-checks grouped by transport (common / remote service / stdio credential chain), including whether the backend you point at is organization-enabled; each with a suggested fix |
162
+
163
+ ## Environment variables
164
+
165
+ Both apply to the local stdio transport and the CLI.
166
+
167
+ | Variable | Effect |
168
+ |---|---|
169
+ | `LUNE_MCP_ALLOW_FILE_CREDENTIALS=1` | Fallback for machines without a usable system keychain (e.g. headless Linux without Secret Service). `login` then stores the refresh token in **plaintext** at `~/.lune-mcp/credentials.json` (mode 0600): anyone who can read that file can act as your account. Ignored while the keychain works; `logout` when you are done |
170
+ | `LUNE_MCP_LOG_LEVEL` | `debug` \| `info` \| `warn` \| `error` (default `info`; any other value means `info`). Logs go to stderr |
171
+
172
+ ## Security notes
173
+
174
+ - The plaintext API key returned by `create_key` **appears in your AI client's conversation
175
+ history**. Treat that conversation like a password; `delete_key` any key you no longer need.
176
+ - Write operations are gated by two-step confirmation, but keeping manual approval for
177
+ write tools in your MCP client is still a good habit.
178
+ - To revoke credentials: `logout`, or change your password in the Lune.io Console (this
179
+ immediately invalidates every credential issued to the account).
180
+
181
+ ## Moving from @zenlayer/tkex-mcp
182
+
183
+ The package is now `@zenlayer/lune-mcp` (versions continue from the old package), and the
184
+ service moved to `www.lune.io`. Nothing from the old setup is migrated or recognized, so redo
185
+ the setup once:
186
+
187
+ 1. **Reinstall**: `npx @zenlayer/lune-mcp install` (add `--stdio` for the local transport).
188
+ It writes a connector named `lune-io`; tools show up as `mcp__lune-io__*` in Claude Code.
189
+ 2. **Sign in again**: `npx @zenlayer/lune-mcp login` (stdio only). Credentials saved by the
190
+ old package (system keychain entry `tkex-mcp`, `~/.tkex`) are not read. Delete the old
191
+ keychain entry `tkex-mcp` and the `~/.tkex` directory (it may hold a plaintext refresh
192
+ token). To invalidate old credentials right away, change your password.
193
+ 3. **Delete the old connector by hand**: `install` does not touch the `tkex` entry in your
194
+ client's config, so it stays behind as a dead connector next to `lune-io`.
195
+ Claude Code: `claude mcp remove tkex -s user` (also try `-s project` / `-s local`).
196
+ 4. **Remote connectors**: the address changed to `https://www.lune.io/mcp`. Add it as a new
197
+ connector and authorize it; the old `www.tkex.ai/mcp` one will not work again.
198
+ 5. **Environment variables**: rename them in your client config. The old names are ignored.
199
+
200
+ | Old | New |
201
+ |---|---|
202
+ | `TKEX_TOKEN` | `LUNE_MCP_TOKEN` |
203
+ | `TKEX_SUPPLIER` | `LUNE_MCP_SUPPLIER` |
204
+ | `TKEX_ALLOW_FILE_CREDENTIALS` | `LUNE_MCP_ALLOW_FILE_CREDENTIALS` |
205
+ | `TKEX_MCP_LOG_LEVEL` | `LUNE_MCP_LOG_LEVEL` |
206
+ | `TKEX_API_BASE` | `LUNE_MCP_API_BASE` |
207
+ | `TKEX_AS_ISSUER` | `LUNE_MCP_AS_ISSUER` |
208
+ | `TKEX_MCP_URL` | `LUNE_MCP_URL` |
209
+ | `TKEX_WEBSITE_ORIGIN` | `LUNE_MCP_WEBSITE_ORIGIN` |
210
+ | `TKEX_SUPPLIER_ORIGIN` | `LUNE_MCP_SUPPLIER_ORIGIN` |
211
+
212
+ Self-hosted remote deployments also rename `TKEX_ALLOWED_HOSTS`, `TKEX_ALLOWED_ORIGINS` and
213
+ `TKEX_MCP_INSTANCE` to `LUNE_MCP_ALLOWED_HOSTS`, `LUNE_MCP_ALLOWED_ORIGINS` and
214
+ `LUNE_MCP_INSTANCE`.
215
+
216
+ ## Tool changes since tkex-mcp 1.0.2
217
+
218
+ `@zenlayer/tkex-mcp` 1.0.3 followed the Lune.io Console's move to **organizations and
219
+ workspaces**, and `@zenlayer/lune-mcp` carries those changes. If you came from 1.0.2 or
220
+ earlier, these break saved prompts and tool allowlists:
221
+
222
+ - **Removed and renamed tools** (no aliases): `set_spend_limit` → `set_budget` (spend limits
223
+ were replaced by workspace and member budgets); `get_auto_topup` → `get_credits`. Update
224
+ tool allowlists or saved prompts that name the old tools.
225
+ - **Every buyer tool is now organization- and workspace-aware**: optional `project_id` /
226
+ `workspace_id` inputs, a `scope` in every result, and `update_key` / `delete_key` require
227
+ `workspace_id`. `get_account` no longer returns the balance (use `get_credits`), and
228
+ `get_usage` reports one workspace for a time range instead of lifetime totals.
229
+ - **Paging inputs use one set of names**: page size is always `max_results`; tools that page
230
+ also take `offset`, set to the previous result's `next_offset` (`null` = no more pages).
231
+ `get_logs`, `supplier_logs` and `list_payouts` renamed `limit` to `max_results`. The old
232
+ name is ignored rather than rejected, so update saved prompts that pass it. `list_keys` and
233
+ `get_billing` are now paged (`max_results` / `offset`; billing statements use
234
+ `statements_max_results` / `statements_offset`). `list_public_models`,
235
+ `list_available_models`, `list_model_catalog`, `list_listings` and `list_upstream_models`
236
+ take `max_results` but no `offset`: narrow them with their filters instead of paging.
237
+ - **New tools**: `list_workspaces`, `get_org_settings`, `get_credits`, `list_budgets`,
238
+ `get_analytics`, `list_members`, and the write tools `create_workspace`,
239
+ `update_workspace`, `delete_workspace`, `set_budget`, `invite_members`, `revoke_invite`,
240
+ `update_member_role`, `remove_member`, `leave_organization`, `update_org_settings`,
241
+ `create_organization`.
242
+
243
+ ## Access policy changes
244
+
245
+ Model and IP limits moved off API keys into **access policies**:
246
+
247
+ - `create_key` / `update_key` drop `allowed_models` / `ip_whitelist`; use `upsert_access_policy`.
248
+ - `get_org_settings` / `update_org_settings` add `models` and `regions`.
249
+ - Update: older versions can't create keys; remote connections must re-authorize.
250
+
251
+ ## Billing role
252
+
253
+ New organization role (`role: "billing"`): credits, auto top-up, budgets, and read-only usage,
254
+ keys and members. Update first: older versions deny Billing everything and label everyone's
255
+ usage and keys as only theirs. This version needs the matching backend.
256
+
257
+ ## Requirements and troubleshooting
258
+
259
+ - The organization-enabled Lune.io backend (`doctor` check ⑩ tells you which one you are
260
+ talking to).
261
+ - Node.js >= 20 (stdio only; the remote transport has no local requirements).
262
+ - If something misbehaves, run `npx @zenlayer/lune-mcp doctor` first — it distinguishes
263
+ network, credential, and client-config problems and tells you what to do next.
264
+
265
+ ## License
266
+
267
+ Proprietary — © Zenlayer Inc. All rights reserved.
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ probeIdentity
4
+ } from "./chunk-MC3S3YL6.js";
5
+ import {
6
+ BackendClient,
7
+ log
8
+ } from "./chunk-TFX4RC2N.js";
9
+ import {
10
+ CLI_INVOKE
11
+ } from "./chunk-G7ZX5GSF.js";
12
+ import {
13
+ BRAND_NAME
14
+ } from "./chunk-NN23AOUC.js";
15
+
16
+ // src/stdio/oauth-login.ts
17
+ import { createHash, randomBytes } from "crypto";
18
+ import { createServer } from "http";
19
+ var CLI_CLIENT_ID = "mcp-cli";
20
+ var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
21
+ var HTTP_TIMEOUT_MS = 3e4;
22
+ function assertOpenableUrl(url) {
23
+ let parsed;
24
+ try {
25
+ parsed = new URL(url);
26
+ } catch {
27
+ throw new Error(`Refusing to open invalid URL: ${url.slice(0, 100)}`);
28
+ }
29
+ const loopbackHttp = parsed.protocol === "http:" && (parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost");
30
+ if (parsed.protocol !== "https:" && !loopbackHttp) {
31
+ throw new Error(
32
+ `Refusing to open a non-https authorization URL (${parsed.protocol}//\u2026) \u2014 only https: or loopback http: is allowed (lesson of CVE-2025-6514).`
33
+ );
34
+ }
35
+ }
36
+ var RESULT_PATH_OK = "/cli-login/complete";
37
+ var RESULT_PATH_FAILED = "/cli-login/failed";
38
+ function resultPageOrigin(asIssuer) {
39
+ let u;
40
+ try {
41
+ u = new URL(asIssuer);
42
+ } catch {
43
+ return null;
44
+ }
45
+ const loopbackHttp = u.protocol === "http:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost");
46
+ if (u.protocol !== "https:" && !loopbackHttp) return null;
47
+ return u.origin;
48
+ }
49
+ function failReasonForOAuthError(error) {
50
+ if (error === "access_denied") return "denied";
51
+ if (error === "temporarily_unavailable") return "busy";
52
+ return "server";
53
+ }
54
+ function metadataUrlsFor(issuer) {
55
+ const u = new URL(issuer);
56
+ const path = u.pathname.replace(/\/+$/, "");
57
+ const primary = `${u.origin}/.well-known/oauth-authorization-server${path === "/" ? "" : path}`;
58
+ if (path === "" || path === "/") return [primary];
59
+ return [primary, `${u.origin}${path}/.well-known/oauth-authorization-server`];
60
+ }
61
+ async function runLoginFlow(opts) {
62
+ const asIssuer = opts.asIssuer.replace(/\/+$/, "");
63
+ const fetchImpl = opts.fetchImpl ?? fetch;
64
+ const print = opts.print ?? ((msg) => process.stderr.write(`${msg}
65
+ `));
66
+ const timeoutMs = opts.timeoutMs ?? LOGIN_TIMEOUT_MS;
67
+ let meta = null;
68
+ const attempts = [];
69
+ for (const metaUrl of metadataUrlsFor(asIssuer)) {
70
+ const metaRes = await fetchImpl(metaUrl, {
71
+ headers: { accept: "application/json" },
72
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
73
+ });
74
+ if (metaRes.ok) {
75
+ meta = await metaRes.json();
76
+ break;
77
+ }
78
+ attempts.push(`${metaUrl} \u2192 HTTP ${metaRes.status}`);
79
+ }
80
+ if (!meta) {
81
+ throw new Error(
82
+ `Failed to fetch AS metadata (issuer=${asIssuer}):
83
+ ${attempts.join("\n ")}
84
+ If you set LUNE_MCP_AS_ISSUER yourself, check that the /oauth path prefix is not missing.`
85
+ );
86
+ }
87
+ if (meta.issuer !== asIssuer) {
88
+ throw new Error(`AS issuer mismatch: expected ${asIssuer}, metadata declares ${meta.issuer}`);
89
+ }
90
+ const server = createServer();
91
+ await new Promise((resolve, reject) => {
92
+ server.once("error", reject);
93
+ server.listen(0, "127.0.0.1", resolve);
94
+ });
95
+ const port = server.address().port;
96
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
97
+ const verifier = randomBytes(32).toString("base64url");
98
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
99
+ const state = randomBytes(16).toString("base64url");
100
+ try {
101
+ const authorizeUrl = new URL(meta.authorization_endpoint);
102
+ authorizeUrl.searchParams.set("response_type", "code");
103
+ authorizeUrl.searchParams.set("client_id", CLI_CLIENT_ID);
104
+ authorizeUrl.searchParams.set("redirect_uri", redirectUri);
105
+ authorizeUrl.searchParams.set("code_challenge", challenge);
106
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
107
+ authorizeUrl.searchParams.set("state", state);
108
+ assertOpenableUrl(authorizeUrl.toString());
109
+ const callbackPromise = waitForCallback(server, {
110
+ state,
111
+ asIssuer,
112
+ resultOrigin: resultPageOrigin(asIssuer)
113
+ });
114
+ void callbackPromise.catch(() => {
115
+ });
116
+ if (opts.noBrowser) {
117
+ print(`Open this URL in your browser to sign in:
118
+
119
+ ${authorizeUrl}
120
+ `);
121
+ } else {
122
+ const openBrowser = opts.openBrowser ?? (async (url) => {
123
+ const { default: open } = await import("open");
124
+ await open(url);
125
+ });
126
+ try {
127
+ print("Opening your browser to sign in\u2026");
128
+ await openBrowser(authorizeUrl.toString());
129
+ } catch (err) {
130
+ print(
131
+ `Could not open the browser automatically (${err instanceof Error ? err.message : String(err)}). Open this URL manually:
132
+
133
+ ${authorizeUrl}
134
+ `
135
+ );
136
+ }
137
+ }
138
+ const code = await withTimeout(
139
+ callbackPromise,
140
+ timeoutMs,
141
+ "Timed out waiting for browser authorization (5 minutes)"
142
+ );
143
+ const tokenRes = await fetchImpl(meta.token_endpoint, {
144
+ method: "POST",
145
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
146
+ body: new URLSearchParams({
147
+ grant_type: "authorization_code",
148
+ code,
149
+ code_verifier: verifier,
150
+ client_id: CLI_CLIENT_ID,
151
+ redirect_uri: redirectUri
152
+ }).toString(),
153
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
154
+ });
155
+ if (!tokenRes.ok) {
156
+ const body = await tokenRes.text().catch(() => "");
157
+ throw new Error(`Token exchange failed: HTTP ${tokenRes.status} ${body.slice(0, 200)}`);
158
+ }
159
+ const tokens = await tokenRes.json();
160
+ if (!tokens.access_token || !tokens.refresh_token) {
161
+ throw new Error("Token response is missing access_token/refresh_token");
162
+ }
163
+ const backend = new BackendClient({
164
+ baseUrl: opts.apiBase,
165
+ fetchImpl,
166
+ credentials: {
167
+ getAccessToken: async () => tokens.access_token,
168
+ forceRefresh: async () => null,
169
+ reauthHint: () => `The temporary credentials from this login flow expired. Run \`${CLI_INVOKE} login\` again.`
170
+ }
171
+ });
172
+ const identity = await probeIdentity(backend);
173
+ const scopes = tokens.scopes ?? tokens.scope ?? "";
174
+ await opts.store.write({
175
+ refresh_token: tokens.refresh_token,
176
+ user_id: identity.userId,
177
+ is_supplier: identity.isSupplier,
178
+ scopes,
179
+ obtained_at: (/* @__PURE__ */ new Date()).toISOString()
180
+ });
181
+ return { userId: identity.userId, isSupplier: identity.isSupplier, scopes };
182
+ } finally {
183
+ server.close();
184
+ server.closeAllConnections?.();
185
+ }
186
+ }
187
+ function waitForCallback(server, expect) {
188
+ return new Promise((resolve, reject) => {
189
+ server.on("request", (req, res) => {
190
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
191
+ if (url.pathname !== "/callback") {
192
+ res.writeHead(404).end();
193
+ return;
194
+ }
195
+ const land = (outcome) => {
196
+ if (expect.resultOrigin) {
197
+ const location = outcome.ok ? `${expect.resultOrigin}${RESULT_PATH_OK}` : `${expect.resultOrigin}${RESULT_PATH_FAILED}?reason=${outcome.reason}`;
198
+ res.writeHead(302, { location, "cache-control": "no-store" });
199
+ res.end();
200
+ return;
201
+ }
202
+ res.writeHead(outcome.ok ? 200 : 400, { "content-type": "text/html; charset=utf-8" });
203
+ res.end(
204
+ outcome.ok ? `<html><head><title>Signed in \xB7 ${BRAND_NAME}</title></head><body><p>Signed in to the ${BRAND_NAME} CLI. You can close this tab and return to the terminal.</p></body></html>` : `<html><head><title>Sign-in failed \xB7 ${BRAND_NAME}</title></head><body><p>${BRAND_NAME} CLI sign-in failed. Return to the terminal for details.</p></body></html>`
205
+ );
206
+ };
207
+ const fail = (reason, why) => {
208
+ land({ ok: false, reason });
209
+ reject(new Error(why));
210
+ };
211
+ const error = url.searchParams.get("error");
212
+ if (error) {
213
+ fail(
214
+ failReasonForOAuthError(error),
215
+ `Authorization denied: ${error}${url.searchParams.get("error_description") ? ` (${url.searchParams.get("error_description")})` : ""}`
216
+ );
217
+ return;
218
+ }
219
+ const state = url.searchParams.get("state");
220
+ if (state !== expect.state) {
221
+ fail("mismatch", "state mismatch (possible CSRF or a crossed callback); rejected");
222
+ return;
223
+ }
224
+ const iss = url.searchParams.get("iss");
225
+ if (iss !== expect.asIssuer) {
226
+ fail(
227
+ "mismatch",
228
+ `Authorization response iss mismatch (expected ${expect.asIssuer}, got ${iss ?? "missing"}); rejected`
229
+ );
230
+ return;
231
+ }
232
+ const code = url.searchParams.get("code");
233
+ if (!code) {
234
+ fail("server", "Authorization response is missing code");
235
+ return;
236
+ }
237
+ land({ ok: true });
238
+ resolve(code);
239
+ });
240
+ });
241
+ }
242
+ async function withTimeout(promise, ms, message) {
243
+ let timer;
244
+ try {
245
+ return await Promise.race([
246
+ promise,
247
+ new Promise((_, reject) => {
248
+ timer = setTimeout(() => reject(new Error(message)), ms);
249
+ })
250
+ ]);
251
+ } finally {
252
+ clearTimeout(timer);
253
+ }
254
+ }
255
+ async function runLogout(opts) {
256
+ const fetchImpl = opts.fetchImpl ?? fetch;
257
+ const print = opts.print ?? ((msg) => process.stderr.write(`${msg}
258
+ `));
259
+ const creds = await opts.store.read();
260
+ if (creds) {
261
+ try {
262
+ await fetchImpl(`${opts.apiBase.replace(/\/+$/, "")}/v1/auth/revoke`, {
263
+ method: "POST",
264
+ headers: { "content-type": "application/json" },
265
+ body: JSON.stringify({ refresh_token: creds.refresh_token }),
266
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
267
+ });
268
+ } catch (err) {
269
+ log.warn(
270
+ "Server-side revocation failed (ignored; local credentials will still be cleared):",
271
+ err instanceof Error ? err.message : err
272
+ );
273
+ }
274
+ }
275
+ await opts.store.delete();
276
+ print(
277
+ creds ? "Signed out: local credentials cleared; refresh token revocation requested." : "No saved credentials on this machine."
278
+ );
279
+ }
280
+
281
+ export {
282
+ CLI_CLIENT_ID,
283
+ assertOpenableUrl,
284
+ resultPageOrigin,
285
+ failReasonForOAuthError,
286
+ metadataUrlsFor,
287
+ runLoginFlow,
288
+ runLogout
289
+ };