@kne/fastify-oidc 0.1.16 → 0.1.17

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
@@ -608,10 +608,12 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
608
608
 
609
609
  `POST /api/oidc/backchannel-logout`,`application/x-www-form-urlencoded`,参数 `logout_token`。校验通过后撤销 `sid`(无 sid 时按 `sub`),返回 200。
610
610
 
611
- ##### 租户变更通知(independent 子应用)
611
+ ##### 租户变更通知(independent 子应用 / 已配对主平台的 standalone 应用)
612
612
 
613
613
  `POST /api/oidc/tenant-sync`,`application/json` 或 `application/x-www-form-urlencoded`,参数 `tenant_sync_token`。校验宿主签名、`aud` 为本应用 serviceClient 的 clientId、`jti` 未使用过后返回 `{}`,并在后台回拉该租户快照。签名错误、过期或重放返回 400。
614
614
 
615
+ standalone 应用按令牌 `iss` 找到已配对的平台,`aud` 须为该平台登记的 `serviceClientId`;`iss` 不是已配对平台时返回 400。
616
+
615
617
  ##### 租户代理(client 子应用,`tenantProxy`)
616
618
 
617
619
  | 接口 | 说明 |
@@ -676,6 +678,9 @@ central 模式下主项目的 `avatar` 是主项目文件库的 id,子项目
676
678
  | `fastify.oidc.appRegistry.register()` / `whenStarted()` / `getState()` | 子应用手动注册 / 等待启动时的首次注册 / 注册状态 |
677
679
  | `fastify.oidc.tenantSync.sync(hostTenantId)` / `ensureFresh(hostTenantId)` / `whenIdle(hostTenantId)` | independent 子应用:立即回拉 / 按 `tenantSyncTTL` 回拉并返回本地托管租户 id / 等待进行中的同步 |
678
680
  | `fastify.oidc.services.app.list()` / `detail()` / `setStatus()` / `remove()` / `register()` | 同管理接口 / 服务接口(standalone) |
681
+ | `fastify.oidc.services.app.register({ ..., permissionRoot: true })` | 登记权限树由宿主其他来源维护在顶层 `<code>` 下的应用(如应用中心关联的外部应用):不再挂 `apps:<code>` 权限树,开通判断与权限去前缀都按 `<code>` |
682
+ | `fastify.oidc.platforms.upsert(platform)` / `remove(platformOrigin)` / `getAll()` / `publicList()` | 已配对主平台登记;`serviceClientSecret` / `appCode` / `apiBase` / `serviceAudience` / `claimNamespace` 只在内部使用,不出现在 `publicList()` 与 `/config` 中 |
683
+ | `fastify.oidc.platformContexts.forIssuer(iss)` | standalone:取已配对平台的上下文(`serviceClient` / `userMirror` / `tenantSync`),未配对返回 `null` |
679
684
  | `fastify.oidc.services.tenantPush.push(tenantId)` | 立即通知 independent 子应用回拉该租户(standalone) |
680
685
  | `fastify.oidc.serviceClient.exchangeToken({ subjectToken, resource, scope })` | Token Exchange |
681
686
  | `fastify.oidc.revocation.revokeSession(sid)` / `revokeSubject(sub)` / `isRevoked(payload)` | 撤销列表 |
@@ -771,13 +776,13 @@ central 模式下主项目的 `avatar` 是主项目文件库的 id,子项目
771
776
 
772
777
  | 属性名 | 类型 | 说明 |
773
778
  |--------|------|------|
774
- | code | string | 应用编码(唯一),宿主权限 code 前缀 `apps:<code>` |
779
+ | code | string | 应用编码(唯一),宿主权限 code 前缀 `apps:<code>`;`permissions.root` 为 true 时为顶层 `<code>` |
775
780
  | name / description | string | 名称 / 描述 |
776
781
  | tenantMode | string | `client` / `independent` |
777
782
  | serviceClientId | string | 首次注册的服务 client_id,之后只有它能更新该应用、读取应用相关数据 |
778
783
  | clientIds | JSON | 子应用 SPA 的 client_id 列表 |
779
784
  | resource | string | 子应用资源服务 identifier |
780
- | permissions | JSON | 子应用上报的权限树(不含前缀) |
785
+ | permissions | JSON | 子应用上报的权限树(不含前缀);`permissionRoot` 登记时为 `{ root: true }` |
781
786
  | permissionsHash | string | 权限树摘要,未变化时不重建宿主权限树 |
782
787
  | tenantSyncUri | string | independent 接收通知的地址 |
783
788
  | registeredAt | Date | 最近一次注册时间 |
@@ -888,6 +893,15 @@ const store = {
888
893
  fastify.register(require('@kne/fastify-oidc'), { revocationStore: store, dpopReplayStore: store });
889
894
  ```
890
895
 
896
+ ###### 按用户撤销的时间精度
897
+
898
+ JWT 的标准 `iat` 只有秒精度,同一秒内「先撤销、后签发」与「先签发、后撤销」的令牌无法区分,按秒比较会把刚签发的有效令牌误拒。本 IdP 签发的令牌(含登录、刷新与 `issueUserAccessToken`)带毫秒级签发时间 claim `{namespace}issued_at_ms`(如 `https://idp.example.com/issued_at_ms`),`revokeSubject` 同时写入 `sub:{id}`(秒)与 `sub-ms:{id}`(毫秒)两个键:
899
+
900
+ - 令牌带毫秒 claim 且存在 `sub-ms` 记录:按毫秒比较,签发时间 **不晚于** 撤销时间的令牌失效,之后签发的有效。
901
+ - 令牌没有该 claim(旧版 IdP、外部签发),或撤销记录只有秒(旧版进程写入):退回按秒比较,同一秒内保守地视为已撤销。
902
+
903
+ 自定义 `revocationStore` 无需改动;`sub-ms:*` 值是毫秒时间戳,Redis 返回字符串也可以。
904
+
891
905
  ##### 签名密钥轮换
892
906
 
893
907
  | 状态 | 用途 |
@@ -952,6 +966,22 @@ independent 模式的同步范围(以宿主为准,全部只读):
952
966
  - independent 模式下 `request.user.hostTenantId` 为 token 中的宿主租户,`request.user.tenantId` 与 `request.authenticatePayload.tenantId` 由本地默认租户决定(首次同步时为成员设置默认租户),本地没有默认租户时用宿主租户对应的托管租户。
953
967
  - 交互时子应用 client 只考虑已开通该应用的租户;IdP 会话的当前租户在宿主与子应用之间共享,若会话当前租户未开通该应用且只有一个可用租户,会切换会话租户。
954
968
 
969
+ ##### standalone 应用配对主平台
970
+
971
+ standalone 应用自己是 IdP,用户和租户都在本地维护。它与主平台配对后(`platforms.upsert`,一般由 `@kne/fastify-app-runtime` 的配对流程写入),会同时服务主平台的用户与租户,相当于对每个已配对平台各跑一套 central + independent:
972
+
973
+ | 来源 | 用户 | 租户 |
974
+ |------|------|------|
975
+ | 本地 IdP 签发的令牌 | 本地用户 | 本地自建租户,本地维护 |
976
+ | 已配对平台签发的令牌(按 `iss` 识别) | 用平台的服务 client 拉取资料,镜像到本地用户表,id 为平台用户 id | 平台租户同步为本地只读托管租户(`managedBy.issuer` 为平台 issuer),由平台用户修改 |
977
+
978
+ - 平台登记需带 `serviceClientId` + `serviceClientSecret`;`appCode` 不传时从 `audience`(`{平台}/app/{code}/api`)推导;`apiBase` / `serviceAudience` 默认 `{平台 origin}${prefix}`;`claimNamespace` 默认 `{平台 origin}/`。
979
+ - 平台令牌的 `request.user.hostTenantId` 为平台租户,`request.user.tenantId` 与 `request.authenticatePayload.tenantId` 为对应的本地托管租户 id(平台租户未开通该应用时为 `null`),fastify-tenant 的 `tenantUser` 按本地租户读取成员与权限。
980
+ - 镜像平台用户时不同步平台的超级管理员身份,本地超级管理员仍由本地维护。
981
+ - 同一个人在本地和平台各有账号时是两个用户,不做合并。
982
+ - 平台登记该应用时用 `register({ tenantMode: 'independent', tenantSyncUri: '{应用}/api/oidc/tenant-sync', ... })`,平台租户变更后会推送通知,应用按平台验签后回拉。
983
+ - 平台用户直接打开应用登录:前端请求 `/api/oidc/config?iss={平台 issuer}`(或 `?platform={平台 origin}`)拿到平台的 issuer / client_id / audience 后发起授权;不带参数时仍用本地 IdP。
984
+
955
985
  ##### 国际化
956
986
 
957
987
  返回给前端的错误信息、OAuth `error_description`、登出页文案均通过 [@kne/fastify-intl](https://www.npmjs.com/package/@kne/fastify-intl) 按请求语言翻译:
package/index.js CHANGED
@@ -14,6 +14,7 @@ const createTenantSync = require('./libs/resource/tenant-sync');
14
14
  const createAppRegistry = require('./libs/resource/app-registry');
15
15
  const createRemoteTenant = require('./libs/resource/remote-tenant');
16
16
  const { createPlatformsRegistry } = require('./libs/utils/platforms');
17
+ const createPlatformContexts = require('./libs/resource/platform-context');
17
18
  const { createPlatformAssertionSigner, createPlatformAssertionVerifier, createMemoryJtiStore } = require('./libs/utils/platform-assertion');
18
19
  const { locale, createTranslator } = require('./libs/utils/intl');
19
20
 
@@ -112,7 +113,11 @@ module.exports = fp(
112
113
 
113
114
  const translator = createTranslator({ fastify, options });
114
115
  const idp = runtime.idpEnabled ? createIdp({ fastify, options, translator }) : null;
115
- const revocation = createRevocation({ store: options.revocationStore, ttl: Math.max(options.ttl.accessToken, options.ttl.idToken) + options.clockTolerance });
116
+ const revocation = createRevocation({
117
+ store: options.revocationStore,
118
+ ttl: Math.max(options.ttl.accessToken, options.ttl.idToken) + options.clockTolerance,
119
+ issuedAtMsClaim: runtime.claims.issuedAtMs
120
+ });
116
121
  const platforms = createPlatformsRegistry({ initial: options.platforms || [] });
117
122
  const verifier = createVerifier({
118
123
  options,
@@ -136,7 +141,9 @@ module.exports = fp(
136
141
  const tenantSync = runtime.tenantRole === 'independent' ? createTenantSync({ fastify, options, serviceClient, userMirror }) : null;
137
142
  const appRegistry = runtime.app ? createAppRegistry({ fastify, options, serviceClient }) : null;
138
143
  const remoteTenant = runtime.tenantRole === 'client' ? createRemoteTenant({ serviceClient }) : null;
139
- const authenticate = createAuthenticate({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, tenantSync, translator });
144
+ // standalone 与主平台配对后,按令牌 iss 用对应平台的服务凭据镜像用户、同步租户
145
+ const platformContexts = runtime.idpEnabled ? createPlatformContexts({ fastify, options, platforms }) : null;
146
+ const authenticate = createAuthenticate({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, tenantSync, platformContexts, translator });
140
147
 
141
148
  if (appRegistry) {
142
149
  fastify.addHook('onReady', async () => {
@@ -147,6 +154,9 @@ module.exports = fp(
147
154
  if (tenantSync) {
148
155
  fastify.addHook('onClose', async () => tenantSync.close());
149
156
  }
157
+ if (platformContexts) {
158
+ fastify.addHook('onClose', async () => platformContexts.close());
159
+ }
150
160
 
151
161
  const modules = [];
152
162
  if (runtime.idpEnabled) {
@@ -181,6 +191,7 @@ module.exports = fp(
181
191
  ['serviceClient', serviceClient],
182
192
  ['userMirror', userMirror],
183
193
  ['tenantSync', tenantSync],
194
+ ['platformContexts', platformContexts],
184
195
  ['appRegistry', appRegistry],
185
196
  ['tenant', remoteTenant],
186
197
  ['authenticate', authenticate],
@@ -1,18 +1,35 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const httpErrors = require('http-errors');
3
+ const { decodeJwt } = require('jose');
3
4
  const { createError } = require('../utils/intl');
4
5
  const { empty } = require('../schema/response');
5
6
 
6
7
  const { BadRequest } = httpErrors;
7
8
 
8
9
  /**
9
- * independent 子应用接收宿主的租户变更通知:验签 + jti 防重放后后台回拉快照,立即返回
10
+ * independent 子应用接收宿主的租户变更通知:验签 + jti 防重放后后台回拉快照,立即返回。
11
+ * standalone 应用接收已配对平台的通知:按令牌 iss 找到平台,以该平台的服务 client 为 audience 验签
10
12
  */
11
13
  module.exports = fp(async (fastify, options) => {
12
- if (options.runtime.tenantRole !== 'independent') {
14
+ const independent = options.runtime.tenantRole === 'independent';
15
+ if (!independent && !options.runtime.idpEnabled) {
13
16
  return;
14
17
  }
15
- const { verifier, tenantSync, translator } = fastify[options.name];
18
+ const { verifier, tenantSync, platformContexts, translator } = fastify[options.name];
19
+
20
+ const resolveTarget = token => {
21
+ if (independent) {
22
+ return { audience: options.serviceClient.clientId, tenantSync };
23
+ }
24
+ let iss;
25
+ try {
26
+ iss = decodeJwt(token).iss;
27
+ } catch (e) {
28
+ return null;
29
+ }
30
+ const context = platformContexts?.forIssuer(iss);
31
+ return context?.tenantSync ? { audience: context.platform.serviceClientId, tenantSync: context.tenantSync } : null;
32
+ };
16
33
  const usedJti = new Map();
17
34
 
18
35
  const consumeJti = (jti, exp) => {
@@ -37,23 +54,28 @@ module.exports = fp(async (fastify, options) => {
37
54
  {
38
55
  schema: {
39
56
  tags: ['OIDC-服务接口'],
40
- summary: '接收宿主租户变更通知(independent 子应用)',
57
+ summary: '接收宿主租户变更通知(independent 子应用 / 已配对平台的 standalone 应用)',
41
58
  description: '验签并校验 jti 防重放后立即返回,后台回拉该租户快照;令牌无效或重放返回 400',
42
59
  body: { type: 'object', required: ['tenant_sync_token'], properties: { tenant_sync_token: { type: 'string', description: '宿主签发的租户同步令牌(JWT),含 tenant_id' } } },
43
60
  response: empty('已接收,后台同步')
44
61
  }
45
62
  },
46
63
  translator.wrap(async (request, reply) => {
64
+ const token = request.body.tenant_sync_token;
65
+ const target = resolveTarget(token);
47
66
  let payload;
48
67
  try {
49
- payload = await verifier.verifyTenantSyncToken(request.body.tenant_sync_token, { audience: options.serviceClient.clientId });
68
+ if (!target?.audience) {
69
+ throw new Error('tenant sync target not found');
70
+ }
71
+ payload = await verifier.verifyTenantSyncToken(token, { audience: target.audience });
50
72
  } catch (e) {
51
73
  throw createError(BadRequest, 'tenantSyncTokenInvalid');
52
74
  }
53
75
  if (!consumeJti(payload.jti, payload.exp)) {
54
76
  throw createError(BadRequest, 'tenantSyncTokenReplayed');
55
77
  }
56
- tenantSync.syncInBackground(payload.tenant_id);
78
+ target.tenantSync.syncInBackground(payload.tenant_id);
57
79
  reply.header('cache-control', 'no-store');
58
80
  return {};
59
81
  })
@@ -227,7 +227,7 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
227
227
  if (!accountId) {
228
228
  return undefined;
229
229
  }
230
- const extra = {};
230
+ const extra = { [claims.issuedAtMs]: Date.now() };
231
231
  let sid = token.sid;
232
232
  if (!sid && token.sessionUid) {
233
233
  const session = await ctx.oidc.provider.Session.findByUid(token.sessionUid);
@@ -1,4 +1,4 @@
1
- const { scopePermissions, isAppEnabledIn } = require('../utils/app-permissions');
1
+ const { appModuleCode, scopePermissions, isAppEnabledIn } = require('../utils/app-permissions');
2
2
  const { COMPANY_FIELDS } = require('../utils/tenant-images');
3
3
 
4
4
  const ACTIVE_USER_STATUS = [0, 1];
@@ -33,9 +33,11 @@ module.exports = ({ fastify, options }) => {
33
33
  }
34
34
  };
35
35
 
36
- const isAppEnabled = async (tenantId, appCode) => isAppEnabledIn(await getTenantPermissionCodes(tenantId), appCode, prefix);
36
+ const moduleCodeOf = appCode => appModuleCode(prefix, appCode, fastify[options.name].services.app?.findByCode(appCode));
37
37
 
38
- const scopeAppPermissions = (permissions, appCode) => scopePermissions(permissions, appCode, prefix);
38
+ const isAppEnabled = async (tenantId, appCode) => isAppEnabledIn(await getTenantPermissionCodes(tenantId), moduleCodeOf(appCode));
39
+
40
+ const scopeAppPermissions = (permissions, appCode) => scopePermissions(permissions, moduleCodeOf(appCode));
39
41
 
40
42
  const getUser = async id => {
41
43
  try {
@@ -175,7 +177,7 @@ module.exports = ({ fastify, options }) => {
175
177
  }
176
178
  const hostTenant = plain(await services.tenant.detail({ id: tenantId, withTenantSetting: false }));
177
179
  const codes = await getTenantPermissionCodes(tenantId);
178
- const enabled = appOpen && isAppEnabledIn(codes, appCode, prefix);
180
+ const enabled = appOpen && isAppEnabledIn(codes, moduleCodeOf(appCode));
179
181
  const snapshot = {
180
182
  tenant: Object.assign(pickFields(hostTenant, SNAPSHOT_TENANT_FIELDS), {
181
183
  id: String(hostTenant.id),
@@ -38,7 +38,7 @@ const extractToken = request => {
38
38
  * 与 fastify.account.authenticate 同形的认证中间件:
39
39
  * 填充 request.user(统一结构)以及兼容字段 request.userInfo / request.authenticatePayload / request.tenantUserInfo
40
40
  */
41
- module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, tenantSync, translator }) => {
41
+ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, tenantSync, platformContexts, translator }) => {
42
42
  const { runtime } = options;
43
43
  const account = () => fastify[options.accountNamespace];
44
44
  const tenant = () => options.getTenant();
@@ -67,6 +67,20 @@ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, se
67
67
  }
68
68
  };
69
69
 
70
+ // standalone 已配对平台签发的令牌:宿主租户换成本地托管租户,下游 fastify-tenant 按本地租户 id 读成员与权限
71
+ const resolvePlatformTenant = async (normalized, context) => {
72
+ normalized.platformIssuer = context.issuer;
73
+ normalized.hostTenantId = normalized.tenantId;
74
+ normalized.tenantId = null;
75
+ if (normalized.hostTenantId && context.tenantSync) {
76
+ try {
77
+ normalized.tenantId = await context.tenantSync.ensureFresh(normalized.hostTenantId);
78
+ } catch (err) {
79
+ fastify.log.warn({ err, issuer: context.issuer, hostTenantId: normalized.hostTenantId }, 'fastify-oidc: 解析平台租户对应的本地租户失败');
80
+ }
81
+ }
82
+ };
83
+
70
84
  const getRequestUrl = request => (options.getRequestUrl ? options.getRequestUrl(request) : `${runtime.origin}${request.raw.url}`);
71
85
 
72
86
  const verifyRequest = async (request, { audience } = {}) => {
@@ -127,16 +141,19 @@ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, se
127
141
  }
128
142
  throw createError(Unauthorized, 'accessTokenMissing');
129
143
  }
130
- const normalized = normalizeClaims(payload, runtime.claims);
144
+ const platformContext = runtime.idpEnabled && platformContexts ? platformContexts.forIssuer(payload.iss) : null;
145
+ const normalized = normalizeClaims(payload, platformContext ? platformContext.claims : runtime.claims);
131
146
  if (normalized.isClient) {
132
147
  throw createError(Unauthorized, 'userTokenRequired');
133
148
  }
134
149
  if (independent) {
135
150
  await resolveIndependentTenant(normalized);
151
+ } else if (platformContext) {
152
+ await resolvePlatformTenant(normalized, platformContext);
136
153
  }
137
154
  request.user = normalized;
138
155
  request.authenticatePayload = { id: normalized.userId, tenantId: normalized.tenantId };
139
- request.userInfo = await resolveUserInfo(normalized.userId);
156
+ request.userInfo = platformContext && account() ? await platformContext.userMirror.ensure(normalized.userId) : await resolveUserInfo(normalized.userId);
140
157
  request.appName = request.headers['x-app-name'];
141
158
  };
142
159
 
@@ -0,0 +1,66 @@
1
+ const createServiceClient = require('./service-client');
2
+ const createUserMirror = require('./user-mirror');
3
+ const createTenantSync = require('./tenant-sync');
4
+ const { claimNames } = require('../utils/resolve-options');
5
+
6
+ /**
7
+ * standalone 应用与主平台配对后,同时服务平台的用户与租户:
8
+ * 平台用户镜像到本地用户表,平台租户同步为本地只读托管租户(managedBy.issuer = 平台 issuer),
9
+ * 相当于对每个已配对平台各跑一套 central + independent。本地 IdP 的用户与自建租户不受影响。
10
+ */
11
+ module.exports = ({ fastify, options, platforms }) => {
12
+ const contexts = new Map();
13
+
14
+ // 未登记 appCode 时从应用中心的资源标识({平台}/app/{code}/api)推导
15
+ const appCodeOf = platform => platform.appCode || (String(platform.audience || '').match(/\/app\/([A-Za-z0-9_-]+)\/api$/) || [])[1] || null;
16
+
17
+ const signatureOf = platform => JSON.stringify([platform.issuer, platform.serviceClientId, platform.serviceClientSecret, platform.apiBase, platform.serviceAudience, platform.claimNamespace, appCodeOf(platform)]);
18
+
19
+ const build = platform => {
20
+ const issuerOrigin = new URL(platform.issuer).origin;
21
+ const apiBase = platform.apiBase || `${issuerOrigin}${options.prefix}`;
22
+ const claimNamespace = platform.claimNamespace || `${issuerOrigin}/`;
23
+ const appCode = appCodeOf(platform);
24
+ const runtime = Object.assign({}, options.runtime, {
25
+ issuer: platform.issuer,
26
+ issuerOrigin,
27
+ idpApiBase: apiBase,
28
+ serviceAudience: platform.serviceAudience || apiBase,
29
+ claimNamespace,
30
+ claims: claimNames(claimNamespace),
31
+ app: appCode ? { code: appCode, tenantMode: 'independent' } : null,
32
+ tenantRole: 'independent'
33
+ });
34
+ const platformOptions = Object.assign({}, options, {
35
+ runtime,
36
+ serviceClient: { clientId: platform.serviceClientId, clientSecret: platform.serviceClientSecret },
37
+ // 本地有自己的超级管理员,平台超级管理员身份不带进来
38
+ mirrorSuperAdmin: false
39
+ });
40
+ const serviceClient = createServiceClient({ options: platformOptions });
41
+ const userMirror = createUserMirror({ fastify, options: platformOptions, serviceClient });
42
+ const managed = options.getTenant()?.services?.managed;
43
+ const tenantSync = appCode && managed ? createTenantSync({ fastify, options: platformOptions, serviceClient, userMirror }) : null;
44
+ return { platform, issuer: platform.issuer, claims: runtime.claims, serviceClient, userMirror, tenantSync };
45
+ };
46
+
47
+ /** 令牌 iss 命中已配对平台时返回该平台的上下文,平台信息变化(如重新配对换了密钥)后重建 */
48
+ const forIssuer = issuer => {
49
+ const platform = issuer ? platforms.findByIssuer(issuer) : null;
50
+ if (!platform || platform.status !== 'paired') {
51
+ return null;
52
+ }
53
+ const signature = signatureOf(platform);
54
+ const cached = contexts.get(platform.issuer);
55
+ if (cached && cached.signature === signature) {
56
+ return cached.context;
57
+ }
58
+ const context = build(platform);
59
+ contexts.set(platform.issuer, { signature, context });
60
+ return context;
61
+ };
62
+
63
+ const close = () => Promise.allSettled([...contexts.values()].map(({ context }) => context.tenantSync?.close()));
64
+
65
+ return { forIssuer, close };
66
+ };
@@ -30,9 +30,14 @@ const createMemoryStore = () => {
30
30
 
31
31
  /**
32
32
  * 记录已登出的会话(sid)和需要强制失效的用户(sub)。
33
- * JWT access_token 无法真正撤销,只能在资源侧拒绝:sid 命中,或 sub 的撤销时间晚于 token 的 iat。
33
+ * JWT access_token 无法真正撤销,只能在资源侧拒绝:sid 命中,或 sub 的撤销时间不早于 token 的签发时间。
34
+ *
35
+ * 签发时间的精度:标准 iat 只有秒,同一秒内「先吊销、后签发」的令牌与「先签发、后吊销」的令牌无法区分,
36
+ * 若按秒比较会把刚签发的有效令牌误拒。IdP 签发的令牌带毫秒级签发时间 claim(issuedAtMsClaim),
37
+ * 吊销同时记毫秒时间:两边都有毫秒信息时按毫秒精确比较;令牌没有该 claim(旧版 IdP、外部签发)
38
+ * 或吊销记录没有毫秒时间(旧版进程写入)时,退回按秒比较(同一秒内保守地视为已吊销)。
34
39
  */
35
- module.exports = ({ store, ttl }) => {
40
+ module.exports = ({ store, ttl, issuedAtMsClaim }) => {
36
41
  store = store || createMemoryStore();
37
42
 
38
43
  const revokeSession = async sid => {
@@ -40,7 +45,9 @@ module.exports = ({ store, ttl }) => {
40
45
  };
41
46
 
42
47
  const revokeSubject = async sub => {
43
- await store.set(`sub:${sub}`, Math.floor(Date.now() / 1000), ttl);
48
+ const revokedAtMs = Date.now();
49
+ await store.set(`sub:${sub}`, Math.floor(revokedAtMs / 1000), ttl);
50
+ await store.set(`sub-ms:${sub}`, revokedAtMs, ttl);
44
51
  };
45
52
 
46
53
  const isRevoked = async payload => {
@@ -48,6 +55,13 @@ module.exports = ({ store, ttl }) => {
48
55
  return true;
49
56
  }
50
57
  if (payload.sub) {
58
+ const issuedAtMs = issuedAtMsClaim ? Number(payload[issuedAtMsClaim]) : NaN;
59
+ if (Number.isFinite(issuedAtMs)) {
60
+ const revokedAtMs = Number(await store.get(`sub-ms:${payload.sub}`));
61
+ if (revokedAtMs) {
62
+ return issuedAtMs <= revokedAtMs;
63
+ }
64
+ }
51
65
  const revokedAt = await store.get(`sub:${payload.sub}`);
52
66
  if (revokedAt && payload.iat <= revokedAt) {
53
67
  return true;
@@ -59,7 +59,7 @@ module.exports = ({ fastify, options, serviceClient }) => {
59
59
  profile.avatar = avatar;
60
60
  }
61
61
  // 主项目超级管理员身份以主项目为准,升降级都同步到镜像,子项目 authenticate.admin 照常读本地 isSuperAdmin
62
- if (typeof remote?.isSuperAdmin === 'boolean' && getModel().rawAttributes.isSuperAdmin) {
62
+ if (options.mirrorSuperAdmin !== false && typeof remote?.isSuperAdmin === 'boolean' && getModel().rawAttributes.isSuperAdmin) {
63
63
  profile.isSuperAdmin = remote.isSuperAdmin;
64
64
  }
65
65
  return profile;
@@ -1,7 +1,7 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const httpErrors = require('http-errors');
3
3
  const { createError } = require('../utils/intl');
4
- const { wrapAppTree, countPermissions, hashPermissions } = require('../utils/app-permissions');
4
+ const { isRootPermissionApp, wrapAppTree, countPermissions, hashPermissions } = require('../utils/app-permissions');
5
5
 
6
6
  const { NotFound, BadRequest, Forbidden } = httpErrors;
7
7
 
@@ -33,13 +33,16 @@ module.exports = fp(async (fastify, options) => {
33
33
  return;
34
34
  }
35
35
  const next = new Map();
36
- listOpen().forEach(app => {
37
- const signature = `${app.name}:${app.permissionsHash}`;
38
- if (loaded.get(app.code) !== signature) {
39
- tenant.setPermissionSource(sourceKey(app.code), wrapAppTree({ prefix: options.appPermissionPrefix, centerName: options.appCenterName, app }), { defaultDisabled: true });
40
- }
41
- next.set(app.code, signature);
42
- });
36
+ // permissionRoot 的应用权限树由宿主其他来源挂在顶层,这里不再挂一份 apps:<code>
37
+ listOpen()
38
+ .filter(app => !isRootPermissionApp(app))
39
+ .forEach(app => {
40
+ const signature = `${app.name}:${app.permissionsHash}`;
41
+ if (loaded.get(app.code) !== signature) {
42
+ tenant.setPermissionSource(sourceKey(app.code), wrapAppTree({ prefix: options.appPermissionPrefix, centerName: options.appCenterName, app }), { defaultDisabled: true });
43
+ }
44
+ next.set(app.code, signature);
45
+ });
43
46
  loaded.forEach((signature, code) => !next.has(code) && tenant.removePermissionSource(sourceKey(code)));
44
47
  loaded = next;
45
48
  };
@@ -72,7 +75,7 @@ module.exports = fp(async (fastify, options) => {
72
75
  return item;
73
76
  };
74
77
 
75
- const register = async ({ serviceClientId, code, name, description, tenantMode = 'client', clientId, resource, permissions, tenantSyncUri }) => {
78
+ const register = async ({ serviceClientId, code, name, description, tenantMode = 'client', clientId, resource, permissions, permissionRoot = false, tenantSyncUri }) => {
76
79
  if (!code || !/^[A-Za-z0-9_-]+$/.test(code)) {
77
80
  throw createError(BadRequest, 'appCodeInvalid');
78
81
  }
@@ -84,7 +87,8 @@ module.exports = fp(async (fastify, options) => {
84
87
  if (item && !removed && item.serviceClientId !== serviceClientId) {
85
88
  throw createError(Forbidden, 'appCodeTaken', { code });
86
89
  }
87
- const tree = permissions && typeof permissions === 'object' ? permissions : { modules: [] };
90
+ // permissionRoot:权限树由宿主其他来源维护在顶层 <code> 下(如应用中心关联的外部应用),只记标记,开通与权限裁剪都按顶层 code
91
+ const tree = permissionRoot ? { root: true } : permissions && typeof permissions === 'object' ? permissions : { modules: [] };
88
92
  const permissionsHash = hashPermissions(tree);
89
93
  const values = {
90
94
  name: name || code,
@@ -3,16 +3,19 @@ const crypto = require('node:crypto');
3
3
  const TENANT_SYNC_EVENT = 'urn:kne:oidc:tenant-sync';
4
4
 
5
5
  /**
6
- * 子应用权限在宿主侧统一挂在 `${prefix}:<appCode>:` 之下,模块 code `${prefix}:<appCode>` 即租户是否开通该应用的开关
6
+ * 子应用权限在宿主侧统一挂在 `${prefix}:<appCode>:` 之下,模块 code `${prefix}:<appCode>` 即租户是否开通该应用的开关。
7
+ * 权限树由宿主其他来源维护的应用(注册时 permissionRoot,如应用中心关联的外部应用)挂在顶层 `<appCode>` 下
7
8
  */
8
- const appModuleCode = (prefix, appCode) => `${prefix}:${appCode}`;
9
+ const isRootPermissionApp = app => app?.permissions?.root === true;
9
10
 
10
- const scopePermissions = (permissions, appCode, prefix) => {
11
- const head = `${appModuleCode(prefix, appCode)}:`;
11
+ const appModuleCode = (prefix, appCode, app) => (isRootPermissionApp(app) ? appCode : `${prefix}:${appCode}`);
12
+
13
+ const scopePermissions = (permissions, moduleCode) => {
14
+ const head = `${moduleCode}:`;
12
15
  return [...new Set((permissions || []).filter(code => typeof code === 'string' && code.startsWith(head)).map(code => code.slice(head.length)))];
13
16
  };
14
17
 
15
- const isAppEnabledIn = (permissions, appCode, prefix) => (permissions || []).includes(appModuleCode(prefix, appCode));
18
+ const isAppEnabledIn = (permissions, moduleCode) => (permissions || []).includes(moduleCode);
16
19
 
17
20
  const wrapAppTree = ({ prefix, centerName, app }) => ({
18
21
  modules: [
@@ -49,4 +52,4 @@ const hashPermissions = tree =>
49
52
  .update(JSON.stringify(tree || {}))
50
53
  .digest('hex');
51
54
 
52
- module.exports = { TENANT_SYNC_EVENT, appModuleCode, scopePermissions, isAppEnabledIn, wrapAppTree, countPermissions, hashPermissions };
55
+ module.exports = { TENANT_SYNC_EVENT, isRootPermissionApp, appModuleCode, scopePermissions, isAppEnabledIn, wrapAppTree, countPermissions, hashPermissions };
@@ -2,6 +2,9 @@
2
2
  * central 多平台:运行时 platforms[](按 platformOrigin / issuer 唯一)。
3
3
  * 登录与验签按 token.iss 选择对应 JWKS + audience。
4
4
  */
5
+ const PLATFORM_SERVICE_FIELDS = ['serviceClientSecret', 'appCode', 'apiBase', 'serviceAudience', 'claimNamespace'];
6
+ const URL_FIELDS = ['apiBase', 'serviceAudience'];
7
+
5
8
  const normalizePlatform = (item = {}) => {
6
9
  const platformOrigin = String(item.platformOrigin || '')
7
10
  .replace(/\/+$/, '')
@@ -12,7 +15,7 @@ const normalizePlatform = (item = {}) => {
12
15
  if (!platformOrigin || !issuer) {
13
16
  throw new Error('fastify-oidc: platform 需要 platformOrigin 与 issuer');
14
17
  }
15
- return {
18
+ const platform = {
16
19
  platformOrigin,
17
20
  platformName: item.platformName || platformOrigin,
18
21
  issuer,
@@ -23,6 +26,14 @@ const normalizePlatform = (item = {}) => {
23
26
  status: item.status || 'paired',
24
27
  pairedAt: item.pairedAt || null
25
28
  };
29
+ // standalone 服务该平台的用户与租户时才需要(不进 publicList):服务 client 密钥、本应用在平台的 code、平台服务接口地址;
30
+ // 只在传入时写入,upsert 未带这些字段时保留已有值
31
+ PLATFORM_SERVICE_FIELDS.forEach(key => {
32
+ if (item[key]) {
33
+ platform[key] = URL_FIELDS.includes(key) ? String(item[key]).replace(/\/+$/, '') : String(item[key]);
34
+ }
35
+ });
36
+ return platform;
26
37
  };
27
38
 
28
39
  const createPlatformsRegistry = ({ initial = [], onChange = null } = {}) => {
@@ -20,7 +20,9 @@ const claimNames = namespace => ({
20
20
  tenantUserId: `${namespace}tenant_user_id`,
21
21
  roles: `${namespace}roles`,
22
22
  permissions: `${namespace}permissions`,
23
- clientToken: `${namespace}client_token`
23
+ clientToken: `${namespace}client_token`,
24
+ // 令牌签发时间(毫秒):标准 iat 只有秒精度,吊销需要它区分同一秒内先后签发的令牌
25
+ issuedAtMs: `${namespace}issued_at_ms`
24
26
  });
25
27
 
26
28
  const TENANT_MODES = ['client', 'independent'];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-oidc",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌",
5
5
  "main": "index.js",
6
6
  "scripts": {