@lsamien/yaoyao 0.4.75

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