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