From d1857543f3caecbc3db6734b7c54adb814898aa4 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:45:31 -0500 Subject: [PATCH] fix(setup): verify the effective OpenCode project launcher (#13538) --- src/application/ClientConfigurationFiles.ts | 132 ++++++++++---- .../McpClientRegistration.layers.test.ts | 117 ++++++++---- src/application/McpRegistrationCatalog.ts | 23 +++ .../McpRegistrationConfiguration.ts | 52 +++++- src/application/SupportedClients.ts | 7 +- tests/boundary/cli/mcpAddClientPolicy.test.ts | 170 +++++++++++++++++- 6 files changed, 427 insertions(+), 74 deletions(-) diff --git a/src/application/ClientConfigurationFiles.ts b/src/application/ClientConfigurationFiles.ts index 02ea205e16..2534bd8ee1 100644 --- a/src/application/ClientConfigurationFiles.ts +++ b/src/application/ClientConfigurationFiles.ts @@ -28,6 +28,7 @@ import { errorMessage } from "../kernel/errorMessage.js"; import { lstat, realpath } from "node:fs/promises"; import { posix, win32 } from "node:path"; import { isQualifiedCallerPath } from "../filesystem/callerPath.js"; +import { canonicalCallerPath } from "../filesystem/canonicalCallerPath.js"; import { isAbsentClientConfigPath } from "./ClientConfigPath.js"; export type ClientRegistrationScope = "user" | "project"; @@ -599,8 +600,14 @@ export const hasProjectRegistrationContribution = ({ }: EffectiveClientRegistrationConfiguration): boolean => declarations.some(({ source }) => source.scope === "project"); -interface ProjectConfigurationReadOptions { +export interface ProjectConfigurationReadOptions { readonly projectDirectory: string; + /** The registration transaction must still select a native project source. */ + readonly writeTarget?: { + readonly path: string; + readonly transactionPath: string; + readonly allowMissing: boolean; + }; readonly mode?: "ownership"; /** Original and proposed layers from the transaction owner's snapshots. */ readonly candidates?: readonly { @@ -639,8 +646,28 @@ export const readEffectiveClientRegistrationConfiguration = async ( client, project.projectDirectory, platform, + project.writeTarget, ); if (!paths.ok) return paths; + const target = project.writeTarget; + if (target !== undefined) { + const selected = paths.value.find(({ path }) => path === target.path); + if (selected?.userPath !== undefined) + return err({ + kind: "unreadable", + path: target.path, + scope: "project", + detail: `Project configuration ${target.path} aliases the user configuration at ${selected.userPath}. Select a project-only file.`, + }); + if (selected?.aliasesWriteTarget !== true) + return err({ + kind: "unreadable", + path: target.path, + scope: "project", + detail: + "The selected file could not be verified in the native project configuration load order.", + }); + } const candidates = new Map< string, NonNullable[number] @@ -680,6 +707,14 @@ export const readEffectiveClientRegistrationConfiguration = async ( }); candidates.set(path, candidate); } + const publication = + target === undefined ? undefined : candidates.get(target.path); + if (publication !== undefined) + for (const { path, userPath, aliasesWriteTarget } of layers) { + // An atomic replacement updates what symlinks to the destination read. + if (aliasesWriteTarget && userPath === undefined) + candidates.set(path, publication); + } if (layers.length === 0 && userAliasPaths.size === 0) return readEffectiveUserConfiguration(client, resources, platform); @@ -983,56 +1018,91 @@ const filesystemPathKey = (path: string, platform: NodeJS.Platform): string => ? win32.normalize(path).toLowerCase() : posix.normalize(path); -const physicalPathKey = async ( - path: string, - platform: NodeJS.Platform, -): Promise => - filesystemPathKey(await realpath(path).catch(() => path), platform); +interface PresentProjectSource { + readonly path: string; + readonly userPath?: string; + readonly aliasesWriteTarget?: true; +} /** Project discovery cannot reclassify the current user's physical settings file. */ const presentProjectSources = async ( client: SetupClient, projectDirectory: string, platform: NodeJS.Platform, + writeTarget?: ProjectConfigurationReadOptions["writeTarget"], ): Promise< - Result< - readonly { readonly path: string; readonly userPath?: string }[], - ClientConfigurationFileError - > + Result > => { + const physicalPath = + writeTarget === undefined ? realpath : canonicalCallerPath; + const keyOf = async (path: string) => + filesystemPathKey(await physicalPath(path).catch(() => path), platform); + const targetKey = + writeTarget === undefined + ? undefined + : filesystemPathKey(writeTarget.transactionPath, platform); const userPaths = client.configPaths ?? [client.configPath]; - const user = new Map( - await Promise.all( - userPaths.map( - async (path) => [await physicalPathKey(path, platform), path] as const, - ), - ), + const user = new Map(); + const userKeys = await Promise.all( + userPaths.map(async (path) => { + try { + return { + path, + key: filesystemPathKey(await physicalPath(path), platform), + }; + } catch (cause: unknown) { + // A dangling user link might become active when the project file is + // created. A non-directory ancestor cannot lead to that destination. + if ( + writeTarget?.allowMissing === true && + !( + cause instanceof Error && + "code" in cause && + cause.code === "ENOTDIR" + ) + ) + return { path, cause }; + return { path, key: filesystemPathKey(path, platform) }; + } + }), ); + for (const { path, key, cause } of userKeys) { + if (key === undefined) + return err({ + kind: "unreadable", + path, + scope: "user", + detail: `User configuration path ${path} could not be verified before creating project settings: ${errorMessage(cause)}.`, + }); + user.set(key, path); + } const nativePaths = clientProjectConfigurationPaths( client, projectDirectory, platform, ); - const project = new Map(); + const project = new Map(); for (const candidate of new Set(nativePaths)) { try { await lstat(candidate); } catch (cause: unknown) { - if (isAbsentClientConfigPath(cause)) continue; - return err({ - kind: "unreadable", - path: candidate, - scope: "project", - detail: `Project configuration ${candidate} could not be inspected: ${errorMessage(cause)}`, - }); + if (!isAbsentClientConfigPath(cause)) + return err({ + kind: "unreadable", + path: candidate, + scope: "project", + detail: `Project configuration ${candidate} could not be inspected: ${errorMessage(cause)}`, + }); + if (writeTarget?.allowMissing !== true || candidate !== writeTarget.path) + continue; } - const userPath = user.get(await physicalPathKey(candidate, platform)); - project.set( - candidate, - userPath === undefined - ? { path: candidate } - : { path: candidate, userPath }, - ); + const key = await keyOf(candidate); + const userPath = user.get(key); + project.set(candidate, { + path: candidate, + ...(userPath === undefined ? {} : { userPath }), + ...(key === targetKey ? { aliasesWriteTarget: true } : {}), + }); } return ok( nativePaths.flatMap((path) => { diff --git a/src/application/McpClientRegistration.layers.test.ts b/src/application/McpClientRegistration.layers.test.ts index 21c3cbbe6e..f935a5d204 100644 --- a/src/application/McpClientRegistration.layers.test.ts +++ b/src/application/McpClientRegistration.layers.test.ts @@ -15,6 +15,7 @@ import { ClientConfigurationPublication } from "./ClientConfigurationPublication import { mergeClientConfigurationDocuments } from "./ClientConfigurationFiles.js"; import { mcpClientRegistrationProfile, + resolveMcpRegistrationClients, type McpRegistrationClient, } from "./McpRegistrationCatalog.js"; @@ -138,47 +139,85 @@ it("refuses a higher Kilo file launcher before creating the lower selected targe }); }); -it("reports the retained backup when a higher layer invalidates publication", async () => { - const root = await createTestTempDirectory( - "rea-registration-layer-readback-", - ); - const target = join(root, "project", "kilo.json"); - const higher = join(root, "higher", "kilo.json"); - const original = await write(target, { theme: "target" }); - const higherDocument = { - mcp: { rea: { type: "local", command: ["higher-server"] } }, - }; - const publish = ClientConfigurationPublication.write; - let higherText: string | undefined; - vi.spyOn(ClientConfigurationPublication, "write").mockImplementation( - async (...args) => { - const publication = await publish(...args); - higherText = await write(higher, higherDocument); - return publication; - }, - ); - const result = await registerMcpClientOnHost( - clientFor(target, [target, higher]), - launcher, - undefined, - resources, - ); - if (result.ok) - throw new Error("Registration should refuse the changed launcher"); - const backup = `${target}.rea.backup`; - expect(result.error.message).toContain( - "higher-priority configuration overrides", - ); - expect(projectAnalysisError(result.error).details?.diagnostics).toMatchObject( - { +it.each(["kilo", "opencode"] as const)( + "reports the retained backup when a higher %s layer invalidates publication", + async (format) => { + const root = await createTestTempDirectory( + "rea-registration-layer-readback-", + ); + const project = join(root, "project"); + const target = join( + project, + format === "kilo" ? "kilo.json" : "opencode.jsonc", + ); + const higher = + format === "kilo" + ? join(root, "higher", "kilo.json") + : join(project, ".opencode", "opencode.json"); + const original = await write(target, { + theme: "target", + ...(format === "opencode" ? { mcp: { servers: {} } } : {}), + }); + const higherRow = { type: "local", command: ["higher-server"] }; + const higherDocument = { + mcp: + format === "kilo" + ? { rea: higherRow } + : { servers: { rea: higherRow } }, + }; + let client: McpRegistrationClient; + if (format === "kilo") client = clientFor(target, [target, higher]); + else { + const selected = await resolveMcpRegistrationClients( + { + agents: ["opencode"], + global: false, + home: join(root, "home"), + cwd: project, + platform: HOST_PLATFORM.platform, + environment: {}, + }, + resources, + ); + if (!selected.ok) throw selected.error; + const [projectClient] = selected.value; + if (projectClient === undefined) + throw new Error("OpenCode project was not selected"); + client = projectClient; + } + const publish = ClientConfigurationPublication.write; + let higherText: string | undefined; + vi.spyOn(ClientConfigurationPublication, "write").mockImplementation( + async (...args) => { + const publication = await publish(...args); + higherText = await write(higher, higherDocument); + return publication; + }, + ); + const result = await registerMcpClientOnHost( + client, + launcher, + undefined, + resources, + ); + if (result.ok) + throw new Error("Registration should refuse the changed launcher"); + const backup = `${target}.rea.backup`; + expect(result.error.message).toContain( + "overrides the selected stdio launcher", + ); + expect( + projectAnalysisError(result.error).details?.diagnostics, + ).toMatchObject({ settings_path: target, backup_path: backup, - }, - ); - expect(await readFile(target, "utf8")).toBe(original); - expect(await readFile(backup, "utf8")).toBe(original); - expect(await readFile(higher, "utf8")).toBe(higherText); -}); + ...(format === "opencode" ? { override_path: higher } : {}), + }); + expect(await readFile(target, "utf8")).toBe(original); + expect(await readFile(backup, "utf8")).toBe(original); + expect(await readFile(higher, "utf8")).toBe(higherText); + }, +); it("refuses a conflicting KILO_CONFIG_CONTENT launcher without mutating the inline source or creating a target", async () => { const root = await createTestTempDirectory( diff --git a/src/application/McpRegistrationCatalog.ts b/src/application/McpRegistrationCatalog.ts index 09a8a7f4b4..e9f47aed7a 100644 --- a/src/application/McpRegistrationCatalog.ts +++ b/src/application/McpRegistrationCatalog.ts @@ -15,6 +15,7 @@ import { clientEvidencePaths, registrationWriteBlocker, supportedClientDefinition, + supportedClients, resolveSupportedClients, type ClientSystemPaths, type SetupClient, @@ -127,6 +128,11 @@ export interface McpRegistrationClient { readonly configPaths?: readonly string[]; readonly inlineConfiguration?: ClientInlineConfiguration; readonly scope: "global" | "project"; + /** OpenCode's native project read scope, independent of the selected write target. */ + readonly projectConfiguration?: { + readonly directory: string; + readonly userClient: SetupClient; + }; readonly format: ClientConfigurationFormat; readonly privateProfile?: SetupClient["privateProfile"]; /** @@ -181,12 +187,29 @@ const projectTarget = async ( `${descriptor.displayName} has no project-scoped registration. Remove --no-global or select a project-capable client; no settings were written.`, ); const resolved = await descriptor.projectLocation(context); + const [userClient] = + id === "opencode" + ? supportedClients( + context.home, + context.platform, + context.environment, + undefined, + "opencode", + ) + : []; + if (id === "opencode" && userClient === undefined) + throw new ConfigurationError( + "OpenCode's user configuration could not be located for project registration.", + ); return { id, displayName: descriptor.displayName, registrationProfile: mcpClientRegistrationProfile(id), ...resolved, scope: "project", + ...(userClient === undefined + ? {} + : { projectConfiguration: { directory: context.cwd, userClient } }), format: descriptor.projectFormat ?? descriptor.format, }; }; diff --git a/src/application/McpRegistrationConfiguration.ts b/src/application/McpRegistrationConfiguration.ts index e72da3d8e0..047ca02b07 100644 --- a/src/application/McpRegistrationConfiguration.ts +++ b/src/application/McpRegistrationConfiguration.ts @@ -18,7 +18,9 @@ import { clientConfigurationForWrite, mergeClientConfigurationDocuments, readClientConfigurationFiles, + readEffectiveClientRegistrationConfiguration, type ClientConfigurationFileError, + type ProjectConfigurationReadOptions, } from "./ClientConfigurationFiles.js"; import { replaceClientRegistrationLauncher } from "./ClientRegistration.js"; import { readClientPolicyBlock } from "./GeminiClientSettings.js"; @@ -139,6 +141,12 @@ export const prepareRegistration = async ( admitClientConfigurationCandidate(location, layers, candidate, platform), ); assertEffectiveLauncher(client, effective, launcher); + await verifyProjectLauncher(client, launcher, platform, path, { + candidates: [ + { path: client.configPath, original: target, replacement: candidate }, + ], + allowMissing: snapshot === undefined, + }); return { path, client, @@ -156,6 +164,7 @@ const assertEffectiveLauncher = ( client: McpRegistrationClient, effective: ClientConfigurationDocument | undefined, launcher: ClientRegistrationCommand, + overridePath?: string, ): void => { const admitted = admitClientStdioConnection( effective === undefined @@ -173,12 +182,15 @@ const assertEffectiveLauncher = ( ) throw new ConfigurationError( admitted.ok - ? "A higher-priority configuration overrides the selected stdio launcher. Update that source before registering this command." + ? `A higher-priority configuration${overridePath === undefined ? "" : ` at ${overridePath}`} overrides the selected stdio launcher. Update that source before registering this command.` : admitted.error.cause.message, { ...(admitted.ok ? {} : { cause: admitted.error.cause }), diagnostics: { settings_path: client.configPath, + ...(overridePath === undefined + ? {} + : { override_path: overridePath }), ...(client.inlineConfiguration === undefined ? {} : { inline_origin: client.inlineConfiguration.origin }), @@ -187,6 +199,43 @@ const assertEffectiveLauncher = ( ); }; +const verifyProjectLauncher = async ( + client: McpRegistrationClient, + launcher: ClientRegistrationCommand, + platform: NodeJS.Platform, + transactionPath: string, + proposed?: Pick & { + readonly allowMissing: boolean; + }, +): Promise => { + const project = client.projectConfiguration; + if (project === undefined) return; + const { document, launcherConfigPath } = requireAdmittedConfiguration( + await readEffectiveClientRegistrationConfiguration( + project.userClient, + undefined, + platform, + { + projectDirectory: project.directory, + writeTarget: { + path: client.configPath, + transactionPath, + allowMissing: proposed?.allowMissing ?? false, + }, + ...(proposed?.candidates === undefined + ? {} + : { candidates: proposed.candidates }), + }, + ), + ); + assertEffectiveLauncher( + client, + document, + launcher, + launcherConfigPath === client.configPath ? undefined : launcherConfigPath, + ); +}; + /** Re-admit native layers around the caller's identity-verified target snapshot. */ export const verifyEffectiveRegistration = async ( prepared: Awaited>, @@ -206,4 +255,5 @@ export const verifyEffectiveRegistration = async ( mergeClientConfigurationDocuments(layers, platform), launcher, ); + await verifyProjectLauncher(client, launcher, platform, prepared.path); }; diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 71f989235a..82718f0ea9 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -2055,10 +2055,15 @@ export const supportedClients = ( platform: NodeJS.Platform, env: ClientPathContext["env"] = process.env, systemPaths: ClientSystemPaths = {}, + only?: SupportedClientName, ): readonly SetupClient[] => { const context = { home, platform, env, systemPaths }; const definitions: readonly ClientDefinition[] = SUPPORTED_CLIENT_DEFINITIONS; - return definitions.map((definition) => { + const selected = + only === undefined + ? definitions + : definitions.filter(({ name }) => name === only); + return selected.map((definition) => { try { const location = resolveLocation(definition, context); if (!location.ok) diff --git a/tests/boundary/cli/mcpAddClientPolicy.test.ts b/tests/boundary/cli/mcpAddClientPolicy.test.ts index 34396033bd..94341df8d8 100644 --- a/tests/boundary/cli/mcpAddClientPolicy.test.ts +++ b/tests/boundary/cli/mcpAddClientPolicy.test.ts @@ -1,10 +1,18 @@ -import { access, mkdir, readFile, writeFile } from "node:fs/promises"; +import { + access, + mkdir, + readFile, + readlink, + symlink, + unlink, + writeFile, +} from "node:fs/promises"; import { dirname, join } from "node:path"; import { expect } from "vitest"; import { mcpRegistrationReportSchema } from "../../../src/contracts/mcpRegistration.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { cliTest } from "../../support/cli/cliFixture.js"; +import { cliTest, type TestCli } from "../../support/cli/cliFixture.js"; import { registrationEnvironment } from "../../support/cli/registrationEnvironment.js"; cliTest( @@ -72,3 +80,161 @@ cliTest( } }, ); + +cliTest( + "project OpenCode registration verifies the launcher in native load order before publishing", + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-mcp-opencode-project-policy-", + ); + const project = join(root, "project"); + const home = join(root, "home"); + await mkdir(join(project, ".git"), { recursive: true }); + await mkdir(join(project, ".opencode")); + const environment = await registrationEnvironment(home, {}); + const selected = join(project, "opencode.jsonc"); + const higher = join(project, ".opencode", "opencode.json"); + const local = (command: string) => + JSON.stringify({ + mcp: { servers: { rea: { type: "local", command: [command, "mcp"] } } }, + }); + const original = local("previous-direct-launcher"); + const overriding = local("nested-launcher"); + await writeFile(selected, original); + await writeFile(higher, overriding); + const blocked = await addOpenCodeProject(cli, project, environment); + expect(blocked.exitCode).toBe(1); + expect(mcpRegistrationReportSchema.parse(blocked.json)).toMatchObject({ + ok: false, + clients: [ + { + config_path: selected, + scope: "project", + status: "failed", + error: { reason: expect.stringContaining(higher) }, + }, + ], + }); + expect(await readFile(selected, "utf8")).toBe(original); + expect(await readFile(higher, "utf8")).toBe(overriding); + for (const path of [selected, higher]) + await expect(access(`${path}.rea.backup`)).rejects.toMatchObject({ + code: "ENOENT", + }); + + await unlink(higher); + expect((await addOpenCodeProject(cli, project, environment)).exitCode).toBe( + 0, + ); + expect(JSON.parse(await readFile(selected, "utf8"))).toMatchObject({ + mcp: { servers: { rea: { command: ["rea", "mcp"] } } }, + }); + expect(await readFile(`${selected}.rea.backup`, "utf8")).toBe(original); + + const fresh = join(root, "new-project"); + await mkdir(fresh); + expect((await addOpenCodeProject(cli, fresh, environment)).exitCode).toBe( + 0, + ); + expect( + JSON.parse(await readFile(join(fresh, "opencode.jsonc"), "utf8")), + ).toMatchObject({ + mcp: { rea: { command: ["rea", "mcp"] } }, + }); + }, +); + +cliTest.skipIf(process.platform === "win32")( + "project OpenCode registration cannot create a user settings file through an alias", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-mcp-opencode-user-alias-"); + const project = join(root, "project"); + const parentAlias = join(root, "project-alias"); + const fileAlias = join(root, "user-override.jsonc"); + await mkdir(project); + const selected = join(project, "opencode.jsonc"); + await symlink(project, parentAlias); + await symlink(selected, fileAlias); + for (const userPath of [join(parentAlias, "opencode.jsonc"), fileAlias]) { + const result = await addOpenCodeProject( + cli, + project, + await registrationEnvironment(join(root, "home"), { + OPENCODE_CONFIG: userPath, + }), + ); + expect(result.exitCode, userPath).toBe(1); + for (const path of [selected, userPath, `${selected}.rea.backup`]) + await expect(access(path), path).rejects.toMatchObject({ + code: "ENOENT", + }); + expect(mcpRegistrationReportSchema.parse(result.json)).toMatchObject({ + ok: false, + clients: [ + { + config_path: selected, + scope: "project", + status: "failed", + error: { reason: expect.stringContaining(userPath) }, + }, + ], + }); + } + expect(await readlink(fileAlias)).toBe(selected); + }, +); + +cliTest.skipIf(process.platform === "win32")( + "project OpenCode registration replays a proposed edit through a higher alias of the same file", + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-mcp-opencode-project-alias-", + ); + const project = join(root, "project"); + const selected = join(project, "opencode.jsonc"); + const higher = join(project, ".opencode", "opencode.json"); + const original = + '{"mcp":{"servers":{"rea":{"type":"local","command":["previous-direct-launcher","mcp"]}}}}'; + await mkdir(join(project, ".git"), { recursive: true }); + await mkdir(dirname(higher)); + await writeFile(selected, original); + await symlink(selected, higher); + const result = await addOpenCodeProject( + cli, + project, + await registrationEnvironment(join(root, "home"), {}), + ); + expect(result.exitCode, result.stderr).toBe(0); + expect(mcpRegistrationReportSchema.parse(result.json)).toMatchObject({ + ok: true, + clients: [ + { config_path: selected, scope: "project", status: "configured" }, + ], + }); + expect(await readlink(higher)).toBe(selected); + expect(JSON.parse(await readFile(higher, "utf8"))).toMatchObject({ + mcp: { servers: { rea: { command: ["rea", "mcp"] } } }, + }); + expect(await readFile(`${selected}.rea.backup`, "utf8")).toBe(original); + }, +); + +const addOpenCodeProject = ( + cli: TestCli, + cwd: string, + environment: NodeJS.ProcessEnv, +) => + cli.run({ + arguments: [ + "mcp", + "add", + "--no-global", + "--agent", + "opencode", + "--command", + "rea mcp", + "--json", + ], + cwd, + environment, + });