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:
@@ -258,10 +258,8 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
|
||||
});
|
||||
|
||||
app.put('/api/config/settings', async (req, res) => {
|
||||
console.log('[API:PUT /api/config/settings] Received request');
|
||||
try {
|
||||
const updated = await persistSettings(req.body ?? {});
|
||||
console.log(`[API:PUT /api/config/settings] Success, returning ${updated.projects?.length || 0} projects`);
|
||||
res.json(updated);
|
||||
} catch (error) {
|
||||
console.error('[API:PUT /api/config/settings] Failed to save settings:', error);
|
||||
|
||||
@@ -145,13 +145,6 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
result.activeProjectId = candidate.activeProjectId;
|
||||
}
|
||||
|
||||
if (Array.isArray(candidate.approvedDirectories)) {
|
||||
result.approvedDirectories = normalizeStringArray(
|
||||
candidate.approvedDirectories
|
||||
.map((entry) => (typeof entry === 'string' ? normalizePathForPersistence(entry) : entry))
|
||||
.filter((entry) => typeof entry === 'string' && entry.length > 0)
|
||||
);
|
||||
}
|
||||
if (Array.isArray(candidate.securityScopedBookmarks)) {
|
||||
result.securityScopedBookmarks = normalizeStringArray(candidate.securityScopedBookmarks);
|
||||
}
|
||||
@@ -702,31 +695,6 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
};
|
||||
|
||||
const mergePersistedSettings = (current, changes) => {
|
||||
const baseApproved = Array.isArray(changes.approvedDirectories)
|
||||
? changes.approvedDirectories
|
||||
: Array.isArray(current.approvedDirectories)
|
||||
? current.approvedDirectories
|
||||
: [];
|
||||
|
||||
const additionalApproved = [];
|
||||
if (typeof changes.lastDirectory === 'string' && changes.lastDirectory.length > 0) {
|
||||
additionalApproved.push(changes.lastDirectory);
|
||||
}
|
||||
if (typeof changes.homeDirectory === 'string' && changes.homeDirectory.length > 0) {
|
||||
additionalApproved.push(changes.homeDirectory);
|
||||
}
|
||||
const projectEntries = Array.isArray(changes.projects)
|
||||
? changes.projects
|
||||
: Array.isArray(current.projects)
|
||||
? current.projects
|
||||
: [];
|
||||
projectEntries.forEach((project) => {
|
||||
if (project && typeof project.path === 'string' && project.path.length > 0) {
|
||||
additionalApproved.push(project.path);
|
||||
}
|
||||
});
|
||||
const approvedSource = [...baseApproved, ...additionalApproved];
|
||||
|
||||
const baseBookmarks = Array.isArray(changes.securityScopedBookmarks)
|
||||
? changes.securityScopedBookmarks
|
||||
: Array.isArray(current.securityScopedBookmarks)
|
||||
@@ -743,11 +711,6 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
const next = {
|
||||
...current,
|
||||
...changes,
|
||||
approvedDirectories: Array.from(
|
||||
new Set(
|
||||
approvedSource.filter((entry) => typeof entry === 'string' && entry.length > 0)
|
||||
)
|
||||
),
|
||||
securityScopedBookmarks: Array.from(
|
||||
new Set(
|
||||
baseBookmarks.filter((entry) => typeof entry === 'string' && entry.length > 0)
|
||||
@@ -762,7 +725,6 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
const formatSettingsResponse = (settings) => {
|
||||
const sanitized = sanitizeSettingsUpdate(settings);
|
||||
delete sanitized.managedRemoteTunnelToken;
|
||||
const approved = normalizeStringArray(settings.approvedDirectories);
|
||||
const bookmarks = normalizeStringArray(settings.securityScopedBookmarks);
|
||||
const hasManagedRemoteTunnelToken = typeof settings?.managedRemoteTunnelToken === 'string' && settings.managedRemoteTunnelToken.trim().length > 0;
|
||||
const pwaAppName = normalizePwaAppName(settings?.pwaAppName, '');
|
||||
@@ -775,7 +737,6 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
...(pwaAppName ? { pwaAppName } : {}),
|
||||
pwaOrientation,
|
||||
mobileKeyboardMode,
|
||||
approvedDirectories: approved,
|
||||
securityScopedBookmarks: bookmarks,
|
||||
pinnedDirectories: normalizeStringArray(settings.pinnedDirectories),
|
||||
typographySizes: sanitizeTypographySizesPartial(settings.typographySizes),
|
||||
|
||||
@@ -226,7 +226,6 @@ export const createSettingsNormalizationRuntime = (dependencies) => {
|
||||
|
||||
normalizePathField('lastDirectory');
|
||||
normalizePathField('homeDirectory');
|
||||
normalizePathArrayField('approvedDirectories');
|
||||
normalizePathArrayField('pinnedDirectories');
|
||||
|
||||
if (Array.isArray(settings.projects)) {
|
||||
|
||||
@@ -493,41 +493,34 @@ export const createSettingsRuntime = (deps) => {
|
||||
};
|
||||
|
||||
const validateProjectEntries = async (projects) => {
|
||||
console.log(`[validateProjectEntries] Starting validation for ${projects.length} projects`);
|
||||
|
||||
if (!Array.isArray(projects)) {
|
||||
console.warn('[validateProjectEntries] Input is not an array, returning empty');
|
||||
return [];
|
||||
}
|
||||
|
||||
const validations = projects.map(async (project) => {
|
||||
if (!project || typeof project.path !== 'string' || project.path.length === 0) {
|
||||
console.error('[validateProjectEntries] Invalid project entry: missing or empty path', project);
|
||||
console.warn('[validateProjectEntries] Dropping project entry with missing or empty path');
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const stats = await fsPromises.stat(project.path);
|
||||
if (!stats.isDirectory()) {
|
||||
console.error(`[validateProjectEntries] Project path is not a directory: ${project.path}`);
|
||||
console.warn(`[validateProjectEntries] Dropping project — path is not a directory: ${project.path}`);
|
||||
return null;
|
||||
}
|
||||
return project;
|
||||
} catch (error) {
|
||||
const err = error;
|
||||
console.error(`[validateProjectEntries] Failed to validate project "${project.path}": ${err.code || err.message || err}`);
|
||||
if (err && typeof err === 'object' && err.code === 'ENOENT') {
|
||||
console.log(`[validateProjectEntries] Removing project with ENOENT: ${project.path}`);
|
||||
if (error && typeof error === 'object' && error.code === 'ENOENT') {
|
||||
console.warn(`[validateProjectEntries] Dropping project — directory no longer exists: ${project.path}`);
|
||||
return null;
|
||||
}
|
||||
console.log(`[validateProjectEntries] Keeping project despite non-ENOENT error: ${project.path}`);
|
||||
// Permission or transient fs error — keep the project rather than
|
||||
// silently losing it from the user's list.
|
||||
return project;
|
||||
}
|
||||
});
|
||||
|
||||
const results = (await Promise.all(validations)).filter((p) => p !== null);
|
||||
|
||||
console.log(`[validateProjectEntries] Validation complete: ${results.length}/${projects.length} projects valid`);
|
||||
return results;
|
||||
return (await Promise.all(validations)).filter((p) => p !== null);
|
||||
};
|
||||
|
||||
const migrateSettingsFromLegacyLastDirectory = async (current) => {
|
||||
@@ -769,6 +762,19 @@ export const createSettingsRuntime = (deps) => {
|
||||
return { settings: changed ? next : settings, changed };
|
||||
};
|
||||
|
||||
// `approvedDirectories` was a write-only registry: every project path and
|
||||
// visited directory was appended forever, but nothing ever read it. Strip
|
||||
// the stale key from persisted settings on upgrade.
|
||||
const migrateSettingsRemoveApprovedDirectories = (current) => {
|
||||
const settings = current && typeof current === 'object' ? current : {};
|
||||
if (!Object.prototype.hasOwnProperty.call(settings, 'approvedDirectories')) {
|
||||
return { settings, changed: false };
|
||||
}
|
||||
const next = { ...settings };
|
||||
delete next.approvedDirectories;
|
||||
return { settings: next, changed: true };
|
||||
};
|
||||
|
||||
const readSettingsFromDiskMigrated = async () => {
|
||||
const current = await readSettingsFromDisk();
|
||||
const migration1 = await migrateSettingsFromLegacyLastDirectory(current);
|
||||
@@ -778,17 +784,19 @@ export const createSettingsRuntime = (deps) => {
|
||||
const migration5 = await migrateSettingsFromLegacyNamedTunnelKeys(migration4.settings);
|
||||
const migration6 = normalizeSettingsPaths(migration5.settings);
|
||||
const migration7 = await migrateSettingsToDeterministicProjectIds(migration6.settings);
|
||||
if (migration1.changed || migration2.changed || migration3.changed || migration4.changed || migration5.changed || migration6.changed || migration7.changed) {
|
||||
await writeSettingsToDisk(migration7.settings);
|
||||
const migration8 = migrateSettingsRemoveApprovedDirectories(migration7.settings);
|
||||
if (migration1.changed || migration2.changed || migration3.changed || migration4.changed || migration5.changed || migration6.changed || migration7.changed || migration8.changed) {
|
||||
await writeSettingsToDisk(migration8.settings);
|
||||
}
|
||||
return migration7.settings;
|
||||
return migration8.settings;
|
||||
};
|
||||
|
||||
const persistSettings = async (changes) => {
|
||||
persistSettingsLock = persistSettingsLock.then(async () => {
|
||||
console.log('[persistSettings] Called with changes:', JSON.stringify(changes, null, 2));
|
||||
// Log field names only — changes can carry credentials (UI password,
|
||||
// client tokens, tunnel tokens) that must never reach the log file.
|
||||
console.log('[persistSettings] Updating fields:', Object.keys(changes || {}).join(', ') || '(none)');
|
||||
const current = await readSettingsFromDisk();
|
||||
console.log('[persistSettings] Current projects count:', Array.isArray(current.projects) ? current.projects.length : 'N/A');
|
||||
const sanitized = sanitizeSettingsUpdate(changes);
|
||||
let next = mergePersistedSettings(current, sanitized);
|
||||
|
||||
@@ -802,10 +810,16 @@ export const createSettingsRuntime = (deps) => {
|
||||
next = deterministicProjectIdMigration.settings;
|
||||
}
|
||||
|
||||
if (Array.isArray(next.projects)) {
|
||||
console.log(`[persistSettings] Validating ${next.projects.length} projects...`);
|
||||
const approvedDirectoriesMigration = migrateSettingsRemoveApprovedDirectories(next);
|
||||
if (approvedDirectoriesMigration.changed) {
|
||||
next = approvedDirectoriesMigration.settings;
|
||||
}
|
||||
|
||||
// Validating project paths hits the filesystem for every entry, so only
|
||||
// do it when the incoming update actually touches the projects list —
|
||||
// not on every theme/window-state/etc. save.
|
||||
if (Object.prototype.hasOwnProperty.call(sanitized, 'projects') && Array.isArray(next.projects)) {
|
||||
const validated = await validateProjectEntries(next.projects);
|
||||
console.log(`[persistSettings] After validation: ${validated.length} projects remain`);
|
||||
next = { ...next, projects: validated };
|
||||
}
|
||||
|
||||
@@ -848,7 +862,6 @@ export const createSettingsRuntime = (deps) => {
|
||||
}
|
||||
|
||||
await writeSettingsToDisk(next);
|
||||
console.log(`[persistSettings] Successfully saved ${next.projects?.length || 0} projects to disk`);
|
||||
return formatSettingsResponse(next);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user