/** * Attachment uploads — POST writes bytes through the configured ObjectStore * driver (ADR-002 Phase 1); GET streams them back, trying the driver first * and falling back to legacy `File.data` records for backward compatibility. * * ADR-002 Phase 1b adds the signed-URL mint endpoint: * - `GET /:fileName/url` — bearer-auth'd, ACL-checked, rate-limited mint of * a short-TTL token scoped to `(fileName, viewerUserId)`. The frontend * exchanges this for a URL (`/api/uploads/:fileName?t=`) it can * drop into ``. * * The public-read behavior on `GET /:fileName` is unchanged in this PR. The * `?t=` query param is passed through harmlessly today; the follow-up PR * flips `GET /:fileName` to require a valid token or header auth and drops * the unauth fallback. Until that flip lands, the REVIEW.md §Attachments * invariant ("GET must be authorized") is not fully satisfied. */ // ADR-002 Phase 1b: ESM import (not require) so CodeQL's js/missing-rate-limiting // query recognises the middleware on the mint route. import rateLimit from 'express-rate-limit'; import { createHash } from 'crypto'; import path from 'path'; import jwt from 'jsonwebtoken'; import { DEFAULT_TOKEN_TTL_SECONDS, canReadAttachment, signAttachmentToken, verifyAttachmentToken, } from '../services/attachmentAccess'; import { logAttachmentTokenMint } from '../services/auditService'; import { cloudflareIpRateLimitKeyGenerator, presentedCredentialRateLimitKeyGenerator, authenticatedUserRateLimitKeyGenerator, } from '../middleware/ipRateLimit'; import { normalizeAvatarUrl } from '../services/avatarService'; // eslint-disable-next-line global-require const express = require('express'); // eslint-disable-next-line global-require const multer = require('multer'); // eslint-disable-next-line global-require const File = require('../models/File'); // eslint-disable-next-line global-require const User = require('../models/User'); // eslint-disable-next-line global-require const auth = require('../middleware/auth'); const { refuseDollarKeys } = require('../middleware/refuseDollarKeys'); // eslint-disable-next-line global-require const agentRuntimeAuth = require('../middleware/agentRuntimeAuth'); import { getObjectStore } from '../services/objectStore'; import { loadSessionAccount, sessionRefusal } from '../services/sessionAccountService'; import { requirePodMember } from '../services/podMembershipService'; interface AuthReq { userId?: string; ip?: string; get?: (header: string) => string | undefined; file?: { originalname: string; mimetype: string; size: number; buffer: Buffer }; params?: { fileName?: string }; query?: { t?: string }; body?: { podId?: string }; agentUser?: { _id: { toString: () => string } }; agentAuthorizedPodIds?: string[]; } interface Res { status: (n: number) => Res; json: (d: unknown) => void; set: (header: string, value: string) => void; send: (d: unknown) => void; } // Per-kind extension allowlist. Replaces the original image-only regex. // // Office formats (docx/xlsx/pptx + legacy doc/xls/ppt) and zip archives // shipped 2026-05-03 alongside the v2 inspector demo path. They store as // opaque bytes and download (no in-page render), so the XSS / SVG-style // attack surface that gates `image/*` doesn't apply. Macro execution risk // lives at file-OPEN on the user's machine — same model as receiving the // same file via email. // // Still deferred to ADR-002 Phase 6: ClamAV scanning, AV media (mp4/mov/ // mp3/wav — large + needs streaming), virus signature feed. const KIND_EXTENSIONS: Record = { image: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'], document: ['pdf', 'md', 'txt'], data: ['csv', 'json'], office: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp'], archive: ['zip'], }; const ALLOWED_EXT_REGEX = new RegExp( `\\.(${Object.values(KIND_EXTENSIONS).flat().join('|')})$`, 'i', ); const kindFromName = (originalName: string): string => { const dot = originalName.lastIndexOf('.'); if (dot < 0) return 'other'; const ext = originalName.slice(dot + 1).toLowerCase(); for (const [kind, exts] of Object.entries(KIND_EXTENSIONS)) { if (exts.includes(ext)) return kind; } return 'other'; }; // What a stored file is served as. The type comes from the file's extension, // which the upload allowlist has already checked, never from the type the // uploading client declared. Only types a browser renders without running // anything are served inline; everything else, SVG included, downloads. const SERVED_TYPES: Record = { jpg: { type: 'image/jpeg', inline: true }, jpeg: { type: 'image/jpeg', inline: true }, png: { type: 'image/png', inline: true }, gif: { type: 'image/gif', inline: true }, webp: { type: 'image/webp', inline: true }, svg: { type: 'image/svg+xml', inline: false }, pdf: { type: 'application/pdf', inline: true }, md: { type: 'text/plain; charset=utf-8', inline: true }, txt: { type: 'text/plain; charset=utf-8', inline: true }, csv: { type: 'text/csv; charset=utf-8', inline: true }, json: { type: 'application/json; charset=utf-8', inline: true }, doc: { type: 'application/msword', inline: false }, docx: { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', inline: false }, xls: { type: 'application/vnd.ms-excel', inline: false }, xlsx: { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', inline: false }, ppt: { type: 'application/vnd.ms-powerpoint', inline: false }, pptx: { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', inline: false }, odt: { type: 'application/vnd.oasis.opendocument.text', inline: false }, ods: { type: 'application/vnd.oasis.opendocument.spreadsheet', inline: false }, odp: { type: 'application/vnd.oasis.opendocument.presentation', inline: false }, zip: { type: 'application/zip', inline: false }, }; const OPAQUE = { type: 'application/octet-stream', inline: false }; const setServedHeaders = (res: Res, fileName: string): void => { const ext = path.extname(fileName).slice(1).toLowerCase(); const served = Object.prototype.hasOwnProperty.call(SERVED_TYPES, ext) ? SERVED_TYPES[ext] : OPAQUE; res.set('Content-Type', served.type); res.set('X-Content-Type-Options', 'nosniff'); res.set('Content-Disposition', served.inline ? 'inline' : 'attachment'); // Set explicitly on every response that carries file bytes, so the header never depends on a default. res.set('Cache-Control', 'private, no-store'); }; // Size cap is driven by the driver's declared max. multer returns 413 itself // when the multipart exceeds it, so the route doesn't need a secondary check. // // This runs at module load, so driver constructors MUST stay pure (no network, // no DB connects). The current MongoObjectStore only sets capability fields; // any future driver (GCS, S3) should defer network I/O to first put/get, not // its constructor, or this require() becomes a silent network call. const MAX_UPLOAD_BYTES = getObjectStore().capabilities.maxObjectBytes; const storage = multer.memoryStorage(); const upload = multer({ storage, limits: { fileSize: MAX_UPLOAD_BYTES }, fileFilter( _req: unknown, file: { originalname: string }, cb: (err: Error | null, accept: boolean) => void, ) { if (!ALLOWED_EXT_REGEX.test(file.originalname)) { return cb(new Error('File type not allowed'), false); } cb(null, true); }, }); // Wrap multer.single so filter / size errors become 400s instead of bubbling // as 500. Multer's default error path is the route's try/catch, which can't // distinguish "user sent a bad type" from "driver crashed". const uploadSingle = (field: string) => (req: AuthReq, res: Res, next: (err?: unknown) => void) => { upload.single(field)(req as never, res as never, (err: unknown) => { if (err) { const e = err as { code?: string; message?: string }; if (e?.code === 'LIMIT_FILE_SIZE') { return res.status(413).json({ msg: 'File too large' }); } return res.status(400).json({ msg: e?.message || 'Invalid upload' }); } // multer parses the multipart fields only now, after the global // `$`-key check has run, so the fields are checked here too. return refuseDollarKeys(req as never, res as never, next as never); }); }; // 30 mints/min/bucket is generous for a page loading dozens of avatars + // images (clients cache until TTL expiry) and low enough that a compromised // JWT can't scrape attachments en masse. Keyed on the Authorization header // (hashed) so each user's bearer token gets its own bucket — NAT'd users // sharing one office IP don't collide. Falling back to the Cloudflare edge IP // covers the unauth path. Inlined in this file and applied as the FIRST // middleware on the route so CodeQL's `js/missing-rate-limiting` query sees it // (the query only recognises the limiter when it precedes other middleware). const mintRateLimit = rateLimit({ windowMs: 60_000, max: 30, standardHeaders: true, legacyHeaders: false, keyGenerator: (req: AuthReq) => { const authHeader = req.get?.('authorization'); if (authHeader) { return `tok:${createHash('sha256').update(authHeader).digest('hex').slice(0, 16)}`; } return cloudflareIpRateLimitKeyGenerator(req as never); }, handler: (_req: unknown, res: Res) => res.status(429).json({ msg: 'rate limit exceeded: 30 mints per 60s' }), }); // IP-keyed limiter for the UNAUTHENTICATED artifact GETs below // (`/:fileName` + `/:fileName/preview-pptx-html`). These have public read by // design today (the showcase renders artifacts through them, ADR-002 Phase 1); // this blunts mass scraping without changing their auth. The full signed-URL // flip that removes public-read is the documented follow-up. ~240/min/IP is // generous for a showcase page loading dozens of artifacts but caps a scraper. // Applied as the FIRST middleware on each GET so CodeQL's js/missing-rate-limiting // query recognises it. const artifactReadRateLimit = rateLimit({ windowMs: 60_000, max: 240, standardHeaders: true, legacyHeaders: false, keyGenerator: (req: AuthReq) => cloudflareIpRateLimitKeyGenerator(req as never), handler: (_req: unknown, res: Res) => res.status(429).json({ msg: 'rate limit exceeded: 240 requests per 60s' }), }); // Attachment reads also serve browser image requests, so they cannot require // auth unconditionally: signed URLs and public avatars arrive without an // Authorization header. Runtime clients do send their opaque `cm_agent_*` // token, however. Resolve that token before the ACL check so the existing // user-based attachment policy can evaluate the agent's bot User row. // Human JWTs deliberately keep the existing inline verification path in // authorizePodFile below. const maybeAgentRuntimeAuth = (req: AuthReq, res: Res, next: () => void) => { const bearer = req.get?.('Authorization')?.replace(/^Bearer\s+/i, '').trim(); const alternate = req.get?.('x-commonly-agent-token')?.trim(); if (!(bearer || alternate)?.startsWith('cm_agent_')) return next(); return agentRuntimeAuth(req as never, res as never, next); }; const router: ReturnType = express.Router(); // Shared upload handler — used by both the user-auth POST / and the // agent-runtime POST /agent. Caller passes the resolved uploader id and // (optionally) the podId scope to bind the File row to. // // Upload routes accept a `podId` form field; populating it surfaces the // file in the pod inspector's Artifacts section. Agent uploads must // supply a podId they're installed in (enforced in the agent route). const handleUpload = async ( req: AuthReq, res: Res, uploaderId: string, ): Promise => { try { if (!req.file) { res.status(400).json({ msg: 'No file uploaded' }); return; } const uploader = await User.findById(uploaderId).select('accountDeletionRequestedAt').lean(); if (!uploader || uploader.accountDeletionRequestedAt) { res.status(403).json({ msg: 'Account deletion is in progress. Uploads are disabled.' }); return; } const store = getObjectStore(); const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`; const ext = path.extname(req.file.originalname); const fileName = `user-${uploaderId}-${uniqueSuffix}${ext}`; const kind = kindFromName(req.file.originalname); const podId = req.body?.podId?.toString().trim() || null; await store.put(fileName, req.file.buffer, req.file.mimetype); // Metadata-only File record. Bytes live in the ObjectStore driver; // Phase 2 replaces File with a proper Attachment registry and removes // the legacy `data` field entirely. const newFile = new File({ fileName, originalName: req.file.originalname, contentType: req.file.mimetype, size: req.file.size, uploadedBy: uploaderId, podId, }); await newFile.save(); // A request authenticated before deletion may finish its upload after the // deletion scan. Recheck AFTER metadata exists: either the scan owns it, // or this request removes both the bytes and its metadata. const remainingUploader = await User.findById(uploaderId).select('accountDeletionRequestedAt').lean(); if (!remainingUploader || remainingUploader.accountDeletionRequestedAt) { await store.delete(fileName); await File.deleteOne({ _id: newFile._id }); res.status(403).json({ msg: 'Account deletion is in progress. Upload discarded.' }); return; } // Stored upload references must survive hostname changes. Callers can // persist this response directly without baking the current API origin // into User.profilePicture or package icon metadata. const url = normalizeAvatarUrl(fileName); res.json({ url, fileName, originalName: req.file.originalname, contentType: req.file.mimetype, size: req.file.size, kind, podId, }); } catch (err) { const e = err as { message?: string }; console.error('Upload error:', e.message); res.status(500).json({ msg: 'Server Error' }); } }; const uploadCredentialRateLimit = rateLimit({ windowMs: 15 * 60_000, max: 6000, standardHeaders: true, legacyHeaders: false, keyGenerator: presentedCredentialRateLimitKeyGenerator, }); const uploadRateLimit = rateLimit({ windowMs: 15 * 60_000, max: 60, standardHeaders: true, legacyHeaders: false, keyGenerator: authenticatedUserRateLimitKeyGenerator, }); // A podId binds the file to that pod's Files and its agents' context, so the // uploader must hold write membership there, the same check task writes use. // Every refusal (unknown pod, malformed id, non-member, viewer) answers the // same 403, so the route does not reveal which pods exist. The agent route // pins podId to a pod its token is authorized for and does not come here. const podWriteRefused = async (podId: string, userId: string): Promise => { if (!/^[0-9a-f]{24}$/i.test(podId)) return true; try { return Boolean((await requirePodMember(podId, userId, { write: true })).error); } catch { return true; } }; router.post('/', uploadCredentialRateLimit, auth, uploadRateLimit, uploadSingle('image'), async (req: AuthReq, res: Res) => { if (!req.userId) { res.status(401).json({ msg: 'auth required' }); return; } const podId = req.body?.podId?.toString().trim(); if (podId && await podWriteRefused(podId, req.userId)) { res.status(403).json({ msg: 'You cannot add files to this pod' }); return; } await handleUpload(req, res, req.userId); }); // ADR-002 Phase 1b: signed-URL mint endpoint. Declared before the bare // `:fileName` GET so Express doesn't match `/:fileName/url` as a fileName // containing a slash. `mintRateLimit` runs before `auth` because (1) CodeQL's // js/missing-rate-limiting query only recognises the limiter as the first // middleware, and (2) the limiter's keyGenerator reads the Authorization // header directly, so it doesn't need auth to have populated `req.userId`. router.get('/:fileName/url', mintRateLimit, auth, async (req: AuthReq, res: Res) => { try { const fileName = req.params?.fileName; if (!fileName) return res.status(400).json({ msg: 'fileName required' }); if (!req.userId) return res.status(401).json({ msg: 'auth required' }); const allowed = await canReadAttachment(fileName, req.userId); if (!allowed) return res.status(403).json({ msg: 'no access to this attachment' }); const token = signAttachmentToken(fileName, req.userId); const url = `/api/uploads/${fileName}?t=${encodeURIComponent(token)}`; // Fire-and-forget: auditService swallows failures. void logAttachmentTokenMint({ fileName, userId: req.userId, ip: req.ip, userAgent: req.get?.('user-agent'), }); return res.json({ url, expiresIn: DEFAULT_TOKEN_TTL_SECONDS }); } catch (err) { const e = err as { message?: string }; console.error('Mint signed URL error:', e.message); return res.status(500).json({ msg: 'Server Error' }); } }); // ADR-002 Phase 1b "flip" — authorize reads of a POD-SCOPED file. Previously // ANY caller who knew a filename could read a file bound to a private pod // (IDOR). A file with a podId now requires one of: // (a) a valid `?t=` minted by GET /:fileName/url (the frontend // already mints these via getSignedAttachmentUrl before rendering), or // (b) a Bearer token whose user canReadAttachment (owner / pod member). // // A Bearer token is a user session, so it is verified against the live row the // same way the HTTP middleware and the socket handshake verify theirs: a session // whose account has since become an agent is not a person's read any more // (TASK-133). `authorizePodFile` used to check the signature and the ACL and // never read the row, so `canReadAttachment` decided on behalf of a bot user. // Un-scoped files (avatars, profile pictures — File.podId null) are always // allowed, matching how they render in public post feeds. Returns true when // the read is permitted. const authorizePodFile = async (req: AuthReq, fileName: string): Promise => { // findByFileName returns a Mongoose query (.lean() → plain object); some // callers/tests resolve it directly, so handle both shapes. const q = File.findByFileName(fileName); const meta = q && typeof q.lean === 'function' ? await q.lean() : await q; if (!meta?.podId) return true; // un-scoped: public (avatars etc.) const token = typeof req.query?.t === 'string' ? req.query.t : ''; if (token && verifyAttachmentToken(token, fileName)) return true; const agentUserId = req.agentUser?._id?.toString(); if (agentUserId && await canReadAttachment(fileName, agentUserId)) return true; const bearer = req.get?.('Authorization')?.replace('Bearer ', ''); if (bearer) { try { const decoded = jwt.verify(bearer, process.env.JWT_SECRET as string) as Record; const uid = (decoded.id || (decoded.user as Record)?.id) as string | undefined; if (uid && !sessionRefusal(await loadSessionAccount(uid), decoded) && await canReadAttachment(fileName, uid)) { return true; } } catch { // invalid bearer — fall through to unauthorized } } return false; }; router.get('/:fileName', artifactReadRateLimit, maybeAgentRuntimeAuth, async (req: AuthReq, res: Res) => { try { const fileName = req.params?.fileName; if (!fileName) return res.status(400).json({ msg: 'fileName required' }); // ADR-002 Phase 1b "flip" — authorize POD-SCOPED files (see // authorizePodFile). Un-scoped files (avatars) stay publicly readable. if (!(await authorizePodFile(req, fileName))) { return res.status(403).json({ msg: 'Not authorized to read this file' }); } const store = getObjectStore(); const obj = await store.get(fileName); if (obj) { setServedHeaders(res, fileName); (obj.stream as unknown as { pipe: (dst: unknown) => void }).pipe(res); return; } // Backward-compat fallback for pre-ADR-002 records with inline bytes. // Phase 2 backfills these into the driver and removes this fallback. const legacy = await File.findByFileName(fileName); if (legacy && legacy.data && legacy.data.length > 0) { setServedHeaders(res, fileName); return res.send(legacy.data); } return res.status(404).json({ msg: 'File not found' }); } catch (err) { const e = err as { message?: string }; console.error('Error retrieving file:', e.message); return res.status(500).json({ msg: 'Server Error' }); } }); // PPTX → HTML preview rendering via the bundled OfficeCLI binary in the // backend image. Used by the v2 inspector's PptxPreview component to render // uploaded .pptx files inline. The output HTML is self-contained (embedded // CSS, three.js loaded from a CDN inside the iframe sandbox) so we just pass // it through to the browser as text/html. // // Auth — preview shares the raw-file route's pod-scoped authorization below. // A private deck must not become readable merely because it is rendered. const officecliPreview = (() => { // eslint-disable-next-line @typescript-eslint/no-require-imports const { spawn } = require('child_process'); // eslint-disable-next-line @typescript-eslint/no-require-imports const { mkdtempSync, readFileSync, writeFileSync, rmSync, readdirSync } = require('fs'); // eslint-disable-next-line @typescript-eslint/no-require-imports const fsPath = require('path'); // eslint-disable-next-line @typescript-eslint/no-require-imports const osMod = require('os'); const runOfficeCli = (args: string[], cwd: string): Promise<{ stdout: string; stderr: string; code: number }> => new Promise((resolve) => { const child = spawn('officecli', args, { cwd }); let stdout = ''; let stderr = ''; child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString(); }); child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString(); }); child.on('close', (code: number | null) => resolve({ stdout, stderr, code: code ?? -1 })); }); return { renderPptx: async (binary: Buffer): Promise<{ html: string } | { error: string; code?: number }> => { const tmpDir = mkdtempSync(fsPath.join(osMod.tmpdir(), 'pptx-preview-')); try { const inputPath = fsPath.join(tmpDir, 'input.pptx'); writeFileSync(inputPath, binary); // officecli writes the rendered HTML to a temp file and prints the // path on stdout. Capture the path, then read the file content. const result = await runOfficeCli(['view', inputPath, 'html'], tmpDir); if (result.code !== 0) { return { error: (result.stderr || result.stdout).trim() || 'render failed', code: result.code }; } // Path may be on the last line; pick the line that looks like a path const lines = result.stdout.trim().split('\n'); const pathLine = lines.reverse().find((l) => l.trim().endsWith('.html')); if (!pathLine) { // Fallback: scan tmpDir for any .html file const found = readdirSync(tmpDir).find((f: string) => f.endsWith('.html')); if (!found) return { error: 'no html output produced' }; const html = readFileSync(fsPath.join(tmpDir, found), 'utf8'); return { html }; } const html = readFileSync(pathLine.trim(), 'utf8'); return { html }; } catch (e) { const err = e as Error; return { error: err.message || 'unknown error' }; } finally { try { rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best-effort */ } } }, }; })(); // 30s ceiling per render — guards against a malformed pptx hanging the // officecli process. Plenty for normal decks (sub-second to a few seconds). const PPTX_RENDER_TIMEOUT_MS = 30_000; router.get('/:fileName/preview-pptx-html', artifactReadRateLimit, maybeAgentRuntimeAuth, async (req: AuthReq, res: Res) => { try { const fileName = req.params?.fileName; if (!fileName) return res.status(400).json({ msg: 'fileName required' }); if (!/\.pptx$/i.test(String(fileName))) { return res.status(400).json({ msg: 'fileName must end in .pptx' }); } // Same pod-scoped authorization as the raw file fetch — a private deck // must not be renderable by anyone who knows its filename. if (!(await authorizePodFile(req, fileName))) { return res.status(403).json({ msg: 'Not authorized to read this file' }); } // Fetch the binary from object storage (or legacy MongoDB inline bytes). const store = getObjectStore(); const obj = await store.get(String(fileName)); let buffer: Buffer | null = null; if (obj) { const chunks: Buffer[] = []; const stream = obj.stream as unknown as NodeJS.ReadableStream; await new Promise((resolve, reject) => { stream.on('data', (c: Buffer) => chunks.push(c)); stream.on('end', () => resolve()); stream.on('error', reject); }); buffer = Buffer.concat(chunks); } else { const legacy = await File.findByFileName(fileName); if (legacy?.data?.length > 0) buffer = Buffer.from(legacy.data); } if (!buffer) return res.status(404).json({ msg: 'File not found' }); // Render with timeout const renderPromise = officecliPreview.renderPptx(buffer); const timeoutPromise = new Promise<{ error: string }>((resolve) => setTimeout(() => resolve({ error: 'render timeout' }), PPTX_RENDER_TIMEOUT_MS), ); const result = await Promise.race([renderPromise, timeoutPromise]); if ('error' in result) { console.warn('[uploads] PPTX preview render failed:', result.error); return res.status(500).json({ msg: 'Could not render preview', detail: result.error }); } res.set('Content-Type', 'text/html; charset=utf-8'); res.set('X-Content-Type-Options', 'nosniff'); res.set('Cache-Control', 'private, max-age=300'); return res.send(result.html); } catch (err) { const e = err as { message?: string }; console.error('PPTX preview error:', e.message); return res.status(500).json({ msg: 'Server Error' }); } }); // Exported so the agent-runtime upload route can reuse the shared helpers // without going through HTTP. The route file mounts `handleUpload` behind // agentRuntimeAuth and gates podId against the agent's authorized pods. export { handleUpload, uploadSingle }; module.exports = router; module.exports.handleUpload = handleUpload; module.exports.uploadSingle = uploadSingle;