routes.ts 92 KB

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