diff --git a/PLUGINS.md b/PLUGINS.md new file mode 100644 index 0000000..875e55b --- /dev/null +++ b/PLUGINS.md @@ -0,0 +1,344 @@ +# 擴充功能開發 + +擴充功能(以前叫「插件」)讓你用 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": { "zh_tw": "在地圖旁邊加一個自己的面板" }, + "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 \| 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` 物件: + +| 成員 | 說明 | +|---|---| +| `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"); // 另一個擴充功能的路徑 +``` + +也可以直接用**另一個擴充功能的名稱**,會拿到它 `index.js` 匯出的東西 —— 這是不用打包工具就能共用程式碼的方式: + +```js +const shared = require("other-plugin"); // 等同 require("../other-plugin/index.js") +``` + +兩個前提:那個擴充功能要**已安裝且已啟用**,而且要在自己的 `info.json` 的 `dependencies` 裡寫上它(見下節),確保它先載入。名稱只能是小寫字母、數字與連字號 —— `react-dom/client` 這種含 `/` 或 `.` 的寫法一律當成 npm 套件拒絕,不會被當成擴充功能名稱。 + +被載入的檔案**以自己的身分執行**:它裡面的 `fs` 相對路徑、以及它寫入的檔案,都算在擁有那個檔案的擴充功能上,而不是呼叫它的那一個(寫到別的擴充功能仍然會被拒絕)。 + +**可以**用:`path`、`fs`、`fs-extra`、`buffer`、`process`、`events`、`util`、`os`、`url`、`crypto`、`electron`。 + +**不可以用**,會拿到明確的錯誤訊息: + +| 模組 | 訊息 | +|---|---| +| `@electron/remote` | 擴充功能不能用 remote 取得主視窗,請改用 `ctx.TREM`。 | +| `child_process` | 擴充功能不能啟動其他程式。 | +| `worker_threads` | 擴充功能不能建立 worker。 | +| `net` / `http` / `https` / `axios` | 擴充功能不能直接開 socket,請改用 `fetch`。 | +| 其他 npm 套件 | 擴充功能不能載入 npm 套件,請改用相對路徑,或另一個擴充功能的名稱。 | + +npm 套件要用就得在打包時自己 bundle 成一個 `.js` 放進擴充功能資料夾(例如 `esbuild --bundle --format=cjs`),執行時不會去 Node 的解析路徑裡找 `node_modules`。 + +抓網路資料請用標準的 `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` 交給主視窗的擴充功能。 + +視窗裡的錯誤會寫進應用程式日誌,不會再無聲無息:頁面拋出的例外、沒有接住的 `Promise`,以及載入失敗的資源(`"##; + +/// 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 -------------------------------------------------------------- +// +// Every one of these is `async` on purpose. A command declared without it is +// run inline on the thread the IPC arrived on, which is the main thread, inside +// WebView2's own message callback; `WebviewWindowBuilder::build` would then +// create a window and a second WebView2 controller back inside that callback, +// which is what made the app freeze solid the moment an extension opened its +// window. `async` moves the body onto the async runtime, so the window is built +// from the event loop the way any other window is. + +#[tauri::command] +pub async 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 async 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 async 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 async 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 async 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 async 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() { + // A page's own failures, forwarded by the bootstrap. V3 showed these in + // the app's log; without this a blank window says nothing at all. + "__page-error" => { + log::warn!( + "擴充功能視窗 {plugin}:{}", + payload.as_str().unwrap_or_default() + ); + return Ok(()); + } + "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).await; + } + "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).await; + } + "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())).await; + 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" => { + // `open_devtools` is compiled only when devtools exist (see lib.rs): + // a release binary has no such method, so the arm answers the + // plugin without doing anything there instead of failing to build. + #[cfg(debug_assertions)] + 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).await; + } + 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/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..281cf18 --- /dev/null +++ b/packages/core/src/features/plugin/bridge.ts @@ -0,0 +1,75 @@ +/** + * 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])), + ]), + ); +} + +/** + * 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; + 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/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/host.ts b/packages/core/src/features/plugin/host.ts new file mode 100644 index 0000000..d3fed52 --- /dev/null +++ b/packages/core/src/features/plugin/host.ts @@ -0,0 +1,697 @@ +/** + * 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 maplibregl from "maplibre-gl"; + +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, + removePlugin, + writePluginFile, +} from "./bridge"; +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"; + +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"; +/** 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 = "初始化失敗,請聯繫擴充作者。"; +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: + 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; +} + +/** + * 設定 → 擴充 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(); + 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. */ + tremVersion = ""; + /** + * `/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", options: LoaderOptions = {}) { + this.type = type; + this.management = options.management ?? false; + } + + // -- 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])); + this.reported = this.management ? this.readStatus() : {}; + + 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); + } + // 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(); + } + + 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; + // 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, + present: true, + verified: verified.valid, + verifyError: verified.error, + keyId: verified.keyId, + enabled: this.readEnabled().includes(name), + loaded: this.management && this.readLoaded().includes(name), + status: reported ?? (verified.valid ? null : { type: "warn", msg: verified.error ?? "未發現有效簽名。" }), + sensitivity: { + level, + description: localizedText(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)])); + } + + /** + * 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; + } + + /** 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); + if (!entry) return; + + if (enabled) { + this.writeEnabled([...this.readEnabled(), name]); + entry.enabled = true; + 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; + 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.importPackages(); + await this.scan(); + const enabled = new Set(this.readEnabled()); + + for (const entry of this.entries.values()) { + const byExptech = authorNames(entry.info.author).some((name) => name.includes("ExpTechTW")); + if (entry.info["auto-enable"] === true && byExptech && 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}`, + // A plugin that `require`s another by name gets *that* plugin's runtime, + // so the file it loads keeps its own folder and its own `fs`. Only + // plugins already running answer, which is what `dependencyOrder` above + // arranged; a name that is installed but disabled gets its own message + // rather than a silent `undefined`. + lookup: (other) => this.running.get(other)?.runtime, + 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}${failureReason(e)}` }; + 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 ---------------------------------------------------------- + + /** + * 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. + * + * 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 parsed = parsePackage(data); + const plugin = name ?? parsed.name; + if (!NAME_PATTERN.test(plugin)) { + throw new Error("info.json 的 name 不合格式(僅允許小寫字母、數字與連字號)。"); + } + await this.install(plugin, parsed.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(STATUS_KEY, 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", options: LoaderOptions = {}): PluginLoader { + instance ??= new PluginLoader(type, options); + 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..4706b7b --- /dev/null +++ b/packages/core/src/features/plugin/index.ts @@ -0,0 +1,53 @@ +/** + * 擴充功能 — 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 { 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)}`); + }); +} + +/** + * 設定 → 擴充 — 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 { + if (!pluginStorageAvailable) return; + + const loader = createPluginLoader("index", { management: true }); + loader.scan().catch((e: unknown) => { + log.error(`擴充功能清單讀取失敗:${String(e)}`); + }); +} + +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"; +export type { LoadedPlugin, LocalizedText, 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/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/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..dee0121 --- /dev/null +++ b/packages/core/src/features/plugin/sandbox.ts @@ -0,0 +1,797 @@ +/** + * 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` and npm + * packages. A plugin that reaches for one gets a named error rather than a + * confusing `undefined` — and a *bare* specifier is not a package but another + * extension's folder, which is what makes `require("other-plugin")` work. + * `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"); +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; + /** + * The runtime of another plugin, for `require("")`. + * + * A module has to be evaluated by the runtime that owns its folder: `fs` + * resolves relative paths against `pluginDir` and writes are attributed to + * `plugin`, so evaluating one plugin's file with another's runtime would + * hand it the wrong directory. The loader answers this from the plugins it + * has running, which is also why a plugin reached by name must be enabled. + */ + lookup?: (plugin: string) => PluginRuntime | undefined; +} + +/** + * 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(".")) { + // One extension standing on another: the tree holds every installed + // plugin, so a bare name is that plugin's own folder. `dependencies` + // already ordered the two, and asking for an absent one happens when a + // plugin reaches for a package, so say both halves. + if (this.isBareName(specifier)) { + const root = join(PLUGIN_ROOT, specifier); + if (this.tree.isDirectory(root)) { + // `index.js`, because that is the file the host loads as the plugin + // itself — anything else would hand the asker a module the host never + // treated as that plugin. + return this.evaluate(`${root}/index.js`); + } + } + throw new Error(`Cannot find module '${specifier}':擴充功能不能載入 npm 套件,請改用相對路徑,或另一個擴充功能的名稱。`); + } + + 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}`); + } + + /** A plugin name is a bare specifier only if it could name a directory. */ + private isBareName(specifier: string): boolean { + return /^[a-z0-9][a-z0-9-]*$/.test(specifier); + } + + private evaluate(file: string): unknown { + // A file in another plugin's folder — reached by name, or by the + // `../other-plugin/util` path V3 documented — has to run under *its* owner's + // runtime. Otherwise the `fs` inside it resolves relative paths against the + // plugin that happened to ask, and a write would be attributed there too. + // No owner means nothing loaded that plugin yet, which is a message about + // `dependencies`, not a missing file: the folder is right there. + const owner = this.ownName(file); + if (owner !== this.options.plugin) { + const other = this.options.lookup?.(owner); + if (!other) { + throw new Error(`擴充功能「${owner}」尚未載入,請在 info.json 的 dependencies 加入 ${owner},讓它先載入。`); + } + return other.evaluate(file); + } + + 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; + case "electron": + return electronModule(this.options.plugin); + 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, + electron: true, +}; + +/** Named refusals: a plugin that needs one of these needs a different host. */ +const UNSUPPORTED: Record = { + "@electron/remote": "擴充功能不能用 remote 取得主視窗,請改用 ctx.TREM。", + 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..6c58bee --- /dev/null +++ b/packages/core/src/features/plugin/types.ts @@ -0,0 +1,123 @@ +/** + * 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. + */ + +/** + * 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?: 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. */ + "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?: 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. */ + 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?: LocalizedText; + author?: LocalizedText | LocalizedText[]; + 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..bc057c9 --- /dev/null +++ b/packages/core/src/features/plugin/version.ts @@ -0,0 +1,207 @@ +/** + * Version requirements, ported from `legacy/src/js/core/plugin.js` with three + * deliberate corrections: + * + * - the weekly snapshot tag is compared, so `26.1.0-26w40a` really is newer + * than `26.1.0-26w39a` (V3 treated every snapshot of a version as equal, + * because it only ever looked at the first segment of the pre-release); + * - numeric segments are compared as numbers, so `1.2.3-rc.10` is newer than + * `1.2.3-rc.9` (V3 compared them as strings); + * - a requirement may spell the space after its operator (`">= 1.0.0"`) and may + * write `==`; V3 silently failed on both, since it split on every space. + * + * Everything else is V3's, including the channel order: a release sorts above + * `-rc`, above `-pre`, above any snapshot. `26.1.0` is therefore newer than + * `26.1.0-26w39a`, which is what makes `=26.1.0` refuse to match a snapshot + * build (that requirement names the release, not the snapshot) and `>=26.1.0` + * unsatisfied on one. `compareVersions` still returns "v1 >= v2" rather than a + * three-way compare. + */ + +export interface ParsedVersion { + major: number; + minor: number; + patch: number; + prerelease: string[]; + build: string[]; + version: string; +} + +const VERSION_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+([\w.-]+))?$/; +const DIGITS_RE = /^\d+$/; +const SNAPSHOT_RE = /^(\d{2}|\d{4})w(\d{1,2})([a-z])?$/i; + +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, any other pre-release (a snapshot) = 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; +} + +/** A weekly build tag such as `26w39a`: two-digit year, week, optional letter. */ +interface WeekSnapshot { + year: number; + week: number; + letter: string; +} + +function parseSnapshot(segment: string): WeekSnapshot | null { + const match = SNAPSHOT_RE.exec(segment); + if (!match) return null; + const year = parseInt(match[1], 10); + return { + year: year < 100 ? 2000 + year : year, + week: parseInt(match[2], 10), + letter: (match[3] ?? "").toLowerCase(), + }; +} + +function order(left: number, right: number): number { + if (left === right) return 0; + return left < right ? -1 : 1; +} + +function orderText(left: string, right: string): number { + if (left === right) return 0; + return left < right ? -1 : 1; +} + +/** One `-a.b.c` segment: snapshots by year/week/letter, digits as numbers. */ +function compareSegment(left: string, right: string): number { + const leftSnapshot = parseSnapshot(left); + const rightSnapshot = parseSnapshot(right); + if (leftSnapshot && rightSnapshot) { + return ( + order(leftSnapshot.year, rightSnapshot.year) || + order(leftSnapshot.week, rightSnapshot.week) || + orderText(leftSnapshot.letter, rightSnapshot.letter) + ); + } + if (DIGITS_RE.test(left) && DIGITS_RE.test(right)) { + return order(parseInt(left, 10), parseInt(right, 10)); + } + return orderText(left, right); +} + +/** Three-way compare of the pre-release segments; the shorter one sorts first. */ +function compareSegments(left: string[], right: string[]): number { + const length = Math.max(left.length, right.length); + for (let index = 0; index < length; index += 1) { + const one = left[index]; + const other = right[index]; + // `1.2.3-rc` sorts below `1.2.3-rc.1`, the way semver counts them. + if (one === undefined) return -1; + if (other === undefined) return 1; + const result = compareSegment(one, other); + if (result !== 0) return result; + } + return 0; +} + +function compareParsed(one: ParsedVersion, other: ParsedVersion): number { + const core = order(one.major, other.major) || order(one.minor, other.minor) || order(one.patch, other.patch); + if (core !== 0) return core; + const channel = order(getVersionPriority(one.version), getVersionPriority(other.version)); + if (channel !== 0) return channel; + return compareSegments(one.prerelease, other.prerelease); +} + +export function isExactVersionMatch(v1: string, v2: string): boolean { + const parsed1 = parseVersion(v1); + const parsed2 = parseVersion(v2); + if (!parsed1 || !parsed2) return false; + return compareParsed(parsed1, parsed2) === 0; +} + +/** 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; + return compareParsed(parsed1, parsed2) >= 0; +} + +/** One `operator + version` pair, e.g. `>=1.0.0`. */ +interface VersionRange { + operator: string; + version: string; +} + +/** + * `">=1.0.0 <2.0.0"` keeps V3's meaning — every range has to hold — and the + * spelling people reach for first also works: an operator that stands alone + * takes the next token as its version, so `">= 1.0.0"` and `">=1.0.0"` are the + * same requirement, and `==` is read as `=`. + */ +function parseRanges(required: string): VersionRange[] { + const tokens = required.trim().split(/\s+/).filter(Boolean); + const ranges: VersionRange[] = []; + for (let index = 0; index < tokens.length; index += 1) { + let token = tokens[index]; + if (/^[><=]+$/.test(token) && index + 1 < tokens.length) { + index += 1; + token += tokens[index]; + } + const matched = /^[><=]+/.exec(token)?.[0]; + ranges.push({ + operator: matched === "==" ? "=" : (matched ?? ">="), + // A bare version keeps its digits: only what was matched is an operator. + version: token.slice(matched?.length ?? 0), + }); + } + return ranges; +} + +/** `">=1.0.0"`, `"<2.0.0"`, `"=1.2.3"`, or several ranges separated by spaces. */ +export function validateVersionRequirement(current: string, required: string): boolean { + const ranges = parseRanges(required); + if (ranges.length === 0) return false; + return ranges.every(({ operator, version }) => { + switch (operator) { + case "=": + return isExactVersionMatch(current, version); + case ">=": + return compareVersions(current, version); + case ">": + return compareVersions(current, version) && !isExactVersionMatch(current, version); + case "<": + return !compareVersions(current, version); + case "<=": + return !compareVersions(current, version) || isExactVersionMatch(current, version); + default: + return compareVersions(current, version); + } + }); +} + +/** `">=1.0.0 <2.0.0"` → `"大於等於 1.0.0 且 小於 2.0.0"`, for the error message. */ +export function getVersionPrefixString(required: string): string { + const prefixMap: Record = { + "=": "等於", + ">": "大於", + ">=": "大於等於", + "<": "小於", + "<=": "小於等於", + }; + return parseRanges(required) + .map(({ operator, version }) => `${prefixMap[operator] ?? "大於等於"} ${version}`) + .join(" 且 "); +} diff --git a/packages/core/src/features/settings/Extensions.tsx b/packages/core/src/features/settings/Extensions.tsx new file mode 100644 index 0000000..b9af2ef --- /dev/null +++ b/packages/core/src/features/settings/Extensions.tsx @@ -0,0 +1,286 @@ +/** + * 擴充 — 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 { ChevronRight, FolderOpen, Puzzle, Trash2 } from "lucide-react"; +import { useEffect, useState } from "react"; +import { authorNames, localizedText, pluginLoader, pluginStorageAvailable } from "../plugin"; +import { revealItemInDir } from "@tauri-apps/plugin-opener"; + +import { createLogger } from "@/lib/logger"; + +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); + // Which rows are unfolded. The details belong to the extension they describe, + // so they live inside its row instead of in a second list further down, where + // two extensions' facts were only told apart by the name on the left. + const [open, setOpen] = useState([]); + + 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]); + + // 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 ? "讀取中" : "不支援"} + +
+ ); + } + + 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) => { + const expanded = open.includes(entry.name); + return ( +
+
+ +
+ {entry.loaded && 已載入} + {/* Enabled but not running: the dependency or the signature + said no, and the reason is one unfold away. */} + {entry.enabled && !entry.loaded && 未載入} + + {entry.verified ? "已驗證" : "未驗證"} + + + {confirmRemove === entry.name ? ( + <> + + + + ) : ( + + )} +
+
+ + {expanded && ( +
+ {/* Why it is not running comes first: it is the only line + here that asks the reader to do something. */} + {entry.status && entry.status.type !== "ok" && ( +

+ {entry.status.msg} +

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

簽章:{entry.verifyError}

+ )} +

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

+

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

+

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

+ {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。

} +
+ )} +
+ ); + }) + )} +
+ +
+ +
{ + 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/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, }); } 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 (