mslxdff 0.1.160 → 0.1.162
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/package.json +1 -1
- package/src/autostart.js +3 -0
- package/src/chat-pipeline/empty-turn.js +119 -0
- package/src/chat-pipeline/index.js +4 -1
- package/src/chat-pipeline/serial-trial.js +53 -19
- package/src/cli/commands/daemon.js +4 -4
- package/src/cli/commands/model/list-providers.js +1 -1
- package/src/cli/commands/provider/globalqwenwork-login.js +126 -0
- package/src/cli/commands/provider/index.js +2 -0
- package/src/cli/commands/provider/models.js +3 -0
- package/src/cli/commands/system.js +2 -2
- package/src/cli/format.js +7 -0
- package/src/cli/policy.js +2 -2
- package/src/cli/provider-row.js +2 -2
- package/src/daemon.js +7 -2
- package/src/logs.js +14 -1
- package/src/model-trace.js +8 -4
- package/src/providers/classify.js +1 -1
- package/src/providers/dispatcher.js +26 -14
- package/src/providers/globalqwenwork/account-store.js +141 -0
- package/src/providers/globalqwenwork/constants.js +73 -0
- package/src/providers/globalqwenwork/cosy.js +123 -0
- package/src/providers/globalqwenwork/crypto.js +220 -0
- package/src/providers/globalqwenwork/http.js +22 -0
- package/src/providers/globalqwenwork/index.js +331 -0
- package/src/providers/globalqwenwork/payload.js +145 -0
- package/src/providers/globalqwenwork/rsa.js +56 -0
- package/src/providers/globalqwenwork/sse.js +270 -0
- package/src/providers/globalqwenwork/stream.js +132 -0
- package/src/providers/globalqwenwork/upstream.js +122 -0
- package/src/providers/globalqwenwork.js +1 -0
- package/src/providers/qoder/chat.js +16 -6
- package/src/providers/qoder/index.js +13 -4
- package/src/providers/qoder/sse.js +39 -1
- package/src/providers/registry.js +8 -0
- package/src/providers/zcode/sse.js +19 -2
- package/src/routes/chat/exhausted-handler.js +23 -8
- package/src/routes/chat/local-handler.js +3 -1
- package/src/routes/chat/relay-pipeline.js +22 -10
- package/src/routes/helpers.js +20 -4
- package/src/routes/stream-hold.js +138 -0
- package/src/routes/stream-scan.js +192 -0
- package/src/routes/stream.js +97 -104
- package/src/runtime/lifecycle-forensics.js +116 -0
- package/src/runtime/lifecycle-log.js +23 -0
- package/src/runtime/provider-gate.js +4 -3
- package/src/runtime/server-lifecycle.js +5 -6
- package/src/talk-log.js +226 -0
- package/src/timeline.js +5 -2
package/src/model-trace.js
CHANGED
|
@@ -78,7 +78,8 @@ const DECISION_FIELDS = [
|
|
|
78
78
|
"winPeer", "winTarget", "peer", "peers", "peerLabel", "routeBest", "at",
|
|
79
79
|
"latencyMs", "ttfMs", "hedged", "hops", "hasShare", "elapsedMs", "threshold",
|
|
80
80
|
"stallHits", "maxGapMs", "interrupted", "providers", "via",
|
|
81
|
-
"retry", "max", "delayMs", "upstream", "account", "pick", "cooled",
|
|
81
|
+
"retry", "step", "max", "delayMs", "upstream", "account", "pick", "cooled", "queued", "nudged", "retries", "waitedMs", "raiseFrom", "raiseTo",
|
|
82
|
+
"heldOpen", "terminalForm", "requestWaitedMs", "budgetMs", "budgetOut",
|
|
82
83
|
];
|
|
83
84
|
|
|
84
85
|
function decisionKv(data = {}) {
|
|
@@ -91,7 +92,7 @@ function decisionKv(data = {}) {
|
|
|
91
92
|
return out.join(" ");
|
|
92
93
|
}
|
|
93
94
|
|
|
94
|
-
// provider 回显头 → 日志字段(谁上的 / 打哪个站 / 为什么选它 /
|
|
95
|
+
// provider 回显头 → 日志字段(谁上的 / 打哪个站 / 为什么选它 / 是否被冷却 / 是否被判排队):
|
|
95
96
|
// 单一来源,防各处重复写法漂移;取不到时返回空对象(其它供应商零变化)。
|
|
96
97
|
export function upstreamEcho(res) {
|
|
97
98
|
const h = res?.headers;
|
|
@@ -102,6 +103,7 @@ export function upstreamEcho(res) {
|
|
|
102
103
|
account: pick("x-mslxdff-workbuddy-uid") || pick("x-mslxdff-qoder-region"),
|
|
103
104
|
pick: pick("x-mslxdff-qoder-account"),
|
|
104
105
|
cooled: pick("x-mslxdff-qoder-cooldown"),
|
|
106
|
+
queued: pick("x-mslxdff-qoder-queued"),
|
|
105
107
|
};
|
|
106
108
|
}
|
|
107
109
|
|
|
@@ -114,8 +116,10 @@ export function formatModelTrace({ type, reqId, model, data = {}, request = null
|
|
|
114
116
|
else if (type === "alias") detail = `rawModel=${data.rawModel || "-"} requested=${data.requested || model || "-"}`;
|
|
115
117
|
else if (type === "exhausted-local" || type === "exhausted-all") detail = `last=${data.lastModel || model || "-"} status=${data.lastStatus ?? "-"} order=${(data.order || []).join(" | ")}`;
|
|
116
118
|
else if (type === "upstream-try") detail = `target=${data.model || model || "-"} attempt=${data.attempt ?? "-"} payload=${kv(data.payload || {})}`;
|
|
117
|
-
else if (type === "upstream-done" || type === "upstream-error") detail = `upstream status=${data.status ?? "-"} timing=${data.timing?.totalMs ?? "-"}ms${data.upstream ? ` via=${data.upstream}` : ""}${data.account ? ` account=${data.account}` : ""}${data.pick ? ` pick=${data.pick}` : ""}${data.cooled ? ` cooled=${data.cooled}` : ""} ${safeText(data.message || data.error || "")}`;
|
|
118
|
-
else if (type === "empty-turn-retry") detail =
|
|
119
|
+
else if (type === "upstream-done" || type === "upstream-error") detail = `upstream status=${data.status ?? "-"} timing=${data.timing?.totalMs ?? "-"}ms${data.upstream ? ` via=${data.upstream}` : ""}${data.account ? ` account=${data.account}` : ""}${data.pick ? ` pick=${data.pick}` : ""}${data.cooled ? ` cooled=${data.cooled}` : ""}${data.queued ? ` queued=1` : ""} ${safeText(data.message || data.error || "")}`;
|
|
120
|
+
else if (type === "empty-turn-retry") detail = `空转重试:retry ${data.retry ?? "-"}/${data.max ?? "-"}${data.step != null ? ` step=${data.step}` : ""} delay=${data.delayMs ?? "-"}ms${data.waitedMs ? ` waited=${data.waitedMs}ms` : ""}${data.requestWaitedMs != null ? ` 请求级累计=${data.requestWaitedMs}ms/预算${data.budgetMs ?? "-"}ms` : ""}${data.raiseTo ? ` max_tokens ${data.raiseFrom}→${data.raiseTo}` : ""}${data.upstream ? ` after=${data.upstream}` : ""}${data.account ? ` account=${data.account}` : ""}${data.pick ? ` pick=${data.pick}` : ""}${data.nudged ? ` nudged=1` : ""} reason=empty turn${data.reason ? ` :: ${safeText(data.reason, 120)}` : ""}`;
|
|
121
|
+
else if (type === "empty-turn-recovered") detail = `空转重试成功:第 ${data.retries ?? "-"}/${data.max ?? "-"} 次重拉拿到真实输出,本轮共白等 ${data.waitedMs ?? "-"}ms${data.upstream ? ` via=${data.upstream}` : ""}${data.account ? ` account=${data.account}` : ""}${data.pick ? ` pick=${data.pick}` : ""}`;
|
|
122
|
+
else if (type === "empty-turn-exhausted") detail = `空转重试已用尽:重试 ${data.retries ?? 0}/${data.max ?? "-"} 次仍零输出(累计等待 ${data.waitedMs ?? 0}ms${data.budgetOut ? `,请求级等待预算 ${data.budgetMs ?? "-"}ms 用尽` : ""}),交回换候选${data.heldOpen ? "(响应仍开着,换过去的正文还能送达)" : "(响应已封口,重拉只为省额度)"}${data.upstream ? ` after=${data.upstream}` : ""}${data.account ? ` account=${data.account}` : ""}${data.pick ? ` pick=${data.pick}` : ""}${data.reason ? ` :: ${safeText(data.reason, 120)}` : ""}`;
|
|
119
123
|
else if (type === "peer-request" || type === "peer-forward" || type === "peer-error") detail = `peer=${hostPort(data.peer)} status=${data.status ?? "-"} latency=${data.latencyMs ?? "-"}ms payload=${kv(data.payload || {})} ${safeText(data.message || data.error || "")}`;
|
|
120
124
|
else if (type === "relay-done") {
|
|
121
125
|
const d = data.detail || {};
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// latency-compare:key/token 类,direct vs link+remote 比延迟
|
|
5
5
|
export function classifyProvider(id) {
|
|
6
6
|
const s = String(id || "").trim().toLowerCase();
|
|
7
|
-
if (s === "workbuddy" || s === "cline" || s === "codearts" || s === "traework" || s === "qoder" || s === "qwenwork" || s === "zcode") return "local-only";
|
|
7
|
+
if (s === "workbuddy" || s === "cline" || s === "codearts" || s === "traework" || s === "qoder" || s === "qwenwork" || s === "globalqwenwork" || s === "zcode") return "local-only";
|
|
8
8
|
if (s === "opencode") return "quota-pool";
|
|
9
9
|
return "latency-compare";
|
|
10
10
|
}
|
|
@@ -1,6 +1,14 @@
|
|
|
1
|
-
import { appendEvent } from "../logs.js";
|
|
2
|
-
import { splitModelId, DEFAULT_PROVIDER, joinModelId } from "./model-id.js";
|
|
3
|
-
import { isModelAllowed as stateIsAllowed, loadProviderAllowedModels as stateLoadAllowed, loadProviderAllowAnyModels as stateLoadAllowAny } from "../state.js";
|
|
1
|
+
import { appendEvent } from "../logs.js";
|
|
2
|
+
import { splitModelId, DEFAULT_PROVIDER, joinModelId } from "./model-id.js";
|
|
3
|
+
import { isModelAllowed as stateIsAllowed, loadProviderAllowedModels as stateLoadAllowed, loadProviderAllowAnyModels as stateLoadAllowAny } from "../state.js";
|
|
4
|
+
// 定制预热名单:registry customProviders 8 家 + 默认 opencode;openrouter/自配 generic 不预热(按需自拉)
|
|
5
|
+
const CUSTOM_PREHEAT_IDS = new Set(["opencode", "workbuddy", "traework", "cline", "codearts", "qoder", "globalqwenwork", "qwenwork", "zcode"]);
|
|
6
|
+
function isPreheatDisabled() {
|
|
7
|
+
const raw = process.env.MSLXDFF_PREHEAT;
|
|
8
|
+
if (raw === undefined || raw === null || raw === "") return false;
|
|
9
|
+
const s = String(raw).trim().toLowerCase();
|
|
10
|
+
return s === "0" || s === "off" || s === "false" || s === "no" || s === "disable" || s === "disabled";
|
|
11
|
+
}
|
|
4
12
|
|
|
5
13
|
// 多供应商 dispatcher:把多个 Provider 聚合成一个 `upstream` 形状(chat/preheat/close),
|
|
6
14
|
// 按 body.model 的前缀路由到对应供应商,转发上游前剥掉前缀只发原始 id。
|
|
@@ -111,18 +119,22 @@ export function createProviderDispatcher(providers = [], opts = {}) {
|
|
|
111
119
|
return out;
|
|
112
120
|
}
|
|
113
121
|
|
|
114
|
-
//
|
|
115
|
-
//
|
|
116
|
-
// 对所有上游各发一次 GET;MSLXDFF_PREHEAT=0 的关闭由唯一被调的 opencode preheat 自行尊重。
|
|
117
|
-
// 见 .agents/notes/implemented/simplification/2026-09-16-preheat-opencode-only.md
|
|
122
|
+
// 预热定制供应商 + 默认供应商(opencode):registry 名单 8 家 + opencode 共 9 家并发各打一次;
|
|
123
|
+
// openrouter/用户自配 generic 不在此列(按需首次请求自拉)。单家失败静默,不拖累启动。
|
|
118
124
|
async function preheat() {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
125
|
+
if (isPreheatDisabled()) return { ok: true, skipped: true };
|
|
126
|
+
const targets = providers.filter((p) => p && typeof p.preheat === "function" && CUSTOM_PREHEAT_IDS.has(p.id));
|
|
127
|
+
if (!targets.length) return { ok: false, skipped: true };
|
|
128
|
+
const settled = await Promise.all(targets.map(async (p) => {
|
|
129
|
+
try {
|
|
130
|
+
const r = await p.preheat();
|
|
131
|
+
return { id: p.id, ...(r && typeof r === "object" ? r : { ok: false }) };
|
|
132
|
+
} catch {
|
|
133
|
+
return { id: p.id, ok: false, error: "preheat failed" };
|
|
134
|
+
}
|
|
135
|
+
}));
|
|
136
|
+
const okCount = settled.filter((r) => r && r.ok).length;
|
|
137
|
+
return { ok: okCount > 0, results: settled, okCount, total: settled.length };
|
|
126
138
|
}
|
|
127
139
|
|
|
128
140
|
async function close() {
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// globalqwenwork 账号落盘单一源:auths/globalqwenwork-<uid>.json(0600 tmp+rename)+ state.json 双写。
|
|
2
|
+
// vendor 自 src/providers/qwenwork/account-store.js 逐字搬,改三处命名空间:
|
|
3
|
+
// ① 文件名前缀 `globalqwenwork-`(与 cn 的 `qwenwork-` **互不为前缀**,故两站号同目录也不串;
|
|
4
|
+
// 反向亦然:`qwenwork-x.json` 不 startsWith("globalqwenwork-"))
|
|
5
|
+
// ② state 键 `providerConfigs.globalqwenwork`
|
|
6
|
+
// ③ auth 目录 env 独立为 `GLOBALQWENWORK_AUTH_DIR`(不与 cn 的 QWENWORK_AUTH_DIR 共享,防两站串号)
|
|
7
|
+
// 国际站与 cn 站凭证**不互通**(实测 cn token 打 .ai userinfo → 401 INVALID_TOKEN),故必须各存各的。
|
|
8
|
+
import { writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, readdirSync, readFileSync, chmodSync } from "node:fs";
|
|
9
|
+
import { join, dirname } from "node:path";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { isTestEnv, defaultStateFile } from "../../state/store.js";
|
|
12
|
+
|
|
13
|
+
const PROVIDER_ID = "globalqwenwork";
|
|
14
|
+
const FILE_PREFIX = "globalqwenwork-";
|
|
15
|
+
|
|
16
|
+
export function authDirFor({ explicit = "", testEnv = false, stateFile } = {}) {
|
|
17
|
+
if (explicit) return explicit;
|
|
18
|
+
if (testEnv) return join(tmpdir(), "mslxdff-test-auths-globalqwenwork");
|
|
19
|
+
return join(dirname(stateFile), "auths");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function resolveAuthDir() {
|
|
23
|
+
return authDirFor({
|
|
24
|
+
explicit: process.env.GLOBALQWENWORK_AUTH_DIR || "",
|
|
25
|
+
testEnv: isTestEnv(),
|
|
26
|
+
stateFile: defaultStateFile(),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function resolveAuthDirs() {
|
|
31
|
+
const primary = resolveAuthDir();
|
|
32
|
+
const cwdDir = join(process.cwd(), "auths");
|
|
33
|
+
return primary === cwdDir ? [primary] : [primary, cwdDir];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function listAccountDocs({ dirs } = {}) {
|
|
37
|
+
const out = [];
|
|
38
|
+
const seen = new Set();
|
|
39
|
+
for (const dir of dirs || resolveAuthDirs()) {
|
|
40
|
+
let files = [];
|
|
41
|
+
try {
|
|
42
|
+
if (!existsSync(dir)) continue;
|
|
43
|
+
files = readdirSync(dir).filter((f) => f.startsWith(FILE_PREFIX) && f.endsWith(".json"));
|
|
44
|
+
} catch { continue; }
|
|
45
|
+
for (const f of files) {
|
|
46
|
+
try {
|
|
47
|
+
const doc = JSON.parse(readFileSync(join(dir, f), "utf8"));
|
|
48
|
+
const uid = doc?.account?.uid;
|
|
49
|
+
if (!uid || !doc?.auth?.accessToken) continue;
|
|
50
|
+
if (seen.has(String(uid))) continue;
|
|
51
|
+
seen.add(String(uid));
|
|
52
|
+
out.push({ uid: String(uid), file: join(dir, f), dir, doc });
|
|
53
|
+
} catch {}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function writeAccountFile({ uid, accessToken, refreshToken = "", expiresAt = 0, name = "", email = "" }) {
|
|
60
|
+
const authDir = resolveAuthDir();
|
|
61
|
+
mkdirSync(authDir, { recursive: true });
|
|
62
|
+
const doc = {
|
|
63
|
+
account: { uid, name, email },
|
|
64
|
+
auth: { accessToken, refreshToken, expiresAt },
|
|
65
|
+
};
|
|
66
|
+
const fp = join(authDir, `${FILE_PREFIX}${uid}.json`);
|
|
67
|
+
const tmp = `${fp}.tmp`;
|
|
68
|
+
writeFileSync(tmp, JSON.stringify(doc, null, 2), { mode: 0o600 });
|
|
69
|
+
try {
|
|
70
|
+
if (existsSync(fp)) { try { chmodSync(fp, 0o600); } catch {} unlinkSync(fp); }
|
|
71
|
+
renameSync(tmp, fp);
|
|
72
|
+
} catch {
|
|
73
|
+
writeFileSync(fp, JSON.stringify(doc, null, 2), { mode: 0o600 });
|
|
74
|
+
try { unlinkSync(tmp); } catch {}
|
|
75
|
+
}
|
|
76
|
+
try { chmodSync(fp, 0o600); } catch {}
|
|
77
|
+
return fp;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// state 落盘:keys[i] 存 JSON blob({device_token, refresh_token},对齐家族形状),auths 存 uid 索引行。
|
|
81
|
+
async function persistAccounts(accounts, file) {
|
|
82
|
+
const { loadProviderConfigs } = await import("../../state.js");
|
|
83
|
+
const { saveProviderConfig } = await import("../../state.js");
|
|
84
|
+
const cfg = (loadProviderConfigs(file ? { file } : {})?.[PROVIDER_ID]) || {};
|
|
85
|
+
const keys = [...(Array.isArray(cfg.keys) ? cfg.keys : [])];
|
|
86
|
+
const auths = [...(Array.isArray(cfg.auths) ? cfg.auths : [])];
|
|
87
|
+
let updated = 0;
|
|
88
|
+
for (const acc of accounts) {
|
|
89
|
+
if (!acc?.uid || !acc?.accessToken) continue;
|
|
90
|
+
const blob = JSON.stringify({ device_token: acc.accessToken, refresh_token: acc.refreshToken || "" });
|
|
91
|
+
const row = { uid: acc.uid, name: acc.name || "", refreshToken: acc.refreshToken || "" };
|
|
92
|
+
const idx = auths.findIndex((a) => String(a?.uid) === String(acc.uid));
|
|
93
|
+
if (idx >= 0) { keys[idx] = blob; auths[idx] = row; updated += 1; }
|
|
94
|
+
else { keys.push(blob); auths.push(row); }
|
|
95
|
+
}
|
|
96
|
+
// saveProviderConfig 起手保留 allowAnyModels(已在 state 层修复,见 ADR-0033 字段保留修复)
|
|
97
|
+
saveProviderConfig(PROVIDER_ID, { baseUrl: cfg.baseUrl || "", keys, auths }, file ? { file } : {});
|
|
98
|
+
return { keys, auths, updated };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function saveGlobalQwenworkAccount({ uid, accessToken, refreshToken = "", expiresAt = 0, name = "", email = "", file } = {}) {
|
|
102
|
+
if (!uid || !accessToken) throw new Error("saveGlobalQwenworkAccount: 缺少 uid/accessToken");
|
|
103
|
+
const fp = writeAccountFile({ uid, accessToken, refreshToken, expiresAt, name, email });
|
|
104
|
+
const st = await persistAccounts([{ uid, accessToken, refreshToken, name }], file);
|
|
105
|
+
return { file: fp, accounts: st.keys.length, updated: st.updated > 0 };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 回写刷新后的 token(上游每次 refresh 会轮换 refreshToken,必须落盘)。 */
|
|
109
|
+
export async function updateGlobalQwenworkTokens({ uid, accessToken, refreshToken = "", expiresAt = 0, file } = {}) {
|
|
110
|
+
if (!uid || !accessToken) throw new Error("updateGlobalQwenworkTokens: 缺少 uid/accessToken");
|
|
111
|
+
const docs = listAccountDocs();
|
|
112
|
+
const hit = docs.find((d) => String(d.uid) === String(uid));
|
|
113
|
+
const prev = hit?.doc || {};
|
|
114
|
+
const fp = writeAccountFile({
|
|
115
|
+
uid,
|
|
116
|
+
accessToken,
|
|
117
|
+
refreshToken: refreshToken || prev?.auth?.refreshToken || "",
|
|
118
|
+
expiresAt: expiresAt || 0,
|
|
119
|
+
name: prev?.account?.name || "",
|
|
120
|
+
email: prev?.account?.email || "",
|
|
121
|
+
});
|
|
122
|
+
await persistAccounts([{ uid, accessToken, refreshToken: refreshToken || prev?.auth?.refreshToken || "", name: prev?.account?.name || "" }], file);
|
|
123
|
+
try {
|
|
124
|
+
const { invalidateSession } = await import("./cosy.js");
|
|
125
|
+
invalidateSession({ uid, accessToken: prev?.auth?.accessToken });
|
|
126
|
+
} catch {}
|
|
127
|
+
return { file: fp };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// 从 provider keys 的 blob 还原凭据(device_token/deviceToken 双形状兼容)
|
|
131
|
+
export function accountFromBlob(blob) {
|
|
132
|
+
try {
|
|
133
|
+
const j = JSON.parse(String(blob || "{}"));
|
|
134
|
+
const accessToken = String(j.device_token || j.accessToken || "");
|
|
135
|
+
const refreshToken = String(j.refresh_token || j.refreshToken || "");
|
|
136
|
+
if (!accessToken) return null;
|
|
137
|
+
return { accessToken, refreshToken };
|
|
138
|
+
} catch {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// globalqwenwork(千问办公国际站 gateway.qwenwork.ai)上游技术常量。
|
|
2
|
+
// 值来源:2026-10-01 用真号现网取证 —— 设备流/poll/refresh/userinfo/account-context/
|
|
3
|
+
// model/list/COSY 签名/chat SSE 全部实测 200(非推测)。**禁止凭记忆改值**;
|
|
4
|
+
// 要改先现网复测(客户端一升级这些快照就可能 403)。
|
|
5
|
+
// Note: 为何独立 provider 而非 qwenwork 的新 region — 见 docs/adr/0041-globalqwenwork-international-provider.md
|
|
6
|
+
export const BASE = "https://gateway.qwenwork.ai";
|
|
7
|
+
|
|
8
|
+
// OAuth 设备授权。client_id 与 cn 站(qwenwork 的 e883ade2…)**不同**:实测用 cn 的
|
|
9
|
+
// client_id + redirect_uri=qwenwork-cn:// 打本域名,selectAccounts 判
|
|
10
|
+
// `INVALID_DEVICE_FLOW / field=query / reason=not_allowed`(整串 query 不被接受)。
|
|
11
|
+
// 国际版官方客户端硬编码 CONFIGURED_OAUTH_CLIENT_ID=cc65e5fc…(app.asar 取证 + 运行日志实证)。
|
|
12
|
+
export const CLIENT_ID = "cc65e5fc-05bd-4f5d-a4e8-0df19aa3d75a";
|
|
13
|
+
// 深链协议同国际版客户端日志:`qwenwork://`(cn 站是 `qwenwork-cn://`)
|
|
14
|
+
export const REDIRECT_URI = "qwenwork://";
|
|
15
|
+
|
|
16
|
+
export const DEVICE_AUTH_URL = `${BASE}/device/selectAccounts`;
|
|
17
|
+
export const POLL_URL = `${BASE}/api/v1/deviceToken/poll`;
|
|
18
|
+
export const REFRESH_URL = `${BASE}/api/v1/deviceToken/refresh`;
|
|
19
|
+
export const USERINFO_URL = `${BASE}/api/v1/userinfo`;
|
|
20
|
+
// 额度/套餐:data.{user,plan,quota};国际站免费档 pid=`subscription-sgp-free`(新加坡池,与 cn 积分池独立)
|
|
21
|
+
export const ACCOUNT_CONTEXT_URL = `${BASE}/api/v1/adapter/user/account-context?include=user,plan,quota`;
|
|
22
|
+
// 无 `Encode=1`:请求体走纯 JSON(与 cn 同)
|
|
23
|
+
export const CHAT_URL = `${BASE}/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common`;
|
|
24
|
+
export const MODELS_URL = `${BASE}/algo/api/v2/model/list`;
|
|
25
|
+
|
|
26
|
+
export function envStr(name, fallback) {
|
|
27
|
+
const v = process.env[name];
|
|
28
|
+
return typeof v === "string" && v.trim() ? v.trim() : fallback;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// 客户端指纹常量:实测国际站网关接受 cn 同款值(COSY 签名 200),故与 qwenwork 保持一致;
|
|
32
|
+
// 官方国际版客户端自身 UA 为 `qwenwork/1.0.4`,如上游开始校验版本可用下列 env 覆盖排障。
|
|
33
|
+
export const UA = envStr("MSLXDFF_GLOBALQWENWORK_UA", "qoderwork/1.0.5");
|
|
34
|
+
export const COSY_VERSION = envStr("MSLXDFF_GLOBALQWENWORK_COSY_VERSION", "1.1.18");
|
|
35
|
+
export const IDE_VERSION = envStr("MSLXDFF_GLOBALQWENWORK_IDE_VERSION", "1.0.5");
|
|
36
|
+
export const RELEASE_VERSION = envStr("MSLXDFF_GLOBALQWENWORK_RELEASE_VERSION", "1.0.5-26090901");
|
|
37
|
+
export const BUILD = envStr("MSLXDFF_GLOBALQWENWORK_BUILD", "26090901");
|
|
38
|
+
export const CLIENT_TYPE = "6";
|
|
39
|
+
// 业务归属字段:实测国际站接受 cn 同款 `qoder_work`/`agent`/`qwork`(chat 200 出词)
|
|
40
|
+
export const BUSINESS_PRODUCT = "qoder_work";
|
|
41
|
+
export const BUSINESS_TYPE = "agent";
|
|
42
|
+
export const SCENE = "qwork";
|
|
43
|
+
export const MACHINE_OS = "x86_64_win32";
|
|
44
|
+
|
|
45
|
+
// 上游 model/list 返回 11 个根切片,实测国际站同样**只有 `qwork` 非空**(n=2);
|
|
46
|
+
// 但切片内容与 cn 站**完全不同池**:cn 是 flash/pro/qwen3.8-max-preview,国际站是下面两个。
|
|
47
|
+
export const MODEL_SLICE = "qwork";
|
|
48
|
+
export const DEFAULT_MODEL = "qwork-auto";
|
|
49
|
+
export const CONTEXT_LENGTH = 180000;
|
|
50
|
+
export const MAX_TOKENS_DEFAULT = 32000;
|
|
51
|
+
|
|
52
|
+
// 实测模型池(2026-10-01 真号取证,`/algo/api/v2/model/list` 原文):
|
|
53
|
+
// 两者 is_reasoning=false / is_vl=true / price_factor=0 / max_input_tokens=180000 /
|
|
54
|
+
// context_config 1M(默认)|200K|400K;`qwork-auto` 上游实为 qwen3.8-flash,
|
|
55
|
+
// `qwork-advanced` 上游实为 gpt-5.6-sol(响应头 X-Model-Name 取证)。仅作取数失败时兜底展示。
|
|
56
|
+
export const KNOWN_MODELS = [
|
|
57
|
+
{ key: "qwork-auto", name: "Standard|Qwen3.8-Flash", priceFactor: 0 },
|
|
58
|
+
{ key: "qwork-advanced", name: "Advanced", priceFactor: 0 },
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
// RSA-1024 模数:实测国际站接受与 cn **同一枚**模数(COSY 签名 200),逐字符沿用勿改。
|
|
62
|
+
export const RSA_MODULUS_HEX =
|
|
63
|
+
"c0f22307e5cd362e296bb04470f6de8fbf935ce24e8fcf511a0e2701329769c4" +
|
|
64
|
+
"a76e499bb938036a52af1eaf818cf79a2600620e3ce87e371d2ca6d85803606a" +
|
|
65
|
+
"1b3fa5e874643c9ed2db7e85673ef7227fca56e2e7c08f0927609bb896a9f24b" +
|
|
66
|
+
"e1782099a66016a5bfdc3f1ff756bfc9e88d7b5dc5be30bf45a0223a00ebcecf";
|
|
67
|
+
export const RSA_EXPONENT = 65537;
|
|
68
|
+
|
|
69
|
+
export const LOGIN_TTL_MS = 10 * 60 * 1000;
|
|
70
|
+
export const COOLDOWN_MS = 30_000;
|
|
71
|
+
export const QUOTA_COOLDOWN_MS = 60 * 60 * 1000;
|
|
72
|
+
export const REFRESH_MARGIN_MS = 30 * 60 * 1000;
|
|
73
|
+
export const MODELS_CACHE_MS = 10 * 60 * 1000;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// cosy.js(COSY 会话 + 签名头)— vendor 自 src/providers/qwenwork/cosy.js 逐字搬;
|
|
2
|
+
// 本目录 import 全为相对路径,自动绑定本目录 constants/crypto/rsa。线上头 x-qwenwork-* 与 cn 同名,**禁止改名**(实测 .ai 接受)。
|
|
3
|
+
// 关键不变式(改动即 403):
|
|
4
|
+
// · identity/payload 都必须 key 升序紧凑 JSON(sortedCompact)
|
|
5
|
+
// · 签名 = md5(payloadB64 \n cosyKey \n date \n body \n pathSig),pathSig 去 /algo 前缀、不含 query
|
|
6
|
+
// · authorization = `Bearer COSY.${payloadB64}.${sig}`;payloadB64 是**标准 base64(带 padding)**
|
|
7
|
+
// · 同一 requestId 重放会被上游判 `code 103 Duplicate request`
|
|
8
|
+
import { uuid, b64, b64url, utf8, aesCbcEncrypt, md5 } from "./crypto.js";
|
|
9
|
+
import { rsaPkcs1Encrypt } from "./rsa.js";
|
|
10
|
+
import {
|
|
11
|
+
COSY_VERSION, IDE_VERSION, RELEASE_VERSION, BUILD, CLIENT_TYPE,
|
|
12
|
+
BUSINESS_PRODUCT, BUSINESS_TYPE, SCENE, MACHINE_OS, UA,
|
|
13
|
+
} from "./constants.js";
|
|
14
|
+
|
|
15
|
+
const cache = new Map();
|
|
16
|
+
|
|
17
|
+
function sortedCompact(obj) {
|
|
18
|
+
const keys = Object.keys(obj).sort();
|
|
19
|
+
let out = "{";
|
|
20
|
+
for (let i = 0; i < keys.length; i++) {
|
|
21
|
+
if (i > 0) out += ",";
|
|
22
|
+
out += JSON.stringify(keys[i]) + ":" + JSON.stringify(obj[keys[i]]);
|
|
23
|
+
}
|
|
24
|
+
return out + "}";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function newSession(account) {
|
|
28
|
+
const machineID = uuid();
|
|
29
|
+
const seed = (uuid() + uuid()).slice(0, 50);
|
|
30
|
+
const machineToken = b64url(utf8(seed));
|
|
31
|
+
const machineType = uuid().replace(/-/g, "").slice(0, 18);
|
|
32
|
+
const tempKey = uuid().replace(/-/g, "").slice(0, 16);
|
|
33
|
+
|
|
34
|
+
const identity = sortedCompact({
|
|
35
|
+
uid: account.uid || "",
|
|
36
|
+
aid: account.uid || "",
|
|
37
|
+
name: account.nickname || "",
|
|
38
|
+
email: account.email || "",
|
|
39
|
+
security_oauth_token: account.accessToken,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
machineID,
|
|
44
|
+
machineToken,
|
|
45
|
+
machineType,
|
|
46
|
+
tempKey,
|
|
47
|
+
cosyKey: rsaPkcs1Encrypt(utf8(tempKey)),
|
|
48
|
+
info: b64(aesCbcEncrypt(utf8(identity), utf8(tempKey))),
|
|
49
|
+
accessToken: account.accessToken,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function sessionFor(account) {
|
|
54
|
+
if (!account || !account.accessToken) throw new Error("cosy: empty access token");
|
|
55
|
+
const key = account.id || account.uid || account.accessToken.slice(0, 16);
|
|
56
|
+
const hit = cache.get(key);
|
|
57
|
+
if (hit && hit.accessToken === account.accessToken) return hit;
|
|
58
|
+
if (cache.size > 128) cache.clear();
|
|
59
|
+
const sess = newSession(account);
|
|
60
|
+
cache.set(key, sess);
|
|
61
|
+
return sess;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function invalidateSession(account) {
|
|
65
|
+
const key = account && (account.id || account.uid);
|
|
66
|
+
if (key) cache.delete(key);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function pathSig(rawURL) {
|
|
70
|
+
const u = new URL(rawURL);
|
|
71
|
+
let p = u.pathname;
|
|
72
|
+
if (p.startsWith("/algo")) p = p.slice("/algo".length);
|
|
73
|
+
return p;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function signHeaders(account, body, rawURL, modelKey, accept) {
|
|
77
|
+
const sess = sessionFor(account);
|
|
78
|
+
const payload = sortedCompact({
|
|
79
|
+
cosyVersion: COSY_VERSION,
|
|
80
|
+
ideVersion: IDE_VERSION,
|
|
81
|
+
info: sess.info,
|
|
82
|
+
requestId: uuid(),
|
|
83
|
+
version: "v1",
|
|
84
|
+
});
|
|
85
|
+
const payloadB64 = b64(utf8(payload));
|
|
86
|
+
const date = Math.floor(Date.now() / 1000).toString();
|
|
87
|
+
const sig = md5(`${payloadB64}\n${sess.cosyKey}\n${date}\n${body}\n${pathSig(rawURL)}`);
|
|
88
|
+
|
|
89
|
+
const headers = {
|
|
90
|
+
accept: accept || "text/event-stream",
|
|
91
|
+
"content-type": "application/json",
|
|
92
|
+
"user-agent": UA,
|
|
93
|
+
"x-request-id": uuid(),
|
|
94
|
+
"x-qwenwork-version": IDE_VERSION,
|
|
95
|
+
"x-qwenwork-release-version": RELEASE_VERSION,
|
|
96
|
+
"x-qwenwork-build": BUILD,
|
|
97
|
+
"x-qwenwork-platform": "win32",
|
|
98
|
+
"x-qwenwork-arch": "x64",
|
|
99
|
+
"x-qwenwork-channel": "stable",
|
|
100
|
+
"cosy-version": COSY_VERSION,
|
|
101
|
+
"cosy-clienttype": CLIENT_TYPE,
|
|
102
|
+
"cosy-business-product": BUSINESS_PRODUCT,
|
|
103
|
+
"cosy-business-type": BUSINESS_TYPE,
|
|
104
|
+
"cosy-scene": SCENE,
|
|
105
|
+
"cosy-machineos": MACHINE_OS,
|
|
106
|
+
"login-version": "v2",
|
|
107
|
+
authorization: `Bearer COSY.${payloadB64}.${sig}`,
|
|
108
|
+
"cosy-key": sess.cosyKey,
|
|
109
|
+
"cosy-user": account.uid || "",
|
|
110
|
+
"cosy-date": date,
|
|
111
|
+
"cosy-machineid": sess.machineID,
|
|
112
|
+
"accept-encoding": "identity",
|
|
113
|
+
connection: "keep-alive",
|
|
114
|
+
"cache-control": "no-cache",
|
|
115
|
+
};
|
|
116
|
+
if (modelKey) {
|
|
117
|
+
headers["x-model-key"] = modelKey;
|
|
118
|
+
headers["x-model-source"] = "system";
|
|
119
|
+
}
|
|
120
|
+
return headers;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// globalqwenwork 变体(国际站 gateway.qwenwork.ai):协议与 cn 逐字同构,2026-10-01 现网实测签名/请求 200 — 见 docs/adr/0041-globalqwenwork-international-provider.md
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// vendor 自 qwenwork2api-makers 的 edge-functions/_shared/crypto.js(逐字搬,仅加 webcrypto 兜底)。
|
|
2
|
+
// 原作者手写 AES/RSA/MD5 是因为 Cloudflare Workers 无 node:crypto;**不要**"顺手优化"成原生实现 ——
|
|
3
|
+
// 实测换成 node:crypto 后上游回 `code 101 Signature invalid`(RSA/AES 材料与上游期望不等价)。
|
|
4
|
+
// Node 侧需要 globalThis.crypto(getRandomValues / subtle.digest);<19 用 node:crypto 的 webcrypto 兜底。
|
|
5
|
+
if (!globalThis.crypto || !globalThis.crypto.subtle) {
|
|
6
|
+
const { webcrypto } = await import("node:crypto");
|
|
7
|
+
globalThis.crypto = webcrypto;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const SBOX = (() => {
|
|
11
|
+
const s = new Uint8Array(256);
|
|
12
|
+
let p = 1;
|
|
13
|
+
let q = 1;
|
|
14
|
+
do {
|
|
15
|
+
p = p ^ ((p << 1) & 0xff) ^ (p & 0x80 ? 0x1b : 0);
|
|
16
|
+
q ^= q << 1;
|
|
17
|
+
q ^= q << 2;
|
|
18
|
+
q ^= q << 4;
|
|
19
|
+
if (q & 0x80) q ^= 0x09;
|
|
20
|
+
q &= 0xff;
|
|
21
|
+
const x = q ^ ((q << 1) | (q >> 7)) ^ ((q << 2) | (q >> 6)) ^ ((q << 3) | (q >> 5)) ^ ((q << 4) | (q >> 4));
|
|
22
|
+
s[p] = (x ^ 0x63) & 0xff;
|
|
23
|
+
} while (p !== 1);
|
|
24
|
+
s[0] = 0x63;
|
|
25
|
+
return s;
|
|
26
|
+
})();
|
|
27
|
+
|
|
28
|
+
const RCON = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
|
|
29
|
+
|
|
30
|
+
export function utf8(str) {
|
|
31
|
+
return new TextEncoder().encode(str);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function hex(bytes) {
|
|
35
|
+
let out = "";
|
|
36
|
+
for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function b64(bytes) {
|
|
41
|
+
let s = "";
|
|
42
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
43
|
+
return btoa(s);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function unb64(str) {
|
|
47
|
+
const s = atob(str);
|
|
48
|
+
const out = new Uint8Array(s.length);
|
|
49
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function b64url(bytes) {
|
|
54
|
+
return b64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function uuid() {
|
|
58
|
+
const r = new Uint8Array(16);
|
|
59
|
+
crypto.getRandomValues(r);
|
|
60
|
+
r[6] = (r[6] & 0x0f) | 0x40;
|
|
61
|
+
r[8] = (r[8] & 0x3f) | 0x80;
|
|
62
|
+
const h = hex(r);
|
|
63
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const MD5_S = [
|
|
67
|
+
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
|
|
68
|
+
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
const MD5_K = new Int32Array(64);
|
|
72
|
+
for (let i = 0; i < 64; i++) MD5_K[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) | 0;
|
|
73
|
+
|
|
74
|
+
function rotl(x, n) {
|
|
75
|
+
return (x << n) | (x >>> (32 - n));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function md5(input) {
|
|
79
|
+
const msg = typeof input === "string" ? utf8(input) : input;
|
|
80
|
+
const len = msg.length;
|
|
81
|
+
const bitLen = len * 8;
|
|
82
|
+
const padLen = (56 - ((len + 1) % 64) + 64) % 64;
|
|
83
|
+
const total = len + 1 + padLen + 8;
|
|
84
|
+
const buf = new Uint8Array(total);
|
|
85
|
+
buf.set(msg, 0);
|
|
86
|
+
buf[len] = 0x80;
|
|
87
|
+
const view = new DataView(buf.buffer);
|
|
88
|
+
view.setUint32(total - 8, bitLen >>> 0, true);
|
|
89
|
+
view.setUint32(total - 4, Math.floor(bitLen / 4294967296), true);
|
|
90
|
+
|
|
91
|
+
let a0 = 0x67452301;
|
|
92
|
+
let b0 = 0xefcdab89;
|
|
93
|
+
let c0 = 0x98badcfe;
|
|
94
|
+
let d0 = 0x10325476;
|
|
95
|
+
|
|
96
|
+
for (let i = 0; i < total; i += 64) {
|
|
97
|
+
const m = new Int32Array(16);
|
|
98
|
+
for (let j = 0; j < 16; j++) m[j] = view.getInt32(i + j * 4, true);
|
|
99
|
+
let a = a0;
|
|
100
|
+
let b = b0;
|
|
101
|
+
let c = c0;
|
|
102
|
+
let d = d0;
|
|
103
|
+
for (let j = 0; j < 64; j++) {
|
|
104
|
+
let f;
|
|
105
|
+
let g;
|
|
106
|
+
if (j < 16) {
|
|
107
|
+
f = (b & c) | (~b & d);
|
|
108
|
+
g = j;
|
|
109
|
+
} else if (j < 32) {
|
|
110
|
+
f = (d & b) | (~d & c);
|
|
111
|
+
g = (5 * j + 1) % 16;
|
|
112
|
+
} else if (j < 48) {
|
|
113
|
+
f = b ^ c ^ d;
|
|
114
|
+
g = (3 * j + 5) % 16;
|
|
115
|
+
} else {
|
|
116
|
+
f = c ^ (b | ~d);
|
|
117
|
+
g = (7 * j) % 16;
|
|
118
|
+
}
|
|
119
|
+
f = (f + a + MD5_K[j] + m[g]) | 0;
|
|
120
|
+
a = d;
|
|
121
|
+
d = c;
|
|
122
|
+
c = b;
|
|
123
|
+
b = (b + rotl(f, MD5_S[j])) | 0;
|
|
124
|
+
}
|
|
125
|
+
a0 = (a0 + a) | 0;
|
|
126
|
+
b0 = (b0 + b) | 0;
|
|
127
|
+
c0 = (c0 + c) | 0;
|
|
128
|
+
d0 = (d0 + d) | 0;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const out = new Uint8Array(16);
|
|
132
|
+
const ov = new DataView(out.buffer);
|
|
133
|
+
ov.setInt32(0, a0, true);
|
|
134
|
+
ov.setInt32(4, b0, true);
|
|
135
|
+
ov.setInt32(8, c0, true);
|
|
136
|
+
ov.setInt32(12, d0, true);
|
|
137
|
+
return hex(out);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function xtime(a) {
|
|
141
|
+
return ((a << 1) ^ (a & 0x80 ? 0x1b : 0)) & 0xff;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function keyExpansion(key) {
|
|
145
|
+
const w = new Uint8Array(176);
|
|
146
|
+
w.set(key, 0);
|
|
147
|
+
for (let i = 4; i < 44; i++) {
|
|
148
|
+
const t = [w[(i - 1) * 4], w[(i - 1) * 4 + 1], w[(i - 1) * 4 + 2], w[(i - 1) * 4 + 3]];
|
|
149
|
+
if (i % 4 === 0) {
|
|
150
|
+
const r = t[0];
|
|
151
|
+
t[0] = t[1];
|
|
152
|
+
t[1] = t[2];
|
|
153
|
+
t[2] = t[3];
|
|
154
|
+
t[3] = r;
|
|
155
|
+
for (let j = 0; j < 4; j++) t[j] = SBOX[t[j]];
|
|
156
|
+
t[0] ^= RCON[i / 4 - 1];
|
|
157
|
+
}
|
|
158
|
+
for (let j = 0; j < 4; j++) w[i * 4 + j] = w[(i - 4) * 4 + j] ^ t[j];
|
|
159
|
+
}
|
|
160
|
+
return w;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function addRoundKey(state, w, round) {
|
|
164
|
+
for (let c = 0; c < 4; c++) {
|
|
165
|
+
for (let r = 0; r < 4; r++) state[c * 4 + r] ^= w[round * 16 + c * 4 + r];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function subBytes(state) {
|
|
170
|
+
for (let i = 0; i < 16; i++) state[i] = SBOX[state[i]];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function shiftRows(s) {
|
|
174
|
+
const t = s.slice();
|
|
175
|
+
const map = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11];
|
|
176
|
+
for (let i = 0; i < 16; i++) s[i] = t[map[i]];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function mixColumns(s) {
|
|
180
|
+
for (let c = 0; c < 4; c++) {
|
|
181
|
+
const i = c * 4;
|
|
182
|
+
const a0 = s[i];
|
|
183
|
+
const a1 = s[i + 1];
|
|
184
|
+
const a2 = s[i + 2];
|
|
185
|
+
const a3 = s[i + 3];
|
|
186
|
+
s[i] = xtime(a0) ^ (xtime(a1) ^ a1) ^ a2 ^ a3;
|
|
187
|
+
s[i + 1] = a0 ^ xtime(a1) ^ (xtime(a2) ^ a2) ^ a3;
|
|
188
|
+
s[i + 2] = a0 ^ a1 ^ xtime(a2) ^ (xtime(a3) ^ a3);
|
|
189
|
+
s[i + 3] = (xtime(a0) ^ a0) ^ a1 ^ a2 ^ xtime(a3);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function aesCbcEncrypt(plain, key) {
|
|
194
|
+
const w = keyExpansion(key);
|
|
195
|
+
const padLen = 16 - (plain.length % 16);
|
|
196
|
+
const data = new Uint8Array(plain.length + padLen);
|
|
197
|
+
data.set(plain, 0);
|
|
198
|
+
for (let i = plain.length; i < data.length; i++) data[i] = padLen;
|
|
199
|
+
const out = new Uint8Array(data.length);
|
|
200
|
+
const block = new Uint8Array(16);
|
|
201
|
+
let prev = key.slice(0, 16);
|
|
202
|
+
for (let off = 0; off < data.length; off += 16) {
|
|
203
|
+
for (let i = 0; i < 16; i++) block[i] = data[off + i] ^ prev[i];
|
|
204
|
+
addRoundKey(block, w, 0);
|
|
205
|
+
for (let round = 1; round < 10; round++) {
|
|
206
|
+
subBytes(block);
|
|
207
|
+
shiftRows(block);
|
|
208
|
+
mixColumns(block);
|
|
209
|
+
addRoundKey(block, w, round);
|
|
210
|
+
}
|
|
211
|
+
subBytes(block);
|
|
212
|
+
shiftRows(block);
|
|
213
|
+
addRoundKey(block, w, 10);
|
|
214
|
+
out.set(block, off);
|
|
215
|
+
prev = block.slice(0, 16);
|
|
216
|
+
}
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// globalqwenwork 变体:国际站 gateway.qwenwork.ai,协议与 cn 逐字同构(2026-10-01 现网取证),仅命名空间与常量不同 — 见 docs/adr/0041-globalqwenwork-international-provider.md
|