@kne/fastify-oidc 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +681 -2
  2. package/index.js +146 -0
  3. package/libs/controllers/admin.js +150 -0
  4. package/libs/controllers/backchannel.js +49 -0
  5. package/libs/controllers/interaction.js +87 -0
  6. package/libs/controllers/service.js +59 -0
  7. package/libs/idp/adapters/sequelize.js +82 -0
  8. package/libs/idp/create-provider.js +286 -0
  9. package/libs/idp/grant-helpers.js +31 -0
  10. package/libs/idp/grants/token-exchange.js +82 -0
  11. package/libs/idp/identity.js +108 -0
  12. package/libs/idp/index.js +123 -0
  13. package/libs/idp/mount.js +26 -0
  14. package/libs/locale/en-US.js +63 -0
  15. package/libs/locale/index.js +4 -0
  16. package/libs/locale/zh-CN.js +63 -0
  17. package/libs/models/client.js +43 -0
  18. package/libs/models/key.js +44 -0
  19. package/libs/models/payload.js +50 -0
  20. package/libs/models/resource-server.js +42 -0
  21. package/libs/models/session-tenant.js +26 -0
  22. package/libs/resource/authenticate.js +203 -0
  23. package/libs/resource/dpop.js +52 -0
  24. package/libs/resource/normalize-user.js +42 -0
  25. package/libs/resource/revocation.js +62 -0
  26. package/libs/resource/service-client.js +91 -0
  27. package/libs/resource/user-mirror.js +60 -0
  28. package/libs/resource/verify-token.js +51 -0
  29. package/libs/services/client.js +167 -0
  30. package/libs/services/grant.js +104 -0
  31. package/libs/services/interaction.js +118 -0
  32. package/libs/services/key.js +103 -0
  33. package/libs/services/resource-server.js +99 -0
  34. package/libs/services/session-tenant.js +32 -0
  35. package/libs/utils/crypto.js +25 -0
  36. package/libs/utils/intl.js +71 -0
  37. package/libs/utils/resolve-options.js +68 -0
  38. package/package.json +83 -4
package/README.md CHANGED
@@ -1,3 +1,682 @@
1
- # Temporary Holding Version
1
+ # fastify-oidc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ### 描述
4
+
5
+ 基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌
6
+
7
+ ### 关键词
8
+
9
+ fastify, oidc, oauth2, sso, oidc-provider, authentication, jwt, pkce, dpop, token-exchange, multi-tenant, kne
10
+
11
+ ### 安装
12
+
13
+ ```shell
14
+ npm i --save @kne/fastify-oidc
15
+ ```
16
+
17
+ ### 概述
18
+
19
+ #### 项目概述
20
+
21
+ `@kne/fastify-oidc` 基于 [oidc-provider](https://github.com/panva/node-oidc-provider) 为 kne 体系的 Fastify 项目提供 OIDC / OAuth 2.0 认证能力,解决多个业务项目之间的统一登录、租户上下文传递与跨项目调用问题。
22
+
23
+ 同一个插件按 `mode` 扮演两种角色:
24
+
25
+ | 模式 | 角色 | 说明 |
26
+ |------|------|------|
27
+ | `standalone` | IdP + 资源服务 | 内嵌 OIDC Provider,账号来自 `@kne/fastify-account`,租户 / 角色 / 权限来自 `@kne/fastify-tenant`;单独部署的项目和"主项目"都用此模式 |
28
+ | `central` | 资源服务 + Client | 不启动 IdP、不建 OIDC 表,用主项目的 JWKS 验签,用户在本地 fastify-account 中按 `sub` 建镜像 |
29
+
30
+ > **关键设计**:业务代码只依赖 `fastify.oidc.authenticate.*` 填充的 `request.user`(以及兼容字段 `request.userInfo` / `request.authenticatePayload` / `request.tenantUserInfo`),从 standalone 切换到 central 只需改环境变量。
31
+
32
+ #### 核心架构与流程
33
+
34
+ ```
35
+ ┌──────────────────────── 主项目(standalone) ────────────────────────┐
36
+ 浏览器 SPA │ │
37
+ (components-admin Oidc) │ /oidc/* oidc-provider(授权、token、jwks、end_session) │
38
+ │ 1.授权请求(PKCE) ──→ │ ↓ 需要交互 │
39
+ │ 2.前端交互页 /oidc-interaction?uid= ←── /api/oidc/interaction/{uid}(303) │
40
+ │ 3.登录/选租户/确认 ──→ │ /api/oidc/interaction/{uid}/login|tenant|confirm|abort │
41
+ │ │ ↓ identity.js(fastify-account.verifyCredentials / fastify-tenant)│
42
+ │ 4.code → token ──→ │ JWT access_token(aud=资源、带租户 claims、sid) │
43
+ │ 5.Bearer/DPoP 调 API → │ authenticate.user → request.user │
44
+ │ └──────────────────────────────────────────────────────────────────────┘
45
+ │ ↑ JWKS / client_credentials / back-channel logout
46
+ │ ┌──────────── 子项目(central) ────────────┐
47
+ └── 同一 IdP 会话 SSO ─→ │ authenticate.user(远程 JWKS 验签) │
48
+ │ user-mirror(按 sub 建本地用户镜像) │
49
+ │ /api/oidc/backchannel-logout(登出通知) │
50
+ └───────────────────────────────────────────┘
51
+ ```
52
+
53
+ | 环节 | 实现 | 说明 |
54
+ |------|------|------|
55
+ | 协议端点 | `libs/idp/mount.js` | 把 `mountPath`(默认 `/oidc`)下的请求原样交给 oidc-provider |
56
+ | 交互 | `libs/services/interaction.js` | 登录、选择租户、授权确认、取消,返回 `{ redirectTo }` 由前端跳转 |
57
+ | 账号 / 租户桥接 | `libs/idp/identity.js` | 唯一依赖 fastify-account / fastify-tenant 的地方 |
58
+ | 资源侧鉴权 | `libs/resource/*` | JWT 验签、DPoP、撤销列表、`request.user` 归一化、legacy token 回退 |
59
+ | 管理 | `libs/controllers/admin.js` | client、资源服务、签名密钥、会话 |
60
+
61
+ #### 核心概念详解
62
+
63
+ ##### 资源服务(Resource Server)与 audience
64
+
65
+ 每个需要 access_token 的 API 是一个资源服务,`identifier` 即 token 的 `aud`。默认自动注册:
66
+
67
+ | 资源 | identifier | scope | 用途 |
68
+ |------|------------|-------|------|
69
+ | 本项目 API | `${ORIGIN}/api` | `api` | SPA 调用本项目接口 |
70
+ | 服务接口 | `${issuer origin}${prefix}` | `user:read tenant:read` | 子项目以 client_credentials 读取用户 / 租户 |
71
+
72
+ client 只能申请 `allowedResources` 中的资源;子项目 token 的 `aud` 是子项目 API,拿到主项目会被拒绝。
73
+
74
+ ##### 租户上下文
75
+
76
+ 登录后增加一个自定义交互步骤 `tenant`(位于 login 与 consent 之间),选定的租户按 IdP 会话保存:
77
+
78
+ | 情况 | 行为 |
79
+ |------|------|
80
+ | 用户不属于任何租户 | 跳过,token 不带租户 claims |
81
+ | 只属于一个租户 | 自动选中 |
82
+ | 多个租户 | 前端展示租户列表 |
83
+ | 授权请求带 `tenant_id` 且用户是成员 | 静默切换(可配合 `prompt=none`) |
84
+ | 会话中的租户已不再有效(被移出、关闭) | 重新判断上面几种情况 |
85
+
86
+ token 中的租户相关 claim 以命名空间为前缀(默认 `${ORIGIN}/`,central 模式为 issuer 的 origin):`tenant_id`、`tenant_user_id`、`roles`、`permissions`(按资源服务 `includePermissions` 决定是否携带)。
87
+
88
+ ##### 令牌撤销
89
+
90
+ JWT access_token 无法真正撤销,插件在资源侧维护一个撤销列表:
91
+
92
+ | 触发 | 撤销方式 |
93
+ |------|----------|
94
+ | RP-Initiated Logout(standalone) | 会话中各 client 的 `sid` 加入撤销列表 |
95
+ | Back-Channel Logout(central) | 子项目收到 logout_token 后撤销 `sid`(无 sid 时按 `sub`) |
96
+ | 权限变化 `onPermissionChange` | 撤销该用户所有 grant / refresh token,并拒绝撤销时间之前签发的 token;IdP 会话保留,前端静默重新获取带新权限的 token |
97
+ | 管理接口强制下线 | 同上,并结束 IdP 会话、发送 back-channel logout |
98
+
99
+ > **注意**:撤销列表默认存内存,多实例部署时需通过 `revocationStore` 传入共享存储(见 API 文档)。central 子项目的撤销列表与主项目相互独立,权限变化只在主项目生效,子项目依赖较短的 access_token 有效期(默认 10 分钟)。
100
+
101
+ #### 主要特性
102
+
103
+ | 特性 | 说明 |
104
+ |------|------|
105
+ | 授权码 + PKCE | SPA 公共 client,`token_endpoint_auth_method: none` |
106
+ | JWT access_token | RS256 签名,`typ: at+jwt`,按资源服务区分 `aud` |
107
+ | Refresh Token 轮转 | 每次刷新签发新 refresh token,旧的立即失效 |
108
+ | 多租户 | 交互式 / 自动 / 静默切换租户,租户信息写入 token |
109
+ | SSO | 多个项目共用主项目 IdP 会话 |
110
+ | RP-Initiated Logout / Back-Channel Logout | 登出时通知所有子项目 |
111
+ | DPoP | 前端可选启用,token 与浏览器密钥绑定,资源侧校验 proof 与重放 |
112
+ | Client Credentials | 服务间调用,token 带 `client_token` 标记,只能访问 `authenticate.client` 保护的接口 |
113
+ | Token Exchange(RFC 8693) | 服务端代用户换取访问其它资源服务的 token,token 带 `act` |
114
+ | 签名密钥轮换 | active / next / retired 三态,多实例定期检测并热加载 |
115
+ | 兼容旧 token | `legacyToken` 开启时,无 `Authorization` 头回退到 fastify-account 的 `x-user-token` |
116
+ | 国际化 | 注册 @kne/fastify-intl 后错误信息、协议错误描述、登出页按请求语言返回(内置 `zh-CN` / `en-US`) |
117
+
118
+ #### 使用方法
119
+
120
+ ##### 主项目 / 独立项目(standalone)
121
+
122
+ 注册顺序:`fastify-sequelize` → `fastify-account` → `fastify-tenant` → `fastify-oidc`。
123
+
124
+ ```js
125
+ // server 插件注册
126
+ // 可选:注册后错误信息按请求语言(x-user-locale / accept-language)返回,否则固定返回中文
127
+ fastify.register(require('@kne/fastify-intl'), { defaultLocale: 'zh-CN' });
128
+
129
+ fastify.register(require('@kne/fastify-account'), {
130
+ // 让 fastify-account 自身的接口(如 getUserInfo)也接受 OIDC access_token
131
+ getUserAuthenticate: () => fastify.oidc.authenticate.user
132
+ });
133
+
134
+ fastify.register(require('@kne/fastify-tenant'), {
135
+ getUserAuthenticate: () => fastify.oidc.authenticate.user,
136
+ // 角色 / 成员 / 租户变化后撤销已签发的 token
137
+ onPermissionChange: payload => fastify.oidc.onPermissionChange(payload)
138
+ });
139
+
140
+ fastify.register(require('@kne/fastify-oidc'), {
141
+ // mode / origin / keyEncryptionSecret 默认读取环境变量,见下表
142
+ });
143
+
144
+ // 其它 kne 插件的 getAuthenticate 改用 fastify.oidc.authenticate
145
+ fastify.register(require('@kne/fastify-file-manager'), {
146
+ getAuthenticate: () => [fastify.oidc.authenticate.user]
147
+ });
148
+ ```
149
+
150
+ | 环境变量 | 必填 | 说明 |
151
+ |----------|------|------|
152
+ | `ORIGIN` | 是 | 本项目对外访问的 origin,如 `https://a.example.com` |
153
+ | `AUTH_MODE` | 否 | `standalone`(默认)/ `central` |
154
+ | `OIDC_KEY_SECRET` | 是(standalone) | 加密签名私钥与 client_secret 的密钥,未配置时使用不安全的默认值并告警 |
155
+ | `OIDC_COOKIE_SECRET` | 否 | 交互 cookie 签名密钥,默认由 `OIDC_KEY_SECRET` 派生 |
156
+
157
+ `fastify.sequelize.sync()` 完成后 IdP 才会初始化(生成密钥、写入默认 client / 资源服务),此前访问 `/oidc/*` 返回 503;需要等待时可 `await fastify.oidc.whenReady()`。
158
+
159
+ ##### 子项目(central)
160
+
161
+ ```js
162
+ fastify.register(require('@kne/fastify-account'), {
163
+ getUserAuthenticate: () => fastify.oidc.authenticate.user
164
+ });
165
+ fastify.register(require('@kne/fastify-oidc'), {
166
+ mode: 'central'
167
+ });
168
+ ```
169
+
170
+ | 环境变量 | 必填 | 说明 |
171
+ |----------|------|------|
172
+ | `AUTH_MODE` | 是 | `central` |
173
+ | `ORIGIN` | 是 | 子项目 origin |
174
+ | `OIDC_ISSUER` | 是 | 主项目 issuer,如 `https://a.example.com/oidc` |
175
+ | `OIDC_CLIENT_ID` | 否 | 子项目 SPA 在主项目注册的 client_id,默认 `oidc-spa` |
176
+ | `OIDC_SERVICE_CLIENT_ID` / `OIDC_SERVICE_CLIENT_SECRET` | 建议 | 子项目服务端 client,用于拉取用户资料(镜像)与远程租户信息 |
177
+
178
+ 在主项目管理后台(或 `clients` / `resourceServers` 选项)登记子项目:
179
+
180
+ ```js
181
+ // 主项目 fastify-oidc 选项
182
+ {
183
+ resourceServers: [{ identifier: 'https://b.example.com/api', name: 'B 项目 API' }],
184
+ clients: [
185
+ {
186
+ clientId: 'b-spa',
187
+ redirect_uris: ['https://b.example.com/oidc-callback'],
188
+ post_logout_redirect_uris: ['https://b.example.com/'],
189
+ backchannel_logout_uri: 'https://b.example.com/api/oidc/backchannel-logout',
190
+ backchannel_logout_session_required: true,
191
+ allowedResources: ['https://b.example.com/api']
192
+ },
193
+ {
194
+ clientId: 'b-service',
195
+ grant_types: ['client_credentials'],
196
+ response_types: [],
197
+ token_endpoint_auth_method: 'client_secret_basic',
198
+ allowedResources: ['https://a.example.com/api/oidc']
199
+ }
200
+ ]
201
+ }
202
+ ```
203
+
204
+ > **建议**:子项目 client 配置 `backchannel_logout_session_required: true`,登出通知会携带 `sid`,子项目只撤销该会话的 token;否则按用户撤销。
205
+
206
+ ##### 前端
207
+
208
+ 前端使用 components-admin 的 `Oidc` 模块(授权码 + PKCE,可选 DPoP),管理后台使用 `OidcAdmin` 模块。默认路径:
209
+
210
+ | 路径 | 组件 | 说明 |
211
+ |------|------|------|
212
+ | `/oidc-interaction` | `components-admin:Oidc@Interaction` | 登录交互页(`interactionPage`),参数 `uid`;仅 IdP 项目需要 |
213
+ | `/oidc-callback` | `components-admin:Oidc@Callback` | 授权回调页(`callbackPath`) |
214
+
215
+ 在 `preset.js` 中创建 client,并接入 ajax 拦截器与 preset:
216
+
217
+ ```js
218
+ import { loadModule } from '@kne/remote-loader';
219
+ import createAjax from '@kne/axios-fetch';
220
+
221
+ export const globalInit = async () => {
222
+ const { createOidcClient } = await loadModule('components-admin:Oidc');
223
+ const oidc = createOidcClient({
224
+ issuer: window.runtimeOidcIssuer || `${window.location.origin}/oidc`,
225
+ clientId: window.runtimeOidcClientId,
226
+ resource: `${window.location.origin}/api`
227
+ });
228
+ const ajax = createAjax({
229
+ baseURL: baseApiUrl,
230
+ errorHandler: error => message.error(error),
231
+ registerInterceptors: interceptors => oidc.registerInterceptors(interceptors)
232
+ });
233
+ // ...fetchPreset / remoteLoaderPreset 同原有配置
234
+ return { ajax, oidc, apis: getApis() };
235
+ };
236
+ ```
237
+
238
+ 需要登录的路由用 `components-admin:Oidc@OidcAuthenticate` 包裹(替代原 `X-User-Token` 登录跳转),原有的 `UserInfo` / `AfterUserLoginLayout` 可继续使用:请求已自动携带 `Authorization`,fastify-account 的 `authenticate.user` 通过 `getUserAuthenticate` 委托给 fastify-oidc 校验。租户切换使用 `components-admin:Oidc@TenantSwitch`,退出使用 `components-admin:Oidc@OidcLogout`。
239
+
240
+ > **注意**:前端路由不能放在 issuer 路径(默认 `/oidc`)下,否则会被 oidc-provider 接管。`clientId`、`resource` 需与 `OIDC_CLIENT_ID`、`OIDC_AUDIENCE` 一致,`redirectUri` 需在 client 的 `redirect_uris` 中登记。
241
+
242
+ ##### 运行环境
243
+
244
+ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求 Node.js `>= 22.12`;在 oidc-provider 未列入支持范围的 Node 版本上启动时会输出 `Unsupported runtime` 警告,不影响运行。
245
+
246
+
247
+ ### 示例
248
+
249
+ ### API
250
+
251
+ #### 配置项
252
+
253
+ ##### 基础
254
+
255
+ | 属性名 | 类型 | 必填 | 默认值 | 说明 |
256
+ |--------|------|------|--------|------|
257
+ | name | string | 否 | `oidc` | 命名空间名称,即 `fastify.oidc` |
258
+ | prefix | string | 否 | `/api/oidc` | 插件接口前缀(交互、管理、服务接口) |
259
+ | dbTableNamePrefix | string | 否 | `t_` | 表名前缀,表名形如 `t_oidc_payload` |
260
+ | mode | string | 否 | `AUTH_MODE` 或 `standalone` | `standalone` / `central` |
261
+ | origin | string | 是 | `ORIGIN` | 本项目对外 origin |
262
+ | issuer | string | central 必填 | `OIDC_ISSUER`;standalone 为 `${origin}${mountPath}` | issuer 必须带路径 |
263
+ | mountPath | string | 否 | `/oidc` | standalone 未配置 issuer 时 IdP 的挂载路径 |
264
+ | audience | string | 否 | `OIDC_AUDIENCE` 或 `${origin}/api` | 本项目 API 的资源标识,即 access_token 的 `aud` |
265
+ | clientId | string | 否 | `OIDC_CLIENT_ID` 或 `${name}-spa` | 本项目 SPA 的 client_id |
266
+ | claimNamespace | string | 否 | standalone 为 `${origin}/`,central 为 `${issuer origin}/` | 自定义 claim 前缀 |
267
+ | accountNamespace | string | 否 | `account` | fastify-account 命名空间 |
268
+ | tenantNamespace | string | 否 | `tenant` | fastify-tenant 命名空间,不存在时不启用租户 |
269
+ | intlNamespace | string | 否 | `intl` | @kne/fastify-intl 命名空间,不存在时返回内置中文文案 |
270
+
271
+ ##### IdP(standalone)
272
+
273
+ | 属性名 | 类型 | 必填 | 默认值 | 说明 |
274
+ |--------|------|------|--------|------|
275
+ | keyEncryptionSecret | string | 是 | `OIDC_KEY_SECRET` | 加密签名私钥、client_secret;未配置时使用不安全默认值并告警 |
276
+ | cookieSecret | string | 否 | `OIDC_COOKIE_SECRET`,否则由 keyEncryptionSecret 派生 | 交互 cookie 签名 |
277
+ | trustProxy | boolean | 否 | `true` | 信任 `X-Forwarded-*`(部署在反向代理后) |
278
+ | allowPrivateFetch | boolean / function | 否 | `false` | oidc-provider 默认禁止向内网 / 回环地址发请求(back-channel logout 等);内网部署时设为 `true` 或 `url => boolean` |
279
+ | adapter | function | 否 | `null` | 自定义存储 adapter(如 Redis),见「自定义 adapter」 |
280
+ | ttl | object | 否 | 见下表 | 各类令牌有效期(秒) |
281
+ | clockTolerance | number | 否 | `5` | 时钟偏差容忍(秒) |
282
+ | retiredKeyTTL | number | 否 | `172800` | 退役密钥保留时长(秒),应大于 access_token / id_token 最长有效期 |
283
+ | keyReloadInterval | number | 否 | `60` | 多实例检测密钥变化的间隔(秒),`0` 关闭 |
284
+ | cleanupInterval | number | 否 | `3600` | 清理过期数据间隔(秒),`0` 关闭 |
285
+ | interactionPage | string | 否 | `/oidc-interaction` | 前端交互页路径 |
286
+ | callbackPath | string | 否 | `/oidc-callback` | 本项目 SPA 回调路径(用于默认 client) |
287
+ | includePermissions | boolean | 否 | `false` | 资源服务未设置时,token 是否携带 permissions |
288
+ | defaultResourceScope | string | 否 | `api` | 资源服务默认 scope |
289
+ | seedSelf | boolean | 否 | `true` | 启动时自动登记本项目 SPA client、本项目 API、服务接口资源 |
290
+ | selfClient | object | 否 | `{}` | 覆盖默认 SPA client 的 metadata |
291
+ | clients | array | 否 | `[]` | 启动时登记的 client(已存在则跳过),字段同管理接口 `client/create`,metadata 直接平铺 |
292
+ | resourceServers | array | 否 | `[]` | 启动时登记的资源服务(已存在则跳过) |
293
+ | serviceScopes | array | 否 | `['user:read', 'tenant:read']` | 服务接口资源的 scope |
294
+ | getAuthenticate | function | 否 | 见下文 | 管理接口鉴权,参数为 `client:manage` / `resource-server:manage` / `key:manage` / `session:manage` |
295
+
296
+ `ttl` 默认值:
297
+
298
+ | 键 | 默认值 | 说明 |
299
+ |----|--------|------|
300
+ | accessToken | `600` | access_token,资源服务可单独配置 |
301
+ | idToken | `3600` | id_token |
302
+ | refreshToken | `1209600` | refresh_token(14 天) |
303
+ | interaction | `600` | 登录交互 |
304
+ | session | `1209600` | IdP 会话 |
305
+ | grant | `1209600` | 授权记录 |
306
+
307
+ `getAuthenticate` 默认:`*:manage` 返回 `[authenticate.user, authenticate.admin]`,其余返回 `[authenticate.user]`。
308
+
309
+ ##### 资源侧
310
+
311
+ | 属性名 | 类型 | 必填 | 默认值 | 说明 |
312
+ |--------|------|------|--------|------|
313
+ | legacyToken | boolean | 否 | `true` | 无 `Authorization` 头时回退到 fastify-account 的 `x-user-token` |
314
+ | requireDPoP | boolean | 否 | `false` | 只接受 DPoP 绑定的 token |
315
+ | tenantSource | string | 否 | standalone 且有 fastify-tenant 为 `local`,否则 `claims` | `authenticate.tenantUser` 的数据来源:`local` 实时查本地 fastify-tenant;`claims` 由 token 构造;`remote` 调主项目服务接口 |
316
+ | tenantUserContextName | string | 否 | `tenantUserInfo` | 租户用户挂载到 request 上的字段名 |
317
+ | revocationStore | object | 否 | 内存 | 撤销列表存储,见「撤销列表存储」 |
318
+ | dpopReplayStore | object | 否 | 内存 | DPoP proof 防重放存储,接口同 revocationStore |
319
+ | getRequestUrl | function | 否 | `${origin}${request.raw.url}` | 计算 DPoP `htu` 比对用的请求地址 |
320
+ | serviceClient | object | 否 | `{ clientId: OIDC_SERVICE_CLIENT_ID, clientSecret: OIDC_SERVICE_CLIENT_SECRET }` | 服务端 client(central 拉取用户资料、远程租户、token exchange) |
321
+ | serviceAudience | string | 否 | `${issuer origin}${prefix}` | 服务接口资源标识 |
322
+ | idpApiBase | string | 否 | `${issuer origin}${prefix}` | 主项目服务接口地址 |
323
+ | jwksUri | string | 否 | `${issuer}/jwks` | central 模式远程 JWKS 地址 |
324
+ | userMirrorTTL | number | 否 | `600` | central 模式用户镜像缓存时长(秒) |
325
+
326
+ #### 接口
327
+
328
+ ##### OIDC 协议端点(standalone)
329
+
330
+ 挂载在 issuer 路径下(默认 `/oidc`),由 oidc-provider 提供,以 `GET {issuer}/.well-known/openid-configuration` 为准:
331
+
332
+ | 端点 | 路径 | 说明 |
333
+ |------|------|------|
334
+ | discovery | `GET /oidc/.well-known/openid-configuration` | 元数据 |
335
+ | authorization | `GET /oidc/auth` | 授权请求,额外支持 `tenant_id` 参数 |
336
+ | token | `POST /oidc/token` | authorization_code / refresh_token / client_credentials / token-exchange |
337
+ | jwks | `GET /oidc/jwks` | 公钥集 |
338
+ | userinfo | `GET /oidc/me` | 用户信息(需 issuer 作为 aud 的 token) |
339
+ | end_session | `GET /oidc/session/end` | RP-Initiated Logout |
340
+ | revocation / introspection | `POST /oidc/token/revocation`、`POST /oidc/token/introspection` | 撤销、内省 |
341
+
342
+ ##### 登录交互(standalone)
343
+
344
+ 前端交互页通过以下接口驱动流程,均依赖交互 cookie,需与 IdP 同源调用。成功时返回 `{ redirectTo }`,前端 `window.location` 跳转即可。
345
+
346
+ ###### GET /api/oidc/interaction/{uid}
347
+
348
+ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={uid}`。
349
+
350
+ ###### GET /api/oidc/interaction/{uid}/details
351
+
352
+ 获取当前步骤:
353
+
354
+ ```json
355
+ {
356
+ "uid": "xxx",
357
+ "prompt": { "name": "login", "reasons": ["no_session"], "details": {} },
358
+ "params": { "clientId": "oidc-spa", "scope": "openid profile offline_access api", "resource": "https://a.example.com/api", "tenantId": null, "loginHint": null, "uiLocales": null },
359
+ "client": { "clientId": "oidc-spa", "clientName": "oidc 前端", "logoUri": null, "clientUri": null },
360
+ "user": null,
361
+ "tenants": null
362
+ }
363
+ ```
364
+
365
+ `prompt.name` 为 `login` / `tenant` / `consent`;已登录时 `user` 为 `{ id, nickname, avatar, email, phone }`;`tenant` 步骤时 `tenants` 为 `{ list: [{ tenantId, tenantUserId, name, logo, companyName }], defaultTenantId }`。
366
+
367
+ ###### POST /api/oidc/interaction/{uid}/login
368
+
369
+ | 参数 | 类型 | 必填 | 默认值 | 说明 |
370
+ |------|------|------|--------|------|
371
+ | type | string | 否 | `email` | `email` / `phone` |
372
+ | email / phone | string | 否 | - | 账号 |
373
+ | password | string | 是 | - | 与 fastify-account 登录一致(前端 md5) |
374
+ | remember | boolean | 否 | `true` | `false` 时 IdP 会话随浏览器关闭失效 |
375
+
376
+ 账号密码错误返回 400;账号状态不是 0 / 1 时返回 `{ status }`(与 fastify-account 登录一致,由前端处理如重置密码)。
377
+
378
+ ###### POST /api/oidc/interaction/{uid}/tenant
379
+
380
+ 参数 `tenantId`(必填)。只能选择当前用户所属且开启的租户。
381
+
382
+ ###### POST /api/oidc/interaction/{uid}/confirm
383
+
384
+ 确认授权(`skip_consent: false` 的 client 才会出现 consent 步骤)。
385
+
386
+ ###### POST /api/oidc/interaction/{uid}/abort
387
+
388
+ 取消登录,client 回调收到 `error=access_denied`。
389
+
390
+ ##### 管理接口(standalone)
391
+
392
+ 列表 `GET`(`filter`、`perPage`、`currentPage`),写操作 `POST`,`save` / `set-status` / `remove` 返回 `{}`。
393
+
394
+ | 接口 | 说明 | 鉴权 type |
395
+ |------|------|-----------|
396
+ | `GET /api/oidc/admin/client/list` | client 列表(`filter.keyword` / `filter.status`),不返回 secret | `client:manage` |
397
+ | `GET /api/oidc/admin/client/detail?id=` | client 详情 | `client:manage` |
398
+ | `POST /api/oidc/admin/client/create` | 创建,参数 `clientId`、`clientName`、`clientSecret`、`metadata`、`allowedResources`、`description`;confidential client 返回一次明文 `clientSecret` | `client:manage` |
399
+ | `POST /api/oidc/admin/client/save` | 修改 | `client:manage` |
400
+ | `POST /api/oidc/admin/client/set-status` | `{ id, status: open / closed }` | `client:manage` |
401
+ | `POST /api/oidc/admin/client/remove` | 删除 | `client:manage` |
402
+ | `POST /api/oidc/admin/client/rotate-secret` | 重置 secret,返回 `{ clientId, clientSecret }` | `client:manage` |
403
+ | `GET /api/oidc/admin/resource-server/list` / `detail` | 资源服务列表 / 详情 | `resource-server:manage` |
404
+ | `POST /api/oidc/admin/resource-server/create` / `save` / `set-status` / `remove` | 参数 `identifier`(绝对 URI)、`name`、`scope`、`accessTokenTTL`、`includePermissions`、`description` | `resource-server:manage` |
405
+ | `GET /api/oidc/admin/key/list` | 签名密钥列表 `[{ id, kid, alg, status, activatedAt, retiredAt, createdAt }]` | `key:manage` |
406
+ | `POST /api/oidc/admin/key/rotate` | 轮换签名密钥 | `key:manage` |
407
+ | `GET /api/oidc/admin/session/list?userId=` | 用户 IdP 会话 `[{ uid, loginAt, expiresAt, clients: [{ clientId, sid }] }]` | `session:manage` |
408
+ | `POST /api/oidc/admin/session/revoke` | `{ uid }` 结束会话并通知子项目 | `session:manage` |
409
+ | `POST /api/oidc/admin/session/revoke-user` | `{ userId, logout = true }` 撤销用户全部令牌,`logout` 时同时强制下线;返回 `{ grants, sessions }` | `session:manage` |
410
+
411
+ ##### 服务接口(standalone,client_credentials)
412
+
413
+ 需 `aud` 为 `serviceAudience`、带 `client_token` 标记的 token。
414
+
415
+ | 接口 | scope | 说明 |
416
+ |------|-------|------|
417
+ | `GET /api/oidc/service/user?id=` | `user:read` | 用户资料 `{ id, nickname, avatar, email, phone, gender, birthday, description, status }` |
418
+ | `GET /api/oidc/service/tenant-user?userId=&tenantId=` | `tenant:read` | 用户在租户内的身份、角色、权限(fastify-tenant `getTenantUserInfo` 结果) |
419
+
420
+ ##### Back-Channel Logout(central)
421
+
422
+ `POST /api/oidc/backchannel-logout`,`application/x-www-form-urlencoded`,参数 `logout_token`。校验通过后撤销 `sid`(无 sid 时按 `sub`),返回 200。
423
+
424
+ #### 程序化 API
425
+
426
+ ##### fastify.oidc.authenticate
427
+
428
+ | 方法 | 说明 |
429
+ |------|------|
430
+ | `authenticate.user` | 校验 `Authorization: Bearer / DPoP`,填充 `request.user` 与兼容字段;无 token 且 `legacyToken` 时回退 `x-user-token`;拒绝 client 令牌 |
431
+ | `authenticate.tenantUser` | 按 `tenantSource` 填充 `request.tenantUserInfo`;legacy 请求委托给 fastify-tenant |
432
+ | `authenticate.admin` | 委托 fastify-account 的超级管理员校验 |
433
+ | `authenticate.scope(...scopes)` | 返回中间件,校验 token scope |
434
+ | `authenticate.permission(...codes)` | 返回中间件,校验租户权限(`local` / `remote` 实时查询;`claims` 使用 token 中的 permissions) |
435
+ | `authenticate.client(...scopes)` | 返回中间件,只接受 `aud` 为 `serviceAudience` 的 client 令牌 |
436
+
437
+ `request.user` 结构:
438
+
439
+ | 属性名 | 类型 | 说明 |
440
+ |--------|------|------|
441
+ | userId | string | 用户 id(`sub`),client 令牌为 `null` |
442
+ | tenantId / tenantUserId | string | 当前租户 / 租户用户 id |
443
+ | roles | array | 角色 code |
444
+ | permissions | array | token 携带的权限,未携带为 `null` |
445
+ | clientId | string | 签发 token 的 client |
446
+ | scope | array | scope 列表 |
447
+ | sid | string | 会话 id |
448
+ | actor | string | token exchange 的调用方 client |
449
+ | isClient | boolean | 是否 client 令牌 |
450
+ | legacy | boolean | 是否来自 `x-user-token` 回退 |
451
+ | expiresAt | number | 过期时间(秒) |
452
+ | payload | object | 原始 claims |
453
+
454
+ 兼容字段:`request.authenticatePayload = { id, tenantId }`,`request.userInfo` 为 fastify-account 用户(central 为镜像用户)。
455
+
456
+ ##### 其它
457
+
458
+ | 方法 | 说明 |
459
+ |------|------|
460
+ | `fastify.oidc.whenReady()` | 等待 IdP 初始化完成(`sequelize.sync()` 之后) |
461
+ | `fastify.oidc.onPermissionChange({ userIds, logout = false })` | 撤销用户已签发的令牌,供 fastify-tenant `onPermissionChange` 调用 |
462
+ | `fastify.oidc.services.grant.revokeByAccount(userId, { logout })` | 同上,单个用户 |
463
+ | `fastify.oidc.services.grant.listSessions({ userId })` / `revokeSession({ uid })` | 会话管理 |
464
+ | `fastify.oidc.services.key.rotate()` | 轮换签名密钥并热加载 |
465
+ | `fastify.oidc.services.client.*` / `resourceServer.*` | 同管理接口 |
466
+ | `fastify.oidc.serviceClient.getServiceToken({ resource, scope })` | client_credentials 取 token(带缓存) |
467
+ | `fastify.oidc.serviceClient.getUserProfile(userId)` / `getTenantUser({ userId, tenantId })` | 调主项目服务接口 |
468
+ | `fastify.oidc.serviceClient.exchangeToken({ subjectToken, resource, scope })` | Token Exchange |
469
+ | `fastify.oidc.revocation.revokeSession(sid)` / `revokeSubject(sub)` / `isRevoked(payload)` | 撤销列表 |
470
+ | `fastify.oidc.idp.getProvider()` | oidc-provider 实例(standalone) |
471
+
472
+ #### 数据模型
473
+
474
+ 以下表只在 standalone 模式创建。
475
+
476
+ ##### payload(`t_oidc_payload`)
477
+
478
+ | 属性名 | 类型 | 说明 |
479
+ |--------|------|------|
480
+ | modelName | string | oidc-provider 模型名,如 Session、AccessToken、Grant |
481
+ | payloadId | string | oidc-provider 生成的 id |
482
+ | payload | JSON | 完整 payload |
483
+ | grantId | string | 所属 grant,用于按 grant 撤销 |
484
+ | userCode | string | device flow user code |
485
+ | uid | string | Session uid |
486
+ | accountId | string | 用户 id,用于按用户撤销 / 列出会话 |
487
+ | expiresAt | Date | 过期时间 |
488
+ | consumedAt | Date | 已使用时间(授权码、轮转后的 refresh token) |
489
+
490
+ 唯一索引 `(model_name, payload_id)`;索引 `grant_id`、`uid`、`user_code`、`(account_id, model_name)`、`expires_at`。
491
+
492
+ ##### client(`t_oidc_client`)
493
+
494
+ | 属性名 | 类型 | 说明 |
495
+ |--------|------|------|
496
+ | clientId | string | client_id(唯一) |
497
+ | clientName | string | 应用名称 |
498
+ | clientSecret | text | 加密存储的 client_secret,public client 为空 |
499
+ | metadata | JSON | OIDC client metadata,另支持 `skip_consent`(默认免确认)、`backchannel_logout_uri` 等 |
500
+ | allowedResources | JSON | 允许申请的资源服务 identifier |
501
+ | description | text | 描述 |
502
+ | status | string | `open` / `closed` |
503
+
504
+ ##### resourceServer(`t_oidc_resource_server`)
505
+
506
+ | 属性名 | 类型 | 说明 |
507
+ |--------|------|------|
508
+ | identifier | string | 资源标识,即 access_token 的 `aud`(唯一) |
509
+ | name | string | 名称 |
510
+ | scope | string | 支持的 scope,空格分隔 |
511
+ | accessTokenTTL | number | access_token 有效期(秒),为空使用 `ttl.accessToken` |
512
+ | includePermissions | boolean | 是否携带 permissions,为空使用 `includePermissions` |
513
+ | description | text | 描述 |
514
+ | status | string | `open` / `closed` |
515
+
516
+ ##### key(`t_oidc_key`)
517
+
518
+ | 属性名 | 类型 | 说明 |
519
+ |--------|------|------|
520
+ | kid | string | JWK kid(唯一) |
521
+ | alg | string | 签名算法(RS256) |
522
+ | privateJwk | text | 加密存储的私钥 |
523
+ | publicJwk | JSON | 公钥 |
524
+ | status | string | `active` 当前签名 / `next` 已发布待启用 / `retired` 仅验签 |
525
+ | activatedAt / retiredAt | Date | 启用 / 退役时间 |
526
+
527
+ ##### sessionTenant(`t_oidc_session_tenant`)
528
+
529
+ | 属性名 | 类型 | 说明 |
530
+ |--------|------|------|
531
+ | sessionUid | string | IdP 会话 uid(唯一) |
532
+ | accountId | string | 用户 id |
533
+ | tenantId | string | 会话当前租户 |
534
+
535
+ #### 机制说明
536
+
537
+ ##### 自定义 adapter(如 Redis)
538
+
539
+ 默认 oidc-provider 的数据存于 `payload` 表。高并发场景可通过 `adapter` 改用 Redis 等存储,插件不内置实现,由业务按以下约定自行编写。Client 始终从 `client` 表读取,不经过 adapter。
540
+
541
+ `adapter` 为 class(`new Adapter(name)`)或工厂函数(`name => instance`),`name` 为 oidc-provider 模型名:
542
+
543
+ | 方法 | 说明 |
544
+ |------|------|
545
+ | `upsert(id, payload, expiresIn)` | 写入,`expiresIn` 秒后过期(映射为 Redis TTL) |
546
+ | `find(id)` | 读取,不存在或过期返回 `undefined` |
547
+ | `findByUid(uid)` | 按 Session uid 读取(Session 模型) |
548
+ | `findByUserCode(userCode)` | device flow,可不实现 |
549
+ | `consume(id)` | 标记已使用:payload 写入 `consumed` 秒级时间戳 |
550
+ | `destroy(id)` | 删除 |
551
+ | `revokeByGrantId(grantId)` | 删除该 grant 下的所有记录 |
552
+ | `findGrantIdsByAccountId(accountId)` | **kne 扩展**,Grant 模型调用,返回该用户的 grantId 列表;未实现时无法按用户撤销 |
553
+ | `findByAccountId(accountId)` | **kne 扩展**,Session 模型调用,返回该用户的会话 payload;未实现时管理接口无法列出 / 强制下线 |
554
+
555
+ ```js
556
+ // 业务项目 libs/oidc-redis-adapter.js(示意,基于 ioredis)
557
+ const createRedisAdapter = redis =>
558
+ class RedisAdapter {
559
+ constructor(name) {
560
+ this.name = name;
561
+ }
562
+ key(id) {
563
+ return `oidc:${this.name}:${id}`;
564
+ }
565
+ async upsert(id, payload, expiresIn) {
566
+ const multi = redis.multi();
567
+ multi.set(this.key(id), JSON.stringify(payload), ...(expiresIn ? ['EX', expiresIn] : []));
568
+ if (payload.grantId) {
569
+ // grant 下的所有令牌,用于 revokeByGrantId
570
+ multi.rpush(`oidc:grant:${payload.grantId}`, this.key(id));
571
+ if (expiresIn) multi.expire(`oidc:grant:${payload.grantId}`, expiresIn);
572
+ }
573
+ if (payload.uid) multi.set(`oidc:uid:${payload.uid}`, id, ...(expiresIn ? ['EX', expiresIn] : []));
574
+ if (payload.accountId && ['Grant', 'Session'].includes(this.name)) {
575
+ // kne 扩展:按用户索引 grant / session
576
+ multi.sadd(`oidc:account:${this.name}:${payload.accountId}`, id);
577
+ }
578
+ await multi.exec();
579
+ }
580
+ async find(id) {
581
+ const data = await redis.get(this.key(id));
582
+ return data ? JSON.parse(data) : undefined;
583
+ }
584
+ async findByUid(uid) {
585
+ const id = await redis.get(`oidc:uid:${uid}`);
586
+ return id ? this.find(id) : undefined;
587
+ }
588
+ async consume(id) {
589
+ const payload = await this.find(id);
590
+ if (payload) {
591
+ payload.consumed = Math.floor(Date.now() / 1000);
592
+ await redis.set(this.key(id), JSON.stringify(payload), 'KEEPTTL');
593
+ }
594
+ }
595
+ async destroy(id) {
596
+ await redis.del(this.key(id));
597
+ }
598
+ async revokeByGrantId(grantId) {
599
+ const keys = await redis.lrange(`oidc:grant:${grantId}`, 0, -1);
600
+ await redis.del(...keys, `oidc:grant:${grantId}`);
601
+ }
602
+ async findGrantIdsByAccountId(accountId) {
603
+ const ids = await redis.smembers(`oidc:account:Grant:${accountId}`);
604
+ const alive = await Promise.all(ids.map(id => redis.exists(this.key(id))));
605
+ return ids.filter((id, index) => alive[index]);
606
+ }
607
+ async findByAccountId(accountId) {
608
+ const ids = await redis.smembers(`oidc:account:${this.name}:${accountId}`);
609
+ return (await Promise.all(ids.map(id => this.find(id)))).filter(Boolean);
610
+ }
611
+ };
612
+
613
+ fastify.register(require('@kne/fastify-oidc'), {
614
+ adapter: createRedisAdapter(fastify.redis)
615
+ });
616
+ ```
617
+
618
+ > **注意**:账号索引集合(`oidc:account:*`)不会随成员过期自动清理,`findGrantIdsByAccountId` / `findByAccountId` 需过滤已过期的 id,或定期清理。
619
+
620
+ ##### 撤销列表存储
621
+
622
+ `revocationStore` / `dpopReplayStore` 只需实现两个方法,可直接用 Redis:
623
+
624
+ | 方法 | 说明 |
625
+ |------|------|
626
+ | `get(key)` | 返回值或 `undefined` |
627
+ | `set(key, value, ttlSeconds)` | 写入并设置过期 |
628
+
629
+ ```js
630
+ // 多实例部署:撤销列表与 DPoP 防重放共享
631
+ const store = {
632
+ get: async key => (await fastify.redis.get(`oidc:revocation:${key}`)) ?? undefined,
633
+ set: async (key, value, ttl) => fastify.redis.set(`oidc:revocation:${key}`, value, 'EX', ttl)
634
+ };
635
+ fastify.register(require('@kne/fastify-oidc'), { revocationStore: store, dpopReplayStore: store });
636
+ ```
637
+
638
+ ##### 签名密钥轮换
639
+
640
+ | 状态 | 用途 |
641
+ |------|------|
642
+ | active | 当前签发 token |
643
+ | next | 已发布到 JWKS,下次轮换时启用(让各方提前缓存公钥) |
644
+ | retired | 只用于验证轮换前签发的 token,超过 `retiredKeyTTL` 后删除 |
645
+
646
+ `key.rotate()`:active → retired、next → active、生成新 next。其它实例每 `keyReloadInterval` 秒检测密钥指纹变化并重建 provider。
647
+
648
+ ##### Token Exchange
649
+
650
+ `grant_type=urn:ietf:params:oauth:grant-type:token-exchange`,调用方为已认证的 confidential client,且 `grant_types` 包含该值:
651
+
652
+ | 参数 | 必填 | 说明 |
653
+ |------|------|------|
654
+ | subject_token | 是 | 本 IdP 签发的用户 access_token,其 `aud` 必须在调用方 `allowedResources` 中,且未被撤销 |
655
+ | subject_token_type | 是 | `urn:ietf:params:oauth:token-type:access_token` |
656
+ | resource | 是 | 目标资源,必须在调用方 `allowedResources` 中 |
657
+ | scope | 否 | 默认为目标资源全部 scope |
658
+
659
+ 新 token 保留原用户与租户,`act.sub` 为调用方 client_id。
660
+
661
+ ##### 国际化
662
+
663
+ 返回给前端的错误信息、OAuth `error_description`、登出页文案均通过 [@kne/fastify-intl](https://www.npmjs.com/package/@kne/fastify-intl) 按请求语言翻译:
664
+
665
+ | 场景 | 语言来源 |
666
+ |------|------|
667
+ | `/api/oidc/*` 接口、`authenticate.*` 钩子 | fastify-intl 的 `getRequestLocale(request)`(query `lang` → cookie / header `x-user-locale` → `accept-language`) |
668
+ | `/oidc/*` 协议端点(oidc-provider) | 进入 oidc-provider 前按同样规则解析,存在 `request.raw.kneOidcLocale` |
669
+
670
+ 查找顺序:请求语言 → fastify-intl `defaultLocale` → 内置 `zh-CN`。未注册 fastify-intl 时始终返回内置 `zh-CN`。
671
+
672
+ 内置语言包 `zh-CN`、`en-US` 以命名空间 `locale` 模块挂在 `fastify.oidc.locale`,fastify-intl 会自动以模块名 `oidc` 加载;其它语言可通过 fastify-intl 的 `requestMessages`(模块名 `oidc`)或 fastify-intl-admin 补充,key 与内置语言包一致。
673
+
674
+ 包内抛出的错误带 `messageId` / `messageValues`。业务代码直接调用 `serviceClient` 等方法捕获到错误时,可用 `fastify.oidc.translator.translateError(request, error)` 翻译:
675
+
676
+ | 方法 | 说明 |
677
+ |------|------|
678
+ | `fastify.oidc.translator.t(request \| locale, messageId, values)` | 翻译单条文案 |
679
+ | `fastify.oidc.translator.translateError(request \| locale, error)` | 有 `messageId` 时按请求语言改写 `error.message` |
680
+ | `fastify.oidc.translator.getLocale(request)` | 当前请求语言,未注册 fastify-intl 时为 `null` |
681
+
682
+ > **注意**:启动期的配置校验错误(如缺少 `ORIGIN`、central 未配置 issuer)面向开发者,不做翻译。