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

+89 -7
View File
@@ -1,13 +1,21 @@
import { getStringSetting, setStringSetting } from "../../native/settings-store";
/**
* Terminal-app connection registry: the g2mirror hosts the app knows about,
* stored as JSON under one settings key so every isolate sees the same list
* and change notifications ride the ordinary settings-store channel.
* Terminal-app connection registry: the hosts the app knows about, stored as
* JSON under one settings key so every isolate sees the same list and change
* notifications ride the ordinary settings-store channel.
*
* A connection is entered as a g2mirror:// connection string (the same form
* g2mirror-view accepts): g2mirror://<token>@<host>[:port] for plain
* websockets (default port 8737), g2mirrors://... for TLS (default 443).
* A connection is entered as a connection string:
* - g2mirror://<token>@<host>[:port]: a g2mirror server reached directly
* (the same form g2mirror-view accepts) over a plain websocket (default
* port 8737); g2mirrors://... for TLS (default 443).
* - ssh://<user>@<host>[:port]: tmux on an SSH host (default port 22).
* - ssh://<user>@<host>[:port]?g2mirror=<token>[@<host>[:port]]: a g2mirror
* server tunnelled over SSH; the address after the token is where the
* server listens as seen from the SSH host (default 127.0.0.1:8737).
* SSH connections pin the host's key (hostKeys, trusted on first connection
* after the user checks its fingerprint); their passwords live in the
* platform keystore (app/native/ssh), not here.
*/
export const TERMINAL_CONNECTIONS_KEY = "terminal.connections";
@@ -25,6 +33,8 @@ export type TerminalConnection = {
serverName: string | null;
/** Auto-connect while the Terminal app is open. Toggled by Connect/Disconnect. */
enabled: boolean;
/** SSH connections: trusted host keys (SSH wire format, base64). */
hostKeys: string[];
};
export type ParsedConnectionString = {
@@ -54,8 +64,79 @@ export function parseConnectionString(url: string): ParsedConnectionString | nul
return { secure, host, port, authToken };
}
/** The host[:port] part of a connection string; "" if it doesn't parse. */
export type ParsedSshConnection = {
user: string;
host: string;
port: number;
} & (
| { mode: "tmux" }
| {
mode: "g2mirror";
authToken: string;
/** Where g2mirror-server listens, from the SSH host's point of view. */
targetHost: string;
targetPort: number;
}
);
function decodeComponent(text: string): string {
try {
return decodeURIComponent(text);
} catch {
return text;
}
}
/** Parse an ssh://user@host[:port][?g2mirror=token[@host[:port]]] string; null if malformed. */
export function parseSshConnectionString(url: string): ParsedSshConnection | null {
const match = /^ssh:\/\/([^@\s/?]+)@(\[[^\]\s]+\]|[^:/@\s?]+)(?::(\d+))?\/?(?:\?(.*))?$/.exec(url.trim());
if (!match) return null;
const user = decodeComponent(match[1]!);
const host = match[2]!.replace(/^\[(.*)\]$/, "$1");
const port = match[3] ? parseInt(match[3], 10) : 22;
if (!user || !(port >= 1 && port <= 65535)) return null;
const params = new Map<string, string>();
for (const part of (match[4] ?? "").split("&").filter(Boolean)) {
const equals = part.indexOf("=");
if (equals < 0) return null;
params.set(part.slice(0, equals), decodeComponent(part.slice(equals + 1)));
}
for (const key of params.keys()) {
if (key !== "g2mirror") return null;
}
const g2mirror = params.get("g2mirror");
if (g2mirror === undefined) return { user, host, port, mode: "tmux" };
// token[@host[:port]], split at the last "@" so the token may contain one.
const at = g2mirror.lastIndexOf("@");
const authToken = at < 0 ? g2mirror : g2mirror.slice(0, at);
const target = at < 0 ? "" : g2mirror.slice(at + 1);
const targetMatch = /^(\[[^\]\s]+\]|[^:\s]*)(?::(\d+))?$/.exec(target);
if (!authToken || !targetMatch) return null;
const targetHost = targetMatch[1] || "127.0.0.1";
const targetPort = targetMatch[2] ? parseInt(targetMatch[2], 10) : 8737;
if (!(targetPort >= 1 && targetPort <= 65535)) return null;
return { user, host, port, mode: "g2mirror", authToken, targetHost, targetPort };
}
export type ParsedAnyConnection =
| ({ kind: "g2mirror" } & ParsedConnectionString)
| ({ kind: "ssh" } & ParsedSshConnection);
/** Parse any supported connection string; null if it's none of them. */
export function parseAnyConnectionString(url: string): ParsedAnyConnection | null {
const direct = parseConnectionString(url);
if (direct) return { kind: "g2mirror", ...direct };
const ssh = parseSshConnectionString(url);
return ssh ? { kind: "ssh", ...ssh } : null;
}
/** The [user@]host[:port] part of a connection string (never a token); "" if it doesn't parse. */
export function connectionStringHostLabel(url: string): string {
const ssh = parseSshConnectionString(url);
if (ssh) {
const host = ssh.host.includes(":") ? `[${ssh.host}]` : ssh.host;
return `${ssh.user}@${host}${ssh.port === 22 ? "" : `:${ssh.port}`}`;
}
const parsed = parseConnectionString(url);
if (!parsed) return "";
const defaultPort = parsed.secure ? 443 : 8737;
@@ -79,6 +160,7 @@ export function loadConnections(): TerminalConnection[] {
url: String(item?.url ?? ""),
serverName: typeof item?.serverName === "string" && item.serverName ? item.serverName : null,
enabled: item?.enabled !== false,
hostKeys: Array.isArray(item?.hostKeys) ? item.hostKeys.filter((key: unknown) => typeof key === "string") : [],
}))
.filter((connection) => connection.id.length > 0 && connection.url.length > 0);
} catch {
+461 -36
View File
@@ -16,11 +16,17 @@
* Each view has its own websocket connection (the protocol allows one attached
* session per connection) and its own xterm emulator.
*
* Connections are g2mirror://<token>@<host>[:port] strings (g2mirrors:// for
* TLS), stored as JSON in the settings store (see connections.ts). Each
* enabled connection gets a control websocket that backs the session list and
* carries unsolicited bell/title notifications; control connections live as
* long as the worker so bells keep flowing even if the hub window is closed.
* Connections are connection strings stored as JSON in the settings store
* (see connections.ts): g2mirror://<token>@<host>[:port] for a g2mirror
* server (g2mirrors:// for TLS), ssh://<user>@<host> for tmux over SSH
* (TmuxClient), or ssh://<user>@<host>?g2mirror=<token> for a g2mirror server
* tunnelled over SSH. Each enabled connection gets a control client that
* backs the session list and carries bell/title/activity notifications;
* control connections live as long as the worker so bells keep flowing even
* if the hub window is closed. SSH connections that need the user (an
* unverified or changed host key, a password, an unauthorized key) record
* the failure on the control (sshIssue) and offer a page that resolves it
* instead of retrying.
* The host's server_name (from the init reply) is cached per connection and
* used as its display name, falling back to the connection string's
* host[:port] before the first successful handshake.
@@ -57,7 +63,22 @@ import { getActiveDisplay } from "../../native/active-display";
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
import type { KeyEvent } from "../../g2/keyboard/keys";
import { encodeTerminalKey, terminalScrollbackKey } from "./terminal-keys";
import { G2MirrorClient, type G2MirrorClientOptions, type G2MirrorSession, type G2MirrorState } from "../../native/g2mirror-client";
import { G2MirrorClient, type G2MirrorSession, type G2MirrorState } from "../../native/g2mirror-client";
import type { TerminalClient } from "./terminal-client";
import { TmuxClient, type OpenLineChannel } from "./tmux-client";
import {
copyToPhoneClipboard,
describeSshFailure,
getSshSecret,
openSshChannel,
removeSshSecret,
setSshSecret,
sshClientKey,
type SshEndpoint,
type SshFailure,
type SshHostKey,
} from "../../native/ssh";
import { wrapText } from "../../graphics/textwrap";
import { onSettingsStoreChanged } from "../../native/settings-store";
import { clamp } from "../../util/numeric-util";
import {
@@ -66,12 +87,22 @@ import {
terminalDisplayLayoutSetting,
terminalLaunchPresetsSetting,
terminalNewConnectionSetting,
terminalSshPasswordSetting,
terminalWakeOnBellSetting,
textSettingMenuItem,
toggleSettingMenuItem,
} from "../../ui/dashboard-settings";
import { terminalFontPickerMenuItem } from "../../ui/font-picker";
import { connectionDisplayName, loadConnections, parseConnectionString, saveConnections, TERMINAL_CONNECTIONS_KEY, updateConnection, type TerminalConnection } from "./connections";
import {
connectionDisplayName,
connectionStringHostLabel,
loadConnections,
parseAnyConnectionString,
saveConnections,
TERMINAL_CONNECTIONS_KEY,
updateConnection,
type TerminalConnection,
} from "./connections";
import { TerminalEmulator } from "./terminal-emulator";
import { drawSubmenuIndicator, submenuItem, type MenuItem } from "../../ui/menu";
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
@@ -114,6 +145,10 @@ const RECONNECT_MAX_DELAY_MS = 60_000;
const NEW_CONNECTION_DRAFT_KEY = "terminal.newConnectionDraft";
// Storage key of terminalLaunchPresetsSetting, edited from the window menu.
const LAUNCH_PRESETS_KEY = "terminal.launchPresets";
// Storage key of terminalSshPasswordSetting (the password page's draft).
const SSH_PASSWORD_DRAFT_KEY = "terminal.sshPasswordDraft";
// Comment on this device's SSH public key in authorized_keys.
const SSH_KEY_COMMENT = "faceclaw";
type BaseWindow = {
windowId: string;
@@ -150,10 +185,24 @@ type BaseWindow = {
/**
* What the hub window is showing: the session list, the Manage Connections
* section, or the Add-connection screen (type the g2mirror:// string on the
* phone, click to save).
* section, the Add-connection screen (type the connection string on the
* phone, click to save), or a page of text with a click action (verify a
* host key, enter a password, show this device's SSH key).
*/
type HubMode = "sessions" | "connections" | "add";
type HubMode = "sessions" | "connections" | "add" | "page";
type HubPage = {
title: string;
/** Body text, wrapped to the window; re-read on every paint. */
body: () => string;
/** Bottom hint line. */
hint: string;
onClick?: () => void;
/** Double-click. */
onBack: () => void;
/** Runs whenever the page goes away (back, click, window closed). */
onLeave?: () => void;
};
type HubWindow = BaseWindow & {
kind: "hub";
@@ -170,6 +219,8 @@ type HubWindow = BaseWindow & {
sessionOrder: string[];
/** Parse-failure message shown on the Add-connection screen. */
addError: string;
/** The page shown in mode "page". */
page: HubPage | null;
};
type ViewWindow = BaseWindow & {
@@ -188,7 +239,7 @@ type ViewWindow = BaseWindow & {
label: string;
/** Sidebar-icon character (">3"); "" if every glyph was taken at open time. */
glyph: string;
client: G2MirrorClient;
client: TerminalClient;
emulator: TerminalEmulator;
receivedData: boolean;
attachRequested: boolean;
@@ -222,8 +273,8 @@ type PendingView = {
socket: string;
label: string;
glyph: string;
/** Client options captured when the view was requested from a live control. */
options: G2MirrorClientOptions;
/** How to make the view's client, captured when it was requested from a live control. */
options: ClientRecipe;
};
const windows = new Map<string, TerminalWindow>();
@@ -304,7 +355,13 @@ let screenOn = true;
*/
type ControlConnection = {
config: TerminalConnection;
client: G2MirrorClient | null;
client: TerminalClient | null;
/**
* An SSH failure only the user can fix (host key to verify, password or
* key needed). Shown on the host's heading with a row that opens the fix;
* reconnects wait for it. Cleared on a successful connection.
*/
sshIssue: SshFailure | null;
state: G2MirrorState | null;
unsubscribers: Array<() => void>;
reconnectTimer: ReturnType<typeof setTimeout> | null;
@@ -513,7 +570,8 @@ onSettingsStoreChanged((key) => {
reportIdle();
return;
case NEW_CONNECTION_DRAFT_KEY:
// Live keystrokes from the phone editor; repaint the add screen.
case SSH_PASSWORD_DRAFT_KEY:
// Live keystrokes from the phone editor; repaint the add/password screen.
renderHubWindows();
return;
case "terminal.autoReconnect":
@@ -587,6 +645,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport
list: null,
sessionOrder: [],
addError: "",
page: null,
});
// The hub carries the app's assistant tools; declare them once it exists.
post({ type: "set-tools", windowId, tools: TERMINAL_TOOLS });
@@ -619,6 +678,10 @@ function closeWindow(windowId: string): void {
// Window closed mid-add: shut the phone editor down.
endAddConnection(window);
}
if (window.kind === "hub" && window.mode === "page") {
// Likewise for a page's phone editor (the password draft).
closeHubPage(window, "sessions");
}
// Likewise for a setting being edited from the window menu.
window.menu?.close();
windows.delete(windowId);
@@ -636,17 +699,120 @@ function closeWindow(windowId: string): void {
}
}
/** Client options for a connection string; null if the string doesn't parse. */
function clientOptionsFor(connection: TerminalConnection): G2MirrorClientOptions | null {
const parsed = parseConnectionString(connection.url);
/**
* How to make clients for a connection: "g2mirror" dials a g2mirror server
* directly, "ssh-g2mirror" reaches one through an SSH tunnel, "tmux" runs
* tmux control mode over SSH.
*/
type ClientRecipe = {
kind: "g2mirror" | "ssh-g2mirror" | "tmux";
/**
* `role` "control" watches bells (tmux keeps the bell bookkeeping for that
* client only). `onSshFailure` hears why an SSH channel failed.
*/
create(cols: number, rows: number, role: "control" | "view", onSshFailure?: (failure: SshFailure) => void): TerminalClient;
};
/** Client recipe for a connection string; null if the string doesn't parse. */
function clientOptionsFor(connection: TerminalConnection): ClientRecipe | null {
const parsed = parseAnyConnectionString(connection.url);
if (!parsed) return null;
if (parsed.kind === "g2mirror") {
const { secure, host, port, authToken } = parsed;
return {
kind: "g2mirror",
create: (cols, rows) => new G2MirrorClient({ secure, host, port, authToken, deviceName: DEVICE_NAME, cols, rows }),
};
}
const connectionId = connection.id;
const label = connectionStringHostLabel(connection.url);
// Read at every channel open, so a newly trusted key or saved password
// applies to the next (re)connect, views included.
const endpoint = (): SshEndpoint => ({
host: parsed.host,
port: parsed.port,
user: parsed.user,
hostKeys: loadConnections().find((candidate) => candidate.id === connectionId)?.hostKeys ?? [],
password: getSshSecret(sshPasswordSecretId(connectionId)),
useKey: true,
});
if (parsed.mode === "g2mirror") {
const { authToken, targetHost, targetPort } = parsed;
const urlHost = targetHost.includes(":") && !targetHost.startsWith("[") ? `[${targetHost}]` : targetHost;
const url = `ws://${urlHost}:${targetPort}/`;
return {
kind: "ssh-g2mirror",
create: (cols, rows, _role, onSshFailure) =>
new G2MirrorClient({
secure: false,
host: targetHost,
port: targetPort,
authToken,
deviceName: DEVICE_NAME,
cols,
rows,
transport: {
label: `${label} over SSH`,
open: (listener) => {
const channel = openSshChannel(endpoint(), { type: "websocket", url }, {
onOpen: () => listener.onOpen(),
onText: (text) => listener.onTextMessage(text),
onClosed: (info) => listener.onClosed(info.code ?? 1000, info.reason ?? ""),
onFailure: (failure) => {
onSshFailure?.(failure);
listener.onFailure(describeSshFailure(failure));
},
});
return { sendText: (text) => channel.send(text), sendBinary: () => false, close: () => channel.close() };
},
},
}),
};
}
return {
...parsed,
deviceName: DEVICE_NAME,
...viewGrid(),
kind: "tmux",
create: (cols, rows, role, onSshFailure) => {
const openChannel: OpenLineChannel = (command, listener) =>
openSshChannel(endpoint(), { type: "exec", command }, {
onOpen: () => listener.onOpen(),
onText: (line) => listener.onLine(line),
onStderr: (line) => listener.onStderr(line),
onClosed: (info) => listener.onClosed(info.exitStatus ?? null),
onFailure: (failure) => {
onSshFailure?.(failure);
listener.onFailure(describeSshFailure(failure));
},
});
return new TmuxClient({ openChannel, label, cols, rows, stateKey: role === "control" ? connectionId : "" });
},
};
}
function sshPasswordSecretId(connectionId: string): string {
return `terminal.password.${connectionId}`;
}
/** Failures that retrying can't fix: the user has to verify a key or supply credentials. */
function sshFailureNeedsUser(failure: SshFailure): boolean {
return failure.kind === "hostkey-unknown" || failure.kind === "hostkey-mismatch" || failure.kind === "auth";
}
/**
* A control's SSH channel failed. If the user has to act, remember why, and
* if they're looking at the hub's lists, open the page that fixes it.
*/
function noteSshFailure(control: ControlConnection, failure: SshFailure): void {
if (!sshFailureNeedsUser(failure) || controls.get(control.config.id) !== control || !control.client) return;
control.sshIssue = failure;
renderHubWindows();
for (const window of windows.values()) {
if (window.kind === "hub" && window.foreground && (window.mode === "sessions" || window.mode === "connections")) {
openSshIssuePage(window, control);
break;
}
}
}
/**
* Reconcile the live control clients with the stored connection list: start
* enabled connections, stop disabled or removed ones, restart ones whose
@@ -672,6 +838,7 @@ function syncControlsFromSettings(): void {
control = {
config: connection,
client: null,
sshIssue: null,
state: null,
unsubscribers: [],
reconnectTimer: null,
@@ -693,12 +860,13 @@ function syncControlsFromSettings(): void {
function startControl(control: ControlConnection): void {
stopControl(control);
const options = clientOptionsFor(control.config);
if (!options) {
const recipe = clientOptionsFor(control.config);
if (!recipe) {
control.state = null;
return;
}
const client = new G2MirrorClient(options);
const grid = viewGrid();
const client = recipe.create(grid.cols, grid.rows, "control", (failure) => noteSshFailure(control, failure));
const connectionId = control.config.id;
control.client = client;
control.state = client.state();
@@ -712,6 +880,7 @@ function startControl(control: ControlConnection): void {
control.state = state;
if (state.phase === "connected") {
control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS;
control.sshIssue = null;
maybeCacheServerName(control, state.serverName);
}
if (state.phase === "failed") scheduleControlReconnect(control);
@@ -786,6 +955,8 @@ function scheduleControlReconnect(control: ControlConnection): void {
if (!terminalAutoReconnectSetting.get()) return;
if (windows.size === 0 && !hasTerminalBackgroundWork()) return;
if (!control.config.enabled) return;
// Waiting on the user (host key, password) or on the host (no usable tmux).
if (control.sshIssue || control.state?.retryable === false) return;
const delayMs = control.reconnectDelayMs;
control.reconnectDelayMs = Math.min(control.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS);
control.reconnectTimer = setTimeout(() => {
@@ -952,7 +1123,7 @@ function createViewWindow(
const cell = getTerminalFontConfig();
const gridCols = Math.floor(viewport.width / cell.cellWidth);
const gridRows = Math.floor(viewport.height / cell.cellHeight);
const client = new G2MirrorClient({ ...view.options, cols: gridCols, rows: gridRows });
const client = view.options.create(gridCols, gridRows, "view");
const window: ViewWindow = {
kind: "view",
hub: null,
@@ -1247,6 +1418,11 @@ function handleInput(window: TerminalWindow, event: InputEvent, frameId: number)
renderAndSubmit(window, frameId);
return;
}
if (window.kind === "hub" && window.mode === "page") {
window.page?.onBack();
renderAndSubmit(window, frameId);
return;
}
if (window.kind === "hub" && window.mode === "connections") {
setHubMode(window, "sessions");
renderAndSubmit(window, frameId);
@@ -1424,6 +1600,154 @@ function setHubMode(window: HubWindow, mode: HubMode): void {
window.addError = "";
}
function openHubPage(window: HubWindow, page: HubPage): void {
if (window.mode === "add") endAddConnection(window);
if (window.mode === "page") window.page?.onLeave?.();
window.page = page;
window.mode = "page";
scheduleRender(window);
}
/** Leave the current page (if any) for `mode`. */
function closeHubPage(window: HubWindow, mode: HubMode): void {
const page = window.page;
window.page = null;
page?.onLeave?.();
setHubMode(window, mode);
scheduleRender(window);
}
/** The list a page returns to: the one it was opened from. */
function hubListMode(window: HubWindow): HubMode {
return window.mode === "connections" ? "connections" : "sessions";
}
function openSshIssuePage(window: HubWindow, control: ControlConnection): void {
const issue = control.sshIssue;
if (!issue) return;
if (issue.kind === "hostkey-unknown" && issue.hostKey) {
openHostKeyPage(window, control, issue.hostKey);
} else if (issue.kind === "hostkey-mismatch" && issue.hostKey) {
openHostKeyChangedPage(window, control, issue.hostKey);
} else if (issue.kind === "auth" && issue.passwordAllowed) {
openPasswordPage(window, control, Boolean(issue.passwordTried));
} else if (issue.kind === "auth") {
openClientKeyPage(window, `${connectionDisplayName(control.config)} didn't accept this device's key (and doesn't take passwords).\n`);
}
}
function hostKeyTypeName(type: string): string {
if (type === "ssh-ed25519") return "ED25519";
if (type.startsWith("ecdsa-")) return "ECDSA";
if (type === "ssh-rsa") return "RSA";
return type;
}
function hostKeyFile(type: string): string {
if (type === "ssh-ed25519") return "/etc/ssh/ssh_host_ed25519_key.pub";
if (type.startsWith("ecdsa-")) return "/etc/ssh/ssh_host_ecdsa_key.pub";
return "/etc/ssh/ssh_host_rsa_key.pub";
}
/** First connection to an SSH host: show the key's fingerprint; click trusts it. */
function openHostKeyPage(window: HubWindow, control: ControlConnection, hostKey: SshHostKey): void {
const returnMode = hubListMode(window);
openHubPage(window, {
title: "Verify host key",
body: () =>
`First connection to ${connectionStringHostLabel(control.config.url)}. Its ${hostKeyTypeName(hostKey.type)} host key fingerprint is:\n` +
`${hostKey.fingerprint}\n\n` +
`To check it, run this on the host and compare:\nssh-keygen -lf ${hostKeyFile(hostKey.type)}`,
hint: `click trust and connect ${GESTURE_DOUBLE_CLICK} cancel`,
onClick: () => {
const hostKeys = [...control.config.hostKeys.filter((key) => key !== hostKey.key), hostKey.key];
control.config.hostKeys = hostKeys;
updateConnection(control.config.id, { hostKeys });
control.sshIssue = null;
closeHubPage(window, returnMode);
connectControl(control);
},
onBack: () => closeHubPage(window, returnMode),
});
}
function openHostKeyChangedPage(window: HubWindow, control: ControlConnection, hostKey: SshHostKey): void {
const returnMode = hubListMode(window);
openHubPage(window, {
title: "HOST KEY CHANGED",
body: () =>
`${connectionStringHostLabel(control.config.url)} presented a different host key than the one trusted before: ` +
`${hostKeyTypeName(hostKey.type)} ${hostKey.fingerprint}\n\n` +
"Someone may be intercepting the connection, so Faceclaw won't connect. If the host was reinstalled or its keys " +
'were regenerated, use "Forget host key" on this connection in Manage Connections, then verify the new fingerprint.',
hint: `${GESTURE_DOUBLE_CLICK} back`,
onBack: () => closeHubPage(window, returnMode),
});
}
/** Ask for the host's password on the phone (masked editor); click saves it and connects. */
function openPasswordPage(window: HubWindow, control: ControlConnection, rejected: boolean): void {
const returnMode = hubListMode(window);
terminalSshPasswordSetting.set("");
post({ type: "start-text-setting-edit", settingId: terminalSshPasswordSetting.id });
openHubPage(window, {
title: "SSH password",
body: () => {
const typed = terminalSshPasswordSetting.get();
return (
(rejected ? "The host refused the saved password.\n" : "") +
`Type the password for ${connectionStringHostLabel(control.config.url)} in the phone app, then click to connect. ` +
"It is saved encrypted on this phone.\n\n" +
(typed ? "*".repeat(Math.min(typed.length, 32)) : "(nothing typed yet)")
);
},
hint: `click connect ${GESTURE_DOUBLE_CLICK} cancel`,
onClick: () => {
const password = terminalSshPasswordSetting.get();
if (!password) return;
setSshSecret(sshPasswordSecretId(control.config.id), password);
control.sshIssue = null;
closeHubPage(window, returnMode);
connectControl(control);
},
onBack: () => closeHubPage(window, returnMode),
onLeave: () => {
terminalSshPasswordSetting.set("");
post({ type: "end-text-setting-edit" });
},
});
}
/** This device's SSH public key (the private half never leaves the keystore); click copies it. */
function openClientKeyPage(window: HubWindow, intro = ""): void {
const returnMode = hubListMode(window);
let key: { authorizedKey: string; fingerprint: string } | null = null;
let error = "";
try {
key = sshClientKey(SSH_KEY_COMMENT);
} catch (caught) {
error = String((caught as Error)?.message ?? caught);
}
let copied = false;
openHubPage(window, {
title: "This device's SSH key",
body: () =>
key
? `${intro}Add this line to ~/.ssh/authorized_keys on each host to log in with this phone's key:\n` +
`${key.authorizedKey}\n${key.fingerprint}` +
(copied ? "\n\nCopied to the phone's clipboard." : "")
: `Couldn't create this device's key: ${error}`,
hint: key ? `click copy to phone clipboard ${GESTURE_DOUBLE_CLICK} back` : `${GESTURE_DOUBLE_CLICK} back`,
onClick: key
? () => {
copyToPhoneClipboard("SSH public key", key!.authorizedKey);
copied = true;
}
: undefined,
onBack: () => closeHubPage(window, returnMode),
});
}
/**
* One control connection's sessions in this hub window's display order:
* most-recently-updated first as of when the window became visible, with
@@ -1479,6 +1803,7 @@ function hubSessionItems(window: HubWindow): HubItem[] {
];
const multiHost = controls.size > 1;
const canLaunch = launchPresetNames().length > 0;
const isTmux = (control: ControlConnection) => clientOptionsFor(control.config)?.kind === "tmux";
// Every configured host is listed under its own heading, in stored order,
// whatever its connection state: a connected host lists its sessions, any
// other shows its state on the heading plus a Connect row (unless it is
@@ -1488,10 +1813,17 @@ function hubSessionItems(window: HubWindow): HubItem[] {
const name = connectionDisplayName(control.config);
if (!isControlConnected(control)) {
items.push({ label: `${name} (${controlStatusWord(control)})`, heading: true });
if (control.sshIssue && control.config.enabled) {
items.push({ label: sshIssueAction(control.sshIssue), onSelect: () => openSshIssuePage(window, control) });
continue;
}
const connecting = control.config.enabled && control.state?.phase === "connecting";
if (!connecting && clientOptionsFor(control.config)) {
// A failure retrying can't fix (tmux missing or too old) says why;
// selecting it retries once the host is fixed.
const unfixable = control.config.enabled && control.state?.retryable === false;
items.push({
label: control.reconnectTimer ? "Connect now" : "Connect",
label: unfixable ? control.state!.status : control.reconnectTimer ? "Connect now" : "Connect",
onSelect: () => connectControl(control),
});
}
@@ -1500,7 +1832,8 @@ function hubSessionItems(window: HubWindow): HubItem[] {
items.push({
label: name,
heading: true,
onSelect: canLaunch ? () => launchOnHost(window, control) : undefined,
// tmux hosts can always start a shell, presets or not.
onSelect: canLaunch || isTmux(control) ? () => launchOnHost(window, control) : undefined,
});
const sessions = orderedSessions(window, control);
for (const session of sessions) {
@@ -1516,7 +1849,11 @@ function hubSessionItems(window: HubWindow): HubItem[] {
}
if (!sessions.length) {
items.push({
label: multiHost ? "(no live sessions)" : "(no live sessions; run g2mirror <command>)",
label: isTmux(control)
? "(no tmux sessions; select the host to start one)"
: multiHost
? "(no live sessions)"
: "(no live sessions; run g2mirror <command>)",
onSelect: () => control.client?.listSessions(),
});
}
@@ -1537,6 +1874,10 @@ function hubConnectionItems(window: HubWindow): HubItem[] {
label: "Add connection",
onSelect: () => beginAddConnection(window),
},
{
label: "This device's SSH key",
onSelect: () => openClientKeyPage(window),
},
{
label: "Done",
onSelect: () => setHubMode(window, "sessions"),
@@ -1547,6 +1888,13 @@ function hubConnectionItems(window: HubWindow): HubItem[] {
function controlStatusWord(control: ControlConnection): string {
if (!control.config.enabled) return "off";
const issue = control.sshIssue;
if (issue) {
if (issue.kind === "hostkey-unknown") return "verify host key";
if (issue.kind === "hostkey-mismatch") return "HOST KEY CHANGED";
if (issue.passwordTried) return "password rejected";
return issue.passwordAllowed ? "password needed" : "key not authorized";
}
switch (control.state?.phase) {
case "connected":
case "attached":
@@ -1579,6 +1927,32 @@ function openConnectionActions(window: HubWindow, control: ControlConnection): v
connectControl(control);
},
},
...(control.config.hostKeys.length
? [
{
label: "Forget host key",
onSelect: (ctx: { stack: { pop(): unknown } }) => {
ctx.stack.pop();
control.config.hostKeys = [];
updateConnection(control.config.id, { hostKeys: [] });
control.sshIssue = null;
if (control.config.enabled) startControl(control);
renderHubWindows();
},
},
]
: []),
...(isSshConnection(control) && getSshSecret(sshPasswordSecretId(control.config.id))
? [
{
label: "Forget saved password",
onSelect: (ctx: { stack: { pop(): unknown } }) => {
ctx.stack.pop();
removeSshSecret(sshPasswordSecretId(control.config.id));
},
},
]
: []),
{
label: `Remove ${name}`,
onSelect: (ctx) => {
@@ -1596,6 +1970,11 @@ function openConnectionActions(window: HubWindow, control: ControlConnection): v
windowMenu(window).open(items);
}
function isSshConnection(control: ControlConnection): boolean {
const kind = clientOptionsFor(control.config)?.kind;
return kind === "tmux" || kind === "ssh-g2mirror";
}
/** Enable and (re)connect now; also the manual retry path, so reset backoff. */
function connectControl(control: ControlConnection): void {
control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS;
@@ -1616,6 +1995,7 @@ function disconnectControl(control: ControlConnection): void {
function removeControl(control: ControlConnection): void {
stopControl(control);
removeSshSecret(sshPasswordSecretId(control.config.id));
controls.delete(control.config.id);
saveConnections(loadConnections().filter((connection) => connection.id !== control.config.id));
renderHubWindows();
@@ -1624,7 +2004,7 @@ function removeControl(control: ControlConnection): void {
/**
* Enter the Add-connection screen: clear the draft and ask the shell to open
* the phone text editor on it. The user types (or voice-inputs) the
* g2mirror:// string, then clicks to save or double-clicks to cancel.
* connection string, then clicks to save or double-clicks to cancel.
*/
function beginAddConnection(window: HubWindow): void {
terminalNewConnectionSetting.set("");
@@ -1634,15 +2014,15 @@ function beginAddConnection(window: HubWindow): void {
function saveAddConnection(window: HubWindow): void {
const url = terminalNewConnectionSetting.get();
if (!parseConnectionString(url)) {
if (!parseAnyConnectionString(url)) {
window.addError = url
? "Not a g2mirror://token@host connection string."
: "Enter a g2mirror:// connection string first.";
? "Not an ssh://user@host or g2mirror://token@host string."
: "Enter a connection string first.";
scheduleRender(window);
return;
}
const connections = loadConnections();
connections.push({ id: `c${Date.now()}`, url, serverName: null, enabled: true });
connections.push({ id: `c${Date.now()}`, url, serverName: null, enabled: true, hostKeys: [] });
saveConnections(connections);
endAddConnection(window);
setHubMode(window, "connections");
@@ -1672,6 +2052,15 @@ function handleHubInput(window: HubWindow, event: InputEvent, frameId: number):
frameTimings.finishFrame(frameId, "discarded: terminal add-connection ignored input");
return;
}
if (window.mode === "page") {
if (event.type === "click" && window.page?.onClick) {
window.page.onClick();
renderAndSubmit(window, frameId);
return;
}
frameTimings.finishFrame(frameId, "discarded: terminal page ignored input");
return;
}
const list = hubMenu(window);
list.setItems(hubItems(window));
switch (event.type) {
@@ -1859,6 +2248,11 @@ function launchPresetNames(): string[] {
*/
function launchOnHost(window: HubWindow, control: ControlConnection): void {
const presets = launchPresetNames();
if (presets.length === 0) {
// A tmux host with no presets configured: a new session running the login shell.
launchFromUi(control, "shell");
return;
}
if (presets.length === 1) {
launchFromUi(control, presets[0]!);
return;
@@ -1903,6 +2297,9 @@ function paintHub(window: HubWindow): GrayImage {
if (window.mode === "add") {
return paintAddConnection(window);
}
if (window.mode === "page" && window.page) {
return paintHubPage(window, window.page);
}
const { viewportWidth: width, viewportHeight: height, padding } = window;
const image = new GrayImage(width, height, 0);
const font = chromeFont();
@@ -1917,7 +2314,7 @@ function paintHub(window: HubWindow): GrayImage {
let listTop = header.listTop;
if (window.mode === "sessions" && controls.size === 0) {
image.drawText(font, header.titleX, listTop, "Add a g2mirror:// connection to get started, see:", 150);
image.drawText(font, header.titleX, listTop, "Add an ssh:// (tmux) or g2mirror:// connection to get started, see:", 150);
image.drawText(font, header.titleX, listTop + step, "https://github.com/jimrandomh/g2mirror", 190);
listTop += 2 * step + 6;
}
@@ -1959,8 +2356,8 @@ function paintAddConnection(window: HubWindow): GrayImage {
image.drawText(font, padding.left, padding.top, "Add connection", 220);
const bodyX = padding.left + PAGE_BODY_INDENT;
const instructionsY = padding.top + 10 + step;
image.drawText(font, bodyX, instructionsY, "Type the g2mirror://token@host string in the", 170);
image.drawText(font, bodyX, instructionsY + step, "phone app (or use voice input from the menu).", 170);
image.drawText(font, bodyX, instructionsY, "Type ssh://user@host (tmux) or g2mirror://token@host in", 170);
image.drawText(font, bodyX, instructionsY + step, "the phone app (or use voice input from the menu).", 170);
const draftY = instructionsY + 3 * step;
const draft = terminalNewConnectionSetting.get();
image.drawText(font, bodyX, draftY, truncateLabel(draft || "(empty)", 52), 220);
@@ -1971,6 +2368,34 @@ function paintAddConnection(window: HubWindow): GrayImage {
return image;
}
/** A page of text: title at the top padding, wrapped body, hint on the bottom padding. */
function paintHubPage(window: HubWindow, page: HubPage): GrayImage {
const { viewportWidth: width, viewportHeight: height, padding } = window;
const image = new GrayImage(width, height, 0);
const font = chromeFont();
const step = lineStep(font);
image.drawText(font, padding.left, padding.top, page.title, 220);
const bodyX = padding.left + PAGE_BODY_INDENT;
const hintY = height - padding.bottom - font.lineHeight;
const lines = wrapText(font, page.body(), Math.max(1, width - padding.right - bodyX), { breakLongWords: true });
let y = padding.top + 10 + step;
for (const line of lines) {
if (y + step > hintY) break;
image.drawText(font, bodyX, y, line, 190);
y += step;
}
image.drawText(font, bodyX, hintY, page.hint, 110);
return image;
}
/** The action row under a host whose SSH connection needs the user. */
function sshIssueAction(issue: SshFailure): string {
if (issue.kind === "hostkey-unknown") return "Verify host key...";
if (issue.kind === "hostkey-mismatch") return "Host key changed!";
if (issue.passwordAllowed) return issue.passwordTried ? "Re-enter password..." : "Enter password...";
return "Show this device's SSH key...";
}
function truncateLabel(text: string, maxLength: number): string {
return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`;
}
+44
View File
@@ -0,0 +1,44 @@
import type {
G2MirrorHistoryReply,
G2MirrorPhase,
G2MirrorSession,
G2MirrorState,
} from "../../native/terminal-session-types";
/**
* What the Terminal worker needs from a session backend. G2MirrorClient (a
* g2mirror server, directly or tunnelled over SSH) and TmuxClient (tmux
* control mode over SSH) both provide it. The model is g2mirror's: a client
* starts "connecting", reaches "connected" (it can list and launch sessions,
* and reports bells/activity/titles for them), and can then attach to one
* session, view it (snapshot + live output), page its scrollback, and type
* into it.
*/
export interface TerminalClient {
state(): G2MirrorState;
onStateChange(listener: (state: G2MirrorState) => void): () => void;
/** Raw VT100/xterm bytes to feed the emulator. Snapshot implies reset-first. */
onTerminalData(listener: (data: Uint8Array, kind: "snapshot" | "output") => void): () => void;
onSessionAttached(listener: (command: string) => void): () => void;
onSessionDetached(listener: (reason: string) => void): () => void;
onBell(listener: (socket: string, lastBellAtMs: number) => void): () => void;
onActivity(listener: (socket: string, lastOutputAtMs: number) => void): () => void;
onTitle(listener: (socket: string, title: string) => void): () => void;
/** Fired after a snapshot's terminal data, with its scrollback splice point. */
onSnapshot(listener: (historyNext: number, historyOldest: number) => void): () => void;
onHistoryLines(listener: (reply: G2MirrorHistoryReply) => void): () => void;
setViewport(cols: number, rows: number): void;
start(): void;
stop(): void;
listSessions(): void;
launchSession(preset: string): Promise<string>;
connectSession(socket: string): void;
disconnectSession(): void;
view(): void;
unview(): void;
requestHistory(before: number, limit?: number): void;
sendInput(text: string): void;
submitInput(text: string): void;
}
export type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState };
File diff suppressed because it is too large. Load diff
+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[];
};
+18 -1
View File
@@ -1340,11 +1340,28 @@ export const terminalNewConnectionSetting = new ConfigSettingString({
label: "New connection",
storageKey: "terminal.newConnectionDraft",
defaultValue: "",
editorTitle: "g2mirror connection string (g2mirror://token@host)",
editorTitle: "Connection (ssh://user@host or g2mirror://token@host)",
glassesEditTitle: "Add connection",
normalize: (value) => (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(),
});
/**
* Staging buffer for the Terminal app's SSH password prompt: the worker opens
* the phone's (masked) text editor on it, then moves what was typed into the
* platform keystore (app/native/ssh) and clears it as soon as the user
* confirms or cancels on the glasses. Not listed in the Settings app.
*/
export const terminalSshPasswordSetting = new ConfigSettingString({
id: "terminal-ssh-password",
label: "SSH password",
storageKey: "terminal.sshPasswordDraft",
defaultValue: "",
inputKind: "password",
editorTitle: "SSH password",
glassesEditTitle: "SSH password",
normalize: (value) => (value ?? "").replace(/[\r\n]+/g, ""),
});
/**
* Staging buffer for the T3 Code app's Pair-environment screen: the phone
* text editor types the `t3 pair` link into it, and the app reads it back