@kne/fastify-oidc 0.1.13 → 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/interaction.js +47 -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/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/services/interaction.js +42 -1
- package/libs/services/mfa.js +125 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ npm i --save @kne/fastify-oidc
|
|
|
53
53
|
| 环节 | 实现 | 说明 |
|
|
54
54
|
|------|------|------|
|
|
55
55
|
| 协议端点 | `libs/idp/mount.js` | 把 `mountPath`(默认 `/oidc`)下的请求原样交给 oidc-provider |
|
|
56
|
-
| 交互 | `libs/services/interaction.js` |
|
|
56
|
+
| 交互 | `libs/services/interaction.js` | 登录、选择租户、短信 MFA、授权确认、取消,返回 `{ redirectTo }` 由前端跳转 |
|
|
57
57
|
| 账号 / 租户桥接 | `libs/idp/identity.js` | 唯一依赖 fastify-account / fastify-tenant 的地方 |
|
|
58
58
|
| 资源侧鉴权 | `libs/resource/*` | JWT 验签、DPoP、撤销列表、`request.user` 归一化、legacy token 回退 |
|
|
59
59
|
| 管理 | `libs/controllers/admin.js` | client、资源服务、签名密钥、会话 |
|
|
@@ -87,6 +87,21 @@ client 只能申请 `allowedResources` 中的资源;子项目 token 的 `aud`
|
|
|
87
87
|
|
|
88
88
|
token 中的租户相关 claim 以命名空间为前缀(默认 `${ORIGIN}/`,central 模式为 issuer 的 origin):`tenant_id`、`tenant_user_id`、`roles`、`permissions`(按资源服务 `includePermissions` 决定是否携带)。
|
|
89
89
|
|
|
90
|
+
##### 租户短信 MFA
|
|
91
|
+
|
|
92
|
+
租户在 fastify-tenant 的 MFA 设置(`/api/tenant/mfa-setting`)中开启后,`tenant` 之后会出现 `mfa` 步骤,前端调用 `mfa/send` 发码、`mfa/verify` 校验:
|
|
93
|
+
|
|
94
|
+
| 情况 | 行为 |
|
|
95
|
+
|------|------|
|
|
96
|
+
| 租户未开启 MFA,或宿主 fastify-tenant 版本没有 MFA 设置 | 跳过 |
|
|
97
|
+
| 本会话距上次 MFA 验证未超过租户的 `maxAge`(秒) | 跳过(同一会话切到另一个开启 MFA 的租户时,按该租户的 `maxAge` 判断) |
|
|
98
|
+
| 超过 `maxAge` 或从未验证 | 前端展示短信验证(`prompt=none` 时返回 `interaction_required`) |
|
|
99
|
+
| 账号没有手机号 | `mfa/send` 以 `access_denied` 结束授权,需管理员先给账号绑定手机号 |
|
|
100
|
+
|
|
101
|
+
- 验证码通过 fastify-account 的 `sendVerificationCode` 发送(`type` 默认 `6`),宿主的 `sendMessage` 必须处理该类型的短信,否则验证码发不出去
|
|
102
|
+
- 验证码绑定交互、只能使用一次,错误 5 次锁定,60 秒内不能重发(可通过 `mfa` 选项调整)
|
|
103
|
+
- 通过后 id_token 的 `amr` 为 `['pwd', 'sms', 'mfa']`,RP 可据此判断;已签发的 refresh_token 不受之后开启的 MFA 影响
|
|
104
|
+
|
|
90
105
|
##### 令牌撤销
|
|
91
106
|
|
|
92
107
|
JWT access_token 无法真正撤销,插件在资源侧维护一个撤销列表:
|
|
@@ -362,6 +377,15 @@ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求
|
|
|
362
377
|
|
|
363
378
|
`getAuthenticate` 默认:`*:manage` 返回 `[authenticate.user, authenticate.admin]`,其余返回 `[authenticate.user]`。
|
|
364
379
|
|
|
380
|
+
`mfa` 默认值(租户短信 MFA,是否开启与有效期由 fastify-tenant 的租户 MFA 设置决定,见「租户短信 MFA」):
|
|
381
|
+
|
|
382
|
+
| 键 | 默认值 | 说明 |
|
|
383
|
+
|----|--------|------|
|
|
384
|
+
| codeTTL | `300` | 验证码有效期(秒) |
|
|
385
|
+
| maxAttempts | `5` | 同一验证码最多错误次数,达到后锁定,需重新发送 |
|
|
386
|
+
| resendInterval | `60` | 重新发送的最小间隔(秒) |
|
|
387
|
+
| smsType | `6` | 调用 fastify-account `sendVerificationCode` 时的 `type`,宿主的 `sendMessage` 需处理该类型的短信 |
|
|
388
|
+
|
|
365
389
|
##### 资源侧
|
|
366
390
|
|
|
367
391
|
| 属性名 | 类型 | 必填 | 默认值 | 说明 |
|
|
@@ -463,7 +487,7 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
|
|
|
463
487
|
}
|
|
464
488
|
```
|
|
465
489
|
|
|
466
|
-
`prompt.name` 为 `login` / `tenant` / `consent`;已登录时 `user` 为 `{ id, nickname, avatar, email, phone }`;`tenant` 步骤时 `tenants` 为 `{ list: [{ tenantId, tenantUserId, name, logo, companyName }], defaultTenantId }`。
|
|
490
|
+
`prompt.name` 为 `login` / `tenant` / `mfa` / `consent`;已登录时 `user` 为 `{ id, nickname, avatar, email, phone }`;`tenant` 步骤时 `tenants` 为 `{ list: [{ tenantId, tenantUserId, name, logo, companyName }], defaultTenantId }`;`mfa` 步骤时 `mfa` 为 `{ method: 'sms', tenantId, maxAge, phoneMissing, phoneMasked, resendAfter }`。
|
|
467
491
|
|
|
468
492
|
###### POST /api/oidc/interaction/{uid}/login
|
|
469
493
|
|
|
@@ -480,6 +504,14 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
|
|
|
480
504
|
|
|
481
505
|
参数 `tenantId`(必填)。只能选择当前用户所属且开启的租户。
|
|
482
506
|
|
|
507
|
+
###### POST /api/oidc/interaction/{uid}/mfa/send
|
|
508
|
+
|
|
509
|
+
`mfa` 步骤发送短信验证码到账号绑定的手机号,返回 `{ phoneMasked, expiresIn, resendAfter }`;发送间隔内重复调用返回 400。账号没有手机号时以 `access_denied` 结束交互,返回 `{ redirectTo }`。
|
|
510
|
+
|
|
511
|
+
###### POST /api/oidc/interaction/{uid}/mfa/verify
|
|
512
|
+
|
|
513
|
+
参数 `code`(必填)。验证码错误、过期或错误次数过多返回 400;通过后返回 `{ redirectTo }`,本次登录的 id_token `amr` 为 `['pwd', 'sms', 'mfa']`,`auth_time` 保持原登录时间。
|
|
514
|
+
|
|
483
515
|
###### POST /api/oidc/interaction/{uid}/confirm
|
|
484
516
|
|
|
485
517
|
确认授权(`skip_consent: false` 的 client 才会出现 consent 步骤)。
|
|
@@ -712,6 +744,29 @@ central 模式下主项目的 `avatar` 是主项目文件库的 id,子项目
|
|
|
712
744
|
| accountId | string | 用户 id |
|
|
713
745
|
| tenantId | string | 会话当前租户 |
|
|
714
746
|
|
|
747
|
+
##### sessionMfa(`t_oidc_session_mfa`)
|
|
748
|
+
|
|
749
|
+
| 属性名 | 类型 | 说明 |
|
|
750
|
+
|--------|------|------|
|
|
751
|
+
| sessionUid | string | IdP 会话 uid(唯一) |
|
|
752
|
+
| accountId | string | 用户 id |
|
|
753
|
+
| method | string | 验证方式,如 `sms` |
|
|
754
|
+
| verifiedAt | Date | 本会话最近一次通过 MFA 的时间 |
|
|
755
|
+
|
|
756
|
+
##### mfaChallenge(`t_oidc_mfa_challenge`)
|
|
757
|
+
|
|
758
|
+
| 属性名 | 类型 | 说明 |
|
|
759
|
+
|--------|------|------|
|
|
760
|
+
| interactionUid | string | 交互 uid(唯一),验证码只在该次交互内有效 |
|
|
761
|
+
| accountId | string | 用户 id |
|
|
762
|
+
| method | string | 验证方式 |
|
|
763
|
+
| codeHash | string | 验证码 HMAC,不存明文 |
|
|
764
|
+
| attempts | number | 已错误次数 |
|
|
765
|
+
| status | string | `pending` 待验证 / `verified` 已使用 / `locked` 错误次数过多 |
|
|
766
|
+
| sentAt / expiresAt | Date | 最近发送时间 / 过期时间 |
|
|
767
|
+
|
|
768
|
+
新表由 `sequelize.sync()` 创建,无需迁移脚本。
|
|
769
|
+
|
|
715
770
|
##### app(`t_oidc_app`)
|
|
716
771
|
|
|
717
772
|
| 属性名 | 类型 | 说明 |
|
package/index.js
CHANGED
|
@@ -85,6 +85,7 @@ module.exports = fp(
|
|
|
85
85
|
options
|
|
86
86
|
);
|
|
87
87
|
options.ttl = Object.assign({ accessToken: 10 * 60, idToken: 60 * 60, refreshToken: 14 * DAY, interaction: 10 * 60, session: 14 * DAY, grant: 14 * DAY }, options.ttl);
|
|
88
|
+
options.mfa = Object.assign({ codeTTL: 5 * 60, maxAttempts: 5, resendInterval: 60, smsType: 6 }, options.mfa);
|
|
88
89
|
options.serviceClient = Object.assign({ clientId: env.OIDC_SERVICE_CLIENT_ID, clientSecret: env.OIDC_SERVICE_CLIENT_SECRET }, options.serviceClient);
|
|
89
90
|
// 代码里的 app 作默认值(如 tenantMode),部署时宿主注入的环境变量优先;最终没有 code 视为未作为子应用部署
|
|
90
91
|
const envApp = pickBy({ code: env.OIDC_APP_CODE, name: env.OIDC_APP_NAME, tenantMode: env.OIDC_APP_TENANT_MODE, tenantSyncUri: env.OIDC_APP_TENANT_SYNC_URI });
|
|
@@ -39,7 +39,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
39
39
|
properties: {
|
|
40
40
|
uid: str('交互 uid'),
|
|
41
41
|
prompt: obj('当前步骤', {
|
|
42
|
-
name: str('步骤:login 登录,tenant 选择租户,consent 确认授权'),
|
|
42
|
+
name: str('步骤:login 登录,tenant 选择租户,mfa 多因素认证(短信),consent 确认授权'),
|
|
43
43
|
reasons: any('需要该步骤的原因'),
|
|
44
44
|
details: any('步骤详情(如缺少的 scope)')
|
|
45
45
|
}),
|
|
@@ -64,7 +64,15 @@ module.exports = fp(async (fastify, options) => {
|
|
|
64
64
|
email: str('邮箱'),
|
|
65
65
|
phone: str('手机号')
|
|
66
66
|
}),
|
|
67
|
-
tenants: obj('可选租户(仅 tenant 步骤返回,否则为 null):{ list, defaultTenantId }')
|
|
67
|
+
tenants: obj('可选租户(仅 tenant 步骤返回,否则为 null):{ list, defaultTenantId }'),
|
|
68
|
+
mfa: obj('多因素认证信息(仅 mfa 步骤返回)', {
|
|
69
|
+
method: str('验证方式,目前固定为 sms'),
|
|
70
|
+
tenantId: str('要求验证的租户 ID'),
|
|
71
|
+
maxAge: any('租户配置的 MFA 有效期(秒)'),
|
|
72
|
+
phoneMissing: any('账号没有手机号时为 true,此时无法完成验证,调用 mfa/send 会以 access_denied 结束交互'),
|
|
73
|
+
phoneMasked: str('脱敏手机号'),
|
|
74
|
+
resendAfter: any('距离可以重新发送验证码的秒数,0 表示可以发送')
|
|
75
|
+
})
|
|
68
76
|
}
|
|
69
77
|
})
|
|
70
78
|
}
|
|
@@ -121,6 +129,43 @@ module.exports = fp(async (fastify, options) => {
|
|
|
121
129
|
wrap(async (request, reply) => services.interaction.selectTenant({ request, reply, uid: request.params.uid, tenantId: request.body.tenantId }))
|
|
122
130
|
);
|
|
123
131
|
|
|
132
|
+
fastify.post(
|
|
133
|
+
`${base}/mfa/send`,
|
|
134
|
+
{
|
|
135
|
+
schema: {
|
|
136
|
+
tags,
|
|
137
|
+
summary: '发送 MFA 短信验证码',
|
|
138
|
+
description: `仅 mfa 步骤可调用,${HINT}。验证码发到账号绑定的手机号,只在本次交互内有效;发送间隔内重复调用返回 400。账号没有手机号时以 access_denied 结束交互并返回 redirectTo`,
|
|
139
|
+
params,
|
|
140
|
+
response: success('发送结果', {
|
|
141
|
+
type: 'object',
|
|
142
|
+
properties: {
|
|
143
|
+
phoneMasked: str('脱敏手机号'),
|
|
144
|
+
expiresIn: any('验证码有效期(秒)'),
|
|
145
|
+
resendAfter: any('距离可以重新发送的秒数'),
|
|
146
|
+
redirectTo: str('账号没有手机号、交互已结束时前端需要跳转的地址')
|
|
147
|
+
}
|
|
148
|
+
})
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
wrap(async (request, reply) => services.interaction.mfaSend({ request, reply, uid: request.params.uid }))
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
fastify.post(
|
|
155
|
+
`${base}/mfa/verify`,
|
|
156
|
+
{
|
|
157
|
+
schema: {
|
|
158
|
+
tags,
|
|
159
|
+
summary: '校验 MFA 短信验证码',
|
|
160
|
+
description: `仅 mfa 步骤可调用,${HINT}。验证码错误、过期或错误次数过多返回 400,错误次数过多后需重新发送;通过后返回 redirectTo,id_token 的 amr 会包含 sms、mfa`,
|
|
161
|
+
params,
|
|
162
|
+
body: { type: 'object', required: ['code'], properties: { code: { type: 'string', description: '短信验证码' } } },
|
|
163
|
+
response: redirect('验证通过')
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
wrap(async (request, reply) => services.interaction.mfaVerify({ request, reply, uid: request.params.uid, code: request.body.code }))
|
|
167
|
+
);
|
|
168
|
+
|
|
124
169
|
fastify.post(
|
|
125
170
|
`${base}/confirm`,
|
|
126
171
|
{
|
|
@@ -107,8 +107,36 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
|
|
|
107
107
|
return interactionPolicy.Check.REQUEST_PROMPT;
|
|
108
108
|
});
|
|
109
109
|
|
|
110
|
+
// 在 tenant 之后执行:tenantCheck 已把本次选定的租户写入 sessionTenant
|
|
111
|
+
const mfaCheck = new interactionPolicy.Check('mfa_required', '需要多因素认证', async ctx => {
|
|
112
|
+
const { oidc } = ctx;
|
|
113
|
+
const accountId = oidc.session.accountId;
|
|
114
|
+
if (!accountId || !identity.tenantEnabled()) {
|
|
115
|
+
return interactionPolicy.Check.NO_NEED_TO_PROMPT;
|
|
116
|
+
}
|
|
117
|
+
// 本次授权刚完成验证(maxAge 为 0 时也不会重复要求)
|
|
118
|
+
if (oidc.result?.mfa && String(oidc.result.mfa.accountId) === String(accountId)) {
|
|
119
|
+
return interactionPolicy.Check.NO_NEED_TO_PROMPT;
|
|
120
|
+
}
|
|
121
|
+
const sessionUid = oidc.session.uid;
|
|
122
|
+
const current = await services.sessionTenant.get({ sessionUid });
|
|
123
|
+
if (!current || current.accountId !== String(accountId) || !(await identity.isTenantMember(accountId, current.tenantId, services.app.scopeOfClient(oidc.client.clientId)))) {
|
|
124
|
+
return interactionPolicy.Check.NO_NEED_TO_PROMPT;
|
|
125
|
+
}
|
|
126
|
+
const mfa = await identity.getTenantMfa(current.tenantId);
|
|
127
|
+
if (!mfa.enabled) {
|
|
128
|
+
return interactionPolicy.Check.NO_NEED_TO_PROMPT;
|
|
129
|
+
}
|
|
130
|
+
const verifiedAt = await services.mfa.getSessionVerifiedAt({ sessionUid, accountId });
|
|
131
|
+
if (verifiedAt && Date.now() - new Date(verifiedAt).getTime() <= mfa.maxAge * 1000) {
|
|
132
|
+
return interactionPolicy.Check.NO_NEED_TO_PROMPT;
|
|
133
|
+
}
|
|
134
|
+
return interactionPolicy.Check.REQUEST_PROMPT;
|
|
135
|
+
});
|
|
136
|
+
|
|
110
137
|
const policy = interactionPolicy.base();
|
|
111
138
|
policy.add(new interactionPolicy.Prompt({ name: 'tenant', requestable: false }, ctx => ({ tenant_id: ctx.oidc.params.tenant_id }), tenantCheck), 1);
|
|
139
|
+
policy.add(new interactionPolicy.Prompt({ name: 'mfa', requestable: false }, () => ({}), mfaCheck), 2);
|
|
112
140
|
|
|
113
141
|
const ttl = options.ttl;
|
|
114
142
|
const configuration = {
|
|
@@ -119,7 +147,8 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
|
|
|
119
147
|
keys: [deriveKey(options.cookieSecret || options.keyEncryptionSecret, 'cookie').toString('base64url')]
|
|
120
148
|
},
|
|
121
149
|
claims: {
|
|
122
|
-
openid
|
|
150
|
+
// amr 归到 openid scope 才会写进 id_token,RP 据此判断本次登录是否做过 MFA(含 sms、mfa)
|
|
151
|
+
openid: ['sub', 'amr'],
|
|
123
152
|
profile: ['name', 'nickname', 'picture', 'gender', 'birthdate'],
|
|
124
153
|
email: ['email'],
|
|
125
154
|
phone: ['phone_number']
|
|
@@ -280,6 +309,7 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
|
|
|
280
309
|
}
|
|
281
310
|
if (!(await getAdapter('Session').findByUid(session.uid))) {
|
|
282
311
|
await services.sessionTenant.remove({ sessionUid: session.uid });
|
|
312
|
+
await services.mfa.removeSession({ sessionUid: session.uid });
|
|
283
313
|
}
|
|
284
314
|
} catch (e) {
|
|
285
315
|
fastify.log.warn({ err: e }, 'fastify-oidc: 登出后清理会话失败');
|
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/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
|
+
};
|
|
@@ -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
|
+
});
|