@kne/fastify-app-manager 0.1.31 → 0.1.33

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
@@ -920,7 +920,7 @@ data: {"name":"demo","ts":1791456608533,...}
920
920
  | 方法签名 | 说明 |
921
921
  |----------|------|
922
922
  | `onReady()` | `ensureSchema` 后连接 PM2、挂 log bus、启动日志切分与负载采样定时器,并 **setImmediate** 异步执行 `recoverOnStartup`,以及一次 `rotateLogs` 与一次 `sampleLoad`(不阻塞父应用 ready) |
923
- | `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增的可空列(当前为 `appVersion.fileId`、`appVersion.migrationFiles`、`appVersion.envSchema`、`appOpenApiRecord.searchText`),可重复执行 |
923
+ | `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增列/可空约束(含 `app.kind`、`appVersion.fileId|migrationFiles|envSchema`、`appOpenApiRecord.searchText`,并把 `port/rootPath/pm2Name` 改为可空),可重复执行;插件 `after` 与 `onReady` 都会调用。离线补齐见包内 `sql/host-upgrade-linked-kind.sql` |
924
924
  | `recoverOnStartup()` | 两路并行:部署目录完好的应用立即 `reconcile`;目录缺失的应用逐个 `restoreArtifact`(需重装依赖,较慢),每补完一个即单独 `syncStatus` 并按需拉起;补不回且原为 `running`/`deploying` 的标记 `error`;两路结束后 `pruneAllVersionArtifacts`。返回 `{ reconciled, restored, pruned }` |
925
925
  | `onClose()` | 停止切分与采样定时器并等待进行中的任务,断开 bus / PM2(由插件 `onClose` 调用) |
926
926
  | `rotateLogs({ now? })` | 立即执行一轮切分 + 压缩 + 保留清理;返回本轮切分的 `[{ name, stream, fileName, reason }]`,`reason` 为 `size` / `daily` |
package/index.js CHANGED
@@ -194,6 +194,18 @@ module.exports = fp(
194
194
  ]
195
195
  });
196
196
 
197
+ // 插件装载完成后立刻补齐老库列(不依赖 onReady);避免 listen 前/竞态请求打到缺 kind 的表
198
+ fastify.after(async () => {
199
+ try {
200
+ const { services } = fastify[options.name] || {};
201
+ if (services?.bootstrap?.ensureSchema) {
202
+ await services.bootstrap.ensureSchema();
203
+ }
204
+ } catch (e) {
205
+ fastify.log.warn({ err: e }, 'ensure app-manager schema failed (after)');
206
+ }
207
+ });
208
+
197
209
  fastify.addHook('onReady', async () => {
198
210
  const { services } = fastify[options.name];
199
211
  await services.bootstrap.onReady();
@@ -67,6 +67,7 @@ const appBodyProps = {
67
67
  category: { type: ['object', 'string', 'null'], description: '应用分类:分组记录(只保留 code、name)或分类编码;null 清空' },
68
68
  isPublic: { type: 'boolean', description: '是否公开,公开的应用未登录也能在应用中心看到;不传视为公开' },
69
69
  entries: entriesSchema,
70
+ homePath: { type: 'string', description: '应用首页路径(相对应用根,默认 /);也可填完整 http(s) URL,详情「主页」Tab 用 iframe 打开' },
70
71
  env: { type: 'object', description: '应用环境变量;值为 ******** 的密钥变量保持原值,PORT 与宿主维护的系统变量会被忽略' },
71
72
  pm2Config: { type: 'object', description: 'PM2 覆盖配置,与插件级 pm2Defaults 合并' },
72
73
  options: { type: 'object', description: '扩展配置(如 secretEnvKeys 指定按密钥处理的变量名)' }
@@ -944,7 +945,16 @@ module.exports = fp(async (fastify, options) => {
944
945
  },
945
946
  async (request, reply) => {
946
947
  const { name, stream } = request.query;
947
- await services.app.detail({ name });
948
+ const app = await services.app.detail({ name });
949
+ if (app.kind === 'linked' || app.options?.kind === 'linked') {
950
+ const user = request.userInfo || request.user;
951
+ return services.link.proxy.logStream(app, {
952
+ reply,
953
+ request,
954
+ stream: stream || 'out',
955
+ actor: services.link.formatActorLabel?.(user) || user?.nickname || user?.email || user?.id || null
956
+ });
957
+ }
948
958
  const sse = createSseReply(reply, { heartbeatMs: options.sseHeartbeatMs });
949
959
  const hub = services.app.getLogHub();
950
960
 
@@ -81,6 +81,18 @@ module.exports = fp(async (fastify, options) => {
81
81
  return result;
82
82
  }, []);
83
83
  };
84
+ /** 详情「主页」Tab / iframe 地址:相对应用根,默认 /;允许完整 http(s) URL */
85
+ const normalizeHomePath = value => {
86
+ if (value == null || value === '') {
87
+ return '/';
88
+ }
89
+ const raw = String(value).trim();
90
+ if (/^https?:\/\//i.test(raw)) {
91
+ return raw.replace(/\/+$/, '') || raw;
92
+ }
93
+ const path = raw.startsWith('/') ? raw : `/${raw}`;
94
+ return path.length > 1 ? path.replace(/\/+$/, '') : '/';
95
+ };
84
96
  const resolveEntries = appLike => {
85
97
  const linked = isLinked(appLike);
86
98
  const remote = linked ? linkedBaseUrl(appLike) : null;
@@ -109,6 +121,7 @@ module.exports = fp(async (fastify, options) => {
109
121
  json.kind = linked ? KIND_LINKED : KIND_MANAGED;
110
122
  json.category = json.options?.category || null;
111
123
  json.isPublic = isAppPublic(json);
124
+ json.homePath = normalizeHomePath(json.options?.homePath);
112
125
  json.entries = resolveEntries(json);
113
126
  return json;
114
127
  };
@@ -122,7 +135,7 @@ module.exports = fp(async (fastify, options) => {
122
135
  };
123
136
 
124
137
  const create = async data => {
125
- const { name, label, domain, icon, description, category, isPublic, entries, env, pm2Config, options: appOptions } = data;
138
+ const { name, label, domain, icon, description, category, isPublic, entries, homePath, env, pm2Config, options: appOptions } = data;
126
139
  if (!name || !NAME_RE.test(name)) {
127
140
  httpError(400, 'invalid name: use lowercase slug [a-z0-9-]');
128
141
  }
@@ -166,6 +179,11 @@ module.exports = fp(async (fastify, options) => {
166
179
  if (entries !== undefined) {
167
180
  normalizedOptions.entries = normalizeEntries(entries);
168
181
  }
182
+ if (homePath !== undefined || normalizedOptions.homePath !== undefined) {
183
+ normalizedOptions.homePath = normalizeHomePath(homePath !== undefined ? homePath : normalizedOptions.homePath);
184
+ } else {
185
+ normalizedOptions.homePath = '/';
186
+ }
169
187
 
170
188
  const app = await models.app.create({
171
189
  name,
@@ -186,9 +204,9 @@ module.exports = fp(async (fastify, options) => {
186
204
  return toPublicApp(app);
187
205
  };
188
206
 
189
- const save = async ({ name, category, isPublic, entries, ...data }) => {
207
+ const save = async ({ name, category, isPublic, entries, homePath, ...data }) => {
190
208
  const app = await getByName(name);
191
- const omit = ['name', 'port', 'rootPath', 'pm2Name', 'status', 'currentVersionId'];
209
+ const omit = ['name', 'port', 'rootPath', 'pm2Name', 'status', 'currentVersionId', 'homePath', 'kind', 'pathUrl', 'openUrl', 'entries', 'category', 'isPublic', 'secretEnvKeys', 'passthroughEnvKeys'];
192
210
  const patch = {};
193
211
  for (const [k, v] of Object.entries(data)) {
194
212
  if (omit.includes(k) || v === undefined) {
@@ -224,6 +242,9 @@ module.exports = fp(async (fastify, options) => {
224
242
  if (entries !== undefined) {
225
243
  patch.options = Object.assign({}, patch.options || app.options || {}, { entries: normalizeEntries(entries) });
226
244
  }
245
+ if (homePath !== undefined) {
246
+ patch.options = Object.assign({}, patch.options || app.options || {}, { homePath: normalizeHomePath(homePath) });
247
+ }
227
248
  await app.update(patch);
228
249
  return toPublicApp(app);
229
250
  };
@@ -716,6 +737,11 @@ module.exports = fp(async (fastify, options) => {
716
737
  if (!app) {
717
738
  return null;
718
739
  }
740
+ if (isLinked(app)) {
741
+ // linked 无 PM2:状态来自远程健康检查与权限同步
742
+ await fastify[options.name].services.link.syncOne(app);
743
+ return toPublicApp(await models.app.findByPk(appId));
744
+ }
719
745
  try {
720
746
  let pm2Status = await getPm2ProcessStatus(app.pm2Name);
721
747
 
@@ -1464,6 +1490,7 @@ module.exports = fp(async (fastify, options) => {
1464
1490
 
1465
1491
  const removeLogFiles = async ({ name, files = [] }) => {
1466
1492
  const app = await getByName(name);
1493
+ assertNotLinked(app, '删除远程日志');
1467
1494
  const targets = [];
1468
1495
  for (const fileName of files) {
1469
1496
  if (isCurrentFileName(fileName)) {
@@ -37,7 +37,7 @@ module.exports = fp(async (fastify, options) => {
37
37
  return models.app.findOne({ where: { pm2Name } });
38
38
  };
39
39
 
40
- /** 宿主 sync() 不会给已有表加列:老库升级时补齐后续新增的可空列 */
40
+ /** 宿主 sync() 不会给已有表加列:老库升级时补齐后续新增列 / 可空约束(幂等) */
41
41
  const ensureSchema = async () => {
42
42
  const { models } = fastify[options.name];
43
43
  const targets = [
@@ -64,6 +64,7 @@ module.exports = fp(async (fastify, options) => {
64
64
  // linked 应用不占本机端口/目录/PM2:将既有非空列改为可空(幂等)
65
65
  const queryInterface = models.app.sequelize.getQueryInterface();
66
66
  const table = models.app.getTableName();
67
+ const tableName = typeof table === 'string' ? table : table.tableName;
67
68
  const columns = await queryInterface.describeTable(table);
68
69
  for (const name of ['port', 'rootPath', 'pm2Name']) {
69
70
  const attr = models.app.rawAttributes[name];
@@ -76,6 +77,16 @@ module.exports = fp(async (fastify, options) => {
76
77
  });
77
78
  }
78
79
  }
80
+ // 与 model indexes 对齐:老库 addColumn 不会自动建索引
81
+ const kindAttr = models.app.rawAttributes.kind;
82
+ if (kindAttr) {
83
+ const indexName = `${tableName}_${kindAttr.field}`;
84
+ const indexes = await queryInterface.showIndex(table);
85
+ const exists = (indexes || []).some(item => item.name === indexName || (item.fields || []).includes(kindAttr.field));
86
+ if (!exists) {
87
+ await queryInterface.addIndex(table, [kindAttr.field], { name: indexName });
88
+ }
89
+ }
79
90
  };
80
91
 
81
92
  const onReady = async () => {
@@ -1,7 +1,8 @@
1
1
  const fp = require('fastify-plugin');
2
- const { KIND_LINKED, isLinked, linkedBaseUrl } = require('../utils/appKind');
2
+ const { KIND_LINKED, isLinked, linkedBaseUrl, linkedApiBaseUrl } = require('../utils/appKind');
3
3
  const { mergeAppPermissionTree } = require('../utils/permissionSnapshot');
4
4
  const { createProxyAuditStore } = require('../utils/proxyAudit');
5
+ const { SYSTEM_ENV_KEYS, DB_CONNECTION_KEYS, DB_DEDICATED_KEY } = require('../utils/env');
5
6
 
6
7
  const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
7
8
 
@@ -80,7 +81,7 @@ module.exports = fp(async (fastify, options) => {
80
81
  };
81
82
 
82
83
  const remoteFetch = async (app, { path: opsPath, method = 'GET', query, body, scope, auditAction, actor } = {}) => {
83
- const baseUrl = linkedBaseUrl(app);
84
+ const baseUrl = linkedApiBaseUrl(app);
84
85
  if (!baseUrl) {
85
86
  httpError(400, '应用缺少 options.baseUrl');
86
87
  }
@@ -146,7 +147,9 @@ module.exports = fp(async (fastify, options) => {
146
147
 
147
148
  const applyPermissionSnapshot = async (app, remotePermissions) => {
148
149
  const previous = app.options?.permissionTree || null;
149
- const tree = mergeAppPermissionTree(app.name, remotePermissions, previous);
150
+ const tree = mergeAppPermissionTree(app.name, remotePermissions, previous, {
151
+ label: app.label || app.name
152
+ });
150
153
  const nextOptions = Object.assign({}, app.options || {}, {
151
154
  permissionsSnapshot: remotePermissions,
152
155
  permissionTree: tree,
@@ -163,7 +166,20 @@ module.exports = fp(async (fastify, options) => {
163
166
  const assertNameAvailable = async name => {
164
167
  const exists = await models.app.findOne({ where: { name } });
165
168
  if (exists) {
166
- httpError(409, `应用 ${name} 已存在`);
169
+ // 上次导入 redeem 成功但 activate 失败时可能残留 pending_activate 半成品,允许覆盖重试
170
+ const linkStatus = exists.options?.linkStatus;
171
+ if (isLinked(exists) && (linkStatus === 'pending_activate' || linkStatus === 'error')) {
172
+ if (typeof options.onAppRemoved === 'function') {
173
+ try {
174
+ await options.onAppRemoved({ app: exists.toJSON ? exists.toJSON() : exists });
175
+ } catch (cleanupErr) {
176
+ fastify.log.warn({ err: cleanupErr }, 'cleanup orphan linked OIDC failed');
177
+ }
178
+ }
179
+ await exists.destroy();
180
+ } else {
181
+ httpError(409, `应用 ${name} 已存在`);
182
+ }
167
183
  }
168
184
  if (typeof options.getPermissionRootCodes === 'function') {
169
185
  const roots = await options.getPermissionRootCodes();
@@ -203,9 +219,13 @@ module.exports = fp(async (fastify, options) => {
203
219
  httpError(400, 'installKey 已过期');
204
220
  }
205
221
  const baseUrl = String(key.baseUrl || '').replace(/\/+$/, '');
222
+ const apiBaseUrl = String(key.apiBaseUrl || key.baseUrl || '').replace(/\/+$/, '');
206
223
  if (!baseUrl) {
207
224
  httpError(400, 'installKey 缺少 baseUrl');
208
225
  }
226
+ if (!apiBaseUrl) {
227
+ httpError(400, 'installKey 缺少 apiBaseUrl');
228
+ }
209
229
  const name = overrideName || slugifyName(key.appName);
210
230
  if (!name || !NAME_RE.test(name)) {
211
231
  httpError(400, '应用 name 无效:请传合法 slug 或远程改名');
@@ -213,7 +233,7 @@ module.exports = fp(async (fastify, options) => {
213
233
  await assertNameAvailable(name);
214
234
 
215
235
  const assertion = await signAssertion(baseUrl);
216
- const redeemRes = await fetch(`${baseUrl}/app-ops/link/redeem`, {
236
+ const redeemRes = await fetch(`${apiBaseUrl}/app-ops/link/redeem`, {
217
237
  method: 'POST',
218
238
  headers: { 'content-type': 'application/json' },
219
239
  body: JSON.stringify({
@@ -243,6 +263,7 @@ module.exports = fp(async (fastify, options) => {
243
263
  options: {
244
264
  kind: KIND_LINKED,
245
265
  baseUrl,
266
+ apiBaseUrl,
246
267
  linkStatus: 'pending_activate',
247
268
  permissionsSnapshot: manifest.permissions || [],
248
269
  capabilities: manifest.capabilities || {},
@@ -260,7 +281,7 @@ module.exports = fp(async (fastify, options) => {
260
281
  try {
261
282
  oidcInfo = await ensureOidc({ app, remoteBaseUrl: baseUrl });
262
283
  const activateAssertion = await signAssertion(baseUrl);
263
- const activateRes = await fetch(`${baseUrl}/app-ops/link/activate`, {
284
+ const activateRes = await fetch(`${apiBaseUrl}/app-ops/link/activate`, {
264
285
  method: 'POST',
265
286
  headers: { 'content-type': 'application/json' },
266
287
  body: JSON.stringify({
@@ -322,6 +343,25 @@ module.exports = fp(async (fastify, options) => {
322
343
  return null;
323
344
  }
324
345
  const baseUrl = linkedBaseUrl(app);
346
+ const apiBaseUrl = linkedApiBaseUrl(app);
347
+ // 运行状态只看 /ready:运维代理偶发失败不应把已配对应用打成「错误」
348
+ let readyOk = false;
349
+ let readyError = null;
350
+ try {
351
+ const ready = await fetch(`${apiBaseUrl}/ready`, { signal: AbortSignal.timeout(5000) });
352
+ const ct = String(ready.headers.get('content-type') || '');
353
+ // 前端 SPA 会对未知路径回 HTML 200,不能当成健康
354
+ readyOk = ready.ok && !ct.includes('text/html');
355
+ if (!readyOk) {
356
+ readyError = ready.ok ? '远程 /ready 返回了非 JSON(可能打到前端)' : `远程健康检查失败 HTTP ${ready.status}`;
357
+ }
358
+ } catch (e) {
359
+ readyOk = false;
360
+ readyError = e.message || '远程健康检查失败';
361
+ }
362
+
363
+ let syncError = null;
364
+ let remotePerms = app.options?.permissionsSnapshot || app.options?.permissionTree || [];
325
365
  try {
326
366
  await remoteFetch(app, {
327
367
  path: '/app-ops/link/status',
@@ -332,38 +372,42 @@ module.exports = fp(async (fastify, options) => {
332
372
  path: '/app-ops/permissions',
333
373
  scope: 'app-ops:permissions:read'
334
374
  });
335
- let readyOk = false;
375
+ remotePerms = perms?.permissions || perms || remotePerms;
376
+ } catch (e) {
377
+ syncError = e;
378
+ fastify.log.warn({ err: e, app: app.name }, 'linked sync ops failed; keep snapshot');
379
+ }
380
+
381
+ const now = new Date().toISOString();
382
+ await app.update({
383
+ status: readyOk ? 'running' : 'error',
384
+ message: readyOk ? (syncError ? `权限同步失败:${syncError.message}` : null) : readyError || syncError?.message || '远程健康检查失败',
385
+ options: Object.assign({}, app.options || {}, {
386
+ linkStatus: readyOk || app.options?.linkStatus === 'paired' ? 'paired' : app.options?.linkStatus || 'error',
387
+ lastHealthAt: now,
388
+ lastHealthOk: readyOk,
389
+ ...(syncError
390
+ ? {}
391
+ : {
392
+ permissionsSyncedAt: now
393
+ })
394
+ })
395
+ });
396
+ await app.reload();
397
+
398
+ if (!syncError) {
336
399
  try {
337
- const ready = await fetch(`${baseUrl}/ready`, { signal: AbortSignal.timeout(5000) });
338
- readyOk = ready.ok;
400
+ await applyPermissionSnapshot(app, remotePerms);
401
+ if (typeof options.ensureLinkedRegistration === 'function') {
402
+ await options.ensureLinkedRegistration({ app, remoteBaseUrl: baseUrl });
403
+ }
404
+ await app.reload();
339
405
  } catch (e) {
340
- readyOk = false;
406
+ fastify.log.warn({ err: e, app: app.name }, 'linked apply snapshot failed');
341
407
  }
342
- await app.update({
343
- status: readyOk ? 'running' : 'error',
344
- message: readyOk ? null : '远程健康检查失败',
345
- options: Object.assign({}, app.options || {}, {
346
- linkStatus: 'paired'
347
- })
348
- });
349
- await app.reload();
350
- const remotePerms = perms?.permissions || perms || app.options?.permissionsSnapshot || [];
351
- await applyPermissionSnapshot(app, remotePerms);
352
- if (typeof options.ensureLinkedRegistration === 'function') {
353
- await options.ensureLinkedRegistration({ app, remoteBaseUrl: baseUrl });
354
- }
355
- await app.reload();
356
- return { name: app.name, ok: true, status: app.status };
357
- } catch (e) {
358
- // 远程不可达:沿用已有 permissionTree / snapshot,不清空
359
- await app
360
- .update({
361
- status: 'error',
362
- message: e.message
363
- })
364
- .catch(() => {});
365
- return { name: app.name, ok: false, error: e.message };
366
408
  }
409
+
410
+ return { name: app.name, ok: readyOk, status: app.status, syncError: syncError?.message || null };
367
411
  };
368
412
 
369
413
  const syncAllLinked = async () => {
@@ -375,12 +419,141 @@ module.exports = fp(async (fastify, options) => {
375
419
  return results.filter(Boolean);
376
420
  };
377
421
 
422
+ /**
423
+ * 透传远程 SSE(logs/stream)。会 hijack reply;超时加长以免掐断长连接。
424
+ */
425
+ const remoteStream = async (app, { path: opsPath, query, scope, reply, request, auditAction, actor } = {}) => {
426
+ const baseUrl = linkedApiBaseUrl(app);
427
+ if (!baseUrl) {
428
+ httpError(400, '应用缺少 options.baseUrl');
429
+ }
430
+ const action = auditAction || opsPath.replace(/^\/app-ops\//, '').replace(/\//g, '.');
431
+ const token = await getOpsToken(app, scope);
432
+ const url = new URL(opsPath.replace(/^\//, ''), `${baseUrl}/`);
433
+ if (query && typeof query === 'object') {
434
+ for (const [k, v] of Object.entries(query)) {
435
+ if (v !== undefined && v !== null && v !== '') {
436
+ url.searchParams.set(k, String(v));
437
+ }
438
+ }
439
+ }
440
+ const abort = new AbortController();
441
+ const onClose = () => abort.abort();
442
+ request.raw.on('close', onClose);
443
+ let response;
444
+ try {
445
+ response = await fetch(url, {
446
+ method: 'GET',
447
+ headers: { authorization: `Bearer ${token}`, accept: 'text/event-stream' },
448
+ signal: abort.signal
449
+ });
450
+ } catch (e) {
451
+ request.raw.off('close', onClose);
452
+ await proxyAudit
453
+ .append({
454
+ appName: app.name,
455
+ action,
456
+ result: 'error',
457
+ statusCode: 502,
458
+ actor,
459
+ detail: e.message
460
+ })
461
+ .catch(() => {});
462
+ httpError(502, e.message || '远程 SSE 连接失败');
463
+ }
464
+ if (!response.ok) {
465
+ request.raw.off('close', onClose);
466
+ const text = await response.text().catch(() => '');
467
+ await proxyAudit
468
+ .append({
469
+ appName: app.name,
470
+ action,
471
+ result: 'error',
472
+ statusCode: response.status,
473
+ actor,
474
+ detail: text.slice(0, 200)
475
+ })
476
+ .catch(() => {});
477
+ httpError(response.status >= 400 && response.status < 600 ? response.status : 502, text || `远程 ${response.status}`);
478
+ }
479
+ await proxyAudit
480
+ .append({
481
+ appName: app.name,
482
+ action,
483
+ result: 'ok',
484
+ statusCode: 200,
485
+ actor
486
+ })
487
+ .catch(() => {});
488
+
489
+ reply.hijack();
490
+ reply.raw.writeHead(200, {
491
+ 'Content-Type': 'text/event-stream; charset=utf-8',
492
+ 'Cache-Control': 'no-cache, no-transform',
493
+ Connection: 'keep-alive',
494
+ 'X-Accel-Buffering': 'no'
495
+ });
496
+
497
+ const { Readable } = require('node:stream');
498
+ const { pipeline } = require('node:stream/promises');
499
+ try {
500
+ const nodeStream = Readable.fromWeb(response.body);
501
+ await pipeline(nodeStream, reply.raw);
502
+ } catch (e) {
503
+ if (!abort.signal.aborted) {
504
+ fastify.log.warn({ err: e, app: app.name }, 'linked logs stream proxy ended');
505
+ }
506
+ } finally {
507
+ request.raw.off('close', onClose);
508
+ try {
509
+ reply.raw.end();
510
+ } catch (e) {
511
+ /* ignore */
512
+ }
513
+ }
514
+ };
515
+
378
516
  const proxy = {
379
517
  logs: (app, query) => remoteFetch(app, { path: '/app-ops/logs', query, scope: 'app-ops:logs:read' }),
380
518
  logFiles: app => remoteFetch(app, { path: '/app-ops/logs/files', scope: 'app-ops:logs:read' }),
381
- env: app => remoteFetch(app, { path: '/app-ops/env', scope: 'app-ops:env:read' }),
519
+ logStream: (app, { reply, request, stream, actor }) =>
520
+ remoteStream(app, {
521
+ path: '/app-ops/logs/stream',
522
+ query: stream ? { stream } : {},
523
+ scope: 'app-ops:logs:read',
524
+ reply,
525
+ request,
526
+ auditAction: 'logs.stream',
527
+ actor
528
+ }),
529
+ env: async app => {
530
+ const remote = await remoteFetch(app, { path: '/app-ops/env', scope: 'app-ops:env:read' });
531
+ // 对齐托管应用 Env:只展示 schema 声明,并隐藏系统注入 / DB 连接等内部项
532
+ const injected = new Set(['PORT', ...SYSTEM_ENV_KEYS, ...DB_CONNECTION_KEYS, DB_DEDICATED_KEY, ...(remote?.injectedKeys || [])]);
533
+ const declared = (remote?.declared || []).filter(item => item && !injected.has(item.key));
534
+ return {
535
+ name: app.name,
536
+ versionId: 'linked',
537
+ version: null,
538
+ hasSchema: remote?.hasSchema !== false && declared.length > 0,
539
+ valid: true,
540
+ readOnly: true,
541
+ declared,
542
+ others: []
543
+ };
544
+ },
382
545
  permissions: app => remoteFetch(app, { path: '/app-ops/permissions', scope: 'app-ops:permissions:read' }),
383
- dbTables: app => remoteFetch(app, { path: '/app-ops/db/tables', scope: 'app-ops:db:read' }),
546
+ dbTables: async app => {
547
+ const data = await remoteFetch(app, { path: '/app-ops/db/tables', scope: 'app-ops:db:read' });
548
+ // 兼容远程曾返回 name 的旧形,统一成 DataOps 使用的 table
549
+ if (data?.pageData) {
550
+ data.pageData = data.pageData.map(row => Object.assign({}, row, { table: row.table || row.name }));
551
+ }
552
+ return Object.assign({}, data, {
553
+ dbScope: data?.dbScope || 'remote',
554
+ readOnly: true
555
+ });
556
+ },
384
557
  dbRows: (app, query) => remoteFetch(app, { path: '/app-ops/db/rows', query, scope: 'app-ops:db:read' }),
385
558
  dbQuery: (app, body) => remoteFetch(app, { path: '/app-ops/db/query', method: 'POST', body, scope: 'app-ops:db:read' }),
386
559
  dbSaveRow: (app, body) => remoteFetch(app, { path: '/app-ops/db/row/save', method: 'POST', body, scope: 'app-ops:db:write' }),
@@ -390,6 +563,49 @@ module.exports = fp(async (fastify, options) => {
390
563
  migrationsAction: (app, body) => remoteFetch(app, { path: '/app-ops/migrations/action', method: 'POST', body, scope: 'app-ops:migrations:execute' })
391
564
  };
392
565
 
566
+ const looksLikeUserId = value => /^\d{10,}$/.test(String(value || ''));
567
+
568
+ /** 操作者展示:昵称 / 邮箱 / 手机,避免审计列表只剩雪花 id */
569
+ const formatActorLabel = user => {
570
+ if (!user) {
571
+ return null;
572
+ }
573
+ return user.nickname || user.email || user.phone || user.username || (user.id != null ? String(user.id) : null);
574
+ };
575
+
576
+ const listProxyAudit = async props => {
577
+ const result = await proxyAudit.list(props);
578
+ const ids = [
579
+ ...new Set(
580
+ (result.pageData || [])
581
+ .map(row => row.actor)
582
+ .filter(looksLikeUserId)
583
+ .map(String)
584
+ )
585
+ ];
586
+ const User = fastify.account?.models?.user;
587
+ if (!ids.length || !User) {
588
+ return result;
589
+ }
590
+ try {
591
+ const users = await User.findAll({
592
+ where: { id: ids },
593
+ attributes: ['id', 'nickname', 'email', 'phone']
594
+ });
595
+ const labelById = new Map(users.map(u => [String(u.id), formatActorLabel(u)]));
596
+ return {
597
+ ...result,
598
+ pageData: (result.pageData || []).map(row => {
599
+ const label = labelById.get(String(row.actor));
600
+ return label ? Object.assign({}, row, { actor: label, actorId: row.actor }) : row;
601
+ })
602
+ };
603
+ } catch (e) {
604
+ fastify.log.warn({ err: e }, 'link audit enrich actor failed');
605
+ return result;
606
+ }
607
+ };
608
+
393
609
  Object.assign(fastify[options.name].services, {
394
610
  link: {
395
611
  importByInstallKey,
@@ -398,7 +614,9 @@ module.exports = fp(async (fastify, options) => {
398
614
  decodeInstallKey,
399
615
  proxy,
400
616
  remoteFetch,
401
- listProxyAudit: proxyAudit.list,
617
+ remoteStream,
618
+ listProxyAudit,
619
+ formatActorLabel,
402
620
  applyPermissionSnapshot
403
621
  }
404
622
  });
@@ -15,7 +15,7 @@ module.exports = fp(async (fastify, options) => {
15
15
  throw err;
16
16
  };
17
17
 
18
- const { isLinked, linkedBaseUrl } = require('../utils/appKind');
18
+ const { isLinked, linkedApiBaseUrl } = require('../utils/appKind');
19
19
 
20
20
  const getRunningApp = async (name, hook) => {
21
21
  if (typeof options[hook] !== 'function') {
@@ -30,7 +30,7 @@ module.exports = fp(async (fastify, options) => {
30
30
 
31
31
  const openApiUrl = app => {
32
32
  if (isLinked(app)) {
33
- const base = linkedBaseUrl(app);
33
+ const base = linkedApiBaseUrl(app);
34
34
  if (!base) {
35
35
  httpError(400, `应用 ${app.name} 缺少 options.baseUrl`);
36
36
  }
@@ -43,11 +43,16 @@ module.exports = fp(async (fastify, options) => {
43
43
  const getDocument = async ({ name }) => {
44
44
  const app = await getRunningApp(name, 'getOpenApiToken');
45
45
  const token = await options.getOpenApiToken(app);
46
- const response = await fetch(openApiUrl(app), {
46
+ const docUrl = openApiUrl(app);
47
+ const response = await fetch(docUrl, {
47
48
  headers: { authorization: `Bearer ${token}` },
48
49
  signal: AbortSignal.timeout(15000)
49
50
  });
50
- const isJson = String(response.headers.get('content-type') || '').includes('application/json');
51
+ const contentType = String(response.headers.get('content-type') || '');
52
+ const isJson = contentType.includes('application/json');
53
+ if (response.ok && contentType.includes('text/html')) {
54
+ httpError(400, `应用 ${name} 的 ${docUrl} 返回了前端页面而非 OpenAPI:请配置 options.apiBaseUrl 指向 API 端口,或让前端把 /open-api.json 代理到后端`);
55
+ }
51
56
  if (response.status === 404 || (response.ok && !isJson)) {
52
57
  httpError(400, `应用 ${name} 未开启 /open-api.json:需 @kne/fastify-app-runtime >=0.1.1、server 最前面注册 @fastify/swagger 且注册了 account 模块`);
53
58
  }
@@ -15,6 +15,12 @@ const linkedBaseUrl = appLike => {
15
15
  return url ? String(url).replace(/\/+$/, '') : null;
16
16
  };
17
17
 
18
+ /** 宿主服务端调远程(app-ops / open-api / ready)用;本地 ORIGIN 为前端端口时可与 baseUrl 不同 */
19
+ const linkedApiBaseUrl = appLike => {
20
+ const url = appLike?.options?.apiBaseUrl || appLike?.apiBaseUrl || linkedBaseUrl(appLike);
21
+ return url ? String(url).replace(/\/+$/, '') : null;
22
+ };
23
+
18
24
  const assertNotLinked = (appLike, action) => {
19
25
  if (isLinked(appLike)) {
20
26
  const err = new Error(`外部关联应用不支持${action || '该操作'}`);
@@ -29,5 +35,6 @@ module.exports = {
29
35
  normalizeKind,
30
36
  isLinked,
31
37
  linkedBaseUrl,
38
+ linkedApiBaseUrl,
32
39
  assertNotLinked
33
40
  };
@@ -53,41 +53,53 @@ const asModulesTree = permissions => {
53
53
  return { modules: [] };
54
54
  };
55
55
 
56
+ /** 外部应用顶层排在平台自有权限之后(tenant mergePermissions 按 index 降序) */
57
+ const LINKED_APP_ROOT_INDEX = -1000;
58
+
56
59
  /**
57
60
  * @param {string} appName
58
61
  * @param {object|array} remotePermissions 远程返回
59
62
  * @param {object|null} previousTree 上一份已规范树(含顶层 appName)
63
+ * @param {{ label?: string, index?: number }} [meta] label 用应用显示名,勿用 slug
60
64
  */
61
- const mergeAppPermissionTree = (appName, remotePermissions, previousTree = null) => {
65
+ const mergeAppPermissionTree = (appName, remotePermissions, previousTree = null, meta = {}) => {
62
66
  const name = String(appName);
63
67
  const remote = asModulesTree(remotePermissions);
64
68
  const liveCodes = flattenCodes(remote);
65
- // 远程子树挂到 appName 顶层下;若远程已自带同名顶层则直接用
69
+ const prevRoot = previousTree?.modules?.[0];
70
+ const displayName = (meta.label && String(meta.label).trim()) || (prevRoot?.name && prevRoot.name !== name ? prevRoot.name : null) || name;
71
+ const rootIndex = meta.index != null ? meta.index : LINKED_APP_ROOT_INDEX;
72
+
73
+ // 远程子树挂到 appName 顶层下;若远程已自带同名顶层则取其 children,但 name 仍用应用显示名
66
74
  let children = remote.modules;
67
75
  if (children.length === 1 && children[0].code === name) {
68
76
  children = children[0].modules || children[0].permissions ? [children[0]] : children;
69
77
  if (children[0].code === name) {
70
- const root = Object.assign({}, children[0], { modules: markStaleDeep(children[0].modules || [], liveCodes) });
78
+ const root = Object.assign({}, children[0], {
79
+ name: displayName,
80
+ code: name,
81
+ index: rootIndex,
82
+ modules: markStaleDeep(children[0].modules || [], liveCodes)
83
+ });
71
84
  // 合并 previous 中已 stale 但仍存在的叶子
72
- if (previousTree?.modules?.[0]?.code === name) {
73
- root.modules = mergeMissingStale(root.modules || [], previousTree.modules[0].modules || [], liveCodes);
85
+ if (prevRoot?.code === name) {
86
+ root.modules = mergeMissingStale(root.modules || [], prevRoot.modules || [], liveCodes);
74
87
  }
75
88
  return { modules: [root] };
76
89
  }
77
90
  }
78
91
 
79
92
  let modules = markStaleDeep(children, liveCodes);
80
- if (previousTree?.modules?.[0]?.code === name) {
81
- modules = mergeMissingStale(modules, previousTree.modules[0].modules || [], liveCodes);
93
+ if (prevRoot?.code === name) {
94
+ modules = mergeMissingStale(modules, prevRoot.modules || [], liveCodes);
82
95
  }
83
96
 
84
- const label = (previousTree?.modules?.[0] && previousTree.modules[0].name) || (remote.modules?.[0] && remote.modules[0].name) || name;
85
-
86
97
  return {
87
98
  modules: [
88
99
  {
89
- name: label,
100
+ name: displayName,
90
101
  code: name,
102
+ index: rootIndex,
91
103
  modules
92
104
  }
93
105
  ]
@@ -136,5 +148,6 @@ module.exports = {
136
148
  flattenCodes,
137
149
  asModulesTree,
138
150
  mergeAppPermissionTree,
139
- topLevelCodes
151
+ topLevelCodes,
152
+ LINKED_APP_ROOT_INDEX
140
153
  };
package/oidc.js CHANGED
@@ -123,8 +123,13 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
123
123
  }
124
124
  };
125
125
 
126
- const ensureServiceClient = async ({ clientId, clientName }) => {
126
+ /**
127
+ * 子应用服务 client:始终可访问宿主 serviceAudience;
128
+ * 另可合并应用自身 audience(linked 运维代理 / central 调本应用 API 需要)。
129
+ */
130
+ const ensureServiceClient = async ({ clientId, clientName, allowedResources: extraResources = [] } = {}) => {
127
131
  const { models, services, options } = oidc();
132
+ const resources = Array.from(new Set([serviceAudience, ...[].concat(extraResources || [])].filter(Boolean)));
128
133
  const existing = await models.client.findOne({ where: { clientId } });
129
134
  if (!existing) {
130
135
  const clientSecret = oidcCrypto().randomSecret(32);
@@ -133,11 +138,16 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
133
138
  clientName,
134
139
  clientSecret,
135
140
  metadata: { grant_types: ['client_credentials'], response_types: [], token_endpoint_auth_method: 'client_secret_basic' },
136
- allowedResources: [serviceAudience],
141
+ allowedResources: resources,
137
142
  description: '应用中心子应用自动登记'
138
143
  });
139
144
  return clientSecret;
140
145
  }
146
+ const current = existing.allowedResources || [];
147
+ const missing = resources.filter(item => !current.includes(item));
148
+ if (missing.length) {
149
+ await services.client.save({ id: existing.id, allowedResources: [...current, ...missing] });
150
+ }
141
151
  // 以认证管理中的实际 secret 为准(管理员可能重置过)
142
152
  return oidcCrypto().decrypt(options.keyEncryptionSecret, existing.clientSecret);
143
153
  };
@@ -254,7 +264,11 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
254
264
  metadata: spaMetadata(urls, upstreamUrl),
255
265
  allowedResources: [urls.audience]
256
266
  });
257
- const serviceSecret = await ensureServiceClient({ clientId: ids.service, clientName: `${app.label || app.name} 服务端` });
267
+ const serviceSecret = await ensureServiceClient({
268
+ clientId: ids.service,
269
+ clientName: `${app.label || app.name} 服务端`,
270
+ allowedResources: [urls.audience]
271
+ });
258
272
 
259
273
  return Object.assign(
260
274
  {
@@ -320,7 +334,8 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
320
334
  });
321
335
  const serviceClientSecret = await ensureServiceClient({
322
336
  clientId: ids.service,
323
- clientName: `${app.label || app.name} 服务端`
337
+ clientName: `${app.label || app.name} 服务端`,
338
+ allowedResources: [urls.audience]
324
339
  });
325
340
  await ensureDocsClient(urls.audience);
326
341
  return {
@@ -336,10 +351,13 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
336
351
  const getServiceToken = async ({ app, scope }) => {
337
352
  const audience = app.env?.OIDC_AUDIENCE || app.options?.oidc?.audience || resolveUrls(app).audience;
338
353
  const clientId = app.env?.OIDC_SERVICE_CLIENT_ID || app.options?.oidc?.serviceClientId || clientIds(app.name).service;
339
- let clientSecret = app.options?.oidc?.serviceClientSecret;
340
- if (!clientSecret) {
341
- clientSecret = await ensureServiceClient({ clientId, clientName: `${app.label || app.name} 服务端` });
342
- }
354
+ // 即使已有 secret,也要确保 allowedResources 含应用 audience(旧数据可能只有宿主 serviceAudience)
355
+ const clientSecret =
356
+ (await ensureServiceClient({
357
+ clientId,
358
+ clientName: `${app.label || app.name} 服务端`,
359
+ allowedResources: [audience]
360
+ })) || app.options?.oidc?.serviceClientSecret;
343
361
  await ensureResourceServer({ identifier: audience, name: app.label || app.name, extraScopes: APP_OPS_SCOPES });
344
362
  const response = await fastify.inject({
345
363
  method: 'POST',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -21,7 +21,8 @@
21
21
  "files": [
22
22
  "index.js",
23
23
  "oidc.js",
24
- "libs"
24
+ "libs",
25
+ "sql"
25
26
  ],
26
27
  "repository": {
27
28
  "type": "git",
@@ -0,0 +1,28 @@
1
+ -- 宿主库升级脚本(可选):当 ensureSchema 未跑到、或需离线补齐时执行。
2
+ -- 默认表前缀 t_app_manager_;若宿主传了 dbTableNamePrefix / DB_TABLE_PREFIX,请改表名。
3
+ -- 幂等。对应 @kne/fastify-app-manager >= 0.1.30 libs/models/app.js
4
+
5
+ DO $$
6
+ BEGIN
7
+ IF EXISTS (
8
+ SELECT 1 FROM information_schema.tables
9
+ WHERE table_schema = 'public' AND table_name = 't_app_manager_app'
10
+ ) THEN
11
+ ALTER TABLE t_app_manager_app
12
+ ADD COLUMN IF NOT EXISTS kind VARCHAR(255) NOT NULL DEFAULT 'managed';
13
+ COMMENT ON COLUMN t_app_manager_app.kind IS 'managed=本机托管 | linked=外部关联';
14
+
15
+ ALTER TABLE t_app_manager_app ALTER COLUMN port DROP NOT NULL;
16
+ ALTER TABLE t_app_manager_app ALTER COLUMN root_path DROP NOT NULL;
17
+ ALTER TABLE t_app_manager_app ALTER COLUMN pm2_name DROP NOT NULL;
18
+
19
+ IF NOT EXISTS (
20
+ SELECT 1 FROM pg_indexes
21
+ WHERE schemaname = 'public'
22
+ AND tablename = 't_app_manager_app'
23
+ AND indexname = 't_app_manager_app_kind'
24
+ ) THEN
25
+ CREATE INDEX t_app_manager_app_kind ON t_app_manager_app (kind);
26
+ END IF;
27
+ END IF;
28
+ END $$;