Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Keep each agent's Switch token readable by its owner alone (CHOO-4022) (#1349)
Christian McDermottac437c93a6cd
diff --git a/console/AGENTS.md b/console/AGENTS.mdindex 87c6823ce..cb0ef4470 100644--- a/console/AGENTS.md+++ b/console/AGENTS.md@@ -529,6 +529,21 @@ pnpm run lintCode's own file, read by every session in the directory, which does not needthe credential. Do not add a token back to it: two copies is how one goes staleand authenticates as the wrong agent.+ - **It is readable by its owner alone:** `0600` in a `0700` `.switch/agents/`,+ with owner-only ACLs on Windows. Every write of it is a secret write:+ `PluginFs.write` with `{ secret: true }`, or what that calls —+ `writeSecretFile` in `src/main/core/providers/plugin-fs.ts` locally,+ `SshFileSystem.writeSecret` over SFTP. A plain write takes the umask,+ typically leaving the token readable by every account on the machine. A+ directory another account owns is left as it is, with a warning, rather+ than failing the write; the file is private either way.+ - To tighten a file already there, use `PluginFs.protectSecret`, which+ changes permissions only; rewriting the content to the same end can undo a+ concurrent write. `{ fileOnly: true }` leaves the directory alone, for a+ legacy file in `.claude/` that still holds a token.+ - A secret write that is cut off leaves its temporary `<file>.<uuid>` copy+ behind, so `PluginFs.delete` removes those too: delete the file through it,+ or through `deleteFiles` on a host, never with a bare `rm`.- **Where Switch Console writes the settings file, Claude Code makes it live.**Its `env` block becomes real process environment for everything a sessionspawns, so keep the agent id in it in step with `.switch/agents/`; changingdiff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.test.tsindex 5e7dee265..51de41d91 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.test.ts@@ -1,6 +1,6 @@import { type ChildProcess, execFile, spawn } from 'node:child_process';import { createHash } from 'node:crypto';-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { promisify } from 'node:util';@@ -103,4 +103,27 @@ describe('credentials files on a host', () => {await deleteFiles(run, [one, two]);expect(await readFiles(run, [one])).toEqual({ [one]: null });});++ it('removes the copies an interrupted secret write left beside each, and nothing else', async () => {+ const dir = join(home, 'agents');+ await mkdir(dir);+ const uuid = '0b6f1d2e-3c4a-4b5d-8e9f-a0b1c2d3e4f5';+ for (const name of [+ 'a.json',+ `a.json.${uuid}`,+ 'a.json.bak',+ 'b.json',+ `b.json.${uuid}`,+ `c.json.${uuid}`,+ ])+ await writeFile(join(dir, name), '{"a":1}');++ await deleteFiles(run, [+ join(dir, 'a.json'),+ join(dir, 'b.json'),+ join(home, 'gone', 'd.json'),+ ]);++ expect((await readdir(dir)).sort()).toEqual(['a.json.bak', `c.json.${uuid}`]);+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.tsindex 43572f4ac..60d37b8f1 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/host-batch.ts@@ -1,4 +1,5 @@import { z } from 'zod';+import { SECRET_TEMP_SUFFIX } from '@main/core/fs/secret-temp';import { WATCHER_ROOT } from '@main/core/sdk-host/state-roots';import type { MachineScript } from './session-handoff';@@ -100,10 +101,32 @@ for (const file of JSON.parse(process.argv[1])) {console.log(JSON.stringify(out));`;-/** Removes several files on a host in one command. Takes a JSON array of absolute paths. */+/**+ * Removes several credentials files on a host in one command, with any+ * temporary copy an interrupted secret write of one left beside it. Takes a+ * JSON array of absolute paths.+ */export const DELETE_FILES_SCRIPT = String.raw`const fs = require('node:fs');-for (const file of JSON.parse(process.argv[1])) fs.rmSync(file, { force: true });+const path = require('node:path');+const temporary = new RegExp(${JSON.stringify(SECRET_TEMP_SUFFIX)});+const byDir = new Map();+for (const file of JSON.parse(process.argv[1])) {+ fs.rmSync(file, { force: true });+ const dir = path.dirname(file);+ byDir.set(dir, [...(byDir.get(dir) ?? []), path.basename(file)]);+}+for (const [dir, names] of byDir) {+ let entries = [];+ try {+ entries = fs.readdirSync(dir);+ } catch (error) {+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;+ }+ for (const entry of entries)+ if (names.some((name) => entry.startsWith(name) && temporary.test(entry.slice(name.length))))+ fs.rmSync(path.join(dir, entry), { force: true });+}console.log('{}');`;diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.tsindex 34a50efeb..37faebc4b 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts@@ -36,6 +36,9 @@ function memoryFs(): PluginFs & { files: Map<string, string> } {async delete(p) {files.delete(p);},+ async protectSecret(p) {+ return files.has(p);+ },async exists(p) {return files.has(p);},diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.test.tsindex 58c160b8c..302ab13fc 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.test.ts@@ -25,6 +25,24 @@ describe('createRemoteHomePluginFs', () => {expect(args![1]).not.toContain('hooks":{}');});+ it('refuses a secret write without running anything on the host', async () => {+ const { ctx, exec } = makeCtx(async () => ({ stdout: '' }));++ await expect(+ createRemoteHomePluginFs(ctx).write('.codex/token.json', 'secret', { secret: true })+ ).rejects.toThrow(/secret/);+ expect(exec).not.toHaveBeenCalled();+ });++ it('refuses to protect a secret file without running anything on the host', async () => {+ const { ctx, exec } = makeCtx(async () => ({ stdout: '' }));++ await expect(createRemoteHomePluginFs(ctx).protectSecret('.codex/token.json')).rejects.toThrow(+ /secret/+ );+ expect(exec).not.toHaveBeenCalled();+ });+it('decodes the file content the far side base64-encoded', async () => {const content = 'a = "b"\n# ünicode\n';const { ctx } = makeCtx(async () => ({diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.tsindex f233404d3..98e67eef9 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.ts@@ -1,4 +1,4 @@-import type { PluginFs } from '@switch-console/core/agents/plugins';+import type { PluginFs, PluginFsWriteOptions } from '@switch-console/core/agents/plugins';import type { IExecutionContext } from '@main/core/execution-context/types';/**@@ -41,7 +41,12 @@ export function createRemoteHomePluginFs(ctx: IExecutionContext): PluginFs {return Buffer.from(stdout.slice(1), 'base64').toString('utf8');},- async write(path: string, content: string): Promise<void> {+ async write(path: string, content: string, options?: PluginFsWriteOptions): Promise<void> {+ // Nothing secret is kept under the remote home today; refuse rather than+ // write a credential with the host's default permissions.+ if (options?.secret) {+ throw new Error(`remote home fs: cannot write ${path} as a secret file`);+ }await ctx.exec('sh', ['-c','set -e; mkdir -p "$HOME/$(dirname "$1")"; printf %s "$2" | base64 -d > "$HOME/$1"',@@ -51,6 +56,10 @@ export function createRemoteHomePluginFs(ctx: IExecutionContext): PluginFs {]);},+ async protectSecret(path: string): Promise<boolean> {+ throw new Error(`remote home fs: cannot protect ${path} as a secret file`);+ },+async delete(path: string): Promise<void> {await ctx.exec('sh', ['-c', 'rm -f "$HOME/$1"', 'sh', checked(path)]);},diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.tsindex e1d490c52..ea234bb32 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts@@ -19,6 +19,7 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs {files.delete(p);return Promise.resolve();},+ protectSecret: (p) => Promise.resolve(files.has(p)),exists: (p) => Promise.resolve(files.has(p)),list: () => Promise.resolve([...files.keys()]),};diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.tsindex ba8315c76..cba0d4789 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts@@ -25,6 +25,7 @@ const fakeFs = vi.hoisted(() => (): PluginFs => ({delete: async (path: string) => {state.files.delete(path);},+ protectSecret: async (path: string) => state.files.has(path),exists: async (path: string) => state.files.has(path),list: async () => [],}));diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.tsindex 2e6a40a12..d74bdd35e 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts@@ -19,6 +19,8 @@ const MARKER_KEY = 'agentStorageMigrationComplete';* - `2` — the credential collapse runs for every provider.* - `3` — every agent gets a config file, taking over what a Claude Code agent* kept in its definition and what other providers kept on the agent row.+ * - `4` — every file in an agent's working directory that can hold its token+ * is made readable by its owner alone, by changing permissions only.** Bump this whenever the migration learns to fix something it previously* skipped, so installs that latched an earlier generation run the new pass@@ -26,7 +28,7 @@ const MARKER_KEY = 'agentStorageMigrationComplete';* it says. Then teach `migrateAgentStorage` which agents the new generation can* actually change, so the re-run does not re-open workspaces it cannot fix.*/-export const AGENT_STORAGE_MIGRATION_GENERATION = 3;+export const AGENT_STORAGE_MIGRATION_GENERATION = 4;/** The generation last completed on this install; 0 when it has never run. */export async function completedAgentStorageMigrationGeneration(): Promise<number> {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.tsindex a0c9e2002..624a104f3 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-workdir-fs.ts@@ -28,6 +28,7 @@ export type WorkdirFs = {const EMPTY_PLUGIN_FS: PluginFs = {read: () => Promise.resolve(null),write: () => Promise.reject(new Error('home scope is read-only for remote agents')),+ protectSecret: () => Promise.resolve(false),delete: () => Promise.resolve(),exists: () => Promise.resolve(false),list: () => Promise.resolve([]),diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.tsindex a911ea750..c4feed212 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts@@ -20,6 +20,8 @@ function readOnlyFs(seed: Record<string, string>): PluginFs & { files: Map<strinreturn Promise.resolve();},delete: (p) => Promise.reject(new Error(`attach deleted from the workdir: ${p}`)),+ protectSecret: (p) =>+ Promise.reject(new Error(`attach changed permissions in the workdir: ${p}`)),exists: (p) => Promise.resolve(files.has(p)),list: (dir) => {const prefix = `${dir}/`;diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.tsindex 7684d5c16..2e7099697 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.test.ts@@ -8,6 +8,7 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs {read: async (p) => files.get(p) ?? null,write: async (p, c) => void files.set(p, c),delete: async (p) => void files.delete(p),+ protectSecret: async (p) => files.has(p),exists: async (p) => files.has(p),list: async () => [...files.keys()],};diff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.tsindex 453b32007..3ea7542c0 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.test.ts@@ -18,6 +18,7 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs {files.delete(p);return Promise.resolve();},+ protectSecret: (p) => Promise.resolve(files.has(p)),exists: (p) => Promise.resolve(files.has(p)),list: (dir) => {const prefix = `${dir}/`;diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.tsindex faf7f2436..14ff03e0b 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts@@ -18,6 +18,7 @@ function fakeFs(seed: Record<string, string>): PluginFs {files.delete(p);return Promise.resolve();},+ protectSecret: (p) => Promise.resolve(files.has(p)),exists: (p) => Promise.resolve(files.has(p)),list: (dir) =>Promise.resolve(@@ -106,7 +107,7 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: vvi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));vi.mock('./agent-storage-migration-marker', () => ({- AGENT_STORAGE_MIGRATION_GENERATION: 3,+ AGENT_STORAGE_MIGRATION_GENERATION: 4,completedAgentStorageMigrationGeneration: h.completedGeneration,markAgentStorageMigrationComplete: h.markComplete,}));@@ -185,7 +186,7 @@ describe('migrateAgentStorage', () => {expect(log.warn).not.toHaveBeenCalled();});- it('never reads .claude/settings.local.json for a provider without repo-agents', async () => {+ it('never adopts .claude/settings.local.json for a provider without repo-agents', async () => {// The shared settings file is written only by provisionAgent /// provisionRemoteAgent, always as the Claude "main" agent, so for any other// provider it is a different agent's identity and token. Adopting it would@@ -201,7 +202,9 @@ describe('migrateAgentStorage', () => {await migrateAgentStorage();- expect(read).not.toHaveBeenCalledWith('.claude/settings.local.json');+ // One read, by the step that protects a token it finds there; the+ // credential step, which would adopt it, never looks.+ expect(read.mock.calls.filter(([p]) => p === '.claude/settings.local.json')).toHaveLength(1);expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(false);});@@ -250,12 +253,15 @@ describe('migrateAgentStorage', () => {h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];h.state.repoAgents = null;const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-other') });+ const protectSecret = vi.spyOn(ws, 'protectSecret');h.state.workdir = ws;await migrateAgentStorage();expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(false);expect(await ws.read('.switch/agents/agent-id-1.json')).toBe(credsJson('sw-other'));+ // Kept, so made private: the token in it is no less live for being refused.+ expect(protectSecret).toHaveBeenCalledWith('.switch/agents/agent-id-1.json', undefined);expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('different Switch agent'),expect.objectContaining({ foundSwitchAgentId: 'sw-other', providerId: 'codex' })@@ -291,7 +297,7 @@ describe('migrateAgentStorage', () => {});it('skips the whole pass (no workdir opened) once the current generation is latched', async () => {- h.completedGeneration.mockResolvedValueOnce(3);+ h.completedGeneration.mockResolvedValueOnce(4);const resolveWorkdirFsFor = (await import('./agent-workdir-fs')).resolveWorkdirFsFor;await migrateAgentStorage();@@ -359,6 +365,167 @@ describe('migrateAgentStorage', () => {expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(true);});+ it('re-running after generation 3 protects existing credentials without rewriting them', async () => {+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });+ const protectSecret = vi.spyOn(ws, 'protectSecret');+ const write = vi.spyOn(ws, 'write');+ h.state.workdir = ws;++ await migrateAgentStorage();++ // A rewrite could undo a rename or endpoint change landing at the same+ // moment; changing permissions alone cannot.+ expect(protectSecret.mock.calls).toEqual([['.switch/agents/cc-hoot-main.json', undefined]]);+ expect(write).not.toHaveBeenCalled();+ expect(await ws.read('.switch/agents/cc-hoot-main.json')).toBe(credsJson('sw-1'));+ expect(h.readLaunchEnv).not.toHaveBeenCalled();+ expect(h.markComplete).toHaveBeenCalledTimes(1);+ });++ it('protects every credential in the working directory, leaving .claude/ itself alone', async () => {+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({+ '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),+ // A stale id-keyed file the credential step refused, and another agent's.+ '.switch/agents/agent-id-1.json': credsJson('sw-other'),+ '.switch/agents/colleague.json': credsJson('sw-2'),+ '.switch/agents/.gitignore': '*\n',+ '.claude/switch-subagents/legacy.settings.json': credsJson('sw-3'),+ '.claude/settings.local.json': credsJson('sw-4'),+ });+ const protectSecret = vi.spyOn(ws, 'protectSecret');+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(protectSecret.mock.calls).toEqual(+ expect.arrayContaining([+ ['.switch/agents/cc-hoot-main.json', undefined],+ ['.switch/agents/agent-id-1.json', undefined],+ ['.switch/agents/colleague.json', undefined],+ ['.claude/switch-subagents/legacy.settings.json', { fileOnly: true }],+ ['.claude/settings.local.json', { fileOnly: true }],+ ])+ );+ expect(protectSecret).toHaveBeenCalledTimes(5);+ });++ it('leaves a .claude/settings.local.json that holds no token alone', async () => {+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({+ '.claude/settings.local.json': JSON.stringify({+ env: { SWITCH_API_ENDPOINT: 'http://switch.example', SWITCH_AGENT_ID: 'sw-1' },+ }),+ });+ const protectSecret = vi.spyOn(ws, 'protectSecret');+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(protectSecret.mock.calls).toEqual([['.switch/agents/cc-hoot-main.json', undefined]]);+ });++ it('latches generation 4 for an agent with no credentials to protect', async () => {+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({});+ const write = vi.spyOn(ws, 'write');+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(write).not.toHaveBeenCalled();+ expect(h.markComplete).toHaveBeenCalledTimes(1);+ });++ it('counts a credential it is refused as done, with a warning, and protects the rest', async () => {+ // Another account's file: no retry changes that, and an unlatched+ // generation would re-open every working directory on every boot.+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({+ '.switch/agents/cc-hoot-main.json': credsJson('sw-1'),+ '.switch/agents/colleague.json': credsJson('sw-2'),+ });+ const protectSecret = vi.spyOn(ws, 'protectSecret').mockImplementation(async (p) => {+ if (p === '.switch/agents/colleague.json')+ throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });+ return true;+ });+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(protectSecret).toHaveBeenCalledWith('.switch/agents/cc-hoot-main.json', undefined);+ expect(log.warn).toHaveBeenCalledWith(+ expect.stringContaining('cannot make a credentials file private'),+ expect.objectContaining({ path: '.switch/agents/colleague.json' })+ );+ expect(h.markComplete).toHaveBeenCalledTimes(1);+ });++ it('counts a settings file it may not read as done too', async () => {+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });+ const read = ws.read.bind(ws);+ vi.spyOn(ws, 'read').mockImplementation(async (p) => {+ if (p === '.claude/settings.local.json')+ throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });+ return read(p);+ });+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(h.markComplete).toHaveBeenCalledTimes(1);+ });++ it('retries next boot when the credentials directory cannot be listed for a reason that may pass', async () => {+ // A listing that failed must not read as an empty directory: the files in+ // it would go unprotected and the generation would latch over them.+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });+ const list = vi.spyOn(ws, 'list');+ list.mockRejectedValueOnce(new Error('SSH connection is not available'));+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(list).toHaveBeenCalledWith('.switch/agents', { strict: true });+ expect(h.markComplete).not.toHaveBeenCalled();+ });++ it('counts a credentials directory it may not list as done, still protecting the agent’s own file', async () => {+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });+ vi.spyOn(ws, 'list').mockRejectedValueOnce(+ Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' })+ );+ const protectSecret = vi.spyOn(ws, 'protectSecret');+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(protectSecret).toHaveBeenCalledWith('.switch/agents/cc-hoot-main.json', undefined);+ expect(log.warn).toHaveBeenCalledWith(+ expect.stringContaining('cannot make a credentials file private'),+ expect.objectContaining({ path: '.switch/agents' })+ );+ expect(h.markComplete).toHaveBeenCalledTimes(1);+ });++ it('retries next boot when credentials cannot be protected for a reason that may pass', async () => {+ h.completedGeneration.mockResolvedValueOnce(3);+ const ws = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });+ vi.spyOn(ws, 'protectSecret').mockRejectedValueOnce(+ new Error('SSH connection is not available')+ );+ h.state.workdir = ws;++ await migrateAgentStorage();++ expect(h.markComplete).not.toHaveBeenCalled();+ });+it('latches the marker after a clean pass', async () => {h.state.workdir = fakeFs({'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.tsindex 2b3ae4946..428c6bb60 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts@@ -1,4 +1,9 @@-import type { IRepoAgentsBehavior, PluginFs } from '@switch-console/core/agents/plugins';+import type {+ IRepoAgentsBehavior,+ PluginFs,+ PluginFsProtectOptions,+} from '@switch-console/core/agents/plugins';+import { isPermissionDenied } from '@main/core/fs/permission-denied';import { getLocationById } from '@main/core/locations/store';import { getPlugin } from '@main/core/providers/plugin-registry';import {@@ -16,16 +21,22 @@ import { markAgentUnmigrated } from './agent-storage-migration-ready';import { resolveWorkdirFsFor } from './agent-workdir-fs';import { getAgents } from './getAgents';import { importAgentConfig } from './import-agent-config';-import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';-import { writeNeutralAgentSettingsFs } from './write-switch-settings';+import {+ agentSettingsRelativePath,+ SWITCH_AGENTS_DIR_RELATIVE,+ SWITCH_SETTINGS_RELATIVE_PATH,+ SWITCH_SUBAGENTS_DIR_RELATIVE,+} from './switch-settings-paths';+import { holdsSwitchToken, writeNeutralAgentSettingsFs } from './write-switch-settings';/*** Migrate existing Switch Console-managed agents to the current storage layout* (CHOO-1440): every agent has a per-agent credentials file at- * `.switch/agents/<name>.json` and a config file at `.switch/config/<name>.json`,- * both keyed by the agent's single `name`. Pre-CHOO-1440 installs kept- * credentials in the legacy `.claude/switch-subagents/<name>.settings.json` (or- * the shared `.claude/settings.local.json`).+ * `.switch/agents/<name>.json`, readable by its owner alone, and a config file+ * at `.switch/config/<name>.json`, both keyed by the agent's single `name`.+ * Pre-CHOO-1440 installs kept credentials in the legacy+ * `.claude/switch-subagents/<name>.settings.json` (or the shared+ * `.claude/settings.local.json`).** Runs once at boot, best-effort: each agent is migrated in isolation so one bad* directory or unreachable host never aborts the rest, and every step is@@ -83,6 +94,7 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// Generation 2 only broadened step 1 to providers WITHOUT a behavior; for one// that has it, step 1 is what generation 1 already ran.const credentialsDone = completedGeneration >= 2 || (completedGeneration >= 1 && !!behavior);+ const credentialsPrivate = completedGeneration >= 4;const location = await getLocationById(agent.locationId);if (!location) return false;@@ -112,6 +124,11 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bochanged = true;}+ // 3. Every credential in the working directory readable by its owner alone.+ if (!credentialsPrivate && (await protectCredentials(workdir.fs, name))) {+ changed = true;+ }+return changed;} finally {workdir.close();@@ -183,6 +200,69 @@ async function migrateCredentials(return changed;}+/**+ * Make every file in a working directory that can hold a Switch token readable+ * by its owner alone: each `.switch/agents/*.json` (the agent's own, a stale+ * id-keyed one the credential step refused, another agent's), the legacy+ * `.claude/switch-subagents/*.settings.json`, and `.claude/settings.local.json`+ * while it still carries a token. `.claude/` belongs to Claude Code, so only+ * the files there change. Only permissions change, never content, so a rename+ * or endpoint change landing meanwhile is not undone.+ *+ * A file this account is refused (another account's) is left with a warning+ * and counts as done: no retry would change it, and leaving the generation+ * unlatched would re-open every agent's working directory on every boot.+ */+async function protectCredentials(fs: PluginFs, name: string): Promise<boolean> {+ const refused = (path: string, error: unknown) => {+ if (!isPermissionDenied(error)) throw error;+ log.warn('migrateAgentStorage: cannot make a credentials file private; left as it is', {+ path,+ error: String(error),+ });+ };+ // Strict: a directory that could not be read must not pass for an empty one,+ // or the files in it would be skipped without a word and never retried.+ const inDir = async (dir: string, suffix: string) => {+ try {+ const entries = await fs.list(dir, { strict: true });+ return entries.filter((entry) => entry.endsWith(suffix)).map((e) => `${dir}/${e}`);+ } catch (error) {+ refused(dir, error);+ return [];+ }+ };++ const neutral = new Set([+ agentSettingsRelativePath(name),+ ...(await inDir(SWITCH_AGENTS_DIR_RELATIVE, '.json')),+ ]);+ const targets: Array<{ path: string; options?: PluginFsProtectOptions }> = [+ ...[...neutral].map((path) => ({ path })),+ ...(await inDir(SWITCH_SUBAGENTS_DIR_RELATIVE, '.settings.json')).map((path) => ({+ path,+ options: { fileOnly: true },+ })),+ ];+ try {+ if (holdsSwitchToken(await fs.read(SWITCH_SETTINGS_RELATIVE_PATH))) {+ targets.push({ path: SWITCH_SETTINGS_RELATIVE_PATH, options: { fileOnly: true } });+ }+ } catch (error) {+ refused(SWITCH_SETTINGS_RELATIVE_PATH, error);+ }++ let changed = false;+ for (const { path, options } of targets) {+ try {+ if (await fs.protectSecret(path, options)) changed = true;+ } catch (error) {+ refused(path, error);+ }+ }+ return changed;+}+/*** Whether recovered credentials are this agent's own. The row's `switchAgentId`* is the authority on which Switch identity the agent has, so a file naming adiff --git a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.tsindex a91a8759a..b59eb1020 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts@@ -11,6 +11,8 @@ import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switconst mocks = vi.hoisted(() => ({db: undefined as AppDb | undefined,+ /** An SSH host's files, set by a test of the remote path; null fails it loud. */+ remote: null as { files: Map<string, string>; calls: unknown[][] } | null,}));vi.mock('@main/db/client', () => ({@@ -20,17 +22,48 @@ vi.mock('@main/db/client', () => ({},}));-// The propagation module imports the SSH stack for the remote path. This test-// exercises only local agents, so stub those out to keep it from loading (and-// to fail loud if a remote write is attempted unexpectedly).+// The propagation module imports the SSH stack for the remote path. Stub it so+// it does not load: a test of the remote path sets `mocks.remote` to the host's+// files, and any other test fails loud if a remote write is attempted.vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({- ensureSshConnected: vi.fn(() => {- throw new Error('remote path not expected in this test');+ ensureSshConnected: vi.fn(async () => {+ if (!mocks.remote) throw new Error('remote path not expected in this test');+ return {};}),}));-vi.mock('@main/core/fs/impl/ssh-fs', () => ({- SshFileSystem: class {},-}));+vi.mock('@main/core/fs/impl/ssh-fs', async () => {+ const { FileSystemError, FileSystemErrorCodes } =+ await vi.importActual<typeof import('@main/core/fs/types')>('@main/core/fs/types');+ const host = () => {+ if (!mocks.remote) throw new Error('remote path not expected in this test');+ return mocks.remote;+ };+ return {+ SshFileSystem: class {+ async read(p: string) {+ const content = host().files.get(p);+ if (content === undefined) {+ throw new FileSystemError(`File not found: ${p}`, FileSystemErrorCodes.NOT_FOUND);+ }+ return { content, truncated: false, totalSize: content.length };+ }+ async write(p: string, content: string) {+ host().calls.push(['write', p]);+ host().files.set(p, content);+ return { success: true, bytesWritten: content.length };+ }+ async writeSecret(p: string, content: string) {+ host().calls.push(['writeSecret', p]);+ host().files.set(p, content);+ }+ async protectSecret(p: string, options?: { fileOnly?: boolean }) {+ host().calls.push(['protectSecret', p, options]);+ return host().files.has(p);+ }+ close() {}+ },+ };+});vi.mock('@main/core/locations/location-transport', () => ({sshConnectionIdForHost: (host: string) => host,}));@@ -81,6 +114,7 @@ describe('propagateServerApiUrl', () => {afterEach(async () => {fixture.close();mocks.db = undefined;+ mocks.remote = null;await nodeFs.rm(tmpRoot, { recursive: true, force: true });});@@ -95,6 +129,8 @@ describe('propagateServerApiUrl', () => {SWITCH_AGENT_ID: 'switch-agent-1',},});+ const claudeDir = path.dirname(path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH));+ const claudeDirMode = (await nodeFs.stat(claudeDir)).mode & 0o777;await fixture.db.insert(locations).values({ id: 'loc-1', name: 'Local', sshHost: '', dir });await fixture.db.insert(agents).values({id: 'agent-1',@@ -124,6 +160,13 @@ describe('propagateServerApiUrl', () => {SWITCH_API_TOKEN: 'secret-token',SWITCH_AGENT_ID: 'switch-agent-1',});+ // It still holds a token, so it is the owner's alone; `.claude/` is Claude+ // Code's and keeps its mode.+ if (process.platform !== 'win32') {+ const file = path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH);+ expect((await nodeFs.stat(file)).mode & 0o777).toBe(0o600);+ expect((await nodeFs.stat(claudeDir)).mode & 0o777).toBe(claudeDirMode);+ }// DB mirror follows the file.const [row] = await fixture.db@@ -169,6 +212,10 @@ describe('propagateServerApiUrl', () => {...env,SWITCH_API_ENDPOINT: 'https://new-api.example.com',});+ // Seeded with the default umask; the rewrite leaves it the owner's alone.+ if (process.platform !== 'win32') {+ expect((await nodeFs.stat(file)).mode & 0o777).toBe(0o600);+ }expect((await readEnv(dir)).SWITCH_API_ENDPOINT).toBe('https://other-api.example.com');});@@ -288,4 +335,76 @@ describe('propagateServerApiUrl', () => {expect(results).toEqual([]);expect((await readEnv(dir)).SWITCH_API_ENDPOINT).toBe('https://other-api.example.com');});+ async function remoteAgent(id: string, switchAgentId: string): Promise<void> {+ await fixture.db+ .insert(locations)+ .values({ id: `loc-${id}`, name: 'VM', sshHost: 'vm', dir: '/srv/repo' });+ await fixture.db.insert(agents).values({+ id,+ locationId: `loc-${id}`,+ name: id,+ switchAgentId,+ providerId: 'claude',+ apiEndpoint: 'https://old-api.example.com',+ workspaceId: 'ws-pilot',+ });+ }++ it('rewrites a remote agent’s credentials through a secret write', async () => {+ const relPath = agentSettingsRelativePath('remote-agent');+ mocks.remote = {+ files: new Map([+ [+ relPath,+ JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://old-api.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'sw-remote',+ },+ }),+ ],+ ]),+ calls: [],+ };+ await remoteAgent('remote-agent', 'sw-remote');++ expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([+ { agentId: 'remote-agent', location: 'remote', outcome: 'updated' },+ ]);++ expect(mocks.remote.calls).toEqual([['writeSecret', relPath]]);+ expect(JSON.parse(mocks.remote.files.get(relPath) as string).env).toMatchObject({+ SWITCH_API_ENDPOINT: 'https://new-api.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ });+ });++ it('restricts a remote legacy settings file that holds a token, file only, before rewriting it', async () => {+ mocks.remote = {+ files: new Map([+ [+ SWITCH_SETTINGS_RELATIVE_PATH,+ JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://old-api.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'sw-legacy',+ },+ }),+ ],+ ]),+ calls: [],+ };+ await remoteAgent('legacy-agent', 'sw-legacy');++ expect(await propagateServerApiUrl('pilot', 'https://new-api.example.com')).toMatchObject([+ { agentId: 'legacy-agent', location: 'remote', outcome: 'updated' },+ ]);++ expect(mocks.remote.calls).toEqual([+ ['protectSecret', SWITCH_SETTINGS_RELATIVE_PATH, { fileOnly: true }],+ ['write', SWITCH_SETTINGS_RELATIVE_PATH],+ ]);+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.tsindex d98378ee8..37859a8d6 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/propagate-server-api-url.ts@@ -4,6 +4,7 @@ import { eq } from 'drizzle-orm';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';+import { protectSecretFile, writeSecretFile } from '@main/core/providers/plugin-fs';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import { db } from '@main/db/client';import { agents, workspaces } from '@main/db/schema';@@ -14,7 +15,7 @@ import { getAgentLocation } from './agent-location';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';import { updateAgent } from './updateAgent';import { mapAgentRowToAgent } from './utils';-import { mergeSwitchApiEndpoint } from './write-switch-settings';+import { holdsSwitchToken, mergeSwitchApiEndpoint } from './write-switch-settings';/*** Rewrite one local agent's `SWITCH_API_ENDPOINT`, preserving its token and@@ -50,6 +51,13 @@ async function propagateLocal(throw new Error('The agent credentials file is invalid; its endpoint was not changed.');return false;}+ if (relativePath !== SWITCH_SETTINGS_RELATIVE_PATH) {+ await writeSecretFile(settingsPath, merged);+ return true;+ }+ // Claude Code's own file, so only the file is restricted, not `.claude/`; before+ // the write, which keeps an existing file's mode.+ if (holdsSwitchToken(merged)) await protectSecretFile(settingsPath, { fileOnly: true });await nodeFs.writeFile(settingsPath, merged, 'utf8');return true;}@@ -90,6 +98,11 @@ async function propagateRemote(throw new Error('The agent credentials file is invalid; its endpoint was not changed.');return false;}+ if (relativePath !== SWITCH_SETTINGS_RELATIVE_PATH) {+ await fs.writeSecret(relativePath, merged);+ return true;+ }+ if (holdsSwitchToken(merged)) await fs.protectSecret(relativePath, { fileOnly: true });const result = await fs.write(relativePath, merged);if (!result.success) {throw new Error(`failed to write remote Switch settings: ${result.error ?? 'unknown error'}`);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.test.tsindex ecb601026..3e6f5b356 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.test.ts@@ -19,6 +19,7 @@ function fakeFs(initial: Record<string, string>): PluginFs & { files: Map<stringfiles.delete(p);return Promise.resolve();},+ protectSecret: (p: string) => Promise.resolve(files.has(p)),exists: (p: string) => Promise.resolve(files.has(p)),list: () => Promise.resolve([]),};diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.tsindex 4716bd8c7..33ba2f01e 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts@@ -9,6 +9,7 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs & { files: Map<striread: async (p) => files.get(p) ?? null,write: async (p, c) => void files.set(p, c),delete: async (p) => void files.delete(p),+ protectSecret: async (p) => files.has(p),exists: async (p) => files.has(p),list: async () => [...files.keys()],};@@ -90,11 +91,15 @@ describe('renameLocalAgent', () => {[agentConfigRelativePath('notes-taker')]: '{"instructions":"Take notes"}',});h.state.fs = fs;+ const write = vi.spyOn(fs, 'write');const renamed = await renameLocalAgent({ agentId: 'agent-1', newName: 'meeting-scribe' });expect(renamed.name).toBe('meeting-scribe');expect(fs.files.get(agentSettingsRelativePath('meeting-scribe'))).toBe(OURS);+ expect(write).toHaveBeenCalledWith(agentSettingsRelativePath('meeting-scribe'), OURS, {+ secret: true,+ });expect(fs.files.get(agentConfigRelativePath('meeting-scribe'))).toBe('{"instructions":"Take notes"}');diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.tsindex 41762d4b7..f22d98581 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts@@ -103,7 +103,7 @@ async function moveProvisionedFiles(previous: Agent, renamed: Agent): Promise<vo`${agentSettingsRelativePath(to)} belongs to the Switch server at ${owner}; refusing to overwrite another install's credentials`);}- await ctx.fs.write(agentSettingsRelativePath(to), creds);+ await ctx.fs.write(agentSettingsRelativePath(to), creds, { secret: true });}const config = await ctx.fs.read(agentConfigRelativePath(from));if (config !== null) await ctx.fs.write(agentConfigRelativePath(to), config);diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.tsindex c4dc881e8..c4f91a83d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -14,6 +14,7 @@ import {ForeignAgentCredentialsError,foreignCredentialsEndpoint,foreignCredentialsOwnerFs,+ holdsSwitchToken,mergeSwitchApiEndpoint,mergeSwitchSettings,removeSwitchSettings,@@ -119,6 +120,48 @@ describe('writeNeutralAgentSettingsFs', () => {expect(ignore).toBe('*\n');});+ it.skipIf(process.platform === 'win32')(+ 'leaves the token readable by its owner alone, whatever the umask',+ async () => {+ const previous = process.umask(0o022);+ try {+ await writeNeutralAgentSettingsFs(createPluginFs(dir), {+ slug: 'agent-abc',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'secret-token',+ agentId: 'switch-agent-1',+ });+ } finally {+ process.umask(previous);+ }++ const file = path.join(dir, agentSettingsRelativePath('agent-abc'));+ expect((await fs.stat(file)).mode & 0o777).toBe(0o600);+ expect((await fs.stat(path.dirname(file))).mode & 0o777).toBe(0o700);+ }+ );++ it.skipIf(process.platform === 'win32')(+ 'tightens a credentials file and directory an earlier version left open',+ async () => {+ const file = path.join(dir, agentSettingsRelativePath('agent-abc'));+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o755 });+ await fs.writeFile(file, JSON.stringify({ env: { SWITCH_API_TOKEN: 'old' } }), {+ mode: 0o644,+ });++ await writeNeutralAgentSettingsFs(createPluginFs(dir), {+ slug: 'agent-abc',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'new-token',+ agentId: 'switch-agent-1',+ });++ expect((await fs.stat(file)).mode & 0o777).toBe(0o600);+ expect((await fs.stat(path.dirname(file))).mode & 0o777).toBe(0o700);+ }+ );+it('merges into an existing per-agent file, preserving unrelated env keys and allow rules', async () => {const relPath = agentSettingsRelativePath('agent-abc');await fs.mkdir(path.dirname(path.join(dir, relPath)), { recursive: true });@@ -482,3 +525,14 @@ describe('removeSwitchSettings', () => {expect(await detectSwitchAgent(dir)).toBeNull();});});++describe('holdsSwitchToken', () => {+ it('is true only for settings whose env carries a token', () => {+ expect(holdsSwitchToken(JSON.stringify({ env: { SWITCH_API_TOKEN: 'secret' } }))).toBe(true);+ expect(holdsSwitchToken(JSON.stringify({ env: { SWITCH_AGENT_ID: 'a' } }))).toBe(false);+ expect(holdsSwitchToken(JSON.stringify({ SWITCH_API_TOKEN: 'not in env' }))).toBe(false);+ expect(holdsSwitchToken('null')).toBe(false);+ expect(holdsSwitchToken('{')).toBe(false);+ expect(holdsSwitchToken(null)).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.tsindex 4336f9f52..6cc5e6a81 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts@@ -110,6 +110,21 @@ export function mergeAgentCredentials(return `${JSON.stringify({ ...merged, env }, null, 2)}\n`;}+/**+ * Whether a settings file's text carries a Switch token in its `env` block,+ * which makes it a credential however it was written. False for text that is+ * not a JSON object.+ */+export function holdsSwitchToken(raw: string | null): boolean {+ if (raw === null) return false;+ try {+ const parsed = JSON.parse(raw) as { env?: Record<string, unknown> } | null;+ return typeof parsed?.env?.SWITCH_API_TOKEN === 'string';+ } catch {+ return false;+ }+}+/*** Update ONLY `SWITCH_API_ENDPOINT` in an already-provisioned settings file,* returning the new file text — or `null` when the file is not a provisioned@@ -519,5 +534,5 @@ export async function writeNeutralAgentSettingsFs(if (!(await workdirFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {await workdirFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');}- await workdirFs.write(relPath, mergeAgentCredentials(existingRaw, params));+ await workdirFs.write(relPath, mergeAgentCredentials(existingRaw, params), { secret: true });}diff --git a/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.test.ts b/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.test.tsindex 099633179..5bd685bcb 100644--- a/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.test.ts@@ -3,6 +3,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { FileSystemErrorCodes, type FileEntry, type FileListResult } from '../types';import { SshFileSystem } from './ssh-fs';+const h = vi.hoisted(() => ({ warn: vi.fn() }));++vi.mock('@main/lib/logger', () => ({+ log: { warn: h.warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));+type SftpMkdirError = Error & { code?: number };function listResult(entries: FileEntry[]): FileListResult {@@ -135,6 +141,217 @@ describe('SshFileSystem.remove', () => {});});+/** What an SFTP server answers for a path that is not there. */+const noSuchFile = () => Object.assign(new Error('No such file'), { code: 2 });+/** What an SFTP server answers for a path this account may not change. */+const permissionDenied = () => Object.assign(new Error('Permission denied'), { code: 3 });++function makeSecretFs(+ options: { renameThrows?: Error; missing?: string[]; denied?: string[]; entries?: string[] } = {}+) {+ const missing = options.missing ?? [];+ const denied = options.denied ?? [];+ const calls: unknown[][] = [];+ const handle = Buffer.from('handle');+ const step = (name: string) =>+ vi.fn((...args: unknown[]) => {+ const callback = args.pop() as (error?: Error) => void;+ calls.push([name, ...args]);+ const target = args[0] as string;+ callback(+ missing.includes(target)+ ? noSuchFile()+ : denied.includes(target)+ ? permissionDenied()+ : undefined+ );+ });+ const sftp = {+ on: vi.fn(),+ readdir: vi.fn(+ (+ dir: string,+ callback: (error: Error | undefined, list?: { filename: string }[]) => void+ ) => {+ calls.push(['readdir', dir]);+ if (missing.includes(dir)) callback(noSuchFile());+ else+ callback(+ undefined,+ (options.entries ?? []).map((filename) => ({ filename }))+ );+ }+ ),+ mkdir: vi.fn((dirPath: string, callback: (error?: Error) => void) => {+ calls.push(['mkdir', dirPath]);+ callback(new Error('File exists'));+ }),+ chmod: step('chmod'),+ open: vi.fn(+ (+ path: string,+ flags: string,+ attrs: unknown,+ callback: (error: Error | undefined, handle: Buffer) => void+ ) => {+ calls.push(['open', path, flags, attrs]);+ callback(undefined, handle);+ }+ ),+ fchmod: step('fchmod'),+ write: step('write'),+ close: step('close'),+ // ssh2 throws, rather than calling back, when the server lacks posix-rename.+ ext_openssh_rename: options.renameThrows+ ? vi.fn((from: string, to: string) => {+ calls.push(['rename', from, to]);+ throw options.renameThrows;+ })+ : step('rename'),+ unlink: step('unlink'),+ };+ const proxy = {+ sftp: vi.fn((callback: (error: Error | undefined, sftp: unknown) => void) => {+ callback(undefined, sftp);+ }),+ };+ return { fs: new SshFileSystem(proxy as never, '/repo'), calls, handle };+}++describe('SshFileSystem.writeSecret', () => {+ it('writes a 0600 temporary file and renames it over the target, in a 0700 directory', async () => {+ const { fs, calls, handle } = makeSecretFs();++ await fs.writeSecret('.switch/agents/a.json', 'token');++ const temporary = calls.find((call) => call[0] === 'open')?.[1] as string;+ expect(temporary).toMatch(/^\/repo\/\.switch\/agents\/a\.json\.[0-9a-f-]{36}$/);+ expect(calls.map((call) => call[0])).toEqual([+ 'mkdir',+ 'chmod',+ 'open',+ 'fchmod',+ 'write',+ 'close',+ 'rename',+ ]);+ expect(calls).toContainEqual(['chmod', '/repo/.switch/agents', 0o700]);+ expect(calls).toContainEqual(['open', temporary, 'wx', { mode: 0o600 }]);+ expect(calls).toContainEqual(['fchmod', handle, 0o600]);+ expect(String(calls.find((call) => call[0] === 'write')?.[2])).toBe('token');+ expect(calls).toContainEqual(['rename', temporary, '/repo/.switch/agents/a.json']);+ });++ it('writes the file and warns when its directory belongs to another account', async () => {+ const { fs, calls } = makeSecretFs({ denied: ['/repo/.switch/agents'] });++ await fs.writeSecret('.switch/agents/a.json', 'token');++ expect(calls.map((call) => call[0])).toEqual([+ 'mkdir',+ 'chmod',+ 'open',+ 'fchmod',+ 'write',+ 'close',+ 'rename',+ ]);+ expect(h.warn).toHaveBeenCalledWith(expect.stringContaining('another account'), {+ dir: '/repo/.switch/agents',+ });+ });++ it('removes the temporary file and fails when the server cannot rename over the target', async () => {+ const { fs, calls } = makeSecretFs({+ renameThrows: new Error('Server does not support this extended request'),+ });++ await expect(fs.writeSecret('.switch/agents/a.json', 'token')).rejects.toThrow(+ /does not support/+ );++ const temporary = calls.find((call) => call[0] === 'open')?.[1];+ expect(calls.at(-1)).toEqual(['unlink', temporary]);+ });++ it('rejects a path escape before reaching SFTP', async () => {+ const { fs, calls } = makeSecretFs();++ await expect(fs.writeSecret('../outside.json', 'token')).rejects.toMatchObject({+ code: FileSystemErrorCodes.PATH_ESCAPE,+ });+ expect(calls).toEqual([]);+ });+});++describe('SshFileSystem.protectSecret', () => {+ it('makes an existing file 0600 and its directory 0700, writing nothing', async () => {+ const { fs, calls } = makeSecretFs();++ expect(await fs.protectSecret('.switch/agents/a.json')).toBe(true);++ expect(calls).toEqual([+ ['chmod', '/repo/.switch/agents/a.json', 0o600],+ ['chmod', '/repo/.switch/agents', 0o700],+ ]);+ });++ it('leaves the directory alone when asked to protect only the file', async () => {+ const { fs, calls } = makeSecretFs();++ expect(await fs.protectSecret('.claude/settings.local.json', { fileOnly: true })).toBe(true);++ expect(calls).toEqual([['chmod', '/repo/.claude/settings.local.json', 0o600]]);+ });++ it('still fails when the file itself cannot be changed', async () => {+ const { fs } = makeSecretFs({ denied: ['/repo/.switch/agents/a.json'] });++ await expect(fs.protectSecret('.switch/agents/a.json')).rejects.toMatchObject({+ code: FileSystemErrorCodes.PERMISSION_DENIED,+ });+ });++ it('changes nothing and says so when there is no file', async () => {+ const { fs, calls } = makeSecretFs({ missing: ['/repo/.switch/agents/a.json'] });++ expect(await fs.protectSecret('.switch/agents/a.json')).toBe(false);++ expect(calls).toEqual([['chmod', '/repo/.switch/agents/a.json', 0o600]]);+ });+});++describe('SshFileSystem.removeSecretTemps', () => {+ const uuid = '0b6f1d2e-3c4a-4b5d-8e9f-a0b1c2d3e4f5';++ it('removes only the copies an interrupted secret write of the file left', async () => {+ const { fs, calls } = makeSecretFs({+ entries: ['a.json', `a.json.${uuid}`, 'a.json.bak', `a.json2.${uuid}`, `b.json.${uuid}`],+ });++ await fs.removeSecretTemps('.switch/agents/a.json');++ expect(calls).toEqual([+ ['readdir', '/repo/.switch/agents'],+ ['unlink', `/repo/.switch/agents/a.json.${uuid}`],+ ]);+ });++ it('resolves when the directory is not there', async () => {+ const { fs, calls } = makeSecretFs({ missing: ['/repo/.switch/agents'] });++ await expect(fs.removeSecretTemps('.switch/agents/a.json')).resolves.toBeUndefined();+ expect(calls).toEqual([['readdir', '/repo/.switch/agents']]);+ });++ it('resolves when a copy is gone by the time it is removed', async () => {+ const temporary = `/repo/.switch/agents/a.json.${uuid}`;+ const { fs } = makeSecretFs({ entries: [`a.json.${uuid}`], missing: [temporary] });++ await expect(fs.removeSecretTemps('.switch/agents/a.json')).resolves.toBeUndefined();+ });+});+describe('SshFileSystem.watch', () => {afterEach(() => {vi.useRealTimers();diff --git a/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.ts b/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.tsindex 694c05dc8..1dcf9bb4f 100644--- a/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.ts+++ b/console/apps/switch-console-desktop/src/main/core/fs/impl/ssh-fs.ts@@ -5,6 +5,8 @@import { posix as pathPosix } from 'node:path';import type { SFTPWrapper } from 'ssh2';+import { isPermissionDenied } from '@main/core/fs/permission-denied';+import { isSecretTempOf, secretTempPath } from '@main/core/fs/secret-temp';import { buildRemoteShellCommand } from '@main/core/ssh/lifecycle/remote-shell-profile';import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';import { log } from '@main/lib/logger';@@ -50,6 +52,9 @@ const MAX_READ_SIZE = 100 * 1024 * 1024;*/const DEFAULT_MAX_BYTES = 200 * 1024;+const isNotFound = (error: unknown) =>+ error instanceof FileSystemError && error.code === FileSystemErrorCodes.NOT_FOUND;+function fileEntryMetadataChanged(prev: FileEntry, next: FileEntry): boolean {return (prev.type !== next.type ||@@ -355,6 +360,118 @@ export class SshFileSystem implements FileSystemProvider {});}+ /**+ * Write a file readable by its owner alone (`0600`) inside a directory only+ * its owner can enter (`0700`, when this account owns it): the `secret` write+ * of `PluginFs`, for a file holding a credential. The content goes into a temporary file created+ * `0600` and is renamed over the target with OpenSSH's POSIX rename, so it+ * never sits in a file anyone else can read, and an existing file with wider+ * permissions is replaced rather than kept. A server without that+ * rename fails the write rather than falling back to one that could expose+ * the credential.+ */+ async writeSecret(path: string, content: string): Promise<void> {+ const fullPath = this.resolveRemotePath(path);+ const sftp = await this.getSftp();++ const dir = pathPosix.dirname(fullPath);+ await this.ensureRemoteDir(sftp, dir);+ // A directory that already existed keeps its mode until it is changed here.+ await this.restrictSecretDirectory(sftp, dir);++ const temporary = secretTempPath(fullPath);+ const handle = await new Promise<Buffer>((resolve, reject) =>+ sftp.open(temporary, 'wx', { mode: 0o600 }, (err, opened) =>+ err ? reject(this.mapSftpError(err, temporary)) : resolve(opened)+ )+ );+ try {+ try {+ // Not every server applies the mode it is given at open.+ await this.sftpDone(temporary, (cb) => sftp.fchmod(handle, 0o600, cb));+ const buffer = Buffer.from(content, 'utf-8');+ if (buffer.length > 0)+ await this.sftpDone(temporary, (cb) =>+ sftp.write(handle, buffer, 0, buffer.length, 0, cb)+ );+ } finally {+ await this.sftpDone(temporary, (cb) => sftp.close(handle, cb));+ }+ await this.sftpDone(fullPath, (cb) => sftp.ext_openssh_rename(temporary, fullPath, cb));+ } catch (error) {+ await this.sftpDone(temporary, (cb) => sftp.unlink(temporary, cb)).catch(() => {});+ throw error;+ }+ }++ /**+ * Give an existing file the permissions {@link writeSecret} would (`0600`, in+ * a `0700` directory unless `fileOnly`) without touching its content.+ * Resolves false, changing nothing, when there is no file.+ */+ async protectSecret(path: string, options?: { fileOnly?: boolean }): Promise<boolean> {+ const fullPath = this.resolveRemotePath(path);+ const sftp = await this.getSftp();+ try {+ await this.sftpDone(fullPath, (cb) => sftp.chmod(fullPath, 0o600, cb));+ } catch (error) {+ if (isNotFound(error)) return false;+ throw error;+ }+ if (!options?.fileOnly) await this.restrictSecretDirectory(sftp, pathPosix.dirname(fullPath));+ return true;+ }++ /**+ * `chmod(dir, 0o700)`. A directory another account owns cannot be changed by+ * this one; it is left as it is with a warning rather than failing the+ * operation, since the secret file in it is private either way.+ */+ private async restrictSecretDirectory(sftp: SFTPWrapper, dir: string): Promise<void> {+ try {+ await this.sftpDone(dir, (cb) => sftp.chmod(dir, 0o700, cb));+ } catch (error) {+ if (!isPermissionDenied(error)) throw error;+ log.warn('ssh-fs: secret directory belongs to another account; left as it is', { dir });+ }+ }++ /** Remove the temporary copies an interrupted {@link writeSecret} of `path` left beside it. */+ async removeSecretTemps(path: string): Promise<void> {+ const fullPath = this.resolveRemotePath(path);+ const sftp = await this.getSftp();+ const dir = pathPosix.dirname(fullPath);+ let names: string[];+ try {+ names = await new Promise<string[]>((resolve, reject) =>+ sftp.readdir(dir, (err, list) =>+ err ? reject(this.mapSftpError(err, dir)) : resolve(list.map((item) => item.filename))+ )+ );+ } catch (error) {+ if (isNotFound(error)) return;+ throw error;+ }+ for (const name of names) {+ if (!isSecretTempOf(name, pathPosix.basename(fullPath))) continue;+ const temporary = `${dir}/${name}`;+ // Gone already is fine: a write in flight may have just renamed it.+ await this.sftpDone(temporary, (cb) => sftp.unlink(temporary, cb)).catch((error) => {+ if (!isNotFound(error)) throw error;+ });+ }+ }++ /** Run one callback-style SFTP call, rejecting with its error mapped to a {@link FileSystemError}. */+ private sftpDone(+ target: string,+ run: (callback: (err?: Error | null) => void) => void+ ): Promise<void> {+ return new Promise<void>((resolve, reject) =>+ run((err) => (err ? reject(this.mapSftpError(err, target)) : resolve()))+ );+ }+/*** Recursively list all files and directories via SSH find (single round-trip).* Returns items in the same {path, type} format used by the local fs:list handler.diff --git a/console/apps/switch-console-desktop/src/main/core/fs/permission-denied.test.ts b/console/apps/switch-console-desktop/src/main/core/fs/permission-denied.test.tsnew file mode 100644index 000000000..1f65210e7--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/fs/permission-denied.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { isPermissionDenied } from './permission-denied';+import { FileSystemError, FileSystemErrorCodes } from './types';++describe('isPermissionDenied', () => {+ it('recognises a refusal from the local disk or over SFTP', () => {+ expect(isPermissionDenied(Object.assign(new Error('x'), { code: 'EPERM' }))).toBe(true);+ expect(isPermissionDenied(Object.assign(new Error('x'), { code: 'EACCES' }))).toBe(true);+ expect(+ isPermissionDenied(new FileSystemError('x', FileSystemErrorCodes.PERMISSION_DENIED))+ ).toBe(true);+ });++ it('does not take a failure that may pass for one', () => {+ expect(isPermissionDenied(new Error('SSH connection is not available'))).toBe(false);+ expect(isPermissionDenied(Object.assign(new Error('x'), { code: 'EIO' }))).toBe(false);+ expect(+ isPermissionDenied(new FileSystemError('x', FileSystemErrorCodes.CONNECTION_ERROR))+ ).toBe(false);+ expect(isPermissionDenied(null)).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/fs/permission-denied.ts b/console/apps/switch-console-desktop/src/main/core/fs/permission-denied.tsnew file mode 100644index 000000000..66c6533a8--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/fs/permission-denied.ts@@ -0,0 +1,14 @@+import { FileSystemError, FileSystemErrorCodes } from './types';++/**+ * Whether a filesystem failure, on the local disk or over SFTP, is this account+ * being refused: typically a file or directory another account owns, which+ * trying again will not change.+ */+export function isPermissionDenied(error: unknown): boolean {+ if (error instanceof FileSystemError) {+ return error.code === FileSystemErrorCodes.PERMISSION_DENIED;+ }+ const code = (error as NodeJS.ErrnoException | null)?.code;+ return code === 'EPERM' || code === 'EACCES';+}diff --git a/console/apps/switch-console-desktop/src/main/core/fs/secret-temp.test.ts b/console/apps/switch-console-desktop/src/main/core/fs/secret-temp.test.tsnew file mode 100644index 000000000..018b00ce9--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/fs/secret-temp.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { isSecretTempOf, secretTempPath } from './secret-temp';++describe('secret temporary copies', () => {+ it('recognises the names it hands out, for that file only', () => {+ const temporary = secretTempPath('/w/.switch/agents/a.json');+ const name = temporary.slice('/w/.switch/agents/'.length);++ expect(isSecretTempOf(name, 'a.json')).toBe(true);+ expect(isSecretTempOf(name, 'b.json')).toBe(false);+ expect(isSecretTempOf(name, 'a.jso')).toBe(false);+ });++ it('ignores names that only look like one', () => {+ const uuid = '0b6f1d2e-3c4a-4b5d-8e9f-a0b1c2d3e4f5';+ expect(isSecretTempOf('a.json', 'a.json')).toBe(false);+ expect(isSecretTempOf('a.json.bak', 'a.json')).toBe(false);+ expect(isSecretTempOf(`a.json2.${uuid}`, 'a.json')).toBe(false);+ expect(isSecretTempOf(`a.json.${uuid.toUpperCase()}`, 'a.json')).toBe(false);+ expect(isSecretTempOf(`a.json.${uuid}.x`, 'a.json')).toBe(false);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/fs/secret-temp.ts b/console/apps/switch-console-desktop/src/main/core/fs/secret-temp.tsnew file mode 100644index 000000000..c8f8a1c89--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/fs/secret-temp.ts@@ -0,0 +1,26 @@+import { randomUUID } from 'node:crypto';++/**+ * A secret write puts the content in a temporary `<file>.<uuid>` beside the+ * file and renames it into place. A write cut off before the rename (the app+ * killed, the SSH connection dropped) leaves that copy behind holding the same+ * secret, so deleting the file removes those copies with it.+ */+export function secretTempPath(file: string): string {+ return `${file}.${randomUUID()}`;+}++/**+ * What follows the file's name in a temporary copy's name, as a regular+ * expression source. It is written without backslashes so it can be embedded+ * in a script run on a host.+ */+export const SECRET_TEMP_SUFFIX =+ '^[.][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$';++const suffix = new RegExp(SECRET_TEMP_SUFFIX);++/** Whether `entry`, a name in a directory, is a temporary copy of the file `name` there. */+export function isSecretTempOf(entry: string, name: string): boolean {+ return entry.startsWith(name) && suffix.test(entry.slice(name.length));+}diff --git a/console/apps/switch-console-desktop/src/main/core/fs/windows-owner-acl.test.ts b/console/apps/switch-console-desktop/src/main/core/fs/windows-owner-acl.test.tsnew file mode 100644index 000000000..3d66cf7e9--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/fs/windows-owner-acl.test.ts@@ -0,0 +1,74 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ execFile: vi.fn(+ (+ _command: string,+ _args: string[],+ _options: unknown,+ callback: (error: Error | null) => void+ ) => callback(null)+ ),+ warn: vi.fn(),+}));++vi.mock('node:child_process', () => ({ execFile: h.execFile }));+vi.mock('@main/lib/logger', () => ({ log: { warn: h.warn } }));++import { restrictWindowsDirectoryToOwner, restrictWindowsFileToOwner } from './windows-owner-acl';++describe('Windows owner-only ACLs', () => {+ const previousUser = process.env.USERNAME;++ beforeEach(() => {+ vi.clearAllMocks();+ process.env.USERNAME = 'alice';+ });++ afterEach(() => {+ if (previousUser === undefined) delete process.env.USERNAME;+ else process.env.USERNAME = previousUser;+ });++ it('replaces a file’s inherited ACL with full control for the current user alone', async () => {+ await restrictWindowsFileToOwner('C:\\work\\.switch\\agents\\a.json');++ expect(h.execFile.mock.calls[0]?.slice(0, 2)).toEqual([+ 'icacls',+ ['C:\\work\\.switch\\agents\\a.json', '/inheritance:r', '/grant:r', 'alice:F'],+ ]);+ });++ it('makes a directory’s grant inheritable, so the files in it are restricted too', async () => {+ await restrictWindowsDirectoryToOwner('C:\\work\\.switch\\agents');++ expect(h.execFile.mock.calls[0]?.slice(0, 2)).toEqual([+ 'icacls',+ ['C:\\work\\.switch\\agents', '/inheritance:r', '/grant:r', 'alice:(OI)(CI)F'],+ ]);+ });++ it('warns and leaves the path alone when it cannot tell who the user is', async () => {+ delete process.env.USERNAME;++ await restrictWindowsFileToOwner('C:\\work\\a.json');++ expect(h.execFile).not.toHaveBeenCalled();+ expect(h.warn).toHaveBeenCalledWith(expect.stringContaining('USERNAME unset'), {+ path: 'C:\\work\\a.json',+ });+ });++ it('warns rather than throws when icacls fails', async () => {+ h.execFile.mockImplementationOnce((_command, _args, _options, callback) =>+ callback(new Error('Access is denied.'))+ );++ await expect(restrictWindowsDirectoryToOwner('C:\\work')).resolves.toBeUndefined();++ expect(h.warn).toHaveBeenCalledWith(expect.stringContaining('could not restrict'), {+ path: 'C:\\work',+ error: 'Access is denied.',+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/fs/windows-owner-acl.ts b/console/apps/switch-console-desktop/src/main/core/fs/windows-owner-acl.tsnew file mode 100644index 000000000..f17ad16c7--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/fs/windows-owner-acl.ts@@ -0,0 +1,48 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { log } from '@main/lib/logger';++const execFileAsync = promisify(execFile);++/**+ * Replace the inherited ACL on `path` with one granting the current user alone.+ *+ * A failure is logged rather than thrown: losing the operation over a+ * hardening step is worse than a degraded mode that says so out loud.+ */+async function restrictToOwner(path: string, grant: (account: string) => string): Promise<void> {+ const account = process.env.USERNAME;+ if (!account) {+ log.warn('fs: USERNAME unset; path left with inherited permissions', { path });+ return;+ }+ try {+ await execFileAsync('icacls', [path, '/inheritance:r', '/grant:r', grant(account)], {+ timeout: 15_000,+ });+ } catch (error) {+ log.warn('fs: could not restrict permissions; the path stays readable by other accounts', {+ path,+ error: String((error as Error)?.message ?? error),+ });+ }+}++/**+ * Windows has no mode bits: `chmod(path, 0o600)` only toggles the read-only+ * flag, so on its own it would leave a credential readable by every account on+ * the machine while looking protected.+ */+export function restrictWindowsFileToOwner(path: string): Promise<void> {+ return restrictToOwner(path, (account) => `${account}:F`);+}++/**+ * The directory counterpart of {@link restrictWindowsFileToOwner}, standing in+ * for `chmod(dir, 0o700)`. The grant is inheritable, so files already in the+ * directory that inherit their permissions, and any created in it later, are+ * restricted with it.+ */+export function restrictWindowsDirectoryToOwner(path: string): Promise<void> {+ return restrictToOwner(path, (account) => `${account}:(OI)(CI)F`);+}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.tsindex 9ff4f4576..410415e13 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/host/local-host.ts@@ -1,10 +1,9 @@-import { execFile, spawn } from 'node:child_process';+import { spawn } from 'node:child_process';import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';import { dirname, join } from 'node:path';-import { promisify } from 'node:util';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import type { IExecutionContext } from '@main/core/execution-context/types';-import { log } from '@main/lib/logger';+import { restrictWindowsFileToOwner } from '@main/core/fs/windows-owner-acl';import type { DockerAvailability } from '@shared/core/managed-switch-server/managed-switch-server';import { LOCAL_SERVER_PROJECT_NAME } from '../constants';import { detectDocker, dockerExecutable } from '../docker';@@ -12,38 +11,6 @@ import { type LocalServerPorts, pickFreePorts } from '../free-port';import { localServerDir } from '../paths';import type { ServerHost } from './types';-const execFileAsync = promisify(execFile);--/**- * Windows has no mode bits: `chmod(path, 0o600)` only toggles the read-only- * flag, so on its own it would leave the managed server's Postgres and gateway- * credentials readable by every account on the machine while looking protected.- * Replace the inherited ACL with one that grants the current user alone.- *- * A failure is logged rather than thrown: the caller has already written the- * file, and losing the stack over a hardening step nobody asked for is worse- * than a degraded mode that says so out loud.- */-async function restrictWindowsFileToOwner(path: string): Promise<void> {- const account = process.env.USERNAME;- if (!account) {- log.warn('local-switch-server: USERNAME unset; file left with inherited permissions', {- path,- });- return;- }- try {- await execFileAsync('icacls', [path, '/inheritance:r', '/grant:r', `${account}:F`], {- timeout: 15_000,- });- } catch (error) {- log.warn('local-switch-server: could not restrict file permissions; it stays world-readable', {- path,- error: String((error as Error)?.message ?? error),- });- }-}-/*** The managed stack running on this machine's Docker daemon — the CHOO-1428* behaviour, now expressed through {@link ServerHost}. Commands run via a localdiff --git a/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.test.tsindex aa66b7966..3618bd59b 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.test.ts@@ -1,9 +1,31 @@-import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { promises as nodeFs } from 'node:fs';+import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createPluginFs } from './plugin-fs';+const acl = vi.hoisted(() => ({+ directory: vi.fn(async (_path: string) => {}),+ file: vi.fn(async (_path: string) => {}),+}));+const warn = vi.hoisted(() => vi.fn());++vi.mock('@main/core/fs/windows-owner-acl', () => ({+ restrictWindowsDirectoryToOwner: acl.directory,+ restrictWindowsFileToOwner: acl.file,+}));+vi.mock('@main/lib/logger', () => ({ log: { warn } }));++/** Make `chmod` of `target` fail with `code`, as it does for a path another account owns. */+function refuseChmod(target: string, code: string) {+ const real = nodeFs.chmod;+ return vi.spyOn(nodeFs, 'chmod').mockImplementation(async (p, mode) => {+ if (p === target) throw Object.assign(new Error(`${code}: chmod '${target}'`), { code });+ return real(p, mode);+ });+}+/*** Against a real temp directory rather than a mocked `node:fs`: the behaviour* under test is which errno values are treated as "already absent", and a mock@@ -60,4 +82,251 @@ describe('createPluginFs delete', () => {const fs = createPluginFs(root);await expect(fs.delete('../outside.json')).rejects.toThrow(/path escape/);});++ it('removes the copies an interrupted secret write left, and nothing else', async () => {+ // A secret write renames `<file>.<uuid>` into place; cut off first, the copy+ // holds the same token, and deleting the agent must not leave it behind.+ const fs = createPluginFs(root);+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true });+ const uuid = '0b6f1d2e-3c4a-4b5d-8e9f-a0b1c2d3e4f5';+ for (const name of [+ 'a.json',+ `a.json.${uuid}`,+ `a.json.${uuid.replace('0b6f', '1c7a')}`,+ 'a.json.bak',+ `a.json2.${uuid}`,+ `b.json.${uuid}`,+ ]) {+ await writeFile(path.join(dir, name), 'token');+ }++ await fs.delete('.switch/agents/a.json');++ expect((await readdir(dir)).sort()).toEqual([+ 'a.json.bak',+ `a.json2.${uuid}`,+ `b.json.${uuid}`,+ ]);+ });++ it('removes a leftover copy when the file itself was never written', async () => {+ const fs = createPluginFs(root);+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true });+ await writeFile(path.join(dir, 'a.json.0b6f1d2e-3c4a-4b5d-8e9f-a0b1c2d3e4f5'), 'token');++ await fs.delete('.switch/agents/a.json');++ expect(await readdir(dir)).toEqual([]);+ });+});++const modeOf = async (p: string) => (await stat(p)).mode & 0o777;++describe.skipIf(process.platform === 'win32')('createPluginFs secret write', () => {+ let root: string;++ beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'plugin-fs-secret-'));+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ warn.mockClear();+ await rm(root, { recursive: true, force: true });+ });++ it('creates the file 0600 in a 0700 directory whatever the umask, leaving nothing else', async () => {+ const previous = process.umask(0o022);+ try {+ await createPluginFs(root).write('.switch/agents/a.json', 'token', { secret: true });+ } finally {+ process.umask(previous);+ }++ const dir = path.join(root, '.switch', 'agents');+ expect(await readFile(path.join(dir, 'a.json'), 'utf8')).toBe('token');+ expect(await modeOf(path.join(dir, 'a.json'))).toBe(0o600);+ expect(await modeOf(dir)).toBe(0o700);+ expect(await readdir(dir)).toEqual(['a.json']);+ });++ it('replaces a file and tightens a directory an earlier version left open', async () => {+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true, mode: 0o755 });+ await chmod(dir, 0o755);+ await writeFile(path.join(dir, 'a.json'), 'old', { mode: 0o644 });++ await createPluginFs(root).write('.switch/agents/a.json', 'new', { secret: true });++ expect(await readFile(path.join(dir, 'a.json'), 'utf8')).toBe('new');+ expect(await modeOf(path.join(dir, 'a.json'))).toBe(0o600);+ expect(await modeOf(dir)).toBe(0o700);+ });++ it('removes its temporary file and throws when the target cannot be replaced', async () => {+ // A directory where the file should be: the rename over it fails.+ await mkdir(path.join(root, 'secrets', 'a.json'), { recursive: true });++ await expect(+ createPluginFs(root).write('secrets/a.json', 'token', { secret: true })+ ).rejects.toThrow();++ expect(await readdir(path.join(root, 'secrets'))).toEqual(['a.json']);+ });++ it('refuses a path escape', async () => {+ await expect(+ createPluginFs(root).write('../outside.json', 'token', { secret: true })+ ).rejects.toThrow(/path escape/);+ });++ it('protects an existing file and its directory without touching the content', async () => {+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true });+ await chmod(dir, 0o755);+ await writeFile(path.join(dir, 'a.json'), 'token', { mode: 0o644 });+ const before = await stat(path.join(dir, 'a.json'));++ expect(await createPluginFs(root).protectSecret('.switch/agents/a.json')).toBe(true);++ const after = await stat(path.join(dir, 'a.json'));+ expect(after.mode & 0o777).toBe(0o600);+ expect(await modeOf(dir)).toBe(0o700);+ // The same file, not a replacement: nothing a concurrent writer did is undone.+ expect(after.ino).toBe(before.ino);+ expect(await readFile(path.join(dir, 'a.json'), 'utf8')).toBe('token');+ });++ it('leaves the directory alone and says so when there is no file to protect', async () => {+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true });+ await chmod(dir, 0o755);++ expect(await createPluginFs(root).protectSecret('.switch/agents/a.json')).toBe(false);+ expect(await createPluginFs(root).protectSecret('missing/a.json')).toBe(false);++ expect(await modeOf(dir)).toBe(0o755);+ });++ it('writes the file 0600 and warns when its directory belongs to another account', async () => {+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true });+ await chmod(dir, 0o755);+ refuseChmod(dir, 'EPERM');++ await createPluginFs(root).write('.switch/agents/a.json', 'token', { secret: true });++ expect(await readFile(path.join(dir, 'a.json'), 'utf8')).toBe('token');+ expect(await modeOf(path.join(dir, 'a.json'))).toBe(0o600);+ expect(await modeOf(dir)).toBe(0o755);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('another account'), { dir });+ });++ it('still fails when the directory cannot be changed for any other reason', async () => {+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true });+ refuseChmod(dir, 'EROFS');++ await expect(+ createPluginFs(root).write('.switch/agents/a.json', 'token', { secret: true })+ ).rejects.toThrow(/EROFS/);+ expect(await readdir(dir)).toEqual([]);+ });++ it('protects only the file when asked to leave its directory alone', async () => {+ const dir = path.join(root, '.claude');+ await mkdir(dir, { recursive: true });+ await chmod(dir, 0o755);+ await writeFile(path.join(dir, 'settings.local.json'), '{}', { mode: 0o644 });++ expect(+ await createPluginFs(root).protectSecret('.claude/settings.local.json', { fileOnly: true })+ ).toBe(true);++ expect(await modeOf(path.join(dir, 'settings.local.json'))).toBe(0o600);+ expect(await modeOf(dir)).toBe(0o755);+ });++ it('refuses to protect a path outside its root', async () => {+ await expect(createPluginFs(root).protectSecret('../outside.json')).rejects.toThrow(+ /path escape/+ );+ });+});++describe.skipIf(process.platform === 'win32')('createPluginFs list', () => {+ let root: string;++ beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'plugin-fs-list-'));+ });++ afterEach(async () => {+ await chmod(path.join(root, 'locked'), 0o755).catch(() => {});+ await rm(root, { recursive: true, force: true });+ });++ it('answers [] for a directory that is not there, strict or not', async () => {+ const fs = createPluginFs(root);+ await writeFile(path.join(root, 'afile'), 'x');+ expect(await fs.list('missing')).toEqual([]);+ expect(await fs.list('missing', { strict: true })).toEqual([]);+ expect(await fs.list('afile', { strict: true })).toEqual([]);+ });++ it('throws for a directory it may not read only when strict', async () => {+ const fs = createPluginFs(root);+ await mkdir(path.join(root, 'locked'));+ await writeFile(path.join(root, 'locked', 'a.json'), 'token');+ await chmod(path.join(root, 'locked'), 0o000);++ expect(await fs.list('locked')).toEqual([]);+ await expect(fs.list('locked', { strict: true })).rejects.toMatchObject({ code: 'EACCES' });+ });+});++describe('createPluginFs secret write on Windows', () => {+ const platform = process.platform;+ let root: string;++ beforeEach(async () => {+ vi.clearAllMocks();+ root = await mkdtemp(path.join(tmpdir(), 'plugin-fs-secret-win-'));+ Object.defineProperty(process, 'platform', { value: 'win32' });+ });++ afterEach(async () => {+ Object.defineProperty(process, 'platform', { value: platform });+ await rm(root, { recursive: true, force: true });+ });++ it('restricts the directory, then the still-empty temporary file, before writing the token', async () => {+ const seen: Array<[string, string, string | null]> = [];+ acl.directory.mockImplementationOnce(async (p) => void seen.push(['directory', p, null]));+ acl.file.mockImplementationOnce(+ async (p) => void seen.push(['file', p, await readFile(p, 'utf8')])+ );++ await createPluginFs(root).write('.switch/agents/a.json', 'token', { secret: true });++ const dir = path.join(root, '.switch', 'agents');+ expect(seen).toEqual([+ ['directory', dir, null],+ ['file', expect.stringMatching(/a\.json\.[0-9a-f-]{36}$/), ''],+ ]);+ expect(await readFile(path.join(dir, 'a.json'), 'utf8')).toBe('token');+ });++ it('protects an existing file and its directory with owner-only ACLs', async () => {+ const dir = path.join(root, '.switch', 'agents');+ await mkdir(dir, { recursive: true });+ await writeFile(path.join(dir, 'a.json'), 'token');++ expect(await createPluginFs(root).protectSecret('.switch/agents/a.json')).toBe(true);++ expect(acl.directory).toHaveBeenCalledWith(dir);+ expect(acl.file).toHaveBeenCalledWith(path.join(dir, 'a.json'));+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.ts b/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.tsindex 70394ac7b..7330928ac 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/plugin-fs.ts@@ -1,6 +1,105 @@import { promises as fs } from 'node:fs';-import { dirname, join, resolve, sep } from 'node:path';-import type { PluginFs } from '@switch-console/core/agents/plugins';+import { basename, dirname, join, resolve, sep } from 'node:path';+import { replaceFile } from '@switch-console/agent-providers';+import type {+ PluginFs,+ PluginFsListOptions,+ PluginFsProtectOptions,+ PluginFsWriteOptions,+} from '@switch-console/core/agents/plugins';+import { isSecretTempOf, secretTempPath } from '@main/core/fs/secret-temp';+import {+ restrictWindowsDirectoryToOwner,+ restrictWindowsFileToOwner,+} from '@main/core/fs/windows-owner-acl';+import { log } from '@main/lib/logger';++const isAbsent = (error: unknown) => {+ const code = (error as NodeJS.ErrnoException).code;+ return code === 'ENOENT' || code === 'ENOTDIR';+};++/**+ * `chmod(dir, 0o700)`, or what stands in for it on Windows, where a mode does+ * nothing for a directory. A directory another account owns cannot be changed+ * by this one; it is left as it is with a warning rather than failing the+ * operation, since the secret file in it is private either way.+ */+async function restrictSecretDirectory(dir: string): Promise<void> {+ if (process.platform === 'win32') return restrictWindowsDirectoryToOwner(dir);+ try {+ await fs.chmod(dir, 0o700);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EPERM') throw error;+ log.warn('plugin-fs: secret directory belongs to another account; left as it is', {+ dir,+ });+ }+}++/**+ * Write `content` to `abs` readable by its owner alone, in a directory only its+ * owner can enter: the `secret` write of {@link PluginFs}, for a file holding a+ * credential. The content goes into a temporary file created `0600` and is+ * renamed over `abs`, so it never sits in a file anyone else can read, and an+ * existing file with wider permissions is replaced rather than kept.+ */+export async function writeSecretFile(abs: string, content: string): Promise<void> {+ const dir = dirname(abs);+ await fs.mkdir(dir, { recursive: true });+ // mkdir's mode reaches only a directory it creates, not one that was already there.+ await restrictSecretDirectory(dir);+ const temporary = secretTempPath(abs);+ const file = await fs.open(temporary, 'wx', 0o600);+ try {+ try {+ if (process.platform === 'win32') await restrictWindowsFileToOwner(temporary);+ await file.writeFile(content, 'utf-8');+ await file.sync();+ } finally {+ await file.close();+ }+ await replaceFile(temporary, abs);+ } catch (error) {+ await fs.rm(temporary, { force: true });+ throw error;+ }+}++/**+ * Give an existing file at `abs` the permissions {@link writeSecretFile} would,+ * without touching its content. Resolves false, changing nothing, when there is+ * no file.+ */+export async function protectSecretFile(+ abs: string,+ options?: PluginFsProtectOptions+): Promise<boolean> {+ try {+ await fs.chmod(abs, 0o600);+ } catch (error) {+ if (isAbsent(error)) return false;+ throw error;+ }+ if (!options?.fileOnly) await restrictSecretDirectory(dirname(abs));+ if (process.platform === 'win32') await restrictWindowsFileToOwner(abs);+ return true;+}++/** Remove the temporary copies an interrupted {@link writeSecretFile} of `abs` left beside it. */+async function removeSecretTemps(abs: string): Promise<void> {+ const dir = dirname(abs);+ let entries: string[];+ try {+ entries = await fs.readdir(dir);+ } catch (error) {+ if (isAbsent(error)) return;+ throw error;+ }+ for (const entry of entries) {+ if (isSecretTempOf(entry, basename(abs))) await fs.rm(join(dir, entry), { force: true });+ }+}/*** Create a CLIAgentPluginFs scoped to a given root directory.@@ -37,12 +136,17 @@ export function createPluginFs(root: string): PluginFs {}},- async write(path: string, content: string): Promise<void> {+ async write(path: string, content: string, options?: PluginFsWriteOptions): Promise<void> {const abs = resolveSafe(path);+ if (options?.secret) return writeSecretFile(abs, content);await fs.mkdir(dirname(abs), { recursive: true });await fs.writeFile(abs, content, 'utf-8');},+ async protectSecret(path: string, options?: PluginFsProtectOptions): Promise<boolean> {+ return protectSecretFile(resolveSafe(path), options);+ },+async delete(path: string): Promise<void> {const abs = resolveSafe(path);try {@@ -52,11 +156,11 @@ export function createPluginFs(root: string): PluginFs {// A permission error or an I/O failure must propagate: delete is how an// agent's Switch token is revoked from disk, and a silent no-op there// reports a credential as destroyed while it is still readable.- const code = (error as NodeJS.ErrnoException).code;- if (code !== 'ENOENT' && code !== 'ENOTDIR') {- throw error;- }+ if (!isAbsent(error)) throw error;}+ // Whether or not the file was there: a first write cut off before its+ // rename leaves only the copy.+ await removeSecretTemps(abs);},async exists(path: string): Promise<boolean> {@@ -68,10 +172,11 @@ export function createPluginFs(root: string): PluginFs {}},- async list(path: string): Promise<string[]> {+ async list(path: string, options?: PluginFsListOptions): Promise<string[]> {try {return await fs.readdir(resolveSafe(path));- } catch {+ } catch (error) {+ if (options?.strict && !isAbsent(error)) throw error;return [];}},diff --git a/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.test.tsindex 6b3ef8f4f..44262ebc5 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.test.ts@@ -57,19 +57,73 @@ describe('createRemotePluginFs', () => {await expect(fs.write('a', 'b')).rejects.toThrow(/disk full/);});+ it('a secret write goes through writeSecret, never the ordinary write', async () => {+ const write = vi.fn(async () => ({ success: true, bytesWritten: 5 }));+ const writeSecret = vi.fn(async () => {});+ const fs = adapter({ write, writeSecret });+ await fs.write('.switch/agents/a.json', 'token', { secret: true });+ expect(writeSecret).toHaveBeenCalledWith('.switch/agents/a.json', 'token');+ expect(write).not.toHaveBeenCalled();+ });++ it('a secret write that fails propagates rather than falling back to an ordinary one', async () => {+ const write = vi.fn(async () => ({ success: true, bytesWritten: 5 }));+ const fs = adapter({+ write,+ writeSecret: vi.fn(async () => {+ throw new Error('Server does not support this extended request');+ }),+ });+ await expect(fs.write('.switch/agents/a.json', 'token', { secret: true })).rejects.toThrow(+ /does not support/+ );+ expect(write).not.toHaveBeenCalled();+ });+it('delete removes the path and ignores a missing file', async () => {// The literal SshFileSystem.remove produces when its stat finds nothing.const remove = vi.fn(async () => ({ success: false, error: 'File not found: gone' }));- const fs = adapter({ remove });+ const fs = adapter({ remove, removeSecretTemps: vi.fn(async () => {}) });await expect(fs.delete('gone')).resolves.toBeUndefined();expect(remove).toHaveBeenCalledWith('gone');});it('delete resolves when the remove succeeds', async () => {- const fs = adapter({ remove: vi.fn(async () => ({ success: true })) });+ const fs = adapter({+ remove: vi.fn(async () => ({ success: true })),+ removeSecretTemps: vi.fn(async () => {}),+ });await expect(fs.delete('x')).resolves.toBeUndefined();});+ it('delete also removes what an interrupted secret write of the file left', async () => {+ const removeSecretTemps = vi.fn(async () => {});+ const fs = adapter({ remove: vi.fn(async () => ({ success: true })), removeSecretTemps });+ await fs.delete('.switch/agents/a.json');+ expect(removeSecretTemps).toHaveBeenCalledWith('.switch/agents/a.json');+ });++ it('delete throws when those copies cannot be removed', async () => {+ const fs = adapter({+ remove: vi.fn(async () => ({ success: true })),+ removeSecretTemps: vi.fn(async () => {+ throw new Error('Permission denied');+ }),+ });+ await expect(fs.delete('.switch/agents/a.json')).rejects.toThrow(/Permission denied/);+ });++ it('protectSecret goes to the remote filesystem, options and all, and returns what it found', async () => {+ const protectSecret = vi.fn(async () => false);+ const fs = adapter({ protectSecret });+ expect(await fs.protectSecret('.switch/agents/a.json')).toBe(false);+ await fs.protectSecret('.claude/settings.local.json', { fileOnly: true });+ expect(protectSecret.mock.calls).toEqual([+ ['.switch/agents/a.json', undefined],+ ['.claude/settings.local.json', { fileOnly: true }],+ ]);+ });+it('delete throws (fails loud) when the file is there but cannot be removed', async () => {// `remove` reports failure through its result rather than throwing, so a// caller that ignores the result reports an undeletable Switch token as@@ -101,6 +155,23 @@ describe('createRemotePluginFs', () => {expect(list).toHaveBeenCalledWith('.claude/switch-subagents', { includeHidden: true });});+ it('a strict list answers [] for a missing directory and throws on anything else', async () => {+ const missing = adapter({+ list: vi.fn(async () => {+ throw new FileSystemError('No such file', FileSystemErrorCodes.NOT_FOUND);+ }),+ });+ expect(await missing.list('gone', { strict: true })).toEqual([]);++ const broken = adapter({+ list: vi.fn(async () => {+ throw new FileSystemError('channel open failure', FileSystemErrorCodes.CONNECTION_ERROR);+ }),+ });+ expect(await broken.list('x')).toEqual([]);+ await expect(broken.list('x', { strict: true })).rejects.toThrow(/channel open failure/);+ });+it('list returns [] when the directory is missing', async () => {const fs = adapter({list: vi.fn(async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.ts b/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.tsindex a4093fdb3..7cef0a637 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/remote-plugin-fs.ts@@ -1,5 +1,10 @@import { posix as pathPosix } from 'node:path';-import type { PluginFs } from '@switch-console/core/agents/plugins';+import type {+ PluginFs,+ PluginFsListOptions,+ PluginFsProtectOptions,+ PluginFsWriteOptions,+} from '@switch-console/core/agents/plugins';import { assertRemoved } from '@main/core/fs/assert-removed';import type { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';@@ -37,7 +42,8 @@ export function createRemotePluginFs(fs: SshFileSystem): PluginFs {}},- async write(path: string, content: string): Promise<void> {+ async write(path: string, content: string, options?: PluginFsWriteOptions): Promise<void> {+ if (options?.secret) return fs.writeSecret(path, content);const result = await fs.write(path, content);if (!result.success) {throw new Error(@@ -46,19 +52,27 @@ export function createRemotePluginFs(fs: SshFileSystem): PluginFs {}},+ async protectSecret(path: string, options?: PluginFsProtectOptions): Promise<boolean> {+ return fs.protectSecret(path, options);+ },+async delete(path: string): Promise<void> {assertRemoved(path, await fs.remove(path));+ await fs.removeSecretTemps(path);},async exists(path: string): Promise<boolean> {return fs.exists(path);},- async list(path: string): Promise<string[]> {+ async list(path: string, options?: PluginFsListOptions): Promise<string[]> {try {const result = await fs.list(path, { includeHidden: true });return result.entries.map((entry) => pathPosix.basename(entry.path));- } catch {+ } catch (error) {+ const absent =+ error instanceof FileSystemError && error.code === FileSystemErrorCodes.NOT_FOUND;+ if (options?.strict && !absent) throw error;return [];}},diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.test.tsindex b821bb9ee..c484d7886 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-credentials.test.ts@@ -22,6 +22,7 @@ function memoryFs(files: Record<string, string> = {}): PluginFs {read: async (p) => store.get(p) ?? null,write: async (p, c) => void store.set(p, c),delete: async (p) => void store.delete(p),+ protectSecret: async (p) => store.has(p),exists: async (p) => store.has(p),list: async () => [...store.keys()],};diff --git a/console/packages/core/src/agents/plugins/helpers/mcp.test.ts b/console/packages/core/src/agents/plugins/helpers/mcp.test.tsindex 490abac39..1367ed1e3 100644--- a/console/packages/core/src/agents/plugins/helpers/mcp.test.ts+++ b/console/packages/core/src/agents/plugins/helpers/mcp.test.ts@@ -17,6 +17,9 @@ function createMemoryFs(initial: Record<string, string> = {}): PluginFs {async delete(path) {store.delete(path);},+ async protectSecret(path) {+ return store.has(path);+ },async exists(path) {return store.has(path);},diff --git a/console/packages/core/src/agents/plugins/index.ts b/console/packages/core/src/agents/plugins/index.tsindex d55f489b6..68d3017ae 100644--- a/console/packages/core/src/agents/plugins/index.ts+++ b/console/packages/core/src/agents/plugins/index.ts@@ -72,7 +72,12 @@ export type { AgentIconAsset, AgentIconVariant } from './assets/icon';// Convenience re-exports for impl packagesexport type { AgentCommand, CommandContext } from './capabilities/prompt';-export type { PluginFs } from '../runtime/fs';+export type {+ PluginFs,+ PluginFsListOptions,+ PluginFsProtectOptions,+ PluginFsWriteOptions,+} from '../runtime/fs';// Capability behavior interfaces — needed for dts portabilityexport type { IHostDependencyBehavior } from '../../host-dependencies/capability';export type {diff --git a/console/packages/core/src/agents/runtime/fs.ts b/console/packages/core/src/agents/runtime/fs.tsindex 5d5e8d4ee..9ec6f600a 100644--- a/console/packages/core/src/agents/runtime/fs.ts+++ b/console/packages/core/src/agents/runtime/fs.ts@@ -1,3 +1,34 @@+export interface PluginFsWriteOptions {+ /**+ * The file holds a credential. It is readable by its owner alone (`0600`),+ * including when it already existed with wider permissions: the content is+ * written to a private temporary file and renamed into place, so it is never+ * readable by anyone else, even briefly. Its directory is made one only its+ * owner can enter (`0700`) when this account owns it; one owned by another+ * account is left as it is, with a warning, since the file is private either+ * way. On Windows both get owner-only ACLs, and a failure to apply one is a+ * warning rather than an error.+ */+ secret?: boolean;+}++export interface PluginFsProtectOptions {+ /**+ * Leave the file's directory alone: for a credential kept in a directory+ * that belongs to another tool, such as `.claude/`.+ */+ fileOnly?: boolean;+}++export interface PluginFsListOptions {+ /**+ * Throw on any failure other than the directory not being there, rather+ * than answering `[]`, for a caller that must not mistake an unreadable+ * directory for an empty one.+ */+ strict?: boolean;+}+export interface PluginFs {/*** Returns the file's content, or `null` only when the file does not exist.@@ -6,8 +37,24 @@ export interface PluginFs {* makes them rewrite the file from scratch, discarding its real content.*/read(path: string): Promise<string | null>;- write(path: string, content: string): Promise<void>;+ /**+ * An implementation that does not support `secret` must throw rather than+ * write the file with ordinary permissions.+ */+ write(path: string, content: string, options?: PluginFsWriteOptions): Promise<void>;+ /**+ * Gives an existing file the permissions a `secret` write would, without+ * reading or rewriting it, so it cannot undo a concurrent write. Resolves+ * false, changing nothing, when there is no file. An implementation that+ * does not support this must throw.+ */+ protectSecret(path: string, options?: PluginFsProtectOptions): Promise<boolean>;+ /**+ * Also removes any temporary copy an interrupted `secret` write of the file+ * left beside it. Resolves when the file is already absent; any other+ * failure throws.+ */delete(path: string): Promise<void>;exists(path: string): Promise<boolean>;- list(path: string): Promise<string[]>;+ list(path: string, options?: PluginFsListOptions): Promise<string[]>;}diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts b/console/packages/plugins/src/agents/impl/claude/subagents.test.tsindex aac2ac45b..100282a3c 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -15,6 +15,7 @@ function fakeFs(files: Record<string, string>): PluginFs {store.delete(p);return Promise.resolve();},+ protectSecret: (p) => Promise.resolve(store.has(p)),exists: (p) => Promise.resolve(store.has(p)),list: (dir) => {const prefix = dir.endsWith('/') ? dir : `${dir}/`;