@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,62 @@
1
+ /**
2
+ * 内存版过期表,单实例可用;多实例部署需通过 options.revocationStore 传入共享存储(如 Redis),
3
+ * 接口:get(key) => value | undefined,set(key, value, ttlSeconds)
4
+ */
5
+ const createMemoryStore = () => {
6
+ const map = new Map();
7
+ return {
8
+ async get(key) {
9
+ const item = map.get(key);
10
+ if (!item) {
11
+ return undefined;
12
+ }
13
+ if (item.expiresAt <= Date.now()) {
14
+ map.delete(key);
15
+ return undefined;
16
+ }
17
+ return item.value;
18
+ },
19
+ async set(key, value, ttlSeconds) {
20
+ map.set(key, { value, expiresAt: Date.now() + ttlSeconds * 1000 });
21
+ if (map.size > 10000) {
22
+ const now = Date.now();
23
+ for (const [k, v] of map) {
24
+ if (v.expiresAt <= now) map.delete(k);
25
+ }
26
+ }
27
+ }
28
+ };
29
+ };
30
+
31
+ /**
32
+ * 记录已登出的会话(sid)和需要强制失效的用户(sub)。
33
+ * JWT access_token 无法真正撤销,只能在资源侧拒绝:sid 命中,或 sub 的撤销时间晚于 token 的 iat。
34
+ */
35
+ module.exports = ({ store, ttl }) => {
36
+ store = store || createMemoryStore();
37
+
38
+ const revokeSession = async sid => {
39
+ await store.set(`sid:${sid}`, Math.floor(Date.now() / 1000), ttl);
40
+ };
41
+
42
+ const revokeSubject = async sub => {
43
+ await store.set(`sub:${sub}`, Math.floor(Date.now() / 1000), ttl);
44
+ };
45
+
46
+ const isRevoked = async payload => {
47
+ if (payload.sid && (await store.get(`sid:${payload.sid}`))) {
48
+ return true;
49
+ }
50
+ if (payload.sub) {
51
+ const revokedAt = await store.get(`sub:${payload.sub}`);
52
+ if (revokedAt && payload.iat <= revokedAt) {
53
+ return true;
54
+ }
55
+ }
56
+ return false;
57
+ };
58
+
59
+ return { revokeSession, revokeSubject, isRevoked };
60
+ };
61
+
62
+ module.exports.createMemoryStore = createMemoryStore;
@@ -0,0 +1,91 @@
1
+ const { GRANT_TYPE: TOKEN_EXCHANGE, ACCESS_TOKEN_TYPE } = require('../idp/grants/token-exchange');
2
+ const { createError } = require('../utils/intl');
3
+
4
+ /**
5
+ * 服务端调用主项目(IdP)的客户端:client_credentials 获取服务令牌、token exchange 代用户换取其它资源的令牌
6
+ */
7
+ module.exports = ({ options, fetch = globalThis.fetch }) => {
8
+ const { runtime, serviceClient } = options;
9
+ const { clientId, clientSecret } = serviceClient || {};
10
+ let discovery;
11
+ const tokenCache = new Map();
12
+
13
+ const enabled = () => !!(clientId && clientSecret);
14
+
15
+ const assertEnabled = () => {
16
+ if (!enabled()) {
17
+ throw createError(null, 'serviceClientNotConfigured');
18
+ }
19
+ };
20
+
21
+ const getDiscovery = async () => {
22
+ if (!discovery) {
23
+ const response = await fetch(`${runtime.issuer}/.well-known/openid-configuration`);
24
+ if (!response.ok) {
25
+ throw createError(null, 'idpDiscoveryFailed', { status: String(response.status) });
26
+ }
27
+ discovery = await response.json();
28
+ }
29
+ return discovery;
30
+ };
31
+
32
+ const tokenRequest = async body => {
33
+ const { token_endpoint } = await getDiscovery();
34
+ const response = await fetch(token_endpoint, {
35
+ method: 'POST',
36
+ headers: {
37
+ 'content-type': 'application/x-www-form-urlencoded',
38
+ authorization: `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64')}`
39
+ },
40
+ body: new URLSearchParams(body).toString()
41
+ });
42
+ const data = await response.json();
43
+ if (!response.ok) {
44
+ const error = createError(null, 'idpTokenRequestFailed', { status: String(response.status), reason: data.error_description || data.error || '' });
45
+ error.statusCode = response.status === 400 ? 400 : 502;
46
+ throw error;
47
+ }
48
+ return data;
49
+ };
50
+
51
+ const getServiceToken = async ({ resource = runtime.serviceAudience, scope = options.serviceScopes.join(' ') } = {}) => {
52
+ assertEnabled();
53
+ const key = `${resource} ${scope}`;
54
+ const cached = tokenCache.get(key);
55
+ if (cached && cached.expiresAt - 30 * 1000 > Date.now()) {
56
+ return cached.accessToken;
57
+ }
58
+ const data = await tokenRequest({ grant_type: 'client_credentials', resource, scope });
59
+ tokenCache.set(key, { accessToken: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 });
60
+ return data.access_token;
61
+ };
62
+
63
+ const callService = async (path, query) => {
64
+ const token = await getServiceToken();
65
+ const url = new URL(`${runtime.idpApiBase}${path}`);
66
+ Object.entries(query || {}).forEach(([key, value]) => value !== undefined && url.searchParams.set(key, value));
67
+ const response = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
68
+ const data = await response.json().catch(() => null);
69
+ if (!response.ok) {
70
+ throw createError(null, 'idpServiceCallFailed', { path, status: String(response.status), reason: data?.message || '' });
71
+ }
72
+ return data && Object.prototype.hasOwnProperty.call(data, 'data') && Object.prototype.hasOwnProperty.call(data, 'code') ? data.data : data;
73
+ };
74
+
75
+ const getUserProfile = async userId => callService('/service/user', { id: userId });
76
+
77
+ const getTenantUser = async ({ userId, tenantId }) => callService('/service/tenant-user', { userId, tenantId });
78
+
79
+ const exchangeToken = async ({ subjectToken, resource, scope }) => {
80
+ assertEnabled();
81
+ return tokenRequest({
82
+ grant_type: TOKEN_EXCHANGE,
83
+ subject_token: subjectToken,
84
+ subject_token_type: ACCESS_TOKEN_TYPE,
85
+ resource,
86
+ ...(scope ? { scope } : {})
87
+ });
88
+ };
89
+
90
+ return { enabled, getServiceToken, getUserProfile, getTenantUser, exchangeToken };
91
+ };
@@ -0,0 +1,60 @@
1
+ const { pick } = require('lodash');
2
+
3
+ const PROFILE_FIELDS = ['nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description'];
4
+ const USER_FIELDS = ['id', ...PROFILE_FIELDS, 'status'];
5
+
6
+ /**
7
+ * central 模式:子项目保留 fastify-account 的用户表作为镜像,按 sub 即时创建 / 定期同步,
8
+ * 保证依赖 getUserModel 关联用户表的 kne 插件照常工作。
9
+ */
10
+ module.exports = ({ fastify, options, serviceClient }) => {
11
+ const cache = new Map();
12
+ const getModel = () => fastify[options.accountNamespace].models.user;
13
+
14
+ const fetchProfile = async userId => {
15
+ if (!serviceClient.enabled()) {
16
+ return null;
17
+ }
18
+ try {
19
+ return pick(await serviceClient.getUserProfile(userId), PROFILE_FIELDS);
20
+ } catch (e) {
21
+ fastify.log.warn({ err: e, userId }, 'fastify-oidc: 获取主项目用户资料失败,使用本地镜像');
22
+ return null;
23
+ }
24
+ };
25
+
26
+ const createMirror = async (userId, profile) => {
27
+ const model = getModel();
28
+ const values = Object.assign({ nickname: userId }, profile, { id: userId, status: 0 });
29
+ try {
30
+ return await model.create(values, { hooks: false });
31
+ } catch (e) {
32
+ if (e.name !== 'SequelizeUniqueConstraintError') {
33
+ throw e;
34
+ }
35
+ fastify.log.warn({ userId }, 'fastify-oidc: 镜像用户邮箱或手机号与本地已有用户冲突,忽略这两个字段');
36
+ return model.create(Object.assign({}, values, { email: null, phone: null }), { hooks: false });
37
+ }
38
+ };
39
+
40
+ const ensure = async userId => {
41
+ const cached = cache.get(userId);
42
+ if (cached && cached.expiresAt > Date.now()) {
43
+ return cached.user;
44
+ }
45
+ const model = getModel();
46
+ let row = await model.findByPk(userId);
47
+ const profile = await fetchProfile(userId);
48
+ if (!row) {
49
+ row = await createMirror(userId, profile);
50
+ } else if (profile) {
51
+ await row.update(profile).catch(e => fastify.log.warn({ err: e, userId }, 'fastify-oidc: 同步镜像用户资料失败'));
52
+ }
53
+ const user = pick(row.get({ plain: true }), USER_FIELDS);
54
+ user.id = String(row.id);
55
+ cache.set(userId, { user, expiresAt: Date.now() + options.userMirrorTTL * 1000 });
56
+ return user;
57
+ };
58
+
59
+ return { ensure };
60
+ };
@@ -0,0 +1,51 @@
1
+ const { jwtVerify, createRemoteJWKSet } = require('jose');
2
+ const { createError } = require('../utils/intl');
3
+
4
+ const LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';
5
+
6
+ /**
7
+ * standalone 模式直接用本进程的公钥集验签;central 模式从主项目的 jwks_uri 拉取(jose 内置缓存与按 kid 刷新)
8
+ */
9
+ module.exports = ({ options, getLocalJWKS }) => {
10
+ const { runtime } = options;
11
+ let remote;
12
+
13
+ const getJWKS = () => {
14
+ const local = getLocalJWKS && getLocalJWKS();
15
+ if (local) {
16
+ return local;
17
+ }
18
+ remote = remote || createRemoteJWKSet(new URL(runtime.jwksUri));
19
+ return remote;
20
+ };
21
+
22
+ const verifyAccessToken = async (token, { audience = runtime.audience } = {}) => {
23
+ const { payload } = await jwtVerify(token, getJWKS(), {
24
+ issuer: runtime.issuer,
25
+ audience,
26
+ typ: 'at+jwt',
27
+ clockTolerance: options.clockTolerance
28
+ });
29
+ return payload;
30
+ };
31
+
32
+ const verifyLogoutToken = async (token, { audience }) => {
33
+ const { payload } = await jwtVerify(token, getJWKS(), {
34
+ issuer: runtime.issuer,
35
+ audience,
36
+ clockTolerance: options.clockTolerance
37
+ });
38
+ if (!payload.events || typeof payload.events[LOGOUT_EVENT] !== 'object') {
39
+ throw createError(null, 'logoutTokenEventMissing');
40
+ }
41
+ if (payload.nonce !== undefined) {
42
+ throw createError(null, 'logoutTokenNonceNotAllowed');
43
+ }
44
+ if (!payload.sid && !payload.sub) {
45
+ throw createError(null, 'logoutTokenSubjectMissing');
46
+ }
47
+ return payload;
48
+ };
49
+
50
+ return { verifyAccessToken, verifyLogoutToken };
51
+ };
@@ -0,0 +1,167 @@
1
+ const fp = require('fastify-plugin');
2
+ const httpErrors = require('http-errors');
3
+ const { encrypt, decrypt, randomSecret } = require('../utils/crypto');
4
+ const { createError } = require('../utils/intl');
5
+
6
+ const { NotFound, BadRequest } = httpErrors;
7
+
8
+ const PUBLIC_DEFAULTS = {
9
+ application_type: 'web',
10
+ grant_types: ['authorization_code', 'refresh_token'],
11
+ response_types: ['code'],
12
+ token_endpoint_auth_method: 'none'
13
+ };
14
+
15
+ module.exports = fp(async (fastify, options) => {
16
+ const { models, services } = fastify[options.name];
17
+ if (!options.runtime.idpEnabled) {
18
+ return;
19
+ }
20
+ const { Op } = fastify.sequelize.Sequelize;
21
+ const secret = options.keyEncryptionSecret;
22
+
23
+ const normalizeMetadata = (metadata = {}) => {
24
+ const result = Object.assign({}, PUBLIC_DEFAULTS, metadata);
25
+ if (!Array.isArray(result.redirect_uris)) {
26
+ result.redirect_uris = result.grant_types.includes('authorization_code') ? [] : undefined;
27
+ }
28
+ ['client_id', 'client_secret', 'client_name', 'allowed_resources'].forEach(key => delete result[key]);
29
+ return result;
30
+ };
31
+
32
+ const isConfidential = metadata => metadata.token_endpoint_auth_method !== 'none';
33
+
34
+ const validate = async ({ clientId, metadata, allowedResources }) => {
35
+ const provider = fastify[options.name].idp.getProvider();
36
+ if (!provider) {
37
+ return;
38
+ }
39
+ try {
40
+ await provider.Client.validate(
41
+ Object.assign({}, metadata, {
42
+ client_id: clientId,
43
+ client_secret: isConfidential(metadata) ? 'validate-only-secret' : undefined,
44
+ allowed_resources: allowedResources || []
45
+ })
46
+ );
47
+ } catch (e) {
48
+ throw createError(BadRequest, 'clientMetadataInvalid', { reason: e.error_description || e.message });
49
+ }
50
+ };
51
+
52
+ const format = item => {
53
+ const data = item.get({ plain: true });
54
+ delete data.clientSecret;
55
+ data.hasSecret = !!item.clientSecret;
56
+ data.allowedResources = data.allowedResources || [];
57
+ return data;
58
+ };
59
+
60
+ const getInstance = async ({ id }) => {
61
+ const item = await models.client.findByPk(id);
62
+ if (!item) {
63
+ throw createError(NotFound, 'clientNotFound');
64
+ }
65
+ return item;
66
+ };
67
+
68
+ const list = async ({ filter = {}, perPage = 20, currentPage = 1 } = {}) => {
69
+ const where = {};
70
+ if (filter.keyword) {
71
+ where[Op.or] = [{ clientId: { [Op.like]: `%${filter.keyword}%` } }, { clientName: { [Op.like]: `%${filter.keyword}%` } }];
72
+ }
73
+ if (filter.status) {
74
+ where.status = filter.status;
75
+ }
76
+ const { rows, count } = await models.client.findAndCountAll({
77
+ where,
78
+ offset: perPage * (currentPage - 1),
79
+ limit: perPage,
80
+ order: [['createdAt', 'DESC']]
81
+ });
82
+ return { pageData: rows.map(format), totalCount: count };
83
+ };
84
+
85
+ const detail = async ({ id }) => format(await getInstance({ id }));
86
+
87
+ const create = async ({ clientId, clientName, clientSecret, metadata, allowedResources = [], description }) => {
88
+ clientId = clientId || randomSecret(12);
89
+ if (await models.client.count({ where: { clientId } })) {
90
+ throw createError(BadRequest, 'clientIdExists', { clientId });
91
+ }
92
+ const normalized = normalizeMetadata(metadata);
93
+ await validate({ clientId, metadata: normalized, allowedResources });
94
+ const plainSecret = isConfidential(normalized) ? clientSecret || randomSecret(32) : null;
95
+ const item = await models.client.create({
96
+ clientId,
97
+ clientName,
98
+ clientSecret: plainSecret ? encrypt(secret, plainSecret) : null,
99
+ metadata: normalized,
100
+ allowedResources,
101
+ description
102
+ });
103
+ return Object.assign(format(item), plainSecret ? { clientSecret: plainSecret } : {});
104
+ };
105
+
106
+ const save = async ({ id, clientName, metadata, allowedResources, description }) => {
107
+ const item = await getInstance({ id });
108
+ const nextMetadata = metadata ? normalizeMetadata(metadata) : item.metadata;
109
+ const nextResources = allowedResources || item.allowedResources || [];
110
+ await validate({ clientId: item.clientId, metadata: nextMetadata, allowedResources: nextResources });
111
+ const patch = { metadata: nextMetadata, allowedResources: nextResources };
112
+ if (clientName !== undefined) patch.clientName = clientName;
113
+ if (description !== undefined) patch.description = description;
114
+ if (isConfidential(nextMetadata) && !item.clientSecret) {
115
+ patch.clientSecret = encrypt(secret, randomSecret(32));
116
+ }
117
+ if (!isConfidential(nextMetadata)) {
118
+ patch.clientSecret = null;
119
+ }
120
+ await item.update(patch);
121
+ return format(item);
122
+ };
123
+
124
+ const rotateSecret = async ({ id }) => {
125
+ const item = await getInstance({ id });
126
+ if (!isConfidential(item.metadata)) {
127
+ throw createError(BadRequest, 'publicClientNoSecret');
128
+ }
129
+ const plainSecret = randomSecret(32);
130
+ await item.update({ clientSecret: encrypt(secret, plainSecret) });
131
+ return { clientId: item.clientId, clientSecret: plainSecret };
132
+ };
133
+
134
+ const setStatus = async ({ id, status }) => {
135
+ const item = await getInstance({ id });
136
+ await item.update({ status });
137
+ };
138
+
139
+ const remove = async ({ id }) => {
140
+ const item = await getInstance({ id });
141
+ await item.destroy();
142
+ };
143
+
144
+ const findForProvider = async clientId => {
145
+ const item = await models.client.findOne({ where: { clientId, status: 'open' } });
146
+ if (!item) {
147
+ return undefined;
148
+ }
149
+ return Object.assign({}, item.metadata, {
150
+ client_id: item.clientId,
151
+ client_name: item.clientName || undefined,
152
+ client_secret: item.clientSecret ? decrypt(secret, item.clientSecret) : undefined,
153
+ allowed_resources: item.allowedResources || []
154
+ });
155
+ };
156
+
157
+ const seed = async clients => {
158
+ for (const { clientId, clientName, clientSecret, allowedResources, description, ...metadata } of clients || []) {
159
+ if (await models.client.count({ where: { clientId } })) {
160
+ continue;
161
+ }
162
+ await create({ clientId, clientName, clientSecret, metadata, allowedResources, description });
163
+ }
164
+ };
165
+
166
+ services.client = { list, detail, create, save, rotateSecret, setStatus, remove, findForProvider, seed };
167
+ });
@@ -0,0 +1,104 @@
1
+ const fp = require('fastify-plugin');
2
+ const httpErrors = require('http-errors');
3
+ const { createError } = require('../utils/intl');
4
+
5
+ const { NotFound } = httpErrors;
6
+
7
+ const TOKEN_MODELS = ['AccessToken', 'AuthorizationCode', 'RefreshToken', 'DeviceCode', 'BackchannelAuthenticationRequest'];
8
+
9
+ module.exports = fp(async (fastify, options) => {
10
+ const { services } = fastify[options.name];
11
+ if (!options.runtime.idpEnabled) {
12
+ return;
13
+ }
14
+ const getIdp = () => fastify[options.name].idp;
15
+ const revocation = () => fastify[options.name].revocation;
16
+
17
+ const revokeGrant = async grantId => {
18
+ const idp = getIdp();
19
+ for (const model of TOKEN_MODELS) {
20
+ await idp.getAdapter(model).revokeByGrantId(grantId);
21
+ }
22
+ await idp.getAdapter('Grant').destroy(grantId);
23
+ };
24
+
25
+ const notifyBackchannel = async ({ accountId, authorizations }) => {
26
+ const provider = getIdp().getProvider();
27
+ for (const [clientId, { sid } = {}] of Object.entries(authorizations || {})) {
28
+ if (sid) {
29
+ await revocation().revokeSession(sid);
30
+ }
31
+ const client = provider && (await provider.Client.find(clientId));
32
+ if (client && client.backchannelLogoutUri && sid) {
33
+ await client.backchannelLogout(String(accountId), sid).catch(e => {
34
+ fastify.log.warn({ err: e, clientId }, 'fastify-oidc: back-channel logout 通知失败');
35
+ });
36
+ }
37
+ }
38
+ };
39
+
40
+ const listSessions = async ({ userId }) => {
41
+ const adapter = getIdp().getAdapter('Session');
42
+ if (typeof adapter.findByAccountId !== 'function') {
43
+ throw createError(null, 'adapterSessionQueryMissing');
44
+ }
45
+ const sessions = await adapter.findByAccountId(String(userId));
46
+ return sessions.map(session => ({
47
+ uid: session.uid,
48
+ loginAt: session.loginTs ? new Date(session.loginTs * 1000) : null,
49
+ expiresAt: session.exp ? new Date(session.exp * 1000) : null,
50
+ clients: Object.entries(session.authorizations || {}).map(([clientId, { sid }]) => ({ clientId, sid }))
51
+ }));
52
+ };
53
+
54
+ const revokeSession = async ({ uid }) => {
55
+ const adapter = getIdp().getAdapter('Session');
56
+ const session = await adapter.findByUid(uid);
57
+ if (!session) {
58
+ throw createError(NotFound, 'sessionNotFound');
59
+ }
60
+ await notifyBackchannel({ accountId: session.accountId, authorizations: session.authorizations });
61
+ let grants = 0;
62
+ for (const { grantId } of Object.values(session.authorizations || {})) {
63
+ if (grantId) {
64
+ await revokeGrant(grantId);
65
+ grants++;
66
+ }
67
+ }
68
+ await adapter.destroy(session.jti);
69
+ await services.sessionTenant.remove({ sessionUid: uid });
70
+ return { grants };
71
+ };
72
+
73
+ /**
74
+ * 撤销用户已签发的全部令牌。logout=false(权限变更)时保留 IdP 会话,前端可静默重新获取带新权限的令牌;
75
+ * logout=true(禁用 / 强制下线)时同时结束会话并发送 back-channel logout。
76
+ */
77
+ const revokeByAccount = async (userId, { logout = false } = {}) => {
78
+ const idp = getIdp();
79
+ const grantAdapter = idp.getAdapter('Grant');
80
+ if (typeof grantAdapter.findGrantIdsByAccountId !== 'function') {
81
+ throw createError(null, 'adapterGrantQueryMissing');
82
+ }
83
+ await revocation().revokeSubject(String(userId));
84
+ let sessions = 0;
85
+ let grants = 0;
86
+ if (logout) {
87
+ const sessionAdapter = idp.getAdapter('Session');
88
+ if (typeof sessionAdapter.findByAccountId !== 'function') {
89
+ throw createError(null, 'adapterSessionQueryMissing');
90
+ }
91
+ for (const session of await sessionAdapter.findByAccountId(String(userId))) {
92
+ grants += (await revokeSession({ uid: session.uid })).grants;
93
+ sessions++;
94
+ }
95
+ }
96
+ const grantIds = await grantAdapter.findGrantIdsByAccountId(String(userId));
97
+ for (const grantId of grantIds) {
98
+ await revokeGrant(grantId);
99
+ }
100
+ return { grants: grants + grantIds.length, sessions };
101
+ };
102
+
103
+ services.grant = { revokeGrant, revokeByAccount, listSessions, revokeSession };
104
+ });
@@ -0,0 +1,118 @@
1
+ const fp = require('fastify-plugin');
2
+ const httpErrors = require('http-errors');
3
+ const { fillGrantFromDetails } = require('../idp/grant-helpers');
4
+ const { createError } = require('../utils/intl');
5
+
6
+ const { BadRequest } = httpErrors;
7
+
8
+ module.exports = fp(async (fastify, options) => {
9
+ const { services, translator } = fastify[options.name];
10
+ if (!options.runtime.idpEnabled) {
11
+ return;
12
+ }
13
+ const getIdp = () => fastify[options.name].idp;
14
+
15
+ const loadInteraction = async ({ request, reply, uid, prompt }) => {
16
+ const provider = getIdp().getProvider();
17
+ let interaction;
18
+ try {
19
+ interaction = await provider.interactionDetails(request.raw, reply.raw);
20
+ } catch (e) {
21
+ throw createError(BadRequest, 'interactionExpired');
22
+ }
23
+ if (interaction.uid !== uid) {
24
+ throw createError(BadRequest, 'interactionMismatch');
25
+ }
26
+ if (prompt && interaction.prompt.name !== prompt) {
27
+ throw createError(BadRequest, 'interactionPromptMismatch', { current: interaction.prompt.name, expected: prompt });
28
+ }
29
+ return { provider, interaction };
30
+ };
31
+
32
+ const finish = async ({ provider, request, reply, result, merge = true }) => {
33
+ const redirectTo = await provider.interactionResult(request.raw, reply.raw, result, { mergeWithLastSubmission: merge });
34
+ return { redirectTo };
35
+ };
36
+
37
+ const details = async ({ request, reply, uid }) => {
38
+ const { provider, interaction } = await loadInteraction({ request, reply, uid });
39
+ const { identity } = getIdp();
40
+ const { prompt, params, session } = interaction;
41
+ const client = await provider.Client.find(params.client_id);
42
+ const output = {
43
+ uid: interaction.uid,
44
+ prompt: { name: prompt.name, reasons: prompt.reasons, details: prompt.details },
45
+ params: {
46
+ clientId: params.client_id,
47
+ scope: params.scope,
48
+ resource: params.resource,
49
+ tenantId: params.tenant_id,
50
+ loginHint: params.login_hint,
51
+ uiLocales: params.ui_locales
52
+ },
53
+ client: client ? { clientId: client.clientId, clientName: client.clientName, logoUri: client.logoUri, clientUri: client.clientUri } : null,
54
+ user: null,
55
+ tenants: null
56
+ };
57
+ if (session?.accountId) {
58
+ const user = await identity.getUser(session.accountId);
59
+ output.user = user && { id: String(user.id), nickname: user.nickname, avatar: user.avatar, email: user.email, phone: user.phone };
60
+ }
61
+ if (prompt.name === 'tenant' && session?.accountId) {
62
+ output.tenants = await identity.listTenants(session.accountId);
63
+ }
64
+ return output;
65
+ };
66
+
67
+ const login = async ({ request, reply, uid, credentials, remember = true }) => {
68
+ const { provider } = await loadInteraction({ request, reply, uid, prompt: 'login' });
69
+ const { status, user } = await getIdp().identity.verifyCredentials(credentials);
70
+ if (!user) {
71
+ return { status };
72
+ }
73
+ return finish({
74
+ provider,
75
+ request,
76
+ reply,
77
+ result: { login: { accountId: String(user.id), remember: remember !== false, amr: ['pwd'] } },
78
+ merge: false
79
+ });
80
+ };
81
+
82
+ const selectTenant = async ({ request, reply, uid, tenantId }) => {
83
+ const { provider, interaction } = await loadInteraction({ request, reply, uid, prompt: 'tenant' });
84
+ const accountId = interaction.session?.accountId;
85
+ if (!accountId || !(await getIdp().identity.isTenantMember(accountId, tenantId))) {
86
+ throw createError(BadRequest, 'tenantNotAvailable');
87
+ }
88
+ return finish({ provider, request, reply, result: { tenant: { tenantId: String(tenantId) } } });
89
+ };
90
+
91
+ const confirm = async ({ request, reply, uid }) => {
92
+ const { provider, interaction } = await loadInteraction({ request, reply, uid, prompt: 'consent' });
93
+ const { params, session, prompt } = interaction;
94
+ let grant;
95
+ if (interaction.grantId) {
96
+ grant = await provider.Grant.find(interaction.grantId);
97
+ }
98
+ if (!grant) {
99
+ grant = new provider.Grant({ accountId: session.accountId, clientId: params.client_id });
100
+ }
101
+ fillGrantFromDetails(grant, prompt.details);
102
+ const grantId = await grant.save();
103
+ return finish({ provider, request, reply, result: { consent: { grantId } } });
104
+ };
105
+
106
+ const abort = async ({ request, reply, uid }) => {
107
+ const { provider } = await loadInteraction({ request, reply, uid });
108
+ return finish({
109
+ provider,
110
+ request,
111
+ reply,
112
+ result: { error: 'access_denied', error_description: await translator.t(request, 'interactionAborted') },
113
+ merge: false
114
+ });
115
+ };
116
+
117
+ services.interaction = { details, login, selectTenant, confirm, abort };
118
+ });