Skip to content

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.

security+perf: app hardening pass for release

enesf69f24463cd8
diff --git a/.gitignore b/.gitignore
index 59fd59d65..b5c501603 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,6 @@ build/icon.png
# private backend lives in its own repo (a-private-repo)
/nodebaseserver/
+
+# local session handoff transcripts / app state
+.nodeterm/
diff --git a/package-lock.json b/package-lock.json
index e7989a832..c4c34d5d7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,7 +10,7 @@
"hasInstallScript": true,
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
- "dompurify": "^3.4.10",
+ "dompurify": "^3.4.11",
"electron-updater": "^6.8.9",
"marked": "^12.0.2",
"monaco-editor": "^0.52.2",
@@ -4342,9 +4342,9 @@
}
},
"node_modules/dompurify": {
- "version": "3.4.10",
- "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.10.tgz",
- "integrity": "sha512-0xzNv0e7oYC6yyuOGZIABPM4qtg3QxLFniDNPP4ZP90wR8Yq3zgwpRbrNiT4N3IKqDbbYFEJLV+JWEs19aZ//w==",
+ "version": "3.4.11",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.11.tgz",
+ "integrity": "sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
diff --git a/package.json b/package.json
index 58bfe9bb2..1bb1697f2 100644
--- a/package.json
+++ b/package.json
@@ -66,7 +66,7 @@
}
},
"dependencies": {
- "dompurify": "^3.4.10",
+ "dompurify": "^3.4.11",
"electron-updater": "^6.8.9",
"marked": "^12.0.2",
"monaco-editor": "^0.52.2",
diff --git a/src/main/agents/hook-server.ts b/src/main/agents/hook-server.ts
index 1adf97e20..ab942ea2d 100644
--- a/src/main/agents/hook-server.ts
+++ b/src/main/agents/hook-server.ts
@@ -1,5 +1,5 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
-import { randomUUID } from 'crypto'
+import { randomUUID, timingSafeEqual } from 'crypto'
import { writeFileSync, mkdirSync } from 'fs'
import path from 'path'
import { app } from 'electron'
@@ -66,7 +66,7 @@ class HookServer {
res.end()
return
}
- if (req.headers['x-nodeterm-hook-token'] !== this.token) {
+ if (!this.tokenMatches(req.headers['x-nodeterm-hook-token'])) {
res.writeHead(403)
res.end()
return
@@ -113,6 +113,14 @@ class HookServer {
})
}
+ // Constant-time bearer-token check (avoids a timing side channel on the compare).
+ private tokenMatches(provided: string | string[] | undefined): boolean {
+ if (typeof provided !== 'string' || !this.token) return false
+ const a = Buffer.from(provided)
+ const b = Buffer.from(this.token)
+ return a.length === b.length && timingSafeEqual(a, b)
+ }
+
// The managed script sources this file at invocation to get the LIVE port/token.
// tmux sessions outlive the app, so env-baked coords go stale after a restart.
private writeEndpointFile(): void {
@@ -122,7 +130,9 @@ class HookServer {
writeFileSync(
p,
`NODETERM_HOOK_PORT=${this.port}\nNODETERM_HOOK_TOKEN=${this.token}\nNODETERM_HOOK_VERSION=${NODETERM_HOOK_PROTOCOL_VERSION}\n`,
- 'utf8'
+ // 0o600: this file holds the bearer token — owner read/write only so another local user
+ // can't read it and forge hook events.
+ { encoding: 'utf8', mode: 0o600 }
)
} catch (e) {
console.warn('[agent-hooks] could not write endpoint file', e)
diff --git a/src/main/commit-message.ts b/src/main/commit-message.ts
index 23959aec3..9bcc68032 100644
--- a/src/main/commit-message.ts
+++ b/src/main/commit-message.ts
@@ -29,8 +29,12 @@ function resolveBinary(name: string): string | null {
// ignore
}
}
+ // Resolve via PATH without a shell. `name` comes from a user setting (custom commit agent),
+ // so never interpolate it into a shell string — pass it as a plain argv to `command -v`.
+ // Reject anything that isn't a bare binary name to keep it well out of injection territory.
+ if (!/^[A-Za-z0-9._-]+$/.test(name)) return null
try {
- const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', `command -v ${name}`], {
+ const out = execFileSync('/usr/bin/env', ['sh', '-c', 'command -v "$1"', 'sh', name], {
encoding: 'utf-8'
}).trim()
if (out) return out
diff --git a/src/main/context-tail.ts b/src/main/context-tail.ts
index e7b4a7a57..d274fb3cb 100644
--- a/src/main/context-tail.ts
+++ b/src/main/context-tail.ts
@@ -9,6 +9,11 @@ import type { ContextWindowUsage } from '../shared/types'
import { cachedWindowFor, resolveModelWindow } from './model-window'
const POLL_MS = 1000
+// Cap the initial read: a resumed Claude transcript can be many MB, and reading the whole file
+// synchronously on the main thread (Buffer.alloc(size) + JSON.parse per line) stalls all IPC.
+// Only the LATEST assistant usage matters, so a tail of the file is enough; the partial first
+// line is dropped naturally by the JSON.parse guard.
+const INITIAL_READ_CAP = 1024 * 1024 // 1 MB
interface Tracked {
path: string
@@ -58,6 +63,8 @@ export function createContextTail(win: BrowserWindow): ContextTail {
}
if (size >= 0) {
if (size < t.offset) t.offset = 0 // truncated/rotated → re-read from start
+ // First read of a large transcript: skip to the last INITIAL_READ_CAP bytes.
+ if (t.offset === 0 && size > INITIAL_READ_CAP) t.offset = size - INITIAL_READ_CAP
if (size > t.offset) {
let chunk = ''
try {
diff --git a/src/main/index.ts b/src/main/index.ts
index f2178e902..e75f99ced 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -35,6 +35,19 @@ import { initRemoteClient } from './remote/client-service'
const NT_MULTI = !app.isPackaged && !!process.env.NT_MULTI
if (NT_MULTI && process.env.NT_USER_DATA) app.setPath('userData', process.env.NT_USER_DATA)
+// Only hand the OS a URL with a vetted scheme. Blocks file://, smb://, and custom
+// protocol-handler schemes that could be smuggled in via remote announcement feeds or
+// rendered markdown links. Used by both the window-open handler and the IPC handler.
+function isSafeExternalUrl(url: unknown): url is string {
+ if (typeof url !== 'string') return false
+ try {
+ const { protocol } = new URL(url)
+ return protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:'
+ } catch {
+ return false
+ }
+}
+
const settingsStore = new SettingsStore()
const sshStore = new SshStore()
const ptyManager = new PtyManager()
@@ -45,6 +58,12 @@ const gitService = new GitService()
// can check focus and route clicks back to the renderer.
let mainWin: BrowserWindow | null = null
+// Node → live tail bookkeeping, so closing a node (× → pty:destroy) releases its file tailers.
+// Without this, a node closed mid-run never emits SessionEnd/PostToolUse, so context-tail (1s
+// poll) and subagent-tail (400ms poll) would keep stat/read-ing forever. Keyed by node id.
+const nodeContextSession = new Map<string, string>() // nodeId → claude sessionId
+const nodeSubagents = new Map<string, Set<string>>() // nodeId → active subagent tool_use_ids
+
// Enforce a single instance. A second instance would re-attach every node's tmux session
// (`new-session -A -D`), whose `-D` detaches the first instance's clients — leaving
// "[detached (from session ...)]" dead terminals. Bail out and focus the existing window
@@ -97,12 +116,22 @@ function createWindow(): BrowserWindow {
}
})
- // Open external links in the system browser.
+ // Open external links in the system browser — only safe schemes (no file://, no custom
+ // protocol handlers). Reachable from remotely-fetched announcement URLs and rendered
+ // markdown links, so the allowlist mirrors the shellOpenExternal IPC handler.
win.webContents.setWindowOpenHandler(({ url }) => {
- shell.openExternal(url)
+ if (isSafeExternalUrl(url)) void shell.openExternal(url)
return { action: 'deny' }
})
+ // Block any in-page top-level navigation away from the app origin (defense in depth).
+ win.webContents.on('will-navigate', (e, url) => {
+ if (!url.startsWith('file://') && !url.startsWith(process.env['ELECTRON_RENDERER_URL'] ?? '\0')) {
+ e.preventDefault()
+ if (isSafeExternalUrl(url)) void shell.openExternal(url)
+ }
+ })
+
// Load the electron-vite dev server if present, otherwise the built file.
if (process.env['ELECTRON_RENDERER_URL']) {
win.loadURL(process.env['ELECTRON_RENDERER_URL'])
@@ -182,7 +211,7 @@ app.whenReady().then(async () => {
})
ipcMain.on(IPC.shellOpenExternal, (_e, url: string) => {
- if (typeof url === 'string' && /^https?:\/\//.test(url)) void shell.openExternal(url)
+ if (isSafeExternalUrl(url)) void shell.openExternal(url)
})
// The local Explorer/Editor fs IPC: thin wrappers over the shared fs-ops (the SAME logic the
@@ -275,13 +304,39 @@ app.whenReady().then(async () => {
}
// Context-window meter: tail the session transcript (any event carrying both fields).
if (p.session_id && p.transcript_path) contextTail.track(p.session_id, p.transcript_path)
+ if (nodeId && p.session_id) nodeContextSession.set(nodeId, p.session_id)
if (nodeId && p.session_id && p.transcript_path) setNodeTranscript(nodeId, p.session_id, p.transcript_path)
if (p.hook_event_name === 'SessionEnd' && p.session_id) contextTail.untrack(p.session_id)
// Subagent live transcript: track on PreToolUse / finish on PostToolUse for subagent tools.
const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
if (p.tool_use_id && p.tool_name && SUBAGENT_TOOLS.has(p.tool_name)) {
- if (p.hook_event_name === 'PreToolUse') subagentTail.track(p.tool_use_id, p.transcript_path)
- else if (p.hook_event_name === 'PostToolUse') subagentTail.finish(p.tool_use_id)
+ if (p.hook_event_name === 'PreToolUse') {
+ subagentTail.track(p.tool_use_id, p.transcript_path)
+ if (nodeId) {
+ const set = nodeSubagents.get(nodeId) ?? new Set<string>()
+ set.add(p.tool_use_id)
+ nodeSubagents.set(nodeId, set)
+ }
+ } else if (p.hook_event_name === 'PostToolUse') {
+ subagentTail.finish(p.tool_use_id)
+ if (nodeId) nodeSubagents.get(nodeId)?.delete(p.tool_use_id)
+ }
+ }
+ })
+
+ // Releasing tails on node close: pty:destroy fires when the user clicks × (persistKey = node
+ // id). pty-manager already handles the same channel to kill the tmux session; this extra
+ // listener tears down the per-node file tailers so they stop polling a now-dead session.
+ ipcMain.on(IPC.ptyDestroy, (_e, nodeId: string) => {
+ const sessionId = nodeContextSession.get(nodeId)
+ if (sessionId) {
+ contextTail.untrack(sessionId)
+ nodeContextSession.delete(nodeId)
+ }
+ const subs = nodeSubagents.get(nodeId)
+ if (subs) {
+ for (const toolUseId of subs) subagentTail.finish(toolUseId)
+ nodeSubagents.delete(nodeId)
}
})
await hookServer.start()
diff --git a/src/main/ssh-store.ts b/src/main/ssh-store.ts
index 2f904d46b..ae023c01e 100644
--- a/src/main/ssh-store.ts
+++ b/src/main/ssh-store.ts
@@ -52,7 +52,9 @@ export class SshStore {
this.writeChain = this.writeChain
.catch(() => {})
.then(async () => {
- await fs.writeFile(tmp, snapshot, 'utf-8')
+ // 0o600: this holds the user's SSH host inventory (hosts/users/identity-file paths) —
+ // owner read/write only, not world-readable.
+ await fs.writeFile(tmp, snapshot, { encoding: 'utf-8', mode: 0o600 })
await fs.rename(tmp, this.path)
})
return this.writeChain
diff --git a/src/renderer/state/contextWindow.ts b/src/renderer/state/contextWindow.ts
index 585bd716a..b4106b27d 100644
--- a/src/renderer/state/contextWindow.ts
+++ b/src/renderer/state/contextWindow.ts
@@ -10,24 +10,47 @@ import type { ContextWindowUsage } from '@shared/types'
// even though the session (and its fill) is unchanged. We restore the last-known value so the
// meter survives the restart; the live tailer overwrites it on the next prompt.
const KEY = 'nodeterm.contextWindow'
+// Hard cap on retained sessions. Every resume / `/clear` / restart mints a new sessionId, so
+// without a bound the map would grow forever (and we'd re-stringify the whole thing on every
+// hook tick). 200 is far more than any realistic number of live meters; oldest are evicted.
+const MAX_SESSIONS = 200
+// Don't write localStorage on every update (onUpdate fires repeatedly within a turn); coalesce.
+const SAVE_DEBOUNCE_MS = 2000
function load(): Record<string, ContextWindowUsage> {
try {
const raw = localStorage.getItem(KEY)
if (!raw) return {}
const data = JSON.parse(raw) as Record<string, ContextWindowUsage>
- return data && typeof data === 'object' ? data : {}
+ return data && typeof data === 'object' ? prune(data) : {}
} catch {
return {}
}
}
-function save(bySessionId: Record<string, ContextWindowUsage>): void {
- try {
- localStorage.setItem(KEY, JSON.stringify(bySessionId))
- } catch {
- // ignore quota / serialization errors
- }
+/** Keep only the MAX_SESSIONS most-recently-updated entries (LRU by updatedAt). */
+function prune(map: Record<string, ContextWindowUsage>): Record<string, ContextWindowUsage> {
+ const keys = Object.keys(map)
+ if (keys.length <= MAX_SESSIONS) return map
+ const newest = keys
+ .sort((a, b) => (map[b]?.updatedAt ?? 0) - (map[a]?.updatedAt ?? 0))
+ .slice(0, MAX_SESSIONS)
+ const out: Record<string, ContextWindowUsage> = {}
+ for (const k of newest) out[k] = map[k]
+ return out
+}
+
+let saveTimer: ReturnType<typeof setTimeout> | null = null
+function scheduleSave(bySessionId: Record<string, ContextWindowUsage>): void {
+ if (saveTimer) clearTimeout(saveTimer)
+ saveTimer = setTimeout(() => {
+ saveTimer = null
+ try {
+ localStorage.setItem(KEY, JSON.stringify(bySessionId))
+ } catch {
+ // ignore quota / serialization errors
+ }
+ }, SAVE_DEBOUNCE_MS)
}
interface ContextWindowState {
@@ -39,8 +62,9 @@ export const useContextWindow = create<ContextWindowState>((set) => ({
bySessionId: load(),
set: (usage) =>
set((s) => {
- const bySessionId = { ...s.bySessionId, [usage.sessionId]: usage }
- save(bySessionId)
+ const merged = { ...s.bySessionId, [usage.sessionId]: usage }
+ const bySessionId = prune(merged)
+ scheduleSave(bySessionId)
return { bySessionId }
})
}))
diff --git a/src/renderer/terminal/useTerminalSearch.ts b/src/renderer/terminal/useTerminalSearch.ts
index dda8170a1..e16bef93a 100644
--- a/src/renderer/terminal/useTerminalSearch.ts
+++ b/src/renderer/terminal/useTerminalSearch.ts
@@ -60,8 +60,6 @@ export function useTerminalSearch({
}
if (!captured) captured = readBuffer()
for (const t of captured.split('\n')) lines.push({ source: 'terminal', text: t })
- // [find2] TEMP diagnostic — one line tells us which link is broken.
- console.log('[find2] searchTranscript=', searchTranscript, '| sessionId=', sessionId, '| cwd=', cwd, '| terminalLines=', lines.length)
// Search the full Claude transcript for agent nodes. Resolved by sessionId when known,
// else by cwd (durable) — so it works even when no live hook event set the sessionId.
if (searchTranscript) {
@@ -70,15 +68,12 @@ export function useTerminalSearch({
sessionId,
cwd
)
- console.log('[find2] readTranscript ->', tr.length, 'transcript lines')
for (const l of tr) {
for (const t of l.text.split('\n')) lines.push({ source: 'claude', role: l.role, text: t })
}
- } catch (e) {
- console.error('[find2] readTranscript THREW (preload/main not reloaded?):', e)
+ } catch {
+ // transcript unavailable — fall back to terminal buffer only
}
- } else {
- console.log('[find2] transcript SKIPPED — searchTranscript is false (not an agent node?)')
}
if (!cancelled) setSource(lines)
})()