@kne/fastify-oidc 0.1.11 → 0.1.13

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.
@@ -1,18 +1,27 @@
1
1
  const fp = require('fastify-plugin');
2
+ const { str, num, any, list, obj, success, empty, pageResult, client, resourceServer, app, key } = require('../schema/response');
2
3
 
3
- const idSchema = { type: 'object', required: ['id'], properties: { id: { type: 'string' } } };
4
+ const idSchema = { type: 'object', required: ['id'], properties: { id: { type: 'string', description: '记录 ID' } } };
4
5
  const listQuery = {
5
6
  type: 'object',
6
7
  properties: {
7
- filter: { type: 'object', additionalProperties: true },
8
- perPage: { type: 'number', default: 20 },
9
- currentPage: { type: 'number', default: 1 }
8
+ filter: {
9
+ type: 'object',
10
+ additionalProperties: true,
11
+ description: '筛选条件',
12
+ properties: {
13
+ keyword: { description: '关键字,模糊匹配编码 / 名称' },
14
+ status: { description: '状态:open 启用,closed 停用' }
15
+ }
16
+ },
17
+ perPage: { type: 'number', default: 20, description: '每页条数' },
18
+ currentPage: { type: 'number', default: 1, description: '页码,从 1 开始' }
10
19
  }
11
20
  };
12
21
  const statusBody = {
13
22
  type: 'object',
14
23
  required: ['id', 'status'],
15
- properties: { id: { type: 'string' }, status: { type: 'string', enum: ['open', 'closed'] } }
24
+ properties: { id: { type: 'string', description: '记录 ID' }, status: { type: 'string', enum: ['open', 'closed'], description: '目标状态:open 启用,closed 停用' } }
16
25
  };
17
26
 
18
27
  module.exports = fp(async (fastify, options) => {
@@ -26,50 +35,57 @@ module.exports = fp(async (fastify, options) => {
26
35
  const clientBody = {
27
36
  type: 'object',
28
37
  properties: {
29
- id: { type: 'string' },
30
- clientId: { type: 'string' },
31
- clientName: { type: 'string' },
32
- clientSecret: { type: 'string' },
33
- metadata: { type: 'object', additionalProperties: true },
34
- allowedResources: { type: 'array', items: { type: 'string' } },
35
- description: { type: 'string' }
38
+ id: { type: 'string', description: '记录 ID,修改时必填,创建时忽略' },
39
+ clientId: { type: 'string', description: 'client_id,仅创建时生效,不传随机生成;不能与已有 client 重复' },
40
+ clientName: { type: 'string', description: '应用名称;修改时不传保持原值' },
41
+ clientSecret: { type: 'string', description: 'client secret,仅创建 confidential client 时生效,不传随机生成;修改请用重置 secret 接口' },
42
+ metadata: {
43
+ type: 'object',
44
+ additionalProperties: true,
45
+ description: 'OIDC client metadata(redirect_uris、post_logout_redirect_uris、grant_types、response_types、token_endpoint_auth_method 等,snake_case),未传的字段使用 public SPA 默认值;修改时传入则整体替换,不传保持原值'
46
+ },
47
+ allowedResources: { type: 'array', items: { type: 'string' }, description: '允许申请的资源服务 identifier 列表;修改时不传保持原值' },
48
+ description: { type: 'string', description: '描述;修改时不传保持原值' }
36
49
  }
37
50
  };
38
51
 
39
52
  const resourceServerBody = {
40
53
  type: 'object',
41
54
  properties: {
42
- id: { type: 'string' },
43
- identifier: { type: 'string' },
44
- name: { type: 'string' },
45
- scope: { type: 'string' },
46
- accessTokenTTL: { type: 'number' },
47
- includePermissions: { type: 'boolean' },
48
- description: { type: 'string' }
55
+ id: { type: 'string', description: '记录 ID,修改时必填,创建时忽略' },
56
+ identifier: { type: 'string', description: 'resource indicator(URL),即 access_token 的 aud;仅创建时生效,不能与已有资源服务重复' },
57
+ name: { type: 'string', description: '资源名称' },
58
+ scope: { type: 'string', description: '支持的 scope,空格分隔;为空使用默认 scope(defaultResourceScope)' },
59
+ accessTokenTTL: { type: 'number', description: 'access_token 有效期(秒),为空使用全局配置' },
60
+ includePermissions: { type: 'boolean', description: 'access_token 中是否携带 permissions,为空使用全局配置' },
61
+ description: { type: 'string', description: '描述' }
49
62
  }
50
63
  };
51
64
 
52
- const crud = (path, tag, service, body) => {
65
+ const crud = ({ path, tag, name, service, body, item, createDescription, saveDescription }) => {
53
66
  const tags = [tag];
54
67
  const onRequest = options.getAuthenticate(`${path}:manage`);
55
68
  fastify.get(
56
69
  `${admin}/${path}/list`,
57
- { onRequest, schema: { tags, summary: `${tag}列表`, query: listQuery } },
70
+ {
71
+ onRequest,
72
+ schema: { tags, summary: `${name}列表`, description: '分页查询,按创建时间倒序', query: listQuery, response: success(`${name}分页列表`, pageResult(name, item)) }
73
+ },
58
74
  wrap(async request => service().list(request.query))
59
75
  );
60
76
  fastify.get(
61
77
  `${admin}/${path}/detail`,
62
- { onRequest, schema: { tags, summary: `${tag}详情`, query: idSchema } },
78
+ { onRequest, schema: { tags, summary: `${name}详情`, query: idSchema, response: success(`${name}详情`, Object.assign({}, item, { nullable: false })) } },
63
79
  wrap(async request => service().detail(request.query))
64
80
  );
65
81
  fastify.post(
66
82
  `${admin}/${path}/create`,
67
- { onRequest, schema: { tags, summary: `创建${tag}`, body } },
83
+ { onRequest, schema: { tags, summary: `创建${name}`, description: createDescription, body, response: success(`创建后的${name}`, Object.assign({}, item, { nullable: false })) } },
68
84
  wrap(async request => service().create(request.body))
69
85
  );
70
86
  fastify.post(
71
87
  `${admin}/${path}/save`,
72
- { onRequest, schema: { tags, summary: `修改${tag}`, body: Object.assign({}, body, { required: ['id'] }) } },
88
+ { onRequest, schema: { tags, summary: `修改${name}`, description: saveDescription, body: Object.assign({}, body, { required: ['id'] }), response: empty('保存成功') } },
73
89
  wrap(async request => {
74
90
  await service().save(request.body);
75
91
  return {};
@@ -77,7 +93,7 @@ module.exports = fp(async (fastify, options) => {
77
93
  );
78
94
  fastify.post(
79
95
  `${admin}/${path}/set-status`,
80
- { onRequest, schema: { tags, summary: `启用 / 停用${tag}`, body: statusBody } },
96
+ { onRequest, schema: { tags, summary: `启用 / 停用${name}`, description: `停用后该${name}不再参与 OIDC 授权`, body: statusBody, response: empty('设置成功') } },
81
97
  wrap(async request => {
82
98
  await service().setStatus(request.body);
83
99
  return {};
@@ -85,7 +101,7 @@ module.exports = fp(async (fastify, options) => {
85
101
  );
86
102
  fastify.post(
87
103
  `${admin}/${path}/remove`,
88
- { onRequest, schema: { tags, summary: `删除${tag}`, body: idSchema } },
104
+ { onRequest, schema: { tags, summary: `删除${name}`, description: `物理删除该${name}`, body: idSchema, response: empty('删除成功') } },
89
105
  wrap(async request => {
90
106
  await service().remove(request.body);
91
107
  return {};
@@ -93,25 +109,74 @@ module.exports = fp(async (fastify, options) => {
93
109
  );
94
110
  };
95
111
 
96
- crud('client', 'OIDC Client', () => services.client, clientBody);
97
- crud('resource-server', 'OIDC 资源服务', () => services.resourceServer, resourceServerBody);
112
+ crud({
113
+ path: 'client',
114
+ tag: 'OIDC管理后台-Client',
115
+ name: 'OIDC Client',
116
+ service: () => services.client,
117
+ body: clientBody,
118
+ item: client,
119
+ createDescription: '创建接入应用。metadata 会经 oidc-provider 校验;confidential client(token_endpoint_auth_method 不为 none)返回中额外带一次 clientSecret 明文,之后不再返回',
120
+ saveDescription: '修改接入应用;clientId 与 clientSecret 不可通过本接口修改。改为 public client 时清除 secret,改为 confidential 且原来没有 secret 时自动生成(不返回明文,需再调用重置 secret)'
121
+ });
122
+ crud({
123
+ path: 'resource-server',
124
+ tag: 'OIDC管理后台-资源服务',
125
+ name: '资源服务',
126
+ service: () => services.resourceServer,
127
+ body: resourceServerBody,
128
+ item: resourceServer,
129
+ createDescription: '注册一个可申请 access_token 的资源服务(API),identifier 必须是合法 URL',
130
+ saveDescription: '修改资源服务;identifier 不可修改,未传的字段保持原值;scope 未传或为空时重置为默认 scope'
131
+ });
98
132
 
99
133
  // 应用由子应用通过服务接口注册,管理端只能查看、启停与删除
100
- const appTags = ['OIDC 应用中心'];
134
+ const appTags = ['OIDC管理后台-子应用'];
101
135
  const appOnRequest = options.getAuthenticate('app:manage');
136
+ const appListQuery = Object.assign({}, listQuery, {
137
+ properties: Object.assign({}, listQuery.properties, {
138
+ filter: Object.assign({}, listQuery.properties.filter, {
139
+ properties: Object.assign({}, listQuery.properties.filter.properties, {
140
+ status: { description: '状态:open 启用,closed 停用;不传返回未删除的全部应用' },
141
+ tenantMode: { description: '租户模式:client / independent' }
142
+ })
143
+ })
144
+ })
145
+ });
102
146
  fastify.get(
103
147
  `${admin}/app/list`,
104
- { onRequest: appOnRequest, schema: { tags: appTags, summary: '子应用列表', query: listQuery } },
148
+ {
149
+ onRequest: appOnRequest,
150
+ schema: {
151
+ tags: appTags,
152
+ summary: '子应用列表',
153
+ description: '分页查询已注册的子应用(不含已删除),按创建时间倒序',
154
+ query: appListQuery,
155
+ response: success('子应用分页列表', pageResult('子应用', app))
156
+ }
157
+ },
105
158
  wrap(async request => services.app.list(request.query))
106
159
  );
107
160
  fastify.get(
108
161
  `${admin}/app/detail`,
109
- { onRequest: appOnRequest, schema: { tags: appTags, summary: '子应用详情(含权限树)', query: idSchema } },
162
+ {
163
+ onRequest: appOnRequest,
164
+ schema: { tags: appTags, summary: '子应用详情(含权限树)', query: idSchema, response: success('子应用详情,permissions 为完整权限树', Object.assign({}, app, { nullable: false })) }
165
+ },
110
166
  wrap(async request => services.app.detail(request.query))
111
167
  );
112
168
  fastify.post(
113
169
  `${admin}/app/set-status`,
114
- { onRequest: appOnRequest, schema: { tags: appTags, summary: '启用 / 停用子应用(停用后从权限树移除)', body: statusBody } },
170
+ {
171
+ onRequest: appOnRequest,
172
+ schema: {
173
+ tags: appTags,
174
+ summary: '启用 / 停用子应用(停用后从权限树移除)',
175
+ description: '停用后该应用的 client 没有可用租户;状态变化时后台通知 independent 子应用回拉快照',
176
+ body: statusBody,
177
+ response: empty('设置成功')
178
+ }
179
+ },
115
180
  wrap(async request => {
116
181
  await services.app.setStatus(request.body);
117
182
  return {};
@@ -119,7 +184,16 @@ module.exports = fp(async (fastify, options) => {
119
184
  );
120
185
  fastify.post(
121
186
  `${admin}/app/remove`,
122
- { onRequest: appOnRequest, schema: { tags: appTags, summary: '删除子应用(子应用下次启动会重新注册)', body: idSchema } },
187
+ {
188
+ onRequest: appOnRequest,
189
+ schema: {
190
+ tags: appTags,
191
+ summary: '删除子应用(子应用下次启动会重新注册)',
192
+ description: '只标记为 removed,保留记录以继续拦截该应用的 client;后台通知 independent 子应用关闭托管租户',
193
+ body: idSchema,
194
+ response: empty('删除成功')
195
+ }
196
+ },
123
197
  wrap(async request => {
124
198
  await services.app.remove(request.body);
125
199
  return {};
@@ -128,19 +202,40 @@ module.exports = fp(async (fastify, options) => {
128
202
 
129
203
  fastify.post(
130
204
  `${admin}/client/rotate-secret`,
131
- { onRequest: options.getAuthenticate('client:manage'), schema: { tags: ['OIDC Client'], summary: '重置 client secret(明文只返回一次)', body: idSchema } },
205
+ {
206
+ onRequest: options.getAuthenticate('client:manage'),
207
+ schema: {
208
+ tags: ['OIDC管理后台-Client'],
209
+ summary: '重置 client secret(明文只返回一次)',
210
+ description: '为 confidential client 生成新的 secret,旧 secret 立即失效;public client 调用返回 400',
211
+ body: idSchema,
212
+ response: success('新的 client secret', { type: 'object', properties: { clientId: str('client_id'), clientSecret: str('新的 client secret 明文,只返回这一次') } })
213
+ }
214
+ },
132
215
  wrap(async request => services.client.rotateSecret(request.body))
133
216
  );
134
217
 
218
+ const keyList = { type: 'array', items: key };
135
219
  fastify.get(
136
220
  `${admin}/key/list`,
137
- { onRequest: options.getAuthenticate('key:manage'), schema: { tags: ['OIDC 签名密钥'], summary: '签名密钥列表' } },
221
+ {
222
+ onRequest: options.getAuthenticate('key:manage'),
223
+ schema: { tags: ['OIDC管理后台-签名密钥'], summary: '签名密钥列表', description: '按 active、next、retired 排序,不返回私钥', response: success('签名密钥列表', keyList) }
224
+ },
138
225
  wrap(async () => services.key.list())
139
226
  );
140
227
 
141
228
  fastify.post(
142
229
  `${admin}/key/rotate`,
143
- { onRequest: options.getAuthenticate('key:manage'), schema: { tags: ['OIDC 签名密钥'], summary: '轮换签名密钥' } },
230
+ {
231
+ onRequest: options.getAuthenticate('key:manage'),
232
+ schema: {
233
+ tags: ['OIDC管理后台-签名密钥'],
234
+ summary: '轮换签名密钥',
235
+ description: '当前 active 密钥退役(仍用于验签),next 密钥启用,并生成新的 next 密钥;清理超过保留期的退役密钥后重载 provider',
236
+ response: success('轮换后的签名密钥列表', keyList)
237
+ }
238
+ },
144
239
  wrap(async () => services.key.rotate())
145
240
  );
146
241
 
@@ -148,7 +243,21 @@ module.exports = fp(async (fastify, options) => {
148
243
  `${admin}/session/list`,
149
244
  {
150
245
  onRequest: options.getAuthenticate('session:manage'),
151
- schema: { tags: ['OIDC 会话'], summary: '用户登录会话列表', query: { type: 'object', required: ['userId'], properties: { userId: { type: 'string' } } } }
246
+ schema: {
247
+ tags: ['OIDC管理后台-会话'],
248
+ summary: '用户登录会话列表',
249
+ description: '列出用户在 IdP 的登录会话及已授权的 client',
250
+ query: { type: 'object', required: ['userId'], properties: { userId: { type: 'string', description: '用户 ID' } } },
251
+ response: success('会话列表', {
252
+ type: 'array',
253
+ items: obj('登录会话', {
254
+ uid: str('会话 uid,结束会话时使用'),
255
+ loginAt: any('登录时间'),
256
+ expiresAt: any('会话过期时间'),
257
+ clients: list('已授权的 client', obj('授权', { clientId: str('client_id'), sid: str('该 client 的会话 sid') }))
258
+ })
259
+ })
260
+ }
152
261
  },
153
262
  wrap(async request => services.grant.listSessions(request.query))
154
263
  );
@@ -157,7 +266,13 @@ module.exports = fp(async (fastify, options) => {
157
266
  `${admin}/session/revoke`,
158
267
  {
159
268
  onRequest: options.getAuthenticate('session:manage'),
160
- schema: { tags: ['OIDC 会话'], summary: '结束指定会话', body: { type: 'object', required: ['uid'], properties: { uid: { type: 'string' } } } }
269
+ schema: {
270
+ tags: ['OIDC管理后台-会话'],
271
+ summary: '结束指定会话',
272
+ description: '撤销该会话下全部授权与令牌,向已授权 client 发送 back-channel logout 通知并删除会话',
273
+ body: { type: 'object', required: ['uid'], properties: { uid: { type: 'string', description: '会话 uid(来自会话列表)' } } },
274
+ response: empty('会话已结束')
275
+ }
161
276
  },
162
277
  wrap(async request => {
163
278
  await services.grant.revokeSession(request.body);
@@ -170,9 +285,18 @@ module.exports = fp(async (fastify, options) => {
170
285
  {
171
286
  onRequest: options.getAuthenticate('session:manage'),
172
287
  schema: {
173
- tags: ['OIDC 会话'],
288
+ tags: ['OIDC管理后台-会话'],
174
289
  summary: '撤销用户全部令牌(logout=true 时同时强制下线)',
175
- body: { type: 'object', required: ['userId'], properties: { userId: { type: 'string' }, logout: { type: 'boolean', default: true } } }
290
+ description: '撤销用户已签发的全部令牌与授权;logout=true 时同时结束全部会话并发送 back-channel logout',
291
+ body: {
292
+ type: 'object',
293
+ required: ['userId'],
294
+ properties: {
295
+ userId: { type: 'string', description: '用户 ID' },
296
+ logout: { type: 'boolean', default: true, description: '是否同时结束会话(强制下线),默认 true;false 时保留会话,前端可静默重新获取令牌' }
297
+ }
298
+ },
299
+ response: success('撤销结果', { type: 'object', properties: { grants: num('撤销的授权数量'), sessions: num('结束的会话数量') } })
176
300
  }
177
301
  },
178
302
  wrap(async request => services.grant.revokeByAccount(request.body.userId, { logout: request.body.logout }))
@@ -1,6 +1,7 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const httpErrors = require('http-errors');
3
3
  const { createError } = require('../utils/intl');
4
+ const { empty } = require('../schema/response');
4
5
 
5
6
  const { BadRequest } = httpErrors;
6
7
 
@@ -24,9 +25,11 @@ module.exports = fp(async (fastify, options) => {
24
25
  `${options.prefix}/backchannel-logout`,
25
26
  {
26
27
  schema: {
27
- tags: ['OIDC 服务接口'],
28
+ tags: ['OIDC-服务接口'],
28
29
  summary: '接收 back-channel logout 通知',
29
- body: { type: 'object', required: ['logout_token'], properties: { logout_token: { type: 'string' } } }
30
+ description: 'central 子项目接收主项目的登出通知(application/x-www-form-urlencoded),验签后把 sid(或 sub)加入本地撤销列表;logout_token 无效返回 400',
31
+ body: { type: 'object', required: ['logout_token'], properties: { logout_token: { type: 'string', description: '主项目签发的 logout token(JWT)' } } },
32
+ response: empty('已处理')
30
33
  }
31
34
  },
32
35
  translator.wrap(async (request, reply) => {
@@ -1,4 +1,5 @@
1
1
  const fp = require('fastify-plugin');
2
+ const { str, bool, success } = require('../schema/response');
2
3
 
3
4
  /**
4
5
  * 前端登录方式发现:免登录,只返回公开信息,不能包含任何密钥
@@ -9,7 +10,21 @@ module.exports = fp(async (fastify, options) => {
9
10
  fastify.get(
10
11
  `${options.prefix}/config`,
11
12
  {
12
- schema: { tags: ['OIDC 配置'], summary: '获取前端登录配置(免登录)' }
13
+ schema: {
14
+ tags: ['OIDC-配置'],
15
+ summary: '获取前端登录配置(免登录)',
16
+ description: '前端据此决定登录方式(发起 OIDC 授权的 issuer、client_id、resource),只包含公开信息',
17
+ response: success('前端登录配置', {
18
+ type: 'object',
19
+ properties: {
20
+ mode: str('部署模式:standalone 独立部署(本项目即 IdP),central 由主项目统一登录'),
21
+ isMain: bool('standalone 模式下是否为主项目'),
22
+ issuer: str('OIDC issuer 地址'),
23
+ clientId: str('前端使用的 client_id'),
24
+ audience: str('申请 access_token 时的 resource(API 资源标识)')
25
+ }
26
+ })
27
+ }
13
28
  },
14
29
  async () => ({
15
30
  mode: options.mode,
@@ -1,4 +1,5 @@
1
1
  const fp = require('fastify-plugin');
2
+ const { str, any, obj, success } = require('../schema/response');
2
3
 
3
4
  module.exports = fp(async (fastify, options) => {
4
5
  const { services, translator } = fastify[options.name];
@@ -7,13 +8,15 @@ module.exports = fp(async (fastify, options) => {
7
8
  }
8
9
  const { wrap } = translator;
9
10
  const base = `${options.prefix}/interaction/:uid`;
10
- const params = { type: 'object', required: ['uid'], properties: { uid: { type: 'string' } } };
11
- const tags = ['OIDC 登录交互'];
11
+ const params = { type: 'object', required: ['uid'], properties: { uid: { type: 'string', description: '交互 uid(oidc-provider 跳转到登录交互页时带上的 uid)' } } };
12
+ const tags = ['OIDC-登录交互'];
13
+ const HINT = '依赖浏览器携带的 oidc-provider 交互 cookie;交互过期或 uid 不匹配返回 400';
14
+ const redirect = description => success(description, { type: 'object', properties: { redirectTo: str('前端需要跳转的地址(回到授权端点继续流程)') } });
12
15
 
13
16
  fastify.get(
14
17
  base,
15
18
  {
16
- schema: { tags, summary: '交互入口,跳转到前端登录交互页', params }
19
+ schema: { tags, summary: '交互入口,跳转到前端登录交互页', description: '303 重定向到前端交互页(interactionPage?uid=<uid>),不返回 JSON', params }
17
20
  },
18
21
  async (request, reply) => {
19
22
  const target = new URL(options.interactionPage, options.runtime.origin);
@@ -25,7 +28,46 @@ module.exports = fp(async (fastify, options) => {
25
28
  fastify.get(
26
29
  `${base}/details`,
27
30
  {
28
- schema: { tags, summary: '获取当前交互详情(步骤、client、用户、可选租户)', params }
31
+ schema: {
32
+ tags,
33
+ summary: '获取当前交互详情(步骤、client、用户、可选租户)',
34
+ description: HINT,
35
+ params,
36
+ response: success('交互详情', {
37
+ type: 'object',
38
+ additionalProperties: true,
39
+ properties: {
40
+ uid: str('交互 uid'),
41
+ prompt: obj('当前步骤', {
42
+ name: str('步骤:login 登录,tenant 选择租户,consent 确认授权'),
43
+ reasons: any('需要该步骤的原因'),
44
+ details: any('步骤详情(如缺少的 scope)')
45
+ }),
46
+ params: obj('授权请求参数', {
47
+ clientId: str('client_id'),
48
+ scope: str('申请的 scope'),
49
+ resource: any('申请的资源服务'),
50
+ tenantId: str('指定的租户 ID'),
51
+ loginHint: str('登录提示'),
52
+ uiLocales: str('界面语言')
53
+ }),
54
+ client: obj('发起授权的 client,不存在时为 null', {
55
+ clientId: str('client_id'),
56
+ clientName: str('应用名称'),
57
+ logoUri: str('logo 地址'),
58
+ clientUri: str('应用主页')
59
+ }),
60
+ user: obj('已登录用户,未登录时为 null', {
61
+ id: str('用户 ID'),
62
+ nickname: str('昵称'),
63
+ avatar: any('头像文件 ID'),
64
+ email: str('邮箱'),
65
+ phone: str('手机号')
66
+ }),
67
+ tenants: obj('可选租户(仅 tenant 步骤返回,否则为 null):{ list, defaultTenantId }')
68
+ }
69
+ })
70
+ }
29
71
  },
30
72
  wrap(async (request, reply) => services.interaction.details({ request, reply, uid: request.params.uid }))
31
73
  );
@@ -36,18 +78,26 @@ module.exports = fp(async (fastify, options) => {
36
78
  schema: {
37
79
  tags,
38
80
  summary: '账号密码登录',
81
+ description: `仅 login 步骤可调用,${HINT}。账号状态不允许登录时只返回 status,否则返回 redirectTo`,
39
82
  params,
40
83
  body: {
41
84
  type: 'object',
42
85
  required: ['password'],
43
86
  properties: {
44
- type: { type: 'string', enum: ['email', 'phone'], default: 'email' },
45
- email: { type: 'string' },
46
- phone: { type: 'string' },
47
- password: { type: 'string' },
48
- remember: { type: 'boolean', default: true }
87
+ type: { type: 'string', enum: ['email', 'phone'], default: 'email', description: '登录方式:email 邮箱(默认),phone 手机号' },
88
+ email: { type: 'string', description: '邮箱,type=email 时必填' },
89
+ phone: { type: 'string', description: '手机号,type=phone 时必填' },
90
+ password: { type: 'string', description: '密码' },
91
+ remember: { type: 'boolean', default: true, description: '是否保持登录(持久会话 cookie),默认 true' }
92
+ }
93
+ },
94
+ response: success('登录结果', {
95
+ type: 'object',
96
+ properties: {
97
+ redirectTo: str('登录成功后前端需要跳转的地址'),
98
+ status: any('账号状态,仅在账号不允许登录(如未激活、已禁用)时返回')
49
99
  }
50
- }
100
+ })
51
101
  }
52
102
  },
53
103
  wrap(async (request, reply) => {
@@ -62,8 +112,10 @@ module.exports = fp(async (fastify, options) => {
62
112
  schema: {
63
113
  tags,
64
114
  summary: '选择租户',
115
+ description: `仅 tenant 步骤可调用,${HINT}。租户不在用户可用列表中返回 400`,
65
116
  params,
66
- body: { type: 'object', required: ['tenantId'], properties: { tenantId: { type: 'string' } } }
117
+ body: { type: 'object', required: ['tenantId'], properties: { tenantId: { type: 'string', description: '选择的租户 ID(来自交互详情的 tenants.list)' } } },
118
+ response: redirect('选择成功')
67
119
  }
68
120
  },
69
121
  wrap(async (request, reply) => services.interaction.selectTenant({ request, reply, uid: request.params.uid, tenantId: request.body.tenantId }))
@@ -72,7 +124,7 @@ module.exports = fp(async (fastify, options) => {
72
124
  fastify.post(
73
125
  `${base}/confirm`,
74
126
  {
75
- schema: { tags, summary: '确认授权(consent)', params }
127
+ schema: { tags, summary: '确认授权(consent)', description: `仅 consent 步骤可调用,${HINT}。授予本次申请缺少的 scope 与资源权限`, params, response: redirect('授权成功') }
76
128
  },
77
129
  wrap(async (request, reply) => services.interaction.confirm({ request, reply, uid: request.params.uid }))
78
130
  );
@@ -80,7 +132,7 @@ module.exports = fp(async (fastify, options) => {
80
132
  fastify.post(
81
133
  `${base}/abort`,
82
134
  {
83
- schema: { tags, summary: '取消登录', params }
135
+ schema: { tags, summary: '取消登录', description: `${HINT}。以 access_denied 结束授权流程,client 会收到错误回调`, params, response: redirect('已取消') }
84
136
  },
85
137
  wrap(async (request, reply) => services.interaction.abort({ request, reply, uid: request.params.uid }))
86
138
  );
@@ -3,6 +3,7 @@ const httpErrors = require('http-errors');
3
3
  const { pick } = require('lodash');
4
4
  const { createError } = require('../utils/intl');
5
5
  const { collectTenantImages } = require('../utils/tenant-images');
6
+ const { str, num, bool, any, list, obj, success, tenantList } = require('../schema/response');
6
7
 
7
8
  const { NotFound, Forbidden } = httpErrors;
8
9
 
@@ -18,7 +19,8 @@ module.exports = fp(async (fastify, options) => {
18
19
  const { authenticate, translator, services } = fastify[options.name];
19
20
  const { wrap } = translator;
20
21
  const getIdp = () => fastify[options.name].idp;
21
- const tags = ['OIDC 服务接口'];
22
+ const tags = ['OIDC-服务接口'];
23
+ const SERVICE_HINT = '供 central 子项目以 client_credentials 令牌(Bearer)调用';
22
24
 
23
25
  // 头像、租户 logo 是主项目文件库的 id,子项目无法解析,额外给出可直接下载的地址
24
26
  const resolveFileUrl = async fileId => {
@@ -52,7 +54,29 @@ module.exports = fp(async (fastify, options) => {
52
54
  `${options.prefix}/service/user`,
53
55
  {
54
56
  onRequest: [authenticate.client('user:read')],
55
- schema: { tags, summary: '获取用户资料', query: { type: 'object', required: ['id'], properties: { id: { type: 'string' } } } }
57
+ schema: {
58
+ tags,
59
+ summary: '获取用户资料',
60
+ description: `${SERVICE_HINT},需要 user:read scope。用户不存在返回 404`,
61
+ query: { type: 'object', required: ['id'], properties: { id: { type: 'string', description: '用户 ID' } } },
62
+ response: success('用户资料', {
63
+ type: 'object',
64
+ additionalProperties: true,
65
+ properties: {
66
+ id: str('用户 ID'),
67
+ nickname: str('昵称'),
68
+ avatar: any('头像文件 ID(主项目文件库)'),
69
+ avatarUrl: str('头像可直接下载的地址,无法解析时为 null'),
70
+ email: str('邮箱'),
71
+ phone: str('手机号'),
72
+ gender: str('性别:F 女,M 男'),
73
+ birthday: any('出生日期'),
74
+ description: str('个人简介'),
75
+ status: any('用户状态:0 正常'),
76
+ isSuperAdmin: bool('是否为平台超级管理员;账号插件不支持判断时不返回')
77
+ }
78
+ })
79
+ }
56
80
  },
57
81
  wrap(async request => {
58
82
  const { identity } = getIdp();
@@ -89,7 +113,7 @@ module.exports = fp(async (fastify, options) => {
89
113
  return app;
90
114
  };
91
115
 
92
- const appQuery = { app: { type: 'string', description: '子应用 code,传入后只返回已开通该应用的数据,权限去掉 apps:<code>: 前缀' } };
116
+ const appQuery = { app: { type: 'string', description: '子应用 code,传入后只返回已开通该应用的数据,权限去掉 apps:<code>: 前缀;必须是当前服务 client 注册的应用' } };
93
117
 
94
118
  fastify.get(
95
119
  `${options.prefix}/service/tenant-user`,
@@ -98,7 +122,22 @@ module.exports = fp(async (fastify, options) => {
98
122
  schema: {
99
123
  tags,
100
124
  summary: '获取用户在租户内的身份、角色与权限',
101
- query: { type: 'object', required: ['userId', 'tenantId'], properties: Object.assign({ userId: { type: 'string' }, tenantId: { type: 'string' } }, appQuery) }
125
+ description: `${SERVICE_HINT},需要 tenant:read scope。用户不是该租户成员(或租户未开通该应用)返回 404`,
126
+ query: {
127
+ type: 'object',
128
+ required: ['userId', 'tenantId'],
129
+ properties: Object.assign({ userId: { type: 'string', description: '用户 ID' }, tenantId: { type: 'string', description: '租户 ID' } }, appQuery)
130
+ },
131
+ response: success(
132
+ '租户成员信息(fastify-tenant getTenantUserInfo 原样返回,传 app 时 permissions 已去前缀)',
133
+ obj('租户成员信息', {
134
+ id: any('租户成员 ID'),
135
+ tenantId: any('租户 ID'),
136
+ permissions: any('权限 code 列表'),
137
+ roleDetails: any('角色详情列表'),
138
+ tenant: any('租户信息')
139
+ })
140
+ )
102
141
  }
103
142
  },
104
143
  wrap(async request => {
@@ -120,7 +159,13 @@ module.exports = fp(async (fastify, options) => {
120
159
  `${options.prefix}/service/tenant-list`,
121
160
  {
122
161
  onRequest: [authenticate.client('tenant:read')],
123
- schema: { tags, summary: '用户可用租户列表', query: { type: 'object', required: ['userId'], properties: Object.assign({ userId: { type: 'string' } }, appQuery) } }
162
+ schema: {
163
+ tags,
164
+ summary: '用户可用租户列表',
165
+ description: `${SERVICE_HINT},需要 tenant:read scope。传 app 且应用已停用时返回空列表`,
166
+ query: { type: 'object', required: ['userId'], properties: Object.assign({ userId: { type: 'string', description: '用户 ID' } }, appQuery) },
167
+ response: success('可用租户列表', tenantList)
168
+ }
124
169
  },
125
170
  wrap(async request => {
126
171
  assertTenantEnabled();
@@ -139,20 +184,30 @@ module.exports = fp(async (fastify, options) => {
139
184
  schema: {
140
185
  tags,
141
186
  summary: '子应用注册权限树到应用中心',
187
+ description: `${SERVICE_HINT},需要 app:register scope。同一 code 只能由首次注册的服务 client 更新;已删除的应用重新注册时恢复启用`,
142
188
  body: {
143
189
  type: 'object',
144
190
  required: ['code'],
145
191
  properties: {
146
- code: { type: 'string' },
147
- name: { type: 'string' },
148
- description: { type: 'string' },
149
- tenantMode: { type: 'string', enum: ['client', 'independent'] },
150
- clientId: { type: 'string' },
151
- resource: { type: 'string' },
152
- permissions: { type: 'object', additionalProperties: true },
153
- tenantSyncUri: { type: 'string' }
192
+ code: { type: 'string', description: '应用编码,只能包含字母、数字、_、-' },
193
+ name: { type: 'string', description: '应用名称,不传使用 code' },
194
+ description: { type: 'string', description: '应用描述' },
195
+ tenantMode: { type: 'string', enum: ['client', 'independent'], description: '租户模式:client 租户由宿主提供(默认),independent 子应用本地租户' },
196
+ clientId: { type: 'string', description: '子应用登录用的 client_id' },
197
+ resource: { type: 'string', description: '子应用资源服务 identifier(access_token 的 aud)' },
198
+ permissions: { type: 'object', additionalProperties: true, description: '权限树(不含 apps 前缀),不传视为空树 { modules: [] }' },
199
+ tenantSyncUri: { type: 'string', description: 'independent 模式接收租户变更通知的地址,client 模式忽略' }
154
200
  }
155
- }
201
+ },
202
+ response: success('注册结果', {
203
+ type: 'object',
204
+ properties: {
205
+ code: str('应用编码'),
206
+ status: str('应用状态:open 启用,closed 停用'),
207
+ permissionsHash: str('权限树摘要'),
208
+ changed: bool('权限树是否有变化(新注册、恢复或权限树变更)')
209
+ }
210
+ })
156
211
  }
157
212
  },
158
213
  wrap(async request => services.app.register(Object.assign({}, request.body, { serviceClientId: request.user.clientId })))
@@ -165,7 +220,50 @@ module.exports = fp(async (fastify, options) => {
165
220
  schema: {
166
221
  tags,
167
222
  summary: '租户快照(基本信息、租户权限、角色、组织),供 independent 子应用接管',
168
- query: { type: 'object', required: ['tenantId', 'app'], properties: Object.assign({ tenantId: { type: 'string' } }, appQuery) }
223
+ description: `${SERVICE_HINT},需要 tenant:sync scope。id 均为宿主侧 id;租户未开通应用时 enabled=false 且不返回权限、角色、组织;宿主已删除租户时 removed=true`,
224
+ query: { type: 'object', required: ['tenantId', 'app'], properties: Object.assign({ tenantId: { type: 'string', description: '宿主租户 ID' } }, appQuery) },
225
+ response: success('租户快照', {
226
+ type: 'object',
227
+ additionalProperties: true,
228
+ properties: {
229
+ tenant: obj('租户基本信息', {
230
+ id: str('租户 ID'),
231
+ name: str('租户名称'),
232
+ status: any('租户状态'),
233
+ logo: any('租户 logo 文件 ID(宿主文件库)'),
234
+ companyName: str('公司名称'),
235
+ company: any('公司信息')
236
+ }),
237
+ enabled: bool('租户是否已开通且应用处于启用状态'),
238
+ removed: bool('宿主是否已删除该租户;未删除时不返回'),
239
+ permissions: any('租户已开通的应用权限 code(已去前缀)'),
240
+ roles: list(
241
+ '角色列表',
242
+ obj('角色', {
243
+ id: str('角色 ID'),
244
+ code: str('角色 code,没有 code 时为 role-<id>'),
245
+ name: any('角色名称'),
246
+ description: any('角色描述'),
247
+ type: any('角色类型'),
248
+ status: any('角色状态'),
249
+ permissions: any('角色权限 code(已去前缀)')
250
+ })
251
+ ),
252
+ orgs: list(
253
+ '组织列表',
254
+ obj('组织', {
255
+ id: str('组织 ID'),
256
+ parentId: str('上级组织 ID,根组织为 null'),
257
+ name: any('组织名称'),
258
+ description: any('组织描述'),
259
+ index: any('排序'),
260
+ status: any('组织状态'),
261
+ leaderTenantUserId: str('负责人租户成员 ID')
262
+ })
263
+ ),
264
+ fileUrls: obj('快照中图片文件的下载地址:{ 宿主文件 id: 地址 },解析不到的不返回;租户已删除时不返回')
265
+ }
266
+ })
169
267
  }
170
268
  },
171
269
  wrap(async request => {
@@ -186,11 +284,41 @@ module.exports = fp(async (fastify, options) => {
186
284
  schema: {
187
285
  tags,
188
286
  summary: '租户成员分页(含角色 code 与所属组织),供 independent 子应用接管',
287
+ description: `${SERVICE_HINT},需要 tenant:sync scope。只返回已关联账号的成员,按加入时间正序;应用停用或租户未开通时返回空列表`,
189
288
  query: {
190
289
  type: 'object',
191
290
  required: ['tenantId', 'app'],
192
- properties: Object.assign({ tenantId: { type: 'string' }, currentPage: { type: 'number', default: 1 }, perPage: { type: 'number', default: 200, maximum: 1000 } }, appQuery)
193
- }
291
+ properties: Object.assign(
292
+ {
293
+ tenantId: { type: 'string', description: '宿主租户 ID' },
294
+ currentPage: { type: 'number', default: 1, description: '页码,从 1 开始' },
295
+ perPage: { type: 'number', default: 200, maximum: 1000, description: '每页条数,最大 1000' }
296
+ },
297
+ appQuery
298
+ )
299
+ },
300
+ response: success('租户成员分页', {
301
+ type: 'object',
302
+ additionalProperties: true,
303
+ properties: {
304
+ pageData: list(
305
+ '当前页成员',
306
+ obj('租户成员', {
307
+ id: str('租户成员 ID'),
308
+ userId: str('账号用户 ID'),
309
+ name: any('成员姓名'),
310
+ email: any('邮箱'),
311
+ phone: any('手机号'),
312
+ avatar: any('头像文件 ID(宿主文件库)'),
313
+ status: any('成员状态'),
314
+ roleCodes: any('角色 code 列表'),
315
+ tenantOrgIds: any('所属组织 ID 列表')
316
+ })
317
+ ),
318
+ totalCount: num('成员总数'),
319
+ fileUrls: obj('头像下载地址:{ 宿主文件 id: 地址 };返回空列表时不返回')
320
+ }
321
+ })
194
322
  }
195
323
  },
196
324
  wrap(async request => {
@@ -1,4 +1,5 @@
1
1
  const fp = require('fastify-plugin');
2
+ const { str, obj, success } = require('../schema/response');
2
3
 
3
4
  /**
4
5
  * 宿主租户端:当前租户已开通且启用的子应用。当前租户与 fastify-tenant 的 tenantUser 一致(token 中的租户,否则默认租户)
@@ -15,7 +16,20 @@ module.exports = fp(async (fastify, options) => {
15
16
  `${options.prefix}/tenant/apps`,
16
17
  {
17
18
  onRequest: [authenticate.user, resolveTenantUser],
18
- schema: { tags: ['OIDC 应用中心'], summary: '当前租户已开通的子应用' }
19
+ schema: {
20
+ tags: ['OIDC-应用中心'],
21
+ summary: '当前租户已开通的子应用',
22
+ description: '宿主租户端使用:返回已启用且当前租户已开通权限的子应用;没有当前租户时返回空数组',
23
+ response: success('子应用列表', {
24
+ type: 'array',
25
+ items: obj('子应用', {
26
+ code: str('应用编码'),
27
+ name: str('应用名称'),
28
+ description: str('描述'),
29
+ tenantMode: str('租户模式:client / independent')
30
+ })
31
+ })
32
+ }
19
33
  },
20
34
  wrap(async request => {
21
35
  const tenantId = request[options.tenantUserContextName]?.tenantId;
@@ -1,4 +1,5 @@
1
1
  const fp = require('fastify-plugin');
2
+ const { str, any, list, obj, success } = require('../schema/response');
2
3
 
3
4
  const FORWARD_HEADERS = ['content-type', 'accept', 'accept-language', 'x-app-name'];
4
5
 
@@ -39,26 +40,93 @@ module.exports = fp(async (fastify, options) => {
39
40
  defaultTenantId
40
41
  });
41
42
 
42
- fastify.get(`${proxy.prefix}/getUserInfo`, { onRequest: [authenticate.user, authenticate.tenantUser] }, async request => {
43
- const info = request[options.tenantUserContextName];
44
- return { userInfo: request.userInfo, tenantUserInfo: info, company: info?.tenant?.tenantCompany || info?.tenant?.company || null, tenant: info?.tenant || null };
45
- });
43
+ const tags = ['OIDC-租户代理'];
44
+
45
+ fastify.get(
46
+ `${proxy.prefix}/getUserInfo`,
47
+ {
48
+ onRequest: [authenticate.user, authenticate.tenantUser],
49
+ schema: {
50
+ tags,
51
+ summary: '获取当前用户与当前租户信息',
52
+ description: 'client 子应用使用,与 fastify-tenant getUserInfo 同形;租户信息经服务接口获取,权限已去掉 apps:<code>: 前缀',
53
+ response: success('当前用户与租户信息', {
54
+ type: 'object',
55
+ additionalProperties: true,
56
+ properties: {
57
+ userInfo: any('当前用户'),
58
+ tenantUserInfo: any('当前租户成员信息'),
59
+ company: any('当前租户的公司信息'),
60
+ tenant: any('当前租户')
61
+ }
62
+ })
63
+ }
64
+ },
65
+ async request => {
66
+ const info = request[options.tenantUserContextName];
67
+ return { userInfo: request.userInfo, tenantUserInfo: info, company: info?.tenant?.tenantCompany || info?.tenant?.company || null, tenant: info?.tenant || null };
68
+ }
69
+ );
46
70
 
47
- fastify.get(`${proxy.prefix}/available-list`, { onRequest: [authenticate.user] }, async request => toTenantList(await serviceClient.getTenantList({ userId: request.user.userId })));
71
+ fastify.get(
72
+ `${proxy.prefix}/available-list`,
73
+ {
74
+ onRequest: [authenticate.user],
75
+ schema: {
76
+ tags,
77
+ summary: '当前用户可用租户列表',
78
+ description: 'client 子应用使用,经服务接口获取(只含已开通本应用的租户),与 fastify-tenant available-list 同形',
79
+ response: success('可用租户列表', {
80
+ type: 'object',
81
+ additionalProperties: true,
82
+ properties: {
83
+ list: list(
84
+ '可用租户',
85
+ obj('租户成员身份', {
86
+ id: str('用户在该租户的成员 ID'),
87
+ tenantId: str('租户 ID'),
88
+ status: str('成员状态,固定 open'),
89
+ tenant: obj('租户', {
90
+ id: str('租户 ID'),
91
+ name: str('租户名称'),
92
+ logo: any('租户 logo 文件 ID'),
93
+ status: str('租户状态,固定 open'),
94
+ company: obj('公司,没有时为 null', { name: str('公司名称') })
95
+ })
96
+ })
97
+ ),
98
+ defaultTenantId: str('默认租户 ID')
99
+ }
100
+ })
101
+ }
102
+ },
103
+ async request => toTenantList(await serviceClient.getTenantList({ userId: request.user.userId }))
104
+ );
48
105
 
49
- fastify.all(`${proxy.prefix}/*`, { onRequest: [authenticate.user] }, async (request, reply) => {
50
- const subjectToken = String(request.headers.authorization || '').replace(/^(bearer|dpop)\s+/i, '');
51
- const headers = { authorization: `Bearer ${await getHostToken(subjectToken)}` };
52
- FORWARD_HEADERS.forEach(name => request.headers[name] && (headers[name] = request.headers[name]));
53
- const url = new URL(`${target}/${request.params['*']}`);
54
- url.search = new URL(request.raw.url, 'http://localhost').search;
55
- const hasBody = !['GET', 'HEAD'].includes(request.method) && request.body !== undefined;
56
- const response = await fetch(url, { method: request.method, headers, body: hasBody ? JSON.stringify(request.body) : undefined });
57
- reply.code(response.status);
58
- const contentType = response.headers.get('content-type');
59
- if (contentType) {
60
- reply.header('content-type', contentType);
106
+ fastify.all(
107
+ `${proxy.prefix}/*`,
108
+ {
109
+ onRequest: [authenticate.user],
110
+ schema: {
111
+ tags,
112
+ summary: '转发到宿主 fastify-tenant',
113
+ description: '以 token exchange 把当前令牌换成宿主 API 令牌后,原样转发 JSON 请求(路径、query、body)到宿主 /api/tenant,按宿主响应的状态码与内容返回'
114
+ }
115
+ },
116
+ async (request, reply) => {
117
+ const subjectToken = String(request.headers.authorization || '').replace(/^(bearer|dpop)\s+/i, '');
118
+ const headers = { authorization: `Bearer ${await getHostToken(subjectToken)}` };
119
+ FORWARD_HEADERS.forEach(name => request.headers[name] && (headers[name] = request.headers[name]));
120
+ const url = new URL(`${target}/${request.params['*']}`);
121
+ url.search = new URL(request.raw.url, 'http://localhost').search;
122
+ const hasBody = !['GET', 'HEAD'].includes(request.method) && request.body !== undefined;
123
+ const response = await fetch(url, { method: request.method, headers, body: hasBody ? JSON.stringify(request.body) : undefined });
124
+ reply.code(response.status);
125
+ const contentType = response.headers.get('content-type');
126
+ if (contentType) {
127
+ reply.header('content-type', contentType);
128
+ }
129
+ return reply.send(Buffer.from(await response.arrayBuffer()));
61
130
  }
62
- return reply.send(Buffer.from(await response.arrayBuffer()));
63
- });
131
+ );
64
132
  });
@@ -1,6 +1,7 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const httpErrors = require('http-errors');
3
3
  const { createError } = require('../utils/intl');
4
+ const { empty } = require('../schema/response');
4
5
 
5
6
  const { BadRequest } = httpErrors;
6
7
 
@@ -35,9 +36,11 @@ module.exports = fp(async (fastify, options) => {
35
36
  `${options.prefix}/tenant-sync`,
36
37
  {
37
38
  schema: {
38
- tags: ['OIDC 服务接口'],
39
+ tags: ['OIDC-服务接口'],
39
40
  summary: '接收宿主租户变更通知(independent 子应用)',
40
- body: { type: 'object', required: ['tenant_sync_token'], properties: { tenant_sync_token: { type: 'string' } } }
41
+ description: '验签并校验 jti 防重放后立即返回,后台回拉该租户快照;令牌无效或重放返回 400',
42
+ body: { type: 'object', required: ['tenant_sync_token'], properties: { tenant_sync_token: { type: 'string', description: '宿主签发的租户同步令牌(JWT),含 tenant_id' } } },
43
+ response: empty('已接收,后台同步')
41
44
  }
42
45
  },
43
46
  translator.wrap(async (request, reply) => {
package/libs/idp/mount.js CHANGED
@@ -21,6 +21,12 @@ module.exports = async (fastify, { idp, mountPath, translator }) => {
21
21
  idp.handle(req, reply.raw);
22
22
  };
23
23
 
24
- fastify.route({ method: METHODS, url: mountPath, handler });
25
- fastify.route({ method: METHODS, url: `${mountPath}/*`, handler });
24
+ const schema = {
25
+ tags: ['OIDC-协议端点'],
26
+ summary: 'OIDC 协议端点(oidc-provider)',
27
+ description:
28
+ '原样交给 oidc-provider 处理的标准端点:/.well-known/openid-configuration、/jwks、/auth、/token、/me、/session/end、/token/introspection、/token/revocation 等,请求与响应格式见 OpenID Connect / OAuth 2.0 规范;provider 未就绪时返回 503'
29
+ };
30
+ fastify.route({ method: METHODS, url: mountPath, schema, handler });
31
+ fastify.route({ method: METHODS, url: `${mountPath}/*`, schema, handler });
26
32
  };
@@ -1,4 +1,5 @@
1
1
  const { mapTenantImages } = require('../utils/tenant-images');
2
+ const findMirroredFile = require('../utils/find-mirrored-file');
2
3
 
3
4
  const FAILURE_RETRY_MS = 30 * 1000;
4
5
  const FILE_SOURCE = 'oidcHostFileSource';
@@ -54,7 +55,7 @@ module.exports = ({ fastify, options, serviceClient, userMirror }) => {
54
55
  const mapping = {};
55
56
  for (const [source, url] of Object.entries(fileUrls)) {
56
57
  const current = previous[source];
57
- if (current && (await Promise.resolve(files.getFileInstance({ id: current })).catch(() => null))) {
58
+ if (await findMirroredFile(files, current)) {
58
59
  mapping[source] = current;
59
60
  continue;
60
61
  }
@@ -1,5 +1,6 @@
1
1
  const crypto = require('node:crypto');
2
2
  const { pick } = require('lodash');
3
+ const findMirroredFile = require('../utils/find-mirrored-file');
3
4
 
4
5
  const PROFILE_FIELDS = ['nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description'];
5
6
  const USER_FIELDS = ['id', ...PROFILE_FIELDS, 'status'];
@@ -22,7 +23,7 @@ module.exports = ({ fastify, options, serviceClient }) => {
22
23
  if (!remote.avatar) {
23
24
  return null;
24
25
  }
25
- const mirrored = current ? await Promise.resolve(files.getFileInstance({ id: current })).catch(() => null) : null;
26
+ const mirrored = await findMirroredFile(files, current);
26
27
  const mirroredSource = mirrored?.options?.[AVATAR_SOURCE];
27
28
  if (mirroredSource && mirroredSource === remote.avatar) {
28
29
  return current;
@@ -0,0 +1,103 @@
1
+ // 响应 schema 会参与 fast-json-stringify 序列化:对象一律 additionalProperties: true 以免裁掉未声明字段;
2
+ // 用 nullable 而非类型数组(类型数组遇到不匹配的值会直接 500),类型不确定的字段(如 id、日期、JSON 列)只写说明不声明类型
3
+ const str = description => ({ type: 'string', nullable: true, description });
4
+ const num = description => ({ type: 'number', nullable: true, description });
5
+ const bool = description => ({ type: 'boolean', nullable: true, description });
6
+ const any = description => ({ description });
7
+ const strArray = description => ({ type: 'array', nullable: true, description, items: { type: 'string' } });
8
+ const list = (description, items) => ({ type: 'array', nullable: true, description, items });
9
+ const obj = (description, properties = {}) => ({ type: 'object', nullable: true, description, additionalProperties: true, properties });
10
+
11
+ const timestamps = () => ({
12
+ createdAt: any('创建时间'),
13
+ updatedAt: any('更新时间')
14
+ });
15
+
16
+ const success = (description, schema) => ({
17
+ 200: Object.assign({}, schema || { type: 'object' }, { description })
18
+ });
19
+
20
+ const empty = (description = '操作成功,返回空对象') => success(description);
21
+
22
+ const pageResult = (description, item) => ({
23
+ type: 'object',
24
+ additionalProperties: true,
25
+ properties: {
26
+ pageData: list(`当前页${description}列表`, item),
27
+ totalCount: num('符合条件的总条数')
28
+ }
29
+ });
30
+
31
+ const STATUS = '状态:open 启用,closed 停用';
32
+
33
+ const client = obj('OIDC Client', {
34
+ id: any('记录 ID'),
35
+ clientId: str('client_id'),
36
+ clientName: str('应用名称'),
37
+ hasSecret: bool('是否已设置 client secret(public client 为 false);secret 不会返回'),
38
+ metadata: any('OIDC client metadata(redirect_uris、grant_types、response_types、token_endpoint_auth_method 等)'),
39
+ allowedResources: any('允许申请的资源服务 identifier 列表'),
40
+ description: str('描述'),
41
+ status: str(STATUS),
42
+ ...timestamps()
43
+ });
44
+
45
+ const resourceServer = obj('资源服务', {
46
+ id: any('记录 ID'),
47
+ identifier: str('resource indicator,即 access_token 的 aud'),
48
+ name: str('资源名称'),
49
+ scope: str('支持的 scope,空格分隔'),
50
+ accessTokenTTL: num('access_token 有效期(秒),为空使用全局配置'),
51
+ includePermissions: any('access_token 中是否携带 permissions,为空使用全局配置'),
52
+ description: str('描述'),
53
+ status: str(STATUS),
54
+ ...timestamps()
55
+ });
56
+
57
+ const app = obj('子应用', {
58
+ id: any('记录 ID'),
59
+ code: str('应用编码,宿主权限 code 前缀 apps:<code>'),
60
+ name: str('应用名称'),
61
+ description: str('描述'),
62
+ tenantMode: str('租户模式:client 租户由宿主提供,independent 子应用本地租户(宿主同步的租户由宿主接管)'),
63
+ serviceClientId: str('首次注册该应用的服务 client_id'),
64
+ clientIds: any('子应用登录用的 client_id 列表'),
65
+ resource: str('子应用资源服务 identifier'),
66
+ permissions: any('子应用权限树(不含 apps 前缀)'),
67
+ permissionsHash: str('权限树摘要'),
68
+ permissionCount: num('权限树中的权限点数量'),
69
+ tenantSyncUri: str('independent 模式接收租户变更通知的地址'),
70
+ registeredAt: any('最近一次注册时间'),
71
+ status: str('状态:open 启用,closed 停用(removed 已删除的不会出现在列表与详情中)'),
72
+ ...timestamps()
73
+ });
74
+
75
+ const key = obj('签名密钥(不含私钥)', {
76
+ id: any('记录 ID'),
77
+ kid: str('JWK kid'),
78
+ alg: str('签名算法'),
79
+ status: str('状态:active 当前签名,next 已发布待启用,retired 已退役仅用于验签'),
80
+ activatedAt: any('启用时间'),
81
+ retiredAt: any('退役时间'),
82
+ createdAt: any('创建时间')
83
+ });
84
+
85
+ const tenantList = {
86
+ type: 'object',
87
+ additionalProperties: true,
88
+ properties: {
89
+ list: list(
90
+ '可用租户列表(只含启用状态的成员身份与租户)',
91
+ obj('租户', {
92
+ tenantId: str('租户 ID'),
93
+ tenantUserId: str('用户在该租户的成员 ID'),
94
+ name: str('租户名称'),
95
+ logo: any('租户 logo 文件 ID'),
96
+ companyName: str('公司名称')
97
+ })
98
+ ),
99
+ defaultTenantId: str('默认租户 ID;默认租户不在列表中时取列表第一个,列表为空时为 null')
100
+ }
101
+ };
102
+
103
+ module.exports = { str, num, bool, any, strArray, list, obj, timestamps, success, empty, pageResult, STATUS, client, resourceServer, app, key, tenantList };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 找已拷到本地文件库的文件:记录还在但文件已丢(本地存储随部署目录变化丢失)时视为没有,调用方重新拷贝
3
+ */
4
+ module.exports = async (files, id) => {
5
+ if (!id) {
6
+ return null;
7
+ }
8
+ const file = await Promise.resolve(files.getFileInstance({ id })).catch(() => null);
9
+ if (!file || typeof files.getFileUrl !== 'function') {
10
+ return file;
11
+ }
12
+ const available = await Promise.resolve(files.getFileUrl({ id })).then(
13
+ () => true,
14
+ () => false
15
+ );
16
+ return available ? file : null;
17
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-oidc",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌",
5
5
  "main": "index.js",
6
6
  "scripts": {