@everyai/cli 0.1.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.
@@ -0,0 +1,87 @@
1
+ import { CliError } from '../errors.js';
2
+ import { ExitCode } from '../exit-codes.js';
3
+ const DISCOVERY_TIMEOUT_MS = 10_000;
4
+ export class HttpStatusError extends CliError {
5
+ url;
6
+ status;
7
+ constructor(url, status) {
8
+ super(`Request failed for ${url}: HTTP ${status}`, ExitCode.NETWORK, 'network');
9
+ this.url = url;
10
+ this.status = status;
11
+ }
12
+ }
13
+ const discoveryCache = new Map();
14
+ function trimTrailingSlash(value) {
15
+ return value.replace(/\/+$/, '');
16
+ }
17
+ function wellKnownUrl(baseUrl, path) {
18
+ return `${trimTrailingSlash(baseUrl)}${path}`;
19
+ }
20
+ function isTimeoutError(err) {
21
+ return err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError');
22
+ }
23
+ export async function fetchJsonWithTimeout(url, init = {}, timeoutMs = DISCOVERY_TIMEOUT_MS) {
24
+ let response;
25
+ try {
26
+ response = await fetch(url, {
27
+ ...init,
28
+ signal: init.signal ?? AbortSignal.timeout(timeoutMs),
29
+ });
30
+ }
31
+ catch (err) {
32
+ if (isTimeoutError(err)) {
33
+ throw new CliError(`Timed out reaching ${url} after ${timeoutMs}ms`, ExitCode.NETWORK, 'network');
34
+ }
35
+ const detail = err instanceof Error ? err.message : String(err);
36
+ throw new CliError(`Failed to reach ${url}: ${detail}`, ExitCode.NETWORK, 'network');
37
+ }
38
+ if (!response.ok) {
39
+ throw new HttpStatusError(url, response.status);
40
+ }
41
+ try {
42
+ return (await response.json());
43
+ }
44
+ catch (err) {
45
+ const detail = err instanceof Error ? err.message : String(err);
46
+ throw new CliError(`Invalid JSON from ${url}: ${detail}`, ExitCode.NETWORK, 'network');
47
+ }
48
+ }
49
+ function validateProtectedResource(value, url) {
50
+ if (!Array.isArray(value.authorization_servers) || value.authorization_servers.length === 0) {
51
+ throw new CliError(`OAuth protected-resource metadata at ${url} did not include authorization_servers`, ExitCode.NETWORK, 'network');
52
+ }
53
+ return value;
54
+ }
55
+ function validateAuthServer(value, url) {
56
+ if (!value.issuer || !value.authorization_endpoint || !value.token_endpoint) {
57
+ throw new CliError(`OAuth authorization-server metadata at ${url} is missing required endpoints`, ExitCode.NETWORK, 'network');
58
+ }
59
+ return value;
60
+ }
61
+ async function discoverUncached(mcpBaseUrl) {
62
+ const protectedResourceUrl = wellKnownUrl(mcpBaseUrl, '/.well-known/oauth-protected-resource');
63
+ const protectedResource = validateProtectedResource(await fetchJsonWithTimeout(protectedResourceUrl), protectedResourceUrl);
64
+ const authServerBaseUrl = protectedResource.authorization_servers[0];
65
+ const authServerUrl = wellKnownUrl(authServerBaseUrl, '/.well-known/oauth-authorization-server');
66
+ const authServer = validateAuthServer(await fetchJsonWithTimeout(authServerUrl), authServerUrl);
67
+ return {
68
+ mcpBaseUrl: trimTrailingSlash(mcpBaseUrl),
69
+ protectedResource,
70
+ authServer,
71
+ };
72
+ }
73
+ export async function discoverOAuth(mcpBaseUrl) {
74
+ const cacheKey = trimTrailingSlash(mcpBaseUrl);
75
+ let cached = discoveryCache.get(cacheKey);
76
+ if (!cached) {
77
+ cached = discoverUncached(cacheKey).catch((err) => {
78
+ discoveryCache.delete(cacheKey);
79
+ throw err;
80
+ });
81
+ discoveryCache.set(cacheKey, cached);
82
+ }
83
+ return cached;
84
+ }
85
+ export function clearDiscoveryCache() {
86
+ discoveryCache.clear();
87
+ }
@@ -0,0 +1,177 @@
1
+ import http from 'node:http';
2
+ import { spawn } from 'node:child_process';
3
+ import { CliError } from '../errors.js';
4
+ import { ExitCode } from '../exit-codes.js';
5
+ import { DEFAULT_SCOPE, getOrRegisterClient } from './dcr.js';
6
+ import { discoverOAuth, fetchJsonWithTimeout, HttpStatusError, } from './discovery.js';
7
+ import { createPkcePair, createState } from './pkce.js';
8
+ import { toStoredTokenSet } from './tokens.js';
9
+ const LOGIN_TIMEOUT_MS = 300_000;
10
+ const TOKEN_TIMEOUT_MS = 10_000;
11
+ function callbackHtml() {
12
+ return '<!doctype html><meta charset="utf-8"><title>Every AI CLI</title><main style="font-family: system-ui, sans-serif; max-width: 42rem; margin: 4rem auto; line-height: 1.5;"><h1>You&apos;re logged in</h1><p>Return to your terminal.</p></main>';
13
+ }
14
+ function callbackErrorHtml(message) {
15
+ const escaped = message
16
+ .replaceAll('&', '&amp;')
17
+ .replaceAll('<', '&lt;')
18
+ .replaceAll('>', '&gt;')
19
+ .replaceAll('"', '&quot;');
20
+ return `<!doctype html><meta charset="utf-8"><title>Every AI CLI</title><main style="font-family: system-ui, sans-serif; max-width: 42rem; margin: 4rem auto; line-height: 1.5;"><h1>Login failed</h1><p>${escaped}</p></main>`;
21
+ }
22
+ function writeHtml(response, status, body) {
23
+ response.writeHead(status, { 'content-type': 'text/html; charset=utf-8' });
24
+ response.end(body);
25
+ }
26
+ async function createLoopbackCallbackServer(state) {
27
+ let settle;
28
+ let reject;
29
+ const waitForCallback = new Promise((resolve, rejectPromise) => {
30
+ settle = resolve;
31
+ reject = rejectPromise;
32
+ });
33
+ const server = http.createServer((request, response) => {
34
+ const host = request.headers.host ?? '127.0.0.1';
35
+ const url = new URL(request.url ?? '/', `http://${host}`);
36
+ if (url.pathname !== '/callback') {
37
+ writeHtml(response, 404, callbackErrorHtml('Unknown callback path.'));
38
+ return;
39
+ }
40
+ const returnedState = url.searchParams.get('state');
41
+ const code = url.searchParams.get('code');
42
+ const error = url.searchParams.get('error');
43
+ if (returnedState !== state) {
44
+ writeHtml(response, 400, callbackErrorHtml('The login state did not match.'));
45
+ reject?.(new CliError('OAuth callback state did not match', ExitCode.AUTH, 'auth'));
46
+ return;
47
+ }
48
+ if (error) {
49
+ const description = url.searchParams.get('error_description') ?? error;
50
+ writeHtml(response, 400, callbackErrorHtml(description));
51
+ reject?.(new CliError(`OAuth login failed: ${description}`, ExitCode.AUTH, 'auth'));
52
+ return;
53
+ }
54
+ if (!code) {
55
+ writeHtml(response, 400, callbackErrorHtml('The callback did not include an authorization code.'));
56
+ reject?.(new CliError('OAuth callback did not include a code', ExitCode.AUTH, 'auth'));
57
+ return;
58
+ }
59
+ writeHtml(response, 200, callbackHtml());
60
+ settle?.({ code });
61
+ });
62
+ await new Promise((resolve, rejectPromise) => {
63
+ server.once('error', rejectPromise);
64
+ server.listen(0, '127.0.0.1', () => resolve());
65
+ });
66
+ const address = server.address();
67
+ if (!address || typeof address === 'string') {
68
+ server.close();
69
+ throw new CliError('Failed to bind OAuth loopback server', ExitCode.NETWORK, 'network');
70
+ }
71
+ return {
72
+ redirectUri: `http://127.0.0.1:${address.port}/callback`,
73
+ waitForCallback,
74
+ close: () => new Promise((resolve) => {
75
+ server.close(() => resolve());
76
+ }),
77
+ };
78
+ }
79
+ function buildAuthorizationUrl(params) {
80
+ const url = new URL(params.metadata.authorization_endpoint);
81
+ url.searchParams.set('response_type', 'code');
82
+ url.searchParams.set('client_id', params.clientId);
83
+ url.searchParams.set('redirect_uri', params.redirectUri);
84
+ url.searchParams.set('scope', DEFAULT_SCOPE);
85
+ url.searchParams.set('state', params.state);
86
+ url.searchParams.set('code_challenge', params.codeChallenge);
87
+ url.searchParams.set('code_challenge_method', 'S256');
88
+ return url.toString();
89
+ }
90
+ export async function openBrowser(url) {
91
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
92
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
93
+ await new Promise((resolve) => {
94
+ const child = spawn(command, args, { detached: true, stdio: 'ignore' });
95
+ child.once('error', () => resolve());
96
+ child.once('spawn', () => {
97
+ child.unref();
98
+ resolve();
99
+ });
100
+ });
101
+ }
102
+ export async function exchangeAuthorizationCode(opts) {
103
+ const body = new URLSearchParams({
104
+ grant_type: 'authorization_code',
105
+ code: opts.code,
106
+ redirect_uri: opts.redirectUri,
107
+ client_id: opts.clientId,
108
+ code_verifier: opts.codeVerifier,
109
+ });
110
+ let response;
111
+ try {
112
+ response = await fetchJsonWithTimeout(opts.metadata.token_endpoint, {
113
+ method: 'POST',
114
+ headers: {
115
+ 'content-type': 'application/x-www-form-urlencoded',
116
+ accept: 'application/json',
117
+ },
118
+ body,
119
+ }, TOKEN_TIMEOUT_MS);
120
+ }
121
+ catch (err) {
122
+ if (err instanceof HttpStatusError) {
123
+ throw new CliError(`OAuth token exchange failed: HTTP ${err.status}`, ExitCode.AUTH, 'auth');
124
+ }
125
+ throw err;
126
+ }
127
+ return toStoredTokenSet({
128
+ issuer: opts.metadata.issuer,
129
+ client_id: opts.clientId,
130
+ response: response,
131
+ now: opts.now,
132
+ });
133
+ }
134
+ export async function loginFlow(opts) {
135
+ const timeoutMs = opts.timeoutMs ?? LOGIN_TIMEOUT_MS;
136
+ const startedAt = Date.now();
137
+ const state = createState();
138
+ const pkce = createPkcePair();
139
+ const loopback = await createLoopbackCallbackServer(state);
140
+ const timeout = new Promise((_, reject) => {
141
+ setTimeout(() => {
142
+ reject(new CliError('Login timed out after 300s', ExitCode.AUTH, 'auth'));
143
+ }, timeoutMs).unref();
144
+ });
145
+ try {
146
+ const discovery = await discoverOAuth(opts.baseUrl);
147
+ const client = await getOrRegisterClient(discovery.authServer, loopback.redirectUri);
148
+ const authorizationUrl = buildAuthorizationUrl({
149
+ metadata: discovery.authServer,
150
+ clientId: client.client_id,
151
+ redirectUri: loopback.redirectUri,
152
+ state,
153
+ codeChallenge: pkce.challenge,
154
+ });
155
+ opts.onAuthorizationUrl?.(authorizationUrl);
156
+ await (opts.openBrowser ?? openBrowser)(authorizationUrl);
157
+ const callback = await Promise.race([loopback.waitForCallback, timeout]);
158
+ const elapsed = Date.now() - startedAt;
159
+ if (elapsed > timeoutMs) {
160
+ throw new CliError('Login timed out after 300s', ExitCode.AUTH, 'auth');
161
+ }
162
+ return await Promise.race([
163
+ exchangeAuthorizationCode({
164
+ metadata: discovery.authServer,
165
+ clientId: client.client_id,
166
+ redirectUri: loopback.redirectUri,
167
+ code: callback.code,
168
+ codeVerifier: pkce.verifier,
169
+ now: opts.now,
170
+ }),
171
+ timeout,
172
+ ]);
173
+ }
174
+ finally {
175
+ await loopback.close();
176
+ }
177
+ }
@@ -0,0 +1,15 @@
1
+ export function decodeJwtClaims(token) {
2
+ const parts = token.split('.');
3
+ if (parts.length < 2 || !parts[1])
4
+ return null;
5
+ try {
6
+ const json = Buffer.from(parts[1], 'base64url').toString('utf8');
7
+ const parsed = JSON.parse(json);
8
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
9
+ return null;
10
+ return parsed;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
@@ -0,0 +1,12 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ export function createPkcePair() {
3
+ const verifier = randomBytes(32).toString('base64url');
4
+ const challenge = createPkceChallenge(verifier);
5
+ return { verifier, challenge };
6
+ }
7
+ export function createPkceChallenge(verifier) {
8
+ return createHash('sha256').update(verifier).digest('base64url');
9
+ }
10
+ export function createState() {
11
+ return randomBytes(24).toString('base64url');
12
+ }
@@ -0,0 +1,302 @@
1
+ import { mkdir, readFile, rename, stat, writeFile, chmod } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { getConfigDir, PROD_BASE_URL, resolveBaseUrl, STAGING_BASE_URL } from '../config.js';
4
+ import { CliError } from '../errors.js';
5
+ import { ExitCode } from '../exit-codes.js';
6
+ import { DEFAULT_SCOPE } from './dcr.js';
7
+ import { discoverOAuth, fetchJsonWithTimeout, HttpStatusError } from './discovery.js';
8
+ import { decodeJwtClaims } from './jwt.js';
9
+ const TOKEN_TIMEOUT_MS = 10_000;
10
+ const KEYRING_SERVICE = 'everyai-cli';
11
+ function tokenPath() {
12
+ return path.join(getConfigDir(), 'tokens.json');
13
+ }
14
+ function keyringIndexPath() {
15
+ return path.join(getConfigDir(), 'keyring-index.json');
16
+ }
17
+ function trimTrailingSlash(value) {
18
+ return value.replace(/\/+$/, '');
19
+ }
20
+ export function environmentKeyForBaseUrl(baseUrl) {
21
+ const normalized = trimTrailingSlash(baseUrl);
22
+ if (normalized === trimTrailingSlash(PROD_BASE_URL))
23
+ return 'prod';
24
+ if (normalized === trimTrailingSlash(STAGING_BASE_URL))
25
+ return 'staging';
26
+ return `custom:${normalized}`;
27
+ }
28
+ export function resolveAuthTarget(opts = {}) {
29
+ const baseUrl = trimTrailingSlash(opts.baseUrl ?? resolveBaseUrl({ staging: opts.staging }));
30
+ return { baseUrl, environmentKey: environmentKeyForBaseUrl(baseUrl) };
31
+ }
32
+ async function readTokenFile(filePath) {
33
+ try {
34
+ const text = await readFile(filePath, 'utf8');
35
+ const parsed = JSON.parse(text);
36
+ return {
37
+ tokens: parsed && typeof parsed.tokens === 'object' && parsed.tokens ? parsed.tokens : {},
38
+ };
39
+ }
40
+ catch (err) {
41
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
42
+ return { tokens: {} };
43
+ }
44
+ throw err;
45
+ }
46
+ }
47
+ async function writePrivateJson(filePath, value) {
48
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
49
+ const tempPath = `${filePath}.${process.pid}.tmp`;
50
+ await writeFile(tempPath, JSON.stringify(value, null, 2), { mode: 0o600 });
51
+ await chmod(tempPath, 0o600);
52
+ await rename(tempPath, filePath);
53
+ await chmod(filePath, 0o600);
54
+ }
55
+ export class FileStore {
56
+ filePath;
57
+ backend = 'file';
58
+ constructor(filePath = tokenPath()) {
59
+ this.filePath = filePath;
60
+ }
61
+ async get(environmentKey) {
62
+ const file = await readTokenFile(this.filePath);
63
+ return file.tokens[environmentKey];
64
+ }
65
+ async set(environmentKey, tokens) {
66
+ const file = await readTokenFile(this.filePath);
67
+ file.tokens[environmentKey] = tokens;
68
+ await writePrivateJson(this.filePath, file);
69
+ }
70
+ async delete(environmentKey) {
71
+ const file = await readTokenFile(this.filePath);
72
+ if (!(environmentKey in file.tokens))
73
+ return;
74
+ delete file.tokens[environmentKey];
75
+ await writePrivateJson(this.filePath, file);
76
+ }
77
+ async fileMode() {
78
+ try {
79
+ return (await stat(this.filePath)).mode & 0o777;
80
+ }
81
+ catch (err) {
82
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
83
+ return undefined;
84
+ }
85
+ throw err;
86
+ }
87
+ }
88
+ }
89
+ function keyringAccountForIssuer(issuer) {
90
+ return new URL(issuer).host;
91
+ }
92
+ async function readKeyringIndex(filePath) {
93
+ try {
94
+ const text = await readFile(filePath, 'utf8');
95
+ const parsed = JSON.parse(text);
96
+ return {
97
+ accounts: parsed && typeof parsed.accounts === 'object' && parsed.accounts ? parsed.accounts : {},
98
+ };
99
+ }
100
+ catch (err) {
101
+ if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') {
102
+ return { accounts: {} };
103
+ }
104
+ throw err;
105
+ }
106
+ }
107
+ async function loadKeyringModule() {
108
+ const dynamicImport = new Function('specifier', 'return import(specifier)');
109
+ return dynamicImport('@napi-rs/keyring');
110
+ }
111
+ export class KeyringStore {
112
+ indexPath;
113
+ backend = 'keyring';
114
+ modulePromise;
115
+ constructor(indexPath = keyringIndexPath()) {
116
+ this.indexPath = indexPath;
117
+ }
118
+ static async createAvailable() {
119
+ const store = new KeyringStore();
120
+ try {
121
+ await store.smokeTest();
122
+ return store;
123
+ }
124
+ catch {
125
+ return undefined;
126
+ }
127
+ }
128
+ async keyring() {
129
+ this.modulePromise ??= loadKeyringModule();
130
+ return this.modulePromise;
131
+ }
132
+ async entry(account) {
133
+ const keyring = await this.keyring();
134
+ return new keyring.Entry(KEYRING_SERVICE, account);
135
+ }
136
+ async smokeTest() {
137
+ const account = `_healthcheck:${process.pid}:${Date.now()}`;
138
+ const entry = await this.entry(account);
139
+ await entry.setPassword('ok');
140
+ const password = await entry.getPassword();
141
+ await entry.deletePassword();
142
+ if (password !== 'ok')
143
+ throw new Error('keyring healthcheck failed');
144
+ }
145
+ async get(environmentKey) {
146
+ const index = await readKeyringIndex(this.indexPath);
147
+ const account = index.accounts[environmentKey];
148
+ if (!account)
149
+ return undefined;
150
+ const password = await (await this.entry(account)).getPassword();
151
+ if (!password)
152
+ return undefined;
153
+ return JSON.parse(password);
154
+ }
155
+ async set(environmentKey, tokens) {
156
+ const account = keyringAccountForIssuer(tokens.issuer);
157
+ await (await this.entry(account)).setPassword(JSON.stringify(tokens));
158
+ const index = await readKeyringIndex(this.indexPath);
159
+ index.accounts[environmentKey] = account;
160
+ await writePrivateJson(this.indexPath, index);
161
+ }
162
+ async delete(environmentKey) {
163
+ const index = await readKeyringIndex(this.indexPath);
164
+ const account = index.accounts[environmentKey];
165
+ if (account) {
166
+ try {
167
+ await (await this.entry(account)).deletePassword();
168
+ }
169
+ catch {
170
+ // Logout is idempotent; a missing native keychain item is already logged out.
171
+ }
172
+ }
173
+ if (environmentKey in index.accounts) {
174
+ delete index.accounts[environmentKey];
175
+ await writePrivateJson(this.indexPath, index);
176
+ }
177
+ }
178
+ }
179
+ export async function createTokenStore() {
180
+ if (process.env.EVERYAI_FORCE_FILE_STORE === '1')
181
+ return new FileStore();
182
+ const keyring = await KeyringStore.createAvailable();
183
+ return keyring ?? new FileStore();
184
+ }
185
+ export async function deleteTokenFromAllStores(environmentKey) {
186
+ const fileStore = new FileStore();
187
+ await fileStore.delete(environmentKey);
188
+ const keyring = await KeyringStore.createAvailable();
189
+ if (keyring)
190
+ await keyring.delete(environmentKey);
191
+ }
192
+ function nowSeconds(now) {
193
+ return Math.floor(now() / 1000);
194
+ }
195
+ function expiresAtFromResponse(response, now) {
196
+ const expiresIn = typeof response.expires_in === 'number' ? response.expires_in : 0;
197
+ return nowSeconds(now) + expiresIn;
198
+ }
199
+ function assertAccessToken(response) {
200
+ if (!response.access_token) {
201
+ throw new CliError('OAuth token response did not include access_token', ExitCode.AUTH, 'auth');
202
+ }
203
+ }
204
+ async function refreshToken(baseUrl, environmentKey, store, existing, now) {
205
+ const discovery = await discoverOAuth(baseUrl);
206
+ const body = new URLSearchParams({
207
+ grant_type: 'refresh_token',
208
+ refresh_token: existing.refresh_token ?? '',
209
+ client_id: existing.client_id,
210
+ });
211
+ let response;
212
+ try {
213
+ response = await fetchJsonWithTimeout(discovery.authServer.token_endpoint, {
214
+ method: 'POST',
215
+ headers: {
216
+ 'content-type': 'application/x-www-form-urlencoded',
217
+ accept: 'application/json',
218
+ },
219
+ body,
220
+ }, TOKEN_TIMEOUT_MS);
221
+ }
222
+ catch (err) {
223
+ if (err instanceof HttpStatusError) {
224
+ throw new CliError('Session expired. Run \'every login\'.', ExitCode.AUTH, 'auth');
225
+ }
226
+ if (err instanceof CliError && err.code === 'network')
227
+ throw err;
228
+ throw new CliError('Session expired. Run \'every login\'.', ExitCode.AUTH, 'auth');
229
+ }
230
+ assertAccessToken(response);
231
+ const refreshed = {
232
+ issuer: existing.issuer,
233
+ client_id: existing.client_id,
234
+ access_token: response.access_token,
235
+ refresh_token: response.refresh_token ?? existing.refresh_token,
236
+ expires_at: expiresAtFromResponse(response, now),
237
+ scope: response.scope ?? existing.scope,
238
+ };
239
+ await store.set(environmentKey, refreshed);
240
+ return refreshed.access_token;
241
+ }
242
+ export async function getToken(opts = {}) {
243
+ if (process.env.EVERY_TOKEN)
244
+ return process.env.EVERY_TOKEN;
245
+ const { baseUrl, environmentKey } = resolveAuthTarget(opts);
246
+ const store = opts.store ?? (await createTokenStore());
247
+ const tokenSet = await store.get(environmentKey);
248
+ if (!tokenSet) {
249
+ throw new CliError('Not logged in. Run \'every login\'.', ExitCode.AUTH, 'auth');
250
+ }
251
+ const now = opts.now ?? Date.now;
252
+ if (tokenSet.expires_at - 60 > nowSeconds(now))
253
+ return tokenSet.access_token;
254
+ if (tokenSet.refresh_token) {
255
+ return refreshToken(baseUrl, environmentKey, store, tokenSet, now);
256
+ }
257
+ throw new CliError('Not logged in. Run \'every login\'.', ExitCode.AUTH, 'auth');
258
+ }
259
+ export function toStoredTokenSet(params) {
260
+ assertAccessToken(params.response);
261
+ return {
262
+ issuer: params.issuer,
263
+ client_id: params.client_id,
264
+ access_token: params.response.access_token,
265
+ refresh_token: params.response.refresh_token,
266
+ expires_at: expiresAtFromResponse(params.response, params.now ?? Date.now),
267
+ scope: params.response.scope ?? DEFAULT_SCOPE,
268
+ };
269
+ }
270
+ export async function getAuthStatus(opts = {}) {
271
+ const { baseUrl, environmentKey } = resolveAuthTarget(opts);
272
+ const store = opts.store ?? (await createTokenStore());
273
+ const now = opts.now ?? Date.now;
274
+ const override = process.env.EVERY_TOKEN;
275
+ const stored = await store.get(environmentKey);
276
+ const claims = override ? decodeJwtClaims(override) : null;
277
+ const expiresAt = override ? claims?.exp : stored?.expires_at;
278
+ const expiresIn = typeof expiresAt === 'number' ? expiresAt - nowSeconds(now) : null;
279
+ return {
280
+ logged_in: Boolean(override || stored),
281
+ environment: environmentKey,
282
+ base_url: baseUrl,
283
+ storage_backend: store.backend,
284
+ every_token: Boolean(override),
285
+ issuer: stored?.issuer ?? null,
286
+ expires_at: typeof expiresAt === 'number' ? expiresAt : null,
287
+ expires_in_seconds: expiresIn,
288
+ expires: expiresIn === null ? null : formatRelativeExpiry(expiresIn),
289
+ refresh_token: Boolean(stored?.refresh_token),
290
+ };
291
+ }
292
+ export function formatRelativeExpiry(seconds) {
293
+ const abs = Math.abs(seconds);
294
+ const unit = abs >= 86_400
295
+ ? { name: 'd', value: Math.round(abs / 86_400) }
296
+ : abs >= 3_600
297
+ ? { name: 'h', value: Math.round(abs / 3_600) }
298
+ : abs >= 60
299
+ ? { name: 'm', value: Math.round(abs / 60) }
300
+ : { name: 's', value: abs };
301
+ return seconds >= 0 ? `in ${unit.value}${unit.name}` : `${unit.value}${unit.name} ago`;
302
+ }
@@ -0,0 +1,28 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ /**
4
+ * On-disk config location for the `every` CLI (auth tokens land here in a
5
+ * later phase). Kept under the XDG-style `~/.config/everyai`.
6
+ */
7
+ export const CONFIG_DIR = path.join(os.homedir(), '.config', 'everyai');
8
+ /** Resolve the config directory dynamically so tests can isolate state. */
9
+ export function getConfigDir() {
10
+ return process.env.EVERY_CONFIG_DIR ?? CONFIG_DIR;
11
+ }
12
+ /** Deployed MCP base URLs. */
13
+ export const PROD_BASE_URL = 'https://admin-mcp.every.ai';
14
+ export const STAGING_BASE_URL = 'https://admin-mcp-staging.up.railway.app';
15
+ /**
16
+ * Resolve the MCP base URL to target.
17
+ *
18
+ * Precedence:
19
+ * 1. `EVERY_MCP_URL` env override (any value, wins over `staging`)
20
+ * 2. `{ staging: true }` -> staging deployment
21
+ * 3. default -> production deployment
22
+ */
23
+ export function resolveBaseUrl({ staging } = {}) {
24
+ const override = process.env.EVERY_MCP_URL;
25
+ if (override)
26
+ return override;
27
+ return staging ? STAGING_BASE_URL : PROD_BASE_URL;
28
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Typed CLI error carrying a process exit code and a stable machine `code`.
3
+ *
4
+ * Throw a `CliError` from any command; the top-level handler in `index.ts`
5
+ * renders it through the output envelope and exits with `exitCode`.
6
+ */
7
+ export class CliError extends Error {
8
+ exitCode;
9
+ code;
10
+ constructor(message, exitCode = 1, code = 'generic') {
11
+ super(message);
12
+ this.exitCode = exitCode;
13
+ this.code = code;
14
+ this.name = 'CliError';
15
+ }
16
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Stable process exit codes for the `every` CLI.
3
+ *
4
+ * These are part of the CLI CONTRACT — scripts, agents, and CI depend on them.
5
+ * Do not renumber existing entries; only append new ones.
6
+ */
7
+ export const ExitCode = {
8
+ OK: 0,
9
+ GENERIC: 1,
10
+ USAGE: 2,
11
+ AUTH: 3,
12
+ PERMISSION: 4,
13
+ RATE_LIMIT: 5,
14
+ NOT_FOUND: 6,
15
+ NETWORK: 7,
16
+ };