@kne/fastify-oidc 0.1.13 → 0.1.15
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 +24 -2
- package/libs/controllers/config.js +38 -12
- 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 +7 -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/resource/verify-token.js +56 -19
- package/libs/services/interaction.js +42 -1
- package/libs/services/mfa.js +125 -0
- package/libs/utils/platform-assertion.js +108 -0
- package/libs/utils/platforms.js +110 -0
- package/package.json +7 -2
- package/platform-assertion.js +1 -0
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
|
@@ -13,6 +13,8 @@ const createAuthenticate = require('./libs/resource/authenticate');
|
|
|
13
13
|
const createTenantSync = require('./libs/resource/tenant-sync');
|
|
14
14
|
const createAppRegistry = require('./libs/resource/app-registry');
|
|
15
15
|
const createRemoteTenant = require('./libs/resource/remote-tenant');
|
|
16
|
+
const { createPlatformsRegistry } = require('./libs/utils/platforms');
|
|
17
|
+
const { createPlatformAssertionSigner, createPlatformAssertionVerifier, createMemoryJtiStore } = require('./libs/utils/platform-assertion');
|
|
16
18
|
const { locale, createTranslator } = require('./libs/utils/intl');
|
|
17
19
|
|
|
18
20
|
const DAY = 24 * 60 * 60;
|
|
@@ -57,6 +59,8 @@ module.exports = fp(
|
|
|
57
59
|
fileNamespace: 'fileManager',
|
|
58
60
|
clients: [],
|
|
59
61
|
resourceServers: [],
|
|
62
|
+
/** central 多平台:初始 platforms[],也可运行时 platforms.setAll / upsert */
|
|
63
|
+
platforms: [],
|
|
60
64
|
seedSelf: true,
|
|
61
65
|
selfClient: {},
|
|
62
66
|
serviceScopes: ['user:read', 'tenant:read', 'app:register', 'tenant:sync'],
|
|
@@ -85,6 +89,7 @@ module.exports = fp(
|
|
|
85
89
|
options
|
|
86
90
|
);
|
|
87
91
|
options.ttl = Object.assign({ accessToken: 10 * 60, idToken: 60 * 60, refreshToken: 14 * DAY, interaction: 10 * 60, session: 14 * DAY, grant: 14 * DAY }, options.ttl);
|
|
92
|
+
options.mfa = Object.assign({ codeTTL: 5 * 60, maxAttempts: 5, resendInterval: 60, smsType: 6 }, options.mfa);
|
|
88
93
|
options.serviceClient = Object.assign({ clientId: env.OIDC_SERVICE_CLIENT_ID, clientSecret: env.OIDC_SERVICE_CLIENT_SECRET }, options.serviceClient);
|
|
89
94
|
// 代码里的 app 作默认值(如 tenantMode),部署时宿主注入的环境变量优先;最终没有 code 视为未作为子应用部署
|
|
90
95
|
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 });
|
|
@@ -108,7 +113,23 @@ module.exports = fp(
|
|
|
108
113
|
const translator = createTranslator({ fastify, options });
|
|
109
114
|
const idp = runtime.idpEnabled ? createIdp({ fastify, options, translator }) : null;
|
|
110
115
|
const revocation = createRevocation({ store: options.revocationStore, ttl: Math.max(options.ttl.accessToken, options.ttl.idToken) + options.clockTolerance });
|
|
111
|
-
const
|
|
116
|
+
const platforms = createPlatformsRegistry({ initial: options.platforms || [] });
|
|
117
|
+
const verifier = createVerifier({
|
|
118
|
+
options,
|
|
119
|
+
getLocalJWKS: idp ? () => idp.getLocalJWKS() : null,
|
|
120
|
+
getPlatforms: () => platforms.getAll()
|
|
121
|
+
});
|
|
122
|
+
let readyPromise = Promise.resolve();
|
|
123
|
+
const platformAssertion = idp
|
|
124
|
+
? createPlatformAssertionSigner({
|
|
125
|
+
issuer: runtime.issuer,
|
|
126
|
+
clockTolerance: options.clockTolerance,
|
|
127
|
+
getPrivateJwk: async () => {
|
|
128
|
+
await readyPromise;
|
|
129
|
+
return idp.getSigningJwk();
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
: createPlatformAssertionVerifier({ clockTolerance: options.clockTolerance, jtiStore: createMemoryJtiStore() });
|
|
112
133
|
const serviceClient = createServiceClient({ options });
|
|
113
134
|
const userMirror = createUserMirror({ fastify, options, serviceClient });
|
|
114
135
|
const dpop = createDPoP({ clockTolerance: options.clockTolerance, replayStore: options.dpopReplayStore });
|
|
@@ -138,7 +159,6 @@ module.exports = fp(
|
|
|
138
159
|
]);
|
|
139
160
|
}
|
|
140
161
|
|
|
141
|
-
let readyPromise = Promise.resolve();
|
|
142
162
|
if (idp) {
|
|
143
163
|
readyPromise = fastify.sequelize.syncPromise.then(() => idp.init());
|
|
144
164
|
readyPromise.catch(err => fastify.log.error({ err }, 'fastify-oidc: IdP 初始化失败'));
|
|
@@ -156,6 +176,8 @@ module.exports = fp(
|
|
|
156
176
|
['idp', idp],
|
|
157
177
|
['revocation', revocation],
|
|
158
178
|
['verifier', verifier],
|
|
179
|
+
['platforms', platforms],
|
|
180
|
+
['platformAssertion', platformAssertion],
|
|
159
181
|
['serviceClient', serviceClient],
|
|
160
182
|
['userMirror', userMirror],
|
|
161
183
|
['tenantSync', tenantSync],
|
|
@@ -2,10 +2,12 @@ const fp = require('fastify-plugin');
|
|
|
2
2
|
const { str, bool, success } = require('../schema/response');
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
5
|
+
* 前端登录方式发现:免登录,只返回公开信息,不能包含任何密钥。
|
|
6
|
+
* 多平台 central:附带 platforms[],前端选平台或用 ?iss= / ?platform=。
|
|
6
7
|
*/
|
|
7
8
|
module.exports = fp(async (fastify, options) => {
|
|
8
9
|
const { runtime } = options;
|
|
10
|
+
const oidc = () => fastify[options.name];
|
|
9
11
|
|
|
10
12
|
fastify.get(
|
|
11
13
|
`${options.prefix}/config`,
|
|
@@ -13,25 +15,49 @@ module.exports = fp(async (fastify, options) => {
|
|
|
13
15
|
schema: {
|
|
14
16
|
tags: ['OIDC-配置'],
|
|
15
17
|
summary: '获取前端登录配置(免登录)',
|
|
16
|
-
description: '前端据此决定登录方式(发起 OIDC 授权的 issuer、client_id、resource
|
|
18
|
+
description: '前端据此决定登录方式(发起 OIDC 授权的 issuer、client_id、resource),只包含公开信息;多平台时含 platforms',
|
|
17
19
|
response: success('前端登录配置', {
|
|
18
20
|
type: 'object',
|
|
19
21
|
properties: {
|
|
20
22
|
mode: str('部署模式:standalone 独立部署(本项目即 IdP),central 由主项目统一登录'),
|
|
21
23
|
isMain: bool('standalone 模式下是否为主项目'),
|
|
22
|
-
issuer: str('OIDC issuer
|
|
23
|
-
clientId: str('
|
|
24
|
-
audience: str('
|
|
24
|
+
issuer: str('默认 OIDC issuer 地址(单平台或兼容字段)'),
|
|
25
|
+
clientId: str('默认前端 client_id'),
|
|
26
|
+
audience: str('默认 resource(API 资源标识)'),
|
|
27
|
+
platforms: {
|
|
28
|
+
type: 'array',
|
|
29
|
+
description: '已配对的多个主平台(公开信息);长度>1 时登录页应选择平台'
|
|
30
|
+
}
|
|
25
31
|
}
|
|
26
32
|
})
|
|
27
33
|
}
|
|
28
34
|
},
|
|
29
|
-
async
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
35
|
+
async request => {
|
|
36
|
+
const platforms = oidc().platforms ? oidc().platforms.publicList() : [];
|
|
37
|
+
const hintIss = request.query?.iss;
|
|
38
|
+
const hintPlatform = request.query?.platform;
|
|
39
|
+
let selected = null;
|
|
40
|
+
if (platforms.length) {
|
|
41
|
+
if (hintIss) {
|
|
42
|
+
selected = platforms.find(p => p.issuer === hintIss || p.issuer === String(hintIss).replace(/\/+$/, ''));
|
|
43
|
+
} else if (hintPlatform) {
|
|
44
|
+
const key = String(hintPlatform).replace(/\/+$/, '').toLowerCase();
|
|
45
|
+
selected = platforms.find(p => p.platformOrigin.toLowerCase() === key || p.platformName === hintPlatform);
|
|
46
|
+
} else if (platforms.length === 1) {
|
|
47
|
+
selected = platforms[0];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const issuer = selected?.issuer || runtime.issuer;
|
|
51
|
+
const clientId = selected?.clientId || runtime.clientId;
|
|
52
|
+
const audience = selected?.audience || runtime.audience;
|
|
53
|
+
return {
|
|
54
|
+
mode: options.mode,
|
|
55
|
+
isMain: options.mode === 'standalone' && !!options.isMain,
|
|
56
|
+
issuer,
|
|
57
|
+
clientId,
|
|
58
|
+
audience,
|
|
59
|
+
platforms
|
|
60
|
+
};
|
|
61
|
+
}
|
|
36
62
|
);
|
|
37
63
|
});
|
|
@@ -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: 定时清理失败');
|
|
@@ -128,6 +129,11 @@ module.exports = ({ fastify, options, translator }) => {
|
|
|
128
129
|
|
|
129
130
|
const close = () => timers.forEach(clearInterval);
|
|
130
131
|
|
|
132
|
+
const getSigningJwk = async () => {
|
|
133
|
+
const { keys } = await getServices().key.getPrivateJwks();
|
|
134
|
+
return (keys && keys[0]) || null;
|
|
135
|
+
};
|
|
136
|
+
|
|
131
137
|
return {
|
|
132
138
|
identity,
|
|
133
139
|
init,
|
|
@@ -137,6 +143,7 @@ module.exports = ({ fastify, options, translator }) => {
|
|
|
137
143
|
getAdapter: name => assertReady().getAdapter(name),
|
|
138
144
|
getLocalJWKS: () => state && state.localJWKS,
|
|
139
145
|
getPublicJwks: () => state && state.publicJwks,
|
|
146
|
+
getSigningJwk,
|
|
140
147
|
handle: (req, res) => assertReady().callback(req, res)
|
|
141
148
|
};
|
|
142
149
|
};
|
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
|
+
};
|
|
@@ -1,29 +1,64 @@
|
|
|
1
|
-
const { jwtVerify, createRemoteJWKSet } = require('jose');
|
|
1
|
+
const { jwtVerify, createRemoteJWKSet, decodeJwt } = require('jose');
|
|
2
2
|
const { createError } = require('../utils/intl');
|
|
3
3
|
const { TENANT_SYNC_EVENT } = require('../utils/app-permissions');
|
|
4
4
|
|
|
5
5
|
const LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* standalone
|
|
8
|
+
* standalone:本进程 JWKS。
|
|
9
|
+
* central 单平台:主项目 jwks_uri。
|
|
10
|
+
* central 多平台:先读 token.iss,命中 platforms 后用对应 JWKS + audience 验签。
|
|
9
11
|
*/
|
|
10
|
-
module.exports = ({ options, getLocalJWKS }) => {
|
|
12
|
+
module.exports = ({ options, getLocalJWKS, getPlatforms }) => {
|
|
11
13
|
const { runtime } = options;
|
|
12
|
-
|
|
14
|
+
const remoteByUri = new Map();
|
|
13
15
|
|
|
14
|
-
const
|
|
16
|
+
const getRemoteJWKS = jwksUri => {
|
|
17
|
+
let set = remoteByUri.get(jwksUri);
|
|
18
|
+
if (!set) {
|
|
19
|
+
set = createRemoteJWKSet(new URL(jwksUri));
|
|
20
|
+
remoteByUri.set(jwksUri, set);
|
|
21
|
+
}
|
|
22
|
+
return set;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const resolveVerifyContext = (token, { audience } = {}) => {
|
|
15
26
|
const local = getLocalJWKS && getLocalJWKS();
|
|
16
27
|
if (local) {
|
|
17
|
-
return local;
|
|
28
|
+
return { jwks: local, issuer: runtime.issuer, audience: audience || runtime.audience };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const platforms = typeof getPlatforms === 'function' ? getPlatforms() : [];
|
|
32
|
+
if (platforms && platforms.length) {
|
|
33
|
+
let iss;
|
|
34
|
+
try {
|
|
35
|
+
iss = decodeJwt(token).iss;
|
|
36
|
+
} catch (e) {
|
|
37
|
+
throw createError(null, 'authenticationFailed');
|
|
38
|
+
}
|
|
39
|
+
const platform = platforms.find(p => p.issuer === iss || p.issuer === String(iss || '').replace(/\/+$/, ''));
|
|
40
|
+
if (!platform || platform.status !== 'paired') {
|
|
41
|
+
throw createError(null, 'authenticationFailed');
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
jwks: getRemoteJWKS(platform.jwksUri || `${platform.issuer}/jwks`),
|
|
45
|
+
issuer: platform.issuer,
|
|
46
|
+
audience: audience || platform.audience || runtime.audience
|
|
47
|
+
};
|
|
18
48
|
}
|
|
19
|
-
remote = remote || createRemoteJWKSet(new URL(runtime.jwksUri));
|
|
20
|
-
return remote;
|
|
21
|
-
};
|
|
22
49
|
|
|
23
|
-
|
|
24
|
-
|
|
50
|
+
return {
|
|
51
|
+
jwks: getRemoteJWKS(runtime.jwksUri),
|
|
25
52
|
issuer: runtime.issuer,
|
|
26
|
-
audience
|
|
53
|
+
audience: audience || runtime.audience
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const verifyAccessToken = async (token, { audience } = {}) => {
|
|
58
|
+
const ctx = resolveVerifyContext(token, { audience });
|
|
59
|
+
const { payload } = await jwtVerify(token, ctx.jwks, {
|
|
60
|
+
issuer: ctx.issuer,
|
|
61
|
+
audience: ctx.audience,
|
|
27
62
|
typ: 'at+jwt',
|
|
28
63
|
clockTolerance: options.clockTolerance
|
|
29
64
|
});
|
|
@@ -31,9 +66,10 @@ module.exports = ({ options, getLocalJWKS }) => {
|
|
|
31
66
|
};
|
|
32
67
|
|
|
33
68
|
const verifyLogoutToken = async (token, { audience }) => {
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
69
|
+
const ctx = resolveVerifyContext(token, { audience });
|
|
70
|
+
const { payload } = await jwtVerify(token, ctx.jwks, {
|
|
71
|
+
issuer: ctx.issuer,
|
|
72
|
+
audience: ctx.audience || audience,
|
|
37
73
|
clockTolerance: options.clockTolerance
|
|
38
74
|
});
|
|
39
75
|
if (!payload.events || typeof payload.events[LOGOUT_EVENT] !== 'object') {
|
|
@@ -49,9 +85,10 @@ module.exports = ({ options, getLocalJWKS }) => {
|
|
|
49
85
|
};
|
|
50
86
|
|
|
51
87
|
const verifyTenantSyncToken = async (token, { audience }) => {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
88
|
+
const ctx = resolveVerifyContext(token, { audience });
|
|
89
|
+
const { payload } = await jwtVerify(token, ctx.jwks, {
|
|
90
|
+
issuer: ctx.issuer,
|
|
91
|
+
audience: ctx.audience || audience,
|
|
55
92
|
typ: 'tenant-sync+jwt',
|
|
56
93
|
clockTolerance: options.clockTolerance,
|
|
57
94
|
requiredClaims: ['jti', 'exp', 'tenant_id']
|
|
@@ -62,5 +99,5 @@ module.exports = ({ options, getLocalJWKS }) => {
|
|
|
62
99
|
return payload;
|
|
63
100
|
};
|
|
64
101
|
|
|
65
|
-
return { verifyAccessToken, verifyLogoutToken, verifyTenantSyncToken };
|
|
102
|
+
return { verifyAccessToken, verifyLogoutToken, verifyTenantSyncToken, resolveVerifyContext };
|
|
66
103
|
};
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
const { SignJWT, jwtVerify, createRemoteJWKSet, importJWK } = require('jose');
|
|
3
|
+
|
|
4
|
+
const ASSERTION_TYP = 'platform-link+jwt';
|
|
5
|
+
const DEFAULT_TTL = 5 * 60;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 主平台签发「平台身份断言」:远程 redeem / activate 用登记 origin 的 JWKS 验签,不信任请求体自报 origin。
|
|
9
|
+
*/
|
|
10
|
+
const createPlatformAssertionSigner = ({ getPrivateJwk, issuer, clockTolerance = 5 }) => {
|
|
11
|
+
if (typeof getPrivateJwk !== 'function') {
|
|
12
|
+
throw new Error('fastify-oidc: createPlatformAssertionSigner 需要 getPrivateJwk');
|
|
13
|
+
}
|
|
14
|
+
if (!issuer) {
|
|
15
|
+
throw new Error('fastify-oidc: createPlatformAssertionSigner 需要 issuer');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const sign = async ({ audience, ttl = DEFAULT_TTL, extra = {} } = {}) => {
|
|
19
|
+
if (!audience) {
|
|
20
|
+
throw new Error('fastify-oidc: platform assertion 需要 audience(远程 baseUrl)');
|
|
21
|
+
}
|
|
22
|
+
const jwk = await getPrivateJwk();
|
|
23
|
+
if (!jwk) {
|
|
24
|
+
throw new Error('fastify-oidc: IdP 私钥尚未就绪,无法签发平台断言');
|
|
25
|
+
}
|
|
26
|
+
const key = await importJWK(jwk, jwk.alg || 'RS256');
|
|
27
|
+
const now = Math.floor(Date.now() / 1000);
|
|
28
|
+
return new SignJWT(Object.assign({}, extra))
|
|
29
|
+
.setProtectedHeader({ alg: jwk.alg || 'RS256', typ: ASSERTION_TYP, kid: jwk.kid })
|
|
30
|
+
.setIssuer(issuer)
|
|
31
|
+
.setAudience(audience)
|
|
32
|
+
.setIssuedAt(now)
|
|
33
|
+
.setExpirationTime(now + ttl)
|
|
34
|
+
.setJti(crypto.randomUUID())
|
|
35
|
+
.sign(key);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
return { sign, typ: ASSERTION_TYP };
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 远程侧验签:用登记时的 jwksUri 验签;jtiStore 可选防重放(async has/add)。
|
|
43
|
+
*/
|
|
44
|
+
const createPlatformAssertionVerifier = ({ clockTolerance = 5, jtiStore = null } = {}) => {
|
|
45
|
+
const jwksCache = new Map();
|
|
46
|
+
|
|
47
|
+
const getJWKS = jwksUri => {
|
|
48
|
+
let set = jwksCache.get(jwksUri);
|
|
49
|
+
if (!set) {
|
|
50
|
+
set = createRemoteJWKSet(new URL(jwksUri));
|
|
51
|
+
jwksCache.set(jwksUri, set);
|
|
52
|
+
}
|
|
53
|
+
return set;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const verify = async (token, { issuer, audience, jwksUri } = {}) => {
|
|
57
|
+
if (!token || !issuer || !audience || !jwksUri) {
|
|
58
|
+
throw new Error('fastify-oidc: verifyPlatformAssertion 需要 token、issuer、audience、jwksUri');
|
|
59
|
+
}
|
|
60
|
+
const { payload, protectedHeader } = await jwtVerify(token, getJWKS(jwksUri), {
|
|
61
|
+
issuer,
|
|
62
|
+
audience,
|
|
63
|
+
clockTolerance,
|
|
64
|
+
typ: ASSERTION_TYP
|
|
65
|
+
});
|
|
66
|
+
if (!payload.jti) {
|
|
67
|
+
throw new Error('fastify-oidc: platform assertion 缺少 jti');
|
|
68
|
+
}
|
|
69
|
+
if (jtiStore) {
|
|
70
|
+
if (await jtiStore.has(payload.jti)) {
|
|
71
|
+
throw new Error('fastify-oidc: platform assertion jti 已使用');
|
|
72
|
+
}
|
|
73
|
+
const ttlMs = Math.max(1000, ((payload.exp || 0) - Math.floor(Date.now() / 1000) + clockTolerance) * 1000);
|
|
74
|
+
await jtiStore.add(payload.jti, ttlMs);
|
|
75
|
+
}
|
|
76
|
+
return { payload, protectedHeader };
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
return { verify, typ: ASSERTION_TYP };
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** 内存 jti 防重放(单进程);生产可换 Redis */
|
|
83
|
+
const createMemoryJtiStore = () => {
|
|
84
|
+
const map = new Map();
|
|
85
|
+
const has = async jti => {
|
|
86
|
+
const exp = map.get(jti);
|
|
87
|
+
if (!exp) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
if (exp <= Date.now()) {
|
|
91
|
+
map.delete(jti);
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
return true;
|
|
95
|
+
};
|
|
96
|
+
const add = async (jti, ttlMs) => {
|
|
97
|
+
map.set(jti, Date.now() + ttlMs);
|
|
98
|
+
};
|
|
99
|
+
return { has, add };
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
module.exports = {
|
|
103
|
+
ASSERTION_TYP,
|
|
104
|
+
DEFAULT_TTL,
|
|
105
|
+
createPlatformAssertionSigner,
|
|
106
|
+
createPlatformAssertionVerifier,
|
|
107
|
+
createMemoryJtiStore
|
|
108
|
+
};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* central 多平台:运行时 platforms[](按 platformOrigin / issuer 唯一)。
|
|
3
|
+
* 登录与验签按 token.iss 选择对应 JWKS + audience。
|
|
4
|
+
*/
|
|
5
|
+
const normalizePlatform = (item = {}) => {
|
|
6
|
+
const platformOrigin = String(item.platformOrigin || '')
|
|
7
|
+
.replace(/\/+$/, '')
|
|
8
|
+
.trim();
|
|
9
|
+
const issuer = String(item.issuer || '')
|
|
10
|
+
.replace(/\/+$/, '')
|
|
11
|
+
.trim();
|
|
12
|
+
if (!platformOrigin || !issuer) {
|
|
13
|
+
throw new Error('fastify-oidc: platform 需要 platformOrigin 与 issuer');
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
platformOrigin,
|
|
17
|
+
platformName: item.platformName || platformOrigin,
|
|
18
|
+
issuer,
|
|
19
|
+
audience: item.audience || null,
|
|
20
|
+
spaClientId: item.spaClientId || item.clientId || null,
|
|
21
|
+
serviceClientId: item.serviceClientId || null,
|
|
22
|
+
jwksUri: item.jwksUri || `${issuer}/jwks`,
|
|
23
|
+
status: item.status || 'paired',
|
|
24
|
+
pairedAt: item.pairedAt || null
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const createPlatformsRegistry = ({ initial = [], onChange = null } = {}) => {
|
|
29
|
+
let list = [];
|
|
30
|
+
|
|
31
|
+
const setAll = (platforms = []) => {
|
|
32
|
+
const next = [];
|
|
33
|
+
const seen = new Set();
|
|
34
|
+
for (const raw of platforms) {
|
|
35
|
+
const item = normalizePlatform(raw);
|
|
36
|
+
const key = item.platformOrigin.toLowerCase();
|
|
37
|
+
if (seen.has(key)) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
seen.add(key);
|
|
41
|
+
next.push(item);
|
|
42
|
+
}
|
|
43
|
+
list = next;
|
|
44
|
+
if (typeof onChange === 'function') {
|
|
45
|
+
onChange(list.slice());
|
|
46
|
+
}
|
|
47
|
+
return list.slice();
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const upsert = platform => {
|
|
51
|
+
const item = normalizePlatform(platform);
|
|
52
|
+
const idx = list.findIndex(p => p.platformOrigin.toLowerCase() === item.platformOrigin.toLowerCase());
|
|
53
|
+
if (idx >= 0) {
|
|
54
|
+
list[idx] = Object.assign({}, list[idx], item);
|
|
55
|
+
} else {
|
|
56
|
+
list.push(item);
|
|
57
|
+
}
|
|
58
|
+
if (typeof onChange === 'function') {
|
|
59
|
+
onChange(list.slice());
|
|
60
|
+
}
|
|
61
|
+
return item;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const remove = platformOrigin => {
|
|
65
|
+
const key = String(platformOrigin || '')
|
|
66
|
+
.replace(/\/+$/, '')
|
|
67
|
+
.toLowerCase();
|
|
68
|
+
const before = list.length;
|
|
69
|
+
list = list.filter(p => p.platformOrigin.toLowerCase() !== key);
|
|
70
|
+
if (list.length !== before && typeof onChange === 'function') {
|
|
71
|
+
onChange(list.slice());
|
|
72
|
+
}
|
|
73
|
+
return list.length !== before;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const getAll = () => list.slice();
|
|
77
|
+
|
|
78
|
+
const findByIssuer = issuer => {
|
|
79
|
+
const key = String(issuer || '')
|
|
80
|
+
.replace(/\/+$/, '')
|
|
81
|
+
.toLowerCase();
|
|
82
|
+
return list.find(p => p.issuer.toLowerCase() === key) || null;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const findByOrigin = platformOrigin => {
|
|
86
|
+
const key = String(platformOrigin || '')
|
|
87
|
+
.replace(/\/+$/, '')
|
|
88
|
+
.toLowerCase();
|
|
89
|
+
return list.find(p => p.platformOrigin.toLowerCase() === key) || null;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const publicList = () =>
|
|
93
|
+
list
|
|
94
|
+
.filter(p => p.status === 'paired')
|
|
95
|
+
.map(p => ({
|
|
96
|
+
platformOrigin: p.platformOrigin,
|
|
97
|
+
platformName: p.platformName,
|
|
98
|
+
issuer: p.issuer,
|
|
99
|
+
clientId: p.spaClientId,
|
|
100
|
+
audience: p.audience
|
|
101
|
+
}));
|
|
102
|
+
|
|
103
|
+
if (initial.length) {
|
|
104
|
+
setAll(initial);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return { setAll, upsert, remove, getAll, findByIssuer, findByOrigin, publicList };
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
module.exports = { normalizePlatform, createPlatformsRegistry };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kne/fastify-oidc",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.15",
|
|
4
4
|
"description": "基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -20,8 +20,13 @@
|
|
|
20
20
|
},
|
|
21
21
|
"files": [
|
|
22
22
|
"index.js",
|
|
23
|
-
"libs"
|
|
23
|
+
"libs",
|
|
24
|
+
"platform-assertion.js"
|
|
24
25
|
],
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./index.js",
|
|
28
|
+
"./platform-assertion": "./platform-assertion.js"
|
|
29
|
+
},
|
|
25
30
|
"repository": {
|
|
26
31
|
"type": "git",
|
|
27
32
|
"url": "git+https://github.com/kne-union/fastify-oidc.git"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./libs/utils/platform-assertion');
|