Add an ssh client to Terminal, as an alternative to (or tunnel for) g2mirror

This commit is contained in:
James Babcock committed 2026-11-16 01:41:12 -08:00
1 parent ab692741f7
commit 2b75a9d66e
33 files changed
+4694 -99

No files matched your search

+12 -51
View File
@@ -1,5 +1,6 @@
import { openSocket } from "./socket";
import { openSocket, type SocketConnection, type SocketListener } from "./socket";
import { toUint8Array } from "../util/array-util";
import type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState } from "./terminal-session-types";
declare const android: any;
declare const java: any;
@@ -19,54 +20,7 @@ const LAUNCH_REPLY_TIMEOUT_MS = 10_000;
// otherwise treat the "\r" as a pasted newline instead of the Enter key.
const SUBMIT_DELAY_MS = 150;
export type G2MirrorSession = {
socket: string;
pid: number;
cwdHint: string;
/** Unix epoch ms of the terminal's last bell, or null if none observed. */
lastBellAt: number | null;
/**
* Unix epoch ms (host clock) of the app's last output, or null if none
* observed. Fresh to within the wrapper's 2s activity reporting interval
* while we're connected; compare against other host timestamps, not the
* phone clock (see the worker's local-receive-time activity tracking).
*/
lastOutputAt: number | null;
/** Window title the app last set (xterm OSC 0/2), or null if none observed. */
title: string | null;
};
export type G2MirrorPhase =
| "idle"
| "connecting"
| "connected" // handshake accepted; can list/attach
| "attached" // relaying to one session
| "failed";
export type G2MirrorState = {
phase: G2MirrorPhase;
status: string;
sessions: G2MirrorSession[];
attachedCommand: string;
/**
* server_name from the init success reply: a human-readable name for the
* machine the server runs on. "" until the handshake succeeds (or when an
* older server omits the field).
*/
serverName: string;
};
/** A page of archived scrollback lines (see PROTOCOL.md "Scrollback history"). */
export type G2MirrorHistoryReply = {
/** Absolute index of lines[0]; the page covers [start, start + lines.length). */
start: number;
/** Oldest index still retained by the wrapper (older requests return nothing). */
oldest: number;
/** Current splice point (next line to be archived). */
next: number;
/** Plain text, ANSI-stripped, oldest-to-newest. */
lines: string[];
};
export type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState };
export type G2MirrorClientOptions = {
/** TLS (g2mirrors:// → wss) vs plain (g2mirror:// → ws). */
@@ -77,6 +31,12 @@ export type G2MirrorClientOptions = {
deviceName: string;
cols: number;
rows: number;
/**
* Opens the websocket some other way than dialing host:port directly
* (e.g. through an SSH tunnel); `label` then names the endpoint in status
* lines instead of host:port.
*/
transport?: { open: (listener: SocketListener) => SocketConnection; label: string };
};
type TerminalDataKind = "snapshot" | "output";
@@ -180,7 +140,8 @@ export class G2MirrorClient {
this.stopped = false;
const generation = ++this.connectionGeneration;
const url = `${this.options.secure ? "wss" : "ws"}://${this.options.host}:${this.options.port}`;
this.setState("connecting", `Connecting to ${this.options.host}:${this.options.port}...`);
const transport = this.options.transport;
this.setState("connecting", `Connecting to ${transport ? transport.label : `${this.options.host}:${this.options.port}`}...`);
this.listenerProxy = {
onOpen: () => {
if (this.stopped || generation !== this.connectionGeneration) return;
@@ -208,7 +169,7 @@ export class G2MirrorClient {
},
};
try {
this.ws = openSocket(url, this.listenerProxy);
this.ws = transport ? transport.open(this.listenerProxy!) : openSocket(url, this.listenerProxy);
} catch (error) {
this.ws = null;
this.handleConnectionLost(`Connection failed: ${shortenError(String((error as Error)?.message ?? error))}`);
+153
View File
@@ -0,0 +1,153 @@
/**
* Platform-independent half of the SSH transport bindings (ssh.ts /
* ssh.ios.ts): the types the app uses and the decoding of the Go
* transport's events (native/ssh/faceclawssh.go, Listener).
*/
/** Where and as whom to connect. */
export type SshEndpoint = {
host: string;
port: number;
user: string;
/** Pinned host keys (SSH wire format, base64). Empty: first connection reports hostkey-unknown. */
hostKeys: string[];
/** Saved password, or "" to try only the device key. */
password: string;
/** Offer the device's client key. */
useKey: boolean;
};
export type SshChannelSpec =
| {
/** Run a command on the host; text is exchanged a line at a time. */
type: "exec";
command: string;
}
| {
/** WebSocket to a URL resolved on the host's side (e.g. ws://127.0.0.1:8737/). */
type: "websocket";
url: string;
};
export type SshHostKey = {
/** SSH key type, e.g. "ssh-ed25519". */
type: string;
/** OpenSSH-style "SHA256:..." fingerprint. */
fingerprint: string;
/** SSH wire format, base64: the value to pin in SshEndpoint.hostKeys. */
key: string;
};
export type SshFailureKind =
| "hostkey-unknown"
| "hostkey-mismatch"
| "auth"
| "network"
| "channel"
| "config"
| "internal";
export type SshFailure = {
kind: SshFailureKind;
message: string;
/** For hostkey-*: the key the host presented. */
hostKey?: SshHostKey;
/** For auth: the host takes passwords / we sent one / we offered our key. */
passwordAllowed?: boolean;
passwordTried?: boolean;
keyTried?: boolean;
};
export type SshClosed = {
/** Exec channels: the command's exit status (and signal, if killed). */
exitStatus?: number;
signal?: string;
/** WebSocket channels: the close frame's code and reason. */
code?: number;
reason?: string;
};
export type SshChannelListener = {
onOpen(): void;
onText(text: string): void;
onStderr?(line: string): void;
/** Terminal: the channel ended normally. */
onClosed(info: SshClosed): void;
/** Terminal: the channel couldn't open or was lost. */
onFailure(failure: SshFailure): void;
};
export type SshChannel = {
/** Queue a websocket text frame / an exec stdin line. False once closed. */
send(text: string): boolean;
/** Flush queued sends, then end the channel. No events follow. */
close(): void;
};
export type SshClientKey = {
/** "ecdsa-sha2-nistp256 AAAA... comment", for ~/.ssh/authorized_keys. */
authorizedKey: string;
fingerprint: string;
};
/** Build the Go transport's openSpec JSON. */
export function encodeSshSpec(endpoint: SshEndpoint, channel: SshChannelSpec): string {
return JSON.stringify({
host: endpoint.host,
port: endpoint.port,
user: endpoint.user,
password: endpoint.password,
hostKeys: endpoint.hostKeys,
useKey: endpoint.useKey,
channel,
});
}
/** Route one transport event to the listener. Unknown kinds are ignored. */
export function dispatchSshEvent(listener: SshChannelListener, kind: string, payload: string): void {
switch (kind) {
case "open":
listener.onOpen();
return;
case "text":
listener.onText(payload);
return;
case "stderr":
listener.onStderr?.(payload);
return;
case "closed":
listener.onClosed(parseJson(payload) ?? {});
return;
case "failure": {
const failure = parseJson(payload);
listener.onFailure(
failure && typeof failure.kind === "string"
? failure
: { kind: "internal", message: `bad failure payload: ${payload}` },
);
return;
}
}
}
function parseJson(text: string): any {
try {
return JSON.parse(text);
} catch {
return null;
}
}
/** Human summary of a failure for status lines. */
export function describeSshFailure(failure: SshFailure): string {
switch (failure.kind) {
case "hostkey-unknown":
return "Host key not yet trusted.";
case "hostkey-mismatch":
return "HOST KEY CHANGED; refusing to connect.";
case "auth":
return failure.message || "Authentication failed.";
default:
return failure.message || failure.kind;
}
}
+69
View File
@@ -0,0 +1,69 @@
import {
dispatchSshEvent,
encodeSshSpec,
type SshChannel,
type SshChannelListener,
type SshChannelSpec,
type SshClientKey,
type SshEndpoint,
} from "./ssh-common";
export * from "./ssh-common";
declare const FaceclawSshChannel: any;
declare const FaceclawSshKeys: any;
// Like socket.ios.ts: Go delivers events on its own threads, so the native
// side queues them and this isolate drains the queue on a timer.
const POLL_INTERVAL_MS = 25;
/** iOS SSH transport: FaceclawSshChannel (ObjC) over the gomobile-bound Go package in native/ssh. */
export function openSshChannel(endpoint: SshEndpoint, channel: SshChannelSpec, listener: SshChannelListener): SshChannel {
const native = FaceclawSshChannel.alloc().initWithSpecUseKey(encodeSshSpec(endpoint, channel), endpoint.useKey);
let ended = false;
const stop = () => {
if (ended) return;
ended = true;
clearInterval(timer);
native.close();
};
const timer = setInterval(() => {
const events = JSON.parse(String(native.takeEvents())) as Array<{ kind: string; payload: string }>;
for (const event of events) {
if (ended) break;
if (event.kind === "closed" || event.kind === "failure") {
// Terminal events: stop polling, then deliver.
ended = true;
clearInterval(timer);
}
dispatchSshEvent(listener, event.kind, event.payload);
}
}, POLL_INTERVAL_MS);
return {
send: (text) => !ended && native.send(text) === true,
close: stop,
};
}
export function sshClientKey(comment: string): SshClientKey {
const authorizedKey = FaceclawSshKeys.authorizedKeyWithComment(comment);
const fingerprint = FaceclawSshKeys.fingerprint();
if (!authorizedKey || !fingerprint) throw new Error("Could not create the SSH client key.");
return { authorizedKey: String(authorizedKey), fingerprint: String(fingerprint) };
}
export function getSshSecret(id: string): string {
return String(FaceclawSshKeys.secretForId(id) ?? "");
}
export function setSshSecret(id: string, value: string): void {
FaceclawSshKeys.setSecretForId(value, id);
}
export function removeSshSecret(id: string): void {
FaceclawSshKeys.removeSecretForId(id);
}
export function copyToPhoneClipboard(_label: string, text: string): void {
FaceclawSshKeys.copyToClipboard(text);
}
+66
View File
@@ -0,0 +1,66 @@
import { Utils } from "@nativescript/core";
import {
dispatchSshEvent,
encodeSshSpec,
type SshChannel,
type SshChannelListener,
type SshChannelSpec,
type SshClientKey,
type SshEndpoint,
} from "./ssh-common";
export * from "./ssh-common";
declare const com: any;
/**
* Android SSH transport: FaceclawSshChannel (Kotlin) over the gomobile-bound
* Go package in native/ssh. Callable from the main isolate or a worker;
* events arrive on the calling isolate's thread.
*/
export function openSshChannel(endpoint: SshEndpoint, channel: SshChannelSpec, listener: SshChannelListener): SshChannel {
let closed = false;
const proxy = new com.faceclaw.app.FaceclawSshListener({
onEvent: (kind: string, payload: string) => {
if (closed) return;
dispatchSshEvent(listener, String(kind), payload == null ? "" : String(payload));
},
});
const native = new com.faceclaw.app.FaceclawSshChannel(encodeSshSpec(endpoint, channel), endpoint.useKey, proxy);
return {
send: (text) => !closed && native.send(text) === true,
close: () => {
if (closed) return;
closed = true;
native.close();
},
};
}
function context(): any {
return Utils.android.getApplicationContext();
}
/** The device's SSH client key (generated on first use). */
export function sshClientKey(comment: string): SshClientKey {
return {
authorizedKey: String(com.faceclaw.app.FaceclawSshKeys.authorizedKey(comment)),
fingerprint: String(com.faceclaw.app.FaceclawSshKeys.fingerprint()),
};
}
export function getSshSecret(id: string): string {
return String(com.faceclaw.app.FaceclawSshKeys.getSecret(context(), id) ?? "");
}
export function setSshSecret(id: string, value: string): void {
com.faceclaw.app.FaceclawSshKeys.setSecret(context(), id, value);
}
export function removeSshSecret(id: string): void {
com.faceclaw.app.FaceclawSshKeys.removeSecret(context(), id);
}
export function copyToPhoneClipboard(label: string, text: string): void {
com.faceclaw.app.FaceclawSshKeys.copyToClipboard(context(), label, text);
}
+59
View File
@@ -0,0 +1,59 @@
/**
* Session-list and connection-state types shared by the Terminal app's
* backends (g2mirror-client.ts, apps/terminal/tmux-client.ts). Kept free of
* platform imports so the tmux client can be unit-tested under node.
*/
export type G2MirrorSession = {
socket: string;
pid: number;
cwdHint: string;
/** Unix epoch ms of the terminal's last bell, or null if none observed. */
lastBellAt: number | null;
/**
* Unix epoch ms (host clock) of the app's last output, or null if none
* observed. Fresh to within the wrapper's 2s activity reporting interval
* while we're connected; compare against other host timestamps, not the
* phone clock (see the worker's local-receive-time activity tracking).
*/
lastOutputAt: number | null;
/** Window title the app last set (xterm OSC 0/2), or null if none observed. */
title: string | null;
};
export type G2MirrorPhase =
| "idle"
| "connecting"
| "connected" // handshake accepted; can list/attach
| "attached" // relaying to one session
| "failed";
export type G2MirrorState = {
phase: G2MirrorPhase;
status: string;
sessions: G2MirrorSession[];
attachedCommand: string;
/**
* server_name from the init success reply: a human-readable name for the
* machine the server runs on. "" until the handshake succeeds (or when an
* older server omits the field).
*/
serverName: string;
/**
* False when reconnecting can't help until the user changes something on
* the host (e.g. tmux missing or too old). Absent means retryable.
*/
retryable?: boolean;
};
/** A page of archived scrollback lines (see PROTOCOL.md "Scrollback history"). */
export type G2MirrorHistoryReply = {
/** Absolute index of lines[0]; the page covers [start, start + lines.length). */
start: number;
/** Oldest index still retained by the wrapper (older requests return nothing). */
oldest: number;
/** Current splice point (next line to be archived). */
next: number;
/** Plain text, ANSI-stripped, oldest-to-newest. */
lines: string[];
};