diff --git a/packages/@emulators/autumn/src/__tests__/autumn-carry-over.test.ts b/packages/@emulators/autumn/src/__tests__/autumn-carry-over.test.ts index e4db6bdc0..5ae22be69 100644 --- a/packages/@emulators/autumn/src/__tests__/autumn-carry-over.test.ts +++ b/packages/@emulators/autumn/src/__tests__/autumn-carry-over.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { autumnPlugin, seedFromConfig } from "../index.js"; import { manifest } from "../manifest.js"; @@ -10,12 +10,12 @@ import { manifest } from "../manifest.js"; // old plan's Stripe subscription. Raw fetch, since these routes postdate the // pinned SDK. -const PORT = 41941; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; const PERIOD_END = Date.UTC(2030, 0, 15); const TRIAL_END = Date.UTC(2030, 0, 8); -let httpServer: ReturnType; +let httpServer: FreePortServer; const post = async (path: string, body: unknown) => { const response = await fetch(`${BASE}/v1/${path}`, { @@ -57,7 +57,11 @@ const subscribed = (sub: Record) => ({ ...sub, }); -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(autumnPlugin, { port: PORT, baseUrl: BASE, @@ -95,11 +99,11 @@ beforeAll(() => { { id: "org_taken", subscriptions: [{ plan_id: "free", status: "active" }] }, ], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); }); afterAll(async () => { - await new Promise((resolve) => httpServer.close(() => resolve())); + await httpServer.close(); }); describe("autumn emulator: carrying a subscription over to another catalog", () => { diff --git a/packages/@emulators/autumn/src/__tests__/autumn-catalog.test.ts b/packages/@emulators/autumn/src/__tests__/autumn-catalog.test.ts index aa544a97c..5595b4b27 100644 --- a/packages/@emulators/autumn/src/__tests__/autumn-catalog.test.ts +++ b/packages/@emulators/autumn/src/__tests__/autumn-catalog.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { Autumn } from "autumn-js"; import { autumnPlugin, seedFromConfig } from "../index.js"; @@ -16,8 +16,8 @@ import { manifest } from "../manifest.js"; // executions feature and a non-consumable members feature, and a paid team // plan with unlimited executions and a per-seat usage price. -const PORT = 41881; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; const NS = "app-stage"; const FREE = `${NS}-free`; const TEAM = `${NS}-team`; @@ -27,7 +27,7 @@ const MEMBERS = `${NS}-members`; /** The tiny plan's whole allowance, small enough to exhaust from a test. */ const TINY_INCLUDED = 50; -let httpServer: ReturnType; +let httpServer: FreePortServer; let autumn: Autumn; const post = (path: string, body: unknown) => @@ -77,7 +77,11 @@ const check = (customerId: string, featureId: string, requiredBalance: number, s send_event: sendEvent, }); -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(autumnPlugin, { port: PORT, baseUrl: BASE, @@ -122,12 +126,12 @@ beforeAll(() => { }, ], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); autumn = new Autumn({ secretKey: "am_test_emulate", serverURL: BASE }); }); afterAll(async () => { - await new Promise((resolve) => httpServer.close(() => resolve())); + await httpServer.close(); }); describe("customers.get_or_create honours auto_enable_plan_id", () => { diff --git a/packages/@emulators/autumn/src/__tests__/autumn-setup-payment.test.ts b/packages/@emulators/autumn/src/__tests__/autumn-setup-payment.test.ts index 4cda6ea17..d4535e478 100644 --- a/packages/@emulators/autumn/src/__tests__/autumn-setup-payment.test.ts +++ b/packages/@emulators/autumn/src/__tests__/autumn-setup-payment.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { Autumn } from "autumn-js"; import { autumnPlugin, seedFromConfig } from "../index.js"; @@ -10,14 +10,18 @@ import { manifest } from "../manifest.js"; // card and redirects back, and the customer's default payment method only // changes once the Stripe webhook settles. -const PORT = 41885; -const BASE = `http://localhost:${PORT}`; -const SUCCESS_URL = `${BASE}/back-to-billing`; +let PORT = 0; +let BASE = ""; +const successUrl = () => `${BASE}/back-to-billing`; -let httpServer: ReturnType; +let httpServer: FreePortServer; let autumn: Autumn; -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(autumnPlugin, { port: PORT, baseUrl: BASE, @@ -35,12 +39,12 @@ beforeAll(() => { }, ], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); autumn = new Autumn({ secretKey: "am_test_emulate", serverURL: BASE }); }); afterAll(async () => { - await new Promise((resolve) => httpServer.close(() => resolve())); + await httpServer.close(); }); // The SDK types the expanded field as `any`, so read it through a narrow shape. @@ -60,7 +64,7 @@ describe("autumn emulator: setup_payment (change the card on file)", () => { const CUSTOMER = "org_setup"; it("setup_payment returns a hosted setup URL", async () => { - const res = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: SUCCESS_URL }); + const res = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: successUrl() }); expect(res.customerId).toBe(CUSTOMER); expect(res.url, "a hosted setup URL is returned").toContain("/checkout/setup/"); @@ -69,7 +73,7 @@ describe("autumn emulator: setup_payment (change the card on file)", () => { }); it("the hosted setup page renders a save-card form", async () => { - const { url } = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: SUCCESS_URL }); + const { url } = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: successUrl() }); const page = await fetch(url); expect(page.status).toBe(200); const html = await page.text(); @@ -78,7 +82,7 @@ describe("autumn emulator: setup_payment (change the card on file)", () => { }); it("submitting the card redirects to success_url but does not yet replace the card", async () => { - const { url } = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: SUCCESS_URL }); + const { url } = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: successUrl() }); const sessionId = new URL(url).pathname.split("/").pop()!; const completed = await fetch(`${BASE}/checkout/setup/${sessionId}/complete`, { @@ -88,7 +92,7 @@ describe("autumn emulator: setup_payment (change the card on file)", () => { redirect: "manual", }); expect(completed.status, "completion redirects").toBe(302); - expect(completed.headers.get("location"), "back to the app").toBe(SUCCESS_URL); + expect(completed.headers.get("location"), "back to the app").toBe(successUrl()); // The webhook has not landed: the customer still has the OLD card (none). expect(await cardOnFile(CUSTOMER), "card unchanged before settle").toBeNull(); @@ -122,7 +126,7 @@ describe("autumn emulator: setup_payment (change the card on file)", () => { const before = await cardOnFile(CUSTOMER); expect(before?.card, "the first setup left a mastercard on file").toMatchObject({ last4: "4444" }); - const { url } = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: SUCCESS_URL }); + const { url } = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: successUrl() }); const sessionId = new URL(url).pathname.split("/").pop()!; await fetch(`${BASE}/checkout/setup/${sessionId}/complete`, { method: "POST", @@ -140,7 +144,7 @@ describe("autumn emulator: setup_payment (change the card on file)", () => { it("paying for a plan leaves a visa on file", async () => { const PAYING = "org_pays"; - const attach = await autumn.billing.attach({ customerId: PAYING, planId: "team", successUrl: SUCCESS_URL }); + const attach = await autumn.billing.attach({ customerId: PAYING, planId: "team", successUrl: successUrl() }); const sessionId = new URL(attach.paymentUrl!).pathname.split("/").pop()!; await fetch(`${BASE}/checkout/${sessionId}/complete`, { method: "POST", redirect: "manual" }); await fetch(`${BASE}/checkout/settle`, { @@ -156,17 +160,17 @@ describe("autumn emulator: setup_payment (change the card on file)", () => { describe("autumn emulator: billing portal (change the card on file)", () => { const CUSTOMER = "org_portal"; - const RETURN_URL = `${BASE}/settings/billing`; + const returnUrl = () => `${BASE}/settings/billing`; const openPortal = async (): Promise => { - const res = await autumn.billing.openCustomerPortal({ customerId: CUSTOMER, returnUrl: RETURN_URL }); + const res = await autumn.billing.openCustomerPortal({ customerId: CUSTOMER, returnUrl: returnUrl() }); expect(res.customerId).toBe(CUSTOMER); return res.url; }; it("the portal page shows the card on file and links back to the app", async () => { // Give the customer a card the only supported way: a first setup session. - const setup = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: SUCCESS_URL }); + const setup = await autumn.billing.setupPayment({ customerId: CUSTOMER, successUrl: successUrl() }); const sessionId = new URL(setup.url).pathname.split("/").pop()!; await fetch(`${BASE}/checkout/setup/${sessionId}/complete`, { method: "POST", @@ -186,7 +190,7 @@ describe("autumn emulator: billing portal (change the card on file)", () => { expect(html, "the current card brand").toContain("visa"); expect(html, "the current card last4").toContain("4242"); expect(html, "the update form").toContain("Update payment method"); - expect(html, "the return_url recorded when the portal was opened").toContain(`href="${RETURN_URL}"`); + expect(html, "the return_url recorded when the portal was opened").toContain(`href="${returnUrl()}"`); }); it("updating the card in the portal applies immediately, with no settle step", async () => { diff --git a/packages/@emulators/autumn/src/__tests__/autumn-trial.test.ts b/packages/@emulators/autumn/src/__tests__/autumn-trial.test.ts index 270437722..e99459602 100644 --- a/packages/@emulators/autumn/src/__tests__/autumn-trial.test.ts +++ b/packages/@emulators/autumn/src/__tests__/autumn-trial.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { Autumn } from "autumn-js"; import { autumnPlugin, seedFromConfig } from "../index.js"; @@ -9,14 +9,18 @@ import { manifest } from "../manifest.js"; // SDK (zod-validated responses) plus raw fetch for the hosted checkout page. // This is the contract the cloud app's billing UI depends on. -const PORT = 41875; -const BASE = `http://localhost:${PORT}`; -const SUCCESS_URL = `${BASE}/back-to-billing`; +let PORT = 0; +let BASE = ""; +const successUrl = () => `${BASE}/back-to-billing`; -let httpServer: ReturnType; +let httpServer: FreePortServer; let autumn: Autumn; -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(autumnPlugin, { port: PORT, baseUrl: BASE, @@ -36,12 +40,12 @@ beforeAll(() => { }, ], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); autumn = new Autumn({ secretKey: "am_test_emulate", serverURL: BASE }); }); afterAll(async () => { - await new Promise((resolve) => httpServer.close(() => resolve())); + await httpServer.close(); }); const teamPlan = async (customerId: string) => { @@ -67,7 +71,7 @@ describe("autumn emulator: card-required free-trial checkout", () => { }); it("attach returns a checkout payment URL (card required)", async () => { - const res = await autumn.billing.attach({ customerId: CUSTOMER, planId: "team", successUrl: SUCCESS_URL }); + const res = await autumn.billing.attach({ customerId: CUSTOMER, planId: "team", successUrl: successUrl() }); expect(res.paymentUrl, "a checkout URL is returned").toContain("/checkout/"); // Attaching alone must NOT activate the subscription: the customer is still @@ -80,7 +84,7 @@ describe("autumn emulator: card-required free-trial checkout", () => { const { paymentUrl } = await autumn.billing.attach({ customerId: CUSTOMER, planId: "team", - successUrl: SUCCESS_URL, + successUrl: successUrl(), }); const sessionId = new URL(paymentUrl!).pathname.split("/").pop()!; @@ -93,7 +97,7 @@ describe("autumn emulator: card-required free-trial checkout", () => { redirect: "manual", }); expect(completed.status, "completion redirects").toBe(302); - expect(completed.headers.get("location"), "back to the app").toBe(SUCCESS_URL); + expect(completed.headers.get("location"), "back to the app").toBe(successUrl()); // The webhook has not landed yet: the customer is STILL on free. This is the // exact window in which the billing UI shows the stale plan. diff --git a/packages/@emulators/autumn/src/__tests__/autumn.test.ts b/packages/@emulators/autumn/src/__tests__/autumn.test.ts index 33d089514..3800e20b2 100644 --- a/packages/@emulators/autumn/src/__tests__/autumn.test.ts +++ b/packages/@emulators/autumn/src/__tests__/autumn.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { Autumn } from "autumn-js"; import { autumnPlugin, seedFromConfig } from "../index.js"; @@ -7,16 +7,17 @@ import { manifest } from "../manifest.js"; // The real autumn-js SDK (zod-validated responses) against the emulator. -// Not 41874: workos.test.ts's TTL scenario binds PORT + 1 = 41874, and the -// package suites run concurrently under turbo, so sharing it is a latent -// EADDRINUSE flake. -const PORT = 41880; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; -let httpServer: ReturnType; +let httpServer: FreePortServer; let autumn: Autumn; -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(autumnPlugin, { port: PORT, baseUrl: BASE, @@ -42,12 +43,12 @@ beforeAll(() => { { id: "org_seats", subscriptions: [{ plan_id: "scale", status: "active" }] }, ], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); autumn = new Autumn({ secretKey: "am_test_emulate", serverURL: BASE }); }); afterAll(async () => { - await new Promise((resolve) => httpServer.close(() => resolve())); + await httpServer.close(); }); describe("autumn emulator with the real autumn-js SDK", () => { diff --git a/packages/@emulators/context/src/__tests__/context.test.ts b/packages/@emulators/context/src/__tests__/context.test.ts index 5476b2b2f..4b88c995a 100644 --- a/packages/@emulators/context/src/__tests__/context.test.ts +++ b/packages/@emulators/context/src/__tests__/context.test.ts @@ -1,13 +1,13 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { contextPlugin, seedFromConfig } from "../index.js"; import { manifest } from "../manifest.js"; -const PORT = 41893; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; -let httpServer: ReturnType; +let httpServer: FreePortServer; interface RetrieveResponse { partial: boolean; @@ -24,7 +24,11 @@ const retrieve = (body: unknown) => const retrieveJson = async (body: unknown): Promise => (await (await retrieve(body)).json()) as RetrieveResponse; -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(contextPlugin, { port: PORT, baseUrl: BASE, @@ -43,12 +47,10 @@ beforeAll(() => { { domain: "Enriching.Example", title: "Enriching", partial: true }, ], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); }); -afterAll(() => { - httpServer.close(); -}); +afterAll(() => httpServer.close()); describe("brand/retrieve", () => { it("resolves a seeded company from a work email address", async () => { diff --git a/packages/@emulators/core/src/http.ts b/packages/@emulators/core/src/http.ts index 153c4f478..6dbe4cb58 100644 --- a/packages/@emulators/core/src/http.ts +++ b/packages/@emulators/core/src/http.ts @@ -389,6 +389,41 @@ export function serve(options: ServeOptions): Server { return server; } +export interface FreePortServer { + server: Server; + /** The port the system chose, held for the server's whole life. */ + port: number; + /** Serve requests with this handler; until it is set they answer 503. */ + use(fetch: ServeOptions["fetch"]): void; + close(): Promise; +} + +/** + * Listen on a port the system chooses and keep it. An emulator's address names its + * port, so the emulator is built once the port is known and handed to `use`. Holding + * the socket from the start means nothing else can take the port in between, unlike + * choosing a fixed or "free" port and binding it later. + */ +export async function serveOnFreePort(options: { hostname?: string } = {}): Promise { + let handler: ServeOptions["fetch"] = () => new Response(null, { status: 503 }); + const server = serve({ fetch: (request) => handler(request), port: 0, hostname: options.hostname }); + await new Promise((resolve, reject) => { + if (server.listening) return resolve(); + server.once("listening", () => resolve()); + server.once("error", reject); + }); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("The server has no port."); + return { + server, + port: address.port, + use(fetch) { + handler = fetch; + }, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + function compilePath(pattern: string): CompiledPath { if (pattern === "*" || pattern === "/*") { return { pattern, regex: /^.*$/, paramNames: [] }; diff --git a/packages/@emulators/core/src/index.ts b/packages/@emulators/core/src/index.ts index 26b934842..1f450e4d4 100644 --- a/packages/@emulators/core/src/index.ts +++ b/packages/@emulators/core/src/index.ts @@ -19,6 +19,8 @@ export { HonoRequest, cors, serve, + serveOnFreePort, + type FreePortServer, type ContentfulStatusCode, type CorsOptions, type ErrorHandler, diff --git a/packages/@emulators/mcp/src/enterprise-managed-auth.test.ts b/packages/@emulators/mcp/src/enterprise-managed-auth.test.ts index 53c06c9d6..14feb3ba1 100644 --- a/packages/@emulators/mcp/src/enterprise-managed-auth.test.ts +++ b/packages/@emulators/mcp/src/enterprise-managed-auth.test.ts @@ -1,27 +1,30 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { manifest as workosManifest, seedFromConfig as seedWorkos, workosPlugin } from "@emulators/workos"; import type { LedgerEntry } from "@emulators/core"; import { mcpPlugin } from "./index.js"; -const WORKOS_PORT = 41883; -const MCP_PORT = 41884; -const WORKOS_BASE = `http://localhost:${WORKOS_PORT}`; -const MCP_BASE = `http://localhost:${MCP_PORT}`; +// Ports the system chooses, held from the start (see serveOnFreePort). +let WORKOS_BASE = ""; +let MCP_BASE = ""; const CLIENT_ID = "https://executor.test/client.json"; const TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; const JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; const ID_JAG_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id-jag"; const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; -let workosServer: ReturnType; -let mcpServer: ReturnType; +let workosServer: FreePortServer; +let mcpServer: FreePortServer; let workosLedger: { list: () => LedgerEntry[] }; let mcpLedger: { list: () => LedgerEntry[] }; beforeAll(async () => { + workosServer = await serveOnFreePort(); + mcpServer = await serveOnFreePort(); + WORKOS_BASE = `http://localhost:${workosServer.port}`; + MCP_BASE = `http://localhost:${mcpServer.port}`; const workos = createServer(workosPlugin, { - port: WORKOS_PORT, + port: workosServer.port, baseUrl: WORKOS_BASE, manifest: workosManifest, fallbackUser: { login: "sk_emulate_admin", id: 1, scopes: [] }, @@ -30,23 +33,20 @@ beforeAll(async () => { users: [{ email: "admin@localhost", first_name: "Admin" }], }); workosLedger = workos.ledger; - workosServer = serve({ fetch: workos.app.fetch, port: WORKOS_PORT }); + workosServer.use(workos.app.fetch); const mcp = createServer(mcpPlugin, { - port: MCP_PORT, + port: mcpServer.port, baseUrl: MCP_BASE, fallbackUser: { login: "admin", id: 1, scopes: [] }, }); mcpPlugin.seed?.(mcp.store, MCP_BASE); mcpLedger = mcp.ledger; - mcpServer = serve({ fetch: mcp.app.fetch, port: MCP_PORT }); + mcpServer.use(mcp.app.fetch); }); afterAll(async () => { - await Promise.all([ - new Promise((resolve) => workosServer.close(() => resolve())), - new Promise((resolve) => mcpServer.close(() => resolve())), - ]); + await Promise.all([workosServer.close(), mcpServer.close()]); }); async function workosAccessToken(loginHint: string): Promise { diff --git a/packages/@emulators/mcp/src/okta-enterprise-managed-auth.test.ts b/packages/@emulators/mcp/src/okta-enterprise-managed-auth.test.ts index 476219a2c..0d301a2db 100644 --- a/packages/@emulators/mcp/src/okta-enterprise-managed-auth.test.ts +++ b/packages/@emulators/mcp/src/okta-enterprise-managed-auth.test.ts @@ -1,15 +1,14 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { manifest as oktaManifest, oktaPlugin, seedFromConfig as seedOkta } from "@emulators/okta"; import type { LedgerEntry } from "@emulators/core"; import { decodeJwt } from "jose"; import { mcpPlugin } from "./index.js"; -const OKTA_PORT = 41893; -const MCP_PORT = 41894; -const OKTA_BASE = `http://localhost:${OKTA_PORT}`; -const MCP_BASE = `http://localhost:${MCP_PORT}`; -const OKTA_ISSUER = `${OKTA_BASE}/oauth2/default`; +// Ports the system chooses, held from the start (see serveOnFreePort). +let OKTA_BASE = ""; +let MCP_BASE = ""; +let OKTA_ISSUER = ""; const CLIENT_ID = "mcp-desktop-client"; const CLIENT_SECRET = "mcp-desktop-secret"; const REDIRECT_URI = "http://127.0.0.1:9/callback"; @@ -21,14 +20,19 @@ const JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; const ID_JAG_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id-jag"; const ID_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id_token"; -let oktaServer: ReturnType; -let mcpServer: ReturnType; +let oktaServer: FreePortServer; +let mcpServer: FreePortServer; let oktaLedger: { list: () => LedgerEntry[] }; let mcpLedger: { list: () => LedgerEntry[] }; beforeAll(async () => { + oktaServer = await serveOnFreePort(); + mcpServer = await serveOnFreePort(); + OKTA_BASE = `http://localhost:${oktaServer.port}`; + MCP_BASE = `http://localhost:${mcpServer.port}`; + OKTA_ISSUER = `${OKTA_BASE}/oauth2/default`; const okta = createServer(oktaPlugin, { - port: OKTA_PORT, + port: oktaServer.port, baseUrl: OKTA_BASE, manifest: oktaManifest, tokens: { [OKTA_API_TOKEN]: { login: "okta-admin", id: 1, scopes: ["okta.*"] } }, @@ -47,23 +51,20 @@ beforeAll(async () => { ], }); oktaLedger = okta.ledger; - oktaServer = serve({ fetch: okta.app.fetch, port: OKTA_PORT }); + oktaServer.use(okta.app.fetch); const mcp = createServer(mcpPlugin, { - port: MCP_PORT, + port: mcpServer.port, baseUrl: MCP_BASE, fallbackUser: { login: "admin", id: 1, scopes: [] }, }); mcpPlugin.seed?.(mcp.store, MCP_BASE); mcpLedger = mcp.ledger; - mcpServer = serve({ fetch: mcp.app.fetch, port: MCP_PORT }); + mcpServer.use(mcp.app.fetch); }); afterAll(async () => { - await Promise.all([ - new Promise((resolve) => oktaServer.close(() => resolve())), - new Promise((resolve) => mcpServer.close(() => resolve())), - ]); + await Promise.all([oktaServer.close(), mcpServer.close()]); }); /** OIDC single sign-on to the MCP client, ending with an Okta ID token. */ diff --git a/packages/@emulators/miro/src/__tests__/miro.test.ts b/packages/@emulators/miro/src/__tests__/miro.test.ts index cdf8baccd..d74bef219 100644 --- a/packages/@emulators/miro/src/__tests__/miro.test.ts +++ b/packages/@emulators/miro/src/__tests__/miro.test.ts @@ -1,30 +1,32 @@ import { createHash, randomBytes } from "crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { decodeProtectedHeader, jwtVerify } from "jose"; -import { createServer, serve, type Store } from "@emulators/core"; +import { createServer, type Store, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { miroPlugin, seedFromConfig } from "../index.js"; import { manifest } from "../manifest.js"; -const PORT = 41933; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; const REDIRECT = "http://127.0.0.1:8765/callback"; const SCOPES = ["boards:read", "boards:write", "openid", "email"]; const GRANTS = ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:jwt-bearer"]; -let httpServer: ReturnType; +let httpServer: FreePortServer; let store: Store; -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const server = createServer(miroPlugin, { port: PORT, baseUrl: BASE, manifest }); store = server.store; miroPlugin.seed?.(store, BASE); - httpServer = serve({ fetch: server.app.fetch, port: PORT }); + httpServer.use(server.app.fetch); }); -afterAll(() => { - httpServer.close(); -}); +afterAll(() => httpServer.close()); interface Registration { client_id: string; @@ -418,12 +420,12 @@ describe("refresh and revocation", () => { }); describe("MCP server", () => { - const challenge = `Bearer resource_metadata="${BASE}/.well-known/oauth-protected-resource"`; + const challenge = () => `Bearer resource_metadata="${BASE}/.well-known/oauth-protected-resource"`; it("challenges unauthenticated requests like Miro's gateway", async () => { const res = await mcp({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }); expect(res.status).toBe(401); - expect(res.headers.get("www-authenticate")).toBe(challenge); + expect(res.headers.get("www-authenticate")).toBe(challenge()); expect(await res.json()).toEqual({ error: "Authentication required" }); const invalid = await mcp({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }, "not-a-token"); @@ -432,7 +434,7 @@ describe("MCP server", () => { for (const path of ["/", "/.well-known/oauth-protected-resource/", "/.well-known/jwks.json"]) { const probe = await fetch(`${BASE}${path}`); expect(probe.status).toBe(401); - expect(probe.headers.get("www-authenticate")).toBe(challenge); + expect(probe.headers.get("www-authenticate")).toBe(challenge()); } }); diff --git a/packages/@emulators/planetscale/src/__tests__/planetscale.test.ts b/packages/@emulators/planetscale/src/__tests__/planetscale.test.ts index 63b3fa31f..6d5542652 100644 --- a/packages/@emulators/planetscale/src/__tests__/planetscale.test.ts +++ b/packages/@emulators/planetscale/src/__tests__/planetscale.test.ts @@ -1,33 +1,35 @@ import { createHash, randomBytes } from "crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import * as oauth from "oauth4webapi"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { planetscalePlugin, seedFromConfig } from "../index.js"; import { manifest } from "../manifest.js"; -const PORT = 41921; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; const REDIRECT = "http://127.0.0.1:8765/callback"; const INVALID_CLIENT_DESCRIPTION = "Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method."; const INVALID_GRANT_DESCRIPTION = "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."; -let httpServer: ReturnType; +let httpServer: FreePortServer; -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(planetscalePlugin, { port: PORT, baseUrl: BASE, manifest }); planetscalePlugin.seed?.(store, BASE); seedFromConfig(store, BASE, { organizations: [{ name: "globex", databases: [{ name: "orders", kind: "postgresql" }] }], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); }); -afterAll(() => { - httpServer.close(); -}); +afterAll(() => httpServer.close()); interface Registration { client_id: string; @@ -346,9 +348,10 @@ describe("oauth4webapi against the emulator", () => { }); describe("MCP server", () => { - const MCP = `${BASE}/mcp/planetscale`; + // Read when called: the base is known only once beforeAll has bound the port. + const mcpUrl = () => `${BASE}/mcp/planetscale`; const rpc = (token: string | undefined, body: unknown) => - fetch(MCP, { + fetch(mcpUrl(), { method: "POST", headers: { "content-type": "application/json", @@ -376,7 +379,7 @@ describe("MCP server", () => { }); const prm = await fetch(`${BASE}/.well-known/oauth-protected-resource/mcp/planetscale`); - expect(await prm.json()).toEqual({ resource: MCP, authorization_servers: [BASE] }); + expect(await prm.json()).toEqual({ resource: mcpUrl(), authorization_servers: [BASE] }); }); it("serves tools after the full authorize, PKCE, and token flow", async () => { diff --git a/packages/@emulators/posthog/src/__tests__/posthog.test.ts b/packages/@emulators/posthog/src/__tests__/posthog.test.ts index 35ee88b70..698f705f0 100644 --- a/packages/@emulators/posthog/src/__tests__/posthog.test.ts +++ b/packages/@emulators/posthog/src/__tests__/posthog.test.ts @@ -1,13 +1,21 @@ import { createHash } from "node:crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { Hono, Store, WebhookDispatcher, authMiddleware, serve, type TokenMap } from "@emulators/core"; +import { + Hono, + Store, + WebhookDispatcher, + authMiddleware, + type TokenMap, + serveOnFreePort, + type FreePortServer, +} from "@emulators/core"; import { getPostHogStore, posthogPlugin } from "../index.js"; -const PORT = 41876; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; -let httpServer: ReturnType; +let httpServer: FreePortServer; let app: Hono; let store: Store; @@ -15,7 +23,11 @@ function pkceChallenge(verifier: string): string { return createHash("sha256").update(verifier).digest("base64url"); } -beforeAll(() => { +beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; store = new Store(); const webhooks = new WebhookDispatcher(); const tokenMap: TokenMap = new Map(); @@ -36,11 +48,11 @@ beforeAll(() => { ); posthogPlugin.register(app as any, store, webhooks, BASE, tokenMap); posthogPlugin.seed?.(store, BASE); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); }); afterAll(async () => { - await new Promise((resolve) => httpServer.close(() => resolve())); + await httpServer.close(); }); describe("PostHog emulator OAuth discovery", () => { diff --git a/packages/@emulators/workos/src/__tests__/workos.test.ts b/packages/@emulators/workos/src/__tests__/workos.test.ts index 043f693e7..d7b68aa0a 100644 --- a/packages/@emulators/workos/src/__tests__/workos.test.ts +++ b/packages/@emulators/workos/src/__tests__/workos.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeAll, afterAll } from "vitest"; -import { createServer, serve } from "@emulators/core"; +import { createServer, serveOnFreePort, type FreePortServer } from "@emulators/core"; import { WorkOS } from "@workos-inc/node"; import { createRemoteJWKSet, decodeProtectedHeader, jwtVerify } from "jose"; @@ -10,18 +10,22 @@ import { manifest } from "../manifest.js"; // it unmodified, including sealed-session crypto (local iron seal with the // cookie password) and JWT verification against the emulator's JWKS. -const PORT = 41873; -const BASE = `http://localhost:${PORT}`; +let PORT = 0; +let BASE = ""; const CLIENT_ID = "client_emulate_test"; const COOKIE_PASSWORD = "emulate-cookie-password-0123456789abcdef0123456789"; const TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; const ID_JAG_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id-jag"; const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; -let httpServer: ReturnType; +let httpServer: FreePortServer; let workos: WorkOS; beforeAll(async () => { + // A port the system chooses, held from the start (see serveOnFreePort). + httpServer = await serveOnFreePort(); + PORT = httpServer.port; + BASE = `http://localhost:${PORT}`; const { app, store } = createServer(workosPlugin, { port: PORT, baseUrl: BASE, @@ -31,7 +35,7 @@ beforeAll(async () => { seedFromConfig(store, BASE, { users: [{ email: "seeded@example.com", first_name: "Seeded" }], }); - httpServer = serve({ fetch: app.fetch, port: PORT }); + httpServer.use(app.fetch); workos = new WorkOS("sk_test_emulate", { clientId: CLIENT_ID, apiHostname: "localhost", @@ -41,7 +45,7 @@ beforeAll(async () => { }); afterAll(async () => { - await new Promise((resolve) => httpServer.close(() => resolve())); + await httpServer.close(); }); async function signInAndGetCode(email: string): Promise { @@ -302,7 +306,7 @@ describe("workos emulator with the real @workos-inc/node SDK", () => { }); it("seeds organization metadata", async () => { - const { store } = createServer(workosPlugin, { port: PORT + 1, baseUrl: BASE, manifest }); + const { store } = createServer(workosPlugin, { baseUrl: BASE, manifest }); seedFromConfig(store, BASE, { organizations: [{ name: "Seeded Metadata Org", metadata: { plan: "free" } }] }); const org = getWorkosStoreFor(store).organizations.findOneBy("name", "Seeded Metadata Org"); expect(org?.metadata).toEqual({ plan: "free" }); @@ -620,21 +624,19 @@ describe("workos emulator with the real @workos-inc/node SDK", () => { it("honors the seeded default access-token TTL for plain DCR clients", async () => { const redirectUri = "http://127.0.0.1:9/callback"; + const server = await serveOnFreePort(); + const base = `http://localhost:${server.port}`; const { app, store } = createServer(workosPlugin, { - port: PORT + 1, - baseUrl: `http://localhost:${PORT + 1}`, + port: server.port, + baseUrl: base, manifest, fallbackUser: { login: "sk_emulate_admin", id: 1, scopes: [] }, }); - seedFromConfig(store, `http://localhost:${PORT + 1}`, { + seedFromConfig(store, base, { oauth: { default_access_token_ttl_seconds: 5 }, }); - const server = serve({ fetch: app.fetch, port: PORT + 1 }); - // serve() returns before the socket is listening; without this wait the - // first fetch races the listen and fails with ECONNREFUSED on slow runners. - await new Promise((resolve) => server.once("listening", resolve)); + server.use(app.fetch); try { - const base = `http://localhost:${PORT + 1}`; const registered = (await ( await fetch(`${base}/oauth2/register`, { method: "POST", @@ -662,7 +664,7 @@ describe("workos emulator with the real @workos-inc/node SDK", () => { ).json()) as { expires_in?: number }; expect(tokens.expires_in).toBe(5); } finally { - await new Promise((resolve) => server.close(() => resolve())); + await server.close(); } }); diff --git a/packages/emulate/src/__tests__/api.test.ts b/packages/emulate/src/__tests__/api.test.ts index de2bf7457..717fa55d5 100644 --- a/packages/emulate/src/__tests__/api.test.ts +++ b/packages/emulate/src/__tests__/api.test.ts @@ -5,9 +5,10 @@ describe("createEmulator", () => { // The first test in the suite pays the cold-start plugin import cost, which // can exceed the default 5s on CI runners (it hit 2.9s on a green run). it("starts github and returns a url", { timeout: 15000 }, async () => { - const github = await createEmulator({ service: "github", port: 14000 }); + const github = await createEmulator({ service: "github", port: 0 }); - expect(github.url).toBe("http://localhost:14000"); + expect(github.port).toBeGreaterThan(0); + expect(github.url).toBe(`http://localhost:${github.port}`); const res = await fetch(`${github.url}/user`, { headers: { Authorization: "token test_token_admin" }, @@ -20,7 +21,7 @@ describe("createEmulator", () => { }); it("starts github with the MCP OAuth metadata surface", async () => { - const github = await createEmulator({ service: "github", port: 14001 }); + const github = await createEmulator({ service: "github", port: 0 }); const resource = await fetch(`${github.url}/.well-known/oauth-protected-resource/mcp`); expect(resource.status).toBe(200); @@ -44,7 +45,7 @@ describe("createEmulator", () => { }); it("starts the standalone MCP emulator", async () => { - const mcp = await createEmulator({ service: "mcp", port: 14002 }); + const mcp = await createEmulator({ service: "mcp", port: 0 }); const res = await fetch(`${mcp.url}/.well-known/oauth-authorization-server`); expect(res.status).toBe(200); @@ -56,12 +57,14 @@ describe("createEmulator", () => { it("starts multiple services independently", async () => { const [github, vercel] = await Promise.all([ - createEmulator({ service: "github", port: 14010 }), - createEmulator({ service: "vercel", port: 14011 }), + createEmulator({ service: "github", port: 0 }), + createEmulator({ service: "vercel", port: 0 }), ]); - expect(github.url).toBe("http://localhost:14010"); - expect(vercel.url).toBe("http://localhost:14011"); + expect(github.port).toBeGreaterThan(0); + expect(github.url).toBe(`http://localhost:${github.port}`); + expect(vercel.port).toBeGreaterThan(0); + expect(vercel.url).toBe(`http://localhost:${vercel.port}`); await Promise.all([github.close(), vercel.close()]); }); @@ -69,7 +72,7 @@ describe("createEmulator", () => { it("reset wipes and re-seeds stores", async () => { const github = await createEmulator({ service: "github", - port: 14020, + port: 0, seed: { github: { users: [{ login: "test-user" }] } }, }); @@ -98,7 +101,7 @@ describe("createEmulator", () => { it("does not grant Slack fallback scopes in strict mode", async () => { const slack = await createEmulator({ service: "slack", - port: 14030, + port: 0, seed: { slack: { strict_scopes: true } }, }); @@ -122,7 +125,7 @@ describe("createEmulator", () => { }); it("creates GitHub bearer credentials through the control plane", async () => { - const github = await createEmulator({ service: "github", port: 14040 }); + const github = await createEmulator({ service: "github", port: 0 }); const credentialRes = await fetch(`${github.url}/_emulate/credentials`, { method: "POST", @@ -143,7 +146,7 @@ describe("createEmulator", () => { }); it("creates Spotify client credentials and exchanges them for an app token", async () => { - const spotify = await createEmulator({ service: "spotify", port: 14050 }); + const spotify = await createEmulator({ service: "spotify", port: 0 }); const credentialRes = await fetch(`${spotify.url}/_emulate/credentials`, { method: "POST", @@ -175,7 +178,7 @@ describe("createEmulator", () => { }); it("injects a one-shot fault into a real service emulator", async () => { - const spotify = await createEmulator({ service: "spotify", port: 14051 }); + const spotify = await createEmulator({ service: "spotify", port: 0 }); const credential = await spotify.credentials.mint({ type: "oauth-client-credentials", name: "Fault Test" }); const basic = Buffer.from(`${credential.client_id}:${credential.client_secret}`).toString("base64"); @@ -230,7 +233,7 @@ describe("createEmulator", () => { }); it("creates Microsoft OAuth client credentials and exchanges them for a Graph app token", async () => { - const microsoft = await createEmulator({ service: "microsoft", port: 14055 }); + const microsoft = await createEmulator({ service: "microsoft", port: 0 }); const credentialRes = await fetch(`${microsoft.url}/_emulate/credentials`, { method: "POST", @@ -272,7 +275,7 @@ describe("createEmulator", () => { }); it("creates AWS-style access keys through the control plane", async () => { - const aws = await createEmulator({ service: "aws", port: 14060 }); + const aws = await createEmulator({ service: "aws", port: 0 }); const credentialRes = await fetch(`${aws.url}/_emulate/credentials`, { method: "POST",