routes.ts 99 KB

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