@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 +218 -9
- package/index.js +41 -2
- package/libs/controllers/admin.js +30 -0
- package/libs/controllers/service.js +159 -11
- package/libs/controllers/tenant-apps.js +31 -0
- package/libs/controllers/tenant-proxy.js +64 -0
- package/libs/controllers/tenant-sync.js +59 -0
- package/libs/idp/adapters/sequelize.js +19 -1
- package/libs/idp/create-provider.js +8 -5
- package/libs/idp/identity.js +151 -20
- package/libs/idp/index.js +20 -1
- package/libs/locale/en-US.js +9 -1
- package/libs/locale/zh-CN.js +9 -1
- package/libs/models/app.js +65 -0
- package/libs/resource/app-registry.js +76 -0
- package/libs/resource/authenticate.js +41 -3
- package/libs/resource/remote-tenant.js +7 -0
- package/libs/resource/service-client.js +25 -8
- package/libs/resource/tenant-sync.js +171 -0
- package/libs/resource/user-mirror.js +40 -2
- package/libs/resource/verify-token.js +16 -1
- package/libs/services/app.js +178 -0
- package/libs/services/interaction.js +3 -2
- package/libs/services/resource-server.js +13 -2
- package/libs/services/tenant-push.js +133 -0
- package/libs/utils/app-permissions.js +52 -0
- package/libs/utils/resolve-options.js +30 -0
- package/libs/utils/tenant-images.js +34 -0
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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
|
-
|
|
92
|
+
const existing = await models.resourceServer.findOne({ where: { identifier: item.identifier } });
|
|
93
|
+
if (!existing) {
|
|
94
|
+
await create(item);
|
|
92
95
|
continue;
|
|
93
96
|
}
|
|
94
|
-
|
|
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,
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const COMPANY_FIELDS = ['name', 'fullName', 'logo', 'industry', 'scale', 'address', 'phone', 'email', 'foundedDate', 'companyTags', 'website', 'description', 'banners', 'teamDescription', 'developmentHistory', 'contact'];
|
|
2
|
+
|
|
3
|
+
const isFileId = value => typeof value === 'string' && value !== '';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 租户快照里引用宿主文件库的图片:租户 logo、公司 logo / banner / 团队头像 / 发展历程图片。
|
|
7
|
+
* mapper 收到宿主文件 id,返回替换后的值
|
|
8
|
+
*/
|
|
9
|
+
const mapTenantImages = (tenant, mapper) => {
|
|
10
|
+
const map = value => (isFileId(value) ? mapper(value) : value);
|
|
11
|
+
const mapList = list => (Array.isArray(list) ? list.map(map) : list);
|
|
12
|
+
const result = Object.assign({}, tenant);
|
|
13
|
+
if ('logo' in tenant) {
|
|
14
|
+
result.logo = map(tenant.logo);
|
|
15
|
+
}
|
|
16
|
+
const { company } = tenant;
|
|
17
|
+
if (company) {
|
|
18
|
+
result.company = Object.assign({}, company, {
|
|
19
|
+
logo: map(company.logo),
|
|
20
|
+
banners: mapList(company.banners),
|
|
21
|
+
teamDescription: Array.isArray(company.teamDescription) ? company.teamDescription.map(item => (item ? Object.assign({}, item, { avatar: map(item.avatar) }) : item)) : company.teamDescription,
|
|
22
|
+
developmentHistory: Array.isArray(company.developmentHistory) ? company.developmentHistory.map(item => (item ? Object.assign({}, item, { images: mapList(item.images) }) : item)) : company.developmentHistory
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const collectTenantImages = tenant => {
|
|
29
|
+
const ids = new Set();
|
|
30
|
+
mapTenantImages(tenant, id => ids.add(id) && id);
|
|
31
|
+
return [...ids];
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
module.exports = { COMPANY_FIELDS, mapTenantImages, collectTenantImages };
|