Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(server): keep request-derived values out of object keys and the log
review31840d3f4768
diff --git a/src/server/auth.test.ts b/src/server/auth.test.tsindex efdc5a652..6e1404aaa 100644--- a/src/server/auth.test.ts+++ b/src/server/auth.test.ts@@ -93,6 +93,39 @@ describe('Auth', () => {expect(heard).toHaveLength(2)})+ it('a request-chosen token never indexes an object: odd keys are just "no such session"', () => {+ const a = new Auth(dir)+ const real = a.createSession()+ for (const key of ['__proto__', 'constructor', 'toString', 'hasOwnProperty', '', 'x'.repeat(64)]) {+ expect(a.validateSession(key)).toBe(false)+ expect(a.revokeSession(key)).toBe(false)+ }+ expect(a.validateSession(real)).toBe(true)+ // On disk it is still the { token: { createdAt } } object every older build wrote and reads.+ const onDisk = JSON.parse(fs.readFileSync(path.join(dir, 'sessions.json'), 'utf8'))+ expect(Object.keys(onDisk)).toEqual([real])+ expect(typeof onDisk[real].createdAt).toBe('number')+ })++ it('loading sessions.json keeps only well-formed tokens (an older file keeps working)', () => {+ const good = 'a'.repeat(64)+ fs.writeFileSync(+ path.join(dir, 'sessions.json'),+ `{"${good}":{"createdAt":${Date.now()}},"__proto__":{"createdAt":${Date.now()}},"short":{"createdAt":${Date.now()}},"${'b'.repeat(64)}":{"createdAt":"soon"}}`+ )+ const a = new Auth(dir)+ expect(a.validateSession(good)).toBe(true)+ expect(a.validateSession('__proto__')).toBe(false)+ expect(a.validateSession('short')).toBe(false)+ expect(a.validateSession('b'.repeat(64))).toBe(false)+ // The malformed entries are gone from the next write, not carried along.+ const fresh = a.createSession()+ const onDisk = JSON.parse(fs.readFileSync(path.join(dir, 'sessions.json'), 'utf8'))+ expect(Object.keys(onDisk).sort()).toEqual([good, fresh].sort())+ fs.writeFileSync(path.join(dir, 'sessions.json'), '[1,2]')+ expect(new Auth(dir).validateSession(good)).toBe(false)+ })+it('password rule: at least 8 characters, one definition for setup and the boot seed (S8)', () => {expect(passwordTooShort('1234567')).toBe(true)expect(passwordTooShort('12345678')).toBe(false)diff --git a/src/server/auth.ts b/src/server/auth.tsindex f216b7fb2..ae109bc55 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -111,7 +111,17 @@ interface SessionEntry {createdAt: number}-type SessionMap = { [token: string]: SessionEntry }+/** Sessions by token. A `Map`, never a plain object: the token arrives in a request cookie, and a+ * request-chosen key must not index (or `delete` from) an object's own properties. On disk it stays+ * the `{ token: { createdAt } }` object it always was. */+type SessionMap = Map<string, SessionEntry>++/** What `createSession` mints: 32 random bytes as hex. Anything else is not a token of ours. */+const SESSION_TOKEN_RE = /^[0-9a-f]{64}$/++function isSessionToken(token: string | undefined): token is string {+ return typeof token === 'string' && SESSION_TOKEN_RE.test(token)+}export class Auth {private authPath: string@@ -215,17 +225,27 @@ export class Auth {private loadSessions(): SessionMap {if (this.sessions === null) {+ const map: SessionMap = new Map()try {- this.sessions = JSON.parse(fs.readFileSync(this.sessionsPath, 'utf8')) as SessionMap+ const raw: unknown = JSON.parse(fs.readFileSync(this.sessionsPath, 'utf8'))+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {+ for (const [token, entry] of Object.entries(raw as Record<string, unknown>)) {+ const createdAt = (entry as { createdAt?: unknown } | null)?.createdAt+ if (isSessionToken(token) && typeof createdAt === 'number' && Number.isFinite(createdAt)) {+ map.set(token, { createdAt })+ }+ }+ }} catch {- this.sessions = {}+ /* missing or unreadable: no sessions */}+ this.sessions = map}return this.sessions}private persistSessions(): void {- fs.writeFileSync(this.sessionsPath, JSON.stringify(this.sessions ?? {}, null, 2), {+ fs.writeFileSync(this.sessionsPath, JSON.stringify(Object.fromEntries(this.sessions ?? new Map()), null, 2), {mode: 0o600})}@@ -233,31 +253,31 @@ export class Auth {createSession(): string {const sessions = this.loadSessions()const token = crypto.randomBytes(32).toString('hex')- sessions[token] = { createdAt: Date.now() }+ sessions.set(token, { createdAt: Date.now() })this.persistSessions()return token}validateSession(token: string | undefined): boolean {- if (!token) return false+ if (!isSessionToken(token)) return falseconst sessions = this.loadSessions()const now = Date.now()let changed = false- for (const [t, entry] of Object.entries(sessions)) {+ for (const [t, entry] of sessions) {if (now - entry.createdAt >= SESSION_TTL_MS) {- delete sessions[t]+ sessions.delete(t)changed = true}}if (changed) this.persistSessions()- return Object.prototype.hasOwnProperty.call(sessions, token)+ return sessions.has(token)}/** Sign out ONE session: the token the caller presented (S3). True when it existed. */revokeSession(token: string): boolean {+ if (!isSessionToken(token)) return falseconst sessions = this.loadSessions()- if (!Object.prototype.hasOwnProperty.call(sessions, token)) return false- delete sessions[token]+ if (!sessions.delete(token)) return falsethis.persistSessions()this.announceRevoke()return true@@ -265,7 +285,7 @@ export class Auth {/** Sign out everywhere: every session of every browser (S3). */revokeAll(): void {- this.sessions = {}+ this.sessions = new Map()this.persistSessions()this.announceRevoke()}diff --git a/src/server/http-auth.test.ts b/src/server/http-auth.test.tsindex d63724851..b234db0f3 100644--- a/src/server/http-auth.test.ts+++ b/src/server/http-auth.test.ts@@ -231,10 +231,13 @@ describe('S5: Secure and HSTS', () => {await request(port, 'GET', '/login', { host: '127.0.0.1:8443' })await request(port, 'GET', '/login', { host: '[::1]:8443' })expect(warn).not.toHaveBeenCalled()- await request(port, 'GET', '/login', { host: 'term.example.com' })- await request(port, 'GET', '/login', { host: 'term.example.com' })+ await request(port, 'GET', '/login', { host: 'attacker-chosen.invalid' })+ await request(port, 'GET', '/login', { host: 'attacker-chosen.invalid' })expect(warn).toHaveBeenCalledTimes(1)- expect(String(warn.mock.calls[0][0])).toMatch(/NODETERM_PUBLIC_ORIGIN=https:\/\/term\.example\.com/)+ const line = String(warn.mock.calls[0][0])+ expect(line).toMatch(/NODETERM_PUBLIC_ORIGIN/)+ // The Host header is the client's to write: none of it reaches the log (log injection).+ expect(line).not.toContain('attacker-chosen')// Configured: never warns.warn.mockClear()const port2 = await serve({ publicOrigin: 'https://term.example.com' })diff --git a/src/server/http.ts b/src/server/http.tsindex f7f2a6819..3a1d600e2 100644--- a/src/server/http.ts+++ b/src/server/http.ts@@ -129,10 +129,6 @@ function isLoopbackHost(host: string | undefined): boolean {return name === 'localhost' || name.endsWith('.localhost') || name === '::1' || /^127(\.\d{1,3}){3}$/.test(name)}-/** A `Host` value safe to print: hostname characters only, capped. */-function printableHost(host: string): string {- return host.replace(/[^A-Za-z0-9.:\-[\]]/g, '').slice(0, 100)-}function redirect(res: http.ServerResponse, status: number, location: string): void {res.writeHead(status, { Location: location })@@ -477,9 +473,9 @@ export function createHttpHandler(if (publicOrigin !== undefined) res.setHeader('Strict-Transport-Security', HSTS)else if (!warnedNoPublicOrigin && !isLoopbackHost(req.headers['host'])) {warnedNoPublicOrigin = true- const host = printableHost(req.headers['host'] ?? '')+ // A fixed sentence: the Host header is the client's to write, so none of it reaches the log.console.warn(- `[nodeterm-server] requests are arriving for "${host}" but NODETERM_PUBLIC_ORIGIN is not set: the session cookie is marked Secure only when your proxy sends X-Forwarded-Proto: https, and no HSTS header is sent. Set NODETERM_PUBLIC_ORIGIN=https://${host} (the address you open in the browser). See docs/SERVER.md.`+ `[nodeterm-server] requests are arriving for a non-loopback host name but NODETERM_PUBLIC_ORIGIN is not set: the session cookie is marked Secure only when your proxy sends X-Forwarded-Proto: https, and no HSTS header is sent. Set NODETERM_PUBLIC_ORIGIN to the https address you open in the browser (for example https://term.example.com). See docs/SERVER.md.`)}