@kne/fastify-app-manager 0.1.41 → 0.1.44

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
@@ -18,7 +18,7 @@ npm i --save @kne/fastify-app-manager
18
18
 
19
19
  #### 项目概述
20
20
 
21
- `@kne/fastify-app-manager` 是面向可信团队内部的 **单机应用市场** Fastify 插件:上传 Fullstack Biz App 的 zip 版本、由 PM2 拉起独立 Node 进程、按分配端口反代访问,并提供管理 API、文件日志与 SSE 实时推送。
21
+ `@kne/fastify-app-manager` 是面向可信团队内部的 **单机应用市场** Fastify 插件:上传 Fullstack Biz App 的 zip 版本、由 PM2 拉起独立 Node 进程、按分配端口反代访问,并提供管理 API、文件日志与 SSE 实时推送。kne 宿主可另引 `@kne/fastify-app-manager/host`(`createKneHostOptions`)生成租户/权限/文件等默认钩子,租户上下文走 `@kne/fastify-kv-cache`。
22
22
 
23
23
  适用场景:内网/堡垒机上的业务应用集中托管;不负责多机编排、硬磁盘配额或 WebSocket 升级。
24
24
 
@@ -368,6 +368,16 @@ await fastify.listen({ port: 3000 });
368
368
 
369
369
  运行中应用的 OpenAPI 文档:用 `getOpenApiToken` 签发的服务令牌请求子应用 `http://{upstreamHost}:{port}/open-api.json`,原样返回 JSON。
370
370
 
371
+ ##### GET `{prefix}/app/open-api/federate`
372
+
373
+ 将子应用 OpenAPI 的 `paths` 改写为宿主网关路径 `/app/{name}{原 path}`,并给 operation 打上 `x-app-name` 与 tag `应用:{name}`。宿主启动后 `fastify.mcp.injectOpenApi(doc)` 合并进 MCP 可见文档,管理台开启后再经 `call_api` inject 打网关。
374
+
375
+ Query:`name`(必填)。
376
+
377
+ ##### POST `{prefix}/app/open-api/federate-all`
378
+
379
+ 对全部 `running` 应用执行联邦;单项失败记入 `errors`。返回 `{ apps: [{ name, document }], errors, document }`,其中 `document` 为合并全部成功 `paths` 的总文档。
380
+
371
381
  | 参数名 | 类型 | 必填 | 说明 |
372
382
  |--------|------|------|------|
373
383
  | name | string | 是 | 应用 slug |
@@ -1004,6 +1014,9 @@ data: {"name":"demo","ts":1791456608533,...}
1004
1014
  | 方法签名 | 说明 |
1005
1015
  |----------|------|
1006
1016
  | `getDocument({ name })` | 同 `GET .../app/open-api` |
1017
+ | `getFederatedDocument({ name })` | 同 `GET .../app/open-api/federate` |
1018
+ | `federateRunning()` | 同 `POST .../app/open-api/federate-all` |
1019
+ | `rewriteFederatedPaths(spec, { name })` | 纯函数:改写 paths(测试/自定义合并可用) |
1007
1020
  | `issueUserToken({ name, userId, tenantId? })` | 同 `POST .../app/open-api/token` |
1008
1021
  | `listRecords({ name, type, operationKey?, keyword?, offset?, limit? })` | 同 `GET .../app/open-api/records` |
1009
1022
  | `countRecords({ name, type })` | 同 `GET .../app/open-api/records/count` |
@@ -1235,10 +1248,39 @@ fastify.register(require('@kne/fastify-app-manager'), {
1235
1248
  | pathPrefix | string | 否 | `'/app'` | 与 app-manager 的 `pathPrefix` 一致 |
1236
1249
  | backchannelLogoutPath | string | 否 | `'/api/oidc/backchannel-logout'` | 子应用登出通知路径,拼在 `upstreamUrl` 之后,直连子应用进程 |
1237
1250
 
1238
- 返回 `{ systemEnvKeys, resolveSystemEnv, onAppRemoved, getOpenApiToken, issueUserAccessToken }`。
1251
+ 返回 `{ systemEnvKeys, resolveSystemEnv, onAppRemoved, getOpenApiToken, issueUserAccessToken, getServiceToken, signPlatformAssertion, ensureLinkedRegistration, … }`。
1239
1252
 
1240
1253
  | 子应用情况 | 行为 |
1241
1254
  |------|------|
1242
1255
  | `server/package.json` 未依赖 `@kne/fastify-oidc` | 不登记、不注入 |
1243
1256
  | `server/env.schema.json` 声明 `AUTH_MODE` 默认值为 `standalone` | 不登记、不注入,保持自己的登录;之前以 central 启动过的应用注入 `AUTH_MODE=standalone` 覆盖 |
1244
1257
  | 其它依赖 `@kne/fastify-oidc` 的应用 | 登记资源服务、前端 client、服务 client,注入 `AUTH_MODE=central` 与 `OIDC_*` |
1258
+
1259
+ #### kne 宿主默认钩子(`@kne/fastify-app-manager/host`)
1260
+
1261
+ 已接 `@kne/fastify-tenant` / `@kne/fastify-account` / `@kne/fastify-file-manager` 的宿主,用本模块生成中心列表裁剪、`canUseApp`、权限源同步、版本/图标文件回调等,避免各平台复制粘贴。
1262
+
1263
+ **依赖**:须先注册 `@kne/fastify-kv-cache`(装饰器 `fastify.KVCache`)。租户上下文按 `request.id` 缓存(TTL 60s),不再使用 WeakMap。
1264
+
1265
+ ```js
1266
+ const createAppOidc = require('@kne/fastify-app-manager/oidc');
1267
+ const createKneHostOptions = require('@kne/fastify-app-manager/host');
1268
+
1269
+ await fastify.register(require('@kne/fastify-kv-cache'), {
1270
+ mode: 'pg', // 或 redis / hybrid
1271
+ namespace: 'app-manager',
1272
+ syncDB: true,
1273
+ pg: { /* … */ }
1274
+ });
1275
+
1276
+ const appOidc = createAppOidc(fastify, { origin, issuer, serviceAudience });
1277
+ fastify.register(require('@kne/fastify-app-manager'), createKneHostOptions(fastify, {
1278
+ oidc: appOidc,
1279
+ origin,
1280
+ appsRoot,
1281
+ portMin: 4100
1282
+ // 需要定制时覆盖单个钩子即可,如 canUseApp
1283
+ }));
1284
+ ```
1285
+
1286
+ 默认填入:`filterCenterApps` / `filterCenterMenus` / `canUseApp` / `getTenantId` / `canManageDisplay` / `getPermissionRootCodes` / `onPermissionsSynced` / `onPermissionsRemoved` / `resolveVersionFile` / `saveIconFile`,以及 `oidc` 摊开的 OIDC 钩子。后传入的同名字段覆盖默认。
package/host.js ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * kne 宿主默认接线:在已注册 tenant / account / fileManager / KVCache 时,
3
+ * 生成 app-manager 常用钩子,避免每个平台复制 filterCenter* / canUseApp 等逻辑。
4
+ *
5
+ * @example
6
+ * const createAppOidc = require('@kne/fastify-app-manager/oidc');
7
+ * const createKneHostOptions = require('@kne/fastify-app-manager/host');
8
+ * const appOidc = createAppOidc(fastify, { origin, issuer, serviceAudience });
9
+ * fastify.register(require('@kne/fastify-app-manager'), createKneHostOptions(fastify, {
10
+ * oidc: appOidc,
11
+ * origin,
12
+ * appsRoot,
13
+ * portMin: 4100
14
+ * }));
15
+ */
16
+
17
+ const TENANT_CTX_TTL_SEC = 60;
18
+ const TENANT_CTX_PREFIX = 'app-manager:tenant-ctx:';
19
+
20
+ const flattenOidc = oidc => {
21
+ if (!oidc || typeof oidc !== 'object') {
22
+ return {};
23
+ }
24
+ return {
25
+ signPlatformAssertion: oidc.signPlatformAssertion,
26
+ ensureLinkedRegistration: oidc.ensureLinkedRegistration,
27
+ getOpsServiceToken: oidc.getServiceToken,
28
+ systemEnvKeys: oidc.systemEnvKeys,
29
+ resolveSystemEnv: oidc.resolveSystemEnv,
30
+ onAppRemoved: oidc.onAppRemoved,
31
+ getOpenApiToken: oidc.getOpenApiToken,
32
+ issueUserAccessToken: oidc.issueUserAccessToken
33
+ };
34
+ };
35
+
36
+ const requireKVCache = fastify => {
37
+ if (!fastify.KVCache || typeof fastify.KVCache.get !== 'function' || typeof fastify.KVCache.set !== 'function') {
38
+ throw new Error('@kne/fastify-app-manager/host 需要先注册 @kne/fastify-kv-cache(装饰器 fastify.KVCache)');
39
+ }
40
+ return fastify.KVCache;
41
+ };
42
+
43
+ /**
44
+ * @param {object} fastify
45
+ * @param {object} [options]
46
+ * @param {object} [options.oidc] createAppOidc 返回值,自动摊开 OIDC 钩子
47
+ * @returns {object} 可直接传给 fastify.register(app-manager, …) 的 options(显式字段覆盖默认钩子)
48
+ */
49
+ const createKneHostOptions = (fastify, options = {}) => {
50
+ const { oidc, ...rest } = options;
51
+
52
+ const resolveTenantContext = async request => {
53
+ const kv = requireKVCache(fastify);
54
+ const cacheKey = `${TENANT_CTX_PREFIX}${request.id}`;
55
+ const cached = await kv.get(cacheKey);
56
+ if (cached && typeof cached === 'object') {
57
+ return cached.empty ? null : cached.ctx || null;
58
+ }
59
+
60
+ let ctx = null;
61
+ try {
62
+ await fastify.tenant.authenticate.tenantUser(request);
63
+ const info = request.tenantUserInfo;
64
+ const read = key => (typeof info?.getDataValue === 'function' ? info.getDataValue(key) : info?.[key]);
65
+ if (info?.tenantId) {
66
+ ctx = {
67
+ tenantId: String(info.tenantId),
68
+ permissions: (read('permissions') || []).map(String),
69
+ isAdmin: await fastify.tenant.services.user.resolveIsTenantAdmin({
70
+ tenantId: info.tenantId,
71
+ roleDetails: read('roleDetails'),
72
+ roles: read('roles'),
73
+ currentTenantUserId: info.id
74
+ })
75
+ };
76
+ }
77
+ } catch (e) {
78
+ ctx = null;
79
+ }
80
+
81
+ await kv.set(cacheKey, ctx ? { ctx } : { empty: true }, TENANT_CTX_TTL_SEC);
82
+ return ctx;
83
+ };
84
+
85
+ const isSuperAdminRequest = async request => {
86
+ try {
87
+ if (!request.userInfo) {
88
+ await fastify.account.authenticate.user(request);
89
+ }
90
+ return !!request.userInfo && (await fastify.account.services.admin.checkIsSuperAdmin(request.userInfo));
91
+ } catch (e) {
92
+ return false;
93
+ }
94
+ };
95
+
96
+ const isPermissionRoot = name => (fastify.tenant?.permissions?.modules || []).some(item => item && String(item.code) === name);
97
+
98
+ const permissionSet = ctx => new Set(ctx?.permissions || []);
99
+
100
+ const defaults = {
101
+ onPermissionsSynced: async ({ tree, sourceKey }) => {
102
+ if (fastify.tenant?.setPermissionSource) {
103
+ fastify.tenant.setPermissionSource(sourceKey, tree, { defaultDisabled: true });
104
+ }
105
+ },
106
+ onPermissionsRemoved: async ({ sourceKey }) => {
107
+ if (fastify.tenant?.removePermissionSource) {
108
+ fastify.tenant.removePermissionSource(sourceKey);
109
+ }
110
+ },
111
+ filterCenterApps: async ({ apps, request }) => {
112
+ const tenant = fastify.tenant;
113
+ const roots = new Set((tenant?.permissions?.modules || []).map(item => item && String(item.code)));
114
+ if (!apps.some(app => roots.has(app.name))) {
115
+ return apps;
116
+ }
117
+ let tenantId;
118
+ try {
119
+ await tenant.authenticate.tenantUser(request);
120
+ tenantId = request.tenantUserInfo?.tenantId;
121
+ } catch (e) {
122
+ return apps;
123
+ }
124
+ if (!tenantId) {
125
+ return apps;
126
+ }
127
+ const { codes } = await tenant.services.permission.tenantLevelList({ tenantId });
128
+ const enabled = new Set(codes.map(code => String(code).split(':')[0]));
129
+ return apps.filter(app => !roots.has(app.name) || enabled.has(app.name));
130
+ },
131
+ getTenantId: async ({ request }) => {
132
+ const ctx = await resolveTenantContext(request);
133
+ return ctx ? ctx.tenantId : null;
134
+ },
135
+ canManageDisplay: async ({ request, tenantId }) => {
136
+ if (!(await isSuperAdminRequest(request))) {
137
+ return false;
138
+ }
139
+ if (tenantId) {
140
+ return !!(await fastify.tenant.models.tenant.count({ where: { id: tenantId } }));
141
+ }
142
+ return true;
143
+ },
144
+ canUseApp: async ({ app, request }) => {
145
+ const ctx = await resolveTenantContext(request);
146
+ if (!ctx) {
147
+ return false;
148
+ }
149
+ if (!isPermissionRoot(app.name)) {
150
+ return { tenantId: ctx.tenantId };
151
+ }
152
+ const { codes } = await fastify.tenant.services.permission.tenantLevelList({ tenantId: ctx.tenantId });
153
+ if (!codes.some(code => String(code).split(':')[0] === app.name)) {
154
+ return false;
155
+ }
156
+ const owned = ctx.isAdmin || [...permissionSet(ctx)].some(code => String(code).split(':')[0] === app.name);
157
+ return owned ? { tenantId: ctx.tenantId } : false;
158
+ },
159
+ filterCenterMenus: async ({ menus, app, request }) => {
160
+ const ctx = await resolveTenantContext(request);
161
+ if (!ctx) {
162
+ return [];
163
+ }
164
+ const perms = permissionSet(ctx);
165
+ const checkPermission = isPermissionRoot(app.name);
166
+ const visible = node => !node.permissionCode || !checkPermission || ctx.isAdmin || perms.has(node.permissionCode);
167
+ const filter = list =>
168
+ list
169
+ .filter(visible)
170
+ .map(node => (node.children ? Object.assign({}, node, { children: filter(node.children) }) : node))
171
+ .filter(node => !node.children || node.children.length);
172
+ return filter(menus);
173
+ },
174
+ getPermissionRootCodes: async () => {
175
+ const modules = fastify.tenant?.permissions?.modules || [];
176
+ return modules
177
+ .map(item => item && item.code)
178
+ .filter(Boolean)
179
+ .map(String);
180
+ },
181
+ resolveVersionFile: async ({ fileId }) => {
182
+ const { buffer } = await fastify.fileManager.services.fileRecord.getFileBlob({ id: fileId });
183
+ return buffer;
184
+ },
185
+ saveIconFile: async ({ buffer, filename, mimetype }) => {
186
+ const record = await fastify.fileManager.services.fileRecord.uploadToFileSystem({
187
+ file: { filename, encoding: '7bit', mimetype, buffer }
188
+ });
189
+ return record.id;
190
+ }
191
+ };
192
+
193
+ return Object.assign({}, defaults, flattenOidc(oidc), rest);
194
+ };
195
+
196
+ module.exports = createKneHostOptions;
197
+ module.exports.createKneHostOptions = createKneHostOptions;
198
+ module.exports.flattenOidc = flattenOidc;
@@ -76,9 +76,21 @@ const appBodyProps = {
76
76
  isPublic: { type: 'boolean', description: '是否公开,公开的应用未登录也能在应用中心看到;不传视为公开' },
77
77
  entries: entriesSchema,
78
78
  homePath: { type: 'string', description: '应用首页路径(相对应用根,默认 /);也可填完整 http(s) URL,详情「主页」Tab 用 iframe 打开' },
79
- env: { type: 'object', description: '应用环境变量;值为 ******** 的密钥变量保持原值,PORT 与宿主维护的系统变量会被忽略' },
80
- pm2Config: { type: 'object', description: 'PM2 覆盖配置,与插件级 pm2Defaults 合并' },
81
- options: { type: 'object', description: '扩展配置(如 secretEnvKeys 指定按密钥处理的变量名)' }
79
+ env: {
80
+ type: 'object',
81
+ additionalProperties: true,
82
+ description: '应用环境变量;值为 ******** 的密钥变量保持原值,PORT 与宿主维护的系统变量会被忽略'
83
+ },
84
+ pm2Config: {
85
+ type: 'object',
86
+ additionalProperties: true,
87
+ description: 'PM2 覆盖配置,与插件级 pm2Defaults 合并(如 instances、max_memory_restart)'
88
+ },
89
+ options: {
90
+ type: 'object',
91
+ additionalProperties: true,
92
+ description: '扩展配置(如 secretEnvKeys 指定按密钥处理的变量名)'
93
+ }
82
94
  };
83
95
 
84
96
  const pageQuery = {
@@ -104,7 +116,9 @@ module.exports = fp(async (fastify, options) => {
104
116
  required: ['name', 'label'],
105
117
  properties: Object.assign({ name: { type: 'string', description: '应用 name:小写字母、数字和 -,作为访问路径 /app/{name},创建后不可修改' } }, appBodyProps)
106
118
  },
107
- response: success('创建的应用', app())
119
+ response: success('创建的应用', app()),
120
+ 'x-mcp-scenarios': ['应用管理'],
121
+ 'x-mcp-confirm': true
108
122
  }
109
123
  },
110
124
  async request => services.app.create(request.body)
@@ -123,7 +137,9 @@ module.exports = fp(async (fastify, options) => {
123
137
  required: ['name'],
124
138
  properties: Object.assign({ name: { type: 'string', description: '要更新的应用 name' } }, appBodyProps)
125
139
  },
126
- response: success('更新后的应用', app())
140
+ response: success('更新后的应用', app()),
141
+ 'x-mcp-scenarios': ['应用管理'],
142
+ 'x-mcp-confirm': true
127
143
  }
128
144
  },
129
145
  async request => services.app.save(request.body)
@@ -137,7 +153,9 @@ module.exports = fp(async (fastify, options) => {
137
153
  tags: [TAG_CENTER],
138
154
  summary: '应用中心:运行中应用的公开信息(普通登录用户可访问)',
139
155
  description: '返回所有运行中的应用(含未公开的),只包含展示用字段',
140
- response: success('运行中的应用,按创建时间倒序', pageResult('应用', centerApp))
156
+ response: success('运行中的应用,按创建时间倒序', pageResult('应用', centerApp)),
157
+ 'x-mcp-scenarios': ['应用中心'],
158
+ 'x-mcp-confirm': false
141
159
  }
142
160
  },
143
161
  async request => services.app.centerList({ request })
@@ -152,7 +170,9 @@ module.exports = fp(async (fastify, options) => {
152
170
  summary: '应用中心:声明了菜单的应用及其菜单树(普通登录用户可访问)',
153
171
  description:
154
172
  '只含通过 filterCenterApps 与 filterCenterMenus 的应用;没有声明菜单或菜单为空的应用不出现。菜单快照在应用就绪与 linked 同步时拉取。应用挂了(status=error)但曾经就绪过时仍返回,菜单沿用上一次的快照,进入页面时前端调用 center/status 异步检测并展示错误;从未就绪过的 error 应用不出现',
155
- response: success('声明了菜单的应用,按创建时间倒序', pageResult('应用', centerMenuApp))
173
+ response: success('声明了菜单的应用,按创建时间倒序', pageResult('应用', centerMenuApp)),
174
+ 'x-mcp-scenarios': ['应用中心'],
175
+ 'x-mcp-confirm': false
156
176
  }
157
177
  },
158
178
  async request => services.menu.centerMenus({ request })
@@ -172,7 +192,9 @@ module.exports = fp(async (fastify, options) => {
172
192
  tenantId: { type: 'string', description: '要查看的租户 ID(仅超级管理员)' }
173
193
  }
174
194
  },
175
- response: success('当前租户可见的运行中应用,按创建时间倒序', pageResult('应用展示设置', displaySetting))
195
+ response: success('当前租户可见的运行中应用,按创建时间倒序', pageResult('应用展示设置', displaySetting)),
196
+ 'x-mcp-scenarios': ['应用中心'],
197
+ 'x-mcp-confirm': false
176
198
  }
177
199
  },
178
200
  async request => services.menu.displaySettings({ request, tenantId: request.query?.tenantId })
@@ -204,7 +226,9 @@ module.exports = fp(async (fastify, options) => {
204
226
  displayMode: str('展示方式,未设置过为 null'),
205
227
  labelI18n: obj('租户级应用名称多语言')
206
228
  })
207
- )
229
+ ),
230
+ 'x-mcp-scenarios': ['应用中心'],
231
+ 'x-mcp-confirm': true
208
232
  }
209
233
  },
210
234
  async request => services.menu.saveDisplaySetting({ name: request.body.name, displayMode: request.body.displayMode, labelI18n: request.body.labelI18n, tenantId: request.body.tenantId, request })
@@ -226,7 +250,9 @@ module.exports = fp(async (fastify, options) => {
226
250
  name: { type: 'string', description: APP_NAME }
227
251
  }
228
252
  },
229
- response: success('应用当前可用状态', appStatus)
253
+ response: success('应用当前可用状态', appStatus),
254
+ 'x-mcp-scenarios': ['应用中心'],
255
+ 'x-mcp-confirm': false
230
256
  }
231
257
  },
232
258
  async request => services.menu.appStatus({ name: request.query.name, request })
@@ -253,7 +279,9 @@ module.exports = fp(async (fastify, options) => {
253
279
  token: str('访问子应用接口的令牌'),
254
280
  expiresAt: any('过期时间,令牌不含 exp 时为 null')
255
281
  })
256
- )
282
+ ),
283
+ 'x-mcp-scenarios': ['应用中心'],
284
+ 'x-mcp-confirm': true
257
285
  }
258
286
  },
259
287
  async request => services.menu.issueCenterToken({ name: request.body.name, request })
@@ -265,7 +293,9 @@ module.exports = fp(async (fastify, options) => {
265
293
  schema: {
266
294
  tags: [TAG_CENTER],
267
295
  summary: '应用中心:运行中且公开的应用(无需登录)',
268
- response: success('运行中且公开的应用,按创建时间倒序', pageResult('应用', centerApp))
296
+ response: success('运行中且公开的应用,按创建时间倒序', pageResult('应用', centerApp)),
297
+ 'x-mcp-scenarios': ['应用中心'],
298
+ 'x-mcp-confirm': false
269
299
  }
270
300
  },
271
301
  async () => services.app.centerList({ publicOnly: true })
@@ -301,7 +331,9 @@ module.exports = fp(async (fastify, options) => {
301
331
  background_color: str('背景色'),
302
332
  icons: list('图标', obj('图标', { src: str('图标地址'), sizes: str('尺寸'), type: str('MIME 类型') }))
303
333
  })
304
- )
334
+ ),
335
+ 'x-mcp-scenarios': ['应用中心'],
336
+ 'x-mcp-confirm': false
305
337
  }
306
338
  },
307
339
  async (request, reply) => {
@@ -328,7 +360,9 @@ module.exports = fp(async (fastify, options) => {
328
360
  secretEnvKeys: { type: 'array', items: { type: 'string' }, description: '追加为密钥的变量名(值在接口中掩码);已是密钥的变量不能撤销,只随变量删除而移除' }
329
361
  }
330
362
  },
331
- response: success('更新后的应用', app())
363
+ response: success('更新后的应用', app()),
364
+ 'x-mcp-scenarios': ['应用部署'],
365
+ 'x-mcp-confirm': true
332
366
  }
333
367
  },
334
368
  async request => services.app.saveEnv(request.body)
@@ -374,7 +408,9 @@ module.exports = fp(async (fastify, options) => {
374
408
  ),
375
409
  others: list('已配置但未在 schema 中声明的变量', obj('未声明的变量', { key: str('变量名'), secret: bool('是否为密钥'), value: any('当前值,密钥为 ********') }))
376
410
  })
377
- )
411
+ ),
412
+ 'x-mcp-scenarios': ['应用部署'],
413
+ 'x-mcp-confirm': false
378
414
  }
379
415
  },
380
416
  async request => services.app.getEnvDeclaration(request.query)
@@ -395,12 +431,86 @@ module.exports = fp(async (fastify, options) => {
395
431
  name: { type: 'string', description: APP_NAME }
396
432
  }
397
433
  },
398
- response: success('子应用的 OpenAPI 文档原文')
434
+ response: success('子应用的 OpenAPI 文档原文', {
435
+ type: 'object',
436
+ additionalProperties: true,
437
+ description: 'OpenAPI 3 文档原文'
438
+ }),
439
+ 'x-mcp-scenarios': ['应用接口'],
440
+ 'x-mcp-confirm': false
399
441
  }
400
442
  },
401
443
  async request => services.openApi.getDocument(request.query)
402
444
  );
403
445
 
446
+ fastify.get(
447
+ `${options.prefix}/app/open-api/federate`,
448
+ {
449
+ onRequest: auth(),
450
+ schema: {
451
+ tags: [TAG_OPEN_API],
452
+ summary: '联邦 OpenAPI:路径改写为 /app/{name}{原 path},供宿主 MCP 同步',
453
+ description: '读取子应用 /open-api.json 后将 paths 改为宿主网关前缀,并打上 x-app-name;宿主启动后调用 fastify.mcp.injectOpenApi(doc) 合并进 MCP 可见文档,再在管理台开启接口',
454
+ query: {
455
+ type: 'object',
456
+ required: ['name'],
457
+ properties: {
458
+ name: { type: 'string', description: APP_NAME }
459
+ }
460
+ },
461
+ response: success('联邦后的 OpenAPI 文档', {
462
+ type: 'object',
463
+ additionalProperties: true,
464
+ description: 'paths 已改写为 /app/{name}/… 的 OpenAPI 文档'
465
+ }),
466
+ 'x-mcp-scenarios': ['应用接口', 'MCP同步'],
467
+ 'x-mcp-confirm': false
468
+ }
469
+ },
470
+ async request => services.openApi.getFederatedDocument(request.query)
471
+ );
472
+
473
+ fastify.post(
474
+ `${options.prefix}/app/open-api/federate-all`,
475
+ {
476
+ onRequest: auth(),
477
+ schema: {
478
+ tags: [TAG_OPEN_API],
479
+ summary: '联邦全部 running 应用的 OpenAPI',
480
+ description: '逐个拉取并改写路径;单个失败记入 errors,不中断其余。document 为合并 paths 的总文档',
481
+ body: {
482
+ type: 'object',
483
+ additionalProperties: false,
484
+ properties: {},
485
+ description: '无需参数'
486
+ },
487
+ response: success(
488
+ '联邦结果',
489
+ obj('联邦结果', {
490
+ apps: list(
491
+ '成功联邦的应用',
492
+ obj('应用联邦文档', {
493
+ name: str(APP_NAME),
494
+ document: any('联邦 OpenAPI 文档')
495
+ })
496
+ ),
497
+ errors: list(
498
+ '失败项',
499
+ obj('失败项', {
500
+ name: str(APP_NAME),
501
+ error: str('错误信息')
502
+ })
503
+ ),
504
+ document: any('合并全部成功应用 paths 的 OpenAPI 文档')
505
+ })
506
+ ),
507
+ 'x-mcp-scenarios': ['应用接口', 'MCP同步'],
508
+ 'x-mcp-confirm': false
509
+ }
510
+ },
511
+ async () => services.openApi.federateRunning()
512
+ );
513
+
404
514
  fastify.post(
405
515
  `${options.prefix}/app/open-api/token`,
406
516
  {
@@ -422,7 +532,9 @@ module.exports = fp(async (fastify, options) => {
422
532
  token: str('访问子应用接口的令牌'),
423
533
  expiresAt: any('过期时间,令牌不含 exp 时为 null')
424
534
  })
425
- )
535
+ ),
536
+ 'x-mcp-scenarios': ['应用接口'],
537
+ 'x-mcp-confirm': true
426
538
  }
427
539
  },
428
540
  async request => services.openApi.issueUserToken(Object.assign({}, request.body, { userId: request.userInfo?.id }))
@@ -447,7 +559,9 @@ module.exports = fp(async (fastify, options) => {
447
559
  limit: { type: 'integer', minimum: 1, maximum: 100, description: '每次返回的条数,不传返回全部' }
448
560
  }
449
561
  },
450
- response: success('记录列表;调用记录按时间倒序,用例按时间正序', pageResult('记录(保存时的原文)', any('记录原文')))
562
+ response: success('记录列表;调用记录按时间倒序,用例按时间正序', pageResult('记录(保存时的原文)', any('记录原文'))),
563
+ 'x-mcp-scenarios': ['应用接口'],
564
+ 'x-mcp-confirm': false
451
565
  }
452
566
  },
453
567
  async request => services.openApi.listRecords(request.query)
@@ -468,7 +582,9 @@ module.exports = fp(async (fastify, options) => {
468
582
  type: { type: 'string', enum: ['history', 'case'], description: RECORD_TYPE }
469
583
  }
470
584
  },
471
- response: success('{ [operationKey]: 记录数 },没有 operationKey 的记录计在空字符串键下')
585
+ response: success('{ [operationKey]: 记录数 },没有 operationKey 的记录计在空字符串键下'),
586
+ 'x-mcp-scenarios': ['应用接口'],
587
+ 'x-mcp-confirm': false
472
588
  }
473
589
  },
474
590
  async request => services.openApi.countRecords(request.query)
@@ -508,7 +624,9 @@ module.exports = fp(async (fastify, options) => {
508
624
  }
509
625
  }
510
626
  },
511
- response: empty('保存成功,返回空对象')
627
+ response: empty('保存成功,返回空对象'),
628
+ 'x-mcp-scenarios': ['应用接口'],
629
+ 'x-mcp-confirm': true
512
630
  }
513
631
  },
514
632
  async request => services.openApi.saveRecords(Object.assign({}, request.body, { userId: request.userInfo?.id }))
@@ -531,7 +649,9 @@ module.exports = fp(async (fastify, options) => {
531
649
  all: { type: 'boolean', description: '为 true 时忽略 ids,清空该类型全部记录' }
532
650
  }
533
651
  },
534
- response: empty('删除成功,返回空对象')
652
+ response: empty('删除成功,返回空对象'),
653
+ 'x-mcp-scenarios': ['应用接口'],
654
+ 'x-mcp-confirm': true
535
655
  }
536
656
  },
537
657
  async request => services.openApi.removeRecords(request.body)
@@ -546,7 +666,9 @@ module.exports = fp(async (fastify, options) => {
546
666
  summary: '上传应用版本 zip(multipart 传 file,或 JSON 传宿主文件 fileId)',
547
667
  description:
548
668
  '请求体字段:name 应用 name(必填);version 版本号(必填,同一应用不能重复);label 版本说明;file 部署包 zip(multipart)或 fileId 宿主文件 ID(JSON 或 multipart 字段,需配置 resolveVersionFile)。部署包需包含 server/ 与 server/env.schema.json,校验并安装依赖后登记版本',
549
- response: success('上传的版本', version)
669
+ response: success('上传的版本', version),
670
+ 'x-mcp-scenarios': ['应用部署'],
671
+ 'x-mcp-confirm': true
550
672
  }
551
673
  },
552
674
  async request => {
@@ -591,7 +713,9 @@ module.exports = fp(async (fastify, options) => {
591
713
  required: ['name'],
592
714
  properties: Object.assign({ name: { type: 'string', description: APP_NAME } }, pageQuery)
593
715
  },
594
- response: success('版本列表,按上传时间倒序', pageResult('版本', version))
716
+ response: success('版本列表,按上传时间倒序', pageResult('版本', version)),
717
+ 'x-mcp-scenarios': ['应用部署'],
718
+ 'x-mcp-confirm': false
595
719
  }
596
720
  },
597
721
  async request => services.app.listVersions(request.query)
@@ -613,7 +737,9 @@ module.exports = fp(async (fastify, options) => {
613
737
  token: { type: 'string', description: QUERY_TOKEN }
614
738
  }
615
739
  },
616
- response: raw('zip 文件流(application/zip,附件名 {name}-{version}.zip);由版本目录打包时不含 server/node_modules 与 server/build')
740
+ response: raw('zip 文件流(application/zip,附件名 {name}-{version}.zip);由版本目录打包时不含 server/node_modules 与 server/build'),
741
+ 'x-mcp-scenarios': ['应用部署'],
742
+ 'x-mcp-confirm': false
617
743
  }
618
744
  },
619
745
  async (request, reply) => {
@@ -675,7 +801,9 @@ module.exports = fp(async (fastify, options) => {
675
801
  pathUrl: str('访问地址,如 /app/{name}/'),
676
802
  domain: str('绑定域名,未绑定为 null')
677
803
  })
678
- )
804
+ ),
805
+ 'x-mcp-scenarios': ['应用部署'],
806
+ 'x-mcp-confirm': true
679
807
  }
680
808
  },
681
809
  async request => services.app.deploy(request.body)
@@ -698,7 +826,9 @@ module.exports = fp(async (fastify, options) => {
698
826
  token: { type: 'string', description: QUERY_TOKEN }
699
827
  }
700
828
  },
701
- response: raw('text/event-stream 事件流')
829
+ response: raw('text/event-stream 事件流'),
830
+ 'x-mcp-scenarios': ['应用部署'],
831
+ 'x-mcp-confirm': false
702
832
  }
703
833
  },
704
834
  async (request, reply) => {
@@ -747,7 +877,9 @@ module.exports = fp(async (fastify, options) => {
747
877
  required: ['name'],
748
878
  properties: Object.assign({ name: { type: 'string', description: APP_NAME } }, pageQuery)
749
879
  },
750
- response: success('部署记录,按开始时间倒序;每个应用只保留最近若干条', pageResult('部署记录', deployRecord))
880
+ response: success('部署记录,按开始时间倒序;每个应用只保留最近若干条', pageResult('部署记录', deployRecord)),
881
+ 'x-mcp-scenarios': ['应用部署'],
882
+ 'x-mcp-confirm': false
751
883
  }
752
884
  },
753
885
  async request => services.app.deployList(request.query)
@@ -779,7 +911,9 @@ module.exports = fp(async (fastify, options) => {
779
911
  log: str('部署日志(按 logLines 截取的最后若干行,换行分隔)')
780
912
  })
781
913
  )
782
- )
914
+ ),
915
+ 'x-mcp-scenarios': ['应用部署'],
916
+ 'x-mcp-confirm': false
783
917
  }
784
918
  },
785
919
  async request => services.app.deployDetail(request.query)
@@ -809,7 +943,9 @@ module.exports = fp(async (fastify, options) => {
809
943
  pageQuery
810
944
  )
811
945
  },
812
- response: success('应用列表,按创建时间倒序', pageResult('应用', appListItem))
946
+ response: success('应用列表,按创建时间倒序', pageResult('应用', appListItem)),
947
+ 'x-mcp-scenarios': ['应用管理'],
948
+ 'x-mcp-confirm': false
813
949
  }
814
950
  },
815
951
  async request => services.app.list(request.query)
@@ -829,7 +965,9 @@ module.exports = fp(async (fastify, options) => {
829
965
  name: { type: 'string', description: APP_NAME }
830
966
  }
831
967
  },
832
- response: success('应用详情,含进行中的部署与最近一次部署记录', appDetail)
968
+ response: success('应用详情,含进行中的部署与最近一次部署记录', appDetail),
969
+ 'x-mcp-scenarios': ['应用管理'],
970
+ 'x-mcp-confirm': false
833
971
  }
834
972
  },
835
973
  async request => services.app.detail(request.query)
@@ -854,7 +992,9 @@ module.exports = fp(async (fastify, options) => {
854
992
  required: ['name'],
855
993
  properties: { name: { type: 'string', description: APP_NAME } }
856
994
  },
857
- response: success('操作后的应用', app())
995
+ response: success('操作后的应用', app()),
996
+ 'x-mcp-scenarios': ['应用运维'],
997
+ 'x-mcp-confirm': true
858
998
  }
859
999
  },
860
1000
  async request => services.app[action](request.body)
@@ -889,7 +1029,9 @@ module.exports = fp(async (fastify, options) => {
889
1029
  export: exportResult,
890
1030
  cleanup: cleanupResult
891
1031
  })
892
- )
1032
+ ),
1033
+ 'x-mcp-scenarios': ['应用管理'],
1034
+ 'x-mcp-confirm': true
893
1035
  }
894
1036
  },
895
1037
  async request => services.app.remove(request.body)
@@ -928,7 +1070,9 @@ module.exports = fp(async (fastify, options) => {
928
1070
  totalCount: num('文件总行数'),
929
1071
  hasMore: bool('是否还有更早的日志')
930
1072
  })
931
- )
1073
+ ),
1074
+ 'x-mcp-scenarios': ['应用运维'],
1075
+ 'x-mcp-confirm': false
932
1076
  }
933
1077
  },
934
1078
  async request => services.app.logs(request.query)
@@ -948,7 +1092,9 @@ module.exports = fp(async (fastify, options) => {
948
1092
  name: { type: 'string', description: APP_NAME }
949
1093
  }
950
1094
  },
951
- response: success('日志文件列表', pageResult('日志文件', logFile))
1095
+ response: success('日志文件列表', pageResult('日志文件', logFile)),
1096
+ 'x-mcp-scenarios': ['应用运维'],
1097
+ 'x-mcp-confirm': false
952
1098
  }
953
1099
  },
954
1100
  async request => services.app.logFiles(request.query)
@@ -970,7 +1116,9 @@ module.exports = fp(async (fastify, options) => {
970
1116
  token: { type: 'string', description: QUERY_TOKEN }
971
1117
  }
972
1118
  },
973
- response: raw('日志文件流:.gz 归档为 application/gzip,其余为 text/plain;当前日志只读到请求时的长度')
1119
+ response: raw('日志文件流:.gz 归档为 application/gzip,其余为 text/plain;当前日志只读到请求时的长度'),
1120
+ 'x-mcp-scenarios': ['应用运维'],
1121
+ 'x-mcp-confirm': false
974
1122
  }
975
1123
  },
976
1124
  async (request, reply) => {
@@ -1003,7 +1151,9 @@ module.exports = fp(async (fastify, options) => {
1003
1151
  token: { type: 'string', description: QUERY_TOKEN }
1004
1152
  }
1005
1153
  },
1006
- response: raw('zip 文件流(application/zip,附件名 {name}-logs-{时间}.zip)')
1154
+ response: raw('zip 文件流(application/zip,附件名 {name}-logs-{时间}.zip)'),
1155
+ 'x-mcp-scenarios': ['应用运维'],
1156
+ 'x-mcp-confirm': false
1007
1157
  }
1008
1158
  },
1009
1159
  async (request, reply) => {
@@ -1041,7 +1191,9 @@ module.exports = fp(async (fastify, options) => {
1041
1191
  files: { type: 'array', minItems: 1, items: { type: 'string' }, description: '要删除的归档文件名' }
1042
1192
  }
1043
1193
  },
1044
- response: success('删除结果', obj('删除结果', { removed: strArray('实际删除的文件名(不存在的会跳过)') }))
1194
+ response: success('删除结果', obj('删除结果', { removed: strArray('实际删除的文件名(不存在的会跳过)') })),
1195
+ 'x-mcp-scenarios': ['应用运维'],
1196
+ 'x-mcp-confirm': true
1045
1197
  }
1046
1198
  },
1047
1199
  async request => services.app.removeLogFiles(request.body)
@@ -1064,7 +1216,9 @@ module.exports = fp(async (fastify, options) => {
1064
1216
  token: { type: 'string', description: QUERY_TOKEN }
1065
1217
  }
1066
1218
  },
1067
- response: raw('text/event-stream 事件流')
1219
+ response: raw('text/event-stream 事件流'),
1220
+ 'x-mcp-scenarios': ['应用运维'],
1221
+ 'x-mcp-confirm': false
1068
1222
  }
1069
1223
  },
1070
1224
  async (request, reply) => {
@@ -1131,7 +1285,9 @@ module.exports = fp(async (fastify, options) => {
1131
1285
  current: loadSample,
1132
1286
  pageData: list('最近的采样历史,按时间正序', loadSample)
1133
1287
  })
1134
- )
1288
+ ),
1289
+ 'x-mcp-scenarios': ['应用运维'],
1290
+ 'x-mcp-confirm': false
1135
1291
  }
1136
1292
  },
1137
1293
  async request => services.app.load(request.query)
@@ -1153,7 +1309,9 @@ module.exports = fp(async (fastify, options) => {
1153
1309
  token: { type: 'string', description: QUERY_TOKEN }
1154
1310
  }
1155
1311
  },
1156
- response: raw('text/event-stream 事件流')
1312
+ response: raw('text/event-stream 事件流'),
1313
+ 'x-mcp-scenarios': ['应用运维'],
1314
+ 'x-mcp-confirm': false
1157
1315
  }
1158
1316
  },
1159
1317
  async (request, reply) => {
@@ -41,7 +41,9 @@ module.exports = fp(async (fastify, options) => {
41
41
  pageData: list('表结构', tableInfo),
42
42
  totalCount: num('表数量')
43
43
  })
44
- )
44
+ ),
45
+ 'x-mcp-scenarios': ['应用数据'],
46
+ 'x-mcp-confirm': false
45
47
  }
46
48
  },
47
49
  async request => services.dbops.listTables(request.query)
@@ -63,7 +65,9 @@ module.exports = fp(async (fastify, options) => {
63
65
  mode: { type: 'string', enum: ['union', 'replace'], description: 'union 与已登记的合并(默认),replace 整体替换' }
64
66
  }
65
67
  },
66
- response: success('登记结果', obj('登记结果', { ownedTables: strArray('登记后的所属表'), dbScope: str(DB_SCOPE) }))
68
+ response: success('登记结果', obj('登记结果', { ownedTables: strArray('登记后的所属表'), dbScope: str(DB_SCOPE) })),
69
+ 'x-mcp-scenarios': ['应用数据'],
70
+ 'x-mcp-confirm': true
67
71
  }
68
72
  },
69
73
  async request => services.dbops.registerTables(request.body)
@@ -92,7 +96,9 @@ module.exports = fp(async (fastify, options) => {
92
96
  discovered: strArray('库中扫描到的表(不含系统表)'),
93
97
  claimed: strArray('本次新领取的表')
94
98
  })
95
- )
99
+ ),
100
+ 'x-mcp-scenarios': ['应用数据'],
101
+ 'x-mcp-confirm': true
96
102
  }
97
103
  },
98
104
  async request => services.dbops.syncOwnedFromDatabase(request.body)
@@ -133,7 +139,9 @@ module.exports = fp(async (fastify, options) => {
133
139
  softDeleteField: str('软删除字段名'),
134
140
  softDeleteSupported: bool('表中是否有软删除字段')
135
141
  })
136
- )
142
+ ),
143
+ 'x-mcp-scenarios': ['应用数据'],
144
+ 'x-mcp-confirm': false
137
145
  }
138
146
  },
139
147
  async request => {
@@ -177,7 +185,9 @@ module.exports = fp(async (fastify, options) => {
177
185
  pk: { type: 'string', description: 'JSON primary key object' }
178
186
  }
179
187
  },
180
- response: success('查询结果', obj('查询结果', { data: obj('行数据,不存在为 null'), primaryKey: strArray('主键列名') }))
188
+ response: success('查询结果', obj('查询结果', { data: obj('行数据,不存在为 null'), primaryKey: strArray('主键列名') })),
189
+ 'x-mcp-scenarios': ['应用数据'],
190
+ 'x-mcp-confirm': false
181
191
  }
182
192
  },
183
193
  async request => {
@@ -211,7 +221,9 @@ module.exports = fp(async (fastify, options) => {
211
221
  }
212
222
  }
213
223
  },
214
- response: success('保存结果', obj('保存结果', { data: obj('保存后的行'), action: str('执行的操作:insert 插入,update 更新') }))
224
+ response: success('保存结果', obj('保存结果', { data: obj('保存后的行'), action: str('执行的操作:insert 插入,update 更新') })),
225
+ 'x-mcp-scenarios': ['应用数据'],
226
+ 'x-mcp-confirm': true
215
227
  }
216
228
  },
217
229
  async request => services.dbops.saveRow(request.body)
@@ -242,7 +254,9 @@ module.exports = fp(async (fastify, options) => {
242
254
  mode: str('删除方式:soft 软删除,hard 物理删除'),
243
255
  softDeleteField: str('软删除字段名(软删除时返回)')
244
256
  })
245
- )
257
+ ),
258
+ 'x-mcp-scenarios': ['应用数据'],
259
+ 'x-mcp-confirm': true
246
260
  }
247
261
  },
248
262
  async request => services.dbops.removeRow(request.body)
@@ -265,7 +279,9 @@ module.exports = fp(async (fastify, options) => {
265
279
  pk: { type: 'object', description: '主键对象 { 列名: 值 }' }
266
280
  }
267
281
  },
268
- response: success('恢复结果', obj('恢复结果', { ok: bool('是否成功'), softDeleteField: str('软删除字段名') }))
282
+ response: success('恢复结果', obj('恢复结果', { ok: bool('是否成功'), softDeleteField: str('软删除字段名') })),
283
+ 'x-mcp-scenarios': ['应用数据'],
284
+ 'x-mcp-confirm': true
269
285
  }
270
286
  },
271
287
  async request => services.dbops.restoreRow(request.body)
@@ -297,7 +313,9 @@ module.exports = fp(async (fastify, options) => {
297
313
  rowCount: num('返回的行数'),
298
314
  truncated: bool('是否因超过最大行数被截断')
299
315
  })
300
- )
316
+ ),
317
+ 'x-mcp-scenarios': ['应用数据'],
318
+ 'x-mcp-confirm': true
301
319
  }
302
320
  },
303
321
  async request => services.dbops.runQuery(request.body)
@@ -320,7 +338,9 @@ module.exports = fp(async (fastify, options) => {
320
338
  mode: { type: 'string', enum: ['json', 'file'], description: 'json 按表导出为 JSON 打包成 zip(默认),file 复制 sqlite 文件(仅独享 sqlite 库)' }
321
339
  }
322
340
  },
323
- response: success('导出结果', exportResult)
341
+ response: success('导出结果', exportResult),
342
+ 'x-mcp-scenarios': ['应用数据'],
343
+ 'x-mcp-confirm': true
324
344
  }
325
345
  },
326
346
  async request => services.dbops.exportData(request.body)
@@ -343,7 +363,9 @@ module.exports = fp(async (fastify, options) => {
343
363
  removeSqliteFile: { type: 'boolean', description: '独享 sqlite 库时同时删除数据库文件' }
344
364
  }
345
365
  },
346
- response: success('清理结果', cleanupResult)
366
+ response: success('清理结果', cleanupResult),
367
+ 'x-mcp-scenarios': ['应用数据'],
368
+ 'x-mcp-confirm': true
347
369
  }
348
370
  },
349
371
  async request => services.dbops.cleanup(request.body)
@@ -25,7 +25,9 @@ module.exports = fp(async (fastify, options) => {
25
25
  icon: { type: 'string', description: '可选应用图标(文件 id);未传时从远程应用站点抓取 favicon/manifest 图标并经 saveIconFile 保存,抓取失败则不设置图标' }
26
26
  }
27
27
  },
28
- response: success('导入后的应用', obj({ name: str('应用 name'), kind: str('managed|linked'), status: str('状态') }))
28
+ response: success('导入后的应用', obj({ name: str('应用 name'), kind: str('managed|linked'), status: str('状态') })),
29
+ 'x-mcp-scenarios': ['应用管理'],
30
+ 'x-mcp-confirm': true
29
31
  }
30
32
  },
31
33
  async request => services.link.importByInstallKey(request.body || {})
@@ -39,7 +41,9 @@ module.exports = fp(async (fastify, options) => {
39
41
  tags: [TAG_APP],
40
42
  summary: '同步全部外部关联应用',
41
43
  description: '拉取远程权限树快照、幂等 ensure OIDC,并探测 /ready 写回 status',
42
- response: success('同步结果', any())
44
+ response: success('同步结果', any()),
45
+ 'x-mcp-scenarios': ['应用管理'],
46
+ 'x-mcp-confirm': true
43
47
  }
44
48
  },
45
49
  async () => services.link.syncAllLinked()
@@ -57,7 +61,9 @@ module.exports = fp(async (fastify, options) => {
57
61
  required: ['name'],
58
62
  properties: { name: { type: 'string', description: '应用 name' } }
59
63
  },
60
- response: success('同步结果', any())
64
+ response: success('同步结果', any()),
65
+ 'x-mcp-scenarios': ['应用管理'],
66
+ 'x-mcp-confirm': true
61
67
  }
62
68
  },
63
69
  async request => {
@@ -88,7 +94,9 @@ module.exports = fp(async (fastify, options) => {
88
94
  offset: { type: 'number', description: '偏移' }
89
95
  }
90
96
  },
91
- response: success('审计列表', any())
97
+ response: success('审计列表', any()),
98
+ 'x-mcp-scenarios': ['应用管理'],
99
+ 'x-mcp-confirm': false
92
100
  }
93
101
  },
94
102
  async request => {
@@ -46,7 +46,9 @@ module.exports = fp(async (fastify, options) => {
46
46
  ),
47
47
  totalCount: num('脚本数量')
48
48
  })
49
- )
49
+ ),
50
+ 'x-mcp-scenarios': ['应用部署'],
51
+ 'x-mcp-confirm': false
50
52
  }
51
53
  },
52
54
  async request => services.migration.list(request.query)
@@ -64,7 +66,9 @@ module.exports = fp(async (fastify, options) => {
64
66
  required: ['name', 'file'],
65
67
  properties: Object.assign({}, versionProps, { file: { type: 'string', description: SQL_FILE } })
66
68
  },
67
- response: success('脚本内容', obj('脚本内容', { name: str('文件名'), content: str('SQL 内容') }))
69
+ response: success('脚本内容', obj('脚本内容', { name: str('文件名'), content: str('SQL 内容') })),
70
+ 'x-mcp-scenarios': ['应用部署'],
71
+ 'x-mcp-confirm': false
68
72
  }
69
73
  },
70
74
  async request => services.migration.content(request.query)
@@ -86,7 +90,9 @@ module.exports = fp(async (fastify, options) => {
86
90
  content: { type: 'string', description: 'SQL 内容' }
87
91
  })
88
92
  },
89
- response: success('保存结果', obj('保存结果', { name: str('文件名') }))
93
+ response: success('保存结果', obj('保存结果', { name: str('文件名') })),
94
+ 'x-mcp-scenarios': ['应用部署'],
95
+ 'x-mcp-confirm': true
90
96
  }
91
97
  },
92
98
  async request => services.migration.save(request.body)
@@ -104,7 +110,9 @@ module.exports = fp(async (fastify, options) => {
104
110
  required: ['name', 'versionId', 'file'],
105
111
  properties: Object.assign({}, versionProps, { file: { type: 'string', description: SQL_FILE } })
106
112
  },
107
- response: success('删除结果', obj('删除结果', { name: str('文件名') }))
113
+ response: success('删除结果', obj('删除结果', { name: str('文件名') })),
114
+ 'x-mcp-scenarios': ['应用部署'],
115
+ 'x-mcp-confirm': true
108
116
  }
109
117
  },
110
118
  async request => services.migration.remove(request.body)
@@ -126,7 +134,9 @@ module.exports = fp(async (fastify, options) => {
126
134
  action: { type: 'string', enum: ['execute', 'mark', 'unmark'], description: '操作:execute 执行,mark 标记已执行,unmark 撤销执行记录;linked 应用不传 versionId' }
127
135
  })
128
136
  },
129
- response: success('操作结果', migrationResult)
137
+ response: success('操作结果', migrationResult),
138
+ 'x-mcp-scenarios': ['应用部署'],
139
+ 'x-mcp-confirm': true
130
140
  }
131
141
  },
132
142
  async request => services.migration.action(request.body)
@@ -1,7 +1,7 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const { isLinked, linkedBaseUrl, linkedApiBaseUrl, KIND_LINKED, KIND_MANAGED } = require('../utils/appKind');
3
3
  const { isServed, SERVED_STATUSES } = require('../utils/appAvailability');
4
- const { normalizeMenuManifest, flattenLeafMenus } = require('../utils/menuManifest');
4
+ const { normalizeMenuManifest, flattenLeafMenus, proxyMenuIcons } = require('../utils/menuManifest');
5
5
  const { fetchRemoteModuleConfig } = require('../utils/remoteModuleConfig');
6
6
  const { hasLabels, parseLabelI18n, mergeLabelI18n, appDefaultLabels } = require('../utils/labelI18n');
7
7
 
@@ -136,7 +136,8 @@ module.exports = fp(async (fastify, options) => {
136
136
  baseUrl: base,
137
137
  // 托管应用取当前部署版本;关联应用没有部署记录,取清单声明的 remote.version
138
138
  version: linked ? manifest.remote?.version || null : await currentVersionOf(app),
139
- menus: manifest.menus
139
+ // 关联应用的菜单图标改走网关(同源),见 proxyMenuIcons
140
+ menus: linked && Array.isArray(manifest.menus) ? proxyMenuIcons(manifest.menus, mountPrefix(app.name)) : manifest.menus
140
141
  };
141
142
  // 应用名称多语言:租户配置 > 应用中心配置 > 子应用 manifest 声明
142
143
  const labels = mergeLabelI18n(manifest.labelI18n, app.labelI18n, tenantLabelI18n);
@@ -65,6 +65,88 @@ module.exports = fp(async (fastify, options) => {
65
65
  return response.json();
66
66
  };
67
67
 
68
+ const gatewayPathPrefix = () => String(options.pathPrefix || '/app').replace(/\/$/, '') || '/app';
69
+
70
+ /**
71
+ * 将子应用 OpenAPI paths 改写为宿主网关路径 /app/{name}{originalPath},
72
+ * 便于宿主 @kne/fastify-mcp 用 inject 经网关调用。
73
+ */
74
+ const rewriteFederatedPaths = (spec, { name }) => {
75
+ const prefix = `${gatewayPathPrefix()}/${name}`;
76
+ const appTag = `应用:${name}`;
77
+ const paths = {};
78
+ for (const [apiPath, item] of Object.entries(spec?.paths || {})) {
79
+ const normalized = apiPath.startsWith('/') ? apiPath : `/${apiPath}`;
80
+ const federatedPath = `${prefix}${normalized}`;
81
+ if (!item || typeof item !== 'object') {
82
+ paths[federatedPath] = item;
83
+ continue;
84
+ }
85
+ const next = {};
86
+ for (const [key, value] of Object.entries(item)) {
87
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
88
+ next[key] = value;
89
+ continue;
90
+ }
91
+ const tags = Array.isArray(value.tags) ? value.tags.slice() : [];
92
+ if (!tags.includes(appTag)) {
93
+ tags.push(appTag);
94
+ }
95
+ // 子应用常只有泛化 tags(如「管理后台」);未声明 x-mcp-scenarios 时用应用标签,避免 MCP 目录整片「未分类」
96
+ const existingScenarios = value['x-mcp-scenarios'] ?? value.mcp?.scenarios;
97
+ const mcpScenarios = Array.isArray(existingScenarios) && existingScenarios.length ? existingScenarios : [appTag];
98
+ next[key] = Object.assign({}, value, {
99
+ 'x-app-name': name,
100
+ 'x-mcp-scenarios': mcpScenarios,
101
+ tags
102
+ });
103
+ }
104
+ paths[federatedPath] = next;
105
+ }
106
+ return Object.assign({}, spec, {
107
+ info: Object.assign({}, spec?.info || {}, {
108
+ title: spec?.info?.title ? `${spec.info.title} (via ${name})` : name,
109
+ 'x-app-name': name,
110
+ 'x-federated-path-prefix': prefix
111
+ }),
112
+ paths
113
+ });
114
+ };
115
+
116
+ /** 单应用联邦 OpenAPI(路径已改写) */
117
+ const getFederatedDocument = async ({ name }) => rewriteFederatedPaths(await getDocument({ name }), { name });
118
+
119
+ /**
120
+ * 拉取全部 running 应用的联邦文档。
121
+ * 返回 { apps: [{ name, document }], errors: [{ name, error }], document };
122
+ * document 为合并 paths 的总文档,供宿主一次 seed。
123
+ */
124
+ const federateRunning = async () => {
125
+ const { pageData } = await getAppService().list({ filter: { status: 'running' }, perPage: 1000, currentPage: 1 });
126
+ const apps = [];
127
+ const errors = [];
128
+ const mergedPaths = {};
129
+ for (const row of pageData || []) {
130
+ const name = row.name;
131
+ try {
132
+ const document = await getFederatedDocument({ name });
133
+ apps.push({ name, document });
134
+ Object.assign(mergedPaths, document.paths || {});
135
+ } catch (e) {
136
+ errors.push({ name, error: e.message || String(e) });
137
+ }
138
+ }
139
+ return {
140
+ apps,
141
+ errors,
142
+ document: {
143
+ openapi: '3.0.3',
144
+ info: { title: 'app-manager federated openapi', version: '1.0.0' },
145
+ paths: mergedPaths
146
+ }
147
+ };
148
+ };
149
+
68
150
  /** 以登录用户身份签发访问子应用接口的令牌(在线调试用),返回 { token, expiresAt } */
69
151
  const issueUserToken = async ({ name, userId, tenantId }) => {
70
152
  if (!userId) {
@@ -158,6 +240,16 @@ module.exports = fp(async (fastify, options) => {
158
240
  };
159
241
 
160
242
  Object.assign(fastify[options.name].services, {
161
- openApi: { getDocument, issueUserToken, listRecords, countRecords, saveRecords, removeRecords }
243
+ openApi: {
244
+ getDocument,
245
+ getFederatedDocument,
246
+ federateRunning,
247
+ rewriteFederatedPaths,
248
+ issueUserToken,
249
+ listRecords,
250
+ countRecords,
251
+ saveRecords,
252
+ removeRecords
253
+ }
162
254
  });
163
255
  });
@@ -180,10 +180,30 @@ const flattenLeafMenus = menus => {
180
180
  return output;
181
181
  };
182
182
 
183
+ /**
184
+ * 关联应用(linked)的菜单图标多为相对路径(如 menu-icons/workspace.svg),宿主前端会按应用 baseUrl 解析,
185
+ * 跨域取图会被 CORS 拦截。改写成网关路径 `${prefix}/${icon}`(即 /app/{name}/...),同源访问,由网关转发到子应用。
186
+ * 绝对地址(http(s)、data:)、以 / 开头的路径与不含目录的值(如文件 id)保持不变。
187
+ */
188
+ const isRelativeIconPath = icon => typeof icon === 'string' && icon.includes('/') && !/^([a-z][a-z0-9+.-]*:|\/)/i.test(icon);
189
+
190
+ const proxyMenuIcons = (menus, prefix) =>
191
+ (Array.isArray(menus) ? menus : []).map(menu => {
192
+ const next = Object.assign({}, menu);
193
+ if (isRelativeIconPath(menu.icon)) {
194
+ next.icon = `${prefix}/${menu.icon}`;
195
+ }
196
+ if (Array.isArray(menu.children)) {
197
+ next.children = proxyMenuIcons(menu.children, prefix);
198
+ }
199
+ return next;
200
+ });
201
+
183
202
  module.exports = {
184
203
  MANIFEST_SCHEMA_VERSION,
185
204
  INTEGRATIONS,
186
205
  DEFAULT_PRESET,
187
206
  normalizeMenuManifest,
188
- flattenLeafMenus
207
+ flattenLeafMenus,
208
+ proxyMenuIcons
189
209
  };
package/oidc.js CHANGED
@@ -177,14 +177,11 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
177
177
 
178
178
  const docsTokenCache = new Map();
179
179
 
180
- /** 签发访问子应用 /open-api.json 的服务令牌(audience 为子应用 OIDC_AUDIENCE,scope 为 open-api:read) */
180
+ /** 签发访问子应用 /open-api.json 的服务令牌(audience 按当前 ORIGIN 推导,scope 为 open-api:read) */
181
181
  const getOpenApiToken = async app => {
182
- // app 详情接口会剔除系统注入的 env,audience 按部署时相同规则推导,以资源服务是否已登记判断接入
182
+ // app 详情会剔除系统 env;audience 用 resolveUrls(随宿主 ORIGIN),ORIGIN 变更后补登记资源再签发
183
183
  const { audience } = resolveUrls(app);
184
184
  await oidc().whenReady();
185
- if (!(await oidc().models.resourceServer.findOne({ where: { identifier: audience } }))) {
186
- throw new Error(`应用 ${app.name} 未接入 OIDC(server 未依赖 ${OIDC_PACKAGE} 或尚未部署),无法签发读取文档的令牌`);
187
- }
188
185
  await ensureResourceServer({ identifier: audience, name: app.label || app.name });
189
186
  const cached = docsTokenCache.get(audience);
190
187
  if (cached && cached.expiresAt - 30 * 1000 > Date.now()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.41",
3
+ "version": "0.1.44",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -21,6 +21,7 @@
21
21
  "files": [
22
22
  "index.js",
23
23
  "oidc.js",
24
+ "host.js",
24
25
  "libs",
25
26
  "sql"
26
27
  ],
@@ -49,11 +50,15 @@
49
50
  "@kne/fastify-namespace": "*",
50
51
  "@kne/fastify-sequelize": "*",
51
52
  "fastify-plugin": ">=5",
52
- "@kne/fastify-oidc": "*"
53
+ "@kne/fastify-oidc": "*",
54
+ "@kne/fastify-kv-cache": "*"
53
55
  },
54
56
  "peerDependenciesMeta": {
55
57
  "@kne/fastify-oidc": {
56
58
  "optional": true
59
+ },
60
+ "@kne/fastify-kv-cache": {
61
+ "optional": true
57
62
  }
58
63
  },
59
64
  "devDependencies": {