@kne/fastify-oidc 0.1.4 → 0.1.6

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
@@ -440,7 +440,7 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
440
440
 
441
441
  | 接口 | scope | 说明 |
442
442
  |------|-------|------|
443
- | `GET /api/oidc/service/user?id=` | `user:read` | 用户资料 `{ id, nickname, avatar, email, phone, gender, birthday, description, status }` |
443
+ | `GET /api/oidc/service/user?id=` | `user:read` | 用户资料 `{ id, nickname, avatar, email, phone, gender, birthday, description, status, isSuperAdmin }` |
444
444
  | `GET /api/oidc/service/tenant-user?userId=&tenantId=` | `tenant:read` | 用户在租户内的身份、角色、权限(fastify-tenant `getTenantUserInfo` 结果) |
445
445
 
446
446
  ##### Back-Channel Logout(central)
@@ -479,6 +479,8 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
479
479
 
480
480
  兼容字段:`request.authenticatePayload = { id, tenantId }`,`request.userInfo` 为 fastify-account 用户(central 为镜像用户)。
481
481
 
482
+ central 模式下镜像用户的 `isSuperAdmin` 随主项目同步(升降级均以主项目为准,生效延迟 ≤ `userMirrorTTL`),`authenticate.admin` 仍读本地字段;需配置 `serviceClient`。
483
+
482
484
  ##### 其它
483
485
 
484
486
  | 方法 | 说明 |
@@ -26,11 +26,12 @@ module.exports = fp(async (fastify, options) => {
26
26
  schema: { tags, summary: '获取用户资料', query: { type: 'object', required: ['id'], properties: { id: { type: 'string' } } } }
27
27
  },
28
28
  wrap(async request => {
29
- const user = await getIdp().identity.getUser(request.query.id);
29
+ const { identity } = getIdp();
30
+ const user = await identity.getUser(request.query.id);
30
31
  if (!user) {
31
32
  throw createError(NotFound, 'userNotFound');
32
33
  }
33
- return Object.assign(pick(user, PROFILE_FIELDS), { id: String(user.id) });
34
+ return Object.assign(pick(user, PROFILE_FIELDS), { id: String(user.id), isSuperAdmin: await identity.isSuperAdmin(user.id) });
34
35
  })
35
36
  );
36
37
 
@@ -26,6 +26,18 @@ module.exports = ({ fastify, options }) => {
26
26
  }
27
27
  };
28
28
 
29
+ const isSuperAdmin = async id => {
30
+ const check = account().services.admin?.checkIsSuperAdmin;
31
+ if (!check) {
32
+ return undefined;
33
+ }
34
+ try {
35
+ return (await check({ id })) === true;
36
+ } catch (e) {
37
+ return undefined;
38
+ }
39
+ };
40
+
29
41
  const toProfileClaims = user => ({
30
42
  sub: String(user.id),
31
43
  name: user.nickname || undefined,
@@ -104,5 +116,5 @@ module.exports = ({ fastify, options }) => {
104
116
  };
105
117
  };
106
118
 
107
- return { tenantEnabled, getUser, toProfileClaims, findAccount, verifyCredentials, listTenants, isTenantMember, getTenantContext };
119
+ return { tenantEnabled, getUser, isSuperAdmin, toProfileClaims, findAccount, verifyCredentials, listTenants, isTenantMember, getTenantContext };
108
120
  };
@@ -1,3 +1,4 @@
1
+ const crypto = require('node:crypto');
1
2
  const { pick } = require('lodash');
2
3
 
3
4
  const PROFILE_FIELDS = ['nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description'];
@@ -16,27 +17,54 @@ module.exports = ({ fastify, options, serviceClient }) => {
16
17
  return null;
17
18
  }
18
19
  try {
19
- return pick(await serviceClient.getUserProfile(userId), PROFILE_FIELDS);
20
+ const remote = await serviceClient.getUserProfile(userId);
21
+ const profile = pick(remote, PROFILE_FIELDS);
22
+ // 主项目超级管理员身份以主项目为准,升降级都同步到镜像,子项目 authenticate.admin 照常读本地 isSuperAdmin
23
+ if (typeof remote?.isSuperAdmin === 'boolean' && getModel().rawAttributes.isSuperAdmin) {
24
+ profile.isSuperAdmin = remote.isSuperAdmin;
25
+ }
26
+ return profile;
20
27
  } catch (e) {
21
28
  fastify.log.warn({ err: e, userId }, 'fastify-oidc: 获取主项目用户资料失败,使用本地镜像');
22
29
  return null;
23
30
  }
24
31
  };
25
32
 
26
- const createMirror = async (userId, profile) => {
33
+ // fastify-account 的 user.userAccountId 非空:镜像用户挂一个随机密码的占位账号,central 模式下本地密码登录不可用
34
+ const createPlaceholderAccount = async () => {
35
+ const { userAccount } = fastify[options.accountNamespace].models;
36
+ if (!userAccount || !getModel().rawAttributes.userAccountId) {
37
+ return null;
38
+ }
39
+ return userAccount.create({ password: crypto.randomBytes(32).toString('hex'), salt: crypto.randomBytes(16).toString('hex') });
40
+ };
41
+
42
+ const createUser = async values => {
27
43
  const model = getModel();
28
- const values = Object.assign({ nickname: userId }, profile, { id: userId, status: 0 });
29
44
  try {
30
45
  return await model.create(values, { hooks: false });
31
46
  } catch (e) {
32
47
  if (e.name !== 'SequelizeUniqueConstraintError') {
33
48
  throw e;
34
49
  }
35
- fastify.log.warn({ userId }, 'fastify-oidc: 镜像用户邮箱或手机号与本地已有用户冲突,忽略这两个字段');
50
+ fastify.log.warn({ userId: values.id }, 'fastify-oidc: 镜像用户邮箱或手机号与本地已有用户冲突,忽略这两个字段');
36
51
  return model.create(Object.assign({}, values, { email: null, phone: null }), { hooks: false });
37
52
  }
38
53
  };
39
54
 
55
+ const createMirror = async (userId, profile) => {
56
+ const account = await createPlaceholderAccount();
57
+ const values = Object.assign({ nickname: userId }, profile, { id: userId, status: 0 }, account ? { userAccountId: account.id } : {});
58
+ try {
59
+ const row = await createUser(values);
60
+ await account?.update({ belongToUserId: row.id });
61
+ return row;
62
+ } catch (e) {
63
+ await account?.destroy({ force: true }).catch(() => {});
64
+ throw e;
65
+ }
66
+ };
67
+
40
68
  const ensure = async userId => {
41
69
  const cached = cache.get(userId);
42
70
  if (cached && cached.expiresAt > Date.now()) {
@@ -12,6 +12,10 @@ module.exports = fp(async (fastify, options) => {
12
12
  const { Op } = fastify.sequelize.Sequelize;
13
13
  const secret = options.keyEncryptionSecret;
14
14
 
15
+ // 文件型 sqlite 下 sequelize 会为每个事务单独打开一个连接,与默认连接上其他插件的写入争抢文件锁而 SQLITE_BUSY;
16
+ // sqlite 只用于单进程本地开发,直接在共享的默认连接上执行,同一连接内的写入天然串行
17
+ const withTransaction = fn => (fastify.sequelize.instance.getDialect() === 'sqlite' ? fn() : fastify.sequelize.instance.transaction(fn));
18
+
15
19
  const generate = async ({ status, transaction }) => {
16
20
  const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
17
21
  const kid = crypto.randomUUID();
@@ -42,7 +46,7 @@ module.exports = fp(async (fastify, options) => {
42
46
  };
43
47
 
44
48
  const ensureKeys = async () => {
45
- await fastify.sequelize.instance.transaction(async transaction => {
49
+ await withTransaction(async transaction => {
46
50
  if (!(await models.key.count({ where: { status: 'active' }, transaction }))) {
47
51
  await generate({ status: 'active', transaction });
48
52
  }
@@ -83,7 +87,7 @@ module.exports = fp(async (fastify, options) => {
83
87
  };
84
88
 
85
89
  const rotate = async () => {
86
- await fastify.sequelize.instance.transaction(async transaction => {
90
+ await withTransaction(async transaction => {
87
91
  const now = new Date();
88
92
  await models.key.update({ status: 'retired', retiredAt: now }, { where: { status: 'active' }, transaction });
89
93
  const next = await models.key.findOne({ where: { status: 'next' }, order: [['createdAt', 'ASC']], transaction });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-oidc",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌",
5
5
  "main": "index.js",
6
6
  "scripts": {