hnch-core 0.1.0
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/config/config.js +74 -0
- package/config/errors.js +66 -0
- package/config/logger.js +144 -0
- package/package.json +34 -0
- package/src/ai/index.js +254 -0
- package/src/auth/index.js +49 -0
- package/src/auth/jwt.js +114 -0
- package/src/auth/sso-callback.js +199 -0
- package/src/auth/sso-init.js +155 -0
- package/src/auth/sync-user.js +57 -0
- package/src/index.js +18 -0
- package/src/middleware/index.js +98 -0
- package/src/utils/index.js +5 -0
- package/src/utils/response.js +92 -0
- package/src/utils/sso-client.js +76 -0
- package/src/utils/utils.js +88 -0
- package/src/utils/validate.js +74 -0
package/src/auth/jwt.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 统一鉴权中间件
|
|
3
|
+
*
|
|
4
|
+
* 合并了原来的 requireJwtAuth (Passport JWT) 和 requireSSOAuth (自定义 SSO)
|
|
5
|
+
* 鉴权顺序: 本地 JWT → SSO 远程验证
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const jwt = require('jsonwebtoken');
|
|
9
|
+
|
|
10
|
+
function requireAuth({ User, Session, logger, jwtSecret, ssoServer }) {
|
|
11
|
+
|
|
12
|
+
async function middleware(req, res, next) {
|
|
13
|
+
const token = req.headers.authorization?.replace('Bearer ', '');
|
|
14
|
+
if (!token) {
|
|
15
|
+
return res.status(401).json({
|
|
16
|
+
success: false,
|
|
17
|
+
code: 'NO_TOKEN',
|
|
18
|
+
message: '未提供认证 Token',
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// 1. 本地 JWT 验证(优先,不调网络)
|
|
23
|
+
let user = await verifyLocal(token, User, Session, logger, jwtSecret);
|
|
24
|
+
|
|
25
|
+
// 2. SSO 远程验证(兜底)
|
|
26
|
+
if (!user) {
|
|
27
|
+
user = await verifySSO(token, User, logger, ssoServer);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (!user) {
|
|
31
|
+
return res.status(401).json({
|
|
32
|
+
success: false,
|
|
33
|
+
code: 'INVALID_TOKEN',
|
|
34
|
+
message: 'Token 无效或已过期,请重新登录',
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
req.user = user;
|
|
39
|
+
next();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return middleware;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 本地 JWT 验证
|
|
47
|
+
* 1. 用 JWT_SECRET 解码 token
|
|
48
|
+
* 2. 查 Session 是否有效且未过期
|
|
49
|
+
* 3. 查 User 是否存在
|
|
50
|
+
*/
|
|
51
|
+
async function verifyLocal(token, User, Session, logger, jwtSecret) {
|
|
52
|
+
try {
|
|
53
|
+
const decoded = jwt.verify(token, jwtSecret, { algorithms: ['HS256'] });
|
|
54
|
+
const session = await Session.findOne({
|
|
55
|
+
user: decoded._id || decoded.id,
|
|
56
|
+
expiration: { $gt: new Date() },
|
|
57
|
+
}).lean();
|
|
58
|
+
if (!session) return null;
|
|
59
|
+
|
|
60
|
+
const user = await User.findById(decoded._id || decoded.id)
|
|
61
|
+
.select('-password -__v')
|
|
62
|
+
.lean();
|
|
63
|
+
if (!user) return null;
|
|
64
|
+
|
|
65
|
+
user.id = (user._id || user.id).toString();
|
|
66
|
+
logger.debug(`[auth] 本地JWT验证成功: ${user.username || user.id}`);
|
|
67
|
+
return user;
|
|
68
|
+
} catch (err) {
|
|
69
|
+
if (err.name === 'TokenExpiredError') {
|
|
70
|
+
logger.debug('[auth] 本地JWT已过期');
|
|
71
|
+
} else if (err.name !== 'JsonWebTokenError') {
|
|
72
|
+
logger.error('[auth] 本地JWT验证异常:', err.message);
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* SSO 远程验证
|
|
80
|
+
* 调用 SSO 服务端 /api/auth/verify/ 验证 token,再查本地 User
|
|
81
|
+
*/
|
|
82
|
+
async function verifySSO(token, User, logger, ssoServer) {
|
|
83
|
+
try {
|
|
84
|
+
const res = await fetch(`${ssoServer}/api/auth/verify/`, {
|
|
85
|
+
method: 'POST',
|
|
86
|
+
headers: { 'Content-Type': 'application/json' },
|
|
87
|
+
body: JSON.stringify({ token }),
|
|
88
|
+
});
|
|
89
|
+
if (!res.ok) {
|
|
90
|
+
logger.debug('[auth] SSO远程验证失败, HTTP', res.status);
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
const data = await res.json();
|
|
94
|
+
if (!data.valid || !data.data?.user) {
|
|
95
|
+
logger.debug('[auth] SSO远程验证返回 invalid');
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const ssoUser = data.data.user;
|
|
100
|
+
const user = await User.findOne({ username: ssoUser.username })
|
|
101
|
+
.select('-password -__v')
|
|
102
|
+
.lean();
|
|
103
|
+
if (!user) return null;
|
|
104
|
+
|
|
105
|
+
user.id = (user._id || user.id).toString();
|
|
106
|
+
logger.debug(`[auth] SSO远程验证成功: ${user.username}`);
|
|
107
|
+
return user;
|
|
108
|
+
} catch (err) {
|
|
109
|
+
logger.error('[auth] SSO远程验证异常:', err.message);
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
module.exports = { requireAuth };
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSO OAuth 2.0 回调路由
|
|
3
|
+
*
|
|
4
|
+
* 从 4 个 subsystem 简化为 1 个 OAuth Client。
|
|
5
|
+
* 所有业务模块(合同、案卷、笔记本……)共享同一个 SSO 客户端。
|
|
6
|
+
*
|
|
7
|
+
* 提供路由:
|
|
8
|
+
* GET /api/sso/login-url — 生成 SSO 登录链接
|
|
9
|
+
* GET /api/sso/callback — OAuth 回调(统一入口,不再分 /callback/:system)
|
|
10
|
+
* POST /api/sso/logout — 登出
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const express = require('express');
|
|
14
|
+
const jwt = require('jsonwebtoken');
|
|
15
|
+
|
|
16
|
+
function createSSORouter(deps) {
|
|
17
|
+
const {
|
|
18
|
+
User,
|
|
19
|
+
Session,
|
|
20
|
+
logger,
|
|
21
|
+
jwtSecret,
|
|
22
|
+
jwtRefreshSecret,
|
|
23
|
+
ssoServer,
|
|
24
|
+
ssoClientId,
|
|
25
|
+
ssoClientSecret,
|
|
26
|
+
ssoRedirectUri,
|
|
27
|
+
ssoInitUser,
|
|
28
|
+
} = deps;
|
|
29
|
+
|
|
30
|
+
const router = express.Router();
|
|
31
|
+
|
|
32
|
+
// GET /api/sso/login-url
|
|
33
|
+
router.get('/login-url', (req, res) => {
|
|
34
|
+
const { redirectPath } = req.query;
|
|
35
|
+
|
|
36
|
+
const state = Buffer.from(JSON.stringify({
|
|
37
|
+
redirectPath: redirectPath || '/',
|
|
38
|
+
timestamp: Date.now(),
|
|
39
|
+
})).toString('base64');
|
|
40
|
+
|
|
41
|
+
const url = new URL(`${ssoServer}/oauth/authorize/`);
|
|
42
|
+
url.searchParams.set('client_id', ssoClientId);
|
|
43
|
+
url.searchParams.set('redirect_uri', ssoRedirectUri);
|
|
44
|
+
url.searchParams.set('response_type', 'code');
|
|
45
|
+
url.searchParams.set('scope', 'openid profile email');
|
|
46
|
+
url.searchParams.set('state', state);
|
|
47
|
+
|
|
48
|
+
logger.info(`[SSO] 生成登录URL`);
|
|
49
|
+
|
|
50
|
+
return res.json({
|
|
51
|
+
success: true,
|
|
52
|
+
data: { loginUrl: url.toString() },
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// GET /api/sso/callback
|
|
57
|
+
router.get('/callback', async (req, res) => {
|
|
58
|
+
try {
|
|
59
|
+
const { code, state, error: oauthError } = req.query;
|
|
60
|
+
|
|
61
|
+
if (oauthError) {
|
|
62
|
+
logger.error(`[SSO] 授权失败: ${oauthError}`);
|
|
63
|
+
return res.redirect(`/login?error=${encodeURIComponent(oauthError)}`);
|
|
64
|
+
}
|
|
65
|
+
if (!code) {
|
|
66
|
+
return res.redirect('/login?error=缺少授权码');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 1. 用授权码换取 access_token
|
|
70
|
+
logger.info('[SSO] 正在换取 Token...');
|
|
71
|
+
const tokenRes = await fetch(`${ssoServer}/oauth/token/`, {
|
|
72
|
+
method: 'POST',
|
|
73
|
+
headers: { 'Content-Type': 'application/json' },
|
|
74
|
+
body: JSON.stringify({
|
|
75
|
+
grant_type: 'authorization_code',
|
|
76
|
+
code,
|
|
77
|
+
client_id: ssoClientId,
|
|
78
|
+
client_secret: ssoClientSecret,
|
|
79
|
+
redirect_uri: ssoRedirectUri,
|
|
80
|
+
}),
|
|
81
|
+
});
|
|
82
|
+
if (!tokenRes.ok) {
|
|
83
|
+
const errData = await tokenRes.json().catch(() => ({}));
|
|
84
|
+
throw new Error(errData.error_description || errData.error || `换Token失败: ${tokenRes.status}`);
|
|
85
|
+
}
|
|
86
|
+
const tokenData = await tokenRes.json();
|
|
87
|
+
if (!tokenData.access_token) {
|
|
88
|
+
throw new Error('SSO 未返回 access_token');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 2. 验证 token 获取用户信息
|
|
92
|
+
logger.info('[SSO] 正在验证 Token...');
|
|
93
|
+
const verifyRes = await fetch(`${ssoServer}/api/auth/verify/`, {
|
|
94
|
+
method: 'POST',
|
|
95
|
+
headers: { 'Content-Type': 'application/json' },
|
|
96
|
+
body: JSON.stringify({ token: tokenData.access_token }),
|
|
97
|
+
});
|
|
98
|
+
if (!verifyRes.ok) {
|
|
99
|
+
throw new Error(`Token验证失败: ${verifyRes.status}`);
|
|
100
|
+
}
|
|
101
|
+
const verifyData = await verifyRes.json();
|
|
102
|
+
if (!verifyData.valid || !verifyData.data?.user) {
|
|
103
|
+
throw new Error('Token 验证返回无效');
|
|
104
|
+
}
|
|
105
|
+
const ssoUser = verifyData.data.user;
|
|
106
|
+
logger.info(`[SSO] 用户验证成功: ${ssoUser.username}`);
|
|
107
|
+
|
|
108
|
+
// 3. 同步本地用户(身份字段的唯一写入入口)
|
|
109
|
+
const localUser = await User.syncFromSSO(ssoUser);
|
|
110
|
+
logger.info(`[SSO] 用户同步完成: ${ssoUser.username} (${localUser._id})`);
|
|
111
|
+
|
|
112
|
+
// 4. 创建本地 Session(互斥登录:先删旧 session)
|
|
113
|
+
const expiresInMs = 7 * 24 * 60 * 60 * 1000; // 7 天
|
|
114
|
+
const oldCount = await Session.countDocuments({ user: localUser._id });
|
|
115
|
+
if (oldCount > 0) {
|
|
116
|
+
await Session.deleteMany({ user: localUser._id });
|
|
117
|
+
logger.info(`[SSO] 互斥登录:删除用户 ${localUser._id} 的 ${oldCount} 个旧 session`);
|
|
118
|
+
}
|
|
119
|
+
const session = new Session({
|
|
120
|
+
user: localUser._id,
|
|
121
|
+
expiration: new Date(Date.now() + expiresInMs),
|
|
122
|
+
});
|
|
123
|
+
const refreshToken = jwt.sign(
|
|
124
|
+
{ id: localUser._id, sessionId: session._id },
|
|
125
|
+
jwtRefreshSecret || jwtSecret,
|
|
126
|
+
{ expiresIn: expiresInMs / 1000 }
|
|
127
|
+
);
|
|
128
|
+
session.refreshTokenHash = refreshToken; // 实际应 hash,这里先存原 token(与原实现一致)
|
|
129
|
+
await session.save();
|
|
130
|
+
|
|
131
|
+
// 5. 种 Cookie(跨子域共享)
|
|
132
|
+
try {
|
|
133
|
+
const redirectHost = new URL(ssoRedirectUri).hostname;
|
|
134
|
+
// 提取根域名(hnch.net),以便跨子域共享
|
|
135
|
+
const parts = redirectHost.split('.');
|
|
136
|
+
const domain = parts.length >= 2
|
|
137
|
+
? '.' + parts.slice(-2).join('.')
|
|
138
|
+
: redirectHost;
|
|
139
|
+
res.cookie('auth_token', refreshToken, {
|
|
140
|
+
domain,
|
|
141
|
+
httpOnly: true,
|
|
142
|
+
secure: process.env.NODE_ENV === 'production',
|
|
143
|
+
maxAge: expiresInMs,
|
|
144
|
+
});
|
|
145
|
+
} catch {
|
|
146
|
+
res.cookie('auth_token', refreshToken, {
|
|
147
|
+
httpOnly: true,
|
|
148
|
+
maxAge: expiresInMs,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// 6. 异步初始化新用户(不阻塞)
|
|
153
|
+
if (ssoInitUser && !localUser.ssoInitialized) {
|
|
154
|
+
setImmediate(() => {
|
|
155
|
+
ssoInitUser(localUser).catch(err =>
|
|
156
|
+
logger.error('[SSO] 用户初始化失败:', err)
|
|
157
|
+
);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 7. 重定向
|
|
162
|
+
let redirectPath = '/';
|
|
163
|
+
if (state) {
|
|
164
|
+
try {
|
|
165
|
+
const stateData = JSON.parse(Buffer.from(state, 'base64').toString('utf-8'));
|
|
166
|
+
redirectPath = stateData.redirectPath || '/';
|
|
167
|
+
} catch { /* ignore */ }
|
|
168
|
+
}
|
|
169
|
+
logger.info(`[SSO] 重定向到: ${redirectPath}`);
|
|
170
|
+
return res.redirect(redirectPath);
|
|
171
|
+
|
|
172
|
+
} catch (err) {
|
|
173
|
+
logger.error('[SSO] 回调失败:', err.message);
|
|
174
|
+
return res.redirect(`/login?error=${encodeURIComponent(err.message)}`);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// POST /api/sso/logout
|
|
179
|
+
router.post('/logout', async (req, res) => {
|
|
180
|
+
try {
|
|
181
|
+
const token = req.headers.authorization?.replace('Bearer ', '');
|
|
182
|
+
if (token) {
|
|
183
|
+
// 删除相关 Session
|
|
184
|
+
await Session.deleteMany({
|
|
185
|
+
refreshTokenHash: token,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
res.clearCookie('auth_token');
|
|
189
|
+
return res.json({ success: true, message: '登出成功' });
|
|
190
|
+
} catch (err) {
|
|
191
|
+
logger.error('[SSO] 登出失败:', err.message);
|
|
192
|
+
return res.status(500).json({ success: false, message: err.message });
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
return router;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
module.exports = { createSSORouter };
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSO 用户初始化
|
|
3
|
+
*
|
|
4
|
+
* 从 client_models/server/services/SSOUserInitService.js 提取
|
|
5
|
+
* 异步执行:校验用户上限 → 注册知识库 → 添加默认 GPTs → 标记完成
|
|
6
|
+
*
|
|
7
|
+
* 用法:
|
|
8
|
+
* const { createSSOInit } = require('@hnch/core/auth/sso-init');
|
|
9
|
+
* const initUser = createSSOInit({ User, logger, supremeUser, orgBaseUrl, companyUuid });
|
|
10
|
+
* await initUser(user);
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
function createSSOInit({ User, logger, supremeUser, orgBaseUrl, companyUuid }) {
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 完整初始化 SSO 用户(异步,不阻塞请求)
|
|
17
|
+
*/
|
|
18
|
+
async function initSSOUser(user) {
|
|
19
|
+
if (user.ssoInitialized) {
|
|
20
|
+
logger.debug(`[Init] 用户已初始化,跳过: ${user.username}`);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
logger.info(`[Init] 开始初始化用户: ${user.username}`);
|
|
25
|
+
|
|
26
|
+
// 1. 验证企业账户上限
|
|
27
|
+
try {
|
|
28
|
+
await checkMaxUserLimit(User, logger, supremeUser, companyUuid);
|
|
29
|
+
} catch (err) {
|
|
30
|
+
logger.warn(`[Init] 用户上限检查失败: ${err.message}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// 2. 注册到知识库系统
|
|
34
|
+
try {
|
|
35
|
+
await registerToKnowledgeSystem(user, logger, orgBaseUrl);
|
|
36
|
+
} catch (err) {
|
|
37
|
+
logger.warn(`[Init] 知识库注册失败: ${err.message}`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// 3. 添加默认 GPTs
|
|
41
|
+
try {
|
|
42
|
+
await addDefaultGPTs(user, User, logger, supremeUser);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
logger.warn(`[Init] 添加GPTs失败: ${err.message}`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// 4. 标记完成
|
|
48
|
+
await User.findByIdAndUpdate(user._id, { ssoInitialized: true });
|
|
49
|
+
logger.info(`[Init] 用户初始化完成: ${user.username}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return initSSOUser;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 检查企业用户数量限制
|
|
57
|
+
*/
|
|
58
|
+
async function checkMaxUserLimit(User, logger, supremeUser, companyUuid) {
|
|
59
|
+
if (!supremeUser || !companyUuid) {
|
|
60
|
+
logger.warn('[Init] 未配置企业验证接口,跳过用户上限检查');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const url = `${supremeUser}company/${companyUuid}`;
|
|
65
|
+
const res = await fetch(url, {
|
|
66
|
+
method: 'GET',
|
|
67
|
+
headers: { 'Content-Type': 'application/json' },
|
|
68
|
+
signal: AbortSignal.timeout(5000),
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
if (res.status !== 200) {
|
|
72
|
+
throw new Error(`企业验证失败: HTTP ${res.status}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const data = await res.json();
|
|
76
|
+
const maxUsers = data.max_user;
|
|
77
|
+
const currentUsers = await User.countDocuments({ is_active: true });
|
|
78
|
+
|
|
79
|
+
logger.info(`[Init] 当前用户: ${currentUsers}, 上限: ${maxUsers}`);
|
|
80
|
+
|
|
81
|
+
if (currentUsers >= maxUsers) {
|
|
82
|
+
throw new Error(`用户数已达上限 (${currentUsers}/${maxUsers})`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 将用户注册到知识库系统
|
|
88
|
+
*/
|
|
89
|
+
async function registerToKnowledgeSystem(user, logger, orgBaseUrl) {
|
|
90
|
+
if (!orgBaseUrl) {
|
|
91
|
+
logger.warn('[Init] 未配置知识库URL,跳过注册');
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const url = `${orgBaseUrl}/v1/user/depart/`;
|
|
96
|
+
const payload = {
|
|
97
|
+
username: user.username,
|
|
98
|
+
password: null,
|
|
99
|
+
user_id: user.id || user._id.toString(),
|
|
100
|
+
depart_name: user.depart_name || '默认部门',
|
|
101
|
+
roles: '3',
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
logger.info(`[Init] 注册知识库: ${user.username}`);
|
|
105
|
+
const res = await fetch(url, {
|
|
106
|
+
method: 'POST',
|
|
107
|
+
headers: { 'Content-Type': 'application/json' },
|
|
108
|
+
body: JSON.stringify(payload),
|
|
109
|
+
signal: AbortSignal.timeout(10000),
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
if (res.status !== 200) {
|
|
113
|
+
const text = await res.text();
|
|
114
|
+
throw new Error(`知识库注册失败: HTTP ${res.status} ${text}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
logger.info(`[Init] 知识库注册成功: ${user.username}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 为用户添加默认 GPTs
|
|
122
|
+
*/
|
|
123
|
+
async function addDefaultGPTs(user, User, logger, supremeUser) {
|
|
124
|
+
if (!supremeUser) {
|
|
125
|
+
logger.warn('[Init] 未配置GPTs接口,跳过');
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const url = `${supremeUser}gpts/?count=3`;
|
|
130
|
+
logger.info(`[Init] 获取热门GPTs: ${user.username}`);
|
|
131
|
+
|
|
132
|
+
const res = await fetch(url, {
|
|
133
|
+
method: 'GET',
|
|
134
|
+
headers: { 'Content-Type': 'application/json' },
|
|
135
|
+
signal: AbortSignal.timeout(5000),
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
if (res.status !== 200) {
|
|
139
|
+
throw new Error(`获取GPTs失败: HTTP ${res.status}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const data = await res.json();
|
|
143
|
+
const gptsList = data.data?.data || [];
|
|
144
|
+
const gptIds = gptsList.map(item => item.gid).filter(Boolean);
|
|
145
|
+
|
|
146
|
+
if (gptIds.length > 0) {
|
|
147
|
+
await User.findByIdAndUpdate(
|
|
148
|
+
user._id,
|
|
149
|
+
{ $addToSet: { gpts: { $each: gptIds } } },
|
|
150
|
+
);
|
|
151
|
+
logger.info(`[Init] 添加默认GPTs: ${gptIds.join(', ')}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
module.exports = { createSSOInit };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSO 用户同步 —— 工厂函数
|
|
3
|
+
*
|
|
4
|
+
* 将 `User.syncFromSSO(ssoUser)` 从具体项目模型提取到此底座模块,
|
|
5
|
+
* 新项目引入后只需注入自己的 User Model。
|
|
6
|
+
*
|
|
7
|
+
* 用法:
|
|
8
|
+
* const { createSyncFromSSO } = require('@hnch/core/auth/sync-user');
|
|
9
|
+
* User.syncFromSSO = createSyncFromSSO({ User });
|
|
10
|
+
* // 此后 sso-callback 即可正常调用 User.syncFromSSO(ssoUser)
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
function createSyncFromSSO({ User }) {
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 从 SSO 服务端同步本地用户信息
|
|
17
|
+
*
|
|
18
|
+
* 身份字段(username/email/name/avatar/phone)的唯一写入入口。
|
|
19
|
+
* 业务代码不应直接修改这些字段,应通过此方法从 SSO 同步。
|
|
20
|
+
*
|
|
21
|
+
* @param {Object} ssoUser - SSO 返回的用户信息 { username, email, nickname, avatar, phone, id }
|
|
22
|
+
* @returns {Promise} 本地用户文档
|
|
23
|
+
*/
|
|
24
|
+
return async function syncFromSSO(ssoUser) {
|
|
25
|
+
let localUser = await User.findOne({ username: ssoUser.username });
|
|
26
|
+
|
|
27
|
+
if (localUser) {
|
|
28
|
+
// 已存在 —— 只更新 SSO 身份字段,不覆盖本地业务字段(gpts/plugins/depart 等)
|
|
29
|
+
if (ssoUser.email && localUser.email !== ssoUser.email) localUser.email = ssoUser.email;
|
|
30
|
+
if (ssoUser.nickname && localUser.name !== ssoUser.nickname) localUser.name = ssoUser.nickname;
|
|
31
|
+
if (ssoUser.avatar) localUser.avatar = ssoUser.avatar;
|
|
32
|
+
if (!localUser.ssoUserId) localUser.ssoUserId = String(ssoUser.id);
|
|
33
|
+
if (ssoUser.phone && !localUser.phone) localUser.phone = ssoUser.phone;
|
|
34
|
+
await localUser.save();
|
|
35
|
+
return localUser;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 新用户
|
|
39
|
+
const isFirstUser = (await User.countDocuments({})) === 0;
|
|
40
|
+
localUser = new User({
|
|
41
|
+
provider: 'sso',
|
|
42
|
+
username: ssoUser.username,
|
|
43
|
+
email: ssoUser.email || `sso_${ssoUser.username}@hnch.net`,
|
|
44
|
+
name: ssoUser.nickname || ssoUser.username,
|
|
45
|
+
phone: ssoUser.phone || null,
|
|
46
|
+
avatar: ssoUser.avatar || null,
|
|
47
|
+
role: isFirstUser ? 'ADMIN' : 'USER',
|
|
48
|
+
is_active: true,
|
|
49
|
+
ssoUserId: String(ssoUser.id),
|
|
50
|
+
ssoInitialized: false,
|
|
51
|
+
});
|
|
52
|
+
await localUser.save();
|
|
53
|
+
return localUser;
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = { createSyncFromSSO };
|
package/src/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hnch/core
|
|
3
|
+
* hnch 核心基础设施 —— 鉴权、SSO、AI 网关、通知、日志
|
|
4
|
+
*
|
|
5
|
+
* 用法:
|
|
6
|
+
* const { createAuth } = require('@hnch/core/auth');
|
|
7
|
+
* const auth = createAuth({ User, Session, logger, ...config });
|
|
8
|
+
* app.use('/api/*', auth.requireAuth);
|
|
9
|
+
* app.use('/api/sso', auth.ssoRouter);
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
module.exports = {
|
|
13
|
+
auth: require('./auth'),
|
|
14
|
+
ai: require('./ai'),
|
|
15
|
+
...require('../config'), // logger, config, errors
|
|
16
|
+
middleware: require('./middleware'),
|
|
17
|
+
...require('./utils'), // response, utils, validate
|
|
18
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 底座 Express 错误处理中间件
|
|
3
|
+
*
|
|
4
|
+
* 将 AppError 子类自动转换为 HTTP 响应。
|
|
5
|
+
*
|
|
6
|
+
* 用法:
|
|
7
|
+
* const { errorHandler, notFound } = require('@hnch/core/middleware');
|
|
8
|
+
* app.use(errorHandler({ logger }));
|
|
9
|
+
* app.use(notFound());
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 统一错误处理中间件
|
|
14
|
+
*
|
|
15
|
+
* @param {Object} options
|
|
16
|
+
* @param {Object} options.logger - 日志实例 (可选)
|
|
17
|
+
* @param {boolean} options.exposeStack - 是否暴露堆栈 (默认: NODE_ENV !== 'production')
|
|
18
|
+
*/
|
|
19
|
+
function errorHandler(options = {}) {
|
|
20
|
+
const { logger, exposeStack = process.env.NODE_ENV !== 'production' } = options;
|
|
21
|
+
|
|
22
|
+
return (err, req, res, _next) => {
|
|
23
|
+
// 如果响应已发送,交给 Express 默认处理
|
|
24
|
+
if (res.headersSent) return;
|
|
25
|
+
|
|
26
|
+
// 如果是 AppError 子类,用自带的状态码
|
|
27
|
+
const statusCode = err.statusCode || 500;
|
|
28
|
+
const code = err.code || 'INTERNAL_ERROR';
|
|
29
|
+
const message = statusCode === 500 && !exposeStack
|
|
30
|
+
? '服务器内部错误'
|
|
31
|
+
: err.message || '未知错误';
|
|
32
|
+
|
|
33
|
+
const body = {
|
|
34
|
+
success: false,
|
|
35
|
+
code,
|
|
36
|
+
message,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
if (err.details) {
|
|
40
|
+
body.details = err.details;
|
|
41
|
+
}
|
|
42
|
+
if (exposeStack && err.stack) {
|
|
43
|
+
body.stack = err.stack.split('\n').map(s => s.trim());
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (logger) {
|
|
47
|
+
const level = statusCode >= 500 ? 'error' : 'warn';
|
|
48
|
+
logger[level](`${req.method} ${req.originalUrl} ${statusCode} - ${err.message}`, {
|
|
49
|
+
code,
|
|
50
|
+
stack: err.stack?.split('\n')[0],
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
res.status(statusCode).json(body);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 404 兜底中间件 —— 必须放在所有路由之后
|
|
60
|
+
*/
|
|
61
|
+
function notFound() {
|
|
62
|
+
return (req, res) => {
|
|
63
|
+
res.status(404).json({
|
|
64
|
+
success: false,
|
|
65
|
+
code: 'NOT_FOUND',
|
|
66
|
+
message: `接口不存在: ${req.method} ${req.originalUrl}`,
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 为 Express app 挂载标准中间件
|
|
73
|
+
*
|
|
74
|
+
* @param {Express} app
|
|
75
|
+
* @param {Object} options
|
|
76
|
+
* @param {Object} options.logger - 日志实例
|
|
77
|
+
* @param {number} options.maxBody - body 大小限制 (默认 '50mb')
|
|
78
|
+
*/
|
|
79
|
+
function setupStandard(app, options = {}) {
|
|
80
|
+
const { logger, maxBody = '50mb' } = options;
|
|
81
|
+
const express = require('express');
|
|
82
|
+
const cors = require('cors');
|
|
83
|
+
|
|
84
|
+
app.use(cors());
|
|
85
|
+
app.use(express.json({ limit: maxBody }));
|
|
86
|
+
app.use(express.urlencoded({ extended: true, limit: maxBody }));
|
|
87
|
+
|
|
88
|
+
if (logger) {
|
|
89
|
+
const { requestLogger } = require('@hnch/core/logger');
|
|
90
|
+
app.use(requestLogger({ logger }));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = {
|
|
95
|
+
errorHandler,
|
|
96
|
+
notFound,
|
|
97
|
+
setupStandard,
|
|
98
|
+
};
|