Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: settings changes need the app itself

ogsamratd4cce422026c
diff --git a/apps/desktop/electron/app-request-secret.mjs b/apps/desktop/electron/app-request-secret.mjs
new file mode 100644
index 00000000..99790b63
--- /dev/null
+++ b/apps/desktop/electron/app-request-secret.mjs
@@ -0,0 +1,57 @@
+// The per-launch secret that proves a request to the local server comes from this app (its window,
+// or Electron main itself). Held in this process only: never on disk, never in an environment, never
+// visible to the renderer's scripts. The local server runs in this process and reads it from the
+// same global (apps/server/src/app-request-gate.ts): settings writes, secret reads and approval
+// answers need it, so a server token read from the profile folder or a process environment cannot
+// change what the person decided.
+import { randomBytes } from "node:crypto";
+
+export const APP_SECRET_HEADER = "x-omnirush-app-secret";
+const SECRET_KEY = Symbol.for("omnirush.app.request-secret");
+if (typeof globalThis[SECRET_KEY] !== "string") globalThis[SECRET_KEY] = randomBytes(32).toString("hex");
+const SECRET = globalThis[SECRET_KEY];
+
+const origins = new Set();
+
+function originOf(url) {
+ try {
+ const parsed = new URL(String(url));
+ return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The local server's address (each start may bind another port). */
+export function rememberLocalServer(baseUrl) {
+ const origin = originOf(baseUrl);
+ if (origin && /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/.test(origin)) origins.add(origin);
+}
+
+/** Headers for Electron main's own request to `url`: the secret only for the local server. */
+export function appSecretHeaders(url) {
+ const origin = originOf(url);
+ return origin && origins.has(origin) ? { [APP_SECRET_HEADER]: SECRET } : {};
+}
+
+/**
+ * Adds the secret to the app window's requests to the local server (and only those: another page,
+ * another webContents or another address never gets it), and drops any copy a page set itself.
+ * `isAppContents(webContentsId)` names the app's own window(s).
+ */
+export function installAppRequestSecret(targetSession, isAppContents) {
+ targetSession.webRequest.onBeforeSendHeaders(
+ { urls: ["http://127.0.0.1/*", "http://localhost/*", "http://[::1]/*"] },
+ (details, callback) => {
+ const requestHeaders = {};
+ for (const [name, value] of Object.entries(details.requestHeaders ?? {})) {
+ if (name.toLowerCase() !== APP_SECRET_HEADER) requestHeaders[name] = value;
+ }
+ const origin = originOf(details.url);
+ let fromApp = false;
+ try { fromApp = typeof details.webContentsId === "number" && isAppContents(details.webContentsId); } catch { fromApp = false; }
+ if (fromApp && origin && origins.has(origin)) requestHeaders[APP_SECRET_HEADER] = SECRET;
+ callback({ requestHeaders });
+ },
+ );
+}
diff --git a/apps/desktop/electron/app-request-secret.test.mjs b/apps/desktop/electron/app-request-secret.test.mjs
new file mode 100644
index 00000000..0cab544c
--- /dev/null
+++ b/apps/desktop/electron/app-request-secret.test.mjs
@@ -0,0 +1,36 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { APP_SECRET_HEADER, appSecretHeaders, installAppRequestSecret, rememberLocalServer } from "./app-request-secret.mjs";
+
+const SECRET = globalThis[Symbol.for("omnirush.app.request-secret")];
+
+test("the secret exists once per launch, in this process only", () => {
+ assert.equal(typeof SECRET, "string");
+ assert.ok(SECRET.length >= 64);
+ assert.equal(process.env[APP_SECRET_HEADER], undefined);
+ assert.ok(!Object.values(process.env).includes(SECRET));
+});
+
+test("Electron main's own requests carry it to the local server only", () => {
+ rememberLocalServer("http://127.0.0.1:43123");
+ assert.deepEqual(appSecretHeaders("http://127.0.0.1:43123/tokens"), { [APP_SECRET_HEADER]: SECRET });
+ assert.deepEqual(appSecretHeaders("http://127.0.0.1:43124/tokens"), {});
+ assert.deepEqual(appSecretHeaders("https://omnirush.ai/tokens"), {});
+ rememberLocalServer("https://example.com");
+ assert.deepEqual(appSecretHeaders("https://example.com/x"), {});
+});
+
+test("the app window's requests to the local server get it; other pages, ports and copies a page set do not", () => {
+ rememberLocalServer("http://127.0.0.1:43123");
+ let listener = null;
+ const session = { webRequest: { onBeforeSendHeaders: (filter, fn) => { assert.ok(filter.urls.includes("http://127.0.0.1/*")); listener = fn; } } };
+ installAppRequestSecret(session, (id) => id === 7);
+ const run = (details) => { let out = null; listener(details, (result) => { out = result.requestHeaders; }); return out; };
+ assert.equal(run({ webContentsId: 7, url: "http://127.0.0.1:43123/runtime-config/approvals", requestHeaders: { Authorization: "Bearer x" } })[APP_SECRET_HEADER], SECRET);
+ assert.equal(run({ webContentsId: 8, url: "http://127.0.0.1:43123/runtime-config/approvals", requestHeaders: {} })[APP_SECRET_HEADER], undefined);
+ assert.equal(run({ webContentsId: 7, url: "http://127.0.0.1:5173/", requestHeaders: {} })[APP_SECRET_HEADER], undefined);
+ assert.equal(run({ webContentsId: undefined, url: "http://127.0.0.1:43123/tokens", requestHeaders: {} })[APP_SECRET_HEADER], undefined);
+ const forged = run({ webContentsId: 9, url: "http://127.0.0.1:43123/tokens", requestHeaders: { "X-OmniRush-App-Secret": "forged" } });
+ assert.ok(!Object.keys(forged).some((name) => name.toLowerCase() === APP_SECRET_HEADER));
+});
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 0505a66f..055af081 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -22,6 +22,7 @@ import { globalOpencodeConfigDir, workspaceOpencodeConfigCandidates } from "@omn
import { configureFakeMediaForTests, installMediaPermissionHandlers } from "./media-permissions.mjs";
import { registerMigrationIpc } from "./migration.mjs";
import { createRuntimeManager, createSystemCaCertificateVerifyProc } from "./runtime.mjs";
+import { installAppRequestSecret } from "./app-request-secret.mjs";
import { registerUpdaterIpc } from "./updater.mjs";
import {
checkComputerUsePermissions,
@@ -3454,6 +3455,8 @@ or use: pnpm dev:worktree`);
initComputerUse({ getWindow: () => mainWindow, serverInfo: () => runtimeManager.omnirushServerInfo(), log: (message, error) => console.warn(`[computer-use] ${message}`, error?.message ?? "") });
const systemCaCertificates = await runtimeManager.systemCaCertificates();
session.defaultSession.setCertificateVerifyProc(createSystemCaCertificateVerifyProc(systemCaCertificates));
+ // Settings writes to the local server need this app's window (app-request-secret.mjs).
+ installAppRequestSecret(session.defaultSession, (id) => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents.id === id));
installMediaPermissionHandlers(session, () => mainWindow);
await runPendingNukeCleanup({
env: process.env,
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index b4bbbfe8..3fe330c7 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -1,3 +1,4 @@
+import { appSecretHeaders, rememberLocalServer } from "./app-request-secret.mjs";
import { randomUUID, X509Certificate } from "node:crypto";
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
@@ -731,6 +732,7 @@ async function fetchJson(url, options = {}, timeoutMs = 3000) {
signal: controller.signal,
headers: {
Accept: "application/json",
+ ...appSecretHeaders(url),
...(options.headers ?? {}),
},
});
@@ -2282,6 +2284,7 @@ export function createRuntimeManager({
omnirushServerState.host = host;
omnirushServerState.port = boundPort;
omnirushServerState.baseUrl = baseUrl;
+ rememberLocalServer(baseUrl);
omnirushServerState.clientToken = tokens.clientToken;
omnirushServerState.hostToken = tokens.hostToken;
recordRestart({ action: "started", reason: nextStartReason ?? "startup", source: "runtime" });
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 9ded2b18..99c611b2 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/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": "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 electron/app-request-secret.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/server/src/app-request-gate.test.ts b/apps/server/src/app-request-gate.test.ts
new file mode 100644
index 00000000..57373e27
--- /dev/null
+++ b/apps/server/src/app-request-gate.test.ts
@@ -0,0 +1,94 @@
+import { afterEach, describe, expect, test } from "bun:test";
+
+import { APP_SECRET_HEADER, APP_SECRET_KEY, appRequestRefusal, needsApp, normalizedRequestPath } from "./app-request-gate.js";
+
+const SECRET = "a".repeat(64);
+const g = globalThis as Record<symbol, unknown>;
+afterEach(() => { delete g[APP_SECRET_KEY]; });
+
+const refused = (method: string, path: string, secret?: string) =>
+ appRequestRefusal(method, path, new Headers(secret === undefined ? {} : { [APP_SECRET_HEADER]: secret })) !== null;
+
+describe("settings writes need the app", () => {
+ const writes: Array<[string, string]> = [
+ ["PUT", "/runtime-config/approvals"],
+ ["PUT", "/runtime-config/agent-assist"],
+ ["PATCH", "/runtime-config/providers"],
+ ["PUT", "/workspace/ws_1/permissions/mode"],
+ ["PATCH", "/workspace/ws_1/config"],
+ ["POST", "/workspace/ws_1/opencode-config"],
+ ["PUT", "/workspace/ws_1/authorized-folders"],
+ ["PUT", "/workspace/ws_1/box"],
+ ["POST", "/workspace/ws_1/plugins"],
+ ["POST", "/workspace/ws_1/skills"],
+ ["POST", "/workspace/ws_1/commands"],
+ ["POST", "/workspace/ws_1/mcp"],
+ ["POST", "/workspace/ws_1/mcp/notes/enabled"],
+ ["DELETE", "/workspace/ws_1/mcp/notes"],
+ ["POST", "/workspace/ws_1/runtime-config/disabled-providers"],
+ ["POST", "/workspace/ws_1/local-workflows"],
+ ["POST", "/tokens"],
+ ["PUT", "/env"],
+ ["POST", "/approvals/apr_1"],
+ ["POST", "/workspaces/remote"],
+ ["PUT", "/experimental/engine-v2-preview"],
+ ["POST", "/experimental/ui-control/req_1/reply"],
+ ["PUT", "/omnirush/subagent-model"],
+ // approval answers and the engine's own settings, through every proxy mount
+ ["POST", "/opencode/permission/per_1/reply"],
+ ["POST", "/workspace/ws_1/opencode/permission/per_1/reply"],
+ ["POST", "/w/ws_1/opencode/session/ses_1/permissions/per_1"],
+ ["POST", "/workspace/ws_1/opencode2/api/permission/per_1/reply"],
+ ["POST", "/workspace/ws_1/opencode/question/q_1/reject"],
+ ["PATCH", "/opencode/config"],
+ ["PUT", "/opencode/auth/openai"],
+ ["POST", "/opencode/mcp"],
+ // a mounted base URL and path tricks
+ ["PUT", "/w/ws_1/runtime-config/approvals"],
+ ["PUT", "/x/../runtime-config/approvals"],
+ ["PUT", "/runtime-config%2Fapprovals"],
+ ["PUT", "//runtime-config/approvals"],
+ ["PUT", "/runtime-config/approvals;x"],
+ ["PUT", "/runtime-config\\approvals"],
+ ["PUT", "/%E0%A4%A"],
+ ];
+ const reads: Array<[string, string]> = [["GET", "/env"], ["GET", "/env/OPENAI_API_KEY"], ["GET", "/runtime-config/providers"], ["GET", "/tokens"]];
+ const open: Array<[string, string]> = [
+ ["GET", "/runtime-config/approvals"],
+ ["GET", "/workspace/ws_1/config"],
+ ["GET", "/workspaces"],
+ ["OPTIONS", "/runtime-config/approvals"],
+ ["POST", "/managed-policy/evaluate"],
+ ["POST", "/omnirush/subagent-model/resolve"],
+ ["POST", "/experimental/ui-control/request"],
+ ["POST", "/experimental/extensions/call"],
+ ["POST", "/session-upload/events"],
+ ["POST", "/mcp/managed/ws_1/notes"],
+ ["POST", "/workspace/ws_1/mcp-apps/call"],
+ ["POST", "/workspace/ws_1/opencode/session"],
+ ["POST", "/workspace/ws_1/opencode/session/ses_1/prompt_async"],
+ ["GET", "/workspace/ws_1/opencode/permission"],
+ ["PUT", "/workspace/ws_1/editor/file"],
+ ];
+
+ test("with the app's secret configured: refused without it, allowed with it", () => {
+ g[APP_SECRET_KEY] = SECRET;
+ for (const [method, path] of [...writes, ...reads]) {
+ expect([method, path, refused(method, path)]).toEqual([method, path, true]);
+ expect([method, path, refused(method, path, SECRET)]).toEqual([method, path, false]);
+ expect([method, path, refused(method, path, "b".repeat(64))]).toEqual([method, path, true]);
+ }
+ for (const [method, path] of open) expect([method, path, refused(method, path)]).toEqual([method, path, false]);
+ });
+
+ test("a server run on its own (no secret) is unchanged", () => {
+ for (const [method, path] of [...writes, ...reads]) expect(refused(method, path)).toBe(false);
+ expect(needsApp("PUT", "/runtime-config/approvals")).toBe(true);
+ });
+
+ test("paths are read the way routes read them", () => {
+ expect(normalizedRequestPath("/w/ws_1/workspace/ws_1/plugins")).toBe("/workspace/ws_1/plugins");
+ expect(normalizedRequestPath("/x/%2e%2e/tokens")).toBe("/tokens");
+ expect(normalizedRequestPath("/%E0%A4%A")).toBeNull();
+ });
+});
diff --git a/apps/server/src/app-request-gate.ts b/apps/server/src/app-request-gate.ts
new file mode 100644
index 00000000..0b91442e
--- /dev/null
+++ b/apps/server/src/app-request-gate.ts
@@ -0,0 +1,119 @@
+import { timingSafeEqual } from "node:crypto";
+import { posix } from "node:path";
+
+/**
+ * Settings writes need the app itself.
+ *
+ * The local server's bearer reaches places the app does not control: the engine holds it, an
+ * agent command can read the engine's process environment, and the desktop keeps its tokens in a
+ * file under the profile. So a bearer alone must not be enough to change what the person decided:
+ * approvals and permission mode, project config, plugins, skills, commands, MCP servers, folder
+ * access, the sandbox, tokens, environment and provider keys, or the answer to an approval question.
+ *
+ * Electron main holds a per-launch secret in this process only (never on disk, never in an
+ * environment) and adds it as APP_SECRET_HEADER to the app window's requests to this server (and
+ * to its own). Those routes then need it. Without a secret configured (a server run on its own,
+ * not inside the desktop app) nothing changes.
+ */
+export const APP_SECRET_KEY = Symbol.for("omnirush.app.request-secret");
+export const APP_SECRET_HEADER = "x-omnirush-app-secret";
+
+export const APP_REQUIRED_CODE = "app_required";
+export const APP_REQUIRED_MESSAGE = "This change can only be made in the OmniRush.ai app.";
+
+function heldSecret(): string | null {
+ const held: unknown = (globalThis as Record<symbol, unknown>)[APP_SECRET_KEY];
+ return typeof held === "string" && held.length >= 32 ? held : null;
+}
+
+export function appSecretMatches(given: string | null | undefined): boolean {
+ const held = heldSecret();
+ if (!held || typeof given !== "string") return false;
+ const a = Buffer.from(held), b = Buffer.from(given);
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
+// App server routes (method other than GET/HEAD/OPTIONS) that change settings.
+const SETTINGS_WRITES: RegExp[] = [
+ /^\/runtime-config(?:\/|$)/,
+ /^\/workspace\/[^/]+\/(?:runtime-config|config|opencode-config|permissions|authorized-folders|box|plugins|claude-plugins|cloud-plugins|skills|commands|mcp|local-workflows|desktop-cloud-sync|engine)(?:\/|$)/,
+ /^\/workspaces(?:\/|$)/,
+ /^\/tokens(?:\/|$)/,
+ /^\/env(?:\/|$)/,
+ /^\/den-session$/,
+ /^\/cloud-provider-sync(?:\/|$)/,
+ /^\/runtime\/upgrade$/,
+ /^\/approvals(?:\/|$)/,
+ /^\/experimental\/(?:engine-v2-preview|connect\/state)$/,
+ /^\/experimental\/ui-control\/[^/]+\/reply$/,
+ /^\/omnirush\/subagent-model$/,
+];
+
+// App server reads that hand out secrets (environment values, provider keys, tokens): any method.
+const SECRET_READS: RegExp[] = [
+ /^\/env(?:\/|$)/,
+ /^\/runtime-config\/providers$/,
+ /^\/tokens(?:\/|$)/,
+];
+
+// Engine routes behind the proxy (path after the /opencode or /opencode2 segment), any method but
+// GET/HEAD/OPTIONS: answers to approval questions, and the engine's own config, keys and MCP list.
+const ENGINE_WRITES: RegExp[] = [
+ /(?:^|\/)(?:permission|question)\/[^/]+\/(?:reply|reject)$/,
+ /(?:^|\/)session\/[^/]+\/permissions\/[^/]+$/,
+ /^\/(?:global\/)?config(?:\/|$)/,
+ /^\/auth(?:\/|$)/,
+ /^\/mcp(?:\/|$)/,
+ /^\/(?:api\/)?(?:permission|question)(?:\/|$)/,
+];
+
+const READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
+
+/** The path as routes would see it: percent-escapes, backslashes, repeated slashes, dot segments and `;params` resolved. Null when it cannot be read. */
+export function normalizedRequestPath(pathname: string): string | null {
+ let path = pathname;
+ try {
+ for (let i = 0; i < 3; i += 1) {
+ const next = decodeURIComponent(path);
+ if (next === path) break;
+ path = next;
+ }
+ } catch {
+ return null;
+ }
+ path = path.replace(/\\/g, "/").replace(/;[^/]*/g, "");
+ path = posix.normalize(`/${path}`).replace(/\/+$/, "") || "/";
+ // A mounted base URL (/w/<id>/...) routes on the rest.
+ const mount = /^\/w\/[^/]+(\/.*)?$/.exec(path);
+ if (mount) path = mount[1] || "/";
+ return path;
+}
+
+/** The engine path of a proxied request (after its /opencode or /opencode2 segment), or null for an app server route. */
+function enginePath(path: string): string | null {
+ const segments = path.split("/");
+ const at = segments.findIndex((segment) => segment === "opencode" || segment === "opencode2");
+ if (at === -1) return null;
+ if (at !== 1 && !(at === 3 && segments[1] === "workspace")) return null;
+ return `/${segments.slice(at + 1).join("/")}`;
+}
+
+/** Whether a request needs the app's secret: a settings write, a secret read, or an engine decision. */
+export function needsApp(method: string, pathname: string): boolean {
+ const upper = method.toUpperCase();
+ const write = !READ_METHODS.has(upper);
+ const path = normalizedRequestPath(pathname);
+ if (path === null) return write;
+ const engine = enginePath(path);
+ if (engine !== null) return write && ENGINE_WRITES.some((rule) => rule.test(engine));
+ if (SECRET_READS.some((rule) => rule.test(path))) return upper !== "OPTIONS";
+ return write && SETTINGS_WRITES.some((rule) => rule.test(path));
+}
+
+/** The refusal for a request that needs the app and does not carry its secret, or null. */
+export function appRequestRefusal(method: string, pathname: string, headers: Headers): { code: string; message: string } | null {
+ if (!heldSecret()) return null;
+ if (!needsApp(method, pathname)) return null;
+ if (appSecretMatches(headers.get(APP_SECRET_HEADER))) return null;
+ return { code: APP_REQUIRED_CODE, message: APP_REQUIRED_MESSAGE };
+}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index c8497d97..32f41305 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -223,6 +223,7 @@ import { findManagedEngineWorkspace } from "./workspaces.js";
import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";
import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";
import { createEngineV2Preview, type EngineV2Preview } from "./engine-v2-preview.js";
+import { APP_SECRET_HEADER, appRequestRefusal } from "./app-request-gate.js";
import { isUploadFileDenied, sessionUploaderEnabled } from "./session-uploader.js";
import { editorUserEditEvent, editorUserReviewEvent } from "./editor-events.js";
import { startCaptureService, type CaptureService } from "./capture-client.js";
@@ -1550,6 +1551,14 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
return wrapped;
};
+ // Settings writes, secret reads and approval answers need the app itself (app-request-gate.ts).
+ const appRefusal = appRequestRefusal(request.method, url.pathname, request.headers);
+ if (appRefusal) {
+ errorMessage = appRefusal.message;
+ errorCode = appRefusal.code;
+ return finalize(jsonResponse(appRefusal, 403));
+ }
+
const proxyWorkspaceOpencodeMount = async (mount: { workspaceId: string; restPath: string }) => {
authMode = "client";
try {
@@ -2009,6 +2018,7 @@ export async function proxyOpencodeV2Request(input: {
const headers = new Headers(input.request.headers);
headers.delete("authorization");
headers.delete("x-omnirush-host-token");
+ headers.delete(APP_SECRET_HEADER);
headers.delete("x-omnirush-client-id");
headers.delete("host");
headers.delete("origin");
@@ -2449,6 +2459,7 @@ export async function proxyOpencodeRequest(input: {
let headers = new Headers(input.request.headers);
headers.delete("authorization");
headers.delete("x-omnirush-host-token");
+ headers.delete(APP_SECRET_HEADER);
headers.delete("x-omnirush-client-id");
headers.delete("host");
headers.delete("origin");
@@ -3231,7 +3242,7 @@ function withCors(response: Response, request: Request, config: ServerConfig) {
headers.set("Access-Control-Allow-Origin", allowOrigin);
headers.set(
"Access-Control-Allow-Headers",
- "Authorization, Content-Type, X-OmniRush-Host-Token, X-OmniRush-Client-Id, X-OpenCode-Directory, X-Opencode-Directory, x-opencode-directory",
+ "Authorization, Content-Type, X-OmniRush-Host-Token, X-OmniRush-App-Secret, X-OmniRush-Client-Id, X-OpenCode-Directory, X-Opencode-Directory, x-opencode-directory",
);
headers.set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
headers.set("Vary", "Origin");