From 4f37b6e2d076603e614bf51302343c7e66fc9de6 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Thu, 19 Nov 2026 23:54:33 +0900 Subject: [PATCH] chore(release): add runtime-only whitelist ZIP packager, harden Windows ZIP extraction, and update install docs --- .gitignore | 2 + README.md | 38 +-- README.zh-CN.md | 40 +-- sidecars/panel/backend/plugin-updater.mjs | 2 +- sidecars/panel/package.json | 1 + sidecars/panel/scripts/pack-release-zip.mjs | 264 ++++++++++++++++++++ sidecars/panel/test/release-pack.test.mjs | 105 ++++++++ 7 files changed, 412 insertions(+), 40 deletions(-) create mode 100644 sidecars/panel/scripts/pack-release-zip.mjs create mode 100644 sidecars/panel/test/release-pack.test.mjs diff --git a/.gitignore b/.gitignore index 8739bcb..524df6a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ .data/ node_modules/ plan/ +dist/ +usage-monitor.zip *.log *.dpapi .account-test-* diff --git a/README.md b/README.md index 0fd77ff..1a3af90 100644 --- a/README.md +++ b/README.md @@ -117,25 +117,7 @@ English · [简体中文](README.zh-CN.md) Keep the folder name as `usage-monitor`. **No `npm install` is needed.** -### Option 1: Git Clone - -```powershell -# Windows (PowerShell) -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" -``` - -```bash -# macOS / Linux -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor -``` - -Or ask Antigravity directly: - -```text -Clone https://github.com/yuhuan-dev/antigravity-usage-monitor to ~/.gemini/config/plugins/usage-monitor and enable the plugin -``` - -### Option 2: Release ZIP +### Option 1: Release ZIP Download [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip) and extract it into `~/.gemini/config/plugins/` so the directory path is `~/.gemini/config/plugins/usage-monitor`. @@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir +### Option 2: Git Clone + +```powershell +# Windows (PowerShell) +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" +``` + +```bash +# macOS / Linux +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor +``` + +Or ask Antigravity directly: + +```text +Clone https://github.com/yuhuan-dev/antigravity-usage-monitor with --filter=blob:none --single-branch to ~/.gemini/config/plugins/usage-monitor and enable the plugin +``` + --- ## Usage diff --git a/README.zh-CN.md b/README.zh-CN.md index 0a27513..550ec68 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -117,30 +117,12 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、 插件目录名需保持为 `usage-monitor`,**无需运行 `npm install`**。 -### 方式一:Git 克隆 - -```powershell -# Windows PowerShell -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" -``` - -```bash -# macOS / Linux -git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor -``` - -也可以直接在 Antigravity 对话中执行: - -```text -把 https://github.com/yuhuan-dev/antigravity-usage-monitor 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件 -``` - -### 方式二:下载 Release 压缩包 +### 方式一:下载 Release 压缩包 下载 [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip),解压到 `~/.gemini/config/plugins/` 下并保持文件夹名为 `usage-monitor`。
-Windows PowerShell 下载与解压命令 +Windows PowerShell 下载及解压命令 ```powershell $pluginsDir = "$env:USERPROFILE\.gemini\config\plugins" @@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
+### 方式二:Git 克隆 + +```powershell +# Windows PowerShell +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" +``` + +```bash +# macOS / Linux +git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor +``` + +也可以直接在 Antigravity 对话中执行: + +```text +把 https://github.com/yuhuan-dev/antigravity-usage-monitor 用 --filter=blob:none --single-branch 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件 +``` + --- ## 使用方式 diff --git a/sidecars/panel/backend/plugin-updater.mjs b/sidecars/panel/backend/plugin-updater.mjs index 6b27f03..2951e98 100644 --- a/sidecars/panel/backend/plugin-updater.mjs +++ b/sidecars/panel/backend/plugin-updater.mjs @@ -494,7 +494,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { '-NoProfile', '-NonInteractive', '-Command', - `Expand-Archive -LiteralPath '${zipFile.replace(/'/g, "''")}' -DestinationPath '${extractDir.replace(/'/g, "''")}' -Force`, + `Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${zipFile.replace(/'/g, "''")}', '${extractDir.replace(/'/g, "''")}')`, ]); } else { await runExecFile('unzip', ['-oq', zipFile, '-d', extractDir]); diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 6fdf3ce..9339e4e 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -6,6 +6,7 @@ "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", "scripts": { "build": "node scripts/build-bundle.mjs", + "pack:release": "node scripts/pack-release-zip.mjs", "standalone": "node standalone.mjs", "test": "node --test test/*.test.mjs" } diff --git a/sidecars/panel/scripts/pack-release-zip.mjs b/sidecars/panel/scripts/pack-release-zip.mjs new file mode 100644 index 0000000..b077e95 --- /dev/null +++ b/sidecars/panel/scripts/pack-release-zip.mjs @@ -0,0 +1,264 @@ +#!/usr/bin/env node +/** + * @fileoverview Pure Node.js whitelist packager for `usage-monitor.zip`. + * + * Packs ONLY the runtime-essential plugin files (~520 KB compressed) into a + * cross-platform PKZIP archive prefixed with `usage-monitor/`, excluding dev-only + * frontend sources (`src/`), unit tests (`test/`), build scripts (`scripts/`), + * README preview PNGs (`assets/*.png`), local data (`.data/`), and planning docs (`plan/`). + */ + +import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { deflateRawSync } from 'node:zlib'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +export const DEFAULT_REPO_ROOT = resolve(__dirname, '..', '..', '..'); +export const DEFAULT_ZIP_OUT = join(DEFAULT_REPO_ROOT, 'dist', 'usage-monitor.zip'); +export const RELEASE_ARCHIVE_ROOT = 'usage-monitor'; + +const ROOT_WHITELIST = Object.freeze([ + 'plugin.json', + 'mcp_config.json', + 'pricing-catalog.json', + 'LICENSE', + 'assets/logo.svg', +]); + +const PANEL_TOP_WHITELIST = Object.freeze([ + 'sidecars/panel/sidecar.json', + 'sidecars/panel/index.html', + 'sidecars/panel/app.js', + 'sidecars/panel/styles.css', + 'sidecars/panel/main.mjs', + 'sidecars/panel/mcp-entry.mjs', + 'sidecars/panel/bridge-daemon.mjs', + 'sidecars/panel/standalone.mjs', + 'sidecars/panel/cli-statusline.mjs', + 'sidecars/panel/trajectory-metrics.mjs', +]); + +const RUNTIME_SUBDIRS = Object.freeze([ + 'sidecars/panel/backend', + 'sidecars/panel/shared', +]); + +const ALLOWED_SUBDIR_EXT_RE = /\.(?:mjs|ps1|sh|json)$/i; +const FORBIDDEN_PATH_RE = + /(?:^|\/)(?:\.git|\.data|node_modules|plan|dist|src|test|scripts)(?:\/|$)|\.png$|\.jpg$|\.jpeg$|\.webp$|\.log$|\.dpapi$/i; + +const CRC32_TABLE = (() => { + const table = new Uint32Array(256); + for (let i = 0; i < 256; i += 1) { + let c = i; + for (let k = 0; k < 8; k += 1) { + c = (c & 1) !== 0 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + table[i] = c >>> 0; + } + return table; +})(); + +function crc32(buf) { + let crc = 0xffffffff; + for (let i = 0; i < buf.length; i += 1) { + crc = CRC32_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return (crc ^ 0xffffffff) >>> 0; +} + +function toDosTimeDate(date) { + const d = date instanceof Date && Number.isFinite(date.getTime()) ? date : new Date(2026, 0, 1); + const year = Math.max(1980, Math.min(2107, d.getFullYear())); + const dosTime = + ((d.getHours() & 0x1f) << 11) | + ((d.getMinutes() & 0x3f) << 5) | + ((Math.floor(d.getSeconds() / 2)) & 0x1f); + const dosDate = + (((year - 1980) & 0x7f) << 9) | + (((d.getMonth() + 1) & 0x0f) << 5) | + (d.getDate() & 0x1f); + return { dosTime, dosDate }; +} + +function collectRuntimeSubdirFiles(repoRoot, relDir, out) { + const absDir = join(repoRoot, relDir); + if (!existsSync(absDir)) { + throw new Error(`Missing required runtime directory: ${relDir}`); + } + const entries = readdirSync(absDir, { withFileTypes: true }).sort((a, b) => + a.name.localeCompare(b.name) + ); + for (const entry of entries) { + if (entry.name.startsWith('.')) continue; + const childRel = `${relDir}/${entry.name}`; + if (entry.isDirectory()) { + collectRuntimeSubdirFiles(repoRoot, childRel, out); + continue; + } + if (!entry.isFile()) continue; + if (!ALLOWED_SUBDIR_EXT_RE.test(entry.name)) continue; + if (entry.name.includes('.test.')) continue; + out.push(childRel); + } +} + +/** + * Collects the deterministic whitelist of runtime-essential repository paths + * (POSIX relative paths from `repoRoot`). + * + * @param {string} [repoRoot=DEFAULT_REPO_ROOT] + * @returns {string[]} + */ +export function collectReleaseRuntimeFiles(repoRoot = DEFAULT_REPO_ROOT) { + const files = [...ROOT_WHITELIST, ...PANEL_TOP_WHITELIST]; + for (const rel of files) { + const abs = join(repoRoot, rel); + if (!existsSync(abs) || !statSync(abs).isFile()) { + throw new Error(`Missing required runtime file: ${rel}`); + } + } + for (const relDir of RUNTIME_SUBDIRS) { + collectRuntimeSubdirFiles(repoRoot, relDir, files); + } + const uniqueSorted = Array.from(new Set(files)).sort((a, b) => a.localeCompare(b)); + for (const rel of uniqueSorted) { + if (FORBIDDEN_PATH_RE.test(rel)) { + throw new Error(`Forbidden non-runtime file matched release list: ${rel}`); + } + } + return uniqueSorted; +} + +/** + * Builds a standard PKZIP (DEFLATE level 9, UTF-8 POSIX entry names) buffer in pure Node.js. + * + * @param {Array<{ name: string, data: Buffer, mtime?: Date }>} entries + * @returns {Buffer} + */ +export function buildZipBuffer(entries) { + const localParts = []; + const centralParts = []; + let offset = 0; + + for (const entry of entries) { + const nameStr = String(entry.name || '').replace(/\\/g, '/').replace(/^\/+/, ''); + const nameBuf = Buffer.from(nameStr, 'utf8'); + const rawBuf = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data || ''); + const deflated = deflateRawSync(rawBuf, { level: 9 }); + const useDeflate = deflated.length < rawBuf.length; + const payload = useDeflate ? deflated : rawBuf; + const method = useDeflate ? 8 : 0; + const checksum = crc32(rawBuf); + const { dosTime, dosDate } = toDosTimeDate(entry.mtime); + + const localHeader = Buffer.alloc(30); + localHeader.writeUInt32LE(0x04034b50, 0); + localHeader.writeUInt16LE(20, 4); // version needed: 2.0 + localHeader.writeUInt16LE(0x0800, 6); // UTF-8 filename flag + localHeader.writeUInt16LE(method, 8); + localHeader.writeUInt16LE(dosTime, 10); + localHeader.writeUInt16LE(dosDate, 12); + localHeader.writeUInt32LE(checksum, 14); + localHeader.writeUInt32LE(payload.length, 18); + localHeader.writeUInt32LE(rawBuf.length, 22); + localHeader.writeUInt16LE(nameBuf.length, 26); + localHeader.writeUInt16LE(0, 28); + + localParts.push(localHeader, nameBuf, payload); + + const centralHeader = Buffer.alloc(46); + centralHeader.writeUInt32LE(0x02014b50, 0); + centralHeader.writeUInt16LE((3 << 8) | 20, 4); // version made by: Unix / 2.0 + centralHeader.writeUInt16LE(20, 6); // version needed: 2.0 + centralHeader.writeUInt16LE(0x0800, 8); // UTF-8 filename flag + centralHeader.writeUInt16LE(method, 10); + centralHeader.writeUInt16LE(dosTime, 12); + centralHeader.writeUInt16LE(dosDate, 14); + centralHeader.writeUInt32LE(checksum, 16); + centralHeader.writeUInt32LE(payload.length, 20); + centralHeader.writeUInt32LE(rawBuf.length, 24); + centralHeader.writeUInt16LE(nameBuf.length, 28); + centralHeader.writeUInt16LE(0, 30); + centralHeader.writeUInt16LE(0, 32); + centralHeader.writeUInt16LE(0, 34); + centralHeader.writeUInt16LE(0, 36); + centralHeader.writeUInt32LE((0o100644 << 16) >>> 0, 38); // regular file mode + centralHeader.writeUInt32LE(offset, 42); + + centralParts.push(centralHeader, nameBuf); + offset += localHeader.length + nameBuf.length + payload.length; + } + + const centralDirBuf = Buffer.concat(centralParts); + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(0, 4); + eocd.writeUInt16LE(0, 6); + eocd.writeUInt16LE(entries.length, 8); + eocd.writeUInt16LE(entries.length, 10); + eocd.writeUInt32LE(centralDirBuf.length, 12); + eocd.writeUInt32LE(offset, 16); + eocd.writeUInt16LE(0, 20); + + return Buffer.concat([...localParts, centralDirBuf, eocd]); +} + +/** + * Packs the runtime-only `usage-monitor.zip` release bundle. + * + * @param {{ repoRoot?: string, outFile?: string, rootPrefix?: string }} [options] + */ +export function packReleaseZip({ + repoRoot = DEFAULT_REPO_ROOT, + outFile = DEFAULT_ZIP_OUT, + rootPrefix = RELEASE_ARCHIVE_ROOT, +} = {}) { + const relFiles = collectReleaseRuntimeFiles(repoRoot); + let totalRawBytes = 0; + const zipEntries = relFiles.map((rel) => { + const abs = join(repoRoot, rel); + const data = readFileSync(abs); + const st = statSync(abs); + totalRawBytes += data.length; + return { + name: rootPrefix ? `${rootPrefix}/${rel}` : rel, + data, + mtime: st.mtime, + }; + }); + + const zipBuf = buildZipBuffer(zipEntries); + mkdirSync(dirname(outFile), { recursive: true }); + writeFileSync(outFile, zipBuf); + + return { + outFile, + fileCount: relFiles.length, + files: relFiles, + rawBytes: totalRawBytes, + zipBytes: zipBuf.length, + }; +} + +function parseCliOutArg(argv) { + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--out' && argv[i + 1]) { + return resolve(argv[i + 1]); + } + if (arg.startsWith('--out=')) { + return resolve(arg.slice(6)); + } + } + return DEFAULT_ZIP_OUT; +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const outFile = parseCliOutArg(process.argv.slice(2)); + const summary = packReleaseZip({ repoRoot: DEFAULT_REPO_ROOT, outFile }); + console.log( + `Packed ${summary.outFile} (${summary.fileCount} runtime files, raw ${(summary.rawBytes / 1024).toFixed(1)} KB -> zip ${(summary.zipBytes / 1024).toFixed(1)} KB)` + ); +} diff --git a/sidecars/panel/test/release-pack.test.mjs b/sidecars/panel/test/release-pack.test.mjs new file mode 100644 index 0000000..0cfec53 --- /dev/null +++ b/sidecars/panel/test/release-pack.test.mjs @@ -0,0 +1,105 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { + DEFAULT_REPO_ROOT, + collectReleaseRuntimeFiles, + packReleaseZip, +} from '../scripts/pack-release-zip.mjs'; + +test('pack-release-zip ships only runtime-essential files, excludes dev bloat, and extracts a self-contained runnable plugin', async (t) => { + const relFiles = collectReleaseRuntimeFiles(DEFAULT_REPO_ROOT); + + // Required runtime files exist in whitelist + for (const mustHave of [ + 'plugin.json', + 'mcp_config.json', + 'pricing-catalog.json', + 'LICENSE', + 'assets/logo.svg', + 'sidecars/panel/sidecar.json', + 'sidecars/panel/index.html', + 'sidecars/panel/app.js', + 'sidecars/panel/styles.css', + 'sidecars/panel/main.mjs', + 'sidecars/panel/mcp-entry.mjs', + 'sidecars/panel/bridge-daemon.mjs', + 'sidecars/panel/standalone.mjs', + 'sidecars/panel/cli-statusline.mjs', + 'sidecars/panel/trajectory-metrics.mjs', + 'sidecars/panel/backend/api-actions.mjs', + 'sidecars/panel/backend/account-credentials.ps1', + 'sidecars/panel/shared/settings-normalization.mjs', + ]) { + assert.ok(relFiles.includes(mustHave), `Release whitelist must include ${mustHave}`); + } + + // Non-runtime dev/doc/test/preview files must NEVER enter the release ZIP + for (const rel of relFiles) { + assert.doesNotMatch(rel, /^sidecars\/panel\/(?:src|test|scripts)\//); + assert.doesNotMatch(rel, /\.png$/i); + assert.doesNotMatch(rel, /^README/i); + assert.doesNotMatch(rel, /^\.gitignore$/); + assert.doesNotMatch(rel, /(?:^|\/)(?:\.git|\.data|node_modules|plan|dist)(?:\/|$)/); + } + assert.equal(relFiles.includes('sidecars/panel/package.json'), false); + + const workDir = mkdtempSync(join(tmpdir(), 'ag-um-pack-test-')); + t.after(() => { + try { + rmSync(workDir, { recursive: true, force: true }); + } catch { + // ignore temp cleanup error + } + }); + + const zipPath = join(workDir, 'usage-monitor.zip'); + const extractDir = join(workDir, 'extracted'); + const summary = packReleaseZip({ repoRoot: DEFAULT_REPO_ROOT, outFile: zipPath }); + + assert.ok(existsSync(zipPath)); + assert.ok(summary.zipBytes > 100 * 1024, 'ZIP should contain compiled assets and backend'); + assert.ok( + summary.zipBytes < 750 * 1024, + `Runtime-only ZIP should stay compact (<750 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB` + ); + + // Extract via OS-native expander (same path used by plugin-updater.mjs, where extractDir already exists) + mkdirSync(extractDir, { recursive: true }); + if (process.platform === 'win32') { + execFileSync( + 'powershell.exe', + [ + '-NoProfile', + '-NonInteractive', + '-Command', + `Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${zipPath.replace(/'/g, "''")}', '${extractDir.replace(/'/g, "''")}')`, + ], + { stdio: 'pipe', windowsHide: true } + ); + } else { + execFileSync('unzip', ['-oq', zipPath, '-d', extractDir], { stdio: 'pipe' }); + } + + const pluginRoot = join(extractDir, 'usage-monitor'); + assert.ok(existsSync(join(pluginRoot, 'plugin.json'))); + const manifest = JSON.parse(readFileSync(join(pluginRoot, 'plugin.json'), 'utf8')); + assert.equal(manifest.name, 'usage-monitor'); + assert.ok(existsSync(join(pluginRoot, manifest.logo))); + + // Verify zero broken syntax and clean standalone ESM load from the extracted clean tree (no src/, test/, package.json) + for (const rel of relFiles) { + if (rel.endsWith('.mjs') || rel === 'sidecars/panel/app.js') { + execFileSync(process.execPath, ['--check', join(pluginRoot, rel)], { stdio: 'pipe' }); + } + } + + const apiMod = await import(pathToFileURL(join(pluginRoot, 'sidecars/panel/backend/api-actions.mjs')).href); + assert.equal(typeof apiMod.executeTelemetryAction, 'function'); + const cliMod = await import(pathToFileURL(join(pluginRoot, 'sidecars/panel/cli-statusline.mjs')).href); + assert.equal(typeof cliMod.runCliStatusLineMain, 'function'); +});