@solayao/koa-server-kit 0.0.0-stage → 0.1.1

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,415 @@
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 { createBuiltinRoutes } from './builtin-routes.js'
12
+ import { defaultLogger } from '../tools/LogColor.js'
13
+ import funcHandler from '../tools/FuncHandler.js'
14
+
15
+ const getLogger = (logger = defaultLogger) => ({
16
+ info: logger.info ? logger.info.bind(logger) : (...args) => logger.log(...args),
17
+ error: logger.error ? logger.error.bind(logger) : (...args) => logger.log(...args)
18
+ })
19
+
20
+ /** 平台token禁止访问的管理接口前缀, 取apiBaseUrl */
21
+ const normalizePrefix = (baseUrl = '') => {
22
+ const tempPath = `${baseUrl || ''}`.replace(/^\/+|\/+$/g, '')
23
+ return tempPath ? `/${tempPath}/` : ''
24
+ }
25
+
26
+ /** useAuth=false走/public, useAuth=true走API_base_url */
27
+ const buildRouteUrl = (baseUrl = '', url = '', useAuth = false) => {
28
+ const tempUrl = `/${useAuth ? baseUrl : '/public'}/${url}`.replace(/(\/)+/g, '/')
29
+ return /(\/public)+/.test(tempUrl)
30
+ ? tempUrl.replace(/(\/public)+/g, useAuth ? '' : '/public')
31
+ : tempUrl
32
+ }
33
+
34
+ /** 缓存/日志参数脱敏: 避免口令、token落到缓存或日志文件 */
35
+ const SENSITIVE_PARAM_KEYS = /^(password|passwd|pass|secret|token|key|authorization|platform-key|x-platform-key)$/i
36
+ const solSanitizeParams = (params = {}) => {
37
+ if (!params || typeof params !== 'object') return params
38
+
39
+ return Object.keys(params).reduce((total, key) => {
40
+ total[key] = SENSITIVE_PARAM_KEYS.test(key) ? '[REDACTED]' : params[key]
41
+ return total
42
+ }, {})
43
+ }
44
+
45
+ /** 解析缓存分钟数并限制上限, 防止非法输入与超大TTL */
46
+ const solGetCacheMinute = (value, defaultValue = 0, maxValue = 1440) => {
47
+ if ([null, undefined, ''].includes(value)) return defaultValue
48
+
49
+ const tempStr = `${value}`
50
+ if (!/^\d+(\.\d+)?$/.test(tempStr)) return defaultValue
51
+
52
+ return Math.min(parseFloat(tempStr), maxValue)
53
+ }
54
+
55
+ /** 兼容 { status, data } 与 { error, data } 两种getAuthData返回 */
56
+ const normalizeAuthData = (raw = {}) => {
57
+ if (!raw) return { status: false, error: 'no auth data', data: null }
58
+
59
+ if (typeof raw.status === 'boolean') {
60
+ return { status: raw.status, error: raw.error || '', data: raw.data || null }
61
+ }
62
+
63
+ return { status: !raw.error, error: raw.error || '', data: raw.data || null }
64
+ }
65
+
66
+ /**
67
+ * 请求路由基础方法封装, 缓存层通过注入实现
68
+ * @param {Object} options 路由声明与注入依赖
69
+ */
70
+ const routerHandler = ({
71
+ cb = null,
72
+ useAuth = true,
73
+ useRequestCache = false,
74
+ minuteRequestCache = 0,
75
+ ignoreHeaderRk = false,
76
+ getAuthData = null,
77
+ cacheEnabled = false,
78
+ cacheGet = async () => null,
79
+ cacheSet = async () => {},
80
+ logger = defaultLogger,
81
+ privilegedPrefix = ''
82
+ } = {}) => {
83
+ return async (ctx, next) => {
84
+ const { request } = ctx
85
+ const { body, query, method, originalUrl } = request
86
+ const log = getLogger(logger)
87
+
88
+ // 每个请求一个AbortController; rk请求头存在时注册到app事件, 供/public/api/abort触发
89
+ const controller = new AbortController()
90
+ const { signal } = controller
91
+
92
+ if (!ignoreHeaderRk && request.headers.rk) {
93
+ ctx.app.emit('route_login', request.headers.rk, controller)
94
+ }
95
+
96
+ // 身份只存指纹, 敏感字段脱敏, 避免token/密码落到缓存
97
+ const reqParams = {
98
+ auth: request.header.authorization ? md5(request.header.authorization) : '',
99
+ url: originalUrl,
100
+ method,
101
+ query: solSanitizeParams(query),
102
+ body: solSanitizeParams(body)
103
+ }
104
+
105
+ const reqKey = md5(JSON.stringify(reqParams))
106
+
107
+ // 固定格式的缓存key(不含时间戳), 同一请求读写命中同一个key
108
+ const cacheKeyPass = `request:${reqKey}:pass`
109
+ const cacheKeyFail = `request:${reqKey}:fail`
110
+
111
+ // urc可动态开关当前请求缓存
112
+ if ([body.urc, query.urc].some(it => it !== undefined)) {
113
+ useRequestCache = [1, true, '1', 'true'].includes(method === 'POST' ? body.urc : query.urc)
114
+ }
115
+
116
+ const successCacheMinute = solGetCacheMinute(body.successCacheMinute || query.successCacheMinute, minuteRequestCache || 60)
117
+ const failCacheMinute = solGetCacheMinute(body.failCacheMinute || query.failCacheMinute, 2)
118
+
119
+ try {
120
+ // 1. 鉴权: getAuthData由宿主提供, 这里只判断状态和平台token权限
121
+ const authData = getAuthData ? normalizeAuthData(await getAuthData(ctx)) : { status: true, error: '', data: null }
122
+
123
+ if (useAuth) {
124
+ if (!authData.status) {
125
+ ctx.throw(401)
126
+ }
127
+
128
+ // 平台token仅供服务间调用, 不能用于apiBaseUrl下的管理接口
129
+ if (authData.data && authData.data.isPlatform && privilegedPrefix && originalUrl.startsWith(privilegedPrefix)) {
130
+ ctx.throw(403, '平台token无权访问该管理接口')
131
+ }
132
+ }
133
+
134
+ // 2. 读缓存: 一次读取pass/fail两个key, 由注入的cacheGet(keys)完成
135
+ if (cacheEnabled && useRequestCache) {
136
+ let cachedObj = {}
137
+
138
+ // 缓存异常或内容损坏时降级为正常业务处理, 不影响主链路
139
+ try {
140
+ const cachedValues = await cacheGet([cacheKeyPass, cacheKeyFail])
141
+ const cachedValue = Array.isArray(cachedValues)
142
+ ? (cachedValues[0] != null ? cachedValues[0] : cachedValues[1])
143
+ : cachedValues
144
+
145
+ if (cachedValue != null && cachedValue !== '') {
146
+ cachedObj = typeof cachedValue === 'string' ? JSON.parse(cachedValue) : cachedValue
147
+ }
148
+ } catch (cacheErr) {
149
+ log.error(`[routeCache] get error: ${cacheErr.message}`)
150
+ }
151
+
152
+ if (cachedObj.code == 200) {
153
+ ctx.body = {
154
+ code: 200,
155
+ error: '',
156
+ result: cachedObj.result,
157
+ cache: reqKey
158
+ }
159
+ return true
160
+ } else if (cachedObj.code == 500) {
161
+ ctx.throw(500, cachedObj.error)
162
+ }
163
+ }
164
+
165
+ // 3. 执行业务handler: funcHandler保留原始Error, 支持AbortSignal竞争
166
+ const result = await Promise.resolve(
167
+ funcHandler(ctx, authData.data, cb, signal)
168
+ )
169
+
170
+ // 4. 资源型结果直接返回buffer, 不走统一{code,error,result}包装
171
+ if (result && result.isBuffer && result.buffer) {
172
+ ctx.body = result.buffer
173
+
174
+ if (result.isImage) {
175
+ ctx.set('Content-Disposition', 'inline')
176
+ ctx.set('Content-Type', result.type || 'image/png')
177
+ ctx.set('Cache-Control', 'public, max-age=3600')
178
+ }
179
+
180
+ // 路由handler是终点, 不调用next(): 避免后续中间件覆盖ctx.body
181
+ return
182
+ }
183
+
184
+ // 5. 写成功缓存
185
+ if (cacheEnabled && useRequestCache) {
186
+ try {
187
+ await cacheSet(
188
+ cacheKeyPass,
189
+ 1000 * 60 * successCacheMinute,
190
+ JSON.stringify({ code: 200, request: reqParams, result })
191
+ )
192
+ } catch (cacheErr) {
193
+ log.error(`[routeCache] set error: ${cacheErr.message}`)
194
+ }
195
+ }
196
+
197
+ ctx.body = {
198
+ code: 200,
199
+ error: '',
200
+ result
201
+ }
202
+ } catch (err) {
203
+ const errMsg = err.toString()
204
+
205
+ // 被客户端中断的请求与4xx客户端错误都不写失败缓存, 避免401/403被缓存成500
206
+ const ignoreError = errMsg.includes('by AbortController.abort()') || (err.status >= 400 && err.status < 500)
207
+
208
+ if (cacheEnabled && useRequestCache && !ignoreError) {
209
+ try {
210
+ await cacheSet(
211
+ cacheKeyFail,
212
+ 1000 * 60 * failCacheMinute,
213
+ JSON.stringify({ code: 500, request: reqParams, error: errMsg })
214
+ )
215
+ } catch (cacheErr) {
216
+ log.error(`[routeCache] set fail cache error: ${cacheErr.message}`)
217
+ }
218
+ }
219
+
220
+ // 直接抛出原始错误, 保留401/403/400等状态码语义
221
+ throw err
222
+ } finally {
223
+ // 移除路径中断注册, 避免内存泄漏
224
+ if (!ignoreHeaderRk && request.headers.rk) {
225
+ ctx.app.emit('route_logout', request.headers.rk, controller)
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ /** 把路由声明中的swaggerDoc转换成dynamic swagger path */
232
+ const buildSwaggerPath = (fullUrl, method, useAuth, swaggerDoc = {}) => {
233
+ const tempUrl = /:[a-zA-Z\d]+(\/)?/.test(fullUrl)
234
+ ? fullUrl.replace(/:([a-zA-Z\d]+)(\/)?/g, '/{$1}').replace(/(\/)+/g, '/')
235
+ : fullUrl
236
+
237
+ const { summary, description, tags, body, query, header, pathParams } = swaggerDoc
238
+
239
+ return {
240
+ path: tempUrl,
241
+ method: method.toLowerCase(),
242
+ doc: {
243
+ security: useAuth ? [{ api_key: [] }] : undefined,
244
+ tags,
245
+ summary,
246
+ description,
247
+ consumes: ['application/json', 'application/xml'],
248
+ produces: ['application/json', 'application/xml'],
249
+ parameters: [
250
+ Object.keys(body || {}).length ? {
251
+ name: 'body',
252
+ in: 'body',
253
+ required: true,
254
+ schema: body
255
+ } : undefined,
256
+ ...Object.keys(query || {}).map(key => ({ ...query[key], name: key, in: 'query' })),
257
+ ...Object.keys(header || {}).map(key => ({ ...header[key], name: key, in: 'header' })),
258
+ ...Object.keys(pathParams || {}).map(key => ({ ...pathParams[key], name: key, in: 'path' })),
259
+ swaggerDoc.ignoreHeaderRk ? undefined : {
260
+ name: 'rk',
261
+ type: 'string',
262
+ description: '终止请求关键字,用于/public/api/abort方法作为参数trk传入',
263
+ in: 'header'
264
+ }
265
+ ].filter(item => !!item),
266
+ responses: {
267
+ 200: {
268
+ description: '成功',
269
+ schema: { $ref: '#/definitions/callbackresult' }
270
+ }
271
+ }
272
+ }
273
+ }
274
+ }
275
+
276
+ /**
277
+ * 动态扫描routesDir并注册路由; 鉴权与Swagger在包内固化, 缓存仍通过adapters注入
278
+ * 约定: 路由文件默认导出对象或对象数组
279
+ */
280
+ export const createRouteLoader = ({ app, options = {}, adapters = {} } = {}) => {
281
+ const config = {
282
+ routesDir: options.routesDir,
283
+ packageMeta: options.packageMeta || {},
284
+ apiBaseUrl: options.apiBaseUrl || '',
285
+ useRouteCache: !!options.useRouteCache,
286
+ logger: options.logger || defaultLogger,
287
+ isDev: !!options.isDev,
288
+ internalTokenPath: options.internalTokenPath || '/public/internal/token',
289
+ getAuthData: createAuth().getAuthData,
290
+ cacheGet: adapters.cacheGet || (async () => null),
291
+ cacheSet: adapters.cacheSet || (async () => {})
292
+ }
293
+
294
+ const log = getLogger(config.logger)
295
+ const privilegedPrefix = normalizePrefix(config.apiBaseUrl)
296
+
297
+ const register = async () => {
298
+ if (!config.routesDir || !fs.existsSync(config.routesDir)) {
299
+ throw new Error(`[koa-server-kit] routesDir不存在: ${config.routesDir}`)
300
+ }
301
+
302
+ const files = fs.readdirSync(config.routesDir).filter(file => {
303
+ return !fs.statSync(path.join(config.routesDir, file)).isDirectory()
304
+ })
305
+
306
+ const swaggerPaths = {}
307
+
308
+ // 所有路由注册到同一个Router, 避免跨文件同路径不同方法被误拦405
309
+ const mainRouter = new KoaRouter()
310
+ const registeredKeys = new Set()
311
+
312
+ const addRoute = (item) => {
313
+ if (!item || !item.url || (!item.cb && !item.handler)) return
314
+
315
+ const method = (item.method || 'get').toLowerCase()
316
+ const fullUrl = buildRouteUrl(config.apiBaseUrl, item.url, !!item.useAuth)
317
+ const routeKey = `${method}:${fullUrl}`
318
+
319
+ // 宿主显式声明的同路径同方法优先, 内置路由不重复注册
320
+ if (typeof mainRouter[method] !== 'function' || registeredKeys.has(routeKey)) return
321
+ registeredKeys.add(routeKey)
322
+
323
+ mainRouter[method](fullUrl, routerHandler({
324
+ cb: item.cb || item.handler,
325
+ useAuth: !!item.useAuth,
326
+ useRequestCache: !!item.useRequestCache,
327
+ minuteRequestCache: item.minuteRequestCache || 0,
328
+ ignoreHeaderRk: !!item.ignoreHeaderRk,
329
+ getAuthData: config.getAuthData,
330
+ cacheEnabled: config.useRouteCache,
331
+ cacheGet: config.cacheGet,
332
+ cacheSet: config.cacheSet,
333
+ logger: config.logger,
334
+ privilegedPrefix
335
+ }))
336
+
337
+ // 生成动态Swagger路径
338
+ if (item.swaggerDoc) {
339
+ const swaggerItem = buildSwaggerPath(
340
+ fullUrl,
341
+ method,
342
+ !!item.useAuth,
343
+ { ...item.swaggerDoc, ignoreHeaderRk: item.ignoreHeaderRk }
344
+ )
345
+ swaggerPaths[swaggerItem.path] = {
346
+ ...(swaggerPaths[swaggerItem.path] || {}),
347
+ [swaggerItem.method]: swaggerItem.doc
348
+ }
349
+ }
350
+ }
351
+
352
+ for (const name of files) {
353
+ const filePath = path.join(config.routesDir, name)
354
+ const module = await import(pathToFileURL(filePath).href)
355
+ const exported = Array.isArray(module.default) ? module.default : [module.default]
356
+
357
+ for (const item of exported) addRoute(item)
358
+ }
359
+
360
+ // 包内通用路由: 内部token、测试、中断与开发环境模拟登录
361
+ const builtinRoutes = createBuiltinRoutes({
362
+ isDev: config.isDev,
363
+ internalTokenPath: config.internalTokenPath
364
+ })
365
+ for (const item of builtinRoutes) addRoute(item)
366
+
367
+ app.use(mainRouter.routes(), mainRouter.allowedMethods())
368
+
369
+ // SwaggerRoutes: 原始项目用/swagger.json输出swagger-jsdoc结果, /swagger展示UI
370
+ if (Object.keys(swaggerPaths).length) {
371
+ const swaggerRouter = new KoaRouter()
372
+
373
+ swaggerRouter.get('/swagger.json', ctx => {
374
+ ctx.set('Content-Type', 'application/json')
375
+
376
+ ctx.body = swaggerJSDoc({
377
+ apis: [],
378
+ swaggerDefinition: {
379
+ info: {
380
+ title: config.packageMeta.title || `API FOR ${config.packageMeta.name || 'koa-server-kit'}`,
381
+ version: config.packageMeta.version || '1.0.0',
382
+ description: config.packageMeta.description || ''
383
+ },
384
+ // Referer兼容docker转发, 为空时回退到请求host
385
+ host: (ctx.header.referer || '').replace(/\/swagger(\/)?/, '').replace(/http(s)?:\/\//, '') || ctx.host,
386
+ basePath: '/',
387
+ schemes: ['http', 'https'],
388
+ securityDefinitions: {
389
+ api_key: {
390
+ type: 'apiKey',
391
+ name: 'Authorization',
392
+ in: 'header'
393
+ }
394
+ },
395
+ paths: swaggerPaths,
396
+ definitions: swaggerDefinitions
397
+ }
398
+ })
399
+ })
400
+
401
+ app.use(swaggerRouter.routes(), swaggerRouter.allowedMethods())
402
+
403
+ app.use(koaSwagger({
404
+ routePrefix: '/swagger',
405
+ swaggerOptions: { url: './swagger.json' },
406
+ showRequestHeaders: true
407
+ }))
408
+ }
409
+
410
+ log.info(`[routeLoader] registered ${files.length} route files + ${builtinRoutes.length} builtin routes`)
411
+ return mainRouter
412
+ }
413
+
414
+ return { register }
415
+ }
@@ -0,0 +1,173 @@
1
+ import crypto from 'crypto'
2
+ import { createAuth } from '../auth/auth.js'
3
+
4
+ /** 恒定时间字符串比较(先做sha256归一化长度, 防时序攻击), 用于密钥核验 */
5
+ const solSafeEqual = (a = '', b = '') => {
6
+ const tempHashA = crypto.createHash('sha256').update(`${a}`).digest()
7
+ const tempHashB = crypto.createHash('sha256').update(`${b}`).digest()
8
+
9
+ return crypto.timingSafeEqual(tempHashA, tempHashB)
10
+ }
11
+
12
+ /** 归一化IPv4映射与IPv6环回地址(::ffff:127.0.0.1 / ::1 -> 127.0.0.1) */
13
+ const solNormalizeIp = (ip = '') => {
14
+ const tempIp = `${ip}`.replace(/^::ffff:/i, '')
15
+ return tempIp === '::1' ? '127.0.0.1' : tempIp
16
+ }
17
+
18
+ /**
19
+ * 获取可信客户端IP: 直接连接的socket必须属于信任列表(本机TCP代理), 并取XFF最后一段(由代理写入);
20
+ * HTTPS内部端口流量加密、代理无法注入XFF, 因此该接口在HTTPS直连上直接拒绝
21
+ */
22
+ const solGetTrustedClientIp = (ctx) => {
23
+ const tempSocketIp = solNormalizeIp((ctx.request.socket && ctx.request.socket.remoteAddress) || '')
24
+ const tempTrustedIps = (ctx.$ips || []).map(solNormalizeIp)
25
+
26
+ if (!tempSocketIp || !tempTrustedIps.includes(tempSocketIp)) return null
27
+
28
+ const tempForwarded = `${ctx.request.headers['x-forwarded-for'] || ''}`
29
+ .split(',')
30
+ .map(it => solNormalizeIp(it.trim()))
31
+ .filter(Boolean)
32
+
33
+ return tempForwarded.length ? tempForwarded[tempForwarded.length - 1] : null
34
+ }
35
+
36
+ /** 是否内网来源IP(私网段/环回), APP_Internal_Allow_Ips中配置的IP额外放行 */
37
+ const solIsIntranetIp = (ip = '') => {
38
+ const tempIp = solNormalizeIp(ip)
39
+ const tempIntranetRegex = /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|::1|f[cd][0-9a-f]{2}:|fe80:)/i
40
+ const tempExtraIps = (process.env.APP_Internal_Allow_Ips || '').split(/\s+/).filter(Boolean)
41
+
42
+ return tempIntranetRegex.test(tempIp) || tempExtraIps.includes(tempIp)
43
+ }
44
+
45
+ /**
46
+ * 包内通用路由: 内部token换取、可用性测试、请求中断与开发环境模拟登录。
47
+ * 业务项目仍可在自己的routesDir覆盖同路径路由。
48
+ * @param {Object} options
49
+ * @param {Boolean} options.isDev 开发环境才注册模拟登录
50
+ * @param {String} options.internalTokenPath 内部token接口完整路径, 默认/public/internal/token
51
+ */
52
+ export const createBuiltinRoutes = ({
53
+ isDev = false,
54
+ internalTokenPath = '/public/internal/token'
55
+ } = {}) => {
56
+ const auth = createAuth()
57
+ const tokenUrl = `${internalTokenPath || '/public/internal/token'}`.replace(/^\/public/, '') || '/internal/token'
58
+ const expiresIn = '10m'
59
+
60
+ const internalTokenRoute = {
61
+ url: tokenUrl,
62
+ method: 'post',
63
+ useAuth: false,
64
+ useRequestCache: false,
65
+ cb: async (ctx) => {
66
+ // 1. 仅接受本机代理注入的XFF末段, 拒绝客户端伪造头与无法确认来源的HTTPS直连
67
+ const clientIp = solGetTrustedClientIp(ctx)
68
+ if (!clientIp) {
69
+ ctx.throw(403, '无法确认可信来源IP, 请通过本机HTTP代理访问')
70
+ }
71
+ if (!solIsIntranetIp(clientIp)) {
72
+ ctx.throw(403, `非内网来源禁止访问: ${clientIp}`)
73
+ }
74
+
75
+ // 2. 密钥核验(恒定时间比较), 密钥仅通过环境变量注入
76
+ const configuredKey = process.env.APP_Platform_Auth_Pass_Key || ''
77
+ if (!configuredKey) {
78
+ ctx.throw(500, '平台服务鉴权口令未配置, 请设置环境变量APP_Platform_Auth_Pass_Key')
79
+ }
80
+
81
+ const requestKey = ctx.get('X-Platform-Key') || (ctx.get('authorization') || '').replace(/^Bearer\s+/i, '')
82
+ if (!requestKey || !solSafeEqual(requestKey, configuredKey)) {
83
+ ctx.throw(401, '平台服务鉴权口令错误')
84
+ }
85
+
86
+ // 3. 颁发短时效低权限token(自带Bearer前缀)
87
+ return { token: auth.getPlatformToken(expiresIn), expiresIn }
88
+ },
89
+ swaggerDoc: {
90
+ summary: '服务间平台token获取',
91
+ description: '内网服务携带平台密钥(X-Platform-Key头)换取短时效JWT token',
92
+ tags: ['内部'],
93
+ body: {},
94
+ query: {},
95
+ header: {
96
+ 'X-Platform-Key': {
97
+ type: 'string',
98
+ description: '平台服务鉴权口令, 与服务端环境变量APP_Platform_Auth_Pass_Key一致',
99
+ required: true
100
+ }
101
+ }
102
+ }
103
+ }
104
+
105
+ const mockTestRoute = {
106
+ url: '/mock/test',
107
+ method: 'get',
108
+ useAuth: false,
109
+ useRequestCache: false,
110
+ cb: async () => {
111
+ // 模拟长时间操作请求, 供连通性检查与请求中断验证使用
112
+ await new Promise(resolve => setTimeout(resolve, 1000 * 60 * 5))
113
+ return 'Hello world!'
114
+ },
115
+ swaggerDoc: {
116
+ summary: '测试接口',
117
+ description: '',
118
+ tags: ['测试'],
119
+ body: {},
120
+ query: {},
121
+ header: {}
122
+ }
123
+ }
124
+
125
+ const abortRoute = {
126
+ url: '/api/abort',
127
+ method: 'get',
128
+ useAuth: false,
129
+ useRequestCache: false,
130
+ cb: (ctx) => {
131
+ ctx.app.emit('route_abort', ctx.request.headers.trk || '/')
132
+ return '取消的请求key:' + (ctx.request.headers.trk || '/')
133
+ },
134
+ swaggerDoc: {
135
+ summary: '暂停请求',
136
+ description: '',
137
+ tags: ['测试'],
138
+ body: {},
139
+ query: {},
140
+ header: {
141
+ trk: {
142
+ type: 'string',
143
+ description: '对应上待终止请求的接口header内设置的rk',
144
+ required: true
145
+ }
146
+ }
147
+ },
148
+ ignoreHeaderRk: true
149
+ }
150
+
151
+ const mockLoginRoute = {
152
+ url: '/mock/login',
153
+ method: 'post',
154
+ useAuth: false,
155
+ useRequestCache: false,
156
+ cb: () => auth.getMockUserToken({
157
+ isMock: true,
158
+ id: 'mock-id',
159
+ username: 'mock-username',
160
+ password: 'mock-password'
161
+ }, '1d'),
162
+ swaggerDoc: {
163
+ summary: '模拟登录',
164
+ description: '',
165
+ tags: ['测试'],
166
+ body: { $ref: '#/definitions/loginparam' },
167
+ query: {},
168
+ header: {}
169
+ }
170
+ }
171
+
172
+ return [internalTokenRoute, mockTestRoute, abortRoute, ...(isDev ? [mockLoginRoute] : [])]
173
+ }
@@ -0,0 +1,2 @@
1
+ export * from './RouteLoader.js'
2
+ export * from './builtin-routes.js'