@kne/fastify-oidc 0.1.17 → 0.1.19
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 +1 -0
- package/libs/controllers/admin.js +40 -1
- package/libs/idp/adapters/sequelize.js +21 -1
- package/libs/idp/create-provider.js +24 -2
- package/libs/idp/index.js +1 -0
- package/libs/services/grant.js +37 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -538,6 +538,7 @@ oidc-provider 的交互地址,303 跳转到 `${ORIGIN}${interactionPage}?uid={
|
|
|
538
538
|
| `GET /api/oidc/admin/key/list` | 签名密钥列表 `[{ id, kid, alg, status, activatedAt, retiredAt, createdAt }]` | `key:manage` |
|
|
539
539
|
| `POST /api/oidc/admin/key/rotate` | 轮换签名密钥 | `key:manage` |
|
|
540
540
|
| `GET /api/oidc/admin/session/list?userId=` | 用户 IdP 会话 `[{ uid, loginAt, expiresAt, clients: [{ clientId, sid }] }]` | `session:manage` |
|
|
541
|
+
| `GET /api/oidc/admin/session/active-users` | 活跃用户(有未过期会话),按最近登录倒序分页(`perPage` 默认 20、`currentPage`;传 `userIds`(逗号分隔)时只判断这些用户是否活跃,用于标记搜索结果):`{ pageData: [{ id, nickname, avatar, email, phone, status, isSuperAdmin, sessionCount, lastLoginAt }], totalCount, activeCount }`,`activeCount` 为全部活跃用户数 | `session:manage` |
|
|
541
542
|
| `POST /api/oidc/admin/session/revoke` | `{ uid }` 结束会话并通知子项目 | `session:manage` |
|
|
542
543
|
| `POST /api/oidc/admin/session/revoke-user` | `{ userId, logout = true }` 撤销用户全部令牌,`logout` 时同时强制下线;返回 `{ grants, sessions }` | `session:manage` |
|
|
543
544
|
| `GET /api/oidc/admin/app/list` | 子应用列表(`filter.keyword` / `filter.status` / `filter.tenantMode`),每项带 `permissionCount` | `app:manage` |
|
|
@@ -1,5 +1,5 @@
|
|
|
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
|
+
const { str, num, bool, any, list, obj, success, empty, pageResult, client, resourceServer, app, key } = require('../schema/response');
|
|
3
3
|
|
|
4
4
|
const idSchema = { type: 'object', required: ['id'], properties: { id: { type: 'string', description: '记录 ID' } } };
|
|
5
5
|
const listQuery = {
|
|
@@ -24,6 +24,18 @@ const statusBody = {
|
|
|
24
24
|
properties: { id: { type: 'string', description: '记录 ID' }, status: { type: 'string', enum: ['open', 'closed'], description: '目标状态:open 启用,closed 停用' } }
|
|
25
25
|
};
|
|
26
26
|
|
|
27
|
+
const activeUser = obj('活跃用户', {
|
|
28
|
+
id: str('用户 ID'),
|
|
29
|
+
nickname: str('昵称'),
|
|
30
|
+
avatar: any('头像文件 ID'),
|
|
31
|
+
email: str('邮箱'),
|
|
32
|
+
phone: str('手机号'),
|
|
33
|
+
status: any('用户状态'),
|
|
34
|
+
isSuperAdmin: bool('是否为平台超级管理员;账号插件不支持判断时不返回'),
|
|
35
|
+
sessionCount: num('未过期会话数'),
|
|
36
|
+
lastLoginAt: any('最近登录时间')
|
|
37
|
+
});
|
|
38
|
+
|
|
27
39
|
module.exports = fp(async (fastify, options) => {
|
|
28
40
|
const { services, translator } = fastify[options.name];
|
|
29
41
|
if (!options.runtime.idpEnabled) {
|
|
@@ -262,6 +274,33 @@ module.exports = fp(async (fastify, options) => {
|
|
|
262
274
|
wrap(async request => services.grant.listSessions(request.query))
|
|
263
275
|
);
|
|
264
276
|
|
|
277
|
+
fastify.get(
|
|
278
|
+
`${admin}/session/active-users`,
|
|
279
|
+
{
|
|
280
|
+
onRequest: options.getAuthenticate('session:manage'),
|
|
281
|
+
schema: {
|
|
282
|
+
tags: ['OIDC管理后台-会话'],
|
|
283
|
+
summary: '活跃用户列表',
|
|
284
|
+
description: '活跃用户 = 有未过期 IdP 登录会话的用户,按最近登录时间倒序分页;totalCount 为符合条件的活跃用户数,activeCount 为全部活跃用户数。传 userIds 时只判断这些用户是否活跃(用于标记搜索结果)',
|
|
285
|
+
query: {
|
|
286
|
+
type: 'object',
|
|
287
|
+
properties: {
|
|
288
|
+
userIds: { type: 'string', description: '只在这些用户中查询活跃用户,逗号分隔的用户 ID' },
|
|
289
|
+
perPage: { type: 'number', default: 20, minimum: 1, maximum: 100, description: '每页条数' },
|
|
290
|
+
currentPage: { type: 'number', default: 1, minimum: 1, description: '页码,从 1 开始' }
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
response: success(
|
|
294
|
+
'活跃用户',
|
|
295
|
+
Object.assign({}, pageResult('活跃用户', activeUser), {
|
|
296
|
+
properties: Object.assign({}, pageResult('活跃用户', activeUser).properties, { activeCount: num('全部活跃用户数,不受 userIds 影响') })
|
|
297
|
+
})
|
|
298
|
+
)
|
|
299
|
+
}
|
|
300
|
+
},
|
|
301
|
+
wrap(async request => services.grant.listActiveUsers(request.query))
|
|
302
|
+
);
|
|
303
|
+
|
|
265
304
|
fastify.post(
|
|
266
305
|
`${admin}/session/revoke`,
|
|
267
306
|
{
|
|
@@ -7,7 +7,7 @@ const epochTime = date => Math.floor(date.getTime() / 1000);
|
|
|
7
7
|
* 退出时 end_session 要先等 back-channel 通知完才销毁 Session,期间同一 cookie 的并发请求(如子应用 401 后静默登录)
|
|
8
8
|
* 已读到旧 Session,会在销毁后把它原样写回;这里记下已销毁的 Session id,拒绝写回与读取。
|
|
9
9
|
*/
|
|
10
|
-
module.exports = ({ models, endedStore, sessionTTL = 0 }) => {
|
|
10
|
+
module.exports = ({ models, Op, endedStore, sessionTTL = 0 }) => {
|
|
11
11
|
const endedKey = id => `session-ended:${id}`;
|
|
12
12
|
const isEnded = async (name, id) => name === 'Session' && !!endedStore && !!(await endedStore.get(endedKey(id)));
|
|
13
13
|
const toPayload = row => {
|
|
@@ -89,6 +89,26 @@ module.exports = ({ models, endedStore, sessionTTL = 0 }) => {
|
|
|
89
89
|
return rows.map(toPayload).filter(Boolean);
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
/** 有未过期登录会话的用户,按用户聚合:[{ accountId, sessionCount, lastLoginTs }];传 accountIds 时只在这些用户中查 */
|
|
93
|
+
async findActiveAccounts({ accountIds } = {}) {
|
|
94
|
+
const rows = await models.payload.findAll({
|
|
95
|
+
attributes: ['accountId', 'payload'],
|
|
96
|
+
where: {
|
|
97
|
+
modelName: this.name,
|
|
98
|
+
accountId: accountIds ? { [Op.in]: accountIds.map(String) } : { [Op.ne]: null },
|
|
99
|
+
expiresAt: { [Op.gt]: new Date() }
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
const accounts = new Map();
|
|
103
|
+
for (const { accountId, payload } of rows) {
|
|
104
|
+
const item = accounts.get(accountId) || { accountId, sessionCount: 0, lastLoginTs: 0 };
|
|
105
|
+
item.sessionCount++;
|
|
106
|
+
item.lastLoginTs = Math.max(item.lastLoginTs, payload?.loginTs || 0);
|
|
107
|
+
accounts.set(accountId, item);
|
|
108
|
+
}
|
|
109
|
+
return Array.from(accounts.values());
|
|
110
|
+
}
|
|
111
|
+
|
|
92
112
|
async findGrantIdsByAccountId(accountId) {
|
|
93
113
|
const rows = await models.payload.findAll({
|
|
94
114
|
attributes: ['payloadId'],
|
|
@@ -272,9 +272,31 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
|
|
|
272
272
|
}
|
|
273
273
|
return globalThis.fetch(url, init);
|
|
274
274
|
},
|
|
275
|
+
// 浏览器授权失败(如 interaction 过期)时不要吐 JSON;跳 SPA 回调页由前端引导重新登录。
|
|
276
|
+
// 纯 API 客户端(Accept 只要 JSON、不要 HTML)仍返回 JSON。
|
|
275
277
|
renderError: async (ctx, out) => {
|
|
276
|
-
ctx.
|
|
277
|
-
|
|
278
|
+
const accept = String(ctx.get('accept') || '');
|
|
279
|
+
const wantsJson = accept.includes('application/json') && !accept.includes('text/html');
|
|
280
|
+
if (wantsJson) {
|
|
281
|
+
ctx.type = 'json';
|
|
282
|
+
ctx.body = out;
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const params = new URLSearchParams();
|
|
286
|
+
if (out.error) {
|
|
287
|
+
params.set('error', out.error);
|
|
288
|
+
}
|
|
289
|
+
if (out.error_description) {
|
|
290
|
+
params.set('error_description', out.error_description);
|
|
291
|
+
}
|
|
292
|
+
if (out.state) {
|
|
293
|
+
params.set('state', out.state);
|
|
294
|
+
}
|
|
295
|
+
const path = options.errorRedirectPath || '/oidc-callback';
|
|
296
|
+
const target = new URL(path, `${runtime.issuerOrigin}/`);
|
|
297
|
+
target.search = params.toString();
|
|
298
|
+
ctx.status = 303;
|
|
299
|
+
ctx.redirect(target.toString());
|
|
278
300
|
}
|
|
279
301
|
};
|
|
280
302
|
|
package/libs/idp/index.js
CHANGED
|
@@ -114,6 +114,7 @@ module.exports = ({ fastify, options, translator }) => {
|
|
|
114
114
|
options.adapter ||
|
|
115
115
|
createSequelizeAdapter({
|
|
116
116
|
models: fastify[options.name].models,
|
|
117
|
+
Op: fastify.sequelize.Sequelize.Op,
|
|
117
118
|
endedStore: options.revocationStore || createMemoryStore(),
|
|
118
119
|
sessionTTL: options.ttl.session
|
|
119
120
|
});
|
package/libs/services/grant.js
CHANGED
|
@@ -4,6 +4,8 @@ const { createError } = require('../utils/intl');
|
|
|
4
4
|
|
|
5
5
|
const { NotFound } = httpErrors;
|
|
6
6
|
|
|
7
|
+
const ACTIVE_USER_FIELDS = ['nickname', 'avatar', 'email', 'phone', 'status'];
|
|
8
|
+
const pick = (source, keys) => Object.fromEntries(keys.filter(key => source[key] !== undefined).map(key => [key, source[key]]));
|
|
7
9
|
const TOKEN_MODELS = ['AccessToken', 'AuthorizationCode', 'RefreshToken', 'DeviceCode', 'BackchannelAuthenticationRequest'];
|
|
8
10
|
|
|
9
11
|
module.exports = fp(async (fastify, options) => {
|
|
@@ -51,6 +53,40 @@ module.exports = fp(async (fastify, options) => {
|
|
|
51
53
|
}));
|
|
52
54
|
};
|
|
53
55
|
|
|
56
|
+
/**
|
|
57
|
+
* 活跃用户:有未过期登录会话的用户,按最近登录倒序分页。
|
|
58
|
+
* totalCount 为符合条件的活跃用户数,activeCount 为全部活跃用户数;
|
|
59
|
+
* 传 userIds(逗号分隔)时只判断这些用户是否活跃,用于对搜索结果标记活跃状态。
|
|
60
|
+
*/
|
|
61
|
+
const listActiveUsers = async ({ perPage = 20, currentPage = 1, userIds } = {}) => {
|
|
62
|
+
const adapter = getIdp().getAdapter('Session');
|
|
63
|
+
if (typeof adapter.findActiveAccounts !== 'function') {
|
|
64
|
+
throw createError(null, 'adapterSessionQueryMissing');
|
|
65
|
+
}
|
|
66
|
+
const { identity } = getIdp();
|
|
67
|
+
const accountIds = userIds ? String(userIds).split(',').filter(Boolean) : null;
|
|
68
|
+
const accounts = (await adapter.findActiveAccounts({ accountIds })).sort((a, b) => b.lastLoginTs - a.lastLoginTs);
|
|
69
|
+
const activeCount = accountIds ? (await adapter.findActiveAccounts()).length : accounts.length;
|
|
70
|
+
const offset = perPage * (currentPage - 1);
|
|
71
|
+
const pageData = (
|
|
72
|
+
await Promise.all(
|
|
73
|
+
accounts.slice(offset, offset + perPage).map(async ({ accountId, sessionCount, lastLoginTs }) => {
|
|
74
|
+
const user = await identity.getUser(accountId);
|
|
75
|
+
if (!user) {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
return Object.assign(pick(user, ACTIVE_USER_FIELDS), {
|
|
79
|
+
id: String(user.id),
|
|
80
|
+
isSuperAdmin: await identity.isSuperAdmin(user.id),
|
|
81
|
+
sessionCount,
|
|
82
|
+
lastLoginAt: lastLoginTs ? new Date(lastLoginTs * 1000) : null
|
|
83
|
+
});
|
|
84
|
+
})
|
|
85
|
+
)
|
|
86
|
+
).filter(Boolean);
|
|
87
|
+
return { pageData, totalCount: accounts.length, activeCount };
|
|
88
|
+
};
|
|
89
|
+
|
|
54
90
|
const revokeSession = async ({ uid }) => {
|
|
55
91
|
const adapter = getIdp().getAdapter('Session');
|
|
56
92
|
const session = await adapter.findByUid(uid);
|
|
@@ -100,5 +136,5 @@ module.exports = fp(async (fastify, options) => {
|
|
|
100
136
|
return { grants: grants + grantIds.length, sessions };
|
|
101
137
|
};
|
|
102
138
|
|
|
103
|
-
services.grant = { revokeGrant, revokeByAccount, listSessions, revokeSession };
|
|
139
|
+
services.grant = { revokeGrant, revokeByAccount, listSessions, listActiveUsers, revokeSession };
|
|
104
140
|
});
|