import { nanoid } from 'nanoid' import type { Database } from 'bun:sqlite' import { error as logError, log } from '../logger' import { getDb } from '../db/sqlite' import { isSessionVisibleToUser } from './session' import { publishSessionEvent } from './transport' /** * Artifacts — self-hosted HTML pages uploaded by the CLI `artifact` tool or * created from the web UI gallery. * * Mirrors the upstream cloud-artifacts semantics: the `id` is an unguessable * nanoid that doubles as the share slug (URL-is-the-secret), passing `hash` * on upload overwrites in place (URL stays stable, version bumps), and TTL * bounds retention (7 or 30 days). */ export const ARTIFACT_ALLOWED_TTLS = [7, 30] as const export type ArtifactTtl = (typeof ARTIFACT_ALLOWED_TTLS)[number] export const ARTIFACT_MAX_BYTES = 10 * 1024 * 1024 /** Same charset contract as the upstream service. */ export const ARTIFACT_HASH_PATTERN = /^[A-Za-z0-9_-]{1,128}$/ export interface ArtifactRow { id: string session_id: string | null team_id: string | null title: string | null content_type: string content: string size: number version: number created_by: string | null created_at: string updated_at: string expires_at: string | null } export type ArtifactMeta = Omit export interface CreateArtifactParams { html: string /** Overwrite the artifact with this id (URL stays stable). */ hash?: string ttl?: ArtifactTtl sessionId?: string title?: string createdBy?: string contentType?: string } export interface CreateArtifactResult { id: string expiresAt: string created: boolean } function toMeta(row: ArtifactRow): ArtifactMeta { const { content: _content, ...meta } = row return meta } /** * Publish a lifecycle event to the owning session's bus so the RCS web UI * shows the artifacts badge immediately (agent uploads land asynchronously). * Meta-only payload — the HTML content never travels on the event bus. * Best-effort: notification must never break the create/update path. */ function notifyArtifactEvent( sessionId: string | null, action: 'created' | 'updated', meta: { id: string; title: string | null; version: number }, ): void { if (!sessionId) return try { publishSessionEvent( sessionId, `artifact_${action}`, { id: meta.id, title: meta.title, version: meta.version, url: `/v1/artifacts/${meta.id}/content`, }, 'outbound', ) } catch (err) { logError(`[artifacts] notify event failed id=${meta.id}:`, err) } } function nowIso(): string { return new Date().toISOString() } function isExpired(row: ArtifactRow): boolean { if (!row.expires_at) return false return new Date(row.expires_at).getTime() < Date.now() } /** Derive the owning team (if any) for a session — denormalized onto the * artifact so the team gallery query is a single index scan. */ function deriveTeamId( db: Database, sessionId: string | undefined, ): string | null { if (!sessionId) return null try { const row = db .query( `SELECT owner_id FROM session_owners WHERE session_id = $sid AND owner_type = 'team' LIMIT 1`, ) .get({ $sid: sessionId }) as { owner_id: string } | undefined return row?.owner_id ?? null } catch (err) { logError(`[artifacts] deriveTeamId failed session=${sessionId}:`, err) return null } } export function getArtifactRow(id: string): ArtifactRow | null { try { const row = getDb() .query('SELECT * FROM artifacts WHERE id = $id') .get({ $id: id }) as ArtifactRow | null if (!row) return null // Expired artifacts behave as deleted for every reader. return isExpired(row) ? null : row } catch (err) { logError(`[artifacts] getArtifactRow failed id=${id}:`, err) return null } } export function getArtifactContent(id: string): { content: string contentType: string } | null { const row = getArtifactRow(id) if (!row) return null return { content: row.content, contentType: row.content_type } } export function createArtifact( params: CreateArtifactParams, ): CreateArtifactResult { const db = getDb() const html = params.html const size = Buffer.byteLength(html, 'utf8') if (size > ARTIFACT_MAX_BYTES) { throw new ArtifactError( `payload_too_large`, `Artifact is ${size} bytes; limit is ${ARTIFACT_MAX_BYTES}.`, ) } const ttl = params.ttl ?? 7 if (!ARTIFACT_ALLOWED_TTLS.includes(ttl)) { throw new ArtifactError('invalid_ttl', `ttl must be 7 or 30 (got ${ttl}).`) } if (params.hash !== undefined && !ARTIFACT_HASH_PATTERN.test(params.hash)) { throw new ArtifactError( 'invalid_hash', 'hash must match ^[A-Za-z0-9_-]{1,128}$', ) } const expiresAt = new Date( Date.now() + ttl * 24 * 60 * 60 * 1000, ).toISOString() const now = nowIso() const sessionId = params.sessionId ?? null const teamId = deriveTeamId(db, sessionId ?? undefined) // Overwrite path — keep the URL stable, bump version, refresh TTL. if (params.hash) { const existing = db .query( 'SELECT id, session_id, version, title FROM artifacts WHERE id = $id', ) .get({ $id: params.hash }) as { id: string session_id: string | null version: number title: string | null } | null if (existing) { db.query( `UPDATE artifacts SET content = $content, size = $size, title = COALESCE($title, title), version = version + 1, updated_at = $now, expires_at = $expires, session_id = COALESCE($session_id, session_id), team_id = COALESCE($team_id, team_id) WHERE id = $id`, ).run({ $id: params.hash, $content: html, $size: size, $title: params.title ?? null, $now: now, $expires: expiresAt, $session_id: sessionId, $team_id: teamId, }) // Notify the session that ends up owning the row (new binding wins, // otherwise the original owner) — e.g. a CLI overwrite of an artifact // created from the web gallery still notifies the gallery session. notifyArtifactEvent(sessionId ?? existing.session_id, 'updated', { id: params.hash, title: params.title ?? existing.title, version: existing.version + 1, }) return { id: params.hash, expiresAt, created: false } } } const id = params.hash ?? nanoid(21) const title = params.title ?? null const createdBy = params.createdBy ?? null db.query( `INSERT INTO artifacts (id, session_id, team_id, title, content_type, content, size, version, created_by, created_at, updated_at, expires_at) VALUES ($id, $session_id, $team_id, $title, $content_type, $content, $size, 1, $created_by, $now, $now, $expires)`, ).run({ $id: id, $session_id: sessionId, $team_id: teamId, $title: title, $content_type: params.contentType ?? 'text/html; charset=utf-8', $content: html, $size: size, $created_by: createdBy, $now: now, $expires: expiresAt, }) notifyArtifactEvent(sessionId, 'created', { id, title, version: 1 }) return { id, expiresAt, created: true } } export function deleteArtifact(id: string): boolean { try { const result = getDb() .query('DELETE FROM artifacts WHERE id = $id') .run({ $id: id }) return (result as unknown as { changes?: number }).changes === 1 } catch (err) { logError(`[artifacts] deleteArtifact failed id=${id}:`, err) return false } } /** * Whether a user can see an artifact's metadata. Follows session visibility * (owner / team member / share grantee); session-less artifacts (web gallery * creations) are visible to their creator and to members of the owning team. */ export function isArtifactVisibleToUser( id: string, userId: string, isAdmin = false, ): boolean { const db = getDb() const row = getArtifactRow(id) if (!row) return false if (isAdmin) return true if (row.created_by === userId) return true if (row.session_id) { if (isSessionVisibleToUser(row.session_id, userId, db)) return true } if (row.team_id) { const member = db .query( 'SELECT 1 FROM team_members WHERE team_id = $teamId AND user_id = $userId LIMIT 1', ) .get({ $teamId: row.team_id, $userId: userId }) if (member) return true } return false } /** * Whether a user can delete/update an artifact: system admin, the artifact * creator, or a manager of the owning session/team. */ export function canManageArtifact( id: string, userId: string, isAdmin = false, ): boolean { const db = getDb() const row = getArtifactRow(id) if (!row) return false if (isAdmin) return true if (row.created_by === userId) return true if (row.session_id) { // Reuse session management rules (direct owner / team owner+admin / admin). const userRole = db .query('SELECT role FROM users WHERE id = $userId') .get({ $userId: userId }) as { role: string } | null if (userRole?.role === 'admin') return true const directOwner = db .query( `SELECT 1 FROM session_owners WHERE session_id = $sid AND owner_type = 'user' AND owner_id = $uid LIMIT 1`, ) .get({ $sid: row.session_id, $uid: userId }) if (directOwner) return true const teamManager = db .query( `SELECT 1 FROM session_owners so JOIN team_members tm ON tm.team_id = so.owner_id WHERE so.session_id = $sid AND so.owner_type = 'team' AND tm.user_id = $uid AND tm.role IN ('owner', 'admin') LIMIT 1`, ) .get({ $sid: row.session_id, $uid: userId }) if (teamManager) return true } if (row.team_id) { const teamManager = db .query( `SELECT 1 FROM team_members WHERE team_id = $teamId AND user_id = $userId AND role IN ('owner', 'admin') LIMIT 1`, ) .get({ $teamId: row.team_id, $userId: userId }) if (teamManager) return true } return false } export interface ListArtifactsFilter { sessionId?: string teamId?: string /** Personal-space scope — exclude team-domain artifacts (team_id IS NULL). * Mirrors the web UI's global team context (SessionList semantics): * personal space vs. a specific team. Mutually exclusive with teamId. */ personalScope?: boolean } /** * List artifact metadata visible to a user. When `sessionId` is given the * caller must already have passed the session-visibility check (route-level); * otherwise rows are filtered per-row via isArtifactVisibleToUser. */ export function listArtifactsForUser( userId: string, filter: ListArtifactsFilter = {}, isAdmin = false, ): ArtifactMeta[] { const db = getDb() const conditions: string[] = [`(expires_at IS NULL OR expires_at > $now)`] const params: Record = { $now: nowIso() } if (filter.sessionId) { conditions.push('session_id = $sessionId') params.$sessionId = filter.sessionId } if (filter.teamId) { conditions.push('team_id = $teamId') params.$teamId = filter.teamId } else if (filter.personalScope) { conditions.push('team_id IS NULL') } let rows: ArtifactRow[] = [] try { rows = db .query( `SELECT * FROM artifacts WHERE ${conditions.join(' AND ')} ORDER BY updated_at DESC LIMIT 500`, ) .all(params) as unknown as ArtifactRow[] } catch (err) { logError('[artifacts] listArtifactsForUser failed:', err) return [] } if (isAdmin) return rows.map(toMeta) return rows .filter(row => isArtifactVisibleToUser(row.id, userId, false)) .map(toMeta) } /** Delete all artifacts past their expires_at. Returns the removed count. */ export function cleanupExpiredArtifacts(): number { try { const result = getDb() .query( 'DELETE FROM artifacts WHERE expires_at IS NOT NULL AND expires_at <= $now', ) .run({ $now: nowIso() }) const removed = (result as unknown as { changes?: number }).changes ?? 0 if (removed > 0) log(`[artifacts] cleaned up ${removed} expired artifacts`) return removed } catch (err) { logError('[artifacts] cleanupExpiredArtifacts failed:', err) return 0 } } /** Typed error carrying an upstream-compatible code. */ export class ArtifactError extends Error { code: string constructor(code: string, message: string) { super(message) this.name = 'ArtifactError' this.code = code } }