diff --git a/apps/cli/package.json b/apps/cli/package.json index a9b9c1f5a..71aec20b3 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -18,6 +18,7 @@ "build:publish": "bun run src/build.ts publish", "release:publish:dry-run": "bun run src/release.ts --dry-run", "release:publish": "bun run src/release.ts", + "test": "bun --bun vitest run", "typecheck": "tsgo --noEmit", "typecheck:slow": "tsc --noEmit" }, @@ -27,12 +28,15 @@ "@executor-js/integrations-registry": "workspace:*", "@executor-js/local": "workspace:*", "@executor-js/runtime-quickjs": "workspace:*", + "@executor-js/sdk": "workspace:*", "@jitl/quickjs-wasmfile-release-sync": "catalog:", "effect": "catalog:", "quickjs-emscripten": "catalog:" }, "devDependencies": { + "@effect/vitest": "catalog:", "bun-types": "catalog:", - "typescript": "catalog:" + "typescript": "catalog:", + "vitest": "catalog:" } } diff --git a/apps/cli/src/local-server-manifest.test.ts b/apps/cli/src/local-server-manifest.test.ts new file mode 100644 index 000000000..38175521b --- /dev/null +++ b/apps/cli/src/local-server-manifest.test.ts @@ -0,0 +1,100 @@ +import { afterEach, describe, expect, it } from "@effect/vitest"; +import { BunServices } from "@effect/platform-bun"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Path } from "effect"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; + +import { normalizeExecutorServerConnection } from "@executor-js/sdk/shared"; +import { + acquireLocalServerStartLock, + readLocalServerManifest, + releaseLocalServerStartLock, + removeLocalServerManifestIfOwnedBy, + resolveExecutorDataDir, + writeLocalServerManifest, +} from "./local-server-manifest"; + +const previousDataDir = process.env.EXECUTOR_DATA_DIR; + +afterEach(() => { + if (previousDataDir === undefined) { + delete process.env.EXECUTOR_DATA_DIR; + } else { + process.env.EXECUTOR_DATA_DIR = previousDataDir; + } +}); + +describe("local server manifest", () => { + it.effect("round-trips the active local server owner", () => + Effect.gen(function* () { + const dataDir = mkdtempSync(join(tmpdir(), "executor-local-server-")); + process.env.EXECUTOR_DATA_DIR = dataDir; + + try { + const manifest = { + version: 1 as const, + kind: "cli-daemon" as const, + pid: process.pid, + startedAt: "2026-05-28T00:00:00.000Z", + dataDir, + scopeDir: dataDir, + connection: normalizeExecutorServerConnection({ + origin: "http://localhost:4788", + }), + owner: { + client: "cli" as const, + version: "1.2.3", + executablePath: "/usr/local/bin/executor", + }, + }; + + yield* writeLocalServerManifest(manifest); + expect((yield* readLocalServerManifest())?.connection.origin).toBe("http://localhost:4788"); + + yield* removeLocalServerManifestIfOwnedBy({ pid: process.pid + 1 }); + expect(yield* readLocalServerManifest()).not.toBeNull(); + + yield* removeLocalServerManifestIfOwnedBy({ pid: process.pid }); + expect(yield* readLocalServerManifest()).toBeNull(); + } finally { + rmSync(dataDir, { recursive: true, force: true }); + } + }).pipe(Effect.provide(BunServices.layer)), + ); + + it.effect("serializes local startup with a stale-aware lock", () => + Effect.gen(function* () { + const dataDir = mkdtempSync(join(tmpdir(), "executor-local-server-lock-")); + process.env.EXECUTOR_DATA_DIR = dataDir; + + try { + const first = yield* acquireLocalServerStartLock(); + const second = yield* Effect.exit(acquireLocalServerStartLock()); + + expect(Exit.isFailure(second)).toBe(true); + yield* releaseLocalServerStartLock(first); + const third = yield* acquireLocalServerStartLock(); + yield* releaseLocalServerStartLock(third); + } finally { + rmSync(dataDir, { recursive: true, force: true }); + } + }).pipe(Effect.provide(BunServices.layer)), + ); + + it.effect("resolves the data dir from EXECUTOR_DATA_DIR", () => + Effect.gen(function* () { + const dataDir = mkdtempSync(join(tmpdir(), "executor-local-server-dir-")); + process.env.EXECUTOR_DATA_DIR = dataDir; + + try { + const path = yield* Path.Path; + expect(resolveExecutorDataDir(path)).toBe(dataDir); + } finally { + rmSync(dataDir, { recursive: true, force: true }); + } + }).pipe(Effect.provide(BunServices.layer)), + ); +}); diff --git a/apps/cli/src/local-server-manifest.ts b/apps/cli/src/local-server-manifest.ts new file mode 100644 index 000000000..7ec8abd8a --- /dev/null +++ b/apps/cli/src/local-server-manifest.ts @@ -0,0 +1,130 @@ +import { homedir } from "node:os"; +import { resolve } from "node:path"; +import { FileSystem, Option, Path, Schema } from "effect"; +import type { PlatformError } from "effect/PlatformError"; +import * as Effect from "effect/Effect"; + +import { + parseExecutorLocalServerManifest, + serializeExecutorLocalServerManifest, + type ExecutorLocalServerManifest, +} from "@executor-js/sdk/shared"; +import { isPidAlive } from "./daemon-state"; + +export interface LocalServerStartLock { + readonly path: string; +} + +export const resolveExecutorDataDir = (path: Path.Path): string => + resolve(process.env.EXECUTOR_DATA_DIR ?? path.join(homedir(), ".executor")); + +const serverControlDir = (path: Path.Path): string => + path.join(resolveExecutorDataDir(path), "server-control"); + +const localServerManifestPath = (path: Path.Path): string => + path.join(serverControlDir(path), "server.json"); + +const localServerStartLockPath = (path: Path.Path): string => + path.join(serverControlDir(path), "startup.lock"); + +export const readLocalServerManifest = (): Effect.Effect< + ExecutorLocalServerManifest | null, + never, + FileSystem.FileSystem | Path.Path +> => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const raw = yield* fs + .readFileString(localServerManifestPath(path)) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + if (raw === null) return null; + return parseExecutorLocalServerManifest(raw); + }); + +export const writeLocalServerManifest = ( + manifest: ExecutorLocalServerManifest, +): Effect.Effect => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.makeDirectory(serverControlDir(path), { recursive: true }); + yield* fs.writeFileString( + localServerManifestPath(path), + serializeExecutorLocalServerManifest(manifest), + ); + }); + +export const removeLocalServerManifestIfOwnedBy = (input: { + readonly pid: number; +}): Effect.Effect => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const manifestPath = localServerManifestPath(path); + const raw = yield* fs + .readFileString(manifestPath) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + if (raw === null) return; + const manifest = parseExecutorLocalServerManifest(raw); + if (manifest?.pid !== input.pid) return; + yield* fs.remove(manifestPath, { force: true }); + }); + +const StartupLockPayload = Schema.Struct({ + pid: Schema.Number, +}); + +const decodeStartupLockPayload = Schema.decodeUnknownOption( + Schema.fromJsonString(StartupLockPayload), +); + +const parseLockPid = (raw: string): number | null => { + const decoded = decodeStartupLockPayload(raw); + return Option.isSome(decoded) ? decoded.value.pid : null; +}; + +export const acquireLocalServerStartLock = (): Effect.Effect< + LocalServerStartLock, + Error, + FileSystem.FileSystem | Path.Path +> => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.makeDirectory(serverControlDir(path), { recursive: true }); + + const lockPath = localServerStartLockPath(path); + const lockPayload = `${JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }, null, 2)}\n`; + + const tryAcquire = () => + fs.writeFileString(lockPath, lockPayload, { flag: "wx" }).pipe( + Effect.as(true), + Effect.catchCause(() => Effect.succeed(false)), + ); + + if (yield* tryAcquire()) return { path: lockPath }; + + const existingRaw = yield* fs + .readFileString(lockPath) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + if (existingRaw !== null) { + const existingPid = parseLockPid(existingRaw); + if (existingPid !== null && !isPidAlive(existingPid)) { + yield* fs.remove(lockPath, { force: true }); + if (yield* tryAcquire()) return { path: lockPath }; + } + } + + return yield* Effect.fail( + new Error("Another local Executor server startup is already in progress."), + ); + }); + +export const releaseLocalServerStartLock = ( + lock: LocalServerStartLock, +): Effect.Effect => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(lock.path, { force: true }); + }); diff --git a/apps/cli/src/main.ts b/apps/cli/src/main.ts index 33fe8519c..bbc3187f8 100644 --- a/apps/cli/src/main.ts +++ b/apps/cli/src/main.ts @@ -52,13 +52,23 @@ if (typeof Bun !== "undefined" && (await Bun.file(wasmOnDisk).exists())) { import { Argument as Args, Command, Flag as Options } from "effect/unstable/cli"; import { BunRuntime, BunServices } from "@effect/platform-bun"; import { HttpApiClient } from "effect/unstable/httpapi"; -import { FetchHttpClient } from "effect/unstable/http"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http"; import { FileSystem, Path as PlatformPath } from "effect"; +import type { PlatformError } from "effect/PlatformError"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Cause from "effect/Cause"; import { ExecutorApi } from "@executor-js/api"; +import { + DEFAULT_EXECUTOR_SERVER_USERNAME, + getExecutorServerAuthorizationHeader, + normalizeExecutorServerConnection, + type ExecutorLocalServerKind, + type ExecutorLocalServerManifest, + type ExecutorServerConnection, + type ExecutorServerConnectionInput, +} from "@executor-js/sdk/shared"; import { startServer, runMcpStdioServer, getExecutor } from "@executor-js/local"; import { makeQuickJsExecutor } from "@executor-js/runtime-quickjs"; import { fetchIntegrations } from "./integrations"; @@ -86,6 +96,30 @@ import { writeDaemonPointer, writeDaemonRecord, } from "./daemon-state"; +import { + canAutoStartCliServerConnection, + chooseCliServerConnectionWithActiveLocal, + parseCliExecutorServerConnection, + type CliServerConnectionSource, + withCliServerAuthFallback, +} from "./server-connection"; +import { + acquireLocalServerStartLock, + readLocalServerManifest, + releaseLocalServerStartLock, + removeLocalServerManifestIfOwnedBy, + resolveExecutorDataDir, + writeLocalServerManifest, +} from "./local-server-manifest"; +import { + defaultCliServerConnectionProfile, + findCliServerConnectionProfile, + readCliServerConnectionStore, + removeCliServerConnectionProfile, + setDefaultCliServerConnectionProfile, + upsertCliServerConnectionProfile, + validateCliServerConnectionProfileName, +} from "./server-profile"; import { buildResumeContentTemplate, buildToolPath, @@ -146,9 +180,15 @@ interface DaemonScopeInfo { readonly dir: string; } -const readDaemonScopeInfo = (baseUrl: string): Effect.Effect => +const readDaemonScopeInfo = ( + baseUrl: string, + authorization?: string, +): Effect.Effect => Effect.tryPromise(() => - fetch(`${baseUrl}/api/scope`, { signal: AbortSignal.timeout(2000) }), + fetch(`${baseUrl}/api/scope`, { + ...(authorization ? { headers: { authorization } } : {}), + signal: AbortSignal.timeout(2000), + }), ).pipe( Effect.flatMap((res) => { if (!res.ok) return Effect.succeed(null); @@ -174,8 +214,38 @@ const readDaemonScopeInfo = (baseUrl: string): Effect.Effect Effect.succeed(null)), ); -const isServerReachable = (baseUrl: string): Effect.Effect => - readDaemonScopeInfo(baseUrl).pipe(Effect.map((scopeInfo) => scopeInfo !== null)); +const isServerReachable = (baseUrl: string, authorization?: string): Effect.Effect => + readDaemonScopeInfo(baseUrl, authorization).pipe(Effect.map((scopeInfo) => scopeInfo !== null)); + +const readActiveLocalServerManifest = (): Effect.Effect< + ExecutorLocalServerManifest | null, + Error, + FileSystem.FileSystem | PlatformPath.Path +> => + Effect.gen(function* () { + const manifest = yield* readLocalServerManifest(); + if (!manifest) return null; + + if (!isPidAlive(manifest.pid)) { + yield* removeLocalServerManifestIfOwnedBy({ pid: manifest.pid }).pipe(Effect.ignore); + return null; + } + + const authorization = getExecutorServerAuthorizationHeader(manifest.connection) ?? undefined; + if (yield* isServerReachable(manifest.connection.origin, authorization)) { + return manifest; + } + + return yield* Effect.fail( + new Error( + [ + `A local Executor ${manifest.kind} is registered at ${manifest.connection.origin} (pid ${manifest.pid}) but is not reachable.`, + "Refusing to start another local server against the same data directory.", + "Stop the existing process or remove the stale server-control manifest after verifying the process is not using the database.", + ].join("\n"), + ), + ); + }); const normalizeDaemonScopeDir = (dir: string): string => { const resolved = resolve(dir); @@ -185,6 +255,9 @@ const normalizeDaemonScopeDir = (dir: string): string => { const currentDaemonScopeDir = (): string => normalizeDaemonScopeDir(process.env.EXECUTOR_SCOPE_DIR ?? process.cwd()); +const currentScopeDirForManifest = (): string | null => + process.env.EXECUTOR_SCOPE_DIR ? normalizeDaemonScopeDir(process.env.EXECUTOR_SCOPE_DIR) : null; + const script = process.argv[1]; const isDevMode = isDevCliEntrypoint(script); const cliPrefix = isDevMode ? `bun run ${script}` : "executor"; @@ -192,6 +265,21 @@ const cliPrefix = isDevMode ? `bun run ${script}` : "executor"; const toError = (cause: unknown): Error => cause instanceof Error ? cause : new Error(String(cause)); +interface ServerTarget { + readonly baseUrl?: string; + readonly serverName?: string; +} + +interface RequestedExecutorServerConnection { + readonly connection: ExecutorServerConnection; + readonly source: CliServerConnectionSource; +} + +interface ExecuteCodeResult { + readonly connection: ExecutorServerConnection; + readonly outcome: ExecuteCodeOutcome; +} + const parseDaemonUrl = (baseUrl: string) => Effect.try({ try: () => parseDaemonBaseUrl(baseUrl, DEFAULT_PORT), @@ -199,9 +287,81 @@ const parseDaemonUrl = (baseUrl: string) => cause instanceof Error ? cause : new Error(`Invalid base URL: ${String(cause)}`), }); +const parseExecutorServerConnection = (baseUrl: string) => + Effect.try({ + try: () => parseCliExecutorServerConnection(baseUrl), + catch: (cause) => + cause instanceof Error ? cause : new Error(`Invalid server URL: ${String(cause)}`), + }); + const daemonBaseUrl = (hostname: string, port: number): string => `http://${canonicalDaemonHost(hostname)}:${port}`; +const serverAuthFromInputs = (input: { + readonly authToken: string | undefined; + readonly authPassword: string | undefined; +}): ExecutorServerConnection["auth"] | undefined => { + if (input.authPassword) { + return { + kind: "basic", + username: DEFAULT_EXECUTOR_SERVER_USERNAME, + password: input.authPassword, + }; + } + if (input.authToken) return { kind: "bearer", token: input.authToken }; + return undefined; +}; + +const makeLocalServerManifest = (input: { + readonly kind: ExecutorLocalServerKind; + readonly connection: ExecutorServerConnection; +}): Effect.Effect => + Effect.gen(function* () { + const path = yield* PlatformPath.Path; + return { + version: 1, + kind: input.kind, + pid: process.pid, + startedAt: new Date().toISOString(), + dataDir: resolveExecutorDataDir(path), + scopeDir: currentScopeDirForManifest(), + connection: input.connection, + owner: { + client: "cli", + version: CLI_VERSION, + executablePath: isDevMode ? (script ?? null) : process.execPath, + }, + }; + }); + +const assertNoOtherActiveLocalServer = (): Effect.Effect< + void, + Error, + FileSystem.FileSystem | PlatformPath.Path +> => + Effect.gen(function* () { + const active = yield* readActiveLocalServerManifest(); + if (!active || active.pid === process.pid) return; + return yield* Effect.fail( + new Error( + [ + `A local Executor ${active.kind} is already running at ${active.connection.origin} (pid ${active.pid}).`, + `It owns the current data directory: ${active.dataDir}`, + "Stop it before starting another local server.", + ].join("\n"), + ), + ); + }); + +const publishLocalServerManifest = (input: { + readonly kind: ExecutorLocalServerKind; + readonly connection: ExecutorServerConnection; +}): Effect.Effect => + Effect.gen(function* () { + const manifest = yield* makeLocalServerManifest(input); + yield* writeLocalServerManifest(manifest); + }); + const installDefaultExecutorWebBaseUrl = (baseUrl: string): (() => void) => { if (process.env.EXECUTOR_WEB_BASE_URL !== undefined) { return () => {}; @@ -343,6 +503,23 @@ const ensureDaemon = ( return resolvedTarget.baseUrl; } + const active = yield* readActiveLocalServerManifest(); + if ( + active && + normalizeExecutorServerConnection({ origin: active.connection.origin }).origin !== + normalizeExecutorServerConnection({ origin: resolvedTarget.baseUrl }).origin + ) { + return yield* Effect.fail( + new Error( + [ + `A local Executor ${active.kind} is already running at ${active.connection.origin} (pid ${active.pid}).`, + `It owns the current data directory: ${active.dataDir}`, + "Refusing to start another local daemon against the same database.", + ].join("\n"), + ), + ); + } + const parsed = yield* parseDaemonUrl(baseUrl); const host = canonicalDaemonHost(parsed.hostname); @@ -366,6 +543,99 @@ const ensureDaemon = ( }); }).pipe(Effect.mapError(toError)); +const resolveRequestedExecutorServerConnection = ( + target: ServerTarget, +): Effect.Effect< + RequestedExecutorServerConnection, + Error, + FileSystem.FileSystem | PlatformPath.Path +> => + Effect.gen(function* () { + if (target.baseUrl && target.serverName) { + return yield* Effect.fail(new Error("Use either --server or --base-url, not both.")); + } + + if (target.serverName) { + const store = yield* readCliServerConnectionStore(); + const profile = findCliServerConnectionProfile(store, target.serverName); + if (!profile) { + return yield* Effect.fail(new Error(`No server profile named "${target.serverName}".`)); + } + return { connection: withCliServerAuthFallback(profile.connection), source: "explicit" }; + } + + if (!target.baseUrl) { + const store = yield* readCliServerConnectionStore(); + const profile = defaultCliServerConnectionProfile(store); + if (profile) { + return { + connection: withCliServerAuthFallback(profile.connection), + source: "default-profile", + }; + } + + const active = yield* readActiveLocalServerManifest(); + if (active) return { connection: active.connection, source: "active-local" }; + } + + return { + connection: yield* parseExecutorServerConnection(target.baseUrl ?? DEFAULT_BASE_URL), + source: target.baseUrl ? "explicit" : "implicit-default", + }; + }); + +const resolveExecutorServerConnection = ( + target: ServerTarget, +): Effect.Effect => + Effect.gen(function* () { + const requestedResult = yield* resolveRequestedExecutorServerConnection(target); + const active = yield* readActiveLocalServerManifest(); + const decision = chooseCliServerConnectionWithActiveLocal({ + requested: requestedResult.connection, + source: requestedResult.source, + active, + }); + + if (decision.kind === "conflict") { + return yield* Effect.fail( + new Error( + [ + `A local Executor ${decision.active.kind} is already running at ${decision.active.connection.origin} (pid ${decision.active.pid}).`, + `It owns the current data directory: ${decision.active.dataDir}`, + "Refusing to auto-start another local server against the same database.", + `Use the active server, or stop it before starting ${cliPrefix} daemon run.`, + ].join("\n"), + ), + ); + } + + const requested = decision.connection; + if (decision.kind === "use-active") return requested; + + if (!canAutoStartCliServerConnection(requested)) { + const authorization = getExecutorServerAuthorizationHeader(requested) ?? undefined; + if (yield* isServerReachable(requested.origin, authorization)) { + return requested; + } + return yield* Effect.fail( + new Error( + [ + `Executor server is not reachable at ${requested.origin}.`, + "For hosted Executor, set EXECUTOR_API_KEY to a bearer API key.", + "For password-protected local or desktop servers, set EXECUTOR_AUTH_PASSWORD.", + "For unauthenticated local Executor, use an http://localhost or http://127.0.0.1 server URL.", + ].join("\n"), + ), + ); + } + + const daemonUrl = yield* ensureDaemon(requested.origin); + return normalizeExecutorServerConnection({ + ...requested, + origin: daemonUrl, + }); + }).pipe(Effect.mapError(toError)); + const stopDaemon = ( baseUrl: string, ): Effect.Effect => @@ -434,6 +704,7 @@ const stopDaemon = ( yield* removeDaemonRecord({ hostname: host, port: target.port }); yield* removeDaemonPointer({ hostname: host, scopeId }).pipe(Effect.ignore); + yield* removeLocalServerManifestIfOwnedBy({ pid: record.pid }).pipe(Effect.ignore); console.log(`Daemon stopped at ${target.baseUrl}.`); }).pipe(Effect.mapError(toError)); @@ -463,12 +734,12 @@ const buildResumeApprovalUrl = (baseUrl: string, executionId: string): string => }; const executeCode = (input: { - baseUrl: string; + target: ServerTarget; code: string; -}): Effect.Effect => +}): Effect.Effect => Effect.gen(function* () { - const daemonUrl = yield* ensureDaemon(input.baseUrl); - const client = yield* makeApiClient(daemonUrl); + const connection = yield* resolveExecutorServerConnection(input.target); + const client = yield* makeApiClient(connection); const response = yield* client.executions.execute({ payload: { code: input.code, @@ -478,11 +749,16 @@ const executeCode = (input: { if (response.status === "paused") { const executionId = extractExecutionId(response.structured); return { - status: "paused" as const, - text: response.text, - executionId, - approvalUrl: executionId ? buildResumeApprovalUrl(daemonUrl, executionId) : undefined, - interaction: extractPausedInteraction(response.structured), + connection, + outcome: { + status: "paused" as const, + text: response.text, + executionId, + approvalUrl: executionId + ? buildResumeApprovalUrl(connection.origin, executionId) + : undefined, + interaction: extractPausedInteraction(response.structured), + }, }; } @@ -491,12 +767,27 @@ const executeCode = (input: { } return { - status: "completed" as const, - result: extractExecutionResult(response.structured), + connection, + outcome: { + status: "completed" as const, + result: extractExecutionResult(response.structured), + }, }; }).pipe(Effect.mapError(toError)); -const printExecutionOutcome = (input: { baseUrl: string; outcome: ExecuteCodeOutcome }) => +const serverTargetResumeFlag = ( + target: ServerTarget, + connection: ExecutorServerConnection, +): string => + target.serverName + ? `--server ${shellQuoteArg(target.serverName)}` + : `--base-url ${shellQuoteArg(target.baseUrl ?? connection.origin)}`; + +const printExecutionOutcome = (input: { + target: ServerTarget; + connection: ExecutorServerConnection; + outcome: ExecuteCodeOutcome; +}) => Effect.sync(() => { if (input.outcome.status === "paused") { console.log(input.outcome.text); @@ -505,7 +796,7 @@ const printExecutionOutcome = (input: { baseUrl: string; outcome: ExecuteCodeOut console.log("\nApprove in browser:"); console.log(` ${input.outcome.approvalUrl}`); } - const commandPrefix = `${cliPrefix} resume --execution-id ${input.outcome.executionId} --base-url ${input.baseUrl}`; + const commandPrefix = `${cliPrefix} resume --execution-id ${input.outcome.executionId} ${serverTargetResumeFlag(input.target, input.connection)}`; if (input.outcome.interaction?.kind === "form") { const requestedSchema = input.outcome.interaction.requestedSchema; if (requestedSchema && Object.keys(requestedSchema).length > 0) { @@ -537,10 +828,19 @@ const printExecutionOutcome = (input: { baseUrl: string; outcome: ExecuteCodeOut // Typed API client // --------------------------------------------------------------------------- -const makeApiClient = (baseUrl: string) => - HttpApiClient.make(ExecutorApi, { baseUrl: `${baseUrl}/api` }).pipe( - Effect.provide(FetchHttpClient.layer), - ); +const makeApiClient = (connection: ExecutorServerConnection) => { + const authorization = getExecutorServerAuthorizationHeader(connection); + return HttpApiClient.make(ExecutorApi, { + baseUrl: connection.apiBaseUrl, + ...(authorization + ? { + transformClient: HttpClient.mapRequest((request) => + HttpClientRequest.setHeader(request, "authorization", authorization), + ), + } + : {}), + }).pipe(Effect.provide(FetchHttpClient.layer)); +}; // --------------------------------------------------------------------------- // Foreground session @@ -561,39 +861,65 @@ const runForegroundSession = (input: { ); try { - const server = yield* Effect.promise(() => - startServer({ - port: input.port, - hostname: input.hostname, - allowedHosts: input.allowedHosts, - authToken: input.authToken, - authPassword: input.authPassword, - embeddedWebUI, - }), - ); + const startupLock = yield* acquireLocalServerStartLock(); + let server: Awaited> | null = null; + let baseUrl: string | null = null; - const baseUrl = `http://${displayHost}:${server.port}`; - console.log(`Executor is ready.`); - console.log(`Web: ${baseUrl}`); - console.log(`MCP: ${baseUrl}/mcp`); - console.log(`OpenAPI: ${baseUrl}/api/docs`); - if (input.hostname !== "127.0.0.1" && input.hostname !== "localhost") { - console.log( - `\n⚠ Listening on ${input.hostname}. Executor runs arbitrary commands — only expose on trusted networks.`, + try { + yield* assertNoOtherActiveLocalServer(); + server = yield* Effect.promise(() => + startServer({ + port: input.port, + hostname: input.hostname, + allowedHosts: input.allowedHosts, + authToken: input.authToken, + authPassword: input.authPassword, + embeddedWebUI, + }), ); - if (input.allowedHosts.length > 0) { - console.log(` Extra allowed Host headers: ${input.allowedHosts.join(", ")}`); - } - if (input.authPassword) { - console.log(" Basic authentication is enabled."); - } else if (input.authToken) { - console.log(" Token authentication is enabled."); - } + baseUrl = `http://${displayHost}:${server.port}`; + yield* publishLocalServerManifest({ + kind: "foreground", + connection: normalizeExecutorServerConnection({ + kind: "http", + origin: baseUrl, + displayName: "CLI web", + auth: serverAuthFromInputs(input), + }), + }); + } finally { + yield* releaseLocalServerStartLock(startupLock).pipe(Effect.ignore); + } + + if (!server || !baseUrl) { + return yield* Effect.fail(new Error("Failed to start local Executor server.")); } - console.log(`\nPress Ctrl+C to stop.`); - yield* waitForShutdownSignal(); - yield* Effect.promise(() => server.stop()); + try { + console.log(`Executor is ready.`); + console.log(`Web: ${baseUrl}`); + console.log(`MCP: ${baseUrl}/mcp`); + console.log(`OpenAPI: ${baseUrl}/api/docs`); + if (input.hostname !== "127.0.0.1" && input.hostname !== "localhost") { + console.log( + `\n⚠ Listening on ${input.hostname}. Executor runs arbitrary commands — only expose on trusted networks.`, + ); + if (input.allowedHosts.length > 0) { + console.log(` Extra allowed Host headers: ${input.allowedHosts.join(", ")}`); + } + if (input.authPassword) { + console.log(" Basic authentication is enabled."); + } else if (input.authToken) { + console.log(" Token authentication is enabled."); + } + } + console.log(`\nPress Ctrl+C to stop.`); + + yield* waitForShutdownSignal(); + } finally { + yield* Effect.promise(() => server.stop()); + yield* removeLocalServerManifestIfOwnedBy({ pid: process.pid }).pipe(Effect.ignore); + } } finally { restoreWebBaseUrl(); } @@ -614,37 +940,62 @@ const runDaemonSession = (input: { const scopeId = currentDaemonScopeId(); try { - const existing = yield* readDaemonPointer({ hostname: daemonHost, scopeId }); + const startupLock = yield* acquireLocalServerStartLock(); + let server: Awaited> | null = null; + let daemonPort: number | null = null; + let token: string | null = null; - if (existing) { - const existingUrl = daemonBaseUrl(existing.hostname, existing.port); - if (isPidAlive(existing.pid) && (yield* isServerReachable(existingUrl))) { - return yield* Effect.fail( - new Error( - [ - `A daemon is already running for scope ${scopeId} on ${daemonHost}.`, - `Existing daemon: ${existingUrl} (pid ${existing.pid}).`, - `Stop it first: ${cliPrefix} daemon stop`, - ].join("\n"), - ), - ); + try { + yield* assertNoOtherActiveLocalServer(); + + const existing = yield* readDaemonPointer({ hostname: daemonHost, scopeId }); + + if (existing) { + const existingUrl = daemonBaseUrl(existing.hostname, existing.port); + if (isPidAlive(existing.pid) && (yield* isServerReachable(existingUrl))) { + return yield* Effect.fail( + new Error( + [ + `A daemon is already running for scope ${scopeId} on ${daemonHost}.`, + `Existing daemon: ${existingUrl} (pid ${existing.pid}).`, + `Stop it first: ${cliPrefix} daemon stop`, + ].join("\n"), + ), + ); + } + yield* cleanupPointer({ hostname: existing.hostname, scopeId, port: existing.port }); } - yield* cleanupPointer({ hostname: existing.hostname, scopeId, port: existing.port }); - } - const server = yield* Effect.promise(() => - startServer({ - port: input.port, - hostname: input.hostname, - allowedHosts: input.allowedHosts, - authToken: input.authToken, - authPassword: input.authPassword, - embeddedWebUI, - }), - ); + server = yield* Effect.promise(() => + startServer({ + port: input.port, + hostname: input.hostname, + allowedHosts: input.allowedHosts, + authToken: input.authToken, + authPassword: input.authPassword, + embeddedWebUI, + }), + ); + + daemonPort = server.port; + token = randomUUID(); + const daemonUrl = daemonBaseUrl(daemonHost, daemonPort); + yield* publishLocalServerManifest({ + kind: "cli-daemon", + connection: normalizeExecutorServerConnection({ + kind: "http", + origin: daemonUrl, + displayName: "CLI daemon", + auth: serverAuthFromInputs(input), + }), + }); + } finally { + yield* releaseLocalServerStartLock(startupLock).pipe(Effect.ignore); + } - const daemonPort = server.port; - const token = randomUUID(); + if (!server || daemonPort === null || token === null) { + return yield* Effect.fail(new Error("Failed to start local Executor daemon.")); + } try { yield* writeDaemonRecord({ @@ -674,6 +1025,7 @@ const runDaemonSession = (input: { yield* Effect.promise(() => server.stop()); yield* removeDaemonRecord({ hostname: daemonHost, port: daemonPort }); yield* removeDaemonPointer({ hostname: daemonHost, scopeId }).pipe(Effect.ignore); + yield* removeLocalServerManifestIfOwnedBy({ pid: process.pid }).pipe(Effect.ignore); } } finally { restoreWebBaseUrl(); @@ -748,30 +1100,57 @@ const withStdoutReroutedToStderr = async (body: () => Promise): Promise const runStdioMcpSession = (input: { readonly elicitationMode: "browser" | "model" }) => Effect.gen(function* () { - const web = yield* Effect.promise(() => - withStdoutReroutedToStderr(async () => { - const host = "127.0.0.1"; - const port = await Effect.runPromise( - chooseDaemonPort({ preferredPort: DEFAULT_PORT, hostname: host }), - ); - const baseUrl = `http://localhost:${port}`; - const restoreWebBaseUrl = installDefaultExecutorWebBaseUrl(baseUrl); - - try { - const executor = await getExecutor(); - const server = await startServer({ - port, - hostname: host, - embeddedWebUI, - }); - const serverBaseUrl = `http://localhost:${server.port}`; - return { executor, server, baseUrl: serverBaseUrl, restoreWebBaseUrl }; - } catch (cause) { - restoreWebBaseUrl(); - throw cause; - } - }), - ); + const startupLock = yield* acquireLocalServerStartLock(); + let web: Awaited< + ReturnType< + typeof withStdoutReroutedToStderr<{ + readonly executor: Awaited>; + readonly server: Awaited>; + readonly baseUrl: string; + readonly restoreWebBaseUrl: () => void; + }> + > + > | null = null; + + try { + yield* assertNoOtherActiveLocalServer(); + web = yield* Effect.promise(() => + withStdoutReroutedToStderr(async () => { + const host = "127.0.0.1"; + const port = await Effect.runPromise( + chooseDaemonPort({ preferredPort: DEFAULT_PORT, hostname: host }), + ); + const baseUrl = `http://localhost:${port}`; + const restoreWebBaseUrl = installDefaultExecutorWebBaseUrl(baseUrl); + + try { + const executor = await getExecutor(); + const server = await startServer({ + port, + hostname: host, + embeddedWebUI, + }); + const serverBaseUrl = `http://localhost:${server.port}`; + return { executor, server, baseUrl: serverBaseUrl, restoreWebBaseUrl }; + } catch (cause) { + restoreWebBaseUrl(); + throw cause; + } + }), + ); + yield* publishLocalServerManifest({ + kind: "foreground", + connection: normalizeExecutorServerConnection({ + kind: "http", + origin: web.baseUrl, + displayName: "CLI MCP", + }), + }); + } finally { + yield* releaseLocalServerStartLock(startupLock).pipe(Effect.ignore); + } + + if (!web) return yield* Effect.fail(new Error("Failed to start local Executor MCP server.")); try { yield* Effect.promise(() => @@ -791,6 +1170,7 @@ const runStdioMcpSession = (input: { readonly elicitationMode: "browser" | "mode } finally { web.restoreWebBaseUrl(); yield* Effect.promise(() => web.server.stop()); + yield* removeLocalServerManifestIfOwnedBy({ pid: process.pid }).pipe(Effect.ignore); } }); @@ -799,6 +1179,31 @@ const scope = Options.string("scope").pipe( Options.withDescription("Path to workspace directory containing executor.jsonc"), ); +const serverBaseUrl = Options.string("base-url").pipe( + Options.optional, + Options.withDescription( + "Executor server origin. Overrides the default profile; local URLs auto-start the daemon.", + ), +); + +const serverProfile = Options.string("server").pipe( + Options.optional, + Options.withDescription("Named Executor server profile."), +); + +const daemonBaseUrlOption = Options.string("base-url").pipe( + Options.withDefault(DEFAULT_BASE_URL), + Options.withDescription("Local daemon origin."), +); + +const serverTargetFromOptions = (input: { + readonly baseUrl: Option.Option; + readonly server: Option.Option; +}): ServerTarget => ({ + baseUrl: Option.getOrUndefined(input.baseUrl), + serverName: Option.getOrUndefined(input.server), +}); + const applyScope = (s: Option.Option) => { const dir = Option.getOrUndefined(s); if (dir) process.env.EXECUTOR_SCOPE_DIR = resolve(dir); @@ -866,7 +1271,8 @@ const parsePositiveIntegerOption = (name: string, raw: string): number => { interface ParsedCallHelpArgs { readonly pathParts: ReadonlyArray; - readonly baseUrl: string; + readonly baseUrl: string | undefined; + readonly serverName: string | undefined; readonly scopeDir: string | undefined; readonly match: string | undefined; readonly limit: number | undefined; @@ -877,7 +1283,8 @@ const HELP_FLAGS = new Set(["--help", "-h"]); const isHelpFlag = (value: string): boolean => HELP_FLAGS.has(value); const parseCallHelpArgs = (args: ReadonlyArray): ParsedCallHelpArgs => { - let baseUrl = DEFAULT_BASE_URL; + let baseUrl: string | undefined = undefined; + let serverName: string | undefined = undefined; let scopeDir: string | undefined = undefined; let match: string | undefined = undefined; let limit: number | undefined = undefined; @@ -899,6 +1306,18 @@ const parseCallHelpArgs = (args: ReadonlyArray): ParsedCallHelpArgs => { continue; } + if (token === "--server") { + const value = args[index + 1]; + if (!value) throw new Error("Missing value for --server"); + serverName = value; + index += 1; + continue; + } + if (token.startsWith("--server=")) { + serverName = token.slice("--server=".length); + continue; + } + if (token === "--scope") { const value = args[index + 1]; if (!value) throw new Error("Missing value for --scope"); @@ -958,7 +1377,7 @@ const parseCallHelpArgs = (args: ReadonlyArray): ParsedCallHelpArgs => { pathParts.pop(); } - return { pathParts, baseUrl, scopeDir, match, limit }; + return { pathParts, baseUrl, serverName, scopeDir, match, limit }; }; const printCallBrowseHelp = (input: { @@ -1097,8 +1516,11 @@ const runCallHelp = ( Effect.gen(function* () { if (args.scopeDir) process.env.EXECUTOR_SCOPE_DIR = resolve(args.scopeDir); - const daemonUrl = yield* ensureDaemon(args.baseUrl); - const client = yield* makeApiClient(daemonUrl); + const connection = yield* resolveExecutorServerConnection({ + baseUrl: args.baseUrl, + serverName: args.serverName, + }); + const client = yield* makeApiClient(connection); const scopeInfo = yield* client.scope.info(); const tools = yield* client.tools.list({ params: { scopeId: scopeInfo.id } }); const toolPaths = tools.map((tool) => tool.id); @@ -1257,12 +1679,14 @@ const callCommand = Command.make( "call", { pathParts: Args.string("tool-path-segment").pipe(Args.variadic({})), - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: serverBaseUrl, + server: serverProfile, scope, }, - ({ pathParts, baseUrl, scope }) => + ({ pathParts, baseUrl, server, scope }) => Effect.gen(function* () { applyScope(scope); + const target = serverTargetFromOptions({ baseUrl, server }); const { path, args } = yield* resolveToolInvocation({ rawPathParts: pathParts, }); @@ -1272,8 +1696,12 @@ const callCommand = Command.make( cause instanceof Error ? cause : new Error(`Invalid tool path: ${String(cause)}`), }); - const outcome = yield* executeCode({ baseUrl, code }); - yield* printExecutionOutcome({ baseUrl, outcome }); + const result = yield* executeCode({ target, code }); + yield* printExecutionOutcome({ + target, + connection: result.connection, + outcome: result.outcome, + }); }), ).pipe( Command.withDescription( @@ -1295,17 +1723,19 @@ const resumeCommand = Command.make( Options.optional, Options.withDescription("JSON object to send when action=accept"), ), - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: serverBaseUrl, + server: serverProfile, scope, }, - ({ executionId, action, content, baseUrl, scope }) => + ({ executionId, action, content, baseUrl, server, scope }) => Effect.gen(function* () { applyScope(scope); - const daemonUrl = yield* ensureDaemon(baseUrl); + const target = serverTargetFromOptions({ baseUrl, server }); + const connection = yield* resolveExecutorServerConnection(target); const contentObj = yield* parseOptionalJsonObject(Option.getOrUndefined(content)); - const client = yield* makeApiClient(daemonUrl); + const client = yield* makeApiClient(connection); const result = yield* client.executions.resume({ params: { executionId }, payload: { action, content: contentObj }, @@ -1317,7 +1747,7 @@ const resumeCommand = Command.make( if (nextExecutionId) { console.log(""); console.log("Approval required:"); - console.log(buildResumeApprovalUrl(daemonUrl, nextExecutionId)); + console.log(buildResumeApprovalUrl(connection.origin, nextExecutionId)); } process.exit(0); } @@ -1347,20 +1777,26 @@ const toolsSearchCommand = Command.make( query: Args.string("query"), namespace: Options.string("namespace").pipe(Options.optional), limit: Options.integer("limit").pipe(Options.withDefault(12)), - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: serverBaseUrl, + server: serverProfile, scope, }, - ({ query, namespace, limit, baseUrl, scope }) => + ({ query, namespace, limit, baseUrl, server, scope }) => Effect.gen(function* () { applyScope(scope); + const target = serverTargetFromOptions({ baseUrl, server }); const code = buildSearchToolsCode({ query, namespace: Option.getOrUndefined(namespace), limit, }); - const outcome = yield* executeCode({ baseUrl, code }); - yield* printExecutionOutcome({ baseUrl, outcome }); + const result = yield* executeCode({ target, code }); + yield* printExecutionOutcome({ + target, + connection: result.connection, + outcome: result.outcome, + }); }), ).pipe(Command.withDescription("Search tools by natural-language query")); @@ -1369,19 +1805,25 @@ const toolsSourcesCommand = Command.make( { query: Options.string("query").pipe(Options.optional), limit: Options.integer("limit").pipe(Options.withDefault(50)), - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: serverBaseUrl, + server: serverProfile, scope, }, - ({ query, limit, baseUrl, scope }) => + ({ query, limit, baseUrl, server, scope }) => Effect.gen(function* () { applyScope(scope); + const target = serverTargetFromOptions({ baseUrl, server }); const code = buildListSourcesCode({ query: Option.getOrUndefined(query), limit, }); - const outcome = yield* executeCode({ baseUrl, code }); - yield* printExecutionOutcome({ baseUrl, outcome }); + const result = yield* executeCode({ target, code }); + yield* printExecutionOutcome({ + target, + connection: result.connection, + outcome: result.outcome, + }); }), ).pipe(Command.withDescription("List configured sources and tool counts")); @@ -1389,15 +1831,21 @@ const toolsDescribeCommand = Command.make( "describe", { path: Args.string("path"), - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: serverBaseUrl, + server: serverProfile, scope, }, - ({ path, baseUrl, scope }) => + ({ path, baseUrl, server, scope }) => Effect.gen(function* () { applyScope(scope); + const target = serverTargetFromOptions({ baseUrl, server }); const code = buildDescribeToolCode(path); - const outcome = yield* executeCode({ baseUrl, code }); - yield* printExecutionOutcome({ baseUrl, outcome }); + const result = yield* executeCode({ target, code }); + yield* printExecutionOutcome({ + target, + connection: result.connection, + outcome: result.outcome, + }); }), ).pipe(Command.withDescription("Describe a tool's TypeScript and JSON schema")); @@ -1406,6 +1854,131 @@ const toolsCommand = Command.make("tools").pipe( Command.withDescription("Discover available tools and sources"), ); +const profileConnectionInput = (input: { + readonly origin: string; + readonly displayName: Option.Option; + readonly kind: Option.Option<"http" | "desktop-sidecar">; +}): ExecutorServerConnectionInput => { + const selectedKind = Option.getOrUndefined(input.kind); + const displayName = Option.getOrUndefined(input.displayName); + return { + kind: selectedKind ?? "http", + origin: input.origin, + ...(displayName ? { displayName } : {}), + }; +}; + +const printServerProfiles = () => + Effect.gen(function* () { + const store = yield* readCliServerConnectionStore(); + if (store.profiles.length === 0) { + console.log("No server profiles configured."); + console.log(`Add one: ${cliPrefix} server add local ${DEFAULT_BASE_URL} --default`); + return; + } + + const rows = store.profiles.map((profile) => ({ + marker: profile.name === store.defaultProfile ? "*" : " ", + name: profile.name, + kind: profile.connection.kind, + origin: profile.connection.origin, + displayName: profile.connection.displayName, + auth: profile.connection.auth ? "stored-auth" : "env-auth", + })); + const nameWidth = rows.reduce((max, row) => Math.max(max, row.name.length), 4); + const kindWidth = rows.reduce((max, row) => Math.max(max, row.kind.length), 4); + + for (const row of rows) { + console.log( + `${row.marker} ${row.name.padEnd(nameWidth)} ${row.kind.padEnd(kindWidth)} ${row.origin} ${row.displayName} ${row.auth}`, + ); + } + }); + +const serverAddCommand = Command.make( + "add", + { + name: Args.string("name"), + origin: Args.string("origin"), + displayName: Options.string("display-name").pipe( + Options.optional, + Options.withDescription("Display label for this server profile."), + ), + kind: Options.choice("kind", ["http", "desktop-sidecar"] as const).pipe( + Options.optional, + Options.withDescription("Server kind. Defaults to http."), + ), + makeDefault: Options.boolean("default").pipe( + Options.withDefault(false), + Options.withDescription("Make this profile the default server."), + ), + }, + ({ name, origin, displayName, kind, makeDefault }) => + Effect.gen(function* () { + const profileName = validateCliServerConnectionProfileName(name); + const store = yield* upsertCliServerConnectionProfile({ + name: profileName, + connection: profileConnectionInput({ origin, displayName, kind }), + makeDefault, + }); + const profile = findCliServerConnectionProfile(store, profileName); + if (!profile) return yield* Effect.fail(new Error(`Failed to save "${profileName}".`)); + console.log(`Saved server profile "${profile.name}" (${profile.connection.origin}).`); + if (store.defaultProfile === profile.name) { + console.log(`Default server profile: ${profile.name}`); + } + }), +).pipe(Command.withDescription("Add or update a named Executor server profile")); + +const serverListCommand = Command.make("list", {}, () => printServerProfiles()).pipe( + Command.withDescription("List configured Executor server profiles"), +); + +const serverUseCommand = Command.make( + "use", + { + name: Args.string("name"), + }, + ({ name }) => + Effect.gen(function* () { + const store = yield* setDefaultCliServerConnectionProfile(name); + const profile = defaultCliServerConnectionProfile(store); + if (!profile) return yield* Effect.fail(new Error(`No server profile named "${name}".`)); + console.log(`Default server profile: ${profile.name} (${profile.connection.origin}).`); + }), +).pipe(Command.withDescription("Set the default Executor server profile")); + +const serverRemoveCommand = Command.make( + "remove", + { + name: Args.string("name"), + }, + ({ name }) => + Effect.gen(function* () { + const profileName = validateCliServerConnectionProfileName(name); + const store = yield* readCliServerConnectionStore(); + const profile = findCliServerConnectionProfile(store, profileName); + if (!profile) { + return yield* Effect.fail(new Error(`No server profile named "${profileName}".`)); + } + const nextStore = yield* removeCliServerConnectionProfile(profileName); + console.log(`Removed server profile "${profileName}".`); + if (nextStore.defaultProfile === null) { + console.log("No default server profile is configured."); + } + }), +).pipe(Command.withDescription("Remove an Executor server profile")); + +const serverCommand = Command.make("server").pipe( + Command.withSubcommands([ + serverAddCommand, + serverListCommand, + serverUseCommand, + serverRemoveCommand, + ] as const), + Command.withDescription("Manage named Executor server profiles"), +); + const webCommand = Command.make( "web", { @@ -1490,7 +2063,7 @@ const daemonRunCommand = Command.make( const daemonStatusCommand = Command.make( "status", { - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: daemonBaseUrlOption, }, ({ baseUrl }) => Effect.gen(function* () { @@ -1542,7 +2115,7 @@ const daemonStatusCommand = Command.make( const daemonStopCommand = Command.make( "stop", { - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: daemonBaseUrlOption, }, ({ baseUrl }) => stopDaemon(baseUrl), ).pipe(Command.withDescription("Stop the local daemon")); @@ -1550,7 +2123,7 @@ const daemonStopCommand = Command.make( const daemonRestartCommand = Command.make( "restart", { - baseUrl: Options.string("base-url").pipe(Options.withDefault(DEFAULT_BASE_URL)), + baseUrl: daemonBaseUrlOption, scope, }, ({ baseUrl, scope }) => @@ -1600,6 +2173,7 @@ const root = Command.make("executor").pipe( callCommand, resumeCommand, toolsCommand, + serverCommand, webCommand, daemonCommand, mcpCommand, diff --git a/apps/cli/src/server-connection.test.ts b/apps/cli/src/server-connection.test.ts new file mode 100644 index 000000000..ff6033d02 --- /dev/null +++ b/apps/cli/src/server-connection.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { + canAutoStartCliServerConnection, + chooseCliServerConnectionWithActiveLocal, + parseCliExecutorServerConnection, + withCliServerAuthFallback, +} from "./server-connection"; + +describe("CLI server connection", () => { + it("treats localhost HTTP servers as auto-startable daemon targets", () => { + const connection = parseCliExecutorServerConnection("localhost:4788", {}); + + expect(connection.origin).toBe("http://localhost:4788"); + expect(connection.apiBaseUrl).toBe("http://localhost:4788/api"); + expect(canAutoStartCliServerConnection(connection)).toBe(true); + }); + + it("treats hosted HTTPS servers as explicit server connections", () => { + const connection = parseCliExecutorServerConnection("https://executor.example/api", { + EXECUTOR_API_KEY: "key_123", + }); + + expect(connection.origin).toBe("https://executor.example"); + expect(connection.apiBaseUrl).toBe("https://executor.example/api"); + expect(connection.auth).toEqual({ kind: "bearer", token: "key_123" }); + expect(canAutoStartCliServerConnection(connection)).toBe(false); + }); + + it("adds environment auth only when a profile did not carry auth", () => { + const fromProfile = parseCliExecutorServerConnection("https://executor.example", {}); + expect(withCliServerAuthFallback(fromProfile, { EXECUTOR_API_KEY: "key_123" }).auth).toEqual({ + kind: "bearer", + token: "key_123", + }); + + const storedAuth = parseCliExecutorServerConnection("https://executor.example", { + EXECUTOR_API_KEY: "stored", + }); + expect(withCliServerAuthFallback(storedAuth, { EXECUTOR_API_KEY: "env" }).auth).toEqual({ + kind: "bearer", + token: "stored", + }); + }); + + it("supports desktop-style basic auth for local server connections", () => { + const connection = parseCliExecutorServerConnection("http://127.0.0.1:4789", { + EXECUTOR_AUTH_PASSWORD: "desktop-password", + }); + + expect(connection.auth).toEqual({ + kind: "basic", + username: "executor", + password: "desktop-password", + }); + expect(canAutoStartCliServerConnection(connection)).toBe(false); + }); + + it("never auto-starts desktop sidecar profiles", () => { + const connection = { + ...parseCliExecutorServerConnection("http://127.0.0.1:4789", {}), + kind: "desktop-sidecar" as const, + }; + + expect(canAutoStartCliServerConnection(connection)).toBe(false); + }); + + it("prefers bearer auth for hosted connections and basic auth for local connections", () => { + const hosted = parseCliExecutorServerConnection("https://executor.example", { + EXECUTOR_API_KEY: "key_123", + EXECUTOR_AUTH_PASSWORD: "desktop-password", + }); + expect(hosted.auth).toEqual({ kind: "bearer", token: "key_123" }); + + const local = parseCliExecutorServerConnection("http://127.0.0.1:4789", { + EXECUTOR_API_KEY: "key_123", + EXECUTOR_AUTH_PASSWORD: "desktop-password", + EXECUTOR_AUTH_USERNAME: "rhys", + }); + expect(local.auth).toEqual({ + kind: "basic", + username: "rhys", + password: "desktop-password", + }); + }); + + it("attaches implicit local requests to the active local owner", () => { + const requested = parseCliExecutorServerConnection("http://localhost:4788", {}); + const active = { + version: 1 as const, + kind: "desktop-sidecar" as const, + pid: process.pid, + startedAt: "2026-05-28T00:00:00.000Z", + dataDir: "/tmp/executor", + scopeDir: "/tmp/executor", + connection: parseCliExecutorServerConnection("http://127.0.0.1:4789", { + EXECUTOR_AUTH_PASSWORD: "desktop-password", + }), + owner: { + client: "desktop" as const, + version: "1.2.3", + executablePath: "/Applications/Executor.app/Contents/MacOS/Executor", + }, + }; + + const decision = chooseCliServerConnectionWithActiveLocal({ + requested, + source: "active-local", + active, + }); + + expect(decision).toMatchObject({ + kind: "use-active", + connection: { + origin: "http://127.0.0.1:4789", + auth: { + kind: "basic", + username: "executor", + password: "desktop-password", + }, + }, + }); + }); + + it("blocks local auto-start when another local owner is active", () => { + const requested = parseCliExecutorServerConnection("http://localhost:4788", {}); + const active = { + version: 1 as const, + kind: "desktop-sidecar" as const, + pid: process.pid, + startedAt: "2026-05-28T00:00:00.000Z", + dataDir: "/tmp/executor", + scopeDir: "/tmp/executor", + connection: parseCliExecutorServerConnection("http://127.0.0.1:4789", { + EXECUTOR_AUTH_PASSWORD: "desktop-password", + }), + owner: { + client: "desktop" as const, + version: "1.2.3", + executablePath: "/Applications/Executor.app/Contents/MacOS/Executor", + }, + }; + + expect( + chooseCliServerConnectionWithActiveLocal({ + requested, + source: "explicit", + active, + }).kind, + ).toBe("conflict"); + }); +}); diff --git a/apps/cli/src/server-connection.ts b/apps/cli/src/server-connection.ts new file mode 100644 index 000000000..3845e2ea2 --- /dev/null +++ b/apps/cli/src/server-connection.ts @@ -0,0 +1,111 @@ +import { + DEFAULT_EXECUTOR_SERVER_USERNAME, + normalizeExecutorServerConnection, + type ExecutorLocalServerManifest, + type ExecutorServerAuth, + type ExecutorServerConnection, +} from "@executor-js/sdk/shared"; +import { canAutoStartLocalDaemonForHost } from "./daemon"; + +const readCliBasicServerAuth = ( + env: Record = process.env, +): ExecutorServerAuth | undefined => { + const password = env.EXECUTOR_AUTH_PASSWORD; + if (!password) return undefined; + return { + kind: "basic", + username: env.EXECUTOR_AUTH_USERNAME ?? DEFAULT_EXECUTOR_SERVER_USERNAME, + password, + }; +}; + +const readCliBearerServerAuth = ( + env: Record = process.env, +): ExecutorServerAuth | undefined => { + const token = env.EXECUTOR_API_KEY ?? env.EXECUTOR_AUTH_TOKEN; + if (!token) return undefined; + return { kind: "bearer", token }; +}; + +export const readCliServerAuth = ( + env: Record = process.env, +): ExecutorServerAuth | undefined => readCliBearerServerAuth(env) ?? readCliBasicServerAuth(env); + +const readCliServerAuthForConnection = ( + connection: ExecutorServerConnection, + env: Record = process.env, +): ExecutorServerAuth | undefined => { + const bearer = readCliBearerServerAuth(env); + const basic = readCliBasicServerAuth(env); + const protocol = new URL(connection.origin).protocol; + + if (protocol === "https:") { + return bearer ?? basic; + } + + return basic ?? bearer; +}; + +export const parseCliExecutorServerConnection = ( + baseUrl: string, + env: Record = process.env, +): ExecutorServerConnection => { + const connection = normalizeExecutorServerConnection({ + origin: baseUrl, + }); + return normalizeExecutorServerConnection({ + ...connection, + auth: readCliServerAuthForConnection(connection, env), + }); +}; + +export const withCliServerAuthFallback = ( + connection: ExecutorServerConnection, + env: Record = process.env, +): ExecutorServerConnection => + connection.auth + ? connection + : normalizeExecutorServerConnection({ + ...connection, + auth: readCliServerAuthForConnection(connection, env), + }); + +export const canAutoStartCliServerConnection = (connection: ExecutorServerConnection): boolean => { + if (connection.kind !== "http") return false; + if (connection.auth?.kind === "basic") return false; + const url = new URL(connection.origin); + return url.protocol === "http:" && canAutoStartLocalDaemonForHost(url.hostname); +}; + +export type CliServerConnectionSource = + | "explicit" + | "default-profile" + | "implicit-default" + | "active-local"; + +export type ActiveLocalServerDecision = + | { readonly kind: "use-requested"; readonly connection: ExecutorServerConnection } + | { readonly kind: "use-active"; readonly connection: ExecutorServerConnection } + | { readonly kind: "conflict"; readonly active: ExecutorLocalServerManifest }; + +const sameOrigin = (left: string, right: string): boolean => + normalizeExecutorServerConnection({ origin: left }).origin === + normalizeExecutorServerConnection({ origin: right }).origin; + +export const chooseCliServerConnectionWithActiveLocal = (input: { + readonly requested: ExecutorServerConnection; + readonly source: CliServerConnectionSource; + readonly active: ExecutorLocalServerManifest | null; +}): ActiveLocalServerDecision => { + if (!input.active) return { kind: "use-requested", connection: input.requested }; + if (input.source === "active-local") { + return { kind: "use-active", connection: input.active.connection }; + } + if (sameOrigin(input.requested.origin, input.active.connection.origin)) { + return { kind: "use-active", connection: input.active.connection }; + } + if (canAutoStartCliServerConnection(input.requested)) { + return { kind: "conflict", active: input.active }; + } + return { kind: "use-requested", connection: input.requested }; +}; diff --git a/apps/cli/src/server-profile.test.ts b/apps/cli/src/server-profile.test.ts new file mode 100644 index 000000000..465aa75fe --- /dev/null +++ b/apps/cli/src/server-profile.test.ts @@ -0,0 +1,131 @@ +import { afterEach, describe, expect, it } from "@effect/vitest"; +import { BunServices } from "@effect/platform-bun"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as Effect from "effect/Effect"; + +import { + defaultCliServerConnectionProfile, + parseCliServerConnectionStore, + readCliServerConnectionStore, + removeCliServerConnectionProfile, + setDefaultCliServerConnectionProfile, + upsertCliServerConnectionProfile, +} from "./server-profile"; + +const previousDataDir = process.env.EXECUTOR_DATA_DIR; + +afterEach(() => { + if (previousDataDir === undefined) { + delete process.env.EXECUTOR_DATA_DIR; + } else { + process.env.EXECUTOR_DATA_DIR = previousDataDir; + } +}); + +describe("CLI server connection profiles", () => { + it("round-trips named server connections and default selection", () => + Effect.gen(function* () { + const dataDir = mkdtempSync(join(tmpdir(), "executor-server-profiles-")); + process.env.EXECUTOR_DATA_DIR = dataDir; + + try { + yield* upsertCliServerConnectionProfile({ + name: "remote", + connection: { + origin: "https://executor.example/api", + auth: { kind: "bearer", token: "key_123" }, + }, + makeDefault: true, + }); + + const store = yield* readCliServerConnectionStore(); + expect(store.defaultProfile).toBe("remote"); + expect(store.profiles).toHaveLength(1); + expect(store.profiles[0]?.connection.kind).toBe("http"); + expect(store.profiles[0]?.connection.origin).toBe("https://executor.example"); + expect(store.profiles[0]?.connection.apiBaseUrl).toBe("https://executor.example/api"); + expect(store.profiles[0]?.connection.auth).toEqual({ + kind: "bearer", + token: "key_123", + }); + expect(defaultCliServerConnectionProfile(store)?.name).toBe("remote"); + } finally { + rmSync(dataDir, { recursive: true, force: true }); + } + }).pipe(Effect.provide(BunServices.layer))); + + it("switches and removes the default profile", () => + Effect.gen(function* () { + const dataDir = mkdtempSync(join(tmpdir(), "executor-server-profiles-")); + process.env.EXECUTOR_DATA_DIR = dataDir; + + try { + yield* upsertCliServerConnectionProfile({ + name: "local", + connection: { origin: "localhost:4788" }, + makeDefault: true, + }); + yield* upsertCliServerConnectionProfile({ + name: "remote", + connection: { origin: "https://executor.example" }, + makeDefault: false, + }); + + const switched = yield* setDefaultCliServerConnectionProfile("remote"); + expect(switched.defaultProfile).toBe("remote"); + + const removed = yield* removeCliServerConnectionProfile("remote"); + expect(removed.defaultProfile).toBeNull(); + expect(removed.profiles.map((profile) => profile.name)).toEqual(["local"]); + } finally { + rmSync(dataDir, { recursive: true, force: true }); + } + }).pipe(Effect.provide(BunServices.layer))); + + it("drops malformed profiles when parsing", () => { + const store = parseCliServerConnectionStore( + JSON.stringify({ + version: 1, + defaultProfile: "missing", + profiles: [ + { name: "valid", connection: { origin: "https://executor.example" } }, + { name: "bad space", connection: { origin: "https://ignored.example" } }, + { name: "no-origin", connection: {} }, + ], + }), + ); + + expect(store.defaultProfile).toBeNull(); + expect(store.profiles.map((profile) => profile.name)).toEqual(["valid"]); + }); + + it("preserves desktop sidecar profile kind", () => { + const store = parseCliServerConnectionStore( + JSON.stringify({ + version: 1, + defaultProfile: "desktop", + profiles: [ + { + name: "desktop", + connection: { + kind: "desktop-sidecar", + key: "desktop-sidecar", + origin: "http://127.0.0.1:4789", + auth: { kind: "basic", username: "executor", password: "secret" }, + }, + }, + ], + }), + ); + + expect(store.defaultProfile).toBe("desktop"); + expect(store.profiles[0]?.connection.kind).toBe("desktop-sidecar"); + expect(store.profiles[0]?.connection.auth).toEqual({ + kind: "basic", + username: "executor", + password: "secret", + }); + }); +}); diff --git a/apps/cli/src/server-profile.ts b/apps/cli/src/server-profile.ts new file mode 100644 index 000000000..9accf979f --- /dev/null +++ b/apps/cli/src/server-profile.ts @@ -0,0 +1,217 @@ +import { homedir } from "node:os"; +import { FileSystem, Option, Path, Schema } from "effect"; +import type { PlatformError } from "effect/PlatformError"; +import * as Effect from "effect/Effect"; + +import { + normalizeExecutorServerConnection, + type ExecutorServerConnection, + type ExecutorServerConnectionInput, +} from "@executor-js/sdk/shared"; + +export interface CliServerConnectionProfile { + readonly name: string; + readonly connection: ExecutorServerConnection; +} + +export interface CliServerConnectionStore { + readonly version: 1; + readonly defaultProfile: string | null; + readonly profiles: readonly CliServerConnectionProfile[]; +} + +export const emptyCliServerConnectionStore: CliServerConnectionStore = { + version: 1, + defaultProfile: null, + profiles: [], +}; + +export const validateCliServerConnectionProfileName = (name: string): string => { + const trimmed = name.trim(); + if (!/^[A-Za-z0-9_.-]+$/.test(trimmed)) { + throw new Error( + "Server profile names may contain only letters, numbers, dots, underscores, and dashes.", + ); + } + return trimmed; +}; + +const resolveDataDir = (path: Path.Path): string => + process.env.EXECUTOR_DATA_DIR ?? path.join(homedir(), ".executor"); + +const serverConnectionStorePath = (path: Path.Path): string => + path.join(resolveDataDir(path), "server-connections.json"); + +const PersistedAuth = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("basic"), + username: Schema.optional(Schema.String), + password: Schema.String, + }), + Schema.Struct({ + kind: Schema.Literal("bearer"), + token: Schema.String, + }), +]); + +const PersistedConnection = Schema.Struct({ + kind: Schema.optional(Schema.Literals(["http", "desktop-sidecar"])), + key: Schema.optional(Schema.String), + origin: Schema.optional(Schema.String), + apiBaseUrl: Schema.optional(Schema.String), + displayName: Schema.optional(Schema.String), + auth: Schema.optional(PersistedAuth), +}); + +const PersistedProfile = Schema.Struct({ + name: Schema.String, + connection: PersistedConnection, +}); + +const PersistedStore = Schema.Struct({ + version: Schema.Literal(1), + defaultProfile: Schema.optional(Schema.NullOr(Schema.String)), + profiles: Schema.Array(PersistedProfile), +}); + +const decodeStoreJson = Schema.decodeUnknownOption(Schema.fromJsonString(PersistedStore)); + +const decodeConnection = ( + input: ExecutorServerConnectionInput, +): ExecutorServerConnection | null => { + if (!input.origin && !input.apiBaseUrl) return null; + return normalizeExecutorServerConnection(input); +}; + +export const parseCliServerConnectionStore = (raw: string): CliServerConnectionStore => { + const decoded = decodeStoreJson(raw); + if (Option.isNone(decoded)) return emptyCliServerConnectionStore; + const record = decoded.value; + + const profiles = record.profiles.flatMap((value): readonly CliServerConnectionProfile[] => { + const connection = decodeConnection(value.connection); + if (!connection) return []; + try { + return [{ name: validateCliServerConnectionProfileName(value.name), connection }]; + } catch { + return []; + } + }); + + const defaultProfile = + record.defaultProfile && profiles.some((profile) => profile.name === record.defaultProfile) + ? record.defaultProfile + : null; + + return { + version: 1, + defaultProfile, + profiles, + }; +}; + +const serializeCliServerConnectionStore = (store: CliServerConnectionStore): string => + `${JSON.stringify(store, null, 2)}\n`; + +export const readCliServerConnectionStore = (): Effect.Effect< + CliServerConnectionStore, + never, + FileSystem.FileSystem | Path.Path +> => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const raw = yield* fs + .readFileString(serverConnectionStorePath(path)) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + if (raw === null) return emptyCliServerConnectionStore; + return parseCliServerConnectionStore(raw); + }); + +export const writeCliServerConnectionStore = ( + store: CliServerConnectionStore, +): Effect.Effect => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dataDir = resolveDataDir(path); + yield* fs.makeDirectory(dataDir, { recursive: true }); + yield* fs.writeFileString( + serverConnectionStorePath(path), + serializeCliServerConnectionStore(store), + ); + }); + +export const upsertCliServerConnectionProfile = (input: { + readonly name: string; + readonly connection: ExecutorServerConnectionInput; + readonly makeDefault: boolean; +}): Effect.Effect => + Effect.gen(function* () { + const name = validateCliServerConnectionProfileName(input.name); + const store = yield* readCliServerConnectionStore(); + const connection = normalizeExecutorServerConnection({ + ...input.connection, + key: input.connection.key ?? `profile:${name}`, + displayName: input.connection.displayName ?? name, + }); + const nextProfiles = [ + ...store.profiles.filter((profile) => profile.name !== name), + { name, connection }, + ].sort((a, b) => a.name.localeCompare(b.name)); + const nextStore: CliServerConnectionStore = { + version: 1, + defaultProfile: + input.makeDefault || store.defaultProfile === null ? name : store.defaultProfile, + profiles: nextProfiles, + }; + yield* writeCliServerConnectionStore(nextStore); + return nextStore; + }); + +export const setDefaultCliServerConnectionProfile = ( + name: string, +): Effect.Effect< + CliServerConnectionStore, + Error | PlatformError, + FileSystem.FileSystem | Path.Path +> => + Effect.gen(function* () { + const profileName = validateCliServerConnectionProfileName(name); + const store = yield* readCliServerConnectionStore(); + if (!store.profiles.some((profile) => profile.name === profileName)) { + return yield* Effect.fail(new Error(`No server profile named "${profileName}".`)); + } + const nextStore: CliServerConnectionStore = { ...store, defaultProfile: profileName }; + yield* writeCliServerConnectionStore(nextStore); + return nextStore; + }); + +export const removeCliServerConnectionProfile = ( + name: string, +): Effect.Effect => + Effect.gen(function* () { + const profileName = validateCliServerConnectionProfileName(name); + const store = yield* readCliServerConnectionStore(); + const nextProfiles = store.profiles.filter((profile) => profile.name !== profileName); + const nextStore: CliServerConnectionStore = { + version: 1, + defaultProfile: store.defaultProfile === profileName ? null : store.defaultProfile, + profiles: nextProfiles, + }; + yield* writeCliServerConnectionStore(nextStore); + return nextStore; + }); + +export const findCliServerConnectionProfile = ( + store: CliServerConnectionStore, + name: string, +): CliServerConnectionProfile | null => { + const profileName = validateCliServerConnectionProfileName(name); + return store.profiles.find((profile) => profile.name === profileName) ?? null; +}; + +export const defaultCliServerConnectionProfile = ( + store: CliServerConnectionStore, +): CliServerConnectionProfile | null => + store.defaultProfile ? findCliServerConnectionProfile(store, store.defaultProfile) : null; diff --git a/apps/local/src/serve.test.ts b/apps/local/src/serve.test.ts index 9aa471ec0..9b46bc400 100644 --- a/apps/local/src/serve.test.ts +++ b/apps/local/src/serve.test.ts @@ -116,4 +116,78 @@ describe("startServer network bind auth", () => { expect(authorized.status).toBe(200); expect(await authorized.text()).toBe("ok"); }); + + it("answers browser CORS preflights before auth", async () => { + server = await startServer({ + port: 0, + hostname: "127.0.0.1", + clientDir, + authToken: "test-token", + handlers: { + api: { + handler: async () => new Response("ok"), + dispose: async () => {}, + }, + mcp: { + handleRequest: async () => new Response("ok"), + handleApprovalRequest: async () => new Response("ok"), + close: async () => {}, + }, + }, + }); + + const response = await fetch(`http://127.0.0.1:${server.port}/api/scope`, { + method: "OPTIONS", + headers: { + origin: "http://127.0.0.1:4789", + "access-control-request-method": "GET", + "access-control-request-headers": "authorization,b3,traceparent", + }, + }); + + expect(response.status).toBe(204); + expect(response.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:4789"); + expect(response.headers.get("access-control-allow-credentials")).toBe("true"); + expect(response.headers.get("access-control-allow-headers")).toContain("traceparent"); + expect(response.headers.get("access-control-allow-headers")).toContain("b3"); + }); + + it("adds CORS headers to authenticated API failures", async () => { + server = await startServer({ + port: 0, + hostname: "127.0.0.1", + clientDir, + authToken: "test-token", + handlers: { + api: { + handler: async () => new Response("ok"), + dispose: async () => {}, + }, + mcp: { + handleRequest: async () => new Response("ok"), + handleApprovalRequest: async () => new Response("ok"), + close: async () => {}, + }, + }, + }); + + const response = await fetch(`http://127.0.0.1:${server.port}/api/scope`, { + headers: { origin: "http://127.0.0.1:4789" }, + }); + + expect(response.status).toBe(401); + expect(response.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:4789"); + expect(response.headers.get("access-control-allow-credentials")).toBe("true"); + expect(response.headers.get("access-control-allow-headers")).toContain("traceparent"); + }); + + it("does not expose unauthenticated loopback servers cross-origin", async () => { + const baseUrl = await startTestServer(); + const response = await fetch(`${baseUrl}/api/scope`, { + headers: { origin: "https://example.com" }, + }); + + expect(response.status).toBe(200); + expect(response.headers.get("access-control-allow-origin")).toBeNull(); + }); }); diff --git a/apps/local/src/serve.ts b/apps/local/src/serve.ts index c39569544..28c576e81 100644 --- a/apps/local/src/serve.ts +++ b/apps/local/src/serve.ts @@ -200,6 +200,36 @@ export interface ServerInstance { type ServerHandlers = Awaited>; +const corsHeaders = { + "access-control-allow-methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS", + "access-control-allow-headers": + "authorization, content-type, x-executor-token, x-requested-with, traceparent, tracestate, baggage, b3", + "access-control-allow-credentials": "true", + "access-control-expose-headers": "*", +} as const; + +const withCorsHeaders = (req: Request, response: Response): Response => { + const origin = req.headers.get("origin"); + if (!origin) return response; + const headers = new Headers(response.headers); + headers.set("access-control-allow-origin", origin); + for (const [key, value] of Object.entries(corsHeaders)) headers.set(key, value); + headers.set( + "access-control-allow-headers", + req.headers.get("access-control-request-headers") ?? + corsHeaders["access-control-allow-headers"], + ); + headers.append("vary", "Origin"); + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }); +}; + +const corsPreflightResponse = (req: Request): Response => + withCorsHeaders(req, new Response(null, { status: 204 })); + export async function startServer(opts: StartServerOptions = {}): Promise { const port = opts.port ?? parseInt(process.env.PORT ?? "4788", 10); const hostname = opts.hostname ?? "127.0.0.1"; @@ -264,8 +294,15 @@ export async function startServer(opts: StartServerOptions = {}): Promise + requiresAuth ? withCorsHeaders(req, response) : response; + if (!isAllowedHost(req)) { - return new Response("Forbidden", { status: 403 }); + return maybeWithCorsHeaders(new Response("Forbidden", { status: 403 })); + } + + if (requiresAuth && req.method === "OPTIONS" && req.headers.has("origin")) { + return corsPreflightResponse(req); } const url = new URL(req.url); @@ -276,18 +313,20 @@ export async function startServer(opts: StartServerOptions = {}): Promise