create-skweb 1.1.5 → 2.0.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/src/cli.ts CHANGED
@@ -20,6 +20,7 @@ async function main() {
20
20
  .argument('[name]', 'Project name')
21
21
  .option('--template <type>', 'Template type: ts, mjs, cjs', 'ts')
22
22
  .option('--dest <path>', 'Destination directory', '.')
23
+ .option('--auth <type>', 'Auth provider: static (HS256) or jwks (Keycloak/Auth0)', 'static')
23
24
  .option('--skip-install', 'Skip dependency installation')
24
25
  .option('--skip-git', 'Skip git initialization')
25
26
  .action(async (name, options) => {
@@ -28,6 +29,7 @@ async function main() {
28
29
  // 只要没有传 --no-interactive 且任何一个关键参数缺失,就走交互式 prompt
29
30
  const providedTemplate = process.argv.includes('--template')
30
31
  const providedDest = process.argv.includes('--dest')
32
+ const providedAuth = process.argv.includes('--auth')
31
33
  const providedSkipInstall = process.argv.includes('--skip-install')
32
34
  const providedSkipGit = process.argv.includes('--skip-git')
33
35
 
@@ -35,6 +37,7 @@ async function main() {
35
37
  const needsPrompt = !name
36
38
  || !providedTemplate
37
39
  || !providedDest
40
+ || !providedAuth
38
41
  || !providedSkipInstall
39
42
  || !providedSkipGit
40
43
 
@@ -67,6 +70,18 @@ async function main() {
67
70
  default: 'ts'
68
71
  })
69
72
  }
73
+ if (!providedAuth) {
74
+ questions.push({
75
+ type: 'list',
76
+ name: 'auth',
77
+ message: 'Select auth provider:',
78
+ choices: [
79
+ { name: 'Static (HS256 shared secret)', value: 'static' },
80
+ { name: 'JWKS (Keycloak / Auth0 / OIDC)', value: 'jwks' }
81
+ ],
82
+ default: 'static'
83
+ })
84
+ }
70
85
  if (!providedDest) {
71
86
  questions.push({
72
87
  type: 'input',
@@ -96,21 +111,23 @@ async function main() {
96
111
 
97
112
  if (answers.name) name = answers.name
98
113
  if (answers.template) options.template = answers.template
114
+ if (answers.auth) options.auth = answers.auth
99
115
  if (answers.dest) options.dest = answers.dest
100
116
  if (typeof answers.install === 'boolean') options.skipInstall = !answers.install
101
117
  if (typeof answers.git === 'boolean') options.skipGit = !answers.git
102
118
  }
103
-
119
+
104
120
  const spinner = ora('Creating project...').start()
105
-
121
+
106
122
  try {
107
123
  await createProject({
108
124
  name,
109
125
  template: options.template as 'ts' | 'mjs' | 'cjs',
110
- dest: options.dest
126
+ dest: options.dest,
127
+ auth: (options.auth || 'static') as 'static' | 'jwks'
111
128
  })
112
129
  spinner.succeed('Project files created')
113
-
130
+
114
131
  if (!options.skipInstall) {
115
132
  spinner.text = 'Installing dependencies...'
116
133
  spinner.start()
@@ -124,11 +141,11 @@ async function main() {
124
141
  await initGit(options.dest, name)
125
142
  spinner.succeed('Git repository initialized')
126
143
  }
127
-
144
+
128
145
  spinner.stop()
129
-
146
+
130
147
  printSuccess(name, options.dest)
131
-
148
+
132
149
  } catch (error) {
133
150
  spinner.fail('Failed to create project')
134
151
  console.error(error)
package/src/index.ts CHANGED
@@ -10,10 +10,13 @@ export interface CreateOptions {
10
10
  description?: string
11
11
  template: 'ts' | 'mjs' | 'cjs'
12
12
  dest: string
13
+ /** Auth provider: 'static' (HS256, default) or 'jwks' (Keycloak/Auth0) */
14
+ auth?: 'static' | 'jwks'
13
15
  }
14
16
 
15
17
  export async function createProject(options: CreateOptions): Promise<void> {
16
18
  const { name, description = 'A SKWeb project', template, dest } = options
19
+ const auth = options.auth ?? 'static'
17
20
 
18
21
  const templateDir = path.join(__dirname, '..', 'templates', template)
19
22
  const baseDir = path.resolve(dest)
@@ -44,6 +47,7 @@ export async function createProject(options: CreateOptions): Promise<void> {
44
47
  content = content
45
48
  .replace(/\{\{name\}\}/g, name)
46
49
  .replace(/\{\{description\}\}/g, description)
50
+ .replace(/\{\{auth\}\}/g, auth)
47
51
 
48
52
  const destPath = path.join(targetDir, fileName)
49
53
  await fs.writeFile(destPath, content)
@@ -96,20 +100,23 @@ export function printSuccess(name: string, dest: string): void {
96
100
  接下来可以执行:
97
101
 
98
102
  cd ${name}
99
-
103
+
104
+ # 复制环境变量模板并按需修改
105
+ cp .env.example .env
106
+
100
107
  # 开发模式运行
101
108
  npm run start:dev
102
-
109
+
103
110
  # 生产模式运行 (需要先构建)
104
111
  npm run build
105
112
  npm run start
106
-
113
+
107
114
  # 查看日志
108
115
  npm run logs
109
-
116
+
110
117
  # 停止服务
111
118
  npm run stop
112
-
119
+
113
120
  # 重启服务
114
121
  npm run restart
115
122
 
@@ -118,6 +125,7 @@ export function printSuccess(name: string, dest: string): void {
118
125
  ✅ @dotenvx/dotenvx 环境变量管理
119
126
  ✅ PM2 进程管理
120
127
  ✅ SKWeb Express 集成
128
+ ✅ Keycloak/JWKS 鉴权 (可选)
121
129
  ✅ ESLint 代码检查
122
130
  ✅ Mocha 测试框架
123
131
  `)
@@ -0,0 +1,73 @@
1
+ # ============================================
2
+ # SKWeb Environment Variables Template
3
+ # ============================================
4
+ # Copy this file to .env and fill in your values:
5
+ # cp .env.example .env
6
+ #
7
+ # Variables with default values can be omitted.
8
+ # Variables marked [REQUIRED] must be set in production.
9
+
10
+ # ---------- Node Environment ----------
11
+ # Development | Production | Test
12
+ NODE_ENV=development
13
+
14
+ # ---------- Server ----------
15
+ PORT=3000
16
+ HOST=0.0.0.0
17
+
18
+ # ---------- Database (MySQL / MariaDB) ----------
19
+ DB_HOST=127.0.0.1
20
+ DB_PORT=3306
21
+ DB_USER=root
22
+ DB_PASS=
23
+ DB_NAME={{name}}
24
+ DB_DIALECT=mysql
25
+ DB_CHARSET=utf8mb4
26
+ DEBUG_DB=false
27
+
28
+ # ---------- Redis ----------
29
+ REDIS_HOST=127.0.0.1
30
+ REDIS_PORT=6379
31
+ REDIS_PASSWORD=
32
+ REDIS_DB=0
33
+
34
+ # ---------- Swagger / OpenAPI ----------
35
+ # Mounts Swagger UI at /api-docs and exposes raw spec at /api-docs.json.
36
+ # Only enabled when NODE_ENV is 'development' or 'test'.
37
+ # Set SWAGGER_ENABLED=false to force-disable in dev/test as well.
38
+ # (Production is always disabled to avoid exposing internal API details.)
39
+ SWAGGER_ENABLED=true
40
+
41
+ # ---------- Auth Provider ----------
42
+ # 'static' (default): use a shared secret (HS256)
43
+ # 'jwks': verify via JWKS endpoint (Keycloak / Auth0 / generic OIDC)
44
+ AUTH_PROVIDER={{auth}}
45
+
46
+ # ---------- JWT (static mode) ----------
47
+ # [REQUIRED in production] Use a strong random string, e.g. `openssl rand -hex 32`
48
+ JWT_SECRET=please-change-this-in-production
49
+ JWT_EXPIRES_IN=7d
50
+
51
+ # ---------- JWT (jwks mode, OIDC compatible) ----------
52
+ # Works with any OIDC-compliant IdP. Common issuer formats:
53
+ # Keycloak: https://kc.example.com/realms/myrealm
54
+ # Auth0: https://your-tenant.auth0.com/
55
+ # Okta: https://your-domain.okta.com/oauth2/default
56
+ # Authing: https://your-app.authing.cn/oauth2/default
57
+ # Keycloak Realm: https://kc.example.com/auth/realms/myrealm
58
+ # `audience` is the client id of this API in the IdP (recommended).
59
+ # JWKS URI is auto-derived as ${OIDC_ISSUER}/.well-known/jwks.json
60
+ # unless OIDC_JWKS_URI is set explicitly.
61
+ OIDC_ISSUER=
62
+ OIDC_AUDIENCE=
63
+ OIDC_JWKS_URI=
64
+
65
+ # ---------- Logging ----------
66
+ # error | warn | info | http | verbose | debug | silly
67
+ LOG_LEVEL=info
68
+ LOG_DIR=./logs
69
+ LOG_CONSOLE=true
70
+
71
+ # ---------- CORS ----------
72
+ # Comma-separated origins, or * for all
73
+ CORS_ORIGIN=*
@@ -23,7 +23,7 @@
23
23
  "@dotenvx/dotenvx": "^1.71.0",
24
24
  "http-errors": "^2.0.0",
25
25
  "skweb-express": "^1.0.0",
26
- "skweb-express-jwt": "^1.0.0",
26
+ "skweb-express-jwt": "^1.2.0",
27
27
  "skweb-express-logger": "^1.0.0",
28
28
  "skweb-sequelize": "^1.0.0",
29
29
  "skweb-redis": "^1.0.0",
@@ -32,7 +32,9 @@
32
32
  "skweb-plugin": "^1.0.0",
33
33
  "skweb-util": "^1.0.0",
34
34
  "winston": "^3.17.0",
35
- "sequelize": "^6.37.7"
35
+ "sequelize": "^6.37.7",
36
+ "swagger-jsdoc": "^6.2.8",
37
+ "swagger-ui-express": "^5.0.1"
36
38
  },
37
39
  "devDependencies": {
38
40
  "chai": "^6.2.1",
@@ -3,9 +3,55 @@ require('dotenv/config')
3
3
  const path = require('path')
4
4
  const express = require('skweb-express')
5
5
  const expressLogger = require('skweb-express-logger').default || require('skweb-express-logger')
6
+ const swaggerUi = require('swagger-ui-express')
6
7
  const { WebFramework } = require('skweb-framework')
7
8
  const { logger } = require('./utils/logger.js')
8
9
  const { checkRequiredEnv } = require('./utils/config.js')
10
+ const { buildOpenApiSpec } = require('./swagger.js')
11
+
12
+ /**
13
+ * 构建 JWT 配置,支持两种模式:
14
+ * - 'static' (默认):使用共享密钥(HS256/HS384/HS512),适用于自签 token
15
+ * - 'jwks':通过 JWKS 端点动态获取公钥(RS256 等),适用于 Keycloak/Auth0 等 IdP
16
+ */
17
+ function buildJwtOptions() {
18
+ const provider = process.env.AUTH_PROVIDER || 'static'
19
+
20
+ if (provider === 'jwks') {
21
+ const issuer = process.env.OIDC_ISSUER
22
+ const jwksUri = process.env.OIDC_JWKS_URI
23
+ const audience = process.env.OIDC_AUDIENCE
24
+ if (!issuer && !jwksUri) {
25
+ throw new Error('AUTH_PROVIDER=jwks requires OIDC_ISSUER or OIDC_JWKS_URI')
26
+ }
27
+ return {
28
+ provider: 'jwks',
29
+ algorithms: ['RS256'],
30
+ jwks: { jwksUri, issuer, audience },
31
+ verify: { issuer, audience },
32
+ requestProperty: 'resolvedToken'
33
+ }
34
+ }
35
+
36
+ return {
37
+ provider: 'static',
38
+ secret: process.env.JWT_SECRET || 'please-change-this-in-production',
39
+ algorithms: ['HS256'],
40
+ sign: { expiresIn: process.env.JWT_EXPIRES_IN || '7d' },
41
+ requestProperty: 'resolvedToken'
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Swagger UI 仅在 NODE_ENV 为 development / test,且 SWAGGER_ENABLED !== 'false' 时启用。
47
+ * 生产环境(production / unset)默认禁用,避免暴露内部 API 细节。
48
+ */
49
+ function shouldEnableSwagger() {
50
+ const env = (process.env.NODE_ENV || '').toLowerCase()
51
+ if (env !== 'development' && env !== 'test') return false
52
+ if ((process.env.SWAGGER_ENABLED || '').toLowerCase() === 'false') return false
53
+ return true
54
+ }
9
55
 
10
56
  async function bootstrap() {
11
57
  logger.info('[app] Initializing web process...')
@@ -50,17 +96,33 @@ async function bootstrap() {
50
96
  app.setOkCode(0)
51
97
  app.setOkMessage('success')
52
98
 
53
- app.setJWT('default', {
54
- secret: process.env.JWT_SECRET || 'please-change-this-in-production',
55
- algorithms: ['HS256'],
56
- sign: { expiresIn: process.env.JWT_EXPIRES_IN || '7d' },
57
- requestProperty: 'resolvedToken'
58
- })
99
+ // JWT 配置(按 AUTH_PROVIDER 选择 static 或 jwks 模式)
100
+ const jwtOptions = buildJwtOptions()
101
+ app.setJWT('default', jwtOptions)
59
102
  app.setJwtHintHeader('JwtHint')
60
103
 
104
+ if (jwtOptions.provider === 'jwks') {
105
+ logger.info(`[app] JWT auth provider: jwks (issuer: ${jwtOptions.jwks.issuer || jwtOptions.jwks.jwksUri})`)
106
+ } else {
107
+ logger.info('[app] JWT auth provider: static (HS256)')
108
+ }
109
+
61
110
  app.use(expressLogger())
62
111
  app.use(express.static(path.join(__dirname, '..', 'public')))
63
112
 
113
+ // 仅在 dev / test 环境挂载 Swagger UI(默认关闭,需显式 SWAGGER_ENABLED=true)
114
+ if (shouldEnableSwagger()) {
115
+ const openapiSpec = buildOpenApiSpec()
116
+ app.get('/api-docs.json', (_req, res) => res.json(openapiSpec))
117
+ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openapiSpec, {
118
+ customSiteTitle: `${process.env.APP_NAME || 'SKWeb'} API Docs`,
119
+ swaggerOptions: { persistAuthorization: true }
120
+ }))
121
+ logger.info(`[app] Swagger UI mounted at http://localhost:${process.env.PORT || 3000}/api-docs (env: ${process.env.NODE_ENV})`)
122
+ } else {
123
+ logger.info(`[app] Swagger UI disabled (env: ${process.env.NODE_ENV || 'unset'})`)
124
+ }
125
+
64
126
  await framework.loadControllers(path.join(__dirname, './controllers'))
65
127
  await framework.loadPluginControllers()
66
128
 
@@ -88,4 +150,4 @@ if (require.main === module) {
88
150
  })
89
151
  }
90
152
 
91
- module.exports = { bootstrap }
153
+ module.exports = { bootstrap }
@@ -1,3 +1,49 @@
1
+ /**
2
+ * @swagger
3
+ * /:
4
+ * get:
5
+ * summary: 欢迎页
6
+ * description: 返回项目基本信息。
7
+ * tags: [Hello]
8
+ * responses:
9
+ * 200:
10
+ * description: OK
11
+ * content:
12
+ * application/json:
13
+ * schema:
14
+ * type: object
15
+ * properties:
16
+ * message: { type: string, example: 'Welcome to SKWeb!' }
17
+ * version: { type: string, example: '1.0.0' }
18
+ * timestamp: { type: string, format: date-time }
19
+ * /health:
20
+ * get:
21
+ * summary: 健康检查
22
+ * tags: [Hello]
23
+ * responses:
24
+ * 200:
25
+ * description: OK
26
+ * content:
27
+ * application/json:
28
+ * schema:
29
+ * type: object
30
+ * properties:
31
+ * status: { type: string, example: 'ok' }
32
+ * timestamp: { type: string, format: date-time }
33
+ * /echo:
34
+ * post:
35
+ * summary: 回显请求体
36
+ * tags: [Hello]
37
+ * requestBody:
38
+ * required: true
39
+ * content:
40
+ * application/json:
41
+ * schema:
42
+ * type: object
43
+ * responses:
44
+ * 200:
45
+ * description: OK
46
+ */
1
47
  module.exports = [
2
48
  {
3
49
  method: 'get',
@@ -0,0 +1,52 @@
1
+ 'use strict'
2
+
3
+ const path = require('path')
4
+ const swaggerJSDoc = require('swagger-jsdoc')
5
+
6
+ /**
7
+ * 构建 OpenAPI 3.0 规范对象。
8
+ *
9
+ * 控制器中应使用 @swagger JSDoc 注释描述端点,例如:
10
+ *
11
+ * /**
12
+ * * @swagger
13
+ * * /api/users:
14
+ * * get:
15
+ * * summary: 获取用户列表
16
+ * * tags: [Users]
17
+ * * responses:
18
+ * * 200:
19
+ * * description: OK
20
+ * *\/
21
+ */
22
+ function buildOpenApiSpec() {
23
+ return swaggerJSDoc({
24
+ definition: {
25
+ openapi: '3.0.3',
26
+ info: {
27
+ title: process.env.APP_NAME || 'SKWeb API',
28
+ version: process.env.API_VERSION || '1.0.0',
29
+ description: process.env.APP_DESCRIPTION || 'SKWeb project API documentation',
30
+ contact: { name: 'API Support' }
31
+ },
32
+ servers: [
33
+ { url: `http://localhost:${process.env.PORT || 3000}`, description: 'Local development' }
34
+ ],
35
+ components: {
36
+ securitySchemes: {
37
+ bearerAuth: {
38
+ type: 'http',
39
+ scheme: 'bearer',
40
+ bearerFormat: 'JWT',
41
+ description: 'Paste a JWT token here (only needed when AUTH_PROVIDER=static)'
42
+ }
43
+ }
44
+ }
45
+ },
46
+ apis: [
47
+ path.join(__dirname, 'controllers', '*.js')
48
+ ]
49
+ })
50
+ }
51
+
52
+ module.exports = { buildOpenApiSpec }
@@ -0,0 +1,73 @@
1
+ # ============================================
2
+ # SKWeb Environment Variables Template
3
+ # ============================================
4
+ # Copy this file to .env and fill in your values:
5
+ # cp .env.example .env
6
+ #
7
+ # Variables with default values can be omitted.
8
+ # Variables marked [REQUIRED] must be set in production.
9
+
10
+ # ---------- Node Environment ----------
11
+ # Development | Production | Test
12
+ NODE_ENV=development
13
+
14
+ # ---------- Server ----------
15
+ PORT=3000
16
+ HOST=0.0.0.0
17
+
18
+ # ---------- Database (MySQL / MariaDB) ----------
19
+ DB_HOST=127.0.0.1
20
+ DB_PORT=3306
21
+ DB_USER=root
22
+ DB_PASS=
23
+ DB_NAME={{name}}
24
+ DB_DIALECT=mysql
25
+ DB_CHARSET=utf8mb4
26
+ DEBUG_DB=false
27
+
28
+ # ---------- Redis ----------
29
+ REDIS_HOST=127.0.0.1
30
+ REDIS_PORT=6379
31
+ REDIS_PASSWORD=
32
+ REDIS_DB=0
33
+
34
+ # ---------- Swagger / OpenAPI ----------
35
+ # Mounts Swagger UI at /api-docs and exposes raw spec at /api-docs.json.
36
+ # Only enabled when NODE_ENV is 'development' or 'test'.
37
+ # Set SWAGGER_ENABLED=false to force-disable in dev/test as well.
38
+ # (Production is always disabled to avoid exposing internal API details.)
39
+ SWAGGER_ENABLED=true
40
+
41
+ # ---------- Auth Provider ----------
42
+ # 'static' (default): use a shared secret (HS256)
43
+ # 'jwks': verify via JWKS endpoint (Keycloak / Auth0 / generic OIDC)
44
+ AUTH_PROVIDER={{auth}}
45
+
46
+ # ---------- JWT (static mode) ----------
47
+ # [REQUIRED in production] Use a strong random string, e.g. `openssl rand -hex 32`
48
+ JWT_SECRET=please-change-this-in-production
49
+ JWT_EXPIRES_IN=7d
50
+
51
+ # ---------- JWT (jwks mode, OIDC compatible) ----------
52
+ # Works with any OIDC-compliant IdP. Common issuer formats:
53
+ # Keycloak: https://kc.example.com/realms/myrealm
54
+ # Auth0: https://your-tenant.auth0.com/
55
+ # Okta: https://your-domain.okta.com/oauth2/default
56
+ # Authing: https://your-app.authing.cn/oauth2/default
57
+ # Keycloak Realm: https://kc.example.com/auth/realms/myrealm
58
+ # `audience` is the client id of this API in the IdP (recommended).
59
+ # JWKS URI is auto-derived as ${OIDC_ISSUER}/.well-known/jwks.json
60
+ # unless OIDC_JWKS_URI is set explicitly.
61
+ OIDC_ISSUER=
62
+ OIDC_AUDIENCE=
63
+ OIDC_JWKS_URI=
64
+
65
+ # ---------- Logging ----------
66
+ # error | warn | info | http | verbose | debug | silly
67
+ LOG_LEVEL=info
68
+ LOG_DIR=./logs
69
+ LOG_CONSOLE=true
70
+
71
+ # ---------- CORS ----------
72
+ # Comma-separated origins, or * for all
73
+ CORS_ORIGIN=*
@@ -23,7 +23,7 @@
23
23
  "@dotenvx/dotenvx": "^1.71.0",
24
24
  "http-errors": "^2.0.0",
25
25
  "skweb-express": "^1.0.0",
26
- "skweb-express-jwt": "^1.0.0",
26
+ "skweb-express-jwt": "^1.2.0",
27
27
  "skweb-express-logger": "^1.0.0",
28
28
  "skweb-sequelize": "^1.0.0",
29
29
  "skweb-redis": "^1.0.0",
@@ -32,7 +32,9 @@
32
32
  "skweb-plugin": "^1.0.0",
33
33
  "skweb-util": "^1.0.0",
34
34
  "winston": "^3.17.0",
35
- "sequelize": "^6.37.7"
35
+ "sequelize": "^6.37.7",
36
+ "swagger-jsdoc": "^6.2.8",
37
+ "swagger-ui-express": "^5.0.1"
36
38
  },
37
39
  "devDependencies": {
38
40
  "chai": "^6.2.1",
@@ -4,12 +4,58 @@ import path from 'path'
4
4
  import { fileURLToPath } from 'url'
5
5
  import express from 'skweb-express'
6
6
  import expressLogger from 'skweb-express-logger'
7
+ import swaggerUi from 'swagger-ui-express'
7
8
  import logger from './utils/logger.js'
8
9
  import { checkRequiredEnv } from './utils/config.js'
10
+ import { buildOpenApiSpec } from './swagger.js'
9
11
 
10
12
  const __filename = fileURLToPath(import.meta.url)
11
13
  const __dirname = path.dirname(__filename)
12
14
 
15
+ /**
16
+ * 构建 JWT 配置,支持两种模式:
17
+ * - 'static' (默认):使用共享密钥(HS256/HS384/HS512),适用于自签 token
18
+ * - 'jwks':通过 JWKS 端点动态获取公钥(RS256 等),适用于 Keycloak/Auth0 等 IdP
19
+ */
20
+ function buildJwtOptions() {
21
+ const provider = process.env.AUTH_PROVIDER || 'static'
22
+
23
+ if (provider === 'jwks') {
24
+ const issuer = process.env.OIDC_ISSUER
25
+ const jwksUri = process.env.OIDC_JWKS_URI
26
+ const audience = process.env.OIDC_AUDIENCE
27
+ if (!issuer && !jwksUri) {
28
+ throw new Error('AUTH_PROVIDER=jwks requires OIDC_ISSUER or OIDC_JWKS_URI')
29
+ }
30
+ return {
31
+ provider: 'jwks',
32
+ algorithms: ['RS256'],
33
+ jwks: { jwksUri, issuer, audience },
34
+ verify: { issuer, audience },
35
+ requestProperty: 'resolvedToken'
36
+ }
37
+ }
38
+
39
+ return {
40
+ provider: 'static',
41
+ secret: process.env.JWT_SECRET || 'please-change-this-in-production',
42
+ algorithms: ['HS256'],
43
+ sign: { expiresIn: process.env.JWT_EXPIRES_IN || '7d' },
44
+ requestProperty: 'resolvedToken'
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Swagger UI 仅在 NODE_ENV 为 development / test,且 SWAGGER_ENABLED !== 'false' 时启用。
50
+ * 生产环境(production / unset)默认禁用,避免暴露内部 API 细节。
51
+ */
52
+ function shouldEnableSwagger() {
53
+ const env = (process.env.NODE_ENV || '').toLowerCase()
54
+ if (env !== 'development' && env !== 'test') return false
55
+ if ((process.env.SWAGGER_ENABLED || '').toLowerCase() === 'false') return false
56
+ return true
57
+ }
58
+
13
59
  async function bootstrap() {
14
60
  logger.info('[app] Initializing web process...')
15
61
 
@@ -55,17 +101,33 @@ async function bootstrap() {
55
101
  app.setOkCode(0)
56
102
  app.setOkMessage('success')
57
103
 
58
- app.setJWT('default', {
59
- secret: process.env.JWT_SECRET || 'please-change-this-in-production',
60
- algorithms: ['HS256'],
61
- sign: { expiresIn: process.env.JWT_EXPIRES_IN || '7d' },
62
- requestProperty: 'resolvedToken'
63
- })
104
+ // JWT 配置(按 AUTH_PROVIDER 选择 static 或 jwks 模式)
105
+ const jwtOptions = buildJwtOptions()
106
+ app.setJWT('default', jwtOptions)
64
107
  app.setJwtHintHeader('JwtHint')
65
108
 
109
+ if (jwtOptions.provider === 'jwks') {
110
+ logger.info(`[app] JWT auth provider: jwks (issuer: ${jwtOptions.jwks.issuer || jwtOptions.jwks.jwksUri})`)
111
+ } else {
112
+ logger.info('[app] JWT auth provider: static (HS256)')
113
+ }
114
+
66
115
  app.use(expressLogger())
67
116
  app.use(express.static(path.join(__dirname, '..', 'public')))
68
117
 
118
+ // 仅在 dev / test 环境挂载 Swagger UI(默认关闭,需显式 SWAGGER_ENABLED=true)
119
+ if (shouldEnableSwagger()) {
120
+ const openapiSpec = buildOpenApiSpec()
121
+ app.get('/api-docs.json', (_req, res) => res.json(openapiSpec))
122
+ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openapiSpec, {
123
+ customSiteTitle: `${process.env.APP_NAME || 'SKWeb'} API Docs`,
124
+ swaggerOptions: { persistAuthorization: true }
125
+ }))
126
+ logger.info(`[app] Swagger UI mounted at http://localhost:${process.env.PORT || 3000}/api-docs (env: ${process.env.NODE_ENV})`)
127
+ } else {
128
+ logger.info(`[app] Swagger UI disabled (env: ${process.env.NODE_ENV || 'unset'})`)
129
+ }
130
+
69
131
  await framework.loadControllers(path.join(__dirname, './controllers'))
70
132
  await framework.loadPluginControllers()
71
133
 
@@ -94,4 +156,4 @@ if (isMainModule) {
94
156
  })
95
157
  }
96
158
 
97
- export { bootstrap }
159
+ export { bootstrap }
@@ -1,3 +1,49 @@
1
+ /**
2
+ * @swagger
3
+ * /:
4
+ * get:
5
+ * summary: 欢迎页
6
+ * description: 返回项目基本信息。
7
+ * tags: [Hello]
8
+ * responses:
9
+ * 200:
10
+ * description: OK
11
+ * content:
12
+ * application/json:
13
+ * schema:
14
+ * type: object
15
+ * properties:
16
+ * message: { type: string, example: 'Welcome to SKWeb!' }
17
+ * version: { type: string, example: '1.0.0' }
18
+ * timestamp: { type: string, format: date-time }
19
+ * /health:
20
+ * get:
21
+ * summary: 健康检查
22
+ * tags: [Hello]
23
+ * responses:
24
+ * 200:
25
+ * description: OK
26
+ * content:
27
+ * application/json:
28
+ * schema:
29
+ * type: object
30
+ * properties:
31
+ * status: { type: string, example: 'ok' }
32
+ * timestamp: { type: string, format: date-time }
33
+ * /echo:
34
+ * post:
35
+ * summary: 回显请求体
36
+ * tags: [Hello]
37
+ * requestBody:
38
+ * required: true
39
+ * content:
40
+ * application/json:
41
+ * schema:
42
+ * type: object
43
+ * responses:
44
+ * 200:
45
+ * description: OK
46
+ */
1
47
  export default [
2
48
  {
3
49
  method: 'get',