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(email): reject filesystem attachment paths (#110)

OKNOTOK73585d9c2c03
diff --git a/docs/email.md b/docs/email.md
index b39a36f..5130f07 100644
--- a/docs/email.md
+++ b/docs/email.md
@@ -244,6 +244,11 @@ cumora email reply <message_id> --body "..." [--cc ...]
`--to` and `--cc` accept either real addresses (`[email protected]`) or
participant ids (`aurora`); ids are resolved against the agent's tenant.
+Agent CLI email is text-only. Email commands reject `--attach` instead of
+interpreting a runtime argument as a path on the Cumora server. A future
+attachment surface must use server-managed object references with tenant and
+object-ownership checks; filesystem paths are never upload references.
+
## Heartbeat integration
`server/src/agents/idle.ts` runs every `IDLE_INTERVAL_MS` (default
diff --git a/server/src/__integration__/runtime-server.test.ts b/server/src/__integration__/runtime-server.test.ts
index d2d83bd..0a24421 100644
--- a/server/src/__integration__/runtime-server.test.ts
+++ b/server/src/__integration__/runtime-server.test.ts
@@ -17,15 +17,17 @@
* - Payload validation: 400s for missing required fields, without ever
* touching the DB.
*
- * The full /cli endpoint (which actually spawns runCli) is intentionally
- * not exercised here — booting the CLI requires the whole agent stack.
- * Its security-critical bit (argv strip + JWT-sub injection) lives in
- * agents-runtime-cli-argv.test.ts as a unit test.
+ * The full /cli endpoint is covered for security-critical boundaries that
+ * require the real HTTP/JWT/runCli chain. Lower-level argv normalization
+ * remains exhaustively covered in agents-runtime-cli-argv.test.ts.
*/
import { test, before, beforeEach, after } from 'node:test'
import assert from 'node:assert/strict'
import { createServer, type Server } from 'node:http'
import { randomUUID } from 'node:crypto'
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'
import { mintAgentRuntimeToken } from '../agents/computer/registry.js'
import { signAgentToken, verifyAgentToken } from '../agents/runtime/jwt.js'
@@ -303,6 +305,95 @@ test('[integration] runtime: /inbox-triage/payload rejects a stale token before
assert.match(String(r.body?.error ?? ''), /token tenant/i)
})
+test('[integration] runtime: /cli rejects email server-path attachments before storage or mail side effects', async () => {
+ const { token } = await seedAgent()
+ const root = await mkdtemp(join(tmpdir(), 'cumora-email-attachment-'))
+ const secretPath = join(root, 'server-secret.txt')
+ const nested = join(root, 'nested')
+ const symlinkPath = join(root, 'server-secret-link.txt')
+ await writeFile(secretPath, 'must never leave the server')
+ await mkdir(nested)
+ await symlink(secretPath, symlinkPath)
+
+ const candidates = [
+ secretPath,
+ `${nested}/../server-secret.txt`,
+ symlinkPath,
+ '/proc/self/environ',
+ '/var/run/secrets/kubernetes.io/serviceaccount/token',
+ ]
+
+ try {
+ const { storage } = await import('../storage.js')
+ const beforeKeys = (await storage.listObjectsByPrefix('email-attachments/'))
+ .map((item) => item.key)
+ .sort()
+
+ for (const candidate of candidates) {
+ for (const argv of [
+ ['email', 'send', '--to', '[email protected]', '--subject', 'status', '--body', 'body', '--attach', candidate],
+ ['email', 'reply', 'missing-message', '--body', 'body', '--attach', candidate],
+ ]) {
+ const r = await call('/runtime/cli', { token, body: { argv } })
+ assert.equal(r.status, 200)
+ assert.equal(r.body?.ok, false)
+ assert.equal(r.body?.exitCode, 1)
+ assert.match(String(r.body?.text ?? ''), /never accepts server filesystem paths/i)
+ }
+ }
+
+ const afterKeys = (await storage.listObjectsByPrefix('email-attachments/'))
+ .map((item) => item.key)
+ .sort()
+ assert.deepEqual(afterKeys, beforeKeys, 'rejected paths must not upload storage objects')
+
+ const { rows } = await pool.query<{
+ conversations: number; messages: number; emailMessages: number; emailAttachments: number;
+ }>(
+ `SELECT
+ (SELECT COUNT(*)::int FROM conversations) AS conversations,
+ (SELECT COUNT(*)::int FROM messages) AS messages,
+ (SELECT COUNT(*)::int FROM email_messages) AS "emailMessages",
+ (SELECT COUNT(*)::int FROM email_attachments) AS "emailAttachments"`,
+ )
+ assert.deepEqual(rows[0], {
+ conversations: 0,
+ messages: 0,
+ emailMessages: 0,
+ emailAttachments: 0,
+ })
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
+
+test('[integration] runtime: /cli still sends text-only agent email in mock mode', async () => {
+ const { token } = await seedAgent()
+ const r = await call('/runtime/cli', {
+ token,
+ body: {
+ argv: [
+ 'email', 'send',
+ '--to', '[email protected]',
+ '--subject', 'text-only status',
+ '--body', 'safe body',
+ ],
+ },
+ })
+
+ assert.equal(r.status, 200)
+ assert.equal(r.body?.ok, true, String(r.body?.text ?? ''))
+ assert.equal(r.body?.sideEffects?.[0]?.event, 'email.sent')
+ assert.equal(r.body?.sideEffects?.[0]?.attachmentCount, 0)
+
+ const { rows } = await pool.query<{ messages: number; attachments: number }>(
+ `SELECT
+ (SELECT COUNT(*)::int FROM email_messages) AS messages,
+ (SELECT COUNT(*)::int FROM email_attachments) AS attachments`,
+ )
+ assert.deepEqual(rows[0], { messages: 1, attachments: 0 })
+})
+
test('[integration] runtime: /faces requires a tenant-pinned token', async () => {
const { agentId } = await seedAgent()
const token = signAgentToken({ agentId, companyId: null })
diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.ts
index 1df18b5..fce61c0 100644
--- a/server/src/agents/cli.ts
+++ b/server/src/agents/cli.ts
@@ -1599,6 +1599,8 @@ async function cmdReply(parsed: ParsedArgs): Promise<CliResult> {
// sendViaProvider path. autoSubmitted=true because every CLI reply is
// agent-driven by construction.
if (cv[0].kind === 'email') {
+ const attachmentError = rejectsEmailAttachmentFlags(parsed)
+ if (attachmentError) return attachmentError
if (!body) {
return err('email replies require a non-empty body')
}
@@ -2299,39 +2301,6 @@ function extToMime(ext: string): string | null {
}
}
-/** Load a local file for use as an outbound email attachment. Reads the
- * bytes off the agent's filesystem, uploads them to object storage under
- * the `email-attachments/` prefix (same prefix the inbound webhook uses
- * — keeps the renderer's JOIN agnostic to direction), and returns the
- * combined metadata. The returned `base64` is what we hand to Resend;
- * the `storageKey` + `publicUrl` are how the recipient's UI downloads
- * the file after the fact. */
-async function loadEmailAttachmentFromPath(path: string): Promise<{
- filename: string; mimeType: string; sizeBytes: number;
- base64: string; storageKey: string; publicUrl: string;
-}> {
- const fs = await import('node:fs/promises')
- const nodePath = await import('node:path')
- const cryptoMod = await import('node:crypto')
- const MAX_BYTES = 20 * 1024 * 1024 // 20MB — matches Resend's per-attachment ceiling
- const buf = await fs.readFile(path)
- if (buf.length === 0) throw new Error(`empty file: ${path}`)
- if (buf.length > MAX_BYTES) {
- throw new Error(`file too large: ${buf.length} bytes (max ${MAX_BYTES})`)
- }
- const filename = nodePath.basename(path)
- const ext = filename.includes('.') ? filename.split('.').pop()!.toLowerCase() : 'bin'
- const mimeType = extToMime(ext) ?? 'application/octet-stream'
- const id = cryptoMod.randomUUID().replace(/-/g, '')
- const storageKey = `email-attachments/${id}${ext ? '.' + ext : ''}`
- const publicUrl = await storage.put(storageKey, buf, mimeType)
- return {
- filename, mimeType, sizeBytes: buf.length,
- base64: buf.toString('base64'),
- storageKey, publicUrl,
- }
-}
-
/** Regenerate the calling agent's portrait via the image API. Composes
* the same prompt the HTTP endpoint uses, uploads to storage as
* `avatars/avatar-<id>-<rand>.png`, and stamps `participants.avatar_url`.
@@ -2860,8 +2829,8 @@ async function cmdEmail(parsed: ParsedArgs): Promise<CliResult> {
if (!sub) {
return err(
'usage:\n' +
- ' email send --to <addr|id>[,<addr|id>...] [--cc <...>] --subject "..." --body "..." [--attach <path>[,<path>...]] [--as <id>]\n' +
- ' email reply <message_id> --body "..." [--cc <addr|id>...] [--attach <path>[,<path>...]] [--as <id>]\n' +
+ ' email send --to <addr|id>[,<addr|id>...] [--cc <...>] --subject "..." --body "..." [--as <id>]\n' +
+ ' email reply <message_id> --body "..." [--cc <addr|id>...] [--as <id>]\n' +
' email inbox [--unread] [--limit N] [--as <id>]\n' +
' email show <conversation_id> [--tail N] [--as <id>]\n' +
' email contacts [<query>] [--as <id>] (or just: cumora contacts [<query>])\n' +
@@ -2884,6 +2853,21 @@ async function cmdEmail(parsed: ParsedArgs): Promise<CliResult> {
}
}
+const EMAIL_ATTACHMENTS_UNSUPPORTED =
+ 'outbound email attachments are not supported; --attach never accepts server filesystem paths'
+
+function rejectsEmailAttachmentFlags(parsed: ParsedArgs): CliResult | null {
+ if (
+ parsed.flags.attach ||
+ parsed.flags['attach-text'] ||
+ parsed.flags['attach-bytes'] ||
+ parsed.flags['generate-image']
+ ) {
+ return err(EMAIL_ATTACHMENTS_UNSUPPORTED)
+ }
+ return null
+}
+
async function cmdEmailWhoami(me: string): Promise<CliResult> {
const { ensureAgentAddress } = await import('../email.js')
const { env } = await import('../env.js')
@@ -3034,22 +3018,11 @@ async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string):
} = await import('../email.js')
const subject = sanitizeSubject(unescapeChat(String(parsed.flags.subject ?? '')))
const body = unescapeChat(String(parsed.flags.body ?? '')).trim()
- // --attach takes a comma-separated list of paths (also accepts the same
- // flag repeated by the agent — bin/cumora collapses repeats into the
- // last value, so comma is the supported multi-attach syntax here).
- const attachRaw = parsed.flags.attach ? String(parsed.flags.attach) : ''
if (!toRaw || !subject || !body) {
- return err('usage: email send --to <addr|id>[,...] [--cc <...>] --subject "..." --body "..." [--attach <path>[,<path>...]]')
- }
- const attachPaths = attachRaw.split(',').map((s) => s.trim()).filter(Boolean)
- const loadedAttachments: Awaited<ReturnType<typeof loadEmailAttachmentFromPath>>[] = []
- for (const p of attachPaths) {
- try {
- loadedAttachments.push(await loadEmailAttachmentFromPath(p))
- } catch (e) {
- return err(`attachment ${p}: ${e instanceof Error ? e.message : String(e)}`)
- }
+ return err('usage: email send --to <addr|id>[,...] [--cc <...>] --subject "..." --body "..."')
}
+ const attachmentError = rejectsEmailAttachmentFlags(parsed)
+ if (attachmentError) return attachmentError
const sender = await ensureAgentAddress(me)
if (!sender) return err('agent has no email address (EMAIL_DOMAIN unset or company missing)')
@@ -3100,9 +3073,6 @@ async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string):
text: body,
messageId,
autoSubmitted: 'auto-generated',
- attachments: loadedAttachments.map((a) => ({
- filename: a.filename, mimeType: a.mimeType, base64: a.base64,
- })),
})
const persisted = await persistEmailMessage({
@@ -3121,10 +3091,6 @@ async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string):
ccAddrs: ccResolved.map((r) => formatAddress(r.addr, r.name)),
body,
autoSubmitted: true,
- attachments: loadedAttachments.map((a) => ({
- filename: a.filename, mimeType: a.mimeType, sizeBytes: a.sizeBytes,
- storageKey: a.storageKey,
- })),
})
if (!sendRes.ok) {
@@ -3141,7 +3107,7 @@ async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string):
subject,
to: toResolved.map((r) => r.addr),
cc: ccResolved.map((r) => r.addr),
- attachmentCount: loadedAttachments.length,
+ attachmentCount: 0,
transportStatus: 'sent',
mock: sendRes.mock,
visibleToUser: true,
@@ -3151,17 +3117,9 @@ async function cmdEmailSend(parsed: ParsedArgs, me: string, companyId: string):
async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string): Promise<CliResult> {
const replyTo = parsed.positional[1]
const body = unescapeChat(String(parsed.flags.body ?? '')).trim()
- const attachRaw = parsed.flags.attach ? String(parsed.flags.attach) : ''
- if (!replyTo || !body) return err('usage: email reply <message_id> --body "..." [--cc <addr|id>...] [--attach <path>[,<path>...]]')
- const attachPaths = attachRaw.split(',').map((s) => s.trim()).filter(Boolean)
- const loadedAttachments: Awaited<ReturnType<typeof loadEmailAttachmentFromPath>>[] = []
- for (const p of attachPaths) {
- try {
- loadedAttachments.push(await loadEmailAttachmentFromPath(p))
- } catch (e) {
- return err(`attachment ${p}: ${e instanceof Error ? e.message : String(e)}`)
- }
- }
+ if (!replyTo || !body) return err('usage: email reply <message_id> --body "..." [--cc <addr|id>...]')
+ const attachmentError = rejectsEmailAttachmentFlags(parsed)
+ if (attachmentError) return attachmentError
// Pull the original email row and its conversation context.
const { rows: orig } = await pool.query<{
conversation_id: string
@@ -3250,9 +3208,6 @@ async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string):
references: newReferences,
messageId,
autoSubmitted: 'auto-replied',
- attachments: loadedAttachments.map((a) => ({
- filename: a.filename, mimeType: a.mimeType, base64: a.base64,
- })),
})
const persisted = await persistEmailMessage({
@@ -3271,10 +3226,6 @@ async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string):
ccAddrs: ccCombined,
body,
autoSubmitted: true,
- attachments: loadedAttachments.map((a) => ({
- filename: a.filename, mimeType: a.mimeType, sizeBytes: a.sizeBytes,
- storageKey: a.storageKey,
- })),
})
// Auto-ack — replying definitionally means I read the original.
@@ -3298,7 +3249,7 @@ async function cmdEmailReply(parsed: ParsedArgs, me: string, companyId: string):
subject,
to: toAddrs,
cc: ccCombined,
- attachmentCount: loadedAttachments.length,
+ attachmentCount: 0,
transportStatus: 'sent',
mock: sendRes.mock,
visibleToUser: true,