api.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import fs from 'node:fs'
  2. import path from 'node:path'
  3. import pino from 'pino'
  4. import { afterAll, beforeAll, describe, expect, it } from 'vitest'
  5. import type { AgentEvent, ProviderStatusDto } from '@agent-server/shared'
  6. import { createApp, type App } from '../src/app'
  7. import { buildServer } from '../src/http/server'
  8. import type { AgentProvider, RunContext } from '../src/providers/types'
  9. /** 假引擎:输出文本 → 请求审批 → 写产出文件 */
  10. class FakeProvider implements AgentProvider {
  11. readonly id = 'claude' as const
  12. quota?: AgentProvider['quota']
  13. lastCtx: RunContext | null = null
  14. async run(ctx: RunContext) {
  15. this.lastCtx = ctx
  16. ctx.setProviderSessionId('fake-session')
  17. ctx.emit('message.delta', { messageId: 'm1', text: '你好' })
  18. ctx.emit('message.completed', { messageId: 'm1', text: '你好' })
  19. if (ctx.input.text.includes('审批')) {
  20. ctx.emit('tool.started', { toolCallId: 't1', name: 'Bash', title: 'echo', input: { command: 'echo' } })
  21. const outcome = await ctx.interact({ kind: 'approval', tool: 'Bash', title: 'echo', input: {}, options: ['allow_once', 'allow_session', 'deny'] })
  22. ctx.emit('tool.completed', { toolCallId: 't1', status: outcome.resolution === 'allowed' ? 'ok' : 'denied', output: '', truncated: false })
  23. }
  24. if (ctx.input.text.includes('等待')) await new Promise((_, reject) => ctx.signal.addEventListener('abort', () => reject(new Error('aborted'))))
  25. fs.writeFileSync(path.join(ctx.workspaceDir, 'outputs/report.md'), '# 报告')
  26. return { usage: { inputTokens: 1, outputTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0, costUsd: 0.001 } }
  27. }
  28. async status(): Promise<ProviderStatusDto> {
  29. return { id: 'claude', enabled: true, available: true, loggedIn: true, account: 'test', cliPath: '', version: 'x', models: ['m'], defaultModel: 'm', message: null }
  30. }
  31. }
  32. let app: App
  33. let server: Awaited<ReturnType<typeof buildServer>>
  34. let apiKey: string
  35. const fake = new FakeProvider()
  36. const auth = () => ({ authorization: `Bearer ${apiKey}` })
  37. async function waitFor<T>(fn: () => T | undefined, ms = 3000): Promise<T> {
  38. const end = Date.now() + ms
  39. while (Date.now() < end) {
  40. const v = fn()
  41. if (v) return v
  42. await new Promise(r => setTimeout(r, 20))
  43. }
  44. throw new Error('timeout')
  45. }
  46. const events = async (sid: string) =>
  47. (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}/events`, headers: auth() })).json().items as AgentEvent[]
  48. beforeAll(async () => {
  49. const log = pino({ level: 'silent' })
  50. app = createApp(log, { providers: { claude: fake } })
  51. server = await buildServer(app, { logger: log })
  52. const builtin = app.profiles.getBuiltin().id
  53. apiKey = app.apiKeys.create('test', { allowedProfileIds: [builtin], defaultProfileId: builtin }).key
  54. })
  55. afterAll(() => server.close())
  56. describe('鉴权', () => {
  57. it('没有 Key 返回 401', async () => {
  58. expect((await server.inject({ method: 'GET', url: '/v1/sessions' })).statusCode).toBe(401)
  59. })
  60. it('后台登录后可以访问管理接口', async () => {
  61. const login = await server.inject({ method: 'POST', url: '/admin/v1/auth/login', payload: { password: 'test-password' } })
  62. expect(login.statusCode).toBe(200)
  63. const cookie = login.cookies[0]!
  64. const res = await server.inject({ method: 'GET', url: '/admin/v1/settings', cookies: { [cookie.name]: cookie.value } })
  65. expect(res.statusCode).toBe(200)
  66. expect(res.json().settings.paths.workspaceRoot).toContain('workspaces')
  67. })
  68. it('错误密码返回 401', async () => {
  69. expect((await server.inject({ method: 'POST', url: '/admin/v1/auth/login', payload: { password: 'nope' } })).statusCode).toBe(401)
  70. })
  71. })
  72. describe('会话与 Run', () => {
  73. it('完整流程:上传 → 发送 → 审批 → 产出文件', async () => {
  74. const created = await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })
  75. expect(created.statusCode).toBe(201)
  76. const sid = created.json().id as string
  77. const boundary = 'xBOUNDARYx'
  78. const upload = await server.inject({
  79. method: 'POST', url: `/v1/sessions/${sid}/files`,
  80. headers: { ...auth(), 'content-type': `multipart/form-data; boundary=${boundary}` },
  81. payload: `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="销售.csv"\r\nContent-Type: text/csv\r\n\r\na,b\n1,2\n\r\n--${boundary}--\r\n`,
  82. })
  83. expect(upload.statusCode).toBe(201)
  84. const fileId = upload.json()[0].id as string
  85. expect(upload.json()[0].path).toBe('uploads/销售.csv')
  86. const sent = await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: '请审批', attachments: [fileId] } })
  87. expect(sent.statusCode).toBe(202)
  88. const runId = sent.json().id as string
  89. // 会话忙时不能再发
  90. const busy = await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: 'x' } })
  91. expect(busy.statusCode).toBe(409)
  92. const itx = await waitFor(() => app.interactions.pendingFor(sid)[0])
  93. expect(fake.lastCtx?.input.attachments[0]?.path).toBe('uploads/销售.csv')
  94. const detail = await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: auth() })
  95. expect(detail.json().status).toBe('waiting_input')
  96. const reply = await server.inject({ method: 'POST', url: `/v1/interactions/${itx.interactionId}`, headers: auth(), payload: { decision: 'allow_once' } })
  97. expect(reply.statusCode).toBe(200)
  98. const again = await server.inject({ method: 'POST', url: `/v1/interactions/${itx.interactionId}`, headers: auth(), payload: { decision: 'allow_once' } })
  99. expect(again.statusCode).toBe(409)
  100. await waitFor(() => app.runs.activeForSession(sid) === undefined || undefined)
  101. const run = (await server.inject({ method: 'GET', url: `/v1/runs/${runId}`, headers: auth() })).json()
  102. expect(run.status).toBe('completed')
  103. // 每个 Run 签发网关令牌,结束后作废
  104. expect(fake.lastCtx?.gateway.token).toMatch(/^rt_/)
  105. expect(app.gatewayTokens.get(fake.lastCtx!.gateway.token)).toBeNull()
  106. expect(run.usage.outputTokens).toBe(2)
  107. const types = (await events(sid)).map(e => e.type)
  108. expect(types).toEqual(expect.arrayContaining([
  109. 'user.message', 'run.queued', 'run.started', 'message.completed', 'tool.started',
  110. 'interaction.required', 'interaction.resolved', 'tool.completed', 'file.changed', 'usage', 'run.completed',
  111. ]))
  112. // 内存缓冲中包含瞬时的 delta 事件
  113. expect(types).toContain('message.delta')
  114. const files = (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}/files`, headers: auth() })).json()
  115. const report = files.find((f: { path: string }) => f.path === 'outputs/report.md')
  116. expect(report.origin).toBe('agent')
  117. const dl = await server.inject({ method: 'GET', url: `/v1/files/${report.id}`, headers: auth() })
  118. expect(dl.body).toBe('# 报告')
  119. const session = (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: auth() })).json()
  120. expect(session.title).toBe('请审批')
  121. })
  122. it('中断运行中的 Run', async () => {
  123. const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })).json().id
  124. const runId = (await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: '等待' } })).json().id
  125. await waitFor(() => app.runs.activeForSession(sid)?.status === 'running' || undefined)
  126. expect((await server.inject({ method: 'POST', url: `/v1/runs/${runId}/interrupt`, headers: auth() })).statusCode).toBe(202)
  127. await waitFor(() => app.runs.activeForSession(sid) === undefined || undefined)
  128. expect(app.runs.get(runId).status).toBe('interrupted')
  129. expect((await events(sid)).at(-1)?.type).toBe('run.interrupted')
  130. })
  131. it('其他 API Key 看不到这个会话', async () => {
  132. const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })).json().id
  133. const b = app.profiles.getBuiltin().id
  134. const otherKey = app.apiKeys.create('other', { allowedProfileIds: [b], defaultProfileId: b }).key
  135. const res = await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: { authorization: `Bearer ${otherKey}` } })
  136. expect(res.statusCode).toBe(404)
  137. })
  138. it('删除会话同时删除工作区', async () => {
  139. const created = await app.sessions.create(app.apiKeys.list()[0]!.id, {})
  140. expect(fs.existsSync(created.workspaceDir)).toBe(true)
  141. await app.sessions.delete(created.id, 'admin')
  142. expect(fs.existsSync(created.workspaceDir)).toBe(false)
  143. })
  144. })
  145. describe('资料库', () => {
  146. it('拒绝不安全的路径', () => {
  147. expect(() => app.knowledge.create({ name: 'home', path: '~' })).toThrow(/全局禁止项/)
  148. expect(() => app.knowledge.create({ name: 'none', path: '/does/not/exist' })).toThrow(/不存在/)
  149. })
  150. })
  151. describe('API Key 可用的 Profile', () => {
  152. const profileInput = (name: string, permissionMode: 'ask' | 'auto' | 'readonly' = 'ask') => ({
  153. name, description: '', provider: 'claude' as const, model: 'haiku', systemPrompt: '', permissionMode,
  154. allowedTools: [], disallowedTools: [], skills: 'all' as const, fileAccess: { mode: 'restricted' as const, read: [], write: [], deny: [] },
  155. knowledgeRootIds: [], isDefault: false,
  156. })
  157. it('平台只能看到并使用配置给它的 Profile', async () => {
  158. const builtin = app.profiles.getBuiltin()
  159. const finance = app.profiles.create(profileInput('财务'))
  160. const secret = app.profiles.create(profileInput('其他'))
  161. const { key } = app.apiKeys.create('平台A', { allowedProfileIds: [builtin.id, finance.id], defaultProfileId: finance.id })
  162. const h = { authorization: `Bearer ${key}` }
  163. const list = (await server.inject({ method: 'GET', url: '/v1/profiles', headers: h })).json() as { id: string; isDefault: boolean }[]
  164. expect(list.map(p => p.id).sort()).toEqual([builtin.id, finance.id].sort())
  165. expect(list.find(p => p.isDefault)?.id).toBe(finance.id)
  166. // 不指定时用平台的默认 Profile,并使用其默认模型
  167. const s1 = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: {} })).json()
  168. expect(s1.profileId).toBe(finance.id)
  169. expect(s1.model).toBe('haiku')
  170. const denied = await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: { profileId: secret.id } })
  171. expect(denied.statusCode).toBe(403)
  172. expect(denied.json().error.code).toBe('profile_not_allowed')
  173. // 可以自选模型,但必须是可用模型
  174. expect((await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: { model: 'opus' } })).statusCode).toBe(201)
  175. expect((await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: { model: 'gpt-x' } })).statusCode).toBe(400)
  176. })
  177. it('权限模式由 Profile 决定:平台不能指定,修改 Profile 后立即生效', async () => {
  178. const p = app.profiles.create(profileInput('只读助手', 'readonly'))
  179. const { key } = app.apiKeys.create('平台B', { allowedProfileIds: [p.id], defaultProfileId: p.id })
  180. const h = { authorization: `Bearer ${key}` }
  181. expect((await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: { permissionMode: 'auto' } })).statusCode).toBe(400)
  182. const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: {} })).json().id
  183. expect((await server.inject({ method: 'PATCH', url: `/v1/sessions/${sid}`, headers: h, payload: { permissionMode: 'auto' } })).statusCode).toBe(400)
  184. expect((await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: h })).json().permissionMode).toBe('readonly')
  185. app.profiles.update(p.id, { ...profileInput('只读助手', 'ask') })
  186. const detail = (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: h })).json()
  187. expect(detail.permissionMode).toBe('ask')
  188. expect(detail.permissionModeOverridden).toBe(false)
  189. await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: h, payload: { text: 'hi' } })
  190. await waitFor(() => app.runs.activeForSession(sid) === undefined || undefined)
  191. expect(fake.lastCtx?.permissionMode).toBe('ask')
  192. })
  193. it('撤销 Profile 后,已有会话不能继续运行', async () => {
  194. const builtin = app.profiles.getBuiltin()
  195. const p = app.profiles.create(profileInput('临时'))
  196. const { key, apiKey } = app.apiKeys.create('平台C', { allowedProfileIds: [builtin.id, p.id], defaultProfileId: p.id })
  197. const h = { authorization: `Bearer ${key}` }
  198. const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: {} })).json().id
  199. app.apiKeys.setProfiles(apiKey.id, { allowedProfileIds: [builtin.id], defaultProfileId: builtin.id })
  200. const res = await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: h, payload: { text: 'hi' } })
  201. expect(res.statusCode).toBe(403)
  202. })
  203. it('Key 配置校验;内置 Profile 和被引用的 Profile 不能删除', async () => {
  204. const builtin = app.profiles.getBuiltin()
  205. expect(builtin.builtin).toBe(true)
  206. expect(() => app.apiKeys.create('x', { allowedProfileIds: [], defaultProfileId: builtin.id })).toThrow(/至少选择一个/)
  207. const p = app.profiles.create(profileInput('另一个'))
  208. expect(() => app.apiKeys.create('x', { allowedProfileIds: [builtin.id], defaultProfileId: p.id })).toThrow(/默认 Profile 必须/)
  209. expect(() => app.profiles.delete(builtin.id)).toThrow(/内置/)
  210. app.apiKeys.create('平台D', { allowedProfileIds: [p.id], defaultProfileId: p.id })
  211. const login = await server.inject({ method: 'POST', url: '/admin/v1/auth/login', payload: { password: 'test-password' } })
  212. const cookie = login.cookies[0]!
  213. const del = await server.inject({ method: 'DELETE', url: `/admin/v1/profiles/${p.id}`, cookies: { [cookie.name]: cookie.value } })
  214. expect(del.statusCode).toBe(400)
  215. expect(del.json().error.message).toContain('平台D')
  216. })
  217. })
  218. describe('引擎由 Profile 决定', () => {
  219. it('每个引擎一个内置通用助手:不可删除,引擎不可修改', () => {
  220. const claude = app.profiles.getBuiltin('claude')
  221. const codex = app.profiles.getBuiltin('codex')
  222. expect(claude).toMatchObject({ name: '通用助手(Claude)', provider: 'claude', builtin: true })
  223. expect(codex).toMatchObject({ name: '通用助手(Codex)', provider: 'codex', builtin: true })
  224. expect(() => app.profiles.delete(codex.id)).toThrow(/内置/)
  225. const { id: _i, version: _v, updatedAt: _u, builtin: _b, ...input } = codex
  226. expect(() => app.profiles.update(codex.id, { ...input, provider: 'claude' })).toThrow(/引擎不能修改/)
  227. })
  228. it('平台和后台都不能单独指定引擎;会话引擎取自 Profile', async () => {
  229. const claude = app.profiles.getBuiltin('claude')
  230. const codex = app.profiles.getBuiltin('codex')
  231. const { key } = app.apiKeys.create('双引擎平台', { allowedProfileIds: [claude.id, codex.id], defaultProfileId: claude.id })
  232. const h = { authorization: `Bearer ${key}` }
  233. const bad = await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: { provider: 'codex' } })
  234. expect(bad.statusCode).toBe(400)
  235. expect(bad.json().error.message).toContain('引擎由 Profile 决定')
  236. await expect(app.sessions.create('admin', { provider: 'codex' } as never)).rejects.toThrow(/引擎由 Profile 决定/)
  237. // Codex 未启用时不能建会话;启用后按 Profile 使用 codex
  238. expect((await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: { profileId: codex.id } })).statusCode).toBe(400)
  239. app.settings.update({ providers: { codex: { enabled: true } } })
  240. const s = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: h, payload: { profileId: codex.id } })).json()
  241. expect(s.provider).toBe('codex')
  242. expect(s.model).toBe(codex.model)
  243. // 换 Profile 时引擎随之改变(尚未开始对话)
  244. const patched = (await server.inject({ method: 'PATCH', url: `/v1/sessions/${s.id}`, headers: h, payload: { profileId: claude.id } })).json()
  245. expect(patched.provider).toBe('claude')
  246. expect((await server.inject({ method: 'PATCH', url: `/v1/sessions/${s.id}`, headers: h, payload: { provider: 'codex' } })).statusCode).toBe(400)
  247. })
  248. })
  249. describe('内置 Profile 的兜底', () => {
  250. it('设置中的默认模型为空时,仍能创建内置 Profile', async () => {
  251. const { createDb } = await import('../src/db')
  252. const { SettingsService } = await import('../src/services/settings')
  253. const { ProfileService } = await import('../src/services/catalog')
  254. const os = await import('node:os')
  255. const db = createDb(path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'seed-')), 'db.sqlite'))
  256. const { migrateDb } = await import('../src/db')
  257. migrateDb(db)
  258. const settings = new SettingsService(db)
  259. settings.update({ providers: { codex: { defaultModel: '' } } })
  260. const profiles = new ProfileService(db, settings)
  261. expect(profiles.getBuiltin('codex').model).toBe('gpt-6.1-sol')
  262. })
  263. })
  264. describe('用量统计', () => {
  265. it('Run 结束后按天累加;删除会话后历史用量保留;平台只能看到自己的用量', async () => {
  266. const before = app.usage.summary({ days: 7 }).total.runs
  267. const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })).json().id as string
  268. await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: '统计' } })
  269. await waitFor(() => app.runs.activeForSession(sid) === undefined || undefined)
  270. await waitFor(() => app.usage.summary({ days: 7 }).total.runs > before || undefined)
  271. await server.inject({ method: 'DELETE', url: `/v1/sessions/${sid}`, headers: auth() })
  272. const s = app.usage.summary({ days: 7 })
  273. expect(s.daily).toHaveLength(7)
  274. expect(s.total.runs).toBe(before + 1)
  275. expect(s.today.outputTokens).toBeGreaterThanOrEqual(2)
  276. expect(s.bySource.find(x => x.name === 'test')).toBeTruthy()
  277. expect(s.byModel[0]).toMatchObject({ provider: 'claude' })
  278. const mine = (await server.inject({ method: 'GET', url: '/v1/usage?days=7', headers: auth() })).json()
  279. expect(mine.bySource.map((x: { name: string }) => x.name)).toEqual(['test'])
  280. const admin = await server.inject({ method: 'GET', url: '/admin/v1/usage', headers: auth() })
  281. expect(admin.statusCode).toBe(401)
  282. })
  283. it('区间按日期补零;同一键累加', () => {
  284. app.usage.record({ source: 'k', provider: 'codex', model: 'gpt', status: 'failed', inputTokens: 5, durationMs: 100 }, '2026-01-02')
  285. app.usage.record({ source: 'k', provider: 'codex', model: 'gpt', status: 'completed', inputTokens: 7, costUsd: 0.5 }, '2026-01-02')
  286. const s = app.usage.summary({ days: 3, today: '2026-01-03', source: 'k' })
  287. expect(s.daily.map(d => [d.date, d.runs, d.inputTokens])).toEqual([['2026-01-01', 0, 0], ['2026-01-02', 2, 12], ['2026-01-03', 0, 0]])
  288. expect(s.total).toMatchObject({ runs: 2, failed: 1, costUsd: 0.5, durationMs: 100 })
  289. expect(s.bySource[0]!.name).toMatch(/已删除的 Key/)
  290. expect(s.byProvider).toEqual([{ provider: 'codex', total: expect.objectContaining({ runs: 2, inputTokens: 12 }), today: expect.objectContaining({ runs: 0 }) }])
  291. const onDay = app.usage.summary({ days: 1, today: '2026-01-02', source: 'k' })
  292. expect(onDay.byProvider[0]!.today).toMatchObject({ runs: 2, failed: 1 })
  293. })
  294. it('引擎不支持额度查询时返回 404', async () => {
  295. const cookie = { agent_admin: app.adminAuth.login('test-password').id }
  296. const r = await server.inject({ method: 'GET', url: '/admin/v1/providers/claude/quota', cookies: cookie })
  297. expect(r.statusCode).toBe(404)
  298. fake.quota = async () => ({ provider: 'claude', plan: 'team', windows: [{ key: 'five_hour', label: '5 小时', usedPercent: 27, resetsAt: null }], source: 'live', fetchedAt: '', message: null })
  299. const ok = await server.inject({ method: 'GET', url: '/admin/v1/providers/claude/quota', cookies: cookie })
  300. expect(ok.json()).toMatchObject({ plan: 'team', windows: [{ usedPercent: 27 }] })
  301. delete (fake as { quota?: unknown }).quota
  302. })
  303. })
  304. describe('浏览器令牌与 CORS', () => {
  305. it('API Key 签发令牌;令牌可调用 /v1,但不能再签发;停用 Key 后令牌失效', async () => {
  306. const builtin = app.profiles.getBuiltin().id
  307. const k = app.apiKeys.create('browser-test', { allowedProfileIds: [builtin], defaultProfileId: builtin })
  308. const issued = await server.inject({ method: 'POST', url: '/v1/browser-tokens', headers: { authorization: `Bearer ${k.key}` }, payload: { ttlSeconds: 600 } })
  309. expect(issued.statusCode).toBe(201)
  310. const { token, expiresAt } = issued.json()
  311. expect(token).toMatch(/^bt_/)
  312. expect(Date.parse(expiresAt) - Date.now()).toBeGreaterThan(590_000)
  313. const bt = { authorization: `Bearer ${token}` }
  314. const created = await server.inject({ method: 'POST', url: '/v1/sessions', headers: bt, payload: {} })
  315. expect(created.statusCode).toBe(201)
  316. // 令牌创建的会话归属于签发它的 Key
  317. const list = (await server.inject({ method: 'GET', url: '/v1/sessions', headers: { authorization: `Bearer ${k.key}` } })).json()
  318. expect(list.items.map((s: { id: string }) => s.id)).toContain(created.json().id)
  319. expect((await server.inject({ method: 'POST', url: '/v1/browser-tokens', headers: bt, payload: {} })).statusCode).toBe(403)
  320. expect((await server.inject({ method: 'POST', url: '/v1/browser-tokens', headers: { authorization: `Bearer ${k.key}` }, payload: { ttlSeconds: 999999 } })).statusCode).toBe(400)
  321. // 篡改、过期
  322. expect((await server.inject({ method: 'GET', url: '/v1/profiles', headers: { authorization: `Bearer ${token.slice(0, -2)}xx` } })).statusCode).toBe(401)
  323. const old = app.browserTokens.issue(k.apiKey.id, 60, Date.now() - 120_000)
  324. expect((await server.inject({ method: 'GET', url: '/v1/profiles', headers: { authorization: `Bearer ${old.token}` } })).statusCode).toBe(401)
  325. app.apiKeys.setEnabled(k.apiKey.id, false)
  326. const after = await server.inject({ method: 'GET', url: '/v1/profiles', headers: bt })
  327. expect(after.statusCode).toBe(401)
  328. expect(after.json().error.code).toBe('invalid_token')
  329. })
  330. it('只对设置中允许的来源返回 CORS 头;预检请求;不对后台开放', async () => {
  331. app.settings.update({ security: { corsOrigins: ['https://tools.example.com'] } })
  332. const pre = await server.inject({ method: 'OPTIONS', url: '/v1/sessions', headers: { origin: 'https://tools.example.com', 'access-control-request-method': 'POST' } })
  333. expect(pre.statusCode).toBe(204)
  334. expect(pre.headers['access-control-allow-origin']).toBe('https://tools.example.com')
  335. expect(pre.headers['access-control-allow-headers']).toContain('last-event-id')
  336. expect(pre.headers['access-control-allow-credentials']).toBeUndefined()
  337. const ok = await server.inject({ method: 'GET', url: '/v1/profiles', headers: { ...auth(), origin: 'https://tools.example.com' } })
  338. expect(ok.headers['access-control-allow-origin']).toBe('https://tools.example.com')
  339. const other = await server.inject({ method: 'GET', url: '/v1/profiles', headers: { ...auth(), origin: 'https://evil.example.com' } })
  340. expect(other.headers['access-control-allow-origin']).toBeUndefined()
  341. const adminRoute = await server.inject({ method: 'GET', url: '/admin/v1/overview', headers: { origin: 'https://tools.example.com' } })
  342. expect(adminRoute.headers['access-control-allow-origin']).toBeUndefined()
  343. expect(() => app.settings.update({ security: { corsOrigins: ['https://x.com/path'] } })).toThrow()
  344. app.settings.update({ security: { corsOrigins: [] } })
  345. })
  346. })
  347. describe('Profile 版本历史', () => {
  348. it('内容变化才产生新版本;可以查看改动字段并恢复(恢复保存为新版本)', () => {
  349. const base = app.profiles.getBuiltin()
  350. const { id: _id, version: _v, updatedAt: _u, builtin: _b, ...input } = base
  351. const p = app.profiles.create({ ...input, name: '版本测试', isDefault: false })
  352. expect(p.version).toBe(1)
  353. const v2 = app.profiles.update(p.id, { ...input, name: '版本测试', isDefault: false, systemPrompt: '第二版' })
  354. expect(v2.version).toBe(2)
  355. // 没有变化不产生新版本
  356. expect(app.profiles.update(p.id, { ...input, name: '版本测试', isDefault: false, systemPrompt: '第二版' }).version).toBe(2)
  357. app.profiles.update(p.id, { ...input, name: '版本测试3', isDefault: false, systemPrompt: '第二版', model: 'opus' })
  358. const versions = app.profiles.versions(p.id)
  359. expect(versions.map(v => [v.version, v.changed])).toEqual([[3, ['name', 'model']], [2, ['systemPrompt']], [1, []]])
  360. const restored = app.profiles.restore(p.id, 1)
  361. expect(restored).toMatchObject({ version: 4, name: '版本测试', systemPrompt: input.systemPrompt, model: input.model })
  362. expect(() => app.profiles.restore(p.id, 99)).toThrow(/不存在/)
  363. app.profiles.delete(p.id)
  364. expect(() => app.profiles.versions(p.id)).toThrow()
  365. })
  366. })