create-skweb 1.1.5 → 2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-skweb",
3
- "version": "1.1.5",
3
+ "version": "2.1.0",
4
4
  "description": "Create a new SKWeb project with TypeScript, CJS, or MJS support",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -13,11 +13,14 @@
13
13
  "clean": "rm -rf dist",
14
14
  "clean:temp": "rm -rf .rollup.cache",
15
15
  "prebuild": "tsc --outDir dist --rootDir src",
16
- "build": "rollup -c rollup.config.mjs && node scripts/inject-shebang.cjs && chmod +x dist/cli.cjs",
17
- "build:dev": "rollup -c rollup.config.mjs --environment NODE_ENV:development && node scripts/inject-shebang.cjs && chmod +x dist/cli.cjs",
16
+ "build": "rollup -c rollup.config.mjs && node scripts/inject-shebang.mjs && chmod +x dist/cli.cjs",
17
+ "build:dev": "rollup -c rollup.config.mjs --environment NODE_ENV:development && node scripts/inject-shebang.mjs && chmod +x dist/cli.cjs",
18
18
  "lint": "eslint --fix --ext .ts src",
19
19
  "check": "tsc --noEmit",
20
- "test": "mocha test/**/*.mjs"
20
+ "test": "mocha test/**/*.mjs",
21
+ "sync:versions": "node scripts/sync-template-versions.mjs",
22
+ "sync:versions:apply": "node scripts/sync-template-versions.mjs --apply",
23
+ "sync:versions:strict": "node scripts/sync-template-versions.mjs --strict"
21
24
  },
22
25
  "dependencies": {
23
26
  "commander": "^12.1.0",
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // inject-shebang.mjs
4
+ //
5
+ // 给 rollup 产出的 CLI 文件加 shebang。
6
+ // rollup 在某些场景下会丢失或重复 shebang(特别是使用 @rollup/plugin-replace
7
+ // 替换 /usr/bin/env 时),这里统一收口。
8
+ //
9
+ // 用法:
10
+ // node scripts/inject-shebang.mjs # 默认 ./dist/cli.cjs
11
+ // node scripts/inject-shebang.mjs dist/cli.cjs # 相对 cwd 的目标
12
+ // node scripts/inject-shebang.mjs /abs/path/cli # 绝对路径
13
+ //
14
+ // 说明:
15
+ // - 已存在 shebang 时跳过,不重复添加
16
+ // - 文件不存在时给出明确错误信息(避免静默失败)
17
+ //
18
+
19
+ import fs from 'node:fs'
20
+ import path from 'node:path'
21
+
22
+ const SHEBANG = '#!/usr/bin/env node\n'
23
+
24
+ const arg = process.argv[2]
25
+ const target = arg ? path.resolve(arg) : path.resolve('dist/cli.cjs')
26
+
27
+ if (!fs.existsSync(target)) {
28
+ console.error(`[inject-shebang] target not found: ${target}`)
29
+ process.exit(1)
30
+ }
31
+
32
+ let content = fs.readFileSync(target, 'utf-8')
33
+ if (content.startsWith('#!')) {
34
+ console.log(`[inject-shebang] Shebang already present in ${target}`)
35
+ process.exit(0)
36
+ }
37
+
38
+ fs.writeFileSync(target, SHEBANG + content, 'utf-8')
39
+ console.log(`[inject-shebang] Shebang added to ${target}`)
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // sync-template-versions.mjs
4
+ //
5
+ // 把本工程 packages 下的 skweb-* 包版本号
6
+ // 同步到 tools/create-skweb/templates 下的 package.json。
7
+ //
8
+ // 用法:
9
+ // node scripts/sync-template-versions.mjs # 默认 dry-run,仅打印
10
+ // node scripts/sync-template-versions.mjs --apply # 写回文件
11
+ // node scripts/sync-template-versions.mjs --strict # 严格模式:发现不一致退出码 1
12
+ // node scripts/sync-template-versions.mjs --help # 查看帮助
13
+ //
14
+ // 同步规则:
15
+ // - workspace 的 X.Y.Z 映射到模板的 ^X.Y.0
16
+ // - 仅修改 skweb-* 开头的依赖(其他依赖不动)
17
+ // - 仅处理 templates 目录下 .json 文件
18
+ //
19
+ // 退出码:
20
+ // 0 全部一致,或已 --apply 写回
21
+ // 1 --strict 模式下发现不一致且未 --apply
22
+ // 2 执行过程异常
23
+ //
24
+ // 建议在以下时机执行:
25
+ // - 每次 changeset version 之后
26
+ // - 提交前
27
+ // - CI 发布前
28
+ //
29
+
30
+ import fs from 'node:fs'
31
+ import path from 'node:path'
32
+ import { fileURLToPath } from 'node:url'
33
+
34
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
35
+ const ROOT = path.join(__dirname, '..', '..', '..') // -> skweb-mono/
36
+ const PACKAGES_DIR = path.join(ROOT, 'packages')
37
+ const TEMPLATES_DIR = path.join(__dirname, '..', 'templates')
38
+
39
+ // ANSI 颜色(仅在 TTY 启用,避免污染 CI 日志)
40
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR
41
+ const color = (code) => (useColor ? `\x1b[${code}m` : '')
42
+ const cBold = color('1')
43
+ const cYellow = color('33')
44
+ const cRed = color('31')
45
+ const cGreen = color('32')
46
+ const cCyan = color('36')
47
+ const cReset = color('0')
48
+
49
+ function showHelp() {
50
+ console.log(`${cBold}sync-template-versions${cReset}
51
+ 把 packages/ 下的 skweb-* 版本号同步到 templates/ 下的 package.json。
52
+
53
+ ${cBold}用法${cReset}
54
+ ${cCyan}node scripts/sync-template-versions.mjs${cReset} ${cYellow}# 默认 dry-run${cReset}
55
+ ${cCyan}node scripts/sync-template-versions.mjs --apply${cReset} # 写回文件
56
+ ${cCyan}node scripts/sync-template-versions.mjs --strict${cReset} # 严格模式(CI 推荐)
57
+ ${cCyan}node scripts/sync-template-versions.mjs --help${cReset} # 查看帮助
58
+
59
+ ${cBold}同步规则${cReset}
60
+ - workspace 的 X.Y.Z 映射到模板的 ^X.Y.0
61
+ - 仅修改 skweb-* 开头的依赖
62
+ - 仅处理 templates 目录下 *.json
63
+
64
+ ${cBold}退出码${cReset}
65
+ 0 全部一致,或已 --apply 写回
66
+ 1 --strict 模式下发现不一致且未 --apply
67
+ 2 执行过程异常
68
+
69
+ ${cBold}同步规则说明${cReset}
70
+ 使用 ${cCyan}--apply${cReset} 真正写入文件;不带 --apply 永远只打印,不会改动模板。`)
71
+ }
72
+
73
+ const APPLY = process.argv.includes('--apply')
74
+ const STRICT = process.argv.includes('--strict')
75
+ const HELP = process.argv.includes('--help') || process.argv.includes('-h')
76
+
77
+ if (HELP) {
78
+ showHelp()
79
+ process.exit(0)
80
+ }
81
+
82
+ // 扫描 packages/ 下所有 package.json,返回 { 包名: 版本 } 映射。
83
+ function loadWorkspaceVersions() {
84
+ const result = {}
85
+ if (!fs.existsSync(PACKAGES_DIR)) {
86
+ throw new Error(`packages dir not found: ${PACKAGES_DIR}`)
87
+ }
88
+ for (const dir of fs.readdirSync(PACKAGES_DIR)) {
89
+ const pkgJsonPath = path.join(PACKAGES_DIR, dir, 'package.json')
90
+ if (!fs.existsSync(pkgJsonPath)) continue
91
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'))
92
+ if (pkg.name && pkg.version) {
93
+ result[pkg.name] = pkg.version
94
+ }
95
+ }
96
+ return result
97
+ }
98
+
99
+ // 把 X.Y.Z 转换为 ^X.Y.0 范围,允许 minor/patch 升级。
100
+ function toRange(version) {
101
+ const parts = version.split('.')
102
+ if (parts.length < 2) {
103
+ throw new Error(`unexpected version format: ${version}`)
104
+ }
105
+ return `^${parts[0]}.${parts[1]}.0`
106
+ }
107
+
108
+ // 同步单个模板文件,返回变更列表。
109
+ function syncTemplate(templatePath, workspaceVersions) {
110
+ const raw = fs.readFileSync(templatePath, 'utf-8')
111
+ const pkg = JSON.parse(raw)
112
+ const deps = pkg.dependencies || {}
113
+ const changes = []
114
+
115
+ for (const depName of Object.keys(deps)) {
116
+ if (!depName.startsWith('skweb-')) continue
117
+ if (!workspaceVersions[depName]) continue
118
+ const newRange = toRange(workspaceVersions[depName])
119
+ const oldRange = deps[depName]
120
+ if (oldRange !== newRange) {
121
+ changes.push({ dep: depName, old: oldRange, new: newRange })
122
+ deps[depName] = newRange
123
+ }
124
+ }
125
+
126
+ if (changes.length > 0 && APPLY) {
127
+ const updated = JSON.stringify(pkg, null, 2) + '\n'
128
+ fs.writeFileSync(templatePath, updated, 'utf-8')
129
+ }
130
+
131
+ return changes
132
+ }
133
+
134
+ function main() {
135
+ // 在最顶部打印运行模式,避免用户漏看后续信息
136
+ if (APPLY) {
137
+ console.log(`${cGreen}[sync] mode: APPLY (will write to files)${cReset}`)
138
+ } else {
139
+ console.log(`${cYellow}[sync] mode: DRY-RUN (no files will be modified; pass --apply to write)${cReset}`)
140
+ }
141
+ if (STRICT) {
142
+ console.log(`${cYellow}[sync] mode: STRICT (will exit 1 on pending changes)${cReset}`)
143
+ }
144
+ console.log('')
145
+
146
+ const workspaceVersions = loadWorkspaceVersions()
147
+ console.log(`[sync] workspace versions: ${Object.keys(workspaceVersions).length} packages`)
148
+ for (const [name, ver] of Object.entries(workspaceVersions)) {
149
+ console.log(` ${name}: ${ver} -> ${toRange(ver)}`)
150
+ }
151
+ console.log('')
152
+
153
+ if (!fs.existsSync(TEMPLATES_DIR)) {
154
+ throw new Error(`templates dir not found: ${TEMPLATES_DIR}`)
155
+ }
156
+
157
+ let totalChanges = 0
158
+ const templateDirs = fs.readdirSync(TEMPLATES_DIR).filter(d => {
159
+ const full = path.join(TEMPLATES_DIR, d)
160
+ return fs.statSync(full).isDirectory()
161
+ })
162
+
163
+ for (const tpl of templateDirs) {
164
+ const pkgJson = path.join(TEMPLATES_DIR, tpl, 'package.json')
165
+ if (!fs.existsSync(pkgJson)) continue
166
+ const changes = syncTemplate(pkgJson, workspaceVersions)
167
+ if (changes.length === 0) {
168
+ console.log(`[sync] ${tpl}/package.json: in sync`)
169
+ } else {
170
+ totalChanges += changes.length
171
+ const tag = APPLY ? `${cGreen}[APPLIED]${cReset}` : `${cYellow}[dry-run]${cReset}`
172
+ console.log(`[sync] ${tpl}/package.json: ${changes.length} update(s) ${tag}`)
173
+ for (const c of changes) {
174
+ console.log(` ${c.dep}: ${c.old} -> ${c.new}`)
175
+ }
176
+ }
177
+ }
178
+
179
+ console.log('')
180
+ if (totalChanges === 0) {
181
+ console.log(`${cGreen}[sync] All templates are in sync with workspace versions.${cReset}`)
182
+ } else if (APPLY) {
183
+ console.log(`${cGreen}[sync] Applied ${totalChanges} update(s).${cReset}`)
184
+ } else {
185
+ console.log(
186
+ `${cYellow}[sync] ${totalChanges} update(s) pending.${cReset} ` +
187
+ `${cBold}Re-run with ${cCyan}--apply${cReset}${cBold} to write.${cReset}`
188
+ )
189
+ if (STRICT) {
190
+ console.log(`${cRed}[sync] STRICT mode: exiting with code 1.${cReset}`)
191
+ process.exit(1)
192
+ }
193
+ }
194
+ }
195
+
196
+ try {
197
+ main()
198
+ } catch (err) {
199
+ console.error('[sync] FAILED:', err.message)
200
+ process.exit(2)
201
+ }
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=*
@@ -22,17 +22,19 @@
22
22
  "dependencies": {
23
23
  "@dotenvx/dotenvx": "^1.71.0",
24
24
  "http-errors": "^2.0.0",
25
- "skweb-express": "^1.0.0",
26
- "skweb-express-jwt": "^1.0.0",
27
- "skweb-express-logger": "^1.0.0",
28
- "skweb-sequelize": "^1.0.0",
29
- "skweb-redis": "^1.0.0",
30
- "skweb-cron": "^1.0.0",
31
- "skweb-framework": "^1.0.0",
32
- "skweb-plugin": "^1.0.0",
33
- "skweb-util": "^1.0.0",
25
+ "skweb-express": "^1.1.0",
26
+ "skweb-express-jwt": "^2.0.0",
27
+ "skweb-express-logger": "^1.1.0",
28
+ "skweb-sequelize": "^1.1.0",
29
+ "skweb-redis": "^1.1.0",
30
+ "skweb-cron": "^1.1.0",
31
+ "skweb-framework": "^1.1.0",
32
+ "skweb-plugin": "^1.1.0",
33
+ "skweb-util": "^1.1.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',