opencode-anyrouter-auth 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +245 -0
- package/LICENSE +21 -0
- package/README.md +224 -2
- package/UPSTREAM.md +96 -0
- package/generic.mjs +156 -0
- package/icon.png +0 -0
- package/index.mjs +52 -0
- package/lib/accounts.mjs +200 -0
- package/lib/catalog.mjs +138 -0
- package/lib/headers.mjs +65 -0
- package/lib/model-metadata.mjs +140 -0
- package/lib/model-registry.mjs +61 -0
- package/lib/protocols.mjs +129 -0
- package/lib/provider.mjs +501 -0
- package/lib/responses-filter.mjs +710 -0
- package/lib/site-client.mjs +585 -0
- package/lib/sse-delivery.mjs +140 -0
- package/package.json +48 -4
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
import { SITES, assertSameUser, beijingDay, withSiteIdentity } from "./accounts.mjs";
|
|
2
|
+
import { browserHeaders, customHeaders } from "./headers.mjs";
|
|
3
|
+
import { createContext, runInContext } from "node:vm";
|
|
4
|
+
|
|
5
|
+
export class SiteError extends Error {
|
|
6
|
+
constructor(kind, message, details = {}) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "SiteError";
|
|
9
|
+
this.kind = kind;
|
|
10
|
+
this.status = details.status ?? 0;
|
|
11
|
+
this.retryAfterMs = details.retryAfterMs ?? 0;
|
|
12
|
+
this.data = details.data ?? null;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function quotaNumber(value) {
|
|
17
|
+
if ((typeof value !== "string" && typeof value !== "number") || String(value).trim() === "") return null;
|
|
18
|
+
const number = Number(value);
|
|
19
|
+
return Number.isFinite(number) ? number : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function mergeCookies(previous = "", responseHeaders) {
|
|
23
|
+
const values = new Map();
|
|
24
|
+
for (const pair of previous.split(";")) {
|
|
25
|
+
const at = pair.indexOf("=");
|
|
26
|
+
if (at > 0) values.set(pair.slice(0, at).trim(), pair.slice(at + 1).trim());
|
|
27
|
+
}
|
|
28
|
+
const separate = responseHeaders?.getSetCookie?.() ?? [];
|
|
29
|
+
const lines = separate.length
|
|
30
|
+
? separate
|
|
31
|
+
: (responseHeaders?.get("set-cookie") ?? "").split(/,(?=\s*[^;,=\s]+=)/);
|
|
32
|
+
for (const line of lines) {
|
|
33
|
+
const pair = /^\s*([^=;,\s]+)=([^;]*)/.exec(line);
|
|
34
|
+
if (!pair) continue;
|
|
35
|
+
if (/;\s*max-age\s*=\s*0\s*(?:;|$)/i.test(line) || !pair[2]) values.delete(pair[1]);
|
|
36
|
+
else values.set(pair[1], pair[2]);
|
|
37
|
+
}
|
|
38
|
+
return [...values].map(([name, value]) => `${name}=${value}`).join("; ");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function mergeCookieStrings(...sources) {
|
|
42
|
+
const values = new Map();
|
|
43
|
+
for (const source of sources) {
|
|
44
|
+
for (const pair of String(source || "").split(";")) {
|
|
45
|
+
const at = pair.indexOf("=");
|
|
46
|
+
if (at > 0) values.set(pair.slice(0, at).trim(), pair.slice(at + 1).trim());
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return [...values].map(([name, value]) => `${name}=${value}`).join("; ");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function retryAfterMs(headers) {
|
|
53
|
+
let result = 0;
|
|
54
|
+
for (const name of ["retry-after-ms", "x-ms-retry-after-ms"]) {
|
|
55
|
+
const raw = headers?.get?.(name);
|
|
56
|
+
if (raw === null || raw === undefined) continue;
|
|
57
|
+
const value = Number(raw);
|
|
58
|
+
if (Number.isFinite(value) && value >= 0) result = Math.max(result, value);
|
|
59
|
+
}
|
|
60
|
+
const retryAfter = headers?.get?.("retry-after");
|
|
61
|
+
if (retryAfter !== null && retryAfter !== undefined) {
|
|
62
|
+
const seconds = Number(retryAfter);
|
|
63
|
+
const value = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retryAfter) - Date.now();
|
|
64
|
+
if (Number.isFinite(value) && value >= 0) result = Math.max(result, value);
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isShieldChallenge(response, raw) {
|
|
70
|
+
const contentType = response?.headers?.get?.("content-type") || "";
|
|
71
|
+
const text = String(raw || "");
|
|
72
|
+
if (/text\/html/i.test(contentType) &&
|
|
73
|
+
/var\s+arg1\s*=|acw_sc__v2|cdn_sec_tc|challenge-platform|<script/i.test(text)) {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
return /var\s+arg1\s*=/.test(text);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const CHALLENGE_SCRIPT_LIMIT = 128 * 1024;
|
|
80
|
+
|
|
81
|
+
export function solveWafChallenge(raw) {
|
|
82
|
+
const html = String(raw || "");
|
|
83
|
+
if (!html || html.length > CHALLENGE_SCRIPT_LIMIT * 2) return "";
|
|
84
|
+
const scripts = [...html.matchAll(/<script\b(?![^>]*\bsrc\s*=)[^>]*>([\s\S]*?)<\/script>/gi)]
|
|
85
|
+
.map(match => match[1]);
|
|
86
|
+
for (const script of scripts) {
|
|
87
|
+
if (script.length > CHALLENGE_SCRIPT_LIMIT ||
|
|
88
|
+
!/\barg1\s*=/.test(script) || !/acw_sc__v2/.test(script)) continue;
|
|
89
|
+
let cookie = "";
|
|
90
|
+
const document = {
|
|
91
|
+
get cookie() {
|
|
92
|
+
return cookie;
|
|
93
|
+
},
|
|
94
|
+
set cookie(value) {
|
|
95
|
+
const match = /(?:^|;\s*)acw_sc__v2=([^;]+)/i.exec(String(value));
|
|
96
|
+
if (match && /^[A-Za-z0-9._~-]{1,512}$/.test(match[1])) {
|
|
97
|
+
cookie = `acw_sc__v2=${match[1]}`;
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
location: { reload() {} },
|
|
101
|
+
body: { appendChild() {} },
|
|
102
|
+
createElement() {
|
|
103
|
+
return { style: {}, appendChild() {}, setAttribute() {}, remove() {} };
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
const window = {
|
|
107
|
+
document,
|
|
108
|
+
location: document.location,
|
|
109
|
+
navigator: { userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36" }
|
|
110
|
+
};
|
|
111
|
+
const context = createContext({
|
|
112
|
+
document,
|
|
113
|
+
window,
|
|
114
|
+
self: window,
|
|
115
|
+
top: window,
|
|
116
|
+
parent: window,
|
|
117
|
+
location: document.location,
|
|
118
|
+
navigator: window.navigator,
|
|
119
|
+
setTimeout() { return 0; },
|
|
120
|
+
clearTimeout() {},
|
|
121
|
+
console: { log() {}, warn() {}, error() {} }
|
|
122
|
+
});
|
|
123
|
+
try {
|
|
124
|
+
runInContext(script, context, { timeout: 1000 });
|
|
125
|
+
} catch {
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (cookie) return cookie;
|
|
129
|
+
}
|
|
130
|
+
return "";
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const CAPTCHA_RE = /captcha|turnstile|验证码|人机验证|challenge-platform|cf-chl|aliyun_waf_aa/i;
|
|
134
|
+
const FORBIDDEN_RE = /无权|权限不足|禁止|封禁|banned|forbidden|permission denied|access denied/i;
|
|
135
|
+
const RATE_RE = /请求次数过多|请求过多|限流|稍后再试|too many requests|rate.?limit|负载已饱和|负载已满|系统繁忙|繁忙|overloaded|server busy/i;
|
|
136
|
+
const INACTIVE_RE = /未开启签到|签到.*未开启|签到.*关闭|没有签到|不支持.*签到|签到.*不支持|活动.*未开启|活动.*结束|not support.*checkin|checkin.*not supported|inactive/i;
|
|
137
|
+
const ALREADY_RE = /已签到|已经签到|今日已|今天已|重复签到|已领取|already (?:signed|checked)|checked.?in today|no.?reward/i;
|
|
138
|
+
const CREDENTIAL_RE = /密码错误|用户名或密码|账号或密码|incorrect password|wrong password|未登录|登录已过期|登录失效|invalid (?:password|credential|token)|unauthorized|not logged/i;
|
|
139
|
+
const SITE_HEADER_NAMES = new Set([
|
|
140
|
+
"cookie", "new-api-user", "user-agent", "accept-language", "accept", "x-requested-with",
|
|
141
|
+
"sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "sec-fetch-dest", "sec-fetch-mode",
|
|
142
|
+
"sec-fetch-site", "priority"
|
|
143
|
+
]);
|
|
144
|
+
|
|
145
|
+
export function classifySiteMessage(message, status = 0) {
|
|
146
|
+
const value = String(message || "");
|
|
147
|
+
if (ALREADY_RE.test(value)) return "done";
|
|
148
|
+
if (CAPTCHA_RE.test(value)) return "captcha";
|
|
149
|
+
if (INACTIVE_RE.test(value)) return "inactive";
|
|
150
|
+
if (FORBIDDEN_RE.test(value) || status === 403) return "ineligible";
|
|
151
|
+
if (status === 401 || CREDENTIAL_RE.test(value)) return "ineligible";
|
|
152
|
+
if (status === 404 || status === 405) return "inactive";
|
|
153
|
+
if (status === 429 || RATE_RE.test(value)) return "failed";
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function siteFailure(response, data, raw, operation) {
|
|
158
|
+
const status = response?.status ?? 0;
|
|
159
|
+
const message = String(data?.message ?? data?.error?.message ?? data?.msg ?? "").trim();
|
|
160
|
+
const combined = `${message} ${String(raw || "").slice(0, 4000)}`;
|
|
161
|
+
const details = { status, retryAfterMs: retryAfterMs(response?.headers), data };
|
|
162
|
+
|
|
163
|
+
if (isShieldChallenge(response, raw)) {
|
|
164
|
+
return new SiteError("waf", "AnyRouter 返回了 WAF/JS 盾验证页,自动挑战未完成。请改用“AnyRouter 浏览器会话(WAF/JS 盾请用此入口;可签到)”入口,在浏览器完成验证后导入 /api/user/self。", details);
|
|
165
|
+
}
|
|
166
|
+
if (CAPTCHA_RE.test(combined)) {
|
|
167
|
+
return new SiteError("captcha", "站点要求 Turnstile/验证码,插件不会代解;请在浏览器完成后重试。", details);
|
|
168
|
+
}
|
|
169
|
+
if (ALREADY_RE.test(message)) {
|
|
170
|
+
return new SiteError("already", message || "今天已经签到。", details);
|
|
171
|
+
}
|
|
172
|
+
if (INACTIVE_RE.test(message) || status === 404 || status === 405) {
|
|
173
|
+
return new SiteError("inactive", message || "站点当前没有可用的签到接口。", details);
|
|
174
|
+
}
|
|
175
|
+
if (status === 401 || CREDENTIAL_RE.test(message) || (status === 403 && !FORBIDDEN_RE.test(message))) {
|
|
176
|
+
return new SiteError("credentials", `站点拒绝了 ${operation};请重新连接该账号。`, details);
|
|
177
|
+
}
|
|
178
|
+
if (status === 403 || FORBIDDEN_RE.test(message)) {
|
|
179
|
+
return new SiteError("forbidden", message || "账号没有执行该站点操作的权限。", details);
|
|
180
|
+
}
|
|
181
|
+
if (status === 429 || RATE_RE.test(message)) {
|
|
182
|
+
return new SiteError("rate-limit", message || "站点对该操作限流,请稍后再试。", details);
|
|
183
|
+
}
|
|
184
|
+
if (status >= 500) {
|
|
185
|
+
return new SiteError("unavailable", `站点暂时不可用(HTTP ${status}),请稍后再试。`, details);
|
|
186
|
+
}
|
|
187
|
+
if (status === 0) {
|
|
188
|
+
return new SiteError("unavailable", "站点请求失败或超时。", details);
|
|
189
|
+
}
|
|
190
|
+
if (message) {
|
|
191
|
+
return new SiteError("unavailable", message, details);
|
|
192
|
+
}
|
|
193
|
+
return new SiteError("unavailable", `站点未能完成 ${operation}(HTTP ${status})。`, details);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export async function readBoundedText(response, limit = 2 * 1024 * 1024) {
|
|
197
|
+
const reader = response.body?.getReader();
|
|
198
|
+
if (!reader) return "";
|
|
199
|
+
const decoder = new TextDecoder();
|
|
200
|
+
let size = 0;
|
|
201
|
+
let text = "";
|
|
202
|
+
try {
|
|
203
|
+
while (true) {
|
|
204
|
+
const { done, value } = await reader.read();
|
|
205
|
+
if (done) return text + decoder.decode();
|
|
206
|
+
size += value.byteLength;
|
|
207
|
+
if (size > limit) throw new SiteError("unavailable", "站点响应超过了账号 API 的大小上限。");
|
|
208
|
+
text += decoder.decode(value, { stream: true });
|
|
209
|
+
}
|
|
210
|
+
} finally {
|
|
211
|
+
await reader.cancel().catch(() => {});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function safeSiteHeaders(value) {
|
|
216
|
+
if (!value) return {};
|
|
217
|
+
const result = {};
|
|
218
|
+
let headers;
|
|
219
|
+
try {
|
|
220
|
+
headers = new Headers(value);
|
|
221
|
+
} catch {
|
|
222
|
+
return result;
|
|
223
|
+
}
|
|
224
|
+
for (const name of SITE_HEADER_NAMES) {
|
|
225
|
+
if (name === "cookie" || name === "new-api-user") continue;
|
|
226
|
+
if (headers.has(name)) result[name] = headers.get(name);
|
|
227
|
+
}
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function parseSessionHandoff(value, { allowedOrigins = Object.values(SITES) } = {}) {
|
|
232
|
+
const text = String(value ?? "").trim();
|
|
233
|
+
if (!text || text.length > 65536) {
|
|
234
|
+
throw new SiteError("credentials", "粘贴有边界的 AnyRouter 会话导出,或 Copy as cURL 请求文本。");
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
let cookie;
|
|
238
|
+
let userId;
|
|
239
|
+
let siteHeaders = {};
|
|
240
|
+
if (text.startsWith("{")) {
|
|
241
|
+
let data;
|
|
242
|
+
try {
|
|
243
|
+
data = JSON.parse(text);
|
|
244
|
+
} catch {
|
|
245
|
+
throw new SiteError("credentials", "会话导出不是合法的 JSON。");
|
|
246
|
+
}
|
|
247
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
248
|
+
throw new SiteError("credentials", "会话导出必须是一个对象。");
|
|
249
|
+
}
|
|
250
|
+
cookie = data.cookie ?? data.cookies;
|
|
251
|
+
userId = String(data.userId ?? data.user_id ?? "");
|
|
252
|
+
siteHeaders = safeSiteHeaders(data.siteHeaders ?? data.headers);
|
|
253
|
+
} else {
|
|
254
|
+
// Clipboard text is data, never a command. Only a site self request and
|
|
255
|
+
// the minimum browser headers are accepted. DevTools emits both
|
|
256
|
+
// `curl '<url>'` and `curl --url '<url>'` shapes; the origin, path and
|
|
257
|
+
// credential checks below stay strict either way.
|
|
258
|
+
if (!/^curl(?:\.exe)?\b/.test(text)) {
|
|
259
|
+
throw new SiteError("credentials", "请粘贴浏览器 DevTools 复制的 cURL 命令文本。");
|
|
260
|
+
}
|
|
261
|
+
const target = /(['"])(https:\/\/[^'"\s]+)\1/.exec(text);
|
|
262
|
+
let url;
|
|
263
|
+
try {
|
|
264
|
+
url = new URL(target?.[2]);
|
|
265
|
+
} catch {}
|
|
266
|
+
if (!url || !allowedOrigins.includes(url.origin) || url.pathname !== "/api/user/self" || url.username || url.password) {
|
|
267
|
+
throw new SiteError("credentials", "请复制 AnyRouter 的 /api/user/self 请求,而不是 GitHub 或 LinuxDO 的请求。");
|
|
268
|
+
}
|
|
269
|
+
const headers = new Headers();
|
|
270
|
+
for (const match of text.matchAll(/(?:^|\s)(?:-H|--header)\s+(?:'([^'\r\n]*)'|"([^"\r\n]*)")/g)) {
|
|
271
|
+
const value = match[1] ?? match[2];
|
|
272
|
+
const at = value.indexOf(":");
|
|
273
|
+
if (at <= 0) continue;
|
|
274
|
+
const name = value.slice(0, at).trim().toLowerCase();
|
|
275
|
+
if (SITE_HEADER_NAMES.has(name)) {
|
|
276
|
+
try {
|
|
277
|
+
headers.set(name, value.slice(at + 1).trim());
|
|
278
|
+
} catch {
|
|
279
|
+
throw new SiteError("credentials", "导出的站点请求头无效。");
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const cookies = /(?:^|\s)(?:-b|--cookie)\s+(['"])([^'"\r\n]*)\1/.exec(text);
|
|
284
|
+
cookie = headers.get("cookie") || cookies?.[2];
|
|
285
|
+
userId = headers.get("new-api-user") || "";
|
|
286
|
+
for (const name of SITE_HEADER_NAMES) {
|
|
287
|
+
if (name === "cookie" || name === "new-api-user") continue;
|
|
288
|
+
if (headers.has(name)) siteHeaders[name] = headers.get(name);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (typeof cookie !== "string" || !/(?:^|;\s*)session=[^;\s]+/.test(cookie) || /[\r\n]/.test(cookie) ||
|
|
293
|
+
!/^\d+$/.test(userId)) {
|
|
294
|
+
throw new SiteError("credentials", "导出必须包含 AnyRouter 的 session Cookie、可选 WAF Cookie,以及数字形式的 New-Api-User ID。");
|
|
295
|
+
}
|
|
296
|
+
return { session: cookie, userId, siteHeaders };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function createSiteClient({ fetchImpl = (...args) => fetch(...args), timeoutMs = 30000, now = Date.now } = {}) {
|
|
300
|
+
async function requestRaw(account, path, options = {}) {
|
|
301
|
+
const {
|
|
302
|
+
body,
|
|
303
|
+
anonymous = false,
|
|
304
|
+
cookies = "",
|
|
305
|
+
signal,
|
|
306
|
+
operation = "account read",
|
|
307
|
+
navigation = false,
|
|
308
|
+
allowChallenge = true
|
|
309
|
+
} = options;
|
|
310
|
+
if (account.siteURL !== SITES.top) {
|
|
311
|
+
throw new SiteError("credentials", "AnyRouter 登录和站点接口只支持 anyrouter.top。");
|
|
312
|
+
}
|
|
313
|
+
const headers = browserHeaders();
|
|
314
|
+
headers.set("referer", account.siteURL + (navigation ? "/login" : "/"));
|
|
315
|
+
if (navigation) {
|
|
316
|
+
headers.set("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8");
|
|
317
|
+
headers.set("cache-control", "max-age=0");
|
|
318
|
+
headers.set("sec-fetch-dest", "document");
|
|
319
|
+
headers.set("sec-fetch-mode", "navigate");
|
|
320
|
+
headers.set("sec-fetch-site", "none");
|
|
321
|
+
headers.set("upgrade-insecure-requests", "1");
|
|
322
|
+
headers.delete("priority");
|
|
323
|
+
} else {
|
|
324
|
+
headers.set("cache-control", "no-store");
|
|
325
|
+
}
|
|
326
|
+
if (body !== undefined) headers.set("origin", account.siteURL);
|
|
327
|
+
if (operation === "daily sign-in") headers.set("x-requested-with", "XMLHttpRequest");
|
|
328
|
+
customHeaders(account.headers).forEach((value, name) => headers.set(name, value));
|
|
329
|
+
customHeaders(account.siteHeaders).forEach((value, name) => headers.set(name, value));
|
|
330
|
+
|
|
331
|
+
const cookie = cookies || (anonymous ? "" : account.session);
|
|
332
|
+
if (cookie) headers.set("cookie", cookie);
|
|
333
|
+
if (!anonymous) {
|
|
334
|
+
if (account.accessToken) headers.set("authorization", account.accessToken);
|
|
335
|
+
if (account.userId) headers.set("new-api-user", account.userId);
|
|
336
|
+
} else {
|
|
337
|
+
headers.set("new-api-user", "-1");
|
|
338
|
+
}
|
|
339
|
+
if (body !== undefined) headers.set("content-type", "application/json");
|
|
340
|
+
|
|
341
|
+
const controller = new AbortController();
|
|
342
|
+
const abort = () => controller.abort(signal.reason);
|
|
343
|
+
if (signal?.aborted) abort();
|
|
344
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
345
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
346
|
+
try {
|
|
347
|
+
const response = await fetchImpl(account.siteURL + path, {
|
|
348
|
+
method: body === undefined ? "GET" : "POST",
|
|
349
|
+
headers,
|
|
350
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
351
|
+
redirect: "error",
|
|
352
|
+
signal: controller.signal
|
|
353
|
+
});
|
|
354
|
+
const raw = await readBoundedText(response);
|
|
355
|
+
let data;
|
|
356
|
+
try {
|
|
357
|
+
data = JSON.parse(raw);
|
|
358
|
+
} catch {}
|
|
359
|
+
const result = {
|
|
360
|
+
response,
|
|
361
|
+
raw,
|
|
362
|
+
data,
|
|
363
|
+
cookies: mergeCookies(cookie, response.headers),
|
|
364
|
+
status: response.status
|
|
365
|
+
};
|
|
366
|
+
if (allowChallenge && isShieldChallenge(response, raw)) {
|
|
367
|
+
const challengeCookie = solveWafChallenge(raw);
|
|
368
|
+
if (challengeCookie) {
|
|
369
|
+
return requestRaw(account, path, {
|
|
370
|
+
...options,
|
|
371
|
+
cookies: mergeCookieStrings(cookie, result.cookies, challengeCookie),
|
|
372
|
+
allowChallenge: false
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return result;
|
|
377
|
+
} catch (error) {
|
|
378
|
+
if (signal?.aborted) throw signal.reason;
|
|
379
|
+
if (error instanceof SiteError) throw error;
|
|
380
|
+
throw new SiteError("unavailable", "站点请求失败或超时;未执行自动重试登录。");
|
|
381
|
+
} finally {
|
|
382
|
+
clearTimeout(timer);
|
|
383
|
+
signal?.removeEventListener("abort", abort);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function request(account, path, options = {}) {
|
|
388
|
+
const result = await requestRaw(account, path, options);
|
|
389
|
+
if (!result.response.ok || !result.data || result.data.success !== true) {
|
|
390
|
+
throw siteFailure(result.response, result.data, result.raw, options.operation || "account read");
|
|
391
|
+
}
|
|
392
|
+
return { data: result.data.data, cookies: result.cookies, raw: result.raw, response: result.response };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function status(account, signal, cookies = account.session) {
|
|
396
|
+
return request(account, "/api/status", {
|
|
397
|
+
anonymous: true,
|
|
398
|
+
cookies,
|
|
399
|
+
signal,
|
|
400
|
+
operation: "site status read"
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async function bootstrapLoginPage(account, signal) {
|
|
405
|
+
return requestRaw(account, "/login", {
|
|
406
|
+
anonymous: true,
|
|
407
|
+
cookies: account.session,
|
|
408
|
+
signal,
|
|
409
|
+
navigation: true,
|
|
410
|
+
operation: "login page bootstrap"
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function login(account, signal) {
|
|
415
|
+
if (!account.username || !account.password) {
|
|
416
|
+
throw new SiteError("credentials", "需要提供 AnyRouter 站点用户名和密码。");
|
|
417
|
+
}
|
|
418
|
+
let bootstrap;
|
|
419
|
+
let siteStatus;
|
|
420
|
+
try {
|
|
421
|
+
siteStatus = await status(account, signal);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
if (error?.kind !== "waf") throw error;
|
|
424
|
+
bootstrap = await bootstrapLoginPage(account, signal);
|
|
425
|
+
siteStatus = await status(account, signal, bootstrap.cookies);
|
|
426
|
+
}
|
|
427
|
+
if (siteStatus.data?.turnstile_check === true) {
|
|
428
|
+
throw new SiteError("captcha", "AnyRouter 当前开启了 Turnstile;请在浏览器登录后导入站点会话。");
|
|
429
|
+
}
|
|
430
|
+
const loginOptions = cookies => ({
|
|
431
|
+
anonymous: true,
|
|
432
|
+
cookies,
|
|
433
|
+
body: { username: account.username, password: account.password },
|
|
434
|
+
signal,
|
|
435
|
+
operation: "password login"
|
|
436
|
+
});
|
|
437
|
+
let result;
|
|
438
|
+
try {
|
|
439
|
+
result = await request(
|
|
440
|
+
account,
|
|
441
|
+
"/api/user/login?turnstile=",
|
|
442
|
+
loginOptions(mergeCookieStrings(account.session, siteStatus.cookies))
|
|
443
|
+
);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
if (error?.kind !== "waf") throw error;
|
|
446
|
+
bootstrap ??= await bootstrapLoginPage(account, signal);
|
|
447
|
+
result = await request(
|
|
448
|
+
account,
|
|
449
|
+
"/api/user/login?turnstile=",
|
|
450
|
+
loginOptions(mergeCookieStrings(account.session, bootstrap.cookies, siteStatus.cookies))
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
if (!result.data || typeof result.data !== "object") {
|
|
454
|
+
throw new SiteError("unavailable", "站点登录响应缺少用户信息。");
|
|
455
|
+
}
|
|
456
|
+
return {
|
|
457
|
+
user: result.data,
|
|
458
|
+
status: siteStatus.data,
|
|
459
|
+
account: withSiteIdentity({ ...account, session: result.cookies }, result.data)
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function selfResponse(account) {
|
|
464
|
+
if (!account.userId || (!account.session && !account.accessToken)) {
|
|
465
|
+
throw new SiteError("credentials", "读取账号信息需要站点会话或系统访问令牌加用户 ID。");
|
|
466
|
+
}
|
|
467
|
+
const result = await request(account, "/api/user/self", { operation: "account read" });
|
|
468
|
+
assertSameUser(account, result.data);
|
|
469
|
+
return result;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async function self(account) {
|
|
473
|
+
return (await selfResponse(account)).data;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async function profile(account) {
|
|
477
|
+
const result = await selfResponse(account);
|
|
478
|
+
return {
|
|
479
|
+
user: result.data,
|
|
480
|
+
account: withSiteIdentity({ ...account, session: result.cookies }, result.data),
|
|
481
|
+
profileVerified: true
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
async function importSession(account, text) {
|
|
486
|
+
// Session handoff is deliberately limited to the confirmed AnyRouter
|
|
487
|
+
// origin. A legacy/custom siteURL must not turn clipboard text into an
|
|
488
|
+
// arbitrary cookie import target.
|
|
489
|
+
if (!Object.values(SITES).includes(new URL(account.siteURL).origin)) {
|
|
490
|
+
throw new SiteError("credentials", "会话导入只支持已知的 AnyRouter 站点。");
|
|
491
|
+
}
|
|
492
|
+
const handoff = parseSessionHandoff(text, { allowedOrigins: Object.values(SITES) });
|
|
493
|
+
if (account.userId && account.userId !== handoff.userId) {
|
|
494
|
+
throw new SiteError("credentials", "导出的会话属于另一个账号。");
|
|
495
|
+
}
|
|
496
|
+
const candidate = { ...account, ...handoff, accessToken: "", password: "" };
|
|
497
|
+
return profile(candidate);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async function selectKey(account, selection = "") {
|
|
501
|
+
const selected = String(selection).trim();
|
|
502
|
+
if (selected && !/^\d+$/.test(selected)) {
|
|
503
|
+
throw new SiteError("selection", "请指定一个现有 API key 的数字 ID。");
|
|
504
|
+
}
|
|
505
|
+
const result = await request(account, selected ? `/api/token/${selected}` : "/api/token/?p=0&size=100", {
|
|
506
|
+
operation: "API key lookup"
|
|
507
|
+
});
|
|
508
|
+
const items = selected ? [result.data] : Array.isArray(result.data) ? result.data : result.data?.items;
|
|
509
|
+
if (!Array.isArray(items)) {
|
|
510
|
+
throw new SiteError("unavailable", "站点没有返回 API key 列表。");
|
|
511
|
+
}
|
|
512
|
+
const active = items.filter(item => {
|
|
513
|
+
const expires = quotaNumber(item?.expired_time);
|
|
514
|
+
const remaining = quotaNumber(item?.remain_quota);
|
|
515
|
+
return item?.status === 1 && typeof item.key === "string" && item.key.trim() && !/[\s*]/.test(item.key) &&
|
|
516
|
+
(expires === null || expires <= 0 || expires * 1000 > now()) &&
|
|
517
|
+
(item.unlimited_quota === true || remaining === null || remaining > 0);
|
|
518
|
+
});
|
|
519
|
+
if (selected && active[0] && String(active[0].id) !== selected) {
|
|
520
|
+
throw new SiteError("selection", "站点返回了不同的 API key ID。");
|
|
521
|
+
}
|
|
522
|
+
const truncated = !selected && Number(result.data?.total) > items.length;
|
|
523
|
+
if (!active.length) {
|
|
524
|
+
throw new SiteError("selection", "没有可用的 API key。请先在网站上创建或启用一个 key,再重新连接。");
|
|
525
|
+
}
|
|
526
|
+
if (active.length !== 1 || truncated) {
|
|
527
|
+
const ids = active.slice(0, 10).map(item => String(item.id)).filter(id => /^\d+$/.test(id)).join(", ");
|
|
528
|
+
throw new SiteError("selection", `More than one key may be available. Select an existing key ID in advanced login settings${ids ? ` (IDs: ${ids})` : ""}.`);
|
|
529
|
+
}
|
|
530
|
+
return { key: active[0].key.trim(), keyId: String(active[0].id ?? "") };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async function signIn(account, signal) {
|
|
534
|
+
if (!account.session) {
|
|
535
|
+
throw new SiteError("credentials", "AnyRouter 签到需要有效的站点会话 Cookie。");
|
|
536
|
+
}
|
|
537
|
+
const result = await requestRaw({ ...account, accessToken: "" }, "/api/user/sign_in", {
|
|
538
|
+
body: {},
|
|
539
|
+
signal,
|
|
540
|
+
operation: "daily sign-in"
|
|
541
|
+
});
|
|
542
|
+
if (!result.response.ok) {
|
|
543
|
+
throw siteFailure(result.response, result.data, result.raw, "daily sign-in");
|
|
544
|
+
}
|
|
545
|
+
if (!result.data || typeof result.data !== "object") {
|
|
546
|
+
throw siteFailure(result.response, result.data, result.raw, "daily sign-in");
|
|
547
|
+
}
|
|
548
|
+
return {
|
|
549
|
+
success: result.data.success === true,
|
|
550
|
+
message: String(result.data.message ?? "").trim(),
|
|
551
|
+
data: result.data.data,
|
|
552
|
+
cookies: result.cookies,
|
|
553
|
+
status: result.status
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
function checkinResult(result) {
|
|
558
|
+
const message = result.message || "";
|
|
559
|
+
const outcome = result.success
|
|
560
|
+
? (ALREADY_RE.test(message) ? "done" : "claimed")
|
|
561
|
+
: (classifySiteMessage(message) || "failed");
|
|
562
|
+
const lastCheckin = {
|
|
563
|
+
outcome,
|
|
564
|
+
message: message || (outcome === "claimed" ? "AnyRouter 签到请求成功。" : "AnyRouter 未返回签到结果。")
|
|
565
|
+
};
|
|
566
|
+
const reward = quotaNumber(result.data?.reward ?? result.data?.credit);
|
|
567
|
+
if (Number.isFinite(reward) && reward > 0) lastCheckin.credit = reward;
|
|
568
|
+
return { lastCheckinDay: beijingDay(now()), lastCheckin };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
return {
|
|
572
|
+
request,
|
|
573
|
+
requestRaw,
|
|
574
|
+
status,
|
|
575
|
+
login,
|
|
576
|
+
self,
|
|
577
|
+
profile,
|
|
578
|
+
importSession,
|
|
579
|
+
selectKey,
|
|
580
|
+
signIn,
|
|
581
|
+
checkinResult
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
export const _internal = { classifySiteMessage, isShieldChallenge, retryAfterMs, siteFailure, solveWafChallenge };
|