eversince 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,100 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { mkdir, readFile, writeFile, rm, chmod } from 'node:fs/promises';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ const run = promisify(execFile);
7
+ const SERVICE = 'eversince-cli';
8
+ export function stateDir() {
9
+ return join(homedir(), '.eversince');
10
+ }
11
+ function credentialsPath() {
12
+ return join(stateDir(), 'credentials.json');
13
+ }
14
+ const keychainUsable = process.platform === 'darwin';
15
+ async function keychainGet(host) {
16
+ if (!keychainUsable)
17
+ return null;
18
+ try {
19
+ const { stdout } = await run('security', ['find-generic-password', '-s', SERVICE, '-a', host, '-w']);
20
+ return JSON.parse(stdout.trim());
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ async function keychainSet(host, creds) {
27
+ if (!keychainUsable)
28
+ return false;
29
+ try {
30
+ await run('security', [
31
+ 'add-generic-password', '-U',
32
+ '-s', SERVICE, '-a', host,
33
+ '-w', JSON.stringify(creds),
34
+ ]);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ const stored = await keychainGet(host);
40
+ return stored?.token === creds.token;
41
+ }
42
+ async function keychainDelete(host) {
43
+ if (!keychainUsable)
44
+ return;
45
+ try {
46
+ await run('security', ['delete-generic-password', '-s', SERVICE, '-a', host]);
47
+ }
48
+ catch {
49
+ }
50
+ }
51
+ async function fileRead() {
52
+ try {
53
+ const raw = await readFile(credentialsPath(), 'utf8');
54
+ const parsed = JSON.parse(raw);
55
+ return parsed && typeof parsed === 'object' ? parsed : {};
56
+ }
57
+ catch {
58
+ return {};
59
+ }
60
+ }
61
+ async function fileWrite(next) {
62
+ await mkdir(stateDir(), { recursive: true, mode: 0o700 });
63
+ await writeFile(credentialsPath(), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
64
+ await chmod(credentialsPath(), 0o600);
65
+ }
66
+ export async function readCredentials(host) {
67
+ const fromKeychain = await keychainGet(host);
68
+ if (fromKeychain)
69
+ return fromKeychain;
70
+ const all = await fileRead();
71
+ return all[host] ?? null;
72
+ }
73
+ export async function writeCredentials(creds) {
74
+ if (await keychainSet(creds.host, creds)) {
75
+ const all = await fileRead();
76
+ if (all[creds.host]) {
77
+ delete all[creds.host];
78
+ await fileWrite(all);
79
+ }
80
+ return 'keychain';
81
+ }
82
+ const all = await fileRead();
83
+ all[creds.host] = creds;
84
+ await fileWrite(all);
85
+ return 'file';
86
+ }
87
+ export async function deleteCredentials(host) {
88
+ await keychainDelete(host);
89
+ const all = await fileRead();
90
+ if (all[host]) {
91
+ delete all[host];
92
+ if (Object.keys(all).length === 0)
93
+ await rm(credentialsPath(), { force: true });
94
+ else
95
+ await fileWrite(all);
96
+ }
97
+ }
98
+ export function storageKind() {
99
+ return keychainUsable ? 'keychain' : 'file';
100
+ }
package/dist/bridge.js ADDED
@@ -0,0 +1,198 @@
1
+ import { DoorBlocked, cacheFile as cacheFileFor, isBlocked, isRefused, probe, reachApp, readJson, readState, sandboxedWithoutNetwork, stateFile as defaultStateFile, } from './door.js';
2
+ function write(message) {
3
+ process.stdout.write(`${typeof message === 'string' ? message : JSON.stringify(message)}\n`);
4
+ }
5
+ function idOf(message) {
6
+ const id = message?.id;
7
+ return typeof id === 'string' || typeof id === 'number' ? id : null;
8
+ }
9
+ function rpcError(id, message, code = -32000) {
10
+ return { jsonrpc: '2.0', id, error: { code, message } };
11
+ }
12
+ export function runBridge(options) {
13
+ const file = options.stateFile ?? defaultStateFile();
14
+ const cacheFile = cacheFileFor(file);
15
+ const reconnect = options.reconnect ?? `Run \`eversince init --agent ${options.agent}\` to connect it again.`;
16
+ function connectionFor(state) {
17
+ const found = (state?.connections ?? []).find((c) => c && (options.connectionId ? c.id === options.connectionId : c.agent === options.agent));
18
+ return found && typeof found.token === 'string' ? { token: found.token } : null;
19
+ }
20
+ if (!readState(file)) {
21
+ process.stderr.write('eversince: the Eversince app is not set up on this computer. Install it, open it and sign in.\n');
22
+ process.exit(1);
23
+ }
24
+ let listFromCache = null;
25
+ let opening = null;
26
+ function open() {
27
+ if (!opening) {
28
+ opening = reachApp(file, () => process.stderr.write('eversince: opening the Eversince app\n')).finally(() => { opening = null; });
29
+ }
30
+ return opening;
31
+ }
32
+ class Unreachable extends Error {
33
+ }
34
+ class Gone extends Error {
35
+ }
36
+ async function post(body, mayOpen) {
37
+ let state = readState(file);
38
+ const seen = state ? await probe(state) : 'closed';
39
+ if (seen === 'blocked')
40
+ throw new DoorBlocked();
41
+ if (seen !== 'ours') {
42
+ if (!mayOpen)
43
+ throw new Unreachable();
44
+ state = await open();
45
+ if (!state)
46
+ throw new Error('The Eversince app did not open. Open it and try again.');
47
+ }
48
+ const connection = connectionFor(state);
49
+ if (!state || !connection)
50
+ throw new Gone();
51
+ return fetch(`http://127.0.0.1:${state.port}/mcp`, {
52
+ method: 'POST',
53
+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${connection.token}` },
54
+ body,
55
+ });
56
+ }
57
+ function fromCache(message, id) {
58
+ if (!message || typeof message.method !== 'string')
59
+ return null;
60
+ if (id === null)
61
+ return {};
62
+ if (message.method === 'ping')
63
+ return { reply: { jsonrpc: '2.0', id, result: {} } };
64
+ const cache = readJson(cacheFile);
65
+ if (!cache)
66
+ return null;
67
+ if (message.method === 'initialize') {
68
+ const version = typeof message.params?.protocolVersion === 'string' ? message.params.protocolVersion : '';
69
+ const result = cache.initialize?.[version] ?? Object.values(cache.initialize ?? {})[0];
70
+ if (!result || typeof result !== 'object')
71
+ return null;
72
+ const capabilities = (result.capabilities ?? {});
73
+ const tools = { ...(capabilities.tools ?? {}), listChanged: true };
74
+ return { reply: { jsonrpc: '2.0', id, result: { ...result, capabilities: { ...capabilities, tools } } } };
75
+ }
76
+ if (message.method === 'tools/list' && !message.params?.cursor && cache.tools) {
77
+ listFromCache = JSON.stringify(cache.tools);
78
+ return { reply: { jsonrpc: '2.0', id, result: cache.tools } };
79
+ }
80
+ return null;
81
+ }
82
+ async function checkList() {
83
+ if (!listFromCache)
84
+ return;
85
+ const given = listFromCache;
86
+ listFromCache = null;
87
+ try {
88
+ const res = await post(JSON.stringify({ jsonrpc: '2.0', id: 'eversince-list-check', method: 'tools/list' }), false);
89
+ const answer = (await res.json());
90
+ if (answer.result && JSON.stringify(answer.result) !== given)
91
+ write({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' });
92
+ }
93
+ catch {
94
+ }
95
+ }
96
+ async function answerFor(id, res) {
97
+ const text = await res.text();
98
+ let body = null;
99
+ try {
100
+ body = text ? JSON.parse(text) : null;
101
+ }
102
+ catch {
103
+ }
104
+ const rpc = body;
105
+ if (res.status === 401)
106
+ return rpcError(id, `Eversince no longer has this connection. ${reconnect}`);
107
+ if (rpc && typeof rpc === 'object' && !Array.isArray(rpc) && rpc.jsonrpc === '2.0' && ('result' in rpc || 'error' in rpc)) {
108
+ return rpc.id === id ? rpc : { ...rpc, id };
109
+ }
110
+ const envelope = body;
111
+ const said = typeof envelope?.error?.message === 'string' ? envelope.error.message : null;
112
+ if (res.status === 503 || res.status === 504)
113
+ return rpcError(id, said ?? 'Eversince is busy. Try again in a moment.');
114
+ return rpcError(id, said ?? `Eversince could not answer (${res.status}).`);
115
+ }
116
+ async function relay(line) {
117
+ let message = null;
118
+ try {
119
+ const parsed = JSON.parse(line);
120
+ if (Array.isArray(parsed)) {
121
+ try {
122
+ const text = await (await post(line, true)).text();
123
+ if (text.trim().startsWith('['))
124
+ write(text.replace(/\r?\n/g, ' '));
125
+ }
126
+ catch {
127
+ }
128
+ return;
129
+ }
130
+ if (parsed && typeof parsed === 'object')
131
+ message = parsed;
132
+ }
133
+ catch {
134
+ return;
135
+ }
136
+ const id = idOf(message);
137
+ try {
138
+ let res;
139
+ try {
140
+ res = await post(line, false);
141
+ }
142
+ catch (error) {
143
+ if (!(error instanceof Unreachable) && !isRefused(error))
144
+ throw error;
145
+ const cached = fromCache(message, id);
146
+ if (cached) {
147
+ if (cached.reply)
148
+ write(cached.reply);
149
+ return;
150
+ }
151
+ res = await post(line, true);
152
+ }
153
+ if (id !== null)
154
+ write(await answerFor(id, res));
155
+ await checkList();
156
+ }
157
+ catch (error) {
158
+ if (id === null)
159
+ return;
160
+ if (error instanceof Gone)
161
+ write(rpcError(id, `This client is not connected to Eversince. ${reconnect}`));
162
+ else if (error instanceof DoorBlocked || isBlocked(error))
163
+ write(rpcError(id, new DoorBlocked().message));
164
+ else
165
+ write(rpcError(id, `Eversince is not reachable: ${error instanceof Error ? error.message : String(error)}`));
166
+ }
167
+ }
168
+ if (sandboxedWithoutNetwork())
169
+ process.stderr.write(`eversince: ${new DoorBlocked().message}\n`);
170
+ let buffer = '';
171
+ let inFlight = 0;
172
+ let closed = false;
173
+ const track = (work) => {
174
+ inFlight += 1;
175
+ void work.finally(() => {
176
+ inFlight -= 1;
177
+ if (closed && inFlight === 0)
178
+ process.exit(0);
179
+ });
180
+ };
181
+ process.stdin.setEncoding('utf8');
182
+ process.stdin.on('data', (chunk) => {
183
+ buffer += chunk;
184
+ let at;
185
+ while ((at = buffer.indexOf('\n')) >= 0) {
186
+ const line = buffer.slice(0, at).trim();
187
+ buffer = buffer.slice(at + 1);
188
+ if (line)
189
+ track(relay(line));
190
+ }
191
+ });
192
+ process.stdin.on('end', () => {
193
+ closed = true;
194
+ if (inFlight === 0)
195
+ process.exit(0);
196
+ });
197
+ process.stdin.resume();
198
+ }
package/dist/client.js ADDED
@@ -0,0 +1,224 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { DEFAULT_BASE_URL, normalizeBaseUrl, readSettings, resolveBaseUrl, resolveWorkspace } from './config.js';
3
+ import { localDoor } from './local.js';
4
+ import { note } from './output.js';
5
+ import { readCredentials, writeCredentials } from './auth/store.js';
6
+ import { refreshTokens } from './auth/oauth.js';
7
+ import { hostOf } from './config.js';
8
+ import { USER_AGENT } from './version.js';
9
+ export class ApiError extends Error {
10
+ status;
11
+ body;
12
+ requestId;
13
+ constructor(status, body, requestId) {
14
+ super(body.message);
15
+ this.name = 'ApiError';
16
+ this.status = status;
17
+ this.body = body;
18
+ this.requestId = requestId;
19
+ }
20
+ }
21
+ export class NotLoggedIn extends Error {
22
+ constructor(host) {
23
+ super(`Not signed in to ${host}. Run \`eversince login\`.`);
24
+ this.name = 'NotLoggedIn';
25
+ }
26
+ }
27
+ const RETRYABLE_STATUS = new Set([429, 502, 503, 504]);
28
+ const MAX_ATTEMPTS = 4;
29
+ function sleep(ms) {
30
+ return new Promise((r) => setTimeout(r, ms));
31
+ }
32
+ function backoffMs(attempt) {
33
+ return Math.round(Math.random() * Math.min(8000, 500 * 2 ** attempt));
34
+ }
35
+ export class Client {
36
+ baseUrl;
37
+ workspace;
38
+ credentials;
39
+ debug;
40
+ defaultTimeoutMs;
41
+ local;
42
+ constructor(baseUrl, workspace, credentials, opts, local = null) {
43
+ this.baseUrl = baseUrl;
44
+ this.workspace = workspace;
45
+ this.credentials = credentials;
46
+ this.debug = opts.debug === true || process.env.ES_DEBUG === '1';
47
+ this.defaultTimeoutMs = (opts.timeout ?? 600) * 1000;
48
+ this.local = local;
49
+ }
50
+ static async create(opts = {}) {
51
+ if (await mayUseDesktop(opts)) {
52
+ const door = await localDoor(() => note('Opening the Eversince app on this computer.'));
53
+ if (door) {
54
+ const credentials = { kind: 'api_key', token: door.token, host: hostOf(door.baseUrl) };
55
+ return new Client(door.baseUrl, undefined, credentials, opts, door);
56
+ }
57
+ }
58
+ const baseUrl = await resolveBaseUrl(opts.baseUrl);
59
+ const workspace = await resolveWorkspace(baseUrl, opts.workspace);
60
+ const credentials = opts.credentials ?? (await loadCredentials(baseUrl));
61
+ if (!credentials)
62
+ throw new NotLoggedIn(hostOf(baseUrl));
63
+ return new Client(baseUrl, workspace, credentials, opts);
64
+ }
65
+ get authKind() {
66
+ return this.credentials.kind;
67
+ }
68
+ async get(path, query) {
69
+ return this.request('GET', path, { query });
70
+ }
71
+ async post(path, body, options = {}) {
72
+ return this.request('POST', path, { ...options, body });
73
+ }
74
+ async tool(name, input = {}, options = {}) {
75
+ return this.post(`/api/v1/tools/${encodeURIComponent(name)}`, input, options);
76
+ }
77
+ async headers(method, options) {
78
+ await this.ensureFreshToken();
79
+ const headers = {
80
+ authorization: `Bearer ${this.credentials.token}`,
81
+ accept: 'application/json',
82
+ 'user-agent': USER_AGENT,
83
+ };
84
+ if (options.body !== undefined)
85
+ headers['content-type'] = 'application/json';
86
+ if (this.workspace && this.credentials.kind === 'oauth')
87
+ headers['x-workspace-id'] = this.workspace;
88
+ if (method !== 'GET')
89
+ headers['idempotency-key'] = options.idempotencyKey ?? randomUUID();
90
+ return headers;
91
+ }
92
+ async ensureFreshToken() {
93
+ const { kind, expiresAt, refreshToken, clientId } = this.credentials;
94
+ if (kind !== 'oauth' || !expiresAt || Date.now() < expiresAt)
95
+ return;
96
+ if (!refreshToken || !clientId) {
97
+ throw new ApiError(401, {
98
+ code: 'unauthorized',
99
+ message: 'Session expired and cannot be renewed. Run `eversince login`.',
100
+ });
101
+ }
102
+ const next = await refreshTokens(this.baseUrl, clientId, refreshToken);
103
+ this.credentials = {
104
+ ...this.credentials,
105
+ token: next.accessToken,
106
+ refreshToken: next.refreshToken ?? refreshToken,
107
+ expiresAt: next.expiresAt,
108
+ };
109
+ await writeCredentials(this.credentials);
110
+ }
111
+ async request(method, path, options) {
112
+ const url = new URL(path, this.baseUrl);
113
+ for (const [key, value] of Object.entries(options.query ?? {})) {
114
+ if (value !== undefined)
115
+ url.searchParams.set(key, value);
116
+ }
117
+ const idempotencyKey = options.idempotencyKey ?? (method !== 'GET' ? randomUUID() : undefined);
118
+ let lastError = null;
119
+ let refreshedOnce = false;
120
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
121
+ if (this.local)
122
+ url.host = new URL(await this.local.verify()).host;
123
+ const controller = new AbortController();
124
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? this.defaultTimeoutMs);
125
+ try {
126
+ const headers = await this.headers(method, { ...options, idempotencyKey });
127
+ if (this.debug) {
128
+ process.stderr.write(`→ ${method} ${url.pathname}${url.search}\n`);
129
+ }
130
+ const res = await fetch(url, {
131
+ method,
132
+ headers,
133
+ signal: controller.signal,
134
+ ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),
135
+ });
136
+ const requestId = res.headers.get('x-request-id') ?? undefined;
137
+ const text = await res.text();
138
+ if (this.debug) {
139
+ process.stderr.write(`← ${res.status} ${text.slice(0, 400)}\n`);
140
+ }
141
+ let payload = null;
142
+ if (text) {
143
+ try {
144
+ payload = JSON.parse(text);
145
+ }
146
+ catch {
147
+ throw new ApiError(res.status, {
148
+ code: 'bad_response',
149
+ message: `Expected JSON from ${url.pathname}, got: ${text.slice(0, 120)}`,
150
+ }, requestId);
151
+ }
152
+ }
153
+ if (res.status === 401 && this.local && !refreshedOnce) {
154
+ refreshedOnce = true;
155
+ this.credentials = { ...this.credentials, token: await this.local.reconnect() };
156
+ continue;
157
+ }
158
+ if (res.status === 401 && this.credentials.kind === 'oauth' && !refreshedOnce) {
159
+ refreshedOnce = true;
160
+ this.credentials = { ...this.credentials, expiresAt: 0 };
161
+ continue;
162
+ }
163
+ if (!res.ok || payload?.ok === false) {
164
+ const body = payload?.error ?? {
165
+ code: 'http_error',
166
+ message: `Request failed (${res.status})`,
167
+ retryable: RETRYABLE_STATUS.has(res.status),
168
+ };
169
+ const error = new ApiError(res.status, body, requestId);
170
+ const canRetry = RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS - 1;
171
+ if (canRetry) {
172
+ const retryAfter = Number(res.headers.get('retry-after'));
173
+ await sleep(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : backoffMs(attempt));
174
+ lastError = error;
175
+ continue;
176
+ }
177
+ throw error;
178
+ }
179
+ const envelope = payload;
180
+ return envelope && typeof envelope === 'object' && 'data' in envelope ? envelope.data : payload;
181
+ }
182
+ catch (error) {
183
+ if (error instanceof ApiError) {
184
+ if (attempt === MAX_ATTEMPTS - 1 || !RETRYABLE_STATUS.has(error.status))
185
+ throw error;
186
+ lastError = error;
187
+ continue;
188
+ }
189
+ const aborted = error instanceof Error && error.name === 'AbortError';
190
+ const wrapped = new ApiError(0, {
191
+ code: aborted ? 'timeout' : 'network_error',
192
+ message: aborted
193
+ ? `Timed out after ${Math.round((options.timeoutMs ?? this.defaultTimeoutMs) / 1000)}s calling ${url.pathname}`
194
+ : `Could not reach ${url.host}: ${error instanceof Error ? error.message : String(error)}`,
195
+ retryable: true,
196
+ });
197
+ if (attempt === MAX_ATTEMPTS - 1)
198
+ throw wrapped;
199
+ lastError = wrapped;
200
+ await sleep(backoffMs(attempt));
201
+ }
202
+ finally {
203
+ clearTimeout(timer);
204
+ }
205
+ }
206
+ throw lastError ?? new ApiError(0, { code: 'unknown', message: 'Request failed' });
207
+ }
208
+ }
209
+ async function mayUseDesktop(opts) {
210
+ if (opts.cloud || opts.baseUrl || opts.credentials || opts.workspace)
211
+ return false;
212
+ if (process.env.ES_BASE_URL?.trim() || process.env.ES_API_KEY?.trim())
213
+ return false;
214
+ const settings = await readSettings();
215
+ if (settings.baseUrl && normalizeBaseUrl(settings.baseUrl) !== DEFAULT_BASE_URL)
216
+ return false;
217
+ return !(await resolveWorkspace(DEFAULT_BASE_URL));
218
+ }
219
+ export async function loadCredentials(baseUrl) {
220
+ const envKey = process.env.ES_API_KEY?.trim();
221
+ if (envKey)
222
+ return { kind: 'api_key', token: envKey, host: hostOf(baseUrl) };
223
+ return readCredentials(hostOf(baseUrl));
224
+ }
@@ -0,0 +1,139 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import { browserLogin } from '../auth/oauth.js';
3
+ import { readCredentials, writeCredentials, deleteCredentials, storageKind } from '../auth/store.js';
4
+ import { resolveBaseUrl, resolveWorkspace, writeSettings, hostOf } from '../config.js';
5
+ import { Client, ApiError, loadCredentials } from '../client.js';
6
+ import { line, note, printResult } from '../output.js';
7
+ import { desktopInstalled } from '../local.js';
8
+ const KEY_PREFIX = 'es_live_';
9
+ async function readKeyFromInput(fromStdin) {
10
+ if (fromStdin) {
11
+ const chunks = [];
12
+ for await (const chunk of process.stdin)
13
+ chunks.push(Buffer.from(chunk));
14
+ return Buffer.concat(chunks).toString('utf8').trim();
15
+ }
16
+ if (!process.stdin.isTTY) {
17
+ throw new Error('No terminal to ask on. Pass the key with `--key es_live_…`, pipe it with `--key -`, or set ES_API_KEY.');
18
+ }
19
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
20
+ try {
21
+ return (await rl.question('API key (es_live_…): ')).trim();
22
+ }
23
+ finally {
24
+ rl.close();
25
+ }
26
+ }
27
+ async function verify(baseUrl, credentials) {
28
+ const client = await Client.create({ baseUrl, credentials });
29
+ await client.get('/api/v1/tools', { schemas: 'false' });
30
+ }
31
+ export async function login(argv, connection, mode) {
32
+ const baseUrl = await resolveBaseUrl(connection.baseUrl);
33
+ const host = hostOf(baseUrl);
34
+ const previous = await readCredentials(host);
35
+ const useKey = Boolean(argv.key) || argv.noBrowser === true;
36
+ let stored;
37
+ if (useKey) {
38
+ const given = argv.key?.trim();
39
+ const key = given && given !== '-' ? given : await readKeyFromInput(given === '-');
40
+ if (!key)
41
+ throw new Error('No key given.');
42
+ if (!key.startsWith(KEY_PREFIX)) {
43
+ throw new Error(`That doesn't look like an Eversince key — they start with ${KEY_PREFIX}`);
44
+ }
45
+ stored = { kind: 'api_key', token: key, host };
46
+ }
47
+ else {
48
+ const tokens = await browserLogin(baseUrl, {
49
+ existingClientId: previous?.clientId,
50
+ existingRedirectUri: previous?.redirectUri,
51
+ onUrl: (url) => {
52
+ if (mode.json)
53
+ return;
54
+ note('Opening your browser to sign in.');
55
+ note(`If it doesn't open: ${url}`);
56
+ },
57
+ });
58
+ stored = {
59
+ kind: 'oauth',
60
+ token: tokens.accessToken,
61
+ refreshToken: tokens.refreshToken,
62
+ expiresAt: tokens.expiresAt,
63
+ clientId: tokens.clientId,
64
+ redirectUri: tokens.redirectUri,
65
+ host,
66
+ };
67
+ }
68
+ try {
69
+ await verify(baseUrl, stored);
70
+ }
71
+ catch (error) {
72
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
73
+ throw new Error(error.status === 403
74
+ ? error.body.message
75
+ : useKey
76
+ ? 'That key was rejected. Check it in Settings → API keys.'
77
+ : 'Sign-in completed but the token was rejected. Try again, or use an API key.');
78
+ }
79
+ throw error;
80
+ }
81
+ const where = await writeCredentials(stored);
82
+ if (connection.baseUrl)
83
+ await writeSettings({ baseUrl });
84
+ printResult(mode, { host, kind: stored.kind, storage: where }, () => {
85
+ line(`Signed in to ${host}${stored.kind === 'api_key' ? ' with an API key' : ''}.`);
86
+ line(`Credential stored in the ${where === 'keychain' ? 'system keychain' : 'config file'}.`);
87
+ if (process.env.ES_API_KEY) {
88
+ note('ES_API_KEY is set in this shell and takes precedence over what was just stored.');
89
+ }
90
+ });
91
+ }
92
+ export async function logout(connection, mode) {
93
+ const baseUrl = await resolveBaseUrl(connection.baseUrl);
94
+ const host = hostOf(baseUrl);
95
+ const had = await readCredentials(host);
96
+ await deleteCredentials(host);
97
+ printResult(mode, { host, removed: had !== null }, () => {
98
+ line(had ? `Signed out of ${host}.` : `Nothing stored for ${host}.`);
99
+ if (process.env.ES_API_KEY) {
100
+ note('ES_API_KEY is still set in this environment and will keep being used.');
101
+ }
102
+ if (had?.kind === 'oauth') {
103
+ note('The authorisation is also revocable from Settings → Connected apps.');
104
+ }
105
+ });
106
+ }
107
+ export async function status(connection, mode) {
108
+ const baseUrl = await resolveBaseUrl(connection.baseUrl);
109
+ const host = hostOf(baseUrl);
110
+ const credentials = await loadCredentials(baseUrl);
111
+ const workspace = await resolveWorkspace(baseUrl, connection.workspace);
112
+ const fromEnv = Boolean(process.env.ES_API_KEY);
113
+ const desktop = desktopInstalled();
114
+ const payload = {
115
+ desktop_app: desktop.installed ? (desktop.canConnect ? 'used' : 'update_needed') : 'not_installed',
116
+ signed_in: credentials !== null,
117
+ host,
118
+ base_url: baseUrl,
119
+ kind: credentials?.kind ?? null,
120
+ source: fromEnv ? 'env' : credentials ? storageKind() : null,
121
+ workspace: workspace ?? null,
122
+ expires_at: credentials?.expiresAt ? new Date(credentials.expiresAt).toISOString() : null,
123
+ };
124
+ printResult(mode, payload, () => {
125
+ if (desktop.canConnect)
126
+ line('Desktop app: commands go through it, unless run with --cloud.');
127
+ else if (desktop.installed)
128
+ line('Desktop app: update it so commands can go through it.');
129
+ if (!credentials) {
130
+ line(`Not signed in to ${host}.`);
131
+ return;
132
+ }
133
+ line(`${host} — signed in (${credentials.kind === 'api_key' ? 'API key' : 'browser sign-in'}${fromEnv ? ', from ES_API_KEY' : ''})`);
134
+ line(`workspace: ${workspace ?? 'account default'}`);
135
+ if (credentials.kind === 'oauth') {
136
+ line(`session renews automatically${credentials.refreshToken ? '' : ' — no refresh token, sign in again when it lapses'}`);
137
+ }
138
+ });
139
+ }