Repository Public
1# SPRemoteKit23Two small libraries for SP Term (Swift 6, macOS 14+, no dependencies):45- **SSHKit** prepares and interprets invocations of the *system* OpenSSH tools.6- **GitKit** reads git context (status, log, diff) and cannot modify a repository.78Neither library implements cryptography, reads private key contents, or handles passwords.9All subprocesses are spawned with an explicit argv (never a shell), a timeout and a cap on captured output.1011```12swift build13swift test14```1516## SSHKit1718| Type | Purpose |19|---|---|20| `SSHConfigParser` / `SSHConfig` / `SSHConfigHost` | Parse `~/.ssh/config` text into concrete aliases and their effective options. |21| `SSHConfigFileSystem` | File access for `Include` (`.live`, `.inMemory([path: text])`, or custom closures). |22| `SSHHostProfile` | Codable host entry (`.sshConfig` or `.manual`), plus `merge(configHosts:saved:)`. |23| `SSHCommandBuilder` / `SSHCommand` / `SSHOption` | Validated argv for `/usr/bin/ssh` and `/usr/bin/sftp`, plus a shell-quoted display string. |24| `KnownHostsInspector` | `.known / .unknown / .indeterminate` through `ssh-keygen -F`. |25| `SSHErrorClassifier` / `SSHErrorKind` | Map ssh stderr + exit status to a cause with an English explanation. |2627```swift28let config = SSHConfigParser().parseFile() // ~/.ssh/config29let profiles = SSHHostProfile.merge(configHosts: config.hosts, saved: savedProfiles)30let command = try SSHCommandBuilder.sshCommand(for: profiles[0], extraOptions: [SSHOption("ConnectTimeout", "10")])31// spawn command.executable with command.arguments in a pty; show command.displayString3233let known = await KnownHostsInspector().status(host: "example.com", port: 2222)34let cause = SSHErrorClassifier.classify(stderr: stderrText, exitStatus: 255)?.explanation35```3637### Config parser3839- `Host` with several patterns, `*` / `?` wildcards and `!negation`; `key value`, `key=value`, `key = value`;40 single and double quotes, `\` escapes, `#` comments; keywords are case-insensitive.41- Kept keywords: `HostName`, `User`, `Port`, `ProxyJump`, `IdentityFile` (path string only, never opened),42 `ForwardAgent`. Resolution follows OpenSSH: the first obtained value wins across all matching blocks43 (`IdentityFile` accumulates).44- `Include`: `~` and absolute paths, relative paths against the config directory, globs, depth limit45 (16 by default), missing files ignored. A `Host`/`Match` opened inside an included file does not leak into46 the including file.47- `Match` blocks are skipped (their options apply to nobody), except the unconditional `Match all`.48- `SSHConfig.aliases` / `.hosts` list the patterns without wildcard or negation; `resolve(_:)` works for any name.4950Differences from OpenSSH: host patterns are matched case-sensitively, comma-separated pattern lists inside a51single `Host` argument are not split, tokens (`%h`) and environment variables are not expanded,52`CanonicalizeHostname` and `Match` criteria are not evaluated, and unterminated quotes are tolerated.5354### Command builder guarantees5556- Host, user and ProxyJump are validated against strict ASCII allowlists; a value that is empty, starts with57 `-`, or contains whitespace, control characters or shell metacharacters throws `SSHCommandError`.58 Ports must be 1–65535. The host is always placed after `--`.59- Extra `-o` options go through an allowlist with per-key value checks (`SSHCommandBuilder.allowedOptionKeys`:60 AddressFamily, Compression, ConnectTimeout, ConnectionAttempts, ForwardAgent, RequestTTY,61 ServerAliveCountMax, ServerAliveInterval, TCPKeepAlive). Anything else throws.62- Never emitted, whatever the input: `StrictHostKeyChecking`, `UserKnownHostsFile`, `GlobalKnownHostsFile`,63 `KnownHostsCommand`, `CheckHostIP`, `VerifyHostKeyDNS`, `HostKeyAlias`, `UpdateHostKeys`, `BatchMode`,64 password options, `ProxyCommand`, `LocalCommand`. Host key verification stays under OpenSSH's control.65- For `.sshConfig` profiles only the alias is emitted (OpenSSH resolves user, port and jump hosts from the66 config); `user`, `port` and `proxyJump` of such a profile are informational.67- Internationalized (non-ASCII) host names are rejected; use the punycode form.6869### Known hosts7071`KnownHostsInspector` only runs `ssh-keygen -F <host | [host]:port> [-f file]`; it never uses `-R`/`-H` and72never writes. It searches one file (default `~/.ssh/known_hosts`), not the global files, and expects the real73host name (`SSHConfigHost.hostName`), not a config alias. A missing file means `.unknown`.7475### Error classifier7677`classify(stderr:exitStatus:)` returns `nil` for exit status 0, and for a status other than 255 without a78recognizable ssh message (that status belongs to the remote command). Matching is on English OpenSSH messages.7980## GitKit8182| Type | Purpose |83|---|---|84| `GitRunner` | Runs `/usr/bin/git` for allowlisted read-only commands. |85| `GitRepository` | `discover(from:)`, `status()`, `recentCommits(limit:)`, `diff(staged:path:maxBytes:)`. |86| `GitStatus`, `GitStatusEntry`, `GitHead`, `GitChangeKind`, `GitCommit`, `GitDiff`, `GitError` | Models. |8788```swift89let repository = try await GitRepository.discover(from: workingDirectoryURL)90let status = try await repository.status() // head, upstream, ahead/behind, staged/unstaged/untracked/conflicted91let commits = try await repository.recentCommits(limit: 20)92let diff = try await repository.diff(staged: false, path: "Sources/App.swift") // diff.truncated when capped93```9495### Read-only guarantees9697- `GitRunner.validate(_:)` runs before anything is spawned and throws `GitError.commandNotAllowed` unless the98 command is one of: `rev-parse`, `status`, `log`, `diff`, `show`, `branch` in listing mode99 (`--list`, `-a`, `-r`, `--show-current`), `worktree list`, `remote`, `remote -v`, `remote get-url`.100 The first argument must be the subcommand, so caller-supplied global options (`-c`, `-C`, `--git-dir`) are refused.101- Options that write files or run programs are refused, including their abbreviations: `--output`,102 `--ext-diff`, `--textconv`, `--no-index`, `--show-signature`.103- Every invocation uses `--no-optional-locks --no-pager`, disables `core.fsmonitor` and signature programs,104 adds `--no-ext-diff --no-textconv` to `diff`/`log`/`show`, and runs with a reduced environment plus105 `GIT_TERMINAL_PROMPT=0`, `GIT_OPTIONAL_LOCKS=0`, `GIT_PAGER=cat`, `LC_ALL=C`.106- Timeout (10 s by default) and bounded stdout (4 MiB by default, 256 KiB for `diff`): on overflow git is107 killed and the result is flagged `truncated` / `isTruncated`.108109Notes: `status()` uses git's default untracked mode (an untracked directory is one entry ending in `/`);110paths and diffs are decoded as UTF-8 with replacement; `diff(path:)` treats the path literally; bare111repositories are reported as `notARepository`.112113## Layout114115`Sources/SPProcess` is an internal target (not a product) shared by both libraries for subprocess execution.116