@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,117 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import Router from '@koa/router';
3
+ import { z } from 'zod';
4
+ import { HttpError } from './errors.js';
5
+ import { parse } from './workspaceStore.js';
6
+ import { DESKTOP_HOST_PROTOCOL } from '../shared/desktopHost.js';
7
+ import { desktopHostExchangeSchema } from './desktopHostProtocol.js';
8
+ import { readComputerNames, saveComputerName } from './computerNames.js';
9
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
10
+ const enrollInput = z.object({
11
+ name: z.string().trim().min(1).max(100),
12
+ installId: z.string().uuid().optional(),
13
+ previousHostId: z.string().uuid().optional(),
14
+ }).strict();
15
+ /** Outbound-only machine transport for remote computers. Browser auth and
16
+ * machine auth remain separate: these endpoints never enter the user session,
17
+ * CSRF or CORS pipeline, and reject any request carrying an Origin header. */
18
+ export class DesktopHostHub {
19
+ store;
20
+ auth;
21
+ /** Bound to DesktopEnvironments.remoteExchange once the runtime exists. */
22
+ exchange = () => { throw new HttpError(503, '电脑尚未接入', 'desktop_host_offline'); };
23
+ /** Bound to DesktopEnvironments.dropHost so revocation fences live commands. */
24
+ drop = () => { };
25
+ online = new Map();
26
+ constructor(store, auth) {
27
+ this.store = store;
28
+ this.auth = auth;
29
+ }
30
+ records() { return this.store.list('_system', 'desktop-host'); }
31
+ enroll(value) {
32
+ const body = parse(enrollInput, value);
33
+ const token = randomBytes(32).toString('base64url');
34
+ const records = this.records();
35
+ let record = body.installId ? records.find(item => item.installId === body.installId) : undefined;
36
+ if (!record && body.previousHostId)
37
+ record = records.find(item => item.id === body.previousHostId);
38
+ if (!record && body.installId) {
39
+ const unnamed = records.filter(item => item.enabled && item.name === body.name && !item.installId).sort((a, b) => a.createdAt - b.createdAt);
40
+ record = unnamed[0];
41
+ for (const extra of unnamed.slice(1)) {
42
+ extra.enabled = false;
43
+ this.store.put('_system', 'desktop-host', extra.id, extra);
44
+ this.online.delete(extra.id);
45
+ this.drop(extra.id);
46
+ }
47
+ }
48
+ if (record) {
49
+ record.name = body.name;
50
+ record.installId = body.installId;
51
+ record.tokenHash = hash(token);
52
+ record.enabled = true;
53
+ this.store.put('_system', 'desktop-host', record.id, record);
54
+ return { host: this.summary(record), token };
55
+ }
56
+ const created = { name: body.name, installId: body.installId, id: randomUUID(), tokenHash: hash(token), enabled: true, createdAt: Date.now() };
57
+ this.store.put('_system', 'desktop-host', created.id, created);
58
+ return { host: this.summary(created), token };
59
+ }
60
+ summary(record) {
61
+ const { tokenHash: _secret, ...publicRecord } = record;
62
+ const state = this.online.get(record.id);
63
+ const displayName = readComputerNames(this.store.home)[record.id] || '';
64
+ return { ...publicRecord, online: !!state && Date.now() - state.seen < 15_000, lastSeen: state?.seen, hostName: state?.name, platform: state?.platform, displayName };
65
+ }
66
+ remove(id) {
67
+ const record = this.store.require('_system', 'desktop-host', id);
68
+ record.enabled = false;
69
+ this.store.put('_system', 'desktop-host', id, record);
70
+ this.online.delete(id);
71
+ this.drop(id);
72
+ }
73
+ adminRouter() {
74
+ const router = new Router();
75
+ router.get('/api/app/admin/desktop-hosts', ctx => { this.auth.requireAdmin(ctx); ctx.set('Cache-Control', 'no-store'); const names = readComputerNames(this.store.home); ctx.body = { protocol: DESKTOP_HOST_PROTOCOL, localName: names.local || '', hosts: this.records().map(record => this.summary(record)) }; });
76
+ router.put('/api/app/admin/desktop-hosts/:id/name', ctx => { this.auth.requireAdmin(ctx); const id = ctx.params.id; if (id !== 'local' && !this.records().some(record => record.id === id && record.enabled))
77
+ throw new HttpError(404, '这台电脑不存在', 'desktop_host_unknown'); const name = typeof ctx.request.body?.name === 'string' ? ctx.request.body.name : ''; ctx.body = { id, name: saveComputerName(this.store.home, id, name)[id] || '' }; });
78
+ router.post('/api/app/admin/desktop-hosts', ctx => { this.auth.requireAdmin(ctx); ctx.body = this.enroll(ctx.request.body); ctx.status = 201; });
79
+ router.delete('/api/app/admin/desktop-hosts/:id', ctx => { this.auth.requireAdmin(ctx); this.remove(ctx.params.id); ctx.body = { ok: true }; });
80
+ return router;
81
+ }
82
+ middleware() {
83
+ return async (ctx, next) => {
84
+ const match = /^\/api\/desktop-host\/v1\/([0-9a-f-]{36})\/exchange$/.exec(ctx.path);
85
+ if (!match)
86
+ return next();
87
+ const record = this.store.get('_system', 'desktop-host', match[1]);
88
+ const authorization = ctx.get('authorization');
89
+ if (ctx.get('origin') || !record?.enabled || !authorization.startsWith('Bearer ') || !timingSafeEqual(Buffer.from(record.tokenHash), Buffer.from(hash(authorization.slice(7)))))
90
+ throw new HttpError(403, '电脑授权无效', 'desktop_host_unauthorized');
91
+ if (ctx.method !== 'POST')
92
+ throw new HttpError(405, '仅允许 POST', 'method_not_allowed');
93
+ if (ctx.get('x-desktop-host-protocol') !== String(DESKTOP_HOST_PROTOCOL))
94
+ throw new HttpError(409, '电脑连接协议不兼容', 'desktop_host_protocol_mismatch');
95
+ let bytes = 0;
96
+ const chunks = [];
97
+ for await (const chunk of ctx.req) {
98
+ bytes += chunk.length;
99
+ if (bytes > 24 * 1024 * 1024)
100
+ throw new HttpError(413, '电脑请求过大', 'desktop_limit');
101
+ chunks.push(Buffer.from(chunk));
102
+ }
103
+ let json;
104
+ try {
105
+ json = JSON.parse(Buffer.concat(chunks).toString());
106
+ }
107
+ catch {
108
+ throw new HttpError(400, '电脑请求格式无效', 'desktop_invalid');
109
+ }
110
+ const value = parse(desktopHostExchangeSchema, json);
111
+ this.online.set(record.id, { seen: Date.now(), name: value.host.name, platform: value.host.platform });
112
+ ctx.set('Cache-Control', 'no-store');
113
+ ctx.body = this.exchange(record.id, value);
114
+ };
115
+ }
116
+ close() { this.online.clear(); }
117
+ }
@@ -0,0 +1,12 @@
1
+ export class HttpError extends Error {
2
+ status;
3
+ code;
4
+ constructor(status, message, code = 'request_failed') {
5
+ super(message);
6
+ this.status = status;
7
+ this.code = code;
8
+ }
9
+ }
10
+ export function errorMessage(value) {
11
+ return value instanceof Error ? value.message : 'Unexpected server error';
12
+ }
@@ -0,0 +1,171 @@
1
+ import Router from '@koa/router';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { existsSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { parse } from './workspaceStore.js';
7
+ import { HttpError } from './errors.js';
8
+ import { CodexAuthorization } from './codexAuthorization.js';
9
+ const SYSTEM = '_system', KIND = 'execution-settings';
10
+ const key = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/).refine(k => !/^(?:YAOYAO_|HERMES_YAOYAO_|NODE_OPTIONS$|LD_|DYLD_|PYTHONPATH$|PYTHONHOME$|BASH_ENV$|ENV$|HOME$|PATH$|CODEX_HOME$|HTTPS?_PROXY$|ALL_PROXY$|NO_PROXY$)/i.test(k), '该变量由运行环境管理');
11
+ const variables = z.record(key, z.string().max(32000).refine(s => !s.includes('\0'))).refine(v => Object.keys(v).length <= 100);
12
+ const resourceInput = z.object({ name: z.string().trim().min(1).max(80), kind: z.enum(['variables', 'api', 'codex']), agentIds: z.array(z.string().uuid()).max(500),
13
+ variables: variables.optional(), baseUrl: z.string().url().max(2000).optional(), token: z.string().min(1).max(32000).optional(),
14
+ tokenEnv: z.union([key, z.literal('')]).optional(), authJson: z.string().max(64000).optional(), revision: z.number().int().nonnegative().default(0) }).strict();
15
+ export const SERVICE_TOOLS = [{ id: 'yaoyao_service_request', name: 'yaoyao_service_request', description: '调用本轮获准的系统服务。serviceId 必须来自系统服务目录;凭据由系统附加。模型、图片等请求格式遵循对应服务和 Skill。', inputSchema: { type: 'object', properties: { serviceId: { type: 'string' }, path: { type: 'string' }, method: { enum: ['GET', 'POST'] }, body: { type: 'object' } }, required: ['serviceId', 'path', 'method'], additionalProperties: false } }];
16
+ /** One encrypted system store; grants reference globally unique Bot IDs. */
17
+ export class ExecutionSettings {
18
+ store;
19
+ nodes;
20
+ auth;
21
+ codexAuthorization;
22
+ testProxy = async () => { throw new HttpError(409, '未连接虚拟环境执行节点', 'proxy_node_unavailable'); };
23
+ onProxyChange = async () => { };
24
+ nodeStatus = () => [];
25
+ activeTurns = () => [];
26
+ constructor(store, nodes, auth) {
27
+ this.store = store;
28
+ this.nodes = nodes;
29
+ this.auth = auth;
30
+ this.codexAuthorization = new CodexAuthorization(auth);
31
+ if (!store.get(SYSTEM, KIND, 'selection')) {
32
+ const existing = existsSync(join(store.home, 'host-tools.json')) || !!store.db.prepare("SELECT 1 FROM workspace_entities WHERE kind='agent' LIMIT 1").get();
33
+ store.put(SYSTEM, KIND, 'selection', { mode: existing ? 'server' : 'none', revision: 1 });
34
+ }
35
+ }
36
+ selection() { const value = this.store.require(SYSTEM, KIND, 'selection'); return { ...value, credentialSource: value.mode === 'server' ? 'native' : 'yaoyao' }; }
37
+ proxy() { const value = this.store.get(SYSTEM, KIND, 'proxy'); return value ? this.nodes.open(value.sealed) : { enabled: false, protocol: 'http', host: '', port: 8080, username: '', revision: 0 }; }
38
+ entries() { return this.store.list(SYSTEM, 'execution-resource').map(row => this.nodes.open(row.sealed)); }
39
+ summary(v) { return { id: v.id, name: v.name, kind: v.kind, revision: v.revision, agentIds: v.agentIds, envKeys: [...Object.keys(v.variables ?? {}), ...(v.tokenEnv ? [v.tokenEnv] : []), ...(v.kind === 'codex' ? ['CODEX_HOME'] : [])], baseUrl: v.baseUrl, tokenEnv: v.tokenEnv, configured: true }; }
40
+ agents() { return this.store.db.prepare("SELECT owner,data FROM workspace_entities WHERE kind='agent'").all().flatMap(row => { const a = JSON.parse(row.data); return a.archived || a.remoteAgentId ? [] : [{ id: a.id, name: a.name, owner: row.owner }]; }); }
41
+ view() { const { password, ...proxy } = this.proxy(); return { execution: this.selection(), proxy: { ...proxy, hasPassword: !!password }, resources: this.entries().map(v => this.summary(v)), agents: this.agents(), nodes: this.nodeStatus(), activeTurns: this.activeTurns() }; }
42
+ saveSelection(value) { const v = parse(z.object({ mode: z.enum(['none', 'server', 'virtual']), revision: z.number().int().positive() }).strict(), value); if (v.revision !== this.selection().revision)
43
+ throw new HttpError(409, '配置已变化,请刷新', 'execution_revision_conflict'); this.store.put(SYSTEM, KIND, 'selection', { mode: v.mode, revision: v.revision + 1 }); return this.selection(); }
44
+ async saveProxy(value) {
45
+ const v = parse(z.object({ enabled: z.boolean(), protocol: z.enum(['http', 'socks5']), host: z.string().trim().max(253).refine(s => !s || /^[A-Za-z0-9.:[\]_-]+$/.test(s)), port: z.number().int().min(1).max(65535), username: z.string().max(255), password: z.string().max(255).optional(), revision: z.number().int().nonnegative() }).strict(), value);
46
+ const old = this.proxy();
47
+ if (old.revision !== v.revision)
48
+ throw new HttpError(409, '代理配置已变化,请刷新', 'execution_revision_conflict');
49
+ if (v.enabled && !v.host)
50
+ throw new HttpError(400, '请输入代理服务器地址', 'proxy_host_required');
51
+ this.store.put(SYSTEM, KIND, 'proxy', { sealed: this.nodes.seal({ ...v, password: v.password ?? old.password, revision: v.revision + 1 }) });
52
+ await this.onProxyChange();
53
+ return this.view().proxy;
54
+ }
55
+ saveResource(value, id = randomUUID()) {
56
+ const v = parse(resourceInput, value), old = this.entries().find(row => row.id === id);
57
+ if ((old?.revision ?? 0) !== v.revision)
58
+ throw new HttpError(409, '授权已变化,请刷新', 'execution_revision_conflict');
59
+ const known = new Set(this.agents().map(a => a.id));
60
+ if (v.agentIds.some(a => !known.has(a)))
61
+ throw new HttpError(400, '授权列表包含不可用的 Bot', 'execution_agent_invalid');
62
+ if (old && old.kind !== v.kind)
63
+ throw new HttpError(400, '请新建不同类型的授权', 'execution_resource_invalid');
64
+ const next = { ...old, ...v, id, revision: v.revision + 1 };
65
+ if (v.kind === 'api') {
66
+ const url = new URL(next.baseUrl ?? 'https://invalid.invalid');
67
+ if (!next.baseUrl || url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !next.token)
68
+ throw new HttpError(400, '服务需要 HTTPS 地址和授权令牌', 'execution_resource_invalid');
69
+ }
70
+ if (v.kind === 'codex') {
71
+ try {
72
+ const data = JSON.parse(next.authJson ?? '');
73
+ if (!data || typeof data !== 'object' || Array.isArray(data) || !(data.OPENAI_API_KEY || data.tokens?.access_token))
74
+ throw new Error();
75
+ }
76
+ catch {
77
+ throw new HttpError(400, '需要有效的 Codex auth.json;不会将它用作通用 API 密钥', 'execution_resource_invalid');
78
+ }
79
+ }
80
+ if (next.tokenEnv && Object.hasOwn(next.variables ?? {}, next.tokenEnv))
81
+ throw new HttpError(409, '授权令牌与环境变量名称重复', 'execution_variable_conflict');
82
+ const other = this.entries().filter(r => r.id !== id);
83
+ const ownKeys = this.summary(next).envKeys;
84
+ if (other.some(r => r.agentIds.some(a => next.agentIds.includes(a)) && this.summary(r).envKeys.some(k => ownKeys.includes(k))))
85
+ throw new HttpError(409, '同一 Bot 的变量名称重复,请合并或移除重复授权', 'execution_variable_conflict');
86
+ this.store.put(SYSTEM, 'execution-resource', id, { id, revision: next.revision, sealed: this.nodes.seal(next) });
87
+ return this.summary(next);
88
+ }
89
+ removeResource(id) { this.store.remove(SYSTEM, 'execution-resource', id); }
90
+ granted(owner, agentId) { const agent = this.store.require(owner, 'agent', agentId); if (!this.auth.isUserActive(owner) || agent.archived)
91
+ throw new HttpError(403, 'Bot 授权已结束', 'execution_grant_revoked'); return this.entries().filter(r => r.agentIds.includes(agentId)); }
92
+ openTurn(owner, agentId) {
93
+ // Resource grants belong to the Bot, not its default execution target.
94
+ // Variable/file injection is requested only by the VM tool session.
95
+ const initial = this.granted(owner, agentId);
96
+ const check = (id) => { const current = this.granted(owner, agentId); for (const r of initial.filter(v => !id || id === v.id))
97
+ if (!current.some(v => v.id === r.id && v.revision === r.revision))
98
+ throw new HttpError(403, '系统变量或服务授权已变化,请开始新一轮任务', 'execution_grant_revoked'); };
99
+ const taskEnvironment = () => { check(); const agent = this.store.require(owner, 'agent', agentId); if (agent.computerEnvironmentId) {
100
+ const peers = this.store.db.prepare("SELECT data FROM workspace_entities WHERE kind='agent'").all().map(row => JSON.parse(row.data)).filter(a => !a.archived && a.computerEnvironmentId === agent.computerEnvironmentId);
101
+ if (initial.some(r => this.summary(r).envKeys.length && peers.some(a => !r.agentIds.includes(a.id))))
102
+ throw new HttpError(403, '共享虚拟环境内仍有未获授权的 Bot;请为成员统一授权,或改用独立环境和服务工具', 'execution_shared_credentials_forbidden');
103
+ } const result = { variables: {}, files: [] }; for (const r of initial) {
104
+ Object.assign(result.variables, r.variables);
105
+ if (r.kind === 'api' && r.tokenEnv)
106
+ result.variables[r.tokenEnv] = r.token;
107
+ if (r.kind === 'codex')
108
+ result.files.push({ name: 'auth.json', content: r.authJson, envKey: 'CODEX_HOME' });
109
+ } return result; };
110
+ return { check, vmTaskEnvironment: taskEnvironment, catalog: () => initial.some(r => r.kind === 'api') ? SERVICE_TOOLS : [], description: initial.map(r => ({ id: r.id, name: r.name, kind: r.kind, envKeys: this.summary(r).envKeys, baseUrl: r.baseUrl })),
111
+ call: async (args, signal) => {
112
+ const body = parse(z.object({ serviceId: z.string(), path: z.string().max(2000), method: z.enum(['GET', 'POST']), body: z.record(z.string(), z.unknown()).optional() }).strict(), args);
113
+ check(body.serviceId);
114
+ const r = initial.find(r => r.id === body.serviceId && r.kind === 'api');
115
+ if (!r)
116
+ throw new HttpError(403, '当前环境未授权该系统服务', 'execution_service_forbidden');
117
+ const base = new URL(r.baseUrl.replace(/\/?$/, '/')), url = new URL(body.path.replace(/^\//, ''), base);
118
+ if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname) || url.username || url.password || /%(?:2f|5c|25)/i.test(url.pathname))
119
+ throw new HttpError(400, '请求路径超出已授权服务', 'execution_service_path');
120
+ try {
121
+ const response = await fetch(url, { method: body.method, headers: { authorization: `Bearer ${r.token}`, 'content-type': 'application/json' }, body: body.method === 'POST' ? JSON.stringify(body.body ?? {}) : undefined, signal: AbortSignal.any([signal, AbortSignal.timeout(60000)]), redirect: 'error' });
122
+ const chunks = [];
123
+ let size = 0;
124
+ for await (const part of response.body ?? []) {
125
+ const b = Buffer.from(part);
126
+ size += b.length;
127
+ if (size > 8 * 1024 * 1024)
128
+ throw new Error('limit');
129
+ chunks.push(b);
130
+ }
131
+ check(body.serviceId);
132
+ const data = Buffer.concat(chunks).toString().split(r.token).join('[已隐藏授权]');
133
+ return { status: response.status, body: data };
134
+ }
135
+ catch (error) {
136
+ check(body.serviceId);
137
+ throw new HttpError(502, '服务调用失败,请检查连接、授权和请求格式', 'execution_service_failed');
138
+ }
139
+ } };
140
+ }
141
+ router() {
142
+ const router = new Router({ prefix: '/api/app/admin/execution' });
143
+ router.use(async (ctx, next) => { this.auth.requireAdmin(ctx); ctx.set('Cache-Control', 'no-store'); await next(); });
144
+ const body = (ctx) => ctx.request.body;
145
+ router.get('/', ctx => { ctx.body = this.view(); });
146
+ router.put('/environment', ctx => { ctx.body = this.saveSelection(body(ctx)); });
147
+ router.put('/proxy', async (ctx) => { ctx.body = await this.saveProxy(body(ctx)); });
148
+ router.post('/proxy/test', async (ctx) => { ctx.body = await this.testProxy(); });
149
+ router.post('/codex-auth', ctx => { const { requestId } = parse(z.object({ requestId: z.string().uuid() }).strict(), body(ctx)); ctx.body = this.codexAuthorization.begin(this.auth.requireAdmin(ctx).id, requestId); });
150
+ router.get('/codex-auth/:id', ctx => { ctx.body = this.codexAuthorization.snapshot(this.auth.requireAdmin(ctx).id, ctx.params.id); });
151
+ router.delete('/codex-auth/:id', ctx => { ctx.body = this.codexAuthorization.cancel(this.auth.requireAdmin(ctx).id, ctx.params.id); });
152
+ const save = (ctx, id) => {
153
+ const { authAttemptId, ...input } = parse(resourceInput.extend({ authAttemptId: z.string().uuid().optional() }), body(ctx));
154
+ const owner = this.auth.requireAdmin(ctx).id;
155
+ if (authAttemptId) {
156
+ if (input.kind !== 'codex' || input.authJson !== undefined)
157
+ throw new HttpError(400, '请选择一种登录授权方式', 'execution_resource_invalid');
158
+ input.authJson = this.codexAuthorization.credentials(owner, authAttemptId);
159
+ }
160
+ const result = this.saveResource(input, id);
161
+ if (authAttemptId)
162
+ this.codexAuthorization.cancel(owner, authAttemptId);
163
+ return result;
164
+ };
165
+ router.post('/resources', ctx => { ctx.body = save(ctx); ctx.status = 201; });
166
+ router.put('/resources/:id', ctx => { ctx.body = save(ctx, ctx.params.id); });
167
+ router.delete('/resources/:id', ctx => { this.removeResource(ctx.params.id); ctx.body = { ok: true }; });
168
+ return router;
169
+ }
170
+ close() { this.codexAuthorization.close(); }
171
+ }
@@ -0,0 +1,247 @@
1
+ import { createPrivateKey, sign } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ export const FCM_ENDPOINT_ORIGIN = 'https://fcm.googleapis.com';
4
+ export const FCM_OAUTH_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
5
+ export const FCM_MAX_DATA_BYTES = 4_096;
6
+ export class FCMProbeError extends Error {
7
+ result;
8
+ constructor(result) {
9
+ super(result.reason || `FCM_PROBE_HTTP_${result.status}`);
10
+ this.result = result;
11
+ this.name = 'FCMProbeError';
12
+ }
13
+ }
14
+ const ACCESS_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1_000;
15
+ const FCM_QUOTA_RETRY_MILLISECONDS = 60_000;
16
+ const FCM_TRANSIENT_RETRY_MILLISECONDS = 10_000;
17
+ function encodedJSON(value) {
18
+ return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
19
+ }
20
+ function clean(value) {
21
+ return typeof value === 'string' ? value.trim() : '';
22
+ }
23
+ function serviceAccount(path) {
24
+ const value = JSON.parse(readFileSync(path, 'utf8'));
25
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
26
+ throw new Error('FCM service account file must contain a JSON object');
27
+ }
28
+ const record = value;
29
+ const clientEmail = clean(record.client_email);
30
+ const privateKey = clean(record.private_key);
31
+ const tokenUri = clean(record.token_uri) || 'https://oauth2.googleapis.com/token';
32
+ if (!clientEmail || !privateKey || !tokenUri)
33
+ throw new Error('FCM service account credentials are incomplete');
34
+ if (tokenUri !== 'https://oauth2.googleapis.com/token')
35
+ throw new Error('FCM OAuth token URI is invalid');
36
+ return { clientEmail, privateKey, tokenUri };
37
+ }
38
+ export function createFCMServiceAccountJWT(credentials, now = Date.now(), suppliedKey) {
39
+ const issuedAt = Math.floor(now / 1_000);
40
+ const header = encodedJSON({ alg: 'RS256', typ: 'JWT' });
41
+ const claims = encodedJSON({
42
+ iss: credentials.clientEmail,
43
+ scope: FCM_OAUTH_SCOPE,
44
+ aud: credentials.tokenUri,
45
+ iat: issuedAt,
46
+ exp: issuedAt + 3_600,
47
+ });
48
+ const signingInput = `${header}.${claims}`;
49
+ const key = suppliedKey ?? createPrivateKey(credentials.privateKey);
50
+ const signature = sign('RSA-SHA256', Buffer.from(signingInput, 'ascii'), key).toString('base64url');
51
+ return `${signingInput}.${signature}`;
52
+ }
53
+ function firstHeader(headers, name) {
54
+ if (!headers)
55
+ return undefined;
56
+ if (headers instanceof Headers)
57
+ return headers.get(name) ?? undefined;
58
+ const value = headers[name] ?? headers[name.toLowerCase()];
59
+ return Array.isArray(value) ? value[0] : value;
60
+ }
61
+ function retryAfterMilliseconds(value, now) {
62
+ if (!value)
63
+ return undefined;
64
+ const seconds = Number(value);
65
+ if (Number.isFinite(seconds) && seconds >= 0)
66
+ return Math.ceil(seconds * 1_000);
67
+ const at = Date.parse(value);
68
+ return Number.isNaN(at) ? undefined : Math.max(0, at - now);
69
+ }
70
+ function errorDetails(body) {
71
+ if (!body)
72
+ return {};
73
+ try {
74
+ const value = JSON.parse(body);
75
+ const error = value.error;
76
+ const status = clean(error?.status);
77
+ let reason = '';
78
+ for (const detail of error?.details ?? []) {
79
+ if (!detail || typeof detail !== 'object' || Array.isArray(detail))
80
+ continue;
81
+ const code = clean(detail.errorCode);
82
+ if (code) {
83
+ reason = code;
84
+ break;
85
+ }
86
+ }
87
+ return {
88
+ ...(reason ? { reason: reason.slice(0, 128) } : {}),
89
+ ...(status ? { status } : {}),
90
+ };
91
+ }
92
+ catch {
93
+ return { reason: 'FCM_ERROR_RESPONSE_INVALID' };
94
+ }
95
+ }
96
+ export function classifyFCMResponse(response, now = Date.now()) {
97
+ const details = errorDetails(response.body);
98
+ const common = {
99
+ status: response.status,
100
+ ...(details.reason ? { reason: details.reason } : {}),
101
+ };
102
+ if (response.status >= 200 && response.status < 300)
103
+ return { disposition: 'success', ...common };
104
+ if (details.reason === 'UNREGISTERED' || details.reason === 'INVALID_ARGUMENT') {
105
+ return { disposition: 'unregister', ...common };
106
+ }
107
+ if (response.status === 429 || response.status >= 500
108
+ || details.status === 'RESOURCE_EXHAUSTED' || details.status === 'UNAVAILABLE' || details.status === 'INTERNAL') {
109
+ const quotaLimited = response.status === 429 || details.status === 'RESOURCE_EXHAUSTED';
110
+ const retryAfterMs = retryAfterMilliseconds(firstHeader(response.headers, 'retry-after'), now)
111
+ ?? (quotaLimited ? FCM_QUOTA_RETRY_MILLISECONDS : FCM_TRANSIENT_RETRY_MILLISECONDS);
112
+ return { disposition: 'retry', ...common, retryAfterMs };
113
+ }
114
+ if (response.status === 401 || response.status === 403
115
+ || details.reason === 'SENDER_ID_MISMATCH' || details.reason === 'THIRD_PARTY_AUTH_ERROR') {
116
+ return { disposition: 'configuration', ...common };
117
+ }
118
+ return { disposition: 'failed', ...common };
119
+ }
120
+ export class FetchFCMTransport {
121
+ fetchImpl;
122
+ timeoutMilliseconds;
123
+ constructor(fetchImpl = fetch, timeoutMilliseconds = 15_000) {
124
+ this.fetchImpl = fetchImpl;
125
+ this.timeoutMilliseconds = timeoutMilliseconds;
126
+ }
127
+ async request(url, init) {
128
+ const response = await this.fetchImpl(url, {
129
+ ...init,
130
+ signal: init.signal ?? AbortSignal.timeout(this.timeoutMilliseconds),
131
+ });
132
+ const body = (await response.text()).slice(0, 64 * 1_024);
133
+ return { status: response.status, headers: response.headers, body };
134
+ }
135
+ }
136
+ export class FCMProvider {
137
+ config;
138
+ transport;
139
+ now;
140
+ credentials;
141
+ privateKey;
142
+ token;
143
+ constructor(config, options = {}) {
144
+ this.config = config;
145
+ this.transport = options.transport ?? new FetchFCMTransport();
146
+ this.now = options.now ?? Date.now;
147
+ this.credentials = serviceAccount(config.serviceAccountFile);
148
+ this.privateKey = createPrivateKey(this.credentials.privateKey);
149
+ }
150
+ async probe() {
151
+ const result = await this.send({
152
+ fid: 'probe-target-is-intentionally-invalid',
153
+ data: { probe: '1' },
154
+ priority: 'normal',
155
+ validateOnly: true,
156
+ });
157
+ // validate_only may either accept a syntactically valid probe target or
158
+ // reject the intentionally nonexistent FID after credentials are checked.
159
+ if (result.disposition === 'success' || result.disposition === 'unregister')
160
+ return;
161
+ throw new FCMProbeError(result);
162
+ }
163
+ async send(request) {
164
+ for (const [key, value] of Object.entries(request.data)) {
165
+ const normalizedKey = key.toLowerCase();
166
+ if (typeof value !== 'string') {
167
+ return { disposition: 'failed', status: 400, reason: 'DataValueMustBeString' };
168
+ }
169
+ if (normalizedKey === 'from' || normalizedKey === 'message_type'
170
+ || normalizedKey.startsWith('google.') || normalizedKey.startsWith('gcm.')) {
171
+ return { disposition: 'failed', status: 400, reason: 'ReservedDataKey' };
172
+ }
173
+ }
174
+ if (Buffer.byteLength(JSON.stringify(request.data), 'utf8') > FCM_MAX_DATA_BYTES) {
175
+ return { disposition: 'failed', status: 400, reason: 'PayloadTooLarge' };
176
+ }
177
+ const authorization = await this.authorizationToken();
178
+ if ('result' in authorization)
179
+ return authorization.result;
180
+ const ttlSeconds = Math.max(0, Math.min(2_419_200, Math.trunc(request.ttlSeconds ?? 86_400)));
181
+ const endpoint = new URL(`/v1/projects/${encodeURIComponent(this.config.projectId)}/messages:send`, FCM_ENDPOINT_ORIGIN);
182
+ const payload = {
183
+ ...(request.validateOnly ? { validate_only: true } : {}),
184
+ message: {
185
+ fid: request.fid,
186
+ data: request.data,
187
+ android: {
188
+ priority: request.priority === 'normal' ? 'NORMAL' : 'HIGH',
189
+ ttl: `${ttlSeconds}s`,
190
+ restricted_package_name: this.config.packageName,
191
+ },
192
+ },
193
+ };
194
+ try {
195
+ const response = await this.transport.request(endpoint, {
196
+ method: 'POST',
197
+ headers: {
198
+ authorization: `Bearer ${authorization.token}`,
199
+ 'content-type': 'application/json; charset=utf-8',
200
+ },
201
+ body: JSON.stringify(payload),
202
+ });
203
+ const result = classifyFCMResponse(response, this.now());
204
+ if (response.status === 401)
205
+ this.token = undefined;
206
+ return result;
207
+ }
208
+ catch {
209
+ return { disposition: 'retry', status: 0, reason: 'FCM transport unavailable' };
210
+ }
211
+ }
212
+ close() {
213
+ this.token = undefined;
214
+ }
215
+ async authorizationToken() {
216
+ const now = this.now();
217
+ if (this.token && now + ACCESS_TOKEN_REFRESH_SKEW_MS < this.token.expiresAt) {
218
+ return { token: this.token.value };
219
+ }
220
+ const assertion = createFCMServiceAccountJWT(this.credentials, now, this.privateKey);
221
+ try {
222
+ const response = await this.transport.request(new URL(this.credentials.tokenUri), {
223
+ method: 'POST',
224
+ headers: { 'content-type': 'application/x-www-form-urlencoded; charset=utf-8' },
225
+ body: new URLSearchParams({
226
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
227
+ assertion,
228
+ }).toString(),
229
+ });
230
+ if (response.status < 200 || response.status >= 300) {
231
+ const result = classifyFCMResponse(response, now);
232
+ return { result: result.disposition === 'failed' ? { ...result, disposition: 'configuration' } : result };
233
+ }
234
+ const value = JSON.parse(response.body || '{}');
235
+ const token = clean(value.access_token);
236
+ const expiresIn = Number(value.expires_in);
237
+ if (!token || !Number.isFinite(expiresIn) || expiresIn <= 0) {
238
+ return { result: { disposition: 'configuration', status: response.status, reason: 'FCM OAuth response is invalid' } };
239
+ }
240
+ this.token = { value: token, expiresAt: now + expiresIn * 1_000 };
241
+ return { token };
242
+ }
243
+ catch {
244
+ return { result: { disposition: 'retry', status: 0, reason: 'FCM OAuth transport unavailable' } };
245
+ }
246
+ }
247
+ }