Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(security): keep model ids out of the Windows shell (#320)

OKNOTOK2264514973d1
diff --git a/server/src/__tests__/computer-engine-defaults.test.ts b/server/src/__tests__/computer-engine-defaults.test.ts
index a6267bb..47f98f6 100644
--- a/server/src/__tests__/computer-engine-defaults.test.ts
+++ b/server/src/__tests__/computer-engine-defaults.test.ts
@@ -109,6 +109,14 @@ test('a missing or inaccessible computer closes the transaction without writing'
assert.deepEqual(state(), { stored: {}, releases: 1, commits: 1, rollbacks: 0 })
})
+test('a model id with shell metacharacters is rejected and not stored', async () => {
+ const state = database({ claude: { model: 'original' } })
+ await assert.rejects(save({ claude: { model: 'sonnet & calc.exe' } }), /invalid model id/)
+ assert.deepEqual(state(), {
+ stored: { claude: { model: 'original' } }, releases: 1, commits: 0, rollbacks: 1,
+ })
+})
+
test('a failed write rolls back and releases the connection', async () => {
const state = database({ claude: { model: 'original' } }, { failWrite: true })
await assert.rejects(save({ claude: { model: 'changed' } }), /write failed/)
diff --git a/server/src/__tests__/model-id.test.ts b/server/src/__tests__/model-id.test.ts
new file mode 100644
index 0000000..6b7af72
--- /dev/null
+++ b/server/src/__tests__/model-id.test.ts
@@ -0,0 +1,39 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { InvalidModelIdError, modelIdOrNull, parseModelId } from '../agents/computer/model-id.js'
+import { shellSafeSpawnPlan } from '../agents/computer/engine.js'
+import { resolveEngineFastModel, resolveEngineModel } from '../agents/computer/daemon.js'
+
+test('a model id is one token vendors actually use', () => {
+ assert.equal(parseModelId('claude-sonnet-4-5'), 'claude-sonnet-4-5')
+ assert.equal(parseModelId(' my-provider/some-model '), 'my-provider/some-model')
+ assert.equal(parseModelId('gpt-5.4-mini'), 'gpt-5.4-mini')
+ assert.equal(parseModelId(''), null)
+ assert.equal(parseModelId(' '), null)
+ assert.equal(parseModelId(null), null)
+ assert.equal(parseModelId(undefined), undefined)
+ assert.equal(parseModelId(1), undefined)
+})
+
+test('a model id cannot carry a shell metacharacter', () => {
+ for (const value of ['sonnet & calc.exe', 'sonnet|calc', 'sonnet;calc', 'a"b', 'a%PATH%', 'a b', '../x']) {
+ assert.throws(() => parseModelId(value), InvalidModelIdError)
+ assert.equal(modelIdOrNull(value), null)
+ }
+})
+
+test('resolveEngineModel drops an id that must not reach the shell', () => {
+ assert.equal(resolveEngineModel('sonnet & calc.exe', undefined), null)
+ assert.equal(resolveEngineModel('claude-opus-4-7', 'sonnet & calc.exe'), null)
+ assert.equal(resolveEngineFastModel('sonnet & calc.exe', undefined), null)
+ assert.equal(resolveEngineModel('claude-opus-4-7', 'my-provider/some-model'), 'my-provider/some-model')
+})
+
+test('a Windows shell spawn quotes the model instead of using shell:true', () => {
+ const plan = shellSafeSpawnPlan('C:\\Tools\\claude.cmd', ['--model', 'sonnet & calc.exe'], { shell: true, cwd: 'C:\\agent' }, 'win32')
+ assert.equal(plan.options.shell, false)
+ assert.equal(plan.options.windowsVerbatimArguments, true)
+ assert.deepEqual(plan.args.slice(0, 3), ['/d', '/s', '/c'])
+ assert.match(plan.args[3], /"sonnet & calc\.exe"/)
+ assert.equal(plan.options.windowsHide, true)
+})
diff --git a/server/src/agents/computer/cli-version.ts b/server/src/agents/computer/cli-version.ts
index 827b418..5bd511e 100644
--- a/server/src/agents/computer/cli-version.ts
+++ b/server/src/agents/computer/cli-version.ts
@@ -28,6 +28,7 @@ export function versionCommandInvocation(
args: string[],
platform = process.platform,
comspec = process.env.ComSpec || 'cmd.exe',
+ forceShell = false,
): CommandInvocation {
if (platform !== 'win32') return { command, args }
@@ -40,8 +41,15 @@ export function versionCommandInvocation(
}
}
}
- if (!/\.(?:cmd|bat)$/i.test(runnable)) return { command: runnable, args }
+ if (!forceShell && !/\.(?:cmd|bat)$/i.test(runnable)) return { command: runnable, args }
+ return comspecInvocation(comspec, runnable, args)
+}
+/** cmd.exe `/s /c` with one quoted command line. Node's `shell: true` joins
+ * argv without quoting, so a model id containing `&` becomes a second command.
+ * Arguments outside the unquoted token set are quoted; quotes inside them are
+ * doubled, which is cmd's escape. */
+function comspecInvocation(comspec: string, runnable: string, args: string[]): CommandInvocation {
const commandArgs = args.map((arg) => {
const value = String(arg)
return /^[\w./:=+-]+$/u.test(value) ? value : `"${value.replace(/"/g, '""')}"`
diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.ts
index a93ecb9..3047986 100644
--- a/server/src/agents/computer/daemon.ts
+++ b/server/src/agents/computer/daemon.ts
@@ -39,6 +39,7 @@ import {
} from '../memory-scope.js'
import { parseSseStream, wakeStreamWasStable } from '../runtime/sse-parse.js'
import { type ProviderProfile, providerProfileEnv, providerProfileFingerprint, providerProfileMetadata, readProviderProfiles, redactProviderSecret } from './provider-profiles.js'
+import { modelIdOrNull } from './model-id.js'
import { parseComputerControlEvent } from './control-event.js'
import {
mergeWakeBackgroundBriefs,
@@ -1708,8 +1709,9 @@ export function resolveEngineModel(
override: string | undefined,
): string | null {
const o = override?.trim()
- if (!o) return configured ?? null
- return o.toLowerCase() === ENGINE_MODEL_LOCAL ? null : o
+ if (!o) return modelIdOrNull(configured)
+ if (o.toLowerCase() === ENGINE_MODEL_LOCAL) return null
+ return modelIdOrNull(o)
}
/** The same knob governs the small-brain pin. `local` has to impose NOTHING:
@@ -1721,7 +1723,7 @@ export function resolveEngineFastModel(
configured: string | null | undefined,
override: string | undefined,
): string | null {
- return override?.trim().toLowerCase() === ENGINE_MODEL_LOCAL ? null : (configured ?? null)
+ return override?.trim().toLowerCase() === ENGINE_MODEL_LOCAL ? null : modelIdOrNull(configured)
}
/** Resolve the actual classifier model. A member-specific small brain is more
diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.ts
index 2ee53eb..9b64604 100644
--- a/server/src/agents/computer/engine.ts
+++ b/server/src/agents/computer/engine.ts
@@ -31,7 +31,7 @@ import { basename, dirname, join, delimiter as PATH_DELIMITER } from 'node:path'
import { StringDecoder } from 'node:string_decoder'
import { stripLoneSurrogates } from '../text-safety.js'
import { isCustomAnthropicEndpoint, readClaudeUserSettings, withClaudeUserSettingsEnv } from './claude-user-settings.js'
-import { isCliVersionAtLeast, probeEngineVersion, probeLocalEngineVersionWithRetry } from './cli-version.js'
+import { isCliVersionAtLeast, probeEngineVersion, probeLocalEngineVersionWithRetry, versionCommandInvocation } from './cli-version.js'
import { discoverEngineModelCatalog, type EngineModelCatalog } from './model-catalog.js'
const IS_WIN = process.platform === 'win32'
@@ -48,8 +48,38 @@ export function headlessSpawnOptions(options: SpawnOptions = {}): SpawnOptions {
return { ...options, windowsHide: true }
}
+/** What `spawn` will actually execute. On Windows, `shell: true` is rewritten
+ * to an explicit `cmd.exe /d /s /c` invocation with quoted arguments. Node's
+ * own `shell: true` does not quote argv, so a model id can break out of the
+ * command. Exported so the rewrite can be tested off Windows. */
+export function shellSafeSpawnPlan(
+ command: string,
+ args: string[],
+ options: SpawnOptions = {},
+ platform = process.platform,
+): { command: string; args: string[]; options: SpawnOptions } {
+ if (options.shell && platform === 'win32') {
+ const unquoted = command.length >= 2 && command.startsWith('"') && command.endsWith('"')
+ ? command.slice(1, -1)
+ : command
+ const invocation = versionCommandInvocation(unquoted, args, platform, process.env.ComSpec || 'cmd.exe', true)
+ const { shell: _shell, ...rest } = options
+ return {
+ command: invocation.command,
+ args: invocation.args,
+ options: headlessSpawnOptions({
+ ...rest,
+ shell: false,
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments === true,
+ }),
+ }
+ }
+ return { command, args, options: headlessSpawnOptions(options) }
+}
+
function spawn(command: string, args: string[], options: SpawnOptions = {}): ChildProcess {
- return nodeSpawn(command, args, headlessSpawnOptions(options))
+ const plan = shellSafeSpawnPlan(command, args, options)
+ return nodeSpawn(plan.command, plan.args, plan.options)
}
/** Model tools may spawn descendants that outlive the CLI parent. Put every
diff --git a/server/src/agents/computer/model-id.ts b/server/src/agents/computer/model-id.ts
new file mode 100644
index 0000000..b255edd
--- /dev/null
+++ b/server/src/agents/computer/model-id.ts
@@ -0,0 +1,35 @@
+/** Model ids are interpolated into engine argv. On Windows that argv is joined
+ * into a cmd.exe command line, so the id has to be a single token. Vendor ids
+ * use letters, digits, and `.` `_` `:` `/` `-`. Anything else is rejected. */
+export const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/
+
+export class InvalidModelIdError extends Error {
+ constructor() {
+ super('invalid model id')
+ this.name = 'InvalidModelIdError'
+ }
+}
+
+/** `undefined` leaves the stored value alone, `null` clears it, a string sets
+ * it. A non-string is ignored. A string that is not a model id throws. */
+export function parseModelId(value: unknown): string | null | undefined {
+ if (value === undefined) return undefined
+ if (value === null) return null
+ if (typeof value !== 'string') return undefined
+ const trimmed = value.trim()
+ if (!trimmed) return null
+ if (!MODEL_ID_RE.test(trimmed)) throw new InvalidModelIdError()
+ return trimmed
+}
+
+/** Spawn-time guard. An id that does not match is dropped instead of being
+ * passed to the shell. `local` is not a model id; callers handle it first. */
+export function modelIdOrNull(value: string | null | undefined): string | null {
+ if (value == null) return null
+ try {
+ return parseModelId(value) ?? null
+ } catch (error) {
+ if (error instanceof InvalidModelIdError) return null
+ throw error
+ }
+}
diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.ts
index eda0542..e0492b5 100644
--- a/server/src/agents/computer/registry.ts
+++ b/server/src/agents/computer/registry.ts
@@ -15,6 +15,7 @@
* runtime/jwt.ts — the same token a pod gets)
*/
import { type ProviderProfileMetadata, isProviderProfileId, sanitizeProviderProfiles } from './provider-profiles.js'
+import { InvalidModelIdError, parseModelId } from './model-id.js'
import { createHash, randomBytes, randomUUID } from 'node:crypto'
import { pool } from '../../db/pool.js'
import { audit } from '../../auth.js'
@@ -1201,8 +1202,10 @@ export async function reportDetectedEngines(args: {
}
/** Sanitize and validate engine defaults before storage. Only accepts known
- * engine ids and string model names within length limits. */
-function sanitizeEngineDefaults(raw: unknown): EngineDefaultsMap {
+ * engine ids and model ids. `strict` throws on a bad id so a write is
+ * rejected; a read drops the bad id instead, so one stored value cannot
+ * make the computer's defaults unreadable. */
+function sanitizeEngineDefaults(raw: unknown, strict = false): EngineDefaultsMap {
if (!raw || typeof raw !== 'object') return {}
const result: EngineDefaultsMap = {}
for (const [engineId, defaults] of Object.entries(raw as Record<string, unknown>)) {
@@ -1211,11 +1214,15 @@ function sanitizeEngineDefaults(raw: unknown): EngineDefaultsMap {
const rec = defaults as Record<string, unknown>
// Empty/whitespace-only strings mean "clear" — same as an explicit null.
const cleanModel = (value: unknown): string | null | undefined => {
- if (typeof value === 'string') {
- const trimmed = value.trim()
- return trimmed ? trimmed.slice(0, 160) : null
+ try {
+ return parseModelId(value)
+ } catch (error) {
+ if (error instanceof InvalidModelIdError) {
+ if (strict) throw error
+ return undefined
+ }
+ throw error
}
- return value === null ? null : undefined
}
const model = cleanModel(rec.model)
const fastModel = cleanModel(rec.fastModel)
@@ -1250,7 +1257,7 @@ export async function updateEngineDefaults(args: {
return null
}
const existing = sanitizeEngineDefaults(rows[0].engine_defaults)
- const merged = sanitizeEngineDefaults(args.defaults)
+ const merged = sanitizeEngineDefaults(args.defaults, true)
// Deep merge: for each engine, merge model and fastModel
for (const [engineId, defaults] of Object.entries(merged)) {
if (defaults.model === null && defaults.fastModel === null) {
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 3f8fbcf..66f761f 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -10,6 +10,7 @@
*/
import { Router, json, type Request, type Response, type NextFunction } from 'express'
import { isProviderProfileId } from '../agents/computer/provider-profiles.js'
+import { InvalidModelIdError, parseModelId } from '../agents/computer/model-id.js'
import type { PoolClient } from 'pg'
import {
storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey,
@@ -1365,11 +1366,17 @@ api.put('/computers/:id/engine-defaults', safe(async (req, res) => {
if (!defaults || typeof defaults !== 'object') {
throw new HttpError(400, 'defaults object required')
}
- const updated = await updateEngineDefaults({
- computerId: String(req.params.id),
- companyId,
- defaults,
- })
+ let updated: Awaited<ReturnType<typeof updateEngineDefaults>>
+ try {
+ updated = await updateEngineDefaults({
+ computerId: String(req.params.id),
+ companyId,
+ defaults,
+ })
+ } catch (error) {
+ if (error instanceof InvalidModelIdError) throw new HttpError(400, 'invalid model id')
+ throw error
+ }
if (updated === null) throw new HttpError(404, 'computer not found')
res.json({ ok: true, defaults: updated })
}))
@@ -2956,10 +2963,15 @@ function readAgentBody(b: AgentBody): {
if (typeof b.avatarBg === 'string') out.avatarBg = b.avatarBg.trim()
if (b.avatarUrl === null) out.avatarUrl = null
else if (typeof b.avatarUrl === 'string') out.avatarUrl = b.avatarUrl.trim()
- if (b.model === null) out.model = null
- else if (typeof b.model === 'string') out.model = b.model.trim() || null
- if (b.fastModel === null) out.fastModel = null
- else if (typeof b.fastModel === 'string') out.fastModel = b.fastModel.trim() || null
+ try {
+ const model = parseModelId(b.model)
+ const fastModel = parseModelId(b.fastModel)
+ if (model !== undefined) out.model = model
+ if (fastModel !== undefined) out.fastModel = fastModel
+ } catch (error) {
+ if (error instanceof InvalidModelIdError) throw new HttpError(400, 'invalid model id')
+ throw error
+ }
if (Array.isArray(b.tools)) out.tools = b.tools.map((x) => String(x))
return out as ReturnType<typeof readAgentBody>
}