import { Hono } from 'hono' import type { Context, Next } from 'hono' import { log } from '../../logger' import { config, getBaseUrl } from '../../config' import { validateApiKey } from '../../auth/api-key' import { verifyWorkerJwt } from '../../auth/jwt' import { extractBearerToken, sessionAuth } from '../../auth/middleware' import { resolveExistingSessionId } from '../../services/session' import { ArtifactError, ARTIFACT_ALLOWED_TTLS, ARTIFACT_MAX_BYTES, createArtifact, getArtifactContent, type ArtifactTtl, } from '../../services/artifacts' const app = new Hono() /** * CLI/worker artifact upload + public content read. * * Mirrors the upstream cloud-artifacts worker contract: * - POST /v1/artifacts (API key or worker JWT auth) — body {html, hash?, ttl?, * session_id?, title?} → {id, url, expiresAt}. Passing `hash` overwrites * the artifact in place (URL stays stable). * - GET /v1/artifacts/:id/content — serves the stored HTML document. Access * is URL-is-the-secret (the id is an unguessable nanoid), same trust model * as the upstream service. Set RCS_ARTIFACTS_PUBLIC_ACCESS=false to require * auth on content reads as well. */ function artifactUrl(id: string): string { return `${getBaseUrl()}/v1/artifacts/${id}/content` } /** API key or worker JWT — same credential surface as session ingress. */ function authenticateWorker(c: Context): boolean { const token = extractBearerToken(c) if (!token) return false if (validateApiKey(token)) return true return verifyWorkerJwt(token) !== null } /** * Content-read auth. Default (artifactsPublicAccess=true): open — the * unguessable id IS the secret, matching the upstream cloud-artifacts trust * model. Operators can set RCS_ARTIFACTS_PUBLIC_ACCESS=false to require a * web session (cookie/bearer) or worker credential instead. */ async function contentAuth(c: Context, next: Next) { if (config.artifactsPublicAccess === false) { if (authenticateWorker(c)) { await next() return } return sessionAuth(c, next) } await next() } app.post('/artifacts', async c => { if (!authenticateWorker(c)) { return c.json( { error: { type: 'unauthorized', message: 'Invalid auth token' } }, 401, ) } let body: Record try { body = await c.req.json() } catch { return c.json( { error: { type: 'bad_request', message: 'Invalid JSON body' } }, 400, ) } const html = typeof body.html === 'string' ? body.html : undefined if (!html || html.length === 0) { return c.json( { error: { type: 'bad_request', message: 'html is required' } }, 400, ) } const hash = typeof body.hash === 'string' ? body.hash : undefined const ttlRaw = body.ttl let ttl: ArtifactTtl | undefined if (ttlRaw !== undefined) { const n = typeof ttlRaw === 'number' ? ttlRaw : Number.parseInt(String(ttlRaw), 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 } const title = typeof body.title === 'string' ? body.title : undefined // Session association is best-effort: unknown session ids (local REPL runs, // SDK mode) simply leave the artifact session-less. let sessionId: string | undefined const requestedSessionId = typeof body.session_id === 'string' ? body.session_id : undefined if (requestedSessionId) { sessionId = resolveExistingSessionId(requestedSessionId) ?? undefined if (!sessionId) { log( `[artifacts] upload referenced unknown session ${requestedSessionId} — storing session-less`, ) } } try { const result = createArtifact({ html, hash, ttl, sessionId, title, }) return c.json( { id: result.id, url: artifactUrl(result.id), expiresAt: result.expiresAt, }, 201, ) } catch (err) { if (err instanceof ArtifactError) { const status = err.code === 'payload_too_large' ? 413 : err.code === 'invalid_ttl' || err.code === 'invalid_hash' ? 400 : 500 return c.json({ error: { type: err.code, message: err.message } }, status) } throw err } }) /** Content read — URL-is-the-secret by default; session-auth-gated when public access is disabled. */ app.get('/artifacts/:id/content', contentAuth, async c => { const id = c.req.param('id')! const artifact = getArtifactContent(id) if (!artifact) { return c.notFound() } return c.body(artifact.content, 200, { 'content-type': artifact.contentType, 'cache-control': 'public, max-age=60', 'x-content-type-options': 'nosniff', }) }) /** Head variant so embedders can probe existence cheaply. */ app.on('HEAD', '/artifacts/:id/content', contentAuth, async c => { const id = c.req.param('id')! const artifact = getArtifactContent(id) if (!artifact) return c.notFound() return c.body(null, 200, { 'content-type': artifact.contentType, 'cache-control': 'public, max-age=60', }) }) // Cap documented alongside the service — kept here so route-level callers // (tests) can assert against the same constant. export { ARTIFACT_MAX_BYTES } export default app