@everyai/cli 0.7.0 → 0.7.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.
@@ -2,11 +2,12 @@ import { access } from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { createInterface } from 'node:readline/promises';
5
- import { environmentNameForBaseUrl, resolveBaseUrl, signupUrlForBaseUrl, } from '../lib/config.js';
5
+ import { apiKeysUrlForBaseUrl, environmentNameForBaseUrl, resolveBaseUrl, signupUrlForBaseUrl, } from '../lib/config.js';
6
6
  import { CliError } from '../lib/errors.js';
7
7
  import { ExitCode } from '../lib/exit-codes.js';
8
8
  import { mcpCall } from '../lib/mcp.js';
9
9
  import { loginFlow, openBrowser as openBrowserDefault } from '../lib/auth/flow.js';
10
+ import { activeCredentialIsApiKey, isApiKeyToken } from '../lib/auth/api-key.js';
10
11
  import { decodeJwtClaims } from '../lib/auth/jwt.js';
11
12
  import { createTokenStore, deleteTokenFromAllStores, getAuthStatus, getToken, resolveAuthTarget, } from '../lib/auth/tokens.js';
12
13
  import { fetchUserInfo, invalidateUserInfoCache, readCachedUserInfo, requestUserInfo, writeUserInfoCache, } from '../lib/auth/userinfo.js';
@@ -124,7 +125,9 @@ function emitCommand(data, human, opts) {
124
125
  process.stdout.write(`${human}\n`);
125
126
  }
126
127
  function identityFromToken(token) {
127
- const claims = decodeJwtClaims(token);
128
+ // An API key carries no claims; decoding its secret half as a JWT payload
129
+ // could only produce noise.
130
+ const claims = isApiKeyToken(token) ? null : decodeJwtClaims(token);
128
131
  return {
129
132
  subject: claims?.sub ?? null,
130
133
  email: claims?.email ?? null,
@@ -154,13 +157,18 @@ function emitLogin(data, opts, output = process.stdout, errorOutput = process.st
154
157
  output.write(`${human}\n`);
155
158
  }
156
159
  }
160
+ function everyTokenStatusLabel(status) {
161
+ if (!status.every_token)
162
+ return 'not set';
163
+ return status.auth_method === 'api_key' ? 'overriding (Every API key)' : 'overriding';
164
+ }
157
165
  function statusHuman(status) {
158
166
  return [
159
167
  `Logged in: ${status.logged_in ? 'yes' : 'no'}`,
160
168
  `Environment: ${status.environment}`,
161
169
  `Base URL: ${status.base_url}`,
162
170
  `Storage: ${status.storage_backend}`,
163
- `EVERY_TOKEN: ${status.every_token ? 'overriding' : 'not set'}`,
171
+ `EVERY_TOKEN: ${everyTokenStatusLabel(status)}`,
164
172
  `Issuer: ${status.issuer ?? 'none'}`,
165
173
  `Expires: ${status.expires ?? 'unknown'}`,
166
174
  `Refresh token: ${status.refresh_token ? 'yes' : 'no'}`,
@@ -168,6 +176,7 @@ function statusHuman(status) {
168
176
  }
169
177
  function orgFromUserInfo(userinfo) {
170
178
  return {
179
+ auth_method: 'oauth',
171
180
  org_id: userinfo.org_id,
172
181
  org_slug: userinfo.org_slug,
173
182
  org_name: userinfo.org_name,
@@ -185,6 +194,34 @@ function orgHuman(org) {
185
194
  ];
186
195
  return lines.join('\n');
187
196
  }
197
+ /**
198
+ * What an API key can truthfully say about its workspace.
199
+ *
200
+ * The key IS bound to exactly one org, but that binding lives server-side: the
201
+ * MCP surface hands a key no org identity (the only tool that reports one,
202
+ * `get_home`, is denied to keys), and the OAuth userinfo endpoint cannot resolve
203
+ * the key at all. So the workspace is stated as unavailable rather than guessed
204
+ * at, and there is no `every org switch` suggestion — a key cannot switch.
205
+ */
206
+ const API_KEY_ORG_LINE = 'Org: not reported for API keys — the key is bound to one workspace on the server';
207
+ function apiKeyOrgHuman(environment, baseUrl) {
208
+ return [
209
+ API_KEY_ORG_LINE,
210
+ 'Authenticated: yes (Every API key)',
211
+ `Environment: ${environment} (${baseUrl})`,
212
+ 'Note: the server scopes writes to the key\'s workspace.',
213
+ `Manage keys in Every: Settings → API keys (${apiKeysUrlForBaseUrl(baseUrl)})`,
214
+ ].join('\n');
215
+ }
216
+ function apiKeyWhoamiHuman(data) {
217
+ return [
218
+ 'Authenticated: yes (Every API key)',
219
+ API_KEY_ORG_LINE,
220
+ `Environment: ${data.environment} (${data.base_url})`,
221
+ `Tools: ${data.tools} available to this key`,
222
+ `Manage keys in Every: Settings → API keys (${apiKeysUrlForBaseUrl(data.base_url)})`,
223
+ ].join('\n');
224
+ }
188
225
  function formatUser(userinfo) {
189
226
  if (userinfo.name && userinfo.email)
190
227
  return `${userinfo.name} (${userinfo.email})`;
@@ -219,7 +256,11 @@ function validateBrowserLogin(opts, switching = false) {
219
256
  if (opts.org !== undefined)
220
257
  validateOrgTarget(opts.org);
221
258
  if (process.env.EVERY_TOKEN && (switching || opts.org !== undefined)) {
222
- throw new CliError('Workspace switching requires stored credentials; unset EVERY_TOKEN and try again.', ExitCode.USAGE, 'usage');
259
+ throw new CliError(activeCredentialIsApiKey()
260
+ ? 'An Every API key is bound to one workspace and cannot switch. ' +
261
+ 'Workspace switching requires stored credentials; unset EVERY_TOKEN and try again, ' +
262
+ 'or mint a key in the other workspace under Settings → API keys.'
263
+ : 'Workspace switching requires stored credentials; unset EVERY_TOKEN and try again.', ExitCode.USAGE, 'usage');
223
264
  }
224
265
  }
225
266
  /** Exchange, verify, then commit. A failed assertion never mutates stored auth or identity. */
@@ -425,14 +466,48 @@ export async function authStatusCommand(opts = {}) {
425
466
  const status = await getAuthStatus({ staging: opts.staging });
426
467
  emitCommand(status, statusHuman(status), opts);
427
468
  }
469
+ /**
470
+ * `every whoami` for an org API key.
471
+ *
472
+ * The key is verified where it is actually valid — the MCP server — instead of
473
+ * at the Clerk userinfo endpoint, which knows nothing about it and answers 401.
474
+ * `tools/list` is the right probe: it needs no scope of its own, and the server
475
+ * filters it to the key's scopes, so the count doubles as "what this key can
476
+ * do". A rejected key surfaces its own reason from mcpCall, never a login
477
+ * prompt. Identity fields stay null because no reachable surface reports them
478
+ * for a key — never guessed from a cache written by some other credential.
479
+ */
480
+ async function apiKeyWhoami(baseUrl, opts) {
481
+ const token = await getToken({ baseUrl });
482
+ const liveness = await verifyMcpLiveness(baseUrl, token);
483
+ const data = {
484
+ authenticated: liveness.authenticated,
485
+ auth_method: 'api_key',
486
+ user_id: null,
487
+ subject: null,
488
+ email: null,
489
+ name: null,
490
+ org_id: null,
491
+ org_slug: null,
492
+ org_name: null,
493
+ environment: environmentNameForBaseUrl(baseUrl),
494
+ base_url: baseUrl,
495
+ tools: liveness.tools,
496
+ };
497
+ emitCommand(data, apiKeyWhoamiHuman(data), opts);
498
+ await maybeShowSkillHint();
499
+ }
428
500
  export async function whoamiCommand(opts = {}) {
429
501
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
502
+ if (activeCredentialIsApiKey())
503
+ return apiKeyWhoami(baseUrl, opts);
430
504
  const userinfo = await fetchUserInfo({ baseUrl });
431
505
  const token = await getToken({ baseUrl });
432
506
  const liveness = await verifyMcpLiveness(baseUrl, token);
433
507
  const environment = environmentNameForBaseUrl(baseUrl);
434
508
  const data = {
435
509
  authenticated: liveness.authenticated,
510
+ auth_method: 'oauth',
436
511
  user_id: userinfo.user_id,
437
512
  subject: userinfo.user_id,
438
513
  email: userinfo.email,
@@ -455,6 +530,22 @@ export async function whoamiCommand(opts = {}) {
455
530
  }
456
531
  export async function orgCommand(opts = {}) {
457
532
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
533
+ if (activeCredentialIsApiKey()) {
534
+ // Still verify the credential against the MCP server, so a dead key reports
535
+ // itself as rejected rather than quietly returning an empty workspace.
536
+ await verifyMcpLiveness(baseUrl, await getToken({ baseUrl }));
537
+ const org = {
538
+ auth_method: 'api_key',
539
+ org_id: null,
540
+ org_slug: null,
541
+ org_name: null,
542
+ organization_id: null,
543
+ organization_slug: null,
544
+ organization_name: null,
545
+ };
546
+ emitCommand(org, apiKeyOrgHuman(environmentNameForBaseUrl(baseUrl), baseUrl), opts);
547
+ return;
548
+ }
458
549
  const org = orgFromUserInfo(await fetchUserInfo({ baseUrl }));
459
550
  emitCommand(org, orgHuman(org), opts);
460
551
  }
@@ -5,6 +5,7 @@ import { ExitCode } from '../lib/exit-codes.js';
5
5
  import { callTool, listTools } from '../lib/mcp.js';
6
6
  import { emit } from '../lib/output.js';
7
7
  import { classify, promptForTool, requirementDescription, requirementFor, } from '../lib/policy.js';
8
+ import { activeCredentialIsApiKey } from '../lib/auth/api-key.js';
8
9
  import { getToken } from '../lib/auth/tokens.js';
9
10
  import { fetchUserInfo } from '../lib/auth/userinfo.js';
10
11
  import { maybeShowSkillHint } from '../lib/hints.js';
@@ -210,11 +211,19 @@ function orgLabel(userinfo) {
210
211
  };
211
212
  }
212
213
  function targetLabel(userinfo, environment) {
214
+ // An API key resolves no userinfo by design, so name the credential instead
215
+ // of reporting "unknown org" as though a lookup had failed.
216
+ if (activeCredentialIsApiKey())
217
+ return `the API key's workspace · ${environment}`;
213
218
  const orgName = userinfo?.org_name ?? 'unknown org';
214
219
  const orgId = userinfo?.org_id ?? 'unknown';
215
220
  return `${orgName} (${orgId}) · ${environment}`;
216
221
  }
217
222
  async function resolveWriteTarget(baseUrl) {
223
+ // API keys have no OAuth identity to resolve; asking would fail every time
224
+ // and print a "could not verify target org" warning that names the wrong fix.
225
+ if (activeCredentialIsApiKey())
226
+ return undefined;
218
227
  try {
219
228
  return await fetchUserInfo({ baseUrl });
220
229
  }
@@ -0,0 +1,77 @@
1
+ import { apiKeysUrlForBaseUrl } from '../config.js';
2
+ /**
3
+ * Org API keys — the headless credential.
4
+ *
5
+ * An org admin mints one in Every under Settings → API keys; it looks like
6
+ * `evk_<uuid>.<secret>` and is presented to the CLI as `EVERY_TOKEN`. Unlike a
7
+ * browser login it is NOT a Clerk OAuth credential: the MCP server validates it
8
+ * locally against `org_api_keys` and never sends it to Clerk. Two consequences
9
+ * drive every branch that imports this module:
10
+ *
11
+ * 1. The OAuth userinfo endpoint cannot resolve a key, so any identity lookup
12
+ * that assumes a Clerk token reports "not logged in" for a perfectly valid
13
+ * key. Identity resolution must branch on `isApiKeyToken` first.
14
+ * 2. A key is not a JWT, so `decodeJwtClaims` cannot read a subject, email or
15
+ * expiry from it. Callers must not infer identity or expiry from the string.
16
+ *
17
+ * This is the single place that knows the token shape — never string-match
18
+ * `evk_` anywhere else.
19
+ */
20
+ export const API_KEY_TOKEN_PREFIX = 'evk_';
21
+ /** True when `token` is an Every org API key rather than a Clerk OAuth token. */
22
+ export function isApiKeyToken(token) {
23
+ return typeof token === 'string' && token.startsWith(API_KEY_TOKEN_PREFIX);
24
+ }
25
+ /** True when this process's credential (`EVERY_TOKEN`) is an org API key. */
26
+ export function activeCredentialIsApiKey() {
27
+ return isApiKeyToken(process.env.EVERY_TOKEN);
28
+ }
29
+ /** Classify the credential a command is about to use. */
30
+ export function authMethodForToken(token) {
31
+ return isApiKeyToken(token) ? 'api_key' : 'oauth';
32
+ }
33
+ /**
34
+ * Pull the server's own reason out of a 401/403 body.
35
+ *
36
+ * Verified shape — admin-mcp's `ClerkAuthMiddleware` answers a rejected bearer
37
+ * with `{"error":"invalid_token","error_description":"Invalid or expired token"}`
38
+ * (JSON, RFC 6750 field names, and no `WWW-Authenticate` header on this path;
39
+ * the header only appears when no bearer was sent at all). Anything that is not
40
+ * that shape yields `undefined` so the caller falls back to its own copy — this
41
+ * never guesses at a body it has not seen.
42
+ */
43
+ export function authErrorReasonFromBody(raw) {
44
+ let parsed;
45
+ try {
46
+ parsed = JSON.parse(raw);
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
52
+ return undefined;
53
+ const body = parsed;
54
+ const candidate = [body.error_description, body.error].find((value) => typeof value === 'string' && value.trim().length > 0);
55
+ if (candidate === undefined)
56
+ return undefined;
57
+ // Server copy is rendered into a terminal: flatten it and bound it so an
58
+ // unexpected payload can never reshape the CLI's own error output.
59
+ const flattened = candidate.replace(/\s+/g, ' ').trim();
60
+ return flattened.length > 200 ? `${flattened.slice(0, 197)}...` : flattened;
61
+ }
62
+ /**
63
+ * The message for a rejected API key. Deliberately enumerates the causes the
64
+ * server collapses into one generic 401: it logs which one applied, the client
65
+ * only ever sees "Invalid or expired token".
66
+ *
67
+ * Never interpolates the key itself.
68
+ */
69
+ export function apiKeyRejectedMessage(baseUrl, serverReason) {
70
+ const origin = serverReason
71
+ ? `HTTP 401 from ${baseUrl}; server said: ${serverReason}`
72
+ : `HTTP 401 from ${baseUrl}`;
73
+ return (`Every rejected the API key in EVERY_TOKEN (${origin}). ` +
74
+ 'The key may be invalid, expired or revoked, or the admin who created it may no longer ' +
75
+ 'be an admin of its workspace. ' +
76
+ `Check it in Every under Settings → API keys: ${apiKeysUrlForBaseUrl(baseUrl)}`);
77
+ }
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { getConfigDir, PROD_BASE_URL, resolveBaseUrl, STAGING_BASE_URL } from '../config.js';
4
4
  import { CliError } from '../errors.js';
5
5
  import { ExitCode } from '../exit-codes.js';
6
+ import { authMethodForToken, isApiKeyToken } from './api-key.js';
6
7
  import { DEFAULT_SCOPE } from './dcr.js';
7
8
  import { discoverOAuth, fetchJsonWithTimeout, HttpStatusError } from './discovery.js';
8
9
  import { decodeJwtClaims } from './jwt.js';
@@ -273,7 +274,10 @@ export async function getAuthStatus(opts = {}) {
273
274
  const now = opts.now ?? Date.now;
274
275
  const override = process.env.EVERY_TOKEN;
275
276
  const stored = await store.get(environmentKey);
276
- const claims = override ? decodeJwtClaims(override) : null;
277
+ // An API key is not a JWT: its secret half is arbitrary base64url text, so
278
+ // decoding it as claims can only ever yield nothing or a fabricated expiry.
279
+ const apiKey = isApiKeyToken(override);
280
+ const claims = override && !apiKey ? decodeJwtClaims(override) : null;
277
281
  const expiresAt = override ? claims?.exp : stored?.expires_at;
278
282
  const expiresIn = typeof expiresAt === 'number' ? expiresAt - nowSeconds(now) : null;
279
283
  return {
@@ -282,6 +286,7 @@ export async function getAuthStatus(opts = {}) {
282
286
  base_url: baseUrl,
283
287
  storage_backend: store.backend,
284
288
  every_token: Boolean(override),
289
+ auth_method: override || stored ? authMethodForToken(override) : null,
285
290
  issuer: stored?.issuer ?? null,
286
291
  expires_at: typeof expiresAt === 'number' ? expiresAt : null,
287
292
  expires_in_seconds: expiresIn,
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { getConfigDir } from '../config.js';
4
4
  import { CliError } from '../errors.js';
5
5
  import { ExitCode } from '../exit-codes.js';
6
+ import { isApiKeyToken } from './api-key.js';
6
7
  import { discoverOAuth, fetchJsonWithTimeout, HttpStatusError } from './discovery.js';
7
8
  import { environmentKeyForBaseUrl, getToken, resolveAuthTarget, } from './tokens.js';
8
9
  const USERINFO_TIMEOUT_MS = 10_000;
@@ -98,6 +99,14 @@ async function fetchOpenIdConfiguration(issuer) {
98
99
  export async function fetchUserInfo(opts = {}) {
99
100
  const { baseUrl } = resolveAuthTarget(opts);
100
101
  const token = await getToken({ baseUrl, store: opts.store, now: opts.now });
102
+ // An API key has no OAuth identity to fetch. Refusing here — BEFORE the cache
103
+ // read — also stops the identity cache from answering for the wrong
104
+ // credential: it is keyed by base URL alone, so a login earlier on this
105
+ // machine would otherwise have this key's caller shown another account's org.
106
+ if (isApiKeyToken(token)) {
107
+ throw new CliError('An Every API key has no OAuth user identity to look up. ' +
108
+ 'Run \'every whoami\' to verify the key instead.', ExitCode.AUTH, 'auth');
109
+ }
101
110
  if (!opts.forceRefresh) {
102
111
  const cached = await readCachedUserInfo(baseUrl, { now: opts.now }).catch(() => undefined);
103
112
  if (cached)
@@ -17,6 +17,9 @@ export const PROD_BASE_URL = 'https://admin-mcp.every.ai';
17
17
  export const STAGING_BASE_URL = 'https://admin-mcp-staging.up.railway.app';
18
18
  export const PROD_SIGNUP_URL = 'https://app.every.ai/sign-up';
19
19
  export const STAGING_SIGNUP_URL = 'https://app.staging.every.ai/sign-up';
20
+ /** Where an org admin mints, inspects and revokes org API keys. */
21
+ export const PROD_API_KEYS_URL = 'https://app.every.ai/settings/api-keys';
22
+ export const STAGING_API_KEYS_URL = 'https://app.staging.every.ai/settings/api-keys';
20
23
  /**
21
24
  * Resolve the MCP base URL to target.
22
25
  *
@@ -55,3 +58,9 @@ export function signupUrlForBaseUrl(baseUrl) {
55
58
  ? STAGING_SIGNUP_URL
56
59
  : PROD_SIGNUP_URL;
57
60
  }
61
+ /** The web-app page that manages the API keys a given MCP base URL accepts. */
62
+ export function apiKeysUrlForBaseUrl(baseUrl) {
63
+ return environmentNameForBaseUrl(baseUrl) === 'staging'
64
+ ? STAGING_API_KEYS_URL
65
+ : PROD_API_KEYS_URL;
66
+ }
package/dist/lib/mcp.js CHANGED
@@ -4,6 +4,7 @@ import { getConfigDir } from './config.js';
4
4
  import { CliError } from './errors.js';
5
5
  import { ExitCode } from './exit-codes.js';
6
6
  import { environmentKeyForBaseUrl } from './auth/tokens.js';
7
+ import { apiKeyRejectedMessage, authErrorReasonFromBody, isApiKeyToken } from './auth/api-key.js';
7
8
  const DEFAULT_MCP_TIMEOUT_MS = 30_000;
8
9
  const DEFAULT_TOOL_TIMEOUT_MS = 120_000;
9
10
  const TOOL_CACHE_TTL_MS = 10 * 60 * 1000;
@@ -100,6 +101,28 @@ function parseJsonRpcResponse(raw, params) {
100
101
  throw jsonRpcErrorToCliError(body.error, params);
101
102
  return body.result;
102
103
  }
104
+ /**
105
+ * Explain a 401 in terms of the credential that was actually rejected.
106
+ *
107
+ * An OAuth session and an org API key fail for disjoint reasons and have
108
+ * disjoint fixes, and the server collapses both into one generic body — so the
109
+ * client is the only place that can name the right one. `every login` is the
110
+ * fix for a stale OAuth session and is actively misleading for a key, whose
111
+ * whole purpose is that nobody is signed in.
112
+ */
113
+ async function unauthorizedError(response, baseUrl, token) {
114
+ if (!isApiKeyToken(token)) {
115
+ return new CliError('Not logged in. Run \'every login\'.', ExitCode.AUTH, 'auth');
116
+ }
117
+ let reason;
118
+ try {
119
+ reason = authErrorReasonFromBody(await response.text());
120
+ }
121
+ catch {
122
+ // A body that cannot be read is not a reason to lose the diagnosis.
123
+ }
124
+ return new CliError(apiKeyRejectedMessage(baseUrl, reason), ExitCode.AUTH, 'auth');
125
+ }
103
126
  export async function mcpCall(baseUrl, token, method, params = {}, { timeoutMs = DEFAULT_MCP_TIMEOUT_MS } = {}) {
104
127
  const url = mcpUrl(baseUrl);
105
128
  let response;
@@ -128,7 +151,7 @@ export async function mcpCall(baseUrl, token, method, params = {}, { timeoutMs =
128
151
  throw new CliError(`Failed to reach ${url}: ${detail}`, ExitCode.NETWORK, 'network');
129
152
  }
130
153
  if (response.status === 401) {
131
- throw new CliError('Not logged in. Run \'every login\'.', ExitCode.AUTH, 'auth');
154
+ throw await unauthorizedError(response, baseUrl, token);
132
155
  }
133
156
  if (!response.ok) {
134
157
  const classified = classifyHttpStatus(response.status);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@everyai/cli",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Every-AI-Inc/everyai-cli.git"