routes.ts 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. import { RegistrationLimiter } from './subaccountAccess.js'
  2. import { readServerIdentity, updateServerIdentity } from './serverIdentity.js'
  3. import { authorizeFileRead, fileAccessWorkingDirectory, readFileAccess, saveFileAccess } from './fileAccess.js'
  4. import { readHostTools, saveHostTools } from './hostToolSettings.js'
  5. import type { ServerIdentity } from '../shared/serverIdentity.js'
  6. import type Koa from 'koa'
  7. import type { WorkspaceStore } from './workspaceStore.js'
  8. import type { WorkspaceConversation } from '../shared/workspace.js'
  9. import Router from '@koa/router'
  10. import { parse } from 'cookie'
  11. import { createReadStream, realpathSync, statSync } from 'node:fs'
  12. import { basename, resolve, sep } from 'node:path'
  13. import { lookup as mimeLookup } from 'mime-types'
  14. import { isSupportedGroupProtocolVersion, SUPPORTED_GROUP_PROTOCOL_VERSION_LABEL } from '../shared/types.js'
  15. import type { ServerConfig } from './config.js'
  16. import { isLoopbackHost, isLoopbackUpstream, isPrivateHost } from './config.js'
  17. import { HttpError } from './errors.js'
  18. import { compareReleaseVersions } from './releases.js'
  19. import {
  20. bearerToken,
  21. DEFAULT_NODE_SCOPES,
  22. NODE_PAIRING_PROTOCOL_VERSION,
  23. type NodeScope,
  24. NodePairingStore,
  25. } from './pairing.js'
  26. import { CsrfProtection, requestAccountKey } from './security.js'
  27. import {
  28. applyUpstreamCookies,
  29. CookieJar,
  30. decodeUpstreamError,
  31. sendUpstreamResponse,
  32. type UpstreamResponse,
  33. UpstreamClient,
  34. } from './upstream.js'
  35. import { receiveGroupUploads, uploadMarkdown, UploadStore } from './uploads.js'
  36. import { SystemUpdateManager, type SystemUpdateStatus } from './updateManager.js'
  37. import { LocalAuthStore, type LocalUser, UpstreamServiceSession } from './localAuth.js'
  38. import { AccountLoginPairingStore } from './accountPairing.js'
  39. import { UpstreamProfileIdentityService } from './profileIdentities.js'
  40. import { PushCoordinator } from './pushCoordinator.js'
  41. import {
  42. APNsConfigurationManager,
  43. type APNsConfigurationInput,
  44. } from './apnsConfiguration.js'
  45. import {
  46. FCMConfigurationManager,
  47. type FCMConfigurationInput,
  48. } from './fcmConfiguration.js'
  49. import type { OpenVikingConfigurationManager } from './openVikingConfiguration.js'
  50. import type { OpenVikingService } from './openVikingService.js'
  51. import type { OpenVikingSessionSync } from './openVikingSessionSync.js'
  52. import {
  53. AllowedHostsConfigurationManager,
  54. canonicalAllowedHosts,
  55. normalizeAllowedHost,
  56. } from './allowedHostsConfiguration.js'
  57. import { chatCacheKey, type ChatCacheCoordinator } from './chatCache.js'
  58. type JsonObject = Record<string, unknown>
  59. export interface RouteDependencies {
  60. hermesBridge: import('./hermesBridge.js').HermesBridgeManager
  61. onChatListChanged?: (owner:string,profile:string,id:string)=>void
  62. onServerIdentityChanged?: (identity: ServerIdentity) => void
  63. onUserAccessChanged?: (owner: string) => Promise<void>
  64. workspace: WorkspaceStore
  65. config: ServerConfig
  66. csrf: CsrfProtection
  67. upstream: UpstreamClient
  68. pairings: NodePairingStore
  69. uploads: UploadStore
  70. updates: SystemUpdateManager
  71. auth: LocalAuthStore
  72. upstreamSession: UpstreamServiceSession
  73. accountPairings: AccountLoginPairingStore
  74. profileIdentities: UpstreamProfileIdentityService
  75. push: PushCoordinator
  76. apnsConfiguration: APNsConfigurationManager
  77. fcmConfiguration: FCMConfigurationManager
  78. openVikingConfiguration: OpenVikingConfigurationManager
  79. openVikingService: OpenVikingService
  80. openVikingSessionSync: OpenVikingSessionSync
  81. allowedHostsConfiguration: AllowedHostsConfigurationManager
  82. chatCache?: ChatCacheCoordinator
  83. }
  84. function body(ctx: Koa.Context): JsonObject {
  85. const value = (ctx.request as Koa.Request & { body?: unknown }).body
  86. if (!value || typeof value !== 'object' || Array.isArray(value)) {
  87. throw new HttpError(400, 'A JSON object body is required', 'invalid_json_body')
  88. }
  89. return value as JsonObject
  90. }
  91. function optionalBody(ctx: Koa.Context): JsonObject | undefined {
  92. const value = (ctx.request as Koa.Request & { body?: unknown }).body
  93. return value && typeof value === 'object' && !Array.isArray(value)
  94. ? value as JsonObject
  95. : undefined
  96. }
  97. function parseJson(response: UpstreamResponse): JsonObject {
  98. try {
  99. const value = JSON.parse(response.body.toString('utf8')) as unknown
  100. if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object')
  101. return value as JsonObject
  102. } catch {
  103. throw new HttpError(502, 'Hermes returned invalid JSON', 'invalid_upstream_json')
  104. }
  105. }
  106. function parseJsonValue(response: UpstreamResponse): unknown {
  107. try {
  108. return JSON.parse(response.body.toString('utf8')) as unknown
  109. } catch {
  110. throw new HttpError(502, 'Hermes returned invalid JSON', 'invalid_upstream_json')
  111. }
  112. }
  113. function requireSuccess(response: UpstreamResponse): JsonObject {
  114. if (response.status < 200 || response.status >= 300) {
  115. const decoded = decodeUpstreamError(response)
  116. throw new HttpError(response.status, decoded.error, decoded.code)
  117. }
  118. return parseJson(response)
  119. }
  120. function searchFrom(ctx: Koa.Context, allowed: readonly string[]): URLSearchParams {
  121. const incoming = new URLSearchParams(ctx.querystring)
  122. const outgoing = new URLSearchParams()
  123. for (const name of allowed) {
  124. for (const value of incoming.getAll(name)) outgoing.append(name, value)
  125. }
  126. return outgoing
  127. }
  128. function safeIdentifier(value: string, label = 'identifier'): string {
  129. const normalized = value.trim()
  130. if (!normalized || normalized === '.' || normalized === '..'
  131. || normalized.length > 256 || /[\u0000-\u001f\u007f/\\]/.test(normalized)) {
  132. throw new HttpError(400, `Invalid ${label}`, 'invalid_identifier')
  133. }
  134. return normalized
  135. }
  136. function canonicalUUID(value: string, label: string): string {
  137. const normalized = value.toLowerCase()
  138. if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(normalized)) {
  139. throw new HttpError(400, `${label} must be a UUID`, 'invalid_identifier')
  140. }
  141. return normalized
  142. }
  143. function normalizedProfiles(value: JsonObject): unknown[] {
  144. const profiles = Array.isArray(value.profiles) ? value.profiles : []
  145. return profiles.map((entry) => {
  146. if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
  147. const object = entry as JsonObject
  148. return object.profile && typeof object.profile === 'object' ? object.profile : object
  149. }
  150. return entry
  151. })
  152. }
  153. function profilesWithCoreNames(profiles: unknown[]): unknown[] {
  154. return profiles.map(entry => {
  155. if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return entry
  156. const profile = entry as JsonObject
  157. const meta = profile.ui_meta as Record<string, any> | undefined
  158. const title = meta?.['hermes-bots']?.title ?? profile.display_name
  159. return typeof title === 'string' && title.trim() ? { ...profile, agentName:title.trim(), display_name:title.trim(), description:title.trim() } : profile
  160. })
  161. }
  162. function authRequired(status: JsonObject): boolean {
  163. return status.auth_required === true || status.authRequired === true
  164. }
  165. function publicStatus(status: JsonObject): JsonObject {
  166. return {
  167. state: typeof status.overall === 'string' ? status.overall : 'unknown',
  168. version: typeof status.version === 'string' ? status.version : undefined,
  169. gatewayRunning: status.gateway_running === true || status.gatewayRunning === true,
  170. gatewayState: typeof status.gateway_state === 'string'
  171. ? status.gateway_state
  172. : typeof status.gatewayState === 'string' ? status.gatewayState : undefined,
  173. }
  174. }
  175. export function systemUpdateRequestAllowed(address: string, allowRemoteUpdate = false): boolean {
  176. if (allowRemoteUpdate) return true
  177. return isLoopbackHost(address.replace(/^::ffff:/, ''))
  178. }
  179. function localSystemUpdateAllowed(ctx: Koa.Context, dependencies: RouteDependencies): boolean {
  180. const address = (ctx.req.socket.remoteAddress ?? '').replace(/^::ffff:/, '')
  181. return systemUpdateRequestAllowed(address, dependencies.config.allowRemoteUpdate)
  182. }
  183. function systemUpdateStatusForRequest(
  184. ctx: Koa.Context,
  185. dependencies: RouteDependencies,
  186. status: SystemUpdateStatus,
  187. ): SystemUpdateStatus {
  188. if (!status.supported || localSystemUpdateAllowed(ctx, dependencies)) return status
  189. return {
  190. ...status,
  191. supported: false,
  192. unsupportedReason: '系统升级默认只允许在本机执行;可通过服务配置显式允许远程升级',
  193. }
  194. }
  195. function requireLocalSystemUpdate(ctx: Koa.Context, dependencies: RouteDependencies): void {
  196. if (!localSystemUpdateAllowed(ctx, dependencies)) {
  197. throw new HttpError(
  198. 403,
  199. '系统升级默认只允许在本机执行',
  200. 'remote_system_update_disabled',
  201. )
  202. }
  203. }
  204. function updateFailure(error: unknown): HttpError {
  205. const message = error instanceof Error ? error.message : String(error)
  206. if (/最新版本|目标版本|正在执行|可回滚|不支持/.test(message)) {
  207. return new HttpError(409, message, 'system_update_conflict')
  208. }
  209. return new HttpError(502, `无法访问系统发布源:${message}`, 'system_update_source_failed')
  210. }
  211. async function withJar<T>(ctx: Koa.Context, run: (jar: CookieJar) => Promise<T>): Promise<T> {
  212. const service = ctx.state.upstreamSession as UpstreamServiceSession | undefined
  213. if (service) {
  214. await service.ensure()
  215. return run(service.jar)
  216. }
  217. const jar = new CookieJar(ctx.get('cookie'))
  218. try { return await run(jar) } finally { applyUpstreamCookies(ctx, jar) }
  219. }
  220. function json(ctx: Koa.Context, status: number, value: unknown): void {
  221. ctx.status = status
  222. ctx.type = 'application/json; charset=utf-8'
  223. ctx.body = value
  224. }
  225. function pushSystemStatus(dependencies: RouteDependencies): Record<string, unknown> {
  226. const runtime = dependencies.push.status()
  227. const settings = dependencies.apnsConfiguration.snapshot()
  228. const input = settings.input
  229. const apns = {
  230. ...runtime,
  231. source: settings.source,
  232. editable: settings.editable,
  233. keyFile: input?.keyFile,
  234. keyId: input?.keyId,
  235. teamId: input?.teamId,
  236. topic: input?.topic ?? runtime.topic,
  237. environments: input?.environments ?? runtime.environments,
  238. warnings: settings.warnings,
  239. ...(settings.configurationError ? { configurationError: settings.configurationError } : {}),
  240. }
  241. const fcmRuntime = dependencies.push.fcmStatus()
  242. const fcmSettings = dependencies.fcmConfiguration.snapshot()
  243. const fcmInput = fcmSettings.input
  244. const fcm = {
  245. ...fcmRuntime,
  246. source: fcmSettings.source,
  247. editable: fcmSettings.editable,
  248. serviceAccountFile: fcmInput?.serviceAccountFile,
  249. projectId: fcmInput?.projectId ?? fcmRuntime.projectId,
  250. packageName: fcmInput?.packageName ?? fcmRuntime.packageName,
  251. warnings: fcmSettings.warnings,
  252. ...(fcmSettings.configurationError ? { configurationError: fcmSettings.configurationError } : {}),
  253. }
  254. return { ...apns, providers: { apns, fcm } }
  255. }
  256. function pushRequest<T>(operation: () => T): T {
  257. try {
  258. return operation()
  259. } catch (cause) {
  260. const message = cause instanceof Error ? cause.message : '推送请求无效'
  261. throw new HttpError(400, message, 'invalid_push_request')
  262. }
  263. }
  264. function bestEffortRemoveUserPush(
  265. ctx: Koa.Context,
  266. dependencies: RouteDependencies,
  267. userID: string,
  268. ): void {
  269. try {
  270. dependencies.push.removeUser(userID)
  271. } catch (cause) {
  272. const detail = cause instanceof Error ? cause.message : String(cause)
  273. ctx.app.emit('error', new Error(`用户权限已更新,但推送状态清理失败:${detail}`), ctx)
  274. }
  275. }
  276. async function latestGroupMessageSequence(dependencies: RouteDependencies, roomID: string, owner: string): Promise<number> {
  277. const room = dependencies.workspace.require<WorkspaceConversation>(owner, 'conversation', roomID)
  278. if (room.kind !== 'group') throw new HttpError(404,'群聊不存在','group_not_found')
  279. return room.lastSeq
  280. }
  281. function requestOrigin(ctx: Koa.Context, config: ServerConfig): string {
  282. const secure = ctx.secure || Boolean(config.tlsCert)
  283. return `${secure ? 'https' : 'http'}://${ctx.host}`
  284. }
  285. function pairingScopes(value: unknown): string[] | undefined {
  286. if (value === undefined) return undefined
  287. if (!Array.isArray(value) || !value.every((scope) => typeof scope === 'string')) {
  288. throw new HttpError(400, 'scopes must be a string array', 'invalid_scope')
  289. }
  290. return value
  291. }
  292. function pairedProxyScope(path: string, method: string): NodeScope {
  293. if (path === '/profiles' || path.startsWith('/profiles/')) {
  294. return path.includes('/sessions') ? 'history.read' : 'agents.read'
  295. }
  296. if (path === '/sessions' || path.startsWith('/sessions/')) {
  297. return ['GET', 'HEAD'].includes(method) ? 'history.read' : 'sessions.execute'
  298. }
  299. return 'sessions.execute'
  300. }
  301. function isNativeSessionMutation(path: string, method: string): boolean {
  302. if (['GET', 'HEAD'].includes(method)) return false
  303. return path === '/sessions'
  304. || path.startsWith('/sessions/')
  305. || /^\/profiles\/[^/]+\/sessions(?:\/|$)/.test(path)
  306. }
  307. function nativeSessionsReadOnly(): never {
  308. throw new HttpError(
  309. 410,
  310. '原生 Hermes 会话仅供历史查看;请在聊天中开始或继续对话',
  311. 'native_sessions_read_only',
  312. )
  313. }
  314. function requireWritableOwnedSession(response: UpstreamResponse, locallyOwned = false): void {
  315. requireSuccess(response)
  316. if (!locallyOwned) nativeSessionsReadOnly()
  317. }
  318. function isMissingSessionResponse(response: UpstreamResponse): boolean {
  319. if (response.status !== 404) return false
  320. try {
  321. const payload = parseJson(response)
  322. if (payload.code === 'session_not_found') return true
  323. const detail = payload.detail
  324. const message = [payload.error, payload.message, detail,
  325. detail && typeof detail === 'object' && 'message' in detail ? detail.message : undefined]
  326. .find(value => typeof value === 'string')
  327. return typeof message === 'string'
  328. && /^(session not found|session ?不存在|会话不存在)([.!。!]|\s*[::].*)?$/i
  329. .test(message.trim().replace(/\s+/g, ' '))
  330. } catch {
  331. return false
  332. }
  333. }
  334. function writableSessionPatch(input: JsonObject): JsonObject {
  335. const allowed = new Set(['title', 'archived', 'pinned'])
  336. const unknown = Object.keys(input).filter(key => !allowed.has(key))
  337. if (unknown.length) {
  338. throw new HttpError(400, `Session field is not writable: ${unknown[0]}`, 'invalid_session_patch')
  339. }
  340. const patch: JsonObject = {}
  341. if (Object.hasOwn(input, 'title')) {
  342. if (typeof input.title !== 'string' || !input.title.trim() || input.title.length > 500) {
  343. throw new HttpError(400, 'Session title is invalid', 'invalid_session_patch')
  344. }
  345. patch.title = input.title.trim()
  346. }
  347. for (const key of ['archived', 'pinned'] as const) {
  348. if (!Object.hasOwn(input, key)) continue
  349. if (typeof input[key] !== 'boolean') {
  350. throw new HttpError(400, `Session ${key} must be a boolean`, 'invalid_session_patch')
  351. }
  352. patch[key] = input[key]
  353. }
  354. if (!Object.keys(patch).length) {
  355. throw new HttpError(400, 'Session patch is empty', 'invalid_session_patch')
  356. }
  357. return patch
  358. }
  359. function pairedProxyPath(rawPath: string): string {
  360. const path = rawPath.startsWith('/') ? rawPath : `/${rawPath}`
  361. if (path.includes('\\') || path.includes('\u0000') || path.length > 2_048) {
  362. throw new HttpError(400, 'Paired node path is invalid', 'invalid_node_path')
  363. }
  364. const allowed = path === '/status'
  365. || path === '/auth/me'
  366. || path === '/profiles'
  367. || path.startsWith('/profiles/')
  368. || path === '/sessions'
  369. || path.startsWith('/sessions/')
  370. || path.startsWith('/model/')
  371. || path.startsWith('/models/')
  372. || path.startsWith('/files/')
  373. || path.startsWith('/attachments/')
  374. if (!allowed) throw new HttpError(404, 'Paired node route is not available', 'node_route_not_found')
  375. return `/api${path}`
  376. }
  377. async function proxy(
  378. ctx: Koa.Context,
  379. upstream: UpstreamClient,
  380. path: string,
  381. options: {
  382. search?: URLSearchParams
  383. method?: string
  384. requestBody?: unknown
  385. requestHeaders?: Record<string, string>
  386. maxResponseBytes?: number
  387. } = {},
  388. ): Promise<void> {
  389. await withJar(ctx, async (jar) => {
  390. const response = await upstream.request(path, jar, {
  391. method: options.method,
  392. search: options.search,
  393. body: options.requestBody,
  394. headers: options.requestHeaders,
  395. maxResponseBytes: options.maxResponseBytes,
  396. })
  397. sendUpstreamResponse(ctx, response, jar)
  398. })
  399. }
  400. async function completeSessionList(
  401. upstream: UpstreamClient,
  402. path: string,
  403. jar: CookieJar,
  404. baseSearch: URLSearchParams,
  405. ): Promise<UpstreamResponse> {
  406. const rows = new Map<string, unknown>()
  407. let firstResponse: UpstreamResponse | undefined
  408. let firstPayload: JsonObject | undefined
  409. let collectionKey: 'items' | 'sessions' | undefined
  410. let offset = 0
  411. const limit = 100
  412. for (let page = 0; page < 1_000; page++) {
  413. const search = new URLSearchParams(baseSearch)
  414. search.set('offset', String(offset))
  415. search.set('limit', String(limit))
  416. const response = await upstream.request(path, jar, { search })
  417. if (!firstResponse) firstResponse = response
  418. if (response.status < 200 || response.status >= 300) return response
  419. const payload = parseJson(response)
  420. const key = Array.isArray(payload.items) ? 'items'
  421. : Array.isArray(payload.sessions) ? 'sessions' : undefined
  422. if (!key) return response
  423. if (!firstPayload) { firstPayload = payload; collectionKey = key }
  424. const values = payload[key] as unknown[]
  425. values.forEach((value, index) => {
  426. const item = value && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : undefined
  427. const id = item ? String(item.id ?? item.session_id ?? item.sessionId ?? '') : ''
  428. const profile = item ? String(item.profile ?? item.profile_name ?? '') : ''
  429. rows.set(id ? `${profile}\u0000${id}` : `${offset}\u0000${index}`, value)
  430. })
  431. const responseOffset = Math.max(0, Number(payload.offset ?? offset) || offset)
  432. const responseLimit = Math.max(1, Number(payload.limit ?? limit) || limit)
  433. const total = Math.max(0, Number(payload.total ?? 0) || 0)
  434. const nextOffset = responseOffset + responseLimit
  435. if (!values.length || (total > 0 && nextOffset >= total)
  436. || (total === 0 && values.length < responseLimit)) break
  437. if (nextOffset <= offset) throw new HttpError(502, 'Hermes session pagination did not advance', 'invalid_upstream_pagination')
  438. offset = nextOffset
  439. if (page === 999) throw new HttpError(502, 'Hermes session list is too large to project', 'upstream_pagination_limit')
  440. }
  441. const response = firstResponse!
  442. const payload = firstPayload!
  443. const headers = new Headers(response.headers)
  444. headers.delete('content-length')
  445. return {
  446. ...response,
  447. headers,
  448. body: Buffer.from(JSON.stringify({
  449. ...payload,
  450. [collectionKey!]: [...rows.values()],
  451. total: rows.size,
  452. offset: 0,
  453. limit: rows.size,
  454. })),
  455. }
  456. }
  457. async function proxyAdminFeature(
  458. ctx: Koa.Context,
  459. dependencies: RouteDependencies,
  460. path: string,
  461. options: {
  462. search?: URLSearchParams
  463. method?: string
  464. requestBody?: unknown
  465. } = {},
  466. ): Promise<void> {
  467. dependencies.auth.requireAdmin(ctx)
  468. await withJar(ctx, async (jar) => {
  469. const response = await dependencies.upstream.request(path, jar, {
  470. method: options.method,
  471. search: options.search,
  472. body: options.requestBody,
  473. })
  474. if (response.status === 404 || response.status === 405) {
  475. throw new HttpError(501, '当前上游版本不支持此管理功能', 'upstream_feature_unsupported')
  476. }
  477. sendUpstreamResponse(ctx, response, jar)
  478. })
  479. }
  480. const KANBAN_UPSTREAM_PREFIX = '/api/plugins/kanban'
  481. function sendKanbanUpstreamResponse(
  482. ctx: Koa.Context,
  483. response: UpstreamResponse,
  484. jar: CookieJar,
  485. ): void {
  486. if (response.status === 401) {
  487. throw new HttpError(502, '9119 Kanban 认证会话不可用', 'upstream_auth_unavailable')
  488. }
  489. sendUpstreamResponse(ctx, response, jar)
  490. }
  491. async function kanbanAvailability(
  492. ctx: Koa.Context,
  493. dependencies: RouteDependencies,
  494. ): Promise<void> {
  495. dependencies.auth.require(ctx)
  496. const probe = await dependencies.upstreamSession.request(`${KANBAN_UPSTREAM_PREFIX}/boards`)
  497. if (probe.status === 404 || probe.status === 405) {
  498. json(ctx, 200, {
  499. available: false,
  500. reason: '9119 未安装、未启用或未挂载 Kanban API',
  501. })
  502. return
  503. }
  504. if (probe.status < 200 || probe.status >= 300) {
  505. sendKanbanUpstreamResponse(ctx, probe, dependencies.upstreamSession.jar)
  506. return
  507. }
  508. let version: string | undefined
  509. try {
  510. const metadata = await dependencies.upstreamSession.request('/api/dashboard/plugins')
  511. if (metadata.status >= 200 && metadata.status < 300) {
  512. const manifests = parseJsonValue(metadata)
  513. if (Array.isArray(manifests)) {
  514. const manifest = manifests.find(entry => (
  515. entry && typeof entry === 'object' && !Array.isArray(entry)
  516. && (entry as JsonObject).name === 'kanban'
  517. )) as JsonObject | undefined
  518. if (typeof manifest?.version === 'string') version = manifest.version
  519. }
  520. }
  521. } catch { /* The mounted API is authoritative; metadata is optional. */ }
  522. json(ctx, 200, {
  523. available: true,
  524. version,
  525. })
  526. }
  527. async function proxyKanban(
  528. ctx: Koa.Context,
  529. dependencies: RouteDependencies,
  530. path: string | (() => string),
  531. options: {
  532. allowedQuery?: readonly string[]
  533. body?: 'required' | 'optional'
  534. boardRequired?: boolean
  535. requestBody?: () => JsonObject
  536. sanitizeTaskDetail?: boolean
  537. } = {},
  538. ): Promise<void> {
  539. if (ctx.method === 'GET' || ctx.method === 'HEAD') dependencies.auth.require(ctx)
  540. else dependencies.auth.requireAdmin(ctx)
  541. const resolvedPath = typeof path === 'function' ? path() : path
  542. const requestBody = options.requestBody?.() ?? (options.body === 'required' ? body(ctx)
  543. : options.body === 'optional' ? optionalBody(ctx) : undefined)
  544. const search = searchFrom(ctx, options.allowedQuery ?? [])
  545. if (options.boardRequired) {
  546. const boardValues = search.getAll('board')
  547. const board = boardValues[0]?.trim() ?? ''
  548. if (boardValues.length === 0 || !board) {
  549. throw new HttpError(400, 'Kanban board is required', 'kanban_board_required')
  550. }
  551. if (boardValues.length !== 1) {
  552. throw new HttpError(400, 'Kanban board must be provided exactly once', 'invalid_kanban_board')
  553. }
  554. if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(board)) {
  555. throw new HttpError(400, 'Kanban board is invalid', 'invalid_kanban_board')
  556. }
  557. search.set('board', board)
  558. }
  559. const upstreamPath = `${KANBAN_UPSTREAM_PREFIX}${resolvedPath}`
  560. if (options.sanitizeTaskDetail) {
  561. await withJar(ctx, async (jar) => {
  562. const response = await dependencies.upstream.request(upstreamPath, jar, {
  563. method: ctx.method,
  564. search,
  565. body: requestBody,
  566. })
  567. if (response.status < 200 || response.status >= 300) {
  568. sendKanbanUpstreamResponse(ctx, response, jar)
  569. return
  570. }
  571. const payload = parseJson(response)
  572. if (Object.prototype.hasOwnProperty.call(payload, 'attachments')) payload.attachments = []
  573. json(ctx, response.status, payload)
  574. })
  575. return
  576. }
  577. await withJar(ctx, async (jar) => {
  578. const response = await dependencies.upstream.request(upstreamPath, jar, {
  579. method: ctx.method,
  580. search,
  581. body: requestBody,
  582. })
  583. sendKanbanUpstreamResponse(ctx, response, jar)
  584. })
  585. }
  586. function kanbanBoardCreateBody(ctx: Koa.Context): JsonObject {
  587. const input = body(ctx)
  588. const output: JsonObject = {}
  589. for (const key of ['slug', 'name', 'description']) {
  590. if (Object.prototype.hasOwnProperty.call(input, key)) output[key] = input[key]
  591. }
  592. output.switch = false
  593. return output
  594. }
  595. function kanbanCommentBody(ctx: Koa.Context, dependencies: RouteDependencies): JsonObject {
  596. const input = body(ctx)
  597. const admin = dependencies.auth.requireAdmin(ctx)
  598. return {
  599. body: input.body,
  600. author: admin.username,
  601. }
  602. }
  603. function registerKanbanRoutes(router: Router, dependencies: RouteDependencies, prefix: string): void {
  604. router.get(`${prefix}/status`, async (ctx) => {
  605. await kanbanAvailability(ctx, dependencies)
  606. })
  607. router.get(`${prefix}/boards`, async (ctx) => {
  608. await proxyKanban(ctx, dependencies, '/boards', {
  609. allowedQuery: ['include_archived'],
  610. })
  611. })
  612. router.post(`${prefix}/boards`, async (ctx) => {
  613. await proxyKanban(ctx, dependencies, '/boards', {
  614. requestBody: () => kanbanBoardCreateBody(ctx),
  615. })
  616. })
  617. router.get(`${prefix}/board`, async (ctx) => {
  618. await proxyKanban(ctx, dependencies, '/board', {
  619. allowedQuery: ['board', 'include_archived'],
  620. boardRequired: true,
  621. })
  622. })
  623. router.get(`${prefix}/profiles`, async (ctx) => {
  624. await proxyKanban(ctx, dependencies, '/profiles')
  625. })
  626. router.get(`${prefix}/tasks/:taskID`, async (ctx) => {
  627. await proxyKanban(ctx, dependencies, () => {
  628. const id = safeIdentifier(ctx.params.taskID, 'Kanban task ID')
  629. return `/tasks/${encodeURIComponent(id)}`
  630. }, {
  631. allowedQuery: ['board', 'run_state_name', 'run_state_type'],
  632. boardRequired: true,
  633. sanitizeTaskDetail: true,
  634. })
  635. })
  636. router.post(`${prefix}/tasks`, async (ctx) => {
  637. await proxyKanban(ctx, dependencies, '/tasks', {
  638. allowedQuery: ['board'],
  639. boardRequired: true,
  640. body: 'required',
  641. })
  642. })
  643. router.patch(`${prefix}/tasks/:taskID`, async (ctx) => {
  644. await proxyKanban(ctx, dependencies, () => {
  645. const id = safeIdentifier(ctx.params.taskID, 'Kanban task ID')
  646. return `/tasks/${encodeURIComponent(id)}`
  647. }, {
  648. allowedQuery: ['board'],
  649. boardRequired: true,
  650. body: 'required',
  651. })
  652. })
  653. router.delete(`${prefix}/tasks/:taskID`, async (ctx) => {
  654. await proxyKanban(ctx, dependencies, () => {
  655. const id = safeIdentifier(ctx.params.taskID, 'Kanban task ID')
  656. return `/tasks/${encodeURIComponent(id)}`
  657. }, {
  658. allowedQuery: ['board'],
  659. boardRequired: true,
  660. body: 'optional',
  661. })
  662. })
  663. router.post(`${prefix}/tasks/:taskID/comments`, async (ctx) => {
  664. await proxyKanban(ctx, dependencies, () => {
  665. const id = safeIdentifier(ctx.params.taskID, 'Kanban task ID')
  666. return `/tasks/${encodeURIComponent(id)}/comments`
  667. }, {
  668. allowedQuery: ['board'],
  669. boardRequired: true,
  670. requestBody: () => kanbanCommentBody(ctx, dependencies),
  671. })
  672. })
  673. router.post(`${prefix}/dispatch`, async (ctx) => {
  674. await proxyKanban(ctx, dependencies, '/dispatch', {
  675. allowedQuery: ['board', 'dry_run', 'max'],
  676. boardRequired: true,
  677. body: 'optional',
  678. })
  679. })
  680. }
  681. async function proxyOptionalUnread(
  682. ctx: Koa.Context,
  683. upstream: UpstreamClient,
  684. path: string,
  685. options: {
  686. search?: URLSearchParams
  687. method?: string
  688. requestBody?: unknown
  689. },
  690. fallback: unknown,
  691. ): Promise<void> {
  692. await withJar(ctx, async (jar) => {
  693. const response = await upstream.request(path, jar, {
  694. method: options.method,
  695. search: options.search,
  696. body: options.requestBody,
  697. })
  698. if (response.status === 404 || response.status === 405) {
  699. json(ctx, 200, fallback)
  700. return
  701. }
  702. sendUpstreamResponse(ctx, response, jar)
  703. })
  704. }
  705. async function cachedChatRead(
  706. ctx: Koa.Context,
  707. dependencies: RouteDependencies,
  708. options: {
  709. key: string
  710. kind: 'list' | 'detail' | 'messages'
  711. profile: string
  712. sessionID?: string
  713. offset?: number
  714. limit?: number
  715. archived?: string
  716. ownedList?: boolean
  717. load: (jar: CookieJar) => Promise<UpstreamResponse>
  718. },
  719. ): Promise<void> {
  720. const user = dependencies.auth.require(ctx)
  721. const load = async () => {
  722. await dependencies.upstreamSession.ensure()
  723. return options.load(dependencies.upstreamSession.jar)
  724. }
  725. if (!dependencies.chatCache) {
  726. throw new HttpError(503, 'Chat ownership registry is unavailable', 'chat_registry_unavailable')
  727. }
  728. // Explicit native history browsing retains its independent upstream path.
  729. if(ctx.query.view==='history' || ctx.state.hermesBotNative || !ctx.path.startsWith('/api/app/')){
  730. const response=await load()
  731. sendUpstreamResponse(ctx,options.sessionID?dependencies.chatCache.store.markSessionOwnership(user.id,options.profile,options.sessionID,response):response,dependencies.upstreamSession.jar)
  732. return
  733. }
  734. const result = dependencies.chatCache.readLocal(user.id, options.kind, options.profile, options.sessionID,
  735. {offset:options.offset,limit:options.limit,archived:options.archived},ctx.get('x-yaoyao-cache').toLowerCase()==='bypass')
  736. ctx.set('X-Yaoyao-Data-Source', result.source)
  737. ctx.set('X-Yaoyao-Sync-State', result.state)
  738. sendUpstreamResponse(
  739. ctx,
  740. options.sessionID
  741. ? dependencies.chatCache.store.markSessionOwnership(
  742. user.id,
  743. options.profile,
  744. options.sessionID,
  745. result.response,
  746. )
  747. : result.response,
  748. dependencies.upstreamSession.jar,
  749. )
  750. }
  751. async function bootstrap(
  752. ctx: Koa.Context,
  753. dependencies: RouteDependencies,
  754. rotateCsrf = false,
  755. ): Promise<void> {
  756. const user = dependencies.auth.current(ctx)
  757. const csrfToken = dependencies.csrf.issue(ctx, rotateCsrf)
  758. if (!user) {
  759. json(ctx, 200, {
  760. status: { state: 'ready' },
  761. authRequired: true,
  762. authenticated: false,
  763. setupRequired: dependencies.auth.setupRequired,
  764. registrationAvailable: !dependencies.auth.setupRequired,
  765. profiles: [],
  766. csrfToken,
  767. insecureLan: dependencies.config.insecureLan,
  768. groupUploadsEnabled: true,
  769. upstreamReady: false,
  770. serverKind: 'yaoyao-web',
  771. })
  772. return
  773. }
  774. let status: JsonObject = { state: user.mustChangePassword ? 'password_change_required' : 'degraded' }
  775. let profiles: unknown[] = []
  776. let upstreamReady = false
  777. let upstreamError: string | undefined
  778. if (!user.mustChangePassword) {
  779. let timeout: ReturnType<typeof setTimeout> | undefined
  780. try {
  781. // Local login/settings must remain usable even when 9119 never responds.
  782. // Publish only a complete result; a late probe cannot mutate this response.
  783. const upstream = await Promise.race([
  784. (async () => {
  785. const statusResponse = await dependencies.upstreamSession.request('/api/status')
  786. const rawStatus = requireSuccess(statusResponse)
  787. const profilesResponse = await dependencies.upstreamSession.request('/api/profiles')
  788. return {
  789. status: publicStatus(rawStatus),
  790. profiles: profilesWithCoreNames(normalizedProfiles(requireSuccess(profilesResponse))),
  791. }
  792. })(),
  793. new Promise<never>((_resolve, reject) => {
  794. timeout = setTimeout(() => reject(new Error('9119 连接超时;仍可管理 15300 和升级 Web')), 3_000)
  795. timeout.unref()
  796. }),
  797. ])
  798. status = upstream.status
  799. profiles = user.role === 'admin' ? upstream.profiles : []
  800. upstreamReady = true
  801. } catch (error) {
  802. upstreamError = error instanceof Error ? error.message : '9119 不可用'
  803. } finally {
  804. if (timeout) clearTimeout(timeout)
  805. }
  806. }
  807. json(ctx, 200, {
  808. status,
  809. authRequired: true,
  810. authenticated: true,
  811. registrationAvailable: true,
  812. serverIdentity: readServerIdentity(dependencies.workspace),
  813. user,
  814. profiles,
  815. csrfToken,
  816. insecureLan: dependencies.config.insecureLan,
  817. groupUploadsEnabled: true,
  818. upstreamReady,
  819. upstreamError,
  820. serverKind: 'yaoyao-web',
  821. })
  822. }
  823. async function login(ctx: Koa.Context, dependencies: RouteDependencies): Promise<void> {
  824. const request = body(ctx)
  825. const username = typeof request.username === 'string' ? request.username.trim() : ''
  826. const password = typeof request.password === 'string' ? request.password : ''
  827. if (!username || !password || username.length > 320 || password.length > 4_096) {
  828. throw new HttpError(400, 'Username and password are required', 'invalid_credentials')
  829. }
  830. dependencies.auth.login(ctx, username, password)
  831. await bootstrap(ctx, dependencies, true)
  832. }
  833. async function setup(ctx: Koa.Context, dependencies: RouteDependencies): Promise<void> {
  834. const request = body(ctx)
  835. const username = typeof request.username === 'string' ? request.username : ''
  836. const password = typeof request.password === 'string' ? request.password : ''
  837. dependencies.auth.setupAdmin(ctx, username, password)
  838. await bootstrap(ctx, dependencies, true)
  839. }
  840. async function independentPairingCookies(
  841. ctx: Koa.Context,
  842. dependencies: RouteDependencies,
  843. authenticatedJar: CookieJar,
  844. request: JsonObject | undefined,
  845. ): Promise<string> {
  846. const status = requireSuccess(
  847. await dependencies.upstream.request('/api/status', authenticatedJar),
  848. )
  849. if (!authRequired(status)) {
  850. const cookies = authenticatedJar.header
  851. if (!cookies) throw new HttpError(401, 'Hermes session is unavailable', 'authentication_required')
  852. return cookies
  853. }
  854. const username = typeof request?.username === 'string' ? request.username.trim() : ''
  855. const password = typeof request?.password === 'string' ? request.password : ''
  856. if (!username || !password || username.length > 320 || password.length > 4_096) {
  857. throw new HttpError(
  858. 400,
  859. 'Hermes username and password are required to create an independent paired-device session',
  860. 'pairing_credentials_required',
  861. )
  862. }
  863. const jar = new CookieJar('')
  864. const providersBody = requireSuccess(
  865. await dependencies.upstream.request('/api/auth/providers', jar),
  866. )
  867. const providers = Array.isArray(providersBody.providers) ? providersBody.providers : []
  868. const provider = providers.find((entry) => Boolean(
  869. entry && typeof entry === 'object' && !Array.isArray(entry)
  870. && (entry as JsonObject).supports_password === true
  871. && String((entry as JsonObject).name).toLowerCase() === 'basic',
  872. )) as JsonObject | undefined
  873. if (!provider || typeof provider.name !== 'string') {
  874. throw new HttpError(
  875. 403,
  876. 'Hermes does not offer independent password sessions for QR pairing',
  877. 'pairing_login_unavailable',
  878. )
  879. }
  880. const response = await dependencies.upstream.request('/auth/password-login', jar, {
  881. method: 'POST',
  882. body: { provider: provider.name, username, password, next: '' },
  883. clientAddress: ctx.req.socket.remoteAddress,
  884. })
  885. const result = requireSuccess(response)
  886. if (result.ok !== true) throw new HttpError(401, 'Hermes rejected the pairing login', 'pairing_login_failed')
  887. await requireGatewayAuthentication(ctx, dependencies, jar)
  888. if (!jar.header) throw new HttpError(502, 'Hermes did not issue paired-device cookies', 'pairing_session_missing')
  889. return jar.header
  890. }
  891. async function requireGatewayAuthentication(
  892. ctx: Koa.Context,
  893. dependencies: RouteDependencies,
  894. jar: CookieJar,
  895. ): Promise<void> {
  896. const status = requireSuccess(await dependencies.upstream.request('/api/status', jar))
  897. if (!authRequired(status)) return
  898. const identity = await dependencies.upstream.request('/api/auth/me', jar, {
  899. clientAddress: ctx.req.socket.remoteAddress,
  900. })
  901. if (identity.status === 401 || identity.status === 403) {
  902. throw new HttpError(401, 'Hermes authentication is required', 'authentication_required')
  903. }
  904. requireSuccess(identity)
  905. }
  906. async function searchSessions(ctx: Koa.Context, dependencies: RouteDependencies): Promise<void> {
  907. const owner = dependencies.auth.require(ctx).id
  908. if (!dependencies.chatCache) {
  909. throw new HttpError(503, 'Chat ownership registry is unavailable', 'chat_registry_unavailable')
  910. }
  911. const chatCache = dependencies.chatCache
  912. await withJar(ctx, async (jar) => {
  913. const view = ctx.query.view === 'chat' || ctx.query.view === 'history'
  914. ? ctx.query.view : undefined
  915. const query = searchFrom(ctx, ['q', 'limit', 'source', 'profile'])
  916. const text = query.get('q')?.trim()
  917. if (!text) throw new HttpError(400, 'q is required', 'missing_query')
  918. const limit = Math.max(1, Math.min(100, Number(query.get('limit') ?? '50') || 50))
  919. query.set('limit', '100')
  920. if (view) query.delete('source')
  921. if (!query.get('source')) query.set('exclude_sources', 'cron,ios_group,yaoyao_workspace')
  922. if (query.get('profile')) {
  923. const response = await dependencies.upstream.request('/api/sessions/search', jar, { search: query })
  924. sendUpstreamResponse(
  925. ctx,
  926. chatCache.store.markOwnedSearchResults(
  927. owner,
  928. query.get('profile') || 'default',
  929. response,
  930. view,
  931. limit,
  932. ),
  933. jar,
  934. )
  935. return
  936. }
  937. const profilesResponse = await dependencies.upstream.request('/api/profiles', jar)
  938. const profileObjects = normalizedProfiles(requireSuccess(profilesResponse))
  939. const profiles = profileObjects.flatMap((entry) => {
  940. if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return []
  941. const name = (entry as JsonObject).name
  942. return typeof name === 'string' && name.trim() ? [name.trim()] : []
  943. })
  944. const results: JsonObject[] = []
  945. for (const profile of profiles) {
  946. const scoped = new URLSearchParams(query)
  947. scoped.set('profile', profile)
  948. const response = await dependencies.upstream.request('/api/sessions/search', jar, { search: scoped })
  949. const value = requireSuccess(response)
  950. for (const raw of Array.isArray(value.results) ? value.results : []) {
  951. if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
  952. results.push({ profile, ...(raw as JsonObject) })
  953. }
  954. }
  955. }
  956. results.sort((left, right) => {
  957. const leftRank = Number(left.rank ?? left.last_active ?? left.started_at ?? 0)
  958. const rightRank = Number(right.rank ?? right.last_active ?? right.started_at ?? 0)
  959. return rightRank - leftRank
  960. })
  961. const marked = results.map((result) => {
  962. const profile = typeof result.profile === 'string' ? result.profile : 'default'
  963. const id = String(result.id ?? result.session_id ?? result.sessionId ?? '')
  964. const metadata = id
  965. ? chatCache.store.ownedSessionMetadata(owner, profile, id)
  966. : { owned: false }
  967. return {
  968. ...result,
  969. ...(metadata.authoritativeTitle ? { title: metadata.authoritativeTitle } : {}),
  970. owned: metadata.owned,
  971. }
  972. })
  973. const projected = marked.filter(result => !view
  974. || (view === 'chat' ? result.owned : !result.owned))
  975. json(ctx, 200, { results: projected.slice(0, limit), total: projected.length })
  976. })
  977. }
  978. function localMediaPath(root: string, relativePath: string): string {
  979. let resolvedRoot: string
  980. let resolvedFile: string
  981. try {
  982. resolvedRoot = realpathSync(root)
  983. resolvedFile = realpathSync(resolve(resolvedRoot, relativePath))
  984. } catch {
  985. throw new HttpError(404, '本地文件不存在', 'local_media_not_found')
  986. }
  987. if (!resolvedFile.startsWith(`${resolvedRoot}${sep}`) || !statSync(resolvedFile).isFile()) {
  988. throw new HttpError(404, '本地文件不存在', 'local_media_not_found')
  989. }
  990. return resolvedFile
  991. }
  992. function sendLocalMedia(ctx: Koa.Context, path: string, contentType?: string, displayName?: string): void {
  993. const size = statSync(path).size
  994. const type = contentType || mimeLookup(path) || 'application/octet-stream'
  995. const fileName = displayName || basename(path)
  996. const range = ctx.get('range').match(/^bytes=(\d*)-(\d*)$/)
  997. ctx.set('Accept-Ranges', 'bytes')
  998. ctx.set('Cache-Control', 'private, no-store')
  999. ctx.set('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(fileName)}`)
  1000. ctx.type = type
  1001. if (!range) {
  1002. ctx.length = size
  1003. ctx.body = createReadStream(path)
  1004. return
  1005. }
  1006. const start = range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2] || 0))
  1007. const end = range[2] ? Number(range[2]) : size - 1
  1008. if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || start >= size) {
  1009. ctx.status = 416
  1010. ctx.set('Content-Range', `bytes */${size}`)
  1011. return
  1012. }
  1013. const boundedEnd = Math.min(end, size - 1)
  1014. ctx.status = 206
  1015. ctx.set('Content-Range', `bytes ${start}-${boundedEnd}/${size}`)
  1016. ctx.length = boundedEnd - start + 1
  1017. ctx.body = createReadStream(path, { start, end: boundedEnd })
  1018. }
  1019. function prepareFilePreview(ctx: Koa.Context, name: string, preserveDisposition = false): void {
  1020. const type = ctx.response.get('content-type').split(';', 1)[0]?.trim().toLowerCase()
  1021. const activeContent = type === 'text/html'
  1022. || type === 'application/xhtml+xml'
  1023. || type === 'image/svg+xml'
  1024. || Boolean(type?.endsWith('/xml') || type?.endsWith('+xml'))
  1025. if (activeContent) {
  1026. ctx.type = 'application/octet-stream'
  1027. ctx.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(name)}`)
  1028. } else if (!preserveDisposition) {
  1029. ctx.remove('Content-Disposition')
  1030. }
  1031. }
  1032. function hermesMediaPath(ctx: Koa.Context, rootDirectory = 'cache'): string {
  1033. const segment = (value: string): string => {
  1034. if (!value || value === '.' || value === '..' || /[/\\\u0000-\u001f\u007f]/.test(value)) {
  1035. throw new HttpError(400, '媒体路径无效', 'invalid_media_path')
  1036. }
  1037. return value
  1038. }
  1039. const owner = segment(ctx.params.owner)
  1040. const profile = ctx.params.profile ? segment(ctx.params.profile) : undefined
  1041. const directory = profile ? ctx.params.mediaDir : rootDirectory
  1042. if (!['cache', 'images', 'screenshots', 'attachments', 'workspace'].includes(directory)) {
  1043. throw new HttpError(404, '媒体目录不存在', 'media_not_found')
  1044. }
  1045. const raw = ctx.params.filePath
  1046. const parts = (Array.isArray(raw) ? raw : [raw]).flatMap(part => part.split('/')).map(segment)
  1047. return `/Users/${owner}/.hermes/${profile ? `profiles/${profile}/` : ''}${directory}/${parts.join('/')}`
  1048. }
  1049. async function proxyHermesMedia(ctx: Koa.Context, dependencies: RouteDependencies, rootDirectory = 'cache'): Promise<void> {
  1050. const user = dependencies.auth.require(ctx)
  1051. const path = await authorizeFileRead(dependencies.config, dependencies.upstreamSession, hermesMediaPath(ctx, rootDirectory), ctx.params.profile || String(ctx.query.profile || ctx.get('x-hermes-profile') || 'default'))
  1052. const cached = dependencies.chatCache?.store.attachment(user.id, path)
  1053. if (cached) {
  1054. ctx.set('X-Yaoyao-Data-Source', 'local')
  1055. sendLocalMedia(ctx, cached.localPath, cached.mimeType, basename(path))
  1056. prepareFilePreview(ctx, basename(path), true)
  1057. return
  1058. }
  1059. // Generated media belongs to Hermes, which may run on a different machine
  1060. // or inside a container. Let its file API enforce the managed-root policy.
  1061. const response = await dependencies.upstreamSession.request('/api/files/download', {
  1062. search: new URLSearchParams({ path }),
  1063. headers: ctx.get('range') ? { range: ctx.get('range') } : undefined,
  1064. maxResponseBytes: 100 * 1_024 * 1_024,
  1065. })
  1066. ctx.set('X-Yaoyao-Data-Source', 'upstream')
  1067. if (!ctx.get('range') && dependencies.chatCache?.store.knowsAttachment(user.id, path)) {
  1068. dependencies.chatCache.store.storeAttachment(user.id, path, response)
  1069. } else if (ctx.get('range')) {
  1070. void dependencies.chatCache?.cacheAttachment(user.id, path)
  1071. }
  1072. sendUpstreamResponse(ctx, response, dependencies.upstreamSession.jar)
  1073. ctx.set('Cache-Control', 'private, no-store')
  1074. if (response.status >= 200 && response.status < 300) prepareFilePreview(ctx, basename(path))
  1075. }
  1076. function pairedLocalMediaPath(config: ServerConfig, rawPath: string): string {
  1077. if (!rawPath || rawPath.length > 8_192 || rawPath.includes('\u0000')) {
  1078. throw new HttpError(400, '远程文件路径无效', 'invalid_node_file_path')
  1079. }
  1080. let file: string
  1081. try { file = realpathSync(rawPath) } catch {
  1082. throw new HttpError(404, '远程文件不存在', 'node_file_not_found')
  1083. }
  1084. const roots = [config.mediaRoot, config.attachmentsRoot, config.imagesRoot].flatMap(root => {
  1085. try { return [realpathSync(root)] } catch { return [] }
  1086. })
  1087. if (!roots.some(root => file.startsWith(`${root}${sep}`)) || !statSync(file).isFile()) {
  1088. throw new HttpError(403, '远程文件不在允许的目录中', 'node_file_forbidden')
  1089. }
  1090. return file
  1091. }
  1092. export function createApiRouter(dependencies: RouteDependencies): Router {
  1093. const router = new Router()
  1094. const registrations = new RegistrationLimiter()
  1095. const fileReadRequest = (ctx: Koa.Context, path: string) => ['GET', 'HEAD'].includes(ctx.method)
  1096. && /^\/api\/(?:files(?:\/[^/]+)?|fs\/[^/]+|media|hermes\/download)$/.test(path)
  1097. const authorizeFileQuery = async (ctx: Koa.Context, route: string, host: Pick<UpstreamServiceSession, 'request'> = dependencies.upstreamSession) => {
  1098. const profile = String(ctx.query.profile || ctx.get('x-hermes-profile') || 'default')
  1099. const directoryRequest = ['/api/files', '/api/fs/list', '/api/fs/git-root'].includes(route)
  1100. const rawPath = ctx.query.path || (directoryRequest ? await fileAccessWorkingDirectory(host, profile) : undefined)
  1101. if (typeof rawPath === 'string') {
  1102. const path = await authorizeFileRead(dependencies.config, host, rawPath, profile, directoryRequest)
  1103. const search = new URLSearchParams(ctx.querystring)
  1104. search.set('path', path)
  1105. search.set('profile', profile)
  1106. ctx.querystring = search.toString()
  1107. }
  1108. }
  1109. router.use(async (ctx, next) => {
  1110. if (fileReadRequest(ctx, ctx.path)) {
  1111. dependencies.auth.require(ctx)
  1112. await authorizeFileQuery(ctx, ctx.path)
  1113. }
  1114. await next()
  1115. })
  1116. router.get('/api/app/settings/file-access', async ctx => {
  1117. dependencies.auth.require(ctx)
  1118. const settings = readFileAccess(dependencies.config.home)
  1119. const profile = String(ctx.query.profile || ctx.get('x-hermes-profile') || 'default')
  1120. try { json(ctx, 200, { ...settings, profile, workingDirectory: await fileAccessWorkingDirectory(dependencies.upstreamSession, profile) }) }
  1121. catch (error) { json(ctx, 200, { ...settings, profile, workingDirectory: null, cwdError: error instanceof Error ? error.message : '无法读取工作目录' }) }
  1122. })
  1123. router.put('/api/app/settings/file-access', ctx => {
  1124. dependencies.auth.requireAdmin(ctx)
  1125. json(ctx, 200, saveFileAccess(dependencies.config.home, body(ctx)))
  1126. })
  1127. router.get('/api/app/settings/host-tools', ctx => {
  1128. dependencies.auth.require(ctx)
  1129. json(ctx, 200, readHostTools(dependencies.config.home))
  1130. })
  1131. router.put('/api/app/settings/host-tools', ctx => {
  1132. dependencies.auth.requireAdmin(ctx)
  1133. json(ctx, 200, saveHostTools(dependencies.config.home, body(ctx)))
  1134. })
  1135. registerKanbanRoutes(router, dependencies, '/api/app/kanban')
  1136. registerKanbanRoutes(router, dependencies, '/api/kanban/v1')
  1137. router.get('/healthz', (ctx) => {
  1138. ctx.set('Cache-Control', 'no-store')
  1139. json(ctx, 200, {
  1140. ok: true,
  1141. chatCache: dependencies.chatCache
  1142. ? { available: true, mode: dependencies.chatCache.mode, ...dependencies.chatCache.store.stats(), reads: dependencies.chatCache.diagnostics }
  1143. : { available: false, mode: dependencies.config.chatCacheMode ?? 'upstream-only' },
  1144. })
  1145. })
  1146. // Hermes Gateway-compatible authentication surface for native clients.
  1147. // Content requests are still executed through the server-owned 9119 session.
  1148. router.get('/api/status', (ctx) => {
  1149. json(ctx, 200, {
  1150. overall: 'ready',
  1151. auth_required: true,
  1152. gateway_running: true,
  1153. server_kind: 'yaoyao-web',
  1154. node_transport: '15300',
  1155. })
  1156. })
  1157. router.get('/api/auth/providers', (ctx) => {
  1158. json(ctx, 200, { providers: [{ name: 'basic', supports_password: true }] })
  1159. })
  1160. router.post('/auth/password-login', async (ctx) => {
  1161. const request = body(ctx)
  1162. const username = typeof request.username === 'string' ? request.username : ''
  1163. const password = typeof request.password === 'string' ? request.password : ''
  1164. const user = dependencies.auth.login(ctx, username, password)
  1165. json(ctx, 200, { ok: true, must_change_password: user.mustChangePassword, server_kind: 'yaoyao-web' })
  1166. })
  1167. router.post('/auth/logout', (ctx) => {
  1168. dependencies.auth.logout(ctx)
  1169. json(ctx, 200, { ok: true })
  1170. })
  1171. router.get('/api/auth/me', (ctx) => {
  1172. const user = dependencies.auth.require(ctx, true)
  1173. json(ctx, 200, {
  1174. user_id: user.id,
  1175. display_name: user.username,
  1176. username: user.username,
  1177. avatar: user.avatar,
  1178. provider: 'yaoyao-local',
  1179. role: user.role,
  1180. must_change_password: user.mustChangePassword,
  1181. server_kind: 'yaoyao-web',
  1182. })
  1183. })
  1184. router.get('/api/profile-identities', async (ctx) => {
  1185. dependencies.auth.require(ctx, true)
  1186. json(ctx, 200, { profiles: await dependencies.profileIdentities.load() })
  1187. })
  1188. router.get('/api/profiles', async (ctx) => {
  1189. if (dependencies.auth.require(ctx, true).role !== 'admin') { json(ctx, 200, { profiles: [] }); return }
  1190. const profilesResponse = await dependencies.upstreamSession.request('/api/profiles')
  1191. json(ctx, profilesResponse.status, {
  1192. profiles: profilesWithCoreNames(normalizedProfiles(requireSuccess(profilesResponse))),
  1193. })
  1194. })
  1195. router.get('/api/push/v1/capabilities', (ctx) => {
  1196. dependencies.auth.require(ctx)
  1197. const capabilities = dependencies.push.capabilities()
  1198. json(ctx, 200, {
  1199. ...capabilities,
  1200. maximumSummaryCharacters: capabilities.maxSummaryCharacters,
  1201. })
  1202. })
  1203. router.put('/api/push/v1/installations/:installationID/accounts/:clientAccountID', (ctx) => {
  1204. const user = dependencies.auth.require(ctx)
  1205. const request = body(ctx)
  1206. const platform = request.platform === undefined || request.platform === 'ios' ? 'ios'
  1207. : request.platform === 'android' ? 'android' : undefined
  1208. if (!platform) {
  1209. throw new HttpError(400, 'platform must be ios or android', 'invalid_push_request')
  1210. }
  1211. if (platform === 'ios' && request.environment !== 'development' && request.environment !== 'production') {
  1212. throw new HttpError(400, 'environment must be development or production', 'invalid_push_request')
  1213. }
  1214. const common = {
  1215. userId: user.id,
  1216. installationId: canonicalUUID(ctx.params.installationID, 'installation ID'),
  1217. clientAccountId: canonicalUUID(ctx.params.clientAccountID, 'client account ID'),
  1218. appVersion: typeof request.appVersion === 'string' ? request.appVersion : undefined,
  1219. authorizationVersion: dependencies.auth.pushAuthorizationVersion(user.id),
  1220. }
  1221. const installation = platform === 'android'
  1222. ? pushRequest(() => dependencies.push.registerInstallation({
  1223. ...common,
  1224. platform: 'android',
  1225. fid: typeof request.fid === 'string' ? request.fid : '',
  1226. }))
  1227. : pushRequest(() => dependencies.push.registerInstallation({
  1228. ...common,
  1229. platform: 'ios',
  1230. deviceToken: typeof request.token === 'string'
  1231. ? request.token
  1232. : typeof request.deviceToken === 'string' ? request.deviceToken : '',
  1233. environment: request.environment as 'development' | 'production',
  1234. }))
  1235. json(ctx, 200, { installation })
  1236. })
  1237. router.delete('/api/push/v1/installations/:installationID/accounts/:clientAccountID', (ctx) => {
  1238. const user = dependencies.auth.require(ctx)
  1239. const removed = pushRequest(() => dependencies.push.unregisterInstallation(
  1240. user.id,
  1241. canonicalUUID(ctx.params.installationID, 'installation ID'),
  1242. canonicalUUID(ctx.params.clientAccountID, 'client account ID'),
  1243. ))
  1244. json(ctx, 200, { ok: true, removed })
  1245. })
  1246. router.post('/api/push/v1/installations/:installationID/accounts/:clientAccountID/badge-reset', (ctx) => {
  1247. const user = dependencies.auth.require(ctx)
  1248. const badge = pushRequest(() => dependencies.push.resetBadge(
  1249. user.id,
  1250. canonicalUUID(ctx.params.installationID, 'installation ID'),
  1251. canonicalUUID(ctx.params.clientAccountID, 'client account ID'),
  1252. ))
  1253. json(ctx, 200, { badge })
  1254. })
  1255. router.get('/api/push/v1/group-subscriptions', (ctx) => {
  1256. const user = dependencies.auth.require(ctx)
  1257. const subscriptions = dependencies.push.listGroupSubscriptions(user.id).filter(s => dependencies.workspace.get<WorkspaceConversation>(user.id,'conversation',s.roomId)?.kind === 'group')
  1258. json(ctx, 200, {
  1259. subscriptions,
  1260. roomIds: subscriptions.filter(item => item.enabled).map(item => item.roomId),
  1261. })
  1262. })
  1263. router.put('/api/push/v1/group-subscriptions/:roomID', async (ctx) => {
  1264. const user = dependencies.auth.require(ctx)
  1265. const request = body(ctx)
  1266. if (typeof request.enabled !== 'boolean') {
  1267. throw new HttpError(400, 'enabled must be a boolean', 'invalid_push_request')
  1268. }
  1269. const enabled = request.enabled
  1270. const roomID = canonicalUUID(ctx.params.roomID, 'room ID')
  1271. const baseline = enabled ? await latestGroupMessageSequence(dependencies, roomID, user.id) : undefined
  1272. const subscription = pushRequest(() => dependencies.push.setGroupSubscription(
  1273. user.id,
  1274. roomID,
  1275. enabled,
  1276. baseline,
  1277. ))
  1278. json(ctx, 200, { subscription, enabled: subscription.enabled })
  1279. })
  1280. // Browser aliases stay inside the /api/app CSRF boundary. Native iOS uses
  1281. // the Gateway-compatible /api/push/v1 surface with the same account state.
  1282. router.get('/api/app/push/v1/capabilities', (ctx) => {
  1283. dependencies.auth.require(ctx)
  1284. const capabilities = dependencies.push.capabilities()
  1285. json(ctx, 200, {
  1286. ...capabilities,
  1287. maximumSummaryCharacters: capabilities.maxSummaryCharacters,
  1288. })
  1289. })
  1290. router.get('/api/app/push/v1/group-subscriptions', (ctx) => {
  1291. const user = dependencies.auth.require(ctx)
  1292. const subscriptions = dependencies.push.listGroupSubscriptions(user.id).filter(s => dependencies.workspace.get<WorkspaceConversation>(user.id,'conversation',s.roomId)?.kind === 'group')
  1293. json(ctx, 200, {
  1294. subscriptions,
  1295. roomIds: subscriptions.filter(item => item.enabled).map(item => item.roomId),
  1296. })
  1297. })
  1298. router.put('/api/app/push/v1/group-subscriptions/:roomID', async (ctx) => {
  1299. const user = dependencies.auth.require(ctx)
  1300. const request = body(ctx)
  1301. if (typeof request.enabled !== 'boolean') {
  1302. throw new HttpError(400, 'enabled must be a boolean', 'invalid_push_request')
  1303. }
  1304. const enabled = request.enabled
  1305. const roomID = canonicalUUID(ctx.params.roomID, 'room ID')
  1306. const baseline = enabled ? await latestGroupMessageSequence(dependencies, roomID, user.id) : undefined
  1307. const subscription = pushRequest(() => dependencies.push.setGroupSubscription(
  1308. user.id,
  1309. roomID,
  1310. enabled,
  1311. baseline,
  1312. ))
  1313. json(ctx, 200, { subscription, enabled: subscription.enabled })
  1314. })
  1315. router.put('/api/account/credentials', (ctx) => {
  1316. const request = body(ctx)
  1317. const currentPassword = typeof request.currentPassword === 'string' ? request.currentPassword : ''
  1318. const newPassword = typeof request.newPassword === 'string' ? request.newPassword : ''
  1319. const username = typeof request.username === 'string' ? request.username : undefined
  1320. const user = dependencies.auth.changeCredentials(ctx, currentPassword, newPassword, username)
  1321. json(ctx, 200, { user, must_change_password: false, server_kind: 'yaoyao-web' })
  1322. })
  1323. router.post('/api/app/account-pairings', (ctx) => {
  1324. const user = dependencies.auth.require(ctx)
  1325. const pairing = dependencies.accountPairings.create(user.id)
  1326. const origin = requestOrigin(ctx, dependencies.config)
  1327. const deepLink = new URL('yaoyao://login')
  1328. deepLink.searchParams.set('v', '1')
  1329. deepLink.searchParams.set('url', origin)
  1330. deepLink.searchParams.set('id', pairing.id)
  1331. deepLink.searchParams.set('secret', pairing.secret)
  1332. json(ctx, 201, {
  1333. protocolVersion: 1,
  1334. serviceType: 'yaoyao-web',
  1335. pairingId: pairing.id,
  1336. expiresAt: pairing.expiresAt,
  1337. qrPayload: deepLink.toString(),
  1338. })
  1339. })
  1340. router.get('/api/app/account-pairings/:pairingID', (ctx) => {
  1341. dependencies.auth.require(ctx)
  1342. json(ctx, 200, dependencies.accountPairings.status(ctx.params.pairingID))
  1343. })
  1344. router.get('/api/account-pair/v1/capabilities', (ctx) => {
  1345. json(ctx, 200, {
  1346. protocolVersion: 1,
  1347. serviceType: 'yaoyao-web',
  1348. feature: 'server-login',
  1349. })
  1350. })
  1351. router.post('/api/account-pair/v1/claim', (ctx) => {
  1352. const request = body(ctx)
  1353. const pairingID = typeof request.pairingId === 'string' ? request.pairingId : ''
  1354. const secret = typeof request.secret === 'string' ? request.secret : ''
  1355. const userID = dependencies.accountPairings.claim(pairingID, secret)
  1356. const user = dependencies.auth.issueSession(ctx, userID)
  1357. json(ctx, 201, {
  1358. protocolVersion: 1,
  1359. serviceType: 'yaoyao-web',
  1360. serverUrl: requestOrigin(ctx, dependencies.config),
  1361. user,
  1362. })
  1363. })
  1364. router.post('/api/app/pairings', async (ctx) => {
  1365. const pairingOwner = dependencies.auth.requireAdmin(ctx)
  1366. await withJar(ctx, async (jar) => {
  1367. await requireGatewayAuthentication(ctx, dependencies, jar)
  1368. const request = optionalBody(ctx)
  1369. const cookieHeader = jar.header
  1370. if (!cookieHeader) throw new HttpError(503, '9119 服务会话尚未就绪', 'upstream_session_missing')
  1371. const pairing = dependencies.pairings.create(
  1372. cookieHeader,
  1373. pairingScopes(request?.scopes),
  1374. pairingOwner.id,
  1375. )
  1376. const origin = requestOrigin(ctx, dependencies.config)
  1377. const deepLink = new URL('yaoyao://pair')
  1378. deepLink.searchParams.set('v', String(NODE_PAIRING_PROTOCOL_VERSION))
  1379. deepLink.searchParams.set('url', origin)
  1380. deepLink.searchParams.set('node', pairing.nodeID)
  1381. deepLink.searchParams.set('id', pairing.id)
  1382. deepLink.searchParams.set('secret', pairing.secret)
  1383. deepLink.searchParams.set('fingerprint', pairing.fingerprint)
  1384. json(ctx, 201, {
  1385. protocolVersion: NODE_PAIRING_PROTOCOL_VERSION,
  1386. serviceType: 'yaoyao-web',
  1387. pairingId: pairing.id,
  1388. nodeId: pairing.nodeID,
  1389. fingerprint: pairing.fingerprint,
  1390. scopes: pairing.scopes,
  1391. expiresAt: pairing.expiresAt,
  1392. qrPayload: deepLink.toString(),
  1393. })
  1394. })
  1395. })
  1396. router.get('/api/app/pairings/:pairingID', async (ctx) => {
  1397. dependencies.auth.requireAdmin(ctx)
  1398. await withJar(ctx, async (jar) => {
  1399. await requireGatewayAuthentication(ctx, dependencies, jar)
  1400. json(ctx, 200, dependencies.pairings.status(ctx.params.pairingID))
  1401. })
  1402. })
  1403. router.get('/api/app/paired-devices', async (ctx) => {
  1404. dependencies.auth.requireAdmin(ctx)
  1405. await withJar(ctx, async (jar) => {
  1406. await requireGatewayAuthentication(ctx, dependencies, jar)
  1407. json(ctx, 200, {
  1408. nodeId: dependencies.pairings.nodeID,
  1409. fingerprint: dependencies.pairings.fingerprint,
  1410. devices: dependencies.pairings.list(),
  1411. })
  1412. })
  1413. })
  1414. router.delete('/api/app/paired-devices/:deviceID', async (ctx) => {
  1415. dependencies.auth.requireAdmin(ctx)
  1416. await withJar(ctx, async (jar) => {
  1417. await requireGatewayAuthentication(ctx, dependencies, jar)
  1418. try {
  1419. const delegated = new CookieJar(
  1420. dependencies.pairings.delegatedCookies(ctx.params.deviceID),
  1421. )
  1422. await dependencies.upstream.request('/auth/logout', delegated, {
  1423. method: 'POST', clientAddress: ctx.req.socket.remoteAddress,
  1424. })
  1425. } catch {
  1426. // Revocation of the local delegation remains authoritative even when
  1427. // Hermes is temporarily unreachable; its cookie is never returned.
  1428. }
  1429. if (!dependencies.pairings.revoke(ctx.params.deviceID)) {
  1430. throw new HttpError(404, 'Paired device was not found', 'paired_device_not_found')
  1431. }
  1432. json(ctx, 200, { ok: true })
  1433. })
  1434. })
  1435. router.post('/api/pair/v1/claim', (ctx) => {
  1436. const request = body(ctx)
  1437. const pairingID = typeof request.pairingId === 'string' ? request.pairingId : ''
  1438. const secret = typeof request.secret === 'string' ? request.secret : ''
  1439. const deviceName = typeof request.deviceName === 'string' ? request.deviceName : ''
  1440. const existingDeviceID = typeof request.existingDeviceId==='string' ? request.existingDeviceId : undefined
  1441. const claimed = dependencies.pairings.claim({ pairingID, secret, deviceName, existingDeviceID,
  1442. existingToken: existingDeviceID ? bearerToken(ctx.get('authorization')) : undefined })
  1443. const origin = requestOrigin(ctx, dependencies.config)
  1444. json(ctx, 201, {
  1445. protocolVersion: NODE_PAIRING_PROTOCOL_VERSION,
  1446. serviceType: 'yaoyao-web',
  1447. nodeId: claimed.nodeID,
  1448. fingerprint: claimed.fingerprint,
  1449. deviceId: claimed.device.id,
  1450. deviceName: claimed.device.name,
  1451. token: claimed.token,
  1452. scopes: claimed.scopes,
  1453. serverUrl: `${origin}/node/${claimed.device.id}`,
  1454. })
  1455. })
  1456. router.get('/api/pair/v1/capabilities', (ctx) => {
  1457. json(ctx, 200, {
  1458. protocolVersion: NODE_PAIRING_PROTOCOL_VERSION,
  1459. serviceType: 'yaoyao-web',
  1460. nodeId: dependencies.pairings.nodeID,
  1461. fingerprint: dependencies.pairings.fingerprint,
  1462. scopes: [...DEFAULT_NODE_SCOPES],
  1463. features: ['bots', 'history', 'workspace-agents', 'pair-renewal'],
  1464. })
  1465. })
  1466. router.delete('/api/pair/v1/devices/:deviceID', async (ctx) => {
  1467. const token = bearerToken(ctx.get('authorization'))
  1468. const cookies = dependencies.pairings.authorize(ctx.params.deviceID, token)
  1469. try {
  1470. await dependencies.upstream.request('/auth/logout', new CookieJar(cookies), {
  1471. method: 'POST', clientAddress: ctx.req.socket.remoteAddress,
  1472. })
  1473. } catch {
  1474. // The paired bearer is revoked locally even if upstream logout fails.
  1475. }
  1476. if (!dependencies.pairings.revoke(ctx.params.deviceID)) {
  1477. throw new HttpError(404, 'Paired device was not found', 'paired_device_not_found')
  1478. }
  1479. json(ctx, 200, { ok: true })
  1480. })
  1481. router.get('/node/:deviceID/api/node-files', (ctx) => {
  1482. const token = bearerToken(ctx.get('authorization'))
  1483. dependencies.pairings.authorize(
  1484. ctx.params.deviceID,
  1485. token,
  1486. 'history.read',
  1487. )
  1488. const value = typeof ctx.query.path === 'string' ? ctx.query.path : ''
  1489. sendLocalMedia(
  1490. ctx,
  1491. pairedLocalMediaPath(dependencies.config, value),
  1492. )
  1493. })
  1494. router.get('/node/:deviceID/api/profile-identities', async (ctx) => {
  1495. const token = bearerToken(ctx.get('authorization'))
  1496. dependencies.pairings.authorize(
  1497. ctx.params.deviceID,
  1498. token,
  1499. 'agents.read',
  1500. )
  1501. json(ctx, 200, { profiles: await dependencies.profileIdentities.load() })
  1502. })
  1503. router.all('/node/:deviceID/api/*nodePath', async (ctx) => {
  1504. const rawPath = Array.isArray(ctx.params.nodePath)
  1505. ? ctx.params.nodePath.join('/')
  1506. : ctx.params.nodePath
  1507. const path = pairedProxyPath(rawPath)
  1508. if (isNativeSessionMutation(path.slice('/api'.length), ctx.method)) {
  1509. nativeSessionsReadOnly()
  1510. }
  1511. const scope = pairedProxyScope(path.slice('/api'.length), ctx.method)
  1512. const token = bearerToken(ctx.get('authorization'))
  1513. const cookieHeader = dependencies.pairings.authorize(
  1514. ctx.params.deviceID,
  1515. token,
  1516. scope,
  1517. )
  1518. if (ctx.querystring.length > 8_192) {
  1519. throw new HttpError(414, 'Paired node query is too long', 'node_query_too_long')
  1520. }
  1521. const jar = new CookieJar(cookieHeader)
  1522. if (fileReadRequest(ctx, path)) await authorizeFileQuery(ctx, path, {
  1523. request: (path, options) => dependencies.upstream.request(path, jar, options),
  1524. })
  1525. const response = await dependencies.upstream.withReadScope(`device:${ctx.params.deviceID}`, ctx.get('x-yaoyao-cache') === 'bypass', () => dependencies.upstream.request(path, jar, {
  1526. method: ctx.method,
  1527. search: new URLSearchParams(ctx.querystring),
  1528. body: ['GET', 'HEAD'].includes(ctx.method)
  1529. ? undefined : optionalBody(ctx),
  1530. headers: { 'x-yaoyao-node-client': ctx.params.deviceID },
  1531. clientAddress: path === '/api/auth/ws-ticket'
  1532. ? undefined : ctx.req.socket.remoteAddress,
  1533. }))
  1534. dependencies.pairings.updateCookies(ctx.params.deviceID, jar.header)
  1535. sendUpstreamResponse(ctx, response, jar)
  1536. })
  1537. // Keep the original URL usable by inline Markdown, the lightbox and downloads.
  1538. // These root/profile cache paths are not files on the Web server itself.
  1539. router.get('/Users/:owner/.hermes/cache/*filePath', ctx => proxyHermesMedia(ctx, dependencies))
  1540. router.get('/Users/:owner/.hermes/workspace/*filePath', ctx => proxyHermesMedia(ctx, dependencies, 'workspace'))
  1541. router.get('/Users/:owner/.hermes/profiles/:profile/:mediaDir/*filePath', ctx => proxyHermesMedia(ctx, dependencies))
  1542. // Historical messages can contain Markdown links such as
  1543. // /Users/<owner>/Agents/<path>. Map only the configured media root, never
  1544. // an arbitrary local filesystem path.
  1545. router.get('/Users/:owner/Agents/*filePath', async (ctx) => {
  1546. if (!isLoopbackUpstream(dependencies.config.upstream)) {
  1547. throw new HttpError(409, '本地媒体只支持回环 Hermes 上游', 'remote_local_media_disabled')
  1548. }
  1549. if (ctx.params.owner !== dependencies.config.mediaOwner) {
  1550. throw new HttpError(404, '本地文件不存在', 'local_media_not_found')
  1551. }
  1552. await withJar(ctx, async (jar) => {
  1553. await requireGatewayAuthentication(ctx, dependencies, jar)
  1554. const filePath = Array.isArray(ctx.params.filePath) ? ctx.params.filePath.join('/') : ctx.params.filePath
  1555. const path = await authorizeFileRead(dependencies.config, dependencies.upstreamSession, localMediaPath(dependencies.config.mediaRoot, filePath))
  1556. sendLocalMedia(ctx, path)
  1557. prepareFilePreview(ctx, basename(path), true)
  1558. })
  1559. })
  1560. router.get('/Users/:owner/.hermes/attachments/*filePath', async (ctx) => {
  1561. if (!isLoopbackUpstream(dependencies.config.upstream)) {
  1562. throw new HttpError(409, '本地附件只支持回环 Hermes 上游', 'remote_local_media_disabled')
  1563. }
  1564. if (ctx.params.owner !== dependencies.config.mediaOwner) {
  1565. throw new HttpError(404, '本地附件不存在', 'local_media_not_found')
  1566. }
  1567. await withJar(ctx, async (jar) => {
  1568. await requireGatewayAuthentication(ctx, dependencies, jar)
  1569. const filePath = Array.isArray(ctx.params.filePath) ? ctx.params.filePath.join('/') : ctx.params.filePath
  1570. const path = await authorizeFileRead(dependencies.config, dependencies.upstreamSession, localMediaPath(dependencies.config.attachmentsRoot, filePath))
  1571. sendLocalMedia(ctx, path)
  1572. prepareFilePreview(ctx, basename(path), true)
  1573. })
  1574. })
  1575. router.get('/Users/:owner/.hermes/images/*filePath', async (ctx) => {
  1576. if (!isLoopbackUpstream(dependencies.config.upstream)) {
  1577. throw new HttpError(409, '本地图片只支持回环 Hermes 上游', 'remote_local_media_disabled')
  1578. }
  1579. if (ctx.params.owner !== dependencies.config.mediaOwner) {
  1580. throw new HttpError(404, '本地图片不存在', 'local_media_not_found')
  1581. }
  1582. await withJar(ctx, async (jar) => {
  1583. await requireGatewayAuthentication(ctx, dependencies, jar)
  1584. const filePath = Array.isArray(ctx.params.filePath) ? ctx.params.filePath.join('/') : ctx.params.filePath
  1585. const path = await authorizeFileRead(dependencies.config, dependencies.upstreamSession, localMediaPath(dependencies.config.imagesRoot, filePath))
  1586. sendLocalMedia(ctx, path)
  1587. prepareFilePreview(ctx, basename(path), true)
  1588. })
  1589. })
  1590. router.get('/attachments/*filePath', async (ctx) => {
  1591. if (!isLoopbackUpstream(dependencies.config.upstream)) {
  1592. throw new HttpError(409, '本地附件只支持回环 Hermes 上游', 'remote_local_media_disabled')
  1593. }
  1594. await withJar(ctx, async (jar) => {
  1595. await requireGatewayAuthentication(ctx, dependencies, jar)
  1596. const filePath = Array.isArray(ctx.params.filePath) ? ctx.params.filePath.join('/') : ctx.params.filePath
  1597. const path = await authorizeFileRead(dependencies.config, dependencies.upstreamSession, localMediaPath(dependencies.config.attachmentsRoot, filePath), String(ctx.query.profile || ctx.get('x-hermes-profile') || 'default'))
  1598. sendLocalMedia(ctx, path)
  1599. prepareFilePreview(ctx, basename(path), true)
  1600. })
  1601. })
  1602. router.get('/readyz', async (ctx) => {
  1603. ctx.set('Cache-Control', 'no-store')
  1604. try {
  1605. const response = await dependencies.upstream.request(
  1606. '/api/status',
  1607. new CookieJar(''),
  1608. { maxResponseBytes: 2 * 1_024 * 1_024 },
  1609. )
  1610. const reachable = response.status >= 200 && response.status < 500
  1611. json(ctx, reachable ? 200 : 503, {
  1612. ok: reachable,
  1613. upstream: reachable ? 'reachable' : 'unavailable',
  1614. })
  1615. } catch {
  1616. json(ctx, 503, { ok: false, upstream: 'unavailable' })
  1617. }
  1618. })
  1619. router.get('/api/app/bootstrap', async (ctx) => {
  1620. ctx.set('Cache-Control', 'no-store')
  1621. if (ctx.query.csrfOnly === '1') {
  1622. json(ctx, 200, {
  1623. csrfToken: dependencies.csrf.issue(ctx),
  1624. userId: dependencies.auth.current(ctx)?.id ?? null,
  1625. })
  1626. return
  1627. }
  1628. await bootstrap(ctx, dependencies)
  1629. })
  1630. router.post('/api/app/setup', async (ctx) => {
  1631. await setup(ctx, dependencies)
  1632. })
  1633. router.post('/api/app/login', async (ctx) => {
  1634. await login(ctx, dependencies)
  1635. })
  1636. router.post('/api/app/register', ctx => {
  1637. const retry = registrations.take(ctx.req.socket.remoteAddress ?? 'unknown')
  1638. if (retry) {
  1639. ctx.set('Retry-After', String(retry))
  1640. throw new HttpError(429, '注册请求过于频繁,请稍后重试。', 'registration_rate_limited')
  1641. }
  1642. const request = body(ctx)
  1643. if (Object.keys(request).some(key => !['username', 'password'].includes(key)) || typeof request.username !== 'string' || typeof request.password !== 'string')
  1644. throw new HttpError(400, '请填写用户名和密码', 'invalid_registration')
  1645. dependencies.auth.register(request.username, request.password)
  1646. json(ctx, 201, { registrationStatus: 'pending', message: '注册成功,请等待管理员开通。' })
  1647. })
  1648. router.post('/api/app/logout', async (ctx) => {
  1649. dependencies.auth.logout(ctx)
  1650. json(ctx, 200, { ok: true, csrfToken: dependencies.csrf.issue(ctx, true) })
  1651. })
  1652. router.put('/api/app/account/credentials', async (ctx) => {
  1653. const request = body(ctx)
  1654. const currentPassword = typeof request.currentPassword === 'string' ? request.currentPassword : ''
  1655. const newPassword = typeof request.newPassword === 'string' ? request.newPassword : ''
  1656. const username = typeof request.username === 'string' ? request.username : undefined
  1657. const user = dependencies.auth.changeCredentials(ctx, currentPassword, newPassword, username)
  1658. json(ctx, 200, { user, mustChangePassword: false, csrfToken: dependencies.csrf.issue(ctx, true) })
  1659. })
  1660. router.put('/api/app/account/avatar', (ctx) => {
  1661. const request = body(ctx)
  1662. const user = dependencies.auth.setAvatar(ctx, request.avatar)
  1663. json(ctx, 200, { user })
  1664. })
  1665. router.get('/api/app/admin/users', (ctx) => {
  1666. const admin = dependencies.auth.requireAdmin(ctx)
  1667. json(ctx, 200, { items: dependencies.auth.list(admin) })
  1668. })
  1669. router.post('/api/app/admin/users', (ctx) => {
  1670. const admin = dependencies.auth.requireAdmin(ctx)
  1671. const request = body(ctx)
  1672. const username = typeof request.username === 'string' ? request.username : ''
  1673. const password = typeof request.password === 'string' ? request.password : ''
  1674. json(ctx, 201, dependencies.auth.create(admin, username, password, request.assignedProfiles))
  1675. })
  1676. router.post('/api/app/admin/users/:userID/approve', async ctx => {
  1677. dependencies.auth.requireAdmin(ctx)
  1678. const userID = canonicalUUID(ctx.params.userID, 'user ID'), request = body(ctx)
  1679. if (Object.keys(request).some(key => key !== 'assignedProfiles')) throw new HttpError(400, '开通参数无效', 'invalid_approval')
  1680. const profiles = dependencies.auth.validateAssignedProfiles(request.assignedProfiles)
  1681. if (!profiles.length) throw new HttpError(400, '开通时必须分配至少一个基础机器人', 'assignment_required')
  1682. const response = await dependencies.upstreamSession.request('/api/profiles', { cache: 'reload' })
  1683. const available = new Set(normalizedProfiles(requireSuccess(response)).map(value => typeof value === 'string' ? value : (value as JsonObject).name))
  1684. if (profiles.some(profile => !available.has(profile))) throw new HttpError(409, '所选基础机器人当前不可用,请刷新后重新选择。', 'source_unavailable')
  1685. // Revalidate the administrator after the asynchronous catalogue lookup.
  1686. delete ctx.state.localUser
  1687. const admin = dependencies.auth.requireAdmin(ctx)
  1688. json(ctx, 200, dependencies.auth.approve(admin, userID, profiles))
  1689. })
  1690. router.patch('/api/app/admin/users/:userID', async (ctx) => {
  1691. const admin = dependencies.auth.requireAdmin(ctx)
  1692. const request = body(ctx)
  1693. const userID = canonicalUUID(ctx.params.userID, 'user ID')
  1694. const updated = dependencies.auth.updateUser(admin, userID, {
  1695. assignedProfiles: request.assignedProfiles,
  1696. enabled: typeof request.enabled === 'boolean' ? request.enabled : undefined,
  1697. password: typeof request.password === 'string' ? request.password : undefined,
  1698. })
  1699. await dependencies.onUserAccessChanged?.(userID)
  1700. if (request.enabled === false || typeof request.password === 'string' || request.assignedProfiles !== undefined) {
  1701. bestEffortRemoveUserPush(ctx, dependencies, userID)
  1702. }
  1703. json(ctx, 200, updated)
  1704. })
  1705. router.delete('/api/app/admin/users/:userID', async (ctx) => {
  1706. const admin = dependencies.auth.requireAdmin(ctx)
  1707. const userID = canonicalUUID(ctx.params.userID, 'user ID')
  1708. dependencies.auth.deleteUser(admin, userID)
  1709. await dependencies.onUserAccessChanged?.(userID)
  1710. bestEffortRemoveUserPush(ctx, dependencies, userID)
  1711. json(ctx, 200, { ok: true })
  1712. })
  1713. router.put('/api/app/admin/upstream-credentials', async (ctx) => {
  1714. const admin = dependencies.auth.requireAdmin(ctx)
  1715. const request = body(ctx)
  1716. const username = typeof request.username === 'string' ? request.username : ''
  1717. const password = typeof request.password === 'string' ? request.password : ''
  1718. await dependencies.upstreamSession.verify({ username, password })
  1719. dependencies.auth.setUpstreamCredentials(admin, { username, password })
  1720. json(ctx, 200, { ok: true })
  1721. })
  1722. router.get('/api/app/admin/upstream-connection', async (ctx) => {
  1723. dependencies.auth.requireAdmin(ctx)
  1724. let ready = false
  1725. let error: string | undefined
  1726. try {
  1727. await dependencies.upstreamSession.ensure()
  1728. ready = true
  1729. } catch (cause) {
  1730. error = cause instanceof Error ? cause.message : '9119 不可用'
  1731. }
  1732. json(ctx, 200, {
  1733. ...dependencies.upstreamSession.connectionInfo(),
  1734. ready,
  1735. error,
  1736. webNetworkScope: isLoopbackHost(dependencies.config.host) ? 'local' : 'network',
  1737. })
  1738. })
  1739. router.get('/api/app/admin/hermes-bridge', async ctx => {
  1740. dependencies.auth.requireAdmin(ctx)
  1741. json(ctx,200,await dependencies.hermesBridge.status())
  1742. })
  1743. router.post('/api/app/admin/hermes-bridge/install', async ctx => {
  1744. dependencies.auth.requireAdmin(ctx)
  1745. json(ctx,200,await dependencies.hermesBridge.install(body(ctx)))
  1746. })
  1747. router.post('/api/app/admin/hermes-bridge/restart', async ctx => {
  1748. dependencies.auth.requireAdmin(ctx)
  1749. json(ctx,200,await dependencies.hermesBridge.restartDashboard())
  1750. })
  1751. router.get('/api/app/admin/model-services', async (ctx) => {
  1752. await proxyAdminFeature(ctx, dependencies, '/api/providers/custom-endpoints', {
  1753. search: searchFrom(ctx, ['profile']),
  1754. })
  1755. })
  1756. router.put('/api/app/admin/profiles/:profileName/model', async (ctx) => {
  1757. dependencies.auth.requireAdmin(ctx)
  1758. const profileName = safeIdentifier(ctx.params.profileName, 'profile name')
  1759. const request = body(ctx)
  1760. const provider = typeof request.provider === 'string' ? request.provider.trim() : ''
  1761. const model = typeof request.model === 'string' ? request.model.trim() : ''
  1762. if (!provider || !model) {
  1763. throw new HttpError(400, 'Provider 和模型不能为空', 'invalid_profile_model')
  1764. }
  1765. await proxyAdminFeature(
  1766. ctx,
  1767. dependencies,
  1768. `/api/profiles/${encodeURIComponent(profileName)}/model`,
  1769. { method: 'PUT', requestBody: { provider, model } },
  1770. )
  1771. })
  1772. router.post('/api/app/admin/model-services', async (ctx) => {
  1773. await proxyAdminFeature(ctx, dependencies, '/api/providers/custom-endpoints', {
  1774. method: 'POST', search: searchFrom(ctx, ['profile']), requestBody: body(ctx),
  1775. })
  1776. })
  1777. router.post('/api/app/admin/model-services/validate', async (ctx) => {
  1778. await proxyAdminFeature(ctx, dependencies, '/api/providers/custom-endpoints/validate', {
  1779. method: 'POST', requestBody: body(ctx),
  1780. })
  1781. })
  1782. router.post('/api/app/admin/model-services/:serviceID/activate', async (ctx) => {
  1783. const id = safeIdentifier(ctx.params.serviceID, 'model service ID')
  1784. await proxyAdminFeature(ctx, dependencies, `/api/providers/custom-endpoints/${encodeURIComponent(id)}/activate`, {
  1785. method: 'POST', search: searchFrom(ctx, ['profile']), requestBody: optionalBody(ctx) ?? {},
  1786. })
  1787. })
  1788. router.delete('/api/app/admin/model-services/:serviceID', async (ctx) => {
  1789. const id = safeIdentifier(ctx.params.serviceID, 'model service ID')
  1790. await proxyAdminFeature(ctx, dependencies, `/api/providers/custom-endpoints/${encodeURIComponent(id)}`, {
  1791. method: 'DELETE', search: searchFrom(ctx, ['profile']),
  1792. })
  1793. })
  1794. router.get('/api/app/admin/legacy-model-services', async (ctx) => {
  1795. dependencies.auth.requireAdmin(ctx)
  1796. await withJar(ctx, async (jar) => {
  1797. const search = searchFrom(ctx, ['profile'])
  1798. const [configResponse, optionsResponse] = await Promise.all([
  1799. dependencies.upstream.request('/api/config', jar, { search }),
  1800. dependencies.upstream.request('/api/model/options', jar, {
  1801. search: new URLSearchParams([...search, ['explicit_only', 'true']]),
  1802. }),
  1803. ])
  1804. if ([configResponse.status, optionsResponse.status].some(status => status === 404 || status === 405)) {
  1805. throw new HttpError(501, '当前上游版本不支持旧版模型服务管理', 'upstream_feature_unsupported')
  1806. }
  1807. const config = requireSuccess(configResponse)
  1808. const options = requireSuccess(optionsResponse)
  1809. const currentProvider = typeof options.provider === 'string' ? options.provider.toLocaleLowerCase() : ''
  1810. const entries = Array.isArray(config.custom_providers) ? config.custom_providers : []
  1811. const items = entries.flatMap(raw => {
  1812. if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return []
  1813. const entry = raw as JsonObject
  1814. const name = typeof entry.name === 'string' ? entry.name.trim() : ''
  1815. const baseURL = typeof entry.base_url === 'string' ? entry.base_url.trim() : ''
  1816. const model = typeof entry.model === 'string' ? entry.model.trim() : ''
  1817. if (!name || !baseURL || !model) return []
  1818. const rawModels = entry.models
  1819. const models = Array.isArray(rawModels)
  1820. ? rawModels.map(String).map(value => value.trim()).filter(Boolean)
  1821. : rawModels && typeof rawModels === 'object'
  1822. ? Object.keys(rawModels).filter(value => !value.startsWith('__'))
  1823. : [model]
  1824. const modelConfig = rawModels && typeof rawModels === 'object' && !Array.isArray(rawModels)
  1825. ? (rawModels as JsonObject)[model]
  1826. : undefined
  1827. const contextLength = typeof entry.context_length === 'number' ? entry.context_length
  1828. : modelConfig && typeof modelConfig === 'object' && !Array.isArray(modelConfig)
  1829. && typeof (modelConfig as JsonObject).context_length === 'number'
  1830. ? (modelConfig as JsonObject).context_length as number
  1831. : undefined
  1832. const id = `custom:${name}`
  1833. return [{
  1834. id, name, base_url: baseURL, model, models: [...new Set([...models, model])],
  1835. ...(contextLength ? { context_length: contextLength } : {}),
  1836. discover_models: entry.models_discovered === true,
  1837. has_api_key: Boolean(entry.key_env || entry.api_key),
  1838. can_edit_api_key: typeof entry.key_env === 'string' && Boolean(entry.key_env.trim()),
  1839. is_current: currentProvider === id.toLocaleLowerCase(),
  1840. source: 'legacy',
  1841. }]
  1842. })
  1843. json(ctx, 200, { items })
  1844. })
  1845. })
  1846. router.put('/api/app/admin/legacy-model-services/:serviceID', async (ctx) => {
  1847. dependencies.auth.requireAdmin(ctx)
  1848. const serviceID = safeIdentifier(ctx.params.serviceID, 'legacy model service ID')
  1849. const request = body(ctx)
  1850. const baseURL = typeof request.base_url === 'string' ? request.base_url.trim().replace(/\/$/, '') : ''
  1851. const model = typeof request.model === 'string' ? request.model.trim() : ''
  1852. const models = Array.isArray(request.models)
  1853. ? [...new Set(request.models.map(String).map(value => value.trim()).filter(Boolean))]
  1854. : []
  1855. if (!/^https?:\/\//i.test(baseURL)) throw new HttpError(400, 'Base URL 必须使用 http 或 https', 'invalid_model_service')
  1856. if (!model) throw new HttpError(400, '默认模型不能为空', 'invalid_model_service')
  1857. if (!models.includes(model)) models.push(model)
  1858. const contextLength = typeof request.context_length === 'number' && Number.isInteger(request.context_length) && request.context_length > 0
  1859. ? request.context_length : undefined
  1860. await withJar(ctx, async (jar) => {
  1861. const search = searchFrom(ctx, ['profile'])
  1862. const [configResponse, optionsResponse] = await Promise.all([
  1863. dependencies.upstream.request('/api/config', jar, { search }),
  1864. dependencies.upstream.request('/api/model/options', jar, {
  1865. search: new URLSearchParams([...search, ['explicit_only', 'true']]),
  1866. }),
  1867. ])
  1868. const config = requireSuccess(configResponse)
  1869. const options = requireSuccess(optionsResponse)
  1870. const providers = Array.isArray(config.custom_providers) ? [...config.custom_providers] : []
  1871. const index = providers.findIndex(raw => {
  1872. if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false
  1873. const name = typeof (raw as JsonObject).name === 'string' ? String((raw as JsonObject).name) : ''
  1874. return `custom:${name}`.toLocaleLowerCase() === serviceID.toLocaleLowerCase()
  1875. })
  1876. if (index < 0) throw new HttpError(404, '旧版模型服务不存在', 'model_service_not_found')
  1877. const current = providers[index] as JsonObject
  1878. const existingModels = current.models && typeof current.models === 'object' && !Array.isArray(current.models)
  1879. ? current.models as JsonObject : {}
  1880. const nextModels = Object.fromEntries(models.map(id => {
  1881. const previous = existingModels[id]
  1882. const metadata: JsonObject = previous && typeof previous === 'object' && !Array.isArray(previous)
  1883. ? { ...previous as JsonObject } : {}
  1884. if (id === model && contextLength) metadata.context_length = contextLength
  1885. return [id, metadata]
  1886. }))
  1887. providers[index] = {
  1888. ...current,
  1889. base_url: baseURL,
  1890. model,
  1891. models: nextModels,
  1892. models_discovered: request.discover_models === true,
  1893. ...(contextLength ? { context_length: contextLength } : {}),
  1894. }
  1895. requireSuccess(await dependencies.upstream.request('/api/config', jar, {
  1896. method: 'PUT', search, body: { config: { custom_providers: providers }, profile: search.get('profile') || undefined },
  1897. }))
  1898. if (Object.prototype.hasOwnProperty.call(request, 'api_key')) {
  1899. const keyEnvironment = typeof current.key_env === 'string' ? current.key_env.trim() : ''
  1900. if (!keyEnvironment) throw new HttpError(409, '该旧版服务没有可管理的密钥变量', 'model_service_key_unmanaged')
  1901. const apiKey = typeof request.api_key === 'string' ? request.api_key.trim() : ''
  1902. requireSuccess(await dependencies.upstream.request('/api/env', jar, {
  1903. method: apiKey ? 'PUT' : 'DELETE', search,
  1904. body: apiKey ? { key: keyEnvironment, value: apiKey, profile: search.get('profile') || undefined }
  1905. : { key: keyEnvironment, profile: search.get('profile') || undefined },
  1906. }))
  1907. }
  1908. const currentProvider = typeof options.provider === 'string' ? options.provider.toLocaleLowerCase() : ''
  1909. if (currentProvider === serviceID.toLocaleLowerCase()) {
  1910. requireSuccess(await dependencies.upstream.request('/api/model/set', jar, {
  1911. method: 'POST', search,
  1912. body: { scope: 'main', provider: serviceID, model, base_url: baseURL, confirm_expensive_model: true, profile: search.get('profile') || undefined },
  1913. }))
  1914. }
  1915. json(ctx, 200, { ok: true })
  1916. })
  1917. })
  1918. router.get('/api/app/system/update/status', async (ctx) => {
  1919. dependencies.auth.requireAdmin(ctx)
  1920. // No upstream calls, including best-effort plugin probes: a stalled 9119
  1921. // must not delay or prevent access to the independent Web updater.
  1922. json(ctx, 200, systemUpdateStatusForRequest(ctx, dependencies, dependencies.updates.status()))
  1923. })
  1924. router.get('/api/app/system/push-status', (ctx) => {
  1925. dependencies.auth.requireAdmin(ctx)
  1926. json(ctx, 200, pushSystemStatus(dependencies))
  1927. })
  1928. router.get('/api/app/admin/openviking', (ctx) => {
  1929. dependencies.auth.requireAdmin(ctx)
  1930. json(ctx, 200, dependencies.openVikingConfiguration.snapshot())
  1931. })
  1932. router.get('/api/app/admin/openviking/session-sync', ctx => {
  1933. dependencies.auth.requireAdmin(ctx)
  1934. json(ctx, 200, dependencies.openVikingSessionSync.status())
  1935. })
  1936. router.post('/api/app/admin/openviking/session-sync/retry', ctx => {
  1937. dependencies.auth.requireAdmin(ctx)
  1938. json(ctx, 200, dependencies.openVikingSessionSync.retry())
  1939. })
  1940. router.put('/api/app/admin/openviking', async (ctx) => {
  1941. dependencies.auth.requireAdmin(ctx)
  1942. const request = body(ctx)
  1943. const snapshot = await dependencies.openVikingConfiguration.update({
  1944. enabled: request.enabled === true,
  1945. url: typeof request.url === 'string' ? request.url : '',
  1946. accountId: typeof request.accountId === 'string' ? request.accountId : '',
  1947. ...(typeof request.adminKey === 'string' && request.adminKey.trim() ? { adminKey: request.adminKey } : {}),
  1948. }, config => dependencies.openVikingService.configure(config))
  1949. json(ctx, 200, snapshot)
  1950. })
  1951. router.get('/api/app/server-identity', (ctx) => {
  1952. dependencies.auth.require(ctx)
  1953. ctx.set('Cache-Control', 'no-store')
  1954. json(ctx, 200, readServerIdentity(dependencies.workspace))
  1955. })
  1956. router.put('/api/app/server-identity', (ctx) => {
  1957. dependencies.auth.requireAdmin(ctx)
  1958. const identity = updateServerIdentity(dependencies.workspace, body(ctx))
  1959. dependencies.onServerIdentityChanged?.(identity)
  1960. json(ctx, 200, identity)
  1961. })
  1962. router.get('/api/app/system/allowed-hosts', (ctx) => {
  1963. dependencies.auth.requireAdmin(ctx)
  1964. json(ctx, 200, dependencies.allowedHostsConfiguration.snapshot())
  1965. })
  1966. router.put('/api/app/system/allowed-hosts', (ctx) => {
  1967. dependencies.auth.requireAdmin(ctx)
  1968. const request = body(ctx)
  1969. if (!Array.isArray(request.hosts) || request.hosts.some(host => typeof host !== 'string')) {
  1970. throw new HttpError(400, 'hosts 必须是域名或 IP 数组', 'invalid_allowed_hosts')
  1971. }
  1972. const requestedHosts = canonicalAllowedHosts(request.hosts as string[])
  1973. const currentHost = normalizeAllowedHost(ctx.hostname)
  1974. const environmentHosts = dependencies.allowedHostsConfiguration.snapshot().environmentHosts
  1975. if (!isPrivateHost(currentHost) && !new Set([...environmentHosts, ...requestedHosts]).has(currentHost)) {
  1976. throw new HttpError(409, `不能移除当前正在使用的访问地址 ${currentHost}`, 'current_host_required')
  1977. }
  1978. json(ctx, 200, dependencies.allowedHostsConfiguration.update(requestedHosts))
  1979. })
  1980. router.put('/api/app/system/push-config', async (ctx) => {
  1981. dependencies.auth.requireAdmin(ctx)
  1982. const request = body(ctx)
  1983. const input: Partial<APNsConfigurationInput> = {
  1984. keyFile: typeof request.keyFile === 'string' ? request.keyFile : '',
  1985. keyId: typeof request.keyId === 'string' ? request.keyId : '',
  1986. teamId: typeof request.teamId === 'string' ? request.teamId : '',
  1987. topic: typeof request.topic === 'string' ? request.topic : '',
  1988. environments: Array.isArray(request.environments) ? request.environments as APNsConfigurationInput['environments'] : [],
  1989. }
  1990. await dependencies.apnsConfiguration.update(input, async config => {
  1991. await dependencies.push.configureAPNs(config)
  1992. })
  1993. json(ctx, 200, pushSystemStatus(dependencies))
  1994. })
  1995. router.put('/api/app/system/push-config/fcm', async (ctx) => {
  1996. dependencies.auth.requireAdmin(ctx)
  1997. const request = body(ctx)
  1998. const input: Partial<FCMConfigurationInput> = {
  1999. serviceAccountFile: typeof request.serviceAccountFile === 'string' ? request.serviceAccountFile : '',
  2000. projectId: typeof request.projectId === 'string' ? request.projectId : '',
  2001. packageName: typeof request.packageName === 'string' ? request.packageName : '',
  2002. }
  2003. await dependencies.fcmConfiguration.update(input, async config => {
  2004. await dependencies.push.configureFCM(config)
  2005. })
  2006. json(ctx, 200, pushSystemStatus(dependencies))
  2007. })
  2008. router.post('/api/app/system/update/check', async (ctx) => {
  2009. dependencies.auth.requireAdmin(ctx)
  2010. try {
  2011. json(ctx, 200, systemUpdateStatusForRequest(ctx, dependencies, await dependencies.updates.check()))
  2012. } catch (error) {
  2013. throw updateFailure(error)
  2014. }
  2015. })
  2016. router.post('/api/app/system/update/apply', async (ctx) => {
  2017. dependencies.auth.requireAdmin(ctx)
  2018. requireLocalSystemUpdate(ctx, dependencies)
  2019. const request = body(ctx)
  2020. const targetVersion = typeof request.targetVersion === 'string' ? request.targetVersion.trim() : ''
  2021. if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(targetVersion)) {
  2022. throw new HttpError(400, 'targetVersion 必须是有效的发布版本', 'invalid_request')
  2023. }
  2024. try {
  2025. json(ctx, 202, await dependencies.updates.startUpdate(targetVersion))
  2026. } catch (error) {
  2027. throw updateFailure(error)
  2028. }
  2029. })
  2030. router.get('/api/app/system/update/jobs/:jobID', async (ctx) => {
  2031. dependencies.auth.requireAdmin(ctx)
  2032. const job = dependencies.updates.job(ctx.params.jobID)
  2033. if (!job) throw new HttpError(404, '升级任务不存在', 'system_update_job_not_found')
  2034. json(ctx, 200, job)
  2035. })
  2036. router.post('/api/app/system/update/rollback', async (ctx) => {
  2037. dependencies.auth.requireAdmin(ctx)
  2038. requireLocalSystemUpdate(ctx, dependencies)
  2039. try {
  2040. json(ctx, 202, dependencies.updates.startRollback())
  2041. } catch (error) {
  2042. throw updateFailure(error)
  2043. }
  2044. })
  2045. router.get('/api/app/profiles', async (ctx) => {
  2046. await withJar(ctx, async (jar) => {
  2047. const profilesResponse = await dependencies.upstream.request('/api/profiles', jar)
  2048. if (profilesResponse.status < 200 || profilesResponse.status >= 300) {
  2049. sendUpstreamResponse(ctx, profilesResponse, jar)
  2050. return
  2051. }
  2052. const profiles = profilesWithCoreNames(normalizedProfiles(parseJson(profilesResponse)))
  2053. json(ctx, 200, { profiles })
  2054. })
  2055. })
  2056. router.get('/api/app/models', async (ctx) => {
  2057. const search = searchFrom(ctx, ['profile'])
  2058. search.set('explicit_only', 'true')
  2059. await proxy(ctx, dependencies.upstream, '/api/model/options', { search })
  2060. })
  2061. router.get('/api/app/sessions/search', async (ctx) => {
  2062. await searchSessions(ctx, dependencies)
  2063. })
  2064. router.get('/api/app/sessions/pins', ctx => {
  2065. const owner=dependencies.auth.require(ctx).id
  2066. ctx.body={session_ids:dependencies.chatCache!.store.pins(owner,String(ctx.query.profile??''))}
  2067. })
  2068. router.get('/api/app/sessions/unread', ctx => {
  2069. const owner=dependencies.auth.require(ctx).id
  2070. ctx.body=dependencies.chatCache!.store.unread(owner,String(ctx.query.profile??''))
  2071. })
  2072. router.patch('/api/app/sessions/unread/:sessionID', ctx => {
  2073. const owner=dependencies.auth.require(ctx).id,profile=String(ctx.query.profile??'default'),id=safeIdentifier(ctx.params.sessionID,'session ID')
  2074. const input=body(ctx) as Record<string,unknown>,value=input.readMessageCount??input.read_message_count
  2075. ctx.body=dependencies.chatCache!.store.markRead(owner,profile,id,typeof value==='number'&&Number.isFinite(value)?value:undefined)
  2076. dependencies.onChatListChanged?.(owner,profile,id)
  2077. })
  2078. router.post('/api/app/sessions/:sessionID/sync',ctx=>{
  2079. const owner=dependencies.auth.require(ctx).id,profile=String(ctx.query.profile??'default'),id=safeIdentifier(ctx.params.sessionID,'session ID')
  2080. dependencies.chatCache!.store.requireOwned(owner,profile,id)
  2081. dependencies.chatCache!.schedule(owner,profile,id,true)
  2082. ctx.status=202;ctx.body={sync_state:'syncing'}
  2083. })
  2084. router.get('/api/app/sessions', async (ctx) => {
  2085. const view = ctx.query.view === 'history' || ctx.query.view === 'chat' ? ctx.query.view : undefined
  2086. const search = searchFrom(ctx, ['limit', 'offset', 'order', 'archived', 'profile', 'source'])
  2087. const offset = Math.max(0, Number(search.get('offset') ?? '0') || 0)
  2088. const limit = Math.max(1, Math.min(200, Number(search.get('limit') ?? '100') || 100))
  2089. search.set('offset', String(offset))
  2090. search.set('limit', String(limit))
  2091. if (!search.get('order')) search.set('order', 'recent')
  2092. if (!search.get('archived')) search.set('archived', 'exclude')
  2093. if (view) search.delete('source')
  2094. search.set('exclude_sources', 'cron,ios_group,yaoyao_workspace')
  2095. const path = search.get('profile') ? '/api/sessions' : '/api/profiles/sessions'
  2096. if (view && !dependencies.chatCache) {
  2097. throw new HttpError(503, 'Chat ownership registry is unavailable', 'chat_registry_unavailable')
  2098. }
  2099. if (view === 'history' && dependencies.chatCache) {
  2100. const owner = dependencies.auth.require(ctx).id
  2101. const profile = search.get('profile') || ''
  2102. await withJar(ctx, async (jar) => {
  2103. const response = await completeSessionList(dependencies.upstream, path, jar, search)
  2104. sendUpstreamResponse(
  2105. ctx,
  2106. dependencies.chatCache!.store.excludeOwnedSessionsFromList(
  2107. owner,
  2108. profile,
  2109. response,
  2110. { offset, limit },
  2111. ),
  2112. jar,
  2113. )
  2114. })
  2115. return
  2116. }
  2117. if (view !== 'chat') {
  2118. await proxy(ctx, dependencies.upstream, path, { search })
  2119. return
  2120. }
  2121. const profile = search.get('profile') || ''
  2122. const upstreamSearch = new URLSearchParams(search)
  2123. upstreamSearch.set('offset', '0')
  2124. upstreamSearch.set('limit', '100')
  2125. await cachedChatRead(ctx, dependencies, {
  2126. key: chatCacheKey('list', profile, undefined, search),
  2127. kind: 'list', profile, ownedList: true, offset, limit,
  2128. archived: search.get('archived') || 'exclude',
  2129. load: jar => completeSessionList(dependencies.upstream, path, jar, upstreamSearch),
  2130. })
  2131. })
  2132. router.get('/api/app/sessions/:sessionID/messages', async (ctx) => {
  2133. const id = safeIdentifier(ctx.params.sessionID, 'session ID')
  2134. const incoming = searchFrom(ctx, ['offset', 'limit', 'profile'])
  2135. const offset = Math.max(0, Number(incoming.get('offset') ?? '0') || 0)
  2136. const limit = Math.max(1, Math.min(500, Number(incoming.get('limit') ?? '100') || 100))
  2137. incoming.set('offset', String(offset))
  2138. incoming.set('limit', String(limit))
  2139. incoming.set('order', 'latest')
  2140. incoming.set('include_compacted', 'true')
  2141. const profile = incoming.get('profile') || 'default'
  2142. await cachedChatRead(ctx, dependencies, {
  2143. key: chatCacheKey('messages', profile, id, incoming),
  2144. kind: 'messages', profile, sessionID: id, offset, limit,
  2145. load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}/messages`, jar, { search: incoming }),
  2146. })
  2147. })
  2148. router.get('/api/app/sessions/:sessionID', async (ctx) => {
  2149. const id = safeIdentifier(ctx.params.sessionID, 'session ID')
  2150. const search = searchFrom(ctx, ['profile'])
  2151. const profile = search.get('profile') || 'default'
  2152. await cachedChatRead(ctx, dependencies, {
  2153. key: chatCacheKey('detail', profile, id, search),
  2154. kind: 'detail', profile, sessionID: id,
  2155. load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search }),
  2156. })
  2157. })
  2158. router.patch('/api/app/sessions/:sessionID', async (ctx) => {
  2159. const id = safeIdentifier(ctx.params.sessionID, 'session ID')
  2160. const search = searchFrom(ctx, ['profile'])
  2161. const localPatch=writableSessionPatch(body(ctx))
  2162. if(Object.keys(localPatch).every(key=>['title','pinned','archived'].includes(key))){
  2163. const owner=dependencies.auth.require(ctx).id,profile=search.get('profile')||'default'
  2164. if(!dependencies.chatCache!.store.ownsSession(owner,profile,id))throw new HttpError(410,'原生历史只读','native_sessions_read_only')
  2165. dependencies.chatCache!.store.patchLocal(owner,profile,id,localPatch)
  2166. dependencies.onChatListChanged?.(owner,profile,id)
  2167. ctx.body={ok:true};return
  2168. }
  2169. await withJar(ctx, async jar => {
  2170. const profile = search.get('profile') || 'default'
  2171. const owner = dependencies.auth.require(ctx).id
  2172. requireWritableOwnedSession(
  2173. await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search }),
  2174. dependencies.chatCache?.store.ownsSession(owner, profile, id) ?? false,
  2175. )
  2176. const request = writableSessionPatch(body(ctx))
  2177. const requestedProfile = search.get('profile')
  2178. if (requestedProfile) request.profile = requestedProfile
  2179. const response = await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { method: 'PATCH', search, body: request })
  2180. if (response.status >= 200 && response.status < 300) {
  2181. if (typeof request.title === 'string') {
  2182. dependencies.chatCache?.store.recordAuthoritativeTitle(
  2183. owner,
  2184. profile,
  2185. id,
  2186. request.title,
  2187. )
  2188. }
  2189. dependencies.chatCache?.store.markListsStale(owner)
  2190. void dependencies.chatCache?.reconcile(owner, profile, id).catch(() => {})
  2191. }
  2192. sendUpstreamResponse(ctx, response, jar)
  2193. })
  2194. })
  2195. router.delete('/api/app/sessions/:sessionID', async (ctx) => {
  2196. const id = safeIdentifier(ctx.params.sessionID, 'session ID')
  2197. const search = searchFrom(ctx, ['profile'])
  2198. await withJar(ctx, async jar => {
  2199. const profile = search.get('profile') || 'default'
  2200. const owner = dependencies.auth.require(ctx).id
  2201. const existing = await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search })
  2202. if (isMissingSessionResponse(existing)) {
  2203. // Only this account's cached copy remains; no upstream mutation is needed.
  2204. dependencies.chatCache?.store.deleteSession(owner, profile, id)
  2205. ctx.body = { ok: true }
  2206. return
  2207. }
  2208. requireWritableOwnedSession(
  2209. existing,
  2210. dependencies.chatCache?.store.ownsSession(owner, profile, id) ?? false,
  2211. )
  2212. const response = await dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { method: 'DELETE', search })
  2213. const alreadyMissing = isMissingSessionResponse(response)
  2214. if ((response.status >= 200 && response.status < 300) || alreadyMissing) {
  2215. dependencies.chatCache?.store.deleteSession(
  2216. owner,
  2217. profile,
  2218. id,
  2219. )
  2220. }
  2221. if (alreadyMissing) {
  2222. ctx.body = { ok: true }
  2223. return
  2224. }
  2225. sendUpstreamResponse(ctx, response, jar)
  2226. })
  2227. })
  2228. for (const listPath of ['/api/sessions', '/api/profiles/sessions']) {
  2229. router.get(listPath, async ctx => {
  2230. const search = new URLSearchParams(ctx.querystring)
  2231. await withJar(ctx, async jar => sendUpstreamResponse(
  2232. ctx,
  2233. await dependencies.upstream.request(listPath, jar, { search }),
  2234. jar,
  2235. ))
  2236. })
  2237. }
  2238. router.get('/api/sessions/:sessionID/messages', async ctx => {
  2239. const id = safeIdentifier(ctx.params.sessionID, 'session ID')
  2240. const search = new URLSearchParams(ctx.querystring)
  2241. const profile = search.get('profile') || 'default'
  2242. const offset = Math.max(0, Number(search.get('offset') ?? 0) || 0)
  2243. const limit = Math.max(1, Math.min(500, Number(search.get('limit') ?? 100) || 100))
  2244. await cachedChatRead(ctx, dependencies, {
  2245. key: chatCacheKey('messages', profile, id, search),
  2246. kind: 'messages', profile, sessionID: id, offset, limit,
  2247. load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}/messages`, jar, { search }),
  2248. })
  2249. })
  2250. router.get('/api/sessions/:sessionID', async ctx => {
  2251. const id = safeIdentifier(ctx.params.sessionID, 'session ID')
  2252. const search = new URLSearchParams(ctx.querystring)
  2253. const profile = search.get('profile') || 'default'
  2254. await cachedChatRead(ctx, dependencies, {
  2255. key: chatCacheKey('detail', profile, id, search),
  2256. kind: 'detail', profile, sessionID: id,
  2257. load: jar => dependencies.upstream.request(`/api/sessions/${encodeURIComponent(id)}`, jar, { search }),
  2258. })
  2259. })
  2260. router.get('/api/files/download', async ctx => {
  2261. const user = dependencies.auth.require(ctx)
  2262. const path = typeof ctx.query.path === 'string' ? ctx.query.path : ''
  2263. if (!path) throw new HttpError(400, 'path is required', 'missing_path')
  2264. const cached = dependencies.chatCache?.store.attachment(user.id, path)
  2265. if (cached) {
  2266. ctx.set('X-Yaoyao-Data-Source', 'local')
  2267. sendLocalMedia(ctx, cached.localPath, cached.mimeType, basename(path))
  2268. prepareFilePreview(ctx, basename(path), true)
  2269. return
  2270. }
  2271. const response = await dependencies.upstreamSession.request('/api/files/download', {
  2272. search: new URLSearchParams({ path }),
  2273. headers: ctx.get('range') ? { range: ctx.get('range') } : undefined,
  2274. maxResponseBytes: 100 * 1_024 * 1_024,
  2275. })
  2276. ctx.set('X-Yaoyao-Data-Source', 'upstream')
  2277. if (!ctx.get('range') && dependencies.chatCache?.store.knowsAttachment(user.id, path)) {
  2278. dependencies.chatCache.store.storeAttachment(user.id, path, response)
  2279. } else if (ctx.get('range')) {
  2280. void dependencies.chatCache?.cacheAttachment(user.id, path)
  2281. }
  2282. sendUpstreamResponse(ctx, response, dependencies.upstreamSession.jar)
  2283. ctx.set('Cache-Control', 'private, no-store')
  2284. ctx.set('X-Content-Type-Options', 'nosniff')
  2285. if (response.status >= 200 && response.status < 300 && ctx.query.preview === '1') prepareFilePreview(ctx, basename(path))
  2286. })
  2287. router.all('/api/*gatewayPath', async (ctx) => {
  2288. if (ctx.path.startsWith('/api/app/') || ctx.path.startsWith('/api/pair/')) {
  2289. throw new HttpError(404, 'Route not found', 'not_found')
  2290. }
  2291. dependencies.auth.require(ctx, ctx.path === '/api/profiles')
  2292. const raw = Array.isArray(ctx.params.gatewayPath)
  2293. ? ctx.params.gatewayPath.join('/')
  2294. : ctx.params.gatewayPath
  2295. const upstreamPath = pairedProxyPath(raw)
  2296. if (isNativeSessionMutation(upstreamPath.slice('/api'.length), ctx.method)) {
  2297. nativeSessionsReadOnly()
  2298. }
  2299. const response = await dependencies.upstreamSession.request(upstreamPath, {
  2300. method: ctx.method,
  2301. search: new URLSearchParams(ctx.querystring),
  2302. body: ['GET', 'HEAD'].includes(ctx.method) ? undefined : optionalBody(ctx),
  2303. // Hermes binds WebSocket tickets to the request address. The relay's
  2304. // upstream connection originates from 15300 itself, so forwarding the
  2305. // phone's address here would make 9119 reject the ticket during Upgrade.
  2306. clientAddress: upstreamPath === '/api/auth/ws-ticket'
  2307. ? undefined : ctx.req.socket.remoteAddress,
  2308. })
  2309. sendUpstreamResponse(ctx, response, dependencies.upstreamSession.jar)
  2310. })
  2311. return router
  2312. }
  2313. export function incomingCookieNames(ctx: Koa.Context): string[] {
  2314. return Object.keys(parse(ctx.get('cookie')))
  2315. }