@inkeep/impulse-ssh
v0.2.0
Published
One SSH policy over system OpenSSH, as an Effect service: trust resolved once into an owned known_hosts, exec and copy with both sides' digests, a consumer kit's ssh_config resolved into a target, argv for other languages, an Include-able or standalone ss
Keywords
Readme
@inkeep/impulse-ssh
One SSH policy for the repository, applied through system OpenSSH (ssh, scp, ssh-keygen, ssh-keyscan). It is
an Effect 4.1.2 service, Ssh, and reimplements no part of SSH. It is the default implementation of the outside
terminal capability (O12); the slot interface for other realizations is written in PSP's O12 spec when a second one
is built (campaign question Q7).
The design is campaign row M12's note, revision 2:
programs/cua-spaces-addon/campaign-notes/M12-ssh-library.md.
Install
The package is public on npm. Install it with its two peers, any 4.1.x patch from 4.1.2; its process layer,
@inkeep/impulse-owned-process, comes with it as a dependency:
npm install @inkeep/impulse-ssh [email protected] @effect/[email protected]
pnpm add @inkeep/impulse-ssh [email protected] @effect/[email protected]- It is ESM with TypeScript declarations. A consumer typechecks it under TypeScript 5.9 or later with
strict, aseffectrequires. Version 0.1.0's pack, installed with owned-process 0.1.0's, imported and typechecked (skipLibCheck: false) with npm under TypeScript 5.9.3 and pnpm under TypeScript 7.0.2 on 2026-10-23. No later version's pack has been through that consumer check. - From 0.2.0 its peers are
~4.1.2: a consumer oneffect4.0.x is refused, and one on a later 4.1.x patch is accepted. Its suite passed witheffect,@effect/platform-nodeand@effect/vitestat 4.1.2 and at 4.1.4, on Ubuntu with a realsshd(2026-11-03 and 2026-11-16). - It depends on owned-process at a patch range of the version it was packed with, so npm installs one copy of owned-process for a consumer that also depends on it.
- It declares no
enginesfield. It needs Node 26.10.0 or later: owned-process refuses its new-group path withSpawnFailed/ENOSYSbelow 26.10.0. Its tests passed on Node 26.10.0 on macOS arm64, and the nightly runs them on 26.12.1, the repository's pin. - pnpm 11 and later install no version published less than a day ago (
minimumReleaseAge, 1440 minutes by default). To take a release on its first day, list the package, andeffector@effect/*if they are as new, underminimumReleaseAgeExclude. npm waits only when you set itsmin-release-age. - It runs system OpenSSH on the machine that imports it (Preconditions, below).
- Inside this repository, a member depends on it with
"@inkeep/impulse-ssh": "workspace:*"instead.
Use
import * as NodeServices from "@effect/platform-node/NodeServices"
import { Effect, Layer, Schema } from "effect"
import { AbsolutePath, Ssh, SshTarget } from "@inkeep/impulse-ssh"
const program = Effect.gen(function* () {
const ssh = yield* Ssh
const target = yield* Schema.decodeUnknownEffect(SshTarget)(config)
const prepared = yield* ssh.prepare(target, AbsolutePath.make("/home/me/.config/run"))
const result = yield* ssh.exec(prepared, { command: "uname -a", deadline: "30 seconds" })
return result.exitCode
})
program.pipe(Effect.provide(Ssh.layer.pipe(Layer.provide(NodeServices.layer))))A consumer kit's ssh_config becomes a target the same way:
const resolved = yield* ssh.resolve({ configFile, alias: SshAlias.make("o6-h1") })
const prepared = yield* ssh.prepare(yield* resolvedTarget(resolved), runDirectory)effect and @effect/platform-node are peer dependencies at ~4.1.2, any 4.1.x patch from 4.1.2, so a tree holds one
copy of each.
Operations
prepare(target, directory)resolves host-key trust once into an ownedknown_hostsand returns aPreparedTargetwith a trust receipt. Every other operation takes aPreparedTarget, so none runs on unresolved trust.resolve({ configFile, alias })runsssh -F <file> -G -- <alias>and returns what OpenSSH resolved: host name, port, user, identity files, userknown_hostsfiles,HostKeyAlias, strict checking,ServerAliveand any proxy. It gives a receipt the host identity OpenSSH will use.resolvedTarget(resolved)turns that into anSshTargetwithKnownHostsFiletrust, carrying the file'sHostKeyAliasand keepalive (OpenSSH's default of no keepalive becomes the library's 5/2), or fails withConfigNotResolvednaming each key the library cannot carry: anything but one absolute identity file, more than one or a relativeknown_hostsfile, strict checking other thanyes, a proxy, or a value the target's schema refuses. Operations then run under the library's own policy, never the file's.exec(target, request)runs a remote command beforedeadline. The exit code is a value.stdintakes bytes or a stream, fed with backpressure (225 MiB measured, below). A clean source ends stdin so the child sees EOF; a failed source stops the group without presenting truncated input as complete and returns the source's error.stdoutis anOutput:capture(n, "terminate")by default withn1 MiB,forward(sink)to stream every byte to the caller uncapped,forward(sink, { limitBytes: n })to cap a forward, orignore. stderr is the library's: the last 64 KiB, which classification reads.copy(target, request)is anscpupload or download beforedeadline. After the transfer it reads both sides' bytes and sha256 (the remote withsha256sumover the same policy) and returns one receipt withlocal { path, bytes, sha256 }andremote { path, bytes, sha256 }. When they differ it fails withCopyMismatch, naming both.argv(target, request)returns the exact argv and environmentexecorcopywould run, for callers in other languages.writeStanza,checkStanza,renderShimhandle theHostblock. It is written once (mode 0600, never overwritten), and installed withIncludein a user's configuration or passed with-F(O6's consumer kits).checkStanzaresolves the alias withssh -G, through the user's configuration or the given file, and names every pinned key that resolved differently.renderShimrenders a PATH shim that sends the alias, and only the alias, through the-Ffile, for clients such as Docker and git that startsshthemselves.generateIdentity(directory, comment)makes a per-run Ed25519 key and returns its public key and fingerprint.leaseCarrier,tetherCarrier,observeCarrier,closeCarriermanage port forwards held by a separate owner process; see Carriers.
Every failure is one SshError with an operation and a tagged reason: HostKeyRejected, Unreachable,
ConnectionLost, AuthRefused, ForwardRefused, SftpUnavailable, ConfigNotResolved, CopyMismatch, Timeout,
OutputLimit, Terminated (with the signal's name), SshFailed, CarrierIdentityMismatch, CarrierEnded,
LifetimeRejected, LocalFileRefused or SpawnFailed (with the spawn's errno code when there was one). Recover one
with Effect.catchReason("SshError", "<reason>", ...). An SshError never carries the command, stdout or stderr.
How an exit of 255 is read
OpenSSH and a remote command both use exit 255, so only OpenSSH's own lines become reasons, read from the last line of
stderr that matches one of them (src/classify.ts); anything else is the exit code, returned as a value.
exec and copy are never retried or replayed by this package. ConnectionLost, Timeout, Terminated and
OutputLimit mean the command may have run, so its remote outcome is unknown to the caller.
Unreachable, so the command never ran:ssh: connect to host … port …: …,ssh: Could not resolve hostname …,Connection timed out during banner exchange,kex_exchange_identification: …,Connection to … port N timed out.ConnectionLost, so the session may have started and the command may have run:Connection closed by … port N,Connection reset by … port N,Connection to … closed by remote host.,Read from remote host …: …,client_loop: send disconnect: …,Timeout, server … not responding.,banner exchange: Connection to … port N: Broken pipe.HostKeyRejected:Host key verification failed.AuthRefused:user@host: Permission denied (…).ForwardRefused:Error: remote port forwarding failed for listen port …(orpath),bind […]:N: Address already in use,channel_setup_fwd_listener_tcpip: cannot listen to port: N,Could not request local forwarding.SftpUnavailable:subsystem request failed on channel N.
The policy runs at LogLevel=INFO because OpenSSH prints a keepalive timeout and a peer that closes during key
exchange only at INFO; at ERROR both end with exit 255 and nothing on stderr. INFO adds nothing to a normal session;
it does print a server's Banner at the start of stderr.
Trust
| trust._tag | Source | Pinned as |
| ----------------- | ---------------------------------------------------------------------- | --------------------------- |
| KnownHostsFile | a known_hosts the caller supplies, with its HostKeyAlias if any | used as is |
| DeliveredKey | an Ed25519 public key delivered over an authenticated channel | the alias, in an owned file |
| ScannedMatching | ssh-keyscan, accepted only if the fingerprint is in the expected set | the alias, in an owned file |
| FirstUse | ssh-keyscan, recorded on first use | the alias, in an owned file |
Every kind ends in StrictHostKeyChecking=yes. A scan that does not match is refused before any credential is
offered. Preparing the same alias in the same directory with a different key is refused (HostKeyRejected, stage
pinned).
The policy every invocation carries
-F none, public-key authentication only (BatchMode, IdentitiesOnly, IdentityAgent=none, no password or
keyboard-interactive), strict host-key checking against a quoted UserKnownHostsFile with GlobalKnownHostsFile
/dev/null, UpdateHostKeys and VerifyHostKeyDNS off, no agent forwarding or local commands, ConnectTimeout=15,
the target's keepalive (ServerAliveInterval/ServerAliveCountMax, 5/2 unless the target declares another),
LogLevel=INFO, HostKeyAlias when the target has one, and HostKeyAlgorithms=ssh-ed25519 when the library wrote
the known_hosts. exec and copy add no forwarding and no multiplexing. Each process gets an explicit environment
(PATH, HOME, LC_ALL=C), so no parent secret and no agent socket reaches it.
Paths are AbsolutePath values: absolute, with no control characters, quotes, backslashes, colons or % (OpenSSH
expands % tokens). Spaces are allowed and always quoted.
Carriers
A carrier is an ssh holding forwards (Local, RemoteTcp, RemoteSocket; every listener binds 127.0.0.1) under
a separate owner process, which publishes receipts to the carrier directory and ends ssh at expiresAt.
- Lease (
leaseCarrier): outlives its creator untilexpiresAt. It runs as an OpenSSH master on a private control socket, soobserveCarrierchecks the process identities and-O check, andcloseCarriercloses it with-O exiteven after its owner is gone. The creator releases the owner process and the receipt carries the hand-off,handOff { identity: { pid, startedAt }, releasedAt, deadlineAt }, checked against the identity the owner published.HandOffandProcessIdentityare re-exported from@inkeep/impulse-owned-processas plain structs, so every schema-valid value encodes, a plain object with those fields included. - Tether (
tetherCarrier): ends when the creating scope closes, when the creator process dies (the owner reads end of file on a pipe the creator holds), or atexpiresAt. - Restart (
restart: "until-expiry"): only a carrier with this setting relaunches its ownsshconnection afterUnreachable,ConnectionLost,ForwardRefusedorTerminated, backing off from 1 s to at most 30 s, and publishes each incarnation. It never retries or replays anexecorcopycommand. A rejected host key or refused authentication is not retried. - Remote backstop: the remote session is
exec sleep <seconds to expiresAt + 5>, so the far side ends the carrier when every local owner was killed. It drains rather than bounds: a forwarded connection neither end closes holds it open, and after an early close the remotesleeplingers until its deadline. - A bundled command line that cannot run this package's owner file points
CarrierOwnerCommandat its own hidden subcommand, which callsrunCarrierOwner(requestFile)underNodeRuntime.runMain.
A process's identity is its pid with ps -o lstart=, read under TZ=UTC so every reader gets the same text. It is
gone only when kill(pid, 0) fails with ESRCH; a start time that cannot be read for a process that exists is a
failure, never "gone".
The process layer
@inkeep/impulse-owned-process owns every spawn, output drain, stdin feed, termination and process-group probe.
SSH imports its run, checked and owned directly. Every request supplies deadline and terminationGrace
(the library's 1 s), which sets forceKillAfter. A deadline or interruption sends SIGTERM to the child's process
group (to the child alone under processGroup: "inherit") and SIGKILL after the grace. Group confirmation runs
as the shared runner's last finalizer, so cancelling while it waits for a zombie to be reaped still waits for ESRCH
within the remaining grace. A group still present at that bound remains unconfirmed.
The package re-exports the shared Output helpers, bounded lines sink, ProcessIdentity and HandOff. SSH keeps
its policy, SshError, carrier owner entry and receipts. Its tests retain both stdin controls, the cancellation
regression, UTC identity, exact-bound UTF-8 lines and the 225 MiB digest/RSS check; generic process tests live with
their implementation in packages/owned-process.
Preconditions
- OpenSSH client 8.7 or later (measured: 10.3p1 on macOS; the nightly's Ubuntu runners have 9.6p1).
- On the remote: a POSIX shell and
sleepfor carriers; an SFTP subsystem forcopy(SftpUnavailablewithout one), andsha256sumandwcfor its far-side digest (Linux has them; macOS has/sbin/sha256sum). Linux test runs also require/usr/bin/setfacland/usr/bin/getfaclfor the POSIX ACL private-directory case; a missing utility fails the package test. - Remote forwards need the guest's
ClientAliveInterval 5andClientAliveCountMax 2. Without them a frozen client keeps its remote listener and every relaunch is refused (ForwardRefused); with them a relaunch recovers within about 18 s. The library cannot set a guest'ssshd_config.
Checks
A member of the root workspace. From the repository root, pnpm install --frozen-lockfile; then from this
directory, run the tests first to build the owned-process dependency:
pnpm run test
pnpm run typecheck
pnpm run lint
pnpm run buildFor a standalone typecheck or build on a fresh checkout, first run pnpm --filter '@inkeep/impulse-ssh^...' run build, which builds the package's workspace dependencies.
The nightly runs the tests in the packages suite (node scripts/ci/run-suite.mjs packages from the root); its
root-static suite builds, lints, typechecks and checks the formatting of the package with the rest of the workspace.
The packages suite then builds the package and checks what it would publish. To run that check here, build, then
run node scripts/ci/pack-contents.mjs packages/ssh from the repository root: it packs the package and fails on a
source map, a sourceMappingURL comment, TypeScript source, a test file, an @openteammate/* runtime dependency or a
missing entry point.
The private-directory ACL case runs through pnpm run test on both supported platforms: Linux plants POSIX access
and default ACLs, while macOS plants and strips a macOS ACL. The Linux nightly packages suite runs its Linux
branch. No registered macOS suite selects packages/ssh; run pnpm --dir packages/ssh run test on macOS to execute
the macOS branch. Neither branch uses a runner skip, and an unsupported platform fails explicitly.
The tests start an unprivileged /usr/sbin/sshd on 127.0.0.1 with throwaway keys under /tmp/ots-*, reach nothing
beyond loopback, need no Docker or root, and remove what they create. The PATH-shim test also runs /usr/bin/git.
A missing sshd fails the tests; it does not skip them. One test streams 225 MiB of stdin into sha256sum on the
far side and checks the digest and the sender's peak RSS; it takes about 4 s.
Not covered here: behaviour over a long client absence (the keepalive measurement in the design note) and hosted runs.
Releasing
Releases follow packages/README.md, "Publishing a member to npm", which also lists the owner's one-time setup. For
this package:
- In a PR, set
versioninpackage.jsonto the release, and merge it. A new owned-process version this one needs is released first. - From the repository root, pack and check it on
main:gh workflow run publish-package.yml --ref main -f package=ssh -f action=check. The check refuses the pack while npm does not yet serve the@inkeep/impulse-owned-processversion it depends on. - Release that commit: the same command with
-f action=publish.
The first version, 0.1.0, is the owner's to publish by hand from step 2's artifact, after owned-process 0.1.0, because npm sets up trusted publishing only on a package that already exists.
