SPRemoteKit
Two small libraries for SP Term (Swift 6, macOS 14+, no dependencies):
- SSHKit prepares and interprets invocations of the system OpenSSH tools.
- GitKit reads git context (status, log, diff) and cannot modify a repository.
Neither library implements cryptography, reads private key contents, or handles passwords. All subprocesses are spawned with an explicit argv (never a shell), a timeout and a cap on captured output.
swift build
swift testSSHKit
| Type | Purpose |
|---|---|
SSHConfigParser / SSHConfig / SSHConfigHost |
Parse ~/.ssh/config text into concrete aliases and their effective options. |
SSHConfigFileSystem |
File access for Include (.live, .inMemory([path: text]), or custom closures). |
SSHHostProfile |
Codable host entry (.sshConfig or .manual), plus merge(configHosts:saved:). |
SSHCommandBuilder / SSHCommand / SSHOption |
Validated argv for /usr/bin/ssh and /usr/bin/sftp, plus a shell-quoted display string. |
KnownHostsInspector |
.known / .unknown / .indeterminate through ssh-keygen -F. |
SSHErrorClassifier / SSHErrorKind |
Map ssh stderr + exit status to a cause with an English explanation. |
let config = SSHConfigParser().parseFile() // ~/.ssh/config
let profiles = SSHHostProfile.merge(configHosts: config.hosts, saved: savedProfiles)
let command = try SSHCommandBuilder.sshCommand(for: profiles[0], extraOptions: [SSHOption("ConnectTimeout", "10")])
// spawn command.executable with command.arguments in a pty; show command.displayString
let known = await KnownHostsInspector().status(host: "example.com", port: 2222)
let cause = SSHErrorClassifier.classify(stderr: stderrText, exitStatus: 255)?.explanationConfig parser
Hostwith several patterns,*/?wildcards and!negation;key value,key=value,key = value; single and double quotes,\escapes,#comments; keywords are case-insensitive.- Kept keywords:
HostName,User,Port,ProxyJump,IdentityFile(path string only, never opened),ForwardAgent. Resolution follows OpenSSH: the first obtained value wins across all matching blocks (IdentityFileaccumulates). Include:~and absolute paths, relative paths against the config directory, globs, depth limit (16 by default), missing files ignored. AHost/Matchopened inside an included file does not leak into the including file.Matchblocks are skipped (their options apply to nobody), except the unconditionalMatch all.SSHConfig.aliases/.hostslist the patterns without wildcard or negation;resolve(_:)works for any name.
Differences from OpenSSH: host patterns are matched case-sensitively, comma-separated pattern lists inside a
single Host argument are not split, tokens (%h) and environment variables are not expanded,
CanonicalizeHostname and Match criteria are not evaluated, and unterminated quotes are tolerated.
Command builder guarantees
- Host, user and ProxyJump are validated against strict ASCII allowlists; a value that is empty, starts with
-, or contains whitespace, control characters or shell metacharacters throwsSSHCommandError. Ports must be 1–65535. The host is always placed after--. - Extra
-ooptions go through an allowlist with per-key value checks (SSHCommandBuilder.allowedOptionKeys: AddressFamily, Compression, ConnectTimeout, ConnectionAttempts, ForwardAgent, RequestTTY, ServerAliveCountMax, ServerAliveInterval, TCPKeepAlive). Anything else throws. - Never emitted, whatever the input:
StrictHostKeyChecking,UserKnownHostsFile,GlobalKnownHostsFile,KnownHostsCommand,CheckHostIP,VerifyHostKeyDNS,HostKeyAlias,UpdateHostKeys,BatchMode, password options,ProxyCommand,LocalCommand. Host key verification stays under OpenSSH's control. - For
.sshConfigprofiles only the alias is emitted (OpenSSH resolves user, port and jump hosts from the config);user,portandproxyJumpof such a profile are informational. - Internationalized (non-ASCII) host names are rejected; use the punycode form.
Known hosts
KnownHostsInspector only runs ssh-keygen -F <host | [host]:port> [-f file]; it never uses -R/-H and
never writes. It searches one file (default ~/.ssh/known_hosts), not the global files, and expects the real
host name (SSHConfigHost.hostName), not a config alias. A missing file means .unknown.
Error classifier
classify(stderr:exitStatus:) returns nil for exit status 0, and for a status other than 255 without a
recognizable ssh message (that status belongs to the remote command). Matching is on English OpenSSH messages.
GitKit
| Type | Purpose |
|---|---|
GitRunner |
Runs /usr/bin/git for allowlisted read-only commands. |
GitRepository |
discover(from:), status(), recentCommits(limit:), diff(staged:path:maxBytes:). |
GitStatus, GitStatusEntry, GitHead, GitChangeKind, GitCommit, GitDiff, GitError |
Models. |
let repository = try await GitRepository.discover(from: workingDirectoryURL)
let status = try await repository.status() // head, upstream, ahead/behind, staged/unstaged/untracked/conflicted
let commits = try await repository.recentCommits(limit: 20)
let diff = try await repository.diff(staged: false, path: "Sources/App.swift") // diff.truncated when cappedRead-only guarantees
GitRunner.validate(_:)runs before anything is spawned and throwsGitError.commandNotAllowedunless the command is one of:rev-parse,status,log,diff,show,branchin listing mode (--list,-a,-r,--show-current),worktree list,remote,remote -v,remote get-url. The first argument must be the subcommand, so caller-supplied global options (-c,-C,--git-dir) are refused.- Options that write files or run programs are refused, including their abbreviations:
--output,--ext-diff,--textconv,--no-index,--show-signature. - Every invocation uses
--no-optional-locks --no-pager, disablescore.fsmonitorand signature programs, adds--no-ext-diff --no-textconvtodiff/log/show, and runs with a reduced environment plusGIT_TERMINAL_PROMPT=0,GIT_OPTIONAL_LOCKS=0,GIT_PAGER=cat,LC_ALL=C. - Timeout (10 s by default) and bounded stdout (4 MiB by default, 256 KiB for
diff): on overflow git is killed and the result is flaggedtruncated/isTruncated.
Notes: status() uses git's default untracked mode (an untracked directory is one entry ending in /);
paths and diffs are decoded as UTF-8 with replacement; diff(path:) treats the path literally; bare
repositories are reported as notARepository.
Layout
Sources/SPProcess is an internal target (not a product) shared by both libraries for subprocess execution.