@kne/fastify-oidc 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -67,7 +67,7 @@ npm i --save @kne/fastify-oidc
67
67
  | 资源 | identifier | scope | 用途 |
68
68
  |------|------------|-------|------|
69
69
  | 本项目 API(名称为 `name`) | `${ORIGIN}/api` | `api` | SPA 调用本项目接口 |
70
- | 服务接口 | `${issuer origin}${prefix}` | `user:read tenant:read` | 子项目以 client_credentials 读取用户 / 租户 |
70
+ | 服务接口 | `${issuer origin}${prefix}` | `user:read tenant:read app:register tenant:sync` | 子项目以 client_credentials 读取用户 / 租户、注册应用、回拉租户快照 |
71
71
 
72
72
  client 只能申请 `allowedResources` 中的资源;子项目 token 的 `aud` 是子项目 API,拿到主项目会被拒绝。
73
73
 
@@ -106,6 +106,7 @@ JWT access_token 无法真正撤销,插件在资源侧维护一个撤销列表
106
106
  | JWT access_token | RS256 签名,`typ: at+jwt`,按资源服务区分 `aud` |
107
107
  | Refresh Token 轮转 | 每次刷新签发新 refresh token,旧的立即失效 |
108
108
  | 多租户 | 交互式 / 自动 / 静默切换租户,租户信息写入 token |
109
+ | 应用中心 | 子应用把权限树注册到宿主「应用中心」节点,宿主按租户开关子应用及其功能;client / independent 两种租户模式 |
109
110
  | SSO | 多个项目共用主项目 IdP 会话 |
110
111
  | RP-Initiated Logout / Back-Channel Logout | 登出时通知所有子项目 |
111
112
  | DPoP | 前端可选启用,token 与浏览器密钥绑定,资源侧校验 proof 与重放 |
@@ -204,6 +205,50 @@ fastify.register(require('@kne/fastify-oidc'), {
204
205
 
205
206
  > **建议**:子项目 client 配置 `backchannel_logout_session_required: true`,登出通知会携带 `sid`,子项目只撤销该会话的 token;否则按用户撤销。
206
207
 
208
+ ##### 子应用与应用中心
209
+
210
+ 宿主显式传入 fastify-tenant 开启应用中心:
211
+
212
+ ```js
213
+ // 宿主(standalone)
214
+ fastify.register(require('@kne/fastify-oidc'), {
215
+ tenant: () => fastify.tenant
216
+ });
217
+ ```
218
+
219
+ 子应用以 central 模式接入,并声明 `app`。宿主登记的服务 client 需要 `allowedResources` 包含服务接口资源;client 模式开启 `tenantProxy` 时还需 token exchange 与宿主 API 资源:
220
+
221
+ ```js
222
+ // client 模式:租户相关接口与数据全部由宿主提供
223
+ fastify.register(require('@kne/fastify-oidc'), {
224
+ mode: 'central',
225
+ tenantProxy: true, // 可选:/api/tenant/* 由宿主提供
226
+ app: {
227
+ code: 'crm',
228
+ name: 'CRM',
229
+ tenantMode: 'client',
230
+ permissions: { modules: [{ code: 'order', name: '订单', permissions: [{ code: 'view', name: '查看' }] }] }
231
+ }
232
+ });
233
+
234
+ // independent 模式:本地 fastify-tenant,宿主同步过来的租户由宿主接管
235
+ fastify.register(require('@kne/fastify-tenant'), { getUserAuthenticate: () => fastify.oidc.authenticate.user });
236
+ fastify.register(require('@kne/fastify-oidc'), {
237
+ mode: 'central',
238
+ tenant: () => fastify.tenant,
239
+ app: { code: 'erp', name: 'ERP', tenantMode: 'independent' } // 权限树默认取 fastify.tenant.permissions
240
+ });
241
+ ```
242
+
243
+ | 模式 | 租户来源 | 权限 | 说明 |
244
+ |------|----------|------|------|
245
+ | client | 宿主(`tenantSource = remote`) | 宿主下发,已去 `apps:<code>:` 前缀 | 只能选择已开通本应用的租户 |
246
+ | independent | 本地 fastify-tenant | 本地计算 | 宿主同步的租户(托管租户)只读;本地自建租户不受影响 |
247
+
248
+ > **注意**:托管租户名与本地租户重名时追加 `(宿主)` 后缀(仍冲突依次为 `(宿主2)`……);组织架构完全以宿主为准,子应用不能在托管租户下补充部门。independent 模式依赖 fastify-tenant 的托管租户能力(`services.managed`),需同时升级 fastify-tenant。
249
+
250
+ > **注意**:应用中心停用或删除某应用后,该应用的 client 登录不带任何租户与权限;independent 应用的托管租户会收到推送并关闭,宿主删除租户时同样关闭。删除的应用在子应用重启重新注册后恢复。宿主拒绝注册(如编码已被占用)时子应用停止重试,需修正配置后重启。
251
+
207
252
  ##### 前端
208
253
 
209
254
  前端使用 components-admin 的 `Oidc` 模块(授权码 + PKCE,可选 DPoP),管理后台使用 `OidcAdmin` 模块。默认路径:
@@ -267,8 +312,10 @@ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求
267
312
  | clientId | string | 否 | `OIDC_CLIENT_ID` 或 `${name}-spa` | 本项目 SPA 的 client_id |
268
313
  | claimNamespace | string | 否 | standalone 为 `${origin}/`,central 为 `${issuer origin}/` | 自定义 claim 前缀 |
269
314
  | accountNamespace | string | 否 | `account` | fastify-account 命名空间 |
270
- | tenantNamespace | string | 否 | `tenant` | fastify-tenant 命名空间,不存在时不启用租户 |
315
+ | tenantNamespace | string | 否 | `tenant` | fastify-tenant 命名空间,不存在时不启用租户;未传 `tenant` 时使用 |
316
+ | tenant | object / function | 否 | `null` | 显式传入 fastify-tenant(对象或 getter,如 `() => fastify.tenant`)。standalone 传入后开启应用中心;central 的 independent 子应用必填,指向本地 fastify-tenant;不传时回退 `fastify[tenantNamespace]`,不开启应用中心 |
271
317
  | intlNamespace | string | 否 | `intl` | @kne/fastify-intl 命名空间,不存在时返回内置中文文案 |
318
+ | fileNamespace | string | 否 | `fileManager` | @kne/fastify-file-manager 命名空间:主项目用它把头像 id 解析成 `avatarUrl`,子项目用它把头像拷到本地文件库;不存在时不处理头像 |
272
319
 
273
320
  ##### IdP(standalone)
274
321
 
@@ -291,9 +338,14 @@ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求
291
338
  | seedSelf | boolean | 否 | `true` | 启动时自动登记本项目 SPA client、本项目 API、服务接口资源 |
292
339
  | selfClient | object | 否 | `{}` | 覆盖默认 SPA client 的字段与 metadata,如 `{ clientName: '系统名称' }`(默认名称为 `name`);仅首次登记时生效;已存在的 client 只会追加缺失的 `redirect_uris` / `post_logout_redirect_uris` / `allowedResources`(如 `ORIGIN` 变更),其他字段不覆盖 |
293
340
  | clients | array | 否 | `[]` | 启动时登记的 client(已存在则只追加缺失的 `redirect_uris` / `post_logout_redirect_uris` / `allowedResources`),字段同管理接口 `client/create`,metadata 直接平铺 |
294
- | resourceServers | array | 否 | `[]` | 启动时登记的资源服务(已存在则跳过) |
295
- | serviceScopes | array | 否 | `['user:read', 'tenant:read']` | 服务接口资源的 scope |
296
- | getAuthenticate | function | 否 | 见下文 | 管理接口鉴权,参数为 `client:manage` / `resource-server:manage` / `key:manage` / `session:manage` |
341
+ | resourceServers | array | 否 | `[]` | 启动时登记的资源服务(已存在则只追加配置中新增的 scope,其他字段不覆盖) |
342
+ | serviceScopes | array | 否 | `['user:read', 'tenant:read', 'app:register', 'tenant:sync']` | 服务接口资源的 scope;已登记的服务接口资源启动时会补齐新增的 scope |
343
+ | appPermissionPrefix | string | 否 | `apps` | 应用中心根节点 code,子应用权限挂在 `apps:<appCode>:` 下 |
344
+ | appCenterName | string | 否 | `应用中心` | 应用中心根节点名称 |
345
+ | tenantSyncDebounce | number | 否 | `1000` | 同一租户变更通知的防抖时长(毫秒),合并导入 / 同步成员时的大量事件 |
346
+ | tenantSyncTimeout | number | 否 | `10000` | 推送通知的请求超时(毫秒) |
347
+ | tenantSyncTokenTTL | number | 否 | `300` | `tenant_sync_token` 有效期(秒) |
348
+ | getAuthenticate | function | 否 | 见下文 | 管理接口鉴权,参数为 `client:manage` / `resource-server:manage` / `key:manage` / `session:manage` / `app:manage` |
297
349
 
298
350
  `ttl` 默认值:
299
351
 
@@ -314,7 +366,7 @@ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求
314
366
  |--------|------|------|--------|------|
315
367
  | legacyToken | boolean | 否 | `true` | 无 `Authorization` 头时回退到 fastify-account 的 `x-user-token` |
316
368
  | requireDPoP | boolean | 否 | `false` | 只接受 DPoP 绑定的 token |
317
- | tenantSource | string | 否 | standalone 且有 fastify-tenant 为 `local`,否则 `claims` | `authenticate.tenantUser` 的数据来源:`local` 实时查本地 fastify-tenant;`claims` 由 token 构造;`remote` 调主项目服务接口 |
369
+ | tenantSource | string | 否 | standalone 且有 fastify-tenant 为 `local`;client 子应用为 `remote`;independent 子应用为 `local`(本地托管租户);否则 `claims` | `authenticate.tenantUser` 的数据来源:`local` 实时查本地 fastify-tenant;`claims` 由 token 构造;`remote` 调主项目服务接口 |
318
370
  | tenantUserContextName | string | 否 | `tenantUserInfo` | 租户用户挂载到 request 上的字段名 |
319
371
  | revocationStore | object | 否 | 内存 | 撤销列表存储,见「撤销列表存储」 |
320
372
  | dpopReplayStore | object | 否 | 内存 | DPoP proof 防重放存储,接口同 revocationStore |
@@ -325,6 +377,27 @@ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求
325
377
  | jwksUri | string | 否 | `${issuer}/jwks` | central 模式远程 JWKS 地址 |
326
378
  | userMirrorTTL | number | 否 | `600` | central 模式用户镜像缓存时长(秒) |
327
379
 
380
+ ##### 子应用(central)
381
+
382
+ | 属性名 | 类型 | 必填 | 默认值 | 说明 |
383
+ |--------|------|------|--------|------|
384
+ | app | object | 否 | `null` | 配置后作为宿主应用中心的子应用,启动时注册权限,见下表。环境变量 `OIDC_APP_CODE` / `OIDC_APP_NAME` / `OIDC_APP_TENANT_MODE` / `OIDC_APP_TENANT_SYNC_URI` 覆盖同名字段,托管平台可通过它们注入;代码里可只写默认值(如 `{ tenantMode: 'independent' }`),合并后没有 `code` 视为未作为子应用部署(本地独立运行不受影响) |
385
+ | appRegisterRetryMax | number | 否 | `300` | 注册失败退避重试的最大间隔(秒);宿主返回 4xx(408、429 除外,如编码已被占用、未授权 scope)时停止重试并记错误日志,修正配置后重启 |
386
+ | tenantProxy | boolean / object | 否 | `false` | client 模式开启 `/api/tenant` 代理;对象可配 `prefix`(默认 `/api/tenant`)、`resource`(默认 `${issuer origin}/api`,token exchange 的目标资源)、`target`(默认 `${issuer origin}${prefix}`) |
387
+ | tenantSyncTTL | number | 否 | `600` | independent 模式托管租户的过期时长(秒),过期后请求时后台回拉 |
388
+ | tenantSyncPageSize | number | 否 | `200` | independent 模式回拉成员的分页大小 |
389
+
390
+ `app` 字段:
391
+
392
+ | 属性名 | 类型 | 必填 | 默认值 | 说明 |
393
+ |--------|------|------|--------|------|
394
+ | code | string | 是 | - | 应用编码,只能包含字母、数字、`_`、`-`;首次注册后绑定当前 serviceClient |
395
+ | name | string | 否 | `code` | 应用名称,即权限树中应用节点名称 |
396
+ | description | string | 否 | - | 描述 |
397
+ | tenantMode | string | 否 | `client` | `client` / `independent` |
398
+ | permissions | object | client 必填 | independent 取 `tenant.permissions` | 权限树 `{ modules }`,code 不带 `apps` 前缀 |
399
+ | tenantSyncUri | string | 否 | independent 为 `${origin}${prefix}/tenant-sync` | 接收宿主变更通知的地址 |
400
+
328
401
  #### 接口
329
402
 
330
403
  ##### OIDC 协议端点(standalone)
@@ -433,6 +506,22 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
433
506
  | `GET /api/oidc/admin/session/list?userId=` | 用户 IdP 会话 `[{ uid, loginAt, expiresAt, clients: [{ clientId, sid }] }]` | `session:manage` |
434
507
  | `POST /api/oidc/admin/session/revoke` | `{ uid }` 结束会话并通知子项目 | `session:manage` |
435
508
  | `POST /api/oidc/admin/session/revoke-user` | `{ userId, logout = true }` 撤销用户全部令牌,`logout` 时同时强制下线;返回 `{ grants, sessions }` | `session:manage` |
509
+ | `GET /api/oidc/admin/app/list` | 子应用列表(`filter.keyword` / `filter.status` / `filter.tenantMode`),每项带 `permissionCount` | `app:manage` |
510
+ | `GET /api/oidc/admin/app/detail?id=` | 子应用详情,`permissions` 为子应用上报的权限树 | `app:manage` |
511
+ | `POST /api/oidc/admin/app/set-status` | `{ id, status }`,停用后从权限树移除,子应用视为所有租户未开通 | `app:manage` |
512
+ | `POST /api/oidc/admin/app/remove` | 删除(状态置为 `removed`)并移除权限来源;列表与详情不再返回;子应用下次启动重新注册即恢复为 `open` | `app:manage` |
513
+
514
+ 子应用只能通过服务接口注册,管理端不提供创建 / 修改。
515
+
516
+ - 应用停用或删除后,它的 client 登录时没有可用租户,签发的 token 不带租户 claims 与权限(不会回退为宿主未裁剪的权限);`tenant-list` / `tenant-user` 返回空或 404。
517
+ - 已删除的应用编码可以被其他 serviceClient 重新注册接管。
518
+ - independent 应用状态变化(停用 / 启用 / 删除 / 删除后重新注册)时,宿主向租户权限中仍有 `apps:<code>` 的租户逐个推送通知,子应用无需等到 `tenantSyncTTL` 即关闭或恢复托管租户。
519
+
520
+ ##### 租户端(standalone 且配置了 `tenant`)
521
+
522
+ | 接口 | 说明 | 鉴权 |
523
+ |------|------|------|
524
+ | `GET /api/oidc/tenant/apps` | 当前租户已开通(租户权限含 `apps:<code>`)且启用的子应用 `[{ code, name, description, tenantMode }]`,供宿主租户端应用中心展示;当前租户与 fastify-tenant 的 `tenantUser` 一致(token 中的租户,否则默认租户) | 登录用户 |
436
525
 
437
526
  ##### 服务接口(standalone,client_credentials)
438
527
 
@@ -440,13 +529,65 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
440
529
 
441
530
  | 接口 | scope | 说明 |
442
531
  |------|-------|------|
443
- | `GET /api/oidc/service/user?id=` | `user:read` | 用户资料 `{ id, nickname, avatar, email, phone, gender, birthday, description, status, isSuperAdmin }` |
444
- | `GET /api/oidc/service/tenant-user?userId=&tenantId=` | `tenant:read` | 用户在租户内的身份、角色、权限(fastify-tenant `getTenantUserInfo` 结果) |
532
+ | `GET /api/oidc/service/user?id=` | `user:read` | 用户资料 `{ id, nickname, avatar, avatarUrl, email, phone, gender, birthday, description, status, isSuperAdmin }`;`avatarUrl` 为头像的完整下载地址(经 `fileNamespace` 解析,无文件服务或解析失败时为 `null`) |
533
+ | `GET /api/oidc/service/tenant-user?userId=&tenantId=&app=` | `tenant:read` | 用户在租户内的身份、角色、权限(fastify-tenant `getTenantUserInfo` 结果);传 `app` 时租户未开通该应用返回 404,`permissions` 只含该应用的且去掉 `apps:<app>:` 前缀 |
534
+ | `GET /api/oidc/service/tenant-list?userId=&app=` | `tenant:read` | 用户可用租户 `{ list: [{ tenantId, tenantUserId, name, logo, companyName }], defaultTenantId }`;传 `app` 时只含已开通该应用的租户 |
535
+ | `POST /api/oidc/service/app/register` | `app:register` | 子应用注册,参数见下;`code` 已被其他 client 注册时返回 403;返回 `{ code, status, permissionsHash, changed }` |
536
+ | `GET /api/oidc/service/tenant-snapshot?tenantId=&app=` | `tenant:sync` | 租户快照,见下 |
537
+ | `GET /api/oidc/service/tenant-members?tenantId=&app=&currentPage=1&perPage=200` | `tenant:sync` | 成员分页 `{ pageData: [{ id, userId, name, email, phone, avatar, status, roleCodes, tenantOrgIds }], totalCount, fileUrls }`,只含已关联账号的成员;未开通时为空;`fileUrls` 为本页成员头像 `{ 宿主文件 id: 下载地址 }` |
538
+
539
+ 带 `app` 参数的接口只接受注册该应用的 serviceClient 调用,其他 client 返回 403。
540
+
541
+ `app/register` 参数:
542
+
543
+ | 参数 | 类型 | 必填 | 默认值 | 说明 |
544
+ |------|------|------|--------|------|
545
+ | code | string | 是 | - | 应用编码 |
546
+ | name / description | string | 否 | - | 名称 / 描述 |
547
+ | tenantMode | string | 否 | `client` | `client` / `independent` |
548
+ | clientId | string | 否 | - | 子应用 SPA 的 client_id,交互时据此只列出已开通的租户 |
549
+ | resource | string | 否 | - | 子应用资源服务 identifier,签发 token 时据此裁剪 permissions |
550
+ | permissions | object | 否 | `{ modules: [] }` | 权限树,code 不带前缀 |
551
+ | tenantSyncUri | string | 否 | - | independent 接收通知的地址 |
552
+
553
+ `tenant-snapshot` 返回(id 均为宿主侧 id,权限已去前缀):
554
+
555
+ ```json
556
+ {
557
+ "tenant": {
558
+ "id": "t1", "name": "租户 A", "status": "open", "logo": "f-logo", "companyName": "A 公司", "themeColor": "#1677ff", "defaultLanguage": "zh-CN",
559
+ "company": { "name": "A 公司", "fullName": "A 有限公司", "logo": "f-company", "banners": ["f-banner"], "teamDescription": [{ "name": "甲", "avatar": "f-avatar" }], "developmentHistory": [{ "time": "2020-01", "event": "成立", "images": ["f-history"] }] }
560
+ },
561
+ "enabled": true,
562
+ "permissions": ["stock", "stock:view"],
563
+ "roles": [{ "id": "r1", "code": "admin", "name": "管理员", "type": "system", "status": "open", "permissions": ["stock:view"] }],
564
+ "orgs": [{ "id": "o1", "parentId": null, "name": "总部", "index": 0, "status": "open", "leaderTenantUserId": "tu1" }],
565
+ "fileUrls": { "f-logo": "https://host.example.com/api/v1/static/file/xxx.png?filename=logo.png" }
566
+ }
567
+ ```
568
+
569
+ `enabled` 为 `false`(租户未开通或应用已停用)时 `permissions` / `roles` / `orgs` 为空数组。`logo` 与 `company` 中的图片(`logo`、`banners`、`teamDescription[].avatar`、`developmentHistory[].images`)是宿主文件 id,`fileUrls` 给出它们的下载地址(经 `fileNamespace` 解析,解析失败的不返回)。
570
+
571
+ 宿主租户已被删除时返回 `{ "tenant": { "id": "t1", "status": "closed" }, "enabled": false, "removed": true, "permissions": [], "roles": [], "orgs": [] }`,子应用沿用本地托管租户名将其关闭;本地没有对应托管租户则忽略。
445
572
 
446
573
  ##### Back-Channel Logout(central)
447
574
 
448
575
  `POST /api/oidc/backchannel-logout`,`application/x-www-form-urlencoded`,参数 `logout_token`。校验通过后撤销 `sid`(无 sid 时按 `sub`),返回 200。
449
576
 
577
+ ##### 租户变更通知(independent 子应用)
578
+
579
+ `POST /api/oidc/tenant-sync`,`application/json` 或 `application/x-www-form-urlencoded`,参数 `tenant_sync_token`。校验宿主签名、`aud` 为本应用 serviceClient 的 clientId、`jti` 未使用过后返回 `{}`,并在后台回拉该租户快照。签名错误、过期或重放返回 400。
580
+
581
+ ##### 租户代理(client 子应用,`tenantProxy`)
582
+
583
+ | 接口 | 说明 |
584
+ |------|------|
585
+ | `GET /api/tenant/getUserInfo` | `{ userInfo, tenantUserInfo, company, tenant }`,`tenantUserInfo` 来自宿主 `tenant-user`(权限已去前缀) |
586
+ | `GET /api/tenant/available-list` | 与 fastify-tenant 同形 `{ list: [{ id, tenantId, status, tenant }], defaultTenantId }`,只含已开通本应用的租户 |
587
+ | `* /api/tenant/*` | 以 token exchange 换取宿主 API 令牌后原样转发给宿主 fastify-tenant;只支持 JSON 请求体 |
588
+
589
+ client 模式切换租户需带 `tenant_id` 重新走授权(租户在 token 中),不能用 `switch-default-tenant`。
590
+
450
591
  #### 程序化 API
451
592
 
452
593
  ##### fastify.oidc.authenticate
@@ -481,6 +622,8 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
481
622
 
482
623
  central 模式下镜像用户的 `isSuperAdmin` 随主项目同步(升降级均以主项目为准,生效延迟 ≤ `userMirrorTTL`),`authenticate.admin` 仍读本地字段;需配置 `serviceClient`。
483
624
 
625
+ central 模式下主项目的 `avatar` 是主项目文件库的 id,子项目无法解析。子项目注册了 fastify-file-manager 时,镜像会按 `avatarUrl` 把头像拷到本地文件库,`avatar` 存本地文件 id(文件记录 `options.oidcAvatarSource` 记来源 id,主项目头像不变不重复下载,变更时原地替换);主项目未返回 `avatarUrl` 或下载失败时保留已同步的头像,没有则置空。子项目未注册文件服务时 `avatar` 仍为主项目原值。主项目需同时升级才会返回 `avatarUrl`。
626
+
484
627
  ##### 其它
485
628
 
486
629
  | 方法 | 说明 |
@@ -492,7 +635,14 @@ central 模式下镜像用户的 `isSuperAdmin` 随主项目同步(升降级
492
635
  | `fastify.oidc.services.key.rotate()` | 轮换签名密钥并热加载 |
493
636
  | `fastify.oidc.services.client.*` / `resourceServer.*` | 同管理接口 |
494
637
  | `fastify.oidc.serviceClient.getServiceToken({ resource, scope })` | client_credentials 取 token(带缓存) |
495
- | `fastify.oidc.serviceClient.getUserProfile(userId)` / `getTenantUser({ userId, tenantId })` | 调主项目服务接口 |
638
+ | `fastify.oidc.serviceClient.getUserProfile(userId)` / `getTenantUser({ userId, tenantId })` | 调主项目服务接口;配置了 `app` 时 `getTenantUser` 自动带 `app` 参数 |
639
+ | `fastify.oidc.serviceClient.getTenantList({ userId })` / `registerApp(body)` / `getTenantSnapshot({ tenantId })` / `getTenantMembers({ tenantId, currentPage, perPage })` | 子应用调宿主服务接口,自动带 `app` |
640
+ | `fastify.oidc.serviceClient.callService(path, { query, method, body, scope })` | 调宿主任意服务接口,每次只申请传入的 `scope`;失败时 error 带 `upstreamStatus` |
641
+ | `fastify.oidc.tenant.getTenantUserInfo({ userId, tenantId })` / `tenantList({ userId })` | client 子应用的租户门面,数据来自宿主,其余模式为 `null` |
642
+ | `fastify.oidc.appRegistry.register()` / `whenStarted()` / `getState()` | 子应用手动注册 / 等待启动时的首次注册 / 注册状态 |
643
+ | `fastify.oidc.tenantSync.sync(hostTenantId)` / `ensureFresh(hostTenantId)` / `whenIdle(hostTenantId)` | independent 子应用:立即回拉 / 按 `tenantSyncTTL` 回拉并返回本地托管租户 id / 等待进行中的同步 |
644
+ | `fastify.oidc.services.app.list()` / `detail()` / `setStatus()` / `remove()` / `register()` | 同管理接口 / 服务接口(standalone) |
645
+ | `fastify.oidc.services.tenantPush.push(tenantId)` | 立即通知 independent 子应用回拉该租户(standalone) |
496
646
  | `fastify.oidc.serviceClient.exchangeToken({ subjectToken, resource, scope })` | Token Exchange |
497
647
  | `fastify.oidc.revocation.revokeSession(sid)` / `revokeSubject(sub)` / `isRevoked(payload)` | 撤销列表 |
498
648
  | `fastify.oidc.idp.getProvider()` | oidc-provider 实例(standalone) |
@@ -560,6 +710,24 @@ central 模式下镜像用户的 `isSuperAdmin` 随主项目同步(升降级
560
710
  | accountId | string | 用户 id |
561
711
  | tenantId | string | 会话当前租户 |
562
712
 
713
+ ##### app(`t_oidc_app`)
714
+
715
+ | 属性名 | 类型 | 说明 |
716
+ |--------|------|------|
717
+ | code | string | 应用编码(唯一),宿主权限 code 前缀 `apps:<code>` |
718
+ | name / description | string | 名称 / 描述 |
719
+ | tenantMode | string | `client` / `independent` |
720
+ | serviceClientId | string | 首次注册的服务 client_id,之后只有它能更新该应用、读取应用相关数据 |
721
+ | clientIds | JSON | 子应用 SPA 的 client_id 列表 |
722
+ | resource | string | 子应用资源服务 identifier |
723
+ | permissions | JSON | 子应用上报的权限树(不含前缀) |
724
+ | permissionsHash | string | 权限树摘要,未变化时不重建宿主权限树 |
725
+ | tenantSyncUri | string | independent 接收通知的地址 |
726
+ | registeredAt | Date | 最近一次注册时间 |
727
+ | status | string | `open` / `closed` |
728
+
729
+ 新表由 `sequelize.sync()` 创建,无需迁移脚本。
730
+
563
731
  #### 机制说明
564
732
 
565
733
  ##### 自定义 adapter(如 Redis)
@@ -686,6 +854,47 @@ fastify.register(require('@kne/fastify-oidc'), { revocationStore: store, dpopRep
686
854
 
687
855
  新 token 保留原用户与租户,`act.sub` 为调用方 client_id。
688
856
 
857
+ ##### 子应用与租户
858
+
859
+ 宿主(standalone 且传入 `tenant`)按 `tenantRole` 区分运行角色:
860
+
861
+ | tenantRole | 条件 | 说明 |
862
+ |------------|------|------|
863
+ | host | standalone + `tenant` | 开启应用中心,接收子应用注册,按租户开关子应用 |
864
+ | client | central + `app.tenantMode = client` | 租户相关数据全部来自宿主 |
865
+ | independent | central + `app.tenantMode = independent` + `tenant` | 本地 fastify-tenant;宿主同步过来的租户由宿主接管,本地自建租户不受影响 |
866
+ | none | 其它 | 与之前行为一致 |
867
+
868
+ ```
869
+ 子应用启动(onReady)
870
+ ↓ POST /service/app/register(失败退避重试)
871
+ 宿主 oidc_app ─→ tenant.setPermissionSource('oidc-app:<code>', apps → <code> → 权限树, { defaultDisabled: true })
872
+ ↓ 管理员在租户权限中勾选 apps:<code>(即开通)
873
+ 交互 / 签发 token:子应用 client 只列出已开通的租户;token permissions 只含 apps:<code>: 下的权限并去前缀
874
+ ↓ independent:tenant.onChange(防抖)→ POST tenantSyncUri(tenant_sync_token)
875
+ 子应用 /api/oidc/tenant-sync → 回拉 tenant-snapshot + tenant-members(分页)→ userMirror.ensure → managed.applySnapshot
876
+ ```
877
+
878
+ > **关键设计**:子应用的权限 code 在宿主侧统一加 `apps:<code>:` 前缀,模块 code `apps:<code>` 本身就是租户开关;下发给子应用时去掉前缀,子应用代码仍写自己的 code。新租户默认不开通任何子应用。
879
+
880
+ independent 模式的同步范围(以宿主为准,全部只读):
881
+
882
+ | 内容 | 规则 |
883
+ |------|------|
884
+ | 租户基本信息与状态 | 名称、主题色、语言、服务期等;宿主关闭或删除租户、取消开通、停用或删除应用时本地托管租户置为 `closed` |
885
+ | 租户权限 | 宿主租户在该应用下的权限(去前缀) |
886
+ | 角色与角色权限 | 按 code 对应;宿主删除的非系统角色置为 `closed` |
887
+ | 组织架构 | 按层级先父后子写入,`parentId`、负责人映射为本地 id;宿主删除的组织置为 `closed` |
888
+ | 公司信息 | 全称、logo、行业、banner、团队介绍、发展历程等整体覆盖 |
889
+ | 成员 | `userId` 为宿主用户 id(即镜像用户),多组织、角色按映射整体替换;头像优先用宿主租户内的头像,没有时用镜像用户的头像;宿主删除的成员置为 `closed` |
890
+
891
+ - **图片**:租户 logo、公司信息中的图片、成员头像按宿主给出的地址下载,经 `uploadFromUrl` 存入子应用自己的文件库,写入本地文件 id;`宿主文件 id → 本地文件 id` 记在 `tenant.options.managedBy.files`,宿主文件不变且本地文件仍在时不再下载;下载失败的图片置空,下次同步重试。子应用没有文件库时保留宿主文件 id。
892
+ - 托管租户的标记、写拦截和快照写入由 fastify-tenant 提供(`tenant.options.managedBy`、`services.managed.applySnapshot`),子应用不能修改托管租户下的任何数据,也不能在其下补充本地部门或接入第三方组织同步。
893
+ - **重名规则**:宿主租户名与子应用本地已有租户重名时,托管租户名追加 `(宿主)` 后缀,仍冲突依次为 `(宿主2)`、`(宿主3)`……;宿主改名后按同样规则重新计算。
894
+ - 推送是尽力而为,失败只记日志;服务关闭时会等进行中的推送与同步结束;子应用请求带宿主租户时,本地没有对应托管租户会先同步拉取,已超过 `tenantSyncTTL` 则后台刷新。同一租户的同步串行执行,进行中再收到通知只重跑一次。
895
+ - independent 模式下 `request.user.hostTenantId` 为 token 中的宿主租户,`request.user.tenantId` 与 `request.authenticatePayload.tenantId` 由本地默认租户决定(首次同步时为成员设置默认租户),本地没有默认租户时用宿主租户对应的托管租户。
896
+ - 交互时子应用 client 只考虑已开通该应用的租户;IdP 会话的当前租户在宿主与子应用之间共享,若会话当前租户未开通该应用且只有一个可用租户,会切换会话租户。
897
+
689
898
  ##### 国际化
690
899
 
691
900
  返回给前端的错误信息、OAuth `error_description`、登出页文案均通过 [@kne/fastify-intl](https://www.npmjs.com/package/@kne/fastify-intl) 按请求语言翻译:
package/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const path = require('node:path');
3
+ const { pickBy } = require('lodash');
3
4
  const resolveOptions = require('./libs/utils/resolve-options');
4
5
  const createIdp = require('./libs/idp');
5
6
  const mount = require('./libs/idp/mount');
@@ -9,6 +10,9 @@ const createVerifier = require('./libs/resource/verify-token');
9
10
  const createServiceClient = require('./libs/resource/service-client');
10
11
  const createUserMirror = require('./libs/resource/user-mirror');
11
12
  const createAuthenticate = require('./libs/resource/authenticate');
13
+ const createTenantSync = require('./libs/resource/tenant-sync');
14
+ const createAppRegistry = require('./libs/resource/app-registry');
15
+ const createRemoteTenant = require('./libs/resource/remote-tenant');
12
16
  const { locale, createTranslator } = require('./libs/utils/intl');
13
17
 
14
18
  const DAY = 24 * 60 * 60;
@@ -50,12 +54,24 @@ module.exports = fp(
50
54
  accountNamespace: 'account',
51
55
  tenantNamespace: 'tenant',
52
56
  intlNamespace: 'intl',
57
+ fileNamespace: 'fileManager',
53
58
  clients: [],
54
59
  resourceServers: [],
55
60
  seedSelf: true,
56
61
  selfClient: {},
57
- serviceScopes: ['user:read', 'tenant:read'],
62
+ serviceScopes: ['user:read', 'tenant:read', 'app:register', 'tenant:sync'],
58
63
  userMirrorTTL: 10 * 60,
64
+ tenant: null,
65
+ app: null,
66
+ appPermissionPrefix: 'apps',
67
+ appCenterName: '应用中心',
68
+ appRegisterRetryMax: 5 * 60,
69
+ tenantProxy: false,
70
+ tenantSyncTTL: 10 * 60,
71
+ tenantSyncPageSize: 200,
72
+ tenantSyncDebounce: 1000,
73
+ tenantSyncTimeout: 10 * 1000,
74
+ tenantSyncTokenTTL: 5 * 60,
59
75
  revocationStore: null,
60
76
  dpopReplayStore: null,
61
77
  getAuthenticate: type => {
@@ -70,8 +86,15 @@ module.exports = fp(
70
86
  );
71
87
  options.ttl = Object.assign({ accessToken: 10 * 60, idToken: 60 * 60, refreshToken: 14 * DAY, interaction: 10 * 60, session: 14 * DAY, grant: 14 * DAY }, options.ttl);
72
88
  options.serviceClient = Object.assign({ clientId: env.OIDC_SERVICE_CLIENT_ID, clientSecret: env.OIDC_SERVICE_CLIENT_SECRET }, options.serviceClient);
89
+ // 代码里的 app 作默认值(如 tenantMode),部署时宿主注入的环境变量优先;最终没有 code 视为未作为子应用部署
90
+ const envApp = pickBy({ code: env.OIDC_APP_CODE, name: env.OIDC_APP_NAME, tenantMode: env.OIDC_APP_TENANT_MODE, tenantSyncUri: env.OIDC_APP_TENANT_SYNC_URI });
91
+ const app = Object.assign({}, options.app, envApp);
92
+ options.app = app.code ? app : null;
73
93
  options.runtime = resolveOptions(options);
74
94
  const { runtime } = options;
95
+ // 显式传入 tenant(对象或 getter)开启应用中心 / 子应用租户;不传时回退 fastify[tenantNamespace],保持兼容
96
+ const tenantOption = options.tenant;
97
+ options.getTenant = typeof tenantOption === 'function' ? tenantOption : () => tenantOption || fastify[options.tenantNamespace];
75
98
 
76
99
  if (runtime.idpEnabled && !options.keyEncryptionSecret) {
77
100
  fastify.log.warn('fastify-oidc: 未配置 keyEncryptionSecret(环境变量 OIDC_KEY_SECRET),正在使用不安全的默认值,生产环境必须配置');
@@ -89,7 +112,20 @@ module.exports = fp(
89
112
  const serviceClient = createServiceClient({ options });
90
113
  const userMirror = createUserMirror({ fastify, options, serviceClient });
91
114
  const dpop = createDPoP({ clockTolerance: options.clockTolerance, replayStore: options.dpopReplayStore });
92
- const authenticate = createAuthenticate({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, translator });
115
+ const tenantSync = runtime.tenantRole === 'independent' ? createTenantSync({ fastify, options, serviceClient, userMirror }) : null;
116
+ const appRegistry = runtime.app ? createAppRegistry({ fastify, options, serviceClient }) : null;
117
+ const remoteTenant = runtime.tenantRole === 'client' ? createRemoteTenant({ serviceClient }) : null;
118
+ const authenticate = createAuthenticate({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, tenantSync, translator });
119
+
120
+ if (appRegistry) {
121
+ fastify.addHook('onReady', async () => {
122
+ appRegistry.start();
123
+ });
124
+ fastify.addHook('onClose', async () => appRegistry.stop());
125
+ }
126
+ if (tenantSync) {
127
+ fastify.addHook('onClose', async () => tenantSync.close());
128
+ }
93
129
 
94
130
  const modules = [];
95
131
  if (runtime.idpEnabled) {
@@ -122,6 +158,9 @@ module.exports = fp(
122
158
  ['verifier', verifier],
123
159
  ['serviceClient', serviceClient],
124
160
  ['userMirror', userMirror],
161
+ ['tenantSync', tenantSync],
162
+ ['appRegistry', appRegistry],
163
+ ['tenant', remoteTenant],
125
164
  ['authenticate', authenticate],
126
165
  ['whenReady', () => readyPromise],
127
166
  [
@@ -96,6 +96,36 @@ module.exports = fp(async (fastify, options) => {
96
96
  crud('client', 'OIDC Client', () => services.client, clientBody);
97
97
  crud('resource-server', 'OIDC 资源服务', () => services.resourceServer, resourceServerBody);
98
98
 
99
+ // 应用由子应用通过服务接口注册,管理端只能查看、启停与删除
100
+ const appTags = ['OIDC 应用中心'];
101
+ const appOnRequest = options.getAuthenticate('app:manage');
102
+ fastify.get(
103
+ `${admin}/app/list`,
104
+ { onRequest: appOnRequest, schema: { tags: appTags, summary: '子应用列表', query: listQuery } },
105
+ wrap(async request => services.app.list(request.query))
106
+ );
107
+ fastify.get(
108
+ `${admin}/app/detail`,
109
+ { onRequest: appOnRequest, schema: { tags: appTags, summary: '子应用详情(含权限树)', query: idSchema } },
110
+ wrap(async request => services.app.detail(request.query))
111
+ );
112
+ fastify.post(
113
+ `${admin}/app/set-status`,
114
+ { onRequest: appOnRequest, schema: { tags: appTags, summary: '启用 / 停用子应用(停用后从权限树移除)', body: statusBody } },
115
+ wrap(async request => {
116
+ await services.app.setStatus(request.body);
117
+ return {};
118
+ })
119
+ );
120
+ fastify.post(
121
+ `${admin}/app/remove`,
122
+ { onRequest: appOnRequest, schema: { tags: appTags, summary: '删除子应用(子应用下次启动会重新注册)', body: idSchema } },
123
+ wrap(async request => {
124
+ await services.app.remove(request.body);
125
+ return {};
126
+ })
127
+ );
128
+
99
129
  fastify.post(
100
130
  `${admin}/client/rotate-secret`,
101
131
  { onRequest: options.getAuthenticate('client:manage'), schema: { tags: ['OIDC Client'], summary: '重置 client secret(明文只返回一次)', body: idSchema } },