@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.
@@ -0,0 +1,31 @@
1
+ const fp = require('fastify-plugin');
2
+
3
+ /**
4
+ * 宿主租户端:当前租户已开通且启用的子应用。当前租户与 fastify-tenant 的 tenantUser 一致(token 中的租户,否则默认租户)
5
+ */
6
+ module.exports = fp(async (fastify, options) => {
7
+ if (options.runtime.tenantRole !== 'host') {
8
+ return;
9
+ }
10
+ const { authenticate, translator, services } = fastify[options.name];
11
+ const { wrap } = translator;
12
+ const resolveTenantUser = request => options.getTenant().authenticate.tenantUser(request);
13
+
14
+ fastify.get(
15
+ `${options.prefix}/tenant/apps`,
16
+ {
17
+ onRequest: [authenticate.user, resolveTenantUser],
18
+ schema: { tags: ['OIDC 应用中心'], summary: '当前租户已开通的子应用' }
19
+ },
20
+ wrap(async request => {
21
+ const tenantId = request[options.tenantUserContextName]?.tenantId;
22
+ if (!tenantId) {
23
+ return [];
24
+ }
25
+ const { identity } = fastify[options.name].idp;
26
+ const apps = services.app.listOpen();
27
+ const enabled = await Promise.all(apps.map(app => identity.isAppEnabled(String(tenantId), app.code)));
28
+ return apps.filter((app, index) => enabled[index]).map(({ code, name, description, tenantMode }) => ({ code, name, description, tenantMode }));
29
+ })
30
+ );
31
+ });
@@ -0,0 +1,64 @@
1
+ const fp = require('fastify-plugin');
2
+
3
+ const FORWARD_HEADERS = ['content-type', 'accept', 'accept-language', 'x-app-name'];
4
+
5
+ /**
6
+ * client 子应用的 /api/tenant 代理:getUserInfo、available-list 走服务接口(权限已去前缀、租户已按应用过滤),
7
+ * 其余请求以 token exchange 换成宿主 API 的令牌后转发给宿主 fastify-tenant。只转发 JSON 请求
8
+ */
9
+ module.exports = fp(async (fastify, options) => {
10
+ if (options.runtime.tenantRole !== 'client' || !options.tenantProxy) {
11
+ return;
12
+ }
13
+ const { runtime } = options;
14
+ const { authenticate, serviceClient } = fastify[options.name];
15
+ const proxy = Object.assign({ prefix: '/api/tenant', resource: `${runtime.issuerOrigin}/api`, target: null }, options.tenantProxy === true ? {} : options.tenantProxy);
16
+ const target = proxy.target || `${runtime.issuerOrigin}${proxy.prefix}`;
17
+ const exchanged = new Map();
18
+
19
+ const getHostToken = async subjectToken => {
20
+ const now = Date.now();
21
+ exchanged.forEach((item, key) => item.expiresAt <= now && exchanged.delete(key));
22
+ const cached = exchanged.get(subjectToken);
23
+ if (cached && cached.expiresAt - 30 * 1000 > now) {
24
+ return cached.accessToken;
25
+ }
26
+ const data = await serviceClient.exchangeToken({ subjectToken, resource: proxy.resource });
27
+ exchanged.set(subjectToken, { accessToken: data.access_token, expiresAt: now + data.expires_in * 1000 });
28
+ return data.access_token;
29
+ };
30
+
31
+ // 与 fastify-tenant available-list 同形,前端无需区分
32
+ const toTenantList = ({ list = [], defaultTenantId = null }) => ({
33
+ list: list.map(item => ({
34
+ id: item.tenantUserId,
35
+ tenantId: item.tenantId,
36
+ status: 'open',
37
+ tenant: { id: item.tenantId, name: item.name, logo: item.logo, status: 'open', company: item.companyName ? { name: item.companyName } : null }
38
+ })),
39
+ defaultTenantId
40
+ });
41
+
42
+ fastify.get(`${proxy.prefix}/getUserInfo`, { onRequest: [authenticate.user, authenticate.tenantUser] }, async request => {
43
+ const info = request[options.tenantUserContextName];
44
+ return { userInfo: request.userInfo, tenantUserInfo: info, company: info?.tenant?.tenantCompany || info?.tenant?.company || null, tenant: info?.tenant || null };
45
+ });
46
+
47
+ fastify.get(`${proxy.prefix}/available-list`, { onRequest: [authenticate.user] }, async request => toTenantList(await serviceClient.getTenantList({ userId: request.user.userId })));
48
+
49
+ fastify.all(`${proxy.prefix}/*`, { onRequest: [authenticate.user] }, async (request, reply) => {
50
+ const subjectToken = String(request.headers.authorization || '').replace(/^(bearer|dpop)\s+/i, '');
51
+ const headers = { authorization: `Bearer ${await getHostToken(subjectToken)}` };
52
+ FORWARD_HEADERS.forEach(name => request.headers[name] && (headers[name] = request.headers[name]));
53
+ const url = new URL(`${target}/${request.params['*']}`);
54
+ url.search = new URL(request.raw.url, 'http://localhost').search;
55
+ const hasBody = !['GET', 'HEAD'].includes(request.method) && request.body !== undefined;
56
+ const response = await fetch(url, { method: request.method, headers, body: hasBody ? JSON.stringify(request.body) : undefined });
57
+ reply.code(response.status);
58
+ const contentType = response.headers.get('content-type');
59
+ if (contentType) {
60
+ reply.header('content-type', contentType);
61
+ }
62
+ return reply.send(Buffer.from(await response.arrayBuffer()));
63
+ });
64
+ });
@@ -0,0 +1,59 @@
1
+ const fp = require('fastify-plugin');
2
+ const httpErrors = require('http-errors');
3
+ const { createError } = require('../utils/intl');
4
+
5
+ const { BadRequest } = httpErrors;
6
+
7
+ /**
8
+ * independent 子应用接收宿主的租户变更通知:验签 + jti 防重放后后台回拉快照,立即返回
9
+ */
10
+ module.exports = fp(async (fastify, options) => {
11
+ if (options.runtime.tenantRole !== 'independent') {
12
+ return;
13
+ }
14
+ const { verifier, tenantSync, translator } = fastify[options.name];
15
+ const usedJti = new Map();
16
+
17
+ const consumeJti = (jti, exp) => {
18
+ const now = Date.now();
19
+ usedJti.forEach((expiresAt, key) => expiresAt < now && usedJti.delete(key));
20
+ if (usedJti.has(jti)) {
21
+ return false;
22
+ }
23
+ usedJti.set(jti, exp * 1000 + options.clockTolerance * 1000);
24
+ return true;
25
+ };
26
+
27
+ fastify.register(async child => {
28
+ if (!child.hasContentTypeParser('application/x-www-form-urlencoded')) {
29
+ child.addContentTypeParser('application/x-www-form-urlencoded', { parseAs: 'string' }, (request, body, done) => {
30
+ done(null, Object.fromEntries(new URLSearchParams(body)));
31
+ });
32
+ }
33
+
34
+ child.post(
35
+ `${options.prefix}/tenant-sync`,
36
+ {
37
+ schema: {
38
+ tags: ['OIDC 服务接口'],
39
+ summary: '接收宿主租户变更通知(independent 子应用)',
40
+ body: { type: 'object', required: ['tenant_sync_token'], properties: { tenant_sync_token: { type: 'string' } } }
41
+ }
42
+ },
43
+ translator.wrap(async (request, reply) => {
44
+ let payload;
45
+ try {
46
+ payload = await verifier.verifyTenantSyncToken(request.body.tenant_sync_token, { audience: options.serviceClient.clientId });
47
+ } catch (e) {
48
+ throw createError(BadRequest, 'tenantSyncTokenInvalid');
49
+ }
50
+ if (!consumeJti(payload.jti, payload.exp)) {
51
+ throw createError(BadRequest, 'tenantSyncTokenReplayed');
52
+ }
53
+ tenantSync.syncInBackground(payload.tenant_id);
54
+ reply.header('cache-control', 'no-store');
55
+ return {};
56
+ })
57
+ );
58
+ });
59
+ });
@@ -3,8 +3,13 @@ const epochTime = date => Math.floor(date.getTime() / 1000);
3
3
  /**
4
4
  * 基于 fastify-sequelize 的 oidc-provider Adapter。
5
5
  * Client 不走这里,由 create-provider 中的 client adapter 从 client 表读取。
6
+ *
7
+ * 退出时 end_session 要先等 back-channel 通知完才销毁 Session,期间同一 cookie 的并发请求(如子应用 401 后静默登录)
8
+ * 已读到旧 Session,会在销毁后把它原样写回;这里记下已销毁的 Session id,拒绝写回与读取。
6
9
  */
7
- module.exports = ({ models }) => {
10
+ module.exports = ({ models, endedStore, sessionTTL = 0 }) => {
11
+ const endedKey = id => `session-ended:${id}`;
12
+ const isEnded = async (name, id) => name === 'Session' && !!endedStore && !!(await endedStore.get(endedKey(id)));
8
13
  const toPayload = row => {
9
14
  if (!row) {
10
15
  return undefined;
@@ -25,6 +30,9 @@ module.exports = ({ models }) => {
25
30
  }
26
31
 
27
32
  async upsert(id, payload, expiresIn) {
33
+ if (await isEnded(this.name, id)) {
34
+ return;
35
+ }
28
36
  const values = {
29
37
  payload,
30
38
  grantId: payload.grantId || null,
@@ -43,6 +51,9 @@ module.exports = ({ models }) => {
43
51
  }
44
52
 
45
53
  async find(id) {
54
+ if (await isEnded(this.name, id)) {
55
+ return undefined;
56
+ }
46
57
  return toPayload(await models.payload.findOne({ where: { modelName: this.name, payloadId: id } }));
47
58
  }
48
59
 
@@ -59,6 +70,13 @@ module.exports = ({ models }) => {
59
70
  }
60
71
 
61
72
  async destroy(id) {
73
+ if (this.name === 'Session' && endedStore) {
74
+ const row = await models.payload.findOne({ attributes: ['expiresAt'], where: { modelName: this.name, payloadId: id } });
75
+ const ttl = row?.expiresAt ? Math.ceil((row.expiresAt.getTime() - Date.now()) / 1000) : sessionTTL;
76
+ if (ttl > 0) {
77
+ await endedStore.set(endedKey(id), 1, ttl);
78
+ }
79
+ }
62
80
  await models.payload.destroy({ where: { modelName: this.name, payloadId: id } });
63
81
  }
64
82
 
@@ -68,21 +68,23 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
68
68
  const sessionUid = oidc.session.uid;
69
69
  const requested = oidc.params.tenant_id ? String(oidc.params.tenant_id) : null;
70
70
  const chosen = oidc.result?.tenant?.tenantId ? String(oidc.result.tenant.tenantId) : null;
71
+ // 子应用的 client 只考虑已开通该应用的租户
72
+ const scope = services.app.scopeOfClient(oidc.client.clientId);
71
73
  const select = async tenantId => {
72
74
  await services.sessionTenant.set({ sessionUid, accountId, tenantId });
73
75
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
74
76
  };
75
77
 
76
- if (chosen && (await identity.isTenantMember(accountId, chosen))) {
78
+ if (chosen && (await identity.isTenantMember(accountId, chosen, scope))) {
77
79
  return select(chosen);
78
80
  }
79
81
  const current = await services.sessionTenant.get({ sessionUid });
80
- const currentTenantId = current && current.accountId === String(accountId) && (await identity.isTenantMember(accountId, current.tenantId)) ? current.tenantId : null;
82
+ const currentTenantId = current && current.accountId === String(accountId) && (await identity.isTenantMember(accountId, current.tenantId, scope)) ? current.tenantId : null;
81
83
  if (requested) {
82
84
  if (requested === currentTenantId) {
83
85
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
84
86
  }
85
- if (await identity.isTenantMember(accountId, requested)) {
87
+ if (await identity.isTenantMember(accountId, requested, scope)) {
86
88
  return select(requested);
87
89
  }
88
90
  return interactionPolicy.Check.REQUEST_PROMPT;
@@ -90,7 +92,7 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
90
92
  if (currentTenantId) {
91
93
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
92
94
  }
93
- const { list } = await identity.listTenants(accountId);
95
+ const { list } = await identity.listTenants(accountId, scope);
94
96
  if (list.length === 0) {
95
97
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
96
98
  }
@@ -207,7 +209,8 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
207
209
  if (!tenantId && token.sessionUid) {
208
210
  tenantId = (await services.sessionTenant.get({ sessionUid: token.sessionUid }))?.tenantId;
209
211
  }
210
- const tenantContext = await identity.getTenantContext({ accountId, tenantId });
212
+ // 资源属于子应用时:租户未开通该应用则不带租户 claims,权限只下发该应用的并去掉 apps:<code>: 前缀
213
+ const tenantContext = await identity.getTenantContext(Object.assign({ accountId, tenantId }, services.app.scopeOfResource(token.resourceServer?.identifier())));
211
214
  if (tenantContext) {
212
215
  extra[claims.tenantId] = tenantContext.tenantId;
213
216
  extra[claims.tenantUserId] = tenantContext.tenantUserId;
@@ -1,6 +1,12 @@
1
+ const { scopePermissions, isAppEnabledIn } = require('../utils/app-permissions');
2
+ const { COMPANY_FIELDS } = require('../utils/tenant-images');
3
+
1
4
  const ACTIVE_USER_STATUS = [0, 1];
5
+ const SNAPSHOT_TENANT_FIELDS = ['themeColor', 'description', 'accountCount', 'supportLanguage', 'defaultLanguage', 'serviceStartTime', 'serviceEndTime'];
2
6
 
3
7
  const plain = item => (item && typeof item.get === 'function' ? item.get({ plain: true }) : item);
8
+ const pickFields = (item, fields) => Object.fromEntries(fields.filter(key => item[key] !== undefined).map(key => [key, item[key]]));
9
+ const toOrgIds = member => (Array.isArray(member.tenantOrgIds) ? member.tenantOrgIds : member.tenantOrgId ? [member.tenantOrgId] : []).map(String);
4
10
 
5
11
  /**
6
12
  * oidc-provider 与 kne 包之间的唯一桥接层:
@@ -14,10 +20,23 @@ module.exports = ({ fastify, options }) => {
14
20
  }
15
21
  return ns;
16
22
  };
17
- const tenant = () => fastify[options.tenantNamespace];
23
+ const tenant = () => options.getTenant();
24
+ const prefix = options.appPermissionPrefix;
18
25
 
19
26
  const tenantEnabled = () => !!tenant();
20
27
 
28
+ const getTenantPermissionCodes = async tenantId => {
29
+ try {
30
+ return (await tenant().services.permission.list({ tenantId })).codes || [];
31
+ } catch (e) {
32
+ return [];
33
+ }
34
+ };
35
+
36
+ const isAppEnabled = async (tenantId, appCode) => isAppEnabledIn(await getTenantPermissionCodes(tenantId), appCode, prefix);
37
+
38
+ const scopeAppPermissions = (permissions, appCode) => scopePermissions(permissions, appCode, prefix);
39
+
21
40
  const getUser = async id => {
22
41
  try {
23
42
  return await account().services.user.getUser({ id });
@@ -70,33 +89,51 @@ module.exports = ({ fastify, options }) => {
70
89
  return services.account.verifyCredentials(credentials);
71
90
  };
72
91
 
73
- const listTenants = async accountId => {
74
- if (!tenantEnabled()) {
92
+ // appCode:只保留已开通该子应用的租户;appOpen=false(应用已停用 / 删除)时没有可用租户
93
+ const listTenants = async (accountId, { appCode, appOpen = true } = {}) => {
94
+ if (!tenantEnabled() || (appCode && !appOpen)) {
75
95
  return { list: [], defaultTenantId: null };
76
96
  }
77
97
  const { list, defaultTenantId } = await tenant().services.user.tenantList({ id: accountId });
98
+ let result = list
99
+ .map(plain)
100
+ .filter(item => item.status === 'open' && (!item.tenant || item.tenant.status === 'open'))
101
+ .map(item => ({
102
+ tenantId: String(item.tenantId),
103
+ tenantUserId: String(item.id),
104
+ name: item.tenant?.name,
105
+ logo: item.tenant?.logo,
106
+ companyName: item.tenant?.company?.name
107
+ }));
108
+ if (appCode) {
109
+ const enabled = await Promise.all(result.map(item => isAppEnabled(item.tenantId, appCode)));
110
+ result = result.filter((item, index) => enabled[index]);
111
+ }
112
+ const normalizedDefault = defaultTenantId ? String(defaultTenantId) : null;
78
113
  return {
79
- list: list
80
- .map(plain)
81
- .filter(item => item.status === 'open' && (!item.tenant || item.tenant.status === 'open'))
82
- .map(item => ({
83
- tenantId: String(item.tenantId),
84
- tenantUserId: String(item.id),
85
- name: item.tenant?.name,
86
- logo: item.tenant?.logo,
87
- companyName: item.tenant?.company?.name
88
- })),
89
- defaultTenantId: defaultTenantId ? String(defaultTenantId) : null
114
+ list: result,
115
+ defaultTenantId: result.some(item => item.tenantId === normalizedDefault) ? normalizedDefault : result[0]?.tenantId || null
90
116
  };
91
117
  };
92
118
 
93
- const isTenantMember = async (accountId, tenantId) => {
94
- const { list } = await listTenants(accountId);
119
+ const isTenantMember = async (accountId, tenantId, scope = {}) => {
120
+ const { list } = await listTenants(accountId, scope);
95
121
  return list.some(item => item.tenantId === String(tenantId));
96
122
  };
97
123
 
98
- const getTenantContext = async ({ accountId, tenantId }) => {
99
- if (!tenantEnabled() || !tenantId) {
124
+ const getTenantUserInfo = async ({ accountId, tenantId, appCode }) => {
125
+ const info = plain(await tenant().services.user.getTenantUserInfo({ id: accountId, tenantId }));
126
+ if (!appCode) {
127
+ return info;
128
+ }
129
+ return Object.assign({}, info, { permissions: scopeAppPermissions(info.permissions, appCode) });
130
+ };
131
+
132
+ const getTenantContext = async ({ accountId, tenantId, appCode, appOpen = true }) => {
133
+ if (!tenantEnabled() || !tenantId || (appCode && !appOpen)) {
134
+ return null;
135
+ }
136
+ if (appCode && !(await isAppEnabled(tenantId, appCode))) {
100
137
  return null;
101
138
  }
102
139
  let info;
@@ -112,9 +149,103 @@ module.exports = ({ fastify, options }) => {
112
149
  tenantId: String(info.tenantId),
113
150
  tenantUserId: String(info.id),
114
151
  roles: (info.roleDetails || []).map(role => role.code || String(role.id)).filter(Boolean),
115
- permissions: info.permissions || []
152
+ permissions: appCode ? scopeAppPermissions(info.permissions, appCode) : info.permissions || []
153
+ };
154
+ };
155
+
156
+ // independent 子应用回拉的租户快照,id 均为宿主侧 id,权限已按应用去前缀;成员另走分页接口
157
+ const getTenantSnapshot = async ({ tenantId, appCode, appOpen = true }) => {
158
+ const { models, services } = tenant();
159
+ // 宿主已删除该租户:返回 removed,子应用据此关闭托管租户(否则回拉一直失败,托管租户停在 open)
160
+ if (!(await models.tenant.findByPk(tenantId))) {
161
+ return { tenant: { id: String(tenantId), status: 'closed' }, enabled: false, removed: true, permissions: [], roles: [], orgs: [] };
162
+ }
163
+ const hostTenant = plain(await services.tenant.detail({ id: tenantId, withTenantSetting: false }));
164
+ const codes = await getTenantPermissionCodes(tenantId);
165
+ const enabled = appOpen && isAppEnabledIn(codes, appCode, prefix);
166
+ const snapshot = {
167
+ tenant: Object.assign(pickFields(hostTenant, SNAPSHOT_TENANT_FIELDS), {
168
+ id: String(hostTenant.id),
169
+ name: hostTenant.name,
170
+ status: hostTenant.status,
171
+ logo: hostTenant.logo || null,
172
+ companyName: hostTenant.tenantCompany?.name || hostTenant.company?.name,
173
+ company: pickFields(plain(hostTenant.tenantCompany || hostTenant.company) || {}, COMPANY_FIELDS)
174
+ }),
175
+ enabled,
176
+ permissions: [],
177
+ roles: [],
178
+ orgs: []
179
+ };
180
+ if (!enabled) {
181
+ return snapshot;
182
+ }
183
+ snapshot.permissions = scopeAppPermissions(codes, appCode);
184
+ const roles = await models.role.findAll({ where: { tenantId } });
185
+ snapshot.roles = roles.map(plain).map(role => ({
186
+ id: String(role.id),
187
+ code: role.code || `role-${role.id}`,
188
+ name: role.name,
189
+ description: role.description,
190
+ type: role.type,
191
+ status: role.status,
192
+ permissions: scopeAppPermissions(role.permissions, appCode)
193
+ }));
194
+ const orgs = await models.org.findAll({ where: { tenantId } });
195
+ snapshot.orgs = orgs.map(plain).map(org => ({
196
+ id: String(org.id),
197
+ parentId: org.parentId != null ? String(org.parentId) : null,
198
+ name: org.name,
199
+ description: org.description,
200
+ index: org.index,
201
+ status: org.status,
202
+ leaderTenantUserId: org.leaderUserId != null ? String(org.leaderUserId) : null
203
+ }));
204
+ return snapshot;
205
+ };
206
+
207
+ // 只同步已关联账号的成员(未加入的邀请没有 userId,子应用无法建立镜像用户)
208
+ const listTenantMembers = async ({ tenantId, currentPage = 1, perPage = 200 }) => {
209
+ const { models } = tenant();
210
+ const { Op } = fastify.sequelize.Sequelize;
211
+ const roleCodes = new Map((await models.role.findAll({ where: { tenantId } })).map(plain).map(role => [String(role.id), role.code || `role-${role.id}`]));
212
+ const { rows, count } = await models.user.findAndCountAll({
213
+ where: { tenantId, userId: { [Op.ne]: null } },
214
+ offset: perPage * (currentPage - 1),
215
+ limit: perPage,
216
+ order: [['createdAt', 'ASC']]
217
+ });
218
+ return {
219
+ pageData: rows.map(plain).map(member => ({
220
+ id: String(member.id),
221
+ userId: String(member.userId),
222
+ name: member.name,
223
+ email: member.email,
224
+ phone: member.phone,
225
+ avatar: member.avatar,
226
+ status: member.status,
227
+ roleCodes: (member.roles || []).map(id => roleCodes.get(String(id))).filter(Boolean),
228
+ tenantOrgIds: toOrgIds(member)
229
+ })),
230
+ totalCount: count
116
231
  };
117
232
  };
118
233
 
119
- return { tenantEnabled, getUser, isSuperAdmin, toProfileClaims, findAccount, verifyCredentials, listTenants, isTenantMember, getTenantContext };
234
+ return {
235
+ tenant,
236
+ tenantEnabled,
237
+ getUser,
238
+ isSuperAdmin,
239
+ toProfileClaims,
240
+ findAccount,
241
+ verifyCredentials,
242
+ listTenants,
243
+ isTenantMember,
244
+ getTenantUserInfo,
245
+ getTenantContext,
246
+ isAppEnabled,
247
+ scopePermissions: scopeAppPermissions,
248
+ getTenantSnapshot,
249
+ listTenantMembers
250
+ };
120
251
  };
package/libs/idp/index.js CHANGED
@@ -2,6 +2,7 @@ const { createLocalJWKSet } = require('jose');
2
2
  const createIdentity = require('./identity');
3
3
  const createProvider = require('./create-provider');
4
4
  const createSequelizeAdapter = require('./adapters/sequelize');
5
+ const { createMemoryStore } = require('../resource/revocation');
5
6
 
6
7
  /**
7
8
  * IdP 运行期:持有当前 oidc-provider 实例,负责初始化、密钥轮换后的热替换和定时清理
@@ -75,6 +76,15 @@ module.exports = ({ fastify, options, translator }) => {
75
76
  }
76
77
  };
77
78
 
79
+ // 多实例部署时其他实例注册 / 停用的应用靠周期重载同步到本实例的权限树
80
+ const reloadApps = async () => {
81
+ try {
82
+ await getServices().app.reload();
83
+ } catch (e) {
84
+ fastify.log.warn({ err: e }, 'fastify-oidc: 重载应用中心失败');
85
+ }
86
+ };
87
+
78
88
  const cleanup = async () => {
79
89
  try {
80
90
  const { models } = fastify[options.name];
@@ -99,11 +109,20 @@ module.exports = ({ fastify, options, translator }) => {
99
109
  };
100
110
 
101
111
  const init = async () => {
102
- PayloadAdapter = options.adapter || createSequelizeAdapter({ models: fastify[options.name].models });
112
+ PayloadAdapter =
113
+ options.adapter ||
114
+ createSequelizeAdapter({
115
+ models: fastify[options.name].models,
116
+ endedStore: options.revocationStore || createMemoryStore(),
117
+ sessionTTL: options.ttl.session
118
+ });
103
119
  await getServices().key.ensureKeys();
104
120
  await seed();
121
+ await getServices().app.reload();
122
+ getServices().tenantPush?.start();
105
123
  await build();
106
124
  schedule(reloadIfKeysChanged, options.keyReloadInterval);
125
+ schedule(reloadApps, options.keyReloadInterval);
107
126
  schedule(cleanup, options.cleanupInterval);
108
127
  };
109
128
 
@@ -59,5 +59,13 @@ module.exports = {
59
59
  subjectTokenAccountInvalid: 'The user of subject_token does not exist or is disabled',
60
60
  logoutPageTitle: 'Log out',
61
61
  logoutConfirm: 'Confirm log out',
62
- logoutSuccess: 'You have been logged out'
62
+ logoutSuccess: 'You have been logged out',
63
+ appNotFound: 'App does not exist',
64
+ appCodeInvalid: 'App code may only contain letters, digits, underscores and hyphens',
65
+ appTenantModeInvalid: 'tenantMode must be client or independent',
66
+ appCodeTaken: 'App {code} has been registered by another client',
67
+ appClientMismatch: 'The current client cannot access data of app {code}',
68
+ appNotEnabled: 'The tenant has not enabled this app or the app is disabled',
69
+ tenantSyncTokenInvalid: 'tenant_sync_token is invalid or expired',
70
+ tenantSyncTokenReplayed: 'tenant_sync_token has already been used'
63
71
  };
@@ -59,5 +59,13 @@ module.exports = {
59
59
  subjectTokenAccountInvalid: 'subject_token 对应的用户不存在或已被禁用',
60
60
  logoutPageTitle: '退出登录',
61
61
  logoutConfirm: '确认退出',
62
- logoutSuccess: '已退出登录'
62
+ logoutSuccess: '已退出登录',
63
+ appNotFound: '子应用不存在',
64
+ appCodeInvalid: '应用 code 只能包含字母、数字、下划线和中划线',
65
+ appTenantModeInvalid: 'tenantMode 只能是 client 或 independent',
66
+ appCodeTaken: '应用 {code} 已由其他 client 注册',
67
+ appClientMismatch: '当前 client 无权访问应用 {code} 的数据',
68
+ appNotEnabled: '租户未开通该应用或应用已停用',
69
+ tenantSyncTokenInvalid: 'tenant_sync_token 无效或已过期',
70
+ tenantSyncTokenReplayed: 'tenant_sync_token 已被使用'
63
71
  };
@@ -0,0 +1,65 @@
1
+ module.exports = ({ DataTypes }) => {
2
+ return {
3
+ model: {
4
+ code: {
5
+ type: DataTypes.STRING(64),
6
+ allowNull: false,
7
+ comment: '应用编码,宿主权限 code 前缀 apps:<code>'
8
+ },
9
+ name: {
10
+ type: DataTypes.STRING(255),
11
+ comment: '应用名称'
12
+ },
13
+ description: {
14
+ type: DataTypes.TEXT,
15
+ comment: '描述'
16
+ },
17
+ tenantMode: {
18
+ type: DataTypes.STRING(16),
19
+ allowNull: false,
20
+ defaultValue: 'client',
21
+ comment: 'client: 租户由宿主提供, independent: 子应用本地租户,宿主同步的租户由宿主接管'
22
+ },
23
+ serviceClientId: {
24
+ type: DataTypes.STRING(255),
25
+ allowNull: false,
26
+ comment: '首次注册的服务 client_id,其他 client 不能覆盖该应用'
27
+ },
28
+ clientIds: {
29
+ type: DataTypes.JSON,
30
+ comment: '子应用登录用的 client_id 列表,用于交互与签发 token 时识别应用'
31
+ },
32
+ resource: {
33
+ type: DataTypes.STRING(255),
34
+ comment: '子应用资源服务 identifier(access_token 的 aud)'
35
+ },
36
+ permissions: {
37
+ type: DataTypes.JSON,
38
+ comment: '子应用权限树(不含 apps 前缀)'
39
+ },
40
+ permissionsHash: {
41
+ type: DataTypes.STRING(64),
42
+ comment: '权限树摘要'
43
+ },
44
+ tenantSyncUri: {
45
+ type: DataTypes.STRING(1024),
46
+ comment: 'independent 模式接收租户变更通知的地址'
47
+ },
48
+ registeredAt: {
49
+ type: DataTypes.DATE,
50
+ comment: '最近一次注册时间'
51
+ },
52
+ status: {
53
+ type: DataTypes.STRING(16),
54
+ allowNull: false,
55
+ defaultValue: 'open',
56
+ comment: 'open: 启用, closed: 停用, removed: 已删除(子应用重新注册时恢复)'
57
+ }
58
+ },
59
+ options: {
60
+ comment: 'OIDC 子应用(应用中心)',
61
+ paranoid: false,
62
+ indexes: [{ fields: ['code'], unique: true }]
63
+ }
64
+ };
65
+ };