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.

feat(media): nt-media:// streaming protocol with range + path jail

enesd090f8527666
diff --git a/src/main/index.ts b/src/main/index.ts
index 9d69806c9..3d1cd4951 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -41,6 +41,12 @@ import { initRemoteClient } from './remote/client-service'
import { initSshProject } from './remote-ssh/ssh-project'
import { setGitRemoteResolver, type GitRemoteRef } from './remote-ssh/remote-git'
import { SshFs } from './ssh-fs'
+import {
+ registerMediaScheme,
+ initMediaProtocol,
+ allowMediaPath,
+ writeAgentHtml
+} from './media-protocol'
// Dev-only: NT_MULTI lets a SECOND instance run (host + client testing on one machine) with an
// isolated userData via NT_USER_DATA — its own device-id/session/license/workspace. Never active
@@ -101,6 +107,10 @@ if (!gotSingleInstanceLock) {
})
}
+// Declare the nt-media:// scheme privileged BEFORE the app is ready (required by Electron).
+// The actual request handler is installed post-ready via initMediaProtocol().
+registerMediaScheme()
+
function createWindow(): BrowserWindow {
const win = new BrowserWindow({
width: 1400,
@@ -177,6 +187,9 @@ app.whenReady().then(async () => {
generateCommitMessage(cwd, settingsStore.get())
)
+ ipcMain.handle(IPC.mediaAllow, (_e, absPath: string) => allowMediaPath(absPath))
+ ipcMain.handle(IPC.mediaWriteHtml, (_e, html: string) => writeAgentHtml(html))
+
ipcMain.handle(IPC.ptyGenerateName, async (_e, persistKey: string, cwd: string) =>
generateTerminalName(await ptyManager.captureSession(persistKey), cwd, settingsStore.get())
)
@@ -541,6 +554,7 @@ app.whenReady().then(async () => {
}
})
await hookServer.start()
+ initMediaProtocol()
initContextLink(win, ptyManager)
initClaudeUsage(win)
diff --git a/src/main/media-protocol.test.ts b/src/main/media-protocol.test.ts
new file mode 100644
index 000000000..a3e70415a
--- /dev/null
+++ b/src/main/media-protocol.test.ts
@@ -0,0 +1,26 @@
+import { describe, it, expect } from 'vitest'
+import { resolveMediaPath, mediaUrlFor } from './media-protocol'
+
+describe('resolveMediaPath (path jail)', () => {
+ const allow = new Set(['/projects/app/clip.mp4', '/projects/app/out.html'])
+
+ it('returns the absolute path for an allowed file', () => {
+ const url = mediaUrlFor('/projects/app/clip.mp4')
+ expect(resolveMediaPath(new URL(url).pathname, allow)).toBe('/projects/app/clip.mp4')
+ })
+
+ it('rejects a path not on the allowlist', () => {
+ const url = mediaUrlFor('/etc/passwd')
+ expect(resolveMediaPath(new URL(url).pathname, allow)).toBeNull()
+ })
+
+ it('rejects traversal that escapes an allowed file', () => {
+ expect(resolveMediaPath('/projects/app/../../etc/passwd', allow)).toBeNull()
+ })
+
+ it('round-trips paths with spaces/unicode via mediaUrlFor', () => {
+ const allow2 = new Set(['/a b/çlip.mp4'])
+ const url = mediaUrlFor('/a b/çlip.mp4')
+ expect(resolveMediaPath(new URL(url).pathname, allow2)).toBe('/a b/çlip.mp4')
+ })
+})
diff --git a/src/main/media-protocol.ts b/src/main/media-protocol.ts
new file mode 100644
index 000000000..84b8c300d
--- /dev/null
+++ b/src/main/media-protocol.ts
@@ -0,0 +1,96 @@
+// nt-media:// — a privileged streaming protocol for local media (video) + large images.
+// Files are served ONLY if they are on the per-session allowlist (path jail), so the
+// renderer/agent can never read an arbitrary local file. Supports HTTP Range so <video> seeks.
+import { createReadStream, statSync, mkdirSync, writeFileSync } from 'fs'
+import { normalize } from 'path'
+import { app, protocol } from 'electron'
+
+export const MEDIA_SCHEME = 'nt-media'
+
+// Absolute paths the app has explicitly opened this session. Cleared only on quit.
+const allowed = new Set<string>()
+
+/** Build the nt-media:// URL for an absolute path (path encoded as the URL pathname). */
+export function mediaUrlFor(absPath: string): string {
+ // Use the path as an opaque, percent-encoded pathname under a fixed host.
+ return `${MEDIA_SCHEME}://media${encodeURI(absPath)}`
+}
+
+/**
+ * Pure jail check: decode the request pathname, normalize it, and return it only if the
+ * normalized absolute path is on `allow`. Returns null otherwise (unknown path or traversal
+ * that resolves outside the allowlist).
+ */
+export function resolveMediaPath(requestPath: string, allow: ReadonlySet<string>): string | null {
+ let p: string
+ try {
+ p = decodeURIComponent(requestPath)
+ } catch {
+ return null
+ }
+ const norm = normalize(p)
+ return allow.has(norm) ? norm : null
+}
+
+/** Register the path (so the protocol will serve it) and return its nt-media:// URL. */
+export function allowMediaPath(absPath: string): string {
+ const norm = normalize(absPath)
+ allowed.add(norm)
+ return mediaUrlFor(norm)
+}
+
+let htmlSeq = 0
+/** Write raw HTML to a per-session file under userData, allowlist it, return its abs path. */
+export function writeAgentHtml(html: string): string {
+ const d = `${app.getPath('userData')}/agent-web`
+ mkdirSync(d, { recursive: true })
+ const p = `${d}/${Date.now().toString(36)}-${++htmlSeq}.html`
+ writeFileSync(p, html, 'utf8')
+ allowMediaPath(p)
+ return p
+}
+
+/** Call BEFORE app.whenReady(): declares the scheme privileged (secure + streamable). */
+export function registerMediaScheme(): void {
+ protocol.registerSchemesAsPrivileged([
+ {
+ scheme: MEDIA_SCHEME,
+ privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true, bypassCSP: false }
+ }
+ ])
+}
+
+/** Call AFTER app is ready: serve allowed files with Range support. */
+export function initMediaProtocol(): void {
+ protocol.handle(MEDIA_SCHEME, async (req) => {
+ const url = new URL(req.url)
+ const abs = resolveMediaPath(url.pathname, allowed)
+ if (!abs) return new Response('Not found', { status: 404 })
+ let size: number
+ try {
+ size = statSync(abs).size
+ } catch {
+ return new Response('Not found', { status: 404 })
+ }
+ const range = req.headers.get('range')
+ const m = range && /bytes=(\d*)-(\d*)/.exec(range)
+ if (m) {
+ const start = m[1] ? parseInt(m[1], 10) : 0
+ const end = m[2] ? parseInt(m[2], 10) : size - 1
+ const stream = createReadStream(abs, { start, end })
+ return new Response(stream as unknown as ReadableStream, {
+ status: 206,
+ headers: {
+ 'Content-Range': `bytes ${start}-${end}/${size}`,
+ 'Accept-Ranges': 'bytes',
+ 'Content-Length': String(end - start + 1)
+ }
+ })
+ }
+ const stream = createReadStream(abs)
+ return new Response(stream as unknown as ReadableStream, {
+ status: 200,
+ headers: { 'Content-Length': String(size), 'Accept-Ranges': 'bytes' }
+ })
+ })
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 15d76cebd..fb72b0ac1 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -168,6 +168,10 @@ const api: NodeTerminalApi = {
readBinary: (filePath: string) => ipcRenderer.invoke(IPC.fsReadBinary, filePath),
write: (filePath: string, content: string) => ipcRenderer.invoke(IPC.fsWrite, filePath, content)
},
+ media: {
+ allow: (absPath: string) => ipcRenderer.invoke(IPC.mediaAllow, absPath),
+ writeHtml: (html: string) => ipcRenderer.invoke(IPC.mediaWriteHtml, html)
+ },
files: {
quickOpen: (cwd: string) => ipcRenderer.invoke(IPC.filesQuickOpen, cwd)
},
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 8402a6ce4..3fce5fc1f 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
http-equiv="Content-Security-Policy"
- content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self'; worker-src 'self' blob:; font-src 'self' data:"
+ content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: nt-media:; media-src 'self' nt-media:; script-src 'self'; worker-src 'self' blob:; font-src 'self' data:"
/>
<title>node-terminal</title>
</head>
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 4a85d830e..97f5c58cd 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -116,6 +116,8 @@ export const IPC = {
gitSetActiveRemote: 'git:set-active-remote',
shellOpenExternal: 'shell:open-external',
commitGenerate: 'commit:generate',
+ mediaAllow: 'media:allow',
+ mediaWriteHtml: 'media:write-html',
remoteHostStart: 'remote:host:start',
remoteHostStop: 'remote:host:stop',
// Connection approval gate: main → renderer when a client finishes the handshake (carries the
diff --git a/src/shared/types.ts b/src/shared/types.ts
index efdbc12c2..a3b87d9d3 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -245,6 +245,13 @@ export interface FilesApi {
quickOpen(cwd: string): Promise<string[]>
}
+export interface MediaApi {
+ /** Allow an absolute local path to be served, and return its nt-media:// URL. */
+ allow(absPath: string): Promise<string>
+ /** Persist raw HTML to <userData>/agent-web/<id>.html, allowlist it, return its absolute path. */
+ writeHtml(html: string): Promise<string>
+}
+
/** A user-defined agent (BYO CLI). In no capability list, so it gets only spawn +
* terminal-title + process status (no hooks/branch/loop/bridge). */
export interface CustomAgent {
@@ -818,6 +825,7 @@ export interface NodeTerminalApi {
clipboard: ClipboardApi
shell: ShellApi
fs: FsApi
+ media: MediaApi
files: FilesApi
updates: UpdateApi
announcements: AnnouncementsApi