oauth-interactive.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. import { createHash, randomBytes } from "node:crypto";
  2. import {
  3. auth,
  4. type FetchLike,
  5. type OAuthClientInformationMixed,
  6. type OAuthClientMetadata,
  7. type OAuthClientProvider,
  8. type OAuthDiscoveryState,
  9. type OAuthTokens,
  10. } from "@modelcontextprotocol/client";
  11. import type { Logger, McpOAuthConfig } from "@zcode/contracts";
  12. import {
  13. createLocalhostOAuthCallbackServer,
  14. type LocalhostOAuthCallbackServer,
  15. } from "../auth/localhost-callback.js";
  16. import type { SharedZCodeCredentialStore } from "../auth/shared-credentials.js";
  17. import {
  18. loadCanonicalCredentials,
  19. publishCanonicalCredentials,
  20. type CanonicalCredentialSnapshot,
  21. } from "./oauth-credentials.js";
  22. import {
  23. deletePendingAuthorizationIfOwned,
  24. loadPendingAuthorization,
  25. publishPendingAuthorization,
  26. tryAcquireAuthorizationLease,
  27. } from "./oauth-lease.js";
  28. import {
  29. loadDiscoveryRecord,
  30. saveDiscoveryRecord,
  31. type McpOAuthAuthorizationContext,
  32. } from "./oauth-shared.js";
  33. import { withTimeout } from "./timeout.js";
  34. type McpAuthorizationCodeOAuthConfig = Extract<McpOAuthConfig, { type: "authorization_code" }>;
  35. /** 授权事务的全局寿命。与 caller 等待预算(session 15s)无关,由 caller 侧独立收口。 */
  36. export const MCP_OAUTH_AUTHORIZATION_TRANSACTION_TTL_MS = 5 * 60 * 1000;
  37. const FOLLOWER_POLL_INTERVAL_MS = 500;
  38. export type McpInteractiveAuthorizationOutcome =
  39. /** 本次调用完成了授权,凭据已发布。 */
  40. | { status: "authorized" }
  41. /** 另一个事务已完成授权(generation 已换代),直接回 Phase 1 重连即可。 */
  42. | { status: "already-authorized" }
  43. /** 事务仍在进行(本调用是 follower 或已达事务 TTL),授权 URL 可供展示。 */
  44. | { status: "pending"; authorizationUrl?: string }
  45. | { status: "failed"; error: unknown };
  46. export interface McpInteractiveAuthorizationInput {
  47. adapterInstanceId?: string;
  48. config: McpAuthorizationCodeOAuthConfig;
  49. credentialStore: SharedZCodeCredentialStore;
  50. fetchFn?: FetchLike;
  51. /** 403 step-up:unionScope 是 requiredScope 的严格超集时,refresh 无法扩权,必须强制重新授权。 */
  52. forceReauthorization?: boolean;
  53. keyPrefix: string;
  54. logger?: Logger;
  55. onAuthorizationRequired?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  56. openAuthorizationUrl?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  57. /** 编排层算好的最终 scope(config scope ∪ token.scope ∪ challenge scope)。 */
  58. requestedScope?: string;
  59. resourceMetadataUrl?: URL;
  60. serverName: string;
  61. serverUrl: string;
  62. signal?: AbortSignal;
  63. transactionTtlMs?: number;
  64. }
  65. /**
  66. * Phase 2:交互授权事务。
  67. *
  68. * 不创建任何 MCP transport。直接用 SDK 导出的 `auth()` 驱动 discovery → DCR → authorize →
  69. * code exchange,因此不存在「Phase 2 transport 必须销毁」的隐患:授权成功后调用方直接用
  70. * Phase 1 的纯 AuthProvider 重新建连即可。
  71. */
  72. export async function runMcpInteractiveAuthorization(
  73. input: McpInteractiveAuthorizationInput,
  74. ): Promise<McpInteractiveAuthorizationOutcome> {
  75. const transactionTtlMs = input.transactionTtlMs ?? MCP_OAUTH_AUTHORIZATION_TRANSACTION_TTL_MS;
  76. const baseline = await loadCanonicalCredentials(input.credentialStore, input.keyPrefix);
  77. const baselineGeneration = baseline?.generation;
  78. const lease = await tryAcquireAuthorizationLease({
  79. credentialsFilePath: input.credentialStore.filePath,
  80. keyPrefix: input.keyPrefix,
  81. });
  82. if (!lease) {
  83. return await followAuthorization(input, baselineGeneration, transactionTtlMs);
  84. }
  85. try {
  86. // 锁内重读:等待 lease 期间别人可能已经完成授权。
  87. const current = await loadCanonicalCredentials(input.credentialStore, input.keyPrefix);
  88. if (hasNewerCredentials(current, baselineGeneration)) {
  89. return { status: "already-authorized" };
  90. }
  91. return await leadAuthorization(input, {
  92. attemptId: lease.attemptId,
  93. baselineGeneration,
  94. transactionTtlMs,
  95. });
  96. } finally {
  97. await deletePendingAuthorizationIfOwned(
  98. input.credentialStore,
  99. input.keyPrefix,
  100. lease.attemptId,
  101. ).catch(() => undefined);
  102. await lease.release();
  103. }
  104. }
  105. async function leadAuthorization(
  106. input: McpInteractiveAuthorizationInput,
  107. context: {
  108. attemptId: string;
  109. baselineGeneration?: string;
  110. transactionTtlMs: number;
  111. },
  112. ): Promise<McpInteractiveAuthorizationOutcome> {
  113. const state = randomBytes(24).toString("base64url");
  114. const callbackPath = normalizeCallbackPath(input.config.redirectPath, input.serverName);
  115. // 每次授权都重新 listen(0)。彻底放弃端口复用:listener 在整个连接期长期存活,复用必撞;
  116. // fresh DCR 会把当前存活 listener 的 URL 写进 redirect_uris,端口变化不再导致失配。
  117. let callbackServer: LocalhostOAuthCallbackServer;
  118. try {
  119. callbackServer = await createLocalhostOAuthCallbackServer({ callbackPath, state });
  120. } catch (error) {
  121. // EACCES/EMFILE/ENFILE/EADDRNOTAVAIL 等一律按 leader 失败处理,不特殊处理 EADDRINUSE。
  122. input.logger?.warn("MCP OAuth callback listener failed", {
  123. event: "mcp.oauth.callback_listener.failed",
  124. ...logContext(input, state),
  125. error: error instanceof Error ? error.message : String(error),
  126. status: "failed",
  127. });
  128. return { status: "failed", error };
  129. }
  130. const provider = new InteractiveAuthorizationProvider({
  131. attemptId: context.attemptId,
  132. baselineGeneration: context.baselineGeneration,
  133. callbackServer,
  134. config: input.config,
  135. credentialStore: input.credentialStore,
  136. keyPrefix: input.keyPrefix,
  137. logger: input.logger,
  138. onAuthorizationRequired: input.onAuthorizationRequired,
  139. openAuthorizationUrl: input.openAuthorizationUrl,
  140. requestedScope: input.requestedScope,
  141. serverName: input.serverName,
  142. state,
  143. transactionTtlMs: context.transactionTtlMs,
  144. });
  145. try {
  146. const redirected = await auth(provider, {
  147. serverUrl: input.serverUrl,
  148. ...(input.requestedScope ? { scope: input.requestedScope } : {}),
  149. ...(input.resourceMetadataUrl ? { resourceMetadataUrl: input.resourceMetadataUrl } : {}),
  150. ...(input.fetchFn ? { fetchFn: input.fetchFn } : {}),
  151. ...(input.forceReauthorization ? { forceReauthorization: true } : {}),
  152. });
  153. if (redirected === "AUTHORIZED") {
  154. // 静态配置 client 且服务器直接放行时可能不经过浏览器。
  155. return { status: "authorized" };
  156. }
  157. // 只有「等人点授权」这一段有超时。code exchange 一律等到 settle,不与超时竞速:
  158. // 否则可能在 token response 已返回、saveTokens 仍在进行时放锁,fencing 就漏了。
  159. const callback = await withTimeout(
  160. callbackServer.waitForCallback(),
  161. context.transactionTtlMs,
  162. `MCP server ${input.serverName} OAuth authorization timed out`,
  163. input.signal,
  164. );
  165. const callbackParams = new URL(callback.url).searchParams;
  166. const authorizationCode = callbackParams.get("code") ?? callback.code;
  167. const issuerParam = callbackParams.get("iss");
  168. await auth(provider, {
  169. serverUrl: input.serverUrl,
  170. authorizationCode,
  171. ...(issuerParam ? { iss: issuerParam } : {}),
  172. ...(input.requestedScope ? { scope: input.requestedScope } : {}),
  173. ...(input.resourceMetadataUrl ? { resourceMetadataUrl: input.resourceMetadataUrl } : {}),
  174. ...(input.fetchFn ? { fetchFn: input.fetchFn } : {}),
  175. });
  176. input.logger?.info("MCP OAuth authorization completed", {
  177. event: "mcp.oauth.authorization.completed",
  178. ...logContext(input, state),
  179. status: "completed",
  180. });
  181. return { status: "authorized" };
  182. } catch (error) {
  183. // 事务 TTL 到点时授权仍可能在浏览器里进行,但本 leader 已经放弃:把 listener 关掉,
  184. // 让下一次连接重新成为 leader,而不是留下一个不会被消费的回调端口。
  185. const published = await loadCanonicalCredentials(input.credentialStore, input.keyPrefix);
  186. if (hasNewerCredentials(published, context.baselineGeneration)) {
  187. return { status: "already-authorized" };
  188. }
  189. input.logger?.warn("MCP OAuth authorization failed", {
  190. event: "mcp.oauth.authorization.failed",
  191. ...logContext(input, state),
  192. error: error instanceof Error ? error.message : String(error),
  193. status: "failed",
  194. });
  195. return { status: "failed", error };
  196. } finally {
  197. await callbackServer.close().catch(() => undefined);
  198. }
  199. }
  200. async function followAuthorization(
  201. input: McpInteractiveAuthorizationInput,
  202. baselineGeneration: string | undefined,
  203. transactionTtlMs: number,
  204. ): Promise<McpInteractiveAuthorizationOutcome> {
  205. const deadline = Date.now() + transactionTtlMs;
  206. let projectedUrl: string | undefined;
  207. input.logger?.info("MCP OAuth authorization is already in progress elsewhere", {
  208. event: "mcp.oauth.authorization.following",
  209. ...logContext(input),
  210. status: "waiting",
  211. });
  212. while (Date.now() < deadline && !input.signal?.aborted) {
  213. const current = await loadCanonicalCredentials(input.credentialStore, input.keyPrefix);
  214. if (hasNewerCredentials(current, baselineGeneration)) return { status: "already-authorized" };
  215. const pending = await loadPendingAuthorization(input.credentialStore, input.keyPrefix);
  216. if (pending && pending.authorizationUrl !== projectedUrl) {
  217. // 设置页与 session 是独立 lease,leader 的 onAuthorizationRequired 回调对 follower
  218. // 不可见;follower 必须从共享 pending 键把同一个授权 URL 投影到自己的状态。
  219. projectedUrl = pending.authorizationUrl;
  220. await input.onAuthorizationRequired?.({
  221. authorizationUrl: pending.authorizationUrl,
  222. redirectUrl: "",
  223. serverName: input.serverName,
  224. });
  225. }
  226. await sleep(FOLLOWER_POLL_INTERVAL_MS, input.signal);
  227. }
  228. return { status: "pending", ...(projectedUrl ? { authorizationUrl: projectedUrl } : {}) };
  229. }
  230. /**
  231. * Phase 2 专用 OAuthClientProvider。
  232. *
  233. * 与 Phase 1 的纯 AuthProvider 相反,这里必须是完整 `OAuthClientProvider` 才能驱动 `auth()`;
  234. * 但它只在授权事务内存活,且:
  235. * - `clientInformation()` 只认静态配置 clientId,其余一律返回 undefined,强制 fresh DCR;
  236. * - `saveClientInformation()` 只写事务内存,绝不落盘;
  237. * - `tokens()` 恒为 undefined,绝不触发 refresh(refresh 是 Phase 1 的唯一职责);
  238. * - PKCE verifier 只存内存:整个事务在同一进程、同一 lease 内完成,不存在 provider 重建。
  239. */
  240. class InteractiveAuthorizationProvider implements OAuthClientProvider {
  241. private readonly attemptId: string;
  242. private readonly baselineGeneration?: string;
  243. private readonly callbackServer: LocalhostOAuthCallbackServer;
  244. private readonly config: McpAuthorizationCodeOAuthConfig;
  245. private readonly credentialStore: SharedZCodeCredentialStore;
  246. private readonly keyPrefix: string;
  247. private readonly logger?: Logger;
  248. private readonly onAuthorizationRequired?: (
  249. context: McpOAuthAuthorizationContext,
  250. ) => Promise<void> | void;
  251. private readonly openAuthorizationUrl?: (
  252. context: McpOAuthAuthorizationContext,
  253. ) => Promise<void> | void;
  254. /** 编排层算好的最终 scope(step-up 时为并集);DCR 与 authorize 请求必须用同一个值。 */
  255. private readonly requestedScope?: string;
  256. private readonly serverName: string;
  257. private readonly stateValue: string;
  258. private readonly transactionId: string;
  259. private readonly transactionTtlMs: number;
  260. private issuer?: string;
  261. private memoryCodeVerifier?: string;
  262. private memoryDiscoveryState?: OAuthDiscoveryState;
  263. private transactionClientInformation?: OAuthClientInformationMixed;
  264. constructor(input: {
  265. attemptId: string;
  266. baselineGeneration?: string;
  267. callbackServer: LocalhostOAuthCallbackServer;
  268. config: McpAuthorizationCodeOAuthConfig;
  269. credentialStore: SharedZCodeCredentialStore;
  270. keyPrefix: string;
  271. logger?: Logger;
  272. onAuthorizationRequired?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  273. openAuthorizationUrl?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  274. requestedScope?: string;
  275. serverName: string;
  276. state: string;
  277. transactionTtlMs: number;
  278. }) {
  279. this.attemptId = input.attemptId;
  280. this.baselineGeneration = input.baselineGeneration;
  281. this.callbackServer = input.callbackServer;
  282. this.config = input.config;
  283. this.credentialStore = input.credentialStore;
  284. this.keyPrefix = input.keyPrefix;
  285. this.logger = input.logger;
  286. this.onAuthorizationRequired = input.onAuthorizationRequired;
  287. this.openAuthorizationUrl = input.openAuthorizationUrl;
  288. this.requestedScope = input.requestedScope;
  289. this.serverName = input.serverName;
  290. this.stateValue = input.state;
  291. this.transactionId = createHash("sha256").update(input.state).digest("hex");
  292. this.transactionTtlMs = input.transactionTtlMs;
  293. }
  294. get redirectUrl(): string {
  295. return this.callbackServer.callbackUrl;
  296. }
  297. get clientMetadata(): OAuthClientMetadata {
  298. return {
  299. client_name: this.config.clientName ?? `ZCode ${this.serverName}`,
  300. grant_types: ["authorization_code", "refresh_token"],
  301. redirect_uris: [this.redirectUrl],
  302. response_types: ["code"],
  303. ...(this.config.clientSecret ? { token_endpoint_auth_method: "client_secret_basic" } : {}),
  304. // DCR 注册的 scope 与 authorize 请求的 scope 必须是同一个并集结果。
  305. // 若 DCR 只写 config scope,注册的 client 与后续按并集发起的授权请求不一致,
  306. // 严格授权服务器会拒绝或静默按注册值收敛。
  307. ...((this.requestedScope ?? this.config.scope)
  308. ? { scope: this.requestedScope ?? this.config.scope }
  309. : {}),
  310. };
  311. }
  312. state(): string {
  313. return this.stateValue;
  314. }
  315. clientInformation(): OAuthClientInformationMixed | undefined {
  316. if (this.config.clientId) {
  317. return {
  318. client_id: this.config.clientId,
  319. ...(this.config.clientSecret ? { client_secret: this.config.clientSecret } : {}),
  320. };
  321. }
  322. // 过去这里优先返回持久化的 DCR client,而它的 redirect_uris 锁死在
  323. // 注册当时的随机端口。授权请求随后带「旧 client_id + 新 redirect_uri」,授权服务器按
  324. // RFC 6749 §4.1.2.1 禁止回跳、就地渲染错误页,回调永不到达且重试永不自愈。
  325. // 返回 undefined 让 SDK 用当前存活 listener 的 URL 重新注册,失配从根上消除。
  326. return this.transactionClientInformation;
  327. }
  328. saveClientInformation(clientInformation: OAuthClientInformationMixed): void {
  329. // 只写事务内存。DCR client 只有与本次授权换到的 token 组成一对才有意义;单独落盘
  330. // 也会污染其他事务的 canonical pair。
  331. this.transactionClientInformation = clientInformation;
  332. }
  333. tokens(): undefined {
  334. return undefined;
  335. }
  336. async saveTokens(tokens: OAuthTokens): Promise<void> {
  337. const clientInformation = this.clientInformation();
  338. if (!clientInformation) {
  339. throw new Error(`Missing MCP OAuth client information for ${this.serverName}`);
  340. }
  341. const published = await publishCanonicalCredentials(this.credentialStore, this.keyPrefix, {
  342. clientInformation,
  343. ...(this.issuer ? { issuer: this.issuer } : {}),
  344. publishedBy: this.transactionId,
  345. tokens,
  346. });
  347. this.logger?.info("MCP OAuth credentials published", {
  348. event: "mcp.oauth.credentials.published",
  349. ...this.logContext(),
  350. clientIdHash: hashIdentifier(clientInformation.client_id),
  351. grantKind: "authorization_code",
  352. hasRefreshToken: Boolean(tokens.refresh_token),
  353. publishedGeneration: published.generation.slice(0, 12),
  354. status: "completed",
  355. tokenExpiresInSeconds: tokens.expires_in,
  356. });
  357. }
  358. async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
  359. const context: McpOAuthAuthorizationContext = {
  360. authorizationUrl: authorizationUrl.toString(),
  361. redirectUrl: this.redirectUrl,
  362. serverName: this.serverName,
  363. };
  364. // pending 与 attempt 绑定:删除按 attempt CAS,旧 leader 的 finally 不会抹掉新 leader 的
  365. // pending。TTL 只用于展示过期判断,不承担锁所有权语义。
  366. await publishPendingAuthorization(this.credentialStore, this.keyPrefix, {
  367. attemptId: this.attemptId,
  368. authorizationUrl: context.authorizationUrl,
  369. ...(this.baselineGeneration ? { baselineGeneration: this.baselineGeneration } : {}),
  370. expiresAt: Date.now() + this.transactionTtlMs,
  371. state: this.stateValue,
  372. });
  373. this.logger?.info("MCP OAuth authorization required", {
  374. event: "mcp.oauth.authorization.required",
  375. ...this.logContext(),
  376. callbackPort: Number(new URL(this.redirectUrl).port),
  377. status: "waiting",
  378. });
  379. await this.onAuthorizationRequired?.(context);
  380. // 默认只暴露 URL,等用户在设置页点击授权;自动拉起浏览器会打断当前操作。
  381. await this.openAuthorizationUrl?.(context);
  382. }
  383. saveCodeVerifier(codeVerifier: string): void {
  384. this.memoryCodeVerifier = codeVerifier;
  385. }
  386. codeVerifier(): string {
  387. if (!this.memoryCodeVerifier) {
  388. throw new Error(`Missing MCP OAuth PKCE verifier for ${this.serverName}`);
  389. }
  390. return this.memoryCodeVerifier;
  391. }
  392. saveAuthorizationServerUrl(authorizationServerUrl: string): void {
  393. this.issuer = authorizationServerUrl;
  394. }
  395. authorizationServerUrl(): string | undefined {
  396. return this.issuer;
  397. }
  398. async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {
  399. // 事务内也留一份内存副本:code exchange 那一腿需要能读回 authorize 腿记录的
  400. // issuer,否则 SDK 抛 AuthorizationServerMismatchError。共享记录可能被别的进程改写或过期,
  401. // 内存副本保证同一事务内的 issuer 绑定稳定。
  402. this.memoryDiscoveryState = state;
  403. await saveDiscoveryRecord(this.credentialStore, this.keyPrefix, state);
  404. }
  405. async discoveryState(): Promise<OAuthDiscoveryState | undefined> {
  406. if (this.memoryDiscoveryState) return this.memoryDiscoveryState;
  407. return await loadDiscoveryRecord(this.credentialStore, this.keyPrefix);
  408. }
  409. private logContext(): Record<string, unknown> {
  410. return {
  411. credentialKeyPrefix: this.keyPrefix,
  412. mcpServerName: this.serverName,
  413. oauthAttemptId: this.attemptId.slice(0, 12),
  414. oauthStateId: this.transactionId.slice(0, 16),
  415. processId: process.pid,
  416. };
  417. }
  418. }
  419. function hasNewerCredentials(
  420. current: CanonicalCredentialSnapshot | undefined,
  421. baselineGeneration: string | undefined,
  422. ): boolean {
  423. return Boolean(current?.tokens && current.generation !== baselineGeneration);
  424. }
  425. function normalizeCallbackPath(value: string | undefined, serverName: string): string {
  426. const fallback = `/oauth/callback/mcp/${encodeURIComponent(serverName)}`;
  427. if (!value) return fallback;
  428. return value.startsWith("/") ? value : `/${value}`;
  429. }
  430. function logContext(
  431. input: McpInteractiveAuthorizationInput,
  432. state?: string,
  433. ): Record<string, unknown> {
  434. return {
  435. adapterInstanceId: input.adapterInstanceId,
  436. credentialKeyPrefix: input.keyPrefix,
  437. mcpServerName: input.serverName,
  438. ...(state
  439. ? { oauthStateId: createHash("sha256").update(state).digest("hex").slice(0, 16) }
  440. : {}),
  441. processId: process.pid,
  442. };
  443. }
  444. function hashIdentifier(value: string | undefined): string | undefined {
  445. if (!value) return undefined;
  446. return createHash("sha256").update(value).digest("hex").slice(0, 12);
  447. }
  448. function sleep(durationMs: number, signal?: AbortSignal): Promise<void> {
  449. return new Promise((resolve) => {
  450. const timer = setTimeout(() => {
  451. signal?.removeEventListener("abort", onAbort);
  452. resolve();
  453. }, durationMs);
  454. const onAbort = () => {
  455. clearTimeout(timer);
  456. resolve();
  457. };
  458. signal?.addEventListener("abort", onAbort, { once: true });
  459. });
  460. }