@kne/fastify-oidc 0.0.0-stage → 0.1.0

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.
Files changed (38) hide show
  1. package/README.md +681 -2
  2. package/index.js +146 -0
  3. package/libs/controllers/admin.js +150 -0
  4. package/libs/controllers/backchannel.js +49 -0
  5. package/libs/controllers/interaction.js +87 -0
  6. package/libs/controllers/service.js +59 -0
  7. package/libs/idp/adapters/sequelize.js +82 -0
  8. package/libs/idp/create-provider.js +286 -0
  9. package/libs/idp/grant-helpers.js +31 -0
  10. package/libs/idp/grants/token-exchange.js +82 -0
  11. package/libs/idp/identity.js +108 -0
  12. package/libs/idp/index.js +123 -0
  13. package/libs/idp/mount.js +26 -0
  14. package/libs/locale/en-US.js +63 -0
  15. package/libs/locale/index.js +4 -0
  16. package/libs/locale/zh-CN.js +63 -0
  17. package/libs/models/client.js +43 -0
  18. package/libs/models/key.js +44 -0
  19. package/libs/models/payload.js +50 -0
  20. package/libs/models/resource-server.js +42 -0
  21. package/libs/models/session-tenant.js +26 -0
  22. package/libs/resource/authenticate.js +203 -0
  23. package/libs/resource/dpop.js +52 -0
  24. package/libs/resource/normalize-user.js +42 -0
  25. package/libs/resource/revocation.js +62 -0
  26. package/libs/resource/service-client.js +91 -0
  27. package/libs/resource/user-mirror.js +60 -0
  28. package/libs/resource/verify-token.js +51 -0
  29. package/libs/services/client.js +167 -0
  30. package/libs/services/grant.js +104 -0
  31. package/libs/services/interaction.js +118 -0
  32. package/libs/services/key.js +103 -0
  33. package/libs/services/resource-server.js +99 -0
  34. package/libs/services/session-tenant.js +32 -0
  35. package/libs/utils/crypto.js +25 -0
  36. package/libs/utils/intl.js +71 -0
  37. package/libs/utils/resolve-options.js +68 -0
  38. package/package.json +83 -4
@@ -0,0 +1,286 @@
1
+ const { deriveKey } = require('../utils/crypto');
2
+ const { fillGrantFromRequest } = require('./grant-helpers');
3
+ const tokenExchange = require('./grants/token-exchange');
4
+
5
+ const instantiate = (Adapter, name) => (Adapter.prototype ? new Adapter(name) : Adapter(name));
6
+
7
+ const escapeHtml = value => String(value).replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
8
+
9
+ /**
10
+ * 生成 oidc-provider 实例。每次密钥轮换后会重新调用本方法得到新实例。
11
+ */
12
+ module.exports = async ({ fastify, options, identity, translator, jwks, getLocalJWKS, PayloadAdapter }) => {
13
+ const { default: Provider, interactionPolicy, errors } = await import('oidc-provider');
14
+ const { services } = fastify[options.name];
15
+ const { runtime } = options;
16
+ const { claims } = runtime;
17
+ const t = (ctx, messageId, messageValues) => translator.t(ctx?.req?.kneOidcLocale, messageId, messageValues);
18
+
19
+ const clientAdapter = {
20
+ find: id => services.client.findForProvider(id),
21
+ upsert: async () => {
22
+ throw new Error('client 由 fastify-oidc 管理接口维护,不支持动态注册');
23
+ },
24
+ destroy: async () => {}
25
+ };
26
+ const adapters = new Map();
27
+ const getAdapter = name => {
28
+ if (name === 'Client') {
29
+ return clientAdapter;
30
+ }
31
+ if (!adapters.has(name)) {
32
+ adapters.set(name, instantiate(PayloadAdapter, name));
33
+ }
34
+ return adapters.get(name);
35
+ };
36
+
37
+ const resourceIncludePermissions = new Map();
38
+ const includePermissions = resourceServer => {
39
+ const value = resourceServer && resourceIncludePermissions.get(resourceServer.identifier());
40
+ return typeof value === 'boolean' ? value : options.includePermissions;
41
+ };
42
+
43
+ const getResourceServerInfo = async (ctx, indicator, client) => {
44
+ const allowed = client.allowed_resources || [];
45
+ if (!allowed.includes(indicator)) {
46
+ throw new errors.InvalidTarget(await t(ctx, 'resourceForbidden', { clientId: client.clientId, resource: indicator }));
47
+ }
48
+ const resourceServer = await services.resourceServer.findByIdentifier(indicator);
49
+ if (!resourceServer) {
50
+ throw new errors.InvalidTarget(await t(ctx, 'resourceUnavailable', { resource: indicator }));
51
+ }
52
+ resourceIncludePermissions.set(indicator, resourceServer.includePermissions);
53
+ return {
54
+ scope: resourceServer.scope || options.defaultResourceScope,
55
+ audience: resourceServer.identifier,
56
+ accessTokenTTL: resourceServer.accessTokenTTL || options.ttl.accessToken,
57
+ accessTokenFormat: 'jwt',
58
+ jwt: { sign: { alg: 'RS256' } }
59
+ };
60
+ };
61
+
62
+ const tenantCheck = new interactionPolicy.Check('tenant_required', '需要选择租户', async ctx => {
63
+ const { oidc } = ctx;
64
+ const accountId = oidc.session.accountId;
65
+ if (!accountId || !identity.tenantEnabled()) {
66
+ return interactionPolicy.Check.NO_NEED_TO_PROMPT;
67
+ }
68
+ const sessionUid = oidc.session.uid;
69
+ const requested = oidc.params.tenant_id ? String(oidc.params.tenant_id) : null;
70
+ const chosen = oidc.result?.tenant?.tenantId ? String(oidc.result.tenant.tenantId) : null;
71
+ const select = async tenantId => {
72
+ await services.sessionTenant.set({ sessionUid, accountId, tenantId });
73
+ return interactionPolicy.Check.NO_NEED_TO_PROMPT;
74
+ };
75
+
76
+ if (chosen && (await identity.isTenantMember(accountId, chosen))) {
77
+ return select(chosen);
78
+ }
79
+ const current = await services.sessionTenant.get({ sessionUid });
80
+ const currentTenantId = current && current.accountId === String(accountId) && (await identity.isTenantMember(accountId, current.tenantId)) ? current.tenantId : null;
81
+ if (requested) {
82
+ if (requested === currentTenantId) {
83
+ return interactionPolicy.Check.NO_NEED_TO_PROMPT;
84
+ }
85
+ if (await identity.isTenantMember(accountId, requested)) {
86
+ return select(requested);
87
+ }
88
+ return interactionPolicy.Check.REQUEST_PROMPT;
89
+ }
90
+ if (currentTenantId) {
91
+ return interactionPolicy.Check.NO_NEED_TO_PROMPT;
92
+ }
93
+ const { list } = await identity.listTenants(accountId);
94
+ if (list.length === 0) {
95
+ return interactionPolicy.Check.NO_NEED_TO_PROMPT;
96
+ }
97
+ if (list.length === 1) {
98
+ return select(list[0].tenantId);
99
+ }
100
+ return interactionPolicy.Check.REQUEST_PROMPT;
101
+ });
102
+
103
+ const policy = interactionPolicy.base();
104
+ policy.add(new interactionPolicy.Prompt({ name: 'tenant', requestable: false }, ctx => ({ tenant_id: ctx.oidc.params.tenant_id }), tenantCheck), 1);
105
+
106
+ const ttl = options.ttl;
107
+ const configuration = {
108
+ adapter: getAdapter,
109
+ jwks,
110
+ clockTolerance: options.clockTolerance,
111
+ cookies: {
112
+ keys: [deriveKey(options.cookieSecret || options.keyEncryptionSecret, 'cookie').toString('base64url')]
113
+ },
114
+ claims: {
115
+ openid: ['sub'],
116
+ profile: ['name', 'nickname', 'picture', 'gender', 'birthdate'],
117
+ email: ['email'],
118
+ phone: ['phone_number']
119
+ },
120
+ scopes: ['openid', 'offline_access', 'profile', 'email', 'phone'],
121
+ extraParams: ['tenant_id'],
122
+ extraClientMetadata: {
123
+ properties: ['skip_consent', 'allowed_resources'],
124
+ validator(ctx, key, value) {
125
+ if (key === 'skip_consent' && value !== undefined && typeof value !== 'boolean') {
126
+ throw new errors.InvalidClientMetadata('skip_consent 必须是布尔值');
127
+ }
128
+ if (key === 'allowed_resources' && value !== undefined && !(Array.isArray(value) && value.every(item => typeof item === 'string'))) {
129
+ throw new errors.InvalidClientMetadata('allowed_resources 必须是字符串数组');
130
+ }
131
+ }
132
+ },
133
+ features: {
134
+ devInteractions: { enabled: false },
135
+ resourceIndicators: {
136
+ enabled: true,
137
+ defaultResource: async (ctx, client, oneOf) => oneOf || (client.allowed_resources || [])[0],
138
+ useGrantedResource: async () => true,
139
+ getResourceServerInfo
140
+ },
141
+ rpInitiatedLogout: {
142
+ enabled: true,
143
+ logoutSource: async (ctx, form) => {
144
+ const title = escapeHtml(await t(ctx, 'logoutPageTitle'));
145
+ const confirm = escapeHtml(await t(ctx, 'logoutConfirm'));
146
+ ctx.body = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${title}</title></head><body>${form}<input type="hidden" name="logout" value="yes" form="op.logoutForm"/><noscript><button type="submit" form="op.logoutForm">${confirm}</button></noscript><script>document.getElementById('op.logoutForm').submit()</script></body></html>`;
147
+ },
148
+ postLogoutSuccessSource: async ctx => {
149
+ const message = escapeHtml(await t(ctx, 'logoutSuccess'));
150
+ ctx.body = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${message}</title></head><body><p>${message}</p></body></html>`;
151
+ }
152
+ },
153
+ backchannelLogout: { enabled: true },
154
+ clientCredentials: { enabled: true },
155
+ dPoP: { enabled: true },
156
+ revocation: { enabled: true },
157
+ introspection: { enabled: true },
158
+ userinfo: { enabled: true }
159
+ },
160
+ interactions: {
161
+ policy,
162
+ url: async (ctx, interaction) => `${options.prefix}/interaction/${interaction.uid}`
163
+ },
164
+ findAccount: identity.findAccount,
165
+ loadExistingGrant: async ctx => {
166
+ const { oidc } = ctx;
167
+ const grantId = oidc.result?.consent?.grantId || oidc.session.grantIdFor(oidc.client.clientId);
168
+ const existing = grantId && (await oidc.provider.Grant.find(grantId));
169
+ if (existing) {
170
+ if (oidc.client.skip_consent !== false) {
171
+ fillGrantFromRequest(ctx, existing);
172
+ await existing.save();
173
+ }
174
+ return existing;
175
+ }
176
+ if (oidc.client.skip_consent === false) {
177
+ return undefined;
178
+ }
179
+ const grant = new oidc.provider.Grant({ clientId: oidc.client.clientId, accountId: oidc.session.accountId });
180
+ fillGrantFromRequest(ctx, grant);
181
+ await grant.save();
182
+ return grant;
183
+ },
184
+ issueRefreshToken: async (ctx, client) => client.grantTypeAllowed('refresh_token'),
185
+ rotateRefreshToken: () => true,
186
+ extraTokenClaims: async (ctx, token) => {
187
+ if (token.kind === 'ClientCredentials') {
188
+ return { [claims.clientToken]: true };
189
+ }
190
+ const accountId = token.accountId;
191
+ if (!accountId) {
192
+ return undefined;
193
+ }
194
+ const extra = {};
195
+ let sid = token.sid;
196
+ if (!sid && token.sessionUid) {
197
+ const session = await ctx.oidc.provider.Session.findByUid(token.sessionUid);
198
+ sid = session?.sidFor(token.clientId);
199
+ }
200
+ if (sid) {
201
+ extra.sid = sid;
202
+ }
203
+ if (token.kneActor) {
204
+ extra.act = { sub: token.kneActor };
205
+ }
206
+ let tenantId = token.kneTenantId;
207
+ if (!tenantId && token.sessionUid) {
208
+ tenantId = (await services.sessionTenant.get({ sessionUid: token.sessionUid }))?.tenantId;
209
+ }
210
+ const tenantContext = await identity.getTenantContext({ accountId, tenantId });
211
+ if (tenantContext) {
212
+ extra[claims.tenantId] = tenantContext.tenantId;
213
+ extra[claims.tenantUserId] = tenantContext.tenantUserId;
214
+ extra[claims.roles] = tenantContext.roles;
215
+ if (includePermissions(token.resourceServer)) {
216
+ extra[claims.permissions] = tenantContext.permissions;
217
+ }
218
+ }
219
+ return extra;
220
+ },
221
+ ttl: {
222
+ AccessToken: (ctx, token) => token.resourceServer?.accessTokenTTL || ttl.accessToken,
223
+ ClientCredentials: (ctx, token) => token.resourceServer?.accessTokenTTL || ttl.accessToken,
224
+ AuthorizationCode: () => 60,
225
+ IdToken: () => ttl.idToken,
226
+ RefreshToken: () => ttl.refreshToken,
227
+ Interaction: () => ttl.interaction,
228
+ Session: () => ttl.session,
229
+ Grant: () => ttl.grant
230
+ },
231
+ fetch: (url, init) => {
232
+ const { allowPrivateFetch } = options;
233
+ if (allowPrivateFetch === true || (typeof allowPrivateFetch === 'function' && allowPrivateFetch(new URL(url)))) {
234
+ delete init.dispatcher;
235
+ }
236
+ return globalThis.fetch(url, init);
237
+ },
238
+ renderError: async (ctx, out) => {
239
+ ctx.type = 'json';
240
+ ctx.body = out;
241
+ }
242
+ };
243
+
244
+ const provider = new Provider(runtime.issuer, configuration);
245
+ provider.proxy = options.trustProxy;
246
+
247
+ provider.registerGrantType(
248
+ tokenExchange.GRANT_TYPE,
249
+ tokenExchange.createTokenExchangeHandler({
250
+ errors,
251
+ t,
252
+ options,
253
+ identity,
254
+ getResourceServerInfo,
255
+ getLocalJWKS,
256
+ isRevoked: payload => fastify[options.name].revocation.isRevoked(payload)
257
+ }),
258
+ tokenExchange.PARAMETERS
259
+ );
260
+
261
+ provider.on('end_session.success', async ctx => {
262
+ const session = ctx.oidc.session;
263
+ if (!session) {
264
+ return;
265
+ }
266
+ try {
267
+ for (const clientId of Object.keys(session.authorizations || {})) {
268
+ const sid = session.sidFor(clientId);
269
+ if (sid) {
270
+ await fastify[options.name].revocation.revokeSession(sid);
271
+ }
272
+ }
273
+ if (!(await getAdapter('Session').findByUid(session.uid))) {
274
+ await services.sessionTenant.remove({ sessionUid: session.uid });
275
+ }
276
+ } catch (e) {
277
+ fastify.log.warn({ err: e }, 'fastify-oidc: 登出后清理会话失败');
278
+ }
279
+ });
280
+
281
+ provider.on('server_error', (ctx, err) => {
282
+ fastify.log.error({ err }, 'fastify-oidc: provider server_error');
283
+ });
284
+
285
+ return { provider, getAdapter, errors };
286
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * 把当前授权请求中申请的 OIDC scope / claims / 资源 scope 写入 grant。
3
+ * 用于免确认(skip_consent)的一方应用,以及用户在 consent 页确认之后。
4
+ */
5
+ const fillGrantFromRequest = (ctx, grant) => {
6
+ const { oidc } = ctx;
7
+ if (oidc.requestParamOIDCScopes?.size) {
8
+ grant.addOIDCScope([...oidc.requestParamOIDCScopes].join(' '));
9
+ }
10
+ if (oidc.requestParamClaims?.size) {
11
+ grant.addOIDCClaims([...oidc.requestParamClaims]);
12
+ }
13
+ for (const [indicator, resourceServer] of Object.entries(oidc.resourceServers || {})) {
14
+ const scopes = [...(oidc.requestParamScopes || [])].filter(scope => resourceServer.scopes.has(scope));
15
+ grant.addResourceScope(indicator, scopes.join(' '));
16
+ }
17
+ };
18
+
19
+ const fillGrantFromDetails = (grant, details = {}) => {
20
+ if (details.missingOIDCScope) {
21
+ grant.addOIDCScope(details.missingOIDCScope.join(' '));
22
+ }
23
+ if (details.missingOIDCClaims) {
24
+ grant.addOIDCClaims(details.missingOIDCClaims);
25
+ }
26
+ for (const [indicator, scopes] of Object.entries(details.missingResourceScopes || {})) {
27
+ grant.addResourceScope(indicator, scopes.join(' '));
28
+ }
29
+ };
30
+
31
+ module.exports = { fillGrantFromRequest, fillGrantFromDetails };
@@ -0,0 +1,82 @@
1
+ const { jwtVerify } = require('jose');
2
+
3
+ const GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
4
+ const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
5
+ const PARAMETERS = ['subject_token', 'subject_token_type', 'requested_token_type', 'resource', 'audience', 'scope'];
6
+
7
+ /**
8
+ * RFC 8693 Token Exchange:服务端拿着用户的 access_token,换取访问另一个资源服务的 access_token。
9
+ * - 调用方必须是已认证的 client,且 grant_types 包含本 grant
10
+ * - subject_token 必须由本 IdP 签发,且其 aud 在调用方 client 的 allowed_resources 中(防止拿别人的令牌来换)
11
+ * - 目标资源必须在调用方 client 的 allowed_resources 中
12
+ */
13
+ const createTokenExchangeHandler = ({ errors, t, options, identity, getResourceServerInfo, getLocalJWKS, isRevoked }) => {
14
+ return async ctx => {
15
+ const { client, params, provider } = ctx.oidc;
16
+ const { claims } = options.runtime;
17
+
18
+ if (params.subject_token_type !== ACCESS_TOKEN_TYPE) {
19
+ throw new errors.InvalidRequest(await t(ctx, 'subjectTokenTypeUnsupported'));
20
+ }
21
+ if (params.requested_token_type && params.requested_token_type !== ACCESS_TOKEN_TYPE) {
22
+ throw new errors.InvalidRequest(await t(ctx, 'requestedTokenTypeUnsupported'));
23
+ }
24
+ const target = params.resource || params.audience;
25
+ if (!target) {
26
+ throw new errors.InvalidTarget(await t(ctx, 'tokenExchangeTargetMissing'));
27
+ }
28
+
29
+ let subject;
30
+ try {
31
+ ({ payload: subject } = await jwtVerify(params.subject_token, getLocalJWKS(), {
32
+ issuer: options.runtime.issuer,
33
+ typ: 'at+jwt'
34
+ }));
35
+ } catch (e) {
36
+ throw new errors.InvalidGrant(await t(ctx, 'subjectTokenInvalid'));
37
+ }
38
+ if (subject[claims.clientToken] || !subject.sub) {
39
+ throw new errors.InvalidGrant(await t(ctx, 'subjectTokenNotUser'));
40
+ }
41
+ if (await isRevoked(subject)) {
42
+ throw new errors.InvalidGrant(await t(ctx, 'subjectTokenRevoked'));
43
+ }
44
+ const allowed = client.allowed_resources || [];
45
+ const subjectAudiences = [].concat(subject.aud || []);
46
+ if (!subjectAudiences.some(aud => allowed.includes(aud))) {
47
+ throw new errors.InvalidGrant(await t(ctx, 'subjectTokenAudienceForbidden'));
48
+ }
49
+
50
+ const resourceServerInfo = await getResourceServerInfo(ctx, target, client);
51
+ const account = await identity.findAccount(ctx, subject.sub);
52
+ if (!account) {
53
+ throw new errors.InvalidGrant(await t(ctx, 'subjectTokenAccountInvalid'));
54
+ }
55
+
56
+ const requested = (params.scope || resourceServerInfo.scope || '').split(' ').filter(Boolean);
57
+ const available = new Set(resourceServerInfo.scope.split(' '));
58
+ const scope = requested.filter(item => available.has(item)).join(' ') || undefined;
59
+
60
+ const token = new provider.AccessToken({
61
+ accountId: account.accountId,
62
+ client,
63
+ gty: 'token_exchange',
64
+ scope
65
+ });
66
+ token.resourceServer = new provider.ResourceServer(target, resourceServerInfo);
67
+ token.kneTenantId = subject[claims.tenantId];
68
+ token.kneActor = client.clientId;
69
+ ctx.oidc.entity('AccessToken', token);
70
+ const value = await token.save();
71
+
72
+ ctx.body = {
73
+ access_token: value,
74
+ issued_token_type: ACCESS_TOKEN_TYPE,
75
+ token_type: 'Bearer',
76
+ expires_in: token.expiration,
77
+ scope: token.scope
78
+ };
79
+ };
80
+ };
81
+
82
+ module.exports = { GRANT_TYPE, ACCESS_TOKEN_TYPE, PARAMETERS, createTokenExchangeHandler };
@@ -0,0 +1,108 @@
1
+ const ACTIVE_USER_STATUS = [0, 1];
2
+
3
+ const plain = item => (item && typeof item.get === 'function' ? item.get({ plain: true }) : item);
4
+
5
+ /**
6
+ * oidc-provider 与 kne 包之间的唯一桥接层:
7
+ * 用户来自 fastify-account,租户 / 角色 / 权限来自 fastify-tenant(可选)
8
+ */
9
+ module.exports = ({ fastify, options }) => {
10
+ const account = () => {
11
+ const ns = fastify[options.accountNamespace];
12
+ if (!ns) {
13
+ throw new Error(`fastify-oidc: 未找到 fastify.${options.accountNamespace},IdP 模式需要先注册 @kne/fastify-account`);
14
+ }
15
+ return ns;
16
+ };
17
+ const tenant = () => fastify[options.tenantNamespace];
18
+
19
+ const tenantEnabled = () => !!tenant();
20
+
21
+ const getUser = async id => {
22
+ try {
23
+ return await account().services.user.getUser({ id });
24
+ } catch (e) {
25
+ return null;
26
+ }
27
+ };
28
+
29
+ const toProfileClaims = user => ({
30
+ sub: String(user.id),
31
+ name: user.nickname || undefined,
32
+ nickname: user.nickname || undefined,
33
+ picture: user.avatar || undefined,
34
+ email: user.email || undefined,
35
+ phone_number: user.phone || undefined,
36
+ gender: user.gender || undefined,
37
+ birthdate: user.birthday ? String(user.birthday).slice(0, 10) : undefined
38
+ });
39
+
40
+ const findAccount = async (ctx, sub) => {
41
+ const user = await getUser(sub);
42
+ if (!user || !ACTIVE_USER_STATUS.includes(user.status)) {
43
+ return undefined;
44
+ }
45
+ return {
46
+ accountId: String(user.id),
47
+ async claims() {
48
+ return toProfileClaims(user);
49
+ }
50
+ };
51
+ };
52
+
53
+ const verifyCredentials = async credentials => {
54
+ const { services } = account();
55
+ if (typeof services.account.verifyCredentials !== 'function') {
56
+ throw new Error('fastify-oidc: 需要 @kne/fastify-account 提供 services.account.verifyCredentials,请升级 fastify-account');
57
+ }
58
+ return services.account.verifyCredentials(credentials);
59
+ };
60
+
61
+ const listTenants = async accountId => {
62
+ if (!tenantEnabled()) {
63
+ return { list: [], defaultTenantId: null };
64
+ }
65
+ const { list, defaultTenantId } = await tenant().services.user.tenantList({ id: accountId });
66
+ return {
67
+ list: list
68
+ .map(plain)
69
+ .filter(item => item.status === 'open' && (!item.tenant || item.tenant.status === 'open'))
70
+ .map(item => ({
71
+ tenantId: String(item.tenantId),
72
+ tenantUserId: String(item.id),
73
+ name: item.tenant?.name,
74
+ logo: item.tenant?.logo,
75
+ companyName: item.tenant?.company?.name
76
+ })),
77
+ defaultTenantId: defaultTenantId ? String(defaultTenantId) : null
78
+ };
79
+ };
80
+
81
+ const isTenantMember = async (accountId, tenantId) => {
82
+ const { list } = await listTenants(accountId);
83
+ return list.some(item => item.tenantId === String(tenantId));
84
+ };
85
+
86
+ const getTenantContext = async ({ accountId, tenantId }) => {
87
+ if (!tenantEnabled() || !tenantId) {
88
+ return null;
89
+ }
90
+ let info;
91
+ try {
92
+ info = plain(await tenant().services.user.getTenantUserInfo({ id: accountId, tenantId }));
93
+ } catch (e) {
94
+ return null;
95
+ }
96
+ if (!info || String(info.tenantId) !== String(tenantId)) {
97
+ return null;
98
+ }
99
+ return {
100
+ tenantId: String(info.tenantId),
101
+ tenantUserId: String(info.id),
102
+ roles: (info.roleDetails || []).map(role => role.code || String(role.id)).filter(Boolean),
103
+ permissions: info.permissions || []
104
+ };
105
+ };
106
+
107
+ return { tenantEnabled, getUser, toProfileClaims, findAccount, verifyCredentials, listTenants, isTenantMember, getTenantContext };
108
+ };
@@ -0,0 +1,123 @@
1
+ const { createLocalJWKSet } = require('jose');
2
+ const createIdentity = require('./identity');
3
+ const createProvider = require('./create-provider');
4
+ const createSequelizeAdapter = require('./adapters/sequelize');
5
+
6
+ /**
7
+ * IdP 运行期:持有当前 oidc-provider 实例,负责初始化、密钥轮换后的热替换和定时清理
8
+ */
9
+ module.exports = ({ fastify, options, translator }) => {
10
+ const identity = createIdentity({ fastify, options });
11
+ const timers = [];
12
+ let PayloadAdapter;
13
+ let state = null;
14
+
15
+ const getServices = () => fastify[options.name].services;
16
+
17
+ const assertReady = () => {
18
+ if (!state) {
19
+ throw new Error('fastify-oidc: IdP 尚未初始化完成');
20
+ }
21
+ return state;
22
+ };
23
+
24
+ const build = async () => {
25
+ const services = getServices();
26
+ const jwks = await services.key.getPrivateJwks();
27
+ const publicJwks = await services.key.getPublicJwks();
28
+ const fingerprint = await services.key.fingerprint();
29
+ const localJWKS = createLocalJWKSet(publicJwks);
30
+ const result = await createProvider({
31
+ fastify,
32
+ options,
33
+ identity,
34
+ translator,
35
+ jwks,
36
+ PayloadAdapter,
37
+ getLocalJWKS: () => assertReady().localJWKS
38
+ });
39
+ state = Object.assign(result, { callback: result.provider.callback(), localJWKS, publicJwks, fingerprint });
40
+ };
41
+
42
+ const seed = async () => {
43
+ const services = getServices();
44
+ const { runtime } = options;
45
+ const resourceServers = [...(options.resourceServers || [])];
46
+ const clients = [...(options.clients || [])];
47
+ if (options.seedSelf) {
48
+ resourceServers.push({ identifier: runtime.audience, name: `${options.name} API` });
49
+ resourceServers.push({ identifier: runtime.serviceAudience, name: 'OIDC 服务接口', scope: options.serviceScopes.join(' ') });
50
+ clients.push(
51
+ Object.assign(
52
+ {
53
+ clientId: runtime.clientId,
54
+ clientName: `${options.name} 前端`,
55
+ redirect_uris: [`${runtime.origin}${options.callbackPath}`],
56
+ post_logout_redirect_uris: [`${runtime.origin}/`],
57
+ token_endpoint_auth_method: 'none',
58
+ allowedResources: [runtime.audience]
59
+ },
60
+ options.selfClient
61
+ )
62
+ );
63
+ }
64
+ await services.resourceServer.seed(resourceServers);
65
+ await services.client.seed(clients);
66
+ };
67
+
68
+ const reloadIfKeysChanged = async () => {
69
+ try {
70
+ if (state && (await getServices().key.fingerprint()) !== state.fingerprint) {
71
+ await build();
72
+ }
73
+ } catch (e) {
74
+ fastify.log.warn({ err: e }, 'fastify-oidc: 检查密钥变更失败');
75
+ }
76
+ };
77
+
78
+ const cleanup = async () => {
79
+ try {
80
+ const { models } = fastify[options.name];
81
+ const { Op } = fastify.sequelize.Sequelize;
82
+ if (!options.adapter) {
83
+ await models.payload.destroy({ where: { expiresAt: { [Op.lt]: new Date() } } });
84
+ }
85
+ await models.sessionTenant.destroy({ where: { updatedAt: { [Op.lt]: new Date(Date.now() - options.ttl.session * 1000) } } });
86
+ await getServices().key.pruneRetired();
87
+ } catch (e) {
88
+ fastify.log.warn({ err: e }, 'fastify-oidc: 定时清理失败');
89
+ }
90
+ };
91
+
92
+ const schedule = (fn, seconds) => {
93
+ if (!seconds) {
94
+ return;
95
+ }
96
+ const timer = setInterval(fn, seconds * 1000);
97
+ timer.unref();
98
+ timers.push(timer);
99
+ };
100
+
101
+ const init = async () => {
102
+ PayloadAdapter = options.adapter || createSequelizeAdapter({ models: fastify[options.name].models });
103
+ await getServices().key.ensureKeys();
104
+ await seed();
105
+ await build();
106
+ schedule(reloadIfKeysChanged, options.keyReloadInterval);
107
+ schedule(cleanup, options.cleanupInterval);
108
+ };
109
+
110
+ const close = () => timers.forEach(clearInterval);
111
+
112
+ return {
113
+ identity,
114
+ init,
115
+ close,
116
+ reload: build,
117
+ getProvider: () => state && state.provider,
118
+ getAdapter: name => assertReady().getAdapter(name),
119
+ getLocalJWKS: () => state && state.localJWKS,
120
+ getPublicJwks: () => state && state.publicJwks,
121
+ handle: (req, res) => assertReady().callback(req, res)
122
+ };
123
+ };
@@ -0,0 +1,26 @@
1
+ const METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
2
+
3
+ /**
4
+ * 把 issuer 路径下的请求原样交给 oidc-provider(Koa)处理。
5
+ * 必须以非 fastify-plugin 的方式注册:这里清空了 body 解析器,避免请求体被 fastify 提前读走。
6
+ */
7
+ module.exports = async (fastify, { idp, mountPath, translator }) => {
8
+ fastify.removeAllContentTypeParsers();
9
+ fastify.addContentTypeParser('*', (request, payload, done) => done(null));
10
+
11
+ const handler = (request, reply) => {
12
+ if (!idp.getProvider()) {
13
+ return translator.t(request, 'providerNotReady').then(message => reply.code(503).send({ message }));
14
+ }
15
+ reply.hijack();
16
+ const req = request.raw;
17
+ req.originalUrl = req.url;
18
+ req.kneOidcLocale = translator.getLocale(request);
19
+ const rest = req.url.slice(mountPath.length);
20
+ req.url = rest.startsWith('/') ? rest : `/${rest}`;
21
+ idp.handle(req, reply.raw);
22
+ };
23
+
24
+ fastify.route({ method: METHODS, url: mountPath, handler });
25
+ fastify.route({ method: METHODS, url: `${mountPath}/*`, handler });
26
+ };