T10: key management UI

- KeysPage: list (name / algorithm / SHA256 fingerprint / date) with
  long-press menu (copy public key / rename / delete)
- FAB menu: generate / paste import / file import
- generate: name + type chips (Ed25519 / ECDSA P-256 / RSA-4096),
  taskpool background thread (@Concurrent generateKeyTask), busy overlay
- paste import: TextArea + parse preview (type + fingerprint) + confirm
- file import: DocumentViewPicker (.pem/.key/.txt) + chunked read +
  parse (encrypted containers rejected by parser)
- import re-serializes to canonical openssh-key-v1 with name as comment
- delete guarded by KeyRepository.isUsed (hosts referencing the key)
- copy public key builds authorized_keys one-liner onto clipboard
This commit is contained in:
STRIX
2026-09-08 18:19:45 +08:00
parent 12c73d7a87
commit 72a4e127e3
+749 -17
View File
@@ -2,33 +2,765 @@
* 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.
* T10: key management — list with fingerprints, FAB menu offering key
* generation (Ed25519 / ECDSA P-256 / RSA-4096 via taskpool background
* thread), paste import with parse preview, and file import via the
* document picker. Row actions: copy public key / rename / delete
* (guarded while referenced by a host).
*/
import { common } from '@kit.AbilityKit';
import { taskpool } from '@kit.ArkTS';
import { fileIo as fs, picker } from '@kit.CoreFileKit';
import { Database } from '../data/Database';
import { SecretStore } from '../data/SecretStore';
import { KeyRepository } from '../data/KeyRepository';
import { generateKey } from '../data/KeyGenerator';
import type { GeneratedKey } from '../data/KeyGenerator';
import { parsePrivateKeyPem, serializeOpensshPrivateKey } from '../data/OpenSshKey';
import type { ParsedPrivateKey } from '../data/OpenSshKey';
import { KeyRecord, SshKeyType } from '../data/Models';
import { sha256Fingerprint } from '../common/Fingerprint';
import { base64ToBytes, bytesToBase64, bytesToUtf8 } from '../ssh/SshWire';
import { authorizedKeysLine } from '../ssh/crypto/KeyImport';
import { copyText, showToast } from './SessionLaunch';
/** RSA-4096 generation is synchronous and heavy — always run off the UI thread. */
@Concurrent
function generateKeyTask(keyType: string, name: string): Promise<GeneratedKey> {
return generateKey(keyType, name);
}
@Component
export struct KeysPage {
build() {
Column({ space: 8 }) {
Text('密钥')
.fontSize(26)
@State keys: KeyRecord[] = [];
/** 0 = closed, 1 = generate, 2 = paste import, 3 = rename. */
@State coverMode: number = 0;
@State generating: boolean = false;
@State genName: string = '';
@State genTypeIndex: number = 0;
@State importText: string = '';
@State importName: string = '';
@State importPreview: string = '';
@State renameName: string = '';
private importKey: ParsedPrivateKey | null = null;
private renameTarget: KeyRecord | null = null;
private keyRepo: KeyRepository | null = null;
aboutToAppear(): void {
this.reload();
}
// ------------------------------------------------------------------ data
private async ensureRepo(): Promise<KeyRepository> {
if (this.keyRepo === null) {
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.keyRepo = new KeyRepository(db, secrets, context);
}
return this.keyRepo;
}
private async reload(): Promise<void> {
try {
const repo: KeyRepository = await this.ensureRepo();
this.keys = await repo.list();
} catch (e) {
showToast(this.getUIContext(), `加载失败:${(e as Error).message}`);
}
}
// ---------------------------------------------------------------- helpers
private algoDisplay(algorithm: string): string {
if (algorithm === SshKeyType.ED25519) {
return 'Ed25519';
}
if (algorithm === SshKeyType.ECDSA_P256) {
return 'ECDSA P-256';
}
if (algorithm === SshKeyType.RSA) {
return 'RSA 4096';
}
return algorithm;
}
private formatDate(ts: number): string {
const d: Date = new Date(ts);
const m: number = d.getMonth() + 1;
const day: number = d.getDate();
const mm: string = m < 10 ? `0${m}` : `${m}`;
const dd: string = day < 10 ? `0${day}` : `${day}`;
return `${d.getFullYear()}-${mm}-${dd}`;
}
private keyTypes(): string[] {
const out: string[] = [SshKeyType.ED25519, SshKeyType.ECDSA_P256, SshKeyType.RSA];
return out;
}
// ---------------------------------------------------------------- actions
private openGenerate(): void {
this.genName = '';
this.genTypeIndex = 0;
this.coverMode = 1;
}
private openPasteImport(): void {
this.importText = '';
this.importName = '';
this.importPreview = '';
this.importKey = null;
this.coverMode = 2;
}
private async runGenerate(): Promise<void> {
const ui: UIContext = this.getUIContext();
if (this.generating) {
return;
}
const name: string = this.genName.trim();
if (name.length === 0) {
showToast(ui, '请输入密钥名称');
return;
}
const types: string[] = this.keyTypes();
const keyType: string = types[this.genTypeIndex];
this.generating = true;
try {
const repo: KeyRepository = await this.ensureRepo();
const task: taskpool.Task = new taskpool.Task(generateKeyTask, keyType, name);
const key: GeneratedKey = await taskpool.execute(task) as GeneratedKey;
const record: KeyRecord = {
id: 0,
name: name,
algorithm: key.keyType,
publicBlob: bytesToBase64(key.pubBlob),
fingerprint: key.fingerprint,
createdAt: Date.now()
};
await repo.insert(record, key.opensshPrivate);
this.coverMode = 0;
showToast(ui, `已生成 ${name}`);
this.reload();
} catch (e) {
showToast(ui, `生成失败:${(e as Error).message}`);
}
this.generating = false;
}
private parseImport(): void {
const ui: UIContext = this.getUIContext();
try {
const parsed: ParsedPrivateKey = parsePrivateKeyPem(this.importText);
this.importKey = parsed;
this.importPreview =
`类型:${this.algoDisplay(parsed.keyType)}\n指纹:${sha256Fingerprint(parsed.pubBlob)}`;
} catch (e) {
this.importKey = null;
this.importPreview = '';
showToast(ui, `无法解析:${(e as Error).message}`);
}
}
private async commitImport(): Promise<void> {
const ui: UIContext = this.getUIContext();
const parsed: ParsedPrivateKey | null = this.importKey;
if (parsed === null) {
showToast(ui, '请先解析密钥');
return;
}
const name: string = this.importName.trim();
if (name.length === 0) {
showToast(ui, '请输入密钥名称');
return;
}
try {
const repo: KeyRepository = await this.ensureRepo();
const fp: string = sha256Fingerprint(parsed.pubBlob);
const privText: string =
serializeOpensshPrivateKey(parsed.keyType, parsed.pubBlob, parsed.priMaterial, name);
const record: KeyRecord = {
id: 0,
name: name,
algorithm: parsed.keyType,
publicBlob: bytesToBase64(parsed.pubBlob),
fingerprint: fp,
createdAt: Date.now()
};
await repo.insert(record, privText);
this.coverMode = 0;
showToast(ui, `已导入 ${name}`);
this.reload();
} catch (e) {
showToast(ui, `导入失败:${(e as Error).message}`);
}
}
private async importFromFile(): Promise<void> {
const ui: UIContext = this.getUIContext();
const context: common.Context | undefined = ui.getHostContext();
if (context === undefined) {
showToast(ui, '无法获取应用上下文');
return;
}
try {
const docPicker: picker.DocumentViewPicker =
new picker.DocumentViewPicker(context);
const opts: picker.DocumentSelectOptions = new picker.DocumentSelectOptions();
const suffixes: string[] = ['.pem', '.key', '.txt'];
opts.fileSuffixFilters = suffixes;
const uris: Array<string> = await docPicker.select(opts);
if (uris.length === 0) {
return;
}
const text: string = this.readTextFromUri(uris[0]);
const parsed: ParsedPrivateKey = parsePrivateKeyPem(text);
const name: string = this.nameFromUri(uris[0]);
const fp: string = sha256Fingerprint(parsed.pubBlob);
const privText: string =
serializeOpensshPrivateKey(parsed.keyType, parsed.pubBlob, parsed.priMaterial, name);
const repo: KeyRepository = await this.ensureRepo();
const record: KeyRecord = {
id: 0,
name: name,
algorithm: parsed.keyType,
publicBlob: bytesToBase64(parsed.pubBlob),
fingerprint: fp,
createdAt: Date.now()
};
await repo.insert(record, privText);
showToast(ui, `已导入 ${name}`);
this.reload();
} catch (e) {
showToast(ui, `导入失败:${(e as Error).message}`);
}
}
private readTextFromUri(uri: string): string {
const file: fs.File = fs.openSync(uri, fs.OpenMode.READ_ONLY);
try {
const parts: Uint8Array[] = [];
let total: number = 0;
const buf: ArrayBuffer = new ArrayBuffer(4096);
while (total < 262144) {
const n: number = fs.readSync(file.fd, buf);
if (n <= 0) {
break;
}
parts.push(new Uint8Array(buf.slice(0, n)));
total += n;
}
const all: Uint8Array = new Uint8Array(total);
let off: number = 0;
for (let i: number = 0; i < parts.length; i++) {
all.set(parts[i], off);
off += parts[i].length;
}
return bytesToUtf8(all);
} finally {
fs.closeSync(file);
}
}
private nameFromUri(uri: string): string {
const slash: number = uri.lastIndexOf('/');
let base: string = slash >= 0 ? uri.substring(slash + 1) : uri;
const dot: number = base.lastIndexOf('.');
if (dot > 0) {
base = base.substring(0, dot);
}
if (base.length === 0) {
return 'imported_key';
}
return base;
}
private async copyPublicKey(record: KeyRecord): Promise<void> {
const ui: UIContext = this.getUIContext();
try {
const blob: Uint8Array = base64ToBytes(record.publicBlob);
const line: string = authorizedKeysLine(record.algorithm, blob, record.name);
copyText(ui, line);
showToast(ui, '公钥已复制,可粘贴到服务器 authorized_keys');
} catch (e) {
showToast(ui, `复制失败:${(e as Error).message}`);
}
}
private openRename(record: KeyRecord): void {
this.renameTarget = record;
this.renameName = record.name;
this.coverMode = 3;
}
private async commitRename(): Promise<void> {
const ui: UIContext = this.getUIContext();
const target: KeyRecord | null = this.renameTarget;
if (target === null) {
this.coverMode = 0;
return;
}
const name: string = this.renameName.trim();
if (name.length === 0) {
showToast(ui, '请输入名称');
return;
}
try {
const repo: KeyRepository = await this.ensureRepo();
await repo.rename(target.id, name);
this.coverMode = 0;
this.renameTarget = null;
this.reload();
} catch (e) {
showToast(ui, `重命名失败:${(e as Error).message}`);
}
}
private confirmDelete(record: KeyRecord): void {
const params: AlertDialogParamWithButtons = {
title: '删除密钥',
message: `确定删除密钥 “${record.name}” 吗?私钥文件将被一并删除。`,
autoCancel: true,
alignment: DialogAlignment.Center,
primaryButton: {
value: '删除',
fontColor: '#E5484D',
action: (): void => {
this.deleteKey(record);
}
},
secondaryButton: {
value: '取消',
fontColor: '#666666',
action: (): void => {
}
}
};
this.getUIContext().showAlertDialog(params);
}
private async deleteKey(record: KeyRecord): Promise<void> {
const ui: UIContext = this.getUIContext();
try {
const repo: KeyRepository = await this.ensureRepo();
if (await repo.isUsed(record.id)) {
showToast(ui, '该密钥正被连接使用,请先修改对应主机');
return;
}
await repo.remove(record.id);
showToast(ui, '已删除');
this.reload();
} catch (e) {
showToast(ui, `删除失败:${(e as Error).message}`);
}
}
// ---------------------------------------------------------------- builders
private menuOption(content: string): MenuItemOptions {
const opt: MenuItemOptions = { content: content };
return opt;
}
private fabMenuItems(): MenuElement[] {
const gen: MenuElement = {
value: '生成密钥',
action: (): void => {
this.openGenerate();
}
};
const paste: MenuElement = {
value: '粘贴导入',
action: (): void => {
this.openPasteImport();
}
};
const file: MenuElement = {
value: '文件导入',
action: (): void => {
this.importFromFile();
}
};
const out: MenuElement[] = [gen, paste, file];
return out;
}
@Builder
sheetHeader(title: string) {
Row() {
Text(title)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.layoutWeight(1)
Button('关闭')
.fontSize(14)
.backgroundColor('#00000000')
.fontColor('#666666')
.onClick((): void => {
this.coverMode = 0;
})
}
.width('100%')
.padding({ left: 20, right: 12, top: 16, bottom: 8 })
}
@Builder
generatePanel() {
Column() {
this.sheetHeader('生成密钥')
Scroll() {
Column() {
Text('名称')
.fontSize(13)
.fontColor('#666666')
.margin({ top: 14, bottom: 6 })
TextInput({ text: this.genName, placeholder: '例如 id_ed25519' })
.width('100%')
.height(44)
.fontSize(14)
.backgroundColor('#F5F6F7')
.borderRadius(10)
.onChange((value: string): void => {
this.genName = value;
})
Text('算法')
.fontSize(13)
.fontColor('#666666')
.margin({ top: 16, bottom: 6 })
Row({ space: 8 }) {
Text('Ed25519')
.fontSize(13)
.padding({ left: 14, right: 14, top: 8, bottom: 8 })
.borderRadius(14)
.backgroundColor(this.genTypeIndex === 0 ? '#0A59F7' : '#FFFFFF')
.fontColor(this.genTypeIndex === 0 ? '#FFFFFF' : '#333333')
.border({ width: 1, color: this.genTypeIndex === 0 ? '#0A59F7' : '#D9D9D9' })
.onClick((): void => {
this.genTypeIndex = 0;
})
Text('ECDSA P-256')
.fontSize(13)
.padding({ left: 14, right: 14, top: 8, bottom: 8 })
.borderRadius(14)
.backgroundColor(this.genTypeIndex === 1 ? '#0A59F7' : '#FFFFFF')
.fontColor(this.genTypeIndex === 1 ? '#FFFFFF' : '#333333')
.border({ width: 1, color: this.genTypeIndex === 1 ? '#0A59F7' : '#D9D9D9' })
.onClick((): void => {
this.genTypeIndex = 1;
})
Text('RSA 4096')
.fontSize(13)
.padding({ left: 14, right: 14, top: 8, bottom: 8 })
.borderRadius(14)
.backgroundColor(this.genTypeIndex === 2 ? '#0A59F7' : '#FFFFFF')
.fontColor(this.genTypeIndex === 2 ? '#FFFFFF' : '#333333')
.border({ width: 1, color: this.genTypeIndex === 2 ? '#0A59F7' : '#D9D9D9' })
.onClick((): void => {
this.genTypeIndex = 2;
})
}
.width('100%')
if (this.genTypeIndex === 2) {
Text('RSA 4096 生成较慢,约需数秒,请耐心等待')
.fontSize(12)
.fontColor('#E5484D')
.margin({ top: 8 })
}
if (this.generating) {
Row({ space: 8 }) {
LoadingProgress()
.width(20)
.height(20)
.color('#0A59F7')
Text('正在生成密钥…')
.fontSize(14)
.fontColor('#666666')
}
.margin({ top: 24 })
} else {
Button('生成')
.width('100%')
.height(44)
.fontSize(15)
.backgroundColor('#0A59F7')
.fontColor('#FFFFFF')
.margin({ top: 24 })
.onClick((): void => {
this.runGenerate();
})
}
}
.width('100%')
.padding({ left: 20, right: 20, top: 16 })
Column({ space: 8 }) {
Text('密钥管理即将开放')
.fontSize(15)
.fontColor('#8C8C8C')
Text('将在下一阶段提供生成、导入与管理功能')
.fontSize(13)
.fontColor('#B0B0B0')
.padding({ left: 20, right: 20 })
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.layoutWeight(1)
.justifyContent(FlexAlign.Center)
.scrollBar(BarState.Off)
}
.width('100%')
.height('100%')
.backgroundColor('#F7F8FA')
.backgroundColor('#F1F3F5')
}
@Builder
pasteImportPanel() {
Column() {
this.sheetHeader('粘贴导入密钥')
Scroll() {
Column() {
Text('名称')
.fontSize(13)
.fontColor('#666666')
.margin({ top: 14, bottom: 6 })
TextInput({ text: this.importName, placeholder: '密钥名称' })
.width('100%')
.height(44)
.fontSize(14)
.backgroundColor('#F5F6F7')
.borderRadius(10)
.onChange((value: string): void => {
this.importName = value;
})
Text('PEM 文本')
.fontSize(13)
.fontColor('#666666')
.margin({ top: 16, bottom: 6 })
TextArea({ text: this.importText, placeholder: '粘贴 -----BEGIN OPENSSH PRIVATE KEY----- / RSA / EC / PKCS8 文本' })
.width('100%')
.height(160)
.fontSize(12)
.backgroundColor('#F5F6F7')
.borderRadius(10)
.onChange((value: string): void => {
this.importText = value;
})
Button('解析')
.width('100%')
.height(40)
.fontSize(14)
.backgroundColor('#FFFFFF')
.fontColor('#0A59F7')
.margin({ top: 12 })
.onClick((): void => {
this.parseImport();
})
if (this.importPreview.length > 0) {
Text(this.importPreview)
.fontSize(13)
.fontColor('#333333')
.width('100%')
.padding(12)
.borderRadius(10)
.backgroundColor('#E8F1FF')
.margin({ top: 12 })
Button('导入')
.width('100%')
.height(44)
.fontSize(15)
.backgroundColor('#0A59F7')
.fontColor('#FFFFFF')
.margin({ top: 12 })
.onClick((): void => {
this.commitImport();
})
}
}
.width('100%')
.padding({ left: 20, right: 20, bottom: 24 })
.alignItems(HorizontalAlign.Start)
}
.layoutWeight(1)
.scrollBar(BarState.Off)
}
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
}
@Builder
renamePanel() {
Column() {
this.sheetHeader('重命名密钥')
Column() {
Text('新名称')
.fontSize(13)
.fontColor('#666666')
.margin({ top: 14, bottom: 6 })
TextInput({ text: this.renameName, placeholder: '密钥名称' })
.width('100%')
.height(44)
.fontSize(14)
.backgroundColor('#F5F6F7')
.borderRadius(10)
.onChange((value: string): void => {
this.renameName = value;
})
Button('保存')
.width('100%')
.height(44)
.fontSize(15)
.backgroundColor('#0A59F7')
.fontColor('#FFFFFF')
.margin({ top: 24 })
.onClick((): void => {
this.commitRename();
})
}
.width('100%')
.padding({ left: 20, right: 20 })
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
}
@Builder
keySheetBuilder() {
Column() {
if (this.coverMode === 1) {
this.generatePanel()
} else if (this.coverMode === 2) {
this.pasteImportPanel()
} else if (this.coverMode === 3) {
this.renamePanel()
}
}
.width('100%')
.height('100%')
}
@Builder
keyRow(record: KeyRecord) {
Row({ space: 12 }) {
Column({ space: 2 }) {
Text(record.name)
.fontSize(16)
.fontWeight(FontWeight.Medium)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Text(`${this.algoDisplay(record.algorithm)} · ${record.fingerprint}`)
.fontSize(12)
.fontColor('#8C8C8C')
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.layoutWeight(1)
.alignItems(HorizontalAlign.Start)
Text(this.formatDate(record.createdAt))
.fontSize(12)
.fontColor('#B0B0B0')
}
.width('100%')
.padding({ left: 16, right: 16, top: 12, bottom: 12 })
.alignItems(VerticalAlign.Center)
.borderRadius(12)
.backgroundColor('#FFFFFF')
}
@Builder
keyMenuBuilder(record: KeyRecord) {
Menu() {
MenuItem(this.menuOption('复制公钥'))
.onClick((): void => {
this.copyPublicKey(record);
})
MenuItem(this.menuOption('重命名'))
.onClick((): void => {
this.openRename(record);
})
MenuItem(this.menuOption('删除'))
.onClick((): void => {
this.confirmDelete(record);
})
}
}
// ---------------------------------------------------------------- build
build() {
Stack({ alignContent: Alignment.BottomEnd }) {
Column() {
Text('密钥')
.fontSize(26)
.fontWeight(FontWeight.Bold)
.width('100%')
.padding({ left: 20, right: 20, top: 16, bottom: 8 })
if (this.keys.length === 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 }) {
ForEach(this.keys, (record: KeyRecord) => {
ListItem() {
this.keyRow(record)
}
.onClick((): void => {
this.copyPublicKey(record);
})
.bindContextMenu((): void => {
this.keyMenuBuilder(record)
}, ResponseType.LongPress)
}, (record: KeyRecord) => record.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 })
.bindMenu(this.fabMenuItems())
}
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
.bindContentCover(this.coverMode > 0, this.keySheetBuilder(), {
modalTransition: ModalTransition.DEFAULT,
onDisappear: (): void => {
this.coverMode = 0;
}
})
}
}