Introducing a new way to review your PRs.

Read the announcement

hcavarsan / kftray

kubectl port-forward manager and reverse tunnel (ngrok-like) for exposing local services publicly, with TLS termination, HTTP traffic inspection, UDP forwarding, multi-hop proxy routing through k8s clusters, stateful config via filesystem or git - GUI and TUI available

View on GitHub

19 documents · Updated Nov 23, 2026

docs / shared-domain-platform

Shared domain platform

The shared domain platform is the common contract layer for the workspace. It gives the desktop app, terminal app, forwarding services, proxy server, and integration services the same view of connection configuration, run state, settings, storage, and tunnel messages. The platform is centered on crates/kftray-commons, which is consumed by most workspace crates through the kftray_commons library.

Domain contract surface

The domain contract surface defines the data that moves between user-facing clients, connection workers, persistence, and network peers. The contracts use serializable Rust types so a configuration can move from JSON or a database into a forwarder and then into a status or response shown by another client.

The main contracts are:

ContractShared meaning
ConfigOne connection definition. It can describe a Kubernetes target, an SSH forward, a proxy, or an exposed endpoint.
ConfigStateThe run state tied to a configuration, including ownership, retry status, and the last error.
AppSettingsApp-wide choices such as logging, network monitoring, SSL, shortcuts, updates, and the MCP service.
HttpLogsConfigPer-connection HTTP log policy and retention limits.
TunnelMessageThe message contract between an app-side expose client and a relay server.
CustomResponseThe result of a start or stop action, including output and status.

These types keep product surfaces aligned without making each client define its own version of the same concept. The Config contract also carries the routing meaning for each supported workload, while shared import and export rules keep that meaning intact when data crosses a file boundary. The child page Shared models and utilities explains the contracts and helper groups in more detail.

References: crates/…/lib.rs• L1-5 crates/…/mod.rs• L1-9 crates/…/config_model.rs• L78-160 crates/…/config_model.rs• L198-317 crates/…/config_state_model.rs• L6-23 crates/…/settings_model.rs• L6-49 crates/…/http_logs_config_model.rs• L6-17 crates/…/tunnel_protocol.rs• L23-88 crates/…/response.rs• L1-20

Configuration lifecycle

The configuration lifecycle turns a connection definition into shared persistent data and then supplies it to clients and workers. The common layer owns the rules for import and export, storage access, schema setup, migrations, state updates, and the choice between a file-backed database and an in-memory database. Startup also creates the shared database artifacts and the proxy and expose manifests that the services need.

When a client or service uses a configuration, the shared flow is:

flowchart LR
    Input[User or integration input] --> Contract[Config contract]
    Repo[GitHub repository files] --> Contract
    Contract --> Validate[Validation and normalization]
    Validate --> Store[Database and related settings]
    Store --> Read[Desktop terminal or service client]
    Read --> Worker[Forwarding or expose worker]
    Worker --> State[ConfigState and CustomResponse]
    State --> Read

The same configuration can be read through file mode for normal use or memory mode for an isolated session. The mode keeps temporary runs from sharing state with the file database while preserving the same domain behavior. Repository imports clone the selected source, merge the requested files, and validate the complete content before it changes saved data. A flush replaces file-mode configurations only after validation succeeds; other modes use an incremental update. The import path keeps requested files inside the cloned repository, avoids interactive credential prompts, limits token use to the intended origin, and removes tokens from failure messages.

References: crates/…/mod.rs• L1-17 crates/…/db.rs• L43-91 crates/…/db.rs• L126-224 crates/…/config.rs• L78-193 crates/…/config.rs• L343-376 crates/…/config.rs• L384-500 crates/…/config.rs• L698-755 crates/…/config.rs• L758-935 crates/…/config.rs• L1006-1113 crates/…/config_model.rs• L227-317 crates/…/db_mode.rs• L12-69 crates/…/migration.rs• L18-122 crates/…/github.rs• L42-161 crates/…/github.rs• L257-341 crates/…/github.rs• L347-513 crates/…/config.rs• L9-54 crates/…/lib.rs• L5-12

Runtime ownership and status

Runtime ownership and status let more than one process observe a connection without treating an old process as the current owner. ConfigState links a running connection to its configuration and records process identity, process-start identity, retry information, and the last connection error. Shared helpers use this state when clients start, stop, retry, or inspect connections.

The state contract supports these relationships:

  • A configuration is the durable definition of what to connect.
  • A ConfigState is the current run record for that definition.
  • A process identity and its start identity distinguish the owner from a later process that reuses the same process ID.
  • A running snapshot records the configuration that a forward actually holds, even if the saved configuration changes while it runs.
  • A CustomResponse reports the result of an action. A batch can return individual failures inside an otherwise successful operation result.

State updates for errors and retries apply only to a running row that still belongs to the expected owner. Shutdown cleanup clears state and its running snapshot together, but keeps a configuration marked running when resource cleanup is still owed so a later stop can retry it. This separation lets the desktop UI, terminal UI, forwarding code, and MCP tools use one status model while each surface presents it in its own way.

References: crates/…/config_state_model.rs• L6-40 crates/…/config_state.rs• L14-35 crates/…/config_state.rs• L136-180 crates/…/config_state.rs• L234-378 crates/…/config_state.rs• L380-518 crates/…/response.rs• L16-46 crates/…/portforward.rs• L1-20 crates/…/app.rs• L1-20

Persistent shared context

Persistent shared context gives every client a stable place for configuration data, settings, logs, and ownership information. The configuration directory follows an explicit environment setting first and then platform defaults. Startup creates the database file and the service manifests in that directory, then prepares the tables, foreign-key rules, and config-state links that keep stored configuration and runtime state aligned. The database and related files use that location so the desktop and terminal products can work with the same user data.

Database migration keeps older installations usable as the shared domain grows. It fills missing configuration defaults, adds run-state fields, creates per-configuration HTTP log data and shortcuts, preserves an existing global shortcut, and restores the triggers that maintain related rows. These upgrades keep durable configuration, runtime state, and derived settings available to all clients after startup.

The platform also separates installation identity from configuration IDs. This prevents a file-mode or memory-mode session from claiming resources that belong to another installation or database context. Hosts-file helpers use the same shared domain rules to add and remove names for forwarded services while preserving entries owned by other writers.

References: crates/…/config_dir.rs• L9-37 crates/…/config_dir.rs• L45-92 crates/…/db.rs• L43-91 crates/…/db.rs• L98-124 crates/…/db.rs• L126-224 crates/…/migration.rs• L18-122 crates/…/migration.rs• L124-272 crates/…/migration.rs• L275-475 crates/…/migration.rs• L477-583 crates/…/validate_configs.rs• L25-65 crates/…/hostfile.rs• L8-12 crates/…/hostsfile.rs• L66-100 crates/…/hostfile.rs• L1-28

Cross-crate network contract

The cross-crate network contract connects the expose client in the forwarding crate to the relay in the server crate. The client and relay keep matching JSON-tagged TunnelMessage definitions and use the same path and header names to agree on TCP mode, half-close support, upgrades, and flow control.

The exchange has two related paths:

  1. HTTP requests and responses carry ordinary request data and can negotiate an upgraded stream.
  2. TCP mode opens logical streams with StreamOpen, StreamData, StreamEnd, StreamCredit, and StreamClose messages.

Optional fields default to the older behavior. This lets a peer that does not support an added capability continue with the earlier message path instead of failing at decode time.

sequenceDiagram
    participant App as Forwarding client
    participant Relay as Proxy server
    participant Local as Local endpoint
    App->>Relay: WebSocket handshake and capability headers
    Relay-->>App: Mode and capability headers
    App->>Relay: HttpRequest or stream messages
    Relay->>Local: Forward request or open stream
    Local-->>Relay: Data and end signals
    Relay-->>App: HttpResponse, StreamData, StreamEnd, or Error
    App-->>Relay: StreamCredit or StreamClose

References: crates/…/tunnel_protocol.rs• L6-21 crates/…/tunnel_protocol.rs• L23-88 crates/…/tunnel_protocol.rs• L141-149 crates/…/tunnel_protocol.rs• L6-21 crates/…/tunnel_protocol.rs• L23-88 crates/…/websocket_server.rs• L258-352 crates/…/websocket_server.rs• L597-622 crates/…/websocket_client.rs• L26-32

Reusable domain utilities

Reusable domain utilities keep shared policy in one place instead of making each product surface rebuild it. They cover configuration storage and migration, settings, grouping and filtering, HTTP log policy, configuration-directory discovery, host-file edits, SSH host keys, timeouts, validation, runtime ownership, and remote configuration import.

The utilities act as shared services for the larger crates:

  • The desktop and terminal surfaces use configuration, settings, grouping, and state helpers.
  • Forwarding code uses configuration state, log policy, host-file support, SSH key storage, and database mode.
  • The server uses the tunnel message contract rather than a second wire format.
  • MCP tools use the same configuration and state operations as the native clients.
  • GitHub-backed imports use the shared configuration parser and merge rules in the selected database mode.
  • The helper process uses the host entry contract and host-file rules for privileged file work.

These utilities define behavior at the domain boundary. Product crates decide when to call them and how to show their results. The focused guide Shared models and utilities provides the next level of detail.

References: crates/…/mod.rs• L1-17 crates/…/config_view.rs• L27-57 crates/…/config_state.rs• L136-378 crates/…/http_logs_config.rs• L14-57 crates/…/settings.rs• L34-43 crates/…/ssh_host_keys.rs• L1-30 crates/…/migration.rs• L18-122 crates/…/github.rs• L19-49 crates/…/github.rs• L197-341 crates/…/github.rs• L347-513 crates/…/Cargo.toml• L24-29 crates/…/Cargo.toml• L22-28 crates/…/Cargo.toml• L27-33 crates/…/Cargo.toml• L23-29

Change checklist

When these files or sections are changed, remember to consider these:

  • A change to Config fields or export rules must stay compatible with stored JSON, import flows, the desktop commands, terminal views, and MCP config tools. Check that meaningful user values are not mistaken for storage defaults during export.
  • A change to import identity, validation, or replacement rules must preserve the same behavior for local input and GitHub-sourced content across file and memory database modes. Replacement must also remove deleted configuration IDs without leaving stale shortcut targets.
  • A change to database initialization, tables, triggers, or manifest creation must preserve startup for new config directories and keep configs, config_state, settings, HTTP log data, and SSH host-key data aligned.
  • A change to ConfigState ownership fields, process-start identity, running snapshots, or guarded retry updates must be checked against start, stop, retry, cleanup, and resource ownership behavior.
  • A change to migration defaults or derived tables must preserve existing user configuration values and keep upgrades safe to run more than once.
  • A change to TunnelMessage variants, capability flags, or headers must be applied to both the forwarding client and proxy server peers.
  • A change to database mode or configuration-directory identity must preserve separation between file data, memory data, and installation-owned resources.
  • A change to HTTP log settings must keep the per-config record, embedded config fields, and app defaults aligned.
  • A change to GitHub import authentication, fallback behavior, or repository paths must preserve non-interactive failure behavior, path containment, origin-scoped token use, and token redaction.

Important failure modes

TriggerConsequenceGuard
A peer changes tunnel fields or capability headers without updating the other peerExpose traffic can fall back to the old path, reject an upgrade, or close a streamKeep the client and relay on the same message and handshake contract.
A batch action returns failed CustomResponse values but the caller checks only the outer resultThe UI or integration reports success for failed connectionsInspect each response with batch_failure.
A process writes stale run state after another process takes ownership, or a process ID is reusedA stopped or replaced forward can appear to be runningMatch process identity and process-start identity before state changes.
A running forward's saved configuration is edited before cleanupCleanup can target the edited address or aliases instead of the resources the forward ownsUse the recorded running snapshot for the active forward.
A new config directory cannot create its database, tables, triggers, or service manifestsStartup fails or a client has no shared persistence and runtime resourcesRun shared initialization and migration before use.
Multiple configuration directories contain databasesDifferent clients can read different connection setsResolve the active directory and report competing locations before normal use.
A memory session reuses a file-mode configuration ID without a separate owner identityCleanup can remove resources from the wrong database contextUse the mode-specific owner identity.
An export treats a real target, proxy address, or alias as a placeholderA valid connection loses data and can fail validation after importRemove only empty values, the explicit remote-address sentinel, and fields unused by the workload.
A remote import contains an invalid file, an unsafe path, or a config that fails shared validationThe import stops instead of producing a usable configuration set; a flush must not discard the prior setResolve files inside the cloned repository and validate the complete content before replacement.
GitHub authentication or fallback handling sends a token to the wrong host, prompts for input, or includes it in an errorThe import fails, hangs, or exposes a repository credentialScope token use to the intended origin, disable interactive prompts, and redact token forms from errors.

Key files

FileWhy to read it
crates/…/lib.rsShows the public shared library surface.
crates/…/config_model.rsDefines the central connection contract, routing semantics, and portable export behavior.
crates/…/config_state_model.rsDefines the shared run-state contract.
crates/…/tunnel_protocol.rsDefines the client-relay wire contract.
crates/…/config.rsShows how configurations enter, leave, merge, validate, and persist in the shared domain layer.
crates/…/db.rsShows how shared persistence and service manifests are created during startup.
crates/…/migration.rsShows how stored configurations and related tables move to the current shared schema.
crates/…/github.rsShows how repository configuration files enter the shared import flow and how remote access failures are contained.
crates/…/config_state.rsShows how runtime ownership, snapshots, retry status, and errors are stored.
crates/…/db_mode.rsShows the file and memory persistence contexts.
crates/…/config_dir.rsShows configuration location and resource ownership identity.
crates/…/websocket_server.rsShows how the relay consumes the shared tunnel contract.
crates/…/websocket_client.rsShows the forwarding-side use of the relay contract.
Shared models and utilitiesProvides the focused guide to the shared model and utility modules.