Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/build-harmony-genui-runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const HTML = `<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' resource:; style-src 'self' resource: 'unsafe-inline'; img-src data: blob: https://genui-assets.openbitfun.invalid; font-src 'self' data: resource:; connect-src 'none'; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' resource:; style-src 'self' resource: 'unsafe-inline'; img-src data: blob: https://genui-assets.openbitfun.invalid; font-src 'self' data: resource:; connect-src 'none'; frame-src https://genui-sandbox.openbitfun.invalid/view; object-src 'none'; form-action 'none'; base-uri 'none'">
<link rel="stylesheet" href="runtime.css">
<title>Local GenUI</title>
</head>
Expand Down
12 changes: 9 additions & 3 deletions src/apps/mobile/harmonyos/entry/src/main/ets/pages/AppRoot.ets
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,16 @@ struct AppRoot {
if (!hostContext) {
throw new Error('App root host context is unavailable.');
}
this.showStartupBrand = StartupRevealPreference.claim(hostContext);
this.hostAdapter.attach(hostContext, this.getUIContext());
const firstLaunch = this.showStartupBrand;
const coldStartCandidate = ColdStartPresentationState.claimProcess() && !firstLaunch;
// A cold shortcut is delivered synchronously on subscription. A warm one can
// arrive while a reveal is running or while account restoration is pending.
this.runtime.subscribeToDesktopLaunch(() => {
this.coldStartConsumed = true;
this.showStartupBrand = false;
this.showColdStart = false;
});
this.showStartupBrand = !this.coldStartConsumed && StartupRevealPreference.claim(hostContext);
const coldStartCandidate = !this.coldStartConsumed && ColdStartPresentationState.claimProcess() && !this.showStartupBrand;
await this.runtime.aboutToAppear((signedIn: boolean): void => {
if (!this.coldStartConsumed) {
this.coldStartConsumed = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,12 @@ import { LocalGenUIRuntimeBridge } from '../../services/local-genui/LocalGenUIRu
import { LOCAL_GENUI_ICON3D_ROOT } from '../../services/local-genui/LocalGenUIIcon3DStore';
import { LOCAL_GENUI_PHOTO_ROOT } from '../../services/local-genui/LocalGenUIImageSearch';
import { LOCAL_GENUI_COLLABORATION_ROOT } from '../../services/local-genui/LocalGenUICollaborationAssets';
import { HTML_SANDBOX_URL, htmlSandboxResponse } from '../../services/local-genui/LocalGenUIHtmlSandbox';
import { RemoteLogger } from '../../services/RemoteLogger';

const LOCAL_GENUI_WEB_ID: string = 'local-genui-runtime-web';

/** ArkWeb javaScriptProxy object. Every message is untrusted input. */
class LocalGenUINativeChannel {
private readonly dispatch: (raw: string) => void;
constructor(dispatch: (raw: string) => void) { this.dispatch = dispatch; }
post(raw: string): void { this.dispatch(raw); }
}
const RUNTIME_URL: string = 'resource://rawfile/genui/runtime/index.html';

/**
* Platform leaf for the Local GenUI runtime. It owns only the WebView
Expand All @@ -31,9 +27,19 @@ export struct LocalGenUIWebSurface {
private alive: boolean = true;
// Offline documents repeat the same blocked-resource warning on every render.
private loggedConsole: Set<string> = new Set<string>();
private channel: LocalGenUINativeChannel = new LocalGenUINativeChannel((raw: string): void => {
if (this.alive) this.bridge.receive(raw);
});
private port?: webview.WebMessagePort;

private connectRuntime(url: string): void {
if (!this.alive || url !== RUNTIME_URL || this.controller.getUrl() !== RUNTIME_URL) return;
this.port?.close();
const ports = this.controller.createWebMessagePorts();
this.port = ports[0];
this.port.onMessageEvent((data: webview.WebMessage): void => {
if (this.alive && typeof data === 'string') this.bridge.receive(data);
});
// postMessage targets the main document. No JavaScript proxy is injected into frames.
this.controller.postMessage('local-genui-port', [ports[1]], '*');
}

aboutToAppear(): void {
if (BuildProfile.DEBUG) {
Expand All @@ -45,6 +51,8 @@ export struct LocalGenUIWebSurface {

aboutToDisappear(): void {
this.alive = false;
this.port?.close();
this.port = undefined;
this.bridge.detach();
}

Expand Down Expand Up @@ -100,15 +108,15 @@ export struct LocalGenUIWebSurface {
.darkMode(WebDarkMode.Off)
.forceDarkAccess(false)
.overScrollMode(OverScrollMode.NEVER)
.javaScriptProxy({ object: this.channel, name: 'genuiNative', methodList: ['post'], controller: this.controller })
.onPageEnd((event) => { if (event) this.connectRuntime(event.url); })
.onControllerAttached(() => {
this.bridge.attach((json: string): void => this.send(json));
this.bridge.attachSnapshot((): Promise<image.PixelMap | undefined> => this.capture());
})
.onInterceptRequest((event: OnInterceptRequestEvent): WebResourceResponse | null => {
// Host-served 3D pictures; nothing else is intercepted. Answers are
// asynchronous: the picture may need one download before the cache has it.
// Both the sandbox document and host-served images are answered locally.
const url = event.request.getRequestUrl();
if (!event.request.isMainFrame() && url === HTML_SANDBOX_URL) return htmlSandboxResponse();
const collaborationImage = url.startsWith(LOCAL_GENUI_COLLABORATION_ROOT);
const photo = url.startsWith(LOCAL_GENUI_PHOTO_ROOT);
if (!url.startsWith(LOCAL_GENUI_ICON3D_ROOT) && !collaborationImage && !photo) {
Expand Down Expand Up @@ -140,7 +148,7 @@ export struct LocalGenUIWebSurface {
})
.onOverrideUrlLoading((request: WebResourceRequest) => {
// The runtime never navigates. Generated content cannot open pages.
return request.getRequestUrl().indexOf('genui/runtime/index.html') < 0;
return request.isMainFrame() ? request.getRequestUrl() !== RUNTIME_URL : request.getRequestUrl() !== HTML_SANDBOX_URL;
})
.onConsole((event) => {
if (event && event.message.getMessageLevel() === MessageLevel.Error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export struct MiniAppGallery {
private originX: number = 0;
private originY: number = 0;

private pinning: boolean = false;
@Local pinning: boolean = false;

build() {
Stack({ alignContent: Alignment.TopStart }) {
Expand Down Expand Up @@ -71,10 +71,8 @@ export struct MiniAppGallery {
.borderRadius(4).backgroundColor(index === this.currentIndex() ? INK : SUBTLE)
.opacity(index === this.currentIndex() ? 1 : 0.4)
}, (app: MiniAppGalleryItem): string => app.id)
}.justifyContent(FlexAlign.Center).padding({ top: 20, bottom: 12 })
}.justifyContent(FlexAlign.Center).padding({ top: 20, bottom: this.bottomInset + 16 })
.opacity(this.state.drag.active ? 0 : 1).accessibilityLevel('no')
Text(RemoteI18n.t('miniapp.shortcutHint')).fontSize(MobileDesignTypography.labelSmall.size)
.fontColor(SUBTLE).margin({ bottom: this.bottomInset + 16 }).opacity(this.state.drag.active ? 0 : 1)
}
}.width('100%').height('100%')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,20 @@ export class AppRootRuntime extends AppRootRuntimeComposition {
super(host);
}

async aboutToAppear(onAccountRestored?: (signedIn: boolean) => void): Promise<void> {
subscribeToDesktopLaunch(onLaunch: () => void): void {
// A generated app opened from its home-screen card is local: it does not
// wait for account, device, or remote restoration below.
LocalGenUILaunchInbox.subscribe((appId: string): void => {
onLaunch();
if (BUILTIN_MINIAPP_IDS.includes(appId)) {
void this.miniAppViewModel.openShortcut(appId);
} else {
void this.localGenUIViewModel.openGalleryApp(appId);
}
});
}

async aboutToAppear(onAccountRestored?: (signedIn: boolean) => void): Promise<void> {
// Account login can be tapped while the rest of the cold-start work is
// still running. Initialize its secure store first so the login path never
// races the asynchronous cache and onboarding setup below.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { GitHubAccountProfile, readCachedGitHubProfile } from './GitHubAccountProfile';
import { BusinessError } from '@kit.BasicServicesKit';
import { huks } from '@kit.UniversalKeystoreKit';
import { preferences } from '@kit.ArkData';
import { Encoding } from './Encoding';
Expand All @@ -11,6 +12,16 @@ const CIPHER_KEY: string = 'github_device_session_v1_cipher';
const IV_KEY: string = 'github_device_session_v1_iv';
const HUKS_ALIAS: string = HarmonyUpgradeIdentityContract.CLOUD_ACCOUNT_HUKS_ALIAS;

const DEVICE_CIPHER_KEY: string = 'device_private_key_v1_cipher';
const DEVICE_IV_KEY: string = 'device_private_key_v1_iv';
const GENERATION_KEY: string = 'active_key_generation';

class MissingAccountKeyError extends Error {}

function recordKey(key: string, generation: number): string {
return generation === 0 ? key : `g${generation}_${key}`;
}

export interface PersistedCloudAccountSession {
relayUrl: string;
username: string;
Expand All @@ -32,11 +43,18 @@ export interface PersistedWatchProvisionIdentity {
/** Persists only an HUKS-encrypted account session, never plaintext secrets. */
export class CloudAccountSessionStore {
private store?: preferences.Preferences;
private generation: number = 0;
private deviceKeyWork?: Promise<Uint8Array>;

async init(context: Context): Promise<void> {
try {
this.store = await preferences.getPreferences(context, STORE_NAME);
const store = await preferences.getPreferences(context, STORE_NAME);
const generation = await store.get(GENERATION_KEY, 0);
if (typeof generation !== 'number' || !Number.isSafeInteger(generation) || generation < 0) {
throw new Error('Invalid cloud account key generation.');
}
this.generation = generation;
this.store = store;
} catch (err) {
throw OhosError.wrap('cloud account session init', err);
}
Expand All @@ -49,32 +67,51 @@ export class CloudAccountSessionStore {
}

private async loadOrCreateDeviceSecret(): Promise<Uint8Array> {
const value = await this.readSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv');
let value: string | undefined;
let previous: PersistedCloudAccountSession | undefined;
try {
value = await this.readSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY);
if (!value) previous = await this.load();
} catch (err) {
if (!(err instanceof MissingAccountKeyError) || await this.keyItemExists()) {
throw OhosError.wrap('device identity read', err);
}
// Only explicit sign-in calls deviceSecret(). Preserve every record from
// the previous generation, including its session and watch identities.
const next = this.generation + 1;
const secret = Encoding.randomBytes(32);
await this.writeSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY, Encoding.bytesToBase64(secret), next);
const store = this.requireStore();
await store.put(GENERATION_KEY, next);
await store.flush();
this.generation = next;
RemoteLogger.warn('Cloud account sign-in created a new device identity after confirming the previous key is missing');
return secret;
}
if (value) {
const secret = Encoding.base64ToBytes(value);
if (secret.length !== 32) throw new Error('Stored device identity is invalid.');
return secret;
}
const previous = await this.load();
const secret = previous ? Encoding.base64ToBytes(previous.masterKey) : Encoding.randomBytes(32);
if (secret.length !== 32) throw new Error('Stored device identity is invalid.');
try {
await this.writeSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv', Encoding.bytesToBase64(secret));
await this.writeSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY, Encoding.bytesToBase64(secret));
} catch (err) {
// A reinstall clears Preferences but HarmonyOS may retain the HUKS alias.
// Only rotate the alias when there is no prior session record: existing
// encrypted account data must never be made unreadable as recovery.
if (previous) throw err instanceof Error ? err : new Error(OhosError.reason(err));
RemoteLogger.warn('cloud account device identity write failed on fresh install; recreating local key');
await this.recreateKeyForFreshInstall();
await this.writeSealed('device_private_key_v1_cipher', 'device_private_key_v1_iv', Encoding.bytesToBase64(secret));
await this.writeSealed(DEVICE_CIPHER_KEY, DEVICE_IV_KEY, Encoding.bytesToBase64(secret));
}
return secret;
}

private async recreateKeyForFreshInstall(): Promise<void> {
try {
await huks.deleteKeyItem(HUKS_ALIAS, {});
await huks.deleteKeyItem(recordKey(HUKS_ALIAS, this.generation), {});
} catch (err) {
const message = OhosError.reason(err);
if (message.indexOf('12000011') < 0 && message.indexOf('-13') < 0 &&
Expand Down Expand Up @@ -120,22 +157,23 @@ export class CloudAccountSessionStore {
return `watch_provision_v1_${encodeURIComponent(relayUrl)}_${encodeURIComponent(userId)}_${deviceId}`;
}

private async writeSealed(cipherKey: string, ivKey: string, plaintext: string): Promise<void> {
private async writeSealed(cipherKey: string, ivKey: string, plaintext: string,
generation: number = this.generation): Promise<void> {
try {
const store = this.requireStore();
await this.ensureKey();
await this.ensureKey(generation);
const iv = Encoding.randomBytes(16);
const options = this.options(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, iv);
const handle = await huks.initSession(HUKS_ALIAS, options);
const handle = await huks.initSession(recordKey(HUKS_ALIAS, generation), options);
const encrypted = await huks.finishSession(handle.handle, {
properties: options.properties,
inData: Encoding.utf8ToBytes(plaintext)
});
if (!encrypted.outData || encrypted.outData.length === 0) {
throw new Error('Cloud account session encryption failed.');
}
await store.put(cipherKey, Encoding.bytesToBase64(encrypted.outData));
await store.put(ivKey, Encoding.bytesToBase64(iv));
await store.put(recordKey(cipherKey, generation), Encoding.bytesToBase64(encrypted.outData));
await store.put(recordKey(ivKey, generation), Encoding.bytesToBase64(iv));
await store.flush();
} catch (err) {
throw OhosError.wrap('cloud account session save', err);
Expand All @@ -150,14 +188,23 @@ export class CloudAccountSessionStore {
private async readSealed(cipherKey: string, ivKey: string): Promise<string | undefined> {
try {
const store = this.requireStore();
const cipher = await store.get(cipherKey, '');
const ivText = await store.get(ivKey, '');
const generation = this.generation;
const cipher = await store.get(recordKey(cipherKey, generation), '');
const ivText = await store.get(recordKey(ivKey, generation), '');
if (typeof cipher !== 'string' || typeof ivText !== 'string' || cipher.length === 0 || ivText.length === 0) {
return undefined;
}
const iv = Encoding.base64ToBytes(ivText);
const options = this.options(huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, iv);
const handle = await huks.initSession(HUKS_ALIAS, options);
let handle: huks.HuksSessionHandle;
try {
handle = await huks.initSession(recordKey(HUKS_ALIAS, generation), options);
} catch (err) {
if ((err as BusinessError).code === huks.HuksExceptionErrCode.HUKS_ERR_CODE_ITEM_NOT_EXIST) {
throw new MissingAccountKeyError('The key for the saved cloud account is missing.');
}
throw OhosError.wrap('cloud account decrypt init', err);
}
const decrypted = await huks.finishSession(handle.handle, {
properties: options.properties,
inData: Encoding.base64ToBytes(cipher)
Expand All @@ -174,20 +221,21 @@ export class CloudAccountSessionStore {
async clear(): Promise<void> {
try {
const store = this.requireStore();
await store.delete(CIPHER_KEY);
await store.delete(IV_KEY);
const generation = this.generation;
await store.delete(recordKey(CIPHER_KEY, generation));
await store.delete(recordKey(IV_KEY, generation));
await store.flush();
} catch (err) {
throw OhosError.wrap('cloud account session clear', err);
}
}

private async ensureKey(): Promise<void> {
if (await this.keyItemExists()) {
private async ensureKey(generation: number = this.generation): Promise<void> {
if (await this.keyItemExists(generation)) {
return;
}
try {
await huks.generateKeyItem(HUKS_ALIAS, {
await huks.generateKeyItem(recordKey(HUKS_ALIAS, generation), {
properties: [
{ tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_AES },
{ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 },
Expand All @@ -201,16 +249,12 @@ export class CloudAccountSessionStore {
}
}

private async keyItemExists(): Promise<boolean> {
private async keyItemExists(generation: number = this.generation): Promise<boolean> {
try {
return await huks.isKeyItemExist(HUKS_ALIAS, {});
return await huks.isKeyItemExist(recordKey(HUKS_ALIAS, generation), {});
} catch (err) {
const message = err instanceof Error ? err.message : JSON.stringify(err);
if (message.indexOf('12000011') >= 0 || message.indexOf('-13') >= 0 ||
message.toLowerCase().indexOf('does not exist') >= 0) {
return false;
}
throw new Error(message || 'HUKS key lookup failed.');
if ((err as BusinessError).code === huks.HuksExceptionErrCode.HUKS_ERR_CODE_ITEM_NOT_EXIST) return false;
throw OhosError.wrap('cloud account key lookup', err);
}
}

Expand Down
Loading
Loading