Skip to content

The agent that grows with you

feat(desktop): folder-scoped plugin file access (ctx.files)

Tekniumc421c930fe95
diff --git a/apps/desktop/electron/fs-ipc.test.ts b/apps/desktop/electron/fs-ipc.test.ts
index 76f33cec01e..b7ce849154d 100644
--- a/apps/desktop/electron/fs-ipc.test.ts
+++ b/apps/desktop/electron/fs-ipc.test.ts
@@ -16,6 +16,9 @@ const electron = vi.hoisted(() => ({
}))
vi.mock('electron', () => ({
+ app: { getPath: () => os.tmpdir() },
+ BrowserWindow: { fromWebContents: () => null },
+ dialog: { showOpenDialog: vi.fn() },
ipcMain: {
handle: (channel: string, handler: (...args: unknown[]) => unknown) => electron.handlers.set(channel, handler)
},
diff --git a/apps/desktop/electron/fs-ipc.ts b/apps/desktop/electron/fs-ipc.ts
index 9a4cb972130..a70a1cf8459 100644
--- a/apps/desktop/electron/fs-ipc.ts
+++ b/apps/desktop/electron/fs-ipc.ts
@@ -1,12 +1,14 @@
// IPC surface for local filesystem operations the renderer's project/file
// surfaces use: directory reads, reveal/open in the OS file manager, plugin
-// roots + git installs, rename/write/trash. Extracted from main.ts; path
-// hardening, HERMES_HOME resolution, and the git binary stay injected.
+// roots + git installs, rename/write/trash, and the plugin SDK's folder-scoped
+// file door. Extracted from main.ts; path hardening, HERMES_HOME resolution,
+// and the git binary stay injected.
import fs from 'node:fs'
import path from 'node:path'
-import { ipcMain, shell } from 'electron'
+import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron'
+import { platformDefaultHermesHome } from './data-paths'
import { installDesktopPluginFromGit, probePluginRepo } from './desktop-plugin-install'
import { removeDesktopPlugin } from './desktop-plugin-remove'
import {
@@ -18,6 +20,7 @@ import {
import { DESKTOP_PROFILE_NAME_RE } from './desktop-profile'
import { readDirForIpc } from './fs-read-dir'
import { gitRootForIpc } from './git-root'
+import { registerPluginFilesIpc } from './plugin-files-ipc'
export interface FsIpcDeps {
hermesHome: string
@@ -38,6 +41,27 @@ export function registerFsIpc({
}: FsIpcDeps) {
ipcMain.handle('hermes:fs:readDir', async (_event, dirPath) => readDirForIpc(dirPath))
+ // `ctx.files`: a plugin's own data folder plus folders the user grants it.
+ // The legacy `~/.hermes` stays protected beside the resolved and default homes.
+ registerPluginFilesIpc({
+ ipcMain,
+ dialog,
+ windowFor: event => BrowserWindow.fromWebContents(event.sender),
+ // App windows only: preview guests and webviews never hear about grants.
+ broadcastChange: change => {
+ for (const window of BrowserWindow.getAllWindows()) {
+ window.webContents.send('hermes:pluginFiles:changed', change)
+ }
+ },
+ userDataDir: () => app.getPath('userData'),
+ hermesHomes: () => [
+ hermesHome,
+ platformDefaultHermesHome(app.getPath('home')),
+ path.join(app.getPath('home'), '.hermes')
+ ],
+ trashItem: target => shell.trashItem(target)
+ })
+
ipcMain.handle('hermes:fs:gitRoot', async (_event, startPath) => gitRootForIpc(startPath))
// Reveal a path in the OS file manager (Finder / Explorer / Files).
diff --git a/apps/desktop/electron/plugin-files-guards.ts b/apps/desktop/electron/plugin-files-guards.ts
new file mode 100644
index 00000000000..b1875869b48
--- /dev/null
+++ b/apps/desktop/electron/plugin-files-guards.ts
@@ -0,0 +1,243 @@
+// Path rules for the `ctx.files` door (plugin-files.ts): how a plugin-supplied
+// relative path is split, how containment is compared, and which folders can
+// never be granted. Pure helpers plus filesystem identity checks; no state.
+
+import { createHash } from 'node:crypto'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { realpathOrNull, refuse } from './plugin-files-ops'
+
+const REL_PATH_MAX = 1024
+const SEGMENT_MAX = 255
+// Plugin ids become a folder name under the shared data root, so only a plain
+// slug may reach the join (no separators, no leading dot, no `..`, and no
+// trailing dot, which Windows drops: `foo.` would share `foo`'s folder).
+const PLUGIN_ID_RE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,126}[A-Za-z0-9_-])?$/
+// Windows device names open the device, not a file, with any extension.
+const WIN_RESERVED_RE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$|clock\$)(?:\.|$)/i
+// Kernel pseudo-filesystems: their files are "regular" with size 0 and can
+// hold the app's own environment (`/proc/self/environ`).
+const SYSTEM_ROOTS = ['/proc', '/sys', '/dev']
+
+// The same filesystems by type, wherever they are mounted (a container's
+// `/host/proc`, a chroot's `proc`): proc, sysfs, debugfs, tracefs,
+// securityfs, cgroup, cgroup2, bpf, efivarfs, configfs, pstore, selinuxfs.
+const PSEUDO_FS_TYPES = new Set([
+ 0x9fa0, 0x62656572, 0x64626720, 0x74726163, 0x73636673, 0x27e0eb, 0x63677270, 0xcafe4a11, 0xde5e81e4,
+ 0x62656570, 0x6165676c, 0xf97cff8c
+])
+
+const WSL_SHARE_RE = /^\\\\(?:wsl\.localhost|wsl\$)\\[^\\]+/i
+// Top-level WSL folders that are not files of the distro: its kernel views
+// (process environments included) and its mounts of the Windows drives.
+const WSL_SYSTEM_DIRS = new Set(['dev', 'mnt', 'proc', 'run', 'sys'])
+
+const within = (child: string, parent: string): boolean => {
+ const rel = path.relative(parent, child)
+
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))
+}
+
+export function pathTools(platform: NodeJS.Platform) {
+ // Every comparison errs toward refusing. Containment ("may the plugin use
+ // this?") compares realpaths exactly, so a case-sensitive volume's `vault`
+ // is never mistaken for the granted `Vault`. Protection ("is this Hermes
+ // data?") also matches case-insensitively where volumes usually are, so a
+ // differently-cased spelling of a protected path is still refused.
+ const caseless = platform === 'win32' || platform === 'darwin'
+ const inside = (child: string, parent: string) => within(child, parent)
+
+ const insideLoose = (child: string, parent: string) =>
+ within(child, parent) || (caseless && within(child.toLowerCase(), parent.toLowerCase()))
+
+ const same = (a: string, b: string) => path.resolve(a) === path.resolve(b)
+
+ // Split a plugin-supplied relative path into plain segments, refusing (not
+ // normalizing) anything that could name a place outside the folder.
+ const segments = (raw: unknown): string[] => {
+ if (typeof raw !== 'string' || raw.length > REL_PATH_MAX || raw.includes('\0')) {
+ return refuse('invalid-path', 'Path must be a relative path inside the folder.')
+ }
+
+ if (path.posix.isAbsolute(raw) || path.win32.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw)) {
+ return refuse('invalid-path', 'Path must be relative to the folder, not absolute.')
+ }
+
+ const parts = raw.split(/[\\/]+/).filter(part => part && part !== '.')
+
+ for (const part of parts) {
+ // `..namedfork` opens a macOS file's forks under another name
+ // (`.env/..namedfork/data` is `.env`).
+ if (part === '..' || part.length > SEGMENT_MAX || part.toLowerCase() === '..namedfork') {
+ return refuse('invalid-path', 'Path may not leave the folder.')
+ }
+
+ // Windows drops trailing dots/spaces (`.. ` is `..`), reads `:` as a
+ // stream, and opens a device for `CON`, `NUL.txt`…
+ if (platform === 'win32' && (part.includes(':') || /[. ]$/.test(part) || WIN_RESERVED_RE.test(part))) {
+ return refuse('invalid-path', 'Path segment is not valid on Windows.')
+ }
+ }
+
+ return parts
+ }
+
+ return { inside, insideLoose, same, segments }
+}
+
+export const pluginKey = (pluginId: unknown): string =>
+ typeof pluginId === 'string' && PLUGIN_ID_RE.test(pluginId) && !WIN_RESERVED_RE.test(pluginId)
+ ? pluginId
+ : refuse('invalid-plugin', 'Plugin id is not a plain slug.')
+
+// Case-insensitive filesystems would give `Plexus` and `plexus` one folder; an
+// id with capitals gets a suffix (`~` never appears in an id) to keep them apart.
+export function dataDirName(pluginId: string): string {
+ return pluginId === pluginId.toLowerCase()
+ ? pluginId
+ : `${pluginId.toLowerCase()}~${createHash('sha256').update(pluginId).digest('hex').slice(0, 8)}`
+}
+
+export const systemRoots = (platform: NodeJS.Platform): string[] => (platform === 'win32' ? [] : SYSTEM_ROOTS)
+
+export async function realRoots(roots: string[]): Promise<string[]> {
+ const resolved = await Promise.all(
+ roots.filter(Boolean).map(async root => (await realpathOrNull(root)) ?? path.resolve(root))
+ )
+
+ return [...new Set(resolved)]
+}
+
+/**
+ * A WSL share path that is Hermes data or not the distro's own files: the
+ * distro root, `/home`, a home dir and `/root` each hold a `~/.hermes`, and
+ * anything under a `.hermes` segment is one (Windows Desktop cannot know which
+ * WSL user runs the gateway, so every WSL home counts); `/proc`, `/sys`,
+ * `/dev` and `/run` are the distro's kernel views, and `/mnt` reaches the
+ * Windows drives (and this app's own data) by a second spelling.
+ */
+export function wslProtectedPath(candidate: string): boolean {
+ const share = WSL_SHARE_RE.exec(candidate)
+
+ if (!share) {
+ return false
+ }
+
+ const rest = candidate
+ .slice(share[0].length)
+ .split('\\')
+ .filter(Boolean)
+ .map(part => part.toLowerCase())
+
+ const holdsHome =
+ rest.length === 0 ||
+ (rest.length === 1 && (rest[0] === 'home' || rest[0] === 'root')) ||
+ (rest.length === 2 && rest[0] === 'home')
+
+ return holdsHome || WSL_SYSTEM_DIRS.has(rest[0]) || rest.includes('.hermes')
+}
+
+const LOOPBACK_HOSTS = new Set(['localhost', '::1', '[::1]', '0--1.ipv6-literal.net'])
+
+/**
+ * A Windows path that reaches this machine's own drives a second way, which a
+ * realpath comparison cannot match to the protected folders: a device path
+ * (`\\?\C:\`, `\\.\`, `\\?\GLOBALROOT\…` shadow copies) or a share served by
+ * this machine (`\\localhost\C$`, `\\127.0.0.1\…`, its own name or address).
+ */
+export function loopbackShare(candidate: string): boolean {
+ const unc = /^\\\\\?\\UNC\\/i.test(candidate) ? `\\\\${candidate.slice(8)}` : candidate
+
+ if (/^\\\\[?.]\\/.test(unc)) {
+ return true
+ }
+
+ const host = /^\\\\([^\\]+)/.exec(unc)?.[1].split('@')[0].toLowerCase()
+
+ if (!host) {
+ return false
+ }
+
+ const own = new Set([os.hostname().toLowerCase()])
+
+ for (const addresses of Object.values(os.networkInterfaces())) {
+ for (const address of addresses ?? []) {
+ own.add(address.address.toLowerCase())
+ }
+ }
+
+ return LOOPBACK_HOSTS.has(host) || /^127\./.test(host) || own.has(host) || own.has(host.split('.')[0])
+}
+
+/** True when `target` lives on a kernel pseudo-filesystem (Linux). */
+export async function onPseudoFilesystem(target: string): Promise<boolean> {
+ const stats = await fs.promises.statfs(target).catch(() => null)
+
+ return stats !== null && PSEUDO_FS_TYPES.has(Number(stats.type))
+}
+
+const identity = async (target: string): Promise<null | string> => {
+ const stat = await fs.promises.stat(target).catch(() => null)
+
+ return stat ? `${stat.dev}:${stat.ino}` : null
+}
+
+// The identity of a path and of every folder above it.
+async function identityChain(target: string): Promise<string[]> {
+ const ids: string[] = []
+
+ for (let current = target; ; current = path.dirname(current)) {
+ const id = await identity(current)
+
+ if (id) {
+ ids.push(id)
+ }
+
+ if (path.dirname(current) === current) {
+ return ids
+ }
+ }
+}
+
+/**
+ * Overlap by filesystem identity, not spelling: a bind mount, a macOS firmlink
+ * (`/System/Volumes/Data/Users/…`) or a case-insensitive mount is a second
+ * path to the same folder that a realpath string comparison would miss.
+ */
+export async function overlapsByIdentity(candidate: string, roots: string[]): Promise<boolean> {
+ const self = await identity(candidate)
+ const chain = await identityChain(candidate)
+
+ for (const root of roots) {
+ const rootId = await identity(root)
+
+ if (rootId && (chain.includes(rootId) || (self && (await identityChain(root)).includes(self)))) {
+ return true
+ }
+ }
+
+ return false
+}
+
+/**
+ * True when `target`, or a folder between it and `root`, is one of `roots` by
+ * filesystem identity: a bind mount of the Hermes home inside a granted folder
+ * keeps an inside path but is the protected folder itself.
+ */
+export async function protectedIdentityWithin(target: string, root: string, roots: string[]): Promise<boolean> {
+ const ids = new Set((await Promise.all(roots.map(identity))).filter((id): id is string => id !== null))
+
+ for (let current = target; ; current = path.dirname(current)) {
+ const id = await identity(current)
+
+ if (id && ids.has(id)) {
+ return true
+ }
+
+ if (current === root || path.dirname(current) === current) {
+ return false
+ }
+ }
+}
diff --git a/apps/desktop/electron/plugin-files-hardening.test.ts b/apps/desktop/electron/plugin-files-hardening.test.ts
new file mode 100644
index 00000000000..a1ba0167742
--- /dev/null
+++ b/apps/desktop/electron/plugin-files-hardening.test.ts
@@ -0,0 +1,488 @@
+/**
+ * `ctx.files` refusals beyond plain containment: sensitive files moved out of
+ * their names, kernel pseudo-filesystems, FIFOs, hard links, a folder or file
+ * swapped between the check and the open, and the grants record itself.
+ */
+import { execFileSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { createPluginFiles, type PluginFiles } from './plugin-files'
+
+const posix = process.platform !== 'win32'
+const unprivileged = posix && process.getuid?.() !== 0
+
+let scratch: string
+let userData: string
+let hermesHome: string
+let vault: string
+let files: PluginFiles
+
+const make = () =>
+ createPluginFiles({
+ userDataDir: () => userData,
+ protectedRoots: () => [hermesHome],
+ trashItem: target => fs.promises.rm(target, { recursive: true })
+ })
+
+beforeEach(() => {
+ scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-plugin-files-hard-')))
+ userData = path.join(scratch, 'userData')
+ hermesHome = path.join(scratch, 'home', '.hermes')
+ vault = path.join(scratch, 'home', 'Vault')
+ fs.mkdirSync(userData, { recursive: true })
+ fs.mkdirSync(hermesHome, { recursive: true })
+ fs.writeFileSync(path.join(hermesHome, 'config.yaml'), 'model: secret-config\n')
+ fs.mkdirSync(path.join(vault, 'notes'), { recursive: true })
+ fs.writeFileSync(path.join(vault, 'notes', 'a.md'), '# A\n')
+ files = make()
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ fs.chmodSync(scratch, 0o700)
+ fs.rmSync(scratch, { recursive: true, force: true })
+})
+
+async function grantVault(): Promise<string> {
+ const granted = await files.addGrant('plexus', vault)
+
+ expect(granted.ok).toBe(true)
+
+ return (granted as { folder: { id: string } }).folder.id
+}
+
+describe('sensitive files cannot be moved out of their names', () => {
+ it.each([
+ ['.env', 'notes.txt'],
+ ['server.pem', 'p.txt'],
+ ['id_ed25519', 'key.txt']
+ ])('refuses renaming %s to %s, and trashing it', async (name, renamed) => {
+ const id = await grantVault()
+ fs.writeFileSync(path.join(vault, name), 'SECRET=sk-live\n')
+
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: name, name: renamed })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ expect(await files.run('plexus', { op: 'trash', folder: id, path: name })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ expect(fs.existsSync(path.join(vault, name))).toBe(true)
+ expect(fs.existsSync(path.join(vault, renamed))).toBe(false)
+ })
+
+ it('refuses renaming a key folder so its files lose the rule', async () => {
+ const id = await grantVault()
+ fs.mkdirSync(path.join(vault, '.ssh'))
+ fs.writeFileSync(path.join(vault, '.ssh', 'config'), 'Host x\n')
+
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: '.ssh', name: 'ssh' })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: '.ssh/config' })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ })
+})
+
+describe('only plain files', () => {
+ it.runIf(process.platform === 'linux').each(['/proc', '/sys', '/dev', '/proc/self'])(
+ 'refuses to grant the kernel pseudo-filesystem %s',
+ async folder => {
+ expect(await files.addGrant('plexus', folder)).toMatchObject({
+ ok: false,
+ error: 'protected',
+ message: expect.stringContaining('system folder')
+ })
+ }
+ )
+
+ it.runIf(posix)('refuses a FIFO instead of blocking on it', async () => {
+ const id = await grantVault()
+ execFileSync('mkfifo', [path.join(vault, 'pipe')])
+
+ const result = await Promise.race([
+ files.run('plexus', { op: 'readText', folder: id, path: 'pipe' }),
+ new Promise(resolve => setTimeout(() => resolve('blocked'), 1500))
+ ])
+
+ expect(result).toMatchObject({ ok: false, error: 'not-a-file' })
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: id, path: 'pipe', text: 'x' })
+ ).toMatchObject({ ok: false, error: 'not-a-file' })
+ })
+
+ it.runIf(posix)('refuses a hard link, which may be a second name for Hermes data', async () => {
+ const id = await grantVault()
+ fs.linkSync(path.join(hermesHome, 'config.yaml'), path.join(vault, 'notes', 'c.md'))
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: 'notes/c.md' })).toMatchObject({
+ ok: false,
+ error: 'protected'
+ })
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: id, path: 'notes/c.md', text: 'pwned' })
+ ).toMatchObject({ ok: false, error: 'protected' })
+ expect(fs.readFileSync(path.join(hermesHome, 'config.yaml'), 'utf8')).toBe('model: secret-config\n')
+ })
+})
+
+describe('a swap between the check and the open is refused', () => {
+ // Stands in for another process changing the folder right after `resolve`
+ // looked at `checked` (with lstat, or with stat for its last look).
+ const swapAfterCheck = (method: 'lstat' | 'stat', checked: string, swap: () => void) => {
+ const original = fs.promises[method].bind(fs.promises) as (target: fs.PathLike) => Promise<fs.Stats>
+ let done = false
+
+ vi.spyOn(fs.promises, method).mockImplementation((async (target: fs.PathLike) => {
+ try {
+ return await original(target)
+ } finally {
+ if (!done && String(target) === checked) {
+ done = true
+ swap()
+ }
+ }
+ }) as never)
+ }
+
+ it.runIf(posix)('a parent folder swapped for a link into the Hermes home: no file lands there', async () => {
+ const id = await grantVault()
+ const sub = path.join(vault, 'sub')
+ fs.mkdirSync(sub)
+
+ swapAfterCheck('lstat', path.join(sub, 'pwn.txt'), () => {
+ fs.renameSync(sub, path.join(vault, 'sub-old'))
+ fs.symlinkSync(hermesHome, sub)
+ })
+
+ // Refused either as outside the folder or, when the swap lands before the
+ // identity check, as Hermes data.
+ expect(
+ ((await files.run('plexus', { op: 'writeText', folder: id, path: 'sub/pwn.txt', text: 'pwned' })) as { error?: string })
+ .error
+ ).toMatch(/^(outside-folder|protected)$/)
+ expect(fs.existsSync(path.join(hermesHome, 'pwn.txt'))).toBe(false)
+ })
+
+ it.runIf(posix)('a checked file swapped for a link to Hermes data is not read or written', async () => {
+ const id = await grantVault()
+ const note = path.join(vault, 'notes', 'a.md')
+
+ const swap = () => {
+ fs.rmSync(note)
+ fs.symlinkSync(path.join(hermesHome, 'config.yaml'), note)
+ }
+
+ swapAfterCheck('stat', note, swap)
+ const read = await files.run('plexus', { op: 'readText', folder: id, path: 'notes/a.md' })
+
+ expect(read).toMatchObject({ ok: false })
+ expect(JSON.stringify(read)).not.toContain('secret-config')
+
+ vi.restoreAllMocks()
+ fs.rmSync(note)
+ fs.writeFileSync(note, '# A\n')
+ swapAfterCheck('stat', note, swap)
+
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: id, path: 'notes/a.md', text: 'pwned' })
+ ).toMatchObject({ ok: false })
+ expect(fs.readFileSync(path.join(hermesHome, 'config.yaml'), 'utf8')).toBe('model: secret-config\n')
+ })
+})
+
+describe('a swap before the final look is refused too', () => {
+ // Stands in for another process acting right after `resolve` realpath'd the
+ // target, before it took the identity the open is compared against.
+ const afterRealpath = (checked: string, swap: () => void) => {
+ const original = fs.promises.realpath.bind(fs.promises) as (target: fs.PathLike) => Promise<string>
+ let done = false
+
+ vi.spyOn(fs.promises, 'realpath').mockImplementation((async (target: fs.PathLike) => {
+ try {
+ return await original(target)
+ } finally {
+ if (!done && String(target) === checked) {
+ done = true
+ swap()
+ }
+ }
+ }) as never)
+ }
+
+ it.runIf(posix)('a checked file swapped for a link to Hermes data: not read, not written', async () => {
+ const id = await grantVault()
+ const note = path.join(vault, 'notes', 'a.md')
+
+ const swap = () => {
+ fs.rmSync(note)
+ fs.symlinkSync(path.join(hermesHome, 'config.yaml'), note)
+ }
+
+ afterRealpath(note, swap)
+ const read = await files.run('plexus', { op: 'readText', folder: id, path: 'notes/a.md' })
+
+ expect(read).toMatchObject({ ok: false })
+ expect(JSON.stringify(read)).not.toContain('secret-config')
+
+ vi.restoreAllMocks()
+ fs.rmSync(note)
+ fs.writeFileSync(note, '# A\n')
+ afterRealpath(note, swap)
+
+ expect(await files.run('plexus', { op: 'writeText', folder: id, path: 'notes/a.md', text: 'pwned' })).toMatchObject({
+ ok: false
+ })
+ expect(fs.readFileSync(path.join(hermesHome, 'config.yaml'), 'utf8')).toBe('model: secret-config\n')
+ })
+
+ it.runIf(posix)('a parent folder swapped for a link into the Hermes home: not read, not written', async () => {
+ const id = await grantVault()
+ fs.writeFileSync(path.join(hermesHome, 'a.md'), 'hermes-secret\n')
+ const notes = path.join(vault, 'notes')
+ const note = path.join(notes, 'a.md')
+
+ const swap = () => {
+ fs.renameSync(notes, path.join(vault, 'notes-old'))
+ fs.symlinkSync(hermesHome, notes)
+ }
+
+ afterRealpath(note, swap)
+ const read = await files.run('plexus', { op: 'readText', folder: id, path: 'notes/a.md' })
+
+ expect(read).toMatchObject({ ok: false })
+ expect(JSON.stringify(read)).not.toContain('hermes-secret')
+
+ vi.restoreAllMocks()
+ fs.rmSync(notes)
+ fs.renameSync(path.join(vault, 'notes-old'), notes)
+ afterRealpath(note, swap)
+
+ expect(await files.run('plexus', { op: 'writeText', folder: id, path: 'notes/a.md', text: 'pwned' })).toMatchObject({
+ ok: false
+ })
+ expect(fs.readFileSync(path.join(hermesHome, 'a.md'), 'utf8')).toBe('hermes-secret\n')
+ })
+})
+
+describe('rename, trash and list after a parent swap', () => {
+ // Another process swaps `notes` for a link into the Hermes home right after
+ // `resolve` finished (its last look is the second lstat of the entry): the
+ // op must not act on the Hermes home.
+ const swapParentAfterResolve = (entry: string, notes: string) => {
+ const original = fs.promises.lstat.bind(fs.promises) as (target: fs.PathLike) => Promise<fs.Stats>
+ let seen = 0
+
+ vi.spyOn(fs.promises, 'lstat').mockImplementation((async (target: fs.PathLike) => {
+ try {
+ return await original(target)
+ } finally {
+ if (String(target) === entry && ++seen === 2) {
+ fs.renameSync(notes, `${notes}-old`)
+ fs.symlinkSync(hermesHome, notes)
+ }
+ }
+ }) as never)
+ }
+
+ beforeEach(() => {
+ fs.writeFileSync(path.join(hermesHome, 'a.md'), 'hermes-file\n')
+ })
+
+ it.runIf(posix)('rename does not move a Hermes file', async () => {
+ const id = await grantVault()
+ const notes = path.join(vault, 'notes')
+ swapParentAfterResolve(path.join(notes, 'a.md'), notes)
+
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: 'notes/a.md', name: 'b.md' })).toMatchObject({
+ ok: false
+ })
+ expect(fs.readFileSync(path.join(hermesHome, 'a.md'), 'utf8')).toBe('hermes-file\n')
+ expect(fs.existsSync(path.join(hermesHome, 'b.md'))).toBe(false)
+ })
+
+ it.runIf(posix)('a swap in the last instant before the rename is undone', async () => {
+ const id = await grantVault()
+ const notes = path.join(vault, 'notes')
+ const original = fs.promises.rename.bind(fs.promises) as (from: fs.PathLike, to: fs.PathLike) => Promise<void>
+ let swapped = false
+
+ vi.spyOn(fs.promises, 'rename').mockImplementation((async (from: fs.PathLike, to: fs.PathLike) => {
+ if (!swapped && String(from) === path.join(notes, 'a.md')) {
+ swapped = true
+ fs.renameSync(notes, `${notes}-old`)
+ fs.symlinkSync(hermesHome, notes)
+ }
+
+ return original(from, to)
+ }) as never)
+
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: 'notes/a.md', name: 'b.md' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ expect(fs.readFileSync(path.join(hermesHome, 'a.md'), 'utf8')).toBe('hermes-file\n')
+ expect(fs.existsSync(path.join(hermesHome, 'b.md'))).toBe(false)
+ })
+
+ it.runIf(posix)('the undo never overwrites a file recreated meanwhile', async () => {
+ const id = await grantVault()
+ const notes = path.join(vault, 'notes')
+ const original = fs.promises.rename.bind(fs.promises) as (from: fs.PathLike, to: fs.PathLike) => Promise<void>
+ let calls = 0
+
+ vi.spyOn(fs.promises, 'rename').mockImplementation((async (from: fs.PathLike, to: fs.PathLike) => {
+ if (++calls === 1) {
+ fs.renameSync(notes, `${notes}-old`)
+ fs.symlinkSync(hermesHome, notes)
+ await original(from, to)
+ // Another app writes a new a.md where the moved one was.
+ fs.writeFileSync(path.join(hermesHome, 'a.md'), 'newer\n')
+
+ return
+ }
+
+ return original(from, to)
+ }) as never)
+
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: 'notes/a.md', name: 'b.md' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ expect(fs.readFileSync(path.join(hermesHome, 'a.md'), 'utf8')).toBe('newer\n')
+ expect(fs.readFileSync(path.join(hermesHome, 'b.md'), 'utf8')).toBe('hermes-file\n')
+ })
+
+ it.runIf(posix)('trash does not remove a Hermes file', async () => {
+ const id = await grantVault()
+ const notes = path.join(vault, 'notes')
+ swapParentAfterResolve(path.join(notes, 'a.md'), notes)
+
+ expect(await files.run('plexus', { op: 'trash', folder: id, path: 'notes/a.md' })).toMatchObject({ ok: false })
+ expect(fs.readFileSync(path.join(hermesHome, 'a.md'), 'utf8')).toBe('hermes-file\n')
+ })
+
+ it.runIf(posix)('list does not return the Hermes home', async () => {
+ const id = await grantVault()
+ const sub = path.join(vault, 'notes', 'sub')
+ fs.mkdirSync(sub)
+ fs.mkdirSync(path.join(hermesHome, 'sub'))
+ fs.writeFileSync(path.join(hermesHome, 'sub', 'config.yaml'), 'x\n')
+ swapParentAfterResolve(sub, path.join(vault, 'notes'))
+
+ const listed = await files.run('plexus', { op: 'list', folder: id, path: 'notes/sub' })
+
+ expect(listed).toMatchObject({ ok: false })
+ expect(JSON.stringify(listed)).not.toContain('config.yaml')
+ })
+})
+
+describe('Hermes data mounted inside a granted folder', () => {
+ // Stands in for a bind mount of the Hermes home at Vault/mounted (present
+ // before the grant or added after): same filesystem identity, inside path.
+ it('refuses every op under it', async () => {
+ const mounted = path.join(vault, 'mounted')
+ fs.mkdirSync(mounted)
+ fs.writeFileSync(path.join(mounted, 'config.yaml'), 'mirror\n')
+ const id = await grantVault()
+ const home = fs.statSync(hermesHome)
+ const original = fs.promises.stat.bind(fs.promises) as (target: fs.PathLike, options?: never) => Promise<fs.Stats>
+
+ vi.spyOn(fs.promises, 'stat').mockImplementation((async (target: fs.PathLike, options?: never) => {
+ const real = await original(target, options)
+
+ return String(target) === mounted ? Object.assign(Object.create(Object.getPrototypeOf(real)), real, { dev: home.dev, ino: home.ino }) : real
+ }) as never)
+
+ for (const request of [
+ { op: 'readText', path: 'mounted/config.yaml' },
+ { op: 'list', path: 'mounted' },
+ { op: 'stat', path: 'mounted/config.yaml' },
+ { op: 'writeText', path: 'mounted/new.md', text: 'x' }
+ ] as const) {
+ expect(await files.run('plexus', { ...request, folder: id } as never)).toMatchObject({ ok: false, error: 'protected' })
+ }
+
+ expect(fs.existsSync(path.join(mounted, 'new.md'))).toBe(false)
+ })
+})
+
+describe('the grants record', () => {
+ it.runIf(unprivileged)('a record that cannot be read is not overwritten with nothing', async () => {
+ await grantVault()
+ const record = path.join(userData, 'plugin-files', 'grants.json')
+ const before = fs.readFileSync(record, 'utf8')
+ fs.chmodSync(record, 0o000)
+ const other = path.join(scratch, 'Other')
+ fs.mkdirSync(other)
+
+ expect(await make().addGrant('plexus', other)).toMatchObject({ ok: false, error: 'io-error' })
+ fs.chmodSync(record, 0o600)
+ expect(fs.readFileSync(record, 'utf8')).toBe(before)
+ })
+
+ it.runIf(unprivileged)('a revoke that cannot be saved does not take effect now or after restart', async () => {
+ const id = await grantVault()
+ const base = path.join(userData, 'plugin-files')
+ fs.chmodSync(base, 0o500)
+
+ await expect(files.revoke('plexus', id)).rejects.toThrow()
+ fs.chmodSync(base, 0o700)
+
+ expect((await files.grants('plexus')).map(row => row.id)).toEqual([id])
+ expect((await make().grants('plexus')).map(row => row.id)).toEqual([id])
+ })
+
+ it('a first read still in flight cannot undo a revoke made meanwhile', async () => {
+ const id = await grantVault()
+ const fresh = make()
+ const original = fs.promises.readFile.bind(fs.promises) as (...args: unknown[]) => Promise<unknown>
+
+ let releaseFirst = () => {}
+ const firstHeld = new Promise<void>(resolve => (releaseFirst = resolve))
+ let calls = 0
+
+ // The first read of the record finishes only after the revoke has saved.
+ vi.spyOn(fs.promises, 'readFile').mockImplementation((async (...args: unknown[]) => {
+ const data = await original(...args)
+
+ if (String(args[0]).endsWith('grants.json') && calls++ === 0) {
+ await firstHeld
+ }
+
+ return data
+ }) as never)
+
+ const reading = fresh.grants('plexus')
+ const revoking = fresh.revoke('plexus', id)
+ await new Promise(resolve => setTimeout(resolve, 200))
+ releaseFirst()
+
+ expect((await Promise.all([reading, revoking]))[1]).toEqual({ ok: true, removed: 1 })
+ expect(await fresh.grants('plexus')).toEqual([])
+ expect(await fresh.run('plexus', { op: 'list', folder: id, path: '' })).toMatchObject({
+ ok: false,
+ error: 'not-granted'
+ })
+ })
+
+ it('treats an id such as `constructor` as a plain key', async () => {
+ expect(await files.addGrant('constructor', vault)).toMatchObject({ ok: true })
+ expect(await files.grants('toString')).toEqual([])
+ })
+
+ it.each(['foo.', 'con', 'NUL.txt', 'com1'])('refuses the plugin id %s, which Windows would alias', async id => {
+ expect(await files.run(id, { op: 'list', folder: 'data', path: '' })).toMatchObject({
+ ok: false,
+ error: 'invalid-plugin'
+ })
+ })
+})
diff --git a/apps/desktop/electron/plugin-files-ipc.test.ts b/apps/desktop/electron/plugin-files-ipc.test.ts
new file mode 100644
index 00000000000..048b82362b6
--- /dev/null
+++ b/apps/desktop/electron/plugin-files-ipc.test.ts
@@ -0,0 +1,106 @@
+/**
+ * A folder grant is minted only by the native picker main opens itself: the
+ * renderer names the plugin and the picker labels, never a path.
+ */
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { registerPluginFilesIpc } from './plugin-files-ipc'
+
+const scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-plugin-files-ipc-')))
+const hermesHome = path.join(scratch, '.hermes')
+const vault = path.join(scratch, 'Vault')
+fs.mkdirSync(hermesHome)
+fs.mkdirSync(vault)
+fs.writeFileSync(path.join(vault, 'note.md'), 'hello')
+
+const handlers = new Map<string, (...args: unknown[]) => Promise<unknown>>()
+const showOpenDialog = vi.fn()
+const broadcastChange = vi.fn()
+const window = { id: 1 }
+
+registerPluginFilesIpc({
+ ipcMain: { handle: (channel: string, handler: never) => handlers.set(channel, handler) } as never,
+ dialog: { showOpenDialog } as never,
+ windowFor: () => window as never,
+ broadcastChange,
+ userDataDir: () => path.join(scratch, 'userData'),
+ hermesHomes: () => [hermesHome],
+ trashItem: async () => undefined
+})
+
+const call = (channel: string, ...args: unknown[]) => handlers.get(channel)!({ sender: {} }, ...args)
+
+afterAll(() => fs.rmSync(scratch, { recursive: true, force: true }))
+
+beforeEach(() => broadcastChange.mockClear())
+
+describe('hermes:pluginFiles:request', () => {
+ it('a cancelled picker grants nothing', async () => {
+ showOpenDialog.mockResolvedValueOnce({ canceled: true, filePaths: [] })
+
+ expect(await call('hermes:pluginFiles:request', 'plexus', { title: 'Choose a folder for Plexus' })).toEqual({
+ ok: true,
+ folder: null
+ })
+ expect(showOpenDialog).toHaveBeenLastCalledWith(
+ window,
+ expect.objectContaining({ properties: ['openDirectory', 'createDirectory'], title: 'Choose a folder for Plexus' })
+ )
+ expect(await call('hermes:pluginFiles:grants', 'plexus')).toEqual([])
+ })
+
+ it('the Hermes home is refused even when the user picks it', async () => {
+ showOpenDialog.mockResolvedValueOnce({ canceled: false, filePaths: [hermesHome] })
+
+ expect(await call('hermes:pluginFiles:request', 'plexus')).toMatchObject({ ok: false, error: 'protected' })
+ expect(await call('hermes:pluginFiles:grants', 'plexus')).toEqual([])
+ })
+
+ it('the picked folder becomes a grant the plugin can read through, until revoked', async () => {
+ showOpenDialog.mockResolvedValueOnce({ canceled: false, filePaths: [vault] })
+
+ const granted = (await call('hermes:pluginFiles:request', 'plexus')) as { folder: { id: string; path: string } }
+
+ expect(granted.folder.path).toBe(vault)
+ expect(
+ await call('hermes:pluginFiles:op', 'plexus', { op: 'readText', folder: granted.folder.id, path: 'note.md' })
+ ).toMatchObject({ ok: true, text: 'hello' })
+
+ await call('hermes:pluginFiles:revoke', 'plexus', granted.folder.id)
+
+ expect(
+ await call('hermes:pluginFiles:op', 'plexus', { op: 'readText', folder: granted.folder.id, path: 'note.md' })
+ ).toMatchObject({ ok: false, error: 'not-granted' })
+ })
+
+ it('a refused or cancelled pick tells no window anything', async () => {
+ showOpenDialog.mockResolvedValueOnce({ canceled: true, filePaths: [] })
+ await call('hermes:pluginFiles:request', 'plexus')
+ showOpenDialog.mockResolvedValueOnce({ canceled: false, filePaths: [hermesHome] })
+ await call('hermes:pluginFiles:request', 'plexus')
+
+ expect(broadcastChange).not.toHaveBeenCalled()
+ })
+})
+
+describe('every window hears about grant changes', () => {
+ it('a grant and a revoke each broadcast the plugin id; a revoke of nothing does not', async () => {
+ showOpenDialog.mockResolvedValueOnce({ canceled: false, filePaths: [vault] })
+ const granted = (await call('hermes:pluginFiles:request', 'plexus')) as { folder: { id: string } }
+
+ expect(broadcastChange).toHaveBeenCalledTimes(1)
+ expect(broadcastChange).toHaveBeenLastCalledWith({ pluginId: 'plexus' })
+
+ await call('hermes:pluginFiles:revoke', 'plexus', granted.folder.id)
+
+ expect(broadcastChange).toHaveBeenCalledTimes(2)
+
+ await call('hermes:pluginFiles:revoke', 'plexus', granted.folder.id)
+
+ expect(broadcastChange).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/apps/desktop/electron/plugin-files-ipc.ts b/apps/desktop/electron/plugin-files-ipc.ts
new file mode 100644
index 00000000000..b88dca270e8
--- /dev/null
+++ b/apps/desktop/electron/plugin-files-ipc.ts
@@ -0,0 +1,80 @@
+// IPC for the plugin SDK's folder-scoped file door (`ctx.files`). The only way
+// a folder grant is ever minted is `hermes:pluginFiles:request`: main opens
+// the native folder picker itself, attached to the window that asked, and
+// grants exactly what the user picked. Every file operation goes through
+// plugin-files.ts, which re-checks the grant and the path on each call.
+
+import path from 'node:path'
+
+import type { BrowserWindow, Dialog, IpcMain, IpcMainInvokeEvent } from 'electron'
+
+import { createPluginFiles, type PluginFiles, type PluginFilesDeps } from './plugin-files'
+
+const LABEL_MAX = 200
+
+interface PickerLabels {
+ buttonLabel?: unknown
+ title?: unknown
+}
+
+export interface PluginFilesIpcDeps extends Omit<PluginFilesDeps, 'protectedRoots'> {
+ ipcMain: Pick<IpcMain, 'handle'>
+ dialog: Pick<Dialog, 'showOpenDialog'>
+ windowFor: (event: IpcMainInvokeEvent) => BrowserWindow | null
+ /** Tell every app window a plugin's grants changed (Folder access lists). */
+ broadcastChange: (change: { pluginId: string }) => void
+ /** The resolved HERMES_HOME plus the platform-default homes it may differ from. */
+ hermesHomes: () => string[]
+}
+
+const label = (value: unknown, fallback: string) =>
+ typeof value === 'string' && value.trim() ? value.trim().slice(0, LABEL_MAX) : fallback
+
+export function registerPluginFilesIpc(deps: PluginFilesIpcDeps): PluginFiles {
+ const files = createPluginFiles({ ...deps, protectedRoots: deps.hermesHomes })
+
+ deps.ipcMain.handle(
+ 'hermes:pluginFiles:request',
+ async (event: IpcMainInvokeEvent, pluginId: unknown, labels: PickerLabels = {}) => {
+ const window = deps.windowFor(event)
+
+ const options = {
+ buttonLabel: label(labels?.buttonLabel, 'Allow access'),
+ properties: ['openDirectory', 'createDirectory'] as Array<'createDirectory' | 'openDirectory'>,
+ title: label(labels?.title, 'Choose a folder')
+ }
+
+ const picked = window ? await deps.dialog.showOpenDialog(window, options) : await deps.dialog.showOpenDialog(options)
+
+ if (picked.canceled || !picked.filePaths[0]) {
+ return { ok: true, folder: null }
+ }
+
+ const granted = await files.addGrant(pluginId, path.resolve(picked.filePaths[0]))
+
+ if (granted.ok) {
+ deps.broadcastChange({ pluginId: String(pluginId) })
+ }
+
+ return granted
+ }
+ )
+
+ deps.ipcMain.handle('hermes:pluginFiles:grants', async (_event, pluginId: unknown) => files.grants(pluginId))
+
+ deps.ipcMain.handle('hermes:pluginFiles:revoke', async (_event, pluginId: unknown, folderId?: unknown) => {
+ const revoked = await files.revoke(pluginId, folderId)
+
+ if (revoked.removed) {
+ deps.broadcastChange({ pluginId: String(pluginId) })
+ }
+
+ return revoked
+ })
+
+ deps.ipcMain.handle('hermes:pluginFiles:op', async (_event, pluginId: unknown, request) =>
+ files.run(pluginId, request)
+ )
+
+ return files
+}
diff --git a/apps/desktop/electron/plugin-files-ops.ts b/apps/desktop/electron/plugin-files-ops.ts
new file mode 100644
index 00000000000..107db16a215
--- /dev/null
+++ b/apps/desktop/electron/plugin-files-ops.ts
@@ -0,0 +1,470 @@
+// The operations behind `ctx.files` (plugin-files.ts owns grants and path
+// resolution). Each op gets a target already resolved inside its folder and
+// re-applies the per-op rules: size caps, sensitive names, no op on the folder
+// itself, regular files only, O_EXCL creation. Reads and writes go through a
+// handle whose identity (dev/ino) must match the file that was checked, so a
+// swap between the check and the open is refused rather than followed.
+
+import fs from 'node:fs'
+import path from 'node:path'
+
+import { sensitiveFileBlockReason } from './hardening'
+import type { PluginFilesErrorCode, PluginFilesFailure, PluginFilesRequest, PluginFilesResult } from './plugin-files'
+
+const TEXT_MAX_BYTES = 4 * 1024 * 1024
+const DATA_URL_MAX_BYTES = 16 * 1024 * 1024
+const LIST_MAX_ENTRIES = 10_000
+const READ_CHUNK_BYTES = 1024 * 1024
+// Folders whose contents are keys; renaming one away from its name would put
+// those keys out of reach of the name-based sensitive-file rules.
+const SENSITIVE_DIRS = new Set(['.aws', '.gnupg', '.ssh'])
+// Non-blocking so a FIFO or device that slipped in cannot park a main-process
+// worker; no-follow so a link swapped in for an existing file is refused.
+const READ_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0) | (fs.constants.O_NOFOLLOW ?? 0)
+const UPDATE_FLAGS = fs.constants.O_RDWR | (fs.constants.O_NONBLOCK ?? 0) | (fs.constants.O_NOFOLLOW ?? 0)
+
+const IMAGE_MIME: Record<string, string> = {
+ '.avif': 'image/avif',
+ '.bmp': 'image/bmp',
+ '.gif': 'image/gif',
+ '.ico': 'image/x-icon',
+ '.jpeg': 'image/jpeg',
+ '.jpg': 'image/jpeg',
+ '.png': 'image/png',
+ '.svg': 'image/svg+xml',
+ '.webp': 'image/webp'
+}
+
+export const fail = (error: PluginFilesErrorCode, message: string): PluginFilesFailure => ({ ok: false, error, message })
+
+export class Refusal extends Error {
+ constructor(readonly failure: PluginFilesFailure) {
+ super(failure.message)
+ }
+}
+
+export const refuse = (error: PluginFilesErrorCode, message: string): never => {
+ throw new Refusal(fail(error, message))
+}
+
+export const errnoCode = (error: unknown): string | undefined =>
+ error && typeof error === 'object' && 'code' in error ? String((error as { code?: unknown }).code) : undefined
+
+export async function lstatOrNull(target: string): Promise<fs.Stats | null> {
+ try {
+ return await fs.promises.lstat(target)
+ } catch (error) {
+ if (errnoCode(error) === 'ENOENT') {
+ return null
+ }
+
+ throw error
+ }
+}
+
+export async function realpathOrNull(target: string): Promise<null | string> {
+ try {
+ return await fs.promises.realpath(target)
+ } catch (error) {
+ const code = errnoCode(error)
+
+ if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP') {
+ return null
+ }
+
+ throw error
+ }
+}
+
+// Default-ignorable code points (zero-width, bidi marks, BOM, soft hyphen,
+// variation selectors), which HFS+ skips when it compares names.
+const IGNORABLE_RANGES: [number, number][] = [
+ [0xad, 0xad],
+ [0x34f, 0x34f],
+ [0x115f, 0x1160],
+ [0x17b4, 0x17b5],
+ [0x180b, 0x180f],
+ [0x200b, 0x200f],
+ [0x202a, 0x202e],
+ [0x2060, 0x206f],
+ [0x3164, 0x3164],
+ [0xfe00, 0xfe0f],
+ [0xfeff, 0xfeff],
+ [0xffa0, 0xffa0]
+]
+
+const ignorable = (char: string) => {
+ const code = char.codePointAt(0) ?? 0
+
+ return IGNORABLE_RANGES.some(([low, high]) => code >= low && code <= high)
+}
+
+// The app's sensitive-file rules, checked on the name as given and as macOS
+// and Windows may match it (Unicode case folding: `id_rſa` opens `id_rsa`
+// there; HFS+ also ignores zero-width characters).
+export function sensitiveReason(target: string): null | string {
+ const folded = [...target.normalize('NFKC')]
+ .filter(char => !ignorable(char))
+ .join('')
+ .toLowerCase()
+
+ const reason = sensitiveFileBlockReason(target) ?? sensitiveFileBlockReason(folded)
+
+ if (reason) {
+ return reason
+ }
+
+ return SENSITIVE_DIRS.has(path.basename(folded)) ? 'That folder holds keys and cannot be used by a plugin.' : null
+}
+
+export const refuseSensitive = (...targets: string[]) => {
+ for (const target of targets) {
+ const reason = sensitiveReason(target)
+
+ if (reason) {
+ refuse('sensitive-file', reason)
+ }
+ }
+}
+
+const sameFile = (a: fs.Stats, b: fs.Stats) => a.dev === b.dev && a.ino === b.ino
+
+// Only a plain, singly-linked file: a FIFO or device has no size to cap, and a
+// hard link may be a second name for a file anywhere on the volume.
+function refuseNonPlain(stat: fs.Stats) {
+ if (!stat.isFile()) {
+ refuse('not-a-file', 'That path is not a regular file.')
+ }
+
+ if (stat.nlink > 1) {
+ refuse('protected', 'That file is hard-linked elsewhere, so the app cannot tell what it belongs to.')
+ }
+}
+
+// The opened file must be the one that was checked AND still sit at the
+// checked path inside the folder: a parent folder swapped for a link after
+// `resolve` makes the same path open a file elsewhere.
+async function refuseMoved(resolved: Resolved, opened: fs.Stats) {
+ const real = await realpathOrNull(resolved.target)
+ const now = real === resolved.target ? await lstatOrNull(real) : null
+
+ if (!sameFile(opened, resolved.stat!) || !now || !sameFile(now, opened)) {
+ refuse('outside-folder', 'The file changed while it was being opened.')
+ }
+}
+
+// Rename, trash and list act on paths (Node has no dirfd-relative rename,
+// unlink or readdir), so each re-checks right before (and list and rename
+// right after) that the entry is still the checked one in the checked folder.
+async function refuseChanged(resolved: Resolved) {
+ const parent = resolved.parent === null ? null : await realpathOrNull(resolved.parent)
+ const real = await realpathOrNull(resolved.entry)
+ const now = real ? await lstatOrNull(real) : null
+
+ if (parent !== resolved.parent || real !== resolved.target || !now || !sameFile(now, resolved.stat!)) {
+ refuse('outside-folder', 'The folder changed while it was being used.')
+ }
+}
+
+// Move `from` back to `to` only if nothing is at `to`: a file through a hard
+// link plus unlink (the link refuses an existing name), a folder by rename
+// after checking the name is free.
+async function restoreWithoutOverwrite(from: string, to: string): Promise<boolean> {
+ const moved = await lstatOrNull(from)
+
+ if (!moved || (await lstatOrNull(to))) {
+ return false
+ }
+
+ try {
+ if (moved.isDirectory()) {
+ await fs.promises.rename(from, to)
+ } else {
+ await fs.promises.link(from, to)
+ await fs.promises.unlink(from)
+ }
+
+ return true
+ } catch {
+ return false
+ }
+}
+
+// Read at most `maxBytes` through a handle that must still be the checked
+// file. The cap counts bytes read, not the size stat reported (0 for a pseudo
+// file), so a file is refused past the cap whatever it claims.
+async function readChecked(resolved: Resolved, maxBytes: number): Promise<Buffer> {
+ const handle = await fs.promises.open(resolved.target, READ_FLAGS)
+
+ try {
+ const opened = await handle.stat()
+ await refuseMoved(resolved, opened)
+ refuseNonPlain(opened)
+ const chunks: Buffer[] = []
+ let total = 0
+
+ for (;;) {
+ const chunk = Buffer.alloc(Math.min(READ_CHUNK_BYTES, maxBytes + 1 - total))
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, total)
+
+ if (bytesRead === 0) {
+ return Buffer.concat(chunks, total)
+ }
+
+ chunks.push(chunk.subarray(0, bytesRead))
+ total += bytesRead
+
+ if (total > maxBytes) {
+ return refuse('too-large', `File is larger than ${Math.round(maxBytes / (1024 * 1024))} MiB.`)
+ }
+ }
+ } finally {
+ await handle.close()
+ }
+}
+
+// Write `text` to the checked target: an existing file through a no-follow
+// handle that must be the checked file (and is only truncated after that),
+// a new one created O_EXCL and then confirmed to sit where it was checked.
+async function writeChecked(resolved: Resolved, text: string) {
+ if (resolved.stat) {
+ refuseNonPlain(resolved.stat)
+ const handle = await fs.promises.open(resolved.target, UPDATE_FLAGS)
+
+ try {
+ const opened = await handle.stat()
+ await refuseMoved(resolved, opened)
+ refuseNonPlain(opened)
+ await handle.truncate(0)
+ await handle.writeFile(text, 'utf8')
+ } finally {
+ await handle.close()
+ }
+
+ return
+ }
+
+ const handle = await fs.promises.open(resolved.entry, 'wx')
+
+ try {
+ const created = await handle.stat()
+ const real = await realpathOrNull(resolved.entry)
+ const landed = real ? await lstatOrNull(real) : null
+
+ if (real !== resolved.entry || !landed || !sameFile(landed, created)) {
+ if (landed && sameFile(landed, created)) {
+ await fs.promises.unlink(real!)
+ }
+
+ refuse('outside-folder', 'The folder changed while the file was being created.')
+ }
+
+ await handle.writeFile(text, 'utf8')
+ } finally {
+ await handle.close()
+ }
+}
+
+function mimeFor(target: string): string {
+ return IMAGE_MIME[path.extname(target).toLowerCase()] ?? 'application/octet-stream'
+}
+
+const toRel = (parts: string[]) => parts.join('/')
+
+export interface Resolved {
+ /** The folder's realpath. */
+ root: string
+ parts: string[]
+ /** Realpath of the target's parent (null for the folder itself). */
+ parent: null | string
+ /** The entry as named (in the real parent), not following a final link. */
+ entry: string
+ /** What reads/writes act on: the entry's realpath (inside the folder). */
+ target: string
+ /** `lstat` of `target` (null when the entry does not exist yet). */
+ stat: fs.Stats | null
+}
+
+export interface PluginFileOpsDeps {
+ resolve: (pluginId: string, folder: unknown, rel: unknown) => Promise<Resolved>
+ inside: (child: string, parent: string) => boolean
+ segments: (raw: unknown) => string[]
+ trashItem: (target: string) => Promise<void>
+}
+
+type PluginFileOp = (pluginId: string, req: any) => Promise<PluginFilesResult>
+
+export function createPluginFileOps({
+ resolve,
+ inside,
+ segments,
+ trashItem
+}: PluginFileOpsDeps): Record<PluginFilesRequest['op'], PluginFileOp> {
+ const requireFile = (resolved: Resolved, maxBytes: number) => {
+ if (!resolved.stat) {
+ refuse('not-found', 'No such file.')
+ }
+
+ if (resolved.stat!.isDirectory()) {
+ refuse('is-directory', 'That path is a folder.')
+ }
+
+ refuseNonPlain(resolved.stat!)
+
+ if (resolved.stat!.size > maxBytes) {
+ refuse('too-large', `File is larger than ${Math.round(maxBytes / (1024 * 1024))} MiB.`)
+ }
+
+ refuseSensitive(resolved.entry, resolved.target)
+ }
+
+ const requireChild = (resolved: Resolved) => {
+ if (!resolved.parent) {
+ refuse('invalid-path', 'This operation needs a path inside the folder, not the folder itself.')
+ }
+ }
+
+ return {
+ async list(pluginId, req) {
+ const resolved = await resolve(pluginId, req.folder, req.path)
+
+ if (!resolved.stat?.isDirectory()) {
+ return fail(resolved.stat ? 'not-a-directory' : 'not-found', 'That path is not a folder.')
+ }
+
+ await refuseChanged(resolved)
+ const dirents = await fs.promises.readdir(resolved.target, { withFileTypes: true })
+ await refuseChanged(resolved)
+ const entries: { name: string; path: string; isDirectory: boolean }[] = []
+
+ for (const dirent of dirents.slice(0, LIST_MAX_ENTRIES)) {
+ const full = path.join(resolved.target, dirent.name)
+ let isDirectory = dirent.isDirectory()
+
+ if (dirent.isSymbolicLink()) {
+ const real = await realpathOrNull(full)
+
+ if (!real || !inside(real, resolved.root)) {
+ continue
+ }
+
+ isDirectory = (await fs.promises.stat(real)).isDirectory()
+ }
+
+ entries.push({ name: dirent.name, path: toRel([...resolved.parts, dirent.name]), isDirectory })
+ }
+
+ return { ok: true, entries, truncated: dirents.length > LIST_MAX_ENTRIES }
+ },
+
+ async stat(pluginId, req) {
+ const { stat } = await resolve(pluginId, req.folder, req.path)
+
+ return stat
+ ? { ok: true, exists: true, isDirectory: stat.isDirectory(), size: stat.size, mtimeMs: stat.mtimeMs }
+ : { ok: true, exists: false }
+ },
+
+ async readText(pluginId, req) {
+ const resolved = await resolve(pluginId, req.folder, req.path)
+ requireFile(resolved, TEXT_MAX_BYTES)
+ const data = await readChecked(resolved, TEXT_MAX_BYTES)
+
+ if (data.subarray(0, 8000).includes(0)) {
+ return fail('binary', 'That file is binary; read it as a data URL.')
+ }
+
+ return { ok: true, text: data.toString('utf8'), size: data.length, mtimeMs: resolved.stat!.mtimeMs }
+ },
+
+ async readDataUrl(pluginId, req) {
+ const resolved = await resolve(pluginId, req.folder, req.path)
+ requireFile(resolved, DATA_URL_MAX_BYTES)
+ const data = await readChecked(resolved, DATA_URL_MAX_BYTES)
+
+ return { ok: true, url: `data:${mimeFor(resolved.target)};base64,${data.toString('base64')}` }
+ },
+
+ async writeText(pluginId, req) {
+ const text = typeof req.text === 'string' ? req.text : ''
+
+ if (Buffer.byteLength(text, 'utf8') > TEXT_MAX_BYTES) {
+ return fail('too-large', 'Text is larger than 4 MiB.')
+ }
+
+ const resolved = await resolve(pluginId, req.folder, req.path)
+ requireChild(resolved)
+
+ if (resolved.stat?.isDirectory()) {
+ return fail('is-directory', 'That path is a folder.')
+ }
+
+ if (resolved.stat && req.exclusive) {
+ return fail('exists', 'A file with that name already exists.')
+ }
+
+ refuseSensitive(resolved.entry, resolved.target)
+ await writeChecked(resolved, text)
+ const stat = await fs.promises.stat(resolved.target)
+
+ return { ok: true, path: toRel(resolved.parts), size: stat.size, mtimeMs: stat.mtimeMs }
+ },
+
+ async rename(pluginId, req) {
+ const name = typeof req.name === 'string' ? req.name.trim() : ''
+
+ if (segments(name).length !== 1 || /[\\/]/.test(name) || name === '.') {
+ return fail('invalid-path', 'A new name is one plain file or folder name.')
+ }
+
+ const resolved = await resolve(pluginId, req.folder, req.path)
+ requireChild(resolved)
+
+ if (!resolved.stat) {
+ return fail('not-found', 'No such file or folder.')
+ }
+
+ const destination = path.join(resolved.parent!, name)
+ refuseSensitive(resolved.entry, resolved.target, destination)
+
+ if (await lstatOrNull(destination)) {
+ return fail('exists', `"${name}" already exists.`)
+ }
+
+ await refuseChanged(resolved)
+ await fs.promises.rename(resolved.entry, destination)
+
+ // If the folder was swapped in the last instant, put the moved entry
+ // back, never over a file that has taken its old name meanwhile.
+ const landedIn = await realpathOrNull(path.dirname(destination))
+ const landed = await fs.promises.stat(destination).catch(() => null)
+
+ if (landedIn !== resolved.parent || !landed || !sameFile(landed, resolved.stat!)) {
+ const undone = await restoreWithoutOverwrite(destination, resolved.entry)
+ refuse(
+ 'outside-folder',
+ undone
+ ? 'The folder changed during the rename, so it was undone.'
+ : 'The folder changed during the rename and it could not be undone safely.'
+ )
+ }
+
+ return { ok: true, path: toRel([...resolved.parts.slice(0, -1), name]) }
+ },
+
+ async trash(pluginId, req) {
+ const resolved = await resolve(pluginId, req.folder, req.path)
+ requireChild(resolved)
+
+ if (!resolved.stat) {
+ return fail('not-found', 'No such file or folder.')
+ }
+
+ refuseSensitive(resolved.entry, resolved.target)
+ await refuseChanged(resolved)
+ await trashItem(resolved.entry)
+
+ return { ok: true }
+ }
+ }
+}
diff --git a/apps/desktop/electron/plugin-files-spellings.test.ts b/apps/desktop/electron/plugin-files-spellings.test.ts
new file mode 100644
index 00000000000..53703e62e31
--- /dev/null
+++ b/apps/desktop/electron/plugin-files-spellings.test.ts
@@ -0,0 +1,243 @@
+/**
+ * `ctx.files` refusals for a second spelling of a path: case on a
+ * case-sensitive macOS volume, Unicode case folding, macOS named forks, WSL
+ * shares, loopback admin shares, and kernel pseudo-filesystems mounted
+ * somewhere a grant can reach.
+ */
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { createPluginFiles, type PluginFiles } from './plugin-files'
+import { loopbackShare, onPseudoFilesystem, overlapsByIdentity, wslProtectedPath } from './plugin-files-guards'
+
+const posix = process.platform !== 'win32'
+
+let scratch: string
+let userData: string
+let hermesHome: string
+let vault: string
+
+const make = (platform?: NodeJS.Platform): PluginFiles =>
+ createPluginFiles({
+ userDataDir: () => userData,
+ protectedRoots: () => [hermesHome],
+ trashItem: target => fs.promises.rm(target, { recursive: true }),
+ platform
+ })
+
+beforeEach(() => {
+ scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-plugin-files-spell-')))
+ userData = path.join(scratch, 'userData')
+ hermesHome = path.join(scratch, 'home', '.hermes')
+ vault = path.join(scratch, 'home', 'Vault')
+ fs.mkdirSync(userData, { recursive: true })
+ fs.mkdirSync(hermesHome, { recursive: true })
+ fs.mkdirSync(vault, { recursive: true })
+ fs.writeFileSync(path.join(vault, 'a.md'), '# A\n')
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ fs.rmSync(scratch, { recursive: true, force: true })
+})
+
+async function grant(files: PluginFiles, folder = vault): Promise<string> {
+ const granted = await files.addGrant('plexus', folder)
+
+ expect(granted.ok).toBe(true)
+
+ return (granted as { folder: { id: string } }).folder.id
+}
+
+// Linux volumes are case-sensitive, so they stand in for a case-sensitive
+// macOS volume here: `Vault` and `vault` are two folders.
+describe('case on a case-sensitive macOS volume', () => {
+ it.runIf(posix)('a link from the granted Vault into a sibling vault is outside the folder', async () => {
+ const files = make('darwin')
+ const id = await grant(files)
+ const sibling = path.join(scratch, 'home', 'vault')
+ fs.mkdirSync(sibling)
+ fs.writeFileSync(path.join(sibling, 'secret.txt'), 'not granted')
+ fs.symlinkSync(path.join(sibling, 'secret.txt'), path.join(vault, 'link.txt'))
+
+ const read = await files.run('plexus', { op: 'readText', folder: id, path: 'link.txt' })
+
+ expect(read).toMatchObject({ ok: false, error: 'outside-folder' })
+ expect(JSON.stringify(read)).not.toContain('not granted')
+ })
+
+ it.runIf(posix)('a granted Vault replaced by a differently-cased vault must be granted again', async () => {
+ const files = make('darwin')
+ const id = await grant(files)
+ fs.renameSync(vault, path.join(scratch, 'home', 'vault'))
+ fs.symlinkSync(path.join(scratch, 'home', 'vault'), vault)
+
+ expect(await files.run('plexus', { op: 'list', folder: id, path: '' })).toMatchObject({
+ ok: false,
+ error: 'folder-changed'
+ })
+ })
+
+ it.runIf(posix)('a differently-cased spelling of the Hermes home still cannot be granted', async () => {
+ const lookalike = path.join(scratch, 'home', '.HERMES')
+ fs.mkdirSync(lookalike)
+
+ expect(await make('darwin').addGrant('plexus', lookalike)).toMatchObject({ ok: false, error: 'protected' })
+ })
+})
+
+// macOS and Windows match names with Unicode case folding (`ſ` is `s`), so a
+// name that folds onto a key file may open that key file there.
+describe('sensitive names after Unicode folding', () => {
+ // HFS+ also ignores zero-width and other default-ignorable code points.
+ it.each(['id_r\u017fa', '.ENV', '\uff0eenv', '.env.LOCAL', '.e\u200dnv', 'id_\u200brsa', '.np\ufeffmrc'])(
+ 'refuses reading or writing %s',
+ async name => {
+ const files = make()
+ const id = await grant(files)
+ fs.writeFileSync(path.join(vault, name), 'SECRET=1\n')
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: name })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ fs.mkdirSync(path.join(vault, 'fresh'))
+
+ expect(await files.run('plexus', { op: 'writeText', folder: id, path: `fresh/${name}`, text: 'x' })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ expect(fs.existsSync(path.join(vault, 'fresh', name))).toBe(false)
+ }
+ )
+
+ it('refuses a folded key folder as a path and as a rename target', async () => {
+ const files = make()
+ const id = await grant(files)
+ fs.mkdirSync(path.join(vault, '.\u017f\u017fh'))
+ fs.writeFileSync(path.join(vault, '.\u017f\u017fh', 'config'), 'Host x\n')
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: '.\u017f\u017fh/config' })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: 'a.md', name: '.ENV' })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ })
+})
+
+describe('macOS named forks', () => {
+ it.each(['.env/..namedfork/data', 'a.md/..namedfork/rsrc', 'x/..NamedFork/data'])('refuses %s', async rel => {
+ const files = make()
+ const id = await grant(files)
+ fs.writeFileSync(path.join(vault, '.env'), 'SECRET=1\n')
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: rel })).toMatchObject({
+ ok: false,
+ error: 'invalid-path'
+ })
+ })
+})
+
+describe('Windows names that open something else', () => {
+ it.each(['CON', 'nul.txt', 'COM1', 'lpt\u00b9', 'CONIN$', 'conout$.log', 'CLOCK$', 'a.md:secret', '.env.', '.env ', 'notes\\..\\..'])(
+ 'refuses the segment %s',
+ async rel => {
+ const files = make('win32')
+ const id = await grant(files)
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: rel })).toMatchObject({
+ ok: false,
+ error: 'invalid-path'
+ })
+ }
+ )
+})
+
+describe('Windows second paths to this machine', () => {
+ it.each([
+ ['\\\\wsl.localhost\\Ubuntu', true],
+ ['\\\\wsl$\\Ubuntu\\home', true],
+ ['\\\\wsl.localhost\\Ubuntu\\home\\me', true],
+ ['\\\\wsl.localhost\\Ubuntu\\root', true],
+ ['\\\\wsl.localhost\\Ubuntu\\home\\me\\.hermes\\profiles', true],
+ ['\\\\WSL.LOCALHOST\\Debian\\HOME\\me\\.Hermes', true],
+ // The distro's own process environments and its view of the Windows drives.
+ ['\\\\wsl.localhost\\Ubuntu\\proc', true],
+ ['\\\\wsl$\\Ubuntu\\proc\\1\\environ', true],
+ ['\\\\wsl.localhost\\Ubuntu\\sys', true],
+ ['\\\\wsl.localhost\\Ubuntu\\dev', true],
+ ['\\\\wsl.localhost\\Ubuntu\\run\\user', true],
+ ['\\\\wsl.localhost\\Ubuntu\\mnt\\c\\Users\\me', true],
+ ['\\\\wsl.localhost\\Ubuntu\\home\\me\\Vault', false],
+ ['\\\\server\\share\\home', false],
+ ['C:\\Users\\me\\Vault', false]
+ ])('treats the WSL path %s as protected: %s', (candidate, exposed) => {
+ expect(wslProtectedPath(candidate)).toBe(exposed)
+ })
+
+ it.each([
+ ['\\\\localhost\\C$\\Users\\me', true],
+ ['\\\\LOCALHOST\\share', true],
+ ['\\\\127.0.0.1\\c$\\Users', true],
+ ['\\\\127.1.2.3\\c$', true],
+ ['\\\\[::1]\\c$', true],
+ ['\\\\0--1.ipv6-literal.net\\c$', true],
+ ['\\\\?\\UNC\\localhost\\c$\\Users', true],
+ ['\\\\.\\C:\\Users', true],
+ ['\\\\?\\C:\\Users', true],
+ [`\\\\${os.hostname()}\\c$`, true],
+ ['\\\\fileserver\\team\\notes', false],
+ ['C:\\Users\\me\\Vault', false]
+ ])('treats %s as a second path to this machine: %s', (candidate, loopback) => {
+ expect(loopbackShare(candidate)).toBe(loopback)
+ })
+})
+
+describe('kernel pseudo-filesystems wherever they are mounted', () => {
+ it.runIf(process.platform === 'linux')('recognizes procfs and sysfs by filesystem type', async () => {
+ expect(await onPseudoFilesystem('/proc/self/environ')).toBe(true)
+ expect(await onPseudoFilesystem('/sys/kernel')).toBe(true)
+ expect(await onPseudoFilesystem(vault)).toBe(false)
+ })
+
+ // Stands in for a procfs mounted inside a granted folder (a container's
+ // `/host/proc`, a chroot's `proc`): its files are regular and singly linked.
+ it.runIf(process.platform === 'linux')('refuses a file whose filesystem is procfs', async () => {
+ const files = make()
+ const id = await grant(files)
+ const environ = path.join(vault, 'environ')
+ fs.writeFileSync(environ, 'OPENAI_API_KEY=sk-live\n')
+ const original = fs.promises.statfs.bind(fs.promises)
+
+ vi.spyOn(fs.promises, 'statfs').mockImplementation((async (target: fs.PathLike, options?: never) => {
+ const real = await original(target, options)
+
+ return String(target) === environ ? { ...real, type: 0x9fa0 } : real
+ }) as never)
+
+ for (const op of ['readText', 'readDataUrl', 'stat'] as const) {
+ expect(await files.run('plexus', { op, folder: id, path: 'environ' })).toMatchObject({ ok: false, error: 'protected' })
+ }
+
+ expect(await files.run('plexus', { op: 'writeText', folder: id, path: 'environ', text: 'x' })).toMatchObject({
+ ok: false,
+ error: 'protected'
+ })
+ })
+})
+
+describe('Hermes data reached by another spelling', () => {
+ it('compares folders by filesystem identity', async () => {
+ expect(await overlapsByIdentity(hermesHome, [hermesHome])).toBe(true)
+ expect(await overlapsByIdentity(path.join(scratch, 'home'), [hermesHome])).toBe(true)
+ fs.mkdirSync(path.join(hermesHome, 'skills'))
+ expect(await overlapsByIdentity(path.join(hermesHome, 'skills'), [hermesHome])).toBe(true)
+ expect(await overlapsByIdentity(vault, [hermesHome])).toBe(false)
+ })
+})
diff --git a/apps/desktop/electron/plugin-files.test.ts b/apps/desktop/electron/plugin-files.test.ts
new file mode 100644
index 00000000000..72c4154c29d
--- /dev/null
+++ b/apps/desktop/electron/plugin-files.test.ts
@@ -0,0 +1,418 @@
+/**
+ * The folder-scoped plugin file door (`ctx.files`). Every refusal here is the
+ * main process's own: the renderer (and the plugin in it) only names a folder
+ * handle and a relative path, and this module decides what that may reach.
+ */
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { createPluginFiles, type PluginFiles } from './plugin-files'
+
+let scratch: string
+let userData: string
+let hermesHome: string
+let vault: string
+let trashed: string[]
+let files: PluginFiles
+
+const make = () =>
+ createPluginFiles({
+ userDataDir: () => userData,
+ protectedRoots: () => [hermesHome],
+ trashItem: async target => {
+ trashed.push(target)
+ await fs.promises.rm(target, { recursive: true })
+ }
+ })
+
+beforeEach(() => {
+ scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-plugin-files-')))
+ userData = path.join(scratch, 'userData')
+ hermesHome = path.join(scratch, 'home', '.hermes')
+ vault = path.join(scratch, 'home', 'Vault')
+ fs.mkdirSync(userData, { recursive: true })
+ fs.mkdirSync(hermesHome, { recursive: true })
+ fs.writeFileSync(path.join(hermesHome, '.env'), 'OPENROUTER_API_KEY=sk-secret\n')
+ fs.writeFileSync(path.join(hermesHome, 'config.yaml'), 'model: x\n')
+ fs.mkdirSync(path.join(vault, 'notes'), { recursive: true })
+ fs.writeFileSync(path.join(vault, 'notes', 'a.md'), '# A\n')
+ trashed = []
+ files = make()
+})
+
+afterEach(() => {
+ fs.rmSync(scratch, { recursive: true, force: true })
+})
+
+async function grantVault(pluginId = 'plexus', folder = vault): Promise<string> {
+ const granted = await files.addGrant(pluginId, folder)
+
+ expect(granted.ok).toBe(true)
+
+ return (granted as { folder: { id: string } }).folder.id
+}
+
+describe('grants', () => {
+ it('persists a user-picked folder per plugin and survives a restart', async () => {
+ const id = await grantVault()
+
+ expect(await make().grants('plexus')).toEqual([expect.objectContaining({ id, name: 'Vault', path: vault })])
+ expect(await make().grants('other')).toEqual([])
+ })
+
+ it('re-picking the same folder reuses the grant', async () => {
+ const first = await grantVault()
+
+ expect(await grantVault()).toBe(first)
+ expect(await files.grants('plexus')).toHaveLength(1)
+ })
+
+ it.each([
+ ['the Hermes home', () => hermesHome],
+ ['a folder inside the Hermes home', () => path.join(hermesHome, 'skills')],
+ ['a folder that contains the Hermes home', () => path.join(scratch, 'home')],
+ ['the app data folder', () => userData],
+ ['another plugin data folder', () => path.join(userData, 'plugin-files', 'data', 'other')]
+ ])('refuses to grant %s', async (_label, folder) => {
+ fs.mkdirSync(folder(), { recursive: true })
+
+ expect(await files.addGrant('plexus', folder())).toMatchObject({ ok: false, error: 'protected' })
+ expect(await files.grants('plexus')).toEqual([])
+ })
+
+ it('refuses to grant a key folder such as ~/.ssh', async () => {
+ const ssh = path.join(scratch, 'home', '.ssh')
+ fs.mkdirSync(ssh, { recursive: true })
+
+ expect(await files.addGrant('plexus', ssh)).toMatchObject({ ok: false, error: 'protected' })
+ })
+
+ it('refuses to grant a symlink that resolves into the Hermes home', async () => {
+ const link = path.join(scratch, 'innocent')
+ fs.symlinkSync(hermesHome, link)
+
+ expect(await files.addGrant('plexus', link)).toMatchObject({ ok: false, error: 'protected' })
+ })
+
+ it('a revoked grant refuses every later operation at once', async () => {
+ const id = await grantVault()
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: 'notes/a.md' })).toMatchObject({ ok: true })
+ expect(await files.revoke('plexus', id)).toEqual({ ok: true, removed: 1 })
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: 'notes/a.md' })).toMatchObject({
+ ok: false,
+ error: 'not-granted'
+ })
+ expect(await make().grants('plexus')).toEqual([])
+ })
+
+ it("one plugin cannot use another plugin's grant id", async () => {
+ const id = await grantVault('plexus')
+
+ expect(await files.run('intruder', { op: 'list', folder: id, path: '' })).toMatchObject({
+ ok: false,
+ error: 'not-granted'
+ })
+ })
+
+ it('refuses a grant whose folder was swapped for a link into the Hermes home', async () => {
+ const id = await grantVault()
+ fs.rmSync(vault, { recursive: true })
+ fs.symlinkSync(hermesHome, vault)
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: '.env' })).toMatchObject({ ok: false })
+ expect(await files.run('plexus', { op: 'list', folder: id, path: '' })).toMatchObject({ ok: false })
+ })
+})
+
+describe('path containment', () => {
+ it.each([
+ ['parent traversal', '../.hermes/.env'],
+ ['nested traversal', 'notes/../../.hermes/.env'],
+ ['backslash traversal', 'notes\\..\\..\\.hermes\\.env'],
+ ['an absolute POSIX path', '/etc/passwd'],
+ ['an absolute path into the Hermes home', ''],
+ ['a Windows drive path', 'C:\\Users\\me\\.hermes\\.env'],
+ ['a UNC path', '\\\\server\\share\\x'],
+ ['a NUL byte', 'notes/a.md\0.png']
+ ])('refuses %s', async (label, rel) => {
+ const id = await grantVault()
+ const target = label === 'an absolute path into the Hermes home' ? path.join(hermesHome, '.env') : rel
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: target })).toMatchObject({
+ ok: false,
+ error: 'invalid-path'
+ })
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: id, path: target, text: 'pwned' })
+ ).toMatchObject({ ok: false, error: 'invalid-path' })
+ expect(fs.readFileSync(path.join(hermesHome, 'config.yaml'), 'utf8')).toBe('model: x\n')
+ })
+
+ it('refuses to read through a symlinked file that points outside the folder', async () => {
+ const id = await grantVault()
+ fs.symlinkSync(path.join(hermesHome, '.env'), path.join(vault, 'notes', 'leak.md'))
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: 'notes/leak.md' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ expect(await files.run('plexus', { op: 'readDataUrl', folder: id, path: 'notes/leak.md' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ })
+
+ it('refuses to write through a symlinked file or folder that points outside', async () => {
+ const id = await grantVault()
+ fs.symlinkSync(path.join(hermesHome, 'config.yaml'), path.join(vault, 'cfg.md'))
+ fs.symlinkSync(hermesHome, path.join(vault, 'home'))
+
+ for (const rel of ['cfg.md', 'home/config.yaml', 'home/new.md']) {
+ expect(await files.run('plexus', { op: 'writeText', folder: id, path: rel, text: 'pwned' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ }
+
+ expect(fs.readFileSync(path.join(hermesHome, 'config.yaml'), 'utf8')).toBe('model: x\n')
+ expect(fs.existsSync(path.join(hermesHome, 'new.md'))).toBe(false)
+ })
+
+ it('refuses a dangling symlink instead of creating its target', async () => {
+ const id = await grantVault()
+ const outside = path.join(scratch, 'created-outside.md')
+ fs.symlinkSync(outside, path.join(vault, 'dangling.md'))
+
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: id, path: 'dangling.md', text: 'x' })
+ ).toMatchObject({ ok: false })
+ expect(fs.existsSync(outside)).toBe(false)
+ })
+
+ it('refuses listing, renaming and trashing through a symlinked folder into the Hermes home', async () => {
+ const id = await grantVault()
+ fs.symlinkSync(hermesHome, path.join(vault, 'home'))
+
+ expect(await files.run('plexus', { op: 'list', folder: id, path: 'home' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ expect(
+ await files.run('plexus', { op: 'rename', folder: id, path: 'home/config.yaml', name: 'x.yaml' })
+ ).toMatchObject({ ok: false, error: 'outside-folder' })
+ expect(await files.run('plexus', { op: 'trash', folder: id, path: 'home/.env' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ expect(trashed).toEqual([])
+ expect(fs.existsSync(path.join(hermesHome, '.env'))).toBe(true)
+ })
+
+ it('a listing hides links that leave the folder and keeps links that stay inside', async () => {
+ const id = await grantVault()
+ fs.symlinkSync(hermesHome, path.join(vault, 'escape'))
+ fs.symlinkSync(path.join(vault, 'notes'), path.join(vault, 'alias'))
+
+ const listed = await files.run('plexus', { op: 'list', folder: id, path: '' })
+
+ expect(listed).toMatchObject({ ok: true })
+ expect((listed as unknown as { entries: { name: string }[] }).entries.map(e => e.name).sort()).toEqual(['alias', 'notes'])
+ })
+
+ it('rename keeps the item in its folder and refuses a name with a separator or traversal', async () => {
+ const id = await grantVault()
+
+ for (const name of ['../../escaped.md', 'sub/x.md', '..', '.', '']) {
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: 'notes/a.md', name })).toMatchObject({
+ ok: false,
+ error: 'invalid-path'
+ })
+ }
+
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: 'notes/a.md', name: 'b.md' })).toEqual({
+ ok: true,
+ path: 'notes/b.md'
+ })
+ expect(fs.existsSync(path.join(vault, 'notes', 'b.md'))).toBe(true)
+ })
+
+ it('never trashes or renames the granted folder itself', async () => {
+ const id = await grantVault()
+
+ expect(await files.run('plexus', { op: 'trash', folder: id, path: '' })).toMatchObject({
+ ok: false,
+ error: 'invalid-path'
+ })
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: '.', name: 'x' })).toMatchObject({
+ ok: false,
+ error: 'invalid-path'
+ })
+ expect(fs.existsSync(vault)).toBe(true)
+ })
+})
+
+describe('plugin data folder', () => {
+ it('reads and writes inside its own data folder without any grant', async () => {
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: 'data', path: 'state.json', text: '{"a":1}' })
+ ).toMatchObject({ ok: true, path: 'state.json' })
+ expect(await files.run('plexus', { op: 'readText', folder: 'data', path: 'state.json' })).toMatchObject({
+ ok: true,
+ text: '{"a":1}'
+ })
+ expect(fs.readFileSync(path.join(userData, 'plugin-files', 'data', 'plexus', 'state.json'), 'utf8')).toBe(
+ '{"a":1}'
+ )
+ })
+
+ it("cannot reach another plugin's data folder or the grants record", async () => {
+ await files.run('other', { op: 'writeText', folder: 'data', path: 'secret.json', text: 'theirs' })
+ await files.run('plexus', { op: 'writeText', folder: 'data', path: 'mine.json', text: 'mine' })
+
+ for (const rel of ['../other/secret.json', '../../grants.json']) {
+ expect(await files.run('plexus', { op: 'readText', folder: 'data', path: rel })).toMatchObject({
+ ok: false,
+ error: 'invalid-path'
+ })
+ }
+
+ fs.symlinkSync(
+ path.join(userData, 'plugin-files', 'data', 'other'),
+ path.join(userData, 'plugin-files', 'data', 'plexus', 'peek')
+ )
+
+ expect(await files.run('plexus', { op: 'readText', folder: 'data', path: 'peek/secret.json' })).toMatchObject({
+ ok: false,
+ error: 'outside-folder'
+ })
+ })
+
+ it('keeps ids that differ only in case apart on any filesystem', async () => {
+ await files.run('plexus', { op: 'writeText', folder: 'data', path: 'who.txt', text: 'lower' })
+ await files.run('Plexus', { op: 'writeText', folder: 'data', path: 'who.txt', text: 'upper' })
+
+ expect(await files.run('plexus', { op: 'readText', folder: 'data', path: 'who.txt' })).toMatchObject({
+ text: 'lower'
+ })
+ })
+
+ it.each(['../x', 'a/b', '..', '', 'x'.repeat(200)])('refuses a plugin id that is not a plain slug: %j', async id => {
+ expect(await files.run(id, { op: 'list', folder: 'data', path: '' })).toMatchObject({
+ ok: false,
+ error: 'invalid-plugin'
+ })
+ })
+})
+
+describe('caps and shapes', () => {
+ it('refuses oversized writes and reads instead of truncating', async () => {
+ const id = await grantVault()
+ const big = 'x'.repeat(4 * 1024 * 1024 + 1)
+
+ expect(await files.run('plexus', { op: 'writeText', folder: id, path: 'big.md', text: big })).toMatchObject({
+ ok: false,
+ error: 'too-large'
+ })
+ expect(fs.existsSync(path.join(vault, 'big.md'))).toBe(false)
+
+ fs.writeFileSync(path.join(vault, 'big.md'), big)
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: 'big.md' })).toMatchObject({
+ ok: false,
+ error: 'too-large'
+ })
+ })
+
+ it('reads binary files only as data URLs', async () => {
+ const id = await grantVault()
+ fs.writeFileSync(path.join(vault, 'pic.png'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 1, 2]))
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: 'pic.png' })).toMatchObject({
+ ok: false,
+ error: 'binary'
+ })
+ expect(await files.run('plexus', { op: 'readDataUrl', folder: id, path: 'pic.png' })).toEqual({
+ ok: true,
+ url: 'data:image/png;base64,iVBORwABAg=='
+ })
+ })
+
+ it('refuses sensitive files inside a granted folder', async () => {
+ const id = await grantVault()
+ fs.writeFileSync(path.join(vault, '.env'), 'TOKEN=x\n')
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: '.env' })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: id, path: 'notes/id_ed25519', text: 'k' })
+ ).toMatchObject({ ok: false, error: 'sensitive-file' })
+ expect(await files.run('plexus', { op: 'rename', folder: id, path: 'notes/a.md', name: '.env' })).toMatchObject({
+ ok: false,
+ error: 'sensitive-file'
+ })
+ })
+
+ it('an exclusive write never replaces an existing file', async () => {
+ const id = await grantVault()
+
+ expect(
+ await files.run('plexus', { op: 'writeText', folder: id, path: 'notes/a.md', text: 'new', exclusive: true })
+ ).toMatchObject({ ok: false, error: 'exists' })
+ expect(fs.readFileSync(path.join(vault, 'notes', 'a.md'), 'utf8')).toBe('# A\n')
+ })
+
+ it('answers an unknown op as a result, never a throw', async () => {
+ const id = await grantVault()
+
+ expect(await files.run('plexus', { op: 'unlink', folder: id, path: 'notes/a.md' } as never)).toMatchObject({
+ ok: false,
+ error: 'invalid-op'
+ })
+ })
+
+ it('stat reports a missing entry without failing', async () => {
+ const id = await grantVault()
+
+ expect(await files.run('plexus', { op: 'stat', folder: id, path: 'notes/missing.md' })).toEqual({
+ ok: true,
+ exists: false
+ })
+ expect(await files.run('plexus', { op: 'stat', folder: id, path: 'notes/a.md' })).toMatchObject({
+ ok: true,
+ exists: true,
+ isDirectory: false,
+ size: 4
+ })
+ })
+
+ it('trash moves only the named entry', async () => {
+ const id = await grantVault()
+
+ expect(await files.run('plexus', { op: 'trash', folder: id, path: 'notes/a.md' })).toEqual({ ok: true })
+ expect(trashed).toEqual([path.join(vault, 'notes', 'a.md')])
+ })
+})
+
+describe('protected roots', () => {
+ it('an op inside a granted folder never reaches a protected root nested under it', async () => {
+ // A grant made before HERMES_HOME moved inside it must not become a door into the new home.
+ const id = await grantVault()
+ const nestedHome = path.join(vault, 'hermes')
+ fs.mkdirSync(nestedHome)
+ fs.writeFileSync(path.join(nestedHome, 'config.yaml'), 'model: y\n')
+ const roots = vi.fn(() => [hermesHome, nestedHome])
+
+ files = createPluginFiles({ userDataDir: () => userData, protectedRoots: roots, trashItem: async () => undefined })
+
+ expect(await files.run('plexus', { op: 'readText', folder: id, path: 'hermes/config.yaml' })).toMatchObject({
+ ok: false,
+ error: 'protected'
+ })
+ })
+})
diff --git a/apps/desktop/electron/plugin-files.ts b/apps/desktop/electron/plugin-files.ts
new file mode 100644
index 00000000000..07fa3a65389
--- /dev/null
+++ b/apps/desktop/electron/plugin-files.ts
@@ -0,0 +1,421 @@
+// The folder-scoped file door behind the plugin SDK's `ctx.files`. A plugin
+// names a folder handle (`'data'` = its own data folder, or the id of a folder
+// the user granted it through the app's picker) plus a RELATIVE path; this
+// module, in the main process, decides what that may reach:
+//
+// - a relative path is split into plain segments; `..`, absolute paths, drive
+// letters, UNC paths and NUL bytes are refused, never normalized away;
+// - the parent of every target is realpath'd and must sit inside the folder's
+// realpath, and an existing target that is a symlink is followed only when
+// its realpath stays inside (a dangling link is refused, so a write can
+// never create the link's outside target);
+// - nothing may resolve into a protected root (the Hermes homes, which hold
+// config.yaml, .env, auth and every profile; the app's own data folder,
+// which holds every plugin's data folder and the grants record), and a
+// folder overlapping one in either direction (by path, by filesystem
+// identity, as a WSL home or a loopback share) can never be granted, and
+// no op reaches a kernel pseudo-filesystem (/proc, /sys, …) by path or by
+// filesystem type;
+// - reads and writes are size-capped and refused, never truncated, and the
+// app's sensitive-file rules (.env, SSH/GPG keys, .npmrc…) hold inside a
+// granted folder too; a key folder (~/.ssh, ~/.gnupg) cannot be granted.
+//
+// Grants live in `<userData>/plugin-files/grants.json`, written only here.
+// The renderer cannot mint one: `addGrant` is reached only from the native
+// folder picker the user answers (plugin-files-ipc.ts).
+//
+// This bounds what the DOOR can reach. It is not a sandbox for plugin code:
+// a renderer-realm plugin can still call the raw `window.hermesDesktop` file
+// bridge, which is why catalog admission requires the door instead.
+
+import { randomBytes } from 'node:crypto'
+import fs from 'node:fs'
+import path from 'node:path'
+
+import {
+ dataDirName,
+ loopbackShare,
+ onPseudoFilesystem,
+ overlapsByIdentity,
+ pathTools,
+ pluginKey,
+ protectedIdentityWithin,
+ realRoots,
+ systemRoots,
+ wslProtectedPath
+} from './plugin-files-guards'
+import {
+ createPluginFileOps,
+ errnoCode,
+ fail,
+ lstatOrNull,
+ realpathOrNull,
+ Refusal,
+ refuse,
+ type Resolved,
+ sensitiveReason
+} from './plugin-files-ops'
+
+export const PLUGIN_DATA_FOLDER = 'data'
+
+const GRANT_ID_RE = /^[a-f0-9]{16}$/
+
+export type PluginFilesErrorCode =
+ | 'binary'
+ | 'exists'
+ | 'folder-changed'
+ | 'folder-missing'
+ | 'invalid-op'
+ | 'invalid-path'
+ | 'invalid-plugin'
+ | 'io-error'
+ | 'is-directory'
+ | 'not-a-directory'
+ | 'not-a-file'
+ | 'not-found'
+ | 'not-granted'
+ | 'outside-folder'
+ | 'protected'
+ | 'sensitive-file'
+ | 'too-large'
+
+export interface PluginFilesFailure {
+ ok: false
+ error: PluginFilesErrorCode
+ message: string
+}
+
+export type PluginFilesResult<T extends object = object> = ({ ok: true } & T) | PluginFilesFailure
+
+export interface PluginFolderGrant {
+ id: string
+ name: string
+ path: string
+ grantedAt: string
+}
+
+export type PluginFilesRequest =
+ | { op: 'list'; folder: string; path: string }
+ | { op: 'readDataUrl'; folder: string; path: string }
+ | { op: 'readText'; folder: string; path: string }
+ | { op: 'rename'; folder: string; path: string; name: string }
+ | { op: 'stat'; folder: string; path: string }
+ | { op: 'trash'; folder: string; path: string }
+ | { op: 'writeText'; folder: string; path: string; text: string; exclusive?: boolean }
+
+export interface PluginFilesDeps {
+ /** Electron's userData dir, read lazily (main sets it before `ready`). */
+ userDataDir: () => string
+ /** Hermes homes (the resolved HERMES_HOME and the platform defaults). */
+ protectedRoots: () => string[]
+ trashItem: (target: string) => Promise<void>
+ platform?: NodeJS.Platform
+}
+
+export interface PluginFiles {
+ grants: (pluginId: unknown) => Promise<PluginFolderGrant[]>
+ addGrant: (pluginId: unknown, picked: string) => Promise<PluginFilesResult<{ folder: PluginFolderGrant }>>
+ revoke: (pluginId: unknown, folderId?: unknown) => Promise<{ ok: true; removed: number }>
+ run: (pluginId: unknown, request: PluginFilesRequest) => Promise<PluginFilesResult>
+}
+
+
+export function createPluginFiles(deps: PluginFilesDeps): PluginFiles {
+ const platform = deps.platform ?? process.platform
+ const { inside, insideLoose, same, segments } = pathTools(platform)
+ const baseDir = () => path.join(deps.userDataDir(), 'plugin-files')
+ const storeFile = () => path.join(baseDir(), 'grants.json')
+
+ type Store = Record<string, PluginFolderGrant[]>
+ let store: null | Store = null
+ let loading: null | Promise<Store> = null
+ let writes: Promise<unknown> = Promise.resolve()
+
+ // Null prototype: a plugin id such as `constructor` is just a key.
+ const fresh = (grants: unknown): Store =>
+ Object.assign(Object.create(null), grants && typeof grants === 'object' ? grants : {})
+
+ const readStore = async (): Promise<Store> => {
+ // A missing or unreadable-as-JSON record is no grants (fail closed). Any
+ // other read error is thrown, so a later write never replaces a record
+ // it could not read.
+ const raw = await fs.promises.readFile(storeFile(), 'utf8').catch(error => {
+ if (errnoCode(error) === 'ENOENT') {
+ return '{}'
+ }
+
+ throw error
+ })
+
+ try {
+ return fresh((JSON.parse(raw) as { grants?: unknown } | null)?.grants)
+ } catch {
+ return fresh(null)
+ }
+ }
+
+ // One initial read, shared; a read finishing late never replaces a record
+ // a write already published.
+ const load = async (): Promise<Store> => {
+ if (store) {
+ return store
+ }
+
+ loading ??= readStore().finally(() => {
+ loading = null
+ })
+ const read = await loading
+ store ??= read
+
+ return store
+ }
+
+ // Serialized read-modify-write on a copy, saved with tmp + rename, and only
+ // published once saved: a failed save changes nothing, now or after restart.
+ const mutate = <T>(change: (grants: Store) => T): Promise<T> => {
+ const next = writes.then(async () => {
+ const grants = fresh(structuredClone({ ...(await load()) }))
+ const result = change(grants)
+ await fs.promises.mkdir(baseDir(), { recursive: true })
+ const tmp = `${storeFile()}.${process.pid}.tmp`
+ await fs.promises.writeFile(tmp, JSON.stringify({ version: 1, grants }, null, 2), { mode: 0o600 })
+ await fs.promises.rename(tmp, storeFile())
+ store = grants
+
+ return result
+ })
+
+ writes = next.catch(() => undefined)
+
+ return next
+ }
+
+ const protectedRoots = async (): Promise<string[]> =>
+ realRoots([...deps.protectedRoots(), deps.userDataDir(), ...systemRoots(platform)])
+
+ // A second spelling of this machine's files that no realpath comparison can
+ // match: a WSL share or a loopback/device path on Windows.
+ const secondPath = (real: string) => platform === 'win32' && (wslProtectedPath(real) || loopbackShare(real))
+
+ // Kernel pseudo-filesystems by type, so one mounted anywhere is refused.
+ const refusePseudo = async (real: string) => {
+ if (platform === 'linux' && (await onPseudoFilesystem(real))) {
+ refuse('protected', 'That is a kernel filesystem and cannot be used by a plugin.')
+ }
+ }
+
+ const overlapsProtected = (real: string, roots: string[]) =>
+ roots.some(root => insideLoose(real, root) || insideLoose(root, real)) || secondPath(real)
+
+ // The folder a handle names, as a realpath, plus the protected roots an op
+ // inside it must still avoid (none for the plugin's own data folder, whose
+ // root already excludes every sibling).
+ const openFolder = async (pluginId: string, folder: unknown): Promise<{ root: string; avoid: string[] }> => {
+ const roots = await realRoots(deps.protectedRoots())
+
+ if (folder === PLUGIN_DATA_FOLDER) {
+ const dir = path.join(baseDir(), 'data', dataDirName(pluginId))
+ await fs.promises.mkdir(dir, { recursive: true })
+
+ return { root: await fs.promises.realpath(dir), avoid: roots }
+ }
+
+ const grant =
+ typeof folder === 'string' && GRANT_ID_RE.test(folder)
+ ? (await load())[pluginId]?.find(row => row.id === folder)
+ : undefined
+
+ if (!grant) {
+ return refuse('not-granted', 'This plugin has no access to that folder.')
+ }
+
+ const real = await realpathOrNull(grant.path)
+
+ if (!real) {
+ return refuse('folder-missing', 'The granted folder no longer exists.')
+ }
+
+ // A grant is to the folder the user picked, not to whatever a path later
+ // resolves to (a folder swapped for a link into another tree).
+ if (!same(real, grant.path)) {
+ return refuse('folder-changed', 'The granted folder was moved or replaced; grant it again.')
+ }
+
+ const avoid = await protectedRoots()
+
+ if (overlapsProtected(real, avoid)) {
+ return refuse('protected', 'That folder overlaps Hermes data and cannot be used by a plugin.')
+ }
+
+ await refusePseudo(real)
+
+ return { root: real, avoid }
+ }
+
+ const resolve = async (pluginId: string, folder: unknown, rel: unknown): Promise<Resolved> => {
+ const parts = segments(rel)
+ const { root, avoid } = await openFolder(pluginId, folder)
+
+ const guard = (real: string) => {
+ if (!inside(real, root)) {
+ refuse('outside-folder', 'That path leaves the folder.')
+ }
+
+ if (avoid.some(protectedRoot => insideLoose(real, protectedRoot)) || secondPath(real)) {
+ refuse('protected', 'That path is Hermes data and cannot be used by a plugin.')
+ }
+ }
+
+ // Hermes data mounted inside the folder keeps an inside path; its
+ // filesystem identity gives it away.
+ const refuseMounted = async (real: string) => {
+ if (await protectedIdentityWithin(real, root, avoid)) {
+ refuse('protected', 'That path is Hermes data mounted inside the folder and cannot be used by a plugin.')
+ }
+ }
+
+ if (parts.length === 0) {
+ return { root, parts, parent: null, entry: root, target: root, stat: await fs.promises.stat(root) }
+ }
+
+ const parent = await realpathOrNull(path.join(root, ...parts.slice(0, -1)))
+
+ if (!parent) {
+ return refuse('not-found', 'The parent folder does not exist.')
+ }
+
+ guard(parent)
+
+ const entry = path.join(parent, parts[parts.length - 1])
+ const lstat = await lstatOrNull(entry)
+
+ if (!lstat) {
+ await refuseMounted(parent)
+
+ return { root, parts, parent, entry, target: entry, stat: null }
+ }
+
+ // Every existing entry is checked by its realpath: a symlink's target, and
+ // the long, correctly-cased name behind a Windows short name (`ENV~1`).
+ const target = await realpathOrNull(entry)
+
+ if (!target) {
+ return refuse('outside-folder', 'That link points nowhere inside the folder.')
+ }
+
+ guard(target)
+ await refusePseudo(target)
+ await refuseMounted(target)
+
+ // The realpath itself, not followed: a link here now means the path was
+ // swapped after it was resolved. The ops re-check it after they open.
+ const stat = await fs.promises.lstat(target)
+
+ if (stat.isSymbolicLink()) {
+ return refuse('outside-folder', 'The file changed while it was being checked.')
+ }
+
+ return { root, parts, parent, entry, target, stat }
+ }
+
+ const OPS = createPluginFileOps({ resolve, inside, segments, trashItem: deps.trashItem })
+
+ const answer = async <T>(work: () => Promise<T>): Promise<PluginFilesFailure | T> => {
+ try {
+ return await work()
+ } catch (error) {
+ if (error instanceof Refusal) {
+ return error.failure
+ }
+
+ const code = errnoCode(error)
+
+ return code === 'ENOENT' || code === 'ENOTDIR'
+ ? fail('not-found', 'No such file or folder.')
+ : code === 'EEXIST'
+ ? fail('exists', 'A file with that name already exists.')
+ : fail('io-error', error instanceof Error ? error.message : String(error))
+ }
+ }
+
+ return {
+ async grants(pluginId) {
+ const key = typeof pluginId === 'string' ? pluginId : ''
+
+ return [...((await load())[key] ?? [])]
+ },
+
+ addGrant: (pluginId, picked) =>
+ answer(async () => {
+ const key = pluginKey(pluginId)
+ const real = await realpathOrNull(String(picked || ''))
+
+ if (!real || !(await fs.promises.stat(real)).isDirectory()) {
+ return fail('not-a-directory', 'Pick a folder.')
+ }
+
+ if ((await realRoots(systemRoots(platform))).some(root => insideLoose(real, root))) {
+ return fail('protected', 'That is a system folder and cannot be shared with a plugin.')
+ }
+
+ const roots = await protectedRoots()
+
+ if (overlapsProtected(real, roots) || (await overlapsByIdentity(real, roots))) {
+ return fail('protected', 'That folder holds Hermes data and cannot be shared with a plugin.')
+ }
+
+ await refusePseudo(real)
+
+ if (sensitiveReason(path.join(real, 'entry')) || sensitiveReason(real)) {
+ return fail('protected', 'That folder holds keys or credentials and cannot be shared with a plugin.')
+ }
+
+ return mutate(grants => {
+ const rows = (grants[key] ??= [])
+ const existing = rows.find(row => same(row.path, real))
+
+ if (existing) {
+ return { ok: true as const, folder: { ...existing } }
+ }
+
+ const folder = {
+ id: randomBytes(8).toString('hex'),
+ name: path.basename(real) || real,
+ path: real,
+ grantedAt: new Date().toISOString()
+ }
+
+ rows.push(folder)
+
+ return { ok: true as const, folder: { ...folder } }
+ })
+ }),
+
+ revoke: (pluginId, folderId) =>
+ mutate(grants => {
+ const key = typeof pluginId === 'string' ? pluginId : ''
+ const rows = grants[key] ?? []
+ const kept = folderId === undefined ? [] : rows.filter(row => row.id !== folderId)
+
+ if (kept.length) {
+ grants[key] = kept
+ } else {
+ delete grants[key]
+ }
+
+ return { ok: true as const, removed: rows.length - kept.length }
+ }),
+
+ run: (pluginId, request) =>
+ answer(async () => {
+ const key = pluginKey(pluginId)
+ const op = request && typeof request === 'object' ? request.op : undefined
+
+ if (typeof op !== 'string' || !Object.prototype.hasOwnProperty.call(OPS, op)) {
+ return fail('invalid-op', 'Unknown file operation.')
+ }
+
+ return OPS[op](key, request)
+ })
+ }
+}
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 2d6f0a6443a..7237b4c0721 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -478,6 +478,18 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
renamePath: (targetPath, newName) => ipcRenderer.invoke('hermes:fs:rename', targetPath, newName),
writeTextFile: (filePath, content) => ipcRenderer.invoke('hermes:fs:writeText', filePath, content),
trashPath: targetPath => ipcRenderer.invoke('hermes:fs:trash', targetPath),
+ pluginFiles: {
+ request: (pluginId, labels) => ipcRenderer.invoke('hermes:pluginFiles:request', pluginId, labels),
+ grants: pluginId => ipcRenderer.invoke('hermes:pluginFiles:grants', pluginId),
+ revoke: (pluginId, folderId) => ipcRenderer.invoke('hermes:pluginFiles:revoke', pluginId, folderId),
+ op: (pluginId, request) => ipcRenderer.invoke('hermes:pluginFiles:op', pluginId, request),
+ onChanged: callback => {
+ const listener = (_event, change) => callback(change)
+ ipcRenderer.on('hermes:pluginFiles:changed', listener)
+
+ return () => ipcRenderer.removeListener('hermes:pluginFiles:changed', listener)
+ }
+ },
git: {
worktreeList: repoPath => ipcRenderer.invoke('hermes:git:worktreeList', repoPath),
worktreeAdd: (repoPath, options) => ipcRenderer.invoke('hermes:git:worktreeAdd', repoPath, options),
diff --git a/apps/desktop/src/app/capabilities/plugins/plugin-folder-access.test.tsx b/apps/desktop/src/app/capabilities/plugins/plugin-folder-access.test.tsx
new file mode 100644
index 00000000000..20678b6e602
--- /dev/null
+++ b/apps/desktop/src/app/capabilities/plugins/plugin-folder-access.test.tsx
@@ -0,0 +1,61 @@
+import { QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import type { PluginRecord } from '@/contrib/plugins-store'
+import { queryClient } from '@/lib/query-client'
+
+import { PluginFolderAccess } from './plugin-folder-access'
+
+vi.mock('@/store/notifications', () => ({ notify: vi.fn(), notifyError: vi.fn() }))
+
+const grants = [{ grantedAt: 'x', id: 'f1', name: 'Vault', path: '/home/me/Vault' }]
+
+const door = {
+ grants: vi.fn(async () => [...grants]),
+ op: vi.fn(),
+ request: vi.fn(),
+ revoke: vi.fn(async () => {
+ grants.length = 0
+
+ return { ok: true, removed: 1 }
+ })
+}
+
+afterEach(() => {
+ cleanup()
+ queryClient.clear()
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+})
+
+describe('PluginFolderAccess', () => {
+ it('shows each granted folder and revokes it for that plugin', async () => {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { pluginFiles: door }
+ render(
+ <QueryClientProvider client={queryClient}>
+ <PluginFolderAccess name="Plexus" plugin={{ id: 'plexus' } as PluginRecord} />
+ </QueryClientProvider>
+ )
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Revoke access to /home/me/Vault' }))
+
+ expect(door.revoke).toHaveBeenCalledWith('plexus', 'f1')
+ await waitFor(() => expect(screen.queryByText('/home/me/Vault')).toBeNull())
+ })
+
+ it('a failed read says so and can be retried, instead of looking like no access', async () => {
+ grants.splice(0, grants.length, { grantedAt: 'x', id: 'f1', name: 'Vault', path: '/home/me/Vault' })
+ door.grants.mockRejectedValueOnce(new Error('EACCES: grants.json'))
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { pluginFiles: door }
+ render(
+ <QueryClientProvider client={queryClient}>
+ <PluginFolderAccess name="Plexus" plugin={{ id: 'plexus' } as PluginRecord} />
+ </QueryClientProvider>
+ )
+
+ expect(await screen.findByText('Could not load the folders shared with Plexus.')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+
+ expect(await screen.findByText('/home/me/Vault')).toBeTruthy()
+ })
+})
diff --git a/apps/desktop/src/app/capabilities/plugins/plugin-folder-access.tsx b/apps/desktop/src/app/capabilities/plugins/plugin-folder-access.tsx
new file mode 100644
index 00000000000..9fdd7b8f031
--- /dev/null
+++ b/apps/desktop/src/app/capabilities/plugins/plugin-folder-access.tsx
@@ -0,0 +1,112 @@
+import { useQuery } from '@tanstack/react-query'
+import { useEffect } from 'react'
+
+import { Button } from '@/components/ui/button'
+import { Codicon } from '@/components/ui/codicon'
+import { PLUGIN_FOLDER_GRANTS_KEY } from '@/contrib/plugin-files'
+import type { PluginRecord } from '@/contrib/plugins-store'
+import { useI18n } from '@/i18n'
+import { queryClient } from '@/lib/query-client'
+import { notify, notifyError } from '@/store/notifications'
+
+interface PluginFolderAccessProps {
+ /** The package's desktop half; a package without one has no grants. */
+ plugin: null | PluginRecord
+ name: string
+}
+
+const grantsKey = (pluginId: string) => [...PLUGIN_FOLDER_GRANTS_KEY, pluginId]
+
+/** The folders the user granted a desktop plugin through `ctx.files`, each
+ * with a Revoke that takes effect on the plugin's next call. Renders nothing
+ * when the plugin holds no grant (or the shell predates the door), and a
+ * retry when the grants could not be read. */
+export function PluginFolderAccess({ plugin, name }: PluginFolderAccessProps) {
+ const { t } = useI18n()
+ const copy = t.skills.plugins.folderAccess
+ const door = window.hermesDesktop?.pluginFiles
+ const pluginId = plugin?.id ?? ''
+
+ const {
+ data: grants = [],
+ isError,
+ refetch
+ } = useQuery({
+ enabled: Boolean(door && pluginId),
+ queryFn: () => door!.grants(pluginId),
+ queryKey: grantsKey(pluginId),
+ retry: false
+ })
+
+ // A grant made or revoked in another window refreshes this list too.
+ useEffect(
+ () =>
+ door?.onChanged?.(change => {
+ if (change.pluginId === pluginId) {
+ void queryClient.invalidateQueries({ queryKey: grantsKey(pluginId) })
+ }
+ }),
+ [door, pluginId]
+ )
+
+ // A record the app could not read is not "no access": say so, offer a retry.
+ if (isError) {
+ return (
+ <div className="flex flex-col gap-2" data-testid={`plugin-folder-access-${pluginId}`}>
+ <div className="text-xs font-medium text-(--ui-text-secondary)">{copy.title}</div>
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="flex-1 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
+ {copy.loadFailed(name)}
+ </span>
+ <Button onClick={() => void refetch()} size="xs" variant="text">
+ {t.common.retry}
+ </Button>
+ </div>
+ </div>
+ )
+ }
+
+ if (!grants.length) {
+ return null
+ }
+
+ const revoke = async (folderId: string, folderPath: string) => {
+ try {
+ await door!.revoke(pluginId, folderId)
+ notify({ kind: 'success', message: copy.revoked(name, folderPath) })
+ } catch (error) {
+ notifyError(error, copy.revokeFailed(name))
+ } finally {
+ void queryClient.invalidateQueries({ queryKey: PLUGIN_FOLDER_GRANTS_KEY })
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-2" data-testid={`plugin-folder-access-${pluginId}`}>
+ <div className="text-xs font-medium text-(--ui-text-secondary)">{copy.title}</div>
+ <div className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
+ {copy.hint(name)}
+ </div>
+ {grants.map(grant => (
+ <div className="flex min-w-0 items-center gap-2" key={grant.id}>
+ <Codicon name="folder" size="0.85rem" />
+ <span className="flex min-w-0 flex-1 flex-col" title={grant.path}>
+ <span className="truncate text-xs text-(--ui-text-secondary)">{grant.name}</span>
+ <span className="truncate font-mono text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
+ {grant.path}
+ </span>
+ </span>
+ <Button
+ aria-label={copy.revokeLabel(grant.path)}
+ className="text-destructive hover:text-destructive"
+ onClick={() => void revoke(grant.id, grant.path)}
+ size="xs"
+ variant="text"
+ >
+ {copy.revoke}
+ </Button>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx b/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx
index 6c68ffde46a..a556e145c78 100644
--- a/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx
+++ b/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button'
import { Codicon } from '@/components/ui/codicon'
import { Switch } from '@/components/ui/switch'
import { Tip } from '@/components/ui/tooltip'
+import { revokeGrantsIfUninstalled } from '@/contrib/plugin-files'
import { $pluginRecords, enablePackageDesktopHalf, type PluginRecord, setPluginEnabled } from '@/contrib/plugins-store'
import { useContributions } from '@/contrib/react/use-contributions'
import { discoverRuntimePlugins, uninstallDiskPlugin } from '@/contrib/runtime-loader'
@@ -45,6 +46,7 @@ import { type CatalogEntry, parseCatalog } from '../catalog/catalog-data'
import { CatalogSwitch } from '../catalog/catalog-switch'
import { TOOLSETS_QUERY_KEY } from '../toolsets/toolsets-data'
+import { PluginFolderAccess } from './plugin-folder-access'
import { mergePluginPackages, type PackageKind, type PluginPackage } from './plugin-packages'
import { PluginPageAccess } from './plugin-page-access'
import { runPluginUpdate } from './plugin-update'
@@ -276,7 +278,7 @@ function PackageRow({
request: GatewayRequest
onAgentToggle: (row: AgentPluginRow, enable: boolean) => void
onAgentUpdate: (row: AgentPluginRow) => void
- onAgentRemove: (row: AgentPluginRow) => void
+ onAgentRemove: (row: AgentPluginRow, desktop: null | PluginRecord) => void
onDesktopRemove: (record: PluginRecord) => void
}) {
const { t } = useI18n()
@@ -437,6 +439,8 @@ function PackageRow({
</span>
</div>
+ <PluginFolderAccess name={pkg.name} plugin={desktop} />
+
{/* The two halves. Desktop is app-level and reads the same whichever
profile is selected; Agent follows the selector. A half the package
lacks shows a dash; a half it has but which is missing on this side
@@ -519,7 +523,7 @@ function PackageRow({
disabled={busy}
name={pkg.name}
note={p.uninstallTip(pkg.name, scopeLabel)}
- onUninstall={() => onAgentRemove(agent)}
+ onUninstall={() => onAgentRemove(agent, desktop)}
/>
) : (
desktop &&
@@ -685,7 +689,7 @@ export const PluginsTab = memo(function PluginsTab({
const isInstalled = (entry: CatalogEntry) => packageById.has(entry.id)
const handleAgentRemove = useCallback(
- (row: AgentPluginRow) => {
+ (row: AgentPluginRow, desktop: null | PluginRecord) => {
void confirm({
confirmLabel: p.uninstall,
description: p.uninstallConfirmBody(row.name, label),
@@ -698,8 +702,13 @@ export const PluginsTab = memo(function PluginsTab({
if (await removeAgentPlugin(requestGateway, row.name, p.uninstallFailed(row.name), scope)) {
notify({ kind: 'success', message: p.uninstalled(row.name) })
- // Prunes the app-level desktop half whose source package just went away.
+
+ // Prunes the app-level desktop half whose source package just went
+ // away; its folder grants go with it, and only then (another profile
+ // may still install the package).
void rescanAll(requestGateway, scope)
+ .then(() => desktop && revokeGrantsIfUninstalled(desktop.id))
+ .catch(error => notifyError(error, p.folderAccess.revokeFailed(row.name)))
}
})
},
diff --git a/apps/desktop/src/contrib/plugin-files.test.ts b/apps/desktop/src/contrib/plugin-files.test.ts
new file mode 100644
index 00000000000..315fe6ad599
--- /dev/null
+++ b/apps/desktop/src/contrib/plugin-files.test.ts
@@ -0,0 +1,79 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { notify } from '@/store/notifications'
+
+import { createPluginContext } from './plugin'
+import { revokeGrantsIfUninstalled } from './plugin-files'
+import { $pluginRecords, type PluginRecord } from './plugins-store'
+
+vi.mock('@/store/notifications', () => ({ notify: vi.fn(), notifyError: vi.fn() }))
+
+const door = {
+ grants: vi.fn(async () => []),
+ op: vi.fn(async () => ({ ok: true, text: 'hi' })),
+ request: vi.fn(),
+ revoke: vi.fn(async () => ({ ok: true, removed: 1 }))
+}
+
+beforeEach(() => {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { pluginFiles: door }
+})
+
+afterEach(() => {
+ vi.clearAllMocks()
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+})
+
+describe('ctx.files', () => {
+ it("always names the calling plugin and asks with the app's own picker copy", async () => {
+ door.request.mockResolvedValueOnce({ ok: true, folder: { grantedAt: 'x', id: 'f1', name: 'Vault', path: '/v' } })
+ const files = createPluginContext('plexus').files
+
+ expect(await files.requestFolder()).toEqual({ ok: true, folder: { id: 'f1', name: 'Vault', path: '/v' } })
+ expect(door.request).toHaveBeenCalledWith('plexus', {
+ buttonLabel: 'Allow access',
+ title: 'Choose a folder for plexus'
+ })
+
+ await files.readText('f1', 'notes/a.md')
+ expect(door.op).toHaveBeenCalledWith('plexus', { op: 'readText', folder: 'f1', path: 'notes/a.md' })
+ })
+
+ it('tells the user when the app refuses the folder they picked', async () => {
+ door.request.mockResolvedValueOnce({ ok: false, error: 'protected', message: 'no' })
+
+ expect(await createPluginContext('plexus').files.requestFolder()).toMatchObject({ ok: false, error: 'protected' })
+ expect(notify).toHaveBeenCalledWith(expect.objectContaining({ kind: 'warning' }))
+ })
+
+ it('answers unavailable on a shell without the door instead of throwing', async () => {
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+ const files = createPluginContext('plexus').files
+
+ expect(await files.requestFolder()).toMatchObject({ ok: false, error: 'unavailable' })
+ expect(await files.list('data')).toMatchObject({ ok: false, error: 'unavailable' })
+ expect(await files.folders()).toEqual([])
+ })
+})
+
+describe('grants after a package removal', () => {
+ afterEach(() => $pluginRecords.set({}))
+
+ it('keeps the grants of a desktop plugin another profile still installs', async () => {
+ $pluginRecords.set({ plexus: { id: 'plexus' } as PluginRecord })
+
+ expect(await revokeGrantsIfUninstalled('plexus')).toBe(false)
+ expect(door.revoke).not.toHaveBeenCalled()
+ })
+
+ it('drops the grants once the desktop plugin is gone', async () => {
+ expect(await revokeGrantsIfUninstalled('plexus')).toBe(true)
+ expect(door.revoke).toHaveBeenCalledWith('plexus')
+ })
+
+ it('a revoke that fails is reported, not counted as done', async () => {
+ door.revoke.mockRejectedValueOnce(new Error('EACCES: grants.json'))
+
+ await expect(revokeGrantsIfUninstalled('plexus')).rejects.toThrow('EACCES')
+ })
+})
diff --git a/apps/desktop/src/contrib/plugin-files.ts b/apps/desktop/src/contrib/plugin-files.ts
new file mode 100644
index 00000000000..574b71785ee
--- /dev/null
+++ b/apps/desktop/src/contrib/plugin-files.ts
@@ -0,0 +1,176 @@
+/**
+ * `ctx.files` — the folder-scoped file door. A plugin reads and writes inside
+ * its own data folder (`'data'`) and inside folders the user granted it
+ * through the app's picker, by RELATIVE path. Electron's main process owns the
+ * grants and checks every call (electron/plugin-files.ts); this side only
+ * names the plugin, supplies the app's own picker copy, and keeps the
+ * Capabilities ▸ Plugins grant list fresh. Every member resolves a result and
+ * never throws, so an older shell reads as `{ ok: false, error: 'unavailable' }`.
+ */
+
+import { translateNow } from '@/i18n/runtime'
+import { queryClient } from '@/lib/query-client'
+import { notify } from '@/store/notifications'
+
+import { $pluginRecords } from './plugins-store'
+
+export const PLUGIN_FOLDER_GRANTS_KEY = ['plugin-folder-grants'] as const
+
+export interface PluginFolder {
+ /** Opaque handle to pass as `folder` to the other calls. */
+ id: string
+ /** The folder's name, for display. */
+ name: string
+ /** Absolute path the user picked, for display only — calls take `id`. */
+ path: string
+}
+
+export interface PluginFileEntry {
+ name: string
+ /** Relative to the folder, `/`-separated; pass it back as `path`. */
+ path: string
+ isDirectory: boolean
+}
+
+export type PluginFilesResult<T extends object = object> =
+ | ({ ok: true } & T)
+ | { ok: false; error: string; message: string }
+
+export interface PluginFiles {
+ /** Handle of this plugin's private data folder (always available). */
+ readonly dataFolder: 'data'
+ /** Ask the user for a folder with the app's own picker. `folder` is null on
+ * cancel. A folder holding Hermes data is refused (`error: 'protected'`)
+ * and the app tells the user why. */
+ requestFolder: () => Promise<PluginFilesResult<{ folder: PluginFolder | null }>>
+ /** Folders the user has granted this plugin and not revoked. */
+ folders: () => Promise<PluginFolder[]>
+ /** Give a granted folder back (the user can also revoke it in Settings). */
+ release: (folderId: string) => Promise<boolean>
+ list: (folder: string, path?: string) => Promise<PluginFilesResult<{ entries: PluginFileEntry[]; truncated: boolean }>>
+ stat: (
+ folder: string,
+ path: string
+ ) => Promise<PluginFilesResult<{ exists: boolean; isDirectory?: boolean; mtimeMs?: number; size?: number }>>
+ /** UTF-8 text up to 4 MiB; a binary or larger file is refused, never truncated. */
+ readText: (folder: string, path: string) => Promise<PluginFilesResult<{ mtimeMs: number; size: number; text: string }>>
+ /** A file (up to 16 MiB) as a `data:` URL, for image previews. */
+ readDataUrl: (folder: string, path: string) => Promise<PluginFilesResult<{ url: string }>>
+ /** Write up to 4 MiB of UTF-8 text. The parent folder must exist;
+ * `exclusive` refuses to replace an existing file. */
+ writeText: (
+ folder: string,
+ path: string,
+ text: string,
+ options?: { exclusive?: boolean }
+ ) => Promise<PluginFilesResult<{ mtimeMs: number; path: string; size: number }>>
+ /** Rename in place (same parent folder); `name` is one plain name. */
+ rename: (folder: string, path: string, name: string) => Promise<PluginFilesResult<{ path: string }>>
+ /** Move to the OS trash (recoverable). The folder itself cannot be trashed. */
+ trash: (folder: string, path: string) => Promise<PluginFilesResult>
+}
+
+const unavailable = { ok: false as const, error: 'unavailable', message: 'This Hermes Desktop build has no plugin file access.' }
+
+const bridge = () => (typeof window === 'undefined' ? undefined : window.hermesDesktop?.pluginFiles)
+
+const folderOf = (row: PluginFolder): PluginFolder => ({ id: row.id, name: row.name, path: row.path })
+
+const refreshGrantList = () => void queryClient.invalidateQueries({ queryKey: PLUGIN_FOLDER_GRANTS_KEY })
+
+/** Drop a desktop plugin's folder grants once it is really gone. Removing a
+ * package's agent half from one profile leaves the app-wide desktop half
+ * (and its grants) in place while another profile still installs it. A
+ * failed revoke rejects, so the caller can tell the user. */
+export async function revokeGrantsIfUninstalled(pluginId: string): Promise<boolean> {
+ if ($pluginRecords.get()[pluginId]) {
+ return false
+ }
+
+ try {
+ await bridge()?.revoke(pluginId)
+ } finally {
+ refreshGrantList()
+ }
+
+ return true
+}
+
+export function createPluginFiles(pluginId: string): PluginFiles {
+ const run = async <T extends object>(request: Record<string, unknown>): Promise<PluginFilesResult<T>> => {
+ const door = bridge()
+
+ if (!door) {
+ return unavailable
+ }
+
+ try {
+ return (await door.op(pluginId, request)) as PluginFilesResult<T>
+ } catch (error) {
+ return { ok: false, error: 'io-error', message: error instanceof Error ? error.message : String(error) }
+ }
+ }
+
+ return {
+ dataFolder: 'data',
+
+ async requestFolder() {
+ const door = bridge()
+
+ if (!door) {
+ return unavailable
+ }
+
+ const name = $pluginRecords.get()[pluginId]?.name ?? pluginId
+
+ try {
+ const result = await door.request(pluginId, {
+ buttonLabel: translateNow('skills.plugins.folderAccess.pickerButton'),
+ title: translateNow('skills.plugins.folderAccess.pickerTitle', name)
+ })
+
+ if (!result.ok) {
+ if (result.error === 'protected') {
+ notify({ kind: 'warning', message: translateNow('skills.plugins.folderAccess.refusedProtected', name) })
+ }
+
+ return result
+ }
+
+ refreshGrantList()
+
+ return { ok: true, folder: result.folder ? folderOf(result.folder) : null }
+ } catch (error) {
+ return { ok: false, error: 'io-error', message: error instanceof Error ? error.message : String(error) }
+ }
+ },
+
+ folders: async () => {
+ try {
+ return ((await bridge()?.grants(pluginId)) ?? []).map(folderOf)
+ } catch {
+ return []
+ }
+ },
+
+ async release(folderId) {
+ try {
+ const removed = ((await bridge()?.revoke(pluginId, folderId))?.removed ?? 0) > 0
+ refreshGrantList()
+
+ return removed
+ } catch {
+ return false
+ }
+ },
+
+ list: (folder, path = '') => run({ op: 'list', folder, path }),
+ stat: (folder, path) => run({ op: 'stat', folder, path }),
+ readText: (folder, path) => run({ op: 'readText', folder, path }),
+ readDataUrl: (folder, path) => run({ op: 'readDataUrl', folder, path }),
+ writeText: (folder, path, text, options) =>
+ run({ op: 'writeText', folder, path, text, exclusive: Boolean(options?.exclusive) }),
+ rename: (folder, path, name) => run({ op: 'rename', folder, path, name }),
+ trash: (folder, path) => run({ op: 'trash', folder, path })
+ }
+}
diff --git a/apps/desktop/src/contrib/plugin.ts b/apps/desktop/src/contrib/plugin.ts
index f3ad9848c91..9fe4bbe1a40 100644
--- a/apps/desktop/src/contrib/plugin.ts
+++ b/apps/desktop/src/contrib/plugin.ts
@@ -29,11 +29,13 @@ import { $petActive } from '@/store/pet'
import { clearPetMessages, type PetSayOptions, sayPetMessage } from '@/store/pet-plugin-messages'
import { type GatewayEventListener, onGatewayEvent } from './events'
+import { createPluginFiles, type PluginFiles } from './plugin-files'
import { createPluginPreview, type PluginPreview } from './plugin-preview'
import { $pluginRecords } from './plugins-store'
import { registry } from './registry'
import { type PluginSettingsPage, settingsPageContribution } from './settings-pages'
+export type { PluginFileEntry, PluginFiles, PluginFilesResult, PluginFolder } from './plugin-files'
export type { PluginPreview } from './plugin-preview'
import type { Contribution } from './types'
@@ -180,6 +182,11 @@ export interface PluginContext {
preview: PluginPreview
/** Plugin-scoped persistence. */
storage: PluginStorage
+ /** Folder-scoped file access: this plugin's own data folder plus folders
+ * the user grants it through the app's picker, by relative path. The app
+ * checks every call; nothing outside those folders (or inside Hermes'
+ * own data) is reachable. Feature-detect on older hosts: `ctx.files?.…`. */
+ files: PluginFiles
/** Plugin-scoped i18n: ship + register locale bundles under this plugin,
* resolved against the app's active locale — no core `en.ts` edit. */
i18n: PluginI18n
@@ -394,6 +401,7 @@ export function createPluginContext(
listActions: listPluginAppActions,
preview: createPluginPreview(pluginId, capabilities),
storage: createPluginStorage(pluginId),
+ files: createPluginFiles(pluginId),
i18n: createPluginI18n(pluginId, track)
}
}
diff --git a/apps/desktop/src/contrib/runtime-loader.ts b/apps/desktop/src/contrib/runtime-loader.ts
index a872c9c7e66..d1d17d2e5ff 100644
--- a/apps/desktop/src/contrib/runtime-loader.ts
+++ b/apps/desktop/src/contrib/runtime-loader.ts
@@ -1014,6 +1014,20 @@ export async function uninstallDiskPlugin(pluginId: string): Promise<{ ok: boole
retireDiskPlugin(file, record)
+ // A reinstall under the same id must ask for its folders again (ctx.files).
+ // A revoke that fails is reported: the plugin's row is gone, so the user
+ // could not revoke it there any more.
+ if (record.id) {
+ try {
+ await window.hermesDesktop?.pluginFiles?.revoke(record.id)
+ } catch (error) {
+ return {
+ ok: false,
+ error: `removed, but its folder access could not be revoked: ${error instanceof Error ? error.message : String(error)}`
+ }
+ }
+ }
+
return { ok: true }
}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 10e4ed6c2de..f4a4ff20bb9 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -505,6 +505,19 @@ declare global {
writeTextFile?: (path: string, content: string) => Promise<{ path: string }>
// Move a file/folder to the OS trash (recoverable).
trashPath?: (path: string) => Promise<boolean>
+ /** The plugin SDK's folder-scoped file door (`ctx.files`). Main owns
+ * grants and checks every path; older shells lack it. */
+ pluginFiles?: {
+ request: (
+ pluginId: string,
+ labels: { buttonLabel: string; title: string }
+ ) => Promise<HermesPluginFilesResult<{ folder: HermesPluginFolderGrant | null }>>
+ grants: (pluginId: string) => Promise<HermesPluginFolderGrant[]>
+ revoke: (pluginId: string, folderId?: string) => Promise<{ ok: true; removed: number }>
+ op: (pluginId: string, request: Record<string, unknown>) => Promise<HermesPluginFilesResult>
+ /** A grant was added or revoked in any window; returns an unsubscribe. */
+ onChanged?: (callback: (change: { pluginId: string }) => void) => () => void
+ }
// Git-driven worktree management for the "Start work" flow.
git?: {
worktreeList: (repoPath: string) => Promise<HermesGitWorktree[]>
@@ -700,6 +713,17 @@ declare global {
}
}
+export interface HermesPluginFolderGrant {
+ id: string
+ name: string
+ path: string
+ grantedAt: string
+}
+
+export type HermesPluginFilesResult<T extends object = Record<string, unknown>> =
+ | ({ ok: true } & T)
+ | { ok: false; error: string; message: string }
+
export interface DesktopMarketplaceSearchItem {
extensionId: string
displayName: string
diff --git a/apps/desktop/src/i18n/ar_capabilities.ts b/apps/desktop/src/i18n/ar_capabilities.ts
index 76090b327c7..32a3e50e146 100644
--- a/apps/desktop/src/i18n/ar_capabilities.ts
+++ b/apps/desktop/src/i18n/ar_capabilities.ts
@@ -16,7 +16,20 @@ export const arCapabilities = {
skills: {
plugins: {
...arPluginPreviewAccess,
- pageBlurb: 'يمكن للإضافة توسيع هذا التطبيق أو الوكيل أو كليهما — ولكل جزء مفتاح تشغيل مستقل.'
+ pageBlurb: 'يمكن للإضافة توسيع هذا التطبيق أو الوكيل أو كليهما — ولكل جزء مفتاح تشغيل مستقل.',
+ folderAccess: {
+ title: 'الوصول إلى المجلدات',
+ hint: (name: string) => `يمكن لـ ${name} قراءة الملفات وتعديلها في هذه المجلدات. يسري الإلغاء فورًا.`,
+ revoke: 'إلغاء',
+ revokeLabel: (path: string) => `إلغاء الوصول إلى ${path}`,
+ revoked: (name: string, path: string) => `لم يعد بإمكان ${name} استخدام ${path}.`,
+ revokeFailed: (name: string) => `تعذر إلغاء وصول ${name} إلى المجلدات`,
+ pickerTitle: (name: string) => `اختر مجلدًا لـ ${name}`,
+ pickerButton: 'السماح بالوصول',
+ refusedProtected: (name: string) =>
+ `لا يمكن لـ ${name} استخدام هذا المجلد: فهو يحتوي على إعدادات Hermes أو مفاتيحه أو بيانات الإضافات. اختر مجلدًا لا يحتويها.`,
+ loadFailed: (name: string) => `تعذّر تحميل المجلدات المشتركة مع ${name}.`
+ }
},
tabSkills: 'المهارات',
tabToolsets: 'مجموعات الأدوات',
diff --git a/apps/desktop/src/i18n/de_plugin_update.ts b/apps/desktop/src/i18n/de_plugin_update.ts
index 29da9034b3f..b74d61e6ab5 100644
--- a/apps/desktop/src/i18n/de_plugin_update.ts
+++ b/apps/desktop/src/i18n/de_plugin_update.ts
@@ -2,6 +2,19 @@ import type { PluginUpdateTranslations } from './types_plugin_update'
/** Copy for updating an installed plugin (Plugins tab): catalog re-pin consent and the security-scan override. */
export const dePluginUpdate: PluginUpdateTranslations = {
+ folderAccess: {
+ title: 'Ordnerzugriff',
+ hint: (name: string) => `${name} darf Dateien in diesen Ordnern lesen und ändern. Ein Widerruf gilt sofort.`,
+ revoke: 'Widerrufen',
+ revokeLabel: (path: string) => `Zugriff auf ${path} widerrufen`,
+ revoked: (name: string, path: string) => `${name} kann ${path} nicht mehr verwenden.`,
+ revokeFailed: (name: string) => `Ordnerzugriff für ${name} konnte nicht widerrufen werden`,
+ pickerTitle: (name: string) => `Ordner für ${name} auswählen`,
+ pickerButton: 'Zugriff erlauben',
+ refusedProtected: (name: string) =>
+ `${name} kann diesen Ordner nicht verwenden: Er enthält Hermes-Einstellungen, Schlüssel oder Plugin-Daten. Wählen Sie einen Ordner, der sie nicht enthält.`,
+ loadFailed: (name: string) => `Die für ${name} freigegebenen Ordner konnten nicht geladen werden.`
+ },
updateToPin: sha => `Auf ${sha} aktualisieren`,
updateFailed: name => `${name} konnte nicht aktualisiert werden`,
updated: name =>
diff --git a/apps/desktop/src/i18n/en_plugin_update.ts b/apps/desktop/src/i18n/en_plugin_update.ts
index c8e964f5ec4..65e119e3c8c 100644
--- a/apps/desktop/src/i18n/en_plugin_update.ts
+++ b/apps/desktop/src/i18n/en_plugin_update.ts
@@ -2,6 +2,19 @@ import type { PluginUpdateTranslations } from './types_plugin_update'
/** Copy for updating an installed plugin (Plugins tab): catalog re-pin consent and the security-scan override. */
export const enPluginUpdate: PluginUpdateTranslations = {
+ folderAccess: {
+ title: 'Folder access',
+ hint: (name: string) => `${name} can read and change files in these folders. Revoking takes effect at once.`,
+ revoke: 'Revoke',
+ revokeLabel: (path: string) => `Revoke access to ${path}`,
+ revoked: (name: string, path: string) => `${name} can no longer use ${path}.`,
+ revokeFailed: (name: string) => `Could not revoke folder access for ${name}`,
+ pickerTitle: (name: string) => `Choose a folder for ${name}`,
+ pickerButton: 'Allow access',
+ refusedProtected: (name: string) =>
+ `${name} cannot use that folder: it holds Hermes settings, keys or plugin data. Choose a folder that does not contain them.`,
+ loadFailed: (name: string) => `Could not load the folders shared with ${name}.`
+ },
updateToPin: (sha: string) => `Update to ${sha}`,
updateFailed: (name: string) => `Could not update ${name}`,
updated: (name: string) => `${name} updated to the current catalog pin. Restart the gateway to apply.`,
diff --git a/apps/desktop/src/i18n/es_plugin_update.ts b/apps/desktop/src/i18n/es_plugin_update.ts
index 0f529b0b0b1..c07be648a33 100644
--- a/apps/desktop/src/i18n/es_plugin_update.ts
+++ b/apps/desktop/src/i18n/es_plugin_update.ts
@@ -2,6 +2,19 @@ import type { PluginUpdateTranslations } from './types_plugin_update'
/** Copy for updating an installed plugin (Plugins tab): catalog re-pin consent and the security-scan override. */
export const esPluginUpdate: PluginUpdateTranslations = {
+ folderAccess: {
+ title: 'Acceso a carpetas',
+ hint: (name: string) => `${name} puede leer y modificar archivos en estas carpetas. Revocar el acceso surte efecto al instante.`,
+ revoke: 'Revocar',
+ revokeLabel: (path: string) => `Revocar el acceso a ${path}`,
+ revoked: (name: string, path: string) => `${name} ya no puede usar ${path}.`,
+ revokeFailed: (name: string) => `No se pudo revocar el acceso a carpetas de ${name}`,
+ pickerTitle: (name: string) => `Elige una carpeta para ${name}`,
+ pickerButton: 'Permitir acceso',
+ refusedProtected: (name: string) =>
+ `${name} no puede usar esa carpeta: contiene ajustes, claves o datos de plugins de Hermes. Elige una carpeta que no los contenga.`,
+ loadFailed: (name: string) => `No se pudieron cargar las carpetas compartidas con ${name}.`
+ },
updateToPin: (sha: string) => `Actualizar a ${sha}`,
updateFailed: (name: string) => `No se pudo actualizar ${name}`,
updated: (name: string) =>
diff --git a/apps/desktop/src/i18n/fr_plugin_update.ts b/apps/desktop/src/i18n/fr_plugin_update.ts
index d460a500ed8..12b03aa1dd9 100644
--- a/apps/desktop/src/i18n/fr_plugin_update.ts
+++ b/apps/desktop/src/i18n/fr_plugin_update.ts
@@ -2,6 +2,19 @@ import type { PluginUpdateTranslations } from './types_plugin_update'
/** Copy for updating an installed plugin (Plugins tab): catalog re-pin consent and the security-scan override. */
export const frPluginUpdate: PluginUpdateTranslations = {
+ folderAccess: {
+ title: 'Accès aux dossiers',
+ hint: (name: string) => `${name} peut lire et modifier les fichiers de ces dossiers. Une révocation prend effet immédiatement.`,
+ revoke: 'Révoquer',
+ revokeLabel: (path: string) => `Révoquer l’accès à ${path}`,
+ revoked: (name: string, path: string) => `${name} ne peut plus utiliser ${path}.`,
+ revokeFailed: (name: string) => `Impossible de révoquer l’accès aux dossiers de ${name}`,
+ pickerTitle: (name: string) => `Choisir un dossier pour ${name}`,
+ pickerButton: 'Autoriser l’accès',
+ refusedProtected: (name: string) =>
+ `${name} ne peut pas utiliser ce dossier : il contient des réglages, des clés ou des données de plugins Hermes. Choisissez un dossier qui ne les contient pas.`,
+ loadFailed: (name: string) => `Impossible de charger les dossiers partagés avec ${name}.`
+ },
updateToPin: (sha: string) => `Mettre à jour vers ${sha}`,
updateFailed: (name: string) => `Impossible de mettre à jour ${name}`,
updated: (name: string) =>
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 9d98bbba3d8..32f9180d40d 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -16,7 +16,7 @@ import { jaNotices } from './ja_notices'
import { jaNotifications } from './ja_notifications'
import { jaOnboarding } from './ja_onboarding'
import { jaPluginPreviewAccess } from './ja_plugin_preview_access'
-import { jaPluginSettings } from './ja_plugins'
+import { jaPluginSettings, jaPluginsTab } from './ja_plugins'
import { jaProjects } from './ja_projects'
import { jaSharedMetrics } from './ja_shared_metrics'
import { jaThemePicker } from './ja_theme_picker'
@@ -1313,11 +1313,7 @@ export const jaOverrides = {
skillDeepLink: jaSkillDeepLink,
skills: {
- plugins: {
- ...jaPluginPreviewAccess,
- pageBlurb:
- 'プラグインはこのアプリ、エージェント、または両方を拡張できます。それぞれに独立したスイッチがあります。'
- },
+ plugins: { ...jaPluginPreviewAccess, ...jaPluginsTab },
hub: {
search: '検索',
searching: '検索中…',
diff --git a/apps/desktop/src/i18n/ja_plugins.ts b/apps/desktop/src/i18n/ja_plugins.ts
index 82f135e8dd6..0f58332b476 100644
--- a/apps/desktop/src/i18n/ja_plugins.ts
+++ b/apps/desktop/src/i18n/ja_plugins.ts
@@ -41,3 +41,22 @@ export const jaPluginSettings = {
}
}
} satisfies Pick<SettingsOverrides, 'pluginPages' | 'plugins'>
+
+/** Japanese copy for the Capabilities ▸ Plugins tab: the page blurb and a plugin's folder access. */
+export const jaPluginsTab = {
+ pageBlurb:
+ 'プラグインはこのアプリ、エージェント、または両方を拡張できます。それぞれに独立したスイッチがあります。',
+ folderAccess: {
+ title: 'フォルダーへのアクセス',
+ hint: (name: string) => `${name} はこれらのフォルダー内のファイルを読み取り、変更できます。取り消しはすぐに反映されます。`,
+ revoke: '取り消す',
+ revokeLabel: (path: string) => `${path} へのアクセスを取り消す`,
+ revoked: (name: string, path: string) => `${name} は ${path} を使用できなくなりました。`,
+ revokeFailed: (name: string) => `${name} のフォルダーアクセスを取り消せませんでした`,
+ pickerTitle: (name: string) => `${name} 用のフォルダーを選択`,
+ pickerButton: 'アクセスを許可',
+ refusedProtected: (name: string) =>
+ `${name} はこのフォルダーを使用できません。Hermes の設定、キー、またはプラグインデータが含まれています。それらを含まないフォルダーを選択してください。`,
+ loadFailed: (name: string) => `${name} と共有しているフォルダーを読み込めませんでした。`
+ }
+} satisfies NonNullable<NonNullable<TranslationOverrides['skills']>['plugins']>
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 396f9ac06fe..68763dd2504 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -14,7 +14,7 @@ import { ruNotices } from './ru_notices'
import { ruNotifications } from './ru_notifications'
import { ruOnboarding } from './ru_onboarding'
import { ruPluginPreviewAccess } from './ru_plugin_preview_access'
-import { ruPluginSettings } from './ru_plugins'
+import { ruPluginSettings, ruPluginsTab } from './ru_plugins'
import { ruProjects } from './ru_projects'
import { ruSharedMetrics } from './ru_shared_metrics'
import { ruThemePicker } from './ru_theme_picker'
@@ -1437,10 +1437,7 @@ export const ruOverrides = {
},
skillDeepLink: ruSkillDeepLink,
skills: {
- plugins: {
- ...ruPluginPreviewAccess,
- pageBlurb: 'Плагин может расширять приложение, агента или оба сразу — у каждой части свой переключатель.'
- },
+ plugins: { ...ruPluginPreviewAccess, ...ruPluginsTab },
tabSkills: 'Навыки',
tabToolsets: 'Инструменты',
configuringProfile: 'Настраивается:',
diff --git a/apps/desktop/src/i18n/ru_plugins.ts b/apps/desktop/src/i18n/ru_plugins.ts
index d525961b38d..85fc2289358 100644
--- a/apps/desktop/src/i18n/ru_plugins.ts
+++ b/apps/desktop/src/i18n/ru_plugins.ts
@@ -77,3 +77,22 @@ export const ruPluginSettings = {
}
}
} satisfies Pick<SettingsOverrides, 'pluginPages' | 'plugins'>
+
+/** Russian copy for the Capabilities ▸ Plugins tab: the page blurb and a plugin's folder access. */
+export const ruPluginsTab = {
+ pageBlurb:
+ 'Плагин может расширять приложение, агента или оба сразу — у каждой части свой переключатель.',
+ folderAccess: {
+ title: 'Доступ к папкам',
+ hint: (name: string) => `${name} может читать и изменять файлы в этих папках. Отзыв доступа действует сразу.`,
+ revoke: 'Отозвать',
+ revokeLabel: (path: string) => `Отозвать доступ к ${path}`,
+ revoked: (name: string, path: string) => `${name} больше не может использовать ${path}.`,
+ revokeFailed: (name: string) => `Не удалось отозвать доступ ${name} к папкам`,
+ pickerTitle: (name: string) => `Выберите папку для ${name}`,
+ pickerButton: 'Разрешить доступ',
+ refusedProtected: (name: string) =>
+ `${name} не может использовать эту папку: в ней хранятся настройки, ключи или данные плагинов Hermes. Выберите папку, в которой их нет.`,
+ loadFailed: (name: string) => `Не удалось загрузить папки, открытые для ${name}.`
+ }
+} satisfies NonNullable<NonNullable<TranslationOverrides['skills']>['plugins']>
diff --git a/apps/desktop/src/i18n/types_plugin_update.ts b/apps/desktop/src/i18n/types_plugin_update.ts
index 2e587b47212..a1e8c4e2770 100644
--- a/apps/desktop/src/i18n/types_plugin_update.ts
+++ b/apps/desktop/src/i18n/types_plugin_update.ts
@@ -1,5 +1,22 @@
-/** Copy for updating an installed plugin (Plugins tab): catalog re-pin consent and the security-scan override. */
+/** Plugins tab copy for the folders a plugin may use (`ctx.files`): the app's
+ * picker, the per-plugin grant list and its Revoke action. */
+export interface PluginFolderAccessTranslations {
+ title: string
+ hint: (name: string) => string
+ revoke: string
+ revokeLabel: (path: string) => string
+ revoked: (name: string, path: string) => string
+ revokeFailed: (name: string) => string
+ pickerTitle: (name: string) => string
+ pickerButton: string
+ refusedProtected: (name: string) => string
+ loadFailed: (name: string) => string
+}
+
+/** Copy for updating an installed plugin (Plugins tab): catalog re-pin consent and the security-scan override,
+ * plus the plugin's folder access. */
export interface PluginUpdateTranslations {
+ folderAccess: PluginFolderAccessTranslations
updateToPin: (sha: string) => string
updateFailed: (name: string) => string
updated: (name: string) => string
diff --git a/apps/desktop/src/i18n/zh-hant_capabilities.ts b/apps/desktop/src/i18n/zh-hant_capabilities.ts
index 89574c6d613..44f9a85a16b 100644
--- a/apps/desktop/src/i18n/zh-hant_capabilities.ts
+++ b/apps/desktop/src/i18n/zh-hant_capabilities.ts
@@ -5,7 +5,20 @@ export const zhHantCapabilities = {
skills: {
plugins: {
...zhHantPluginPreviewAccess,
- pageBlurb: '外掛可以擴充本應用程式、代理,或兩者 — 每一部分都有自己的開關。'
+ pageBlurb: '外掛可以擴充本應用程式、代理,或兩者 — 每一部分都有自己的開關。',
+ folderAccess: {
+ title: '資料夾存取',
+ hint: (name: string) => `${name} 可以讀取和修改這些資料夾中的檔案。撤銷後立即生效。`,
+ revoke: '撤銷',
+ revokeLabel: (path: string) => `撤銷對 ${path} 的存取`,
+ revoked: (name: string, path: string) => `${name} 已無法再使用 ${path}。`,
+ revokeFailed: (name: string) => `無法撤銷 ${name} 的資料夾存取`,
+ pickerTitle: (name: string) => `為 ${name} 選擇資料夾`,
+ pickerButton: '允許存取',
+ refusedProtected: (name: string) =>
+ `${name} 不能使用該資料夾:其中包含 Hermes 的設定、金鑰或外掛資料。請選擇不包含它們的資料夾。`,
+ loadFailed: (name: string) => `無法載入與 ${name} 共用的資料夾。`
+ }
},
hub: {
search: '搜尋',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index f5a1b1dd702..c61f1f8479b 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -15,6 +15,7 @@ import { zhNotices } from './zh_notices'
import { zhNotifications } from './zh_notifications'
import { zhOnboarding } from './zh_onboarding'
import { zhPluginPreviewAccess } from './zh_plugin_preview_access'
+import { zhPluginUpdate } from './zh_plugin_update'
import { zhProjects } from './zh_projects'
import { zhSharedMetrics } from './zh_shared_metrics'
import { zhThemePicker } from './zh_theme_picker'
@@ -2081,9 +2082,7 @@ export const zhOverrides = {
catalogProvenance: (sha: string) => `从 Hermes 目录安装${sha ? `,固定提交 ${sha}` : ''}。`,
pinnedProvenance: (sha: string) => `已固定到提交 ${sha}。重新固定前将拒绝更新。`,
pinnedBadge: (sha: string) => `固定 @ ${sha}`,
- updateToPin: (sha: string) => `更新到 ${sha}`,
- updateFailed: (name: string) => `无法更新 ${name}`,
- updated: (name: string) => `${name} 已更新到当前目录固定提交。重启网关后生效。`,
+ ...zhPluginUpdate,
uninstall: '卸载',
uninstallTip: (name: string, profile: string) => `从 ${profile} 卸载 ${name}`,
uninstallConfirmTitle: (name: string) => `卸载 ${name}?`,
diff --git a/apps/desktop/src/i18n/zh_plugin_update.ts b/apps/desktop/src/i18n/zh_plugin_update.ts
new file mode 100644
index 00000000000..caf845c0f89
--- /dev/null
+++ b/apps/desktop/src/i18n/zh_plugin_update.ts
@@ -0,0 +1,21 @@
+import type { TranslationOverrides } from './define-locale'
+
+/** Chinese copy for the Plugins tab: updating an installed plugin and the folders it may use. */
+export const zhPluginUpdate = {
+ updateToPin: (sha: string) => `更新到 ${sha}`,
+ updateFailed: (name: string) => `无法更新 ${name}`,
+ updated: (name: string) => `${name} 已更新到当前目录固定提交。重启网关后生效。`,
+ folderAccess: {
+ title: '文件夹访问',
+ hint: (name: string) => `${name} 可以读取和修改这些文件夹中的文件。撤销后立即生效。`,
+ revoke: '撤销',
+ revokeLabel: (path: string) => `撤销对 ${path} 的访问`,
+ revoked: (name: string, path: string) => `${name} 已无法再使用 ${path}。`,
+ revokeFailed: (name: string) => `无法撤销 ${name} 的文件夹访问`,
+ pickerTitle: (name: string) => `为 ${name} 选择文件夹`,
+ pickerButton: '允许访问',
+ refusedProtected: (name: string) =>
+ `${name} 不能使用该文件夹:其中包含 Hermes 的设置、密钥或插件数据。请选择不包含它们的文件夹。`,
+ loadFailed: (name: string) => `无法加载与 ${name} 共享的文件夹。`
+ }
+} satisfies NonNullable<NonNullable<TranslationOverrides['skills']>['plugins']>
diff --git a/apps/desktop/src/sdk/plugin-contract.ts b/apps/desktop/src/sdk/plugin-contract.ts
index 5d79ba13def..9a1ec067393 100644
--- a/apps/desktop/src/sdk/plugin-contract.ts
+++ b/apps/desktop/src/sdk/plugin-contract.ts
@@ -8,6 +8,10 @@ export type {
PluginAppActionInfo,
PluginContext,
PluginContribution,
+ PluginFileEntry,
+ PluginFiles,
+ PluginFilesResult,
+ PluginFolder,
PluginNativeNotificationInput,
PluginNotificationAction,
PluginOs,
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index c47003fed7b..5632e2ce173 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -4832,6 +4832,16 @@
"skills.plugins.empty",
"skills.plugins.emptyAll",
"skills.plugins.emptyHint",
+ "skills.plugins.folderAccess.hint",
+ "skills.plugins.folderAccess.loadFailed",
+ "skills.plugins.folderAccess.pickerButton",
+ "skills.plugins.folderAccess.pickerTitle",
+ "skills.plugins.folderAccess.refusedProtected",
+ "skills.plugins.folderAccess.revoke",
+ "skills.plugins.folderAccess.revokeFailed",
+ "skills.plugins.folderAccess.revokeLabel",
+ "skills.plugins.folderAccess.revoked",
+ "skills.plugins.folderAccess.title",
"skills.plugins.halfAgent",
"skills.plugins.halfAgentIn",
"skills.plugins.halfDesktop",
diff --git a/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md b/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md
index eee55adecb4..cd6374ef5c6 100644
--- a/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md
+++ b/skills/autonomous-ai-agents/hermes-agent/references/desktop-plugins.md
@@ -114,6 +114,14 @@ The ONLY import surface is `@hermes/plugin-sdk` (plus `react` /
After registering one, TELL the model it exists (a bundled skill or the
user's instructions) — it won't discover the name on its own.
- `ctx.storage.get/set/remove` — persistence namespaced to your plugin.
+- `ctx.files` — the only file door: the plugin's own data folder (`'data'`) and
+ folders the user grants through `ctx.files.requestFolder()` (the app's
+ picker; listed and revocable under Capabilities ▸ Plugins). Calls take a
+ folder handle plus a RELATIVE path (`list`, `stat`, `readText`,
+ `readDataUrl`, `writeText(…, { exclusive })`, `rename`, `trash`) and resolve
+ `{ ok, … }` / `{ ok: false, error }`; `..`, absolute paths, escaping
+ symlinks and Hermes' own data are refused by the main process. Never call
+ `window.hermesDesktop` file methods from a plugin.
- `ctx.os` — the curated OS door, attributed to your plugin:
`ctx.os.notify({ title, body?, silent?, icon?, activate?, onActivate?, actions? })`
posts a native OS notification. Fires only while the user is away from Hermes
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 620f9a285d0..e8bae8cbcdd 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -1286,6 +1286,8 @@ ctx.os.notify({ title, body?, silent?, icon?, activate?, onActivate?, actions? }
ctx.os.openExternal(url) // OS default handler (browser, mail, spotify:) → Promise<boolean>
ctx.os.revealPath(path) // reveal in Finder / Explorer → Promise<boolean>
ctx.os.writeClipboard(text) // system clipboard → Promise<boolean>
+ctx.files.requestFolder() // the app's folder picker → { ok, folder: { id, name, path } | null }
+ctx.files.readText(folder, 'notes/a.md') // folder = 'data' or a granted folder's id; path is relative
ctx.pet.say(text, { id?, tone?, ttlMs? }) // line in the core pet's speech bubble → disposer
ctx.pet.clear(id?) // drop one line (or all of yours)
ctx.pet.visible // ReadableAtom<boolean> — is a pet on screen?
@@ -1474,6 +1476,73 @@ The other doors (`openExternal`, `revealPath`, `writeClipboard`) resolve
`false` instead of throwing when the capability isn't available (older desktop
shell, plain browser) — branch on the result rather than sniffing the bridge.
+### Files — `ctx.files` {#plugin-files}
+
+`ctx.files` is the one sanctioned way for a plugin to touch files on the
+computer running Desktop. A plugin reaches exactly two kinds of folder:
+
+- **Its own data folder**, handle `'data'`: private to the plugin, always
+ available, no prompt. Use it for caches, indexes and exports that are too big
+ for `ctx.storage`.
+- **Folders the user granted it**: `ctx.files.requestFolder()` opens the app's
+ own folder picker (titled with your plugin's name; you cannot change its
+ copy). The grant is remembered for your plugin across restarts, listed under
+ your plugin in **Capabilities → Plugins → Folder access**, and the user can
+ revoke it there at any time. Uninstalling the plugin drops its grants.
+
+Every call names a folder handle and a path **relative to that folder**. The
+app's main process checks each call: `..`, absolute paths, drive letters and
+symlinks that resolve outside the folder are refused, never normalized, and
+nothing inside Hermes' own data (the Hermes home with `config.yaml`, `.env`,
+auth and profiles; the app data folder with every plugin's data and the grants
+record) is reachable. A folder that holds or sits inside Hermes data (however
+it is spelled: a bind mount, a macOS firmlink, a WSL share or a
+`\\localhost\C$` share counts), a key folder such as `~/.ssh`, or a kernel
+filesystem such as `/proc` (wherever it is mounted) cannot be granted at all;
+the app tells the user why. Only plain files are read or written: a pipe, a
+device or a hard-linked file is refused, and a file swapped for a link between
+the app's check and its open is refused rather than followed.
+
+```ts
+// First run: ask once, remember the handle.
+let vault = (await ctx.files.folders())[0]
+if (!vault) {
+ const picked = await ctx.files.requestFolder()
+ if (!picked.ok || !picked.folder) return // cancelled, refused, or an older app
+ vault = picked.folder
+}
+
+const listing = await ctx.files.list(vault.id, 'notes') // { ok, entries: [{ name, path, isDirectory }], truncated }
+const note = await ctx.files.readText(vault.id, 'notes/a.md') // { ok, text, size, mtimeMs }
+await ctx.files.writeText(vault.id, 'notes/b.md', '# B\n', { exclusive: true }) // refuses to replace a file
+await ctx.files.rename(vault.id, 'notes/b.md', 'c.md') // same folder only
+await ctx.files.trash(vault.id, 'notes/c.md') // OS trash, recoverable
+await ctx.files.readDataUrl(vault.id, 'img/cover.png') // { ok, url: 'data:image/png;base64,…' }
+await ctx.files.stat(vault.id, 'notes/a.md') // { ok, exists, isDirectory?, size?, mtimeMs? }
+await ctx.files.writeText('data', 'index.json', JSON.stringify(index))
+await ctx.files.release(vault.id) // give the folder back
+```
+
+No member throws. `dataFolder` is the string `'data'`; `folders()` resolves
+an array of `{ id, name, path }` (empty when the app has no door);
+`release(id)` resolves `true` when it gave a folder back and `false`
+otherwise. Every other member resolves `{ ok: true, … }` or
+`{ ok: false, error, message }`, where `error` is one of `invalid-path`, `outside-folder`, `protected`,
+`not-granted` (revoked, or another plugin's folder), `folder-missing`,
+`folder-changed` (the granted folder was moved or replaced: ask again),
+`not-found`, `exists`, `is-directory`, `not-a-directory`, `not-a-file`,
+`binary`, `too-large`, `sensitive-file` (`.env`, SSH keys and similar are
+refused even inside a granted folder, under any spelling the OS treats as the
+same name, and cannot be renamed or trashed),
+`io-error`, or `unavailable` (an app build without
+the door: feature-detect with `ctx.files?.…`). Limits: text reads and writes up
+to 4 MiB, data URLs up to 16 MiB, listings up to 10,000 entries. Reads are
+refused past the limit, never truncated. A write needs its parent folder to
+exist.
+
+Paths are on the machine running Desktop, not on a remote backend. To work
+with the backend's files, go through your plugin's `ctx.rest` routes.
+
### Pet bubble — `ctx.pet` {#pet-bubble}
The core pet (the petdex mascot, in-window or popped out into its own OS
@@ -2188,6 +2257,9 @@ const tab = ctx.storage.get('lastTab', 'summary')
ctx.storage.remove('lastTab')
```
+For files (a vault, a notes folder, exports) use [`ctx.files`](#plugin-files):
+your own data folder plus folders the user grants you.
+
## Bundled plugins
A plugin can ship in-tree at `apps/desktop/src/plugins/<id>/plugin.tsx` (default
@@ -2226,7 +2298,12 @@ or dynamic `import` of anything else, including `https:` URLs, fails the load).
Neither is a sandbox. Doors that touch user data outside the app are gated
on top of that: `ctx.preview.executeJavaScript` needs a declared capability
and the user's per-origin consent ([Preview page scripts](#preview-page-scripts)).
-A future remote-source door will need a real boundary
+File access follows the same rule: a catalog plugin
+should read and write through [`ctx.files`](#plugin-files), not the raw
+`window.hermesDesktop` file bridge. `ctx.files` is enforced in the main
+process, so a plugin that uses it (or untrusted text it handles, such as a
+note name from the model) cannot leave the folders the user granted; the raw
+bridge has no such limit, which is why catalog review asks for `ctx.files`. A future remote-source door will need a real boundary
(iframe/worker + CSP + capability gating) before it can land; do not treat this
pipeline as a trust boundary.
@@ -2269,7 +2346,7 @@ pipeline as a trust boundary.
| Category | Exports |
|----------|---------|
| Host | `host` (`.state.*`, `.settings`, `.notify`, `.notifyError`, `.navigate`, `.onEvent`, `.logs`, `.status`, `.restartGateway`, `.request`, `.composer`, `.spellcheck`, `.sessions`, `.skills`, `.toolsets`, `.profiles`, `.pluginDecisions`) |
-| Plugin contract | `HermesPlugin`, `PluginContext`, `PluginContribution`, `PluginStorage`, `PluginOs`, `PluginPet`, `PetSayOptions`, `PetMessageTone`, `PluginAppActionId`, `PluginAppActionInfo`, `PluginRunActionResult`, `PLUGIN_APP_ACTIONS`, `PluginRestOptions`, `PluginNativeNotificationInput`, `PluginNotificationAction`, `HermesOpenTarget`, `Contribution` |
+| Plugin contract | `HermesPlugin`, `PluginContext`, `PluginContribution`, `PluginStorage`, `PluginFiles`, `PluginFolder`, `PluginFileEntry`, `PluginFilesResult`, `PluginOs`, `PluginPet`, `PetSayOptions`, `PetMessageTone`, `PluginAppActionId`, `PluginAppActionInfo`, `PluginRunActionResult`, `PLUGIN_APP_ACTIONS`, `PluginRestOptions`, `PluginNativeNotificationInput`, `PluginNotificationAction`, `HermesOpenTarget`, `Contribution` |
| Area constants | `PANES_AREA`, `ROUTES_AREA`, `SIDEBAR_NAV_AREA`, `STATUSBAR_AREAS`, `TITLEBAR_AREAS`, `WORKSPACE_PAGE_HEADER_AREA`, `PALETTE_AREA`, `KEYBINDS_AREA`, `THEMES_AREA`, `COMPOSER_AREAS`, `MODEL_MENU_ROW_AREA`, `KANBAN_CARD_AREAS`, `SESSION_ROW_AREAS`, `SIDEBAR_NAV_PREFS_AREA`, `APPEARANCE_AREAS`, `SETTINGS_PLUGINS_AREA` |
| Area payloads | `PluginSettingsPage`, `PluginSettingsSubpage` (+ `pluginSettingsHref`), `RouteContribution`, `SidebarNavContribution`, `StatusbarItem`, `TitlebarTool`, `PaletteContribution`, `KeybindContribution`, `ComposerMiddleware`, `ComposerAttachmentProvider`, `ComposerContextMenuProvider` (+ `ComposerContextMenuItem`, `ComposerContextMenuContext`, `ComposerContextMenuAction`), `SessionRowSlotContribution`, `KanbanCardBadgeContribution` (+ `KanbanCard`, `KanbanCardBoard`, `KanbanCardBadge`, `KanbanCardBadgeTone`, `KANBAN_CARD_BADGE_HUES`, `KANBAN_CARD_BADGE_LIMITS`), `SidebarNavPrefsContribution` |
| React / state | `useValue`, `atom`, `computed`, `useQuery`, `useMutation`, `useQueryClient`, `queryClient`, `Contribute`, `WorkspacePageHeaderControl` |