@kne/fastify-app-manager 0.1.19 → 0.1.21

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 CHANGED
@@ -201,18 +201,19 @@ await fastify.listen({ port: 3000 });
201
201
  | `pwaIconPrefix` | string | 否 | `'/api/v1/static/file-id'` | PWA manifest 图标地址前缀(应用 `icon` 为文件 id 时拼接) |
202
202
  | `secretEnvKeyPattern` | RegExp | 否 | `/(SECRET\|PASSWORD\|TOKEN\|KEY\|PRIVATE)/i` | 按键名正则脱敏;与显式 `secretEnvKeys` 取并集 |
203
203
  | `systemEnvKeys` | array | 否 | `[]` | 宿主维护的系统变量键名,与内置 `DB_TABLE_PREFIX` 合并:接口不返回,create / save / saveEnv 不可新增、修改或删除 |
204
- | `resolveSystemEnv` | function | 否 | `null` | `async ({ app, version, serverDir }) => env \| null`,每次启动进程(deploy / start / restart / 恢复)前调用;返回值覆盖应用变量注入子进程,值为 `null` / `undefined` 的键忽略,属于 `systemEnvKeys` 的键持久化到 `app.env` |
204
+ | `resolveSystemEnv` | function | 否 | `null` | `async ({ app, version, serverDir, upstreamUrl }) => env \| null`(`upstreamUrl` 为子应用进程地址 `http://{upstreamHost}:{port}`),每次启动进程(deploy / start / restart / 恢复)前调用;返回值覆盖应用变量注入子进程,值为 `null` / `undefined` 的键忽略,属于 `systemEnvKeys` 的键持久化到 `app.env` |
205
205
  | `onAppRemoved` | function | 否 | `null` | `async ({ app }) => void`,应用删除成功后调用,`app` 为删除前快照(含 `env`);数据清理未完成而未删除时不调用,钩子报错只记 warn 日志 |
206
206
  | `resolveVersionFile` | function | 否 | `null` | `async ({ fileId, name, version, request }) => Buffer`,版本上传传 `fileId`(而非 multipart 文件)时调用,返回 zip 内容;未配置时传 `fileId` 返回 400。版本记录保存 `fileId`;这类版本只在当前部署时常驻磁盘,部署非当前版本或启动时当前版本目录缺失会再次调用以重建 |
207
207
  | `defaultAppDb` | object | 否 | `appsRoot/_shared/apps-data.sqlite` | 托管应用默认库(须与宿主主库分离) |
208
208
  | `dbQueryMaxRows` | number | 否 | `500` | 只读 query SQL 最大返回行数 |
209
209
  | `pm2Defaults` | object | 否 | 见下表 | 全局 PM2 默认;可被应用 `pm2Config` 覆盖 |
210
- | `createAuthenticate` | function | 否 | 见说明 | 返回 `onRequest` 钩子数组;默认尝试 admin |
210
+ | `createAuthenticate` | function | 否 | 见说明 | 返回 `onRequest` 钩子数组;默认 `fastify.account.authenticate.user` + `admin` |
211
211
  | `createUserAuthenticate` | function | 否 | 见说明 | 应用中心等普通用户接口的 `onRequest` 钩子数组;默认尝试 `fastify.account.authenticate.user` |
212
+ | `upstreamHost` | string | 否 | `'127.0.0.1'` | 子应用进程监听地址:网关转发、WebSocket、就绪探测、端口探测与 `resolveSystemEnv` 的 `upstreamUrl` 共用 |
212
213
  | `healthCheckPath` | string | 否 | `'/'` | 部署后就绪探测路径 |
213
214
  | `healthCheckTimeoutMs` | number | 否 | `30000` | 探测总超时(毫秒) |
214
215
  | `healthCheckIntervalMs` | number | 否 | `1000` | 探测轮询间隔(毫秒) |
215
- | `maxZipSize` | number | 否 | `209715200` | zip 最大字节(200MB);同步 multipart 限制 |
216
+ | `maxZipSize` | number | 否 | `209715200` | zip 最大字节(200MB);上传接口按此值读取 multipart,不受宿主已注册 multipart 的限制影响 |
216
217
  | `maxZipEntries` | number | 否 | `20000` | zip 最大条目数(不含被丢弃的 `node_modules` 条目) |
217
218
  | `npmInstallTimeoutMs` | number | 否 | `600000` | `server` 目录 `npm install` 超时 |
218
219
  | `deployRecordKeep` | number | 否 | `20` | 每个应用保留的部署记录条数 |
@@ -248,7 +249,11 @@ await fastify.listen({ port: 3000 });
248
249
 
249
250
  应用级 `pm2Config` 仅允许覆盖:`exec_mode`、`instances`、`autorestart`、`max_memory_restart`、`max_restarts`、`min_uptime`、`kill_timeout`、`merge_logs`。
250
251
 
251
- > **关键设计**:`createAuthenticate` 默认实现在存在 `fastify.account.authenticate.admin` 时返回该钩子,否则返回空数组(便于本地无 account 插件时调试)。生产环境应显式传入鉴权。
252
+ > **关键设计**:`createAuthenticate` 默认实现在存在 `fastify.account.authenticate.admin` 时返回 `[user, admin]`(admin 依赖 user 先写入 `request.userInfo`),否则返回空数组(便于本地无 account 插件时调试)。生产环境应显式传入鉴权。
253
+ >
254
+ > **query token**:`createAuthenticate` / `createUserAuthenticate` 返回非空数组时,会在最前面自动加一个钩子:请求没有 `Authorization` 头而 query 带 `token` 时,转成 `Bearer {token}`(日志 SSE、原生导航下载无法带请求头)。宿主无需自行处理。
255
+ >
256
+ > **重复注册**:宿主已注册 `@fastify/multipart` 或 `@fastify/reply-from` 时(如 `@kne/fastify-file-manager` 会注册 multipart),本插件不再重复注册。
252
257
 
253
258
  > **依赖**:插件 `dependencies: ['fastify-sequelize']`,须先 `register('@kne/fastify-sequelize')` 再注册本插件,并在业务侧调用 `fastify.sequelize.sync()`。
254
259
 
@@ -584,6 +589,8 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
584
589
 
585
590
  返回脱敏后的应用对象,另带 `deployment`:最近一次部署尚未结束(未出错、就绪阶段未完成)时为 `{ progressId, versionId, version, startedAt, step, detail }`,否则为 `null`。准备部署包阶段应用仍是旧的 `status` 与 `currentVersionId`,用它判断哪个版本正在部署。`app/list` 的每个元素同样带该字段。
586
591
 
592
+ 详情另带 `pm2Defaults`:宿主生效的全局 PM2 默认(即插件选项 `pm2Defaults`),供管理端展示应用 `pm2Config` 未覆盖项的实际取值。
593
+
587
594
  ##### POST `{prefix}/app/start` | `stop` | `restart` | `remove`
588
595
 
589
596
  | 参数名 | 类型 | 必填 | 说明 |
@@ -965,3 +972,34 @@ pickHostEnv(passthroughEnvKeys) → app.env → PORT=分配端口(强制)
965
972
  ```
966
973
 
967
974
  API 响应脱敏:`secretEnvKeyPattern` ∪ `options.secretEnvKeys`;明文密钥不回传,顶层 `secretEnvKeys` 只暴露键名。
975
+
976
+ #### 应用 OIDC 对接(可选)
977
+
978
+ 宿主已注册 `@kne/fastify-oidc` 作为主 IdP、希望子应用统一登录时使用;不传则子应用不注入任何登录相关变量,按各自的登录运行(`@kne/fastify-oidc` 未设置 `AUTH_MODE` 时默认 `standalone`)。`@kne/fastify-oidc` 为可选 peer 依赖,不用 OIDC 的宿主无需安装。
979
+
980
+ ```js
981
+ const createAppOidc = require('@kne/fastify-app-manager/oidc');
982
+
983
+ const appOidc = createAppOidc(fastify, { origin, issuer, serviceAudience });
984
+ fastify.register(require('@kne/fastify-app-manager'), {
985
+ systemEnvKeys: appOidc.systemEnvKeys,
986
+ resolveSystemEnv: appOidc.resolveSystemEnv,
987
+ onAppRemoved: appOidc.onAppRemoved
988
+ });
989
+ ```
990
+
991
+ | 参数 | 类型 | 必填 | 默认值 | 说明 |
992
+ |------|------|------|--------|------|
993
+ | origin | string | 是 | - | 宿主对外地址,拼子应用回调地址与 audience |
994
+ | issuer | string | 是 | - | 宿主 IdP issuer |
995
+ | serviceAudience | string | 是 | - | 子应用服务 client 可访问的宿主资源标识 |
996
+ | pathPrefix | string | 否 | `'/app'` | 与 app-manager 的 `pathPrefix` 一致 |
997
+ | backchannelLogoutPath | string | 否 | `'/api/oidc/backchannel-logout'` | 子应用登出通知路径,拼在 `upstreamUrl` 之后,直连子应用进程 |
998
+
999
+ 返回 `{ systemEnvKeys, resolveSystemEnv, onAppRemoved, getOpenApiToken, issueUserAccessToken }`。
1000
+
1001
+ | 子应用情况 | 行为 |
1002
+ |------|------|
1003
+ | `server/package.json` 未依赖 `@kne/fastify-oidc` | 不登记、不注入 |
1004
+ | `server/env.schema.json` 声明 `AUTH_MODE` 默认值为 `standalone` | 不登记、不注入,保持自己的登录;之前以 central 启动过的应用注入 `AUTH_MODE=standalone` 覆盖 |
1005
+ | 其它依赖 `@kne/fastify-oidc` 的应用 | 登记资源服务、前端 client、服务 client,注入 `AUTH_MODE=central` 与 `OIDC_*` |
package/index.js CHANGED
@@ -15,6 +15,8 @@ module.exports = fp(
15
15
  prefix: '/api/v1/app-manager',
16
16
  appsRoot,
17
17
  portMin: 4000,
18
+ /** 子应用进程监听地址:网关转发、WebSocket、就绪探测、端口探测与 resolveSystemEnv 的 upstreamUrl 共用 */
19
+ upstreamHost: '127.0.0.1',
18
20
  portMax: 7999,
19
21
  pathPrefix: '/app',
20
22
  healthCheckPath: '/',
@@ -74,9 +76,10 @@ module.exports = fp(
74
76
  kill_timeout: 5000,
75
77
  merge_logs: true
76
78
  },
79
+ // admin 依赖 user 先写入 request.userInfo,不可只挂 authenticate.admin
77
80
  createAuthenticate: () => {
78
81
  if (fastify.account?.authenticate?.admin) {
79
- return [fastify.account.authenticate.admin];
82
+ return [fastify.account.authenticate.user, fastify.account.authenticate.admin];
80
83
  }
81
84
  return [];
82
85
  },
@@ -109,13 +112,31 @@ module.exports = fp(
109
112
  await fs.ensureDir(path.dirname(options.defaultAppDb.storage));
110
113
  }
111
114
 
112
- await fastify.register(require('@fastify/multipart'), {
113
- limits: {
114
- fileSize: options.maxZipSize
115
+ // 日志 SSE、原生导航下载无法带请求头,token 放在 query 中
116
+ const queryTokenToAuthorization = async request => {
117
+ if (!request.headers.authorization && typeof request.query?.token === 'string' && request.query.token) {
118
+ request.headers.authorization = `Bearer ${request.query.token}`;
115
119
  }
116
- });
120
+ };
121
+ const withQueryToken = createAuthenticate => () => {
122
+ const list = createAuthenticate() || [];
123
+ return list.length ? [queryTokenToAuthorization, ...list] : list;
124
+ };
125
+ options.createAuthenticate = withQueryToken(options.createAuthenticate);
126
+ options.createUserAuthenticate = withQueryToken(options.createUserAuthenticate);
117
127
 
118
- await fastify.register(require('@fastify/reply-from'));
128
+ // 宿主可能已注册(如 fastify-file-manager),重复注册会报错
129
+ if (!fastify.hasDecorator('multipartErrors')) {
130
+ await fastify.register(require('@fastify/multipart'), {
131
+ limits: {
132
+ fileSize: options.maxZipSize
133
+ }
134
+ });
135
+ }
136
+
137
+ if (!fastify.hasReplyDecorator('from')) {
138
+ await fastify.register(require('@fastify/reply-from'));
139
+ }
119
140
 
120
141
  fastify.register(require('@kne/fastify-namespace'), {
121
142
  options,
@@ -167,7 +167,7 @@ module.exports = fp(async (fastify, options) => {
167
167
  let { name, version, label, fileId } = request.isMultipart() ? {} : request.body || {};
168
168
  let zipBuffer;
169
169
  if (request.isMultipart()) {
170
- for await (const part of request.parts()) {
170
+ for await (const part of request.parts({ limits: { fileSize: options.maxZipSize } })) {
171
171
  if (part.type === 'file') {
172
172
  zipBuffer = await part.toBuffer();
173
173
  } else {
@@ -24,7 +24,7 @@ module.exports = fp(async (fastify, options) => {
24
24
  const rawUrl = request.raw.url || '/';
25
25
  const targetPath = stripPrefix ? stripMountPrefix(rawUrl, app.name) : rawUrl;
26
26
 
27
- const dest = `http://127.0.0.1:${app.port}${targetPath}`;
27
+ const dest = `http://${options.upstreamHost}:${app.port}${targetPath}`;
28
28
  const mountPrefix = `${pathPrefix}/${app.name}`;
29
29
 
30
30
  const tracker = fastify[ns].requestMetrics?.begin(app.name);
@@ -196,7 +196,7 @@ module.exports = fp(async (fastify, options) => {
196
196
  }
197
197
 
198
198
  req.url = targetPath;
199
- wsProxy.ws(req, socket, head, { target: `http://127.0.0.1:${app.port}` }, error => {
199
+ wsProxy.ws(req, socket, head, { target: `http://${options.upstreamHost}:${app.port}` }, error => {
200
200
  fastify.log.warn({ err: error, app: app.name }, 'websocket upgrade proxy failed');
201
201
  rejectUpgrade(socket, 502);
202
202
  });
@@ -137,7 +137,8 @@ module.exports = fp(async (fastify, options) => {
137
137
  const port = await portPool.allocate({
138
138
  models,
139
139
  portMin: options.portMin,
140
- portMax: options.portMax
140
+ portMax: options.portMax,
141
+ host: options.upstreamHost
141
142
  });
142
143
 
143
144
  const normalizedOptions = Object.assign({}, appOptions || {});
@@ -295,7 +296,11 @@ module.exports = fp(async (fastify, options) => {
295
296
 
296
297
  const detail = async ({ name }) => {
297
298
  const app = await getByName(name);
298
- return Object.assign(toPublicApp(app), { deployment: deployProgress.active(app.name), lastDeployment: await lastDeployment(app.name) });
299
+ return Object.assign(toPublicApp(app), {
300
+ pm2Defaults: options.pm2Defaults || {},
301
+ deployment: deployProgress.active(app.name),
302
+ lastDeployment: await lastDeployment(app.name)
303
+ });
299
304
  };
300
305
 
301
306
  const versionSqlDir = ver => path.join(ver.artifactPath, 'server', ver.migrationPath || options.sqlPath || 'sql');
@@ -489,7 +494,7 @@ module.exports = fp(async (fastify, options) => {
489
494
 
490
495
  const healthCheck = async (port, { timeoutMs, intervalMs, healthPath }) => {
491
496
  const started = Date.now();
492
- const url = `http://127.0.0.1:${port}${healthPath || '/'}`;
497
+ const url = `http://${options.upstreamHost}:${port}${healthPath || '/'}`;
493
498
  while (Date.now() - started < timeoutMs) {
494
499
  try {
495
500
  const res = await fetch(url, { method: 'GET' });
@@ -808,7 +813,7 @@ module.exports = fp(async (fastify, options) => {
808
813
  }
809
814
 
810
815
  if (typeof options.resolveSystemEnv === 'function') {
811
- const systemEnv = await options.resolveSystemEnv({ app, version, serverDir });
816
+ const systemEnv = await options.resolveSystemEnv({ app, version, serverDir, upstreamUrl: `http://${options.upstreamHost}:${app.port}` });
812
817
  const injectedKeys = [];
813
818
  if (systemEnv && typeof systemEnv === 'object') {
814
819
  const persisted = {};
@@ -1,6 +1,6 @@
1
1
  const net = require('node:net');
2
2
 
3
- const isPortFree = port =>
3
+ const isPortFree = (port, host = '127.0.0.1') =>
4
4
  new Promise(resolve => {
5
5
  const server = net.createServer();
6
6
  server.unref();
@@ -8,19 +8,19 @@ const isPortFree = port =>
8
8
  server.once('listening', () => {
9
9
  server.close(() => resolve(true));
10
10
  });
11
- server.listen(port, '127.0.0.1');
11
+ server.listen(port, host);
12
12
  });
13
13
 
14
14
  module.exports = {
15
15
  isPortFree,
16
- async allocate({ models, portMin, portMax, excludePorts = [] }) {
16
+ async allocate({ models, portMin, portMax, excludePorts = [], host }) {
17
17
  const rows = await models.app.findAll({ attributes: ['port'] });
18
18
  const used = new Set([...rows.map(r => r.port), ...excludePorts]);
19
19
  for (let port = portMin; port <= portMax; port++) {
20
20
  if (used.has(port)) {
21
21
  continue;
22
22
  }
23
- if (await isPortFree(port)) {
23
+ if (await isPortFree(port, host)) {
24
24
  return port;
25
25
  }
26
26
  }
package/oidc.js ADDED
@@ -0,0 +1,282 @@
1
+ /**
2
+ * 应用中心子应用 OIDC 接入(可选):宿主已注册 @kne/fastify-oidc 作为主 IdP 时使用。
3
+ * 子应用 server 依赖 @kne/fastify-oidc 时,部署时登记资源服务与 client,并以 central 模式启动;
4
+ * 子应用在 server/env.schema.json 中声明 AUTH_MODE 默认值为 standalone 时,保持自己的登录。
5
+ */
6
+ const path = require('node:path');
7
+ const fs = require('fs-extra');
8
+ const isEqual = require('lodash/isEqual');
9
+ // 宿主启用 OIDC 时才会用到,未安装 @kne/fastify-oidc 的宿主不受影响
10
+ const oidcCrypto = () => require('@kne/fastify-oidc/libs/utils/crypto');
11
+ const OIDC_PACKAGE = '@kne/fastify-oidc';
12
+ // 子应用 @kne/fastify-app-runtime 的 /open-api.json 放行带此 scope 的 client 令牌
13
+ const OPEN_API_SCOPE = 'open-api:read';
14
+ const DOCS_CLIENT_ID = 'app-center-docs';
15
+
16
+ const SYSTEM_ENV_KEYS = ['AUTH_MODE', 'OIDC_ISSUER', 'OIDC_AUDIENCE', 'OIDC_CLIENT_ID', 'OIDC_SERVICE_CLIENT_ID', 'OIDC_SERVICE_CLIENT_SECRET'];
17
+
18
+ const supportsOidc = async serverDir => {
19
+ try {
20
+ const pkg = await fs.readJson(path.join(serverDir, 'package.json'));
21
+ return !!pkg.dependencies?.[OIDC_PACKAGE];
22
+ } catch (e) {
23
+ return false;
24
+ }
25
+ };
26
+
27
+ const prefersStandalone = async serverDir => {
28
+ try {
29
+ const schema = await fs.readJson(path.join(serverDir, 'env.schema.json'));
30
+ return schema?.properties?.AUTH_MODE?.default === 'standalone';
31
+ } catch (e) {
32
+ return false;
33
+ }
34
+ };
35
+
36
+ /**
37
+ * @param fastify 已注册 @kne/fastify-oidc 的宿主实例
38
+ * @param options.origin 宿主对外地址,拼子应用回调地址与 audience
39
+ * @param options.issuer 宿主 IdP issuer
40
+ * @param options.serviceAudience 子应用服务 client 可访问的宿主资源标识
41
+ * @param options.pathPrefix 应用中心路径前缀,与 app-manager 的 pathPrefix 一致
42
+ * @param options.backchannelLogoutPath 子应用 fastify-oidc 的登出通知路径,默认与其默认 prefix /api/oidc 对应
43
+ */
44
+ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix = '/app', backchannelLogoutPath = '/api/oidc/backchannel-logout' } = {}) => {
45
+ if (!origin || !issuer || !serviceAudience) {
46
+ throw new Error('createAppOidc requires origin, issuer and serviceAudience');
47
+ }
48
+ origin = origin.replace(/\/+$/, '');
49
+ const oidc = () => fastify.oidc;
50
+ const { protocol } = new URL(origin);
51
+
52
+ const clientIds = name => ({ spa: `app-${name}`, service: `app-${name}-service` });
53
+
54
+ const resolveUrls = app => {
55
+ const pathBase = `${origin}${pathPrefix}/${app.name}`;
56
+ const domainBase = app.domain ? `${protocol}//${app.domain}` : null;
57
+ return {
58
+ bases: [domainBase, pathBase].filter(Boolean),
59
+ // 子应用用 ORIGIN 拼邀请 / 重置密码等对外链接,路径模式必须带 /app/{name};fastify-oidc 只取其 origin 部分
60
+ appUrl: domainBase || pathBase,
61
+ // 资源标识只作 token 的 aud,固定用路径形式,绑定 / 更换域名后不变
62
+ audience: `${pathBase}/api`
63
+ };
64
+ };
65
+
66
+ const spaMetadata = ({ bases }, upstreamUrl) => ({
67
+ application_type: 'web',
68
+ grant_types: ['authorization_code', 'refresh_token'],
69
+ response_types: ['code'],
70
+ token_endpoint_auth_method: 'none',
71
+ redirect_uris: bases.map(base => `${base}/oidc-callback`),
72
+ post_logout_redirect_uris: bases.map(base => `${base}/`),
73
+ // 登出通知直连子应用进程(地址由 app-manager 的 upstreamHost 决定),不经过网关
74
+ backchannel_logout_uri: `${upstreamUrl}${backchannelLogoutPath}`,
75
+ backchannel_logout_session_required: true
76
+ });
77
+
78
+ const ensureResourceServer = async ({ identifier, name }) => {
79
+ const { models, services, options } = oidc();
80
+ const existing = await models.resourceServer.findOne({ where: { identifier } });
81
+ if (!existing) {
82
+ await services.resourceServer.create({ identifier, name, scope: `${options.defaultResourceScope} ${OPEN_API_SCOPE}`, description: '应用中心子应用自动登记' });
83
+ return;
84
+ }
85
+ const scopes = String(existing.scope || options.defaultResourceScope)
86
+ .split(' ')
87
+ .filter(Boolean);
88
+ if (!scopes.includes(OPEN_API_SCOPE)) {
89
+ await existing.update({ scope: [...scopes, OPEN_API_SCOPE].join(' ') });
90
+ }
91
+ };
92
+
93
+ const ensureSpaClient = async ({ clientId, clientName, metadata, allowedResources }) => {
94
+ const { models, services } = oidc();
95
+ const existing = await models.client.findOne({ where: { clientId } });
96
+ if (!existing) {
97
+ await services.client.create({ clientId, clientName, metadata, allowedResources, description: '应用中心子应用自动登记' });
98
+ return;
99
+ }
100
+ const nextMetadata = Object.assign({}, existing.metadata, metadata);
101
+ if (!isEqual(nextMetadata, existing.metadata) || !isEqual(allowedResources, existing.allowedResources)) {
102
+ await services.client.save({ id: existing.id, metadata: nextMetadata, allowedResources });
103
+ }
104
+ };
105
+
106
+ const ensureServiceClient = async ({ clientId, clientName }) => {
107
+ const { models, services, options } = oidc();
108
+ const existing = await models.client.findOne({ where: { clientId } });
109
+ if (!existing) {
110
+ const clientSecret = oidcCrypto().randomSecret(32);
111
+ await services.client.create({
112
+ clientId,
113
+ clientName,
114
+ clientSecret,
115
+ metadata: { grant_types: ['client_credentials'], response_types: [], token_endpoint_auth_method: 'client_secret_basic' },
116
+ allowedResources: [serviceAudience],
117
+ description: '应用中心子应用自动登记'
118
+ });
119
+ return clientSecret;
120
+ }
121
+ // 以认证管理中的实际 secret 为准(管理员可能重置过)
122
+ return oidcCrypto().decrypt(options.keyEncryptionSecret, existing.clientSecret);
123
+ };
124
+
125
+ /** 本系统读取子应用文档用的 client:allowedResources 随需要读取的子应用 audience 增加 */
126
+ const ensureDocsClient = async audience => {
127
+ const { models, services, options } = oidc();
128
+ const existing = await models.client.findOne({ where: { clientId: DOCS_CLIENT_ID } });
129
+ if (!existing) {
130
+ const clientSecret = oidcCrypto().randomSecret(32);
131
+ await services.client.create({
132
+ clientId: DOCS_CLIENT_ID,
133
+ clientName: '应用中心文档读取',
134
+ clientSecret,
135
+ metadata: { grant_types: ['client_credentials'], response_types: [], token_endpoint_auth_method: 'client_secret_basic' },
136
+ allowedResources: [audience],
137
+ description: '应用中心 MCP 读取子应用 OpenAPI 文档'
138
+ });
139
+ return clientSecret;
140
+ }
141
+ const allowedResources = existing.allowedResources || [];
142
+ if (!allowedResources.includes(audience)) {
143
+ await services.client.save({ id: existing.id, allowedResources: [...allowedResources, audience] });
144
+ }
145
+ return oidcCrypto().decrypt(options.keyEncryptionSecret, existing.clientSecret);
146
+ };
147
+
148
+ const docsTokenCache = new Map();
149
+
150
+ /** 签发访问子应用 /open-api.json 的服务令牌(audience 为子应用 OIDC_AUDIENCE,scope 为 open-api:read) */
151
+ const getOpenApiToken = async app => {
152
+ // app 详情接口会剔除系统注入的 env,audience 按部署时相同规则推导,以资源服务是否已登记判断接入
153
+ const { audience } = resolveUrls(app);
154
+ await oidc().whenReady();
155
+ if (!(await oidc().models.resourceServer.findOne({ where: { identifier: audience } }))) {
156
+ throw new Error(`应用 ${app.name} 未接入 OIDC(server 未依赖 ${OIDC_PACKAGE} 或尚未部署),无法签发读取文档的令牌`);
157
+ }
158
+ await ensureResourceServer({ identifier: audience, name: app.label || app.name });
159
+ const cached = docsTokenCache.get(audience);
160
+ if (cached && cached.expiresAt - 30 * 1000 > Date.now()) {
161
+ return cached.accessToken;
162
+ }
163
+ const clientSecret = await ensureDocsClient(audience);
164
+ // IdP 挂在本进程上,直接 inject 到 token 端点,不经公网 issuer 地址绕回自身
165
+ const response = await fastify.inject({
166
+ method: 'POST',
167
+ url: `${new URL(issuer).pathname}/token`,
168
+ headers: {
169
+ 'content-type': 'application/x-www-form-urlencoded',
170
+ authorization: `Basic ${Buffer.from(`${encodeURIComponent(DOCS_CLIENT_ID)}:${encodeURIComponent(clientSecret)}`).toString('base64')}`
171
+ },
172
+ payload: new URLSearchParams({ grant_type: 'client_credentials', resource: audience, scope: OPEN_API_SCOPE }).toString()
173
+ });
174
+ const data = response.json();
175
+ if (response.statusCode !== 200) {
176
+ throw new Error(`签发读取文档的令牌失败:${data.error_description || data.error || response.statusCode}`);
177
+ }
178
+ docsTokenCache.set(audience, { accessToken: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 });
179
+ return data.access_token;
180
+ };
181
+
182
+ /** 以登录用户身份签发访问子应用 API 的用户令牌(audience 为子应用 OIDC_AUDIENCE) */
183
+ const issueUserAccessToken = async ({ app, userId, tenantId }) => {
184
+ const { audience } = resolveUrls(app);
185
+ await oidc().whenReady();
186
+ const resource = await oidc().models.resourceServer.findOne({ where: { identifier: audience } });
187
+ if (!resource) {
188
+ throw new Error(`应用 ${app.name} 未接入 OIDC(server 未依赖 ${OIDC_PACKAGE} 或尚未部署),无法代登录用户调用`);
189
+ }
190
+ const provider = oidc().idp.getProvider();
191
+ if (!provider) {
192
+ throw new Error('IdP 尚未就绪,无法代登录用户调用');
193
+ }
194
+ const client = await provider.Client.find(clientIds(app.name).spa);
195
+ if (!client) {
196
+ throw new Error(`应用 ${app.name} 尚未登记登录客户端,请先完成一次部署`);
197
+ }
198
+ const scope =
199
+ String(resource.scope || oidc().options.defaultResourceScope)
200
+ .split(/\s+/)
201
+ .filter(item => item && item !== OPEN_API_SCOPE)
202
+ .join(' ') || oidc().options.defaultResourceScope;
203
+ const token = new provider.AccessToken({
204
+ client,
205
+ accountId: String(userId),
206
+ scope,
207
+ gty: 'mcp'
208
+ });
209
+ token.resourceServer = new provider.ResourceServer(audience, {
210
+ scope: resource.scope,
211
+ audience,
212
+ accessTokenTTL: resource.accessTokenTTL || oidc().options.ttl.accessToken,
213
+ accessTokenFormat: 'jwt',
214
+ jwt: { sign: { alg: 'RS256' } }
215
+ });
216
+ if (tenantId) {
217
+ token.kneTenantId = String(tenantId);
218
+ }
219
+ return token.save();
220
+ };
221
+
222
+ const resolveSystemEnv = async ({ app, serverDir, upstreamUrl }) => {
223
+ if (!(await supportsOidc(serverDir)) || (await prefersStandalone(serverDir))) {
224
+ // 之前以 central 启动过的应用,持久化的 AUTH_MODE 需覆盖回 standalone
225
+ return app.env?.AUTH_MODE ? { AUTH_MODE: 'standalone' } : null;
226
+ }
227
+ await oidc().whenReady();
228
+ const urls = resolveUrls(app);
229
+ const ids = clientIds(app.name);
230
+ await ensureResourceServer({ identifier: urls.audience, name: app.label || app.name });
231
+ await ensureSpaClient({
232
+ clientId: ids.spa,
233
+ clientName: app.label || app.name,
234
+ metadata: spaMetadata(urls, upstreamUrl),
235
+ allowedResources: [urls.audience]
236
+ });
237
+ const serviceSecret = await ensureServiceClient({ clientId: ids.service, clientName: `${app.label || app.name} 服务端` });
238
+
239
+ return Object.assign(
240
+ {
241
+ AUTH_MODE: 'central',
242
+ OIDC_ISSUER: issuer,
243
+ OIDC_AUDIENCE: urls.audience,
244
+ OIDC_CLIENT_ID: ids.spa,
245
+ OIDC_SERVICE_CLIENT_ID: ids.service,
246
+ OIDC_SERVICE_CLIENT_SECRET: serviceSecret
247
+ },
248
+ app.env?.ORIGIN ? {} : { ORIGIN: urls.appUrl }
249
+ );
250
+ };
251
+
252
+ const onAppRemoved = async ({ app }) => {
253
+ if (!app.env?.OIDC_CLIENT_ID) {
254
+ return;
255
+ }
256
+ const { models, services } = oidc();
257
+ await oidc().whenReady();
258
+ for (const clientId of [app.env.OIDC_CLIENT_ID, app.env.OIDC_SERVICE_CLIENT_ID].filter(Boolean)) {
259
+ const item = await models.client.findOne({ where: { clientId } });
260
+ if (item) {
261
+ await services.client.remove({ id: item.id });
262
+ }
263
+ }
264
+ if (app.env.OIDC_AUDIENCE) {
265
+ const docsClient = await models.client.findOne({ where: { clientId: DOCS_CLIENT_ID } });
266
+ if (docsClient && (docsClient.allowedResources || []).includes(app.env.OIDC_AUDIENCE)) {
267
+ await services.client.save({ id: docsClient.id, allowedResources: docsClient.allowedResources.filter(item => item !== app.env.OIDC_AUDIENCE) });
268
+ }
269
+ const item = await models.resourceServer.findOne({ where: { identifier: app.env.OIDC_AUDIENCE } });
270
+ if (item) {
271
+ await services.resourceServer.remove({ id: item.id });
272
+ }
273
+ }
274
+ };
275
+
276
+ return { systemEnvKeys: SYSTEM_ENV_KEYS, resolveSystemEnv, onAppRemoved, getOpenApiToken, issueUserAccessToken };
277
+ };
278
+
279
+ module.exports = createAppOidc;
280
+ module.exports.supportsOidc = supportsOidc;
281
+ module.exports.prefersStandalone = prefersStandalone;
282
+ module.exports.SYSTEM_ENV_KEYS = SYSTEM_ENV_KEYS;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -20,6 +20,7 @@
20
20
  },
21
21
  "files": [
22
22
  "index.js",
23
+ "oidc.js",
23
24
  "libs"
24
25
  ],
25
26
  "repository": {
@@ -46,7 +47,13 @@
46
47
  "peerDependencies": {
47
48
  "@kne/fastify-namespace": "*",
48
49
  "@kne/fastify-sequelize": "*",
49
- "fastify-plugin": ">=5"
50
+ "fastify-plugin": ">=5",
51
+ "@kne/fastify-oidc": "*"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "@kne/fastify-oidc": {
55
+ "optional": true
56
+ }
50
57
  },
51
58
  "devDependencies": {
52
59
  "@fastify/env": "^5.0.2",