Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(node-icon): accept Windows paths, and close the backslash traversal hole
albaneselorenzofee5b244815f
diff --git a/src/renderer/components/NodeIconPicker.test.tsx b/src/renderer/components/NodeIconPicker.test.tsxnew file mode 100644index 000000000..33cb76f67--- /dev/null+++ b/src/renderer/components/NodeIconPicker.test.tsx@@ -0,0 +1,131 @@+// @vitest-environment jsdom+//+// The picker's image path, on a machine that is not a mac.+//+// Two things are pinned here and both were review findings on #293:+//+// 1. **The extension is checked BEFORE the copy.** `selectFile` applies no filter, so an+// unsupported file is one click away — and validating after `saveCanvasImage` meant the bytes+// were already written into the project's git-shared `.nodeterm/images/`. Nothing removes+// them afterwards, so every refusal left a file behind in the user's repo.+//+// 2. **A Windows path from `saveCanvasImage` is usable.** `saveCanvasImage` answers with the+// host's own `path.join`, i.e. `C:\...` on Windows. The old POSIX-only `startsWith('/')`+// check refused it, and `chooseImage` then reported "that file type cannot be used" about a+// perfectly good PNG — sending Windows users after a format problem that did not exist.+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { NodeIconDialogHost, nodeIconDialog, type NodeIconChoice } from './NodeIconPicker'+import { useProjects } from '../state/projects'++// React refuses act() outside a configured test environment without this flag.+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const selectFile = vi.fn<() => Promise<string | null>>()+const readBinary = vi.fn<(path: string) => Promise<string | null>>()+// Arguments are FORWARDED, not swallowed: the name this is called with is itself under test+// (`iconFileName` vs the old `split('/')`), and a mock that drops its args cannot fail for it.+const saveCanvasImage =+ vi.fn<(projectId: string, name: string, b64: string) => Promise<string | null>>()++vi.mock('../session/session', () => ({+ sessionForProject: () => ({+ api: {+ dialog: { selectFile: () => selectFile() },+ fs: { readBinary: (p: string) => readBinary(p) },+ files: {+ saveCanvasImage: (id: string, name: string, b64: string) =>+ saveCanvasImage(id, name, b64)+ }+ }+ })+}))++const PROJECT = { id: 'p1', name: 'proj', color: '#888', cwd: 'C:\\proj', viewport: {}, nodes: [] }++/** Click "Choose image…" and let the promise chain inside `chooseImage` settle. */+async function clickChooseImage(): Promise<void> {+ const button = [...document.querySelectorAll('button')].find(+ (b) => b.textContent?.startsWith('Choose image')+ )+ expect(button).toBeTruthy()+ await act(async () => {+ button!.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ })+}++const errorText = (): string =>+ document.querySelector('.node-icon-dialog__error')?.textContent ?? ''++describe('NodeIconPicker image pick', () => {+ let root: Root | undefined+ let host: HTMLElement+ let choice: Promise<NodeIconChoice>++ beforeEach(async () => {+ vi.clearAllMocks()+ host = document.createElement('div')+ document.body.appendChild(host)+ useProjects.setState({+ activeProjectId: 'p1',+ getProject: () => PROJECT+ } as never)+ choice = nodeIconDialog({ nodeId: 'n1', title: 'Build' })+ root = createRoot(host)+ await act(async () => {+ root!.render(<NodeIconDialogHost />)+ })+ })++ afterEach(async () => {+ await act(async () => root?.unmount())+ root = undefined+ host.remove()+ // Every test resolves the dialog so the module-level singleton does not leak into the next.+ void choice+ })++ it('refuses an unsupported file WITHOUT copying it into the project', async () => {+ selectFile.mockResolvedValue('C:\\Users\\me\\photo.heic')+ await clickChooseImage()++ expect(saveCanvasImage).not.toHaveBeenCalled()+ // Not even read: there is nothing to do with the bytes once the extension is refused.+ expect(readBinary).not.toHaveBeenCalled()+ expect(errorText()).toContain('cannot be used as an icon')+ })++ it('accepts a Windows path and names the copy after the file, not the whole path', async () => {+ selectFile.mockResolvedValue('C:\\Users\\me\\logo.png')+ readBinary.mockResolvedValue('aGVsbG8=')+ saveCanvasImage.mockResolvedValue('C:\\proj\\.nodeterm\\images\\logo.png')+ await clickChooseImage()++ // The COPY is named after the file, not the whole path. `split('/')` on a Windows path+ // returns it whole, so the saved file was named `C:\\Users\\me\\logo.png` and only+ // `safeUploadName` stopped that being a directory escape.+ expect(saveCanvasImage).toHaveBeenCalledWith('p1', 'logo.png', 'aGVsbG8=')+ expect(errorText()).toBe('')+ // Inside the project root, so it is stored `./`-relative and POSIX-separated: the icon+ // travels with the repo that names it.+ await expect(choice).resolves.toEqual({+ type: 'image',+ path: './.nodeterm/images/logo.png'+ })+ })++ it('keeps a Windows path outside the project absolute rather than refusing it', async () => {+ selectFile.mockResolvedValue('C:\\Users\\me\\logo.png')+ readBinary.mockResolvedValue('aGVsbG8=')+ // The app-local fallback `saveCanvasImage` takes when the project folder will not accept it.+ saveCanvasImage.mockResolvedValue('C:\\Users\\me\\AppData\\nodeterm\\canvas-images\\logo.png')+ await clickChooseImage()++ expect(errorText()).toBe('')+ await expect(choice).resolves.toEqual({+ type: 'image',+ path: 'C:\\Users\\me\\AppData\\nodeterm\\canvas-images\\logo.png'+ })+ })+})diff --git a/src/renderer/components/NodeIconPicker.tsx b/src/renderer/components/NodeIconPicker.tsxindex 38eccd6ac..79fcfacca 100644--- a/src/renderer/components/NodeIconPicker.tsx+++ b/src/renderer/components/NodeIconPicker.tsx@@ -24,7 +24,13 @@import { useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { create } from 'zustand'-import { type NodeIcon, normalizeNodeIcon, portableIconPath } from '@shared/node-icon'+import {+ iconFileName,+ type NodeIcon,+ nodeIconMime,+ normalizeNodeIcon,+ portableIconPath+} from '@shared/node-icon'import { canvasImportRefusal } from '../canvas/canvas-image-import'import { useProjects } from '../state/projects'import { sessionForProject } from '../session/session'@@ -134,6 +140,15 @@ function NodeIconPicker({const api = sessionForProject(project.id).apiconst picked = await api.dialog.selectFile()if (!picked) return+ // Checked BEFORE the copy, not after it. `selectFile` applies no filter, so a .heic is one+ // click away — and validating afterwards meant the bytes had already been written into the+ // project's git-shared `.nodeterm/images/`, leaving an orphan file behind every refusal.+ // Nothing later removes it: `saveCanvasImage` creates exclusively, so the next pick would sit+ // beside it as `photo (2).heic`.+ if (!nodeIconMime(picked)) {+ setError('That file type cannot be used as an icon. Try PNG, JPEG, GIF, WEBP or SVG.')+ return+ }setBusy(true)try {const b64 = await api.fs.readBinary(picked)@@ -141,7 +156,10 @@ function NodeIconPicker({setError('Could not read that file.')return}- const name = picked.split('/').pop() || 'icon.png'+ // Both separators, because `selectFile` answers in the HOST's dialect: on Windows it is+ // `C:\\Users\\me\\logo.png`, which `split('/')` returned whole — so the copy was named after+ // the entire path and `safeUploadName` then had to salvage it.+ const name = iconFileName(picked) || 'icon.png'const saved = await api.files.saveCanvasImage(project.id, name, b64)if (!saved) {setError('Could not save the image — check that this project’s folder is writable.')@@ -153,9 +171,12 @@ function NodeIconPicker({const stored = portableIconPath(saved, project.ssh ? undefined : project.cwd)const next = normalizeNodeIcon({ type: 'image', path: stored })if (!next) {- // Reachable when the picked file has an extension we do not render (a .heic, say). Saying- // which formats work is more use than "invalid".- setError('That file type cannot be used as an icon. Try PNG, JPEG, GIF, WEBP or SVG.')+ // The extension was already accepted above, so this is no longer "wrong file type" — it+ // means the SAVED path is one the validator will not vouch for (a UNC share, a path with+ // no root). Blaming the file type here is what sent Windows users hunting for a format+ // problem that did not exist: `saveCanvasImage` returns `C:\\...`, which the old+ // POSIX-only check refused.+ setError('Could not use that file’s location as an icon path.')return}onDone(next)diff --git a/src/shared/node-icon.test.ts b/src/shared/node-icon.test.tsindex 638eeb74c..9f80cbf57 100644--- a/src/shared/node-icon.test.ts+++ b/src/shared/node-icon.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'import {+ iconFileName,nodeIconMime,normalizeNodeIcon,portableIconPath,@@ -175,3 +176,92 @@ describe('portable round trip', () => {}})})++// The path seams, on a machine that is not the one that wrote the value. `.nodeterm/project.json`+// is git-shared, so a Windows teammate's icon reaches a mac's serializer and back; and a hostile+// value written for Windows is CHECKED here, wherever "here" happens to be. Both directions are+// pinned, because getting either wrong is silent: one deletes a colleague's icons, the other+// leaves the project root escapable.+describe('path dialects', () => {+ it('keeps a Windows drive-absolute path, so a mac save does not strip a colleague’s icon', () => {+ for (const path of ['C:\\Users\\me\\proj\\.nodeterm\\images\\a.png', 'D:/work/b.jpg']) {+ expect(normalizeNodeIcon({ type: 'image', path })).toEqual({ type: 'image', path })+ }+ })++ it('refuses a UNC path — reading one reaches another machine over the network', () => {+ for (const path of ['\\\\host\\share\\a.png', '//host/share/a.png']) {+ expect(normalizeNodeIcon({ type: 'image', path })).toBeUndefined()+ }+ })++ it('refuses a drive-RELATIVE path, which has no root of its own to resolve against', () => {+ expect(normalizeNodeIcon({ type: 'image', path: 'C:a.png' })).toBeUndefined()+ })++ // The one that was broken: `\` was not a separator here, so this was a single segment that was+ // neither '', '.' nor '..' — it passed on every platform and escaped the project on Windows.+ it('refuses a relative path that traverses out via BACKSLASH separators', () => {+ for (const path of [+ './a\\..\\..\\secret.png',+ '.\\..\\..\\secret.png',+ './sub\\..\\..\\..\\etc\\passwd.png'+ ]) {+ expect(normalizeNodeIcon({ type: 'image', path })).toBeUndefined()+ }+ })++ it('refuses a relative segment carrying a drive qualifier or an NTFS data stream', () => {+ expect(normalizeNodeIcon({ type: 'image', path: './C:/Windows/a.png' })).toBeUndefined()+ expect(normalizeNodeIcon({ type: 'image', path: './icon.png:payload.png' })).toBeUndefined()+ })++ it('canonicalizes a relative path to one stored dialect, so its next reader is not guessing', () => {+ expect(normalizeNodeIcon({ type: 'image', path: '.\\images\\a.png' })).toEqual({+ type: 'image',+ path: './images/a.png'+ })+ })++ it('relativizes under a Windows project root, and stores it POSIX-separated', () => {+ expect(portableIconPath('C:\\proj\\.nodeterm\\images\\a.png', 'C:\\proj')).toBe(+ './.nodeterm/images/a.png'+ )+ // A trailing separator on the root is not a reason to give up on portability.+ expect(portableIconPath('C:\\proj\\images\\a.png', 'C:\\proj\\')).toBe('./images/a.png')+ })++ it('leaves a Windows path outside the project absolute', () => {+ expect(portableIconPath('C:\\other\\a.png', 'C:\\proj')).toBe('C:\\other\\a.png')+ })++ it('resolves a ./ path against a Windows root', () => {+ expect(resolveIconPath('./images/a.png', 'C:\\proj')).toBe('C:\\proj/images/a.png')+ })++ it('survives store -> normalize -> resolve on Windows', () => {+ const abs = 'C:\\proj\\.nodeterm\\images\\a.png'+ const cwd = 'C:\\proj'+ const stored = portableIconPath(abs, cwd)+ const icon = normalizeNodeIcon({ type: 'image', path: stored })+ expect(icon).toBeDefined()+ // Same FILE as `abs`; Node accepts forward slashes on Windows, so the spelling differs and+ // the target does not.+ expect(resolveIconPath((icon as { path: string }).path, cwd)).toBe(+ 'C:\\proj/.nodeterm/images/a.png'+ )+ })+})++describe('iconFileName', () => {+ it('answers the last segment in either dialect', () => {+ expect(iconFileName('/a/b/c.png')).toBe('c.png')+ expect(iconFileName('C:\\Users\\me\\logo.png')).toBe('logo.png')+ expect(iconFileName('logo.png')).toBe('logo.png')+ })++ it('is what lets nodeIconMime read a Windows path', () => {+ expect(nodeIconMime('C:\\Users\\me\\logo.PNG')).toBe('image/png')+ expect(nodeIconMime('C:\\dir.with.dots\\README')).toBeUndefined()+ })+})diff --git a/src/shared/node-icon.ts b/src/shared/node-icon.tsindex 392583013..6cc18a0d7 100644--- a/src/shared/node-icon.ts+++ b/src/shared/node-icon.ts@@ -24,7 +24,25 @@** 3. **A relative path may not traverse.** `./` paths are resolved against the project cwd (see* below), so a `./..`-prefixed one would walk straight out of the project. Same rule, and the- * same reasoning, as `isSafeQuickOpenRelPath` on the remote quick-open index.+ * same reasoning, as `isSafeQuickOpenRelPath` on the remote quick-open index. **Both `/` and+ * `\\` count as separators when that rule is applied, on every platform** — see+ * `isSafeRelIconPath`.+ *+ * **Two dialects in, one dialect out.** The value is written by one machine and read by another,+ * so validation ACCEPTS a Windows path (`C:\\...`) and a POSIX one (`/...`) regardless of where+ * the check runs, while everything this module STORES is POSIX-separated. Both halves are+ * load-bearing:+ *+ * • Accepting both everywhere is what stops a mac's `flowToNodeStates` from silently deleting a+ * Windows teammate's icons: refuse `C:\\...` on mac and a mac user merely opening the shared+ * canvas and saving it strips them from `project.json`. A Windows absolute path on a mac does+ * not RESOLVE, of course — it just does not draw, exactly as a POSIX absolute path from someone+ * else's machine already does not. That is a degrade, and a degrade is not a reason to destroy+ * the value on the way past.+ * • Storing one dialect is what makes the `./` form portable at all. A stored `.\\a\\b.png` would+ * mean "a file called `a\\b.png`" on POSIX and "`b.png` inside `a`" on Windows. So+ * `normalizeNodeIcon` canonicalizes a relative path to `./` with forward slashes, the same way+ * it canonicalizes an emoji to its first grapheme.** **Portability.** An icon image lives beside the canvas that names it, in the project's own* git-shared `.nodeterm/images/` (see core/canvas-images.ts). A path stored absolutely would@@ -80,9 +98,52 @@ interface GraphemeSegmenter {segment(input: string): Iterable<{ segment: string }>}+/**+ * A path separator. BOTH are separators everywhere, never "`\` only on Windows": the value is+ * written by one machine and validated on another, so a check that reads `\` as an ordinary+ * filename character on the validating machine is simply wrong about the machine that will read+ * it. Applying the strict rule on every platform costs a POSIX user only the ability to name an+ * icon file with a literal backslash in it.+ */+const SEP_RE = /[\\/]/++/** `./` or `.\` — the marker for a path stored relative to the project root. */+const REL_PREFIX_RE = /^\.[\\/]/++/**+ * A drive-qualified absolute path: `C:\...` or `C:/...`. The separator is REQUIRED, because+ * `C:x.png` is drive-RELATIVE — it resolves against whatever directory that drive happens to be+ * sitting on in the reading process, which is precisely the guess this module refuses to make.+ */+const DRIVE_ABS_RE = /^[A-Za-z]:[\\/]/++/**+ * A UNC path: `\\host\share\...` or `//host/share/...`. Refused, matching the decision already+ * made for terminal file links (`renderer/terminal/file-links.ts`, which consumes UNC+ * specifically so it can refuse it). Reading one reaches ANOTHER MACHINE over SMB, which is a+ * long way outside "an icon beside the canvas" and is exactly the reach the extension gate exists+ * to keep narrow. Note this also refuses a POSIX `//foo/bar`, where a leading `//` is+ * implementation-defined anyway — no real icon path is lost.+ */+const UNC_RE = /^(?:\\\\|\/\/)/++/** Absolute in EITHER dialect, and not a network path. The one predicate all three exported+ * functions ask, so they cannot disagree about what "absolute" means. */+function isAbsoluteIconPath(path: string): boolean {+ if (UNC_RE.test(path)) return false+ return path.startsWith('/') || DRIVE_ABS_RE.test(path)+}++/** The final segment of a path in either dialect — `C:\a\b.png` and `/a/b.png` both give+ * `b.png`. Exported because the picker needs the same answer when it names the copied file. */+export function iconFileName(path: string): string {+ const segments = path.split(SEP_RE)+ return segments[segments.length - 1] ?? ''+}+/** The MIME type for an icon image path, or undefined when the extension is not an image one. */export function nodeIconMime(path: string): string | undefined {- const name = path.split('/').pop() ?? ''+ const name = iconFileName(path)// A name with no dot has no extension: `.split('.').pop()` would return the whole name, so// `README` would resolve as an extension and only miss by luck.if (!name.includes('.')) return undefined@@ -110,9 +171,24 @@ function firstGrapheme(raw: string): string {return clean.slice(0, EMOJI_MAX_UNITS)}-/** True when a `./`-relative icon path stays inside the project root. */+/**+ * True when a `./`-relative icon path stays inside the project root.+ *+ * Splitting on BOTH separators is the whole point, and it is not a Windows nicety. Splitting on+ * `/` alone, `./a\..\..\secret.png` is ONE segment — not `''`, not `.`, not `..` — so it passed+ * this guard on every platform and then walked two directories out of the project the moment a+ * Windows reader resolved it. One machine writes this value and another reads it, so the rule has+ * to hold where it is CHECKED, not only where it happens to be dangerous.+ *+ * A segment may also not contain `:`. On Windows that is either a drive qualifier (`./C:/Windows`)+ * or an NTFS alternate data stream (`./icon.png:payload`), and a project-relative icon path has no+ * business expressing either.+ */function isSafeRelIconPath(rel: string): boolean {- return rel.split('/').every((seg) => seg !== '' && seg !== '..' && seg !== '.')+ const segments = rel.split(SEP_RE)+ return segments.every(+ (seg) => seg !== '' && seg !== '.' && seg !== '..' && !seg.includes(':')+ )}/**@@ -132,13 +208,19 @@ export function normalizeNodeIcon(raw: unknown): NodeIcon | undefined {if (typeof v.path !== 'string') return undefinedconst path = v.path.trim()if (!path || hasControl(path) || !nodeIconMime(path)) return undefined- if (path.startsWith('./')) {- return isSafeRelIconPath(path.slice(2)) ? { type: 'image', path } : undefined+ if (REL_PREFIX_RE.test(path)) {+ const rel = path.slice(2)+ if (!isSafeRelIconPath(rel)) return undefined+ // Canonicalize to the one stored dialect. A hand-edited `.\a\b.png` means two different+ // files on the two platforms; rewriting it here (the same way an emoji is rewritten to its+ // first grapheme) is what keeps the shared file unambiguous for its next reader.+ return { type: 'image', path: `./${rel.replace(/\\/g, '/')}` }}- // Anything else must be an absolute POSIX path: a bare `foo.png` has no root to resolve+ // Anything else must be absolute, in either dialect: a bare `foo.png` has no root to resolve// against, and resolving it against the cwd of whatever process happens to be running is- // precisely the kind of guess this module refuses to make.- return path.startsWith('/') ? { type: 'image', path } : undefined+ // precisely the kind of guess this module refuses to make. An absolute path is kept BYTE FOR+ // BYTE — it belongs to one machine's filesystem and is not ours to rewrite.+ return isAbsoluteIconPath(path) ? { type: 'image', path } : undefined}return undefined}@@ -150,9 +232,22 @@ export function normalizeNodeIcon(raw: unknown): NodeIcon | undefined {*/export function portableIconPath(absPath: string, projectCwd?: string): string {if (!projectCwd) return absPath- const root = projectCwd.replace(/\/+$/, '')- if (!root || !absPath.startsWith(`${root}/`)) return absPath- const rel = absPath.slice(root.length + 1)+ const root = projectCwd.replace(/[\\/]+$/, '')+ if (!root) return absPath+ // The prefix test is separator-INSENSITIVE: `saveCanvasImage` builds its answer with the host's+ // own `path.join`, so on Windows it comes back `C:\proj\.nodeterm\images\x.png` while+ // `project.cwd` may carry either separator. Comparing raw strings there simply never matched,+ // and the icon silently stayed absolute — travelling nowhere, with nothing said about it.+ //+ // The comparison stays CASE-sensitive even though Windows filesystems usually are not: both+ // sides come from the same `project.cwd` in practice, so they match exactly, and a+ // case-insensitive test would wrongly relativize on a case-sensitive filesystem. Not matching+ // costs only portability; matching wrongly costs correctness.+ const toPosix = (p: string): string => p.replace(/\\/g, '/')+ const posixRoot = toPosix(root)+ const posixAbs = toPosix(absPath)+ if (!posixAbs.startsWith(`${posixRoot}/`)) return absPath+ const rel = posixAbs.slice(posixRoot.length + 1)return rel && isSafeRelIconPath(rel) ? `./${rel}` : absPath}@@ -162,9 +257,17 @@ export function portableIconPath(absPath: string, projectCwd?: string): string {* means the icon does not draw; it must never mean "read something else".*/export function resolveIconPath(storedPath: string, projectCwd?: string): string | undefined {- if (!storedPath.startsWith('./')) return storedPath.startsWith('/') ? storedPath : undefined+ // Re-asked rather than assumed: this is exported, and the next caller may not have come through+ // `normalizeNodeIcon` (the same reasoning `loadNodeIconSrc` gives for re-checking the MIME).+ if (!REL_PREFIX_RE.test(storedPath)) {+ return isAbsoluteIconPath(storedPath) ? storedPath : undefined+ }const rel = storedPath.slice(2)if (!isSafeRelIconPath(rel)) return undefined- const root = projectCwd?.replace(/\/+$/, '')- return root ? `${root}/${rel}` : undefined+ const root = projectCwd?.replace(/[\\/]+$/, '')+ if (!root) return undefined+ // Joined with `/` even when `root` is a Windows path: Node's fs accepts forward slashes on+ // Windows, and one deterministic spelling keeps `nodeIconImage`'s per-path cache from holding+ // two entries for one file.+ return `${root}/${rel.replace(/\\/g, '/')}`}