opencode-anyrouter-auth 0.0.0-stage → 0.1.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/DESIGN.md +255 -0
- package/LICENSE +21 -0
- package/README.md +226 -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 +151 -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
package/lib/provider.mjs
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
API_ENDPOINTS,
|
|
5
|
+
PROVIDER,
|
|
6
|
+
SITES,
|
|
7
|
+
accountCapabilities,
|
|
8
|
+
apiEndpointChoice,
|
|
9
|
+
beijingDay,
|
|
10
|
+
protocolBase,
|
|
11
|
+
readAccount,
|
|
12
|
+
saveAccount
|
|
13
|
+
} from "./accounts.mjs";
|
|
14
|
+
import { createSiteClient, quotaNumber } from "./site-client.mjs";
|
|
15
|
+
import { MODEL_HINT_HEADER, customHeaders, inferenceHeaders } from "./headers.mjs";
|
|
16
|
+
import { createCatalog, protocolOfURL } from "./catalog.mjs";
|
|
17
|
+
import { createModelRegistry } from "./model-registry.mjs";
|
|
18
|
+
|
|
19
|
+
const required = value => typeof value === "string" && value.length ? undefined : "This field is required.";
|
|
20
|
+
const advanced = { key: "advanced", op: "eq", value: "yes" };
|
|
21
|
+
const SESSION_MODES = new Set(["github", "linuxdo", "session"]);
|
|
22
|
+
const PLUGIN_ICON = `data:image/png;base64,${readFileSync(new URL("../icon.png", import.meta.url)).toString("base64")}`;
|
|
23
|
+
|
|
24
|
+
function prompts(mode) {
|
|
25
|
+
const out = [];
|
|
26
|
+
if (mode === "api-key") {
|
|
27
|
+
out.push({
|
|
28
|
+
type: "text",
|
|
29
|
+
key: "email",
|
|
30
|
+
message: "账号邮箱(可选,不是显示别名)",
|
|
31
|
+
placeholder: "模型 key 无法查询账号身份;显示别名请在添加后使用 Magpie 原生改名",
|
|
32
|
+
validate: value => !value?.trim() || /^[^\s@]+@[^\s@]+$/.test(value.trim()) ? undefined : "请输入账号邮箱;显示别名请在添加后设置。"
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
if (mode === "password") {
|
|
36
|
+
out.push(
|
|
37
|
+
{
|
|
38
|
+
type: "select",
|
|
39
|
+
key: "checkinEnabled",
|
|
40
|
+
message: "开启每日自动签到?这会把 AnyRouter 站点密码保存在本地。",
|
|
41
|
+
options: [
|
|
42
|
+
{ label: "否 - 只用这次,不保存密码", value: "no" },
|
|
43
|
+
{ label: "是 - 保存密码用于每日签到", value: "yes" }
|
|
44
|
+
]
|
|
45
|
+
},
|
|
46
|
+
{ type: "text", key: "username", message: "AnyRouter 站点用户名或邮箱", validate: required },
|
|
47
|
+
{ type: "password", key: "password", message: "AnyRouter 站点密码(不是 GitHub 或 LinuxDO 密码)", validate: required }
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
if (SESSION_MODES.has(mode)) {
|
|
51
|
+
out.push({
|
|
52
|
+
type: "select",
|
|
53
|
+
key: "checkinEnabled",
|
|
54
|
+
message: "使用这个站点会话执行每日签到?会话过期后需要重新导入。",
|
|
55
|
+
options: [
|
|
56
|
+
{ label: "否 - 只用于账号信息和模型连接", value: "no" },
|
|
57
|
+
{ label: "是 - 保存会话用于每日签到", value: "yes" }
|
|
58
|
+
]
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (mode === "access-token") {
|
|
62
|
+
out.push(
|
|
63
|
+
{ type: "password", key: "accessToken", message: "AnyRouter 系统访问令牌(不是模型 API key)", validate: required },
|
|
64
|
+
{ type: "text", key: "userId", message: "AnyRouter user ID (New-Api-User)", validate: value => /^\d+$/.test(value) ? undefined : "请输入数字形式的站点用户 ID。" }
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
out.push({
|
|
68
|
+
type: "select",
|
|
69
|
+
key: "apiEndpoint",
|
|
70
|
+
message: "模型 API 端点",
|
|
71
|
+
options: [
|
|
72
|
+
{ label: "anyrouter.top(默认)", value: "top" },
|
|
73
|
+
{ label: "a-ocnfniawgw.cn-shanghai.fcapp.run(备用 API)", value: "fcapp" }
|
|
74
|
+
]
|
|
75
|
+
});
|
|
76
|
+
out.push({
|
|
77
|
+
type: "select",
|
|
78
|
+
key: "advanced",
|
|
79
|
+
message: "展开高级账号设置?供应商/模型原生请求头始终可用。",
|
|
80
|
+
options: [{ label: "否", value: "no" }, { label: "是", value: "yes" }]
|
|
81
|
+
});
|
|
82
|
+
if (mode !== "api-key") {
|
|
83
|
+
out.push({
|
|
84
|
+
type: "text",
|
|
85
|
+
key: "keyId",
|
|
86
|
+
message: "使用指定的 API key ID(只有一个可用 key 时可留空)",
|
|
87
|
+
when: advanced,
|
|
88
|
+
validate: value => !value || /^\d+$/.test(value) ? undefined : "请输入数字形式的 API key ID。"
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
out.push(
|
|
92
|
+
{
|
|
93
|
+
type: "text",
|
|
94
|
+
key: "headers",
|
|
95
|
+
message: "自定义请求头(可选,每行一条 Name: value)",
|
|
96
|
+
when: advanced,
|
|
97
|
+
validate: value => {
|
|
98
|
+
try {
|
|
99
|
+
customHeaders(value);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
return error.message;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
);
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function accountFromInputs(mode, inputs = {}) {
|
|
110
|
+
const checkinEnabled = (mode === "password" || SESSION_MODES.has(mode)) && inputs.checkinEnabled === "yes";
|
|
111
|
+
const apiEndpoint = apiEndpointChoice(inputs.apiEndpoint || "top");
|
|
112
|
+
const account = {
|
|
113
|
+
mode,
|
|
114
|
+
site: "top",
|
|
115
|
+
siteURL: SITES.top,
|
|
116
|
+
apiBase: protocolBase(API_ENDPOINTS[apiEndpoint]),
|
|
117
|
+
key: "",
|
|
118
|
+
keyId: inputs.keyId || "",
|
|
119
|
+
label: String(inputs.label ?? inputs.email ?? "").trim(),
|
|
120
|
+
email: "",
|
|
121
|
+
username: mode === "password" ? String(inputs.username || "").trim() : "",
|
|
122
|
+
password: mode === "password" ? inputs.password || "" : "",
|
|
123
|
+
session: "",
|
|
124
|
+
accessToken: mode === "access-token" ? String(inputs.accessToken || "").trim() : "",
|
|
125
|
+
userId: mode === "access-token" ? String(inputs.userId || "").trim() : "",
|
|
126
|
+
headers: inputs.headers || "",
|
|
127
|
+
checkinEnabled
|
|
128
|
+
};
|
|
129
|
+
customHeaders(account.headers);
|
|
130
|
+
return account;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const failed = error => ({ type: "failed", error: error.message || "站点未能完成登录。" });
|
|
134
|
+
|
|
135
|
+
function requestURL(request, init, headers, account, provider, explicit) {
|
|
136
|
+
const original = new URL(request instanceof Request ? request.url : String(request));
|
|
137
|
+
const protocol = protocolOfURL(original.href);
|
|
138
|
+
if (!protocol) return original.href;
|
|
139
|
+
let id = headers.get(MODEL_HINT_HEADER);
|
|
140
|
+
if (!id && init.body) {
|
|
141
|
+
try {
|
|
142
|
+
const body = typeof init.body === "string"
|
|
143
|
+
? init.body
|
|
144
|
+
: ArrayBuffer.isView(init.body) ? new TextDecoder().decode(init.body) : "";
|
|
145
|
+
const model = JSON.parse(body).model;
|
|
146
|
+
if (typeof model === "string") id = model;
|
|
147
|
+
} catch {}
|
|
148
|
+
}
|
|
149
|
+
if (!id && protocol === "gemini") {
|
|
150
|
+
id = decodeURIComponent(original.pathname.match(/\/models\/([^/]+):[^/]+$/)?.[1] || "");
|
|
151
|
+
}
|
|
152
|
+
const [name, model] = Object.entries(provider.models ?? {})
|
|
153
|
+
.find(([name, model]) => name === id || model.api?.id === id) ?? [id, null];
|
|
154
|
+
const user = explicit.models?.[name] ||
|
|
155
|
+
Object.entries(explicit.models ?? {}).find(([name, model]) => (model.id || name) === id)?.[1];
|
|
156
|
+
const isOfficial = value => [...Object.values(SITES), ...Object.values(API_ENDPOINTS)].includes(new URL(value).origin);
|
|
157
|
+
const isDefaultSiteBase = value => {
|
|
158
|
+
const parsed = new URL(value);
|
|
159
|
+
const path = parsed.pathname.replace(/\/+$/, "");
|
|
160
|
+
return isOfficial(value) && ["", "/", "/v1", "/v1beta"].includes(path);
|
|
161
|
+
};
|
|
162
|
+
const userModelBase = user?.provider?.api || "";
|
|
163
|
+
const catalogModelBase = model?.api?.url || "";
|
|
164
|
+
const modelBase = userModelBase ||
|
|
165
|
+
(catalogModelBase && !isDefaultSiteBase(catalogModelBase) ? catalogModelBase : "");
|
|
166
|
+
const accountApiBase = account.apiBase && isDefaultSiteBase(account.apiBase)
|
|
167
|
+
? protocolBase(account.apiBase, protocol)
|
|
168
|
+
: account.apiBase;
|
|
169
|
+
const configuredBase = accountApiBase ||
|
|
170
|
+
(explicit.api && !isDefaultSiteBase(explicit.api) ? explicit.api : "");
|
|
171
|
+
const override = modelBase || configuredBase || protocolBase(account.siteURL, protocol);
|
|
172
|
+
const base = override.replace(/\/+$/, "");
|
|
173
|
+
if (original.href.startsWith(base + "/")) return original.href;
|
|
174
|
+
const suffix = original.pathname.match(/\/(?:responses|chat\/completions|messages)\/?$|\/models\/[^/]+:(?:streamGenerateContent|generateContent)$/)?.[0];
|
|
175
|
+
return base + suffix + original.search;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function checkinFailure(error) {
|
|
179
|
+
const kind = error?.kind;
|
|
180
|
+
const outcome = kind === "captcha" || kind === "waf" ? "captcha"
|
|
181
|
+
: kind === "credentials" || kind === "forbidden" ? "ineligible"
|
|
182
|
+
: kind === "inactive" ? "inactive"
|
|
183
|
+
: kind === "already" ? "done"
|
|
184
|
+
: "failed";
|
|
185
|
+
return { outcome, message: error?.message || "AnyRouter 签到失败。" };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function createProvider(input = {}, options = {}, dependencies = {}) {
|
|
189
|
+
const fetchImpl = dependencies.fetchImpl || ((...args) => fetch(...args));
|
|
190
|
+
const now = dependencies.now || Date.now;
|
|
191
|
+
const site = createSiteClient({
|
|
192
|
+
fetchImpl,
|
|
193
|
+
now,
|
|
194
|
+
timeoutMs: options.siteTimeoutMs ?? 30000
|
|
195
|
+
});
|
|
196
|
+
let explicit = {};
|
|
197
|
+
const compatibility = () => input.magpie?.option?.(PROVIDER, "send-codex-headers") !== false;
|
|
198
|
+
const loadRegistry = dependencies.loadRegistry || createModelRegistry({
|
|
199
|
+
fetchImpl,
|
|
200
|
+
...(options.modelsRegistryPath ? { paths: [options.modelsRegistryPath] } : {})
|
|
201
|
+
});
|
|
202
|
+
const catalog = createCatalog({
|
|
203
|
+
site,
|
|
204
|
+
explicit: () => explicit,
|
|
205
|
+
compatibility,
|
|
206
|
+
fetchImpl,
|
|
207
|
+
loadRegistry
|
|
208
|
+
});
|
|
209
|
+
const pending = new Map();
|
|
210
|
+
const completed = new Map();
|
|
211
|
+
const quotaPerUnit = options.quotaPerUnit ?? 500000;
|
|
212
|
+
if (typeof quotaPerUnit !== "number" || !Number.isFinite(quotaPerUnit) || quotaPerUnit <= 0) {
|
|
213
|
+
throw new Error("quotaPerUnit must be a positive number.");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function finishLogin(result, selection) {
|
|
217
|
+
const account = result.profileVerified
|
|
218
|
+
? result.account
|
|
219
|
+
: (await site.profile(result.account)).account;
|
|
220
|
+
const key = await site.selectKey(account, selection);
|
|
221
|
+
const state = { ...account, ...key };
|
|
222
|
+
const { type, ...record } = saveAccount(state);
|
|
223
|
+
return { type: "success", ...record };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const methods = [
|
|
227
|
+
{
|
|
228
|
+
type: "api",
|
|
229
|
+
keyless: true,
|
|
230
|
+
label: "AnyRouter 账号密码(可处理 acw_sc__v2 JS 盾;Turnstile 需浏览器;可选签到)",
|
|
231
|
+
prompts: prompts("password"),
|
|
232
|
+
async authorize(inputs) {
|
|
233
|
+
try {
|
|
234
|
+
return await finishLogin(
|
|
235
|
+
await site.login(accountFromInputs("password", inputs)),
|
|
236
|
+
inputs?.keyId
|
|
237
|
+
);
|
|
238
|
+
} catch (error) {
|
|
239
|
+
return failed(error);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
...["github", "linuxdo"].map(provider => ({
|
|
244
|
+
type: "oauth",
|
|
245
|
+
label: provider === "github" ? "使用 GitHub 登录 AnyRouter" : "使用 LinuxDO 登录 AnyRouter",
|
|
246
|
+
prompts: prompts(provider),
|
|
247
|
+
async authorize(inputs) {
|
|
248
|
+
const account = accountFromInputs(provider, inputs);
|
|
249
|
+
let used = false;
|
|
250
|
+
return {
|
|
251
|
+
url: account.siteURL + "/login",
|
|
252
|
+
method: "code",
|
|
253
|
+
instructions: `在 AnyRouter 登录页选择 ${provider === "github" ? "GitHub" : "LinuxDO"} 并完成正常登录。登录后打开浏览器 DevTools > Network,刷新账号页,把 /api/user/self 请求复制为 cURL 粘贴到这里。只导入 AnyRouter 会话和用户 ID,不会执行命令;也接受包含 cookie 和 userId 的 JSON 导出。`,
|
|
254
|
+
async callback(value) {
|
|
255
|
+
if (used) return failed(new Error("这份回传已被使用,请重新发起登录。"));
|
|
256
|
+
used = true;
|
|
257
|
+
try {
|
|
258
|
+
return await finishLogin(await site.importSession(account, value), inputs?.keyId);
|
|
259
|
+
} catch (error) {
|
|
260
|
+
return failed(error);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
})),
|
|
266
|
+
{
|
|
267
|
+
type: "oauth",
|
|
268
|
+
label: "AnyRouter 浏览器会话(WAF/JS 盾请用此入口;可签到)",
|
|
269
|
+
prompts: prompts("session"),
|
|
270
|
+
async authorize(inputs) {
|
|
271
|
+
const account = accountFromInputs("session", inputs);
|
|
272
|
+
let used = false;
|
|
273
|
+
return {
|
|
274
|
+
url: account.siteURL + "/login",
|
|
275
|
+
method: "code",
|
|
276
|
+
instructions: "在浏览器完成 AnyRouter 登录和 WAF/JS 盾验证。然后打开 DevTools > Network,刷新账号页,把 /api/user/self 请求复制为 cURL 粘贴到这里。导出应包含 session Cookie;如站点还要求 WAF 验证,请一并保留 acw_tc、cdn_sec_tc、acw_sc__v2。插件只解析文本,不执行命令。",
|
|
277
|
+
async callback(value) {
|
|
278
|
+
if (used) return failed(new Error("这份回传已被使用,请重新发起登录。"));
|
|
279
|
+
used = true;
|
|
280
|
+
try {
|
|
281
|
+
return await finishLogin(await site.importSession(account, value), inputs?.keyId);
|
|
282
|
+
} catch (error) {
|
|
283
|
+
return failed(error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
{
|
|
290
|
+
type: "api",
|
|
291
|
+
keyless: true,
|
|
292
|
+
label: "AnyRouter 系统访问令牌(无每日签到)",
|
|
293
|
+
prompts: prompts("access-token"),
|
|
294
|
+
async authorize(inputs) {
|
|
295
|
+
try {
|
|
296
|
+
return await finishLogin(
|
|
297
|
+
await site.profile(accountFromInputs("access-token", inputs)),
|
|
298
|
+
inputs?.keyId
|
|
299
|
+
);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
return failed(error);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
type: "api",
|
|
307
|
+
label: "AnyRouter 模型 API key(仅推理)",
|
|
308
|
+
placeholder: "模型 API key",
|
|
309
|
+
prompts: prompts("api-key")
|
|
310
|
+
}
|
|
311
|
+
];
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
async config(cfg) {
|
|
315
|
+
cfg.provider ??= {};
|
|
316
|
+
explicit = structuredClone(cfg.provider[PROVIDER] ?? {});
|
|
317
|
+
cfg.provider[PROVIDER] ??= {
|
|
318
|
+
name: "AnyRouter",
|
|
319
|
+
npm: "@ai-sdk/openai",
|
|
320
|
+
api: SITES.top + "/v1",
|
|
321
|
+
models: {}
|
|
322
|
+
};
|
|
323
|
+
},
|
|
324
|
+
auth: {
|
|
325
|
+
provider: PROVIDER,
|
|
326
|
+
methods,
|
|
327
|
+
icon: PLUGIN_ICON,
|
|
328
|
+
options: [{
|
|
329
|
+
key: "send-codex-headers",
|
|
330
|
+
label: "默认兼容客户端请求头",
|
|
331
|
+
description: "Responses 协议的模型请求自动使用 codex 客户端身份覆盖网关默认请求头;账号自定义请求头始终优先。",
|
|
332
|
+
default: true
|
|
333
|
+
}],
|
|
334
|
+
async loader(getAuth, provider) {
|
|
335
|
+
const state = readAccount(await getAuth(), provider);
|
|
336
|
+
if (!state) return {};
|
|
337
|
+
return {
|
|
338
|
+
apiKey: state.key,
|
|
339
|
+
async fetch(request, init = {}) {
|
|
340
|
+
const account = readAccount(await getAuth(), provider);
|
|
341
|
+
if (!account?.key) {
|
|
342
|
+
throw new Error("This account has no model API key. Reconnect it before sending requests.");
|
|
343
|
+
}
|
|
344
|
+
if ((state.userId && account.userId && state.userId !== account.userId) ||
|
|
345
|
+
state.apiBase !== account.apiBase ||
|
|
346
|
+
((!state.userId || !account.userId) && state.key !== account.key)) {
|
|
347
|
+
throw Object.assign(
|
|
348
|
+
new Error("The selected account changed during this request. Start a new request; no data was sent with the replacement account."),
|
|
349
|
+
{ code: "account_changed", status: 409, retryable: false }
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
const incoming = new Headers(request instanceof Request ? request.headers : undefined);
|
|
353
|
+
new Headers(init.headers).forEach((value, name) => incoming.set(name, value));
|
|
354
|
+
const url = requestURL(request, init, incoming, account, provider, explicit);
|
|
355
|
+
const headers = inferenceHeaders(account, incoming, protocolOfURL(request), compatibility());
|
|
356
|
+
const target = request instanceof Request ? new Request(url, request) : url;
|
|
357
|
+
return fetchImpl(target, { ...init, headers });
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
},
|
|
361
|
+
async usage(getAuth, provider) {
|
|
362
|
+
const account = readAccount(await getAuth(), provider);
|
|
363
|
+
if (!account) return { error: "未连接账号。", windows: [], signIn: "kept" };
|
|
364
|
+
if (account.mode === "api-key") {
|
|
365
|
+
return { plan: "API key - 仅推理", windows: [], signIn: "kept" };
|
|
366
|
+
}
|
|
367
|
+
try {
|
|
368
|
+
const user = await site.self(account);
|
|
369
|
+
const quota = quotaNumber(user.quota);
|
|
370
|
+
if (quota === null) {
|
|
371
|
+
return { error: "站点没有返回剩余余额。", windows: [], signIn: "kept" };
|
|
372
|
+
}
|
|
373
|
+
const balance = quota / quotaPerUnit;
|
|
374
|
+
const display = "$" + balance.toFixed(Math.abs(balance) < 0.01 && balance !== 0 ? 6 : 2);
|
|
375
|
+
return {
|
|
376
|
+
balance: display,
|
|
377
|
+
signIn: "kept",
|
|
378
|
+
windows: [{ name: "AnyRouter 钱包", balance: Math.max(0, balance), unit: "USD", display }]
|
|
379
|
+
};
|
|
380
|
+
} catch (error) {
|
|
381
|
+
return { error: error.message, windows: [], signIn: "kept" };
|
|
382
|
+
}
|
|
383
|
+
},
|
|
384
|
+
async checkin(getAuth, provider) {
|
|
385
|
+
const auth = await getAuth();
|
|
386
|
+
const account = readAccount(auth, provider);
|
|
387
|
+
if (!accountCapabilities(account).checkin) {
|
|
388
|
+
return {
|
|
389
|
+
outcome: "ineligible",
|
|
390
|
+
message: "每日签到需要显式开启,并提供 AnyRouter 站点密码或有效会话。"
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const day = beijingDay(now());
|
|
395
|
+
for (const [key, value] of completed) {
|
|
396
|
+
if (value.day !== day) completed.delete(key);
|
|
397
|
+
}
|
|
398
|
+
const key = `${account.siteURL}:${account.userId}`;
|
|
399
|
+
if (account.lastCheckinDay === day || completed.get(key)?.day === day) {
|
|
400
|
+
return { outcome: "done", message: "该账号今日签到已完成。" };
|
|
401
|
+
}
|
|
402
|
+
if (pending.has(key)) {
|
|
403
|
+
const result = await pending.get(key);
|
|
404
|
+
return result.outcome === "claimed"
|
|
405
|
+
? { outcome: "done", message: "并发的每日签到已完成。" }
|
|
406
|
+
: result;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const operation = (async () => {
|
|
410
|
+
let siteAccount = account;
|
|
411
|
+
let session = account.session;
|
|
412
|
+
try {
|
|
413
|
+
if (account.mode === "password") {
|
|
414
|
+
const login = await site.login(account);
|
|
415
|
+
siteAccount = login.account;
|
|
416
|
+
session = login.account.session;
|
|
417
|
+
} else {
|
|
418
|
+
await site.self(account);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const signIn = await site.signIn(siteAccount);
|
|
422
|
+
session = signIn.cookies || session;
|
|
423
|
+
const daily = site.checkinResult(signIn);
|
|
424
|
+
// A failed HTTP-200 response is retryable later; never burn the
|
|
425
|
+
// Beijing day or persist it as a terminal check-in.
|
|
426
|
+
if (daily.lastCheckin.outcome === "failed") {
|
|
427
|
+
return daily.lastCheckin;
|
|
428
|
+
}
|
|
429
|
+
completed.set(key, { day: daily.lastCheckinDay });
|
|
430
|
+
|
|
431
|
+
const latestAuth = await getAuth();
|
|
432
|
+
const latest = readAccount(latestAuth, provider);
|
|
433
|
+
if (latest?.userId !== account.userId || latest.siteURL !== account.siteURL) {
|
|
434
|
+
return {
|
|
435
|
+
...daily.lastCheckin,
|
|
436
|
+
message: "签到已完成,但所选账号已变更,未覆盖其凭据。"
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
await input.client?.auth?.set?.({
|
|
441
|
+
path: { id: PROVIDER },
|
|
442
|
+
body: saveAccount({
|
|
443
|
+
...latest,
|
|
444
|
+
session,
|
|
445
|
+
...daily
|
|
446
|
+
}, latestAuth)
|
|
447
|
+
});
|
|
448
|
+
} catch {
|
|
449
|
+
return {
|
|
450
|
+
...daily.lastCheckin,
|
|
451
|
+
message: "签到已完成,但刷新后的站点会话未能保存。"
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
return daily.lastCheckin;
|
|
455
|
+
} catch (error) {
|
|
456
|
+
const result = checkinFailure(error);
|
|
457
|
+
if (result.outcome !== "failed") {
|
|
458
|
+
completed.set(key, { day });
|
|
459
|
+
try {
|
|
460
|
+
const latestAuth = await getAuth();
|
|
461
|
+
const latest = readAccount(latestAuth, provider);
|
|
462
|
+
if (latest?.userId === account.userId && latest.siteURL === account.siteURL) {
|
|
463
|
+
await input.client?.auth?.set?.({
|
|
464
|
+
path: { id: PROVIDER },
|
|
465
|
+
body: saveAccount({
|
|
466
|
+
...latest,
|
|
467
|
+
session,
|
|
468
|
+
lastCheckinDay: day,
|
|
469
|
+
lastCheckin: result
|
|
470
|
+
}, latestAuth)
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
} catch {}
|
|
474
|
+
}
|
|
475
|
+
return result;
|
|
476
|
+
}
|
|
477
|
+
})();
|
|
478
|
+
|
|
479
|
+
pending.set(key, operation);
|
|
480
|
+
try {
|
|
481
|
+
return await operation;
|
|
482
|
+
} finally {
|
|
483
|
+
pending.delete(key);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
provider: {
|
|
488
|
+
id: PROVIDER,
|
|
489
|
+
models: (provider, { auth } = {}) => catalog(provider, readAccount(auth, provider))
|
|
490
|
+
},
|
|
491
|
+
"chat.headers": async (context, output) => {
|
|
492
|
+
if (context.model?.providerID !== PROVIDER && context.provider?.info?.id !== PROVIDER) return;
|
|
493
|
+
const supplied = new Headers(context.model?.headers);
|
|
494
|
+
const modelId = context.model?.id || context.model?.api?.id;
|
|
495
|
+
if (modelId) output.headers[MODEL_HINT_HEADER] = modelId;
|
|
496
|
+
if (context.sessionID && !supplied.has("x-session-id") && !output.headers["x-session-id"]) {
|
|
497
|
+
output.headers["x-session-id"] = context.sessionID;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
}
|