@kne/fastify-oidc 0.1.7 → 0.1.9

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 CHANGED
@@ -269,6 +269,7 @@ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求
269
269
  | accountNamespace | string | 否 | `account` | fastify-account 命名空间 |
270
270
  | tenantNamespace | string | 否 | `tenant` | fastify-tenant 命名空间,不存在时不启用租户 |
271
271
  | intlNamespace | string | 否 | `intl` | @kne/fastify-intl 命名空间,不存在时返回内置中文文案 |
272
+ | fileNamespace | string | 否 | `fileManager` | @kne/fastify-file-manager 命名空间:主项目用它把头像 id 解析成 `avatarUrl`,子项目用它把头像拷到本地文件库;不存在时不处理头像 |
272
273
 
273
274
  ##### IdP(standalone)
274
275
 
@@ -289,8 +290,8 @@ oidc-provider 9.x 为 ESM 包,本插件通过动态 `import()` 加载,要求
289
290
  | includePermissions | boolean | 否 | `false` | 资源服务未设置时,token 是否携带 permissions |
290
291
  | defaultResourceScope | string | 否 | `api` | 资源服务默认 scope |
291
292
  | seedSelf | boolean | 否 | `true` | 启动时自动登记本项目 SPA client、本项目 API、服务接口资源 |
292
- | selfClient | object | 否 | `{}` | 覆盖默认 SPA client 的字段与 metadata,如 `{ clientName: '系统名称' }`(默认名称为 `name`);仅首次登记时生效;已存在的 client 只会追加缺失的 `redirect_uris` / `post_logout_redirect_uris`(如 `ORIGIN` 变更),其他字段不覆盖 |
293
- | clients | array | 否 | `[]` | 启动时登记的 client(已存在则只追加缺失的 `redirect_uris` / `post_logout_redirect_uris`),字段同管理接口 `client/create`,metadata 直接平铺 |
293
+ | selfClient | object | 否 | `{}` | 覆盖默认 SPA client 的字段与 metadata,如 `{ clientName: '系统名称' }`(默认名称为 `name`);仅首次登记时生效;已存在的 client 只会追加缺失的 `redirect_uris` / `post_logout_redirect_uris` / `allowedResources`(如 `ORIGIN` 变更),其他字段不覆盖 |
294
+ | clients | array | 否 | `[]` | 启动时登记的 client(已存在则只追加缺失的 `redirect_uris` / `post_logout_redirect_uris` / `allowedResources`),字段同管理接口 `client/create`,metadata 直接平铺 |
294
295
  | resourceServers | array | 否 | `[]` | 启动时登记的资源服务(已存在则跳过) |
295
296
  | serviceScopes | array | 否 | `['user:read', 'tenant:read']` | 服务接口资源的 scope |
296
297
  | getAuthenticate | function | 否 | 见下文 | 管理接口鉴权,参数为 `client:manage` / `resource-server:manage` / `key:manage` / `session:manage` |
@@ -440,7 +441,7 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
440
441
 
441
442
  | 接口 | scope | 说明 |
442
443
  |------|-------|------|
443
- | `GET /api/oidc/service/user?id=` | `user:read` | 用户资料 `{ id, nickname, avatar, email, phone, gender, birthday, description, status, isSuperAdmin }` |
444
+ | `GET /api/oidc/service/user?id=` | `user:read` | 用户资料 `{ id, nickname, avatar, avatarUrl, email, phone, gender, birthday, description, status, isSuperAdmin }`;`avatarUrl` 为头像的完整下载地址(经 `fileNamespace` 解析,无文件服务或解析失败时为 `null`) |
444
445
  | `GET /api/oidc/service/tenant-user?userId=&tenantId=` | `tenant:read` | 用户在租户内的身份、角色、权限(fastify-tenant `getTenantUserInfo` 结果) |
445
446
 
446
447
  ##### Back-Channel Logout(central)
@@ -481,6 +482,8 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
481
482
 
482
483
  central 模式下镜像用户的 `isSuperAdmin` 随主项目同步(升降级均以主项目为准,生效延迟 ≤ `userMirrorTTL`),`authenticate.admin` 仍读本地字段;需配置 `serviceClient`。
483
484
 
485
+ central 模式下主项目的 `avatar` 是主项目文件库的 id,子项目无法解析。子项目注册了 fastify-file-manager 时,镜像会按 `avatarUrl` 把头像拷到本地文件库,`avatar` 存本地文件 id(文件记录 `options.oidcAvatarSource` 记来源 id,主项目头像不变不重复下载,变更时原地替换);主项目未返回 `avatarUrl` 或下载失败时保留已同步的头像,没有则置空。子项目未注册文件服务时 `avatar` 仍为主项目原值。主项目需同时升级才会返回 `avatarUrl`。
486
+
484
487
  ##### 其它
485
488
 
486
489
  | 方法 | 说明 |
package/index.js CHANGED
@@ -50,6 +50,7 @@ module.exports = fp(
50
50
  accountNamespace: 'account',
51
51
  tenantNamespace: 'tenant',
52
52
  intlNamespace: 'intl',
53
+ fileNamespace: 'fileManager',
53
54
  clients: [],
54
55
  resourceServers: [],
55
56
  seedSelf: true,
@@ -19,6 +19,27 @@ module.exports = fp(async (fastify, options) => {
19
19
  const getIdp = () => fastify[options.name].idp;
20
20
  const tags = ['OIDC 服务接口'];
21
21
 
22
+ // avatar 是主项目文件库的 id,子项目无法解析,额外给出可直接下载的地址
23
+ const resolveAvatarUrl = async avatar => {
24
+ if (!avatar) {
25
+ return null;
26
+ }
27
+ if (/^https?:\/\//.test(avatar)) {
28
+ return avatar;
29
+ }
30
+ const getFileUrl = fastify[options.fileNamespace]?.services?.getFileUrl;
31
+ if (typeof getFileUrl !== 'function') {
32
+ return null;
33
+ }
34
+ try {
35
+ const url = await getFileUrl({ id: avatar });
36
+ return url ? new URL(url, options.runtime.origin).href : null;
37
+ } catch (e) {
38
+ fastify.log.warn({ err: e, avatar }, 'fastify-oidc: 解析用户头像地址失败');
39
+ return null;
40
+ }
41
+ };
42
+
22
43
  fastify.get(
23
44
  `${options.prefix}/service/user`,
24
45
  {
@@ -31,7 +52,11 @@ module.exports = fp(async (fastify, options) => {
31
52
  if (!user) {
32
53
  throw createError(NotFound, 'userNotFound');
33
54
  }
34
- return Object.assign(pick(user, PROFILE_FIELDS), { id: String(user.id), isSuperAdmin: await identity.isSuperAdmin(user.id) });
55
+ return Object.assign(pick(user, PROFILE_FIELDS), {
56
+ id: String(user.id),
57
+ avatarUrl: await resolveAvatarUrl(user.avatar),
58
+ isSuperAdmin: await identity.isSuperAdmin(user.id)
59
+ });
35
60
  })
36
61
  );
37
62
 
@@ -3,6 +3,7 @@ const { pick } = require('lodash');
3
3
 
4
4
  const PROFILE_FIELDS = ['nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description'];
5
5
  const USER_FIELDS = ['id', ...PROFILE_FIELDS, 'status'];
6
+ const AVATAR_SOURCE = 'oidcAvatarSource';
6
7
 
7
8
  /**
8
9
  * central 模式:子项目保留 fastify-account 的用户表作为镜像,按 sub 即时创建 / 定期同步,
@@ -12,13 +13,50 @@ module.exports = ({ fastify, options, serviceClient }) => {
12
13
  const cache = new Map();
13
14
  const getModel = () => fastify[options.accountNamespace].models.user;
14
15
 
15
- const fetchProfile = async userId => {
16
+ // 主项目 avatar 是主项目文件库的 id:拷到本地文件库,镜像存本地文件 id;文件记录 options 记来源 id,主项目头像不变就不再下载
17
+ const syncAvatar = async (remote, current) => {
18
+ const files = fastify[options.fileNamespace]?.services;
19
+ if (typeof files?.uploadFromUrl !== 'function') {
20
+ return remote.avatar;
21
+ }
22
+ if (!remote.avatar) {
23
+ return null;
24
+ }
25
+ const mirrored = current ? await Promise.resolve(files.getFileInstance({ id: current })).catch(() => null) : null;
26
+ const mirroredSource = mirrored?.options?.[AVATAR_SOURCE];
27
+ if (mirroredSource && mirroredSource === remote.avatar) {
28
+ return current;
29
+ }
30
+ const fallback = mirroredSource ? current : null;
31
+ if (!remote.avatarUrl) {
32
+ return fallback;
33
+ }
34
+ try {
35
+ const file = await files.uploadFromUrl({
36
+ id: mirroredSource ? current : undefined,
37
+ url: remote.avatarUrl,
38
+ options: { [AVATAR_SOURCE]: remote.avatar }
39
+ });
40
+ return file.id;
41
+ } catch (e) {
42
+ fastify.log.warn({ err: e, avatar: remote.avatar }, 'fastify-oidc: 同步主项目用户头像失败');
43
+ return fallback;
44
+ }
45
+ };
46
+
47
+ const fetchProfile = async (userId, current) => {
16
48
  if (!serviceClient.enabled()) {
17
49
  return null;
18
50
  }
19
51
  try {
20
52
  const remote = await serviceClient.getUserProfile(userId);
21
53
  const profile = pick(remote, PROFILE_FIELDS);
54
+ const avatar = await syncAvatar(remote, current?.avatar);
55
+ if (avatar === undefined) {
56
+ delete profile.avatar;
57
+ } else {
58
+ profile.avatar = avatar;
59
+ }
22
60
  // 主项目超级管理员身份以主项目为准,升降级都同步到镜像,子项目 authenticate.admin 照常读本地 isSuperAdmin
23
61
  if (typeof remote?.isSuperAdmin === 'boolean' && getModel().rawAttributes.isSuperAdmin) {
24
62
  profile.isSuperAdmin = remote.isSuperAdmin;
@@ -72,7 +110,7 @@ module.exports = ({ fastify, options, serviceClient }) => {
72
110
  }
73
111
  const model = getModel();
74
112
  let row = await model.findByPk(userId);
75
- const profile = await fetchProfile(userId);
113
+ const profile = await fetchProfile(userId, row);
76
114
  if (!row) {
77
115
  row = await createMirror(userId, profile);
78
116
  } else if (profile) {
@@ -154,20 +154,29 @@ module.exports = fp(async (fastify, options) => {
154
154
  });
155
155
  };
156
156
 
157
- // 已存在的客户端只追加配置中缺失的回调地址(如 ORIGIN 变更),不覆盖管理端维护的其他字段
158
- const mergeSeedUris = async (item, metadata) => {
159
- const next = Object.assign({}, item.metadata);
160
- let changed = false;
157
+ const appendMissing = (current, values) => {
158
+ const list = Array.isArray(current) ? current : [];
159
+ const missing = (values || []).filter(value => !list.includes(value));
160
+ return missing.length ? [...list, ...missing] : null;
161
+ };
162
+
163
+ // 已存在的客户端只追加配置中缺失的回调地址与资源(如 ORIGIN 变更),不覆盖管理端维护的其他字段
164
+ const mergeSeed = async (item, { metadata, allowedResources }) => {
165
+ const nextMetadata = Object.assign({}, item.metadata);
166
+ const patch = {};
161
167
  ['redirect_uris', 'post_logout_redirect_uris'].forEach(key => {
162
- const current = Array.isArray(next[key]) ? next[key] : [];
163
- const missing = (metadata[key] || []).filter(uri => !current.includes(uri));
164
- if (missing.length) {
165
- next[key] = [...current, ...missing];
166
- changed = true;
168
+ const next = appendMissing(nextMetadata[key], metadata[key]);
169
+ if (next) {
170
+ nextMetadata[key] = next;
171
+ patch.metadata = nextMetadata;
167
172
  }
168
173
  });
169
- if (changed) {
170
- await item.update({ metadata: next });
174
+ const nextResources = appendMissing(item.allowedResources, allowedResources);
175
+ if (nextResources) {
176
+ patch.allowedResources = nextResources;
177
+ }
178
+ if (Object.keys(patch).length) {
179
+ await item.update(patch);
171
180
  }
172
181
  };
173
182
 
@@ -175,7 +184,7 @@ module.exports = fp(async (fastify, options) => {
175
184
  for (const { clientId, clientName, clientSecret, allowedResources, description, ...metadata } of clients || []) {
176
185
  const item = await models.client.findOne({ where: { clientId } });
177
186
  if (item) {
178
- await mergeSeedUris(item, metadata);
187
+ await mergeSeed(item, { metadata, allowedResources });
179
188
  continue;
180
189
  }
181
190
  await create({ clientId, clientName, clientSecret, metadata, allowedResources, description });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-oidc",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌",
5
5
  "main": "index.js",
6
6
  "scripts": {