@agentpro/scroll 0.0.0-stage → 2.5.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.
- package/AGENTS.md +55 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/SPEC.md +1079 -0
- package/bin/scroll.js +8 -0
- package/docs/prompt-caching.md +128 -0
- package/index.js +33 -0
- package/lib/audit.js +358 -0
- package/lib/auth.js +849 -0
- package/lib/chat-sdk/admin-controller.js +289 -0
- package/lib/chat-sdk/debouncer.js +94 -0
- package/lib/chat-sdk/group-grants.js +150 -0
- package/lib/chat-sdk/index.js +222 -0
- package/lib/chat-sdk/long-task-runner.js +413 -0
- package/lib/chat-session.js +1788 -0
- package/lib/chat-telemetry.js +557 -0
- package/lib/codex-app-server.js +851 -0
- package/lib/digest.js +112 -0
- package/lib/effects.js +157 -0
- package/lib/eval.js +408 -0
- package/lib/grounding.js +356 -0
- package/lib/installers.js +176 -0
- package/lib/knowledge.js +335 -0
- package/lib/ledger.js +38 -0
- package/lib/loop.js +197 -0
- package/lib/mcp-client.js +926 -0
- package/lib/memory-cli.js +66 -0
- package/lib/memory-tracker.js +1472 -0
- package/lib/memory.js +1279 -0
- package/lib/people-cli.js +81 -0
- package/lib/people.js +534 -0
- package/lib/permissions.js +272 -0
- package/lib/providers.js +1572 -0
- package/lib/runtime.js +928 -0
- package/lib/sandbox.js +744 -0
- package/lib/scheduler.js +402 -0
- package/lib/scroll.js +1225 -0
- package/lib/skill-cli.js +120 -0
- package/lib/skill-eval.js +156 -0
- package/lib/skills.js +860 -0
- package/lib/style.js +126 -0
- package/lib/tool-retriever.js +489 -0
- package/lib/tools.js +1833 -0
- package/lib/user.js +711 -0
- package/lib/vault.js +151 -0
- package/package.json +88 -4
- package/templates/agent/IDENTITY.md +56 -0
- package/templates/agent/SOUL.md +23 -0
- package/templates/agent/TOOLS.md +25 -0
- package/templates/agent/evals/case-02-citation-discipline.md +29 -0
- package/templates/agent/evals/case-03-boundary.md +27 -0
- package/templates/agent/evals/case-example.md +43 -0
- package/templates/agent/hard-rules.md +11 -0
- package/templates/agent/memory/lessons.md +5 -0
- package/templates/agent/memory/log/.gitkeep +0 -0
- package/templates/external-safety-contract.md +5 -0
- package/templates/long-task-planner.md +17 -0
- package/templates/work/LOOP.md +37 -0
- package/templates/work/WORK.md +50 -0
- package/types/chat.d.ts +61 -0
- package/types/index.d.ts +112 -0
package/lib/auth.js
ADDED
|
@@ -0,0 +1,849 @@
|
|
|
1
|
+
// SCROLL 2.0 -- §46 Unified AuthProvider (OAuth 2.0 PKCE, Device Code Flow, API key, Proxy, multi-account failover).
|
|
2
|
+
//
|
|
3
|
+
// Zero runtime dependencies. Node >= 20 built-ins only.
|
|
4
|
+
// Stores credentials atomically with mode 0600 outside git repos; redacts secrets on list/inspect.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import http from 'node:http';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
|
|
10
|
+
export const AUTH_SCHEMA = 'scroll-auth/1';
|
|
11
|
+
|
|
12
|
+
export const OAUTH_PROVIDERS = {
|
|
13
|
+
openai: {
|
|
14
|
+
id: 'openai',
|
|
15
|
+
authorizeUrl: 'https://auth.openai.com/oauth/authorize',
|
|
16
|
+
tokenUrl: 'https://auth.openai.com/oauth/token',
|
|
17
|
+
deviceCodeUrl: 'https://auth.openai.com/api/accounts/deviceauth/usercode',
|
|
18
|
+
scopes: ['openid', 'profile', 'email', 'offline_access'],
|
|
19
|
+
supportsCodexAppServer: true,
|
|
20
|
+
},
|
|
21
|
+
google: {
|
|
22
|
+
id: 'google',
|
|
23
|
+
authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
|
|
24
|
+
tokenUrl: 'https://oauth2.googleapis.com/token',
|
|
25
|
+
deviceCodeUrl: 'https://oauth2.googleapis.com/device/code',
|
|
26
|
+
scopes: ['openid', 'email', 'profile'],
|
|
27
|
+
supportsCodexAppServer: false,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function base64Url(buf) {
|
|
32
|
+
return Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// RFC 7636 PKCE S256 challenge generator
|
|
36
|
+
export function createPkceChallenge() {
|
|
37
|
+
const verifier = base64Url(crypto.randomBytes(32));
|
|
38
|
+
const challenge = base64Url(crypto.createHash('sha256').update(verifier).digest());
|
|
39
|
+
const state = base64Url(crypto.randomBytes(16));
|
|
40
|
+
return { verifier, challenge, method: 'S256', state };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function buildAuthorizationUrl({
|
|
44
|
+
authorizeUrl,
|
|
45
|
+
provider = null,
|
|
46
|
+
clientId,
|
|
47
|
+
redirectUri,
|
|
48
|
+
scope = null,
|
|
49
|
+
challenge,
|
|
50
|
+
state,
|
|
51
|
+
extraParams = {},
|
|
52
|
+
} = {}) {
|
|
53
|
+
const preset = provider ? OAUTH_PROVIDERS[provider] : null;
|
|
54
|
+
const base = authorizeUrl || (preset && preset.authorizeUrl);
|
|
55
|
+
if (!base) throw new Error('buildAuthorizationUrl: authorizeUrl or known provider is required');
|
|
56
|
+
if (!clientId) throw new Error('buildAuthorizationUrl: clientId is required');
|
|
57
|
+
if (!redirectUri) throw new Error('buildAuthorizationUrl: redirectUri is required');
|
|
58
|
+
const url = new URL(base);
|
|
59
|
+
const scopes = Array.isArray(scope)
|
|
60
|
+
? scope.join(' ')
|
|
61
|
+
: (scope || (preset ? preset.scopes.join(' ') : 'openid'));
|
|
62
|
+
url.searchParams.set('response_type', 'code');
|
|
63
|
+
url.searchParams.set('client_id', String(clientId));
|
|
64
|
+
url.searchParams.set('redirect_uri', String(redirectUri));
|
|
65
|
+
if (scopes) url.searchParams.set('scope', scopes);
|
|
66
|
+
if (challenge) {
|
|
67
|
+
url.searchParams.set('code_challenge', String(challenge));
|
|
68
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
69
|
+
}
|
|
70
|
+
if (state) url.searchParams.set('state', String(state));
|
|
71
|
+
for (const [k, v] of Object.entries(extraParams || {})) {
|
|
72
|
+
if (v != null) url.searchParams.set(k, String(v));
|
|
73
|
+
}
|
|
74
|
+
return url.toString();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function parseTokenPayload(json, nowMs) {
|
|
78
|
+
const accessToken = json.access_token || json.accessToken || null;
|
|
79
|
+
if (!accessToken) throw new Error('oauth_token_missing_access_token');
|
|
80
|
+
const expiresIn = Number(json.expires_in || json.expiresIn || 3600);
|
|
81
|
+
const expiresAt = Number.isFinite(expiresIn) && expiresIn > 0
|
|
82
|
+
? new Date(nowMs + expiresIn * 1000).toISOString()
|
|
83
|
+
: null;
|
|
84
|
+
return {
|
|
85
|
+
accessToken,
|
|
86
|
+
refreshToken: json.refresh_token || json.refreshToken || null,
|
|
87
|
+
tokenType: json.token_type || json.tokenType || 'Bearer',
|
|
88
|
+
scope: json.scope || null,
|
|
89
|
+
idToken: json.id_token || null,
|
|
90
|
+
expiresAt,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function postForm(url, params, { fetchImpl = globalThis.fetch, headers = {} } = {}) {
|
|
95
|
+
if (typeof fetchImpl !== 'function') throw new Error('fetch is not available');
|
|
96
|
+
const body = new URLSearchParams();
|
|
97
|
+
for (const [k, v] of Object.entries(params || {})) {
|
|
98
|
+
if (v != null && v !== '') body.set(k, String(v));
|
|
99
|
+
}
|
|
100
|
+
const res = await fetchImpl(url, {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', ...headers },
|
|
103
|
+
body: body.toString(),
|
|
104
|
+
});
|
|
105
|
+
const text = await res.text();
|
|
106
|
+
let json;
|
|
107
|
+
try { json = JSON.parse(text); } catch { json = { raw: text }; }
|
|
108
|
+
return { ok: res.ok, status: res.status, json, text };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function exchangeAuthCode({
|
|
112
|
+
tokenUrl,
|
|
113
|
+
provider = null,
|
|
114
|
+
clientId,
|
|
115
|
+
clientSecret = null,
|
|
116
|
+
code,
|
|
117
|
+
verifier = null,
|
|
118
|
+
redirectUri,
|
|
119
|
+
fetchImpl = globalThis.fetch,
|
|
120
|
+
clock = () => Date.now(),
|
|
121
|
+
} = {}) {
|
|
122
|
+
const preset = provider ? OAUTH_PROVIDERS[provider] : null;
|
|
123
|
+
const endpoint = tokenUrl || (preset && preset.tokenUrl);
|
|
124
|
+
if (!endpoint) throw new Error('exchangeAuthCode: tokenUrl or known provider is required');
|
|
125
|
+
if (!clientId || !code || !redirectUri) {
|
|
126
|
+
throw new Error('exchangeAuthCode: clientId, code, and redirectUri are required');
|
|
127
|
+
}
|
|
128
|
+
const r = await postForm(endpoint, {
|
|
129
|
+
grant_type: 'authorization_code',
|
|
130
|
+
client_id: clientId,
|
|
131
|
+
client_secret: clientSecret,
|
|
132
|
+
code,
|
|
133
|
+
redirect_uri: redirectUri,
|
|
134
|
+
code_verifier: verifier,
|
|
135
|
+
}, { fetchImpl });
|
|
136
|
+
if (!r.ok) {
|
|
137
|
+
const err = new Error(r.json?.error_description || r.json?.error || `oauth_exchange_failed:${r.status}`);
|
|
138
|
+
err.status = r.status;
|
|
139
|
+
err.oauthError = r.json?.error || null;
|
|
140
|
+
throw err;
|
|
141
|
+
}
|
|
142
|
+
return parseTokenPayload(r.json, clock());
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// RFC 8628 Device Authorization Grant
|
|
146
|
+
export async function startDeviceAuth({
|
|
147
|
+
deviceCodeUrl,
|
|
148
|
+
provider = null,
|
|
149
|
+
clientId,
|
|
150
|
+
scope = null,
|
|
151
|
+
extraParams = {},
|
|
152
|
+
fetchImpl = globalThis.fetch,
|
|
153
|
+
} = {}) {
|
|
154
|
+
const preset = provider ? OAUTH_PROVIDERS[provider] : null;
|
|
155
|
+
const endpoint = deviceCodeUrl || (preset && preset.deviceCodeUrl);
|
|
156
|
+
if (!endpoint) throw new Error('startDeviceAuth: deviceCodeUrl or known provider is required');
|
|
157
|
+
if (!clientId) throw new Error('startDeviceAuth: clientId is required');
|
|
158
|
+
const scopes = Array.isArray(scope)
|
|
159
|
+
? scope.join(' ')
|
|
160
|
+
: (scope || (preset ? preset.scopes.join(' ') : 'openid'));
|
|
161
|
+
const r = await postForm(endpoint, {
|
|
162
|
+
client_id: clientId,
|
|
163
|
+
scope: scopes,
|
|
164
|
+
...extraParams,
|
|
165
|
+
}, { fetchImpl });
|
|
166
|
+
if (!r.ok) {
|
|
167
|
+
const err = new Error(r.json?.error_description || r.json?.error || `device_auth_start_failed:${r.status}`);
|
|
168
|
+
err.status = r.status;
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
const j = r.json || {};
|
|
172
|
+
return {
|
|
173
|
+
deviceCode: j.device_code || j.deviceCode,
|
|
174
|
+
userCode: j.user_code || j.userCode,
|
|
175
|
+
verificationUri: j.verification_uri || j.verificationUri || j.verification_url || null,
|
|
176
|
+
verificationUriComplete: j.verification_uri_complete || j.verificationUriComplete || null,
|
|
177
|
+
expiresIn: Number(j.expires_in || 600),
|
|
178
|
+
interval: Number(j.interval || 5),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function pollDeviceToken({
|
|
183
|
+
tokenUrl,
|
|
184
|
+
provider = null,
|
|
185
|
+
clientId,
|
|
186
|
+
deviceCode,
|
|
187
|
+
intervalMs = 5000,
|
|
188
|
+
timeoutMs = 300_000,
|
|
189
|
+
fetchImpl = globalThis.fetch,
|
|
190
|
+
sleepImpl = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
191
|
+
clock = () => Date.now(),
|
|
192
|
+
} = {}) {
|
|
193
|
+
const preset = provider ? OAUTH_PROVIDERS[provider] : null;
|
|
194
|
+
const endpoint = tokenUrl || (preset && preset.tokenUrl);
|
|
195
|
+
if (!endpoint || !clientId || !deviceCode) {
|
|
196
|
+
throw new Error('pollDeviceToken: tokenUrl, clientId, and deviceCode are required');
|
|
197
|
+
}
|
|
198
|
+
const deadline = clock() + timeoutMs;
|
|
199
|
+
let waitMs = Math.max(10, Number(intervalMs) || 5000);
|
|
200
|
+
while (clock() < deadline) {
|
|
201
|
+
const r = await postForm(endpoint, {
|
|
202
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
203
|
+
device_code: deviceCode,
|
|
204
|
+
client_id: clientId,
|
|
205
|
+
}, { fetchImpl });
|
|
206
|
+
if (r.ok) return parseTokenPayload(r.json, clock());
|
|
207
|
+
const code = r.json?.error || '';
|
|
208
|
+
if (code === 'authorization_pending') {
|
|
209
|
+
await sleepImpl(waitMs);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (code === 'slow_down') {
|
|
213
|
+
waitMs += 5000;
|
|
214
|
+
await sleepImpl(waitMs);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const err = new Error(r.json?.error_description || code || `device_poll_failed:${r.status}`);
|
|
218
|
+
err.status = r.status;
|
|
219
|
+
err.oauthError = code || null;
|
|
220
|
+
throw err;
|
|
221
|
+
}
|
|
222
|
+
const err = new Error('device_auth_timeout');
|
|
223
|
+
err.oauthError = 'expired_token';
|
|
224
|
+
throw err;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function redactSecret(val) {
|
|
228
|
+
if (!val) return null;
|
|
229
|
+
const s = String(val);
|
|
230
|
+
if (s.length <= 8) return '***';
|
|
231
|
+
return `${s.slice(0, 4)}...${s.slice(-4)}`;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function sanitizeProfile(p, includeSecrets) {
|
|
235
|
+
const copy = { ...p };
|
|
236
|
+
if (!includeSecrets) {
|
|
237
|
+
if (copy.accessToken) copy.accessToken = redactSecret(copy.accessToken);
|
|
238
|
+
if (copy.refreshToken) copy.refreshToken = redactSecret(copy.refreshToken);
|
|
239
|
+
if (copy.apiKey) copy.apiKey = redactSecret(copy.apiKey);
|
|
240
|
+
if (copy.clientSecret) copy.clientSecret = redactSecret(copy.clientSecret);
|
|
241
|
+
if (copy.extraHeaders && typeof copy.extraHeaders === 'object') {
|
|
242
|
+
const safe = {};
|
|
243
|
+
for (const [k, v] of Object.entries(copy.extraHeaders)) {
|
|
244
|
+
safe[k] = /auth|key|token|secret/i.test(k) ? redactSecret(v) : v;
|
|
245
|
+
}
|
|
246
|
+
copy.extraHeaders = safe;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return copy;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function writeAtomicSecure(filePath, data) {
|
|
253
|
+
const dir = path.dirname(filePath);
|
|
254
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
255
|
+
const tmp = `${filePath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
|
|
256
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
|
|
257
|
+
try {
|
|
258
|
+
const fd = fs.openSync(tmp, 'r');
|
|
259
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
260
|
+
} catch { /* fsync optional on virtual filesystems */ }
|
|
261
|
+
fs.renameSync(tmp, filePath);
|
|
262
|
+
try { fs.chmodSync(filePath, 0o600); } catch { /* ignore on non-POSIX */ }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function isRateLimitError(err) {
|
|
266
|
+
if (!err) return false;
|
|
267
|
+
if (Number(err.status) === 429) return true;
|
|
268
|
+
const msg = String(err.message || err).toLowerCase();
|
|
269
|
+
return /429|rate.?limit|quota|too many requests|resource_exhausted/.test(msg);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function isAuthError(err) {
|
|
273
|
+
if (!err) return false;
|
|
274
|
+
const st = Number(err.status);
|
|
275
|
+
if (st === 401 || st === 403) return true;
|
|
276
|
+
const msg = String(err.message || err).toLowerCase();
|
|
277
|
+
return /401|403|unauthorized|invalid_token|invalid_grant|expired_token|authentication/.test(msg);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export async function runLoopbackOAuthCallback({
|
|
281
|
+
host = '127.0.0.1',
|
|
282
|
+
port = 0,
|
|
283
|
+
callbackPath = '/callback',
|
|
284
|
+
expectedState = null,
|
|
285
|
+
timeoutMs = 180_000,
|
|
286
|
+
} = {}) {
|
|
287
|
+
let resolveResult;
|
|
288
|
+
let rejectResult;
|
|
289
|
+
const resultPromise = new Promise((resolve, reject) => {
|
|
290
|
+
resolveResult = resolve;
|
|
291
|
+
rejectResult = reject;
|
|
292
|
+
});
|
|
293
|
+
let settled = false;
|
|
294
|
+
let timer = null;
|
|
295
|
+
|
|
296
|
+
const finish = (err, val) => {
|
|
297
|
+
if (settled) return;
|
|
298
|
+
settled = true;
|
|
299
|
+
if (timer) clearTimeout(timer);
|
|
300
|
+
try { server.close(); } catch { /* ignore */ }
|
|
301
|
+
if (err) rejectResult(err);
|
|
302
|
+
else resolveResult(val);
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const server = http.createServer((req, res) => {
|
|
306
|
+
try {
|
|
307
|
+
const url = new URL(req.url || '/', `http://${host}`);
|
|
308
|
+
if (url.pathname !== callbackPath) {
|
|
309
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
310
|
+
res.end('Not Found');
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const code = url.searchParams.get('code');
|
|
314
|
+
const state = url.searchParams.get('state');
|
|
315
|
+
const oauthError = url.searchParams.get('error');
|
|
316
|
+
const oauthErrorDesc = url.searchParams.get('error_description');
|
|
317
|
+
if (oauthError) {
|
|
318
|
+
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
319
|
+
res.end('<html><body><h2>Authentication failed</h2><p>You may close this window.</p></body></html>');
|
|
320
|
+
const err = new Error(oauthErrorDesc || oauthError);
|
|
321
|
+
err.oauthError = oauthError;
|
|
322
|
+
finish(err);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (expectedState && state !== expectedState) {
|
|
326
|
+
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
327
|
+
res.end('<html><body><h2>Invalid OAuth state</h2></body></html>');
|
|
328
|
+
finish(new Error('oauth_state_mismatch'));
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (!code) {
|
|
332
|
+
res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
333
|
+
res.end('<html><body><h2>Missing authorization code</h2></body></html>');
|
|
334
|
+
finish(new Error('oauth_missing_code'));
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
338
|
+
res.end('<html><body><h2>Authentication received</h2><p>You may close this window and return to SCROLL.</p></body></html>');
|
|
339
|
+
finish(null, { code, state });
|
|
340
|
+
} catch (err) {
|
|
341
|
+
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
342
|
+
res.end('Internal Error');
|
|
343
|
+
finish(err);
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
await new Promise((resolve, reject) => {
|
|
348
|
+
server.once('error', reject);
|
|
349
|
+
server.listen(port, host, () => {
|
|
350
|
+
server.removeListener('error', reject);
|
|
351
|
+
resolve();
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
const addr = server.address();
|
|
356
|
+
const actualPort = typeof addr === 'object' && addr ? addr.port : port;
|
|
357
|
+
const redirectUri = `http://${host}:${actualPort}${callbackPath}`;
|
|
358
|
+
timer = setTimeout(() => finish(new Error('oauth_loopback_timeout')), Math.max(1000, Number(timeoutMs || 180_000)));
|
|
359
|
+
if (timer.unref) timer.unref();
|
|
360
|
+
|
|
361
|
+
return {
|
|
362
|
+
redirectUri,
|
|
363
|
+
port: actualPort,
|
|
364
|
+
waitForCode: () => resultPromise,
|
|
365
|
+
close: () => finish(new Error('oauth_loopback_closed')),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function isPidAlive(pid) {
|
|
370
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
371
|
+
try {
|
|
372
|
+
process.kill(pid, 0);
|
|
373
|
+
return true;
|
|
374
|
+
} catch (err) {
|
|
375
|
+
return err?.code === 'EPERM';
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function withAuthFileLock(absPath, fn, { timeoutMs = 6000, staleMs = 30_000 } = {}) {
|
|
380
|
+
if (!absPath) return fn();
|
|
381
|
+
const lockPath = `${absPath}.lock`;
|
|
382
|
+
fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 });
|
|
383
|
+
const ownerToken = `${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
|
|
384
|
+
const deadline = Date.now() + timeoutMs;
|
|
385
|
+
let acquired = false;
|
|
386
|
+
while (!acquired) {
|
|
387
|
+
try {
|
|
388
|
+
const fd = fs.openSync(lockPath, 'wx', 0o600);
|
|
389
|
+
try {
|
|
390
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, token: ownerToken, ts: Date.now() }) + '\n');
|
|
391
|
+
} finally {
|
|
392
|
+
fs.closeSync(fd);
|
|
393
|
+
}
|
|
394
|
+
acquired = true;
|
|
395
|
+
} catch (err) {
|
|
396
|
+
if (err?.code !== 'EEXIST') throw err;
|
|
397
|
+
// Serialize stale-lock reaping behind an exclusive per-dead-lock `.reap.<deadKey>` lock so two concurrent waiters
|
|
398
|
+
// can NEVER double-unlink a freshly acquired lock OR steal a newly created live `.reap` lock!
|
|
399
|
+
const exclFlags = fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | (fs.constants.O_NOFOLLOW || 0);
|
|
400
|
+
const inspectStaleLock = (targetPath, maxAgeMs) => {
|
|
401
|
+
try {
|
|
402
|
+
const st = fs.lstatSync(targetPath);
|
|
403
|
+
let info = null;
|
|
404
|
+
try { info = JSON.parse(fs.readFileSync(targetPath, 'utf8')); } catch { info = null; }
|
|
405
|
+
if (info && typeof info === 'object' && info.pid && !isPidAlive(Number(info.pid))) {
|
|
406
|
+
const tok = typeof info.token === 'string' && /^[A-Za-z0-9._-]{1,64}$/.test(info.token) ? info.token : null;
|
|
407
|
+
return {
|
|
408
|
+
stale: true,
|
|
409
|
+
key: tok ? `tok-${tok}` : `ino-${st.ino}-${Math.floor(st.mtimeMs)}`,
|
|
410
|
+
expectedToken: tok,
|
|
411
|
+
ino: st.ino,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
if ((!info || !info.pid) && Date.now() - st.mtimeMs > maxAgeMs) {
|
|
415
|
+
return {
|
|
416
|
+
stale: true,
|
|
417
|
+
key: `ino-${st.ino}-${Math.floor(st.mtimeMs)}`,
|
|
418
|
+
expectedToken: null,
|
|
419
|
+
ino: st.ino,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
} catch { /* vanished */ }
|
|
423
|
+
return { stale: false, key: null, expectedToken: null, ino: null };
|
|
424
|
+
};
|
|
425
|
+
const matchesDeadSnapshot = (targetPath, snap, maxAgeMs) => {
|
|
426
|
+
const cur = inspectStaleLock(targetPath, maxAgeMs);
|
|
427
|
+
if (!cur.stale) return false;
|
|
428
|
+
if (snap.expectedToken) return cur.expectedToken === snap.expectedToken;
|
|
429
|
+
return cur.expectedToken === null && cur.ino === snap.ino && cur.key === snap.key;
|
|
430
|
+
};
|
|
431
|
+
const unlinkIfOwned = (targetPath, myTok) => {
|
|
432
|
+
try {
|
|
433
|
+
const cur = JSON.parse(fs.readFileSync(targetPath, 'utf8'));
|
|
434
|
+
if (cur && cur.token === myTok) fs.rmSync(targetPath, { force: true });
|
|
435
|
+
} catch { /* already cleaned or replaced */ }
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
const deadLock = inspectStaleLock(lockPath, staleMs);
|
|
439
|
+
if (deadLock.stale) {
|
|
440
|
+
const reapPath = `${lockPath}.reap.${deadLock.key}`;
|
|
441
|
+
let reapFd = null;
|
|
442
|
+
try {
|
|
443
|
+
reapFd = fs.openSync(reapPath, exclFlags, 0o600);
|
|
444
|
+
try { fs.writeFileSync(reapFd, JSON.stringify({ pid: process.pid, token: ownerToken, ts: Date.now() }) + '\n'); } catch { /* ignore */ }
|
|
445
|
+
} catch (reapErr) {
|
|
446
|
+
if (reapErr?.code === 'EEXIST') {
|
|
447
|
+
const reapStaleMs = Math.max(5_000, staleMs);
|
|
448
|
+
const deadReap = inspectStaleLock(reapPath, reapStaleMs);
|
|
449
|
+
if (deadReap.stale) {
|
|
450
|
+
// Walk any chain of crashed claim holders using pure O_CREAT|O_EXCL (ZERO renameSync/linkSync!),
|
|
451
|
+
// then unlink bottom-up (reapPath FIRST while dead claims block rivals, then dead claims) under exclusive guard!
|
|
452
|
+
const chain = [{ path: reapPath, snap: deadReap }];
|
|
453
|
+
for (let depth = 0; depth < 16; depth++) {
|
|
454
|
+
const top = chain[chain.length - 1];
|
|
455
|
+
const guardPath = `${reapPath}.claim.${top.snap.key}`;
|
|
456
|
+
let guardFd = null;
|
|
457
|
+
try {
|
|
458
|
+
guardFd = fs.openSync(guardPath, exclFlags, 0o600);
|
|
459
|
+
try { fs.writeFileSync(guardFd, JSON.stringify({ pid: process.pid, token: ownerToken, ts: Date.now() }) + '\n'); } catch { /* ignore */ }
|
|
460
|
+
if (chain.every((item) => matchesDeadSnapshot(item.path, item.snap, reapStaleMs))) {
|
|
461
|
+
for (const item of chain) {
|
|
462
|
+
try { fs.rmSync(item.path, { force: true }); } catch { /* ignore */ }
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
break;
|
|
466
|
+
} catch (guardErr) {
|
|
467
|
+
if (guardErr?.code !== 'EEXIST') break;
|
|
468
|
+
const deadGuard = inspectStaleLock(guardPath, reapStaleMs);
|
|
469
|
+
if (!deadGuard.stale) break; // Live claimer owns guardPath -- never interfere!
|
|
470
|
+
if (chain.some((c) => c.path === guardPath)) break;
|
|
471
|
+
chain.push({ path: guardPath, snap: deadGuard });
|
|
472
|
+
} finally {
|
|
473
|
+
if (guardFd !== null) {
|
|
474
|
+
try { fs.closeSync(guardFd); } catch { /* ignore */ }
|
|
475
|
+
unlinkIfOwned(guardPath, ownerToken);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (reapFd !== null) {
|
|
483
|
+
try {
|
|
484
|
+
if (matchesDeadSnapshot(lockPath, deadLock, staleMs)) {
|
|
485
|
+
fs.rmSync(lockPath, { force: true });
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
} finally {
|
|
489
|
+
try { fs.closeSync(reapFd); } catch { /* ignore */ }
|
|
490
|
+
unlinkIfOwned(reapPath, ownerToken);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (Date.now() >= deadline) {
|
|
495
|
+
throw new Error(`auth_lock_timeout:${lockPath}`);
|
|
496
|
+
}
|
|
497
|
+
await new Promise((r) => setTimeout(r, 25 + Math.floor(Math.random() * 40)));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
try {
|
|
501
|
+
return await fn();
|
|
502
|
+
} finally {
|
|
503
|
+
// Compare owner token before releasing so we NEVER delete another process's lockfile
|
|
504
|
+
try {
|
|
505
|
+
const cur = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
|
|
506
|
+
if (cur && cur.token === ownerToken) {
|
|
507
|
+
fs.rmSync(lockPath, { force: true });
|
|
508
|
+
}
|
|
509
|
+
} catch { /* ignore */ }
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
export function createAuthStore({
|
|
514
|
+
filePath = null,
|
|
515
|
+
clock = () => Date.now(),
|
|
516
|
+
fetchImpl = globalThis.fetch,
|
|
517
|
+
defaultCooldownMs = 60_000,
|
|
518
|
+
maxCooldownMs = 900_000,
|
|
519
|
+
} = {}) {
|
|
520
|
+
const absPath = filePath ? path.resolve(filePath) : null;
|
|
521
|
+
|
|
522
|
+
function emptyState() {
|
|
523
|
+
return { schema: AUTH_SCHEMA, defaults: {}, profiles: {} };
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function load() {
|
|
527
|
+
if (!absPath || !fs.existsSync(absPath)) return emptyState();
|
|
528
|
+
const raw = fs.readFileSync(absPath, 'utf8');
|
|
529
|
+
const parsed = JSON.parse(raw);
|
|
530
|
+
return {
|
|
531
|
+
schema: parsed.schema || AUTH_SCHEMA,
|
|
532
|
+
defaults: parsed.defaults && typeof parsed.defaults === 'object' ? { ...parsed.defaults } : {},
|
|
533
|
+
profiles: parsed.profiles && typeof parsed.profiles === 'object' ? { ...parsed.profiles } : {},
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
let memState = load();
|
|
538
|
+
|
|
539
|
+
function persist(changedProfileId = null) {
|
|
540
|
+
if (!absPath) return;
|
|
541
|
+
// Merge-before-write: preserve newer profile rotations written by concurrent processes
|
|
542
|
+
if (fs.existsSync(absPath)) {
|
|
543
|
+
try {
|
|
544
|
+
const disk = load();
|
|
545
|
+
for (const [id, dp] of Object.entries(disk.profiles || {})) {
|
|
546
|
+
if (id === changedProfileId) continue;
|
|
547
|
+
const mp = memState.profiles[id];
|
|
548
|
+
if (!mp) continue;
|
|
549
|
+
const diskTs = Date.parse(dp?.updatedAt || 0);
|
|
550
|
+
const memTs = Date.parse(mp?.updatedAt || 0);
|
|
551
|
+
if (Number.isFinite(diskTs) && Number.isFinite(memTs) && diskTs > memTs) {
|
|
552
|
+
memState.profiles[id] = dp;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
} catch { /* ignore unreadable disk snapshot */ }
|
|
556
|
+
}
|
|
557
|
+
writeAtomicSecure(absPath, memState);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function reload() {
|
|
561
|
+
memState = load();
|
|
562
|
+
return memState;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function listProfiles({ provider = null, includeSecrets = false } = {}) {
|
|
566
|
+
const items = Object.values(memState.profiles)
|
|
567
|
+
.filter((p) => !provider || p.provider === provider)
|
|
568
|
+
.sort((a, b) => (Number(a.priority || 100) - Number(b.priority || 100)) || String(a.id).localeCompare(String(b.id)));
|
|
569
|
+
return items.map((p) => ({
|
|
570
|
+
...sanitizeProfile(p, includeSecrets),
|
|
571
|
+
isDefault: memState.defaults[p.provider] === p.id,
|
|
572
|
+
inCooldown: Boolean(p.cooldownUntil && Date.parse(p.cooldownUntil) > clock()),
|
|
573
|
+
}));
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function getProfile(id, { includeSecrets = false } = {}) {
|
|
577
|
+
const p = memState.profiles[id];
|
|
578
|
+
if (!p) return null;
|
|
579
|
+
return {
|
|
580
|
+
...sanitizeProfile(p, includeSecrets),
|
|
581
|
+
isDefault: memState.defaults[p.provider] === p.id,
|
|
582
|
+
inCooldown: Boolean(p.cooldownUntil && Date.parse(p.cooldownUntil) > clock()),
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function upsertProfile(profile) {
|
|
587
|
+
if (!profile || !profile.id || !profile.provider) {
|
|
588
|
+
throw new Error('upsertProfile: id and provider are required');
|
|
589
|
+
}
|
|
590
|
+
const id = String(profile.id).trim();
|
|
591
|
+
const type = profile.type || (profile.apiKey ? 'api_key' : (profile.baseUrl ? 'proxy' : 'oauth'));
|
|
592
|
+
if (!['oauth', 'api_key', 'proxy', 'codex_app_server'].includes(type)) {
|
|
593
|
+
throw new Error(`upsertProfile: unsupported type "${type}"`);
|
|
594
|
+
}
|
|
595
|
+
const prev = memState.profiles[id] || {};
|
|
596
|
+
const next = {
|
|
597
|
+
...prev,
|
|
598
|
+
...profile,
|
|
599
|
+
id,
|
|
600
|
+
provider: String(profile.provider).trim(),
|
|
601
|
+
type,
|
|
602
|
+
priority: Number.isFinite(Number(profile.priority)) ? Number(profile.priority) : (prev.priority ?? 100),
|
|
603
|
+
disabled: profile.disabled === true,
|
|
604
|
+
failures: Number.isFinite(Number(profile.failures)) ? Number(profile.failures) : (prev.failures ?? 0),
|
|
605
|
+
updatedAt: new Date(clock()).toISOString(),
|
|
606
|
+
};
|
|
607
|
+
memState.profiles[id] = next;
|
|
608
|
+
if (!memState.defaults[next.provider] || profile.isDefault === true) {
|
|
609
|
+
memState.defaults[next.provider] = id;
|
|
610
|
+
}
|
|
611
|
+
persist();
|
|
612
|
+
return sanitizeProfile(next, false);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function removeProfile(id) {
|
|
616
|
+
const prev = memState.profiles[id];
|
|
617
|
+
if (!prev) return { ok: false, removed: false };
|
|
618
|
+
delete memState.profiles[id];
|
|
619
|
+
if (memState.defaults[prev.provider] === id) {
|
|
620
|
+
const replacement = Object.values(memState.profiles).find((p) => p.provider === prev.provider);
|
|
621
|
+
if (replacement) memState.defaults[prev.provider] = replacement.id;
|
|
622
|
+
else delete memState.defaults[prev.provider];
|
|
623
|
+
}
|
|
624
|
+
persist();
|
|
625
|
+
return { ok: true, removed: true };
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function setDefault(provider, profileId) {
|
|
629
|
+
const p = memState.profiles[profileId];
|
|
630
|
+
if (!p || p.provider !== provider) {
|
|
631
|
+
throw new Error(`setDefault: profile "${profileId}" not found for provider "${provider}"`);
|
|
632
|
+
}
|
|
633
|
+
memState.defaults[provider] = profileId;
|
|
634
|
+
persist();
|
|
635
|
+
return { ok: true, provider, profileId };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const inflightRefreshes = new Map();
|
|
639
|
+
|
|
640
|
+
async function refreshTokenIfNeeded(profileId, { skewMs = 120_000, force = false } = {}) {
|
|
641
|
+
if (inflightRefreshes.has(profileId) && !force) {
|
|
642
|
+
return inflightRefreshes.get(profileId);
|
|
643
|
+
}
|
|
644
|
+
const task = withAuthFileLock(absPath, async () => {
|
|
645
|
+
// Compare-before-write: reload from disk inside lock in case another process already refreshed!
|
|
646
|
+
if (absPath && fs.existsSync(absPath)) {
|
|
647
|
+
try { memState = load(); } catch { /* keep in-memory state if unreadable */ }
|
|
648
|
+
}
|
|
649
|
+
const p = memState.profiles[profileId];
|
|
650
|
+
if (!p) throw new Error(`refreshTokenIfNeeded: unknown profile "${profileId}"`);
|
|
651
|
+
if (p.type !== 'oauth') return { refreshed: false, profile: p };
|
|
652
|
+
const nowMs = clock();
|
|
653
|
+
const expMs = p.expiresAt ? Date.parse(p.expiresAt) : Infinity;
|
|
654
|
+
const needsRefresh = force || !p.accessToken || (Number.isFinite(expMs) && expMs - nowMs <= skewMs);
|
|
655
|
+
if (!needsRefresh) return { refreshed: false, profile: p };
|
|
656
|
+
if (!p.refreshToken) {
|
|
657
|
+
if (!force && p.accessToken && expMs > nowMs) return { refreshed: false, profile: p };
|
|
658
|
+
const err = new Error(`oauth_refresh_token_missing:${profileId}`);
|
|
659
|
+
err.status = 401;
|
|
660
|
+
throw err;
|
|
661
|
+
}
|
|
662
|
+
const preset = OAUTH_PROVIDERS[p.provider] || null;
|
|
663
|
+
const tokenUrl = p.tokenUrl || (preset && preset.tokenUrl);
|
|
664
|
+
if (!tokenUrl) throw new Error(`oauth_token_url_missing:${profileId}`);
|
|
665
|
+
const r = await postForm(tokenUrl, {
|
|
666
|
+
grant_type: 'refresh_token',
|
|
667
|
+
refresh_token: p.refreshToken,
|
|
668
|
+
client_id: p.clientId || '',
|
|
669
|
+
client_secret: p.clientSecret || '',
|
|
670
|
+
}, { fetchImpl });
|
|
671
|
+
if (!r.ok) {
|
|
672
|
+
const code = r.json?.error || '';
|
|
673
|
+
const permanent = code === 'invalid_grant' || code === 'unauthorized_client' || r.status === 401 || r.status === 403;
|
|
674
|
+
reportAuthFailure(profileId, { error: r.json?.error_description || code || `refresh_failed:${r.status}`, permanent });
|
|
675
|
+
const err = new Error(r.json?.error_description || code || `refresh_failed:${r.status}`);
|
|
676
|
+
err.status = r.status;
|
|
677
|
+
err.oauthError = code || null;
|
|
678
|
+
throw err;
|
|
679
|
+
}
|
|
680
|
+
const tok = parseTokenPayload(r.json, clock());
|
|
681
|
+
p.accessToken = tok.accessToken;
|
|
682
|
+
if (tok.refreshToken) p.refreshToken = tok.refreshToken;
|
|
683
|
+
p.expiresAt = tok.expiresAt;
|
|
684
|
+
p.tokenType = tok.tokenType || 'Bearer';
|
|
685
|
+
p.failures = 0;
|
|
686
|
+
p.cooldownUntil = null;
|
|
687
|
+
p.lastError = null;
|
|
688
|
+
p.updatedAt = new Date(clock()).toISOString();
|
|
689
|
+
persist();
|
|
690
|
+
return { refreshed: true, profile: p };
|
|
691
|
+
});
|
|
692
|
+
inflightRefreshes.set(profileId, task);
|
|
693
|
+
try {
|
|
694
|
+
return await task;
|
|
695
|
+
} finally {
|
|
696
|
+
if (inflightRefreshes.get(profileId) === task) {
|
|
697
|
+
inflightRefreshes.delete(profileId);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function reportRateLimit(profileId, { retryAfterMs = null, error = 'rate_limited' } = {}) {
|
|
703
|
+
const p = memState.profiles[profileId];
|
|
704
|
+
if (!p) return null;
|
|
705
|
+
p.failures = Number(p.failures || 0) + 1;
|
|
706
|
+
const backoff = retryAfterMs != null && Number.isFinite(Number(retryAfterMs))
|
|
707
|
+
? Math.max(1000, Number(retryAfterMs))
|
|
708
|
+
: Math.min(maxCooldownMs, defaultCooldownMs * Math.pow(2, Math.min(4, p.failures - 1)));
|
|
709
|
+
p.cooldownUntil = new Date(clock() + backoff).toISOString();
|
|
710
|
+
p.lastError = String(error || 'rate_limited').slice(0, 300);
|
|
711
|
+
p.updatedAt = new Date(clock()).toISOString();
|
|
712
|
+
persist();
|
|
713
|
+
return { profileId, cooldownUntil: p.cooldownUntil, failures: p.failures };
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function reportAuthFailure(profileId, { error = 'auth_failed', permanent = false } = {}) {
|
|
717
|
+
const p = memState.profiles[profileId];
|
|
718
|
+
if (!p) return null;
|
|
719
|
+
p.failures = Number(p.failures || 0) + 1;
|
|
720
|
+
p.lastError = String(error || 'auth_failed').slice(0, 300);
|
|
721
|
+
if (permanent) {
|
|
722
|
+
p.disabled = true;
|
|
723
|
+
} else {
|
|
724
|
+
p.cooldownUntil = new Date(clock() + Math.min(maxCooldownMs, defaultCooldownMs * 2)).toISOString();
|
|
725
|
+
}
|
|
726
|
+
p.updatedAt = new Date(clock()).toISOString();
|
|
727
|
+
persist();
|
|
728
|
+
return { profileId, disabled: p.disabled, cooldownUntil: p.cooldownUntil };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function reportSuccess(profileId) {
|
|
732
|
+
const p = memState.profiles[profileId];
|
|
733
|
+
if (!p) return null;
|
|
734
|
+
if (p.failures || p.cooldownUntil || p.lastError) {
|
|
735
|
+
p.failures = 0;
|
|
736
|
+
p.cooldownUntil = null;
|
|
737
|
+
p.lastError = null;
|
|
738
|
+
p.updatedAt = new Date(clock()).toISOString();
|
|
739
|
+
persist();
|
|
740
|
+
}
|
|
741
|
+
return { profileId, ok: true };
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function rankCandidates(provider, { preferredProfileId = null, excludeIds = new Set() } = {}) {
|
|
745
|
+
const nowMs = clock();
|
|
746
|
+
const defId = memState.defaults[provider] || null;
|
|
747
|
+
const all = Object.values(memState.profiles).filter((p) => p.provider === provider && !p.disabled && !excludeIds.has(p.id));
|
|
748
|
+
const score = (p) => {
|
|
749
|
+
let s = Number(p.priority ?? 100);
|
|
750
|
+
if (preferredProfileId && p.id === preferredProfileId) s -= 10000;
|
|
751
|
+
else if (defId && p.id === defId) s -= 1000;
|
|
752
|
+
return s;
|
|
753
|
+
};
|
|
754
|
+
const ready = all.filter((p) => !p.cooldownUntil || Date.parse(p.cooldownUntil) <= nowMs).sort((a, b) => score(a) - score(b));
|
|
755
|
+
if (ready.length) return { ready, fallbackCooling: [] };
|
|
756
|
+
const cooling = all.sort((a, b) => (Date.parse(a.cooldownUntil || 0) - Date.parse(b.cooldownUntil || 0)) || (score(a) - score(b)));
|
|
757
|
+
return { ready: [], fallbackCooling: cooling };
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
async function acquireCredential(provider, { preferredProfileId = null, excludeIds = new Set(), skewMs = 120_000, allowCoolingFallback = false } = {}) {
|
|
761
|
+
const { ready, fallbackCooling } = rankCandidates(provider, { preferredProfileId, excludeIds });
|
|
762
|
+
const candidates = ready.length ? ready : (allowCoolingFallback ? fallbackCooling : []);
|
|
763
|
+
if (!candidates.length) {
|
|
764
|
+
const err = new Error(fallbackCooling.length
|
|
765
|
+
? `auth_all_profiles_in_cooldown:${provider}`
|
|
766
|
+
: `auth_no_profile:${provider}`);
|
|
767
|
+
err.code = fallbackCooling.length ? 'ALL_IN_COOLDOWN' : 'NO_PROFILE';
|
|
768
|
+
err.nextAvailableAt = fallbackCooling[0]?.cooldownUntil || null;
|
|
769
|
+
throw err;
|
|
770
|
+
}
|
|
771
|
+
let lastErr = null;
|
|
772
|
+
for (const candidate of candidates) {
|
|
773
|
+
try {
|
|
774
|
+
if (candidate.type === 'oauth') {
|
|
775
|
+
await refreshTokenIfNeeded(candidate.id, { skewMs });
|
|
776
|
+
}
|
|
777
|
+
const live = memState.profiles[candidate.id];
|
|
778
|
+
const token = live.type === 'oauth' ? live.accessToken : (live.apiKey || live.accessToken || null);
|
|
779
|
+
const headers = { ...(live.extraHeaders || {}) };
|
|
780
|
+
if (token && !headers.Authorization && live.type !== 'codex_app_server') {
|
|
781
|
+
headers.Authorization = `${live.tokenType || 'Bearer'} ${token}`;
|
|
782
|
+
}
|
|
783
|
+
return {
|
|
784
|
+
profileId: live.id,
|
|
785
|
+
provider: live.provider,
|
|
786
|
+
type: live.type,
|
|
787
|
+
label: live.label || live.id,
|
|
788
|
+
token,
|
|
789
|
+
baseUrl: live.baseUrl || null,
|
|
790
|
+
headers,
|
|
791
|
+
expiresAt: live.expiresAt || null,
|
|
792
|
+
};
|
|
793
|
+
} catch (e) {
|
|
794
|
+
lastErr = e;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
throw lastErr || new Error(`auth_acquire_failed:${provider}`);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
async function withFailover(provider, fn, { preferredProfileId = null, maxAttempts = 4 } = {}) {
|
|
801
|
+
const tried = new Set();
|
|
802
|
+
let lastErr = null;
|
|
803
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
804
|
+
let cred;
|
|
805
|
+
try {
|
|
806
|
+
cred = await acquireCredential(provider, {
|
|
807
|
+
preferredProfileId: attempt === 0 ? preferredProfileId : null,
|
|
808
|
+
excludeIds: tried,
|
|
809
|
+
});
|
|
810
|
+
} catch (e) {
|
|
811
|
+
throw lastErr || e;
|
|
812
|
+
}
|
|
813
|
+
tried.add(cred.profileId);
|
|
814
|
+
try {
|
|
815
|
+
const result = await fn(cred);
|
|
816
|
+
reportSuccess(cred.profileId);
|
|
817
|
+
return { result, profileId: cred.profileId, attempts: attempt + 1 };
|
|
818
|
+
} catch (err) {
|
|
819
|
+
lastErr = err;
|
|
820
|
+
if (isRateLimitError(err)) {
|
|
821
|
+
reportRateLimit(cred.profileId, { retryAfterMs: err.retryAfterMs ?? null, error: err.message });
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
if (isAuthError(err)) {
|
|
825
|
+
reportAuthFailure(cred.profileId, { error: err.message, permanent: err.oauthError === 'invalid_grant' });
|
|
826
|
+
continue;
|
|
827
|
+
}
|
|
828
|
+
throw err;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
throw lastErr || new Error(`auth_failover_exhausted:${provider}`);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
return {
|
|
835
|
+
filePath: absPath,
|
|
836
|
+
reload,
|
|
837
|
+
listProfiles,
|
|
838
|
+
getProfile,
|
|
839
|
+
upsertProfile,
|
|
840
|
+
removeProfile,
|
|
841
|
+
setDefault,
|
|
842
|
+
refreshTokenIfNeeded,
|
|
843
|
+
acquireCredential,
|
|
844
|
+
reportRateLimit,
|
|
845
|
+
reportAuthFailure,
|
|
846
|
+
reportSuccess,
|
|
847
|
+
withFailover,
|
|
848
|
+
};
|
|
849
|
+
}
|