import { describe, test, expect, beforeEach, mock } from 'bun:test'
import { mockConfigModule } from './helpers/mock-config'
// Mock config (apiKeys: ['test-api-key'])
mock.module('../config', () => mockConfigModule({}))
import { Hono } from 'hono'
import v1Artifacts from '../routes/v1/artifacts'
import webArtifacts from '../routes/web/artifacts'
import { getDb } from '../db/sqlite'
import { freshDb } from './helpers/db'
import { createUserDirectly, type TestUser } from './helpers/fixtures'
import { storeCreateSession, storeBindSession, storeReset } from '../store'
import { issueSessionToken } from '../auth/session'
import { getEventBus } from '../transport/event-bus'
import {
createArtifact,
getArtifactContent,
getArtifactRow,
deleteArtifact,
isArtifactVisibleToUser,
canManageArtifact,
listArtifactsForUser,
cleanupExpiredArtifacts,
ArtifactError,
} from '../services/artifacts'
// Fresh DB per file so schema additions (artifacts table) are guaranteed.
freshDb()
function createApp() {
const app = new Hono()
app.route('/v1', v1Artifacts)
app.route('/web', webArtifacts)
return app
}
const AUTH_HEADERS = {
Authorization: 'Bearer test-api-key',
}
/** SQLite-backed session token (production login path) — userId = users.id. */
function issueBearer(userId: string): string {
return `Bearer ${issueSessionToken(userId, getDb()).accessToken}`
}
describe('artifacts service', () => {
beforeEach(() => {
const db = getDb()
db.query('DELETE FROM artifacts').run()
})
test('createArtifact returns id and stores content', () => {
const result = createArtifact({ html: '
hello
', ttl: 7 })
expect(result.id).toHaveLength(21)
expect(result.created).toBe(true)
const content = getArtifactContent(result.id)
expect(content?.content).toBe('hello
')
expect(content?.contentType).toBe('text/html; charset=utf-8')
})
test('hash overwrite keeps id stable and bumps version', () => {
const first = createArtifact({ html: 'v1', ttl: 7 })
const second = createArtifact({ html: 'v2', hash: first.id, ttl: 7 })
expect(second.id).toBe(first.id)
expect(second.created).toBe(false)
const row = getArtifactRow(first.id)
expect(row?.version).toBe(2)
expect(row?.content).toBe('v2')
})
test('rejects invalid ttl and hash', () => {
expect(() => createArtifact({ html: 'x', ttl: 14 as 7 })).toThrow(
ArtifactError,
)
expect(() => createArtifact({ html: 'x', hash: 'bad hash!' })).toThrow(
ArtifactError,
)
})
test('rejects payload over 10MB', () => {
const big = 'a'.repeat(10 * 1024 * 1024 + 1)
let caught: ArtifactError | null = null
try {
createArtifact({ html: big })
} catch (err) {
caught = err as ArtifactError
}
expect(caught?.code).toBe('payload_too_large')
})
test('expired artifacts read as missing and are reaped', () => {
const result = createArtifact({ html: 'temp', ttl: 7 })
const db = getDb()
// Backdate expiry
db.query('UPDATE artifacts SET expires_at = $e WHERE id = $id').run({
$e: '2000-01-01T00:00:00.000Z',
$id: result.id,
})
expect(getArtifactContent(result.id)).toBeNull()
expect(getArtifactRow(result.id)).toBeNull()
const removed = cleanupExpiredArtifacts()
expect(removed).toBeGreaterThanOrEqual(1)
})
test('deleteArtifact removes the row', () => {
const result = createArtifact({ html: 'x' })
expect(deleteArtifact(result.id)).toBe(true)
expect(deleteArtifact(result.id)).toBe(false)
expect(getArtifactRow(result.id)).toBeNull()
})
test('visibility follows session ownership', () => {
const db = getDb()
const owner = createUserDirectly(db, { username: 'art-owner-1' })
const stranger = createUserDirectly(db, { username: 'art-stranger-1' })
const session = storeCreateSession({ title: 'art test' })
storeBindSession(session.id, owner.id)
const result = createArtifact({
html: 'x',
sessionId: session.id,
})
// team_id denormalized from session_owners — session owned by user, so null
const row = getArtifactRow(result.id)
expect(row?.session_id).toBe(session.id)
expect(isArtifactVisibleToUser(result.id, owner.id)).toBe(true)
expect(isArtifactVisibleToUser(result.id, stranger.id)).toBe(false)
expect(isArtifactVisibleToUser(result.id, owner.id, true)).toBe(true)
expect(canManageArtifact(result.id, owner.id)).toBe(true)
expect(canManageArtifact(result.id, stranger.id)).toBe(false)
})
test('listArtifactsForUser filters by visibility', () => {
const db = getDb()
const owner = createUserDirectly(db, { username: 'art-owner-2' })
const stranger = createUserDirectly(db, { username: 'art-stranger-2' })
const session = storeCreateSession({ title: 'list test' })
storeBindSession(session.id, owner.id)
createArtifact({ html: 'a', sessionId: session.id })
createArtifact({ html: 'b', createdBy: stranger.id })
const ownerList = listArtifactsForUser(owner.id)
// owner sees session artifact + stranger's session-less artifact is NOT visible
expect(ownerList.length).toBe(1)
const strangerList = listArtifactsForUser(stranger.id)
expect(strangerList.length).toBe(1)
expect(strangerList[0].created_by).toBe(stranger.id)
// Admin sees everything
const adminList = listArtifactsForUser(owner.id, {}, true)
expect(adminList.length).toBe(2)
})
test('createArtifact with session publishes artifact_created on the bus', () => {
const session = storeCreateSession({ title: 'events create' })
storeBindSession(session.id, 'art-ev-user-1')
const bus = getEventBus(session.id)
const received: Array<{
type: string
payload: Record
}> = []
const unsub = bus.subscribe(e =>
received.push({
type: e.type,
payload: e.payload as Record,
}),
)
const result = createArtifact({
html: 'secret content
',
sessionId: session.id,
title: 'Bus Event',
})
unsub()
expect(received.length).toBe(1)
expect(received[0].type).toBe('artifact_created')
expect(received[0].payload.id).toBe(result.id)
expect(received[0].payload.title).toBe('Bus Event')
expect(received[0].payload.version).toBe(1)
expect(received[0].payload.url).toBe(`/v1/artifacts/${result.id}/content`)
// Meta-only: the HTML content must never travel on the event bus.
expect(JSON.stringify(received[0].payload)).not.toContain('secret content')
// Mirrored durably — survives server restart for SSE history replay.
const persisted = getDb()
.query(
"SELECT type FROM session_events WHERE session_id = $sid AND type = 'artifact_created'",
)
.all({ $sid: session.id })
expect(persisted.length).toBe(1)
})
test('hash overwrite publishes artifact_updated with bumped version', () => {
const session = storeCreateSession({ title: 'events update' })
storeBindSession(session.id, 'art-ev-user-2')
const first = createArtifact({
html: 'v1',
sessionId: session.id,
title: 'Original',
})
const bus = getEventBus(session.id)
const received: Array<{ type: string; payload: Record }> =
[]
const unsub = bus.subscribe(e =>
received.push({
type: e.type,
payload: e.payload as Record,
}),
)
createArtifact({ html: 'v2', hash: first.id, ttl: 7, title: 'Renamed' })
unsub()
expect(received.length).toBe(1)
expect(received[0].type).toBe('artifact_updated')
expect(received[0].payload.version).toBe(2)
expect(received[0].payload.title).toBe('Renamed')
})
test('overwrite without sessionId notifies the original owning session', () => {
const session = storeCreateSession({ title: 'events owner' })
storeBindSession(session.id, 'art-ev-user-3')
const first = createArtifact({ html: 'v1', sessionId: session.id })
const bus = getEventBus(session.id)
const received: Array<{ type: string }> = []
const unsub = bus.subscribe(e => received.push({ type: e.type }))
// No sessionId on the overwrite — the stored session_id wins.
createArtifact({ html: 'v2', hash: first.id, ttl: 7 })
unsub()
expect(received.length).toBe(1)
expect(received[0].type).toBe('artifact_updated')
})
test('session-less artifacts publish no events', () => {
// No session to notify — the create path must be silent, not throw.
const result = createArtifact({ html: 'x' })
expect(result.created).toBe(true)
})
})
describe('artifacts routes', () => {
let app: ReturnType
let user: TestUser
let stranger: TestUser
beforeEach(() => {
app = createApp()
storeReset()
const db = getDb()
db.query('DELETE FROM artifacts').run()
user = createUserDirectly(db, { username: 'art-webuser' })
stranger = createUserDirectly(db, { username: 'art-webstranger' })
})
test('POST /v1/artifacts requires worker auth', async () => {
const res = await app.request('/v1/artifacts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ html: 'x
' }),
})
expect(res.status).toBe(401)
})
test('POST /v1/artifacts creates and returns URL', async () => {
const res = await app.request('/v1/artifacts', {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ html: 'hello
', ttl: 7, title: 'Test' }),
})
expect(res.status).toBe(201)
const data = (await res.json()) as {
id: string
url: string
expiresAt: string
}
expect(data.id).toHaveLength(21)
expect(data.url).toBe(
`http://localhost:3000/v1/artifacts/${data.id}/content`,
)
expect(data.expiresAt).toBeTruthy()
// Content is served publicly (URL-is-the-secret)
const contentRes = await app.request(`/v1/artifacts/${data.id}/content`)
expect(contentRes.status).toBe(200)
expect(await contentRes.text()).toBe('hello
')
expect(contentRes.headers.get('content-type')).toContain('text/html')
})
test('POST /v1/artifacts overwrite via hash keeps URL stable', async () => {
const create = await app.request('/v1/artifacts', {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ html: 'first' }),
})
const first = (await create.json()) as { id: string; url: string }
const overwrite = await app.request('/v1/artifacts', {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ html: 'second', hash: first.id }),
})
expect(overwrite.status).toBe(201)
const second = (await overwrite.json()) as { id: string; url: string }
expect(second.id).toBe(first.id)
expect(second.url).toBe(first.url)
const content = await app.request(`/v1/artifacts/${first.id}/content`)
expect(await content.text()).toBe('second')
})
test('POST /v1/artifacts validates body', async () => {
const noHtml = await app.request('/v1/artifacts', {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ ttl: 7 }),
})
expect(noHtml.status).toBe(400)
const badTtl = await app.request('/v1/artifacts', {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ html: 'x', ttl: 14 }),
})
expect(badTtl.status).toBe(400)
})
test('GET /v1/artifacts/:id/content 404s for unknown id', async () => {
const res = await app.request('/v1/artifacts/nonexistent/content')
expect(res.status).toBe(404)
})
test('unknown session_id stored session-less', async () => {
const res = await app.request('/v1/artifacts', {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ html: 'x', session_id: 'session_unknown' }),
})
expect(res.status).toBe(201)
const data = (await res.json()) as { id: string }
const row = getArtifactRow(data.id)
expect(row?.session_id).toBeNull()
})
test('v1 upload with session_id is visible to the session owner in the web gallery', async () => {
// The CLI artifact tool's contract (spawn-mode children send their
// --session-id argv value): a worker-authenticated upload attributed to
// a session must appear for that session's owner — in the session view
// AND the owner's default gallery scope. Without session attribution the
// row is creator-less and invisible to everyone except admins.
const session = storeCreateSession({ title: 'ai gen session' })
storeBindSession(session.id, user.id)
const res = await app.request('/v1/artifacts', {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({
html: 'dashboard
',
session_id: session.id,
title: 'AI Dashboard',
}),
})
expect(res.status).toBe(201)
const data = (await res.json()) as { id: string }
// Session-filtered gallery (embedded panel in session detail).
const sessionList = await app.request(
`/web/artifacts?session_id=${session.id}`,
{ headers: { Authorization: issueBearer(user.id) } },
)
expect(sessionList.status).toBe(200)
const sessionRows = (await sessionList.json()) as Array<{ id: string }>
expect(sessionRows.map(r => r.id)).toContain(data.id)
// Owner's default gallery scope (standalone gallery, no team context).
const defaultList = await app.request('/web/artifacts', {
headers: { Authorization: issueBearer(user.id) },
})
const defaultRows = (await defaultList.json()) as Array<{ id: string }>
expect(defaultRows.map(r => r.id)).toContain(data.id)
// Strangers still see nothing (session is private to the owner).
const strangerList = await app.request('/web/artifacts', {
headers: { Authorization: issueBearer(stranger.id) },
})
const strangerRows = (await strangerList.json()) as Array<{ id: string }>
expect(strangerRows.map(r => r.id)).not.toContain(data.id)
})
test('GET /web/artifacts requires auth', async () => {
const res = await app.request('/web/artifacts')
expect(res.status).toBe(401)
})
test('GET /web/artifacts lists own artifacts', async () => {
createArtifact({ html: 'mine', createdBy: user.id, title: 'Mine' })
const res = await app.request('/web/artifacts', {
headers: { Authorization: issueBearer(user.id) },
})
expect(res.status).toBe(200)
const list = (await res.json()) as Array>
expect(list.length).toBe(1)
expect(list[0].title).toBe('Mine')
expect(list[0].url).toMatch(/^\/v1\/artifacts\/.+\/content$/)
})
test('POST /web/artifacts creates with session attribution', async () => {
const session = storeCreateSession({ title: 'web create' })
storeBindSession(session.id, user.id)
const res = await app.request('/web/artifacts', {
method: 'POST',
headers: {
Authorization: issueBearer(user.id),
'Content-Type': 'application/json',
},
body: JSON.stringify({
html: 'Web created
',
title: 'From Web',
ttl: 30,
session_id: session.id,
}),
})
expect(res.status).toBe(201)
const artifact = (await res.json()) as { id: string; session_id: string }
expect(artifact.session_id).toBe(session.id)
const content = await app.request(`/v1/artifacts/${artifact.id}/content`)
expect(await content.text()).toBe('Web created
')
})
test('POST /web/artifacts rejects binding to invisible session', async () => {
const session = storeCreateSession({ title: 'private' })
storeBindSession(session.id, user.id)
const res = await app.request('/web/artifacts', {
method: 'POST',
headers: {
Authorization: issueBearer(stranger.id),
'Content-Type': 'application/json',
},
body: JSON.stringify({
html: 'x',
session_id: session.id,
}),
})
expect(res.status).toBe(403)
})
test('DELETE /web/artifacts/:id enforces manage permission', async () => {
const created = createArtifact({ html: 'x', createdBy: user.id })
// Stranger cannot delete
const denied = await app.request(`/web/artifacts/${created.id}`, {
method: 'DELETE',
headers: { Authorization: issueBearer(stranger.id) },
})
expect(denied.status).toBe(403)
// Creator can delete
const ok = await app.request(`/web/artifacts/${created.id}`, {
method: 'DELETE',
headers: { Authorization: issueBearer(user.id) },
})
expect(ok.status).toBe(200)
expect(getArtifactRow(created.id)).toBeNull()
})
test('GET /web/artifacts/:id enforces visibility', async () => {
const created = createArtifact({ html: 'x', createdBy: user.id })
const ok = await app.request(`/web/artifacts/${created.id}`, {
headers: { Authorization: issueBearer(user.id) },
})
expect(ok.status).toBe(200)
const denied = await app.request(`/web/artifacts/${created.id}`, {
headers: { Authorization: issueBearer(stranger.id) },
})
expect(denied.status).toBe(403)
})
test('session_id filter cross-team leak protection', async () => {
const session = storeCreateSession({ title: 'owned' })
storeBindSession(session.id, user.id)
const res = await app.request(`/web/artifacts?session_id=${session.id}`, {
headers: { Authorization: issueBearer(stranger.id) },
})
expect(res.status).toBe(403)
})
test('GET /web/artifacts/:id returns content and can_manage', async () => {
const created = createArtifact({
html: 'editable
',
createdBy: user.id,
})
const res = await app.request(`/web/artifacts/${created.id}`, {
headers: { Authorization: issueBearer(user.id) },
})
expect(res.status).toBe(200)
const data = (await res.json()) as { content: string; can_manage: boolean }
expect(data.content).toBe('editable
')
expect(data.can_manage).toBe(true)
})
test('GET /web/artifacts list rows carry can_manage', async () => {
createArtifact({ html: 'x', createdBy: user.id })
const res = await app.request('/web/artifacts', {
headers: { Authorization: issueBearer(user.id) },
})
const list = (await res.json()) as Array<{
id: string
can_manage: boolean
}>
expect(list.length).toBe(1)
expect(list[0].can_manage).toBe(true)
})
test('POST /web/artifacts with hash overwrites for the manager (200)', async () => {
const created = createArtifact({
html: 'v1',
createdBy: user.id,
title: 'Old',
})
const res = await app.request('/web/artifacts', {
method: 'POST',
headers: {
Authorization: issueBearer(user.id),
'Content-Type': 'application/json',
},
body: JSON.stringify({
html: 'v2-web',
hash: created.id,
ttl: 30,
title: 'New',
}),
})
expect(res.status).toBe(200)
const data = (await res.json()) as {
id: string
version: number
title: string
}
expect(data.id).toBe(created.id)
expect(data.version).toBe(2)
expect(data.title).toBe('New')
const row = getArtifactRow(created.id)
expect(row?.content).toBe('v2-web')
})
test('POST /web/artifacts with hash: 404 missing, 403 not manager, 400 bad format', async () => {
// Missing (or expired) — not 403, the caller can't even see it.
const missing = await app.request('/web/artifacts', {
method: 'POST',
headers: {
Authorization: issueBearer(user.id),
'Content-Type': 'application/json',
},
body: JSON.stringify({ html: 'x', hash: 'nonexistent-id' }),
})
expect(missing.status).toBe(404)
// Exists but owned by someone else.
const created = createArtifact({ html: 'x', createdBy: user.id })
const denied = await app.request('/web/artifacts', {
method: 'POST',
headers: {
Authorization: issueBearer(stranger.id),
'Content-Type': 'application/json',
},
body: JSON.stringify({ html: 'x', hash: created.id }),
})
expect(denied.status).toBe(403)
// Row untouched.
expect(getArtifactRow(created.id)?.content).toBe('x')
// Malformed hash format.
const badFormat = await app.request('/web/artifacts', {
method: 'POST',
headers: {
Authorization: issueBearer(user.id),
'Content-Type': 'application/json',
},
body: JSON.stringify({ html: 'x', hash: 'bad hash!' }),
})
expect(badFormat.status).toBe(400)
})
test('POST /web/artifacts hash on expired artifact returns 404', async () => {
const created = createArtifact({ html: 'x', createdBy: user.id })
getDb()
.query('UPDATE artifacts SET expires_at = $e WHERE id = $id')
.run({ $e: '2000-01-01T00:00:00.000Z', $id: created.id })
const res = await app.request('/web/artifacts', {
method: 'POST',
headers: {
Authorization: issueBearer(user.id),
'Content-Type': 'application/json',
},
body: JSON.stringify({ html: 'resurrect', hash: created.id }),
})
expect(res.status).toBe(404)
})
/** Seed a team + a session owned by it (mirrors the transfer route's
* session_owners shape) so deriveTeamId stamps artifacts into the team
* domain. */
function seedTeamSession(db: ReturnType, teamId: string) {
db.query(
`INSERT INTO teams (id, name, slug, created_by, created_at, updated_at)
VALUES ($id, $name, $slug, $by, $now, $now)`,
).run({
$id: teamId,
$name: 'Art Filter Team',
$slug: 'art-filter-team',
$by: user.id,
$now: new Date().toISOString(),
})
db.query(
`INSERT INTO team_members (team_id, user_id, role, added_at, added_by)
VALUES ($teamId, $userId, 'owner', $now, $userId)`,
).run({
$teamId: teamId,
$userId: user.id,
$now: new Date().toISOString(),
})
const session = storeCreateSession({ title: 'team session' })
db.query(
`INSERT INTO session_owners (session_id, owner_type, owner_id)
VALUES ($sid, 'team', $teamId)`,
).run({ $sid: session.id, $teamId: teamId })
return session
}
test('GET /web/artifacts scope=personal excludes team-domain artifacts', async () => {
const db = getDb()
const teamSession = seedTeamSession(db, 'team_artfilter1')
// Personal-space artifacts: own gallery creation + own session upload.
createArtifact({ html: 'gallery-mine', createdBy: user.id, title: 'G' })
const personalSession = storeCreateSession({ title: 'personal session' })
storeBindSession(personalSession.id, user.id)
createArtifact({ html: 'personal-session', sessionId: personalSession.id })
// Team-domain artifact (team_id derived from the session's team owner).
const teamArtifact = createArtifact({
html: 'team-art',
sessionId: teamSession.id,
})
expect(getArtifactRow(teamArtifact.id)?.team_id).toBe('team_artfilter1')
const res = await app.request('/web/artifacts?scope=personal', {
headers: { Authorization: issueBearer(user.id) },
})
expect(res.status).toBe(200)
const list = (await res.json()) as Array<{ id: string }>
const ids = list.map(a => a.id)
expect(ids).not.toContain(teamArtifact.id)
expect(ids.length).toBe(2)
// No filter (legacy default) still returns everything visible.
const all = await app.request('/web/artifacts', {
headers: { Authorization: issueBearer(user.id) },
})
const allList = (await all.json()) as Array<{ id: string }>
expect(allList.map(a => a.id)).toContain(teamArtifact.id)
expect(allList.length).toBe(3)
})
test('GET /web/artifacts team filter returns the team domain', async () => {
const db = getDb()
const teamSession = seedTeamSession(db, 'team_artfilter2')
const teamArtifact = createArtifact({
html: 'team-art',
sessionId: teamSession.id,
})
createArtifact({ html: 'gallery-mine', createdBy: user.id })
const res = await app.request(`/web/artifacts?team_id=team_artfilter2`, {
headers: { Authorization: issueBearer(user.id) },
})
expect(res.status).toBe(200)
const list = (await res.json()) as Array<{ id: string }>
expect(list.length).toBe(1)
expect(list[0].id).toBe(teamArtifact.id)
})
test('GET /web/artifacts rejects scope=personal combined with team_id', async () => {
const res = await app.request(
'/web/artifacts?scope=personal&team_id=team_x',
{ headers: { Authorization: issueBearer(user.id) } },
)
expect(res.status).toBe(400)
})
})