From b60f634b7608d05211439150f4e26950201b9506 Mon Sep 17 00:00:00 2001 From: STRIX Date: Tue, 8 Sep 2026 17:20:05 +0800 Subject: [PATCH] T8: data layer (RDB schema, SecretStore, OpenSSH key containers, repositories) - data/Models.ts: AuthMethod/SshKeyType enums, HostProfile/KeyRecord/KnownHostRow - data/Database.ts: haven.db (S3) with version-ladder migration, getInstance/openFresh - data/SecretStore.ts: Asset-backed master key (Preferences fallback), ENC: password envelopes, AES-256-GCM private key files under files/keys/ - data/OpenSshKey.ts: kit-free openssh-key-v1 serialize/parse (raw magic, mpint-style EC scalars, checkint/padding validation, cross-checked pub blobs) + PKCS#1/SEC1/ PKCS#8 PEM import, encrypted containers rejected - data/KeyGenerator.ts: ed25519/ecdsa-p256/rsa-4096 generation with fingerprints - HostRepository/KeyRepository/KnownHostRepository(DbKnownHostStore)/SettingsRepository - common/QuickConnect.ts: user@host[:port] parser incl. bracketed IPv6 - DiagPage button 12: generate Ed25519, persist, reopen fresh handles, read back - Node self-test 19/19 incl. real ssh-keygen interop both directions (-y roundtrip) --- entry/src/main/ets/common/QuickConnect.ts | 92 +++ entry/src/main/ets/data/Database.ts | 120 ++++ entry/src/main/ets/data/HostRepository.ts | 144 ++++ entry/src/main/ets/data/KeyGenerator.ts | 71 ++ entry/src/main/ets/data/KeyRepository.ts | 119 ++++ .../src/main/ets/data/KnownHostRepository.ts | 104 +++ entry/src/main/ets/data/Models.ts | 74 ++ entry/src/main/ets/data/OpenSshKey.ts | 668 ++++++++++++++++++ entry/src/main/ets/data/SecretStore.ts | 262 +++++++ entry/src/main/ets/data/SettingsRepository.ts | 108 +++ entry/src/main/ets/pages/DiagPage.ets | 72 +- 11 files changed, 1833 insertions(+), 1 deletion(-) create mode 100644 entry/src/main/ets/common/QuickConnect.ts create mode 100644 entry/src/main/ets/data/Database.ts create mode 100644 entry/src/main/ets/data/HostRepository.ts create mode 100644 entry/src/main/ets/data/KeyGenerator.ts create mode 100644 entry/src/main/ets/data/KeyRepository.ts create mode 100644 entry/src/main/ets/data/KnownHostRepository.ts create mode 100644 entry/src/main/ets/data/Models.ts create mode 100644 entry/src/main/ets/data/OpenSshKey.ts create mode 100644 entry/src/main/ets/data/SecretStore.ts create mode 100644 entry/src/main/ets/data/SettingsRepository.ts diff --git a/entry/src/main/ets/common/QuickConnect.ts b/entry/src/main/ets/common/QuickConnect.ts new file mode 100644 index 0000000..7796ee5 --- /dev/null +++ b/entry/src/main/ets/common/QuickConnect.ts @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8: quick-connect bar parser — "[user@]host[:port]" with bracketed + * IPv6 literals ("[2001:db8::1]:2222"). Deliberately kit-free and + * regex-free so it stays unit-testable under plain Node. + */ + +/** Parsed quick-connect target; username may be empty. */ +export interface QuickConnectTarget { + username: string; + host: string; + port: number; +} + +/** + * Parse a quick-connect input string. Throws a user-presentable Error on + * malformed input. Bare multi-colon strings are treated as IPv6 hosts on + * port 22; a single colon separates host and (decimal) port. + */ +export function parseQuickConnect(input: string): QuickConnectTarget { + let rest: string = input.trim(); + if (rest.length === 0) { + throw new Error('请输入连接目标'); + } + + let username: string = ''; + const at: number = rest.lastIndexOf('@'); + if (at >= 0) { + username = rest.substring(0, at).trim(); + rest = rest.substring(at + 1).trim(); + if (username.length === 0) { + throw new Error('用户名不能为空'); + } + if (rest.length === 0) { + throw new Error('缺少主机地址'); + } + } + + let host: string = ''; + let port: number = 22; + + if (rest.startsWith('[')) { + const close: number = rest.indexOf(']'); + if (close < 0) { + throw new Error('IPv6 地址缺少右括号 ]'); + } + host = rest.substring(1, close); + const tail: string = rest.substring(close + 1); + if (tail.length > 0) { + if (!tail.startsWith(':')) { + throw new Error('IPv6 地址后仅允许 :端口'); + } + port = parsePort(tail.substring(1)); + } + } else { + const colon: number = rest.indexOf(':'); + const second: number = colon < 0 ? -1 : rest.indexOf(':', colon + 1); + if (colon >= 0 && second < 0) { + host = rest.substring(0, colon); + port = parsePort(rest.substring(colon + 1)); + } else { + // No colon, or a bare multi-colon IPv6 literal. + host = rest; + } + } + + if (host.length === 0) { + throw new Error('主机地址不能为空'); + } + + const target: QuickConnectTarget = { username: username, host: host, port: port }; + return target; +} + +function parsePort(s: string): number { + if (s.length === 0) { + throw new Error('端口不能为空'); + } + for (let i: number = 0; i < s.length; i++) { + const c: number = s.charCodeAt(i); + if (c < 48 || c > 57) { + throw new Error('端口必须是 1-65535 的数字'); + } + } + const port: number = parseInt(s); + if (port < 1 || port > 65535) { + throw new Error('端口必须是 1-65535 的数字'); + } + return port; +} diff --git a/entry/src/main/ets/data/Database.ts b/entry/src/main/ets/data/Database.ts new file mode 100644 index 0000000..27d0f6c --- /dev/null +++ b/entry/src/main/ets/data/Database.ts @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2026 Haven for GlassHaven contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: RelationalStore v1 with a forward-compatible version + * migration framework. DDL mirrors the approved plan §4 exactly. + */ + +import { relationalStore } from '@kit.ArkData'; +import { common } from '@kit.AbilityKit'; +import { Log } from '../common/Log'; + +const TAG: string = 'Database'; + +/** Current schema version; bump and append a migration step on change. */ +export const DB_VERSION: number = 1; + +const SQL_CREATE_HOSTS: string = + 'CREATE TABLE IF NOT EXISTS hosts (id INTEGER PRIMARY KEY AUTOINCREMENT, ' + + 'label TEXT NOT NULL, host TEXT NOT NULL, port INTEGER NOT NULL DEFAULT 22, ' + + 'username TEXT NOT NULL DEFAULT \'\', auth_method TEXT NOT NULL DEFAULT \'PASSWORD\', ' + + 'key_id INTEGER, password_enc TEXT, color_tag INTEGER NOT NULL DEFAULT 0, ' + + 'sort_order INTEGER NOT NULL DEFAULT 0, last_connected_at INTEGER, ' + + 'created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL)'; + +const SQL_CREATE_KEYS: string = + 'CREATE TABLE IF NOT EXISTS keys (id INTEGER PRIMARY KEY AUTOINCREMENT, ' + + 'name TEXT NOT NULL, algorithm TEXT NOT NULL, public_blob TEXT NOT NULL, ' + + 'fingerprint TEXT NOT NULL, created_at INTEGER NOT NULL)'; + +const SQL_CREATE_KNOWN_HOSTS: string = + 'CREATE TABLE IF NOT EXISTS known_hosts (id INTEGER PRIMARY KEY AUTOINCREMENT, ' + + 'host TEXT NOT NULL, port INTEGER NOT NULL, key_type TEXT NOT NULL, ' + + 'public_blob TEXT NOT NULL, fingerprint TEXT NOT NULL, first_seen INTEGER NOT NULL, ' + + 'UNIQUE(host, port, key_type))'; + +/** + * Owns the single RdbStore handle for the app. Repositories receive the + * store from here; the class also centralizes schema versioning. + */ +export class Database { + private static instance: Database | undefined; + + private store: relationalStore.RdbStore | null = null; + private opening: Promise | null = null; + + /** Get the process-wide instance, opening the store on first use. */ + static async getInstance(context: common.Context): Promise { + if (Database.instance === undefined) { + Database.instance = new Database(); + } + await Database.instance.ensureOpen(context); + return Database.instance; + } + + /** Create a fresh handle over the same DB file (diag restart simulation). */ + static async openFresh(context: common.Context): Promise { + const fresh: Database = new Database(); + await fresh.ensureOpen(context); + return fresh; + } + + private async ensureOpen(context: common.Context): Promise { + if (this.store !== null) { + return; + } + if (this.opening !== null) { + await this.opening; + return; + } + const task: Promise = this.open(context); + this.opening = task; + try { + await task; + } finally { + this.opening = null; + } + } + + private async open(context: common.Context): Promise { + const config: relationalStore.StoreConfig = { + name: 'haven.db', + securityLevel: relationalStore.SecurityLevel.S3 + }; + const store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, config); + await this.migrate(store); + this.store = store; + Log.info(TAG, `opened haven.db at schema v${store.version}`); + } + + /** + * Sequential migration ladder: each step upgrades exactly one version. + * Fresh databases report version 0 and run every step in order. + */ + private async migrate(store: relationalStore.RdbStore): Promise { + let version: number = store.version; + if (version > DB_VERSION) { + throw new Error(`Database: schema v${version} is newer than supported v${DB_VERSION}`); + } + if (version === 0) { + await store.execute(SQL_CREATE_HOSTS); + await store.execute(SQL_CREATE_KEYS); + await store.execute(SQL_CREATE_KNOWN_HOSTS); + version = 1; + Log.info(TAG, 'migrated schema 0 -> 1 (hosts, keys, known_hosts)'); + } + // Future migrations append here: + // if (version === 1) { ...; version = 2; } + store.version = version; + } + + /** The opened RdbStore; throws if used before getInstance resolves. */ + getStore(): relationalStore.RdbStore { + const store: relationalStore.RdbStore | null = this.store; + if (store === null) { + throw new Error('Database: store not opened yet'); + } + return store; + } +} diff --git a/entry/src/main/ets/data/HostRepository.ts b/entry/src/main/ets/data/HostRepository.ts new file mode 100644 index 0000000..098077e --- /dev/null +++ b/entry/src/main/ets/data/HostRepository.ts @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: CRUD over the `hosts` table. Passwords only ever pass + * through as SecretStore envelopes ('ENC:…'). + */ + +import { relationalStore } from '@kit.ArkData'; +import { Database } from './Database'; +import { HostProfile, AuthMethod } from './Models'; + +const COLS: string = 'id, label, host, port, username, auth_method, key_id, ' + + 'password_enc, color_tag, sort_order, last_connected_at, created_at, updated_at'; + +export class HostRepository { + private db: Database; + + constructor(db: Database) { + this.db = db; + } + + /** All hosts in display order (sort_order, then insertion order). */ + async list(): Promise { + const rs: relationalStore.ResultSet = await this.db.getStore() + .querySql(`SELECT ${COLS} FROM hosts ORDER BY sort_order ASC, id ASC`); + try { + const out: HostProfile[] = []; + while (rs.goToNextRow()) { + out.push(HostRepository.rowToHost(rs)); + } + return out; + } finally { + rs.close(); + } + } + + async getById(id: number): Promise { + const rs: relationalStore.ResultSet = await this.db.getStore() + .querySql(`SELECT ${COLS} FROM hosts WHERE id = ?`, [id]); + try { + if (!rs.goToNextRow()) { + return null; + } + return HostRepository.rowToHost(rs); + } finally { + rs.close(); + } + } + + /** Insert a new host; returns the row id. */ + async insert(host: HostProfile): Promise { + const now: number = Date.now(); + const bucket: relationalStore.ValuesBucket = { + 'label': host.label, + 'host': host.host, + 'port': host.port, + 'username': host.username, + 'auth_method': host.authMethod, + 'key_id': host.keyId, + 'password_enc': host.passwordEnc, + 'color_tag': host.colorTag, + 'sort_order': host.sortOrder, + 'last_connected_at': null, + 'created_at': now, + 'updated_at': now + }; + return this.db.getStore().insert('hosts', bucket); + } + + /** Update an existing host row (id must be set). */ + async update(host: HostProfile): Promise { + if (host.id <= 0) { + throw new Error('HostRepository: update called on an unsaved host'); + } + const bucket: relationalStore.ValuesBucket = { + 'label': host.label, + 'host': host.host, + 'port': host.port, + 'username': host.username, + 'auth_method': host.authMethod, + 'key_id': host.keyId, + 'password_enc': host.passwordEnc, + 'color_tag': host.colorTag, + 'sort_order': host.sortOrder, + 'last_connected_at': host.lastConnectedAt, + 'updated_at': Date.now() + }; + const predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates('hosts'); + predicates.equalTo('id', host.id); + await this.db.getStore().update(bucket, predicates); + } + + async remove(id: number): Promise { + const predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates('hosts'); + predicates.equalTo('id', id); + await this.db.getStore().delete(predicates); + } + + /** Stamp last_connected_at = now for a successful connection. */ + async touchLastConnected(id: number): Promise { + await this.db.getStore().execute( + 'UPDATE hosts SET last_connected_at = ?, updated_at = ? WHERE id = ?', + [Date.now(), Date.now(), id]); + } + + /** Next free sort_order value (appended at the list tail). */ + async nextSortOrder(): Promise { + const rs: relationalStore.ResultSet = await this.db.getStore() + .querySql('SELECT COALESCE(MAX(sort_order), -1) + 1 AS next FROM hosts'); + try { + if (!rs.goToNextRow()) { + return 0; + } + return rs.getLong(rs.getColumnIndex('next')); + } finally { + rs.close(); + } + } + + private static rowToHost(rs: relationalStore.ResultSet): HostProfile { + const keyIdIdx: number = rs.getColumnIndex('key_id'); + const pwIdx: number = rs.getColumnIndex('password_enc'); + const lastIdx: number = rs.getColumnIndex('last_connected_at'); + const authMethod: string = rs.getString(rs.getColumnIndex('auth_method')); + const host: HostProfile = { + id: rs.getLong(rs.getColumnIndex('id')), + label: rs.getString(rs.getColumnIndex('label')), + host: rs.getString(rs.getColumnIndex('host')), + port: rs.getLong(rs.getColumnIndex('port')), + username: rs.getString(rs.getColumnIndex('username')), + authMethod: authMethod === AuthMethod.PUBLICKEY ? + AuthMethod.PUBLICKEY : AuthMethod.PASSWORD, + keyId: rs.isColumnNull(keyIdIdx) ? null : rs.getLong(keyIdIdx), + passwordEnc: rs.isColumnNull(pwIdx) ? null : rs.getString(pwIdx), + colorTag: rs.getLong(rs.getColumnIndex('color_tag')), + sortOrder: rs.getLong(rs.getColumnIndex('sort_order')), + lastConnectedAt: rs.isColumnNull(lastIdx) ? null : rs.getLong(lastIdx), + createdAt: rs.getLong(rs.getColumnIndex('created_at')), + updatedAt: rs.getLong(rs.getColumnIndex('updated_at')) + }; + return host; + } +} diff --git a/entry/src/main/ets/data/KeyGenerator.ts b/entry/src/main/ets/data/KeyGenerator.ts new file mode 100644 index 0000000..78fb9d4 --- /dev/null +++ b/entry/src/main/ets/data/KeyGenerator.ts @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: key generation on top of the platform crypto adapter. + * Serialization itself lives in the kit-free OpenSshKey module. + */ + +import { CryptoAdapter, RawKeyPair } from '../ssh/crypto/CryptoAdapter'; +import { DerUtils, RsaPublicKeyParts } from '../ssh/crypto/DerUtils'; +import { buildPublicKeyBlob, authorizedKeysLine, PublicKeyMaterial } from '../ssh/crypto/KeyImport'; +import { sha256Fingerprint } from '../common/Fingerprint'; +import { SshKeyType } from './Models'; +import { serializeOpensshPrivateKey } from './OpenSshKey'; + +/** RSA key size offered by the generator (matches the KeysPage option). */ +export const RSA_BITS: number = 4096; + +/** A freshly generated key, ready to be persisted via KeyRepository. */ +export interface GeneratedKey { + /** SshKeyType value. */ + keyType: string; + /** SSH wire public key blob. */ + pubBlob: Uint8Array; + /** 'SHA256:…' OpenSSH-style fingerprint of pubBlob. */ + fingerprint: string; + /** authorized_keys one-liner ` `. */ + publicKeyLine: string; + /** Unencrypted openssh-key-v1 PEM text (caller stores it via SecretStore). */ + opensshPrivate: string; +} + +/** + * Generate a key pair and package every derived form the app needs: + * public blob, fingerprint, authorized_keys line and the openssh-key-v1 + * private container. RSA-4096 generation is synchronous and heavy — call + * from a background context in UI. + */ +export async function generateKey(keyType: string, name: string): Promise { + let priMaterial: Uint8Array; + let pubBlob: Uint8Array; + + if (keyType === SshKeyType.ED25519) { + const kp: RawKeyPair = await CryptoAdapter.ed25519GenerateKeyPair(); + priMaterial = kp.pri; + const mat: PublicKeyMaterial = { algo: SshKeyType.ED25519, ed25519Pub: kp.pub }; + pubBlob = buildPublicKeyBlob(SshKeyType.ED25519, mat); + } else if (keyType === SshKeyType.ECDSA_P256) { + const kp: RawKeyPair = CryptoAdapter.ecdsaP256GenerateKeyPairSync(); + priMaterial = kp.pri; + const mat: PublicKeyMaterial = { algo: SshKeyType.ECDSA_P256, ecPoint: kp.pub }; + pubBlob = buildPublicKeyBlob(SshKeyType.ECDSA_P256, mat); + } else if (keyType === SshKeyType.RSA) { + const kp: RawKeyPair = CryptoAdapter.rsaGenerateKeyPairSync(RSA_BITS); + priMaterial = kp.pri; + const parts: RsaPublicKeyParts = DerUtils.parseRsaSpki(kp.pub); + const mat: PublicKeyMaterial = { algo: SshKeyType.RSA, rsaE: parts.e, rsaN: parts.n }; + pubBlob = buildPublicKeyBlob(SshKeyType.RSA, mat); + } else { + throw new Error(`KeyGenerator: unsupported key type '${keyType}'`); + } + + const key: GeneratedKey = { + keyType: keyType, + pubBlob: pubBlob, + fingerprint: sha256Fingerprint(pubBlob), + publicKeyLine: authorizedKeysLine(keyType, pubBlob, name), + opensshPrivate: serializeOpensshPrivateKey(keyType, pubBlob, priMaterial, name) + }; + return key; +} diff --git a/entry/src/main/ets/data/KeyRepository.ts b/entry/src/main/ets/data/KeyRepository.ts new file mode 100644 index 0000000..05c4239 --- /dev/null +++ b/entry/src/main/ets/data/KeyRepository.ts @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: CRUD over the `keys` table plus the encrypted private + * key file that shadows each row (files/keys/key_.bin via SecretStore). + */ + +import { relationalStore } from '@kit.ArkData'; +import { common } from '@kit.AbilityKit'; +import { Database } from './Database'; +import { SecretStore } from './SecretStore'; +import { KeyRecord } from './Models'; + +const COLS: string = 'id, name, algorithm, public_blob, fingerprint, created_at'; + +export class KeyRepository { + private db: Database; + private secrets: SecretStore; + private context: common.Context; + + constructor(db: Database, secrets: SecretStore, context: common.Context) { + this.db = db; + this.secrets = secrets; + this.context = context; + } + + /** All keys, newest first. */ + async list(): Promise { + const rs: relationalStore.ResultSet = await this.db.getStore() + .querySql(`SELECT ${COLS} FROM keys ORDER BY created_at DESC, id DESC`); + try { + const out: KeyRecord[] = []; + while (rs.goToNextRow()) { + out.push(KeyRepository.rowToKey(rs)); + } + return out; + } finally { + rs.close(); + } + } + + async getById(id: number): Promise { + const rs: relationalStore.ResultSet = await this.db.getStore() + .querySql(`SELECT ${COLS} FROM keys WHERE id = ?`, [id]); + try { + if (!rs.goToNextRow()) { + return null; + } + return KeyRepository.rowToKey(rs); + } finally { + rs.close(); + } + } + + /** True when any host references the key (delete guard in the UI). */ + async isUsed(keyId: number): Promise { + const rs: relationalStore.ResultSet = await this.db.getStore() + .querySql('SELECT COUNT(*) AS n FROM hosts WHERE key_id = ?', [keyId]); + try { + if (!rs.goToNextRow()) { + return false; + } + return rs.getLong(rs.getColumnIndex('n')) > 0; + } finally { + rs.close(); + } + } + + /** + * Insert a key row and persist the encrypted private container. + * Returns the new row id (the file is named after it). + */ + async insert(record: KeyRecord, opensshPrivate: string): Promise { + const rowId: number = await this.db.getStore().insert('keys', { + 'name': record.name, + 'algorithm': record.algorithm, + 'public_blob': record.publicBlob, + 'fingerprint': record.fingerprint, + 'created_at': record.createdAt + }); + await this.secrets.savePrivateKeyFile(this.context, rowId, opensshPrivate); + return rowId; + } + + /** Persist a new private container for an existing key (re-import). */ + async replacePrivateKey(id: number, opensshPrivate: string): Promise { + await this.secrets.savePrivateKeyFile(this.context, id, opensshPrivate); + } + + async rename(id: number, name: string): Promise { + await this.db.getStore().execute('UPDATE keys SET name = ? WHERE id = ?', [name, id]); + } + + /** Delete the row and wipe the private key file. */ + async remove(id: number): Promise { + const predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates('keys'); + predicates.equalTo('id', id); + await this.db.getStore().delete(predicates); + this.secrets.deletePrivateKeyFile(this.context, id); + } + + /** Decrypt the private container back into openssh-key-v1 text. */ + async loadPrivateKeyText(id: number): Promise { + return this.secrets.loadPrivateKeyFile(this.context, id); + } + + private static rowToKey(rs: relationalStore.ResultSet): KeyRecord { + const record: KeyRecord = { + id: rs.getLong(rs.getColumnIndex('id')), + name: rs.getString(rs.getColumnIndex('name')), + algorithm: rs.getString(rs.getColumnIndex('algorithm')), + publicBlob: rs.getString(rs.getColumnIndex('public_blob')), + fingerprint: rs.getString(rs.getColumnIndex('fingerprint')), + createdAt: rs.getLong(rs.getColumnIndex('created_at')) + }; + return record; + } +} diff --git a/entry/src/main/ets/data/KnownHostRepository.ts b/entry/src/main/ets/data/KnownHostRepository.ts new file mode 100644 index 0000000..be03885 --- /dev/null +++ b/entry/src/main/ets/data/KnownHostRepository.ts @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: known_hosts persistence backing the TOFU engine. Adapts + * the ssh.KnownHostStore interface onto the known_hosts table; the + * "[host]:port" wire shape only exists at the interface boundary. + */ + +import { relationalStore } from '@kit.ArkData'; +import { KnownHostRecord } from '../ssh/HostKeyVerifier'; +import { hostPortString } from '../ssh/HostKeyVerifier'; +import { sha256Fingerprint } from '../common/Fingerprint'; +import { base64ToBytes, bytesToBase64 } from '../ssh/SshWire'; +import { Database } from './Database'; + +export class DbKnownHostStore implements KnownHostStore { + private db: Database; + + constructor(db: Database) { + this.db = db; + } + + /** All stored keys for one host:port spec, TOFU order preserved. */ + async lookup(hostPort: string): Promise { + const hp: HostPort = DbKnownHostStore.splitHostPort(hostPort); + const rs: relationalStore.ResultSet = await this.db.getStore() + .querySql('SELECT key_type, public_blob FROM known_hosts WHERE host = ? AND port = ? ' + + 'ORDER BY id ASC', [hp.host, hp.port]); + try { + const out: KnownHostRecord[] = []; + while (rs.goToNextRow()) { + const record: KnownHostRecord = { + hostPort: hostPortString(hp.host, hp.port), + keyAlgo: rs.getString(rs.getColumnIndex('key_type')), + keyBlob: base64ToBytes(rs.getString(rs.getColumnIndex('public_blob'))) + }; + out.push(record); + } + return out; + } finally { + rs.close(); + } + } + + /** Insert or replace the (host, port, key_type) entry. */ + async save(record: KnownHostRecord): Promise { + const hp: HostPort = DbKnownHostStore.splitHostPort(record.hostPort); + const fingerprint: string = sha256Fingerprint(record.keyBlob); + await this.db.getStore().execute( + 'INSERT OR REPLACE INTO known_hosts (host, port, key_type, public_blob, fingerprint, ' + + 'first_seen) VALUES (?, ?, ?, ?, ?, ?)', + [hp.host, hp.port, record.keyAlgo, bytesToBase64(record.keyBlob), fingerprint, Date.now()]); + } + + /** + * Inverse of hostPortString: "host" (port 22) or "[host]:port". + * Bare IPv6 strings with port 22 never carry brackets and round-trip + * unchanged. + */ + private static splitHostPort(hostPort: string): HostPort { + if (hostPort.startsWith('[')) { + const close: number = hostPort.indexOf(']'); + if (close < 0) { + throw new Error(`DbKnownHostStore: malformed host spec '${hostPort}'`); + } + const host: string = hostPort.substring(1, close); + const rest: string = hostPort.substring(close + 1); + let port: number = 22; + if (rest.length > 0) { + if (!rest.startsWith(':')) { + throw new Error(`DbKnownHostStore: malformed host spec '${hostPort}'`); + } + port = DbKnownHostStore.parsePort(rest.substring(1)); + } + const hp: HostPort = { host: host, port: port }; + return hp; + } + const hp: HostPort = { host: hostPort, port: 22 }; + return hp; + } + + private static parsePort(s: string): number { + if (s.length === 0) { + throw new Error('DbKnownHostStore: empty port'); + } + for (let i: number = 0; i < s.length; i++) { + const c: number = s.charCodeAt(i); + if (c < 48 || c > 57) { + throw new Error(`DbKnownHostStore: non-numeric port '${s}'`); + } + } + const port: number = parseInt(s); + if (port < 1 || port > 65535) { + throw new Error(`DbKnownHostStore: port out of range '${s}'`); + } + return port; + } +} + +interface HostPort { + host: string; + port: number; +} diff --git a/entry/src/main/ets/data/Models.ts b/entry/src/main/ets/data/Models.ts new file mode 100644 index 0000000..37f9a0f --- /dev/null +++ b/entry/src/main/ets/data/Models.ts @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: row-shaped record models mirroring the RelationalStore + * v1 schema (see data/Database.ts DDL). Nullable DB columns map to + * `| null` fields; TEXT enum columns map to string-valued enums. + */ + +/** hosts.auth_method column values. */ +export enum AuthMethod { + PASSWORD = 'PASSWORD', + PUBLICKEY = 'PUBLICKEY' +} + +/** + * Base key type names as stored in keys.algorithm and inside the SSH + * public key blob. RSA keys authenticate as rsa-sha2-256/512 (RFC 8332); + * the concrete variant is chosen at connect time, not persisted. + */ +export enum SshKeyType { + ED25519 = 'ssh-ed25519', + ECDSA_P256 = 'ecdsa-sha2-nistp256', + RSA = 'ssh-rsa' +} + +/** One row of the `hosts` table. */ +export interface HostProfile { + /** 0 for an unsaved draft; the DB id once inserted. */ + id: number; + label: string; + host: string; + port: number; + username: string; + authMethod: AuthMethod; + /** Referenced keys.id when authMethod is PUBLICKEY, else null. */ + keyId: number | null; + /** SecretStore envelope ('ENC:…') or null; plaintext never persisted. */ + passwordEnc: string | null; + /** 0-7 palette index for the status dot / terminal tab. */ + colorTag: number; + sortOrder: number; + /** Epoch millis of the last successful connection, null if never. */ + lastConnectedAt: number | null; + createdAt: number; + updatedAt: number; +} + +/** One row of the `keys` table. */ +export interface KeyRecord { + /** 0 for an unsaved draft; the DB id once inserted. */ + id: number; + name: string; + /** SshKeyType value. */ + algorithm: string; + /** Base64 of the SSH wire public key blob (RFC 4253 §6.6). */ + publicBlob: string; + /** 'SHA256:…' OpenSSH-style fingerprint of publicBlob. */ + fingerprint: string; + createdAt: number; +} + +/** One row of the `known_hosts` table. */ +export interface KnownHostRow { + id: number; + host: string; + port: number; + /** SshKeyType value of the stored server key. */ + keyType: string; + /** Base64 of the server public key blob. */ + publicBlob: string; + fingerprint: string; + firstSeen: number; +} diff --git a/entry/src/main/ets/data/OpenSshKey.ts b/entry/src/main/ets/data/OpenSshKey.ts new file mode 100644 index 0000000..966426a --- /dev/null +++ b/entry/src/main/ets/data/OpenSshKey.ts @@ -0,0 +1,668 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: OpenSSH key container serialization/parsing, kept free of + * platform-kit imports so it stays unit-testable under plain Node. + * + * Normalized private material conventions (mirrors ssh.ClientPrivateKey): + * - ssh-ed25519: 32-byte seed + * - ecdsa-sha2-nistp256: 32-byte scalar + * - ssh-rsa: PKCS#8 PrivateKeyInfo DER + * + * Encrypted containers (openssh-key-v1 with cipher != none, PKCS#8 + * EncryptedPrivateKeyInfo, OpenSSL traditional encryption) are detected + * and rejected with an explicit error — no silent key loss. + */ + +import { SshReader, SshWriter, base64ToBytes, bytesToBase64, bytesToUtf8, + concatBytes, bytesEqual, hexToBytes, normalizeMagnitude, utf8ToBytes } from '../ssh/SshWire'; +import { DerUtils } from '../ssh/crypto/DerUtils'; +import type { DerTlv, DerIntegerResult, RsaCrtParams } from '../ssh/crypto/DerUtils'; +import { SshKeyType } from './Models'; + +const OPENSSH_MAGIC: string = 'openssh-key-v1\u0000'; +const ARMOR_LINE_WIDTH: number = 70; + +const BEGIN_OPENSSH: string = '-----BEGIN OPENSSH PRIVATE KEY-----'; +const END_OPENSSH: string = '-----END OPENSSH PRIVATE KEY-----'; +const BEGIN_PKCS8: string = '-----BEGIN PRIVATE KEY-----'; +const END_PKCS8: string = '-----END PRIVATE KEY-----'; +const BEGIN_RSA: string = '-----BEGIN RSA PRIVATE KEY-----'; +const END_RSA: string = '-----END RSA PRIVATE KEY-----'; +const BEGIN_EC: string = '-----BEGIN EC PRIVATE KEY-----'; +const END_EC: string = '-----END EC PRIVATE KEY-----'; + +/** OID contents (body without the 0x06 tag/length). */ +const OID_RSA_ENCRYPTION: Uint8Array = hexToBytes('2a864886f70d010101'); +const OID_EC_PUBLIC_KEY: Uint8Array = hexToBytes('2a8648ce3d0201'); +const OID_PRIME256V1: Uint8Array = hexToBytes('2a8648ce3d03010701'); +const OID_ED25519: Uint8Array = hexToBytes('2b6570'); + +const ERR_ENCRYPTED: string = + 'encrypted private keys are not supported yet — strip the passphrase first'; +const ERR_NO_EC_PUB: string = + 'EC private key without an embedded public key is not supported'; +const ERR_NO_ED25519_PUB: string = + 'raw PKCS#8 Ed25519 lacks the public key — export in openssh format instead'; + +/** A private key parsed from any supported container. */ +export interface ParsedPrivateKey { + /** SshKeyType value. */ + keyType: string; + /** Normalized private material (see header comment). */ + priMaterial: Uint8Array; + /** SSH wire public key blob taken from the container itself. */ + pubBlob: Uint8Array; + comment: string; +} + +/** Local mirror of the SSH public key material (kit-free). */ +interface PubMaterial { + algo: string; + ed25519Pub?: Uint8Array; + ecPoint?: Uint8Array; + rsaE?: Uint8Array; + rsaN?: Uint8Array; +} + +/** RSAPrivateKey fields needed by the openssh-key-v1 layout. */ +interface RsaPrivateParts { + n: Uint8Array; + e: Uint8Array; + d: Uint8Array; + p: Uint8Array; + q: Uint8Array; +} + +interface EcPrivateParts { + scalar: Uint8Array; + point: Uint8Array; +} + +/** A length-prefixed substring read at a fixed offset. */ +interface StrSlice { + data: Uint8Array; + next: number; +} + +// ------------------------------------------------------------- serializing + +/** + * Build an unencrypted openssh-key-v1 PEM (ssh-keygen compatible) from the + * normalized private material. RSA material must be PKCS#8 DER; it is + * re-expanded to the n/e/d/iqmp/p/q CRT layout required by the format. + */ +export function serializeOpensshPrivateKey(keyType: string, pubBlob: Uint8Array, + priMaterial: Uint8Array, comment: string): string { + const pub: PubMaterial = parsePubBlob(pubBlob); + + const keyFields: SshWriter = new SshWriter(128); + if (keyType === SshKeyType.ED25519) { + if (priMaterial.length !== 32) { + throw new Error(`OpenSshKey: ed25519 seed must be 32 bytes, got ${priMaterial.length}`); + } + const pub32: Uint8Array | undefined = pub.ed25519Pub; + if (pub32 === undefined) { + throw new Error('OpenSshKey: public blob is not ed25519'); + } + keyFields.writeString(SshKeyType.ED25519); + keyFields.writeStringBytes(pub32); + keyFields.writeStringBytes(concatBytes(priMaterial, pub32)); + keyFields.writeString(comment); + } else if (keyType === SshKeyType.ECDSA_P256) { + if (priMaterial.length !== 32) { + throw new Error(`OpenSshKey: P-256 scalar must be 32 bytes, got ${priMaterial.length}`); + } + const point: Uint8Array | undefined = pub.ecPoint; + if (point === undefined) { + throw new Error('OpenSshKey: public blob is not ecdsa-sha2-nistp256'); + } + // OpenSSH stores the scalar mpint-style: minimal magnitude, 0x00 sign + // byte when the top bit is set. + const mag: Uint8Array = normalizeMagnitude(priMaterial); + keyFields.writeString(SshKeyType.ECDSA_P256); + keyFields.writeString('nistp256'); + keyFields.writeStringBytes(point); + if ((mag[0] & 0x80) !== 0) { + keyFields.writeStringBytes(concatBytes(new Uint8Array(1), mag)); + } else { + keyFields.writeStringBytes(mag); + } + keyFields.writeString(comment); + } else if (keyType === SshKeyType.RSA) { + const parts: RsaPrivateParts = parseRsaPkcs8(priMaterial); + const e: Uint8Array | undefined = pub.rsaE; + const n: Uint8Array | undefined = pub.rsaN; + if (e === undefined || n === undefined) { + throw new Error('OpenSshKey: public blob is not ssh-rsa'); + } + if (!bytesEqual(parts.e, e) || !bytesEqual(parts.n, n)) { + throw new Error('OpenSshKey: RSA public blob does not match private material'); + } + const crt: RsaCrtParams = DerUtils.modPowCrtParams(parts.d, parts.p, parts.q); + keyFields.writeString(SshKeyType.RSA); + keyFields.writeMpint(parts.n); + keyFields.writeMpint(parts.e); + keyFields.writeMpint(parts.d); + keyFields.writeMpint(crt.iqmp); + keyFields.writeMpint(parts.p); + keyFields.writeMpint(parts.q); + keyFields.writeString(comment); + } else { + throw new Error(`OpenSshKey: cannot serialize key type '${keyType}'`); + } + + // Private section: checkint(×2) + key fields + 1,2,3… padding to a + // multiple of the cipher block size (8 for 'none'). + const check: number = Date.now() & 0xffffffff; + const coreLen: number = 8 + keyFields.length(); + const padLen: number = (8 - (coreLen % 8)) % 8; + const section: SshWriter = new SshWriter(coreLen + padLen); + section.writeUint32(check); + section.writeUint32(check); + section.writeRaw(keyFields.toBytes()); + for (let i: number = 0; i < padLen; i++) { + section.writeByte(i + 1); + } + + const w: SshWriter = new SshWriter(256); + // PROTOCOL.key: the magic is raw NUL-terminated bytes, NOT an SSH string. + w.writeRaw(utf8ToBytes(OPENSSH_MAGIC)); + w.writeString('none'); + w.writeString('none'); + w.writeStringBytes(new Uint8Array(0)); + w.writeUint32(1); + w.writeStringBytes(pubBlob); + w.writeStringBytes(section.toBytes()); + return armor(w.toBytes(), BEGIN_OPENSSH, END_OPENSSH); +} + +// ---------------------------------------------------------------- parsing + +/** + * Parse a private key from any supported PEM flavor: + * openssh-key-v1 (unencrypted), RSA PKCS#1, EC SEC1, or PKCS#8 + * (RSA / EC P-256). Ed25519 is only available via the openssh container. + */ +export function parsePrivateKeyPem(text: string): ParsedPrivateKey { + if (text.includes(BEGIN_OPENSSH)) { + return parseOpensshPrivateKey(text); + } + if (text.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----') || + text.includes('Proc-Type: 4,ENCRYPTED')) { + throw new Error(ERR_ENCRYPTED); + } + if (text.includes(BEGIN_RSA)) { + return fromRsaPkcs1(extractPemBody(text, BEGIN_RSA, END_RSA), ''); + } + if (text.includes(BEGIN_EC)) { + return fromEcSec1(extractPemBody(text, BEGIN_EC, END_EC), ''); + } + if (text.includes(BEGIN_PKCS8)) { + return fromPkcs8(extractPemBody(text, BEGIN_PKCS8, END_PKCS8)); + } + throw new Error('OpenSshKey: unrecognized private key format'); +} + +/** Parse an unencrypted openssh-key-v1 container. */ +export function parseOpensshPrivateKey(text: string): ParsedPrivateKey { + const der: Uint8Array = extractPemBody(text, BEGIN_OPENSSH, END_OPENSSH); + const r: SshReader = new SshReader(der); + // Raw magic (no length prefix) per PROTOCOL.key. + const magic: string = bytesToUtf8(r.readRaw(OPENSSH_MAGIC.length)); + if (magic !== OPENSSH_MAGIC) { + throw new Error('OpenSshKey: bad openssh-key-v1 magic'); + } + const cipherName: string = r.readString(); + const kdfName: string = r.readString(); + const kdfOptions: Uint8Array = r.readStringBytes(); + if (cipherName !== 'none' || kdfName !== 'none') { + throw new Error(ERR_ENCRYPTED); + } + if (kdfOptions.length !== 0) { + throw new Error('OpenSshKey: unexpected kdf options for unencrypted key'); + } + const nkeys: number = r.readUint32(); + if (nkeys !== 1) { + throw new Error(`OpenSshKey: expected 1 key, got ${nkeys}`); + } + const pubBlob: Uint8Array = r.readStringBytes(); + const section: Uint8Array = r.readStringBytes(); + + const check1: number = readU32At(section, 0); + const check2: number = readU32At(section, 4); + if (check1 !== check2) { + throw new Error('OpenSshKey: checkint mismatch (corrupt container)'); + } + let off: number = 8; + const typeSlice: StrSlice = readStrAt(section, off); + off = typeSlice.next; + const keyType: string = bytesToUtf8(typeSlice.data); + let priMaterial: Uint8Array; + let comment: string = ''; + + if (keyType === SshKeyType.ED25519) { + const pubS: StrSlice = readStrAt(section, off); + off = pubS.next; + const privS: StrSlice = readStrAt(section, off); + off = privS.next; + if (pubS.data.length !== 32 || privS.data.length !== 64) { + throw new Error('OpenSshKey: malformed ed25519 private section'); + } + if (!bytesEqual(pubS.data, privS.data.slice(32))) { + throw new Error('OpenSshKey: ed25519 public key mismatch inside container'); + } + if (!bytesEqual(buildEd25519PubBlob(pubS.data), pubBlob)) { + throw new Error('OpenSshKey: ed25519 public blob mismatch inside container'); + } + priMaterial = privS.data.slice(0, 32); + } else if (keyType === SshKeyType.ECDSA_P256) { + const curveS: StrSlice = readStrAt(section, off); + off = curveS.next; + const pointS: StrSlice = readStrAt(section, off); + off = pointS.next; + const scalarS: StrSlice = readStrAt(section, off); + off = scalarS.next; + // OpenSSH writes the scalar mpint-style: 32 bytes, 33 with a 0x00 sign + // byte, or shorter when leading zeros were stripped. + if (bytesToUtf8(curveS.data) !== 'nistp256' || pointS.data.length !== 65 || + pointS.data[0] !== 0x04 || scalarS.data.length === 0 || scalarS.data.length > 33) { + throw new Error('OpenSshKey: malformed P-256 private section'); + } + if (!bytesEqual(buildEcdsaPubBlob(pointS.data), pubBlob)) { + throw new Error('OpenSshKey: P-256 public key mismatch inside container'); + } + priMaterial = padScalar32(scalarS.data); + } else if (keyType === SshKeyType.RSA) { + const nS: StrSlice = readMpintAt(section, off); + off = nS.next; + const eS: StrSlice = readMpintAt(section, off); + off = eS.next; + const dS: StrSlice = readMpintAt(section, off); + off = dS.next; + const iqmpS: StrSlice = readMpintAt(section, off); + off = iqmpS.next; + const pS: StrSlice = readMpintAt(section, off); + off = pS.next; + const qS: StrSlice = readMpintAt(section, off); + off = qS.next; + if (!bytesEqual(buildRsaPubBlob(eS.data, nS.data), pubBlob)) { + throw new Error('OpenSshKey: RSA public blob mismatch inside container'); + } + const parts: RsaPrivateParts = { + n: nS.data, e: eS.data, d: dS.data, p: pS.data, q: qS.data + }; + priMaterial = rsaPkcs8FromParts(parts); + } else { + throw new Error(`OpenSshKey: unsupported key type '${keyType}'`); + } + + const commentS: StrSlice = readStrAt(section, off); + off = commentS.next; + comment = bytesToUtf8(commentS.data); + + // Padding: 1,2,3… to the section end. + let padIdx: number = 1; + while (off < section.length) { + if (section[off] !== padIdx) { + throw new Error('OpenSshKey: bad private section padding'); + } + off += 1; + padIdx += 1; + } + + // The container's outer public blob must agree with the private section. + const rebuilt: Uint8Array = pubBlobFromMaterial(normalizeToPub(keyType, + priMaterial, pubBlob)); + if (!bytesEqual(rebuilt, pubBlob)) { + throw new Error('OpenSshKey: public blob mismatch inside container'); + } + + const parsed: ParsedPrivateKey = { + keyType: keyType, + priMaterial: priMaterial, + pubBlob: pubBlob.slice(), + comment: comment + }; + return parsed; +} + +// -------------------------------------------------------------- PEM paths + +/** RSA PKCS#1 RSAPrivateKey DER -> normalized record. */ +function fromRsaPkcs1(der: Uint8Array, comment: string): ParsedPrivateKey { + const parts: RsaPrivateParts = parseRsaPkcs1(der); + const pkcs8: Uint8Array = rsaPkcs8FromParts(parts); + const pubBlob: Uint8Array = buildRsaPubBlob(parts.e, parts.n); + const parsed: ParsedPrivateKey = { + keyType: SshKeyType.RSA, + priMaterial: pkcs8, + pubBlob: pubBlob, + comment: comment + }; + return parsed; +} + +/** SEC1 ECPrivateKey DER (P-256, embedded public key required). */ +function fromEcSec1(der: Uint8Array, comment: string): ParsedPrivateKey { + const parts: EcPrivateParts = parseEcSec1(der); + const pubBlob: Uint8Array = buildEcdsaPubBlob(parts.point); + const parsed: ParsedPrivateKey = { + keyType: SshKeyType.ECDSA_P256, + priMaterial: parts.scalar, + pubBlob: pubBlob, + comment: comment + }; + return parsed; +} + +/** Generic PKCS#8 PrivateKeyInfo (RSA / EC P-256). */ +function fromPkcs8(der: Uint8Array): ParsedPrivateKey { + const outer: DerTlv = DerUtils.readTlv(der, 0); + if (outer.tag !== 0x30) { + throw new Error('OpenSshKey: PKCS#8 must be a SEQUENCE'); + } + const version: DerTlv = DerUtils.readTlv(outer.content, 0); + if (version.tag !== 0x02) { + throw new Error('OpenSshKey: PKCS#8 version must be INTEGER'); + } + const algId: DerTlv = DerUtils.readTlv(outer.content, version.nextOffset); + if (algId.tag !== 0x30) { + throw new Error('OpenSshKey: PKCS#8 AlgorithmIdentifier must be a SEQUENCE'); + } + const oidTlv: DerTlv = DerUtils.readTlv(algId.content, 0); + if (oidTlv.tag !== 0x06) { + throw new Error('OpenSshKey: PKCS#8 algorithm OID missing'); + } + const octet: DerTlv = DerUtils.readTlv(outer.content, algId.nextOffset); + if (octet.tag !== 0x04) { + throw new Error('OpenSshKey: PKCS#8 privateKey must be an OCTET STRING'); + } + + if (bytesEqual(oidTlv.content, OID_RSA_ENCRYPTION)) { + return fromRsaPkcs1(octet.content, ''); + } + if (bytesEqual(oidTlv.content, OID_EC_PUBLIC_KEY)) { + const paramsTlv: DerTlv = DerUtils.readTlv(algId.content, oidTlv.nextOffset); + if (paramsTlv.tag !== 0x06 || !bytesEqual(paramsTlv.content, OID_PRIME256V1)) { + throw new Error('OpenSshKey: only curve prime256v1 is supported'); + } + return fromEcSec1(octet.content, ''); + } + if (bytesEqual(oidTlv.content, OID_ED25519)) { + throw new Error(ERR_NO_ED25519_PUB); + } + throw new Error('OpenSshKey: unsupported PKCS#8 algorithm'); +} + +// ---------------------------------------------------------------- RSA DER + +/** Parse PKCS#1 RSAPrivateKey: SEQUENCE{ 0, n, e, d, p, q, dp, dq, qinv }. */ +function parseRsaPkcs1(der: Uint8Array): RsaPrivateParts { + const seq: DerTlv = DerUtils.readTlv(der, 0); + if (seq.tag !== 0x30) { + throw new Error('OpenSshKey: RSAPrivateKey must be a SEQUENCE'); + } + const v: DerIntegerResult = DerUtils.derIntegerRead(seq.content, 0); + if (v.magnitude.length > 1 || (v.magnitude.length === 1 && v.magnitude[0] !== 0)) { + throw new Error('OpenSshKey: multi-prime RSA keys are not supported'); + } + const n: DerIntegerResult = DerUtils.derIntegerRead(seq.content, v.nextOffset); + const e: DerIntegerResult = DerUtils.derIntegerRead(seq.content, n.nextOffset); + const d: DerIntegerResult = DerUtils.derIntegerRead(seq.content, e.nextOffset); + const p: DerIntegerResult = DerUtils.derIntegerRead(seq.content, d.nextOffset); + const q: DerIntegerResult = DerUtils.derIntegerRead(seq.content, p.nextOffset); + const parts: RsaPrivateParts = { + n: n.magnitude, + e: e.magnitude, + d: d.magnitude, + p: p.magnitude, + q: q.magnitude + }; + return parts; +} + +/** Parse our PKCS#8 RSA material back into CRT parts. */ +function parseRsaPkcs8(der: Uint8Array): RsaPrivateParts { + const outer: DerTlv = DerUtils.readTlv(der, 0); + if (outer.tag !== 0x30) { + throw new Error('OpenSshKey: PKCS#8 must be a SEQUENCE'); + } + const version: DerTlv = DerUtils.readTlv(outer.content, 0); + const algId: DerTlv = DerUtils.readTlv(outer.content, version.nextOffset); + const oidTlv: DerTlv = DerUtils.readTlv(algId.content, 0); + if (oidTlv.tag !== 0x06 || !bytesEqual(oidTlv.content, OID_RSA_ENCRYPTION)) { + throw new Error('OpenSshKey: expected an RSA PKCS#8 key'); + } + const octet: DerTlv = DerUtils.readTlv(outer.content, algId.nextOffset); + if (octet.tag !== 0x04) { + throw new Error('OpenSshKey: PKCS#8 privateKey must be an OCTET STRING'); + } + return parseRsaPkcs1(octet.content); +} + +/** Canonical PKCS#8 from CRT parts (dp/dq/iqmp recomputed via modPowCrtParams). */ +function rsaPkcs8FromParts(parts: RsaPrivateParts): Uint8Array { + const crt: RsaCrtParams = DerUtils.modPowCrtParams(parts.d, parts.p, parts.q); + return DerUtils.buildRsaPkcs8(parts.n, parts.e, parts.d, parts.p, parts.q, + crt.dp, crt.dq, crt.iqmp); +} + +// ----------------------------------------------------------------- EC DER + +/** + * SEC1 ECPrivateKey: SEQUENCE{ INTEGER 1, OCTET STRING scalar, + * [0] curve OID, [1] BIT STRING public }. The public key is mandatory + * (no scalar-only derivation path on this platform). + */ +function parseEcSec1(der: Uint8Array): EcPrivateParts { + const seq: DerTlv = DerUtils.readTlv(der, 0); + if (seq.tag !== 0x30) { + throw new Error('OpenSshKey: ECPrivateKey must be a SEQUENCE'); + } + const v: DerIntegerResult = DerUtils.derIntegerRead(seq.content, 0); + if (v.magnitude.length !== 1 || v.magnitude[0] !== 1) { + throw new Error('OpenSshKey: unsupported ECPrivateKey version'); + } + const scalarTlv: DerTlv = DerUtils.readTlv(seq.content, v.nextOffset); + if (scalarTlv.tag !== 0x04 || scalarTlv.content.length !== 32) { + throw new Error('OpenSshKey: P-256 scalar must be a 32-byte OCTET STRING'); + } + let point: Uint8Array | undefined = undefined; + let off: number = scalarTlv.nextOffset; + while (off < seq.content.length) { + const tlv: DerTlv = DerUtils.readTlv(seq.content, off); + if (tlv.tag === 0xa0) { + const oid: DerTlv = DerUtils.readTlv(tlv.content, 0); + if (oid.tag !== 0x06 || !bytesEqual(oid.content, OID_PRIME256V1)) { + throw new Error('OpenSshKey: only curve prime256v1 is supported'); + } + } else if (tlv.tag === 0xa1) { + const bitStr: DerTlv = DerUtils.readTlv(tlv.content, 0); + if (bitStr.tag !== 0x03 || bitStr.content.length < 1 || bitStr.content[0] !== 0x00) { + throw new Error('OpenSshKey: malformed EC public key BIT STRING'); + } + const raw: Uint8Array = bitStr.content.slice(1); + if (raw.length !== 65 || raw[0] !== 0x04) { + throw new Error('OpenSshKey: EC public key must be 04||X||Y (65 bytes)'); + } + point = raw; + } + off = tlv.nextOffset; + } + if (point === undefined) { + throw new Error(ERR_NO_EC_PUB); + } + const parts: EcPrivateParts = { scalar: scalarTlv.content.slice(), point: point }; + return parts; +} + +// ------------------------------------------------------------ blob helpers + +function buildRsaPubBlob(e: Uint8Array, n: Uint8Array): Uint8Array { + const w: SshWriter = new SshWriter(80); + w.writeString(SshKeyType.RSA); + w.writeMpint(e); + w.writeMpint(n); + return w.toBytes(); +} + +function buildEcdsaPubBlob(point: Uint8Array): Uint8Array { + const w: SshWriter = new SshWriter(96); + w.writeString(SshKeyType.ECDSA_P256); + w.writeString('nistp256'); + w.writeStringBytes(point); + return w.toBytes(); +} + +function buildEd25519PubBlob(pub: Uint8Array): Uint8Array { + const w: SshWriter = new SshWriter(48); + w.writeString(SshKeyType.ED25519); + w.writeStringBytes(pub); + return w.toBytes(); +} + +function pubBlobFromMaterial(mat: PubMaterial): Uint8Array { + if (mat.algo === SshKeyType.ED25519) { + const pub: Uint8Array | undefined = mat.ed25519Pub; + if (pub === undefined) { + throw new Error('OpenSshKey: missing ed25519 public material'); + } + return buildEd25519PubBlob(pub); + } + if (mat.algo === SshKeyType.ECDSA_P256) { + const point: Uint8Array | undefined = mat.ecPoint; + if (point === undefined) { + throw new Error('OpenSshKey: missing EC point material'); + } + return buildEcdsaPubBlob(point); + } + const e: Uint8Array | undefined = mat.rsaE; + const n: Uint8Array | undefined = mat.rsaN; + if (e === undefined || n === undefined) { + throw new Error('OpenSshKey: missing RSA public material'); + } + return buildRsaPubBlob(e, n); +} + +/** Parse an SSH wire public key blob into its parts. */ +function parsePubBlob(blob: Uint8Array): PubMaterial { + const r: SshReader = new SshReader(blob); + const algo: string = r.readString(); + if (algo === SshKeyType.ED25519) { + const pub: Uint8Array = r.readStringBytes(); + if (pub.length !== 32) { + throw new Error('OpenSshKey: ed25519 public key must be 32 bytes'); + } + const mat: PubMaterial = { algo: algo, ed25519Pub: pub }; + return mat; + } + if (algo === SshKeyType.ECDSA_P256) { + const curve: string = r.readString(); + const point: Uint8Array = r.readStringBytes(); + if (curve !== 'nistp256' || point.length !== 65 || point[0] !== 0x04) { + throw new Error('OpenSshKey: malformed P-256 public key'); + } + const mat: PubMaterial = { algo: algo, ecPoint: point }; + return mat; + } + if (algo === SshKeyType.RSA) { + const e: Uint8Array = r.readMpint(); + const n: Uint8Array = r.readMpint(); + const mat: PubMaterial = { algo: algo, rsaE: e, rsaN: n }; + return mat; + } + throw new Error(`OpenSshKey: unsupported public key algorithm '${algo}'`); +} + +/** + * Public material derived from the private side + the container's own + * public blob. For all supported types the public parts come from the + * blob (already validated against the private section), so this only + * reparses the blob. + */ +function normalizeToPub(keyType: string, priMaterial: Uint8Array, + pubBlob: Uint8Array): PubMaterial { + const mat: PubMaterial = parsePubBlob(pubBlob); + if (mat.algo !== keyType) { + throw new Error('OpenSshKey: container key type does not match its public blob'); + } + return mat; +} + +// -------------------------------------------------------------- raw reads + +/** + * Normalize an mpint-style EC scalar: strip sign byte / leading zeros, then + * left-pad to the 32-byte normalized convention. + */ +function padScalar32(raw: Uint8Array): Uint8Array { + const mag: Uint8Array = normalizeMagnitude(raw); + if (mag.length > 32) { + throw new Error('OpenSshKey: P-256 scalar out of range'); + } + const out: Uint8Array = new Uint8Array(32); + out.set(mag, 32 - mag.length); + return out; +} + +function readU32At(buf: Uint8Array, off: number): number { + if (off < 0 || off + 4 > buf.length) { + throw new Error('OpenSshKey: truncated uint32 in private section'); + } + return ((buf[off] << 24) | (buf[off + 1] << 16) | (buf[off + 2] << 8) | buf[off + 3]) >>> 0; +} + +function readStrAt(buf: Uint8Array, off: number): StrSlice { + const len: number = readU32At(buf, off); + if (off + 4 + len > buf.length) { + throw new Error('OpenSshKey: truncated string in private section'); + } + const slice: StrSlice = { data: buf.slice(off + 4, off + 4 + len), next: off + 4 + len }; + return slice; +} + +function readMpintAt(buf: Uint8Array, off: number): StrSlice { + // readStrAt already consumed the 4-byte length; the content IS the mpint + // body, so only sign-byte/leading-zero normalization remains. + const raw: StrSlice = readStrAt(buf, off); + const slice: StrSlice = { data: normalizeMagnitude(raw.data), next: raw.next }; + return slice; +} + +// ------------------------------------------------------------------ armor + +function extractPemBody(text: string, begin: string, end: string): Uint8Array { + const lines: string[] = text.split('\n'); + let collecting: boolean = false; + let b64: string = ''; + for (let i: number = 0; i < lines.length; i++) { + const line: string = lines[i].replace('\r', '').trim(); + if (line === begin) { + collecting = true; + continue; + } + if (line === end) { + if (!collecting) { + break; + } + return base64ToBytes(b64); + } + if (collecting && line.length > 0) { + b64 += line; + } + } + throw new Error('OpenSshKey: PEM armor not found'); +} + +function armor(der: Uint8Array, begin: string, end: string): string { + const b64: string = bytesToBase64(der); + let out: string = begin + '\n'; + for (let i: number = 0; i < b64.length; i += ARMOR_LINE_WIDTH) { + const endIdx: number = i + ARMOR_LINE_WIDTH; + out += (endIdx < b64.length ? b64.substring(i, endIdx) : b64.substring(i)) + '\n'; + } + out += end + '\n'; + return out; +} diff --git a/entry/src/main/ets/data/SecretStore.ts b/entry/src/main/ets/data/SecretStore.ts new file mode 100644 index 0000000..8f2310c --- /dev/null +++ b/entry/src/main/ets/data/SecretStore.ts @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: secret envelope over a device-encrypted master key. + * - Master key: 32 random bytes in the Asset Store (system secure + * storage); Preferences fallback with an UI-visible warning flag. + * - Passwords: 'ENC:' + base64(iv(12) || AES-256-GCM ciphertext || tag16), + * matching the prefix convention of Haven's CredentialEncryption. + * - Private keys: OpenSSH text encrypted with AES-256-GCM under AAD + * 'haven-ssh-private-key', stored at files/keys/key_.bin. + */ + +import { asset } from '@kit.AssetStoreKit'; +import { preferences } from '@kit.ArkData'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { common } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { CryptoAdapter } from '../ssh/crypto/CryptoAdapter'; +import { Log } from '../common/Log'; +import { bytesToBase64, base64ToBytes, utf8ToBytes, bytesToUtf8, concatBytes } from '../ssh/SshWire'; + +const TAG: string = 'SecretStore'; + +const MASTER_KEY_ALIAS: string = 'haven-ssh-key-master'; +const ENC_PREFIX: string = 'ENC:'; +const AAD_PRIVATE_KEY: string = 'haven-ssh-private-key'; +const AAD_PASSWORD: string = 'haven-ssh-password'; +const GCM_IV_LEN: number = 12; +const FALLBACK_PREFS: string = 'haven_secure'; +const FALLBACK_KEY: string = 'master_key_b64'; + +/** Asset Store error codes we branch on. */ +const ASSET_ERR_NOT_FOUND: number = 24000002; +const ASSET_ERR_EXISTS: number = 24000003; + +export class SecretStore { + private static instance: SecretStore | undefined; + + private masterKey: Uint8Array | null = null; + private fallback: boolean = false; + + static async getInstance(context: common.Context): Promise { + if (SecretStore.instance === undefined) { + SecretStore.instance = new SecretStore(); + } + if (SecretStore.instance.masterKey === null) { + SecretStore.instance.masterKey = + await SecretStore.instance.loadOrCreateMaster(context); + } + return SecretStore.instance; + } + + /** True when the master key is only Preferences-backed (weaker). */ + isUsingFallback(): boolean { + return this.fallback; + } + + /** + * (Re)load the master key from persistent storage. Freshly constructed + * instances must call this before sealing/unsealing; the process-wide + * getInstance() does it automatically. + */ + async ensureMasterKey(context: common.Context): Promise { + if (this.masterKey === null) { + this.masterKey = await this.loadOrCreateMaster(context); + } + } + + // ------------------------------------------------------------- passwords + + isEncryptedValue(value: string): boolean { + return value.startsWith(ENC_PREFIX); + } + + /** Wrap a plaintext password into the 'ENC:' envelope. */ + async encryptPassword(plain: string): Promise { + const sealed: Uint8Array = await this.seal(utf8ToBytes(plain), + utf8ToBytes(AAD_PASSWORD)); + return ENC_PREFIX + bytesToBase64(sealed); + } + + /** + * Unwrap an 'ENC:' envelope. Values without the prefix (legacy plaintext + * rows) are returned unchanged; corrupt envelopes throw. + */ + async decryptPassword(value: string): Promise { + if (!this.isEncryptedValue(value)) { + return value; + } + const sealed: Uint8Array = base64ToBytes(value.substring(ENC_PREFIX.length)); + const plain: Uint8Array = await this.unseal(sealed, utf8ToBytes(AAD_PASSWORD)); + return bytesToUtf8(plain); + } + + // ------------------------------------------------------- private key file + + private keysDir(context: common.Context): string { + return `${context.filesDir}/keys`; + } + + private keyFilePath(context: common.Context, keyId: number): string { + return `${this.keysDir(context)}/key_${keyId}.bin`; + } + + /** Encrypt `opensshText` and write it to files/keys/key_.bin. */ + async savePrivateKeyFile(context: common.Context, keyId: number, + opensshText: string): Promise { + const dir: string = this.keysDir(context); + if (!fs.accessSync(dir)) { + fs.mkdirSync(dir, true); + } + const sealed: Uint8Array = await this.seal(utf8ToBytes(opensshText), + utf8ToBytes(AAD_PRIVATE_KEY)); + const path: string = this.keyFilePath(context, keyId); + const file: fs.File = fs.openSync(path, + fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC); + try { + const buf: ArrayBuffer = sealed.buffer.slice(sealed.byteOffset, + sealed.byteOffset + sealed.byteLength); + fs.writeSync(file.fd, buf); + } finally { + fs.closeSync(file); + } + Log.info(TAG, `private key file written: key_${keyId}.bin (${sealed.length} bytes)`); + } + + /** Read and decrypt files/keys/key_.bin back into OpenSSH text. */ + async loadPrivateKeyFile(context: common.Context, keyId: number): Promise { + const path: string = this.keyFilePath(context, keyId); + const stat: fs.Stat = fs.statSync(path); + const file: fs.File = fs.openSync(path, fs.OpenMode.READ_ONLY); + let sealed: Uint8Array; + try { + const buf: ArrayBuffer = new ArrayBuffer(stat.size); + fs.readSync(file.fd, buf); + sealed = new Uint8Array(buf); + } finally { + fs.closeSync(file); + } + const plain: Uint8Array = await this.unseal(sealed, utf8ToBytes(AAD_PRIVATE_KEY)); + return bytesToUtf8(plain); + } + + /** Remove the on-disk private key file (idempotent). */ + deletePrivateKeyFile(context: common.Context, keyId: number): void { + const path: string = this.keyFilePath(context, keyId); + if (fs.accessSync(path)) { + fs.unlinkSync(path); + Log.info(TAG, `private key file removed: key_${keyId}.bin`); + } + } + + // --------------------------------------------------------------- sealing + + /** iv(12) || ciphertext || GCM tag under the master key. */ + private async seal(plain: Uint8Array, aad: Uint8Array): Promise { + const key: Uint8Array = this.requireMaster(); + const iv: Uint8Array = await CryptoAdapter.randomBytes(GCM_IV_LEN); + const sealed: Uint8Array = await CryptoAdapter.aesGcmEncrypt(key, iv, plain, aad); + return concatBytes(iv, sealed); + } + + private async unseal(sealed: Uint8Array, aad: Uint8Array): Promise { + const key: Uint8Array = this.requireMaster(); + if (sealed.length < GCM_IV_LEN + 16) { + throw new Error('SecretStore: sealed payload too short'); + } + const iv: Uint8Array = sealed.slice(0, GCM_IV_LEN); + const ct: Uint8Array = sealed.slice(GCM_IV_LEN); + return CryptoAdapter.aesGcmDecrypt(key, iv, ct, aad); + } + + private requireMaster(): Uint8Array { + const key: Uint8Array | null = this.masterKey; + if (key === null) { + throw new Error('SecretStore: master key not initialized'); + } + return key; + } + + // ----------------------------------------------------------- master key + + private async loadOrCreateMaster(context: common.Context): Promise { + try { + const existing: Uint8Array | null = await this.queryAssetMaster(); + if (existing !== null) { + return existing; + } + const fresh: Uint8Array = await CryptoAdapter.randomBytes(32); + const attrs: asset.AssetMap = new Map(); + attrs.set(asset.Tag.ALIAS, utf8ToBytes(MASTER_KEY_ALIAS)); + attrs.set(asset.Tag.SECRET, fresh); + attrs.set(asset.Tag.ACCESSIBILITY, asset.Accessibility.DEVICE_POWERED_ON); + try { + await asset.add(attrs); + Log.info(TAG, 'master key created in Asset Store'); + return fresh; + } catch (e) { + const err = e as BusinessError; + if (err.code === ASSET_ERR_EXISTS) { + const raced: Uint8Array | null = await this.queryAssetMaster(); + if (raced !== null) { + return raced; + } + } + throw e; + } + } catch (e) { + const err = e as BusinessError; + Log.error(TAG, `Asset Store unavailable (code ${err.code}), ` + + `falling back to Preferences — ${err.message}`); + this.fallback = true; + return this.loadOrCreateFallbackMaster(context); + } + } + + private async queryAssetMaster(): Promise { + const query: asset.AssetMap = new Map(); + query.set(asset.Tag.ALIAS, utf8ToBytes(MASTER_KEY_ALIAS)); + query.set(asset.Tag.RETURN_TYPE, asset.ReturnType.ALL); + const results: Array = await asset.query(query); + if (results.length === 0) { + return null; + } + const secret: asset.Value = results[0].get(asset.Tag.SECRET); + if (secret === undefined || !(secret instanceof Uint8Array) || secret.length !== 32) { + throw new Error('SecretStore: master key asset has unexpected content'); + } + return secret; + } + + private async loadOrCreateFallbackMaster(context: common.Context): Promise { + const prefs: preferences.Preferences = + preferences.getPreferencesSync(context, { name: FALLBACK_PREFS }); + if (prefs.hasSync(FALLBACK_KEY)) { + const b64: string = prefs.getSync(FALLBACK_KEY, '') as string; + const key: Uint8Array = base64ToBytes(b64); + if (key.length !== 32) { + throw new Error('SecretStore: fallback master key corrupted'); + } + return key; + } + const fresh: Uint8Array = await CryptoAdapter.randomBytes(32); + prefs.putSync(FALLBACK_KEY, bytesToBase64(fresh)); + await this.flushPrefs(prefs); + Log.warn(TAG, 'master key stored in Preferences fallback (weaker protection)'); + return fresh; + } + + private flushPrefs(prefs: preferences.Preferences): Promise { + return new Promise((resolve: () => void, reject: (e: Error) => void): void => { + prefs.flush((err: BusinessError): void => { + if (err) { + reject(new Error(`SecretStore: preferences flush failed — ${err.message}`)); + } else { + resolve(); + } + }); + }); + } +} diff --git a/entry/src/main/ets/data/SettingsRepository.ts b/entry/src/main/ets/data/SettingsRepository.ts new file mode 100644 index 0000000..ca831bb --- /dev/null +++ b/entry/src/main/ets/data/SettingsRepository.ts @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T8 data layer: Preferences-backed user settings (plan §4): + * default_color_scheme, font_size (6-30vp, default 14), keep_screen_on, + * last_tab. Getters are synchronous; setters persist and flush. + */ + +import { preferences } from '@kit.ArkData'; +import { common } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { Log } from '../common/Log'; + +const TAG: string = 'SettingsRepository'; + +const PREFS_NAME: string = 'haven_settings'; +const KEY_COLOR_SCHEME: string = 'default_color_scheme'; +const KEY_FONT_SIZE: string = 'font_size'; +const KEY_KEEP_SCREEN_ON: string = 'keep_screen_on'; +const KEY_LAST_TAB: string = 'last_tab'; + +export const FONT_SIZE_MIN: number = 6; +export const FONT_SIZE_MAX: number = 30; +export const FONT_SIZE_DEFAULT: number = 14; +export const COLOR_SCHEME_DEFAULT: string = 'HAVEN'; + +export class SettingsRepository { + private static instance: SettingsRepository | undefined; + + private prefs: preferences.Preferences; + + static getInstance(context: common.Context): SettingsRepository { + if (SettingsRepository.instance === undefined) { + SettingsRepository.instance = new SettingsRepository( + preferences.getPreferencesSync(context, { name: PREFS_NAME })); + } + return SettingsRepository.instance; + } + + constructor(prefs: preferences.Preferences) { + this.prefs = prefs; + } + + // ------------------------------------------------------------ color scheme + + getDefaultColorScheme(): string { + return this.prefs.getSync(KEY_COLOR_SCHEME, COLOR_SCHEME_DEFAULT) as string; + } + + async setDefaultColorScheme(scheme: string): Promise { + this.prefs.putSync(KEY_COLOR_SCHEME, scheme); + await this.flush(); + } + + // --------------------------------------------------------------- font size + + getFontSize(): number { + const v: number = this.prefs.getSync(KEY_FONT_SIZE, FONT_SIZE_DEFAULT) as number; + if (v < FONT_SIZE_MIN) { + return FONT_SIZE_MIN; + } + if (v > FONT_SIZE_MAX) { + return FONT_SIZE_MAX; + } + return v; + } + + async setFontSize(size: number): Promise { + const clamped: number = size < FONT_SIZE_MIN ? FONT_SIZE_MIN : + (size > FONT_SIZE_MAX ? FONT_SIZE_MAX : size); + this.prefs.putSync(KEY_FONT_SIZE, clamped); + await this.flush(); + } + + // ------------------------------------------------------------ keep screen + + getKeepScreenOn(): boolean { + return this.prefs.getSync(KEY_KEEP_SCREEN_ON, false) as boolean; + } + + async setKeepScreenOn(on: boolean): Promise { + this.prefs.putSync(KEY_KEEP_SCREEN_ON, on); + await this.flush(); + } + + // ---------------------------------------------------------------- last tab + + getLastTab(): number { + return this.prefs.getSync(KEY_LAST_TAB, 0) as number; + } + + async setLastTab(index: number): Promise { + this.prefs.putSync(KEY_LAST_TAB, index); + await this.flush(); + } + + private async flush(): Promise { + await new Promise((resolve: () => void): void => { + this.prefs.flush((err: BusinessError): void => { + if (err) { + Log.error(TAG, `flush failed: ${err.message}`); + } + resolve(); + }); + }); + } +} diff --git a/entry/src/main/ets/pages/DiagPage.ets b/entry/src/main/ets/pages/DiagPage.ets index 4f9f7cf..417921c 100644 --- a/entry/src/main/ets/pages/DiagPage.ets +++ b/entry/src/main/ets/pages/DiagPage.ets @@ -21,10 +21,18 @@ import { verifyHostKeyTofu, InMemoryKnownHostStore, HostKeyDecider, HostKeyPromp HostKeyDecision, HostKeyStatus } from '../ssh/HostKeyVerifier'; import { SshSession, SshSessionOptions, ExecResult } from '../ssh/SshSession'; import { AuthResult } from '../ssh/Auth'; -import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual, concatBytes, SshWriter } from '../ssh/SshWire'; +import { bytesToUtf8, utf8ToBytes, hexToBytes, bytesToHex, bytesEqual, concatBytes, SshWriter, bytesToBase64 } from '../ssh/SshWire'; import { runVtSelfTest, VtTestResult } from '../vterm/VtSelfTest'; import { cryptoFramework } from '@kit.CryptoArchitectureKit'; import { BusinessError } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; +import { Database } from '../data/Database'; +import { SecretStore } from '../data/SecretStore'; +import { KeyRepository } from '../data/KeyRepository'; +import { SshKeyType, KeyRecord } from '../data/Models'; +import { generateKey, GeneratedKey } from '../data/KeyGenerator'; +import { parsePrivateKeyPem, ParsedPrivateKey } from '../data/OpenSshKey'; +import { sha256Fingerprint } from '../common/Fingerprint'; @Entry @Component @@ -143,6 +151,11 @@ struct DiagPage { .onClick(() => { this.runTest((): Promise => this.testVtEmulator()); }) + Button('12. 数据层: 密钥生成→落库→重启读回') + .width('100%') + .onClick(() => { + this.runTest((): Promise => this.testDbKeyStore()); + }) } .width('100%') @@ -849,4 +862,61 @@ struct DiagPage { this.log('FAIL', `VT 终端模拟器自测 ${pass}/${results.length},${fail} 项失败`); } } + + /** + * 12) T8 acceptance: generate an Ed25519 key, persist it (keys row + + * encrypted file), reopen the database with fresh handles simulating a + * restart, read everything back and verify it parses to the same key. + */ + private async testDbKeyStore(): Promise { + const context: common.Context = this.getUIContext().getHostContext() as common.Context; + + this.log('INFO', '生成 Ed25519 密钥…'); + const gen: GeneratedKey = await generateKey(SshKeyType.ED25519, 'diag-key'); + this.log('INFO', `指纹: ${gen.fingerprint}`); + + const db: Database = await Database.getInstance(context); + const secrets: SecretStore = await SecretStore.getInstance(context); + if (secrets.isUsingFallback()) { + this.log('INFO', '注意: Asset Store 不可用,主密钥已降级到 Preferences 存储'); + } + const keyRepo: KeyRepository = new KeyRepository(db, secrets, context); + const record: KeyRecord = { + id: 0, + name: 'diag-key', + algorithm: gen.keyType, + publicBlob: bytesToBase64(gen.pubBlob), + fingerprint: gen.fingerprint, + createdAt: Date.now() + }; + const id: number = await keyRepo.insert(record, gen.opensshPrivate); + this.log('INFO', `已写入 keys 表 (id=${id}),私钥文件已加密落盘`); + + // Simulated restart: brand-new Database + SecretStore handles. + const db2: Database = await Database.openFresh(context); + const secrets2: SecretStore = new SecretStore(); + await secrets2.ensureMasterKey(context); + const keyRepo2: KeyRepository = new KeyRepository(db2, secrets2, context); + + const loaded: KeyRecord | null = await keyRepo2.getById(id); + if (loaded === null) { + this.log('FAIL', `重启后读不到 keys 行 id=${id}`); + return; + } + const pem: string = await keyRepo2.loadPrivateKeyText(id); + const parsed: ParsedPrivateKey = parsePrivateKeyPem(pem); + + const sameBlob: boolean = bytesEqual(parsed.pubBlob, gen.pubBlob); + const sameFp: boolean = sha256Fingerprint(parsed.pubBlob) === loaded.fingerprint; + if (parsed.keyType === SshKeyType.ED25519 && sameBlob && sameFp && + parsed.comment === 'diag-key') { + this.log('PASS', `重启读回一致: ${parsed.keyType} ${loaded.fingerprint} ✓`); + } else { + this.log('FAIL', `读回不一致: type=${parsed.keyType} blob一致=${sameBlob} ` + + `指纹一致=${sameFp} comment=${parsed.comment}`); + } + + await keyRepo2.remove(id); + this.log('INFO', `已清理测试数据 (id=${id})`); + } }