@lks347/dsh-oauth 0.0.0-stage → 1.0.1
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/README.en.md +155 -0
- package/README.md +100 -2
- package/app.js +1005 -0
- package/auth.html +80 -0
- package/client.js +31 -0
- package/cordis.patch.yml +4 -0
- package/docs/CONNECTIONS.md +77 -0
- package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
- package/docs/RELEASE-1.0.1.md +38 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/index.html +43 -0
- package/package.json +64 -4
- package/providers.js +73 -0
- package/scripts/check-upstreams.mjs +27 -0
- package/scripts/link-peers.js +38 -0
- package/scripts/verify-browser.mjs +297 -0
- package/scripts/verify-host.mjs +484 -0
- package/scripts/verify-live.mjs +268 -0
- package/scripts/verify-package.mjs +168 -0
- package/scripts/verify-persistence.mjs +307 -0
- package/scripts/verify-subscriptions-ui.mjs +304 -0
- package/src/account.js +85 -0
- package/src/account.test.js +52 -0
- package/src/authorization.js +199 -0
- package/src/authorization.test.js +332 -0
- package/src/catalog.js +177 -0
- package/src/catalog.test.js +146 -0
- package/src/chat-recovery.js +110 -0
- package/src/chat-recovery.test.js +261 -0
- package/src/connection-runtime.js +126 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +103 -0
- package/src/grants.test.js +327 -0
- package/src/index.js +704 -0
- package/src/local-imports.js +145 -0
- package/src/local-imports.test.js +168 -0
- package/src/media.js +149 -0
- package/src/models.js +546 -0
- package/src/models.test.js +415 -0
- package/src/profile-store.js +51 -0
- package/src/pulls.js +100 -0
- package/src/pulls.test.js +156 -0
- package/src/qwen.js +141 -0
- package/src/qwen.test.js +35 -0
- package/src/request-errors.js +50 -0
- package/src/request-errors.test.js +131 -0
- package/src/routes.js +47 -0
- package/src/routes.test.js +136 -0
- package/src/subscription-models.test.js +139 -0
- package/src/usage/aggregators.js +292 -0
- package/src/usage/aggregators.test.js +316 -0
- package/src/usage/core.js +68 -0
- package/src/usage/index.js +93 -0
- package/src/usage/official.js +339 -0
- package/src/usage/official.test.js +273 -0
- package/src/usage/service.test.js +89 -0
- package/src/xai-browser.js +272 -0
- package/src/xai-browser.test.js +256 -0
- package/src/xai-login.js +121 -0
- package/src/xai-login.test.js +259 -0
- package/styles.css +364 -0
- package/theme.js +118 -0
- package/upstreams.json +10 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { createUsageService, fetchUsage } from './index.js';
|
|
7
|
+
import { finite, iso, quotaWindow, balance, UsageError, createUsageRequest } from './core.js';
|
|
8
|
+
|
|
9
|
+
async function setup(t) {
|
|
10
|
+
const directory = await mkdtemp(join(tmpdir(), 'dsh-usage-test-'));
|
|
11
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
12
|
+
return directory;
|
|
13
|
+
}
|
|
14
|
+
const context = () => ({ access: 'test-secret', rawGrant: { access: 'test-secret' }, connection: { revision: 'one' } });
|
|
15
|
+
const sample = { windows: [{ id: 'daily', unit: 'requests', used: 5, limit: 10, remaining: 5 }], balances: [] };
|
|
16
|
+
|
|
17
|
+
test('unknown, zero, negative balance and explicit timestamp units remain distinct', () => {
|
|
18
|
+
assert.equal(finite(null), undefined); assert.equal(finite(false), undefined); assert.equal(finite(''), undefined);
|
|
19
|
+
assert.equal(finite('0'), 0); assert.equal(iso(1700000000, 'seconds'), '2023-11-14T22:13:20.000Z');
|
|
20
|
+
assert.equal(iso('invalid'), undefined); assert.equal(balance({ amount: '-1.25', unit: 'money' }).amount, '-1.25');
|
|
21
|
+
assert.deepEqual(quotaWindow({ used: 15, limit: 10 }), { used: 15, limit: 10, remaining: -5, usedPercent: 150, remainingPercent: -50 });
|
|
22
|
+
assert.deepEqual(quotaWindow({ used: 0, limit: 0 }), { used: 0, limit: 0, remaining: 0 });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test('transport blocks redirects/unapproved hosts and redacts provider error text', async () => {
|
|
26
|
+
let options;
|
|
27
|
+
const request = createUsageRequest({ allowedHosts: ['api.example.test'], fetchImpl: async (_url, init) => { options = init; return new Response('test-secret', { status: 403 }); } });
|
|
28
|
+
await assert.rejects(request('https://evil.test'), { code: 'needs-configuration' });
|
|
29
|
+
await assert.rejects(request('https://api.example.test/usage'), error => error.code === 'needs-permission' && !error.message.includes('test-secret'));
|
|
30
|
+
assert.equal(options.redirect, 'error');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('persistent quota cache retains source timestamp, coalesces calls and contains no credential', async t => {
|
|
34
|
+
const directory = await setup(t); let clock = 1700000000000; let calls = 0;
|
|
35
|
+
const options = { directory, contextFor: context, now: () => clock, reader: async () => { calls++; return sample; } };
|
|
36
|
+
const first = createUsageService(options);
|
|
37
|
+
const results = await Promise.all([first.get('openrouter'), first.get('openrouter')]);
|
|
38
|
+
assert.equal(calls, 1); assert.deepEqual(results[0], results[1]);
|
|
39
|
+
const restarted = createUsageService(options);
|
|
40
|
+
assert.deepEqual(await restarted.get('openrouter'), results[0]); assert.equal(calls, 1);
|
|
41
|
+
assert.equal((await readFile(join(directory, 'dsh-oauth-usage.json'), 'utf8')).includes('test-secret'), false);
|
|
42
|
+
clock += 61000;
|
|
43
|
+
const unavailable = createUsageService({ ...options, reader: async () => { throw new UsageError('unavailable', 'offline'); } });
|
|
44
|
+
const stale = await unavailable.get('openrouter');
|
|
45
|
+
assert.equal(stale.status, 'stale'); assert.equal(stale.snapshot.observedAt, results[0].snapshot.observedAt);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('account switch never displays previous account quota and permission loss hides stale figures', async t => {
|
|
49
|
+
const directory = await setup(t); let current = context(); let clock = 1700000000000;
|
|
50
|
+
const options = { directory, contextFor: () => current, now: () => clock, reader: async () => sample };
|
|
51
|
+
await createUsageService(options).get('openrouter'); clock += 61000;
|
|
52
|
+
const denied = createUsageService({ ...options, reader: async () => { throw new UsageError('needs-permission', 'forbidden'); } });
|
|
53
|
+
assert.equal((await denied.get('openrouter')).snapshot, undefined);
|
|
54
|
+
current = { ...current, rawGrant: { access: 'second-account' } };
|
|
55
|
+
const switched = createUsageService({ ...options, reader: async () => { throw new UsageError('unavailable', 'offline'); } });
|
|
56
|
+
assert.equal((await switched.get('openrouter')).status, 'unavailable');
|
|
57
|
+
assert.equal((await switched.get('openrouter')).snapshot, undefined);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('disconnect invalidates an in-flight query without reviving its persisted snapshot', async t => {
|
|
61
|
+
const directory = await setup(t); let release; let started;
|
|
62
|
+
const entered = new Promise(resolve => { started = resolve; });
|
|
63
|
+
const service = createUsageService({ directory, contextFor: context, reader: async () => { started(); await new Promise(resolve => { release = resolve; }); return sample; } });
|
|
64
|
+
const pending = service.get('openrouter'); await entered; await service.invalidate('openrouter'); release();
|
|
65
|
+
assert.equal((await pending).status, 'reauth-required');
|
|
66
|
+
assert.deepEqual(JSON.parse(await readFile(join(directory, 'dsh-oauth-usage.json'), 'utf8')).entries, {});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('429 retry-after survives restart and cannot be bypassed by force', async t => {
|
|
70
|
+
const directory = await setup(t); let calls = 0; const now = 1700000000000;
|
|
71
|
+
const options = { directory, contextFor: context, now: () => now, reader: async () => { calls++; throw new UsageError('rate-limited', 'limited', { retryAt: new Date(now + 120000).toISOString() }); } };
|
|
72
|
+
assert.equal((await createUsageService(options).get('poe')).status, 'rate-limited');
|
|
73
|
+
await createUsageService(options).get('poe', { force: true }); assert.equal(calls, 1);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('provider-specific permission and scope failures normalize to documented UI states', async t => {
|
|
77
|
+
const directory = await setup(t);
|
|
78
|
+
for (const [id, code, status] of [['anthropic', 'scope-required', 'needs-permission'], ['google-gemini-cli', 'scope-required', 'needs-configuration'], ['aliyun-token-plan', 'billing-credential-required', 'needs-permission']]) {
|
|
79
|
+
const service = createUsageService({ directory, contextFor: context, reader: async () => { throw new UsageError(code, 'additional authorization required'); } });
|
|
80
|
+
assert.equal((await service.get(id)).status, status);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test('DeepSeek API decimal balances and New API deployment units are preserved', async () => {
|
|
85
|
+
const deepseek = await fetchUsage('deepseek', { access: 'test', request: async () => ({ balance_infos: [{ currency: 'CNY', total_balance: '0.00001' }] }) });
|
|
86
|
+
assert.equal(deepseek.balances[0].amount, '0.00001');
|
|
87
|
+
const gateway = await fetchUsage('new-api', { access: 'test', baseURL: 'https://gateway.example.test/v1', request: async (url) => { assert.equal(url, 'https://gateway.example.test/api/usage/token/'); return { success: true, data: { total_available: 5, total_used: 10, total_granted: 15 } }; } });
|
|
88
|
+
assert.equal(gateway.windows[0].unit, 'quota'); assert.equal(gateway.windows[0].remaining, 5);
|
|
89
|
+
});
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/** xAI's production loopback Authorization Code + PKCE transport. Never stores credentials. */
|
|
2
|
+
import { constants, createHash, createPublicKey, randomBytes, timingSafeEqual, verify } from "node:crypto";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
|
|
5
|
+
const ISSUER = "https://auth.x.ai";
|
|
6
|
+
const CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
7
|
+
const ACCOUNTS_ORIGIN = "https://accounts.x.ai";
|
|
8
|
+
// Preserve the existing device-flow permission set; the official full CLI also
|
|
9
|
+
// requests conversation/workspace scopes that this plugin does not require.
|
|
10
|
+
const SCOPES = "openid profile email offline_access grok-cli:access api:access";
|
|
11
|
+
const MAX_JSON_BYTES = 1024 * 1024;
|
|
12
|
+
const OAUTH_ERRORS = new Set(["invalid_request", "invalid_client", "invalid_grant", "invalid_scope", "access_denied", "unsupported_grant_type", "temporarily_unavailable", "server_error"]);
|
|
13
|
+
const ALGORITHMS = {
|
|
14
|
+
RS256: { digest: "sha256", kty: "RSA" }, RS384: { digest: "sha384", kty: "RSA" }, RS512: { digest: "sha512", kty: "RSA" },
|
|
15
|
+
PS256: { digest: "sha256", kty: "RSA", pss: true }, PS384: { digest: "sha384", kty: "RSA", pss: true }, PS512: { digest: "sha512", kty: "RSA", pss: true },
|
|
16
|
+
ES256: { digest: "sha256", kty: "EC", curve: "P-256", signatureBytes: 64 }, ES384: { digest: "sha384", kty: "EC", curve: "P-384", signatureBytes: 96 },
|
|
17
|
+
EdDSA: { digest: null, kty: "OKP" },
|
|
18
|
+
};
|
|
19
|
+
const failure = (message, code, status) => Object.assign(new Error(message), { code, ...(status === undefined ? {} : { status }) });
|
|
20
|
+
const cancelled = () => failure("xAI 浏览器登录已取消", "XAI_BROWSER_CANCELLED");
|
|
21
|
+
const equal = (a, b) => typeof a === "string" && typeof b === "string" && Buffer.byteLength(a) === Buffer.byteLength(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
22
|
+
const random = () => randomBytes(32).toString("base64url");
|
|
23
|
+
const positive = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
24
|
+
|
|
25
|
+
function endpoint(value) {
|
|
26
|
+
let url;
|
|
27
|
+
try { url = new URL(value); } catch { throw failure("xAI 登录服务返回了无效端点", "XAI_BROWSER_DISCOVERY"); }
|
|
28
|
+
if (url.origin !== ISSUER || url.protocol !== "https:" || url.username || url.password || url.hash) {
|
|
29
|
+
throw failure("xAI 登录服务返回了不受信任的端点", "XAI_BROWSER_DISCOVERY");
|
|
30
|
+
}
|
|
31
|
+
return url.href;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function page(response, status, message, origin) {
|
|
35
|
+
response.writeHead(status, {
|
|
36
|
+
"content-type": "text/html; charset=utf-8", "cache-control": "no-store", "connection": "close",
|
|
37
|
+
"referrer-policy": "no-referrer", "x-content-type-options": "nosniff",
|
|
38
|
+
"content-security-policy": "default-src 'none'; frame-ancestors 'none'; base-uri 'none'",
|
|
39
|
+
...(origin ? { "access-control-allow-origin": origin, "vary": "Origin" } : {}),
|
|
40
|
+
});
|
|
41
|
+
// Every message is a constant owned by this module; request parameters are never reflected.
|
|
42
|
+
response.end(`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>xAI 授权</title><body><h1>xAI 授权</h1><p>${message}</p></body></html>`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function readJson(response) {
|
|
46
|
+
const length = Number(response.headers?.get?.("content-length"));
|
|
47
|
+
if (Number.isFinite(length) && length > MAX_JSON_BYTES) throw new Error("oversized JSON");
|
|
48
|
+
const reader = response.body?.getReader?.();
|
|
49
|
+
if (!reader) throw new Error("missing JSON body");
|
|
50
|
+
const chunks = [];
|
|
51
|
+
let size = 0;
|
|
52
|
+
try {
|
|
53
|
+
for (;;) {
|
|
54
|
+
const { done, value } = await reader.read();
|
|
55
|
+
if (done) break;
|
|
56
|
+
size += value.byteLength;
|
|
57
|
+
if (size > MAX_JSON_BYTES) throw new Error("oversized JSON");
|
|
58
|
+
chunks.push(Buffer.from(value));
|
|
59
|
+
}
|
|
60
|
+
} finally { void reader.cancel().catch(() => {}); }
|
|
61
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
62
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("invalid JSON object");
|
|
63
|
+
return body;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Test seams change I/O and time only; issuer, public client, scopes and loopback
|
|
68
|
+
* binding remain fixed. Once a valid callback is accepted, the caller's signal
|
|
69
|
+
* cannot interrupt the one-use code exchange; its independent timeout still can.
|
|
70
|
+
* `onExchangeStart` lets the host protect the resulting credential commit too.
|
|
71
|
+
*/
|
|
72
|
+
export async function loginXaiBrowser(interaction, {
|
|
73
|
+
fetchImpl = globalThis.fetch, timeoutMs = 600000, requestTimeoutMs = 15000,
|
|
74
|
+
discoveryTimeoutMs = 10000, now = Date.now, onExchangeStart, clientVersion,
|
|
75
|
+
} = {}) {
|
|
76
|
+
if (typeof interaction?.notify !== "function") throw new TypeError("xAI browser login requires a notify callback");
|
|
77
|
+
if (interaction.signal?.aborted) throw cancelled();
|
|
78
|
+
const waiting = new AbortController();
|
|
79
|
+
const deadlineError = failure("xAI 浏览器登录等待超时,请重新登录", "XAI_BROWSER_TIMEOUT");
|
|
80
|
+
let accepted = false;
|
|
81
|
+
let listener;
|
|
82
|
+
let callbackResolve;
|
|
83
|
+
let callbackReject;
|
|
84
|
+
let callbackSettled = false;
|
|
85
|
+
const callback = new Promise((resolve, reject) => { callbackResolve = resolve; callbackReject = reject; });
|
|
86
|
+
// Discovery can fail before the callback promise is awaited.
|
|
87
|
+
void callback.catch(() => {});
|
|
88
|
+
const rejectWaiting = (error) => {
|
|
89
|
+
if (accepted) return;
|
|
90
|
+
waiting.abort(error);
|
|
91
|
+
if (!callbackSettled) { callbackSettled = true; callbackReject(error); }
|
|
92
|
+
};
|
|
93
|
+
const onAbort = () => rejectWaiting(cancelled());
|
|
94
|
+
interaction.signal?.addEventListener("abort", onAbort, { once: true });
|
|
95
|
+
const lifetime = setTimeout(() => rejectWaiting(deadlineError), positive(timeoutMs, 600000));
|
|
96
|
+
|
|
97
|
+
async function requestJson(url, options, label, parentSignal, limit = requestTimeoutMs) {
|
|
98
|
+
const controller = new AbortController();
|
|
99
|
+
const timeout = failure(`xAI ${label}请求超时,请稍后重试`, "XAI_BROWSER_REQUEST_TIMEOUT");
|
|
100
|
+
const signal = parentSignal ? AbortSignal.any([parentSignal, controller.signal]) : controller.signal;
|
|
101
|
+
let rejectAborted;
|
|
102
|
+
const aborted = new Promise((_, reject) => { rejectAborted = reject; });
|
|
103
|
+
const abort = () => rejectAborted(parentSignal?.aborted ? parentSignal.reason : timeout);
|
|
104
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
105
|
+
const timer = setTimeout(() => controller.abort(timeout), positive(limit, 15000));
|
|
106
|
+
try {
|
|
107
|
+
if (signal.aborted) abort();
|
|
108
|
+
const operation = Promise.resolve().then(async () => {
|
|
109
|
+
if (signal.aborted) throw signal.reason;
|
|
110
|
+
const response = await fetchImpl(url, { ...options, redirect: "error", signal });
|
|
111
|
+
if (!response.ok) {
|
|
112
|
+
let safeCode;
|
|
113
|
+
try {
|
|
114
|
+
const body = await readJson(response);
|
|
115
|
+
safeCode = [body.error, body.code, body.error?.code].find((code) => OAUTH_ERRORS.has(code));
|
|
116
|
+
} catch { /* Preserve HTTP diagnostics without exposing arbitrary upstream text. */ }
|
|
117
|
+
throw failure(`xAI ${label}失败(HTTP ${response.status}${safeCode ? `,${safeCode}` : ""}),请稍后重试`, "XAI_BROWSER_HTTP", response.status);
|
|
118
|
+
}
|
|
119
|
+
try { return await readJson(response); }
|
|
120
|
+
catch { throw failure(`xAI ${label}返回了无效响应`, "XAI_BROWSER_RESPONSE"); }
|
|
121
|
+
});
|
|
122
|
+
return await Promise.race([operation, aborted]);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (parentSignal?.aborted) throw parentSignal.reason;
|
|
125
|
+
if (controller.signal.aborted) throw timeout;
|
|
126
|
+
if (typeof error?.code === "string" && error.code.startsWith("XAI_BROWSER_")) throw error;
|
|
127
|
+
throw failure(`xAI ${label}网络请求失败,请稍后重试`, "XAI_BROWSER_NETWORK");
|
|
128
|
+
} finally {
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
signal.removeEventListener("abort", abort);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
if (interaction.signal?.aborted) onAbort();
|
|
136
|
+
const discovery = await requestJson(`${ISSUER}/.well-known/openid-configuration`, { headers: { accept: "application/json" } }, "登录服务发现", waiting.signal, discoveryTimeoutMs);
|
|
137
|
+
if (discovery.issuer !== undefined && discovery.issuer !== ISSUER) throw failure("xAI 登录服务的 issuer 不匹配", "XAI_BROWSER_DISCOVERY");
|
|
138
|
+
const authorizationEndpoint = endpoint(discovery.authorization_endpoint);
|
|
139
|
+
const tokenEndpoint = endpoint(discovery.token_endpoint);
|
|
140
|
+
const jwksUri = endpoint(discovery.jwks_uri);
|
|
141
|
+
if (Array.isArray(discovery.code_challenge_methods_supported) && !discovery.code_challenge_methods_supported.includes("S256")) {
|
|
142
|
+
throw failure("xAI 登录服务未提供 S256 PKCE", "XAI_BROWSER_DISCOVERY");
|
|
143
|
+
}
|
|
144
|
+
const state = random();
|
|
145
|
+
const nonce = random();
|
|
146
|
+
const verifier = random();
|
|
147
|
+
const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url");
|
|
148
|
+
let callbackHost;
|
|
149
|
+
listener = createServer((request, response) => {
|
|
150
|
+
try {
|
|
151
|
+
const origin = request.headers.origin;
|
|
152
|
+
if (request.headers.host !== callbackHost || origin !== undefined && origin !== ACCOUNTS_ORIGIN) {
|
|
153
|
+
page(response, 403, "此回调来源不受信任。请返回原授权窗口。", undefined); return;
|
|
154
|
+
}
|
|
155
|
+
if (!request.url || request.url.length > 32768 || !request.url.startsWith("/")) {
|
|
156
|
+
page(response, 400, "授权回调格式无效。", origin); return;
|
|
157
|
+
}
|
|
158
|
+
const url = new URL(request.url, `http://${callbackHost}`);
|
|
159
|
+
if (url.origin !== `http://${callbackHost}` || url.pathname !== "/callback") {
|
|
160
|
+
page(response, 404, "未找到此授权回调。", origin); return;
|
|
161
|
+
}
|
|
162
|
+
if (request.method === "OPTIONS") {
|
|
163
|
+
if (origin !== ACCOUNTS_ORIGIN || request.headers["access-control-request-method"] !== "GET") {
|
|
164
|
+
page(response, 403, "此回调请求不受支持。", undefined); return;
|
|
165
|
+
}
|
|
166
|
+
response.writeHead(204, {
|
|
167
|
+
"access-control-allow-origin": ACCOUNTS_ORIGIN, "access-control-allow-methods": "GET",
|
|
168
|
+
"access-control-allow-private-network": "true", "cache-control": "no-store", "connection": "close",
|
|
169
|
+
"vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Private-Network",
|
|
170
|
+
});
|
|
171
|
+
response.end(); return;
|
|
172
|
+
}
|
|
173
|
+
if (request.method !== "GET") { page(response, 405, "此回调仅支持 GET。", origin); return; }
|
|
174
|
+
if (accepted || callbackSettled) { page(response, 409, "此授权回调已处理。请返回管理面板。", origin); return; }
|
|
175
|
+
const params = url.searchParams;
|
|
176
|
+
if (params.getAll("state").length !== 1 || !equal(params.get("state"), state) || params.getAll("code").length > 1 || params.getAll("error").length > 1) {
|
|
177
|
+
page(response, 400, "授权状态不匹配,请返回原授权窗口。", origin); return;
|
|
178
|
+
}
|
|
179
|
+
if (params.has("error")) {
|
|
180
|
+
if (params.has("code")) { page(response, 400, "授权回调格式无效。", origin); return; }
|
|
181
|
+
callbackSettled = true;
|
|
182
|
+
callbackReject(failure("xAI 未批准本次浏览器授权,请重新登录", "XAI_BROWSER_DENIED"));
|
|
183
|
+
page(response, 400, "本次授权未完成。请返回管理面板。", origin); return;
|
|
184
|
+
}
|
|
185
|
+
const code = params.get("code");
|
|
186
|
+
if (typeof code !== "string" || code.length === 0 || code.length > 8192 || /[\x00-\x20\x7f]/.test(code)) {
|
|
187
|
+
page(response, 400, "授权回调缺少有效授权码。", origin); return;
|
|
188
|
+
}
|
|
189
|
+
// Claim before resolving, so simultaneous callbacks cannot exchange twice.
|
|
190
|
+
accepted = true;
|
|
191
|
+
callbackSettled = true;
|
|
192
|
+
clearTimeout(lifetime);
|
|
193
|
+
interaction.signal?.removeEventListener("abort", onAbort);
|
|
194
|
+
callbackResolve(code);
|
|
195
|
+
page(response, 200, "授权回调已收到,正在完成验证。请返回管理面板查看结果。", origin);
|
|
196
|
+
} catch { page(response, 400, "授权回调格式无效。", undefined); }
|
|
197
|
+
});
|
|
198
|
+
listener.maxHeadersCount = 32;
|
|
199
|
+
listener.headersTimeout = 10000;
|
|
200
|
+
listener.requestTimeout = 10000;
|
|
201
|
+
await new Promise((resolve, reject) => {
|
|
202
|
+
listener.once("error", reject);
|
|
203
|
+
listener.listen(0, "127.0.0.1", () => { listener.removeListener("error", reject); resolve(); });
|
|
204
|
+
});
|
|
205
|
+
listener.on("error", () => rejectWaiting(failure("xAI 本机回调服务失败,请重试", "XAI_BROWSER_LISTENER")));
|
|
206
|
+
const address = listener.address();
|
|
207
|
+
callbackHost = `127.0.0.1:${address.port}`;
|
|
208
|
+
const redirectUri = `http://${callbackHost}/callback`;
|
|
209
|
+
const authorize = new URL(authorizationEndpoint);
|
|
210
|
+
for (const [key, value] of Object.entries({ response_type: "code", client_id: CLIENT_ID, redirect_uri: redirectUri, scope: SCOPES, code_challenge: challenge, code_challenge_method: "S256", state, nonce, referrer: "grok-build" })) authorize.searchParams.set(key, value);
|
|
211
|
+
if (waiting.signal.aborted) throw waiting.signal.reason;
|
|
212
|
+
interaction.notify({ url: authorize.href, message: "请在浏览器中完成 xAI 授权,完成后会自动返回本机面板。" });
|
|
213
|
+
const code = await callback;
|
|
214
|
+
(onExchangeStart ?? interaction.onExchangeStart)?.();
|
|
215
|
+
const headers = { accept: "application/json", "content-type": "application/x-www-form-urlencoded" };
|
|
216
|
+
if (typeof clientVersion === "string" && /^[0-9A-Za-z.+_-]{1,80}$/.test(clientVersion)) headers["x-grok-client-version"] = clientVersion;
|
|
217
|
+
const token = await requestJson(tokenEndpoint, { method: "POST", headers, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, client_id: CLIENT_ID, code_verifier: verifier }) }, "授权码交换");
|
|
218
|
+
const tokenString = (value) => typeof value === "string" && value.trim().length > 0 && !/[\r\n\x00]/.test(value);
|
|
219
|
+
if (!tokenString(token.access_token) || !tokenString(token.refresh_token)) {
|
|
220
|
+
throw failure("xAI 授权响应缺少有效访问或刷新令牌", "XAI_BROWSER_TOKEN");
|
|
221
|
+
}
|
|
222
|
+
if (token.token_type !== undefined && (typeof token.token_type !== "string" || token.token_type.toLowerCase() !== "bearer")) {
|
|
223
|
+
throw failure("xAI 授权响应的令牌类型不受支持", "XAI_BROWSER_TOKEN");
|
|
224
|
+
}
|
|
225
|
+
const expiresIn = token.expires_in === undefined ? 3600 : token.expires_in;
|
|
226
|
+
if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) throw failure("xAI 授权响应的有效期无效", "XAI_BROWSER_TOKEN");
|
|
227
|
+
const expires = now() + expiresIn * 1000 - 5 * 60 * 1000;
|
|
228
|
+
if (!Number.isFinite(expires) || !Number.isSafeInteger(Math.trunc(expires))) throw failure("xAI 授权响应的有效期过大", "XAI_BROWSER_TOKEN");
|
|
229
|
+
if (typeof token.id_token !== "string") throw failure("xAI 个人账号授权缺少身份令牌", "XAI_BROWSER_ID_TOKEN");
|
|
230
|
+
await validateIdentityToken(token.id_token, discovery, jwksUri, nonce, requestJson, now);
|
|
231
|
+
return { type: "oauth", access: token.access_token, refresh: token.refresh_token, expires };
|
|
232
|
+
} finally {
|
|
233
|
+
clearTimeout(lifetime);
|
|
234
|
+
interaction.signal?.removeEventListener("abort", onAbort);
|
|
235
|
+
if (listener) await new Promise((resolve) => {
|
|
236
|
+
listener.close(() => resolve());
|
|
237
|
+
listener.closeAllConnections();
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function validateIdentityToken(token, discovery, jwksUri, nonce, requestJson, now) {
|
|
243
|
+
try {
|
|
244
|
+
if (token.length > 65536) throw new Error();
|
|
245
|
+
const segments = token.split(".");
|
|
246
|
+
if (segments.length !== 3 || segments.some((part) => !/^[A-Za-z0-9_-]+$/.test(part))) throw new Error();
|
|
247
|
+
const header = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
|
|
248
|
+
const claims = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8"));
|
|
249
|
+
const algorithm = ALGORITHMS[header.alg];
|
|
250
|
+
if (!Object.hasOwn(ALGORITHMS, header.alg) || !algorithm || typeof header.kid !== "string" || !header.kid || header.crit !== undefined) throw new Error();
|
|
251
|
+
if (Array.isArray(discovery.id_token_signing_alg_values_supported) && !discovery.id_token_signing_alg_values_supported.includes(header.alg)) throw new Error();
|
|
252
|
+
const jwks = await requestJson(jwksUri, { headers: { accept: "application/json" } }, "身份签名密钥读取", undefined, 10000);
|
|
253
|
+
const keys = Array.isArray(jwks.keys) ? jwks.keys.filter((key) => key?.kid === header.kid) : [];
|
|
254
|
+
if (keys.length !== 1) throw new Error();
|
|
255
|
+
const jwk = keys[0];
|
|
256
|
+
if (jwk.kty !== algorithm.kty || jwk.alg !== undefined && jwk.alg !== header.alg || jwk.use !== undefined && jwk.use !== "sig" || jwk.key_ops !== undefined && (!Array.isArray(jwk.key_ops) || !jwk.key_ops.includes("verify"))) throw new Error();
|
|
257
|
+
if (algorithm.curve && jwk.crv !== algorithm.curve || header.alg === "EdDSA" && !["Ed25519", "Ed448"].includes(jwk.crv)) throw new Error();
|
|
258
|
+
const key = createPublicKey({ key: jwk, format: "jwk" });
|
|
259
|
+
if (algorithm.kty === "RSA" && key.asymmetricKeyDetails?.modulusLength < 2048) throw new Error();
|
|
260
|
+
const signature = Buffer.from(segments[2], "base64url");
|
|
261
|
+
if (algorithm.signatureBytes && signature.length !== algorithm.signatureBytes) throw new Error();
|
|
262
|
+
const keyOptions = algorithm.pss ? { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST } : algorithm.kty === "EC" ? { key, dsaEncoding: "ieee-p1363" } : key;
|
|
263
|
+
if (!verify(algorithm.digest, Buffer.from(`${segments[0]}.${segments[1]}`, "ascii"), keyOptions, signature)) throw new Error();
|
|
264
|
+
const audience = claims.aud;
|
|
265
|
+
if (claims.iss !== ISSUER || !(audience === CLIENT_ID || Array.isArray(audience) && audience.includes(CLIENT_ID)) || typeof claims.sub !== "string" || !claims.sub.trim() || !equal(claims.nonce, nonce)) throw new Error();
|
|
266
|
+
const seconds = now() / 1000;
|
|
267
|
+
if (typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp <= seconds - 60 || claims.nbf !== undefined && (typeof claims.nbf !== "number" || claims.nbf > seconds + 60) || claims.azp !== undefined && claims.azp !== CLIENT_ID) throw new Error();
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (typeof error?.code === "string" && error.code.startsWith("XAI_BROWSER_")) throw error;
|
|
270
|
+
throw failure("xAI 身份令牌验证失败,请重新登录", "XAI_BROWSER_ID_TOKEN");
|
|
271
|
+
}
|
|
272
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { createHash, generateKeyPairSync, sign } from "node:crypto";
|
|
4
|
+
import { request } from "node:http";
|
|
5
|
+
import { loginXaiBrowser } from "./xai-browser.js";
|
|
6
|
+
|
|
7
|
+
const ISSUER = "https://auth.x.ai";
|
|
8
|
+
const CLIENT = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
9
|
+
const NOW = 1800000000000;
|
|
10
|
+
const pair = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
|
|
11
|
+
const publicJwk = { ...pair.publicKey.export({ format: "jwk" }), kid: "test-key", alg: "ES256", use: "sig" };
|
|
12
|
+
const discovery = { issuer: ISSUER, authorization_endpoint: `${ISSUER}/oauth2/authorize`, token_endpoint: `${ISSUER}/oauth2/token`, jwks_uri: `${ISSUER}/.well-known/jwks.json`, code_challenge_methods_supported: ["S256"], id_token_signing_alg_values_supported: ["ES256"] };
|
|
13
|
+
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
14
|
+
const defer = () => { let resolve; const promise = new Promise((done) => { resolve = done; }); return { promise, resolve }; };
|
|
15
|
+
function jwt(nonce, claimChanges = {}, headerChanges = {}) {
|
|
16
|
+
const header = Buffer.from(JSON.stringify({ alg: "ES256", kid: "test-key", ...headerChanges })).toString("base64url");
|
|
17
|
+
const payload = Buffer.from(JSON.stringify({ iss: ISSUER, aud: CLIENT, sub: "mock-user", exp: NOW / 1000 + 3600, nonce, ...claimChanges })).toString("base64url");
|
|
18
|
+
const signature = sign("sha256", Buffer.from(`${header}.${payload}`), { key: pair.privateKey, dsaEncoding: "ieee-p1363" }).toString("base64url");
|
|
19
|
+
return `${header}.${payload}.${signature}`;
|
|
20
|
+
}
|
|
21
|
+
function http(url, { method = "GET", headers = {} } = {}) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const req = request(url, { method, headers, agent: false }, (response) => {
|
|
24
|
+
const chunks = [];
|
|
25
|
+
response.on("data", (chunk) => chunks.push(chunk));
|
|
26
|
+
response.on("end", () => resolve({ status: response.statusCode, headers: response.headers, body: Buffer.concat(chunks).toString("utf8") }));
|
|
27
|
+
});
|
|
28
|
+
req.on("error", reject);
|
|
29
|
+
req.end();
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function flow({ metadata = {}, tokenChanges = {}, claims = {}, jwtHeader = {}, jwks, tokenImpl, idTokenImpl, onExchangeStart, options = {} } = {}) {
|
|
33
|
+
const ready = defer();
|
|
34
|
+
const tokenStarted = defer();
|
|
35
|
+
const controller = new AbortController();
|
|
36
|
+
const calls = [];
|
|
37
|
+
let authUrl;
|
|
38
|
+
let exchangeMarked = false;
|
|
39
|
+
const promise = loginXaiBrowser({
|
|
40
|
+
signal: controller.signal,
|
|
41
|
+
notify(notice) { authUrl = new URL(notice.url); ready.resolve(authUrl); },
|
|
42
|
+
onExchangeStart() { exchangeMarked = true; onExchangeStart?.(controller); },
|
|
43
|
+
}, {
|
|
44
|
+
now: () => NOW,
|
|
45
|
+
...options,
|
|
46
|
+
fetchImpl: async (url, init) => {
|
|
47
|
+
calls.push({ url: String(url), init });
|
|
48
|
+
if (String(url) === `${ISSUER}/.well-known/openid-configuration`) return json({ ...discovery, ...metadata });
|
|
49
|
+
if (String(url) === `${ISSUER}/oauth2/token`) {
|
|
50
|
+
assert.equal(exchangeMarked, true, "the host learns the exchange phase before its POST starts");
|
|
51
|
+
tokenStarted.resolve();
|
|
52
|
+
if (tokenImpl) return tokenImpl(url, init, authUrl);
|
|
53
|
+
const nonce = authUrl.searchParams.get("nonce");
|
|
54
|
+
return json({ access_token: "mock-browser-access", refresh_token: "mock-browser-refresh", expires_in: 3600, id_token: idTokenImpl ? idTokenImpl(nonce) : jwt(nonce, claims, jwtHeader), ...tokenChanges });
|
|
55
|
+
}
|
|
56
|
+
if (String(url) === `${ISSUER}/.well-known/jwks.json`) return json(jwks ?? { keys: [publicJwk] });
|
|
57
|
+
throw new Error("unexpected external request refused by test");
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
// Some tests deliberately reject before they await the flow.
|
|
61
|
+
void promise.catch(() => {});
|
|
62
|
+
return {
|
|
63
|
+
promise, controller, calls, tokenStarted: tokenStarted.promise,
|
|
64
|
+
async url() { return ready.promise; },
|
|
65
|
+
async callback(query = {}, headers) {
|
|
66
|
+
const authorize = await ready.promise;
|
|
67
|
+
const url = new URL(authorize.searchParams.get("redirect_uri"));
|
|
68
|
+
url.search = new URLSearchParams({ state: authorize.searchParams.get("state"), code: "mock-authorization-code", ...query });
|
|
69
|
+
return http(url, { headers });
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const closed = async (authorize) => assert.rejects(http(new URL(authorize.searchParams.get("redirect_uri"))), (error) => error.code === "ECONNREFUSED");
|
|
74
|
+
|
|
75
|
+
test("token endpoint failures expose only a standard OAuth code and never its arbitrary description", async () => {
|
|
76
|
+
const pending = flow({ tokenImpl: () => json({ error: "invalid_scope", error_description: "private-response-must-not-appear" }, 400) });
|
|
77
|
+
await pending.callback();
|
|
78
|
+
await assert.rejects(pending.promise, (error) => {
|
|
79
|
+
assert.match(error.message, /HTTP 400,invalid_scope/);
|
|
80
|
+
assert.doesNotMatch(error.message, /private-response-must-not-appear/);
|
|
81
|
+
return true;
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("actual loopback callback completes S256 exchange and verifies the signed OIDC identity", async () => {
|
|
86
|
+
const pending = flow();
|
|
87
|
+
const authorize = await pending.url();
|
|
88
|
+
const redirect = new URL(authorize.searchParams.get("redirect_uri"));
|
|
89
|
+
assert.equal(redirect.hostname, "127.0.0.1");
|
|
90
|
+
assert.equal(redirect.pathname, "/callback");
|
|
91
|
+
assert.ok(Number(redirect.port) > 0);
|
|
92
|
+
assert.equal(authorize.origin, ISSUER);
|
|
93
|
+
assert.equal(authorize.pathname, "/oauth2/authorize");
|
|
94
|
+
assert.equal(authorize.searchParams.get("client_id"), CLIENT);
|
|
95
|
+
assert.equal(authorize.searchParams.get("response_type"), "code");
|
|
96
|
+
assert.equal(authorize.searchParams.get("scope"), "openid profile email offline_access grok-cli:access api:access");
|
|
97
|
+
assert.equal(authorize.searchParams.get("referrer"), "grok-build");
|
|
98
|
+
assert.equal(authorize.searchParams.get("code_challenge_method"), "S256");
|
|
99
|
+
assert.match(authorize.searchParams.get("state"), /^[A-Za-z0-9_-]{43}$/);
|
|
100
|
+
assert.match(authorize.searchParams.get("nonce"), /^[A-Za-z0-9_-]{43}$/);
|
|
101
|
+
assert.notEqual(authorize.searchParams.get("state"), authorize.searchParams.get("nonce"));
|
|
102
|
+
const response = await pending.callback({}, { origin: "https://accounts.x.ai" });
|
|
103
|
+
assert.equal(response.status, 200);
|
|
104
|
+
assert.equal(response.headers["access-control-allow-origin"], "https://accounts.x.ai");
|
|
105
|
+
assert.ok(!response.body.includes("mock-authorization-code"));
|
|
106
|
+
const grant = await pending.promise;
|
|
107
|
+
assert.deepEqual(grant, { type: "oauth", access: "mock-browser-access", refresh: "mock-browser-refresh", expires: NOW + 3300000 });
|
|
108
|
+
const exchange = pending.calls.find((call) => call.url.endsWith("/token"));
|
|
109
|
+
const form = exchange.init.body;
|
|
110
|
+
assert.equal(form.get("grant_type"), "authorization_code");
|
|
111
|
+
assert.equal(form.get("client_id"), CLIENT);
|
|
112
|
+
assert.equal(form.get("redirect_uri"), redirect.href);
|
|
113
|
+
assert.equal(form.get("code"), "mock-authorization-code");
|
|
114
|
+
assert.match(form.get("code_verifier"), /^[A-Za-z0-9_-]{43}$/);
|
|
115
|
+
assert.equal(createHash("sha256").update(form.get("code_verifier"), "ascii").digest("base64url"), authorize.searchParams.get("code_challenge"));
|
|
116
|
+
assert.equal(form.has("client_secret"), false);
|
|
117
|
+
assert.equal(exchange.init.headers["x-grok-client-version"], undefined);
|
|
118
|
+
await closed(authorize);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("Host/Origin/state validation and CORS/PNA preflight do not consume the valid attempt", async () => {
|
|
122
|
+
const pending = flow();
|
|
123
|
+
const authorize = await pending.url();
|
|
124
|
+
const redirect = authorize.searchParams.get("redirect_uri");
|
|
125
|
+
assert.equal((await pending.callback({}, { host: "evil.example" })).status, 403);
|
|
126
|
+
assert.equal((await pending.callback({}, { origin: "https://evil.example" })).status, 403);
|
|
127
|
+
assert.equal((await pending.callback({}, { origin: "null" })).status, 403);
|
|
128
|
+
assert.equal((await pending.callback({ state: "wrong-state" })).status, 400);
|
|
129
|
+
assert.equal((await pending.callback({ state: "wrong-state", error: "access_denied" })).status, 400);
|
|
130
|
+
const repeated = new URL(redirect);
|
|
131
|
+
repeated.search = new URLSearchParams({ state: authorize.searchParams.get("state"), code: "test" });
|
|
132
|
+
repeated.searchParams.append("state", authorize.searchParams.get("state"));
|
|
133
|
+
assert.equal((await http(repeated)).status, 400);
|
|
134
|
+
assert.equal(pending.calls.length, 1, "only discovery was requested after malicious callbacks");
|
|
135
|
+
const preflight = await http(redirect, { method: "OPTIONS", headers: { origin: "https://accounts.x.ai", "access-control-request-method": "GET", "access-control-request-private-network": "true" } });
|
|
136
|
+
assert.equal(preflight.status, 204);
|
|
137
|
+
assert.equal(preflight.headers["access-control-allow-origin"], "https://accounts.x.ai");
|
|
138
|
+
assert.equal(preflight.headers["access-control-allow-private-network"], "true");
|
|
139
|
+
assert.equal((await http(redirect, { method: "OPTIONS", headers: { origin: "https://accounts.x.ai", "access-control-request-method": "POST" } })).status, 403);
|
|
140
|
+
assert.equal((await http(redirect, { method: "POST" })).status, 405);
|
|
141
|
+
assert.equal((await http(new URL("/other", redirect))).status, 404);
|
|
142
|
+
assert.equal((await pending.callback()).status, 200);
|
|
143
|
+
assert.equal((await pending.promise).type, "oauth");
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("simultaneous callback replay is rejected while the single token exchange is pending", async () => {
|
|
147
|
+
const gate = defer();
|
|
148
|
+
const pending = flow({ tokenImpl: async (_url, _init, authorize) => {
|
|
149
|
+
await gate.promise;
|
|
150
|
+
return json({ access_token: "mock-a", refresh_token: "mock-r", id_token: jwt(authorize.searchParams.get("nonce")) });
|
|
151
|
+
} });
|
|
152
|
+
assert.equal((await pending.callback()).status, 200);
|
|
153
|
+
await pending.tokenStarted;
|
|
154
|
+
assert.equal((await pending.callback()).status, 409);
|
|
155
|
+
assert.equal(pending.calls.filter((call) => call.url.endsWith("/token")).length, 1);
|
|
156
|
+
gate.resolve();
|
|
157
|
+
assert.equal((await pending.promise).access, "mock-a");
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("a valid-state provider denial is terminal and does not echo error descriptions", async () => {
|
|
161
|
+
const pending = flow();
|
|
162
|
+
const authorize = await pending.url();
|
|
163
|
+
const redirect = new URL(authorize.searchParams.get("redirect_uri"));
|
|
164
|
+
redirect.search = new URLSearchParams({ state: authorize.searchParams.get("state"), error: "access_denied", error_description: "sensitive-callback-detail" });
|
|
165
|
+
const response = await http(redirect);
|
|
166
|
+
assert.equal(response.status, 400);
|
|
167
|
+
assert.ok(!response.body.includes("sensitive-callback-detail"));
|
|
168
|
+
await assert.rejects(pending.promise, (error) => error.code === "XAI_BROWSER_DENIED" && !error.message.includes("sensitive-callback-detail"));
|
|
169
|
+
assert.equal(pending.calls.length, 1);
|
|
170
|
+
await closed(authorize);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("cancellation and waiting timeout close the real callback listener", async (t) => {
|
|
174
|
+
await t.test("pre-aborted signal never fetches", async () => {
|
|
175
|
+
const controller = new AbortController(); controller.abort();
|
|
176
|
+
let fetched = false;
|
|
177
|
+
await assert.rejects(loginXaiBrowser({ signal: controller.signal, notify() {} }, { fetchImpl: async () => { fetched = true; } }), (error) => error.code === "XAI_BROWSER_CANCELLED");
|
|
178
|
+
assert.equal(fetched, false);
|
|
179
|
+
});
|
|
180
|
+
await t.test("cancel while waiting", async () => {
|
|
181
|
+
const pending = flow(); const authorize = await pending.url();
|
|
182
|
+
pending.controller.abort(new Error("must-not-be-reflected"));
|
|
183
|
+
await assert.rejects(pending.promise, (error) => error.code === "XAI_BROWSER_CANCELLED" && !error.message.includes("must-not-be-reflected"));
|
|
184
|
+
await closed(authorize);
|
|
185
|
+
});
|
|
186
|
+
await t.test("wait expires", async () => {
|
|
187
|
+
const pending = flow({ options: { timeoutMs: 60 } }); const authorize = await pending.url();
|
|
188
|
+
await assert.rejects(pending.promise, (error) => error.code === "XAI_BROWSER_TIMEOUT");
|
|
189
|
+
await closed(authorize);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test("ordinary cancellation after exchange starts does not discard the one-use code exchange", async () => {
|
|
194
|
+
const pending = flow({ onExchangeStart: (controller) => controller.abort() });
|
|
195
|
+
assert.equal((await pending.callback()).status, 200);
|
|
196
|
+
assert.equal((await pending.promise).type, "oauth");
|
|
197
|
+
assert.equal(pending.controller.signal.aborted, true);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("a stalled token request is bounded independently and closes the listener", async () => {
|
|
201
|
+
const pending = flow({ options: { requestTimeoutMs: 30 }, tokenImpl: () => new Promise(() => {}) });
|
|
202
|
+
const authorize = await pending.url();
|
|
203
|
+
await pending.callback();
|
|
204
|
+
await assert.rejects(pending.promise, (error) => error.code === "XAI_BROWSER_REQUEST_TIMEOUT");
|
|
205
|
+
await closed(authorize);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("token exchange failures are sanitized and incomplete credentials never report success", async (t) => {
|
|
209
|
+
for (const [name, change] of [["missing access", { access_token: "" }], ["missing refresh", { refresh_token: undefined }], ["invalid expiry", { expires_in: -1 }], ["overflowing expiry", { expires_in: 1e308 }], ["non-Bearer token", { token_type: "mac" }], ["blank access", { access_token: " " }], ["missing personal ID token", { id_token: undefined }]]) {
|
|
210
|
+
await t.test(name, async () => {
|
|
211
|
+
const pending = flow({ tokenChanges: change }); await pending.callback();
|
|
212
|
+
await assert.rejects(pending.promise, (error) => /XAI_BROWSER_(TOKEN|ID_TOKEN)/.test(error.code) && !error.message.includes("mock-browser"));
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
for (const [name, implementation] of [["network", () => { throw new Error("sensitive-mock-token-detail"); }], ["HTTP error", () => json({ error_description: "sensitive-mock-token-detail" }, 400)], ["invalid JSON", () => new Response("sensitive-mock-token-detail")]]) {
|
|
216
|
+
await t.test(name, async () => {
|
|
217
|
+
const pending = flow({ tokenImpl: implementation }); await pending.callback();
|
|
218
|
+
await assert.rejects(pending.promise, (error) => error.code.startsWith("XAI_BROWSER_") && !error.message.includes("sensitive-mock-token-detail"));
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("ID token signature, nonce, issuer, audience, expiry, subject and key identity are enforced", async (t) => {
|
|
224
|
+
const cases = [
|
|
225
|
+
["nonce", { claims: { nonce: "wrong" } }], ["issuer", { claims: { iss: "https://evil.example" } }],
|
|
226
|
+
["audience", { claims: { aud: "other-client" } }], ["expiry", { claims: { exp: NOW / 1000 - 120 } }],
|
|
227
|
+
["subject", { claims: { sub: "" } }], ["blank subject", { claims: { sub: " " } }], ["kid", { jwtHeader: { kid: "unknown" } }],
|
|
228
|
+
["symmetric/none algorithm", { jwtHeader: { alg: "HS256" } }],
|
|
229
|
+
["invalid signature", { idTokenImpl: (nonce) => { const token = jwt(nonce).split("."); token[2] = Buffer.alloc(64, 1).toString("base64url"); return token.join("."); } }],
|
|
230
|
+
["duplicate key IDs", { jwks: { keys: [publicJwk, publicJwk] } }],
|
|
231
|
+
];
|
|
232
|
+
for (const [name, options] of cases) await t.test(name, async () => {
|
|
233
|
+
const pending = flow(options); await pending.callback();
|
|
234
|
+
await assert.rejects(pending.promise, (error) => error.code === "XAI_BROWSER_ID_TOKEN");
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("untrusted discovery endpoints and unsupported PKCE are rejected before notification", async (t) => {
|
|
239
|
+
for (const metadata of [{ token_endpoint: "https://evil.example/token" }, { authorization_endpoint: "http://auth.x.ai/authorize" }, { jwks_uri: "https://evil.example/jwks" }, { issuer: "https://evil.example" }, { code_challenge_methods_supported: ["plain"] }]) {
|
|
240
|
+
await t.test(JSON.stringify(metadata), async () => {
|
|
241
|
+
const pending = flow({ metadata });
|
|
242
|
+
await assert.rejects(pending.promise, (error) => error.code === "XAI_BROWSER_DISCOVERY");
|
|
243
|
+
assert.equal(pending.calls.length, 1);
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
test("discovery has its own deadline and never opens a listener when it stalls", async () => {
|
|
250
|
+
let notified = false;
|
|
251
|
+
await assert.rejects(loginXaiBrowser({ notify() { notified = true; } }, {
|
|
252
|
+
discoveryTimeoutMs: 30,
|
|
253
|
+
fetchImpl: () => new Promise(() => {}),
|
|
254
|
+
}), (error) => error.code === "XAI_BROWSER_REQUEST_TIMEOUT");
|
|
255
|
+
assert.equal(notified, false);
|
|
256
|
+
});
|