@oracle-agent/oracle 0.9.7 → 0.10.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,672 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import readline from "node:readline/promises";
6
+ import { spawn, spawnSync } from "node:child_process";
7
+
8
+ import { ensureDir, oracleConfigDir } from "../cli/paths.mjs";
9
+
10
+ const PROVIDERS = Object.freeze({
11
+ "anthropic-oauth": {
12
+ aliases: ["anthropic-oauth", "anthropic", "claude", "claude-oauth"],
13
+ clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
14
+ authorizeUrl: "https://claude.ai/oauth/authorize",
15
+ tokenUrl: "https://platform.claude.com/v1/oauth/token",
16
+ redirectUri: "https://console.anthropic.com/oauth/code/callback",
17
+ scope: "org:create_api_key user:profile user:inference",
18
+ baseUrl: "https://api.anthropic.com/v1",
19
+ model: "claude-sonnet-4-6",
20
+ protocol: "anthropic-messages",
21
+ },
22
+ "openai-codex": {
23
+ aliases: ["openai-codex", "openai-oauth", "codex", "codex-oauth"],
24
+ clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
25
+ issuer: "https://auth.openai.com",
26
+ tokenUrl: "https://auth.openai.com/oauth/token",
27
+ baseUrl: "https://chatgpt.com/backend-api/codex",
28
+ model: "gpt-5.6-sol",
29
+ protocol: "responses",
30
+ },
31
+ "xai-oauth": {
32
+ aliases: ["xai-oauth", "xai", "grok", "grok-oauth"],
33
+ clientId: "b1a00492-073a-47ea-816f-4c329264a828",
34
+ issuer: "https://auth.x.ai",
35
+ discoveryUrl: "https://auth.x.ai/.well-known/openid-configuration",
36
+ deviceUrl: "https://auth.x.ai/oauth2/device/code",
37
+ scope: "openid profile email offline_access grok-cli:access api:access",
38
+ baseUrl: "https://api.x.ai/v1",
39
+ model: "grok-4.5",
40
+ protocol: "responses",
41
+ },
42
+ });
43
+
44
+ const REFRESH_SKEW_MS = 120_000;
45
+
46
+ function nowMs(options = {}) {
47
+ return typeof options.now === "function" ? Number(options.now()) : Date.now();
48
+ }
49
+
50
+ function providerConfig(value) {
51
+ return PROVIDERS[oauthProviderId(value)];
52
+ }
53
+
54
+ export function oauthProviderId(value) {
55
+ const needle = String(value || "").trim().toLowerCase();
56
+ for (const [id, config] of Object.entries(PROVIDERS)) {
57
+ if (config.aliases.includes(needle)) return id;
58
+ }
59
+ throw new Error(`unsupported OAuth provider: ${value || "(empty)"}`);
60
+ }
61
+
62
+ export function oauthProviderConfig(value) {
63
+ const id = oauthProviderId(value);
64
+ return { id, ...PROVIDERS[id] };
65
+ }
66
+
67
+ function readJson(file, fallback = {}) {
68
+ if (!fs.existsSync(file)) return fallback;
69
+ try {
70
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
71
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("invalid object");
72
+ return parsed;
73
+ } catch {
74
+ throw new Error(`credential store is unreadable or corrupt: ${path.basename(file)}`);
75
+ }
76
+ }
77
+
78
+ function ensurePrivateDir(dir) {
79
+ ensureDir(dir);
80
+ if (process.platform !== "win32") fs.chmodSync(dir, 0o700);
81
+ }
82
+
83
+ function atomicJsonWrite(file, value) {
84
+ ensurePrivateDir(path.dirname(file));
85
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
86
+ fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
87
+ fs.renameSync(temp, file);
88
+ if (process.platform !== "win32") fs.chmodSync(file, 0o600);
89
+ }
90
+
91
+ function linuxSecretToolAvailable(spawnFn) {
92
+ if (process.platform !== "linux") return false;
93
+ const result = spawnFn("secret-tool", ["--version"], {
94
+ encoding: "utf8",
95
+ stdio: ["ignore", "pipe", "ignore"],
96
+ });
97
+ return !result.error && result.status === 0;
98
+ }
99
+
100
+ function normalizeApiKeyProvider(value) {
101
+ const provider = String(value || "").trim().toLowerCase();
102
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(provider)) throw new Error(`invalid API-key provider: ${value || "(empty)"}`);
103
+ return provider;
104
+ }
105
+
106
+ function normalizeCredential(credential = {}) {
107
+ const accessToken = String(credential.accessToken || credential.access_token || "").trim();
108
+ const refreshToken = String(credential.refreshToken || credential.refresh_token || "").trim();
109
+ const expiresAt = Number(credential.expiresAt || credential.expires_at || 0);
110
+ if (!accessToken) throw new Error("OAuth credential is missing access token");
111
+ return {
112
+ accessToken,
113
+ refreshToken,
114
+ expiresAt: Number.isFinite(expiresAt) ? expiresAt : 0,
115
+ tokenType: String(credential.tokenType || credential.token_type || "Bearer"),
116
+ source: String(credential.source || "oracle"),
117
+ ...(credential.discovery ? { discovery: credential.discovery } : {}),
118
+ ...(credential.scope ? { scope: credential.scope } : {}),
119
+ ...(credential.idToken || credential.id_token ? { idToken: String(credential.idToken || credential.id_token) } : {}),
120
+ };
121
+ }
122
+
123
+ export function createOAuthStore(options = {}) {
124
+ const file = options.file || path.join(oracleConfigDir(), "oauth.json");
125
+ const metadataFile = options.metadataFile || path.join(path.dirname(file), "oauth-meta.json");
126
+ const spawnFn = options.spawnFn || spawnSync;
127
+ const useSecretTool = options.keychain !== false &&
128
+ process.env.ORACLE_AUTH_FILE_STORE !== "1" &&
129
+ linuxSecretToolAvailable(spawnFn);
130
+ const storage = useSecretTool ? "linux-secret-service" : "private-file";
131
+ const lockFile = `${file}.lock`;
132
+
133
+ async function withLock(fn) {
134
+ ensurePrivateDir(path.dirname(lockFile));
135
+ let descriptor;
136
+ for (let attempt = 0; attempt < 400; attempt += 1) {
137
+ try {
138
+ descriptor = fs.openSync(lockFile, "wx", 0o600);
139
+ break;
140
+ } catch (error) {
141
+ if (error?.code !== "EEXIST") throw error;
142
+ try {
143
+ if (Date.now() - fs.statSync(lockFile).mtimeMs > 300_000) fs.unlinkSync(lockFile);
144
+ } catch {}
145
+ await new Promise((resolve) => setTimeout(resolve, 25));
146
+ }
147
+ }
148
+ if (descriptor === undefined) throw new Error("timed out waiting for OAuth credential lock");
149
+ try {
150
+ return await fn();
151
+ } finally {
152
+ try { fs.closeSync(descriptor); } catch {}
153
+ try { fs.unlinkSync(lockFile); } catch {}
154
+ }
155
+ }
156
+
157
+ function secretArgs(provider, kind = "oauth") {
158
+ return ["application", "oracle", "kind", kind, "provider", provider];
159
+ }
160
+
161
+ function get(providerValue) {
162
+ const provider = oauthProviderId(providerValue);
163
+ if (useSecretTool) {
164
+ const result = spawnFn("secret-tool", ["lookup", ...secretArgs(provider)], {
165
+ encoding: "utf8",
166
+ stdio: ["ignore", "pipe", "ignore"],
167
+ });
168
+ if (result.error || result.status !== 0 || !String(result.stdout || "").trim()) return null;
169
+ try {
170
+ return normalizeCredential(JSON.parse(String(result.stdout).trim()));
171
+ } catch {
172
+ return null;
173
+ }
174
+ }
175
+ const state = readJson(file, { providers: {} });
176
+ const value = state.providers?.[provider];
177
+ if (!value) return null;
178
+ try {
179
+ return normalizeCredential(value);
180
+ } catch {
181
+ return null;
182
+ }
183
+ }
184
+
185
+ function set(providerValue, credential) {
186
+ const provider = oauthProviderId(providerValue);
187
+ const normalized = normalizeCredential(credential);
188
+ if (useSecretTool) {
189
+ const result = spawnFn("secret-tool", ["store", `--label=Oracle ${provider} OAuth`, ...secretArgs(provider)], {
190
+ input: JSON.stringify(normalized),
191
+ encoding: "utf8",
192
+ stdio: ["pipe", "ignore", "pipe"],
193
+ });
194
+ if (result.error || result.status !== 0) throw new Error("OS credential store rejected OAuth credential");
195
+ const metadata = readJson(metadataFile, { providers: {} });
196
+ metadata.providers ||= {};
197
+ metadata.providers[provider] = {
198
+ expiresAt: normalized.expiresAt,
199
+ source: normalized.source,
200
+ };
201
+ atomicJsonWrite(metadataFile, metadata);
202
+ return normalized;
203
+ }
204
+ const state = readJson(file, { providers: {} });
205
+ state.providers ||= {};
206
+ state.providers[provider] = normalized;
207
+ atomicJsonWrite(file, state);
208
+ return normalized;
209
+ }
210
+
211
+ function remove(providerValue) {
212
+ const provider = oauthProviderId(providerValue);
213
+ if (useSecretTool) {
214
+ const result = spawnFn("secret-tool", ["clear", ...secretArgs(provider)], {
215
+ encoding: "utf8",
216
+ stdio: ["ignore", "ignore", "pipe"],
217
+ });
218
+ const metadata = readJson(metadataFile, { providers: {} });
219
+ if (metadata.providers) delete metadata.providers[provider];
220
+ atomicJsonWrite(metadataFile, metadata);
221
+ return !result.error && result.status === 0;
222
+ }
223
+ const state = readJson(file, { providers: {} });
224
+ const existed = Boolean(state.providers?.[provider]);
225
+ if (state.providers) delete state.providers[provider];
226
+ atomicJsonWrite(file, state);
227
+ return existed;
228
+ }
229
+
230
+ function getApiKey(providerValue) {
231
+ const provider = normalizeApiKeyProvider(providerValue);
232
+ if (useSecretTool) {
233
+ const result = spawnFn("secret-tool", ["lookup", ...secretArgs(provider, "api-key")], {
234
+ encoding: "utf8",
235
+ stdio: ["ignore", "pipe", "ignore"],
236
+ });
237
+ return result.error || result.status !== 0 ? "" : String(result.stdout || "").trim();
238
+ }
239
+ return String(readJson(file, { apiKeys: {} }).apiKeys?.[provider] || "").trim();
240
+ }
241
+
242
+ function setApiKey(providerValue, apiKeyValue) {
243
+ const provider = normalizeApiKeyProvider(providerValue);
244
+ const apiKey = String(apiKeyValue || "").trim();
245
+ if (!apiKey) throw new Error("API key is empty");
246
+ if (useSecretTool) {
247
+ const result = spawnFn("secret-tool", ["store", `--label=Oracle ${provider} API key`, ...secretArgs(provider, "api-key")], {
248
+ input: apiKey,
249
+ encoding: "utf8",
250
+ stdio: ["pipe", "ignore", "pipe"],
251
+ });
252
+ if (result.error || result.status !== 0) throw new Error("OS credential store rejected API key");
253
+ const metadata = readJson(metadataFile, { providers: {}, apiKeys: {} });
254
+ metadata.apiKeys ||= {};
255
+ metadata.apiKeys[provider] = { configured: true };
256
+ atomicJsonWrite(metadataFile, metadata);
257
+ return true;
258
+ }
259
+ const state = readJson(file, { providers: {}, apiKeys: {} });
260
+ state.apiKeys ||= {};
261
+ state.apiKeys[provider] = apiKey;
262
+ atomicJsonWrite(file, state);
263
+ return true;
264
+ }
265
+
266
+ function removeApiKey(providerValue) {
267
+ const provider = normalizeApiKeyProvider(providerValue);
268
+ if (useSecretTool) {
269
+ const result = spawnFn("secret-tool", ["clear", ...secretArgs(provider, "api-key")], {
270
+ encoding: "utf8",
271
+ stdio: ["ignore", "ignore", "pipe"],
272
+ });
273
+ const metadata = readJson(metadataFile, { providers: {}, apiKeys: {} });
274
+ if (metadata.apiKeys) delete metadata.apiKeys[provider];
275
+ atomicJsonWrite(metadataFile, metadata);
276
+ return !result.error && result.status === 0;
277
+ }
278
+ const state = readJson(file, { providers: {}, apiKeys: {} });
279
+ const existed = Boolean(state.apiKeys?.[provider]);
280
+ if (state.apiKeys) delete state.apiKeys[provider];
281
+ atomicJsonWrite(file, state);
282
+ return existed;
283
+ }
284
+
285
+ function status() {
286
+ const providers = {};
287
+ const apiKeys = {};
288
+ if (useSecretTool) {
289
+ const metadata = readJson(metadataFile, { providers: {}, apiKeys: {} });
290
+ for (const [provider, value] of Object.entries(metadata.providers || {})) {
291
+ providers[provider] = {
292
+ loggedIn: Boolean(get(provider)),
293
+ expiresAt: Number(value.expiresAt || 0),
294
+ source: String(value.source || "oracle"),
295
+ storage,
296
+ };
297
+ }
298
+ for (const provider of Object.keys(metadata.apiKeys || {})) {
299
+ apiKeys[provider] = { configured: Boolean(getApiKey(provider)), storage };
300
+ }
301
+ } else {
302
+ const state = readJson(file, { providers: {}, apiKeys: {} });
303
+ for (const [provider, value] of Object.entries(state.providers || {})) {
304
+ providers[provider] = {
305
+ loggedIn: Boolean(value?.accessToken),
306
+ expiresAt: Number(value?.expiresAt || 0),
307
+ source: String(value?.source || "oracle"),
308
+ storage,
309
+ };
310
+ }
311
+ for (const [provider, value] of Object.entries(state.apiKeys || {})) {
312
+ apiKeys[provider] = { configured: Boolean(value), storage };
313
+ }
314
+ }
315
+ return { storage, providers, apiKeys };
316
+ }
317
+
318
+ return Object.freeze({
319
+ file,
320
+ storage,
321
+ get,
322
+ set,
323
+ remove,
324
+ getApiKey,
325
+ setApiKey,
326
+ removeApiKey,
327
+ status,
328
+ withLock,
329
+ });
330
+ }
331
+
332
+ let defaultStore;
333
+ export function getOAuthStore() {
334
+ defaultStore ||= createOAuthStore();
335
+ return defaultStore;
336
+ }
337
+
338
+ function base64url(input) {
339
+ return Buffer.from(input).toString("base64url");
340
+ }
341
+
342
+ function generatePkce() {
343
+ const verifier = base64url(randomBytes(32));
344
+ return {
345
+ verifier,
346
+ challenge: base64url(createHash("sha256").update(verifier).digest()),
347
+ state: base64url(randomBytes(24)),
348
+ };
349
+ }
350
+
351
+ function sameState(left, right) {
352
+ const a = Buffer.from(String(left || ""));
353
+ const b = Buffer.from(String(right || ""));
354
+ return a.length === b.length && timingSafeEqual(a, b);
355
+ }
356
+
357
+ function openBrowser(url) {
358
+ const target = String(url);
359
+ const spec = process.platform === "darwin"
360
+ ? ["open", [target]]
361
+ : process.platform === "win32"
362
+ ? ["cmd.exe", ["/d", "/s", "/c", "start", "", target]]
363
+ : ["xdg-open", [target]];
364
+ try {
365
+ const child = spawn(spec[0], spec[1], { detached: true, stdio: "ignore" });
366
+ child.unref();
367
+ return true;
368
+ } catch {
369
+ return false;
370
+ }
371
+ }
372
+
373
+ function formBody(value) {
374
+ return new URLSearchParams(value).toString();
375
+ }
376
+
377
+ async function responseJson(response, label) {
378
+ if (!response?.ok) {
379
+ let code = "";
380
+ try {
381
+ code = String((await response.json())?.error || "");
382
+ } catch {}
383
+ throw new Error(`${label} failed (HTTP ${response?.status || "unknown"}${code ? `, ${code}` : ""})`);
384
+ }
385
+ const payload = await response.json();
386
+ if (!payload || typeof payload !== "object") throw new Error(`${label} returned invalid JSON`);
387
+ return payload;
388
+ }
389
+
390
+ async function readAuthorizationCode(inputFn) {
391
+ if (inputFn) return String(await inputFn()).trim();
392
+ const io = readline.createInterface({ input: process.stdin, output: process.stdout });
393
+ try {
394
+ return String(await io.question("Authorization code: ")).trim();
395
+ } finally {
396
+ io.close();
397
+ }
398
+ }
399
+
400
+ function credentialFromTokenPayload(payload, options = {}) {
401
+ const accessToken = String(payload.access_token || "").trim();
402
+ const refreshToken = String(payload.refresh_token || options.refreshToken || "").trim();
403
+ if (!accessToken) throw new Error("OAuth token response is missing access token");
404
+ const ttlSeconds = Number(payload.expires_in || 3600);
405
+ return normalizeCredential({
406
+ accessToken,
407
+ refreshToken,
408
+ expiresAt: nowMs(options) + Math.max(1, ttlSeconds) * 1000,
409
+ tokenType: payload.token_type || "Bearer",
410
+ idToken: payload.id_token,
411
+ source: "oracle",
412
+ ...(options.discovery ? { discovery: options.discovery } : {}),
413
+ ...(payload.scope ? { scope: payload.scope } : {}),
414
+ });
415
+ }
416
+
417
+ async function loginClaude(options) {
418
+ const config = PROVIDERS["anthropic-oauth"];
419
+ const pkce = options.pkce || generatePkce();
420
+ const params = new URLSearchParams({
421
+ code: "true",
422
+ client_id: config.clientId,
423
+ response_type: "code",
424
+ redirect_uri: config.redirectUri,
425
+ scope: config.scope,
426
+ code_challenge: pkce.challenge,
427
+ code_challenge_method: "S256",
428
+ state: pkce.state,
429
+ });
430
+ const authorizeUrl = `${config.authorizeUrl}?${params}`;
431
+ options.output(`Open: ${authorizeUrl}`);
432
+ options.openFn(authorizeUrl);
433
+ const returned = await readAuthorizationCode(options.inputFn);
434
+ const [code, state] = returned.split("#", 2);
435
+ if (!code || !sameState(state, pkce.state)) throw new Error("Claude OAuth state mismatch");
436
+ const response = await options.fetchFn(config.tokenUrl, {
437
+ method: "POST",
438
+ headers: {
439
+ "content-type": "application/json",
440
+ "user-agent": "axios/1.7.9",
441
+ },
442
+ body: JSON.stringify({
443
+ grant_type: "authorization_code",
444
+ client_id: config.clientId,
445
+ code,
446
+ state,
447
+ redirect_uri: config.redirectUri,
448
+ code_verifier: pkce.verifier,
449
+ }),
450
+ });
451
+ return credentialFromTokenPayload(await responseJson(response, "Claude OAuth token exchange"), options);
452
+ }
453
+
454
+ async function loginCodex(options) {
455
+ const config = PROVIDERS["openai-codex"];
456
+ const device = await responseJson(await options.fetchFn(`${config.issuer}/api/accounts/deviceauth/usercode`, {
457
+ method: "POST",
458
+ headers: { "content-type": "application/json" },
459
+ body: JSON.stringify({ client_id: config.clientId }),
460
+ }), "Codex device authorization");
461
+ if (!device.user_code || !device.device_auth_id) throw new Error("Codex device authorization returned incomplete data");
462
+ const verifyUrl = `${config.issuer}/codex/device`;
463
+ options.output(`Open: ${verifyUrl}`);
464
+ options.output(`Code: ${device.user_code}`);
465
+ options.openFn(verifyUrl);
466
+ const interval = Math.max(3, Number(device.interval || 5));
467
+ let authorization;
468
+ for (let attempt = 0; attempt < Math.ceil(900 / interval); attempt += 1) {
469
+ await options.sleepFn(interval * 1000);
470
+ const response = await options.fetchFn(`${config.issuer}/api/accounts/deviceauth/token`, {
471
+ method: "POST",
472
+ headers: { "content-type": "application/json" },
473
+ body: JSON.stringify({ device_auth_id: device.device_auth_id, user_code: device.user_code }),
474
+ });
475
+ if (response.ok) {
476
+ authorization = await responseJson(response, "Codex device authorization");
477
+ break;
478
+ }
479
+ if (![403, 404].includes(response.status)) throw new Error(`Codex device authorization failed (HTTP ${response.status})`);
480
+ }
481
+ if (!authorization) throw new Error("Codex device authorization timed out");
482
+ const response = await options.fetchFn(config.tokenUrl, {
483
+ method: "POST",
484
+ headers: { "content-type": "application/x-www-form-urlencoded" },
485
+ body: formBody({
486
+ grant_type: "authorization_code",
487
+ code: authorization.authorization_code,
488
+ redirect_uri: `${config.issuer}/deviceauth/callback`,
489
+ client_id: config.clientId,
490
+ code_verifier: authorization.code_verifier,
491
+ }),
492
+ });
493
+ return credentialFromTokenPayload(await responseJson(response, "Codex OAuth token exchange"), options);
494
+ }
495
+
496
+ function validateXaiUrl(value) {
497
+ const url = new URL(String(value));
498
+ const host = url.hostname.toLowerCase();
499
+ if (url.protocol !== "https:" || (host !== "x.ai" && !host.endsWith(".x.ai"))) {
500
+ throw new Error("xAI OAuth discovery returned an untrusted endpoint");
501
+ }
502
+ return url.toString();
503
+ }
504
+
505
+ async function loginGrok(options) {
506
+ const config = PROVIDERS["xai-oauth"];
507
+ const discovery = await responseJson(await options.fetchFn(config.discoveryUrl, {
508
+ headers: { accept: "application/json" },
509
+ }), "xAI OAuth discovery");
510
+ validateXaiUrl(discovery.authorization_endpoint);
511
+ const tokenEndpoint = validateXaiUrl(discovery.token_endpoint);
512
+ const device = await responseJson(await options.fetchFn(config.deviceUrl, {
513
+ method: "POST",
514
+ headers: {
515
+ "content-type": "application/x-www-form-urlencoded",
516
+ accept: "application/json",
517
+ },
518
+ body: formBody({ client_id: config.clientId, scope: config.scope }),
519
+ }), "xAI device authorization");
520
+ if (!device.device_code || !device.user_code || !device.verification_uri) {
521
+ throw new Error("xAI device authorization returned incomplete data");
522
+ }
523
+ const verifyUrl = validateXaiUrl(device.verification_uri_complete || device.verification_uri);
524
+ options.output(`Open: ${verifyUrl}`);
525
+ options.output(`Code: ${device.user_code}`);
526
+ options.openFn(verifyUrl);
527
+ const interval = Math.max(1, Number(device.interval || 5));
528
+ const attempts = Math.ceil(Math.max(1, Number(device.expires_in || 600)) / interval);
529
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
530
+ const response = await options.fetchFn(tokenEndpoint, {
531
+ method: "POST",
532
+ headers: {
533
+ "content-type": "application/x-www-form-urlencoded",
534
+ accept: "application/json",
535
+ },
536
+ body: formBody({
537
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
538
+ client_id: config.clientId,
539
+ device_code: device.device_code,
540
+ }),
541
+ });
542
+ if (response.ok) {
543
+ const payload = await responseJson(response, "xAI OAuth token exchange");
544
+ return credentialFromTokenPayload(payload, {
545
+ ...options,
546
+ discovery: {
547
+ authorization_endpoint: validateXaiUrl(discovery.authorization_endpoint),
548
+ token_endpoint: tokenEndpoint,
549
+ },
550
+ });
551
+ }
552
+ let code = "";
553
+ try {
554
+ code = String((await response.json())?.error || "");
555
+ } catch {}
556
+ if (code === "slow_down") await options.sleepFn((interval + 1) * 1000);
557
+ else if (code === "authorization_pending") await options.sleepFn(interval * 1000);
558
+ else throw new Error(`xAI OAuth token exchange failed (HTTP ${response.status}${code ? `, ${code}` : ""})`);
559
+ }
560
+ throw new Error("xAI device authorization timed out");
561
+ }
562
+
563
+ export async function loginOAuth(providerValue, options = {}) {
564
+ const provider = oauthProviderId(providerValue);
565
+ const normalized = {
566
+ fetchFn: options.fetchFn || globalThis.fetch,
567
+ inputFn: options.inputFn,
568
+ sleepFn: options.sleepFn || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
569
+ openFn: options.openFn || openBrowser,
570
+ output: options.output || ((line) => process.stdout.write(`${line}\n`)),
571
+ now: options.now,
572
+ pkce: options.pkce,
573
+ };
574
+ if (provider === "anthropic-oauth") return loginClaude(normalized);
575
+ if (provider === "openai-codex") return loginCodex(normalized);
576
+ return loginGrok(normalized);
577
+ }
578
+
579
+ export async function refreshOAuthCredentials(providerValue, credential, options = {}) {
580
+ const provider = oauthProviderId(providerValue);
581
+ const config = PROVIDERS[provider];
582
+ const current = normalizeCredential(credential);
583
+ if (!current.refreshToken) throw new Error(`${provider} OAuth credential cannot refresh; run oracle auth login`);
584
+ let discovery = current.discovery;
585
+ let endpoint;
586
+ const fetchFn = options.fetchFn || globalThis.fetch;
587
+ if (provider === "xai-oauth") {
588
+ if (!discovery?.token_endpoint) {
589
+ const discoveryResponse = await fetchFn(config.discoveryUrl);
590
+ const discovered = await responseJson(discoveryResponse, "xAI OAuth discovery");
591
+ discovery = {
592
+ ...(discovered.authorization_endpoint
593
+ ? { authorization_endpoint: validateXaiUrl(discovered.authorization_endpoint) }
594
+ : {}),
595
+ token_endpoint: validateXaiUrl(discovered.token_endpoint),
596
+ };
597
+ }
598
+ endpoint = validateXaiUrl(discovery.token_endpoint);
599
+ } else {
600
+ endpoint = config.tokenUrl;
601
+ }
602
+ const response = await fetchFn(endpoint, {
603
+ method: "POST",
604
+ headers: {
605
+ "content-type": "application/x-www-form-urlencoded",
606
+ accept: "application/json",
607
+ ...(provider === "anthropic-oauth" ? { "user-agent": "axios/1.7.9" } : {}),
608
+ },
609
+ body: formBody({
610
+ grant_type: "refresh_token",
611
+ refresh_token: current.refreshToken,
612
+ client_id: config.clientId,
613
+ }),
614
+ });
615
+ const payload = await responseJson(response, `${provider} OAuth refresh`);
616
+ return credentialFromTokenPayload(payload, {
617
+ ...options,
618
+ refreshToken: current.refreshToken,
619
+ discovery,
620
+ });
621
+ }
622
+
623
+ export async function resolveOAuthCredentials(providerValue, options = {}) {
624
+ const provider = oauthProviderId(providerValue);
625
+ const store = options.store || getOAuthStore();
626
+ const credential = store.get(provider);
627
+ if (!credential) throw new Error(`${provider} OAuth is not logged in; run oracle auth login ${providerValue}`);
628
+ const now = nowMs(options);
629
+ if (!credential.expiresAt || credential.expiresAt > now + REFRESH_SKEW_MS) return credential;
630
+ const refresh = async () => {
631
+ const current = store.get(provider);
632
+ if (!current) throw new Error(`${provider} OAuth is not logged in; run oracle auth login ${providerValue}`);
633
+ const checkedAt = nowMs(options);
634
+ if (!current.expiresAt || current.expiresAt > checkedAt + REFRESH_SKEW_MS) return current;
635
+ const refreshed = await refreshOAuthCredentials(provider, current, options);
636
+ store.set(provider, refreshed);
637
+ return refreshed;
638
+ };
639
+ return typeof store.withLock === "function" ? store.withLock(refresh) : refresh();
640
+ }
641
+
642
+ export function hasOAuthCredentials(providerValue, options = {}) {
643
+ try {
644
+ return Boolean((options.store || getOAuthStore()).get(providerValue)?.accessToken);
645
+ } catch {
646
+ return false;
647
+ }
648
+ }
649
+
650
+ export function oauthRuntimeConfig(providerValue) {
651
+ const config = oauthProviderConfig(providerValue);
652
+ return {
653
+ kind: "standalone",
654
+ provider: config.id,
655
+ model: config.model,
656
+ baseUrl: config.baseUrl,
657
+ authType: "oauth",
658
+ protocol: config.protocol,
659
+ };
660
+ }
661
+
662
+ export default {
663
+ createOAuthStore,
664
+ getOAuthStore,
665
+ hasOAuthCredentials,
666
+ loginOAuth,
667
+ oauthProviderConfig,
668
+ oauthProviderId,
669
+ oauthRuntimeConfig,
670
+ refreshOAuthCredentials,
671
+ resolveOAuthCredentials,
672
+ };