@aria-cli/tools 1.0.12 → 1.0.14

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 (233) hide show
  1. package/dist/index.js +378 -70
  2. package/dist/network-runtime/index.js +8 -12
  3. package/dist-cjs/index.js +400 -435
  4. package/dist-cjs/network-runtime/index.js +8 -172
  5. package/package.json +8 -6
  6. package/dist/.tsbuildinfo +0 -1
  7. package/dist/ask-user-interaction.js +0 -22
  8. package/dist/cache/web-cache.js +0 -66
  9. package/dist/definitions/arion.js +0 -104
  10. package/dist/definitions/browser/browser.js +0 -418
  11. package/dist/definitions/browser/index.js +0 -4
  12. package/dist/definitions/browser/pw-downloads.js +0 -114
  13. package/dist/definitions/browser/pw-interactions.js +0 -199
  14. package/dist/definitions/browser/pw-responses.js +0 -76
  15. package/dist/definitions/browser/pw-session.js +0 -310
  16. package/dist/definitions/browser/pw-shared.js +0 -66
  17. package/dist/definitions/browser/pw-snapshot.js +0 -301
  18. package/dist/definitions/browser/pw-state.js +0 -62
  19. package/dist/definitions/browser/types.js +0 -4
  20. package/dist/definitions/code-intelligence.js +0 -470
  21. package/dist/definitions/core.js +0 -109
  22. package/dist/definitions/delegation.js +0 -512
  23. package/dist/definitions/deploy.js +0 -65
  24. package/dist/definitions/filesystem.js +0 -196
  25. package/dist/definitions/frg.js +0 -63
  26. package/dist/definitions/index.js +0 -20
  27. package/dist/definitions/memory.js +0 -123
  28. package/dist/definitions/messaging.js +0 -625
  29. package/dist/definitions/meta.js +0 -349
  30. package/dist/definitions/network.js +0 -159
  31. package/dist/definitions/outlook.js +0 -277
  32. package/dist/definitions/patch/apply-patch.js +0 -184
  33. package/dist/definitions/patch/fuzzy-match.js +0 -166
  34. package/dist/definitions/patch/index.js +0 -1
  35. package/dist/definitions/patch/patch-parser.js +0 -207
  36. package/dist/definitions/patch/sandbox-paths.js +0 -105
  37. package/dist/definitions/process/index.js +0 -4
  38. package/dist/definitions/process/process-registry.js +0 -213
  39. package/dist/definitions/process/process.js +0 -386
  40. package/dist/definitions/process/pty-keys.js +0 -254
  41. package/dist/definitions/process/session-slug.js +0 -142
  42. package/dist/definitions/quip.js +0 -195
  43. package/dist/definitions/search.js +0 -60
  44. package/dist/definitions/session-history.js +0 -69
  45. package/dist/definitions/shell.js +0 -181
  46. package/dist/definitions/slack.js +0 -180
  47. package/dist/definitions/web.js +0 -109
  48. package/dist/executors/apply-patch.js +0 -901
  49. package/dist/executors/arion.js +0 -119
  50. package/dist/executors/code-intelligence.js +0 -882
  51. package/dist/executors/deploy.js +0 -848
  52. package/dist/executors/filesystem.js +0 -1122
  53. package/dist/executors/frg-freshness.js +0 -576
  54. package/dist/executors/frg.js +0 -298
  55. package/dist/executors/index.js +0 -46
  56. package/dist/executors/learning-meta.js +0 -1146
  57. package/dist/executors/lsp-client.js +0 -296
  58. package/dist/executors/memory.js +0 -750
  59. package/dist/executors/meta.js +0 -220
  60. package/dist/executors/process-registry.js +0 -465
  61. package/dist/executors/pty-session-store.js +0 -30
  62. package/dist/executors/pty.js +0 -271
  63. package/dist/executors/restart.js +0 -119
  64. package/dist/executors/search-freshness.js +0 -195
  65. package/dist/executors/search-types.js +0 -52
  66. package/dist/executors/search.js +0 -66
  67. package/dist/executors/self-diagnose.js +0 -398
  68. package/dist/executors/session-history.js +0 -283
  69. package/dist/executors/shell-safety.js +0 -473
  70. package/dist/executors/shell.js +0 -954
  71. package/dist/executors/utils.js +0 -33
  72. package/dist/executors/web.js +0 -542
  73. package/dist/extraction/content-extraction.js +0 -235
  74. package/dist/extraction/index.js +0 -4
  75. package/dist/headless-control-contract.js +0 -967
  76. package/dist/local-control-http-auth.js +0 -2
  77. package/dist/mcp/client.js +0 -181
  78. package/dist/mcp/connection.js +0 -480
  79. package/dist/mcp/index.js +0 -10
  80. package/dist/mcp/jsonrpc.js +0 -144
  81. package/dist/mcp/types.js +0 -7
  82. package/dist/network-control-adapter.js +0 -72
  83. package/dist/network-runtime/address-types.js +0 -165
  84. package/dist/network-runtime/db-owner-fencing.js +0 -69
  85. package/dist/network-runtime/delivery-receipts.js +0 -267
  86. package/dist/network-runtime/direct-endpoint-authority.js +0 -25
  87. package/dist/network-runtime/local-control-contract.js +0 -627
  88. package/dist/network-runtime/node-store-contract.js +0 -34
  89. package/dist/network-runtime/pair-route-contract.js +0 -77
  90. package/dist/network-runtime/peer-capabilities.js +0 -28
  91. package/dist/network-runtime/peer-principal-ref.js +0 -12
  92. package/dist/network-runtime/peer-state-machine.js +0 -121
  93. package/dist/network-runtime/protocol-schemas.js +0 -205
  94. package/dist/network-runtime/runtime-bootstrap-contract.js +0 -60
  95. package/dist/outlook/desktop-session.js +0 -279
  96. package/dist/policy.js +0 -149
  97. package/dist/providers/brave.js +0 -62
  98. package/dist/providers/duckduckgo.js +0 -176
  99. package/dist/providers/exa.js +0 -63
  100. package/dist/providers/firecrawl.js +0 -55
  101. package/dist/providers/index.js +0 -7
  102. package/dist/providers/jina.js +0 -49
  103. package/dist/providers/router.js +0 -96
  104. package/dist/providers/search-provider.js +0 -32
  105. package/dist/providers/tavily.js +0 -54
  106. package/dist/quip/desktop-session.js +0 -317
  107. package/dist/registry/index.js +0 -1
  108. package/dist/registry/registry.js +0 -756
  109. package/dist/runtime-socket-local-control-client.js +0 -330
  110. package/dist/security/dns-normalization.js +0 -19
  111. package/dist/security/dns-pinning.js +0 -123
  112. package/dist/security/external-content.js +0 -91
  113. package/dist/security/ssrf.js +0 -181
  114. package/dist/slack/desktop-session.js +0 -324
  115. package/dist/tool-factory.js +0 -47
  116. package/dist/types.js +0 -7
  117. package/dist/utils/retry.js +0 -132
  118. package/dist/utils/safe-parse-json.js +0 -160
  119. package/dist/utils/url.js +0 -19
  120. package/dist-cjs/.tsbuildinfo +0 -1
  121. package/dist-cjs/ask-user-interaction.js +0 -27
  122. package/dist-cjs/cache/web-cache.js +0 -70
  123. package/dist-cjs/definitions/arion.js +0 -107
  124. package/dist-cjs/definitions/browser/browser.js +0 -421
  125. package/dist-cjs/definitions/browser/index.js +0 -8
  126. package/dist-cjs/definitions/browser/pw-downloads.js +0 -117
  127. package/dist-cjs/definitions/browser/pw-interactions.js +0 -213
  128. package/dist-cjs/definitions/browser/pw-responses.js +0 -84
  129. package/dist-cjs/definitions/browser/pw-session.js +0 -326
  130. package/dist-cjs/definitions/browser/pw-shared.js +0 -72
  131. package/dist-cjs/definitions/browser/pw-snapshot.js +0 -307
  132. package/dist-cjs/definitions/browser/pw-state.js +0 -70
  133. package/dist-cjs/definitions/browser/types.js +0 -5
  134. package/dist-cjs/definitions/code-intelligence.js +0 -473
  135. package/dist-cjs/definitions/core.js +0 -133
  136. package/dist-cjs/definitions/delegation.js +0 -515
  137. package/dist-cjs/definitions/deploy.js +0 -68
  138. package/dist-cjs/definitions/filesystem.js +0 -199
  139. package/dist-cjs/definitions/frg.js +0 -66
  140. package/dist-cjs/definitions/index.js +0 -43
  141. package/dist-cjs/definitions/memory.js +0 -126
  142. package/dist-cjs/definitions/messaging.js +0 -631
  143. package/dist-cjs/definitions/meta.js +0 -352
  144. package/dist-cjs/definitions/network.js +0 -162
  145. package/dist-cjs/definitions/outlook.js +0 -280
  146. package/dist-cjs/definitions/patch/apply-patch.js +0 -191
  147. package/dist-cjs/definitions/patch/fuzzy-match.js +0 -172
  148. package/dist-cjs/definitions/patch/index.js +0 -5
  149. package/dist-cjs/definitions/patch/patch-parser.js +0 -215
  150. package/dist-cjs/definitions/patch/sandbox-paths.js +0 -113
  151. package/dist-cjs/definitions/process/index.js +0 -8
  152. package/dist-cjs/definitions/process/process-registry.js +0 -231
  153. package/dist-cjs/definitions/process/process.js +0 -389
  154. package/dist-cjs/definitions/process/pty-keys.js +0 -259
  155. package/dist-cjs/definitions/process/session-slug.js +0 -145
  156. package/dist-cjs/definitions/quip.js +0 -198
  157. package/dist-cjs/definitions/search.js +0 -63
  158. package/dist-cjs/definitions/session-history.js +0 -72
  159. package/dist-cjs/definitions/shell.js +0 -184
  160. package/dist-cjs/definitions/slack.js +0 -183
  161. package/dist-cjs/definitions/web.js +0 -112
  162. package/dist-cjs/executors/apply-patch.js +0 -938
  163. package/dist-cjs/executors/arion.js +0 -125
  164. package/dist-cjs/executors/code-intelligence.js +0 -925
  165. package/dist-cjs/executors/deploy.js +0 -869
  166. package/dist-cjs/executors/filesystem.js +0 -1167
  167. package/dist-cjs/executors/frg-freshness.js +0 -627
  168. package/dist-cjs/executors/frg.js +0 -334
  169. package/dist-cjs/executors/index.js +0 -143
  170. package/dist-cjs/executors/learning-meta.js +0 -1165
  171. package/dist-cjs/executors/lsp-client.js +0 -310
  172. package/dist-cjs/executors/memory.js +0 -796
  173. package/dist-cjs/executors/meta.js +0 -226
  174. package/dist-cjs/executors/process-registry.js +0 -469
  175. package/dist-cjs/executors/pty-session-store.js +0 -34
  176. package/dist-cjs/executors/pty.js +0 -312
  177. package/dist-cjs/executors/restart.js +0 -155
  178. package/dist-cjs/executors/search-freshness.js +0 -234
  179. package/dist-cjs/executors/search-types.js +0 -56
  180. package/dist-cjs/executors/search.js +0 -102
  181. package/dist-cjs/executors/self-diagnose.js +0 -434
  182. package/dist-cjs/executors/session-history.js +0 -320
  183. package/dist-cjs/executors/shell-safety.js +0 -478
  184. package/dist-cjs/executors/shell.js +0 -1001
  185. package/dist-cjs/executors/utils.js +0 -73
  186. package/dist-cjs/executors/web.js +0 -547
  187. package/dist-cjs/extraction/content-extraction.js +0 -243
  188. package/dist-cjs/extraction/index.js +0 -8
  189. package/dist-cjs/headless-control-contract.js +0 -972
  190. package/dist-cjs/local-control-http-auth.js +0 -5
  191. package/dist-cjs/mcp/client.js +0 -185
  192. package/dist-cjs/mcp/connection.js +0 -484
  193. package/dist-cjs/mcp/index.js +0 -30
  194. package/dist-cjs/mcp/jsonrpc.js +0 -148
  195. package/dist-cjs/mcp/types.js +0 -8
  196. package/dist-cjs/network-control-adapter.js +0 -77
  197. package/dist-cjs/network-runtime/address-types.js +0 -168
  198. package/dist-cjs/network-runtime/db-owner-fencing.js +0 -76
  199. package/dist-cjs/network-runtime/delivery-receipts.js +0 -276
  200. package/dist-cjs/network-runtime/direct-endpoint-authority.js +0 -29
  201. package/dist-cjs/network-runtime/local-control-contract.js +0 -633
  202. package/dist-cjs/network-runtime/node-store-contract.js +0 -38
  203. package/dist-cjs/network-runtime/pair-route-contract.js +0 -80
  204. package/dist-cjs/network-runtime/peer-capabilities.js +0 -37
  205. package/dist-cjs/network-runtime/peer-principal-ref.js +0 -15
  206. package/dist-cjs/network-runtime/peer-state-machine.js +0 -129
  207. package/dist-cjs/network-runtime/protocol-schemas.js +0 -212
  208. package/dist-cjs/network-runtime/runtime-bootstrap-contract.js +0 -63
  209. package/dist-cjs/outlook/desktop-session.js +0 -318
  210. package/dist-cjs/policy.js +0 -155
  211. package/dist-cjs/providers/brave.js +0 -66
  212. package/dist-cjs/providers/duckduckgo.js +0 -180
  213. package/dist-cjs/providers/exa.js +0 -67
  214. package/dist-cjs/providers/firecrawl.js +0 -59
  215. package/dist-cjs/providers/index.js +0 -17
  216. package/dist-cjs/providers/jina.js +0 -53
  217. package/dist-cjs/providers/router.js +0 -100
  218. package/dist-cjs/providers/search-provider.js +0 -36
  219. package/dist-cjs/providers/tavily.js +0 -58
  220. package/dist-cjs/quip/desktop-session.js +0 -353
  221. package/dist-cjs/registry/index.js +0 -6
  222. package/dist-cjs/registry/registry.js +0 -761
  223. package/dist-cjs/runtime-socket-local-control-client.js +0 -367
  224. package/dist-cjs/security/dns-normalization.js +0 -22
  225. package/dist-cjs/security/dns-pinning.js +0 -160
  226. package/dist-cjs/security/external-content.js +0 -95
  227. package/dist-cjs/security/ssrf.js +0 -221
  228. package/dist-cjs/slack/desktop-session.js +0 -366
  229. package/dist-cjs/tool-factory.js +0 -50
  230. package/dist-cjs/types.js +0 -8
  231. package/dist-cjs/utils/retry.js +0 -169
  232. package/dist-cjs/utils/safe-parse-json.js +0 -164
  233. package/dist-cjs/utils/url.js +0 -23
@@ -1,848 +0,0 @@
1
- /**
2
- * @aria/tools - Deploy tool executor
3
- *
4
- * Deploys ARIA to a remote machine via SSH. Handles OS detection,
5
- * Node.js installation, repo setup, keypair generation, TLS cert
6
- * discovery/provisioning, firewall configuration, config writing,
7
- * daemon startup, and health check.
8
- */
9
- import { spawn } from "node:child_process";
10
- import { success, fail } from "./utils.js";
11
- // ============================================================================
12
- // Pure Helper Functions (exported for testing)
13
- // ============================================================================
14
- /**
15
- * Detect OS type from `uname -s` output.
16
- */
17
- export function detectOS(unameOutput) {
18
- const trimmed = unameOutput.trim();
19
- if (!trimmed || trimmed === "UNKNOWN") {
20
- return { os: "unknown" };
21
- }
22
- if (trimmed === "Linux") {
23
- return { os: "linux" };
24
- }
25
- if (trimmed === "Darwin") {
26
- return { os: "darwin" };
27
- }
28
- // MINGW, MSYS, CYGWIN, or Windows-style output
29
- if (/^(MINGW|MSYS|CYGWIN)/i.test(trimmed) || /windows/i.test(trimmed)) {
30
- return { os: "windows" };
31
- }
32
- return { os: "unknown" };
33
- }
34
- /**
35
- * Detect Linux distribution from /etc/os-release content.
36
- * Returns the package manager type to use.
37
- */
38
- export function detectLinuxDistro(osReleaseContent) {
39
- const lower = osReleaseContent.toLowerCase();
40
- // Extract ID and ID_LIKE fields
41
- const idMatch = lower.match(/^id=(.+)$/m);
42
- const idLikeMatch = lower.match(/^id_like=(.+)$/m);
43
- const id = idMatch?.[1]?.replace(/"/g, "").trim() ?? "";
44
- const idLike = idLikeMatch?.[1]?.replace(/"/g, "").trim() ?? "";
45
- // Alpine
46
- if (id === "alpine") {
47
- return "apk";
48
- }
49
- // Debian/Ubuntu family
50
- if (id === "debian" ||
51
- id === "ubuntu" ||
52
- idLike.includes("debian") ||
53
- idLike.includes("ubuntu")) {
54
- return "apt";
55
- }
56
- // RHEL/Fedora/CentOS/Amazon Linux family
57
- if (id === "fedora" ||
58
- id === "rhel" ||
59
- id === "centos" ||
60
- id === "amzn" ||
61
- id === "rocky" ||
62
- id === "almalinux" ||
63
- idLike.includes("fedora") ||
64
- idLike.includes("rhel") ||
65
- idLike.includes("centos") ||
66
- idLike.includes("suse")) {
67
- return "dnf";
68
- }
69
- // Default to apt (nvm-based install works universally)
70
- return "apt";
71
- }
72
- /**
73
- * Get the shell command to install Node.js for a given OS and distro.
74
- */
75
- export function getNodeInstallCommand(osInfo, distro) {
76
- switch (osInfo.os) {
77
- case "linux":
78
- switch (distro) {
79
- case "apk":
80
- return "apk add --no-cache nodejs npm";
81
- case "dnf":
82
- return "dnf module install -y nodejs:22 || dnf install -y nodejs";
83
- case "apt":
84
- default:
85
- return ("curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash && " +
86
- 'export NVM_DIR="$HOME/.nvm" && . "$NVM_DIR/nvm.sh" && nvm install 22');
87
- }
88
- case "darwin":
89
- return ("command -v brew >/dev/null && brew install node@22 || " +
90
- "{ curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash && " +
91
- 'export NVM_DIR="$HOME/.nvm" && . "$NVM_DIR/nvm.sh" && nvm install 22; }');
92
- case "windows":
93
- return "winget install --id OpenJS.NodeJS.LTS --accept-source-agreements --accept-package-agreements";
94
- default:
95
- throw new Error(`Unsupported OS: ${osInfo.os}. Deploy supports Linux, macOS, and Windows.`);
96
- }
97
- }
98
- /**
99
- * Generate firewall commands to open ARIA ports (443/tcp + 51820/udp).
100
- */
101
- export function getFirewallCommands(firewallType) {
102
- switch (firewallType) {
103
- case "ufw":
104
- return "ufw allow 443/tcp && ufw allow 51820/udp";
105
- case "iptables":
106
- return ("iptables -A INPUT -p tcp --dport 443 -j ACCEPT && " +
107
- "iptables -A INPUT -p udp --dport 51820 -j ACCEPT");
108
- case "firewalld":
109
- return ("firewall-cmd --permanent --add-port=443/tcp && " +
110
- "firewall-cmd --permanent --add-port=51820/udp && " +
111
- "firewall-cmd --reload");
112
- case "windows":
113
- return ('netsh advfirewall firewall add rule name="ARIA HTTPS" dir=in action=allow protocol=tcp localport=443 && ' +
114
- 'netsh advfirewall firewall add rule name="ARIA WireGuard" dir=in action=allow protocol=udp localport=51820');
115
- case "none":
116
- return "";
117
- }
118
- }
119
- /**
120
- * Parse TLS cert discovery output from the remote host.
121
- * The discovery script outputs JSON: { found, type?, cert?, key? }
122
- */
123
- export function discoverTlsCerts(sshOutput) {
124
- if (!sshOutput || !sshOutput.trim()) {
125
- return { found: false };
126
- }
127
- try {
128
- const data = JSON.parse(sshOutput.trim());
129
- if (data.found === true && data.cert && data.key) {
130
- return {
131
- found: true,
132
- type: data.type,
133
- cert: data.cert,
134
- key: data.key,
135
- };
136
- }
137
- return { found: false };
138
- }
139
- catch {
140
- return { found: false };
141
- }
142
- }
143
- /**
144
- * Build the config JSON object for ~/.aria/config.json.
145
- */
146
- export function buildConfigJson(params) {
147
- const config = {
148
- arion_name: params.arionName,
149
- };
150
- if (params.coordinationUrl) {
151
- config.coordination_url = params.coordinationUrl;
152
- }
153
- if (params.tlsCert && params.tlsKey) {
154
- config.tls = {
155
- cert: params.tlsCert,
156
- key: params.tlsKey,
157
- };
158
- }
159
- return config;
160
- }
161
- /**
162
- * Construct the health check URL for the deployed daemon.
163
- */
164
- export function buildHealthCheckUrl(host, port) {
165
- const p = port ?? 443;
166
- return `https://${host}:${p}/api/v1/network/peers`;
167
- }
168
- function buildRemoteRuntimePidLookupCommand(repoDir) {
169
- return `
170
- export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
171
- cd ${repoDir} && node --input-type=module <<'NODE'
172
- import { resolveOrCreateNode, resolveRuntimeRootDirectory, readRuntimeOwnerRecord } from "./packages/server/dist/index.js";
173
- const ariaHome = process.env.ARIA_HOME || (process.env.HOME + "/.aria");
174
- const resolved = await resolveOrCreateNode({ ariaHome });
175
- const record = readRuntimeOwnerRecord(resolveRuntimeRootDirectory(), resolved.nodeId);
176
- if (record?.runtimePid) {
177
- console.log(String(record.runtimePid));
178
- }
179
- NODE
180
- `;
181
- }
182
- function buildRemoteRuntimeStatusLookupCommand(repoDir) {
183
- return `
184
- export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
185
- cd ${repoDir} && node --input-type=module <<'NODE'
186
- import { createRuntimeSocketLocalControlClient } from "./packages/tools/dist/index.js";
187
- import { resolveOrCreateNode, resolveRuntimeRootDirectory, readRuntimeOwnerRecord } from "./packages/server/dist/index.js";
188
- const ariaHome = process.env.ARIA_HOME || (process.env.HOME + "/.aria");
189
- const resolved = await resolveOrCreateNode({ ariaHome });
190
- const record = readRuntimeOwnerRecord(resolveRuntimeRootDirectory(), resolved.nodeId);
191
- if (!record?.runtimeSocket) {
192
- process.exit(1);
193
- }
194
- const client = createRuntimeSocketLocalControlClient({ runtimeSocket: record.runtimeSocket });
195
- const status = await client.getRuntimeStatus();
196
- console.log(JSON.stringify(status));
197
- NODE
198
- `;
199
- }
200
- // ============================================================================
201
- // Input Validators (A1 — prevent shell injection)
202
- // ============================================================================
203
- /**
204
- * Validate git repo URL — must be HTTPS with no shell metacharacters.
205
- */
206
- export function validateRepoUrl(url) {
207
- if (!url)
208
- return null;
209
- if (!/^https?:\/\/[a-zA-Z0-9.-]+\/[a-zA-Z0-9_.\/-]+(?:\.git)?$/.test(url)) {
210
- return "Invalid repo URL format. Use 'https://host/org/repo.git'.";
211
- }
212
- return null;
213
- }
214
- /**
215
- * Validate branch name — alphanumeric, dots, slashes, hyphens, underscores.
216
- * Rejects shell metacharacters and path traversal.
217
- */
218
- export function validateBranch(branch) {
219
- if (!branch)
220
- return null;
221
- if (!/^[a-zA-Z0-9_.\/-]+$/.test(branch) || branch.includes("..")) {
222
- return "Invalid branch name. Alphanumeric, dots, slashes, hyphens only.";
223
- }
224
- return null;
225
- }
226
- /**
227
- * Validate arion name — alphanumeric, underscores, hyphens only.
228
- */
229
- export function validateArionName(name) {
230
- if (!name)
231
- return null;
232
- if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
233
- return "Invalid arion name. Alphanumeric, underscores, hyphens only.";
234
- }
235
- return null;
236
- }
237
- /**
238
- * Validate SSH key path — reject traversal and shell metacharacters.
239
- */
240
- export function validateSshKeyPath(keyPath) {
241
- if (!keyPath)
242
- return null;
243
- if (keyPath.includes("..") || /[;|&`$(){}!<>]/.test(keyPath)) {
244
- return "Invalid SSH key path. No traversal or shell metacharacters.";
245
- }
246
- return null;
247
- }
248
- /**
249
- * Validate git commit hash — must be 7-64 lowercase hex characters.
250
- * Rejects non-hex, too-short, and shell injection attempts.
251
- */
252
- export function validateCommitHash(hash) {
253
- if (!hash)
254
- return null;
255
- if (!/^[a-f0-9]{7,64}$/.test(hash)) {
256
- return "Invalid commit hash. Must be 7-64 lowercase hex characters.";
257
- }
258
- return null;
259
- }
260
- /**
261
- * Pinned pnpm version — matches packageManager field in root package.json.
262
- * Prevents unpinned `pnpm@latest` from pulling a compromised version.
263
- */
264
- export const PINNED_PNPM_VERSION = "10.28.2";
265
- /**
266
- * Get firewall undo commands to reverse port-opening rules.
267
- */
268
- export function getFirewallUndoCommands(firewallType) {
269
- switch (firewallType) {
270
- case "ufw":
271
- return "ufw delete allow 443/tcp && ufw delete allow 51820/udp";
272
- case "iptables":
273
- return ("iptables -D INPUT -p tcp --dport 443 -j ACCEPT && " +
274
- "iptables -D INPUT -p udp --dport 51820 -j ACCEPT");
275
- case "firewalld":
276
- return ("firewall-cmd --permanent --remove-port=443/tcp && " +
277
- "firewall-cmd --permanent --remove-port=51820/udp && " +
278
- "firewall-cmd --reload");
279
- case "windows":
280
- return ('netsh advfirewall firewall delete rule name="ARIA HTTPS" && ' +
281
- 'netsh advfirewall firewall delete rule name="ARIA WireGuard"');
282
- case "none":
283
- return "";
284
- }
285
- }
286
- /**
287
- * Build rollback commands from recorded deploy steps.
288
- * Returns commands in reverse order (last step undone first).
289
- * Skips steps with empty undoCmd.
290
- */
291
- export function buildRollbackCommands(steps) {
292
- return steps
293
- .filter((s) => s.undoCmd.length > 0)
294
- .reverse()
295
- .map((s) => s.undoCmd);
296
- }
297
- // ============================================================================
298
- // Idempotency — Deep Merge Config (A3)
299
- // ============================================================================
300
- /**
301
- * Deep-merge two config objects. Preserves nested objects from existing config
302
- * while applying updates. Does not mutate inputs.
303
- */
304
- export function deepMergeConfig(existing, update) {
305
- const result = {};
306
- // Copy all existing keys
307
- for (const key of Object.keys(existing)) {
308
- const val = existing[key];
309
- if (val !== null && typeof val === "object" && !Array.isArray(val)) {
310
- result[key] = { ...val };
311
- }
312
- else {
313
- result[key] = val;
314
- }
315
- }
316
- // Apply updates
317
- for (const key of Object.keys(update)) {
318
- const updateVal = update[key];
319
- const existingVal = result[key];
320
- if (updateVal !== null &&
321
- typeof updateVal === "object" &&
322
- !Array.isArray(updateVal) &&
323
- existingVal !== null &&
324
- typeof existingVal === "object" &&
325
- !Array.isArray(existingVal)) {
326
- // Recursive merge for nested objects
327
- result[key] = deepMergeConfig(existingVal, updateVal);
328
- }
329
- else {
330
- result[key] = updateVal;
331
- }
332
- }
333
- return result;
334
- }
335
- // ============================================================================
336
- // Key Permissions (A3)
337
- // ============================================================================
338
- /**
339
- * Get chmod commands to restrict key and config file permissions to owner-only.
340
- */
341
- export function getKeyPermissionCommands() {
342
- return "chmod 600 ~/.aria/signing-key.json && chmod 600 ~/.aria/config.json";
343
- }
344
- // ============================================================================
345
- // SSH Helper
346
- // ============================================================================
347
- /**
348
- * Validate SSH target format — prevent command injection.
349
- */
350
- function validateTarget(target) {
351
- if (!target) {
352
- return "target is required (e.g. 'user@host')";
353
- }
354
- // Block shell metacharacters that could enable injection
355
- if (/[;|&`$(){}!<>\s]/.test(target)) {
356
- return "Invalid target format. Use 'user@host' or 'hostname'.";
357
- }
358
- return null;
359
- }
360
- /**
361
- * Execute a command on the remote host via SSH.
362
- * Returns { stdout, stderr, exitCode }.
363
- */
364
- export function sshExec(target, command, options) {
365
- return new Promise((resolve, reject) => {
366
- const args = [
367
- "-o",
368
- "StrictHostKeyChecking=accept-new",
369
- "-o",
370
- "ConnectTimeout=10",
371
- "-o",
372
- "BatchMode=yes",
373
- ];
374
- if (options?.sshKeyPath) {
375
- args.push("-i", options.sshKeyPath);
376
- }
377
- args.push(target, command);
378
- const child = spawn("ssh", args, {
379
- stdio: ["ignore", "pipe", "pipe"],
380
- });
381
- let stdout = "";
382
- let stderr = "";
383
- child.stdout.on("data", (data) => {
384
- stdout += data.toString();
385
- });
386
- child.stderr.on("data", (data) => {
387
- stderr += data.toString();
388
- });
389
- const timeoutMs = options?.timeoutMs ?? 120_000;
390
- const timer = setTimeout(() => {
391
- child.kill("SIGTERM");
392
- reject(new Error(`SSH command timed out after ${timeoutMs}ms: ${command}`));
393
- }, timeoutMs);
394
- if (options?.abortSignal) {
395
- options.abortSignal.addEventListener("abort", () => {
396
- child.kill("SIGTERM");
397
- clearTimeout(timer);
398
- reject(new Error("SSH command aborted"));
399
- }, { once: true });
400
- }
401
- child.on("close", (code) => {
402
- clearTimeout(timer);
403
- resolve({ stdout: stdout.trim(), stderr: stderr.trim(), exitCode: code ?? 1 });
404
- });
405
- child.on("error", (err) => {
406
- clearTimeout(timer);
407
- reject(err);
408
- });
409
- });
410
- }
411
- // ============================================================================
412
- // TLS Discovery Script (run on remote host)
413
- // ============================================================================
414
- const TLS_DISCOVERY_SCRIPT = `
415
- node -e "
416
- const fs = require('fs');
417
- const path = require('path');
418
-
419
- // Check Let's Encrypt first
420
- const leDirs = ['/etc/letsencrypt/live'];
421
- for (const dir of leDirs) {
422
- try {
423
- const domains = fs.readdirSync(dir).filter(d => !d.startsWith('.'));
424
- for (const domain of domains) {
425
- const cert = path.join(dir, domain, 'fullchain.pem');
426
- const key = path.join(dir, domain, 'privkey.pem');
427
- if (fs.existsSync(cert) && fs.existsSync(key)) {
428
- console.log(JSON.stringify({ found: true, type: 'letsencrypt', cert, key }));
429
- process.exit(0);
430
- }
431
- }
432
- } catch {}
433
- }
434
-
435
- // Check standard SSL locations
436
- const sslPairs = [
437
- ['/etc/ssl/certs/server.crt', '/etc/ssl/private/server.key'],
438
- ['/etc/ssl/certs/aria.crt', '/etc/ssl/private/aria.key'],
439
- ];
440
- for (const [cert, key] of sslPairs) {
441
- if (fs.existsSync(cert) && fs.existsSync(key)) {
442
- console.log(JSON.stringify({ found: true, type: 'real-ca', cert, key }));
443
- process.exit(0);
444
- }
445
- }
446
-
447
- console.log(JSON.stringify({ found: false }));
448
- "
449
- `;
450
- // ============================================================================
451
- // Firewall Detection Script (run on remote host)
452
- // ============================================================================
453
- const FIREWALL_DETECT_SCRIPT = `
454
- if command -v ufw >/dev/null 2>&1; then echo "ufw"
455
- elif command -v firewall-cmd >/dev/null 2>&1; then echo "firewalld"
456
- elif command -v iptables >/dev/null 2>&1; then echo "iptables"
457
- else echo "none"
458
- fi
459
- `;
460
- // ============================================================================
461
- // Deploy Executor
462
- // ============================================================================
463
- /**
464
- * Deploy ARIA to a remote machine via SSH.
465
- *
466
- * Steps:
467
- * 1. SSH connectivity check
468
- * 2. OS detection (uname -s)
469
- * 3. Linux distro detection (for package manager selection)
470
- * 4. Install Node.js 20+ if missing
471
- * 5. Enable corepack + pnpm
472
- * 6. Clone or update repo
473
- * 7. pnpm install && pnpm build
474
- * 8. Generate Ed25519 signing keypair if not present
475
- * 9. TLS cert discovery + optional provisioning
476
- * 10. Firewall port opening (443/tcp + 51820/udp)
477
- * 11. Write ~/.aria/config.json
478
- * 12. Start daemon on port 443
479
- * 13. Health check (curl endpoint)
480
- */
481
- export async function executeDeploy(input, ctx) {
482
- // Validate all inputs before any SSH calls (A1 — prevent shell injection)
483
- const targetError = validateTarget(input.target);
484
- if (targetError) {
485
- return fail(targetError);
486
- }
487
- const repoErr = validateRepoUrl(input.repo_url ?? "");
488
- if (repoErr)
489
- return fail(repoErr);
490
- const branchErr = validateBranch(input.branch ?? "");
491
- if (branchErr)
492
- return fail(branchErr);
493
- const nameErr = validateArionName(input.arion_name ?? "");
494
- if (nameErr)
495
- return fail(nameErr);
496
- const keyErr = validateSshKeyPath(input.ssh_key_path ?? "");
497
- if (keyErr)
498
- return fail(keyErr);
499
- const hashErr = validateCommitHash(input.commit_hash ?? "");
500
- if (hashErr)
501
- return fail(hashErr);
502
- const sshOpts = { sshKeyPath: input.ssh_key_path, abortSignal: ctx.abortSignal };
503
- const branch = input.branch ?? "main";
504
- const repoUrl = input.repo_url ?? "https://github.com/aria-ai/aria.git";
505
- // Request user confirmation — this is a dangerous operation
506
- const confirmed = await ctx.confirm(`Deploy ARIA to ${input.target}? This will install Node.js, clone the repo, build, and start the daemon.`);
507
- if (!confirmed) {
508
- return fail("User cancelled deployment");
509
- }
510
- // Track mutating steps for rollback on failure (A2)
511
- const completedSteps = [];
512
- let deployFailed = false;
513
- try {
514
- // Step 1: SSH connectivity check
515
- const connectivity = await sshExec(input.target, "echo ARIA_SSH_OK", sshOpts);
516
- if (connectivity.exitCode !== 0 || !connectivity.stdout.includes("ARIA_SSH_OK")) {
517
- return fail(`SSH connectivity failed to ${input.target}: ${connectivity.stderr || "no response"}`);
518
- }
519
- // Step 2: Detect OS
520
- const osResult = await sshExec(input.target, "uname -s 2>/dev/null || echo UNKNOWN", sshOpts);
521
- const osInfo = detectOS(osResult.stdout);
522
- if (osInfo.os === "unknown") {
523
- return fail(`Unsupported OS detected from uname: ${osResult.stdout.trim()}`);
524
- }
525
- // Step 3: Detect Linux distro for package manager selection
526
- let distro = "apt";
527
- if (osInfo.os === "linux") {
528
- const distroResult = await sshExec(input.target, "cat /etc/os-release 2>/dev/null || echo ''", sshOpts);
529
- distro = detectLinuxDistro(distroResult.stdout);
530
- }
531
- // Step 4: Install Node.js 20+ if not present
532
- const nodeCheck = await sshExec(input.target, 'node --version 2>/dev/null || echo "NO_NODE"', sshOpts);
533
- const hasNode = nodeCheck.stdout.startsWith("v") && parseInt(nodeCheck.stdout.slice(1), 10) >= 20;
534
- if (!hasNode) {
535
- const installCmd = getNodeInstallCommand(osInfo, distro);
536
- const installResult = await sshExec(input.target, installCmd, {
537
- ...sshOpts,
538
- timeoutMs: 300_000,
539
- });
540
- if (installResult.exitCode !== 0) {
541
- return fail(`Node.js installation failed: ${installResult.stderr}`);
542
- }
543
- }
544
- // Step 5: Enable corepack + pnpm (pinned version — never use @latest)
545
- const corepackCmd = `export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; corepack enable && corepack prepare pnpm@${PINNED_PNPM_VERSION} --activate`;
546
- const corepackResult = await sshExec(input.target, corepackCmd, sshOpts);
547
- if (corepackResult.exitCode !== 0) {
548
- return fail(`corepack/pnpm setup failed: ${corepackResult.stderr}`);
549
- }
550
- // Step 6: Clone or update repo
551
- const repoDir = "~/aria";
552
- const cloneCmd = `
553
- export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
554
- if [ -d ${repoDir}/.git ]; then
555
- cd ${repoDir} && git fetch origin && git checkout ${branch} && git pull origin ${branch}
556
- else
557
- git clone --branch ${branch} ${repoUrl} ${repoDir}
558
- fi
559
- `;
560
- const cloneResult = await sshExec(input.target, cloneCmd, {
561
- ...sshOpts,
562
- timeoutMs: 180_000,
563
- });
564
- if (cloneResult.exitCode !== 0) {
565
- return fail(`Repo clone/update failed: ${cloneResult.stderr}`);
566
- }
567
- // Step 6b: Pin to exact commit hash if provided (prevents MITM on branch refs)
568
- if (input.commit_hash) {
569
- const checkoutResult = await sshExec(input.target, `cd ${repoDir} && git checkout ${input.commit_hash}`, sshOpts);
570
- if (checkoutResult.exitCode !== 0) {
571
- return fail(`Commit hash checkout failed: ${checkoutResult.stderr}`);
572
- }
573
- }
574
- // Step 6c: Verify GPG signature on HEAD if requested
575
- if (input.verify_signatures) {
576
- const gpgResult = await sshExec(input.target, `cd ${repoDir} && git verify-commit HEAD`, sshOpts);
577
- if (gpgResult.exitCode !== 0) {
578
- return fail(`GPG signature verification failed: ${gpgResult.stderr}. ` +
579
- `Set verify_signatures=false to skip.`);
580
- }
581
- }
582
- // Step 7: pnpm install && pnpm build
583
- const buildCmd = `
584
- export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
585
- cd ${repoDir} && pnpm install --frozen-lockfile && pnpm store verify && pnpm build
586
- `;
587
- const buildResult = await sshExec(input.target, buildCmd, {
588
- ...sshOpts,
589
- timeoutMs: 600_000,
590
- });
591
- if (buildResult.exitCode !== 0) {
592
- return fail(`Build failed: ${buildResult.stderr}`);
593
- }
594
- // Step 8: Generate Ed25519 signing keypair if not present
595
- const keypairCmd = `
596
- mkdir -p ~/.aria
597
- if [ ! -f ~/.aria/signing-key.json ]; then
598
- node -e "
599
- const crypto = require('crypto');
600
- const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
601
- const pub = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');
602
- const priv = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64');
603
- const fp = crypto.createHash('sha256').update(Buffer.from(pub, 'base64')).digest('hex');
604
- const data = JSON.stringify({ publicKey: pub, privateKey: priv, fingerprint: fp }, null, 2);
605
- require('fs').writeFileSync(process.env.HOME + '/.aria/signing-key.json', data, { mode: 0o600 });
606
- console.log(JSON.stringify({ publicKey: pub, fingerprint: fp }));
607
- "
608
- else
609
- node -e "
610
- const data = JSON.parse(require('fs').readFileSync(process.env.HOME + '/.aria/signing-key.json', 'utf8'));
611
- console.log(JSON.stringify({ publicKey: data.publicKey, fingerprint: data.fingerprint }));
612
- "
613
- fi
614
- `;
615
- const keypairResult = await sshExec(input.target, keypairCmd, sshOpts);
616
- if (keypairResult.exitCode !== 0) {
617
- return fail(`Keypair generation failed: ${keypairResult.stderr}`);
618
- }
619
- completedSteps.push({ name: "keypair", undoCmd: "" }); // keypair is not rolled back (idempotent)
620
- // A3: Set key file permissions (chmod 600)
621
- const chmodKeyResult = await sshExec(input.target, "chmod 600 ~/.aria/signing-key.json", sshOpts);
622
- if (chmodKeyResult.exitCode !== 0) {
623
- // Non-fatal — best effort
624
- }
625
- let fingerprint = null;
626
- try {
627
- const keypairData = JSON.parse(keypairResult.stdout);
628
- fingerprint = keypairData.fingerprint ?? null;
629
- }
630
- catch {
631
- // Non-fatal — fingerprint is informational
632
- }
633
- // Step 9: TLS cert discovery + optional provisioning
634
- const tlsResult = await sshExec(input.target, TLS_DISCOVERY_SCRIPT, sshOpts);
635
- let tlsInfo = discoverTlsCerts(tlsResult.stdout);
636
- let tlsType = null;
637
- if (tlsInfo.found && tlsInfo.type) {
638
- tlsType = tlsInfo.type;
639
- }
640
- else {
641
- // Try Let's Encrypt auto-provisioning
642
- const hostnameResult = await sshExec(input.target, "hostname -f 2>/dev/null || hostname", sshOpts);
643
- const hostname = hostnameResult.stdout.trim();
644
- // Only attempt certbot if we have a domain name (not just an IP)
645
- if (hostname && !/^[\d.]+$/.test(hostname) && !/^[\da-f:]+$/i.test(hostname)) {
646
- const certbotResult = await sshExec(input.target, `command -v certbot >/dev/null 2>&1 && certbot certonly --standalone -d ${hostname} --non-interactive --agree-tos --register-unsafely-without-email 2>&1 || echo "NO_CERTBOT"`, { ...sshOpts, timeoutMs: 120_000 });
647
- if (certbotResult.exitCode === 0 && !certbotResult.stdout.includes("NO_CERTBOT")) {
648
- tlsInfo = {
649
- found: true,
650
- type: "letsencrypt",
651
- cert: `/etc/letsencrypt/live/${hostname}/fullchain.pem`,
652
- key: `/etc/letsencrypt/live/${hostname}/privkey.pem`,
653
- };
654
- tlsType = "letsencrypt";
655
- }
656
- }
657
- // Fall back to ARIA private CA
658
- if (!tlsType) {
659
- const privateCaCmd = `
660
- export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
661
- cd ~/aria && node -e "
662
- const { ensureMeshCerts } = require('./packages/server/dist/tls/mesh-certs.js');
663
- ensureMeshCerts().then(r => console.log(JSON.stringify({ cert: r.certPath, key: r.keyPath })));
664
- " 2>/dev/null || echo '{"cert":"~/.aria/tls/server.crt","key":"~/.aria/tls/server.key"}'
665
- `;
666
- const privateCaResult = await sshExec(input.target, privateCaCmd, sshOpts);
667
- try {
668
- const caPaths = JSON.parse(privateCaResult.stdout);
669
- tlsInfo = {
670
- found: true,
671
- type: "private-ca",
672
- cert: caPaths.cert,
673
- key: caPaths.key,
674
- };
675
- tlsType = "private-ca";
676
- }
677
- catch {
678
- // TLS setup failed, proceed without — daemon may still start on HTTP
679
- }
680
- }
681
- }
682
- // Step 10: Firewall port opening (A2 — tracked for rollback)
683
- let firewallType = "none";
684
- if (osInfo.os === "linux") {
685
- const fwDetect = await sshExec(input.target, FIREWALL_DETECT_SCRIPT, sshOpts);
686
- firewallType = fwDetect.stdout.trim();
687
- const fwCmds = getFirewallCommands(firewallType);
688
- if (fwCmds) {
689
- const fwResult = await sshExec(input.target, fwCmds, sshOpts);
690
- if (fwResult.exitCode === 0) {
691
- completedSteps.push({
692
- name: "firewall",
693
- undoCmd: getFirewallUndoCommands(firewallType),
694
- });
695
- }
696
- // Best-effort — don't fail the deploy if firewall commands fail (may need sudo)
697
- }
698
- }
699
- // Derive arion name from target hostname if not provided
700
- const host = input.target.includes("@") ? input.target.split("@")[1] : input.target;
701
- const arionName = input.arion_name ?? host.replace(/[^a-zA-Z0-9-]/g, "-");
702
- // Step 11: Write ~/.aria/config.json (A3 — deep merge for idempotency)
703
- const configObj = buildConfigJson({
704
- arionName,
705
- coordinationUrl: input.coordination_url,
706
- tlsCert: tlsInfo.found ? tlsInfo.cert : undefined,
707
- tlsKey: tlsInfo.found ? tlsInfo.key : undefined,
708
- });
709
- const configJson = JSON.stringify(configObj);
710
- // Escape for shell — replace single quotes
711
- const escapedConfig = configJson.replace(/'/g, "'\\''");
712
- const configCmd = `
713
- mkdir -p ~/.aria
714
- if [ -f ~/.aria/config.json ]; then
715
- node -e "
716
- const fs = require('fs');
717
- const existing = JSON.parse(fs.readFileSync(process.env.HOME + '/.aria/config.json', 'utf8'));
718
- const updates = JSON.parse('${escapedConfig}');
719
- // Deep merge: preserve nested objects
720
- function deepMerge(target, source) {
721
- for (const key of Object.keys(source)) {
722
- if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key]) &&
723
- target[key] && typeof target[key] === 'object' && !Array.isArray(target[key])) {
724
- deepMerge(target[key], source[key]);
725
- } else {
726
- target[key] = source[key];
727
- }
728
- }
729
- return target;
730
- }
731
- deepMerge(existing, updates);
732
- fs.writeFileSync(process.env.HOME + '/.aria/config.json', JSON.stringify(existing, null, 2), { mode: 0o600 });
733
- "
734
- else
735
- echo '${escapedConfig}' > ~/.aria/config.json && chmod 600 ~/.aria/config.json
736
- fi
737
- `;
738
- const configResult = await sshExec(input.target, configCmd, sshOpts);
739
- if (configResult.exitCode !== 0) {
740
- deployFailed = true;
741
- return fail(`Config write failed: ${configResult.stderr}`);
742
- }
743
- completedSteps.push({ name: "config", undoCmd: "rm -f ~/.aria/config.json" });
744
- // A3: Set config file permissions (chmod 600)
745
- await sshExec(input.target, "chmod 600 ~/.aria/config.json", sshOpts);
746
- // Step 12: Start daemon (nohup, backgrounded) on port 443
747
- const runtimePidLookupCmd = buildRemoteRuntimePidLookupCommand(repoDir);
748
- const runtimeStatusLookupCmd = buildRemoteRuntimeStatusLookupCommand(repoDir);
749
- const daemonCmd = `
750
- # Kill existing daemon if running
751
- PID=$(${runtimePidLookupCmd} 2>/dev/null || true)
752
- [ -n "$PID" ] && kill "$PID" 2>/dev/null || true
753
- export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
754
- cd ${repoDir}
755
- nohup node packages/cli/bin/aria.js daemon --arion ${arionName} --port 443 > ~/.aria/daemon.log 2>&1 &
756
- echo $!
757
- `;
758
- const daemonResult = await sshExec(input.target, daemonCmd, sshOpts);
759
- if (daemonResult.exitCode !== 0) {
760
- deployFailed = true;
761
- return fail(`Daemon start failed: ${daemonResult.stderr}`);
762
- }
763
- completedSteps.push({
764
- name: "daemon",
765
- undoCmd: `PID=$(${runtimePidLookupCmd} 2>/dev/null || true); [ -n "$PID" ] && kill "$PID" 2>/dev/null || true`,
766
- });
767
- // Step 13: Health check — wait for runtime owner/socket status then verify endpoint (A3 — mandatory)
768
- const healthCmd = `
769
- for i in $(seq 1 15); do
770
- STATUS=$(${runtimeStatusLookupCmd} 2>/dev/null || true)
771
- if [ -n "$STATUS" ]; then
772
- echo "$STATUS"
773
- exit 0
774
- fi
775
- sleep 1
776
- done
777
- echo "TIMEOUT"
778
- exit 1
779
- `;
780
- const healthResult = await sshExec(input.target, healthCmd, {
781
- ...sshOpts,
782
- timeoutMs: 30_000,
783
- });
784
- let port = null;
785
- if (healthResult.exitCode === 0 && !healthResult.stdout.includes("TIMEOUT")) {
786
- try {
787
- const runtimeStatus = JSON.parse(healthResult.stdout);
788
- port = runtimeStatus.port ?? null;
789
- }
790
- catch {
791
- // Non-fatal
792
- }
793
- }
794
- // A3: Mandatory health check — verify HTTP(S) endpoint returns 2xx
795
- if (port) {
796
- const healthUrl = buildHealthCheckUrl(host, port);
797
- const curlCmd = `curl -sSk -o /dev/null -w "%{http_code}" ${healthUrl} 2>/dev/null || echo "000"`;
798
- const curlResult = await sshExec(input.target, curlCmd, {
799
- ...sshOpts,
800
- timeoutMs: 10_000,
801
- });
802
- const httpCode = parseInt(curlResult.stdout.trim(), 10);
803
- if (isNaN(httpCode) || httpCode < 200 || httpCode >= 300) {
804
- deployFailed = true;
805
- return fail(`Health check failed: ${healthUrl} returned HTTP ${curlResult.stdout.trim()}. ` +
806
- `Check ~/.aria/daemon.log on ${input.target}.`);
807
- }
808
- }
809
- else if (healthResult.exitCode !== 0) {
810
- deployFailed = true;
811
- return fail(`Health check failed: runtime owner/socket status not available within 15s. ` +
812
- `Check ~/.aria/daemon.log on ${input.target}.`);
813
- }
814
- const output = {
815
- success: true,
816
- host,
817
- port,
818
- fingerprint,
819
- arionName,
820
- tlsType,
821
- };
822
- const statusLine = `Daemon running (port ${port ?? "unknown"})`;
823
- const tlsLine = tlsType ? `TLS: ${tlsType}` : "TLS: none (HTTP only)";
824
- return success(`ARIA deployed to ${input.target}.\n` +
825
- `Arion: ${arionName}\n` +
826
- `Fingerprint: ${fingerprint ?? "unknown"}\n` +
827
- `${tlsLine}\n` +
828
- `${statusLine}`, output);
829
- }
830
- catch (error) {
831
- deployFailed = true;
832
- return fail(`Deploy failed: ${error instanceof Error ? error.message : String(error)}`);
833
- }
834
- finally {
835
- // A2: Rollback on failure — undo completed steps in reverse order
836
- if (deployFailed && completedSteps.length > 0) {
837
- const rollbackCmds = buildRollbackCommands(completedSteps);
838
- for (const cmd of rollbackCmds) {
839
- try {
840
- await sshExec(input.target, cmd, sshOpts);
841
- }
842
- catch {
843
- // Best-effort rollback — don't throw during cleanup
844
- }
845
- }
846
- }
847
- }
848
- }