Skip to content

The agent that grows with you

fix(desktop): a native plugin install never replaces a folder outside desktop-plugins

kshitijk4poor00953653cffd
diff --git a/apps/desktop/electron/desktop-plugin-install.test.ts b/apps/desktop/electron/desktop-plugin-install.test.ts
index c80d4d6040c..03dd38541c5 100644
--- a/apps/desktop/electron/desktop-plugin-install.test.ts
+++ b/apps/desktop/electron/desktop-plugin-install.test.ts
@@ -370,6 +370,95 @@ describe('installDesktopPluginFromGit', () => {
expect(fs.readdirSync(path.join(appRoot, result.pluginName!)).sort()).toEqual(['asset.bin', 'plugin.js'])
}, 60_000)
+ it.each(['..', 'C:..', 'a/b', 'nul .js', 'C:foo', '.hidden', 'gizmo.', 'x'.repeat(129)])(
+ 'refuses a package named %s on a forced install and deletes nothing',
+ async name => {
+ // The folder name comes from the package's manifest: `..` would make a forced install replace
+ // the Hermes home that holds desktop-plugins/.
+ const repo = pluginRepo(name)
+ const home = mkdtemp('hermes-home-')
+ roots.push(home)
+ const appRoot = path.join(home, 'desktop-plugins')
+ fs.mkdirSync(appRoot)
+ fs.writeFileSync(path.join(home, 'config.yaml'), 'keep\n')
+
+ const result = await installDesktopPluginFromGit('git', pathToFileURL(repo).href, appRoot, true)
+
+ expect(fs.readFileSync(path.join(home, 'config.yaml'), 'utf8')).toBe('keep\n')
+ expect(result.ok).toBe(false)
+ expect(result.error).toContain('is not a desktop plugin folder name')
+ expect(fs.readdirSync(appRoot)).toEqual([])
+ }
+ )
+
+ it('refuses a plugin.json name with a long inner run of spaces without stalling', async () => {
+ // Stripping the trailing run must stay linear: this name is repository-controlled, and the
+ // check runs synchronously in the main process. A quadratic strip takes about 30 s here.
+ const repo = pluginRepo(null)
+ fs.writeFileSync(path.join(repo, 'plugin.json'), JSON.stringify({ name: 'a' + ' '.repeat(200_000) + 'b' }))
+ execFileSync('git', ['add', '-A'], { cwd: repo, stdio: 'pipe' })
+ execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=F', 'commit', '-qm', 'manifest'], {
+ cwd: repo,
+ stdio: 'pipe'
+ })
+ const appRoot = mkdtemp('hermes-plugin-root-')
+ roots.push(appRoot)
+
+ const result = await installDesktopPluginFromGit('git', pathToFileURL(repo).href, appRoot)
+
+ expect(result.ok).toBe(false)
+ expect(result.error).toContain('is not a desktop plugin folder name')
+ expect(fs.readdirSync(appRoot)).toEqual([])
+ }, 10_000)
+
+ it('names the package marker after the folder when a plugin.json name has outer spaces', async () => {
+ // The folder name is trimmed; a marker naming the untrimmed package would not pair with that folder.
+ const repo = pluginRepo(null)
+ fs.writeFileSync(path.join(repo, 'plugin.json'), JSON.stringify({ name: ' spaced ' }))
+ execFileSync('git', ['add', '-A'], { cwd: repo, stdio: 'pipe' })
+ execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=F', 'commit', '-qm', 'manifest'], {
+ cwd: repo,
+ stdio: 'pipe'
+ })
+ const appRoot = mkdtemp('hermes-plugin-root-')
+ roots.push(appRoot)
+
+ const result = await installDesktopPluginFromGit('git', pathToFileURL(repo).href, appRoot)
+
+ expect(result).toMatchObject({ ok: true, pluginName: 'spaced' })
+ const marker = JSON.parse(fs.readFileSync(path.join(appRoot, 'spaced', PACKAGE_MARKER), 'utf8'))
+ expect(marker.package).toBe('spaced')
+ })
+
+ it.each([
+ // 79 code points (the 128 cap counts code points, as Python's len() does), 129 UTF-16 units, 229 UTF-8 bytes.
+ [
+ 'a non-BMP name over 128 UTF-16 units',
+ '\u{1F600}'.repeat(50) + 'x'.repeat(29),
+ '\u{1F600}'.repeat(50) + 'x'.repeat(29)
+ ],
+ // Trimmed like Python's str.strip(): U+FEFF is kept, U+0085 and U+001C are stripped.
+ ['a BOM-prefixed name', '\ufeffgizmo', '\ufeffgizmo'],
+ ['a name wrapped in NEL and U+001C', '\x85gizmo\x1c', 'gizmo']
+ ])('installs %s under the folder the agent side picks', async (_label, name, folder) => {
+ const repo = pluginRepo(null)
+ fs.writeFileSync(path.join(repo, 'plugin.json'), JSON.stringify({ name }))
+ execFileSync('git', ['add', '-A'], { cwd: repo, stdio: 'pipe' })
+ execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=F', 'commit', '-qm', 'manifest'], {
+ cwd: repo,
+ stdio: 'pipe'
+ })
+ const appRoot = mkdtemp('hermes-plugin-root-')
+ roots.push(appRoot)
+
+ const result = await installDesktopPluginFromGit('git', pathToFileURL(repo).href, appRoot)
+
+ expect(result).toMatchObject({ ok: true, pluginName: folder })
+ expect(fs.readdirSync(appRoot)).toEqual([folder])
+ const marker = JSON.parse(fs.readFileSync(path.join(appRoot, folder, PACKAGE_MARKER), 'utf8'))
+ expect(marker.package).toBe(folder)
+ })
+
it('stamps the package marker on a unified package half and names the folder after the agent package', async () => {
// Without the marker the Plugins page has no evidence that this copy is the
// agent row's desktop half: the row sits on "copying…" while the copy shows
diff --git a/apps/desktop/electron/desktop-plugin-install.ts b/apps/desktop/electron/desktop-plugin-install.ts
index a3aa6b8bc50..784d4c95c43 100644
--- a/apps/desktop/electron/desktop-plugin-install.ts
+++ b/apps/desktop/electron/desktop-plugin-install.ts
@@ -21,6 +21,7 @@ import {
writeDesktopHalfMarker
} from './desktop-plugins-root'
import { execGit, hiddenGitSpawnSpec } from './no-console-git'
+import { stripLikePython, WIN_RESERVED_RE } from './plugin-files-guards'
const GITHUB_BROWSER_SEGMENTS = new Set(['tree', 'blob', 'commit'])
@@ -137,6 +138,30 @@ export function repoNameFromUrl(url: string): string {
return name
}
+/** *name* when it can be one folder directly under the desktop-plugins root, else throw. It comes from
+ * the repository (a manifest's `name`, a subdirectory's last segment), so it must never reach a path
+ * unchecked: `..` would make a forced install replace the Hermes home. No separators, no leading dot
+ * (the root's staging folders use it), and none of the names Windows reads as something else (a colon
+ * makes `C:..` drive-relative, a device name opens the device, a trailing dot is dropped). The agent
+ * side's `_checked_name` refuses the same names (#146394). */
+export function checkedDesktopFolderName(name: string): string {
+ const candidate = stripLikePython(name)
+
+ if (
+ !candidate ||
+ candidate.startsWith('.') ||
+ candidate.endsWith('.') ||
+ /[/\\:]/.test(candidate) ||
+ [...candidate].some(char => char.charCodeAt(0) < 32) ||
+ [...candidate].length > 128 ||
+ WIN_RESERVED_RE.test(candidate.split('.', 1)[0].replace(/ +$/, ''))
+ ) {
+ throw new Error(`'${name}' is not a desktop plugin folder name: it must be a plain folder name, not a path.`)
+ }
+
+ return candidate
+}
+
/** Stable on-disk folder for a desktop plugin. Never the clone temp dir or a generic `desktop/` folder. */
export function desktopPluginFolderName(gitUrl: string, subdir: string | null): string {
if (subdir) {
@@ -528,7 +553,7 @@ export async function installDesktopPluginFromGit(
// and the Plugins page pairs them into one row. A desktop-only repo keeps
// the git-derived folder name and stays a standalone plugin.
const packageName = detected.agent ? (detected.agentName ?? desktopPluginFolderName(gitUrl, subdir)) : null
- const pluginName = packageName ?? desktopPluginFolderName(gitUrl, subdir)
+ const pluginName = checkedDesktopFolderName(packageName ?? desktopPluginFolderName(gitUrl, subdir))
const targetDir = path.join(desktopPluginsRoot, pluginName)
const targetPlugin = path.join(targetDir, 'plugin.js')
@@ -565,7 +590,7 @@ export async function installDesktopPluginFromGit(
}
await writeDesktopHalfMarker(staged, {
- package: packageName,
+ package: pluginName,
repo: gitUrl,
// The published folder, not the temp clone. The clone is deleted
// below; a source that disappears is ghost-pruned on the next
diff --git a/apps/desktop/electron/desktop-plugin-remove.test.ts b/apps/desktop/electron/desktop-plugin-remove.test.ts
index f738dc8e1b0..540e5cafe96 100644
--- a/apps/desktop/electron/desktop-plugin-remove.test.ts
+++ b/apps/desktop/electron/desktop-plugin-remove.test.ts
@@ -66,6 +66,24 @@ describe('removeDesktopPlugin', () => {
expect(fs.existsSync(path.join(root, 'hello', 'plugin.js'))).toBe(true)
})
+ it.each([
+ // An existing folder's exact name removes that folder, never its trimmed `gizmo` neighbour; any other
+ // name is trimmed like the installer (Python's str.strip()): U+FEFF kept, U+0085 and U+001C stripped.
+ ['a BOM-prefixed name', '\ufeffgizmo', '\ufeffgizmo', 'gizmo'],
+ ['an existing folder ending in NEL', 'gizmo\x85', 'gizmo\x85', 'gizmo'],
+ ['an existing folder with outer spaces', ' gizmo ', ' gizmo ', 'gizmo'],
+ ['a name wrapped in NEL and U+001C with no such folder', '\x85gizmo\x1c', 'gizmo', '\ufeffgizmo']
+ ])('removes %s as the matching folder', async (_label, name, folder, neighbour) => {
+ const { root } = makeRoot()
+ write(path.join(root, folder, 'plugin.js'), 'export default {}')
+ write(path.join(root, neighbour, 'plugin.js'), 'export default {}')
+
+ const result = await removeDesktopPlugin(root, name)
+
+ expect(result).toEqual({ ok: true, path: path.join(root, folder) })
+ expect(fs.readdirSync(root)).toEqual([neighbour])
+ })
+
it('refuses a unified package half (marker present) and a missing folder', async () => {
const { root } = makeRoot()
write(path.join(root, 'uni', 'plugin.js'), 'export default {}')
diff --git a/apps/desktop/electron/desktop-plugin-remove.ts b/apps/desktop/electron/desktop-plugin-remove.ts
index a654a54c996..f719f1d4ea6 100644
--- a/apps/desktop/electron/desktop-plugin-remove.ts
+++ b/apps/desktop/electron/desktop-plugin-remove.ts
@@ -11,6 +11,7 @@ import fs from 'node:fs'
import path from 'node:path'
import { PACKAGE_MARKER, withDesktopPluginsRoot } from './desktop-plugins-root'
+import { stripLikePython } from './plugin-files-guards'
export interface RemoveDesktopPluginResult {
ok: boolean
@@ -25,14 +26,29 @@ export function removeDesktopPlugin(appRoot: string, rawName: unknown): Promise<
return withDesktopPluginsRoot(appRoot, () => removeFolder(appRoot, rawName))
}
+function isSingleSegment(name: string): boolean {
+ return Boolean(name) && name !== '.' && name !== '..' && !/[\\/]/.test(name)
+}
+
async function removeFolder(appRoot: string, rawName: unknown): Promise<RemoveDesktopPluginResult> {
- const name = String(rawName ?? '').trim()
+ const root = path.resolve(appRoot)
+ const raw = String(rawName ?? '')
- if (!name || name === '.' || name === '..' || /[\\/]/.test(name)) {
+ // An existing folder's exact name removes that folder (one an older version named differently, or copied in
+ // by hand); any other name is trimmed as the installer trims the folder name it creates.
+ const exists =
+ isSingleSegment(raw) &&
+ (await fs.promises.lstat(path.join(root, raw)).then(
+ () => true,
+ () => false
+ ))
+
+ const name = exists ? raw : stripLikePython(raw)
+
+ if (!isSingleSegment(name)) {
return { ok: false, error: 'invalid plugin folder name' }
}
- const root = path.resolve(appRoot)
const target = path.resolve(root, name)
if (path.relative(root, target) !== name) {
diff --git a/apps/desktop/electron/plugin-files-guards.ts b/apps/desktop/electron/plugin-files-guards.ts
index b1875869b48..8456617a9ce 100644
--- a/apps/desktop/electron/plugin-files-guards.ts
+++ b/apps/desktop/electron/plugin-files-guards.ts
@@ -16,7 +16,17 @@ const SEGMENT_MAX = 255
// 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
+export const WIN_RESERVED_RE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$|clock\$)(?:\.|$)/i
+// Python's str.strip() set (what the agent side's `_checked_name` trims). JS trim() differs: it also
+// strips U+FEFF and keeps U+001C-U+001F and U+0085, so the two sides would name different folders.
+const PY_STRIP_WS = '\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000'
+// The trailing run must start after a non-space: a bare `[ws]+$` retries from every space of an
+// inner run, which is quadratic in a repository-controlled name and blocks the main process.
+const PY_STRIP_RE = new RegExp(`^[${PY_STRIP_WS}]+|(?<![${PY_STRIP_WS}])[${PY_STRIP_WS}]+$`, 'g')
+
+/** *text* without the leading and trailing whitespace Python's `str.strip()` removes, in linear time.
+ * Desktop plugin folder names go through this on install and on remove, so both agree with the agent side. */
+export const stripLikePython = (text: string): string => text.replace(PY_STRIP_RE, '')
// 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']