@ornncompute/cli 1.0.372 → 1.0.373

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.
package/README.md CHANGED
@@ -583,8 +583,8 @@ The upload replay contract requires the matching gateway/orchestrator release;
583
583
  see [the service contract](../../services/orchestrator/README.md#file-upload-replay-and-usage).
584
584
 
585
585
  For `ornn admin ssh <node-id>`, including `--user` for custom accounts,
586
- one-off commands, private nodes, and CA trust setup, see the
587
- [staff SSH procedure](../../docs/cli.md#staff-ssh).
586
+ one-off commands, private nodes, CA trust setup, and the repair it offers when
587
+ a node is blocked, see the [staff SSH procedure](../../docs/cli.md#staff-ssh).
588
588
 
589
589
  Gateway-bound connections resolve their gateway before producing SSH commands.
590
590
  Forwarded endpoints remain a single SSH destination. Supplier-provided jump hosts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ornncompute/cli",
3
- "version": "1.0.372",
3
+ "version": "1.0.373",
4
4
  "description": "Command-line interface for Ornn compute access workflows.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/admin-ssh.mjs CHANGED
@@ -1,19 +1,34 @@
1
+ import { getCliSession } from "../vendor/api-client/authorization.js";
1
2
  import * as orchestrator from "../vendor/api-client/orchestrator.js";
2
3
  import { sshArguments } from "../vendor/capabilities/cli.js";
3
4
  import { spawn } from "node:child_process";
5
+ import { randomUUID } from "node:crypto";
6
+ import { once } from "node:events";
4
7
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
5
8
  import { isIP } from "node:net";
6
9
  import { constants, tmpdir } from "node:os";
7
10
  import { join } from "node:path";
11
+ import { createInterface } from "node:readline/promises";
12
+ import { setTimeout as delay } from "node:timers/promises";
8
13
  import { ADMIN_MUTATION_SAFETY } from "./admin-mutations.mjs";
9
14
  import { parseAdminSshArgs, runAdminSshCommand } from "./admin-node-diagnostics.mjs";
10
15
  import { openSshRelay } from "./admin-ssh-relay.mjs";
11
16
  import { forwardSignals } from "./signals.mjs";
12
17
 
13
- function run(program, args, signal) {
18
+ const FIREWALL_RULE_SECONDS = 1800;
19
+
20
+ function run(program, args, signal, onDiagnostics) {
14
21
  signal.throwIfAborted();
15
22
  return new Promise((resolve, reject) => {
16
- const child = spawn(program, args, { stdio: "inherit", signal });
23
+ const child = spawn(program, args, {
24
+ stdio: ["inherit", "inherit", onDiagnostics ? "pipe" : "inherit"],
25
+ signal,
26
+ });
27
+ // The session itself stays on the terminal; only the program's own messages pass through here.
28
+ child.stderr?.on("data", (chunk) => {
29
+ process.stderr.write(chunk);
30
+ onDiagnostics(chunk.toString());
31
+ });
17
32
  child.once("error", (error) => {
18
33
  // A cancelled key generator must finish exiting before we remove its files.
19
34
  if (error.name !== "AbortError") reject(error);
@@ -24,6 +39,77 @@ function run(program, args, signal) {
24
39
  });
25
40
  }
26
41
 
42
+ // This command only runs with terminal stdin and stdout; stderr may be redirected to a file.
43
+ async function confirmOnTerminal(
44
+ question,
45
+ { stdin = process.stdin, stdout = process.stdout },
46
+ signal
47
+ ) {
48
+ const reader = createInterface({ input: stdin, output: stdout, terminal: false });
49
+ try {
50
+ // End of input leaves the question pending, so it counts as a refusal.
51
+ const answer = await Promise.race([
52
+ reader.question(`${question} [Y/n] `, { signal }),
53
+ once(reader, "close").then(() => "n"),
54
+ ]);
55
+ return ["", "y", "yes"].includes(answer.trim().toLowerCase());
56
+ } finally {
57
+ reader.close();
58
+ }
59
+ }
60
+
61
+ // Why OpenSSH never opened a session. One that connected and later dropped matches neither.
62
+ // `destination` is the host name OpenSSH logged in to, so a jump host's denial is not the node's.
63
+ function sshBlock(exitCode, diagnostics, username, destination) {
64
+ if (exitCode !== 255) return null;
65
+ if (
66
+ diagnostics
67
+ .split(/\r?\n/)
68
+ .some((line) => line.startsWith(`${username}@${destination}: Permission denied`))
69
+ ) {
70
+ return "access";
71
+ }
72
+ return /^ssh: connect to host \S+ port \d+: (Connection timed out|Operation timed out|Connection refused|No route to host)/m.test(
73
+ diagnostics
74
+ )
75
+ ? "network"
76
+ : null;
77
+ }
78
+
79
+ async function callerAddress(request, host) {
80
+ const { clientIp } = await getCliSession(request);
81
+ if (!clientIp) throw new Error("Ornn could not determine this machine's public address.");
82
+ if (isIP(host) && isIP(host) !== isIP(clientIp)) {
83
+ throw new Error(
84
+ `This machine reaches Ornn from ${clientIp}, a different IP version than the node's SSH address ${host}, so a firewall rule for it would not help.`
85
+ );
86
+ }
87
+ return clientIp;
88
+ }
89
+
90
+ async function allowSshFrom(request, nodeId, sourceIp, port, sleep) {
91
+ const change = {
92
+ request_id: randomUUID(),
93
+ rule: { source_ip: sourceIp, protocol: "tcp", port },
94
+ operation: "add",
95
+ ttl_seconds: FIREWALL_RULE_SECONDS,
96
+ reason: "Staff SSH session",
97
+ };
98
+ for (;;) {
99
+ // Repeating the same request reads its saved result.
100
+ const { status, result } = await orchestrator.changeManagedNodeFirewall(
101
+ request,
102
+ nodeId,
103
+ change
104
+ );
105
+ if (status === "completed") return;
106
+ if (status !== "accepted") {
107
+ throw new Error(result?.error ?? "The node did not confirm the firewall change.");
108
+ }
109
+ await sleep(1000);
110
+ }
111
+ }
112
+
27
113
  async function supplierJumpArguments(fetch, node, host, port, username, signal) {
28
114
  if (node.ssh_relay_configured === true || !node.ssh_gateway_id) return [];
29
115
  const gateway = await orchestrator.getSupplierGateway(fetch, node.ssh_gateway_id, signal);
@@ -53,7 +139,7 @@ async function supplierJumpArguments(fetch, node, host, port, username, signal)
53
139
 
54
140
  export async function openAdminSsh(
55
141
  { input, fetch, runtime },
56
- { runProcess = run, openRelay = openSshRelay } = {}
142
+ { runProcess = run, openRelay = openSshRelay, confirm = confirmOnTerminal } = {}
57
143
  ) {
58
144
  // Read the existing node route; issuance returns only its own certificate.
59
145
  const node = await orchestrator.getNode(fetch, input.node_id);
@@ -74,9 +160,9 @@ export async function openAdminSsh(
74
160
  const signal = runtime.signal
75
161
  ? AbortSignal.any([runtime.signal, controller.signal])
76
162
  : controller.signal;
163
+ const request = (path, init) => fetch(path, { ...init, signal });
77
164
  let interrupted;
78
165
  let directory;
79
- let relay;
80
166
  const removeSignals = forwardSignals(process, null, (received) => {
81
167
  interrupted ??= received;
82
168
  controller.abort();
@@ -92,11 +178,10 @@ export async function openAdminSsh(
92
178
  );
93
179
  if (generated !== 0) throw new Error("Could not generate the temporary SSH key.");
94
180
  const public_key = (await readFile(`${key}.pub`, "utf8")).trim();
95
- const issued = await orchestrator.issueNodeSshCertificate(
96
- (path, init) => fetch(path, { ...init, signal }),
97
- input.node_id,
98
- { public_key, ...(input.username === undefined ? {} : { username }) }
99
- );
181
+ const issued = await orchestrator.issueNodeSshCertificate(request, input.node_id, {
182
+ public_key,
183
+ ...(input.username === undefined ? {} : { username }),
184
+ });
100
185
  signal.throwIfAborted();
101
186
  if (
102
187
  typeof issued.certificate !== "string" ||
@@ -104,48 +189,90 @@ export async function openAdminSsh(
104
189
  )
105
190
  throw new Error("The issuer returned an invalid SSH certificate.");
106
191
  await writeFile(`${key}-cert.pub`, `${issued.certificate}\n`, { mode: 0o600 });
107
- if (node.ssh_relay_configured === true) {
108
- relay = await openRelay(input.node_id, { env: runtime.env, signal });
192
+ const connect = async () => {
193
+ // The relay carries one connection, so each attempt opens its own.
194
+ const relay =
195
+ node.ssh_relay_configured === true
196
+ ? await openRelay(input.node_id, { env: runtime.env, signal })
197
+ : undefined;
198
+ const relayOptions = relay
199
+ ? [
200
+ "-o",
201
+ "HostName=127.0.0.1",
202
+ "-o",
203
+ `HostKeyAlias=${port === 22 ? host : `[${host}]:${port}`}`,
204
+ "-o",
205
+ "ProxyCommand=none",
206
+ "-o",
207
+ "ControlPath=none",
208
+ ]
209
+ : [];
210
+ let diagnostics = "";
211
+ try {
212
+ const exitCode = await runProcess(
213
+ "ssh",
214
+ [
215
+ "-o",
216
+ "IdentitiesOnly=yes",
217
+ "-o",
218
+ `CertificateFile=${key}-cert.pub`,
219
+ "-i",
220
+ key,
221
+ "-p",
222
+ String(relay?.port ?? port),
223
+ ...relayOptions,
224
+ ...jumpOptions,
225
+ "-l",
226
+ username,
227
+ host,
228
+ ],
229
+ signal,
230
+ (text) => {
231
+ diagnostics = (diagnostics + text).slice(-4096);
232
+ }
233
+ );
234
+ signal.throwIfAborted();
235
+ return {
236
+ exitCode,
237
+ block: sshBlock(exitCode, diagnostics, username, relay ? "127.0.0.1" : host),
238
+ };
239
+ } finally {
240
+ relay?.close();
241
+ }
242
+ };
243
+ let session = await connect();
244
+ // A firewall rule names this machine, so it only helps when SSH goes straight to the node.
245
+ const direct = node.ssh_relay_configured !== true && !node.ssh_gateway_id;
246
+ if (session.block === "access" || (session.block === "network" && direct)) {
247
+ const sourceIp = session.block === "network" ? await callerAddress(request, host) : null;
248
+ const repair = sourceIp
249
+ ? `SSH from this machine cannot reach it. Allow SSH from ${sourceIp} for ${FIREWALL_RULE_SECONDS / 60} minutes and install Ornn SSH access for ${username}?`
250
+ : `It does not accept Ornn SSH certificates for ${username}. Install Ornn SSH access for ${username}?`;
251
+ if (await confirm(`Node ${input.node_id} is blocked. ${repair}`, runtime, signal)) {
252
+ (runtime.stdout ?? process.stdout).write("Unblocking the node...\n");
253
+ if (sourceIp) {
254
+ await allowSshFrom(
255
+ request,
256
+ input.node_id,
257
+ sourceIp,
258
+ port,
259
+ runtime.sleep ?? ((milliseconds) => delay(milliseconds, undefined, { signal }))
260
+ );
261
+ }
262
+ // The certificate in hand is signed by the active CA, staged replacement or not.
263
+ await orchestrator.installNodeSshCaTrust(request, input.node_id, {
264
+ ca: "active",
265
+ ...(input.username === undefined ? {} : { username }),
266
+ });
267
+ session = await connect();
268
+ }
109
269
  }
110
- const relayOptions = relay
111
- ? [
112
- "-o",
113
- "HostName=127.0.0.1",
114
- "-o",
115
- `HostKeyAlias=${port === 22 ? host : `[${host}]:${port}`}`,
116
- "-o",
117
- "ProxyCommand=none",
118
- "-o",
119
- "ControlPath=none",
120
- ]
121
- : [];
122
- const exitCode = await runProcess(
123
- "ssh",
124
- [
125
- "-o",
126
- "IdentitiesOnly=yes",
127
- "-o",
128
- `CertificateFile=${key}-cert.pub`,
129
- "-i",
130
- key,
131
- "-p",
132
- String(relay?.port ?? port),
133
- ...relayOptions,
134
- ...jumpOptions,
135
- "-l",
136
- username,
137
- host,
138
- ],
139
- signal
140
- );
141
- signal.throwIfAborted();
142
- return { suppressResult: true, exitCode };
270
+ return { suppressResult: true, exitCode: session.exitCode };
143
271
  } catch (error) {
144
272
  if (!interrupted) throw error;
145
273
  return { suppressResult: true, exitCode: 128 + constants.signals[interrupted] };
146
274
  } finally {
147
275
  try {
148
- relay?.close();
149
276
  if (directory) await rm(directory, { recursive: true, force: true });
150
277
  } finally {
151
278
  removeSignals();
@@ -776,7 +776,10 @@ const DIRECT_GATEWAY_PREFIXES = [
776
776
  "/v1/orchestrator/supplier-connection-configs",
777
777
  "/v1/orchestrator/supplier-gateways",
778
778
  ];
779
- const DIRECT_GATEWAY_PATHS = new Set(["/v1/orchestrator/supplier-gateway-regions"]);
779
+ const DIRECT_GATEWAY_PATHS = new Set([
780
+ "/v1/cli/session",
781
+ "/v1/orchestrator/supplier-gateway-regions",
782
+ ]);
780
783
 
781
784
  // Same 1:1 owner set as apps/mcp/lib/tools/admin.ts isDirectOrchestratorOwnerPath.
782
785
  const STAFF_ORCHESTRATOR_ROOTS = new Set([
@@ -850,6 +850,9 @@ function updateNodeKeys(request, id, body, headers) {
850
850
  function issueNodeSshCertificate(request, id, body) {
851
851
  return request(`${nodeResourcePath(id)}/ssh-certificates`, { method: "POST", body });
852
852
  }
853
+ function installNodeSshCaTrust(request, id, body) {
854
+ return request(`${nodeResourcePath(id)}/ssh-ca-trust`, { method: "PUT", body });
855
+ }
853
856
  function rebootNode(request, id, body, headers) {
854
857
  return request(`${nodeResourcePath(id)}/reboot`, {
855
858
  method: "POST",
@@ -1311,6 +1314,7 @@ export {
1311
1314
  getVirtualMachineLogs,
1312
1315
  hardwareCatalogPath,
1313
1316
  importDisk,
1317
+ installNodeSshCaTrust,
1314
1318
  issueEnrollmentCredential,
1315
1319
  issueNodeSshCertificate,
1316
1320
  keepDriveUploadsAlive,