eversince 0.2.2 → 0.2.3
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/dist/auth/oauth.js +22 -12
- package/dist/auth/store.js +53 -5
- package/dist/client.js +47 -11
- package/dist/commands/auth.js +7 -4
- package/package.json +1 -1
package/dist/auth/oauth.js
CHANGED
|
@@ -7,8 +7,13 @@ const CLIENT_URI = 'https://eversince.ai';
|
|
|
7
7
|
function base64url(input) {
|
|
8
8
|
return input.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
9
9
|
}
|
|
10
|
+
const AUTH_REQUEST_TIMEOUT_MS = 10_000;
|
|
11
|
+
export const RENEWAL_DEADLINE_MS = 15_000;
|
|
12
|
+
export class RenewalRefused extends Error {
|
|
13
|
+
}
|
|
10
14
|
async function getJson(url, init) {
|
|
11
15
|
const res = await fetch(url, {
|
|
16
|
+
signal: AbortSignal.timeout(AUTH_REQUEST_TIMEOUT_MS),
|
|
12
17
|
...init,
|
|
13
18
|
headers: { accept: 'application/json', 'user-agent': USER_AGENT, ...(init?.headers ?? {}) },
|
|
14
19
|
});
|
|
@@ -23,8 +28,9 @@ async function getJson(url, init) {
|
|
|
23
28
|
throw new Error(`${url} did not return JSON`);
|
|
24
29
|
}
|
|
25
30
|
}
|
|
26
|
-
export async function discoverAuthorizationServer(baseUrl) {
|
|
27
|
-
const
|
|
31
|
+
export async function discoverAuthorizationServer(baseUrl, signal) {
|
|
32
|
+
const init = signal ? { signal } : undefined;
|
|
33
|
+
const metadata = (await getJson(new URL('/.well-known/oauth-protected-resource', baseUrl).toString(), init));
|
|
28
34
|
const issuer = metadata.authorization_servers?.[0];
|
|
29
35
|
if (!issuer)
|
|
30
36
|
throw new Error(`${baseUrl} does not advertise an authorization server.`);
|
|
@@ -32,10 +38,10 @@ export async function discoverAuthorizationServer(baseUrl) {
|
|
|
32
38
|
const wellKnown = new URL(`/.well-known/oauth-authorization-server${issuerUrl.pathname.replace(/\/$/, '')}`, issuerUrl.origin).toString();
|
|
33
39
|
let server;
|
|
34
40
|
try {
|
|
35
|
-
server = (await getJson(wellKnown));
|
|
41
|
+
server = (await getJson(wellKnown, init));
|
|
36
42
|
}
|
|
37
43
|
catch {
|
|
38
|
-
server = (await getJson(new URL('.well-known/oauth-authorization-server', `${issuer}/`).toString()));
|
|
44
|
+
server = (await getJson(new URL('.well-known/oauth-authorization-server', `${issuer}/`).toString(), init));
|
|
39
45
|
}
|
|
40
46
|
if (!server.authorization_endpoint || !server.token_endpoint) {
|
|
41
47
|
throw new Error('Authorization server metadata is missing its endpoints.');
|
|
@@ -77,10 +83,11 @@ function openBrowser(url) {
|
|
|
77
83
|
catch {
|
|
78
84
|
}
|
|
79
85
|
}
|
|
80
|
-
const DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>
|
|
81
|
-
<style>body{font:
|
|
82
|
-
|
|
83
|
-
|
|
86
|
+
const DONE_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Eversince is connected</title>
|
|
87
|
+
<style>body{font-family:Inter,-apple-system,system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0;padding:0 16px;background:#fff;color:#18181b;text-align:center;-webkit-font-smoothing:antialiased}
|
|
88
|
+
h1{font-size:14px;font-weight:500;margin:0}p{font-size:14px;color:#71717a;margin:6px 0 0}
|
|
89
|
+
@media(prefers-color-scheme:dark){body{background:#161616;color:#f4f4f5}p{color:#a1a1aa}}</style>
|
|
90
|
+
<body><div><h1>You're all set</h1><p>You can close this tab and go back to your agent</p></div>`;
|
|
84
91
|
const PREFERRED_PORTS = [51703, 51704, 51705, 0];
|
|
85
92
|
async function awaitCallback(timeoutMs) {
|
|
86
93
|
let settle = null;
|
|
@@ -180,8 +187,9 @@ export async function browserLogin(baseUrl, opts) {
|
|
|
180
187
|
callback.close();
|
|
181
188
|
}
|
|
182
189
|
}
|
|
183
|
-
async function exchange(server, params) {
|
|
190
|
+
async function exchange(server, params, signal) {
|
|
184
191
|
const res = await fetch(server.token_endpoint, {
|
|
192
|
+
signal: signal ?? AbortSignal.timeout(AUTH_REQUEST_TIMEOUT_MS),
|
|
185
193
|
method: 'POST',
|
|
186
194
|
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json', 'user-agent': USER_AGENT },
|
|
187
195
|
body: new URLSearchParams(params).toString(),
|
|
@@ -195,7 +203,8 @@ async function exchange(server, params) {
|
|
|
195
203
|
throw new Error(`Token endpoint returned non-JSON (${res.status}).`);
|
|
196
204
|
}
|
|
197
205
|
if (!res.ok || !payload.access_token) {
|
|
198
|
-
|
|
206
|
+
const reason = payload.error_description || payload.msg || payload.error_code || payload.error || `Token exchange failed (${res.status}).`;
|
|
207
|
+
throw res.status === 400 || res.status === 401 ? new RenewalRefused(reason) : new Error(reason);
|
|
199
208
|
}
|
|
200
209
|
return {
|
|
201
210
|
accessToken: payload.access_token,
|
|
@@ -204,11 +213,12 @@ async function exchange(server, params) {
|
|
|
204
213
|
};
|
|
205
214
|
}
|
|
206
215
|
export async function refreshTokens(baseUrl, clientId, refreshToken) {
|
|
207
|
-
const
|
|
216
|
+
const signal = AbortSignal.timeout(RENEWAL_DEADLINE_MS);
|
|
217
|
+
const { server, resource } = await discoverAuthorizationServer(baseUrl, signal);
|
|
208
218
|
return exchange(server, {
|
|
209
219
|
grant_type: 'refresh_token',
|
|
210
220
|
refresh_token: refreshToken,
|
|
211
221
|
client_id: clientId,
|
|
212
222
|
resource,
|
|
213
|
-
});
|
|
223
|
+
}, signal);
|
|
214
224
|
}
|
package/dist/auth/store.js
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
import { homedir } from 'node:os';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
|
-
import { mkdir, readFile, writeFile, rm, chmod } from 'node:fs/promises';
|
|
3
|
+
import { mkdir, readFile, writeFile, rm, chmod, open, stat, unlink, rename } from 'node:fs/promises';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
4
5
|
import { execFile } from 'node:child_process';
|
|
5
6
|
import { promisify } from 'node:util';
|
|
6
7
|
const run = promisify(execFile);
|
|
7
8
|
const SERVICE = 'eversince-cli';
|
|
8
9
|
export function stateDir() {
|
|
9
|
-
return join(homedir(), '.eversince');
|
|
10
|
+
return process.env.ES_STATE_DIR || join(homedir(), '.eversince');
|
|
10
11
|
}
|
|
11
12
|
function credentialsPath() {
|
|
12
13
|
return join(stateDir(), 'credentials.json');
|
|
13
14
|
}
|
|
14
|
-
const keychainUsable = process.platform === 'darwin';
|
|
15
|
+
const keychainUsable = process.platform === 'darwin' && !process.env.ES_STATE_DIR;
|
|
16
|
+
const KEYCHAIN_TIMEOUT_MS = 3_000;
|
|
15
17
|
async function keychainGet(host) {
|
|
16
18
|
if (!keychainUsable)
|
|
17
19
|
return null;
|
|
18
20
|
try {
|
|
19
|
-
const { stdout } = await run('security', ['find-generic-password', '-s', SERVICE, '-a', host, '-w']);
|
|
21
|
+
const { stdout } = await run('security', ['find-generic-password', '-s', SERVICE, '-a', host, '-w'], { timeout: KEYCHAIN_TIMEOUT_MS });
|
|
20
22
|
return JSON.parse(stdout.trim());
|
|
21
23
|
}
|
|
22
24
|
catch {
|
|
@@ -31,7 +33,7 @@ async function keychainSet(host, creds) {
|
|
|
31
33
|
'add-generic-password', '-U',
|
|
32
34
|
'-s', SERVICE, '-a', host,
|
|
33
35
|
'-w', JSON.stringify(creds),
|
|
34
|
-
]);
|
|
36
|
+
], { timeout: KEYCHAIN_TIMEOUT_MS });
|
|
35
37
|
}
|
|
36
38
|
catch {
|
|
37
39
|
return false;
|
|
@@ -63,6 +65,52 @@ async function fileWrite(next) {
|
|
|
63
65
|
await writeFile(credentialsPath(), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
|
64
66
|
await chmod(credentialsPath(), 0o600);
|
|
65
67
|
}
|
|
68
|
+
const LOCK_STALE_MS = 40_000;
|
|
69
|
+
const LOCK_WAIT_MS = 45_000;
|
|
70
|
+
const LOCK_BUSY = new Set(['EEXIST', 'EPERM', 'EBUSY', 'EACCES']);
|
|
71
|
+
export class RenewalBusy extends Error {
|
|
72
|
+
}
|
|
73
|
+
export async function withRenewalLock(host, run) {
|
|
74
|
+
await mkdir(stateDir(), { recursive: true, mode: 0o700 });
|
|
75
|
+
const path = join(stateDir(), `renew-${host.replace(/[^a-z0-9.-]/gi, '_')}.lock`);
|
|
76
|
+
const owner = randomUUID();
|
|
77
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
78
|
+
for (;;) {
|
|
79
|
+
try {
|
|
80
|
+
const handle = await open(path, 'wx', 0o600);
|
|
81
|
+
await handle.writeFile(owner);
|
|
82
|
+
await handle.close();
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (!LOCK_BUSY.has(error.code ?? ''))
|
|
87
|
+
throw error;
|
|
88
|
+
const held = await stat(path).then((s) => ({ age: Date.now() - s.mtimeMs }), () => null);
|
|
89
|
+
if (held && held.age > LOCK_STALE_MS) {
|
|
90
|
+
const before = await readFile(path, 'utf8').catch(() => null);
|
|
91
|
+
const aside = `${path}.${owner}`;
|
|
92
|
+
if (before !== null && await rename(path, aside).then(() => true, () => false)) {
|
|
93
|
+
const moved = await readFile(aside, 'utf8').catch(() => null);
|
|
94
|
+
if (moved === before)
|
|
95
|
+
await unlink(aside).catch(() => { });
|
|
96
|
+
else
|
|
97
|
+
await rename(aside, path).catch(() => unlink(aside).catch(() => { }));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (Date.now() > deadline)
|
|
101
|
+
throw new RenewalBusy('Another Eversince process is renewing the session.');
|
|
102
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
return await run();
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
const mine = await readFile(path, 'utf8').then((text) => text === owner, () => false);
|
|
110
|
+
if (mine)
|
|
111
|
+
await unlink(path).catch(() => { });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
66
114
|
export async function readCredentials(host) {
|
|
67
115
|
const fromKeychain = await keychainGet(host);
|
|
68
116
|
if (fromKeychain)
|
package/dist/client.js
CHANGED
|
@@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { DEFAULT_BASE_URL, normalizeBaseUrl, readSettings, resolveBaseUrl, resolveWorkspace } from './config.js';
|
|
3
3
|
import { localDoor } from './local.js';
|
|
4
4
|
import { note } from './output.js';
|
|
5
|
-
import { readCredentials, writeCredentials } from './auth/store.js';
|
|
6
|
-
import { refreshTokens } from './auth/oauth.js';
|
|
5
|
+
import { readCredentials, withRenewalLock, writeCredentials } from './auth/store.js';
|
|
6
|
+
import { RenewalRefused, refreshTokens } from './auth/oauth.js';
|
|
7
7
|
import { hostOf } from './config.js';
|
|
8
8
|
import { isConnectFailure } from './retry.js';
|
|
9
9
|
import { USER_AGENT } from './version.js';
|
|
@@ -29,6 +29,8 @@ const RETRYABLE_STATUS = new Set([429, 502, 503, 504]);
|
|
|
29
29
|
const MAX_ATTEMPTS = 4;
|
|
30
30
|
const MAX_WRITE_ATTEMPTS = 2;
|
|
31
31
|
const WRITE_RETRY_PAUSE_MS = 500;
|
|
32
|
+
class RenewalUnreachable extends Error {
|
|
33
|
+
}
|
|
32
34
|
function sleep(ms) {
|
|
33
35
|
return new Promise((r) => setTimeout(r, ms));
|
|
34
36
|
}
|
|
@@ -39,6 +41,7 @@ export class Client {
|
|
|
39
41
|
baseUrl;
|
|
40
42
|
workspace;
|
|
41
43
|
credentials;
|
|
44
|
+
fromStore;
|
|
42
45
|
debug;
|
|
43
46
|
defaultTimeoutMs;
|
|
44
47
|
local;
|
|
@@ -49,6 +52,7 @@ export class Client {
|
|
|
49
52
|
this.debug = opts.debug === true || process.env.ES_DEBUG === '1';
|
|
50
53
|
this.defaultTimeoutMs = (opts.timeout ?? 600) * 1000;
|
|
51
54
|
this.local = local;
|
|
55
|
+
this.fromStore = !opts.credentials && !local;
|
|
52
56
|
}
|
|
53
57
|
static async create(opts = {}) {
|
|
54
58
|
if (await mayUseDesktop(opts)) {
|
|
@@ -111,14 +115,46 @@ export class Client {
|
|
|
111
115
|
message: 'Session expired and cannot be renewed. Run `eversince login`.',
|
|
112
116
|
});
|
|
113
117
|
}
|
|
114
|
-
const
|
|
115
|
-
this.credentials
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
118
|
+
const host = this.credentials.host;
|
|
119
|
+
const expired = this.credentials.expiresAt;
|
|
120
|
+
try {
|
|
121
|
+
await withRenewalLock(host, async () => {
|
|
122
|
+
if (this.credentials.expiresAt !== expired)
|
|
123
|
+
return;
|
|
124
|
+
const stored = await readCredentials(host);
|
|
125
|
+
if (!stored && this.fromStore) {
|
|
126
|
+
throw new ApiError(401, { code: 'unauthorized', message: `Signed out of ${host}. Run \`eversince login\`.` });
|
|
127
|
+
}
|
|
128
|
+
if (stored && stored.kind !== 'oauth') {
|
|
129
|
+
this.credentials = stored;
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (stored && stored.token !== this.credentials.token && stored.expiresAt && Date.now() < stored.expiresAt) {
|
|
133
|
+
this.credentials = stored;
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const base = stored ?? this.credentials;
|
|
137
|
+
if (!base.refreshToken || !base.clientId) {
|
|
138
|
+
throw new ApiError(401, { code: 'unauthorized', message: 'Session expired and cannot be renewed. Run `eversince login`.' });
|
|
139
|
+
}
|
|
140
|
+
const next = await refreshTokens(this.baseUrl, base.clientId, base.refreshToken);
|
|
141
|
+
this.credentials = {
|
|
142
|
+
...base,
|
|
143
|
+
token: next.accessToken,
|
|
144
|
+
refreshToken: next.refreshToken ?? base.refreshToken,
|
|
145
|
+
expiresAt: next.expiresAt,
|
|
146
|
+
};
|
|
147
|
+
await writeCredentials(this.credentials);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
if (error instanceof RenewalRefused) {
|
|
152
|
+
throw new ApiError(401, { code: 'unauthorized', message: `The session could not be renewed (${error.message}). Run \`eversince login\`.` });
|
|
153
|
+
}
|
|
154
|
+
if (error instanceof ApiError)
|
|
155
|
+
throw error;
|
|
156
|
+
throw new RenewalUnreachable(error instanceof Error ? error.message : String(error));
|
|
157
|
+
}
|
|
122
158
|
}
|
|
123
159
|
async request(method, path, options) {
|
|
124
160
|
const url = new URL(path, this.baseUrl);
|
|
@@ -206,7 +242,7 @@ export class Client {
|
|
|
206
242
|
continue;
|
|
207
243
|
}
|
|
208
244
|
const aborted = error instanceof Error && error.name === 'AbortError';
|
|
209
|
-
const connectFailure = !aborted && isConnectFailure(error);
|
|
245
|
+
const connectFailure = !aborted && (isConnectFailure(error) || error instanceof RenewalUnreachable);
|
|
210
246
|
const wrapped = new ApiError(0, {
|
|
211
247
|
code: aborted ? 'timeout' : 'network_error',
|
|
212
248
|
message: aborted
|
package/dist/commands/auth.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createInterface } from 'node:readline/promises';
|
|
2
2
|
import { browserLogin } from '../auth/oauth.js';
|
|
3
|
-
import { readCredentials, writeCredentials, deleteCredentials, storageKind } from '../auth/store.js';
|
|
3
|
+
import { readCredentials, writeCredentials, deleteCredentials, storageKind, withRenewalLock } from '../auth/store.js';
|
|
4
4
|
import { resolveBaseUrl, resolveWorkspace, writeSettings, hostOf } from '../config.js';
|
|
5
5
|
import { Client, ApiError, loadCredentials } from '../client.js';
|
|
6
6
|
import { line, note, printResult } from '../output.js';
|
|
@@ -78,7 +78,7 @@ export async function login(argv, connection, mode) {
|
|
|
78
78
|
}
|
|
79
79
|
throw error;
|
|
80
80
|
}
|
|
81
|
-
const where = await writeCredentials(stored);
|
|
81
|
+
const where = await withRenewalLock(host, () => writeCredentials(stored));
|
|
82
82
|
if (connection.baseUrl)
|
|
83
83
|
await writeSettings({ baseUrl });
|
|
84
84
|
printResult(mode, { host, kind: stored.kind, storage: where }, () => {
|
|
@@ -92,8 +92,11 @@ export async function login(argv, connection, mode) {
|
|
|
92
92
|
export async function logout(connection, mode) {
|
|
93
93
|
const baseUrl = await resolveBaseUrl(connection.baseUrl);
|
|
94
94
|
const host = hostOf(baseUrl);
|
|
95
|
-
const had = await
|
|
96
|
-
|
|
95
|
+
const had = await withRenewalLock(host, async () => {
|
|
96
|
+
const found = await readCredentials(host);
|
|
97
|
+
await deleteCredentials(host);
|
|
98
|
+
return found;
|
|
99
|
+
});
|
|
97
100
|
printResult(mode, { host, removed: had !== null }, () => {
|
|
98
101
|
line(had ? `Signed out of ${host}.` : `Nothing stored for ${host}.`);
|
|
99
102
|
if (process.env.ES_API_KEY) {
|