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" + } + ] + } +} 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。 diff --git a/external_plugins/db-admin-generator/skills/db-admin-generator/SKILL.md b/external_plugins/db-admin-generator/skills/db-admin-generator/SKILL.md new file mode 100644 index 00000000..1a41a3ae --- /dev/null +++ b/external_plugins/db-admin-generator/skills/db-admin-generator/SKILL.md @@ -0,0 +1,13 @@ +--- +name: db-admin-generator +description: 给 SQLite 数据库生成无依赖的管理后台(Node.js + 网页界面:登录、admin/editor/viewer 角色、搜索、筛选、表单校验、增删改查),并用数据库的临时副本自动启动自测。用户提到“管理后台 / 后台管理系统 / admin panel / 给数据库做个界面 / CRUD”时使用。 +--- + +# 数据库转管理后台 + +1. 找到 SQLite 文件(.db / .sqlite / .sqlite3)。如果用户说的是 Postgres 或 MySQL,告诉他这一版只支持 SQLite;可以先导出一份 SQLite 测试库。 +2. 用 `db_inspect({db})` 读取表结构,向用户简要说明有哪些表和视图、行数、引用关系,以及默认隐藏的敏感列(密码、令牌等)。 +3. 和用户确认:要管理哪些表、每张表允许哪些操作、editor 和 viewer 能做什么、界面语言和标题。然后调用 `db_generate({db, only?, tables?, roles?, lang?, title?})`。 +4. 查看自测结果。如果有失败项,说明是哪一项、可能的原因(例如数据库里的触发器或 CHECK 约束),必要时调整方案后重新生成。 +5. 告诉用户怎么运行:`cd && node server.mjs`(需要 Node 22.13+),第一次启动会在终端打印 admin 的密码;用 `node server.mjs user add <名字> <角色>` 添加其他人。默认只能本机访问;要给别人用,需要先放到 HTTPS 后面。 +6. 用户手动改过生成的代码后,可以用 `db_selftest({out})` 再验证一遍。 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) 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/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")); +} 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/kit/console.ts b/ui-plugins/db-admin-generator/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/kit/console.ts @@ -0,0 +1,5 @@ +// stdout 只留给 MCP 协议;依赖库的日志改写到 stderr。 +console.log = (...args: unknown[]) => process.stderr.write(`${args.map(String).join(" ")}\n`); +console.info = console.log; +console.warn = console.log; +console.debug = console.log; diff --git a/ui-plugins/db-admin-generator/src/kit/server-kit.ts b/ui-plugins/db-admin-generator/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/kit/server-kit.ts @@ -0,0 +1,84 @@ +import { readFile } from "node:fs/promises"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { z } from "zod"; +import { KitError } from "./workspace.ts"; + +export const HTML_MIME = "text/html;profile=mcp-app"; +type Visibility = ("model" | "app")[]; +type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; + +export interface ToolOutput { + text: string; + structured?: Record; + images?: { data: string; mimeType: string }[]; +} + +export interface KitServerOptions { + name: string; + version: string; + panelUri: string; + surface: string; + panelHtml: () => Promise; + log?: (line: string) => void; + /** 页面资源的额外 _meta,例如 { "zcode/csp": { wasmUnsafeEval: true } }。 */ + panelMeta?: Record; +} + +/** 统一的工具注册:所有工具都关联同一个侧栏面板,错误带 code 返回给 Agent 与页面。 */ +export function createKitServer(options: KitServerOptions) { + const log = options.log ?? (() => undefined); + const server = new McpServer({ name: options.name, version: options.version }, { capabilities: { logging: {} } }); + const panelMeta = { ui: { prefersBorder: false }, ...options.panelMeta }; + server.registerResource("panel", options.panelUri, { mimeType: HTML_MIME, _meta: panelMeta }, async () => ({ + contents: [{ uri: options.panelUri, mimeType: HTML_MIME, _meta: panelMeta, text: await options.panelHtml() }], + })); + + const tool = ( + name: string, + config: { + description: string; + input: Record; + visibility?: Visibility; + openPanel?: boolean; + readOnly?: boolean; + timeoutMs?: number; + }, + run: (input: any) => Promise, + ) => { + server.registerTool( + name, + { + description: config.description, + inputSchema: config.input, + annotations: { readOnlyHint: !!config.readOnly, ...(config.readOnly ? {} : { destructiveHint: false }), openWorldHint: false }, + _meta: { + ui: { resourceUri: options.panelUri, surface: options.surface, visibility: config.visibility ?? ["model", "app"] }, + ...(config.timeoutMs ? { timeoutMs: config.timeoutMs } : {}), + ...(config.openPanel ? { "openai/ui": { preferredModelDisplayMode: "fullscreen" } } : {}), + }, + }, + async (input: unknown) => { + try { + const output = await run(input); + const content: Content[] = [{ type: "text", text: output.text }]; + for (const image of output.images ?? []) content.push({ type: "image", ...image }); + return { content, ...(output.structured ? { structuredContent: output.structured } : {}) }; + } catch (error) { + const code = error instanceof KitError ? error.code : "internal_error"; + const message = error instanceof Error ? error.message : String(error); + if (!(error instanceof KitError)) log(`${name} failed: ${error instanceof Error ? error.stack : message}`); + return { + isError: true, + content: [{ type: "text" as const, text: `[${code}] ${message}` }], + structuredContent: { error: { code, message } }, + }; + } + }, + ); + }; + return { server, tool }; +} + +export async function readPanel(path: string) { + return readFile(path, "utf8"); +} diff --git a/ui-plugins/db-admin-generator/src/kit/workspace.ts b/ui-plugins/db-admin-generator/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/db-admin-generator/src/kit/workspace.ts @@ -0,0 +1,151 @@ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; +import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +export class KitError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + this.name = "KitError"; + } +} + +const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".cache", "__pycache__"]); + +/** 只允许读写当前工作区内的文件;所有路径都相对工作区根目录。 */ +export class Workspace { + readonly root: string; + constructor(root: string) { + this.root = resolve(root); + } + + resolve(path: string): string { + if (typeof path !== "string" || !path.trim()) throw new KitError("bad_path", "Path is empty."); + const absolute = resolve(this.root, path); + const rel = relative(this.root, absolute); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) + throw new KitError("outside_workspace", `Path is outside the workspace: ${path}`); + this.assertRealInside(absolute, path); + return absolute; + } + + private realRoot?: string; + + /** + * 符号链接不能把读写带出工作区:从目标往上找到第一个已存在的路径,取它的真实路径, + * 必须仍在工作区根目录的真实路径之下。还不存在的写入目标按其已存在的上级目录判断; + * 指向不存在位置的悬空链接一律拒绝(否则 writeFile 会顺着它在外部建文件)。 + */ + private assertRealInside(absolute: string, path: string) { + let realRoot: string; + try { + realRoot = this.realRoot ??= realpathSync(this.root); + } catch { + return; // 根目录本身不存在时,没有可逃出的链接 + } + const outside = (real: string) => { + const rel = relative(realRoot, real); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + }; + let probe = absolute; + for (;;) { + let real: string | undefined; + try { + real = realpathSync(probe); + } catch { + let link = false; + try { + link = lstatSync(probe).isSymbolicLink(); + } catch {} + if (link) { + const target = resolve(dirname(probe), readlinkSync(probe)); + throw new KitError("outside_workspace", outside(target) ? `Path leaves the workspace through a link: ${path}` : `Path goes through a broken link: ${path}`); + } + } + if (real !== undefined) { + if (outside(real)) throw new KitError("outside_workspace", `Path leaves the workspace through a link: ${path}`); + return; + } + const parent = dirname(probe); + if (parent === probe) return; + probe = parent; + } + } + + rel(absolute: string): string { + return relative(this.root, absolute).split(sep).join("/") || "."; + } + + async exists(path: string): Promise { + try { + await stat(this.resolve(path)); + return true; + } catch { + return false; + } + } + + async read(path: string, maxBytes = 200 * 1024 * 1024): Promise { + const absolute = this.resolve(path); + let info; + try { + info = await stat(absolute); + } catch { + throw new KitError("not_found", `File not found: ${path}`); + } + if (!info.isFile()) throw new KitError("not_a_file", `Not a file: ${path}`); + if (info.size > maxBytes) throw new KitError("too_large", `File is larger than ${Math.round(maxBytes / 1048576)} MB: ${path}`); + return readFile(absolute); + } + + async readText(path: string): Promise { + return (await this.read(path, 20 * 1024 * 1024)).toString("utf8"); + } + + async write(path: string, data: Uint8Array | string): Promise { + const absolute = this.resolve(path); + await mkdir(dirname(absolute), { recursive: true }); + await writeFile(absolute, data); + return this.rel(absolute); + } + + /** 列出文件(默认递归、跳过依赖与构建目录),按路径排序。 */ + async list({ dir = ".", exts, recursive = true, limit = 2000 }: { dir?: string; exts?: string[]; recursive?: boolean; limit?: number } = {}) { + const wanted = exts?.map((ext) => ext.toLowerCase()); + const out: { path: string; size: number }[] = []; + const walk = async (absolute: string, depth: number) => { + if (out.length >= limit || depth > 8) return; + let entries; + try { + entries = await readdir(absolute, { withFileTypes: true }); + } catch { + return; + } + entries.sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true })); + for (const entry of entries) { + if (out.length >= limit) return; + if (entry.name.startsWith(".") && entry.name !== ".") continue; + const child = join(absolute, entry.name); + if (entry.isDirectory()) { + if (recursive && !SKIP.has(entry.name)) await walk(child, depth + 1); + } else if (entry.isFile() && (!wanted || wanted.includes(extname(entry.name).toLowerCase()))) { + out.push({ path: this.rel(child), size: (await stat(child)).size }); + } + } + }; + await walk(this.resolve(dir), 0); + return out; + } +} + +/** 把文件名中不适合的字符替换掉,保留中文。 */ +export function safeFileName(name: string, fallback = "file"): string { + const cleaned = name + .replace(/[\\/:*?"<>|]+/g, "_") + .replace(/\p{Cc}+/gu, "_") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return (cleaned || fallback).slice(0, 120); +} 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/runtime/public/app.js b/ui-plugins/db-admin-generator/src/runtime/public/app.js new file mode 100644 index 00000000..e74305a6 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/runtime/public/app.js @@ -0,0 +1,126 @@ +// Admin UI generated by DB Admin Generator. Vanilla JS, talks to /api on the same server. +(function () { + "use strict"; + var app = document.getElementById("app"), meta = null, cur = null, st = {}, ZH = false; + var S = function (zh, en) { return ZH ? zh : en; }; + function el(tag, props) { + var e = document.createElement(tag); + for (var k in props || {}) { var v = props[k]; if (v == null || v === false) continue; if (k.slice(0, 2) === "on") e.addEventListener(k.slice(2), v); else if (k === "class") e.className = v; else if (k === "text") e.textContent = v; else if (k in e && typeof v !== "string") e[k] = v; else e.setAttribute(k, v === true ? "" : v); } + for (var i = 2; i < arguments.length; i++) { var c = arguments[i]; if (c == null || c === false) continue; if (Array.isArray(c)) c.forEach(function (x) { if (x != null && x !== false) e.append(x); }); else e.append(c); } + return e; + } + function toast(t, bad) { var e = document.getElementById("toast"); e.textContent = t; e.className = "on" + (bad ? " bad" : ""); clearTimeout(e._t); e._t = setTimeout(function () { e.className = ""; }, 2200); } + function api(method, path, body) { + return fetch(path, { method: method, headers: method === "GET" ? {} : { "Content-Type": "application/json", "X-Admin": "1" }, body: body ? JSON.stringify(body) : undefined, credentials: "same-origin" }) + .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { if (!r.ok) { var e = new Error(j.error || r.statusText); e.status = r.status; e.fields = j.fields; throw e; } return j; }); }); + } + function login(msg) { + document.title = "Sign in"; + var u = el("input", { id: "user", autocomplete: "username", autofocus: true }), p = el("input", { id: "pw", type: "password", autocomplete: "current-password" }), err = el("div", { class: "err", text: msg || "" }); + app.replaceChildren(el("form", { class: "login", onsubmit: function (e) { e.preventDefault(); api("POST", "/api/login", { user: u.value, password: p.value }).then(boot).catch(function (x) { err.textContent = x.message; }); } }, + el("h1", { text: "Admin" }), el("label", { for: "user", text: "User / 用户名" }), u, el("label", { for: "pw", text: "Password / 密码" }), p, err, el("button", { class: "pri", type: "submit", text: "Sign in / 登录" }))); + } + function boot() { + api("GET", "/api/meta").then(function (m) { meta = m; ZH = m.lang === "zh"; document.title = m.title; document.documentElement.lang = ZH ? "zh-CN" : "en"; var h = location.hash.slice(1); open(m.tables.find(function (t) { return t.name === decodeURIComponent(h); }) || m.tables[0]); }) + .catch(function (e) { if (e.status === 401) login(); else app.textContent = e.message; }); + } + function open(t) { cur = t; st = { q: "", f: {}, sort: null, dir: "asc", page: 0 }; if (t) history.replaceState(null, "", "#" + encodeURIComponent(t.name)); render(); } + var refOpts = {}; + function options(t, c) { var k = t.name + "." + c.name; return refOpts[k] ? Promise.resolve(refOpts[k]) : api("GET", "/api/t/" + encodeURIComponent(t.name) + "/options/" + encodeURIComponent(c.name)).then(function (j) { return (refOpts[k] = j.options); }); } + function fmt(c, v, labels) { + if (v === null || v === undefined) return el("span", { class: "null", text: "—" }); + if (c.kind === "boolean") return v ? S("是", "Yes") : S("否", "No"); + if (c.fk && labels && labels[c.name] && labels[c.name][String(v)] != null) return el("span", {}, String(labels[c.name][String(v)]) + " ", el("span", { class: "ref", text: "#" + v })); + return String(v); + } + function render() { + var side = el("aside", {}, el("h1", { text: meta.title }), meta.tables.map(function (t) { return el("a", { class: t === cur ? "on" : "", "data-t": t.name, onclick: function () { open(t); } }, el("span", { text: t.label }), el("small", { text: t.view ? S("视图", "view") : "" })); }), + el("div", { class: "who" }, el("div", {}, el("b", { text: meta.user }), el("span", { class: "role", text: meta.role })), el("button", { id: "logout", onclick: function () { api("POST", "/api/logout").then(function () { login(); }); } }, S("退出登录", "Sign out")))); + var main = el("main", {}); + app.replaceChildren(el("div", { class: "shell" }, side, main)); + if (!cur) { main.append(el("div", { class: "empty", text: S("你的角色没有可查看的表。", "Your role has no tables to view.") })); return; } + var t = cur, can = function (o) { return t.ops.indexOf(o) >= 0; }; + var cols = t.list.map(function (n) { return t.columns.find(function (c) { return c.name === n; }); }).filter(Boolean); + var q = el("input", { type: "search", id: "q", placeholder: S("搜索 ", "Search ") + t.search.join(", "), value: st.q, oninput: function () { clearTimeout(q._t); q._t = setTimeout(function () { st.q = q.value; st.page = 0; load(); }, 200); } }); + var filters = t.columns.filter(function (c) { return c.kind === "select" || c.kind === "boolean" || c.fk; }).map(function (c) { + var s = el("select", { "data-f": c.name, onchange: function () { if (s.value === "") delete st.f[c.name]; else st.f[c.name] = s.value; st.page = 0; load(); } }, el("option", { value: "", text: c.name + ": " + S("全部", "all") })); + if (c.kind === "boolean") { s.append(el("option", { value: "1", text: S("是", "Yes") }), el("option", { value: "0", text: S("否", "No") })); } + else if (c.options) c.options.forEach(function (o) { s.append(el("option", { value: o, text: o })); }); + else options(t, c).then(function (os) { os.forEach(function (o) { s.append(el("option", { value: String(o.value), text: String(o.label) })); }); s.value = st.f[c.name] || ""; }); + if (!c.required) s.append(el("option", { value: "\u2205", text: S("(空)", "(empty)") })); + s.value = st.f[c.name] || ""; return s; + }); + var thead = el("tr", {}, cols.map(function (c) { return el("th", { "data-c": c.name, onclick: function () { st.dir = st.sort === c.name && st.dir === "asc" ? "desc" : "asc"; st.sort = c.name; load(); } }, c.name + (st.sort === c.name ? (st.dir === "asc" ? " ▲" : " ▼") : "")); })); + var tbody = el("tbody", {}), count = el("span", { id: "count" }), prev = el("button", { id: "prev", text: S("上一页", "Previous"), onclick: function () { st.page--; load(); } }), next = el("button", { id: "next", text: S("下一页", "Next"), onclick: function () { st.page++; load(); } }); + main.append(el("div", { class: "top" }, el("h2", { text: t.label }), t.view ? el("span", { class: "ro", text: S("只读视图", "read-only view") }) : (!can("create") && !can("update") && !can("delete")) ? el("span", { class: "ro", text: S("只读", "read-only") }) : null, el("span", { class: "sp" }), + can("create") ? el("button", { class: "pri", id: "new", text: S("新增", "New"), onclick: function () { form(null); } }) : null), + el("div", { class: "bar" }, t.search.length ? q : null, filters), el("div", { class: "tbl" }, el("table", {}, el("thead", {}, thead), tbody)), el("div", { class: "foot" }, count, el("span", {}, prev, " ", next))); + function load() { + var p = new URLSearchParams({ q: st.q, page: st.page }); if (st.sort) { p.set("sort", st.sort); p.set("dir", st.dir); } + for (var k in st.f) p.set("f." + k, st.f[k]); + api("GET", "/api/t/" + encodeURIComponent(t.name) + "?" + p).then(function (j) { + thead.querySelectorAll("th").forEach(function (th) { var n = th.getAttribute("data-c"); th.textContent = n + (st.sort === n ? (st.dir === "asc" ? " ▲" : " ▼") : ""); }); + tbody.replaceChildren.apply(tbody, j.rows.length ? j.rows.map(function (r) { return el("tr", { class: t.keyed ? "click" : "", onclick: t.keyed ? function () { form(r._key); } : null }, cols.map(function (c) { return el("td", { class: c.kind === "integer" || c.kind === "number" ? "num" : "" }, fmt(c, r[c.name], j.labels)); })); }) : [el("tr", {}, el("td", { class: "empty", colspan: cols.length, text: S("没有记录", "No rows") }))]); + var from = j.total ? j.page * j.size + 1 : 0; count.textContent = from + "–" + (j.page * j.size + j.rows.length) + " / " + j.total; + prev.disabled = j.page === 0; next.disabled = (j.page + 1) * j.size >= j.total; + }).catch(function (e) { if (e.status === 401) login(S("登录已过期", "Session expired")); else toast(e.message, true); }); + } + load(); + st.reload = load; + } + function input(c, v, ro) { + var id = "f_" + c.name, x; + if (c.kind === "boolean") x = el("input", { type: "checkbox", id: id, checked: !!v && v !== "0", disabled: ro }); + else if (c.kind === "longtext") { x = el("textarea", { id: id, disabled: ro }); x.value = v == null ? "" : v; } + else if (c.options || c.fk) { + x = el("select", { id: id, disabled: ro }, el("option", { value: "", text: c.required ? S("— 请选择 —", "— choose —") : S("(空)", "(empty)") })); + if (c.options) c.options.forEach(function (o) { x.append(el("option", { value: o, text: o })); }); x.value = v == null ? "" : String(v); + if (c.fk) options(cur, c).then(function (os) { os.forEach(function (o) { x.append(el("option", { value: String(o.value), text: o.label + " (#" + o.value + ")" })); }); x.value = v == null ? "" : String(v); }); + } else { + var type = { integer: "number", number: "number", date: "date", datetime: "datetime-local", email: "email", url: "url", tel: "tel" }[c.kind] || "text"; + x = el("input", { id: id, type: type, step: c.kind === "number" ? "any" : c.kind === "integer" ? "1" : null, maxlength: c.maxLength || null, disabled: ro }); + x.value = v == null ? "" : c.kind === "datetime" ? String(v).replace(" ", "T").slice(0, 16) : String(v); + } + x.setAttribute("name", c.name); + return el("div", { class: "fld" }, el("label", { for: id }, c.name, c.required && !ro ? el("span", { class: "req", text: " *" }) : null, el("span", { class: "hintc", text: " " + (c.fk ? "→ " + c.fk.table : c.type) })), x, el("div", { class: "err" })); + } + function form(key) { + var t = cur, can = function (o) { return t.ops.indexOf(o) >= 0; }, editing = key != null, ro = editing && !can("update"); + var fields = el("div", {}), ferr = el("div", { class: "formerr" }); + var dlg = el("dialog", { id: "dlg" }), save = el("button", { class: "pri", type: "submit", text: S("保存", "Save") }); + dlg.append(el("form", { method: "dialog", novalidate: true, onsubmit: function (e) { e.preventDefault(); submit(); } }, + el("h3", { text: (editing ? (ro ? S("查看", "View") : S("编辑", "Edit")) : S("新增", "New")) + " · " + t.label }), fields, ferr, + el("div", { class: "acts" }, editing && can("delete") ? el("button", { type: "button", class: "danger", id: "del", text: S("删除", "Delete"), onclick: del }) : null, el("span", { class: "sp" }), + el("button", { type: "button", id: "cancel", text: ro ? S("关闭", "Close") : S("取消", "Cancel"), onclick: function () { dlg.close(); } }), ro ? null : save))); + dlg.addEventListener("close", function () { dlg.remove(); }); + document.body.append(dlg); + var show = function (row) { fields.replaceChildren.apply(fields, t.columns.filter(function (c) { return c.editable || editing; }).map(function (c) { return input(c, row ? row[c.name] : null, ro || !c.editable); })); dlg.showModal(); }; + if (editing) api("GET", "/api/t/" + encodeURIComponent(t.name) + "/r/" + encodeURIComponent(key)).then(function (j) { show(j.row); }).catch(function (e) { toast(e.message, true); dlg.remove(); }); + else { var d = {}; t.columns.forEach(function (c) { var v = c.default; if (v == null) return; var m = /^'((?:[^']|'')*)'$/.exec(v); if (m) d[c.name] = m[1].replace(/''/g, "'"); else if (/^-?\d+(\.\d+)?$/.test(v)) d[c.name] = c.kind === "boolean" ? v !== "0" : Number(v); else if (/^(true|false)$/i.test(v)) d[c.name] = /^true$/i.test(v); }); show(d); } + function value(c) { var x = fields.querySelector("[name='" + c.name + "']"); if (!x) return undefined; if (c.kind === "boolean") return x.checked; return x.value === "" ? null : x.value; } + function clientErrors(vals) { + var errs = {}; t.columns.forEach(function (c) { if (!c.editable || !(c.name in vals)) return; var v = vals[c.name]; + if (v == null) { if (c.required) errs[c.name] = S("必填", "Required"); return; } + if (c.kind === "integer" && !/^-?\d+$/.test(v)) errs[c.name] = S("需要整数", "Must be a whole number"); + if (c.kind === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v)) errs[c.name] = S("邮箱格式不对", "Not a valid email"); + if (c.maxLength && String(v).length > c.maxLength) errs[c.name] = S("最多 " + c.maxLength + " 个字符", "At most " + c.maxLength + " characters"); }); + return errs; + } + function mark(errs) { fields.querySelectorAll(".err").forEach(function (e) { e.textContent = ""; }); for (var k in errs || {}) { var x = fields.querySelector("[name='" + k + "']"); if (x) x.parentNode.querySelector(".err").textContent = errs[k]; } } + function submit() { + var vals = {}; t.columns.forEach(function (c) { if (c.editable) vals[c.name] = value(c); }); + var errs = clientErrors(vals); mark(errs); ferr.textContent = ""; + if (Object.keys(errs).length) return; + save.disabled = true; + (editing ? api("PUT", "/api/t/" + encodeURIComponent(t.name) + "/r/" + encodeURIComponent(key), vals) : api("POST", "/api/t/" + encodeURIComponent(t.name), vals)) + .then(function () { dlg.close(); toast(S("已保存", "Saved")); st.reload(); }) + .catch(function (e) { mark(e.fields); ferr.textContent = e.message; }) + .finally(function () { save.disabled = false; }); + } + function del() { + if (!confirm(S("确定删除这条记录?", "Delete this record?"))) return; + api("DELETE", "/api/t/" + encodeURIComponent(t.name) + "/r/" + encodeURIComponent(key)).then(function () { dlg.close(); toast(S("已删除", "Deleted")); st.reload(); }).catch(function (e) { ferr.textContent = e.message; }); + } + } + boot(); +})(); diff --git a/ui-plugins/db-admin-generator/src/runtime/public/index.html b/ui-plugins/db-admin-generator/src/runtime/public/index.html new file mode 100644 index 00000000..e76f41ec --- /dev/null +++ b/ui-plugins/db-admin-generator/src/runtime/public/index.html @@ -0,0 +1,4 @@ + +Admin + +
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)} diff --git a/ui-plugins/db-admin-generator/src/runtime/schema.mjs b/ui-plugins/db-admin-generator/src/runtime/schema.mjs new file mode 100644 index 00000000..3f6291ac --- /dev/null +++ b/ui-plugins/db-admin-generator/src/runtime/schema.mjs @@ -0,0 +1,140 @@ +// Shared by DB Admin Generator (the plugin) and the generated admin server. Plain JS, Node >= 22.13 (node:sqlite). +// Reads a SQLite schema and validates rows against it. + +/** @param {string} s */ +const qi = (s) => `"${String(s).replace(/"/g, '""')}"`; +export const quoteIdent = qi; + +function affinity(type) { + const t = String(type || "").toUpperCase(); + if (t.includes("INT")) return "integer"; + if (/CHAR|CLOB|TEXT/.test(t)) return "text"; + if (t === "" || t.includes("BLOB")) return t === "" ? "any" : "blob"; + if (/REAL|FLOA|DOUB/.test(t)) return "real"; + return "numeric"; +} + +/** Parse `col IN ('a','b')` style CHECK constraints from CREATE TABLE sql. */ +function checkOptions(sql, col) { + if (!sql) return undefined; + const esc = col.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const re = new RegExp(`CHECK\\s*\\(\\s*["\`\\[]?${esc}["\`\\]]?\\s+IN\\s*\\(([^)]*)\\)\\s*\\)`, "i"); + const m = re.exec(sql); + if (!m) return undefined; + const opts = [...m[1].matchAll(/'((?:[^']|'')*)'|(-?\d+(?:\.\d+)?)/g)].map((x) => (x[1] !== undefined ? x[1].replace(/''/g, "'") : x[2])); + return opts.length ? opts : undefined; +} + +function kindOf(c, table) { + const t = c.type.toUpperCase(), n = c.name.toLowerCase(); + if (c.fk) return "ref"; + if (c.options) return c.options.every((o) => o === "0" || o === "1") ? "boolean" : "select"; + if (/BOOL/.test(t) || (c.affinity === "integer" && /^(is|has|can|in)_/.test(n))) return "boolean"; + if (/DATETIME|TIMESTAMP/.test(t) || (c.affinity !== "integer" && /_at$/.test(n))) return "datetime"; + if (/^DATE$/.test(t) || /(_on|_date|^date)$/.test(n)) return "date"; + if (c.affinity === "integer") return "integer"; + if (c.affinity === "real" || (c.affinity === "numeric" && !/DATE|TIME|BOOL/.test(t))) return "number"; + if (/e-?mail/.test(n)) return "email"; + if (/(^|_)(url|website|link)$/.test(n)) return "url"; + if (/(^|_)(phone|tel|mobile)$/.test(n)) return "tel"; + if (/^(notes?|description|body|content|comment|bio|details)$/.test(n) || /TEXT|CLOB/.test(t) && /note|desc|comment/.test(n)) return "longtext"; + void table; + return "text"; +} + +/** + * @param {import("node:sqlite").DatabaseSync} db + * @returns {Array<{name:string,type:"table"|"view",sql:string,pk:string[],rowid:boolean,columns:any[],rows:number,refs:any[]}>} + */ +export function introspect(db) { + const objs = db.prepare("SELECT name, type, sql FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY name").all(); + const tables = []; + for (const o of objs) { + const cols = db.prepare(`PRAGMA table_xinfo(${qi(o.name)})`).all().filter((c) => !c.hidden); + const fks = o.type === "table" ? db.prepare(`PRAGMA foreign_key_list(${qi(o.name)})`).all() : []; + const uniques = new Set(); + if (o.type === "table") for (const ix of db.prepare(`PRAGMA index_list(${qi(o.name)})`).all()) { + if (!ix.unique || ix.origin === "pk") continue; + const ic = db.prepare(`PRAGMA index_info(${qi(ix.name)})`).all(); + if (ic.length === 1) uniques.add(ic[0].name); + } + const pk = cols.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk).map((c) => c.name); + const withoutRowid = /WITHOUT\s+ROWID\s*;?\s*$/i.test(o.sql || ""); + const columns = cols.map((c) => { + const fk = fks.find((f) => f.from === c.name && fks.filter((g) => g.id === f.id).length === 1); + const col = { + name: c.name, type: c.type || "", affinity: affinity(c.type), notNull: !!c.notnull || (c.pk > 0 && !(pk.length === 1 && /^INTEGER$/i.test(c.type || "") && !withoutRowid)), + default: c.dflt_value, pk: c.pk, unique: uniques.has(c.name) || (pk.length === 1 && pk[0] === c.name), + fk: fk ? { table: fk.table, column: fk.to ?? null, onDelete: fk.on_delete } : undefined, + options: checkOptions(o.sql, c.name), + maxLength: /\(\s*(\d+)\s*\)/.test(c.type || "") && /CHAR/i.test(c.type) ? Number(/\(\s*(\d+)/.exec(c.type)[1]) : undefined, + auto: pk.length === 1 && pk[0] === c.name && /^INTEGER$/i.test(c.type || "") && !withoutRowid, + }; + col.kind = kindOf(col, o.name); + return col; + }); + let rows = 0; + try { rows = db.prepare(`SELECT COUNT(*) AS n FROM ${qi(o.name)}`).get().n; } catch { rows = -1; } + tables.push({ name: o.name, type: o.type, sql: o.sql || "", pk, rowid: o.type === "table" && !withoutRowid && pk.length === 0, columns, rows, refs: [] }); + } + // FK target column defaults to the target's primary key + for (const t of tables) for (const c of t.columns) if (c.fk) { + const target = tables.find((x) => x.name === c.fk.table); + if (!c.fk.column) c.fk.column = target?.pk[0] ?? "rowid"; + if (target) target.refs.push({ table: t.name, column: c.name }); + } + return tables; +} + +/** A column a human would recognise a row by. */ +export function labelColumn(t) { + const names = t.columns.map((c) => c.name); + for (const want of ["name", "full_name", "display_name", "title", "label", "username", "model", "email", "serial", "code"]) { const hit = names.find((n) => n.toLowerCase() === want); if (hit) return hit; } + return t.columns.find((c) => c.kind === "text" && !c.pk)?.name ?? t.pk[0] ?? names[0]; +} + +export const required = (c) => c.notNull && c.default === null && !c.auto; +export const editable = (c) => !c.auto && !(c.name === "created_at" || c.name === "updated_at") ; + +const DATE = /^\d{4}-\d{2}-\d{2}$/, DT = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z?$/, EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; + +/** + * Validate and coerce one row for insert/update. Returns { values, errors } where errors maps column → message. + * @param {{columns:any[]}} t + * @param {Record} input + * @param {"create"|"update"} mode + */ +export function validateRow(t, input, mode, lang = "en") { + const zh = lang === "zh"; + const M = zh ? { req: "必填", int: "需要整数", num: "需要数字", date: "日期格式应为 YYYY-MM-DD", dt: "时间格式应为 YYYY-MM-DD HH:MM", email: "邮箱格式不对", url: "需要 http(s) 链接", opt: "不在可选值里", len: (n) => `最多 ${n} 个字符`, bool: "需要 是/否" } + : { req: "Required", int: "Must be a whole number", num: "Must be a number", date: "Use YYYY-MM-DD", dt: "Use YYYY-MM-DD HH:MM", email: "Not a valid email", url: "Needs an http(s) link", opt: "Not one of the allowed values", len: (n) => `At most ${n} characters`, bool: "Must be yes/no" }; + const values = {}, errors = {}; + for (const c of t.columns) { + if (!editable(c)) continue; + if (!(c.name in input)) { if (mode === "create" && required(c)) errors[c.name] = M.req; continue; } + let v = input[c.name]; + if (typeof v === "string") v = v.trim(); + if (v === "" || v === undefined) v = null; + if (v === null) { + if (required(c) || (mode === "update" && c.notNull)) errors[c.name] = M.req; + else if (!(mode === "create" && c.default !== null)) values[c.name] = null; // let the column default apply on insert + continue; + } + switch (c.kind) { + case "boolean": if (v === true || v === 1 || v === "1" || v === "true") v = 1; else if (v === false || v === 0 || v === "0" || v === "false") v = 0; else { errors[c.name] = M.bool; continue; } break; + case "integer": if (!/^-?\d+$/.test(String(v))) { errors[c.name] = M.int; continue; } v = Number(v); break; + case "number": if (!Number.isFinite(Number(v))) { errors[c.name] = M.num; continue; } v = Number(v); break; + case "date": if (!DATE.test(String(v))) { errors[c.name] = M.date; continue; } break; + case "datetime": if (!DT.test(String(v))) { errors[c.name] = M.dt; continue; } v = String(v).replace("T", " ").replace(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2})$/, "$1:00"); break; + case "email": if (!EMAIL.test(String(v))) { errors[c.name] = M.email; continue; } break; + case "url": if (!/^https?:\/\/\S+$/i.test(String(v))) { errors[c.name] = M.url; continue; } break; + case "ref": if (c.affinity === "integer") { if (!/^-?\d+$/.test(String(v))) { errors[c.name] = M.int; continue; } v = Number(v); } break; + default: break; + } + if (c.options && !c.options.includes(String(v))) { errors[c.name] = M.opt; continue; } + if (c.maxLength && String(v).length > c.maxLength) { errors[c.name] = M.len(c.maxLength); continue; } + if (typeof v === "object") v = JSON.stringify(v); + values[c.name] = v; + } + return { values, errors }; +} diff --git a/ui-plugins/db-admin-generator/src/runtime/server.mjs b/ui-plugins/db-admin-generator/src/runtime/server.mjs new file mode 100644 index 00000000..039d2d50 --- /dev/null +++ b/ui-plugins/db-admin-generator/src/runtime/server.mjs @@ -0,0 +1,285 @@ +#!/usr/bin/env node +// Admin panel server generated by DB Admin Generator (ZCode). No dependencies: Node >= 22.13 (node:sqlite, node:http). +// node server.mjs start (http://127.0.0.1:8787 by default; PORT / HOST / ADMIN_DB env to change) +// node server.mjs user add add a user (role: admin | editor | viewer); password from ADMIN_PASSWORD or generated +// node server.mjs user passwd set a new password +// node server.mjs user list | user remove +import { appendFileSync, chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { createHmac, randomBytes, scryptSync, timingSafeEqual } from "node:crypto"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { DatabaseSync } from "node:sqlite"; +import { editable, introspect, labelColumn, quoteIdent as qi, required, validateRow } from "./schema.mjs"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CFG = JSON.parse(readFileSync(join(HERE, "admin.config.json"), "utf8")); +const DB_PATH = resolve(HERE, process.env.ADMIN_DB || CFG.db); +const USERS = resolve(HERE, process.env.ADMIN_USERS || "users.json"); +const SECRET_FILE = resolve(HERE, process.env.ADMIN_SECRET_FILE || ".session-secret"); +const AUDIT = resolve(HERE, process.env.ADMIN_AUDIT || "audit.log"); +const ROLES = CFG.roles || { admin: ["read", "create", "update", "delete"], editor: ["read", "create", "update"], viewer: ["read"] }; +const ZH = CFG.lang === "zh"; +const L = ZH ? { login: "用户名或密码不对", locked: "尝试次数过多,请 10 分钟后再试", auth: "请先登录", forbid: "你的角色没有这个权限", nf: "找不到", bad: "请求无效", dup: "已存在相同的值", inuse: "还有其他记录引用它,不能删除", fkbad: "引用的记录不存在", check: "不符合数据库的约束", fix: "请修正标出的字段", nothing: "没有要保存的修改" } + : { login: "Wrong user name or password", locked: "Too many attempts; try again in 10 minutes", auth: "Please sign in", forbid: "Your role is not allowed to do this", nf: "Not found", bad: "Bad request", dup: "This value already exists", inuse: "Other records still refer to this one; it can't be deleted", fkbad: "The referenced record does not exist", check: "Violates a database constraint", fix: "Please fix the marked fields", nothing: "Nothing to save" }; + +// ---------- users ---------- +const readUsers = () => (existsSync(USERS) ? JSON.parse(readFileSync(USERS, "utf8")) : {}); +const writeUsers = (u) => { writeFileSync(USERS, JSON.stringify(u, null, 1) + "\n", { mode: 0o600 }); try { chmodSync(USERS, 0o600); } catch {} }; +const hash = (pw, salt = randomBytes(16).toString("hex")) => `scrypt$${salt}$${scryptSync(pw, salt, 32).toString("hex")}`; +const verify = (pw, stored) => { const [, salt, h] = String(stored).split("$"); if (!salt || !h) return false; const a = Buffer.from(scryptSync(pw, salt, 32).toString("hex")), b = Buffer.from(h); return a.length === b.length && timingSafeEqual(a, b); }; +const genPw = () => randomBytes(12).toString("base64url"); +function userCli(args) { + const [cmd, name, role] = args, users = readUsers(); + if (cmd === "list") { for (const [n, u] of Object.entries(users)) console.log(`${n}\t${u.role}`); return; } + if (cmd === "remove") { if (!users[name]) throw new Error(`no user ${name}`); delete users[name]; writeUsers(users); console.log(`removed ${name}`); return; } + if (cmd === "add" || cmd === "passwd") { + if (!name || !/^[\w.@-]{1,64}$/.test(name)) throw new Error("user name: letters, digits, . _ - @"); + if (cmd === "add" && !ROLES[role]) throw new Error(`role must be one of: ${Object.keys(ROLES).join(", ")}`); + if (cmd === "passwd" && !users[name]) throw new Error(`no user ${name}`); + const given = process.env.ADMIN_PASSWORD, pw = given || genPw(); + if (given && given.length < 8) throw new Error("ADMIN_PASSWORD must be at least 8 characters"); + users[name] = { role: cmd === "add" ? role : users[name].role, hash: hash(pw), created: users[name]?.created ?? new Date().toISOString() }; + writeUsers(users); + console.log(`${cmd === "add" ? "added" : "updated"} ${name} (${users[name].role})${given ? "" : `; password: ${pw}`}`); + return; + } + throw new Error("usage: node server.mjs user add | passwd | list | remove "); +} + +// ---------- sessions ---------- +function secret() { + if (!existsSync(SECRET_FILE)) writeFileSync(SECRET_FILE, randomBytes(32).toString("hex"), { mode: 0o600 }); + return readFileSync(SECRET_FILE, "utf8").trim(); +} +const sign = (payload, key) => { const b = Buffer.from(JSON.stringify(payload)).toString("base64url"); return `${b}.${createHmac("sha256", key).update(b).digest("base64url")}`; }; +function unsign(token, key) { + const [b, s] = String(token || "").split("."); + if (!b || !s) return null; + const want = createHmac("sha256", key).update(b).digest("base64url"); + if (want.length !== s.length || !timingSafeEqual(Buffer.from(want), Buffer.from(s))) return null; + try { const p = JSON.parse(Buffer.from(b, "base64url").toString()); return p.e > Date.now() ? p : null; } catch { return null; } +} +const cookies = (req) => Object.fromEntries(String(req.headers.cookie || "").split(/;\s*/).filter(Boolean).map((c) => { const i = c.indexOf("="); return [c.slice(0, i), decodeURIComponent(c.slice(i + 1))]; })); + +// ---------- database ---------- +function openDb() { + if (!existsSync(DB_PATH)) throw new Error(`Database not found: ${DB_PATH}`); + const db = new DatabaseSync(DB_PATH); + db.exec("PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 3000;"); + return db; +} + +class HttpError extends Error { constructor(status, message, fields) { super(message); this.status = status; this.fields = fields; } } + +function buildModel(db) { + const schema = introspect(db); + const out = new Map(); + for (const tc of CFG.tables || []) { + const t = schema.find((x) => x.name === tc.name); + if (!t) { console.warn(`! table ${tc.name} from admin.config.json is not in the database; skipped`); continue; } + const cols = new Set(t.columns.map((c) => c.name)); + const ops = (tc.ops || ["read"]).filter((o) => t.type === "table" || o === "read"); + const keyed = t.type === "table"; + out.set(t.name, { + t, ops, label: tc.label || t.name, labelColumn: cols.has(tc.labelColumn) ? tc.labelColumn : labelColumn(t), + list: (tc.list || t.columns.slice(0, 7).map((c) => c.name)).filter((c) => cols.has(c)), + search: (tc.search || t.columns.filter((c) => ["text", "email", "tel", "longtext", "url", "select"].includes(c.kind)).map((c) => c.name)).filter((c) => cols.has(c)), + hidden: new Set((tc.hidden || []).filter((c) => cols.has(c))), + keyCols: !keyed ? [] : t.rowid ? ["rowid"] : t.pk, + }); + } + return { schema, tables: out }; +} + +const escLike = (s) => s.replace(/[\\%_]/g, (c) => `\\${c}`); +function keyWhere(m, key) { + let vals; + try { vals = JSON.parse(key); } catch { throw new HttpError(400, L.bad); } + if (!Array.isArray(vals) || vals.length !== m.keyCols.length || !m.keyCols.length) throw new HttpError(400, L.bad); + return { sql: m.keyCols.map((c) => `${c === "rowid" ? "rowid" : qi(c)} = ?`).join(" AND "), params: vals }; +} +const keySelect = (m) => (m.keyCols.length ? m.keyCols.map((c, i) => `${c === "rowid" ? "rowid" : qi(c)} AS "__k${i}"`).join(", ") + ", " : ""); +function shape(m, row) { + const o = { _key: m.keyCols.length ? JSON.stringify(m.keyCols.map((_, i) => row[`__k${i}`])) : null }; + for (const c of m.t.columns) if (!m.hidden.has(c.name)) o[c.name] = row[c.name]; + return o; +} +function fkLabels(db, model, m, rows) { + const labels = {}; + for (const c of m.t.columns) { + if (!c.fk || !rows.length) continue; + const target = model.schema.find((x) => x.name === c.fk.table); + if (!target) continue; + const lc = model.tables.get(target.name)?.labelColumn ?? labelColumn(target); + const vals = [...new Set(rows.map((r) => r[c.name]).filter((v) => v !== null && v !== undefined))]; + if (!vals.length) continue; + const res = db.prepare(`SELECT ${qi(c.fk.column)} AS v, ${qi(lc)} AS l FROM ${qi(target.name)} WHERE ${qi(c.fk.column)} IN (${vals.map(() => "?").join(",")})`).all(...vals); + labels[c.name] = Object.fromEntries(res.map((r) => [String(r.v), r.l])); + } + return labels; +} +function mapSqlError(e, t) { + const msg = String(e?.message || e); + let m = /UNIQUE constraint failed: ([^\n]+)/.exec(msg); + if (m) { const fields = {}; for (const part of m[1].split(",")) fields[part.trim().split(".").pop()] = L.dup; return new HttpError(409, L.dup, fields); } + m = /NOT NULL constraint failed: \S+\.(\S+)/.exec(msg); + if (m) return new HttpError(400, L.fix, { [m[1]]: ZH ? "必填" : "Required" }); + if (/FOREIGN KEY constraint failed/.test(msg)) return new HttpError(409, t === "delete" ? L.inuse : L.fkbad); + if (/CHECK constraint failed/.test(msg)) return new HttpError(400, `${L.check}: ${msg.replace(/^.*CHECK constraint failed: /, "")}`); + return new HttpError(500, msg); +} +const audit = (user, action, table, key) => { try { appendFileSync(AUDIT, `${new Date().toISOString()}\t${user}\t${action}\t${table}\t${key ?? ""}\n`); } catch {} }; + +// ---------- http ---------- +const STATIC = { "/": ["index.html", "text/html; charset=utf-8"], "/app.js": ["app.js", "text/javascript; charset=utf-8"], "/style.css": ["style.css", "text/css; charset=utf-8"] }; +function send(res, status, body, type = "application/json; charset=utf-8", extra = {}) { + res.writeHead(status, { "Content-Type": type, "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "no-referrer", "Cache-Control": "no-store", + "Content-Security-Policy": "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", ...extra }); + res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body)); +} +const readBody = (req) => new Promise((ok, fail) => { + let n = 0; const chunks = []; + req.on("data", (c) => { n += c.length; if (n > 1_000_000) { fail(new HttpError(413, "Too large")); req.destroy(); } else chunks.push(c); }); + req.on("end", () => { try { ok(chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {}); } catch { fail(new HttpError(400, L.bad)); } }); + req.on("error", fail); +}); + +export function start({ port = Number(process.env.PORT ?? CFG.port ?? 8787), host = process.env.HOST || "127.0.0.1" } = {}) { + const db = openDb(); + const model = buildModel(db); + const key = secret(); + const fails = new Map(); + const ttl = (CFG.sessionHours ?? 12) * 3600_000; + const server = createServer(async (req, res) => { + const url = new URL(req.url, "http://x"); + const path = url.pathname; + try { + if (req.method === "GET" && STATIC[path]) { const [f, type] = STATIC[path]; return send(res, 200, readFileSync(join(HERE, "public", f)), type); } + if (path === "/favicon.ico") { res.writeHead(204); return res.end(); } + if (!path.startsWith("/api/")) throw new HttpError(404, L.nf); + if (req.method !== "GET" && req.headers["x-admin"] !== "1") throw new HttpError(403, "Missing X-Admin header"); + if (path === "/api/login" && req.method === "POST") { + const ip = req.socket.remoteAddress || "?", f = fails.get(ip); + if (f && f.n >= 5 && Date.now() - f.t < 600_000) throw new HttpError(429, L.locked); + const { user, password } = await readBody(req); + const u = readUsers()[String(user || "")]; + if (!u || !verify(String(password || ""), u.hash)) { fails.set(ip, { n: (f && Date.now() - f.t < 600_000 ? f.n : 0) + 1, t: Date.now() }); throw new HttpError(401, L.login); } + fails.delete(ip); + const secure = req.headers["x-forwarded-proto"] === "https" ? "; Secure" : ""; + return send(res, 200, { ok: true, user, role: u.role }, undefined, { "Set-Cookie": `adm=${encodeURIComponent(sign({ u: user, e: Date.now() + ttl }, key))}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${ttl / 1000 | 0}${secure}` }); + } + if (path === "/api/logout" && req.method === "POST") return send(res, 200, { ok: true }, undefined, { "Set-Cookie": "adm=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0" }); + const sess = unsign(cookies(req).adm, key), u = sess && readUsers()[sess.u]; + if (!u || !ROLES[u.role]) throw new HttpError(401, L.auth); + const user = sess.u, can = (m, op) => m.ops.includes(op) && ROLES[u.role].includes(op); + if (path === "/api/meta") { + return send(res, 200, { title: CFG.title, lang: CFG.lang, user, role: u.role, pageSize: CFG.pageSize ?? 25, tables: [...model.tables.values()].filter((m) => can(m, "read")).map((m) => ({ + name: m.t.name, label: m.label, view: m.t.type === "view", rows: m.t.rows, keyed: m.keyCols.length > 0, labelColumn: m.labelColumn, list: m.list.filter((c) => !m.hidden.has(c)), search: m.search, + ops: ["read", "create", "update", "delete"].filter((o) => can(m, o)), + columns: m.t.columns.filter((c) => !m.hidden.has(c.name)).map((c) => ({ name: c.name, kind: c.kind, type: c.type, required: required(c), editable: editable(c), auto: c.auto, pk: c.pk > 0, options: c.options, maxLength: c.maxLength, fk: c.fk ? { table: c.fk.table, column: c.fk.column } : undefined, default: c.default })), + })) }); + } + const mt = /^\/api\/t\/([^/]+)(?:\/(r|options)\/([^/]+))?$/.exec(path); + if (!mt) throw new HttpError(404, L.nf); + const m = model.tables.get(decodeURIComponent(mt[1])); + if (!m || !can(m, "read")) throw new HttpError(404, L.nf); + const T = qi(m.t.name); + if (mt[2] === "options") { + const c = m.t.columns.find((x) => x.name === decodeURIComponent(mt[3])); + if (!c?.fk) throw new HttpError(404, L.nf); + const target = model.schema.find((x) => x.name === c.fk.table); + if (!target) throw new HttpError(404, L.nf); + const lc = model.tables.get(target.name)?.labelColumn ?? labelColumn(target); + return send(res, 200, { options: db.prepare(`SELECT ${qi(c.fk.column)} AS value, ${qi(lc)} AS label FROM ${qi(target.name)} ORDER BY 2 LIMIT 2000`).all() }); + } + if (mt[2] === "r") { + const w = keyWhere(m, decodeURIComponent(mt[3])); + if (req.method === "GET") { + const row = db.prepare(`SELECT ${keySelect(m)}* FROM ${T} WHERE ${w.sql}`).get(...w.params); + if (!row) throw new HttpError(404, L.nf); + return send(res, 200, { row: shape(m, row), labels: fkLabels(db, model, m, [row]) }); + } + if (req.method === "PUT") { + if (!can(m, "update")) throw new HttpError(403, L.forbid); + const body = await readBody(req); + for (const h of m.hidden) delete body[h]; + const { values, errors } = validateRow(m.t, body, "update", CFG.lang); + if (Object.keys(errors).length) throw new HttpError(400, L.fix, errors); + const cols = Object.keys(values); + if (!cols.length) throw new HttpError(400, L.nothing); + let r; + try { r = db.prepare(`UPDATE ${T} SET ${cols.map((c) => `${qi(c)} = ?`).join(", ")} WHERE ${w.sql}`).run(...cols.map((c) => values[c]), ...w.params); } catch (e) { throw mapSqlError(e, "update"); } + if (!r.changes) throw new HttpError(404, L.nf); + audit(user, "update", m.t.name, mt[3]); + const nk = m.keyCols.map((c, i) => (c in values ? values[c] : w.params[i])); + const row = db.prepare(`SELECT ${keySelect(m)}* FROM ${T} WHERE ${keyWhere(m, JSON.stringify(nk)).sql}`).get(...nk); + return send(res, 200, { row: row ? shape(m, row) : null }); + } + if (req.method === "DELETE") { + if (!can(m, "delete")) throw new HttpError(403, L.forbid); + let r; + try { r = db.prepare(`DELETE FROM ${T} WHERE ${w.sql}`).run(...w.params); } catch (e) { throw mapSqlError(e, "delete"); } + if (!r.changes) throw new HttpError(404, L.nf); + audit(user, "delete", m.t.name, mt[3]); + return send(res, 200, { ok: true }); + } + throw new HttpError(405, L.bad); + } + if (req.method === "POST") { + if (!can(m, "create")) throw new HttpError(403, L.forbid); + const body = await readBody(req); + for (const h of m.hidden) delete body[h]; + const { values, errors } = validateRow(m.t, body, "create", CFG.lang); + if (Object.keys(errors).length) throw new HttpError(400, L.fix, errors); + const cols = Object.keys(values); + let r; + try { r = db.prepare(cols.length ? `INSERT INTO ${T} (${cols.map(qi).join(", ")}) VALUES (${cols.map(() => "?").join(", ")})` : `INSERT INTO ${T} DEFAULT VALUES`).run(...cols.map((c) => values[c])); } catch (e) { throw mapSqlError(e, "create"); } + const row = /WITHOUT\s+ROWID/i.test(m.t.sql) ? db.prepare(`SELECT ${keySelect(m)}* FROM ${T} WHERE ${m.t.pk.map((c) => `${qi(c)} = ?`).join(" AND ")}`).get(...m.t.pk.map((c) => values[c])) : db.prepare(`SELECT ${keySelect(m)}* FROM ${T} WHERE rowid = ?`).get(r.lastInsertRowid); + const out = row ? shape(m, row) : null; + audit(user, "create", m.t.name, out?._key); + return send(res, 201, { row: out }); + } + if (req.method !== "GET") throw new HttpError(405, L.bad); + // list + const where = [], params = []; + const q = (url.searchParams.get("q") || "").trim(); + if (q && m.search.length) { where.push(`(${m.search.map((c) => `CAST(${qi(c)} AS TEXT) LIKE ? ESCAPE '\\'`).join(" OR ")})`); for (const _ of m.search) params.push(`%${escLike(q)}%`); } + for (const [k, v] of url.searchParams) { + if (!k.startsWith("f.")) continue; + const c = m.t.columns.find((x) => x.name === k.slice(2)); + if (!c || m.hidden.has(c.name)) throw new HttpError(400, L.bad); + if (v === "\u2205") where.push(`${qi(c.name)} IS NULL`); else { where.push(`${qi(c.name)} = ?`); params.push(v); } + } + const sortCol = m.t.columns.find((x) => x.name === url.searchParams.get("sort") && !m.hidden.has(x.name)); + const dir = url.searchParams.get("dir") === "desc" ? "DESC" : "ASC"; + const order = sortCol ? `${qi(sortCol.name)} ${dir}` : m.keyCols.length ? m.keyCols.map((c) => (c === "rowid" ? "rowid" : qi(c))).join(", ") + " DESC" : "1"; + const size = Math.min(200, Math.max(1, Number(url.searchParams.get("size")) || (CFG.pageSize ?? 25))); + const page = Math.max(0, Number(url.searchParams.get("page")) || 0); + const W = where.length ? ` WHERE ${where.join(" AND ")}` : ""; + const total = db.prepare(`SELECT COUNT(*) AS n FROM ${T}${W}`).get(...params).n; + const rows = db.prepare(`SELECT ${keySelect(m)}* FROM ${T}${W} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...params, size, page * size); + return send(res, 200, { total, page, size, rows: rows.map((r) => shape(m, r)), labels: fkLabels(db, model, m, rows) }); + } catch (e) { + const status = e instanceof HttpError ? e.status : 500; + if (status === 500) console.error(e); + return send(res, status, { error: e.message, fields: e.fields }); + } + }); + return new Promise((ok) => server.listen(port, host, () => { + const a = server.address(); + console.log(`${CFG.title}: admin running at http://${a.address === "::1" ? "localhost" : a.address}:${a.port} (database ${DB_PATH})`); + ok({ server, port: a.port, close: () => new Promise((d) => { server.close(() => { db.close(); d(); }); server.closeAllConnections?.(); }) }); + })); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const [cmd, ...rest] = process.argv.slice(2); + try { + if (cmd === "user") userCli(rest); + else { + if (!Object.keys(readUsers()).length) { const pw = process.env.ADMIN_PASSWORD || genPw(); writeUsers({ admin: { role: "admin", hash: hash(pw), created: new Date().toISOString() } }); console.log(`First start: created user "admin"${process.env.ADMIN_PASSWORD ? "" : ` with password ${pw}`} — change it with: node server.mjs user passwd admin`); } + await start(); + } + } catch (e) { console.error(String(e?.message || e)); process.exit(1); } +} 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; +} 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(/