Skip to main content

oxdock_ssh_plugin/
funcs.rs

1//! The `SSH` host module: `SERVE`, `ACCEPT` / `DEQUEUE` + `PUMP_CHANNEL`,
2//! `CLOSE`, `CONNECT`, `PUMP`.
3//!
4//! Pipe direction convention (fixed for every func): `out_pipe` carries
5//! bytes produced by the wire side (the DSL reads them), `in_pipe`
6//! carries bytes consumed by the wire side (the DSL writes them).
7
8use std::collections::BTreeMap;
9use std::sync::Arc;
10use std::sync::atomic::AtomicBool;
11
12use anyhow::{Context, Result, bail};
13use oxdock_core::{Field, HostModule, OxDockFn, OxDockType, RecordSchema, StepCtx, TypeTag, Value};
14use oxdock_func_macro::oxdock_func;
15use oxdock_net_plugin::{
16    AcquiredListener, EndpointKey, EndpointRegistry, ServiceTarget, SocketRequirement,
17    acquire_listener, no_cli_mapping, parse_virtual_endpoint, resolve_service_target,
18};
19use oxdock_pipe::PipeHandle;
20use oxdock_process::ProcessManager;
21use russh::keys::{Algorithm, PrivateKey};
22
23use crate::bridge::{pump_pipe_to_pipe, pump_session};
24use crate::keys::load_or_create_host_key;
25use crate::runtime::{connect_runtime, connect_session};
26use crate::state::{
27    CLOSE_JOIN_TIMEOUT, Dequeue, PendingSession, ServerState, SessionQueue, ShutdownSignal,
28};
29use crate::types::{SshServerTag, SshSessionTag};
30use crate::validate::parse_serve_endpoint;
31
32/// Result map keys for SSH session outcomes. Single source for the
33/// `Field` schemas below and every `map.insert` site, so a rename
34/// cannot drift one side silent.
35const FIELD_CLOSED: &str = "closed";
36const FIELD_COMMAND: &str = "command";
37const FIELD_EXIT_STATUS: &str = "exit_status";
38const FIELD_SERVER: &str = "server";
39const FIELD_ADDR: &str = "addr";
40const FIELD_USERNAME: &str = "username";
41const FIELD_PASSWORD: &str = "password";
42const FIELD_VIRTUAL: &str = "virtual";
43const FIELD_SESSION: &str = "session";
44const FIELD_EXIT: &str = "exit";
45const FIELD_TRUNCATED: &str = "truncated";
46const FIELD_TIMED_OUT: &str = "timed_out";
47
48/// Option map keys for SSH calls. `username` and `password` reuse the
49/// `FIELD_*` spellings above (same words, same meaning); the rest live
50/// here so every lookup matches its `#[options]` spelling.
51const OPT_KEY_PATH: &str = "key_path";
52const OPT_IDLE_TIMEOUT: &str = "idle_timeout";
53const OPT_TIMEOUT: &str = "timeout";
54const OPT_MAX_BYTES: &str = "max_bytes";
55
56/// Unique server ids per process.
57static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
58
59/// Block until the queue yields an authenticated session (or teardown).
60/// Shared by `SSH_DEQUEUE` and the `SSH_ACCEPT` wrapper. No timeout:
61/// a waiter parks in the queue condvar while a bridge thread parks on
62/// the task hub; on hub fire the bridge pokes the queue awake and the
63/// waiter ends with `Cancelled`. One transient thread per call, spent
64/// only on wakeups, never on ticks.
65fn dequeue_session<P: ProcessManager>(
66    cx: &StepCtx<P>,
67    queue: &Arc<SessionQueue>,
68    func: &str,
69) -> Result<PendingSession> {
70    let hub = cx.cancel_hub();
71    let bridge_queue = Arc::clone(queue);
72    let bridge_hub = Arc::clone(&hub);
73    let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
74    std::thread::scope(|scope| {
75        let bridge = scope.spawn(move || {
76            // Rendezvous: read the sequence, then signal, then park,
77            // so the release below can never land before the wait.
78            let seen = bridge_hub.sequence();
79            let _ = started_tx.send(());
80            let (cancelled, _) = bridge_hub.wait(seen);
81            if cancelled {
82                bridge_queue.poke();
83            }
84        });
85        let result = loop {
86            if hub.is_cancelled() || cx.is_cancelled() {
87                break Err(anyhow::anyhow!("{func}: task cancelled"));
88            }
89            match queue.try_pop() {
90                Dequeue::Session(session) => break Ok(session),
91                Dequeue::Shutdown => break Err(anyhow::anyhow!("{func}: server is closed")),
92                Dequeue::Empty | Dequeue::Cancelled => {}
93            }
94            match queue.wait_blocking(&hub) {
95                Dequeue::Session(session) => break Ok(session),
96                Dequeue::Shutdown => break Err(anyhow::anyhow!("{func}: server is closed")),
97                Dequeue::Cancelled | Dequeue::Empty => {}
98            }
99        };
100        // Release the bridge (rendezvous first so the poke cannot
101        // land before its wait, then poke, never cancel: the dequeue
102        // may have ended cleanly) and join it: no thread outlives the
103        // call.
104        let _ = started_rx.recv();
105        hub.poke();
106        let _ = bridge.join();
107        result
108    })
109}
110
111/// Dequeue one authenticated session for routing before any byte
112/// pumping starts. Must run inside `ASYNC`.
113///
114/// The server sends first: the client side never EOFs its input, so a
115/// synthetic reply cannot race teardown.
116///
117#[oxdock_func(
118    returns = TypeTag::Record(dequeue_result_fields()),
119    summary = "Dequeue one SSH session with its metadata."
120)]
121#[example(
122    name = "route one session",
123    code = r###"
124    IMPORT [STD, SSH]
125    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-route", {username: "u", password: "p"})
126
127    # Serve: dequeue one session and pump a synthetic reply.
128    LET $in: PIPE
129    LET $out: PIPE
130    LET $w: HANDLE<VOID> = ASYNC {
131        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
132        ASSERT_EQ $sess.username "u"
133        SSH_PUMP_CHANNEL($sess.session, $in, $out)
134    }
135
136    # Connect a client to the server.
137    LET $cin: PIPE
138    LET $cout: PIPE
139    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-route", "u", "p", $cin, $cout) }
140
141    # Close both inputs: each pump observes EOF, half-closes, and every
142    # task returns with no cancellation.
143    WITH_IO [stdout=$cin] ECHO "client-hello"
144    WITH_IO [stdout=$in] ECHO "server-greeting"
145    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
146    ASSERT_EQ $cDone.closed true
147    AWAIT $w
148    SSH_CLOSE($m.server)
149    "###
150)]
151fn ssh_dequeue<P: ProcessManager>(
152    cx: &mut StepCtx<P>,
153    /// Server handle from `SSH_SERVE`.
154    server: SshServerTag,
155) -> Result<Value> {
156    if !cx.is_async_task() {
157        bail!(
158            "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE<T> = ASYNC {{ SSH_DEQUEUE($server.server) }}"
159        );
160    }
161    let state = Arc::clone(server.state());
162    let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
163    let command = session.exec_command.clone().unwrap_or_default();
164    let username = session.username.clone().unwrap_or_default();
165    let addr = session
166        .peer_addr
167        .map(|addr| addr.to_string())
168        .unwrap_or_default();
169    let tag = SshSessionTag::new(
170        session.exec_command,
171        session.username,
172        session.peer_addr,
173        session.pty_size,
174        session.up_rx,
175        session.down_tx,
176    );
177    let mut map = BTreeMap::new();
178    map.insert(
179        "session".to_string(),
180        Value::mint_heap(SshSessionTag::descriptor(), tag),
181    );
182    map.insert(FIELD_COMMAND.to_string(), Value::string(command));
183    map.insert(FIELD_USERNAME.to_string(), Value::string(username));
184    map.insert(FIELD_ADDR.to_string(), Value::string(addr));
185    Ok(Value::map(map))
186}
187
188/// Spin up an SSH server on a runner-mapped service. Unmapped and
189/// memory services bail: SSH needs a TCP socket.
190/// `options` takes required `username`/`password` STRINGs plus the
191/// optional `key_path` STRING (workspace-relative Ed25519 file,
192/// load-or-create; blank keeps the ephemeral key) and the optional
193/// `idle_timeout` DURATION (quiet-connection kill, default 5m; zero
194/// disables it for persistent sessions).
195#[oxdock_func(returns = TypeTag::Record(serve_result_fields()), summary = "Serve SSH on a virtual service endpoint.")]
196#[example(
197    name = "serve and close",
198    code = r###"
199    IMPORT [STD, SSH]
200    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-serve", {username: "u", password: "p"})
201    ASSERT_EQ $m.virtual "doc-ssh-serve"
202    SSH_CLOSE($m.server)
203    "###
204)]
205fn ssh_serve<P: ProcessManager>(
206    cx: &mut StepCtx<P>,
207    /// Service name to serve; the runner maps it with -p/--listen.
208    bind: String,
209    /// Server credentials and host key.
210    #[options(
211        "username: STRING",
212        "password: STRING",
213        "key_path?: STRING",
214        "idle_timeout?: DURATION|STRING"
215    )]
216    options: BTreeMap<String, Value>,
217) -> Result<Value> {
218    let map = &options;
219    let username = match map.get(FIELD_USERNAME) {
220        Some(value) => {
221            let text = value.as_str().expect("check_options verified STRING");
222            if text.trim().is_empty() {
223                bail!("SSH_SERVE option '{FIELD_USERNAME}' must not be empty");
224            }
225            text.to_string()
226        }
227        None => bail!("SSH_SERVE option '{FIELD_USERNAME}' is required"),
228    };
229    let password = match map.get(FIELD_PASSWORD) {
230        Some(value) => {
231            let text = value.as_str().expect("check_options verified STRING");
232            if text.trim().is_empty() {
233                bail!("SSH_SERVE option '{FIELD_PASSWORD}' must not be empty");
234            }
235            text.to_string()
236        }
237        None => bail!("SSH_SERVE option '{FIELD_PASSWORD}' is required"),
238    };
239    let key_path = match map.get(OPT_KEY_PATH) {
240        Some(value) => {
241            let text = value.as_str().expect("check_options verified STRING");
242            if text.trim().is_empty() {
243                None
244            } else {
245                Some(text.to_string())
246            }
247        }
248        None => None,
249    };
250    // Idle kill override: absent keeps the default, zero disables the
251    // timeout entirely (persistent sessions must opt out explicitly).
252    let idle_timeout = match map.get(OPT_IDLE_TIMEOUT) {
253        Some(value) => {
254            // `check_options` verified `DURATION|STRING`; narrow directly.
255            let timeout = if let Some(duration) = value.as_duration() {
256                duration
257            } else {
258                let text = value
259                    .as_str()
260                    .expect("check_options verified DURATION|STRING");
261                oxdock_parser::command::parse_duration(text).with_context(|| {
262                    format!(
263                        "SSH_SERVE option '{OPT_IDLE_TIMEOUT}' must be a duration, got {text:?}"
264                    )
265                })?
266            };
267            (!timeout.is_zero()).then_some(timeout)
268        }
269        None => Some(crate::runtime::DEFAULT_INACTIVITY_TIMEOUT),
270    };
271    let registry = cx
272        .module_state::<EndpointRegistry>("SSH")
273        .expect("SSH module registers its endpoint registry as module state");
274    let endpoint = parse_serve_endpoint(&bind)?;
275    let key = EndpointKey::tcp(endpoint);
276    let (acquired, registry) = acquire_listener(
277        &registry,
278        &key,
279        "SSH_SERVE",
280        SocketRequirement::SocketRequired,
281    )?;
282    let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
283        Some(key) => key,
284        None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
285            .context("generate ephemeral Ed25519 host key")?,
286    };
287    let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
288    let id = format!("ssh-{pid}-{id}", pid = std::process::id());
289    let queue = Arc::new(SessionQueue::new());
290    let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
291    let (local_addr, addr_text, thread) = match acquired {
292        AcquiredListener::Tcp { listener, addr } => {
293            // The runtime owns a clone; the slot keeps the backlog socket.
294            let owned = listener
295                .try_clone()
296                .context("SSH_SERVE cannot clone its listener")?;
297            let thread_queue = Arc::clone(&queue);
298            let thread_user = username.clone();
299            let thread_pass = password.clone();
300            let thread = std::thread::Builder::new()
301                .name(id.clone())
302                .spawn(move || {
303                    crate::runtime::serve(
304                        owned,
305                        host_key,
306                        thread_user,
307                        thread_pass,
308                        thread_queue,
309                        shutdown_rx,
310                        idle_timeout,
311                    )
312                })
313                .context("SSH_SERVE cannot spawn the server thread")?;
314            (addr, addr.to_string(), Some(thread))
315        }
316        AcquiredListener::Memory => {
317            // Unreachable: `SocketRequired` already bailed; same text.
318            drop(shutdown_rx);
319            return Err(no_cli_mapping("SSH_SERVE", &key.endpoint));
320        }
321        AcquiredListener::Offline => {
322            // No thread: dropping the receiver makes shutdown a no-op.
323            drop(shutdown_rx);
324            (
325                std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
326                key.endpoint.to_string(),
327                None,
328            )
329        }
330    };
331    let state = Arc::new(ServerState::new(crate::state::ServerConfig {
332        id,
333        local_addr,
334        addr_text: addr_text.clone(),
335        queue,
336        shutdown_tx,
337        thread,
338        registry: Arc::clone(&registry),
339        endpoint: key.clone(),
340    }));
341    let mut map = BTreeMap::new();
342    map.insert(
343        "server".to_string(),
344        Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
345    );
346    map.insert(FIELD_ADDR.to_string(), Value::string(addr_text));
347    map.insert(FIELD_USERNAME.to_string(), Value::string(username));
348    map.insert(FIELD_PASSWORD.to_string(), Value::string(password));
349    map.insert(
350        "virtual".to_string(),
351        Value::string(key.endpoint.to_string()),
352    );
353    Ok(Value::map(map))
354}
355
356/// `SSH_DEQUEUE` + `SSH_PUMP_CHANNEL` in one call, for worker loops
357/// that need no pre-pump inspection. Must run inside `ASYNC`.
358///
359/// The server sends first: the client side never EOFs its input, so
360/// the reply cannot race teardown.
361///
362#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
363    name: FIELD_CLOSED.to_string(),
364    ty: TypeTag::Bool,
365    docs: "True when the session closed cleanly.",
366    optional: false,
367}, Field {
368    name: FIELD_COMMAND.to_string(),
369    ty: TypeTag::String,
370    docs: "Executed command, empty for shells.",
371    optional: false,
372}])), summary = "Accept one SSH session into pipes.")]
373#[example(
374    name = "accept and close",
375    code = r###"
376    IMPORT [STD, SSH]
377    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-accept", {username: "u", password: "p"})
378    LET $in: PIPE
379    LET $out: PIPE
380    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
381    LET $cin: PIPE
382    LET $cout: PIPE
383    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-accept", "u", "p", $cin, $cout) }
384
385    # Close both inputs: each pump observes EOF, half-closes, and both
386    # tasks return their result maps with no cancellation.
387    WITH_IO [stdout=$cin] ECHO "client-hello"
388    WITH_IO [stdout=$in] ECHO "server-greeting"
389    LET $done: MAP<ANY> = AWAIT $acc
390    ASSERT_EQ $done.closed true
391    ASSERT_CONTAINS $done "command"
392    LET $cDone: MAP<ANY> = AWAIT $c
393    ASSERT_EQ $cDone.closed true
394    SSH_CLOSE($m.server)
395    "###
396)]
397fn ssh_accept<P: ProcessManager>(
398    cx: &mut StepCtx<P>,
399    /// Server handle from `SSH_SERVE`.
400    server: SshServerTag,
401    /// Pipe carrying bytes consumed by the wire side.
402    in_pipe: PipeHandle,
403    /// Pipe carrying bytes produced by the wire side.
404    out_pipe: PipeHandle,
405) -> Result<Value> {
406    if !cx.is_async_task() {
407        bail!(
408            "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE<T> = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
409        );
410    }
411    let in_pipe = Value::pipe_handle(in_pipe);
412    let out_pipe = Value::pipe_handle(out_pipe);
413    let state = Arc::clone(server.state());
414    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
415    pump_session(
416        cx,
417        &in_pipe,
418        &out_pipe,
419        session.up_rx,
420        session.down_tx,
421        true,
422    )?;
423    let mut map = BTreeMap::new();
424    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
425    map.insert(
426        "command".to_string(),
427        Value::string(session.exec_command.unwrap_or_default()),
428    );
429    Ok(Value::map(map))
430}
431
432/// Pump a dequeued session through explicit pipes until the channel
433/// closes. Must run inside `ASYNC`. Pump ends take once: a second
434/// pump bails instead of splitting bytes.
435///
436#[oxdock_func(
437    returns = TypeTag::Record(std::sync::Arc::from([Field {
438        name: FIELD_CLOSED.to_string(),
439        ty: TypeTag::Bool,
440        docs: "True when the session closed cleanly.",
441        optional: false,
442    }])),
443    summary = "Pump a dequeued SSH session through pipes."
444)]
445#[example(
446    name = "pump a session",
447    code = r###"
448    IMPORT [STD, SSH]
449    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pump", {username: "u", password: "p"})
450    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
451    LET $cin: PIPE
452    LET $cout: PIPE
453    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-pump", "u", "p", $cin, $cout) }
454    WITH_IO [stdout=$cin] ECHO "client-hello"
455    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
456    LET $sin: PIPE
457    LET $sout: PIPE
458    LET $p: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
459    WITH_IO [stdout=$sin] ECHO "server-greeting"
460    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
461    ASSERT_EQ $cDone.closed true
462    LET $pDone: MAP<ANY> = AWAIT $p
463    ASSERT_EQ $pDone.closed true
464    SSH_CLOSE($m.server)
465    "###
466)]
467fn ssh_pump_channel<P: ProcessManager>(
468    cx: &mut StepCtx<P>,
469    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
470    session: SshSessionTag,
471    /// Pipe carrying bytes consumed by the wire side.
472    in_pipe: PipeHandle,
473    /// Pipe carrying bytes produced by the wire side.
474    out_pipe: PipeHandle,
475) -> Result<Value> {
476    if !cx.is_async_task() {
477        bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
478    }
479    let in_pipe = Value::pipe_handle(in_pipe);
480    let out_pipe = Value::pipe_handle(out_pipe);
481    let (up_rx, down_tx) = session.take_pump_ends()?;
482    // Release the control sender when the pump ends (pass or fail):
483    // the wire writer must observe the drain and close then, not when
484    // the last session clone drops long after.
485    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, true);
486    session.finish_pump();
487    pump?;
488    let mut map = BTreeMap::new();
489    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
490    Ok(Value::map(map))
491}
492
493/// Report the session's exit status to the client (RFC 4254 6.10),
494/// ahead of the channel close. Survives the take-once pump ends, so
495/// call it before the pump drains. `SSH_PTY_RUN` reports by itself;
496/// this covers other legs (`RUN`, synthetic replies).
497#[oxdock_func(returns = TypeTag::Bool, summary = "Send the session exit status to the client.")]
498#[example(
499    name = "report exit status",
500    code = r###"
501    IMPORT [STD, SSH]
502    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exit-status", {username: "u", password: "p"})
503    LET $srv: HANDLE<VOID> = ASYNC {
504        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
505        LET $sin: PIPE
506        LET $sout: PIPE
507        LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
508        SSH_SEND_EXIT_STATUS($sess.session, 3)
509        WITH_IO [stdout=$sin] ECHO "server-greeting"
510        AWAIT $p
511    }
512    LET $cin: PIPE
513    LET $cout: PIPE
514    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-exit-status", "u", "p", $cin, $cout) }
515    # Close the client input: its pump observes EOF and half-closes, so
516    # both pumps drain instead of idling on an empty pipe.
517    WITH_IO [stdout=$cin] ECHO "client-hello"
518    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
519    ASSERT_EQ $cDone.closed true
520    ASSERT_EQ $cDone.exit_status 3
521    AWAIT $srv
522    SSH_CLOSE($m.server)
523    "###
524)]
525fn ssh_send_exit_status<P: ProcessManager>(
526    cx: &mut StepCtx<P>,
527    /// Session handle from `SSH_DEQUEUE`.
528    session: SshSessionTag,
529    /// Exit status to report (0 to 4294967295).
530    code: i64,
531) -> Result<Value> {
532    let _ = cx;
533    if code < 0 {
534        bail!("SSH_SEND_EXIT_STATUS code must not be negative: {code}");
535    }
536    let code = u32::try_from(code)
537        .map_err(|_| anyhow::anyhow!("SSH_SEND_EXIT_STATUS code out of range: {code}"))?;
538    session.send_exit_status(code)?;
539    Ok(Value::bool(true))
540}
541
542/// Shut a server down and join its runtime thread (bounded).
543/// Idempotent.
544///
545#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
546#[example(
547    name = "shut down",
548    code = r###"
549    IMPORT [STD, SSH]
550    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-close", {username: "u", password: "p"})
551    LET $ok: BOOL = SSH_CLOSE($m.server)
552    ASSERT_EQ $ok true
553    "###
554)]
555fn ssh_close<P: ProcessManager>(
556    cx: &mut StepCtx<P>,
557    /// Server handle from `SSH_SERVE`.
558    server: SshServerTag,
559) -> Result<Value> {
560    let _ = cx;
561    let state = Arc::clone(server.state());
562    state.request_shutdown();
563    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
564}
565
566/// Open an SSH client session and pump its shell channel through
567/// explicit pipes until it closes. Must run inside `ASYNC`, beside
568/// the pump tasks. Under `--offline` the dial bails before any
569/// socket work. The result MAP carries `exit_status`, or -1 when the
570/// server sent none.
571#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
572    name: FIELD_CLOSED.to_string(),
573    ty: TypeTag::Bool,
574    docs: "True when the session closed cleanly.",
575    optional: false,
576}, Field {
577    name: FIELD_EXIT_STATUS.to_string(),
578    ty: TypeTag::Int,
579    docs: "Remote exit status, or -1 when none arrived.",
580    optional: false,
581}])), summary = "Open an SSH client session into pipes.")]
582#[example(
583    name = "connect and close",
584    code = r###"
585    IMPORT [STD, SSH]
586    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-connect", {username: "u", password: "p"})
587    LET $in: PIPE
588    LET $out: PIPE
589    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
590    LET $cin: PIPE
591    LET $cout: PIPE
592    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-connect", "u", "p", $cin, $cout) }
593
594    # Close both inputs: each pump observes EOF, half-closes, and both
595    # tasks return their result maps with no cancellation.
596    WITH_IO [stdout=$cin] ECHO "client-hello"
597    WITH_IO [stdout=$in] ECHO "server-greeting"
598    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
599    ASSERT_EQ $cDone.closed true
600    LET $adone: MAP<ANY> = AWAIT $acc
601    ASSERT_EQ $adone.closed true
602    SSH_CLOSE($m.server)
603    "###
604)]
605fn ssh_connect<P: ProcessManager>(
606    cx: &mut StepCtx<P>,
607    /// Dial target: a service name resolved through runner mappings.
608    target: String,
609    /// Inner credentials for the SSH session.
610    username: String,
611    /// Inner credentials for the SSH session.
612    password: String,
613    /// Pipe carrying bytes consumed by the wire side.
614    in_pipe: PipeHandle,
615    /// Pipe carrying bytes produced by the wire side.
616    out_pipe: PipeHandle,
617) -> Result<Value> {
618    if !cx.is_async_task() {
619        bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
620    }
621    // Registry travels as module state.
622    let registry = cx
623        .module_state::<EndpointRegistry>("SSH")
624        .expect("SSH module registers its endpoint registry as module state");
625    let in_pipe = Value::pipe_handle(in_pipe);
626    let out_pipe = Value::pipe_handle(out_pipe);
627    if registry.is_offline() {
628        bail!("SSH_CONNECT failed: engine running in --offline mode");
629    }
630    if username.is_empty() {
631        bail!("SSH_CONNECT username must not be empty");
632    }
633    // Symbolic only: physical shapes already failed in the parser.
634    let endpoint = parse_virtual_endpoint(&target, "SSH_CONNECT")?;
635    let key = EndpointKey::tcp(endpoint);
636    let addr = match resolve_service_target(
637        &registry,
638        &key,
639        "SSH_CONNECT",
640        SocketRequirement::SocketRequired,
641    )? {
642        ServiceTarget::Tcp(addr) => addr,
643        // Unreachable: the shared resolver already bailed; same text.
644        ServiceTarget::Memory => {
645            return Err(no_cli_mapping("SSH_CONNECT", &key.endpoint));
646        }
647    };
648    let runtime = connect_runtime()?;
649    let session = runtime
650        .block_on(connect_session(&addr, &username, &password))
651        .context("SSH_CONNECT failed")?;
652    let crate::runtime::OutboundSession {
653        up_rx,
654        down_tx,
655        exit_status,
656        wire_done,
657        handle,
658        ..
659    } = session;
660    // Client linger: the reply and the exit-status arrive after the
661    // client's own stdin EOF, so never cut the output wait short.
662    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, false);
663    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
664    pump?;
665    // Joined after disconnect: a post-EOF status records before this read.
666    let _ = runtime.block_on(wire_done);
667    let mut map = BTreeMap::new();
668    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
669    let status = exit_status
670        .lock()
671        .map(|slot| slot.map(i64::from))
672        .unwrap_or(None);
673    map.insert(
674        FIELD_EXIT_STATUS.to_string(),
675        Value::int(status.unwrap_or(-1)),
676    );
677    Ok(Value::map(map))
678}
679
680/// Copy one pipe into another until EOF, then close the target.
681/// Either task placement works, as long as the other end is live.
682///
683#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
684#[example(
685    name = "copy",
686    code = r###"
687    # Closing the source ends the copy: the count proves the bytes moved.
688    IMPORT [STD, SSH]
689    LET $in: PIPE
690    WITH_IO [stdout=$in] ECHO "pump-me"
691    LET $out: PIPE
692    LET $n: INT = SSH_PUMP($in, $out)
693    ASSERT_EQ $n 8
694    WITH_IO [stdin=$out] READ_LINE $got
695    ASSERT_EQ $got "pump-me"
696    "###
697)]
698fn ssh_pump<P: ProcessManager>(
699    cx: &mut StepCtx<P>,
700    /// Source pipe to drain.
701    from_pipe: PipeHandle,
702    /// Target pipe receiving the bytes (closed at EOF).
703    to_pipe: PipeHandle,
704) -> Result<Value> {
705    let from_pipe = Value::pipe_handle(from_pipe);
706    let to_pipe = Value::pipe_handle(to_pipe);
707    let cancel = AtomicBool::new(false);
708    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
709    Ok(Value::int(total))
710}
711
712/// Run `argv` under a local pseudo-terminal and pump it through
713/// explicit pipes until the child exits. Must run inside `ASYNC`.
714/// Returns the INT exit code.
715///
716/// `rows`/`cols` seed the initial size when positive, else the
717/// session's requested size (24x80 default). Outer window-changes
718/// resize live; each session owns its cell.
719///
720/// The code also reports as the wire `exit-status` at child exit, so
721/// stock clients see the real code instead of 255.
722///
723/// Every session opens cleared and homed, like Win32-OpenSSH, so the
724/// child renders onto a known blank screen.
725///
726/// Windows joining follows MSVCRT rules, so CRT programs parse back
727/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
728/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
729/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
730///
731/// Stdin arrives with console line endings handled: the pump expands
732/// a lone `\n` to `\r\n` on Windows, so portable lines submit as-is
733/// and an explicit `\r` passes through untouched. Real terminals
734/// already send CR for Enter.
735///
736/// Environment is exactly the script environment like `RUN`:
737/// block-scoped `ENV` (such as the session's `SSH_USER` / `SSH_CLIENT` /
738/// `SSH_SERVER` / `SSH_COMMAND` relay) reaches the child; host names
739/// arrive only through `INHERIT_ENV`, including `TERM` for terminal
740/// definitions. The working directory comes from the script.
741///
742/// `WITH_IO [tty]` shares the same pump core and covers terminal
743/// runs with host or static sizing and step-local reporting. This
744/// function covers the two session-bound cases a script assembly
745/// cannot reproduce: a rendered run with static geometry observes
746/// the opener but never an outer resize (no script primitive
747/// subscribes a running pty to the session cell), and a failing DSL
748/// `RUN` aborts its task before any script-level status report could
749/// follow (there is no try/catch; the close race after that would be
750/// the second problem). If a second consumer ever needs
751/// session-driven sizing or reaper-ordered reporting, that is the
752/// point to revisit unifying the two.
753///
754#[oxdock_func(
755    returns = TypeTag::Int,
756    summary = "Run a command under a sized local terminal into pipes."
757)]
758#[example(
759    name = "run under a terminal",
760    code = r###"
761    IMPORT [STD, SSH]
762    INHERIT_ENV [PATH]
763    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
764    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
765    LET $cin: PIPE
766    LET $cout: PIPE
767    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
768    WITH_IO [stdout=$cin] ECHO "client-hello"
769    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
770
771    # The client task only proved the session live: cancel it before the
772    # terminal run, so no two pumps share the session.
773    CANCEL $c
774    LET $pin: PIPE
775    LET $pout: PIPE
776    # Assert on the whole pipe: terminal streams carry setup noise ahead
777    # of child output, so line reads are version-dependent.
778    [family:unix] {
779        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
780        LET $code: INT = AWAIT $t
781        ASSERT_EQ $code 0
782        ASSERT_CONTAINS $pout "pty-hi"
783    }
784    [family:windows] {
785        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
786        LET $code: INT = AWAIT $t
787        ASSERT_EQ $code 0
788        ASSERT_CONTAINS $pout "pty-hi"
789    }
790    SSH_CLOSE($m.server)
791    "###
792)]
793fn ssh_pty_run<P: ProcessManager>(
794    cx: &mut StepCtx<P>,
795    /// Session handle from `SSH_DEQUEUE`.
796    session: SshSessionTag,
797    /// Program and arguments to run.
798    argv: Vec<String>,
799    /// Terminal rows when positive, session size otherwise.
800    rows: i64,
801    /// Terminal columns when positive, session size otherwise.
802    cols: i64,
803    /// Pipe carrying bytes consumed by the child.
804    in_pipe: PipeHandle,
805    /// Pipe carrying bytes produced by the child.
806    out_pipe: PipeHandle,
807) -> Result<Value> {
808    if !cx.is_async_task() {
809        bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
810    }
811    let in_pipe = Value::pipe_handle(in_pipe);
812    let out_pipe = Value::pipe_handle(out_pipe);
813    let initial = if rows > 0 && cols > 0 {
814        crate::state::PtySize::new(rows as u32, cols as u32)
815    } else {
816        session.pty_size()
817    };
818    // Best effort: an unpumped session has no reader. Owned clone:
819    // the reaper runs detached, so the callback must be `'static`.
820    let session_report = session.clone();
821    let report = move |code: u32| {
822        let _ = session_report.send_exit_status(code);
823    };
824    let code = crate::pty::pump_pty_session(
825        cx,
826        &argv,
827        initial,
828        &session.pty_size_handle(),
829        &in_pipe,
830        &out_pipe,
831        Some(std::sync::Arc::new(report)),
832    )?;
833    Ok(Value::int(code))
834}
835
836/// Run `argv` directly (no terminal) and pump it through explicit pipes
837/// until the child exits. Must run inside `ASYNC`. Returns the INT exit
838/// code (-1 when the child died by signal).
839///
840/// Bytes travel untouched: no init sequence, no newline translation, no
841/// setup handshake. This is the binary-safe leg `scp`-style protocols
842/// need; `SSH_PTY_RUN` owns the interactive side instead.
843///
844/// The code reports as the wire `exit-status` at child exit, so stock
845/// clients see the real code instead of 255. Signaled children report
846/// nothing: clients observe the close without a status.
847///
848/// Stdin EOF closes the child's stdin, so stdin-driven children like
849/// `cat` exit on their own. Standard output and error ride separate
850/// pipes: diagnostics must never pollute the byte stream.
851///
852/// Environment is exactly the script environment like `RUN`:
853/// block-scoped `ENV` reaches the child; host names arrive only through
854/// `INHERIT_ENV`. The working directory comes from the script.
855///
856/// Windows joining follows MSVCRT rules, so CRT programs parse back
857/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
858/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
859/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
860#[oxdock_func(
861    returns = TypeTag::Int,
862    summary = "Run a command with piped stdio into explicit pipes."
863)]
864#[example(
865    name = "run with piped stdio",
866    code = r###"
867    IMPORT [STD, SSH]
868    INHERIT_ENV [PATH]
869    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-run", {username: "u", password: "p"})
870    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
871    LET $cin: PIPE
872    LET $cout: PIPE
873    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-run", "u", "p", $cin, $cout) }
874    WITH_IO [stdout=$cin] ECHO "client-hello"
875    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
876
877    # The client task only proved the session live: cancel it before the
878    # run, so no two pumps share the session.
879    CANCEL $c
880    LET $pin: PIPE
881    LET $pout: PIPE
882    LET $perr: PIPE
883    LET $argv: LIST<STRING> = ["sh", "-c", "echo run-hi"]
884    [family:windows] {
885        $argv = ["cmd", "/c", "echo run-hi"]
886    }
887    LET $t: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
888    LET $code: INT = AWAIT $t
889    ASSERT_EQ $code 0
890    ASSERT_CONTAINS $pout "run-hi"
891    SSH_CLOSE($m.server)
892    "###
893)]
894fn ssh_run<P: ProcessManager>(
895    cx: &mut StepCtx<P>,
896    /// Session handle from `SSH_DEQUEUE`.
897    session: SshSessionTag,
898    /// Program and arguments to run.
899    argv: Vec<String>,
900    /// Pipe carrying bytes consumed by the child on stdin.
901    in_pipe: PipeHandle,
902    /// Pipe carrying bytes produced by the child on stdout.
903    out_pipe: PipeHandle,
904    /// Pipe carrying bytes produced by the child on stderr.
905    err_pipe: PipeHandle,
906) -> Result<Value> {
907    if !cx.is_async_task() {
908        bail!("SSH_RUN requires ASYNC: run it in its own task beside the session pump task");
909    }
910    let in_pipe = Value::pipe_handle(in_pipe);
911    let out_pipe = Value::pipe_handle(out_pipe);
912    let err_pipe = Value::pipe_handle(err_pipe);
913    // Best effort: an unpumped session has no reader. Owned clone:
914    // the reaper runs detached, so the callback must be `'static`.
915    let session_report = session.clone();
916    let report = move |code: u32| {
917        let _ = session_report.send_exit_status(code);
918    };
919    let code = crate::run::pump_run_session(
920        cx,
921        &argv,
922        &in_pipe,
923        &out_pipe,
924        &err_pipe,
925        Some(std::sync::Arc::new(report)),
926    )?;
927    Ok(Value::int(code))
928}
929
930/// Run one argv vector on a remote host over SSH and collect the
931/// result. Stateless by design: every call carries its target,
932/// credentials, and argv, holds no session, and returns one MAP with
933/// `exit`, `stdout`, `stderr`, `truncated`, and `timed_out`. A retry
934/// after a dropped channel repeats the same bytes, so idempotent
935/// commands make retries boring.
936///
937/// The argv never becomes a shell string in script hands: it joins
938/// once here through `shell_words::join`, the same vetted
939/// implementation behind `SHELL_SPLIT_ARGS`/`SHELL_JOIN_ARGS` and the
940/// remote plugins. Quoting `$HOME`, backticks, and redirects arrive as
941/// literal arguments because no layer between the caller and this join
942/// re-parses them.
943///
944/// Output caps apply while reading: past `max_bytes` per stream the
945/// buffers stop growing but the drain continues, so a flood still
946/// learns its exit status and reports `truncated`. A timeout kills
947/// the wait and returns whatever arrived with `timed_out`. `exit` is
948/// -1 when the server never sent a status.
949#[oxdock_func(returns = TypeTag::Map, summary = "Run argv on a remote host over SSH and collect the result.")]
950#[example(
951    name = "exec collects remote output",
952    code = r###"
953    # The server side answers exec with a local run: dequeue the
954    # session, split the joined command back into argv, run it, and
955    # pump the child output into the channel. The exit status rides
956    # the wire through the session report.
957    IMPORT [STD, SSH]
958    INHERIT_ENV [PATH]
959    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exec", {username: "u", password: "p"})
960    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
961    LET $runner: HANDLE<VOID> = ASYNC {
962        LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
963        LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
964        LET $wire: PIPE
965        LET $drain: PIPE
966        LET $pump: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
967        LET $pin: PIPE
968        LET $pout: PIPE
969        LET $perr: PIPE
970        LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
971        LET $n: INT = SSH_PUMP($pout, $wire)
972        LET $code: INT = AWAIT $run
973        LET $pDone: MAP<ANY> = AWAIT $pump
974        ASSERT_EQ $code 0
975    }
976
977    # One call, one MAP: argv in, collected streams out.
978    [family:unix] {
979        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["echo", "exec-hi"], {})
980        ASSERT_EQ $res.timed_out false
981        ASSERT_EQ $res.exit 0
982        ASSERT_CONTAINS $res.stdout "exec-hi"
983    }
984    [family:windows] {
985        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["cmd", "/c", "echo exec-hi"], {})
986        ASSERT_EQ $res.timed_out false
987        ASSERT_EQ $res.exit 0
988        ASSERT_CONTAINS $res.stdout "exec-hi"
989    }
990    AWAIT $runner
991    SSH_CLOSE($m.server)
992    "###
993)]
994fn ssh_exec<P: ProcessManager>(
995    cx: &mut StepCtx<P>,
996    /// Dial target: a service name resolved through runner mappings.
997    target: String,
998    /// Inner credentials for the SSH session.
999    username: String,
1000    /// Inner credentials for the SSH session.
1001    password: String,
1002    /// Program and arguments to run remotely; joined once, by the
1003    /// plugin, with POSIX shell quoting.
1004    argv: Vec<String>,
1005    /// `timeout` DURATION|STRING (default 60s) and `max_bytes` INT
1006    /// (default 8 MiB per stream).
1007    #[options("timeout?: DURATION|STRING", "max_bytes?: INT")]
1008    options: BTreeMap<String, Value>,
1009) -> Result<Value> {
1010    if argv.is_empty() {
1011        bail!("SSH_EXEC needs at least a program");
1012    }
1013    if username.is_empty() {
1014        bail!("SSH_EXEC username must not be empty");
1015    }
1016    let registry = cx
1017        .module_state::<EndpointRegistry>("SSH")
1018        .expect("SSH module registers its endpoint registry as module state");
1019    if registry.is_offline() {
1020        bail!("SSH_EXEC failed: engine running in --offline mode");
1021    }
1022    // Symbolic only: physical shapes already failed in the parser.
1023    let endpoint = parse_virtual_endpoint(&target, "SSH_EXEC")?;
1024    let key = EndpointKey::tcp(endpoint);
1025    let addr = match resolve_service_target(
1026        &registry,
1027        &key,
1028        "SSH_EXEC",
1029        SocketRequirement::SocketRequired,
1030    )? {
1031        ServiceTarget::Tcp(addr) => addr,
1032        // Unreachable: the shared resolver already bailed; same text.
1033        ServiceTarget::Memory => {
1034            return Err(no_cli_mapping("SSH_EXEC", &key.endpoint));
1035        }
1036    };
1037    let timeout = match options.get(OPT_TIMEOUT) {
1038        None => crate::runtime::DEFAULT_EXEC_TIMEOUT,
1039        Some(value) => {
1040            // `check_options` verified `DURATION|STRING`; narrow directly.
1041            let timeout = if let Some(duration) = value.as_duration() {
1042                duration
1043            } else {
1044                let text = value
1045                    .as_str()
1046                    .expect("check_options verified DURATION|STRING");
1047                oxdock_parser::command::parse_duration(text).with_context(|| {
1048                    format!("SSH_EXEC option '{OPT_TIMEOUT}' must be a duration, got {text:?}")
1049                })?
1050            };
1051            if timeout.is_zero() {
1052                bail!("SSH_EXEC option '{OPT_TIMEOUT}' must be positive");
1053            }
1054            timeout
1055        }
1056    };
1057    let max_bytes = match options.get(OPT_MAX_BYTES) {
1058        None => crate::runtime::DEFAULT_EXEC_MAX_BYTES,
1059        Some(value) => {
1060            let bytes = value.as_i64().expect("check_options verified INT");
1061            if bytes <= 0 {
1062                bail!("SSH_EXEC option '{OPT_MAX_BYTES}' must be positive");
1063            }
1064            bytes as usize
1065        }
1066    };
1067    // The single shell encoding in the pipeline: argv becomes one
1068    // string here, and only here.
1069    let command = shell_words::join(&argv).into_bytes();
1070    let runtime = connect_runtime()?;
1071    let outcome = runtime
1072        .block_on(crate::runtime::run_remote_exec(
1073            &addr, &username, &password, command, timeout, max_bytes,
1074        ))
1075        .context("SSH_EXEC failed")?;
1076    let mut map = BTreeMap::new();
1077    map.insert(
1078        FIELD_EXIT.to_string(),
1079        Value::int(outcome.exit.unwrap_or(-1)),
1080    );
1081    map.insert(
1082        "stdout".to_string(),
1083        Value::string(String::from_utf8_lossy(&outcome.stdout).into_owned()),
1084    );
1085    map.insert(
1086        "stderr".to_string(),
1087        Value::string(String::from_utf8_lossy(&outcome.stderr).into_owned()),
1088    );
1089    map.insert(FIELD_TRUNCATED.to_string(), Value::bool(outcome.truncated));
1090    map.insert(FIELD_TIMED_OUT.to_string(), Value::bool(outcome.timed_out));
1091    Ok(Value::map(map))
1092}
1093
1094/// Mint a random server password (256 bits, hex).
1095///
1096/// Each call draws fresh OS-RNG key material and renders 64
1097/// lowercase hex chars, so committed scripts carry no usable
1098/// credential: mint at runtime, hand the value to both sides, drop
1099/// it after. Pure (no step context), so it runs anywhere a STRING
1100/// binds, including option maps and placeholders.
1101#[oxdock_func(pure, returns = TypeTag::String)]
1102#[example(
1103    name = "mint and serve",
1104    code = r###"
1105    IMPORT [STD, SSH]
1106
1107    # Fresh draws mint 64 hex chars with no committed secret.
1108    LET $pass: STRING = SSH_GENERATE_PASSWORD()
1109    LET $len: INT = LEN($pass)
1110    ASSERT_EQ $len 64
1111
1112    # The minted value serves directly as a server password.
1113    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-gen-pass", {username: "u", password: $pass})
1114    SSH_CLOSE($m.server)
1115    "###
1116)]
1117fn ssh_generate_password() -> Result<Value> {
1118    Ok(Value::string(crate::generate_password()))
1119}
1120
1121/// Field table backing the `SSH_SERVE_INFO` schema and return tag.
1122fn serve_result_fields() -> Arc<[Field]> {
1123    Arc::from(vec![
1124        Field {
1125            name: FIELD_SERVER.to_string(),
1126            ty: TypeTag::Custom(SshServerTag::descriptor()),
1127            docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
1128            optional: false,
1129        },
1130        Field {
1131            name: FIELD_ADDR.to_string(),
1132            ty: TypeTag::String,
1133            docs: "Bound socket address (`ip:port`) of the server.",
1134            optional: false,
1135        },
1136        Field {
1137            name: FIELD_USERNAME.to_string(),
1138            ty: TypeTag::String,
1139            docs: "Configured username.",
1140            optional: false,
1141        },
1142        Field {
1143            name: FIELD_PASSWORD.to_string(),
1144            ty: TypeTag::String,
1145            docs: "Configured password.",
1146            optional: false,
1147        },
1148        Field {
1149            name: FIELD_VIRTUAL.to_string(),
1150            ty: TypeTag::String,
1151            docs: "Virtual endpoint echo of the claimed slot.",
1152            optional: false,
1153        },
1154    ])
1155}
1156
1157/// Field table backing the `SSH_DEQUEUE_INFO` schema and return tag.
1158fn dequeue_result_fields() -> Arc<[Field]> {
1159    Arc::from(vec![
1160        Field {
1161            name: FIELD_SESSION.to_string(),
1162            ty: TypeTag::Custom(SshSessionTag::descriptor()),
1163            docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
1164            optional: false,
1165        },
1166        Field {
1167            name: FIELD_COMMAND.to_string(),
1168            ty: TypeTag::String,
1169            docs: "Executed command, empty for shells.",
1170            optional: false,
1171        },
1172        Field {
1173            name: FIELD_USERNAME.to_string(),
1174            ty: TypeTag::String,
1175            docs: "Authenticated username, empty when unset.",
1176            optional: false,
1177        },
1178        Field {
1179            name: FIELD_ADDR.to_string(),
1180            ty: TypeTag::String,
1181            docs: "Peer address, empty when unset.",
1182            optional: false,
1183        },
1184    ])
1185}
1186
1187/// The `SSH` host module: virtual-endpoint server plus client, bridged
1188/// to DSL pipes. Generic over the process manager like every host module.
1189pub fn module_with<P: ProcessManager>() -> HostModule<P> {
1190    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
1191}
1192
1193/// The `SSH` host module resolving through `registry`: the registry
1194/// travels as module state (`HostModule::with_state`) for bodies to
1195/// fetch from `cx`, so every entry stays `#[oxdock_func]`. Everything
1196/// else reaches the same registry through its `SSH_SERVER` handle. A
1197/// pre-run service check rides along: every service the steps name must
1198/// be fully bound before execution starts.
1199pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
1200    let check = registry.pre_run_check("SSH");
1201    HostModule {
1202        name: "SSH".to_string(),
1203        funcs: vec![
1204            SshServe::registration(),
1205            SshAccept::registration(),
1206            SshDequeue::registration(),
1207            SshPumpChannel::registration(),
1208            SshSendExitStatus::registration(),
1209            SshClose::registration(),
1210            SshConnect::registration(),
1211            SshExec::registration(),
1212            SshPump::registration(),
1213            SshPtyRun::registration(),
1214            SshRun::registration(),
1215            SshGeneratePassword::registration(),
1216        ],
1217        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
1218        record_schemas: vec![
1219            RecordSchema {
1220                name: "SSH_SERVE_INFO",
1221                fields: serve_result_fields(),
1222            },
1223            RecordSchema {
1224                name: "SSH_DEQUEUE_INFO",
1225                fields: dequeue_result_fields(),
1226            },
1227        ],
1228        states: Vec::new(),
1229    }
1230    .with_state(registry)
1231    .with_state(Arc::new(check))
1232}