From ffa4f0b339c1872c70840ee0b3096ac01926e6b9 Mon Sep 17 00:00:00 2001 From: Elemt Date: Tue, 3 Nov 2026 11:59:46 +0800 Subject: [PATCH] dev: sync --- common/oh-package-lock.json5 | 19 ++ .../@ohos/common/oh-package-lock.json5 | 19 ++ .../@ohos/common/src/main/cpp/CMakeLists.txt | 11 + .../cpp/types/libunimp_archive/index.d.ts | 1 + .../types/libunimp_archive/oh-package.json5 | 6 + .../common/src/main/cpp/unimp_archive.cpp | 74 +++++ .../common/src/main/ets/utils/HuaweiAuth.ets | 24 ++ .../src/main/ets/utils/UniMpArchive.ets | 41 +++ .../src/main/ets/utils/UniMpDownloader.ets | 134 +++++++++ .../src/main/ets/utils/UniMpHostRuntime.ets | 15 + .../common/src/main/ets/utils/UniMpPolicy.ets | 39 +++ .../src/main/ets/utils/UniMpRelease.ets | 59 ++++ .../src/main/ets/utils/UniMpReporter.ets | 24 ++ .../src/main/ets/utils/UniMpRuntimeCompat.ets | 67 +++++ .../src/main/ets/utils/WindowSafeArea.ets | 156 ++++++++++ .../main/ets/viewmodel/HomeBannerEntity.ets | 22 ++ .../resources/rawfile/unimp-harmony-compat.js | 98 +++++++ .../ohosTest/ets/test/UniMpPassword.test.ets | 69 +++++ .../resources/rawfile/unimp/wrong-id.wgt | Bin 0 -> 604 bytes .../resources/rawfile/unimp/zipcrypto.wgt | Bin 0 -> 498 bytes tests/unimp-host-runtime.test.cjs | 49 ++++ tests/unimp-runtime-compat.test.cjs | 277 ++++++++++++++++++ 22 files changed, 1204 insertions(+) create mode 100644 common/oh-package-lock.json5 create mode 100644 features/mainLayout/oh_modules/@ohos/common/oh-package-lock.json5 create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/cpp/CMakeLists.txt create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/index.d.ts create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/oh-package.json5 create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/cpp/unimp_archive.cpp create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/HuaweiAuth.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpArchive.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpDownloader.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpHostRuntime.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpPolicy.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRelease.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpReporter.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRuntimeCompat.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/WindowSafeArea.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/HomeBannerEntity.ets create mode 100644 features/mainLayout/oh_modules/@ohos/common/src/main/resources/rawfile/unimp-harmony-compat.js create mode 100644 products/app/src/ohosTest/ets/test/UniMpPassword.test.ets create mode 100644 products/app/src/ohosTest/resources/rawfile/unimp/wrong-id.wgt create mode 100644 products/app/src/ohosTest/resources/rawfile/unimp/zipcrypto.wgt create mode 100644 tests/unimp-host-runtime.test.cjs create mode 100644 tests/unimp-runtime-compat.test.cjs diff --git a/common/oh-package-lock.json5 b/common/oh-package-lock.json5 new file mode 100644 index 0000000..675b6b2 --- /dev/null +++ b/common/oh-package-lock.json5 @@ -0,0 +1,19 @@ +{ + "meta": { + "stableOrder": true, + "enableUnifiedLockfile": false + }, + "lockfileVersion": 3, + "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", + "specifiers": { + "libunimp_archive.so@src/main/cpp/types/libunimp_archive": "libunimp_archive.so@src/main/cpp/types/libunimp_archive" + }, + "packages": { + "libunimp_archive.so@src/main/cpp/types/libunimp_archive": { + "name": "libunimp_archive.so", + "version": "1.0.0", + "resolved": "src/main/cpp/types/libunimp_archive", + "registryType": "local" + } + } +} \ No newline at end of file diff --git a/features/mainLayout/oh_modules/@ohos/common/oh-package-lock.json5 b/features/mainLayout/oh_modules/@ohos/common/oh-package-lock.json5 new file mode 100644 index 0000000..675b6b2 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/oh-package-lock.json5 @@ -0,0 +1,19 @@ +{ + "meta": { + "stableOrder": true, + "enableUnifiedLockfile": false + }, + "lockfileVersion": 3, + "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", + "specifiers": { + "libunimp_archive.so@src/main/cpp/types/libunimp_archive": "libunimp_archive.so@src/main/cpp/types/libunimp_archive" + }, + "packages": { + "libunimp_archive.so@src/main/cpp/types/libunimp_archive": { + "name": "libunimp_archive.so", + "version": "1.0.0", + "resolved": "src/main/cpp/types/libunimp_archive", + "registryType": "local" + } + } +} \ No newline at end of file diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/CMakeLists.txt b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..f7dbaf2 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.5.0) +project(unimp_archive) + +set(CMAKE_CXX_STANDARD 17) +set(MINIZIP_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../../../oh_modules/@ohos/minizip") +add_library(minizip_runtime SHARED IMPORTED) +set_target_properties(minizip_runtime PROPERTIES + IMPORTED_LOCATION "${MINIZIP_ROOT}/libs/${OHOS_ARCH}/libminizip_ng.so") + +add_library(unimp_archive SHARED unimp_archive.cpp) +target_link_libraries(unimp_archive PRIVATE minizip_runtime libace_napi.z.so) diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/index.d.ts b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/index.d.ts new file mode 100644 index 0000000..097e829 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/index.d.ts @@ -0,0 +1 @@ +export const extract: (source: string, target: string, password: string) => number; diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/oh-package.json5 b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/oh-package.json5 new file mode 100644 index 0000000..e3cddca --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/types/libunimp_archive/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libunimp_archive.so", + "version": "1.0.0", + "types": "./index.d.ts", + "description": "UniMP ZIP extraction with checked CRC/AES authentication" +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/unimp_archive.cpp b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/unimp_archive.cpp new file mode 100644 index 0000000..f39813d --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/cpp/unimp_archive.cpp @@ -0,0 +1,74 @@ +#include +#include +#include +#include + +// Public C ABI of minizip-ng 4.2.2 bundled by pinned @ohos/minizip 1.0.6. +// https://github.com/zlib-ng/minizip-ng/blob/4.2.2/mz_zip_rw.h +// Use save_all's checked entry close (CRC/AES authentication). The package's +// ExtractFileToJS binding can return bytes even when final authentication fails. +extern "C" { +void *mz_zip_reader_create(void); +void mz_zip_reader_delete(void **handle); +int32_t mz_zip_reader_open_file(void *handle, const char *path); +void mz_zip_reader_set_password(void *handle, const char *password); +void mz_zip_reader_set_encoding(void *handle, int32_t encoding); +int32_t mz_zip_reader_save_all(void *handle, const char *directory); +} + +namespace { +struct ReaderDeleter { + void operator()(void *reader) const { mz_zip_reader_delete(&reader); } +}; + +bool ReadString(napi_env env, napi_value value, std::string &result) { + size_t length = 0; + if (napi_get_value_string_utf8(env, value, nullptr, 0, &length) != napi_ok) return false; + result.resize(length); + if (napi_get_value_string_utf8(env, value, result.data(), length + 1, &length) != napi_ok) return false; + return result.find('\0') == std::string::npos; +} + +napi_value Extract(napi_env env, napi_callback_info info) { + try { + size_t argc = 3; + napi_value argv[3]; + std::string source, target, password; + if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok || argc != 3 || + !ReadString(env, argv[0], source) || !ReadString(env, argv[1], target) || + !ReadString(env, argv[2], password) || source.empty() || target.empty()) { + napi_throw_type_error(env, nullptr, "Invalid WGT extraction arguments"); + return nullptr; + } + std::unique_ptr reader(mz_zip_reader_create()); + if (!reader) { + napi_throw_error(env, nullptr, "Cannot create WGT reader"); + return nullptr; + } + mz_zip_reader_set_encoding(reader.get(), 65001); + mz_zip_reader_set_password(reader.get(), password.c_str()); + int32_t result = mz_zip_reader_open_file(reader.get(), source.c_str()); + if (result == 0) result = mz_zip_reader_save_all(reader.get(), target.c_str()); + napi_value value; + napi_create_int32(env, result, &value); + return value; + } catch (...) { + napi_throw_error(env, nullptr, "WGT native extraction failed"); + return nullptr; + } +} + +napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor property = { + "extract", nullptr, Extract, nullptr, nullptr, nullptr, napi_default, nullptr + }; + napi_define_properties(env, exports, 1, &property); + return exports; +} + +napi_module module = {1, 0, nullptr, Init, "unimp_archive", nullptr, {0}}; +} + +extern "C" __attribute__((constructor)) void RegisterUniMpArchive() { + napi_module_register(&module); +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/HuaweiAuth.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/HuaweiAuth.ets new file mode 100644 index 0000000..4d83e43 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/HuaweiAuth.ets @@ -0,0 +1,24 @@ +import { BusinessError } from '@kit.BasicServicesKit'; + +export const HUAWEI_AUTH_AGREEMENT_URL = + 'https://privacy.consumer.huawei.com/legal/id/authentication-terms.htm?code=CN&language=zh-CN'; + +/** 对齐 weiquan-har 的 HuaweiAuthService,授权交给官方快速登录按钮。 */ +export class HuaweiAuth { + static getErrorMessage(error: BusinessError): string { + switch (error.code) { + case 1001502001: + return '请先在系统设置中登录华为账号,或使用短信验证码登录'; + case 1001502012: + return '已取消华为账号授权'; + case 1001502005: + return '网络异常,请检查网络后重试'; + case 1001500002: + return '正在进行华为账号授权,请稍候'; + case 1005300001: + return '请先阅读并同意用户协议、隐私协议和华为账号用户认证协议'; + default: + return '华为账号授权失败,请重试或使用短信验证码登录'; + } + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpArchive.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpArchive.ets new file mode 100644 index 0000000..ac5ddb9 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpArchive.ets @@ -0,0 +1,41 @@ +import { MinizipNative } from '@ohos/minizip'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { extract } from 'libunimp_archive.so'; + +// Native 解密/解压与文件写入在 TaskPool 中执行,不阻塞首页。 +@Concurrent +export function extractUniMpArchive(wgtPath: string, directory: string, password: string, appId: string): void { + const archive = new MinizipNative(wgtPath); + // Android Zip4JUtil.upZipFileWithPassword 同样明确使用 UTF-8。 + archive.SetCharEncoding(65001); + const code = archive.Open(); + if (code !== 0) { + throw new Error('WGT资源包打开失败,错误码: ' + code); + } + const entries = archive.GetEntryNames(); + if (entries.length === 0) { + throw new Error('WGT资源包为空'); + } + // 在写入任何条目前检查全部路径。 + for (const entry of entries) { + const parts = entry.split('/'); + if (!entry || entry.startsWith('/') || entry.includes('\\') || entry.includes(':') || entry.includes('\0') || + parts.some((part: string) => part === '..' || part === '.') || + parts.slice(0, -1).some((part: string) => part.length === 0)) { + throw new Error('WGT资源包包含非法文件路径'); + } + } + // 直接调用原生 save_all 并检查返回值,不能使用丢失 CRC/AES 校验错误的 ExtractFileToJS。 + const result = extract(wgtPath, directory, password); + if (result !== 0) { + throw new Error('WGT解压失败:密码错误、资源包损坏或写入失败,错误码: ' + result); + } + const manifestPath = directory + '/manifest.json'; + if (!fs.accessSync(manifestPath)) { + throw new Error('WGT资源包缺少manifest.json'); + } + const manifest = JSON.parse(fs.readTextSync(manifestPath)) as Record; + if (manifest['id'] !== appId) { + throw new Error('WGT资源包的应用ID与配置不一致'); + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpDownloader.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpDownloader.ets new file mode 100644 index 0000000..dcf6fb9 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpDownloader.ets @@ -0,0 +1,134 @@ +import { request } from '@kit.BasicServicesKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { UniVersionEntity } from '../viewmodel/DataBean'; +import { isUniMpPackageAvailable } from './KVManager'; +import { getUniMpUrls } from './UniMpPolicy'; +import { reportUniMp } from './UniMpReporter'; +import { Logger } from './Logger'; + +const DOWNLOAD_TIMEOUT = 60000; + +export function removeUniMpPackage(path: string): void { + if (fs.accessSync(path)) { + fs.unlinkSync(path); + } +} + +async function downloadAttempt(context: Context, url: string, path: string, + onProgress: (progress: number) => void): Promise { + removeUniMpPackage(path); + const config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: url, + saveas: path, + mode: request.agent.Mode.FOREGROUND, + overwrite: true, + retry: false + }; + const task = await request.agent.create(context, config); + try { + await new Promise((resolve, reject) => { + let settled = false; + const timer = setTimeout(() => { + fail('下载超时(60秒)'); + }, DOWNLOAD_TIMEOUT); + const fail = (reason: string): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + reject(new Error(reason)); + }; + task.on('progress', (progress: request.agent.Progress) => { + if (!settled && progress.sizes.length > 0 && progress.sizes[0] > 0) { + onProgress(Math.min(99, Math.floor(progress.processed * 100 / progress.sizes[0]))); + } + }); + task.on('completed', () => { + if (!settled) { + settled = true; + clearTimeout(timer); + resolve(); + } + }); + task.on('failed', (info: request.agent.Progress) => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + // failed 事件只携带进度,查询任务才能取得真实网络错误码和原因。 + request.agent.show(task.tid).then((detail: request.agent.TaskInfo) => { + reject(new Error(detail.reason || `下载失败,错误码: ${detail.faults}`)); + }).catch(() => reject(new Error(`下载失败: ${JSON.stringify(info)}`))); + }); + try { + task.start().catch((error: Error) => fail(error.message)); + } catch (error) { + fail((error as Error).message); + } + }); + } finally { + // 停止写入后才允许下一地址重用临时文件。 + try { + await task.stop(); + } catch (_) { + // 完成/失败的任务已经停止。 + } + await request.agent.remove(task.tid); + } +} + +export async function downloadUniMp(context: Context, entity: UniVersionEntity, + onProgress: (progress: number) => void): Promise { + const id = entity.unimp_id ?? ''; + const target = `${context.filesDir}/${id}.wgt`; + const temporary = `${context.filesDir}/${id}_cache.wgt`; + const urls = getUniMpUrls(entity); + let maxProgress = 0; + onProgress(0); + if (urls.length === 0) { + reportUniMp('error', 'client.download.unimp.error', 'url为空!', '上报原因:未配置下载地址'); + throw new Error('未配置下载地址'); + } + for (const url of urls) { + const start = Date.now(); + try { + await downloadAttempt(context, url, temporary, (progress: number) => { + maxProgress = Math.max(maxProgress, progress); + onProgress(maxProgress); + }); + if (!isUniMpPackageAvailable(temporary)) { + throw new Error('下载资源包为空'); + } + } catch (error) { + const reason = (error as Error).message || 'Url连接错误'; + const time = ((Date.now() - start) / 1000).toFixed(2); + reportUniMp('error', 'client.download.unimp.error', reason, + `下载地址:${url} 持续时间:${time}秒 上报原因:${reason}`); + try { + removeUniMpPackage(temporary); + } catch (cleanupError) { + Logger.info('UniMp', `清理临时包失败: ${(cleanupError as Error).message}`); + throw new Error((cleanupError as Error).message); + } + continue; + } + const time = ((Date.now() - start) / 1000).toFixed(2); + try { + // 下载过程中保留旧包,完整下载后才替换;SDK 所需文件名必须为 appId.wgt。 + removeUniMpPackage(target); + fs.renameSync(temporary, target); + } catch (error) { + reportUniMp('error', 'client.download.unimp.error', '复制资源包失败', + `下载地址:${url} 持续时间:${time}秒 上报原因:下载完成,复制资源包失败!`); + throw new Error((error as Error).message); + } + onProgress(100); + reportUniMp('click', 'client.download.unimp.success', `下载时间:${time}s`, + `下载地址:${url} 持续时间:${time}秒 上报原因:下载完成。`); + return target; + } + throw new Error('所有下载地址均失败'); +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpHostRuntime.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpHostRuntime.ets new file mode 100644 index 0000000..441e297 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpHostRuntime.ets @@ -0,0 +1,15 @@ +import { UIAbility } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; +import { hiAppEvent } from '@kit.PerformanceAnalysisKit'; +import { init } from '@dcloudio/uni-app-runtime'; + +export function initUniMpRuntime(ability: UIAbility, stage: window.WindowStage, debug: boolean): void { + try { + init(ability, stage, { debug }); + } finally { + // uni-app-runtime 5.14 在 init 中同步注册此监听器。历史 APP_CRASH 随后异步投递时, + // uni-crash 会在尚无 currentMP 的宿主页面调用 uni.getStorageSync,导致启动循环崩溃。 + // 只关闭这个 SDK 监听器;系统崩溃日志及其他监听器仍保留。SDK 升级后需重新核验。 + hiAppEvent.removeWatcher({ name: 'uniAppCrashWatcher' }); + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpPolicy.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpPolicy.ets new file mode 100644 index 0000000..a7a4570 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpPolicy.ets @@ -0,0 +1,39 @@ +import { UniVersionEntity } from '../viewmodel/DataBean'; + +export enum UniMpUpdate { + NONE, + OPTIONAL, + REQUIRED +} + +export function getUniMpUpdate(entity: UniVersionEntity, localVersion: string, hasPackage: boolean): UniMpUpdate { + if (!hasPackage || entity.force) { + return UniMpUpdate.REQUIRED; + } + const target = entity.version ?? ''; + // 与 Android UserUtils.checkVersion 一致,仅比较三段数字版本。 + if (!/^\d+\.\d+\.\d+$/.test(target) || !/^\d+\.\d+\.\d+$/.test(localVersion)) { + return UniMpUpdate.NONE; + } + const remote = target.split('.').map((part: string) => Number(part)); + const local = localVersion.split('.').map((part: string) => Number(part)); + for (let index = 0; index < 3; index++) { + if (remote[index] > local[index]) { + return UniMpUpdate.OPTIONAL; + } + if (remote[index] < local[index]) { + return UniMpUpdate.NONE; + } + } + return UniMpUpdate.NONE; +} + +export function getUniMpUrls(entity: UniVersionEntity): string[] { + // 新配置以 urls 的顺序为准;旧配置只有 url 时保持兼容。 + const urls = (entity.urls ?? []).filter((url: string) => url.trim().length > 0); + return urls.length > 0 ? urls : (entity.url ? [entity.url] : []); +} + +export function getUniMpReleasePassword(releasePassword: string, uniPassword: string): string { + return (releasePassword.length > 10 ? releasePassword.substring(10) : releasePassword) + uniPassword; +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRelease.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRelease.ets new file mode 100644 index 0000000..ed278c9 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRelease.ets @@ -0,0 +1,59 @@ +import { getUniMPRunPath } from '@dcloudio/uni-app-runtime'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { taskpool } from '@kit.ArkTS'; +import { extractUniMpArchive } from './UniMpArchive'; +import { Logger } from './Logger'; + +// SDK 自带接口没有 password 参数,直接将解密后的资源部署到它公开的运行目录。 +export async function releaseUniMpWgt(appId: string, wgtPath: string, password: string): Promise { + await deployUniMpWgt(appId, wgtPath, password, getUniMPRunPath(appId)); +} + +// 将目录部署与 SDK 上下文分开,真机测试可使用专用目录而不触碰用户的小程序数据。 +export async function deployUniMpWgt(appId: string, wgtPath: string, password: string, root: string): Promise { + if (!/^[A-Za-z0-9_-]+$/.test(appId)) { + throw new Error('小程序ID无效'); + } + const runtime = root + '/www'; + const staging = root + '/www.pending'; + const backup = root + '/www.previous'; + // 恢复上一次在替换运行目录时被中断的部署。 + if (fs.accessSync(backup) && !fs.accessSync(runtime)) { + fs.renameSync(backup, runtime); + } + if (fs.accessSync(backup)) { + await fs.rmdir(backup); + } + if (fs.accessSync(staging)) { + await fs.rmdir(staging); + } + await fs.mkdir(staging, true); + try { + const task = new taskpool.Task(extractUniMpArchive, wgtPath, staging, password, appId); + await taskpool.execute(task); + // 只替换 www,保留小程序的 _doc 等业务数据。 + if (fs.accessSync(runtime)) { + fs.renameSync(runtime, backup); + } + try { + fs.renameSync(staging, runtime); + } catch (error) { + if (fs.accessSync(backup)) { + fs.renameSync(backup, runtime); + } + throw new Error('WGT运行目录替换失败'); + } + } finally { + if (fs.accessSync(staging)) { + await fs.rmdir(staging); + } + } + // 新资源已经完整部署;旧目录的清理失败不能误报本次解压失败。 + try { + if (fs.accessSync(backup)) { + await fs.rmdir(backup); + } + } catch (_) { + Logger.info('UniMp', '旧资源目录将在下次部署时清理'); + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpReporter.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpReporter.ets new file mode 100644 index 0000000..0d36a30 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpReporter.ets @@ -0,0 +1,24 @@ +import { PLATFORM } from '../constants/AppConstants'; +import { ApiManager } from '../provider/ApiManager'; +import { Logger } from './Logger'; + +interface UniMpReport { + source: string; + type: string; + key: string; + value: string; + extra: string; +} + +// 使用 Android 相同的接口、事件名称和字段,沿用宿主已有的 source/请求签名约定。 +export function reportUniMp(type: string, key: string, value: string = '', extra: string = ''): void { + const data: UniMpReport = { source: PLATFORM, type: type, key: key, value: value, extra: extra }; + try { + ApiManager.getInstance().request('/api/user/event', undefined, 'post', data).catch((error: Error) => { + // 上报失败不能影响下载、解压或启动,也不递归上报。 + Logger.info('UniMp', `事件上报失败 ${key}: ${error.message}`); + }); + } catch (error) { + Logger.info('UniMp', `事件上报失败 ${key}: ${(error as Error).message}`); + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRuntimeCompat.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRuntimeCompat.ets new file mode 100644 index 0000000..2ffc421 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/UniMpRuntimeCompat.ets @@ -0,0 +1,67 @@ +import { common } from '@kit.AbilityKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { util } from '@kit.ArkTS'; +import { getUniMPRunPath } from '@dcloudio/uni-app-runtime'; +import { Logger } from './Logger'; + +/** 修复旧 WGT 在鸿蒙启动时读取 plus.os.name 等缺失元数据导致的白屏。 */ +export class UniMpRuntimeCompat { + static readonly MARKER: string = '/* rabbit-unimp-harmony-compat:v6 */'; + + static async prepare(context: common.Context, appId: string): Promise { + const servicePath = getUniMPRunPath(appId) + '/www/app-service.js'; + let source = await fs.readText(servicePath); + if (source.startsWith(UniMpRuntimeCompat.MARKER)) { + return; + } + if (source.startsWith('/* rabbit-unimp-harmony-compat:v1 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v2 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v3 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v4 */') || + source.startsWith('/* rabbit-unimp-harmony-compat:v5 */')) { + const endMarker = '/* end-rabbit-unimp-harmony-compat */'; + const end = source.indexOf(endMarker); + if (end < 0) { + throw new Error('旧版小程序兼容脚本不完整'); + } + source = source.substring(end + endMarker.length).replace(/^\r?\n/, ''); + } + // 当前 WGT 留有无业务回调的 safeBottom 调试弹窗。只移除已确认的这一条语句, + // 不拦截 showModal API,也不修改其他提示、协议或确认逻辑。 + source = source.replace( + /uni\.showModal\(\{title:"safeBottom",showCancel:!1,content:[$\w]+\.safeBottom,success:function\([$\w]+\)\{\}\}\)/g, + 'void 0'); + if (!source.trim()) { + throw new Error('小程序启动脚本为空'); + } + const resource = await context.resourceManager.getRawFileContent('unimp-harmony-compat.js'); + const bootstrap = util.TextDecoder.create('utf-8').decodeWithStream(resource); + if (!bootstrap.startsWith(UniMpRuntimeCompat.MARKER)) { + throw new Error('小程序启动兼容资源无效'); + } + const temporary = servicePath + '.compat-tmp'; + try { + const file = await fs.open(temporary, fs.OpenMode.CREATE | fs.OpenMode.WRITE_ONLY | fs.OpenMode.TRUNC); + try { + const bytes = new util.TextEncoder().encodeInto(bootstrap + '\n' + source); + let written = 0; + while (written < bytes.byteLength) { + const count = await fs.write(file.fd, bytes.buffer.slice(written)); + if (count <= 0) { + throw new Error('小程序启动兼容脚本写入不完整'); + } + written += count; + } + } finally { + await fs.close(file); + } + // 只更新已解压的运行资源,原始 WGT 和用户数据不变。 + await fs.rename(temporary, servicePath); + Logger.info('UniMp', '已补齐鸿蒙启动元数据: ' + appId); + } finally { + if (fs.accessSync(temporary)) { + await fs.unlink(temporary); + } + } + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/WindowSafeArea.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/WindowSafeArea.ets new file mode 100644 index 0000000..9424512 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/utils/WindowSafeArea.ets @@ -0,0 +1,156 @@ +import { window } from '@kit.ArkUI'; +import { common } from '@kit.AbilityKit'; +import { settings } from '@kit.BasicServicesKit'; +import { Logger } from './Logger'; + +export interface NavigationInsets { + left: number; + right: number; + bottom: number; +} + +// 传统三键导航属于 TYPE_SYSTEM,手势导航属于 TYPE_NAVIGATION_INDICATOR。 +// 两类区域可能重叠,取最大值,不能累加;返回值单位为 px。 +export function getNavigationInsets(mainWindow: window.Window): NavigationInsets { + const systemArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); + const navigationArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR); + return { + left: Math.max(0, systemArea.leftRect.width, navigationArea.leftRect.width), + right: Math.max(0, systemArea.rightRect.width, navigationArea.rightRect.width), + bottom: Math.max(0, systemArea.bottomRect.height, navigationArea.bottomRect.height) + }; +} + +const FLOAT_NAVIGATION_KEY: string = 'float_navigation_info'; + +interface FloatingNavigationInfo { + showType: number; + region: number[]; +} + +// 悬浮三键在部分系统版本不计入 TYPE_SYSTEM;region 是屏幕坐标,单位 px。 +export function getFloatingNavigationInsets(value: string, bounds: window.Rect): NavigationInsets { + const result: NavigationInsets = { left: 0, right: 0, bottom: 0 }; + try { + const info = JSON.parse(value) as FloatingNavigationInfo; + if (!info || info.showType !== 0 || !Array.isArray(info.region) || info.region.length !== 4 || + !info.region.every((part: number) => typeof part === 'number' && Number.isFinite(part))) { + return result; + } + const x = info.region[0]; + const y = info.region[1]; + const width = info.region[2]; + const height = info.region[3]; + const right = bounds.left + bounds.width; + const bottom = bounds.top + bounds.height; + if (width <= 0 || height <= 0 || x >= right || x + width <= bounds.left || + y >= bottom || y + height <= bounds.top) { + return result; + } + if (width >= height && y + height >= bottom) { + result.bottom = bottom - Math.max(bounds.top, y); + } else if (width < height && x <= bounds.left) { + result.left = Math.min(right, x + width) - bounds.left; + } else if (width < height && x + width >= right) { + result.right = right - Math.max(bounds.left, x); + } + } catch (_) { + // 平板、旧系统或设置尚未就绪时,继续使用窗口标准避让区域。 + } + return result; +} + +export class WindowSafeArea { + private mainWindow: window.Window | undefined = undefined; + private context: common.UIAbilityContext | undefined = undefined; + private floatingNavigationValue: string = ''; + private navigationRequest: number = 0; + private observingNavigation: boolean = false; + private readonly onFloatingNavigationChange = (): void => { this.refresh(); }; + private readonly onAvoidAreaChange = (options: window.AvoidAreaOptions): void => { + if (options.type === window.AvoidAreaType.TYPE_SYSTEM || + options.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) { + this.refresh(); + } + }; + private readonly onWindowSizeChange = (): void => { + this.refresh(); + }; + + start(mainWindow: window.Window, context: common.UIAbilityContext): void { + this.stop(); + this.mainWindow = mainWindow; + this.context = context; + mainWindow.on('avoidAreaChange', this.onAvoidAreaChange); + mainWindow.on('windowSizeChange', this.onWindowSizeChange); + try { + this.observingNavigation = settings.registerKeyObserver(context, FLOAT_NAVIGATION_KEY, + settings.domainName.USER_PROPERTY, this.onFloatingNavigationChange); + } catch (_) {} + this.refresh(); + } + + refresh(): void { + this.updateInsets(); + const context = this.context; + if (!context) { return; } + const request = ++this.navigationRequest; + this.updateFloatingNavigation(context, request); + } + + private async updateFloatingNavigation(context: common.UIAbilityContext, request: number): Promise { + try { + const value = await settings.getValue(context, FLOAT_NAVIGATION_KEY, settings.domainName.USER_PROPERTY); + if (request !== this.navigationRequest || context !== this.context) { return; } + this.floatingNavigationValue = value; + this.updateInsets(); + } catch (_) { + if (request !== this.navigationRequest || context !== this.context) { return; } + this.floatingNavigationValue = ''; + this.updateInsets(); + } + } + + private updateInsets(): void { + const mainWindow = this.mainWindow; + if (!mainWindow) { + return; + } + try { + const uiContext = mainWindow.getUIContext(); + const systemArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM); + const insets = getNavigationInsets(mainWindow); + const floating = getFloatingNavigationInsets(this.floatingNavigationValue, + mainWindow.getWindowProperties().windowRect); + insets.left = Math.max(insets.left, floating.left); + insets.right = Math.max(insets.right, floating.right); + insets.bottom = Math.max(insets.bottom, floating.bottom); + AppStorage.setOrCreate('statusBarHeight', uiContext.px2vp(systemArea.topRect.height)); + AppStorage.setOrCreate('navigationBarLeft', uiContext.px2vp(insets.left)); + AppStorage.setOrCreate('navigationBarRight', uiContext.px2vp(insets.right)); + AppStorage.setOrCreate('navigationBarBottom', uiContext.px2vp(insets.bottom)); + // 三键导航是不可遮挡的系统区域;首页可单独收紧手势指示条上方的留白。 + AppStorage.setOrCreate('systemNavigationBarBottom', + uiContext.px2vp(Math.max(0, systemArea.bottomRect.height, floating.bottom))); + } catch (error) { + Logger.error('WindowSafeArea', '更新系统栏避让区域失败: ' + JSON.stringify(error)); + } + } + + stop(): void { + this.navigationRequest++; + if (this.context && this.observingNavigation) { + try { + settings.unregisterKeyObserver(this.context, FLOAT_NAVIGATION_KEY, settings.domainName.USER_PROPERTY); + } catch (_) {} + } + this.observingNavigation = false; + this.context = undefined; + this.floatingNavigationValue = ''; + if (this.mainWindow) { + this.mainWindow.off('avoidAreaChange', this.onAvoidAreaChange); + this.mainWindow.off('windowSizeChange', this.onWindowSizeChange); + this.mainWindow = undefined; + } + } +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/HomeBannerEntity.ets b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/HomeBannerEntity.ets new file mode 100644 index 0000000..5adcb85 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/ets/viewmodel/HomeBannerEntity.ets @@ -0,0 +1,22 @@ +/** client.banner.home,与 Rabbit-android HomeBannerEntity 字段一致。 */ +export interface HomeBannerEntity { + img?: string | null; + url?: string | null; + type?: string | null; + enable?: boolean | null; + text?: string | null; +} + +export function visibleHomeBanners(value: Object | null | undefined): HomeBannerEntity[] { + if (!Array.isArray(value)) { + return []; + } + const result: HomeBannerEntity[] = []; + for (const item of value as (HomeBannerEntity | null)[]) { + if (item && item.enable === true && typeof item.img === 'string' && item.img.trim().length > 0 && + (item.type === 'wx' || item.type === 'alipay' || item.type === 'app' || item.type === 'web')) { + result.push(item); + } + } + return result; +} diff --git a/features/mainLayout/oh_modules/@ohos/common/src/main/resources/rawfile/unimp-harmony-compat.js b/features/mainLayout/oh_modules/@ohos/common/src/main/resources/rawfile/unimp-harmony-compat.js new file mode 100644 index 0000000..ee4d435 --- /dev/null +++ b/features/mainLayout/oh_modules/@ohos/common/src/main/resources/rawfile/unimp-harmony-compat.js @@ -0,0 +1,98 @@ +/* rabbit-unimp-harmony-compat:v6 */ +// Legacy WGT startup reads these properties before mounting its first page. +// Only fill metadata absent from the Harmony SDK; do not emulate native Android APIs. +(function () { + if (typeof plus !== 'object' || !plus || typeof uni !== 'object' || !uni) return; + + // Both console and uni.__log__ are wrapped by the WGT's native log bridge. + // Reentry guards alone still let JSON.stringify walk a whole Vue component tree. + // Never enumerate objects (or invoke their getters/toJSON) at these log boundaries. + var logDepth = 0; + var guarded = new WeakSet(); + function logValue(value) { + if (value === null) return value; + if (typeof value === 'object') { + try { + if (value instanceof Error) return String(value.stack || value.message).slice(0, 2048); + return Array.isArray(value) ? '[Array]' : '[Object]'; + } catch (_) { return '[Object]'; } + } + if (typeof value === 'function') return '[Function]'; + return typeof value === 'string' ? value.slice(0, 2048) : value; + } + function protectLog(target, key) { + var descriptor = Object.getOwnPropertyDescriptor(target, key); + if (descriptor && descriptor.configurable === false) return; + function guard(fn) { + if (typeof fn !== 'function' || guarded.has(fn)) return fn; + var active = false; + var wrapped = function () { + if (active || logDepth >= 8) return; + active = true; + logDepth++; + try { + var args = []; + for (var i = 0; i < arguments.length && i < 16; i++) args.push(logValue(arguments[i])); + return fn.apply(target, args); + } finally { + logDepth--; + active = false; + } + }; + guarded.add(wrapped); + return wrapped; + } + var current = guard(target[key]); + Object.defineProperty(target, key, { + configurable: true, enumerable: true, + get: function () { return current; }, + set: function (fn) { current = guard(fn); } + }); + } + if (typeof console === 'object' && console) { + ['log', 'info', 'warn', 'error', 'debug'].forEach(function (level) { protectLog(console, level); }); + } + protectLog(uni, '__log__'); + + function systemInfo() { + try { return uni.getSystemInfoSync() || {}; } catch (_) { return {}; } + } + + function hostVersion() { + try { + var launch = uni.getLaunchOptionsSync(); + var extra = launch && launch.referrerInfo && launch.referrerInfo.extraData; + if (extra && extra['x-version']) return String(extra['x-version']); + } catch (_) {} + try { return String(uni.getAppBaseInfo().hostVersion || ''); } catch (_) { return ''; } + } + + if (!plus.os) { + var info = systemInfo(); + // Reporting Android here would select unsupported plus.android code paths. + plus.os = { name: 'HarmonyOS', version: info.osVersion || info.system || '', language: info.language || '' }; + } + if (!plus.device) { + var device = systemInfo(); + plus.device = { vendor: device.brand || '', model: device.model || '' }; + } + // Legacy templates read this field on every row but never define it on Harmony. + // Supply it before the first render instead of suppressing Vue's warning handler. + if (typeof Vue === 'object' && Vue) { + ['createApp', 'createSSRApp', 'createVueApp'].forEach(function (key) { + var create = Vue[key]; + var descriptor = Object.getOwnPropertyDescriptor(Vue, key); + if (typeof create !== 'function' || (descriptor && descriptor.writable === false)) return; + Vue[key] = function () { + var app = create.apply(this, arguments); + var properties = app && app.config && app.config.globalProperties; + if (properties && !('$system' in properties)) properties.$system = plus.os.name; + return app; + }; + }); + } + if (plus.runtime && !('version' in plus.runtime)) { + Object.defineProperty(plus.runtime, 'version', { configurable: true, enumerable: true, get: hostVersion }); + } +})(); +/* end-rabbit-unimp-harmony-compat */ diff --git a/products/app/src/ohosTest/ets/test/UniMpPassword.test.ets b/products/app/src/ohosTest/ets/test/UniMpPassword.test.ets new file mode 100644 index 0000000..e1a680f --- /dev/null +++ b/products/app/src/ohosTest/ets/test/UniMpPassword.test.ets @@ -0,0 +1,69 @@ +import { describe, it, expect } from '@ohos/hypium'; +import { abilityDelegatorRegistry } from '@kit.TestKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { deployUniMpWgt } from '@ohos/common/src/main/ets/utils/UniMpRelease'; +import { getUniMpReleasePassword } from '@ohos/common/src/main/ets/utils/UniMpPolicy'; + +const TEST_ID = '__UNI__PASSWORD_TEST'; + +function writeText(path: string, text: string): void { + const parent = path.substring(0, path.lastIndexOf('/')); + if (!fs.accessSync(parent)) { fs.mkdirSync(parent, true); } + const file = fs.openSync(path, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE | fs.OpenMode.TRUNC); + try { fs.writeSync(file.fd, text); } finally { fs.closeSync(file); } +} + +async function verifyArchive(name: string, password: string, fails: boolean = false, + interrupted: boolean = false): Promise { + const context = abilityDelegatorRegistry.getAbilityDelegator().getAppContext(); + const resources = context.createModuleContext('app_test').resourceManager; + // 只操作测试专用目录,不使用 SDK 的真实 apps 路径。 + const base = context.filesDir + '/unimp-password-tests'; + if (fs.accessSync(base)) { await fs.rmdir(base); } + await fs.mkdir(base, true); + const wgtPath = base + '/fixture.wgt'; + const root = base + '/runtime'; + const bytes = await resources.getRawFileContent('unimp/' + name + '.wgt'); + const file = fs.openSync(wgtPath, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE); + try { fs.writeSync(file.fd, bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)); } + finally { fs.closeSync(file); } + writeText(root + (interrupted ? '/www.previous' : '/www') + '/old.txt', 'old resources'); + writeText(root + '/doc/user.txt', 'user data'); + try { + let rejected = false; + try { await deployUniMpWgt(TEST_ID, wgtPath, password, root); } + catch (_) { rejected = true; } + expect(rejected).assertEqual(fails); + expect(fs.readTextSync(root + '/doc/user.txt')).assertEqual('user data'); + expect(fs.accessSync(root + '/www.pending')).assertFalse(); + expect(fs.accessSync(root + '/www.previous')).assertFalse(); + expect(fs.accessSync(root + '/outside.txt')).assertFalse(); + if (fails) { + expect(fs.readTextSync(root + '/www/old.txt')).assertEqual('old resources'); + expect(fs.accessSync(root + '/www/manifest.json')).assertFalse(); + } else { + expect(fs.readTextSync(root + '/www/static/中文.txt')).assertEqual('UniMP 密码解压验证'); + expect(fs.statSync(root + '/www/empty.txt').size).assertEqual(0); + expect(fs.accessSync(root + '/www/old.txt')).assertFalse(); + } + } finally { + await fs.rmdir(base); + } +} + +export default function uniMpPasswordTest() { + describe('UniMpPasswordTest', () => { + const password = getUniMpReleasePassword('0123456789test-password-', 'tail'); + it('plainWgt', 0, async () => { await verifyArchive('plain', ''); }); + it('plainWgtWithConfiguredPassword', 0, async () => { await verifyArchive('plain', password); }); + it('zipCryptoWgt', 0, async () => { await verifyArchive('zipcrypto', password); }); + it('aes128Wgt', 0, async () => { await verifyArchive('aes128', password); }); + it('aes256Wgt', 0, async () => { await verifyArchive('aes256', password); }); + it('wrongPasswordPreservesOldResources', 0, async () => { await verifyArchive('aes256', 'wrong', true); }); + it('missingPasswordFails', 0, async () => { await verifyArchive('zipcrypto', '', true); }); + it('corruptWgtFails', 0, async () => { await verifyArchive('corrupt', password, true); }); + it('wrongAppIdFails', 0, async () => { await verifyArchive('wrong-id', password, true); }); + it('unsafePathFails', 0, async () => { await verifyArchive('traversal', password, true); }); + it('interruptedDeploymentRecovers', 0, async () => { await verifyArchive('aes256', password, false, true); }); + }); +} diff --git a/products/app/src/ohosTest/resources/rawfile/unimp/wrong-id.wgt b/products/app/src/ohosTest/resources/rawfile/unimp/wrong-id.wgt new file mode 100644 index 0000000000000000000000000000000000000000..1688585755c36dc70ce15e1621338ac99092c04e GIT binary patch literal 604 zcmWIWW@a&F;N(bV=qgN#Wk3SF4BQO4iFui6sl_FFS;hHzj5FC8m>3*gnK>9{?MyiL zq499TVZFDz^k?KSJwCwZ&L1kiuht^GD&Dv`zhUiKo|5OYJJxM{-|F${cC=fAVy#%x zw?5`IToWXxJP{6)5w0-R>$YYy_1G90;LXkfvey@g4S+ZRr;`MMPAV=*EXhpPf3jok zvuW*mB^4z|&bk!Q$?ULYE^F>GrUM$K+@B(jcIssYocnrg(bSEij-Pi+`31gGIN-ef zS99Od_+6J(L{+^!RvTEs9AFN#Tmr8HIDrmG%`GUYM7P-Nfa0gQC7zr!T^78{?kVJp zGr9QL`=9=#X$$9g>cPyH1DXv20p5&E#tf*T4)Z)H)KLMhIKXBK%m<)=LV(FYCca?9 iW)jS;ARi-u2qObl{|9)pvVl}F1K}kgT>@0czyJWvf{%{? literal 0 HcmV?d00001 diff --git a/products/app/src/ohosTest/resources/rawfile/unimp/zipcrypto.wgt b/products/app/src/ohosTest/resources/rawfile/unimp/zipcrypto.wgt new file mode 100644 index 0000000000000000000000000000000000000000..03080f954a860eba0696c908bc5dddc760b6e713 GIT binary patch literal 498 zcmWIWW@Zs#;N;+7=qgN#Wk3SFKz43oUS?Wqafx15aeiK+S)uJ!0SiC=mp?5_PnF~? zak;r_ipG=w&u!nno$YRR^Zz}UY}1X^MJ$_?-PV?9<<0-4>X`ax<2;K86ZXmf+Vgk8 z9-af&1H9Qeil)R0xB^YL0OA0g_6q`Ki%SwqGL!Y6>{$D3TDx9JMG0F=i}5U-JHJ1E z%$K%Wb$zqOt}T@bXI__Sr2hN4E-YYgk6rjATgwk1TY~Q%vR4P1A%WKxPM~aRZb3;U z$aHS=m4Y8!3ms?M*L>fb3Ni#J%fJUBfFQt|k;#|=5m?CH00kB*KnXf@t;lWz`4a&e nfJ_WuqiY8#hq(&m0R(skWWv1@;LXYgl41tJjX+wP5yS%kquPO5 literal 0 HcmV?d00001 diff --git a/tests/unimp-host-runtime.test.cjs b/tests/unimp-host-runtime.test.cjs new file mode 100644 index 0000000..9605f86 --- /dev/null +++ b/tests/unimp-host-runtime.test.cjs @@ -0,0 +1,49 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const ts = require(process.env.UNIMP_TYPESCRIPT || 'C:/Program Files/Huawei/DevEco Studio/tools/hvigor/hvigor/node_modules/typescript'); + +function fixture(failInit = false) { + const watchers = new Map([['hostWatcher', () => {}]]); + const calls = [], exports = {}; + const filename = path.join(__dirname, '../common/src/main/ets/utils/UniMpHostRuntime.ets'); + const code = ts.transpileModule(fs.readFileSync(filename, 'utf8'), { + fileName: 'UniMpHostRuntime.ts', + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } + }).outputText; + const mocks = { + '@dcloudio/uni-app-runtime': { init: (ability, stage, config) => { + calls.push({ ability, stage, config }); + // SDK 5.14 registers this synchronously; historical crashes arrive later. + watchers.set('uniAppCrashWatcher', () => { throw new TypeError('Cannot read property appId of null'); }); + if (failInit) throw new Error('SDK init failed'); + } }, + '@kit.PerformanceAnalysisKit': { hiAppEvent: { removeWatcher: watcher => watchers.delete(watcher.name) } } + }; + vm.runInNewContext(code, { exports, require: name => { + assert.ok(mocks[name], name); + return mocks[name]; + } }); + return { init: exports.initUniMpRuntime, watchers, calls }; +} + +test('cold start and recreated stages cannot replay old crashes into mini-program storage', () => { + const f = fixture(), ability = {}, stage = {}; + for (let i = 0; i < 3; i++) { + f.init(ability, stage, true); + assert.doesNotThrow(() => f.watchers.forEach(callback => callback())); + assert.equal(f.watchers.has('uniAppCrashWatcher'), false); + assert.equal(f.watchers.has('hostWatcher'), true); + } + assert.equal(f.calls[0].ability, ability); + assert.equal(f.calls[0].stage, stage); + assert.equal(f.calls[0].config.debug, true); +}); + +test('partial SDK initialization removes the unsafe watcher and preserves the original error', () => { + const f = fixture(true); + assert.throws(() => f.init({}, {}, false), /SDK init failed/); + assert.equal(f.watchers.has('uniAppCrashWatcher'), false); +}); diff --git a/tests/unimp-runtime-compat.test.cjs b/tests/unimp-runtime-compat.test.cjs new file mode 100644 index 0000000..eb1ea7e --- /dev/null +++ b/tests/unimp-runtime-compat.test.cjs @@ -0,0 +1,277 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const { TextEncoder, TextDecoder } = require('node:util'); +const ts = require(process.env.UNIMP_TYPESCRIPT || 'C:/Program Files/Huawei/DevEco Studio/tools/hvigor/hvigor/node_modules/typescript'); +const root = path.resolve(__dirname, '..'); +const bootstrap = fs.readFileSync(path.join(root, 'common/src/main/resources/rawfile/unimp-harmony-compat.js'), 'utf8'); + +function sandbox(plus = { runtime: {} }) { + return { plus, uni: { + getSystemInfoSync: () => ({ osVersion: '5.1', system: 'HarmonyOS 5.1', language: 'zh-CN', brand: 'HUAWEI', model: 'test-model' }), + getLaunchOptionsSync: () => ({ referrerInfo: { extraData: { 'x-version': '1.0.1' } } }), + getAppBaseInfo: () => ({ hostVersion: 'fallback-version' }) + }}; +} + +test('legacy plus.os.name startup crashes without compatibility and mounts after it', () => { + const source = 'var platform = plus.os.name.toLowerCase(); var mounted = true;'; + assert.throws(() => vm.runInNewContext(source, sandbox()), /name/); + const context = sandbox(); + vm.runInNewContext(bootstrap + '\n' + source, context); + assert.equal(context.platform, 'harmonyos'); + assert.equal(context.mounted, true); + assert.equal(context.plus.device.vendor, 'HUAWEI'); + assert.equal(context.plus.runtime.version, '1.0.1'); + assert.equal(context.plus.android, undefined); +}); + +test('existing SDK metadata and runtime APIs remain intact across repeated evaluation', () => { + const os = { name: 'HarmonyOS', version: 'native-version' }; + const device = { model: 'native-model' }; + const runtime = { version: 'native-host', openURL() {} }; + const context = sandbox({ os, device, runtime }); + vm.runInNewContext(bootstrap, context); vm.runInNewContext(bootstrap, context); + assert.equal(context.plus.os, os); assert.equal(context.plus.device, device); + assert.equal(context.plus.runtime, runtime); assert.equal(runtime.version, 'native-host'); +}); + +test('missing metadata APIs do not introduce another startup exception', () => { + const context = { plus: { runtime: {} }, uni: { + getSystemInfoSync: () => { throw new Error('not supported'); }, + getLaunchOptionsSync: () => { throw new Error('not ready'); } + }}; + vm.runInNewContext(bootstrap, context); + assert.equal(context.plus.os.name, 'HarmonyOS'); + assert.equal(context.plus.runtime.version, ''); + vm.runInNewContext(bootstrap, {}); +}); + +test('host version is evaluated lazily with API fallback', () => { + const context = sandbox(); + context.uni.getLaunchOptionsSync = () => ({}); + vm.runInNewContext(bootstrap, context); + assert.equal(context.plus.runtime.version, 'fallback-version'); + context.uni.getLaunchOptionsSync = () => ({ referrerInfo: { extraData: { 'x-version': '2.0.0' } } }); + assert.equal(context.plus.runtime.version, '2.0.0'); +}); + +test('Vue apps receive the missing platform before rendering without overriding WGT configuration', () => { + const context = sandbox(), calls = []; + const create = function (...args) { + calls.push({ owner: this, args }); + return { config: { globalProperties: args[0] } }; + }; + context.Vue = { createApp: create, createSSRApp: create, createVueApp: create }; + vm.runInNewContext(bootstrap, context); + const props = {}, custom = { $system: 'custom' }; + assert.equal(context.Vue.createApp(props).config.globalProperties, props); + assert.equal(props.$system, 'HarmonyOS'); + assert.equal(context.Vue.createSSRApp(custom).config.globalProperties.$system, 'custom'); + assert.equal(context.Vue.createVueApp({}).config.globalProperties.$system, 'HarmonyOS'); + assert.equal(calls[0].owner, context.Vue); + assert.equal(calls[0].args[0], props); +}); + +test('read-only Vue exports do not introduce a startup exception', () => { + const context = sandbox(), createApp = () => ({}); + context.Vue = Object.freeze({ createApp }); + assert.doesNotThrow(() => vm.runInNewContext(bootstrap, context)); + assert.equal(context.Vue.createApp, createApp); +}); + +test('Vue proxy warnings cannot recursively re-enter WGT console forwarding', () => { + let nativeCalls = 0, forwarded = 0; + const context = sandbox(); + context.console = { warn: () => { nativeCalls++; } }; + vm.runInNewContext(bootstrap, context); + const original = context.console.warn; + context.console.warn = function (...args) { + original(...args); + forwarded++; + for (const value of args) JSON.stringify(value); + }; + const component = new Proxy({}, { ownKeys: () => { + context.console.warn('Avoid enumerating component keys', component); + return []; + }}); + context.console.warn(component); + assert.equal(nativeCalls, 1); assert.equal(forwarded, 1); + context.console.warn('next independent message'); + assert.equal(nativeCalls, 2); assert.equal(forwarded, 2); +}); + +test('console and uni.__log__ never enumerate component trees, including later bridge wrappers', () => { + const context = sandbox(); + const logs = [], forwarded = []; + let enumerations = 0; + context.console = { warn: (...args) => logs.push(args), log: (...args) => logs.push(args) }; + context.uni.__log__ = (level, file, ...args) => context.console[level](...args, file); + vm.runInNewContext(bootstrap, context); + const originalLog = context.uni.__log__; + context.uni.__log__ = function (...args) { + originalLog(...args); + forwarded.push(args.map(value => JSON.stringify(value)).join(' ')); + }; + const originalWarn = context.console.warn; + context.console.warn = function (...args) { + originalWarn(...args); + forwarded.push(args.map(value => JSON.stringify(value)).join(' ')); + }; + const component = new Proxy({}, { ownKeys() { + enumerations++; + context.console.warn('component enumeration', component); + return []; + } }); + context.uni.__log__('log', 'at page.vue:1', component); + context.console.warn('render warning', component); + assert.equal(enumerations, 0); + assert.equal(logs.length, 2); + assert.equal(forwarded.length, 2); + assert.ok(forwarded.every(line => line.includes('[Object]'))); +}); + +test('object logs do not invoke getters or toJSON, and strings are bounded', () => { + const context = sandbox(), logs = []; + context.console = { log: (...args) => logs.push(args) }; + vm.runInNewContext(bootstrap, context); + const value = { get secret() { assert.fail('getter invoked'); }, toJSON() { assert.fail('toJSON invoked'); } }; + context.console.log(value, 'x'.repeat(100000), 42, null); + assert.equal(logs[0][0], '[Object]'); + assert.equal(logs[0][1].length, 2048); + assert.equal(logs[0][2], 42); + assert.equal(logs[0][3], null); + // Non-logging API payloads retain their original identity and contents. + context.uni.sendNativeEvent = (_, data) => assert.equal(data, value); + context.uni.sendNativeEvent('business', value); +}); + +test('a late uni.__log__ implementation remains callable and self-assignment does not stack guards', () => { + const context = sandbox(), calls = []; + vm.runInNewContext(bootstrap, context); + assert.equal(context.uni.__log__, undefined); + context.uni.__log__ = (...args) => calls.push(args); + const guarded = context.uni.__log__; + context.uni.__log__ = context.uni.__log__; + assert.equal(context.uni.__log__, guarded); + context.uni.__log__('error', 'at page.vue:2', 'failure'); + assert.deepEqual(calls, [['error', 'at page.vue:2', 'failure']]); +}); + +function fixture(options = {}) { + const source = 'var title = "中文页面"; var mounted = plus.os.name;'; + const service = '/apps/__UNI__WX/www/app-service.js'; + const files = new Map([[service, Buffer.from(options.source ?? source)]]); + const handles = new Map(); + let resources = 0, writes = 0; + const fileIo = { + OpenMode: { CREATE: 1, WRITE_ONLY: 2, TRUNC: 4 }, + readText: async p => { + if (!files.has(p)) throw new Error('missing script'); + return files.get(p).toString('utf8'); + }, + open: async p => { files.set(p, Buffer.alloc(0)); handles.set(1, p); return { fd: 1 }; }, + write: async (fd, input) => { + writes++; + if (options.failWrite) throw new Error('disk full'); + const data = Buffer.from(input); + const count = options.shortWrite ? Math.min(data.length, 7) : data.length; + const p = handles.get(fd); + files.set(p, Buffer.concat([files.get(p), data.subarray(0, count)])); + return count; + }, + close: async () => {}, + rename: async (from, to) => { + if (options.failRename) throw new Error('rename failed'); + files.set(to, files.get(from)); files.delete(from); + }, + accessSync: p => files.has(p), + unlink: async p => { files.delete(p); } + }; + const mocks = { + '@kit.CoreFileKit': { fileIo }, + '@kit.ArkTS': { util: { + TextDecoder: { create: () => ({ decodeWithStream: data => new TextDecoder().decode(data) }) }, + TextEncoder: class { encodeInto(text) { return new TextEncoder().encode(text); } } + } }, + '@dcloudio/uni-app-runtime': { getUniMPRunPath: () => '/apps/__UNI__WX' }, + './Logger': { Logger: { info: () => {} } } + }; + const exports = {}; + const filename = path.join(root, 'common/src/main/ets/utils/UniMpRuntimeCompat.ets'); + const code = ts.transpileModule(fs.readFileSync(filename, 'utf8'), { + fileName: 'UniMpRuntimeCompat.ts', + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } + }).outputText; + vm.runInNewContext(code, { exports, require: name => { + if (mocks[name]) return mocks[name]; + throw new Error('Unmocked dependency: ' + name); + }}); + const context = { resourceManager: { getRawFileContent: async name => { + resources++; assert.equal(name, 'unimp-harmony-compat.js'); + return Buffer.from(options.invalidResource ? 'invalid' : bootstrap); + }}}; + return { source, service, files, + prepare: () => exports.UniMpRuntimeCompat.prepare(context, '__UNI__WX'), + get writes() { return writes; }, get resources() { return resources; } + }; +} + +test('existing decrypted script is patched once, preserving its original Unicode source', async () => { + const f = fixture(); await f.prepare(); + const result = f.files.get(f.service).toString('utf8'); + assert.equal(result, bootstrap + '\n' + f.source); + assert.equal(f.files.has(f.service + '.compat-tmp'), false); + await f.prepare(); + assert.equal(f.resources, 1); assert.equal(f.writes, 1); +}); + +test('partial filesystem writes still produce a complete executable UTF-8 script', async () => { + const f = fixture({ shortWrite: true }); await f.prepare(); + const context = sandbox(); + vm.runInNewContext(f.files.get(f.service).toString('utf8'), context); + assert.equal(context.title, '中文页面'); assert.equal(context.mounted, 'HarmonyOS'); + assert.ok(f.writes > 1); +}); + +test('write and rename errors preserve the original script and clean temporary output', async () => { + for (const failure of ['failWrite', 'failRename']) { + const f = fixture({ [failure]: true }); + await assert.rejects(f.prepare()); + assert.equal(f.files.get(f.service).toString('utf8'), f.source); + assert.equal(f.files.has(f.service + '.compat-tmp'), false); + } +}); + +test('empty startup scripts and invalid compatibility assets are rejected before replacement', async () => { + for (const options of [{ source: ' ' }, { invalidResource: true }]) { + const f = fixture(options); + await assert.rejects(f.prepare()); + assert.equal(f.writes, 0); + } +}); + +test('older compatibility bootstrap is upgraded without stacking or changing business code', async () => { + const business = 'var mounted = plus.os.name;'; + for (const version of ['v1', 'v2', 'v3', 'v4', 'v5']) { + const f = fixture({ source: '/* rabbit-unimp-harmony-compat:' + version + ' */\noldShim();\n/* end-rabbit-unimp-harmony-compat */\n' + business }); + await f.prepare(); + assert.equal(f.files.get(f.service).toString('utf8'), bootstrap + '\n' + business); + } +}); + +test('known no-op safeBottom diagnostic is removed without changing initialization', async () => { + const f = fixture({ source: 'var extra={safeBottom:"28"};uni.showModal({title:"safeBottom",showCancel:!1,content:extra.safeBottom,success:function(e){}});var mounted=true;' }); + await f.prepare(); + const context = sandbox(); context.uni.showModal = () => assert.fail('debug dialog must not appear'); + vm.runInNewContext(f.files.get(f.service).toString('utf8'), context); + assert.equal(context.mounted, true); +}); + +test('business modal callbacks are preserved even when the title is safeBottom', async () => { + const source = 'uni.showModal({title:"safeBottom",showCancel:!1,content:extra.safeBottom,success:function(e){save(e)}});'; + const f = fixture({ source }); await f.prepare(); + assert.ok(f.files.get(f.service).toString('utf8').endsWith(source)); +});