mslxdff 0.1.200 → 0.1.203
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.md +3 -3
- package/bin/mslxdff.js +1 -1
- package/package.json +38 -38
- package/plugins/README.md +14 -14
- package/plugins/prefer-model.mjs.example +14 -14
- package/src/anthropic/count-tokens.js +61 -61
- package/src/anthropic/request-body.js +126 -126
- package/src/anthropic/shared.js +18 -18
- package/src/anthropic/sse-aggregate.js +56 -56
- package/src/anthropic/translate.js +287 -287
- package/src/anthropic/web-search.js +361 -361
- package/src/api-kind.js +31 -31
- package/src/autostart.js +288 -288
- package/src/bench/probe.js +1 -1
- package/src/bench/runner.js +1 -1
- package/src/bench/via-probe.js +1 -1
- package/src/bench/via.js +144 -144
- package/src/bench/workbuddy-bench.js +1 -1
- package/src/chat/config.js +11 -11
- package/src/chat/cooling.js +81 -81
- package/src/chat/direct.js +58 -58
- package/src/chat/index.js +6 -6
- package/src/chat/spinner.js +38 -38
- package/src/chat/sse.js +69 -69
- package/src/chat/stats.js +247 -247
- package/src/chat/store.js +48 -48
- package/src/chat/tool-handlers.js +67 -67
- package/src/chat/tools.js +1 -1
- package/src/chat/upstream.js +59 -59
- package/src/chat-pipeline/auto-race.js +158 -158
- package/src/chat-pipeline/empty-turn.js +147 -147
- package/src/chat-pipeline/engine.js +17 -17
- package/src/chat-pipeline/serial-trial.js +283 -283
- package/src/chat-pipeline/terminal-verdict.js +147 -147
- package/src/chooser.js +54 -54
- package/src/claude-desktop/apply.js +101 -101
- package/src/claude-desktop/context1m.js +38 -38
- package/src/claude-desktop/doctor.js +146 -146
- package/src/claude-desktop/slots.js +152 -152
- package/src/cli/bootstrap.js +1 -1
- package/src/cli/commands/claude-desktop.js +284 -284
- package/src/cli/commands/daemon.js +231 -231
- package/src/cli/commands/model/list-live.js +22 -22
- package/src/cli/commands/model/list-providers.js +76 -76
- package/src/cli/commands/model/list-render.js +77 -77
- package/src/cli/commands/model/list-sort.js +52 -52
- package/src/cli/commands/model/list-tty.js +76 -76
- package/src/cli/commands/model/list.js +166 -166
- package/src/cli/commands/model/live-models.js +24 -24
- package/src/cli/commands/model/stats.js +43 -43
- package/src/cli/commands/model/status.js +47 -47
- package/src/cli/commands/model.js +51 -51
- package/src/cli/commands/provider/add.js +108 -108
- package/src/cli/commands/provider/allowlist.js +99 -99
- package/src/cli/commands/provider/cline-free.js +99 -99
- package/src/cli/commands/provider/cline-login.js +218 -218
- package/src/cli/commands/provider/cline-quota.js +65 -65
- package/src/cli/commands/provider/codearts-login.js +45 -45
- package/src/cli/commands/provider/config.js +119 -119
- package/src/cli/commands/provider/globalqwenwork-login.js +126 -126
- package/src/cli/commands/provider/keys-guard.js +50 -50
- package/src/cli/commands/provider/keys.js +161 -161
- package/src/cli/commands/provider/qoder-checkin.js +81 -81
- package/src/cli/commands/provider/qoder-login.js +102 -102
- package/src/cli/commands/provider/raccoon-login.js +180 -180
- package/src/cli/commands/provider/raccoon-password.js +162 -162
- package/src/cli/commands/provider/raccoon-quota.js +109 -109
- package/src/cli/commands/provider/traework-checkin.js +144 -144
- package/src/cli/commands/provider/traework-login.js +164 -164
- package/src/cli/commands/provider/workbuddy-login.js +153 -153
- package/src/cli/commands/provider/zcode-login.js +77 -77
- package/src/cli/commands/provider/zcode-quota.js +55 -55
- package/src/cli/commands/provider.js +1 -1
- package/src/cli/commands/stats.js +149 -149
- package/src/cli/commands/system.js +261 -261
- package/src/cli/commands/timezone.js +47 -47
- package/src/cli/commands/use-group.js +60 -60
- package/src/cli/commands/workbuddy.js +189 -189
- package/src/cli/format.js +141 -141
- package/src/cli/group-helpers.js +70 -70
- package/src/cli/help.js +80 -80
- package/src/cli/index.js +70 -70
- package/src/cli/interactive.js +121 -121
- package/src/cli/join-core.js +99 -99
- package/src/cli/join-wizard.js +175 -175
- package/src/cli/policy.js +136 -136
- package/src/cli/provider-row.js +126 -126
- package/src/cli/util.js +24 -24
- package/src/compat.js +53 -53
- package/src/events.js +38 -38
- package/src/free-lane.js +131 -131
- package/src/free-watcher.js +63 -63
- package/src/groups.js +262 -262
- package/src/logs.js +195 -195
- package/src/metrics.js +62 -62
- package/src/model-capabilities/context-lookup.js +65 -65
- package/src/model-capabilities/merge.js +142 -142
- package/src/model-trace.js +187 -187
- package/src/models.js +1 -1
- package/src/opencode-identity.js +72 -72
- package/src/peers.js +254 -251
- package/src/plugins.js +107 -107
- package/src/providers/base.js +164 -164
- package/src/providers/classify.js +22 -22
- package/src/providers/cline/allowlist-sync.js +93 -93
- package/src/providers/cline/free-catalog.js +71 -71
- package/src/providers/cline/headers.js +37 -37
- package/src/providers/cline/index.js +130 -130
- package/src/providers/cline/models.js +150 -150
- package/src/providers/cline/usage.js +274 -274
- package/src/providers/codearts/auth-pool.js +148 -148
- package/src/providers/codearts/concurrency.js +34 -34
- package/src/providers/codearts/const.js +65 -65
- package/src/providers/codearts/dpop.js +95 -95
- package/src/providers/codearts/index.js +175 -175
- package/src/providers/codearts/login.js +214 -214
- package/src/providers/codearts/models.js +182 -182
- package/src/providers/codearts/sign.js +96 -96
- package/src/providers/codearts/sse.js +204 -204
- package/src/providers/codearts/stream.js +209 -209
- package/src/providers/codearts/sts.js +124 -124
- package/src/providers/codearts.js +1 -1
- package/src/providers/dispatcher.js +146 -146
- package/src/providers/generic.js +156 -156
- package/src/providers/globalqwenwork/account-store.js +141 -141
- package/src/providers/globalqwenwork/constants.js +73 -73
- package/src/providers/globalqwenwork/crypto.js +2 -2
- package/src/providers/globalqwenwork/http.js +2 -2
- package/src/providers/globalqwenwork/index.js +331 -331
- package/src/providers/globalqwenwork/payload.js +147 -147
- package/src/providers/globalqwenwork/rsa.js +2 -2
- package/src/providers/globalqwenwork/sse.js +2 -2
- package/src/providers/globalqwenwork/stream.js +2 -2
- package/src/providers/globalqwenwork.js +1 -1
- package/src/providers/globalworkbuddy/account-store.js +198 -198
- package/src/providers/globalworkbuddy/auth.js +97 -97
- package/src/providers/globalworkbuddy/catalog.js +138 -138
- package/src/providers/globalworkbuddy/constants.js +73 -73
- package/src/providers/globalworkbuddy/device-auth.js +120 -120
- package/src/providers/globalworkbuddy/errors.js +98 -98
- package/src/providers/globalworkbuddy/headers.js +89 -89
- package/src/providers/globalworkbuddy/models.js +96 -96
- package/src/providers/globalworkbuddy/payload.js +80 -80
- package/src/providers/index.js +5 -5
- package/src/providers/model-id.js +172 -172
- package/src/providers/opencode.js +19 -19
- package/src/providers/openrouter.js +31 -31
- package/src/providers/qoder/account-store.js +106 -106
- package/src/providers/qoder/aggregate.js +60 -60
- package/src/providers/qoder/baseprompt.json +591 -591
- package/src/providers/qoder/checkin.js +160 -160
- package/src/providers/qoder/constants.js +44 -44
- package/src/providers/qoder/encode.js +41 -41
- package/src/providers/qoder/fingerprint.js +38 -38
- package/src/providers/qoder/models.js +77 -77
- package/src/providers/qoder/oauth.js +84 -84
- package/src/providers/qoder/payload.js +162 -162
- package/src/providers/qoder/request.js +27 -27
- package/src/providers/qoder/session.js +134 -134
- package/src/providers/qoder/sticky.js +38 -38
- package/src/providers/qoder/stream.js +116 -116
- package/src/providers/qoder.js +1 -1
- package/src/providers/raccoon/account-store.js +216 -216
- package/src/providers/raccoon/auth.js +67 -67
- package/src/providers/raccoon/chat.js +228 -228
- package/src/providers/raccoon/const.js +180 -165
- package/src/providers/raccoon/credits.js +185 -175
- package/src/providers/raccoon/crypto.js +43 -0
- package/src/providers/raccoon/envelope.js +31 -31
- package/src/providers/raccoon/headers.js +45 -45
- package/src/providers/raccoon/index.js +216 -216
- package/src/providers/raccoon/login.js +279 -279
- package/src/providers/raccoon/models.js +160 -160
- package/src/providers/raccoon/password-login.js +102 -87
- package/src/providers/raccoon/qr-codewords.js +115 -115
- package/src/providers/raccoon/qr.js +236 -236
- package/src/providers/raccoon/sse.js +135 -135
- package/src/providers/responses-channel.js +120 -120
- package/src/providers/share-keys.js +53 -53
- package/src/providers/traework/account-store.js +234 -234
- package/src/providers/traework/chat.js +217 -217
- package/src/providers/traework/checkin.js +77 -77
- package/src/providers/traework/constants.js +41 -41
- package/src/providers/traework/errors.js +52 -52
- package/src/providers/traework/headers.js +79 -79
- package/src/providers/traework/index.js +132 -132
- package/src/providers/traework/market-identity.js +116 -116
- package/src/providers/traework/models.js +98 -98
- package/src/providers/traework/payload.js +86 -86
- package/src/providers/traework/sse.js +184 -184
- package/src/providers/traework/token.js +52 -52
- package/src/providers/traework.js +2 -2
- package/src/providers/workbuddy/account-store.js +186 -186
- package/src/providers/workbuddy/auth.js +158 -158
- package/src/providers/workbuddy/balance.js +86 -86
- package/src/providers/workbuddy/cat-travel.js +125 -125
- package/src/providers/workbuddy/checkin.js +75 -75
- package/src/providers/workbuddy/desktop-info.js +78 -78
- package/src/providers/workbuddy/growth-api.js +67 -67
- package/src/providers/workbuddy/growth-plans.js +63 -63
- package/src/providers/workbuddy/growth.js +181 -181
- package/src/providers/workbuddy/index.js +217 -217
- package/src/providers/workbuddy/models.js +126 -126
- package/src/providers/workbuddy/payload.js +141 -141
- package/src/providers/workbuddy/rotation-log.js +83 -83
- package/src/providers/workbuddy/sanitize-tools.js +61 -61
- package/src/providers/workbuddy/sdk-chat.js +26 -26
- package/src/providers/workbuddy-balance.js +78 -78
- package/src/providers/zcode/account-store.js +129 -129
- package/src/providers/zcode/auth.js +28 -28
- package/src/providers/zcode/chat.js +179 -179
- package/src/providers/zcode/const.js +54 -54
- package/src/providers/zcode/context-shape.js +162 -162
- package/src/providers/zcode/headers.js +93 -93
- package/src/providers/zcode/index.js +124 -124
- package/src/providers/zcode/models.js +65 -65
- package/src/providers/zcode/oauth.js +120 -120
- package/src/providers/zcode/quota.js +176 -176
- package/src/providers/zcode/sse.js +196 -196
- package/src/readline-compat.js +25 -25
- package/src/responses/translate.js +311 -311
- package/src/routes/chat/broadband-handler.js +72 -72
- package/src/routes/chat/empty-turn-report.js +31 -31
- package/src/routes/chat/exhausted-handler.js +87 -87
- package/src/routes/chat/hedge-handler.js +130 -130
- package/src/routes/chat/index.js +1 -1
- package/src/routes/chat/local-handler.js +63 -63
- package/src/routes/chat/peer-handler.js +81 -81
- package/src/routes/chat.js +3 -3
- package/src/routes/fallback.js +88 -88
- package/src/routes/groups-relay.js +214 -214
- package/src/routes/groups.js +122 -122
- package/src/routes/helpers.js +83 -83
- package/src/routes/index.js +147 -147
- package/src/routes/messages-route.js +365 -365
- package/src/routes/peers.js +23 -1
- package/src/routes/relay-queue.js +181 -181
- package/src/routes/relay.js +60 -60
- package/src/routes/responses-route.js +213 -213
- package/src/routes/stream-body.js +84 -84
- package/src/routes/stream-hold.js +337 -337
- package/src/routes/stream-scan.js +366 -366
- package/src/routes.js +3 -3
- package/src/runtime/auto-update.js +113 -113
- package/src/runtime/bootstrap.js +8 -0
- package/src/runtime/broadband-stream.js +79 -79
- package/src/runtime/broadband.js +103 -103
- package/src/runtime/group-sync.js +81 -81
- package/src/runtime/keep-warm.js +120 -0
- package/src/runtime/lifecycle-forensics.js +116 -116
- package/src/runtime/lifecycle-log.js +87 -87
- package/src/runtime/log-stamp.js +73 -73
- package/src/runtime/proc-info.js +137 -137
- package/src/runtime/qoder-checkin.js +93 -93
- package/src/runtime/raccoon-checkin.js +126 -126
- package/src/runtime/server-lifecycle.js +189 -189
- package/src/runtime/traework-checkin.js +118 -118
- package/src/runtime/workbuddy-checkin.js +120 -120
- package/src/runtime/workbuddy-growth.js +133 -133
- package/src/server.js +7 -0
- package/src/state/facade.js +58 -58
- package/src/state/memory.js +162 -162
- package/src/state/merge.js +25 -25
- package/src/state/migrations/cline-unify.js +94 -94
- package/src/state/migrations.js +33 -33
- package/src/state/persist.js +42 -42
- package/src/state/provider-config.js +142 -142
- package/src/state/schemas/group.js +31 -31
- package/src/state/schemas/model.js +94 -94
- package/src/state/schemas/peer.js +31 -31
- package/src/state/schemas/port.js +10 -10
- package/src/state/schemas/provider.js +202 -202
- package/src/state/schemas/timezone.js +70 -70
- package/src/state/schemas/token.js +48 -48
- package/src/state/schemas/use-group.js +102 -102
- package/src/state/store.js +176 -176
- package/src/state.js +1 -1
- package/src/sync-claude-desktop.js +234 -234
- package/src/sync-claude.js +152 -152
- package/src/sync-codex.js +116 -116
- package/src/sync-workbuddy.js +158 -158
- package/src/talk-full-redact.js +129 -129
- package/src/talk-full.js +131 -131
- package/src/talk-log.js +257 -257
- package/src/text-tokens.js +52 -52
- package/src/thinking-effort.js +67 -67
- package/src/time.js +106 -106
- package/src/timeline.js +26 -26
- package/src/transport/index.js +1 -1
- package/src/upstream-engine/index.js +74 -74
- package/src/upstream-engine/mode.js +15 -15
- package/src/upstream-engine/sdk/attempt.js +221 -221
- package/src/upstream-engine/sdk/chat.js +28 -28
- package/src/upstream-engine/sdk/convert.js +192 -192
- package/src/upstream-engine/sdk/diagnose.js +62 -62
- package/src/upstream-engine/sdk/dispatch.js +55 -55
- package/src/upstream-engine/sdk/responses.js +176 -176
- package/src/upstream-engine/sdk/sse.js +166 -166
- package/src/upstream-responses.js +305 -305
- package/src/usage/record.js +106 -106
- package/src/usage/report.js +195 -195
- package/src/v6pool/claim.js +157 -157
- package/src/v6pool/config.js +65 -65
- package/src/v6pool/detect.js +130 -130
- package/src/v6pool/index.js +152 -152
- package/src/v6pool/prefix.js +140 -140
- package/src/v6pool/probe.js +40 -40
- package/src/v6pool/report.js +104 -104
- package/src/v6pool/rotate.js +263 -263
- package/src/warp-pool/config.js +74 -74
- package/src/warp-pool/health.js +106 -106
- package/src/warp-pool/identity.js +141 -141
- package/src/warp-pool/index.js +358 -358
- package/src/warp-pool/keys.js +29 -29
- package/src/warp-pool/nodes.js +95 -95
- package/src/warp-pool/ports.js +160 -160
- package/src/warp-pool/register.js +113 -113
- package/src/warp-pool/report.js +232 -232
- package/src/warp-pool/revive.js +168 -168
- package/src/warp-pool/rotate.js +214 -214
- package/src/warp-pool/strategy.js +43 -43
- package/src/warp-pool/verdict.js +69 -69
- package/src/warp-pool/wireproxy.js +162 -162
- package/docs/cli_help_mini.md +0 -146
- package/src/providers/AGENTS.md +0 -49
- package/src/routes/AGENTS.md +0 -37
|
@@ -1,182 +1,182 @@
|
|
|
1
|
-
// 模型目录(按账号隔离)+ 三路发现(agent-center / builtin / 福利网关)+ 福利 claim。
|
|
2
|
-
// 福利是按账号授予的:目录按 userId 存,isBenefit 只信「发起请求的账号」的目录;
|
|
3
|
-
// 目录里没有的模型回退冷启动种子(少带 maas_type 头 = InferHub.002002009.404)。
|
|
4
|
-
// 算法对齐 HITZY2002/codearts2api internal/upstream/models.go。
|
|
5
|
-
import {
|
|
6
|
-
SNAP_BASE, BENEFIT_HOST, EP_MODEL_BUILTIN, EP_AGENT_LIST, EP_AGENT_DETAIL,
|
|
7
|
-
EP_BENEFIT_CONFIG, EP_BENEFIT_CLAIM,
|
|
8
|
-
SEED_BENEFIT_MODELS, SEED_KNOWN_MODELS, CATALOG_TTL_MS,
|
|
9
|
-
} from "./const.js";
|
|
10
|
-
import { signRequest } from "./sign.js";
|
|
11
|
-
import { compatFetch } from "../../compat.js";
|
|
12
|
-
|
|
13
|
-
const lower = (s) => String(s || "").trim().toLowerCase();
|
|
14
|
-
|
|
15
|
-
export function createCatalog() {
|
|
16
|
-
const known = new Map(); // lower → 精确 ID(种子 + 已发现,大小写归一单点)
|
|
17
|
-
for (const id of [...SEED_KNOWN_MODELS, ...SEED_BENEFIT_MODELS]) {
|
|
18
|
-
if (!known.has(lower(id))) known.set(lower(id), id);
|
|
19
|
-
}
|
|
20
|
-
const accounts = new Map(); // userId → {models, benefit:Set, knows:Set, lastBenefit:Map, fetched}
|
|
21
|
-
|
|
22
|
-
function setAccount(userId, models, { keepBenefit = false, now = Date.now() } = {}) {
|
|
23
|
-
if (!userId) return;
|
|
24
|
-
const prev = accounts.get(userId);
|
|
25
|
-
const ac = { models: [], benefit: new Set(), knows: new Set(), lastBenefit: prev ? new Map(prev.lastBenefit) : new Map(), fetched: now };
|
|
26
|
-
for (const m of models || []) {
|
|
27
|
-
if (!m?.id) continue;
|
|
28
|
-
const key = lower(m.id);
|
|
29
|
-
ac.knows.add(key);
|
|
30
|
-
if (m.benefit) { ac.benefit.add(key); ac.lastBenefit.set(key, m); }
|
|
31
|
-
if (!known.has(key) || m.id !== key) known.set(key, m.id);
|
|
32
|
-
ac.models.push(m);
|
|
33
|
-
}
|
|
34
|
-
if (keepBenefit) {
|
|
35
|
-
// 福利来源失败但内置成功:上轮福利条目只要内置没明确登记(转正)就保留标记
|
|
36
|
-
for (const [key, mi] of ac.lastBenefit) {
|
|
37
|
-
if (ac.knows.has(key)) continue;
|
|
38
|
-
ac.benefit.add(key);
|
|
39
|
-
ac.knows.add(key);
|
|
40
|
-
ac.models.push(mi);
|
|
41
|
-
if (!known.has(key) || mi.id !== key) known.set(key, mi.id);
|
|
42
|
-
}
|
|
43
|
-
ac.models.sort((a, b) => (lower(a.id) < lower(b.id) ? -1 : lower(a.id) > lower(b.id) ? 1 : (a.id < b.id ? -1 : 1)));
|
|
44
|
-
}
|
|
45
|
-
accounts.set(userId, ac);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// 判定顺序:账号目录标了福利 → true;目录里有但没标 → false(已转正);目录没有 → 种子兜底。
|
|
49
|
-
function isBenefit(userId, model) {
|
|
50
|
-
const key = lower(model);
|
|
51
|
-
if (!key) return false;
|
|
52
|
-
const ac = accounts.get(userId);
|
|
53
|
-
if (ac) {
|
|
54
|
-
if (ac.benefit.has(key)) return true;
|
|
55
|
-
if (ac.knows.has(key)) return false;
|
|
56
|
-
}
|
|
57
|
-
return SEED_BENEFIT_MODELS.some((m) => lower(m) === key);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function canonical(model) {
|
|
61
|
-
const exact = known.get(lower(model));
|
|
62
|
-
return exact || null;
|
|
63
|
-
}
|
|
64
|
-
function accountModels(userId) {
|
|
65
|
-
const ac = accounts.get(userId);
|
|
66
|
-
return ac ? [...ac.models] : [];
|
|
67
|
-
}
|
|
68
|
-
function isStale(userId, now = Date.now(), ttlMs = CATALOG_TTL_MS) {
|
|
69
|
-
const ac = accounts.get(userId);
|
|
70
|
-
return !ac || now - ac.fetched >= ttlMs;
|
|
71
|
-
}
|
|
72
|
-
return { setAccount, isBenefit, canonical, accountModels, isStale };
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** 多路合并:按小写 ID 去重,福利标记取或,参数更全/精确大小写优先,按小写 ID 排序。 */
|
|
76
|
-
export function mergeModels(sets) {
|
|
77
|
-
const merged = new Map();
|
|
78
|
-
for (const set of sets || []) {
|
|
79
|
-
for (const m of set || []) {
|
|
80
|
-
if (!m?.id) continue;
|
|
81
|
-
const key = lower(m.id);
|
|
82
|
-
const cur = merged.get(key);
|
|
83
|
-
if (!cur) { merged.set(key, { ...m }); continue; }
|
|
84
|
-
const keep = (m.contextWindow > 0 && !cur.contextWindow) || (m.id !== lower(m.id) && cur.id === lower(cur.id)) ? m : cur;
|
|
85
|
-
const drop = keep === m ? cur : m;
|
|
86
|
-
merged.set(key, {
|
|
87
|
-
...keep,
|
|
88
|
-
benefit: !!(keep.benefit || drop.benefit),
|
|
89
|
-
name: keep.name || drop.name || "",
|
|
90
|
-
contextWindow: keep.contextWindow || drop.contextWindow || 0,
|
|
91
|
-
maxTokens: keep.maxTokens || drop.maxTokens || 0,
|
|
92
|
-
desc: keep.desc || drop.desc || "",
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
return [...merged.values()].sort((a, b) => (lower(a.id) < lower(b.id) ? -1 : lower(a.id) > lower(b.id) ? 1 : (a.id < b.id ? -1 : 1)));
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** 签名 GET 并解析 JSON(Agent-Type 可选;空 body 签名 = sha256(""))。 */
|
|
100
|
-
export async function signedGetJson({ url, cred, agentType, fetchImpl }) {
|
|
101
|
-
const doFetch = fetchImpl || compatFetch;
|
|
102
|
-
const headers = { "content-type": "application/json", "x-language": "zh-cn" };
|
|
103
|
-
if (agentType) headers["agent-type"] = agentType;
|
|
104
|
-
if (cred?.securityToken) headers["x-security-token"] = cred.securityToken;
|
|
105
|
-
const { headers: signed } = signRequest({ method: "GET", url, headers, body: "", cred });
|
|
106
|
-
const res = await doFetch(url, { method: "GET", headers: signed });
|
|
107
|
-
const raw = await res.text().catch(() => "");
|
|
108
|
-
if (res.status >= 400) throw new Error(`http ${res.status}: ${String(raw).slice(0, 200)}`);
|
|
109
|
-
try { return JSON.parse(raw); } catch { throw new Error(`non-JSON body: ${String(raw).slice(0, 120)}`); }
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** 幂等领取限时福利(官方客户端打开模型菜单即调用;error_code "0000" 视为成功)。 */
|
|
113
|
-
export async function claimBenefit({ cred, benefitHost = BENEFIT_HOST, fetchImpl }) {
|
|
114
|
-
const doFetch = fetchImpl || compatFetch;
|
|
115
|
-
const url = benefitHost + EP_BENEFIT_CLAIM;
|
|
116
|
-
const body = "{}";
|
|
117
|
-
const headers = { "content-type": "application/json", "x-language": "zh-cn" };
|
|
118
|
-
if (cred?.securityToken) headers["x-security-token"] = cred.securityToken;
|
|
119
|
-
const { headers: signed } = signRequest({ method: "POST", url, headers, body, cred });
|
|
120
|
-
const res = await doFetch(url, { method: "POST", headers: signed, body });
|
|
121
|
-
const raw = await res.text().catch(() => "");
|
|
122
|
-
if (res.status >= 400) throw new Error(`claim http ${res.status}: ${String(raw).slice(0, 200)}`);
|
|
123
|
-
const json = JSON.parse(raw);
|
|
124
|
-
if (String(json?.error_code || "") !== "0000") throw new Error(`claim failed: error_code=${json?.error_code} msg=${json?.error_msg}`);
|
|
125
|
-
return json;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
const toModelInfo = (m, { benefit = false } = {}) => {
|
|
129
|
-
const id = m?.model_id || m?.model_name || m?.modelAlias || "";
|
|
130
|
-
if (!id) return null;
|
|
131
|
-
return {
|
|
132
|
-
id: String(id),
|
|
133
|
-
name: String(m?.model_name || id),
|
|
134
|
-
contextWindow: Number(m?.context_window) || 0,
|
|
135
|
-
maxTokens: Number(m?.max_tokens) || 0,
|
|
136
|
-
benefit,
|
|
137
|
-
desc: String(m?.model_desc || ""),
|
|
138
|
-
};
|
|
139
|
-
};
|
|
140
|
-
|
|
141
|
-
/** 三路发现(任一路失败不阻断)→ {models, builtinOk, benefitOk, agentOk}。 */
|
|
142
|
-
export async function discoverAccountModels({ account, snapBase = SNAP_BASE, benefitHost = BENEFIT_HOST, autoClaim = true, fetchImpl } = {}) {
|
|
143
|
-
const cred = { accessKeyId: account.accessKeyId, secretAccessKey: account.secretAccessKey, securityToken: account.securityToken };
|
|
144
|
-
const sets = [];
|
|
145
|
-
let agentOk = false, builtinOk = false, benefitOk = false;
|
|
146
|
-
|
|
147
|
-
// 1) agent-center:useragents 找 CodeAgent → detail.gpts.models
|
|
148
|
-
try {
|
|
149
|
-
const list = await signedGetJson({ url: `${snapBase}${EP_AGENT_LIST}?offset=0&limit=100&is_primary_agent=true`, cred, agentType: "AgentCenter", fetchImpl });
|
|
150
|
-
const agents = Array.isArray(list?.agents) ? list.agents : [];
|
|
151
|
-
const pick = agents.find((a) => a?.agent_name === "CodeAgent" && a?.alias?.alias_zh_cn === "智能体" && a?.show_in_ide)
|
|
152
|
-
|| agents.find((a) => a?.is_primary_agent) || agents[0];
|
|
153
|
-
if (pick?.agent_id) {
|
|
154
|
-
const detail = await signedGetJson({ url: `${snapBase}${EP_AGENT_DETAIL}?agent_id=${encodeURIComponent(pick.agent_id)}`, cred, agentType: "AgentCenter", fetchImpl });
|
|
155
|
-
const models = (Array.isArray(detail?.gpts?.models) ? detail.gpts.models : [])
|
|
156
|
-
.map((m) => toModelInfo({ model_id: m?.model_id, model_name: m?.model_name || m?.model_alias, context_window: m?.model_parameters?.context_window, max_tokens: m?.model_parameters?.max_tokens, model_desc: m?.model_parameters?.model_desc }))
|
|
157
|
-
.filter(Boolean);
|
|
158
|
-
if (models.length) { sets.push(models); agentOk = true; }
|
|
159
|
-
}
|
|
160
|
-
} catch { /* agent 路失败不阻断 */ }
|
|
161
|
-
|
|
162
|
-
// 2) 内置模型(Agent-Type: PromptCenter)
|
|
163
|
-
try {
|
|
164
|
-
const json = await signedGetJson({ url: `${snapBase}${EP_MODEL_BUILTIN}`, cred, agentType: "PromptCenter", fetchImpl });
|
|
165
|
-
const models = (Array.isArray(json?.builtinModels) ? json.builtinModels : []).map((m) => toModelInfo(m)).filter(Boolean);
|
|
166
|
-
if (models.length) { sets.push(models); builtinOk = true; }
|
|
167
|
-
} catch { /* builtin 失败不阻断 */ }
|
|
168
|
-
|
|
169
|
-
// 3) 福利网关(先幂等 claim 再拉目录;error_code!=0000 视为该来源失败)
|
|
170
|
-
try {
|
|
171
|
-
if (autoClaim) { try { await claimBenefit({ cred, benefitHost, fetchImpl }); } catch { /* 未开通福利套餐时 claim 可能报错,继续拉目录 */ } }
|
|
172
|
-
const json = await signedGetJson({ url: benefitHost + EP_BENEFIT_CONFIG, cred, fetchImpl });
|
|
173
|
-
if (String(json?.error_code || "") === "0000") {
|
|
174
|
-
const models = (Array.isArray(json?.result?.models) ? json.result.models : []).map((m) => toModelInfo(m, { benefit: true })).filter(Boolean);
|
|
175
|
-
if (models.length) { sets.push(models); benefitOk = true; }
|
|
176
|
-
}
|
|
177
|
-
} catch { /* benefit 失败不阻断 */ }
|
|
178
|
-
|
|
179
|
-
const models = mergeModels(sets);
|
|
180
|
-
if (!models.length) throw new Error("codearts models api returned empty list");
|
|
181
|
-
return { models, agentOk, builtinOk, benefitOk };
|
|
182
|
-
}
|
|
1
|
+
// 模型目录(按账号隔离)+ 三路发现(agent-center / builtin / 福利网关)+ 福利 claim。
|
|
2
|
+
// 福利是按账号授予的:目录按 userId 存,isBenefit 只信「发起请求的账号」的目录;
|
|
3
|
+
// 目录里没有的模型回退冷启动种子(少带 maas_type 头 = InferHub.002002009.404)。
|
|
4
|
+
// 算法对齐 HITZY2002/codearts2api internal/upstream/models.go。
|
|
5
|
+
import {
|
|
6
|
+
SNAP_BASE, BENEFIT_HOST, EP_MODEL_BUILTIN, EP_AGENT_LIST, EP_AGENT_DETAIL,
|
|
7
|
+
EP_BENEFIT_CONFIG, EP_BENEFIT_CLAIM,
|
|
8
|
+
SEED_BENEFIT_MODELS, SEED_KNOWN_MODELS, CATALOG_TTL_MS,
|
|
9
|
+
} from "./const.js";
|
|
10
|
+
import { signRequest } from "./sign.js";
|
|
11
|
+
import { compatFetch } from "../../compat.js";
|
|
12
|
+
|
|
13
|
+
const lower = (s) => String(s || "").trim().toLowerCase();
|
|
14
|
+
|
|
15
|
+
export function createCatalog() {
|
|
16
|
+
const known = new Map(); // lower → 精确 ID(种子 + 已发现,大小写归一单点)
|
|
17
|
+
for (const id of [...SEED_KNOWN_MODELS, ...SEED_BENEFIT_MODELS]) {
|
|
18
|
+
if (!known.has(lower(id))) known.set(lower(id), id);
|
|
19
|
+
}
|
|
20
|
+
const accounts = new Map(); // userId → {models, benefit:Set, knows:Set, lastBenefit:Map, fetched}
|
|
21
|
+
|
|
22
|
+
function setAccount(userId, models, { keepBenefit = false, now = Date.now() } = {}) {
|
|
23
|
+
if (!userId) return;
|
|
24
|
+
const prev = accounts.get(userId);
|
|
25
|
+
const ac = { models: [], benefit: new Set(), knows: new Set(), lastBenefit: prev ? new Map(prev.lastBenefit) : new Map(), fetched: now };
|
|
26
|
+
for (const m of models || []) {
|
|
27
|
+
if (!m?.id) continue;
|
|
28
|
+
const key = lower(m.id);
|
|
29
|
+
ac.knows.add(key);
|
|
30
|
+
if (m.benefit) { ac.benefit.add(key); ac.lastBenefit.set(key, m); }
|
|
31
|
+
if (!known.has(key) || m.id !== key) known.set(key, m.id);
|
|
32
|
+
ac.models.push(m);
|
|
33
|
+
}
|
|
34
|
+
if (keepBenefit) {
|
|
35
|
+
// 福利来源失败但内置成功:上轮福利条目只要内置没明确登记(转正)就保留标记
|
|
36
|
+
for (const [key, mi] of ac.lastBenefit) {
|
|
37
|
+
if (ac.knows.has(key)) continue;
|
|
38
|
+
ac.benefit.add(key);
|
|
39
|
+
ac.knows.add(key);
|
|
40
|
+
ac.models.push(mi);
|
|
41
|
+
if (!known.has(key) || mi.id !== key) known.set(key, mi.id);
|
|
42
|
+
}
|
|
43
|
+
ac.models.sort((a, b) => (lower(a.id) < lower(b.id) ? -1 : lower(a.id) > lower(b.id) ? 1 : (a.id < b.id ? -1 : 1)));
|
|
44
|
+
}
|
|
45
|
+
accounts.set(userId, ac);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 判定顺序:账号目录标了福利 → true;目录里有但没标 → false(已转正);目录没有 → 种子兜底。
|
|
49
|
+
function isBenefit(userId, model) {
|
|
50
|
+
const key = lower(model);
|
|
51
|
+
if (!key) return false;
|
|
52
|
+
const ac = accounts.get(userId);
|
|
53
|
+
if (ac) {
|
|
54
|
+
if (ac.benefit.has(key)) return true;
|
|
55
|
+
if (ac.knows.has(key)) return false;
|
|
56
|
+
}
|
|
57
|
+
return SEED_BENEFIT_MODELS.some((m) => lower(m) === key);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function canonical(model) {
|
|
61
|
+
const exact = known.get(lower(model));
|
|
62
|
+
return exact || null;
|
|
63
|
+
}
|
|
64
|
+
function accountModels(userId) {
|
|
65
|
+
const ac = accounts.get(userId);
|
|
66
|
+
return ac ? [...ac.models] : [];
|
|
67
|
+
}
|
|
68
|
+
function isStale(userId, now = Date.now(), ttlMs = CATALOG_TTL_MS) {
|
|
69
|
+
const ac = accounts.get(userId);
|
|
70
|
+
return !ac || now - ac.fetched >= ttlMs;
|
|
71
|
+
}
|
|
72
|
+
return { setAccount, isBenefit, canonical, accountModels, isStale };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 多路合并:按小写 ID 去重,福利标记取或,参数更全/精确大小写优先,按小写 ID 排序。 */
|
|
76
|
+
export function mergeModels(sets) {
|
|
77
|
+
const merged = new Map();
|
|
78
|
+
for (const set of sets || []) {
|
|
79
|
+
for (const m of set || []) {
|
|
80
|
+
if (!m?.id) continue;
|
|
81
|
+
const key = lower(m.id);
|
|
82
|
+
const cur = merged.get(key);
|
|
83
|
+
if (!cur) { merged.set(key, { ...m }); continue; }
|
|
84
|
+
const keep = (m.contextWindow > 0 && !cur.contextWindow) || (m.id !== lower(m.id) && cur.id === lower(cur.id)) ? m : cur;
|
|
85
|
+
const drop = keep === m ? cur : m;
|
|
86
|
+
merged.set(key, {
|
|
87
|
+
...keep,
|
|
88
|
+
benefit: !!(keep.benefit || drop.benefit),
|
|
89
|
+
name: keep.name || drop.name || "",
|
|
90
|
+
contextWindow: keep.contextWindow || drop.contextWindow || 0,
|
|
91
|
+
maxTokens: keep.maxTokens || drop.maxTokens || 0,
|
|
92
|
+
desc: keep.desc || drop.desc || "",
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return [...merged.values()].sort((a, b) => (lower(a.id) < lower(b.id) ? -1 : lower(a.id) > lower(b.id) ? 1 : (a.id < b.id ? -1 : 1)));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 签名 GET 并解析 JSON(Agent-Type 可选;空 body 签名 = sha256(""))。 */
|
|
100
|
+
export async function signedGetJson({ url, cred, agentType, fetchImpl }) {
|
|
101
|
+
const doFetch = fetchImpl || compatFetch;
|
|
102
|
+
const headers = { "content-type": "application/json", "x-language": "zh-cn" };
|
|
103
|
+
if (agentType) headers["agent-type"] = agentType;
|
|
104
|
+
if (cred?.securityToken) headers["x-security-token"] = cred.securityToken;
|
|
105
|
+
const { headers: signed } = signRequest({ method: "GET", url, headers, body: "", cred });
|
|
106
|
+
const res = await doFetch(url, { method: "GET", headers: signed });
|
|
107
|
+
const raw = await res.text().catch(() => "");
|
|
108
|
+
if (res.status >= 400) throw new Error(`http ${res.status}: ${String(raw).slice(0, 200)}`);
|
|
109
|
+
try { return JSON.parse(raw); } catch { throw new Error(`non-JSON body: ${String(raw).slice(0, 120)}`); }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 幂等领取限时福利(官方客户端打开模型菜单即调用;error_code "0000" 视为成功)。 */
|
|
113
|
+
export async function claimBenefit({ cred, benefitHost = BENEFIT_HOST, fetchImpl }) {
|
|
114
|
+
const doFetch = fetchImpl || compatFetch;
|
|
115
|
+
const url = benefitHost + EP_BENEFIT_CLAIM;
|
|
116
|
+
const body = "{}";
|
|
117
|
+
const headers = { "content-type": "application/json", "x-language": "zh-cn" };
|
|
118
|
+
if (cred?.securityToken) headers["x-security-token"] = cred.securityToken;
|
|
119
|
+
const { headers: signed } = signRequest({ method: "POST", url, headers, body, cred });
|
|
120
|
+
const res = await doFetch(url, { method: "POST", headers: signed, body });
|
|
121
|
+
const raw = await res.text().catch(() => "");
|
|
122
|
+
if (res.status >= 400) throw new Error(`claim http ${res.status}: ${String(raw).slice(0, 200)}`);
|
|
123
|
+
const json = JSON.parse(raw);
|
|
124
|
+
if (String(json?.error_code || "") !== "0000") throw new Error(`claim failed: error_code=${json?.error_code} msg=${json?.error_msg}`);
|
|
125
|
+
return json;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const toModelInfo = (m, { benefit = false } = {}) => {
|
|
129
|
+
const id = m?.model_id || m?.model_name || m?.modelAlias || "";
|
|
130
|
+
if (!id) return null;
|
|
131
|
+
return {
|
|
132
|
+
id: String(id),
|
|
133
|
+
name: String(m?.model_name || id),
|
|
134
|
+
contextWindow: Number(m?.context_window) || 0,
|
|
135
|
+
maxTokens: Number(m?.max_tokens) || 0,
|
|
136
|
+
benefit,
|
|
137
|
+
desc: String(m?.model_desc || ""),
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** 三路发现(任一路失败不阻断)→ {models, builtinOk, benefitOk, agentOk}。 */
|
|
142
|
+
export async function discoverAccountModels({ account, snapBase = SNAP_BASE, benefitHost = BENEFIT_HOST, autoClaim = true, fetchImpl } = {}) {
|
|
143
|
+
const cred = { accessKeyId: account.accessKeyId, secretAccessKey: account.secretAccessKey, securityToken: account.securityToken };
|
|
144
|
+
const sets = [];
|
|
145
|
+
let agentOk = false, builtinOk = false, benefitOk = false;
|
|
146
|
+
|
|
147
|
+
// 1) agent-center:useragents 找 CodeAgent → detail.gpts.models
|
|
148
|
+
try {
|
|
149
|
+
const list = await signedGetJson({ url: `${snapBase}${EP_AGENT_LIST}?offset=0&limit=100&is_primary_agent=true`, cred, agentType: "AgentCenter", fetchImpl });
|
|
150
|
+
const agents = Array.isArray(list?.agents) ? list.agents : [];
|
|
151
|
+
const pick = agents.find((a) => a?.agent_name === "CodeAgent" && a?.alias?.alias_zh_cn === "智能体" && a?.show_in_ide)
|
|
152
|
+
|| agents.find((a) => a?.is_primary_agent) || agents[0];
|
|
153
|
+
if (pick?.agent_id) {
|
|
154
|
+
const detail = await signedGetJson({ url: `${snapBase}${EP_AGENT_DETAIL}?agent_id=${encodeURIComponent(pick.agent_id)}`, cred, agentType: "AgentCenter", fetchImpl });
|
|
155
|
+
const models = (Array.isArray(detail?.gpts?.models) ? detail.gpts.models : [])
|
|
156
|
+
.map((m) => toModelInfo({ model_id: m?.model_id, model_name: m?.model_name || m?.model_alias, context_window: m?.model_parameters?.context_window, max_tokens: m?.model_parameters?.max_tokens, model_desc: m?.model_parameters?.model_desc }))
|
|
157
|
+
.filter(Boolean);
|
|
158
|
+
if (models.length) { sets.push(models); agentOk = true; }
|
|
159
|
+
}
|
|
160
|
+
} catch { /* agent 路失败不阻断 */ }
|
|
161
|
+
|
|
162
|
+
// 2) 内置模型(Agent-Type: PromptCenter)
|
|
163
|
+
try {
|
|
164
|
+
const json = await signedGetJson({ url: `${snapBase}${EP_MODEL_BUILTIN}`, cred, agentType: "PromptCenter", fetchImpl });
|
|
165
|
+
const models = (Array.isArray(json?.builtinModels) ? json.builtinModels : []).map((m) => toModelInfo(m)).filter(Boolean);
|
|
166
|
+
if (models.length) { sets.push(models); builtinOk = true; }
|
|
167
|
+
} catch { /* builtin 失败不阻断 */ }
|
|
168
|
+
|
|
169
|
+
// 3) 福利网关(先幂等 claim 再拉目录;error_code!=0000 视为该来源失败)
|
|
170
|
+
try {
|
|
171
|
+
if (autoClaim) { try { await claimBenefit({ cred, benefitHost, fetchImpl }); } catch { /* 未开通福利套餐时 claim 可能报错,继续拉目录 */ } }
|
|
172
|
+
const json = await signedGetJson({ url: benefitHost + EP_BENEFIT_CONFIG, cred, fetchImpl });
|
|
173
|
+
if (String(json?.error_code || "") === "0000") {
|
|
174
|
+
const models = (Array.isArray(json?.result?.models) ? json.result.models : []).map((m) => toModelInfo(m, { benefit: true })).filter(Boolean);
|
|
175
|
+
if (models.length) { sets.push(models); benefitOk = true; }
|
|
176
|
+
}
|
|
177
|
+
} catch { /* benefit 失败不阻断 */ }
|
|
178
|
+
|
|
179
|
+
const models = mergeModels(sets);
|
|
180
|
+
if (!models.length) throw new Error("codearts models api returned empty list");
|
|
181
|
+
return { models, agentOk, builtinOk, benefitOk };
|
|
182
|
+
}
|
|
@@ -1,96 +1,96 @@
|
|
|
1
|
-
// 华为云 SDK-HMAC-SHA256 请求签名(AK/SK + 可选 STS security token)。
|
|
2
|
-
// 对齐 @huaweicloud/huaweicloud-sdk-core AKSKSigner(逆向参考:HITZY2002/codearts2api internal/upstream/signer.go):
|
|
3
|
-
// - SignedHeaders = 请求全部头(小写排序,含 host / x-sdk-content-sha256 / maas_type)
|
|
4
|
-
// - CanonicalURI 每段 percent-encode 且末尾补 "/"
|
|
5
|
-
// - payload hash 取 X-Sdk-Content-Sha256(= 请求体原样 sha256 hex)
|
|
6
|
-
import crypto from "node:crypto";
|
|
7
|
-
|
|
8
|
-
export const SIGN_ALGORITHM = "SDK-HMAC-SHA256";
|
|
9
|
-
|
|
10
|
-
export function sha256Hex(data) {
|
|
11
|
-
const buf = typeof data === "string" ? Buffer.from(data, "utf8") : (data || Buffer.alloc(0));
|
|
12
|
-
return crypto.createHash("sha256").update(buf).digest("hex");
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function hmacHex(key, msg) {
|
|
16
|
-
return crypto.createHmac("sha256", String(key || "")).update(String(msg || ""), "utf8").digest("hex");
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
// Go url.PathEscape(encodePathSegment):仅 / ; , ? 与非 URI 字符转义。
|
|
20
|
-
// 本项目全部端点路径均为纯字母数字(恒等),此处按 RFC3986 pchar 集保守实现。
|
|
21
|
-
const PCHAR = /[^A-Za-z0-9\-._~!$&'()*+,;=:@]/g;
|
|
22
|
-
function escapeSegment(seg) {
|
|
23
|
-
return String(seg || "").replace(PCHAR, (c) => encodeURIComponent(c));
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// 末尾强制补 "/"(对齐 JS SDK CanonicalURI;漏掉即签名失败)。
|
|
27
|
-
export function canonicalUriPath(pathname) {
|
|
28
|
-
const out = String(pathname || "/").split("/").map(escapeSegment).join("/");
|
|
29
|
-
return out.endsWith("/") ? out : out + "/";
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// Go url.QueryEscape:空格 → "+";key/value 各自排序。
|
|
33
|
-
const QESC = (s) => encodeURIComponent(s).replace(/%20/g, "+").replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
|
|
34
|
-
function decodeSafe(s) { try { return decodeURIComponent(s); } catch { return s; } }
|
|
35
|
-
|
|
36
|
-
export function canonicalQuery(rawQuery) {
|
|
37
|
-
const raw = String(rawQuery || "");
|
|
38
|
-
if (!raw) return "";
|
|
39
|
-
const pairs = raw.replace(/^\?/, "").split("&").filter(Boolean).map((p) => {
|
|
40
|
-
const i = p.indexOf("=");
|
|
41
|
-
const k = i < 0 ? p : p.slice(0, i);
|
|
42
|
-
const v = i < 0 ? "" : p.slice(i + 1);
|
|
43
|
-
return [decodeSafe(k), decodeSafe(v)];
|
|
44
|
-
});
|
|
45
|
-
pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
|
|
46
|
-
return pairs.map(([k, v]) => `${QESC(k)}=${QESC(v)}`).join("&");
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// 全部请求头(小写 key 排序;值 TrimSpace)→ canonical 行集 + SignedHeaders 串。
|
|
50
|
-
export function canonicalHeaders(headers) {
|
|
51
|
-
const canon = {};
|
|
52
|
-
for (const [k, v] of Object.entries(headers || {})) {
|
|
53
|
-
if (v === undefined || v === null) continue;
|
|
54
|
-
canon[k.toLowerCase()] = String(v).trim();
|
|
55
|
-
}
|
|
56
|
-
const keys = Object.keys(canon).sort();
|
|
57
|
-
const lines = keys.map((k) => `${k}:${canon[k]}\n`).join("");
|
|
58
|
-
return { canonical: lines, signed: keys.join(";"), canon };
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* 给请求补签名头:x-sdk-date / x-security-token / x-sdk-content-sha256 / authorization。
|
|
63
|
-
* @param {object} p
|
|
64
|
-
* @param {string} p.method HTTP 方法
|
|
65
|
-
* @param {string} p.url 完整 URL(host 取自这里)
|
|
66
|
-
* @param {object} p.headers 签名前已就位的全部业务头(maas_type 必须已含)
|
|
67
|
-
* @param {string|Buffer} [p.body] 请求体原样字节
|
|
68
|
-
* @param {{accessKeyId, secretAccessKey, securityToken?}} p.cred
|
|
69
|
-
* @returns {{headers: object, stringToSign: string, canonicalRequest: string}} 最终待发送头
|
|
70
|
-
*/
|
|
71
|
-
export function signRequest({ method, url, headers = {}, body = "", cred, now = new Date() }) {
|
|
72
|
-
const u = new URL(url);
|
|
73
|
-
const xDate = now.toISOString().slice(0, 19).replace(/[-:]/g, "") + "Z";
|
|
74
|
-
const payloadHash = sha256Hex(body);
|
|
75
|
-
const h = { ...headers };
|
|
76
|
-
if (cred?.securityToken) h["x-security-token"] = cred.securityToken;
|
|
77
|
-
h["x-sdk-date"] = xDate;
|
|
78
|
-
h["x-sdk-content-sha256"] = payloadHash;
|
|
79
|
-
// host 进签名集(Go 显式 Set("Host"));fetch 会按 URL 自发同值 Host 头,服务端验签一致。
|
|
80
|
-
h["host"] = u.host;
|
|
81
|
-
const { canonical, signed } = canonicalHeaders(h);
|
|
82
|
-
const canonicalRequest = [
|
|
83
|
-
String(method || "GET").toUpperCase(),
|
|
84
|
-
canonicalUriPath(u.pathname),
|
|
85
|
-
canonicalQuery(u.search),
|
|
86
|
-
canonical,
|
|
87
|
-
signed,
|
|
88
|
-
payloadHash,
|
|
89
|
-
].join("\n");
|
|
90
|
-
const stringToSign = [SIGN_ALGORITHM, xDate, sha256Hex(canonicalRequest)].join("\n");
|
|
91
|
-
const signature = hmacHex(cred?.secretAccessKey, stringToSign);
|
|
92
|
-
const finalHeaders = { ...h };
|
|
93
|
-
delete finalHeaders.host; // host 头由 HTTP 客户端自行发出,不在 fetch 头里透传
|
|
94
|
-
finalHeaders.authorization = `${SIGN_ALGORITHM} Access=${cred?.accessKeyId || ""}, SignedHeaders=${signed}, Signature=${signature}`;
|
|
95
|
-
return { headers: finalHeaders, stringToSign, canonicalRequest };
|
|
96
|
-
}
|
|
1
|
+
// 华为云 SDK-HMAC-SHA256 请求签名(AK/SK + 可选 STS security token)。
|
|
2
|
+
// 对齐 @huaweicloud/huaweicloud-sdk-core AKSKSigner(逆向参考:HITZY2002/codearts2api internal/upstream/signer.go):
|
|
3
|
+
// - SignedHeaders = 请求全部头(小写排序,含 host / x-sdk-content-sha256 / maas_type)
|
|
4
|
+
// - CanonicalURI 每段 percent-encode 且末尾补 "/"
|
|
5
|
+
// - payload hash 取 X-Sdk-Content-Sha256(= 请求体原样 sha256 hex)
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
|
|
8
|
+
export const SIGN_ALGORITHM = "SDK-HMAC-SHA256";
|
|
9
|
+
|
|
10
|
+
export function sha256Hex(data) {
|
|
11
|
+
const buf = typeof data === "string" ? Buffer.from(data, "utf8") : (data || Buffer.alloc(0));
|
|
12
|
+
return crypto.createHash("sha256").update(buf).digest("hex");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function hmacHex(key, msg) {
|
|
16
|
+
return crypto.createHmac("sha256", String(key || "")).update(String(msg || ""), "utf8").digest("hex");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Go url.PathEscape(encodePathSegment):仅 / ; , ? 与非 URI 字符转义。
|
|
20
|
+
// 本项目全部端点路径均为纯字母数字(恒等),此处按 RFC3986 pchar 集保守实现。
|
|
21
|
+
const PCHAR = /[^A-Za-z0-9\-._~!$&'()*+,;=:@]/g;
|
|
22
|
+
function escapeSegment(seg) {
|
|
23
|
+
return String(seg || "").replace(PCHAR, (c) => encodeURIComponent(c));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// 末尾强制补 "/"(对齐 JS SDK CanonicalURI;漏掉即签名失败)。
|
|
27
|
+
export function canonicalUriPath(pathname) {
|
|
28
|
+
const out = String(pathname || "/").split("/").map(escapeSegment).join("/");
|
|
29
|
+
return out.endsWith("/") ? out : out + "/";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Go url.QueryEscape:空格 → "+";key/value 各自排序。
|
|
33
|
+
const QESC = (s) => encodeURIComponent(s).replace(/%20/g, "+").replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
|
|
34
|
+
function decodeSafe(s) { try { return decodeURIComponent(s); } catch { return s; } }
|
|
35
|
+
|
|
36
|
+
export function canonicalQuery(rawQuery) {
|
|
37
|
+
const raw = String(rawQuery || "");
|
|
38
|
+
if (!raw) return "";
|
|
39
|
+
const pairs = raw.replace(/^\?/, "").split("&").filter(Boolean).map((p) => {
|
|
40
|
+
const i = p.indexOf("=");
|
|
41
|
+
const k = i < 0 ? p : p.slice(0, i);
|
|
42
|
+
const v = i < 0 ? "" : p.slice(i + 1);
|
|
43
|
+
return [decodeSafe(k), decodeSafe(v)];
|
|
44
|
+
});
|
|
45
|
+
pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
|
|
46
|
+
return pairs.map(([k, v]) => `${QESC(k)}=${QESC(v)}`).join("&");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 全部请求头(小写 key 排序;值 TrimSpace)→ canonical 行集 + SignedHeaders 串。
|
|
50
|
+
export function canonicalHeaders(headers) {
|
|
51
|
+
const canon = {};
|
|
52
|
+
for (const [k, v] of Object.entries(headers || {})) {
|
|
53
|
+
if (v === undefined || v === null) continue;
|
|
54
|
+
canon[k.toLowerCase()] = String(v).trim();
|
|
55
|
+
}
|
|
56
|
+
const keys = Object.keys(canon).sort();
|
|
57
|
+
const lines = keys.map((k) => `${k}:${canon[k]}\n`).join("");
|
|
58
|
+
return { canonical: lines, signed: keys.join(";"), canon };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 给请求补签名头:x-sdk-date / x-security-token / x-sdk-content-sha256 / authorization。
|
|
63
|
+
* @param {object} p
|
|
64
|
+
* @param {string} p.method HTTP 方法
|
|
65
|
+
* @param {string} p.url 完整 URL(host 取自这里)
|
|
66
|
+
* @param {object} p.headers 签名前已就位的全部业务头(maas_type 必须已含)
|
|
67
|
+
* @param {string|Buffer} [p.body] 请求体原样字节
|
|
68
|
+
* @param {{accessKeyId, secretAccessKey, securityToken?}} p.cred
|
|
69
|
+
* @returns {{headers: object, stringToSign: string, canonicalRequest: string}} 最终待发送头
|
|
70
|
+
*/
|
|
71
|
+
export function signRequest({ method, url, headers = {}, body = "", cred, now = new Date() }) {
|
|
72
|
+
const u = new URL(url);
|
|
73
|
+
const xDate = now.toISOString().slice(0, 19).replace(/[-:]/g, "") + "Z";
|
|
74
|
+
const payloadHash = sha256Hex(body);
|
|
75
|
+
const h = { ...headers };
|
|
76
|
+
if (cred?.securityToken) h["x-security-token"] = cred.securityToken;
|
|
77
|
+
h["x-sdk-date"] = xDate;
|
|
78
|
+
h["x-sdk-content-sha256"] = payloadHash;
|
|
79
|
+
// host 进签名集(Go 显式 Set("Host"));fetch 会按 URL 自发同值 Host 头,服务端验签一致。
|
|
80
|
+
h["host"] = u.host;
|
|
81
|
+
const { canonical, signed } = canonicalHeaders(h);
|
|
82
|
+
const canonicalRequest = [
|
|
83
|
+
String(method || "GET").toUpperCase(),
|
|
84
|
+
canonicalUriPath(u.pathname),
|
|
85
|
+
canonicalQuery(u.search),
|
|
86
|
+
canonical,
|
|
87
|
+
signed,
|
|
88
|
+
payloadHash,
|
|
89
|
+
].join("\n");
|
|
90
|
+
const stringToSign = [SIGN_ALGORITHM, xDate, sha256Hex(canonicalRequest)].join("\n");
|
|
91
|
+
const signature = hmacHex(cred?.secretAccessKey, stringToSign);
|
|
92
|
+
const finalHeaders = { ...h };
|
|
93
|
+
delete finalHeaders.host; // host 头由 HTTP 客户端自行发出,不在 fetch 头里透传
|
|
94
|
+
finalHeaders.authorization = `${SIGN_ALGORITHM} Access=${cred?.accessKeyId || ""}, SignedHeaders=${signed}, Signature=${signature}`;
|
|
95
|
+
return { headers: finalHeaders, stringToSign, canonicalRequest };
|
|
96
|
+
}
|