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.
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 底座配置模块
3
+ *
4
+ * 提供统一的环境变量加载和校验。
5
+ *
6
+ * 用法:
7
+ * const { loadConfig, requireKeys, get } = require('@hnch/core/config');
8
+ * const config = loadConfig({
9
+ * required: ['JWT_SECRET', 'GATEWAY_URL'],
10
+ * defaults: { PORT: '3080', HOST: '0.0.0.0' },
11
+ * });
12
+ * console.log(config.get('PORT')); // '3080'
13
+ */
14
+
15
+ /**
16
+ * 校验必填环境变量,缺失则抛出
17
+ */
18
+ function requireKeys(keys) {
19
+ const missing = keys.filter(k => !process.env[k]);
20
+ if (missing.length) {
21
+ throw new Error(`缺少必要的环境变量: ${missing.join(', ')}`);
22
+ }
23
+ }
24
+
25
+ /**
26
+ * 安全获取环境变量,支持类型转换和默认值
27
+ */
28
+ function get(key, fallback) {
29
+ const val = process.env[key];
30
+ if (val === undefined || val === '') return fallback;
31
+ // 自动转换布尔和数字
32
+ if (val === 'true') return true;
33
+ if (val === 'false') return false;
34
+ const num = Number(val);
35
+ if (!isNaN(num) && val.trim() !== '') return num;
36
+ return val;
37
+ }
38
+
39
+ /**
40
+ * 加载配置
41
+ *
42
+ * @param {Object} opts
43
+ * @param {string[]} opts.required - 必填的环境变量列表
44
+ * @param {Object} opts.defaults - 默认值 { KEY: fallback }
45
+ * @returns {{ get, env, config }} - get(key, fb), env 原始对象, config 合并后的对象
46
+ */
47
+ function loadConfig(opts = {}) {
48
+ const { required = [], defaults = {} } = opts;
49
+
50
+ if (required.length) {
51
+ requireKeys(required);
52
+ }
53
+
54
+ const config = { ...defaults };
55
+ for (const key of Object.keys(process.env)) {
56
+ if (process.env[key] !== undefined) {
57
+ config[key] = get(key);
58
+ }
59
+ }
60
+ // defaults 优先(已设置的 env 会覆盖)
61
+ for (const [k, v] of Object.entries(defaults)) {
62
+ if (config[k] === undefined) {
63
+ config[k] = v;
64
+ }
65
+ }
66
+
67
+ return {
68
+ get: (key, fb) => config[key] ?? fb,
69
+ env: process.env,
70
+ config,
71
+ };
72
+ }
73
+
74
+ module.exports = { loadConfig, requireKeys, get };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 底座统一错误类
3
+ *
4
+ * 用法:
5
+ * const { AppError, NotFoundError, AuthError, ValidationError } = require('@hnch/core/errors');
6
+ * throw new NotFoundError('用户不存在');
7
+ * throw new AuthError('Token 无效');
8
+ * throw new ValidationError('手机号格式错误', { field: 'phone' });
9
+ */
10
+
11
+ class AppError extends Error {
12
+ constructor(message, statusCode = 500, code = 'APP_ERROR', details = null) {
13
+ super(message);
14
+ this.name = this.constructor.name;
15
+ this.statusCode = statusCode;
16
+ this.code = code;
17
+ this.details = details;
18
+ Error.captureStackTrace(this, this.constructor);
19
+ }
20
+ }
21
+
22
+ class NotFoundError extends AppError {
23
+ constructor(message = '资源不存在', code = 'NOT_FOUND', details = null) {
24
+ super(message, 404, code, details);
25
+ }
26
+ }
27
+
28
+ class AuthError extends AppError {
29
+ constructor(message = '未授权', code = 'UNAUTHORIZED', details = null) {
30
+ super(message, 401, code, details);
31
+ }
32
+ }
33
+
34
+ class ForbiddenError extends AppError {
35
+ constructor(message = '无权限', code = 'FORBIDDEN', details = null) {
36
+ super(message, 403, code, details);
37
+ }
38
+ }
39
+
40
+ class ValidationError extends AppError {
41
+ constructor(message = '参数校验失败', details = null) {
42
+ super(message, 400, 'VALIDATION_ERROR', details);
43
+ }
44
+ }
45
+
46
+ class ConflictError extends AppError {
47
+ constructor(message = '数据冲突', code = 'CONFLICT', details = null) {
48
+ super(message, 409, code, details);
49
+ }
50
+ }
51
+
52
+ class TooManyError extends AppError {
53
+ constructor(message = '请求过于频繁', code = 'TOO_MANY', details = null) {
54
+ super(message, 429, code, details);
55
+ }
56
+ }
57
+
58
+ module.exports = {
59
+ AppError,
60
+ NotFoundError,
61
+ AuthError,
62
+ ForbiddenError,
63
+ ValidationError,
64
+ ConflictError,
65
+ TooManyError,
66
+ };
@@ -0,0 +1,144 @@
1
+ /**
2
+ * 底座统一日志模块
3
+ *
4
+ * 基于 winston,同时提供:
5
+ * - 结构化日志 (info/warn/error/debug)
6
+ * - HTTP 请求日志中间件 (Express 兼容)
7
+ * - 彩色控制台输出 + 文件持久化
8
+ *
9
+ * 用法:
10
+ * const { createLogger, requestLogger } = require('@hnch/core/logger');
11
+ * const logger = createLogger({ name: 'my-app' });
12
+ * app.use(requestLogger({ logger }));
13
+ */
14
+
15
+ const winston = require('winston');
16
+ const path = require('path');
17
+ const fs = require('fs');
18
+
19
+ // ── 自定义等级和颜色 ──
20
+ const levels = { error: 0, warn: 1, info: 2, http: 3, debug: 4 };
21
+ const colors = { error: 'red', warn: 'yellow', info: 'green', http: 'cyan', debug: 'blue' };
22
+ winston.addColors(colors);
23
+
24
+ // ── 控制台格式(带颜色) ──
25
+ const consoleFormat = winston.format.combine(
26
+ winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
27
+ winston.format.colorize({ all: true }),
28
+ winston.format.printf(({ timestamp, level, message, name, ...meta }) => {
29
+ const prefix = name ? `[${name}]` : '';
30
+ const extra = Object.keys(meta).length ? ' ' + JSON.stringify(meta) : '';
31
+ return `${timestamp} ${level}: ${prefix} ${message}${extra}`;
32
+ }),
33
+ );
34
+
35
+ // ── 文件格式(无颜色) ──
36
+ const fileFormat = winston.format.combine(
37
+ winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
38
+ winston.format.printf(({ timestamp, level, message, name, ...meta }) => {
39
+ const prefix = name ? `[${name}]` : '';
40
+ const extra = Object.keys(meta).length ? ' ' + JSON.stringify(meta) : '';
41
+ return `${timestamp} [${level.toUpperCase()}]: ${prefix} ${message}${extra}`;
42
+ }),
43
+ );
44
+
45
+ /**
46
+ * 创建 logger 实例
47
+ *
48
+ * @param {Object} options
49
+ * @param {string} options.name - 应用名称,会出现在日志前缀
50
+ * @param {string} options.level - 最低日志级别 (默认 debug)
51
+ * @param {string} options.logDir - 文件日志目录 (默认 './logs')
52
+ * @param {boolean} options.console - 是否输出到控制台 (默认 true)
53
+ * @param {boolean} options.file - 是否输出到文件 (默认 true)
54
+ * @returns {winston.Logger}
55
+ */
56
+ function createLogger(options = {}) {
57
+ const {
58
+ name = 'app',
59
+ level = process.env.LOG_LEVEL || (process.env.NODE_ENV === 'production' ? 'info' : 'debug'),
60
+ logDir = './logs',
61
+ console: enableConsole = true,
62
+ file: enableFile = true,
63
+ } = options;
64
+
65
+ const transports = [];
66
+
67
+ if (enableConsole) {
68
+ transports.push(new winston.transports.Console({ format: consoleFormat }));
69
+ }
70
+
71
+ if (enableFile) {
72
+ if (!fs.existsSync(logDir)) {
73
+ fs.mkdirSync(logDir, { recursive: true });
74
+ }
75
+ transports.push(new winston.transports.File({
76
+ filename: path.join(logDir, 'app.log'),
77
+ format: fileFormat,
78
+ maxsize: 10 * 1024 * 1024, // 10MB
79
+ maxFiles: 7,
80
+ }));
81
+ transports.push(new winston.transports.File({
82
+ filename: path.join(logDir, 'error.log'),
83
+ level: 'error',
84
+ format: fileFormat,
85
+ maxsize: 10 * 1024 * 1024,
86
+ maxFiles: 7,
87
+ }));
88
+ }
89
+
90
+ return winston.createLogger({
91
+ levels,
92
+ level,
93
+ defaultMeta: { name },
94
+ transports,
95
+ });
96
+ }
97
+
98
+ /**
99
+ * HTTP 请求日志中间件 (Express)
100
+ *
101
+ * 用法:
102
+ * app.use(requestLogger({ logger }));
103
+ *
104
+ * @param {Object} options
105
+ * @param {winston.Logger} options.logger - logger 实例
106
+ * @param {boolean} options.color - 是否彩色输出 (默认 true)
107
+ */
108
+ function requestLogger(options = {}) {
109
+ const {
110
+ logger = createLogger({ name: 'http' }),
111
+ } = options;
112
+
113
+ return (req, res, next) => {
114
+ const start = Date.now();
115
+
116
+ res.on('finish', () => {
117
+ const ms = Date.now() - start;
118
+ const level = res.statusCode >= 500 ? 'error'
119
+ : res.statusCode >= 400 ? 'warn'
120
+ : 'http';
121
+
122
+ logger.log(level, '', {
123
+ method: req.method,
124
+ url: req.originalUrl || req.url,
125
+ status: res.statusCode,
126
+ ms,
127
+ ip: req.ip || req.socket?.remoteAddress,
128
+ });
129
+ });
130
+
131
+ next();
132
+ };
133
+ }
134
+
135
+ /**
136
+ * 默认 logger —— 零配置可用
137
+ */
138
+ const defaultLogger = createLogger();
139
+
140
+ module.exports = {
141
+ createLogger,
142
+ requestLogger,
143
+ logger: defaultLogger,
144
+ };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "hnch-core",
3
+ "version": "0.1.0",
4
+ "description": "hnch 核心基础设施 —— 鉴权、SSO、AI 网关、通知、日志等共享能力",
5
+ "main": "src/index.js",
6
+ "exports": {
7
+ ".": "./src/index.js",
8
+ "./auth": "./src/auth/index.js",
9
+ "./auth/sso-init": "./src/auth/sso-init.js",
10
+ "./ai": "./src/ai/index.js",
11
+ "./logger": "./config/logger.js",
12
+ "./config": "./config/config.js",
13
+ "./errors": "./config/errors.js",
14
+ "./middleware": "./src/middleware/index.js",
15
+ "./response": "./src/utils/response.js",
16
+ "./utils": "./src/utils/utils.js",
17
+ "./validate": "./src/utils/validate.js",
18
+ "./utils/sso-client": "./src/utils/sso-client.js",
19
+ "./auth/sync-user": "./src/auth/sync-user.js"
20
+ },
21
+ "scripts": {
22
+ "test": "echo \"Error: no test specified\" && exit 1"
23
+ },
24
+ "keywords": [],
25
+ "author": "",
26
+ "license": "ISC",
27
+ "dependencies": {
28
+ "jsonwebtoken": "^9.0.3",
29
+ "winston": "^3.19.0"
30
+ },
31
+ "peerDependencies": {
32
+ "express": "^4.21.0"
33
+ }
34
+ }
@@ -0,0 +1,254 @@
1
+ /**
2
+ * 底座 AI 客户端
3
+ *
4
+ * 统一 AI 网关调用 —— 所有客户项目通过此模块访问 server_models。
5
+ * 原生 fetch 实现,零额外依赖。
6
+ *
7
+ * 用法:
8
+ * const ai = require('@hnch/core/ai').init({ gatewayUrl: 'http://...' });
9
+ *
10
+ * // 流式对话
11
+ * await ai.streamChat('/api/ask/openAI', data, { req, res, onComplete });
12
+ *
13
+ * // 非流式调用
14
+ * const result = await ai.call('POST', '/api/files/out/word', data, { req });
15
+ *
16
+ * // 文件上传
17
+ * await ai.upload('/api/files/in', formData, { req });
18
+ */
19
+
20
+ function init({ gatewayUrl, defaultTimeout = 300000 }) {
21
+
22
+ // ── 构造完整网关 URL ─────────────────────────────────
23
+
24
+ function urlFor(endpoint) {
25
+ const base = gatewayUrl.replace(/\/$/, '');
26
+ const path = endpoint.startsWith('/') ? endpoint : '/' + endpoint;
27
+ return `${base}/proxy${path}`;
28
+ }
29
+
30
+ // ── 通用请求头 ─────────────────────────────────────
31
+
32
+ function headersFor(options = {}) {
33
+ const h = {
34
+ 'Content-Type': 'application/json',
35
+ 'Accept': 'text/event-stream',
36
+ };
37
+ const auth = options.req?.headers?.authorization || options.authorization || '';
38
+ if (auth) h['Authorization'] = auth;
39
+ if (options.req?.headers?.cookie) h['Cookie'] = options.req.headers.cookie;
40
+ if (process.env.GATEWAY_KEY) h['X-CH-API-KEY'] = process.env.GATEWAY_KEY;
41
+ if (options.headers) Object.assign(h, options.headers);
42
+ return h;
43
+ }
44
+
45
+ // ── SSE 流式响应 (AI 聊天) ────────────────────────
46
+
47
+ async function streamChat(endpoint, data, options = {}) {
48
+ const { req, res, onComplete, onToolMessage } = options;
49
+ const messageCollection = options.messageCollection || [];
50
+
51
+ const url = urlFor(endpoint);
52
+ const headers = headersFor({ req });
53
+ headers['Content-Type'] = 'application/json';
54
+
55
+ // ── AbortController: 超时 + 客户端断开双重保护 ──
56
+
57
+ const abort = new AbortController();
58
+ const timeoutId = setTimeout(() => abort.abort(), defaultTimeout);
59
+
60
+ // 客户端断开(关闭页面/取消请求)→ 终止上游请求,停止消耗 token
61
+ const onClientClose = () => {
62
+ if (!abort.signal.aborted) abort.abort();
63
+ };
64
+ if (req) {
65
+ req.on('close', onClientClose);
66
+ req.on('aborted', onClientClose);
67
+ }
68
+ res.on('close', onClientClose);
69
+
70
+ let abortedByClient = false;
71
+
72
+ try {
73
+ const response = await fetch(url, {
74
+ method: 'POST',
75
+ headers,
76
+ body: JSON.stringify(data),
77
+ signal: abort.signal,
78
+ });
79
+
80
+ clearTimeout(timeoutId);
81
+
82
+ if (!response.ok) {
83
+ const text = await response.text().catch(() => '');
84
+ throw new Error(`AI 网关错误 (${response.status}): ${text.slice(0, 200)}`);
85
+ }
86
+
87
+ // 设置 SSE 响应头
88
+ res.setHeader('Content-Type', 'text/event-stream');
89
+ res.setHeader('Cache-Control', 'no-cache');
90
+ res.setHeader('Connection', 'keep-alive');
91
+
92
+ const reader = response.body.getReader();
93
+ const decoder = new TextDecoder();
94
+ let lastChunk = '';
95
+ let reachedFinal = false;
96
+ let collectingFinal = false;
97
+ let lineBuffer = ''; // SSE 行缓冲 —— 防 TCP 截断
98
+
99
+ try {
100
+ while (true) {
101
+ const { done, value } = await reader.read();
102
+ if (done) break;
103
+
104
+ const chunkStr = decoder.decode(value, { stream: true });
105
+
106
+ // 写入前检查客户端是否还在线
107
+ if (res.writableEnded || res.destroyed) break;
108
+ res.write(chunkStr);
109
+
110
+ // ── 行缓冲: 拼接不完整的 SSE 行 ──
111
+ lineBuffer += chunkStr;
112
+ const lines = lineBuffer.split('\n');
113
+ lineBuffer = lines.pop(); // 最后一段不完整,留到下次
114
+
115
+ for (const line of lines) {
116
+ if (!line.startsWith('data: ')) continue;
117
+
118
+ // 检测 final=true
119
+ if (!reachedFinal && line.includes('"final":true')) {
120
+ reachedFinal = true;
121
+ collectingFinal = true;
122
+ lastChunk = line;
123
+ }
124
+
125
+ // 工具消息收集
126
+ if (line.includes('"type":"toolMessage"') || line.includes('"type": "toolMessage"')) {
127
+ try {
128
+ const m = line.match(/data: ({.*})/);
129
+ if (m && m[1] && onToolMessage) {
130
+ const toolMsg = JSON.parse(m[1]);
131
+ messageCollection.push({
132
+ type: 'toolMessage',
133
+ result: toolMsg.data?.result,
134
+ name: toolMsg.data?.name,
135
+ content: toolMsg.data?.content,
136
+ tool_call_id: toolMsg.data?.tool_call_id,
137
+ });
138
+ onToolMessage(toolMsg);
139
+ }
140
+ } catch { /* ignore parse errors */ }
141
+ }
142
+
143
+ // 消息增量收集
144
+ if (line.includes('"event":"on_message_delta"')) {
145
+ try {
146
+ const m = line.match(/data: ({.*})/);
147
+ if (m && m[1]) {
148
+ const delta = JSON.parse(m[1]);
149
+ if (delta.data?.delta?.content) {
150
+ messageCollection.push({
151
+ type: 'messageDelta',
152
+ data: delta.data.delta.content[0],
153
+ });
154
+ }
155
+ }
156
+ } catch { /* ignore */ }
157
+ }
158
+
159
+ // 继续收集 final 之后的片段
160
+ if (collectingFinal && !line.includes('"final":true')) {
161
+ lastChunk += line + '\n';
162
+ }
163
+ }
164
+ }
165
+ } finally {
166
+ reader.releaseLock();
167
+ }
168
+
169
+ // 正常结束才触发 onComplete
170
+ if (!res.writableEnded) res.end();
171
+ if (onComplete && lastChunk) {
172
+ onComplete(lastChunk, messageCollection);
173
+ }
174
+ } catch (err) {
175
+ clearTimeout(timeoutId);
176
+
177
+ // 客户端主动断开——正常行为,不算错误
178
+ if (err.name === 'AbortError' && abort.signal.aborted && (res.writableEnded || res.destroyed)) {
179
+ abortedByClient = true;
180
+ return;
181
+ }
182
+
183
+ // 其他错误(网络/超时/网关错误)
184
+ if (!res.headersSent) {
185
+ res.status(502).json({ error: err.message });
186
+ } else if (!res.writableEnded) {
187
+ res.write(`data: ${JSON.stringify({ error: err.message })}\n\n`);
188
+ res.end();
189
+ }
190
+ throw err;
191
+ } finally {
192
+ // 清理事件监听
193
+ clearTimeout(timeoutId);
194
+ if (req) {
195
+ req.off('close', onClientClose);
196
+ req.off('aborted', onClientClose);
197
+ }
198
+ res.off('close', onClientClose);
199
+ }
200
+ }
201
+
202
+ // ── 通用非流式调用 ────────────────────────────────
203
+
204
+ async function call(method, endpoint, data = {}, options = {}) {
205
+ const url = urlFor(endpoint);
206
+ const headers = headersFor(options);
207
+ const m = method.toUpperCase();
208
+
209
+ const fetchOptions = {
210
+ method: m,
211
+ headers,
212
+ signal: AbortSignal.timeout(defaultTimeout),
213
+ };
214
+
215
+ if (m === 'GET' || m === 'DELETE') {
216
+ const qs = new URLSearchParams(data).toString();
217
+ const finalUrl = qs ? `${url}?${qs}` : url;
218
+ const response = await fetch(finalUrl, fetchOptions);
219
+ if (!response.ok) throw new Error(`AI 网关错误 (${response.status})`);
220
+ return response.json();
221
+ }
222
+
223
+ // POST/PUT: body could be JSON or FormData
224
+ if (data instanceof FormData || data.constructor?.name === 'FormData') {
225
+ delete fetchOptions.headers['Content-Type']; // let fetch set boundary
226
+ fetchOptions.body = data;
227
+ } else {
228
+ fetchOptions.body = JSON.stringify(data);
229
+ }
230
+
231
+ const response = await fetch(url, fetchOptions);
232
+ if (!response.ok) throw new Error(`AI 网关错误 (${response.status})`);
233
+ return response.json();
234
+ }
235
+
236
+ /** GET 快捷 */
237
+ async function get(endpoint, queryParams = {}, options = {}) {
238
+ return call('GET', endpoint, queryParams, options);
239
+ }
240
+
241
+ /** POST 快捷 */
242
+ async function post(endpoint, data = {}, options = {}) {
243
+ return call('POST', endpoint, data, options);
244
+ }
245
+
246
+ /** 文件上传 (FormData) */
247
+ async function upload(endpoint, formData, options = {}) {
248
+ return call('POST', endpoint, formData, options);
249
+ }
250
+
251
+ return { streamChat, call, get, post, upload };
252
+ }
253
+
254
+ module.exports = { init };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * auth 模块
3
+ *
4
+ * 通过依赖注入创建,不与任何特定数据库/ORM 耦合
5
+ *
6
+ * 用法:
7
+ * const { createAuth } = require('@hnch/core/auth');
8
+ * const auth = createAuth({
9
+ * User, // Mongoose Model (需提供 findById, findOne, create 等方法)
10
+ * Session, // Mongoose Model (需提供 findOne, create 等方法)
11
+ * logger, // winston 或 console 兼容的 logger
12
+ * jwtSecret, // process.env.JWT_SECRET
13
+ * jwtRefreshSecret, // process.env.JWT_REFRESH_SECRET
14
+ * ssoServer, // process.env.SSO_SERVER
15
+ * ssoClientId, // process.env.SSO_CLIENT_ID
16
+ * ssoClientSecret,// process.env.SSO_CLIENT_SECRET
17
+ * ssoRedirectUri, // process.env.SSO_REDIRECT_URI
18
+ * ssoInitUser, // async (user) => void —— SSO 用户初始化回调
19
+ * });
20
+ *
21
+ * app.use('/api/sso', auth.ssoRouter);
22
+ * app.use('/api/*', auth.requireAuth);
23
+ */
24
+
25
+ const { requireAuth } = require('./jwt');
26
+ const { createSSORouter } = require('./sso-callback');
27
+
28
+ function createAuth(deps) {
29
+ // 验证必填依赖
30
+ const missing = [];
31
+ if (!deps.User) missing.push('User');
32
+ if (!deps.Session) missing.push('Session');
33
+ if (!deps.logger) missing.push('logger');
34
+ if (!deps.jwtSecret) missing.push('jwtSecret');
35
+ if (!deps.ssoServer) missing.push('ssoServer');
36
+ if (missing.length) {
37
+ throw new Error(`[core/auth] 缺少必填依赖: ${missing.join(', ')}`);
38
+ }
39
+
40
+ const authMiddleware = requireAuth(deps);
41
+ const ssoRouter = createSSORouter(deps);
42
+
43
+ return {
44
+ requireAuth: authMiddleware,
45
+ ssoRouter,
46
+ };
47
+ }
48
+
49
+ module.exports = { createAuth };