@kne/fastify-oidc 0.1.9 → 0.1.11

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.
@@ -0,0 +1,171 @@
1
+ const { mapTenantImages } = require('../utils/tenant-images');
2
+
3
+ const FAILURE_RETRY_MS = 30 * 1000;
4
+ const FILE_SOURCE = 'oidcHostFileSource';
5
+
6
+ /**
7
+ * independent 子应用:回拉宿主租户快照与成员,写入本地 fastify-tenant 托管租户。
8
+ * 同一租户的同步串行执行,进行中再收到通知只标记一次重跑;过期拉取在后台进行,不阻塞请求
9
+ */
10
+ module.exports = ({ fastify, options, serviceClient, userMirror }) => {
11
+ const { runtime } = options;
12
+ const running = new Map();
13
+ const fresh = new Map();
14
+ const ttl = () => options.tenantSyncTTL * 1000;
15
+ const managed = () => options.getTenant().services.managed;
16
+ const fetchMembers = async tenantId => {
17
+ const members = [];
18
+ const fileUrls = {};
19
+ for (let currentPage = 1; ; currentPage++) {
20
+ const { pageData = [], totalCount = 0, fileUrls: pageFileUrls } = await serviceClient.getTenantMembers({ tenantId, currentPage, perPage: options.tenantSyncPageSize });
21
+ members.push(...pageData);
22
+ Object.assign(fileUrls, pageFileUrls);
23
+ if (!pageData.length || members.length >= totalCount) {
24
+ return { members, fileUrls };
25
+ }
26
+ }
27
+ };
28
+
29
+ // 成员关联的是镜像用户:先确保镜像存在;宿主租户内没有单独头像时用镜像用户已拷到本地的头像
30
+ const mirrorMembers = async members => {
31
+ for (const member of members) {
32
+ try {
33
+ const user = await userMirror.ensure(String(member.userId));
34
+ member.userAvatar = user.avatar || null;
35
+ } catch (err) {
36
+ member.userAvatar = null;
37
+ fastify.log.warn({ err, userId: member.userId }, 'fastify-oidc: 同步租户成员时创建镜像用户失败');
38
+ }
39
+ }
40
+ return members;
41
+ };
42
+
43
+ /**
44
+ * 宿主文件 id 在子应用无法解析:按宿主给出的地址拷到本地文件库,返回 { 宿主 id: 本地 id }。
45
+ * 上次同步的映射记在托管租户 options.managedBy.files,宿主文件不变且本地文件还在就不再下载;本地没有文件库时返回 null
46
+ */
47
+ const mirrorFiles = async (hostTenantId, fileUrls) => {
48
+ const files = fastify[options.fileNamespace]?.services;
49
+ if (typeof files?.uploadFromUrl !== 'function') {
50
+ return null;
51
+ }
52
+ const local = await managed().findByHostTenantId({ issuer: runtime.issuer, hostTenantId });
53
+ const previous = local?.options?.managedBy?.files || {};
54
+ const mapping = {};
55
+ for (const [source, url] of Object.entries(fileUrls)) {
56
+ const current = previous[source];
57
+ if (current && (await Promise.resolve(files.getFileInstance({ id: current })).catch(() => null))) {
58
+ mapping[source] = current;
59
+ continue;
60
+ }
61
+ try {
62
+ mapping[source] = String((await files.uploadFromUrl({ url, options: { [FILE_SOURCE]: source } })).id);
63
+ } catch (err) {
64
+ fastify.log.warn({ err, source }, 'fastify-oidc: 拷贝宿主租户图片失败');
65
+ }
66
+ }
67
+ return mapping;
68
+ };
69
+
70
+ const localizeFiles = async (hostTenantId, snapshot, members, memberFileUrls) => {
71
+ const mapping = await mirrorFiles(hostTenantId, Object.assign({}, snapshot.fileUrls, memberFileUrls));
72
+ const resolve = source => (mapping ? mapping[source] || null : source);
73
+ const { fileUrls, ...rest } = snapshot;
74
+ return {
75
+ snapshot: Object.assign(rest, { tenant: mapTenantImages(snapshot.tenant, resolve) }, mapping ? { files: mapping } : {}),
76
+ members: members.map(({ userAvatar, ...member }) => Object.assign(member, { avatar: (member.avatar && resolve(member.avatar)) || userAvatar }))
77
+ };
78
+ };
79
+
80
+ // 宿主已删除租户时快照只有 id:沿用本地托管租户名关闭它,本地没有则无需处理
81
+ const resolveRemoved = async (hostTenantId, snapshot) => {
82
+ const local = await managed().findByHostTenantId({ issuer: runtime.issuer, hostTenantId });
83
+ return local ? Object.assign({}, snapshot, { tenant: Object.assign({}, snapshot.tenant, { name: local.name }) }) : null;
84
+ };
85
+
86
+ const runOnce = async hostTenantId => {
87
+ let snapshot = await serviceClient.getTenantSnapshot({ tenantId: hostTenantId });
88
+ if (snapshot.removed) {
89
+ snapshot = await resolveRemoved(hostTenantId, snapshot);
90
+ if (!snapshot) {
91
+ fresh.set(hostTenantId, { tenantId: null, syncedAt: Date.now() });
92
+ return null;
93
+ }
94
+ }
95
+ const { members: hostMembers, fileUrls: memberFileUrls } = snapshot.enabled ? await fetchMembers(hostTenantId) : { members: [], fileUrls: {} };
96
+ const localized = await localizeFiles(hostTenantId, snapshot, await mirrorMembers(hostMembers), memberFileUrls);
97
+ const tenant = await managed().applySnapshot({ issuer: runtime.issuer, snapshot: Object.assign(localized.snapshot, { members: localized.members }) });
98
+ fresh.set(hostTenantId, { tenantId: tenant && snapshot.enabled ? String(tenant.id) : null, syncedAt: Date.now() });
99
+ return tenant;
100
+ };
101
+
102
+ const sync = hostTenantId => {
103
+ const key = String(hostTenantId);
104
+ const current = running.get(key);
105
+ if (current) {
106
+ current.rerun = true;
107
+ return current.promise;
108
+ }
109
+ const entry = { rerun: false };
110
+ entry.promise = (async () => {
111
+ try {
112
+ let result;
113
+ do {
114
+ entry.rerun = false;
115
+ result = await runOnce(key);
116
+ } while (entry.rerun);
117
+ return result;
118
+ } finally {
119
+ running.delete(key);
120
+ }
121
+ })();
122
+ running.set(key, entry);
123
+ return entry.promise;
124
+ };
125
+
126
+ const syncInBackground = key =>
127
+ sync(key).catch(err => {
128
+ fastify.log.warn({ err, hostTenantId: key }, 'fastify-oidc: 同步宿主租户失败');
129
+ return null;
130
+ });
131
+
132
+ /**
133
+ * 返回宿主租户对应的本地托管租户 id(未开通 / 拉取失败为 null)。
134
+ * 本地还没有时同步拉取;已过 tenantSyncTTL 时后台刷新,先用本地已有数据
135
+ */
136
+ const ensureFresh = async hostTenantId => {
137
+ const key = String(hostTenantId);
138
+ let cached = fresh.get(key);
139
+ if (!cached) {
140
+ const local = await managed().findByHostTenantId({ issuer: runtime.issuer, hostTenantId: key });
141
+ if (local) {
142
+ cached = { tenantId: local.status === 'open' ? String(local.id) : null, syncedAt: Date.parse(local.options?.managedBy?.syncedAt) || 0 };
143
+ fresh.set(key, cached);
144
+ }
145
+ }
146
+ if (!cached) {
147
+ try {
148
+ await sync(key);
149
+ return fresh.get(key)?.tenantId || null;
150
+ } catch (err) {
151
+ fastify.log.warn({ err, hostTenantId: key }, 'fastify-oidc: 首次同步宿主租户失败');
152
+ fresh.set(key, { tenantId: null, syncedAt: Date.now() - ttl() + FAILURE_RETRY_MS });
153
+ return null;
154
+ }
155
+ }
156
+ if (Date.now() - cached.syncedAt >= ttl() && !running.has(key)) {
157
+ cached.syncedAt = Date.now();
158
+ syncInBackground(key);
159
+ }
160
+ return cached.tenantId;
161
+ };
162
+
163
+ const whenIdle = async hostTenantId => {
164
+ const entry = running.get(String(hostTenantId));
165
+ return entry ? entry.promise.catch(() => null) : null;
166
+ };
167
+
168
+ const close = () => Promise.allSettled([...running.values()].map(entry => entry.promise));
169
+
170
+ return { sync, syncInBackground, ensureFresh, whenIdle, close };
171
+ };
@@ -1,5 +1,6 @@
1
1
  const { jwtVerify, createRemoteJWKSet } = require('jose');
2
2
  const { createError } = require('../utils/intl');
3
+ const { TENANT_SYNC_EVENT } = require('../utils/app-permissions');
3
4
 
4
5
  const LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';
5
6
 
@@ -47,5 +48,19 @@ module.exports = ({ options, getLocalJWKS }) => {
47
48
  return payload;
48
49
  };
49
50
 
50
- return { verifyAccessToken, verifyLogoutToken };
51
+ const verifyTenantSyncToken = async (token, { audience }) => {
52
+ const { payload } = await jwtVerify(token, getJWKS(), {
53
+ issuer: runtime.issuer,
54
+ audience,
55
+ typ: 'tenant-sync+jwt',
56
+ clockTolerance: options.clockTolerance,
57
+ requiredClaims: ['jti', 'exp', 'tenant_id']
58
+ });
59
+ if (!payload.events || typeof payload.events[TENANT_SYNC_EVENT] !== 'object') {
60
+ throw createError(null, 'tenantSyncTokenInvalid');
61
+ }
62
+ return payload;
63
+ };
64
+
65
+ return { verifyAccessToken, verifyLogoutToken, verifyTenantSyncToken };
51
66
  };
@@ -0,0 +1,178 @@
1
+ const fp = require('fastify-plugin');
2
+ const httpErrors = require('http-errors');
3
+ const { createError } = require('../utils/intl');
4
+ const { wrapAppTree, countPermissions, hashPermissions } = require('../utils/app-permissions');
5
+
6
+ const { NotFound, BadRequest, Forbidden } = httpErrors;
7
+
8
+ const TENANT_MODES = ['client', 'independent'];
9
+ const plain = item => item.get({ plain: true });
10
+
11
+ /**
12
+ * 应用中心:子应用注册的权限树挂到宿主 fastify-tenant 的 apps 节点下,按租户开关
13
+ * 应用缓存在内存(含停用 / 已删除),交互与签发 token 时按 clientId / resource 同步查找:
14
+ * 停用或删除的应用仍要拦住其 client,不能退化成不按应用过滤
15
+ */
16
+ module.exports = fp(async (fastify, options) => {
17
+ const { models, services } = fastify[options.name];
18
+ if (!options.runtime.idpEnabled) {
19
+ return;
20
+ }
21
+ const { Op } = fastify.sequelize.Sequelize;
22
+ const sourceKey = code => `oidc-app:${code}`;
23
+ let cache = [];
24
+ let loaded = new Map();
25
+
26
+ const getTenant = () => (options.runtime.tenantRole === 'host' ? options.getTenant() : null);
27
+ const listOpen = () => cache.filter(app => app.status === 'open');
28
+
29
+ // 只对权限树有变化的应用重设来源,避免周期重载时反复重建宿主权限树
30
+ const loadIntoTenant = () => {
31
+ const tenant = getTenant();
32
+ if (!tenant || typeof tenant.setPermissionSource !== 'function') {
33
+ return;
34
+ }
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
+ });
43
+ loaded.forEach((signature, code) => !next.has(code) && tenant.removePermissionSource(sourceKey(code)));
44
+ loaded = next;
45
+ };
46
+
47
+ const reload = async () => {
48
+ cache = (await models.app.findAll()).map(plain);
49
+ loadIntoTenant();
50
+ };
51
+
52
+ // 停用 / 启用 / 删除后通知 independent 子应用回拉,及时关闭或恢复托管租户;后台执行,不阻塞管理操作
53
+ const notifyApp = app => {
54
+ if (app.tenantMode !== 'independent' || !app.tenantSyncUri || !services.tenantPush) {
55
+ return;
56
+ }
57
+ services.tenantPush.notifyApp(app).catch(err => fastify.log.warn({ err, app: app.code }, 'fastify-oidc: 通知子应用应用状态变化失败'));
58
+ };
59
+
60
+ const format = item => {
61
+ const data = plain(item);
62
+ data.clientIds = data.clientIds || [];
63
+ data.permissionCount = countPermissions(data.permissions);
64
+ return data;
65
+ };
66
+
67
+ const getInstance = async ({ id }) => {
68
+ const item = await models.app.findByPk(id);
69
+ if (!item || item.status === 'removed') {
70
+ throw createError(NotFound, 'appNotFound');
71
+ }
72
+ return item;
73
+ };
74
+
75
+ const register = async ({ serviceClientId, code, name, description, tenantMode = 'client', clientId, resource, permissions, tenantSyncUri }) => {
76
+ if (!code || !/^[A-Za-z0-9_-]+$/.test(code)) {
77
+ throw createError(BadRequest, 'appCodeInvalid');
78
+ }
79
+ if (!TENANT_MODES.includes(tenantMode)) {
80
+ throw createError(BadRequest, 'appTenantModeInvalid');
81
+ }
82
+ const item = await models.app.findOne({ where: { code } });
83
+ const removed = item?.status === 'removed';
84
+ if (item && !removed && item.serviceClientId !== serviceClientId) {
85
+ throw createError(Forbidden, 'appCodeTaken', { code });
86
+ }
87
+ const tree = permissions && typeof permissions === 'object' ? permissions : { modules: [] };
88
+ const permissionsHash = hashPermissions(tree);
89
+ const values = {
90
+ name: name || code,
91
+ description,
92
+ tenantMode,
93
+ clientIds: clientId ? [clientId] : [],
94
+ resource,
95
+ permissions: tree,
96
+ permissionsHash,
97
+ tenantSyncUri: tenantMode === 'independent' ? tenantSyncUri || null : null,
98
+ registeredAt: new Date()
99
+ };
100
+ const changed = !item || removed || item.permissionsHash !== permissionsHash;
101
+ // 已删除的应用重新注册时恢复启用,并可由新的服务 client 接手
102
+ const row = item ? await item.update(removed ? Object.assign({ serviceClientId, status: 'open' }, values) : values) : await models.app.create(Object.assign({ code, serviceClientId, status: 'open' }, values));
103
+ await reload();
104
+ if (removed) {
105
+ notifyApp(plain(row));
106
+ }
107
+ return { code, status: row.status, permissionsHash, changed };
108
+ };
109
+
110
+ const list = async ({ filter = {}, perPage = 20, currentPage = 1 } = {}) => {
111
+ const where = {};
112
+ if (filter.keyword) {
113
+ where[Op.or] = [{ code: { [Op.like]: `%${filter.keyword}%` } }, { name: { [Op.like]: `%${filter.keyword}%` } }];
114
+ }
115
+ where.status = filter.status && filter.status !== 'removed' ? filter.status : { [Op.ne]: 'removed' };
116
+ if (filter.tenantMode) {
117
+ where.tenantMode = filter.tenantMode;
118
+ }
119
+ const { rows, count } = await models.app.findAndCountAll({
120
+ where,
121
+ offset: perPage * (currentPage - 1),
122
+ limit: perPage,
123
+ order: [['createdAt', 'DESC']]
124
+ });
125
+ return { pageData: rows.map(format), totalCount: count };
126
+ };
127
+
128
+ const detail = async ({ id }) => format(await getInstance({ id }));
129
+
130
+ const setStatus = async ({ id, status }) => {
131
+ const item = await getInstance({ id });
132
+ const previous = item.status;
133
+ await item.update({ status });
134
+ await reload();
135
+ if (previous !== status) {
136
+ notifyApp(plain(item));
137
+ }
138
+ };
139
+
140
+ // 只标记删除不删行:保留 clientIds 继续拦住该应用的 client;子应用下次启动注册时恢复
141
+ const remove = async ({ id }) => {
142
+ const item = await getInstance({ id });
143
+ await item.update({ status: 'removed' });
144
+ await reload();
145
+ notifyApp(plain(item));
146
+ };
147
+
148
+ // 含停用 / 已删除的应用:independent 子应用回拉快照得到 enabled=false,据此关闭托管租户
149
+ const getByCode = async code => {
150
+ const item = code ? await models.app.findOne({ where: { code } }) : null;
151
+ return item ? plain(item) : null;
152
+ };
153
+
154
+ const findByCode = code => cache.find(app => app.code === code) || null;
155
+ const findByClientId = clientId => (clientId ? cache.find(app => (app.clientIds || []).includes(clientId)) || null : null);
156
+ const findByResource = resource => (resource ? cache.find(app => app.resource === resource) || null : null);
157
+ // 交互 / 签发 token 用的应用范围:appOpen=false 时该 client 没有可用租户
158
+ const toScope = app => (app ? { appCode: app.code, appOpen: app.status === 'open' } : {});
159
+ const scopeOfClient = clientId => toScope(findByClientId(clientId));
160
+ const scopeOfResource = resource => toScope(findByResource(resource));
161
+
162
+ services.app = {
163
+ register,
164
+ list,
165
+ detail,
166
+ setStatus,
167
+ remove,
168
+ reload,
169
+ loadIntoTenant,
170
+ getByCode,
171
+ findByCode,
172
+ findByClientId,
173
+ findByResource,
174
+ scopeOfClient,
175
+ scopeOfResource,
176
+ listOpen
177
+ };
178
+ });
@@ -59,7 +59,7 @@ module.exports = fp(async (fastify, options) => {
59
59
  output.user = user && { id: String(user.id), nickname: user.nickname, avatar: user.avatar, email: user.email, phone: user.phone };
60
60
  }
61
61
  if (prompt.name === 'tenant' && session?.accountId) {
62
- output.tenants = await identity.listTenants(session.accountId);
62
+ output.tenants = await identity.listTenants(session.accountId, services.app.scopeOfClient(params.client_id));
63
63
  }
64
64
  return output;
65
65
  };
@@ -82,7 +82,8 @@ module.exports = fp(async (fastify, options) => {
82
82
  const selectTenant = async ({ request, reply, uid, tenantId }) => {
83
83
  const { provider, interaction } = await loadInteraction({ request, reply, uid, prompt: 'tenant' });
84
84
  const accountId = interaction.session?.accountId;
85
- if (!accountId || !(await getIdp().identity.isTenantMember(accountId, tenantId))) {
85
+ const scope = services.app.scopeOfClient(interaction.params.client_id);
86
+ if (!accountId || !(await getIdp().identity.isTenantMember(accountId, tenantId, scope))) {
86
87
  throw createError(BadRequest, 'tenantNotAvailable');
87
88
  }
88
89
  return finish({ provider, request, reply, result: { tenant: { tenantId: String(tenantId) } } });
@@ -86,12 +86,23 @@ module.exports = fp(async (fastify, options) => {
86
86
  return rows.map(row => row.identifier);
87
87
  };
88
88
 
89
+ // 已存在的资源服务只追加配置中新增的 scope(如升级后服务接口新增 scope),不覆盖管理端维护的其他字段
89
90
  const seed = async resourceServers => {
90
91
  for (const item of resourceServers || []) {
91
- if (await models.resourceServer.count({ where: { identifier: item.identifier } })) {
92
+ const existing = await models.resourceServer.findOne({ where: { identifier: item.identifier } });
93
+ if (!existing) {
94
+ await create(item);
92
95
  continue;
93
96
  }
94
- await create(item);
97
+ const current = String(existing.scope || '')
98
+ .split(' ')
99
+ .filter(Boolean);
100
+ const missing = String(item.scope || '')
101
+ .split(' ')
102
+ .filter(scope => scope && !current.includes(scope));
103
+ if (missing.length) {
104
+ await existing.update({ scope: [...current, ...missing].join(' ') });
105
+ }
95
106
  }
96
107
  };
97
108
 
@@ -0,0 +1,133 @@
1
+ const fp = require('fastify-plugin');
2
+ const crypto = require('node:crypto');
3
+ const { SignJWT, importJWK } = require('jose');
4
+ const { TENANT_SYNC_EVENT } = require('../utils/app-permissions');
5
+
6
+ const NOTIFY_TYPES = ['tenant', 'tenant-permission'];
7
+
8
+ /**
9
+ * 宿主订阅 fastify-tenant 变更,通知 independent 子应用回拉租户快照。
10
+ * 导入 / 同步成员时每个成员都会触发一次事件,按租户防抖合并;推送尽力而为,失败由子应用过期拉取兜底
11
+ */
12
+ module.exports = fp(async (fastify, options) => {
13
+ const { services } = fastify[options.name];
14
+ if (options.runtime.tenantRole !== 'host') {
15
+ return;
16
+ }
17
+ const pending = new Map();
18
+ const running = new Set();
19
+ let unsubscribe = null;
20
+
21
+ const track = promise => {
22
+ running.add(promise);
23
+ promise.finally(() => running.delete(promise));
24
+ return promise;
25
+ };
26
+
27
+ const signToken = async ({ app, tenantId }) => {
28
+ const { keys } = await services.key.getPrivateJwks();
29
+ const jwk = keys[0];
30
+ return new SignJWT({ tenant_id: String(tenantId), events: { [TENANT_SYNC_EVENT]: {} } })
31
+ .setProtectedHeader({ alg: jwk.alg, kid: jwk.kid, typ: 'tenant-sync+jwt' })
32
+ .setIssuer(options.runtime.issuer)
33
+ .setAudience(app.serviceClientId)
34
+ .setIssuedAt()
35
+ .setExpirationTime(`${options.tenantSyncTokenTTL}s`)
36
+ .setJti(crypto.randomUUID())
37
+ .sign(await importJWK(jwk, jwk.alg));
38
+ };
39
+
40
+ const pushTo = async ({ app, tenantId }) => {
41
+ const response = await fetch(app.tenantSyncUri, {
42
+ method: 'POST',
43
+ headers: { 'content-type': 'application/json' },
44
+ body: JSON.stringify({ tenant_sync_token: await signToken({ app, tenantId }) }),
45
+ signal: AbortSignal.timeout(options.tenantSyncTimeout)
46
+ });
47
+ if (!response.ok) {
48
+ throw new Error(`tenant-sync 通知返回 ${response.status}`);
49
+ }
50
+ };
51
+
52
+ // 租户状态或租户权限变化时可能是刚关闭了应用,未开通也要通知子应用把托管租户置为 closed
53
+ const push = async (tenantId, types = new Set(NOTIFY_TYPES)) => {
54
+ const apps = services.app.listOpen().filter(app => app.tenantMode === 'independent' && app.tenantSyncUri);
55
+ if (!apps.length) {
56
+ return;
57
+ }
58
+ const { identity } = fastify[options.name].idp;
59
+ const mayHaveClosed = NOTIFY_TYPES.some(type => types.has(type));
60
+ for (const app of apps) {
61
+ try {
62
+ if (!mayHaveClosed && !(await identity.isAppEnabled(tenantId, app.code))) {
63
+ continue;
64
+ }
65
+ await pushTo({ app, tenantId });
66
+ } catch (err) {
67
+ fastify.log.warn({ err, tenantId, app: app.code }, 'fastify-oidc: 推送租户变更通知失败');
68
+ }
69
+ }
70
+ };
71
+
72
+ // 应用被停用 / 启用 / 删除:通知开通过它的租户(租户权限里仍有 apps:<code>),子应用回拉后关闭或恢复托管租户
73
+ const notifyApp = app => track(notifyAppTenants(app));
74
+
75
+ const notifyAppTenants = async app => {
76
+ const tenant = options.getTenant();
77
+ if (!tenant || app.tenantMode !== 'independent' || !app.tenantSyncUri) {
78
+ return;
79
+ }
80
+ const { identity } = fastify[options.name].idp;
81
+ const rows = await tenant.models.tenant.findAll({ attributes: ['id'] });
82
+ for (const { id } of rows) {
83
+ const tenantId = String(id);
84
+ try {
85
+ if (await identity.isAppEnabled(tenantId, app.code)) {
86
+ await pushTo({ app, tenantId });
87
+ }
88
+ } catch (err) {
89
+ fastify.log.warn({ err, tenantId, app: app.code }, 'fastify-oidc: 推送应用状态变化通知失败');
90
+ }
91
+ }
92
+ };
93
+
94
+ const schedule = ({ tenantId, type } = {}) => {
95
+ if (!tenantId) {
96
+ return;
97
+ }
98
+ const key = String(tenantId);
99
+ const entry = pending.get(key) || { types: new Set() };
100
+ entry.types.add(type);
101
+ clearTimeout(entry.timer);
102
+ entry.timer = setTimeout(() => {
103
+ pending.delete(key);
104
+ track(push(key, entry.types));
105
+ }, options.tenantSyncDebounce);
106
+ entry.timer.unref?.();
107
+ pending.set(key, entry);
108
+ };
109
+
110
+ const start = () => {
111
+ const tenant = options.getTenant();
112
+ if (!unsubscribe && tenant && typeof tenant.onChange === 'function') {
113
+ unsubscribe = tenant.onChange(schedule);
114
+ }
115
+ };
116
+
117
+ const stop = () => {
118
+ pending.forEach(entry => clearTimeout(entry.timer));
119
+ pending.clear();
120
+ unsubscribe?.();
121
+ unsubscribe = null;
122
+ };
123
+
124
+ // 进行中的推送会让子应用回调宿主,关闭前等它们结束,避免宿主 close 挂起
125
+ const whenIdle = () => Promise.allSettled([...running]);
126
+
127
+ fastify.addHook('onClose', async () => {
128
+ stop();
129
+ await whenIdle();
130
+ });
131
+
132
+ services.tenantPush = { start, stop, schedule, push, notifyApp, whenIdle, signToken };
133
+ });
@@ -0,0 +1,52 @@
1
+ const crypto = require('node:crypto');
2
+
3
+ const TENANT_SYNC_EVENT = 'urn:kne:oidc:tenant-sync';
4
+
5
+ /**
6
+ * 子应用权限在宿主侧统一挂在 `${prefix}:<appCode>:` 之下,模块 code `${prefix}:<appCode>` 即租户是否开通该应用的开关
7
+ */
8
+ const appModuleCode = (prefix, appCode) => `${prefix}:${appCode}`;
9
+
10
+ const scopePermissions = (permissions, appCode, prefix) => {
11
+ const head = `${appModuleCode(prefix, appCode)}:`;
12
+ return [...new Set((permissions || []).filter(code => typeof code === 'string' && code.startsWith(head)).map(code => code.slice(head.length)))];
13
+ };
14
+
15
+ const isAppEnabledIn = (permissions, appCode, prefix) => (permissions || []).includes(appModuleCode(prefix, appCode));
16
+
17
+ const wrapAppTree = ({ prefix, centerName, app }) => ({
18
+ modules: [
19
+ {
20
+ code: prefix,
21
+ name: centerName,
22
+ index: -2,
23
+ modules: [
24
+ {
25
+ code: app.code,
26
+ name: app.name || app.code,
27
+ modules: app.permissions?.modules || [],
28
+ permissions: app.permissions?.permissions || []
29
+ }
30
+ ]
31
+ }
32
+ ]
33
+ });
34
+
35
+ const countPermissions = tree => {
36
+ let count = 0;
37
+ const walk = modules =>
38
+ (modules || []).forEach(module => {
39
+ count += (module.permissions || []).length;
40
+ walk(module.modules);
41
+ });
42
+ walk(tree?.modules);
43
+ return count + (tree?.permissions || []).length;
44
+ };
45
+
46
+ const hashPermissions = tree =>
47
+ crypto
48
+ .createHash('sha256')
49
+ .update(JSON.stringify(tree || {}))
50
+ .digest('hex');
51
+
52
+ module.exports = { TENANT_SYNC_EVENT, appModuleCode, scopePermissions, isAppEnabledIn, wrapAppTree, countPermissions, hashPermissions };
@@ -23,6 +23,32 @@ const claimNames = namespace => ({
23
23
  clientToken: `${namespace}client_token`
24
24
  });
25
25
 
26
+ const TENANT_MODES = ['client', 'independent'];
27
+
28
+ // 子应用配置:code 会拼进宿主权限 code(apps:<code>:...),不能含冒号
29
+ const resolveApp = (options, { idpEnabled, origin }) => {
30
+ if (!options.app) {
31
+ return null;
32
+ }
33
+ if (idpEnabled) {
34
+ throw new Error('fastify-oidc: app 只用于 central 模式的子应用');
35
+ }
36
+ const app = Object.assign({ tenantMode: 'client' }, options.app);
37
+ if (!app.code || !/^[A-Za-z0-9_-]+$/.test(app.code)) {
38
+ throw new Error('fastify-oidc: app.code 必填,只能包含字母、数字、下划线和中划线');
39
+ }
40
+ if (!TENANT_MODES.includes(app.tenantMode)) {
41
+ throw new Error(`fastify-oidc: app.tenantMode 只能是 ${TENANT_MODES.join(' / ')},当前为 ${app.tenantMode}`);
42
+ }
43
+ if (app.tenantMode === 'independent' && !options.tenant) {
44
+ throw new Error('fastify-oidc: independent 模式需要通过 tenant 选项传入本地 fastify-tenant');
45
+ }
46
+ if (app.tenantMode === 'independent' && !app.tenantSyncUri) {
47
+ app.tenantSyncUri = `${origin}${options.prefix}/tenant-sync`;
48
+ }
49
+ return app;
50
+ };
51
+
26
52
  /**
27
53
  * 根据 mode / ORIGIN / issuer 推导运行期配置,结果挂在 options 上供各模块读取
28
54
  */
@@ -47,9 +73,13 @@ module.exports = options => {
47
73
  }
48
74
 
49
75
  const claimNamespace = options.claimNamespace || `${idpEnabled ? origin : issuerUrl.origin}/`;
76
+ const app = resolveApp(options, { idpEnabled, origin });
50
77
 
51
78
  return {
52
79
  idpEnabled,
80
+ // host: 宿主显式传入 fastify-tenant,开启应用中心;client / independent: 子应用租户模式
81
+ tenantRole: idpEnabled ? (options.tenant ? 'host' : 'none') : app ? app.tenantMode : 'none',
82
+ app,
53
83
  origin,
54
84
  issuer,
55
85
  issuerOrigin: issuerUrl.origin,