From fd472edb7e9f0c6e3e4f7edc9012800109c9e420 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:58:51 -0400 Subject: [PATCH 01/12] feat(ui-plugins): add DB Admin Generator (db-admin-generator) --- marketplace.json | 50 +++++++++++++++++++++++++++++++ pnpm-lock.yaml | 77 ++++++++++++++++++++++-------------------------- 2 files changed, 86 insertions(+), 41 deletions(-) diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..8d6ff770 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,56 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "db-admin-generator", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/db-admin-generator", + "displayName": "DB Admin Generator", + "displayName_i18n": { + "en": "DB Admin Generator", + "zh-CN": "数据库转管理后台" + }, + "description": "Turn a SQLite database into a working admin panel: reads the schema (tables, views, keys, foreign keys, CHECK options, required and unique columns), lets you pick tables, operations and roles (admin / editor / viewer), and generates a dependency-free Node.js server plus browser UI with sign-in, search, filters, sorting, paging and forms validated against the schema. The generated admin is then started against a temporary copy of the database and self-tested over HTTP (permissions, validation, CRUD, SQL injection). Your database is never modified. Postgres and MySQL are not supported yet.", + "description_i18n": { + "en": "Turn a SQLite database into a working admin panel: reads the schema (tables, views, keys, foreign keys, CHECK options, required and unique columns), lets you pick tables, operations and roles (admin / editor / viewer), and generates a dependency-free Node.js server plus browser UI with sign-in, search, filters, sorting, paging and forms validated against the schema. The generated admin is then started against a temporary copy of the database and self-tested over HTTP (permissions, validation, CRUD, SQL injection). Your database is never modified. Postgres and MySQL are not supported yet.", + "zh-CN": "把 SQLite 数据库变成能用的管理后台:读取表结构(表、视图、主键、外键、CHECK 选项、必填和唯一列),选择要管理的表、操作和角色(admin / editor / viewer),生成没有第三方依赖的 Node.js 服务器和网页界面,带登录、搜索、筛选、排序、分页,以及按数据库结构校验的表单。生成后会用数据库的临时副本实际启动,并通过 HTTP 自测(权限、校验、增删改查、SQL 注入)。不会修改你的数据库。暂不支持 Postgres 和 MySQL。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "developer-tools", + "keywords": [ + "database", + "sqlite", + "admin panel", + "crud", + "back office", + "roles", + "node", + "generator", + "数据库", + "管理后台", + "增删改查", + "权限" + ], + "examplePrompts": [ + "Generate an admin panel for data/shop.db", + "Make a read-only admin for the customers and orders tables", + "Re-run the self-test on the generated admin" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "给 data/shop.db 生成一个管理后台", + "做一个只读后台,只看客户表和订单表", + "重新自测生成的管理后台" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..8600c0b7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -46,6 +46,37 @@ importers: ui-plugins/craft-runtime: {} + ui-plugins/db-admin-generator: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + typescript: + specifier: 6.0.2 + version: 6.0.2 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + ui-plugins/deckcraft: {} ui-plugins/designcraft: {} @@ -2475,10 +2506,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2741,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -3068,10 +3092,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3383,18 +3403,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3742,7 +3754,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -4285,11 +4297,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5809,13 +5821,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5879,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6054,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6406,8 +6410,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6745,7 +6747,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6779,15 +6781,8 @@ snapshots: tinybench@2.9.0: {} - tinyexec@1.1.1: {} - tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) From 517b5fafdc40e0c669c447008f3367778beee8a0 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:59:25 -0400 Subject: [PATCH 02/12] feat(ui-plugins): add DB Admin Generator (db-admin-generator) --- external_plugins/db-admin-generator/LICENSE | 21 ++++++ external_plugins/db-admin-generator/README.md | 73 +++++++++++++++++++ .../db-admin-generator/README_CN.md | 73 +++++++++++++++++++ 3 files changed, 167 insertions(+) create mode 100644 external_plugins/db-admin-generator/LICENSE create mode 100644 external_plugins/db-admin-generator/README.md create mode 100644 external_plugins/db-admin-generator/README_CN.md diff --git a/external_plugins/db-admin-generator/LICENSE b/external_plugins/db-admin-generator/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/db-admin-generator/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/db-admin-generator/README.md b/external_plugins/db-admin-generator/README.md new file mode 100644 index 00000000..feaf7ac6 --- /dev/null +++ b/external_plugins/db-admin-generator/README.md @@ -0,0 +1,73 @@ +# DB Admin Generator + +Turn a **SQLite database** into a working **admin panel**: sign-in, roles, a list per table with search and filters, and add/edit/delete forms that follow the database rules. The generated admin has **no third-party dependencies**; it needs only Node.js 22.13+. Before you get it, it is **started and self-tested** against a temporary copy of your database. + +## What it does + +- **Reads the schema** (read-only): + - Tables and views, primary keys (or rowid), foreign keys, and `CHECK (col IN (…))` options. + - Required (NOT NULL without default), unique and `VARCHAR(n)` lengths. + - Booleans, dates and datetimes, email, phone and URL columns, and which tables reference which. +- **Plan**: + - Pick the tables and the operations allowed on each (read / create / update / delete). + - Pick what each role may do: **admin** can do everything, **editor** defaults to read/create/update, **viewer** to read only. + - Pick the column shown when other tables refer to a row. + - Password-, hash- and token-like columns are hidden by default (never sent to the browser). Migration tables are left out by default. +- **Generates** `-admin/`: + - `server.mjs`: `node:http` + `node:sqlite`. It provides: + - Sign-in with salted scrypt passwords and an HMAC-signed HttpOnly SameSite=Strict cookie. + - Role checks on the server, parameterised SQL with identifiers from the schema only, a CSRF header check and a sign-in lockout after 5 failures. + - Friendly messages for UNIQUE / foreign-key / CHECK conflicts, and an `audit.log` of every change. + - `public/`: a browser UI with no inline scripts and a strict CSP: + - A sidebar of tables and a list with search, filters (options, yes/no, references), sorting and paging. References show the referenced row's name. + - A form per row: dropdowns for references and options, date and checkbox inputs, required marks and max length. Server errors appear on the field. + - Read-only mode for viewers and views. Chinese or English. + - `admin.config.json` (editable), `README.md`, `package.json`, `.gitignore`. + - User CLI: `node server.mjs user add `, `user passwd`, `user list`, `user remove`. +- **Self-test**: the admin is started on a free port against a **temporary copy** of the database. It is then checked over HTTP, about 90 checks for the sample shop: + - Sign-in for each role and rejection of wrong passwords. + - Listing every table (row counts match), search, sorting, and SQL-injection attempts. + - Required-field and type errors, then create → read → update → delete. + - Duplicate unique values (409), and deleting a row that is still referenced (409). + - Viewer and editor permissions, and the audit log. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Generate an admin panel for data/shop.db" +- "Make a read-only admin for the customers and orders tables" +- "Re-run the self-test on the generated admin" + +Or use the panel: choose the database, **Read schema**, adjust tables, operations and roles, then **Generate & self-test**. Then run it: + +```bash +cd shop-admin +node server.mjs # http://127.0.0.1:8787 — the first start creates "admin" and prints its password +``` + +## Tools + +| Tool | Purpose | +|---|---| +| `db_inspect` | Read the schema and propose a plan (writes nothing) | +| `db_generate` | Write the admin folder, then self-test it | +| `db_selftest` | Run the self-test again (for example after editing the generated code) | + +## Scope (v0.1) + +- **SQLite only.** Postgres and MySQL are not supported yet (a Postgres version needs a database to test against). +- Single-column foreign keys become dropdowns; composite foreign keys are shown as plain values. +- No schema changes or migrations, no file uploads or BLOB editing, no per-row permissions. +- Use a test copy of the database while you try it. The plugin itself never writes to the database; the generated admin does, once you run it. +- Listens on 127.0.0.1 by default. Put it behind HTTPS before sharing it on a network. + +## Privacy, network and files + +- Runs locally with no network access and no API keys. The self-test talks only to 127.0.0.1. +- Reads the database read-only. Writes `/` and `.db-admin-generator/plans.json`. The self-test's temporary copy, test users and passwords are deleted afterwards. +- Needs Node.js 22.13 or newer for `node:sqlite`, both in ZCode and for running the generated admin. + +## License + +MIT. diff --git a/external_plugins/db-admin-generator/README_CN.md b/external_plugins/db-admin-generator/README_CN.md new file mode 100644 index 00000000..e40527ea --- /dev/null +++ b/external_plugins/db-admin-generator/README_CN.md @@ -0,0 +1,73 @@ +# 数据库转管理后台 + +把 **SQLite 数据库**变成能直接用的**管理后台**:有登录和角色,每张表一个列表(支持搜索和筛选),新增、修改、删除表单都遵守数据库的规则。生成的后台**没有第三方依赖**,只需要 Node.js 22.13 以上。交给你之前,插件会先用数据库的**临时副本**把它**真正启动并自测**一遍。 + +## 功能 + +- **读取表结构**(只读): + - 表和视图、主键(或 rowid)、外键、`CHECK (col IN (…))` 的选项。 + - 必填列(NOT NULL 且没有默认值)、唯一列、`VARCHAR(n)` 的长度。 + - 布尔、日期和时间、邮箱、电话、链接列,以及表之间的引用关系。 +- **规划**: + - 勾选要管理的表,以及每张表允许的操作(查 / 增 / 改 / 删)。 + - 设置每个角色能做什么:**admin** 拥有全部权限,**editor** 默认可以查、增、改,**viewer** 只能查看。 + - 选择其他表引用这一行时显示哪一列。 + - 名字像密码、哈希、令牌的列默认隐藏,永远不会发到浏览器;迁移记录表默认不纳入。 +- **生成** `<数据库名>-admin/`: + - `server.mjs`:基于 `node:http` + `node:sqlite`,提供: + - 登录:密码用 scrypt 加盐哈希,会话 Cookie 带 HMAC 签名,并设置 HttpOnly 和 SameSite=Strict。 + - 安全:权限在服务器端检查;SQL 全部参数化,表名和列名只来自表结构;有防 CSRF 的请求头检查;连续输错 5 次密码会锁定。 + - 唯一、外键、CHECK 冲突给出易懂的提示;每次修改都写入 `audit.log`。 + - `public/`:网页界面,没有内联脚本,使用严格 CSP: + - 侧边栏列出各表;列表支持搜索、筛选(选项、是/否、引用)、排序和分页;引用列显示被引用记录的名称。 + - 每行一个表单:引用和选项用下拉框,日期用日期选择器,布尔用复选框;标出必填项和长度上限;服务器返回的错误显示在对应字段下面。 + - viewer 角色和视图是只读的;界面可选中文或英文。 + - `admin.config.json`(可以手动修改)、`README.md`、`package.json`、`.gitignore`。 + - 用户命令:`node server.mjs user add <名字> <角色>`、`user passwd`、`user list`、`user remove`。 +- **自测**:用数据库的**临时副本**,在空闲端口上启动后台,通过 HTTP 检查(示例店铺数据库约 90 项): + - 每种角色都能登录,错误密码被拒绝。 + - 每张表都能列出(行数一致),搜索、排序正常,SQL 注入尝试无效。 + - 必填项和类型错误会被拦下;新增 → 读取 → 修改 → 删除都能完成。 + - 唯一值重复返回 409;删除仍被引用的记录也返回 409。 + - viewer 和 editor 的权限限制生效,修改写入了审计日志。 + +## 使用 + +在 ZCode Desktop 里对助手说: + +- “给 data/shop.db 生成一个管理后台” +- “做一个只读后台,只看客户表和订单表” +- “重新自测生成的管理后台” + +也可以用面板:选择数据库,点 **读取结构**,调整表、操作和角色,然后点 **生成管理后台并自测**。生成后这样运行: + +```bash +cd shop-admin +node server.mjs # http://127.0.0.1:8787,第一次启动会创建 admin 用户并打印密码 +``` + +## 工具 + +| 工具 | 作用 | +|---|---| +| `db_inspect` | 读取表结构并给出建议方案(不写任何文件) | +| `db_generate` | 生成管理后台目录,然后自测 | +| `db_selftest` | 重新自测,例如手动改过生成的代码之后 | + +## 范围(v0.1) + +- **只支持 SQLite。** 暂不支持 Postgres 和 MySQL(Postgres 版本需要有数据库可以实际测试)。 +- 单列外键会显示为下拉框;复合外键按普通值显示。 +- 不改表结构,不做迁移,不支持文件上传和 BLOB 编辑,也没有行级权限。 +- 试用时请用数据库的测试副本。插件本身从不写数据库;但生成的后台运行之后会写。 +- 默认只监听 127.0.0.1。要在网络上共享,请先放到 HTTPS 后面。 + +## 隐私、网络与文件 + +- 全部在本地运行,不联网,不需要 API Key。自测只访问 127.0.0.1。 +- 以只读方式读取数据库,写入 `<输出目录>/` 和 `.db-admin-generator/plans.json`。自测用的临时副本、测试用户和密码用完即删。 +- ZCode 里运行插件和运行生成的后台,都需要 Node.js 22.13 或更新版本(`node:sqlite`)。 + +## 许可证 + +MIT。 From 68e762388ab074db0cfe6def0238729425fd4736 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:00:00 -0400 Subject: [PATCH 03/12] feat(ui-plugins): add DB Admin Generator (db-admin-generator) --- ui-plugins/db-admin-generator/package.json | 32 +++++++++++++++++++ ui-plugins/db-admin-generator/tsconfig.json | 14 ++++++++ .../db-admin-generator/vitest.config.ts | 2 ++ 3 files changed, 48 insertions(+) create mode 100644 ui-plugins/db-admin-generator/package.json create mode 100644 ui-plugins/db-admin-generator/tsconfig.json create mode 100644 ui-plugins/db-admin-generator/vitest.config.ts diff --git a/ui-plugins/db-admin-generator/package.json b/ui-plugins/db-admin-generator/package.json new file mode 100644 index 00000000..c627396c --- /dev/null +++ b/ui-plugins/db-admin-generator/package.json @@ -0,0 +1,32 @@ +{ + "name": "@penova/plugin-db-admin-generator", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "DB Admin Generator" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/db-admin-generator/tsconfig.json b/ui-plugins/db-admin-generator/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/db-admin-generator/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/db-admin-generator/vitest.config.ts b/ui-plugins/db-admin-generator/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/db-admin-generator/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } }); From 6ae0641baa5e3e2e40d217f6a07cf907734be2c4 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:00:31 -0400 Subject: [PATCH 04/12] feat(ui-plugins): add DB Admin Generator (db-admin-generator) --- .../.zcode-plugin/plugin.json | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 external_plugins/db-admin-generator/.zcode-plugin/plugin.json diff --git a/external_plugins/db-admin-generator/.zcode-plugin/plugin.json b/external_plugins/db-admin-generator/.zcode-plugin/plugin.json new file mode 100644 index 00000000..45527f09 --- /dev/null +++ b/external_plugins/db-admin-generator/.zcode-plugin/plugin.json @@ -0,0 +1,58 @@ +{ + "name": "db-admin-generator", + "version": "0.1.0", + "description": "Turn a SQLite database into a working admin panel: reads the schema (tables, views, keys, foreign keys, CHECK options, required and unique columns), lets you pick tables, operations and roles (admin / editor / viewer), and generates a dependency-free Node.js server plus browser UI with sign-in, search, filters, sorting, paging and forms validated against the schema. The generated admin is then started against a temporary copy of the database and self-tested over HTTP (permissions, validation, CRUD, SQL injection). Your database is never modified. Postgres and MySQL are not supported yet.", + "description_i18n": { + "en": "Turn a SQLite database into a working admin panel: reads the schema (tables, views, keys, foreign keys, CHECK options, required and unique columns), lets you pick tables, operations and roles (admin / editor / viewer), and generates a dependency-free Node.js server plus browser UI with sign-in, search, filters, sorting, paging and forms validated against the schema. The generated admin is then started against a temporary copy of the database and self-tested over HTTP (permissions, validation, CRUD, SQL injection). Your database is never modified. Postgres and MySQL are not supported yet.", + "zh-CN": "把 SQLite 数据库变成能用的管理后台:读取表结构(表、视图、主键、外键、CHECK 选项、必填和唯一列),选择要管理的表、操作和角色(admin / editor / viewer),生成没有第三方依赖的 Node.js 服务器和网页界面,带登录、搜索、筛选、排序、分页,以及按数据库结构校验的表单。生成后会用数据库的临时副本实际启动,并通过 HTTP 自测(权限、校验、增删改查、SQL 注入)。不会修改你的数据库。暂不支持 Postgres 和 MySQL。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "database", + "sqlite", + "admin panel", + "crud", + "back office", + "roles", + "node", + "generator", + "数据库", + "管理后台", + "增删改查", + "权限" + ], + "skills": "skills", + "mcpServers": { + "db-admin-generator": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "数据库转管理后台", + "en-US": "DB Admin Generator" + }, + "icon": "database", + "server": "db-admin-generator", + "resourceUri": "ui://db-admin-generator/panel.html", + "availability": "session" + } + ] + } +} From d4ff4d53f0a097587c411f03c54a5e0625089155 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:01:07 -0400 Subject: [PATCH 05/12] feat(ui-plugins): add DB Admin Generator (db-admin-generator) --- .../db-admin-generator/scripts/build.mjs | 77 +++++++++ ui-plugins/db-admin-generator/scripts/e2e.mts | 139 +++++++++++++++ .../db-admin-generator/scripts/harness.mjs | 162 ++++++++++++++++++ .../db-admin-generator/scripts/licenses.mjs | 43 +++++ 4 files changed, 421 insertions(+) create mode 100644 ui-plugins/db-admin-generator/scripts/build.mjs create mode 100644 ui-plugins/db-admin-generator/scripts/e2e.mts create mode 100644 ui-plugins/db-admin-generator/scripts/harness.mjs create mode 100644 ui-plugins/db-admin-generator/scripts/licenses.mjs diff --git a/ui-plugins/db-admin-generator/scripts/build.mjs b/ui-plugins/db-admin-generator/scripts/build.mjs new file mode 100644 index 00000000..ab8be44e --- /dev/null +++ b/ui-plugins/db-admin-generator/scripts/build.mjs @@ -0,0 +1,77 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `${pkg.zcode?.title ?? pkg.name}
`; +const htmlBytes = Buffer.byteLength(html); +if (htmlBytes > 4 * 1024 * 1024 - 64 * 1024) throw new Error(`panel.html is ${Math.round(htmlBytes / 1024)} KiB; keep it below 4 MiB`); +await writeFile(join(dist, "ui/panel.html"), html); + +// 用不到、且许可证不明的可选依赖(package.json 的 zcode.stub)替换为空模块。 +const stubs = pkg.zcode?.stub ?? []; +const stubPlugin = { + name: "stub", + setup(b) { + if (!stubs.length) return; + const filter = new RegExp(`^(${stubs.map((s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})$`); + b.onResolve({ filter }, (args) => ({ path: args.path, namespace: "stub" })); + b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ contents: "module.exports = {};", loader: "js" })); + }, +}; + +const server = await build({ + plugins: [stubPlugin], + metafile: true, + entryPoints: [join(root, "src/main.ts")], + outfile: join(dist, "server.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node22", + legalComments: "none", + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url);', + }, +}); + +// 运行时需要的 wasm 等文件(package.json 的 zcode.assets:{ 包内路径: 输出文件名 })。 +const require = createRequire(join(root, "package.json")); +for (const [from, to] of Object.entries(pkg.zcode?.assets ?? {})) await copyFile(require.resolve(from), join(dist, to)); + +// 整个目录(package.json 的 zcode.dirs:{ "包名:子目录": 输出目录 }),例如 pdf.js 的 CMap。 +for (const [spec, to] of Object.entries(pkg.zcode?.dirs ?? {})) { + const [name, sub] = spec.split(":"); + const base = dirname(require.resolve(`${name}/package.json`)); + await cp(join(base, sub), join(dist, to), { recursive: true, filter: (path) => !/(_nowasm_fallback\.js|quickjs-eval\.(js|wasm))$/.test(path) }); +} + +// 生成的管理后台的运行时文件(原样复制到输出目录)。 +await cp(join(root, "src/runtime"), join(dist, "runtime"), { recursive: true }); + +await writeNotices([ui.metafile, server.metafile], join(dist, "THIRD_PARTY_NOTICES.txt"), Object.keys(pkg.zcode?.assets ?? {})); +process.stdout.write(`${pkg.name}: panel ${Math.round(htmlBytes / 1024)} KiB, server ${Math.round((await readFile(join(dist, "server.mjs"))).length / 1024)} KiB\n`); diff --git a/ui-plugins/db-admin-generator/scripts/e2e.mts b/ui-plugins/db-admin-generator/scripts/e2e.mts new file mode 100644 index 00000000..ff9506b3 --- /dev/null +++ b/ui-plugins/db-admin-generator/scripts/e2e.mts @@ -0,0 +1,139 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板(读结构 → 调整 → 生成并自测); +// 然后真正启动生成的管理后台,用 Chrome 以 editor / viewer / admin 三种角色操作:登录、搜索、筛选、排序、表单校验、唯一冲突、增改删、外键保护。需要 Chrome。 +import assert from "node:assert/strict"; +import { execFileSync, spawn } from "node:child_process"; +import { mkdirSync } from "node:fs"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "db-admin-generator-shots"); +mkdirSync(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "dbadm-e2e-")); +mkdirSync(join(workspace, "data")); +execFileSync(process.execPath, ["--no-warnings", process.env.DB_SAMPLE ?? "/workspace/zcode-new-plugins/samples/db/make-db.mjs", join(workspace, "data/harbor-bikes.db")]); +const harness = await startHarness({ workspace }); +const step = (t: string) => process.stdout.write(`• ${t}\n`); +let admin: ReturnType | undefined; +try { + const { outer, frame, context } = await harness.open("?locale=zh-CN", { width: 1440, height: 1000 }); + step("panel: read the schema, adjust, generate + self-test"); + await frame.locator("select.db").selectOption("data/harbor-bikes.db"); + await frame.locator("button.inspect").click(); + await frame.locator("tr[data-t='bikes']").waitFor({ timeout: 20_000 }); + assert.ok(await frame.locator("tr[data-t='open_rentals'] input[data-op='create']").isDisabled(), "views are read-only"); + await frame.locator("input.title").fill("Harbor Bikes 管理后台"); + await frame.locator("select.lang").selectOption("zh"); + for (const op of ["create", "update", "delete"]) await frame.locator(`tr[data-t='audit_log'] input[data-op='${op}']`).uncheck(); + await frame.locator("button.gen").click(); + await frame.locator(".done", { hasText: "全部通过" }).waitFor({ timeout: 120_000 }); + await frame.locator(".ck.ok", { hasText: "editor cannot delete" }).first().waitFor(); + assert.equal(await frame.locator(".ck.bad").count(), 0); + await outer.screenshot({ path: join(shots, "01-panel.png") }); + + step("start the generated admin with three users"); + const dir = join(workspace, "harbor-bikes-admin"); + const env = { ...process.env, NODE_NO_WARNINGS: "1", PORT: "0" }; + for (const [u, r] of [["eva", "editor"], ["vic", "viewer"], ["ada", "admin"]]) execFileSync(process.execPath, [join(dir, "server.mjs"), "user", "add", u, r], { env: { ...env, ADMIN_PASSWORD: `pw-${u}-12345` } }); + admin = spawn(process.execPath, [join(dir, "server.mjs")], { env, stdio: ["ignore", "pipe", "pipe"] }); + const base = await new Promise((ok, fail) => { let out = ""; admin!.stdout!.on("data", (d) => { out += d; const m = /running at (http:\/\/\S+)/.exec(out); if (m) ok(m[1]); }); admin!.on("exit", (c) => fail(new Error(`admin exited ${c}`))); setTimeout(() => fail(new Error("admin start timeout")), 15_000); }); + const page = await context.newPage(); + const errs: string[] = []; + page.on("pageerror", (e) => errs.push(String(e))); + page.on("console", (m) => { if (m.type() === "error" && !/status of (400|401|403|409)/.test(m.text())) errs.push(m.text()); }); + page.on("dialog", (d) => void d.accept()); + await page.setViewportSize({ width: 1280, height: 800 }); + const login = async (u: string) => { + await page.goto(base + "/"); + await page.locator("#user").fill(u); + await page.locator("#pw").fill(`pw-${u}-12345`); + await page.locator("button[type=submit]").click(); + await page.locator("aside .role").waitFor(); + }; + + step("editor: wrong password, then sign in"); + await page.goto(base + "/"); + await page.locator("#user").fill("eva"); + await page.locator("#pw").fill("wrong-password"); + await page.locator("button[type=submit]").click(); + await page.locator(".login .err", { hasText: "用户名或密码不对" }).waitFor(); + await login("eva"); + await page.locator("aside a[data-t='bikes']").click(); + await page.locator("#count", { hasText: "/ 24" }).waitFor(); + step("search, filter, sort"); + await page.locator("#q").fill("Volt"); + await page.locator("#count", { hasText: "/ 6" }).waitFor(); + await page.locator("#q").fill(""); + await page.locator("select[data-f='category']").selectOption("kids"); + await page.locator("#count", { hasText: "/ 6" }).waitFor(); + await page.locator("tbody td", { hasText: "Kids bike" }).first().waitFor(); + await page.locator("select[data-f='category']").selectOption(""); + await page.locator("select[data-f='in_service']").selectOption("0"); + await page.locator("#count", { hasText: "/ 2" }).waitFor(); + await page.locator("select[data-f='in_service']").selectOption(""); + await page.locator("th[data-c='serial']").click(); + await page.locator("th[data-c='serial']").click(); + await page.locator("tbody tr").first().locator("td", { hasText: "HB-0024" }).waitFor(); + await page.screenshot({ path: join(shots, "02-admin-list.png") }); + + step("editor: new bike — required errors, duplicate serial (409), then save"); + await page.locator("#new").click(); + assert.ok(await page.locator("#f_in_service").isChecked(), "column default (in_service = 1) prefilled"); + await page.locator("#dlg button[type=submit]").click(); + await page.locator("#dlg .err", { hasText: "必填" }).first().waitFor(); + assert.ok((await page.locator("#dlg .err", { hasText: "必填" }).count()) >= 3); + await page.locator("#f_serial").fill("HB-0001"); + await page.locator("#f_model").fill("Volt Commuter"); + await page.locator("#f_category").selectOption("ebike"); + await page.locator("#f_frame_size").selectOption("M"); + await page.locator("#f_purchased_on").fill("2026-11-20"); + await page.locator("#dlg button[type=submit]").click(); + await page.locator("#dlg .err", { hasText: "已存在相同的值" }).waitFor(); + await page.screenshot({ path: join(shots, "03-form-validation.png") }); + await page.locator("#f_serial").fill("HB-0100"); + await page.locator("#dlg button[type=submit]").click(); + await page.locator("#count", { hasText: "/ 25" }).waitFor(); + step("editor: edit, and no delete button"); + await page.locator("tbody tr", { hasText: "HB-0100" }).click(); + await page.locator("#f_notes").fill("Demo fleet"); + assert.equal(await page.locator("#del").count(), 0, "editor has no delete"); + await page.locator("#dlg button[type=submit]").click(); + await page.locator("#dlg").waitFor({ state: "detached" }); + await page.locator("aside a[data-t='rentals']").click(); + await page.locator("tbody td .ref").first().waitFor(); + await page.locator("#logout").click(); + + step("viewer: read-only"); + await login("vic"); + await page.locator("aside a[data-t='bikes']").click(); + await page.locator("#count", { hasText: "/ 25" }).waitFor(); + assert.equal(await page.locator("#new").count(), 0); + await page.locator("tbody tr", { hasText: "HB-0100" }).click(); + await page.locator("#dlg #f_notes").waitFor(); + assert.equal(await page.locator("#dlg button[type=submit]").count(), 0); + assert.equal(await page.locator("#f_notes").inputValue(), "Demo fleet"); + await page.screenshot({ path: join(shots, "04-viewer-readonly.png") }); + await page.locator("#cancel").click(); + await page.locator("#logout").click(); + + step("admin: delete the new bike; deleting a category in use is refused"); + await login("ada"); + await page.locator("aside a[data-t='bikes']").click(); + await page.locator("tbody tr", { hasText: "HB-0100" }).click(); + await page.locator("#del").click(); + await page.locator("#count", { hasText: "/ 24" }).waitFor(); + await page.locator("aside a[data-t='categories']").click(); + await page.locator("tbody tr", { hasText: "kids" }).click(); + await page.locator("#del").click(); + await page.locator(".formerr", { hasText: "还有其他记录引用它" }).waitFor(); + await page.locator("#cancel").click(); + await page.locator("aside a[data-t='open_rentals']").click(); + await page.locator(".ro", { hasText: "只读视图" }).waitFor(); + assert.deepEqual(errs, [], "no script errors in the admin UI"); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} finally { + admin?.kill(); + await harness.close(); +} diff --git a/ui-plugins/db-admin-generator/scripts/harness.mjs b/ui-plugins/db-admin-generator/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/db-admin-generator/scripts/harness.mjs @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright-core"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +/** + * 浏览器测试宿主:真实打包的 server(stdio)+ 官方 AppBridge 宿主页 + 隔离 iframe 中的面板。 + * 宿主页用与 ZCode 相同的 CSP 约束面板。测试脚本同时扮演 Agent:经同一个 MCP 连接调用工具, + * 并像宿主一样把结果推给页面。 + */ +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +// 与 ZCode 给 MCP App 页面的限制一致:没有网络,允许 wasm(声明了 zcode/csp.wasmUnsafeEval)。 +export const PANEL_CSP = + "default-src 'none'; script-src 'self' 'unsafe-inline' blob: data: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'none'"; + +/** server:要运行的 server 入口(默认真实打包的 dist/server.mjs)。 */ +export async function startHarness({ env = {}, workspace, server = join(root, "dist/server.mjs") }) { + const client = new Client({ name: "kit-harness", version: "1" }); + const sseClients = new Set(); + client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + for (const response of sseClients) response.write(`data: ${JSON.stringify(notification.params)}\n\n`); + }); + const stderr = []; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [server], + cwd: workspace, + env: { ...process.env, ZCODE_WORKSPACE_ROOT: workspace, ...env }, + stderr: "pipe", + }); + transport.stderr?.on("data", (chunk) => stderr.push(String(chunk))); + await client.connect(transport); + const html = await readFile(join(root, "dist/ui/panel.html"), "utf8"); + const hostJs = await build({ + stdin: { + contents: ` +import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge"; +import { z } from "zod"; +const WidgetState = z.object({ method: z.literal('ui/set-widget-state'), params: z.object({ widgetState: z.unknown() }) }); +const rpc = async (method, args) => { + const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})}); + const result = await response.json(); if (!response.ok) throw Error(result.error); return result; +}; +const params = new URLSearchParams(location.search); +const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' }; +const bridge = new AppBridge(null, {name:"kit-harness",version:"1"}, { + serverTools:{}, serverResources:{ listChanged: true }, message:{text:{}}, updateModelContext:{text:{}, structuredContent:{}}, openLinks:{}, + experimental: params.get('nosub') ? { "zcode/widgetState": {} } : { "zcode/resourceSubscribe": {}, "zcode/widgetState": {} }, +}, {hostContext:{...context, "zcode/widgetState": JSON.parse(sessionStorage.getItem('widgetState') || 'null')}}); +window.__messages = []; +window.__context = []; +window.__links = []; +window.__calls = []; +window.__initializations = 0; +bridge.oncalltool = (args) => { window.__calls.push(args.name); return rpc('callTool', args); }; +bridge.onreadresource = (args) => rpc('readResource', args); +bridge.onmessage = async (params) => { window.__messages.push(params.content[0].text); return {}; }; +bridge.onupdatemodelcontext = async (params) => { window.__context.push(params); return {}; }; +bridge.onopenlink = async (params) => { window.__links.push(params.url); return {}; }; +bridge.setRequestHandler('resources/subscribe', async (request) => { await rpc('subscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler('resources/unsubscribe', async (request) => { await rpc('unsubscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler(WidgetState, async (request) => { sessionStorage.setItem('widgetState', JSON.stringify(request.params.widgetState)); return {}; }); +bridge.oninitialized = () => { window.__initializations++; }; +window.__sendToolResult = (result) => bridge.sendToolResult(result); +window.__setContext = (patch) => bridge.setHostContext({ ...context, ...patch }); +new EventSource('/events').onmessage = (event) => { + bridge.notification({ method: 'notifications/resources/updated', params: JSON.parse(event.data) }); +}; +const frame = document.querySelector('iframe'); +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = '/panel'; +`, + resolveDir: root, + sourcefile: "browser-host.mjs", + }, + bundle: true, + format: "esm", + platform: "browser", + write: false, + }); + const http = createServer(async (request, response) => { + try { + const url = new URL(request.url, "http://localhost"); + if (url.pathname === "/") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end( + '', + ); + } else if (url.pathname === "/host.js") { + response.setHeader("Content-Type", "text/javascript"); + response.end(hostJs.outputFiles[0].text); + } else if (url.pathname === "/panel") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.setHeader("Content-Security-Policy", PANEL_CSP); + response.end(html); + } else if (url.pathname === "/events") { + response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + response.write(": connected\n\n"); + sseClients.add(response); + request.on("close", () => sseClients.delete(response)); + } else if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const chunk of request) body += chunk; + const { method, args } = JSON.parse(body); + const result = + method === "readResource" + ? await client.readResource(args) + : method === "subscribe" + ? await client.subscribeResource(args) + : method === "unsubscribe" + ? await client.unsubscribeResource(args) + : await client.callTool(args, undefined, { timeout: 300_000 }); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(result ?? {})); + } else if (url.pathname === "/favicon.ico") response.writeHead(204).end(); + else response.writeHead(404).end(); + } catch (error) { + response.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: String(error) })); + } + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const base = `http://127.0.0.1:${http.address().port}`; + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: "chrome" }); + const errors = []; + const contexts = []; + + const open = async (query = "", viewport = { width: 720, height: 900 }) => { + const context = await browser.newContext({ viewport, deviceScaleFactor: 2 }); + contexts.push(context); + const outer = await context.newPage(); + outer.on("pageerror", (error) => errors.push(String(error))); + outer.on("console", (message) => { + if (message.type() === "error" && !/favicon/.test(message.text())) errors.push(message.text()); + }); + await outer.goto(`${base}/${query}`); + await outer.waitForFunction(() => window.__initializations === 1); + const frame = outer.frames().find((item) => item !== outer.mainFrame()); + assert.ok(frame, "official App iframe exists"); + return { outer, frame, context }; + }; + /** 扮演 Agent:调用工具,再像宿主一样把结果推给页面。 */ + const agent = async (outer, name, args, { expectError = false } = {}) => { + const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 }); + if (expectError) assert.ok(result.isError, `${name} should fail`); + else assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`); + if (outer) await outer.evaluate((value) => window.__sendToolResult(value), result); + return result; + }; + const close = async () => { + await browser.close().catch(() => undefined); + await client.close().catch(() => undefined); + http.close(); + }; + return { client, open, agent, close, errors, stderr, base, contexts: () => contexts.filter((context) => context.pages().length) }; +} diff --git a/ui-plugins/db-admin-generator/scripts/licenses.mjs b/ui-plugins/db-admin-generator/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/db-admin-generator/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name && pkg.version) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} From 4e98f60c1645bb72de8de172e92b6ee867118402 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:01:43 -0400 Subject: [PATCH 06/12] feat(ui-plugins): add DB Admin Generator (db-admin-generator) --- ui-plugins/db-admin-generator/src/generate.ts | 184 ++++++++++++++++++ ui-plugins/db-admin-generator/src/main.ts | 14 ++ ui-plugins/db-admin-generator/src/selftest.ts | 164 ++++++++++++++++ ui-plugins/db-admin-generator/src/server.ts | 122 ++++++++++++ 4 files changed, 484 insertions(+) create mode 100644 ui-plugins/db-admin-generator/src/generate.ts create mode 100644 ui-plugins/db-admin-generator/src/main.ts create mode 100644 ui-plugins/db-admin-generator/src/selftest.ts create mode 100644 ui-plugins/db-admin-generator/src/server.ts diff --git a/ui-plugins/db-admin-generator/src/generate.ts b/ui-plugins/db-admin-generator/src/generate.ts new file mode 100644 index 00000000..f8e8b1ee --- /dev/null +++ b/ui-plugins/db-admin-generator/src/generate.ts @@ -0,0 +1,184 @@ +import { readFile } from "node:fs/promises"; +import { basename, extname, join, relative } from "node:path"; +// @ts-expect-error plain JS runtime shared with the generated admin +import { introspect, labelColumn, required } from "./runtime/schema.mjs"; + +export type Op = "read" | "create" | "update" | "delete"; +export const OPS: Op[] = ["read", "create", "update", "delete"]; +export interface Column { name: string; type: string; kind: string; notNull: boolean; default: string | null; pk: number; unique: boolean; auto: boolean; fk?: { table: string; column: string }; options?: string[]; maxLength?: number } +export interface Table { name: string; type: "table" | "view"; sql: string; pk: string[]; rowid: boolean; columns: Column[]; rows: number; refs: { table: string; column: string }[] } +export interface TablePlan { name: string; label: string; ops: Op[]; list: string[]; search: string[]; hidden: string[]; labelColumn: string } +export interface Plan { title: string; lang: "zh" | "en"; db: string; out: string; port: number; pageSize: number; roles: Record<"admin" | "editor" | "viewer", Op[]>; tables: TablePlan[] } + +export const DEFAULT_ROLES: Plan["roles"] = { admin: ["read", "create", "update", "delete"], editor: ["read", "create", "update"], viewer: ["read"] }; +const SENSITIVE = /(^|_)(password|passwd|pwd|hash|salt|secret|token|api_?key|otp)(_|$)/i; +const INTERNAL = /(^_|migrations?$|^schema_version$|^knex_|^__)/i; + +export async function openDb(abs: string, readOnly = true) { + let mod: typeof import("node:sqlite"); + try { mod = await import("node:sqlite"); } catch { throw new Error("This needs Node.js 22.13 or newer (built-in node:sqlite)."); } + return new mod.DatabaseSync(abs, { readOnly }); +} +export function inspect(db: unknown): Table[] { return introspect(db) as Table[]; } +export const isRequired = (c: Column): boolean => required(c); + +export function slug(s: string) { return s.normalize("NFKD").replace(/[^\w-]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase().slice(0, 40) || "db"; } + +export function defaultPlan(dbRel: string, tables: Table[]): Plan { + const name = basename(dbRel, extname(dbRel)); + return { + title: `${name.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())} Admin`, lang: "en", db: dbRel, out: `${slug(name)}-admin`, port: 8787, pageSize: 25, roles: structuredClone(DEFAULT_ROLES), + tables: tables.map((t) => { + const hidden = t.columns.filter((c) => SENSITIVE.test(c.name)).map((c) => c.name); + const visible = t.columns.filter((c) => !hidden.includes(c.name)); + return { + name: t.name, label: t.name.replace(/[_-]+/g, " ").replace(/^\w/, (c) => c.toUpperCase()), + ops: INTERNAL.test(t.name) ? [] : t.type === "view" ? ["read"] : [...OPS], + list: visible.filter((c) => c.kind !== "longtext").slice(0, 7).map((c) => c.name), + search: visible.filter((c) => ["text", "email", "tel", "select", "longtext", "url"].includes(c.kind)).map((c) => c.name), + hidden, labelColumn: labelColumn(t), + }; + }), + }; +} + +export interface TablePatch { name: string; label?: string; ops?: Op[]; list?: string[]; search?: string[]; hidden?: string[]; labelColumn?: string } +export function applyPatch(plan: Plan, tables: Table[], patch: { title?: string; lang?: "zh" | "en"; out?: string; port?: number; pageSize?: number; roles?: Partial>; tables?: TablePatch[]; only?: string[] }) { + if (patch.title) plan.title = patch.title; + if (patch.lang) plan.lang = patch.lang; + if (patch.out) plan.out = patch.out.replace(/\\/g, "/").replace(/\/+$/, ""); + if (patch.port) plan.port = patch.port; + if (patch.pageSize) plan.pageSize = patch.pageSize; + for (const r of ["editor", "viewer"] as const) if (patch.roles?.[r]) plan.roles[r] = OPS.filter((o) => patch.roles![r]!.includes(o)); + if (patch.only) { const set = new Set(patch.only); for (const tp of plan.tables) if (!set.has(tp.name)) tp.ops = []; for (const n of set) if (!plan.tables.find((x) => x.name === n)) throw new Error(`No table “${n}”. Tables: ${plan.tables.map((x) => x.name).join(", ")}`); } + for (const p of patch.tables ?? []) { + const tp = plan.tables.find((x) => x.name === p.name), t = tables.find((x) => x.name === p.name); + if (!tp || !t) throw new Error(`No table “${p.name}”. Tables: ${tables.map((x) => x.name).join(", ")}`); + const cols = new Set(t.columns.map((c) => c.name)); + const check = (list: string[] | undefined, what: string) => { for (const c of list ?? []) if (!cols.has(c)) throw new Error(`${p.name}.${what}: no column “${c}”. Columns: ${[...cols].join(", ")}`); return list; }; + if (p.label) tp.label = p.label; + if (p.ops) { tp.ops = OPS.filter((o) => p.ops!.includes(o)); if (t.type === "view") tp.ops = tp.ops.filter((o) => o === "read"); if (tp.ops.length && !tp.ops.includes("read")) tp.ops.unshift("read"); } + if (p.list) tp.list = check(p.list, "list")!; + if (p.search) tp.search = check(p.search, "search")!; + if (p.hidden) tp.hidden = check(p.hidden, "hidden")!; + if (p.labelColumn) tp.labelColumn = check([p.labelColumn], "labelColumn")![0]; + } + if (!plan.tables.some((t) => t.ops.length)) throw new Error("Choose at least one table."); + return plan; +} + +/** Files of the generated admin: path (relative to the output folder) → contents. */ +export async function emit(plan: Plan, runtimeDir: string, workspaceRoot: string): Promise> { + const rt = async (p: string) => readFile(join(runtimeDir, p), "utf8"); + const zh = plan.lang === "zh"; + const dbFromOut = relative(join(workspaceRoot, plan.out), join(workspaceRoot, plan.db)).replace(/\\/g, "/"); + const enabled = plan.tables.filter((t) => t.ops.length); + const config = { + title: plan.title, lang: plan.lang, db: dbFromOut, port: plan.port, pageSize: plan.pageSize, sessionHours: 12, roles: plan.roles, + tables: enabled.map((t) => ({ name: t.name, label: t.label, ops: t.ops, list: t.list.filter((c) => !t.hidden.includes(c)), search: t.search.filter((c) => !t.hidden.includes(c)), hidden: t.hidden, labelColumn: t.labelColumn })), + }; + const matrix = (["admin", "editor", "viewer"] as const).map((r) => `| ${r} | ${plan.roles[r].join(", ") || "—"} |`).join("\n"); + const tableRows = enabled.map((t) => `| \`${t.name}\` | ${t.label} | ${t.ops.join(", ")} |${t.hidden.length ? ` ${t.hidden.join(", ")}` : " —"} |`).join("\n"); + const readme = zh ? `# ${plan.title} + +由 ZCode 的“数据库转管理后台”插件生成的管理后台。没有第三方依赖,只需要 **Node.js 22.13 或更新版本**(内置 \`node:sqlite\`)。 + +## 启动 + +\`\`\`bash +node server.mjs +\`\`\` + +打开 http://127.0.0.1:${plan.port} 。第一次启动时,如果还没有用户,会自动创建 \`admin\` 用户,并在终端里打印随机密码。 + +- 数据库:\`${dbFromOut}\`(相对于本文件夹;可用环境变量 \`ADMIN_DB\` 指定其他文件) +- 端口和地址:\`PORT\`(默认 ${plan.port})、\`HOST\`(默认 127.0.0.1,只允许本机访问) + +## 用户与角色 + +\`\`\`bash +node server.mjs user add alice editor # 添加用户,会打印随机密码;也可以用 ADMIN_PASSWORD=... 指定 +node server.mjs user passwd admin # 修改密码 +node server.mjs user list +node server.mjs user remove alice +\`\`\` + +| 角色 | 允许的操作 | +|---|---| +${matrix} + +每张表实际能做的操作 = 表的设置 ∩ 角色的权限。权限检查都在服务器端完成。 + +| 表 | 名称 | 操作 | 隐藏的列 | +|---|---|---|---| +${tableRows} + +## 安全 + +- 密码使用 scrypt 加盐哈希,保存在 \`users.json\`;会话 Cookie 带 HMAC 签名(密钥在 \`.session-secret\`),HttpOnly + SameSite=Strict,修改类请求还要求 \`X-Admin\` 请求头。 +- 同一 IP 连续输错 5 次密码,会锁定 10 分钟;所有修改都记入 \`audit.log\`。 +- 所有 SQL 都使用参数绑定,表名和列名只来自数据库结构白名单。 +- 默认只监听本机。如果要给别人用,请放在 HTTPS 反向代理后面,再设置 \`HOST=0.0.0.0\`。 +- \`users.json\`、\`.session-secret\`、\`audit.log\` 已加入 \`.gitignore\`,不要提交。 + +## 修改 + +可以直接编辑 \`admin.config.json\`(表、操作、列表列、搜索列、隐藏列、角色),重启后生效;也可以在 ZCode 里让插件重新生成。 +` : `# ${plan.title} + +Admin panel generated by the ZCode **DB Admin Generator** plugin. No third-party dependencies; needs **Node.js 22.13 or newer** (built-in \`node:sqlite\`). + +## Run + +\`\`\`bash +node server.mjs +\`\`\` + +Open http://127.0.0.1:${plan.port}. On first start with no users, an \`admin\` user is created and its random password is printed in the terminal. + +- Database: \`${dbFromOut}\` (relative to this folder; set \`ADMIN_DB\` to use another file) +- Port / address: \`PORT\` (default ${plan.port}), \`HOST\` (default 127.0.0.1, this computer only) + +## Users and roles + +\`\`\`bash +node server.mjs user add alice editor # prints a random password, or set ADMIN_PASSWORD=... +node server.mjs user passwd admin +node server.mjs user list +node server.mjs user remove alice +\`\`\` + +| Role | Allowed operations | +|---|---| +${matrix} + +What a user can do on a table = the table's operations ∩ the role's operations, enforced on the server. + +| Table | Label | Operations | Hidden columns | +|---|---|---|---| +${tableRows} + +## Security + +- Passwords are salted scrypt hashes in \`users.json\`. Session cookies are HMAC-signed (key in \`.session-secret\`), HttpOnly and SameSite=Strict, and write requests also need the \`X-Admin\` header. +- 5 wrong passwords from one IP lock sign-in for 10 minutes. Every change is appended to \`audit.log\`. +- All SQL uses bound parameters; table and column names come only from the database schema. +- Listens on this computer only by default. To share it, put it behind an HTTPS reverse proxy and set \`HOST=0.0.0.0\`. +- \`users.json\`, \`.session-secret\` and \`audit.log\` are in \`.gitignore\`; don't commit them. + +## Changing it + +Edit \`admin.config.json\` (tables, operations, list/search/hidden columns, roles) and restart, or ask the plugin in ZCode to regenerate. +`; + return { + "server.mjs": await rt("server.mjs"), + "schema.mjs": await rt("schema.mjs"), + "public/index.html": (await rt("public/index.html")).replace("Admin", `${plan.title.replace(/[<&>"]/g, "")}`), + "public/app.js": await rt("public/app.js"), + "public/style.css": await rt("public/style.css"), + "admin.config.json": JSON.stringify(config, null, 2) + "\n", + "package.json": JSON.stringify({ name: slug(plan.title), version: "0.1.0", private: true, type: "module", scripts: { start: "node server.mjs" }, engines: { node: ">=22.13" } }, null, 2) + "\n", + "README.md": readme, + ".gitignore": "users.json\n.session-secret\naudit.log\n", + }; +} diff --git a/ui-plugins/db-admin-generator/src/main.ts b/ui-plugins/db-admin-generator/src/main.ts new file mode 100644 index 00000000..ad86fd04 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/main.ts @@ -0,0 +1,14 @@ +import "./kit/console.ts"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createServer } from "./server.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const server = createServer({ + workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()), + assetRoot: here, + log: (line) => process.stderr.write(`[db-admin-generator] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/db-admin-generator/src/selftest.ts b/ui-plugins/db-admin-generator/src/selftest.ts new file mode 100644 index 00000000..e44c8726 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/selftest.ts @@ -0,0 +1,164 @@ +import { spawn, execFile } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { copyFile, mkdtemp, readFile, rm } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { type Column, type Plan, type Table, inspect, isRequired, openDb } from "./generate.ts"; + +export interface Check { name: string; ok: boolean; detail?: string } +export interface SelfTest { ok: boolean; passed: number; failed: number; checks: Check[]; ms: number } + +const run = promisify(execFile); +const nodeEnv = (extra: Record) => ({ ...process.env, ELECTRON_RUN_AS_NODE: "1", NODE_NO_WARNINGS: "1", ...extra }); + +/** Start the generated admin against a temporary copy of the database and exercise it over HTTP. The real database is never written. */ +export async function selfTest(outAbs: string, dbAbs: string, plan: Plan): Promise { + const t0 = Date.now(); + const checks: Check[] = []; + const ok = (name: string, cond: boolean, detail?: string) => { checks.push({ name, ok: !!cond, detail: cond ? undefined : detail }); return cond; }; + const tmp = await mkdtemp(join(tmpdir(), "dbadmin-test-")); + const dbCopy = join(tmp, "test.db"); + await copyFile(dbAbs, dbCopy); + for (const s of ["-wal", "-shm"]) if (existsSync(dbAbs + s)) await copyFile(dbAbs + s, dbCopy + s); + const env = nodeEnv({ ADMIN_DB: dbCopy, ADMIN_USERS: join(tmp, "users.json"), ADMIN_SECRET_FILE: join(tmp, "secret"), ADMIN_AUDIT: join(tmp, "audit.log"), PORT: "0", HOST: "127.0.0.1" }); + const pw: Record = {}; + let child: ReturnType | undefined; + try { + for (const role of ["admin", "editor", "viewer"]) { + pw[role] = randomBytes(9).toString("base64url"); + const r = await run(process.execPath, [join(outAbs, "server.mjs"), "user", "add", `test-${role}`, role], { env: { ...env, ADMIN_PASSWORD: pw[role] }, timeout: 20_000 }).catch((e) => ({ stdout: "", stderr: String(e.stderr || e.message) })); + ok(`CLI: add ${role} user`, /added test-/.test(r.stdout), r.stderr); + } + child = spawn(process.execPath, [join(outAbs, "server.mjs")], { env, stdio: ["ignore", "pipe", "pipe"] }); + let out = "", err = ""; + const port = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`server did not start in 20 s\n${err || out}`)), 20_000); + child!.stdout!.on("data", (d) => { out += d; const m = /running at http:\/\/[^:]+:(\d+)/.exec(out); if (m) { clearTimeout(timer); resolve(Number(m[1])); } }); + child!.stderr!.on("data", (d) => { err += d; }); + child!.on("exit", (code) => { clearTimeout(timer); reject(new Error(`server exited (${code}): ${err || out}`)); }); + }); + ok("server starts", true); + const base = `http://127.0.0.1:${port}`; + const req = async (method: string, path: string, body?: unknown, cookie?: string, headers: Record = { "X-Admin": "1" }) => { + const r = await fetch(base + path, { method, headers: { ...(method === "GET" ? {} : { "Content-Type": "application/json", ...headers }), ...(cookie ? { Cookie: cookie } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) }); + const text = await r.text(); + let json: any; try { json = JSON.parse(text); } catch { json = text; } + return { status: r.status, json, cookie: (r.headers.get("set-cookie") ?? "").split(";")[0] }; + }; + const home = await req("GET", "/"); + ok("serves the admin page", home.status === 200 && String(home.json).includes("/app.js"), `status ${home.status}`); + ok("API needs sign-in", (await req("GET", "/api/meta")).status === 401); + ok("wrong password rejected", (await req("POST", "/api/login", { user: "test-admin", password: "nope-nope" })).status === 401); + ok("write without X-Admin header rejected", (await req("POST", "/api/login", { user: "test-admin", password: pw.admin }, undefined, {})).status === 403); + const jar: Record = {}; + for (const role of ["admin", "editor", "viewer"]) { + const r = await req("POST", "/api/login", { user: `test-${role}`, password: pw[role] }); + if (ok(`sign in as ${role}`, r.status === 200 && !!r.cookie, `status ${r.status} ${JSON.stringify(r.json)}`)) jar[role] = r.cookie; + } + if (!jar.admin) throw new Error("admin sign-in failed"); + const meta = (await req("GET", "/api/meta", undefined, jar.admin)).json; + const enabled = plan.tables.filter((t) => t.ops.length); + ok(`meta lists ${enabled.length} table(s)`, meta.tables?.length === enabled.length, `got ${meta.tables?.length}`); + const db = await openDb(dbCopy, true); + const schema = inspect(db); + const firstValue = (table: string, col: string) => (db.prepare(`SELECT "${col.replace(/"/g, '""')}" AS v FROM "${table.replace(/"/g, '""')}" WHERE "${col.replace(/"/g, '""')}" IS NOT NULL LIMIT 1`).get() as { v: unknown } | undefined)?.v; + for (const tp of enabled) { + const t = schema.find((x) => x.name === tp.name)!; + const T = encodeURIComponent(t.name); + const list = await req("GET", `/api/t/${T}?size=5`, undefined, jar.admin); + ok(`${t.name}: list (${t.rows} rows)`, list.status === 200 && list.json.total === t.rows, `status ${list.status}, total ${list.json?.total}`); + const sc = tp.search.find((c) => !tp.hidden.includes(c)); + const sv = sc ? firstValue(t.name, sc) : undefined; + if (sc && sv != null) { const word = String(sv).slice(0, 6); const s = await req("GET", `/api/t/${T}?q=${encodeURIComponent(word)}`, undefined, jar.admin); ok(`${t.name}: search “${word}”`, s.status === 200 && s.json.total >= 1, `status ${s.status}, total ${s.json?.total}`); } + const sortCol = tp.list[1] ?? tp.list[0]; + if (sortCol) { const s = await req("GET", `/api/t/${T}?sort=${encodeURIComponent(sortCol)}&dir=desc`, undefined, jar.admin); ok(`${t.name}: sort by ${sortCol}`, s.status === 200); } + const evil = await req("GET", `/api/t/${T}?sort=${encodeURIComponent("1; DROP TABLE x--")}&q=${encodeURIComponent("' OR 1=1 --")}`, undefined, jar.admin); + ok(`${t.name}: SQL injection in sort/search is harmless`, evil.status === 200 && (!tp.search.length || evil.json.total === 0), `status ${evil.status}, total ${evil.json?.total}`); + ok(`${t.name}: unknown filter column rejected`, (await req("GET", `/api/t/${T}?f.nope=1`, undefined, jar.admin)).status === 400); + for (const c of t.columns.filter((x) => x.fk && !tp.hidden.includes(x.name))) { + const o = await req("GET", `/api/t/${T}/options/${encodeURIComponent(c.name)}`, undefined, jar.admin); + ok(`${t.name}.${c.name}: reference options`, o.status === 200 && Array.isArray(o.json.options), `status ${o.status}`); + } + if (t.type !== "table") continue; + const can = (role: keyof Plan["roles"], op: string) => tp.ops.includes(op as never) && plan.roles[role].includes(op as never); + if (can("admin", "create")) { + const req0 = t.columns.filter((c) => isRequired(c as Column) && !tp.hidden.includes(c.name)); + if (req0.length) { const e = await req("POST", `/api/t/${T}`, {}, jar.admin); ok(`${t.name}: empty form → required-field errors`, e.status === 400 && req0.every((c) => e.json.fields?.[c.name]), `status ${e.status} ${JSON.stringify(e.json.fields)}`); } + const sample = sampleRow(t, schema, firstValue, tp.hidden); + const c1 = await req("POST", `/api/t/${T}`, sample, jar.admin); + if (ok(`${t.name}: create a record`, c1.status === 201 && !!c1.json.row?._key, `status ${c1.status} ${JSON.stringify(c1.json)}`)) { + const key = encodeURIComponent(c1.json.row._key); + const got = await req("GET", `/api/t/${T}/r/${key}`, undefined, jar.admin); + ok(`${t.name}: read it back`, got.status === 200, `status ${got.status}`); + const edit = t.columns.find((c) => !c.auto && !c.pk && !c.fk && !c.options && !tp.hidden.includes(c.name) && ["text", "longtext", "integer", "number"].includes(c.kind) && !c.unique); + if (edit && can("admin", "update")) { + const nv = edit.kind === "integer" || edit.kind === "number" ? 7 : "Self-test edit"; + const u = await req("PUT", `/api/t/${T}/r/${key}`, { [edit.name]: nv }, jar.admin); + ok(`${t.name}: update ${edit.name}`, u.status === 200 && u.json.row?.[edit.name] == nv, `status ${u.status} ${JSON.stringify(u.json)}`); + const bad = t.columns.find((c) => (c.kind === "integer" || c.kind === "number") && !c.auto && !c.fk && !tp.hidden.includes(c.name)); + if (bad) { const b = await req("PUT", `/api/t/${T}/r/${key}`, { [bad.name]: "abc" }, jar.admin); ok(`${t.name}: invalid ${bad.name} rejected`, b.status === 400 && !!b.json.fields?.[bad.name], `status ${b.status}`); } + } + const uq = t.columns.find((c) => c.unique && !c.auto && !tp.hidden.includes(c.name) && c.kind !== "boolean"); + if (uq) { const dup = await req("POST", `/api/t/${T}`, sample, jar.admin); ok(`${t.name}: duplicate ${uq.name} → 409`, dup.status === 409 && !!dup.json.fields?.[uq.name], `status ${dup.status} ${JSON.stringify(dup.json)}`); } + if (jar.viewer && !can("viewer", "update")) ok(`${t.name}: viewer cannot edit`, (await req("PUT", `/api/t/${T}/r/${key}`, sample, jar.viewer)).status === 403 || !can("viewer", "read")); + if (jar.editor && can("editor", "read") && !can("editor", "delete")) ok(`${t.name}: editor cannot delete`, (await req("DELETE", `/api/t/${T}/r/${key}`, undefined, jar.editor)).status === 403); + if (can("admin", "delete")) { const d = await req("DELETE", `/api/t/${T}/r/${key}`, undefined, jar.admin); ok(`${t.name}: delete it`, d.status === 200, `status ${d.status} ${JSON.stringify(d.json)}`); } + } + if (jar.viewer && can("viewer", "read") && !can("viewer", "create")) ok(`${t.name}: viewer cannot create`, (await req("POST", `/api/t/${T}`, sample, jar.viewer)).status === 403); + } + if (t.refs.length && can("admin", "delete")) { + const ref = t.refs.find((r) => { const c = schema.find((x) => x.name === r.table)?.columns.find((x) => x.name === r.column) as (Column & { fk?: { onDelete?: string } }) | undefined; return c && c.fk && !/CASCADE|SET NULL|SET DEFAULT/i.test((c.fk as { onDelete?: string }).onDelete ?? ""); }); + if (ref) { + const fkc = schema.find((x) => x.name === ref.table)!.columns.find((x) => x.name === ref.column)!; + const used = firstValue(ref.table, ref.column); + if (used != null) { + const pkCol = fkc.fk!.column; + const keyRow = db.prepare(`SELECT ${t.rowid ? "rowid AS k" : t.pk.map((p, i) => `"${p}" AS k${i}`).join(", ")} FROM "${t.name}" WHERE "${pkCol}" = ?`).get(used as never) as Record | undefined; + if (keyRow && !t.rowid) { const d = await req("DELETE", `/api/t/${T}/r/${encodeURIComponent(JSON.stringify(t.pk.map((_, i) => keyRow[`k${i}`])))}`, undefined, jar.admin); ok(`${t.name}: deleting a record still used by ${ref.table} → 409`, d.status === 409, `status ${d.status} ${JSON.stringify(d.json)}`); } + } + } + } + } + db.close(); + const auditText = await readFile(join(tmp, "audit.log"), "utf8").catch(() => ""); + if (checks.some((c) => /create a record/.test(c.name) && c.ok)) ok("changes written to audit.log", /\tcreate\t/.test(auditText)); + const out2 = await req("POST", "/api/logout", {}, jar.admin); + ok("sign out", out2.status === 200); + } catch (e) { + ok("self-test ran to the end", false, (e as Error).message); + } finally { + child?.kill(); + await rm(tmp, { recursive: true, force: true }).catch(() => undefined); + } + const failed = checks.filter((c) => !c.ok).length; + return { ok: failed === 0, passed: checks.length - failed, failed, checks, ms: Date.now() - t0 }; +} + +function sampleRow(t: Table, schema: Table[], firstValue: (t: string, c: string) => unknown, hidden: string[]) { + const tag = randomBytes(3).toString("hex"); + const row: Record = {}; + for (const c of t.columns) { + if (c.auto || hidden.includes(c.name) || /^(created|updated)_at$/.test(c.name)) continue; + let v: unknown; + if (c.fk) v = firstValue(c.fk.table, c.fk.column); + else if (c.options) v = c.options[0]; + else switch (c.kind) { + case "boolean": v = true; break; + case "integer": v = 3; break; + case "number": v = 9.5; break; + case "date": v = new Date().toISOString().slice(0, 10); break; + case "datetime": v = new Date().toISOString().slice(0, 16).replace("T", " "); break; + case "email": v = `selftest+${tag}@example.com`; break; + case "url": v = `https://example.com/${tag}`; break; + case "tel": v = "+1 555 0100"; break; + case "longtext": v = "Created by the self-test"; break; + default: v = c.unique || c.pk ? `st-${tag}` : `Self-test ${tag}`; + } + if (typeof v === "string" && c.maxLength) v = v.slice(0, c.maxLength); + if (v !== undefined) row[c.name] = v; + } + void schema; + return row; +} diff --git a/ui-plugins/db-admin-generator/src/server.ts b/ui-plugins/db-admin-generator/src/server.ts new file mode 100644 index 00000000..3ee26f44 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/server.ts @@ -0,0 +1,122 @@ +import { open, readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { KitError, Workspace } from "./kit/workspace.ts"; +import { OPS, type Plan, type Table, applyPatch, defaultPlan, emit, inspect, openDb } from "./generate.ts"; +import { type SelfTest, selfTest } from "./selftest.ts"; + +export const NAME = "db-admin-generator"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const STORE = ".db-admin-generator/plans.json"; +const DB_EXT = [".db", ".sqlite", ".sqlite3", ".db3"]; + +export interface ServerOptions { workspaceRoot: string; assetRoot: string; log?: (line: string) => void } +interface Saved { plan: Plan; generatedAt?: string; test?: SelfTest } + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const { server, tool } = createKitServer({ name: NAME, version: VERSION, panelUri: PANEL_URI, surface: "editor", panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), log: options.log }); + const runtime = join(options.assetRoot, "runtime"); + const load = async (): Promise> => ((await ws.exists(STORE)) ? JSON.parse(await ws.readText(STORE)).plans ?? {} : {}); + const save = async (all: Record) => ws.write(STORE, JSON.stringify({ version: 1, plans: all }, null, 1) + "\n"); + + async function schemaOf(dbRel: string) { + if (!DB_EXT.some((e) => dbRel.toLowerCase().endsWith(e))) throw new KitError("unsupported", `Use a SQLite database file (${DB_EXT.join(", ")}). Postgres and MySQL are not supported in this version.`); + if (!(await ws.exists(dbRel))) throw new KitError("not_found", `${dbRel} not found.`); + const fh = await open(ws.resolve(dbRel), "r"); + const buf = Buffer.alloc(16); + try { await fh.read(buf, 0, 16, 0); } finally { await fh.close(); } + const head = buf.toString("latin1"); + if (!head.startsWith("SQLite format 3")) throw new KitError("not_sqlite", `${dbRel} is not a SQLite database.`); + let db; + try { db = await openDb(ws.resolve(dbRel), true); } catch (e) { throw new KitError("open_failed", (e as Error).message); } + try { return inspect(db); } finally { db.close(); } + } + const describeSchema = (dbRel: string, tables: Table[]) => [ + `${dbRel}: ${tables.filter((t) => t.type === "table").length} table(s), ${tables.filter((t) => t.type === "view").length} view(s).`, + ...tables.map((t) => ` ${t.type === "view" ? "view " : ""}${t.name} (${t.rows} rows; key: ${t.pk.join(", ") || (t.type === "view" ? "—" : "rowid")})${t.refs.length ? ` ← referenced by ${t.refs.map((r) => `${r.table}.${r.column}`).join(", ")}` : ""}\n ${t.columns.map((c) => `${c.name}:${c.kind}${c.notNull && c.default === null && !c.auto ? "*" : ""}${c.fk ? `→${c.fk.table}` : ""}${c.unique && !c.pk ? " unique" : ""}${c.options ? `[${c.options.join("|")}]` : ""}`).join(", ")}`), + `(* = required)`, + ].join("\n"); + const describeTest = (t: SelfTest) => `Self-test against a temporary copy of the database: ${t.passed}/${t.passed + t.failed} checks passed in ${(t.ms / 1000).toFixed(1)} s.${t.failed ? `\nFailed:\n${t.checks.filter((c) => !c.ok).map((c) => ` ✗ ${c.name}${c.detail ? ` — ${c.detail}` : ""}`).join("\n")}` : ""}`; + + tool("db_inspect", { + description: "Read a SQLite database's structure without changing it: tables, views, columns with inferred input types (text, number, date, boolean, select from CHECK IN, reference from foreign keys, email…), primary keys, required/unique columns, row counts and which tables reference which. Also returns the default admin plan (all tables, password-like columns hidden).", + input: { db: z.string().describe("Workspace path of the SQLite file (.db / .sqlite / .sqlite3)") }, readOnly: true, openPanel: true, + }, async (i) => { + const tables = await schemaOf(i.db); + const all = await load(); + const existing = Object.values(all).find((s) => s.plan.db === i.db); + const plan = existing?.plan ?? defaultPlan(i.db, tables); + return { text: describeSchema(i.db, tables), structured: { kind: "plan", plan, tables, saved: existing ?? null } }; + }); + + const tableInput = z.object({ + name: z.string(), label: z.string().optional(), + ops: z.array(z.enum(OPS as [string, ...string[]])).optional().describe("Allowed operations: read, create, update, delete ([] = leave the table out)"), + list: z.array(z.string()).optional().describe("Columns shown in the list"), search: z.array(z.string()).optional().describe("Columns searched by the search box"), + hidden: z.array(z.string()).optional().describe("Columns never sent to the browser (password hashes etc.)"), labelColumn: z.string().optional().describe("Column shown when other tables refer to a row"), + }); + tool("db_generate", { + description: "Generate a dependency-free admin panel for a SQLite database: a Node.js server (node:http + node:sqlite) plus a browser UI with sign-in, roles (admin / editor / viewer), a list per table with search, filters (options, yes/no, references), sorting and paging, and add/edit/delete forms validated against the schema (required, types, CHECK IN options, max length, unique, foreign keys). Writes / (server.mjs, public/, admin.config.json, README.md), then starts it against a temporary copy of the database and runs a self-test over HTTP. The database itself is never modified.", + input: { + db: z.string().describe("Workspace path of the SQLite file"), + out: z.string().optional().describe("Output folder (default -admin)"), + title: z.string().optional(), lang: z.enum(["zh", "en"]).optional().describe("Admin UI language"), + port: z.number().int().min(1).max(65535).optional(), pageSize: z.number().int().min(5).max(200).optional(), + only: z.array(z.string()).optional().describe("Only include these tables"), + tables: z.array(tableInput).optional().describe("Per-table settings"), + roles: z.object({ editor: z.array(z.enum(OPS as [string, ...string[]])).optional(), viewer: z.array(z.enum(OPS as [string, ...string[]])).optional() }).optional().describe("Operations each role may use (admin always has all)"), + selfTest: z.boolean().optional().describe("Run the self-test after generating (default true)"), + }, + openPanel: true, timeoutMs: 180_000, + }, async (i) => { + const tables = await schemaOf(i.db); + const all = await load(); + const prevKey = Object.keys(all).find((k) => all[k].plan.db === i.db && (!i.out || k === i.out.replace(/\/+$/, ""))); + let plan: Plan = prevKey ? structuredClone(all[prevKey].plan) : defaultPlan(i.db, tables); + // tables added to the database since the last run + for (const t of defaultPlan(i.db, tables).tables) if (!plan.tables.find((x) => x.name === t.name)) plan.tables.push(t); + plan.tables = plan.tables.filter((x) => tables.some((t) => t.name === x.name)); + try { plan = applyPatch(plan, tables, i as never); } catch (e) { throw new KitError("bad_plan", (e as Error).message); } + if (plan.out === "." || plan.out.startsWith("..") || plan.out.startsWith("/")) throw new KitError("bad_out", "Choose an output folder inside the workspace."); + const files = await emit(plan, runtime, options.workspaceRoot); + for (const [p, c] of Object.entries(files)) await ws.write(`${plan.out}/${p}`, c); + const saved: Saved = { plan, generatedAt: new Date().toISOString() }; + if (i.selfTest !== false) saved.test = await selfTest(ws.resolve(plan.out), ws.resolve(plan.db), plan); + if (prevKey && prevKey !== plan.out) delete all[prevKey]; + all[plan.out] = saved; await save(all); + const enabled = plan.tables.filter((t) => t.ops.length); + const text = [ + `Generated ${plan.out}/ — “${plan.title}” for ${plan.db}: ${enabled.length} table(s): ${enabled.map((t) => `${t.name} [${t.ops.join(",")}]${t.hidden.length ? ` (hidden: ${t.hidden.join(", ")})` : ""}`).join("; ")}.`, + `Roles: ${Object.entries(plan.roles).map(([r, o]) => `${r}=${o.join("/")}`).join(", ")}.`, + saved.test ? describeTest(saved.test) : "Self-test skipped.", + `Run it: cd ${plan.out} && node server.mjs (Node ≥ 22.13), then open http://127.0.0.1:${plan.port}. The first start creates user “admin” and prints its password; add more with node server.mjs user add .`, + ].join("\n"); + return { text, structured: { kind: "plan", plan, tables, saved } }; + }); + + tool("db_selftest", { + description: "Start a generated admin against a temporary copy of its database and check it over HTTP: sign-in per role, listing, search, sorting, SQL-injection attempts, required-field and type validation, create/read/update/delete, unique and foreign-key conflicts, and role permissions. The real database is not modified.", + input: { out: z.string().describe("Generated admin folder") }, readOnly: true, timeoutMs: 180_000, + }, async (i) => { + const all = await load(); + const s = all[i.out.replace(/\/+$/, "")]; + if (!s) throw new KitError("not_found", `No generated admin at ${i.out}. Known: ${Object.keys(all).join(", ") || "none"}`); + if (!(await ws.exists(`${s.plan.out}/server.mjs`))) throw new KitError("not_found", `${s.plan.out}/server.mjs is missing; run db_generate again.`); + s.test = await selfTest(ws.resolve(s.plan.out), ws.resolve(s.plan.db), s.plan); + await save(all); + return { text: describeTest(s.test), structured: { kind: "test", out: s.plan.out, test: s.test } }; + }); + + tool("db_state", { description: "Panel state.", input: {}, visibility: ["app"], readOnly: true }, async () => { + const all = Object.values(await load()).sort((a, b) => (b.generatedAt ?? "").localeCompare(a.generatedAt ?? "")); + const files = (await ws.list({ exts: DB_EXT })).map((f) => f.path); + if (!all[0]) return { text: "", structured: { kind: "none", files } }; + const tables = await schemaOf(all[0].plan.db).catch(() => []); + return { text: "", structured: { kind: "plan", plan: all[0].plan, tables, saved: all[0], files } }; + }); + tool("db_files", { description: "SQLite files in the workspace.", input: {}, visibility: ["app"], readOnly: true }, async () => ({ text: "", structured: { files: (await ws.list({ exts: DB_EXT })).map((f) => f.path) } })); + return server; +} From c7d1d1702ec9a9578a79c49001e11c3e346a387c Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:02:15 -0400 Subject: [PATCH 07/12] feat(ui-plugins): add DB Admin Generator (db-admin-generator) --- .../db-admin-generator/test/tools.test.ts | 123 ++++++++++++++++++ .../test/workspace-links.test.ts | 43 ++++++ 2 files changed, 166 insertions(+) create mode 100644 ui-plugins/db-admin-generator/test/tools.test.ts create mode 100644 ui-plugins/db-admin-generator/test/workspace-links.test.ts diff --git a/ui-plugins/db-admin-generator/test/tools.test.ts b/ui-plugins/db-admin-generator/test/tools.test.ts new file mode 100644 index 00000000..38904c41 --- /dev/null +++ b/ui-plugins/db-admin-generator/test/tools.test.ts @@ -0,0 +1,123 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { beforeAll, describe, expect, it } from "vitest"; +// @ts-expect-error plain JS runtime +import { introspect, validateRow } from "../src/runtime/schema.mjs"; +import { createServer } from "../src/server.ts"; + +// 虚构样例数据库 “Harbor Bikes” 自行车租赁店(samples/db/make-db.mjs):外键、UNIQUE、CHECK IN、布尔、日期、视图、无主键表。 +const MAKE = process.env.DB_SAMPLE ?? "/workspace/zcode-new-plugins/samples/db/make-db.mjs"; +let ws: string; +let call: (name: string, args: Record) => Promise; +const sha = (p: string) => createHash("sha256").update(readFileSync(p)).digest("hex"); +beforeAll(async () => { + ws = mkdtempSync(join(tmpdir(), "dbadm-")); + mkdirSync(join(ws, "data")); + execFileSync(process.execPath, ["--no-warnings", MAKE, join(ws, "data/harbor-bikes.db")]); + const u = new DatabaseSync(join(ws, "data/accounts.sqlite")); + u.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, api_token TEXT); CREATE TABLE knex_migrations (id INTEGER PRIMARY KEY, name TEXT); INSERT INTO users (email, password_hash) VALUES ('a@example.com','x');"); + u.close(); + const server = createServer({ workspaceRoot: ws, assetRoot: join(import.meta.dirname, "../dist") }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + call = async (name, args) => (await client.callTool({ name, arguments: args })) as any; +}); + +describe("schema runtime", () => { + it("infers input kinds from the SQLite schema", () => { + const t = introspect(new DatabaseSync(join(ws, "data/harbor-bikes.db"), { readOnly: true })); + const col = (tb: string, c: string) => t.find((x: any) => x.name === tb).columns.find((x: any) => x.name === c); + expect(col("bikes", "id")).toMatchObject({ kind: "integer", auto: true }); + expect(col("bikes", "category")).toMatchObject({ kind: "ref", fk: { table: "categories", column: "code" }, notNull: true }); + expect(col("bikes", "frame_size")).toMatchObject({ kind: "select", options: ["S", "M", "L", "XL"] }); + expect(col("bikes", "serial")).toMatchObject({ unique: true, maxLength: 20 }); + expect(col("bikes", "in_service").kind).toBe("boolean"); + expect(col("customers", "is_member").kind).toBe("boolean"); + expect(col("customers", "email").kind).toBe("email"); + expect(col("customers", "joined_at").kind).toBe("datetime"); + expect(col("rentals", "start_date").kind).toBe("date"); + expect(col("categories", "code")).toMatchObject({ notNull: true, unique: true }); + expect(t.find((x: any) => x.name === "audit_log")).toMatchObject({ rowid: true, pk: [] }); + expect(t.find((x: any) => x.name === "open_rentals").type).toBe("view"); + expect(t.find((x: any) => x.name === "bikes").refs).toEqual([{ table: "rentals", column: "bike_id" }]); + }); + it("validates rows (zh messages, defaults left to SQLite)", () => { + const t = introspect(new DatabaseSync(join(ws, "data/harbor-bikes.db"), { readOnly: true })); + const bikes = t.find((x: any) => x.name === "bikes"), customers = t.find((x: any) => x.name === "customers"); + expect(validateRow(bikes, { serial: "x".repeat(21), model: " ", frame_size: "XXL", purchased_on: "2026/1/1", in_service: "maybe", category: "city" }, "create", "zh").errors) + .toEqual({ serial: "最多 20 个字符", model: "必填", frame_size: "不在可选值里", purchased_on: "日期格式应为 YYYY-MM-DD", in_service: "需要 是/否" }); + expect(validateRow(customers, { full_name: "A", email: "a@b.co", joined_at: "", is_member: false }, "create").values).toEqual({ full_name: "A", email: "a@b.co", is_member: 0 }); + expect(validateRow(customers, { joined_at: "" }, "update").errors).toEqual({ joined_at: "Required" }); + expect(validateRow(customers, { joined_at: "2026-11-24T09:30" }, "update").values).toEqual({ joined_at: "2026-11-24 09:30:00" }); + }); +}); + +describe("tools", () => { + it("db_inspect: default plan hides secrets and leaves migration tables out", async () => { + const r = await call("db_inspect", { db: "data/accounts.sqlite" }); + expect(r.isError).toBeFalsy(); + const users = r.structuredContent.plan.tables.find((t: any) => t.name === "users"); + expect(users.hidden).toEqual(["password_hash", "api_token"]); + expect(r.structuredContent.plan.tables.find((t: any) => t.name === "knex_migrations").ops).toEqual([]); + expect(r.content[0].text).toMatch(/email:email\* unique/); + }); + + it("db_generate: writes a dependency-free admin, self-test passes, database untouched", async () => { + const before = sha(join(ws, "data/harbor-bikes.db")); + const r = await call("db_generate", { db: "data/harbor-bikes.db", title: "Harbor Bikes 后台", lang: "zh", tables: [{ name: "audit_log", ops: ["read"] }, { name: "customers", hidden: ["phone"] }] }); + expect(r.isError).toBeFalsy(); + const { plan, saved } = r.structuredContent; + expect(plan.out).toBe("harbor-bikes-admin"); + const failed = saved.test.checks.filter((c: any) => !c.ok); + expect(failed).toEqual([]); + const names = saved.test.checks.map((c: any) => c.name); + for (const n of ["server starts", "API needs sign-in", "wrong password rejected", "write without X-Admin header rejected", "sign in as viewer", "bikes: list (24 rows)", "bikes: empty form → required-field errors", "bikes: create a record", "bikes: duplicate serial → 409", "bikes: editor cannot delete", "bikes: viewer cannot create", "bikes: delete it", "bikes: SQL injection in sort/search is harmless", "categories: deleting a record still used by bikes → 409", "rentals.bike_id: reference options", "changes written to audit.log"]) expect(names).toContain(n); + expect(names.some((n: string) => n.startsWith("audit_log: create"))).toBe(false); // read-only table + expect(sha(join(ws, "data/harbor-bikes.db"))).toBe(before); + const out = join(ws, "harbor-bikes-admin"); + const cfg = JSON.parse(await readFile(join(out, "admin.config.json"), "utf8")); + expect(cfg.db).toBe("../data/harbor-bikes.db"); + expect(cfg.tables.find((t: any) => t.name === "customers").hidden).toEqual(["phone"]); + expect(await readFile(join(out, "README.md"), "utf8")).toContain("node server.mjs user add alice editor"); + expect(JSON.parse(await readFile(join(out, "package.json"), "utf8")).dependencies).toBeUndefined(); + expect(await readFile(join(out, ".gitignore"), "utf8")).toContain("users.json"); + expect(await readFile(join(out, "public/index.html"), "utf8")).not.toMatch(/ diff --git a/ui-plugins/db-admin-generator/src/runtime/public/style.css b/ui-plugins/db-admin-generator/src/runtime/public/style.css new file mode 100644 index 00000000..cdf87232 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/runtime/public/style.css @@ -0,0 +1,20 @@ +:root{--accent:#4f46e5;--bg:#f6f7f9;--card:#fff;--fg:#111827;--muted:#6b7280;--line:#e5e7eb;--bad:#b42318;--side:#111827} +*{box-sizing:border-box}body{margin:0;font:14px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;background:var(--bg);color:var(--fg)} +button{font:inherit;border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:7px;padding:6px 12px;cursor:pointer}button.pri{background:var(--accent);border-color:var(--accent);color:#fff}button.danger{color:var(--bad)}button:disabled{opacity:.5;cursor:default} +input,select,textarea{font:inherit;border:1px solid var(--line);border-radius:7px;padding:6px 9px;background:#fff;color:var(--fg)}textarea{min-height:80px} +.login{max-width:340px;margin:12vh auto;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:26px}.login h1{font-size:19px;margin:0 0 16px}.login label{display:block;font-size:12px;color:var(--muted);margin:10px 0 3px}.login input{width:100%}.login button{width:100%;margin-top:16px} +.err{color:var(--bad);font-size:12px;margin-top:4px} +.shell{display:grid;grid-template-columns:220px 1fr;min-height:100vh}aside{background:var(--side);color:#e5e7eb;padding:16px 10px}aside h1{font-size:15px;margin:2px 8px 16px;color:#fff} +aside a{display:flex;justify-content:space-between;padding:7px 10px;border-radius:7px;color:#d1d5db;text-decoration:none;cursor:pointer}aside a:hover{background:#1f2937}aside a.on{background:#374151;color:#fff}aside a small{color:#9ca3af} +aside .who{margin-top:24px;padding:10px;border-top:1px solid #374151;font-size:12px;color:#9ca3af}aside .who b{color:#fff}aside .who button{margin-top:8px;background:transparent;color:#d1d5db;border-color:#4b5563;width:100%} +.role{display:inline-block;padding:1px 7px;border-radius:999px;background:#312e81;color:#c7d2fe;font-size:11px;margin-left:4px} +main{padding:18px 22px;min-width:0}.top{display:flex;align-items:center;gap:10px;margin-bottom:12px;flex-wrap:wrap}.top h2{margin:0;font-size:18px}.top .sp{flex:1} +.bar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}.bar input[type=search]{min-width:240px} +.tbl{background:var(--card);border:1px solid var(--line);border-radius:10px;overflow:auto}table{border-collapse:collapse;width:100%}th,td{padding:8px 10px;border-bottom:1px solid var(--line);text-align:left;white-space:nowrap;max-width:320px;overflow:hidden;text-overflow:ellipsis} +th{font-size:12px;color:var(--muted);background:#fafafa;cursor:pointer;user-select:none}tbody tr.click{cursor:pointer}tbody tr.click:hover{background:#f5f7ff}td.num{text-align:right;font-variant-numeric:tabular-nums}td .ref{color:var(--muted);font-size:12px} +.null{color:#c0c4cc}.foot{display:flex;justify-content:space-between;align-items:center;margin-top:10px;color:var(--muted)}.empty{padding:30px;text-align:center;color:var(--muted)} +.ro{font-size:12px;color:var(--muted);background:#f3f4f6;border-radius:6px;padding:2px 8px} +dialog{border:0;border-radius:14px;padding:0;width:min(580px,94vw);box-shadow:0 20px 60px rgba(0,0,0,.25)}dialog::backdrop{background:rgba(15,23,42,.45)} +dialog form{padding:18px 20px;max-height:86vh;overflow:auto}dialog h3{margin:0 0 12px}.fld{margin-bottom:10px}.fld label{display:block;font-size:12px;color:var(--muted);margin-bottom:3px}.fld input:not([type=checkbox]),.fld select,.fld textarea{width:100%}.req{color:var(--bad)} +.hintc{font-size:11px;color:var(--muted)}.acts{display:flex;gap:8px;margin-top:14px}.acts .sp{flex:1}.formerr{color:var(--bad);margin-top:8px} +#toast{position:fixed;right:16px;bottom:16px;background:#111827;color:#fff;padding:8px 14px;border-radius:8px;opacity:0;transition:opacity .2s;pointer-events:none}#toast.on{opacity:1}#toast.bad{background:var(--bad)}