@jixing475/magpie-marvis 0.0.0-stage → 0.3.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.
Files changed (79) hide show
  1. package/AGENTS.md +255 -0
  2. package/CHANGELOG.md +751 -0
  3. package/CHECKLIST.md +161 -0
  4. package/CONTRIBUTING.md +83 -0
  5. package/GUIDE.md +275 -0
  6. package/HOOKS.md +1333 -0
  7. package/LICENSE +21 -0
  8. package/MULTI-PROVIDER.md +414 -0
  9. package/NOTICE.md +46 -0
  10. package/OFFICIAL-SOURCES.md +142 -0
  11. package/README-TEMPLATE.md +271 -0
  12. package/README.md +312 -3
  13. package/SCORING.md +151 -0
  14. package/UPDATING.md +660 -0
  15. package/examples/split/README.md +66 -0
  16. package/examples/split/index.mjs +75 -0
  17. package/examples/split/src/hooks/config.mjs +18 -0
  18. package/examples/split/src/hooks/models.mjs +49 -0
  19. package/examples/split/src/hooks/usage.mjs +55 -0
  20. package/extract-contract.py +56 -0
  21. package/index.mjs +48 -0
  22. package/package.json +95 -4
  23. package/panel/first-line.css +112 -0
  24. package/panel/first-line.html +37 -0
  25. package/panel/first-line.js +137 -0
  26. package/registry-entry.json +11 -0
  27. package/scripts/check-magpie-stable.mjs +109 -0
  28. package/scripts/check-maintenance.mjs +146 -0
  29. package/scripts/check.mjs +521 -0
  30. package/scripts/cli.mjs +54 -0
  31. package/scripts/contract-diff.mjs +112 -0
  32. package/scripts/create.mjs +270 -0
  33. package/scripts/npm-name.mjs +19 -0
  34. package/scripts/probe-served-model.mjs +172 -0
  35. package/scripts/probe-vision.mjs +173 -0
  36. package/scripts/publish-npm.mjs +44 -0
  37. package/scripts/release.mjs +442 -0
  38. package/scripts/score.mjs +280 -0
  39. package/src/account-name.mjs +145 -0
  40. package/src/auth.mjs +27 -0
  41. package/src/context.mjs +369 -0
  42. package/src/hooks/config.mjs +236 -0
  43. package/src/hooks/loader.mjs +593 -0
  44. package/src/hooks/methods.mjs +398 -0
  45. package/src/hooks/models.mjs +25 -0
  46. package/src/hooks/refresh.mjs +149 -0
  47. package/src/hooks/usage.mjs +117 -0
  48. package/src/marvis/beacon-mac.mjs +213 -0
  49. package/src/marvis/beacon-shim.mjs +143 -0
  50. package/src/marvis/browser.mjs +598 -0
  51. package/src/marvis/desktop-mac.mjs +232 -0
  52. package/src/marvis/desktop.mjs +273 -0
  53. package/src/marvis/device.mjs +85 -0
  54. package/src/marvis/expiry.mjs +60 -0
  55. package/src/marvis/fingerprint.mjs +168 -0
  56. package/src/marvis/images.mjs +230 -0
  57. package/src/marvis/login.mjs +512 -0
  58. package/src/marvis/profile.mjs +113 -0
  59. package/src/marvis/protocol.mjs +160 -0
  60. package/src/marvis/tool-schema.mjs +97 -0
  61. package/src/quota.mjs +212 -0
  62. package/src/refresh-lock.mjs +115 -0
  63. package/tests/device-registry.test.mjs +48 -0
  64. package/tests/e2e-live.test.mjs +120 -0
  65. package/tests/image-input.test.mjs +314 -0
  66. package/tests/legacy-model-config.test.mjs +349 -0
  67. package/tests/legacy-model-loader.test.mjs +306 -0
  68. package/tests/loader-model-support.test.mjs +823 -0
  69. package/tests/manual-paste-login.test.mjs +228 -0
  70. package/tests/model-alias.test.mjs +59 -0
  71. package/tests/model-catalog-support.test.mjs +241 -0
  72. package/tests/mount.test.mjs +259 -0
  73. package/tests/oauth-exchange.test.mjs +362 -0
  74. package/tests/panel-manifest.test.mjs +73 -0
  75. package/tests/plugin-options.test.mjs +100 -0
  76. package/tests/profile.test.mjs +96 -0
  77. package/tests/refresh-contract.test.mjs +318 -0
  78. package/tests/request-identity.test.mjs +18 -0
  79. package/tests/tool-schema.test.mjs +66 -0
@@ -0,0 +1,259 @@
1
+ // tests/mount.test.mjs —— 入口 / 钩子挂载契约
2
+ //
3
+ // ① 入口只导出一个函数(magpie 会把每个函数导出都当插件工厂调用)
4
+ // ② _internal 是对象(helper 不暴露成插件)
5
+ // ③ 钩子齐全,形状对
6
+ // ④ config() 未登录也有模型(否则卡片显示 "0 models")
7
+ // ⑤ authorize() 立刻返回 Promise(真正的登录在 callback 里)
8
+ // ⑥ loader() 给 baseURL / apiKey / fetch
9
+ // ⑦ 两种模型形状**不能混**:config 用 modalities 数组 + tool_call;
10
+ // provider.models 用 capabilities 对象 + toolcall
11
+ //
12
+ // 全部离线;不需要 magpie 进程、不需要凭据、不联网。
13
+ // 跑法:node --test tests/mount.test.mjs
14
+
15
+ import test from "node:test"
16
+ import assert from "node:assert/strict"
17
+ import { readFileSync, existsSync } from "node:fs"
18
+ import { join } from "node:path"
19
+ import { fileURLToPath } from "node:url"
20
+
21
+ import * as entry from "../index.mjs"
22
+ import { _internal } from "../index.mjs"
23
+ import { usage, usageWindow } from "../src/quota.mjs"
24
+ import { nextResetAt } from "../src/hooks/usage.mjs"
25
+
26
+ const { MarvisAuthPlugin } = entry
27
+
28
+ test("入口只导出一个函数(插件工厂)", () => {
29
+ const functions = Object.entries(entry)
30
+ .filter(([, value]) => typeof value === "function")
31
+ .map(([key]) => key)
32
+ assert.deepEqual(functions, ["MarvisAuthPlugin"])
33
+ })
34
+
35
+ test("_internal 是对象,helper 不暴露成顶层函数导出", () => {
36
+ assert.equal(typeof _internal, "object")
37
+ assert.equal(_internal.PROVIDER, "marvis")
38
+ assert.equal(_internal.PROVIDER_NAME, "腾讯 Marvis TENCENT")
39
+ assert.equal(typeof _internal.staticModels, "function")
40
+ assert.equal(typeof _internal.providerModels, "function")
41
+ assert.equal(_internal.BASE_V1, "https://yybadaccess.3g.qq.com/v1")
42
+ })
43
+
44
+ test("六个钩子齐全", async () => {
45
+ const plugin = await MarvisAuthPlugin({})
46
+ assert.equal(typeof plugin.config, "function")
47
+ assert.ok(plugin.auth && typeof plugin.auth === "object")
48
+ assert.equal(plugin.auth.provider, _internal.PROVIDER)
49
+ assert.equal(typeof plugin.auth.refresh, "function")
50
+ assert.equal(typeof plugin.auth.loader, "function")
51
+ assert.equal(typeof plugin.auth.usage, "function")
52
+ assert.ok(Array.isArray(plugin.auth.methods) && plugin.auth.methods.length >= 2)
53
+ for (const m of plugin.auth.methods) assert.equal(typeof m.authorize, "function")
54
+ assert.equal(typeof plugin.provider.models, "function")
55
+ assert.equal(plugin.provider.id, _internal.PROVIDER)
56
+ assert.ok(plugin.auth.icon?.startsWith("data:image/"), "图标必须内嵌(外部 URL 在 git 源下不渲染)")
57
+ assert.ok(Number.isInteger(plugin.auth.maxConcurrency) && plugin.auth.maxConcurrency >= 1)
58
+ })
59
+
60
+ test("config() 未登录也声明了模型,且 modalities 是数组、tool_call 有下划线", async () => {
61
+ const plugin = await MarvisAuthPlugin({})
62
+ const cfg = {}
63
+ await plugin.config(cfg)
64
+ const models = cfg.provider?.[_internal.PROVIDER]?.models
65
+ assert.ok(models && Object.keys(models).length > 0, "config.models 不能为空(铁律 1)")
66
+ assert.equal(models["deepseek-v4-1-flash-261017"]?.id, "deepseek-v4-1-flash-261017", "config.models 必须以真实模型名为键")
67
+
68
+ for (const m of Object.values(models)) {
69
+ assert.equal(typeof m.id, "string")
70
+ // config 形状:modalities.input / output 是**数组**
71
+ assert.ok(Array.isArray(m.modalities.input), `${m.id}.modalities.input 必须是数组`)
72
+ assert.ok(m.modalities.input.includes("text"), `${m.id}.modalities.input 必须含 text`)
73
+ assert.ok(Array.isArray(m.modalities.output), `${m.id}.modalities.output 必须是数组`)
74
+ // config 形状:tool_call 带下划线
75
+ assert.equal(typeof m.tool_call, "boolean", `${m.id}.tool_call 必须是布尔(config 形状)`)
76
+ assert.equal(m.toolcall, undefined, `${m.id} 不该有 toolcall(那是 provider.models 的形状)`)
77
+ assert.equal(typeof m.attachment, "boolean", `${m.id}.attachment 必须是布尔`)
78
+ assert.equal(typeof m.reasoning, "boolean", `${m.id}.reasoning 必须是布尔`)
79
+ assert.equal(typeof m.limit.context, "number")
80
+ assert.equal(typeof m.limit.output, "number")
81
+ }
82
+ })
83
+
84
+ test("provider.models:capabilities.input 五个模态键必须全是布尔", async () => {
85
+ const plugin = await MarvisAuthPlugin({})
86
+ const models = await plugin.provider.models(async () => null)
87
+ assert.ok(models && typeof models === "object" && Object.keys(models).length > 0)
88
+
89
+ for (const m of Object.values(models)) {
90
+ // provider.models 形状:capabilities.input 是**对象**,五个键都得写
91
+ for (const key of ["text", "image", "audio", "video", "pdf"]) {
92
+ assert.equal(
93
+ typeof m.capabilities.input[key],
94
+ "boolean",
95
+ `${m.id}.capabilities.input.${key} 必须是布尔(漏了等于厂商未表态,会被 models.dev 投票带偏)`,
96
+ )
97
+ }
98
+ assert.equal(m.capabilities.input.text, true, `${m.id} 必须能收文字`)
99
+ // provider.models 形状:toolcall 无下划线
100
+ assert.equal(typeof m.capabilities.toolcall, "boolean")
101
+ assert.equal(m.tool_call, undefined, `${m.id} 不该有 tool_call(那是 config 形状)`)
102
+ assert.equal(typeof m.api.id, "string", "api.id 必须是上游槽位名")
103
+ assert.ok(m.api.id, "api.id 不能为空,漏了会退化成数组下标 0")
104
+ assert.equal(m.api.url, _internal.BASE_V1)
105
+ assert.equal(m.api.npm, "@ai-sdk/openai-compatible")
106
+ assert.equal(typeof m.id, "string")
107
+ assert.equal(typeof m.name, "string")
108
+ assert.equal(m.id, m.name, "id 用真实模型名,路由才显示名字")
109
+ }
110
+ })
111
+
112
+ test("authorize 是 async 函数,且立刻返回(不 await 登录)", async () => {
113
+ const plugin = await MarvisAuthPlugin({})
114
+ for (const method of plugin.auth.methods) {
115
+ assert.equal(typeof method.authorize, "function")
116
+ assert.equal(method.authorize.constructor.name, "AsyncFunction")
117
+ }
118
+ // 铁律 2:authorize 必须立刻返回一个带 callback 的 flow(不碰网络)
119
+ const started = Date.now()
120
+ const flow = await plugin.auth.methods[0].authorize(undefined)
121
+ assert.ok(Date.now() - started < 1_000, "authorize 不能阻塞")
122
+ assert.equal(typeof flow.callback, "function")
123
+ assert.equal(typeof flow.url, "string")
124
+ assert.match(flow.url, /^https:\/\/(graph\.qq\.com|open\.weixin\.qq\.com)\//)
125
+ })
126
+
127
+ test("授权 URL 带对的 appid 与 redirect_uri", async () => {
128
+ const prev = process.env.MARVIS_WX_APP_ID
129
+ process.env.MARVIS_WX_APP_ID = "wx-test-app"
130
+ try {
131
+ const plugin = await MarvisAuthPlugin({})
132
+ const qq = await plugin.auth.methods[0].authorize(undefined)
133
+ assert.match(qq.url, /client_id=1903794758/)
134
+ assert.match(qq.url, /redirect_uri=https%3A%2F%2Fyybadaccess\.3g\.qq\.com%2Fmarvis_client_login%2Fmarvis_oauth/)
135
+
136
+ const wx = await plugin.auth.methods[1].authorize(undefined)
137
+ assert.match(wx.url, /appid=wx-test-app/)
138
+ } finally {
139
+ if (prev === undefined) delete process.env.MARVIS_WX_APP_ID
140
+ else process.env.MARVIS_WX_APP_ID = prev
141
+ }
142
+ })
143
+
144
+ test("loader() 给 baseURL / apiKey / fetch;未登录返回空对象", async () => {
145
+ const plugin = await MarvisAuthPlugin({})
146
+ const out = await plugin.auth.loader(async () => ({
147
+ type: "oauth",
148
+ access: "token",
149
+ metadata: { openid: "OPENID", guid: "GUID", loginType: "6" },
150
+ }))
151
+ assert.equal(typeof out.fetch, "function")
152
+ assert.equal(out.baseURL, _internal.BASE_V1)
153
+ assert.equal(out.apiKey, "placeholder")
154
+
155
+ const empty = await plugin.auth.loader(async () => null)
156
+ assert.deepEqual(empty, {})
157
+ })
158
+
159
+ test("usage() 未登录时给出 error 而不是伪造 0", async () => {
160
+ const plugin = await MarvisAuthPlugin({})
161
+ const anonymous = await plugin.auth.usage(async () => null)
162
+ assert.match(String(anonymous.error), /未登录/)
163
+ assert.deepEqual(anonymous.windows, [])
164
+ })
165
+
166
+ test("usage 构造器可用:至少造一条参与路由的窗口", () => {
167
+ const value = usage({
168
+ plan: "Test",
169
+ windows: [usageWindow({ name: "令牌", amount: 37, limit: 1_000_000, unit: "tokens" })],
170
+ })
171
+ assert.equal(typeof value.plan, "string")
172
+ assert.equal(value.windows.length, 1)
173
+ assert.equal(Number.isFinite(value.windows[0].used), true)
174
+ })
175
+
176
+ test("下一个重置时间是北京时间 0 点(上游不返回,按固定规则推算)", () => {
177
+ // 北京 19:02(UTC 11:02)→ 次日 0 点 = 当天 16:00Z
178
+ assert.equal(nextResetAt(new Date("2026-11-15T11:02:00Z")), "2026-11-15T16:00:00.000Z")
179
+ // 北京 23:59(UTC 15:59)→ 再过一分钟就是 0 点
180
+ assert.equal(nextResetAt(new Date("2026-11-15T15:59:00Z")), "2026-11-15T16:00:00.000Z")
181
+ // 北京次日 00:30(UTC 前一日 16:30)→ 应当给再下一个 0 点
182
+ assert.equal(nextResetAt(new Date("2026-11-15T16:30:00Z")), "2026-11-16T16:00:00.000Z")
183
+ })
184
+
185
+ test("refresh 走串行锁(成对轮换的 token 不能被并发打掉)", () => {
186
+ const source = readFileSync(new URL("../src/hooks/refresh.mjs", import.meta.url), "utf8")
187
+ assert.match(source, /createRefreshLock/)
188
+ assert.match(source, /lock\.run\(/)
189
+ // 合并语义:不能只返回新字段
190
+ assert.match(source, /metadata: \{ \.\.\.meta/)
191
+ })
192
+
193
+ test("native 目录若放了 DLL,出票入口必须齐全", () => {
194
+ // 二进制不随仓库分发。目录里只有桥源码时跳过;放了 DLL 就必须有桥或 napi。
195
+ const dir = fileURLToPath(new URL("../native", import.meta.url))
196
+ if (!existsSync(dir)) return
197
+ const hasDll = ["qimei.dll", "beacon_sdk.dll", "beacon_wrapper.dll"].some((f) => existsSync(join(dir, f)))
198
+ if (!hasDll) return
199
+ for (const f of ["qimei.dll", "beacon_sdk.dll", "beacon_wrapper.dll"]) {
200
+ assert.ok(existsSync(join(dir, f)), `native/${f} 必须齐全`)
201
+ }
202
+ assert.ok(
203
+ existsSync(join(dir, "beacon_napi.node")) || existsSync(join(dir, "beacon_shim.dll")),
204
+ "native/ 至少要有 beacon_napi.node 或 beacon_shim.dll",
205
+ )
206
+ })
207
+
208
+ test("config() 合并:用户改过的值优先,插件只补缺", async () => {
209
+ const { mergeModels } = await import("../src/hooks/config.mjs")
210
+ const { staticModels } = await import("../src/context.mjs")
211
+ const defaults = staticModels()
212
+
213
+ // 用户把 main-auto 的上下文改成 2M,并删掉了 hunyuan-turbos-vision
214
+ const user = Object.fromEntries(
215
+ Object.entries(defaults)
216
+ .filter(([id]) => id !== "HY-Vision-2.0-instruct")
217
+ .map(([id, m]) => [id, id === "deepseek-v4-1-flash-261017" ? { ...m, limit: { ...m.limit, context: 2_000_000 } } : m]),
218
+ )
219
+
220
+ const merged = mergeModels(defaults, user)
221
+ const main = merged["deepseek-v4-1-flash-261017"]
222
+
223
+ assert.equal(main.limit.context, 2_000_000, "用户设的 2M 必须保留")
224
+ assert.equal(typeof main.limit.output, "number", "用户没改的 output 不能被吃掉")
225
+ assert.ok(merged["HY-Vision-2.0-instruct"], "默认表里有、用户没有的模型要追加回来")
226
+ })
227
+
228
+ test("config() 已有 provider 时不重置用户配置", async () => {
229
+ const { MarvisAuthPlugin } = await import("../index.mjs")
230
+ const plugin = await MarvisAuthPlugin({})
231
+ const cfg = {
232
+ provider: {
233
+ marvis: {
234
+ name: "我改的名字",
235
+ npm: "@ai-sdk/openai-compatible",
236
+ api: "https://custom.example.com/v1",
237
+ models: [
238
+ {
239
+ id: "main-auto",
240
+ name: "我的 V4.1 Flash",
241
+ limit: { context: 2_000_000, output: 64_000 },
242
+ modalities: { input: ["text"], output: ["text"] },
243
+ tool_call: true,
244
+ attachment: false,
245
+ reasoning: true,
246
+ },
247
+ ],
248
+ },
249
+ },
250
+ }
251
+ await plugin.config(cfg)
252
+ const p = cfg.provider.marvis
253
+ assert.equal(p.name, "我改的名字", "provider 名不能被我覆盖")
254
+ assert.equal(p.api, "https://custom.example.com/v1", "api 不能被我覆盖")
255
+ assert.equal(p.models["deepseek-v4-1-flash-261017"].limit.context, 2_000_000, "上下文不能被我覆盖")
256
+ assert.equal(p.models["deepseek-v4-1-flash-261017"].name, "我的 V4.1 Flash")
257
+ assert.equal(p.models["deepseek-v4-1-flash-261017"].id, "deepseek-v4-1-flash-261017")
258
+ assert.equal(p.models["deepseek-v4-1-flash-261017"].apiId, "main-auto", "apiId 保留上游槽位名")
259
+ })
@@ -0,0 +1,362 @@
1
+ // tests/oauth-exchange.test.mjs —— OAuth code 换取的形状锁
2
+ //
3
+ // 把已实测的事实写死成测试,改代码时会被拦住:
4
+ // ① 换取成功 = **302 + Set-Cookie**(openid/accesstoken/refreshtoken/logintype/
5
+ // nickname/head_img_url/access_token_expire_time/appid/scope/is_locked),不是 JSON
6
+ // ② 必须带 `Ual-Access-Guid`,且必须 `redirect: "manual"`(跟随重定向会丢登录态)
7
+ // ③ 回调的 `state` 必须原样回传;guid 不能是 undefined
8
+ // ④ -109 = 参数检查未通过(最常见是缺 guid);-107 = 参数已过但 code/会话校验失败
9
+ // —— 都不是「账号或密码错」
10
+ //
11
+ // 全部离线:fetch 换成假实现,不联网、不需要 magpie 进程、不需要任何凭据。
12
+ // 跑法:node --test tests/oauth-exchange.test.mjs
13
+
14
+ import test from "node:test"
15
+ import assert from "node:assert/strict"
16
+
17
+ import {
18
+ exchangeCode,
19
+ parseCallback,
20
+ parseSetCookies,
21
+ accountFromCookies,
22
+ stateOf,
23
+ } from "../src/marvis/login.mjs"
24
+
25
+ /** 32 位小写 hex,形状与 deviceGuid() 一致 */
26
+ const GUID = "0123456789abcdef0123456789abcdef"
27
+ const CODE = "A1B2C3D4E5F6A1B2C3D4E5F6A1B2C3D4"
28
+ const OAUTH_PATH = "/marvis_client_login/marvis_oauth"
29
+
30
+ /**
31
+ * 替身 fetch:记下每次 url / init,回固定响应。
32
+ * @param {(url: string, init: any) => Response | Promise<Response>} makeResponse
33
+ */
34
+ function stubFetch(makeResponse) {
35
+ const calls = []
36
+ const real = globalThis.fetch
37
+ globalThis.fetch = async (url, init) => {
38
+ calls.push({ url: String(url), init: init ?? {} })
39
+ return makeResponse(String(url), init ?? {})
40
+ }
41
+ return {
42
+ calls,
43
+ restore() {
44
+ globalThis.fetch = real
45
+ },
46
+ }
47
+ }
48
+
49
+ /** 官方 302 成功响应:10 个 Set-Cookie,无 body */
50
+ function ok302() {
51
+ const setCookies = [
52
+ "openid=0A1B2C3D4E5F60718293A4B5C6D7E8F9; Path=/; Domain=.qq.com; HttpOnly",
53
+ "accesstoken=TOKEN_abc123; Path=/; Domain=.qq.com; HttpOnly",
54
+ "refreshtoken=REFRESH_def456; Path=/; Domain=.qq.com; HttpOnly",
55
+ "logintype=QC; Path=/; Domain=.qq.com",
56
+ `nickname=${encodeURIComponent("阿明")}; Path=/; Domain=.qq.com`,
57
+ "head_img_url=https%3A%2F%2Fthirdqq.qlogo.cn%2Fabc%2F100; Path=/; Domain=.qq.com",
58
+ "access_token_expire_time=1793000000; Path=/; Domain=.qq.com",
59
+ "appid=1903794758; Path=/; Domain=.qq.com",
60
+ "scope=all; Path=/; Domain=.qq.com",
61
+ "is_locked=0; Path=/; Domain=.qq.com",
62
+ ]
63
+ const headers = new Headers()
64
+ for (const c of setCookies) headers.append("set-cookie", c)
65
+ headers.set("location", "https://yybadaccess.3g.qq.com/marvis_client_login/oauth_done")
66
+ return new Response(null, { status: 302, headers })
67
+ }
68
+
69
+ /** 上游 JSON 失败响应 */
70
+ function jsonError(code, msg) {
71
+ return new Response(JSON.stringify({ code, msg }), {
72
+ status: 200,
73
+ headers: { "content-type": "application/json" },
74
+ })
75
+ }
76
+
77
+ test("302 + Set-Cookie:解析成账号(官方成功形态)", async () => {
78
+ const s = stubFetch(() => ok302())
79
+ try {
80
+ const acct = await exchangeCode(CODE, "QC", GUID, "31.1177412")
81
+ assert.equal(s.calls.length, 1)
82
+
83
+ assert.equal(acct.openid, "0A1B2C3D4E5F60718293A4B5C6D7E8F9")
84
+ assert.equal(acct.accessToken, "TOKEN_abc123")
85
+ assert.equal(acct.refreshToken, "REFRESH_def456")
86
+ assert.equal(acct.nickname, "阿明", "nickname 要百分号解码")
87
+ assert.equal(acct.avatar, "https://thirdqq.qlogo.cn/abc/100", "head_img_url → avatar,且要解码")
88
+ assert.equal(acct.loginType, "1", "logintype=QC → Ual-Access-Login-Type 1")
89
+ assert.equal(acct.expiresAt, 1793000000 * 1000, "10 位秒级时间戳要 ×1000")
90
+ assert.equal(acct.appid, "1903794758")
91
+ assert.equal(acct.scope, "all")
92
+ assert.equal(acct.guid, GUID, "换取用的 guid 要跟着账号一起回去落盘")
93
+ assert.equal(acct.isLocked, undefined, "is_locked=0 不是锁定")
94
+ } finally {
95
+ s.restore()
96
+ }
97
+ })
98
+
99
+ test("换取请求:带 Ual-Access-Guid、redirect=manual、只带 login_type/code/state", async () => {
100
+ const s = stubFetch(() => ok302())
101
+ try {
102
+ await exchangeCode(CODE, "QC", GUID, "31.1177412")
103
+ const { url, init } = s.calls[0]
104
+ const u = new URL(url)
105
+
106
+ assert.equal(`${u.origin}${u.pathname}`, `https://yybadaccess.3g.qq.com${OAUTH_PATH}`)
107
+ assert.equal(u.searchParams.get("login_type"), "QC")
108
+ assert.equal(u.searchParams.get("code"), CODE)
109
+ assert.equal(u.searchParams.get("state"), "31.1177412", "state 必须原样回传")
110
+ assert.deepEqual(
111
+ [...u.searchParams.keys()].sort(),
112
+ ["code", "login_type", "state"],
113
+ "多带一个参数服务端就 -109",
114
+ )
115
+
116
+ assert.equal(init.method, "GET")
117
+ assert.equal(init.redirect, "manual", "必须 manual:跟随 302 就是把 Set-Cookie 丢掉")
118
+ const h = new Headers(init.headers)
119
+ assert.equal(h.get("ual-access-guid"), GUID, "不带它服务端一律 -109")
120
+ assert.ok(!h.get("ual-access-signature"), "签名头会让 WAF 直接 400")
121
+ assert.match(h.get("user-agent"), /Marvis\//, "UA 必须是客户端自己的 Electron UA")
122
+ } finally {
123
+ s.restore()
124
+ }
125
+ })
126
+
127
+ test("兼容 200 + JSON user_info(旧形态仍然认)", async () => {
128
+ const payload = {
129
+ code: 0,
130
+ user_info: {
131
+ openid: "FEDCBA9876543210FEDCBA9876543210",
132
+ access_token: "JSON_TOKEN",
133
+ refresh_token: "JSON_REFRESH",
134
+ nick_name: "小明",
135
+ head_img_url: "https://thirdqq.qlogo.cn/json/100",
136
+ access_token_expire_time: 1793000000,
137
+ login_type: "WX",
138
+ },
139
+ }
140
+ const s = stubFetch(
141
+ () =>
142
+ new Response(JSON.stringify(payload), {
143
+ status: 200,
144
+ headers: { "content-type": "application/json" },
145
+ }),
146
+ )
147
+ try {
148
+ const acct = await exchangeCode(CODE, "WX", GUID)
149
+ assert.equal(acct.openid, "FEDCBA9876543210FEDCBA9876543210")
150
+ assert.equal(acct.accessToken, "JSON_TOKEN")
151
+ assert.equal(acct.refreshToken, "JSON_REFRESH")
152
+ assert.equal(acct.nickname, "小明")
153
+ assert.equal(acct.loginType, "2", "login_type=WX → Ual-Access-Login-Type 2")
154
+ assert.equal(acct.expiresAt, 1793000000 * 1000)
155
+ assert.equal(acct.guid, GUID)
156
+ } finally {
157
+ s.restore()
158
+ }
159
+ })
160
+
161
+ test("兼容 200 + 扁平 JSON(没有 user_info 包一层)", async () => {
162
+ const s = stubFetch(
163
+ () =>
164
+ new Response(JSON.stringify({ openid: "AAAABBBBCCCCDDDD", access_token: "FLAT_TOKEN" }), {
165
+ status: 200,
166
+ headers: { "content-type": "application/json" },
167
+ }),
168
+ )
169
+ try {
170
+ const acct = await exchangeCode(CODE, "QC", GUID)
171
+ assert.equal(acct.openid, "AAAABBBBCCCCDDDD")
172
+ assert.equal(acct.accessToken, "FLAT_TOKEN")
173
+ assert.equal(acct.loginType, "1")
174
+ } finally {
175
+ s.restore()
176
+ }
177
+ })
178
+
179
+ test("-109:含义是「参数检查未通过」,不是「授权码过期 / 账号错」", async () => {
180
+ const s = stubFetch(() => jsonError(-109, "params invalid"))
181
+ try {
182
+ await assert.rejects(
183
+ () => exchangeCode(CODE, "QC", GUID),
184
+ (err) => {
185
+ assert.match(err.message, /code=-109/)
186
+ assert.match(err.message, /RC_PARAMS_INVALID/, "要带上游的符号名")
187
+ assert.match(err.message, /参数检查未通过/)
188
+ assert.match(err.message, /Ual-Access-Guid/, "要指出最常见的缺项")
189
+ assert.doesNotMatch(err.message, /授权码无效|密码|账号错/)
190
+ return true
191
+ },
192
+ )
193
+ } finally {
194
+ s.restore()
195
+ }
196
+ })
197
+
198
+ test("-107:含义是「参数已过、code/会话校验失败」,且不与 -109 混说", async () => {
199
+ const s = stubFetch(() => jsonError(-107, "auth failed"))
200
+ try {
201
+ await assert.rejects(
202
+ () => exchangeCode(CODE, "QC", GUID),
203
+ (err) => {
204
+ assert.match(err.message, /code=-107/)
205
+ assert.match(err.message, /参数已通过/)
206
+ assert.match(err.message, /code 无效|已过期|已被消费/)
207
+ assert.doesNotMatch(err.message, /RC_PARAMS_INVALID/, "-107 不是参数无效")
208
+ assert.doesNotMatch(err.message, /密码错误|账号错/)
209
+ return true
210
+ },
211
+ )
212
+ } finally {
213
+ s.restore()
214
+ }
215
+ })
216
+
217
+ test("302 却没下发登录 Cookie:报清楚,不假装成功", async () => {
218
+ const headers = new Headers()
219
+ headers.append("set-cookie", "waf_check=1; Path=/")
220
+ headers.set("location", "https://yybadaccess.3g.qq.com/risk")
221
+ const s = stubFetch(() => new Response(null, { status: 302, headers }))
222
+ try {
223
+ await assert.rejects(
224
+ () => exchangeCode(CODE, "QC", GUID),
225
+ (err) => {
226
+ assert.match(err.message, /302/)
227
+ assert.match(err.message, /没有下发登录 Cookie/)
228
+ assert.match(err.message, /\/risk/, "要把 Location 带出来,方便定位")
229
+ return true
230
+ },
231
+ )
232
+ } finally {
233
+ s.restore()
234
+ }
235
+ })
236
+
237
+ test("缺 guid:本地就报错,不发那趟注定 -109 的请求", async () => {
238
+ const s = stubFetch(() => ok302())
239
+ try {
240
+ await assert.rejects(
241
+ () => exchangeCode(CODE, "QC", undefined),
242
+ (err) => {
243
+ assert.match(err.message, /Ual-Access-Guid/)
244
+ assert.match(err.message, /-109/)
245
+ return true
246
+ },
247
+ )
248
+ assert.equal(s.calls.length, 0)
249
+ } finally {
250
+ s.restore()
251
+ }
252
+ })
253
+
254
+ test("parseCallback:从回调 URL 保留 state,并把 guid 带进 Ual-Access-Guid", async () => {
255
+ const s = stubFetch(() => ok302())
256
+ try {
257
+ const cb = `https://yybadaccess.3g.qq.com${OAUTH_PATH}?code=${CODE}&state=31.1177412`
258
+ const acct = await parseCallback(cb, "", { loginType: "QC", guid: GUID })
259
+
260
+ assert.equal(s.calls.length, 1)
261
+ const { url, init } = s.calls[0]
262
+ const u = new URL(url)
263
+ assert.equal(u.searchParams.get("state"), "31.1177412", "state 必须是回调里那一个")
264
+ assert.equal(u.searchParams.get("code"), CODE)
265
+ assert.equal(u.searchParams.get("login_type"), "QC")
266
+ assert.equal(new Headers(init.headers).get("ual-access-guid"), GUID, "不能再传 undefined")
267
+ assert.equal(init.redirect, "manual")
268
+
269
+ assert.equal(acct.openid, "0A1B2C3D4E5F60718293A4B5C6D7E8F9")
270
+ assert.equal(acct.guid, GUID)
271
+ } finally {
272
+ s.restore()
273
+ }
274
+ })
275
+
276
+ test("parseCallback:微信的 state 就是 guid,没传 opts.guid 也能对上", async () => {
277
+ const s = stubFetch(() => ok302())
278
+ try {
279
+ const cb = `https://yybadaccess.3g.qq.com${OAUTH_PATH}?code=${CODE}&state=${GUID}`
280
+ await parseCallback(cb, "", { loginType: "WX" })
281
+ assert.equal(new Headers(s.calls[0].init.headers).get("ual-access-guid"), GUID)
282
+ } finally {
283
+ s.restore()
284
+ }
285
+ })
286
+
287
+ test("parseCallback:QQ 回调没带 state 时才退回 opts.state;guid 缺省时取设备 guid(不是 undefined)", async () => {
288
+ const s = stubFetch(() => ok302())
289
+ try {
290
+ const cb = `https://yybadaccess.3g.qq.com${OAUTH_PATH}?code=${CODE}`
291
+ await parseCallback(cb, "", { loginType: "QC", state: "7.5" })
292
+ const u = new URL(s.calls[0].url)
293
+ assert.equal(u.searchParams.get("state"), "7.5")
294
+
295
+ const guid = new Headers(s.calls[0].init.headers).get("ual-access-guid")
296
+ assert.match(guid, /^[0-9a-f]{32}$/, "缺省要取设备 guid(32 位小写 hex),不能是 undefined")
297
+ } finally {
298
+ s.restore()
299
+ }
300
+ })
301
+
302
+ test("parseCallback:正文是 JSON 时直接认,并把 guid 一起带回去", async () => {
303
+ const s = stubFetch(() => {
304
+ throw new Error("不该发请求")
305
+ })
306
+ try {
307
+ const body = ` {\n "code": 0,\n "user_info": { "openid": "0123456789ABCDEF", "access_token": "BODY_TOKEN" }\n}\n`
308
+ const acct = await parseCallback(
309
+ `https://yybadaccess.3g.qq.com${OAUTH_PATH}?code=${CODE}&state=3.5`,
310
+ body,
311
+ { loginType: "QC", guid: GUID },
312
+ )
313
+ assert.equal(s.calls.length, 0, "正文已经是登录态了,不该再换一次")
314
+ assert.equal(acct.accessToken, "BODY_TOKEN")
315
+ assert.equal(acct.guid, GUID)
316
+ } finally {
317
+ s.restore()
318
+ }
319
+ })
320
+
321
+ test("parseSetCookies:Expires 里的逗号劈不开,同名 cookie 取第一个", () => {
322
+ const headers = new Headers()
323
+ headers.append("set-cookie", "openid=ABC; Expires=Wed, 01 Jan 2031 00:00:00 GMT; Path=/")
324
+ headers.append("set-cookie", "accesstoken=T1; Path=/; Domain=.qq.com")
325
+ headers.append("set-cookie", "openid=SECOND; Path=/")
326
+
327
+ const jar = parseSetCookies(headers)
328
+ assert.equal(jar.get("openid"), "ABC")
329
+ assert.equal(jar.get("accesstoken"), "T1")
330
+
331
+ // 没有 openid / accesstoken 的 cookie 集合不算登录成功
332
+ assert.equal(accountFromCookies(jar, { loginType: "QC" }).openid, "ABC")
333
+ assert.equal(accountFromCookies(new Map([["waf_check", "1"]]), {}), null)
334
+ })
335
+
336
+ test("parseSetCookies:没有 getSetCookie 时也能切(老运行时 / 假 headers)", () => {
337
+ const fake = {
338
+ get: (name) =>
339
+ name.toLowerCase() === "set-cookie"
340
+ ? "openid=X1; Expires=Wed, 01 Jan 2031 00:00:00 GMT, accesstoken=Y1; Path=/"
341
+ : null,
342
+ }
343
+ const jar = parseSetCookies(fake)
344
+ assert.equal(jar.get("openid"), "X1")
345
+ assert.equal(jar.get("accesstoken"), "Y1")
346
+ })
347
+
348
+ test("accountFromCookies:logintype 缺失时退回调用方声明的 loginType", () => {
349
+ const jar = new Map([
350
+ ["openid", "OID"],
351
+ ["accesstoken", "AT"],
352
+ ])
353
+ assert.equal(accountFromCookies(jar, { loginType: "WX" }).loginType, "2")
354
+ assert.equal(accountFromCookies(jar, { loginType: "QC" }).loginType, "1")
355
+ })
356
+
357
+ test("stateOf:取不到 state 时返回空串(不是 null / 'null')", () => {
358
+ assert.equal(stateOf(`https://x.y${OAUTH_PATH}?code=C&state=31.1177412`), "31.1177412")
359
+ assert.equal(stateOf(`https://x.y${OAUTH_PATH}?code=C`), "")
360
+ assert.equal(stateOf(""), "")
361
+ assert.equal(stateOf(undefined), "")
362
+ })