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): boot the hosted team relay with a 0600 admin socket and team CLI

reviewbf6d772feffc
diff --git a/src/core/relay/team-admin.test.ts b/src/core/relay/team-admin.test.ts
new file mode 100644
index 000000000..4cc10225a
--- /dev/null
+++ b/src/core/relay/team-admin.test.ts
@@ -0,0 +1,396 @@
+import { describe, it, expect, afterEach } from 'vitest'
+import { spawn } from 'node:child_process'
+import fs from 'node:fs'
+import net from 'node:net'
+import os from 'node:os'
+import path from 'node:path'
+import {
+ startTeamAdmin,
+ callTeamAdmin,
+ adminSocketPath,
+ socketPathProblem,
+ ownerKeyProblem,
+ ownerLabelProblem,
+ projectIdProblem,
+ parseAdminRequest,
+ ADMIN_REQUEST_MAX,
+ type AdminReply
+} from './team-admin'
+import { createHostKey } from './host-key'
+import { genKeyPair, publicKeyToB64 } from './e2ee'
+import type { HostedService, HostedStatus } from './hosted-service'
+
+// A unix socket path is limited to ~107 bytes, and a long mkdtemp path (macOS's /var/folders/…)
+// alone can eat most of that, so every socket test lives under a SHORT base.
+const SHORT_BASE = fs.existsSync('/var/tmp') ? '/var/tmp' : os.tmpdir()
+const made: string[] = []
+const tmp = (): string => {
+ const d = fs.mkdtempSync(path.join(SHORT_BASE, 'nta-'))
+ made.push(d)
+ return d
+}
+const closers: Array<() => Promise<void>> = []
+afterEach(async () => {
+ for (const c of closers.splice(0)) await c()
+ for (const d of made.splice(0)) fs.rmSync(d, { recursive: true, force: true })
+})
+
+const relayDir = (dataDir: string): string => path.join(dataDir, 'relay')
+const writeTeam = (dataDir: string): void => {
+ fs.mkdirSync(relayDir(dataDir), { recursive: true, mode: 0o700 })
+ fs.writeFileSync(path.join(relayDir(dataDir), 'team.json'), JSON.stringify({ v: 1, peers: [], sharedProjects: [] }))
+}
+const validKey = (): string => publicKeyToB64(genKeyPair().publicKey)
+
+const INFO = { relayEndpoint: 'wss://r', hostId: 'H', hostPublicKeyB64: 'P', hostDeviceId: 'D', label: 'box' }
+const offStatus: HostedStatus = { enabled: false, scheduler: null, peers: [], pending: [] }
+const onStatus: HostedStatus = {
+ enabled: true,
+ scheduler: { state: 'running', lastError: null, mintsLastHour: 1, idle: 1, bridged: 0 },
+ peers: [],
+ pending: []
+}
+
+interface FakeOpts {
+ running?: boolean
+ start?: string
+ rotate?: string
+ remove?: 'removed' | 'last-owner' | 'unknown'
+ initThrows?: Error
+}
+function fakeService(o: FakeOpts = {}): { svc: HostedService; calls: string[] } {
+ const calls: string[] = []
+ let running = o.running ?? false
+ const svc = {
+ init: async () => {
+ calls.push('init')
+ if (o.initThrows) throw o.initThrows
+ return { created: true }
+ },
+ start: async () => {
+ calls.push('start')
+ const r = o.start ?? 'started'
+ if (r === 'started') running = true
+ return r
+ },
+ stop: () => {
+ calls.push('stop')
+ running = false
+ },
+ addOwner: async (k: string, label: string) => {
+ calls.push(`owner:${k}:${label}`)
+ },
+ remove: async (k: string, force: boolean) => {
+ calls.push(`remove:${k}:${force}`)
+ return o.remove ?? 'removed'
+ },
+ share: async (p: string, on: boolean) => {
+ calls.push(`share:${p}:${on}`)
+ },
+ info: () => (running ? INFO : null),
+ joinCode: () => (running ? 'nodeterm://join/CODE' : null),
+ status: () => (running ? onStatus : offStatus),
+ rotateKey: async () => {
+ calls.push('rotate')
+ const r = o.rotate ?? (running ? 'started' : 'not-running')
+ return r
+ }
+ } as unknown as HostedService
+ return { svc, calls }
+}
+
+async function boot(dataDir: string, svc: HostedService): Promise<void> {
+ const admin = await startTeamAdmin(dataDir, svc)
+ closers.push(() => admin.close())
+}
+
+/** Send raw bytes over the socket and collect whatever comes back until the server ends it. */
+function rawExchange(dataDir: string, payload: string): Promise<string> {
+ return new Promise((resolve) => {
+ const c = net.connect(adminSocketPath(dataDir))
+ let buf = ''
+ c.setEncoding('utf8')
+ c.on('connect', () => c.write(payload))
+ c.on('data', (d) => (buf += d))
+ c.on('close', () => resolve(buf))
+ c.on('error', () => resolve(buf))
+ })
+}
+
+describe('validation helpers (platform-neutral)', () => {
+ it('accepts a canonical 32-byte base64 key and says what is wrong with anything else', () => {
+ expect(ownerKeyProblem(validKey())).toBeNull()
+ expect(ownerKeyProblem('K')).toMatch(/32 bytes/)
+ expect(ownerKeyProblem(Buffer.alloc(31).toString('base64'))).toMatch(/32 bytes.*31/)
+ const k = validKey()
+ // Missing padding still decodes to 32 bytes, but would never equal the key a peer presents.
+ expect(ownerKeyProblem(k.replace(/=$/, ''))).toMatch(/canonical/)
+ expect(ownerKeyProblem(` ${k}`)).toMatch(/canonical/)
+ expect(ownerKeyProblem(k.replace(/\+/g, '-').replace(/\//g, '_').replace(/=$/, ''))).not.toBeNull()
+ })
+
+ it('labels are at most 60 characters and control-free', () => {
+ expect(ownerLabelProblem('')).toBeNull()
+ expect(ownerLabelProblem('Enes Kırca')).toBeNull()
+ expect(ownerLabelProblem('x'.repeat(60))).toBeNull()
+ expect(ownerLabelProblem('x'.repeat(61))).toMatch(/61.*60/)
+ expect(ownerLabelProblem('a\nb')).toMatch(/control/)
+ expect(ownerLabelProblem('a\u001b[31m')).toMatch(/control/)
+ expect(ownerLabelProblem('a‮b')).toMatch(/control/)
+ })
+
+ it('project ids are non-empty, bounded and control-free', () => {
+ expect(projectIdProblem('p-123')).toBeNull()
+ expect(projectIdProblem('')).toMatch(/empty/)
+ expect(projectIdProblem('x'.repeat(129))).toMatch(/128/)
+ expect(projectIdProblem('a\tb')).toMatch(/control/)
+ })
+
+ it('parses only well-formed requests', () => {
+ const k = validKey()
+ expect(parseAdminRequest({ cmd: 'init' })).toEqual({ cmd: 'init' })
+ expect(parseAdminRequest({ cmd: 'add-owner', pubkey: k, label: 'E' })).toEqual({ cmd: 'add-owner', pubkey: k, label: 'E' })
+ expect(parseAdminRequest({ cmd: 'add-owner', pubkey: 'K', label: 'E' })).toMatch(/32 bytes/)
+ expect(parseAdminRequest({ cmd: 'remove', pubkey: 'K', force: true })).toEqual({ cmd: 'remove', pubkey: 'K', force: true })
+ expect(parseAdminRequest({ cmd: 'remove', pubkey: 'K', force: 'yes' })).toMatch(/force/)
+ expect(parseAdminRequest({ cmd: 'share', projectId: 'P', on: true })).toEqual({ cmd: 'share', projectId: 'P', on: true })
+ expect(parseAdminRequest({ cmd: 'share', projectId: 7, on: true })).toMatch(/project/)
+ expect(parseAdminRequest({ cmd: 'share', projectId: 'P' })).toMatch(/on/)
+ expect(parseAdminRequest({ cmd: 'nuke' })).toMatch(/unknown command/)
+ expect(parseAdminRequest(null)).toMatch(/bad request/)
+ expect(parseAdminRequest([1])).toMatch(/bad request/)
+ })
+
+ it('a socket path longer than a unix socket allows is refused by name, per platform', () => {
+ expect(socketPathProblem('/s/' + 'x'.repeat(104), 'linux')).toBeNull() // 107 bytes
+ expect(socketPathProblem('/s/' + 'x'.repeat(105), 'linux')).toMatch(/108 bytes.*107/)
+ expect(socketPathProblem('/s/' + 'x'.repeat(100), 'darwin')).toBeNull() // 103 bytes
+ expect(socketPathProblem('/s/' + 'x'.repeat(101), 'darwin')).toMatch(/104 bytes.*103/)
+ expect(socketPathProblem('/short', 'win32')).toMatch(/Windows/)
+ })
+})
+
+// The admin channel is a unix socket: POSIX only (the Server Edition targets Linux, and Windows is
+// refused by name above). The mode assertions are POSIX permission bits as well.
+describe.skipIf(process.platform === 'win32')('team admin socket (unix socket, POSIX only)', () => {
+ it('lives in a 0700 relay dir, is 0600, and answers commands', async () => {
+ const dataDir = tmp()
+ writeTeam(dataDir)
+ const { svc, calls } = fakeService({ running: true })
+ await boot(dataDir, svc)
+ expect((fs.statSync(adminSocketPath(dataDir)).mode & 0o777).toString(8)).toBe('600')
+ expect((fs.statSync(relayDir(dataDir)).mode & 0o777).toString(8)).toBe('700')
+ const k = validKey()
+ expect(await callTeamAdmin(dataDir, { cmd: 'add-owner', pubkey: k, label: 'E' })).toEqual({ ok: true, result: null })
+ expect(await callTeamAdmin(dataDir, { cmd: 'share', projectId: 'P', on: false })).toEqual({ ok: true, result: null })
+ expect(await callTeamAdmin(dataDir, { cmd: 'remove', pubkey: k, force: true })).toEqual({ ok: true, result: null })
+ expect(await callTeamAdmin(dataDir, { cmd: 'info' })).toEqual({
+ ok: true,
+ result: { enabled: true, info: INFO, joinCode: 'nodeterm://join/CODE' }
+ })
+ expect(calls).toEqual([`owner:${k}:E`, 'share:P:false', `remove:${k}:true`])
+ })
+
+ it('tightens an existing relay dir to 0700', async () => {
+ const dataDir = tmp()
+ fs.mkdirSync(relayDir(dataDir), { mode: 0o755 })
+ fs.chmodSync(relayDir(dataDir), 0o755)
+ await boot(dataDir, fakeService().svc)
+ expect((fs.statSync(relayDir(dataDir)).mode & 0o777).toString(8)).toBe('700')
+ })
+
+ it('init creates, starts, and hands back the join code and address when hosting runs', async () => {
+ const dataDir = tmp()
+ const { svc, calls } = fakeService()
+ await boot(dataDir, svc)
+ expect(await callTeamAdmin(dataDir, { cmd: 'init' })).toEqual({
+ ok: true,
+ result: { created: true, start: 'started', info: INFO, joinCode: 'nodeterm://join/CODE' }
+ })
+ expect(calls).toEqual(['init', 'start'])
+ })
+
+ it('init reports a start that did not happen, with no join code', async () => {
+ const dataDir = tmp()
+ await boot(dataDir, fakeService({ start: 'stopped' }).svc)
+ expect(await callTeamAdmin(dataDir, { cmd: 'init' })).toEqual({
+ ok: true,
+ result: { created: true, start: 'stopped', info: null, joinCode: null }
+ })
+ })
+
+ it('a service error becomes the reply, verbatim', async () => {
+ const dataDir = tmp()
+ await boot(dataDir, fakeService({ initThrows: new Error('The team host key could not be read (malformed).') }).svc)
+ expect(await callTeamAdmin(dataDir, { cmd: 'init' })).toEqual({ ok: false, error: 'The team host key could not be read (malformed).' })
+ })
+
+ it('remove: the last owner and an unknown key are refusals with a reason', async () => {
+ const dataDir = tmp()
+ writeTeam(dataDir)
+ await boot(dataDir, fakeService({ remove: 'last-owner' }).svc)
+ expect(await callTeamAdmin(dataDir, { cmd: 'remove', pubkey: 'K' })).toEqual({ ok: false, error: expect.stringMatching(/last owner.*--force/) })
+ const other = tmp()
+ writeTeam(other)
+ await boot(other, fakeService({ remove: 'unknown' }).svc)
+ expect(await callTeamAdmin(other, { cmd: 'remove', pubkey: 'K' })).toEqual({ ok: false, error: expect.stringMatching(/No team member/) })
+ })
+
+ it('with no team on this server it serves only init, status and info', async () => {
+ const dataDir = tmp()
+ const { svc, calls } = fakeService()
+ await boot(dataDir, svc)
+ for (const req of [
+ { cmd: 'add-owner' as const, pubkey: validKey(), label: 'E' },
+ { cmd: 'remove' as const, pubkey: 'K' },
+ { cmd: 'share' as const, projectId: 'P', on: true },
+ { cmd: 'rotate-key' as const }
+ ]) {
+ expect(await callTeamAdmin(dataDir, req)).toEqual({ ok: false, error: expect.stringMatching(/no hosted team.*team init/i) })
+ }
+ expect(calls).toEqual([])
+ expect(fs.existsSync(path.join(relayDir(dataDir), 'team.json'))).toBe(false)
+ expect((await callTeamAdmin(dataDir, { cmd: 'status' })).ok).toBe(true)
+ expect((await callTeamAdmin(dataDir, { cmd: 'info' })).ok).toBe(true)
+ })
+
+ it('a host key with no team.json still counts as set up (so `team rotate-key` is never a dead end)', async () => {
+ const dataDir = tmp()
+ fs.mkdirSync(relayDir(dataDir), { recursive: true })
+ fs.writeFileSync(path.join(relayDir(dataDir), 'host-key.json'), 'garbage')
+ const { svc, calls } = fakeService()
+ await boot(dataDir, svc)
+ expect(await callTeamAdmin(dataDir, { cmd: 'rotate-key' })).toEqual({
+ ok: true,
+ result: { result: 'not-running', info: null, joinCode: null }
+ })
+ expect(calls).toEqual(['rotate'])
+ })
+
+ it('a running service counts as set up even when team.json was set aside as corrupt', async () => {
+ const dataDir = tmp()
+ const { svc, calls } = fakeService({ running: true })
+ await boot(dataDir, svc)
+ const k = validKey()
+ expect((await callTeamAdmin(dataDir, { cmd: 'add-owner', pubkey: k, label: '' })).ok).toBe(true)
+ expect(calls).toEqual([`owner:${k}:`])
+ })
+
+ it('rotate-key reports honestly whether hosting restarted', async () => {
+ const off = tmp()
+ writeTeam(off)
+ await boot(off, fakeService({ running: false }).svc)
+ expect(await callTeamAdmin(off, { cmd: 'rotate-key' })).toEqual({
+ ok: true,
+ result: { result: 'not-running', info: null, joinCode: null }
+ })
+ const on = tmp()
+ writeTeam(on)
+ await boot(on, fakeService({ running: true }).svc)
+ expect(await callTeamAdmin(on, { cmd: 'rotate-key' })).toEqual({
+ ok: true,
+ result: { result: 'started', info: INFO, joinCode: 'nodeterm://join/CODE' }
+ })
+ })
+
+ it('status says WHY hosting is off, reading the relay dir', async () => {
+ const dataDir = tmp()
+ await boot(dataDir, fakeService().svc)
+ const off = async (): Promise<unknown> => {
+ const r = (await callTeamAdmin(dataDir, { cmd: 'status' })) as AdminReply
+ return r.ok ? (r.result as { off: unknown }).off : r
+ }
+ expect(await off()).toEqual({ reason: 'no-team' })
+ writeTeam(dataDir)
+ expect(await off()).toEqual({ reason: 'no-host-key' })
+ fs.writeFileSync(path.join(relayDir(dataDir), 'host-key.json'), '{not json')
+ expect(await off()).toEqual({ reason: 'host-key-unreadable', detail: expect.stringMatching(/could not be read/) })
+ fs.rmSync(path.join(relayDir(dataDir), 'host-key.json'))
+ await createHostKey(relayDir(dataDir))
+ expect(await off()).toEqual({ reason: 'stopped' })
+ })
+
+ it('status while running carries the service status and no off reason', async () => {
+ const dataDir = tmp()
+ writeTeam(dataDir)
+ await boot(dataDir, fakeService({ running: true }).svc)
+ expect(await callTeamAdmin(dataDir, { cmd: 'status' })).toEqual({ ok: true, result: { ...onStatus, off: null } })
+ })
+
+ it('malformed lines are answered, never crash the server', async () => {
+ const dataDir = tmp()
+ await boot(dataDir, fakeService().svc)
+ expect(JSON.parse(await rawExchange(dataDir, 'not json\n'))).toEqual({ ok: false, error: expect.stringMatching(/bad request/) })
+ expect(JSON.parse(await rawExchange(dataDir, '{"cmd":"nuke"}\n'))).toEqual({ ok: false, error: expect.stringMatching(/unknown command/) })
+ // Still serving afterwards.
+ expect((await callTeamAdmin(dataDir, { cmd: 'status' })).ok).toBe(true)
+ })
+
+ it('an oversized request is cut off without an answer', async () => {
+ const dataDir = tmp()
+ await boot(dataDir, fakeService().svc)
+ const reply = await rawExchange(dataDir, 'x'.repeat(ADMIN_REQUEST_MAX + 10))
+ expect(reply).toBe('')
+ expect((await callTeamAdmin(dataDir, { cmd: 'status' })).ok).toBe(true)
+ })
+
+ it('callTeamAdmin with no server says the service is not running, and names the path', async () => {
+ const dataDir = tmp()
+ const r = await callTeamAdmin(dataDir, { cmd: 'status' })
+ expect(r).toEqual({ ok: false, error: expect.stringMatching(/not running/) })
+ expect((r as { error: string }).error).toContain(adminSocketPath(dataDir))
+ })
+
+ it('a stale socket file from a crashed run is replaced', async () => {
+ const dataDir = tmp()
+ fs.mkdirSync(relayDir(dataDir), { recursive: true })
+ const sock = adminSocketPath(dataDir)
+ // A real crash: a process binds the path and is SIGKILLed, so nothing unlinks the file.
+ const child = spawn(process.execPath, [
+ '-e',
+ `require('net').createServer().listen(${JSON.stringify(sock)}, () => console.log('up'))`
+ ])
+ await new Promise<void>((r) => child.stdout.once('data', () => r()))
+ child.kill('SIGKILL')
+ await new Promise<void>((r) => child.once('exit', () => r()))
+ expect(fs.lstatSync(sock).isSocket()).toBe(true)
+ await boot(dataDir, fakeService().svc)
+ expect((await callTeamAdmin(dataDir, { cmd: 'status' })).ok).toBe(true)
+ })
+
+ it('refuses to steal the socket from a live admin server', async () => {
+ const dataDir = tmp()
+ await boot(dataDir, fakeService().svc)
+ await expect(startTeamAdmin(dataDir, fakeService().svc)).rejects.toThrow(/already answering/)
+ // The first one is untouched.
+ expect((await callTeamAdmin(dataDir, { cmd: 'status' })).ok).toBe(true)
+ })
+
+ it('refuses to remove something at the socket path that is not a socket', async () => {
+ const dataDir = tmp()
+ fs.mkdirSync(relayDir(dataDir), { recursive: true })
+ fs.writeFileSync(adminSocketPath(dataDir), 'mine')
+ await expect(startTeamAdmin(dataDir, fakeService().svc)).rejects.toThrow(/not a socket/)
+ expect(fs.readFileSync(adminSocketPath(dataDir), 'utf8')).toBe('mine')
+ })
+
+ it('a data dir too long for a unix socket fails with a clear message, on both ends', async () => {
+ const base = tmp()
+ const dataDir = path.join(base, 'd'.repeat(Math.max(1, 110 - base.length)))
+ fs.mkdirSync(dataDir, { recursive: true })
+ expect(Buffer.byteLength(adminSocketPath(dataDir))).toBeGreaterThan(107)
+ await expect(startTeamAdmin(dataDir, fakeService().svc)).rejects.toThrow(/shorter data directory/)
+ expect(await callTeamAdmin(dataDir, { cmd: 'status' })).toEqual({ ok: false, error: expect.stringMatching(/shorter data directory/) })
+ })
+
+ it('close() removes the socket and does not hang on a connection that never sends a request', async () => {
+ const dataDir = tmp()
+ const admin = await startTeamAdmin(dataDir, fakeService().svc)
+ const idle = net.connect(adminSocketPath(dataDir))
+ idle.on('error', () => {})
+ await new Promise<void>((r) => idle.on('connect', () => r()))
+ await admin.close()
+ expect(fs.existsSync(adminSocketPath(dataDir))).toBe(false)
+ idle.destroy()
+ })
+})
diff --git a/src/core/relay/team-admin.ts b/src/core/relay/team-admin.ts
new file mode 100644
index 000000000..8046a42f1
--- /dev/null
+++ b/src/core/relay/team-admin.ts
@@ -0,0 +1,450 @@
+// Local admin channel for the hosted team: a unix socket at <dataDir>/relay/admin.sock, mode 0600
+// in a 0700 directory, speaking one JSON line each way. Filesystem permissions ARE the gate — there
+// is no token, so nothing to leak into a pane's environment. Any process running as this unix user
+// can reach it, which is exactly who could already read host-key.json: SSH access as the core's user
+// is the root of trust. (The 0700 directory is the real gate; the socket's own 0600 is belt and
+// braces, since the socket exists at the process umask for the instant between bind and chmod.)
+//
+// Unix sockets are POSIX. The Server Edition targets Linux; on Windows both ends refuse by name
+// rather than failing with an obscure error (the platform rule: degrade explicitly, never silently).
+//
+// With no hosted team on this server, the channel serves `init`, `status` and `info` only: every
+// other verb would create team state (a team.json, a host key) on a server that never asked to host.
+import net from 'node:net'
+import path from 'node:path'
+import { chmodSync, lstatSync, rmSync } from 'node:fs'
+import { ensurePrivateDir } from './private-dir'
+import { TeamStore, TEAM_LABEL_MAX, TEAM_PROJECT_ID_MAX } from './team-store'
+import { loadHostKey } from './host-key'
+import { publicKeyFromB64, publicKeyToB64 } from './e2ee'
+import type {
+ HostedInfo,
+ HostedRotateResult,
+ HostedService,
+ HostedStartResult,
+ HostedStatus
+} from './hosted-service'
+
+export type AdminRequest =
+ | { cmd: 'init' }
+ | { cmd: 'add-owner'; pubkey: string; label: string }
+ | { cmd: 'remove'; pubkey: string; force?: boolean }
+ | { cmd: 'info' }
+ | { cmd: 'status' }
+ | { cmd: 'share'; projectId: string; on: boolean }
+ | { cmd: 'rotate-key' }
+export type AdminReply = { ok: true; result: unknown } | { ok: false; error: string }
+
+/** `init`'s answer. The address and join code are present only when hosting is running. */
+export interface AdminInitResult {
+ created: boolean
+ start: HostedStartResult
+ info: HostedInfo | null
+ joinCode: string | null
+}
+/** `info`'s answer. `info` can be non-null while `enabled` is false (a key rotated while hosting
+ * was off): that address answers nobody until hosting starts. */
+export interface AdminInfoResult {
+ enabled: boolean
+ info: HostedInfo | null
+ joinCode: string | null
+}
+/** `rotate-key`'s answer. The new address and join code are present only when hosting restarted. */
+export interface AdminRotateResult {
+ result: HostedRotateResult
+ info: HostedInfo | null
+ joinCode: string | null
+}
+/** Why hosting is off, read from the relay directory at the moment `status` asked. */
+export type HostingOff =
+ | { reason: 'no-team' }
+ | { reason: 'no-host-key' }
+ | { reason: 'host-key-unreadable'; detail: string }
+ | { reason: 'stopped' }
+/** `status`'s answer: the service's own status, plus the reason when hosting is off. */
+export interface AdminStatusResult extends HostedStatus {
+ off: HostingOff | null
+}
+
+/** The longest request line the server reads. A request is a few hundred bytes. */
+export const ADMIN_REQUEST_MAX = 64 * 1024
+/** A connection that has not sent its request line by then is dropped. */
+const REQUEST_IDLE_MS = 10_000
+/** How long the CLI waits for an answer. `init` and `rotate-key` do local file work only. */
+const CALL_TIMEOUT_MS = 30_000
+/** How long probing an existing socket may take before it is treated as "cannot tell". */
+const PROBE_TIMEOUT_MS = 2_000
+/** A `remove` key is compared, never decoded: bound it only so a line cannot be all key. */
+const REMOVE_KEY_MAX = 256
+
+const NO_TEAM = 'There is no hosted team on this server yet. Run `team init` first.'
+
+export function adminSocketPath(dataDir: string): string {
+ return path.join(relayDirOf(dataDir), 'admin.sock')
+}
+const relayDirOf = (dataDir: string): string => path.join(dataDir, 'relay')
+
+/**
+ * Why `sock` cannot be a unix socket path here, or null. `sun_path` is 108 bytes on Linux and 104 on
+ * the BSDs (macOS included), one of them the terminating NUL. Measured on Linux (Node 22): a longer
+ * path is TRUNCATED silently — the socket file lands under a shorter name, so the chmod that follows
+ * fails with an ENOENT that says nothing about length. Hence the explicit check, on both ends.
+ */
+export function socketPathProblem(sock: string, platform: NodeJS.Platform = process.platform): string | null {
+ if (platform === 'win32') {
+ return 'The team admin channel is a unix socket, which is not available on Windows. Run the Server Edition on Linux.'
+ }
+ const max = platform === 'linux' || platform === 'android' ? 107 : 103
+ const bytes = Buffer.byteLength(sock)
+ if (bytes <= max) return null
+ return (
+ `The team admin socket path is ${bytes} bytes long; a unix socket path may be at most ${max}. ` +
+ `Use a shorter data directory (--data-dir / NODETERM_DATA_DIR): ${sock}`
+ )
+}
+
+// ---- validation (one definition: the CLI refuses a typo before the socket, the server refuses it again)
+
+/** Why `key` is not a device key a peer could ever present, or null. A key is compared as a STRING
+ * against the canonical base64 the relay handshake reports, so a key that merely decodes to 32 bytes
+ * (missing padding, stray whitespace — Node's base64 decoder skips both) would be written to the
+ * team and never match anyone. */
+export function ownerKeyProblem(key: string): string | null {
+ let bytes: Uint8Array
+ try {
+ bytes = publicKeyFromB64(key)
+ } catch {
+ const got = Buffer.from(key, 'base64').length
+ return (
+ `That is not a device key: a device key is 32 bytes of base64 (44 characters ending in "="), ` +
+ `and this decodes to ${got} bytes. Check that the whole key was copied.`
+ )
+ }
+ if (publicKeyToB64(bytes) !== key) {
+ return (
+ 'That is not a device key in canonical base64 form — check for a typo, a missing "=", ' +
+ 'spaces, or "-"/"_" in place of "+"/"/".'
+ )
+ }
+ return null
+}
+
+// C0/C1 controls and DEL (\p{Cc}), plus the text-direction controls that let a label reorder the
+// text around it when printed in a terminal.
+const CONTROL_RE = /[\p{Cc}؜‎‏‪-‮⁦-⁩]/u
+
+/** Why `label` cannot be a member label, or null. The same limit `team.json`'s reader enforces. */
+export function ownerLabelProblem(label: string): string | null {
+ if (label.length > TEAM_LABEL_MAX) {
+ return `The label is ${label.length} characters long; the limit is ${TEAM_LABEL_MAX}.`
+ }
+ if (CONTROL_RE.test(label)) {
+ return 'The label contains a control character (a newline, tab, escape or text-direction control); use plain text.'
+ }
+ return null
+}
+
+/** Why `id` cannot be a shared project id, or null. The same limit `team.json`'s reader enforces. */
+export function projectIdProblem(id: string): string | null {
+ if (id.length === 0) return 'The project id is empty.'
+ if (id.length > TEAM_PROJECT_ID_MAX) {
+ return `The project id is ${id.length} characters long; the limit is ${TEAM_PROJECT_ID_MAX}.`
+ }
+ if (CONTROL_RE.test(id)) return 'The project id contains a control character.'
+ return null
+}
+
+/** A well-formed request, or the reason it is not. The server's own check: the CLI is one client,
+ * but anything running as this user can write to the socket. */
+export function parseAdminRequest(raw: unknown): AdminRequest | string {
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return 'bad request: expected a JSON object'
+ const o = raw as Record<string, unknown>
+ switch (o.cmd) {
+ case 'init':
+ case 'info':
+ case 'status':
+ case 'rotate-key':
+ return { cmd: o.cmd }
+ case 'add-owner': {
+ if (typeof o.pubkey !== 'string') return 'bad request: add-owner needs a pubkey string'
+ if (typeof o.label !== 'string') return 'bad request: add-owner needs a label string'
+ const problem = ownerKeyProblem(o.pubkey) ?? ownerLabelProblem(o.label)
+ return problem ?? { cmd: 'add-owner', pubkey: o.pubkey, label: o.label }
+ }
+ case 'remove': {
+ if (typeof o.pubkey !== 'string' || o.pubkey.length === 0 || o.pubkey.length > REMOVE_KEY_MAX) {
+ return 'bad request: remove needs a pubkey string'
+ }
+ if (o.force !== undefined && typeof o.force !== 'boolean') return 'bad request: remove force must be a boolean'
+ return o.force === undefined ? { cmd: 'remove', pubkey: o.pubkey } : { cmd: 'remove', pubkey: o.pubkey, force: o.force }
+ }
+ case 'share': {
+ if (typeof o.projectId !== 'string') return 'bad request: share needs a projectId string'
+ if (typeof o.on !== 'boolean') return 'bad request: share needs on (a boolean)'
+ return projectIdProblem(o.projectId) ?? { cmd: 'share', projectId: o.projectId, on: o.on }
+ }
+ default:
+ return `bad request: unknown command ${JSON.stringify(typeof o.cmd === 'string' ? o.cmd.slice(0, 40) : o.cmd)}`
+ }
+}
+
+// ---- handling
+
+type KeyState = 'absent' | 'present' | { unreadable: string }
+
+async function hostKeyState(relayDir: string): Promise<KeyState> {
+ try {
+ return (await loadHostKey(relayDir)) === null ? 'absent' : 'present'
+ } catch (err) {
+ return { unreadable: err instanceof Error ? err.message : String(err) }
+ }
+}
+
+/** Has a hosted team been set up on this server? A running service, a team.json, or a host key in
+ * any state (an unreadable key must still be rotatable — its own error message says to). A
+ * team.json set aside as corrupt while hosting runs is still a team: the recovery is `add-owner`. */
+async function teamIsSetUp(relayDir: string, svc: HostedService): Promise<boolean> {
+ if (svc.status().enabled) return true
+ if (new TeamStore(relayDir).exists()) return true
+ return (await hostKeyState(relayDir)) !== 'absent'
+}
+
+async function offReason(relayDir: string): Promise<HostingOff> {
+ const key = await hostKeyState(relayDir)
+ if (typeof key === 'object') return { reason: 'host-key-unreadable', detail: key.unreadable }
+ if (!new TeamStore(relayDir).exists()) return { reason: 'no-team' }
+ if (key === 'absent') return { reason: 'no-host-key' }
+ return { reason: 'stopped' }
+}
+
+const ok = (result: unknown): AdminReply => ({ ok: true, result })
+const fail = (error: string): AdminReply => ({ ok: false, error })
+
+/** The address teammates need — only while hosting actually runs. */
+const address = (svc: HostedService, running: boolean): { info: HostedInfo | null; joinCode: string | null } =>
+ running ? { info: svc.info(), joinCode: svc.joinCode() } : { info: null, joinCode: null }
+
+async function handle(relayDir: string, svc: HostedService, req: AdminRequest): Promise<AdminReply> {
+ if (req.cmd !== 'init' && req.cmd !== 'status' && req.cmd !== 'info' && !(await teamIsSetUp(relayDir, svc))) {
+ return fail(NO_TEAM)
+ }
+ switch (req.cmd) {
+ case 'init': {
+ const { created } = await svc.init()
+ const start = await svc.start()
+ const result: AdminInitResult = { created, start, ...address(svc, start === 'started') }
+ return ok(result)
+ }
+ case 'add-owner':
+ await svc.addOwner(req.pubkey, req.label)
+ return ok(null)
+ case 'remove': {
+ const r = await svc.remove(req.pubkey, !!req.force)
+ if (r === 'last-owner') return fail('That is the last owner. Add another owner first, or pass --force.')
+ if (r === 'unknown') return fail('No team member has that key.')
+ return ok(null)
+ }
+ case 'info': {
+ const result: AdminInfoResult = { enabled: svc.status().enabled, info: svc.info(), joinCode: svc.joinCode() }
+ return ok(result)
+ }
+ case 'status': {
+ const s = svc.status()
+ const result: AdminStatusResult = { ...s, off: s.enabled ? null : await offReason(relayDir) }
+ return ok(result)
+ }
+ case 'share':
+ await svc.share(req.projectId, req.on)
+ return ok(null)
+ case 'rotate-key': {
+ const r = await svc.rotateKey()
+ const result: AdminRotateResult = { result: r, ...address(svc, r === 'started') }
+ return ok(result)
+ }
+ }
+}
+
+async function answer(relayDir: string, svc: HostedService, line: string): Promise<AdminReply> {
+ let raw: unknown
+ try {
+ raw = JSON.parse(line)
+ } catch {
+ return fail('bad request: not JSON')
+ }
+ const req = parseAdminRequest(raw)
+ if (typeof req === 'string') return fail(req)
+ try {
+ return await handle(relayDir, svc, req)
+ } catch (err) {
+ return fail(err instanceof Error ? err.message : String(err))
+ }
+}
+
+// ---- the server
+
+/**
+ * Clear the way for a fresh bind: nothing there is fine, a socket nobody answers on (a crashed run)
+ * is removed. A socket that ANSWERS belongs to a live server sharing this data dir, and anything that
+ * is not a socket is not ours — both are refused, never removed. Only a refused connection proves a
+ * socket dead; a timeout or any other error is "cannot tell", which also refuses.
+ */
+async function clearStaleSocket(sock: string): Promise<void> {
+ let isSocket: boolean
+ try {
+ isSocket = lstatSync(sock).isSocket()
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return
+ throw err
+ }
+ if (!isSocket) throw new Error(`${sock} exists and is not a socket; refusing to remove it.`)
+ const verdict = await new Promise<'live' | 'dead' | string>((resolve) => {
+ const c = net.connect(sock)
+ const timer = setTimeout(() => {
+ c.destroy()
+ resolve('no answer in time')
+ }, PROBE_TIMEOUT_MS)
+ c.once('connect', () => {
+ clearTimeout(timer)
+ c.destroy()
+ resolve('live')
+ })
+ c.once('error', (err: NodeJS.ErrnoException) => {
+ clearTimeout(timer)
+ resolve(err.code === 'ECONNREFUSED' ? 'dead' : (err.code ?? err.message))
+ })
+ })
+ if (verdict === 'dead') {
+ rmSync(sock, { force: true })
+ return
+ }
+ if (verdict === 'live') {
+ throw new Error(
+ `Another nodeterm server is already answering on ${sock} (two servers sharing one data directory?). Not replacing it.`
+ )
+ }
+ throw new Error(`Could not tell whether ${sock} is still in use (${verdict}); not replacing it.`)
+}
+
+export async function startTeamAdmin(dataDir: string, svc: HostedService): Promise<{ close(): Promise<void> }> {
+ const sock = adminSocketPath(dataDir)
+ const problem = socketPathProblem(sock)
+ if (problem) throw new Error(problem)
+ const relayDir = relayDirOf(dataDir)
+ ensurePrivateDir(relayDir)
+ await clearStaleSocket(sock)
+
+ const conns = new Set<net.Socket>()
+ const server = net.createServer((c) => {
+ conns.add(c)
+ c.on('close', () => conns.delete(c))
+ c.on('error', () => {}) // the peer went away; nothing to tell it
+ c.setEncoding('utf8')
+ c.setTimeout(REQUEST_IDLE_MS, () => c.destroy())
+ let buf = ''
+ let taken = false
+ c.on('data', (d: string) => {
+ if (taken) return
+ buf += d
+ const nl = buf.indexOf('\n')
+ if (nl < 0 ? buf.length > ADMIN_REQUEST_MAX : nl > ADMIN_REQUEST_MAX) {
+ taken = true
+ c.destroy()
+ return
+ }
+ if (nl < 0) return
+ taken = true
+ c.setTimeout(0)
+ void answer(relayDir, svc, buf.slice(0, nl)).then((reply) => {
+ if (!c.destroyed) c.end(JSON.stringify(reply) + '\n')
+ })
+ })
+ })
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(sock, () => {
+ server.off('error', reject)
+ resolve()
+ })
+ })
+ try {
+ chmodSync(sock, 0o600)
+ } catch (err) {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ throw err
+ }
+
+ let closing: Promise<void> | null = null
+ return {
+ close: () =>
+ (closing ??= new Promise<void>((resolve) => {
+ server.close(() => {
+ // Node unlinks the socket file itself on close; this covers a platform that does not.
+ rmSync(sock, { force: true })
+ resolve()
+ })
+ // An idle or slow connection would otherwise hold close() open.
+ for (const c of conns) c.destroy()
+ }))
+ }
+}
+
+// ---- the client
+
+function connectErrorMessage(err: NodeJS.ErrnoException, sock: string): string {
+ if (err.code === 'ENOENT' || err.code === 'ECONNREFUSED') {
+ return (
+ `The nodeterm server is not running (no admin socket at ${sock}). Start the service first. ` +
+ `If it runs with a different data directory, pass --data-dir <dir> (or set NODETERM_DATA_DIR); ` +
+ `a server from before this version has no admin socket and needs a restart after updating.`
+ )
+ }
+ if (err.code === 'EACCES' || err.code === 'EPERM') {
+ return `Permission denied on ${sock}. Run \`team\` as the unix user the nodeterm server runs as.`
+ }
+ return `Could not reach the nodeterm server at ${sock}: ${err.code ?? err.message}.`
+}
+
+function parseReply(line: string): AdminReply {
+ try {
+ const r = JSON.parse(line) as Record<string, unknown> | null
+ if (r && r.ok === true && 'result' in r) return { ok: true, result: r.result }
+ if (r && r.ok === false && typeof r.error === 'string') return { ok: false, error: r.error }
+ } catch {
+ // fall through
+ }
+ return fail('The nodeterm server sent a reply this CLI does not understand (is the server a different version?).')
+}
+
+export function callTeamAdmin(dataDir: string, req: AdminRequest): Promise<AdminReply> {
+ const sock = adminSocketPath(dataDir)
+ const problem = socketPathProblem(sock)
+ if (problem) return Promise.resolve(fail(problem))
+ return new Promise((resolve) => {
+ let done = false
+ let buf = ''
+ const c = net.connect(sock)
+ const timer = setTimeout(
+ () => finish(fail(`The nodeterm server did not answer within ${CALL_TIMEOUT_MS / 1000} s (${sock}).`)),
+ CALL_TIMEOUT_MS
+ )
+ function finish(r: AdminReply): void {
+ if (done) return
+ done = true
+ clearTimeout(timer)
+ c.destroy()
+ resolve(r)
+ }
+ c.setEncoding('utf8')
+ c.on('connect', () => c.write(JSON.stringify(req) + '\n'))
+ c.on('data', (d: string) => {
+ buf += d
+ const nl = buf.indexOf('\n')
+ if (nl >= 0) finish(parseReply(buf.slice(0, nl)))
+ else if (buf.length > ADMIN_REQUEST_MAX) finish(parseReply(''))
+ })
+ c.on('end', () =>
+ finish(buf.trim() ? parseReply(buf) : fail('The nodeterm server closed the connection without answering.'))
+ )
+ c.on('error', (err: NodeJS.ErrnoException) => finish(fail(connectErrorMessage(err, sock))))
+ })
+}
diff --git a/src/core/relay/team-store.ts b/src/core/relay/team-store.ts
index c1fcb2a91..97e0ce825 100644
--- a/src/core/relay/team-store.ts
+++ b/src/core/relay/team-store.ts
@@ -17,7 +17,10 @@ export const TEAM_ROLES: readonly TeamRole[] = ['owner', 'editor', 'commenter',
export interface TeamPeer { pubkeyB64: string; label: string; role: TeamRole; addedAt: string; addedBy: string }
export interface TeamDoc { v: 1; peers: TeamPeer[]; sharedProjects: string[] }
-const LABEL_MAX = 60
+/** The longest member label `team.json` accepts. Exported so the admin CLI refuses what this reader would. */
+export const TEAM_LABEL_MAX = 60
+/** The longest shared project id `team.json` accepts. */
+export const TEAM_PROJECT_ID_MAX = 128
const isStr = (v: unknown, max = 512): v is string => typeof v === 'string' && v.length > 0 && v.length <= max
export function emptyTeam(): TeamDoc {
@@ -35,14 +38,14 @@ export function parseTeam(raw: unknown): TeamDoc | null {
for (const p of o.peers) {
if (!p || typeof p !== 'object') return null
const q = p as Record<string, unknown>
- if (!isStr(q.pubkeyB64, 64) || typeof q.label !== 'string' || q.label.length > LABEL_MAX) return null
+ if (!isStr(q.pubkeyB64, 64) || typeof q.label !== 'string' || q.label.length > TEAM_LABEL_MAX) return null
if (!(TEAM_ROLES as readonly unknown[]).includes(q.role)) return null
if (!isStr(q.addedAt, 40) || !isStr(q.addedBy, 64)) return null
if (seen.has(q.pubkeyB64)) return null
seen.add(q.pubkeyB64)
peers.push({ pubkeyB64: q.pubkeyB64, label: q.label, role: q.role as TeamRole, addedAt: q.addedAt, addedBy: q.addedBy })
}
- if (!o.sharedProjects.every((s) => isStr(s, 128))) return null
+ if (!o.sharedProjects.every((s) => isStr(s, TEAM_PROJECT_ID_MAX))) return null
return { v: 1, peers, sharedProjects: [...new Set(o.sharedProjects as string[])] }
}
@@ -51,7 +54,7 @@ export function peerFor(doc: TeamDoc, pubkeyB64: string): TeamPeer | undefined {
}
export function upsertPeer(doc: TeamDoc, p: TeamPeer): TeamDoc {
- const label = p.label.slice(0, LABEL_MAX)
+ const label = p.label.slice(0, TEAM_LABEL_MAX)
return { ...doc, peers: [...doc.peers.filter((x) => x.pubkeyB64 !== p.pubkeyB64), { ...p, label }] }
}
diff --git a/src/server/config.test.ts b/src/server/config.test.ts
index a0208aadc..c7a844725 100644
--- a/src/server/config.test.ts
+++ b/src/server/config.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import os from 'os'
import path from 'path'
-import { resolveConfig } from './config'
+import { resolveConfig, resolveDataDir } from './config'
describe('resolveConfig', () => {
it('has safe defaults', () => {
@@ -84,3 +84,25 @@ describe('resolveConfig', () => {
)
})
})
+
+describe('resolveDataDir (the team admin CLI\'s data dir)', () => {
+ it('matches resolveConfig: argv > env > default, empty env = unset', () => {
+ expect(resolveDataDir({}, [])).toBe(path.join(os.homedir(), '.nodeterm-server'))
+ expect(resolveDataDir({ NODETERM_DATA_DIR: '' }, [])).toBe(path.join(os.homedir(), '.nodeterm-server'))
+ expect(resolveDataDir({ NODETERM_DATA_DIR: '/data' }, [])).toBe('/data')
+ expect(resolveDataDir({ NODETERM_DATA_DIR: '/data' }, ['--data-dir', '/cli'])).toBe('/cli')
+ for (const [env, argv] of [
+ [{}, []],
+ [{ NODETERM_DATA_DIR: '/data' }, []],
+ [{ NODETERM_DATA_DIR: '/data' }, ['--data-dir', '/cli']]
+ ] as Array<[NodeJS.ProcessEnv, string[]]>) {
+ expect(resolveDataDir(env, argv)).toBe(resolveConfig(env, argv).dataDir)
+ }
+ })
+
+ it('does not trip the serving-only refusals resolveConfig applies', () => {
+ const env = { NODETERM_HOST: '0.0.0.0', NODETERM_DATA_DIR: '/data' }
+ expect(() => resolveConfig(env, [])).toThrow(/non-loopback/)
+ expect(resolveDataDir(env, [])).toBe('/data')
+ })
+})
diff --git a/src/server/config.ts b/src/server/config.ts
index aae60c34e..a15be734c 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -87,6 +87,20 @@ function isLoopback(host: string): boolean {
return host === '127.0.0.1' || host === 'localhost' || host === '::1'
}
+/**
+ * The server's data directory, exactly as `resolveConfig` resolves it (argv > env > default). Split
+ * out for the `team` admin CLI, which needs the data dir — where the admin socket lives — but none of
+ * the serving config, and must not trip `resolveConfig`'s serving-only refusals (a non-loopback
+ * NODETERM_HOST in the operator's shell, a trust-proxy half-configuration).
+ */
+export function resolveDataDir(env: NodeJS.ProcessEnv, argv: string[]): string {
+ const arg = parseArgv(argv)['data-dir']
+ if (typeof arg === 'string') return arg
+ const ev = env.NODETERM_DATA_DIR
+ if (ev !== undefined && ev !== '') return ev
+ return path.join(os.homedir(), '.nodeterm-server')
+}
+
/**
* 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
@@ -105,7 +119,7 @@ export function resolveConfig(env: NodeJS.ProcessEnv, argv: string[]): ServerCon
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 dataDir = resolveDataDir(env, argv)
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
diff --git a/src/server/hosted-boot-admin-disabled.test.ts b/src/server/hosted-boot-admin-disabled.test.ts
new file mode 100644
index 000000000..626ad236c
--- /dev/null
+++ b/src/server/hosted-boot-admin-disabled.test.ts
@@ -0,0 +1,42 @@
+// A data dir too long for a unix socket must not take the Server Edition down: the team admin socket
+// is disabled, and the log says why. Its own file because startServer memoizes some paths per
+// process (see hosted-boot.test.ts), so a second boot in one file writes into the first one's dir.
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { startServer } from './index'
+import { adminSocketPath } from '../core/relay/team-admin'
+
+const SHORT_BASE = fs.existsSync('/var/tmp') ? '/var/tmp' : os.tmpdir()
+
+// The limit is a unix-socket property; on Windows the admin socket is refused by name instead.
+describe.skipIf(process.platform === 'win32')('headless boot with a data dir too long for the admin socket', () => {
+ it('still boots, with administration disabled and said so in the log', async () => {
+ const base = fs.mkdtempSync(path.join(SHORT_BASE, 'nthl-'))
+ const dataDir = path.join(base, 'd'.repeat(Math.max(1, 110 - base.length)))
+ expect(Buffer.byteLength(adminSocketPath(dataDir))).toBeGreaterThan(107)
+ const errors: string[] = []
+ const orig = console.error
+ console.error = (...a: unknown[]) => {
+ errors.push(a.map(String).join(' '))
+ }
+ try {
+ const srv = await startServer({
+ port: 0,
+ host: '127.0.0.1',
+ dataDir,
+ rendererDir: path.join(dataDir, 'no-renderer'),
+ insecureHttp: false,
+ headless: true,
+ // Never touch the developer's real agent configs (see ServerConfig.installHooks).
+ installHooks: false
+ })
+ await srv.close()
+ expect(errors.join('\n')).toMatch(/team admin socket disabled[\s\S]*shorter data directory/)
+ } finally {
+ console.error = orig
+ fs.rmSync(base, { recursive: true, force: true })
+ }
+ }, 30_000)
+})
diff --git a/src/server/hosted-boot.test.ts b/src/server/hosted-boot.test.ts
new file mode 100644
index 000000000..b187d8649
--- /dev/null
+++ b/src/server/hosted-boot.test.ts
@@ -0,0 +1,122 @@
+// Hosted team boot wiring. Two halves:
+// - source-level pins (the pattern hook-verified-parity.test.ts uses): the hosted service boots
+// BEFORE the headless return, stops in BOTH close paths, and relay peers share ONE teardown in
+// ws.ts's order. A missing line here compiles and passes every other test while a headless host
+// silently never hosts, or leaks a relay peer's pty subscription on shutdown;
+// - a real headless boot with NO team: nothing about the Server Edition changes — hosting stays
+// off and writes nothing, and the admin socket answers only init / status / info.
+// ONE startServer per test file: some core paths are memoized per process (contextLinkDir, the hook
+// endpoint file), so a second boot in the same file writes into the first boot's data dir after
+// that test removed it. The admin-disabled boot lives in hosted-boot-admin-disabled.test.ts.
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { startServer } from './index'
+import { adminSocketPath, callTeamAdmin } from '../core/relay/team-admin'
+import { genKeyPair, publicKeyToB64 } from '../core/relay/e2ee'
+
+const src = fs.readFileSync(path.join(__dirname, 'index.ts'), 'utf8').replace(/\r\n/g, '\n')
+const headlessAt = src.indexOf('if (config.headless) {')
+
+describe('hosted team boot wiring (source)', () => {
+ it('starts before the headless early return', () => {
+ expect(headlessAt).toBeGreaterThan(0)
+ for (const needle of ['createHostedService(', 'hosted.start()', 'startTeamAdmin(']) {
+ expect(src.indexOf(needle), needle).toBeGreaterThan(0)
+ expect(src.indexOf(needle), needle).toBeLessThan(headlessAt)
+ }
+ })
+
+ it('boots after the workspace index is loaded (the access policy reads it)', () => {
+ expect(src.indexOf('await workspaceStore.load(')).toBeGreaterThan(0)
+ expect(src.indexOf('await workspaceStore.load(')).toBeLessThan(src.indexOf('createHostedService('))
+ })
+
+ it('stops in both close paths', () => {
+ expect(src.match(/hosted\.stop\(\)/g)?.length).toBe(2)
+ expect(src.match(/teamAdmin\.close\(\)/g)?.length).toBe(2)
+ // Before the pty layer is torn down: a relay peer's teardown hands its pty subscription back.
+ const closes = [...src.matchAll(/async close\(\) \{/g)].map((m) => m.index ?? -1)
+ expect(closes.length).toBe(2)
+ for (const at of closes) {
+ const body = src.slice(at, src.indexOf('await ptyManager.killAll()', at))
+ expect(body).toContain('hosted.stop()')
+ expect(body).toContain('await teamAdmin.close()')
+ }
+ })
+
+ it('relay peers share one teardown, in the order ws.ts uses', () => {
+ const at = src.indexOf('const teardownClient = ')
+ expect(at).toBeGreaterThan(0)
+ const body = src.slice(at, src.indexOf('\n }\n', at))
+ const leave = body.indexOf('presenceHub.leave(')
+ const drop = body.indexOf('dropUiClient(')
+ const detach = body.indexOf('platform.detach(')
+ expect(leave).toBeGreaterThan(0)
+ expect(drop).toBeGreaterThan(leave)
+ expect(detach).toBeGreaterThan(drop)
+ // The same per-client drops a closed browser tab gets, not a second list that can drift.
+ expect(src).toMatch(/onClientGone: dropUiClient/)
+ const dropAt = src.indexOf('const dropUiClient = ')
+ const dropBody = src.slice(dropAt, src.indexOf('\n }\n', dropAt))
+ expect(dropBody).toContain('ptyManager.dropClient(')
+ expect(dropBody).toContain('github.service.dropClient(')
+ })
+
+ it('a dead relay-peer sink is torn down in headless mode too', () => {
+ const at = src.indexOf('platform.setSinkGoneHandler(teardownClient)')
+ expect(at).toBeGreaterThan(0)
+ expect(at).toBeLessThan(headlessAt)
+ })
+
+ it('relay peers join presence as desktop peers, after the sink is registered', () => {
+ const at = src.indexOf('createHostedService(')
+ const block = src.slice(at, src.indexOf('})', src.indexOf('attach(sink)', at)))
+ expect(block.indexOf('platform.attach(sink)')).toBeGreaterThan(0)
+ expect(block.indexOf("presenceHub.join(id, 'desktop')")).toBeGreaterThan(block.indexOf('platform.attach(sink)'))
+ })
+})
+
+// A unix socket path is ~107 bytes at most: boot under a SHORT base so the admin socket fits.
+const SHORT_BASE = fs.existsSync('/var/tmp') ? '/var/tmp' : os.tmpdir()
+const bootConfig = (dataDir: string) => ({
+ port: 0,
+ host: '127.0.0.1',
+ dataDir,
+ rendererDir: path.join(dataDir, 'no-renderer'),
+ insecureHttp: false,
+ headless: true,
+ // Never touch the developer's real agent configs (see ServerConfig.installHooks).
+ installHooks: false
+})
+
+// The admin channel is a unix socket, and the mode check is POSIX permission bits.
+describe.skipIf(process.platform === 'win32')('headless boot with no team (unix socket, POSIX only)', () => {
+ it('hosting stays off and writes nothing; the admin socket serves only init, status and info', async () => {
+ const dataDir = fs.mkdtempSync(path.join(SHORT_BASE, 'nthb-'))
+ try {
+ const srv = await startServer(bootConfig(dataDir))
+ try {
+ const sock = adminSocketPath(dataDir)
+ expect((fs.statSync(sock).mode & 0o777).toString(8)).toBe('600')
+ const status = await callTeamAdmin(dataDir, { cmd: 'status' })
+ expect(status).toEqual({ ok: true, result: expect.objectContaining({ enabled: false, off: { reason: 'no-team' } }) })
+ expect(await callTeamAdmin(dataDir, { cmd: 'info' })).toEqual({ ok: true, result: { enabled: false, info: null, joinCode: null } })
+ const key = publicKeyToB64(genKeyPair().publicKey)
+ expect(await callTeamAdmin(dataDir, { cmd: 'add-owner', pubkey: key, label: 'E' })).toEqual({
+ ok: false,
+ error: expect.stringMatching(/team init/)
+ })
+ // Nothing but the admin socket was created under relay/: no team, no key, no device id.
+ expect(fs.readdirSync(path.join(dataDir, 'relay'))).toEqual(['admin.sock'])
+ expect(fs.existsSync(path.join(dataDir, 'device-id'))).toBe(false)
+ } finally {
+ await srv.close()
+ }
+ expect(fs.existsSync(adminSocketPath(dataDir))).toBe(false)
+ } finally {
+ fs.rmSync(dataDir, { recursive: true, force: true })
+ }
+ }, 30_000)
+})
diff --git a/src/server/index.ts b/src/server/index.ts
index 7c527bc72..1a16eebb2 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -105,10 +105,16 @@ import { WhisperModelStore } from '../core/speech/whisper-models'
import { SpeechService } from '../core/speech/speech-service'
import { registerSpeechIpc } from '../core/speech/register-ipc'
import { isPremium, getStoredEntitlement } from '../core/license'
+import { getDeviceId } from '../core/device-id'
+import { createHostedService } from '../core/relay/hosted-service'
+import { startTeamAdmin } from '../core/relay/team-admin'
// Same env-override + default as src/core/check.ts / license.ts / src/main/telemetry.ts — each
// shell derives it locally rather than sharing an import (src/server must not import src/main).
const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'
+// The hosted team relay's wss endpoint. Same env override + default as the desktop's RELAY_URL
+// (src/main/remote/host-service.ts), derived locally for the same reason as API_BASE.
+const RELAY_URL = process.env.NODETERM_RELAY_URL || 'wss://relay.nodeterm.dev'
/**
* App version fed to ServerPlatform (surfaced to the renderer as the desktop app's
@@ -806,6 +812,74 @@ export async function startServer(
}
})
+ // Hosted team relay (docs/hosted-team-relay.md): this server as the relay host of a team. OFF
+ // unless `team init` created <dataDir>/relay/team.json — with no team, start() answers 'no-team'
+ // and nothing is opened or written. Booted HERE: after every handler above is registered (a relay
+ // peer's requests dispatch through them) and after the workspace index is loaded (the access
+ // policy reads it to place a node in a project), and BEFORE the headless return, because a
+ // headless host is exactly where a team is hosted.
+ //
+ // The per-client drops a disconnected client is owed, shared with ws.ts's closed-tab path below so
+ // the two lists cannot drift: its pty subscriptions (a leaked one can strand a session it paused)
+ // and its GitHub issue subscriptions.
+ const dropUiClient = (uiId: number): void => {
+ ptyManager.dropClient(uiId)
+ github.service.dropClient(uiId)
+ }
+ // The ONE teardown for a relay peer, in the order ws.ts uses for a browser: leave presence, hand
+ // back the per-client state, then detach the sink. Idempotent, like ws.ts's.
+ const teardownClient = (uiId: number): void => {
+ presenceHub.leave(uiId)
+ dropUiClient(uiId)
+ platform.detach(uiId)
+ }
+ // A relay peer whose sink proves dead (consecutive throwing sends) is torn down the same way. In
+ // serving mode ws.ts replaces this with its own, equivalent teardown; in headless mode nothing else
+ // would ever set it, and a dead peer would stay in presence and keep its pty subscriptions.
+ platform.setSinkGoneHandler(teardownClient)
+ let hostedDeviceId: string | undefined
+ const hosted = createHostedService({
+ dataDir: config.dataDir,
+ apiBase: API_BASE,
+ relayUrl: RELAY_URL,
+ // Read on first use (a mint, `team info`), never at boot: getDeviceId CREATES <dataDir>/device-id
+ // when absent, and a server with no team must not change on disk.
+ get deviceId(): string {
+ return (hostedDeviceId ??= getDeviceId())
+ },
+ hostLabel: os.hostname(),
+ attach: {
+ attach(sink) {
+ const id = platform.attach(sink)
+ // Join AFTER registering the sink, so the hub's `presence:sync` lands on a live sink (the
+ // order ws.ts uses). A relay peer is a 'desktop' peer, as on the desktop's own relay host.
+ presenceHub.join(id, 'desktop')
+ return id
+ },
+ detach: teardownClient,
+ dispatch: (id, req) => platform.dispatch(id, req),
+ cast: (id, method, args) => platform.cast(id, method, args)
+ },
+ projectOfNode: (nodeId) =>
+ workspaceStore.persistedCanvases().find((c) => c.nodes.some((n) => n.id === nodeId))?.id,
+ projectCwd: (projectId) => workspaceStore.localCwdForProject(projectId)
+ })
+ const hostedStart = await hosted.start().catch((err: unknown) => {
+ console.error('[hosted-team] start failed:', err)
+ return null
+ })
+ if (hostedStart === 'started') console.log('Hosted team relay: ON (see `team status`).')
+ else if (hostedStart === 'host-key-unreadable') {
+ console.error('Hosted team relay: OFF — the host key could not be read (see above; `team status`).')
+ }
+ // The local admin channel for the `team` CLI. Never fatal: a data dir too long for a unix socket,
+ // or a second server on the same data dir, disables administration — it must not take the rest of
+ // the Server Edition down with it.
+ const teamAdmin = await startTeamAdmin(config.dataDir, hosted).catch((err: unknown) => {
+ console.error(`[hosted-team] team admin socket disabled: ${err instanceof Error ? err.message : String(err)}`)
+ return { close: async (): Promise<void> => {} }
+ })
+
// Headless notification host: every core service above (incl. the loopback hook server, which
// is its own listener and MUST run) is booted, but we bind NO public HTTP/WS listener — no
// renderer serving, no auth surface, no open port. The granted push senders reach the phone over
@@ -818,6 +892,10 @@ export async function startServer(
// Kill any in-flight setup/archive run: it is a detached process group, so nothing else in
// this teardown reaches it. Same call, same reason, in the serving branch's close() below.
projectSetupService.disposeAll()
+ // Stop taking admin commands, then end hosting: every relay peer is torn down (presence,
+ // pty subscriptions) while the pty layer is still up. Same two lines in the serving close().
+ await teamAdmin.close()
+ hosted.stop()
// Detach PTY clients — tmux sessions keep running (Phase 1 contract).
sessionReaper.stop()
pressure.stop()
@@ -851,10 +929,7 @@ export async function startServer(
const wsServer = attachWsServer(server, {
platform,
auth,
- onClientGone: (uiId) => {
- ptyManager.dropClient(uiId)
- github.service.dropClient(uiId)
- },
+ onClientGone: dropUiClient,
trustProxy: config.trustProxy
})
@@ -875,6 +950,10 @@ export async function startServer(
// Kill any in-flight setup/archive run first: it is a detached process group (setsid), so
// neither the WS teardown nor ptyManager.killAll() below would ever reach it.
projectSetupService.disposeAll()
+ // Stop taking admin commands, then end hosting while the pty layer is still up (see the
+ // headless close() above).
+ await teamAdmin.close()
+ hosted.stop()
// Detach PTY clients — tmux sessions keep running (Phase 1 contract; never kill the server).
sessionReaper.stop()
pressure.stop()
diff --git a/src/server/main.ts b/src/server/main.ts
index 90bacd984..55d21cd12 100644
--- a/src/server/main.ts
+++ b/src/server/main.ts
@@ -1,5 +1,6 @@
-import { resolveConfig } from './config'
+import { resolveConfig, resolveDataDir } from './config'
import { startServer } from './index'
+import { runTeamCli } from './team-cli'
/**
* Script entry point for the headless server. Kept separate from index.ts so that
@@ -11,7 +12,19 @@ process.on('uncaughtException', (e) => console.error('[nodeterm-server] uncaught
process.on('unhandledRejection', (e) => console.error('[nodeterm-server] unhandledRejection', e))
async function main(): Promise<void> {
- const config = resolveConfig(process.env, process.argv.slice(2))
+ const argv = process.argv.slice(2)
+ if (argv[0] === 'team') {
+ // `main.cjs team <command>`: the hosted team's admin CLI, not a server boot. It talks to the
+ // RUNNING server over <dataDir>/relay/admin.sock, so it needs the data dir and nothing else —
+ // `resolveDataDir`, not `resolveConfig`, whose serving-only refusals do not apply here.
+ // `--data-dir` on the team command line overrides it (runTeamCli reads that itself).
+ const code = await runTeamCli(argv.slice(1), resolveDataDir(process.env, []), (s) => console.log(s), (s) => console.error(s))
+ // Let buffered output reach a pipe before exiting (stdout to a pipe is asynchronous on macOS).
+ await new Promise<void>((resolve) => process.stdout.write('', () => resolve()))
+ await new Promise<void>((resolve) => process.stderr.write('', () => resolve()))
+ process.exit(code)
+ }
+ const config = resolveConfig(process.env, argv)
const { port, close } = await startServer(config)
// Headless binds no listener, so there is nothing to announce as "listening" (startServer already
// logged the headless line). Only print the address in normal serving mode.
diff --git a/src/server/team-cli.test.ts b/src/server/team-cli.test.ts
new file mode 100644
index 000000000..fc669aaf3
--- /dev/null
+++ b/src/server/team-cli.test.ts
@@ -0,0 +1,301 @@
+import { describe, it, expect, afterEach } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { parseTeamArgv, runTeamCli, describeStatus } from './team-cli'
+import { startTeamAdmin, adminSocketPath, type AdminStatusResult } from '../core/relay/team-admin'
+import { genKeyPair, publicKeyToB64 } from '../core/relay/e2ee'
+import type { HostedService, HostedStatus } from '../core/relay/hosted-service'
+
+const KEY = publicKeyToB64(genKeyPair().publicKey)
+
+describe('team argv', () => {
+ it('parses every command', () => {
+ expect(parseTeamArgv(['init'])).toEqual({ cmd: 'init' })
+ expect(parseTeamArgv(['add-owner', KEY, '--label', 'Enes'])).toEqual({ cmd: 'add-owner', pubkey: KEY, label: 'Enes' })
+ expect(parseTeamArgv(['add-owner', KEY, '--label=Enes K'])).toEqual({ cmd: 'add-owner', pubkey: KEY, label: 'Enes K' })
+ expect(parseTeamArgv(['add-owner', KEY])).toEqual({ cmd: 'add-owner', pubkey: KEY, label: '' })
+ expect(parseTeamArgv(['remove', 'K', '--force'])).toEqual({ cmd: 'remove', pubkey: 'K', force: true })
+ expect(parseTeamArgv(['remove', 'K'])).toEqual({ cmd: 'remove', pubkey: 'K' })
+ expect(parseTeamArgv(['share', 'P'])).toEqual({ cmd: 'share', projectId: 'P', on: true })
+ expect(parseTeamArgv(['unshare', 'P'])).toEqual({ cmd: 'share', projectId: 'P', on: false })
+ expect(parseTeamArgv(['info', '--json'])).toEqual({ cmd: 'info' })
+ expect(parseTeamArgv(['status'])).toEqual({ cmd: 'status' })
+ expect(parseTeamArgv(['status', '--json'])).toEqual({ cmd: 'status' })
+ expect(parseTeamArgv(['rotate-key'])).toEqual({ cmd: 'rotate-key' })
+ })
+
+ it('refuses junk with a usage line', () => {
+ expect(parseTeamArgv([])).toEqual({ error: expect.stringMatching(/usage/i) })
+ expect(parseTeamArgv(['add-owner'])).toEqual({ error: expect.stringMatching(/usage/i) })
+ expect(parseTeamArgv(['nuke'])).toEqual({ error: expect.stringMatching(/unknown command "nuke"[\s\S]*usage/i) })
+ expect(parseTeamArgv(['init', 'extra'])).toEqual({ error: expect.stringMatching(/usage/i) })
+ expect(parseTeamArgv(['remove', 'K', '--forse'])).toEqual({ error: expect.stringMatching(/unknown option --forse[\s\S]*usage/i) })
+ expect(parseTeamArgv(['add-owner', KEY, '--label'])).toEqual({ error: expect.stringMatching(/--label needs a value/) })
+ expect(parseTeamArgv(['add-owner', KEY, '--label', '--json'])).toEqual({ error: expect.stringMatching(/--label needs a value/) })
+ expect(parseTeamArgv(['share'])).toEqual({ error: expect.stringMatching(/usage/i) })
+ expect(parseTeamArgv(['rotate-key', '--json'])).toEqual({ error: expect.stringMatching(/unknown option --json/) })
+ expect(parseTeamArgv(['remove', 'K', '--force=yes'])).toEqual({ error: expect.stringMatching(/--force takes no value/) })
+ })
+
+ it('add-owner names what is wrong with a bad key or label (not the generic usage line)', () => {
+ const bad = parseTeamArgv(['add-owner', 'K', '--label', 'Enes'])
+ expect(bad).toEqual({ error: expect.stringMatching(/32 bytes/) })
+ expect((bad as { error: string }).error).not.toMatch(/usage/i)
+ expect(parseTeamArgv(['add-owner', KEY.replace(/=$/, '')])).toEqual({ error: expect.stringMatching(/canonical/) })
+ expect(parseTeamArgv(['add-owner', KEY, '--label', 'x'.repeat(61)])).toEqual({ error: expect.stringMatching(/60/) })
+ expect(parseTeamArgv(['add-owner', KEY, '--label', 'a\u001bb'])).toEqual({ error: expect.stringMatching(/control/) })
+ })
+
+ it('share names a bad project id', () => {
+ expect(parseTeamArgv(['share', 'x'.repeat(129)])).toEqual({ error: expect.stringMatching(/128/) })
+ })
+})
+
+const idleStatus = (patch: Partial<NonNullable<HostedStatus['scheduler']>> = {}, rest: Partial<AdminStatusResult> = {}): AdminStatusResult => ({
+ enabled: true,
+ scheduler: { state: 'running', lastError: null, mintsLastHour: 3, idle: 1, bridged: 0, ...patch },
+ peers: [],
+ pending: [],
+ off: null,
+ ...rest
+})
+
+describe('describeStatus', () => {
+ it('an idle listener is healthy', () => {
+ const text = describeStatus(idleStatus()).join('\n')
+ expect(text).toMatch(/Hosting: ON — listening/)
+ expect(text).not.toMatch(/not reachable|unhealthy/i)
+ })
+
+ it('a non-null lastError beside an idle listener is history, not an outage', () => {
+ const text = describeStatus(idleStatus({ lastError: 'network' })).join('\n')
+ expect(text).toMatch(/Hosting: ON — listening/)
+ expect(text).toMatch(/network/)
+ expect(text).not.toMatch(/not reachable|unhealthy|failing/i)
+ })
+
+ it('no idle listener and a lastError is a relay that cannot be reached yet', () => {
+ const text = describeStatus(idleStatus({ idle: 0, lastError: 'network' })).join('\n')
+ expect(text).toMatch(/not reachable yet/)
+ expect(text).toMatch(/network/)
+ })
+
+ it('no idle listener and no error is a listener being opened', () => {
+ expect(describeStatus(idleStatus({ idle: 0 })).join('\n')).toMatch(/opening a listener/)
+ expect(describeStatus(idleStatus({ idle: 0, bridged: 2 })).join('\n')).toMatch(/2 sessions \(joined or awaiting approval\)/)
+ })
+
+ it('a refusing backend is named, with its error', () => {
+ const text = describeStatus(idleStatus({ state: 'backend-refused', idle: 0, lastError: 'refused (403)' })).join('\n')
+ expect(text).toMatch(/refused/)
+ expect(text).toMatch(/403/)
+ expect(text).toMatch(/restart/)
+ })
+
+ it('off states say why, and still list the members', () => {
+ const peers = [{ label: 'Enes', role: 'owner' as const, connected: false }, { label: '', role: 'viewer' as const, connected: false }]
+ const unreadable = describeStatus({
+ enabled: false,
+ scheduler: null,
+ peers,
+ pending: [],
+ off: { reason: 'host-key-unreadable', detail: 'The team host key could not be read (malformed).' }
+ }).join('\n')
+ expect(unreadable).toMatch(/Hosting: OFF/)
+ expect(unreadable).toMatch(/could not be read \(malformed\)/)
+ expect(unreadable).toMatch(/owner\s+Enes/)
+ expect(unreadable).toMatch(/viewer\s+\(no label\)/)
+ expect(describeStatus({ enabled: false, scheduler: null, peers: [], pending: [], off: { reason: 'no-team' } }).join('\n')).toMatch(
+ /team init/
+ )
+ expect(describeStatus({ enabled: false, scheduler: null, peers: [], pending: [], off: { reason: 'stopped' } }).join('\n')).toMatch(
+ /team init.*restart/
+ )
+ })
+
+ it('pending join requests are listed by their SAS', () => {
+ const text = describeStatus(idleStatus({}, { pending: [{ pendingId: 'x', sas: '123 456', peerKeyB64: 'k', since: 0 }] })).join('\n')
+ expect(text).toMatch(/1 join request/)
+ expect(text).toMatch(/123 456/)
+ })
+
+ it('tolerates a reply shape it does not know (an older or newer server)', () => {
+ expect(() => describeStatus({} as never)).not.toThrow()
+ expect(describeStatus({ enabled: false, off: { reason: 'constructor' } } as never).join('\n')).toMatch(/Hosting: OFF — hosting is not running\./)
+ })
+
+ it('never prints control characters from a label', () => {
+ const text = describeStatus({
+ enabled: false,
+ scheduler: null,
+ peers: [{ label: 'evil\u001b]0;pwned\u0007', role: 'owner', connected: false }],
+ pending: [],
+ off: { reason: 'stopped' }
+ }).join('\n')
+ expect(text).not.toMatch(/\u001b|\u0007/)
+ expect(text).toContain('evil?]0;pwned?')
+ })
+})
+
+// Exercising runTeamCli end to end needs the admin unix socket: POSIX only.
+const SHORT_BASE = fs.existsSync('/var/tmp') ? '/var/tmp' : os.tmpdir()
+const made: string[] = []
+const closers: Array<() => Promise<void>> = []
+afterEach(async () => {
+ for (const c of closers.splice(0)) await c()
+ for (const d of made.splice(0)) fs.rmSync(d, { recursive: true, force: true })
+})
+const tmp = (): string => {
+ const d = fs.mkdtempSync(path.join(SHORT_BASE, 'ntc-'))
+ made.push(d)
+ return d
+}
+const INFO = { relayEndpoint: 'wss://relay.example', hostId: 'HOSTID', hostPublicKeyB64: 'HPK', hostDeviceId: 'DEV', label: 'box' }
+
+function fake(o: { running?: boolean; rotate?: string } = {}): { svc: HostedService; calls: string[] } {
+ const calls: string[] = []
+ let running = o.running ?? false
+ const svc = {
+ init: async () => ({ created: true }),
+ start: async () => {
+ running = true
+ return 'started'
+ },
+ stop: () => {},
+ addOwner: async (k: string, l: string) => {
+ calls.push(`owner:${k}:${l}`)
+ },
+ remove: async () => 'removed',
+ share: async (p: string, on: boolean) => {
+ calls.push(`share:${p}:${on}`)
+ },
+ info: () => (running ? INFO : null),
+ joinCode: () => (running ? 'nodeterm://join/CODE' : null),
+ status: (): HostedStatus =>
+ running
+ ? { enabled: true, scheduler: { state: 'running', lastError: null, mintsLastHour: 1, idle: 1, bridged: 0 }, peers: [], pending: [] }
+ : { enabled: false, scheduler: null, peers: [], pending: [] },
+ rotateKey: async () => o.rotate ?? (running ? 'started' : 'not-running')
+ } as unknown as HostedService
+ return { svc, calls }
+}
+
+async function served(o: Parameters<typeof fake>[0] = {}, withTeam = true): Promise<{ dataDir: string; calls: string[] }> {
+ const dataDir = tmp()
+ if (withTeam) {
+ fs.mkdirSync(path.join(dataDir, 'relay'), { recursive: true, mode: 0o700 })
+ fs.writeFileSync(path.join(dataDir, 'relay', 'team.json'), JSON.stringify({ v: 1, peers: [], sharedProjects: [] }))
+ }
+ const f = fake(o)
+ const admin = await startTeamAdmin(dataDir, f.svc)
+ closers.push(() => admin.close())
+ return { dataDir, calls: f.calls }
+}
+
+async function run(argv: string[], dataDir: string): Promise<{ code: number; out: string; err: string }> {
+ const out: string[] = []
+ const err: string[] = []
+ const code = await runTeamCli(argv, dataDir, (s) => out.push(s), (s) => err.push(s))
+ return { code, out: out.join('\n'), err: err.join('\n') }
+}
+
+describe.skipIf(process.platform === 'win32')('runTeamCli over the admin socket (unix socket, POSIX only)', () => {
+ it('init prints the join code and the address when hosting runs', async () => {
+ const { dataDir } = await served({}, false)
+ const r = await run(['init'], dataDir)
+ expect(r.code).toBe(0)
+ expect(r.out).toMatch(/Created/)
+ expect(r.out).toMatch(/Hosting: ON/)
+ expect(r.out).toContain('nodeterm://join/CODE')
+ expect(r.out).toContain('HOSTID')
+ })
+
+ it('rotate-key while hosting is off says so, in exactly these words', async () => {
+ const { dataDir } = await served({ running: false })
+ const r = await run(['rotate-key'], dataDir)
+ expect(r.code).toBe(0)
+ expect(r.out).toBe('Host key rotated. Hosting is off; run `team init` (or restart the service) to start it.')
+ })
+
+ it('rotate-key while hosting was on warns that every teammate needs a new join code', async () => {
+ const { dataDir } = await served({ running: true })
+ const r = await run(['rotate-key'], dataDir)
+ expect(r.code).toBe(0)
+ expect(r.out).toMatch(/Every teammate needs a NEW join code/)
+ expect(r.out).toContain('nodeterm://join/CODE')
+ })
+
+ it('rotate-key that could not restart hosting exits non-zero and says so', async () => {
+ const { dataDir } = await served({ running: true, rotate: 'stopped' })
+ const r = await run(['rotate-key'], dataDir)
+ expect(r.code).toBe(1)
+ expect(r.out + r.err).toMatch(/did not restart/)
+ })
+
+ it('a bad add-owner key never reaches the socket (works with no server at all)', async () => {
+ const dataDir = tmp() // nothing listening here
+ const r = await run(['add-owner', 'not-a-key', '--label', 'E'], dataDir)
+ expect(r.code).toBe(2)
+ expect(r.err).toMatch(/32 bytes/)
+ expect(r.err).not.toMatch(/not running/)
+ })
+
+ it('add-owner, share and unshare confirm what they did', async () => {
+ const { dataDir, calls } = await served({ running: true })
+ expect((await run(['add-owner', KEY, '--label', 'Enes'], dataDir)).out).toMatch(/Added Enes as an owner/)
+ expect((await run(['share', 'P1'], dataDir)).out).toMatch(/P1 is now shared/)
+ expect((await run(['unshare', 'P1'], dataDir)).out).toMatch(/P1 is no longer shared/)
+ expect(calls).toEqual([`owner:${KEY}:Enes`, 'share:P1:true', 'share:P1:false'])
+ })
+
+ it('info --json prints the machine-readable reply; info prints the address', async () => {
+ const { dataDir } = await served({ running: true })
+ const json = await run(['info', '--json'], dataDir)
+ expect(json.code).toBe(0)
+ expect(JSON.parse(json.out)).toEqual({ enabled: true, info: INFO, joinCode: 'nodeterm://join/CODE' })
+ const human = await run(['info'], dataDir)
+ expect(human.out).toContain('HOSTID')
+ expect(human.out).toContain('nodeterm://join/CODE')
+ })
+
+ it('info with hosting never started exits 1 with a pointer to init', async () => {
+ const { dataDir } = await served({ running: false })
+ const r = await run(['info'], dataDir)
+ expect(r.code).toBe(1)
+ expect(r.out + r.err).toMatch(/team init/)
+ })
+
+ it('status prints a human summary, --json the raw reply', async () => {
+ const { dataDir } = await served({ running: true })
+ expect((await run(['status'], dataDir)).out).toMatch(/Hosting: ON — listening/)
+ expect(JSON.parse((await run(['status', '--json'], dataDir)).out)).toMatchObject({ enabled: true, off: null })
+ })
+
+ it('a refusal from the server exits 1 with its reason', async () => {
+ const { dataDir } = await served({}, false)
+ const r = await run(['share', 'P'], dataDir)
+ expect(r.code).toBe(1)
+ expect(r.err).toMatch(/team init/)
+ })
+
+ it('--data-dir (anywhere on the line) overrides the default data dir', async () => {
+ const { dataDir } = await served({ running: true })
+ const wrong = tmp()
+ expect((await run(['status', '--data-dir', dataDir], wrong)).code).toBe(0)
+ expect((await run(['--data-dir=' + dataDir, 'status'], wrong)).code).toBe(0)
+ const miss = await run(['status'], wrong)
+ expect(miss.code).toBe(1)
+ expect(miss.err).toMatch(/not running/)
+ expect(miss.err).toContain(adminSocketPath(wrong))
+ expect(miss.err).toMatch(/--data-dir/)
+ })
+
+ it('usage errors exit 2; help exits 0', async () => {
+ const dataDir = tmp()
+ expect((await run([], dataDir)).code).toBe(2)
+ const help = await run(['--help'], dataDir)
+ expect(help.code).toBe(0)
+ expect(help.out).toMatch(/usage/i)
+ })
+})
diff --git a/src/server/team-cli.ts b/src/server/team-cli.ts
new file mode 100644
index 000000000..6909f9d29
--- /dev/null
+++ b/src/server/team-cli.ts
@@ -0,0 +1,327 @@
+// `node out/server/main.cjs team <command>` — the hosted team's admin CLI. It talks to the running
+// server over the local admin socket (src/core/relay/team-admin.ts) and never touches team.json or
+// the host key itself: the server is the only writer, which is what keeps two admin commands (or an
+// admin command and a live approval) from racing each other on disk.
+//
+// Exit codes: 0 done, 1 the server refused or could not be reached, 2 the command line is wrong.
+import path from 'node:path'
+import {
+ callTeamAdmin,
+ ownerKeyProblem,
+ ownerLabelProblem,
+ projectIdProblem,
+ type AdminInfoResult,
+ type AdminInitResult,
+ type AdminRequest,
+ type AdminRotateResult,
+ type AdminStatusResult
+} from '../core/relay/team-admin'
+
+const USAGE_ROWS: Array<[string, string]> = [
+ ['init', 'create the host key and the team, and start hosting'],
+ ['add-owner <device-key> [--label <name>]', 'make a device an owner (its 44-character public key)'],
+ ['remove <device-key> [--force]', 'remove a member and cut its live sessions'],
+ ['share <projectId>', 'show a project to non-editors'],
+ ['unshare <projectId>', 'stop showing it'],
+ ['info [--json]', "this host's team address and join code"],
+ ['status [--json]', 'hosting state, members and join requests'],
+ ['rotate-key', 'replace the host key (every teammate needs a new join code)']
+]
+const USAGE_WIDTH = Math.max(...USAGE_ROWS.map(([cmd]) => cmd.length))
+export const TEAM_USAGE = [
+ 'usage: team <command> [--data-dir <dir>]',
+ ...USAGE_ROWS.map(([cmd, what]) => ` ${cmd.padEnd(USAGE_WIDTH)} ${what}`)
+].join('\n')
+
+type FlagKind = 'bool' | 'value'
+interface CommandSpec {
+ positionals: number
+ flags: Record<string, FlagKind>
+}
+const COMMANDS: Record<string, CommandSpec> = {
+ init: { positionals: 0, flags: {} },
+ 'add-owner': { positionals: 1, flags: { label: 'value' } },
+ remove: { positionals: 1, flags: { force: 'bool' } },
+ share: { positionals: 1, flags: {} },
+ unshare: { positionals: 1, flags: {} },
+ info: { positionals: 0, flags: { json: 'bool' } },
+ status: { positionals: 0, flags: { json: 'bool' } },
+ 'rotate-key': { positionals: 0, flags: {} }
+}
+
+const usageError = (why: string): { error: string } => ({ error: `${why}\n${TEAM_USAGE}` })
+
+/**
+ * Parse one command line into an admin request. Strict: an unknown option or a stray argument is a
+ * usage error, not silently ignored — `remove K --forse` must not run as a remove without --force.
+ * A bad add-owner key or label, or a bad project id, gets its OWN message (not the usage text),
+ * before anything reaches the server. `--json` is presentation only and never part of the request.
+ */
+export function parseTeamArgv(argv: string[]): AdminRequest | { error: string } {
+ const [cmd, ...rest] = argv
+ if (cmd === undefined) return usageError('A command is required.')
+ const spec = Object.hasOwn(COMMANDS, cmd) ? COMMANDS[cmd] : undefined
+ if (!spec) return usageError(`unknown command "${cmd}"`)
+ const positionals: string[] = []
+ const flags: Record<string, string | true> = {}
+ for (let i = 0; i < rest.length; i++) {
+ const tok = rest[i]
+ if (!tok.startsWith('--')) {
+ positionals.push(tok)
+ continue
+ }
+ const eq = tok.indexOf('=')
+ const name = tok.slice(2, eq < 0 ? undefined : eq)
+ const kind = Object.hasOwn(spec.flags, name) ? spec.flags[name] : undefined
+ if (!kind) return usageError(`unknown option --${name} for "team ${cmd}"`)
+ if (kind === 'bool') {
+ if (eq >= 0) return usageError(`--${name} takes no value`)
+ flags[name] = true
+ continue
+ }
+ const value = eq >= 0 ? tok.slice(eq + 1) : rest[i + 1]
+ if (value === undefined || (eq < 0 && value.startsWith('--'))) return usageError(`--${name} needs a value`)
+ if (eq < 0) i++
+ flags[name] = value
+ }
+ if (positionals.length !== spec.positionals) {
+ return usageError(
+ spec.positionals === 0 ? `"team ${cmd}" takes no arguments` : `"team ${cmd}" takes exactly ${spec.positionals} argument`
+ )
+ }
+ switch (cmd) {
+ case 'init':
+ case 'info':
+ case 'status':
+ case 'rotate-key':
+ return { cmd }
+ case 'add-owner': {
+ const pubkey = positionals[0]
+ const label = typeof flags.label === 'string' ? flags.label : ''
+ const problem = ownerKeyProblem(pubkey) ?? ownerLabelProblem(label)
+ return problem ? { error: problem } : { cmd, pubkey, label }
+ }
+ case 'remove':
+ return flags.force ? { cmd, pubkey: positionals[0], force: true } : { cmd, pubkey: positionals[0] }
+ case 'share':
+ case 'unshare': {
+ const problem = projectIdProblem(positionals[0])
+ return problem ? { error: problem } : { cmd: 'share', projectId: positionals[0], on: cmd === 'share' }
+ }
+ }
+ return usageError(`unknown command "${cmd}"`)
+}
+
+/** Take a global `--data-dir <dir>` / `--data-dir=<dir>` off the command line, wherever it sits. */
+function takeDataDir(argv: string[]): { dataDir?: string; argv: string[] } | { error: string } {
+ const out: string[] = []
+ let dataDir: string | undefined
+ for (let i = 0; i < argv.length; i++) {
+ const tok = argv[i]
+ if (tok === '--data-dir' || tok.startsWith('--data-dir=')) {
+ const value = tok === '--data-dir' ? argv[++i] : tok.slice('--data-dir='.length)
+ if (!value || value.startsWith('--')) return usageError('--data-dir needs a value')
+ dataDir = path.resolve(value)
+ continue
+ }
+ out.push(tok)
+ }
+ return { dataDir, argv: out }
+}
+
+// ---- rendering. Every reader tolerates a shape it does not know: the CLI and the running server can
+// be different builds (an update not yet followed by a restart).
+
+const obj = (v: unknown): Record<string, unknown> =>
+ v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}
+// Control characters never reach the admin's terminal: a label in a hand-edited team.json could
+// otherwise carry escape sequences.
+const str = (v: unknown, fallback = ''): string => (typeof v === 'string' ? v.replace(/\p{Cc}/gu, '?') : fallback)
+const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
+const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`
+
+function addressLines(info: unknown, joinCode: unknown): string[] {
+ const i = obj(info)
+ const lines = [
+ ` Team host: ${str(i.label, '?')}`,
+ ` Host id: ${str(i.hostId, '?')}`,
+ ` Host key: ${str(i.hostPublicKeyB64, '?')}`,
+ ` Relay: ${str(i.relayEndpoint, '?')}`
+ ]
+ if (typeof joinCode === 'string') {
+ lines.push('Join code (give it to teammates; an owner approves each new device):', ` ${str(joinCode)}`)
+ }
+ return lines
+}
+
+const OFF_TEXT: Record<string, string> = {
+ 'no-team': 'there is no hosted team on this server. Run `team init` to create one.',
+ 'no-host-key': 'the team has no host key. Run `team init` to create one.',
+ stopped: 'hosting is not running. Run `team init` (or restart the service) to start it.'
+}
+
+/**
+ * The human `team status`. The scheduler's `lastError` is the last failure SINCE THE RELAY LEG WAS
+ * LAST PROVEN, not a current fault, so it is read together with `state` and the idle listener count:
+ * beside an open idle listener it is history the next confirmed registration clears, and only with
+ * NO idle listener does it mean teammates cannot connect yet.
+ */
+export function describeStatus(result: AdminStatusResult): string[] {
+ const s = obj(result)
+ const lines: string[] = []
+ const sched = obj(s.scheduler)
+ const lastError = typeof sched.lastError === 'string' ? sched.lastError : null
+ const idle = num(sched.idle)
+ const bridged = num(sched.bridged)
+ if (s.enabled !== true) {
+ const off = obj(s.off)
+ const reason = str(off.reason)
+ const text =
+ reason === 'host-key-unreadable'
+ ? str(off.detail, 'the host key could not be read.')
+ : Object.hasOwn(OFF_TEXT, reason)
+ ? OFF_TEXT[reason]
+ : 'hosting is not running.'
+ lines.push(`Hosting: OFF — ${text}`)
+ } else if (sched.state === 'backend-refused') {
+ lines.push(
+ `Hosting: STOPPED — the nodeterm API refused to issue relay tokens${lastError ? ` (${lastError})` : ''}. ` +
+ 'Hosting stays off until the service restarts.'
+ )
+ } else if (idle > 0) {
+ lines.push('Hosting: ON — listening for teammates.')
+ if (lastError) {
+ lines.push(` Earlier failure, not yet cleared by a confirmed relay registration: ${lastError}`)
+ }
+ } else if (lastError) {
+ lines.push(`Hosting: ON, but not reachable yet — retrying. Last error: ${lastError}`)
+ } else {
+ lines.push('Hosting: ON — opening a listener.')
+ }
+ if (s.enabled === true) {
+ lines.push(
+ ` ${plural(bridged, 'session')} (joined or awaiting approval) · ${plural(idle, 'idle listener')} · ` +
+ `${plural(num(sched.mintsLastHour), 'relay token')} minted in the last hour`
+ )
+ }
+ const peers = Array.isArray(s.peers) ? s.peers.map(obj) : []
+ if (peers.length === 0) {
+ lines.push('Members: none')
+ } else {
+ lines.push(`Members (${peers.length}):`)
+ const roleWidth = Math.max(...peers.map((p) => str(p.role, '?').length))
+ for (const p of peers) {
+ const label = str(p.label) || '(no label)'
+ lines.push(` ${str(p.role, '?').padEnd(roleWidth)} ${label}${p.connected === true ? ' — connected' : ''}`)
+ }
+ }
+ const pending = Array.isArray(s.pending) ? s.pending.map(obj) : []
+ if (pending.length > 0) {
+ lines.push(`${plural(pending.length, 'join request')} waiting for an owner (approve from an owner's desktop):`)
+ for (const p of pending) lines.push(` code ${str(p.sas, '?')}`)
+ }
+ return lines
+}
+
+/** Render a successful reply. The exit code is 1 when the command did its part but the outcome it
+ * exists for did not happen (hosting did not start, there is no address yet). Only `info` and
+ * `status` take `--json`. */
+function render(req: AdminRequest, result: unknown, json: boolean): { lines: string[]; code: number } {
+ switch (req.cmd) {
+ case 'init': {
+ const r = obj(result) as Partial<AdminInitResult>
+ const lines = [r.created ? 'Created the host key and the team.' : 'The host key already existed; the team is unchanged.']
+ if (r.start === 'started') {
+ lines.push('Hosting: ON.', ...addressLines(r.info, r.joinCode))
+ return { lines, code: 0 }
+ }
+ const why =
+ r.start === 'stopped'
+ ? 'the service is shutting down'
+ : r.start === 'host-key-unreadable'
+ ? 'the host key could not be read (see `team status`)'
+ : `start answered "${str(r.start, '?')}"`
+ lines.push(`Hosting did not start: ${why}.`)
+ return { lines, code: 1 }
+ }
+ case 'add-owner':
+ return { lines: [`Added ${req.label || req.pubkey} as an owner.`], code: 0 }
+ case 'remove':
+ return { lines: ['Removed. Their live sessions were closed.'], code: 0 }
+ case 'share':
+ return {
+ lines: [req.on ? `Project ${req.projectId} is now shared with the team.` : `Project ${req.projectId} is no longer shared.`],
+ code: 0
+ }
+ case 'info': {
+ const r = obj(result) as Partial<AdminInfoResult>
+ const has = r.info !== null && r.info !== undefined
+ if (json) return { lines: [JSON.stringify(result, null, 2)], code: has ? 0 : 1 }
+ if (!has) {
+ return {
+ lines: ['Hosting has not started on this server, so there is no team address yet. Run `team init` (see `team status` for why).'],
+ code: 1
+ }
+ }
+ const lines = r.enabled === true ? ['Hosting: ON.'] : ['Hosting: OFF — this address answers nobody until hosting starts.']
+ lines.push(...addressLines(r.info, r.enabled === true ? r.joinCode : null))
+ return { lines, code: 0 }
+ }
+ case 'status':
+ return { lines: json ? [JSON.stringify(result, null, 2)] : describeStatus(result as AdminStatusResult), code: 0 }
+ case 'rotate-key': {
+ const r = obj(result) as Partial<AdminRotateResult>
+ if (r.result === 'not-running') {
+ return { lines: ['Host key rotated. Hosting is off; run `team init` (or restart the service) to start it.'], code: 0 }
+ }
+ if (r.result === 'started') {
+ return {
+ lines: [
+ 'Host key rotated. Every teammate needs a NEW join code; old bookmarks will not connect.',
+ ...addressLines(r.info, r.joinCode)
+ ],
+ code: 0
+ }
+ }
+ return {
+ lines: [
+ `Host key rotated, but hosting did not restart (${str(r.result, '?')}). Every teammate needs a NEW join code; ` +
+ 'see `team status`.'
+ ],
+ code: 1
+ }
+ }
+ }
+}
+
+export async function runTeamCli(
+ argv: string[],
+ dataDir: string,
+ out: (s: string) => void,
+ err: (s: string) => void = out
+): Promise<number> {
+ if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h' || argv[0] === 'help')) {
+ out(TEAM_USAGE)
+ return 0
+ }
+ const dd = takeDataDir(argv)
+ if ('error' in dd) {
+ err(dd.error)
+ return 2
+ }
+ const req = parseTeamArgv(dd.argv)
+ if ('error' in req) {
+ err(req.error)
+ return 2
+ }
+ const r = await callTeamAdmin(dd.dataDir ?? dataDir, req)
+ if (!r.ok) {
+ err(r.error)
+ return 1
+ }
+ // The reply is printed to `out` even when the exit code is 1: the command ran, and what it found
+ // (hosting did not start, no address yet) is its answer, not a failure to run.
+ const { lines, code } = render(req, r.result, dd.argv.includes('--json'))
+ for (const line of lines) out(line)
+ return code
+}