Reach a Spelunk-managed server through Spelunk, and open one from a Spelunk link

A server Spelunk manages runs Spelunk's agent, which keeps a connection open
to Spelunk. A host can now be marked "Connect through Spelunk": a connect
asks Spelunk for a ticket, opens a WebSocket, and the agent connects to the
SSH server on the machine's own loopback, so the server needs no open SSH
port. Shells and file transfers both go this way.

Client, in Client.Session:

- SpelunkTunnel implements Spelunk's contract: POST
  {api}/api/servers/{id}/tunnel-tickets with the API key as a bearer token
  and {"port":N}, then a WebSocket to the API's own origin at the path
  Spelunk returns, offering spelunk.tunnel.v1 and ticket.<ticket>. After the
  upgrade the relay's RelayBridge carries the bytes unchanged. Every refusal
  is a sentence: 401 key, 403 role (with Spelunk's detail), 404 server, 503
  agent not connected, 401/503 on the upgrade, and close codes 4502 (agent
  could not reach the port, or is too old: "Unknown stream kind") and 4503
  (agent disconnected). Only a path is taken from the ticket response, so it
  cannot send the ticket to another host.
- IConnectionRoute is what RelayRoute and SpelunkTunnelRoute have in common,
  so the connect path has one shape for both.

Host model: HostSecret.Spelunk is a SpelunkRoute (normalised API base,
server id, and the id of the credential holding the API key), at payload
schema version 8. It is written last and only when present, so every other
host keeps its bytes and its version; an older build reads a Spelunk host
as read-only rather than dropping the route. A half-written route makes the
item unreadable instead of dialled. It merges as one value and is exclusive
with RelayEnabled. The API address must be https, or http to loopback.

The API key is an ordinary keychain credential whose password is the key,
referenced by id, so it is encrypted, synced, merged and rotated like every
other secret, one credential serves every server in the organisation, and
the used-by list and deletion warning count it.

Routing: OpenRouteAsync is the one decision for both transports. A Spelunk
host is never dialled directly, never probed after a failure, and a route
that hung up with a reason replaces SSH.NET's transport error.

UI: a "Connect through Spelunk" card beside the relay card in the desktop
drawer and the phone's editor; ticking one unticks the other.

dodossh://spelunk/connect?api=&server=&name=&host= links:

- SpelunkLink parses them strictly and never reads a credential from one.
- Program reads a link from the arguments; a launch that finds DodoSSH
  running passes it down the doorbell as "dodossh.open-link <link>", which
  the running instance parses again, bounded, and otherwise ignores whole.
  The plain come-forward ring is unchanged.
- A saved host routed to that server on that Spelunk is connected to;
  otherwise the editor opens on a new, unsaved Spelunk host, with the key
  pre-chosen only when another host already sends it to that Spelunk. A link
  that arrives while locked waits for the unlock.
- Windows registers the scheme under HKCU from Velopack's install and update
  hooks and removes it on uninstall only if it still points at this
  executable; the macOS plist template declares CFBundleURLTypes and the app
  takes the URL from Avalonia's activation event; the Linux desktop entry
  gets %u and MimeType=x-scheme-handler/dodossh.
This commit is contained in:
jaap-jan committed 2026-09-28 21:25:04 +02:00
1 parent c8848ec1e3
commit 6e39807cc0
32 files changed
+3428 -85

No files matched your search

@@ -0,0 +1,266 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using DodoSSH.Client.Domain;
using DodoSSH.Client.Session;
namespace DodoSSH.Client.Shell.ViewModels;
/// <summary>
/// Reaching a host through Spelunk: the editor's half, the connect path's half, and a link from Spelunk.
/// </summary>
/// <remarks>
/// A file of its own because it is one feature and this class is long enough without it. Everything here
/// follows the relay, which is the other route a host can take: a tick box in the editor, a route opened by
/// the connect that will use it, no falling back to a direct dial, and a stated failure when the route
/// cannot be opened. See <see cref="HostSecret.Spelunk"/> and <see cref="SpelunkRoute"/>.
/// </remarks>
internal sealed partial class VaultViewModel
{
/// <summary>What opens a tunnel when no caller supplied something else.</summary>
/// <remarks>
/// Static and shared for the reason <see cref="DefaultReachability"/> is: it holds nothing but a
/// transport, and every tunnel is a fresh ticket and a fresh socket. Optional in the constructor so both
/// heads and every existing test go on meaning what they did, and a test that wants to see what was
/// opened passes a substitute.
/// </remarks>
private static readonly ISpelunkTunnel DefaultSpelunk = new SpelunkTunnel();
/// <summary>Whether the host being edited is reached through Spelunk.</summary>
/// <remarks>
/// Ticking it unticks the relay and the other way round, rather than letting both be ticked and refusing
/// the save: a host has one route, and <see cref="HostSecret.TryValidate"/> would only catch after the
/// fact what these two boxes can simply not express.
/// </remarks>
[ObservableProperty]
private bool editorThroughSpelunk;
/// <summary>The Spelunk API address in the editor, as typed.</summary>
[ObservableProperty]
private string editorSpelunkApi = string.Empty;
/// <summary>The Spelunk server id in the editor, as typed.</summary>
[ObservableProperty]
private string editorSpelunkServerId = string.Empty;
/// <summary>The credentials the editor offers as the Spelunk API key.</summary>
/// <remarks>
/// Credentials only, and no "none" entry: a route with no key cannot be opened, and nothing selected is
/// how a host made from a link says it has not been chosen yet. A key the host names that has since been
/// deleted keeps a placeholder, for the reason <see cref="BuildAuthenticationChoices"/> keeps one.
/// </remarks>
internal ObservableCollection<AuthenticationChoice> EditorSpelunkKeyChoices { get; } = [];
/// <summary>The credential chosen to hold the Spelunk API key.</summary>
[ObservableProperty]
private AuthenticationChoice? editorSelectedSpelunkKey;
/// <inheritdoc cref="DefaultSpelunk" />
private ISpelunkTunnel Spelunk => spelunk ?? DefaultSpelunk;
partial void OnEditorThroughSpelunkChanged(bool value)
{
if (value)
{
EditorRelayEnabled = false;
}
}
partial void OnEditorRelayEnabledChanged(bool value)
{
if (value)
{
EditorThroughSpelunk = false;
}
}
/// <summary>
/// Opens the route a host is reached by, or null for a host that is dialled.
/// </summary>
/// <remarks>
/// <para>
/// The one place that decides, for both transports: a shell comes through here from
/// <see cref="OpenThroughAsync"/>, and file transfer opens its own connection and comes through here from
/// the transfers screen — or that screen would fail for exactly the hosts a route exists for.
/// </para>
/// <para>
/// A host naming a route that cannot be opened is a refusal, never a quiet direct dial. See
/// <see cref="OpenRelayAsync"/> for the relay's half of that argument; Spelunk's is stronger still,
/// because a Spelunk host's address may be nothing that answers at all.
/// </para>
/// </remarks>
internal async Task<IConnectionRoute?> OpenRouteAsync(HostRowViewModel row, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(row);
if (row.Host.Spelunk is { } route)
{
return await OpenSpelunkTunnelAsync(row, route, cancellationToken).ConfigureAwait(true);
}
return row.Host.RelayEnabled
? await OpenRelayAsync(row.Label, row.EntityId, cancellationToken).ConfigureAwait(true)
: null;
}
/// <summary>
/// Opens a Spelunk tunnel to a host, with the key its credential holds.
/// </summary>
/// <remarks>
/// <para>
/// The key is read from the keychain at the moment of connecting, like every other secret the connect
/// path uses, and goes only to the API address the host names. A credential that has gone is refused in
/// words, exactly as a missing SSH credential is — see <see cref="TryBuildAuthentication"/>.
/// </para>
/// <para>
/// The port is the host's resolved one, group and all: it is the port the agent connects to on the
/// server's own loopback, which is where the SSH server listens whatever address the world sees.
/// </para>
/// </remarks>
private async Task<IConnectionRoute> OpenSpelunkTunnelAsync(
HostRowViewModel row,
SpelunkRoute route,
CancellationToken cancellationToken)
{
if (Credentials.FirstOrDefault(credential => credential.EntityId == route.ApiKeyCredentialId) is not { } key)
{
throw new SpelunkTunnelException(
$"'{row.Label}' is reached through Spelunk with an API key credential that is not in this "
+ "keychain any more. Edit the host to choose another one.");
}
return await Spelunk
.OpenAsync(route.ApiBase, route.ServerId, key.Credential.Password, row.Resolved.Port.Value, cancellationToken)
.ConfigureAwait(true);
}
/// <summary>
/// Does what a <c>dodossh://spelunk/connect</c> link asks, as far as it is allowed to.
/// </summary>
/// <returns>
/// The connection attempt when a saved host was found, so a caller that wants to can wait for it; a
/// completed task otherwise.
/// </returns>
/// <remarks>
/// <para>
/// <b>A saved host for that server on that Spelunk is connected to</b>, exactly as a tap on its row
/// would — a password prompt if it asks for one, a host key question if it has not been seen.
/// </para>
/// <para>
/// <b>Otherwise the editor opens on a new host, and nothing more.</b> The link came from outside, and
/// anything on this machine can make one; it must never be able to make this application connect
/// somewhere, or send an API key somewhere, that the user has not looked at and saved. So the host is
/// pre-filled — the name, the address its key will be pinned under, the Spelunk and the server — and
/// the user chooses how to log in and which credential holds the key, and presses SAVE.
/// </para>
/// <para>
/// <b>The key is pre-chosen only when another host already sends it to the same Spelunk.</b> That is a
/// convenience that cannot leak anything — the key already goes there — whereas guessing a key for a
/// Spelunk no host uses would be offering to send it to whatever address the link named.
/// </para>
/// </remarks>
internal Task OpenSpelunkLinkAsync(SpelunkLink link)
{
ArgumentNullException.ThrowIfNull(link);
if (Hosts.FirstOrDefault(row => row.Host.Spelunk?.IsFor(link.ApiBase, link.ServerId) is true) is { } saved)
{
return ConnectToRowCommand.ExecuteAsync(saved);
}
// Refused while another host is half-edited, as NewHost refuses it, and said the same way: the link
// is not worth somebody's unsaved host.
if (AHostEditorIsInTheWay())
{
return Task.CompletedTask;
}
NewHost();
EditorLabel = link.Name;
EditorHostname = link.Hostname;
EditorPort = HostSecret.DefaultPort;
EditorThroughSpelunk = true;
EditorSpelunkApi = link.ApiBase;
EditorSpelunkServerId = link.ServerId.ToString();
var knownKey = Hosts
.Select(row => row.Host.Spelunk)
.FirstOrDefault(route => route is not null && string.Equals(route.ApiBase, link.ApiBase, StringComparison.Ordinal))
?.ApiKeyCredentialId;
BuildSpelunkKeyChoices(Credentials.Any(credential => credential.EntityId == knownKey) ? knownKey : null);
IsHostPaneOpen = true;
Status = EditorSelectedSpelunkKey is null
? $"Adding {link.Name} from Spelunk at {link.ApiBase}. Choose how to log in and the credential "
+ "holding your Spelunk API key, then save."
: $"Adding {link.Name} from Spelunk at {link.ApiBase}. Choose how to log in, then save.";
return Task.CompletedTask;
}
/// <summary>
/// Whether a host needs this key or credential to connect: as its resolved binding, or as the credential
/// holding its Spelunk API key.
/// </summary>
/// <remarks>
/// The one question the deletion warning, the table's USED BY column and the detail pane's list all ask,
/// so a credential that is only somebody's Spelunk key is not deleted as though nothing used it. Spelunk
/// keys are named by the host itself and never inherited, so the stored route is the whole answer there.
/// </remarks>
private static bool Uses(HostRowViewModel row, ResolvedBindingKind kind, Guid entityId) =>
(row.Resolved.Binding is { } binding && binding.Kind == kind && binding.EntityId == entityId)
|| (kind is ResolvedBindingKind.Credential && row.Host.Spelunk?.ApiKeyCredentialId == entityId);
/// <summary>Puts a host's route into the editor, or clears it for a host that has none.</summary>
private void LoadEditorSpelunk(SpelunkRoute? route)
{
EditorThroughSpelunk = route is not null;
EditorSpelunkApi = route?.ApiBase ?? string.Empty;
EditorSpelunkServerId = route?.ServerId.ToString() ?? string.Empty;
BuildSpelunkKeyChoices(route?.ApiKeyCredentialId);
}
/// <summary>Fills the API key picker, keeping whatever the host names selectable.</summary>
private void BuildSpelunkKeyChoices(Guid? selectedId)
{
EditorSpelunkKeyChoices.Clear();
foreach (var credential in Credentials)
{
EditorSpelunkKeyChoices.Add(AuthenticationChoice.ForCredential(credential.EntityId, credential.Label));
}
if (selectedId is { } missing && EditorSpelunkKeyChoices.All(choice => choice.EntityId != missing))
{
EditorSpelunkKeyChoices.Add(AuthenticationChoice.Missing(AuthenticationKind.Credential, missing));
}
EditorSelectedSpelunkKey = EditorSpelunkKeyChoices.FirstOrDefault(choice => choice.EntityId == selectedId);
}
/// <summary>The editor's route, or null when the box is not ticked.</summary>
/// <remarks>
/// What cannot be read is written as empty rather than left out, so that
/// <see cref="HostSecret.TryValidate"/> says what is wrong with it — "needs the id of its Spelunk server"
/// — instead of the save quietly producing a host that is dialled directly. The address is normalised
/// here when it can be, so <c>https://api.example.com/</c> saves as the same Spelunk as the link's.
/// </remarks>
private SpelunkRoute? BuildSpelunkRoute()
{
if (!EditorThroughSpelunk)
{
return null;
}
return new SpelunkRoute
{
ApiBase = SpelunkRoute.TryNormalizeApiBase(EditorSpelunkApi, out var normalized, out _)
? normalized
: EditorSpelunkApi.Trim(),
ServerId = Guid.TryParse(EditorSpelunkServerId.Trim(), out var serverId) ? serverId : Guid.Empty,
ApiKeyCredentialId = EditorSelectedSpelunkKey?.EntityId ?? Guid.Empty,
};
}
}