@solayao/koa-server-kit 0.0.0-stage → 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/README.md +188 -2
- package/index.js +1 -0
- package/package.json +59 -4
- package/src/auth/JwtSecret.js +39 -0
- package/src/auth/PlatformAuth.js +144 -0
- package/src/auth/auth.js +60 -0
- package/src/auth/index.js +3 -0
- package/src/config.js +295 -0
- package/src/index.js +7 -0
- package/src/middleware/ErrorRoutesCatch.js +21 -0
- package/src/middleware/MiddlewareLoader.js +150 -0
- package/src/middleware/index.js +2 -0
- package/src/plugins/PluginLoader.js +130 -0
- package/src/plugins/index.js +1 -0
- package/src/routes/RouteLoader.js +401 -0
- package/src/routes/index.js +1 -0
- package/src/server/ProcessSignalHandler.js +121 -0
- package/src/server/RouteAbortHandler.js +42 -0
- package/src/server/SelfSignedCert.js +129 -0
- package/src/server/ServerLoader.js +218 -0
- package/src/server/createApiServer.js +100 -0
- package/src/server/index.js +5 -0
- package/src/swagger-definitions.js +43 -0
- package/src/tools/Common.js +91 -0
- package/src/tools/Es6Patch.js +15 -0
- package/src/tools/FetchHandler.js +147 -0
- package/src/tools/FuncHandler.js +52 -0
- package/src/tools/GetRandomValue.js +24 -0
- package/src/tools/GetWordFirstLetters.js +57 -0
- package/src/tools/IpHost.js +57 -0
- package/src/tools/LogColor.js +131 -0
- package/src/tools/StringHandler.js +37 -0
- package/src/tools/TsStringHandler.js +180 -0
- package/src/tools/UrlStringDecode.js +60 -0
- package/src/tools/index.js +11 -0
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
import { pathToFileURL } from 'url'
|
|
4
|
+
import KoaRouter from 'koa-router'
|
|
5
|
+
import { koaSwagger } from 'koa2-swagger-ui'
|
|
6
|
+
import md5 from 'md5'
|
|
7
|
+
import { AbortController } from 'node-abort-controller'
|
|
8
|
+
import swaggerJSDoc from 'swagger-jsdoc'
|
|
9
|
+
import swaggerDefinitions from '../swagger-definitions.js'
|
|
10
|
+
import { createAuth } from '../auth/auth.js'
|
|
11
|
+
import { defaultLogger } from '../tools/LogColor.js'
|
|
12
|
+
import funcHandler from '../tools/FuncHandler.js'
|
|
13
|
+
|
|
14
|
+
const getLogger = (logger = defaultLogger) => ({
|
|
15
|
+
info: logger.info ? logger.info.bind(logger) : (...args) => logger.log(...args),
|
|
16
|
+
error: logger.error ? logger.error.bind(logger) : (...args) => logger.log(...args)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
/** 平台token禁止访问的管理接口前缀, 取apiBaseUrl */
|
|
20
|
+
const normalizePrefix = (baseUrl = '') => {
|
|
21
|
+
const tempPath = `${baseUrl || ''}`.replace(/^\/+|\/+$/g, '')
|
|
22
|
+
return tempPath ? `/${tempPath}/` : ''
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** useAuth=false走/public, useAuth=true走API_base_url */
|
|
26
|
+
const buildRouteUrl = (baseUrl = '', url = '', useAuth = false) => {
|
|
27
|
+
const tempUrl = `/${useAuth ? baseUrl : '/public'}/${url}`.replace(/(\/)+/g, '/')
|
|
28
|
+
return /(\/public)+/.test(tempUrl)
|
|
29
|
+
? tempUrl.replace(/(\/public)+/g, useAuth ? '' : '/public')
|
|
30
|
+
: tempUrl
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 缓存/日志参数脱敏: 避免口令、token落到缓存或日志文件 */
|
|
34
|
+
const SENSITIVE_PARAM_KEYS = /^(password|passwd|pass|secret|token|key|authorization|platform-key|x-platform-key)$/i
|
|
35
|
+
const solSanitizeParams = (params = {}) => {
|
|
36
|
+
if (!params || typeof params !== 'object') return params
|
|
37
|
+
|
|
38
|
+
return Object.keys(params).reduce((total, key) => {
|
|
39
|
+
total[key] = SENSITIVE_PARAM_KEYS.test(key) ? '[REDACTED]' : params[key]
|
|
40
|
+
return total
|
|
41
|
+
}, {})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 解析缓存分钟数并限制上限, 防止非法输入与超大TTL */
|
|
45
|
+
const solGetCacheMinute = (value, defaultValue = 0, maxValue = 1440) => {
|
|
46
|
+
if ([null, undefined, ''].includes(value)) return defaultValue
|
|
47
|
+
|
|
48
|
+
const tempStr = `${value}`
|
|
49
|
+
if (!/^\d+(\.\d+)?$/.test(tempStr)) return defaultValue
|
|
50
|
+
|
|
51
|
+
return Math.min(parseFloat(tempStr), maxValue)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 兼容 { status, data } 与 { error, data } 两种getAuthData返回 */
|
|
55
|
+
const normalizeAuthData = (raw = {}) => {
|
|
56
|
+
if (!raw) return { status: false, error: 'no auth data', data: null }
|
|
57
|
+
|
|
58
|
+
if (typeof raw.status === 'boolean') {
|
|
59
|
+
return { status: raw.status, error: raw.error || '', data: raw.data || null }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return { status: !raw.error, error: raw.error || '', data: raw.data || null }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 请求路由基础方法封装, 缓存层通过注入实现
|
|
67
|
+
* @param {Object} options 路由声明与注入依赖
|
|
68
|
+
*/
|
|
69
|
+
const routerHandler = ({
|
|
70
|
+
cb = null,
|
|
71
|
+
useAuth = true,
|
|
72
|
+
useRequestCache = false,
|
|
73
|
+
minuteRequestCache = 0,
|
|
74
|
+
ignoreHeaderRk = false,
|
|
75
|
+
getAuthData = null,
|
|
76
|
+
cacheEnabled = false,
|
|
77
|
+
cacheGet = async () => null,
|
|
78
|
+
cacheSet = async () => {},
|
|
79
|
+
logger = defaultLogger,
|
|
80
|
+
privilegedPrefix = ''
|
|
81
|
+
} = {}) => {
|
|
82
|
+
return async (ctx, next) => {
|
|
83
|
+
const { request } = ctx
|
|
84
|
+
const { body, query, method, originalUrl } = request
|
|
85
|
+
const log = getLogger(logger)
|
|
86
|
+
|
|
87
|
+
// 每个请求一个AbortController; rk请求头存在时注册到app事件, 供/public/api/abort触发
|
|
88
|
+
const controller = new AbortController()
|
|
89
|
+
const { signal } = controller
|
|
90
|
+
|
|
91
|
+
if (!ignoreHeaderRk && request.headers.rk) {
|
|
92
|
+
ctx.app.emit('route_login', request.headers.rk, controller)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 身份只存指纹, 敏感字段脱敏, 避免token/密码落到缓存
|
|
96
|
+
const reqParams = {
|
|
97
|
+
auth: request.header.authorization ? md5(request.header.authorization) : '',
|
|
98
|
+
url: originalUrl,
|
|
99
|
+
method,
|
|
100
|
+
query: solSanitizeParams(query),
|
|
101
|
+
body: solSanitizeParams(body)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const reqKey = md5(JSON.stringify(reqParams))
|
|
105
|
+
|
|
106
|
+
// 固定格式的缓存key(不含时间戳), 同一请求读写命中同一个key
|
|
107
|
+
const cacheKeyPass = `request:${reqKey}:pass`
|
|
108
|
+
const cacheKeyFail = `request:${reqKey}:fail`
|
|
109
|
+
|
|
110
|
+
// urc可动态开关当前请求缓存
|
|
111
|
+
if ([body.urc, query.urc].some(it => it !== undefined)) {
|
|
112
|
+
useRequestCache = [1, true, '1', 'true'].includes(method === 'POST' ? body.urc : query.urc)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const successCacheMinute = solGetCacheMinute(body.successCacheMinute || query.successCacheMinute, minuteRequestCache || 60)
|
|
116
|
+
const failCacheMinute = solGetCacheMinute(body.failCacheMinute || query.failCacheMinute, 2)
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
// 1. 鉴权: getAuthData由宿主提供, 这里只判断状态和平台token权限
|
|
120
|
+
const authData = getAuthData ? normalizeAuthData(await getAuthData(ctx)) : { status: true, error: '', data: null }
|
|
121
|
+
|
|
122
|
+
if (useAuth) {
|
|
123
|
+
if (!authData.status) {
|
|
124
|
+
ctx.throw(401)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 平台token仅供服务间调用, 不能用于apiBaseUrl下的管理接口
|
|
128
|
+
if (authData.data && authData.data.isPlatform && privilegedPrefix && originalUrl.startsWith(privilegedPrefix)) {
|
|
129
|
+
ctx.throw(403, '平台token无权访问该管理接口')
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// 2. 读缓存: 一次读取pass/fail两个key, 由注入的cacheGet(keys)完成
|
|
134
|
+
if (cacheEnabled && useRequestCache) {
|
|
135
|
+
let cachedObj = {}
|
|
136
|
+
|
|
137
|
+
// 缓存异常或内容损坏时降级为正常业务处理, 不影响主链路
|
|
138
|
+
try {
|
|
139
|
+
const cachedValues = await cacheGet([cacheKeyPass, cacheKeyFail])
|
|
140
|
+
const cachedValue = Array.isArray(cachedValues)
|
|
141
|
+
? (cachedValues[0] != null ? cachedValues[0] : cachedValues[1])
|
|
142
|
+
: cachedValues
|
|
143
|
+
|
|
144
|
+
if (cachedValue != null && cachedValue !== '') {
|
|
145
|
+
cachedObj = typeof cachedValue === 'string' ? JSON.parse(cachedValue) : cachedValue
|
|
146
|
+
}
|
|
147
|
+
} catch (cacheErr) {
|
|
148
|
+
log.error(`[routeCache] get error: ${cacheErr.message}`)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (cachedObj.code == 200) {
|
|
152
|
+
ctx.body = {
|
|
153
|
+
code: 200,
|
|
154
|
+
error: '',
|
|
155
|
+
result: cachedObj.result,
|
|
156
|
+
cache: reqKey
|
|
157
|
+
}
|
|
158
|
+
return true
|
|
159
|
+
} else if (cachedObj.code == 500) {
|
|
160
|
+
ctx.throw(500, cachedObj.error)
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// 3. 执行业务handler: funcHandler保留原始Error, 支持AbortSignal竞争
|
|
165
|
+
const result = await Promise.resolve(
|
|
166
|
+
funcHandler(ctx, authData.data, cb, signal)
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
// 4. 资源型结果直接返回buffer, 不走统一{code,error,result}包装
|
|
170
|
+
if (result && result.isBuffer && result.buffer) {
|
|
171
|
+
ctx.body = result.buffer
|
|
172
|
+
|
|
173
|
+
if (result.isImage) {
|
|
174
|
+
ctx.set('Content-Disposition', 'inline')
|
|
175
|
+
ctx.set('Content-Type', result.type || 'image/png')
|
|
176
|
+
ctx.set('Cache-Control', 'public, max-age=3600')
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 路由handler是终点, 不调用next(): 避免后续中间件覆盖ctx.body
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// 5. 写成功缓存
|
|
184
|
+
if (cacheEnabled && useRequestCache) {
|
|
185
|
+
try {
|
|
186
|
+
await cacheSet(
|
|
187
|
+
cacheKeyPass,
|
|
188
|
+
1000 * 60 * successCacheMinute,
|
|
189
|
+
JSON.stringify({ code: 200, request: reqParams, result })
|
|
190
|
+
)
|
|
191
|
+
} catch (cacheErr) {
|
|
192
|
+
log.error(`[routeCache] set error: ${cacheErr.message}`)
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
ctx.body = {
|
|
197
|
+
code: 200,
|
|
198
|
+
error: '',
|
|
199
|
+
result
|
|
200
|
+
}
|
|
201
|
+
} catch (err) {
|
|
202
|
+
const errMsg = err.toString()
|
|
203
|
+
|
|
204
|
+
// 被客户端中断的请求与4xx客户端错误都不写失败缓存, 避免401/403被缓存成500
|
|
205
|
+
const ignoreError = errMsg.includes('by AbortController.abort()') || (err.status >= 400 && err.status < 500)
|
|
206
|
+
|
|
207
|
+
if (cacheEnabled && useRequestCache && !ignoreError) {
|
|
208
|
+
try {
|
|
209
|
+
await cacheSet(
|
|
210
|
+
cacheKeyFail,
|
|
211
|
+
1000 * 60 * failCacheMinute,
|
|
212
|
+
JSON.stringify({ code: 500, request: reqParams, error: errMsg })
|
|
213
|
+
)
|
|
214
|
+
} catch (cacheErr) {
|
|
215
|
+
log.error(`[routeCache] set fail cache error: ${cacheErr.message}`)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 直接抛出原始错误, 保留401/403/400等状态码语义
|
|
220
|
+
throw err
|
|
221
|
+
} finally {
|
|
222
|
+
// 移除路径中断注册, 避免内存泄漏
|
|
223
|
+
if (!ignoreHeaderRk && request.headers.rk) {
|
|
224
|
+
ctx.app.emit('route_logout', request.headers.rk, controller)
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** 把路由声明中的swaggerDoc转换成dynamic swagger path */
|
|
231
|
+
const buildSwaggerPath = (fullUrl, method, useAuth, swaggerDoc = {}) => {
|
|
232
|
+
const tempUrl = /:[a-zA-Z\d]+(\/)?/.test(fullUrl)
|
|
233
|
+
? fullUrl.replace(/:([a-zA-Z\d]+)(\/)?/g, '/{$1}').replace(/(\/)+/g, '/')
|
|
234
|
+
: fullUrl
|
|
235
|
+
|
|
236
|
+
const { summary, description, tags, body, query, header, pathParams } = swaggerDoc
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
path: tempUrl,
|
|
240
|
+
method: method.toLowerCase(),
|
|
241
|
+
doc: {
|
|
242
|
+
security: useAuth ? [{ api_key: [] }] : undefined,
|
|
243
|
+
tags,
|
|
244
|
+
summary,
|
|
245
|
+
description,
|
|
246
|
+
consumes: ['application/json', 'application/xml'],
|
|
247
|
+
produces: ['application/json', 'application/xml'],
|
|
248
|
+
parameters: [
|
|
249
|
+
Object.keys(body || {}).length ? {
|
|
250
|
+
name: 'body',
|
|
251
|
+
in: 'body',
|
|
252
|
+
required: true,
|
|
253
|
+
schema: body
|
|
254
|
+
} : undefined,
|
|
255
|
+
...Object.keys(query || {}).map(key => ({ ...query[key], name: key, in: 'query' })),
|
|
256
|
+
...Object.keys(header || {}).map(key => ({ ...header[key], name: key, in: 'header' })),
|
|
257
|
+
...Object.keys(pathParams || {}).map(key => ({ ...pathParams[key], name: key, in: 'path' })),
|
|
258
|
+
swaggerDoc.ignoreHeaderRk ? undefined : {
|
|
259
|
+
name: 'rk',
|
|
260
|
+
type: 'string',
|
|
261
|
+
description: '终止请求关键字,用于/public/api/abort方法作为参数trk传入',
|
|
262
|
+
in: 'header'
|
|
263
|
+
}
|
|
264
|
+
].filter(item => !!item),
|
|
265
|
+
responses: {
|
|
266
|
+
200: {
|
|
267
|
+
description: '成功',
|
|
268
|
+
schema: { $ref: '#/definitions/callbackresult' }
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 动态扫描routesDir并注册路由; 鉴权与Swagger在包内固化, 缓存仍通过adapters注入
|
|
277
|
+
* 约定: 路由文件默认导出对象或对象数组
|
|
278
|
+
*/
|
|
279
|
+
export const createRouteLoader = ({ app, options = {}, adapters = {} } = {}) => {
|
|
280
|
+
const config = {
|
|
281
|
+
routesDir: options.routesDir,
|
|
282
|
+
packageMeta: options.packageMeta || {},
|
|
283
|
+
apiBaseUrl: options.apiBaseUrl || '',
|
|
284
|
+
useRouteCache: !!options.useRouteCache,
|
|
285
|
+
logger: options.logger || defaultLogger,
|
|
286
|
+
getAuthData: createAuth().getAuthData,
|
|
287
|
+
cacheGet: adapters.cacheGet || (async () => null),
|
|
288
|
+
cacheSet: adapters.cacheSet || (async () => {})
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const log = getLogger(config.logger)
|
|
292
|
+
const privilegedPrefix = normalizePrefix(config.apiBaseUrl)
|
|
293
|
+
|
|
294
|
+
const register = async () => {
|
|
295
|
+
if (!config.routesDir || !fs.existsSync(config.routesDir)) {
|
|
296
|
+
throw new Error(`[koa-server-kit] routesDir不存在: ${config.routesDir}`)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const files = fs.readdirSync(config.routesDir).filter(file => {
|
|
300
|
+
return !fs.statSync(path.join(config.routesDir, file)).isDirectory()
|
|
301
|
+
})
|
|
302
|
+
|
|
303
|
+
const swaggerPaths = {}
|
|
304
|
+
|
|
305
|
+
// 所有路由文件注册到同一个Router, 避免跨文件同路径不同方法被误拦405
|
|
306
|
+
const mainRouter = new KoaRouter()
|
|
307
|
+
|
|
308
|
+
for (const name of files) {
|
|
309
|
+
const filePath = path.join(config.routesDir, name)
|
|
310
|
+
const module = await import(pathToFileURL(filePath).href)
|
|
311
|
+
const exported = Array.isArray(module.default) ? module.default : [module.default]
|
|
312
|
+
|
|
313
|
+
for (const item of exported) {
|
|
314
|
+
if (!item || !item.url || (!item.cb && !item.handler)) continue
|
|
315
|
+
|
|
316
|
+
const method = (item.method || 'get').toLowerCase()
|
|
317
|
+
const fullUrl = buildRouteUrl(config.apiBaseUrl, item.url, !!item.useAuth)
|
|
318
|
+
|
|
319
|
+
if (typeof mainRouter[method] !== 'function') continue
|
|
320
|
+
|
|
321
|
+
// 注册路由handler
|
|
322
|
+
mainRouter[method](fullUrl, routerHandler({
|
|
323
|
+
cb: item.cb || item.handler,
|
|
324
|
+
useAuth: !!item.useAuth,
|
|
325
|
+
useRequestCache: !!item.useRequestCache,
|
|
326
|
+
minuteRequestCache: item.minuteRequestCache || 0,
|
|
327
|
+
ignoreHeaderRk: !!item.ignoreHeaderRk,
|
|
328
|
+
getAuthData: config.getAuthData,
|
|
329
|
+
cacheEnabled: config.useRouteCache,
|
|
330
|
+
cacheGet: config.cacheGet,
|
|
331
|
+
cacheSet: config.cacheSet,
|
|
332
|
+
logger: config.logger,
|
|
333
|
+
privilegedPrefix
|
|
334
|
+
}))
|
|
335
|
+
|
|
336
|
+
// 生成动态Swagger路径
|
|
337
|
+
if (item.swaggerDoc) {
|
|
338
|
+
const swaggerItem = buildSwaggerPath(
|
|
339
|
+
fullUrl,
|
|
340
|
+
method,
|
|
341
|
+
!!item.useAuth,
|
|
342
|
+
{ ...item.swaggerDoc, ignoreHeaderRk: item.ignoreHeaderRk }
|
|
343
|
+
)
|
|
344
|
+
swaggerPaths[swaggerItem.path] = {
|
|
345
|
+
...(swaggerPaths[swaggerItem.path] || {}),
|
|
346
|
+
[swaggerItem.method]: swaggerItem.doc
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
app.use(mainRouter.routes(), mainRouter.allowedMethods())
|
|
354
|
+
|
|
355
|
+
// SwaggerRoutes: 原始项目用/swagger.json输出swagger-jsdoc结果, /swagger展示UI
|
|
356
|
+
if (Object.keys(swaggerPaths).length) {
|
|
357
|
+
const swaggerRouter = new KoaRouter()
|
|
358
|
+
|
|
359
|
+
swaggerRouter.get('/swagger.json', ctx => {
|
|
360
|
+
ctx.set('Content-Type', 'application/json')
|
|
361
|
+
|
|
362
|
+
ctx.body = swaggerJSDoc({
|
|
363
|
+
apis: [],
|
|
364
|
+
swaggerDefinition: {
|
|
365
|
+
info: {
|
|
366
|
+
title: config.packageMeta.title || `API FOR ${config.packageMeta.name || 'koa-server-kit'}`,
|
|
367
|
+
version: config.packageMeta.version || '1.0.0',
|
|
368
|
+
description: config.packageMeta.description || ''
|
|
369
|
+
},
|
|
370
|
+
// Referer兼容docker转发, 为空时回退到请求host
|
|
371
|
+
host: (ctx.header.referer || '').replace(/\/swagger(\/)?/, '').replace(/http(s)?:\/\//, '') || ctx.host,
|
|
372
|
+
basePath: '/',
|
|
373
|
+
schemes: ['http', 'https'],
|
|
374
|
+
securityDefinitions: {
|
|
375
|
+
api_key: {
|
|
376
|
+
type: 'apiKey',
|
|
377
|
+
name: 'Authorization',
|
|
378
|
+
in: 'header'
|
|
379
|
+
}
|
|
380
|
+
},
|
|
381
|
+
paths: swaggerPaths,
|
|
382
|
+
definitions: swaggerDefinitions
|
|
383
|
+
}
|
|
384
|
+
})
|
|
385
|
+
})
|
|
386
|
+
|
|
387
|
+
app.use(swaggerRouter.routes(), swaggerRouter.allowedMethods())
|
|
388
|
+
|
|
389
|
+
app.use(koaSwagger({
|
|
390
|
+
routePrefix: '/swagger',
|
|
391
|
+
swaggerOptions: { url: './swagger.json' },
|
|
392
|
+
showRequestHeaders: true
|
|
393
|
+
}))
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
log.info(`[routeLoader] registered ${files.length} route files`)
|
|
397
|
+
return mainRouter
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return { register }
|
|
401
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './RouteLoader.js'
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { defaultLogger, solLogShutdown } from '../tools/LogColor.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 注册进程异常与退出信号:
|
|
5
|
+
* 二次信号强退 -> 关闭服务 -> 断开socket -> cleanup -> flush日志 -> 兜底退出
|
|
6
|
+
* cleanup由宿主提供, 包本身不绑定mysql/redis/webdav
|
|
7
|
+
*/
|
|
8
|
+
export const createProcessSignalHandler = ({
|
|
9
|
+
servers = [],
|
|
10
|
+
sockets = [],
|
|
11
|
+
cleanup = [],
|
|
12
|
+
logger = defaultLogger
|
|
13
|
+
} = {}) => {
|
|
14
|
+
// handled保证收尾只执行一次; force为true时二次信号直接强退
|
|
15
|
+
let handled = false
|
|
16
|
+
const log = logger.info ? logger.info.bind(logger) : (...args) => logger.log(...args)
|
|
17
|
+
const logError = logger.error ? logger.error.bind(logger) : log
|
|
18
|
+
|
|
19
|
+
/** 关闭单个server: close()等待现有请求结束, closeAllConnections()断开keep-alive */
|
|
20
|
+
const closeServer = (server) => new Promise(resolve => {
|
|
21
|
+
if (!server || !server.listening) return resolve()
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
server.close(() => resolve())
|
|
25
|
+
|
|
26
|
+
// Node 18.2+才有该方法, 低版本靠5秒兜底定时器强制退出
|
|
27
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
28
|
+
server.closeAllConnections()
|
|
29
|
+
}
|
|
30
|
+
} catch (err) {
|
|
31
|
+
logError(`[process] close server error: ${err.message}`)
|
|
32
|
+
resolve()
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 统一收尾入口
|
|
38
|
+
* @param {String} reason 触发原因(SIGINT/SIGTERM/uncaughtException等)
|
|
39
|
+
* @param {Object} options.force 收尾中再次收到信号时为true, 直接exit(1)
|
|
40
|
+
*/
|
|
41
|
+
const closeAll = async (reason = '', { force = false } = {}) => {
|
|
42
|
+
if (handled) {
|
|
43
|
+
// 收尾过程中再次收到退出信号, 说明常规清理卡住, 直接强退
|
|
44
|
+
if (force) process.exit(1)
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
handled = true
|
|
49
|
+
log(`[process] closing, reason=${reason || 'manual'}`)
|
|
50
|
+
|
|
51
|
+
// 5秒兜底退出, unref避免正常退出时被定时器拖住
|
|
52
|
+
const fallbackTimer = setTimeout(() => process.exit(0), 1000 * 5)
|
|
53
|
+
fallbackTimer.unref()
|
|
54
|
+
|
|
55
|
+
// 1. 开发链路(npm run dev/start)同步结束上层gulp/nodemon, 直接node/pm2不会命中
|
|
56
|
+
if (['dev', 'start'].includes(process.env.npm_lifecycle_event) && process.ppid) {
|
|
57
|
+
try {
|
|
58
|
+
process.kill(process.ppid)
|
|
59
|
+
} catch (err) {
|
|
60
|
+
// 上层进程可能已自行退出, 忽略
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 2. 关闭HTTP/HTTPS/Proxy三个监听
|
|
65
|
+
for (const server of servers) {
|
|
66
|
+
await closeServer(server)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 3. 销毁proxy连接与宿主注入的外部keep-alive连接
|
|
70
|
+
sockets.forEach(socket => socket.destroy())
|
|
71
|
+
sockets.length = 0
|
|
72
|
+
|
|
73
|
+
// 4. 执行宿主资源清理(mysql/redis/webdav等)
|
|
74
|
+
const cleanupJobs = cleanup.map(item => {
|
|
75
|
+
try {
|
|
76
|
+
return Promise.resolve(item())
|
|
77
|
+
} catch (err) {
|
|
78
|
+
logError(`[process] cleanup error: ${err.message}`)
|
|
79
|
+
return Promise.resolve()
|
|
80
|
+
}
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
// 5. 日志落盘后退出, 失败也以退出码0结束
|
|
84
|
+
try {
|
|
85
|
+
await Promise.all([...cleanupJobs, solLogShutdown()])
|
|
86
|
+
} catch (err) {
|
|
87
|
+
logError(`[process] shutdown error: ${err.message}`)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
clearTimeout(fallbackTimer)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const register = () => {
|
|
94
|
+
// Linux不能监听SIGKILL, 这里注册SIGINT/SIGTERM/SIGQUIT
|
|
95
|
+
;['SIGINT', 'SIGTERM', 'SIGQUIT'].forEach(signal => {
|
|
96
|
+
process.once(signal, () => {
|
|
97
|
+
// 第二次Ctrl+C进入closeAll时会因force=true直接exit(1)
|
|
98
|
+
closeAll(signal, { force: true }).finally(() => process.exit(0))
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
// 未捕获异常后进程状态不确定, 记录后走统一收尾并以1退出
|
|
103
|
+
process.on('uncaughtException', async err => {
|
|
104
|
+
logError(`[uncaughtException] ${err.stack || err.message}`)
|
|
105
|
+
await closeAll('uncaughtException')
|
|
106
|
+
process.exit(1)
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
process.on('unhandledRejection', async reason => {
|
|
110
|
+
logError(`[unhandledRejection] ${reason && reason.stack ? reason.stack : reason}`)
|
|
111
|
+
await closeAll('unhandledRejection')
|
|
112
|
+
process.exit(1)
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
process.once('exit', code => {
|
|
116
|
+
log(`[process] exited, code=${code}`)
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return { register, closeAll, closeServer }
|
|
121
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { defaultLogger } from '../tools/LogColor.js'
|
|
2
|
+
|
|
3
|
+
/** 基于app事件维护 rk -> AbortController, 供 /public/api/abort 中断在途请求 */
|
|
4
|
+
export const createRouteAbortHandler = ({ app, logger = defaultLogger } = {}) => {
|
|
5
|
+
const controllers = new Map()
|
|
6
|
+
const log = logger.info ? logger.info.bind(logger) : (...args) => logger.log(...args)
|
|
7
|
+
|
|
8
|
+
// 路由开始: 注册rk对应的controller
|
|
9
|
+
const login = (rk = '', controller = null) => {
|
|
10
|
+
if (!rk || !controller) return
|
|
11
|
+
controllers.set(rk, controller)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 客户端请求中断: 只abort不删除, 允许后续再次abort同一key
|
|
15
|
+
const abort = (rk = '') => {
|
|
16
|
+
const controller = controllers.get(rk)
|
|
17
|
+
if (!controller) return
|
|
18
|
+
controller.abort()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 路由结束: 删除映射, 避免内存泄漏
|
|
22
|
+
const logout = (rk = '') => {
|
|
23
|
+
if (!rk) return
|
|
24
|
+
controllers.delete(rk)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
app.on('route_login', login)
|
|
28
|
+
app.on('route_abort', abort)
|
|
29
|
+
app.on('route_logout', logout)
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
login,
|
|
33
|
+
abort,
|
|
34
|
+
logout,
|
|
35
|
+
getController: (rk = '') => controllers.get(rk) || null,
|
|
36
|
+
clear () {
|
|
37
|
+
controllers.forEach(controller => controller.abort())
|
|
38
|
+
controllers.clear()
|
|
39
|
+
log('[routeAbort] cleared')
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import path from 'path'
|
|
3
|
+
import selfsigned from 'selfsigned'
|
|
4
|
+
import { defaultLogger } from '../tools/LogColor.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 生成两级证书(根CA + 站点证书)并缓存到本地
|
|
8
|
+
* 每次启动都重新生成 RSA-2048 耗时明显, 这里按首个IP复用缓存
|
|
9
|
+
* @param {Array<String>} ips 当前服务对外IP列表, 第1个作为缓存标识与SAN IP
|
|
10
|
+
* @returns {{ private: String, cert: String }} pems
|
|
11
|
+
*/
|
|
12
|
+
const solGeneratePems = ({ ips = [], packageMeta = {}, caAttrs = [], siteAttrs = [] }) => {
|
|
13
|
+
// 根CA只用于签发站点证书, Chrome对keyCertSign有要求, 因此CA与站点分开生成
|
|
14
|
+
const rootCA = selfsigned.generate([
|
|
15
|
+
{ name: 'commonName', value: 'Development Certificate Authority' },
|
|
16
|
+
{ name: 'countryName', value: 'CN' },
|
|
17
|
+
{ name: 'organizationName', value: 'Dizzy L' },
|
|
18
|
+
...caAttrs
|
|
19
|
+
], {
|
|
20
|
+
keySize: 2048,
|
|
21
|
+
algorithm: 'sha256',
|
|
22
|
+
extensions: [
|
|
23
|
+
{ name: 'basicConstraints', cA: true }
|
|
24
|
+
]
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
const siteName = packageMeta.name || packageMeta.title || 'koa-server-kit'
|
|
28
|
+
const siteVersion = packageMeta.version || '1.0.0'
|
|
29
|
+
|
|
30
|
+
const pems = selfsigned.generate([
|
|
31
|
+
{ name: 'commonName', value: `${siteName} V${siteVersion}` },
|
|
32
|
+
{ name: 'countryName', value: 'CN' },
|
|
33
|
+
{ name: 'organizationName', value: 'Dizzy L' },
|
|
34
|
+
...siteAttrs
|
|
35
|
+
], {
|
|
36
|
+
keySize: 2048,
|
|
37
|
+
ca: rootCA,
|
|
38
|
+
algorithm: 'sha256',
|
|
39
|
+
extensions: [
|
|
40
|
+
{ name: 'basicConstraints', cA: false },
|
|
41
|
+
{
|
|
42
|
+
name: 'keyUsage',
|
|
43
|
+
// 必须为false, 否则Chrome不认可该站点证书
|
|
44
|
+
keyCertSign: false,
|
|
45
|
+
digitalSignature: true,
|
|
46
|
+
nonRepudiation: true,
|
|
47
|
+
keyEncipherment: true,
|
|
48
|
+
dataEncipherment: true
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: 'extKeyUsage',
|
|
52
|
+
serverAuth: true,
|
|
53
|
+
clientAuth: true,
|
|
54
|
+
codeSigning: true,
|
|
55
|
+
timeStamping: true
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: 'subjectAltName',
|
|
59
|
+
altNames: [
|
|
60
|
+
{ type: 2, value: 'localhost' }, // type 2 = DNS
|
|
61
|
+
{ type: 2, value: 'localhost.localdomain' },
|
|
62
|
+
{ type: 7, ip: '127.0.0.1' }, // type 7 = IP
|
|
63
|
+
...ips.filter(Boolean).map(ip => ({ type: 7, ip }))
|
|
64
|
+
]
|
|
65
|
+
}
|
|
66
|
+
]
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
return pems
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 读取本地缓存证书, 仅当首个IP一致时复用, 避免IP变化后证书不可用 */
|
|
73
|
+
const solGetCachedPems = (cacheFilePath = '', ips = []) => {
|
|
74
|
+
try {
|
|
75
|
+
if (!fs.existsSync(cacheFilePath)) return null
|
|
76
|
+
|
|
77
|
+
const cached = JSON.parse(fs.readFileSync(cacheFilePath, 'utf8'))
|
|
78
|
+
if (cached && cached.ip === (ips[0] || '') && cached.private && cached.cert) {
|
|
79
|
+
return { private: cached.private, cert: cached.cert }
|
|
80
|
+
}
|
|
81
|
+
} catch (err) {
|
|
82
|
+
// 缓存损坏时直接重新生成, 不让证书问题阻断启动
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 创建自签证书提供者, 返回的函数可直接传给 createServerLoader 的 certProvider
|
|
90
|
+
* @param {Object} options
|
|
91
|
+
* @param {String} options.cacheFilePath 证书缓存文件, 默认 ./temp/.selfsigned-cert.json
|
|
92
|
+
* @param {Array<String>} options.ips 默认IP列表, 运行时可由createServerLoader再传入
|
|
93
|
+
* @param {Object} options.packageMeta 写入证书CN的元信息
|
|
94
|
+
*/
|
|
95
|
+
export const createSelfSignedCert = ({
|
|
96
|
+
cacheFilePath = './temp/.selfsigned-cert.json',
|
|
97
|
+
ips = [],
|
|
98
|
+
packageMeta = {},
|
|
99
|
+
caAttrs = [],
|
|
100
|
+
siteAttrs = [],
|
|
101
|
+
logger = defaultLogger
|
|
102
|
+
} = {}) => {
|
|
103
|
+
const fullCachePath = path.resolve(cacheFilePath)
|
|
104
|
+
|
|
105
|
+
return async (runtimeIps = []) => {
|
|
106
|
+
const finalIps = [...new Set([...(runtimeIps.length ? runtimeIps : ips).filter(Boolean)])]
|
|
107
|
+
const cached = solGetCachedPems(fullCachePath, finalIps)
|
|
108
|
+
|
|
109
|
+
if (cached) {
|
|
110
|
+
return cached
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const pems = solGeneratePems({ ips: finalIps, packageMeta, caAttrs, siteAttrs })
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
fs.mkdirSync(path.dirname(fullCachePath), { recursive: true })
|
|
117
|
+
fs.writeFileSync(fullCachePath, JSON.stringify({
|
|
118
|
+
ip: finalIps[0] || '',
|
|
119
|
+
private: pems.private,
|
|
120
|
+
cert: pems.cert
|
|
121
|
+
}), { mode: 0o600 })
|
|
122
|
+
} catch (err) {
|
|
123
|
+
const log = logger.error ? logger.error.bind(logger) : (...args) => logger.log(...args)
|
|
124
|
+
log(`[cert] 自签证书缓存写入失败: ${err.message}`)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return { private: pems.private, cert: pems.cert }
|
|
128
|
+
}
|
|
129
|
+
}
|