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    default: None,
368}, Field {
369    name: FIELD_COMMAND.to_string(),
370    ty: TypeTag::String,
371    docs: "Executed command, empty for shells.",
372    optional: false,
373    default: None,
374}])), summary = "Accept one SSH session into pipes.")]
375#[example(
376    name = "accept and close",
377    code = r###"
378    IMPORT [STD, SSH]
379    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-accept", {username: "u", password: "p"})
380    LET $in: PIPE
381    LET $out: PIPE
382    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
383    LET $cin: PIPE
384    LET $cout: PIPE
385    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-accept", "u", "p", $cin, $cout) }
386
387    # Close both inputs: each pump observes EOF, half-closes, and both
388    # tasks return their result maps with no cancellation.
389    WITH_IO [stdout=$cin] ECHO "client-hello"
390    WITH_IO [stdout=$in] ECHO "server-greeting"
391    LET $done: MAP<ANY> = AWAIT $acc
392    ASSERT_EQ $done.closed true
393    ASSERT_CONTAINS $done "command"
394    LET $cDone: MAP<ANY> = AWAIT $c
395    ASSERT_EQ $cDone.closed true
396    SSH_CLOSE($m.server)
397    "###
398)]
399fn ssh_accept<P: ProcessManager>(
400    cx: &mut StepCtx<P>,
401    /// Server handle from `SSH_SERVE`.
402    server: SshServerTag,
403    /// Pipe carrying bytes consumed by the wire side.
404    in_pipe: PipeHandle,
405    /// Pipe carrying bytes produced by the wire side.
406    out_pipe: PipeHandle,
407) -> Result<Value> {
408    if !cx.is_async_task() {
409        bail!(
410            "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE<T> = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
411        );
412    }
413    let in_pipe = Value::pipe_handle(in_pipe);
414    let out_pipe = Value::pipe_handle(out_pipe);
415    let state = Arc::clone(server.state());
416    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
417    pump_session(
418        cx,
419        &in_pipe,
420        &out_pipe,
421        session.up_rx,
422        session.down_tx,
423        true,
424    )?;
425    let mut map = BTreeMap::new();
426    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
427    map.insert(
428        "command".to_string(),
429        Value::string(session.exec_command.unwrap_or_default()),
430    );
431    Ok(Value::map(map))
432}
433
434/// Pump a dequeued session through explicit pipes until the channel
435/// closes. Must run inside `ASYNC`. Pump ends take once: a second
436/// pump bails instead of splitting bytes.
437///
438#[oxdock_func(
439    returns = TypeTag::Record(std::sync::Arc::from([Field {
440        name: FIELD_CLOSED.to_string(),
441        ty: TypeTag::Bool,
442        docs: "True when the session closed cleanly.",
443        optional: false,
444        default: None,
445    }])),
446    summary = "Pump a dequeued SSH session through pipes."
447)]
448#[example(
449    name = "pump a session",
450    code = r###"
451    IMPORT [STD, SSH]
452    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pump", {username: "u", password: "p"})
453    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
454    LET $cin: PIPE
455    LET $cout: PIPE
456    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-pump", "u", "p", $cin, $cout) }
457    WITH_IO [stdout=$cin] ECHO "client-hello"
458    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
459    LET $sin: PIPE
460    LET $sout: PIPE
461    LET $p: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
462    WITH_IO [stdout=$sin] ECHO "server-greeting"
463    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
464    ASSERT_EQ $cDone.closed true
465    LET $pDone: MAP<ANY> = AWAIT $p
466    ASSERT_EQ $pDone.closed true
467    SSH_CLOSE($m.server)
468    "###
469)]
470fn ssh_pump_channel<P: ProcessManager>(
471    cx: &mut StepCtx<P>,
472    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
473    session: SshSessionTag,
474    /// Pipe carrying bytes consumed by the wire side.
475    in_pipe: PipeHandle,
476    /// Pipe carrying bytes produced by the wire side.
477    out_pipe: PipeHandle,
478) -> Result<Value> {
479    if !cx.is_async_task() {
480        bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
481    }
482    let in_pipe = Value::pipe_handle(in_pipe);
483    let out_pipe = Value::pipe_handle(out_pipe);
484    let (up_rx, down_tx) = session.take_pump_ends()?;
485    // Release the control sender when the pump ends (pass or fail):
486    // the wire writer must observe the drain and close then, not when
487    // the last session clone drops long after.
488    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, true);
489    session.finish_pump();
490    pump?;
491    let mut map = BTreeMap::new();
492    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
493    Ok(Value::map(map))
494}
495
496/// Report the session's exit status to the client (RFC 4254 6.10),
497/// ahead of the channel close. Survives the take-once pump ends, so
498/// call it before the pump drains. `SSH_PTY_RUN` reports by itself;
499/// this covers other legs (`RUN`, synthetic replies).
500#[oxdock_func(returns = TypeTag::Bool, summary = "Send the session exit status to the client.")]
501#[example(
502    name = "report exit status",
503    code = r###"
504    IMPORT [STD, SSH]
505    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exit-status", {username: "u", password: "p"})
506    LET $srv: HANDLE<VOID> = ASYNC {
507        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
508        LET $sin: PIPE
509        LET $sout: PIPE
510        LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
511        SSH_SEND_EXIT_STATUS($sess.session, 3)
512        WITH_IO [stdout=$sin] ECHO "server-greeting"
513        AWAIT $p
514    }
515    LET $cin: PIPE
516    LET $cout: PIPE
517    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-exit-status", "u", "p", $cin, $cout) }
518    # Close the client input: its pump observes EOF and half-closes, so
519    # both pumps drain instead of idling on an empty pipe.
520    WITH_IO [stdout=$cin] ECHO "client-hello"
521    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
522    ASSERT_EQ $cDone.closed true
523    ASSERT_EQ $cDone.exit_status 3
524    AWAIT $srv
525    SSH_CLOSE($m.server)
526    "###
527)]
528fn ssh_send_exit_status<P: ProcessManager>(
529    cx: &mut StepCtx<P>,
530    /// Session handle from `SSH_DEQUEUE`.
531    session: SshSessionTag,
532    /// Exit status to report (0 to 4294967295).
533    code: i64,
534) -> Result<Value> {
535    let _ = cx;
536    if code < 0 {
537        bail!("SSH_SEND_EXIT_STATUS code must not be negative: {code}");
538    }
539    let code = u32::try_from(code)
540        .map_err(|_| anyhow::anyhow!("SSH_SEND_EXIT_STATUS code out of range: {code}"))?;
541    session.send_exit_status(code)?;
542    Ok(Value::bool(true))
543}
544
545/// Shut a server down and join its runtime thread (bounded).
546/// Idempotent.
547///
548#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
549#[example(
550    name = "shut down",
551    code = r###"
552    IMPORT [STD, SSH]
553    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-close", {username: "u", password: "p"})
554    LET $ok: BOOL = SSH_CLOSE($m.server)
555    ASSERT_EQ $ok true
556    "###
557)]
558fn ssh_close<P: ProcessManager>(
559    cx: &mut StepCtx<P>,
560    /// Server handle from `SSH_SERVE`.
561    server: SshServerTag,
562) -> Result<Value> {
563    let _ = cx;
564    let state = Arc::clone(server.state());
565    state.request_shutdown();
566    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
567}
568
569/// Open an SSH client session and pump its shell channel through
570/// explicit pipes until it closes. Must run inside `ASYNC`, beside
571/// the pump tasks. Under `--offline` the dial bails before any
572/// socket work. The result MAP carries `exit_status`, or -1 when the
573/// server sent none.
574#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
575    name: FIELD_CLOSED.to_string(),
576    ty: TypeTag::Bool,
577    docs: "True when the session closed cleanly.",
578    optional: false,
579    default: None,
580}, Field {
581    name: FIELD_EXIT_STATUS.to_string(),
582    ty: TypeTag::Int,
583    docs: "Remote exit status, or -1 when none arrived.",
584    optional: false,
585    default: None,
586}])), summary = "Open an SSH client session into pipes.")]
587#[example(
588    name = "connect and close",
589    code = r###"
590    IMPORT [STD, SSH]
591    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-connect", {username: "u", password: "p"})
592    LET $in: PIPE
593    LET $out: PIPE
594    LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
595    LET $cin: PIPE
596    LET $cout: PIPE
597    LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-connect", "u", "p", $cin, $cout) }
598
599    # Close both inputs: each pump observes EOF, half-closes, and both
600    # tasks return their result maps with no cancellation.
601    WITH_IO [stdout=$cin] ECHO "client-hello"
602    WITH_IO [stdout=$in] ECHO "server-greeting"
603    LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
604    ASSERT_EQ $cDone.closed true
605    LET $adone: MAP<ANY> = AWAIT $acc
606    ASSERT_EQ $adone.closed true
607    SSH_CLOSE($m.server)
608    "###
609)]
610fn ssh_connect<P: ProcessManager>(
611    cx: &mut StepCtx<P>,
612    /// Dial target: a service name resolved through runner mappings.
613    target: String,
614    /// Inner credentials for the SSH session.
615    username: String,
616    /// Inner credentials for the SSH session.
617    password: String,
618    /// Pipe carrying bytes consumed by the wire side.
619    in_pipe: PipeHandle,
620    /// Pipe carrying bytes produced by the wire side.
621    out_pipe: PipeHandle,
622) -> Result<Value> {
623    if !cx.is_async_task() {
624        bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
625    }
626    // Registry travels as module state.
627    let registry = cx
628        .module_state::<EndpointRegistry>("SSH")
629        .expect("SSH module registers its endpoint registry as module state");
630    let in_pipe = Value::pipe_handle(in_pipe);
631    let out_pipe = Value::pipe_handle(out_pipe);
632    if registry.is_offline() {
633        bail!("SSH_CONNECT failed: engine running in --offline mode");
634    }
635    if username.is_empty() {
636        bail!("SSH_CONNECT username must not be empty");
637    }
638    // Symbolic only: physical shapes already failed in the parser.
639    let endpoint = parse_virtual_endpoint(&target, "SSH_CONNECT")?;
640    let key = EndpointKey::tcp(endpoint);
641    let addr = match resolve_service_target(
642        &registry,
643        &key,
644        "SSH_CONNECT",
645        SocketRequirement::SocketRequired,
646    )? {
647        ServiceTarget::Tcp(addr) => addr,
648        // Unreachable: the shared resolver already bailed; same text.
649        ServiceTarget::Memory => {
650            return Err(no_cli_mapping("SSH_CONNECT", &key.endpoint));
651        }
652    };
653    let runtime = connect_runtime()?;
654    let session = runtime
655        .block_on(connect_session(&addr, &username, &password))
656        .context("SSH_CONNECT failed")?;
657    let crate::runtime::OutboundSession {
658        up_rx,
659        down_tx,
660        exit_status,
661        wire_done,
662        handle,
663        ..
664    } = session;
665    // Client linger: the reply and the exit-status arrive after the
666    // client's own stdin EOF, so never cut the output wait short.
667    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, false);
668    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
669    pump?;
670    // Joined after disconnect: a post-EOF status records before this read.
671    let _ = runtime.block_on(wire_done);
672    let mut map = BTreeMap::new();
673    map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
674    let status = exit_status
675        .lock()
676        .map(|slot| slot.map(i64::from))
677        .unwrap_or(None);
678    map.insert(
679        FIELD_EXIT_STATUS.to_string(),
680        Value::int(status.unwrap_or(-1)),
681    );
682    Ok(Value::map(map))
683}
684
685/// Copy one pipe into another until EOF, then close the target.
686/// Either task placement works, as long as the other end is live.
687///
688#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
689#[example(
690    name = "copy",
691    code = r###"
692    # Closing the source ends the copy: the count proves the bytes moved.
693    IMPORT [STD, SSH]
694    LET $in: PIPE
695    WITH_IO [stdout=$in] ECHO "pump-me"
696    LET $out: PIPE
697    LET $n: INT = SSH_PUMP($in, $out)
698    ASSERT_EQ $n 8
699    WITH_IO [stdin=$out] READ_LINE $got
700    ASSERT_EQ $got "pump-me"
701    "###
702)]
703fn ssh_pump<P: ProcessManager>(
704    cx: &mut StepCtx<P>,
705    /// Source pipe to drain.
706    from_pipe: PipeHandle,
707    /// Target pipe receiving the bytes (closed at EOF).
708    to_pipe: PipeHandle,
709) -> Result<Value> {
710    let from_pipe = Value::pipe_handle(from_pipe);
711    let to_pipe = Value::pipe_handle(to_pipe);
712    let cancel = AtomicBool::new(false);
713    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
714    Ok(Value::int(total))
715}
716
717/// Run `argv` under a local pseudo-terminal and pump it through
718/// explicit pipes until the child exits. Must run inside `ASYNC`.
719/// Returns the INT exit code.
720///
721/// `rows`/`cols` seed the initial size when positive, else the
722/// session's requested size (24x80 default). Outer window-changes
723/// resize live; each session owns its cell.
724///
725/// The code also reports as the wire `exit-status` at child exit, so
726/// stock clients see the real code instead of 255.
727///
728/// Every session opens cleared and homed, like Win32-OpenSSH, so the
729/// child renders onto a known blank screen.
730///
731/// Windows joining follows MSVCRT rules, so CRT programs parse back
732/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
733/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
734/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
735///
736/// Stdin arrives with console line endings handled: the pump expands
737/// a lone `\n` to `\r\n` on Windows, so portable lines submit as-is
738/// and an explicit `\r` passes through untouched. Real terminals
739/// already send CR for Enter.
740///
741/// Environment is exactly the script environment like `RUN`:
742/// block-scoped `ENV` (such as the session's `SSH_USER` / `SSH_CLIENT` /
743/// `SSH_SERVER` / `SSH_COMMAND` relay) reaches the child; host names
744/// arrive only through `INHERIT_ENV`, including `TERM` for terminal
745/// definitions. The working directory comes from the script.
746///
747/// `WITH_IO [tty]` shares the same pump core and covers terminal
748/// runs with host or static sizing and step-local reporting. This
749/// function covers the two session-bound cases a script assembly
750/// cannot reproduce: a rendered run with static geometry observes
751/// the opener but never an outer resize (no script primitive
752/// subscribes a running pty to the session cell), and a failing DSL
753/// `RUN` aborts its task before any script-level status report could
754/// follow (there is no try/catch; the close race after that would be
755/// the second problem). If a second consumer ever needs
756/// session-driven sizing or reaper-ordered reporting, that is the
757/// point to revisit unifying the two.
758///
759#[oxdock_func(
760    returns = TypeTag::Int,
761    summary = "Run a command under a sized local terminal into pipes."
762)]
763#[example(
764    name = "run under a terminal",
765    code = r###"
766    IMPORT [STD, SSH]
767    INHERIT_ENV [PATH]
768    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
769    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
770    LET $cin: PIPE
771    LET $cout: PIPE
772    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
773    WITH_IO [stdout=$cin] ECHO "client-hello"
774    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
775
776    # The client task only proved the session live: cancel it before the
777    # terminal run, so no two pumps share the session.
778    CANCEL $c
779    LET $pin: PIPE
780    LET $pout: PIPE
781    # Assert on the whole pipe: terminal streams carry setup noise ahead
782    # of child output, so line reads are version-dependent.
783    [family:unix] {
784        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
785        LET $code: INT = AWAIT $t
786        ASSERT_EQ $code 0
787        ASSERT_CONTAINS $pout "pty-hi"
788    }
789    [family:windows] {
790        LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
791        LET $code: INT = AWAIT $t
792        ASSERT_EQ $code 0
793        ASSERT_CONTAINS $pout "pty-hi"
794    }
795    SSH_CLOSE($m.server)
796    "###
797)]
798fn ssh_pty_run<P: ProcessManager>(
799    cx: &mut StepCtx<P>,
800    /// Session handle from `SSH_DEQUEUE`.
801    session: SshSessionTag,
802    /// Program and arguments to run.
803    argv: Vec<String>,
804    /// Terminal rows when positive, session size otherwise.
805    rows: i64,
806    /// Terminal columns when positive, session size otherwise.
807    cols: i64,
808    /// Pipe carrying bytes consumed by the child.
809    in_pipe: PipeHandle,
810    /// Pipe carrying bytes produced by the child.
811    out_pipe: PipeHandle,
812) -> Result<Value> {
813    if !cx.is_async_task() {
814        bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
815    }
816    let in_pipe = Value::pipe_handle(in_pipe);
817    let out_pipe = Value::pipe_handle(out_pipe);
818    let initial = if rows > 0 && cols > 0 {
819        crate::state::PtySize::new(rows as u32, cols as u32)
820    } else {
821        session.pty_size()
822    };
823    // Best effort: an unpumped session has no reader. Owned clone:
824    // the reaper runs detached, so the callback must be `'static`.
825    let session_report = session.clone();
826    let report = move |code: u32| {
827        let _ = session_report.send_exit_status(code);
828    };
829    let code = crate::pty::pump_pty_session(
830        cx,
831        &argv,
832        initial,
833        &session.pty_size_handle(),
834        &in_pipe,
835        &out_pipe,
836        Some(std::sync::Arc::new(report)),
837    )?;
838    Ok(Value::int(code))
839}
840
841/// Run `argv` directly (no terminal) and pump it through explicit pipes
842/// until the child exits. Must run inside `ASYNC`. Returns the INT exit
843/// code (-1 when the child died by signal).
844///
845/// Bytes travel untouched: no init sequence, no newline translation, no
846/// setup handshake. This is the binary-safe leg `scp`-style protocols
847/// need; `SSH_PTY_RUN` owns the interactive side instead.
848///
849/// The code reports as the wire `exit-status` at child exit, so stock
850/// clients see the real code instead of 255. Signaled children report
851/// nothing: clients observe the close without a status.
852///
853/// Stdin EOF closes the child's stdin, so stdin-driven children like
854/// `cat` exit on their own. Standard output and error ride separate
855/// pipes: diagnostics must never pollute the byte stream.
856///
857/// Environment is exactly the script environment like `RUN`:
858/// block-scoped `ENV` reaches the child; host names arrive only through
859/// `INHERIT_ENV`. The working directory comes from the script.
860///
861/// Windows joining follows MSVCRT rules, so CRT programs parse back
862/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
863/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
864/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
865#[oxdock_func(
866    returns = TypeTag::Int,
867    summary = "Run a command with piped stdio into explicit pipes."
868)]
869#[example(
870    name = "run with piped stdio",
871    code = r###"
872    IMPORT [STD, SSH]
873    INHERIT_ENV [PATH]
874    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-run", {username: "u", password: "p"})
875    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
876    LET $cin: PIPE
877    LET $cout: PIPE
878    LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-run", "u", "p", $cin, $cout) }
879    WITH_IO [stdout=$cin] ECHO "client-hello"
880    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
881
882    # The client task only proved the session live: cancel it before the
883    # run, so no two pumps share the session.
884    CANCEL $c
885    LET $pin: PIPE
886    LET $pout: PIPE
887    LET $perr: PIPE
888    LET $argv: LIST<STRING> = ["sh", "-c", "echo run-hi"]
889    [family:windows] {
890        $argv = ["cmd", "/c", "echo run-hi"]
891    }
892    LET $t: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
893    LET $code: INT = AWAIT $t
894    ASSERT_EQ $code 0
895    ASSERT_CONTAINS $pout "run-hi"
896    SSH_CLOSE($m.server)
897    "###
898)]
899fn ssh_run<P: ProcessManager>(
900    cx: &mut StepCtx<P>,
901    /// Session handle from `SSH_DEQUEUE`.
902    session: SshSessionTag,
903    /// Program and arguments to run.
904    argv: Vec<String>,
905    /// Pipe carrying bytes consumed by the child on stdin.
906    in_pipe: PipeHandle,
907    /// Pipe carrying bytes produced by the child on stdout.
908    out_pipe: PipeHandle,
909    /// Pipe carrying bytes produced by the child on stderr.
910    err_pipe: PipeHandle,
911) -> Result<Value> {
912    if !cx.is_async_task() {
913        bail!("SSH_RUN requires ASYNC: run it in its own task beside the session pump task");
914    }
915    let in_pipe = Value::pipe_handle(in_pipe);
916    let out_pipe = Value::pipe_handle(out_pipe);
917    let err_pipe = Value::pipe_handle(err_pipe);
918    // Best effort: an unpumped session has no reader. Owned clone:
919    // the reaper runs detached, so the callback must be `'static`.
920    let session_report = session.clone();
921    let report = move |code: u32| {
922        let _ = session_report.send_exit_status(code);
923    };
924    let code = crate::run::pump_run_session(
925        cx,
926        &argv,
927        &in_pipe,
928        &out_pipe,
929        &err_pipe,
930        Some(std::sync::Arc::new(report)),
931    )?;
932    Ok(Value::int(code))
933}
934
935/// Run one argv vector on a remote host over SSH and collect the
936/// result. Stateless by design: every call carries its target,
937/// credentials, and argv, holds no session, and returns one MAP with
938/// `exit`, `stdout`, `stderr`, `truncated`, and `timed_out`. A retry
939/// after a dropped channel repeats the same bytes, so idempotent
940/// commands make retries boring.
941///
942/// The argv never becomes a shell string in script hands: it joins
943/// once here through `shell_words::join`, the same vetted
944/// implementation behind `SHELL_SPLIT_ARGS`/`SHELL_JOIN_ARGS` and the
945/// remote plugins. Quoting `$HOME`, backticks, and redirects arrive as
946/// literal arguments because no layer between the caller and this join
947/// re-parses them.
948///
949/// Output caps apply while reading: past `max_bytes` per stream the
950/// buffers stop growing but the drain continues, so a flood still
951/// learns its exit status and reports `truncated`. A timeout kills
952/// the wait and returns whatever arrived with `timed_out`. `exit` is
953/// -1 when the server never sent a status.
954#[oxdock_func(returns = TypeTag::Map, summary = "Run argv on a remote host over SSH and collect the result.")]
955#[example(
956    name = "exec collects remote output",
957    code = r###"
958    # The server side answers exec with a local run: dequeue the
959    # session, split the joined command back into argv, run it, and
960    # pump the child output into the channel. The exit status rides
961    # the wire through the session report.
962    IMPORT [STD, SSH]
963    INHERIT_ENV [PATH]
964    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exec", {username: "u", password: "p"})
965    LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
966    LET $runner: HANDLE<VOID> = ASYNC {
967        LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
968        LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
969        LET $wire: PIPE
970        LET $drain: PIPE
971        LET $pump: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
972        LET $pin: PIPE
973        LET $pout: PIPE
974        LET $perr: PIPE
975        LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
976        LET $n: INT = SSH_PUMP($pout, $wire)
977        LET $code: INT = AWAIT $run
978        LET $pDone: MAP<ANY> = AWAIT $pump
979        ASSERT_EQ $code 0
980    }
981
982    # One call, one MAP: argv in, collected streams out.
983    [family:unix] {
984        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["echo", "exec-hi"], {})
985        ASSERT_EQ $res.timed_out false
986        ASSERT_EQ $res.exit 0
987        ASSERT_CONTAINS $res.stdout "exec-hi"
988    }
989    [family:windows] {
990        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["cmd", "/c", "echo exec-hi"], {})
991        ASSERT_EQ $res.timed_out false
992        ASSERT_EQ $res.exit 0
993        ASSERT_CONTAINS $res.stdout "exec-hi"
994    }
995    AWAIT $runner
996    SSH_CLOSE($m.server)
997    "###
998)]
999fn ssh_exec<P: ProcessManager>(
1000    cx: &mut StepCtx<P>,
1001    /// Dial target: a service name resolved through runner mappings.
1002    target: String,
1003    /// Inner credentials for the SSH session.
1004    username: String,
1005    /// Inner credentials for the SSH session.
1006    password: String,
1007    /// Program and arguments to run remotely; joined once, by the
1008    /// plugin, with POSIX shell quoting.
1009    argv: Vec<String>,
1010    /// `timeout` DURATION|STRING (default 60s) and `max_bytes` INT
1011    /// (default 8 MiB per stream).
1012    #[options("timeout?: DURATION|STRING", "max_bytes?: INT")]
1013    options: BTreeMap<String, Value>,
1014) -> Result<Value> {
1015    if argv.is_empty() {
1016        bail!("SSH_EXEC needs at least a program");
1017    }
1018    if username.is_empty() {
1019        bail!("SSH_EXEC username must not be empty");
1020    }
1021    let registry = cx
1022        .module_state::<EndpointRegistry>("SSH")
1023        .expect("SSH module registers its endpoint registry as module state");
1024    if registry.is_offline() {
1025        bail!("SSH_EXEC failed: engine running in --offline mode");
1026    }
1027    // Symbolic only: physical shapes already failed in the parser.
1028    let endpoint = parse_virtual_endpoint(&target, "SSH_EXEC")?;
1029    let key = EndpointKey::tcp(endpoint);
1030    let addr = match resolve_service_target(
1031        &registry,
1032        &key,
1033        "SSH_EXEC",
1034        SocketRequirement::SocketRequired,
1035    )? {
1036        ServiceTarget::Tcp(addr) => addr,
1037        // Unreachable: the shared resolver already bailed; same text.
1038        ServiceTarget::Memory => {
1039            return Err(no_cli_mapping("SSH_EXEC", &key.endpoint));
1040        }
1041    };
1042    let timeout = match options.get(OPT_TIMEOUT) {
1043        None => crate::runtime::DEFAULT_EXEC_TIMEOUT,
1044        Some(value) => {
1045            // `check_options` verified `DURATION|STRING`; narrow directly.
1046            let timeout = if let Some(duration) = value.as_duration() {
1047                duration
1048            } else {
1049                let text = value
1050                    .as_str()
1051                    .expect("check_options verified DURATION|STRING");
1052                oxdock_parser::command::parse_duration(text).with_context(|| {
1053                    format!("SSH_EXEC option '{OPT_TIMEOUT}' must be a duration, got {text:?}")
1054                })?
1055            };
1056            if timeout.is_zero() {
1057                bail!("SSH_EXEC option '{OPT_TIMEOUT}' must be positive");
1058            }
1059            timeout
1060        }
1061    };
1062    let max_bytes = match options.get(OPT_MAX_BYTES) {
1063        None => crate::runtime::DEFAULT_EXEC_MAX_BYTES,
1064        Some(value) => {
1065            let bytes = value.as_i64().expect("check_options verified INT");
1066            if bytes <= 0 {
1067                bail!("SSH_EXEC option '{OPT_MAX_BYTES}' must be positive");
1068            }
1069            bytes as usize
1070        }
1071    };
1072    // The single shell encoding in the pipeline: argv becomes one
1073    // string here, and only here.
1074    let command = shell_words::join(&argv).into_bytes();
1075    let runtime = connect_runtime()?;
1076    let outcome = runtime
1077        .block_on(crate::runtime::run_remote_exec(
1078            &addr, &username, &password, command, timeout, max_bytes,
1079        ))
1080        .context("SSH_EXEC failed")?;
1081    let mut map = BTreeMap::new();
1082    map.insert(
1083        FIELD_EXIT.to_string(),
1084        Value::int(outcome.exit.unwrap_or(-1)),
1085    );
1086    map.insert(
1087        "stdout".to_string(),
1088        Value::string(String::from_utf8_lossy(&outcome.stdout).into_owned()),
1089    );
1090    map.insert(
1091        "stderr".to_string(),
1092        Value::string(String::from_utf8_lossy(&outcome.stderr).into_owned()),
1093    );
1094    map.insert(FIELD_TRUNCATED.to_string(), Value::bool(outcome.truncated));
1095    map.insert(FIELD_TIMED_OUT.to_string(), Value::bool(outcome.timed_out));
1096    Ok(Value::map(map))
1097}
1098
1099/// Mint a random server password (256 bits, hex).
1100///
1101/// Each call draws fresh OS-RNG key material and renders 64
1102/// lowercase hex chars, so committed scripts carry no usable
1103/// credential: mint at runtime, hand the value to both sides, drop
1104/// it after. Pure (no step context), so it runs anywhere a STRING
1105/// binds, including option maps and placeholders.
1106#[oxdock_func(pure, returns = TypeTag::String)]
1107#[example(
1108    name = "mint and serve",
1109    code = r###"
1110    IMPORT [STD, SSH]
1111
1112    # Fresh draws mint 64 hex chars with no committed secret.
1113    LET $pass: STRING = SSH_GENERATE_PASSWORD()
1114    LET $len: INT = LEN($pass)
1115    ASSERT_EQ $len 64
1116
1117    # The minted value serves directly as a server password.
1118    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-gen-pass", {username: "u", password: $pass})
1119    SSH_CLOSE($m.server)
1120    "###
1121)]
1122fn ssh_generate_password() -> Result<Value> {
1123    Ok(Value::string(crate::generate_password()))
1124}
1125
1126/// Field table backing the `SSH_SERVE_INFO` schema and return tag.
1127fn serve_result_fields() -> Arc<[Field]> {
1128    Arc::from(vec![
1129        Field {
1130            name: FIELD_SERVER.to_string(),
1131            ty: TypeTag::Custom(SshServerTag::descriptor()),
1132            docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
1133            optional: false,
1134            default: None,
1135        },
1136        Field {
1137            name: FIELD_ADDR.to_string(),
1138            ty: TypeTag::String,
1139            docs: "Bound socket address (`ip:port`) of the server.",
1140            optional: false,
1141            default: None,
1142        },
1143        Field {
1144            name: FIELD_USERNAME.to_string(),
1145            ty: TypeTag::String,
1146            docs: "Configured username.",
1147            optional: false,
1148            default: None,
1149        },
1150        Field {
1151            name: FIELD_PASSWORD.to_string(),
1152            ty: TypeTag::String,
1153            docs: "Configured password.",
1154            optional: false,
1155            default: None,
1156        },
1157        Field {
1158            name: FIELD_VIRTUAL.to_string(),
1159            ty: TypeTag::String,
1160            docs: "Virtual endpoint echo of the claimed slot.",
1161            optional: false,
1162            default: None,
1163        },
1164    ])
1165}
1166
1167/// Field table backing the `SSH_DEQUEUE_INFO` schema and return tag.
1168fn dequeue_result_fields() -> Arc<[Field]> {
1169    Arc::from(vec![
1170        Field {
1171            name: FIELD_SESSION.to_string(),
1172            ty: TypeTag::Custom(SshSessionTag::descriptor()),
1173            docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
1174            optional: false,
1175            default: None,
1176        },
1177        Field {
1178            name: FIELD_COMMAND.to_string(),
1179            ty: TypeTag::String,
1180            docs: "Executed command, empty for shells.",
1181            optional: false,
1182            default: None,
1183        },
1184        Field {
1185            name: FIELD_USERNAME.to_string(),
1186            ty: TypeTag::String,
1187            docs: "Authenticated username, empty when unset.",
1188            optional: false,
1189            default: None,
1190        },
1191        Field {
1192            name: FIELD_ADDR.to_string(),
1193            ty: TypeTag::String,
1194            docs: "Peer address, empty when unset.",
1195            optional: false,
1196            default: None,
1197        },
1198    ])
1199}
1200
1201/// The `SSH` host module: virtual-endpoint server plus client, bridged
1202/// to DSL pipes. Generic over the process manager like every host module.
1203pub fn module_with<P: ProcessManager>() -> HostModule<P> {
1204    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
1205}
1206
1207/// The `SSH` host module resolving through `registry`: the registry
1208/// travels as module state (`HostModule::with_state`) for bodies to
1209/// fetch from `cx`, so every entry stays `#[oxdock_func]`. Everything
1210/// else reaches the same registry through its `SSH_SERVER` handle. A
1211/// pre-run service check rides along: every service the steps name must
1212/// be fully bound before execution starts.
1213pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
1214    let check = registry.pre_run_check("SSH");
1215    HostModule {
1216        name: "SSH".to_string(),
1217        funcs: vec![
1218            SshServe::registration(),
1219            SshAccept::registration(),
1220            SshDequeue::registration(),
1221            SshPumpChannel::registration(),
1222            SshSendExitStatus::registration(),
1223            SshClose::registration(),
1224            SshConnect::registration(),
1225            SshExec::registration(),
1226            SshPump::registration(),
1227            SshPtyRun::registration(),
1228            SshRun::registration(),
1229            SshGeneratePassword::registration(),
1230        ],
1231        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
1232        record_schemas: vec![
1233            RecordSchema {
1234                name: "SSH_SERVE_INFO",
1235                fields: serve_result_fields(),
1236            },
1237            RecordSchema {
1238                name: "SSH_DEQUEUE_INFO",
1239                fields: dequeue_result_fields(),
1240            },
1241        ],
1242        states: Vec::new(),
1243    }
1244    .with_state(registry)
1245    .with_state(Arc::new(check))
1246}