oauth-credentials.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import { createHash, randomBytes } from "node:crypto";
  2. import { isDeepStrictEqual } from "node:util";
  3. import type { OAuthClientInformationMixed, OAuthTokens } from "@modelcontextprotocol/client";
  4. import type { SharedZCodeCredentialStore } from "../auth/shared-credentials.js";
  5. export const MCP_OAUTH_CANONICAL_CREDENTIALS_KEY = "authorization_credentials";
  6. export const MCP_OAUTH_LEGACY_CLIENT_KEY = "client_information";
  7. export const MCP_OAUTH_LEGACY_TOKENS_KEY = "tokens";
  8. export const MCP_OAUTH_CREDENTIALS_VERSION = 2;
  9. export const MCP_OAUTH_SUPPORTED_CREDENTIAL_VERSIONS = new Set([1, MCP_OAUTH_CREDENTIALS_VERSION]);
  10. /**
  11. * canonical credential pair。
  12. *
  13. * `generation`、`obtained_at`、`expires_at`、`issuer` 都是**可选新增字段**,不 bump version:
  14. * 追加可选字段对旧 reader 向后兼容(旧 reader 忽略未知字段即可),bump version 反而会让未升级的
  15. * CLI/desktop 把新记录当未知版本整体忽略、退回 legacy 镜像,丢掉 pair 保证。
  16. */
  17. export interface McpOAuthCanonicalCredentials {
  18. client_information: OAuthClientInformationMixed;
  19. /** 由 `expires_in` 与 `obtained_at` 推导的绝对过期点(epoch ms)。 */
  20. expires_at?: number;
  21. /**
  22. * 每次 publication 唯一的随机 id。
  23. *
  24. * 不能复用 `published_by`:它是 OAuth state 派生的事务 id,同一事务的多次 refresh 不会改变它,
  25. * 无法承担 follower 观察换代与失效 CAS 的职责。随机 id 同时消除 ABA。
  26. */
  27. generation?: string;
  28. /** 授权服务器 issuer。本次只留存字段,不参与 credential key 键控。 */
  29. issuer?: string;
  30. /** token 获取时间(epoch ms)。`OAuthTokens` 只有 `expires_in`,没有它无法跨进程算真实过期点。 */
  31. obtained_at?: number;
  32. published_by: string;
  33. tokens: OAuthTokens;
  34. version: 1 | typeof MCP_OAUTH_CREDENTIALS_VERSION;
  35. }
  36. export interface CanonicalCredentialSnapshot {
  37. clientInformation: OAuthClientInformationMixed;
  38. expiresAt?: number;
  39. generation: string;
  40. issuer?: string;
  41. obtainedAt?: number;
  42. /** 原始 JSON,供 compare-and-delete 使用。 */
  43. raw: string;
  44. tokens: OAuthTokens;
  45. }
  46. export function mcpOAuthCredentialKey(keyPrefix: string, name: string): string {
  47. return `${keyPrefix}:${name}`;
  48. }
  49. export function createCredentialGeneration(): string {
  50. return randomBytes(16).toString("hex");
  51. }
  52. /**
  53. * 迁移期 baseline:旧记录没有 `generation`,用 canonical 原始内容的稳定 hash 代替。
  54. * 内容变化即 generation 变化,足以支撑 follower 的「是否换代」判断。
  55. */
  56. export function resolveCredentialGeneration(
  57. canonical: McpOAuthCanonicalCredentials,
  58. raw: string,
  59. ): string {
  60. if (typeof canonical.generation === "string" && canonical.generation.length > 0) {
  61. return canonical.generation;
  62. }
  63. return `legacy-${createHash("sha256").update(raw).digest("hex").slice(0, 32)}`;
  64. }
  65. export function isCanonicalCredentials(value: unknown): value is McpOAuthCanonicalCredentials {
  66. if (
  67. !isRecord(value) ||
  68. typeof value.version !== "number" ||
  69. !MCP_OAUTH_SUPPORTED_CREDENTIAL_VERSIONS.has(value.version)
  70. ) {
  71. return false;
  72. }
  73. if (typeof value.published_by !== "string" || value.published_by.length === 0) return false;
  74. if (!isRecord(value.client_information) || !isRecord(value.tokens)) return false;
  75. return (
  76. typeof value.client_information.client_id === "string" &&
  77. typeof value.tokens.access_token === "string" &&
  78. typeof value.tokens.token_type === "string"
  79. );
  80. }
  81. /**
  82. * 只读取 canonical pair,不做 legacy 兼容推导。
  83. *
  84. * Phase 2 的 baseline generation 与 Phase 1 的 refresh 都只需要 canonical;legacy 镜像的
  85. * 交错兼容逻辑仍留在 provider 内。
  86. */
  87. export async function loadCanonicalCredentials(
  88. credentialStore: SharedZCodeCredentialStore,
  89. keyPrefix: string,
  90. ): Promise<CanonicalCredentialSnapshot | undefined> {
  91. const key = mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_CANONICAL_CREDENTIALS_KEY);
  92. const raw = await credentialStore.load(key);
  93. if (!raw) return undefined;
  94. let parsed: unknown;
  95. try {
  96. parsed = JSON.parse(raw);
  97. } catch {
  98. return undefined;
  99. }
  100. if (!isCanonicalCredentials(parsed)) return undefined;
  101. return {
  102. clientInformation: parsed.client_information,
  103. ...(parsed.expires_at === undefined ? {} : { expiresAt: parsed.expires_at }),
  104. generation: resolveCredentialGeneration(parsed, raw),
  105. ...(parsed.issuer === undefined ? {} : { issuer: parsed.issuer }),
  106. ...(parsed.obtained_at === undefined ? {} : { obtainedAt: parsed.obtained_at }),
  107. raw,
  108. tokens: parsed.tokens,
  109. };
  110. }
  111. export interface PublishCanonicalCredentialsInput {
  112. clientInformation: OAuthClientInformationMixed;
  113. issuer?: string;
  114. obtainedAt?: number;
  115. publishedBy: string;
  116. tokens: OAuthTokens;
  117. }
  118. export interface PublishedCanonicalCredentials {
  119. canonical: McpOAuthCanonicalCredentials;
  120. generation: string;
  121. legacyClientRaw: string;
  122. legacyTokensRaw: string;
  123. raw: string;
  124. }
  125. /**
  126. * 原子发布 canonical pair 与 legacy 镜像。
  127. *
  128. * client 与 refresh token 必须来自同一次授权,因此三个 key 必须在共享凭据 store 的同一个
  129. * 跨进程 read-modify-write 临界区内一次写入;分开覆盖会让最后写入的 client 与 token 来自
  130. * 不同事务。兼容窗口内继续维护 legacy 镜像,使未升级的 CLI/Desktop 仍可读取。
  131. */
  132. export async function publishCanonicalCredentials(
  133. credentialStore: SharedZCodeCredentialStore,
  134. keyPrefix: string,
  135. input: PublishCanonicalCredentialsInput,
  136. ): Promise<PublishedCanonicalCredentials> {
  137. const obtainedAt = input.obtainedAt ?? Date.now();
  138. const expiresAt =
  139. typeof input.tokens.expires_in === "number" && Number.isFinite(input.tokens.expires_in)
  140. ? obtainedAt + input.tokens.expires_in * 1000
  141. : undefined;
  142. const generation = createCredentialGeneration();
  143. const canonical: McpOAuthCanonicalCredentials = {
  144. client_information: input.clientInformation,
  145. ...(expiresAt === undefined ? {} : { expires_at: expiresAt }),
  146. generation,
  147. ...(input.issuer === undefined ? {} : { issuer: input.issuer }),
  148. obtained_at: obtainedAt,
  149. published_by: input.publishedBy,
  150. tokens: input.tokens,
  151. version: MCP_OAUTH_CREDENTIALS_VERSION,
  152. };
  153. const raw = JSON.stringify(canonical);
  154. const legacyClientRaw = JSON.stringify(input.clientInformation);
  155. const legacyTokensRaw = JSON.stringify(input.tokens);
  156. await credentialStore.saveMany({
  157. [mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_CANONICAL_CREDENTIALS_KEY)]: raw,
  158. [mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_LEGACY_CLIENT_KEY)]: legacyClientRaw,
  159. [mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_LEGACY_TOKENS_KEY)]: legacyTokensRaw,
  160. });
  161. return { canonical, generation, legacyClientRaw, legacyTokensRaw, raw };
  162. }
  163. export function isRecord(value: unknown): value is Record<string, unknown> {
  164. return typeof value === "object" && value !== null && !Array.isArray(value);
  165. }
  166. /** access token 临期判定的安全余量。 */
  167. export const MCP_OAUTH_EXPIRY_SKEW_MS = 30_000;
  168. /**
  169. * 是否需要在把 token 交给请求头之前先刷新。
  170. *
  171. * 没有 `expires_at`(旧记录,或服务器未返回 `expires_in`)一律视为临期:`OAuthTokens` 不带获取
  172. * 时间,无法算出真实过期点,宁可进锁尝试一次刷新,也不要把一个可能已过期的 token 发出去。
  173. */
  174. export function isCanonicalTokenNearExpiry(
  175. snapshot: Pick<CanonicalCredentialSnapshot, "expiresAt">,
  176. now = Date.now(),
  177. skewMs = MCP_OAUTH_EXPIRY_SKEW_MS,
  178. ): boolean {
  179. if (snapshot.expiresAt === undefined) return true;
  180. return now >= snapshot.expiresAt - skewMs;
  181. }
  182. export type CanonicalInvalidationScope = "tokens" | "all";
  183. /**
  184. * 按 canonical 快照做条件失效。
  185. *
  186. * 只有 canonical 当前值仍等于 `expectedRaw` 时才删除,因此另一个事务已经发布新 pair 时本次
  187. * 失效整体放弃,不会误删 winner。`tokens` 保留 legacy client 作为重新授权的种子;`all` 用于
  188. * `invalid_client`,client 与 token 必须整对丢弃。
  189. */
  190. export async function invalidateCanonicalCredentials(
  191. credentialStore: SharedZCodeCredentialStore,
  192. keyPrefix: string,
  193. expectedRaw: string,
  194. scope: CanonicalInvalidationScope,
  195. ): Promise<boolean> {
  196. const canonicalKey = mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_CANONICAL_CREDENTIALS_KEY);
  197. const keysToDelete = [
  198. canonicalKey,
  199. mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_LEGACY_TOKENS_KEY),
  200. ];
  201. if (scope === "all") {
  202. keysToDelete.push(mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_LEGACY_CLIENT_KEY));
  203. }
  204. return await credentialStore.deleteManyIfValue(canonicalKey, expectedRaw, keysToDelete);
  205. }
  206. export interface CredentialPairSnapshot {
  207. clientInformation?: OAuthClientInformationMixed;
  208. expiresAt?: number;
  209. /** canonical 可用时为其 generation;只有 legacy 时按内容派生,仍可用于观察换代。 */
  210. generation?: string;
  211. issuer?: string;
  212. obtainedAt?: number;
  213. /** canonical 原始 JSON;只有 legacy 时为 undefined(无法做 canonical CAS)。 */
  214. raw?: string;
  215. source: "canonical" | "legacy";
  216. tokens?: OAuthTokens;
  217. }
  218. /**
  219. * 读取 canonical 与 legacy 镜像并按兼容规则派生出一份可用 pair。
  220. */
  221. export async function loadCredentialPair(
  222. credentialStore: SharedZCodeCredentialStore,
  223. keyPrefix: string,
  224. ): Promise<CredentialPairSnapshot | undefined> {
  225. const canonicalKey = mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_CANONICAL_CREDENTIALS_KEY);
  226. const legacyClientKey = mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_LEGACY_CLIENT_KEY);
  227. const legacyTokensKey = mcpOAuthCredentialKey(keyPrefix, MCP_OAUTH_LEGACY_TOKENS_KEY);
  228. const values = await credentialStore.loadMany([canonicalKey, legacyClientKey, legacyTokensKey]);
  229. return deriveCredentialPair({
  230. canonicalRaw: values[canonicalKey] ?? undefined,
  231. legacyClientRaw: values[legacyClientKey] ?? undefined,
  232. legacyTokensRaw: values[legacyTokensKey] ?? undefined,
  233. });
  234. }
  235. /**
  236. * 兼容窗口内的 pair 派生规则(纯函数,不做 I/O)。
  237. *
  238. * 抽成纯函数是为了让「已经持有原始快照的调用方」(需要原始值做 compare-and-delete 的
  239. * provider)复用同一份规则,而不是再读一次凭据文件——两处各写一遍这套交错兼容分支必然发散。
  240. *
  241. * 规则背景:兼容窗口内 CLI 与 desktop 可能是不同版本,旧进程只写 legacy key,新进程写
  242. * canonical + 镜像。这里判断的就是「在没有 generation 的旧格式下,legacy 的变化能否被证明属于
  243. * 同一次授权」。
  244. */
  245. export function deriveCredentialPair(input: {
  246. canonicalRaw?: string;
  247. legacyClientRaw?: string;
  248. legacyTokensRaw?: string;
  249. }): CredentialPairSnapshot | undefined {
  250. const canonicalParsed = parseJson<unknown>(input.canonicalRaw);
  251. const canonical =
  252. canonicalParsed !== undefined && isCanonicalCredentials(canonicalParsed)
  253. ? canonicalParsed
  254. : undefined;
  255. const legacyClient = parseJson<OAuthClientInformationMixed>(input.legacyClientRaw);
  256. const legacyTokens = parseJson<OAuthTokens>(input.legacyTokensRaw);
  257. if (canonical && input.canonicalRaw) {
  258. const canonicalSnapshot: CredentialPairSnapshot = {
  259. clientInformation: canonical.client_information,
  260. ...(canonical.expires_at === undefined ? {} : { expiresAt: canonical.expires_at }),
  261. generation: resolveCredentialGeneration(canonical, input.canonicalRaw),
  262. ...(canonical.issuer === undefined ? {} : { issuer: canonical.issuer }),
  263. ...(canonical.obtained_at === undefined ? {} : { obtainedAt: canonical.obtained_at }),
  264. raw: input.canonicalRaw,
  265. source: "canonical",
  266. tokens: canonical.tokens,
  267. };
  268. if (canonical.version === 1) {
  269. const canAdoptLegacyTokens =
  270. legacyTokens !== undefined &&
  271. (!legacyClient || isDeepStrictEqual(legacyClient, canonical.client_information));
  272. if (canAdoptLegacyTokens) {
  273. return {
  274. clientInformation: legacyClient ?? canonical.client_information,
  275. source: "legacy",
  276. tokens: legacyTokens,
  277. };
  278. }
  279. // v1 发布后会删除 legacy 镜像,因此无镜像是正常稳态;若把它套用 v2 的
  280. // 镜像失效规则,会丢弃仍有效的 canonical token,并强制所有升级用户重新授权。
  281. return canonicalSnapshot;
  282. }
  283. if (!legacyTokens) {
  284. // 旧 provider invalidate tokens 后必须维持失效,不能从 canonical 复活旧 token。
  285. return { clientInformation: legacyClient, source: "legacy" };
  286. }
  287. if (isDeepStrictEqual(legacyTokens, canonical.tokens)) {
  288. return legacyClient ? canonicalSnapshot : { source: "legacy", tokens: legacyTokens };
  289. }
  290. if (legacyClient && isDeepStrictEqual(legacyClient, canonical.client_information)) {
  291. // client 未变化时可以确认 legacy token 是同一身份的旧 provider refresh 结果。
  292. return { clientInformation: legacyClient, source: "legacy", tokens: legacyTokens };
  293. }
  294. // client 与 token 都变化且无 generation 时无法证明来自同一事务:保留 client 重新授权,
  295. // 绝不猜测性拼接认证资产。
  296. return { clientInformation: legacyClient, source: "legacy" };
  297. }
  298. if (!legacyClient && !legacyTokens) return undefined;
  299. return {
  300. clientInformation: legacyClient,
  301. source: "legacy",
  302. ...(legacyTokens ? { tokens: legacyTokens } : {}),
  303. };
  304. }
  305. function parseJson<T>(raw: string | undefined): T | undefined {
  306. if (!raw) return undefined;
  307. try {
  308. return JSON.parse(raw) as T;
  309. } catch {
  310. return undefined;
  311. }
  312. }