A desktop coding agent with free access to frontier models.
TypeScript
fix: app-owned provider and engine start checks
ogsamratc55d620be7fd
diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.tsindex 97a418ea..b44e662d 100644--- a/apps/server/src/managed-opencode.ts+++ b/apps/server/src/managed-opencode.ts@@ -3,7 +3,7 @@ import { realpathSync } from "node:fs";import net from "node:net";import { randomUUID } from "node:crypto";import { globalOpencodeConfigDir } from "@omnirush/paths";-import { currentProviderLockPolicy, finishEngineEnv } from "./provider-lock.js";+import { currentProviderLockPolicy, finishEngineEnv, noteEngineStarted } from "./provider-lock.js";import { providerLockEnv, withProviderLockEnv } from "./provider-lock/provider-lock.mjs";import { engineDataEnv } from "./engine-data-home.js";import { repairEngineStoreBeforeStart } from "./engine-store-repair.js";@@ -321,6 +321,8 @@ async function startManagedOpencodeServer(throw error;}+ // Model providers (provider-lock.ts): whether this engine started locked.+ noteEngineStarted(url, providerLock);return {url,username,diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex 5f17d30a..6d8a0c8b 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -246,7 +246,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(// The global row's MCP entries are the account-linked Connect server, which// this app does not run; a project's own servers reach the engine through// its config files and the MCP plugin (opencode-plugins/omnirush-mcp-policy.ts).- const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, agentAssist: _agentAssist, mcp: _mcp, ...engineConfig } = runtimeConfig;+ const { managedPolicy: _managedPolicy, approvals: _approvals, bestPractices: _bestPractices, agentAssist: _agentAssist, mcp: _mcp, provider: _rowProvider, ...engineConfig } = runtimeConfig;// Code diagnostics: the main languages' servers on, the rest off; the engine default (none) while off.const lsp = agentAssistFlags(runtimeConfig, env).diagnostics ? agentAssistLspConfig() : undefined;const enabled = bestPracticesEnabled(runtimeConfig);@@ -256,8 +256,10 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(...(skillsDir ? [skillsDir] : []),...(enabled && bestPracticesDir ? [bestPracticesDir] : []),], userSkillPaths);+ // The app's own provider comes from the internal gateway only: an `omnirush` entry in the stored row is never used.+ const { [INTERNAL_PROVIDER_ID]: _storedOwnProvider, ...storedProviders } = runtimeProviderMap(runtimeConfig);const provider = {- ...runtimeProviderMap(runtimeConfig),+ ...storedProviders,...(internalGateway? { [INTERNAL_PROVIDER_ID]: internalGatewayProvider(internalGateway, catalog, webSearch) }: {}),diff --git a/apps/server/src/provider-lock.test.ts b/apps/server/src/provider-lock.test.tsindex 7ccbe44d..01f5f927 100644--- a/apps/server/src/provider-lock.test.ts+++ b/apps/server/src/provider-lock.test.ts@@ -18,6 +18,10 @@ import {lockedEngineEnv,providerAllowed,providerLockConfigViolations,+ assertEngineStartedWithinLock,+ assertProviderWritable,+ noteEngineStarted,+ resetEngineStarts,resetProviderLock,watchProviderLock,} from "./provider-lock.js";@@ -29,6 +33,7 @@ const roots: string[] = [];afterEach(async () => {resetProviderLock();+ resetEngineStarts();while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });});@@ -280,3 +285,39 @@ describe("provider lock: refusals", () => {expect(() => assertConfigWithinProviderLock(null)).not.toThrow();});});++describe("provider lock: the app's own provider and engines started unlocked", () => {+ test("no route writes the omnirush provider, locked or not", () => {+ expect(() => assertProviderWritable("omnirush")).toThrow("The OmniRush provider is set by the app only.");+ expect(() => assertProviderWritable("OmniRush")).toThrow();+ applyProviderLockAnswer(UNLOCKED);+ expect(() => assertProviderWritable("omnirush")).toThrow("The OmniRush provider is set by the app only.");+ expect(() => assertProviderWritable("openai")).not.toThrow();+ });++ test("an omnirush entry stored in the runtime row never reaches the engine config", () => {+ const stored = { provider: { omnirush: { npm: "@ai-sdk/openai", options: { baseURL: "https://evil.example/v1" }, models: { m: {} } } } };+ const signedIn = buildOmniRushRuntimeConfigObjectFromSnapshot(stored, { baseUrl: "http://127.0.0.1:1/omnirush-gateway/v1" }, {}, builtinOmniRushModelCatalog());+ expect(((signedIn.provider as Record<string, { options: { baseURL: string } }>).omnirush).options.baseURL).toBe("http://127.0.0.1:1/omnirush-gateway/v1");+ const signedOut = buildOmniRushRuntimeConfigObjectFromSnapshot(stored, undefined, {}, builtinOmniRushModelCatalog());+ expect(signedOut).not.toHaveProperty("provider");+ applyProviderLockAnswer(UNLOCKED);+ expect(buildOmniRushRuntimeConfigObjectFromSnapshot(stored, undefined, {}, builtinOmniRushModelCatalog())).not.toHaveProperty("provider");+ });++ test("while locked, an engine that started unlocked takes no model work until the app restarts", () => {+ applyProviderLockAnswer(UNLOCKED);+ noteEngineStarted("http://127.0.0.1:4001");+ resetProviderLock();+ noteEngineStarted("http://127.0.0.1:4002");+ for (const [method, path] of [["POST", "/session"], ["POST", "/session/ses_1/prompt_async"], ["POST", "/opencode/session/ses_1/message"], ["POST", "/api/session/ses_1/command"], ["POST", "/session/ses_1/shell"], ["POST", "/session/ses_1/summarize"]] as const) {+ expect(() => assertEngineStartedWithinLock("http://127.0.0.1:4001/", method, path)).toThrow("Only OmniRush models are available. Restart the app to continue.");+ expect(() => assertEngineStartedWithinLock("http://127.0.0.1:4002", method, path)).not.toThrow();+ }+ expect(() => assertEngineStartedWithinLock("http://127.0.0.1:4001", "GET", "/session/ses_1/message")).not.toThrow();+ expect(() => assertEngineStartedWithinLock("http://127.0.0.1:4001", "POST", "/session/ses_1/abort")).not.toThrow();+ expect(() => assertEngineStartedWithinLock("http://127.0.0.1:4999", "POST", "/session")).not.toThrow();+ applyProviderLockAnswer(UNLOCKED);+ expect(() => assertEngineStartedWithinLock("http://127.0.0.1:4001", "POST", "/session")).not.toThrow();+ });+});diff --git a/apps/server/src/provider-lock.ts b/apps/server/src/provider-lock.tsindex 35a7de41..4a4afcba 100644--- a/apps/server/src/provider-lock.ts+++ b/apps/server/src/provider-lock.ts@@ -89,6 +89,19 @@ export function assertProviderAllowed(providerId: unknown, policy: ProviderLockPif (!providerAllowed(providerId, policy)) throw providerLockedError(policy);}+export const PROVIDER_RESERVED_CODE = "provider_reserved";+export const PROVIDER_RESERVED_MESSAGE = "The OmniRush provider is set by the app only.";++/**+ * A provider a route may write into the app's runtime config: never the+ * app's own (`omnirush`, which only the app sets, locked or not), and only+ * allowed providers while locked. Throws 403 otherwise.+ */+export function assertProviderWritable(providerId: string, policy: ProviderLockPolicy = current): void {+ if (providerId.trim().toLowerCase() === OMNIRUSH_PROVIDER_ID) throw new ApiError(403, PROVIDER_RESERVED_CODE, PROVIDER_RESERVED_MESSAGE);+ assertProviderAllowed(providerId, policy);+}+/** Throws 403 provider_locked while locked (routes that only ever add another provider). */export function assertProvidersUnlocked(policy: ProviderLockPolicy = current): void {if (policy.locked) throw providerLockedError(policy);@@ -270,6 +283,46 @@ export function watchProviderLock({ read, apply, everyMs }: { read: () => Promisreturn () => clearInterval(timer);}+function originOf(url: string): string {+ try {+ return new URL(url).origin;+ } catch {+ return url;+ }+}++/** Whether each engine this app started (by origin) started locked: its environment carries the lock from then on. */+const engineStarts = new Map<string, boolean>();++/** An engine started at `url` under `policy` (managed-opencode.ts, managed-opencode-v2.ts). */+export function noteEngineStarted(url: string, policy: ProviderLockPolicy = current): void {+ engineStarts.set(originOf(url), policy.locked);+}++/** Forgets the engines noted (tests). */+export function resetEngineStarts(): void {+ engineStarts.clear();+}++/** A request that makes the engine do model work: a new chat, a prompt, a command, a shell turn, a summary. */+export function isModelWorkRequest(method: string, enginePath: string): boolean {+ if (method.toUpperCase() !== "POST") return false;+ const path = enginePath.replace(/^\/opencode2?(?=\/|$)/, "").replace(/^\/api(?=\/)/, "").replace(/\/+$/, "");+ return path === "/session" || /^\/session\/[^/]+\/(?:prompt|prompt_async|message|command|shell|summarize|init)$/.test(path);+}++/**+ * While locked, refuses model work on an engine this app started unlocked+ * (its environment has no lock; the switch to locked replaces it, but a+ * replacement that did not happen must not leave it serving other+ * providers): 403 provider_locked, asking for a restart. Engines the app+ * did not start, and every other request, pass.+ */+export function assertEngineStartedWithinLock(engineUrl: string | null | undefined, method: string, enginePath: string, policy: ProviderLockPolicy = current): void {+ if (!policy.locked || !engineUrl || !isModelWorkRequest(method, enginePath)) return;+ if (engineStarts.get(originOf(engineUrl)) === false) throw new ApiError(403, PROVIDER_LOCKED_CODE, `${policy.message} Restart the app to continue.`);+}+/** The policy for the app's UI (GET /omnirush/provider-lock). */export function providerLockStatus(policy: ProviderLockPolicy = current, userPlugins = 0): { locked: boolean; allow: string[]; message: string; source: string; plugins: { off: boolean; message: string | null; userPlugins: number } } {return {diff --git a/apps/server/src/release-guard.test.ts b/apps/server/src/release-guard.test.tsindex 6c5c5e0c..97e75732 100644--- a/apps/server/src/release-guard.test.ts+++ b/apps/server/src/release-guard.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, test } from "bun:test";-import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";+import { chmod, mkdtemp, rm, stat, utimes, writeFile } from "node:fs/promises";import { createHash } from "node:crypto";import { tmpdir } from "node:os";import { join } from "node:path";@@ -50,6 +50,11 @@ describe("release build guard", () => {const other = join(root, "other");await writeFile(other, "#!/bin/sh\necho other\n");await expect(releaseEngineBinary(other, release)).rejects.toThrow("is not the bundled one");+ // Bytes changed in place with the same size and time: still refused (hashed at every start, no cache).+ const { mtime } = await stat(bin);+ await writeFile(bin, "#!/bin/sh\necho EVILLL\n");+ await utimes(bin, mtime, mtime);+ await expect(releaseEngineBinary(bin, release)).rejects.toThrow("is not the bundled one");expect(await releaseEngineBinary("opencode", DEV)).toBe("opencode");expect(await releaseEngineBinary(undefined, DEV)).toBeUndefined();});diff --git a/apps/server/src/release-guard.ts b/apps/server/src/release-guard.tsindex a2c0b0dc..78b22a41 100644--- a/apps/server/src/release-guard.ts+++ b/apps/server/src/release-guard.ts@@ -9,7 +9,7 @@* The dev variant takes any address and engine, as before.*/import { createHash } from "node:crypto";-import { createReadStream, statSync } from "node:fs";+import { createReadStream } from "node:fs";import { isAbsolute } from "node:path";import { BUILD_VARIANT, RELEASE_ENGINE_SHA256 } from "./build-variant.js";@@ -69,19 +69,13 @@ function reportOnce(key: string, message: string): void {export const RELEASE_ENGINE_ERROR = "This build of OmniRush.ai only runs the engine it ships with.";-const hashCache = new Map<string, { size: number; mtimeMs: number; sha256: string }>();-+/** The file's sha256, read in full every time (an engine start checks the bytes it is about to run). */async function fileSha256(path: string): Promise<string> {- const stat = statSync(path);- const cached = hashCache.get(path);- if (cached && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) return cached.sha256;const hash = createHash("sha256");await new Promise<void>((resolvePromise, reject) => {createReadStream(path).on("data", (chunk) => hash.update(chunk)).on("end", () => resolvePromise()).on("error", reject);});- const sha256 = hash.digest("hex");- hashCache.set(path, { size: stat.size, mtimeMs: stat.mtimeMs, sha256 });- return sha256;+ return hash.digest("hex");}/**diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 171fdbac..30b12175 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -190,7 +190,8 @@ import {applyProviderLockAnswer,assertConfigWithinLock,assertPluginsUnlocked,- assertProviderAllowed,+ assertProviderWritable,+ assertEngineStartedWithinLock,assertProxiedEngineRequestWithinProviderLock,currentProviderLockPolicy,parseJsoncContent,@@ -1556,6 +1557,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {await managedDesktopPolicy(config).assertRequest(request, mount.restPath, true);await assertProxiedEngineRequestWithinProviderLock(request, mount.restPath);const workspace = await resolveWorkspaceWithoutBootstrap(config, mount.workspaceId);+ assertEngineStartedWithinLock(resolveWorkspaceOpencodeConnection(config, workspace).baseUrl, request.method, mount.restPath);await assertWorkspaceOwnsProxiedSessionRead(config, workspace, request.method, mount.restPath);proxyService = "opencode";proxyBaseUrl = workspace.baseUrl?.trim() || undefined;@@ -1691,6 +1693,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {await assertProxiedEngineRequestWithinProviderLock(request, url.pathname);proxyService = "opencode";const workspace = config.workspaces[0];+ if (workspace) assertEngineStartedWithinLock(resolveWorkspaceOpencodeConnection(config, workspace).baseUrl, request.method, url.pathname);if (workspace) {await assertWorkspaceOwnsProxiedSessionRead(config, workspace, request.method, url.pathname);}@@ -4631,7 +4634,7 @@ function createRoutes(const body = await readJsonBody(ctx.request);const providerPatch = parseRuntimeProviderPatchPayload(body);// The model provider lock (provider-lock.ts): only removals, or the allowed providers.- for (const [providerId, value] of Object.entries(providerPatch)) if (value !== null) assertProviderAllowed(providerId);+ for (const [providerId, value] of Object.entries(providerPatch)) if (value !== null) assertProviderWritable(providerId);const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({...current,provider: mergeRuntimeProviderUpdate(current.provider, providerPatch),@@ -4833,7 +4836,7 @@ function createRoutes(// would never reach the engine.const providerUpdate = isRecord(provider) ? provider : {};// The model provider lock (provider-lock.ts): no other provider and no model of one.- for (const [providerId, value] of Object.entries(providerUpdate)) if (value !== null) assertProviderAllowed(providerId);+ for (const [providerId, value] of Object.entries(providerUpdate)) if (value !== null) assertProviderWritable(providerId);assertConfigWithinLock(topLevelUpdates);if (Object.keys(providerUpdate).length) await managedDesktopPolicy(config).assert("provider");if (Object.keys(providerUpdate).length) {