officialMcpCredentials.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /* OMCP-005/006/009/021/023/024/026/027 —— 官方 MCP 凭证解析与身份头构造(spec §6.1 / §6.2.1 / §6.3.3)。
  2. *
  3. * OMCP-025(Off-Peak 零回归,验证 §6.1.1 的隔离)不是本文件的用例,而是一条回归动作:
  4. * npx vitest run packages/services/test/offPeakRuntimeModel.test.ts \
  5. * packages/services/test/offPeakServerClient.test.ts \
  6. * packages/services/test/offPeakTaskService.test.ts \
  7. * packages/services/test/offPeakE2eIntegration.test.ts \
  8. * packages/services/test/offPeakClientConfig.test.ts \
  9. * packages/services/test/offPeakTaskRepo.test.ts
  10. * 本次实现后为 6 files / 77 tests 全绿,且未修改 offPeakRuntimeModel.ts 的任何导出。
  11. */
  12. import { describe, expect, it, vi } from "vitest";
  13. import { BUILTIN_MODEL_PROVIDER_IDS, type ZCodeAccountAccess } from "@zcode/shared";
  14. import type { ModelSelectionView } from "@zcode/provider";
  15. // 凭证解析日志的级别断言(OMCP-LOG-*):mock 掉 serviceLogger 才能观察到模块级
  16. // `const log` 的调用;该文件其余用例不断言日志,mock 对它们是透明的。
  17. const { serviceInfo } = vi.hoisted(() => ({ serviceInfo: vi.fn() }));
  18. vi.mock("#src/logger/serviceLogger.js", () => ({
  19. createServiceLogger: () => ({
  20. debug: vi.fn(),
  21. info: serviceInfo,
  22. warn: vi.fn(),
  23. error: vi.fn(),
  24. }),
  25. }));
  26. import {
  27. buildOfficialMcpAuthHeaders,
  28. createCredentialResolvedLogKey,
  29. createOfficialMcpAuthHeadersResolver,
  30. resolveOfficialMcpCredentials,
  31. type OfficialMcpCredentialResolverDeps,
  32. } from "../src/official-mcp/officialMcpCredentials.js";
  33. const JWT = "zcode-jwt-value";
  34. /** MaaS 登录 JWT:Coding Plan 凭证自 2026-08 起走这条通道(X-Bigmodel-Authorization)。 */
  35. const MAAS_JWT = "bigmodel-maas-jwt";
  36. const ZAI_MAAS_JWT = "zai-maas-jwt";
  37. function createRegistry(
  38. providers: Array<{ providerId: string; config: { access: Record<string, unknown> } }>,
  39. ): ModelSelectionView {
  40. return { revision: 1, providers } as unknown as ModelSelectionView;
  41. }
  42. function individualProvider(family: "zai" | "bigmodel") {
  43. return {
  44. providerId:
  45. family === "zai"
  46. ? BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan
  47. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  48. config: {
  49. access: {
  50. type: "zhipu-account",
  51. accountType: family,
  52. mode: "individual-coding-plan",
  53. entitled: true,
  54. },
  55. },
  56. };
  57. }
  58. function teamProvider(family: "zai" | "bigmodel") {
  59. return {
  60. providerId:
  61. family === "zai"
  62. ? BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan
  63. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  64. config: {
  65. access: {
  66. type: "zhipu-account",
  67. accountType: family,
  68. mode: "team-coding-plan",
  69. entitled: true,
  70. },
  71. },
  72. };
  73. }
  74. interface DepsOverrides {
  75. activeProvider?: string | null;
  76. activeProviderSequence?: Array<string | null>;
  77. jwt?: string | null;
  78. /** 依次返回的 JWT,用于模拟 registry 读取期间的 token 轮换(SG-01)。 */
  79. jwtSequence?: Array<string | null>;
  80. /** 覆盖 `oauth:<provider>:access_token`(MaaS 登录 JWT)。 */
  81. maasJwt?: string | null;
  82. /** 依次返回的 MaaS JWT,用于模拟它在 registry 读取期间轮换。 */
  83. maasJwtSequence?: Array<string | null>;
  84. registry?: ModelSelectionView;
  85. registrySequence?: ModelSelectionView[];
  86. settings?: Record<string, unknown>;
  87. settingsSequence?: Array<Record<string, unknown>>;
  88. accountAccess?: ZCodeAccountAccess | null;
  89. accountAccessSequence?: Array<ZCodeAccountAccess | null>;
  90. }
  91. function createDeps(overrides: DepsOverrides = {}): OfficialMcpCredentialResolverDeps {
  92. let activeProviderCalls = 0;
  93. let jwtCalls = 0;
  94. let maasJwtCalls = 0;
  95. let registryCalls = 0;
  96. let accountAccessCalls = 0;
  97. return {
  98. accountRequestAuthService: {
  99. resolveAccessCurrent: async (access) => {
  100. if (overrides.accountAccessSequence) {
  101. const value =
  102. overrides.accountAccessSequence[
  103. Math.min(accountAccessCalls, overrides.accountAccessSequence.length - 1)
  104. ];
  105. accountAccessCalls += 1;
  106. return value ?? null;
  107. }
  108. if (overrides.accountAccess !== undefined) return overrides.accountAccess;
  109. return access.mode === "individual-coding-plan"
  110. ? {
  111. type: "zhipu-account" as const,
  112. family: access.accountType,
  113. planKind: "individual-coding-plan" as const,
  114. }
  115. : null;
  116. },
  117. },
  118. credentialService: {
  119. load: async (key: string) => {
  120. if (key === "oauth:active_provider") {
  121. if (overrides.activeProviderSequence) {
  122. const value =
  123. overrides.activeProviderSequence[
  124. Math.min(activeProviderCalls, overrides.activeProviderSequence.length - 1)
  125. ];
  126. activeProviderCalls += 1;
  127. return value ?? null;
  128. }
  129. return overrides.activeProvider === undefined ? "bigmodel" : overrides.activeProvider;
  130. }
  131. if (key === "zcodejwttoken") {
  132. if (overrides.jwtSequence) {
  133. const value =
  134. overrides.jwtSequence[Math.min(jwtCalls, overrides.jwtSequence.length - 1)];
  135. jwtCalls += 1;
  136. return value ?? null;
  137. }
  138. return overrides.jwt === undefined ? JWT : overrides.jwt;
  139. }
  140. // MaaS 登录 JWT 按 family 精确取键,禁止跨 family 回退。
  141. if (key === "oauth:bigmodel:access_token" || key === "oauth:zai:access_token") {
  142. if (overrides.maasJwtSequence) {
  143. const value =
  144. overrides.maasJwtSequence[
  145. Math.min(maasJwtCalls, overrides.maasJwtSequence.length - 1)
  146. ];
  147. maasJwtCalls += 1;
  148. return value ?? null;
  149. }
  150. if (overrides.maasJwt !== undefined) return overrides.maasJwt;
  151. return key === "oauth:zai:access_token" ? ZAI_MAAS_JWT : MAAS_JWT;
  152. }
  153. return null;
  154. },
  155. },
  156. modelSelectionService: {
  157. getView: async () => {
  158. const fallback = overrides.registry ?? createRegistry([individualProvider("bigmodel")]);
  159. const value =
  160. overrides.registrySequence?.[
  161. Math.min(registryCalls, overrides.registrySequence.length - 1)
  162. ];
  163. registryCalls += 1;
  164. return value ?? fallback;
  165. },
  166. },
  167. };
  168. }
  169. describe("official mcp credential resolver", () => {
  170. it("OMCP-021: emits PERSONAL target type for a personal coding plan", async () => {
  171. const outcome = await resolveOfficialMcpCredentials(createDeps());
  172. expect(outcome).toMatchObject({ ok: true });
  173. if (!outcome.ok) return;
  174. expect(outcome.snapshot.planScope).toEqual({ targetType: "PERSONAL" });
  175. expect(outcome.snapshot.wireScope).toEqual({ targetType: "PERSONAL" });
  176. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  177. Authorization: `Bearer ${JWT}`,
  178. "Bigmodel-Target-Type": "PERSONAL",
  179. "X-Bigmodel-Authorization": `Bearer ${MAAS_JWT}`,
  180. });
  181. });
  182. it("OMCP-005/021: emits TEAM target type with paired identity for a BigModel team plan", async () => {
  183. const outcome = await resolveOfficialMcpCredentials(
  184. createDeps({
  185. registry: createRegistry([teamProvider("bigmodel")]),
  186. accountAccess: {
  187. type: "zhipu-account",
  188. family: "bigmodel",
  189. planKind: "team-coding-plan",
  190. productId: "coding",
  191. organizationId: "org-1",
  192. projectId: "project-1",
  193. },
  194. settings: {
  195. providerFamilyConnectionSelections: {
  196. bigmodel: {
  197. kind: "team-coding-plan",
  198. productId: "coding",
  199. organizationId: "org-1",
  200. projectId: "project-1",
  201. },
  202. },
  203. providerFamilyDomain: "bigmodel",
  204. },
  205. }),
  206. );
  207. expect(outcome).toMatchObject({ ok: true });
  208. if (!outcome.ok) return;
  209. expect(outcome.snapshot).toMatchObject({
  210. planScope: {
  211. organizationId: "org-1",
  212. projectId: "project-1",
  213. targetType: "TEAM",
  214. },
  215. wireScope: {
  216. organizationId: "org-1",
  217. projectId: "project-1",
  218. targetType: "TEAM",
  219. },
  220. });
  221. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  222. Authorization: `Bearer ${JWT}`,
  223. "Bigmodel-Organization": "org-1",
  224. "Bigmodel-Project": "project-1",
  225. "Bigmodel-Target-Type": "TEAM",
  226. "X-Bigmodel-Authorization": `Bearer ${MAAS_JWT}`,
  227. });
  228. });
  229. it("OMCP-006: wireScope=null never emits partial team headers", () => {
  230. expect(
  231. buildOfficialMcpAuthHeaders({
  232. codingPlanAuthorization: MAAS_JWT,
  233. jwt: JWT,
  234. planScope: null,
  235. providerFamily: "bigmodel",
  236. wireScope: null,
  237. }),
  238. ).toEqual({
  239. Authorization: `Bearer ${JWT}`,
  240. "X-Bigmodel-Authorization": `Bearer ${MAAS_JWT}`,
  241. });
  242. });
  243. it("OMCP-021: keeps zai-team consistent with Off-Peak by omitting Target-Type entirely", async () => {
  244. const outcome = await resolveOfficialMcpCredentials(
  245. createDeps({
  246. activeProvider: "zai",
  247. registry: createRegistry([teamProvider("zai")]),
  248. accountAccess: {
  249. type: "zhipu-account",
  250. family: "zai",
  251. planKind: "team-coding-plan",
  252. productId: "coding",
  253. organizationId: "org-z",
  254. projectId: "project-z",
  255. },
  256. settings: {
  257. providerFamilyConnectionSelections: {
  258. zai: {
  259. kind: "team-coding-plan",
  260. productId: "coding",
  261. organizationId: "org-z",
  262. projectId: "project-z",
  263. },
  264. },
  265. providerFamilyDomain: "zai",
  266. },
  267. }),
  268. );
  269. expect(outcome).toMatchObject({ ok: true });
  270. if (!outcome.ok) return;
  271. expect(outcome.snapshot.planScope).toEqual({
  272. organizationId: "org-z",
  273. projectId: "project-z",
  274. targetType: "TEAM",
  275. });
  276. expect(outcome.snapshot.wireScope).toBeNull();
  277. const headers = buildOfficialMcpAuthHeaders(outcome.snapshot);
  278. expect(headers["Bigmodel-Target-Type"]).toBeUndefined();
  279. expect(headers["Bigmodel-Organization"]).toBeUndefined();
  280. expect(headers["Bigmodel-Project"]).toBeUndefined();
  281. });
  282. it("OMCP-023: sends only the ZCode JWT for a Start Plan connection", async () => {
  283. const outcome = await resolveOfficialMcpCredentials(
  284. createDeps({
  285. registry: createRegistry([
  286. {
  287. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  288. config: {
  289. access: {
  290. type: "zhipu-account",
  291. family: "bigmodel",
  292. mode: "start-plan",
  293. },
  294. },
  295. },
  296. ]),
  297. }),
  298. );
  299. expect(outcome).toEqual({
  300. ok: true,
  301. snapshot: {
  302. jwt: JWT,
  303. planScope: null,
  304. providerFamily: "bigmodel",
  305. wireScope: null,
  306. },
  307. });
  308. if (!outcome.ok) return;
  309. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  310. Authorization: `Bearer ${JWT}`,
  311. });
  312. });
  313. it("OMCP-009: reports unavailable when not logged in and plan-required without Account Access", async () => {
  314. await expect(resolveOfficialMcpCredentials(createDeps({ jwt: "" }))).resolves.toEqual({
  315. ok: false,
  316. reason: "official_auth_unavailable",
  317. });
  318. await expect(
  319. resolveOfficialMcpCredentials(
  320. createDeps({
  321. accountAccess: null,
  322. registry: createRegistry([individualProvider("bigmodel")]),
  323. }),
  324. ),
  325. ).resolves.toEqual({ ok: false, reason: "official_auth_plan_required" });
  326. });
  327. it("rejects a login identity that does not match the selected family", async () => {
  328. // ZAI JWT + BigModel key 拼进同一请求,服务端只能在业务校验时才拒绝,这里提前挡掉。
  329. await expect(
  330. resolveOfficialMcpCredentials(createDeps({ activeProvider: "zai" })),
  331. ).resolves.toEqual({ ok: false, reason: "official_auth_unavailable" });
  332. });
  333. it("sends only the ZCode JWT when the selected coding plan connection is absent", async () => {
  334. const outcome = await resolveOfficialMcpCredentials(
  335. createDeps({ registry: createRegistry([]) }),
  336. );
  337. expect(outcome).toMatchObject({ ok: true });
  338. if (!outcome.ok) return;
  339. expect(buildOfficialMcpAuthHeaders(outcome.snapshot)).toEqual({
  340. Authorization: `Bearer ${JWT}`,
  341. });
  342. });
  343. it("does not require a MaaS JWT when no Coding Plan provider is selected", async () => {
  344. const outcome = await resolveOfficialMcpCredentials(
  345. createDeps({ maasJwt: null, registry: createRegistry([]) }),
  346. );
  347. expect(outcome).toMatchObject({ ok: true });
  348. if (!outcome.ok) return;
  349. expect(outcome.snapshot.codingPlanAuthorization).toBeUndefined();
  350. });
  351. it("rejects an identity-only snapshot while the active provider remains unstable", async () => {
  352. await expect(
  353. resolveOfficialMcpCredentials(
  354. createDeps({
  355. activeProviderSequence: ["bigmodel", "zai", "bigmodel", "zai"],
  356. registry: createRegistry([]),
  357. }),
  358. ),
  359. ).resolves.toEqual({ ok: false, reason: "official_auth_unavailable" });
  360. });
  361. it("reports official_auth_unavailable when the MaaS login JWT is missing", async () => {
  362. // 登录态不完整(需重新登录),不是"没有套餐"——两个 provider adapter 登录时都硬性要求
  363. // 写入该 token,因此这主要出现在历史迁移过来的旧登录态上。
  364. await expect(resolveOfficialMcpCredentials(createDeps({ maasJwt: "" }))).resolves.toEqual({
  365. ok: false,
  366. reason: "official_auth_unavailable",
  367. });
  368. });
  369. it("takes the MaaS JWT of the selected family, never the other one", async () => {
  370. const outcome = await resolveOfficialMcpCredentials(
  371. createDeps({
  372. activeProvider: "zai",
  373. registry: createRegistry([individualProvider("zai")]),
  374. settings: {
  375. providerFamilyConnectionSelections: {
  376. zai: { kind: "individual-coding-plan" },
  377. },
  378. providerFamilyDomain: "zai",
  379. },
  380. }),
  381. );
  382. expect(outcome).toMatchObject({ ok: true });
  383. if (!outcome.ok) return;
  384. // 跨 family 回退会发出一次注定失败的请求,且失败原因会指向"没有套餐"这种误导结论。
  385. expect(outcome.snapshot.codingPlanAuthorization).toBe(ZAI_MAAS_JWT);
  386. });
  387. it("re-resolves once when the selection changes mid-flight, then gives up", async () => {
  388. // 前后指纹不一致必须重来,绝不拼接两代凭证。两轮都不稳定则按不可用返回。
  389. const flipping = [
  390. createRegistry([individualProvider("bigmodel")]),
  391. createRegistry([individualProvider("zai")]),
  392. ];
  393. const outcome = await resolveOfficialMcpCredentials(
  394. createDeps({ registrySequence: [flipping[0]!, flipping[1]!, flipping[0]!, flipping[1]!] }),
  395. );
  396. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  397. });
  398. it("动态 Team scope 在解析前后变化时不拼接两代身份", async () => {
  399. const teamAccess = (projectId: string): ZCodeAccountAccess => ({
  400. type: "zhipu-account",
  401. family: "bigmodel",
  402. planKind: "team-coding-plan",
  403. productId: "coding",
  404. organizationId: "org-1",
  405. projectId,
  406. });
  407. const outcome = await resolveOfficialMcpCredentials(
  408. createDeps({
  409. registry: createRegistry([teamProvider("bigmodel")]),
  410. accountAccessSequence: [
  411. teamAccess("project-a"),
  412. teamAccess("project-b"),
  413. teamAccess("project-a"),
  414. teamAccess("project-b"),
  415. ],
  416. }),
  417. );
  418. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  419. });
  420. it("SG-01: discards the round when the JWT rotates during the registry read", async () => {
  421. // 读取顺序:每轮 首次 JWT -> registry -> 二次一致性检查再读 JWT。
  422. // 四个互不相同的值让**两轮**的前后读取都不一致 => 按不可用返回,
  423. // 绝不产出"旧 JWT + 新 key"的混代快照。
  424. const outcome = await resolveOfficialMcpCredentials(
  425. createDeps({
  426. jwtSequence: ["jwt-gen-1", "jwt-gen-2", "jwt-gen-3", "jwt-gen-4"],
  427. }),
  428. );
  429. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  430. });
  431. it("discards the round when the MaaS JWT rotates during the registry read", async () => {
  432. // 与上一条同理:MaaS JWT 现在是真正的 Coding Plan 凭证,必须一起纳入前后一致性检查,
  433. // 否则会拼出"旧 zcode JWT + 新 MaaS JWT"的混代快照。
  434. const outcome = await resolveOfficialMcpCredentials(
  435. createDeps({
  436. maasJwtSequence: ["maas-gen-1", "maas-gen-2", "maas-gen-3", "maas-gen-4"],
  437. }),
  438. );
  439. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  440. });
  441. it("SG-01: accepts the snapshot when the JWT stays stable across the registry read", async () => {
  442. // 第 1、2 次读取一致(同一代),必须成功且快照使用该 JWT。
  443. const outcome = await resolveOfficialMcpCredentials(
  444. createDeps({ jwtSequence: ["jwt-stable", "jwt-stable"] }),
  445. );
  446. expect(outcome).toMatchObject({ ok: true });
  447. if (!outcome.ok) return;
  448. expect(outcome.snapshot.jwt).toBe("jwt-stable");
  449. });
  450. it("SG-01: recovers when the JWT rotates once and then settles", async () => {
  451. // 第一轮不一致(gen1 -> gen2),第二轮稳定在 gen2 => 最终成功且用 gen2。
  452. const outcome = await resolveOfficialMcpCredentials(
  453. createDeps({ jwtSequence: ["jwt-gen-1", "jwt-gen-2", "jwt-gen-2", "jwt-gen-2"] }),
  454. );
  455. expect(outcome).toMatchObject({ ok: true });
  456. if (!outcome.ok) return;
  457. expect(outcome.snapshot.jwt).toBe("jwt-gen-2");
  458. });
  459. it("OMCP-024: has no mock credential branch at all", async () => {
  460. // Off-Peak 的 ZCODE_OFFPEAK_MOCK 占位凭证分支不得在官方 MCP 路径复现。
  461. const previous = process.env["ZCODE_OFFPEAK_MOCK"];
  462. process.env["ZCODE_OFFPEAK_MOCK"] = "1";
  463. try {
  464. const outcome = await resolveOfficialMcpCredentials(createDeps({ jwt: "" }));
  465. expect(outcome).toEqual({ ok: false, reason: "official_auth_unavailable" });
  466. const ok = await resolveOfficialMcpCredentials(createDeps());
  467. expect(ok).toMatchObject({ ok: true });
  468. if (!ok.ok) return;
  469. expect(ok.snapshot.jwt).toBe(JWT);
  470. expect(ok.snapshot.codingPlanAuthorization).toBe(MAAS_JWT);
  471. } finally {
  472. if (previous === undefined) delete process.env["ZCODE_OFFPEAK_MOCK"];
  473. else process.env["ZCODE_OFFPEAK_MOCK"] = previous;
  474. }
  475. });
  476. it("OMCP-026: dedupes concurrent resolves into a single underlying resolution", async () => {
  477. const deps = createDeps();
  478. const spy = vi.spyOn(deps.modelSelectionService, "getView");
  479. const resolver = createOfficialMcpAuthHeadersResolver(deps);
  480. const results = await Promise.all([
  481. resolver.resolveHeaders(),
  482. resolver.resolveHeaders(),
  483. resolver.resolveHeaders(),
  484. resolver.resolveHeaders(),
  485. ]);
  486. expect(spy).toHaveBeenCalledTimes(2);
  487. for (const result of results) {
  488. expect(result).toEqual(results[0]);
  489. }
  490. });
  491. it("OMCP-027: re-resolves after settle, so a connection switch is picked up", async () => {
  492. const deps = createDeps();
  493. const spy = vi.spyOn(deps.modelSelectionService, "getView");
  494. const resolver = createOfficialMcpAuthHeadersResolver(deps);
  495. await resolver.resolveHeaders();
  496. await resolver.resolveHeaders();
  497. // 无时间维度缓存:顺序两次调用必须各解析一遍
  498. expect(spy).toHaveBeenCalledTimes(4);
  499. });
  500. it("clears the in-flight slot when a resolution throws", async () => {
  501. let shouldThrow = true;
  502. const deps = createDeps();
  503. deps.modelSelectionService.getView = async () => {
  504. if (shouldThrow) throw new Error("registry unavailable");
  505. return createRegistry([individualProvider("bigmodel")]);
  506. };
  507. const resolver = createOfficialMcpAuthHeadersResolver(deps);
  508. await expect(resolver.resolveHeaders()).rejects.toThrow("registry unavailable");
  509. shouldThrow = false;
  510. // 失败的 Promise 不得被后续请求永久复用
  511. await expect(resolver.resolveHeaders()).resolves.toMatchObject({ ok: true });
  512. });
  513. });
  514. /* OMCP-LOG —— 凭证解析成功日志:info 级 + 小时分桶去重(spec §4 审计规则)。
  515. *
  516. * 背景:MaaS JWT 无刷新链路,过期被服务端 3101 折叠成 "coding plan is required"(2026-09-12
  517. * 用户事故),剩余有效期是客户端唯一可自证的线索,因此必须 info(生产 debug 不落盘);
  518. * 但解析与官方 MCP 请求数同数量级,必须去重(见 createCredentialResolvedLogKey)。
  519. */
  520. describe("official mcp credential resolved log", () => {
  521. it("OMCP-LOG-01: dedup key buckets expiry by hour and separates family/scope", () => {
  522. const personal = { providerFamily: "bigmodel", planTargetType: "PERSONAL" } as const;
  523. expect(createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: 3600 })).toBe(
  524. "bigmodel|PERSONAL|t1",
  525. );
  526. // 桶边界:3599 落在 t0,跨过 3600 进入 t1
  527. expect(createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: 3599 })).toBe(
  528. "bigmodel|PERSONAL|t0",
  529. );
  530. // 过期(≤0)与解析失败(undefined)是独立桶:跨过零点、token 形态变化必落新键
  531. expect(createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: -5 })).toBe(
  532. "bigmodel|PERSONAL|expired",
  533. );
  534. expect(
  535. createCredentialResolvedLogKey({ ...personal, maasJwtExpiresInSeconds: undefined }),
  536. ).toBe("bigmodel|PERSONAL|unparsable");
  537. expect(
  538. createCredentialResolvedLogKey({
  539. providerFamily: "zai",
  540. planTargetType: null,
  541. maasJwtExpiresInSeconds: 100,
  542. }),
  543. ).toBe("zai|none|t0");
  544. // PERSONAL↔TEAM 切换是身份头语义变化,必须可分辨
  545. expect(
  546. createCredentialResolvedLogKey({
  547. providerFamily: "zai",
  548. planTargetType: "TEAM",
  549. maasJwtExpiresInSeconds: 100,
  550. }),
  551. ).not.toBe(
  552. createCredentialResolvedLogKey({
  553. providerFamily: "zai",
  554. planTargetType: "PERSONAL",
  555. maasJwtExpiresInSeconds: 100,
  556. }),
  557. );
  558. });
  559. it("OMCP-LOG-02: logs jwt expiry at info level and dedupes same-bucket re-resolves", async () => {
  560. // 123456s ≈ 34.3h → t34 桶:本文件其他用例都用解析不出 exp 的假 token(unparsable
  561. // 桶),独特桶值保证本用例首调不被模块级去重键吞掉,用例间不依赖执行顺序。
  562. const deps = createDeps({ maasJwt: makeMaasJwtWithExpiry(123456) });
  563. serviceInfo.mockClear();
  564. const first = await resolveOfficialMcpCredentials(deps);
  565. expect(first.ok).toBe(true);
  566. const resolvedCalls = () =>
  567. serviceInfo.mock.calls.filter(
  568. (call): call is [string, Record<string, unknown>] =>
  569. call[0] === "official mcp credentials resolved",
  570. );
  571. expect(resolvedCalls()).toHaveLength(1);
  572. const fields = resolvedCalls()[0]![1]!;
  573. expect(fields).toMatchObject({
  574. providerFamily: "bigmodel",
  575. planTargetType: "PERSONAL",
  576. wireTargetType: "PERSONAL",
  577. });
  578. expect(fields["maasJwtExpiresInSeconds"]).toBeGreaterThan(123_000);
  579. expect(fields["maasJwtExpiresInSeconds"]).toBeLessThan(123_900);
  580. // resolver 无时间缓存,同一桶内重复解析(两次构造 token 相差 0~1s,同落 t34)
  581. // 不得重复记录——否则日志量与官方 MCP 请求数同数量级。
  582. const second = await resolveOfficialMcpCredentials(
  583. createDeps({ maasJwt: makeMaasJwtWithExpiry(123456) }),
  584. );
  585. expect(second.ok).toBe(true);
  586. expect(resolvedCalls()).toHaveLength(1);
  587. });
  588. it("OMCP-LOG-03: identity-only degradation stays out of info logs", async () => {
  589. // 已登录但 Registry 无 coding plan provider → identity-only 降级仍走 debug,
  590. // 不产生 info 噪音(本次升级范围仅限带 MaaS JWT 的成功解析)。
  591. const deps = createDeps({ registry: createRegistry([]) });
  592. const outcome = await resolveOfficialMcpCredentials(deps);
  593. expect(outcome).toMatchObject({ ok: true });
  594. expect(
  595. serviceInfo.mock.calls.filter((call) => String(call[0]).includes("identity-only")),
  596. ).toHaveLength(0);
  597. });
  598. });
  599. /** 造一个能被 readJwtExpiresInSeconds 解析出 exp 的三段式 MaaS JWT(base64url payload)。 */
  600. function makeMaasJwtWithExpiry(expiresInSeconds: number): string {
  601. const payload = Buffer.from(
  602. JSON.stringify({ exp: Math.round(Date.now() / 1000) + expiresInSeconds }),
  603. ).toString("base64url");
  604. return `header.${payload}.signature`;
  605. }