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;
11use std::time::Duration;
12
13use anyhow::{Context, Result, bail};
14use oxdock_core::{
15    Field, FuncKind, FuncMeta, FuncParam, HostModule, HostRegistration, NativeFn, OxDockFn,
16    OxDockType, ParamOption, RecordSchema, StepCtx, TypeTag, Value, check_value_at,
17};
18use oxdock_func_macro::oxdock_func;
19use oxdock_net_plugin::{AcquiredListener, EndpointKey, EndpointRegistry, acquire_listener};
20use oxdock_pipe::PipeHandle;
21use oxdock_process::ProcessManager;
22use russh::keys::{Algorithm, PrivateKey};
23
24use crate::bridge::{pump_pipe_to_pipe, pump_session};
25use crate::keys::load_or_create_host_key;
26use crate::runtime::{connect_runtime, connect_session};
27use crate::state::{
28    CLOSE_JOIN_TIMEOUT, Dequeue, PendingSession, ServerState, SessionQueue, ShutdownSignal,
29};
30use crate::types::{SshServerTag, SshSessionTag};
31use crate::validate::parse_serve_endpoint;
32
33/// Unique server ids per process.
34static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
35
36/// Dequeue tick: shutdown and cancellation surface within a few ticks.
37const DEQUEUE_TICK: Duration = Duration::from_millis(10);
38
39/// Block until the queue yields an authenticated session (or teardown).
40/// Shared by `SSH_DEQUEUE` and the `SSH_ACCEPT` wrapper.
41fn dequeue_session<P: ProcessManager>(
42    cx: &StepCtx<P>,
43    queue: &Arc<SessionQueue>,
44    func: &str,
45) -> Result<PendingSession> {
46    loop {
47        match queue.try_pop() {
48            Dequeue::Session(session) => return Ok(session),
49            Dequeue::Shutdown => bail!("{func}: server is closed"),
50            Dequeue::Empty => {}
51        }
52        match queue.wait_for_session(DEQUEUE_TICK) {
53            Dequeue::Session(session) => return Ok(session),
54            Dequeue::Shutdown => bail!("{func}: server is closed"),
55            Dequeue::Empty => {}
56        }
57        if cx.is_cancelled() {
58            bail!("{func}: task cancelled");
59        }
60    }
61}
62
63/// Dequeue one authenticated session and expose its metadata before any
64/// byte pumping starts, so scripts can route on the requested command or
65/// client identity. Must run inside `ASYNC`. Returns a MAP with
66/// `session` (SSH_SESSION), `command` (STRING, empty for shells),
67/// `username` and `addr` (STRINGs, empty when unknown).
68///
69/// Routing shape: compare the dequeued command against known commands,
70/// build a fresh pipe pair per session, and pump a synthetic reply with
71/// `SSH_PUMP_CHANNEL`. The server sends first: the client side never
72/// EOFs its input, so the reply cannot race teardown. This complete
73/// program runs end to end under the docs conformance suite.
74///
75/// ```oxdock
76/// IMPORT [STD, SSH]
77/// LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-demo", {username: "u", password: "p"})
78///
79/// # Serve: dequeue one session and pump a synthetic reply.
80/// LET $in: PIPE
81/// LET $out: PIPE
82/// LET $w: HANDLE = ASYNC {
83///     LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
84///     ASSERT_CONTAINS $sess "session"
85///     ASSERT_CONTAINS $sess "command"
86///     ASSERT_CONTAINS $sess "username"
87///     ASSERT_CONTAINS $sess "addr"
88///     ASSERT_EQ $sess.username "u"
89///     SSH_PUMP_CHANNEL($sess.session, $in, $out)
90/// }
91///
92/// # Connect a client to the server.
93/// LET $cin: PIPE
94/// LET $cout: PIPE
95/// LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-demo", "u", "p", $cin, $cout) }
96///
97/// # Greet through the server pipe and wait for delivery.
98/// WITH_IO [stdout=$in] ECHO "server-greeting"
99/// LET $info: MAP<ANY> = INSPECT($cout)
100/// LET $empty: BOOL = $info.buffer_bytes == 0
101/// WHILE $empty {
102///     SLEEP 100ms
103///     $info = INSPECT($cout)
104///     $empty = $info.buffer_bytes == 0
105/// }
106/// ASSERT_CONTAINS $cout "server-greeting"
107///
108/// # Shut everything down.
109/// AWAIT $w
110/// CANCEL $c
111/// SSH_CLOSE($m.server)
112/// ```
113///
114#[oxdock_func(
115    returns = TypeTag::Record(dequeue_result_fields()),
116    summary = "Dequeue one SSH session with its metadata."
117)]
118fn ssh_dequeue<P: ProcessManager>(
119    cx: &mut StepCtx<P>,
120    /// Server handle from `SSH_SERVE`.
121    server: SshServerTag,
122) -> Result<Value> {
123    if !cx.is_async_task() {
124        bail!(
125            "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_DEQUEUE($server.server) }}"
126        );
127    }
128    let state = Arc::clone(server.state());
129    let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
130    let command = session.exec_command.clone().unwrap_or_default();
131    let username = session.username.clone().unwrap_or_default();
132    let addr = session
133        .peer_addr
134        .map(|addr| addr.to_string())
135        .unwrap_or_default();
136    let tag = SshSessionTag::new(
137        session.exec_command,
138        session.username,
139        session.peer_addr,
140        session.pty_size,
141        session.up_rx,
142        session.down_tx,
143    );
144    let mut map = BTreeMap::new();
145    map.insert(
146        "session".to_string(),
147        Value::mint_heap(SshSessionTag::descriptor(), tag),
148    );
149    map.insert("command".to_string(), Value::string(command));
150    map.insert("username".to_string(), Value::string(username));
151    map.insert("addr".to_string(), Value::string(addr));
152    Ok(Value::map(map))
153}
154
155/// Spin up an SSH server on a virtual service endpoint with the given
156/// credentials. `bind` is a logical port (`"2251"`) or service name:
157/// physical binds in-script are rejected, `0` is reserved for the CLI
158/// outer mapping. `options` is a MAP with required `username`/`password`
159/// STRINGs (a server without credentials is meaningless, so blanks bail)
160/// and the optional `key_path` STRING (workspace-relative OpenSSH Ed25519
161/// file, load-or-create; a leading `/` anchors to the workspace root like
162/// WRITE, and escapes still bail; absent or blank keeps the ephemeral
163/// in-memory key).
164/// SERVE options, shared by the registration metadata and the runtime
165/// key check: one source for the keys scripts may pass, so
166/// documentation and enforcement cannot drift apart.
167static SSH_SERVE_OPTIONS: &[ParamOption] = &[
168    ParamOption {
169        name: "username",
170        value: TypeTag::String,
171        required: true,
172        default: None,
173    },
174    ParamOption {
175        name: "password",
176        value: TypeTag::String,
177        required: true,
178        default: None,
179    },
180    ParamOption {
181        name: "key_path",
182        value: TypeTag::String,
183        required: false,
184        default: None,
185    },
186];
187
188/// Non-blocking: returns a MAP with `server` (SSH_SERVER),
189/// `addr` (STRING: the physical bind, or the virtual endpoint echo when
190/// socketless), `username` and `password` (STRINGs), and `virtual`
191/// (STRING echo). Memory services bail: SSH needs a TCP socket, so map
192/// the name with `-p`/`--listen`.
193fn ssh_serve<P: ProcessManager>(
194    cx: &mut StepCtx<P>,
195    registry: &Arc<EndpointRegistry>,
196    bind: String,
197    options: BTreeMap<String, Value>,
198) -> Result<Value> {
199    let map = &options;
200    oxdock_core::check_options(map, SSH_SERVE_OPTIONS, "SSH_SERVE")?;
201    // Compositional reads: one shape check per key, then direct
202    // narrowing. Missing and blank stay domain errors: a server
203    // without credentials is meaningless, so there is no default.
204    let username = match map.get("username") {
205        Some(value) => {
206            check_value_at(&TypeTag::String, value, "SSH_SERVE option 'username'")?;
207            let text = value.as_str().expect("check_value_at verified STRING");
208            if text.trim().is_empty() {
209                bail!("SSH_SERVE option 'username' must not be empty");
210            }
211            text.to_string()
212        }
213        None => bail!("SSH_SERVE option 'username' is required"),
214    };
215    let password = match map.get("password") {
216        Some(value) => {
217            check_value_at(&TypeTag::String, value, "SSH_SERVE option 'password'")?;
218            let text = value.as_str().expect("check_value_at verified STRING");
219            if text.trim().is_empty() {
220                bail!("SSH_SERVE option 'password' must not be empty");
221            }
222            text.to_string()
223        }
224        None => bail!("SSH_SERVE option 'password' is required"),
225    };
226    let key_path = match map.get("key_path") {
227        Some(value) => {
228            check_value_at(&TypeTag::String, value, "SSH_SERVE option 'key_path'")?;
229            let text = value.as_str().expect("check_value_at verified STRING");
230            if text.trim().is_empty() {
231                None
232            } else {
233                Some(text.to_string())
234            }
235        }
236        None => None,
237    };
238    let endpoint = parse_serve_endpoint(&bind)?;
239    let key = EndpointKey::tcp(endpoint);
240    let (acquired, registry) = acquire_listener(registry, &key, "SSH_SERVE")?;
241    let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
242        Some(key) => key,
243        None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
244            .context("generate ephemeral Ed25519 host key")?,
245    };
246    let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
247    let id = format!("ssh-{pid}-{id}", pid = std::process::id());
248    let queue = Arc::new(SessionQueue::new());
249    let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
250    let (local_addr, addr_text, thread) = match acquired {
251        AcquiredListener::Tcp { listener, addr } => {
252            // The slot keeps the shared backlog socket; the runtime owns
253            // its own clone.
254            let owned = listener
255                .try_clone()
256                .context("SSH_SERVE cannot clone its listener")?;
257            let thread_queue = Arc::clone(&queue);
258            let thread_user = username.clone();
259            let thread_pass = password.clone();
260            let thread = std::thread::Builder::new()
261                .name(id.clone())
262                .spawn(move || {
263                    crate::runtime::serve(
264                        owned,
265                        host_key,
266                        thread_user,
267                        thread_pass,
268                        thread_queue,
269                        shutdown_rx,
270                    )
271                })
272                .context("SSH_SERVE cannot spawn the server thread")?;
273            (addr, addr.to_string(), Some(thread))
274        }
275        AcquiredListener::Memory => {
276            drop(shutdown_rx);
277            bail!(
278                "SSH_SERVE: '{key}' is a memory service (SSH needs a TCP socket; map it with -p/--listen)"
279            )
280        }
281        AcquiredListener::Offline => {
282            // Socketless servers spawn no thread: DEQUEUE waits on the
283            // queue until close (test drivers push sessions via the
284            // queue). Dropping the receiver makes later shutdown sends a
285            // silent no-op.
286            drop(shutdown_rx);
287            (
288                std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
289                key.endpoint.to_string(),
290                None,
291            )
292        }
293    };
294    let state = Arc::new(ServerState::new(crate::state::ServerConfig {
295        id,
296        local_addr,
297        addr_text: addr_text.clone(),
298        queue,
299        shutdown_tx,
300        thread,
301        registry: Arc::clone(&registry),
302        endpoint: key.clone(),
303    }));
304    let mut map = BTreeMap::new();
305    map.insert(
306        "server".to_string(),
307        Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
308    );
309    map.insert("addr".to_string(), Value::string(addr_text));
310    map.insert("username".to_string(), Value::string(username));
311    map.insert("password".to_string(), Value::string(password));
312    map.insert(
313        "virtual".to_string(),
314        Value::string(key.endpoint.to_string()),
315    );
316    Ok(Value::map(map))
317}
318
319/// Accept the next authenticated session and pump it through explicit
320/// pipes until the channel closes. Must run inside `ASYNC`. Returns a
321/// MAP with `closed` (BOOL) and `command` (STRING, empty for shells).
322/// Thin wrapper over `SSH_DEQUEUE` + `SSH_PUMP_CHANNEL` for worker loops
323/// that need no pre-pump inspection; use those directly to route on
324/// session metadata first. Returns a MAP with `closed` (BOOL) and
325/// `command` (STRING, empty for shells); the example below asserts both
326/// keys on the awaited result. The server sends first: the client side
327/// never EOFs its input, so the reply cannot race teardown. This
328/// complete program runs end to end under the docs conformance suite.
329///
330/// ```oxdock
331/// IMPORT [STD, SSH]
332/// LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-demo", {username: "u", password: "p"})
333///
334/// # Accept one session into fresh pipes.
335/// LET $in: PIPE
336/// LET $out: PIPE
337/// LET $acc: HANDLE = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
338///
339/// # Connect a client to the server.
340/// LET $cin: PIPE
341/// LET $cout: PIPE
342/// LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-demo", "u", "p", $cin, $cout) }
343///
344/// # Greet through the server pipe and wait for delivery.
345/// WITH_IO [stdout=$in] ECHO "server-greeting"
346/// LET $info: MAP<ANY> = INSPECT($cout)
347/// LET $empty: BOOL = $info.buffer_bytes == 0
348/// WHILE $empty {
349///     SLEEP 100ms
350///     $info = INSPECT($cout)
351///     $empty = $info.buffer_bytes == 0
352/// }
353/// ASSERT_CONTAINS $cout "server-greeting"
354///
355/// # The awaited result carries both keys; then shut down.
356/// LET $done: MAP<ANY> = AWAIT $acc
357/// ASSERT_EQ $done.closed true
358/// ASSERT_CONTAINS $done "command"
359/// CANCEL $c
360/// SSH_CLOSE($m.server)
361/// ```
362///
363#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
364    name: "closed".to_string(),
365    ty: TypeTag::Bool,
366    docs: "True when the session closed cleanly.",
367    optional: false,
368}, Field {
369    name: "command".to_string(),
370    ty: TypeTag::String,
371    docs: "Executed command, empty for shells.",
372    optional: false,
373}])), summary = "Accept one SSH session into pipes.")]
374fn ssh_accept<P: ProcessManager>(
375    cx: &mut StepCtx<P>,
376    /// Server handle from `SSH_SERVE`.
377    server: SshServerTag,
378    /// Pipe carrying bytes consumed by the wire side.
379    in_pipe: PipeHandle,
380    /// Pipe carrying bytes produced by the wire side.
381    out_pipe: PipeHandle,
382) -> Result<Value> {
383    if !cx.is_async_task() {
384        bail!(
385            "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
386        );
387    }
388    // Downstream pumps take `&Value`: re-wrap the extracted handles so
389    // every helper below keeps its Value-based shape.
390    let in_pipe = Value::pipe_handle(in_pipe);
391    let out_pipe = Value::pipe_handle(out_pipe);
392    let state = Arc::clone(server.state());
393    let cancel = AtomicBool::new(false);
394    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
395    pump_session(
396        cx,
397        &in_pipe,
398        &out_pipe,
399        session.up_rx,
400        session.down_tx,
401        &cancel,
402    )?;
403    let mut map = BTreeMap::new();
404    map.insert("closed".to_string(), Value::bool(true));
405    map.insert(
406        "command".to_string(),
407        Value::string(session.exec_command.unwrap_or_default()),
408    );
409    Ok(Value::map(map))
410}
411
412/// Pump a dequeued session between explicit DSL pipes until the channel
413/// closes. Must run inside `ASYNC`. The session ends are take-once: a
414/// second pump on the same session bails instead of splitting bytes.
415/// Returns a MAP with `closed` (BOOL).
416///
417#[oxdock_func(
418    returns = TypeTag::Record(std::sync::Arc::from([Field {
419        name: "closed".to_string(),
420        ty: TypeTag::Bool,
421        docs: "True when the session closed cleanly.",
422        optional: false,
423    }])),
424    summary = "Pump a dequeued SSH session through pipes."
425)]
426fn ssh_pump_channel<P: ProcessManager>(
427    cx: &mut StepCtx<P>,
428    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
429    session: SshSessionTag,
430    /// Pipe carrying bytes consumed by the wire side.
431    in_pipe: PipeHandle,
432    /// Pipe carrying bytes produced by the wire side.
433    out_pipe: PipeHandle,
434) -> Result<Value> {
435    if !cx.is_async_task() {
436        bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
437    }
438    // Downstream pumps take `&Value`: re-wrap the extracted handles so
439    // every helper below keeps its Value-based shape.
440    let in_pipe = Value::pipe_handle(in_pipe);
441    let out_pipe = Value::pipe_handle(out_pipe);
442    let (up_rx, down_tx) = session.take_pump_ends()?;
443    let cancel = AtomicBool::new(false);
444    pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel)?;
445    let mut map = BTreeMap::new();
446    map.insert("closed".to_string(), Value::bool(true));
447    Ok(Value::map(map))
448}
449
450/// Shut a server down and join its runtime thread (bounded). Idempotent:
451/// returns BOOL true when no thread remains.
452///
453#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
454fn ssh_close<P: ProcessManager>(
455    cx: &mut StepCtx<P>,
456    /// Server handle from `SSH_SERVE`.
457    server: SshServerTag,
458) -> Result<Value> {
459    let _ = cx;
460    let state = Arc::clone(server.state());
461    state.request_shutdown();
462    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
463}
464
465/// Connect to an SSH server with distinct inner credentials and pump the
466/// shell channel through explicit pipes until it closes. Must run inside
467/// `ASYNC`, concurrently with the `SSH_PUMP` tasks (never before them).
468/// `target` is a logical port (`"2251"`: CLI-mapped address or loopback
469/// default), a service name (CLI-mapped address only; unmapped names are
470/// memory services and SSH needs TCP), a served address (`$m.addr`), or
471/// a `host:port` dial. Under `--offline` the dial bails before any DNS
472/// or socket work. Returns a MAP with `closed` (BOOL).
473fn ssh_connect<P: ProcessManager>(
474    cx: &mut StepCtx<P>,
475    registry: &Arc<EndpointRegistry>,
476    target: String,
477    username: String,
478    password: String,
479    in_pipe: Value,
480    out_pipe: Value,
481) -> Result<Value> {
482    if !cx.is_async_task() {
483        bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
484    }
485    // Sandbox gate first: offline runs open no OS sockets.
486    if registry.is_offline() {
487        bail!("SSH_CONNECT failed: engine running in --offline mode");
488    }
489    if username.is_empty() {
490        bail!("SSH_CONNECT username must not be empty");
491    }
492    let addr = crate::validate::resolve_connect_addr(registry, &target)?;
493    let runtime = connect_runtime()?;
494    let session = runtime
495        .block_on(connect_session(&addr, &username, &password))
496        .context("SSH_CONNECT failed")?;
497    let crate::runtime::OutboundSession {
498        up_rx,
499        down_tx,
500        handle,
501        ..
502    } = session;
503    let cancel = AtomicBool::new(false);
504    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel);
505    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
506    pump?;
507    let mut map = BTreeMap::new();
508    map.insert("closed".to_string(), Value::bool(true));
509    Ok(Value::map(map))
510}
511
512/// Copy one pipe into another until EOF, then close the target.
513/// Returns the INT byte count. Either task placement works, as long as
514/// the other end is live (usually an `ASYNC` task).
515///
516#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
517fn ssh_pump<P: ProcessManager>(
518    cx: &mut StepCtx<P>,
519    /// Source pipe to drain.
520    from_pipe: PipeHandle,
521    /// Target pipe receiving the bytes (closed at EOF).
522    to_pipe: PipeHandle,
523) -> Result<Value> {
524    // `pump_pipe_to_pipe` takes `&Value`: re-wrap the extracted
525    // handles so the bridge keeps its Value-based shape.
526    let from_pipe = Value::pipe_handle(from_pipe);
527    let to_pipe = Value::pipe_handle(to_pipe);
528    let cancel = AtomicBool::new(false);
529    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
530    Ok(Value::int(total))
531}
532
533/// Run `argv` under a local pseudo-terminal sized from the dequeued
534/// session and pump it through explicit pipes until the child exits.
535/// `rows`/`cols` seed the initial size when positive; non-positive falls
536/// back to the session's requested size (the outer pty request, 24x80
537/// default). Outer window-change requests resize this session's terminal
538/// live; every session owns its size cell, so concurrent guests never
539/// observe each other. Must run inside `ASYNC`. Returns the INT exit
540/// code. Environment is inherited from the host process and layered with
541/// the script environment like `RUN`: block-scoped `ENV` (such as the
542/// session's `SSH_USER` / `SSH_CLIENT` / `SSH_SERVER` / `SSH_COMMAND`
543/// relay) reaches the child; the working directory comes from the script.
544///
545#[oxdock_func(
546    returns = TypeTag::Int,
547    summary = "Run a command under a sized local terminal into pipes."
548)]
549fn ssh_pty_run<P: ProcessManager>(
550    cx: &mut StepCtx<P>,
551    /// Session handle from `SSH_DEQUEUE`.
552    session: SshSessionTag,
553    /// Program and arguments to run.
554    argv: Vec<String>,
555    /// Terminal rows when positive, session size otherwise.
556    rows: i64,
557    /// Terminal columns when positive, session size otherwise.
558    cols: i64,
559    /// Pipe carrying bytes consumed by the child.
560    in_pipe: PipeHandle,
561    /// Pipe carrying bytes produced by the child.
562    out_pipe: PipeHandle,
563) -> Result<Value> {
564    if !cx.is_async_task() {
565        bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
566    }
567    // `pump_pty_session` takes `&Value` pipes: re-wrap the extracted
568    // handles so the bridge keeps its Value-based shape.
569    let in_pipe = Value::pipe_handle(in_pipe);
570    let out_pipe = Value::pipe_handle(out_pipe);
571    let initial = if rows > 0 && cols > 0 {
572        crate::state::PtySize::new(rows as u32, cols as u32)
573    } else {
574        session.pty_size()
575    };
576    let cancel = AtomicBool::new(false);
577    let code = crate::pty::pump_pty_session(
578        cx,
579        &argv,
580        initial,
581        &session.pty_size_handle(),
582        &in_pipe,
583        &out_pipe,
584        &cancel,
585    )?;
586    Ok(Value::int(code))
587}
588
589/// Field table for the `SSH_SERVE` result bundle, backing the
590/// `SSH_SERVE_INFO` schema and the `SSH_SERVE` return tag: one source
591/// for the shape the host mints, so introspection, enforcement, and
592/// documentation cannot drift apart.
593fn serve_result_fields() -> Arc<[Field]> {
594    Arc::from(vec![
595        Field {
596            name: "server".to_string(),
597            ty: TypeTag::Custom(SshServerTag::descriptor()),
598            docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
599            optional: false,
600        },
601        Field {
602            name: "addr".to_string(),
603            ty: TypeTag::String,
604            docs: "Bound socket address (`ip:port`) of the server.",
605            optional: false,
606        },
607        Field {
608            name: "username".to_string(),
609            ty: TypeTag::String,
610            docs: "Configured username.",
611            optional: false,
612        },
613        Field {
614            name: "password".to_string(),
615            ty: TypeTag::String,
616            docs: "Configured password.",
617            optional: false,
618        },
619        Field {
620            name: "virtual".to_string(),
621            ty: TypeTag::String,
622            docs: "Virtual endpoint echo of the claimed slot.",
623            optional: false,
624        },
625    ])
626}
627
628/// Field table for the `SSH_DEQUEUE` result bundle, backing the
629/// `SSH_DEQUEUE_INFO` schema and the `SSH_DEQUEUE` return tag.
630fn dequeue_result_fields() -> Arc<[Field]> {
631    Arc::from(vec![
632        Field {
633            name: "session".to_string(),
634            ty: TypeTag::Custom(SshSessionTag::descriptor()),
635            docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
636            optional: false,
637        },
638        Field {
639            name: "command".to_string(),
640            ty: TypeTag::String,
641            docs: "Executed command, empty for shells.",
642            optional: false,
643        },
644        Field {
645            name: "username".to_string(),
646            ty: TypeTag::String,
647            docs: "Authenticated username, empty when unset.",
648            optional: false,
649        },
650        Field {
651            name: "addr".to_string(),
652            ty: TypeTag::String,
653            docs: "Peer address, empty when unset.",
654            optional: false,
655        },
656    ])
657}
658
659/// The `SSH` host module: virtual-endpoint server plus client, bridged
660/// to DSL pipes. Generic over the process manager like every host module.
661pub fn module_with<P: ProcessManager>() -> HostModule<P> {
662    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
663}
664
665/// The `SSH` host module resolving through `registry`: `SSH_SERVE` and
666/// `SSH_CONNECT` close over it (hand-built entries; the `#[oxdock_func]`
667/// macro only generates closers-over-nothing). Everything else reaches
668/// the same registry through its `SSH_SERVER` handle.
669pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
670    HostModule {
671        name: "SSH".to_string(),
672        funcs: vec![
673            ssh_serve_registration(Arc::clone(&registry)),
674            SshAccept::registration(),
675            SshDequeue::registration(),
676            SshPumpChannel::registration(),
677            SshClose::registration(),
678            ssh_connect_registration(registry),
679            SshPump::registration(),
680            SshPtyRun::registration(),
681        ],
682        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
683        record_schemas: vec![
684            RecordSchema {
685                name: "SSH_SERVE_INFO",
686                fields: serve_result_fields(),
687            },
688            RecordSchema {
689                name: "SSH_DEQUEUE_INFO",
690                fields: dequeue_result_fields(),
691            },
692        ],
693    }
694}
695
696/// Hand-built `SSH_SERVE` entry: same shape the macro would emit (arity
697/// check, `STRING`/`Value` unpacking, metadata), plus the captured
698/// registry threaded into [`ssh_serve`].
699fn ssh_serve_registration<P: ProcessManager>(
700    registry: Arc<EndpointRegistry>,
701) -> HostRegistration<P> {
702    // One params vector feeds both the metadata and the arity check,
703    // so the two can never disagree: add a parameter once, here.
704    let params = vec![
705        FuncParam {
706            name: "bind".to_string(),
707            param_type: Some(TypeTag::String),
708            allowed: None,
709            docs: "Virtual service endpoint to serve (logical port or service name).",
710            options: None,
711            optional: false,
712        },
713        FuncParam {
714            name: "options".to_string(),
715            param_type: Some(TypeTag::Map),
716            allowed: None,
717            docs: "Server credentials and host key.",
718            options: Some(SSH_SERVE_OPTIONS),
719            optional: false,
720        },
721    ];
722    let arity = params.len();
723    let func: NativeFn<P> = Arc::new(move |cx, values| {
724        if values.len() != arity {
725            bail!(
726                "SSH_SERVE() expects {arity} argument(s), got {}",
727                values.len()
728            );
729        }
730        let mut values = values.into_iter();
731        let bind = match values.next().expect("arity checked above").as_str() {
732            Some(s) => s.to_string(),
733            None => bail!("SSH_SERVE() argument `$bind` must be a STRING"),
734        };
735        let options_value = values.next().expect("arity checked above");
736        let options = match options_value.as_map() {
737            Some(map) => map.clone(),
738            None => bail!(
739                "SSH_SERVE() argument `$options` must be a MAP, got {}",
740                options_value.type_name()
741            ),
742        };
743        ssh_serve(cx, &registry, bind, options)
744    });
745    HostRegistration::Stateful {
746        name: "SSH_SERVE".to_string(),
747        meta: FuncMeta {
748            name: "SSH_SERVE".to_string(),
749            // Assigned at registration, like the macro's markers.
750            module: String::new(),
751            kind: FuncKind::HostCtx,
752            params: Some(params),
753            returns: Some(TypeTag::Record(serve_result_fields())),
754            rpn: false,
755            summary: "Serve SSH on a virtual service endpoint.",
756            docs: "Serve SSH on a virtual service endpoint.",
757        },
758        func,
759    }
760}
761
762/// Hand-built `SSH_CONNECT` entry: same shape the macro would emit, plus
763/// the captured registry threaded into [`ssh_connect`].
764fn ssh_connect_registration<P: ProcessManager>(
765    registry: Arc<EndpointRegistry>,
766) -> HostRegistration<P> {
767    // One params vector feeds both the metadata and the arity check,
768    // so the two can never disagree: add a parameter once, here.
769    let params = vec![
770        FuncParam {
771            name: "target".to_string(),
772            param_type: Some(TypeTag::String),
773            allowed: None,
774            docs: "Dial target: logical port, service name, served address, or `host:port`.",
775            options: None,
776            optional: false,
777        },
778        FuncParam {
779            name: "username".to_string(),
780            param_type: Some(TypeTag::String),
781            allowed: None,
782            docs: "Inner credentials for the SSH session.",
783            options: None,
784            optional: false,
785        },
786        FuncParam {
787            name: "password".to_string(),
788            param_type: Some(TypeTag::String),
789            allowed: None,
790            docs: "Inner credentials for the SSH session.",
791            options: None,
792            optional: false,
793        },
794        FuncParam {
795            name: "in_pipe".to_string(),
796            param_type: Some(TypeTag::Pipe),
797            allowed: None,
798            docs: "Pipe carrying bytes consumed by the wire side.",
799            options: None,
800            optional: false,
801        },
802        FuncParam {
803            name: "out_pipe".to_string(),
804            param_type: Some(TypeTag::Pipe),
805            allowed: None,
806            docs: "Pipe carrying bytes produced by the wire side.",
807            options: None,
808            optional: false,
809        },
810    ];
811    let arity = params.len();
812    let func: NativeFn<P> = Arc::new(move |cx, values| {
813        if values.len() != arity {
814            bail!(
815                "SSH_CONNECT() expects {arity} argument(s), got {}",
816                values.len()
817            );
818        }
819        let mut values = values.into_iter();
820        let target = match values.next().expect("arity checked above").as_str() {
821            Some(s) => s.to_string(),
822            None => bail!("SSH_CONNECT() argument `$target` must be a STRING"),
823        };
824        let username = match values.next().expect("arity checked above").as_str() {
825            Some(s) => s.to_string(),
826            None => bail!("SSH_CONNECT() argument `$username` must be a STRING"),
827        };
828        let password = match values.next().expect("arity checked above").as_str() {
829            Some(s) => s.to_string(),
830            None => bail!("SSH_CONNECT() argument `$password` must be a STRING"),
831        };
832        let in_pipe = values.next().expect("arity checked above");
833        if in_pipe.as_pipe_handle().is_none() {
834            bail!(
835                "SSH_CONNECT() argument `$in_pipe` must be a PIPE, got {}",
836                in_pipe.type_name()
837            );
838        }
839        let out_pipe = values.next().expect("arity checked above");
840        if out_pipe.as_pipe_handle().is_none() {
841            bail!(
842                "SSH_CONNECT() argument `$out_pipe` must be a PIPE, got {}",
843                out_pipe.type_name()
844            );
845        }
846        ssh_connect(cx, &registry, target, username, password, in_pipe, out_pipe)
847    });
848    HostRegistration::Stateful {
849        name: "SSH_CONNECT".to_string(),
850        meta: FuncMeta {
851            name: "SSH_CONNECT".to_string(),
852            // Assigned at registration, like the macro's markers.
853            module: String::new(),
854            kind: FuncKind::HostCtx,
855            params: Some(params),
856            returns: Some(TypeTag::Map),
857            rpn: false,
858            summary: "Open an SSH client session into pipes.",
859            docs: "Open an SSH client session into pipes. Target shapes: a logical port (CLI-mapped address or loopback default), a service name (CLI-mapped address only), a served address, or a host:port dial.",
860        },
861        func,
862    }
863}