docs: add README, LICENSE files, and crate/module-level doc comments

Add top-level README.md with alpha status warning, quick start guide,
architecture overview, feature flags, transport modes, auth docs, and
Node.js API examples.

Add dual LICENSE-MIT and LICENSE-APACHE files.

Add comprehensive crate-level and module-level rustdoc to all three
crates (wraith-core, wraith, wraith-napi) and all public modules
(transport, client, server, auth, socks5, error). Add doc comments to
key public types (Transport, TransportAcceptor, ConnectOptions,
ClientSession, Server, ServeOptions, KeySource, ServerAuthConfig, etc).

Update Cargo.toml files with workspace-level package metadata
(version, edition, license, repository) and crate descriptions.
This commit is contained in:
2026-06-02 22:03:10 +00:00
parent f63589a5ca
commit 053ace6fcc
28 changed files with 713 additions and 7 deletions

View File

@@ -5,3 +5,9 @@ members = [
"crates/wraith-napi", "crates/wraith-napi",
] ]
resolver = "2" resolver = "2"
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/alkdev/wraith"

192
LICENSE-APACHE Normal file
View File

@@ -0,0 +1,192 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name), or refer to, the Work.
(Note: Derivative Works shall not include works that remain separable from,
or merely link (or bind by name) to the interfaces of, the Work and
Derivative Works thereof.)
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2025-2026 Alk Development
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

21
LICENSE-MIT Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025-2026 Alk Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

190
README.md Normal file
View File

@@ -0,0 +1,190 @@
# Wraith
> **Status: Alpha** — This project is in early development. It depends on solid libraries (russh, tokio, iroh) for core functionality, but the glue code and integration between them has not been fully vetted for production use. Because wraith operates low in the network stack, bugs can cause serious problems downstream (leaked connections, broken tunnels, auth failures). Use with caution and report issues.
A self-hostable SSH-based tunnel tool that provides VPN-like functionality without being a VPN protocol.
## What it does
- **Private tunneling** — Route traffic to internal services (Postgres, Redis, APIs) over SSH
- **Censorship circumvention** — SSH over TLS on port 443 is indistinguishable from HTTPS to DPI
- **NAT traversal** — The iroh transport enables peer-to-peer connections without public IPs or port forwarding
- **Service mesh connectivity** — Lightweight transport layer for event systems via reserved `wraith-*` destinations
The core insight: SSH tunnels work because SSH is fundamental infrastructure. Blocking it breaks the internet. Wraith makes SSH tunneling accessible through a simple CLI with pluggable transports.
## Quick start
### Build
```bash
cargo build --release
```
The default build includes TLS and iroh transports. To build a minimal binary with just TCP:
```bash
cargo build --release --no-default-features -p wraith
```
### Server
```bash
# Generate a host key
ssh-keygen -t ed25519 -f ssh_host_ed25519_key -N ""
# Start the server on port 22 (TCP)
wraith serve --key ssh_host_ed25519_key \
--authorized-keys ~/.ssh/authorized_keys
# TLS with stealth mode (looks like nginx 404 to scanners)
wraith serve --key ssh_host_ed25519_key \
--transport tls \
--acme-domain example.com \
--stealth
# iroh (no public IP needed)
wraith serve --key ssh_host_ed25519_key \
--transport iroh
```
### Client
```bash
# Connect via TCP and start a SOCKS5 proxy on 127.0.0.1:1080
wraith connect --server example.com:22 \
--identity ~/.ssh/id_ed25519
# Connect via TLS
wraith connect --server example.com:443 \
--transport tls \
--identity ~/.ssh/id_ed25519
# Connect via iroh (peer-to-peer, no public IP)
wraith connect --peer <endpoint-id> \
--transport iroh \
--identity ~/.ssh/id_ed25519
# With port forwarding
wraith connect --server example.com:22 \
--identity ~/.ssh/id_ed25519 \
--forward 5432:db.internal:5432 \
--forward 6379:redis.internal:6379
```
### Use the SOCKS5 proxy
Once connected, point any SOCKS5-aware application at `127.0.0.1:1080`:
```bash
curl --socks5 127.0.0.1:1080 http://internal-api:8080/health
```
For VPN-like "route all traffic" behavior, use [tun2proxy](https://github.com/tun2proxy/tun2proxy) alongside wraith's SOCKS5 proxy (see [ADR-014](docs/architecture/decisions/014-defer-tun-recommend-socks5-proxy.md)).
## Crates
| Crate | Description |
|-------|-------------|
| `wraith-core` | Core library: transport trait, SOCKS5 server, port forwarding, auth, server handler |
| `wraith` | CLI binary (`wraith connect` / `wraith serve`) |
| `wraith-napi` | Node.js native addon via napi-rs (`connect()` / `serve()`) |
## Feature flags
| Feature | Crate | Default | Description |
|---------|-------|---------|-------------|
| `tls` | `wraith-core`, `wraith` | yes | TLS transport (tokio-rustls) |
| `iroh` | `wraith-core`, `wraith` | yes | iroh QUIC P2P transport |
| `acme` | `wraith-core` | no | ACME/Let's Encrypt auto-cert provisioning |
| `testutil` | `wraith-core` | no | Test utilities (for internal use) |
## Transport modes
| Transport | Client | Server | Notes |
|-----------|--------|--------|-------|
| **TCP** | `--transport tcp --server addr:port` | `--transport tcp --listen addr:port` | Direct SSH over TCP. Default. |
| **TLS** | `--transport tls --server addr:port` | `--transport tls --tls-cert/--tls-key or --acme-domain` | SSH wrapped in TLS. Looks like HTTPS. |
| **iroh** | `--transport iroh --peer <id>` | `--transport iroh` | QUIC P2P via iroh. No public IP needed. |
## Authentication
- **Ed25519 public keys** — Default. Load authorized keys from a file via `--authorized-keys`.
- **OpenSSH certificate authority** — Optional. Use `--cert-authority` for multi-user deployments.
- **No password authentication** — Key-based auth only (see [ADR-012](docs/architecture/decisions/012-auth-ed25519-and-cert-authority.md)).
Key formats are OpenSSH throughout (private keys: `-----BEGIN OPENSSH PRIVATE KEY-----`, public keys: `ssh-ed25519 AAAA...`). PEM-encoded keys (PKCS#1, PKCS#8) are not supported.
## Architecture
Wraith's core architectural decision is that SSH never touches the network directly. The transport layer produces a duplex byte stream, and SSH runs over it via `russh::client::connect_stream()` / `russh::server::run_stream()`. This makes transports fully pluggable.
```
Client Server
│ transport.connect() │ transport_acceptor.accept()
│ ─────────────────────────────────────────────▶│
│ (duplex byte stream established) │
│ russh::client::connect_stream(stream) │ russh::server::run_stream(stream, handler)
│ ═══════ SSH session over stream ═════════════ │
│ channel_open_direct_tcpip(host, port) │
│ ─────────────────────────────────────────────▶│
│ ┌─────── TCP proxy ──────────────────┐ │
│ │ SSH channel ←→ TcpStream::connect │ │
│ └────────────────────────────────────┘ │
```
See [docs/architecture/](docs/architecture/) for full specifications and [ADR index](docs/architecture/README.md).
## Node.js API
The `wraith-napi` crate provides a Node.js native addon via napi-rs:
```js
const { connect, serve } = require('wraith-napi');
// Client: open a duplex stream through SSH
const stream = await connect({
server: "example.com:22",
transport: "tcp",
identity: "/path/to/key",
});
const data = await stream.read(1024);
await stream.write(Buffer.from("hello"));
await stream.close();
// Server: accept connections and receive streams
const server = await serve({
transport: "tcp",
hostKey: "/path/to/host_key",
authorizedKeys: "/path/to/authorized_keys",
listen: "0.0.0.0:22",
});
server.onConnection((event) => {
const { stream, info } = event;
// handle stream
});
```
> **Note:** The NAPI `serve()` currently supports TCP transport only. TLS and iroh transports will be added in a future release.
## Status and stability
This is **alpha software**. While it depends on well-established libraries (russh, tokio, rustls, iroh) for SSH, async I/O, TLS, and QUIC respectively, the integration layer that ties them together has not been battle-tested. Potential concerns include:
- **Connection handling edge cases** — reconnection logic, graceful shutdown, resource cleanup
- **Security review** — the auth layer, rate limiting, and stealth mode should be audited before production use
- **API stability** — the library API (`wraith-core`) and NAPI interface may change between versions
- **Performance** — no load testing or benchmarking has been done yet
Please test thoroughly and [file issues](../../issues) for any problems you encounter.
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

View File

@@ -1,7 +1,10 @@
[package] [package]
name = "wraith-core" name = "wraith-core"
version = "0.1.0" version.workspace = true
edition = "2021" edition.workspace = true
license.workspace = true
description = "Core library for Wraith: pluggable SSH tunnel transport, SOCKS5 proxy, port forwarding, and authentication"
repository.workspace = true
[lib] [lib]
name = "wraith_core" name = "wraith_core"

View File

@@ -1,15 +1,29 @@
//! Key loading and parsing for SSH authentication.
//!
//! Supports `KeySource` (file path or in-memory) for private keys, public keys,
//! and certificate authority entries. All keys must be in OpenSSH format.
//! PEM-encoded keys (PKCS#1, PKCS#8) are rejected with a clear error message.
use std::path::PathBuf; use std::path::PathBuf;
use russh::keys::{PrivateKey, PublicKey, decode_secret_key, parse_public_key_base64}; use russh::keys::{PrivateKey, PublicKey, decode_secret_key, parse_public_key_base64};
use crate::error::ConfigError; use crate::error::ConfigError;
/// Source for key material — either a filesystem path or in-memory bytes.
///
/// Used throughout the API to accept keys without committing to a specific
/// loading mechanism. In-memory keys are primarily for the NAPI wrapper.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum KeySource { pub enum KeySource {
File(PathBuf), File(PathBuf),
Memory(Vec<u8>), Memory(Vec<u8>),
} }
/// A certificate authority entry parsed from an `authorized_keys` file.
///
/// Contains the CA public key and its associated options (e.g., `cert-authority`,
/// `permit-port-forwarding`). Used by `ServerAuthConfig` for certificate validation.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CertAuthorityEntry { pub struct CertAuthorityEntry {
pub public_key: PublicKey, pub public_key: PublicKey,

View File

@@ -1,3 +1,8 @@
//! SSH authentication (Ed25519 public key and OpenSSH certificate authority).
//!
//! Supports file-path and in-memory key sources. No password authentication.
//! See ADR-012 for the design rationale.
pub mod client_auth; pub mod client_auth;
pub mod keys; pub mod keys;
pub mod server_auth; pub mod server_auth;

View File

@@ -1,3 +1,9 @@
//! Server-side authentication configuration and validation.
//!
//! `ServerAuthConfig` holds the set of authorized public keys and optional certificate
//! authority entries. Authentication is key-based only (Ed25519 + optional OpenSSH CA).
//! No password authentication. See ADR-012.
use std::collections::HashSet; use std::collections::HashSet;
use std::net::IpAddr; use std::net::IpAddr;
use std::str::FromStr; use std::str::FromStr;
@@ -10,6 +16,10 @@ use russh::keys::{Certificate, PublicKey};
use super::keys::{CertAuthorityEntry, KeySource, load_cert_authority_entries, load_public_keys}; use super::keys::{CertAuthorityEntry, KeySource, load_cert_authority_entries, load_public_keys};
use crate::error::AuthError; use crate::error::AuthError;
/// Server-side authentication configuration.
///
/// Holds authorized public keys (constant-time comparison) and optional certificate
/// authority entries for validating OpenSSH certificates.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ServerAuthConfig { pub struct ServerAuthConfig {
pub authorized_keys: HashSet<PublicKey>, pub authorized_keys: HashSet<PublicKey>,

View File

@@ -1,3 +1,11 @@
//! Channel manager with automatic reconnection.
//!
//! Owns the SSH session handle and provides `open_direct_tcpip()`,
//! `request_tcpip_forward()`, and `cancel_tcpip_forward()`. Monitors
//! the session for disconnect and attempts reconnection with exponential
//! backoff (1s, 2s, 4s, ..., 30s cap). Re-registers remote forwards
//! after successful reconnection.
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;

View File

@@ -1,3 +1,9 @@
//! Client session management and connection logic.
//!
//! `ClientSession` establishes an SSH connection over a transport, authenticates,
//! starts a SOCKS5 proxy, sets up port forwards, and monitors for reconnection.
//! `ConnectOptions` provides a builder-pattern API for programmatic configuration.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -17,6 +23,7 @@ use crate::transport::Transport;
const DEFAULT_SOCKS5_ADDR: &str = "127.0.0.1:1080"; const DEFAULT_SOCKS5_ADDR: &str = "127.0.0.1:1080";
const DRAIN_TIMEOUT: Duration = Duration::from_secs(2); const DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
/// Transport mode for the client connection.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransportMode { pub enum TransportMode {
Tcp, Tcp,
@@ -34,6 +41,22 @@ impl std::fmt::Display for TransportMode {
} }
} }
/// Programmatic configuration for a wraith client session.
///
/// Construct with `ConnectOptions::new(key_source)` and chain builder methods.
/// Call `validate()` before passing to `ClientSession::new()`.
///
/// ```
/// use wraith_core::client::{ConnectOptions, TransportMode};
/// use wraith_core::auth::keys::KeySource;
///
/// let opts = ConnectOptions::new(KeySource::File("/path/to/key".into()))
/// .server("example.com:22")
/// .transport_mode(TransportMode::Tcp)
/// .socks5_addr("127.0.0.1:1080")
/// .forward("5432:db.internal:5432");
/// opts.validate().unwrap();
/// ```
#[derive(Clone)] #[derive(Clone)]
pub struct ConnectOptions { pub struct ConnectOptions {
pub server: Option<String>, pub server: Option<String>,
@@ -155,6 +178,11 @@ impl std::fmt::Debug for ConnectOptions {
} }
} }
/// An active SSH client session over a transport.
///
/// Establishes the connection, authenticates, and runs a SOCKS5 proxy plus
/// port forwards until shutdown or transport failure. On transport failure,
/// attempts reconnection with exponential backoff (1s, 2s, 4s, ..., 30s cap).
pub struct ClientSession<T: Transport> { pub struct ClientSession<T: Transport> {
opts: ConnectOptions, opts: ConnectOptions,
transport: Arc<T>, transport: Arc<T>,
@@ -489,6 +517,7 @@ fn build_remote_specs(opts: &ConnectOptions) -> Result<Vec<PortForwardSpec>, Con
Ok(specs) Ok(specs)
} }
/// Errors that can occur during client connection setup and operation.
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum ConnectError { pub enum ConnectError {
#[error("connection failed")] #[error("connection failed")]

View File

@@ -1,3 +1,10 @@
//! Local and remote port forwarding.
//!
//! `LocalForwarder` binds a local TCP listener and forwards each connection through
//! an SSH `direct-tcpip` channel. `RemoteForwarder` requests `tcpip-forward` from
//! the server and handles `forwarded-tcpip` channels. Specs follow the
//! `bind_addr:bind_port:target_host:target_port` format.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;

View File

@@ -1,3 +1,13 @@
//! Client-side SSH session management.
//!
//! Provides `ClientSession` for establishing an SSH connection over any transport,
//! running a local SOCKS5 proxy, and managing port forwards. Also provides
//! `ChannelManager` for programmatic channel management with automatic reconnection.
//!
//! The client always starts a SOCKS5 proxy (default `127.0.0.1:1080`) when running
//! via `ClientSession::run()`. For VPN-like "route all traffic" behavior, use
//! [tun2proxy](https://github.com/tun2proxy/tun2proxy) alongside the SOCKS5 proxy.
pub mod channel_manager; pub mod channel_manager;
pub mod connect; pub mod connect;
pub mod forward; pub mod forward;

View File

@@ -1,3 +1,12 @@
//! Error types for wraith-core.
//!
//! Layered error hierarchy:
//! - `TransportError` — connection/handshake/timeout errors (trigger reconnection on client)
//! - `AuthError` — key rejection, certificate validation failures
//! - `ChannelError` — per-channel failures (target unreachable, channel closed)
//! - `ConfigError` — invalid configuration (flags, key files, bind failures)
//! - `ForwardError` — port forward setup and connection failures
use std::io; use std::io;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]

View File

@@ -1,3 +1,55 @@
//! # wraith-core
//!
//! Core library for [Wraith](https://github.com/alkdev/wraith), a self-hostable SSH-based
//! tunnel tool. This crate provides the transport abstraction, SOCKS5 server, port forwarding,
//! authentication, and server handler — everything needed to build a wraith client or server
//! on top of pluggable transports.
//!
//! > **Alpha software.** This crate depends on solid libraries (russh, tokio, rustls, iroh)
//! > for core functionality, but the integration layer has not been battle-tested. Use with
//! > caution and report issues.
//!
//! # Key concepts
//!
//! - **Transport trait** — produces a duplex byte stream (`AsyncRead + AsyncWrite + Unpin + Send`)
//! that SSH consumes. Implementations: TCP, TLS, iroh (QUIC P2P).
//! - **SOCKS5 server** — the primary client interface, listening on a local port and routing
//! traffic through SSH channels.
//! - **Port forwarding** — `-L` local and `-R` remote port forwards over SSH channels.
//! - **Authentication** — Ed25519 public key and OpenSSH certificate authority. No passwords.
//! - **Server handler** — accepts SSH connections via a `TransportAcceptor` and proxies
//! `direct-tcpip` channel requests to targets (directly or via outbound proxy).
//!
//! # Feature flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `tls` | yes | TLS transport via `tokio-rustls` |
//! | `iroh` | yes | iroh QUIC P2P transport |
//! | `acme` | no | ACME/Let's Encrypt auto-cert provisioning (implies `tls`) |
//! | `testutil` | no | Test utilities (for internal use) |
//!
//! # Quick example
//!
//! ```no_run
//! use std::sync::Arc;
//! use wraith_core::transport::TcpTransport;
//! use wraith_core::client::{ClientSession, ConnectOptions, TransportMode};
//! use wraith_core::auth::keys::KeySource;
//! use wraith_core::Transport;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let opts = ConnectOptions::new(KeySource::File("/path/to/key".into()))
//! .server("example.com:22")
//! .transport_mode(TransportMode::Tcp);
//! let transport = Arc::new(TcpTransport::new("example.com:22".parse()?));
//! let session = ClientSession::new(opts, transport).await?;
//! session.run().await?;
//! Ok(())
//! }
//! ```
pub mod transport; pub mod transport;
pub mod client; pub mod client;
pub mod server; pub mod server;

View File

@@ -1,3 +1,9 @@
//! Outbound connection proxy for SSH channel targets.
//!
//! Connects to the requested `host:port` either directly, via SOCKS5 proxy, or
//! via HTTP CONNECT proxy, then proxies bytes bidirectionally between the SSH
//! channel and the outbound TCP stream.
use std::net::SocketAddr; use std::net::SocketAddr;
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};

View File

@@ -1,3 +1,9 @@
//! Control channel routing for reserved `wraith-*` destinations.
//!
//! SSH channels opened with a destination starting with `wraith-` are intercepted
//! by the server and routed to a `ControlChannelHandler` instead of proxied to a
//! TCP target. See ADR-018 for the design rationale.
use std::io; use std::io;
use async_trait::async_trait; use async_trait::async_trait;

View File

@@ -1,3 +1,12 @@
//! Server-side SSH connection handling.
//!
//! Provides `Server` for accepting SSH connections over any transport and proxying
//! `direct-tcpip` channel requests to targets. Supports Ed25519 and certificate-authority
//! auth, connection rate limiting, auth attempt limiting, stealth mode (fake nginx 404),
//! and outbound proxy routing (direct/SOCKS5/HTTP CONNECT).
//!
//! Destination hosts starting with `wraith-` are reserved for internal use (control channel, ADR-018).
pub mod channel_proxy; pub mod channel_proxy;
pub mod control_channel; pub mod control_channel;
pub mod handler; pub mod handler;

View File

@@ -1,3 +1,10 @@
//! Connection rate limiting and auth attempt limiting.
//!
//! `ConnectionRateLimiter` tracks per-IP active connections (thread-safe).
//! `AuthAttemptLimiter` caps failed auth attempts per connection.
//! These complement fail2ban on Linux and provide abuse protection on all platforms.
//! See ADR-013.
use std::collections::HashMap; use std::collections::HashMap;
use std::net::IpAddr; use std::net::IpAddr;
use std::sync::Mutex; use std::sync::Mutex;

View File

@@ -1,3 +1,9 @@
//! Server configuration and accept loop.
//!
//! `Server` binds to a transport acceptor and runs an accept loop, handling
//! authentication, stealth mode protocol detection, and graceful shutdown.
//! `ServeOptions` provides a builder-pattern API for programmatic configuration.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -16,6 +22,7 @@ use crate::server::stealth::{self, ProtocolDetection};
const DEFAULT_LISTEN_ADDR: &str = "0.0.0.0:22"; const DEFAULT_LISTEN_ADDR: &str = "0.0.0.0:22";
const DRAIN_TIMEOUT: Duration = Duration::from_secs(2); const DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
/// Transport mode for the server listener.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServeTransportMode { pub enum ServeTransportMode {
Tcp, Tcp,
@@ -33,6 +40,22 @@ impl std::fmt::Display for ServeTransportMode {
} }
} }
/// Programmatic configuration for a wraith server.
///
/// Construct with `ServeOptions::new(key_source)` and chain builder methods.
/// Call `validate()` before passing to `Server::new()`.
///
/// ```
/// use wraith_core::server::{ServeOptions, ServeTransportMode};
/// use wraith_core::auth::keys::KeySource;
///
/// let opts = ServeOptions::new(KeySource::File("/path/to/host_key".into()))
/// .transport_mode(ServeTransportMode::Tcp)
/// .listen_addr("0.0.0.0:22")
/// .max_connections_per_ip(5)
/// .max_auth_attempts(3);
/// opts.validate().unwrap();
/// ```
pub struct ServeOptions { pub struct ServeOptions {
pub key: KeySource, pub key: KeySource,
pub authorized_keys: Option<KeySource>, pub authorized_keys: Option<KeySource>,
@@ -180,6 +203,7 @@ impl std::fmt::Debug for ServeOptions {
} }
} }
/// Errors that can occur during server setup and operation.
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum ServeError { pub enum ServeError {
#[error("config error: {0}")] #[error("config error: {0}")]
@@ -197,6 +221,11 @@ struct ActiveSession {
join: tokio::task::JoinHandle<()>, join: tokio::task::JoinHandle<()>,
} }
/// The wraith SSH server.
///
/// Accepts connections over any `TransportAcceptor`, authenticates via Ed25519 keys
/// or certificate authority, and proxies `direct-tcpip` channels to their targets.
/// Supports stealth mode (TLS only), outbound proxy routing, and connection rate limiting.
pub struct Server { pub struct Server {
config: Arc<server::Config>, config: Arc<server::Config>,
auth_config: Arc<ServerAuthConfig>, auth_config: Arc<ServerAuthConfig>,

View File

@@ -1,3 +1,11 @@
//! Stealth mode: protocol detection on TLS connections.
//!
//! When stealth mode is enabled with TLS transport, the server peeks at the first
//! bytes after the TLS handshake to determine whether the client is speaking SSH
//! or HTTP. Non-SSH connections receive a fake nginx 404 response, making the
//! server appear as an ordinary web server to port scanners and DPI systems.
//! See ADR-017.
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
const SSH_BANNER_PREFIX: &[u8] = b"SSH-2.0-"; const SSH_BANNER_PREFIX: &[u8] = b"SSH-2.0-";

View File

@@ -1,3 +1,10 @@
//! SOCKS5 proxy server.
//!
//! Listens on a local port and routes each SOCKS5 connection through an SSH
//! `direct-tcpip` channel. Supports SOCKS5h (domain names resolved server-side)
//! to prevent DNS leaks. Uses the `ChannelOpener` trait to abstract over the
//! SSH channel mechanism, making it testable without a real SSH session.
mod protocol; mod protocol;
use std::net::SocketAddr; use std::net::SocketAddr;

View File

@@ -1,3 +1,18 @@
//! Pluggable transport layer for Wraith.
//!
//! The transport layer produces a duplex byte stream (`AsyncRead + AsyncWrite + Unpin + Send`)
//! that SSH consumes. This is the core architectural abstraction — SSH never opens its own
//! network connections; it runs entirely over whatever stream the transport provides.
//!
//! Available transports (feature-gated):
//! - `TcpTransport` / `TcpAcceptor` — always available, direct TCP
//! - `TlsTransport` / `TlsAcceptor` — behind the `tls` feature, TCP + rustls
//! - `IrohTransport` / `IrohAcceptor` — behind the `iroh` feature, QUIC P2P via iroh
//! - `AcmeTlsAcceptor` — behind the `acme` feature, auto-provision TLS certs via Let's Encrypt
//!
//! See [ADR-001](docs/architecture/decisions/001-pluggable-transport.md) and
//! [ADR-004](docs/architecture/decisions/004-ssh-over-transport.md) for design rationale.
mod tcp; mod tcp;
#[cfg(feature = "iroh")] #[cfg(feature = "iroh")]
mod iroh_transport; mod iroh_transport;
@@ -24,19 +39,33 @@ use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use tokio::io::{AsyncRead, AsyncWrite}; use tokio::io::{AsyncRead, AsyncWrite};
/// Client-side transport trait. Produces a single duplex stream per connection.
///
/// Implementations connect to a remote endpoint and return a stream that SSH
/// runs over via `russh::client::connect_stream()`. Each call to `connect()` creates
/// a new stream — multiple sessions need multiple calls or multiple transports.
#[async_trait] #[async_trait]
pub trait Transport: Send + Sync + 'static { pub trait Transport: Send + Sync + 'static {
/// The duplex stream type produced by this transport.
type Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static; type Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static;
/// Connect to the remote endpoint and return a duplex stream.
async fn connect(&self) -> Result<Self::Stream>; async fn connect(&self) -> Result<Self::Stream>;
/// Return a human-readable description of this transport for logging.
fn describe(&self) -> String; fn describe(&self) -> String;
} }
/// Server-side transport acceptor. Accepts incoming connections and returns streams.
///
/// Implementations bind to a local endpoint and produce streams that SSH
/// runs over via `russh::server::run_stream()`.
#[async_trait] #[async_trait]
pub trait TransportAcceptor: Send + Sync + 'static { pub trait TransportAcceptor: Send + Sync + 'static {
/// The duplex stream type produced by this acceptor.
type Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static; type Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static;
/// Accept an incoming connection and return a duplex stream with metadata.
async fn accept(&self) -> Result<(Self::Stream, TransportInfo)>; async fn accept(&self) -> Result<(Self::Stream, TransportInfo)>;
} }

View File

@@ -1,7 +1,10 @@
[package] [package]
name = "wraith-napi" name = "wraith-napi"
version = "0.1.0" version.workspace = true
edition = "2021" edition.workspace = true
license.workspace = true
description = "Node.js native addon for Wraith via napi-rs: connect() and serve() SSH tunnel functions"
repository.workspace = true
[lib] [lib]
crate-type = ["cdylib"] crate-type = ["cdylib"]

View File

@@ -1,3 +1,9 @@
//! NAPI `connect()` function and `WraithStream` type.
//!
//! Opens a single SSH channel as a duplex stream for programmatic use.
//! Unlike the CLI client, this does not start a SOCKS5 server or port forwards —
//! it provides a raw stream that JavaScript code can read from and write to.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;

View File

@@ -1,3 +1,26 @@
//! # wraith-napi
//!
//! Node.js native addon for [Wraith](https://github.com/alkdev/wraith) via napi-rs.
//! Exposes `connect()` and `serve()` functions for programmatic SSH tunnel creation.
//!
//! > **Alpha software.** The NAPI interface may change between versions.
//!
//! # Quick example (Node.js)
//!
//! ```js
//! const { connect, serve } = require('wraith-napi');
//!
//! // Client: open a duplex SSH stream
//! const stream = await connect({
//! server: "example.com:22",
//! transport: "tcp",
//! identity: "/path/to/key",
//! });
//! await stream.write(Buffer.from("hello"));
//! const data = await stream.read(1024);
//! await stream.close();
//! ```
#[allow(unused_imports)] #[allow(unused_imports)]
#[macro_use] #[macro_use]
extern crate napi_derive; extern crate napi_derive;

View File

@@ -1,3 +1,9 @@
//! NAPI `serve()` function and `WraithServer` type.
//!
//! Starts a TCP-based SSH server that emits new channel streams via a
//! `ThreadsafeFunction` callback. Currently supports TCP transport only;
//! TLS and iroh will be added in a future release.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;

View File

@@ -1,7 +1,10 @@
[package] [package]
name = "wraith" name = "wraith"
version = "0.1.0" version.workspace = true
edition = "2021" edition.workspace = true
license.workspace = true
description = "CLI binary for Wraith: self-hostable SSH tunnel tool with pluggable transports"
repository.workspace = true
[[bin]] [[bin]]
name = "wraith" name = "wraith"

View File

@@ -1,3 +1,11 @@
//! # wraith
//!
//! CLI binary for [Wraith](https://github.com/alkdev/wraith), a self-hostable SSH-based tunnel
//! tool. Provides `wraith connect` (client) and `wraith serve` (server) subcommands with
//! pluggable transports (TCP, TLS, iroh).
//!
//! > **Alpha software.** See `wraith-core` for library usage.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::process; use std::process;
use std::sync::Arc; use std::sync::Arc;