@everyai/cli 0.6.5 → 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.
package/README.md CHANGED
@@ -47,8 +47,9 @@ The CLI talks to the same Every MCP server (`admin-mcp.every.ai`) and inherits i
47
47
 
48
48
  ```bash
49
49
  # Auth
50
- every login [--create-account] [--staging] # browser OAuth; keychain storage; refresh handled
51
- every logout | whoami | auth status | org
50
+ every login [--create-account] [--org <name|slug|id>] [--staging] # browser OAuth; keychain storage; refresh handled
51
+ every logout | whoami | auth status
52
+ every org [switch --org <name|slug|id>]
52
53
 
53
54
  # Discovery
54
55
  every docs
@@ -75,6 +76,10 @@ every skills install codex # → .agents/skills/use-every/
75
76
 
76
77
  Run `every login` to choose between logging in and creating an account, or use `every login --create-account` to open Every's signup page directly. After you create your account and workspace, return to the terminal and press Enter; the CLI connects through the normal browser OAuth flow.
77
78
 
79
+ ## Switching workspaces
80
+
81
+ Run `every org switch` and pick the workspace in the browser consent page's selector. The token binds one workspace per environment; add `--staging` to switch staging. Use `every org switch --org "<name|slug|id>"` (or `every login --org "<name|slug|id>"`) to verify the selection after login. `--org` does not preselect a workspace; a mismatch keeps your previous credentials. Names can be ambiguous, so use the workspace id when needed. Verify the result with `every whoami --json`. Unset `EVERY_TOKEN` before switching because it overrides stored credentials.
82
+
78
83
  ## Output contract
79
84
 
80
85
  Every command supports `--json`: exactly one JSON document on stdout, nothing else.
@@ -2,14 +2,15 @@ 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
- import { fetchUserInfo } from '../lib/auth/userinfo.js';
13
+ import { fetchUserInfo, invalidateUserInfoCache, readCachedUserInfo, requestUserInfo, writeUserInfoCache, } from '../lib/auth/userinfo.js';
13
14
  import { maybeShowSkillHint, readHints, writeHints, } from '../lib/hints.js';
14
15
  import { emit } from '../lib/output.js';
15
16
  import { installBundledSkill } from './skills.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,
@@ -134,7 +137,7 @@ function loginHuman(data) {
134
137
  if (data.every_token)
135
138
  return 'EVERY_TOKEN is set; login is unnecessary.';
136
139
  const identity = data.email ?? data.subject;
137
- return identity ? `Logged in as ${identity}` : 'Logged in';
140
+ return `Logged in as ${identity ?? 'unknown'} · workspace ${formatOrg(data.org_name, data.org_id)}\nSwitch workspace: every org switch`;
138
141
  }
139
142
  function loginNextSteps() {
140
143
  return [
@@ -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,
@@ -181,9 +190,38 @@ function orgHuman(org) {
181
190
  `Org: ${formatOrg(org.org_name, org.org_id)}`,
182
191
  `Slug: ${org.org_slug ?? 'none'}`,
183
192
  'Note: the server scopes writes to this org.',
193
+ 'Switch: every org switch [--org <name|slug|id>]',
184
194
  ];
185
195
  return lines.join('\n');
186
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
+ }
187
225
  function formatUser(userinfo) {
188
226
  if (userinfo.name && userinfo.email)
189
227
  return `${userinfo.name} (${userinfo.email})`;
@@ -201,39 +239,135 @@ async function verifyMcpLiveness(baseUrl, token) {
201
239
  tools: Array.isArray(body.tools) ? body.tools.length : 0,
202
240
  };
203
241
  }
204
- async function runBrowserLogin(opts, streams = {
205
- input: process.stdin,
206
- output: process.stdout,
207
- errorOutput: process.stderr,
208
- }) {
242
+ function validateOrgTarget(target) {
243
+ if (!target.trim()) {
244
+ throw new CliError('--org must not be empty or whitespace-only', ExitCode.USAGE, 'usage');
245
+ }
246
+ }
247
+ /** IDs are exact; slugs ignore case; display names also trim and normalize Unicode. */
248
+ export function matchesOrg(target, info) {
249
+ validateOrgTarget(target);
250
+ const name = (value) => value.trim().normalize('NFC').toLowerCase();
251
+ return target === info.org_id ||
252
+ (info.org_slug !== null && target.toLowerCase() === info.org_slug.toLowerCase()) ||
253
+ (info.org_name !== null && name(target) === name(info.org_name));
254
+ }
255
+ function validateBrowserLogin(opts, switching = false) {
256
+ if (opts.org !== undefined)
257
+ validateOrgTarget(opts.org);
258
+ if (process.env.EVERY_TOKEN && (switching || opts.org !== undefined)) {
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');
264
+ }
265
+ }
266
+ /** Exchange, verify, then commit. A failed assertion never mutates stored auth or identity. */
267
+ export async function completeBrowserLogin(opts, deps = {}, switching = false) {
268
+ validateBrowserLogin(opts, switching);
269
+ const errorOutput = deps.errorOutput ?? process.stderr;
209
270
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
210
271
  const { environmentKey } = resolveAuthTarget({ baseUrl });
211
- const tokenSet = await loginFlow({
272
+ errorOutput.write(opts.org === undefined
273
+ ? "Pick the workspace in the consent page's selector.\n"
274
+ : `In the consent page's selector, pick "${opts.org}".\n`);
275
+ const tokenSet = await (deps.loginFlow ?? loginFlow)({
212
276
  baseUrl,
213
277
  onAuthorizationUrl(url) {
214
- streams.errorOutput.write(`Open this URL to log in:\n${url}\n`);
278
+ errorOutput.write(`Open this URL to log in:\n${url}\n`);
215
279
  },
216
280
  });
217
- const store = await createTokenStore();
218
- await store.set(environmentKey, tokenSet);
281
+ let userinfo;
282
+ try {
283
+ userinfo = await requestUserInfo({ baseUrl, accessToken: tokenSet.access_token });
284
+ }
285
+ catch {
286
+ if (switching || opts.org !== undefined) {
287
+ throw new CliError('Could not verify the workspace because userinfo is unreachable. Previous credentials kept; try again.', ExitCode.NETWORK, 'network');
288
+ }
289
+ }
290
+ if (opts.org !== undefined && userinfo && !matchesOrg(opts.org, userinfo)) {
291
+ throw new CliError(`Token is bound to workspace ${formatOrg(userinfo.org_name, userinfo.org_id)}, but requested "${opts.org}". ` +
292
+ `Retry: every org switch --org "${opts.org}" and pick that workspace in the consent page. ` +
293
+ 'Use the workspace id as the unambiguous form.', ExitCode.GENERIC, 'org_mismatch');
294
+ }
295
+ const store = deps.store ?? await createTokenStore();
296
+ const previous = await store.get(environmentKey);
297
+ try {
298
+ await store.set(environmentKey, tokenSet);
299
+ }
300
+ catch (err) {
301
+ try {
302
+ if (previous)
303
+ await store.set(environmentKey, previous);
304
+ else
305
+ await store.delete(environmentKey);
306
+ }
307
+ catch {
308
+ errorOutput.write('Warning: could not restore previous credentials after a storage failure.\n');
309
+ }
310
+ throw err;
311
+ }
312
+ if (userinfo) {
313
+ try {
314
+ await writeUserInfoCache(baseUrl, userinfo);
315
+ }
316
+ catch {
317
+ // A failed write may have left the old identity behind. Remove it if possible.
318
+ await invalidateUserInfoCache(baseUrl).catch(() => undefined);
319
+ errorOutput.write('Warning: logged in, but could not cache the current identity.\n');
320
+ }
321
+ }
322
+ else {
323
+ await invalidateUserInfoCache(baseUrl).catch(() => {
324
+ errorOutput.write('Warning: could not invalidate the previous identity cache.\n');
325
+ });
326
+ errorOutput.write('Warning: logged in, but userinfo is unreachable; workspace identity is unknown.\n');
327
+ }
219
328
  const identity = identityFromToken(tokenSet.access_token);
220
- const data = {
329
+ return {
221
330
  logged_in: true,
222
331
  issuer: tokenSet.issuer,
223
- subject: identity.subject,
224
- email: identity.email,
332
+ subject: userinfo?.user_id ?? identity.subject,
333
+ email: userinfo?.email ?? identity.email,
225
334
  storage_backend: store.backend,
226
335
  every_token: false,
336
+ user_id: userinfo?.user_id ?? null,
337
+ org_id: userinfo?.org_id ?? null,
338
+ org_slug: userinfo?.org_slug ?? null,
339
+ org_name: userinfo?.org_name ?? null,
227
340
  };
228
- emitLogin(data, opts, streams.output, streams.errorOutput);
229
- await maybeOfferSkillAfterLogin({
230
- json: opts.json,
231
- input: streams.input,
232
- output: streams.output,
233
- errorOutput: streams.errorOutput,
234
- });
341
+ }
342
+ export async function runBrowserLogin(opts, deps = {}) {
343
+ const data = await completeBrowserLogin(opts, deps);
344
+ emitLogin(data, opts, deps.output, deps.errorOutput);
345
+ await maybeOfferSkillAfterLogin({ json: opts.json, ...deps });
346
+ }
347
+ export async function orgSwitchCommand(opts = {}, deps = {}) {
348
+ validateBrowserLogin(opts, true);
349
+ if (!(deps.output ?? process.stdout).isTTY) {
350
+ throw new CliError('org switch requires a browser and an interactive terminal', ExitCode.AUTH, 'auth');
351
+ }
352
+ const baseUrl = resolveBaseUrl({ staging: opts.staging });
353
+ const previous = await readCachedUserInfo(baseUrl, { allowStale: true }).catch(() => undefined);
354
+ const login = await completeBrowserLogin(opts, deps, true);
355
+ const data = {
356
+ switched: true,
357
+ org_id: login.org_id,
358
+ org_slug: login.org_slug,
359
+ org_name: login.org_name,
360
+ previous_org_id: previous?.org_id ?? null,
361
+ environment: environmentNameForBaseUrl(baseUrl),
362
+ };
363
+ if (opts.json)
364
+ emit(data, { json: true, staging: opts.staging });
365
+ else
366
+ (deps.output ?? process.stdout).write(`Switched to ${formatOrg(data.org_name, data.org_id)} · ${login.email ?? 'unknown'}\n`);
367
+ await maybeOfferSkillAfterLogin({ json: opts.json, ...deps });
235
368
  }
236
369
  export async function createAccountFlow(opts = {}) {
370
+ validateBrowserLogin(opts);
237
371
  const input = opts.input ?? process.stdin;
238
372
  const output = opts.output ?? process.stdout;
239
373
  const errorOutput = opts.errorOutput ?? process.stderr;
@@ -275,6 +409,7 @@ async function promptForLoggedOutAction() {
275
409
  }
276
410
  }
277
411
  export async function loginCommand(opts = {}) {
412
+ validateBrowserLogin(opts);
278
413
  if (process.env.EVERY_TOKEN) {
279
414
  const identity = identityFromToken(process.env.EVERY_TOKEN);
280
415
  const data = {
@@ -284,6 +419,10 @@ export async function loginCommand(opts = {}) {
284
419
  email: identity.email,
285
420
  storage_backend: null,
286
421
  every_token: true,
422
+ user_id: null,
423
+ org_id: null,
424
+ org_slug: null,
425
+ org_name: null,
287
426
  };
288
427
  emitLogin(data, opts);
289
428
  return;
@@ -327,14 +466,48 @@ export async function authStatusCommand(opts = {}) {
327
466
  const status = await getAuthStatus({ staging: opts.staging });
328
467
  emitCommand(status, statusHuman(status), opts);
329
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
+ }
330
500
  export async function whoamiCommand(opts = {}) {
331
501
  const baseUrl = resolveBaseUrl({ staging: opts.staging });
502
+ if (activeCredentialIsApiKey())
503
+ return apiKeyWhoami(baseUrl, opts);
332
504
  const userinfo = await fetchUserInfo({ baseUrl });
333
505
  const token = await getToken({ baseUrl });
334
506
  const liveness = await verifyMcpLiveness(baseUrl, token);
335
507
  const environment = environmentNameForBaseUrl(baseUrl);
336
508
  const data = {
337
509
  authenticated: liveness.authenticated,
510
+ auth_method: 'oauth',
338
511
  user_id: userinfo.user_id,
339
512
  subject: userinfo.user_id,
340
513
  email: userinfo.email,
@@ -357,6 +530,22 @@ export async function whoamiCommand(opts = {}) {
357
530
  }
358
531
  export async function orgCommand(opts = {}) {
359
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
+ }
360
549
  const org = orgFromUserInfo(await fetchUserInfo({ baseUrl }));
361
550
  emitCommand(org, orgHuman(org), opts);
362
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
  }
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import { Command, CommanderError } from 'commander';
4
4
  import { pingCommand } from './commands/ping.js';
5
5
  import { docsCommand } from './commands/docs.js';
6
- import { authStatusCommand, loginCommand, logoutCommand, orgCommand, whoamiCommand, } from './commands/auth.js';
6
+ import { authStatusCommand, loginCommand, logoutCommand, orgCommand, orgSwitchCommand, whoamiCommand, } from './commands/auth.js';
7
7
  import { policyExplainCommand } from './commands/policy.js';
8
8
  import { toolCallCommand, toolsDescribeCommand, toolsListCommand, } from './commands/tools.js';
9
9
  import { contactListCommand, dealListCommand, dealMoveCommand, invoiceCreateCommand, invoiceListCommand, invoiceSendCommand, } from './commands/aliases.js';
@@ -60,12 +60,14 @@ withGlobalOptions(program
60
60
  withGlobalOptions(program
61
61
  .command('login')
62
62
  .description('Log in (or create an account) with browser-based OAuth and store tokens locally')
63
- .option('--create-account', 'create a new Every account, then connect the CLI')).action(async (_options, command) => {
63
+ .option('--create-account', 'create a new Every account, then connect the CLI')
64
+ .option('--org <id|slug|name>', 'verify the workspace selected during login')).action(async (_options, command) => {
64
65
  const opts = command.optsWithGlobals();
65
66
  await loginCommand({
66
67
  json: opts.json,
67
68
  staging: opts.staging,
68
69
  createAccount: opts.createAccount,
70
+ org: opts.org,
69
71
  });
70
72
  });
71
73
  withGlobalOptions(program
@@ -85,12 +87,19 @@ withGlobalOptions(authCommand.command('status').description('Show local auth sta
85
87
  const opts = command.optsWithGlobals();
86
88
  await authStatusCommand({ json: opts.json, staging: opts.staging });
87
89
  });
88
- withGlobalOptions(program
90
+ const org = withGlobalOptions(program
89
91
  .command('org')
90
- .description('Show org claims from the current token; multi-org selection lands in a later phase')).action(async (_options, command) => {
92
+ .allowExcessArguments(false)
93
+ .description('Show or switch the workspace bound to the current token')).action(async (_options, command) => {
91
94
  const opts = command.optsWithGlobals();
92
95
  await orgCommand({ json: opts.json, staging: opts.staging });
93
96
  });
97
+ withGlobalOptions(org.command('switch')
98
+ .description('Switch workspace using the browser consent selector')
99
+ .option('--org <ref>', 'verify the selected workspace by id, slug, or name')).action(async (_options, command) => {
100
+ const opts = command.optsWithGlobals();
101
+ await orgSwitchCommand({ json: opts.json, staging: opts.staging, org: opts.org });
102
+ });
94
103
  const toolsCommand = withGlobalOptions(program.command('tools').description('Inspect the Every MCP tool registry'));
95
104
  withGlobalOptions(toolsCommand
96
105
  .command('list')
@@ -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
+ }
@@ -136,7 +136,7 @@ export async function loginFlow(opts) {
136
136
  const startedAt = Date.now();
137
137
  const state = createState();
138
138
  const pkce = createPkcePair();
139
- const loopback = await createLoopbackCallbackServer(state);
139
+ const loopback = await (opts.createCallbackServer ?? createLoopbackCallbackServer)(state);
140
140
  const timeout = new Promise((_, reject) => {
141
141
  setTimeout(() => {
142
142
  reject(new CliError('Login timed out after 300s', ExitCode.AUTH, 'auth'));
@@ -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,
@@ -1,8 +1,9 @@
1
- import { mkdir, readFile, rename, stat, writeFile, chmod } from 'node:fs/promises';
1
+ import { mkdir, readFile, rename, stat, writeFile, chmod, rm } from 'node:fs/promises';
2
2
  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;
@@ -64,7 +65,7 @@ export async function readCachedUserInfo(baseUrl, { allowStale = false, now = Da
64
65
  }
65
66
  return parsed.userinfo;
66
67
  }
67
- async function writeUserInfoCache(baseUrl, userinfo) {
68
+ export async function writeUserInfoCache(baseUrl, userinfo) {
68
69
  const filePath = userInfoCacheFilePath(baseUrl);
69
70
  await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
70
71
  const tempPath = `${filePath}.${process.pid}.tmp`;
@@ -73,6 +74,9 @@ async function writeUserInfoCache(baseUrl, userinfo) {
73
74
  await rename(tempPath, filePath);
74
75
  await chmod(filePath, 0o600);
75
76
  }
77
+ export async function invalidateUserInfoCache(baseUrl) {
78
+ await rm(userInfoCacheFilePath(baseUrl), { force: true });
79
+ }
76
80
  export async function userInfoCacheFileMode(baseUrl) {
77
81
  try {
78
82
  return (await stat(userInfoCacheFilePath(baseUrl))).mode & 0o777;
@@ -95,11 +99,25 @@ async function fetchOpenIdConfiguration(issuer) {
95
99
  export async function fetchUserInfo(opts = {}) {
96
100
  const { baseUrl } = resolveAuthTarget(opts);
97
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
+ }
98
110
  if (!opts.forceRefresh) {
99
111
  const cached = await readCachedUserInfo(baseUrl, { now: opts.now }).catch(() => undefined);
100
112
  if (cached)
101
113
  return cached;
102
114
  }
115
+ const userinfo = await requestUserInfo({ baseUrl, accessToken: token });
116
+ await writeUserInfoCache(baseUrl, userinfo);
117
+ return userinfo;
118
+ }
119
+ /** Verify a candidate credential without reading or changing stored auth/identity. */
120
+ export async function requestUserInfo({ baseUrl, accessToken }) {
103
121
  const discovery = await discoverOAuth(baseUrl);
104
122
  const openid = await fetchOpenIdConfiguration(discovery.authServer.issuer);
105
123
  let raw;
@@ -107,7 +125,7 @@ export async function fetchUserInfo(opts = {}) {
107
125
  raw = await fetchJsonWithTimeout(openid.userinfo_endpoint, {
108
126
  headers: {
109
127
  accept: 'application/json',
110
- authorization: `Bearer ${token}`,
128
+ authorization: `Bearer ${accessToken}`,
111
129
  },
112
130
  }, USERINFO_TIMEOUT_MS);
113
131
  }
@@ -120,7 +138,5 @@ export async function fetchUserInfo(opts = {}) {
120
138
  }
121
139
  throw err;
122
140
  }
123
- const userinfo = normalizeUserInfo(raw);
124
- await writeUserInfoCache(baseUrl, userinfo);
125
- return userinfo;
141
+ return normalizeUserInfo(raw);
126
142
  }
@@ -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.6.5",
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"
@@ -13,7 +13,7 @@ For headless use, accept `EVERY_TOKEN` from the environment instead of browser l
13
13
 
14
14
  ## What Every Is
15
15
 
16
- Use Every as a service-business workspace for the sales pipeline, deals, People and Companies, proposals, invoices, payments, and services. The authenticated CLI operates on one connected Every workspace at a time. If the user means a different business, tell them to switch accounts in Every.
16
+ Use Every as a service-business workspace for the sales pipeline, deals, People and Companies, proposals, invoices, payments, and services. The authenticated CLI operates on one connected Every workspace at a time. The token binds one workspace per environment; follow the workspace switching rule below when the user means a different business.
17
17
 
18
18
  ## Required Workflow
19
19
 
@@ -69,6 +69,10 @@ Use `every whoami --json` to verify the authenticated user, org, environment, ba
69
69
 
70
70
  ## Domain Rules
71
71
 
72
+ ### Verify the workspace before acting
73
+
74
+ Never assume the bound workspace. When the user names a different workspace, run `every org switch --org "<name>" --json`, then re-verify with `every whoami --json` before continuing. The browser consent page is the picker; `--org` verifies the selection after login. A token binds one workspace per environment. Use the workspace id when names are ambiguous. If `EVERY_TOKEN` is set, ask the user to unset it before switching.
75
+
72
76
  ### Deal activity auto-tracking is creation-only
73
77
 
74
78
  Creating a proposal or invoice automatically records activity on a matching deal when exactly one deal/party (Person or Company) matches. After an Every creation command, never double-log that action: