officialMcpCredentials.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /*
  2. * ZCode 官方 Server MCP 的凭证解析与身份头构造。
  3. *
  4. * 本文件与 Off-Peak 的 offPeakRuntimeModel.ts **逻辑等价但完全独立**:
  5. * 不复用其函数、不修改其行为。理由是两者的套餐门槛、Team 支持范围与凭证通道预期会独立演进,
  6. * 共享 helper 会让任一侧的调整都变成需要评估双方影响的改动。
  7. *
  8. * 与 Off-Peak 的三处有意差异:
  9. * 1. 显式产出 Bigmodel-Target-Type(Off-Peak 侧当前没有生产者);
  10. * 2. 不存在任何 mock 凭证分支(官方 MCP 无 mock 网关,测试用依赖注入替换来源);
  11. * 3. 失败原因使用 official_* 分类,不复用 Off-Peak 的 reason 字符串。
  12. *
  13. * 凭证通道:Coding Plan 凭证走 `X-Bigmodel-Authorization` + MaaS 登录 JWT,
  14. * 不再发送 `X-Coding-Plan-Api-Key`。服务端把 API key 通道标为"仅存量客户端兼容",且两个头同时
  15. * 发送是有害的——JWT 会赢得额度查询,但 API key 的归属校验仍会照跑,一把过期 key 就能让整个
  16. * 请求 403。Off-Peak 仍走 API key 通道,这也是上面"逻辑等价但完全独立"的又一个理由。
  17. */
  18. import {
  19. OFFICIAL_MCP_AUTH_HEADER_NAMES,
  20. zcodeProviderAccountAccessSchema,
  21. type OfficialAuthConsumerKind,
  22. type OfficialMcpAuthFailureReason,
  23. type ZCodeAccountAccess,
  24. type ZCodeProviderAccountAccess,
  25. } from "@zcode/shared";
  26. import {
  27. isSameOAuthAccountMaterial,
  28. type OAuthAccountMaterial,
  29. type OAuthIdentityMaterial,
  30. } from "#src/oauth/repo/oauthCredentialRepo.js";
  31. import type { ModelSelectionView } from "@zcode/provider";
  32. import { createServiceLogger } from "#src/logger/serviceLogger.js";
  33. const log = createServiceLogger("official-mcp");
  34. /**
  35. * 只为日志算出 JWT 的剩余有效期(秒)。**不参与任何控制流**,解析失败返回 undefined。
  36. *
  37. * 存在理由:MaaS JWT 没有刷新链路,过期后服务端的表现是 queryCodingPlan 上游 401,
  38. * 客户端却收到"需要 Coding Plan"这类文案——真实原因与提示不符。有了这个数值,
  39. * "神秘的 403"能一眼看出是"token 早就过期了"。只记数字,绝不记 token 本身。
  40. */
  41. function readJwtExpiresInSeconds(token: string): number | undefined {
  42. const payload = token.split(".")[1];
  43. if (!payload) return undefined;
  44. try {
  45. const normalized = payload.replaceAll("-", "+").replaceAll("_", "/");
  46. const decoded: unknown = JSON.parse(Buffer.from(normalized, "base64").toString("utf8"));
  47. if (typeof decoded !== "object" || decoded === null) return undefined;
  48. const exp = (decoded as { exp?: unknown }).exp;
  49. if (typeof exp !== "number" || !Number.isFinite(exp)) return undefined;
  50. return Math.round(exp - Date.now() / 1000);
  51. } catch {
  52. return undefined;
  53. }
  54. }
  55. /** 凭证解析 info 日志的有效期分桶粒度(秒);桶内不重复记录,见 createCredentialResolvedLogKey。 */
  56. const CREDENTIAL_RESOLVED_LOG_BUCKET_SECONDS = 3600;
  57. /**
  58. * 凭证解析成功日志的去重键(导出仅为可单测,无其他消费方)。
  59. *
  60. * 生产日志保留 JWT 有效期分桶,帮助区分凭据过期与套餐不可用,不记录凭据原文。
  61. * resolver 只合并正在执行的请求,没有时间缓存;因此按小时分桶去重,避免每次
  62. * MCP 调用都产生 info 日志。凭据有效期跨桶、进入 expired 或切换套餐类型时重新记录。
  63. */
  64. export function createCredentialResolvedLogKey(input: {
  65. providerFamily: "zai" | "bigmodel";
  66. planTargetType: string | null;
  67. maasJwtExpiresInSeconds: number | undefined;
  68. }): string {
  69. const expires = input.maasJwtExpiresInSeconds;
  70. const expiryBucket =
  71. expires === undefined
  72. ? "unparsable"
  73. : expires <= 0
  74. ? "expired"
  75. : `t${Math.floor(expires / CREDENTIAL_RESOLVED_LOG_BUCKET_SECONDS)}`;
  76. return `${input.providerFamily}|${input.planTargetType ?? "none"}|${expiryBucket}`;
  77. }
  78. let lastCredentialResolvedLogKey: string | undefined;
  79. export interface OfficialMcpCredentialResolveOptions {
  80. /**
  81. * 套餐可选(插件命令进程,技术方案 5.8):选中连接没有有效套餐时不返回 plan_required,
  82. * 只给 ZCode 登录身份,由服务端按免费档处理。登录态不完整(缺 MaaS JWT、跨 family)
  83. * 仍按 unavailable 返回,绝不把付费用户降成免费。
  84. */
  85. planOptional?: boolean;
  86. }
  87. export interface OfficialMcpCredentialResolverDeps {
  88. accountRequestAuthService: {
  89. resolveAccessCurrent(access: ZCodeProviderAccountAccess): Promise<ZCodeAccountAccess | null>;
  90. };
  91. getRegistryRevision(): number | null;
  92. loadOAuthIdentityMaterial(): Promise<OAuthIdentityMaterial | null>;
  93. loadOAuthAccountMaterial(family: "zai" | "bigmodel"): Promise<OAuthAccountMaterial | null>;
  94. modelSelectionService: {
  95. getView(): Promise<ModelSelectionView>;
  96. };
  97. }
  98. export type OfficialMcpPlanScope =
  99. | { targetType: "PERSONAL" }
  100. | { targetType: "TEAM"; organizationId: string; projectId: string };
  101. export type OfficialMcpWireScope = OfficialMcpPlanScope | null;
  102. /** 解析成功后的凭证快照。仅在 host/service 进程内存活,脱敏后才允许过 RPC。 */
  103. export interface OfficialMcpCredentialSnapshot {
  104. jwt: string;
  105. /**
  106. * MaaS 登录 JWT(`oauth:<family>:access_token` 的原文,**不带 Bearer 前缀**)。
  107. * 前缀在 buildOfficialMcpAuthHeaders 里加,与 reset / usage 通道的既有约定一致。
  108. */
  109. codingPlanAuthorization?: string;
  110. providerFamily: "zai" | "bigmodel" | "zai_cn";
  111. /** 当前选中连接的产品/额度归属;畸形旧 Team key 无法精确归属时为 null。 */
  112. planScope: OfficialMcpPlanScope | null;
  113. /** 实际发往 Server MCP 的身份头 scope;ZAI Team 与 Off-Peak 一致为 null。 */
  114. wireScope: OfficialMcpWireScope;
  115. }
  116. export type OfficialMcpCredentialOutcome =
  117. | { ok: true; snapshot: OfficialMcpCredentialSnapshot }
  118. | { ok: false; reason: OfficialMcpAuthFailureReason };
  119. type SelectedPlan = {
  120. providerFamily: "zai" | "bigmodel";
  121. providerId: string;
  122. planScope: OfficialMcpPlanScope | null;
  123. wireScope: OfficialMcpWireScope;
  124. };
  125. type SelectedProvider = {
  126. providerId: string;
  127. access: ZCodeProviderAccountAccess;
  128. };
  129. function fail(reason: OfficialMcpAuthFailureReason): {
  130. ok: false;
  131. reason: OfficialMcpAuthFailureReason;
  132. } {
  133. return { ok: false, reason };
  134. }
  135. /**
  136. * 从 Registry 判定当前启用的 Coding Plan Provider;动态套餐和 Team scope 随后由账号服务解析。
  137. * 禁止从静态 Provider Config 读取或伪造当前 Team scope。
  138. */
  139. function resolveSelectedProvider(
  140. registry: ModelSelectionView,
  141. ): { ok: true; provider: SelectedProvider } | { ok: false; reason: OfficialMcpAuthFailureReason } {
  142. const candidates = registry.providers.flatMap((provider) => {
  143. const parsed = zcodeProviderAccountAccessSchema.safeParse(provider.config.access);
  144. return parsed.success &&
  145. (parsed.data.mode === "individual-coding-plan" || parsed.data.mode === "team-coding-plan")
  146. ? [{ providerId: provider.providerId, access: parsed.data }]
  147. : [];
  148. });
  149. if (candidates.length !== 1) {
  150. return fail("official_auth_plan_required");
  151. }
  152. return { ok: true, provider: candidates[0]! };
  153. }
  154. function resolveSelectedPlan(
  155. selectedProvider: SelectedProvider,
  156. access: ZCodeAccountAccess | null,
  157. ): { ok: true; plan: SelectedPlan } | { ok: false; reason: OfficialMcpAuthFailureReason } {
  158. if (
  159. !access ||
  160. access.family !== selectedProvider.access.accountType ||
  161. (selectedProvider.access.mode === "team-coding-plan"
  162. ? access.planKind !== "team-coding-plan"
  163. : access.planKind !== "individual-coding-plan")
  164. ) {
  165. return fail("official_auth_plan_required");
  166. }
  167. const { providerId } = selectedProvider;
  168. const providerFamily = access.family;
  169. if (access.planKind === "team-coding-plan") {
  170. const teamScope: OfficialMcpPlanScope = {
  171. organizationId: access.organizationId,
  172. projectId: access.projectId,
  173. targetType: "TEAM",
  174. };
  175. return {
  176. ok: true,
  177. plan: {
  178. providerFamily,
  179. providerId,
  180. planScope: teamScope,
  181. wireScope: providerFamily === "bigmodel" ? teamScope : null,
  182. },
  183. };
  184. }
  185. return {
  186. ok: true,
  187. plan: {
  188. providerFamily,
  189. providerId,
  190. planScope: { targetType: "PERSONAL" },
  191. wireScope: { targetType: "PERSONAL" },
  192. },
  193. };
  194. }
  195. /** 非秘密的选择指纹,用于解析前后比对,防止把切换前后的两代凭证拼进同一请求。 */
  196. function createSelectionFingerprint(registry: ModelSelectionView): string {
  197. return JSON.stringify({ revision: registry.revision, providers: registry.providers });
  198. }
  199. type OfficialMcpIdentitySnapshot = {
  200. activeProvider: "zai" | "bigmodel" | "zai_cn";
  201. userId: string;
  202. sessionRevision: string | null;
  203. jwt: string;
  204. registry: ModelSelectionView;
  205. selectionFingerprint: string;
  206. registryRevision: number | null;
  207. };
  208. async function readIdentitySnapshot(
  209. deps: OfficialMcpCredentialResolverDeps,
  210. ): Promise<
  211. | { ok: true; snapshot: OfficialMcpIdentitySnapshot }
  212. | { ok: false; reason: OfficialMcpAuthFailureReason }
  213. > {
  214. const registryRevision = deps.getRegistryRevision();
  215. const registry = await deps.modelSelectionService.getView();
  216. const identity = await deps.loadOAuthIdentityMaterial();
  217. // 读取身份期间套餐 Registry 可能已切换;同步版本检查之后不再 await。
  218. if (deps.getRegistryRevision() !== registryRevision) return fail("official_auth_unavailable");
  219. if (!identity) return fail("official_auth_unavailable");
  220. const activeProvider =
  221. identity.loginProvider === "zai"
  222. ? "zai"
  223. : identity.loginProvider === "bigmodel"
  224. ? "bigmodel"
  225. : identity.loginProvider === "zai_cn"
  226. ? "zai_cn"
  227. : null;
  228. if (!activeProvider) return fail("official_auth_unavailable");
  229. return {
  230. ok: true,
  231. snapshot: {
  232. activeProvider,
  233. userId: identity.zcodeUserId,
  234. sessionRevision: identity.sessionRevision,
  235. jwt: identity.zcodeJwtToken,
  236. registry,
  237. registryRevision,
  238. selectionFingerprint: createSelectionFingerprint(registry),
  239. },
  240. };
  241. }
  242. function isSameIdentitySnapshot(
  243. before: OfficialMcpIdentitySnapshot,
  244. after: OfficialMcpIdentitySnapshot,
  245. ): boolean {
  246. return (
  247. before.activeProvider === after.activeProvider &&
  248. before.userId === after.userId &&
  249. before.sessionRevision === after.sessionRevision &&
  250. before.jwt === after.jwt &&
  251. before.registryRevision === after.registryRevision &&
  252. before.selectionFingerprint === after.selectionFingerprint
  253. );
  254. }
  255. function identityOnlyOutcome(identity: OfficialMcpIdentitySnapshot): OfficialMcpCredentialOutcome {
  256. log.debug("official mcp identity-only credentials resolved", {
  257. providerFamily: identity.activeProvider,
  258. reason: "official_auth_plan_required",
  259. });
  260. return {
  261. ok: true,
  262. snapshot: {
  263. jwt: identity.jwt,
  264. planScope: null,
  265. providerFamily: identity.activeProvider,
  266. wireScope: null,
  267. },
  268. };
  269. }
  270. /**
  271. * 解析当前选中连接的官方 MCP 凭证。
  272. *
  273. * 防竞态:Registry、动态 Account Access、active provider、zcode JWT 与 MaaS JWT
  274. * 都可能在解析期间变化。登录渠道不决定套餐 family;主身份与关联材料必须匹配同一
  275. * user ID、revision 和业务 JWT。解析前后再比对选择及关联材料,两轮仍不稳定则返回不可用。
  276. */
  277. export async function resolveOfficialMcpCredentials(
  278. deps: OfficialMcpCredentialResolverDeps,
  279. options: OfficialMcpCredentialResolveOptions = {},
  280. ): Promise<OfficialMcpCredentialOutcome> {
  281. for (let attempt = 0; attempt < 2; attempt += 1) {
  282. const identity = await readIdentitySnapshot(deps);
  283. if (!identity.ok) {
  284. if (attempt === 0) continue;
  285. return identity;
  286. }
  287. const selectedProvider = resolveSelectedProvider(identity.snapshot.registry);
  288. if (!selectedProvider.ok) {
  289. const latestIdentity = await readIdentitySnapshot(deps);
  290. if (
  291. !latestIdentity.ok ||
  292. !isSameIdentitySnapshot(identity.snapshot, latestIdentity.snapshot)
  293. ) {
  294. continue;
  295. }
  296. return identityOnlyOutcome(identity.snapshot);
  297. }
  298. const accountAccess = await deps.accountRequestAuthService.resolveAccessCurrent(
  299. selectedProvider.provider.access,
  300. );
  301. const selected = resolveSelectedPlan(selectedProvider.provider, accountAccess);
  302. if (!selected.ok) {
  303. if (!options.planOptional || selected.reason !== "official_auth_plan_required") {
  304. return selected;
  305. }
  306. // 套餐可选:选中的 Coding Plan 连接当前没有有效套餐(过期、类型不符),按只有登录身份处理。
  307. // 和上面「没有选中套餐」一样先确认身份没有在解析期间变化。
  308. const latestIdentity = await readIdentitySnapshot(deps);
  309. if (
  310. !latestIdentity.ok ||
  311. !isSameIdentitySnapshot(identity.snapshot, latestIdentity.snapshot)
  312. ) {
  313. continue;
  314. }
  315. return identityOnlyOutcome(identity.snapshot);
  316. }
  317. const material = await deps.loadOAuthAccountMaterial(selected.plan.providerFamily);
  318. // 登录渠道和套餐家族可以不同;只能接受主身份绑定的同一份关联材料。
  319. if (
  320. !material ||
  321. material.loginProvider !== identity.snapshot.activeProvider ||
  322. material.zcodeUserId !== identity.snapshot.userId ||
  323. material.sessionRevision !== identity.snapshot.sessionRevision ||
  324. material.zcodeJwtToken !== identity.snapshot.jwt
  325. )
  326. continue;
  327. const codingPlanAuthorization = material.accessToken.trim();
  328. if (!codingPlanAuthorization) return fail("official_auth_unavailable");
  329. const latestAccountAccess = await deps.accountRequestAuthService.resolveAccessCurrent(
  330. selectedProvider.provider.access,
  331. );
  332. const latestMaterial = await deps.loadOAuthAccountMaterial(selected.plan.providerFamily);
  333. // 最后一项 IO 再读取主身份和 Registry,不能在换号后仍拼装此前的套餐头。
  334. const latestIdentity = await readIdentitySnapshot(deps);
  335. if (
  336. !latestIdentity.ok ||
  337. !isSameIdentitySnapshot(identity.snapshot, latestIdentity.snapshot) ||
  338. JSON.stringify(accountAccess) !== JSON.stringify(latestAccountAccess) ||
  339. !isSameOAuthAccountMaterial(material, latestMaterial)
  340. )
  341. continue;
  342. // provider 条目只作"该 Coding Plan 连接确实存在"的门槛。业务 key 本身不再是凭证
  343. // (已切到 MaaS JWT 通道),因此不再要求它有值——否则业务 key 正在刷新的瞬态
  344. // 会把一次本可成功的调用判成"没有套餐"。真正的"没有套餐"由上面两道门槛拦住:
  345. // API Key 模式与选中 Start Plan 连接,两者都不依赖业务 key。
  346. const provider = identity.snapshot.registry.providers.find(
  347. (candidate) => candidate.providerId === selected.plan.providerId,
  348. );
  349. if (!provider) return fail("official_auth_plan_required");
  350. // info 而非 debug:生产构建 debug 不落盘,而 MaaS JWT 剩余有效期是排障关键线索
  351. // (见 createCredentialResolvedLogKey 的说明)。只记剩余秒数,绝不记 token 本身。
  352. // 去重键跨桶才记录,避免日志量与官方 MCP 请求数同数量级。
  353. const maasJwtExpiresInSeconds = readJwtExpiresInSeconds(codingPlanAuthorization);
  354. const logKey = createCredentialResolvedLogKey({
  355. providerFamily: selected.plan.providerFamily,
  356. planTargetType: selected.plan.planScope?.targetType ?? null,
  357. maasJwtExpiresInSeconds,
  358. });
  359. if (logKey !== lastCredentialResolvedLogKey) {
  360. lastCredentialResolvedLogKey = logKey;
  361. log.info("official mcp credentials resolved", {
  362. maasJwtExpiresInSeconds,
  363. providerFamily: selected.plan.providerFamily,
  364. planTargetType: selected.plan.planScope?.targetType ?? null,
  365. wireTargetType: selected.plan.wireScope?.targetType ?? null,
  366. });
  367. }
  368. return {
  369. ok: true,
  370. snapshot: {
  371. codingPlanAuthorization,
  372. jwt: identity.snapshot.jwt,
  373. planScope: selected.plan.planScope,
  374. providerFamily: selected.plan.providerFamily,
  375. wireScope: selected.plan.wireScope,
  376. },
  377. };
  378. }
  379. return fail("official_auth_unavailable");
  380. }
  381. /**
  382. * 由凭证快照构造本次请求的身份头。
  383. * Team 身份成对原子性:organization/project 任一缺失时两者都不发送。
  384. */
  385. export function buildOfficialMcpAuthHeaders(
  386. snapshot: OfficialMcpCredentialSnapshot,
  387. ): Record<string, string> {
  388. const headers: Record<string, string> = {
  389. [OFFICIAL_MCP_AUTH_HEADER_NAMES.authorization]: `Bearer ${snapshot.jwt}`,
  390. };
  391. if (snapshot.codingPlanAuthorization) {
  392. // 服务端会 CutPrefix("Bearer "),裸 token 也接受;这里按 MCP 接口文档发 Bearer 形式。
  393. headers[OFFICIAL_MCP_AUTH_HEADER_NAMES.codingPlanAuthorization] =
  394. `Bearer ${snapshot.codingPlanAuthorization}`;
  395. }
  396. const scope = snapshot.wireScope;
  397. if (scope) {
  398. headers[OFFICIAL_MCP_AUTH_HEADER_NAMES.targetType] = scope.targetType;
  399. if (scope.targetType === "TEAM") {
  400. headers[OFFICIAL_MCP_AUTH_HEADER_NAMES.organization] = scope.organizationId;
  401. headers[OFFICIAL_MCP_AUTH_HEADER_NAMES.project] = scope.projectId;
  402. }
  403. }
  404. return headers;
  405. }
  406. /** host handler 透传的请求上下文;不参与凭证选择。 */
  407. export interface OfficialMcpAuthHeadersRequestContext {
  408. consumer: OfficialAuthConsumerKind;
  409. mcpKey: string;
  410. pluginId: string;
  411. targetOrigin: string;
  412. workspace: { workspaceIdentity?: string; workspaceKey: string; workspacePath: string };
  413. }
  414. export type OfficialMcpAuthHeadersOutcome =
  415. | { ok: true; headers: Record<string, string> }
  416. | { ok: false; reason: OfficialMcpAuthFailureReason };
  417. /**
  418. * 身份头解析入口,带 in-flight 去重。
  419. *
  420. * 只合并**并发**请求:已有解析在飞时后来者复用同一 Promise;settle 后立即丢弃,
  421. * 下一个请求重新完整解析。不做任何时间维度缓存,因此不存在"读到已被替换的旧凭证"的窗口。
  422. * 作用域为 host 全局——凭证是全局状态,按 plugin/mcpKey/workspace 分桶只会削弱去重、不增隔离。
  423. */
  424. export function createOfficialMcpAuthHeadersResolver(deps: OfficialMcpCredentialResolverDeps): {
  425. resolveHeaders(
  426. request?: OfficialMcpAuthHeadersRequestContext,
  427. ): Promise<OfficialMcpAuthHeadersOutcome>;
  428. } {
  429. // 两种消费方的解析结果不同(套餐可选与否),按模式分别合并在飞的请求。
  430. const pending = new Map<
  431. "plan-required" | "plan-optional",
  432. Promise<OfficialMcpAuthHeadersOutcome>
  433. >();
  434. return {
  435. // request 只用来选解析模式(host handler 已在此之前完成可信校验,见 zcodeAgentService);
  436. // 凭据是 host 全局状态,**不**按 plugin/mcpKey/workspace 分桶——分桶只会削弱 in-flight
  437. // 去重而不增加隔离。
  438. resolveHeaders(request?: OfficialMcpAuthHeadersRequestContext) {
  439. const mode = request?.consumer === "plugin-command" ? "plan-optional" : "plan-required";
  440. const existing = pending.get(mode);
  441. if (existing) return existing;
  442. const inFlight = (async (): Promise<OfficialMcpAuthHeadersOutcome> => {
  443. const outcome = await resolveOfficialMcpCredentials(deps, {
  444. planOptional: mode === "plan-optional",
  445. });
  446. if (!outcome.ok) return { ok: false, reason: outcome.reason };
  447. return { ok: true, headers: buildOfficialMcpAuthHeaders(outcome.snapshot) };
  448. })();
  449. pending.set(mode, inFlight);
  450. // 用双 handler 的 then 而非 finally:finally 会派生一个同样 reject 的 promise,
  451. // 调用方只 await 了 inFlight,那个派生 promise 无人处理会变成 unhandled rejection。
  452. // 解析抛错也必须清空 slot,否则后续请求会永久复用失败的 Promise。
  453. const clear = (): void => {
  454. if (pending.get(mode) === inFlight) pending.delete(mode);
  455. };
  456. inFlight.then(clear, clear);
  457. return inFlight;
  458. },
  459. };
  460. }