@lks347/dsh-oauth 0.0.0-stage → 1.0.2
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 +101 -2
- package/app.js +1045 -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 +48 -0
- package/docs/RELEASE-1.0.2.md +8 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/docs/evidence/release-1.0.1.json +38 -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 +431 -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 +321 -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 +180 -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 +129 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +104 -0
- package/src/grants.test.js +340 -0
- package/src/index.js +676 -0
- package/src/local-imports.js +263 -0
- package/src/local-imports.test.js +201 -0
- package/src/media.js +152 -0
- package/src/models.js +610 -0
- package/src/models.test.js +503 -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 +160 -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,199 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const abortError = (message = "授权输入已撤回") => Object.assign(new Error(message), { name: "AbortError" });
|
|
4
|
+
const errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Bridge the harness interaction callbacks to short HTTP requests. Only the
|
|
8
|
+
* public snapshot is stored in `sessions`; answers and cancellation handles stay
|
|
9
|
+
* private and are never serialized or persisted.
|
|
10
|
+
*/
|
|
11
|
+
export function createAuthorizationSessions({ sessions = new Map(), readyTimeoutMs = 8000, attemptTimeoutMs = 10 * 60 * 1000, commitGraceMs = 90000 } = {}) {
|
|
12
|
+
const active = new Map();
|
|
13
|
+
|
|
14
|
+
function get(id) {
|
|
15
|
+
const state = sessions.get(id);
|
|
16
|
+
if (state === undefined) return undefined;
|
|
17
|
+
return {
|
|
18
|
+
attemptId: state.attemptId,
|
|
19
|
+
status: state.status ?? "pending",
|
|
20
|
+
pending: state.status === "pending",
|
|
21
|
+
url: state.url ?? "",
|
|
22
|
+
code: state.code ?? "",
|
|
23
|
+
message: state.message ?? "",
|
|
24
|
+
...(state.error ? { error: state.error } : {}),
|
|
25
|
+
...(state.prompt ? { prompt: {
|
|
26
|
+
...state.prompt,
|
|
27
|
+
...(state.prompt.options ? { options: state.prompt.options.map((option) => ({ ...option })) } : {}),
|
|
28
|
+
} } : {}),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function current(id, attemptId) {
|
|
33
|
+
const handle = active.get(id);
|
|
34
|
+
if (!handle || handle.state.status !== "pending") throw new Error("这次登录已经结束,请重新登录");
|
|
35
|
+
if (typeof attemptId !== "string" || handle.state.attemptId !== attemptId) {
|
|
36
|
+
throw new Error("登录尝试已更新,请刷新后重试");
|
|
37
|
+
}
|
|
38
|
+
return handle;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function publishPrompt(handle) {
|
|
42
|
+
const next = handle.prompts[0];
|
|
43
|
+
if (next) handle.state.prompt = next.public;
|
|
44
|
+
else delete handle.state.prompt;
|
|
45
|
+
handle.ready();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function removePrompt(handle, entry) {
|
|
49
|
+
const index = handle.prompts.indexOf(entry);
|
|
50
|
+
if (index >= 0) handle.prompts.splice(index, 1);
|
|
51
|
+
entry.signal?.removeEventListener("abort", entry.withdraw);
|
|
52
|
+
publishPrompt(handle);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function finish(handle, status, error) {
|
|
56
|
+
if (handle.state.status !== "pending") return;
|
|
57
|
+
handle.state.status = status;
|
|
58
|
+
if (error) handle.state.error = error;
|
|
59
|
+
clearTimeout(handle.lifetime);
|
|
60
|
+
for (const entry of [...handle.prompts]) {
|
|
61
|
+
removePrompt(handle, entry);
|
|
62
|
+
entry.reject(abortError(status === "authorized" ? "浏览器回调已完成" : "这次登录已经结束"));
|
|
63
|
+
}
|
|
64
|
+
handle.ready();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function begin(authorization, id, key) {
|
|
68
|
+
const existing = active.get(id);
|
|
69
|
+
if (existing?.state.status === "pending") return get(id);
|
|
70
|
+
const flow = authorization.describe(key);
|
|
71
|
+
if (flow?.inFlight) throw new Error("该提供商正在其他窗口登录,请先完成或取消那次登录");
|
|
72
|
+
const controller = new AbortController();
|
|
73
|
+
const state = { attemptId: randomUUID(), status: "pending", url: "", code: "", message: "正在启动提供商登录" };
|
|
74
|
+
let readyResolve;
|
|
75
|
+
const ready = new Promise((resolve) => { readyResolve = resolve; });
|
|
76
|
+
const handle = { state, authorization, key, controller, prompts: [], ready: readyResolve };
|
|
77
|
+
sessions.set(id, state);
|
|
78
|
+
active.set(id, handle);
|
|
79
|
+
const timeout = () => {
|
|
80
|
+
if (handle.state.status !== "pending") return;
|
|
81
|
+
if (authorization.isCommitting?.(key)) {
|
|
82
|
+
handle.commitDeadline ??= Date.now() + commitGraceMs;
|
|
83
|
+
if (Date.now() < handle.commitDeadline) {
|
|
84
|
+
state.message = "授权回调已收到,正在核验并保存,请稍候";
|
|
85
|
+
handle.lifetime = setTimeout(timeout, Math.min(1000, commitGraceMs));
|
|
86
|
+
handle.lifetime.unref?.();
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
finish(handle, "error", "登录等待超时,请重新登录");
|
|
91
|
+
controller.abort(abortError("登录等待超时"));
|
|
92
|
+
authorization.cancel?.(key);
|
|
93
|
+
};
|
|
94
|
+
handle.lifetime = setTimeout(timeout, attemptTimeoutMs);
|
|
95
|
+
handle.lifetime.unref?.();
|
|
96
|
+
|
|
97
|
+
const interaction = {
|
|
98
|
+
notify(notice) {
|
|
99
|
+
if (state.status !== "pending" || active.get(id) !== handle) return;
|
|
100
|
+
if (typeof notice.message === "string") state.message = notice.message;
|
|
101
|
+
if (typeof notice.url === "string" && notice.url.length > 0) {
|
|
102
|
+
try {
|
|
103
|
+
const url = new URL(notice.url);
|
|
104
|
+
if (url.protocol === "https:" || url.protocol === "http:") state.url = url.href;
|
|
105
|
+
} catch { /* A malformed notice must not navigate the browser. */ }
|
|
106
|
+
}
|
|
107
|
+
if (typeof notice.code === "string") state.code = notice.code;
|
|
108
|
+
handle.ready();
|
|
109
|
+
},
|
|
110
|
+
prompt(prompt) {
|
|
111
|
+
if (state.status !== "pending" || controller.signal.aborted || prompt.signal?.aborted) {
|
|
112
|
+
return Promise.reject(abortError());
|
|
113
|
+
}
|
|
114
|
+
if (!["text", "secret", "select"].includes(prompt.kind)) return Promise.reject(new Error("不支持的授权输入类型"));
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
const entry = {
|
|
117
|
+
public: {
|
|
118
|
+
id: randomUUID(),
|
|
119
|
+
kind: prompt.kind,
|
|
120
|
+
message: String(prompt.message ?? "请补充授权信息"),
|
|
121
|
+
...(typeof prompt.placeholder === "string" ? { placeholder: prompt.placeholder } : {}),
|
|
122
|
+
...(prompt.kind === "select" ? { options: (prompt.options ?? []).map((option) => ({
|
|
123
|
+
id: String(option.id), label: String(option.label),
|
|
124
|
+
...(typeof option.description === "string" ? { description: option.description } : {}),
|
|
125
|
+
})) } : {}),
|
|
126
|
+
},
|
|
127
|
+
resolve, reject, signal: prompt.signal,
|
|
128
|
+
};
|
|
129
|
+
entry.withdraw = () => {
|
|
130
|
+
removePrompt(handle, entry);
|
|
131
|
+
reject(abortError());
|
|
132
|
+
};
|
|
133
|
+
handle.prompts.push(entry);
|
|
134
|
+
prompt.signal?.addEventListener("abort", entry.withdraw, { once: true });
|
|
135
|
+
// Abort can race registration; do not leave a losing manual prompt open.
|
|
136
|
+
if (prompt.signal?.aborted) entry.withdraw();
|
|
137
|
+
else publishPrompt(handle);
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
// Defer begin so synchronous callback throws and rejections share one path.
|
|
142
|
+
void Promise.resolve().then(() => authorization.begin({ key, method: "oauth", interaction, signal: controller.signal }))
|
|
143
|
+
.then((outcome) => finish(handle, outcome.status === "authorized" ? "authorized" : "cancelled"))
|
|
144
|
+
.catch((error) => finish(handle, controller.signal.aborted ? "cancelled" : "error", controller.signal.aborted ? undefined : errorMessage(error)));
|
|
145
|
+
let readyTimer;
|
|
146
|
+
await Promise.race([ready, new Promise((resolve) => {
|
|
147
|
+
readyTimer = setTimeout(resolve, readyTimeoutMs);
|
|
148
|
+
})]);
|
|
149
|
+
clearTimeout(readyTimer);
|
|
150
|
+
return get(id);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function answer(id, { attemptId, promptId, value } = {}) {
|
|
154
|
+
const handle = current(id, attemptId);
|
|
155
|
+
const entry = handle.prompts[0];
|
|
156
|
+
if (!entry || entry.public.id !== promptId) throw new Error("这项授权输入已撤回或更新,请等待最新状态");
|
|
157
|
+
if (typeof value !== "string") throw new Error("需要填写授权输入");
|
|
158
|
+
if (value.length > 16384) throw new Error("授权输入过长");
|
|
159
|
+
if (entry.public.kind === "select" && !entry.public.options.some((option) => option.id === value)) {
|
|
160
|
+
throw new Error("请选择提供商给出的选项");
|
|
161
|
+
}
|
|
162
|
+
removePrompt(handle, entry);
|
|
163
|
+
entry.resolve(value);
|
|
164
|
+
return get(id);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function cancel(id, { attemptId } = {}) {
|
|
168
|
+
const state = sessions.get(id);
|
|
169
|
+
if (!state) throw new Error("没有这次登录记录");
|
|
170
|
+
if (typeof attemptId !== "string" || state.attemptId !== attemptId) throw new Error("登录尝试已更新,请刷新后重试");
|
|
171
|
+
if (state.status !== "pending") return get(id);
|
|
172
|
+
const handle = current(id, attemptId);
|
|
173
|
+
if (handle.authorization.isCommitting?.(handle.key)) {
|
|
174
|
+
handle.state.message = "授权回调已收到,正在核验并保存,请稍候";
|
|
175
|
+
return get(id);
|
|
176
|
+
}
|
|
177
|
+
finish(handle, "cancelled");
|
|
178
|
+
handle.controller.abort(abortError("用户取消登录"));
|
|
179
|
+
handle.authorization.cancel?.(handle.key);
|
|
180
|
+
return get(id);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function clear(id) {
|
|
184
|
+
const handle = active.get(id);
|
|
185
|
+
if (handle?.state.status === "pending") {
|
|
186
|
+
finish(handle, "cancelled");
|
|
187
|
+
handle.controller.abort(abortError("登录记录已移除"));
|
|
188
|
+
handle.authorization.cancel?.(handle.key);
|
|
189
|
+
}
|
|
190
|
+
active.delete(id);
|
|
191
|
+
sessions.delete(id);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function dispose() {
|
|
195
|
+
for (const id of active.keys()) clear(id);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return { begin, get, answer, cancel, clear, dispose };
|
|
199
|
+
}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import vm from "node:vm";
|
|
5
|
+
import { createAuthorizationSessions } from "./authorization.js";
|
|
6
|
+
|
|
7
|
+
const tick = () => new Promise((resolve) => setImmediate(resolve));
|
|
8
|
+
function service(run) {
|
|
9
|
+
const state = { interaction: null, signal: null, cancelCalls: 0 };
|
|
10
|
+
return Object.assign(state, {
|
|
11
|
+
describe: () => ({ inFlight: false }),
|
|
12
|
+
cancel: () => { state.cancelCalls += 1; },
|
|
13
|
+
async begin(request) {
|
|
14
|
+
state.interaction = request.interaction;
|
|
15
|
+
state.signal = request.signal;
|
|
16
|
+
return run(request);
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
test("notices return the device code, URL and real eventual outcome", async () => {
|
|
22
|
+
let complete;
|
|
23
|
+
const upstream = service(({ interaction }) => {
|
|
24
|
+
interaction.notify({ message: "Enter this code", url: "https://example.test/device", code: "ABCD-1234" });
|
|
25
|
+
return new Promise((resolve) => { complete = resolve; });
|
|
26
|
+
});
|
|
27
|
+
const manager = createAuthorizationSessions();
|
|
28
|
+
const snapshot = await manager.begin(upstream, "copilot", "key");
|
|
29
|
+
assert.equal(snapshot.code, "ABCD-1234");
|
|
30
|
+
assert.equal(snapshot.url, "https://example.test/device");
|
|
31
|
+
assert.equal(snapshot.status, "pending");
|
|
32
|
+
const duplicate = await manager.begin(upstream, "copilot", "key");
|
|
33
|
+
assert.equal(duplicate.attemptId, snapshot.attemptId);
|
|
34
|
+
complete({ status: "authorized" });
|
|
35
|
+
await tick();
|
|
36
|
+
assert.equal(manager.get("copilot").status, "authorized");
|
|
37
|
+
manager.dispose();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("manual prompts wait for the matching answer and never include the answer in snapshots", async () => {
|
|
41
|
+
let received;
|
|
42
|
+
const upstream = service(async ({ interaction }) => {
|
|
43
|
+
received = await interaction.prompt({ kind: "secret", message: "Paste code" });
|
|
44
|
+
return { status: "authorized" };
|
|
45
|
+
});
|
|
46
|
+
const manager = createAuthorizationSessions();
|
|
47
|
+
const snapshot = await manager.begin(upstream, "anthropic", "key");
|
|
48
|
+
assert.equal(snapshot.prompt.kind, "secret");
|
|
49
|
+
assert.throws(() => manager.answer("anthropic", { attemptId: "old", promptId: snapshot.prompt.id, value: "secret-value" }), /更新/);
|
|
50
|
+
assert.throws(() => manager.answer("anthropic", { attemptId: snapshot.attemptId, promptId: "old", value: "secret-value" }), /撤回/);
|
|
51
|
+
manager.answer("anthropic", { attemptId: snapshot.attemptId, promptId: snapshot.prompt.id, value: "secret-value" });
|
|
52
|
+
await tick();
|
|
53
|
+
assert.equal(received, "secret-value");
|
|
54
|
+
assert.equal(manager.get("anthropic").status, "authorized");
|
|
55
|
+
assert.ok(!JSON.stringify(manager.get("anthropic")).includes("secret-value"));
|
|
56
|
+
manager.dispose();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("callback-winning prompt withdrawal rejects and removes only that prompt", async () => {
|
|
60
|
+
const manual = new AbortController();
|
|
61
|
+
let promptResult;
|
|
62
|
+
let complete;
|
|
63
|
+
const upstream = service(({ interaction }) => {
|
|
64
|
+
promptResult = interaction.prompt({ kind: "text", message: "Paste callback", signal: manual.signal }).catch((error) => error.name);
|
|
65
|
+
return new Promise((resolve) => { complete = resolve; });
|
|
66
|
+
});
|
|
67
|
+
const manager = createAuthorizationSessions();
|
|
68
|
+
const snapshot = await manager.begin(upstream, "codex", "key");
|
|
69
|
+
assert.ok(snapshot.prompt);
|
|
70
|
+
manual.abort();
|
|
71
|
+
assert.equal(await promptResult, "AbortError");
|
|
72
|
+
assert.equal(manager.get("codex").prompt, undefined);
|
|
73
|
+
assert.equal(manager.get("codex").status, "pending");
|
|
74
|
+
complete({ status: "authorized" });
|
|
75
|
+
await tick();
|
|
76
|
+
assert.equal(manager.get("codex").status, "authorized");
|
|
77
|
+
manager.dispose();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("select prompts validate choices and expose queued questions in order", async () => {
|
|
81
|
+
let first, second;
|
|
82
|
+
const upstream = service(async ({ interaction }) => {
|
|
83
|
+
const choices = interaction.prompt({ kind: "select", message: "Choose mode", options: [{ id: "browser", label: "Browser" }] });
|
|
84
|
+
const code = interaction.prompt({ kind: "text", message: "Code" });
|
|
85
|
+
[first, second] = await Promise.all([choices, code]);
|
|
86
|
+
return { status: "authorized" };
|
|
87
|
+
});
|
|
88
|
+
const manager = createAuthorizationSessions();
|
|
89
|
+
const snapshot = await manager.begin(upstream, "test", "key");
|
|
90
|
+
assert.equal(snapshot.prompt.kind, "select");
|
|
91
|
+
assert.throws(() => manager.answer("test", { attemptId: snapshot.attemptId, promptId: snapshot.prompt.id, value: "invalid" }), /选项/);
|
|
92
|
+
manager.answer("test", { attemptId: snapshot.attemptId, promptId: snapshot.prompt.id, value: "browser" });
|
|
93
|
+
const next = manager.get("test");
|
|
94
|
+
assert.equal(next.prompt.message, "Code");
|
|
95
|
+
manager.answer("test", { attemptId: next.attemptId, promptId: next.prompt.id, value: "callback-code" });
|
|
96
|
+
await tick();
|
|
97
|
+
assert.deepEqual([first, second], ["browser", "callback-code"]);
|
|
98
|
+
manager.dispose();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test("cancel aborts the upstream and pending input, and stale cancel cannot touch a newer attempt", async () => {
|
|
102
|
+
const upstream = service(async ({ interaction }) => {
|
|
103
|
+
await interaction.prompt({ kind: "text", message: "Waiting" });
|
|
104
|
+
return { status: "authorized" };
|
|
105
|
+
});
|
|
106
|
+
const manager = createAuthorizationSessions();
|
|
107
|
+
const first = await manager.begin(upstream, "provider", "key");
|
|
108
|
+
assert.equal(manager.cancel("provider", { attemptId: first.attemptId }).status, "cancelled");
|
|
109
|
+
assert.equal(upstream.signal.aborted, true);
|
|
110
|
+
await tick();
|
|
111
|
+
const second = await manager.begin(upstream, "provider", "key");
|
|
112
|
+
assert.notEqual(first.attemptId, second.attemptId);
|
|
113
|
+
assert.throws(() => manager.cancel("provider", { attemptId: first.attemptId }), /更新/);
|
|
114
|
+
assert.equal(manager.get("provider").status, "pending");
|
|
115
|
+
manager.dispose();
|
|
116
|
+
await tick();
|
|
117
|
+
assert.equal(upstream.signal.aborted, true);
|
|
118
|
+
assert.equal(manager.get("provider"), undefined);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("upstream failures and timeout remain errors, while no first notice still returns pending", async () => {
|
|
122
|
+
const manager = createAuthorizationSessions({ readyTimeoutMs: 5, attemptTimeoutMs: 25 });
|
|
123
|
+
const upstream = service(() => new Promise(() => {}));
|
|
124
|
+
const pending = await manager.begin(upstream, "silent", "key");
|
|
125
|
+
assert.equal(pending.status, "pending");
|
|
126
|
+
await new Promise((resolve) => setTimeout(resolve, 35));
|
|
127
|
+
assert.equal(manager.get("silent").status, "error");
|
|
128
|
+
assert.match(manager.get("silent").error, /超时/);
|
|
129
|
+
assert.equal(upstream.signal.aborted, true);
|
|
130
|
+
const failing = service(() => { throw new Error("provider unavailable"); });
|
|
131
|
+
assert.equal((await manager.begin(failing, "failed", "key2")).error, "provider unavailable");
|
|
132
|
+
manager.dispose();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("unsafe notice URL is discarded and an external in-flight attempt is not invented", async () => {
|
|
136
|
+
const manager = createAuthorizationSessions();
|
|
137
|
+
const upstream = service(({ interaction }) => {
|
|
138
|
+
interaction.notify({ message: "Bad URL", url: "javascript:alert(1)" });
|
|
139
|
+
return new Promise(() => {});
|
|
140
|
+
});
|
|
141
|
+
assert.equal((await manager.begin(upstream, "badurl", "key")).url, "");
|
|
142
|
+
const other = { describe: () => ({ inFlight: true }) };
|
|
143
|
+
await assert.rejects(manager.begin(other, "other", "otherkey"), /其他窗口/);
|
|
144
|
+
manager.dispose();
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("accepted browser callback is allowed to finish saving despite a late cancel", async () => {
|
|
148
|
+
let complete;
|
|
149
|
+
const upstream = service(({ interaction }) => {
|
|
150
|
+
interaction.notify({ url: "https://auth.example.test/authorize" });
|
|
151
|
+
return new Promise((resolve) => { complete = resolve; });
|
|
152
|
+
});
|
|
153
|
+
upstream.isCommitting = () => true;
|
|
154
|
+
const manager = createAuthorizationSessions();
|
|
155
|
+
const started = await manager.begin(upstream, "xai", "key");
|
|
156
|
+
assert.equal(manager.cancel("xai", { attemptId: started.attemptId }).status, "pending");
|
|
157
|
+
assert.equal(upstream.signal.aborted, false);
|
|
158
|
+
assert.equal(upstream.cancelCalls, 0);
|
|
159
|
+
complete({ status: "authorized" });
|
|
160
|
+
await tick();
|
|
161
|
+
assert.equal(manager.get("xai").status, "authorized");
|
|
162
|
+
manager.dispose();
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("logout clear still invalidates a browser attempt while its callback is being saved", async () => {
|
|
166
|
+
let complete;
|
|
167
|
+
const upstream = service(({ interaction }) => {
|
|
168
|
+
interaction.notify({ url: "https://auth.example.test/authorize" });
|
|
169
|
+
return new Promise((resolve) => { complete = resolve; });
|
|
170
|
+
});
|
|
171
|
+
upstream.isCommitting = () => true;
|
|
172
|
+
const manager = createAuthorizationSessions();
|
|
173
|
+
await manager.begin(upstream, "xai", "key");
|
|
174
|
+
manager.clear("xai");
|
|
175
|
+
assert.equal(upstream.signal.aborted, true);
|
|
176
|
+
assert.equal(upstream.cancelCalls, 1);
|
|
177
|
+
complete({ status: "authorized" });
|
|
178
|
+
await tick();
|
|
179
|
+
assert.equal(manager.get("xai"), undefined);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test("an accepted callback has bounded extra time to complete rather than being lost at the waiting deadline", async () => {
|
|
183
|
+
let complete;
|
|
184
|
+
const upstream = service(({ interaction }) => {
|
|
185
|
+
interaction.notify({ url: "https://auth.example.test/authorize" });
|
|
186
|
+
return new Promise((resolve) => { complete = resolve; });
|
|
187
|
+
});
|
|
188
|
+
upstream.isCommitting = () => true;
|
|
189
|
+
const manager = createAuthorizationSessions({ attemptTimeoutMs: 10, commitGraceMs: 30 });
|
|
190
|
+
await manager.begin(upstream, "xai", "key");
|
|
191
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
192
|
+
assert.equal(manager.get("xai").status, "pending");
|
|
193
|
+
assert.equal(upstream.signal.aborted, false);
|
|
194
|
+
complete({ status: "authorized" });
|
|
195
|
+
await tick();
|
|
196
|
+
assert.equal(manager.get("xai").status, "authorized");
|
|
197
|
+
manager.dispose();
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
// The panel tests use a minimal DOM to exercise state and network boundaries
|
|
201
|
+
// without an installed browser, a real provider or any credentials.
|
|
202
|
+
async function panelHarness({ path = "/oauth", fetcher, popupBlocked = false } = {}) {
|
|
203
|
+
const elements = new Map();
|
|
204
|
+
class Element {
|
|
205
|
+
constructor() { this.hidden = false; this.value = ""; this.dataset = {}; this.isConnected = true; this.events = {}; this.children = new Map(); this.attributes = new Map(); this._html = ""; }
|
|
206
|
+
addEventListener(type, handler) { (this.events[type] ||= []).push(handler); }
|
|
207
|
+
setAttribute(name, value) { this.attributes.set(name, String(value)); }
|
|
208
|
+
getAttribute(name) { return this.attributes.get(name) ?? null; }
|
|
209
|
+
hasAttribute(name) { return this.attributes.has(name); }
|
|
210
|
+
focus() { document.activeElement = this; }
|
|
211
|
+
contains(node) { return node === this || [...this.children.values()].includes(node); }
|
|
212
|
+
append(node) { this.children.set(`child-${this.children.size}`, node); }
|
|
213
|
+
set innerHTML(value) {
|
|
214
|
+
this._html = value;
|
|
215
|
+
this.children = new Map();
|
|
216
|
+
for (const match of value.matchAll(/<(input|select|button|div)\b([^>]*)>/g)) {
|
|
217
|
+
const child = new Element();
|
|
218
|
+
child.dataset.promptId = /data-prompt-id="([^"]*)"/.exec(match[2])?.[1];
|
|
219
|
+
const id = /\bid="([^"]+)"/.exec(match[2])?.[1];
|
|
220
|
+
const classes = /\bclass="([^"]+)"/.exec(match[2])?.[1]?.split(/\s+/) || [];
|
|
221
|
+
if (id) { child.id = id; this.children.set(`#${id}`, child); }
|
|
222
|
+
if (classes.includes("dialog")) this.children.set(".dialog", child);
|
|
223
|
+
if (!this.children.has(match[1])) this.children.set(match[1], child);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
get innerHTML() { return this._html; }
|
|
227
|
+
querySelector(id) { return this.children.get(id) || null; }
|
|
228
|
+
querySelectorAll(selector) {
|
|
229
|
+
if (selector === "input, select") return [...new Set([...this.children.values()])].filter((child) => child.id?.startsWith("authorization-"));
|
|
230
|
+
return [];
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
for (const id of ["#count", "#rows", "#refresh", "#reset", "#modal", "#toast", ".lead", "#locale", "#page-kicker", "#page-title", "#providers-title"]) elements.set(id, new Element());
|
|
234
|
+
elements.get("#modal").hidden = true;
|
|
235
|
+
const document = {
|
|
236
|
+
documentElement: new Element(), activeElement: null,
|
|
237
|
+
createElement() { return new Element(); },
|
|
238
|
+
getElementById(id) { return this.querySelector(`#${id}`); },
|
|
239
|
+
querySelector(id) { return elements.get(id) || elements.get("#modal").querySelector(id.replace(/^#modal /, "")); },
|
|
240
|
+
querySelectorAll(selector) { return selector === ".nav button" ? [] : elements.get("#modal").querySelectorAll(selector); },
|
|
241
|
+
addEventListener() {},
|
|
242
|
+
};
|
|
243
|
+
const events = {};
|
|
244
|
+
const timers = new Map();
|
|
245
|
+
const calls = [];
|
|
246
|
+
let sequence = 0;
|
|
247
|
+
const popup = { closed: false, close() { this.closed = true; }, location: { replace(url) { calls.push(["navigate", url]); } } };
|
|
248
|
+
const window = {
|
|
249
|
+
addEventListener(type, handler) { events[type] = handler; },
|
|
250
|
+
open(url) { calls.push(["open", url]); return popupBlocked ? null : popup; },
|
|
251
|
+
setTimeout(fn) { timers.set(++sequence, fn); return sequence; }, clearTimeout(id) { timers.delete(id); },
|
|
252
|
+
setInterval(fn) { timers.set(++sequence, fn); return sequence; }, clearInterval(id) { timers.delete(id); },
|
|
253
|
+
DshOAuth: { loginOpener: () => null, runAuthorizeHooks: async () => true },
|
|
254
|
+
};
|
|
255
|
+
const localStorage = { getItem: () => null, setItem(key, value) { calls.push(["store", key, value]); } };
|
|
256
|
+
const navigator = { sendBeacon(url, body) { calls.push(["beacon", url, body]); return true; } };
|
|
257
|
+
const context = vm.createContext({ window, document, location: new URL(`http://panel.test${path}`), localStorage, navigator, URL, Blob,
|
|
258
|
+
fetch: async (url, options) => { calls.push(["fetch", url, options]); return fetcher(url, options); },
|
|
259
|
+
});
|
|
260
|
+
vm.runInContext('const PROVIDERS = [{ id: "anthropic", name: "Claude", cli: "dsh oauth login anthropic" }]; const FLOW_LABEL = {};', context);
|
|
261
|
+
vm.runInContext(await readFile(new URL("../app.js", import.meta.url), "utf8"), context);
|
|
262
|
+
await tick();
|
|
263
|
+
return { context, calls, events, elements, popup, evaluate: (source) => vm.runInContext(source, context) };
|
|
264
|
+
}
|
|
265
|
+
const response = (body, ok = true) => ({ ok, status: ok ? 200 : 400, json: async () => body });
|
|
266
|
+
const providersResponse = () => response({ providers: [{ id: "anthropic", name: "Claude", loggedIn: false }] });
|
|
267
|
+
|
|
268
|
+
test("hosted panel opens the popup before requesting login and displays the real device code", async () => {
|
|
269
|
+
const panel = await panelHarness({ fetcher: (url) => url.endsWith("providers") ? providersResponse() : response({ attemptId: "attempt", status: "pending", url: "https://example.test/auth", code: "ABCD", prompt: { id: "prompt", kind: "text", message: "Paste code" } }) });
|
|
270
|
+
await panel.evaluate("openLogin('anthropic')");
|
|
271
|
+
const openIndex = panel.calls.findIndex((call) => call[0] === "open");
|
|
272
|
+
const loginIndex = panel.calls.findIndex((call) => call[1] === "/oauth/api/login");
|
|
273
|
+
assert.ok(openIndex >= 0 && openIndex < loginIndex);
|
|
274
|
+
assert.ok(!panel.calls[openIndex][1].includes("preview=1"));
|
|
275
|
+
assert.match(panel.elements.get("#modal").innerHTML, /ABCD/);
|
|
276
|
+
assert.match(panel.elements.get("#modal").innerHTML, /Paste code/);
|
|
277
|
+
assert.ok(panel.calls.some((call) => call[0] === "navigate" && call[1] === "https://example.test/auth"));
|
|
278
|
+
panel.events.pagehide();
|
|
279
|
+
const beacon = panel.calls.find((call) => call[0] === "beacon");
|
|
280
|
+
assert.equal(beacon[1], "/oauth/api/login/cancel");
|
|
281
|
+
assert.deepEqual(JSON.parse(await beacon[2].text()), { provider: "anthropic", attemptId: "attempt" });
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
test("formal API failure cannot create a preview connection or react to simulated success", async () => {
|
|
285
|
+
const panel = await panelHarness({ fetcher: (url) => url.endsWith("providers") ? providersResponse() : response({ error: "upstream offline" }, false) });
|
|
286
|
+
await panel.evaluate("openLogin('anthropic')");
|
|
287
|
+
assert.match(panel.elements.get("#modal").innerHTML, /upstream offline/);
|
|
288
|
+
assert.equal(panel.evaluate("status.anthropic.loggedIn"), false);
|
|
289
|
+
await panel.events.message({ origin: "http://panel.test", source: panel.popup, data: { type: "dsh-oauth-preview", provider: "anthropic", ok: true } });
|
|
290
|
+
assert.equal(panel.evaluate("status.anthropic.loggedIn"), false);
|
|
291
|
+
assert.equal(panel.calls.filter((call) => call[0] === "open").length, 1);
|
|
292
|
+
assert.ok(!panel.calls.some((call) => call[0] === "store"));
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
test("no URL and a blocked popup keep the real attempt pending with manual input", async () => {
|
|
296
|
+
const panel = await panelHarness({ popupBlocked: true, fetcher: (url) => url.endsWith("providers") ? providersResponse() : response({ attemptId: "attempt", status: "pending", url: "", prompt: { id: "prompt", kind: "text", message: "Paste authorization code" } }) });
|
|
297
|
+
await panel.evaluate("openLogin('anthropic')");
|
|
298
|
+
assert.match(panel.elements.get("#modal").innerHTML, /Paste authorization code/);
|
|
299
|
+
assert.match(panel.elements.get("#modal").innerHTML, /拦截/);
|
|
300
|
+
assert.equal(panel.evaluate("activeLogin.snapshot.status"), "pending");
|
|
301
|
+
assert.equal(panel.calls.filter((call) => call[0] === "open").length, 1);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
test("static preview is explicit and does not probe the OAuth API", async () => {
|
|
305
|
+
const panel = await panelHarness({ path: "/index.html", fetcher: () => { throw new Error("must not fetch"); } });
|
|
306
|
+
assert.match(panel.elements.get("#count").textContent, /静态示例/);
|
|
307
|
+
await panel.evaluate("openLogin('anthropic')");
|
|
308
|
+
assert.ok(panel.calls.find((call) => call[0] === "open")[1].includes("preview=1"));
|
|
309
|
+
assert.ok(!panel.calls.some((call) => call[0] === "fetch"));
|
|
310
|
+
await panel.events.message({ origin: "http://panel.test", source: panel.popup, data: { type: "dsh-oauth-preview", provider: "anthropic", ok: true } });
|
|
311
|
+
assert.equal(panel.evaluate("status.anthropic.sourceLabel"), "静态预览");
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
test("manual answer is sent with attempt/prompt identity and cancellation reflects the server outcome", async () => {
|
|
316
|
+
const panel = await panelHarness({ fetcher: (url) => {
|
|
317
|
+
if (url.endsWith("providers")) return providersResponse();
|
|
318
|
+
if (url.endsWith("cancel")) return response({ attemptId: "attempt", status: "cancelled" });
|
|
319
|
+
if (url.endsWith("answer")) return response({ attemptId: "attempt", status: "pending" });
|
|
320
|
+
return response({ attemptId: "attempt", status: "pending", prompt: { id: "prompt", kind: "secret", message: "Paste code" } });
|
|
321
|
+
} });
|
|
322
|
+
await panel.evaluate("openLogin('anthropic')");
|
|
323
|
+
panel.elements.get("#modal").querySelector("#authorization-answer").value = "mock-callback";
|
|
324
|
+
await panel.evaluate('submitAuthorization({target:{id:"authorization-form"},preventDefault(){}})');
|
|
325
|
+
const submitted = panel.calls.find((call) => call[1] === "/oauth/api/login/answer");
|
|
326
|
+
assert.deepEqual(JSON.parse(submitted[2].body), { provider: "anthropic", attemptId: "attempt", promptId: "prompt", value: "mock-callback" });
|
|
327
|
+
assert.ok(!panel.calls.some((call) => call[0] === "store"));
|
|
328
|
+
await panel.evaluate("cancelAuthorization()");
|
|
329
|
+
assert.match(panel.elements.get("#modal").innerHTML, /已取消/);
|
|
330
|
+
assert.equal(panel.evaluate("pendingId"), null);
|
|
331
|
+
assert.equal(panel.popup.closed, true);
|
|
332
|
+
});
|