@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,1422 @@
1
+ import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto';
2
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { APNsProvider, } from './apns.js';
5
+ import { FCMProvider } from './fcm.js';
6
+ import { DEFAULT_APNS_TOPIC, } from './config.js';
7
+ import { DEFAULT_FCM_PACKAGE_NAME } from './fcmConfiguration.js';
8
+ import { notificationPlainText } from './notificationText.js';
9
+ export const PUSH_EVENT_KINDS = [
10
+ 'chat.completed',
11
+ 'chat.failed',
12
+ 'chat.approval.requested',
13
+ 'chat.clarification.requested',
14
+ 'group.message.completed',
15
+ 'group.message.failed',
16
+ 'group.interaction.requested',
17
+ ];
18
+ const MAX_SUMMARY_CHARACTERS = 180;
19
+ const MAX_OUTBOX_ITEMS = 10_000;
20
+ const MAX_GROUP_SUBSCRIPTIONS_PER_USER = 512;
21
+ const MAX_INSTALLATIONS_PER_USER = 32;
22
+ const MAX_CHAT_JOBS_PER_USER = 256;
23
+ const MAX_PROCESSED_EVENTS = 50_000;
24
+ const MAX_AMBIGUOUS_CHAT_SESSIONS = 50_000;
25
+ const AMBIGUOUS_CHAT_SESSION_TTL_MS = 90 * 24 * 60 * 60 * 1_000;
26
+ const DEFAULT_EVENT_LIFETIME_MS = 24 * 60 * 60 * 1_000;
27
+ const DEDUPE_LIFETIME_MS = 90 * 24 * 60 * 60 * 1_000;
28
+ function emptyState() {
29
+ return {
30
+ schemaVersion: 2,
31
+ installations: [],
32
+ groupSubscriptions: [],
33
+ outbox: [],
34
+ processedEvents: {},
35
+ chatJobs: [],
36
+ ambiguousChatSessions: {},
37
+ providerStatus: { ios: {}, android: {} },
38
+ };
39
+ }
40
+ function isObject(value) {
41
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
42
+ }
43
+ function parseState(raw) {
44
+ const value = JSON.parse(raw);
45
+ if (!isObject(value)
46
+ || (value.schemaVersion !== 1 && value.schemaVersion !== 2)
47
+ || !Array.isArray(value.installations)
48
+ || !Array.isArray(value.groupSubscriptions)
49
+ || !Array.isArray(value.outbox)
50
+ || !isObject(value.processedEvents)
51
+ || (value.schemaVersion === 1 && !isObject(value.status))
52
+ || (value.schemaVersion === 2 && !isObject(value.providerStatus))) {
53
+ throw new Error('Unsupported or malformed push state');
54
+ }
55
+ if (value.chatJobs !== undefined && !Array.isArray(value.chatJobs)) {
56
+ throw new Error('Malformed push chat jobs');
57
+ }
58
+ if (value.ambiguousChatSessions !== undefined && !isObject(value.ambiguousChatSessions)) {
59
+ throw new Error('Malformed ambiguous push chat sessions');
60
+ }
61
+ const legacyOwners = isObject(value.chatSessionOwners)
62
+ ? value.chatSessionOwners : {};
63
+ const migratedAmbiguous = Object.fromEntries(Object.entries(legacyOwners).flatMap(([sessionID, owners]) => (Array.isArray(owners) && new Set(owners.map(String)).size > 1 ? [[sessionID, Date.now()]] : [])));
64
+ const installations = value.installations.map(record => {
65
+ if (value.schemaVersion === 1)
66
+ return { ...record, platform: 'ios' };
67
+ return record;
68
+ });
69
+ if (installations.some(record => record.platform !== 'ios' && record.platform !== 'android')) {
70
+ throw new Error('Malformed push installation platform');
71
+ }
72
+ if (installations.some(record => record.platform === 'ios'
73
+ ? typeof record.deviceToken !== 'string'
74
+ || (record.environment !== 'development' && record.environment !== 'production')
75
+ : typeof record.fid !== 'string')) {
76
+ throw new Error('Malformed push installation target');
77
+ }
78
+ const outbox = value.outbox.map(record => {
79
+ if (value.schemaVersion === 1)
80
+ return { ...record, platform: 'ios' };
81
+ return record;
82
+ });
83
+ if (outbox.some(record => record.platform !== 'ios' && record.platform !== 'android')) {
84
+ throw new Error('Malformed push outbox platform');
85
+ }
86
+ const providerStatus = value.schemaVersion === 1
87
+ ? { ios: value.status, android: {} }
88
+ : value.providerStatus;
89
+ if (!isObject(providerStatus.ios) || !isObject(providerStatus.android)) {
90
+ throw new Error('Malformed push provider status');
91
+ }
92
+ return {
93
+ schemaVersion: 2,
94
+ installations,
95
+ groupSubscriptions: value.groupSubscriptions,
96
+ outbox,
97
+ processedEvents: value.processedEvents,
98
+ ...(isObject(value.groupWatch) ? { groupWatch: value.groupWatch } : {}),
99
+ chatJobs: (value.chatJobs ?? []),
100
+ ambiguousChatSessions: {
101
+ ...migratedAmbiguous,
102
+ ...(value.ambiguousChatSessions ?? {}),
103
+ },
104
+ ...(typeof value.chatRecoveryDisabledUntil === 'number'
105
+ ? { chatRecoveryDisabledUntil: value.chatRecoveryDisabledUntil }
106
+ : {}),
107
+ providerStatus: {
108
+ ios: providerStatus.ios,
109
+ android: providerStatus.android,
110
+ },
111
+ };
112
+ }
113
+ function cloneState(state) {
114
+ return JSON.parse(JSON.stringify(state));
115
+ }
116
+ class PushStateStore {
117
+ state = emptyState();
118
+ path;
119
+ loadError;
120
+ constructor(home) {
121
+ this.path = join(home, 'push', 'state.json');
122
+ if (!existsSync(this.path))
123
+ return;
124
+ try {
125
+ chmodSync(this.path, 0o600);
126
+ const raw = readFileSync(this.path, 'utf8');
127
+ const parsed = JSON.parse(raw);
128
+ this.state = parseState(raw);
129
+ if (parsed.schemaVersion === 1)
130
+ this.write(this.state);
131
+ }
132
+ catch {
133
+ this.loadError = '推送状态文件无法读取;为避免覆盖现有数据,推送已停用';
134
+ }
135
+ }
136
+ snapshot() {
137
+ return cloneState(this.state);
138
+ }
139
+ mutate(operation) {
140
+ if (this.loadError)
141
+ throw new Error(this.loadError);
142
+ const next = cloneState(this.state);
143
+ const result = operation(next);
144
+ this.write(next);
145
+ this.state = next;
146
+ return result;
147
+ }
148
+ write(state) {
149
+ const directory = dirname(this.path);
150
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
151
+ const temporary = `${this.path}.${process.pid}.${randomUUID()}.tmp`;
152
+ let descriptor;
153
+ try {
154
+ descriptor = openSync(temporary, 'wx', 0o600);
155
+ writeFileSync(descriptor, `${JSON.stringify(state)}\n`, 'utf8');
156
+ fsyncSync(descriptor);
157
+ closeSync(descriptor);
158
+ descriptor = undefined;
159
+ renameSync(temporary, this.path);
160
+ chmodSync(this.path, 0o600);
161
+ }
162
+ catch (cause) {
163
+ if (descriptor !== undefined)
164
+ closeSync(descriptor);
165
+ try {
166
+ unlinkSync(temporary);
167
+ }
168
+ catch { /* Nothing to clean up. */ }
169
+ throw cause;
170
+ }
171
+ }
172
+ }
173
+ function requiredIdentifier(value, name, maximum = 256) {
174
+ const normalized = value.trim();
175
+ if (!normalized || normalized.length > maximum || /[\u0000-\u001f\u007f]/.test(normalized)) {
176
+ throw new Error(`${name} is invalid`);
177
+ }
178
+ return normalized;
179
+ }
180
+ function normalizedToken(value) {
181
+ const normalized = value.trim().toLowerCase();
182
+ if (!/^(?:[a-f0-9]{2}){16,256}$/.test(normalized))
183
+ throw new Error('deviceToken is invalid');
184
+ return normalized;
185
+ }
186
+ function normalizedFID(value) {
187
+ const normalized = value.trim();
188
+ if (normalized.length < 16 || normalized.length > 4_096
189
+ || !/^[A-Za-z0-9_:.\-]+$/.test(normalized))
190
+ throw new Error('fid is invalid');
191
+ return normalized;
192
+ }
193
+ function limitedText(value, maximum, name) {
194
+ const normalized = value.trim();
195
+ if (!normalized)
196
+ throw new Error(`${name} is required`);
197
+ return Array.from(normalized).slice(0, maximum).join('');
198
+ }
199
+ function publicInstallation(record) {
200
+ return {
201
+ installationId: record.installationId,
202
+ clientAccountId: record.clientAccountId,
203
+ platform: record.platform,
204
+ ...(record.platform === 'ios' ? { environment: record.environment } : {}),
205
+ ...(record.appVersion ? { appVersion: record.appVersion } : {}),
206
+ updatedAt: record.updatedAt,
207
+ };
208
+ }
209
+ function dedupePrefix(userId) {
210
+ return `${Buffer.from(userId, 'utf8').toString('base64url')}.`;
211
+ }
212
+ function dedupeKey(userId, eventId) {
213
+ const digest = createHash('sha256').update(eventId, 'utf8').digest('base64url');
214
+ return `${dedupePrefix(userId)}${digest}`;
215
+ }
216
+ function safeError(result, platform = 'ios') {
217
+ const reason = result.reason || `${platform === 'ios' ? 'APNs' : 'FCM'} HTTP ${result.status}`;
218
+ return reason
219
+ .replace(/(?:[a-fA-F0-9]{2}){16,256}/g, '[device-token]')
220
+ .replace(/[A-Za-z0-9_:.\-]{80,}/g, '[opaque-token]')
221
+ .replace(/[\r\n]+/g, ' ')
222
+ .slice(0, 500);
223
+ }
224
+ function safeProviderException(cause, installation) {
225
+ const target = installation.platform === 'ios' ? installation.deviceToken : installation.fid;
226
+ return (cause instanceof Error ? cause.message : String(cause))
227
+ .split(target).join('[push-target]')
228
+ .replace(/(?:[a-fA-F0-9]{2}){16,256}/g, '[device-token]')
229
+ .replace(/[A-Za-z0-9_:.-]{80,}/g, '[opaque-token]')
230
+ .replace(/[\r\n]+/g, ' ')
231
+ .slice(0, 500) || `${installation.platform === 'ios' ? 'APNs' : 'FCM'} provider failed`;
232
+ }
233
+ function canonicalGroupWatchAnchor(input, now) {
234
+ const epoch = requiredIdentifier(input.epoch, 'epoch', 128);
235
+ if (!Number.isSafeInteger(input.cursor) || input.cursor < 0)
236
+ throw new Error('cursor is invalid');
237
+ return {
238
+ epoch,
239
+ cursor: input.cursor,
240
+ updatedAt: new Date(now).toISOString(),
241
+ ...(input.reason ? { reason: limitedText(input.reason, 200, 'reason') } : {}),
242
+ };
243
+ }
244
+ function canonicalChatJob(input) {
245
+ const id = requiredIdentifier(input.id, 'job.id', 512);
246
+ const localUserID = requiredIdentifier(input.localUserID, 'job.localUserID');
247
+ const runtimeSessionID = requiredIdentifier(input.runtimeSessionID, 'job.runtimeSessionID', 512);
248
+ const requestID = requiredIdentifier(input.requestID, 'job.requestID', 512);
249
+ if (!['submitted', 'accepted', 'watching'].includes(input.phase))
250
+ throw new Error('job.phase is invalid');
251
+ if (!Number.isFinite(input.submittedAt) || !Number.isFinite(input.expiresAt) || input.expiresAt <= input.submittedAt) {
252
+ throw new Error('job timestamps are invalid');
253
+ }
254
+ let metadata;
255
+ if (input.metadata)
256
+ metadata = JSON.parse(JSON.stringify(input.metadata));
257
+ return {
258
+ id,
259
+ localUserID,
260
+ ...(input.profile ? { profile: requiredIdentifier(input.profile, 'job.profile') } : {}),
261
+ runtimeSessionID,
262
+ ...(input.storedSessionID
263
+ ? { storedSessionID: requiredIdentifier(input.storedSessionID, 'job.storedSessionID', 512) }
264
+ : {}),
265
+ requestID,
266
+ queued: Boolean(input.queued),
267
+ phase: input.phase,
268
+ submittedAt: input.submittedAt,
269
+ expiresAt: input.expiresAt,
270
+ ...(metadata ? { metadata } : {}),
271
+ };
272
+ }
273
+ export class PushCoordinator {
274
+ options;
275
+ store;
276
+ provider;
277
+ apns;
278
+ apnsConfigurationError;
279
+ providerFactory;
280
+ fcmProvider;
281
+ fcm;
282
+ fcmConfigurationError;
283
+ fcmProviderFactory;
284
+ now;
285
+ autoFlush;
286
+ baseRetryMilliseconds;
287
+ maxRetryMilliseconds;
288
+ maxAttempts;
289
+ isUserActive;
290
+ userAuthorizationVersion;
291
+ timer;
292
+ activeFlush;
293
+ closed = false;
294
+ runtimeErrors = {};
295
+ flushFailureCount = { ios: 0, android: 0 };
296
+ flushBlockedUntil = { ios: 0, android: 0 };
297
+ correlationSecret;
298
+ correlationError;
299
+ enabledListeners = new Set();
300
+ configurationOperation = Promise.resolve();
301
+ providerGeneration = 0;
302
+ constructor(options) {
303
+ this.options = options;
304
+ this.store = new PushStateStore(options.home);
305
+ this.apns = options.apns;
306
+ this.apnsConfigurationError = options.apnsConfigurationError;
307
+ this.providerFactory = options.providerFactory ?? (config => new APNsProvider(config));
308
+ this.provider = options.provider ?? (options.apns ? this.providerFactory(options.apns) : undefined);
309
+ this.fcm = options.fcm;
310
+ this.fcmConfigurationError = options.fcmConfigurationError;
311
+ this.fcmProviderFactory = options.fcmProviderFactory ?? (config => new FCMProvider(config));
312
+ this.fcmProvider = options.fcmProvider ?? (options.fcm ? this.fcmProviderFactory(options.fcm) : undefined);
313
+ this.now = options.now ?? Date.now;
314
+ this.autoFlush = options.autoFlush ?? true;
315
+ this.baseRetryMilliseconds = options.baseRetryMilliseconds ?? 1_000;
316
+ this.maxRetryMilliseconds = options.maxRetryMilliseconds ?? 60 * 60 * 1_000;
317
+ this.maxAttempts = options.maxAttempts ?? 36;
318
+ this.isUserActive = options.isUserActive ?? (() => true);
319
+ this.userAuthorizationVersion = options.userAuthorizationVersion;
320
+ if (this.isAnyProviderEnabled()) {
321
+ try {
322
+ this.loadCorrelationSecret();
323
+ }
324
+ catch (cause) {
325
+ this.correlationError = cause instanceof Error ? cause.message : 'Push correlation key is unavailable';
326
+ }
327
+ }
328
+ this.markPersistedJobsDisconnected();
329
+ this.scheduleNextFlush();
330
+ }
331
+ configureAPNs(apns, configurationError) {
332
+ const operation = this.configurationOperation.then(() => this.applyAPNsConfiguration(apns, configurationError));
333
+ this.configurationOperation = operation.then(() => undefined, () => undefined);
334
+ return operation;
335
+ }
336
+ async applyAPNsConfiguration(apns, configurationError) {
337
+ const wasEnabled = this.isAnyProviderEnabled();
338
+ const previous = this.provider;
339
+ const next = apns && !configurationError ? this.providerFactory(apns) : undefined;
340
+ if (this.closed) {
341
+ next?.close?.();
342
+ return;
343
+ }
344
+ this.providerGeneration += 1;
345
+ this.apns = apns;
346
+ this.apnsConfigurationError = configurationError;
347
+ this.provider = next;
348
+ delete this.runtimeErrors.ios;
349
+ this.flushFailureCount.ios = 0;
350
+ this.flushBlockedUntil.ios = 0;
351
+ if (this.isAnyProviderEnabled()) {
352
+ this.correlationError = undefined;
353
+ try {
354
+ this.loadCorrelationSecret();
355
+ }
356
+ catch (cause) {
357
+ this.correlationError = cause instanceof Error ? cause.message : 'Push correlation key is unavailable';
358
+ }
359
+ }
360
+ try {
361
+ this.store.mutate(state => {
362
+ delete state.providerStatus.ios.lastError;
363
+ delete state.providerStatus.ios.lastErrorAt;
364
+ });
365
+ }
366
+ catch { /* Existing push state errors remain authoritative. */ }
367
+ if (previous && previous !== next) {
368
+ const closePrevious = () => { try {
369
+ previous.close?.();
370
+ }
371
+ catch { /* provider is already detached */ } };
372
+ if (this.activeFlush)
373
+ void this.activeFlush.then(closePrevious, closePrevious);
374
+ else
375
+ closePrevious();
376
+ }
377
+ if (!this.isAnyProviderEnabled() && this.timer) {
378
+ clearTimeout(this.timer);
379
+ this.timer = undefined;
380
+ }
381
+ this.scheduleNextFlush();
382
+ const enabled = this.isAnyProviderEnabled();
383
+ if (enabled !== wasEnabled) {
384
+ for (const listener of this.enabledListeners) {
385
+ try {
386
+ listener(enabled);
387
+ }
388
+ catch { /* Runtime listeners cannot undo a committed configuration. */ }
389
+ }
390
+ }
391
+ }
392
+ configureFCM(fcm, configurationError) {
393
+ const operation = this.configurationOperation.then(() => this.applyFCMConfiguration(fcm, configurationError));
394
+ this.configurationOperation = operation.then(() => undefined, () => undefined);
395
+ return operation;
396
+ }
397
+ async applyFCMConfiguration(fcm, configurationError) {
398
+ const wasEnabled = this.isAnyProviderEnabled();
399
+ const previous = this.fcmProvider;
400
+ const next = fcm && !configurationError ? this.fcmProviderFactory(fcm) : undefined;
401
+ if (this.closed) {
402
+ next?.close?.();
403
+ return;
404
+ }
405
+ this.providerGeneration += 1;
406
+ this.fcm = fcm;
407
+ this.fcmConfigurationError = configurationError;
408
+ this.fcmProvider = next;
409
+ delete this.runtimeErrors.android;
410
+ this.flushFailureCount.android = 0;
411
+ this.flushBlockedUntil.android = 0;
412
+ if (this.isAnyProviderEnabled()) {
413
+ this.correlationError = undefined;
414
+ try {
415
+ this.loadCorrelationSecret();
416
+ }
417
+ catch (cause) {
418
+ this.correlationError = cause instanceof Error ? cause.message : 'Push correlation key is unavailable';
419
+ }
420
+ }
421
+ try {
422
+ this.store.mutate(state => {
423
+ delete state.providerStatus.android.lastError;
424
+ delete state.providerStatus.android.lastErrorAt;
425
+ });
426
+ }
427
+ catch { /* Existing push state errors remain authoritative. */ }
428
+ if (previous && previous !== next) {
429
+ const closePrevious = () => { try {
430
+ previous.close?.();
431
+ }
432
+ catch { /* provider is already detached */ } };
433
+ if (this.activeFlush)
434
+ void this.activeFlush.then(closePrevious, closePrevious);
435
+ else
436
+ closePrevious();
437
+ }
438
+ if (!this.isAnyProviderEnabled() && this.timer) {
439
+ clearTimeout(this.timer);
440
+ this.timer = undefined;
441
+ }
442
+ this.scheduleNextFlush();
443
+ const enabled = this.isAnyProviderEnabled();
444
+ if (enabled !== wasEnabled) {
445
+ for (const listener of this.enabledListeners) {
446
+ try {
447
+ listener(enabled);
448
+ }
449
+ catch { /* Runtime listeners cannot undo a committed configuration. */ }
450
+ }
451
+ }
452
+ }
453
+ onEnabledChange(listener) {
454
+ this.enabledListeners.add(listener);
455
+ return () => { this.enabledListeners.delete(listener); };
456
+ }
457
+ capabilities() {
458
+ const configurationError = this.apnsConfigurationError ?? this.store.loadError;
459
+ const fcmConfigurationError = this.fcmConfigurationError ?? this.store.loadError;
460
+ const iosEnabled = Boolean(this.apns && this.provider && !configurationError);
461
+ const androidEnabled = Boolean(this.fcm && this.fcmProvider && !fcmConfigurationError);
462
+ return {
463
+ protocolVersion: 1,
464
+ enabled: iosEnabled,
465
+ topic: this.apns?.topic ?? DEFAULT_APNS_TOPIC,
466
+ environments: this.apns?.environments ?? ['development', 'production'],
467
+ previewMode: 'title-and-summary',
468
+ events: PUSH_EVENT_KINDS,
469
+ maxSummaryCharacters: MAX_SUMMARY_CHARACTERS,
470
+ maximumSummaryCharacters: MAX_SUMMARY_CHARACTERS,
471
+ ...(configurationError ? { configurationError } : {}),
472
+ platforms: {
473
+ ios: {
474
+ enabled: iosEnabled,
475
+ provider: 'apns',
476
+ topic: this.apns?.topic ?? DEFAULT_APNS_TOPIC,
477
+ environments: this.apns?.environments ?? ['development', 'production'],
478
+ },
479
+ android: {
480
+ enabled: androidEnabled,
481
+ provider: 'fcm',
482
+ packageName: this.fcm?.packageName ?? DEFAULT_FCM_PACKAGE_NAME,
483
+ previewMode: 'title-and-summary',
484
+ events: PUSH_EVENT_KINDS,
485
+ maxSummaryCharacters: MAX_SUMMARY_CHARACTERS,
486
+ maximumSummaryCharacters: MAX_SUMMARY_CHARACTERS,
487
+ ...(fcmConfigurationError ? { configurationError: fcmConfigurationError } : {}),
488
+ },
489
+ },
490
+ };
491
+ }
492
+ isAnyProviderEnabled() {
493
+ const capabilities = this.capabilities();
494
+ return capabilities.platforms.ios.enabled || capabilities.platforms.android.enabled;
495
+ }
496
+ status() {
497
+ const state = this.store.snapshot();
498
+ const configurationError = this.apnsConfigurationError ?? this.store.loadError;
499
+ const stored = state.providerStatus.ios;
500
+ const runtimeError = this.runtimeErrors.ios;
501
+ const latestSuccess = stored.lastSuccessAt ? Date.parse(stored.lastSuccessAt) : 0;
502
+ const latestError = stored.lastErrorAt ? Date.parse(stored.lastErrorAt) : 0;
503
+ const configured = Boolean(this.apns && this.provider && !configurationError);
504
+ return {
505
+ configured,
506
+ healthy: configured && !this.correlationError && !runtimeError && latestSuccess >= latestError,
507
+ topic: this.apns?.topic ?? DEFAULT_APNS_TOPIC,
508
+ environments: this.apns?.environments ?? ['development', 'production'],
509
+ registrationCount: state.installations.filter(item => item.platform === 'ios').length,
510
+ pendingCount: state.outbox.filter(item => item.platform === 'ios').length,
511
+ subscriptionCount: state.groupSubscriptions.filter(item => item.enabled).length,
512
+ ...(stored.lastSuccessAt ? { lastSuccessAt: stored.lastSuccessAt } : {}),
513
+ ...(configurationError || this.correlationError || runtimeError?.message || stored.lastError
514
+ ? { lastError: configurationError ?? this.correlationError ?? runtimeError?.message ?? stored.lastError }
515
+ : {}),
516
+ ...(runtimeError?.at || stored.lastErrorAt
517
+ ? { lastErrorAt: runtimeError?.at ?? stored.lastErrorAt }
518
+ : {}),
519
+ };
520
+ }
521
+ fcmStatus() {
522
+ const state = this.store.snapshot();
523
+ const configurationError = this.fcmConfigurationError ?? this.store.loadError;
524
+ const stored = state.providerStatus.android;
525
+ const runtimeError = this.runtimeErrors.android;
526
+ const latestSuccess = stored.lastSuccessAt ? Date.parse(stored.lastSuccessAt) : 0;
527
+ const latestError = stored.lastErrorAt ? Date.parse(stored.lastErrorAt) : 0;
528
+ const configured = Boolean(this.fcm && this.fcmProvider && !configurationError);
529
+ return {
530
+ configured,
531
+ healthy: configured && !this.correlationError && !runtimeError && latestSuccess >= latestError,
532
+ provider: 'fcm',
533
+ packageName: this.fcm?.packageName ?? DEFAULT_FCM_PACKAGE_NAME,
534
+ ...(this.fcm?.projectId ? { projectId: this.fcm.projectId } : {}),
535
+ registrationCount: state.installations.filter(item => item.platform === 'android').length,
536
+ pendingCount: state.outbox.filter(item => item.platform === 'android').length,
537
+ subscriptionCount: state.groupSubscriptions.filter(item => item.enabled).length,
538
+ ...(stored.lastSuccessAt ? { lastSuccessAt: stored.lastSuccessAt } : {}),
539
+ ...(configurationError || this.correlationError || runtimeError?.message || stored.lastError
540
+ ? { lastError: configurationError ?? this.correlationError ?? runtimeError?.message ?? stored.lastError }
541
+ : {}),
542
+ ...(runtimeError?.at || stored.lastErrorAt
543
+ ? { lastErrorAt: runtimeError?.at ?? stored.lastErrorAt }
544
+ : {}),
545
+ };
546
+ }
547
+ registerInstallation(input) {
548
+ const userId = requiredIdentifier(input.userId, 'userId');
549
+ const installationId = requiredIdentifier(input.installationId, 'installationId');
550
+ const clientAccountId = requiredIdentifier(input.clientAccountId, 'clientAccountId');
551
+ let target;
552
+ if (input.platform === 'android') {
553
+ target = { platform: 'android', fid: normalizedFID(input.fid) };
554
+ }
555
+ else {
556
+ if (input.environment !== 'development' && input.environment !== 'production') {
557
+ throw new Error('environment is invalid');
558
+ }
559
+ target = {
560
+ platform: 'ios',
561
+ deviceToken: normalizedToken(input.deviceToken),
562
+ environment: input.environment,
563
+ };
564
+ }
565
+ const appVersion = input.appVersion
566
+ ? requiredIdentifier(input.appVersion, 'appVersion', 64)
567
+ : undefined;
568
+ const authorizationVersion = input.authorizationVersion
569
+ ?? this.userAuthorizationVersion?.(userId);
570
+ if (authorizationVersion !== undefined
571
+ && (!Number.isSafeInteger(authorizationVersion) || authorizationVersion < 1)) {
572
+ throw new Error('authorizationVersion is invalid');
573
+ }
574
+ const updatedAt = new Date(this.now()).toISOString();
575
+ const installation = this.store.mutate(state => {
576
+ // Reinstalls and the native-to-Expo migration can create a new local ID for
577
+ // the same APNs/FCM endpoint. Keep one registration per user/device/provider
578
+ // environment so a single event cannot produce two background banners.
579
+ const superseded = state.installations.filter(item => item.userId === userId
580
+ && !(item.installationId === installationId && item.clientAccountId === clientAccountId)
581
+ && (target.platform === 'ios'
582
+ ? item.platform === 'ios' && item.deviceToken === target.deviceToken && item.environment === target.environment
583
+ : item.platform === 'android' && item.fid === target.fid));
584
+ if (superseded.length) {
585
+ state.installations = state.installations.filter(item => !superseded.includes(item));
586
+ state.outbox = state.outbox.filter(item => !superseded.some(old => old.userId === item.userId
587
+ && old.installationId === item.installationId && old.clientAccountId === item.clientAccountId));
588
+ }
589
+ const existingIndex = state.installations.findIndex(item => item.userId === userId
590
+ && item.installationId === installationId
591
+ && item.clientAccountId === clientAccountId);
592
+ if (existingIndex >= 0) {
593
+ const existing = state.installations[existingIndex];
594
+ const base = {
595
+ userId,
596
+ installationId,
597
+ clientAccountId,
598
+ ...(authorizationVersion !== undefined ? { authorizationVersion } : {}),
599
+ ...(appVersion ? { appVersion } : {}),
600
+ badge: existing.badge,
601
+ updatedAt,
602
+ };
603
+ const next = target.platform === 'android'
604
+ ? { ...base, ...target }
605
+ : { ...base, ...target };
606
+ state.installations[existingIndex] = next;
607
+ if (existing.platform !== next.platform) {
608
+ state.outbox = state.outbox.filter(item => !(item.userId === userId
609
+ && item.installationId === installationId
610
+ && item.clientAccountId === clientAccountId));
611
+ }
612
+ return publicInstallation(next);
613
+ }
614
+ if (state.installations.filter(item => item.userId === userId).length >= MAX_INSTALLATIONS_PER_USER) {
615
+ throw new Error('Push installation limit reached');
616
+ }
617
+ const base = {
618
+ userId,
619
+ installationId,
620
+ clientAccountId,
621
+ ...(authorizationVersion !== undefined ? { authorizationVersion } : {}),
622
+ ...(appVersion ? { appVersion } : {}),
623
+ badge: 0,
624
+ updatedAt,
625
+ };
626
+ const record = target.platform === 'android'
627
+ ? { ...base, ...target }
628
+ : { ...base, ...target };
629
+ state.installations.push(record);
630
+ return publicInstallation(record);
631
+ });
632
+ this.scheduleNextFlush();
633
+ return installation;
634
+ }
635
+ unregisterInstallation(userIdValue, installationIdValue, clientAccountIdValue) {
636
+ const userId = requiredIdentifier(userIdValue, 'userId');
637
+ const installationId = requiredIdentifier(installationIdValue, 'installationId');
638
+ const clientAccountId = requiredIdentifier(clientAccountIdValue, 'clientAccountId');
639
+ return this.store.mutate(state => {
640
+ const before = state.installations.length;
641
+ state.installations = state.installations.filter(item => !(item.userId === userId
642
+ && item.installationId === installationId
643
+ && item.clientAccountId === clientAccountId));
644
+ state.outbox = state.outbox.filter(item => !(item.userId === userId
645
+ && item.installationId === installationId
646
+ && item.clientAccountId === clientAccountId));
647
+ return state.installations.length !== before;
648
+ });
649
+ }
650
+ resetBadge(userIdValue, installationIdValue, clientAccountIdValue) {
651
+ const userId = requiredIdentifier(userIdValue, 'userId');
652
+ const installationId = requiredIdentifier(installationIdValue, 'installationId');
653
+ const clientAccountId = requiredIdentifier(clientAccountIdValue, 'clientAccountId');
654
+ return this.store.mutate(state => {
655
+ const installation = state.installations.find(item => item.userId === userId
656
+ && item.installationId === installationId
657
+ && item.clientAccountId === clientAccountId);
658
+ if (installation)
659
+ installation.badge = 0;
660
+ return 0;
661
+ });
662
+ }
663
+ listGroupSubscriptions(userIdValue) {
664
+ const userId = requiredIdentifier(userIdValue, 'userId');
665
+ return this.store.snapshot().groupSubscriptions
666
+ .filter(item => item.userId === userId)
667
+ .map(({ roomId, enabled, updatedAt, lastMessageSeq }) => ({
668
+ roomId, enabled, updatedAt, ...(lastMessageSeq !== undefined ? { lastMessageSeq } : {}),
669
+ }))
670
+ .sort((left, right) => left.roomId.localeCompare(right.roomId));
671
+ }
672
+ setGroupSubscription(userIdValue, roomIdValue, enabled, baselineMessageSeq) {
673
+ const userId = requiredIdentifier(userIdValue, 'userId');
674
+ const roomId = requiredIdentifier(roomIdValue, 'roomId');
675
+ if (typeof enabled !== 'boolean')
676
+ throw new Error('enabled must be a boolean');
677
+ if (baselineMessageSeq !== undefined && (!Number.isSafeInteger(baselineMessageSeq) || baselineMessageSeq < 0)) {
678
+ throw new Error('baselineMessageSeq is invalid');
679
+ }
680
+ const updatedAt = new Date(this.now()).toISOString();
681
+ return this.store.mutate(state => {
682
+ const existing = state.groupSubscriptions.find(item => item.userId === userId && item.roomId === roomId);
683
+ if (existing) {
684
+ if (!enabled) {
685
+ state.groupSubscriptions = state.groupSubscriptions.filter(item => !(item.userId === userId && item.roomId === roomId));
686
+ state.outbox = state.outbox.filter(item => !(item.userId === userId && item.roomId === roomId));
687
+ return { roomId, enabled: false, updatedAt };
688
+ }
689
+ if (existing.enabled === enabled) {
690
+ return {
691
+ roomId, enabled: existing.enabled, updatedAt: existing.updatedAt,
692
+ ...(existing.lastMessageSeq !== undefined ? { lastMessageSeq: existing.lastMessageSeq } : {}),
693
+ };
694
+ }
695
+ existing.enabled = enabled;
696
+ existing.updatedAt = updatedAt;
697
+ if (enabled && baselineMessageSeq !== undefined)
698
+ existing.lastMessageSeq = baselineMessageSeq;
699
+ }
700
+ else {
701
+ if (!enabled)
702
+ return { roomId, enabled: false, updatedAt };
703
+ const count = state.groupSubscriptions.filter(item => item.userId === userId && item.enabled).length;
704
+ if (count >= MAX_GROUP_SUBSCRIPTIONS_PER_USER)
705
+ throw new Error('Group push subscription limit reached');
706
+ state.groupSubscriptions.push({
707
+ userId, roomId, enabled, updatedAt,
708
+ ...(enabled && baselineMessageSeq !== undefined ? { lastMessageSeq: baselineMessageSeq } : {}),
709
+ });
710
+ }
711
+ const saved = state.groupSubscriptions.find(item => item.userId === userId && item.roomId === roomId);
712
+ return {
713
+ roomId, enabled, updatedAt,
714
+ ...(saved.lastMessageSeq !== undefined ? { lastMessageSeq: saved.lastMessageSeq } : {}),
715
+ };
716
+ });
717
+ }
718
+ isGroupSubscribed(userIdValue, roomIdValue) {
719
+ const userId = requiredIdentifier(userIdValue, 'userId');
720
+ const roomId = requiredIdentifier(roomIdValue, 'roomId');
721
+ return this.store.snapshot().groupSubscriptions.some(item => item.userId === userId
722
+ && item.roomId === roomId
723
+ && item.enabled);
724
+ }
725
+ groupSubscriptionStartedAt(userIdValue, roomIdValue) {
726
+ const userId = requiredIdentifier(userIdValue, 'userId');
727
+ const roomId = requiredIdentifier(roomIdValue, 'roomId');
728
+ const subscription = this.store.snapshot().groupSubscriptions.find(item => item.userId === userId
729
+ && item.roomId === roomId
730
+ && item.enabled);
731
+ if (!subscription)
732
+ return undefined;
733
+ const value = Date.parse(subscription.updatedAt);
734
+ return Number.isNaN(value) ? undefined : value;
735
+ }
736
+ groupSubscriptionLastMessageSeq(userIdValue, roomIdValue) {
737
+ const userId = requiredIdentifier(userIdValue, 'userId');
738
+ const roomId = requiredIdentifier(roomIdValue, 'roomId');
739
+ return this.store.snapshot().groupSubscriptions.find(item => item.userId === userId
740
+ && item.roomId === roomId
741
+ && item.enabled)?.lastMessageSeq;
742
+ }
743
+ advanceGroupSubscriptionMessageSeq(userIdValue, roomIdValue, sequence) {
744
+ const userId = requiredIdentifier(userIdValue, 'userId');
745
+ const roomId = requiredIdentifier(roomIdValue, 'roomId');
746
+ if (!Number.isSafeInteger(sequence) || sequence < 0)
747
+ throw new Error('message sequence is invalid');
748
+ const snapshot = this.store.snapshot().groupSubscriptions.find(item => item.userId === userId
749
+ && item.roomId === roomId
750
+ && item.enabled);
751
+ if (!snapshot || (snapshot.lastMessageSeq ?? -1) >= sequence)
752
+ return;
753
+ this.store.mutate(state => {
754
+ const subscription = state.groupSubscriptions.find(item => item.userId === userId
755
+ && item.roomId === roomId
756
+ && item.enabled);
757
+ if (subscription && (subscription.lastMessageSeq ?? -1) < sequence)
758
+ subscription.lastMessageSeq = sequence;
759
+ });
760
+ }
761
+ subscribedUserIds(roomIdValue) {
762
+ const roomId = requiredIdentifier(roomIdValue, 'roomId');
763
+ return [...new Set(this.store.snapshot().groupSubscriptions
764
+ .filter(item => item.roomId === roomId && item.enabled)
765
+ .map(item => item.userId))];
766
+ }
767
+ activeGroupSubscriptions() {
768
+ return this.store.snapshot().groupSubscriptions
769
+ .filter(item => item.enabled)
770
+ .map(({ userId, roomId, enabled, updatedAt, lastMessageSeq }) => ({
771
+ userId, roomId, enabled, updatedAt,
772
+ ...(lastMessageSeq !== undefined ? { lastMessageSeq } : {}),
773
+ }))
774
+ .sort((left, right) => left.roomId.localeCompare(right.roomId) || left.userId.localeCompare(right.userId));
775
+ }
776
+ groupSubscribers(roomIdValue) {
777
+ return this.subscribedUserIds(roomIdValue);
778
+ }
779
+ groupWatchAnchor() {
780
+ const anchor = this.store.snapshot().groupWatch;
781
+ return anchor ? { ...anchor } : undefined;
782
+ }
783
+ resetGroupWatch(anchor) {
784
+ const next = canonicalGroupWatchAnchor(anchor, this.now());
785
+ return this.store.mutate(state => {
786
+ state.groupWatch = next;
787
+ return { ...next };
788
+ });
789
+ }
790
+ resetGroupCursor(anchor) {
791
+ return this.resetGroupWatch(anchor);
792
+ }
793
+ advanceGroupWatch(anchor) {
794
+ const next = canonicalGroupWatchAnchor(anchor, this.now());
795
+ return this.store.mutate(state => {
796
+ if (state.groupWatch && state.groupWatch.epoch !== next.epoch) {
797
+ throw new Error('group watch epoch changed without reset');
798
+ }
799
+ if (state.groupWatch && next.cursor < state.groupWatch.cursor) {
800
+ throw new Error('group watch cursor cannot move backwards');
801
+ }
802
+ state.groupWatch = next;
803
+ return { ...next };
804
+ });
805
+ }
806
+ advanceGroupCursor(anchor) {
807
+ this.advanceGroupWatch(anchor);
808
+ }
809
+ upsertChatJob(input) {
810
+ const job = canonicalChatJob(input);
811
+ return this.store.mutate(state => {
812
+ const existingIndex = state.chatJobs.findIndex(item => item.id === job.id);
813
+ if (existingIndex >= 0 && state.chatJobs[existingIndex].localUserID !== job.localUserID) {
814
+ throw new Error('job.id is already owned by another user');
815
+ }
816
+ if (existingIndex >= 0)
817
+ state.chatJobs[existingIndex] = job;
818
+ else {
819
+ if (state.chatJobs.filter(item => item.localUserID === job.localUserID).length >= MAX_CHAT_JOBS_PER_USER) {
820
+ throw new Error('Chat push job limit reached');
821
+ }
822
+ state.chatJobs.push(job);
823
+ }
824
+ if (job.storedSessionID) {
825
+ for (const [sessionID, observedAt] of Object.entries(state.ambiguousChatSessions)) {
826
+ if (!Number.isFinite(observedAt) || observedAt < this.now() - AMBIGUOUS_CHAT_SESSION_TTL_MS) {
827
+ delete state.ambiguousChatSessions[sessionID];
828
+ }
829
+ }
830
+ const owners = new Set(state.chatJobs
831
+ .filter(item => item.storedSessionID === job.storedSessionID)
832
+ .map(item => item.localUserID));
833
+ if (owners.size > 1) {
834
+ const entries = Object.entries(state.ambiguousChatSessions);
835
+ if (entries.length >= MAX_AMBIGUOUS_CHAT_SESSIONS
836
+ && state.ambiguousChatSessions[job.storedSessionID] === undefined) {
837
+ state.chatRecoveryDisabledUntil = this.now() + AMBIGUOUS_CHAT_SESSION_TTL_MS;
838
+ }
839
+ else {
840
+ state.ambiguousChatSessions[job.storedSessionID] = this.now();
841
+ }
842
+ }
843
+ }
844
+ return { ...job };
845
+ });
846
+ }
847
+ saveChatJob(input) {
848
+ this.upsertChatJob(input);
849
+ }
850
+ listChatJobs(userIdValue) {
851
+ const userId = userIdValue ? requiredIdentifier(userIdValue, 'userId') : undefined;
852
+ const now = this.now();
853
+ return this.store.snapshot().chatJobs
854
+ .filter(item => item.expiresAt > now && (!userId || item.localUserID === userId))
855
+ .sort((left, right) => left.submittedAt - right.submittedAt)
856
+ .map(item => ({ ...item, ...(item.metadata ? { metadata: { ...item.metadata } } : {}) }));
857
+ }
858
+ pendingChatJobs() {
859
+ const now = this.now();
860
+ const snapshot = this.store.snapshot();
861
+ if (snapshot.chatJobs.some(item => item.expiresAt <= now)) {
862
+ this.store.mutate(state => {
863
+ state.chatJobs = state.chatJobs.filter(item => item.expiresAt > now);
864
+ });
865
+ }
866
+ return this.listChatJobs();
867
+ }
868
+ chatJobRecoveryAllowed(job) {
869
+ if (!job.storedSessionID)
870
+ return false;
871
+ const state = this.store.snapshot();
872
+ if ((state.chatRecoveryDisabledUntil ?? 0) > this.now())
873
+ return false;
874
+ if (state.ambiguousChatSessions[job.storedSessionID] !== undefined)
875
+ return false;
876
+ const owners = new Set(state.chatJobs
877
+ .filter(item => item.storedSessionID === job.storedSessionID)
878
+ .map(item => item.localUserID));
879
+ return owners.size === 1 && owners.has(job.localUserID);
880
+ }
881
+ promptDigest(userIdValue, prompt) {
882
+ const userId = requiredIdentifier(userIdValue, 'userId');
883
+ const normalized = prompt.trim().replace(/\r\n/g, '\n');
884
+ if (!normalized || normalized.length > 200_000)
885
+ throw new Error('prompt is invalid');
886
+ if (this.correlationError)
887
+ throw new Error(this.correlationError);
888
+ return createHmac('sha256', this.loadCorrelationSecret())
889
+ .update(userId, 'utf8')
890
+ .update('\0', 'utf8')
891
+ .update(normalized, 'utf8')
892
+ .digest('base64url');
893
+ }
894
+ completeChatJob(userOrJobId, optionalJobId) {
895
+ const jobId = requiredIdentifier(optionalJobId ?? userOrJobId, 'jobId', 512);
896
+ const userId = optionalJobId ? requiredIdentifier(userOrJobId, 'userId') : undefined;
897
+ this.store.mutate(state => {
898
+ state.chatJobs = state.chatJobs.filter(item => !(item.id === jobId && (!userId || item.localUserID === userId)));
899
+ });
900
+ }
901
+ removeUser(userIdValue) {
902
+ const userId = requiredIdentifier(userIdValue, 'userId');
903
+ const prefix = dedupePrefix(userId);
904
+ return this.store.mutate(state => {
905
+ const registrations = state.installations.filter(item => item.userId === userId).length;
906
+ const subscriptions = state.groupSubscriptions.filter(item => item.userId === userId).length;
907
+ const pending = state.outbox.filter(item => item.userId === userId).length;
908
+ state.installations = state.installations.filter(item => item.userId !== userId);
909
+ state.groupSubscriptions = state.groupSubscriptions.filter(item => item.userId !== userId);
910
+ state.outbox = state.outbox.filter(item => item.userId !== userId);
911
+ state.chatJobs = state.chatJobs.filter(item => item.localUserID !== userId);
912
+ for (const key of Object.keys(state.processedEvents)) {
913
+ if (key.startsWith(prefix))
914
+ delete state.processedEvents[key];
915
+ }
916
+ return { registrations, subscriptions, pending };
917
+ });
918
+ }
919
+ enqueueNotification(input) {
920
+ const userId = requiredIdentifier(input.localUserID, 'localUserID');
921
+ const eventId = requiredIdentifier(input.eventID, 'eventID', 512);
922
+ if (this.store.snapshot().processedEvents[dedupeKey(userId, eventId)] !== undefined)
923
+ return 'duplicate';
924
+ const count = this.enqueue({
925
+ eventId,
926
+ userId,
927
+ kind: input.kind,
928
+ title: input.title,
929
+ body: input.body,
930
+ data: input.data,
931
+ collapseId: input.collapseID,
932
+ ...(input.roomID ? { roomId: input.roomID } : {}),
933
+ ...((input.topicID || input.roomID) ? { threadId: input.topicID ?? input.roomID } : {}),
934
+ });
935
+ return count > 0 ? 'enqueued' : 'ignored';
936
+ }
937
+ enqueueGroupEvent(input) {
938
+ if (!this.isGroupSubscribed(input.localUserID, input.roomID))
939
+ return 'ignored';
940
+ return this.enqueueNotification(input);
941
+ }
942
+ enqueueChatCandidate(input) {
943
+ return this.enqueueNotification(input);
944
+ }
945
+ enqueue(input) {
946
+ if (!this.isAnyProviderEnabled())
947
+ return 0;
948
+ const eventId = requiredIdentifier(input.eventId, 'eventId', 512);
949
+ const userId = requiredIdentifier(input.userId, 'userId');
950
+ try {
951
+ if (!this.isUserActive(userId))
952
+ return 0;
953
+ }
954
+ catch {
955
+ return 0;
956
+ }
957
+ if (!PUSH_EVENT_KINDS.includes(input.kind))
958
+ throw new Error('kind is invalid');
959
+ const title = notificationPlainText(input.title, { fallback: '新消息', maximum: 120 });
960
+ const body = notificationPlainText(input.body, {
961
+ fallback: '请打开夭夭查看详情', maximum: MAX_SUMMARY_CHARACTERS,
962
+ });
963
+ const clientAccountId = input.clientAccountId
964
+ ? requiredIdentifier(input.clientAccountId, 'clientAccountId')
965
+ : undefined;
966
+ const roomId = input.roomId ? requiredIdentifier(input.roomId, 'roomId') : undefined;
967
+ const collapseId = input.collapseId ? requiredIdentifier(input.collapseId, 'collapseId', 64) : undefined;
968
+ if (collapseId && Buffer.byteLength(collapseId, 'utf8') > 64)
969
+ throw new Error('collapseId is too long');
970
+ const threadId = input.threadId ? requiredIdentifier(input.threadId, 'threadId', 512) : undefined;
971
+ let data = {};
972
+ if (input.data) {
973
+ const encoded = JSON.stringify(input.data);
974
+ if (encoded === undefined)
975
+ throw new Error('data must be JSON serializable');
976
+ data = JSON.parse(encoded);
977
+ }
978
+ const now = this.now();
979
+ const expiresAt = input.expiresAt ?? now + DEFAULT_EVENT_LIFETIME_MS;
980
+ if (!Number.isFinite(expiresAt) || expiresAt <= now)
981
+ throw new Error('expiresAt must be in the future');
982
+ const capabilities = this.capabilities();
983
+ const allowedEnvironments = new Set(capabilities.environments);
984
+ const queued = this.store.mutate(state => {
985
+ for (const [key, processedAt] of Object.entries(state.processedEvents)) {
986
+ if (!Number.isFinite(processedAt) || processedAt < now - DEDUPE_LIFETIME_MS)
987
+ delete state.processedEvents[key];
988
+ }
989
+ const processed = Object.entries(state.processedEvents);
990
+ if (processed.length >= MAX_PROCESSED_EVENTS) {
991
+ processed.sort((left, right) => left[1] - right[1]);
992
+ for (const [expiredKey] of processed.slice(0, processed.length - MAX_PROCESSED_EVENTS + 1)) {
993
+ delete state.processedEvents[expiredKey];
994
+ }
995
+ }
996
+ const key = dedupeKey(userId, eventId);
997
+ if (state.processedEvents[key] !== undefined)
998
+ return 0;
999
+ const targets = state.installations.filter(item => item.userId === userId
1000
+ && this.registrationIsAuthorized(item)
1001
+ && (item.platform === 'ios'
1002
+ ? capabilities.platforms.ios.enabled && allowedEnvironments.has(item.environment)
1003
+ : capabilities.platforms.android.enabled)
1004
+ && (!clientAccountId || item.clientAccountId === clientAccountId));
1005
+ if (state.outbox.length + targets.length > MAX_OUTBOX_ITEMS)
1006
+ throw new Error('Push outbox limit reached');
1007
+ state.processedEvents[key] = now;
1008
+ for (const target of targets) {
1009
+ target.badge += 1;
1010
+ state.outbox.push({
1011
+ id: randomUUID(),
1012
+ eventId,
1013
+ userId,
1014
+ installationId: target.installationId,
1015
+ clientAccountId: target.clientAccountId,
1016
+ platform: target.platform,
1017
+ kind: input.kind,
1018
+ title,
1019
+ body,
1020
+ data,
1021
+ ...(collapseId ? { collapseId } : {}),
1022
+ ...(threadId ? { threadId } : {}),
1023
+ ...(roomId ? { roomId } : {}),
1024
+ createdAt: now,
1025
+ expiresAt,
1026
+ attempts: 0,
1027
+ nextAttemptAt: now,
1028
+ });
1029
+ }
1030
+ return targets.length;
1031
+ });
1032
+ this.scheduleNextFlush();
1033
+ return queued;
1034
+ }
1035
+ flushDue() {
1036
+ if (this.activeFlush)
1037
+ return this.activeFlush;
1038
+ if (this.closed || !this.isAnyProviderEnabled()) {
1039
+ return Promise.resolve({ delivered: 0, retried: 0, removedRegistrations: 0, failed: 0 });
1040
+ }
1041
+ const generation = this.providerGeneration;
1042
+ this.activeFlush = this.flushInternal(generation)
1043
+ .then(result => {
1044
+ if (generation === this.providerGeneration) {
1045
+ for (const platform of ['ios', 'android']) {
1046
+ this.flushFailureCount[platform] = 0;
1047
+ this.flushBlockedUntil[platform] = 0;
1048
+ delete this.runtimeErrors[platform];
1049
+ }
1050
+ }
1051
+ return result;
1052
+ })
1053
+ .catch(cause => {
1054
+ if (generation === this.providerGeneration) {
1055
+ for (const platform of ['ios', 'android']) {
1056
+ if (!this.platformEnabled(platform))
1057
+ continue;
1058
+ this.flushFailureCount[platform] += 1;
1059
+ const delay = Math.min(60_000, 1_000 * (2 ** Math.min(this.flushFailureCount[platform] - 1, 6)));
1060
+ this.flushBlockedUntil[platform] = this.now() + delay;
1061
+ this.recordRuntimeError(platform, cause);
1062
+ }
1063
+ }
1064
+ throw cause;
1065
+ })
1066
+ .finally(() => {
1067
+ this.activeFlush = undefined;
1068
+ this.scheduleNextFlush();
1069
+ });
1070
+ return this.activeFlush;
1071
+ }
1072
+ async flushInternal(generation) {
1073
+ const summary = { delivered: 0, retried: 0, removedRegistrations: 0, failed: 0 };
1074
+ const due = this.store.snapshot().outbox
1075
+ .filter(item => item.nextAttemptAt <= this.now()
1076
+ && this.platformEnabled(item.platform)
1077
+ && this.flushBlockedUntil[item.platform] <= this.now())
1078
+ .sort((left, right) => left.nextAttemptAt - right.nextAttemptAt)
1079
+ .slice(0, 100);
1080
+ for (const candidate of due) {
1081
+ if (this.closed)
1082
+ break;
1083
+ const state = this.store.snapshot();
1084
+ const item = state.outbox.find(current => current.id === candidate.id);
1085
+ if (!item)
1086
+ continue;
1087
+ let userActive = false;
1088
+ try {
1089
+ userActive = this.isUserActive(item.userId);
1090
+ }
1091
+ catch {
1092
+ userActive = false;
1093
+ }
1094
+ if (!userActive) {
1095
+ this.store.mutate(current => {
1096
+ current.installations = current.installations.filter(entry => entry.userId !== item.userId);
1097
+ current.groupSubscriptions = current.groupSubscriptions.filter(entry => entry.userId !== item.userId);
1098
+ current.outbox = current.outbox.filter(entry => entry.userId !== item.userId);
1099
+ current.chatJobs = current.chatJobs.filter(entry => entry.localUserID !== item.userId);
1100
+ });
1101
+ summary.failed += 1;
1102
+ continue;
1103
+ }
1104
+ const installation = state.installations.find(current => current.userId === item.userId
1105
+ && current.installationId === item.installationId
1106
+ && current.clientAccountId === item.clientAccountId);
1107
+ if (installation && !this.registrationIsAuthorized(installation)) {
1108
+ this.store.mutate(current => {
1109
+ current.installations = current.installations.filter(entry => !(entry.userId === item.userId
1110
+ && entry.installationId === item.installationId
1111
+ && entry.clientAccountId === item.clientAccountId));
1112
+ current.outbox = current.outbox.filter(entry => !(entry.userId === item.userId
1113
+ && entry.installationId === item.installationId
1114
+ && entry.clientAccountId === item.clientAccountId));
1115
+ });
1116
+ summary.failed += 1;
1117
+ continue;
1118
+ }
1119
+ if (installation && installation.platform !== item.platform) {
1120
+ this.store.mutate(current => { current.outbox = current.outbox.filter(entry => entry.id !== item.id); });
1121
+ summary.failed += 1;
1122
+ continue;
1123
+ }
1124
+ if (installation?.platform === 'ios'
1125
+ && !this.capabilities().environments.includes(installation.environment)) {
1126
+ this.store.mutate(current => { current.outbox = current.outbox.filter(entry => entry.id !== item.id); });
1127
+ summary.failed += 1;
1128
+ continue;
1129
+ }
1130
+ const subscribed = !item.roomId || state.groupSubscriptions.some(subscription => subscription.userId === item.userId
1131
+ && subscription.roomId === item.roomId
1132
+ && subscription.enabled);
1133
+ if (!installation || !subscribed || item.expiresAt <= this.now()) {
1134
+ this.store.mutate(current => { current.outbox = current.outbox.filter(entry => entry.id !== item.id); });
1135
+ summary.failed += 1;
1136
+ continue;
1137
+ }
1138
+ let result;
1139
+ try {
1140
+ result = installation.platform === 'ios'
1141
+ ? await this.provider.send({
1142
+ deviceToken: installation.deviceToken,
1143
+ environment: installation.environment,
1144
+ payload: {
1145
+ ...item.data,
1146
+ aps: {
1147
+ alert: { title: item.title, body: item.body },
1148
+ sound: 'default',
1149
+ badge: installation.badge,
1150
+ ...(item.threadId ? { 'thread-id': item.threadId } : {}),
1151
+ },
1152
+ version: 1,
1153
+ eventId: item.eventId,
1154
+ kind: item.kind,
1155
+ clientAccountId: item.clientAccountId,
1156
+ },
1157
+ apnsId: item.id,
1158
+ ...(item.collapseId ? { collapseId: item.collapseId } : {}),
1159
+ expiration: Math.floor(item.expiresAt / 1_000),
1160
+ })
1161
+ : await this.fcmProvider.send({
1162
+ fid: installation.fid,
1163
+ data: this.fcmData(item),
1164
+ ttlSeconds: Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1_000)),
1165
+ priority: 'high',
1166
+ });
1167
+ }
1168
+ catch (cause) {
1169
+ // Provider implementations normally return a classified result, but a
1170
+ // programming/runtime exception in one sender must not starve the
1171
+ // other platform's durable queue.
1172
+ result = {
1173
+ disposition: 'retry',
1174
+ status: 0,
1175
+ reason: safeProviderException(cause, installation),
1176
+ };
1177
+ }
1178
+ const at = new Date(this.now()).toISOString();
1179
+ if (generation !== this.providerGeneration) {
1180
+ if (result.disposition === 'success') {
1181
+ this.store.mutate(current => {
1182
+ current.outbox = current.outbox.filter(entry => entry.id !== item.id);
1183
+ current.providerStatus[item.platform].lastSuccessAt = at;
1184
+ });
1185
+ summary.delivered += 1;
1186
+ }
1187
+ else {
1188
+ this.store.mutate(current => {
1189
+ const pending = current.outbox.find(entry => entry.id === item.id);
1190
+ if (pending)
1191
+ pending.nextAttemptAt = this.now();
1192
+ });
1193
+ summary.retried += 1;
1194
+ }
1195
+ break;
1196
+ }
1197
+ if (result.disposition === 'success') {
1198
+ this.store.mutate(current => {
1199
+ current.outbox = current.outbox.filter(entry => entry.id !== item.id);
1200
+ current.providerStatus[item.platform].lastSuccessAt = at;
1201
+ });
1202
+ summary.delivered += 1;
1203
+ }
1204
+ else if (result.disposition === 'unregister') {
1205
+ let registrationRotated = false;
1206
+ this.store.mutate(current => {
1207
+ const latest = current.installations.find(entry => entry.userId === item.userId
1208
+ && entry.installationId === item.installationId
1209
+ && entry.clientAccountId === item.clientAccountId);
1210
+ registrationRotated = Boolean(latest && this.registrationIdentity(latest) !== this.registrationIdentity(installation));
1211
+ if (registrationRotated) {
1212
+ const pending = current.outbox.find(entry => entry.id === item.id);
1213
+ if (pending) {
1214
+ pending.attempts = 0;
1215
+ pending.nextAttemptAt = this.now();
1216
+ }
1217
+ return;
1218
+ }
1219
+ current.installations = current.installations.filter(entry => !(entry.userId === item.userId
1220
+ && entry.installationId === item.installationId
1221
+ && entry.clientAccountId === item.clientAccountId));
1222
+ current.outbox = current.outbox.filter(entry => !(entry.userId === item.userId
1223
+ && entry.installationId === item.installationId
1224
+ && entry.clientAccountId === item.clientAccountId));
1225
+ });
1226
+ if (registrationRotated)
1227
+ summary.retried += 1;
1228
+ else
1229
+ summary.removedRegistrations += 1;
1230
+ }
1231
+ else if (result.disposition === 'retry' || result.disposition === 'configuration') {
1232
+ const attempts = item.attempts + 1;
1233
+ const exhausted = attempts >= this.maxAttempts || item.expiresAt <= this.now();
1234
+ const delay = Math.min(this.maxRetryMilliseconds, Math.max(result.retryAfterMs ?? 0, this.baseRetryMilliseconds * (2 ** Math.max(0, attempts - 1))));
1235
+ this.store.mutate(current => {
1236
+ const pending = current.outbox.find(entry => entry.id === item.id);
1237
+ if (pending) {
1238
+ if (exhausted)
1239
+ current.outbox = current.outbox.filter(entry => entry.id !== item.id);
1240
+ else {
1241
+ pending.attempts = attempts;
1242
+ pending.nextAttemptAt = this.now() + delay;
1243
+ }
1244
+ }
1245
+ current.providerStatus[item.platform].lastError = safeError(result, item.platform);
1246
+ current.providerStatus[item.platform].lastErrorAt = at;
1247
+ });
1248
+ if (exhausted)
1249
+ summary.failed += 1;
1250
+ else
1251
+ summary.retried += 1;
1252
+ }
1253
+ else {
1254
+ this.store.mutate(current => {
1255
+ current.outbox = current.outbox.filter(entry => entry.id !== item.id);
1256
+ current.providerStatus[item.platform].lastError = safeError(result, item.platform);
1257
+ current.providerStatus[item.platform].lastErrorAt = at;
1258
+ });
1259
+ summary.failed += 1;
1260
+ }
1261
+ }
1262
+ return summary;
1263
+ }
1264
+ platformEnabled(platform) {
1265
+ const capabilities = this.capabilities();
1266
+ return platform === 'ios' ? capabilities.platforms.ios.enabled : capabilities.platforms.android.enabled;
1267
+ }
1268
+ registrationIdentity(installation) {
1269
+ return installation.platform === 'ios'
1270
+ ? `ios:${installation.environment}:${installation.deviceToken}`
1271
+ : `android:${installation.fid}`;
1272
+ }
1273
+ fcmData(item) {
1274
+ const data = {};
1275
+ for (const [key, value] of Object.entries(item.data)) {
1276
+ if (value === undefined || value === null)
1277
+ continue;
1278
+ if (typeof value === 'string')
1279
+ data[key] = value;
1280
+ else if (typeof value === 'number' || typeof value === 'boolean')
1281
+ data[key] = String(value);
1282
+ else
1283
+ data[key] = JSON.stringify(value);
1284
+ }
1285
+ return {
1286
+ ...data,
1287
+ version: '1',
1288
+ eventId: item.eventId,
1289
+ kind: item.kind,
1290
+ clientAccountId: item.clientAccountId,
1291
+ title: item.title,
1292
+ body: item.body,
1293
+ ...(item.collapseId ? { collapseId: item.collapseId } : {}),
1294
+ ...(item.threadId ? { threadId: item.threadId } : {}),
1295
+ ...(item.roomId ? { roomId: item.roomId } : {}),
1296
+ };
1297
+ }
1298
+ scheduleNextFlush() {
1299
+ if (!this.autoFlush || this.closed || !this.isAnyProviderEnabled() || this.activeFlush)
1300
+ return;
1301
+ if (this.timer)
1302
+ clearTimeout(this.timer);
1303
+ this.timer = undefined;
1304
+ const next = this.store.snapshot().outbox.reduce((earliest, item) => {
1305
+ if (!this.platformEnabled(item.platform))
1306
+ return earliest;
1307
+ const attemptAt = Math.max(item.nextAttemptAt, this.flushBlockedUntil[item.platform]);
1308
+ return earliest === undefined || attemptAt < earliest ? attemptAt : earliest;
1309
+ }, undefined);
1310
+ if (next === undefined)
1311
+ return;
1312
+ const delay = Math.max(0, Math.min(2_147_483_647, next - this.now()));
1313
+ this.timer = setTimeout(() => {
1314
+ this.timer = undefined;
1315
+ void this.flushDue().catch(() => undefined);
1316
+ }, delay);
1317
+ this.timer.unref();
1318
+ }
1319
+ close() {
1320
+ this.closed = true;
1321
+ if (this.timer)
1322
+ clearTimeout(this.timer);
1323
+ this.timer = undefined;
1324
+ this.provider?.close?.();
1325
+ this.fcmProvider?.close?.();
1326
+ this.enabledListeners.clear();
1327
+ }
1328
+ recordRuntimeError(platform, cause) {
1329
+ const raw = cause instanceof Error ? cause.message : String(cause);
1330
+ const message = raw
1331
+ .replace(/[a-fA-F0-9]{32,}/g, '[redacted]')
1332
+ .replace(/[\r\n]+/g, ' ')
1333
+ .slice(0, 500) || '推送后台任务失败';
1334
+ const at = new Date(this.now()).toISOString();
1335
+ this.runtimeErrors[platform] = { message, at };
1336
+ try {
1337
+ this.store.mutate(state => {
1338
+ state.providerStatus[platform].lastError = message;
1339
+ state.providerStatus[platform].lastErrorAt = at;
1340
+ });
1341
+ }
1342
+ catch {
1343
+ // The in-memory status remains available when the push state volume is
1344
+ // the reason persistence failed. Never let optional push stop 15300.
1345
+ }
1346
+ }
1347
+ registrationIsAuthorized(installation) {
1348
+ if (!this.userAuthorizationVersion)
1349
+ return true;
1350
+ try {
1351
+ const current = this.userAuthorizationVersion(installation.userId);
1352
+ return current !== undefined && installation.authorizationVersion === current;
1353
+ }
1354
+ catch {
1355
+ return false;
1356
+ }
1357
+ }
1358
+ markPersistedJobsDisconnected() {
1359
+ try {
1360
+ const jobs = this.store.snapshot().chatJobs;
1361
+ if (!jobs.some(job => !Number.isFinite(Number(job.metadata?.disconnectedAt))))
1362
+ return;
1363
+ const disconnectedAt = this.now();
1364
+ this.store.mutate(state => {
1365
+ state.chatJobs = state.chatJobs.map(job => ({
1366
+ ...job,
1367
+ metadata: {
1368
+ ...job.metadata,
1369
+ disconnectedAt: Number.isFinite(Number(job.metadata?.disconnectedAt))
1370
+ ? job.metadata.disconnectedAt
1371
+ : disconnectedAt,
1372
+ recoveredAfterRestart: true,
1373
+ },
1374
+ }));
1375
+ });
1376
+ }
1377
+ catch {
1378
+ // A corrupt/unwritable optional push state already disables recovery.
1379
+ }
1380
+ }
1381
+ loadCorrelationSecret() {
1382
+ if (this.correlationSecret)
1383
+ return this.correlationSecret;
1384
+ const path = join(this.options.home, 'push', 'correlation.key');
1385
+ try {
1386
+ const existing = readFileSync(path);
1387
+ if (existing.byteLength !== 32)
1388
+ throw new Error('Push correlation key has an invalid length');
1389
+ chmodSync(path, 0o600);
1390
+ this.correlationSecret = existing;
1391
+ return existing;
1392
+ }
1393
+ catch (cause) {
1394
+ if (cause.code !== 'ENOENT')
1395
+ throw cause;
1396
+ }
1397
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
1398
+ const generated = randomBytes(32);
1399
+ let descriptor;
1400
+ try {
1401
+ descriptor = openSync(path, 'wx', 0o600);
1402
+ writeFileSync(descriptor, generated);
1403
+ fsyncSync(descriptor);
1404
+ closeSync(descriptor);
1405
+ descriptor = undefined;
1406
+ this.correlationSecret = generated;
1407
+ return generated;
1408
+ }
1409
+ catch (cause) {
1410
+ if (descriptor !== undefined)
1411
+ closeSync(descriptor);
1412
+ if (cause.code === 'EEXIST') {
1413
+ const existing = readFileSync(path);
1414
+ if (existing.byteLength !== 32)
1415
+ throw new Error('Push correlation key has an invalid length');
1416
+ this.correlationSecret = existing;
1417
+ return existing;
1418
+ }
1419
+ throw cause;
1420
+ }
1421
+ }
1422
+ }