From 12c73d7a87d6aac7404e29e65d0accee5c73994a Mon Sep 17 00:00:00 2001 From: STRIX Date: Tue, 8 Sep 2026 18:06:40 +0800 Subject: [PATCH] T9: main UI shell + connection management - session/TerminalSession: kit-free connect orchestrator (CONNECTING -> HOSTKEY_WAIT -> AUTHENTICATING/AUTH_REQUIRED -> READY/CLOSED/ERROR), fresh SshSession per attempt, inline password retry with optional remember+persist, friendly error mapping - session/SessionManager: process-wide session registry with listener notify and active-session tracking - ui/SessionLaunch: SessionDeps assembly (repos + TOFU dialog + crypto envelopes), host-key AlertDialog (save/once/reject), toast/clipboard, quick-connect and host-profile spec builders - pages/Index: bottom Tabs shell (connections/terminal/keys/settings) with AppStorage-driven cross-page tab switching - ui/ConnectionsPage: quick-connect bar, search, LazyForEach host list, long-press context menu (edit/copy/forget-password/delete), FAB + bindContentCover editor, delete/forget confirm dialogs - ui/HostEditSheet: full-screen host editor (label/host/port/user, password/key auth chips, key Select, 8-color tag picker) - ui/TerminalPage: session tab strip + per-state overlays (progress, inline password prompt, error/closed with reconnect) - ui/KeysPage/SettingsPage: stage placeholders (diag entry kept) - ssh/SshSession: optional onClosed callback for transport loss - data/KnownHostRepository: fix missing KnownHostStore import (T8 post-build regression) --- entry/src/main/ets/common/HostColors.ts | 29 ++ .../src/main/ets/data/KnownHostRepository.ts | 2 +- entry/src/main/ets/pages/Index.ets | 53 ++- entry/src/main/ets/session/SessionManager.ts | 113 +++++ entry/src/main/ets/session/TerminalSession.ts | 336 +++++++++++++++ entry/src/main/ets/ssh/SshSession.ts | 15 + entry/src/main/ets/ui/ConnectionsPage.ets | 394 ++++++++++++++++++ entry/src/main/ets/ui/HostEditSheet.ets | 390 +++++++++++++++++ entry/src/main/ets/ui/KeysPage.ets | 34 ++ entry/src/main/ets/ui/SessionLaunch.ets | 199 +++++++++ entry/src/main/ets/ui/SettingsPage.ets | 44 ++ entry/src/main/ets/ui/TerminalPage.ets | 276 ++++++++++++ 12 files changed, 1869 insertions(+), 16 deletions(-) create mode 100644 entry/src/main/ets/common/HostColors.ts create mode 100644 entry/src/main/ets/session/SessionManager.ts create mode 100644 entry/src/main/ets/session/TerminalSession.ts create mode 100644 entry/src/main/ets/ui/ConnectionsPage.ets create mode 100644 entry/src/main/ets/ui/HostEditSheet.ets create mode 100644 entry/src/main/ets/ui/KeysPage.ets create mode 100644 entry/src/main/ets/ui/SessionLaunch.ets create mode 100644 entry/src/main/ets/ui/SettingsPage.ets create mode 100644 entry/src/main/ets/ui/TerminalPage.ets diff --git a/entry/src/main/ets/common/HostColors.ts b/entry/src/main/ets/common/HostColors.ts new file mode 100644 index 0000000..976ba1d --- /dev/null +++ b/entry/src/main/ets/common/HostColors.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + */ + +/** Host color-tag palette: 8 fixed colors, stored per host as an index. */ +export class HostColors { + private static readonly PALETTE: string[] = [ + '#E5484D', // red + '#D6409F', // magenta + '#8E4EC6', // purple + '#3E63DD', // indigo + '#0091FF', // blue + '#00A896', // teal + '#FFB224', // amber + '#8D8D8D' // grey + ]; + + static count(): number { + return HostColors.PALETTE.length; + } + + /** Palette color for a colorTag index (negative values wrap around). */ + static at(tag: number): string { + const n: number = HostColors.PALETTE.length; + const idx: number = ((tag % n) + n) % n; + return HostColors.PALETTE[idx]; + } +} diff --git a/entry/src/main/ets/data/KnownHostRepository.ts b/entry/src/main/ets/data/KnownHostRepository.ts index be03885..9a1c4e2 100644 --- a/entry/src/main/ets/data/KnownHostRepository.ts +++ b/entry/src/main/ets/data/KnownHostRepository.ts @@ -8,7 +8,7 @@ */ import { relationalStore } from '@kit.ArkData'; -import { KnownHostRecord } from '../ssh/HostKeyVerifier'; +import type { KnownHostRecord, KnownHostStore } from '../ssh/HostKeyVerifier'; import { hostPortString } from '../ssh/HostKeyVerifier'; import { sha256Fingerprint } from '../common/Fingerprint'; import { base64ToBytes, bytesToBase64 } from '../ssh/SshWire'; diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets index 2198bd9..0592c83 100644 --- a/entry/src/main/ets/pages/Index.ets +++ b/entry/src/main/ets/pages/Index.ets @@ -3,26 +3,49 @@ * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. */ +import { ConnectionsPage } from '../ui/ConnectionsPage'; +import { TerminalPage } from '../ui/TerminalPage'; +import { KeysPage } from '../ui/KeysPage'; +import { SettingsPage } from '../ui/SettingsPage'; + +/** + * App shell: bottom tab bar with 连接 / 终端 / 密钥 / 设置. + * Cross-page navigation (e.g. "connect" jumping to the terminal tab) goes + * through AppStorage key 'activeTabIndex'. + */ @Entry @Component struct Index { + @StorageLink('activeTabIndex') @Watch('onTabRequested') activeTabIndex: number = 0; + controller: TabsController = new TabsController(); + + onTabRequested(): void { + this.controller.changeIndex(this.activeTabIndex); + } + build() { - Column({ space: 12 }) { - Text('Haven') - .fontSize(26) - .fontWeight(FontWeight.Bold) - Text('HarmonyOS port · SSH client') - .fontSize(14) - .fontColor('#666666') - Button('打开诊断页') - .width('60%') - .height(44) - .margin({ top: 16 }) - .onClick(() => { - this.getUIContext().getRouter().pushUrl({ url: 'pages/DiagPage' }); - }) + Tabs({ barPosition: BarPosition.End, controller: this.controller }) { + TabContent() { + ConnectionsPage() + }.tabBar('连接') + + TabContent() { + TerminalPage() + }.tabBar('终端') + + TabContent() { + KeysPage() + }.tabBar('密钥') + + TabContent() { + SettingsPage() + }.tabBar('设置') } - .justifyContent(FlexAlign.Center) + .barMode(BarMode.Fixed) + .scrollable(true) + .onChange((index: number): void => { + this.activeTabIndex = index; + }) .width('100%') .height('100%') } diff --git a/entry/src/main/ets/session/SessionManager.ts b/entry/src/main/ets/session/SessionManager.ts new file mode 100644 index 0000000..e25f6f6 --- /dev/null +++ b/entry/src/main/ets/session/SessionManager.ts @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: process-wide registry of live TerminalSessions. Pages subscribe via + * subscribe() and re-read all()/getActive() on every notification. + */ + +import { TerminalSession } from './TerminalSession'; +import type { ConnectSpec, SessionDeps } from './TerminalSession'; + +export class SessionManager { + private static instance: SessionManager | null = null; + + static getInstance(): SessionManager { + if (SessionManager.instance === null) { + SessionManager.instance = new SessionManager(); + } + return SessionManager.instance; + } + + private readonly sessions: Map = new Map(); + private readonly listeners: Array<() => void> = []; + private nextId: number = 1; + private activeId: number | null = null; + + /** + * Create a session, make it active and start dialing. The deps' + * onStateChange is replaced with a manager notify so every state move + * refreshes all subscribed pages. + */ + launch(spec: ConnectSpec, deps: SessionDeps): TerminalSession { + const manager: SessionManager = SessionManager.getInstance(); + const wrapped: SessionDeps = { + knownHostStore: deps.knownHostStore, + decideHostKey: deps.decideHostKey, + loadPrivateKey: deps.loadPrivateKey, + decryptPassword: deps.decryptPassword, + encryptPassword: deps.encryptPassword, + persistPassword: deps.persistPassword, + markConnected: deps.markConnected, + onStateChange: (session: TerminalSession): void => { + manager.notify(); + } + }; + const session: TerminalSession = new TerminalSession(this.nextId, spec, wrapped); + this.nextId += 1; + this.sessions.set(session.getId(), session); + this.activeId = session.getId(); + this.notify(); + session.start(); + return session; + } + + get(id: number): TerminalSession | null { + const found: TerminalSession | undefined = this.sessions.get(id); + return found === undefined ? null : found; + } + + all(): TerminalSession[] { + return Array.from(this.sessions.values()); + } + + getActiveId(): number | null { + return this.activeId; + } + + getActive(): TerminalSession | null { + if (this.activeId === null) { + return null; + } + return this.get(this.activeId); + } + + setActive(id: number): void { + if (this.sessions.has(id) && this.activeId !== id) { + this.activeId = id; + this.notify(); + } + } + + /** Close and forget a session; active falls back to the newest survivor. */ + remove(id: number): void { + const session: TerminalSession | null = this.get(id); + if (session === null) { + return; + } + session.close(); + this.sessions.delete(id); + if (this.activeId === id) { + const rest: TerminalSession[] = this.all(); + this.activeId = rest.length > 0 ? rest[rest.length - 1].getId() : null; + } + this.notify(); + } + + subscribe(listener: () => void): () => void { + this.listeners.push(listener); + return (): void => { + const idx: number = this.listeners.indexOf(listener); + if (idx >= 0) { + this.listeners.splice(idx, 1); + } + }; + } + + notify(): void { + const snapshot: Array<() => void> = this.listeners.slice(); + for (let i: number = 0; i < snapshot.length; i++) { + snapshot[i](); + } + } +} diff --git a/entry/src/main/ets/session/TerminalSession.ts b/entry/src/main/ets/session/TerminalSession.ts new file mode 100644 index 0000000..fe5be3e --- /dev/null +++ b/entry/src/main/ets/session/TerminalSession.ts @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: high-level lifecycle of one interactive SSH connection. Pure logic — + * every platform/UI capability (dialogs, storage, crypto envelopes) is + * injected through SessionDeps so this file stays kit-free and testable. + * + * Failure semantics of the underlying engine: SshSession.connect() and + * authenticate() hard-close the transport on any failure, so every attempt + * (including a password retry) builds a fresh SshSession. + */ + +import { AuthMethod } from '../data/Models'; +import type { ClientPrivateKey } from '../ssh/Auth'; +import { SshSession, SshSessionState } from '../ssh/SshSession'; +import type { SshSessionOptions } from '../ssh/SshSession'; +import type { HostKeyDecision, HostKeyPrompt, KnownHostStore } from '../ssh/HostKeyVerifier'; +import { Log } from '../common/Log'; + +/** High-level lifecycle of one interactive SSH connection attempt. */ +export enum SessionState { + IDLE = 'idle', + CONNECTING = 'connecting', + /** TOFU decider is showing its prompt; connection paused inside KEX. */ + HOSTKEY_WAIT = 'hostkey_wait', + AUTHENTICATING = 'authenticating', + /** Waiting for the user to type a password (first prompt or retry). */ + AUTH_REQUIRED = 'auth_required', + READY = 'ready', + CLOSED = 'closed', + ERROR = 'error' +} + +/** Everything needed to dial one host; hostProfileId null = quick connect. */ +export interface ConnectSpec { + /** Display label; empty string falls back to user@host. */ + label: string; + host: string; + port: number; + username: string; + authMethod: AuthMethod; + keyId: number | null; + /** Stored password envelope (SecretStore), null when none saved. */ + passwordEnc: string | null; + colorTag: number; + /** Saved HostProfile id, or null for ephemeral quick connections. */ + hostProfileId: number | null; +} + +/** UI-side capabilities injected into the session. */ +export interface SessionDeps { + knownHostStore: KnownHostStore; + decideHostKey(prompt: HostKeyPrompt): Promise; + loadPrivateKey(keyId: number): Promise; + decryptPassword(enc: string): Promise; + encryptPassword(plain: string): Promise; + persistPassword(hostProfileId: number, enc: string): Promise; + markConnected(hostProfileId: number): Promise; + onStateChange(session: TerminalSession): void; +} + +export class TerminalSession { + private static readonly TAG: string = 'TerminalSession'; + + private readonly id: number; + private readonly spec: ConnectSpec; + private readonly deps: SessionDeps; + + private state: SessionState = SessionState.IDLE; + private errorText: string = ''; + private closeReason: string = ''; + private passwordFailed: boolean = false; + private passwordOverride: string | null = null; + private pendingRemember: boolean = false; + private ssh: SshSession | null = null; + + constructor(id: number, spec: ConnectSpec, deps: SessionDeps) { + this.id = id; + this.spec = spec; + this.deps = deps; + } + + getId(): number { + return this.id; + } + + getState(): SessionState { + return this.state; + } + + getErrorText(): string { + return this.errorText; + } + + getCloseReason(): string { + return this.closeReason; + } + + /** True when a previous password attempt was rejected by the server. */ + isPasswordFailed(): boolean { + return this.passwordFailed; + } + + getColorTag(): number { + return this.spec.colorTag; + } + + isQuickConnect(): boolean { + return this.spec.hostProfileId === null; + } + + getTitle(): string { + if (this.spec.label.length > 0) { + return this.spec.label; + } + return `${this.spec.username}@${this.spec.host}`; + } + + getSubtitle(): string { + return `${this.spec.username}@${this.spec.host}:${this.spec.port}`; + } + + /** Begin (or re-begin) the connection attempt. Never rejects. */ + start(): void { + this.attempt(); + } + + /** Re-dial after ERROR/CLOSED; creates a fresh SshSession. */ + reconnect(): void { + this.attempt(); + } + + /** + * Continue a paused password flow (AUTH_REQUIRED). The password is used + * on a fresh connection; on success it is persisted when `remember`. + */ + providePassword(password: string, remember: boolean): void { + if (this.state !== SessionState.AUTH_REQUIRED || password.length === 0) { + return; + } + this.passwordOverride = password; + this.pendingRemember = remember; + this.attempt(); + } + + /** User-requested teardown; idempotent. */ + close(): void { + this.disposeSsh(); + if (this.state !== SessionState.CLOSED) { + this.state = SessionState.CLOSED; + this.deps.onStateChange(this); + } + } + + // ---------------------------------------------------------------- private + + private async attempt(): Promise { + this.disposeSsh(); + const ssh: SshSession = new SshSession(this.buildSshOptions()); + this.ssh = ssh; + this.setState(SessionState.CONNECTING); + + // TCP + banner + KEX + TOFU (decider flips us to HOSTKEY_WAIT). + try { + await ssh.connect(this.spec.host, this.spec.port); + } catch (e) { + this.failStale(ssh, friendlyError((e as Error).message)); + return; + } + if (this.ssh !== ssh || ssh.getState() !== SshSessionState.KEX) { + return; + } + + if (this.spec.authMethod === AuthMethod.PUBLICKEY) { + this.setState(SessionState.AUTHENTICATING); + let key: ClientPrivateKey; + try { + key = await this.deps.loadPrivateKey(this.spec.keyId === null ? -1 : this.spec.keyId); + } catch (e) { + this.failStale(ssh, `密钥加载失败:${(e as Error).message}`); + return; + } + if (this.ssh !== ssh) { + return; + } + try { + await ssh.authenticate(this.spec.username, '', key); + } catch (e) { + this.failStale(ssh, friendlyError((e as Error).message)); + return; + } + if (this.ssh !== ssh) { + return; + } + } else { + // Password auth: stored envelope -> one-shot override -> prompt. + let password: string | null = this.passwordOverride; + if (password === null && this.spec.passwordEnc !== null) { + try { + password = await this.deps.decryptPassword(this.spec.passwordEnc); + } catch (e) { + password = null; + } + } + if (this.ssh !== ssh) { + return; + } + if (password === null) { + this.passwordFailed = false; + this.setState(SessionState.AUTH_REQUIRED); + return; + } + this.setState(SessionState.AUTHENTICATING); + try { + await ssh.authenticate(this.spec.username, password, null); + } catch (e) { + if (this.ssh !== ssh) { + return; + } + this.passwordFailed = true; + this.passwordOverride = null; + this.setState(SessionState.AUTH_REQUIRED); + return; + } + if (this.ssh !== ssh) { + return; + } + if (this.pendingRemember && this.spec.hostProfileId !== null) { + try { + const enc: string = await this.deps.encryptPassword(password); + await this.deps.persistPassword(this.spec.hostProfileId, enc); + } catch (e) { + Log.warn(TerminalSession.TAG, `persist password failed: ${(e as Error).message}`); + } + } + } + + this.setState(SessionState.READY); + Log.info(TerminalSession.TAG, `session #${this.id} ready: ${this.getSubtitle()}`); + if (this.spec.hostProfileId !== null) { + try { + await this.deps.markConnected(this.spec.hostProfileId); + } catch (e) { + Log.warn(TerminalSession.TAG, `markConnected failed: ${(e as Error).message}`); + } + } + } + + private buildSshOptions(): SshSessionOptions { + const deps: SessionDeps = this.deps; + const opts: SshSessionOptions = { + knownHostStore: deps.knownHostStore, + hostKeyDecider: { + decide: (prompt: HostKeyPrompt): Promise => { + this.setState(SessionState.HOSTKEY_WAIT); + return deps.decideHostKey(prompt); + } + }, + onClosed: (reason: string): void => { + this.handleSshClosed(reason); + } + }; + return opts; + } + + /** Record a terminal failure on a still-current attempt. */ + private failStale(ssh: SshSession, message: string): void { + if (this.ssh !== ssh) { + return; + } + this.errorText = message; + this.setState(SessionState.ERROR); + ssh.close(); + } + + /** + * Transport-level close. Pre-READY failures always surface through the + * connect()/authenticate() rejection paths as ERROR, so only a READY + * session transitions to CLOSED here (server dropped us). + */ + private handleSshClosed(reason: string): void { + if (this.state === SessionState.READY) { + this.closeReason = reason; + this.setState(SessionState.CLOSED); + Log.warn(TerminalSession.TAG, `session #${this.id} dropped: ${reason}`); + } + } + + private disposeSsh(): void { + const ssh: SshSession | null = this.ssh; + this.ssh = null; + if (ssh !== null) { + ssh.close(); + } + } + + private setState(next: SessionState): void { + if (this.state === next) { + return; + } + this.state = next; + this.deps.onStateChange(this); + } +} + +/** + * Map engine-internal English error text to a user-presentable message. + * Unknown messages pass through unchanged. + */ +export function friendlyError(message: string): string { + const lower: string = message.toLowerCase(); + if (lower.includes('rejected (new)') || lower.includes('rejected (changed)')) { + return '主机密钥被拒绝,连接已取消'; + } + if (lower.includes('timeout') || lower.includes('timed out')) { + return '连接超时'; + } + if (lower.includes('refused')) { + return '连接被拒绝(服务未启动或端口错误)'; + } + if (lower.includes('unreachable')) { + return '网络不可达'; + } + if (lower.includes('getaddrinfo') || lower.includes('name or service') || + lower.includes('temporary failure in resolution')) { + return '域名解析失败'; + } + if (lower.includes('banner')) { + return '对方不是 SSH 服务或协议版本不兼容'; + } + if (lower.includes('auth')) { + return `认证失败:${message}`; + } + return message; +} diff --git a/entry/src/main/ets/ssh/SshSession.ts b/entry/src/main/ets/ssh/SshSession.ts index 7463249..361553c 100644 --- a/entry/src/main/ets/ssh/SshSession.ts +++ b/entry/src/main/ets/ssh/SshSession.ts @@ -44,6 +44,8 @@ export interface SshSessionOptions { authTimeoutMs?: number; /** Keepalive probe interval (default 15000 ms). */ keepAliveIntervalMs?: number; + /** Fired exactly once when the session finishes: local close or transport loss. */ + onClosed?: (reason: string) => void; } export interface ExecResult { @@ -226,6 +228,7 @@ export class SshSession { this.closeAllChannels(); this.transport.close(); this.setState(SshSessionState.CLOSED); + this.fireClosed('closed locally'); } // ---------------------------------------------------------------- private @@ -298,6 +301,18 @@ export class SshSession { } this.closeAllChannels(); this.setState(SshSessionState.CLOSED); + this.fireClosed(reason); + } + + private fireClosed(reason: string): void { + const cb: ((reason: string) => void) | undefined = this.options.onClosed; + if (cb !== undefined) { + try { + cb(reason); + } catch (e) { + Log.warn(SshSession.TAG, `onClosed callback failed: ${(e as Error).message}`); + } + } } /** diff --git a/entry/src/main/ets/ui/ConnectionsPage.ets b/entry/src/main/ets/ui/ConnectionsPage.ets new file mode 100644 index 0000000..b688f6a --- /dev/null +++ b/entry/src/main/ets/ui/ConnectionsPage.ets @@ -0,0 +1,394 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: connections page — quick-connect bar, searchable host list with + * long-press context menu, FAB opening the full-screen host editor. + */ + +import { common } from '@kit.AbilityKit'; +import { Database } from '../data/Database'; +import { HostRepository } from '../data/HostRepository'; +import { AuthMethod, HostProfile } from '../data/Models'; +import { HostColors } from '../common/HostColors'; +import { QuickConnectTarget, parseQuickConnect } from '../common/QuickConnect'; +import { ConnectSpec } from '../session/TerminalSession'; +import { + buildQuickConnectSpec, + copyText, + launchSession, + showToast, + specFromHost +} from './SessionLaunch'; +import { HostEditSheet } from './HostEditSheet'; + +/** LazyForEach data source with a full-reload notification on setData. */ +class HostDataSource implements IDataSource { + private items: HostProfile[] = []; + private listeners: DataChangeListener[] = []; + + totalCount(): number { + return this.items.length; + } + + getData(index: number): HostProfile { + return this.items[index]; + } + + registerDataChangeListener(listener: DataChangeListener): void { + this.listeners.push(listener); + } + + unregisterDataChangeListener(listener: DataChangeListener): void { + const idx: number = this.listeners.indexOf(listener); + if (idx >= 0) { + this.listeners.splice(idx, 1); + } + } + + setData(items: HostProfile[]): void { + this.items = items; + const snapshot: DataChangeListener[] = this.listeners.slice(); + for (let i: number = 0; i < snapshot.length; i++) { + snapshot[i].onDataReloaded(); + } + } +} + +@Component +export struct ConnectionsPage { + @State quickInput: string = ''; + @State searchText: string = ''; + @State showEditor: boolean = false; + @State editingId: number = -1; + @State totalCount: number = 0; + + private dataSource: HostDataSource = new HostDataSource(); + private allHosts: HostProfile[] = []; + private hostRepo: HostRepository | null = null; + + aboutToAppear(): void { + this.reload(); + } + + // ---------------------------------------------------------------- actions + + private async ensureRepo(): Promise { + if (this.hostRepo === null) { + const context: common.Context | undefined = this.getUIContext().getHostContext(); + if (context === undefined) { + throw new Error('无法获取应用上下文'); + } + const db: Database = await Database.getInstance(context); + this.hostRepo = new HostRepository(db); + } + return this.hostRepo; + } + + private async reload(): Promise { + try { + const repo: HostRepository = await this.ensureRepo(); + this.allHosts = await repo.list(); + this.applyFilter(); + } catch (e) { + showToast(this.getUIContext(), `加载失败:${(e as Error).message}`); + } + } + + private applyFilter(): void { + const q: string = this.searchText.trim().toLowerCase(); + const out: HostProfile[] = []; + for (let i: number = 0; i < this.allHosts.length; i++) { + const h: HostProfile = this.allHosts[i]; + if (q.length === 0 || h.label.toLowerCase().includes(q) || + h.host.toLowerCase().includes(q) || h.username.toLowerCase().includes(q)) { + out.push(h); + } + } + this.dataSource.setData(out); + this.totalCount = out.length; + } + + private connectQuick(): void { + const ui: UIContext = this.getUIContext(); + try { + const target: QuickConnectTarget = parseQuickConnect(this.quickInput); + if (target.username.length === 0) { + showToast(ui, '请使用 user@host 格式(需要用户名)'); + return; + } + this.launch(buildQuickConnectSpec(target)); + } catch (e) { + showToast(ui, (e as Error).message); + } + } + + private connectHost(host: HostProfile): void { + this.launch(specFromHost(host)); + } + + private launch(spec: ConnectSpec): void { + const ui: UIContext = this.getUIContext(); + launchSession(ui, spec).then((): void => { + this.quickInput = ''; + AppStorage.setOrCreate('activeTabIndex', 1); + }).catch((e: Object): void => { + showToast(ui, `启动失败:${(e as Error).message}`); + }); + } + + private openEditor(id: number): void { + this.editingId = id; + this.showEditor = true; + } + + private confirmDelete(host: HostProfile): void { + const name: string = host.label.length > 0 ? host.label : host.host; + const params: AlertDialogParamWithButtons = { + title: '删除连接', + message: `确定删除 “${name}” 吗?该操作不可撤销。`, + autoCancel: true, + alignment: DialogAlignment.Center, + primaryButton: { + value: '删除', + fontColor: '#E5484D', + action: (): void => { + this.deleteHost(host.id); + } + }, + secondaryButton: { + value: '取消', + fontColor: '#666666', + action: (): void => { + } + } + }; + this.getUIContext().showAlertDialog(params); + } + + private async deleteHost(id: number): Promise { + try { + const repo: HostRepository = await this.ensureRepo(); + await repo.remove(id); + showToast(this.getUIContext(), '已删除'); + this.reload(); + } catch (e) { + showToast(this.getUIContext(), `删除失败:${(e as Error).message}`); + } + } + + private confirmForgetPassword(host: HostProfile): void { + const params: AlertDialogParamWithButtons = { + title: '忘记密码', + message: `确定删除 “${host.username}@${host.host}” 已保存的密码吗?`, + autoCancel: true, + alignment: DialogAlignment.Center, + primaryButton: { + value: '忘记密码', + fontColor: '#E5484D', + action: (): void => { + this.forgetPassword(host); + } + }, + secondaryButton: { + value: '取消', + fontColor: '#666666', + action: (): void => { + } + } + }; + this.getUIContext().showAlertDialog(params); + } + + private async forgetPassword(host: HostProfile): Promise { + try { + const repo: HostRepository = await this.ensureRepo(); + host.passwordEnc = null; + await repo.update(host); + showToast(this.getUIContext(), '已忘记密码'); + this.reload(); + } catch (e) { + showToast(this.getUIContext(), `操作失败:${(e as Error).message}`); + } + } + + // ---------------------------------------------------------------- builders + + @Builder + hostRow(host: HostProfile) { + Row({ space: 12 }) { + Circle({ width: 12, height: 12 }) + .fill(HostColors.at(host.colorTag)) + Column({ space: 2 }) { + Text(host.label.length > 0 ? host.label : `${host.username}@${host.host}`) + .fontSize(16) + .fontWeight(FontWeight.Medium) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + Text(`${host.host}:${host.port} · ${host.username} · ` + + (host.authMethod === AuthMethod.PUBLICKEY ? '密钥' : '密码')) + .fontSize(12) + .fontColor('#8C8C8C') + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + } + .layoutWeight(1) + .alignItems(HorizontalAlign.Start) + } + .width('100%') + .padding({ left: 16, right: 16, top: 12, bottom: 12 }) + .alignItems(VerticalAlign.Center) + .borderRadius(12) + .backgroundColor('#FFFFFF') + } + + /** Typed options so the literal is not inferred against a union param. */ + private menuOption(content: string): MenuItemOptions { + const opt: MenuItemOptions = { content: content }; + return opt; + } + + @Builder + hostMenuBuilder(host: HostProfile) { + Menu() { + MenuItem(this.menuOption('编辑')) + .onClick((): void => { + this.openEditor(host.id); + }) + MenuItem(this.menuOption('复制连接地址')) + .onClick((): void => { + copyText(this.getUIContext(), `${host.username}@${host.host}:${host.port}`); + }) + if (host.passwordEnc !== null) { + MenuItem(this.menuOption('忘记密码')) + .onClick((): void => { + this.confirmForgetPassword(host); + }) + } + MenuItem(this.menuOption('删除')) + .onClick((): void => { + this.confirmDelete(host); + }) + } + } + + @Builder + editorBuilder() { + HostEditSheet({ + initialId: this.editingId, + onSaved: (host: HostProfile) => { + this.showEditor = false; + this.reload(); + }, + onCancelled: () => { + this.showEditor = false; + } + }) + } + + // ---------------------------------------------------------------- build + + build() { + Stack({ alignContent: Alignment.BottomEnd }) { + Column() { + Text('连接') + .fontSize(26) + .fontWeight(FontWeight.Bold) + .width('100%') + .padding({ left: 20, right: 20, top: 16, bottom: 8 }) + + Row({ space: 8 }) { + TextInput({ text: this.quickInput, placeholder: 'user@host[:port] 快速连接' }) + .layoutWeight(1) + .height(44) + .fontSize(14) + .backgroundColor('#FFFFFF') + .borderRadius(10) + .onChange((value: string): void => { + this.quickInput = value; + }) + Button('连接') + .height(44) + .fontSize(14) + .backgroundColor('#0A59F7') + .onClick((): void => { + this.connectQuick(); + }) + } + .width('100%') + .padding({ left: 12, right: 12, top: 4, bottom: 4 }) + + TextInput({ text: this.searchText, placeholder: '搜索主机' }) + .width('100%') + .height(40) + .fontSize(14) + .backgroundColor('#FFFFFF') + .borderRadius(10) + .padding({ left: 12, right: 12 }) + .margin({ left: 12, right: 12, top: 4, bottom: 8 }) + .onChange((value: string): void => { + this.searchText = value; + this.applyFilter(); + }) + + if (this.totalCount === 0) { + Column({ space: 8 }) { + Text('还没有保存的主机') + .fontSize(15) + .fontColor('#8C8C8C') + Text('点击右下角 + 新建连接,或使用上方快速连接') + .fontSize(13) + .fontColor('#B0B0B0') + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + } else { + List({ space: 8 }) { + LazyForEach(this.dataSource, (host: HostProfile) => { + ListItem() { + this.hostRow(host) + } + .onClick((): void => { + this.connectHost(host); + }) + .bindContextMenu((): void => { + this.hostMenuBuilder(host) + }, ResponseType.LongPress) + }, (host: HostProfile) => host.id.toString()) + } + .width('100%') + .layoutWeight(1) + .padding({ left: 12, right: 12, bottom: 88 }) + .scrollBar(BarState.Off) + .edgeEffect(EdgeEffect.Spring) + } + } + .width('100%') + .height('100%') + + Button('+') + .width(56) + .height(56) + .borderRadius(28) + .fontSize(26) + .fontWeight(FontWeight.Bold) + .backgroundColor('#0A59F7') + .fontColor('#FFFFFF') + .margin(20) + .shadow({ radius: 8, color: '#33000000', offsetY: 4 }) + .onClick((): void => { + this.openEditor(-1); + }) + } + .width('100%') + .height('100%') + .backgroundColor('#F1F3F5') + .bindContentCover(this.showEditor, this.editorBuilder(), { + modalTransition: ModalTransition.DEFAULT, + onDisappear: (): void => { + this.showEditor = false; + } + }) + } +} diff --git a/entry/src/main/ets/ui/HostEditSheet.ets b/entry/src/main/ets/ui/HostEditSheet.ets new file mode 100644 index 0000000..d384c19 --- /dev/null +++ b/entry/src/main/ets/ui/HostEditSheet.ets @@ -0,0 +1,390 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: full-screen host editor shown via bindContentCover. initialId < 0 + * creates a new host; otherwise the stored profile is loaded and updated. + */ + +import { common } from '@kit.AbilityKit'; +import { Database } from '../data/Database'; +import { SecretStore } from '../data/SecretStore'; +import { HostRepository } from '../data/HostRepository'; +import { KeyRepository } from '../data/KeyRepository'; +import { AuthMethod, HostProfile, KeyRecord } from '../data/Models'; +import { HostColors } from '../common/HostColors'; +import { showToast } from './SessionLaunch'; + +@Component +export struct HostEditSheet { + @Prop initialId: number = -1; + onSaved?: (host: HostProfile) => void = (host: HostProfile): void => { + }; + onCancelled?: () => void = (): void => { + }; + + @State isEdit: boolean = false; + @State label: string = ''; + @State host: string = ''; + @State portText: string = '22'; + @State username: string = ''; + @State useKeyAuth: boolean = false; + @State keyIndex: number = -1; + @State colorTag: number = 0; + @State keys: KeyRecord[] = []; + + private original: HostProfile | null = null; + private hostRepo: HostRepository | null = null; + private keyRepo: KeyRepository | null = null; + + aboutToAppear(): void { + this.load(); + } + + // ------------------------------------------------------------------ data + + private async ensureRepos(): Promise { + if (this.hostRepo !== null && this.keyRepo !== null) { + return; + } + const context: common.Context | undefined = this.getUIContext().getHostContext(); + if (context === undefined) { + throw new Error('无法获取应用上下文'); + } + const db: Database = await Database.getInstance(context); + const secrets: SecretStore = await SecretStore.getInstance(context); + this.hostRepo = new HostRepository(db); + this.keyRepo = new KeyRepository(db, secrets, context); + } + + private async load(): Promise { + const ui: UIContext = this.getUIContext(); + try { + await this.ensureRepos(); + const repo: HostRepository = this.hostRepo as HostRepository; + const keyRepository: KeyRepository = this.keyRepo as KeyRepository; + this.keys = await keyRepository.list(); + + if (this.initialId >= 0) { + const found: HostProfile | null = await repo.getById(this.initialId); + if (found === null) { + showToast(ui, '主机不存在'); + this.onCancelled?.(); + return; + } + this.original = found; + this.isEdit = true; + this.label = found.label; + this.host = found.host; + this.portText = found.port.toString(); + this.username = found.username; + this.useKeyAuth = found.authMethod === AuthMethod.PUBLICKEY; + this.colorTag = found.colorTag; + this.keyIndex = this.indexOfKey(found.keyId); + } else { + this.colorTag = Math.floor(Math.random() * HostColors.count()); + } + } catch (e) { + showToast(ui, `加载失败:${(e as Error).message}`); + this.onCancelled?.(); + } + } + + private indexOfKey(keyId: number | null): number { + if (keyId === null) { + return -1; + } + for (let i: number = 0; i < this.keys.length; i++) { + if (this.keys[i].id === keyId) { + return i; + } + } + return -1; + } + + private selectedKeyId(): number | null { + if (!this.useKeyAuth || this.keyIndex < 0 || this.keyIndex >= this.keys.length) { + return null; + } + return this.keys[this.keyIndex].id; + } + + private selectedKeyName(): string { + if (this.keyIndex < 0 || this.keyIndex >= this.keys.length) { + return '选择密钥'; + } + return this.keys[this.keyIndex].name; + } + + private keyOptions(): SelectOption[] { + const out: SelectOption[] = []; + for (let i: number = 0; i < this.keys.length; i++) { + const opt: SelectOption = { value: this.keys[i].name }; + out.push(opt); + } + return out; + } + + private colorIndices(): number[] { + const out: number[] = []; + for (let i: number = 0; i < HostColors.count(); i++) { + out.push(i); + } + return out; + } + + // ---------------------------------------------------------------- actions + + private parsePort(ui: UIContext): number { + const s: string = this.portText.trim(); + if (s.length === 0) { + return 22; + } + for (let i: number = 0; i < s.length; i++) { + const c: number = s.charCodeAt(i); + if (c < 48 || c > 57) { + return -1; + } + } + const port: number = parseInt(s); + if (port < 1 || port > 65535) { + return -1; + } + return port; + } + + private async save(): Promise { + const ui: UIContext = this.getUIContext(); + const hostName: string = this.host.trim(); + const user: string = this.username.trim(); + const labelTrim: string = this.label.trim(); + if (hostName.length === 0) { + showToast(ui, '请输入主机地址'); + return; + } + if (user.length === 0) { + showToast(ui, '请输入用户名'); + return; + } + const port: number = this.parsePort(ui); + if (port < 0) { + showToast(ui, '端口必须是 1-65535 的数字'); + return; + } + if (this.useKeyAuth && this.selectedKeyId() === null) { + showToast(ui, '请选择登录密钥'); + return; + } + + try { + const repo: HostRepository = this.hostRepo as HostRepository; + const method: AuthMethod = this.useKeyAuth ? AuthMethod.PUBLICKEY : AuthMethod.PASSWORD; + if (this.isEdit && this.original !== null) { + const h: HostProfile = this.original; + h.label = labelTrim; + h.host = hostName; + h.port = port; + h.username = user; + h.authMethod = method; + h.keyId = method === AuthMethod.PUBLICKEY ? this.selectedKeyId() : null; + h.colorTag = this.colorTag; + await repo.update(h); + this.onSaved?.(h); + return; + } + const h: HostProfile = { + id: 0, + label: labelTrim, + host: hostName, + port: port, + username: user, + authMethod: method, + keyId: method === AuthMethod.PUBLICKEY ? this.selectedKeyId() : null, + passwordEnc: null, + colorTag: this.colorTag, + sortOrder: await repo.nextSortOrder(), + lastConnectedAt: null, + createdAt: 0, + updatedAt: 0 + }; + const id: number = await repo.insert(h); + h.id = id; + this.onSaved?.(h); + } catch (e) { + showToast(ui, `保存失败:${(e as Error).message}`); + } + } + + // ---------------------------------------------------------------- builders + + @Builder + fieldLabel(text: string) { + Text(text) + .fontSize(13) + .fontColor('#666666') + .margin({ top: 14, bottom: 6 }) + } + + // ---------------------------------------------------------------- build + + build() { + Column() { + Row() { + Text(this.isEdit ? '编辑连接' : '新建连接') + .fontSize(20) + .fontWeight(FontWeight.Bold) + .layoutWeight(1) + Button('关闭') + .fontSize(14) + .backgroundColor('#00000000') + .fontColor('#666666') + .onClick((): void => { + this.onCancelled?.(); + }) + } + .width('100%') + .padding({ left: 20, right: 12, top: 16, bottom: 8 }) + + Scroll() { + Column() { + this.fieldLabel('名称(可选)') + TextInput({ text: this.label, placeholder: '例如:开发机' }) + .width('100%') + .height(44) + .fontSize(14) + .backgroundColor('#F5F6F7') + .borderRadius(10) + .onChange((value: string): void => { + this.label = value; + }) + + this.fieldLabel('主机地址') + TextInput({ text: this.host, placeholder: '主机名或 IP 地址' }) + .width('100%') + .height(44) + .fontSize(14) + .backgroundColor('#F5F6F7') + .borderRadius(10) + .onChange((value: string): void => { + this.host = value; + }) + + this.fieldLabel('端口') + TextInput({ text: this.portText, placeholder: '22' }) + .width('100%') + .height(44) + .fontSize(14) + .backgroundColor('#F5F6F7') + .borderRadius(10) + .type(InputType.Number) + .onChange((value: string): void => { + this.portText = value; + }) + + this.fieldLabel('用户名') + TextInput({ text: this.username, placeholder: '登录用户名' }) + .width('100%') + .height(44) + .fontSize(14) + .backgroundColor('#F5F6F7') + .borderRadius(10) + .onChange((value: string): void => { + this.username = value; + }) + + this.fieldLabel('认证方式') + Row({ space: 8 }) { + Text('密码认证') + .fontSize(14) + .padding({ left: 18, right: 18, top: 8, bottom: 8 }) + .borderRadius(16) + .backgroundColor(!this.useKeyAuth ? '#0A59F7' : '#FFFFFF') + .fontColor(!this.useKeyAuth ? '#FFFFFF' : '#333333') + .border({ width: 1, color: !this.useKeyAuth ? '#0A59F7' : '#D9D9D9' }) + .onClick((): void => { + this.useKeyAuth = false; + }) + Text('密钥认证') + .fontSize(14) + .padding({ left: 18, right: 18, top: 8, bottom: 8 }) + .borderRadius(16) + .backgroundColor(this.useKeyAuth ? '#0A59F7' : '#FFFFFF') + .fontColor(this.useKeyAuth ? '#FFFFFF' : '#333333') + .border({ width: 1, color: this.useKeyAuth ? '#0A59F7' : '#D9D9D9' }) + .onClick((): void => { + this.useKeyAuth = true; + }) + } + .width('100%') + + if (this.useKeyAuth) { + if (this.keys.length === 0) { + Text('暂无可用密钥,请先在“密钥”页导入或生成') + .fontSize(13) + .fontColor('#E5484D') + .margin({ top: 8 }) + } else { + Select(this.keyOptions()) + .selected(this.keyIndex) + .value(this.selectedKeyName()) + .font({ size: 14 }) + .fontColor('#333333') + .width('100%') + .height(44) + .margin({ top: 8 }) + .onSelect((index: number, text: string): void => { + this.keyIndex = index; + }) + } + } + + this.fieldLabel('颜色标签') + Row({ space: 12 }) { + ForEach(this.colorIndices(), (idx: number) => { + Circle({ width: 26, height: 26 }) + .fill(HostColors.at(idx)) + .stroke(idx === this.colorTag ? '#1F1F1F' : 'transparent') + .strokeWidth(idx === this.colorTag ? 3 : 0) + .onClick((): void => { + this.colorTag = idx; + }) + }, (idx: number) => idx.toString()) + } + .width('100%') + .margin({ top: 6, bottom: 24 }) + } + .width('100%') + .padding({ left: 20, right: 20 }) + .alignItems(HorizontalAlign.Start) + } + .layoutWeight(1) + .scrollBar(BarState.Off) + + Row({ space: 12 }) { + Button('取消') + .layoutWeight(1) + .height(44) + .fontSize(15) + .backgroundColor('#FFFFFF') + .fontColor('#333333') + .onClick((): void => { + this.onCancelled?.(); + }) + Button('保存') + .layoutWeight(1) + .height(44) + .fontSize(15) + .backgroundColor('#0A59F7') + .fontColor('#FFFFFF') + .onClick((): void => { + this.save(); + }) + } + .width('100%') + .padding({ left: 20, right: 20, top: 8, bottom: 16 }) + } + .width('100%') + .height('100%') + .backgroundColor('#F1F3F5') + } +} diff --git a/entry/src/main/ets/ui/KeysPage.ets b/entry/src/main/ets/ui/KeysPage.ets new file mode 100644 index 0000000..6c8a84b --- /dev/null +++ b/entry/src/main/ets/ui/KeysPage.ets @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: key management placeholder — full UI (generate / import / delete) + * arrives in the next stage. + */ + +@Component +export struct KeysPage { + build() { + Column({ space: 8 }) { + Text('密钥') + .fontSize(26) + .fontWeight(FontWeight.Bold) + .width('100%') + .padding({ left: 20, right: 20, top: 16 }) + Column({ space: 8 }) { + Text('密钥管理即将开放') + .fontSize(15) + .fontColor('#8C8C8C') + Text('将在下一阶段提供生成、导入与管理功能') + .fontSize(13) + .fontColor('#B0B0B0') + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + } + .width('100%') + .height('100%') + .backgroundColor('#F7F8FA') + } +} diff --git a/entry/src/main/ets/ui/SessionLaunch.ets b/entry/src/main/ets/ui/SessionLaunch.ets new file mode 100644 index 0000000..d3a8652 --- /dev/null +++ b/entry/src/main/ets/ui/SessionLaunch.ets @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: UI-side glue for launching sessions. Bridges the kit-free session + * layer to concrete repositories, the TOFU host-key dialog, toasts and + * the clipboard. All functions are stateless. + */ + +import { common } from '@kit.AbilityKit'; +import { pasteboard } from '@kit.BasicServicesKit'; +import { promptAction } from '@kit.ArkUI'; +import { Database } from '../data/Database'; +import { SecretStore } from '../data/SecretStore'; +import { HostRepository } from '../data/HostRepository'; +import { KeyRepository } from '../data/KeyRepository'; +import { DbKnownHostStore } from '../data/KnownHostRepository'; +import { parsePrivateKeyPem, ParsedPrivateKey } from '../data/OpenSshKey'; +import { AuthMethod, HostProfile, SshKeyType } from '../data/Models'; +import { buildClientPrivateKey, ClientPrivateKey } from '../ssh/Auth'; +import { parsePublicKeyBlob, PublicKeyMaterial } from '../ssh/crypto/KeyImport'; +import { HostKeyDecision, HostKeyPrompt, HostKeyStatus } from '../ssh/HostKeyVerifier'; +import { ConnectSpec, SessionDeps, TerminalSession } from '../session/TerminalSession'; +import { SessionManager } from '../session/SessionManager'; +import { QuickConnectTarget } from '../common/QuickConnect'; + +/** Outward signature algorithm used for a stored key type. */ +export function outwardAlgoOf(keyType: string): string { + if (keyType === SshKeyType.RSA) { + return 'rsa-sha2-512'; + } + return keyType; +} + +/** Build the engine private key from stored OpenSSH PEM text. */ +export function loadClientKeyFromPem(pem: string): ClientPrivateKey { + const parsed: ParsedPrivateKey = parsePrivateKeyPem(pem); + const pub: PublicKeyMaterial = parsePublicKeyBlob(parsed.pubBlob); + return buildClientPrivateKey(outwardAlgoOf(parsed.keyType), parsed.priMaterial, pub); +} + +/** ConnectSpec for an ephemeral quick-connect target (password auth). */ +export function buildQuickConnectSpec(target: QuickConnectTarget): ConnectSpec { + const spec: ConnectSpec = { + label: '', + host: target.host, + port: target.port, + username: target.username, + authMethod: AuthMethod.PASSWORD, + keyId: null, + passwordEnc: null, + colorTag: 0, + hostProfileId: null + }; + return spec; +} + +/** ConnectSpec for a saved host profile. */ +export function specFromHost(host: HostProfile): ConnectSpec { + const spec: ConnectSpec = { + label: host.label, + host: host.host, + port: host.port, + username: host.username, + authMethod: host.authMethod, + keyId: host.keyId, + passwordEnc: host.passwordEnc, + colorTag: host.colorTag, + hostProfileId: host.id + }; + return spec; +} + +/** Assemble real (kit-backed) SessionDeps; opens the shared DB on first use. */ +export async function createSessionDeps(ui: UIContext, + context: common.Context): Promise { + const db: Database = await Database.getInstance(context); + const secrets: SecretStore = await SecretStore.getInstance(context); + const keyRepo: KeyRepository = new KeyRepository(db, secrets, context); + const hostRepo: HostRepository = new HostRepository(db); + const knownHosts: DbKnownHostStore = new DbKnownHostStore(db); + const deps: SessionDeps = { + knownHostStore: knownHosts, + decideHostKey: (prompt: HostKeyPrompt): Promise => { + return showHostKeyDialog(ui, prompt); + }, + loadPrivateKey: async (keyId: number): Promise => { + const pem: string = await keyRepo.loadPrivateKeyText(keyId); + return loadClientKeyFromPem(pem); + }, + decryptPassword: (enc: string): Promise => { + return secrets.decryptPassword(enc); + }, + encryptPassword: (plain: string): Promise => { + return secrets.encryptPassword(plain); + }, + persistPassword: async (hostProfileId: number, enc: string): Promise => { + const host: HostProfile | null = await hostRepo.getById(hostProfileId); + if (host !== null) { + host.passwordEnc = enc; + await hostRepo.update(host); + } + }, + markConnected: (hostProfileId: number): Promise => { + return hostRepo.touchLastConnected(hostProfileId); + }, + onStateChange: (session: TerminalSession): void => { + } + }; + return deps; +} + +/** + * Build deps from the page's UIContext and hand the spec to the + * SessionManager (which makes it active and starts dialing). + */ +export async function launchSession(ui: UIContext, spec: ConnectSpec): Promise { + const context: common.Context | undefined = ui.getHostContext(); + if (context === undefined) { + showToast(ui, '无法获取应用上下文'); + return; + } + const deps: SessionDeps = await createSessionDeps(ui, context); + SessionManager.getInstance().launch(spec, deps); +} + +/** + * TOFU host-key prompt as a modal alert. primary = accept & save, + * secondary = accept once, cancel (back / tap outside) = reject. + */ +export function showHostKeyDialog(ui: UIContext, + prompt: HostKeyPrompt): Promise { + return new Promise((resolve: (d: HostKeyDecision) => void): void => { + const finish: (d: HostKeyDecision) => void = (d: HostKeyDecision): void => { + resolve(d); + }; + + const changed: boolean = prompt.status === HostKeyStatus.CHANGED; + const title: string = changed ? '主机密钥已改变' : '新的主机'; + let msg: string; + if (changed) { + let known: string = ''; + for (let i: number = 0; i < prompt.knownFingerprints.length; i++) { + known += `\n· ${prompt.knownFingerprints[i]}`; + } + msg = `警告:主机 “${prompt.hostPort}” 的密钥已改变,这可能意味着中间人攻击。\n\n` + + `新指纹:${prompt.fingerprint}\n已知指纹:${known}\n\n` + + `仍要信任新密钥并继续连接吗?\n(点击对话框外部或返回键将拒绝连接)`; + } else { + msg = `无法确认主机 “${prompt.hostPort}” 的真实性。\n\n` + + `指纹:${prompt.fingerprint}\n\n` + + `信任此主机并继续连接吗?\n(点击对话框外部或返回键将拒绝连接)`; + } + + const params: AlertDialogParamWithButtons = { + title: title, + message: msg, + autoCancel: true, + alignment: DialogAlignment.Center, + primaryButton: { + value: '接受并保存', + fontColor: '#0A59F7', + action: (): void => { + finish(HostKeyDecision.ACCEPT_SAVE); + } + }, + secondaryButton: { + value: '仅本次连接', + fontColor: '#0A59F7', + action: (): void => { + finish(HostKeyDecision.ACCEPT_ONCE); + } + }, + cancel: (): void => { + finish(HostKeyDecision.REJECT); + } + }; + ui.showAlertDialog(params); + }); +} + +/** Short-lived centered toast. */ +export function showToast(ui: UIContext, message: string): void { + const opts: promptAction.ShowToastOptions = { + message: message, + duration: 2500 + }; + ui.getPromptAction().showToast(opts); +} + +/** Put plain text on the system clipboard (fire-and-forget). */ +export function copyText(ui: UIContext, text: string): void { + const data: pasteboard.PasteData = + pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text); + const board: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard(); + board.setData(data).catch((e: Object): void => { + showToast(ui, `复制失败:${(e as Error).message}`); + }); +} diff --git a/entry/src/main/ets/ui/SettingsPage.ets b/entry/src/main/ets/ui/SettingsPage.ets new file mode 100644 index 0000000..23ed654 --- /dev/null +++ b/entry/src/main/ets/ui/SettingsPage.ets @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: settings placeholder — real settings (font size, color scheme, + * keepalive, background task) arrive with the terminal stage. The + * diagnostics page stays reachable here. + */ + +@Component +export struct SettingsPage { + build() { + Column() { + Text('设置') + .fontSize(26) + .fontWeight(FontWeight.Bold) + .width('100%') + .padding({ left: 20, right: 20, top: 16 }) + + Column({ space: 12 }) { + Text('设置项将在终端阶段开放') + .fontSize(15) + .fontColor('#8C8C8C') + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + + Button('打开诊断页') + .width('60%') + .height(44) + .fontSize(14) + .backgroundColor('#FFFFFF') + .fontColor('#0A59F7') + .margin({ bottom: 32 }) + .onClick((): void => { + this.getUIContext().getRouter().pushUrl({ url: 'pages/DiagPage' }); + }) + } + .width('100%') + .height('100%') + .backgroundColor('#F7F8FA') + } +} diff --git a/entry/src/main/ets/ui/TerminalPage.ets b/entry/src/main/ets/ui/TerminalPage.ets new file mode 100644 index 0000000..24ebe17 --- /dev/null +++ b/entry/src/main/ets/ui/TerminalPage.ets @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T9: terminal page skeleton — session tab strip plus per-state overlays + * (connecting progress, host-key notice, inline password prompt, error + * and closed panels with reconnect). The terminal canvas itself lands in + * the next stage. + */ + +import { HostColors } from '../common/HostColors'; +import { SessionManager } from '../session/SessionManager'; +import { SessionState, TerminalSession } from '../session/TerminalSession'; +import { showToast } from './SessionLaunch'; + +@Component +export struct TerminalPage { + @State sessions: TerminalSession[] = []; + @State activeId: number = -1; + @State activeSnapshot: TerminalSession | null = null; + @State passwordInput: string = ''; + @State rememberPassword: boolean = true; + + private unsubscribe: (() => void) | null = null; + + aboutToAppear(): void { + this.unsubscribe = + SessionManager.getInstance().subscribe((): void => { + this.refresh(); + }); + this.refresh(); + } + + aboutToDisappear(): void { + if (this.unsubscribe !== null) { + this.unsubscribe(); + this.unsubscribe = null; + } + } + + private refresh(): void { + const manager: SessionManager = SessionManager.getInstance(); + this.sessions = manager.all(); + const active: number | null = manager.getActiveId(); + this.activeId = active === null ? -1 : active; + this.activeSnapshot = manager.getActive(); + const current: TerminalSession | null = manager.getActive(); + if (current === null || current.getState() !== SessionState.AUTH_REQUIRED) { + this.passwordInput = ''; + } + } + + private submitPassword(session: TerminalSession): void { + const pwd: string = this.passwordInput; + if (pwd.length === 0) { + showToast(this.getUIContext(), '请输入密码'); + return; + } + this.passwordInput = ''; + session.providePassword(pwd, this.rememberPassword); + } + + // ---------------------------------------------------------------- builders + + @Builder + sessionTab(session: TerminalSession) { + Row({ space: 4 }) { + Row({ space: 6 }) { + Circle({ width: 8, height: 8 }) + .fill(HostColors.at(session.getColorTag())) + Text(session.getTitle()) + .fontSize(13) + .maxLines(1) + .fontColor(session.getId() === this.activeId ? '#0A59F7' : '#333333') + } + .padding({ left: 12, right: 10, top: 6, bottom: 6 }) + .borderRadius(14) + .backgroundColor(session.getId() === this.activeId ? '#E8F1FF' : '#FFFFFF') + .onClick((): void => { + SessionManager.getInstance().setActive(session.getId()); + }) + + Text('×') + .fontSize(15) + .fontColor('#999999') + .width(22) + .height(22) + .textAlign(TextAlign.Center) + .onClick((): void => { + SessionManager.getInstance().remove(session.getId()); + }) + } + .margin({ right: 4 }) + } + + @Builder + progressPanel(text: string) { + Column({ space: 12 }) { + LoadingProgress() + .width(36) + .height(36) + .color('#0A59F7') + Text(text) + .fontSize(14) + .fontColor('#666666') + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + } + + @Builder + passwordPanel(session: TerminalSession) { + Column({ space: 12 }) { + Text(session.isPasswordFailed() ? '密码错误,请重试' : '需要密码') + .fontSize(16) + .fontWeight(FontWeight.Medium) + .fontColor(session.isPasswordFailed() ? '#E5484D' : '#333333') + Text(session.getSubtitle()) + .fontSize(13) + .fontColor('#8C8C8C') + TextInput({ text: this.passwordInput, placeholder: '密码' }) + .type(InputType.Password) + .width('80%') + .height(44) + .fontSize(14) + .backgroundColor('#F5F6F7') + .borderRadius(10) + .onChange((value: string): void => { + this.passwordInput = value; + }) + Row({ space: 8 }) { + Checkbox() + .select(this.rememberPassword) + .selectedColor('#0A59F7') + .onChange((value: boolean): void => { + this.rememberPassword = value; + }) + Text('记住密码') + .fontSize(14) + .fontColor('#333333') + } + Button('连接') + .width('80%') + .height(44) + .fontSize(15) + .backgroundColor('#0A59F7') + .fontColor('#FFFFFF') + .margin({ top: 4 }) + .onClick((): void => { + this.submitPassword(session); + }) + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + } + + @Builder + endPanel(title: string, detail: string, session: TerminalSession) { + Column({ space: 12 }) { + Text(title) + .fontSize(16) + .fontWeight(FontWeight.Medium) + .fontColor('#333333') + if (detail.length > 0) { + Text(detail) + .fontSize(13) + .fontColor('#8C8C8C') + .textAlign(TextAlign.Center) + .padding({ left: 32, right: 32 }) + } + Row({ space: 12 }) { + Button('重新连接') + .height(40) + .fontSize(14) + .padding({ left: 20, right: 20 }) + .backgroundColor('#0A59F7') + .fontColor('#FFFFFF') + .onClick((): void => { + session.reconnect(); + }) + Button('关闭会话') + .height(40) + .fontSize(14) + .padding({ left: 20, right: 20 }) + .backgroundColor('#FFFFFF') + .fontColor('#666666') + .onClick((): void => { + SessionManager.getInstance().remove(session.getId()); + }) + } + .margin({ top: 4 }) + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + } + + @Builder + sessionBody(session: TerminalSession) { + Column() { + if (session.getState() === SessionState.READY) { + Column({ space: 8 }) { + Text('会话已就绪') + .fontSize(14) + .fontColor('#4ADE80') + Text('终端渲染将在下一阶段启用') + .fontSize(12) + .fontColor('#888888') + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + .backgroundColor('#1E1E1E') + } else if (session.getState() === SessionState.CONNECTING) { + this.progressPanel(`正在连接 ${session.getSubtitle()} …`) + } else if (session.getState() === SessionState.HOSTKEY_WAIT) { + this.progressPanel('请在弹窗中确认主机密钥…') + } else if (session.getState() === SessionState.AUTHENTICATING) { + this.progressPanel('正在认证…') + } else if (session.getState() === SessionState.AUTH_REQUIRED) { + this.passwordPanel(session) + } else if (session.getState() === SessionState.ERROR) { + this.endPanel('连接失败', session.getErrorText(), session) + } else if (session.getState() === SessionState.CLOSED) { + this.endPanel('连接已关闭', session.getCloseReason(), session) + } + } + .width('100%') + .layoutWeight(1) + } + + // ---------------------------------------------------------------- build + + build() { + Column() { + if (this.sessions.length === 0) { + Column({ space: 8 }) { + Text('暂无会话') + .fontSize(15) + .fontColor('#8C8C8C') + Text('在“连接”页点击主机开始 SSH 会话') + .fontSize(13) + .fontColor('#B0B0B0') + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + } else { + Scroll() { + Row({ space: 4 }) { + ForEach(this.sessions, (session: TerminalSession) => { + this.sessionTab(session) + }, (session: TerminalSession) => session.getId().toString()) + } + .padding({ left: 12, right: 12, top: 8, bottom: 8 }) + } + .scrollable(ScrollDirection.Horizontal) + .scrollBar(BarState.Off) + .width('100%') + + Divider() + .color('#E5E5E5') + .strokeWidth(1) + + if (this.activeSnapshot !== null) { + this.sessionBody(this.activeSnapshot) + } + } + } + .width('100%') + .height('100%') + .backgroundColor('#F7F8FA') + } +}