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