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-models-and-utilities

Shared models and utilities

kftray-commons is the shared contract layer for workspace components. It gives the desktop app, forwarding services, integrations, and terminal flows one view of saved connection data, runtime state, settings, wire messages, and common system actions. See shared domain platform for the wider domain model.

Shared contract role

The crate keeps cross-component behavior consistent by putting data shapes and shared rules in one place. Components can exchange the same values through JSON, the local data store, and the tunnel protocol without creating separate meanings for the same connection.

Configuration contract

Config is the main connection definition. It describes where traffic starts, where it goes, which workload or exposure it uses, and optional features such as domain aliases, tags, and HTTP logs. The contract supports service, pod, proxy, expose, and SSH port-forward use cases. Selected boolean fields also accept the strings true and false, which helps older or external JSON use the same contract.

Configuration helpers decide when a connection can use a direct path, when a domain alias is valid, and which saved record matches imported data. Export removes local identity and default values. It also removes fields that do not apply to the selected workload or exposure. These rules connect the configuration editor to forwarding, exposure, and import flows.

References: crates/…/config_model.rs• L78-317 crates/…/config.rs• L384-557 crates/…/config.rs• L618-756

Runtime state contract

ConfigState records the live status of a saved connection. It lets workspace components show whether a forward runs, identify the process that owns it, and retain retry details or the last connection error. A process-start identity supplements the process ID, so a later process that reuses the same ID is not treated as the owner.

State helpers accept updates only when the recorded owner still runs the forward. This prevents a delayed error or retry update from changing a stopped forward or one taken by another process. They also clean up state for the current process while preserving entries whose resource cleanup is still owed.

The helpers keep a snapshot of the configuration used to start a file-backed forward. This separates the resources a running forward owns from later edits to the saved configuration. Stop and cleanup actions can then use the correct resource values.

References: crates/…/config_state_model.rs• L6-49 crates/…/config_state.rs• L14-35 crates/…/config_state.rs• L136-226 crates/…/config_state.rs• L234-378 crates/…/config_state.rs• L380-519

Settings contract

AppSettings gives the desktop and service layers one typed view of app-wide choices. It covers network monitoring, disconnect timeouts, HTTP log defaults, updates, local certificates, global shortcuts, and the optional MCP server. The settings layer reads these values from the shared store and applies safe defaults when a value is absent or invalid.

Settings can be scoped to the file database or to a process-local memory database. A change to the disconnect timeout also refreshes active forward timers, so a new setting takes effect without restarting the forward.

References: crates/…/settings_model.rs• L6-105 crates/…/settings_model.rs• L107-226 crates/…/settings.rs• L34-73 crates/…/settings.rs• L415-429 crates/…/db_mode.rs• L12-69

Tunnel wire contract

TunnelMessage defines the messages that carry HTTP requests, HTTP responses, raw stream data, stream closure, heartbeats, and errors between tunnel peers. Its optional upgrade and flow-control markers let newer peers add long-lived or half-closed streams while older peers keep the earlier behavior.

The shared constants define the handshake paths, headers, and stream credit window. This contract is consumed by the forwarding path and the terminal or integration paths that use forwarded traffic. See connection forwarding and terminal experience for the user-visible flows around this wire contract.

References: crates/…/tunnel_protocol.rs• L6-88 crates/…/tunnel_protocol.rs• L90-149

Supporting domain contracts

Small shared models complete the boundaries between workspace areas. HTTP log settings stay linked to a configuration, SSH providers describe bastion access while preserving unknown future provider data, responses report per-configuration command results, and window state carries desktop-only position and process state.

The view model adds grouping and filtering over configuration fields and normalized tags. Host entries provide the common shape for managed local aliases. These types let UI, service, and integration code share the same user-facing concepts without copying parsing or display rules.

References: crates/…/http_logs_config_model.rs• L6-50 crates/…/ssh_provider.rs• L6-183 crates/…/response.rs• L1-47 crates/…/window.rs• L10-32 crates/…/hostfile.rs• L8-12 crates/…/config_view.rs• L27-123 crates/…/config_view.rs• L154-310

Configuration and state lifecycle

The shared data flow turns user input or imported data into a validated saved configuration, then keeps its runtime state and related settings aligned. The same flow supports file-backed use for normal operation and memory-backed use for isolated sessions.

This diagram shows how shared contracts turn input into stored data and then into runtime use.

flowchart LR
    Input[User or imported configuration] --> Normalize[Normalize and validate]
    Normalize --> Store[Shared configuration store]
    Store --> State[Runtime state]
    Store --> Logs[HTTP log settings]
    State --> Forward[Forwarding and exposure components]
    Store --> View[Grouping and filtering view]
    Settings[App settings] --> Forward
    Settings --> Desktop[Desktop and integration components]

Configuration persistence

The configuration helpers provide the shared lifecycle for create, read, update, delete, import, and export actions. They normalize tags and local values, assign missing local ports, validate workload-specific requirements, and merge imported records with saved records instead of creating silent duplicates. The save path also keeps the configuration row and its HTTP log settings in sync.

File-backed and memory-backed modes use separate ID ranges, so a temporary session cannot collide with a durable record. Migrations apply current configuration defaults to older saved data, add missing runtime and linked-data structures, and restore the links needed by current components. They also preserve an existing global shortcut when it moves into the shared shortcut model.

References: crates/…/config.rs• L78-166 crates/…/config.rs• L235-376 crates/…/config.rs• L698-756 crates/…/config.rs• L758-893 crates/…/config.rs• L1025-1113 crates/…/db.rs• L125-223 crates/…/migration.rs• L18-121 crates/…/migration.rs• L124-272 crates/…/migration.rs• L275-474

Database initialization

The database utility prepares shared durable storage before other components use it. Startup creates the database and resource manifests, builds the tables that link saved configurations to runtime state, and records the starting point for expose history. This gives configuration, forwarding, and exposure flows one ready store.

If another kftray process briefly holds the SQLite file, a failure to record the expose-history baseline does not block startup. The expose flow can establish the baseline later, so a transient database lock does not turn into a startup failure.

References: crates/…/db.rs• L43-93 crates/…/db.rs• L126-223

Database modes

DatabaseMode separates durable file-backed data from process-local memory data. Shared operations accept the mode so a caller can use the same domain rules for a normal installation, a temporary session, or an isolated integration flow.

The separation also protects resource ownership. Memory sessions get their own identity and use a separate ID range, so records with the same numeric ID in the file database are not treated as their own.

References: crates/…/db_mode.rs• L12-69 crates/…/config.rs• L169-233 crates/…/config.rs• L816-1013 crates/…/config_dir.rs• L73-92 crates/…/config_dir.rs• L157-167

Import and integration flow

The GitHub helper turns selected files from a repository into one configuration set. It supports a saved token or system credentials, uses a bounded repository sync with a fallback path, and reports failures without exposing the token. Only paths inside the cloned repository are accepted.

The helper merges object and array inputs, validates the complete set before a file-mode replacement, and then uses the normal configuration merge rules. This keeps external configuration sources subject to the same contract as desktop edits and local imports. A failed validation does not leave a partially accepted file-mode replacement. See service integrations for the integration surface that uses this flow.

References: crates/…/github.rs• L27-59 crates/…/github.rs• L62-164 crates/…/github.rs• L186-320 crates/…/github.rs• L322-341 crates/…/github.rs• L347-513

Configuration write protection

The configuration helpers protect concurrent edits that happen while a forward prepares a local address. An address write changes only the stored address when the record still requests automatic allocation. It reports whether the record was updated, opted out, or was deleted. This prevents a delayed allocation result from overwriting a user-chosen address or a newer configuration edit.

References: crates/…/config.rs• L953-1004

Shared system helpers

The utility modules isolate system actions that must behave the same across workspace components and operating systems. They cover local paths and ownership, host aliases, SSH trust, time limits, manifests, and shared error reporting.

Local paths and ownership

The path helpers choose one configuration directory from the explicit override, the platform config location, or the user home. They also name the local database, logs, manifests, and window state. The validation helper can detect more than one database location so the app can warn before users edit the wrong data.

Installation and configuration identities let components recognize resources created by this installation. File-mode configuration locks protect cross-process start, stop, and delete actions, while memory-mode resources stay scoped to the current process.

References: crates/…/config_dir.rs• L9-43 crates/…/config_dir.rs• L45-92 crates/…/config_dir.rs• L280-349 crates/…/validate_configs.rs• L25-108

Managed host aliases

The hosts-file helper gives domain-enabled forwards a safe way to publish local aliases. It edits only managed sections, preserves unrelated lines, validates hostnames and owners, and uses a locked read-modify-write action so concurrent writers do not remove each other’s entries.

The helper reports permission problems separately from missing or invalid paths. This lets a caller choose a privileged write path without treating every hosts-file error as an elevation need.

References: crates/…/hostsfile.rs• L19-103 crates/…/hostsfile.rs• L372-385 crates/…/hostsfile.rs• L882-923 crates/…/hostsfile.rs• L925-1035

SSH trust records

The SSH host-key helper stores the first key seen for a host alias. Later connections receive that stored key instead of silently replacing it, while an explicit delete permits a new key to be accepted after the user has decided to forget the old one.

This shared rule supports SSH-based forwarding without spreading host-key persistence decisions across the desktop and service layers. See service integrations for SSH connection use.

References: crates/…/ssh_host_keys.rs• L11-20 crates/…/ssh_host_keys.rs• L41-90

Forward time limits

The timeout helper tracks active forwards by configuration ID. A non-zero disconnect timeout schedules the forward’s stop action, a zero value disables the timer, and changing the setting rebuilds timers from their original start time.

The timer is keyed by database mode so a temporary memory session does not use the file database’s timeout value. Stopping or replacing a forward removes the old timer before another timer takes its place.

References: crates/…/timeout_manager.rs• L18-43 crates/…/timeout_manager.rs• L45-107

Resource manifests

Manifest helpers provide the default resource descriptions used to create proxy and expose resources. They also distinguish an unchanged default from a user-customized file, which allows upgrades to refresh old defaults without overwriting user changes.

The database startup path creates missing manifests and runs the matching migration when an older default is still present. This keeps resource setup aligned with the configuration and exposure contracts.

References: crates/…/manifests.rs• L294-430 crates/…/manifests.rs• L470-557 crates/…/db.rs• L42-75

Change checklist

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

  • A change to Config fields or defaults must stay aligned with import validation, export cleanup, identity matching, database migration, and the UI or integration schema that serializes the field.
  • A change to direct-forward, domain-alias, or exposure rules must stay aligned with forwarding and hosts-file behavior.
  • A change to ConfigState ownership, process-start identity, retry fields, or snapshots must stay aligned with state writes, process cleanup, running snapshots, and any component that decides whether another process owns a forward.
  • A change to TunnelMessage variants, headers, or stream markers must preserve peer fallback behavior and the relay/app contract described in connection forwarding.
  • A change to AppSettings keys or defaults must update both the typed conversion and the settings store paths, including the matching database mode.
  • A change to HTTP log fields must preserve the two-way link between Config, HttpLogsConfig, the related database row, import/export, and log consumers.
  • A change to ownership labels or configuration locks must be checked against resource discovery and cleanup so file and memory sessions cannot claim the same resources.
  • A change to managed host aliases must preserve owner validation, section markers, and the privileged writer contract.
  • A change to database startup tables, triggers, or expose-history setup must stay aligned with configuration state creation, deletion cleanup, and lazy expose-history baseline recovery.
  • A change to repository import authentication, path checks, or replacement order must preserve token redaction, repository containment, bounded sync, and all-or-nothing file-mode replacement.

Important failure modes

TriggerConsequenceGuard
An imported configuration fails validation after a file-mode flush is requestedExisting saved configurations could be lost before the new set is acceptedParse and validate the full input before clearing the file-backed store
Two saved configurations match one imported identity without a clear winnerThe import could update the wrong forwardTreat ambiguous matches as skipped instead of guessing
A repository path is absolute, uses parent traversal, or resolves through a symlink outside the cloneThe import could read a file outside the selected repositoryRequire a repository-relative path and verify its resolved location remains inside the clone
A repository sync stalls or both clone paths failImport cannot produce a configuration set and may otherwise wait without endApply a shared time limit, stop the fallback process, and report both causes
A repository error includes a supplied access tokenCredentials could leak through logs or user-visible errorsRedact the token and its encoded authorization form before reporting the error
A delayed automatic-address write reaches a record after the user opts out or changes the addressThe delayed result could overwrite the user’s newer choiceUpdate only while automatic allocation is still requested and report the write outcome
A state update arrives after a forward stops or changes ownerA stale process could mark another forward as retrying or failedRequire the expected running state and owner identity for error and retry writes
A process ID is reused after the original forward exitsA later process could be treated as the owner of stale runtime stateCompare the recorded process start identity when it is available
A tunnel peer does not support upgrade or half-close markersA long-lived stream can be closed using older whole-stream behaviorDefault missing markers to the compatible older path
A hosts file has duplicate or incomplete managed markersAlias reads or edits can report a false state or alter the wrong sectionRefuse unsafe in-place reads and use explicit destructive cleanup for duplicates
A user edits a default resource manifestStartup could overwrite a deliberate resource changeTreat malformed or non-default content as customized
File and memory modes reuse a configuration IDCleanup could remove resources owned by the other modeInclude the installation and memory-session identity in resource ownership
Another process locks the SQLite file during expose-history baseline setupStartup can log a baseline warning and continue while expose history starts without the initial snapshotRetry or establish the baseline lazily before evaluating expose history

Key files

FileWhy to read it
crates/…/lib.rsShows the public shared surface and the test isolation helpers used by common utilities.
crates/…/config_model.rsDefines the main saved connection contract and its routing and export rules.
crates/…/config_state_model.rsDefines live ownership, retry, and error state for each configuration.
crates/…/tunnel_protocol.rsDefines the message contract between tunnel peers.
crates/…/config.rsConnects validation, persistence, import/export, identity matching, mode selection, address writes, and log settings.
crates/…/db.rsPrepares the shared database, configuration-state links, resource manifests, and expose-history starting point.
crates/…/config_state.rsConnects runtime state updates with process ownership and cleanup.
crates/…/settings.rsProvides shared typed settings access and database-mode scoping.
crates/…/config_view.rsDefines configuration grouping, filtering, and tag behavior used by the desktop view.
crates/…/config_dir.rsDefines configuration paths, installation identity, and cross-process locks.
crates/…/hostsfile.rsDefines safe managed alias updates and preservation of unrelated hosts entries.
crates/…/migration.rsShows how older saved data and linked tables are brought to the current shared contract.
crates/…/github.rsShows how repository-sourced configuration enters the normal import path with bounded and safe sync behavior.