@kne/fastify-oidc 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +681 -2
- package/index.js +146 -0
- package/libs/controllers/admin.js +150 -0
- package/libs/controllers/backchannel.js +49 -0
- package/libs/controllers/interaction.js +87 -0
- package/libs/controllers/service.js +59 -0
- package/libs/idp/adapters/sequelize.js +82 -0
- package/libs/idp/create-provider.js +286 -0
- package/libs/idp/grant-helpers.js +31 -0
- package/libs/idp/grants/token-exchange.js +82 -0
- package/libs/idp/identity.js +108 -0
- package/libs/idp/index.js +123 -0
- package/libs/idp/mount.js +26 -0
- package/libs/locale/en-US.js +63 -0
- package/libs/locale/index.js +4 -0
- package/libs/locale/zh-CN.js +63 -0
- package/libs/models/client.js +43 -0
- package/libs/models/key.js +44 -0
- package/libs/models/payload.js +50 -0
- package/libs/models/resource-server.js +42 -0
- package/libs/models/session-tenant.js +26 -0
- package/libs/resource/authenticate.js +203 -0
- package/libs/resource/dpop.js +52 -0
- package/libs/resource/normalize-user.js +42 -0
- package/libs/resource/revocation.js +62 -0
- package/libs/resource/service-client.js +91 -0
- package/libs/resource/user-mirror.js +60 -0
- package/libs/resource/verify-token.js +51 -0
- package/libs/services/client.js +167 -0
- package/libs/services/grant.js +104 -0
- package/libs/services/interaction.js +118 -0
- package/libs/services/key.js +103 -0
- package/libs/services/resource-server.js +99 -0
- package/libs/services/session-tenant.js +32 -0
- package/libs/utils/crypto.js +25 -0
- package/libs/utils/intl.js +71 -0
- package/libs/utils/resolve-options.js +68 -0
- package/package.json +83 -4
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
authenticationFailed: 'Authentication failed',
|
|
3
|
+
accessTokenMissing: 'Missing access token',
|
|
4
|
+
tokenRevoked: 'Your session has expired, please log in again',
|
|
5
|
+
userTokenRequired: 'This API requires a user identity, client tokens are not allowed',
|
|
6
|
+
clientTokenRequired: 'This API only accepts client tokens',
|
|
7
|
+
userNotAuthenticated: 'Please complete user authentication first',
|
|
8
|
+
tenantNotSelected: 'No tenant is selected for the current login',
|
|
9
|
+
accountPluginMissing: 'fastify-account is not installed, unable to verify administrator permission',
|
|
10
|
+
scopeMissing: 'Missing scope: {scopes}',
|
|
11
|
+
permissionMissing: 'Missing permission: {permissions}',
|
|
12
|
+
dpopSchemeRequired: 'A DPoP-bound token must use the DPoP authorization scheme',
|
|
13
|
+
tokenNotDPoPBound: 'The token is not DPoP-bound',
|
|
14
|
+
dpopRequired: 'A DPoP-bound access token is required',
|
|
15
|
+
dpopInvalid: 'DPoP verification failed',
|
|
16
|
+
dpopProofMissing: 'DPoP verification failed: missing DPoP proof',
|
|
17
|
+
dpopHtmMismatch: 'DPoP verification failed: htm mismatch',
|
|
18
|
+
dpopHtuMismatch: 'DPoP verification failed: htu mismatch',
|
|
19
|
+
dpopJtiMissing: 'DPoP verification failed: missing jti',
|
|
20
|
+
dpopAthMismatch: 'DPoP verification failed: ath mismatch',
|
|
21
|
+
dpopKeyMismatch: 'DPoP verification failed: proof key does not match the access token binding',
|
|
22
|
+
dpopReplayed: 'DPoP verification failed: proof replayed',
|
|
23
|
+
logoutTokenInvalid: 'logout_token verification failed',
|
|
24
|
+
logoutTokenEventMissing: 'logout_token verification failed: missing backchannel-logout event',
|
|
25
|
+
logoutTokenNonceNotAllowed: 'logout_token verification failed: nonce is not allowed',
|
|
26
|
+
logoutTokenSubjectMissing: 'logout_token verification failed: sid or sub is required',
|
|
27
|
+
serviceClientNotConfigured: 'serviceClient (clientId / clientSecret) is not configured, unable to call the main project service API',
|
|
28
|
+
idpDiscoveryFailed: 'Failed to load the main project OIDC configuration ({status})',
|
|
29
|
+
idpTokenRequestFailed: 'Failed to request a token from the main project ({status}): {reason}',
|
|
30
|
+
idpServiceCallFailed: 'Failed to call the main project API {path} ({status}): {reason}',
|
|
31
|
+
providerNotReady: 'OIDC service is not ready yet',
|
|
32
|
+
interactionExpired: 'The login session has expired, please start the login again from the application',
|
|
33
|
+
interactionMismatch: 'The login session does not match, please start the login again from the application',
|
|
34
|
+
interactionPromptMismatch: 'The current step is {current}, cannot perform {expected}',
|
|
35
|
+
interactionAborted: 'The user canceled the login',
|
|
36
|
+
tenantNotAvailable: 'The current user does not belong to this tenant or the tenant is closed',
|
|
37
|
+
clientNotFound: 'Client not found',
|
|
38
|
+
clientIdExists: 'client_id {clientId} already exists',
|
|
39
|
+
clientMetadataInvalid: 'Invalid client configuration: {reason}',
|
|
40
|
+
publicClientNoSecret: 'A public client has no client_secret',
|
|
41
|
+
resourceServerIdentifierInvalid: 'identifier must be an absolute URI, such as https://app.example.com/api',
|
|
42
|
+
resourceServerNotFound: 'Resource server not found',
|
|
43
|
+
resourceServerExists: 'Resource server {identifier} already exists',
|
|
44
|
+
resourceForbidden: 'Client {clientId} is not allowed to access resource {resource}',
|
|
45
|
+
resourceUnavailable: 'Resource server {resource} does not exist or is disabled',
|
|
46
|
+
sessionNotFound: 'The session does not exist or has expired',
|
|
47
|
+
adapterSessionQueryMissing: 'The current adapter does not implement findByAccountId, unable to query or end user sessions',
|
|
48
|
+
adapterGrantQueryMissing: 'The current adapter does not implement findGrantIdsByAccountId, unable to revoke grants by user, please refer to the documentation',
|
|
49
|
+
userNotFound: 'User not found',
|
|
50
|
+
tenantNotEnabled: 'Tenant is not enabled in the main project',
|
|
51
|
+
tenantMemberNotFound: 'The user does not belong to this tenant',
|
|
52
|
+
subjectTokenTypeUnsupported: 'subject_token_type only supports urn:ietf:params:oauth:token-type:access_token',
|
|
53
|
+
requestedTokenTypeUnsupported: 'requested_token_type only supports urn:ietf:params:oauth:token-type:access_token',
|
|
54
|
+
tokenExchangeTargetMissing: 'The target resource server must be specified by resource',
|
|
55
|
+
subjectTokenInvalid: 'subject_token is invalid or expired',
|
|
56
|
+
subjectTokenNotUser: 'subject_token must be a user token',
|
|
57
|
+
subjectTokenRevoked: 'subject_token has been revoked',
|
|
58
|
+
subjectTokenAudienceForbidden: 'The aud of subject_token is not a resource accessible to the current client',
|
|
59
|
+
subjectTokenAccountInvalid: 'The user of subject_token does not exist or is disabled',
|
|
60
|
+
logoutPageTitle: 'Log out',
|
|
61
|
+
logoutConfirm: 'Confirm log out',
|
|
62
|
+
logoutSuccess: 'You have been logged out'
|
|
63
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
authenticationFailed: '身份认证失败',
|
|
3
|
+
accessTokenMissing: '缺少访问令牌',
|
|
4
|
+
tokenRevoked: '登录状态已失效,请重新登录',
|
|
5
|
+
userTokenRequired: '该接口需要用户身份,不能使用 client 令牌',
|
|
6
|
+
clientTokenRequired: '该接口只允许 client 令牌调用',
|
|
7
|
+
userNotAuthenticated: '请先完成用户认证',
|
|
8
|
+
tenantNotSelected: '当前登录未选择租户',
|
|
9
|
+
accountPluginMissing: '未安装 fastify-account,无法校验管理员权限',
|
|
10
|
+
scopeMissing: '缺少 scope: {scopes}',
|
|
11
|
+
permissionMissing: '缺少权限: {permissions}',
|
|
12
|
+
dpopSchemeRequired: 'DPoP 绑定的令牌必须使用 DPoP 认证方案',
|
|
13
|
+
tokenNotDPoPBound: '令牌未绑定 DPoP',
|
|
14
|
+
dpopRequired: '需要 DPoP 绑定的访问令牌',
|
|
15
|
+
dpopInvalid: 'DPoP 校验失败',
|
|
16
|
+
dpopProofMissing: 'DPoP 校验失败:缺少 DPoP proof',
|
|
17
|
+
dpopHtmMismatch: 'DPoP 校验失败:htm 不匹配',
|
|
18
|
+
dpopHtuMismatch: 'DPoP 校验失败:htu 不匹配',
|
|
19
|
+
dpopJtiMissing: 'DPoP 校验失败:缺少 jti',
|
|
20
|
+
dpopAthMismatch: 'DPoP 校验失败:ath 不匹配',
|
|
21
|
+
dpopKeyMismatch: 'DPoP 校验失败:proof 公钥与 access_token 绑定的不一致',
|
|
22
|
+
dpopReplayed: 'DPoP 校验失败:proof 被重放',
|
|
23
|
+
logoutTokenInvalid: 'logout_token 校验失败',
|
|
24
|
+
logoutTokenEventMissing: 'logout_token 校验失败:缺少 backchannel-logout 事件',
|
|
25
|
+
logoutTokenNonceNotAllowed: 'logout_token 校验失败:不允许包含 nonce',
|
|
26
|
+
logoutTokenSubjectMissing: 'logout_token 校验失败:必须包含 sid 或 sub',
|
|
27
|
+
serviceClientNotConfigured: '未配置 serviceClient(clientId / clientSecret),无法调用主项目服务接口',
|
|
28
|
+
idpDiscoveryFailed: '获取主项目 OIDC 配置失败({status})',
|
|
29
|
+
idpTokenRequestFailed: '向主项目申请令牌失败({status}):{reason}',
|
|
30
|
+
idpServiceCallFailed: '调用主项目接口 {path} 失败({status}):{reason}',
|
|
31
|
+
providerNotReady: 'OIDC 服务尚未就绪',
|
|
32
|
+
interactionExpired: '登录会话已失效,请从应用重新发起登录',
|
|
33
|
+
interactionMismatch: '登录会话不匹配,请从应用重新发起登录',
|
|
34
|
+
interactionPromptMismatch: '当前步骤为 {current},不能执行 {expected}',
|
|
35
|
+
interactionAborted: '用户取消了登录',
|
|
36
|
+
tenantNotAvailable: '当前用户不属于该租户或租户已关闭',
|
|
37
|
+
clientNotFound: 'client 不存在',
|
|
38
|
+
clientIdExists: 'client_id {clientId} 已存在',
|
|
39
|
+
clientMetadataInvalid: 'client 配置不合法: {reason}',
|
|
40
|
+
publicClientNoSecret: 'public client 没有 client_secret',
|
|
41
|
+
resourceServerIdentifierInvalid: 'identifier 必须是绝对 URI,如 https://app.example.com/api',
|
|
42
|
+
resourceServerNotFound: '资源服务不存在',
|
|
43
|
+
resourceServerExists: '资源服务 {identifier} 已存在',
|
|
44
|
+
resourceForbidden: 'client {clientId} 无权访问资源 {resource}',
|
|
45
|
+
resourceUnavailable: '资源服务 {resource} 不存在或已停用',
|
|
46
|
+
sessionNotFound: '会话不存在或已过期',
|
|
47
|
+
adapterSessionQueryMissing: '当前 adapter 未实现 findByAccountId,无法查询或结束用户会话',
|
|
48
|
+
adapterGrantQueryMissing: '当前 adapter 未实现 findGrantIdsByAccountId,无法按用户撤销授权,请参考文档补充该方法',
|
|
49
|
+
userNotFound: '用户不存在',
|
|
50
|
+
tenantNotEnabled: '主项目未启用租户',
|
|
51
|
+
tenantMemberNotFound: '用户不属于该租户',
|
|
52
|
+
subjectTokenTypeUnsupported: 'subject_token_type 仅支持 urn:ietf:params:oauth:token-type:access_token',
|
|
53
|
+
requestedTokenTypeUnsupported: 'requested_token_type 仅支持 urn:ietf:params:oauth:token-type:access_token',
|
|
54
|
+
tokenExchangeTargetMissing: '需要通过 resource 指定目标资源服务',
|
|
55
|
+
subjectTokenInvalid: 'subject_token 无效或已过期',
|
|
56
|
+
subjectTokenNotUser: 'subject_token 必须是用户令牌',
|
|
57
|
+
subjectTokenRevoked: 'subject_token 已失效',
|
|
58
|
+
subjectTokenAudienceForbidden: 'subject_token 的 aud 不属于当前 client 可访问的资源',
|
|
59
|
+
subjectTokenAccountInvalid: 'subject_token 对应的用户不存在或已被禁用',
|
|
60
|
+
logoutPageTitle: '退出登录',
|
|
61
|
+
logoutConfirm: '确认退出',
|
|
62
|
+
logoutSuccess: '已退出登录'
|
|
63
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
module.exports = ({ DataTypes }) => {
|
|
2
|
+
return {
|
|
3
|
+
model: {
|
|
4
|
+
clientId: {
|
|
5
|
+
type: DataTypes.STRING(255),
|
|
6
|
+
allowNull: false,
|
|
7
|
+
comment: 'client_id'
|
|
8
|
+
},
|
|
9
|
+
clientName: {
|
|
10
|
+
type: DataTypes.STRING(255),
|
|
11
|
+
comment: '应用名称'
|
|
12
|
+
},
|
|
13
|
+
clientSecret: {
|
|
14
|
+
type: DataTypes.TEXT,
|
|
15
|
+
comment: '加密存储的 client_secret,public client 为空'
|
|
16
|
+
},
|
|
17
|
+
metadata: {
|
|
18
|
+
type: DataTypes.JSON,
|
|
19
|
+
allowNull: false,
|
|
20
|
+
comment: 'OIDC client metadata(redirect_uris、grant_types 等)'
|
|
21
|
+
},
|
|
22
|
+
allowedResources: {
|
|
23
|
+
type: DataTypes.JSON,
|
|
24
|
+
comment: '允许申请的 resource server identifier 列表'
|
|
25
|
+
},
|
|
26
|
+
description: {
|
|
27
|
+
type: DataTypes.TEXT,
|
|
28
|
+
comment: '描述'
|
|
29
|
+
},
|
|
30
|
+
status: {
|
|
31
|
+
type: DataTypes.STRING(16),
|
|
32
|
+
allowNull: false,
|
|
33
|
+
defaultValue: 'open',
|
|
34
|
+
comment: 'open: 启用, closed: 停用'
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
options: {
|
|
38
|
+
comment: 'OIDC 接入应用',
|
|
39
|
+
paranoid: false,
|
|
40
|
+
indexes: [{ fields: ['client_id'], unique: true }]
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
module.exports = ({ DataTypes }) => {
|
|
2
|
+
return {
|
|
3
|
+
model: {
|
|
4
|
+
kid: {
|
|
5
|
+
type: DataTypes.STRING(255),
|
|
6
|
+
allowNull: false,
|
|
7
|
+
comment: 'JWK kid'
|
|
8
|
+
},
|
|
9
|
+
alg: {
|
|
10
|
+
type: DataTypes.STRING(16),
|
|
11
|
+
allowNull: false,
|
|
12
|
+
comment: '签名算法'
|
|
13
|
+
},
|
|
14
|
+
privateJwk: {
|
|
15
|
+
type: DataTypes.TEXT,
|
|
16
|
+
allowNull: false,
|
|
17
|
+
comment: '加密存储的私钥 JWK'
|
|
18
|
+
},
|
|
19
|
+
publicJwk: {
|
|
20
|
+
type: DataTypes.JSON,
|
|
21
|
+
allowNull: false,
|
|
22
|
+
comment: '公钥 JWK'
|
|
23
|
+
},
|
|
24
|
+
status: {
|
|
25
|
+
type: DataTypes.STRING(16),
|
|
26
|
+
allowNull: false,
|
|
27
|
+
comment: 'active: 当前签名, next: 已发布待启用, retired: 已退役仅用于验签'
|
|
28
|
+
},
|
|
29
|
+
activatedAt: {
|
|
30
|
+
type: DataTypes.DATE,
|
|
31
|
+
comment: '启用时间'
|
|
32
|
+
},
|
|
33
|
+
retiredAt: {
|
|
34
|
+
type: DataTypes.DATE,
|
|
35
|
+
comment: '退役时间'
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
options: {
|
|
39
|
+
comment: 'OIDC 签名密钥(JWKS)',
|
|
40
|
+
paranoid: false,
|
|
41
|
+
indexes: [{ fields: ['kid'], unique: true }, { fields: ['status'] }]
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
module.exports = ({ DataTypes }) => {
|
|
2
|
+
return {
|
|
3
|
+
model: {
|
|
4
|
+
modelName: {
|
|
5
|
+
type: DataTypes.STRING(64),
|
|
6
|
+
allowNull: false,
|
|
7
|
+
comment: 'oidc-provider 模型名,如 Session、AccessToken、Grant'
|
|
8
|
+
},
|
|
9
|
+
payloadId: {
|
|
10
|
+
type: DataTypes.STRING(255),
|
|
11
|
+
allowNull: false,
|
|
12
|
+
comment: 'oidc-provider 生成的 id'
|
|
13
|
+
},
|
|
14
|
+
payload: {
|
|
15
|
+
type: DataTypes.JSON,
|
|
16
|
+
allowNull: false,
|
|
17
|
+
comment: 'oidc-provider 存储的完整 payload'
|
|
18
|
+
},
|
|
19
|
+
grantId: {
|
|
20
|
+
type: DataTypes.STRING(255),
|
|
21
|
+
comment: '所属 grant,用于 revokeByGrantId'
|
|
22
|
+
},
|
|
23
|
+
userCode: {
|
|
24
|
+
type: DataTypes.STRING(255),
|
|
25
|
+
comment: 'device flow user code'
|
|
26
|
+
},
|
|
27
|
+
uid: {
|
|
28
|
+
type: DataTypes.STRING(255),
|
|
29
|
+
comment: 'Session uid'
|
|
30
|
+
},
|
|
31
|
+
accountId: {
|
|
32
|
+
type: DataTypes.STRING(255),
|
|
33
|
+
comment: '用户 id,用于按用户撤销授权'
|
|
34
|
+
},
|
|
35
|
+
expiresAt: {
|
|
36
|
+
type: DataTypes.DATE,
|
|
37
|
+
comment: '过期时间'
|
|
38
|
+
},
|
|
39
|
+
consumedAt: {
|
|
40
|
+
type: DataTypes.DATE,
|
|
41
|
+
comment: '已使用时间(授权码、轮转后的 refresh token)'
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
options: {
|
|
45
|
+
comment: 'oidc-provider 协议数据存储',
|
|
46
|
+
paranoid: false,
|
|
47
|
+
indexes: [{ fields: ['model_name', 'payload_id'], unique: true }, { fields: ['grant_id'] }, { fields: ['uid'] }, { fields: ['user_code'] }, { fields: ['account_id', 'model_name'] }, { fields: ['expires_at'] }]
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
module.exports = ({ DataTypes }) => {
|
|
2
|
+
return {
|
|
3
|
+
model: {
|
|
4
|
+
identifier: {
|
|
5
|
+
type: DataTypes.STRING(255),
|
|
6
|
+
allowNull: false,
|
|
7
|
+
comment: 'resource indicator,即 access_token 的 aud'
|
|
8
|
+
},
|
|
9
|
+
name: {
|
|
10
|
+
type: DataTypes.STRING(255),
|
|
11
|
+
comment: '资源名称'
|
|
12
|
+
},
|
|
13
|
+
scope: {
|
|
14
|
+
type: DataTypes.TEXT,
|
|
15
|
+
comment: '该资源支持的 scope,空格分隔'
|
|
16
|
+
},
|
|
17
|
+
accessTokenTTL: {
|
|
18
|
+
type: DataTypes.INTEGER,
|
|
19
|
+
comment: 'access_token 有效期(秒),为空使用全局配置'
|
|
20
|
+
},
|
|
21
|
+
includePermissions: {
|
|
22
|
+
type: DataTypes.BOOLEAN,
|
|
23
|
+
comment: '是否在 access_token 中携带 permissions,为空使用全局配置'
|
|
24
|
+
},
|
|
25
|
+
description: {
|
|
26
|
+
type: DataTypes.TEXT,
|
|
27
|
+
comment: '描述'
|
|
28
|
+
},
|
|
29
|
+
status: {
|
|
30
|
+
type: DataTypes.STRING(16),
|
|
31
|
+
allowNull: false,
|
|
32
|
+
defaultValue: 'open',
|
|
33
|
+
comment: 'open: 启用, closed: 停用'
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
options: {
|
|
37
|
+
comment: 'OIDC 资源服务(API)',
|
|
38
|
+
paranoid: false,
|
|
39
|
+
indexes: [{ fields: ['identifier'], unique: true }]
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
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
|
+
tenantId: {
|
|
15
|
+
type: DataTypes.STRING(255),
|
|
16
|
+
allowNull: false,
|
|
17
|
+
comment: '当前选定的租户 id'
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
options: {
|
|
21
|
+
comment: 'OIDC 会话当前租户',
|
|
22
|
+
paranoid: false,
|
|
23
|
+
indexes: [{ fields: ['session_uid'], unique: true }, { fields: ['account_id'] }]
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
};
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
const httpErrors = require('http-errors');
|
|
2
|
+
const { normalizeClaims, normalizeLegacy } = require('./normalize-user');
|
|
3
|
+
const { createError } = require('../utils/intl');
|
|
4
|
+
|
|
5
|
+
const { Unauthorized, Forbidden } = httpErrors;
|
|
6
|
+
|
|
7
|
+
const extractToken = request => {
|
|
8
|
+
const header = request.headers.authorization;
|
|
9
|
+
if (!header) {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
const index = header.indexOf(' ');
|
|
13
|
+
const scheme = header.slice(0, index).toLowerCase();
|
|
14
|
+
const token = header.slice(index + 1).trim();
|
|
15
|
+
if (!['bearer', 'dpop'].includes(scheme) || !token) {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
return { scheme, token };
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 与 fastify.account.authenticate 同形的认证中间件:
|
|
23
|
+
* 填充 request.user(统一结构)以及兼容字段 request.userInfo / request.authenticatePayload / request.tenantUserInfo
|
|
24
|
+
*/
|
|
25
|
+
module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, translator }) => {
|
|
26
|
+
const { runtime } = options;
|
|
27
|
+
const account = () => fastify[options.accountNamespace];
|
|
28
|
+
const tenant = () => fastify[options.tenantNamespace];
|
|
29
|
+
|
|
30
|
+
const tenantSource = () => {
|
|
31
|
+
if (options.tenantSource) {
|
|
32
|
+
return options.tenantSource;
|
|
33
|
+
}
|
|
34
|
+
return runtime.idpEnabled && tenant() ? 'local' : 'claims';
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const getRequestUrl = request => (options.getRequestUrl ? options.getRequestUrl(request) : `${runtime.origin}${request.raw.url}`);
|
|
38
|
+
|
|
39
|
+
const verifyRequest = async (request, { audience } = {}) => {
|
|
40
|
+
const extracted = extractToken(request);
|
|
41
|
+
if (!extracted) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
let payload;
|
|
45
|
+
try {
|
|
46
|
+
payload = await verifier.verifyAccessToken(extracted.token, audience ? { audience } : undefined);
|
|
47
|
+
} catch (e) {
|
|
48
|
+
throw createError(Unauthorized, 'authenticationFailed');
|
|
49
|
+
}
|
|
50
|
+
if (payload.cnf?.jkt) {
|
|
51
|
+
if (extracted.scheme !== 'dpop') {
|
|
52
|
+
throw createError(Unauthorized, 'dpopSchemeRequired');
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
await dpop.verify({
|
|
56
|
+
proof: request.headers.dpop,
|
|
57
|
+
method: request.method,
|
|
58
|
+
url: getRequestUrl(request),
|
|
59
|
+
accessToken: extracted.token,
|
|
60
|
+
jkt: payload.cnf.jkt
|
|
61
|
+
});
|
|
62
|
+
} catch (e) {
|
|
63
|
+
throw createError(Unauthorized, e.messageId || 'dpopInvalid');
|
|
64
|
+
}
|
|
65
|
+
} else if (extracted.scheme === 'dpop') {
|
|
66
|
+
throw createError(Unauthorized, 'tokenNotDPoPBound');
|
|
67
|
+
} else if (options.requireDPoP) {
|
|
68
|
+
throw createError(Unauthorized, 'dpopRequired');
|
|
69
|
+
}
|
|
70
|
+
if (await revocation.isRevoked(payload)) {
|
|
71
|
+
throw createError(Unauthorized, 'tokenRevoked');
|
|
72
|
+
}
|
|
73
|
+
return payload;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const resolveUserInfo = async userId => {
|
|
77
|
+
if (!account()) {
|
|
78
|
+
return { id: userId };
|
|
79
|
+
}
|
|
80
|
+
if (runtime.idpEnabled) {
|
|
81
|
+
return account().services.user.getUser({ id: userId });
|
|
82
|
+
}
|
|
83
|
+
return userMirror.ensure(userId);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const user = async request => {
|
|
87
|
+
const payload = await verifyRequest(request);
|
|
88
|
+
if (!payload) {
|
|
89
|
+
if (options.legacyToken && account()) {
|
|
90
|
+
const { tokenUser, user: accountUser } = account().authenticate;
|
|
91
|
+
await (tokenUser || accountUser)(request);
|
|
92
|
+
request.user = normalizeLegacy(request);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
throw createError(Unauthorized, 'accessTokenMissing');
|
|
96
|
+
}
|
|
97
|
+
const normalized = normalizeClaims(payload, runtime.claims);
|
|
98
|
+
if (normalized.isClient) {
|
|
99
|
+
throw createError(Unauthorized, 'userTokenRequired');
|
|
100
|
+
}
|
|
101
|
+
request.user = normalized;
|
|
102
|
+
request.authenticatePayload = { id: normalized.userId, tenantId: normalized.tenantId };
|
|
103
|
+
request.userInfo = await resolveUserInfo(normalized.userId);
|
|
104
|
+
request.appName = request.headers['x-app-name'];
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const buildTenantUserFromClaims = currentUser => ({
|
|
108
|
+
id: currentUser.tenantUserId,
|
|
109
|
+
tenantId: currentUser.tenantId,
|
|
110
|
+
userId: currentUser.userId,
|
|
111
|
+
status: 'open',
|
|
112
|
+
roles: currentUser.roles,
|
|
113
|
+
roleDetails: currentUser.roles.map(code => ({ code })),
|
|
114
|
+
permissions: currentUser.permissions || [],
|
|
115
|
+
tenant: { id: currentUser.tenantId, status: 'open' }
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const tenantUser = async request => {
|
|
119
|
+
const contextName = options.tenantUserContextName;
|
|
120
|
+
if (request[contextName]) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (!request.user) {
|
|
124
|
+
throw createError(Unauthorized, 'userNotAuthenticated');
|
|
125
|
+
}
|
|
126
|
+
if (request.user.legacy && tenant()) {
|
|
127
|
+
await tenant().authenticate.tenantUser(request);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (!request.user.tenantId) {
|
|
131
|
+
throw createError(Forbidden, 'tenantNotSelected');
|
|
132
|
+
}
|
|
133
|
+
const source = tenantSource();
|
|
134
|
+
if (source === 'local') {
|
|
135
|
+
request[contextName] = await tenant().services.user.getTenantUserInfo({ id: request.user.userId, tenantId: request.user.tenantId });
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (source === 'remote') {
|
|
139
|
+
request[contextName] = await serviceClient.getTenantUser({ userId: request.user.userId, tenantId: request.user.tenantId });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
request[contextName] = buildTenantUserFromClaims(request.user);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const admin = async request => {
|
|
146
|
+
if (!account()) {
|
|
147
|
+
throw createError(Forbidden, 'accountPluginMissing');
|
|
148
|
+
}
|
|
149
|
+
await account().authenticate.admin(request);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const scope =
|
|
153
|
+
(...required) =>
|
|
154
|
+
async request => {
|
|
155
|
+
const granted = new Set(request.user?.scope || []);
|
|
156
|
+
const missing = required.filter(item => !granted.has(item));
|
|
157
|
+
if (missing.length) {
|
|
158
|
+
throw createError(Forbidden, 'scopeMissing', { scopes: missing.join(' ') });
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const permission =
|
|
163
|
+
(...codes) =>
|
|
164
|
+
async request => {
|
|
165
|
+
let permissions = request.user?.permissions;
|
|
166
|
+
if (tenantSource() !== 'claims' || !permissions) {
|
|
167
|
+
await tenantUser(request);
|
|
168
|
+
const info = request[options.tenantUserContextName];
|
|
169
|
+
permissions = (info && typeof info.get === 'function' ? info.get('permissions') : info?.permissions) || [];
|
|
170
|
+
}
|
|
171
|
+
const missing = codes.filter(code => !permissions.includes(code));
|
|
172
|
+
if (missing.length) {
|
|
173
|
+
throw createError(Forbidden, 'permissionMissing', { permissions: missing.join(', ') });
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const client =
|
|
178
|
+
(...scopes) =>
|
|
179
|
+
async request => {
|
|
180
|
+
const payload = await verifyRequest(request, { audience: runtime.serviceAudience });
|
|
181
|
+
if (!payload) {
|
|
182
|
+
throw createError(Unauthorized, 'accessTokenMissing');
|
|
183
|
+
}
|
|
184
|
+
const normalized = normalizeClaims(payload, runtime.claims);
|
|
185
|
+
if (!normalized.isClient) {
|
|
186
|
+
throw createError(Unauthorized, 'clientTokenRequired');
|
|
187
|
+
}
|
|
188
|
+
request.user = normalized;
|
|
189
|
+
await scope(...scopes)(request);
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const { wrap } = translator;
|
|
193
|
+
return {
|
|
194
|
+
user: wrap(user),
|
|
195
|
+
tenantUser: wrap(tenantUser),
|
|
196
|
+
admin: wrap(admin),
|
|
197
|
+
scope: (...args) => wrap(scope(...args)),
|
|
198
|
+
permission: (...args) => wrap(permission(...args)),
|
|
199
|
+
client: (...args) => wrap(client(...args))
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
module.exports.extractToken = extractToken;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
const { jwtVerify, EmbeddedJWK, calculateJwkThumbprint } = require('jose');
|
|
3
|
+
const { createMemoryStore } = require('./revocation');
|
|
4
|
+
const { createError } = require('../utils/intl');
|
|
5
|
+
|
|
6
|
+
const ALGORITHMS = ['ES256', 'ES384', 'ES512', 'EdDSA', 'Ed25519', 'PS256', 'RS256'];
|
|
7
|
+
|
|
8
|
+
const normalizeHtu = value => {
|
|
9
|
+
const url = new URL(value);
|
|
10
|
+
return `${url.origin}${url.pathname}`;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 资源侧校验 DPoP proof(RFC 9449 第 7 节)
|
|
15
|
+
*/
|
|
16
|
+
module.exports = ({ maxAge = 300, clockTolerance = 5, replayStore } = {}) => {
|
|
17
|
+
replayStore = replayStore || createMemoryStore();
|
|
18
|
+
|
|
19
|
+
const verify = async ({ proof, method, url, accessToken, jkt }) => {
|
|
20
|
+
if (!proof) {
|
|
21
|
+
throw createError(null, 'dpopProofMissing');
|
|
22
|
+
}
|
|
23
|
+
const { payload, protectedHeader } = await jwtVerify(proof, EmbeddedJWK, {
|
|
24
|
+
typ: 'dpop+jwt',
|
|
25
|
+
algorithms: ALGORITHMS,
|
|
26
|
+
maxTokenAge: maxAge,
|
|
27
|
+
clockTolerance
|
|
28
|
+
});
|
|
29
|
+
if (payload.htm !== method) {
|
|
30
|
+
throw createError(null, 'dpopHtmMismatch');
|
|
31
|
+
}
|
|
32
|
+
if (!payload.htu || normalizeHtu(payload.htu) !== normalizeHtu(url)) {
|
|
33
|
+
throw createError(null, 'dpopHtuMismatch');
|
|
34
|
+
}
|
|
35
|
+
if (!payload.jti) {
|
|
36
|
+
throw createError(null, 'dpopJtiMissing');
|
|
37
|
+
}
|
|
38
|
+
const ath = crypto.createHash('sha256').update(accessToken).digest('base64url');
|
|
39
|
+
if (payload.ath !== ath) {
|
|
40
|
+
throw createError(null, 'dpopAthMismatch');
|
|
41
|
+
}
|
|
42
|
+
if ((await calculateJwkThumbprint(protectedHeader.jwk, 'sha256')) !== jkt) {
|
|
43
|
+
throw createError(null, 'dpopKeyMismatch');
|
|
44
|
+
}
|
|
45
|
+
if (await replayStore.get(`dpop:${payload.jti}`)) {
|
|
46
|
+
throw createError(null, 'dpopReplayed');
|
|
47
|
+
}
|
|
48
|
+
await replayStore.set(`dpop:${payload.jti}`, 1, maxAge + clockTolerance);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
return { verify };
|
|
52
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const toArray = value => (Array.isArray(value) ? value.map(String) : []);
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 把 access_token claims 归一成业务代码使用的 request.user
|
|
5
|
+
* permissions 为 null 表示 token 中未携带(需要实时查询 fastify-tenant)
|
|
6
|
+
*/
|
|
7
|
+
const normalizeClaims = (payload, claims) => {
|
|
8
|
+
const isClient = !!payload[claims.clientToken];
|
|
9
|
+
return {
|
|
10
|
+
userId: isClient ? null : String(payload.sub),
|
|
11
|
+
tenantId: payload[claims.tenantId] ? String(payload[claims.tenantId]) : null,
|
|
12
|
+
tenantUserId: payload[claims.tenantUserId] ? String(payload[claims.tenantUserId]) : null,
|
|
13
|
+
roles: toArray(payload[claims.roles]),
|
|
14
|
+
permissions: Array.isArray(payload[claims.permissions]) ? toArray(payload[claims.permissions]) : null,
|
|
15
|
+
clientId: payload.client_id || null,
|
|
16
|
+
scope: payload.scope ? String(payload.scope).split(' ') : [],
|
|
17
|
+
sid: payload.sid || null,
|
|
18
|
+
actor: payload.act?.sub || null,
|
|
19
|
+
isClient,
|
|
20
|
+
legacy: false,
|
|
21
|
+
expiresAt: payload.exp || null,
|
|
22
|
+
payload
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const normalizeLegacy = request => ({
|
|
27
|
+
userId: request.userInfo?.id ? String(request.userInfo.id) : null,
|
|
28
|
+
tenantId: request.authenticatePayload?.tenantId ? String(request.authenticatePayload.tenantId) : null,
|
|
29
|
+
tenantUserId: null,
|
|
30
|
+
roles: [],
|
|
31
|
+
permissions: null,
|
|
32
|
+
clientId: null,
|
|
33
|
+
scope: [],
|
|
34
|
+
sid: null,
|
|
35
|
+
actor: null,
|
|
36
|
+
isClient: false,
|
|
37
|
+
legacy: true,
|
|
38
|
+
expiresAt: null,
|
|
39
|
+
payload: request.authenticatePayload || null
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
module.exports = { normalizeClaims, normalizeLegacy };
|