oauth-refresh.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import { dirname, join } from "node:path";
  2. import {
  3. discoverOAuthServerInfo,
  4. OAuthError,
  5. OAuthErrorCode,
  6. refreshAuthorization,
  7. selectResourceURL,
  8. type AuthorizationServerMetadata,
  9. type FetchLike,
  10. type OAuthDiscoveryState,
  11. } from "@modelcontextprotocol/client";
  12. import type { Logger } from "@zcode/contracts";
  13. import { isZCodeFileLockTimeoutError } from "@zcode/shared";
  14. import { withFileLock } from "@zcode/shared/node";
  15. import type { SharedZCodeCredentialStore } from "../auth/shared-credentials.js";
  16. import {
  17. invalidateCanonicalCredentials,
  18. loadCredentialPair,
  19. publishCanonicalCredentials,
  20. type CredentialPairSnapshot,
  21. } from "./oauth-credentials.js";
  22. import {
  23. createInteractiveAuthorizationRequiredError,
  24. createTemporaryRefreshFailureError,
  25. } from "./oauth-errors.js";
  26. import { sanitizeKeyPrefix } from "./oauth-lease.js";
  27. import { loadDiscoveryRecord, saveDiscoveryRecord } from "./oauth-shared.js";
  28. /**
  29. * refresh 锁的获取预算。
  30. *
  31. * 必须覆盖锁内的网络预算(一次 discovery + 一次 token 请求),否则等待者会在 winner 还没
  32. * 发布结果时就超时。`withFileLock` 的默认值只有 8 秒(privateFilePersistence.ts:9),不够。
  33. */
  34. const REFRESH_LOCK_MAX_WAIT_MS = 45_000;
  35. export interface RefreshMcpOAuthTokensInput {
  36. credentialStore: SharedZCodeCredentialStore;
  37. fetchFn?: FetchLike;
  38. keyPrefix: string;
  39. logger?: Logger;
  40. /**
  41. * reactive = 由 401 的 `onUnauthorized` 触发。
  42. *
  43. * 决定网络失败时的语义:proactive(临期主动刷新)可以 fail-soft 返回现值,因为那个 token 还没
  44. * 被资源服务器拒绝;reactive 不能——它刚被拒绝,返回它必然产生第二次 401 并抛
  45. * `ClientHttpAuthentication`,还会把临时 AS 故障误判成需要交互授权。
  46. */
  47. reactive: boolean;
  48. serverName: string;
  49. serverUrl: string;
  50. /** 静态配置的 clientId。存在时 `invalid_client` 不能靠交互授权自愈。 */
  51. staticClientId?: string;
  52. }
  53. export interface ResolvedAsMetadata {
  54. authorizationServerUrl: string;
  55. metadata?: AuthorizationServerMetadata;
  56. resource?: URL;
  57. }
  58. /**
  59. * 在跨进程单飞锁内刷新 access token,返回可用的 access token。
  60. *
  61. * 并发刷新问题:多个 CLI 进程共享同一份凭据文件,`withFileLock` 只覆盖凭据读写、不覆盖网络
  62. * token exchange。access token 过期时各进程并发用同一个 refresh token 刷新,撞授权服务器的
  63. * rotation reuse-detection,整个 token family 被撤销,最终退化成重新授权。
  64. */
  65. export async function refreshMcpOAuthTokensUnderLock(
  66. input: RefreshMcpOAuthTokensInput,
  67. ): Promise<string> {
  68. const observedGeneration = (await loadCredentialPair(input.credentialStore, input.keyPrefix))
  69. ?.generation;
  70. const lockPath = resolveRefreshLockPath(input.credentialStore.filePath, input.keyPrefix);
  71. try {
  72. return await withFileLock(lockPath, async () => await refreshLocked(input, observedGeneration), {
  73. lockMaxWaitMs: REFRESH_LOCK_MAX_WAIT_MS,
  74. });
  75. } catch (error) {
  76. if (!isZCodeFileLockTimeoutError(error)) throw error;
  77. // 等锁超时不代表刷新失败:winner 可能已经发布结果。先重读,确认换代且有 token 就直接用。
  78. const current = await loadCredentialPair(input.credentialStore, input.keyPrefix);
  79. if (current?.tokens && current.generation !== observedGeneration) {
  80. return current.tokens.access_token;
  81. }
  82. throw createTemporaryRefreshFailureError({ cause: error, serverName: input.serverName });
  83. }
  84. }
  85. async function refreshLocked(
  86. input: RefreshMcpOAuthTokensInput,
  87. observedGeneration: string | undefined,
  88. ): Promise<string> {
  89. const current = await loadCredentialPair(input.credentialStore, input.keyPrefix);
  90. // 合并:等锁期间别人已经刷新过就直接复用,零二次请求。这是 rotation reuse-detection 的关键。
  91. if (current?.tokens && current.generation !== observedGeneration) {
  92. return current.tokens.access_token;
  93. }
  94. if (!current?.tokens) {
  95. // generation 变了但 winner 没留下 token(例如它收到 invalid_grant):不能当成「没有凭据」
  96. // 静默返回,必须转入交互授权。
  97. throw createInteractiveAuthorizationRequiredError({
  98. reason: "no_credentials",
  99. serverName: input.serverName,
  100. });
  101. }
  102. const refreshToken = current.tokens.refresh_token;
  103. const clientInformation = current.clientInformation;
  104. if (!refreshToken || !clientInformation) {
  105. throw createInteractiveAuthorizationRequiredError({
  106. reason: "no_refresh_token",
  107. serverName: input.serverName,
  108. });
  109. }
  110. let resolved: ResolvedAsMetadata;
  111. try {
  112. resolved = await resolveAsMetadata(input, current);
  113. } catch (error) {
  114. // discovery 失败绝不能当作 grant 失效。
  115. return failSoft(input, current, error);
  116. }
  117. try {
  118. const next = await refreshAuthorization(resolved.authorizationServerUrl, {
  119. clientInformation,
  120. refreshToken,
  121. ...(resolved.metadata ? { metadata: resolved.metadata } : {}),
  122. ...(resolved.resource ? { resource: resolved.resource } : {}),
  123. ...(input.fetchFn ? { fetchFn: input.fetchFn } : {}),
  124. });
  125. const published = await publishCanonicalCredentials(input.credentialStore, input.keyPrefix, {
  126. clientInformation,
  127. ...(current.issuer ? { issuer: current.issuer } : {}),
  128. publishedBy: `refresh:${input.keyPrefix}`,
  129. tokens: next,
  130. });
  131. input.logger?.info("MCP OAuth access token refreshed", {
  132. event: "mcp.oauth.refresh.completed",
  133. credentialKeyPrefix: input.keyPrefix,
  134. mcpServerName: input.serverName,
  135. processId: process.pid,
  136. publishedGeneration: published.generation.slice(0, 12),
  137. reactive: input.reactive,
  138. refreshTokenRotated: next.refresh_token !== refreshToken,
  139. status: "completed",
  140. });
  141. return next.access_token;
  142. } catch (error) {
  143. return await handleRefreshFailure(input, current, error);
  144. }
  145. }
  146. async function handleRefreshFailure(
  147. input: RefreshMcpOAuthTokensInput,
  148. current: CredentialPairSnapshot,
  149. error: unknown,
  150. ): Promise<never | string> {
  151. const oauthErrorCode = error instanceof OAuthError ? error.code : undefined;
  152. input.logger?.warn("MCP OAuth access token refresh failed", {
  153. event: "mcp.oauth.refresh.failed",
  154. credentialKeyPrefix: input.keyPrefix,
  155. credentialSource: current.source,
  156. mcpServerName: input.serverName,
  157. oauthErrorCode,
  158. processId: process.pid,
  159. reactive: input.reactive,
  160. status: "failed",
  161. });
  162. if (oauthErrorCode === OAuthErrorCode.InvalidGrant) {
  163. // 确定性失效:refresh token 已被撤销或过期。CAS 清 tokens、保留 client 作为重新授权种子。
  164. if (current.raw) {
  165. await invalidateCanonicalCredentials(
  166. input.credentialStore,
  167. input.keyPrefix,
  168. current.raw,
  169. "tokens",
  170. );
  171. }
  172. throw createInteractiveAuthorizationRequiredError({
  173. cause: error,
  174. reason: "invalid_grant",
  175. serverName: input.serverName,
  176. });
  177. }
  178. if (
  179. oauthErrorCode === OAuthErrorCode.InvalidClient ||
  180. oauthErrorCode === OAuthErrorCode.UnauthorizedClient
  181. ) {
  182. if (input.staticClientId) {
  183. // 静态配置 client 的 invalid_client 无法靠交互授权自愈:Phase 2 仍会使用同一个 client,
  184. // 转授权只会形成循环。按配置错误上报。
  185. throw new Error(
  186. `MCP server ${input.serverName} OAuth client was rejected by the authorization server (invalid_client). ` +
  187. `The configured clientId is not usable; fix the MCP oauth configuration.`,
  188. { cause: error },
  189. );
  190. }
  191. if (current.raw) {
  192. await invalidateCanonicalCredentials(
  193. input.credentialStore,
  194. input.keyPrefix,
  195. current.raw,
  196. "all",
  197. );
  198. }
  199. throw createInteractiveAuthorizationRequiredError({
  200. cause: error,
  201. reason: "invalid_client",
  202. serverName: input.serverName,
  203. });
  204. }
  205. return failSoft(input, current, error);
  206. }
  207. /**
  208. * 非确定性失败(网络、5xx、`server_error`)。
  209. *
  210. * proactive 返回现值:token 还没被拒绝,让请求继续走,401 路径保留最终裁决权。
  211. * reactive 必须抛临时错误:现值刚被拒绝,返回它一定再 401。
  212. */
  213. function failSoft(
  214. input: RefreshMcpOAuthTokensInput,
  215. current: CredentialPairSnapshot,
  216. error: unknown,
  217. ): string {
  218. if (input.reactive || !current.tokens) {
  219. throw createTemporaryRefreshFailureError({ cause: error, serverName: input.serverName });
  220. }
  221. return current.tokens.access_token;
  222. }
  223. /**
  224. * 解析授权服务器元数据与经校验的 resource。
  225. *
  226. * discovery 记录带 TTL 且与 Phase 2 共用;`resource` 必须求出并带进 refresh 请求(RFC 8707),
  227. * SDK 自己的 refresh 会传它,我们绕开 `auth()` 后必须自己补上,否则受众绑定丢失。
  228. */
  229. export async function resolveAsMetadata(
  230. input: Pick<
  231. RefreshMcpOAuthTokensInput,
  232. "credentialStore" | "fetchFn" | "keyPrefix" | "serverUrl"
  233. >,
  234. current: Pick<CredentialPairSnapshot, "issuer">,
  235. ): Promise<ResolvedAsMetadata> {
  236. const cached = await loadDiscoveryRecord(input.credentialStore, input.keyPrefix, {
  237. ...(current.issuer ? { expectedIssuer: current.issuer } : {}),
  238. });
  239. const discovered: OAuthDiscoveryState =
  240. cached ??
  241. (await discoverOAuthServerInfo(input.serverUrl, {
  242. ...(input.fetchFn ? { fetchFn: input.fetchFn } : {}),
  243. }));
  244. if (!cached) {
  245. await saveDiscoveryRecord(input.credentialStore, input.keyPrefix, discovered);
  246. }
  247. const resource = await selectResourceURL(
  248. input.serverUrl,
  249. // selectResourceURL 只读 provider 的 validateResourceURL;这里没有 provider,传一个空壳即可。
  250. {} as never,
  251. discovered.resourceMetadata,
  252. );
  253. return {
  254. authorizationServerUrl: discovered.authorizationServerUrl,
  255. ...(discovered.authorizationServerMetadata
  256. ? { metadata: discovered.authorizationServerMetadata }
  257. : {}),
  258. ...(resource ? { resource } : {}),
  259. };
  260. }
  261. /**
  262. * refresh 锁文件路径。
  263. *
  264. * 必须独立于 credentials 文件:锁内会调用 `publishCanonicalCredentials`,后者自己对
  265. * credentials.json 加锁;同一路径会自重入死锁。basename 只含 hash 与连字符(Windows 文件名
  266. * 不允许冒号)。
  267. */
  268. export function resolveRefreshLockPath(credentialsFilePath: string, keyPrefix: string): string {
  269. return join(dirname(credentialsFilePath), `${sanitizeKeyPrefix(keyPrefix)}.refresh`);
  270. }