@aaronjmars/openroutercli 0.1.6 → 0.2.1

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,6 +1,6 @@
1
- import { parseArgs, authFromValues, numberOption } from '../args.js';
2
- import { api } from '../api.js';
3
- import { c, outln, printResult, table } from '../output.js';
1
+ import { parseArgs, authFromValues, numberOption } from "../args.js";
2
+ import { api } from "../api.js";
3
+ import { c, outln, printResult, table } from "../output.js";
4
4
 
5
5
  const HELP = `Usage: openrouter keys <subcommand> [options]
6
6
 
@@ -23,11 +23,13 @@ create options:
23
23
  --expires-at <iso> ISO 8601 UTC expiry
24
24
  --workspace <uuid> Workspace id
25
25
  --include-byok Include BYOK in limit
26
+ --disabled Create the key already disabled
26
27
 
27
28
  update options:
28
29
  --name <name>
29
30
  --limit <usd>
30
31
  --limit-reset <p>
32
+ --expires-at <iso> ISO 8601 UTC expiry
31
33
  --include-byok / --no-include-byok
32
34
  --disabled / --enabled
33
35
  `;
@@ -35,120 +37,124 @@ update options:
35
37
  export async function keysCommand(argv) {
36
38
  const sub = argv[0];
37
39
  const rest = argv.slice(1);
38
- if (!sub || sub === '-h' || sub === '--help' || sub === 'help') {
40
+ if (!sub || sub === "-h" || sub === "--help" || sub === "help") {
39
41
  process.stdout.write(HELP);
40
42
  return sub ? 0 : 1;
41
43
  }
42
44
 
43
- if (rest.includes('-h') || rest.includes('--help')) {
45
+ if (rest.includes("-h") || rest.includes("--help")) {
44
46
  process.stdout.write(HELP);
45
47
  return 0;
46
48
  }
47
49
 
48
- if (sub === 'list') {
50
+ if (sub === "list") {
49
51
  const { values } = parseArgs(rest, {
50
- offset: { type: 'string' },
51
- 'include-disabled': { type: 'boolean' }
52
+ offset: { type: "string" },
53
+ "include-disabled": { type: "boolean" },
52
54
  });
53
55
  const query = {};
54
56
  if (values.offset) query.offset = values.offset;
55
- if (values['include-disabled']) query.include_disabled = 'true';
56
- const data = await api('GET', '/keys', {
57
+ if (values["include-disabled"]) query.include_disabled = "true";
58
+ const data = await api("GET", "/keys", {
57
59
  auth: authFromValues(values),
58
60
  requiresManagement: true,
59
- query
61
+ query,
60
62
  });
61
63
  printResult(data, () => {
62
64
  const rows = data.data || [];
63
65
  table(rows, [
64
- { label: 'name', value: (k) => k.name || '' },
65
- { label: 'hash', value: (k) => k.hash || k.id || '' },
66
- { label: 'usage', value: (k) => k.usage ?? '' },
67
- { label: 'limit', value: (k) => k.limit ?? '' },
68
- { label: 'disabled', value: (k) => (k.disabled ? 'yes' : '') }
66
+ { label: "name", value: (k) => k.name || "" },
67
+ { label: "hash", value: (k) => k.hash || k.id || "" },
68
+ { label: "usage", value: (k) => k.usage ?? "" },
69
+ { label: "limit", value: (k) => k.limit ?? "" },
70
+ { label: "disabled", value: (k) => (k.disabled ? "yes" : "") },
69
71
  ]);
70
72
  });
71
73
  return 0;
72
74
  }
73
75
 
74
- if (sub === 'get') {
76
+ if (sub === "get") {
75
77
  const { values, positionals } = parseArgs(rest, {});
76
- if (!positionals[0]) throw new Error('hash required');
77
- const data = await api('GET', `/keys/${encodeURIComponent(positionals[0])}`, {
78
+ if (!positionals[0]) throw new Error("hash required");
79
+ const data = await api("GET", `/keys/${encodeURIComponent(positionals[0])}`, {
78
80
  auth: authFromValues(values),
79
- requiresManagement: true
81
+ requiresManagement: true,
80
82
  });
81
83
  printResult(data);
82
84
  return 0;
83
85
  }
84
86
 
85
- if (sub === 'create') {
87
+ if (sub === "create") {
86
88
  const { values, positionals } = parseArgs(rest, {
87
- limit: { type: 'string' },
88
- 'limit-reset': { type: 'string' },
89
- 'expires-at': { type: 'string' },
90
- workspace: { type: 'string' },
91
- 'include-byok': { type: 'boolean' }
89
+ limit: { type: "string" },
90
+ "limit-reset": { type: "string" },
91
+ "expires-at": { type: "string" },
92
+ workspace: { type: "string" },
93
+ "include-byok": { type: "boolean" },
94
+ disabled: { type: "boolean" },
92
95
  });
93
96
  const name = positionals[0];
94
- if (!name) throw new Error('name required');
97
+ if (!name) throw new Error("name required");
95
98
  const body = { name };
96
- if (values.limit) body.limit = numberOption(values.limit, '--limit');
97
- if (values['limit-reset']) body.limit_reset = values['limit-reset'];
98
- if (values['expires-at']) body.expires_at = values['expires-at'];
99
+ if (values.limit) body.limit = numberOption(values.limit, "--limit");
100
+ if (values["limit-reset"]) body.limit_reset = values["limit-reset"];
101
+ if (values["expires-at"]) body.expires_at = values["expires-at"];
99
102
  if (values.workspace) body.workspace_id = values.workspace;
100
- if (values['include-byok']) body.include_byok_in_limit = true;
101
- const data = await api('POST', '/keys', {
103
+ if (values["include-byok"]) body.include_byok_in_limit = true;
104
+ if (values.disabled) body.disabled = true;
105
+ const data = await api("POST", "/keys", {
102
106
  auth: authFromValues(values),
103
107
  requiresManagement: true,
104
- body
108
+ body,
105
109
  });
106
110
  printResult(data, () => {
107
111
  const k = data.key || (data.data && data.data.key);
108
112
  const meta = data.data || data;
109
- outln(c.bold('key (save this - shown only once):'));
110
- outln(' ' + (k || '(see JSON)'));
113
+ outln(c.bold("key (save this - shown only once):"));
114
+ outln(" " + (k || "(see JSON)"));
111
115
  outln(c.dim(JSON.stringify(meta, null, 2)));
112
116
  });
113
117
  return 0;
114
118
  }
115
119
 
116
- if (sub === 'update') {
120
+ if (sub === "update") {
117
121
  const { values, positionals } = parseArgs(rest, {
118
- name: { type: 'string' },
119
- limit: { type: 'string' },
120
- 'limit-reset': { type: 'string' },
121
- 'include-byok': { type: 'boolean' },
122
- 'no-include-byok': { type: 'boolean' },
123
- disabled: { type: 'boolean' },
124
- enabled: { type: 'boolean' }
122
+ name: { type: "string" },
123
+ limit: { type: "string" },
124
+ "limit-reset": { type: "string" },
125
+ "expires-at": { type: "string" },
126
+ "include-byok": { type: "boolean" },
127
+ "no-include-byok": { type: "boolean" },
128
+ disabled: { type: "boolean" },
129
+ enabled: { type: "boolean" },
125
130
  });
126
- if (!positionals[0]) throw new Error('hash required');
131
+ if (!positionals[0]) throw new Error("hash required");
127
132
  const body = {};
128
133
  if (values.name) body.name = values.name;
129
- if (values.limit) body.limit = numberOption(values.limit, '--limit');
130
- if (values['limit-reset']) body.limit_reset = values['limit-reset'];
131
- if (values['include-byok']) body.include_byok_in_limit = true;
132
- if (values['no-include-byok']) body.include_byok_in_limit = false;
134
+ if (values.limit) body.limit = numberOption(values.limit, "--limit");
135
+ if (values["limit-reset"]) body.limit_reset = values["limit-reset"];
136
+ if (values["expires-at"]) body.expires_at = values["expires-at"];
137
+ if (values["include-byok"]) body.include_byok_in_limit = true;
138
+ if (values["no-include-byok"]) body.include_byok_in_limit = false;
133
139
  if (values.disabled) body.disabled = true;
134
140
  if (values.enabled) body.disabled = false;
135
- const data = await api('PATCH', `/keys/${encodeURIComponent(positionals[0])}`, {
141
+ const data = await api("PATCH", `/keys/${encodeURIComponent(positionals[0])}`, {
136
142
  auth: authFromValues(values),
137
143
  requiresManagement: true,
138
- body
144
+ body,
139
145
  });
140
146
  printResult(data);
141
147
  return 0;
142
148
  }
143
149
 
144
- if (sub === 'delete') {
150
+ if (sub === "delete") {
145
151
  const { values, positionals } = parseArgs(rest, {});
146
- if (!positionals[0]) throw new Error('hash required');
147
- const data = await api('DELETE', `/keys/${encodeURIComponent(positionals[0])}`, {
152
+ if (!positionals[0]) throw new Error("hash required");
153
+ const data = await api("DELETE", `/keys/${encodeURIComponent(positionals[0])}`, {
148
154
  auth: authFromValues(values),
149
- requiresManagement: true
155
+ requiresManagement: true,
150
156
  });
151
- printResult(data, () => outln('deleted'));
157
+ printResult(data, () => outln("deleted"));
152
158
  return 0;
153
159
  }
154
160
 
@@ -1,18 +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, numberOption } from '../args.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
7
  import {
8
8
  loadConfig,
9
9
  saveConfig,
10
10
  DEFAULT_AUTH_URL,
11
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';
12
+ PROVISIONING_KEYS_URL,
13
+ } from "../config.js";
14
+ import { api } from "../api.js";
15
+ import { c, info, isJsonMode, outln, printJSON } from "../output.js";
16
16
 
17
17
  const HELP = `Usage: openrouter login [options]
18
18
 
@@ -49,29 +49,25 @@ Environment:
49
49
 
50
50
  function base64url(buf) {
51
51
  return Buffer.from(buf)
52
- .toString('base64')
53
- .replace(/\+/g, '-')
54
- .replace(/\//g, '_')
55
- .replace(/=+$/, '');
52
+ .toString("base64")
53
+ .replace(/\+/g, "-")
54
+ .replace(/\//g, "_")
55
+ .replace(/=+$/, "");
56
56
  }
57
57
 
58
58
  function openBrowser(url) {
59
59
  const cmd =
60
- process.platform === 'darwin'
61
- ? 'open'
62
- : process.platform === 'win32'
63
- ? 'cmd'
64
- : 'xdg-open';
65
- const args = process.platform === 'win32' ? ['/c', 'start', '""', url] : [url];
66
- const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
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" });
67
63
  // Best effort: the URL is printed either way, and a missing launcher arrives
68
64
  // as an async 'error' event that would otherwise crash the process.
69
- child.on('error', () => {});
65
+ child.on("error", () => {});
70
66
  child.unref();
71
67
  }
72
68
 
73
69
  async function readFromStdin() {
74
- let data = '';
70
+ let data = "";
75
71
  for await (const chunk of stdin) data += chunk;
76
72
  return data.trim();
77
73
  }
@@ -79,7 +75,7 @@ async function readFromStdin() {
79
75
  async function promptKey() {
80
76
  const rl = readline.createInterface({ input: stdin, output: stdout });
81
77
  try {
82
- 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-...): ");
83
79
  return answer.trim();
84
80
  } finally {
85
81
  rl.close();
@@ -104,7 +100,7 @@ async function promptManagementKey() {
104
100
  const rl = readline.createInterface({ input: stdin, output: stdout });
105
101
  try {
106
102
  const answer = await rl.question(
107
- `Paste your OpenRouter management key (sk-or-v1-...). Create one at\n ${PROVISIONING_KEYS_URL}\n› `
103
+ `Paste your OpenRouter management key (sk-or-v1-...). Create one at\n ${PROVISIONING_KEYS_URL}\n› `,
108
104
  );
109
105
  return answer.trim();
110
106
  } finally {
@@ -114,136 +110,136 @@ async function promptManagementKey() {
114
110
 
115
111
  async function pkceFlow({ port, openInBrowser, authUrl, baseUrl }) {
116
112
  const verifier = base64url(crypto.randomBytes(48));
117
- const challenge = base64url(
118
- crypto.createHash('sha256').update(verifier).digest()
119
- );
113
+ const challenge = base64url(crypto.createHash("sha256").update(verifier).digest());
120
114
 
121
115
  const codePromise = new Promise((resolve, reject) => {
122
116
  const server = http.createServer((req, res) => {
123
117
  const u = new URL(req.url, `http://localhost`);
124
- if (u.pathname !== '/callback') {
125
- res.writeHead(404).end('not found');
118
+ if (u.pathname !== "/callback") {
119
+ res.writeHead(404).end("not found");
126
120
  return;
127
121
  }
128
- const code = u.searchParams.get('code');
129
- const error = u.searchParams.get('error');
122
+ const code = u.searchParams.get("code");
123
+ const error = u.searchParams.get("error");
130
124
  const html = (title, body) =>
131
125
  `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>` +
132
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}` +
133
127
  `code{background:#f4f4f5;padding:.1rem .35rem;border-radius:.25rem}</style></head><body>${body}</body></html>`;
134
128
  if (error) {
135
- res.writeHead(400, { 'Content-Type': 'text/html' }).end(
136
- html('Login failed', `<h1>Login failed</h1><p>${error}</p>`)
137
- );
129
+ res
130
+ .writeHead(400, { "Content-Type": "text/html" })
131
+ .end(html("Login failed", `<h1>Login failed</h1><p>${error}</p>`));
138
132
  server.close();
139
133
  reject(new Error(`OAuth error: ${error}`));
140
134
  return;
141
135
  }
142
136
  if (!code) {
143
- res.writeHead(400, { 'Content-Type': 'text/html' }).end(
144
- html('Missing code', '<h1>Missing code</h1>')
145
- );
137
+ res
138
+ .writeHead(400, { "Content-Type": "text/html" })
139
+ .end(html("Missing code", "<h1>Missing code</h1>"));
146
140
  return;
147
141
  }
148
- res.writeHead(200, { 'Content-Type': 'text/html' }).end(
149
- html(
150
- 'OpenRouter CLI: signed in',
151
- '<h1>You are signed in.</h1><p>You can close this tab and return to the terminal.</p>'
152
- )
153
- );
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
+ );
154
150
  setTimeout(() => server.close(), 100);
155
151
  resolve(code);
156
152
  });
157
- server.on('error', reject);
158
- server.listen(port || 0, '127.0.0.1', () => {
153
+ server.on("error", reject);
154
+ server.listen(port || 0, "127.0.0.1", () => {
159
155
  const actualPort = server.address().port;
160
156
  const callback = `http://localhost:${actualPort}/callback`;
161
157
  const params = new URLSearchParams({
162
158
  callback_url: callback,
163
159
  code_challenge: challenge,
164
- code_challenge_method: 'S256'
160
+ code_challenge_method: "S256",
165
161
  });
166
162
  const url = `${authUrl}?${params.toString()}`;
167
163
  info(`Listening on ${callback}`);
168
164
  if (openInBrowser) {
169
- info('Opening browser...');
165
+ info("Opening browser...");
170
166
  openBrowser(url);
171
167
  }
172
- outln(c.bold('Open this URL to sign in:'));
173
- outln(' ' + c.cyan(url));
174
- outln('');
175
- 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)...");
176
172
  });
177
173
  });
178
174
 
179
175
  const code = await codePromise;
180
- info('Exchanging authorization code for API key...');
181
- const data = await api('POST', '/auth/keys', {
176
+ info("Exchanging authorization code for API key...");
177
+ const data = await api("POST", "/auth/keys", {
182
178
  requireAuth: false,
183
179
  auth: { baseUrl },
184
180
  body: {
185
181
  code,
186
182
  code_verifier: verifier,
187
- code_challenge_method: 'S256'
188
- }
183
+ code_challenge_method: "S256",
184
+ },
189
185
  });
190
186
  return data;
191
187
  }
192
188
 
193
189
  export async function loginCommand(argv) {
194
190
  const { values } = parseArgs(argv, {
195
- 'no-browser': { type: 'boolean' },
196
- port: { type: 'string' },
197
- 'auth-url': { type: 'string' },
198
- stdin: { type: 'boolean' },
199
- 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" },
200
196
  });
201
197
  if (values.help) {
202
198
  process.stdout.write(HELP);
203
199
  return 0;
204
200
  }
205
201
 
206
- const baseUrl = values['base-url'] || DEFAULT_BASE_URL;
207
- 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;
208
204
 
209
205
  // Management-key path: never OAuth, always paste/stdin/--key.
210
206
  if (values.management) {
211
207
  let key = values.key;
212
208
  if (!key && values.stdin) key = await readFromStdin();
213
209
  if (!key) key = await promptManagementKey();
214
- if (!key || !key.startsWith('sk-or-')) {
210
+ if (!key || !key.startsWith("sk-or-")) {
215
211
  throw new Error('Expected management key starting with "sk-or-".');
216
212
  }
217
213
  await saveManagementKey(key, {
218
- baseUrl: values['base-url'] || undefined
214
+ baseUrl: values["base-url"] || undefined,
219
215
  });
220
- if (isJsonMode()) printJSON({ saved: true, slot: 'management' });
216
+ if (isJsonMode()) printJSON({ saved: true, slot: "management" });
221
217
  else info(`Saved management key (${key.slice(0, 12)}...).`);
222
218
  return 0;
223
219
  }
224
220
 
225
221
  if (values.key || values.stdin) {
226
222
  const key = values.key || (await readFromStdin());
227
- if (!key || !key.startsWith('sk-or-')) {
223
+ if (!key || !key.startsWith("sk-or-")) {
228
224
  throw new Error('Expected API key starting with "sk-or-".');
229
225
  }
230
226
  await saveKey(key, {
231
- baseUrl: values['base-url'] || undefined
227
+ baseUrl: values["base-url"] || undefined,
232
228
  });
233
229
  info(`Saved API key (${key.slice(0, 12)}...).`);
234
- if (isJsonMode()) printJSON({ saved: true, slot: 'user' });
230
+ if (isJsonMode()) printJSON({ saved: true, slot: "user" });
235
231
  return 0;
236
232
  }
237
233
 
238
234
  // Interactive: OAuth PKCE, falling back to manual paste only if it fails.
239
- const port = numberOption(values.port, '--port') ?? 0;
235
+ const port = numberOption(values.port, "--port") ?? 0;
240
236
  let result;
241
237
  try {
242
238
  result = await pkceFlow({
243
239
  port,
244
- openInBrowser: !values['no-browser'],
240
+ openInBrowser: !values["no-browser"],
245
241
  authUrl,
246
- baseUrl
242
+ baseUrl,
247
243
  });
248
244
  } catch (err) {
249
245
  if (process.env.OPENROUTER_DEBUG) info(String(err.stack || err));
@@ -251,38 +247,38 @@ export async function loginCommand(argv) {
251
247
  // answer one.
252
248
  if (isJsonMode() || !stdin.isTTY) throw err;
253
249
  process.stderr.write(`OAuth flow failed: ${err.message}\n`);
254
- info('Falling back to manual key entry.');
250
+ info("Falling back to manual key entry.");
255
251
  const key = await promptKey();
256
- if (!key) throw new Error('No API key provided.');
252
+ if (!key) throw new Error("No API key provided.");
257
253
  await saveKey(key);
258
- if (isJsonMode()) printJSON({ saved: true, mode: 'manual' });
259
- else info('Saved API key.');
254
+ if (isJsonMode()) printJSON({ saved: true, mode: "manual" });
255
+ else info("Saved API key.");
260
256
  return 0;
261
257
  }
262
258
 
263
259
  await saveKey(result.key, {
264
260
  userId: result.user_id,
265
- baseUrl: values['base-url'] || undefined
261
+ baseUrl: values["base-url"] || undefined,
266
262
  });
267
263
  if (isJsonMode()) {
268
264
  printJSON({ saved: true, user_id: result.user_id });
269
265
  } else {
270
- 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}`));
271
267
  }
272
268
  return 0;
273
269
  }
274
270
 
275
271
  export async function logoutCommand(argv) {
276
272
  const { values } = parseArgs(argv, {
277
- management: { type: 'boolean' },
278
- all: { type: 'boolean' }
273
+ management: { type: "boolean" },
274
+ all: { type: "boolean" },
279
275
  });
280
276
  if (values.help) {
281
277
  process.stdout.write(
282
- 'Usage: openrouter logout [--management|--all]\n\n' +
283
- 'Remove the locally stored API key. By default removes the user key.\n' +
284
- ' --management Remove the management key only\n' +
285
- ' --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",
286
282
  );
287
283
  return 0;
288
284
  }
@@ -292,21 +288,21 @@ export async function logoutCommand(argv) {
292
288
  if (cfg.apiKey) {
293
289
  delete cfg.apiKey;
294
290
  delete cfg.userId;
295
- removed.push('user');
291
+ removed.push("user");
296
292
  }
297
293
  }
298
294
  if (values.all || values.management) {
299
295
  if (cfg.managementKey) {
300
296
  delete cfg.managementKey;
301
- removed.push('management');
297
+ removed.push("management");
302
298
  }
303
299
  }
304
300
  if (!removed.length) {
305
- info('No matching key was stored.');
301
+ info("No matching key was stored.");
306
302
  return 0;
307
303
  }
308
304
  await saveConfig(cfg);
309
305
  if (isJsonMode()) printJSON({ logged_out: removed });
310
- else info(`Logged out (${removed.join(', ')}).`);
306
+ else info(`Logged out (${removed.join(", ")}).`);
311
307
  return 0;
312
308
  }