Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: release build checks and plugin lock

ogsamrat10f942c5177a
diff --git a/apps/app/src/app/lib/provider-lock.ts b/apps/app/src/app/lib/provider-lock.ts
index dc5ae76a..977617cb 100644
--- a/apps/app/src/app/lib/provider-lock.ts
+++ b/apps/app/src/app/lib/provider-lock.ts
@@ -12,6 +12,8 @@
import { useSyncExternalStore } from "react";
export const PROVIDER_LOCK_DEFAULT_MESSAGE = "Only OmniRush models are available.";
+/** User plugins while locked: the engine loads only the app's own plugins (owner decision). */
+export const PLUGINS_LOCKED_MESSAGE = "Custom plugins are off while OmniRush models are locked.";
export type ProviderLockState = {
locked: boolean;
@@ -37,10 +39,8 @@ export function parseProviderLockState(value: unknown): ProviderLockState {
if (!isRecord(value)) return LOCKED;
const message = typeof value.message === "string" && value.message.trim() ? value.message.trim() : PROVIDER_LOCK_DEFAULT_MESSAGE;
if (value.locked === false) return { locked: false, allow: [], message };
- const allow = Array.isArray(value.allow)
- ? value.allow.filter((id): id is string => typeof id === "string" && id.trim().length > 0).map((id) => id.trim())
- : [];
- return { locked: true, allow: allow.includes("omnirush") ? allow : ["omnirush", ...allow], message };
+ // Only OmniRush's own provider counts as allowed, whatever else a server lists.
+ return { locked: true, allow: ["omnirush"], message };
}
export function providerLockState(): ProviderLockState {
diff --git a/apps/app/src/react-app/domains/settings/pages/plugins-view.tsx b/apps/app/src/react-app/domains/settings/pages/plugins-view.tsx
index 359c6258..5877469e 100644
--- a/apps/app/src/react-app/domains/settings/pages/plugins-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/plugins-view.tsx
@@ -4,6 +4,7 @@ import { Cpu } from "lucide-react";
import { t } from "../../../../i18n";
import { Button } from "@/components/ui/button";
import { TextInput } from "../../../design-system/text-input";
+import { PLUGINS_LOCKED_MESSAGE, useProviderLock } from "@/app/lib/provider-lock";
// Explicit, prop-driven shape of the extensions store. The Solid
// PluginsView pulled this from useExtensions(); in React we pass it
@@ -59,6 +60,8 @@ export type PluginsViewProps = {
export function PluginsView(props: PluginsViewProps) {
const { extensions } = props;
+ // No user plugin is added while OmniRush models are locked (app/lib/provider-lock.ts); removing stays possible.
+ const pluginsLocked = useProviderLock().locked;
const scope = extensions.pluginScope;
return (
<section className="space-y-6 max-w-3xl w-full">
@@ -69,6 +72,9 @@ export function PluginsView(props: PluginsViewProps) {
{t("plugins.title")}
</div>
<div className="text-xs text-gray-10">{t("plugins.desc")}</div>
+ {pluginsLocked ? (
+ <div className="text-xs text-gray-11" data-testid="plugins-locked-notice">{PLUGINS_LOCKED_MESSAGE}</div>
+ ) : null}
</div>
<div className="flex items-center gap-2">
<Button
@@ -168,6 +174,7 @@ export function PluginsView(props: PluginsViewProps) {
disabled={
props.busy ||
isInstalled ||
+ pluginsLocked ||
!props.canEditPlugins ||
(scope === "project" &&
!props.selectedWorkspaceRoot.trim())
@@ -297,6 +304,7 @@ export function PluginsView(props: PluginsViewProps) {
onClick={() => extensions.addPlugin()}
disabled={
props.busy ||
+ pluginsLocked ||
!extensions.pluginInput().trim() ||
!props.canEditPlugins
}
diff --git a/apps/app/src/react-app/domains/settings/state/extensions-store.ts b/apps/app/src/react-app/domains/settings/state/extensions-store.ts
index 5c59a5ae..ec7d8623 100644
--- a/apps/app/src/react-app/domains/settings/state/extensions-store.ts
+++ b/apps/app/src/react-app/domains/settings/state/extensions-store.ts
@@ -79,6 +79,7 @@ import {
type CreateLibraryItemInput,
type LibraryAuthorableKind,
} from "../library";
+import { isProviderLocked, PLUGINS_LOCKED_MESSAGE } from "@/app/lib/provider-lock";
const OPENCODE_SKILL_NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const OPENCODE_MCP_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
@@ -1763,6 +1764,11 @@ export function createExtensionsStore(options: {
async function addPlugin(pluginNameOverride?: string) {
if (extensionMutationDenied()) return;
+ // User plugins are off while OmniRush models are locked (app/lib/provider-lock.ts).
+ if (isProviderLocked()) {
+ setStateField("pluginStatus", PLUGINS_LOCKED_MESSAGE);
+ return;
+ }
const pluginName = (pluginNameOverride ?? snapshot.pluginInput).trim();
const isManualInput = pluginNameOverride == null;
const triggerName = stripPluginVersion(pluginName);
diff --git a/apps/app/src/react-app/shell/sync-restart-banner.tsx b/apps/app/src/react-app/shell/sync-restart-banner.tsx
index 1fd357a5..1388b36c 100644
--- a/apps/app/src/react-app/shell/sync-restart-banner.tsx
+++ b/apps/app/src/react-app/shell/sync-restart-banner.tsx
@@ -3,7 +3,8 @@ import { useEffect, useState, type ReactNode } from "react";
import { RefreshCw } from "lucide-react";
import { createOmniRushServerClient, type OmniRushCaptureStatus } from "../../app/lib/omnirush-server";
-import { setProviderLockState } from "../../app/lib/provider-lock";
+import { PLUGINS_LOCKED_MESSAGE, setProviderLockState } from "../../app/lib/provider-lock";
+import { toast } from "@/components/ui/sonner";
import { resolveOmniRushConnection } from "./omnirush-connection";
import { BANNER_CLASS, BANNER_HEIGHT_PX, bannerShiftStyle } from "./update-gate";
@@ -80,6 +81,21 @@ export function SyncRestartBanner() {
}
const PROVIDER_LOCK_POLL_MS = 60_000;
+const PLUGINS_OFF_NOTICE_KEY = "omnirush.providerLock.pluginsOffNoticed";
+
+/** Once per app profile: the user had plugins of their own and the lock keeps them off. */
+function noticePluginsOffOnce(answer: unknown): void {
+ if (typeof answer !== "object" || answer === null) return;
+ const plugins = (answer as { locked?: unknown; plugins?: { userPlugins?: unknown } }).plugins;
+ if ((answer as { locked?: unknown }).locked === false || typeof plugins?.userPlugins !== "number" || plugins.userPlugins <= 0) return;
+ try {
+ if (window.localStorage.getItem(PLUGINS_OFF_NOTICE_KEY)) return;
+ window.localStorage.setItem(PLUGINS_OFF_NOTICE_KEY, String(Date.now()));
+ } catch {
+ return;
+ }
+ toast(PLUGINS_LOCKED_MESSAGE);
+}
/**
* Keeps the model provider lock (app/lib/provider-lock.ts) in step with the
@@ -108,7 +124,10 @@ export function useProviderLockSync(): void {
} finally {
inflight = false;
}
- if (!stopped) setProviderLockState(answer);
+ if (!stopped) {
+ setProviderLockState(answer);
+ noticePluginsOffOnce(answer);
+ }
};
void poll();
const timer = window.setInterval(() => void poll(), PROVIDER_LOCK_POLL_MS);
diff --git a/apps/app/tests/desktop-policy-restricted.test.ts b/apps/app/tests/desktop-policy-restricted.test.ts
index a16b8af7..d9aa4c1b 100644
--- a/apps/app/tests/desktop-policy-restricted.test.ts
+++ b/apps/app/tests/desktop-policy-restricted.test.ts
@@ -26,6 +26,14 @@ import {
import { SETTINGS_TAB_VALUES } from "../src/app/types";
import { libraryAddAction } from "../src/react-app/domains/settings/library";
+import { afterAll as afterAllUnlocked, beforeAll as beforeAllUnlocked } from "bun:test";
+import { setProviderLockState } from "../src/app/lib/provider-lock";
+
+// These cover the app while the server leaves model providers unlocked
+// (providers.locked false); tests/provider-lock.test.ts covers the lock.
+beforeAllUnlocked(() => setProviderLockState({ locked: false }));
+afterAllUnlocked(() => setProviderLockState(null));
+
const allowEverything: DesktopAppRestrictionChecker = () => false;
const restrictedChecker: DesktopAppRestrictionChecker = ({ restriction }) =>
checkDesktopAppRestriction({ config: restrictedDesktopPolicyValue, restriction });
diff --git a/apps/app/tests/provider-lock.test.ts b/apps/app/tests/provider-lock.test.ts
index 201aca2b..0b269b66 100644
--- a/apps/app/tests/provider-lock.test.ts
+++ b/apps/app/tests/provider-lock.test.ts
@@ -34,11 +34,12 @@ describe("provider lock in the app", () => {
expect(isProviderLocked()).toBe(true);
});
- test("takes the server's allow list and message", () => {
- setProviderLockState({ locked: true, allow: ["acme"], message: "Ask your admin." });
- expect(providerLockState()).toEqual({ locked: true, allow: ["omnirush", "acme"], message: "Ask your admin." });
+ test("takes the server's message; only omnirush counts as allowed", () => {
+ setProviderLockState({ locked: true, allow: ["acme", "openai"], message: "Ask your admin." });
+ expect(providerLockState()).toEqual({ locked: true, allow: ["omnirush"], message: "Ask your admin." });
expect(providerLockMessage()).toBe("Ask your admin.");
- expect(isProviderAllowedByLock("acme")).toBe(true);
+ expect(isProviderAllowedByLock("acme")).toBe(false);
+ expect(isProviderAllowedByLock("omnirush")).toBe(true);
});
test("model pickers list only OmniRush models while locked, whatever the build flag says", () => {
diff --git a/apps/desktop/electron-builder.base.yml b/apps/desktop/electron-builder.base.yml
index 3baf8e29..4a1b9a9b 100644
--- a/apps/desktop/electron-builder.base.yml
+++ b/apps/desktop/electron-builder.base.yml
@@ -14,6 +14,9 @@ extraResources:
to: computer-use/relay.mjs
- from: .electron-runtime/omnirush-sentry.json
to: omnirush-sentry.json
+ # The build variant (scripts/stamp-build-variant.mjs, electron/build-variant.mjs).
+ - from: .electron-runtime/omnirush-build.json
+ to: omnirush-build.json
# Bundled UI-control MCP (scripts/prepare-ui-mcp.mjs). Launched with the app's
# own binary and ELECTRON_RUN_AS_NODE=1; never fetched from a registry.
- from: .electron-runtime/omnirush-ui-mcp
diff --git a/apps/desktop/electron/build-variant.mjs b/apps/desktop/electron/build-variant.mjs
new file mode 100644
index 00000000..682538b4
--- /dev/null
+++ b/apps/desktop/electron/build-variant.mjs
@@ -0,0 +1,76 @@
+// Which build of the desktop app this is, fixed when it was packaged; nothing
+// at runtime (environment, settings) changes it.
+//
+// A packaged app reads <resources>/omnirush-build.json, written by
+// scripts/electron-build.mjs: { variant: "release" | "dev", engineSha256 }.
+// The file missing or unreadable in a packaged app is a release build with no
+// engine it may run. An app run from the source tree (electron-dev) is dev.
+//
+// A release build (the same rules as apps/server/src/release-guard.ts):
+// - talks to https://omnirush.ai or https://<name>.omnirush.ai only, from
+// every source of an address; another address is an error, not a fallback;
+// - runs only the engine binary it bundles, checked by its sha256.
+import { createHash } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+
+export const DESKTOP_BUILD_FILE = "omnirush-build.json";
+export const RELEASE_GATEWAY_ERROR = "This build of OmniRush.ai only connects to omnirush.ai.";
+export const RELEASE_ENGINE_ERROR = "This build of OmniRush.ai only runs the engine it ships with.";
+
+/** @typedef {{ variant: "dev" | "release", engineSha256: string | null, packaged: boolean }} DesktopBuild */
+
+/** @returns {DesktopBuild} */
+export function readDesktopBuild({
+ resourcesPath = process.resourcesPath,
+ exists = existsSync,
+ read = (file) => readFileSync(file, "utf8"),
+} = {}) {
+ const packaged = Boolean(resourcesPath) && exists(path.join(resourcesPath, "app.asar"));
+ if (!packaged) return { variant: "dev", engineSha256: null, packaged: false };
+ try {
+ const value = JSON.parse(read(path.join(resourcesPath, DESKTOP_BUILD_FILE)));
+ const engineSha256 = typeof value?.engineSha256 === "string" && /^[0-9a-f]{64}$/.test(value.engineSha256) ? value.engineSha256 : null;
+ return { variant: value?.variant === "dev" ? "dev" : "release", engineSha256, packaged: true };
+ } catch {
+ return { variant: "release", engineSha256: null, packaged: true };
+ }
+}
+
+export const desktopBuild = readDesktopBuild();
+
+export function isReleaseBuild(build = desktopBuild) {
+ return build.variant === "release";
+}
+
+/** Whether a release build may use `raw` as its account server or gateway (any address in the dev variant). */
+export function gatewayUrlAllowedForBuild(raw, build = desktopBuild) {
+ if (!isReleaseBuild(build)) return true;
+ if (typeof raw !== "string") return false;
+ try {
+ const url = new URL(raw.trim());
+ const host = url.hostname.toLowerCase();
+ return url.protocol === "https:" && !url.username && !url.password && url.port === ""
+ && (host === "omnirush.ai" || host.endsWith(".omnirush.ai"));
+ } catch {
+ return false;
+ }
+}
+
+function sha256File(file) {
+ return createHash("sha256").update(readFileSync(file)).digest("hex");
+}
+
+/**
+ * The engine binary a release build runs: the bundled one in <resources>/sidecars,
+ * when its sha256 is the one recorded at packaging. Throws otherwise.
+ * @param {{ fileNames: string[], build?: DesktopBuild, resourcesPath?: string, exists?: (file: string) => boolean, hash?: (file: string) => string }} input
+ * @returns {{ path: string, source: "bundled" }}
+ */
+export function releaseEngineBinary({ build = desktopBuild, resourcesPath = process.resourcesPath, fileNames, exists = existsSync, hash = sha256File }) {
+ const directory = resourcesPath ? path.join(resourcesPath, "sidecars") : null;
+ const candidate = directory ? fileNames.map((name) => path.join(directory, name)).find((file) => exists(file)) : null;
+ if (!candidate || !build.engineSha256) throw new Error(`${RELEASE_ENGINE_ERROR} No bundled engine was found. Reinstall OmniRush.ai.`);
+ if (hash(candidate) !== build.engineSha256) throw new Error(`${RELEASE_ENGINE_ERROR} The bundled engine was changed. Reinstall OmniRush.ai.`);
+ return { path: candidate, source: "bundled" };
+}
diff --git a/apps/desktop/electron/build-variant.test.mjs b/apps/desktop/electron/build-variant.test.mjs
new file mode 100644
index 00000000..5c192aa8
--- /dev/null
+++ b/apps/desktop/electron/build-variant.test.mjs
@@ -0,0 +1,97 @@
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, writeFile, mkdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { createHash } from "node:crypto";
+
+import { gatewayUrlAllowedForBuild, readDesktopBuild, releaseEngineBinary } from "./build-variant.mjs";
+import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";
+import { desktopVariant, stampBuildVariant } from "../scripts/stamp-build-variant.mjs";
+
+/** @typedef {import("./build-variant.mjs").DesktopBuild} DesktopBuild */
+/** @type {DesktopBuild} */
+const RELEASE = { variant: "release", engineSha256: "a".repeat(64), packaged: true };
+/** @type {DesktopBuild} */
+const DEV = { variant: "dev", engineSha256: null, packaged: false };
+
+test("the build marker: source tree is dev, a packaged app is release unless it says dev", () => {
+ assert.deepEqual(readDesktopBuild({ resourcesPath: undefined }), DEV);
+ const files = new Map();
+ const at = { resourcesPath: "/r", exists: (file) => file === "/r/app.asar" || files.has(file), read: (file) => { if (!files.has(file)) throw new Error("missing"); return files.get(file); } };
+ assert.equal(readDesktopBuild(at).variant, "release");
+ files.set("/r/omnirush-build.json", "not json");
+ assert.equal(readDesktopBuild(at).variant, "release");
+ files.set("/r/omnirush-build.json", JSON.stringify({ variant: "dev", engineSha256: null }));
+ assert.equal(readDesktopBuild(at).variant, "dev");
+ files.set("/r/omnirush-build.json", JSON.stringify({ variant: "release", engineSha256: "b".repeat(64) }));
+ assert.deepEqual(readDesktopBuild(at), { variant: "release", engineSha256: "b".repeat(64), packaged: true });
+});
+
+test("release: only https omnirush.ai addresses", () => {
+ assert.equal(gatewayUrlAllowedForBuild("https://omnirush.ai/omnirush/v1", RELEASE), true);
+ assert.equal(gatewayUrlAllowedForBuild("https://api.omnirush.ai/omnirush/v1", RELEASE), true);
+ for (const bad of ["http://localhost:8090/omnirush/v1", "https://omnirush.ai.evil.example", "https://omnirush.ai:444", "https://staging.example/omnirush/v1"]) {
+ assert.equal(gatewayUrlAllowedForBuild(bad, RELEASE), false, bad);
+ }
+ assert.equal(gatewayUrlAllowedForBuild("http://localhost:8090/omnirush/v1", DEV), true);
+});
+
+test("release: the account store refuses other servers from env, sign-in and stored credentials", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-build-variant-"));
+ const requested = [];
+ const make = (env) => createDesktopOmniRushAccountStore({
+ build: RELEASE,
+ filePath: path.join(directory, `account-${requested.length}-${Math.random()}.bin`),
+ loadSafeStorage: () => ({ isAsyncEncryptionAvailable: async () => true, getSelectedStorageBackend: () => "keychain", encryptStringAsync: async (v) => Buffer.from(v), decryptStringAsync: async (v) => ({ result: v.toString(), shouldReEncrypt: false }) }),
+ platform: "linux",
+ env,
+ sleep: async () => undefined,
+ execFileImpl: async () => { throw new Error("no keychain"); },
+ fetchImpl: async (url) => { requested.push(String(url)); return Response.json({}, { status: 503 }); },
+ });
+ const sign = (store, gatewayUrl) => store.authorize({ gatewayUrl, deviceName: "t", openVerification: async () => undefined });
+ await assert.rejects(sign(make({ OMNIRUSH_GATEWAY_URL: "https://staging.example/omnirush/v1" })), /only connects to omnirush.ai/);
+ await assert.rejects(sign(make({ OMNIRUSH_DEV_MODE: "1", OMNIRUSH_LOCAL_API: "1" })), /only connects to omnirush.ai/);
+ await assert.rejects(sign(make({}), "http://localhost:8090/omnirush/v1"), /only connects to omnirush.ai/);
+ assert.deepEqual(requested, []);
+ await assert.rejects(sign(make({})));
+ assert.deepEqual(requested, ["https://omnirush.ai/omnirush/device/authorize"]);
+ const status = await make({ OMNIRUSH_GATEWAY_URL: "http://127.0.0.1:1/omnirush/v1" }).status();
+ assert.equal(status.gatewayUrl, null);
+ assert.equal(status.gatewayConfigured, false);
+});
+
+test("release: only the bundled engine with the recorded sha256", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-build-engine-"));
+ await mkdir(path.join(directory, "sidecars"));
+ await writeFile(path.join(directory, "sidecars", "opencode"), "engine");
+ const sha = createHash("sha256").update("engine").digest("hex");
+ /** @type {DesktopBuild} */
+ const build = { variant: "release", engineSha256: sha, packaged: true };
+ assert.deepEqual(releaseEngineBinary({ build, resourcesPath: directory, fileNames: ["opencode"] }), { path: path.join(directory, "sidecars", "opencode"), source: "bundled" });
+ assert.throws(() => releaseEngineBinary({ build: { ...build, engineSha256: "c".repeat(64) }, resourcesPath: directory, fileNames: ["opencode"] }), /was changed/);
+ assert.throws(() => releaseEngineBinary({ build, resourcesPath: directory, fileNames: ["missing"] }), /No bundled engine/);
+});
+
+test("packaging stamps release with the engine hash, or dev when asked at build time", async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-build-stamp-"));
+ const sidecarDir = path.join(directory, "sidecars");
+ const serverDistDir = path.join(directory, "dist");
+ await mkdir(sidecarDir);
+ await mkdir(serverDistDir);
+ await writeFile(path.join(sidecarDir, "opencode"), "engine");
+ await writeFile(path.join(sidecarDir, "opencode-x86_64-unknown-linux-gnu"), "engine");
+ const source = 'export const BUILD_VARIANT = "dev";\nexport const RELEASE_ENGINE_SHA256 = null;\n';
+ await writeFile(path.join(serverDistDir, "build-variant.js"), source);
+ const buildFilePath = path.join(directory, "omnirush-build.json");
+ const sha = createHash("sha256").update("engine").digest("hex");
+ assert.deepEqual(stampBuildVariant({ env: {}, sidecarDir, serverDistDir, buildFilePath }), { variant: "release", engineSha256: sha });
+ assert.equal(await readFile(path.join(serverDistDir, "build-variant.js"), "utf8"), `export const BUILD_VARIANT = "release";\nexport const RELEASE_ENGINE_SHA256 = "${sha}";\n`);
+ assert.deepEqual(JSON.parse(await readFile(buildFilePath, "utf8")), { variant: "release", engineSha256: sha });
+ assert.deepEqual(stampBuildVariant({ env: { OMNIRUSH_DESKTOP_VARIANT: "dev" }, sidecarDir, serverDistDir, buildFilePath }), { variant: "dev", engineSha256: null });
+ assert.equal(await readFile(path.join(serverDistDir, "build-variant.js"), "utf8"), source);
+ assert.throws(() => desktopVariant({ OMNIRUSH_DESKTOP_VARIANT: "staging" }));
+ await writeFile(path.join(sidecarDir, "opencode-x86_64-unknown-linux-gnu"), "other");
+ assert.throws(() => stampBuildVariant({ env: {}, sidecarDir, serverDistDir, buildFilePath }), /one bundled engine/);
+});
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index 73cb09a7..abedaf4f 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -13,6 +13,7 @@ import {
writePlaintextCredentialFile,
} from "./plaintext-credential-file.mjs";
import { CLIENT_HEADER, guiClientHeaderValue, parseClientUpdate } from "./update-gate.mjs";
+import { desktopBuild, gatewayUrlAllowedForBuild, isReleaseBuild, RELEASE_GATEWAY_ERROR } from "./build-variant.mjs";
import { buildathonJoinError, buildathonLinkCode, buildathonLinkError, buildathonProjectName, buildathonTrackId, parseBuildathonAnswer, parseBuildathonSessions, parseBuildathonStatus } from "./buildathon.mjs";
import { parseAccountQuality, parseFailLabels, parseQualitySessions, parseSessionStatus, parseSpinHistory, profileSessionId, parseSpinResult, parseWheelSegments, spinIdempotencyKey, spinRefusal } from "./quality.mjs";
@@ -76,12 +77,14 @@ function normalizeCredential(value) {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
-function normalizeGatewayUrl(value) {
+function normalizeGatewayUrl(value, build = desktopBuild) {
const normalized = normalizeCredential(value);
if (!normalized) return null;
try {
const url = new URL(normalized);
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK_HOSTNAMES.includes(url.hostname))) return null;
+ // A release build talks to omnirush.ai only (build-variant.mjs).
+ if (!gatewayUrlAllowedForBuild(url.toString(), build)) return null;
return url.toString().replace(/\/+$/, "");
} catch {
return null;
@@ -146,9 +149,9 @@ async function responseDetail(response) {
* a bundle written before the counter existed loads as 0.
* @returns {{ gatewayUrl: string, accessToken: string, refreshToken: string, rotation: number } | null}
*/
-function validCredentials(value) {
+function validCredentials(value, build = desktopBuild) {
if (!value || typeof value !== "object") return null;
- const gatewayUrl = normalizeGatewayUrl(value.gatewayUrl);
+ const gatewayUrl = normalizeGatewayUrl(value.gatewayUrl, build);
const accessToken = normalizeCredential(value.accessToken);
const refreshToken = normalizeCredential(value.refreshToken);
if (!gatewayUrl || !accessToken || !refreshToken) return null;
@@ -306,6 +309,8 @@ export function legacyKeychainAllowed({ appIdentifier, productionAppIdentifier,
}
export function createDesktopOmniRushAccountStore({
+ // Which build this is (build-variant.mjs); tests pass one.
+ build = desktopBuild,
filePath,
loadSafeStorage,
platform = process.platform,
@@ -337,7 +342,14 @@ export function createDesktopOmniRushAccountStore({
// An explicit OMNIRUSH_GATEWAY_URL, read once here: the runtime deletes it
// from process.env when it starts the embedded server (runtime.mjs), and a
// later sign-in must still go to the server it named, not to omnirush.ai.
- const explicitGatewayUrl = normalizeGatewayUrl(env.OMNIRUSH_GATEWAY_URL);
+ const storeGatewayUrl = (value) => normalizeGatewayUrl(value, build);
+ const storeCredentials = (value) => validCredentials(value, build);
+ // A release build takes no other account server from the environment: an
+ // address there that is not omnirush.ai is an error at sign-in, not a fallback.
+ const refusedGatewayUrl = isReleaseBuild(build)
+ && ((normalizeCredential(env.OMNIRUSH_GATEWAY_URL) && !storeGatewayUrl(env.OMNIRUSH_GATEWAY_URL))
+ || (env.OMNIRUSH_DEV_MODE === "1" && env.OMNIRUSH_LOCAL_API === "1"));
+ const explicitGatewayUrl = storeGatewayUrl(env.OMNIRUSH_GATEWAY_URL);
const clientHeader = guiClientHeaderValue(clientVersion);
/** fetchImpl with `X-OmniRush-Client` added to every account request. */
const send = clientHeader
@@ -441,7 +453,7 @@ export function createDesktopOmniRushAccountStore({
async function loadFallbackFile() {
try {
const contents = await readPlaintextCredentialFile(fallbackFilePath);
- return contents ? validCredentials(JSON.parse(contents)?.credentials) : null;
+ return contents ? storeCredentials(JSON.parse(contents)?.credentials) : null;
} catch {
return null;
}
@@ -476,7 +488,7 @@ export function createDesktopOmniRushAccountStore({
async function decryptKeyringCopy(storage) {
try {
const decrypted = await storage.decryptStringAsync(await readFile(filePath));
- const credentials = validCredentials(JSON.parse(decrypted.result));
+ const credentials = storeCredentials(JSON.parse(decrypted.result));
return credentials ? { credentials, shouldReEncrypt: Boolean(decrypted.shouldReEncrypt) } : null;
} catch {
return null;
@@ -581,7 +593,7 @@ export function createDesktopOmniRushAccountStore({
async function legacyCredentials() {
if (await exists(filePath) || (fileFallback && await exists(fallbackFilePath))) return null;
if (await exists(signedOutPath)) return null;
- return validCredentials({
+ return storeCredentials({
gatewayUrl: env.OMNIRUSH_GATEWAY_URL ?? await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity),
accessToken: env.OMNIRUSH_ACCESS_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.accessToken, platform, runSecurity),
refreshToken: env.OMNIRUSH_REFRESH_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.refreshToken, platform, runSecurity),
@@ -674,7 +686,7 @@ export function createDesktopOmniRushAccountStore({
async function save(credentials) {
// A new or renewed sign-in: the account is read again (accountId).
knownAccountId = null;
- const normalized = validCredentials(credentials);
+ const normalized = storeCredentials(credentials);
if (!normalized) throw new Error("Invalid OmniRush account credential bundle");
if (clearInFlight) {
const revoked = clearRevokesRemote;
@@ -767,9 +779,10 @@ export function createDesktopOmniRushAccountStore({
// Development builds keep using omnirush.ai. Only an explicit
// OMNIRUSH_GATEWAY_URL, or OMNIRUSH_DEV_MODE=1 together with
// OMNIRUSH_LOCAL_API=1, points the account service at a local API.
+ if (refusedGatewayUrl) throw new Error(`${RELEASE_GATEWAY_ERROR} OMNIRUSH_GATEWAY_URL is not an omnirush.ai address.`);
const localApiSelected = env.OMNIRUSH_DEV_MODE === "1" && env.OMNIRUSH_LOCAL_API === "1";
return explicitGatewayUrl
- ?? normalizeGatewayUrl(await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity))
+ ?? storeGatewayUrl(await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity))
?? (localApiSelected ? DEV_GATEWAY_URL : DEFAULT_GATEWAY_URL);
}
@@ -904,7 +917,7 @@ export function createDesktopOmniRushAccountStore({
try {
const payload = await response.json();
if (payload && typeof payload === "object" && "client_update" in payload) reportClientUpdate(payload);
- const rotated = validCredentials({
+ const rotated = storeCredentials({
gatewayUrl: payload.gateway_url ?? credentials.gatewayUrl,
accessToken: payload.access_token,
refreshToken: payload.refresh_token,
@@ -1040,7 +1053,8 @@ export function createDesktopOmniRushAccountStore({
async function authorize({ gatewayUrl, deviceName, openVerification }) {
const explicitGateway = normalizeCredential(gatewayUrl);
- const configured = explicitGateway ? normalizeGatewayUrl(explicitGateway) : await configuredGatewayUrl();
+ const configured = explicitGateway ? storeGatewayUrl(explicitGateway) : await configuredGatewayUrl();
+ if (explicitGateway && !configured && isReleaseBuild(build)) throw new Error(`${RELEASE_GATEWAY_ERROR} The account server given is not an omnirush.ai address.`);
if (!configured) throw new Error("OmniRush account service is not configured");
const base = controlPlaneBase(configured);
const authorizeUrl = new URL(base);
@@ -1072,7 +1086,7 @@ export function createDesktopOmniRushAccountStore({
if (!tokenResponse.ok) throw new Error(`Account link failed (${tokenResponse.status})`);
const payload = await tokenResponse.json();
if (payload && typeof payload === "object" && "client_update" in payload) reportClientUpdate(payload);
- const credentials = validCredentials({
+ const credentials = storeCredentials({
gatewayUrl: payload.gateway_url ?? configured,
accessToken: payload.access_token,
refreshToken: payload.refresh_token,
@@ -1113,7 +1127,8 @@ export function createDesktopOmniRushAccountStore({
async function status(input = {}) {
const sessionId = profileSessionId(input?.sessionId);
const credentials = await load();
- const configured = await configuredGatewayUrl();
+ // A release build refusing the configured address reports no account server (sign-in shows the error).
+ const configured = await configuredGatewayUrl().catch(() => null);
const gatewayConfigured = Boolean(configured);
// A connected account reports the server it is actually linked to; a
// signed-out app reports the server the next sign-in will use.
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index 158fb005..b4bbbfe8 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -7,6 +7,7 @@ import os from "node:os";
import path from "node:path";
import tls from "node:tls";
import { fileURLToPath } from "node:url";
+import { isReleaseBuild, releaseEngineBinary } from "./build-variant.mjs";
import { pathToFileURL } from "node:url";
import {
appendRuntimeRestartRecord,
@@ -1701,6 +1702,9 @@ export function createRuntimeManager({
}
function resolveOpencodeBinary(opencodeBinPath) {
+ // A release build runs only the engine it bundles, checked by its sha256: no
+ // custom path, no PATH or known-location lookup (build-variant.mjs). Throws.
+ if (isReleaseBuild()) return releaseEngineBinary({ fileNames: binaryFileNames("opencode") });
const explicitPath = typeof opencodeBinPath === "string" ? opencodeBinPath.trim() : "";
return explicitPath ? { path: explicitPath, source: "custom" } : resolveBinaryInfo("opencode");
}
@@ -1798,7 +1802,13 @@ export function createRuntimeManager({
}
function engineDoctor(options = {}) {
- const resolved = resolveOpencodeBinary(options?.opencodeBinPath);
+ let resolved = null;
+ let refused = null;
+ try {
+ resolved = resolveOpencodeBinary(options?.opencodeBinPath);
+ } catch (error) {
+ refused = error instanceof Error ? error.message : String(error);
+ }
if (!resolved?.path) {
return {
found: false,
@@ -1807,7 +1817,7 @@ export function createRuntimeManager({
resolvedSource: null,
version: null,
supportsServe: false,
- notes: ["OmniRush binary not found in bundled sidecars or PATH."],
+ notes: [refused ?? "OmniRush binary not found in bundled sidecars or PATH."],
serveHelpStatus: null,
serveHelpStdout: null,
serveHelpStderr: null,
@@ -2619,7 +2629,7 @@ export function createRuntimeManager({
throw new Error("server_name is required");
}
- const program = resolveBinary("opencode");
+ const program = resolveOpencodeBinary()?.path ?? null;
if (!program) {
throw new Error("Failed to locate the local agent runtime.");
}
@@ -2675,7 +2685,13 @@ export function createRuntimeManager({
engineDoctor,
/** The engine binary a start would use and where the bundled copy belongs (start-report.mjs). */
engineBinaryInfo: () => ({
- resolved: resolveOpencodeBinary(),
+ resolved: (() => {
+ try {
+ return resolveOpencodeBinary();
+ } catch {
+ return null;
+ }
+ })(),
bundledCandidates: sidecarDirs.flatMap((directory) => binaryFileNames("opencode").map((name) => path.join(directory, name))),
versionsFiles: sidecarDirs.map((directory) => path.join(directory, "versions.json")),
}),
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 4c48082a..9ded2b18 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -27,7 +27,7 @@
"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs",
"pretest": "pnpm --filter @omnirush/headless-threads build",
"test:omnirush-account": "node --test electron/omnirush-account.test.mjs",
- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs",
+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/build-variant.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs",
"test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",
"pretest:core": "pnpm --filter @omnirush/headless-threads build"
},
diff --git a/apps/desktop/scripts/electron-build.mjs b/apps/desktop/scripts/electron-build.mjs
index b0f19baf..e28d199b 100644
--- a/apps/desktop/scripts/electron-build.mjs
+++ b/apps/desktop/scripts/electron-build.mjs
@@ -3,6 +3,7 @@ import { copyFileSync, cpSync, readdirSync, rmSync, writeFileSync } from "node:f
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { prepareServerConstants } from "./prepare-server-constants.mjs";
+import { stampBuildVariant } from "./stamp-build-variant.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopRoot = resolve(__dirname, "..");
@@ -78,6 +79,14 @@ prepareServerConstants(serverDistDir, resolve(repoRoot, "constants.json"));
rmSync(packagedServerRoot, { recursive: true, force: true });
cpSync(serverDistDir, resolve(packagedServerRoot, "dist"), { recursive: true });
copyFileSync(resolve(repoRoot, "apps", "server", "package.json"), resolve(packagedServerRoot, "package.json"));
+// Release unless OMNIRUSH_DESKTOP_VARIANT=dev: a release talks to omnirush.ai only and runs only the
+// engine bundled above (its sha256 is recorded here). Stamps the packaged server copy, not the source.
+const desktopBuild = stampBuildVariant({
+ sidecarDir: electronSidecarDir,
+ serverDistDir: resolve(packagedServerRoot, "dist"),
+ buildFilePath: resolve(desktopRoot, ".electron-runtime", "omnirush-build.json"),
+});
+process.stdout.write(`Desktop build variant: ${desktopBuild.variant}\n`);
for (const fileName of readdirSync(electronRoot).filter((name) => name.endsWith(".mjs")).sort()) {
run(nodeCmd, ["--check", resolve(electronRoot, fileName)], repoRoot);
}
diff --git a/apps/desktop/scripts/stamp-build-variant.mjs b/apps/desktop/scripts/stamp-build-variant.mjs
new file mode 100644
index 00000000..2e45e4fb
--- /dev/null
+++ b/apps/desktop/scripts/stamp-build-variant.mjs
@@ -0,0 +1,44 @@
+// The build variant of a packaged desktop app (electron/build-variant.mjs and
+// apps/server/src/build-variant.ts). Release unless the build is asked for the
+// dev variant with OMNIRUSH_DESKTOP_VARIANT=dev; a release records the sha256
+// of the engine binary it bundles, which is then the only engine it runs.
+import { createHash } from "node:crypto";
+import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+export function desktopVariant(env = process.env) {
+ const asked = String(env.OMNIRUSH_DESKTOP_VARIANT ?? "").trim().toLowerCase();
+ if (asked && asked !== "dev" && asked !== "release") throw new Error(`OMNIRUSH_DESKTOP_VARIANT must be "dev" or "release", not "${asked}"`);
+ return asked === "dev" ? "dev" : "release";
+}
+
+/** The sha256 of the bundled engine; every opencode binary in the sidecar folder must be the same file. */
+export function bundledEngineSha256(sidecarDir) {
+ const names = existsSync(sidecarDir) ? readdirSync(sidecarDir).filter((name) => /^opencode(?:-[a-z0-9_-]+)?(?:\.exe)?$/.test(name)) : [];
+ const hashes = [...new Set(names.map((name) => createHash("sha256").update(readFileSync(join(sidecarDir, name))).digest("hex")))];
+ if (hashes.length !== 1) throw new Error(`Expected one bundled engine in ${sidecarDir}, found ${names.length} file(s) with ${hashes.length} different content(s)`);
+ return hashes[0];
+}
+
+/** Stamps the packaged server copy's build-variant.js (two lines, checked). */
+export function stampServerVariant(serverDistDir, variant, engineSha256) {
+ const file = join(serverDistDir, "build-variant.js");
+ const source = readFileSync(file, "utf8");
+ const variantLine = /^export const BUILD_VARIANT = "(?:dev|release)";$/m;
+ const hashLine = /^export const RELEASE_ENGINE_SHA256 = (?:null|"[0-9a-f]{64}");$/m;
+ if (!variantLine.test(source) || !hashLine.test(source)) throw new Error(`${file} does not have the expected build variant lines`);
+ const stamped = source
+ .replace(variantLine, `export const BUILD_VARIANT = "${variant}";`)
+ .replace(hashLine, `export const RELEASE_ENGINE_SHA256 = ${engineSha256 ? `"${engineSha256}"` : "null"};`);
+ writeFileSync(file, stamped, "utf8");
+}
+
+/** Writes <out>/omnirush-build.json and stamps the packaged server; returns what was written. */
+export function stampBuildVariant({ env = process.env, sidecarDir, serverDistDir, buildFilePath }) {
+ const variant = desktopVariant(env);
+ const engineSha256 = variant === "release" ? bundledEngineSha256(sidecarDir) : null;
+ const build = { variant, engineSha256 };
+ writeFileSync(buildFilePath, `${JSON.stringify(build, null, 2)}\n`, "utf8");
+ stampServerVariant(serverDistDir, variant, engineSha256);
+ return build;
+}
diff --git a/apps/server/scripts/copy-shared-modules.mjs b/apps/server/scripts/copy-shared-modules.mjs
index 34b9a9e3..46043ee0 100644
--- a/apps/server/scripts/copy-shared-modules.mjs
+++ b/apps/server/scripts/copy-shared-modules.mjs
@@ -1,11 +1,12 @@
// tsc emits only TypeScript: the plain-JavaScript modules shared with the CLI
-// (src/workspace/*.mjs and src/computer-use/shared/*.mjs, see PARITY.sha256 there) are copied into dist as they are.
+// (src/workspace/*.mjs, src/computer-use/shared/*.mjs and src/provider-lock/*.mjs, see PARITY.sha256 there) are
+// copied into dist as they are.
import { copyFileSync, mkdirSync, readdirSync } from "node:fs";
import { join, resolve } from "node:path";
const root = resolve(import.meta.dirname, "..");
const copied = [];
-for (const folder of ["workspace", "computer-use/shared"]) {
+for (const folder of ["workspace", "computer-use/shared", "provider-lock"]) {
const from = join(root, "src", folder);
const to = join(root, "dist", folder);
mkdirSync(to, { recursive: true });
diff --git a/apps/server/src/agent-context-diagnostics.test.ts b/apps/server/src/agent-context-diagnostics.test.ts
index 5c8dcf7a..c811c3c5 100644
--- a/apps/server/src/agent-context-diagnostics.test.ts
+++ b/apps/server/src/agent-context-diagnostics.test.ts
@@ -44,6 +44,14 @@ import {
} from "./runtime-opencode-config-store.js";
import type { ServerConfig, WorkspaceInfo } from "./types.js";
+import { afterAll as afterAllUnlocked, beforeAll as beforeAllUnlocked } from "bun:test";
+import { applyProviderLockAnswer, resetProviderLock } from "./provider-lock.js";
+
+// These cover the app while the server leaves model providers unlocked
+// (providers.locked false): user plugins reach the engine config only then (provider-lock.ts).
+beforeAllUnlocked(() => { applyProviderLockAnswer({ providers: { locked: false } }); });
+afterAllUnlocked(() => resetProviderLock());
+
type Served = {
port: number;
stop: (closeActiveConnections?: boolean) => void | Promise<void>;
diff --git a/apps/server/src/build-variant.ts b/apps/server/src/build-variant.ts
new file mode 100644
index 00000000..928a0eed
--- /dev/null
+++ b/apps/server/src/build-variant.ts
@@ -0,0 +1,13 @@
+/**
+ * Which build of the app this is, fixed when it is built; nothing at runtime
+ * (environment, settings) changes it.
+ *
+ * The source and `pnpm build` output are the dev variant. The desktop
+ * packaging step (apps/desktop/scripts/electron-build.mjs) stamps its copy of
+ * the compiled server "release", with the sha256 of the engine binary it
+ * bundles, unless that build was asked for the dev variant
+ * (OMNIRUSH_DESKTOP_VARIANT=dev when building). The two constants below are
+ * rewritten there line by line: keep each on one line.
+ */
+export const BUILD_VARIANT: "dev" | "release" = "dev";
+export const RELEASE_ENGINE_SHA256: string | null = null;
diff --git a/apps/server/src/engine2/import.ts b/apps/server/src/engine2/import.ts
index dac4f32e..04f408bd 100644
--- a/apps/server/src/engine2/import.ts
+++ b/apps/server/src/engine2/import.ts
@@ -37,6 +37,7 @@ import { finishEngineEnv } from "../provider-lock.js";
export { ENGINE2_IMPORT_MANIFEST } from "./imported.js";
import { ENGINE2_IMPORT_MANIFEST } from "./imported.js";
+import { releaseEngineBinary } from "../release-guard.js";
const MAX_ATTEMPTS = 3;
const IMPORT_TIMEOUT_MS = 120_000;
const LOCK_STALE_MS = 30 * 60_000;
@@ -350,7 +351,8 @@ export async function importEngine2Sessions(options: Engine2ImportOptions): Prom
}
const file = join(work, `${id}.json`);
writeFileSync(file, JSON.stringify(document), "utf8");
- const run = await runImport(options.bin, file, directory, env, options.timeoutMs ?? IMPORT_TIMEOUT_MS);
+ // A release build runs only the engine it bundles (release-guard.ts).
+ const run = await runImport((await releaseEngineBinary(options.bin)) ?? options.bin, file, directory, env, options.timeoutMs ?? IMPORT_TIMEOUT_MS);
rmSync(file, { force: true });
if (run.ok && run.output.includes(`Imported session: ${id}`)) {
manifest.imported[id] = { at: Date.now(), messages: document.messages.length, from: `opencode ${String(document.info.version ?? "2.x")}` };
diff --git a/apps/server/src/folder-write-check.ts b/apps/server/src/folder-write-check.ts
index 5a5a4995..12d0d1b7 100644
--- a/apps/server/src/folder-write-check.ts
+++ b/apps/server/src/folder-write-check.ts
@@ -16,6 +16,7 @@ import { execFile, spawn } from "node:child_process";
import { chmodSync, closeSync, fsyncSync, mkdirSync, mkdtempSync, openSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
import os from "node:os";
import path from "node:path";
+import { isReleaseBuild, releaseEngineBinary } from "./release-guard.js";
export type FolderWriteReason =
| "missing"
@@ -122,7 +123,9 @@ function isolatedBunFolder(env: NodeJS.ProcessEnv = process.env): string | null
}
/** The probe run by the engine binary; null when it could not run or said nothing usable. */
-export function probeWithEngine(dir: string, engineBin: string, timeoutMs = 15_000): Promise<FolderProbeOutcome | null> {
+export async function probeWithEngine(dir: string, engineBin: string, timeoutMs = 15_000): Promise<FolderProbeOutcome | null> {
+ // A release build runs only the engine it bundles (release-guard.ts); another binary is not run.
+ if (isReleaseBuild() && !(await releaseEngineBinary(engineBin).then(() => true, () => false))) return null;
const folder = isolatedBunFolder();
if (!folder) return Promise.resolve(null);
let exited: Promise<void> = Promise.resolve();
diff --git a/apps/server/src/managed-git-identity.ts b/apps/server/src/managed-git-identity.ts
index 93c5fe47..d872e590 100644
--- a/apps/server/src/managed-git-identity.ts
+++ b/apps/server/src/managed-git-identity.ts
@@ -16,6 +16,7 @@ import { promisify } from "node:util";
import { ApiError } from "./errors.js";
import { externalFetch } from "./server-fetch.js";
import type { ServerConfig } from "./types.js";
+import { gatewayUrlAllowed } from "./release-guard.js";
const execFileAsync = promisify(execFile);
const PROFILE_TTL_MS = 5 * 60_000;
@@ -90,6 +91,8 @@ export function accountIdentityFromProfile(profile: unknown): AccountIdentity |
}
function controlPlaneProfileUrl(gatewayUrl: string): string | null {
+ // A release build asks omnirush.ai only (release-guard.ts).
+ if (!gatewayUrlAllowed(gatewayUrl)) return null;
try {
const url = new URL(gatewayUrl);
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "::1"].includes(url.hostname))) return null;
diff --git a/apps/server/src/managed-opencode-v2.ts b/apps/server/src/managed-opencode-v2.ts
index 61f76be8..7c094e0f 100644
--- a/apps/server/src/managed-opencode-v2.ts
+++ b/apps/server/src/managed-opencode-v2.ts
@@ -13,6 +13,7 @@ import { loopbackFetch } from "./server-fetch.js";
import { writeFileAtomic } from "./atomic-write.js";
import { currentProviderLockPolicy, providerAllowed } from "./provider-lock.js";
import { providerLockEnv } from "./provider-lock/provider-lock.mjs";
+import { isReleaseBuild, RELEASE_ENGINE_ERROR } from "./release-guard.js";
export interface OpencodeV2ModelSpec {
id: string;
@@ -80,6 +81,8 @@ function diagnostics(exitCode: number | null, stdout: string, stderr: string): E
export async function createManagedOpencodeV2Server(
options: ManagedOpencodeV2ServerOptions,
): Promise<ManagedOpencodeV2Server> {
+ // A release build runs only the engine it bundles (release-guard.ts); this preview downloads another.
+ if (isReleaseBuild()) throw new Error(RELEASE_ENGINE_ERROR);
const hostname = options.hostname ?? "127.0.0.1";
const port = options.port ?? 0;
const bootTimeoutMs = options.bootTimeoutMs ?? 60_000;
diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.ts
index a19c98de..97a418ea 100644
--- a/apps/server/src/managed-opencode.ts
+++ b/apps/server/src/managed-opencode.ts
@@ -8,6 +8,7 @@ import { providerLockEnv, withProviderLockEnv } from "./provider-lock/provider-l
import { engineDataEnv } from "./engine-data-home.js";
import { repairEngineStoreBeforeStart } from "./engine-store-repair.js";
import { engineInstallLogEnv } from "./install-log-host.js";
+import { releaseEngineBinary } from "./release-guard.js";
export type ManagedChildProcess = {
pid?: number;
@@ -212,7 +213,8 @@ async function startManagedOpencodeServer(
const username = randomSecret();
const password = randomSecret();
const args = ["serve", "--hostname", hostname, "--port", String(port), "--cors", "*"];
- const command = options.bin?.trim() || "opencode";
+ // A release build runs only the engine it bundles (release-guard.ts): no other path, no PATH lookup.
+ const command = (await releaseEngineBinary(options.bin?.trim() || undefined)) || "opencode";
// The engine's in-process npm installs use Arborist, which audits by default.
// That audit POST depends on npm's advisories endpoint, which has been observed
// to hang for the full five-minute registry timeout, so first-run must not wait.
@@ -271,7 +273,7 @@ async function startManagedOpencodeServer(
await repairEngineStoreBeforeStart(env, (level, message, attributes) => {
console[level === "warn" ? "warn" : "info"](`[engine-store] ${message}`, attributes ?? {});
});
- const child: ChildProcess = spawn(options.bin?.trim() || "opencode", args, {
+ const child: ChildProcess = spawn(command, args, {
cwd: options.cwd,
env,
stdio: ["ignore", "pipe", "pipe"],
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index 205d8e26..a2214b41 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -13,6 +13,7 @@ import {
} from "./omnirush-swarm.js";
import { builtinOmniRushModelCatalog, omnirushModelWantsReasoningSummary } from "./omnirush-model-catalog.js";
import { RejectedAttachments, isRejectedAttachmentError, type Attachment } from "./rejected-attachments.js";
+import { gatewayUrlAllowed, RELEASE_GATEWAY_ERROR } from "./release-guard.js";
/** A refused attachment is left out and the model request sent again, at most this often per request. */
const MAX_ATTACHMENT_RETRIES = 2;
@@ -846,6 +847,11 @@ function normalizedGatewayUrl(value: string): string | null {
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "::1"].includes(url.hostname))) {
return null;
}
+ // A release build talks to omnirush.ai only (release-guard.ts): another address is no account.
+ if (!gatewayUrlAllowed(url.toString())) {
+ console.error(`[omnirush] ${RELEASE_GATEWAY_ERROR} The sign-in names another account server; sign in again.`);
+ return null;
+ }
return url.toString().replace(/\/+$/, "");
} catch {
return null;
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index a86d3036..dc751eef 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -41,6 +41,7 @@ const GUARDED = legacyExecutionPermissions(undefined, "guarded");
import { OMNIRUSH_AGENT_PROMPT } from "./omnirush-agent-prompt.js";
import { BestPracticesEngineReloads, OMNIRUSH_BEST_PRACTICES, omnirushBestPracticesSkillsDir, waitForBestPracticesReady } from "./best-practices.js";
import type { ServerConfig } from "./types.js";
+import { providerLockPolicy } from "./provider-lock/provider-lock.mjs";
const roots: string[] = [];
const cleanups: Array<() => void> = [];
@@ -102,10 +103,14 @@ describe("omnirush runtime config file", () => {
});
test("every plugin omnirush.ai configures is named as its own, so the engine never holds a project for their install", () => {
- const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({ plugin: ["[email protected]"] }, undefined, {}, undefined, undefined, undefined);
+ // Unlocked by the server, the user's plugin is the only one not ours; locked, the app's own only (provider-lock.ts).
+ const unlocked = providerLockPolicy({ providers: { locked: false } });
+ const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({ plugin: ["[email protected]"] }, undefined, {}, undefined, undefined, undefined, null, [], unlocked);
const plugins = Array.isArray(parsed.plugin) ? parsed.plugin.map(String) : [];
const own = new Set(omnirushOwnPluginPaths());
expect(plugins.filter((plugin) => !own.has(plugin))).toEqual(["[email protected]"]);
+ const locked = buildOmniRushRuntimeConfigObjectFromSnapshot({ plugin: ["[email protected]"] });
+ expect((locked.plugin as string[]).filter((plugin) => !own.has(plugin))).toEqual([]);
expect([...own].some((plugin) => /omnirush-box\.(?:ts|js)$/.test(plugin))).toBe(true);
});
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index 82ae3769..5f17d30a 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -70,6 +70,7 @@ import {
removeLegacyBestPracticesSkills,
writeBestPracticesSkills,
} from "./best-practices.js";
+import { gatewayUrlAllowed } from "./release-guard.js";
const INTERNAL_PROVIDER_ID = "omnirush";
@@ -81,6 +82,8 @@ function resolveInternalGatewayRuntime(
env: NodeJS.ProcessEnv = process.env,
): InternalGatewayRuntime | undefined {
const baseUrl = (env.OMNIRUSH_ENGINE_GATEWAY_URL ?? env.OMNIRUSH_GATEWAY_URL)?.trim().replace(/\/+$/, "");
+ // A release build's engine talks to omnirush.ai only (release-guard.ts); another address is not used.
+ if (baseUrl && !gatewayUrlAllowed(baseUrl)) return undefined;
const accessToken = env.OMNIRUSH_ACCESS_TOKEN?.trim();
if (!baseUrl || !accessToken) return undefined;
@@ -336,7 +339,9 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
},
plugin: [
...omnirushLeadingPluginPaths(),
- ...runtimePluginList(runtimeConfig),
+ // The user's plugins only while model providers are unlocked (provider-lock.ts): locked, the
+ // engine loads the app's own plugins and built-ins only.
+ ...(providerLock.locked ? [] : runtimePluginList(runtimeConfig)),
// This must be last: it applies the server's MCP list to the final
// configuration, after every other plugin.
omnirushMcpPolicyPluginPath(),
diff --git a/apps/server/src/provider-lock.test.ts b/apps/server/src/provider-lock.test.ts
index f53bf191..7ccbe44d 100644
--- a/apps/server/src/provider-lock.test.ts
+++ b/apps/server/src/provider-lock.test.ts
@@ -9,7 +9,9 @@ import { buildOmniRushRuntimeConfigObjectFromSnapshot } from "./omnirush-runtime
import { builtinOmniRushModelCatalog } from "./omnirush-model-catalog.js";
import {
applyProviderLockAnswer,
+ assertConfigWithinLock,
assertConfigWithinProviderLock,
+ assertPluginsUnlocked,
assertProxiedEngineRequestWithinProviderLock,
currentProviderLockPolicy,
engineRequestProviderLockDenial,
@@ -47,11 +49,12 @@ describe("provider lock: fails closed", () => {
expect(currentProviderLockPolicy().locked).toBe(true);
});
- test("the server's allow list and message are taken, omnirush always first", () => {
- applyProviderLockAnswer({ providers: { locked: true, allow: ["acme", "BAD ID", 7], message: "Ask your admin." } });
- expect(currentProviderLockPolicy()).toMatchObject({ locked: true, allow: ["omnirush", "acme"], message: "Ask your admin." });
- expect(providerAllowed("acme")).toBe(true);
+ test("the server's message is taken; only omnirush counts as allowed, whatever the list says", () => {
+ applyProviderLockAnswer({ providers: { locked: true, allow: ["acme", "openai", "BAD ID", 7], message: "Ask your admin." } });
+ expect(currentProviderLockPolicy()).toMatchObject({ locked: true, allow: ["omnirush"], message: "Ask your admin." });
+ expect(providerAllowed("acme")).toBe(false);
expect(providerAllowed("openai")).toBe(false);
+ expect(providerAllowed("omnirush")).toBe(true);
});
test("the watcher re-reads, applies a change, and locks on a failed read", async () => {
@@ -129,6 +132,16 @@ describe("provider lock: engine config", () => {
}
});
+ test("locked: the user's plugins stay out of the engine config; the app's own stay", () => {
+ const locked = build({ plugin: ["opencode-wakatime", "file:///home/u/evil.ts"] });
+ const plugins = locked.plugin as string[];
+ expect(plugins.some((entry) => entry.includes("wakatime") || entry.includes("evil"))).toBe(false);
+ expect(plugins.length).toBeGreaterThan(0);
+ expect(plugins).toEqual(build({}).plugin as string[]);
+ applyProviderLockAnswer(UNLOCKED);
+ expect(build({ plugin: ["opencode-wakatime"] }).plugin as string[]).toContain("opencode-wakatime");
+ });
+
test("locked and signed out: still only the allowed providers, and no other provider's map", () => {
const config = build({ provider: userProviders }, { OMNIRUSH_ALLOW_OTHER_PROVIDERS: "1" }, false);
expect(config.enabled_providers).toEqual(["omnirush"]);
@@ -164,7 +177,7 @@ describe("provider lock: engine environment", () => {
test("unlocked: the environment as it was", () => {
applyProviderLockAnswer(UNLOCKED);
- expect(lockedEngineEnv({ OPENCODE_CONFIG_CONTENT: "{}" }, { A: "1" })).toEqual({ OPENCODE_CONFIG_CONTENT: "{}", A: "1" });
+ expect(lockedEngineEnv({ OPENCODE_CONFIG_CONTENT: "{}", OMNIRUSH_PROVIDER_LOCK: "1" }, { A: "1" })).toEqual({ OPENCODE_CONFIG_CONTENT: "{}", A: "1", OMNIRUSH_PROVIDER_LOCK: "0" });
});
test("every managed engine spawn gets the lock, also over the caller's and the user's values", async () => {
@@ -250,6 +263,16 @@ describe("provider lock: refusals", () => {
await assertProxiedEngineRequestWithinProviderLock(ok, "/opencode/session/s/prompt_async");
});
+ test("plugins: config and engine writes that add a user plugin are refused while locked", () => {
+ expect(() => assertConfigWithinLock({ plugin: ["opencode-wakatime"] })).toThrow("Custom plugins are off while OmniRush models are locked.");
+ expect(() => assertConfigWithinLock({ plugin: [] })).not.toThrow();
+ expect(() => assertPluginsUnlocked()).toThrow("Custom plugins are off while OmniRush models are locked.");
+ expect(engineRequestProviderLockDenial("PATCH", "/config", { plugin: ["x"] })).toBe("Custom plugins are off while OmniRush models are locked.");
+ applyProviderLockAnswer(UNLOCKED);
+ expect(() => assertConfigWithinLock({ plugin: ["opencode-wakatime"] })).not.toThrow();
+ expect(() => assertPluginsUnlocked()).not.toThrow();
+ });
+
test("config writes that add another provider or its model are refused", () => {
expect(() => assertConfigWithinProviderLock({ provider: { ollama: {} } })).toThrow("Only OmniRush models are available.");
expect(() => assertConfigWithinProviderLock({ enabled_providers: ["openai"] })).toThrow();
diff --git a/apps/server/src/provider-lock.ts b/apps/server/src/provider-lock.ts
index 04277045..35a7de41 100644
--- a/apps/server/src/provider-lock.ts
+++ b/apps/server/src/provider-lock.ts
@@ -29,6 +29,8 @@ import {
lockEngineConfig,
lockedProviderPolicy,
modelRefAllowed,
+ OMNIRUSH_PROVIDER_ID,
+ PLUGINS_OFF_MESSAGE,
providerLockEnv,
providerLockPolicy,
withProviderLockEnv,
@@ -39,6 +41,9 @@ export type { ProviderLockPolicy } from "./provider-lock/provider-lock.mjs";
export { lockEngineConfig, modelRefAllowed, providerLockPolicy, withProviderLockEnv } from "./provider-lock/provider-lock.mjs";
export const PROVIDER_LOCKED_CODE = "provider_locked";
+export const PLUGINS_LOCKED_CODE = "plugins_locked";
+/** User plugins while locked: the engine loads only the app's own (owner decision). */
+export const PLUGINS_LOCKED_MESSAGE: string = PLUGINS_OFF_MESSAGE;
let current: ProviderLockPolicy = lockedProviderPolicy("default");
@@ -56,7 +61,9 @@ function samePolicy(left: ProviderLockPolicy, right: ProviderLockPolicy): boolea
* answer, which is locked). Whether the policy in force changed.
*/
export function applyProviderLockAnswer(capabilities: unknown): boolean {
- const next = providerLockPolicy(capabilities ?? null);
+ const parsed = providerLockPolicy(capabilities ?? null);
+ // Only OmniRush's own provider counts as allowed, whatever else a server lists.
+ const next = parsed.locked ? { ...parsed, allow: parsed.allow.filter((id) => id === OMNIRUSH_PROVIDER_ID) } : parsed;
const changed = !samePolicy(current, next);
current = next;
return changed;
@@ -143,6 +150,24 @@ export function parseJsoncContent(content: string): Record<string, unknown> | nu
}
}
+/** Whether a config (a file's content, a PATCH) names engine plugins of its own. */
+export function configAddsPlugins(config: unknown): boolean {
+ if (!isRecord(config) || !("plugin" in config)) return false;
+ const plugin = config.plugin;
+ return typeof plugin === "string" ? plugin.trim().length > 0 : Array.isArray(plugin) && plugin.length > 0;
+}
+
+/** Throws 403 plugins_locked while locked (routes that add or turn on a user plugin). */
+export function assertPluginsUnlocked(policy: ProviderLockPolicy = current): void {
+ if (policy.locked) throw new ApiError(403, PLUGINS_LOCKED_CODE, PLUGINS_LOCKED_MESSAGE);
+}
+
+/** Throws 403 when a config would add another provider (provider_locked) or plugins (plugins_locked) while locked. */
+export function assertConfigWithinLock(config: unknown, policy: ProviderLockPolicy = current): void {
+ assertConfigWithinProviderLock(config, policy);
+ if (configAddsPlugins(config)) assertPluginsUnlocked(policy);
+}
+
/** Throws 403 provider_locked when the config would bring in another provider. */
export function assertConfigWithinProviderLock(config: unknown, policy: ProviderLockPolicy = current): void {
if (providerLockConfigViolations(config, policy).length) throw providerLockedError(policy);
@@ -178,6 +203,7 @@ export function engineRequestProviderLockDenial(
const oauth = path.match(/^\/provider\/([^/]+)\/oauth(?:\/|$)/);
if (oauth) return providerAllowed(decodeURIComponent(oauth[1] ?? ""), policy) ? null : policy.message;
if (/^\/(?:global\/)?config\/?$/.test(path)) {
+ if (configAddsPlugins(body)) return PLUGINS_LOCKED_MESSAGE;
return providerLockConfigViolations(body, policy).length ? policy.message : null;
}
if (/^\/session(?:\/|$)/.test(path)) {
@@ -192,7 +218,7 @@ export function engineRequestProviderLockDenial(
/** Throws 403 provider_locked for engineRequestProviderLockDenial(). */
export function assertEngineRequestWithinProviderLock(method: string, enginePath: string, body: Record<string, unknown>, policy: ProviderLockPolicy = current): void {
const denial = engineRequestProviderLockDenial(method, enginePath, body, policy);
- if (denial) throw new ApiError(403, PROVIDER_LOCKED_CODE, denial);
+ if (denial) throw new ApiError(403, denial === PLUGINS_LOCKED_MESSAGE ? PLUGINS_LOCKED_CODE : PROVIDER_LOCKED_CODE, denial);
}
/**
@@ -245,6 +271,12 @@ export function watchProviderLock({ read, apply, everyMs }: { read: () => Promis
}
/** The policy for the app's UI (GET /omnirush/provider-lock). */
-export function providerLockStatus(policy: ProviderLockPolicy = current): { locked: boolean; allow: string[]; message: string; source: string } {
- return { locked: policy.locked, allow: [...policy.allow], message: policy.message, source: policy.source };
+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 {
+ locked: policy.locked,
+ allow: [...policy.allow],
+ message: policy.message,
+ source: policy.source,
+ plugins: { off: policy.locked, message: policy.locked ? PLUGINS_LOCKED_MESSAGE : null, userPlugins },
+ };
}
diff --git a/apps/server/src/provider-lock/PARITY.sha256 b/apps/server/src/provider-lock/PARITY.sha256
index 46b85eab..6a737686 100644
--- a/apps/server/src/provider-lock/PARITY.sha256
+++ b/apps/server/src/provider-lock/PARITY.sha256
@@ -1,4 +1,4 @@
# The model-provider lock module: the same files in omnirush-cli (src/provider-lock/) and omnirush-gui (apps/server/src/provider-lock/).
# A change to one must be ported to the other and this list updated in both.
-70d8f48616bf62b224b284dab6a2245a5778dbf7c1ac6768f2c600b0107dbd57 provider-lock.mjs
-c57d3cea2443066a1687f902e9d1e6bc592cf5e3033ed9854814a6c572edfe06 provider-lock.d.mts
+c9a83c525b2273e9d6ef0265c684e6c98726371b91778db1d031caf42eb3e213 provider-lock.mjs
+c44dcf519ebaff78013e192961f987db1ebf15f36f6dabbf7091f290f1e0dd32 provider-lock.d.mts
diff --git a/apps/server/src/provider-lock/provider-lock.d.mts b/apps/server/src/provider-lock/provider-lock.d.mts
index d568f998..482d3eec 100644
--- a/apps/server/src/provider-lock/provider-lock.d.mts
+++ b/apps/server/src/provider-lock/provider-lock.d.mts
@@ -3,6 +3,7 @@
export const OMNIRUSH_PROVIDER_ID: "omnirush";
export const PROVIDER_LOCK_MESSAGE: string;
+export const PLUGINS_OFF_MESSAGE: string;
export const PROVIDER_ID_PATTERN: RegExp;
export const ENGINE_CONFIG_INJECTION_ENV: readonly string[];
@@ -18,6 +19,6 @@ export function lockedProviderPolicy(source?: ProviderLockPolicy["source"]): Pro
export function providerLockPolicy(capabilities: unknown): ProviderLockPolicy;
export function modelProvider(ref: unknown): string | null;
export function modelRefAllowed(policy: ProviderLockPolicy | null | undefined, ref: unknown): boolean;
-export function providerLockEnv(policy: ProviderLockPolicy | null | undefined): { set: Record<string, string>; remove: string[] };
+export function providerLockEnv(policy?: ProviderLockPolicy | null): { set: Record<string, string>; remove: string[] };
export function withProviderLockEnv<T extends Record<string, string | undefined>>(env: T, policy: ProviderLockPolicy | null | undefined): Record<string, string | undefined>;
export function lockEngineConfig<T>(config: T, policy: ProviderLockPolicy | null | undefined): { config: T; removed: string[] };
diff --git a/apps/server/src/provider-lock/provider-lock.mjs b/apps/server/src/provider-lock/provider-lock.mjs
index ae9caf80..0ece70fa 100644
--- a/apps/server/src/provider-lock/provider-lock.mjs
+++ b/apps/server/src/provider-lock/provider-lock.mjs
@@ -23,8 +23,8 @@
export const OMNIRUSH_PROVIDER_ID = "omnirush";
export const PROVIDER_LOCK_MESSAGE = "Only OmniRush models are available.";
+export const PLUGINS_OFF_MESSAGE = "Custom plugins are off while OmniRush models are locked.";
export const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
-const MAX_ALLOW = 16;
const MAX_MESSAGE = 300;
/**
@@ -66,14 +66,9 @@ export function providerLockPolicy(capabilities) {
if (!isRecord(block)) return lockedProviderPolicy(isRecord(capabilities) ? "missing" : "default");
const message = cleanMessage(block.message);
if (block.locked === false) return { locked: false, allow: [], message, source: "server" };
+ // Only OmniRush's own provider can be allowed: other ids in `allow` are ignored (the engine would not
+ // trust their definitions anyway).
const allow = [OMNIRUSH_PROVIDER_ID];
- if (Array.isArray(block.allow)) {
- for (const id of block.allow) {
- if (typeof id !== "string" || !PROVIDER_ID_PATTERN.test(id) || allow.includes(id)) continue;
- if (allow.length >= MAX_ALLOW) break;
- allow.push(id);
- }
- }
return { locked: true, allow, message, source: "server" };
}
@@ -90,18 +85,20 @@ export function modelProvider(ref) {
* provider) is the app's own catalog's to resolve, so it passes here.
*/
export function modelRefAllowed(policy, ref) {
- if (!policy?.locked) return true;
+ if (policy && policy.locked === false) return true;
const provider = modelProvider(ref);
- return provider === null || policy.allow.includes(provider);
+ return provider === null || (policy ?? lockedProviderPolicy()).allow.includes(provider);
}
/**
* The engine environment changes for `policy`: `set` to add, `remove` to
- * delete from the inherited environment. Unlocked: nothing (the app runs as
- * it did before the lock existed).
+ * delete from the inherited environment. Unlocked: only OMNIRUSH_PROVIDER_LOCK=0
+ * (the app runs as it did before the lock existed). No policy is locked.
*/
-export function providerLockEnv(policy) {
- if (!policy?.locked) return { set: {}, remove: [] };
+export function providerLockEnv(policy = null) {
+ policy = policy ?? lockedProviderPolicy();
+ // Unlocked by the server: the engine is told so (it is locked unless OMNIRUSH_PROVIDER_LOCK=0).
+ if (policy && policy.locked === false) return { set: { OMNIRUSH_PROVIDER_LOCK: "0" }, remove: [] };
return {
set: {
OMNIRUSH_PROVIDER_LOCK: "1",
@@ -131,7 +128,8 @@ export function withProviderLockEnv(env, policy) {
* as it is.
*/
export function lockEngineConfig(config, policy) {
- if (!policy?.locked || !isRecord(config)) return { config, removed: [] };
+ policy = policy ?? lockedProviderPolicy();
+ if (policy.locked === false || !isRecord(config)) return { config, removed: [] };
const removed = [];
const out = { ...config };
if (isRecord(out.provider)) {
diff --git a/apps/server/src/release-guard.test.ts b/apps/server/src/release-guard.test.ts
new file mode 100644
index 00000000..6c5c5e0c
--- /dev/null
+++ b/apps/server/src/release-guard.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { BUILD_VARIANT, RELEASE_ENGINE_SHA256 } from "./build-variant.js";
+import { allowedGatewayUrlFromEnv, assertGatewayUrlAllowed, gatewayUrlAllowed, releaseEngineBinary } from "./release-guard.js";
+
+const DEV = { release: false, engineSha256: null };
+const roots: string[] = [];
+afterEach(async () => {
+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });
+});
+
+describe("release build guard", () => {
+ test("the source is the dev variant; packaging stamps release (apps/desktop/scripts/stamp-build-variant.mjs)", () => {
+ expect(BUILD_VARIANT).toBe("dev");
+ expect(RELEASE_ENGINE_SHA256).toBeNull();
+ });
+
+ test("release: only https omnirush.ai and its subdomains, as an error otherwise", () => {
+ const release = { release: true, engineSha256: null };
+ for (const ok of ["https://omnirush.ai/omnirush/v1", "https://api.omnirush.ai/omnirush/v1", "https://OMNIRUSH.AI"]) expect([ok, gatewayUrlAllowed(ok, release)]).toEqual([ok, true]);
+ for (const bad of ["http://omnirush.ai", "http://127.0.0.1:8090/omnirush/v1", "https://omnirush.ai.evil.example", "https://evilomnirush.ai", "https://omnirush.ai:8443", "https://user:[email protected]", "https://example.com", "not a url", ""]) {
+ expect([bad, gatewayUrlAllowed(bad, release)]).toEqual([bad, false]);
+ }
+ expect(() => assertGatewayUrlAllowed("http://localhost:1", "OMNIRUSH_GATEWAY_URL", release)).toThrow("only connects to omnirush.ai");
+ expect(allowedGatewayUrlFromEnv("http://localhost:1", "OMNIRUSH_GATEWAY_URL", release)).toBeUndefined();
+ expect(allowedGatewayUrlFromEnv("https://omnirush.ai/omnirush/v1", "OMNIRUSH_GATEWAY_URL", release)).toBe("https://omnirush.ai/omnirush/v1");
+ });
+
+ test("dev variant: any address, as before", () => {
+ expect(gatewayUrlAllowed("http://127.0.0.1:8090/omnirush/v1", DEV)).toBe(true);
+ expect(gatewayUrlAllowed("https://gateway.example/omnirush/v1")).toBe(true);
+ });
+
+ test("release: only the bundled engine, by its sha256; dev: the binary as given", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-release-guard-"));
+ roots.push(root);
+ const bin = join(root, "opencode");
+ await writeFile(bin, "#!/bin/sh\necho engine\n");
+ await chmod(bin, 0o755);
+ const sha = createHash("sha256").update("#!/bin/sh\necho engine\n").digest("hex");
+ const release = { release: true, engineSha256: sha };
+ expect(await releaseEngineBinary(bin, release)).toBe(bin);
+ await expect(releaseEngineBinary("opencode", release)).rejects.toThrow("only runs the engine it ships with");
+ await expect(releaseEngineBinary(undefined, release)).rejects.toThrow("only runs the engine it ships with");
+ await expect(releaseEngineBinary(bin, { release: true, engineSha256: null })).rejects.toThrow();
+ 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");
+ 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.ts
new file mode 100644
index 00000000..a2c0b0dc
--- /dev/null
+++ b/apps/server/src/release-guard.ts
@@ -0,0 +1,105 @@
+/**
+ * What a release build of the desktop app (build-variant.ts) refuses:
+ * - an account server or gateway other than https://omnirush.ai or
+ * https://<name>.omnirush.ai, from any source (environment, settings, a
+ * stored or renewed sign-in). Such an address is an error, never a
+ * fallback;
+ * - an engine binary other than the one the app bundles (its sha256 is
+ * stamped into the build).
+ * The dev variant takes any address and engine, as before.
+ */
+import { createHash } from "node:crypto";
+import { createReadStream, statSync } from "node:fs";
+import { isAbsolute } from "node:path";
+
+import { BUILD_VARIANT, RELEASE_ENGINE_SHA256 } from "./build-variant.js";
+
+export type BuildFacts = { release: boolean; engineSha256: string | null };
+
+export function buildFacts(): BuildFacts {
+ return { release: BUILD_VARIANT === "release", engineSha256: RELEASE_ENGINE_SHA256 };
+}
+
+export function isReleaseBuild(facts: BuildFacts = buildFacts()): boolean {
+ return facts.release;
+}
+
+/** Whether a release build may use `raw` as its account server or gateway (any address in the dev variant). */
+export function gatewayUrlAllowed(raw: unknown, facts: BuildFacts = buildFacts()): boolean {
+ if (!facts.release) return true;
+ if (typeof raw !== "string") return false;
+ try {
+ const url = new URL(raw.trim());
+ const host = url.hostname.toLowerCase();
+ return url.protocol === "https:"
+ && !url.username
+ && !url.password
+ && url.port === ""
+ && (host === "omnirush.ai" || host.endsWith(".omnirush.ai"));
+ } catch {
+ return false;
+ }
+}
+
+export const RELEASE_GATEWAY_ERROR = "This build of OmniRush.ai only connects to omnirush.ai.";
+
+/** Throws unless gatewayUrlAllowed(); `what` names the setting in the error. */
+export function assertGatewayUrlAllowed(raw: unknown, what: string, facts: BuildFacts = buildFacts()): void {
+ if (!gatewayUrlAllowed(raw, facts)) throw new Error(`${RELEASE_GATEWAY_ERROR} ${what} is not an omnirush.ai address.`);
+}
+
+/**
+ * A gateway address from the environment (OMNIRUSH_GATEWAY_URL and the like):
+ * returned when allowed; in a release build anything else is reported once
+ * and not used (no other address takes its place).
+ */
+export function allowedGatewayUrlFromEnv(raw: string | undefined, name: string, facts: BuildFacts = buildFacts()): string | undefined {
+ if (raw === undefined || !raw.trim()) return raw;
+ if (gatewayUrlAllowed(raw, facts)) return raw;
+ reportOnce(`${name}`, `${RELEASE_GATEWAY_ERROR} ${name} is not an omnirush.ai address and is not used.`);
+ return undefined;
+}
+
+const reported = new Set<string>();
+function reportOnce(key: string, message: string): void {
+ if (reported.has(key)) return;
+ reported.add(key);
+ console.error(`[omnirush] ${message}`);
+}
+
+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 }>();
+
+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;
+}
+
+/**
+ * The engine binary to run. In a release build: `bin` must be an absolute
+ * path to a file whose sha256 is the one stamped into the build (the bundled
+ * engine); anything else, no path, or no stamped hash throws. In the dev
+ * variant, `bin` as given.
+ */
+export async function releaseEngineBinary(bin: string | undefined | null, facts: BuildFacts = buildFacts()): Promise<string | undefined> {
+ if (!facts.release) return bin ?? undefined;
+ const path = bin?.trim() ?? "";
+ if (!facts.engineSha256 || !path || !isAbsolute(path)) throw new Error(`${RELEASE_ENGINE_ERROR} No bundled engine was found.`);
+ let actual: string;
+ try {
+ actual = await fileSha256(path);
+ } catch {
+ throw new Error(`${RELEASE_ENGINE_ERROR} The bundled engine could not be read.`);
+ }
+ if (actual !== facts.engineSha256) throw new Error(`${RELEASE_ENGINE_ERROR} The engine at ${path} is not the bundled one. Reinstall OmniRush.ai.`);
+ return path;
+}
diff --git a/apps/server/src/runtime-config-global-providers.test.ts b/apps/server/src/runtime-config-global-providers.test.ts
index 48f1c798..f91284de 100644
--- a/apps/server/src/runtime-config-global-providers.test.ts
+++ b/apps/server/src/runtime-config-global-providers.test.ts
@@ -112,8 +112,15 @@ describe("global runtime providers", () => {
const prompt = await fetch(`${base}/workspace/ws_1/opencode/session/ses_x/prompt_async`, { method: "POST", headers: clientHeaders(), body: JSON.stringify({ model: { providerID: "anthropic", modelID: "m" }, parts: [] }) });
expect(prompt.status).toBe(403);
expect(await readJsonObject(prompt)).toMatchObject({ code: "provider_locked" });
+ const plugin = await fetch(`${base}/workspace/ws_1/plugins`, { method: "POST", headers: clientHeaders(), body: JSON.stringify({ spec: "opencode-wakatime" }) });
+ expect(plugin.status).toBe(403);
+ expect(await readJsonObject(plugin)).toMatchObject({ code: "plugins_locked", message: "Custom plugins are off while OmniRush models are locked." });
+ const pluginPatch = await fetch(`${base}/workspace/ws_1/config`, { method: "PATCH", headers: clientHeaders(), body: JSON.stringify({ opencode: { plugin: ["opencode-wakatime"] } }) });
+ expect(pluginPatch.status).toBe(403);
+ const enginePlugin = await fetch(`${base}/opencode/config`, { method: "PATCH", headers: clientHeaders(), body: JSON.stringify({ plugin: ["opencode-wakatime"] }) });
+ expect(enginePlugin.status).toBe(403);
const status = await fetch(`${base}/omnirush/provider-lock`, { headers: clientHeaders() });
- expect(await readJsonObject(status)).toMatchObject({ locked: true, allow: ["omnirush"] });
+ expect(await readJsonObject(status)).toMatchObject({ locked: true, allow: ["omnirush"], plugins: { off: true, message: "Custom plugins are off while OmniRush models are locked." } });
expect(runtimeProviderMap(await readGlobalRuntimeOpencodeConfig(config))).toEqual({});
} finally {
applyProviderLockAnswer({ providers: { locked: false } });
diff --git a/apps/server/src/runtime-opencode-config-store.test.ts b/apps/server/src/runtime-opencode-config-store.test.ts
index 6e817649..abfcc701 100644
--- a/apps/server/src/runtime-opencode-config-store.test.ts
+++ b/apps/server/src/runtime-opencode-config-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from "bun:test";
+import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -22,6 +22,9 @@ import {
} from "./runtime-opencode-config-store.js";
import { startServer } from "./server.js";
import type { ServerConfig } from "./types.js";
+import { applyProviderLockAnswer, resetProviderLock } from "./provider-lock.js";
+
+afterEach(() => resetProviderLock());
const WORKSPACE_ID = "ws_runtime_test";
@@ -163,6 +166,8 @@ describe("runtime OpenCode config store", () => {
});
test("stores plugin changes in the OmniRush.ai runtime DB without rewriting workspace files", async () => {
+ // The injected file carries user plugins only while the server leaves providers unlocked (provider-lock.ts).
+ applyProviderLockAnswer({ providers: { locked: false } });
await withWorkspace(async ({ root, config }) => {
const opencodePath = join(root, "opencode.jsonc");
const opencode = '{\n "plugin": ["project-plugin"]\n}\n';
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 28085d56..171fdbac 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -188,9 +188,11 @@ import { createChatTracker, rememberComputerUseSwitch } from "./computer-use/des
import { registerComputerUseRoutes } from "./computer-use/routes.js";
import {
applyProviderLockAnswer,
- assertConfigWithinProviderLock,
+ assertConfigWithinLock,
+ assertPluginsUnlocked,
assertProviderAllowed,
assertProxiedEngineRequestWithinProviderLock,
+ currentProviderLockPolicy,
parseJsoncContent,
providerLockStatus,
watchProviderLock,
@@ -3173,6 +3175,12 @@ async function applyBoxEngineConfig(config: ServerConfig, reason: string, option
const pool = enginePoolForConfig(config);
const workspaces = config.workspaces.filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim());
const workspace = findManagedEngineWorkspace(workspaces) ?? workspaces[0];
+ if (!pool && workspace && options.restart) {
+ // No managed pool (an engine the app does not start): the lock still reaches it through the
+ // rewritten config file and the dispose reload, on every workspace's engine.
+ for (const entry of workspaces) await reloadOpencodeEngine(config, entry).catch(() => undefined);
+ return { status: "applied" };
+ }
if (!pool || !workspace) return { status: "unmanaged" };
const outcome = await pool.requestRollover({ reason, workspace, manual: true });
return { status: outcome.action === "coalesced" ? "deferred" : outcome.action === "skipped" ? "failed" : "applied" };
@@ -4425,7 +4433,15 @@ function createRoutes(
addRoute(routes, "POST", LEGACY_SESSION_UPLOAD_EVENTS_ROUTE, "policy", sessionUploadEvents);
// The model provider lock (provider-lock.ts): what the app's model pickers and provider screens show.
- addRoute(routes, "GET", "/omnirush/provider-lock", "client", async () => jsonResponse(providerLockStatus()));
+ addRoute(routes, "GET", "/omnirush/provider-lock", "client", async () => {
+ // How many plugins of the user's own the lock keeps off (the app tells the user once).
+ let userPlugins = 0;
+ const workspace = config.workspaces.find((entry) => entry.workspaceType !== "remote");
+ if (workspace && currentProviderLockPolicy().locked) {
+ userPlugins = await listPlugins(config, workspace.id, workspace.path, true).then((result) => result.items.length, () => 0);
+ }
+ return jsonResponse(providerLockStatus(currentProviderLockPolicy(), userPlugins));
+ });
// Sub-agent model and effort (omnirush-subagent-model.ts). The app reads
// and writes the setting; the swarm engine plugin resolves every sub-agent
@@ -4731,7 +4747,7 @@ function createRoutes(
const configPath = resolveOpencodeConfigFilePath(scope, workspace.path);
// The model provider lock (provider-lock.ts): a file that adds another provider or names its model is refused.
- assertConfigWithinProviderLock(parseJsoncContent(content));
+ assertConfigWithinLock(parseJsoncContent(content));
await requireApproval(ctx, {
workspaceId: workspace.id,
action: scope === "global" ? "config.global.write" : "config.write",
@@ -4818,7 +4834,7 @@ function createRoutes(
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);
- assertConfigWithinProviderLock(topLevelUpdates);
+ assertConfigWithinLock(topLevelUpdates);
if (Object.keys(providerUpdate).length) await managedDesktopPolicy(config).assert("provider");
if (Object.keys(providerUpdate).length) {
const providerResult = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({
@@ -4973,6 +4989,8 @@ function createRoutes(
ensureWritable(config);
requireClientScope(ctx, "collaborator");
const workspace = await resolveWorkspace(config, ctx.params.id);
+ // User plugins are off while model providers are locked (provider-lock.ts).
+ assertPluginsUnlocked();
const body = await readJsonBody(ctx.request);
const spec = String(body.spec ?? "");
const normalized = normalizePluginSpec(spec);
diff --git a/apps/server/src/session-archive/upload.ts b/apps/server/src/session-archive/upload.ts
index 971df030..4dd427ee 100644
--- a/apps/server/src/session-archive/upload.ts
+++ b/apps/server/src/session-archive/upload.ts
@@ -9,6 +9,7 @@ import { z } from "zod";
import { parseArchivePolicy, type ArchivePolicy } from "./policy.js";
import { SEAL_ALG, SEAL_CONTENT, sealKid } from "./seal.js";
+import { gatewayUrlAllowed } from "../release-guard.js";
export type ArchiveFetch = (input: string, init?: RequestInit) => Promise<Response>;
/**
@@ -97,6 +98,8 @@ const CHAIN_ENDING_CODES = new Set(["archive_id_conflict", "archive_sequence_con
export function resolveArchiveApiRoot(rawGatewayUrl: string | undefined): string | null {
const value = rawGatewayUrl?.trim();
if (!value) return null;
+ // A release build sends to omnirush.ai only (release-guard.ts).
+ if (!gatewayUrlAllowed(value)) return null;
try {
const url = new URL(value);
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]", "::1"].includes(url.hostname))) return null;
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index cd54e016..676007e7 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -44,6 +44,7 @@ import serverPackage from "../package.json" with { type: "json" };
import { BUNDLED_ENGINE_VERSION, BUNDLED_HARNESS, type Harness } from "./engine-identity.js";
import { mcpServersInUse, workspaceMcpReport, type McpServerUse } from "./mcp-allow/state.js";
import type { ComputerUseEnvironment } from "./computer-use/desktop.js";
+import { gatewayUrlAllowed } from "./release-guard.js";
const execFileAsync = promisify(execFile);
@@ -1203,6 +1204,8 @@ export function sessionUploaderEnabled(input: { upload: boolean; gatewayUrl?: st
function resolveUploadUrl(rawGatewayUrl: string | undefined): string | null {
const value = rawGatewayUrl?.trim();
if (!value) return null;
+ // A release build sends to omnirush.ai only (release-guard.ts).
+ if (!gatewayUrlAllowed(value)) return null;
try {
const url = new URL(value);
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "::1"].includes(url.hostname))) {