From 38076ccdc869e24e24e6d3ac400807e8ebcbb40c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 10:04:30 +0800 Subject: [PATCH 01/16] feat(plugin): run TREM-Lite 3 extensions on the desktop build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Platform: desktop New(zh-Hant): 設定多了「擴充」頁,可以安裝、啟用與移除擴充功能,未簽章的擴充功能要先確認才會執行 New(en-US): Settings gains an Extensions page to install, enable and remove extensions, and an unverified one asks for confirmation before it runs --- apps/desktop/src-tauri/src/lib.rs | 7 + apps/desktop/src-tauri/src/plugin.rs | 270 +++++++ packages/core/src/features/index.ts | 5 + packages/core/src/features/plugin/base64.ts | 54 ++ packages/core/src/features/plugin/bridge.ts | 58 ++ packages/core/src/features/plugin/host.ts | 591 ++++++++++++++ packages/core/src/features/plugin/index.ts | 28 + packages/core/src/features/plugin/mixin.ts | 164 ++++ packages/core/src/features/plugin/paths.ts | 166 ++++ packages/core/src/features/plugin/sandbox.ts | 749 ++++++++++++++++++ packages/core/src/features/plugin/trem.ts | 87 ++ packages/core/src/features/plugin/types.ts | 94 +++ packages/core/src/features/plugin/verify.ts | 117 +++ packages/core/src/features/plugin/version.ts | 118 +++ .../core/src/features/settings/Extensions.tsx | 242 ++++++ .../src/features/settings/SettingsApp.tsx | 9 +- packages/core/src/styles/globals.css | 67 ++ 17 files changed, 2824 insertions(+), 2 deletions(-) create mode 100644 apps/desktop/src-tauri/src/plugin.rs create mode 100644 packages/core/src/features/plugin/base64.ts create mode 100644 packages/core/src/features/plugin/bridge.ts create mode 100644 packages/core/src/features/plugin/host.ts create mode 100644 packages/core/src/features/plugin/index.ts create mode 100644 packages/core/src/features/plugin/mixin.ts create mode 100644 packages/core/src/features/plugin/paths.ts create mode 100644 packages/core/src/features/plugin/sandbox.ts create mode 100644 packages/core/src/features/plugin/trem.ts create mode 100644 packages/core/src/features/plugin/types.ts create mode 100644 packages/core/src/features/plugin/verify.ts create mode 100644 packages/core/src/features/plugin/version.ts create mode 100644 packages/core/src/features/settings/Extensions.tsx diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 446cc8f..e701550 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -8,6 +8,7 @@ mod logging; mod math; mod ml_intensity; mod ntp; +mod plugin; #[cfg(desktop)] mod updater; #[cfg(not(desktop))] @@ -204,6 +205,12 @@ pub fn run() { http_proxy::http_report, math::eew_area_intensity, ntp::ntp_sync, + plugin::plugin_root, + plugin::plugin_list, + plugin::plugin_write, + plugin::plugin_install, + plugin::plugin_remove, + plugin::plugin_keys, updater::update_check, updater::update_pending, updater::update_restart, diff --git a/apps/desktop/src-tauri/src/plugin.rs b/apps/desktop/src-tauri/src/plugin.rs new file mode 100644 index 0000000..ffb2b54 --- /dev/null +++ b/apps/desktop/src-tauri/src/plugin.rs @@ -0,0 +1,270 @@ +//! Extension (plugin) storage — file I/O only, no policy. +//! +//! The extension host itself lives in the webview +//! (`packages/core/src/features/plugin`): it reads manifests, verifies +//! `signature.json`, orders dependencies and evaluates each plugin's code. +//! Rust does the one thing the webview cannot — write files synchronously and +//! safely — and only ever touches `/plugins/`, so a +//! plugin can reach its own directory and nothing else. +//! +//! Verifying a signature in Rust would mean the `rsa` crate; the webview +//! already has WebCrypto, whose RSASSA-PKCS1-v1_5 + SHA-256 is exactly what +//! `crypto.createVerify('SHA256')` did in the Electron build. Reading the whole +//! tree in one call is what lets the host hand plugins a synchronous `fs`: the +//! legacy API is `fs.readFileSync`, and a synchronous read cannot cross an +//! async IPC boundary. + +use std::path::{Path, PathBuf}; + +use base64::Engine as _; +use serde::{Deserialize, Serialize}; +use tauri::Manager; + +/// One file of a plugin, base64 so binary assets survive the trip. +#[derive(Serialize, Deserialize)] +pub struct PluginFile { + /// POSIX-style path relative to the plugin directory. + path: String, + data: String, +} + +/// A plugin directory as the host sees it when it starts up. +#[derive(Serialize)] +pub struct PluginDir { + name: String, + files: Vec, +} + +/// A trusted signing key dropped in `/plugin-keys`. +#[derive(Serialize)] +pub struct PluginKey { + /// File name without `.pem` — the `keyId` a signature refers to. + id: String, + /// The PEM body, as `PluginVerifier.loadKeysFromDirectory` returned it. + pem: String, +} + +/// `info.json`'s `name` is also the directory name, so it must not traverse. +fn valid_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 128 + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +fn base_dir(app: &tauri::AppHandle) -> Result { + app.path() + .app_config_dir() + .map_err(|e| format!("no config dir: {e}")) +} + +fn plugins_dir(app: &tauri::AppHandle) -> Result { + let dir = base_dir(app)?.join("plugins"); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + Ok(dir) +} + +fn plugin_dir(app: &tauri::AppHandle, name: &str) -> Result { + if !valid_name(name) { + return Err(format!("插件名稱不合法:{name}")); + } + Ok(plugins_dir(app)?.join(name)) +} + +/// Reject absolute paths and `..`, so a plugin cannot escape its directory. +fn safe_relative(rel: &str) -> Result { + let mut out = PathBuf::new(); + for part in rel.replace('\\', "/").split('/') { + if part.is_empty() || part == "." { + continue; + } + out.push(part); + } + // Only plain names survive: a drive prefix (`C:foo`), a root, or a `..` + // anywhere means the archive was not written by the signer. + let plain = out + .components() + .all(|part| matches!(part, std::path::Component::Normal(_))); + if out.as_os_str().is_empty() || !plain { + return Err(format!("插件路徑不合法:{rel}")); + } + Ok(out) +} + +/// Every regular file under `dir`, keyed by its path relative to `base`. +fn collect(dir: &Path, base: &Path, out: &mut Vec) -> Result<(), String> { + let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + for entry in entries { + let entry = entry.map_err(|e| e.to_string())?; + let path = entry.path(); + // `file_type` does not follow symlinks: a link into the rest of the + // disk is read as a link and skipped, never followed. + let kind = entry.file_type().map_err(|e| e.to_string())?; + if kind.is_dir() { + collect(&path, base, out)?; + continue; + } + if !kind.is_file() { + continue; + } + let rel = path + .strip_prefix(base) + .map_err(|e| e.to_string())? + .to_string_lossy() + .replace('\\', "/"); + let bytes = std::fs::read(&path).map_err(|e| format!("{rel}: {e}"))?; + out.push(PluginFile { + path: rel, + data: base64::engine::general_purpose::STANDARD.encode(bytes), + }); + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Tauri commands +// --------------------------------------------------------------------------- + +/// Where plugins live, for the "open folder" button. +#[tauri::command] +pub fn plugin_root(app: tauri::AppHandle) -> Result { + Ok(plugins_dir(&app)?.to_string_lossy().into_owned()) +} + +/// Read every installed plugin: the directory name plus each file's bytes, so +/// the host can answer `fs.readFileSync` without another round trip. +#[tauri::command] +pub fn plugin_list(app: tauri::AppHandle) -> Result, String> { + let root = plugins_dir(&app)?; + let mut out = Vec::new(); + let entries = match std::fs::read_dir(&root) { + Ok(entries) => entries, + Err(e) => { + log::warn!(target: "plugin", "讀不到插件資料夾 {}:{e}", root.display()); + return Ok(out); + } + }; + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_dir() { + continue; + } + let name = entry.file_name().to_string_lossy().into_owned(); + if !valid_name(&name) { + log::warn!(target: "plugin", "略過名稱不合法的插件資料夾:{name}"); + continue; + } + let mut files = Vec::new(); + match collect(&path, &path, &mut files) { + Ok(()) => { + log::debug!(target: "plugin", "讀取插件 {name}:{} 個檔案", files.len()); + out.push(PluginDir { name, files }); + } + Err(e) => log::error!(target: "plugin", "讀取插件 {name} 失敗:{e}"), + } + } + Ok(out) +} + +/// Write one file inside a plugin directory (its own `config.yml`, a cache). +/// `data` of `None` removes the file, which is what `fs.unlinkSync` forwards. +#[tauri::command] +pub fn plugin_write( + app: tauri::AppHandle, + plugin: String, + path: String, + data: Option, +) -> Result<(), String> { + let dir = plugin_dir(&app, &plugin)?; + let rel = safe_relative(&path)?; + let target = dir.join(&rel); + let Some(data) = data else { + if target.exists() { + std::fs::remove_file(&target).map_err(|e| e.to_string())?; + } + return Ok(()); + }; + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let bytes = base64::engine::general_purpose::STANDARD + .decode(data.as_bytes()) + .map_err(|e| format!("內容不是合法的 base64:{e}"))?; + std::fs::write(&target, bytes).map_err(|e| { + log::error!(target: "plugin", "寫入 {plugin}/{} 失敗:{e}", rel.display()); + e.to_string() + })?; + Ok(()) +} + +/// Install (or replace) a plugin directory. The webview unzips the `.trem` +/// and hands over the extracted files, so Rust needs no archive dependency. +#[tauri::command] +pub fn plugin_install( + app: tauri::AppHandle, + plugin: String, + files: Vec, +) -> Result<(), String> { + let dir = plugin_dir(&app, &plugin)?; + // Replace, not merge: a stale file left behind would still be hashed by the + // next signature check and reported as an extra file. + if dir.exists() { + std::fs::remove_dir_all(&dir).map_err(|e| e.to_string())?; + } + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + for file in &files { + safe_relative(&file.path)?; + } + for file in files { + let target = dir.join(safe_relative(&file.path)?); + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let bytes = base64::engine::general_purpose::STANDARD + .decode(file.data.as_bytes()) + .map_err(|e| format!("{} 不是合法的 base64:{e}", file.path))?; + std::fs::write(&target, bytes).map_err(|e| format!("{}: {e}", file.path))?; + } + log::info!(target: "plugin", "安裝插件 {plugin}"); + Ok(()) +} + +/// Remove a plugin directory and everything in it. +#[tauri::command] +pub fn plugin_remove(app: tauri::AppHandle, plugin: String) -> Result<(), String> { + let dir = plugin_dir(&app, &plugin)?; + if !dir.exists() { + return Ok(()); + } + std::fs::remove_dir_all(&dir).map_err(|e| e.to_string())?; + log::info!(target: "plugin", "移除插件 {plugin}"); + Ok(()) +} + +/// Keys published by organisations other than ExpTech, dropped in as `.pem`. +#[tauri::command] +pub fn plugin_keys(app: tauri::AppHandle) -> Result, String> { + let dir = base_dir(&app)?.join("plugin-keys"); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let mut out = Vec::new(); + for entry in std::fs::read_dir(&dir) + .map_err(|e| e.to_string())? + .flatten() + { + let path = entry.path(); + if !path.is_file() || path.extension().and_then(|e| e.to_str()) != Some("pem") { + continue; + } + let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { + continue; + }; + match std::fs::read_to_string(&path) { + Ok(pem) => out.push(PluginKey { id, pem }), + Err(e) => log::warn!(target: "plugin", "讀不到金鑰 {}:{e}", path.display()), + } + } + // Keys are small and unordered on disk; sort so both runs agree. + out.sort_by(|a, b| a.id.cmp(&b.id)); + Ok(out) +} diff --git a/packages/core/src/features/index.ts b/packages/core/src/features/index.ts index a0a9422..52829be 100644 --- a/packages/core/src/features/index.ts +++ b/packages/core/src/features/index.ts @@ -11,6 +11,7 @@ import { initNotifications } from "@/lib/notificationClient"; import { initSpeech } from "@/lib/speechClient"; import { initEventLog } from "./log/eventLog"; +import { initPlugins } from "./plugin"; import { initData } from "./data/data"; import { initResource } from "./data/resource"; import { initRts } from "./rts/rts"; @@ -39,6 +40,10 @@ function guard(name: string, fn: () => void) { export function initFeatures(): void { // First: every event is logged before any module acts on it. guard("event-log", initEventLog); + // Then the extensions, before the modules that emit: V3 built its plugin + // loader ahead of every feature (index/require.js), and a plugin that + // subscribes to `DataRts` must hear the session's first frame. + guard("plugin", initPlugins); guard("autostart", initAutostart); guard("audio", initAudio); guard("notifications", initNotifications); diff --git a/packages/core/src/features/plugin/base64.ts b/packages/core/src/features/plugin/base64.ts new file mode 100644 index 0000000..1fdbf7a --- /dev/null +++ b/packages/core/src/features/plugin/base64.ts @@ -0,0 +1,54 @@ +/** + * base64 for the plugin host. + * + * Rust hands a plugin's files over as base64 (assets are not text), and the + * browser's own `atob`/`btoa` are the fastest route that needs no dependency — + * but they cannot carry more than 64 KiB in one call in older engines, so the + * decoding is done in chunks. + */ + +const CHUNK = 0x8000; + +/** + * A view backed by a plain `ArrayBuffer`. + * + * Named because WebCrypto's `BufferSource` refuses a `Uint8Array` that might be + * backed by a `SharedArrayBuffer`, and the default type argument is exactly + * that union. + */ +export type Bytes = Uint8Array; + +export function decodeBase64(data: string): Bytes { + if (data.length <= CHUNK) { + const binary = atob(data); + const out = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i); + return out; + } + // A long payload decodes a chunk at a time: a 1 MB plugin would otherwise + // pass an 800 kB string to `atob`, which some engines reject outright. + const parts: Bytes[] = []; + let total = 0; + for (let offset = 0; offset < data.length; offset += CHUNK) { + const binary = atob(data.slice(offset, offset + CHUNK)); + const part = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) part[i] = binary.charCodeAt(i); + parts.push(part); + total += part.length; + } + const out = new Uint8Array(total); + let at = 0; + for (const part of parts) { + out.set(part, at); + at += part.length; + } + return out; +} + +export function encodeBase64(bytes: Uint8Array): string { + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += CHUNK) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK)); + } + return btoa(binary); +} diff --git a/packages/core/src/features/plugin/bridge.ts b/packages/core/src/features/plugin/bridge.ts new file mode 100644 index 0000000..4322b97 --- /dev/null +++ b/packages/core/src/features/plugin/bridge.ts @@ -0,0 +1,58 @@ +/** + * The plugin host's link to Rust (`src-tauri/src/plugin.rs`). + * + * Small on purpose: Rust stores files, this file moves bytes, and every + * decision — what is verified, what is enabled, what runs — is made in TS where + * it can be read and tested. + */ +import { invoke } from "@tauri-apps/api/core"; + +import { inTauri } from "@/lib/env"; + +import { decodeBase64, encodeBase64 } from "./base64"; +import type { PluginDir, PluginFile, PluginKey } from "./types"; + +/** True once the host can do anything at all. */ +export const pluginStorageAvailable = inTauri; + +export async function pluginRoot(): Promise { + if (!inTauri) return ""; + return invoke("plugin_root"); +} + +/** + * Every installed plugin and every file in it, in one call. + * + * One call, not one per file: the tree it returns is what backs the synchronous + * `fs.readFileSync` a plugin was written against. + */ +export async function readPlugins(): Promise>> { + if (!inTauri) return new Map(); + const dirs = await invoke("plugin_list"); + return new Map( + dirs.map((dir) => [ + dir.name, + new Map(dir.files.map((file) => [file.path, decodeBase64(file.data)] as [string, Uint8Array])), + ]), + ); +} + +/** One file a plugin wrote, or `null` to delete it. */ +export async function writePluginFile(plugin: string, path: string, data: Uint8Array | null): Promise { + if (!inTauri) return; + await invoke("plugin_write", { plugin, path, data: data ? encodeBase64(data) : null }); +} + +export async function installPlugin(plugin: string, files: PluginFile[]): Promise { + await invoke("plugin_install", { plugin, files }); +} + +export async function removePlugin(plugin: string): Promise { + await invoke("plugin_remove", { plugin }); +} + +/** Extra signing keys, `/plugin-keys/*.pem`. */ +export async function pluginKeys(): Promise { + if (!inTauri) return []; + return invoke("plugin_keys"); +} diff --git a/packages/core/src/features/plugin/host.ts b/packages/core/src/features/plugin/host.ts new file mode 100644 index 0000000..ca1d4f5 --- /dev/null +++ b/packages/core/src/features/plugin/host.ts @@ -0,0 +1,591 @@ +/** + * The extension host: scanning, verification, dependency order and loading. + * + * This is `legacy/src/js/core/plugin.js`'s `PluginLoader` rebuilt for V4. The + * parts that a plugin can observe are kept deliberately identical — the `ctx` + * it receives, the `info.json` contract, the dependency rules, the status + * strings, the localStorage key — because extensions already exist that depend + * on them. The parts it cannot observe are new: files live in one tree that was + * read in a single call, verification is WebCrypto, and every plugin runs in a + * CommonJS sandbox rather than in Electron's main world. + * + * Load order, verbatim from V3: scan → auto-enable → dependency order → start. + */ +import { getVersion } from "@tauri-apps/api/app"; +import { unzipSync } from "fflate"; +import maplibregl from "maplibre-gl"; + +import { events } from "@/lib/events"; +import { createLogger } from "@/lib/logger"; +import type { TremEvents } from "@/lib/types"; + +import { + installPlugin, + pluginKeys, + pluginRoot, + pluginStorageAvailable, + readPlugins, + removePlugin, + writePluginFile, +} from "./bridge"; +import { encodeBase64 } from "./base64"; +import { MixinManager } from "./mixin"; +import { PLUGIN_ROOT, PluginRuntime, PluginTree } from "./sandbox"; +import { tremGlobal } from "./trem"; +import type { LoadedPlugin, PluginEntry, PluginFile, PluginInfo, PluginStatus } from "./types"; +import { getVersionPrefixString, validateVersionRequirement } from "./version"; +import { verifyPlugin as verify } from "./verify"; + +const log = createLogger("plugin"); + +/** V3's key. A plugin enabled in the Electron build stays enabled here. */ +const ENABLED_KEY = "enabled-plugins"; +/** What this host loaded, in V3's shape, for tooling that reads it. */ +const LOADED_KEY = "loaded-plugins"; + +/** `info.json` names are lowercase, hyphenated, and nothing else. */ +const NAME_PATTERN = /^[a-z0-9-]+$/; + +/** V3's wording, kept verbatim: the 擴充 page greps for it. */ +const STATUS_INIT_FAILED = "初始化失敗,請聯繫擴充作者。"; +const STATUS_DISABLED = "未啟用。"; + +export function getSensitivityDescription(level: number): string { + switch (level) { + case 4: + return "極高敏感度 - 包含系統核心API存取權限"; + case 3: + return "高敏感度 - 包含注入或檔案系統存取權限"; + case 2: + return "中等敏感度 - 包含事件權限"; + case 1: + return "低敏感度 - 包含日誌/元數據存取權限"; + default: + return "無敏感操作"; + } +} + +type PluginHandler = (...args: never[]) => unknown; +type PluginLogger = ReturnType; + +/** The object handed to a plugin's entry point. This is V3's `ctx`, field for field. */ +export interface PluginContext { + TREM: ReturnType; + events: typeof events; + logger: PluginLogger; + Logger: { + getLogger(scope: string): PluginLogger; + getInstance(): PluginLogger; + }; + MixinManager: typeof MixinManager; + maplibregl: typeof maplibregl; + info: { + /** The plugins *root*, as in V3 — not the plugin's own folder. */ + pluginDir: string; + originalPath: string; + /** V4 addition: the plugin's own name, so a path needs no guessing. */ + name: string; + }; + utils: { path: unknown; fs: unknown }; + on(event: string, handler: PluginHandler): void; + require(modulePath: string): unknown; +} + +interface RunningPlugin { + runtime: PluginRuntime; + /** Handlers registered through `ctx.on`, unbound ones included. */ + handlers: Array<{ event: string; handler: PluginHandler }>; +} + +interface InstallOptions { + /** Replacing a plugin that is already running. */ + replace?: boolean; +} + +export class PluginLoader { + private readonly type: string; + /** Rows the 擴充 page shows, keyed by plugin name. */ + private entries = new Map(); + private running = new Map(); + private trees = new Map>(); + private keys = new Map(); + private listeners = new Set<() => void>(); + private started = false; + /** The app's own version, as `dependencies.trem` is compared against. */ + tremVersion = ""; + /** `/plugins` — where the tree on disk actually is. */ + rootPath = PLUGIN_ROOT; + + constructor(type = "index") { + this.type = type; + } + + // -- reading ------------------------------------------------------------- + + list(): PluginEntry[] { + return [...this.entries.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + } + + get(name: string): PluginEntry | undefined { + return this.entries.get(name); + } + + subscribe(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + private changed(): void { + for (const fn of this.listeners) fn(); + } + + /** V3's `getLoadedPlugins()`, in the shape it persisted under `loaded-plugins`. */ + getLoadedPlugins(): LoadedPlugin[] { + return this.list() + .filter((entry) => entry.loaded) + .map((entry) => ({ + name: entry.name, + version: entry.info.version ?? "", + description: entry.info.description, + author: entry.info.author, + ctxDependencies: (entry.info.dependencies?.ctx as string[] | undefined) ?? [], + sensitivity: entry.sensitivity, + })); + } + + // -- scanning ------------------------------------------------------------ + + /** + * Read every plugin directory and verify each one. + * + * The whole tree arrives in one `plugin_list` call, which is what makes the + * synchronous `fs` a plugin was written against possible: `PluginTree` is + * that call's result, kept in memory. + */ + async scan(): Promise { + if (!pluginStorageAvailable) { + log.info("瀏覽器模式:擴充功能無法使用。"); + return; + } + this.tremVersion = await getVersion(); + this.rootPath = await pluginRoot(); + this.trees = await readPlugins(); + this.keys = new Map((await pluginKeys()).map((key) => [key.id, key.pem])); + + for (const [name, files] of this.trees) { + const entry = await this.inspect(name, files); + if (entry) this.entries.set(name, entry); + } + // A plugin that was uninstalled since the last scan leaves no row behind. + for (const name of [...this.entries.keys()]) { + if (!this.trees.has(name)) this.entries.delete(name); + } + this.changed(); + } + + private async inspect(name: string, files: Map): Promise { + const manifest = files.get("info.json"); + if (!manifest) { + log.warn(`略過 ${name}:缺少 info.json。`); + return null; + } + + let info: PluginInfo; + try { + info = JSON.parse(new TextDecoder().decode(manifest)) as PluginInfo; + } catch (e) { + log.warn(`略過 ${name}:info.json 不是合法的 JSON(${String(e)})。`); + return null; + } + if (!info.name || !NAME_PATTERN.test(info.name)) { + log.warn(`略過 ${name}:info.json 的 name 不合格式(僅允許小寫字母、數字與連字號)。`); + return null; + } + + const verified = await verify(files, this.keys); + const level = info.sensitivity?.level ?? 0; + return { + name: info.name, + info, + present: true, + verified: verified.valid, + verifyError: verified.error, + keyId: verified.keyId, + enabled: false, + loaded: false, + status: verified.valid ? null : { type: "warn", msg: verified.error ?? "未發現有效簽名。" }, + sensitivity: { + level, + description: info.sensitivity?.description ?? getSensitivityDescription(level), + }, + hasConfig: files.has("config.yml"), + }; + } + + // -- enabling ------------------------------------------------------------ + + private readEnabled(): string[] { + try { + const raw = JSON.parse(localStorage.getItem(ENABLED_KEY) ?? "[]") as unknown; + return Array.isArray(raw) ? raw.filter((item): item is string => typeof item === "string") : []; + } catch { + return []; + } + } + + private writeEnabled(names: string[]): void { + localStorage.setItem(ENABLED_KEY, JSON.stringify([...new Set(names)])); + } + + isEnabled(name: string): boolean { + return this.entries.get(name)?.enabled ?? false; + } + + /** Turn one plugin on and start it, or off and unhook it. */ + async setEnabled(name: string, enabled: boolean): Promise { + const entry = this.entries.get(name); + if (!entry) return; + + if (enabled) { + this.writeEnabled([...this.readEnabled(), name]); + entry.enabled = true; + await this.start(name); + } else { + this.writeEnabled(this.readEnabled().filter((item) => item !== name)); + entry.enabled = false; + this.stop(name); + entry.status = { type: "warn", msg: STATUS_DISABLED }; + } + this.persist(); + this.changed(); + } + + // -- loading ------------------------------------------------------------- + + /** + * The whole load, in V3's order. + * + * Auto-enable is deliberately narrow: `auto-enable` in the manifest, an + * ExpTechTW author, **and** a valid signature. Two of the three would let an + * unsigned plugin run by claiming the author's name. + */ + async load(): Promise { + if (this.started) return; + this.started = true; + + await this.scan(); + const enabled = new Set(this.readEnabled()); + + for (const entry of this.entries.values()) { + const author = entry.info.author ?? ""; + if (entry.info["auto-enable"] === true && author.includes("ExpTechTW") && entry.verified) { + enabled.add(entry.name); + } + } + this.writeEnabled([...enabled]); + + for (const name of this.dependencyOrder([...enabled])) { + const entry = this.entries.get(name); + if (!entry) { + log.warn(`略過 ${name}:找不到這個擴充功能。`); + continue; + } + entry.enabled = true; + await this.start(name); + } + + for (const entry of this.entries.values()) { + if (!entry.enabled) entry.status ??= { type: "warn", msg: STATUS_DISABLED }; + } + this.persist(); + this.changed(); + } + + private async start(name: string): Promise { + const entry = this.entries.get(name); + if (!entry || entry.loaded) return; + + const files = this.trees.get(name); + if (!files) { + entry.status = { type: "error", msg: "找不到擴充功能的檔案。" }; + return; + } + if (!this.validateDependencies(entry)) return; + + // `loader` names the host windows a plugin runs in; only `index` exists. + const loader = entry.info.loader ?? ["index"]; + if (!loader.includes(this.type)) { + entry.status = { type: "warn", msg: STATUS_DISABLED }; + return; + } + + const tree = new PluginTree(); + for (const [owned, ownedFiles] of this.trees) { + tree.mount(owned, ownedFiles); + } + const runtime = new PluginRuntime({ + plugin: name, + tree, + pluginDir: `${PLUGIN_ROOT}/${name}`, + log: createLogger(`plugin:${name}`), + onWrite: (path, data) => { + void writePluginFile(name, path, data).catch((e: unknown) => { + log.error(`寫入 ${name}/${path} 失敗:${String(e)}`); + }); + const owned = this.trees.get(name); + if (!owned) return; + if (data === null) owned.delete(path); + else owned.set(path, data); + }, + }); + + const handlers: Array<{ event: string; handler: PluginHandler }> = []; + this.running.set(name, { runtime, handlers }); + const ok = await this.initialize(entry, runtime, handlers); + if (!ok) this.running.delete(name); + } + + private stop(name: string): void { + const plugin = this.running.get(name); + if (!plugin) return; + for (const { event, handler } of plugin.handlers) { + if (event === "load") continue; + events.off(event as keyof TremEvents, handler as never); + } + this.running.delete(name); + const entry = this.entries.get(name); + if (entry) entry.loaded = false; + } + + /** V3's `initializePlugin`: a class gets `onLoad`, a function gets `ctx.on('load')`. */ + private async initialize( + entry: PluginEntry, + runtime: PluginRuntime, + handlers: Array<{ event: string; handler: PluginHandler }>, + ): Promise { + const name = entry.name; + try { + const exported = runtime.loadEntry("index.js"); + const mod = exported as { default?: unknown } | null; + const Plugin = (mod && typeof mod === "object" && "default" in mod ? mod.default : exported) as unknown; + + if (typeof Plugin !== "function") { + throw new TypeError("index.js 沒有匯出擴充功能的進入點。"); + } + const ctx = this.buildContext(name, runtime, handlers); + + if (Plugin.toString().startsWith("class")) { + const instance = new (Plugin as new (ctx: PluginContext) => { onLoad?: () => unknown })(ctx); + if (typeof instance?.onLoad === "function") await instance.onLoad(); + } else { + (Plugin as (ctx: PluginContext) => void)(ctx); + // A function-style plugin receives its `load` event after it returns. + for (const { handler } of handlers.filter((item) => item.event === "load")) { + handler(); + } + } + + for (const { event, handler } of handlers) { + if (event !== "load") events.on(event as keyof TremEvents, handler as never); + } + entry.loaded = true; + entry.status = { type: "ok", msg: "已載入。" }; + log.info(`已載入擴充功能 ${name} ${entry.info.version ?? ""}`); + return true; + } catch (e) { + log.error(`擴充功能 ${name} 初始化失敗:${String(e)}`); + entry.loaded = false; + entry.status = { type: "error", msg: STATUS_INIT_FAILED }; + return false; + } + } + + private buildContext( + name: string, + runtime: PluginRuntime, + handlers: Array<{ event: string; handler: PluginHandler }>, + ): PluginContext { + const pluginLog = createLogger(`plugin:${name}`); + const ownDir = `${PLUGIN_ROOT}/${name}`; + return { + TREM: tremGlobal(), + events, + logger: pluginLog, + Logger: { + getLogger: (scope: string) => createLogger(`plugin:${name}:${scope}`), + getInstance: () => pluginLog, + }, + MixinManager, + maplibregl, + info: { pluginDir: PLUGIN_ROOT, originalPath: PLUGIN_ROOT, name }, + utils: { path: runtime.path, fs: runtime.fs }, + on: (event, handler) => { + handlers.push({ event, handler }); + }, + require: (modulePath) => runtime.ctxRequire(modulePath, ownDir), + }; + } + + // -- dependencies -------------------------------------------------------- + + /** + * V3's `validateDependencies`, messages included. + * + * `dependencies.trem` is the host's version; every other key names another + * plugin, whose declared version must satisfy the requirement. + */ + validateDependencies(entry: PluginEntry): boolean { + const dependencies = entry.info.dependencies; + if (!dependencies) return true; + + const { trem, ...plugins } = dependencies; + if (trem && !validateVersionRequirement(this.tremVersion, trem)) { + entry.status = { + type: "error", + msg: `需要 TREM-Lite 的版本為 ${getVersionPrefixString(trem)},但目前安裝的版本為 ${this.tremVersion}。`, + }; + return false; + } + + for (const [dependency, requirement] of Object.entries(plugins)) { + const target = this.entries.get(dependency); + if (!target) { + entry.status = { type: "error", msg: `缺少 ${dependency} 依賴。` }; + return false; + } + if (requirement && !validateVersionRequirement(target.info.version ?? "", requirement)) { + entry.status = { + type: "error", + msg: `需要 ${dependency} 的版本為 ${getVersionPrefixString(requirement)},但目前安裝的版本為 ${target.info.version}。`, + }; + return false; + } + } + return true; + } + + /** A dependency-first order over the plugins being started, as V3 sorted them. */ + private dependencyOrder(names: string[]): string[] { + const wanted = new Set(names); + const seen = new Set(); + const order: string[] = []; + + const visit = (name: string): void => { + if (seen.has(name)) return; + seen.add(name); + const entry = this.entries.get(name); + const dependencies = entry?.info.dependencies ?? {}; + for (const dependency of Object.keys(dependencies)) { + if (dependency !== "trem" && wanted.has(dependency)) visit(dependency); + } + order.push(name); + }; + + for (const name of [...wanted].sort()) visit(name); + return order; + } + + // -- installing ---------------------------------------------------------- + + /** + * Install an unpacked plugin, replacing any previous copy. + * + * Replace, never merge: a file left over from the previous version would + * still be hashed by the next verification and reported as an extra file. + */ + async install(name: string, files: PluginFile[], options: InstallOptions = {}): Promise { + if (!NAME_PATTERN.test(name)) { + throw new Error("擴充功能的名稱只能包含小寫字母、數字與連字號。"); + } + if (this.running.has(name) && !options.replace) { + throw new Error(`擴充功能 ${name} 正在執行,請先停用再安裝。`); + } + this.stop(name); + await installPlugin(name, files); + await this.scan(); + } + + /** + * Install a `.trem` package — a zip of a plugin directory. + * + * The archive may wrap everything in a single top-level folder, which is what + * most zips of a folder look like; that wrapper is stripped. + */ + async installPackage(data: Uint8Array, name?: string): Promise { + const archive = unzipSync(data); + const paths = Object.keys(archive).filter( + (path) => !path.endsWith("/") && !path.startsWith("__MACOSX/") && !path.endsWith(".DS_Store"), + ); + const manifestPath = paths.find((path) => path === "info.json") ?? paths.find((path) => path.endsWith("/info.json")); + if (!manifestPath) throw new Error("套件裡找不到 info.json。"); + + let info: PluginInfo; + try { + info = JSON.parse(new TextDecoder().decode(archive[manifestPath])) as PluginInfo; + } catch (e) { + throw new Error(`info.json 不是合法的 JSON:${String(e)}`, { cause: e }); + } + const plugin = name ?? info.name; + if (!plugin || !NAME_PATTERN.test(plugin)) { + throw new Error("info.json 的 name 不合格式(僅允許小寫字母、數字與連字號)。"); + } + + const prefix = manifestPath === "info.json" ? "" : `${manifestPath.slice(0, -"info.json".length)}`; + const files: PluginFile[] = paths.map((path) => ({ + path: path.slice(prefix.length), + data: encodeBase64(archive[path]), + })); + await this.install(plugin, files, { replace: true }); + return plugin; + } + + async remove(name: string): Promise { + this.stop(name); + await removePlugin(name); + this.writeEnabled(this.readEnabled().filter((item) => item !== name)); + this.entries.delete(name); + this.trees.delete(name); + this.persist(); + this.changed(); + } + + /** The plugin's `config.yml`, as text, or `null` when it ships none. */ + readConfig(name: string): string | null { + const bytes = this.trees.get(name)?.get("config.yml"); + return bytes ? new TextDecoder().decode(bytes) : null; + } + + async writeConfig(name: string, text: string): Promise { + const bytes = new TextEncoder().encode(text); + await writePluginFile(name, "config.yml", bytes); + this.trees.get(name)?.set("config.yml", bytes); + } + + // -- persistence --------------------------------------------------------- + + /** Mirror V3's `loaded-plugins` and `plugin-status` keys. */ + private persist(): void { + try { + localStorage.setItem(LOADED_KEY, JSON.stringify(this.getLoadedPlugins())); + const status: Record = {}; + for (const entry of this.entries.values()) { + if (entry.status) status[entry.name] = entry.status; + } + localStorage.setItem("plugin-status", JSON.stringify(status)); + } catch (e) { + log.warn(`無法寫入擴充功能狀態:${String(e)}`); + } + } +} + +/** One loader for the app, created on first use. */ +let instance: PluginLoader | null = null; + +export function createPluginLoader(type = "index"): PluginLoader { + instance ??= new PluginLoader(type); + return instance; +} + +export function pluginLoader(): PluginLoader | null { + return instance; +} diff --git a/packages/core/src/features/plugin/index.ts b/packages/core/src/features/plugin/index.ts new file mode 100644 index 0000000..244bf55 --- /dev/null +++ b/packages/core/src/features/plugin/index.ts @@ -0,0 +1,28 @@ +/** + * 擴充功能 — the extension host, started from `features/index.ts`. + * + * V3 created its plugin loader before any feature module (`index/require.js` + * ran `createPluginLoader('index')` first); the same order is kept here so a + * plugin subscribed to `DataRts` hears the session's first frame. + * + * Loading is asynchronous because the plugin tree is a Rust call. Nothing here + * blocks the app: a plugin that fails to load is a row in 設定 → 擴充 that says + * so, never a boot that stops. + */ +import { createLogger } from "@/lib/logger"; + +import { createPluginLoader } from "./host"; + +const log = createLogger("plugin"); + +export function initPlugins(): void { + const loader = createPluginLoader("index"); + loader.load().catch((e: unknown) => { + log.error(`擴充功能載入失敗:${String(e)}`); + }); +} + +export { createPluginLoader, pluginLoader, PluginLoader, getSensitivityDescription } from "./host"; +export type { PluginContext } from "./host"; +export { MixinManager } from "./mixin"; +export type { LoadedPlugin, PluginEntry, PluginInfo } from "./types"; diff --git a/packages/core/src/features/plugin/mixin.ts b/packages/core/src/features/plugin/mixin.ts new file mode 100644 index 0000000..70b9607 --- /dev/null +++ b/packages/core/src/features/plugin/mixin.ts @@ -0,0 +1,164 @@ +/** + * `MixinManager`, ported from `legacy/src/js/core/mixin.js`. + * + * Injection here is textual, not a wrapper call: the handler's *body* is + * spliced into the method's source and the whole method is rebuilt with + * `Function(...params, body)`. A handler therefore runs inside the method's own + * scope and can read its parameters and locals. That is what plugins were + * written against, so it is what the port does — and why `tauri.conf.json` + * keeps `"security": { "csp": null }`: a CSP without `unsafe-eval` would break + * every mixin. + * + * The public shape is a class of statics because V3 handed plugins the class. + */ + +type Handler = (...args: unknown[]) => unknown; + +interface Injection { + id: symbol; + handler: Handler; + position: "start" | "end" | number; +} + +/** Anything with a prototype whose method can be rebuilt. */ +type Target = { prototype: Record }; + +/** The body between the outermost braces, trimmed — the part that is spliced. */ +function handlerBody(handler: Handler): string { + const text = handler.toString(); + return text.slice(text.indexOf("{") + 1, text.lastIndexOf("}")).trim(); +} + +export class MixinManager { + private static mixins = new Map(); + private static cache = new Map(); + private static lineInjections = new Map>(); + private static targetClasses = new Map(); + + static inject(target: Target, methodName: string, handler: Handler, position: Injection["position"] = "end"): symbol { + if (typeof handler !== "function") throw new Error("Handler must be a function"); + + const injection: Injection = { id: Symbol("mixin"), handler, position }; + MixinManager.initializeMethod(target, methodName); + MixinManager.targetClasses.set(methodName, target); + + if (typeof position === "number") { + if (!MixinManager.lineInjections.has(methodName)) MixinManager.lineInjections.set(methodName, new Map()); + const byLine = MixinManager.lineInjections.get(methodName)!; + if (!byLine.has(position)) byLine.set(position, []); + byLine.get(position)!.push(injection); + } else { + MixinManager.mixins.get(methodName)!.push(injection); + } + + MixinManager.rebuild(MixinManager.targetClasses.get(methodName)!, methodName); + MixinManager.cache.delete(methodName); + return injection.id; + } + + static remove(methodName: string, mixinId: symbol): boolean { + let removed = false; + const target = MixinManager.targetClasses.get(methodName); + + const mixins = MixinManager.mixins.get(methodName); + const index = mixins?.findIndex((m) => m.id === mixinId) ?? -1; + if (index !== -1) { + mixins!.splice(index, 1); + removed = true; + } + + for (const injections of MixinManager.lineInjections.get(methodName)?.values() ?? []) { + const at = injections.findIndex((m) => m.id === mixinId); + if (at !== -1) { + injections.splice(at, 1); + removed = true; + } + } + + if (removed && target) { + MixinManager.cache.delete(methodName); + MixinManager.rebuild(target, methodName); + } + return removed; + } + + static getMixins(methodName: string): { id: symbol; methodName: string }[] { + return (MixinManager.mixins.get(methodName) ?? []).map(({ id }) => ({ id, methodName })); + } + + static clear(methodName: string): void { + MixinManager.mixins.delete(methodName); + MixinManager.lineInjections.delete(methodName); + MixinManager.cache.delete(methodName); + } + + private static initializeMethod(target: Target, methodName: string): void { + if (!MixinManager.mixins.has(methodName)) { + MixinManager.mixins.set(methodName, []); + MixinManager.rebuild(target, methodName); + } + } + + /** + * Rebuild `targetClass.prototype[methodName]` with every injection spliced in. + * + * A method written as a class shorthand, an arrow property or a bound + * function cannot be rebuilt this way — `toString()` of the first is + * `methodName() { … }`, which has no `function` keyword, and the others have + * no braces at all. Those throw here, and the plugin that asked for the + * injection is told so rather than silently doing nothing. + */ + private static rebuild(target: Target, methodName: string): void { + const original = target.prototype[methodName]; + if (typeof original !== "function") { + throw new Error(`MixinManager: ${methodName} is not a function`); + } + + const source = original.toString(); + const open = source.indexOf("("); + const close = source.indexOf(")"); + const braceStart = source.indexOf("{"); + const braceEnd = source.lastIndexOf("}"); + if (open === -1 || close === -1 || braceStart === -1 || braceEnd === -1) { + throw new Error(`MixinManager: cannot read the source of ${methodName}`); + } + + const params = source + .slice(open + 1, close) + .split(",") + .map((p) => p.trim()) + .filter(Boolean); + const isAsync = source.includes("async"); + + let lines = source + .slice(braceStart + 1, braceEnd) + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0); + + const injections = MixinManager.mixins.get(methodName) ?? []; + + const start = injections + .filter((m) => m.position === "start") + .map(({ handler }) => handlerBody(handler)) + .join("\n"); + if (start) lines.unshift(start); + + lines = lines.map((line, index) => { + const at = MixinManager.lineInjections.get(methodName)?.get(index + 1) ?? []; + const injected = at.map(({ handler }) => handlerBody(handler)).join("\n"); + return `${injected}\n${line}`; + }); + + const end = injections + .filter((m) => m.position === "end") + .map(({ handler }) => handlerBody(handler)) + .join("\n"); + if (end) lines.push(end); + + const body = lines.join("\n"); + const wrapped = `return ${isAsync ? "async " : ""}function ${methodName}() {\n${body}\n}`; + + target.prototype[methodName] = new Function(...params, wrapped)(); + } +} diff --git a/packages/core/src/features/plugin/paths.ts b/packages/core/src/features/plugin/paths.ts new file mode 100644 index 0000000..5f8a7a6 --- /dev/null +++ b/packages/core/src/features/plugin/paths.ts @@ -0,0 +1,166 @@ +/** + * A POSIX `path` for the plugin sandbox. + * + * Plugins call `path.join(ctx.info.pluginDir, 'config.yml')` and hand the + * result straight back to `fs.readFileSync`. The host answers those calls from + * an in-memory tree rather than the real disk, so the paths are the host's own: + * a virtual, always-POSIX root (`/plugins/`). A plugin that hardcoded a + * Windows separator still works — a backslash is treated as one here, which is + * also what lets a plugin written on Windows load on macOS. + */ + +const SEP = "/"; + +export const sep = SEP; +export const delimiter = ":"; + +export function normalize(input: string): string { + if (!input) return "."; + const text = input.replace(/\\/g, SEP); + const absolute = text.startsWith(SEP); + const trailing = text.length > 1 && text.endsWith(SEP); + const parts: string[] = []; + for (const part of text.split(SEP)) { + if (part === "" || part === ".") continue; + if (part === "..") { + const last = parts[parts.length - 1]; + if (parts.length > 0 && last !== "..") parts.pop(); + else if (!absolute) parts.push(".."); + continue; + } + parts.push(part); + } + let out = parts.join(SEP); + if (absolute) out = SEP + out; + if (!out) out = absolute ? SEP : "."; + else if (trailing) out += SEP; + return out; +} + +export function isAbsolute(input: string): boolean { + return input.startsWith(SEP) || input.startsWith("\\"); +} + +export function join(...parts: string[]): string { + const joined = parts.filter((p) => p && p.length > 0).join(SEP); + return joined ? normalize(joined) : "."; +} + +export function resolve(...parts: string[]): string { + let resolved = ""; + let absolute = false; + for (let i = parts.length - 1; i >= 0 && !absolute; i--) { + const part = parts[i]; + if (!part) continue; + resolved = `${part}${SEP}${resolved}`; + absolute = isAbsolute(part); + } + if (!absolute) resolved = `${SEP}${resolved}`; + const normalized = normalize(resolved); + return normalized.length > 1 && normalized.endsWith(SEP) ? normalized.slice(0, -1) : normalized; +} + +function stripTrailing(input: string): string { + let out = input; + while (out.length > 1 && out.endsWith(SEP)) out = out.slice(0, -1); + return out; +} + +export function dirname(input: string): string { + if (!input) return "."; + const path = stripTrailing(input.replace(/\\/g, SEP)); + const at = path.lastIndexOf(SEP); + if (at === -1) return "."; + if (at === 0) return SEP; + return path.slice(0, at); +} + +export function basename(input: string, ext?: string): string { + const path = stripTrailing(input.replace(/\\/g, SEP)); + const at = path.lastIndexOf(SEP); + const base = at === -1 ? path : path.slice(at + 1); + if (ext && base.endsWith(ext) && base !== ext) return base.slice(0, -ext.length); + return base; +} + +export function extname(input: string): string { + const base = basename(input); + const at = base.lastIndexOf("."); + if (at <= 0) return ""; + return base.slice(at); +} + +export interface ParsedPath { + root: string; + dir: string; + base: string; + ext: string; + name: string; +} + +export function parse(input: string): ParsedPath { + const root = isAbsolute(input) ? SEP : ""; + const dir = dirname(input); + const base = basename(input); + const ext = extname(base); + return { root, dir: dir === "." && !root ? "" : dir, base, ext, name: base.slice(0, base.length - ext.length) }; +} + +export function format(pathObject: Partial): string { + const dir = pathObject.dir || pathObject.root || ""; + const base = pathObject.base || `${pathObject.name ?? ""}${pathObject.ext ?? ""}`; + return dir ? (dir === SEP ? `${SEP}${base}` : `${dir}${SEP}${base}`) : base; +} + +/** `from` → `to`, both absolute: the `../` a plugin would need to write. */ +export function relative(from: string, to: string): string { + const a = resolve(from).split(SEP).filter(Boolean); + const b = resolve(to).split(SEP).filter(Boolean); + let shared = 0; + while (shared < a.length && shared < b.length && a[shared] === b[shared]) shared++; + const up = a.slice(shared).map(() => ".."); + return [...up, ...b.slice(shared)].join(SEP); +} + +export function toNamespacedPath(input: string): string { + return input; +} + +export interface PathModule { + sep: string; + delimiter: string; + normalize(input: string): string; + isAbsolute(input: string): boolean; + join(...parts: string[]): string; + resolve(...parts: string[]): string; + dirname(input: string): string; + basename(input: string, ext?: string): string; + extname(input: string): string; + parse(input: string): ParsedPath; + format(pathObject: Partial): string; + relative(from: string, to: string): string; + toNamespacedPath(input: string): string; + /** Set below: the sandbox has one flavour of path, so both point here. */ + posix?: PathModule; + win32?: PathModule; +} + +/** The whole module, for `ctx.utils.path` and `require('path')`. */ +export const path: PathModule = { + sep, + delimiter, + normalize, + isAbsolute, + join, + resolve, + dirname, + basename, + extname, + parse, + format, + relative, + toNamespacedPath, +}; + +path.posix = path; +path.win32 = path; diff --git a/packages/core/src/features/plugin/sandbox.ts b/packages/core/src/features/plugin/sandbox.ts new file mode 100644 index 0000000..69d7f69 --- /dev/null +++ b/packages/core/src/features/plugin/sandbox.ts @@ -0,0 +1,749 @@ +/** + * The plugin sandbox: one in-memory file tree and the `fs`, `path` and + * `require` a plugin is handed. + * + * V3 plugins ran in Electron's renderer, where `fs.readFileSync` was + * synchronous and the whole disk was theirs. A synchronous read cannot cross an + * async IPC boundary, so the host instead reads every installed plugin up front + * (one `plugin_list` call), serves reads from memory, and forwards writes to + * Rust one file at a time. Plugins see a virtual POSIX tree rooted at + * `/plugins`, mirroring the real directory — the same layout + * `ctx.info.pluginDir` pointed at in V3. + * + * Deliberately absent: any path outside `/plugins`, `child_process`, Electron + * and npm packages. A plugin that reaches for one gets a named error rather + * than a confusing `undefined`. + */ +import { encodeBase64, type Bytes } from "./base64"; +import { dirname, isAbsolute, join, normalize, path as pathsModule, resolve, type PathModule } from "./paths"; + +const decoder = new TextDecoder("utf-8"); +const encoder = new TextEncoder(); + +/** The virtual root every plugin is mounted under. */ +export const PLUGIN_ROOT = "/plugins"; + +/** A Node `Buffer`, enough of one: `toString` is what plugins actually call. */ +export class PluginBuffer extends Uint8Array { + toString(encoding = "utf8"): string { + switch (encoding) { + case "utf8": + case "utf-8": + return decoder.decode(this); + case "base64": + return encodeBase64(this); + case "hex": + return [...this].map((b) => b.toString(16).padStart(2, "0")).join(""); + case "latin1": + case "binary": + return String.fromCharCode(...this); + case "ascii": + return decoder.decode(this); + default: + throw new Error(`不支援的編碼:${encoding}`); + } + } + + static isBuffer(value: unknown): boolean { + return value instanceof Uint8Array; + } + + static alloc(size: number): PluginBuffer { + return new PluginBuffer(size); + } + + static concat(list: Uint8Array[]): PluginBuffer { + const total = list.reduce((sum, part) => sum + part.length, 0); + const out = new PluginBuffer(total); + let at = 0; + for (const part of list) { + out.set(part, at); + at += part.length; + } + return out; + } + + static from(...args: unknown[]): PluginBuffer { + const [value] = args; + if (typeof value === "string") return new PluginBuffer(encoder.encode(value)); + if (value instanceof Uint8Array) return new PluginBuffer(value); + return new PluginBuffer(0); + } +} + +/** What `statSync` returns: the handful of fields plugins look at. */ +export class PluginStats { + constructor( + private readonly dir: boolean, + private readonly file: boolean, + readonly size: number, + readonly mtimeMs = Date.now(), + ) {} + + isDirectory(): boolean { + return this.dir; + } + + isFile(): boolean { + return this.file; + } + + isSymbolicLink(): boolean { + return false; + } + + isBlockDevice(): boolean { + return false; + } + + isCharacterDevice(): boolean { + return false; + } + + isFIFO(): boolean { + return false; + } + + isSocket(): boolean { + return false; + } + + get mtime(): Date { + return new Date(this.mtimeMs); + } + + get ctime(): Date { + return new Date(this.mtimeMs); + } + + get birthtime(): Date { + return new Date(this.mtimeMs); + } +} + +interface Dirent { + name: string; + isDirectory(): boolean; + isFile(): boolean; +} + +/** An `Error` shaped like Node's, because plugins check `.code`. */ +function fsError(code: string, message: string): Error & { code: string } { + return Object.assign(new Error(message), { code }); +} + +function toBytes(data: unknown): Uint8Array { + if (typeof data === "string") return encoder.encode(data); + if (data instanceof Uint8Array) return new Uint8Array(data); + if (data instanceof ArrayBuffer) return new Uint8Array(data); + throw new TypeError("fs: 資料必須是字串或 Uint8Array"); +} + +/** + * Every installed plugin, mounted at `/plugins/`. + * + * One tree rather than one per plugin, because `ctx.require('../other/x.js')` + * was how V3 plugins reached each other, and a bare `require` would have to + * cross the same boundary anyway. + */ +export class PluginTree { + private files = new Map(); + private dirs = new Set([PLUGIN_ROOT]); + + mount(name: string, files: Map): void { + const root = join(PLUGIN_ROOT, name); + this.dirs.add(root); + for (const [relative, bytes] of files) { + this.write(join(root, relative), bytes); + } + } + + has(path: string): boolean { + return this.files.has(normalize(path)); + } + + read(path: string): Uint8Array | undefined { + return this.files.get(normalize(path)); + } + + isDirectory(path: string): boolean { + const key = normalize(path); + if (this.dirs.has(key)) return true; + return this.children(key).length > 0; + } + + write(path: string, bytes: Uint8Array): void { + const key = normalize(path); + this.files.set(key, bytes); + this.dirs.add(dirname(key)); + } + + delete(path: string): boolean { + const key = normalize(path); + let removed = this.files.delete(key); + for (const file of [...this.files.keys()]) { + if (file.startsWith(`${key}/`)) { + this.files.delete(file); + removed = true; + } + } + for (const dir of [...this.dirs]) { + if (dir === key || dir.startsWith(`${key}/`)) { + this.dirs.delete(dir); + removed = true; + } + } + return removed; + } + + /** Every entry directly under `path`, in the order a directory lists them. */ + children(path: string): Dirent[] { + const key = normalize(path); + const prefix = key === "/" ? "/" : `${key}/`; + const seen = new Map(); + const add = (absolute: string, isDir: boolean) => { + const rest = absolute.slice(prefix.length); + if (!rest || rest.includes("/")) return; + const existing = seen.get(rest); + if (existing) { + if (isDir) seen.set(rest, dirent(rest, true, false)); + return; + } + seen.set(rest, dirent(rest, isDir, !isDir)); + }; + for (const file of this.files.keys()) if (file.startsWith(prefix)) add(file, false); + for (const dir of this.dirs) if (dir.startsWith(prefix)) add(dir, true); + return [...seen.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + } + + /** Relative POSIX path → bytes, for the verifier. */ + snapshot(root: string): Map { + const key = normalize(root); + const prefix = `${key}/`; + const out = new Map(); + for (const [file, bytes] of this.files) { + if (file.startsWith(prefix)) out.set(file.slice(prefix.length), bytes); + } + return out; + } +} + +function dirent(name: string, isDir: boolean, isFile: boolean): Dirent { + return { name, isDirectory: () => isDir, isFile: () => isFile }; +} + +export interface RuntimeOptions { + plugin: string; + tree: PluginTree; + /** A file the plugin wrote — `null` when it was deleted. Relative path. */ + onWrite(path: string, data: Uint8Array | null): void; + log: { + debug(...args: unknown[]): void; + info(...args: unknown[]): void; + warn(...args: unknown[]): void; + error(...args: unknown[]): void; + }; + /** + * The plugin's own directory. Relative paths resolve here and `process.cwd()` + * reports it — `ctx.info.pluginDir` stays the *root*, as it was in V3. + */ + pluginDir?: string; +} + +/** + * Everything a plugin sees of its host: `fs`, `path`, `require`, a `Buffer`, a + * minimal `process`, and the entry loader that evaluates `index.js`. + */ +export class PluginRuntime { + readonly path: PathModule; + readonly fs: Record; + readonly pluginDir: string; + readonly Buffer = PluginBuffer; + + private modules = new Map }>(); + private tree: PluginTree; + + constructor(private readonly options: RuntimeOptions) { + this.tree = options.tree; + // V3's `info.pluginDir` was the *root* of the plugins directory, not the + // plugin's own folder; plugins joined their name onto it. That stays true + // for `ctx.info`, but a *relative* path should mean "next to my own files", + // not "at the root beside my siblings". + this.pluginDir = options.pluginDir ?? PLUGIN_ROOT; + this.path = pathsModule; + this.fs = this.buildFs(); + } + + // -- paths --------------------------------------------------------------- + + /** A plugin-relative or absolute path as an absolute virtual path. */ + toVirtual(input: string): string { + if (isAbsolute(input)) return normalize(input); + return resolve(this.pluginDir, input); + } + + /** The plugin this path belongs to, for a cross-plugin write refusal. */ + private ownName(path: string): string { + return normalize(path).slice(PLUGIN_ROOT.length + 1).split("/")[0] ?? ""; + } + + /** A virtual path as the plugin's own relative path, for Rust. */ + private relativeToPlugin(path: string): string { + return normalize(path).slice(`${join(PLUGIN_ROOT, this.options.plugin)}/`.length); + } + + // -- fs ------------------------------------------------------------------ + + private buildFs(): Record { + const fs: Record = {}; + const read = (p: string): Uint8Array => { + const bytes = this.tree.read(this.toVirtual(p)); + if (!bytes) throw fsError("ENOENT", `ENOENT: no such file or directory, open '${p}'`); + return bytes; + }; + + fs.readFileSync = (p: string, options?: string | { encoding?: string | null } | null) => { + const bytes = read(p); + const encoding = typeof options === "string" ? options : options?.encoding; + if (!encoding) return new PluginBuffer(bytes); + return new PluginBuffer(bytes).toString(encoding); + }; + + fs.writeFileSync = (p: string, data: unknown) => { + const target = this.toVirtual(p); + const owner = this.ownName(target); + if (owner !== this.options.plugin) { + // V3's fs could write anywhere; the tree holds only plugins, so the + // only meaningful refusal left is writing into another plugin. + throw fsError("EACCES", `EACCES: 擴充功能只能寫入自己的資料夾,'${p}'`); + } + const bytes = toBytes(data); + this.tree.write(target, bytes); + this.options.onWrite(this.relativeToPlugin(target), bytes); + }; + + fs.appendFileSync = (p: string, data: unknown) => { + const existing = this.tree.read(this.toVirtual(p)); + const addition = toBytes(data); + const merged = new Uint8Array((existing?.length ?? 0) + addition.length); + if (existing) merged.set(existing, 0); + merged.set(addition, existing?.length ?? 0); + (fs.writeFileSync as (p: string, data: unknown) => void)(p, merged); + }; + + fs.existsSync = (p: string): boolean => { + const key = this.toVirtual(p); + return this.tree.has(key) || this.tree.isDirectory(key); + }; + + fs.statSync = (p: string): PluginStats => { + const key = this.toVirtual(p); + const bytes = this.tree.read(key); + if (bytes) return new PluginStats(false, true, bytes.length); + if (this.tree.isDirectory(key)) return new PluginStats(true, false, 0); + throw fsError("ENOENT", `ENOENT: no such file or directory, stat '${p}'`); + }; + + fs.lstatSync = fs.statSync; + + fs.readdirSync = (p: string, options?: { withFileTypes?: boolean } | string): unknown[] => { + const key = this.toVirtual(p); + if (!this.tree.isDirectory(key)) { + throw fsError("ENOENT", `ENOENT: no such file or directory, scandir '${p}'`); + } + const entries = this.tree.children(key); + if (options && typeof options === "object" && options.withFileTypes) return entries; + return entries.map((entry) => entry.name); + }; + + fs.mkdirSync = () => undefined; // directories exist because files do + fs.ensureDirSync = () => undefined; + fs.mkdirpSync = () => undefined; + + fs.unlinkSync = (p: string) => { + const target = this.toVirtual(p); + if (!this.tree.delete(target)) { + throw fsError("ENOENT", `ENOENT: no such file or directory, unlink '${p}'`); + } + this.options.onWrite(this.relativeToPlugin(target), null); + }; + fs.rmdirSync = fs.unlinkSync; + fs.rmSync = fs.unlinkSync; + fs.removeSync = fs.unlinkSync; + + fs.copyFileSync = (from: string, to: string) => { + (fs.writeFileSync as (p: string, data: unknown) => void)(to, read(from)); + }; + + fs.renameSync = (from: string, to: string) => { + const bytes = read(from); + (fs.writeFileSync as (p: string, data: unknown) => void)(to, bytes); + (fs.unlinkSync as (p: string) => void)(from); + }; + + fs.realpathSync = (p: string) => this.toVirtual(p); + + // Callback forms, for plugins that used them. + const callbackify = + (sync: (...args: never[]) => unknown) => + (...args: unknown[]) => { + const callback = args.pop() as ((error: unknown, value?: unknown) => void) | undefined; + try { + const value = (sync as (...a: unknown[]) => unknown)(...args); + callback?.(null, value); + } catch (error) { + callback?.(error); + } + }; + fs.readFile = callbackify(fs.readFileSync as (...args: never[]) => unknown); + fs.writeFile = callbackify(fs.writeFileSync as (...args: never[]) => unknown); + fs.stat = callbackify(fs.statSync as (...args: never[]) => unknown); + fs.readdir = callbackify(fs.readdirSync as (...args: never[]) => unknown); + + fs.promises = { + readFile: (p: string, o?: unknown) => Promise.resolve(fs.readFileSync && (fs.readFileSync as (p: string, o?: unknown) => unknown)(p, o)), + writeFile: (p: string, d: unknown) => Promise.resolve((fs.writeFileSync as (p: string, d: unknown) => void)(p, d)), + stat: (p: string) => Promise.resolve((fs.statSync as (p: string) => PluginStats)(p)), + readdir: (p: string) => Promise.resolve((fs.readdirSync as (p: string) => unknown[])(p)), + unlink: (p: string) => Promise.resolve((fs.unlinkSync as (p: string) => void)(p)), + mkdir: () => Promise.resolve(), + access: (p: string) => Promise.resolve((fs.existsSync as (p: string) => boolean)(p)), + }; + + // fs-extra, which the V3 settings and plugins both used. + fs.readJsonSync = (p: string, options?: { encoding?: string }) => { + const text = (fs.readFileSync as (p: string, o?: unknown) => string)(p, options ?? "utf8"); + return JSON.parse(text) as unknown; + }; + fs.writeJsonSync = (p: string, value: unknown, options?: { spaces?: number }) => { + (fs.writeFileSync as (p: string, d: unknown) => void)(p, JSON.stringify(value, null, options?.spaces ?? 2)); + }; + fs.outputJsonSync = fs.writeJsonSync; + fs.readJSONSync = fs.readJsonSync; + fs.writeJSONSync = fs.writeJsonSync; + + fs.watch = () => ({ close: () => undefined }); + fs.createReadStream = () => { + throw new Error("擴充功能不支援 fs.createReadStream,請改用 fs.readFileSync。"); + }; + fs.createWriteStream = () => { + throw new Error("擴充功能不支援 fs.createWriteStream,請改用 fs.writeFileSync。"); + }; + + fs.constants = { F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 }; + fs.exists = (p: string, callback: (exists: boolean) => void) => callback((fs.existsSync as (p: string) => boolean)(p)); + return fs; + } + + // -- require ------------------------------------------------------------- + + /** Evaluate a module by specifier, relative to the file that asked. */ + require(specifier: string, from: string): unknown { + const name = specifier.replace(/^node:/, ""); + + if (name in BUILTINS) return this.builtin(name); + if (name in UNSUPPORTED) throw new Error(UNSUPPORTED[name]); + + if (!isAbsolute(specifier) && !specifier.startsWith(".")) { + // V3 fell through to Node's `require`, which resolved from core/ — i.e. + // never. Saying so beats an empty module. + throw new Error(`Cannot find module '${specifier}':擴充功能不能載入 npm 套件,請改用相對路徑或 ctx.require。`); + } + + const base = isAbsolute(specifier) ? normalize(specifier) : resolve(dirname(from), specifier); + for (const candidate of [base, `${base}.js`, `${base}.cjs`, `${base}.json`, `${join(base, "index.js")}`, `${join(base, "index.json")}`]) { + if (this.tree.has(candidate)) return this.evaluate(candidate); + } + throw new Error(`Cannot find module '${specifier}' from ${from}`); + } + + private evaluate(file: string): unknown { + const cached = this.modules.get(file); + if (cached) return cached.exports; + + const bytes = this.tree.read(file); + if (!bytes) throw new Error(`Cannot find module '${file}'`); + const source = decoder.decode(bytes); + const dir = dirname(file); + const module = { exports: {} as Record }; + this.modules.set(file, module); + + if (file.endsWith(".json")) { + module.exports = JSON.parse(source) as Record; + return module.exports; + } + + const require = (specifier: string) => this.require(specifier, file); + // The wrapper is what makes a CommonJS plugin run: `require`, `module`, + // `__filename` and `__dirname` as globals inside the file's own scope. + // `sourceURL` puts the plugin's own name in a stack trace. + + const factory = new Function( + "exports", + "require", + "module", + "__filename", + "__dirname", + "Buffer", + "process", + "console", + "global", + `${source}\n//# sourceURL=plugin://${this.options.plugin}${file}`, + ) as (...args: unknown[]) => void; + + factory( + module.exports, + require, + module, + file, + dir, + PluginBuffer, + this.processShim(), + this.consoleShim(), + globalThis, + ); + return module.exports; + } + + /** Evaluate the plugin's entry file and return what it exported. */ + loadEntry(entry = "index.js"): unknown { + return this.evaluate(join(PLUGIN_ROOT, this.options.plugin, entry)); + } + + /** `ctx.require`, which V3 implemented as `require` with path juggling. */ + ctxRequire(modulePath: string, from: string): unknown { + // `from` is the plugin's own *directory*. `require` resolves a relative + // specifier against the directory of the file that asked, so name a file + // inside it — otherwise `./lib/x` would look beside the plugin, not in it. + return this.require(modulePath, `${from}/index.js`); + } + + // -- small builtins ------------------------------------------------------ + + private builtin(name: string): unknown { + switch (name) { + case "path": + return this.path; + case "fs": + case "fs-extra": + case "fs-extra/esm": + return this.fs; + case "buffer": + return { Buffer: PluginBuffer }; + case "process": + return this.processShim(); + case "events": + return { EventEmitter: EventEmitter, default: EventEmitter }; + case "util": + return utilShim; + case "os": + return osShim; + case "url": + return { URL, URLSearchParams, pathToFileURL, fileURLToPath, default: { URL, URLSearchParams } }; + case "crypto": + return cryptoShim; + default: + throw new Error(UNSUPPORTED[name] ?? `Cannot find module '${name}'`); + } + } + + private processShim() { + const platform = navigator.platform.toLowerCase().includes("win") + ? "win32" + : navigator.platform.toLowerCase().includes("mac") + ? "darwin" + : "linux"; + return { + platform, + arch: "x64", + version: "v22.0.0", + versions: { node: "22.0.0", electron: undefined }, + env: {} as Record, + argv: ["trem-lite"], + pid: 0, + cwd: () => this.pluginDir, + chdir: () => undefined, + nextTick: (fn: (...args: unknown[]) => void, ...args: unknown[]) => queueMicrotask(() => fn(...args)), + on: () => undefined, + exit: () => { + throw new Error("擴充功能不能結束主程式。"); + }, + }; + } + + private consoleShim() { + const { log } = this.options; + return { + log: (...args: unknown[]) => log.info(...args), + info: (...args: unknown[]) => log.info(...args), + warn: (...args: unknown[]) => log.warn(...args), + error: (...args: unknown[]) => log.error(...args), + debug: (...args: unknown[]) => log.debug(...args), + trace: (...args: unknown[]) => log.debug(...args), + table: (...args: unknown[]) => log.info(...args), + }; + } +} + +/** The built-in modules `require` answers without touching the tree. */ +const BUILTINS: Record = { + path: true, + fs: true, + "fs-extra": true, + "fs-extra/esm": true, + buffer: true, + process: true, + events: true, + util: true, + os: true, + url: true, + crypto: true, +}; + +/** Named refusals: a plugin that needs one of these needs a different host. */ +const UNSUPPORTED: Record = { + electron: "擴充功能不能使用 Electron API。", + "@electron/remote": "擴充功能不能使用 Electron API。", + child_process: "擴充功能不能啟動其他程式。", + "node:child_process": "擴充功能不能啟動其他程式。", + worker_threads: "擴充功能不能建立 worker。", + net: "擴充功能不能直接開 socket,請改用 ctx.TREM.constant.URL 與 fetch。", + http: "擴充功能不能直接開 socket,請改用 fetch。", + https: "擴充功能不能直接開 socket,請改用 fetch。", + axios: "擴充功能不能載入 npm 套件,請改用 fetch。", +}; + +/** Node's `EventEmitter`, enough of one for the events plugins subscribe to. */ +export class EventEmitter { + private handlers = new Map void)[]>(); + + on(event: string | symbol, handler: (...args: unknown[]) => void): this { + this.handlers.set(event, [...(this.handlers.get(event) ?? []), handler]); + return this; + } + + addListener(event: string | symbol, handler: (...args: unknown[]) => void): this { + return this.on(event, handler); + } + + once(event: string | symbol, handler: (...args: unknown[]) => void): this { + const wrapped = (...args: unknown[]) => { + this.off(event, wrapped); + handler(...args); + }; + return this.on(event, wrapped); + } + + off(event: string | symbol, handler: (...args: unknown[]) => void): this { + this.handlers.set(event, (this.handlers.get(event) ?? []).filter((h) => h !== handler)); + return this; + } + + removeListener(event: string | symbol, handler: (...args: unknown[]) => void): this { + return this.off(event, handler); + } + + removeAllListeners(event?: string | symbol): this { + if (event === undefined) this.handlers.clear(); + else this.handlers.delete(event); + return this; + } + + listeners(event: string | symbol): ((...args: unknown[]) => void)[] { + return [...(this.handlers.get(event) ?? [])]; + } + + listenerCount(event: string | symbol): number { + return this.handlers.get(event)?.length ?? 0; + } + + setMaxListeners(): this { + return this; + } + + emit(event: string | symbol, ...args: unknown[]): boolean { + const handlers = this.handlers.get(event) ?? []; + for (const handler of [...handlers]) handler(...args); + return handlers.length > 0; + } +} + +const utilShim = { + format: (template: unknown, ...args: unknown[]): string => { + let index = 0; + return String(template).replace(/%[sdifjoO%]/g, (match) => { + if (match === "%%") return "%"; + const value = args[index++]; + if (match === "%j") { + try { + return JSON.stringify(value); + } catch { + return "[Circular]"; + } + } + return typeof value === "string" ? value : inspect(value); + }); + }, + inspect, + promisify: + (fn: (...args: unknown[]) => unknown) => + (...args: unknown[]) => + new Promise((done, fail) => { + fn(...args, (error: unknown, value: unknown) => (error ? fail(error) : done(value))); + }), + types: { isDate: (v: unknown) => v instanceof Date, isRegExp: (v: unknown) => v instanceof RegExp }, + inherits: () => undefined, + deprecate: (fn: T): T => fn, +}; + +function inspect(value: unknown, depth = 2): string { + if (typeof value === "string") return `'${value}'`; + if (value instanceof Error) return value.stack ?? value.message; + if (value === null || typeof value !== "object") return String(value); + if (depth <= 0) return "[Object]"; + if (Array.isArray(value)) return `[ ${value.map((v) => inspect(v, depth - 1)).join(", ")} ]`; + return `{ ${Object.entries(value) + .map(([k, v]) => `${k}: ${inspect(v, depth - 1)}`) + .join(", ")} }`; +} + +const osShim = { + platform: (): string => + navigator.platform.toLowerCase().includes("win") ? "win32" : navigator.platform.toLowerCase().includes("mac") ? "darwin" : "linux", + arch: (): string => "x64", + type: (): string => "TREM-Lite", + release: (): string => navigator.userAgent, + hostname: (): string => location.hostname || "localhost", + tmpdir: (): string => PLUGIN_ROOT, + homedir: (): string => PLUGIN_ROOT, + EOL: "\n", + cpus: (): { model: string }[] => [{ model: "unknown" }], + totalmem: (): number => 0, + freemem: (): number => 0, + uptime: (): number => performance.now() / 1000, + userInfo: () => ({ username: "trem" }), +}; + +const cryptoShim = { + getRandomValues: >(array: T): T => crypto.getRandomValues(array), + randomUUID: (): string => crypto.randomUUID(), + randomBytes: (size: number): PluginBuffer => { + const bytes = new PluginBuffer(size); + crypto.getRandomValues(bytes as Bytes); + return bytes; + }, + subtle: crypto.subtle, + createHash: () => { + // WebCrypto's digest is async only, and a plugin's call site is not. + throw new Error("擴充功能不支援 crypto.createHash,請改用 crypto.subtle.digest。"); + }, +}; + +function pathToFileURL(file: string): URL { + return new URL(`file://${file}`); +} + +function fileURLToPath(url: URL | string): string { + const text = typeof url === "string" ? url : url.href; + return decodeURIComponent(text.replace(/^file:\/\//, "")); +} diff --git a/packages/core/src/features/plugin/trem.ts b/packages/core/src/features/plugin/trem.ts new file mode 100644 index 0000000..2ddd676 --- /dev/null +++ b/packages/core/src/features/plugin/trem.ts @@ -0,0 +1,87 @@ +/** + * The `TREM` global a plugin receives as `ctx.TREM`. + * + * V3 plugins were written against the object `legacy/src/js/index/constant.js` + * published: `TREM.constant` (colours, limits, URLs), `TREM.variable` (live app + * state) and `TREM.class` (the app's manager classes). This module rebuilds it + * from V4's equivalents. + * + * Two rules decide what is here. `variable` is handed over **by reference** — + * a plugin that writes `TREM.variable.cache.show_intensity` is mutating the + * app's own state, which is what V3 plugins do — and anything V4 genuinely does + * not have is left out rather than faked, so a plugin that depends on it fails + * loudly at the point of use instead of silently doing nothing. + */ +import * as audioClient from "@/lib/audioClient"; +import { + COLOR, + EEW_AUTHOR, + HTTP_TIMEOUT, + INTENSITY_LIST, + LAST_DATA_TIMEOUT_ERROR, + MAP, + REPORT_LIMIT, + SHOW_REPORT, +} from "@/lib/constants"; +import { HOST } from "@/lib/endpoints"; +import { events } from "@/lib/events"; +import { variable, type TremVariable } from "@/lib/variable"; + +/** `variable` as a V3 plugin sees it: the app state plus the event bus. */ +export type PluginVariable = TremVariable & { events: typeof events }; + +export interface TremGlobal { + constant: { + COLOR: typeof COLOR; + HTTP_TIMEOUT: typeof HTTP_TIMEOUT; + LAST_DATA_TIMEOUT_ERROR: number; + EEW_AUTHOR: string[]; + REPORT_LIMIT: number; + MAP: typeof MAP; + SHOW_REPORT: boolean; + INTENSITY_LIST: string[]; + URL: { API: string; LB: string; REPLAY: string }; + }; + variable: PluginVariable; + /** + * Only the managers with a V4 counterpart are present. DataManager, + * ReportManager, FocusManager, EewAreaManager, BoxManager, ReplayControler + * and WindowControler are gone — V4 splits that work across `features/` and + * Rust — so they are `undefined` here on purpose. + */ + class: { AudioManager: typeof audioClient }; +} + +/** Built once: a plugin compares `ctx.TREM.variable` by identity. */ +let cached: TremGlobal | null = null; + +export function tremGlobal(): TremGlobal { + if (cached) return cached; + + const live = variable as PluginVariable; + // V3 kept the bus at `TREM.variable.events`; plugins call + // `TREM.variable.events.on('DataRts', …)`. Assigning it onto the singleton + // keeps that reachable and leaves the object identity intact. + live.events = events; + + cached = { + constant: { + COLOR, + HTTP_TIMEOUT, + LAST_DATA_TIMEOUT_ERROR, + EEW_AUTHOR: [...EEW_AUTHOR], + REPORT_LIMIT, + MAP, + SHOW_REPORT, + INTENSITY_LIST: [...INTENSITY_LIST], + URL: { + API: `https://${HOST.lbApi}`, + LB: `https://${HOST.lbStatic}`, + REPLAY: `https://${HOST.coreApi}`, + }, + }, + variable: live, + class: { AudioManager: audioClient }, + }; + return cached; +} diff --git a/packages/core/src/features/plugin/types.ts b/packages/core/src/features/plugin/types.ts new file mode 100644 index 0000000..8f34c01 --- /dev/null +++ b/packages/core/src/features/plugin/types.ts @@ -0,0 +1,94 @@ +/** + * The extension contract, carried over from the Electron build + * (`legacy/src/js/core/plugin.js`) so extensions written for TREM-Lite 3 keep + * working. Field names, status strings and both loader styles are the published + * V3 format: changing any of them would break every plugin already in the wild, + * so this file describes what exists rather than what would be tidier. + */ + +/** `info.json` — the manifest every plugin ships. */ +export interface PluginInfo { + name: string; + version: string; + description?: string; + author?: string; + /** Which host this plugin runs in; `index` is the main window. */ + loader?: string[]; + /** Enable on first sight. Honoured only for a verified ExpTechTW plugin. */ + "auto-enable"?: boolean; + /** `trem` is the host's version; every other key is another plugin's name. */ + dependencies?: Record; + /** What the plugin touches, as declared by its author. */ + sensitivity?: { level?: number; description?: string }; + [key: string]: unknown; +} + +/** `signature.json` — written by `tool/plugin/sign.mjs`. */ +export interface PluginSignature { + /** Relative POSIX path → SHA-256 hex of the LF-normalised text. */ + fileHashes: Record; + /** RSA-SHA256 over `JSON.stringify(fileHashes)`, base64. */ + signature: string; + /** A key in `/plugin-keys`; `official` or absent = ExpTech. */ + keyId?: string; +} + +/** One file as Rust hands it over: base64, because assets are not text. */ +export interface PluginFile { + path: string; + data: string; +} + +/** One installed plugin directory, as returned by `plugin_list`. */ +export interface PluginDir { + name: string; + files: PluginFile[]; +} + +/** A trusted signing key, from `plugin_keys`. */ +export interface PluginKey { + id: string; + pem: string; +} + +export interface VerifyResult { + valid: boolean; + error?: string; + keyId?: string; +} + +/** What went wrong with one plugin, shown in the 擴充 page. */ +export interface PluginStatus { + type: "ok" | "warn" | "error"; + msg: string; +} + +/** One row of the 擴充 page. */ +export interface PluginEntry { + name: string; + info: PluginInfo; + /** The directory still exists on disk (false = installed but deleted). */ + present: boolean; + /** `signature.json` is absent, or does not match the files. */ + verified: boolean; + /** Why verification failed, verbatim as V3 reported it. */ + verifyError?: string; + keyId?: string; + enabled: boolean; + /** The plugin's code ran without throwing. */ + loaded: boolean; + status: PluginStatus | null; + sensitivity: { level: number; description: string }; + /** The plugin ships a `config.yml` (V3 offered a YAML editor for it). */ + hasConfig: boolean; +} + +/** The shape persisted under `loaded-plugins`, read by tooling and V3 alike. */ +export interface LoadedPlugin { + name: string; + version: string; + description?: string; + author?: string; + ctxDependencies: string[]; + sensitivity: { level: number; description: string }; +} diff --git a/packages/core/src/features/plugin/verify.ts b/packages/core/src/features/plugin/verify.ts new file mode 100644 index 0000000..ed91b2f --- /dev/null +++ b/packages/core/src/features/plugin/verify.ts @@ -0,0 +1,117 @@ +/** + * Signature checking, ported from `legacy/src/js/core/verify.js`. + * + * The Electron build verified with `crypto.createVerify('SHA256')`; WebCrypto's + * RSASSA-PKCS1-v1_5 with SHA-256 is the same scheme, so a `signature.json` + * written for TREM-Lite 3 verifies here unchanged. Two details decide whether + * that is actually true: + * + * - the hash covers the LF form of each file's text, not its bytes, so the + * same plugin verifies after being unzipped on Windows with CRLF endings; + * - the signed message is the UTF-8 bytes of `JSON.stringify(fileHashes)`, + * in the key order the signer wrote, so the check must not re-serialise. + */ +import { decodeBase64, type Bytes } from "./base64"; +import type { PluginSignature, VerifyResult } from "./types"; + +/** + * ExpTech's release key (`legacy/src/js/core/plugin.js:33`). `keyId` absent or + * `official` selects this one; any other id must have a `.pem` of that name in + * `/plugin-keys`. + */ +export const OFFICIAL_KEY = `-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzQn1ouv0mfzVKJevJiq+ +6rV9mwCEvQpauQ2QNjy4TiwhqzqNiOPwpM3qo+8+3Ld+DUhzZzSzyx894dmJGlWQ +wNss9Vs5/gnuvn6PurNXC42wkxY6Dmsnp/M6g08iqGXVcM6ZWmvCZ3BzBvwExxRR +09KxHZVhwoMcF5Kp9l/hNZqXRgYMn3GLt+m78Hr+ZUjHiF8K9UH2TPxKRa/4ttPX +6nDBZxZUCwFD7Zh6RePg07JDbO5fI/UYrqZYyDPK8w9xdXtke9LbdXmMuuk/x57h +foRArUkhPvUk/77mxo4++3EFnTUxYMnQVuMkDaYNRu7w83abUuhsjNlL/es24HSm +lwIDAQAB +-----END PUBLIC KEY-----`; + +/** `\r\n` and a lone `\r` both become `\n` — what the signer hashed. */ +export function normalizeContent(content: string): string { + return content.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); +} + +const decoder = new TextDecoder("utf-8"); +const encoder = new TextEncoder(); + +/** Rust hands files over base64, so a plugin may ship binary assets. */ +export function decodeFile(data: string): Bytes { + return decodeBase64(data); +} + +/** The text the hashes cover: Node's `readFileSync(path, 'utf8')` equivalent. */ +export function fileText(bytes: Uint8Array): string { + return normalizeContent(decoder.decode(bytes)); +} + +export async function sha256Hex(text: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", encoder.encode(text)); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +/** A `-----BEGIN PUBLIC KEY-----` block as the DER bytes WebCrypto imports. */ +export function pemToBytes(pem: string): Bytes { + const body = pem.replace(/-----(BEGIN|END) PUBLIC KEY-----/g, "").replace(/\s+/g, ""); + return decodeBase64(body); +} + +/** + * Verify one plugin directory. + * + * `files` is keyed by the path relative to the plugin root, POSIX style. + * Hidden entries and `signature.json` itself are not part of the signed set + * (verify.js skipped both), and `trem.json` is hashed by neither side. + */ +export async function verifyPlugin( + files: Map, + keys: Map, +): Promise { + const raw = files.get("signature.json"); + if (!raw) return { valid: false, error: "Missing signature.json" }; + + let parsed: PluginSignature; + try { + parsed = JSON.parse(decoder.decode(raw)) as PluginSignature; + } catch (e) { + return { valid: false, error: `signature.json 不是合法的 JSON:${String(e)}` }; + } + + const { fileHashes, signature, keyId } = parsed; + if (!fileHashes || !signature) return { valid: false, error: "Invalid signature data format" }; + + for (const [path, bytes] of files) { + // A dot-file is the author's business; `trem.json` is written after + // signing (it holds the install source), so neither is covered. + if (path.startsWith(".") || path.split("/").some((part) => part.startsWith("."))) continue; + if (path === "signature.json" || path === "trem.json") continue; + + if (!fileHashes[path]) return { valid: false, error: `Extra file: ${path}` }; + const actual = await sha256Hex(fileText(bytes)); + if (actual !== fileHashes[path]) return { valid: false, error: `Modified file: ${path}` }; + } + + const pem = !keyId || keyId === "official" ? OFFICIAL_KEY : keys.get(keyId); + if (!pem) return { valid: false, error: `Unknown key ID: ${keyId}` }; + + try { + const key = await crypto.subtle.importKey( + "spki", + pemToBytes(pem), + { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, + false, + ["verify"], + ); + const valid = await crypto.subtle.verify( + "RSASSA-PKCS1-v1_5", + key, + decodeBase64(signature), + encoder.encode(JSON.stringify(fileHashes)), + ); + return { valid, error: valid ? undefined : "Invalid signature", keyId: keyId ?? "official" }; + } catch (e) { + return { valid: false, error: `簽名驗證失敗:${String(e)}` }; + } +} diff --git a/packages/core/src/features/plugin/version.ts b/packages/core/src/features/plugin/version.ts new file mode 100644 index 0000000..f5af4ba --- /dev/null +++ b/packages/core/src/features/plugin/version.ts @@ -0,0 +1,118 @@ +/** + * Version requirements, ported from `legacy/src/js/core/plugin.js` line for + * line. `compareVersions` returns "v1 >= v2" rather than a three-way compare, + * and a snapshot sorts below the release it precedes (`26.1.0-26w40a` is a + * pre-release of `26.1.0`) — both quirks are part of the format plugins were + * written against, so they are reproduced rather than corrected. + */ + +export interface ParsedVersion { + major: number; + minor: number; + patch: number; + prerelease: string[]; + build: string[]; + version: string; +} + +const VERSION_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+([\w.-]+))?$/; + +export function parseVersion(version: string): ParsedVersion | null { + const match = VERSION_RE.exec(version ?? ""); + if (!match) return null; + return { + major: parseInt(match[1], 10), + minor: parseInt(match[2], 10), + patch: parseInt(match[3], 10), + prerelease: match[4] ? match[4].split(".") : [], + build: match[5] ? match[5].split(".") : [], + version, + }; +} + +/** release = 3, `-rc` = 2, `-pre` = 1, anything else pre-release = 0. */ +export function getVersionPriority(version: string): number { + if (!version) return 0; + const parsed = parseVersion(version); + if (!parsed) return 0; + const prerelease = parsed.prerelease[0]; + if (!prerelease) return 3; + if (prerelease === "rc") return 2; + if (prerelease === "pre") return 1; + return 0; +} + +export function isExactVersionMatch(v1: string, v2: string): boolean { + const parsed1 = parseVersion(v1); + const parsed2 = parseVersion(v2); + if (!parsed1 || !parsed2) return false; + if (parsed1.major !== parsed2.major || parsed1.minor !== parsed2.minor || parsed1.patch !== parsed2.patch) { + return false; + } + const pre1 = parsed1.prerelease; + const pre2 = parsed2.prerelease; + if (pre1.length !== pre2.length) return false; + if (pre1.length === 0) return true; + return pre1[0] === pre2[0] && pre1[1] === pre2[1]; +} + +/** True when `v1` is the same version as `v2` or newer. */ +export function compareVersions(v1: string, v2: string): boolean { + const parsed1 = parseVersion(v1); + const parsed2 = parseVersion(v2); + if (!parsed1 || !parsed2) return false; + if (parsed1.major !== parsed2.major) return parsed1.major >= parsed2.major; + if (parsed1.minor !== parsed2.minor) return parsed1.minor >= parsed2.minor; + if (parsed1.patch !== parsed2.patch) return parsed1.patch >= parsed2.patch; + + const priority1 = getVersionPriority(v1); + const priority2 = getVersionPriority(v2); + if (priority1 !== priority2) return priority1 >= priority2; + if (parsed1.prerelease.length > 1 && parsed2.prerelease.length > 1) { + return parsed1.prerelease[1] >= parsed2.prerelease[1]; + } + return true; +} + +/** `">=1.0.0"`, `"<2.0.0"`, `"=1.2.3"`, or several ranges separated by spaces. */ +export function validateVersionRequirement(current: string, required: string): boolean { + if (required.includes(" ")) { + return required.split(" ").every((range) => validateVersionRequirement(current, range)); + } + const operator = /^[>=<]+/.exec(required)?.[0] || ">="; + const reqVersion = required.replace(/^[>=<]+/, ""); + switch (operator) { + case "=": + return isExactVersionMatch(current, reqVersion); + case ">=": + return compareVersions(current, reqVersion); + case ">": + return compareVersions(current, reqVersion) && !isExactVersionMatch(current, reqVersion); + case "<": + return !compareVersions(current, reqVersion); + case "<=": + return !compareVersions(current, reqVersion) || isExactVersionMatch(current, reqVersion); + default: + return compareVersions(current, reqVersion); + } +} + +/** `">=1.0.0 <2.0.0"` → `"大於等於 1.0.0 且 小於 2.0.0"`, for the error message. */ +export function getVersionPrefixString(required: string): string { + if (required.includes(" ")) { + return required + .split(" ") + .map((range) => getVersionPrefixString(range)) + .join(" 且 "); + } + const operator = /^[>=<]+/.exec(required)?.[0] ?? ">="; + const version = required.replace(/^[>=<]+/, ""); + const prefixMap: Record = { + "=": "等於", + ">": "大於", + ">=": "大於等於", + "<": "小於", + "<=": "小於等於", + }; + return `${prefixMap[operator] || "大於等於"} ${version}`; +} diff --git a/packages/core/src/features/settings/Extensions.tsx b/packages/core/src/features/settings/Extensions.tsx new file mode 100644 index 0000000..7d48927 --- /dev/null +++ b/packages/core/src/features/settings/Extensions.tsx @@ -0,0 +1,242 @@ +/** + * 擴充 — the extensions page. + * + * V3's `setting/plugin_list.js` page, rebuilt: the same rows (verified or not, + * loaded or not, what it can touch, what went wrong), the same 10-second + * countdown before an unverified extension may be enabled, the same one-click + * removal. What is new is installing: a `.trem` package can be dropped onto the + * page, which is the whole install flow — the archive is unpacked in the + * webview and written through the host. + * + * The markup mirrors `SettingsApp`'s `Group`/`Row` so the page looks like the + * other four; the two components are private to that file, and copying three + * lines of JSX beats exporting them across an import cycle. + */ +import { FolderOpen, Puzzle, Trash2 } from "lucide-react"; +import { useEffect, useState } from "react"; +import { revealItemInDir } from "@tauri-apps/plugin-opener"; + +import { createLogger } from "@/lib/logger"; + +import { pluginLoader } from "../plugin"; +import type { PluginEntry } from "../plugin"; + +const log = createLogger("plugin"); + +/** V3 made an author wait before enabling something unsigned. */ +const UNVERIFIED_WAIT = 10; + +export function ExtensionsTab() { + const loader = pluginLoader(); + const [entries, setEntries] = useState(() => loader?.list() ?? []); + const [note, setNote] = useState(null); + const [busy, setBusy] = useState(null); + const [countdown, setCountdown] = useState<{ name: string; left: number } | null>(null); + const [confirmRemove, setConfirmRemove] = useState(null); + const [dragging, setDragging] = useState(false); + + useEffect(() => { + if (!loader) return; + const update = () => setEntries(loader.list()); + update(); + return loader.subscribe(update); + }, [loader]); + + // V3's pause before an unsigned extension may be enabled: the button counts + // down, and only a second click — after it reached zero — installs trust. + const waitingFor = countdown?.name; + useEffect(() => { + if (!waitingFor) return; + const timer = window.setInterval(() => { + setCountdown((current) => (current && current.left > 0 ? { ...current, left: current.left - 1 } : current)); + }, 1000); + return () => window.clearInterval(timer); + }, [waitingFor]); + + if (!loader) { + return ( +
+ + 不支援 + +
+ ); + } + + const run = async (name: string, action: () => Promise) => { + setBusy(name); + setNote(null); + try { + await action(); + } catch (e) { + log.error(`擴充功能操作失敗:${String(e)}`); + setNote(String(e)); + } finally { + setBusy(null); + } + }; + + const install = async (file: File) => { + setBusy(""); + setNote(null); + try { + const name = await loader.installPackage(new Uint8Array(await file.arrayBuffer())); + setNote(`已安裝 ${name},啟用後即會載入。`); + } catch (e) { + setNote(`安裝失敗:${String(e)}`); + } finally { + setBusy(null); + } + }; + + return ( + <> +
+ {entries.length === 0 ? ( + + + + ) : ( + entries.map((entry) => ( + +
+ {entry.loaded && 已載入} + + {entry.verified ? "已驗證" : "未驗證"} + + + {confirmRemove === entry.name ? ( + <> + + + + ) : ( + + )} +
+
+ )) + )} +
+ + {entries.length > 0 && ( +
+ {entries.map((entry) => ( + +
+

{entry.info.description ?? "沒有說明。"}

+

作者:{entry.info.author ?? "未提供"}

+

+ 敏感度:{entry.sensitivity.description} + {entry.keyId ? `(簽章金鑰:${entry.keyId})` : ""} +

+ {entry.status && entry.status.type !== "ok" && ( +

{entry.status.msg}

+ )} + {entry.hasConfig &&

這個擴充功能有 config.yml。

} +
+
+ ))} +
+ )} + +
+ +
{ + event.preventDefault(); + setDragging(true); + }} + onDragLeave={() => setDragging(false)} + onDrop={(event) => { + event.preventDefault(); + setDragging(false); + const file = event.dataTransfer.files[0]; + if (file) void install(file); + }} + > + + {busy === "" ? "安裝中…" : dragging ? "放開以安裝" : "拖曳 .trem 套件"} +
+
+ + + +
+ + {note && ( +

+ {note} +

+ )} + + ); +} + +/** Same shell as `SettingsApp`'s `Group`. */ +function Section({ title, note, children }: { title: string; note?: string; children: React.ReactNode }) { + return ( +
+

{title}

+
{children}
+ {note &&

{note}

} +
+ ); +} + +/** Same row as `SettingsApp`'s `Row`. */ +function Line({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} diff --git a/packages/core/src/features/settings/SettingsApp.tsx b/packages/core/src/features/settings/SettingsApp.tsx index cc43f65..e01c3d2 100644 --- a/packages/core/src/features/settings/SettingsApp.tsx +++ b/packages/core/src/features/settings/SettingsApp.tsx @@ -5,7 +5,7 @@ import { Channel, invoke } from "@tauri-apps/api/core"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { disable as disableAutostart, enable as enableAutostart } from "@tauri-apps/plugin-autostart"; import { arch, type as osType, version as osVersion } from "@tauri-apps/plugin-os"; -import { BellRing, ChevronDown, Copy, Download, FolderOpen, Info, Minus, Play, SlidersHorizontal, Volume2, X } from "lucide-react"; +import { BellRing, ChevronDown, Copy, Download, FolderOpen, Info, Minus, Play, Puzzle, SlidersHorizontal, Volume2, X } from "lucide-react"; import { region, regionReady } from "@/domain/region"; import { search_loc_name } from "@/domain/utils"; @@ -19,14 +19,16 @@ import type { IdleMap, Station, TremConfig } from "@/lib/types"; import { versionLabel } from "@/lib/version"; import { StationPicker, type CityStations } from "./StationPicker"; +import { ExtensionsTab } from "./Extensions"; /** - * The settings window. Four pages, each only what is used: + * The settings window. Five pages, each only what is used: * * 一般 the station shown on the map, what an idle map shows, starting * with the system, the map's automatic zoom * 警報 which events bring the window forward, speech announcements * 音效 each sound effect, on or off + * 擴充 installed extensions: verified or not, what they may touch * 關於 version and updates, data sources, links, and the reset * * Every change is saved at once (config.rs broadcasts it to the main window). @@ -41,6 +43,7 @@ const TABS = [ { id: "general", label: "一般", icon: SlidersHorizontal }, { id: "alerts", label: "警報", icon: BellRing }, { id: "sound", label: "音效", icon: Volume2 }, + { id: "extensions", label: "擴充", icon: Puzzle }, { id: "about", label: "關於", icon: Info }, ] as const; type TabId = (typeof TABS)[number]["id"]; @@ -338,6 +341,8 @@ export function SettingsApp({ onClose }: { onClose?: () => void }) { ))} + {tab === "extensions" && } + {tab === "about" && ( <> diff --git a/packages/core/src/styles/globals.css b/packages/core/src/styles/globals.css index d3eba74..fd83174 100644 --- a/packages/core/src/styles/globals.css +++ b/packages/core/src/styles/globals.css @@ -1691,6 +1691,73 @@ border-color: #ff6b6b55; } +/* 擴充: how one extension is doing, and the target that installs one. */ +.settings-badge { + padding: 3px 8px; + border: 1px solid #ffffff1f; + border-radius: 999px; + color: #8b8b94; + font-size: 11.5px; + font-weight: 600; +} + +.settings-badge.is-ok { + color: #6ee7a8; + border-color: #6ee7a855; +} + +.settings-badge.is-warn { + color: #ffc861; + border-color: #ffc86155; +} + +.settings-extension-detail { + display: flex; + flex-direction: column; + gap: 2px; + max-width: 62%; + text-align: right; +} + +.settings-extension-detail p { + margin: 0; +} + +.settings-error { + margin: 0; + color: #ff6b6b; + font-size: 12.5px; + line-height: 1.5; +} + +.settings-extension-note { + margin: 12px 4px 0; + color: #d7d7de; + font-size: 13px; +} + +.settings-drop { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 14px; + border: 1px dashed #ffffff2e; + border-radius: 10px; + color: #8b8b94; + font-size: 13px; +} + +.settings-drop.is-active { + border-color: #6ee7a8; + background: #6ee7a814; + color: #d7d7de; +} + +.settings-drop svg { + width: 16px; + height: 16px; +} + .settings-toast { position: absolute; right: 20px; From 43b2d5b26fbbaa853287fe793c9e32bc9a64ffaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 10:04:51 +0800 Subject: [PATCH 02/16] build(plugin): add the extension signing tool and its self-test Platform: all --- tool/plugin/selftest.ts | 126 ++++++++++++++++++++++++++++++++++++++++ tool/plugin/sign.mjs | 100 +++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+) create mode 100644 tool/plugin/selftest.ts create mode 100644 tool/plugin/sign.mjs diff --git a/tool/plugin/selftest.ts b/tool/plugin/selftest.ts new file mode 100644 index 0000000..97caf6a --- /dev/null +++ b/tool/plugin/selftest.ts @@ -0,0 +1,126 @@ +#!/usr/bin/env bun +/** + * Does the signer and the host's verifier agree? + * + * `tool/plugin/sign.mjs` runs in Node; the host verifies in the webview with + * WebCrypto (`packages/core/src/features/plugin/verify.ts`, itself a port of the + * Electron build's `verify.js`). They have to agree on four things that are easy + * to get subtly wrong — which files are covered, that hashes are taken over LF + * text, that the signed message is the *original* key order of + * `JSON.stringify(fileHashes)`, and which key a `keyId` selects — so this builds + * a fixture plugin, signs it with a throwaway key, and checks both directions. + * + * bun tool/plugin/selftest.ts + */ +import { execFileSync } from "node:child_process"; +import { generateKeyPairSync } from "node:crypto"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { verifyPlugin } from "../../packages/core/src/features/plugin/verify.ts"; +import { compareVersions, parseVersion, validateVersionRequirement } from "../../packages/core/src/features/plugin/version.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const work = mkdtempSync(join(tmpdir(), "trem-plugin-selftest-")); +const plugin = join(work, "sample"); +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +let failures = 0; + +function check(label: string, ok: boolean, detail = "") { + if (!ok) failures++; + console.log(`${ok ? "PASS" : "FAIL"} ${label}${ok ? "" : ` -> ${detail}`}`); +} + +/** The plugin as the host holds it: path → bytes, straight off the disk. */ +function load(): Map { + const files = new Map(); + for (const path of ["info.json", "index.js", "signature.json", "trem.json", "lib/util.js"]) { + try { + files.set(path, new Uint8Array(readFileSync(join(plugin, path)))); + } catch { + /* not every fixture has every file */ + } + } + return files; +} + +try { + mkdirSync(join(plugin, "lib"), { recursive: true }); + // Written with CRLF on purpose: Windows tools add them, and both sides must + // hash the LF form so the same plugin verifies wherever it was unzipped. + writeFileSync( + join(plugin, "info.json"), + '{\r\n "name": "sample",\r\n "version": "1.0.0",\r\n "description": "fixture",\r\n "author": "ExpTechTW"\r\n}\r\n', + ); + writeFileSync(join(plugin, "index.js"), "module.exports = class Sample { onLoad() {} };\r\n"); + writeFileSync(join(plugin, "lib", "util.js"), "module.exports = 1;\r\n"); + writeFileSync(join(plugin, "trem.json"), '{"source":"local"}\r\n'); + writeFileSync(join(plugin, ".hidden"), "not hashed\r\n"); + + const { privateKey, publicKey } = generateKeyPairSync("rsa", { + modulusLength: 2048, + publicKeyEncoding: { type: "spki", format: "pem" }, + privateKeyEncoding: { type: "pkcs8", format: "pem" }, + }); + writeFileSync(join(work, "private.pem"), privateKey); + + execFileSync(process.execPath, [join(here, "sign.mjs"), plugin, "--key", join(work, "private.pem"), "--key-id", "test"], { + stdio: "inherit", + }); + + const keys = new Map([["test", publicKey]]); + + const signed = await verifyPlugin(load(), keys); + check("a freshly signed directory verifies", signed.valid, signed.error); + check("the signature reports its key", signed.keyId === "test", String(signed.keyId)); + check("dot-files stay out of the signature", !JSON.parse(decoder.decode(readFileSync(join(plugin, "signature.json")))).fileHashes[".hidden"]); + + const crlf = await verifyPlugin(load(), new Map()); + check("an unknown key id is reported", crlf.error === "Unknown key ID: test", String(crlf.error)); + + const text = decoder.decode(readFileSync(join(plugin, "index.js"))); + writeFileSync(join(plugin, "index.js"), `${text}\r\n// edited\r\n`); + const edited = await verifyPlugin(load(), keys); + writeFileSync(join(plugin, "index.js"), text); + check("an edited file is reported", edited.error === "Modified file: index.js", String(edited.error)); + + const extra = load(); + extra.set("extra.js", encoder.encode("// extra\n")); + const added = await verifyPlugin(extra, keys); + check("an added file is reported", added.error === "Extra file: extra.js", String(added.error)); + + const moved = load(); + moved.set("trem.json", encoder.encode('{"source":"https://example.test/x.trem"}\n')); + const relocated = await verifyPlugin(moved, keys); + check("trem.json is outside the signature", relocated.valid, relocated.error); + + const record = JSON.parse(decoder.decode(readFileSync(join(plugin, "signature.json")))) as { + fileHashes: Record; + signature: string; + keyId: string; + }; + const reordered = load(); + reordered.set( + "signature.json", + encoder.encode(JSON.stringify({ ...record, fileHashes: Object.fromEntries(Object.entries(record.fileHashes).reverse()) })), + ); + const shuffled = await verifyPlugin(reordered, keys); + check("the hash order is part of the signature", shuffled.error === "Invalid signature", String(shuffled.error)); + + const parsed = parseVersion("26.1.0-26w40a"); + check("versions parse", parsed?.major === 26 && parsed.minor === 1 && parsed.patch === 0); + check("versions compare", compareVersions("26.1.0", "26.0.9") === true && compareVersions("26.0.0", "26.1.0") === false); + check( + "requirements hold", + validateVersionRequirement("26.0.0", ">=26.0.0") && !validateVersionRequirement("25.9.0", ">=26.0.0"), + ); +} finally { + rmSync(work, { recursive: true, force: true }); +} + +console.log(failures === 0 ? "\nALL PASS" : `\n${failures} FAILED`); +process.exit(failures === 0 ? 0 : 1); diff --git a/tool/plugin/sign.mjs b/tool/plugin/sign.mjs new file mode 100644 index 0000000..0bdac0b --- /dev/null +++ b/tool/plugin/sign.mjs @@ -0,0 +1,100 @@ +#!/usr/bin/env node +/** + * Sign an extension directory. + * + * The counterpart of the host's verifier (`packages/core/src/features/plugin/verify.ts`, + * itself a port of V3's `legacy/src/js/core/verify.js`). What it writes has to + * reproduce that verifier's arithmetic exactly: + * + * - every file is hashed as **LF-normalised UTF-8 text**, sha256, lowercase hex; + * - dot-files, `signature.json` and `trem.json` are not hashed at all + * (`trem.json` records where the plugin came from and is written on install); + * - the signature is RSA-SHA256 — PKCS#1 v1.5 — over the bytes of + * `JSON.stringify(fileHashes)`, base64 encoded. The verifier parses + * `signature.json` and re-stringifies it, so the key order written here is + * the key order that gets verified. + * + * Usage: + * node tool/plugin/sign.mjs --key [--key-id ] + * + * `--key-id` names a key the host has in `/plugin-keys`; + * leaving it out signs as ExpTech, which only ExpTech's own key can do. + */ +import { createHash, createSign } from "node:crypto"; +import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { join, relative, sep } from "node:path"; + +const SKIP_HASHING = new Set(["signature.json", "trem.json"]); + +function usage(message) { + if (message) console.error(`錯誤:${message}\n`); + console.error("用法:node tool/plugin/sign.mjs --key [--key-id ]"); + process.exit(1); +} + +function parseArgs(argv) { + const out = { dir: null, key: null, keyId: undefined }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === "--key") out.key = argv[++i]; + else if (arg === "--key-id") out.keyId = argv[++i]; + else if (arg.startsWith("-")) usage(`不認識的參數 ${arg}`); + else if (out.dir) usage("只能指定一個資料夾"); + else out.dir = arg; + } + return out; +} + +/** Every path to hash, POSIX-separated and relative to `root`. */ +function walk(root, dir = root, found = []) { + for (const name of readdirSync(dir).sort()) { + // A dot-file is the author's own business, on every level. + if (name.startsWith(".")) continue; + const absolute = join(dir, name); + if (statSync(absolute).isDirectory()) { + walk(root, absolute, found); + continue; + } + const path = relative(root, absolute).split(sep).join("/"); + if (!SKIP_HASHING.has(path)) found.push(path); + } + return found; +} + +/** What the verifier hashes: `\r\n` and a lone `\r` both become `\n`. */ +function normalize(text) { + return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); +} + +const { dir, key, keyId } = parseArgs(process.argv.slice(2)); +if (!dir) usage("請指定擴充功能資料夾"); +if (!key) usage("請以 --key 指定簽章用的私鑰"); + +let manifest; +try { + manifest = JSON.parse(readFileSync(join(dir, "info.json"), "utf8")); +} catch (e) { + usage(`讀不到 ${join(dir, "info.json")}:${e.message}`); +} +if (!/^[a-z0-9-]+$/.test(manifest.name ?? "")) { + usage(`info.json 的 name 不合格式(僅允許小寫字母、數字與連字號):${manifest.name}`); +} + +const fileHashes = {}; +for (const path of walk(dir)) { + fileHashes[path] = createHash("sha256").update(normalize(readFileSync(join(dir, path), "utf8"))).digest("hex"); +} + +const message = JSON.stringify(fileHashes); +const signer = createSign("SHA256"); +signer.update(message); +signer.end(); + +const signature = signer.sign(readFileSync(key, "utf8"), "base64"); +const record = { fileHashes, signature, ...(keyId ? { keyId } : {}) }; +writeFileSync(join(dir, "signature.json"), `${JSON.stringify(record, null, 2)}\n`); + +console.log(`已簽署 ${manifest.name} ${manifest.version ?? ""}(${Object.keys(fileHashes).length} 個檔案)`); +if (!keyId) { + console.log("未指定 --key-id,簽章會以 ExpTech 官方金鑰驗證;只有官方私鑰簽得出來。"); +} From a607087d5a4f7ccdf4494c6dfcc264ebd4b60bbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 10:04:58 +0800 Subject: [PATCH 03/16] docs(plugin): describe the extension API and how to sign one Platform: desktop --- PLUGINS.md | 256 +++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 7 +- 2 files changed, 260 insertions(+), 3 deletions(-) create mode 100644 PLUGINS.md diff --git a/PLUGINS.md b/PLUGINS.md new file mode 100644 index 0000000..8932b2b --- /dev/null +++ b/PLUGINS.md @@ -0,0 +1,256 @@ +# 擴充功能開發 + +擴充功能(以前叫「插件」)讓你用 JavaScript 替 TREM-Lite 加上自己的功能 —— 自訂面板、額外的通知管道、把資料送到自己的伺服器,或改寫介面上既有的行為。 + +擴充功能**只在桌面版執行**。網頁版沒有檔案系統,設定裡的「擴充」頁只會說明這件事。 + +格式沿用 TREM-Lite 3(Electron 版)的擴充功能,欄位名稱、狀態文字與兩種進入點寫法都沒有改變,所以既有的擴充功能可以直接放進來。 + +## 快速開始 + +1. 在擴充功能資料夾底下建一個資料夾,名稱只能用小寫字母、數字與連字號(例如 `my-panel`)。 +2. 在裡面放 `info.json` 與 `index.js`。 +3. 打開 TREM-Lite 的 **設定 → 擴充**,啟用它。 + +擴充功能資料夾的位置(設定頁的「開啟資料夾」可以直接打開): + +| 系統 | 路徑 | +|---|---| +| Windows | `%APPDATA%\com.exptech.trem-lite\plugins` | +| macOS | `~/Library/Application Support/com.exptech.trem-lite/plugins` | +| Linux | `~/.config/com.exptech.trem-lite/plugins` | + +最小的 `info.json`: + +```json +{ + "name": "my-panel", + "version": "1.0.0", + "description": "在地圖旁邊加一個自己的面板", + "author": "你的名字" +} +``` + +`index.js` 有兩種寫法,兩種都可以用。 + +**類別**:建構時拿到 `ctx`,載入完成後呼叫 `onLoad`。 + +```js +module.exports = class MyPanel { + constructor(ctx) { + this.ctx = ctx; + } + + async onLoad() { + this.ctx.logger.info("你好,TREM-Lite"); + } +}; +``` + +**函式**:呼叫時拿到 `ctx`,函式回傳後才觸發 `load`。 + +```js +module.exports = (ctx) => { + ctx.on("load", () => { + ctx.logger.info("你好,TREM-Lite"); + }); + + ctx.on("ReportRelease", (ans) => { + ctx.logger.info(`地震報告 ${ans.data.id}`); + }); +}; +``` + +`load` 是保留事件,代表「這個擴充功能已經準備好了」,不會被綁到應用程式的事件匯流排上。 + +## `info.json` + +| 欄位 | 型別 | 說明 | +|---|---|---| +| `name` | string | **必填**,同時是資料夾名稱。只允許小寫字母、數字與連字號。 | +| `version` | string | 版本,供其他擴充功能的相依性比對。 | +| `description` | string | 一行說明,顯示在設定頁。 | +| `author` | string | 作者。含 `ExpTechTW` 且簽章有效時才會自動啟用。 | +| `loader` | string[] | 要載入到哪些視窗,預設 `["index"]`(主視窗)。 | +| `auto-enable` | boolean | 首次看到就啟用。只有**簽章有效**且 `author` 含 `ExpTechTW` 才生效。 | +| `dependencies` | object | 見下面的「相依性」。 | +| `sensitivity` | object | `{ "level": 0-4, "description": "..." }`,作者自行宣告,顯示在設定頁。 | + +其他欄位會原樣保留,可以放自己的設定。 + +## `ctx` + +擴充功能拿到的 `ctx` 物件: + +| 成員 | 說明 | +|---|---| +| `ctx.logger` | 寫進應用程式日誌的 logger(`trace`/`debug`/`info`/`warn`/`error`)。 | +| `ctx.Logger` | `getLogger(scope)` 取得其他範圍的 logger,`getInstance()` 取得預設的那個。 | +| `ctx.events` | 應用程式的事件匯流排,等於 `ctx.TREM.variable.events`。 | +| `ctx.on(event, handler)` | 註冊事件。載入成功後才會真的接到匯流排上。 | +| `ctx.TREM` | 見下面的「`TREM`」。 | +| `ctx.MixinManager` | 注入既有方法,見下面的「`MixinManager`」。 | +| `ctx.utils.path` | Node 的 `path`(POSIX 語意,分隔字元是 `/`)。 | +| `ctx.utils.fs` | 記憶體中的 `fs`,見下面的「檔案系統」。 | +| `ctx.require(id)` | 載入自己資料夾裡的模組,見下面的「模組」。 | +| `ctx.maplibregl` | MapLibre GL 的模組,用來加圖層或事件。 | +| `ctx.info.name` | 這個擴充功能的名稱。 | +| `ctx.info.pluginDir` | 擴充功能資料夾的**根目錄**(`/plugins`),與舊版相同。 | +| `ctx.info.originalPath` | 同上。 | + +### `TREM` + +| 成員 | 說明 | +|---|---| +| `TREM.variable` | 即時資料:`data`(`rts`、`intensity`、`report`、`eew`、`lpgm`)、`map`、`station`、`time`、`play_mode`、`replay`、`tts`、`cache`,以及 `events`。 | +| `TREM.constant` | 共用常數:`COLOR`、`URL`(`API`、`LB`、`REPLAY`)、`HTTP_TIMEOUT`、`EEW_AUTHOR`、`REPORT_LIMIT`、`MAP`、`SHOW_REPORT`、`INTENSITY_LIST`。 | +| `TREM.class.AudioManager` | 播放音效。 | + +讀 `TREM.variable.data.rts` 拿到的是當下的物件,會由應用程式持續更新;不要在載入時把它存起來。 + +### `MixinManager` + +改寫既有方法的行為: + +```js +const id = ctx.MixinManager.inject(SomeClass, "someMethod", function () { + // 這段原始碼會被插進 someMethod 裡面, + // 可以讀到它的參數、區域變數與 this + ctx.logger.info(this.someProperty); +}, "start"); +``` + +`inject(targetClass, methodName, handler, position)` 的 `position` 可以是 `"start"`、`"end"`(預設)或行號(方法主體的第幾行,從 1 開始)。`remove(methodName, id)` 還原,`clear(methodName)` 移除全部。回傳的 `id` 是 `Symbol`。 + +注入是**文字層級**的:handler 的**函式主體**會被拼進方法的原始碼,再用 `new Function` 重建整個方法,所以 handler 不是在一個獨立的閉包裡被呼叫,也沒有 `next` 可以呼叫原方法。目標方法必須是一般函式(`toString()` 讀得出參數與大括號),箭頭函式或類別簡寫會在注入時擲出錯誤。 + +### `TREM.variable.events` 與 `ctx.on` + +兩者都是同一個 `mitt` 匯流排。`ctx.events.emit(name, payload)` 可以自己發事件給其他擴充功能。 + +## 事件 + +每個事件的 payload 多半是 `{ data, ... }`。`DataRts` 的 `data` 可能是 `null`(重置)。 + +| 事件 | `data` | +|---|---| +| `MapLoad` | 無 | +| `FocusLockChange` | `boolean` | +| `EewDisplayUpdate` | 無 | +| `InternetErrorChange` | `boolean` | +| `UpdateReady` | 版本字串 | +| `MainWindowHidden` | `boolean` | +| `DataRts` | `RtsData \| null` | +| `DataModeReset` | 無 | +| `EewRelease` / `EewUpdate` / `EewEnd` / `EewAlert` / `EewCancel` | `EewData` | +| `EewNewAreaAlert` | `{ city_alert_list: string[] }` | +| `IntensityRelease` / `IntensityUpdate` | `{ id, max, area }` | +| `IntensityEnd` | — | +| `LpgmRelease` | `{ id, time, list }` | +| `ReportRelease` | `ReportListItem`(修訂時多一個 `update: true`) | +| `ReportSpeechEnd` | `{ id }` | +| `ReportListUpdate` | 無 | +| `ReplayStateChange` | `{ active, reportId? }` | +| `RtsPga1` / `RtsPga2` / `RtsShindo0` / `RtsShindo1` / `RtsShindo2` | 無 | +| `TsunamiRelease` | — | + +## 檔案系統 + +擴充功能看到的是**記憶體中的虛擬目錄**,根目錄是 `/plugins`,鏡射磁碟上的實際內容: + +- 讀取是同步的(`fs.readFileSync`),內容在啟動時一次讀進來。 +- 寫入會轉送到 Rust,一次一個檔案。`fs.writeFileSync`、`appendFileSync`、`unlinkSync`、`rmSync`、`mkdirSync`、`copyFileSync`、`renameSync` 都支援。 +- 相對路徑以**自己的資料夾**為基準:`fs.readFileSync("config.yml")` 讀的是 `<自己的資料夾>/config.yml`。`ctx.info.pluginDir` 仍然是根目錄,所以舊版的 `path.join(ctx.info.pluginDir, ctx.info.name, ...)` 也照樣可用。 +- 只能寫自己資料夾裡的檔案,寫到別的擴充功能會被拒絕。 +- `fs-extra` 的 `readJsonSync` / `writeJsonSync` / `outputJsonSync`、`fs.promises` 與 `existsSync`、`statSync`、`readdirSync` 都在。 +- `fs.watch` 是空殼(不會有事件);`fs.createReadStream` / `createWriteStream` 會擲出錯誤,請改用同步版本。 +- `path` 是 POSIX 語意:分隔字元固定是 `/`。 + +## 模組 + +用 `require` 或 `ctx.require` 載入自己資料夾裡的檔案,支援 `.js`、`.cjs`、`.json` 與 `index.js`: + +```js +const { helper } = ctx.require("./lib/helper"); +const other = ctx.require("../other-plugin/util"); // 另一個擴充功能 +``` + +**可以**用:`path`、`fs`、`fs-extra`、`buffer`、`process`、`events`、`util`、`os`、`url`、`crypto`。 + +**不可以用**,會拿到明確的錯誤訊息: + +| 模組 | 訊息 | +|---|---| +| `electron`、`@electron/remote` | 擴充功能不能使用 Electron API。 | +| `child_process` | 擴充功能不能啟動其他程式。 | +| `worker_threads` | 擴充功能不能建立 worker。 | +| `net` / `http` / `https` / `axios` | 擴充功能不能直接開 socket,請改用 `fetch`。 | +| 其他 npm 套件 | 擴充功能不能載入 npm 套件,請改用相對路徑或 `ctx.require`。 | + +抓網路資料請用標準的 `fetch`,並以 `ctx.TREM.constant.URL` 取得官方端點。 + +## 相依性 + +```json +{ + "dependencies": { + "trem": ">= 26.1.0", + "other-plugin": ">= 1.2.0" + } +} +``` + +`trem` 比對的是應用程式版本,其他鍵是**其他擴充功能的名稱**。支援 `>=`、`<=`、`>`、`<`、`==`,也可以用空白分隔多個條件。條件不成立時擴充功能不會載入,設定頁會顯示原因。 + +載入順序會依相依性排序,被依賴的會先載入。 + +## 敏感度 + +`info.json` 的 `sensitivity.level` 只是作者自行的宣告,用來讓使用者知道這個擴充功能會碰什麼: + +| 等級 | 說明 | +|---|---| +| 4 | 極高敏感度 - 包含系統核心 API 存取權限 | +| 3 | 高敏感度 - 包含注入或檔案系統存取權限 | +| 2 | 中等敏感度 - 包含事件權限 | +| 1 | 低敏感度 - 包含日誌/元數據存取權限 | +| 0 | 無敏感操作 | + +沒填 `description` 時,設定頁會用上表的文字。 + +## 簽章與發布 + +未簽章的擴充功能可以安裝,但設定頁會標示「未驗證」,啟用前要等 10 秒的確認倒數。 + +簽章沿用舊版的格式:對每個檔案的內容做 SHA-256,把「相對路徑 → 雜湊」的物件用 RSA-SHA256 簽起來。簽章工具在 `tool/plugin/sign.mjs`: + +```bash +node tool/plugin/sign.mjs ./my-panel --key private.pem +node tool/plugin/sign.mjs ./my-panel --key private.pem --key-id my-key +``` + +幾個必須知道的細節: + +- 雜湊前會先把換行統一成 `\n`(CRLF 與 CR 都會轉換),所以 Git 的換行設定不影響簽章。 +- 簽的是 `JSON.stringify(fileHashes)` 這串文字,鍵的順序是簽章的一部分。 +- 開頭是 `.` 的檔案/資料夾、`signature.json` 與 `trem.json` 不算在簽章裡。 +- 產生出來的 `signature.json` 有 `fileHashes`、`signature` 與可選的 `keyId`。 +- `keyId` 省略或填 `official` 時使用 ExpTech 的官方金鑰;其他值會對應到 `<設定資料夾>/plugin-keys/.pem`,讓第三方用自己的金鑰簽章。使用者要自己放入對應的公開金鑰。 + +打包成 `.trem`(就是一個 zip,`info.json` 在壓縮檔根目錄或往下一層都可以;`__MACOSX/` 與 `.DS_Store` 會被忽略)後,可以拖進設定頁的「安裝」區塊。安裝會**整包取代**既有的同名擴充功能 —— 舊版殘留的檔案會讓下一次簽章檢查回報多餘的檔案。 + +簽章工具本身有自我測試: + +```bash +bun tool/plugin/selftest.ts +``` + +它會產生一組免洗金鑰與範例擴充功能,驗證「簽完可以通過驗證」、「改一個字會被抓到」、「多一個檔案會被抓到」、「金鑰順序會被檢查」等情況。 + +## 與 TREM-Lite 3 的差異 + +- **沒有 Electron**:`electron` 與 `@electron/remote` 都不能用,視窗控制請改用 `ctx.TREM` 或設定頁。 +- **沒有 Node 的網路模組**:`http`、`https`、`net` 都不可用,請用 `fetch`。 +- **`TREM.class` 只剩 `AudioManager`**:舊版還有 `DataManager`、`ReportManager`、`FocusManager`、`EewAreaManager`、`BoxManager`、`ReplayControler`、`WindowControler`,這些工作在 v4 由 Rust 與 `packages/core/src/features/` 負責,資料請從 `TREM.variable` 與事件取得。 +- **`ctx.info.name` 是新增的**:不用再從 `info.pluginDir` 推自己的名字。 +- **`require` 只認相對路徑與內建模組**:不會再去 Node 的解析路徑裡找套件。 diff --git a/README.md b/README.md index 57cb09c..49ba00f 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ [![CI](https://img.shields.io/github/actions/workflow/status/ExpTechTW/TREM-Lite/ci.yml?branch=main&label=CI)](https://github.com/ExpTechTW/TREM-Lite/actions/workflows/ci.yml) [![Discord](https://img.shields.io/discord/926545182407688273?logo=discord&logoColor=white&label=Discord&color=5865F2)](https://discord.gg/5dbHqV8ees) -[官網](https://exptech.dev/trem) • [網頁版](https://exptechtw.github.io/TREM-Lite/) • [更新日誌](https://github.com/ExpTechTW/TREM-Lite/releases) • [Commit 規則](commit.md) +[官網](https://exptech.dev/trem) • [網頁版](https://exptechtw.github.io/TREM-Lite/) • [更新日誌](https://github.com/ExpTechTW/TREM-Lite/releases) • [擴充功能開發](PLUGINS.md) • [Commit 規則](commit.md) @@ -31,6 +31,7 @@ TREM(Taiwan Real-time Earthquake Monitoring,臺灣即時地震監測)是 | **通知與子母畫面** | 主視窗隱藏時,以系統通知和子母畫面小視窗提醒 | | **常駐系統匣** | 關閉視窗後持續監測,也可以隨開機在背景啟動 | | **自動更新** | 在背景下載新版本,下次啟動時套用,不會打斷正在使用的視窗 | +| **擴充功能** | 安裝社群開發的擴充功能,替 TREM-Lite 加上自己的功能(僅桌面版) | ## 下載 @@ -48,7 +49,7 @@ Linux 在下載的資料夾執行 `sudo apt install ./<檔名>.deb`,需要的 結尾是 `.sig` 或 `.app.tar.gz` 的檔案是自動更新用的,不需要下載。 -不想安裝的話,可以直接用 **[網頁版](https://exptechtw.github.io/TREM-Lite/)**。網頁版有地圖、即時震度、強震即時警報、地震報告和語音播報;音效、系統通知、子母畫面、系統匣常駐與自動更新只有桌面版提供。 +不想安裝的話,可以直接用 **[網頁版](https://exptechtw.github.io/TREM-Lite/)**。網頁版有地圖、即時震度、強震即時警報、地震報告和語音播報;音效、系統通知、子母畫面、系統匣常駐、自動更新與擴充功能只有桌面版提供。 ### 版本命名 @@ -97,7 +98,7 @@ git config core.hooksPath .githooks # 啟用 commit 規則檢查 | `packages/core` | 桌面版與網頁版共用的前端:React、MapLibre、地震資料處理 | | `apps/desktop` | Tauri 桌面版。Rust 負責音效、HTTP 代理與快取、自動更新、設定與視窗 | | `apps/web` | 網頁版(GitHub Pages) | -| `tool/` | commit 規則檢查、版本號與發布說明的產生 | +| `tool/` | commit 規則檢查、版本號與發布說明的產生、擴充功能簽章工具 | | `legacy/` | 舊版 Electron 原始碼,僅作為移植參照,不再修改 | > [!NOTE] From 567d87b22c3b1ef7814aad0cc1d2a290475a25db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 10:47:59 +0800 Subject: [PATCH 04/16] fix(plugin): list extensions in the settings window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 擴充 page is rendered by the settings webview, and that webview never started the extension host, so `pluginLoader()` was null and the page fell back to "擴充功能只能在桌面版執行。" on the desktop build. The settings window now builds the same loader in a management mode: it scans, verifies, installs, removes and records what is enabled, but starts nothing — a plugin reaches for the map, the station feed and the audio engine, and those belong to the main window. Enabling one therefore takes effect at the next start, which is what V3 did as well, and the page says so. Platform: desktop Fix(zh-Hant): 設定 → 擴充 不再顯示「不支援」,會列出已安裝的擴充功能 Fix(en-US): the extensions page lists installed extensions instead of reporting the desktop build as unsupported --- packages/core/src/features/plugin/host.ts | 58 ++++++++++++++++--- packages/core/src/features/plugin/index.ts | 18 +++++- .../core/src/features/settings/Extensions.tsx | 4 +- packages/core/src/settings.tsx | 6 ++ 4 files changed, 75 insertions(+), 11 deletions(-) diff --git a/packages/core/src/features/plugin/host.ts b/packages/core/src/features/plugin/host.ts index ca1d4f5..cc533a4 100644 --- a/packages/core/src/features/plugin/host.ts +++ b/packages/core/src/features/plugin/host.ts @@ -49,6 +49,8 @@ const NAME_PATTERN = /^[a-z0-9-]+$/; /** V3's wording, kept verbatim: the 擴充 page greps for it. */ const STATUS_INIT_FAILED = "初始化失敗,請聯繫擴充作者。"; const STATUS_DISABLED = "未啟用。"; +/** The 擴充 page records the choice; the main window loads it at the next boot. */ +const STATUS_RESTART = "將於下次啟動時載入。"; export function getSensitivityDescription(level: number): string { switch (level) { @@ -102,8 +104,19 @@ interface InstallOptions { replace?: boolean; } +/** + * 設定 → 擴充 is a second webview. It lists, verifies, installs and removes; the + * plugins themselves belong to the main window, where the map and the data feed + * are. `management` is how that window keeps this one from starting anything. + */ +export interface LoaderOptions { + management?: boolean; +} + export class PluginLoader { private readonly type: string; + /** Built by 設定 → 擴充: read, verify and record, but never run. */ + private readonly management: boolean; /** Rows the 擴充 page shows, keyed by plugin name. */ private entries = new Map(); private running = new Map(); @@ -113,11 +126,17 @@ export class PluginLoader { private started = false; /** The app's own version, as `dependencies.trem` is compared against. */ tremVersion = ""; - /** `/plugins` — where the tree on disk actually is. */ - rootPath = PLUGIN_ROOT; + /** + * `/plugins` — where the tree on disk actually is. + * + * Empty until `scan()` has asked: `/plugins` is the sandbox's name for the + * same place, not a path anything outside the plugin runtime can open. + */ + rootPath = ""; - constructor(type = "index") { + constructor(type = "index", options: LoaderOptions = {}) { this.type = type; + this.management = options.management ?? false; } // -- reading ------------------------------------------------------------- @@ -211,8 +230,8 @@ export class PluginLoader { verified: verified.valid, verifyError: verified.error, keyId: verified.keyId, - enabled: false, - loaded: false, + enabled: this.readEnabled().includes(name), + loaded: this.management && this.readLoaded().includes(name), status: verified.valid ? null : { type: "warn", msg: verified.error ?? "未發現有效簽名。" }, sensitivity: { level, @@ -237,6 +256,25 @@ export class PluginLoader { localStorage.setItem(ENABLED_KEY, JSON.stringify([...new Set(names)])); } + /** + * What the *main* window left behind under V3's `loaded-plugins` key. + * + * The settings window runs no plugin of its own, so 已載入 cannot come from + * this process; it comes from that key — which is how V3's + * `setting/plugin_list.js` learned it too. + */ + private readLoaded(): string[] { + try { + const raw = JSON.parse(localStorage.getItem(LOADED_KEY) ?? "[]") as unknown; + if (!Array.isArray(raw)) return []; + return raw + .map((item) => (item as LoadedPlugin | undefined)?.name) + .filter((name): name is string => typeof name === "string"); + } catch { + return []; + } + } + isEnabled(name: string): boolean { return this.entries.get(name)?.enabled ?? false; } @@ -249,7 +287,11 @@ export class PluginLoader { if (enabled) { this.writeEnabled([...this.readEnabled(), name]); entry.enabled = true; - await this.start(name); + if (this.management) { + entry.status = { type: "warn", msg: STATUS_RESTART }; + } else { + await this.start(name); + } } else { this.writeEnabled(this.readEnabled().filter((item) => item !== name)); entry.enabled = false; @@ -581,8 +623,8 @@ export class PluginLoader { /** One loader for the app, created on first use. */ let instance: PluginLoader | null = null; -export function createPluginLoader(type = "index"): PluginLoader { - instance ??= new PluginLoader(type); +export function createPluginLoader(type = "index", options: LoaderOptions = {}): PluginLoader { + instance ??= new PluginLoader(type, options); return instance; } diff --git a/packages/core/src/features/plugin/index.ts b/packages/core/src/features/plugin/index.ts index 244bf55..8bae52f 100644 --- a/packages/core/src/features/plugin/index.ts +++ b/packages/core/src/features/plugin/index.ts @@ -22,7 +22,23 @@ export function initPlugins(): void { }); } +/** + * 設定 → 擴充 — the same loader, without the loading. + * + * The settings window is a second webview: it lists the extensions, verifies + * them, installs, removes and records what is enabled, but it must not start + * one — a plugin reaches for the map, the station feed and the audio engine, + * and those live in the main window. V3 read `enabled-plugins` at boot as well, + * so a change made here takes effect the next time the app starts. + */ +export function initPluginAdmin(): void { + const loader = createPluginLoader("index", { management: true }); + loader.scan().catch((e: unknown) => { + log.error(`擴充功能清單讀取失敗:${String(e)}`); + }); +} + export { createPluginLoader, pluginLoader, PluginLoader, getSensitivityDescription } from "./host"; -export type { PluginContext } from "./host"; +export type { LoaderOptions, PluginContext } from "./host"; export { MixinManager } from "./mixin"; export type { LoadedPlugin, PluginEntry, PluginInfo } from "./types"; diff --git a/packages/core/src/features/settings/Extensions.tsx b/packages/core/src/features/settings/Extensions.tsx index 7d48927..6d0b397 100644 --- a/packages/core/src/features/settings/Extensions.tsx +++ b/packages/core/src/features/settings/Extensions.tsx @@ -81,7 +81,7 @@ export function ExtensionsTab() { setNote(null); try { const name = await loader.installPackage(new Uint8Array(await file.arrayBuffer())); - setNote(`已安裝 ${name},啟用後即會載入。`); + setNote(`已安裝 ${name},啟用後將於下次啟動載入。`); } catch (e) { setNote(`安裝失敗:${String(e)}`); } finally { @@ -205,7 +205,7 @@ export function ExtensionsTab() { - diff --git a/packages/core/src/settings.tsx b/packages/core/src/settings.tsx index 2b5edec..47bbf61 100644 --- a/packages/core/src/settings.tsx +++ b/packages/core/src/settings.tsx @@ -3,8 +3,14 @@ import ReactDOM from "react-dom/client"; import { reactRootErrorHandlers } from "@/lib/logger"; import "@/styles/globals.css"; +import { initPluginAdmin } from "@/features/plugin"; import { SettingsApp } from "@/features/settings/SettingsApp"; +// The main window owns the extensions; this one only lists them and records +// what it changed. V3 read `enabled-plugins` at boot too, so a change here takes +// effect the next time the app starts. +initPluginAdmin(); + ReactDOM.createRoot(document.getElementById("root")!, reactRootErrorHandlers).render( From 765b558514b6890ee5b7dca15dd28facf906c798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 11:03:28 +0800 Subject: [PATCH 05/16] fix(plugin): read extensions the way they are published MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The published manifests were checked against the plugin store instead of against this loader: `description` is a locale table (`{ "zh_tw": … }`) and `author` is an array, so rendering them straight into React would have thrown for every real plugin. `resources` and `link` are typed as well now. A `.trem` zipped on Windows — `Compress-Archive`, 「傳送到 → 壓縮的資料夾」 — names its entries with `\`, which the unpacker did not accept as a separator, so such an archive was rejected as missing its own `info.json`. Unpacking moved to `package.ts`, which normalises the separators, and the self-test covers both a wrapped and a flat archive. Platform: desktop Fix(zh-Hant): 修正擴充功能的說明與作者顯示,並支援 Windows 壓縮工具製作的安裝包 Fix(en-US): Read the shapes the plugin store actually publishes and accept .trem archives made by Windows zip tools --- PLUGINS.md | 16 +++-- packages/core/src/features/plugin/host.ts | 39 +++--------- packages/core/src/features/plugin/index.ts | 3 +- packages/core/src/features/plugin/package.ts | 60 +++++++++++++++++++ packages/core/src/features/plugin/types.ts | 39 ++++++++++-- .../core/src/features/settings/Extensions.tsx | 6 +- tool/plugin/selftest.ts | 38 ++++++++++++ 7 files changed, 157 insertions(+), 44 deletions(-) create mode 100644 packages/core/src/features/plugin/package.ts diff --git a/PLUGINS.md b/PLUGINS.md index 8932b2b..92a2396 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -26,8 +26,8 @@ { "name": "my-panel", "version": "1.0.0", - "description": "在地圖旁邊加一個自己的面板", - "author": "你的名字" + "description": { "zh_tw": "在地圖旁邊加一個自己的面板" }, + "author": ["你的名字"] } ``` @@ -69,15 +69,19 @@ module.exports = (ctx) => { |---|---|---| | `name` | string | **必填**,同時是資料夾名稱。只允許小寫字母、數字與連字號。 | | `version` | string | 版本,供其他擴充功能的相依性比對。 | -| `description` | string | 一行說明,顯示在設定頁。 | -| `author` | string | 作者。含 `ExpTechTW` 且簽章有效時才會自動啟用。 | +| `description` | string \| object | 一行說明,顯示在設定頁。物件型式為各語言的對照表,例如 `{ "zh_tw": "…", "zh-Hant": "…" }`。 | +| `author` | string \| string[] | 作者,可寫成陣列。含 `ExpTechTW` 且簽章有效時才會自動啟用。 | | `loader` | string[] | 要載入到哪些視窗,預設 `["index"]`(主視窗)。 | | `auto-enable` | boolean | 首次看到就啟用。只有**簽章有效**且 `author` 含 `ExpTechTW` 才生效。 | | `dependencies` | object | 見下面的「相依性」。 | | `sensitivity` | object | `{ "level": 0-4, "description": "..." }`,作者自行宣告,顯示在設定頁。 | +| `resources` | string[] | 授權條款識別碼,例如 `["AGPL-3.0"]`。 | +| `link` | string | 專案首頁。 | 其他欄位會原樣保留,可以放自己的設定。 +> 官方擴充功能的 `description` 是各語言的物件、`author` 是陣列,兩種寫法都支援;設定頁顯示時會挑 `zh-Hant`(其次 `zh_tw`、`en`)。 + ## `ctx` 擴充功能拿到的 `ctx` 物件: @@ -237,7 +241,9 @@ node tool/plugin/sign.mjs ./my-panel --key private.pem --key-id my-key - 產生出來的 `signature.json` 有 `fileHashes`、`signature` 與可選的 `keyId`。 - `keyId` 省略或填 `official` 時使用 ExpTech 的官方金鑰;其他值會對應到 `<設定資料夾>/plugin-keys/.pem`,讓第三方用自己的金鑰簽章。使用者要自己放入對應的公開金鑰。 -打包成 `.trem`(就是一個 zip,`info.json` 在壓縮檔根目錄或往下一層都可以;`__MACOSX/` 與 `.DS_Store` 會被忽略)後,可以拖進設定頁的「安裝」區塊。安裝會**整包取代**既有的同名擴充功能 —— 舊版殘留的檔案會讓下一次簽章檢查回報多餘的檔案。 +打包成 `.trem`(就是一個 zip,`info.json` 在壓縮檔根目錄或往下一層都可以;`__MACOSX/` 與 `.DS_Store` 會被忽略)後,可以拖進設定頁的「安裝」區塊。Windows 內建的「傳送到 → 壓縮的資料夾」與 PowerShell 的 `Compress-Archive` 都可以直接用,最後把副檔名改成 `.trem` 即可;那些工具寫入的路徑分隔符號會在解壓時正規化。安裝會**整包取代**既有的同名擴充功能 —— 舊版殘留的檔案會讓下一次簽章檢查回報多餘的檔案。 + +沒有簽章的擴充功能還是可以安裝與執行,但設定頁會標成「未驗證」,啟用前要等十秒倒數 —— 這是舊版就有的警告,不是錯誤。 簽章工具本身有自我測試: diff --git a/packages/core/src/features/plugin/host.ts b/packages/core/src/features/plugin/host.ts index cc533a4..9577f3f 100644 --- a/packages/core/src/features/plugin/host.ts +++ b/packages/core/src/features/plugin/host.ts @@ -12,7 +12,6 @@ * Load order, verbatim from V3: scan → auto-enable → dependency order → start. */ import { getVersion } from "@tauri-apps/api/app"; -import { unzipSync } from "fflate"; import maplibregl from "maplibre-gl"; import { events } from "@/lib/events"; @@ -28,10 +27,11 @@ import { removePlugin, writePluginFile, } from "./bridge"; -import { encodeBase64 } from "./base64"; +import { NAME_PATTERN, parsePackage } from "./package"; import { MixinManager } from "./mixin"; import { PLUGIN_ROOT, PluginRuntime, PluginTree } from "./sandbox"; import { tremGlobal } from "./trem"; +import { authorNames, localizedText } from "./types"; import type { LoadedPlugin, PluginEntry, PluginFile, PluginInfo, PluginStatus } from "./types"; import { getVersionPrefixString, validateVersionRequirement } from "./version"; import { verifyPlugin as verify } from "./verify"; @@ -43,9 +43,6 @@ const ENABLED_KEY = "enabled-plugins"; /** What this host loaded, in V3's shape, for tooling that reads it. */ const LOADED_KEY = "loaded-plugins"; -/** `info.json` names are lowercase, hyphenated, and nothing else. */ -const NAME_PATTERN = /^[a-z0-9-]+$/; - /** V3's wording, kept verbatim: the 擴充 page greps for it. */ const STATUS_INIT_FAILED = "初始化失敗,請聯繫擴充作者。"; const STATUS_DISABLED = "未啟用。"; @@ -235,7 +232,7 @@ export class PluginLoader { status: verified.valid ? null : { type: "warn", msg: verified.error ?? "未發現有效簽名。" }, sensitivity: { level, - description: info.sensitivity?.description ?? getSensitivityDescription(level), + description: localizedText(info.sensitivity?.description) ?? getSensitivityDescription(level), }, hasConfig: files.has("config.yml"), }; @@ -319,8 +316,8 @@ export class PluginLoader { const enabled = new Set(this.readEnabled()); for (const entry of this.entries.values()) { - const author = entry.info.author ?? ""; - if (entry.info["auto-enable"] === true && author.includes("ExpTechTW") && entry.verified) { + const byExptech = authorNames(entry.info.author).some((name) => name.includes("ExpTechTW")); + if (entry.info["auto-enable"] === true && byExptech && entry.verified) { enabled.add(entry.name); } } @@ -554,30 +551,12 @@ export class PluginLoader { * most zips of a folder look like; that wrapper is stripped. */ async installPackage(data: Uint8Array, name?: string): Promise { - const archive = unzipSync(data); - const paths = Object.keys(archive).filter( - (path) => !path.endsWith("/") && !path.startsWith("__MACOSX/") && !path.endsWith(".DS_Store"), - ); - const manifestPath = paths.find((path) => path === "info.json") ?? paths.find((path) => path.endsWith("/info.json")); - if (!manifestPath) throw new Error("套件裡找不到 info.json。"); - - let info: PluginInfo; - try { - info = JSON.parse(new TextDecoder().decode(archive[manifestPath])) as PluginInfo; - } catch (e) { - throw new Error(`info.json 不是合法的 JSON:${String(e)}`, { cause: e }); - } - const plugin = name ?? info.name; - if (!plugin || !NAME_PATTERN.test(plugin)) { + const parsed = parsePackage(data); + const plugin = name ?? parsed.name; + if (!NAME_PATTERN.test(plugin)) { throw new Error("info.json 的 name 不合格式(僅允許小寫字母、數字與連字號)。"); } - - const prefix = manifestPath === "info.json" ? "" : `${manifestPath.slice(0, -"info.json".length)}`; - const files: PluginFile[] = paths.map((path) => ({ - path: path.slice(prefix.length), - data: encodeBase64(archive[path]), - })); - await this.install(plugin, files, { replace: true }); + await this.install(plugin, parsed.files, { replace: true }); return plugin; } diff --git a/packages/core/src/features/plugin/index.ts b/packages/core/src/features/plugin/index.ts index 8bae52f..c15f919 100644 --- a/packages/core/src/features/plugin/index.ts +++ b/packages/core/src/features/plugin/index.ts @@ -41,4 +41,5 @@ export function initPluginAdmin(): void { export { createPluginLoader, pluginLoader, PluginLoader, getSensitivityDescription } from "./host"; export type { LoaderOptions, PluginContext } from "./host"; export { MixinManager } from "./mixin"; -export type { LoadedPlugin, PluginEntry, PluginInfo } from "./types"; +export { authorNames, localizedText } from "./types"; +export type { LoadedPlugin, LocalizedText, PluginEntry, PluginInfo } from "./types"; diff --git a/packages/core/src/features/plugin/package.ts b/packages/core/src/features/plugin/package.ts new file mode 100644 index 0000000..af1fdd6 --- /dev/null +++ b/packages/core/src/features/plugin/package.ts @@ -0,0 +1,60 @@ +/** + * Reading a `.trem` — a zip of a plugin directory. + * + * Zip entry names are supposed to be `/`-separated, but the archives Windows + * itself produces — 「傳送到 → 壓縮的資料夾」 and PowerShell's `Compress-Archive` — + * write `\`. Those install too, so names are normalised on the way in. The zip + * may also wrap everything in one top-level folder, which is what zipping a + * folder looks like; that wrapper is stripped here. + * + * Kept apart from `host.ts` so it can be tested: it touches no browser API and + * no bridge, only the bytes. + */ +import { unzipSync } from "fflate"; + +import { encodeBase64 } from "./base64"; +import type { PluginFile, PluginInfo } from "./types"; + +/** Re-exported for `tool/plugin/selftest.ts`, which lives outside the package. */ +export { zipSync } from "fflate"; + +/** `info.json` names are lowercase, hyphenated, and nothing else. */ +export const NAME_PATTERN = /^[a-z0-9-]+$/; + +export interface ParsedPackage { + /** The name from `info.json`, before any override. */ + name: string; + info: PluginInfo; + /** Every file, wrapper stripped, POSIX paths relative to the plugin folder. */ + files: PluginFile[]; +} + +/** Unpack a `.trem` into the files the host would write to disk. */ +export function parsePackage(data: Uint8Array): ParsedPackage { + const entries = Object.entries(unzipSync(data)) + .map(([entry, bytes]) => ({ path: entry.replace(/\\/g, "/").replace(/^\.\//, ""), bytes })) + .filter( + ({ path }) => path && !path.endsWith("/") && !path.startsWith("__MACOSX/") && !path.endsWith(".DS_Store"), + ); + + const manifest = + entries.find(({ path }) => path === "info.json") ?? entries.find(({ path }) => path.endsWith("/info.json")); + if (!manifest) throw new Error("套件裡找不到 info.json。"); + + let info: PluginInfo; + try { + info = JSON.parse(new TextDecoder().decode(manifest.bytes)) as PluginInfo; + } catch (e) { + throw new Error(`info.json 不是合法的 JSON:${String(e)}`, { cause: e }); + } + if (!info.name || !NAME_PATTERN.test(info.name)) { + throw new Error("info.json 的 name 不合格式(僅允許小寫字母、數字與連字號)。"); + } + + const prefix = manifest.path === "info.json" ? "" : manifest.path.slice(0, -"info.json".length); + return { + name: info.name, + info, + files: entries.map(({ path, bytes }) => ({ path: path.slice(prefix.length), data: encodeBase64(bytes) })), + }; +} diff --git a/packages/core/src/features/plugin/types.ts b/packages/core/src/features/plugin/types.ts index 8f34c01..6c58bee 100644 --- a/packages/core/src/features/plugin/types.ts +++ b/packages/core/src/features/plugin/types.ts @@ -6,12 +6,19 @@ * so this file describes what exists rather than what would be tidier. */ +/** + * V3 manifests ship text either as a plain string or as a table of locales — + * the published plugins carry `description: { "zh_tw": …, "zh-Hant": … }`. + */ +export type LocalizedText = string | Record; + /** `info.json` — the manifest every plugin ships. */ export interface PluginInfo { name: string; version: string; - description?: string; - author?: string; + description?: LocalizedText; + /** A string, or a list of them: the store lists authors as an array. */ + author?: LocalizedText | LocalizedText[]; /** Which host this plugin runs in; `index` is the main window. */ loader?: string[]; /** Enable on first sight. Honoured only for a verified ExpTechTW plugin. */ @@ -19,10 +26,32 @@ export interface PluginInfo { /** `trem` is the host's version; every other key is another plugin's name. */ dependencies?: Record; /** What the plugin touches, as declared by its author. */ - sensitivity?: { level?: number; description?: string }; + sensitivity?: { level?: number; description?: LocalizedText }; + /** Licence identifiers, as the plugin store lists them. */ + resources?: string[]; + /** The plugin's home page, as the plugin store lists it. */ + link?: string; [key: string]: unknown; } +/** This locale's wording, out of whatever shape the manifest used. */ +export function localizedText(value: LocalizedText | undefined): string | undefined { + if (typeof value === "string") return value || undefined; + if (!value) return undefined; + for (const key of ["zh-Hant", "zh_tw", "zh-TW", "zh-Hans", "zh_cn", "en", "en-US"]) { + const text = value[key]; + if (typeof text === "string" && text) return text; + } + return Object.values(value).find((text) => typeof text === "string" && text) || undefined; +} + +/** The authors, however the manifest spelled them. */ +export function authorNames(value: LocalizedText | LocalizedText[] | undefined): string[] { + if (!value) return []; + const list = Array.isArray(value) ? value : [value]; + return list.map((item) => localizedText(item)).filter((name): name is string => Boolean(name)); +} + /** `signature.json` — written by `tool/plugin/sign.mjs`. */ export interface PluginSignature { /** Relative POSIX path → SHA-256 hex of the LF-normalised text. */ @@ -87,8 +116,8 @@ export interface PluginEntry { export interface LoadedPlugin { name: string; version: string; - description?: string; - author?: string; + description?: LocalizedText; + author?: LocalizedText | LocalizedText[]; ctxDependencies: string[]; sensitivity: { level: number; description: string }; } diff --git a/packages/core/src/features/settings/Extensions.tsx b/packages/core/src/features/settings/Extensions.tsx index 6d0b397..740930e 100644 --- a/packages/core/src/features/settings/Extensions.tsx +++ b/packages/core/src/features/settings/Extensions.tsx @@ -14,11 +14,11 @@ */ import { FolderOpen, Puzzle, Trash2 } from "lucide-react"; import { useEffect, useState } from "react"; +import { authorNames, localizedText, pluginLoader } from "../plugin"; import { revealItemInDir } from "@tauri-apps/plugin-opener"; import { createLogger } from "@/lib/logger"; -import { pluginLoader } from "../plugin"; import type { PluginEntry } from "../plugin"; const log = createLogger("plugin"); @@ -168,8 +168,8 @@ export function ExtensionsTab() { {entries.map((entry) => (
-

{entry.info.description ?? "沒有說明。"}

-

作者:{entry.info.author ?? "未提供"}

+

{localizedText(entry.info.description) ?? "沒有說明。"}

+

作者:{authorNames(entry.info.author).join("、") || "未提供"}

敏感度:{entry.sensitivity.description} {entry.keyId ? `(簽章金鑰:${entry.keyId})` : ""} diff --git a/tool/plugin/selftest.ts b/tool/plugin/selftest.ts index 97caf6a..00369bd 100644 --- a/tool/plugin/selftest.ts +++ b/tool/plugin/selftest.ts @@ -19,6 +19,8 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; +import { parsePackage, zipSync } from "../../packages/core/src/features/plugin/package.ts"; +import { authorNames, localizedText } from "../../packages/core/src/features/plugin/types.ts"; import { verifyPlugin } from "../../packages/core/src/features/plugin/verify.ts"; import { compareVersions, parseVersion, validateVersionRequirement } from "../../packages/core/src/features/plugin/version.ts"; @@ -118,6 +120,42 @@ try { "requirements hold", validateVersionRequirement("26.0.0", ">=26.0.0") && !validateVersionRequirement("25.9.0", ">=26.0.0"), ); + // The published manifests carry `description` as a locale table and `author` + // as an array (trem-radar-plugin, trem-logger-plugin); the 擴充 page has to + // get plain text out of either shape. + check("a localized description picks zh-Hant", localizedText({ zh_tw: "甲", "zh-Hant": "乙" }) === "乙"); + check("a plain description still works", localizedText("說明") === "說明"); + check( + "authors survive both shapes", + authorNames(["bamboo0403"]).join(",") === "bamboo0403" && authorNames("whes1015").join(",") === "whes1015", + ); + + // A `.trem` is a zip of the plugin folder. Authors zip on Windows, and + // Windows' own tools (`Compress-Archive`, 「傳送到 → 壓縮的資料夾」) write `\` in + // the entry names; both separators and both layouts have to install. + const bytes = (value: string) => encoder.encode(value); + const wrapped = parsePackage( + zipSync({ + "demo\\info.json": bytes('{"name":"demo","version":"1.0.0"}'), + "demo\\index.js": bytes("module.exports = class {};"), + }), + ); + check( + "a Windows-made archive installs", + wrapped.name === "demo" && wrapped.files.map((file) => file.path).sort().join(",") === "index.js,info.json", + JSON.stringify(wrapped.files.map((file) => file.path)), + ); + + const flat = parsePackage(zipSync({ "info.json": bytes('{"name":"flat"}'), "index.js": bytes("x") })); + check("an archive without a wrapper folder installs", flat.name === "flat" && flat.files.length === 2, String(flat.files.length)); + + let refused = ""; + try { + parsePackage(zipSync({ "info.json": bytes('{"name":"Not A Name"}') })); + } catch (e) { + refused = String(e); + } + check("a bad plugin name is refused", refused.includes("name 不合格式"), refused); } finally { rmSync(work, { recursive: true, force: true }); } From c7d3079ef15c72da5319bb2f19b33748c96c512f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 11:15:49 +0800 Subject: [PATCH 06/16] fix(plugin): make the three install paths the page promises work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 擴充 page offered three ways in and only one of them worked. - A plain browser showed the whole install UI. `initPlugins` and `initPluginAdmin` now stop without plugin storage, and the page keys its 不支援 branch off the storage rather than off a loader a browser had built anyway. - Dropping a `.trem` on the page did nothing. Tauri handling the OS-level file drop is what keeps HTML5 drop events from firing on Windows, so the settings window is created with `dragDropEnabled: false`. - A `.trem` copied into the plugin folder was invisible: the folder held an archive where the host expects unpacked directories. The host now installs what it finds there at boot — V3's `index/plugin_init.js` did the same with its bundled package — and discards the archive once it is in, so a package that fails stays put with its reason in the log. Platform: desktop Fix(zh-Hant): 修正擴充功能的安裝:拖曳 .trem 現在有效,複製到擴充功能資料夾的套件會在下次啟動時自動安裝,網頁版正確顯示為不支援。 Fix(en-US): Fixed extension install: dropping a .trem works, a package copied into the plugin folder is installed at the next start, and the browser build reports itself unsupported. --- PLUGINS.md | 2 + apps/desktop/src-tauri/src/lib.rs | 2 + apps/desktop/src-tauri/src/plugin.rs | 53 +++++++++++++++++++ packages/core/src/features/plugin/bridge.ts | 17 ++++++ packages/core/src/features/plugin/host.ts | 35 ++++++++++++ packages/core/src/features/plugin/index.ts | 8 +++ .../core/src/features/settings/Extensions.tsx | 14 +++-- packages/core/src/lib/windows.ts | 4 ++ 8 files changed, 131 insertions(+), 4 deletions(-) diff --git a/PLUGINS.md b/PLUGINS.md index 92a2396..a2c7a82 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -243,6 +243,8 @@ node tool/plugin/sign.mjs ./my-panel --key private.pem --key-id my-key 打包成 `.trem`(就是一個 zip,`info.json` 在壓縮檔根目錄或往下一層都可以;`__MACOSX/` 與 `.DS_Store` 會被忽略)後,可以拖進設定頁的「安裝」區塊。Windows 內建的「傳送到 → 壓縮的資料夾」與 PowerShell 的 `Compress-Archive` 都可以直接用,最後把副檔名改成 `.trem` 即可;那些工具寫入的路徑分隔符號會在解壓時正規化。安裝會**整包取代**既有的同名擴充功能 —— 舊版殘留的檔案會讓下一次簽章檢查回報多餘的檔案。 +不拖檔案也可以:把 `.trem` 直接複製到上面的擴充功能資料夾,下次啟動時會自動安裝,安裝完壓縮檔會被刪掉。安裝失敗的檔案會留在原地,原因寫在日誌裡。 + 沒有簽章的擴充功能還是可以安裝與執行,但設定頁會標成「未驗證」,啟用前要等十秒倒數 —— 這是舊版就有的警告,不是錯誤。 簽章工具本身有自我測試: diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index e701550..858ba9d 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -210,6 +210,8 @@ pub fn run() { plugin::plugin_write, plugin::plugin_install, plugin::plugin_remove, + plugin::plugin_packages, + plugin::plugin_discard, plugin::plugin_keys, updater::update_check, updater::update_pending, diff --git a/apps/desktop/src-tauri/src/plugin.rs b/apps/desktop/src-tauri/src/plugin.rs index ffb2b54..972bfff 100644 --- a/apps/desktop/src-tauri/src/plugin.rs +++ b/apps/desktop/src-tauri/src/plugin.rs @@ -242,6 +242,59 @@ pub fn plugin_remove(app: tauri::AppHandle, plugin: String) -> Result<(), String Ok(()) } +/// `.trem` archives sitting in the plugin folder, base64, `path` = file name. +/// +/// A user who opens the folder can copy a package into it instead of dragging +/// one onto the settings page. The webview unzips what this returns; Rust only +/// carries the bytes. See `PluginLoader::importPackages`. +#[tauri::command] +pub fn plugin_packages(app: tauri::AppHandle) -> Result, String> { + let dir = plugins_dir(&app)?; + let mut out = Vec::new(); + for entry in std::fs::read_dir(&dir) + .map_err(|e| e.to_string())? + .flatten() + { + // `file_type()` rather than `path.is_file()`: a link out of the folder + // is not a package this host should read. + if !entry.file_type().map(|kind| kind.is_file()).unwrap_or(false) { + continue; + } + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("trem") { + continue; + } + let Some(name) = path.file_name().and_then(|s| s.to_str()).map(str::to_owned) else { + continue; + }; + match std::fs::read(&path) { + Ok(bytes) => out.push(PluginFile { + path: name, + data: base64::engine::general_purpose::STANDARD.encode(bytes), + }), + Err(e) => log::warn!(target: "plugin", "讀不到套件 {}:{e}", path.display()), + } + } + out.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(out) +} + +/// Delete one of those archives: it has been installed, and keeping it would +/// install it again on the next start. +/// +/// The name here is a file name (`demo.trem`), not a plugin name, so it is +/// checked for path traversal instead of against `valid_name`. +#[tauri::command] +pub fn plugin_discard(app: tauri::AppHandle, name: String) -> Result<(), String> { + let target = plugins_dir(&app)?.join(safe_relative(&name)?); + if !target.is_file() { + return Ok(()); + } + std::fs::remove_file(&target).map_err(|e| e.to_string())?; + log::info!(target: "plugin", "移除插件套件 {name}"); + Ok(()) +} + /// Keys published by organisations other than ExpTech, dropped in as `.pem`. #[tauri::command] pub fn plugin_keys(app: tauri::AppHandle) -> Result, String> { diff --git a/packages/core/src/features/plugin/bridge.ts b/packages/core/src/features/plugin/bridge.ts index 4322b97..281cf18 100644 --- a/packages/core/src/features/plugin/bridge.ts +++ b/packages/core/src/features/plugin/bridge.ts @@ -37,6 +37,23 @@ export async function readPlugins(): Promise ); } +/** + * The `.trem` archives sitting in the plugin folder, unopened. + * + * A user who finds the folder can copy a package into it instead of dragging + * one onto the settings page; the host installs what it finds at boot. + */ +export async function pluginPackages(): Promise { + if (!inTauri) return []; + return invoke("plugin_packages"); +} + +/** Delete one of those archives, once its contents are installed. */ +export async function discardPackage(name: string): Promise { + if (!inTauri) return; + await invoke("plugin_discard", { name }); +} + /** One file a plugin wrote, or `null` to delete it. */ export async function writePluginFile(plugin: string, path: string, data: Uint8Array | null): Promise { if (!inTauri) return; diff --git a/packages/core/src/features/plugin/host.ts b/packages/core/src/features/plugin/host.ts index 9577f3f..99dfe72 100644 --- a/packages/core/src/features/plugin/host.ts +++ b/packages/core/src/features/plugin/host.ts @@ -18,9 +18,12 @@ import { events } from "@/lib/events"; import { createLogger } from "@/lib/logger"; import type { TremEvents } from "@/lib/types"; +import { decodeBase64 } from "./base64"; import { + discardPackage, installPlugin, pluginKeys, + pluginPackages, pluginRoot, pluginStorageAvailable, readPlugins, @@ -312,6 +315,7 @@ export class PluginLoader { if (this.started) return; this.started = true; + await this.importPackages(); await this.scan(); const enabled = new Set(this.readEnabled()); @@ -526,6 +530,37 @@ export class PluginLoader { // -- installing ---------------------------------------------------------- + /** + * A `.trem` left in the plugin folder is an install waiting to happen. + * + * V3 shipped one that way — `index/plugin_init.js` copied a bundled package + * into the folder at boot — and anyone who opens the folder and copies a file + * into it expects the same. The archive is thrown away once it is in, so a + * package that installs is only ever installed once; one that fails stays + * where it is and says why in the log. + */ + private async importPackages(): Promise { + if (!pluginStorageAvailable) return; + + let packages: PluginFile[]; + try { + packages = await pluginPackages(); + } catch (e) { + log.warn(`讀取擴充功能套件失敗:${String(e)}`); + return; + } + + for (const pkg of packages) { + try { + const name = await this.installPackage(decodeBase64(pkg.data)); + await discardPackage(pkg.path); + log.info(`已安裝擴充功能資料夾中的 ${pkg.path}(${name})。`); + } catch (e) { + log.warn(`安裝 ${pkg.path} 失敗:${String(e)}`); + } + } + } + /** * Install an unpacked plugin, replacing any previous copy. * diff --git a/packages/core/src/features/plugin/index.ts b/packages/core/src/features/plugin/index.ts index c15f919..4706b7b 100644 --- a/packages/core/src/features/plugin/index.ts +++ b/packages/core/src/features/plugin/index.ts @@ -11,11 +11,16 @@ */ import { createLogger } from "@/lib/logger"; +import { pluginStorageAvailable } from "./bridge"; import { createPluginLoader } from "./host"; const log = createLogger("plugin"); export function initPlugins(): void { + // A browser tab has no plugin folder and no way to run what a plugin reaches + // for. 設定 → 擴充 says so rather than offering an install that cannot work. + if (!pluginStorageAvailable) return; + const loader = createPluginLoader("index"); loader.load().catch((e: unknown) => { log.error(`擴充功能載入失敗:${String(e)}`); @@ -32,6 +37,8 @@ export function initPlugins(): void { * so a change made here takes effect the next time the app starts. */ export function initPluginAdmin(): void { + if (!pluginStorageAvailable) return; + const loader = createPluginLoader("index", { management: true }); loader.scan().catch((e: unknown) => { log.error(`擴充功能清單讀取失敗:${String(e)}`); @@ -39,6 +46,7 @@ export function initPluginAdmin(): void { } export { createPluginLoader, pluginLoader, PluginLoader, getSensitivityDescription } from "./host"; +export { pluginStorageAvailable } from "./bridge"; export type { LoaderOptions, PluginContext } from "./host"; export { MixinManager } from "./mixin"; export { authorNames, localizedText } from "./types"; diff --git a/packages/core/src/features/settings/Extensions.tsx b/packages/core/src/features/settings/Extensions.tsx index 740930e..6fca2e5 100644 --- a/packages/core/src/features/settings/Extensions.tsx +++ b/packages/core/src/features/settings/Extensions.tsx @@ -14,7 +14,7 @@ */ import { FolderOpen, Puzzle, Trash2 } from "lucide-react"; import { useEffect, useState } from "react"; -import { authorNames, localizedText, pluginLoader } from "../plugin"; +import { authorNames, localizedText, pluginLoader, pluginStorageAvailable } from "../plugin"; import { revealItemInDir } from "@tauri-apps/plugin-opener"; import { createLogger } from "@/lib/logger"; @@ -53,11 +53,17 @@ export function ExtensionsTab() { return () => window.clearInterval(timer); }, [waitingFor]); - if (!loader) { + // A browser tab has no plugin folder: there is nowhere to install into and + // nothing to run. A missing loader on the desktop is only the moment before + // the list arrives — 設定 → 擴充 is a second webview and does read storage. + if (!pluginStorageAvailable || !loader) { return ( -

+
- 不支援 + {pluginStorageAvailable ? "讀取中" : "不支援"}
); diff --git a/packages/core/src/lib/windows.ts b/packages/core/src/lib/windows.ts index f79d056..2dc62b6 100644 --- a/packages/core/src/lib/windows.ts +++ b/packages/core/src/lib/windows.ts @@ -29,6 +29,10 @@ export async function openSettings(): Promise { resizable: false, decorations: false, transparent: !isMac, + // Tauri handling the OS-level file drop is what stops HTML5 drop events + // from firing on Windows, and 設定 → 擴充 installs a `.trem` by having one + // dropped on the page. + dragDropEnabled: false, }); } From 83ab8ccf83b0148c5ffd34b31ec369059842b0c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 11:34:49 +0800 Subject: [PATCH 07/16] fix(plugin): tell the settings page why a plugin did not load MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Platform: desktop Fix(zh-Hant): 設定 → 擴充 會顯示已啟用的擴充功能載入失敗的原因,不再只說初始化失敗。 Fix(en-US): The extensions page now shows why an enabled extension failed to load. --- packages/core/src/features/plugin/host.ts | 45 +++++++++++++++++-- packages/core/src/features/plugin/sandbox.ts | 4 +- .../core/src/features/settings/Extensions.tsx | 5 ++- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/packages/core/src/features/plugin/host.ts b/packages/core/src/features/plugin/host.ts index 99dfe72..a2ddd34 100644 --- a/packages/core/src/features/plugin/host.ts +++ b/packages/core/src/features/plugin/host.ts @@ -45,6 +45,8 @@ const log = createLogger("plugin"); const ENABLED_KEY = "enabled-plugins"; /** What this host loaded, in V3's shape, for tooling that reads it. */ const LOADED_KEY = "loaded-plugins"; +/** What the last load decided about each one — the key V3's 擴充 page read. */ +const STATUS_KEY = "plugin-status"; /** V3's wording, kept verbatim: the 擴充 page greps for it. */ const STATUS_INIT_FAILED = "初始化失敗,請聯繫擴充作者。"; @@ -52,6 +54,20 @@ const STATUS_DISABLED = "未啟用。"; /** The 擴充 page records the choice; the main window loads it at the next boot. */ const STATUS_RESTART = "將於下次啟動時載入。"; +/** + * Turn a failure into something the 擴充 page can show next to the plugin. + * + * V3 said "contact the author" and left it there; the author cannot act on that + * sentence alone. The reason is either ours (`不能使用 Electron API`) or the + * plugin's own, and it is what the plugin's author needs to be told — kept to + * one line, because the row has one. + */ +function failureReason(error: unknown): string { + const text = (error instanceof Error ? error.message : String(error)).split("\n")[0]?.trim() ?? ""; + if (!text) return ""; + return `(${text.length > 120 ? `${text.slice(0, 119)}…` : text})`; +} + export function getSensitivityDescription(level: number): string { switch (level) { case 4: @@ -122,6 +138,12 @@ export class PluginLoader { private running = new Map(); private trees = new Map>(); private keys = new Map(); + /** + * What the main window's last load concluded, read from `plugin-status`. + * + * Empty in the main window, which knows the answer first hand. + */ + private reported: Record = {}; private listeners = new Set<() => void>(); private started = false; /** The app's own version, as `dependencies.trem` is compared against. */ @@ -190,6 +212,7 @@ export class PluginLoader { this.rootPath = await pluginRoot(); this.trees = await readPlugins(); this.keys = new Map((await pluginKeys()).map((key) => [key.id, key.pem])); + this.reported = this.management ? this.readStatus() : {}; for (const [name, files] of this.trees) { const entry = await this.inspect(name, files); @@ -223,6 +246,11 @@ export class PluginLoader { const verified = await verify(files, this.keys); const level = info.sensitivity?.level ?? 0; + // The settings window runs no plugin of its own, so why one is not running + // can only come from what the main window wrote under `plugin-status` — + // which is exactly what V3's `setting/plugin_list.js` read it for. The + // main window is the one that finds out first hand, so it ignores the key. + const reported = this.reported[name]; return { name: info.name, info, @@ -232,7 +260,7 @@ export class PluginLoader { keyId: verified.keyId, enabled: this.readEnabled().includes(name), loaded: this.management && this.readLoaded().includes(name), - status: verified.valid ? null : { type: "warn", msg: verified.error ?? "未發現有效簽名。" }, + status: reported ?? (verified.valid ? null : { type: "warn", msg: verified.error ?? "未發現有效簽名。" }), sensitivity: { level, description: localizedText(info.sensitivity?.description) ?? getSensitivityDescription(level), @@ -279,6 +307,17 @@ export class PluginLoader { return this.entries.get(name)?.enabled ?? false; } + /** What the last load decided, in V3's shape, for the 擴充 page. */ + private readStatus(): Record { + try { + const raw = JSON.parse(localStorage.getItem(STATUS_KEY) ?? "{}") as unknown; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; + return raw as Record; + } catch { + return {}; + } + } + /** Turn one plugin on and start it, or off and unhook it. */ async setEnabled(name: string, enabled: boolean): Promise { const entry = this.entries.get(name); @@ -438,7 +477,7 @@ export class PluginLoader { } catch (e) { log.error(`擴充功能 ${name} 初始化失敗:${String(e)}`); entry.loaded = false; - entry.status = { type: "error", msg: STATUS_INIT_FAILED }; + entry.status = { type: "error", msg: `${STATUS_INIT_FAILED}${failureReason(e)}` }; return false; } } @@ -627,7 +666,7 @@ export class PluginLoader { for (const entry of this.entries.values()) { if (entry.status) status[entry.name] = entry.status; } - localStorage.setItem("plugin-status", JSON.stringify(status)); + localStorage.setItem(STATUS_KEY, JSON.stringify(status)); } catch (e) { log.warn(`無法寫入擴充功能狀態:${String(e)}`); } diff --git a/packages/core/src/features/plugin/sandbox.ts b/packages/core/src/features/plugin/sandbox.ts index 69d7f69..1cbdcf7 100644 --- a/packages/core/src/features/plugin/sandbox.ts +++ b/packages/core/src/features/plugin/sandbox.ts @@ -602,8 +602,8 @@ const BUILTINS: Record = { /** Named refusals: a plugin that needs one of these needs a different host. */ const UNSUPPORTED: Record = { - electron: "擴充功能不能使用 Electron API。", - "@electron/remote": "擴充功能不能使用 Electron API。", + electron: "擴充功能不能使用 Electron API,需要自己開視窗的擴充功能尚未支援。", + "@electron/remote": "擴充功能不能使用 Electron API,需要自己開視窗的擴充功能尚未支援。", child_process: "擴充功能不能啟動其他程式。", "node:child_process": "擴充功能不能啟動其他程式。", worker_threads: "擴充功能不能建立 worker。", diff --git a/packages/core/src/features/settings/Extensions.tsx b/packages/core/src/features/settings/Extensions.tsx index 6fca2e5..11c5194 100644 --- a/packages/core/src/features/settings/Extensions.tsx +++ b/packages/core/src/features/settings/Extensions.tsx @@ -99,7 +99,7 @@ export function ExtensionsTab() { <>
{entries.length === 0 ? ( @@ -183,6 +183,9 @@ export function ExtensionsTab() { {entry.status && entry.status.type !== "ok" && (

{entry.status.msg}

)} + {entry.verifyError && entry.verifyError !== entry.status?.msg && ( +

簽章:{entry.verifyError}

+ )} {entry.hasConfig &&

這個擴充功能有 config.yml。

}
From 49d6d34399bdfce80db1c4ea8278b7ddaea4e59b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 12:08:26 +0800 Subject: [PATCH 08/16] fix(plugin): check dependencies as soon as the list is read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 擴充 page said nothing about whether an extension could actually run. `validateDependencies` was only ever reached from `start()`, and the settings window never starts anything — it lists, verifies, installs and removes. A plugin whose manifest asked for a newer TREM-Lite, or for another plugin that is not installed, looked exactly like a healthy one until the next boot, and then failed in a log the user does not read. The check now runs at the end of `scan()`, once every manifest is in hand (a plugin may depend on one that sorts after it), and the row names the verdict and the requirement it came from. Platform: desktop Fix(zh-Hant): 設定 → 擴充 會直接標示相依性問題:缺少的擴充功能或版本不符,不必等到下次啟動才知道。 Fix(en-US): The extensions page now reports dependency problems — a missing extension or a version mismatch is named there instead of surfacing at the next start. --- packages/core/src/features/plugin/host.ts | 5 +++++ packages/core/src/features/settings/Extensions.tsx | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/packages/core/src/features/plugin/host.ts b/packages/core/src/features/plugin/host.ts index a2ddd34..12c3f34 100644 --- a/packages/core/src/features/plugin/host.ts +++ b/packages/core/src/features/plugin/host.ts @@ -222,6 +222,11 @@ export class PluginLoader { for (const name of [...this.entries.keys()]) { if (!this.trees.has(name)) this.entries.delete(name); } + // Dependencies are checked once every manifest is in hand: a plugin may + // depend on one that sorts after it. V3 only checked while loading, so the + // row said nothing about a plugin until the next boot; checking here is + // what lets 設定 → 擴充 answer "why can this one not run" straight away. + for (const entry of this.entries.values()) this.validateDependencies(entry); this.changed(); } diff --git a/packages/core/src/features/settings/Extensions.tsx b/packages/core/src/features/settings/Extensions.tsx index 11c5194..11c1e5b 100644 --- a/packages/core/src/features/settings/Extensions.tsx +++ b/packages/core/src/features/settings/Extensions.tsx @@ -186,6 +186,14 @@ export function ExtensionsTab() { {entry.verifyError && entry.verifyError !== entry.status?.msg && (

簽章:{entry.verifyError}

)} + {entry.info.dependencies && Object.keys(entry.info.dependencies).length > 0 && ( +

+ 相依: + {Object.entries(entry.info.dependencies) + .map(([dependency, range]) => `${dependency} ${range}`) + .join("、")} +

+ )} {entry.hasConfig &&

這個擴充功能有 config.yml。

} From 6faec439560983321ce72bb8c315fc75ccb532af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 12:08:39 +0800 Subject: [PATCH 09/16] feat(plugin): give extensions the windows they ask for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every extension with a panel of its own asked for a window the same way — `require("electron")`, then `ipcRenderer.send("open-plugin-window", …)` — and got a named error saying Electron was not available. V3 answered that channel by handing the renderer a second Electron window; that is not something to reuse, so the window is a real Tauri window and the page is served from a scheme of the app's own. - `plugin_window.rs` serves exactly one plugin folder over `trem-plugin://` (`http://trem-plugin.localhost/` on Windows, where a custom scheme is an http origin), injects a bootstrap providing `require("electron")`, `require("./relative")` and `process`, and dispatches every channel V3 answered: `open-plugin-window`, `send-to-plugin-window`, `broadcast-to-plugin-windows`, `close-plugin-window` and its plural, `get-plugin-windows`, `reload` and `all-reload`, `openDevtool`, `toggleFullscreen`, `hide`, the folder openers, and the window controls. One window per plugin, labelled `plugin-`; closing it emits `plugin-window-closed` to the main window. - `electron.ts` is the main window's half: an `ipcRenderer` whose `send` goes through the same dispatcher, so `send-to-plugin-window` reaches the plugin's window without the plugin having to know a window id — which is how the published extensions already write it. - A plugin window gets a capability of its own (`capabilities/plugin-window.json`): the default one covers the app's three windows and nothing else, so without it the page could not talk back. `PLUGINS.md` documents both halves and no longer refuses `electron` in the module table. Platform: desktop New(zh-Hant): 擴充功能可以開啟自己的視窗,用舊版的 ipcRenderer 通道傳資料給它,並在視窗關閉時收到通知。 New(en-US): Extensions can open windows of their own, send data to them over the V3 ipcRenderer channels, and hear about it when one closes. --- PLUGINS.md | 43 +- .../src-tauri/capabilities/plugin-window.json | 7 + apps/desktop/src-tauri/src/lib.rs | 19 + apps/desktop/src-tauri/src/plugin.rs | 10 +- apps/desktop/src-tauri/src/plugin_window.rs | 726 ++++++++++++++++++ packages/core/src/features/plugin/electron.ts | 130 ++++ packages/core/src/features/plugin/sandbox.ts | 15 +- 7 files changed, 937 insertions(+), 13 deletions(-) create mode 100644 apps/desktop/src-tauri/capabilities/plugin-window.json create mode 100644 apps/desktop/src-tauri/src/plugin_window.rs create mode 100644 packages/core/src/features/plugin/electron.ts diff --git a/PLUGINS.md b/PLUGINS.md index a2c7a82..7775fbd 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -179,13 +179,13 @@ const { helper } = ctx.require("./lib/helper"); const other = ctx.require("../other-plugin/util"); // 另一個擴充功能 ``` -**可以**用:`path`、`fs`、`fs-extra`、`buffer`、`process`、`events`、`util`、`os`、`url`、`crypto`。 +**可以**用:`path`、`fs`、`fs-extra`、`buffer`、`process`、`events`、`util`、`os`、`url`、`crypto`、`electron`。 **不可以用**,會拿到明確的錯誤訊息: | 模組 | 訊息 | |---|---| -| `electron`、`@electron/remote` | 擴充功能不能使用 Electron API。 | +| `@electron/remote` | 擴充功能不能用 remote 取得主視窗,請改用 `ctx.TREM`。 | | `child_process` | 擴充功能不能啟動其他程式。 | | `worker_threads` | 擴充功能不能建立 worker。 | | `net` / `http` / `https` / `axios` | 擴充功能不能直接開 socket,請改用 `fetch`。 | @@ -193,6 +193,43 @@ const other = ctx.require("../other-plugin/util"); // 另一個擴充功能 抓網路資料請用標準的 `fetch`,並以 `ctx.TREM.constant.URL` 取得官方端點。 +## 擴充功能視窗 + +要開自己的視窗,跟舊版一樣送 `open-plugin-window`: + +```js +const { ipcRenderer } = require("electron"); + +ipcRenderer.send("open-plugin-window", { + pluginId: "my-panel", + htmlPath: `${info.pluginDir}/my-panel/web/index.html`, + options: { width: 886, height: 673, title: "My Panel" }, +}); +``` + +`options` 支援 `width`、`height`、`minWidth`、`minHeight`、`title`、`resizable`,省略時是 800×600。同一個擴充功能再開一次會先關掉舊的再開新的,不會疊出好幾個視窗。視窗開好後主視窗會收到 `plugin-window-opened`,關掉時收到 `plugin-window-closed`。 + +頁面由應用程式自己的協定提供(Windows 上是 `http://trem-plugin.localhost/`),所以 `./js/map.js`、`fetch("./data/region.json")` 這類相對路徑都能用,頁面也可以直接連外抓 CDN。頁面裡一樣有 `require`: + +```js +const { ipcRenderer } = require("electron"); +ipcRenderer.send("openDevtool"); +document.querySelector("#close").onclick = () => ipcRenderer.send("hide"); +``` + +頁面沒有檔案系統;要讀資料請在主視窗算好再送過去: + +```js +ipcRenderer.send("send-to-plugin-window", { windowId: "my-panel", channel: "rows", payload: rows }); +ipcRenderer.send("broadcast-to-plugin-windows", { pluginId: "my-panel", channel: "rows", payload: rows }); +``` + +`windowId` 填自己的名稱就好(舊版擴充功能幾乎都這樣寫);視窗那側用 `ipcRenderer.on("rows", (event, payload) => …)` 收。 + +其他舊版就有的通道:`close-plugin-window`、`close-plugin-windows`、`get-plugin-windows`(回覆 `plugin-windows-list`)、`reload`、`all-reload`、`openDevtool`、`toggleFullscreen`、`hide`、`openPluginFolder`、`openConfigFolder`、`openReplayFolder`、`openTempFolder`、`minimize-window`、`maximize-window`、`restore-window`。 + +兩邊都還有後路:主視窗送出的未知通道會轉給該擴充功能自己的視窗,頁面送出的未知通道則以 `plugin-window-message` 交給主視窗的擴充功能。 + ## 相依性 ```json @@ -257,7 +294,7 @@ bun tool/plugin/selftest.ts ## 與 TREM-Lite 3 的差異 -- **沒有 Electron**:`electron` 與 `@electron/remote` 都不能用,視窗控制請改用 `ctx.TREM` 或設定頁。 +- **`electron` 只有 `ipcRenderer`、`contextBridge` 與 `shell`**:`ipcRenderer` 背後是應用程式自己的視窗(見上一節),`@electron/remote` 不能用。舊版把 `BrowserWindow`、`Menu` 這類東西直接給擴充功能,v4 只給開視窗與傳訊息的通道。 - **沒有 Node 的網路模組**:`http`、`https`、`net` 都不可用,請用 `fetch`。 - **`TREM.class` 只剩 `AudioManager`**:舊版還有 `DataManager`、`ReportManager`、`FocusManager`、`EewAreaManager`、`BoxManager`、`ReplayControler`、`WindowControler`,這些工作在 v4 由 Rust 與 `packages/core/src/features/` 負責,資料請從 `TREM.variable` 與事件取得。 - **`ctx.info.name` 是新增的**:不用再從 `info.pluginDir` 推自己的名字。 diff --git a/apps/desktop/src-tauri/capabilities/plugin-window.json b/apps/desktop/src-tauri/capabilities/plugin-window.json new file mode 100644 index 0000000..2c0cb57 --- /dev/null +++ b/apps/desktop/src-tauri/capabilities/plugin-window.json @@ -0,0 +1,7 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "plugin-window", + "description": "擴充功能自己的視窗:只讓它把訊息送回去,以及操作自己那個視窗。", + "windows": ["plugin-*"], + "permissions": ["core:default"] +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 858ba9d..9ecd722 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -9,6 +9,7 @@ mod math; mod ml_intensity; mod ntp; mod plugin; +mod plugin_window; #[cfg(desktop)] mod updater; #[cfg(not(desktop))] @@ -59,6 +60,10 @@ pub fn run() { .plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_notification::init()); + // Extensions get their own windows, served over a scheme of our own, and + // the protocol has to exist before the first one asks for a page. + builder = plugin_window::register(builder); + #[cfg(desktop)] { builder = builder @@ -213,6 +218,12 @@ pub fn run() { plugin::plugin_packages, plugin::plugin_discard, plugin::plugin_keys, + plugin_window::plugin_window_open, + plugin_window::plugin_window_close, + plugin_window::plugin_window_send, + plugin_window::plugin_window_broadcast, + plugin_window::plugin_window_list, + plugin_window::plugin_window_ipc, updater::update_check, updater::update_pending, updater::update_restart, @@ -236,6 +247,14 @@ pub fn run() { window::hide_main(window.app_handle()); } } + // A plugin window is disposable: closed by the user, by its own + // page or by the extension being turned off, the main window hears + // about it under the name V3 used. + if window.label().starts_with("plugin-") { + if let WindowEvent::Destroyed = event { + plugin_window::closed(window.app_handle(), window.label()); + } + } }) .build(tauri::generate_context!()) .expect("error while building tauri application") diff --git a/apps/desktop/src-tauri/src/plugin.rs b/apps/desktop/src-tauri/src/plugin.rs index 972bfff..94e0efb 100644 --- a/apps/desktop/src-tauri/src/plugin.rs +++ b/apps/desktop/src-tauri/src/plugin.rs @@ -45,7 +45,7 @@ pub struct PluginKey { } /// `info.json`'s `name` is also the directory name, so it must not traverse. -fn valid_name(name: &str) -> bool { +pub(crate) fn valid_name(name: &str) -> bool { !name.is_empty() && name.len() <= 128 && name @@ -53,19 +53,19 @@ fn valid_name(name: &str) -> bool { .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') } -fn base_dir(app: &tauri::AppHandle) -> Result { +pub(crate) fn base_dir(app: &tauri::AppHandle) -> Result { app.path() .app_config_dir() .map_err(|e| format!("no config dir: {e}")) } -fn plugins_dir(app: &tauri::AppHandle) -> Result { +pub(crate) fn plugins_dir(app: &tauri::AppHandle) -> Result { let dir = base_dir(app)?.join("plugins"); std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; Ok(dir) } -fn plugin_dir(app: &tauri::AppHandle, name: &str) -> Result { +pub(crate) fn plugin_dir(app: &tauri::AppHandle, name: &str) -> Result { if !valid_name(name) { return Err(format!("插件名稱不合法:{name}")); } @@ -73,7 +73,7 @@ fn plugin_dir(app: &tauri::AppHandle, name: &str) -> Result { } /// Reject absolute paths and `..`, so a plugin cannot escape its directory. -fn safe_relative(rel: &str) -> Result { +pub(crate) fn safe_relative(rel: &str) -> Result { let mut out = PathBuf::new(); for part in rel.replace('\\', "/").split('/') { if part.is_empty() || part == "." { diff --git a/apps/desktop/src-tauri/src/plugin_window.rs b/apps/desktop/src-tauri/src/plugin_window.rs new file mode 100644 index 0000000..dd645b3 --- /dev/null +++ b/apps/desktop/src-tauri/src/plugin_window.rs @@ -0,0 +1,726 @@ +//! The plugin-window host — the V4 replacement for Electron's +//! `open-plugin-window` IPC (`legacy/src/main.js:628-780`). +//! +//! A V3 extension that needs its own window calls +//! `ipcRenderer.send("open-plugin-window", { pluginId, htmlPath, options })` +//! from the main window, and the page it names answers with +//! `ipcRenderer.send("send-to-plugin-window", …)`. Neither side can work in V4 +//! as it did: there is no Node in the webview, and a plugin page cannot be +//! loaded from `file://` — `weather/web/weather.html` fetches +//! `./data/region.json` and pulls maplibre-gl from a CDN, so it needs a real +//! origin. +//! +//! So this is the host, in three pieces: +//! +//! 1. A `trem-plugin://` protocol that serves exactly one plugin's folder. +//! HTML going out gets a small `require`/`electron` bootstrap injected, +//! because the page is served with no bundler and nothing else would define +//! them. `ipcRenderer.send` becomes the `plugin_window_ipc` command and +//! messages arrive back through `WebviewWindow::eval` — the same trick V3's +//! main process used, minus the IPC plumbing. +//! 2. One window per plugin, labelled `plugin-`, so a repeat +//! `open-plugin-window` replaces the one already open rather than piling up. +//! 3. One dispatcher for every channel V3 answered, so the main window's +//! `ipcRenderer.send` and a plugin window's own calls both land here. +//! +//! Windows serves custom schemes as `http://.localhost/`, macOS +//! and Linux as `:///`; `window_url` writes the platform's +//! form and `resolve` reads both. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::path::PathBuf; +use tauri::http::{Request, Response, StatusCode}; +use tauri::{Emitter, Manager, Url, WebviewUrl, WebviewWindowBuilder}; + +/// The custom scheme a plugin page is served under. +const SCHEME: &str = "trem-plugin"; +/// The sandbox name the extension host gives the plugins folder +/// (`packages/core/src/features/plugin/sandbox.ts`). A plugin builds its +/// window path from `ctx.info.pluginDir`, so this is what arrives here. +const ROOT: &str = "/plugins"; + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginWindowOptions { + width: Option, + height: Option, + min_width: Option, + min_height: Option, + title: Option, + resizable: Option, +} + +#[derive(Serialize)] +pub struct WindowInfo { + window_id: String, + plugin_id: String, + html_path: String, + options: Value, +} + +/// Register the `trem-plugin://` protocol. Must run before `run()`, which is +/// what `register_uri_scheme_protocol` is for. +pub fn register(builder: tauri::Builder) -> tauri::Builder { + builder.register_uri_scheme_protocol(SCHEME, |ctx, request| serve(ctx.app_handle(), &request)) +} + +/// The window URL for a page, in the form the platform's webview expects. +fn window_url(plugin: &str, page: &str) -> Result { + let text = if cfg!(windows) { + format!("http://{SCHEME}.localhost{ROOT}/{plugin}/{page}") + } else { + format!("{SCHEME}://plugins/{plugin}/{page}") + }; + Url::parse(&text).map_err(|e| format!("擴充功能視窗網址不合法:{e}")) +} + +/// `/plugins//` — the path a plugin builds from `info.pluginDir`. +fn split_html_path(path: &str) -> Result<(String, String), String> { + let normalized = path.replace('\\', "/"); + let marker = format!("{ROOT}/"); + let rest = match normalized.find(&marker) { + Some(index) => &normalized[index + marker.len()..], + None => return Err(format!("擴充功能視窗的路徑不在 plugins 資料夾內:{path}")), + }; + let mut parts = rest.splitn(2, '/'); + let name = parts.next().unwrap_or_default().to_string(); + let page = parts.next().unwrap_or("index.html"); + if !crate::plugin::valid_name(&name) { + return Err(format!("擴充功能視窗的套件名稱不合法:{path}")); + } + Ok(( + name, + if page.is_empty() { "index.html" } else { page }.to_string(), + )) +} + +// -- serving --------------------------------------------------------------- + +fn mime_for(path: &str) -> &'static str { + match path.rsplit('.').next().unwrap_or_default().to_ascii_lowercase().as_str() { + "html" | "htm" => "text/html; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "json" | "map" => "application/json; charset=utf-8", + "txt" | "md" => "text/plain; charset=utf-8", + "csv" => "text/csv; charset=utf-8", + "svg" => "image/svg+xml", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "ico" => "image/x-icon", + "woff" => "font/woff", + "woff2" => "font/woff2", + "ttf" => "font/ttf", + "otf" => "font/otf", + "mp3" => "audio/mpeg", + "wav" => "audio/wav", + "ogg" => "audio/ogg", + "mp4" => "video/mp4", + "wasm" => "application/wasm", + _ => "application/octet-stream", + } +} + +/// The plugin folder's file for a request path, or the status to answer with. +fn resolve(app: &tauri::AppHandle, request: &Request>) -> Result { + let uri = request.uri(); + let path = uri.path(); + // Windows: host `trem-plugin.localhost`, path `/plugins/…`. + // macOS/Linux: host `plugins`, path `/…`. + let full = if path.starts_with(&format!("{ROOT}/")) || path == ROOT { + path.to_string() + } else { + format!("/{}{}", uri.host().unwrap_or_default(), path) + }; + let rest = full + .strip_prefix(&format!("{ROOT}/")) + .or_else(|| full.strip_prefix(ROOT)) + .unwrap_or_default() + .trim_start_matches('/'); + let bad = |status: StatusCode, message: String| (status, message); + let mut parts = rest.splitn(2, '/'); + let name = parts.next().unwrap_or_default(); + let page = parts.next().unwrap_or("index.html"); + if !crate::plugin::valid_name(name) { + return Err(bad( + StatusCode::FORBIDDEN, + format!("不是合法的擴充功能名稱:{name}"), + )); + } + let page = if page.is_empty() { "index.html" } else { page }; + let relative = crate::plugin::safe_relative(page).map_err(|e| bad(StatusCode::BAD_REQUEST, e))?; + let file = crate::plugin::plugin_dir(app, name) + .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e))? + .join(relative); + // `safe_relative` already refuses `..` and absolute parts; this is the + // second half of the check, so a link planted in the folder cannot reach + // outside it either. + if !file.is_file() { + return Err(bad( + StatusCode::NOT_FOUND, + format!("擴充功能 {name} 沒有這個檔案:{page}"), + )); + } + Ok(file) +} + +fn serve( + app: &tauri::AppHandle, + request: &Request>, +) -> Response> { + let file = match resolve(app, request) { + Ok(file) => file, + Err((status, message)) => return plain(status, &message), + }; + let bytes = match std::fs::read(&file) { + Ok(bytes) => bytes, + Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &format!("讀不到檔案:{e}")), + }; + let name = file + .strip_prefix(crate::plugin::plugins_dir(app).unwrap_or_default()) + .ok() + .and_then(|rest| rest.components().next().map(|part| part.as_os_str().to_string_lossy().into_owned())) + .unwrap_or_default(); + let mime = mime_for(&file.to_string_lossy()); + let body = if mime.starts_with("text/html") { + match String::from_utf8(bytes) { + Ok(html) => inject(&html, &name).into_bytes(), + Err(e) => return plain(StatusCode::INTERNAL_SERVER_ERROR, &format!("網頁不是 UTF-8:{e}")), + } + } else { + bytes + }; + Response::builder() + .status(StatusCode::OK) + .header("Content-Type", mime) + .header("Cache-Control", "no-cache") + .body(body) + .unwrap_or_else(|e| plain(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())) +} + +fn plain(status: StatusCode, message: &str) -> Response> { + Response::builder() + .status(status) + .header("Content-Type", "text/plain; charset=utf-8") + .body(message.as_bytes().to_vec()) + .unwrap_or_else(|_| Response::new(Vec::new())) +} + +// -- the page bootstrap ---------------------------------------------------- + +/// Defined for every plugin page: `require("electron")`, `fetch`-based +/// `require` for a plugin's own files, and the `process` fields pages read. +/// Kept in ES5-style plain JavaScript because it is injected as-is. +const BOOTSTRAP: &str = r##""##; + +/// Insert the bootstrap at the top of the page's ``, or at the top of +/// the file for a fragment without one. +fn inject(html: &str, plugin: &str) -> String { + let script = BOOTSTRAP + .replace( + "__PLUGIN__", + &serde_json::to_string(plugin).unwrap_or_else(|_| "\"\"".into()), + ) + .replace("__PLATFORM__", &format!("\"{}\"", std::env::consts::OS)); + let head = find_ci(html, "').map(|close| index + close + 1)); + match head { + Some(index) => format!("{}{}{}", &html[..index], script, &html[index..]), + None => format!("{script}{html}"), + } +} + +/// Byte-wise, ASCII-case-insensitive search. ` Option { + let bytes = haystack.as_bytes(); + let target = needle.as_bytes(); + if target.len() > bytes.len() { + return None; + } + (0..=bytes.len() - target.len()).find(|&i| bytes[i..i + target.len()].eq_ignore_ascii_case(target)) +} + +// -- windows --------------------------------------------------------------- + +fn window_label(plugin: &str) -> String { + format!("plugin-{plugin}") +} + +fn open_window( + app: &tauri::AppHandle, + plugin: &str, + page: &str, + options: PluginWindowOptions, +) -> Result { + if !crate::plugin::valid_name(plugin) { + return Err(format!("不是合法的擴充功能名稱:{plugin}")); + } + let relative = crate::plugin::safe_relative(page)?; + let page = relative.to_string_lossy().replace('\\', "/"); + let label = window_label(plugin); + // V3 closed the previous window for the same plugin first, so a second + // click on the nav button reopens rather than stacks. + if let Some(existing) = app.get_webview_window(&label) { + let _ = existing.close(); + } + let url = window_url(plugin, &page)?; + let mut builder = WebviewWindowBuilder::new(app, &label, WebviewUrl::External(url)) + .title( + options + .title + .clone() + .unwrap_or_else(|| format!("擴充功能 {plugin}")), + ) + .inner_size(options.width.unwrap_or(800.0), options.height.unwrap_or(600.0)) + .resizable(options.resizable.unwrap_or(true)) + .decorations(true); + if let (Some(width), Some(height)) = (options.min_width, options.min_height) { + builder = builder.min_inner_size(width, height); + } + let window = builder + .build() + .map_err(|e| format!("開啟擴充功能視窗失敗:{e}"))?; + let _ = window.center(); + log::info!("擴充功能 {plugin} 的視窗已開啟:{page}"); + let _ = app.emit_to( + "main", + "plugin-window-opened", + serde_json::json!({ "success": true, "windowId": plugin, "pluginId": plugin }), + ); + Ok(label) +} + +/// Tell the main window a plugin window went away, the way V3's `closed` +/// handler did. Called from the window event handler in `lib.rs`. +pub fn closed(app: &tauri::AppHandle, label: &str) { + let Some(plugin) = label.strip_prefix("plugin-") else { + return; + }; + log::info!("擴充功能 {plugin} 的視窗已關閉"); + let _ = app.emit_to( + "main", + "plugin-window-closed", + serde_json::json!({ "windowId": plugin, "pluginId": plugin }), + ); +} + +fn dispatch(app: &tauri::AppHandle, plugin: &str, channel: &str, payload: Value) -> Result<(), String> { + let label = window_label(plugin); + let window = app + .get_webview_window(&label) + .ok_or_else(|| format!("擴充功能 {plugin} 沒有開啟的視窗"))?; + let channel = serde_json::to_string(channel).unwrap_or_else(|_| "\"\"".into()); + let payload = serde_json::to_string(&payload).unwrap_or_else(|_| "null".into()); + window + .eval(format!( + "window.__tremDispatch && window.__tremDispatch({channel}, {payload})" + )) + .map_err(|e| format!("傳送訊息給擴充功能視窗失敗:{e}")) +} + +fn broadcast(app: &tauri::AppHandle, plugin: &str, channel: &str, payload: Value) -> Result<(), String> { + let channel = serde_json::to_string(channel).unwrap_or_else(|_| "\"\"".into()); + let payload = serde_json::to_string(&payload).unwrap_or_else(|_| "null".into()); + let prefix = window_label(plugin); + let mut sent = 0; + for (label, window) in app.webview_windows() { + if label == prefix { + let _ = window.eval(format!( + "window.__tremDispatch && window.__tremDispatch({channel}, {payload})" + )); + sent += 1; + } + } + if sent == 0 { + return Err(format!("擴充功能 {plugin} 沒有開啟的視窗")); + } + Ok(()) +} + +fn value_text(payload: &Value, key: &str) -> Option { + payload.get(key)?.as_str().map(str::to_string) +} + +fn open_folder(path: PathBuf, what: &str) { + let _ = std::fs::create_dir_all(&path); + let text = path.to_string_lossy().into_owned(); + log::info!("開啟{what}:{text}"); + if let Err(e) = tauri_plugin_opener::open_path(&text, None::<&str>) { + log::warn!("開啟{what}失敗:{e}"); + } +} + +// -- commands -------------------------------------------------------------- + +#[tauri::command] +pub fn plugin_window_open( + app: tauri::AppHandle, + plugin: String, + page: String, + options: Option, +) -> Result { + open_window(&app, &plugin, &page, options.unwrap_or_default()) +} + +#[tauri::command] +pub fn plugin_window_close(app: tauri::AppHandle, plugin: String) -> Result<(), String> { + let label = window_label(&plugin); + match app.get_webview_window(&label) { + Some(window) => window + .close() + .map_err(|e| format!("關閉擴充功能視窗失敗:{e}")), + None => Ok(()), + } +} + +#[tauri::command] +pub fn plugin_window_send( + app: tauri::AppHandle, + plugin: String, + channel: String, + payload: Option, +) -> Result<(), String> { + dispatch(&app, &plugin, &channel, payload.unwrap_or(Value::Null)) +} + +#[tauri::command] +pub fn plugin_window_broadcast( + app: tauri::AppHandle, + plugin: String, + channel: String, + payload: Option, +) -> Result<(), String> { + broadcast(&app, &plugin, &channel, payload.unwrap_or(Value::Null)) +} + +#[tauri::command] +pub fn plugin_window_list(app: tauri::AppHandle, plugin: Option) -> Vec { + let mut out = Vec::new(); + for (label, window) in app.webview_windows() { + let Some(name) = label.strip_prefix("plugin-") else { + continue; + }; + if let Some(wanted) = &plugin { + if wanted != name { + continue; + } + } + out.push(WindowInfo { + window_id: name.to_string(), + plugin_id: name.to_string(), + html_path: window.url().map(|url| url.to_string()).unwrap_or_default(), + options: serde_json::json!({}), + }); + } + out.sort_by(|a, b| a.window_id.cmp(&b.window_id)); + out +} + +/// The one entry point every `ipcRenderer.send` reaches: the main window's +/// extensions (`source` `"main"`) and a plugin window's own page +/// (`source` `"plugin"`). V3 answered all of these in the main process. +#[tauri::command] +pub fn plugin_window_ipc( + app: tauri::AppHandle, + plugin: String, + channel: String, + payload: Option, + source: Option, +) -> Result<(), String> { + let payload = payload.unwrap_or(Value::Null); + let from_page = source.as_deref() == Some("plugin"); + match channel.as_str() { + "open-plugin-window" => { + let html = value_text(&payload, "htmlPath") + .ok_or_else(|| "open-plugin-window 缺少 htmlPath".to_string())?; + let (target, page) = match split_html_path(&html) { + Ok(pair) => pair, + // A plugin that built the path some other way still gets its + // own folder, which is what the relative path was for. + Err(_) => (plugin.clone(), html.trim_start_matches("./").to_string()), + }; + let options = payload + .get("options") + .and_then(|options| serde_json::from_value(options.clone()).ok()) + .unwrap_or_default(); + return open_window(&app, &target, &page, options).map(|_| ()); + } + "send-to-plugin-window" => { + // Plugins address their own window by plugin id, not by the + // window id V3 handed back (`eew-info/index.js:66`). + let target = value_text(&payload, "windowId") + .or_else(|| value_text(&payload, "pluginId")) + .unwrap_or_else(|| plugin.clone()); + let channel = value_text(&payload, "channel") + .ok_or_else(|| "send-to-plugin-window 缺少 channel".to_string())?; + let inner = payload.get("payload").cloned().unwrap_or(Value::Null); + return dispatch(&app, &target, &channel, inner); + } + "broadcast-to-plugin-windows" => { + let target = value_text(&payload, "pluginId").unwrap_or_else(|| plugin.clone()); + let channel = value_text(&payload, "channel") + .ok_or_else(|| "broadcast-to-plugin-windows 缺少 channel".to_string())?; + let inner = payload.get("payload").cloned().unwrap_or(Value::Null); + return broadcast(&app, &target, &channel, inner); + } + "close-plugin-window" => { + let target = payload + .as_str() + .map(str::to_string) + .or_else(|| value_text(&payload, "windowId")) + .unwrap_or_else(|| plugin.clone()); + return plugin_window_close(app, target); + } + "close-plugin-windows" => { + let target = payload + .as_str() + .map(str::to_string) + .or_else(|| value_text(&payload, "pluginId")) + .unwrap_or_else(|| plugin.clone()); + return plugin_window_close(app, target); + } + "get-plugin-windows" => { + let target = payload + .as_str() + .map(str::to_string) + .or_else(|| value_text(&payload, "pluginId")) + .unwrap_or_else(|| plugin.clone()); + let windows = plugin_window_list(app.clone(), Some(target.clone())); + let _ = app.emit_to( + "main", + "plugin-windows-list", + serde_json::json!({ "pluginId": target, "windows": windows }), + ); + return Ok(()); + } + "all-reload" => { + log::info!("重新載入所有視窗"); + for (_, window) in app.webview_windows() { + let _ = window.eval("location.reload()"); + } + return Ok(()); + } + "reload" => return plugin_window_eval(&app, &plugin, from_page, "location.reload()"), + "openDevtool" => { + if let Some(window) = app.get_webview_window(&(if from_page { + window_label(&plugin) + } else { + "main".into() + })) { + window.open_devtools(); + } + return Ok(()); + } + "toggleFullscreen" => { + let label = if from_page { window_label(&plugin) } else { "main".into() }; + if let Some(window) = app.get_webview_window(&label) { + let full = window.is_fullscreen().unwrap_or(false); + let _ = window.set_fullscreen(!full); + } + return Ok(()); + } + "hide" => { + if from_page { + // A plugin window has no tray to hide into; V3 hid the window + // and only `toggleFullscreen`/the nav could bring it back. + return plugin_window_close(app, plugin); + } + if let Some(window) = app.get_webview_window("main") { + let _ = window.hide(); + } + return Ok(()); + } + "minimize-window" => return window_state_call(&app, &plugin, from_page, "minimize"), + "maximize-window" => return window_state_call(&app, &plugin, from_page, "maximize"), + "restore-window" => return window_state_call(&app, &plugin, from_page, "unminimize"), + "openPluginFolder" => { + let dir = crate::plugin::plugins_dir(&app).map_err(|e| e)?; + return Ok(open_folder(dir, "擴充功能資料夾")); + } + "openTempFolder" => { + // V3 copied a plugin into `plugins-temp` before running it; V4 + // runs it from the folder it was installed in. + let dir = crate::plugin::plugin_dir(&app, &plugin)?; + return Ok(open_folder(dir, "擴充功能資料夾")); + } + "openConfigFolder" => { + let dir = crate::plugin::base_dir(&app)?; + return Ok(open_folder(dir, "設定資料夾")); + } + "openReplayFolder" => { + // V4 keeps no replay folder of its own. + let dir = crate::plugin::base_dir(&app)?.join("replay"); + return Ok(open_folder(dir, "重播資料夾")); + } + "open-path" | "open-external" => { + if let Some(path) = value_text(&payload, "path") { + let _ = tauri_plugin_opener::open_path(&path, None::<&str>); + } else if let Some(url) = value_text(&payload, "url") { + let _ = tauri_plugin_opener::open_url(&url, None::<&str>); + } + return Ok(()); + } + _ => {} + } + if from_page { + // A plugin window talking to the main window: the extensions running + // there listen with `ipcRenderer.on(channel, …)`. + let _ = app.emit_to( + "main", + "plugin-window-message", + serde_json::json!({ "pluginId": plugin, "channel": channel, "payload": payload }), + ); + return Ok(()); + } + // The main window talking to its own window — `config-updated` and the + // like. V3's main process had no handler for these either. + dispatch(&app, &plugin, &channel, payload) +} + +fn plugin_window_eval( + app: &tauri::AppHandle, + plugin: &str, + from_page: bool, + js: &str, +) -> Result<(), String> { + let label = if from_page { + window_label(plugin) + } else { + "main".to_string() + }; + match app.get_webview_window(&label) { + Some(window) => window + .eval(js.to_string()) + .map_err(|e| format!("重新載入失敗:{e}")), + None => Ok(()), + } +} + +fn window_state_call( + app: &tauri::AppHandle, + plugin: &str, + from_page: bool, + action: &str, +) -> Result<(), String> { + let label = if from_page { window_label(plugin) } else { "main".into() }; + let Some(window) = app.get_webview_window(&label) else { + return Ok(()); + }; + let _ = match action { + "minimize" => window.minimize(), + "maximize" => window.maximize(), + _ => window.unminimize(), + }; + Ok(()) +} diff --git a/packages/core/src/features/plugin/electron.ts b/packages/core/src/features/plugin/electron.ts new file mode 100644 index 0000000..c3055e1 --- /dev/null +++ b/packages/core/src/features/plugin/electron.ts @@ -0,0 +1,130 @@ +/** + * `require("electron")` for an extension running in the main window. + * + * V3 extensions reach for `ipcRenderer` for exactly two things: opening a + * window of their own, and pushing data into it. Both are answered by + * `src-tauri/src/plugin_window.rs` — the window is a real Tauri window, the + * data arrives through `WebviewWindow::eval` — so to a plugin this looks like + * the Electron it was written against. + * + * The four channels Rust sends back are dispatched here, because a plugin's + * `web/` page is the thing that talks to the *window*, while the plugin's own + * `index.js` is the thing that listens for `plugin-window-closed`. Reusing the + * V3 names is what makes that work without a compatibility table. + */ +import { invoke } from "@tauri-apps/api/core"; +import { listen } from "@tauri-apps/api/event"; +import { openPath, openUrl } from "@tauri-apps/plugin-opener"; + +import { inTauri } from "@/lib/env"; +import { createLogger } from "@/lib/logger"; + +const log = createLogger("plugin"); + +type Handler = (event: { sender: string }, payload: unknown) => void; + +const listeners = new Map(); +let wired = false; + +function emit(channel: string, payload: unknown, sender = ""): void { + for (const handler of [...(listeners.get(channel) ?? [])]) { + try { + handler({ sender }, payload); + } catch (e) { + log.error(`擴充功能的事件處理失敗(${channel}):`, e); + } + } +} + +/** Subscribe once, on the first plugin that asks for `electron`. */ +function wire(): void { + if (wired || !inTauri) return; + wired = true; + void listen<{ pluginId: string; channel: string; payload: unknown }>("plugin-window-message", (event) => { + emit(event.payload.channel, event.payload.payload, event.payload.pluginId); + }); + for (const channel of ["plugin-window-opened", "plugin-window-closed", "plugin-windows-list"]) { + void listen(channel, (event) => emit(channel, event.payload)); + } +} + +export interface IpcRenderer { + send(channel: string, ...args: unknown[]): void; + sendSync(channel: string, ...args: unknown[]): null; + invoke(channel: string, ...args: unknown[]): Promise; + on(channel: string, handler: Handler): IpcRenderer; + once(channel: string, handler: Handler): IpcRenderer; + off(channel: string, handler: Handler): IpcRenderer; + removeListener(channel: string, handler: Handler): IpcRenderer; + removeAllListeners(channel?: string): IpcRenderer; +} + +/** + * The `ipcRenderer` one plugin sees. `plugin` names the sender, so a message + * aimed at "my window" can be routed without the plugin knowing a window id. + */ +export function ipcRendererFor(plugin: string): IpcRenderer { + wire(); + const send = (channel: string, args: unknown[]): Promise => { + if (!inTauri) return Promise.resolve(null); + const payload = args.length === 0 ? null : args.length === 1 ? args[0] : args; + return invoke("plugin_window_ipc", { plugin, channel, payload, source: "main" }).catch((e: unknown) => { + log.warn(`擴充功能 ${plugin} 的 ${channel} 沒有完成:${String(e)}`); + return null; + }); + }; + const add = (channel: string, handler: Handler, once: boolean): IpcRenderer => { + const entry: Handler = once + ? (event, payload) => { + ipcRenderer.removeListener(channel, entry); + handler(event, payload); + } + : handler; + listeners.set(channel, [...(listeners.get(channel) ?? []), entry]); + return ipcRenderer; + }; + const ipcRenderer: IpcRenderer = { + send: (channel, ...args) => { + void send(channel, args); + }, + sendSync: (channel, ...args) => { + void send(channel, args); + return null; + }, + invoke: (channel, ...args) => send(channel, args), + on: (channel, handler) => add(channel, handler, false), + once: (channel, handler) => add(channel, handler, true), + off: (channel, handler) => ipcRenderer.removeListener(channel, handler), + removeListener: (channel, handler) => { + listeners.set(channel, (listeners.get(channel) ?? []).filter((item) => item !== handler)); + return ipcRenderer; + }, + removeAllListeners: (channel) => { + if (channel) listeners.delete(channel); + else listeners.clear(); + return ipcRenderer; + }, + }; + return ipcRenderer; +} + +/** + * The rest of the Electron surface a plugin is likely to touch. `shell` goes + * through the opener plugin, so it opens things the way the app does. + */ +export function electronModule(plugin: string) { + return { + ipcRenderer: ipcRendererFor(plugin), + contextBridge: { + exposeInMainWorld: (key: string, value: unknown) => { + (window as unknown as Record)[key] = value; + }, + }, + shell: { + openPath: (path: string) => openPath(path), + openExternal: (url: string) => openUrl(url), + }, + remote: undefined, + default: undefined, + }; +} diff --git a/packages/core/src/features/plugin/sandbox.ts b/packages/core/src/features/plugin/sandbox.ts index 1cbdcf7..e6c06d8 100644 --- a/packages/core/src/features/plugin/sandbox.ts +++ b/packages/core/src/features/plugin/sandbox.ts @@ -10,11 +10,14 @@ * `/plugins`, mirroring the real directory — the same layout * `ctx.info.pluginDir` pointed at in V3. * - * Deliberately absent: any path outside `/plugins`, `child_process`, Electron - * and npm packages. A plugin that reaches for one gets a named error rather - * than a confusing `undefined`. + * Deliberately absent: any path outside `/plugins`, `child_process` and npm + * packages. A plugin that reaches for one gets a named error rather than a + * confusing `undefined`. `electron` is not absent: `ipcRenderer` is what every + * extension that has a window of its own starts with, and `electron.ts` answers + * it with the host's own windows. */ import { encodeBase64, type Bytes } from "./base64"; +import { electronModule } from "./electron"; import { dirname, isAbsolute, join, normalize, path as pathsModule, resolve, type PathModule } from "./paths"; const decoder = new TextDecoder("utf-8"); @@ -542,6 +545,8 @@ export class PluginRuntime { return { URL, URLSearchParams, pathToFileURL, fileURLToPath, default: { URL, URLSearchParams } }; case "crypto": return cryptoShim; + case "electron": + return electronModule(this.options.plugin); default: throw new Error(UNSUPPORTED[name] ?? `Cannot find module '${name}'`); } @@ -598,12 +603,12 @@ const BUILTINS: Record = { os: true, url: true, crypto: true, + electron: true, }; /** Named refusals: a plugin that needs one of these needs a different host. */ const UNSUPPORTED: Record = { - electron: "擴充功能不能使用 Electron API,需要自己開視窗的擴充功能尚未支援。", - "@electron/remote": "擴充功能不能使用 Electron API,需要自己開視窗的擴充功能尚未支援。", + "@electron/remote": "擴充功能不能用 remote 取得主視窗,請改用 ctx.TREM。", child_process: "擴充功能不能啟動其他程式。", "node:child_process": "擴充功能不能啟動其他程式。", worker_threads: "擴充功能不能建立 worker。", From 0f537d91bc89fea4227653a0236da4f8b6faee64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9C=E5=A4=9C?= Date: Mon, 5 Oct 2026 12:18:43 +0800 Subject: [PATCH 10/16] fix(plugin): keep the nav anchors extensions inject into MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A V3 extension that adds a button to the nav — weather and websocket both do — looks up `#focus` and inserts its own node after it: document.querySelector("#focus").insertAdjacentElement("afterend", button) V4 renders that row from React, so the button had no id, the lookup returned null, and the extension's own `onLoad()` threw on the very next line. The row was reachable, but nothing an extension could hang itself off. The two ids legacy/src/view/index.html gave those buttons (`#setting`, `#focus`) are back on the React buttons, and `.nav-bar-location` — the class an injected node carries — is styled with the geometry of nav_bar/box.css, so a button an extension adds sits in the row like the buttons beside it. Platform: desktop Fix(zh-Hant): 舊版擴充功能可以再把按鈕加進左下角的按鈕列,插進去的按鈕外觀與旁邊一致。 Fix(en-US): V3 extensions can add their button to the bottom-left row again, styled like the buttons beside it. --- PLUGINS.md | 19 ++++++++++++++++ packages/core/src/overlays/NavBar.tsx | 16 +++++++++++++- packages/core/src/styles/globals.css | 31 +++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/PLUGINS.md b/PLUGINS.md index 7775fbd..ce6bf93 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -230,6 +230,25 @@ ipcRenderer.send("broadcast-to-plugin-windows", { pluginId: "my-panel", channel: 兩邊都還有後路:主視窗送出的未知通道會轉給該擴充功能自己的視窗,頁面送出的未知通道則以 `plugin-window-message` 交給主視窗的擴充功能。 +## 導覽列按鈕 + +要在左下角的按鈕列加一顆自己的按鈕,舊版的做法是插在 `#focus` 後面: + +```js +const focusButton = document.querySelector("#focus"); +if (focusButton) { + const button = document.createElement("div"); + button.id = "my-button"; + button.className = "nav-bar-location"; + button.title = "我的面板"; + button.innerHTML = ""; + focusButton.insertAdjacentElement("afterend", button); + button.addEventListener("click", () => ipcRenderer.send("open-plugin-window", { … })); +} +``` + +`#setting` 與 `#focus` 這兩個 id 在 V4 保留著就是為了這個(舊版的 `legacy/src/view/index.html` 也是這樣寫的),`.nav-bar-location` 的樣式也在,插進去的按鈕會和旁邊的按鈕長得一樣。`onLoad()` 執行時畫面已經在了,不需要自己等 DOM。 + ## 相依性 ```json diff --git a/packages/core/src/overlays/NavBar.tsx b/packages/core/src/overlays/NavBar.tsx index acb00ae..b73e058 100644 --- a/packages/core/src/overlays/NavBar.tsx +++ b/packages/core/src/overlays/NavBar.tsx @@ -13,6 +13,12 @@ import { TimeBar } from "./TimeBar"; * Bottom-left control cluster — ports legacy `.nav-bar-wrapper`: a single flex ROW * of icon buttons followed by the inline time pill (legacy `.connect #time`). * left:3px / bottom:5px, 30×30 buttons with 20px icons, exactly like nav_bar/box.css. + * + * The buttons keep the ids the legacy markup gave them (`#setting`, `#focus`). + * Extensions of the "add a button to the nav" kind — weather and websocket both + * do it — look up `#focus` and insert their own node after it, so an id-less + * React button would leave them unable to appear at all. `.nav-bar-location` + * (globals.css) is the class they put on that node. */ export function NavBar() { // 自動聚焦被使用者手動操作鎖定時,定位鈕變紅(對應舊版 #focus 紅/白)。 @@ -26,10 +32,15 @@ export function NavBar() { className="legacy-nav absolute bottom-[5px] left-[3px] z-30 flex flex-row items-center gap-[3px] text-[15px] font-medium" style={{ color: "var(--light)" }} > - (inTauri ? void openSettings() : setSettingsOpen(true))}> + (inTauri ? void openSettings() : setSettingsOpen(true))} + > focus_reset(true)} > @@ -42,16 +53,19 @@ export function NavBar() { } function NavPanelButton({ + id, children, title, onClick, }: { + id?: string; children: React.ReactNode; title: string; onClick: () => void; }) { return (