routes.ts 95 KB

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