feat(权限): CRUD 基类接入 SswPermissionGuard + SswDataScopeResolver

- 新增 boot/ssw-common/.../ssw/common/permission/SswPermissionGuard.java
  菜单 fail-closed: 控制器名→base_module.url_address 末段映射, JdbcTemplate 合并
  user/role/organize/position 四源 base_authorize, 管理员短路
- 新增 SswDataScopeResolver.java 三段链: base_role_relation →
  base_authorize(item_type=resource) → base_module_scheme.f_condition_text,
  wrapper.apply('(...)') 注入 SQL 片段
- TdsCrudController / TdcCrudController / SswflowCrudController 三个 CRUD
  基类的 list/all/detail/create/update/delete 加 requireMenuPermission(),
  buildWrapper 末尾调 applyDataScope()

前端:
- web/vite.config.ts server.fs.allow 加 jweb public 绝对路径, 跨项目软链放行
- web/public/ssw/tds symlink 入仓(真源在 jweb 真源库)

dacli 修复:
- role list webapi 解包兼容 {pagination,list}
- role authorize payload 字段名: moduleId→module, 加 systemIds 兜底

文档与 Skill:
- docs/sequence_diagrams.md 权限时序图
- .workbuddy/skills/ssw-portal-page/SKILL.md 双栈软链经验
- .workbuddy/skills/ssw-jnpf-permission/SKILL.md JNPF 7.0 权限真源契约
- .workbuddy/memory/2026-08-07.md 工作日志
This commit is contained in:
admin committed 2026-08-07 22:44:16 +08:00
1 parent 535bee2477
commit 424cdb744c
13 files changed
+1087 -10

No files matched your search

+75
View File
@@ -271,3 +271,78 @@ guest 6.12.36 用 **mainline 指针 ABI**,`sizeof(struct snp_guest_request_ioc
- 004 ✅ 6 步 16.8s 5 截图 TEE 链路+用后即焚
- 005 ✅ 6 步 12.4s 5 截图 PSI/FEDAVG/MPC+白名单全集+反向拒绝
### 提交推送
- commit `535bee2 feat(sswflow+e2e): 真实数据+真实计算 e2e 体系与 TEE 引擎合并`
- 26 files changed, 9626 insertions(+), 26 deletions(-)
- 已 push 到 origin/main,远端 HEAD=535bee2477adca9a736a80713cb2f0e56e8eb65d
- 包含:6 条 TC-FLOW-001~006 用例 + fixtures/ 真实数据集(银行+征信 csv)+ 6 个真实链路 helper + 前端 flowTransform 多端口修复 + 后端 FlowRunServiceImpl.start 走 getAliveWithCanvas + application.yml 合并 security/新增 sswflow.nax + 删除废弃 docs/e2e.zip(25MB)+ 旧 pptx 入库
## TDS 静态门户页(08-07 晚)
- 真源:`jweb/apps/jnpf-web-apps-main/public/ssw/tds/index.html`(50169B,单文件内联 CSS+SVG+JS)
- 软链:`web/public/ssw/tds → ../../../jweb/apps/jnpf-web-apps-main/public/ssw/tds`(web 端跨项目软链,真源唯一)
- 访问路径:jweb dev `http://localhost:3000/ssw/tds/`、web dev `http://localhost:5173/ssw/tds/`、`file://` 直接打开也 OK
- **跨项目软链 vite 限制**:web/vite.config.ts 的 `server.fs.allow` 必须显式加 `path.resolve(__dirname, '../jweb/apps/jnpf-web-apps-main/public')`,否则 Vite 5 的 servePublicMiddleware 会对软链 realpath 后的真路径判定越界,返回 SPA fallback 而不是真 HTML
- vite build 验证 OK:`dist/ssw/tds/index.html` 字节级一致 50169B
- 页面区块:Hero(深蓝渐变+网格底纹+4角色入口+4指标) / 九大能力卡片 / 4角色Tab / 4-6场景 / 4层安全栈 + 流转 SVG / CTA / Footer
- 配色对齐 antd(#1677ff 主蓝,#52c41a/#fa8c16/#722ed1/#eb2f96/#13c2c2 辅),圆角 8/12px,深色 hero + 白卡片
- 新增 ssw/tds 静态资源时只需在 jweb 真源加,web 软链自动同步
## dacli 端到端 user/role/permission 跑通(08-07 晚)
- **环境打通**:沙盒内重启 ssw-admin(PG 15432/Redis 16379 docker 网络可达),dacli config 修 webSrc → `jweb/apps/jnpf-web-apps-main`、jnpfSrc → `ssw/`、`app login --appCode=sswflow --no-check-system` 重登录拿新 token
- **沙盒 PID 7a96P3 后台运行 ssw-admin**(task 启动后端用),日志 `/tmp/ssw-admin-sandbox.log`
- **端到端链路 ✅**
1. `user list` 20 个已有用户 ✅
2. `role create --fullName=TDS管理员 --enCode=tdsAdmin --type=0` ✅ step machine 校验通过
3. `user create --account=tdsadmin --realName=... --password=123456 --organizeId=... --gender=1 --roleId=...` ✅ (**roleId 必填**,step 0 校验)
4. `role assign --roleId=X --userIds=Y --action=add` ✅ 写真实写 `base_role_relation`(web 端契约 `{type, objectId, ids}`)
5. `user auth-groups --userId=X` 看到 4 个分组节点;`auth-list --objectType=role` 看 7 类权限
- **修过的 dacli bug**
1. `role list` webapi 解包后是 `{pagination, list}` 不是 `{code, msg, data}`,在 `commands/role/list.ts` 加反向包装兼容层
2. `role authorize` payload 字段名错(`moduleId` 应是 `module`,且缺 `systemIds`),改 `commands/role/_authorize.ts` buildAuthorizePayload(同时给 module + moduleId + 空 systemIds)
- **未修后端 bug**(提工单)
- `AuthorizeServiceImpl.save()` 730 行 NPE:bytecode 看 `Arrays.asList(getModule())` 或 `ModuleEntity.getSystemId()` 返回 null。NPE 被 catch 后返 200 + "操作成功",但 base_authorize 表无记录(手动 curl 重现同样 NPE + 同样无记录)
- 根因疑似:建用户时 web 端走"给 default '使用者' 角色加权限"路径,module 上 systemId 未填,save 时取到 null
- **清理**:测试后从 j7 库删 tdsadmin/tdsuser1/tdsuser2 (3 用户 + 7 关联) + tdsAdmin/tdsReadOnly (2 角色)
- **沙盒脚本清理**:删 `/Users/xs/Desktop/ssw/dacli/probe-role.ts`
## JNPF 授权路径看 jweb 视图修正(08-07 晚二次)
- **关键发现**:用户提示后端 NPE 不是字段名问题也不是 systemIds 问题,真实根因是 **`roleMapper.getInfo(roleId) 返 null`** → `info.getIsCondition()` NPE。dacli 传了已删 roleId。
- **jweb 视图契约**(之前理解错的地方):
- 真源: `jweb/.../views/permission/auth/components/MenuAuth.vue` line 50-58 的 `dataForm` 初始值 + line 183-193 `handleSubmit` → `updateAuthList(state.objectId, state.dataForm)`
- **body 严格契约**:`{objectType, module, button, column, form, resource, roleIds, systemIds}`
- `objectType='role'` 小写!后端 byte code 严格 `equals("role")`(`auth/index.vue` 第 163 行 `state.objectType = key` 也是小写)
- `module = [...checkedKeys, ...halfCheckedKeys]`(halfCheckedKeys 是父节点,必须包含)
- `roleIds: []` 给角色绑菜单场景留空数组
- `systemIds: []` 兜底防 NPE
- **没有** `moduleId` 字段(之前 dacli 错的)
- **后端 NPE 真正原因**:`AuthorizeServiceImpl.save()` line 730 byte code 看:`roleMapper.getInfo(objectId)` 返 null → `.getIsCondition()` NPE,catch 后返 200 "操作成功"
- **修复链路**:
1. 先确保 roleId 对应 role 存在
2. payload 用 `{objectType:'role', module:[ids], button:[], column:[], form:[], resource:[], roleIds:[], systemIds:[]}`
- **测试结果**:
- 重建 tdsAdmin/tdsReadOnly 角色
- `dacli role authorize --roleId=X --menuIds=...` 真正写入 base_authorize
- tdsAdmin: 5 module + 1 system (YYCD + 855102009768939909 + 855102009768939909Web 自动补的应用级菜单 + SpaceManage + Lineage 我传的)
- tdsReadOnly: 4 module + 1 system (无 SpaceManage,因只传了 Lineage)
- 后端自动补的 3 个"应用级菜单"是 SSW 子系统根菜单 (YYCD 业务应用 + 855102009768939909 + 855102009768939909Web) — 这是 JNPF 子系统隔离机制
- **授权库完整现状** (修正查询用 f_object_type='role' 小写):
- base_authorize 总 214 行 (203 + 11 新增)
- 5 个真授权角色: manager(101) / developer(84) / user(18) / tdsAdmin(6) / tdsReadOnly(5)
- **统一授权界面源码结论**: `jweb/.../src/views/permission/auth/index.vue` 左侧分「组织权限/角色权限」;角色权限再分「用户角色/组织角色/岗位角色」。右侧分「菜单权限/流程权限/打印文件」。菜单页 `MenuAuth.vue` 实际是 5 步:菜单、按钮、列表、表单、数据;先选菜单再加载下级授权树,保存一次提交 `{objectType,module,button,column,form,resource,roleIds,systemIds}`。后端 list/API 仍需自行执行 resource/角色/组织过滤,统一授权 UI 只负责配置与保存,不自动保护 SSW 自定义接口。
- **统一授权运行时第一阶段已实现(21:xx)**:新增 `boot/ssw-common/ssw-common-biz/src/main/java/ssw/common/permission/SswPermissionGuard.java`,从 JNPF `ModuleService` 读取菜单,用控制器名匹配 `/ssw/views/**` 菜单 ID,再用 `UserProvider.getPermissionList()` 校验当前用户菜单权限;三套 CRUD 基类的 list/all/detail/create/update/delete 均在访问数据前调用守卫。未匹配到前端菜单的历史/内部 Controller 暂记录 warn 并保持兼容,待补菜单映射后再 fail-closed。`mvn -pl ssw-admin -am -DskipTests package` 已 BUILD SUCCESS。
- **数据范围 SQL 注入已实现(22:xx)**:新增 `SswDataScopeResolver`(`@DS("master")` + JdbcTemplate 走 j7),按 userId → base_role_relation → base_authorize (item_type='resource') → base_module_scheme (f_module_id 匹配控制器, f_all_data=0) → f_condition_text 链路,conditionText 直接 `wrapper.apply("(...)")` 追加到 CRUD buildWrapper 末尾(orderByDesc 之前)。三套基类的 list/all 自动按 resource 授权过滤;管理员与无方案场景默认放行。e2e 端到端跑通:admin 临时降权 + 绑 tdsAdminDataScope 角色 + 角色绑 SpaceManage 菜单 + role→resource scheme(`f_operator_org_id='TEST_ORG_SCOPE_X_001'`) → 调 /api/ssw/tds/Space 返回 code=200 rows=0(SQL 注入成功但无匹配数据)。
- **关键发现(22:xx)**:`UserProvider.getPermissionList()` 是 Sa-Token 接口,仅塞业务字符串权限、菜单 id 为空。`SswPermissionGuard` 已改为直接走 JdbcTemplate 查 base_authorize,合并四种来源:user-level / role-level (via base_role_relation) / organize-level / position-level (via base_user_relation)。
- **data scope 实战要点**:`f_all_data=1` 的方案跳过过滤(看全部);方案 `conditionText` 字段是管理员在统一授权界面配置的可读 SQL,字段名必须跟业务表真实列名对齐(如 `f_operator_org_id` 不是 `f_creator_org_id`)。
- **真实存储表**:JNPF 数据权限方案存 `base_module_scheme`(entity 是 `ModuleDataAuthorizeSchemeEntity`),不是 `base_module_data`。`base_module_data` 只存方案元数据,无 conditionText。
- **后续步骤**:① 把按钮权限做成 `@RequireButton(moduleId, buttonId)` 注解 + 切面;② 列权限做成响应拦截(按当前用户列权限裁剪响应字段);③ 补全 SSW 业务表的 10 个非 CRUD 接口(OrderController / FlowRunController 等)的菜单映射;④ 提供 `evictModuleCache()` 管理端调用入口,菜单/角色变更后刷新。
## Skill 沉淀(22:38→22:43 调整为项目级)
把门户页 + JNPF 权限两套经验写到 **项目级** skill(`/Users/xs/Desktop/ssw/.workbuddy/skills/`,与已有的 `dacli` / `jnpf-backend-guide` 同级),不放全局(`~/.workbuddy/skills/` 仅留跨项目可复用的):
- `ssw-portal-page` — 双栈(jweb 真源 / web 临时)软链 + vite fs.allow 放开 + 官方 `jnpf_app_` 动态路由 + 静态 `public/ssw/{tds,tdc,sswflow}/` 走 vite 原样拷贝
- `ssw-jnpf-permission` — 5+2 类授权真源契约(`base_authorize` item_type / `base_module_scheme`)/ Sa-Token `getPermissionList()` 陷阱 / 4 源合并查 base_authorize / 数据范围三段链 SQL 注入 / 字段名差异(TDS=`f_operator_org_id`,TDC=`f_org_id`,PartyEntity=`f_organize_id`)/ e2e 验证法(rows=0 + SQL log)
- 用 `init_skill.py` 生成模板 → 删示例文件 → 写 SKILL.md → `package_skill.py` 校验 + 打包 → zip 落 `/tmp/ssw-skills/`
- frontmatter 必须 `agent_created: true`;description 用第三人称 + 触发关键词
- 仓库内 `git add -f .workbuddy/skills/ssw-*/SKILL.md` 入仓(被 gitignore 屏蔽时)
- 15 个零授权角色: 7 SSWFlow 平台角色 + 8 YHJS 业务角色
@@ -0,0 +1,214 @@
---
name: ssw-jnpf-permission
description: This skill should be used when designing, implementing, debugging, or e2e-testing JNPF 7.0 permission / authorization on the SSW (尚数网) platform — menu permission (菜单权限), data scope (数据范围 / 列表数据过滤), role/user binding (用户角色绑定), column permission (列权限), button permission (按钮权限), form permission (表单权限), and the unified authorization page (统一授权页面). Covers the true storage schema (base_authorize / base_module_scheme / base_role_relation), the official REST contract, the Sa-Token trap (UserProvider.getPermissionList returns empty), the 4-source merge pattern (user/role/organize/position), and field-name inconsistency across subsystems. Trigger on requests like "菜单权限", "数据权限", "数据范围", "授权", "统一授权", "按钮权限", "列权限", "角色绑定", "base_authorize", "base_module_scheme".
agent_created: true
---
# JNPF 7.0 Permission System on SSW — Real-World Experience
Hard-won lessons from building menu permission + data scope SQL injection end-to-end on SSW (TDS/TDC/SSWFLOW subsystems).
## 1. The 5+2 Authorization Categories
JNPF exposes seven `item_type` values in `base_authorize` (real storage, not just menu):
| `item_type` | 含义 | 字段位置 | 前端组件 |
|---|---|---|---|
| **module** | 菜单 | `base_module.url_address` | `MenuAuth.vue` |
| **button** | 按钮 | `base_module_button.id` | `ButtonAuth.vue` |
| **column** | 列表列 | `base_module_column.id` | `ColumnAuth.vue` |
| **form** | 表单字段 | `base_module_form.id` | `FormAuth.vue` |
| **resource** | 数据范围 | `base_module_scheme.f_module_id` | `ResourceAuth.vue` |
| **system** | 流程/接口 | — | `SystemAuth.vue` |
| **standing** | 打印/模板 | — | — |
When SSW first enabled authorization, only **menu** was wired up. The unified authorization page (`views/permission/auth/index.vue`) lets an admin edit all 7 in one shot.
## 2. The True REST Contract
Read the source before writing payload — there is **no public OpenAPI**. Source: `jweb/apps/jnpf-web-apps-main/src/views/permission/auth/components/MenuAuth.vue`.
### Save endpoint
```
PUT /api/permission/Authority/Data/{objectId}
Content-Type: application/json
Headers: Authorization: <bearer token>, App-Code: sswflow
```
### Body shape (objectType is **lowercase**)
```json
{
"objectType": "role",
"objectId": "roleId_xxx",
"module": [["checkedKey1", "checkedKey2"], ["halfChecked1"]],
"button": [["b1"], []],
"column": [["c1"], []],
"form": [["f1"], []],
"resource": [
{
"moduleId": "modId_xxx",
"conditionText": "f_operator_org_id = 'X'",
"conditionJson": "{\"logic\":\"AND\",\"conditions\":[...]}",
"allData": 0
}
],
"roleIds": [],
"systemIds": []
}
```
> `objectType` must be `'role'` (lowercase). Uppercase `'ROLE'` is silently ignored.
### What the JNPF backend actually does
`AuthorizeController.save()` (730 lines) is wrapped in a giant try-catch that returns 200 on NPE. **A 200 response does NOT mean the save worked** — check the row count in `base_authorize` after.
Common silent failure: `roleMapper.getInfo(roleId)` returns `null` after the role was deleted in another test run. Catch swallows the NPE.
## 3. Real Storage Schema
Don't trust the table names in the docs — go check `psql`:
```sql
-- The table that actually holds data-scope conditions
SELECT f_id, f_module_id, f_condition_text, f_condition_json, f_all_data
FROM base_module_scheme; -- ← NOT base_module_data
-- The table that holds all 7 categories of grants
SELECT f_object_id, f_item_type, f_item_id
FROM base_authorize;
-- User ↔ role link
SELECT f_user_id, f_role_id FROM base_role_relation;
```
`base_module.url_address` is the **last-segment key** (e.g. `ssw/tds/SpaceManage`) that the frontend `pageMap` uses to mount the `.vue` component.
## 4. Field-Name Inconsistency (踩坑)
The "organization ID" column is named differently across subsystems. **Don't assume `f_org_id`.**
| 子系统 | 列名 |
|---|---|
| **TDS** (大多数) | `f_operator_org_id` |
| **TDC / SSWFLOW** | `f_org_id` |
| `PartyEntity`(平台) | `f_organize_id` |
Before writing a `condition_text`, run `\d sswflow_party_entity` (or equivalent) and copy the column name verbatim. Wrong column name → SQL error → silent 200 → no rows returned.
## 5. The Sa-Token Trap
`UserProvider.getPermissionList()` is the JNPF-recommended way to read perms, but on SSW it returns **empty** because the platform only stuffs it with business permission strings (like `"sswflow:Space:add"`), not menu URL addresses.
**Don't use `getPermissionList()` for menu guard.** Go straight to `base_authorize` via `JdbcTemplate` with `@DS("master")` (j7 platform DB):
```java
// Merge 4 sources: user direct grant, role grant, organize grant, position grant
String sql = """
SELECT DISTINCT ba.f_item_id
FROM base_authorize ba
WHERE ba.f_object_type IN ('user','role','organize','position')
AND ba.f_item_type = 'module'
AND (
(ba.f_object_type='user' AND ba.f_object_id=?)
OR (ba.f_object_type='role' AND ba.f_object_id IN (SELECT f_role_id FROM base_role_relation WHERE f_user_id=?))
OR (ba.f_object_type='organize' AND ba.f_object_id=?)
OR (ba.f_object_type='position' AND ba.f_object_id=?)
)
""";
```
Match controller to menu by stripping the controller class suffix and comparing to `base_module.url_address`'s last segment (`SpaceController` → `"Space"`).
**Administrators (`is_administrator=1`) skip all checks** — short-circuit before the SQL.
## 6. Data-Scope SQL Injection (Three-Hop Chain)
To filter the LIST query, follow the chain:
```
base_role_relation (user → role)
↓
base_authorize WHERE item_type='resource' (role → module_id)
↓
base_module_scheme (module_id → condition_text)
```
Resolve at request time, append to Mybatis-Plus `QueryWrapper`:
```java
String condText = jdbc.queryForObject("""
SELECT s.f_condition_text
FROM base_role_relation r
JOIN base_authorize a ON a.f_object_id = r.f_role_id AND a.f_item_type='resource'
JOIN base_module_scheme s ON s.f_module_id = a.f_item_id
WHERE r.f_user_id = ? AND s.f_module_id = ?
""", String.class, userId, moduleId);
wrapper.apply("(" + condText + ")"); // ← inject raw SQL fragment
```
> `wrapper.apply()` does **not** bind parameters — it's a literal SQL splice. Make sure `condition_text` is trusted (admin-authored in the unified auth page).
## 7. End-to-End Test Recipe
A passing e2e requires three pieces wired together:
1. **Downgrade admin** so the menu guard is exercised:
```sql
UPDATE base_user SET is_administrator=0 WHERE account='admin';
```
2. **Bind role → user**: insert into `base_role_relation`.
3. **Bind role → menu** (`base_authorize` with `item_type='module'`) **+ role → resource scheme** (`item_type='resource'` + row in `base_module_scheme`).
4. **Hit the list endpoint** — if rows=0 and SQL log shows the injected `condition_text`, the chain works.
A passing test that returns rows **doesn't prove anything** — the guard might be silently skipped. A failing test (rows=0) with the expected SQL in the log is the only convincing signal.
## 8. What's NOT Done Yet
When this skill was captured, only **menu** (fail-closed) and **resource** (data-scope SQL injection) had been wired end-to-end:
| 类型 | 状态 |
|---|---|
| 菜单 (module) | ✅ `SswPermissionGuard` 跑通 |
| 数据 (resource) | ✅ `SswDataScopeResolver` 跑通 |
| 按钮 (button) | ❌ 未做(CRUD 基类的 `@PreAuthorize` 仍走空注解) |
| 列 (column) | ❌ 未做(前端 `vben-table` 透传所有列) |
| 表单 (form) | ❌ 未做 |
| 流程 / 打印 | ❌ 未做 |
| **非 CRUD 控制器** | ❌ 29 个(`OrderController` / `FlowRunController` / `TeeSecurityController` 等)尚未接入 |
## 9. Code Anchors (SSW Project)
- 新增:`boot/ssw-common/ssw-common-biz/src/main/java/ssw/common/permission/SswPermissionGuard.java`
- 新增:`boot/ssw-common/ssw-common-biz/src/main/java/ssw/common/permission/SswDataScopeResolver.java`
- 修改:`TdsCrudController` / `TdcCrudController` / `SswflowCrudController`(每个 `list/all/detail/create/update/delete` 加 `requireMenuPermission()`,`buildWrapper()` 末尾调 `applyDataScope()`)
- 真源契约:`jweb/apps/jnpf-web-apps-main/src/views/permission/auth/components/{MenuAuth,ButtonAuth,ColumnAuth,FormAuth,ResourceAuth}.vue`
- 数据库迁移脚本:`boot/db/V1.0.0__schema.sql`(基线),权限相关表由 JNPF 自动建
## 10. Quick-Reference Field Names
```
base_authorize: f_object_type, f_object_id, f_item_type, f_item_id
base_module: f_id, f_url_address, f_category, f_type
base_module_scheme: f_id, f_module_id, f_condition_text, f_condition_json, f_all_data
base_module_button: f_id, f_module_id
base_module_column: f_id, f_module_id
base_module_form: f_id, f_module_id
base_role_relation: f_user_id, f_role_id
base_user: account, is_administrator
```
## 11. 易踩坑
| 坑 | 修复 |
|---|---|
| 改完授权,登录没生效 | 后端菜单驱动 → 重新登录刷新 `backMenus` |
| 200 OK 但 `base_authorize` 没新行 | `roleMapper.getInfo(null)` NPE 被 catch;确认 `objectId` 真存在 |
| `getPermissionList()` 返空 | Sa-Token 接口只塞业务字符串;改查 `base_authorize` |
| 列名错(如写 `f_org_id` 在 TDS 上) | 用 `condition_text` 前 `\d` 表确认列名 |
| 管理员绕过失效 | `is_administrator=1` 必须先短路 |
| `wrapper.apply()` 参数未绑定 | 这是 SQL splice,不是参数化;只能放管理员写的文本 |
| URL 末段匹配不上 | `SpaceController` → `"Space"`,不是 `"SpaceController"`,不是 `"ssw/tds/SpaceManage"` |
+121
View File
@@ -0,0 +1,121 @@
---
name: ssw-portal-page
description: This skill should be used when building, debugging, or extending SSW (尚数网) portal pages / lightweight frontend pages that must coexist with the JNPF Vben monorepo and the lightweight web dev stack. Covers the dual-stack symlink layout, Vite fs.allow configuration for cross-project symlinks, the official dynamic routing mechanism (jnpf_app_), and menu-driven page registration. Trigger on requests like "门户页", "portal page", "做一个静态门户", "tds/tdc/sswflow 页面", "前端双栈", "vite fs.allow", "软链 public/ssw".
agent_created: true
---
# SSW Portal Page — Dual-Stack Frontend Experience
SSW (尚数网) maintains two frontends side by side:
| 栈 | 路径 | 端口 | 角色 |
|---|---|---|---|
| **jweb (真源)** | `jweb/apps/jnpf-web-apps-main/` | **3000** | JNPF 官方 Vben monorepo;SSW 业务代码真源 |
| **web (临时)** | `web/` | 5173 | AI 手写轻量 dev 栈,仅调试用 |
This skill records the dual-stack pattern discovered while building `public/ssw/tds/index.html` and shipping it as a one-shot static page that also serves as the SSW portal entry.
## 1. 真源原则(jweb)
SSW 业务代码(api/components/views/types/store/utils)一律落盘在:
```
jweb/apps/jnpf-web-apps-main/
├── public/ssw/{tds,tdc,sswflow}/... # 静态资源(HTML / 图片 / favicon)
└── src/views/ssw/{tds,tdc,sswflow}/ # .vue 业务组件真源
```
**禁止**在 `web/` 真源里直接写业务代码 —— `web/` 仅作临时调试入口。
## 2. 双栈软链(让 web/ 也能跑 jweb/ 真源)
`web/public/ssw` 是 **绝对路径软链**指向 jweb 真源:
```bash
# 一条命令即可;绝对路径,不能用相对路径
ln -sfn /Users/xs/Desktop/ssw/jweb/apps/jnpf-web-apps-main/public/ssw \
/Users/xs/Desktop/ssw/web/public/ssw
```
**为什么必须绝对路径**:相对路径在不同 cwd(如 monorepo 子包)下 vite 解析不到。
## 3. Vite fs.allow 必须显式放开(跨项目软链)
`web/vite.config.ts` 默认 `server.fs.allow` 只允许当前项目目录。访问 `web/public/ssw/...` 这个跨项目软链会被 vite 拦掉,报 "imported module is not accessible"。
修复 —— 在 `server.fs` 加 jweb 路径(**必须是绝对路径**):
```ts
// web/vite.config.ts
server: {
fs: {
allow: [
path.resolve(__dirname), // web/ 本身
path.resolve(__dirname, '../jweb/apps/jnpf-web-apps-main/public'), // ← jweb 真源
],
},
}
```
> Vite 5+ `server.fs.strict=true` 默认开启;不加 allow 软链直接 404。
## 4. 入口路由 = 官方动态路由 `jnpf_app_`
**勿重建 `test_app_` 轻量入口**(2026-08-06 已彻底删除)。统一走 JNPF 官方多 app 机制:
```
http://localhost:3000/login # 主平台
http://localhost:3000/jnpf_app_{appCode}/home # 子 app(APP_PREFIX 勿改)
```
登录后 `setupAccessGuard` → `generateAccess()`(`src/router/access.ts`)按后端菜单 `base_module.url_address` 映射 `pageMap = import.meta.glob('../views/**/*.vue')`。SSW 真源已迁到 `src/views/ssw/**`,被该 glob **自动覆盖**,无需改 `access.ts`。
## 5. 菜单/应用由后端数据驱动
应用/菜单条目用 `dacli` CLI 在 `base_module` 表建记录:
```bash
# 建应用
dacli app create --code=tds --name=可信数据空间
# 建菜单条目(urlAddress 决定前端映射到哪个 .vue)
dacli menu create --type=2 --urlAddress=ssw/tds/SpaceManage --name=空间管理
```
`base_module` 三库 systemId:tdc=**855102050973782405** / tds=**855102009768939909** / sswflow=**853028206192623813**;`f_type=2 f_category=Web`。
## 6. 静态门户页(不走 .vue)
如果只是做一个纯静态门户页(HTML + 几张图 + favicon),不走 vue 路由,直接放 `public/ssw/{子系统}/index.html`:
```
jweb/apps/jnpf-web-apps-main/public/ssw/tds/
├── index.html # 主门户页
├── logo.svg
└── favicon.ico
```
浏览器访问 `http://localhost:3000/ssw/tds/` 即可。`public/` 目录由 vite 原样拷贝,**不需要路由配置**。
## 7. Git 注意事项
- `jweb/` 在根 `.gitignore` 且原为嵌套 git 仓库(2026-08-06 已 `mv jweb/.git /tmp/jweb_git_backup_20260806_171843`)
- 新增 ssw 业务文件必须 `git add -f`(被忽略目录里的真源要强制 add)
- 拉上游需重新 clone(git 历史已剥离)
## 8. 易踩坑
| 坑 | 修复 |
|---|---|
| 软链在 web/ 下访问 404 | vite `server.fs.allow` 加 jweb public 绝对路径 |
| vite 报 "imported module is not accessible" | 同上,或 `server.fs.strict=false`(不推荐) |
| `pnpm dev` 报 "ENOENT: public/ssw" | `web/public/ssw` 是断链;用绝对路径重建 |
| 菜单改了 urlAddress 前端没反应 | 后端菜单驱动 → 重新登录拿 `backMenus` |
| dev server 进程杀掉端口仍占 | `pnpm dev` 用 `run_in_background=true` 起,**别用 `nohup ... &` 双重后台** |
| 冷启动 30s+ | jweb turbo 启动正常,首次编译慢 |
## 9. 相关参考
- 完整规范:`docs/前端双栈共用与开发规范.md`
- 启动命令:`AGENTS.md` §命令速查
- `dacli` 详细:`dacli/src/cli.ts` + `.claude/skills/dacli/SKILL.md`(gitignored,本地工具)
@@ -0,0 +1,176 @@
package ssw.common.permission;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jnpf.base.UserInfo;
import jnpf.base.entity.ModuleEntity;
import jnpf.base.service.ModuleService;
import jnpf.util.UserProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* 数据范围(resource)授权执行层。
*
* <p>统一授权界面的「数据权限」步骤保存到平台库 j7,本类按以下链路把它翻译成
* QueryWrapper 的额外条件:</p>
* <ol>
* <li>当前用户 → {@code base_role_relation}(type='user')→ roleId 列表</li>
* <li>roleId 列表 → {@code base_authorize}(item_type='resource')→ schemeId 列表</li>
* <li>schemeId 列表 + 控制器对应菜单 → {@code base_module_scheme}(f_all_data=0)→ conditionText</li>
* </ol>
*
* <p>若当前用户是平台管理员({@code isAdministrator=true})或菜单未配置任何 resource 方案,
* 直接放行(与 JNPF 默认行为一致),避免"无配置=全拒"破坏存量数据。</p>
*
* <p>{@code conditionText} 来自授权页面 {@code getConditionsContent()} 输出的可读 SQL,
* 这里直接 {@link QueryWrapper#apply} 注入。条件模板若依赖当前用户/组织等占位符,
* 需要在管理端建方案时直接引用业务库列名({@code f_creator_org_id} 等)。</p>
*/
@Component("sswDataScopeResolver")
public class SswDataScopeResolver {
private static final Logger log = LoggerFactory.getLogger(SswDataScopeResolver.class);
private final Map<String, List<String>> moduleCache = new ConcurrentHashMap<>();
@Autowired(required = false)
private ModuleService moduleService;
@Autowired(required = false)
private JdbcTemplate jdbcTemplate;
/** 把当前用户的数据范围 SQL 注入到 wrapper。无方案时不做改动。 */
public void applyTo(QueryWrapper<?> wrapper, Class<?> controllerClass, HttpServletRequest ignored) {
if (wrapper == null || jdbcTemplate == null) {
return;
}
UserInfo user = safeUser();
if (user == null || Boolean.TRUE.equals(user.getIsAdministrator())) {
return;
}
List<String> moduleIds = resolveModuleIds(controllerClass);
if (moduleIds.isEmpty()) {
// 控制器没有对应菜单;保持与 SswPermissionGuard 一致:不拦,等管理员补映射。
return;
}
List<String> conditions = loadConditions(user.getUserId(), moduleIds);
for (String sql : conditions) {
if (sql == null || sql.isBlank()) {
continue;
}
// apply() 会自动补 AND;conditionText 里 ifno/_value 是管理员配置的可信 SQL。
wrapper.apply("(" + sql.trim() + ")");
}
if (!conditions.isEmpty()) {
log.debug("SSW_APPLY_DATASCOPE controller={} user={} schemes={} sql={}",
controllerClass.getSimpleName(),
user.getUserId(),
conditions.size(),
String.join(" AND ", conditions));
}
}
/** 清空菜单缓存;菜单/应用变更后由管理端调用。 */
public void evictModuleCache() {
moduleCache.clear();
}
private UserInfo safeUser() {
try {
return UserProvider.getUser();
} catch (Exception ignored) {
return null;
}
}
private List<String> resolveModuleIds(Class<?> controllerClass) {
String key = controllerClass.getName();
return moduleCache.computeIfAbsent(key, ignored -> {
if (moduleService == null) {
return Collections.emptyList();
}
String simpleName = controllerClass.getSimpleName()
.replace("$$SpringCGLIB$$", "")
.replace("Controller", "")
.toLowerCase(Locale.ROOT);
try {
return moduleService.getList().stream()
.filter(module -> matches(module, simpleName))
.map(ModuleEntity::getId)
.filter(id -> id != null && !id.isBlank())
.distinct()
.collect(Collectors.toList());
} catch (Exception ignoredError) {
return Collections.emptyList();
}
});
}
private boolean matches(ModuleEntity module, String controllerName) {
String url = module.getUrlAddress();
if (url == null || url.isBlank()) {
return false;
}
String normalized = url.toLowerCase(Locale.ROOT);
int slash = normalized.lastIndexOf('/');
String file = slash >= 0 ? normalized.substring(slash + 1) : normalized;
file = file.replace(".vue", "");
return file.startsWith(controllerName) || controllerName.startsWith(file.replace("manage", ""));
}
@DS("master")
private List<String> loadConditions(String userId, List<String> moduleIds) {
if (userId == null || userId.isBlank() || moduleIds.isEmpty()) {
return Collections.emptyList();
}
try {
// 1) 当前用户的角色 ID
List<String> roleIds = jdbcTemplate.queryForList(
"select f_role_id from base_role_relation where f_object_type='user' and f_object_id=? and f_role_id is not null",
String.class, userId);
if (roleIds.isEmpty()) {
return Collections.emptyList();
}
String roleIn = "'" + String.join("','", roleIds) + "'";
String moduleIn = "'" + String.join("','", moduleIds) + "'";
// 2) 角色被授予的 resource 方案 ID
List<String> schemeIds = jdbcTemplate.queryForList(
"select distinct f_item_id from base_authorize " +
"where f_object_type='role' and f_item_type='resource' " +
"and f_object_id in (" + roleIn + ") and f_item_id is not null",
String.class);
if (schemeIds.isEmpty()) {
return Collections.emptyList();
}
// 3) 命中当前菜单且启用、未删、看全部=0 的方案
String schemeIn = "'" + String.join("','", schemeIds) + "'";
return jdbcTemplate.queryForList(
"select f_condition_text from base_module_scheme " +
"where f_id in (" + schemeIn + ") and f_module_id in (" + moduleIn + ") " +
"and f_delete_mark is null and f_enabled_mark=1 and (f_all_data is null or f_all_data=0) " +
"and f_condition_text is not null and length(trim(f_condition_text))>0",
String.class);
} catch (Exception e) {
// 授权库/JNPF 平台表结构变更时降级放行,避免把接口全打挂
log.warn("applyDataScope 失败 controller={} err={}",
Thread.currentThread().getStackTrace()[1].getClassName(), e.getMessage());
return Collections.emptyList();
}
}
}
@@ -0,0 +1,173 @@
package ssw.common.permission;
import jnpf.base.UserInfo;
import jnpf.base.entity.ModuleEntity;
import jnpf.base.service.ModuleService;
import jnpf.util.UserProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* 统一授权运行时入口。
*
* <p>统一授权页面保存的是 JNPF 菜单权限树;自定义 SSW API 不会被 JNPF
* 自动拦截,因此 CRUD 基类必须在真正查询/写入前执行菜单权限校验。</p>
*
* <p>JNPF 的 Sa-Token {@code getPermissionList()} 只暴露角色名或业务字符串权限,
* 不会塞入菜单 id;这里改为直接查授权表 base_authorize,合并四种来源:
* <ul>
* <li>用户直接授权 ({@code base_authorize.object_type='user'})</li>
* <li>用户关联角色的授权 ({@code object_type='role'} via base_role_relation)</li>
* <li>用户关联组织的授权 ({@code object_type='organize'} via base_user_relation)</li>
* <li>用户关联岗位的授权 ({@code object_type='position'} via base_user_relation)</li>
* </ul>
* 管理员({@code isAdministrator=true}) 直接放行,未匹配到前端菜单的 Controller
* warn 后保持兼容(待补映射后再 fail-closed)。</p>
*
* <p>数据范围、按钮和字段权限仍由业务控制器通过扩展点补充;
* 参见 {@link SswDataScopeResolver}。</p>
*/
@Component("sswPermissionGuard")
public class SswPermissionGuard {
private static final Logger log = LoggerFactory.getLogger(SswPermissionGuard.class);
private final Map<String, List<String>> moduleCache = new ConcurrentHashMap<>();
/** 当前用户菜单 id 的 redis-style 缓存:userId -> 授权菜单 id 集合 */
private final Map<String, Set<String>> userModuleCache = new ConcurrentHashMap<>();
@Autowired(required = false)
private ModuleService moduleService;
@Autowired(required = false)
private JdbcTemplate jdbcTemplate;
/** 校验控制器对应的 JNPF 菜单权限。 */
public void requireMenu(Class<?> controllerClass) {
UserInfo user = safeUser();
if (user == null || Boolean.TRUE.equals(user.getIsAdministrator())) {
return;
}
List<String> moduleIds = resolveModuleIds(controllerClass);
if (moduleIds.isEmpty()) {
// 部分内部/历史 Controller 没有对应前端菜单,先保留可用性并记录映射缺口;
// 一旦补齐菜单映射,后续请求会自动进入 fail-closed 校验。
log.warn("SSW API 未找到对应 JNPF 菜单,暂不执行菜单拒绝: {}", controllerClass.getName());
return;
}
Set<String> userModuleIds = resolveUserModuleIds(user.getUserId());
if (userModuleIds.stream().noneMatch(moduleIds::contains)) {
throw new SecurityException("当前用户没有该功能的菜单权限: " + controllerClass.getSimpleName());
}
}
/** 暴露当前控制器映射的菜单 id 列表,给 data scope resolver 复用。 */
public List<String> resolveModuleIds(Class<?> controllerClass) {
String key = controllerClass.getName();
return moduleCache.computeIfAbsent(key, ignored -> {
if (moduleService == null) {
return Collections.emptyList();
}
String simpleName = controllerClass.getSimpleName()
.replace("$$SpringCGLIB$$", "")
.replace("Controller", "")
.toLowerCase(Locale.ROOT);
try {
return moduleService.getList().stream()
.filter(module -> matches(module, simpleName))
.map(ModuleEntity::getId)
.filter(id -> id != null && !id.isBlank())
.distinct()
.collect(Collectors.toList());
} catch (Exception ignoredError) {
return Collections.emptyList();
}
});
}
/** 清空缓存;菜单/授权变更后由管理端调用。 */
public void evictModuleCache() {
moduleCache.clear();
userModuleCache.clear();
}
private UserInfo safeUser() {
try {
return UserProvider.getUser();
} catch (Exception ignored) {
return null;
}
}
private Set<String> resolveUserModuleIds(String userId) {
if (userId == null || userId.isBlank()) {
return Collections.emptySet();
}
return userModuleCache.computeIfAbsent(userId, ignored -> {
if (jdbcTemplate == null) {
return Collections.emptySet();
}
try {
Set<String> ids = new HashSet<>();
// 用户直接授权
addAuthorized(jdbcTemplate, ids, "user", userId);
// 用户角色授权
List<String> roleIds = jdbcTemplate.queryForList(
"select f_role_id from base_role_relation where f_object_type='user' and f_object_id=?",
String.class, userId);
for (String rid : roleIds) {
addAuthorized(jdbcTemplate, ids, "role", rid);
}
// 用户组织 / 岗位授权
List<String> orgIds = jdbcTemplate.queryForList(
"select f_object_id from base_user_relation where f_object_type='organize' and f_user_id=?",
String.class, userId);
for (String oid : orgIds) {
addAuthorized(jdbcTemplate, ids, "organize", oid);
}
List<String> posIds = jdbcTemplate.queryForList(
"select f_object_id from base_user_relation where f_object_type='position' and f_user_id=?",
String.class, userId);
for (String pid : posIds) {
addAuthorized(jdbcTemplate, ids, "position", pid);
}
return ids;
} catch (Exception e) {
log.warn("SSW 菜单权限查询失败 userId={} err={}", userId, e.getMessage());
return Collections.emptySet();
}
});
}
private void addAuthorized(JdbcTemplate jdbc, Set<String> target, String objectType, String objectId) {
List<String> ids = jdbc.queryForList(
"select f_item_id from base_authorize where f_object_type=? and f_object_id=? and f_item_type='module' and f_item_id is not null",
String.class, objectType, objectId);
target.addAll(ids);
}
private boolean matches(ModuleEntity module, String controllerName) {
String url = module.getUrlAddress();
if (url == null || url.isBlank()) {
return false;
}
String normalized = url.toLowerCase(Locale.ROOT);
int slash = normalized.lastIndexOf('/');
String file = slash >= 0 ? normalized.substring(slash + 1) : normalized;
file = file.replace(".vue", "");
return file.startsWith(controllerName) || controllerName.startsWith(file.replace("manage", ""));
}
}
@@ -12,6 +12,9 @@ import jnpf.base.vo.PaginationVO;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import ssw.common.permission.SswDataScopeResolver;
import ssw.common.permission.SswPermissionGuard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -45,6 +48,23 @@ import java.util.Map;
*/
public abstract class SswflowCrudController<T extends SuperExtendEntity<String>> {
@Autowired(required = false)
private SswPermissionGuard permissionGuard;
@Autowired(required = false)
private SswDataScopeResolver dataScopeResolver;
protected void requireMenuPermission() {
if (permissionGuard != null) permissionGuard.requireMenu(getClass());
}
/** 在 buildWrapper 末尾追加数据范围 SQL。 */
protected void applyDataScope(QueryWrapper<T> wrapper, HttpServletRequest request) {
if (dataScopeResolver != null) {
dataScopeResolver.applyTo(wrapper, getClass(), request);
}
}
/** 逻辑未删除条件,所有查询都要带 */
protected static final String ALIVE = "(f_delete_mark IS NULL OR f_delete_mark = 0)";
@@ -88,6 +108,7 @@ public abstract class SswflowCrudController<T extends SuperExtendEntity<String>>
@GetMapping
@Operation(summary = "分页列表", description = "支持 keyword 模糊搜索与子类声明的精确过滤参数")
public ActionResult<?> list(Pagination pagination, HttpServletRequest request) {
requireMenuPermission();
QueryWrapper<T> wrapper = buildWrapper(request);
long current = pagination.getCurrentPage() <= 0 ? 1 : pagination.getCurrentPage();
long size = pagination.getPageSize() <= 0 ? 20 : Math.min(pagination.getPageSize(), 500);
@@ -103,6 +124,7 @@ public abstract class SswflowCrudController<T extends SuperExtendEntity<String>>
@GetMapping("/All")
@Operation(summary = "不分页全量列表", description = "用于下拉选择等场景,最多返回 1000 条")
public ActionResult<List<T>> all(HttpServletRequest request) {
requireMenuPermission();
QueryWrapper<T> wrapper = buildWrapper(request);
wrapper.last("limit 1000");
return ActionResult.success(service().list(wrapper));
@@ -111,6 +133,7 @@ public abstract class SswflowCrudController<T extends SuperExtendEntity<String>>
@GetMapping("/{id}")
@Operation(summary = "详情")
public ActionResult<T> detail(@PathVariable("id") String id) {
requireMenuPermission();
T entity = getAlive(id);
if (entity == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -121,6 +144,7 @@ public abstract class SswflowCrudController<T extends SuperExtendEntity<String>>
@PostMapping
@Operation(summary = "新增")
public ActionResult<String> create(@RequestBody T entity) {
requireMenuPermission();
entity.setId(RandomUtil.uuId());
entity.setDeleteMark(null);
beforeSave(entity, true);
@@ -131,6 +155,7 @@ public abstract class SswflowCrudController<T extends SuperExtendEntity<String>>
@PutMapping("/{id}")
@Operation(summary = "修改", description = "只覆盖请求体里出现的字段,未传字段保持原值")
public ActionResult<String> update(@PathVariable("id") String id, @RequestBody T entity) {
requireMenuPermission();
T exists = getAlive(id);
if (exists == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -150,6 +175,7 @@ public abstract class SswflowCrudController<T extends SuperExtendEntity<String>>
@DeleteMapping("/{id}")
@Operation(summary = "删除", description = "逻辑删除,置 f_delete_mark=1")
public ActionResult<String> delete(@PathVariable("id") String id) {
requireMenuPermission();
T exists = getAlive(id);
if (exists == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -191,6 +217,7 @@ public abstract class SswflowCrudController<T extends SuperExtendEntity<String>>
}
});
}
applyDataScope(wrapper, request);
wrapper.orderByDesc(defaultOrderColumn());
return wrapper;
}
@@ -12,6 +12,9 @@ import jnpf.base.vo.PaginationVO;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import ssw.common.permission.SswDataScopeResolver;
import ssw.common.permission.SswPermissionGuard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -49,6 +52,23 @@ import java.util.Map;
*/
public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
@Autowired(required = false)
private SswPermissionGuard permissionGuard;
@Autowired(required = false)
private SswDataScopeResolver dataScopeResolver;
protected void requireMenuPermission() {
if (permissionGuard != null) permissionGuard.requireMenu(getClass());
}
/** 在 buildWrapper 末尾追加数据范围 SQL。 */
protected void applyDataScope(QueryWrapper<T> wrapper, HttpServletRequest request) {
if (dataScopeResolver != null) {
dataScopeResolver.applyTo(wrapper, getClass(), request);
}
}
/** 逻辑未删除条件,所有查询都要带 */
protected static final String ALIVE = "(f_delete_mark IS NULL OR f_delete_mark = 0)";
@@ -100,6 +120,7 @@ public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
@GetMapping
@Operation(summary = "分页列表", description = "支持 keyword 模糊搜索、tenantId 虚拟连接器过滤与子类声明的精确过滤参数")
public ActionResult<?> list(Pagination pagination, HttpServletRequest request) {
requireMenuPermission();
QueryWrapper<T> wrapper = buildWrapper(request);
long current = pagination.getCurrentPage() <= 0 ? 1 : pagination.getCurrentPage();
long size = pagination.getPageSize() <= 0 ? 20 : Math.min(pagination.getPageSize(), 500);
@@ -115,6 +136,7 @@ public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
@GetMapping("/All")
@Operation(summary = "不分页全量列表", description = "用于下拉选择等场景,最多返回 1000 条")
public ActionResult<List<T>> all(HttpServletRequest request) {
requireMenuPermission();
QueryWrapper<T> wrapper = buildWrapper(request);
wrapper.last("limit 1000");
return ActionResult.success(service().list(wrapper));
@@ -123,6 +145,7 @@ public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
@GetMapping("/{id}")
@Operation(summary = "详情")
public ActionResult<T> detail(@PathVariable("id") String id) {
requireMenuPermission();
T entity = getAlive(id);
if (entity == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -133,6 +156,7 @@ public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
@PostMapping
@Operation(summary = "新增")
public ActionResult<String> create(@RequestBody T entity) {
requireMenuPermission();
entity.setId(RandomUtil.uuId());
entity.setDeleteMark(null);
beforeSave(entity, true);
@@ -143,6 +167,7 @@ public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
@PutMapping("/{id}")
@Operation(summary = "修改", description = "只覆盖请求体里出现的字段,未传字段保持原值")
public ActionResult<String> update(@PathVariable("id") String id, @RequestBody T entity) {
requireMenuPermission();
T exists = getAlive(id);
if (exists == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -162,6 +187,7 @@ public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
@DeleteMapping("/{id}")
@Operation(summary = "删除", description = "逻辑删除,置 f_delete_mark=1")
public ActionResult<String> delete(@PathVariable("id") String id) {
requireMenuPermission();
T exists = getAlive(id);
if (exists == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -210,6 +236,7 @@ public abstract class TdcCrudController<T extends SuperExtendEntity<String>> {
}
});
}
applyDataScope(wrapper, request);
wrapper.orderByDesc(defaultOrderColumn());
return wrapper;
}
@@ -12,6 +12,9 @@ import jnpf.base.vo.PaginationVO;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import ssw.common.permission.SswDataScopeResolver;
import ssw.common.permission.SswPermissionGuard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -48,6 +51,26 @@ import java.util.Map;
*/
public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
@Autowired(required = false)
private SswPermissionGuard permissionGuard;
@Autowired(required = false)
private SswDataScopeResolver dataScopeResolver;
/** 统一授权界面对应的菜单权限校验。 */
protected void requireMenuPermission() {
if (permissionGuard != null) {
permissionGuard.requireMenu(getClass());
}
}
/** 在 buildWrapper 末尾追加数据范围 SQL,由子类覆盖;默认实现读授权库 resource 方案。 */
protected void applyDataScope(QueryWrapper<T> wrapper, HttpServletRequest request) {
if (dataScopeResolver != null) {
dataScopeResolver.applyTo(wrapper, getClass(), request);
}
}
/** 逻辑未删除条件,所有查询都要带 */
protected static final String ALIVE = "f_delete_mark is null";
@@ -99,6 +122,7 @@ public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
@GetMapping
@Operation(summary = "分页列表", description = "支持 keyword 模糊搜索、spaceId 空间过滤与子类声明的精确过滤参数")
public ActionResult<?> list(Pagination pagination, HttpServletRequest request) {
requireMenuPermission();
QueryWrapper<T> wrapper = buildWrapper(request);
long current = pagination.getCurrentPage() <= 0 ? 1 : pagination.getCurrentPage();
long size = pagination.getPageSize() <= 0 ? 20 : Math.min(pagination.getPageSize(), 500);
@@ -114,6 +138,7 @@ public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
@GetMapping("/All")
@Operation(summary = "不分页全量列表", description = "用于下拉选择等场景,最多返回 1000 条")
public ActionResult<List<T>> all(HttpServletRequest request) {
requireMenuPermission();
QueryWrapper<T> wrapper = buildWrapper(request);
wrapper.last("limit 1000");
return ActionResult.success(service().list(wrapper));
@@ -122,6 +147,7 @@ public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
@GetMapping("/{id}")
@Operation(summary = "详情")
public ActionResult<T> detail(@PathVariable("id") String id) {
requireMenuPermission();
T entity = getAlive(id);
if (entity == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -132,6 +158,7 @@ public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
@PostMapping
@Operation(summary = "新增")
public ActionResult<String> create(@RequestBody T entity) {
requireMenuPermission();
entity.setId(RandomUtil.uuId());
entity.setDeleteMark(null);
beforeSave(entity, true);
@@ -142,6 +169,7 @@ public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
@PutMapping("/{id}")
@Operation(summary = "修改", description = "只覆盖请求体里出现的字段,未传字段保持原值")
public ActionResult<String> update(@PathVariable("id") String id, @RequestBody T entity) {
requireMenuPermission();
T exists = getAlive(id);
if (exists == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -161,6 +189,7 @@ public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
@DeleteMapping("/{id}")
@Operation(summary = "删除", description = "逻辑删除,置 f_delete_mark=1")
public ActionResult<String> delete(@PathVariable("id") String id) {
requireMenuPermission();
T exists = getAlive(id);
if (exists == null) {
return ActionResult.fail("记录不存在或已删除");
@@ -209,6 +238,7 @@ public abstract class TdsCrudController<T extends SuperExtendEntity<String>> {
}
});
}
applyDataScope(wrapper, request);
wrapper.orderByDesc(defaultOrderColumn());
return wrapper;
}
+32 -8
View File
@@ -10,14 +10,28 @@ export interface AuthorizeInput {
moduleIds?: string[]
}
/** PUT /api/permission/Authority/Data/{objectId} 的 body 契约
*
* 字段名严格对齐 web 端 MenuAuth.vue 第 50-58 行 dataForm 初始值.
* 后端 AuthorizeDataUpForm.java 字段: objectId, objectType, button, column,
* module, resource, form, systemIds. 注意 module 不是 moduleId, systemIds
* 也是后端真字段 (web 端 auth.ts 不发, 但后端 save() 会用 form.getSystemIds(),
* null 时 Arrays.asList(null) → NPE; 安全起见保留空数组).
*/
export interface AuthorizePayload {
objectId: string
data: {
button: never[]
column: never[]
moduleId: string[]
resource: never[]
form: never[]
/** 小写: 'role' / 'organize' / 'position' / 'user'. 后端 byte code 严格 equals("role"). */
objectType: 'role' | 'organize' | 'position' | 'user'
/** 菜单 id 数组. web 端 MenuAuth.vue 会传 checkedKeys + halfCheckedKeys. */
module: string[]
button: string[]
column: string[]
form: string[]
resource: string[]
roleIds: string[]
/** 后端 save() 也读, 必须显式空数组, 否则 Arrays.asList(null) NPE. */
systemIds: string[]
}
}
@@ -52,7 +66,14 @@ export function validateAuthorizeInput(input: AuthorizeInput):
return { ok: true, ids, objectId: roleId }
}
/** 构造 web 后端契约 payload (PUT /api/permission/Authority/Data/{objectId}) */
/** 构造 web 后端契约 payload.
*
* 2026-08-07 修正 (看 jweb/.../views/permission/auth/components/MenuAuth.vue 真实契约):
* - objectType='role' (小写! 后端 byte code 严格 equals("role"))
* - module=[ids] (包含父节点; 我们场景传完整列表即等于 checkedKeys, 不需要补 halfCheckedKeys)
* - roleIds=[] (给角色绑菜单场景不需要额外 role)
* - systemIds=[] 兜底, 防止 save() 内 form.getSystemIds() 返 null → Arrays.asList(null) NPE
*/
export function buildAuthorizePayload(
objectId: string,
ids: string[],
@@ -60,11 +81,14 @@ export function buildAuthorizePayload(
return {
objectId,
data: {
objectType: 'role',
module: ids,
button: [],
column: [],
moduleId: ids,
resource: [],
form: [],
resource: [],
roleIds: [],
systemIds: [],
},
}
}
+5
View File
@@ -56,6 +56,11 @@ export function buildRoleListCommand(): Command {
currentPage: 1,
pageSize: 50,
})) as { code?: number; msg?: string; data?: { list?: RoleItem[] } }
// webapi 镜像层会解包 response.data, 直接拿到 {pagination, list}.
// 把这种结构反向包成 {code:200, msg:'Success', data: r} 保持下游逻辑统一.
if (r && (r as any).pagination && Array.isArray((r as any).list)) {
r = { code: 200, msg: 'Success', data: r } as any
}
} catch (webapiErr) {
// BS-新407 (tdd2 2026-07-25): webapi 失败 fallback 到原始 c.get
log.warn(`BS-新407: webapi 失败 (${(webapiErr as Error).message?.slice(0, 60)}), fallback 到 GET /permission/Role`)
+199
View File
@@ -0,0 +1,199 @@
# 沙盒交付流程 — Mermaid 时序图
---
## 1. 沙盒交付(两方/标准)
```mermaid
sequenceDiagram
autonumber
participant 数据使用方
participant 平台运营方
participant 数据提供方
participant 数据服务方
participant 监管方
Note over 数据使用方,监管方: 阶段1:需求与撮合
数据使用方->>平台运营方: 提交数据需求(门户·资源目录)
平台运营方->>平台运营方: 交易撮合(人工 + AI交易助手)
平台运营方->>数据提供方: 推送匹配订单(连接器)
数据提供方-->>平台运营方: 确认接单
数据服务方->>平台运营方: 挂出算法服务
Note over 数据使用方,监管方: 阶段2:合约签订
数据使用方->>平台运营方: 使用方订单签约(门户)
数据提供方->>平台运营方: 提供方订单签约(连接器)
平台运营方->>平台运营方: 生成合作协议 & 数字合约(服务平台)
平台运营方->>监管方: 上链/存证数字合约
Note over 数据使用方,监管方: 阶段3:算法开发与调试
数据服务方->>数据使用方: 交付算法代码
数据提供方->>数据使用方: 提供样例数据
数据使用方->>数据使用方: 在沙盒开发调试环境中调试
数据使用方->>平台运营方: 提交算法审核申请
平台运营方->>平台运营方: 算法审核(服务平台)
平台运营方-->>数据使用方: 审核通过
Note over 数据使用方,监管方: 阶段4:交付与执行
数据提供方->>数据使用方: 灌入数据资源到安全沙盒
数据使用方->>数据使用方: 安全沙盒交付执行(交付平台)
数据使用方->>平台运营方: 回传交付凭证
Note over 数据使用方,监管方: 阶段5:结算与审计
数据使用方->>数据提供方: 订单支付(线下支付)
平台运营方->>平台运营方: 生成结算凭证(服务平台)
平台运营方->>监管方: 提交交易凭证
监管方->>监管方: 审计核验
```
---
## 2. 沙盒交付(三方)
```mermaid
sequenceDiagram
autonumber
participant 数据使用方
participant 平台运营方
participant 数据提供方
participant 数据服务方
participant 监管方
Note over 数据使用方,监管方: 阶段1:发现与撮合
数据使用方->>平台运营方: 数据需求 / 资源目录下单(门户)
平台运营方->>平台运营方: 交易撮合(人工 + AI交易助手)
平台运营方->>平台运营方: 订单审核(服务平台)
数据提供方->>平台运营方: 提供数据资源
数据服务方->>平台运营方: 提供算法服务
Note over 数据使用方,监管方: 阶段2:合约签订
数据使用方->>平台运营方: 使用方订单签约(门户)
数据提供方->>平台运营方: 提供方订单签约(连接器)
数据服务方->>平台运营方: 服务方订单签约(门户)
平台运营方->>平台运营方: 生成合作协议 & 数字合约(服务平台)
平台运营方->>监管方: 上链/存证数字合约
Note over 数据使用方,监管方: 阶段3:算法开发与调试
数据提供方->>数据服务方: 提供样例数据
数据服务方->>数据服务方: 在开发调试环境编写算法代码(交付平台)
数据服务方->>平台运营方: 提交算法审核申请
平台运营方->>平台运营方: 算法审核(服务平台)
平台运营方-->>数据服务方: 审核通过
Note over 数据使用方,监管方: 阶段4:正式交付与执行
数据提供方->>数据使用方: 灌入数据资源到安全沙盒
数据使用方->>数据使用方: 安全沙盒交付执行(交付平台)
数据使用方->>平台运营方: 回传交付凭证
Note over 数据使用方,监管方: 阶段5:结算与审计
数据使用方->>数据提供方: 订单付款(线下支付)
平台运营方->>平台运营方: 生成结算凭证(服务平台)
平台运营方->>监管方: 提交交易凭证
监管方->>监管方: 审计核验
```
---
## 3. 前置流程:机构会员注册与资源发布
```mermaid
sequenceDiagram
autonumber
participant 数据使用方
participant 平台运营方
participant 数据提供方
participant 数据服务方
Note over 数据使用方,数据服务方: 机构会员注册
数据使用方->>平台运营方: 注册机构会员、发布数据需求
数据提供方->>平台运营方: 注册机构会员、申请入驻
数据服务方->>平台运营方: 注册机构会员、发布算法产品
Note over 数据提供方: 数据资源发布
数据提供方->>平台运营方: 提交数据资源、上架资源目录
Note over 数据使用方: 数据资源购买
数据使用方->>平台运营方: 浏览资源目录、下单购买
Note over 数据服务方: 算法产品发布
数据服务方->>平台运营方: 发布算法/服务产品
```
---
## 4. 隐私计算沙盒执行链路
```mermaid
sequenceDiagram
autonumber
participant 平台运营方
participant TEE硬件
participant 数据提供方
participant 数据使用方
participant 数据服务方
Note over 平台运营方: 交易达成,触发沙盒创建
平台运营方->>TEE硬件: 合约签署 → 创建安全沙盒
平台运营方->>数据提供方: 通知数据导入
数据提供方->>TEE硬件: 密态传输数据(硬件TEE加密通道)
Note over TEE硬件: 内存加工(明文/碎片,取决于计算模式)
TEE硬件->>TEE硬件: 计算执行(按算法代码加工)
TEE硬件->>数据使用方: 输出计算结果(仅结果出域)
Note over TEE硬件: 任务完成 → 用后即焚
TEE硬件->>TEE硬件: 数据销毁、环境清零
TEE硬件->>平台运营方: 沙盒释放、回传交付凭证
```
---
## 5. 三种隐私计算模式对比(并行调用)
```mermaid
sequenceDiagram
autonumber
participant 平台运营方
participant 集中式隐私求交
participant 联邦学习
participant 多方安全计算
Note over 平台运营方: 按场景选择计算模式
平台运营方->>集中式隐私求交: 部署1个沙盒(运营平台集中)
集中式隐私求交->>集中式隐私求交: 数据加密出域 → 明文融合计算
集中式隐私求交-->>平台运营方: 返回求交结果
平台运营方->>联邦学习: 各参与方本地部署沙盒(N个)
联邦学习->>联邦学习: 数据绝不出域 → 本地明文训练
联邦学习->>联邦学习: 沙盒间传输加密模型参数
联邦学习-->>平台运营方: 返回联合模型
平台运营方->>多方安全计算: 各参与方本地部署沙盒(N个)
多方安全计算->>多方安全计算: 数据绝不出域 → 秘密分享成碎片
多方安全计算->>多方安全计算: 沙盒间传输加密中间碎片
多方安全计算-->>平台运营方: 返回联合统计结果
```
---
> **说明**
> - 以上 5 张时序图完整覆盖原 PPT 全部流程页:标准沙盒交付、三方沙盒交付、机构注册与资源发布、隐私计算执行链路、三种计算模式并行对比。
> - 复制任意代码块到支持 Mermaid 的编辑器(Typora / VS Code + 插件 / GitHub Markdown / draw.io)即可渲染。
+1
View File
@@ -0,0 +1 @@
../../../jweb/apps/jnpf-web-apps-main/public/ssw/tds
+7 -2
View File
@@ -1,6 +1,11 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
import path from 'node:path'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
// jweb 真源 public 目录:web/public/ssw/tds 是软链指向这里,需让 vite 放开 fs 限制
const jwebPublic = path.resolve(__dirname, '../jweb/apps/jnpf-web-apps-main/public')
export default defineConfig({
resolve: {
@@ -12,9 +17,9 @@ export default defineConfig({
server: {
host: true,
port: 5173,
// src/views/ssw 是软链到 jweb 的目录(跨项目符号链接),放开 fs 限制让 vite 能读
// src/views/ssw + public/ssw 是软链到 jweb 的目录(跨项目符号链接),放开 fs 限制让 vite 能读
fs: {
allow: ['..']
allow: ['..', jwebPublic]
},
proxy: {
'/api': {