|
1 | 1 | import { test, expect, describe, afterEach } from "bun:test" |
| 2 | +import { createConnection, createServer as createNetServer } from "net" |
2 | 3 | import { McpOAuthCallback } from "../../src/mcp/oauth-callback" |
3 | 4 | import { parseRedirectUri } from "../../src/mcp/oauth-provider" |
4 | 5 |
|
| 6 | +async function getFreeLoopbackPort(): Promise<number> { |
| 7 | + return new Promise((resolve, reject) => { |
| 8 | + const probe = createNetServer() |
| 9 | + probe.once("error", reject) |
| 10 | + probe.listen(0, "127.0.0.1", () => { |
| 11 | + const address = probe.address() |
| 12 | + probe.close(() => { |
| 13 | + if (typeof address === "object" && address) { |
| 14 | + resolve(address.port) |
| 15 | + return |
| 16 | + } |
| 17 | + reject(new Error("Could not allocate a loopback port")) |
| 18 | + }) |
| 19 | + }) |
| 20 | + }) |
| 21 | +} |
| 22 | + |
| 23 | +async function canConnect(host: string, port: number): Promise<boolean> { |
| 24 | + return new Promise((resolve) => { |
| 25 | + const socket = createConnection({ host, port }) |
| 26 | + const done = (ok: boolean) => { |
| 27 | + socket.removeAllListeners() |
| 28 | + socket.destroy() |
| 29 | + resolve(ok) |
| 30 | + } |
| 31 | + |
| 32 | + socket.setTimeout(500) |
| 33 | + socket.once("connect", () => done(true)) |
| 34 | + socket.once("error", () => done(false)) |
| 35 | + socket.once("timeout", () => done(false)) |
| 36 | + }) |
| 37 | +} |
| 38 | + |
5 | 39 | describe("parseRedirectUri", () => { |
6 | 40 | test("returns defaults when no URI provided", () => { |
7 | 41 | const result = parseRedirectUri() |
@@ -69,4 +103,12 @@ describe("McpOAuthCallback.ensureRunning", () => { |
69 | 103 |
|
70 | 104 | expect(await response.text()).toContain('<div class="error">The user denied access</div>') |
71 | 105 | }) |
| 106 | + |
| 107 | + test("binds the callback server to IPv4 loopback", async () => { |
| 108 | + const port = await getFreeLoopbackPort() |
| 109 | + await McpOAuthCallback.ensureRunning(`http://127.0.0.1:${port}/custom/callback`) |
| 110 | + |
| 111 | + expect(await canConnect("127.0.0.1", port)).toBe(true) |
| 112 | + expect(await canConnect("::1", port)).toBe(false) |
| 113 | + }) |
72 | 114 | }) |
0 commit comments