@aaronjmars/openroutercli 0.1.4 → 0.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.
@@ -1,12 +1,18 @@
1
- import http from 'node:http';
2
- import crypto from 'node:crypto';
3
- import { spawn } from 'node:child_process';
4
- import readline from 'node:readline/promises';
5
- import { stdin, stdout } from 'node:process';
6
- import { parseArgs } from '../args.js';
7
- import { loadConfig, saveConfig, DEFAULT_AUTH_URL, DEFAULT_BASE_URL } from '../config.js';
8
- import { api } from '../api.js';
9
- import { c, info, isJsonMode, outln, printJSON } from '../output.js';
1
+ import http from "node:http";
2
+ import crypto from "node:crypto";
3
+ import { spawn } from "node:child_process";
4
+ import readline from "node:readline/promises";
5
+ import { stdin, stdout } from "node:process";
6
+ import { parseArgs, numberOption } from "../args.js";
7
+ import {
8
+ loadConfig,
9
+ saveConfig,
10
+ DEFAULT_AUTH_URL,
11
+ DEFAULT_BASE_URL,
12
+ PROVISIONING_KEYS_URL,
13
+ } from "../config.js";
14
+ import { api } from "../api.js";
15
+ import { c, info, isJsonMode, outln, printJSON } from "../output.js";
10
16
 
11
17
  const HELP = `Usage: openrouter login [options]
12
18
 
@@ -18,8 +24,8 @@ Two key types are supported:
18
24
  - Management key: used for account-wide operations (\`keys\`
19
25
  subcommands, \`activity\`). Must be created in
20
26
  the OpenRouter dashboard at
21
- https://openrouter.ai/settings/provisioning-keys
22
- — they cannot be obtained via OAuth.
27
+ ${PROVISIONING_KEYS_URL}
28
+ They cannot be obtained via OAuth.
23
29
 
24
30
  You can store one of each. The CLI picks the right one automatically per
25
31
  command. Both can also be supplied via env vars (see below).
@@ -27,7 +33,7 @@ command. Both can also be supplied via env vars (see below).
27
33
  Options:
28
34
  -k, --key <key> Save an existing API key (sk-or-...). Skips OAuth.
29
35
  --management Save the key into the management slot (instead of
30
- the user-key slot). Implies manual entry — pass with
36
+ the user-key slot). Implies manual entry: pass with
31
37
  --key, --stdin, or via the interactive prompt.
32
38
  --no-browser Don't auto-open the browser; just print the auth URL.
33
39
  --port <port> Local port for the OAuth callback (default: random).
@@ -43,31 +49,25 @@ Environment:
43
49
 
44
50
  function base64url(buf) {
45
51
  return Buffer.from(buf)
46
- .toString('base64')
47
- .replace(/\+/g, '-')
48
- .replace(/\//g, '_')
49
- .replace(/=+$/, '');
52
+ .toString("base64")
53
+ .replace(/\+/g, "-")
54
+ .replace(/\//g, "_")
55
+ .replace(/=+$/, "");
50
56
  }
51
57
 
52
58
  function openBrowser(url) {
53
59
  const cmd =
54
- process.platform === 'darwin'
55
- ? 'open'
56
- : process.platform === 'win32'
57
- ? 'cmd'
58
- : 'xdg-open';
59
- const args = process.platform === 'win32' ? ['/c', 'start', '""', url] : [url];
60
- try {
61
- const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
62
- child.unref();
63
- return true;
64
- } catch {
65
- return false;
66
- }
60
+ process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
61
+ const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
62
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
63
+ // Best effort: the URL is printed either way, and a missing launcher arrives
64
+ // as an async 'error' event that would otherwise crash the process.
65
+ child.on("error", () => {});
66
+ child.unref();
67
67
  }
68
68
 
69
69
  async function readFromStdin() {
70
- let data = '';
70
+ let data = "";
71
71
  for await (const chunk of stdin) data += chunk;
72
72
  return data.trim();
73
73
  }
@@ -75,7 +75,7 @@ async function readFromStdin() {
75
75
  async function promptKey() {
76
76
  const rl = readline.createInterface({ input: stdin, output: stdout });
77
77
  try {
78
- const answer = await rl.question('Paste your OpenRouter API key (sk-or-...): ');
78
+ const answer = await rl.question("Paste your OpenRouter API key (sk-or-...): ");
79
79
  return answer.trim();
80
80
  } finally {
81
81
  rl.close();
@@ -87,7 +87,6 @@ async function saveKey(apiKey, extra = {}) {
87
87
  cfg.apiKey = apiKey;
88
88
  Object.assign(cfg, extra);
89
89
  await saveConfig(cfg);
90
- return cfg;
91
90
  }
92
91
 
93
92
  async function saveManagementKey(apiKey, extra = {}) {
@@ -95,14 +94,13 @@ async function saveManagementKey(apiKey, extra = {}) {
95
94
  cfg.managementKey = apiKey;
96
95
  Object.assign(cfg, extra);
97
96
  await saveConfig(cfg);
98
- return cfg;
99
97
  }
100
98
 
101
99
  async function promptManagementKey() {
102
100
  const rl = readline.createInterface({ input: stdin, output: stdout });
103
101
  try {
104
102
  const answer = await rl.question(
105
- 'Paste your OpenRouter management key (sk-or-v1-...). Create one at\n https://openrouter.ai/settings/provisioning-keys\n› '
103
+ `Paste your OpenRouter management key (sk-or-v1-...). Create one at\n ${PROVISIONING_KEYS_URL}\n› `,
106
104
  );
107
105
  return answer.trim();
108
106
  } finally {
@@ -112,172 +110,175 @@ async function promptManagementKey() {
112
110
 
113
111
  async function pkceFlow({ port, openInBrowser, authUrl, baseUrl }) {
114
112
  const verifier = base64url(crypto.randomBytes(48));
115
- const challenge = base64url(
116
- crypto.createHash('sha256').update(verifier).digest()
117
- );
113
+ const challenge = base64url(crypto.createHash("sha256").update(verifier).digest());
118
114
 
119
115
  const codePromise = new Promise((resolve, reject) => {
120
116
  const server = http.createServer((req, res) => {
121
117
  const u = new URL(req.url, `http://localhost`);
122
- if (u.pathname !== '/callback') {
123
- res.writeHead(404).end('not found');
118
+ if (u.pathname !== "/callback") {
119
+ res.writeHead(404).end("not found");
124
120
  return;
125
121
  }
126
- const code = u.searchParams.get('code');
127
- const error = u.searchParams.get('error');
122
+ const code = u.searchParams.get("code");
123
+ const error = u.searchParams.get("error");
128
124
  const html = (title, body) =>
129
125
  `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>` +
130
126
  `<style>body{font-family:-apple-system,system-ui,sans-serif;max-width:480px;margin:6rem auto;padding:0 1rem;color:#222}h1{font-weight:600}` +
131
127
  `code{background:#f4f4f5;padding:.1rem .35rem;border-radius:.25rem}</style></head><body>${body}</body></html>`;
132
128
  if (error) {
133
- res.writeHead(400, { 'Content-Type': 'text/html' }).end(
134
- html('Login failed', `<h1>Login failed</h1><p>${error}</p>`)
135
- );
129
+ res
130
+ .writeHead(400, { "Content-Type": "text/html" })
131
+ .end(html("Login failed", `<h1>Login failed</h1><p>${error}</p>`));
136
132
  server.close();
137
133
  reject(new Error(`OAuth error: ${error}`));
138
134
  return;
139
135
  }
140
136
  if (!code) {
141
- res.writeHead(400, { 'Content-Type': 'text/html' }).end(
142
- html('Missing code', '<h1>Missing code</h1>')
143
- );
137
+ res
138
+ .writeHead(400, { "Content-Type": "text/html" })
139
+ .end(html("Missing code", "<h1>Missing code</h1>"));
144
140
  return;
145
141
  }
146
- res.writeHead(200, { 'Content-Type': 'text/html' }).end(
147
- html(
148
- 'OpenRouter CLI: signed in',
149
- '<h1>You are signed in.</h1><p>You can close this tab and return to the terminal.</p>'
150
- )
151
- );
142
+ res
143
+ .writeHead(200, { "Content-Type": "text/html" })
144
+ .end(
145
+ html(
146
+ "OpenRouter CLI: signed in",
147
+ "<h1>You are signed in.</h1><p>You can close this tab and return to the terminal.</p>",
148
+ ),
149
+ );
152
150
  setTimeout(() => server.close(), 100);
153
151
  resolve(code);
154
152
  });
155
- server.on('error', reject);
156
- server.listen(port || 0, '127.0.0.1', () => {
153
+ server.on("error", reject);
154
+ server.listen(port || 0, "127.0.0.1", () => {
157
155
  const actualPort = server.address().port;
158
156
  const callback = `http://localhost:${actualPort}/callback`;
159
157
  const params = new URLSearchParams({
160
158
  callback_url: callback,
161
159
  code_challenge: challenge,
162
- code_challenge_method: 'S256'
160
+ code_challenge_method: "S256",
163
161
  });
164
162
  const url = `${authUrl}?${params.toString()}`;
165
163
  info(`Listening on ${callback}`);
166
164
  if (openInBrowser) {
167
- info('Opening browser...');
165
+ info("Opening browser...");
168
166
  openBrowser(url);
169
167
  }
170
- outln(c.bold('Open this URL to sign in:'));
171
- outln(' ' + c.cyan(url));
172
- outln('');
173
- info('Waiting for callback (press Ctrl+C to cancel)...');
168
+ outln(c.bold("Open this URL to sign in:"));
169
+ outln(" " + c.cyan(url));
170
+ outln("");
171
+ info("Waiting for callback (press Ctrl+C to cancel)...");
174
172
  });
175
173
  });
176
174
 
177
175
  const code = await codePromise;
178
- info('Exchanging authorization code for API key...');
179
- const data = await api('POST', '/auth/keys', {
176
+ info("Exchanging authorization code for API key...");
177
+ const data = await api("POST", "/auth/keys", {
180
178
  requireAuth: false,
181
179
  auth: { baseUrl },
182
180
  body: {
183
181
  code,
184
182
  code_verifier: verifier,
185
- code_challenge_method: 'S256'
186
- }
183
+ code_challenge_method: "S256",
184
+ },
187
185
  });
188
186
  return data;
189
187
  }
190
188
 
191
189
  export async function loginCommand(argv) {
192
190
  const { values } = parseArgs(argv, {
193
- 'no-browser': { type: 'boolean' },
194
- port: { type: 'string' },
195
- 'auth-url': { type: 'string' },
196
- stdin: { type: 'boolean' },
197
- management: { type: 'boolean' }
191
+ "no-browser": { type: "boolean" },
192
+ port: { type: "string" },
193
+ "auth-url": { type: "string" },
194
+ stdin: { type: "boolean" },
195
+ management: { type: "boolean" },
198
196
  });
199
197
  if (values.help) {
200
198
  process.stdout.write(HELP);
201
199
  return 0;
202
200
  }
203
201
 
204
- const baseUrl = values['base-url'] || DEFAULT_BASE_URL;
205
- const authUrl = values['auth-url'] || DEFAULT_AUTH_URL;
202
+ const baseUrl = values["base-url"] || DEFAULT_BASE_URL;
203
+ const authUrl = values["auth-url"] || DEFAULT_AUTH_URL;
206
204
 
207
- // Management-key path: never OAuth — always paste/stdin/--key.
205
+ // Management-key path: never OAuth, always paste/stdin/--key.
208
206
  if (values.management) {
209
207
  let key = values.key;
210
208
  if (!key && values.stdin) key = await readFromStdin();
211
209
  if (!key) key = await promptManagementKey();
212
- if (!key || !key.startsWith('sk-or-')) {
210
+ if (!key || !key.startsWith("sk-or-")) {
213
211
  throw new Error('Expected management key starting with "sk-or-".');
214
212
  }
215
213
  await saveManagementKey(key, {
216
- baseUrl: values['base-url'] || undefined
214
+ baseUrl: values["base-url"] || undefined,
217
215
  });
218
- if (isJsonMode()) printJSON({ saved: true, slot: 'management' });
216
+ if (isJsonMode()) printJSON({ saved: true, slot: "management" });
219
217
  else info(`Saved management key (${key.slice(0, 12)}...).`);
220
218
  return 0;
221
219
  }
222
220
 
223
- // Manual user-key path
224
221
  if (values.key || values.stdin) {
225
222
  const key = values.key || (await readFromStdin());
226
- if (!key || !key.startsWith('sk-or-')) {
223
+ if (!key || !key.startsWith("sk-or-")) {
227
224
  throw new Error('Expected API key starting with "sk-or-".');
228
225
  }
229
226
  await saveKey(key, {
230
- baseUrl: values['base-url'] || undefined
227
+ baseUrl: values["base-url"] || undefined,
231
228
  });
232
229
  info(`Saved API key (${key.slice(0, 12)}...).`);
233
- if (isJsonMode()) printJSON({ saved: true, slot: 'user' });
230
+ if (isJsonMode()) printJSON({ saved: true, slot: "user" });
234
231
  return 0;
235
232
  }
236
233
 
237
- // Interactive: try OAuth, but offer paste fallback if user prefers
238
- const port = values.port ? Number(values.port) : 0;
234
+ // Interactive: OAuth PKCE, falling back to manual paste only if it fails.
235
+ const port = numberOption(values.port, "--port") ?? 0;
239
236
  let result;
240
237
  try {
241
238
  result = await pkceFlow({
242
239
  port,
243
- openInBrowser: !values['no-browser'],
240
+ openInBrowser: !values["no-browser"],
244
241
  authUrl,
245
- baseUrl
242
+ baseUrl,
246
243
  });
247
244
  } catch (err) {
248
245
  if (process.env.OPENROUTER_DEBUG) info(String(err.stack || err));
249
- info('OAuth flow failed; falling back to manual key entry.');
246
+ // --json is documented as disabling prompts, and a non-TTY has nobody to
247
+ // answer one.
248
+ if (isJsonMode() || !stdin.isTTY) throw err;
249
+ process.stderr.write(`OAuth flow failed: ${err.message}\n`);
250
+ info("Falling back to manual key entry.");
250
251
  const key = await promptKey();
251
- if (!key) throw new Error('No API key provided.');
252
+ if (!key) throw new Error("No API key provided.");
252
253
  await saveKey(key);
253
- if (isJsonMode()) printJSON({ saved: true, mode: 'manual' });
254
- else info('Saved API key.');
254
+ if (isJsonMode()) printJSON({ saved: true, mode: "manual" });
255
+ else info("Saved API key.");
255
256
  return 0;
256
257
  }
257
258
 
258
259
  await saveKey(result.key, {
259
260
  userId: result.user_id,
260
- baseUrl: values['base-url'] || undefined
261
+ baseUrl: values["base-url"] || undefined,
261
262
  });
262
263
  if (isJsonMode()) {
263
264
  printJSON({ saved: true, user_id: result.user_id });
264
265
  } else {
265
- outln(c.green('Signed in.') + ' ' + c.dim(`user_id=${result.user_id}`));
266
+ outln(c.green("Signed in.") + " " + c.dim(`user_id=${result.user_id}`));
266
267
  }
267
268
  return 0;
268
269
  }
269
270
 
270
271
  export async function logoutCommand(argv) {
271
272
  const { values } = parseArgs(argv, {
272
- management: { type: 'boolean' },
273
- all: { type: 'boolean' }
273
+ management: { type: "boolean" },
274
+ all: { type: "boolean" },
274
275
  });
275
276
  if (values.help) {
276
277
  process.stdout.write(
277
- 'Usage: openrouter logout [--management|--all]\n\n' +
278
- 'Remove the locally stored API key. By default removes the user key.\n' +
279
- ' --management Remove the management key only\n' +
280
- ' --all Remove both\n'
278
+ "Usage: openrouter logout [--management|--all]\n\n" +
279
+ "Remove the locally stored API key. By default removes the user key.\n" +
280
+ " --management Remove the management key only\n" +
281
+ " --all Remove both\n",
281
282
  );
282
283
  return 0;
283
284
  }
@@ -287,21 +288,21 @@ export async function logoutCommand(argv) {
287
288
  if (cfg.apiKey) {
288
289
  delete cfg.apiKey;
289
290
  delete cfg.userId;
290
- removed.push('user');
291
+ removed.push("user");
291
292
  }
292
293
  }
293
294
  if (values.all || values.management) {
294
295
  if (cfg.managementKey) {
295
296
  delete cfg.managementKey;
296
- removed.push('management');
297
+ removed.push("management");
297
298
  }
298
299
  }
299
300
  if (!removed.length) {
300
- info('No matching key was stored.');
301
+ info("No matching key was stored.");
301
302
  return 0;
302
303
  }
303
304
  await saveConfig(cfg);
304
305
  if (isJsonMode()) printJSON({ logged_out: removed });
305
- else info(`Logged out (${removed.join(', ')}).`);
306
+ else info(`Logged out (${removed.join(", ")}).`);
306
307
  return 0;
307
308
  }