@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.
@@ -2,8 +2,9 @@ const fp = require('fastify-plugin');
2
2
  const httpErrors = require('http-errors');
3
3
  const { pick } = require('lodash');
4
4
  const { createError } = require('../utils/intl');
5
+ const { collectTenantImages } = require('../utils/tenant-images');
5
6
 
6
- const { NotFound } = httpErrors;
7
+ const { NotFound, Forbidden } = httpErrors;
7
8
 
8
9
  const PROFILE_FIELDS = ['id', 'nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description', 'status'];
9
10
 
@@ -14,32 +15,39 @@ module.exports = fp(async (fastify, options) => {
14
15
  if (!options.runtime.idpEnabled) {
15
16
  return;
16
17
  }
17
- const { authenticate, translator } = fastify[options.name];
18
+ const { authenticate, translator, services } = fastify[options.name];
18
19
  const { wrap } = translator;
19
20
  const getIdp = () => fastify[options.name].idp;
20
21
  const tags = ['OIDC 服务接口'];
21
22
 
22
- // avatar 是主项目文件库的 id,子项目无法解析,额外给出可直接下载的地址
23
- const resolveAvatarUrl = async avatar => {
24
- if (!avatar) {
23
+ // 头像、租户 logo 是主项目文件库的 id,子项目无法解析,额外给出可直接下载的地址
24
+ const resolveFileUrl = async fileId => {
25
+ if (!fileId) {
25
26
  return null;
26
27
  }
27
- if (/^https?:\/\//.test(avatar)) {
28
- return avatar;
28
+ if (/^https?:\/\//.test(fileId)) {
29
+ return fileId;
29
30
  }
30
31
  const getFileUrl = fastify[options.fileNamespace]?.services?.getFileUrl;
31
32
  if (typeof getFileUrl !== 'function') {
32
33
  return null;
33
34
  }
34
35
  try {
35
- const url = await getFileUrl({ id: avatar });
36
+ const url = await getFileUrl({ id: fileId });
36
37
  return url ? new URL(url, options.runtime.origin).href : null;
37
38
  } catch (e) {
38
- fastify.log.warn({ err: e, avatar }, 'fastify-oidc: 解析用户头像地址失败');
39
+ fastify.log.warn({ err: e, fileId }, 'fastify-oidc: 解析主项目文件地址失败');
39
40
  return null;
40
41
  }
41
42
  };
42
43
 
44
+ // { 宿主文件 id: 可下载地址 },解析不到的不返回
45
+ const resolveFileUrls = async fileIds => {
46
+ const ids = [...new Set(fileIds.filter(Boolean))];
47
+ const urls = await Promise.all(ids.map(resolveFileUrl));
48
+ return Object.fromEntries(ids.map((id, index) => [id, urls[index]]).filter(([, url]) => url));
49
+ };
50
+
43
51
  fastify.get(
44
52
  `${options.prefix}/service/user`,
45
53
  {
@@ -54,12 +62,35 @@ module.exports = fp(async (fastify, options) => {
54
62
  }
55
63
  return Object.assign(pick(user, PROFILE_FIELDS), {
56
64
  id: String(user.id),
57
- avatarUrl: await resolveAvatarUrl(user.avatar),
65
+ avatarUrl: await resolveFileUrl(user.avatar),
58
66
  isSuperAdmin: await identity.isSuperAdmin(user.id)
59
67
  });
60
68
  })
61
69
  );
62
70
 
71
+ const assertTenantEnabled = () => {
72
+ if (!getIdp().identity.tenantEnabled()) {
73
+ throw createError(NotFound, 'tenantNotEnabled');
74
+ }
75
+ };
76
+
77
+ // 只能以注册该应用的服务 client 身份读取应用相关数据
78
+ const resolveApp = async (request, code) => {
79
+ if (!code) {
80
+ return null;
81
+ }
82
+ const app = await services.app.getByCode(code);
83
+ if (!app) {
84
+ throw createError(NotFound, 'appNotFound');
85
+ }
86
+ if (app.serviceClientId !== request.user.clientId) {
87
+ throw createError(Forbidden, 'appClientMismatch', { code });
88
+ }
89
+ return app;
90
+ };
91
+
92
+ const appQuery = { app: { type: 'string', description: '子应用 code,传入后只返回已开通该应用的数据,权限去掉 apps:<code>: 前缀' } };
93
+
63
94
  fastify.get(
64
95
  `${options.prefix}/service/tenant-user`,
65
96
  {
@@ -67,19 +98,111 @@ module.exports = fp(async (fastify, options) => {
67
98
  schema: {
68
99
  tags,
69
100
  summary: '获取用户在租户内的身份、角色与权限',
70
- query: { type: 'object', required: ['userId', 'tenantId'], properties: { userId: { type: 'string' }, tenantId: { type: 'string' } } }
101
+ query: { type: 'object', required: ['userId', 'tenantId'], properties: Object.assign({ userId: { type: 'string' }, tenantId: { type: 'string' } }, appQuery) }
71
102
  }
72
103
  },
73
104
  wrap(async request => {
74
- const tenant = fastify[options.tenantNamespace];
75
- if (!tenant) {
76
- throw createError(NotFound, 'tenantNotEnabled');
77
- }
105
+ assertTenantEnabled();
78
106
  const { userId, tenantId } = request.query;
79
- if (!(await getIdp().identity.isTenantMember(userId, tenantId))) {
80
- throw createError(NotFound, 'tenantMemberNotFound');
107
+ const app = await resolveApp(request, request.query.app);
108
+ const { identity } = getIdp();
109
+ if (app && app.status !== 'open') {
110
+ throw createError(NotFound, 'appNotEnabled');
111
+ }
112
+ if (!(await identity.isTenantMember(userId, tenantId, { appCode: app?.code }))) {
113
+ throw createError(NotFound, app ? 'appNotEnabled' : 'tenantMemberNotFound');
114
+ }
115
+ return identity.getTenantUserInfo({ accountId: userId, tenantId, appCode: app?.code });
116
+ })
117
+ );
118
+
119
+ fastify.get(
120
+ `${options.prefix}/service/tenant-list`,
121
+ {
122
+ onRequest: [authenticate.client('tenant:read')],
123
+ schema: { tags, summary: '用户可用租户列表', query: { type: 'object', required: ['userId'], properties: Object.assign({ userId: { type: 'string' } }, appQuery) } }
124
+ },
125
+ wrap(async request => {
126
+ assertTenantEnabled();
127
+ const app = await resolveApp(request, request.query.app);
128
+ if (app && app.status !== 'open') {
129
+ return { list: [], defaultTenantId: null };
130
+ }
131
+ return getIdp().identity.listTenants(request.query.userId, { appCode: app?.code });
132
+ })
133
+ );
134
+
135
+ fastify.post(
136
+ `${options.prefix}/service/app/register`,
137
+ {
138
+ onRequest: [authenticate.client('app:register')],
139
+ schema: {
140
+ tags,
141
+ summary: '子应用注册权限树到应用中心',
142
+ body: {
143
+ type: 'object',
144
+ required: ['code'],
145
+ properties: {
146
+ code: { type: 'string' },
147
+ name: { type: 'string' },
148
+ description: { type: 'string' },
149
+ tenantMode: { type: 'string', enum: ['client', 'independent'] },
150
+ clientId: { type: 'string' },
151
+ resource: { type: 'string' },
152
+ permissions: { type: 'object', additionalProperties: true },
153
+ tenantSyncUri: { type: 'string' }
154
+ }
155
+ }
156
+ }
157
+ },
158
+ wrap(async request => services.app.register(Object.assign({}, request.body, { serviceClientId: request.user.clientId })))
159
+ );
160
+
161
+ fastify.get(
162
+ `${options.prefix}/service/tenant-snapshot`,
163
+ {
164
+ onRequest: [authenticate.client('tenant:sync')],
165
+ schema: {
166
+ tags,
167
+ summary: '租户快照(基本信息、租户权限、角色、组织),供 independent 子应用接管',
168
+ query: { type: 'object', required: ['tenantId', 'app'], properties: Object.assign({ tenantId: { type: 'string' } }, appQuery) }
169
+ }
170
+ },
171
+ wrap(async request => {
172
+ assertTenantEnabled();
173
+ const app = await resolveApp(request, request.query.app);
174
+ const snapshot = await getIdp().identity.getTenantSnapshot({ tenantId: request.query.tenantId, appCode: app.code, appOpen: app.status === 'open' });
175
+ if (!snapshot.removed) {
176
+ snapshot.fileUrls = await resolveFileUrls(collectTenantImages(snapshot.tenant));
177
+ }
178
+ return snapshot;
179
+ })
180
+ );
181
+
182
+ fastify.get(
183
+ `${options.prefix}/service/tenant-members`,
184
+ {
185
+ onRequest: [authenticate.client('tenant:sync')],
186
+ schema: {
187
+ tags,
188
+ summary: '租户成员分页(含角色 code 与所属组织),供 independent 子应用接管',
189
+ query: {
190
+ type: 'object',
191
+ required: ['tenantId', 'app'],
192
+ properties: Object.assign({ tenantId: { type: 'string' }, currentPage: { type: 'number', default: 1 }, perPage: { type: 'number', default: 200, maximum: 1000 } }, appQuery)
193
+ }
194
+ }
195
+ },
196
+ wrap(async request => {
197
+ assertTenantEnabled();
198
+ const app = await resolveApp(request, request.query.app);
199
+ const { identity } = getIdp();
200
+ const { tenantId, currentPage, perPage } = request.query;
201
+ if (app.status !== 'open' || !(await identity.isAppEnabled(tenantId, app.code))) {
202
+ return { pageData: [], totalCount: 0 };
81
203
  }
82
- return tenant.services.user.getTenantUserInfo({ id: userId, tenantId });
204
+ const result = await identity.listTenantMembers({ tenantId, currentPage, perPage });
205
+ return Object.assign(result, { fileUrls: await resolveFileUrls(result.pageData.map(member => member.avatar)) });
83
206
  })
84
207
  );
85
208
  });
@@ -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,29 +68,36 @@ 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
  }
90
+ // 请求的租户无效(如子应用误传本地租户 id)但只有一个可用租户时直接进入,没得选就不弹选择页
91
+ const { list } = await identity.listTenants(accountId, scope);
92
+ if (list.length === 1) {
93
+ return select(list[0].tenantId);
94
+ }
88
95
  return interactionPolicy.Check.REQUEST_PROMPT;
89
96
  }
90
97
  if (currentTenantId) {
91
98
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
92
99
  }
93
- const { list } = await identity.listTenants(accountId);
100
+ const { list } = await identity.listTenants(accountId, scope);
94
101
  if (list.length === 0) {
95
102
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
96
103
  }
@@ -207,7 +214,8 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
207
214
  if (!tenantId && token.sessionUid) {
208
215
  tenantId = (await services.sessionTenant.get({ sessionUid: token.sessionUid }))?.tenantId;
209
216
  }
210
- const tenantContext = await identity.getTenantContext({ accountId, tenantId });
217
+ // 资源属于子应用时:租户未开通该应用则不带租户 claims,权限只下发该应用的并去掉 apps:<code>: 前缀
218
+ const tenantContext = await identity.getTenantContext(Object.assign({ accountId, tenantId }, services.app.scopeOfResource(token.resourceServer?.identifier())));
211
219
  if (tenantContext) {
212
220
  extra[claims.tenantId] = tenantContext.tenantId;
213
221
  extra[claims.tenantUserId] = tenantContext.tenantUserId;