@kne/fastify-oidc 0.1.9 → 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 +214 -8
- package/index.js +40 -2
- package/libs/controllers/admin.js +30 -0
- package/libs/controllers/service.js +141 -18
- 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/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,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 子应用启动时把权限树注册到宿主应用中心;宿主不可用时退避重试,不阻塞启动。
|
|
3
|
+
* 宿主按 permissionsHash 比对,权限树没变化时不会重建宿主权限树
|
|
4
|
+
*/
|
|
5
|
+
module.exports = ({ fastify, options, serviceClient }) => {
|
|
6
|
+
const { runtime } = options;
|
|
7
|
+
let timer = null;
|
|
8
|
+
let stopped = false;
|
|
9
|
+
let firstAttempt = Promise.resolve(null);
|
|
10
|
+
const state = { registered: false, result: null, lastError: null };
|
|
11
|
+
|
|
12
|
+
const getPermissions = () => {
|
|
13
|
+
const { app } = runtime;
|
|
14
|
+
if (app.permissions) {
|
|
15
|
+
return app.permissions;
|
|
16
|
+
}
|
|
17
|
+
return (app.tenantMode === 'independent' && options.getTenant()?.permissions) || { modules: [] };
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const register = async () => {
|
|
21
|
+
const { app } = runtime;
|
|
22
|
+
const result = await serviceClient.registerApp({
|
|
23
|
+
code: app.code,
|
|
24
|
+
name: app.name,
|
|
25
|
+
description: app.description,
|
|
26
|
+
tenantMode: app.tenantMode,
|
|
27
|
+
clientId: runtime.clientId,
|
|
28
|
+
resource: runtime.audience,
|
|
29
|
+
permissions: getPermissions(),
|
|
30
|
+
tenantSyncUri: app.tenantSyncUri
|
|
31
|
+
});
|
|
32
|
+
Object.assign(state, { registered: true, result, lastError: null });
|
|
33
|
+
return result;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const start = () => {
|
|
37
|
+
if (!runtime.app) {
|
|
38
|
+
return firstAttempt;
|
|
39
|
+
}
|
|
40
|
+
if (!serviceClient.enabled()) {
|
|
41
|
+
fastify.log.warn('fastify-oidc: 配置了 app 但未配置 serviceClient,无法向宿主注册权限');
|
|
42
|
+
return firstAttempt;
|
|
43
|
+
}
|
|
44
|
+
let attempt = 0;
|
|
45
|
+
const run = async () => {
|
|
46
|
+
if (stopped) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
return await register();
|
|
51
|
+
} catch (err) {
|
|
52
|
+
state.lastError = err;
|
|
53
|
+
// 宿主明确拒绝(如 appCodeTaken、参数非法、未授权 scope)重试也不会成功,停止并报错,修正配置后重启
|
|
54
|
+
const status = err.upstreamStatus;
|
|
55
|
+
if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
|
56
|
+
fastify.log.error({ err, status }, 'fastify-oidc: 宿主拒绝注册应用,已停止重试');
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const delay = Math.min(options.appRegisterRetryMax * 1000, 1000 * 2 ** attempt++);
|
|
60
|
+
fastify.log.warn({ err, delay }, 'fastify-oidc: 向宿主注册应用失败,稍后重试');
|
|
61
|
+
timer = setTimeout(run, delay);
|
|
62
|
+
timer.unref?.();
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
firstAttempt = run();
|
|
67
|
+
return firstAttempt;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const stop = () => {
|
|
71
|
+
stopped = true;
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
return { start, stop, register, whenStarted: () => firstAttempt, getState: () => Object.assign({}, state) };
|
|
76
|
+
};
|
|
@@ -38,16 +38,33 @@ 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, translator }) => {
|
|
41
|
+
module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, tenantSync, translator }) => {
|
|
42
42
|
const { runtime } = options;
|
|
43
43
|
const account = () => fastify[options.accountNamespace];
|
|
44
|
-
const tenant = () =>
|
|
44
|
+
const tenant = () => options.getTenant();
|
|
45
|
+
const independent = runtime.tenantRole === 'independent';
|
|
45
46
|
|
|
46
47
|
const tenantSource = () => {
|
|
47
48
|
if (options.tenantSource) {
|
|
48
49
|
return options.tenantSource;
|
|
49
50
|
}
|
|
50
|
-
|
|
51
|
+
if (runtime.tenantRole === 'client') {
|
|
52
|
+
return 'remote';
|
|
53
|
+
}
|
|
54
|
+
return (runtime.idpEnabled || independent) && tenant() ? 'local' : 'claims';
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// independent:token 里是宿主租户,换成本地托管租户;当前租户交给本地 fastify-tenant 的默认租户决定
|
|
58
|
+
const resolveIndependentTenant = async normalized => {
|
|
59
|
+
normalized.hostTenantId = normalized.tenantId;
|
|
60
|
+
normalized.tenantId = null;
|
|
61
|
+
if (normalized.hostTenantId) {
|
|
62
|
+
try {
|
|
63
|
+
normalized.localTenantId = await tenantSync.ensureFresh(normalized.hostTenantId);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
fastify.log.warn({ err, hostTenantId: normalized.hostTenantId }, 'fastify-oidc: 解析宿主租户对应的本地租户失败');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
51
68
|
};
|
|
52
69
|
|
|
53
70
|
const getRequestUrl = request => (options.getRequestUrl ? options.getRequestUrl(request) : `${runtime.origin}${request.raw.url}`);
|
|
@@ -114,12 +131,27 @@ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, se
|
|
|
114
131
|
if (normalized.isClient) {
|
|
115
132
|
throw createError(Unauthorized, 'userTokenRequired');
|
|
116
133
|
}
|
|
134
|
+
if (independent) {
|
|
135
|
+
await resolveIndependentTenant(normalized);
|
|
136
|
+
}
|
|
117
137
|
request.user = normalized;
|
|
118
138
|
request.authenticatePayload = { id: normalized.userId, tenantId: normalized.tenantId };
|
|
119
139
|
request.userInfo = await resolveUserInfo(normalized.userId);
|
|
120
140
|
request.appName = request.headers['x-app-name'];
|
|
121
141
|
};
|
|
122
142
|
|
|
143
|
+
const getIndependentTenantUser = async currentUser => {
|
|
144
|
+
const { services } = tenant();
|
|
145
|
+
try {
|
|
146
|
+
return await services.user.getTenantUserInfo({ id: currentUser.userId });
|
|
147
|
+
} catch (e) {
|
|
148
|
+
if (!currentUser.localTenantId) {
|
|
149
|
+
throw e;
|
|
150
|
+
}
|
|
151
|
+
return services.user.getTenantUserInfo({ id: currentUser.userId, tenantId: currentUser.localTenantId });
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
123
155
|
const buildTenantUserFromClaims = currentUser => ({
|
|
124
156
|
id: currentUser.tenantUserId,
|
|
125
157
|
tenantId: currentUser.tenantId,
|
|
@@ -143,6 +175,12 @@ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, se
|
|
|
143
175
|
await tenant().authenticate.tenantUser(request);
|
|
144
176
|
return;
|
|
145
177
|
}
|
|
178
|
+
if (independent && !options.tenantSource) {
|
|
179
|
+
const info = await getIndependentTenantUser(request.user);
|
|
180
|
+
request[contextName] = info;
|
|
181
|
+
request.user.tenantId = info?.tenantId ? String(info.tenantId) : null;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
146
184
|
if (!request.user.tenantId) {
|
|
147
185
|
throw createError(Forbidden, 'tenantNotSelected');
|
|
148
186
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* client 子应用的租户门面:租户相关数据全部来自宿主服务接口,权限已去掉 apps:<code>: 前缀,租户已按是否开通本应用过滤
|
|
3
|
+
*/
|
|
4
|
+
module.exports = ({ serviceClient }) => ({
|
|
5
|
+
getTenantUserInfo: ({ userId, tenantId }) => serviceClient.getTenantUser({ userId, tenantId }),
|
|
6
|
+
tenantList: ({ userId }) => serviceClient.getTenantList({ userId })
|
|
7
|
+
});
|
|
@@ -60,21 +60,38 @@ module.exports = ({ options, fetch = globalThis.fetch }) => {
|
|
|
60
60
|
return data.access_token;
|
|
61
61
|
};
|
|
62
62
|
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
// 每个接口只申请自己需要的 scope:宿主未升级(服务接口资源没有新 scope)时,旧接口仍可用
|
|
64
|
+
const callService = async (path, { query, method = 'GET', body, scope } = {}) => {
|
|
65
|
+
const token = await getServiceToken(scope ? { scope } : undefined);
|
|
65
66
|
const url = new URL(`${runtime.idpApiBase}${path}`);
|
|
66
|
-
Object.entries(query || {}).forEach(([key, value]) => value !== undefined && url.searchParams.set(key, value));
|
|
67
|
-
const
|
|
67
|
+
Object.entries(query || {}).forEach(([key, value]) => value !== undefined && value !== null && url.searchParams.set(key, value));
|
|
68
|
+
const headers = { authorization: `Bearer ${token}` };
|
|
69
|
+
if (body !== undefined) {
|
|
70
|
+
headers['content-type'] = 'application/json';
|
|
71
|
+
}
|
|
72
|
+
const response = await fetch(url, { method, headers, body: body !== undefined ? JSON.stringify(body) : undefined });
|
|
68
73
|
const data = await response.json().catch(() => null);
|
|
69
74
|
if (!response.ok) {
|
|
70
|
-
|
|
75
|
+
const error = createError(null, 'idpServiceCallFailed', { path, status: String(response.status), reason: data?.message || '' });
|
|
76
|
+
error.upstreamStatus = response.status;
|
|
77
|
+
throw error;
|
|
71
78
|
}
|
|
72
79
|
return data && Object.prototype.hasOwnProperty.call(data, 'data') && Object.prototype.hasOwnProperty.call(data, 'code') ? data.data : data;
|
|
73
80
|
};
|
|
74
81
|
|
|
75
|
-
const
|
|
82
|
+
const appCode = () => runtime.app?.code;
|
|
83
|
+
|
|
84
|
+
const getUserProfile = async userId => callService('/service/user', { query: { id: userId }, scope: 'user:read' });
|
|
85
|
+
|
|
86
|
+
const getTenantUser = async ({ userId, tenantId }) => callService('/service/tenant-user', { query: { userId, tenantId, app: appCode() }, scope: 'tenant:read' });
|
|
87
|
+
|
|
88
|
+
const getTenantList = async ({ userId }) => callService('/service/tenant-list', { query: { userId, app: appCode() }, scope: 'tenant:read' });
|
|
89
|
+
|
|
90
|
+
const registerApp = async body => callService('/service/app/register', { method: 'POST', body, scope: 'app:register' });
|
|
91
|
+
|
|
92
|
+
const getTenantSnapshot = async ({ tenantId }) => callService('/service/tenant-snapshot', { query: { tenantId, app: appCode() }, scope: 'tenant:sync' });
|
|
76
93
|
|
|
77
|
-
const
|
|
94
|
+
const getTenantMembers = async ({ tenantId, currentPage, perPage }) => callService('/service/tenant-members', { query: { tenantId, app: appCode(), currentPage, perPage }, scope: 'tenant:sync' });
|
|
78
95
|
|
|
79
96
|
const exchangeToken = async ({ subjectToken, resource, scope }) => {
|
|
80
97
|
assertEnabled();
|
|
@@ -87,5 +104,5 @@ module.exports = ({ options, fetch = globalThis.fetch }) => {
|
|
|
87
104
|
});
|
|
88
105
|
};
|
|
89
106
|
|
|
90
|
-
return { enabled, getServiceToken, getUserProfile, getTenantUser, exchangeToken };
|
|
107
|
+
return { enabled, getServiceToken, callService, getUserProfile, getTenantUser, getTenantList, registerApp, getTenantSnapshot, getTenantMembers, exchangeToken };
|
|
91
108
|
};
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|