@stage-labs/metro 0.1.0-beta.2 → 0.1.0-beta.200

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 (391) hide show
  1. package/dist/api.js +11 -0
  2. package/dist/claude-settings.js +40 -0
  3. package/dist/claude.js +163 -0
  4. package/dist/cli.js +77 -567
  5. package/dist/control.js +74 -0
  6. package/dist/hold.js +211 -0
  7. package/dist/local.js +43 -0
  8. package/dist/mcp-config.js +25 -0
  9. package/dist/node-name.js +71 -0
  10. package/dist/onboarding.js +44 -0
  11. package/dist/provider-flags.js +9 -0
  12. package/dist/route.js +58 -0
  13. package/dist/runtime-install.js +97 -0
  14. package/dist/runtime.js +74 -0
  15. package/dist/serve.js +158 -0
  16. package/dist/service.js +243 -0
  17. package/dist/tail.js +102 -144
  18. package/dist/update.js +45 -0
  19. package/dist/version.js +97 -0
  20. package/package.json +14 -23
  21. package/runtime/marketplace/.claude-plugin/marketplace.json +12 -0
  22. package/runtime/marketplace/plugin/.claude-plugin/plugin.json +17 -0
  23. package/runtime/marketplace/plugin/.mcp.json +1 -0
  24. package/runtime/marketplace/plugin/bin/guard.mjs +71 -0
  25. package/runtime/marketplace/plugin/bin/metro-plugin.mjs +30 -0
  26. package/runtime/marketplace/plugin/bin/policy.mjs +97 -0
  27. package/runtime/marketplace/plugin/bin/session-start.mjs +31 -0
  28. package/runtime/marketplace/plugin/hooks/hooks.json +25 -0
  29. package/runtime/marketplace/plugin/orchestrator.md +24 -0
  30. package/runtime/node_modules/@metro-labs/core/package.json +47 -0
  31. package/runtime/node_modules/@metro-labs/core/src/endpoints.ts +7 -0
  32. package/runtime/node_modules/@metro-labs/core/src/events.ts +119 -0
  33. package/runtime/node_modules/@metro-labs/core/src/identity.ts +7 -0
  34. package/runtime/node_modules/@metro-labs/core/src/ids.ts +24 -0
  35. package/runtime/node_modules/@metro-labs/core/src/is-record.ts +2 -0
  36. package/runtime/node_modules/@metro-labs/core/src/lines.ts +91 -0
  37. package/runtime/node_modules/@metro-labs/core/src/log.ts +42 -0
  38. package/runtime/node_modules/@metro-labs/core/src/protocol.ts +227 -0
  39. package/runtime/node_modules/@metro-labs/core/src/secure-fs.ts +74 -0
  40. package/runtime/node_modules/@metro-labs/core/src/station-names.ts +13 -0
  41. package/runtime/node_modules/@metro-labs/core/src/stations/account-files.ts +41 -0
  42. package/runtime/node_modules/@metro-labs/core/src/stations/account-store.ts +60 -0
  43. package/runtime/node_modules/@metro-labs/core/src/stations/attachments.ts +196 -0
  44. package/runtime/node_modules/@metro-labs/core/src/stations/messaging-normalize.ts +88 -0
  45. package/runtime/node_modules/@metro-labs/core/src/stations/profile.ts +58 -0
  46. package/runtime/node_modules/@metro-labs/core/src/stations/sender-profile.ts +64 -0
  47. package/runtime/node_modules/@metro-labs/core/src/stations/station-runtime.ts +61 -0
  48. package/runtime/node_modules/@metro-labs/core/src/stations/train-boot.ts +42 -0
  49. package/runtime/node_modules/@metro-labs/core/src/stations/train-events.ts +89 -0
  50. package/runtime/node_modules/@metro-labs/core/src/stations/types.ts +123 -0
  51. package/runtime/node_modules/@metro-labs/core/src/str.ts +5 -0
  52. package/runtime/node_modules/@metro-labs/core/src/tickets.ts +37 -0
  53. package/runtime/node_modules/@metro-labs/core/src/train-error.ts +53 -0
  54. package/runtime/node_modules/@metro-labs/core/src/version.ts +2 -0
  55. package/runtime/node_modules/@metro-labs/daemon/package.json +48 -0
  56. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/agent-fs.ts +134 -0
  57. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/files-api.ts +12 -0
  58. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/files.ts +119 -0
  59. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/home-fs.ts +113 -0
  60. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/job-env.ts +51 -0
  61. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/provision.ts +91 -0
  62. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/schedule-detail.ts +100 -0
  63. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/schedules-api.ts +27 -0
  64. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/schedules.ts +252 -0
  65. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/unit-files.ts +61 -0
  66. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/user.ts +91 -0
  67. package/runtime/node_modules/@metro-labs/daemon/src/agent-user/view.ts +87 -0
  68. package/runtime/node_modules/@metro-labs/daemon/src/agents/account-attach.ts +19 -0
  69. package/runtime/node_modules/@metro-labs/daemon/src/agents/account-lookups.ts +55 -0
  70. package/runtime/node_modules/@metro-labs/daemon/src/agents/account-routes.ts +76 -0
  71. package/runtime/node_modules/@metro-labs/daemon/src/agents/accounts-api.ts +357 -0
  72. package/runtime/node_modules/@metro-labs/daemon/src/agents/admin.ts +30 -0
  73. package/runtime/node_modules/@metro-labs/daemon/src/agents/allowlist.ts +59 -0
  74. package/runtime/node_modules/@metro-labs/daemon/src/agents/api.ts +131 -0
  75. package/runtime/node_modules/@metro-labs/daemon/src/agents/bundle.ts +132 -0
  76. package/runtime/node_modules/@metro-labs/daemon/src/agents/file-admin.ts +305 -0
  77. package/runtime/node_modules/@metro-labs/daemon/src/agents/files.ts +168 -0
  78. package/runtime/node_modules/@metro-labs/daemon/src/agents/keys.ts +35 -0
  79. package/runtime/node_modules/@metro-labs/daemon/src/agents/map.ts +128 -0
  80. package/runtime/node_modules/@metro-labs/daemon/src/agents/policy-route.ts +27 -0
  81. package/runtime/node_modules/@metro-labs/daemon/src/agents/scope.ts +64 -0
  82. package/runtime/node_modules/@metro-labs/daemon/src/agents/sender-cards.ts +86 -0
  83. package/runtime/node_modules/@metro-labs/daemon/src/agents/senders.ts +38 -0
  84. package/runtime/node_modules/@metro-labs/daemon/src/approvals/api.ts +55 -0
  85. package/runtime/node_modules/@metro-labs/daemon/src/approvals/needs.ts +2 -0
  86. package/runtime/node_modules/@metro-labs/daemon/src/approvals/pending.ts +149 -0
  87. package/runtime/node_modules/@metro-labs/daemon/src/approvals/preview.ts +66 -0
  88. package/runtime/node_modules/@metro-labs/daemon/src/boot/boot.ts +221 -0
  89. package/runtime/node_modules/@metro-labs/daemon/src/boot/connect-hint.ts +39 -0
  90. package/runtime/node_modules/@metro-labs/daemon/src/boot/crash-guard.ts +49 -0
  91. package/runtime/node_modules/@metro-labs/daemon/src/boot/local-owner.ts +21 -0
  92. package/runtime/node_modules/@metro-labs/daemon/src/boot/paths.ts +106 -0
  93. package/runtime/node_modules/@metro-labs/daemon/src/channels/addressed.ts +26 -0
  94. package/runtime/node_modules/@metro-labs/daemon/src/channels/dedupe.ts +12 -0
  95. package/runtime/node_modules/@metro-labs/daemon/src/channels/inbound.ts +370 -0
  96. package/runtime/node_modules/@metro-labs/daemon/src/channels/media-note.ts +90 -0
  97. package/runtime/node_modules/@metro-labs/daemon/src/channels/pending.ts +78 -0
  98. package/runtime/node_modules/@metro-labs/daemon/src/channels/react-note.ts +13 -0
  99. package/runtime/node_modules/@metro-labs/daemon/src/channels/relay.ts +129 -0
  100. package/runtime/node_modules/@metro-labs/daemon/src/channels/reply-id.ts +1 -0
  101. package/runtime/node_modules/@metro-labs/daemon/src/channels/webhook-note.ts +51 -0
  102. package/runtime/node_modules/@metro-labs/daemon/src/claude/api.ts +355 -0
  103. package/runtime/node_modules/@metro-labs/daemon/src/claude/files.ts +359 -0
  104. package/runtime/node_modules/@metro-labs/daemon/src/claude/login.ts +208 -0
  105. package/runtime/node_modules/@metro-labs/daemon/src/claude/memory.ts +82 -0
  106. package/runtime/node_modules/@metro-labs/daemon/src/claude/onboarding.ts +60 -0
  107. package/runtime/node_modules/@metro-labs/daemon/src/claude/plugin-install.ts +149 -0
  108. package/runtime/node_modules/@metro-labs/daemon/src/claude/session-files.ts +75 -0
  109. package/runtime/node_modules/@metro-labs/daemon/src/claude/session.ts +283 -0
  110. package/runtime/node_modules/@metro-labs/daemon/src/claude/settings.ts +109 -0
  111. package/runtime/node_modules/@metro-labs/daemon/src/claude/setup.ts +271 -0
  112. package/runtime/node_modules/@metro-labs/daemon/src/claude/skills.ts +120 -0
  113. package/runtime/node_modules/@metro-labs/daemon/src/claude/version.ts +113 -0
  114. package/runtime/node_modules/@metro-labs/daemon/src/connectors/api.ts +306 -0
  115. package/runtime/node_modules/@metro-labs/daemon/src/connectors/config.ts +176 -0
  116. package/runtime/node_modules/@metro-labs/daemon/src/connectors/gates.ts +72 -0
  117. package/runtime/node_modules/@metro-labs/daemon/src/connectors/health.ts +18 -0
  118. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-client.ts +159 -0
  119. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-discovery.ts +135 -0
  120. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-routes.ts +158 -0
  121. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth.ts +166 -0
  122. package/runtime/node_modules/@metro-labs/daemon/src/connectors/plugin-sync.ts +131 -0
  123. package/runtime/node_modules/@metro-labs/daemon/src/connectors/reach.ts +27 -0
  124. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-policy.ts +90 -0
  125. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-target.ts +29 -0
  126. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay.ts +348 -0
  127. package/runtime/node_modules/@metro-labs/daemon/src/connectors/store.ts +358 -0
  128. package/runtime/node_modules/@metro-labs/daemon/src/connectors/tools.ts +81 -0
  129. package/runtime/node_modules/@metro-labs/daemon/src/connectors/url.ts +37 -0
  130. package/runtime/node_modules/@metro-labs/daemon/src/connectors/verify.ts +106 -0
  131. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-grant.ts +99 -0
  132. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-owner.ts +32 -0
  133. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-reaper.ts +174 -0
  134. package/runtime/node_modules/@metro-labs/daemon/src/files/attach-serve.ts +123 -0
  135. package/runtime/node_modules/@metro-labs/daemon/src/files/upload-api.ts +278 -0
  136. package/runtime/node_modules/@metro-labs/daemon/src/files/upload-store.ts +181 -0
  137. package/runtime/node_modules/@metro-labs/daemon/src/gateway/bedrock.ts +233 -0
  138. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-auth.ts +208 -0
  139. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-device.ts +91 -0
  140. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-stream.ts +173 -0
  141. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex-translate.ts +194 -0
  142. package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex.ts +137 -0
  143. package/runtime/node_modules/@metro-labs/daemon/src/gateway/effort.ts +77 -0
  144. package/runtime/node_modules/@metro-labs/daemon/src/gateway/eventstream.ts +123 -0
  145. package/runtime/node_modules/@metro-labs/daemon/src/gateway/forward.ts +237 -0
  146. package/runtime/node_modules/@metro-labs/daemon/src/gateway/frames.ts +118 -0
  147. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gateway.ts +274 -0
  148. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-auth.ts +160 -0
  149. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-client.ts +46 -0
  150. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-setup.ts +150 -0
  151. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-stream.ts +139 -0
  152. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini-translate.ts +223 -0
  153. package/runtime/node_modules/@metro-labs/daemon/src/gateway/gemini.ts +208 -0
  154. package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-api.ts +199 -0
  155. package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-config.ts +299 -0
  156. package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-signin.ts +193 -0
  157. package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-store.ts +70 -0
  158. package/runtime/node_modules/@metro-labs/daemon/src/gateway/openrouter.ts +90 -0
  159. package/runtime/node_modules/@metro-labs/daemon/src/gateway/pkce.ts +36 -0
  160. package/runtime/node_modules/@metro-labs/daemon/src/gateway/provider-models.ts +66 -0
  161. package/runtime/node_modules/@metro-labs/daemon/src/gateway/served.ts +18 -0
  162. package/runtime/node_modules/@metro-labs/daemon/src/gateway/subscription.ts +120 -0
  163. package/runtime/node_modules/@metro-labs/daemon/src/gateway/text.ts +15 -0
  164. package/runtime/node_modules/@metro-labs/daemon/src/gateway/usage.ts +244 -0
  165. package/runtime/node_modules/@metro-labs/daemon/src/mcp/accounts.ts +156 -0
  166. package/runtime/node_modules/@metro-labs/daemon/src/mcp/attachment-schema.ts +91 -0
  167. package/runtime/node_modules/@metro-labs/daemon/src/mcp/call-tools.ts +226 -0
  168. package/runtime/node_modules/@metro-labs/daemon/src/mcp/ctx.ts +62 -0
  169. package/runtime/node_modules/@metro-labs/daemon/src/mcp/event-store.ts +90 -0
  170. package/runtime/node_modules/@metro-labs/daemon/src/mcp/group-tools.ts +129 -0
  171. package/runtime/node_modules/@metro-labs/daemon/src/mcp/index.ts +137 -0
  172. package/runtime/node_modules/@metro-labs/daemon/src/mcp/instructions.ts +19 -0
  173. package/runtime/node_modules/@metro-labs/daemon/src/mcp/member-tools.ts +72 -0
  174. package/runtime/node_modules/@metro-labs/daemon/src/mcp/permission-prompt.ts +87 -0
  175. package/runtime/node_modules/@metro-labs/daemon/src/mcp/permission-relay.ts +79 -0
  176. package/runtime/node_modules/@metro-labs/daemon/src/mcp/policy-gate.ts +83 -0
  177. package/runtime/node_modules/@metro-labs/daemon/src/mcp/policy-snapshot.ts +79 -0
  178. package/runtime/node_modules/@metro-labs/daemon/src/mcp/profile-lookup.ts +60 -0
  179. package/runtime/node_modules/@metro-labs/daemon/src/mcp/profile-tool.ts +96 -0
  180. package/runtime/node_modules/@metro-labs/daemon/src/mcp/raw-get-stream.ts +207 -0
  181. package/runtime/node_modules/@metro-labs/daemon/src/mcp/read-tool.ts +87 -0
  182. package/runtime/node_modules/@metro-labs/daemon/src/mcp/request-identity.ts +46 -0
  183. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session-slot.ts +48 -0
  184. package/runtime/node_modules/@metro-labs/daemon/src/mcp/session.ts +202 -0
  185. package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-catalog.ts +88 -0
  186. package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-def.ts +9 -0
  187. package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-dispatch.ts +225 -0
  188. package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-schemas.ts +333 -0
  189. package/runtime/node_modules/@metro-labs/daemon/src/mcp/upload-tool.ts +61 -0
  190. package/runtime/node_modules/@metro-labs/daemon/src/metro-user/api.ts +43 -0
  191. package/runtime/node_modules/@metro-labs/daemon/src/metro-user/helper-script.ts +126 -0
  192. package/runtime/node_modules/@metro-labs/daemon/src/metro-user/move.ts +165 -0
  193. package/runtime/node_modules/@metro-labs/daemon/src/metro-user/privilege.ts +48 -0
  194. package/runtime/node_modules/@metro-labs/daemon/src/monitor/api.ts +132 -0
  195. package/runtime/node_modules/@metro-labs/daemon/src/net/tunnel.ts +316 -0
  196. package/runtime/node_modules/@metro-labs/daemon/src/policy/policy.ts +118 -0
  197. package/runtime/node_modules/@metro-labs/daemon/src/routes/bearer.ts +35 -0
  198. package/runtime/node_modules/@metro-labs/daemon/src/routes/body.ts +24 -0
  199. package/runtime/node_modules/@metro-labs/daemon/src/routes/http.ts +365 -0
  200. package/runtime/node_modules/@metro-labs/daemon/src/routes/local-mode.ts +208 -0
  201. package/runtime/node_modules/@metro-labs/daemon/src/routes/session-apis.ts +71 -0
  202. package/runtime/node_modules/@metro-labs/daemon/src/routes/session.ts +29 -0
  203. package/runtime/node_modules/@metro-labs/daemon/src/routes/threema-callback.ts +103 -0
  204. package/runtime/node_modules/@metro-labs/daemon/src/server/control.ts +39 -0
  205. package/runtime/node_modules/@metro-labs/daemon/src/server/machine.ts +58 -0
  206. package/runtime/node_modules/@metro-labs/daemon/src/server/owner.ts +26 -0
  207. package/runtime/node_modules/@metro-labs/daemon/src/server/update.ts +90 -0
  208. package/runtime/node_modules/@metro-labs/daemon/src/server.ts +2 -0
  209. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-driver.ts +42 -0
  210. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-inline.ts +128 -0
  211. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-interactive.ts +134 -0
  212. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-outlook.ts +63 -0
  213. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-resolve.ts +225 -0
  214. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-session.ts +288 -0
  215. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach-xmtp.ts +111 -0
  216. package/runtime/node_modules/@metro-labs/daemon/src/stations/attach.ts +248 -0
  217. package/runtime/node_modules/@metro-labs/daemon/src/stations/materialize.ts +265 -0
  218. package/runtime/node_modules/@metro-labs/daemon/src/stations/registry.ts +51 -0
  219. package/runtime/node_modules/@metro-labs/daemon/src/stations/runtime-deps.ts +82 -0
  220. package/runtime/node_modules/@metro-labs/daemon/src/stations/supervisor-io.ts +97 -0
  221. package/runtime/node_modules/@metro-labs/daemon/src/stations/supervisor.ts +320 -0
  222. package/runtime/node_modules/@metro-labs/daemon/src/stations/threema-callbacks.ts +32 -0
  223. package/runtime/node_modules/@metro-labs/daemon/src/stations/train-call.ts +22 -0
  224. package/runtime/node_modules/@metro-labs/daemon/src/stations/webhook-endpoints.ts +51 -0
  225. package/runtime/node_modules/@metro-labs/daemon/src/terminal/api.ts +84 -0
  226. package/runtime/node_modules/@metro-labs/daemon/src/terminal/socket.ts +124 -0
  227. package/runtime/node_modules/@metro-labs/daemon/src/terminal/tickets.ts +15 -0
  228. package/runtime/node_modules/@metro-labs/daemon/src/vault/api.ts +45 -0
  229. package/runtime/node_modules/@metro-labs/daemon/src/vault/config.ts +51 -0
  230. package/runtime/node_modules/@metro-labs/daemon/src/vault/firewall.ts +48 -0
  231. package/runtime/node_modules/@metro-labs/daemon/src/vault/index.ts +96 -0
  232. package/runtime/node_modules/@metro-labs/daemon/src/vault/install.ts +56 -0
  233. package/runtime/node_modules/@metro-labs/daemon/src/vault/paths.ts +26 -0
  234. package/runtime/node_modules/@metro-labs/daemon/src/vault/proxy.ts +148 -0
  235. package/runtime/node_modules/@metro-labs/daemon/src/vault/store.ts +130 -0
  236. package/runtime/node_modules/@metro-labs/daemon/src/vault/trust.ts +61 -0
  237. package/runtime/node_modules/@metro-labs/discord-bot/package.json +26 -0
  238. package/runtime/node_modules/@metro-labs/discord-bot/src/accounts.ts +117 -0
  239. package/runtime/node_modules/@metro-labs/discord-bot/src/actions.ts +240 -0
  240. package/runtime/node_modules/@metro-labs/discord-bot/src/api-base.ts +1 -0
  241. package/runtime/node_modules/@metro-labs/discord-bot/src/attachments.ts +29 -0
  242. package/runtime/node_modules/@metro-labs/discord-bot/src/format.ts +174 -0
  243. package/runtime/node_modules/@metro-labs/discord-bot/src/group-actions.ts +50 -0
  244. package/runtime/node_modules/@metro-labs/discord-bot/src/group.ts +115 -0
  245. package/runtime/node_modules/@metro-labs/discord-bot/src/index.ts +122 -0
  246. package/runtime/node_modules/@metro-labs/discord-bot/src/members.ts +215 -0
  247. package/runtime/node_modules/@metro-labs/discord-bot/src/profile.ts +68 -0
  248. package/runtime/node_modules/@metro-labs/discord-bot/src/send-files.ts +43 -0
  249. package/runtime/node_modules/@metro-labs/discord-bot/src/station.ts +22 -0
  250. package/runtime/node_modules/@metro-labs/discord-bot/src/verify.ts +82 -0
  251. package/runtime/node_modules/@metro-labs/discord-bot/src/wire.ts +1 -0
  252. package/runtime/node_modules/@metro-labs/http/package.json +29 -0
  253. package/runtime/node_modules/@metro-labs/http/src/api-error.ts +8 -0
  254. package/runtime/node_modules/@metro-labs/http/src/api-http.ts +138 -0
  255. package/runtime/node_modules/@metro-labs/http/src/cors.ts +29 -0
  256. package/runtime/node_modules/@metro-labs/http/src/mode-api.ts +32 -0
  257. package/runtime/node_modules/@metro-labs/http/src/return-to.ts +21 -0
  258. package/runtime/node_modules/@metro-labs/http/src/workos-token.ts +149 -0
  259. package/runtime/node_modules/@metro-labs/outlook/package.json +25 -0
  260. package/runtime/node_modules/@metro-labs/outlook/src/accounts.ts +107 -0
  261. package/runtime/node_modules/@metro-labs/outlook/src/actions.ts +20 -0
  262. package/runtime/node_modules/@metro-labs/outlook/src/attachments.ts +97 -0
  263. package/runtime/node_modules/@metro-labs/outlook/src/auth.ts +150 -0
  264. package/runtime/node_modules/@metro-labs/outlook/src/browser.ts +53 -0
  265. package/runtime/node_modules/@metro-labs/outlook/src/config.ts +36 -0
  266. package/runtime/node_modules/@metro-labs/outlook/src/format.ts +141 -0
  267. package/runtime/node_modules/@metro-labs/outlook/src/graph.ts +60 -0
  268. package/runtime/node_modules/@metro-labs/outlook/src/html.ts +72 -0
  269. package/runtime/node_modules/@metro-labs/outlook/src/inbound.ts +104 -0
  270. package/runtime/node_modules/@metro-labs/outlook/src/index.ts +12 -0
  271. package/runtime/node_modules/@metro-labs/outlook/src/login.ts +150 -0
  272. package/runtime/node_modules/@metro-labs/outlook/src/me.ts +41 -0
  273. package/runtime/node_modules/@metro-labs/outlook/src/outbound.ts +116 -0
  274. package/runtime/node_modules/@metro-labs/outlook/src/query.ts +119 -0
  275. package/runtime/node_modules/@metro-labs/outlook/src/state.ts +43 -0
  276. package/runtime/node_modules/@metro-labs/outlook/src/station.ts +15 -0
  277. package/runtime/node_modules/@metro-labs/outlook/src/trust.ts +70 -0
  278. package/runtime/node_modules/@metro-labs/telegram/package.json +26 -0
  279. package/runtime/node_modules/@metro-labs/telegram/src/accounts.ts +80 -0
  280. package/runtime/node_modules/@metro-labs/telegram/src/actions.ts +256 -0
  281. package/runtime/node_modules/@metro-labs/telegram/src/attachments.ts +87 -0
  282. package/runtime/node_modules/@metro-labs/telegram/src/client.ts +77 -0
  283. package/runtime/node_modules/@metro-labs/telegram/src/format.ts +128 -0
  284. package/runtime/node_modules/@metro-labs/telegram/src/group.ts +261 -0
  285. package/runtime/node_modules/@metro-labs/telegram/src/history.ts +52 -0
  286. package/runtime/node_modules/@metro-labs/telegram/src/inbound.ts +57 -0
  287. package/runtime/node_modules/@metro-labs/telegram/src/index.ts +7 -0
  288. package/runtime/node_modules/@metro-labs/telegram/src/login.ts +166 -0
  289. package/runtime/node_modules/@metro-labs/telegram/src/media-actions.ts +80 -0
  290. package/runtime/node_modules/@metro-labs/telegram/src/members.ts +75 -0
  291. package/runtime/node_modules/@metro-labs/telegram/src/normalize.ts +22 -0
  292. package/runtime/node_modules/@metro-labs/telegram/src/profile.ts +70 -0
  293. package/runtime/node_modules/@metro-labs/telegram/src/reactions.ts +167 -0
  294. package/runtime/node_modules/@metro-labs/telegram/src/station.ts +27 -0
  295. package/runtime/node_modules/@metro-labs/telegram/src/types.ts +6 -0
  296. package/runtime/node_modules/@metro-labs/telegram/src/wire.ts +1 -0
  297. package/runtime/node_modules/@metro-labs/telegram-bot/package.json +25 -0
  298. package/runtime/node_modules/@metro-labs/telegram-bot/src/accounts.ts +119 -0
  299. package/runtime/node_modules/@metro-labs/telegram-bot/src/actions.ts +246 -0
  300. package/runtime/node_modules/@metro-labs/telegram-bot/src/attachments.ts +128 -0
  301. package/runtime/node_modules/@metro-labs/telegram-bot/src/format.ts +173 -0
  302. package/runtime/node_modules/@metro-labs/telegram-bot/src/index.ts +103 -0
  303. package/runtime/node_modules/@metro-labs/telegram-bot/src/media-actions.ts +95 -0
  304. package/runtime/node_modules/@metro-labs/telegram-bot/src/members.ts +47 -0
  305. package/runtime/node_modules/@metro-labs/telegram-bot/src/profile.ts +65 -0
  306. package/runtime/node_modules/@metro-labs/telegram-bot/src/station.ts +20 -0
  307. package/runtime/node_modules/@metro-labs/telegram-bot/src/types.ts +56 -0
  308. package/runtime/node_modules/@metro-labs/telegram-bot/src/verify.ts +38 -0
  309. package/runtime/node_modules/@metro-labs/telegram-bot/src/wire.ts +1 -0
  310. package/runtime/node_modules/@metro-labs/threema/package.json +26 -0
  311. package/runtime/node_modules/@metro-labs/threema/src/accounts.ts +106 -0
  312. package/runtime/node_modules/@metro-labs/threema/src/actions.ts +134 -0
  313. package/runtime/node_modules/@metro-labs/threema/src/api.ts +152 -0
  314. package/runtime/node_modules/@metro-labs/threema/src/crypto.ts +100 -0
  315. package/runtime/node_modules/@metro-labs/threema/src/files.ts +58 -0
  316. package/runtime/node_modules/@metro-labs/threema/src/format.ts +169 -0
  317. package/runtime/node_modules/@metro-labs/threema/src/groups.ts +96 -0
  318. package/runtime/node_modules/@metro-labs/threema/src/ids.ts +21 -0
  319. package/runtime/node_modules/@metro-labs/threema/src/inbound.ts +89 -0
  320. package/runtime/node_modules/@metro-labs/threema/src/index.ts +24 -0
  321. package/runtime/node_modules/@metro-labs/threema/src/messages.ts +264 -0
  322. package/runtime/node_modules/@metro-labs/threema/src/outbound.ts +160 -0
  323. package/runtime/node_modules/@metro-labs/threema/src/station.ts +13 -0
  324. package/runtime/node_modules/@metro-labs/threema/src/verify.ts +117 -0
  325. package/runtime/node_modules/@metro-labs/webhook/package.json +23 -0
  326. package/runtime/node_modules/@metro-labs/webhook/src/station.ts +37 -0
  327. package/runtime/node_modules/@metro-labs/whatsapp/package.json +27 -0
  328. package/runtime/node_modules/@metro-labs/whatsapp/src/accounts.ts +66 -0
  329. package/runtime/node_modules/@metro-labs/whatsapp/src/ack.ts +101 -0
  330. package/runtime/node_modules/@metro-labs/whatsapp/src/actions.ts +213 -0
  331. package/runtime/node_modules/@metro-labs/whatsapp/src/attachments.ts +72 -0
  332. package/runtime/node_modules/@metro-labs/whatsapp/src/auth-state.ts +129 -0
  333. package/runtime/node_modules/@metro-labs/whatsapp/src/client.ts +388 -0
  334. package/runtime/node_modules/@metro-labs/whatsapp/src/delivery.ts +49 -0
  335. package/runtime/node_modules/@metro-labs/whatsapp/src/format.ts +83 -0
  336. package/runtime/node_modules/@metro-labs/whatsapp/src/inbound.ts +40 -0
  337. package/runtime/node_modules/@metro-labs/whatsapp/src/index.ts +7 -0
  338. package/runtime/node_modules/@metro-labs/whatsapp/src/keys.ts +59 -0
  339. package/runtime/node_modules/@metro-labs/whatsapp/src/logger.ts +60 -0
  340. package/runtime/node_modules/@metro-labs/whatsapp/src/login.ts +176 -0
  341. package/runtime/node_modules/@metro-labs/whatsapp/src/media.ts +84 -0
  342. package/runtime/node_modules/@metro-labs/whatsapp/src/names.ts +28 -0
  343. package/runtime/node_modules/@metro-labs/whatsapp/src/normalize.ts +22 -0
  344. package/runtime/node_modules/@metro-labs/whatsapp/src/outbox.ts +38 -0
  345. package/runtime/node_modules/@metro-labs/whatsapp/src/parse.ts +185 -0
  346. package/runtime/node_modules/@metro-labs/whatsapp/src/resolve.ts +52 -0
  347. package/runtime/node_modules/@metro-labs/whatsapp/src/station.ts +24 -0
  348. package/runtime/node_modules/@metro-labs/whatsapp/src/token-store.ts +94 -0
  349. package/runtime/node_modules/@metro-labs/whatsapp/src/types.ts +5 -0
  350. package/runtime/node_modules/@metro-labs/whatsapp/src/wire.ts +1 -0
  351. package/runtime/node_modules/@metro-labs/xmtp/package.json +34 -0
  352. package/runtime/node_modules/@metro-labs/xmtp/src/accounts.ts +114 -0
  353. package/runtime/node_modules/@metro-labs/xmtp/src/actions-close.ts +110 -0
  354. package/runtime/node_modules/@metro-labs/xmtp/src/actions-conv.ts +101 -0
  355. package/runtime/node_modules/@metro-labs/xmtp/src/actions-meta.ts +118 -0
  356. package/runtime/node_modules/@metro-labs/xmtp/src/actions.ts +244 -0
  357. package/runtime/node_modules/@metro-labs/xmtp/src/attachments.ts +107 -0
  358. package/runtime/node_modules/@metro-labs/xmtp/src/codecs.ts +171 -0
  359. package/runtime/node_modules/@metro-labs/xmtp/src/conv-helpers.ts +239 -0
  360. package/runtime/node_modules/@metro-labs/xmtp/src/emit-payloads.ts +316 -0
  361. package/runtime/node_modules/@metro-labs/xmtp/src/emit.ts +69 -0
  362. package/runtime/node_modules/@metro-labs/xmtp/src/group-members.ts +34 -0
  363. package/runtime/node_modules/@metro-labs/xmtp/src/group.ts +56 -0
  364. package/runtime/node_modules/@metro-labs/xmtp/src/identity.ts +47 -0
  365. package/runtime/node_modules/@metro-labs/xmtp/src/index.ts +122 -0
  366. package/runtime/node_modules/@metro-labs/xmtp/src/labels.ts +139 -0
  367. package/runtime/node_modules/@metro-labs/xmtp/src/member-args.ts +40 -0
  368. package/runtime/node_modules/@metro-labs/xmtp/src/names.ts +61 -0
  369. package/runtime/node_modules/@metro-labs/xmtp/src/profile.ts +153 -0
  370. package/runtime/node_modules/@metro-labs/xmtp/src/sender.ts +112 -0
  371. package/runtime/node_modules/@metro-labs/xmtp/src/smart.ts +72 -0
  372. package/runtime/node_modules/@metro-labs/xmtp/src/station.ts +17 -0
  373. package/runtime/node_modules/@metro-labs/xmtp/src/tools-handlers.ts +79 -0
  374. package/runtime/node_modules/@metro-labs/xmtp/src/tools.ts +198 -0
  375. package/runtime/node_modules/@metro-labs/xmtp/src/transcribe.ts +88 -0
  376. package/runtime/node_modules/@metro-labs/xmtp/src/verify.ts +98 -0
  377. package/runtime/node_modules/@metro-labs/xmtp/src/wire.ts +51 -0
  378. package/runtime/runtime.json +3 -0
  379. package/runtime/server.ts +1 -0
  380. package/runtime/stations.json +37 -0
  381. package/runtime/trains/.keep +0 -0
  382. package/LICENSE +0 -21
  383. package/README.md +0 -78
  384. package/dist/channels/discord.js +0 -148
  385. package/dist/channels/telegram.js +0 -137
  386. package/dist/lib/address.js +0 -21
  387. package/dist/lib/codex-rc.js +0 -274
  388. package/dist/lib/dotenv.js +0 -31
  389. package/dist/log.js +0 -12
  390. package/dist/paths.js +0 -45
  391. package/skills/metro/SKILL.md +0 -122
@@ -0,0 +1,152 @@
1
+ import { errMsg } from '@metro-labs/core/log';
2
+ import { TrainError } from '@metro-labs/core/train-error';
3
+ import { GATEWAY_API, MESSAGE_ID_RE } from './ids.js';
4
+
5
+ const TIMEOUT_MS = 15_000;
6
+ const PUBLIC_KEY_RE = /^[0-9a-f]{64}$/;
7
+
8
+ export interface GatewayCreds {
9
+ gatewayId: string;
10
+ secret: string;
11
+ }
12
+
13
+ async function call(
14
+ path: string,
15
+ init: RequestInit,
16
+ label: string,
17
+ ): Promise<Response> {
18
+ try {
19
+ return await fetch(`${GATEWAY_API}${path}`, {
20
+ signal: AbortSignal.timeout(TIMEOUT_MS),
21
+ ...init,
22
+ });
23
+ } catch (err) {
24
+ throw new TrainError(
25
+ 'threema_unreachable',
26
+ `${label}: could not reach the Threema Gateway (${errMsg(err)})`,
27
+ { retryable: true },
28
+ );
29
+ }
30
+ }
31
+
32
+ const authQuery = (c: GatewayCreds): string =>
33
+ new URLSearchParams({ from: c.gatewayId, secret: c.secret }).toString();
34
+
35
+ function refusal(status: number, what: string): TrainError {
36
+ if (status === 401)
37
+ return new TrainError(
38
+ 'threema_unauthorized',
39
+ 'the Threema Gateway rejected this account credentials; check the Gateway ID and API secret',
40
+ { retryable: false },
41
+ );
42
+ if (status === 402)
43
+ return new TrainError(
44
+ 'threema_no_credits',
45
+ 'this Threema Gateway ID has no credits left; top it up at gateway.threema.ch',
46
+ { retryable: false },
47
+ );
48
+ if (status === 404)
49
+ return new TrainError('threema_unknown_id', `Threema does not know the ID ${what}`, {
50
+ retryable: false,
51
+ });
52
+ if (status === 413)
53
+ return new TrainError(
54
+ 'threema_message_too_long',
55
+ 'Threema refused the message as too long',
56
+ { retryable: false },
57
+ );
58
+ if (status === 400)
59
+ return new TrainError('threema_bad_recipient', `Threema refused the recipient ${what}`, {
60
+ retryable: false,
61
+ });
62
+ return new TrainError(
63
+ 'threema_gateway_error',
64
+ `the Threema Gateway answered ${status}`,
65
+ { retryable: status >= 500 },
66
+ );
67
+ }
68
+
69
+ export async function fetchPublicKey(
70
+ c: GatewayCreds,
71
+ threemaId: string,
72
+ ): Promise<string> {
73
+ const res = await call(
74
+ `/pubkeys/${encodeURIComponent(threemaId)}?${authQuery(c)}`,
75
+ {},
76
+ 'pubkeys',
77
+ );
78
+ if (!res.ok) throw refusal(res.status, threemaId);
79
+ const hex = (await res.text()).trim().toLowerCase();
80
+ if (!PUBLIC_KEY_RE.test(hex))
81
+ throw new TrainError(
82
+ 'threema_gateway_error',
83
+ `pubkeys: the Threema Gateway gave an unexpected answer for ${threemaId}`,
84
+ );
85
+ return hex;
86
+ }
87
+
88
+ export async function fetchCredits(c: GatewayCreds): Promise<number> {
89
+ const res = await call(`/credits?${authQuery(c)}`, {}, 'credits');
90
+ if (!res.ok) throw refusal(res.status, c.gatewayId);
91
+ const credits = Number((await res.text()).trim());
92
+ if (!Number.isInteger(credits))
93
+ throw new TrainError(
94
+ 'threema_gateway_error',
95
+ 'credits: the Threema Gateway gave an unexpected answer',
96
+ );
97
+ return credits;
98
+ }
99
+
100
+ export async function sendE2E(
101
+ c: GatewayCreds,
102
+ to: string,
103
+ nonceHex: string,
104
+ boxHex: string,
105
+ group = false,
106
+ ): Promise<string> {
107
+ const body = new URLSearchParams({
108
+ from: c.gatewayId,
109
+ to,
110
+ nonce: nonceHex,
111
+ box: boxHex,
112
+ secret: c.secret,
113
+ ...(group ? { group: '1' } : {}),
114
+ });
115
+ const res = await call(
116
+ '/send_e2e',
117
+ {
118
+ method: 'POST',
119
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
120
+ body: body.toString(),
121
+ },
122
+ 'send_e2e',
123
+ );
124
+ if (!res.ok) throw refusal(res.status, to);
125
+ const messageId = (await res.text()).trim().toLowerCase();
126
+ if (!MESSAGE_ID_RE.test(messageId))
127
+ throw new TrainError(
128
+ 'threema_gateway_error',
129
+ 'send_e2e: the Threema Gateway answered without a message id',
130
+ );
131
+ return messageId;
132
+ }
133
+
134
+ const BLOB_ID_RE = /^[0-9a-f]{32}$/;
135
+ const BLOB_TIMEOUT_MS = 120_000;
136
+
137
+ export async function uploadBlob(c: GatewayCreds, data: Uint8Array): Promise<string> {
138
+ const form = new FormData();
139
+ form.append('blob', new Blob([Buffer.from(data)]), 'blob');
140
+ const res = await call(`/upload_blob?${authQuery(c)}`, { method: 'POST', body: form, signal: AbortSignal.timeout(BLOB_TIMEOUT_MS) }, 'upload_blob');
141
+ if (!res.ok) throw refusal(res.status, 'blob');
142
+ const blobId = (await res.text()).trim().toLowerCase();
143
+ if (!BLOB_ID_RE.test(blobId)) throw new TrainError('threema_gateway_error', 'upload_blob: the Threema Gateway answered without a blob id');
144
+ return blobId;
145
+ }
146
+
147
+ export async function downloadBlob(c: GatewayCreds, blobId: string): Promise<Uint8Array> {
148
+ if (!BLOB_ID_RE.test(blobId)) throw new TrainError('threema_bad_blob', `'${blobId}' is not a blob id`, { retryable: false });
149
+ const res = await call(`/blobs/${blobId}?${authQuery(c)}`, { signal: AbortSignal.timeout(BLOB_TIMEOUT_MS) }, 'blob download');
150
+ if (!res.ok) throw refusal(res.status, `blob ${blobId}`);
151
+ return new Uint8Array(await res.arrayBuffer());
152
+ }
@@ -0,0 +1,100 @@
1
+ import { createHmac, randomInt, timingSafeEqual } from 'node:crypto';
2
+ import nacl from 'tweetnacl';
3
+
4
+ const HEX_RE = /^(?:[0-9a-fA-F]{2})*$/;
5
+
6
+ export interface KeyPair {
7
+ publicKey: Uint8Array;
8
+ secretKey: Uint8Array;
9
+ }
10
+
11
+ export function hexToBytes(hex: string, label: string): Uint8Array {
12
+ if (!HEX_RE.test(hex)) throw new Error(`${label} is not hex`);
13
+ return new Uint8Array(Buffer.from(hex, 'hex'));
14
+ }
15
+
16
+ export const bytesToHex = (bytes: Uint8Array): string =>
17
+ Buffer.from(bytes).toString('hex');
18
+
19
+ export const keyPairFrom = (privateKeyHex: string): KeyPair =>
20
+ nacl.box.keyPair.fromSecretKey(hexToBytes(privateKeyHex, 'private key'));
21
+
22
+ function pad(plain: Uint8Array): Uint8Array {
23
+ const n = randomInt(1, 256);
24
+ const out = new Uint8Array(plain.length + n);
25
+ out.set(plain);
26
+ out.fill(n, plain.length);
27
+ return out;
28
+ }
29
+
30
+ function unpad(data: Uint8Array): Uint8Array | null {
31
+ const n = data[data.length - 1];
32
+ if (n === undefined || n < 1 || n > data.length) return null;
33
+ return data.subarray(0, data.length - n);
34
+ }
35
+
36
+ export function seal(
37
+ plain: Uint8Array,
38
+ theirPublicKey: Uint8Array,
39
+ mine: KeyPair,
40
+ ): { nonce: Uint8Array; box: Uint8Array } {
41
+ const nonce = nacl.randomBytes(nacl.box.nonceLength);
42
+ return {
43
+ nonce,
44
+ box: nacl.box(pad(plain), nonce, theirPublicKey, mine.secretKey),
45
+ };
46
+ }
47
+
48
+ export function open(
49
+ box: Uint8Array,
50
+ nonce: Uint8Array,
51
+ theirPublicKey: Uint8Array,
52
+ mine: KeyPair,
53
+ ): Uint8Array | null {
54
+ const padded = nacl.box.open(box, nonce, theirPublicKey, mine.secretKey);
55
+ return padded === null ? null : unpad(padded);
56
+ }
57
+
58
+ export interface CallbackFields {
59
+ from: string;
60
+ to: string;
61
+ messageId: string;
62
+ date: string;
63
+ nonce: string;
64
+ box: string;
65
+ }
66
+
67
+ export const callbackMac = (secret: string, f: CallbackFields): string =>
68
+ createHmac('sha256', secret)
69
+ .update(f.from + f.to + f.messageId + f.date + f.nonce + f.box)
70
+ .digest('hex');
71
+
72
+ export function macMatches(
73
+ secret: string,
74
+ fields: CallbackFields,
75
+ mac: string,
76
+ ): boolean {
77
+ const want = Buffer.from(callbackMac(secret, fields), 'hex');
78
+ const got = Buffer.from(mac.toLowerCase(), 'hex');
79
+ return want.length === got.length && timingSafeEqual(want, got);
80
+ }
81
+
82
+ const QUOTE_RE = /^> quote #([0-9a-f]{16})\n\n([\s\S]*)$/;
83
+
84
+ export const quoted = (replyTo: string, text: string): string =>
85
+ `> quote #${replyTo}\n\n${text}`;
86
+
87
+ export function unquote(text: string): { replyTo?: string; text: string } {
88
+ const m = QUOTE_RE.exec(text);
89
+ const replyTo = m?.[1];
90
+ const body = m?.[2];
91
+ return replyTo === undefined || body === undefined ? { text } : { replyTo, text: body };
92
+ }
93
+
94
+ const FILE_NONCE = new Uint8Array([...new Array<number>(23).fill(0), 1]);
95
+
96
+ export const newBlobKey = (): Uint8Array => nacl.randomBytes(nacl.secretbox.keyLength);
97
+
98
+ export const sealBlob = (data: Uint8Array, key: Uint8Array): Uint8Array => nacl.secretbox(data, FILE_NONCE, key);
99
+
100
+ export const openBlob = (data: Uint8Array, key: Uint8Array): Uint8Array | null => nacl.secretbox.open(data, FILE_NONCE, key);
@@ -0,0 +1,58 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { emit } from '@metro-labs/core/stations/station-runtime';
3
+ import { attachmentFailedEvent, attachmentSavedEvent, emitInbound } from '@metro-labs/core/stations/train-events';
4
+ import { assertAttachmentSize, isImageMime, kindOf, saveBufferToCache } from '@metro-labs/core/stations/attachments';
5
+ import { TrainError } from '@metro-labs/core/train-error';
6
+ import type { Account } from './accounts.js';
7
+ import { downloadBlob, uploadBlob } from './api.js';
8
+ import { bytesToHex, hexToBytes, newBlobKey, openBlob, sealBlob } from './crypto.js';
9
+ import { textEnvelope, type InboundMeta, type Room } from './format.js';
10
+ import { encodeFile, encodeGroupFile, type FileData, type GroupRef } from './messages.js';
11
+
12
+ export const MAX_BLOB_BYTES = 50 * 1024 * 1024;
13
+
14
+ export interface OutgoingFile {
15
+ path: string;
16
+ mime: string;
17
+ name: string;
18
+ }
19
+
20
+ export async function packFile(acct: Account, file: OutgoingFile, caption: string | null): Promise<FileData> {
21
+ const data = await readFile(file.path);
22
+ assertAttachmentSize(data.length);
23
+ if (data.length > MAX_BLOB_BYTES) throw new TrainError('threema_file_too_big', `Threema carries files up to 50 MB; ${file.name} is bigger`, { retryable: false });
24
+ const key = newBlobKey();
25
+ const blobId = await uploadBlob(acct.cfg, sealBlob(new Uint8Array(data), key));
26
+ return { blobId, key: bytesToHex(key), mime: file.mime, name: file.name, size: data.length, caption, media: isImageMime(file.mime) };
27
+ }
28
+
29
+ export const encodeFileFor = (group: GroupRef | null, file: FileData): Uint8Array => (group === null ? encodeFile(file) : encodeGroupFile(group, file));
30
+
31
+ export const fileLabel = (file: OutgoingFile): string => kindOf(file.mime, file.path);
32
+
33
+ async function fetchFile(acct: Account, m: InboundMeta, file: FileData): Promise<{ path: string; bytes: number }> {
34
+ const sealed = await downloadBlob(acct.cfg, file.blobId);
35
+ const plain = openBlob(sealed, hexToBytes(file.key, 'blob key'));
36
+ if (plain === null) throw new TrainError('threema_bad_blob', 'the file did not decrypt with the key in the message', { retryable: false });
37
+ const saved = await saveBufferToCache(plain, m.messageId, 0, { mime: file.mime, name: file.name });
38
+ return { path: saved.path, bytes: saved.bytes };
39
+ }
40
+
41
+ export function deliverFile(acct: Account, m: InboundMeta, file: FileData, room: Room, sentByUs: (id: string) => boolean): void {
42
+ const env = textEnvelope(acct.cfg.id, m, file.caption ?? '', sentByUs, room);
43
+ const line = String(env.line);
44
+ const forId = String(env.id);
45
+ const payload = { ...(env.payload as Record<string, unknown>), attachments: [{ kind: kindOf(file.mime, file.name), name: file.name, mime: file.mime, ...(file.size === null ? {} : { size: file.size }) }] };
46
+ emitInbound(acct.cfg.id, { ...env, payload });
47
+ const at = { station: 'threema', account: acct.cfg.id, line, forId, index: 0 };
48
+ const kind = kindOf(file.mime, file.name);
49
+ fetchFile(acct, m, file)
50
+ .then(({ path, bytes }) => {
51
+ emit(attachmentSavedEvent({ ...at, saved: { path, mime: file.mime, name: file.name }, extra: { kind, size: bytes } }));
52
+ })
53
+ .catch((err: unknown) => {
54
+ const reason = err instanceof Error ? err.message : String(err);
55
+ process.stderr.write(`threema[${acct.cfg.id}]: could not fetch ${file.name} from ${m.from}: ${reason}\n`);
56
+ emit(attachmentFailedEvent({ ...at, reason, extra: { kind } }));
57
+ });
58
+ }
@@ -0,0 +1,169 @@
1
+ import { emit, mintId } from '@metro-labs/core/stations/station-runtime';
2
+ import { selfUri } from '@metro-labs/core/stations/train-events';
3
+ import { unquote } from './crypto.js';
4
+ import { groupKey } from './groups.js';
5
+ import { RECEIPT_ACK, RECEIPT_DECLINE, type GroupRef } from './messages.js';
6
+
7
+ const REACTION_OF: Record<number, string> = {
8
+ [RECEIPT_ACK]: '👍',
9
+ [RECEIPT_DECLINE]: '👎',
10
+ };
11
+
12
+ export const lineOf = (accountId: string, threemaId: string): string =>
13
+ `metro://threema/${accountId}/${threemaId}`;
14
+
15
+ export const groupLineOf = (accountId: string, group: GroupRef): string =>
16
+ `metro://threema/${accountId}/${groupKey(group)}`;
17
+
18
+ const userOf = (accountId: string, threemaId: string): string =>
19
+ `metro://threema/${accountId}/user/${threemaId}`;
20
+
21
+ export interface InboundMeta {
22
+ from: string;
23
+ to: string;
24
+ messageId: string;
25
+ date: string;
26
+ nickname?: string;
27
+ }
28
+
29
+ export interface Room {
30
+ group: GroupRef | null;
31
+ name: string | null;
32
+ }
33
+
34
+ export const DIRECT: Room = { group: null, name: null };
35
+
36
+ const MENTION_ALL = '@@@@@@@@';
37
+
38
+ export const mentionsSelf = (text: string, self: string): boolean =>
39
+ text.includes(MENTION_ALL) || text.toUpperCase().includes(`@@${self.toUpperCase()}`);
40
+
41
+ function tsOf(date: string): string {
42
+ const seconds = Number(date);
43
+ return Number.isFinite(seconds) && seconds > 0
44
+ ? new Date(seconds * 1000).toISOString()
45
+ : new Date().toISOString();
46
+ }
47
+
48
+ function base(
49
+ accountId: string,
50
+ m: InboundMeta,
51
+ type: string,
52
+ room: Room,
53
+ ): Record<string, unknown> {
54
+ const group = room.group;
55
+ return {
56
+ kind: 'inbound',
57
+ id: mintId(),
58
+ ts: tsOf(m.date),
59
+ station: 'threema',
60
+ line: group === null ? lineOf(accountId, m.from) : groupLineOf(accountId, group),
61
+ line_name: group === null ? (m.nickname ?? m.from) : (room.name ?? groupKey(group)),
62
+ from: userOf(accountId, m.from),
63
+ from_name: m.nickname,
64
+ from_display_name: m.nickname,
65
+ is_private: group === null,
66
+ payload: { from: m.from, to: m.to, nickname: m.nickname ?? null, type, ...(group === null ? {} : { group: groupKey(group) }) },
67
+ };
68
+ }
69
+
70
+ export function textEnvelope(
71
+ accountId: string,
72
+ m: InboundMeta,
73
+ raw: string,
74
+ sentByUs: (messageId: string) => boolean,
75
+ room: Room = DIRECT,
76
+ ): Record<string, unknown> {
77
+ const { replyTo, text } = unquote(raw);
78
+ return {
79
+ ...base(accountId, m, 'text', room),
80
+ message_id: m.messageId,
81
+ text,
82
+ ...(room.group !== null && mentionsSelf(text, m.to) ? { mentions_self: true } : {}),
83
+ ...(replyTo === undefined
84
+ ? {}
85
+ : {
86
+ reply_to: replyTo,
87
+ event: { type: 'reply', replyTo },
88
+ reply_to_self: sentByUs(replyTo),
89
+ }),
90
+ };
91
+ }
92
+
93
+ export function reactionEnvelope(
94
+ accountId: string,
95
+ m: InboundMeta,
96
+ emoji: string,
97
+ targetId: string,
98
+ removed: boolean,
99
+ room: Room = DIRECT,
100
+ type = 'reaction',
101
+ ): Record<string, unknown> {
102
+ return {
103
+ ...base(accountId, m, type, room),
104
+ message_id: `${m.messageId}:${targetId}`,
105
+ text: `[react ${emoji}${removed ? ' (removed)' : ''}]`,
106
+ emoji,
107
+ event: { type: 'react', emoji, targetId, ...(removed ? { removed: true } : {}) },
108
+ };
109
+ }
110
+
111
+ export function receiptEnvelope(
112
+ accountId: string,
113
+ m: InboundMeta,
114
+ status: number,
115
+ targetId: string,
116
+ room: Room = DIRECT,
117
+ ): Record<string, unknown> | null {
118
+ const emoji = REACTION_OF[status];
119
+ return emoji === undefined ? null : reactionEnvelope(accountId, m, emoji, targetId, false, room, 'receipt');
120
+ }
121
+
122
+ export function emitOutbound(
123
+ accountId: string,
124
+ line: string,
125
+ messageId: string,
126
+ text: string,
127
+ replyTo?: string,
128
+ ): void {
129
+ emit({
130
+ kind: 'outbound',
131
+ id: mintId(),
132
+ ts: new Date().toISOString(),
133
+ station: 'threema',
134
+ line,
135
+ from: selfUri('threema', accountId),
136
+ to: line,
137
+ message_id: messageId,
138
+ text,
139
+ reply_to: replyTo,
140
+ ...(replyTo ? { event: { type: 'reply', replyTo } } : {}),
141
+ account: accountId,
142
+ payload: { account: accountId },
143
+ });
144
+ }
145
+
146
+ export function emitOutboundReaction(
147
+ accountId: string,
148
+ line: string,
149
+ messageId: string,
150
+ emoji: string,
151
+ targetId: string,
152
+ removed: boolean,
153
+ ): void {
154
+ emit({
155
+ kind: 'outbound',
156
+ id: mintId(),
157
+ ts: new Date().toISOString(),
158
+ station: 'threema',
159
+ line,
160
+ from: selfUri('threema', accountId),
161
+ to: line,
162
+ message_id: messageId,
163
+ text: `[react ${emoji}${removed ? ' (removed)' : ''}]`,
164
+ emoji,
165
+ event: { type: 'react', emoji, targetId, ...(removed ? { removed: true } : {}) },
166
+ account: accountId,
167
+ payload: { account: accountId },
168
+ });
169
+ }
@@ -0,0 +1,96 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { accountFiles } from '@metro-labs/core/stations/account-files';
4
+ import type { GroupRef } from './messages.js';
5
+
6
+ export const GROUP_RE = /^([A-Z0-9]{8}|\*[A-Z0-9]{7})-([0-9a-f]{16})$/i;
7
+
8
+ export interface GroupRoster {
9
+ creator: string;
10
+ groupId: string;
11
+ members: string[];
12
+ name: string | null;
13
+ }
14
+
15
+ export const groupKey = (group: GroupRef): string => `${group.creator.toUpperCase()}-${group.groupId.toLowerCase()}`;
16
+
17
+ export function parseGroupKey(resource: string): GroupRef | null {
18
+ const m = GROUP_RE.exec(resource);
19
+ return m === null ? null : { creator: (m[1] ?? '').toUpperCase(), groupId: (m[2] ?? '').toLowerCase() };
20
+ }
21
+
22
+ export const groupFiles = accountFiles('THREEMA_GROUPS_DIR', 'threema-groups-');
23
+
24
+ const groupsFile = (accountId: string): string => groupFiles.path(accountId);
25
+
26
+ function readRosters(accountId: string): Map<string, GroupRoster> {
27
+ try {
28
+ const raw: unknown = JSON.parse(readFileSync(groupsFile(accountId), 'utf8'));
29
+ const out = new Map<string, GroupRoster>();
30
+ if (Array.isArray(raw))
31
+ for (const entry of raw) {
32
+ const g = (entry ?? {}) as Partial<GroupRoster>;
33
+ if (typeof g.creator === 'string' && typeof g.groupId === 'string' && Array.isArray(g.members))
34
+ out.set(groupKey(g as GroupRef), { creator: g.creator, groupId: g.groupId, members: g.members.filter((m): m is string => typeof m === 'string'), name: typeof g.name === 'string' ? g.name : null });
35
+ }
36
+ return out;
37
+ } catch {
38
+ return new Map();
39
+ }
40
+ }
41
+
42
+ export class GroupStore {
43
+ private readonly rosters: Map<string, GroupRoster>;
44
+
45
+ constructor(
46
+ private readonly accountId: string,
47
+ private readonly self: string,
48
+ ) {
49
+ this.rosters = readRosters(accountId);
50
+ }
51
+
52
+ get(group: GroupRef): GroupRoster | undefined {
53
+ return this.rosters.get(groupKey(group));
54
+ }
55
+
56
+ list(): GroupRoster[] {
57
+ return [...this.rosters.values()];
58
+ }
59
+
60
+ setup(creator: string, groupId: string, members: string[]): GroupRoster {
61
+ const key = groupKey({ creator, groupId });
62
+ const held = this.rosters.get(key);
63
+ const roster: GroupRoster = { creator, groupId, members: [...new Set([creator, ...members])], name: held?.name ?? null };
64
+ this.rosters.set(key, roster);
65
+ this.save();
66
+ return roster;
67
+ }
68
+
69
+ rename(creator: string, groupId: string, name: string): void {
70
+ const held = this.rosters.get(groupKey({ creator, groupId }));
71
+ if (held === undefined) return;
72
+ held.name = name;
73
+ this.save();
74
+ }
75
+
76
+ leave(group: GroupRef, member: string): void {
77
+ const held = this.rosters.get(groupKey(group));
78
+ if (held === undefined) return;
79
+ if (member === this.self) this.rosters.delete(groupKey(group));
80
+ else held.members = held.members.filter((m) => m !== member);
81
+ this.save();
82
+ }
83
+
84
+ recipients(group: GroupRef): string[] | null {
85
+ const held = this.get(group);
86
+ return held === undefined ? null : held.members.filter((m) => m !== this.self);
87
+ }
88
+
89
+ private save(): void {
90
+ const path = groupsFile(this.accountId);
91
+ mkdirSync(dirname(path), { recursive: true });
92
+ const tmp = `${path}.${String(process.pid)}.tmp`;
93
+ writeFileSync(tmp, JSON.stringify(this.list()), { mode: 0o600 });
94
+ renameSync(tmp, path);
95
+ }
96
+ }
@@ -0,0 +1,21 @@
1
+ export const GATEWAY_API = (
2
+ process.env.THREEMA_GATEWAY_URL ?? 'https://msgapi.threema.ch'
3
+ ).replace(/\/+$/, '');
4
+
5
+ const THREEMA_ID_RE = /^(?:[A-Z0-9]{8}|\*[A-Z0-9]{7})$/;
6
+ const KEY_HEX_RE = /^[0-9a-f]{64}$/;
7
+
8
+ export const MESSAGE_ID_RE = /^[0-9a-f]{16}$/;
9
+
10
+ export const isThreemaId = (raw: string): boolean => THREEMA_ID_RE.test(raw);
11
+
12
+ export const isGatewayId = (raw: string): boolean =>
13
+ raw.startsWith('*') && isThreemaId(raw);
14
+
15
+ export const normalizeThreemaId = (raw: string): string =>
16
+ raw.trim().toUpperCase();
17
+
18
+ export function parsePrivateKey(raw: string): string | null {
19
+ const text = raw.trim().replace(/^private:/i, '').trim().toLowerCase();
20
+ return KEY_HEX_RE.test(text) ? text : null;
21
+ }
@@ -0,0 +1,89 @@
1
+ import type { Account } from './accounts.js';
2
+ import { emitInbound } from '@metro-labs/core/stations/train-events';
3
+ import {
4
+ DIRECT,
5
+ reactionEnvelope,
6
+ receiptEnvelope,
7
+ textEnvelope,
8
+ type InboundMeta,
9
+ type Room,
10
+ } from './format.js';
11
+ import { deliverFile } from './files.js';
12
+ import type { Decoded, GroupRef } from './messages.js';
13
+ import { requestSync, sentByUs } from './outbound.js';
14
+
15
+ const synced = new Set<string>();
16
+
17
+ function roomOf(acct: Account, group: GroupRef | null): Room {
18
+ if (group === null) return DIRECT;
19
+ return { group, name: acct.groups.get(group)?.name ?? null };
20
+ }
21
+
22
+ function askForRoster(acct: Account, group: GroupRef): void {
23
+ const key = `${acct.cfg.id}:${group.creator}-${group.groupId}`;
24
+ if (acct.groups.get(group) !== undefined || synced.has(key)) return;
25
+ synced.add(key);
26
+ requestSync(acct, group).catch((err: unknown) => {
27
+ process.stderr.write(`threema[${acct.cfg.id}]: could not ask ${group.creator} for the group roster: ${err instanceof Error ? err.message : String(err)}\n`);
28
+ });
29
+ }
30
+
31
+ function reactions(acct: Account, m: InboundMeta, d: Extract<Decoded, { kind: 'receipt' }>): string {
32
+ let count = 0;
33
+ for (const target of d.messageIds) {
34
+ const env = receiptEnvelope(acct.cfg.id, m, d.status, target, roomOf(acct, d.group));
35
+ if (env === null) continue;
36
+ emitInbound(acct.cfg.id, env);
37
+ count += 1;
38
+ }
39
+ return count > 0 ? 'reaction' : `receipt:${String(d.status)}`;
40
+ }
41
+
42
+ function control(acct: Account, m: InboundMeta, d: Decoded): string | null {
43
+ if (d.kind === 'group-setup') {
44
+ acct.groups.setup(m.from, d.groupId, d.members);
45
+ return 'group-setup';
46
+ }
47
+ if (d.kind === 'group-rename') {
48
+ acct.groups.rename(m.from, d.groupId, d.name);
49
+ return 'group-rename';
50
+ }
51
+ if (d.kind === 'group-leave') {
52
+ acct.groups.leave(d.group, m.from);
53
+ return 'group-leave';
54
+ }
55
+ return null;
56
+ }
57
+
58
+ function chat(acct: Account, m: InboundMeta, d: Decoded): string | null {
59
+ if (d.kind === 'text') {
60
+ emitInbound(acct.cfg.id, textEnvelope(acct.cfg.id, m, d.text, sentByUs));
61
+ return 'text';
62
+ }
63
+ if (d.kind === 'group-text') {
64
+ askForRoster(acct, d.group);
65
+ emitInbound(acct.cfg.id, textEnvelope(acct.cfg.id, m, d.text, sentByUs, roomOf(acct, d.group)));
66
+ return 'group-text';
67
+ }
68
+ if (d.kind === 'file') {
69
+ if (d.group !== null) askForRoster(acct, d.group);
70
+ deliverFile(acct, m, d.file, roomOf(acct, d.group), sentByUs);
71
+ return 'file';
72
+ }
73
+ if (d.kind === 'reaction') {
74
+ if (d.group !== null) askForRoster(acct, d.group);
75
+ emitInbound(acct.cfg.id, reactionEnvelope(acct.cfg.id, m, d.emoji, d.messageId, d.removed, roomOf(acct, d.group)));
76
+ return 'reaction';
77
+ }
78
+ return null;
79
+ }
80
+
81
+ export function deliver(acct: Account, m: InboundMeta, d: Decoded): string {
82
+ const handled = control(acct, m, d) ?? chat(acct, m, d);
83
+ if (handled !== null) return handled;
84
+ if (d.kind === 'receipt') return reactions(acct, m, d);
85
+ if (d.kind === 'typing') return 'typing';
86
+ const type = d.kind === 'other' ? `0x${d.type.toString(16)}` : d.kind;
87
+ process.stderr.write(`threema[${acct.cfg.id}]: ignored a message of type ${type} from ${m.from}\n`);
88
+ return `ignored:${type}`;
89
+ }