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(server): config + boot — startServer() wires auth/http/ws/CorePlatform/PtyManager

enesebd6a5af6640
diff --git a/package.json b/package.json
index 46260ee13..ddae32257 100644
--- a/package.json
+++ b/package.json
@@ -15,6 +15,9 @@
"test": "vitest run",
"test:unit": "vitest run test/remote",
"rebuild": "electron-rebuild -f -w node-pty",
+ "server:build": "esbuild src/server/main.ts --bundle --platform=node --format=cjs --outfile=out/server/main.cjs --external:node-pty --external:ws --tsconfig=tsconfig.node.json",
+ "server:start": "node out/server/main.cjs",
+ "server:dev": "npm run build && npm run server:build && node out/server/main.cjs",
"make-icon": "node scripts/make-icon.mjs",
"make-social": "node scripts/make-social.mjs",
"dist": "npm run make-icon && electron-vite build && electron-builder --mac --arm64 -c.mac.identity=null -c.mac.notarize=false",
diff --git a/src/server/config.test.ts b/src/server/config.test.ts
new file mode 100644
index 000000000..60ee6490c
--- /dev/null
+++ b/src/server/config.test.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect } from 'vitest'
+import os from 'os'
+import path from 'path'
+import { resolveConfig } from './config'
+
+describe('resolveConfig', () => {
+ it('has safe defaults', () => {
+ const c = resolveConfig({}, [])
+ expect(c.port).toBe(8443)
+ expect(c.host).toBe('127.0.0.1')
+ expect(c.dataDir).toBe(path.join(os.homedir(), '.nodeterm-server'))
+ expect(c.insecureHttp).toBe(false)
+ })
+ it('env overrides defaults; argv overrides env', () => {
+ const c = resolveConfig(
+ { NODETERM_PORT: '9000', NODETERM_DATA_DIR: '/data', NODETERM_SERVER_PASSWORD: 'p' },
+ ['--port', '9100', '--insecure-http']
+ )
+ expect(c.port).toBe(9100)
+ expect(c.dataDir).toBe('/data')
+ expect(c.passwordSeed).toBe('p')
+ expect(c.insecureHttp).toBe(true)
+ })
+ it('refuses a non-loopback bind without --insecure-http', () => {
+ expect(() => resolveConfig({ NODETERM_HOST: '0.0.0.0' }, [])).toThrow(/insecure-http|reverse proxy/i)
+ expect(() => resolveConfig({ NODETERM_HOST: '0.0.0.0' }, ['--insecure-http'])).not.toThrow()
+ })
+})
diff --git a/src/server/config.ts b/src/server/config.ts
new file mode 100644
index 000000000..0e844703f
--- /dev/null
+++ b/src/server/config.ts
@@ -0,0 +1,80 @@
+import os from 'os'
+import path from 'path'
+
+/**
+ * Fully-resolved server configuration. Produced by {@link resolveConfig} from the
+ * process environment + CLI argv, then consumed by `startServer` (src/server/index.ts).
+ */
+export type ServerConfig = {
+ port: number
+ host: string
+ dataDir: string
+ rendererDir: string
+ insecureHttp: boolean
+ passwordSeed?: string
+}
+
+/**
+ * Minimal `--flag value` / `--bool` argv parser. Only understands the flags we
+ * define below; anything else is ignored. A flag whose next token is another
+ * flag (or missing) is treated as a boolean.
+ */
+function parseArgv(argv: string[]): Record<string, string | boolean> {
+ const out: Record<string, string | boolean> = {}
+ for (let i = 0; i < argv.length; i++) {
+ const tok = argv[i]
+ if (!tok.startsWith('--')) continue
+ const key = tok.slice(2)
+ if (key === 'insecure-http') {
+ out[key] = true
+ continue
+ }
+ const next = argv[i + 1]
+ if (next !== undefined && !next.startsWith('--')) {
+ out[key] = next
+ i++
+ } else {
+ out[key] = true
+ }
+ }
+ return out
+}
+
+function isLoopback(host: string): boolean {
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1'
+}
+
+/**
+ * Resolve the server config from `env` + `argv`. Precedence is argv > env > default.
+ * Binding a non-loopback host without `--insecure-http` throws: plain HTTP on a
+ * public interface would leak the session cookie, so the server insists on being
+ * kept behind a TLS-terminating reverse proxy (loopback) unless explicitly overridden.
+ */
+export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerConfig {
+ const args = parseArgv(argv)
+
+ const pick = (argKey: string, envKey: string, def: string): string => {
+ if (typeof args[argKey] === 'string') return args[argKey] as string
+ const ev = env[envKey]
+ if (ev !== undefined && ev !== '') return ev
+ return def
+ }
+
+ const port = Number(pick('port', 'NODETERM_PORT', '8443'))
+ const host = pick('host', 'NODETERM_HOST', '127.0.0.1')
+ const dataDir = pick('data-dir', 'NODETERM_DATA_DIR', path.join(os.homedir(), '.nodeterm-server'))
+ const rendererDir = pick('renderer-dir', 'NODETERM_RENDERER_DIR', path.resolve('out/renderer'))
+ const insecureHttp = args['insecure-http'] === true
+ const passwordSeed = env.NODETERM_SERVER_PASSWORD || undefined
+
+ if (!isLoopback(host) && !insecureHttp) {
+ throw new Error(
+ `Refusing to bind non-loopback host "${host}" over plain HTTP. Run nodeterm-server ` +
+ `behind a TLS-terminating reverse proxy and keep it bound to a loopback address ` +
+ `(127.0.0.1 / localhost / ::1), or pass --insecure-http to acknowledge you are ` +
+ `serving plain HTTP directly on this interface.`
+ )
+ }
+
+ return { port, host, dataDir, rendererDir, insecureHttp, passwordSeed }
+}
diff --git a/src/server/index.ts b/src/server/index.ts
new file mode 100644
index 000000000..e12c3320c
--- /dev/null
+++ b/src/server/index.ts
@@ -0,0 +1,105 @@
+import fs from 'fs'
+import path from 'path'
+import http from 'http'
+
+import { ServerPlatform } from './platform-server'
+import { Auth } from './auth'
+import { createHttpHandler } from './http'
+import { attachWsServer } from './ws'
+import type { ServerConfig } from './config'
+
+import { initPlatform } from '../core/platform'
+import { SettingsStore } from '../core/settings-store'
+import { WorkspaceStore } from '../core/workspace-store'
+import { PtyManager } from '../core/pty-manager'
+import { IPC } from '@shared/ipc'
+
+/**
+ * App version fed to ServerPlatform (surfaced to the renderer as the desktop app's
+ * `app.getVersion()` equivalent). Read from package.json at boot; the esbuild bundle
+ * lives at `out/server/main.cjs`, so `../../package.json` resolves to the repo root.
+ * Falls back to '0.0.0' if the file can't be read (never fatal).
+ */
+function readAppVersion(): string {
+ try {
+ const pkgPath = path.join(__dirname, '../../package.json')
+ const parsed = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) as { version?: string }
+ return parsed.version ?? '0.0.0'
+ } catch {
+ return '0.0.0'
+ }
+}
+
+/**
+ * Boot the headless server: wires the CorePlatform (ServerPlatform) to auth + HTTP +
+ * WebSocket, then constructs and registers the same core services the desktop main
+ * process uses (SettingsStore / PtyManager / WorkspaceStore), mirroring
+ * `src/main/index.ts`'s construction + registration order.
+ *
+ * Returns the actually-bound port (so port 0 works in tests) and a `close()` that
+ * detaches PTY clients (tmux sessions keep running — Phase 1 contract) and stops the server.
+ */
+export async function startServer(
+ config: ServerConfig
+): Promise<{ port: number; close(): Promise<void> }> {
+ fs.mkdirSync(config.dataDir, { recursive: true })
+
+ // Core platform boundary — must be initialized before any core service registers handlers.
+ const platform = new ServerPlatform({
+ userDataDir: config.dataDir,
+ appVersion: readAppVersion()
+ })
+ initPlatform(platform)
+
+ const auth = new Auth(config.dataDir)
+ if (config.passwordSeed && !auth.isConfigured()) auth.setPassword(config.passwordSeed)
+ if (!auth.isConfigured()) {
+ // No password set yet: print the one-time setup URL so the operator can bootstrap.
+ console.log(`Setup: http://${config.host}:${config.port}/setup?token=${auth.setupToken()}`)
+ }
+
+ // Core services — same construction + registration order as src/main/index.ts.
+ const settingsStore = new SettingsStore()
+ const ptyManager = new PtyManager()
+ const workspaceStore = new WorkspaceStore()
+
+ settingsStore.init()
+ settingsStore.registerIpc()
+ ptyManager.init(() => settingsStore.get())
+ ptyManager.registerIpc()
+ workspaceStore.registerIpc()
+
+ // Desktop's src/main/index.ts registers a few pty handlers outside PtyManager. Of those,
+ // ptyCapture delegates purely to core (ptyManager.captureSession), so it belongs here.
+ // The others (ptyGenerateName / ptyGenerateGroupName → commit-message.ts; ptyReadSessionName
+ // → transcript-reader.ts) depend on src/main-resident modules and are stubbed by the bridge
+ // in Task 8. readScrollback + sendText are already registered inside PtyManager.registerIpc().
+ platform.handle(IPC.ptyCapture, (persistKey: string, full?: boolean) =>
+ ptyManager.captureSession(persistKey, full)
+ )
+
+ const server = http.createServer(createHttpHandler({ auth, rendererDir: config.rendererDir }))
+ attachWsServer(server, { platform, auth })
+
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(config.port, config.host, () => {
+ server.off('error', reject)
+ resolve()
+ })
+ })
+
+ const addr = server.address()
+ const port = addr && typeof addr === 'object' ? addr.port : config.port
+
+ return {
+ port,
+ async close() {
+ // Detach PTY clients — tmux sessions keep running (Phase 1 contract; never kill the server).
+ await ptyManager.killAll()
+ await new Promise<void>((resolve, reject) => {
+ server.close((err) => (err ? reject(err) : resolve()))
+ })
+ }
+ }
+}
diff --git a/src/server/main.ts b/src/server/main.ts
new file mode 100644
index 000000000..33adb14e9
--- /dev/null
+++ b/src/server/main.ts
@@ -0,0 +1,31 @@
+import { resolveConfig } from './config'
+import { startServer } from './index'
+
+/**
+ * Script entry point for the headless server. Kept separate from index.ts so that
+ * `index.ts` stays side-effect-free (importable by tests without booting a server).
+ */
+async function main(): Promise<void> {
+ const config = resolveConfig(process.env, process.argv.slice(2))
+ const { port, close } = await startServer(config)
+ const scheme = config.insecureHttp ? 'http (insecure)' : 'http'
+ console.log(`nodeterm-server listening on ${scheme} ${config.host}:${port}`)
+
+ const shutdown = (signal: string): void => {
+ console.log(`\nReceived ${signal}, shutting down…`)
+ void close().then(
+ () => process.exit(0),
+ (err) => {
+ console.error('Error during shutdown:', err)
+ process.exit(1)
+ }
+ )
+ }
+ process.on('SIGINT', () => shutdown('SIGINT'))
+ process.on('SIGTERM', () => shutdown('SIGTERM'))
+}
+
+void main().catch((err) => {
+ console.error(err instanceof Error ? err.message : err)
+ process.exit(1)
+})