mcp-oauth-cross-process.e2e.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import { spawn } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { mkdtemp, rm } from "node:fs/promises";
  4. import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import { fileURLToPath } from "node:url";
  8. import { afterEach, describe, expect, it } from "vitest";
  9. import {
  10. createSharedZCodeCredentialStore,
  11. type SharedZCodeCredentialStore,
  12. } from "../src/auth/shared-credentials.js";
  13. import { publishCanonicalCredentials } from "../src/mcp/oauth-credentials.js";
  14. import { createCredentialKeyPrefix } from "../src/mcp/oauth.js";
  15. /**
  16. * 跨进程端到端验证:线上事故的竞态发生在多个真实 CLI 进程之间,同进程测试无法复现
  17. * 「两个进程同时读到临期 token / 同时抢授权」这个现场形态。本文件用 tsx 拉起真实 OS
  18. * 子进程驱动 adapters 源码,主进程只托管假授权服务器/假 MCP 并做协议级断言。
  19. */
  20. const MCP_SCOPE = "mcp:tools";
  21. const OAUTH_ACCESS_TOKEN = "cross-process-access-token";
  22. const ROTATED_ACCESS_TOKEN = "cross-process-rotated-token";
  23. const CHILD_TIMEOUT_MS = 60_000;
  24. const REPO_ROOT = fileURLToPath(new URL("../../../../../", import.meta.url));
  25. const CHILD_DRIVER = fileURLToPath(
  26. new URL("./fixtures/mcp-oauth-child-driver.ts", import.meta.url),
  27. );
  28. const servers: Server[] = [];
  29. const temporaryDirectories: string[] = [];
  30. afterEach(async () => {
  31. await Promise.all(servers.splice(0).map(closeServer));
  32. await Promise.all(
  33. temporaryDirectories
  34. .splice(0)
  35. .map((directory) => rm(directory, { force: true, recursive: true })),
  36. );
  37. });
  38. interface StrictServerState {
  39. authorizationCodes: Map<
  40. string,
  41. { challenge: string; clientId: string; redirectUri: string }
  42. >;
  43. clients: Map<string, { redirectUris: string[] }>;
  44. /** 单次使用的 refresh token;二次使用即 invalid_grant(rotation reuse-detection)。 */
  45. consumedRefreshTokens: Set<string>;
  46. knownRefreshTokens: Set<string>;
  47. refreshRequestCount: number;
  48. refreshRequestBodies: Array<Record<string, string>>;
  49. registrations: Array<Record<string, unknown>>;
  50. authorizationRequests: Array<Record<string, string>>;
  51. tokenExchanges: Array<Record<string, string>>;
  52. }
  53. function createState(): StrictServerState {
  54. return {
  55. authorizationCodes: new Map(),
  56. clients: new Map(),
  57. consumedRefreshTokens: new Set(),
  58. knownRefreshTokens: new Set(),
  59. refreshRequestCount: 0,
  60. refreshRequestBodies: [],
  61. registrations: [],
  62. authorizationRequests: [],
  63. tokenExchanges: [],
  64. };
  65. }
  66. interface FakeStack {
  67. asBaseUrl: string;
  68. mcpUrl: string;
  69. state: StrictServerState;
  70. }
  71. /** 假授权服务器 + 假受保护 MCP。redirect_uri 精确匹配(含端口),模拟 auth.exa.ai 行为。 */
  72. async function startFakeStack(): Promise<FakeStack> {
  73. const state = createState();
  74. const stack: FakeStack = { asBaseUrl: "", mcpUrl: "", state };
  75. const authServer = createServer((req, res) => {
  76. void handleAuthServer(req, res, stack).catch(() => res.destroy());
  77. });
  78. await listen(authServer);
  79. stack.asBaseUrl = serverBaseUrl(authServer);
  80. const mcpServer = createServer((req, res) => {
  81. void handleMcp(req, res, stack).catch(() => res.destroy());
  82. });
  83. await listen(mcpServer);
  84. stack.mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  85. return stack;
  86. }
  87. async function handleAuthServer(
  88. req: IncomingMessage,
  89. res: ServerResponse,
  90. stack: FakeStack,
  91. ): Promise<void> {
  92. const url = new URL(req.url ?? "/", "http://localhost");
  93. const state = stack.state;
  94. if (url.pathname === "/.well-known/oauth-authorization-server") {
  95. sendJson(res, 200, {
  96. issuer: stack.asBaseUrl,
  97. authorization_endpoint: `${stack.asBaseUrl}/authorize`,
  98. token_endpoint: `${stack.asBaseUrl}/token`,
  99. registration_endpoint: `${stack.asBaseUrl}/register`,
  100. grant_types_supported: ["authorization_code", "refresh_token"],
  101. response_types_supported: ["code"],
  102. code_challenge_methods_supported: ["S256"],
  103. token_endpoint_auth_methods_supported: ["none"],
  104. scopes_supported: [MCP_SCOPE, "admin:tools"],
  105. });
  106. return;
  107. }
  108. if (req.method === "POST" && url.pathname === "/register") {
  109. const body = JSON.parse(await readBody(req)) as Record<string, unknown>;
  110. state.registrations.push(body);
  111. const clientId = `cross-process-client-${state.registrations.length}`;
  112. const redirectUris = Array.isArray(body.redirect_uris)
  113. ? (body.redirect_uris as unknown[]).filter(
  114. (entry): entry is string => typeof entry === "string",
  115. )
  116. : [];
  117. state.clients.set(clientId, { redirectUris });
  118. // RFC 7591:注册响应必须回显已注册元数据;SDK 会对响应做 schema 校验
  119. // (redirect_uris 必须是数组),只回 client_id 会在解析阶段失败。
  120. sendJson(res, 201, {
  121. ...body,
  122. client_id: clientId,
  123. client_id_issued_at: 1,
  124. token_endpoint_auth_method: "none",
  125. });
  126. return;
  127. }
  128. if (req.method === "GET" && url.pathname === "/authorize") {
  129. const params = Object.fromEntries(url.searchParams.entries());
  130. state.authorizationRequests.push(params);
  131. const clientId = params.client_id ?? "";
  132. const redirectUri = params.redirect_uri ?? "";
  133. const challenge = params.code_challenge ?? "";
  134. const registered = state.clients.get(clientId);
  135. // 精确匹配(含端口):对 loopback 不做 RFC 8252 端口豁免,模拟 auth.exa.ai。
  136. if (
  137. !registered ||
  138. !redirectUri ||
  139. params.code_challenge_method !== "S256" ||
  140. !registered.redirectUris.includes(redirectUri)
  141. ) {
  142. sendJson(res, 400, { error: "invalid_request" });
  143. return;
  144. }
  145. const code = `auth-code-${state.authorizationRequests.length}`;
  146. state.authorizationCodes.set(code, { challenge, clientId, redirectUri });
  147. const callback = new URL(redirectUri);
  148. callback.searchParams.set("code", code);
  149. if (params.state) callback.searchParams.set("state", params.state);
  150. res.writeHead(302, { Location: callback.toString() });
  151. res.end();
  152. return;
  153. }
  154. if (req.method === "POST" && url.pathname === "/token") {
  155. const body = new URLSearchParams(await readBody(req));
  156. const entries = Object.fromEntries(body.entries());
  157. if (body.get("grant_type") === "refresh_token") {
  158. const refreshToken = body.get("refresh_token") ?? "";
  159. state.refreshRequestCount += 1;
  160. state.refreshRequestBodies.push(entries);
  161. if (
  162. state.consumedRefreshTokens.has(refreshToken) ||
  163. !state.knownRefreshTokens.has(refreshToken)
  164. ) {
  165. // 严格 rotation:同一 refresh token 二次使用即整族作废。
  166. sendJson(res, 400, { error: "invalid_grant" });
  167. return;
  168. }
  169. state.consumedRefreshTokens.add(refreshToken);
  170. const nextRefreshToken = `rotated-rt-${state.refreshRequestCount}`;
  171. state.knownRefreshTokens.add(nextRefreshToken);
  172. sendJson(res, 200, {
  173. access_token: ROTATED_ACCESS_TOKEN,
  174. expires_in: 3600,
  175. refresh_token: nextRefreshToken,
  176. token_type: "Bearer",
  177. });
  178. return;
  179. }
  180. const code = body.get("code") ?? "";
  181. const verifier = body.get("code_verifier") ?? "";
  182. const redirectUri = body.get("redirect_uri") ?? "";
  183. const issued = state.authorizationCodes.get(code);
  184. const actualChallenge = createHash("sha256").update(verifier).digest("base64url");
  185. if (
  186. !issued ||
  187. redirectUri !== issued.redirectUri ||
  188. actualChallenge !== issued.challenge
  189. ) {
  190. sendJson(res, 400, { error: "invalid_grant" });
  191. return;
  192. }
  193. state.authorizationCodes.delete(code);
  194. state.tokenExchanges.push(entries);
  195. const refreshToken = `issued-rt-${state.tokenExchanges.length}`;
  196. state.knownRefreshTokens.add(refreshToken);
  197. sendJson(res, 200, {
  198. access_token: OAUTH_ACCESS_TOKEN,
  199. expires_in: 3600,
  200. refresh_token: refreshToken,
  201. scope: MCP_SCOPE,
  202. token_type: "Bearer",
  203. });
  204. return;
  205. }
  206. res.writeHead(404).end();
  207. }
  208. async function handleMcp(
  209. req: IncomingMessage,
  210. res: ServerResponse,
  211. stack: FakeStack,
  212. ): Promise<void> {
  213. const url = new URL(req.url ?? "/", "http://localhost");
  214. if (url.pathname === "/.well-known/oauth-protected-resource") {
  215. sendJson(res, 200, {
  216. authorization_servers: [stack.asBaseUrl],
  217. resource: stack.mcpUrl,
  218. scopes_supported: [MCP_SCOPE],
  219. });
  220. return;
  221. }
  222. if (req.method !== "POST" || url.pathname !== "/mcp") {
  223. res.writeHead(404).end();
  224. return;
  225. }
  226. if (req.headers.authorization !== `Bearer ${OAUTH_ACCESS_TOKEN}`) {
  227. res.writeHead(401, {
  228. "WWW-Authenticate": [
  229. `Bearer resource_metadata="${new URL("/.well-known/oauth-protected-resource", stack.mcpUrl).href}", scope="${MCP_SCOPE}"`,
  230. ],
  231. });
  232. res.end();
  233. return;
  234. }
  235. const message = JSON.parse(await readBody(req)) as { id?: number | string; method?: string };
  236. if (message.method === "initialize") {
  237. sendJson(res, 200, {
  238. id: message.id,
  239. jsonrpc: "2.0",
  240. result: {
  241. capabilities: { tools: {} },
  242. protocolVersion: "2025-11-25",
  243. serverInfo: { name: "cross-process-mcp", version: "1.0.0" },
  244. },
  245. });
  246. return;
  247. }
  248. if (message.method === "tools/list") {
  249. // tools/list 必须真实返回工具:客户端建连的最后一跳就是它,回错误会让整次连接失败。
  250. sendJson(res, 200, {
  251. id: message.id,
  252. jsonrpc: "2.0",
  253. result: {
  254. tools: [
  255. {
  256. description: "cross-process ping",
  257. inputSchema: { properties: {}, type: "object" },
  258. name: "oauth_ping",
  259. },
  260. ],
  261. },
  262. });
  263. return;
  264. }
  265. // server/discover 回 -32601:让 modern 版本协商回退到 legacy initialize 握手。
  266. if (message.method === "server/discover") {
  267. sendJson(res, 200, {
  268. error: { code: -32601, message: "Method not found" },
  269. id: message.id,
  270. jsonrpc: "2.0",
  271. });
  272. return;
  273. }
  274. sendJson(res, 202, {});
  275. }
  276. interface ChildResult {
  277. authorizationUrls?: string[];
  278. error?: string;
  279. status?: { authorization?: { authorizationUrl?: string }; status?: string; toolCount?: number };
  280. token?: string;
  281. }
  282. interface ChildHandle {
  283. kill(): void;
  284. result: Promise<ChildResult>;
  285. }
  286. function runChild(config: Record<string, unknown>): ChildHandle {
  287. // 用 `node --import tsx` 让驱动直接运行在本进程:tsx CLI 包装器会把自己的真正工作放进
  288. // 子进程,SIGKILL 包装器只会留下孤儿——孤儿持有 lease 且 PID 存活,owner-dead 回收就
  289. // 无法验证。--import 在进程内注册 loader,child.pid 即驱动进程本身。
  290. const child = spawn(process.execPath, ["--import", "tsx", CHILD_DRIVER, JSON.stringify(config)], {
  291. cwd: REPO_ROOT,
  292. env: process.env,
  293. stdio: ["ignore", "pipe", "pipe"],
  294. });
  295. let stdout = "";
  296. let stderr = "";
  297. const result = new Promise<ChildResult>((resolve, reject) => {
  298. const timer = setTimeout(() => {
  299. child.kill("SIGKILL");
  300. reject(new Error(`child timed out after ${CHILD_TIMEOUT_MS}ms; stderr: ${stderr}`));
  301. }, CHILD_TIMEOUT_MS);
  302. child.stdout.on("data", (chunk: Buffer) => {
  303. stdout += chunk.toString("utf8");
  304. });
  305. child.stderr.on("data", (chunk: Buffer) => {
  306. stderr += chunk.toString("utf8");
  307. });
  308. child.once("error", (error) => {
  309. clearTimeout(timer);
  310. reject(error);
  311. });
  312. child.once("close", (code) => {
  313. clearTimeout(timer);
  314. const jsonLine = stdout.trim().split("\n").at(-1);
  315. if (code !== 0 || !jsonLine) {
  316. reject(new Error(`child exited with ${code}; stderr: ${stderr}; stdout: ${stdout}`));
  317. return;
  318. }
  319. resolve(JSON.parse(jsonLine) as ChildResult);
  320. });
  321. });
  322. return { kill: () => child.kill("SIGKILL"), result };
  323. }
  324. async function createCredentials(secret: string): Promise<{
  325. credentialStore: SharedZCodeCredentialStore;
  326. credentialsPath: string;
  327. }> {
  328. const directory = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-cross-process-"));
  329. temporaryDirectories.push(directory);
  330. const credentialsPath = join(directory, "credentials.json");
  331. return {
  332. credentialStore: createSharedZCodeCredentialStore({
  333. env: { ZCODE_CREDENTIAL_SECRET: secret },
  334. filePath: credentialsPath,
  335. }),
  336. credentialsPath,
  337. };
  338. }
  339. describe("MCP OAuth cross-process end-to-end", () => {
  340. it("two real processes refresh one near-expiry token with exactly one network request", async () => {
  341. const stack = await startFakeStack();
  342. const { credentialStore, credentialsPath } = await createCredentials("cross-process-refresh");
  343. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  344. const keyPrefix = createCredentialKeyPrefix("cross", stack.mcpUrl, oauthConfig);
  345. stack.state.knownRefreshTokens.add("seed-rt-0");
  346. await publishCanonicalCredentials(credentialStore, keyPrefix, {
  347. clientInformation: { client_id: "seed-client" },
  348. // 已经过期一小时:两个子进程的 token() 都会判定临期并进锁。
  349. obtainedAt: Date.now() - 7_200_000,
  350. publishedBy: "cross-process-seed",
  351. tokens: {
  352. access_token: "stale-access-token",
  353. expires_in: 3600,
  354. refresh_token: "seed-rt-0",
  355. token_type: "Bearer",
  356. },
  357. });
  358. const config = {
  359. credentialsPath,
  360. keyPrefix,
  361. mcpUrl: stack.mcpUrl,
  362. mode: "refresh-race" as const,
  363. secret: "cross-process-refresh",
  364. };
  365. const racers = [runChild(config), runChild(config)];
  366. const [first, second] = await Promise.all(racers.map((child) => child.result));
  367. // 根因 1 的现场形态:两个真实进程并发用同一 rotation refresh token 刷新。修复后,
  368. // 跨进程文件锁 + 锁内 generation 合并保证只有一个请求到达 token endpoint;
  369. // 若有两个,严格服务器会 invalid_grant、token family 被撤销,子进程会失败。
  370. expect(first.token).toBe(ROTATED_ACCESS_TOKEN);
  371. expect(second.token).toBe(ROTATED_ACCESS_TOKEN);
  372. expect(stack.state.refreshRequestCount).toBe(1);
  373. expect(stack.state.refreshRequestBodies[0]?.grant_type).toBe("refresh_token");
  374. expect(stack.state.refreshRequestBodies[0]?.refresh_token).toBe("seed-rt-0");
  375. // RFC 8707 resource 受众参数必须带上。
  376. expect(stack.state.refreshRequestBodies[0]?.resource).toBe(stack.mcpUrl);
  377. }, 90_000);
  378. it("two real processes elect one authorization leader with one DCR and one authorization URL", async () => {
  379. const stack = await startFakeStack();
  380. const { credentialsPath } = await createCredentials("cross-process-authorize");
  381. const config = {
  382. autoDrive: true,
  383. credentialsPath,
  384. mcpUrl: stack.mcpUrl,
  385. mode: "authorize" as const,
  386. secret: "cross-process-authorize",
  387. };
  388. const racers = [runChild(config), runChild(config)];
  389. const [first, second] = await Promise.all(racers.map((child) => child.result));
  390. // 根因 2 的现场形态:过去两个连接各开一个 listener、各注册一个 client、各生成一个
  391. // 授权 URL,且 client 的 redirect_uris 锁死各自的随机端口。修复后跨进程授权 lease
  392. // 单飞:恰好一次 DCR、一个授权 URL;follower 观察 canonical 换代后用新凭据重连。
  393. expect(first.status?.status).toBe("connected");
  394. expect(second.status?.status).toBe("connected");
  395. expect(first.status?.toolCount).toBe(1);
  396. expect(second.status?.toolCount).toBe(1);
  397. const drivenUrls = [...(first.authorizationUrls ?? []), ...(second.authorizationUrls ?? [])];
  398. expect(drivenUrls).toHaveLength(1);
  399. expect(stack.state.registrations).toHaveLength(1);
  400. expect(stack.state.authorizationRequests).toHaveLength(1);
  401. expect(stack.state.tokenExchanges).toHaveLength(1);
  402. // fresh DCR 注册的 redirect_uri 就是授权请求实际使用的地址(精确匹配服务器下必须一致)。
  403. expect(stack.state.registrations[0]?.redirect_uris).toEqual([
  404. stack.state.authorizationRequests[0]?.redirect_uri,
  405. ]);
  406. }, 90_000);
  407. it("reclaims the authorization lease and completes after the leader process is killed", async () => {
  408. const stack = await startFakeStack();
  409. const { credentialStore, credentialsPath } = await createCredentials("cross-process-kill");
  410. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  411. const keyPrefix = createCredentialKeyPrefix("cross", stack.mcpUrl, oauthConfig);
  412. const secret = "cross-process-kill";
  413. const leaderConfig = {
  414. // 不 autoDrive:leader 会停在等回调,模拟用户还没在浏览器完成授权。
  415. autoDrive: false,
  416. credentialsPath,
  417. mcpUrl: stack.mcpUrl,
  418. mode: "authorize" as const,
  419. secret,
  420. // 必须与主进程计算 keyPrefix 用的 serverName 一致,否则轮询不到 pending 键。
  421. serverName: "cross",
  422. };
  423. const leader = runChild(leaderConfig);
  424. // 等 leader 发布 pending_authorization 共享键(证明它已进入授权等待)。
  425. const pendingKey = `${keyPrefix}:pending_authorization`;
  426. for (let attempt = 0; attempt < 300; attempt += 1) {
  427. if (await credentialStore.load(pendingKey)) break;
  428. await new Promise((resolve) => setTimeout(resolve, 100));
  429. }
  430. expect(await credentialStore.load(pendingKey)).toBeTruthy();
  431. // SIGKILL leader:不留任何清理机会,lease 目录里是死 PID 的 owner 文件。
  432. // runChild 无法定向杀,所以这里绕过封装直接拿 child 进程。
  433. leader.kill();
  434. await leader.result.catch(() => undefined);
  435. const successor = await runChild({ ...leaderConfig, autoDrive: true }).result;
  436. // 接管者必须先回收死 owner 的锁,再以 fresh DCR 重新领导授权;被杀 leader 的 code
  437. // 永远不会被交换(它从未收到回调),token endpoint 只应见到一次 exchange。
  438. expect(successor.status?.status).toBe("connected");
  439. expect(successor.authorizationUrls).toHaveLength(1);
  440. expect(stack.state.tokenExchanges).toHaveLength(1);
  441. const canonicalRaw = await credentialStore.load(`${keyPrefix}:authorization_credentials`);
  442. expect(canonicalRaw).toBeTruthy();
  443. const canonical = JSON.parse(canonicalRaw ?? "{}") as {
  444. client_information?: { client_id?: string };
  445. };
  446. // 最终发布的必须是接管者这次授权的 client,不是死 leader 留下的注册。
  447. expect(canonical.client_information?.client_id).toBe("cross-process-client-2");
  448. expect(stack.state.registrations).toHaveLength(2);
  449. }, 90_000);
  450. it("completes authorization that outlasts the caller budget (incident timeline replay)", async () => {
  451. // 现场:2026-08-11 真人授权耗时约 74 秒,而 session 预算只有 15 秒。旧实现 15 秒后
  452. // 关闭 listener,授权必败;新实现预算只约束 caller 等待,事务继续存活。
  453. // 按比例缩放:caller 预算 100ms,「用户」1500ms 后才完成授权。
  454. const stack = await startFakeStack();
  455. const { credentialStore, credentialsPath } = await createCredentials("cross-process-budget");
  456. const secret = "cross-process-budget";
  457. const { createMcpAdapter } = await import("../src/mcp/index.js");
  458. const adapter = createMcpAdapter({
  459. mcpOAuth: {
  460. credentialStore,
  461. openAuthorizationUrl: async ({ authorizationUrl }) => {
  462. await new Promise((resolve) => setTimeout(resolve, 1500));
  463. const response = await fetch(authorizationUrl, { redirect: "manual" });
  464. const location = response.headers.get("location");
  465. if (location) await fetch(location);
  466. },
  467. },
  468. });
  469. try {
  470. const budgeted = await adapter.connectServer(
  471. "budget",
  472. { type: "http", url: stack.mcpUrl, oauth: { type: "authorization_code", scope: MCP_SCOPE } },
  473. { oauthAuthorizationTimeoutMs: 100 },
  474. );
  475. // 预算到点只返回快照:connecting + 授权 URL,事务没有被杀。
  476. expect(budgeted.status).toBe("connecting");
  477. expect(budgeted.authorization?.authorizationUrl).toContain(stack.asBaseUrl);
  478. let final = budgeted;
  479. for (let attempt = 0; attempt < 100 && final.status !== "connected"; attempt += 1) {
  480. await new Promise((resolve) => setTimeout(resolve, 100));
  481. final = (await adapter.status()).budget ?? final;
  482. }
  483. expect(final.status).toBe("connected");
  484. expect(final.toolCount).toBe(1);
  485. expect(stack.state.registrations).toHaveLength(1);
  486. expect(stack.state.authorizationRequests).toHaveLength(1);
  487. expect(stack.state.tokenExchanges).toHaveLength(1);
  488. } finally {
  489. await adapter.close();
  490. }
  491. }, 90_000);
  492. });
  493. function sendJson(res: ServerResponse, statusCode: number, body: unknown): void {
  494. res.writeHead(statusCode, { "Content-Type": "application/json" });
  495. res.end(JSON.stringify(body));
  496. }
  497. async function readBody(req: IncomingMessage): Promise<string> {
  498. const chunks: Buffer[] = [];
  499. for await (const chunk of req) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
  500. return Buffer.concat(chunks).toString("utf8");
  501. }
  502. async function listen(server: Server): Promise<Server> {
  503. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  504. servers.push(server);
  505. return server;
  506. }
  507. function serverBaseUrl(server: Server): string {
  508. const address = server.address();
  509. if (!address || typeof address === "string") throw new Error("server is not listening on TCP");
  510. return `http://127.0.0.1:${address.port}`;
  511. }
  512. async function closeServer(server: Server): Promise<void> {
  513. if (!server.listening) return;
  514. await new Promise<void>((resolve, reject) => {
  515. server.close((error) => (error ? reject(error) : resolve()));
  516. });
  517. }