routes.ts 102 KB

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