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