oauth.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. import { createHash, randomBytes } from "node:crypto";
  2. import type {
  3. OAuthClientInformationMixed,
  4. OAuthClientMetadata,
  5. OAuthClientProvider,
  6. OAuthDiscoveryState,
  7. OAuthTokens,
  8. } from "@modelcontextprotocol/client";
  9. import type { Logger, McpOAuthConfig } from "@zcode/contracts";
  10. import {
  11. createLocalhostOAuthCallbackServer,
  12. type LocalhostOAuthCallbackServer,
  13. } from "../auth/localhost-callback.js";
  14. import {
  15. createSharedZCodeCredentialStore,
  16. type SharedZCodeCredentialStore,
  17. } from "../auth/shared-credentials.js";
  18. import {
  19. deriveCredentialPair,
  20. isCanonicalCredentials,
  21. isRecord,
  22. MCP_OAUTH_CANONICAL_CREDENTIALS_KEY,
  23. MCP_OAUTH_SUPPORTED_CREDENTIAL_VERSIONS,
  24. publishCanonicalCredentials,
  25. type McpOAuthCanonicalCredentials,
  26. } from "./oauth-credentials.js";
  27. import { createInteractiveAuthorizationRequiredError } from "./oauth-errors.js";
  28. import {
  29. loadDiscoveryRecord,
  30. saveDiscoveryRecord,
  31. type McpOAuthAuthorizationContext,
  32. } from "./oauth-shared.js";
  33. const DEFAULT_MCP_OAUTH_CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
  34. interface CredentialSnapshot<T> {
  35. raw: string;
  36. value: T;
  37. }
  38. interface StoredCredentialPair {
  39. clientInformation?: OAuthClientInformationMixed;
  40. source: "canonical" | "legacy";
  41. tokens?: OAuthTokens;
  42. }
  43. type TransactionClientSource = "canonical" | "legacy" | "registered";
  44. type McpAuthorizationCodeOAuthConfig = Extract<McpOAuthConfig, { type: "authorization_code" }>;
  45. export type { McpOAuthAuthorizationContext };
  46. export interface McpOAuthRuntimeOptions {
  47. authorizationTimeoutMs?: number;
  48. credentialStore?: SharedZCodeCredentialStore;
  49. onAuthorizationRequired?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  50. openAuthorizationUrl?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  51. }
  52. export interface McpOAuthSession {
  53. close(): Promise<void>;
  54. readonly provider: OAuthClientProvider;
  55. readonly timeoutMs: number;
  56. hasPendingAuthorization(): boolean;
  57. waitForAuthorizationCallback(): Promise<URLSearchParams>;
  58. }
  59. export async function createMcpAuthorizationCodeOAuthSession(input: {
  60. adapterInstanceId?: string;
  61. config: McpAuthorizationCodeOAuthConfig;
  62. logger?: Logger;
  63. options?: McpOAuthRuntimeOptions;
  64. serverName: string;
  65. serverUrl: string;
  66. }): Promise<McpOAuthSession> {
  67. const state = randomBytes(24).toString("base64url");
  68. const callbackPath = normalizeCallbackPath(input.config.redirectPath, input.serverName);
  69. const callbackServer = await createLocalhostOAuthCallbackServer({
  70. callbackPath,
  71. state,
  72. });
  73. const credentialStore = input.options?.credentialStore ?? createSharedZCodeCredentialStore();
  74. const keyPrefix = createCredentialKeyPrefix(input.serverName, input.serverUrl, input.config);
  75. const provider = new ZCodeMcpAuthorizationCodeProvider({
  76. adapterInstanceId: input.adapterInstanceId,
  77. callbackServer,
  78. config: input.config,
  79. credentialStore,
  80. keyPrefix,
  81. logger: input.logger,
  82. onAuthorizationRequired: input.options?.onAuthorizationRequired,
  83. openAuthorizationUrl: input.options?.openAuthorizationUrl,
  84. serverName: input.serverName,
  85. state,
  86. });
  87. return {
  88. close: async () => {
  89. await callbackServer.close();
  90. await provider.close();
  91. },
  92. provider,
  93. timeoutMs: input.options?.authorizationTimeoutMs ?? DEFAULT_MCP_OAUTH_CALLBACK_TIMEOUT_MS,
  94. hasPendingAuthorization: () => provider.hasPendingAuthorization(),
  95. waitForAuthorizationCallback: async () => {
  96. const callback = await callbackServer.waitForCallback();
  97. return new URL(callback.url).searchParams;
  98. },
  99. };
  100. }
  101. class ZCodeMcpAuthorizationCodeProvider implements OAuthClientProvider {
  102. private readonly adapterInstanceId?: string;
  103. private readonly callbackServer: LocalhostOAuthCallbackServer;
  104. private readonly config: McpAuthorizationCodeOAuthConfig;
  105. private readonly credentialStore: SharedZCodeCredentialStore;
  106. private readonly keyPrefix: string;
  107. private readonly logger?: Logger;
  108. private readonly onAuthorizationRequired?: (
  109. context: McpOAuthAuthorizationContext,
  110. ) => Promise<void> | void;
  111. private readonly openAuthorizationUrl?: (
  112. context: McpOAuthAuthorizationContext,
  113. ) => Promise<void> | void;
  114. private readonly serverName: string;
  115. private readonly stateValue: string;
  116. private readonly transactionId: string;
  117. private canonicalSnapshot?: CredentialSnapshot<McpOAuthCanonicalCredentials>;
  118. private credentialSnapshotsLoaded = false;
  119. private legacyClientSnapshot?: CredentialSnapshot<OAuthClientInformationMixed>;
  120. private legacyTokensSnapshot?: CredentialSnapshot<OAuthTokens>;
  121. private storedCredentialPair?: StoredCredentialPair;
  122. private storedCredentialPairLoaded = false;
  123. private pendingAuthorization = false;
  124. private transactionClientInformation?: OAuthClientInformationMixed;
  125. private transactionClientSource?: TransactionClientSource;
  126. private verifierPersisted = false;
  127. constructor(input: {
  128. adapterInstanceId?: string;
  129. callbackServer: LocalhostOAuthCallbackServer;
  130. config: McpAuthorizationCodeOAuthConfig;
  131. credentialStore: SharedZCodeCredentialStore;
  132. keyPrefix: string;
  133. logger?: Logger;
  134. onAuthorizationRequired?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  135. openAuthorizationUrl?: (context: McpOAuthAuthorizationContext) => Promise<void> | void;
  136. serverName: string;
  137. state: string;
  138. }) {
  139. this.adapterInstanceId = input.adapterInstanceId;
  140. this.callbackServer = input.callbackServer;
  141. this.config = input.config;
  142. this.credentialStore = input.credentialStore;
  143. this.keyPrefix = input.keyPrefix;
  144. this.logger = input.logger;
  145. this.onAuthorizationRequired = input.onAuthorizationRequired;
  146. this.openAuthorizationUrl = input.openAuthorizationUrl;
  147. this.serverName = input.serverName;
  148. this.stateValue = input.state;
  149. this.transactionId = createHash("sha256").update(input.state).digest("hex");
  150. }
  151. get redirectUrl(): string {
  152. return this.callbackServer.callbackUrl;
  153. }
  154. get clientMetadata(): OAuthClientMetadata {
  155. return {
  156. client_name: this.config.clientName ?? `ZCode ${this.serverName}`,
  157. grant_types: ["authorization_code", "refresh_token"],
  158. redirect_uris: [this.redirectUrl],
  159. response_types: ["code"],
  160. ...(this.config.clientSecret ? { token_endpoint_auth_method: "client_secret_basic" } : {}),
  161. ...(this.config.scope ? { scope: this.config.scope } : {}),
  162. };
  163. }
  164. state(): string {
  165. return this.stateValue;
  166. }
  167. async clientInformation(): Promise<OAuthClientInformationMixed | undefined> {
  168. if (this.config.clientId) {
  169. return {
  170. client_id: this.config.clientId,
  171. ...(this.config.clientSecret ? { client_secret: this.config.clientSecret } : {}),
  172. };
  173. }
  174. if (this.transactionClientInformation) {
  175. return this.transactionClientInformation;
  176. }
  177. const storedPair = await this.loadStoredCredentialPair();
  178. if (storedPair?.clientInformation) {
  179. this.transactionClientInformation = storedPair.clientInformation;
  180. this.transactionClientSource = storedPair.source;
  181. return this.transactionClientInformation;
  182. }
  183. // 修复原因(根因 2 的过渡 seam):返回 undefined 会让 SDK 立刻做一次动态注册,而 DCR 的
  184. // 归属已经整体移交 Phase 2。没有 client 也就没有 refresh token,本来就只能交互授权,
  185. // 因此这里直接抛 interactiveRequired,避免在授权服务器上留下一个永不会被使用的注册。
  186. throw createInteractiveAuthorizationRequiredError({
  187. reason: "no_credentials",
  188. serverName: this.serverName,
  189. });
  190. }
  191. async saveClientInformation(clientInformation: OAuthClientInformationMixed): Promise<void> {
  192. // 修复原因:MCP SDK 在 authorization code exchange 时会再次读取 provider。
  193. // 动态注册结果必须固定在当前 state 对应的 provider 实例;同时先写入 legacy client
  194. // 作为 provider 重建后的恢复种子。当前事务后续只读内存值,不会被并发注册覆盖。
  195. await this.credentialStore.save(
  196. this.key("client_information"),
  197. JSON.stringify(clientInformation),
  198. );
  199. this.transactionClientInformation = clientInformation;
  200. this.transactionClientSource = "registered";
  201. }
  202. async tokens(): Promise<OAuthTokens | undefined> {
  203. return (await this.loadStoredCredentialPair())?.tokens;
  204. }
  205. async saveTokens(tokens: OAuthTokens): Promise<void> {
  206. const clientInformation = await this.clientInformation();
  207. if (!clientInformation) {
  208. throw new Error(`Missing MCP OAuth client information for ${this.serverName}`);
  209. }
  210. const previousTokens = this.storedCredentialPair?.tokens;
  211. // 通过共享 helper 发布,确保 Phase 2 与本 provider 写出的 canonical 形态完全一致
  212. // (含每次 publication 唯一的 generation)。client 与 refresh token 必须来自同一次授权,
  213. // 三个 key 仍在同一个跨进程 read-modify-write 临界区内原子写入。
  214. const published = await publishCanonicalCredentials(this.credentialStore, this.keyPrefix, {
  215. clientInformation,
  216. publishedBy: this.transactionId,
  217. tokens,
  218. });
  219. this.canonicalSnapshot = { raw: published.raw, value: published.canonical };
  220. this.legacyClientSnapshot = { raw: published.legacyClientRaw, value: clientInformation };
  221. this.legacyTokensSnapshot = { raw: published.legacyTokensRaw, value: tokens };
  222. this.credentialSnapshotsLoaded = true;
  223. this.storedCredentialPair = {
  224. clientInformation,
  225. source: "legacy",
  226. tokens,
  227. };
  228. this.storedCredentialPairLoaded = true;
  229. this.transactionClientSource = "canonical";
  230. // 修复原因:授权与刷新过去都没有成功侧事件,日志里只能看到 authorization.required,
  231. // 无法判断一次 refresh 到底成功过没有。只记录安全标识与形态,不记录任何 token 明文。
  232. this.logger?.info("MCP OAuth credentials published", {
  233. event: "mcp.oauth.credentials.published",
  234. ...this.logContext(),
  235. clientIdHash: hashIdentifier(clientInformation.client_id),
  236. grantKind: previousTokens ? "refresh" : "authorization_code",
  237. hasRefreshToken: Boolean(tokens.refresh_token),
  238. publishedGeneration: published.generation.slice(0, 12),
  239. refreshTokenRotated: Boolean(
  240. previousTokens?.refresh_token &&
  241. tokens.refresh_token &&
  242. previousTokens.refresh_token !== tokens.refresh_token,
  243. ),
  244. status: "completed",
  245. tokenExpiresInSeconds: tokens.expires_in,
  246. });
  247. }
  248. async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
  249. this.pendingAuthorization = true;
  250. // 修复原因(根因 2 的过渡 seam):本 provider 复用持久化的 DCR client,而它的 redirect_uris
  251. // 锁死在注册当时的随机端口,`authorizationUrl` 因此可能带「旧 client_id + 新 redirect_uri」。
  252. // 授权服务器按 RFC 6749 §4.1.2.1 禁止回跳、就地渲染错误页,回调永不到达且重试永不自愈。
  253. // 所以这里不再投影该 URL、也不打开浏览器,而是抛出 interactiveRequired,由 adapter 编排层
  254. // 转入 Phase 2 的 fresh DCR 授权事务(见 docs/mcp-oauth-two-phase.md §4.7)。
  255. this.logger?.warn("MCP OAuth authorization handed off to interactive transaction", {
  256. event: "mcp.oauth.authorization.handoff",
  257. ...this.logContext(),
  258. callbackPort: Number(new URL(this.redirectUrl).port),
  259. status: "cancelled",
  260. });
  261. void authorizationUrl;
  262. throw createInteractiveAuthorizationRequiredError({
  263. reason: "legacy_provider_seam",
  264. serverName: this.serverName,
  265. });
  266. }
  267. async saveCodeVerifier(codeVerifier: string): Promise<void> {
  268. await this.credentialStore.save(this.verifierKey(), codeVerifier);
  269. this.verifierPersisted = true;
  270. }
  271. async codeVerifier(): Promise<string> {
  272. const codeVerifier = await this.credentialStore.load(this.verifierKey());
  273. if (!codeVerifier) {
  274. throw new Error(`Missing MCP OAuth PKCE verifier for ${this.serverName}`);
  275. }
  276. this.verifierPersisted = true;
  277. return codeVerifier;
  278. }
  279. async saveDiscoveryState(state: OAuthDiscoveryState): Promise<void> {
  280. // 与 Phase 2 共用同一份带时间戳的 discovery 记录:否则一侧刷新了 AS metadata,另一侧
  281. // 仍可能使用无 TTL 的旧缓存。
  282. await saveDiscoveryRecord(this.credentialStore, this.keyPrefix, state);
  283. }
  284. async discoveryState(): Promise<OAuthDiscoveryState | undefined> {
  285. return await loadDiscoveryRecord(this.credentialStore, this.keyPrefix);
  286. }
  287. async invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery") {
  288. // 修复原因:过去 refresh 失败只在 SDK 内部分类,ZCode 侧不留任何痕迹,事后无法区分
  289. // token 过期、被撤销、client mismatch 和服务端临时错误(见 docs/analysis 的可观测性缺口)。
  290. // SDK 不把 OAuth error code 传给 provider,但 invalidation scope 与之一一对应:
  291. // tokens ← invalid_grant;client/all ← invalid_client / unauthorized_client。
  292. this.logger?.warn("MCP OAuth credentials invalidated", {
  293. event: "mcp.oauth.credentials.invalidated",
  294. ...this.logContext(),
  295. invalidationScope: scope,
  296. status: "failed",
  297. });
  298. if (scope === "all" || scope === "client" || scope === "tokens") {
  299. await this.invalidateCredentialSnapshot(scope);
  300. }
  301. if (scope === "all" || scope === "verifier") {
  302. await this.clearVerifier();
  303. }
  304. if (scope === "all" || scope === "discovery") {
  305. await this.credentialStore.delete(this.key("discovery_state"));
  306. }
  307. }
  308. hasPendingAuthorization(): boolean {
  309. return this.pendingAuthorization;
  310. }
  311. async close(): Promise<void> {
  312. // 修复原因:PKCE verifier 只属于当前 state。adapter 超时或关闭时必须清理本事务,
  313. // 不能再删除相同 MCP 配置下另一个并发授权正在等待的 verifier。清理属于 best-effort:
  314. // token exchange 已成功时,锁超时或损坏文件不能把主链路反转成连接失败。
  315. try {
  316. await this.clearVerifier();
  317. } catch (error) {
  318. this.logger?.warn("MCP OAuth verifier cleanup failed", {
  319. event: "mcp.oauth.verifier.cleanup_failed",
  320. adapterInstanceId: this.adapterInstanceId,
  321. error: error instanceof Error ? error.message : String(error),
  322. mcpServerName: this.serverName,
  323. oauthStateId: this.transactionId.slice(0, 16),
  324. processId: process.pid,
  325. status: "failed",
  326. });
  327. }
  328. this.transactionClientInformation = undefined;
  329. this.transactionClientSource = undefined;
  330. this.resetCredentialSnapshots();
  331. }
  332. private async invalidateCredentialSnapshot(scope: "all" | "client" | "tokens"): Promise<void> {
  333. await this.loadCredentialSnapshots();
  334. const canonicalSnapshot = this.canonicalSnapshot;
  335. const expectedValues: Record<string, string> = {};
  336. if (canonicalSnapshot) {
  337. expectedValues[this.key(MCP_OAUTH_CANONICAL_CREDENTIALS_KEY)] = canonicalSnapshot.raw;
  338. }
  339. if ((scope === "all" || scope === "client") && this.legacyClientSnapshot) {
  340. expectedValues[this.key("client_information")] = this.legacyClientSnapshot.raw;
  341. }
  342. if (
  343. (scope === "all" || scope === "client" || scope === "tokens") &&
  344. this.legacyTokensSnapshot
  345. ) {
  346. expectedValues[this.key("tokens")] = this.legacyTokensSnapshot.raw;
  347. }
  348. const deleted = await this.credentialStore.deleteIfValues(expectedValues);
  349. const canonicalDeleted = canonicalSnapshot
  350. ? deleted[this.key(MCP_OAUTH_CANONICAL_CREDENTIALS_KEY)]
  351. : undefined;
  352. this.logger?.warn("MCP OAuth credential snapshot invalidation resolved", {
  353. event: "mcp.oauth.credentials.invalidate_snapshot",
  354. ...this.logContext(),
  355. canonicalDeleted,
  356. // canonicalDeleted=false 表示 compare-and-delete 失败:另一个事务已发布新 pair,
  357. // 本次失效必须保留 winner。这是并发收口的正常结果,不是错误。
  358. hadCanonicalSnapshot: Boolean(canonicalSnapshot),
  359. invalidationScope: scope,
  360. legacyClientDeleted: deleted[this.key("client_information")],
  361. legacyTokensDeleted: deleted[this.key("tokens")],
  362. status: canonicalDeleted === false ? "cancelled" : "completed",
  363. });
  364. if (scope === "all" || scope === "client") {
  365. this.transactionClientInformation = undefined;
  366. this.transactionClientSource = undefined;
  367. } else if (
  368. this.transactionClientSource === "canonical" ||
  369. (canonicalSnapshot && this.transactionClientSource === "legacy")
  370. ) {
  371. if (canonicalDeleted === false) {
  372. // 修复原因:当前快照已被其他进程替换时,失败方不能删除新 pair;清空本地缓存,
  373. // 让 SDK 的同一次重试重新读取获胜事务发布的 client/tokens。
  374. this.transactionClientInformation = undefined;
  375. this.transactionClientSource = undefined;
  376. } else if (canonicalDeleted === true) {
  377. // token 已失效但动态 client 仍可用于当前 provider 重新授权。
  378. this.transactionClientSource = "registered";
  379. }
  380. }
  381. this.resetCredentialSnapshots();
  382. }
  383. private async loadCredentialSnapshots(): Promise<void> {
  384. if (this.credentialSnapshotsLoaded) return;
  385. const canonicalKey = this.key(MCP_OAUTH_CANONICAL_CREDENTIALS_KEY);
  386. const legacyClientKey = this.key("client_information");
  387. const legacyTokensKey = this.key("tokens");
  388. const values = await this.credentialStore.loadMany([
  389. canonicalKey,
  390. legacyClientKey,
  391. legacyTokensKey,
  392. ]);
  393. const parsedCanonicalSnapshot = await this.parseJsonSnapshot<McpOAuthCanonicalCredentials>(
  394. canonicalKey,
  395. values[canonicalKey],
  396. );
  397. let canonicalSnapshot: CredentialSnapshot<McpOAuthCanonicalCredentials> | undefined;
  398. if (
  399. parsedCanonicalSnapshot &&
  400. isRecord(parsedCanonicalSnapshot.value) &&
  401. typeof parsedCanonicalSnapshot.value.version === "number" &&
  402. !MCP_OAUTH_SUPPORTED_CREDENTIAL_VERSIONS.has(parsedCanonicalSnapshot.value.version)
  403. ) {
  404. // 修复原因:CLI 与 desktop 会独立升级但共享凭据文件。旧版本只能忽略未知版本,
  405. // 不能把新版本写入的 canonical pair 当损坏数据删除。
  406. } else if (parsedCanonicalSnapshot && !isCanonicalCredentials(parsedCanonicalSnapshot.value)) {
  407. await this.credentialStore.deleteIfValue(canonicalKey, parsedCanonicalSnapshot.raw);
  408. } else {
  409. canonicalSnapshot = parsedCanonicalSnapshot;
  410. }
  411. const legacyClientSnapshot = await this.parseJsonSnapshot<OAuthClientInformationMixed>(
  412. legacyClientKey,
  413. values[legacyClientKey],
  414. );
  415. const legacyTokensSnapshot = await this.parseJsonSnapshot<OAuthTokens>(
  416. legacyTokensKey,
  417. values[legacyTokensKey],
  418. );
  419. // 修复原因:共享凭据读取可能因锁超时或临时 I/O 失败而抛错。只有完整快照成功后
  420. // 才发布缓存和 loaded 标志,确保同一个 provider 的下一次调用仍会重试。
  421. this.canonicalSnapshot = canonicalSnapshot;
  422. this.legacyClientSnapshot = legacyClientSnapshot;
  423. this.legacyTokensSnapshot = legacyTokensSnapshot;
  424. this.credentialSnapshotsLoaded = true;
  425. }
  426. private async parseJsonSnapshot<T>(
  427. key: string,
  428. raw: string | null | undefined,
  429. ): Promise<CredentialSnapshot<T> | undefined> {
  430. if (!raw) return undefined;
  431. try {
  432. return { raw, value: JSON.parse(raw) as T };
  433. } catch {
  434. await this.credentialStore.deleteIfValue(key, raw);
  435. return undefined;
  436. }
  437. }
  438. private async loadStoredCredentialPair(): Promise<StoredCredentialPair | undefined> {
  439. if (this.storedCredentialPairLoaded) return this.storedCredentialPair;
  440. await this.loadCredentialSnapshots();
  441. // 委托给共享的纯函数:canonical 与 legacy 镜像的交错兼容规则只能有一份,两处各写一遍必然
  442. // 发散。用已经读到的快照派生,不再多读一次凭据文件;快照本身仍留在本类里,因为
  443. // compare-and-delete 需要发起方读到的原始值。
  444. const pair = deriveCredentialPair({
  445. canonicalRaw: this.canonicalSnapshot?.raw,
  446. legacyClientRaw: this.legacyClientSnapshot?.raw,
  447. legacyTokensRaw: this.legacyTokensSnapshot?.raw,
  448. });
  449. this.storedCredentialPair = pair
  450. ? {
  451. ...(pair.clientInformation ? { clientInformation: pair.clientInformation } : {}),
  452. source: pair.source,
  453. ...(pair.tokens ? { tokens: pair.tokens } : {}),
  454. }
  455. : undefined;
  456. this.storedCredentialPairLoaded = true;
  457. return this.storedCredentialPair;
  458. }
  459. private resetCredentialSnapshots(): void {
  460. this.canonicalSnapshot = undefined;
  461. this.credentialSnapshotsLoaded = false;
  462. this.legacyClientSnapshot = undefined;
  463. this.legacyTokensSnapshot = undefined;
  464. this.storedCredentialPair = undefined;
  465. this.storedCredentialPairLoaded = false;
  466. }
  467. private async loadJson<T>(name: string): Promise<T | undefined> {
  468. const raw = await this.credentialStore.load(this.key(name));
  469. if (!raw) return undefined;
  470. try {
  471. return JSON.parse(raw) as T;
  472. } catch {
  473. await this.credentialStore.deleteIfValue(this.key(name), raw);
  474. return undefined;
  475. }
  476. }
  477. private async saveJson(name: string, value: unknown): Promise<void> {
  478. await this.credentialStore.save(this.key(name), JSON.stringify(value));
  479. }
  480. private key(name: string): string {
  481. return `${this.keyPrefix}:${name}`;
  482. }
  483. /** 并发诊断日志只允许安全标识:PID、adapter id、credential key prefix、state 短哈希。 */
  484. private logContext(): Record<string, unknown> {
  485. return {
  486. adapterInstanceId: this.adapterInstanceId,
  487. credentialKeyPrefix: this.keyPrefix,
  488. mcpServerName: this.serverName,
  489. oauthStateId: this.transactionId.slice(0, 16),
  490. processId: process.pid,
  491. };
  492. }
  493. private verifierKey(): string {
  494. return this.key(`code_verifier:${this.stateValue}`);
  495. }
  496. private async clearVerifier(): Promise<void> {
  497. if (!this.verifierPersisted) return;
  498. await this.credentialStore.delete(this.verifierKey());
  499. this.verifierPersisted = false;
  500. }
  501. }
  502. /** 日志用脱敏摘要:client_id 等标识只记录哈希前缀,不记录原值。 */
  503. function hashIdentifier(value: string | undefined): string | undefined {
  504. if (!value) return undefined;
  505. return createHash("sha256").update(value).digest("hex").slice(0, 12);
  506. }
  507. function normalizeCallbackPath(value: string | undefined, serverName: string): string {
  508. const fallback = `/oauth/callback/mcp/${encodeURIComponent(serverName)}`;
  509. if (!value) return fallback;
  510. return value.startsWith("/") ? value : `/${value}`;
  511. }
  512. export function createCredentialKeyPrefix(
  513. serverName: string,
  514. serverUrl: string,
  515. config: McpAuthorizationCodeOAuthConfig,
  516. ): string {
  517. // OAuth token 和动态 client 注册都依赖授权语义,scope/client/redirect 变化时必须重新授权。
  518. const hash = createHash("sha256")
  519. .update(
  520. [
  521. serverName,
  522. serverUrl,
  523. config.clientId ?? "",
  524. config.scope ?? "",
  525. config.redirectPath ?? "",
  526. ].join("\n"),
  527. )
  528. .digest("hex")
  529. .slice(0, 24);
  530. return `mcp:oauth:${hash}`;
  531. }