@kne/fastify-oidc 0.1.12 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -2
- package/index.js +1 -0
- package/libs/controllers/admin.js +164 -40
- package/libs/controllers/backchannel.js +5 -2
- package/libs/controllers/config.js +16 -1
- package/libs/controllers/interaction.js +110 -13
- package/libs/controllers/service.js +145 -17
- package/libs/controllers/tenant-apps.js +15 -1
- package/libs/controllers/tenant-proxy.js +87 -19
- package/libs/controllers/tenant-sync.js +5 -2
- package/libs/idp/create-provider.js +31 -1
- package/libs/idp/identity.js +14 -0
- package/libs/idp/index.js +1 -0
- package/libs/idp/mount.js +8 -2
- package/libs/locale/en-US.js +5 -0
- package/libs/locale/zh-CN.js +5 -0
- package/libs/models/mfa-challenge.js +53 -0
- package/libs/models/session-mfa.js +31 -0
- package/libs/schema/response.js +103 -0
- package/libs/services/interaction.js +42 -1
- package/libs/services/mfa.js +125 -0
- package/package.json +1 -1
package/libs/idp/identity.js
CHANGED
|
@@ -121,6 +121,19 @@ module.exports = ({ fastify, options }) => {
|
|
|
121
121
|
return list.some(item => item.tenantId === String(tenantId));
|
|
122
122
|
};
|
|
123
123
|
|
|
124
|
+
// 租户 MFA 配置来自 fastify-tenant 的 services.setting.getMfa;未启用租户或旧版本 fastify-tenant 没有该方法时视为未开启
|
|
125
|
+
const getTenantMfa = async tenantId => {
|
|
126
|
+
const getMfa = tenantEnabled() && tenantId ? tenant().services.setting?.getMfa : null;
|
|
127
|
+
if (typeof getMfa !== 'function') {
|
|
128
|
+
return { enabled: false };
|
|
129
|
+
}
|
|
130
|
+
const mfa = (await getMfa({ tenantId })) || {};
|
|
131
|
+
if (!mfa.enabled) {
|
|
132
|
+
return { enabled: false };
|
|
133
|
+
}
|
|
134
|
+
return { enabled: true, methods: mfa.methods?.length ? mfa.methods : ['sms'], maxAge: Math.max(Number(mfa.maxAge) || 0, 0) };
|
|
135
|
+
};
|
|
136
|
+
|
|
124
137
|
const getTenantUserInfo = async ({ accountId, tenantId, appCode }) => {
|
|
125
138
|
const info = plain(await tenant().services.user.getTenantUserInfo({ id: accountId, tenantId }));
|
|
126
139
|
if (!appCode) {
|
|
@@ -241,6 +254,7 @@ module.exports = ({ fastify, options }) => {
|
|
|
241
254
|
verifyCredentials,
|
|
242
255
|
listTenants,
|
|
243
256
|
isTenantMember,
|
|
257
|
+
getTenantMfa,
|
|
244
258
|
getTenantUserInfo,
|
|
245
259
|
getTenantContext,
|
|
246
260
|
isAppEnabled,
|
package/libs/idp/index.js
CHANGED
|
@@ -93,6 +93,7 @@ module.exports = ({ fastify, options, translator }) => {
|
|
|
93
93
|
await models.payload.destroy({ where: { expiresAt: { [Op.lt]: new Date() } } });
|
|
94
94
|
}
|
|
95
95
|
await models.sessionTenant.destroy({ where: { updatedAt: { [Op.lt]: new Date(Date.now() - options.ttl.session * 1000) } } });
|
|
96
|
+
await getServices().mfa.cleanup({ olderThan: new Date(Date.now() - options.ttl.session * 1000) });
|
|
96
97
|
await getServices().key.pruneRetired();
|
|
97
98
|
} catch (e) {
|
|
98
99
|
fastify.log.warn({ err: e }, 'fastify-oidc: 定时清理失败');
|
package/libs/idp/mount.js
CHANGED
|
@@ -21,6 +21,12 @@ module.exports = async (fastify, { idp, mountPath, translator }) => {
|
|
|
21
21
|
idp.handle(req, reply.raw);
|
|
22
22
|
};
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
const schema = {
|
|
25
|
+
tags: ['OIDC-协议端点'],
|
|
26
|
+
summary: 'OIDC 协议端点(oidc-provider)',
|
|
27
|
+
description:
|
|
28
|
+
'原样交给 oidc-provider 处理的标准端点:/.well-known/openid-configuration、/jwks、/auth、/token、/me、/session/end、/token/introspection、/token/revocation 等,请求与响应格式见 OpenID Connect / OAuth 2.0 规范;provider 未就绪时返回 503'
|
|
29
|
+
};
|
|
30
|
+
fastify.route({ method: METHODS, url: mountPath, schema, handler });
|
|
31
|
+
fastify.route({ method: METHODS, url: `${mountPath}/*`, schema, handler });
|
|
26
32
|
};
|
package/libs/locale/en-US.js
CHANGED
|
@@ -34,6 +34,11 @@ module.exports = {
|
|
|
34
34
|
interactionPromptMismatch: 'The current step is {current}, cannot perform {expected}',
|
|
35
35
|
interactionAborted: 'The user canceled the login',
|
|
36
36
|
tenantNotAvailable: 'The current user does not belong to this tenant or the tenant is closed',
|
|
37
|
+
mfaPhoneRequired: 'This tenant requires SMS verification, but the account has no phone number. Please contact the administrator',
|
|
38
|
+
mfaCodeInvalid: 'The verification code is incorrect',
|
|
39
|
+
mfaCodeExpired: 'The verification code has expired, please send a new one',
|
|
40
|
+
mfaTooManyAttempts: 'Too many incorrect attempts, please send a new verification code',
|
|
41
|
+
mfaResendTooFrequent: 'Sending too frequently, please try again in {seconds} seconds',
|
|
37
42
|
clientNotFound: 'Client not found',
|
|
38
43
|
clientIdExists: 'client_id {clientId} already exists',
|
|
39
44
|
clientMetadataInvalid: 'Invalid client configuration: {reason}',
|
package/libs/locale/zh-CN.js
CHANGED
|
@@ -34,6 +34,11 @@ module.exports = {
|
|
|
34
34
|
interactionPromptMismatch: '当前步骤为 {current},不能执行 {expected}',
|
|
35
35
|
interactionAborted: '用户取消了登录',
|
|
36
36
|
tenantNotAvailable: '当前用户不属于该租户或租户已关闭',
|
|
37
|
+
mfaPhoneRequired: '该租户要求短信验证,但账号未绑定手机号,请联系管理员',
|
|
38
|
+
mfaCodeInvalid: '验证码不正确',
|
|
39
|
+
mfaCodeExpired: '验证码已过期,请重新发送',
|
|
40
|
+
mfaTooManyAttempts: '验证码错误次数过多,请重新发送',
|
|
41
|
+
mfaResendTooFrequent: '发送过于频繁,请 {seconds} 秒后再试',
|
|
37
42
|
clientNotFound: 'client 不存在',
|
|
38
43
|
clientIdExists: 'client_id {clientId} 已存在',
|
|
39
44
|
clientMetadataInvalid: 'client 配置不合法: {reason}',
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
module.exports = ({ DataTypes }) => {
|
|
2
|
+
return {
|
|
3
|
+
model: {
|
|
4
|
+
interactionUid: {
|
|
5
|
+
type: DataTypes.STRING(255),
|
|
6
|
+
allowNull: false,
|
|
7
|
+
comment: 'oidc-provider Interaction uid,验证码只在该次交互内有效'
|
|
8
|
+
},
|
|
9
|
+
accountId: {
|
|
10
|
+
type: DataTypes.STRING(255),
|
|
11
|
+
allowNull: false,
|
|
12
|
+
comment: '用户 id'
|
|
13
|
+
},
|
|
14
|
+
method: {
|
|
15
|
+
type: DataTypes.STRING(32),
|
|
16
|
+
allowNull: false,
|
|
17
|
+
comment: '验证方式,如 sms'
|
|
18
|
+
},
|
|
19
|
+
codeHash: {
|
|
20
|
+
type: DataTypes.STRING(255),
|
|
21
|
+
allowNull: false,
|
|
22
|
+
comment: '验证码 HMAC,不存明文'
|
|
23
|
+
},
|
|
24
|
+
attempts: {
|
|
25
|
+
type: DataTypes.INTEGER,
|
|
26
|
+
allowNull: false,
|
|
27
|
+
defaultValue: 0,
|
|
28
|
+
comment: '已错误次数'
|
|
29
|
+
},
|
|
30
|
+
status: {
|
|
31
|
+
type: DataTypes.STRING(16),
|
|
32
|
+
allowNull: false,
|
|
33
|
+
defaultValue: 'pending',
|
|
34
|
+
comment: 'pending: 待验证, verified: 已使用, locked: 错误次数过多'
|
|
35
|
+
},
|
|
36
|
+
sentAt: {
|
|
37
|
+
type: DataTypes.DATE,
|
|
38
|
+
allowNull: false,
|
|
39
|
+
comment: '最近一次发送时间'
|
|
40
|
+
},
|
|
41
|
+
expiresAt: {
|
|
42
|
+
type: DataTypes.DATE,
|
|
43
|
+
allowNull: false,
|
|
44
|
+
comment: '验证码过期时间'
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
options: {
|
|
48
|
+
comment: 'OIDC 交互中的 MFA 验证码',
|
|
49
|
+
paranoid: false,
|
|
50
|
+
indexes: [{ fields: ['interaction_uid'], unique: true }, { fields: ['expires_at'] }]
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
module.exports = ({ DataTypes }) => {
|
|
2
|
+
return {
|
|
3
|
+
model: {
|
|
4
|
+
sessionUid: {
|
|
5
|
+
type: DataTypes.STRING(255),
|
|
6
|
+
allowNull: false,
|
|
7
|
+
comment: 'oidc-provider Session uid'
|
|
8
|
+
},
|
|
9
|
+
accountId: {
|
|
10
|
+
type: DataTypes.STRING(255),
|
|
11
|
+
allowNull: false,
|
|
12
|
+
comment: '用户 id'
|
|
13
|
+
},
|
|
14
|
+
method: {
|
|
15
|
+
type: DataTypes.STRING(32),
|
|
16
|
+
allowNull: false,
|
|
17
|
+
comment: '验证方式,如 sms'
|
|
18
|
+
},
|
|
19
|
+
verifiedAt: {
|
|
20
|
+
type: DataTypes.DATE,
|
|
21
|
+
allowNull: false,
|
|
22
|
+
comment: '本会话最近一次通过 MFA 验证的时间'
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
options: {
|
|
26
|
+
comment: 'OIDC 会话 MFA 验证记录',
|
|
27
|
+
paranoid: false,
|
|
28
|
+
indexes: [{ fields: ['session_uid'], unique: true }]
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// 响应 schema 会参与 fast-json-stringify 序列化:对象一律 additionalProperties: true 以免裁掉未声明字段;
|
|
2
|
+
// 用 nullable 而非类型数组(类型数组遇到不匹配的值会直接 500),类型不确定的字段(如 id、日期、JSON 列)只写说明不声明类型
|
|
3
|
+
const str = description => ({ type: 'string', nullable: true, description });
|
|
4
|
+
const num = description => ({ type: 'number', nullable: true, description });
|
|
5
|
+
const bool = description => ({ type: 'boolean', nullable: true, description });
|
|
6
|
+
const any = description => ({ description });
|
|
7
|
+
const strArray = description => ({ type: 'array', nullable: true, description, items: { type: 'string' } });
|
|
8
|
+
const list = (description, items) => ({ type: 'array', nullable: true, description, items });
|
|
9
|
+
const obj = (description, properties = {}) => ({ type: 'object', nullable: true, description, additionalProperties: true, properties });
|
|
10
|
+
|
|
11
|
+
const timestamps = () => ({
|
|
12
|
+
createdAt: any('创建时间'),
|
|
13
|
+
updatedAt: any('更新时间')
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const success = (description, schema) => ({
|
|
17
|
+
200: Object.assign({}, schema || { type: 'object' }, { description })
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const empty = (description = '操作成功,返回空对象') => success(description);
|
|
21
|
+
|
|
22
|
+
const pageResult = (description, item) => ({
|
|
23
|
+
type: 'object',
|
|
24
|
+
additionalProperties: true,
|
|
25
|
+
properties: {
|
|
26
|
+
pageData: list(`当前页${description}列表`, item),
|
|
27
|
+
totalCount: num('符合条件的总条数')
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const STATUS = '状态:open 启用,closed 停用';
|
|
32
|
+
|
|
33
|
+
const client = obj('OIDC Client', {
|
|
34
|
+
id: any('记录 ID'),
|
|
35
|
+
clientId: str('client_id'),
|
|
36
|
+
clientName: str('应用名称'),
|
|
37
|
+
hasSecret: bool('是否已设置 client secret(public client 为 false);secret 不会返回'),
|
|
38
|
+
metadata: any('OIDC client metadata(redirect_uris、grant_types、response_types、token_endpoint_auth_method 等)'),
|
|
39
|
+
allowedResources: any('允许申请的资源服务 identifier 列表'),
|
|
40
|
+
description: str('描述'),
|
|
41
|
+
status: str(STATUS),
|
|
42
|
+
...timestamps()
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const resourceServer = obj('资源服务', {
|
|
46
|
+
id: any('记录 ID'),
|
|
47
|
+
identifier: str('resource indicator,即 access_token 的 aud'),
|
|
48
|
+
name: str('资源名称'),
|
|
49
|
+
scope: str('支持的 scope,空格分隔'),
|
|
50
|
+
accessTokenTTL: num('access_token 有效期(秒),为空使用全局配置'),
|
|
51
|
+
includePermissions: any('access_token 中是否携带 permissions,为空使用全局配置'),
|
|
52
|
+
description: str('描述'),
|
|
53
|
+
status: str(STATUS),
|
|
54
|
+
...timestamps()
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const app = obj('子应用', {
|
|
58
|
+
id: any('记录 ID'),
|
|
59
|
+
code: str('应用编码,宿主权限 code 前缀 apps:<code>'),
|
|
60
|
+
name: str('应用名称'),
|
|
61
|
+
description: str('描述'),
|
|
62
|
+
tenantMode: str('租户模式:client 租户由宿主提供,independent 子应用本地租户(宿主同步的租户由宿主接管)'),
|
|
63
|
+
serviceClientId: str('首次注册该应用的服务 client_id'),
|
|
64
|
+
clientIds: any('子应用登录用的 client_id 列表'),
|
|
65
|
+
resource: str('子应用资源服务 identifier'),
|
|
66
|
+
permissions: any('子应用权限树(不含 apps 前缀)'),
|
|
67
|
+
permissionsHash: str('权限树摘要'),
|
|
68
|
+
permissionCount: num('权限树中的权限点数量'),
|
|
69
|
+
tenantSyncUri: str('independent 模式接收租户变更通知的地址'),
|
|
70
|
+
registeredAt: any('最近一次注册时间'),
|
|
71
|
+
status: str('状态:open 启用,closed 停用(removed 已删除的不会出现在列表与详情中)'),
|
|
72
|
+
...timestamps()
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const key = obj('签名密钥(不含私钥)', {
|
|
76
|
+
id: any('记录 ID'),
|
|
77
|
+
kid: str('JWK kid'),
|
|
78
|
+
alg: str('签名算法'),
|
|
79
|
+
status: str('状态:active 当前签名,next 已发布待启用,retired 已退役仅用于验签'),
|
|
80
|
+
activatedAt: any('启用时间'),
|
|
81
|
+
retiredAt: any('退役时间'),
|
|
82
|
+
createdAt: any('创建时间')
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const tenantList = {
|
|
86
|
+
type: 'object',
|
|
87
|
+
additionalProperties: true,
|
|
88
|
+
properties: {
|
|
89
|
+
list: list(
|
|
90
|
+
'可用租户列表(只含启用状态的成员身份与租户)',
|
|
91
|
+
obj('租户', {
|
|
92
|
+
tenantId: str('租户 ID'),
|
|
93
|
+
tenantUserId: str('用户在该租户的成员 ID'),
|
|
94
|
+
name: str('租户名称'),
|
|
95
|
+
logo: any('租户 logo 文件 ID'),
|
|
96
|
+
companyName: str('公司名称')
|
|
97
|
+
})
|
|
98
|
+
),
|
|
99
|
+
defaultTenantId: str('默认租户 ID;默认租户不在列表中时取列表第一个,列表为空时为 null')
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
module.exports = { str, num, bool, any, strArray, list, obj, timestamps, success, empty, pageResult, STATUS, client, resourceServer, app, key, tenantList };
|
|
@@ -61,6 +61,18 @@ module.exports = fp(async (fastify, options) => {
|
|
|
61
61
|
if (prompt.name === 'tenant' && session?.accountId) {
|
|
62
62
|
output.tenants = await identity.listTenants(session.accountId, services.app.scopeOfClient(params.client_id));
|
|
63
63
|
}
|
|
64
|
+
if (prompt.name === 'mfa' && session?.accountId) {
|
|
65
|
+
const current = await services.sessionTenant.get({ sessionUid: session.uid });
|
|
66
|
+
const mfa = current ? await identity.getTenantMfa(current.tenantId) : { enabled: false };
|
|
67
|
+
output.mfa = {
|
|
68
|
+
method: 'sms',
|
|
69
|
+
tenantId: current?.tenantId || null,
|
|
70
|
+
maxAge: mfa.maxAge ?? null,
|
|
71
|
+
phoneMissing: !output.user?.phone,
|
|
72
|
+
phoneMasked: output.user?.phone ? services.mfa.maskPhone(output.user.phone) : null,
|
|
73
|
+
resendAfter: await services.mfa.getChallengeState({ interactionUid: interaction.uid })
|
|
74
|
+
};
|
|
75
|
+
}
|
|
64
76
|
return output;
|
|
65
77
|
};
|
|
66
78
|
|
|
@@ -89,6 +101,35 @@ module.exports = fp(async (fastify, options) => {
|
|
|
89
101
|
return finish({ provider, request, reply, result: { tenant: { tenantId: String(tenantId) } } });
|
|
90
102
|
};
|
|
91
103
|
|
|
104
|
+
// 租户开启 MFA 但账号没有手机号:直接以 access_denied 结束交互
|
|
105
|
+
const mfaSend = async ({ request, reply, uid }) => {
|
|
106
|
+
const { provider, interaction } = await loadInteraction({ request, reply, uid, prompt: 'mfa' });
|
|
107
|
+
const accountId = interaction.session?.accountId;
|
|
108
|
+
const user = accountId && (await getIdp().identity.getUser(accountId));
|
|
109
|
+
if (!user?.phone) {
|
|
110
|
+
return finish({
|
|
111
|
+
provider,
|
|
112
|
+
request,
|
|
113
|
+
reply,
|
|
114
|
+
result: { error: 'access_denied', error_description: await translator.t(request, 'mfaPhoneRequired') },
|
|
115
|
+
merge: false
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
return services.mfa.sendCode({ interactionUid: interaction.uid, accountId, phone: user.phone });
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const mfaVerify = async ({ request, reply, uid, code }) => {
|
|
122
|
+
const { provider, interaction } = await loadInteraction({ request, reply, uid, prompt: 'mfa' });
|
|
123
|
+
const { session } = interaction;
|
|
124
|
+
const { method } = await services.mfa.verifyCode({ interactionUid: interaction.uid, accountId: session.accountId, code });
|
|
125
|
+
await services.mfa.markSession({ sessionUid: session.uid, accountId: session.accountId, method });
|
|
126
|
+
// 重新提交 login 以把 amr 写进会话(id_token 的 amr),沿用原登录时间保持 auth_time 不变
|
|
127
|
+
const current = await provider.Session.findByUid(session.uid);
|
|
128
|
+
const amr = [...new Set([...(current?.amr || session.amr || ['pwd']), method, 'mfa'])];
|
|
129
|
+
const login = Object.assign({ accountId: session.accountId, amr, remember: !current?.transient }, current?.loginTs ? { ts: current.loginTs } : {}, current?.acr ? { acr: current.acr } : {});
|
|
130
|
+
return finish({ provider, request, reply, result: { login, mfa: { accountId: session.accountId, method } } });
|
|
131
|
+
};
|
|
132
|
+
|
|
92
133
|
const confirm = async ({ request, reply, uid }) => {
|
|
93
134
|
const { provider, interaction } = await loadInteraction({ request, reply, uid, prompt: 'consent' });
|
|
94
135
|
const { params, session, prompt } = interaction;
|
|
@@ -115,5 +156,5 @@ module.exports = fp(async (fastify, options) => {
|
|
|
115
156
|
});
|
|
116
157
|
};
|
|
117
158
|
|
|
118
|
-
services.interaction = { details, login, selectTenant, confirm, abort };
|
|
159
|
+
services.interaction = { details, login, selectTenant, mfaSend, mfaVerify, confirm, abort };
|
|
119
160
|
});
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
const fp = require('fastify-plugin');
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
const httpErrors = require('http-errors');
|
|
4
|
+
const { deriveKey } = require('../utils/crypto');
|
|
5
|
+
const { createError } = require('../utils/intl');
|
|
6
|
+
|
|
7
|
+
const { BadRequest } = httpErrors;
|
|
8
|
+
|
|
9
|
+
const maskPhone = phone => {
|
|
10
|
+
const value = String(phone);
|
|
11
|
+
return value.length > 7 ? `${value.slice(0, 3)}****${value.slice(-4)}` : `****${value.slice(-2)}`;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* OIDC 交互中的短信 MFA:验证码绑定 interaction、只能用一次、限制错误次数和重发间隔;
|
|
16
|
+
* 通过后按会话记录验证时间,供 mfa prompt 按租户 maxAge 判断是否复用
|
|
17
|
+
*/
|
|
18
|
+
module.exports = fp(async (fastify, options) => {
|
|
19
|
+
const { models, services } = fastify[options.name];
|
|
20
|
+
if (!options.runtime.idpEnabled) {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const { codeTTL, maxAttempts, resendInterval, smsType } = options.mfa;
|
|
24
|
+
const hmacKey = deriveKey(options.keyEncryptionSecret, 'mfa');
|
|
25
|
+
|
|
26
|
+
const hashCode = (interactionUid, code) =>
|
|
27
|
+
crypto
|
|
28
|
+
.createHmac('sha256', hmacKey)
|
|
29
|
+
.update(`${interactionUid}:${String(code).trim()}`)
|
|
30
|
+
.digest('base64url');
|
|
31
|
+
|
|
32
|
+
const sameHash = (a, b) => {
|
|
33
|
+
const left = Buffer.from(a);
|
|
34
|
+
const right = Buffer.from(b);
|
|
35
|
+
return left.length === right.length && crypto.timingSafeEqual(left, right);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const getSessionVerifiedAt = async ({ sessionUid, accountId }) => {
|
|
39
|
+
if (!sessionUid) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
const item = await models.sessionMfa.findOne({ where: { sessionUid } });
|
|
43
|
+
return item && item.accountId === String(accountId) ? item.verifiedAt : null;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const markSession = async ({ sessionUid, accountId, method }) => {
|
|
47
|
+
const values = { accountId: String(accountId), method, verifiedAt: new Date() };
|
|
48
|
+
const item = await models.sessionMfa.findOne({ where: { sessionUid } });
|
|
49
|
+
if (item) {
|
|
50
|
+
await item.update(values);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
await models.sessionMfa.create(Object.assign({ sessionUid }, values));
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const removeSession = async ({ sessionUid }) => {
|
|
57
|
+
await models.sessionMfa.destroy({ where: { sessionUid } });
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const resendAfter = challenge => (challenge ? Math.max(Math.ceil((new Date(challenge.sentAt).getTime() + resendInterval * 1000 - Date.now()) / 1000), 0) : 0);
|
|
61
|
+
|
|
62
|
+
const getChallengeState = async ({ interactionUid }) => resendAfter(await models.mfaChallenge.findOne({ where: { interactionUid } }));
|
|
63
|
+
|
|
64
|
+
const sendCode = async ({ interactionUid, accountId, phone }) => {
|
|
65
|
+
const account = fastify[options.accountNamespace];
|
|
66
|
+
if (typeof account?.services?.account?.sendVerificationCode !== 'function') {
|
|
67
|
+
throw new Error('fastify-oidc: 短信 MFA 需要 @kne/fastify-account 提供 services.account.sendVerificationCode');
|
|
68
|
+
}
|
|
69
|
+
const existing = await models.mfaChallenge.findOne({ where: { interactionUid } });
|
|
70
|
+
const wait = resendAfter(existing);
|
|
71
|
+
if (wait > 0) {
|
|
72
|
+
throw createError(BadRequest, 'mfaResendTooFrequent', { seconds: wait });
|
|
73
|
+
}
|
|
74
|
+
const code = await account.services.account.sendVerificationCode({ name: phone, type: smsType, options: { purpose: 'mfa' } });
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const values = {
|
|
77
|
+
accountId: String(accountId),
|
|
78
|
+
method: 'sms',
|
|
79
|
+
codeHash: hashCode(interactionUid, code),
|
|
80
|
+
attempts: 0,
|
|
81
|
+
status: 'pending',
|
|
82
|
+
sentAt: new Date(now),
|
|
83
|
+
expiresAt: new Date(now + codeTTL * 1000)
|
|
84
|
+
};
|
|
85
|
+
if (existing) {
|
|
86
|
+
await existing.update(values);
|
|
87
|
+
} else {
|
|
88
|
+
await models.mfaChallenge.create(Object.assign({ interactionUid }, values));
|
|
89
|
+
}
|
|
90
|
+
return { phoneMasked: maskPhone(phone), expiresIn: codeTTL, resendAfter: resendInterval };
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const verifyCode = async ({ interactionUid, accountId, code }) => {
|
|
94
|
+
const challenge = await models.mfaChallenge.findOne({ where: { interactionUid } });
|
|
95
|
+
if (!challenge || challenge.accountId !== String(accountId) || challenge.status === 'verified') {
|
|
96
|
+
throw createError(BadRequest, 'mfaCodeInvalid');
|
|
97
|
+
}
|
|
98
|
+
if (challenge.status === 'locked') {
|
|
99
|
+
throw createError(BadRequest, 'mfaTooManyAttempts');
|
|
100
|
+
}
|
|
101
|
+
if (new Date(challenge.expiresAt).getTime() < Date.now()) {
|
|
102
|
+
throw createError(BadRequest, 'mfaCodeExpired');
|
|
103
|
+
}
|
|
104
|
+
if (!sameHash(challenge.codeHash, hashCode(interactionUid, code))) {
|
|
105
|
+
const attempts = challenge.attempts + 1;
|
|
106
|
+
const locked = attempts >= maxAttempts;
|
|
107
|
+
await models.mfaChallenge.update({ attempts, status: locked ? 'locked' : 'pending' }, { where: { id: challenge.id, status: 'pending' } });
|
|
108
|
+
throw createError(BadRequest, locked ? 'mfaTooManyAttempts' : 'mfaCodeInvalid');
|
|
109
|
+
}
|
|
110
|
+
// 条件更新保证并发提交同一个验证码时只有一次成功
|
|
111
|
+
const [count] = await models.mfaChallenge.update({ status: 'verified' }, { where: { id: challenge.id, status: 'pending' } });
|
|
112
|
+
if (count === 0) {
|
|
113
|
+
throw createError(BadRequest, 'mfaCodeInvalid');
|
|
114
|
+
}
|
|
115
|
+
return { method: challenge.method };
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const cleanup = async ({ olderThan }) => {
|
|
119
|
+
const { Op } = fastify.sequelize.Sequelize;
|
|
120
|
+
await models.mfaChallenge.destroy({ where: { expiresAt: { [Op.lt]: new Date() } } });
|
|
121
|
+
await models.sessionMfa.destroy({ where: { updatedAt: { [Op.lt]: olderThan } } });
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
services.mfa = { maskPhone, getSessionVerifiedAt, markSession, removeSession, getChallengeState, sendCode, verifyCode, cleanup };
|
|
125
|
+
});
|