fix: stop forwarding client auth to OpenCode and harden home/session state
Packaged desktop showed no sessions in 1.12.4. Root cause: the sanitized session-list proxy path added in #1538 forwarded the renderer's "authorization" header (the OpenChamber UI client token) to the managed OpenCode upstream alongside the managed "Authorization" credential. OpenCode does not recognize UI client tokens, so every session-list request answered 401 — only in the packaged app, because only its renderer (openchamber-ui:// origin) attaches a bearer token; dev web and dev Electron run same-origin without one. The legacy http-proxy path overwrote the header correctly, which is why everything except session lists kept working. Proxy fix: - proxy-headers: filter the client "authorization" header out of forwarded request headers; the OpenCode upstream must only ever see its own managed credentials. Covered by tests. Desktop cwd: - electron: launch the managed OpenCode CLI from the user home instead of app userData, matching upstream desktop behavior. userData-as-cwd made OpenCode treat the app-data folder as a separate empty workspace. Home directory poisoning loop: - directoryPersistence: stop replaying localStorage homeDirectory through synchronizeHomeDirectory on boot/auth resync. The persisted value is only a boot-time cache; replaying it re-wrote stale values (e.g. a project path) into desktop settings on every start, overriding the authoritative /api/fs/home resolution. - persistence: never overwrite an injected window.__OPENCHAMBER_HOME__ with a persisted value. - useDirectoryStore: host switches happen in place (no reload), so re-resolve home from the new runtime's /api/fs/home on endpoint change instead of keeping the previous host's value. - opencode client: only short-circuit to the injected desktop home when the active runtime is local; remote runtimes ask /api/fs/home. Settings hygiene: - persistSettings: log field names only — change payloads can carry credentials (UI password, client tokens, tunnel tokens) that must not reach the log file; drop step-by-step log chatter. - validateProjectEntries: only stat project paths when the incoming update actually touches the projects list, not on every settings save. - remove the write-only approvedDirectories setting everywhere and add a migration that strips the stale key from persisted settings. Tests: - usePluginsStore.test: register an own runtime-fetch module mock so the suite is independent of process-global mock.module leakage from other files, and restore globalThis.fetch after the suite. - persistence.test: clean up the window global created for the suite.
This commit is contained in:
@@ -638,7 +638,6 @@ export interface SettingsPayload {
|
||||
opencodeBinary?: string;
|
||||
projects?: ProjectEntry[];
|
||||
activeProjectId?: string;
|
||||
approvedDirectories?: string[];
|
||||
securityScopedBookmarks?: string[];
|
||||
pinnedDirectories?: string[];
|
||||
showReasoningTraces?: boolean;
|
||||
|
||||
@@ -59,7 +59,6 @@ export type DesktopSettings = {
|
||||
desktopUiPassword?: string;
|
||||
projects?: ProjectEntry[];
|
||||
activeProjectId?: string;
|
||||
approvedDirectories?: string[];
|
||||
securityScopedBookmarks?: string[];
|
||||
pinnedDirectories?: string[];
|
||||
showReasoningTraces?: boolean;
|
||||
|
||||
@@ -6,23 +6,22 @@ export const applyPersistedDirectoryPreferences = async (): Promise<void> => {
|
||||
return;
|
||||
}
|
||||
|
||||
let savedHome: string | null = null;
|
||||
let savedDirectory: string | null = null;
|
||||
|
||||
try {
|
||||
savedHome = window.localStorage.getItem('homeDirectory');
|
||||
savedDirectory = window.localStorage.getItem('lastDirectory');
|
||||
} catch (error) {
|
||||
console.warn('Failed to read saved directory preferences:', error);
|
||||
}
|
||||
|
||||
const directoryStore = useDirectoryStore.getState();
|
||||
|
||||
if (savedHome && directoryStore.homeDirectory !== savedHome) {
|
||||
directoryStore.synchronizeHomeDirectory(savedHome);
|
||||
}
|
||||
// Home directory is intentionally NOT restored from localStorage here.
|
||||
// The persisted value is only a boot-time cache already consumed by the
|
||||
// directory store's initial state; replaying it through
|
||||
// synchronizeHomeDirectory would persist a possibly stale value back into
|
||||
// desktop settings, overriding the authoritative resolution
|
||||
// (initializeHomeDirectory → /api/fs/home) that runs on every startup.
|
||||
|
||||
if (savedDirectory && !isVSCodeRuntime()) {
|
||||
directoryStore.setDirectory(savedDirectory, { showOverlay: false });
|
||||
useDirectoryStore.getState().setDirectory(savedDirectory, { showOverlay: false });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { PermissionRequest } from "@/types/permission";
|
||||
import type { QuestionRequest } from "@/types/question";
|
||||
import { getRuntimeUrlResolver } from "@/lib/runtime-url";
|
||||
import { runtimeFetch } from "@/lib/runtime-fetch";
|
||||
import { getRuntimeKey } from "@/lib/runtime-switch";
|
||||
import { getRegisteredRuntimeAPIs } from "@/contexts/runtimeAPIRegistry";
|
||||
import { markStartupTrace } from "@/lib/startupTrace";
|
||||
import {
|
||||
@@ -1627,11 +1628,16 @@ class OpencodeService {
|
||||
}
|
||||
|
||||
async getFilesystemHome(): Promise<string | null> {
|
||||
// Optimization: Check for desktop runtime first to avoid unnecessary network calls
|
||||
// and fix the "SyntaxError" warning when the endpoint is missing
|
||||
const desktopHome = await getDesktopHomeDirectory();
|
||||
if (desktopHome) {
|
||||
return desktopHome;
|
||||
// The injected desktop home describes the LOCAL machine. It is only a
|
||||
// valid answer while the active runtime is the local one — after an
|
||||
// in-place switch to a remote host the home must come from that host's
|
||||
// /api/fs/home, not from the local Electron global.
|
||||
const runtimeKey = getRuntimeKey();
|
||||
if (!runtimeKey || runtimeKey === 'local') {
|
||||
const desktopHome = await getDesktopHomeDirectory();
|
||||
if (desktopHome) {
|
||||
return desktopHome;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
|
||||
import { applyPersistedHomeDirectoryToWindow } from './persistence';
|
||||
|
||||
type TestWindow = { __OPENCHAMBER_HOME__?: string };
|
||||
|
||||
let createdWindow = false;
|
||||
|
||||
const getWindow = (): TestWindow => {
|
||||
if (typeof window === 'undefined') {
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
value: {},
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
createdWindow = true;
|
||||
}
|
||||
return window as unknown as TestWindow;
|
||||
};
|
||||
|
||||
describe('applyPersistedHomeDirectoryToWindow', () => {
|
||||
beforeEach(() => {
|
||||
delete getWindow().__OPENCHAMBER_HOME__;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (createdWindow) {
|
||||
delete (globalThis as { window?: unknown }).window;
|
||||
} else {
|
||||
delete getWindow().__OPENCHAMBER_HOME__;
|
||||
}
|
||||
});
|
||||
|
||||
test('does not overwrite an injected desktop home directory', () => {
|
||||
getWindow().__OPENCHAMBER_HOME__ = '/Users/example';
|
||||
|
||||
applyPersistedHomeDirectoryToWindow('/Users/example/projects/app');
|
||||
|
||||
expect(getWindow().__OPENCHAMBER_HOME__).toBe('/Users/example');
|
||||
});
|
||||
|
||||
test('uses persisted home when no runtime home was injected', () => {
|
||||
applyPersistedHomeDirectoryToWindow('/Users/example/projects/app');
|
||||
|
||||
expect(getWindow().__OPENCHAMBER_HOME__).toBe('/Users/example/projects/app');
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,21 @@ import { sanitizeStarterRefs } from '@/lib/draftStarters';
|
||||
import { normalizeMobileKeyboardMode, setStoredMobileKeyboardMode } from '@/lib/mobileKeyboardMode';
|
||||
import { runtimeFetch } from '@/lib/runtime-fetch';
|
||||
|
||||
export const applyPersistedHomeDirectoryToWindow = (homeDirectory: string): void => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
if (typeof window.__OPENCHAMBER_HOME__ === 'string' && window.__OPENCHAMBER_HOME__.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
window.__OPENCHAMBER_HOME__ = homeDirectory;
|
||||
} catch {
|
||||
/* read-only contextBridge property — leave preload-seeded value */
|
||||
}
|
||||
};
|
||||
|
||||
const persistToLocalStorage = (settings: DesktopSettings) => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
@@ -36,15 +51,7 @@ const persistToLocalStorage = (settings: DesktopSettings) => {
|
||||
}
|
||||
if (settings.homeDirectory) {
|
||||
localStorage.setItem('homeDirectory', settings.homeDirectory);
|
||||
// Electron's preload exposes __OPENCHAMBER_HOME__ as a read-only
|
||||
// contextBridge property; assignment throws TypeError there. In VSCode
|
||||
// webview and plain web runtime the property is writable. Swallow the
|
||||
// error in Electron — preload already seeded the value correctly.
|
||||
try {
|
||||
window.__OPENCHAMBER_HOME__ = settings.homeDirectory;
|
||||
} catch {
|
||||
/* read-only contextBridge property — leave preload-seeded value */
|
||||
}
|
||||
applyPersistedHomeDirectoryToWindow(settings.homeDirectory);
|
||||
}
|
||||
if (Array.isArray(settings.projects) && settings.projects.length > 0) {
|
||||
localStorage.setItem('projects', JSON.stringify(settings.projects));
|
||||
@@ -681,11 +688,6 @@ const sanitizeWebSettings = (payload: unknown): DesktopSettings | null => {
|
||||
result.activeProjectId = candidate.activeProjectId;
|
||||
}
|
||||
|
||||
if (Array.isArray(candidate.approvedDirectories)) {
|
||||
result.approvedDirectories = candidate.approvedDirectories.filter(
|
||||
(entry): entry is string => typeof entry === 'string' && entry.length > 0
|
||||
);
|
||||
}
|
||||
if (Array.isArray(candidate.securityScopedBookmarks)) {
|
||||
result.securityScopedBookmarks = candidate.securityScopedBookmarks.filter(
|
||||
(entry): entry is string => typeof entry === 'string' && entry.length > 0
|
||||
|
||||
@@ -2,6 +2,7 @@ import { create } from 'zustand';
|
||||
import { devtools } from 'zustand/middleware';
|
||||
import { opencodeClient } from '@/lib/opencode/client';
|
||||
import { getDesktopHomeDirectory, isVSCodeRuntime } from '@/lib/desktop';
|
||||
import { subscribeRuntimeEndpointChanged } from '@/lib/runtime-switch';
|
||||
import { updateDesktopSettings } from '@/lib/persistence';
|
||||
import { useFileSearchStore } from '@/stores/useFileSearchStore';
|
||||
import { streamDebugEnabled } from '@/stores/utils/streamDebug';
|
||||
@@ -26,6 +27,7 @@ interface DirectoryStore {
|
||||
}
|
||||
|
||||
let cachedHomeDirectory: string | null = null;
|
||||
let homeResolveGeneration = 0;
|
||||
const safeStorage = getSafeStorage();
|
||||
const persistedLastDirectory = safeStorage.getItem('lastDirectory');
|
||||
const initialHasPersistedDirectory =
|
||||
@@ -437,4 +439,16 @@ if (typeof window !== 'undefined') {
|
||||
initializeHomeDirectory().then((home) => {
|
||||
useDirectoryStore.getState().synchronizeHomeDirectory(home);
|
||||
});
|
||||
|
||||
// Host switches happen in place (no page reload), so the home directory
|
||||
// must be re-resolved from the new runtime's authoritative source instead
|
||||
// of keeping the previous host's value cached.
|
||||
subscribeRuntimeEndpointChanged(() => {
|
||||
cachedHomeDirectory = null;
|
||||
const generation = ++homeResolveGeneration;
|
||||
initializeHomeDirectory().then((home) => {
|
||||
if (generation !== homeResolveGeneration) return;
|
||||
useDirectoryStore.getState().synchronizeHomeDirectory(home);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { beforeEach, describe, expect, mock, test } from 'bun:test';
|
||||
import { afterAll, beforeEach, describe, expect, mock, test } from 'bun:test';
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
import type { PluginEntry, PluginFile, RegistryResult } from './usePluginsStore';
|
||||
|
||||
@@ -31,6 +33,16 @@ mock.module('@/lib/configUpdate', () => ({
|
||||
finishConfigUpdate: finishConfigUpdateMock,
|
||||
}));
|
||||
|
||||
// mock.module is process-global in bun: another test file (e.g.
|
||||
// useCommandsStore.test.ts) may have replaced '@/lib/runtime-fetch' with its
|
||||
// own stub before this file runs. Register our own mock so this suite always
|
||||
// reaches its fetch double regardless of test file ordering. Delegating to
|
||||
// globalThis.fetch (instead of this file's double directly) keeps later test
|
||||
// files that stub global fetch working if this registration outlives us.
|
||||
mock.module('@/lib/runtime-fetch', () => ({
|
||||
runtimeFetch: (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init),
|
||||
}));
|
||||
|
||||
const { usePluginsStore } = await import('./usePluginsStore');
|
||||
|
||||
const entry: PluginEntry = {
|
||||
@@ -126,6 +138,10 @@ describe('usePluginsStore', () => {
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
test('loadPlugins calls config plugins endpoint once and populates entries/files', async () => {
|
||||
queueFetchResponses([jsonResponse(pluginListPayload), jsonResponse({ results: [registryOk] })]);
|
||||
|
||||
|
||||
Vendored
+1
@@ -24,6 +24,7 @@ declare module "bun:test" {
|
||||
};
|
||||
};
|
||||
export function beforeEach(fn: () => void | Promise<void>): void;
|
||||
export function afterAll(fn: () => void | Promise<void>): void;
|
||||
export function mock<T extends (...args: never[]) => unknown>(fn?: T): T;
|
||||
export namespace mock {
|
||||
function module(moduleName: string, factory: () => Record<string, unknown>): void;
|
||||
|
||||
Reference in New Issue
Block a user