import { Hono } from 'hono' import { getDb } from '../../db/sqlite' import { sessionAuth } from '../../auth/middleware' import { SYSTEM_USER_ID } from '../../auth/constants' import { isSessionVisibleToUser } from '../../services/session' import { ArtifactError, ARTIFACT_ALLOWED_TTLS, ARTIFACT_HASH_PATTERN, canManageArtifact, createArtifact, deleteArtifact, getArtifactRow, isArtifactVisibleToUser, listArtifactsForUser, type ArtifactTtl, } from '../../services/artifacts' const app = new Hono() /** * Web-UI artifact routes (mounted under /web with CSRF protection). * * - GET /web/artifacts — artifacts visible to the caller * (optionally filtered by ?session_id= / ?team_id=) * - POST /web/artifacts — create from the gallery editor; with `hash` * (existing artifact id) performs an * in-place overwrite (URL stable, version * bumps, TTL resets) gated on manage * permission — 404 if missing/expired, 403 * if not manageable, 403 if not visible. * - GET /web/artifacts/:id — metadata + content + can_manage * (visibility-checked; edit affordances) * - DELETE /web/artifacts/:id — remove (creator / session owner / team admin) */ /** Team membership check reused for ?team_id= filtering. */ function isTeamMember( userId: string, teamId: string, db: ReturnType, ): boolean { const row = db .query( 'SELECT 1 FROM team_members WHERE team_id = $teamId AND user_id = $userId', ) .get({ $teamId: teamId, $userId: userId }) return !!row } type ArtifactResponseRow = { id: string session_id: string | null team_id: string | null title: string | null content_type: string size: number version: number created_by: string | null created_at: string updated_at: string expires_at: string | null } function toResponse(row: ArtifactResponseRow) { return { id: row.id, session_id: row.session_id, team_id: row.team_id, title: row.title, content_type: row.content_type, size: row.size, version: row.version, created_by: row.created_by, created_at: row.created_at, updated_at: row.updated_at, expires_at: row.expires_at, url: `/v1/artifacts/${row.id}/content`, } } app.get('/artifacts', sessionAuth, async c => { const userId = c.get('userId') as string const isAdmin = (c.get('isAdmin') as boolean) || userId === SYSTEM_USER_ID const db = getDb() const sessionId = c.req.query('session_id') const teamId = c.req.query('team_id') // Personal-space scope — mirrors the web UI's global team context: the // gallery in "personal" mode shows artifacts outside every team domain // (own gallery creations + artifacts from one's own sessions), the same // SessionList semantics as switching TeamSwitcher to personal. const personalScope = c.req.query('scope') === 'personal' if (personalScope && teamId) { return c.json( { error: { type: 'bad_request', message: 'scope=personal cannot be combined with team_id', }, }, 400, ) } // Explicit filters narrow the result set but must not leak cross-team rows. if (sessionId) { if (!isAdmin && !isSessionVisibleToUser(sessionId, userId, db)) { return c.json( { error: { type: 'forbidden', message: 'Not authorized for this session', }, }, 403, ) } } if (teamId) { if (!isAdmin && !isTeamMember(userId, teamId, db)) { return c.json( { error: { type: 'forbidden', message: 'Not a member of this team' } }, 403, ) } } const rows = listArtifactsForUser( userId, { sessionId, teamId, personalScope }, isAdmin, ) return c.json( rows.map(row => ({ ...toResponse(row), can_manage: isAdmin || canManageArtifact(row.id, userId, isAdmin), })), 200, ) }) app.get('/artifacts/:id', sessionAuth, async c => { const userId = c.get('userId') as string const isAdmin = (c.get('isAdmin') as boolean) || userId === SYSTEM_USER_ID const id = c.req.param('id')! const row = getArtifactRow(id) if (!row) { return c.json( { error: { type: 'not_found', message: 'Artifact not found' } }, 404, ) } if (!isArtifactVisibleToUser(id, userId, isAdmin)) { return c.json( { error: { type: 'forbidden', message: 'Not authorized for this artifact', }, }, 403, ) } // Single-artifact fetch carries the content (for the web editor) and the // manage bit (for edit affordances) — list responses stay meta-only. return c.json( { ...toResponse(row), content: row.content, can_manage: canManageArtifact(id, userId, isAdmin), }, 200, ) }) app.post('/artifacts', sessionAuth, async c => { const userId = c.get('userId') as string const isAdmin = (c.get('isAdmin') as boolean) || userId === SYSTEM_USER_ID let body: Record try { body = await c.req.json() } catch { return c.json( { error: { type: 'bad_request', message: 'Invalid JSON' } }, 400, ) } const html = typeof body.html === 'string' ? body.html : '' if (!html.trim()) { return c.json( { error: { type: 'bad_request', message: 'html is required' } }, 400, ) } const title = typeof body.title === 'string' && body.title.trim() ? body.title.trim() : undefined let ttl: ArtifactTtl | undefined if (body.ttl !== undefined) { const n = typeof body.ttl === 'number' ? body.ttl : Number.parseInt(String(body.ttl), 10) if (!ARTIFACT_ALLOWED_TTLS.includes(n as ArtifactTtl)) { return c.json( { error: { type: 'bad_request', message: 'ttl must be 7 or 30' } }, 400, ) } ttl = n as ArtifactTtl } // Optional session binding — caller must be able to see the session. let sessionId: string | undefined if (typeof body.session_id === 'string' && body.session_id) { const db = getDb() if (!isSessionVisibleToUser(body.session_id, userId, db)) { return c.json( { error: { type: 'forbidden', message: 'Not authorized for this session', }, }, 403, ) } sessionId = body.session_id } // Optional overwrite — hash targets an EXISTING artifact. Unlike the v1 // worker route (which may create-with-chosen-id), web callers can only // update artifacts they manage: 400 (bad format) / 404 (missing or // expired) / 403 (no manage permission). const hash = typeof body.hash === 'string' ? body.hash : undefined if (hash) { if (!ARTIFACT_HASH_PATTERN.test(hash)) { return c.json( { error: { type: 'bad_request', message: 'invalid hash format' } }, 400, ) } if (!getArtifactRow(hash)) { return c.json( { error: { type: 'not_found', message: 'Artifact not found' } }, 404, ) } if (!canManageArtifact(hash, userId, isAdmin)) { return c.json( { error: { type: 'forbidden', message: 'Not authorized to update this artifact', }, }, 403, ) } } try { const result = createArtifact({ html, hash, ttl, sessionId, title, createdBy: userId, }) const row = getArtifactRow(result.id) return c.json( row ? toResponse(row) : { id: result.id, expires_at: result.expiresAt }, result.created ? 201 : 200, ) } catch (err) { if (err instanceof ArtifactError) { const status = err.code === 'payload_too_large' ? 413 : 400 return c.json({ error: { type: err.code, message: err.message } }, status) } throw err } }) app.delete('/artifacts/:id', sessionAuth, async c => { const userId = c.get('userId') as string const isAdmin = (c.get('isAdmin') as boolean) || userId === SYSTEM_USER_ID const id = c.req.param('id')! if (!getArtifactRow(id)) { return c.json( { error: { type: 'not_found', message: 'Artifact not found' } }, 404, ) } if (!canManageArtifact(id, userId, isAdmin)) { return c.json( { error: { type: 'forbidden', message: 'Not authorized to delete this artifact', }, }, 403, ) } deleteArtifact(id) return c.json({ ok: true }, 200) }) export default app