@kne/fastify-app-manager 0.1.38 → 0.1.39

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.
@@ -71,6 +71,7 @@ const appProps = {
71
71
  id: any('应用 ID'),
72
72
  name: str('应用 name(小写 slug,同时作为访问路径 /app/{name})'),
73
73
  label: str('应用显示名称'),
74
+ labelI18n: obj('应用中心配置的多语言名称(不含租户与子应用声明),没有配置为 null'),
74
75
  domain: str('绑定的域名,未绑定为 null'),
75
76
  icon: str('应用图标(文件 ID 或地址)'),
76
77
  description: str('应用描述'),
@@ -110,15 +111,73 @@ const appListItem = obj('应用', Object.assign({}, appProps, { deployment }));
110
111
  const centerApp = obj('应用中心中的应用', {
111
112
  name: str('应用 name'),
112
113
  label: str('应用显示名称'),
114
+ labelI18n: obj('应用多语言名称(租户配置 > 应用中心配置 > 子应用 menus.json 声明合并后的结果,没有配置为 {}),前端按当前语言取 labelI18n[语言],没有则用 label'),
113
115
  icon: str('应用图标'),
114
116
  description: str('应用描述'),
115
117
  category: any('应用分类:{ code, name } 或分类编码字符串,未设置为 null'),
116
118
  isPublic: bool('是否公开'),
119
+ status: str('应用状态:running 运行中;仅菜单与展示设置场景会带出 error(已挂但有缓存)的应用'),
117
120
  pathUrl: str('访问地址,如 /app/{name}/'),
118
121
  entries: list('开放给前台的应用入口', entry),
119
122
  deployment: obj('正在部署时为 { source },否则为 null', { source: str('部署来源') })
120
123
  });
121
124
 
125
+ const menuNode = obj('菜单节点', {
126
+ key: str('同级唯一 key'),
127
+ fullKey: str('从顶层到本节点的 key 链,以 / 连接,用于路由'),
128
+ label: str('展示名'),
129
+ labelI18n: any('多语言展示名 { [语言]: 文案 }'),
130
+ icon: str('图标标识'),
131
+ permission: str('子应用权限树内的相对权限码,缺省表示开通应用即可见'),
132
+ permissionCode: str('完整权限码:{应用 name}:{permission}'),
133
+ component: str('远程组件模式:src/components 下的组件目录名(仅叶子菜单)'),
134
+ props: any('远程组件模式:传给页面组件的静态 props'),
135
+ path: str('iframe / blank 模式:相对应用根的路径(仅叶子菜单)'),
136
+ children: list('子菜单(最多两级)')
137
+ });
138
+
139
+ const centerMenuApp = obj('应用中心中声明了菜单的应用', {
140
+ name: str('应用 name'),
141
+ label: str('应用显示名称'),
142
+ labelI18n: obj('应用多语言名称(租户配置 > 应用中心配置 > 子应用 menus.json 声明合并后的结果,没有配置为 {}),前端按当前语言取 labelI18n[语言],没有则用 label'),
143
+ icon: str('应用图标'),
144
+ kind: str('managed 托管应用,linked 外部关联应用'),
145
+ status: str('应用状态:running 运行中;error 表示已挂,菜单沿用上一次的快照,进入页面时由前端异步检测并展示错误'),
146
+ integration: str('集成方式:remote 远程组件,iframe,blank 新窗口'),
147
+ baseUrl: str('应用根地址:托管应用为 /app/{name},linked 为其绝对地址'),
148
+ version: str('当前部署版本号,宿主据此判断是否需要重载远程入口'),
149
+ remote: obj('远程组件信息(integration=remote)', {
150
+ name: str('联邦容器名,等于应用 name'),
151
+ preset: str('预设组件名,默认 ComponentPreset'),
152
+ url: str('远程入口基础地址,入口文件为 {url}/remoteEntry.js')
153
+ }),
154
+ apiHost: str('子应用 API 前缀(integration=remote)'),
155
+ menus: list('菜单树', menuNode)
156
+ });
157
+
158
+ const displaySetting = obj('应用在当前租户的展示方式', {
159
+ name: str('应用 name'),
160
+ label: str('应用显示名称'),
161
+ labelI18n: obj('租户为应用配置的多语言名称,如 { "en-US": "Orders" };没有配置为 {}'),
162
+ defaultLabelI18n: obj('不含租户配置的默认多语言名称(应用中心配置覆盖子应用声明),租户编辑名称时可作占位参考'),
163
+ icon: str('应用图标'),
164
+ kind: str('managed 托管应用,linked 外部关联应用'),
165
+ status: str('应用状态:running 运行中;error 表示已挂,菜单沿用上一次的快照'),
166
+ supportsMenu: bool('应用是否声明了可展示的菜单;false 时只能在应用中心展示'),
167
+ menuCount: num('可展示的菜单页面数(叶子菜单)'),
168
+ displayMode: str('当前生效的展示方式:center 应用中心,menu 左菜单'),
169
+ configured: bool('租户是否显式设置过;false 表示使用默认值'),
170
+ menuStatus: str('菜单快照状态:ok / none 未声明 / error 拉取或校验失败'),
171
+ menuError: str('菜单快照失败原因')
172
+ });
173
+
174
+ const appStatus = obj('应用当前可用状态', {
175
+ name: str('应用 name'),
176
+ status: str('应用状态:running / error / stopped / deploying ...'),
177
+ healthy: bool('是否可用:状态为 running 且探测可达'),
178
+ message: str('不可用原因;可用时为 null')
179
+ });
180
+
122
181
  const version = obj('应用版本', {
123
182
  id: any('版本 ID'),
124
183
  appName: str('所属应用 name'),
@@ -222,6 +281,9 @@ module.exports = {
222
281
  appDetail,
223
282
  appListItem,
224
283
  centerApp,
284
+ centerMenuApp,
285
+ displaySetting,
286
+ appStatus,
225
287
  version,
226
288
  logLine,
227
289
  logFile,
@@ -21,6 +21,7 @@ const {
21
21
  } = require('../utils/env');
22
22
  const { readEnvSchema, validateEnv, ENV_SCHEMA_FILE } = require('../utils/envSchema');
23
23
  const { prepareVersionArtifact } = require('../utils/version');
24
+ const { isServed, SERVED_STATUSES } = require('../utils/appAvailability');
24
25
  const { injectEntryHtml } = require('../utils/entryInject');
25
26
  const { ensureLogFiles, readLogTail, readLastLines, appendLog, countLines } = require('../utils/logFiles');
26
27
  const { currentFileName, isCurrentFileName, resolveLogFile, listLogFiles } = require('../utils/logRotate');
@@ -30,6 +31,7 @@ const { readSqlDir, writeSqlDir } = require('../utils/versionSql');
30
31
  const { createDeployProgress } = require('../utils/deployProgress');
31
32
  const pwaDocument = require('@kne/pwa-document');
32
33
  const pm2Util = require('../utils/pm2');
34
+ const { parseLabelI18n, mergeLabelI18n, appDefaultLabels, hasLabels } = require('../utils/labelI18n');
33
35
  const { KIND_MANAGED, KIND_LINKED, isLinked, linkedBaseUrl, assertNotLinked } = require('../utils/appKind');
34
36
 
35
37
  const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
@@ -165,14 +167,27 @@ module.exports = fp(async (fastify, options) => {
165
167
  return app;
166
168
  };
167
169
 
170
+ /** 应用中心配置的多语言名称:空对象与 null 都存 null;不合法 400 */
171
+ const normalizeAppLabels = raw => {
172
+ if (raw === null) {
173
+ return null;
174
+ }
175
+ const { value, error } = parseLabelI18n(raw);
176
+ if (error) {
177
+ httpError(400, error);
178
+ }
179
+ return hasLabels(value) ? value : null;
180
+ };
181
+
168
182
  const create = async data => {
169
- const { name, label, domain, icon, description, category, isPublic, entries, homePath, env, pm2Config, options: appOptions } = data;
183
+ const { name, label, labelI18n, domain, icon, description, category, isPublic, entries, homePath, env, pm2Config, options: appOptions } = data;
170
184
  if (!name || !NAME_RE.test(name)) {
171
185
  httpError(400, 'invalid name: use lowercase slug [a-z0-9-]');
172
186
  }
173
187
  if (!label) {
174
188
  httpError(400, 'label is required');
175
189
  }
190
+ const labels = labelI18n === undefined ? null : normalizeAppLabels(labelI18n);
176
191
  const exists = await models.app.findOne({ where: { name } });
177
192
  if (exists) {
178
193
  httpError(409, `app ${name} already exists`);
@@ -221,6 +236,7 @@ module.exports = fp(async (fastify, options) => {
221
236
  app = await models.app.create({
222
237
  name,
223
238
  label,
239
+ labelI18n: labels,
224
240
  kind: KIND_MANAGED,
225
241
  domain: domain || null,
226
242
  icon: icon || null,
@@ -243,7 +259,7 @@ module.exports = fp(async (fastify, options) => {
243
259
  return toPublicApp(app);
244
260
  };
245
261
 
246
- const save = async ({ name, category, isPublic, entries, homePath, ...data }) => {
262
+ const save = async ({ name, category, isPublic, entries, homePath, labelI18n, ...data }) => {
247
263
  const app = await getByName(name);
248
264
  const omit = ['name', 'port', 'rootPath', 'pm2Name', 'status', 'currentVersionId', 'homePath', 'kind', 'pathUrl', 'openUrl', 'entries', 'category', 'isPublic', 'secretEnvKeys', 'passthroughEnvKeys'];
249
265
  const patch = {};
@@ -253,6 +269,9 @@ module.exports = fp(async (fastify, options) => {
253
269
  }
254
270
  patch[k] = v;
255
271
  }
272
+ if (labelI18n !== undefined) {
273
+ patch.labelI18n = normalizeAppLabels(labelI18n);
274
+ }
256
275
  // 空域名存 null:domain 有唯一约束,多个应用存 '' 会冲突
257
276
  if (patch.domain !== undefined) {
258
277
  patch.domain = patch.domain || null;
@@ -307,7 +326,11 @@ module.exports = fp(async (fastify, options) => {
307
326
  return toPublicApp(app);
308
327
  };
309
328
 
329
+ // linked 应用的状态来自健康检查,子应用重启恢复后在这里补一次复查(节流)
330
+ const recheckLinkedHealth = () => fastify[options.name].services.link?.recheckUnhealthyLinked?.();
331
+
310
332
  const list = async ({ filter = {}, perPage = 20, currentPage = 1 } = {}) => {
333
+ await recheckLinkedHealth();
311
334
  const where = {};
312
335
  if (filter.status) {
313
336
  where.status = filter.status;
@@ -328,26 +351,46 @@ module.exports = fp(async (fastify, options) => {
328
351
  };
329
352
  };
330
353
 
331
- const centerList = async ({ publicOnly = false, request } = {}) => {
332
- const rows = await models.app.findAll({ where: { status: 'running' }, order: [['createdAt', 'DESC']] });
354
+ // 关联应用打开时带上本平台 issuer:远程(standalone + 新版 fastify-oidc)据此用本平台账号登录,不认识该参数的远程忽略
355
+ const withPlatformHint = (url, app) => {
356
+ const issuer = isLinked(app) ? app.options?.oidc?.issuer : null;
357
+ if (!issuer || !url) {
358
+ return url;
359
+ }
360
+ const [head, hash] = String(url).split('#');
361
+ const joined = `${head}${head.includes('?') ? '&' : '?'}oidc_iss=${encodeURIComponent(issuer)}`;
362
+ return hash === undefined ? joined : `${joined}#${hash}`;
363
+ };
364
+
365
+ const centerList = async ({ publicOnly = false, request, includeMenuApps = false, includeUnavailable = false } = {}) => {
366
+ await recheckLinkedHealth();
367
+ // includeUnavailable:挂了(error)但有缓存的应用也返回,供菜单与展示设置按上一次的快照继续提供;应用中心卡片与公开列表只含运行中
368
+ const withDown = includeUnavailable && !publicOnly;
369
+ const rows = await models.app.findAll({ where: { status: withDown ? SERVED_STATUSES : 'running' }, order: [['createdAt', 'DESC']] });
333
370
  let pageData = rows
371
+ .filter(app => (withDown ? isServed(app) : true))
334
372
  .filter(app => !publicOnly || isAppPublic(app))
335
373
  .map(app => {
336
374
  const active = deployProgress.active(app.name);
337
375
  const linked = isLinked(app);
338
376
  const base = linked ? linkedBaseUrl(app) : null;
339
377
  const pathUrl = linked && base ? `${base}/` : `${mountPrefix(app.name)}/`;
340
- const entries = resolveEntries(app).filter(entry => entry.showInCenter);
378
+ const entries = resolveEntries(app)
379
+ .filter(entry => entry.showInCenter)
380
+ .map(entry => Object.assign(entry, { url: withPlatformHint(entry.url, app) }));
381
+ const defaultLabels = appDefaultLabels(app);
341
382
  return {
342
383
  name: app.name,
343
384
  label: app.label,
385
+ ...(hasLabels(defaultLabels) ? { labelI18n: defaultLabels } : {}),
344
386
  kind: linked ? KIND_LINKED : KIND_MANAGED,
387
+ status: app.status,
345
388
  icon: app.icon,
346
389
  description: app.description,
347
390
  category: app.options?.category || null,
348
391
  isPublic: isAppPublic(app),
349
392
  pathUrl,
350
- openUrl: pathUrl,
393
+ openUrl: withPlatformHint(pathUrl, app),
351
394
  entries,
352
395
  deployment: active ? { source: active.source } : null
353
396
  };
@@ -359,6 +402,18 @@ module.exports = fp(async (fastify, options) => {
359
402
  pageData = filtered;
360
403
  }
361
404
  }
405
+ // 租户设置为「左菜单展示」的应用不再出现在应用中心(includeMenuApps 供菜单与展示设置自身使用)
406
+ if (!publicOnly && request && !includeMenuApps) {
407
+ const menuNames = await fastify[options.name].services.menu.menuDisplayedNames({ request, names: pageData.map(item => item.name) });
408
+ if (menuNames.size) {
409
+ pageData = pageData.filter(item => !menuNames.has(item.name));
410
+ }
411
+ }
412
+ // 租户为应用配置的多语言名称覆盖默认名称后随列表下发,前端按当前语言取 labelI18n,没有则用 label
413
+ if (!publicOnly && request) {
414
+ const labels = await fastify[options.name].services.menu.tenantLabels({ request, names: pageData.map(item => item.name) });
415
+ pageData = pageData.map(item => (labels.has(item.name) ? Object.assign({}, item, { labelI18n: mergeLabelI18n(item.labelI18n, labels.get(item.name)) }) : item));
416
+ }
362
417
  return { pageData, totalCount: pageData.length };
363
418
  };
364
419
 
@@ -825,6 +880,13 @@ module.exports = fp(async (fastify, options) => {
825
880
  } catch (e) {
826
881
  fastify.log.warn({ err: e, appId }, 'claim owned tables after ready failed');
827
882
  }
883
+ // 运行后拉取子应用声明的菜单快照,失败只记日志,不影响就绪
884
+ try {
885
+ const menuApp = await models.app.findByPk(appId);
886
+ await fastify[options.name].services.menu.refresh(menuApp);
887
+ } catch (e) {
888
+ fastify.log.warn({ err: e, appId }, 'refresh app menus after ready failed');
889
+ }
828
890
  } else {
829
891
  const again = await getPm2ProcessStatus(app.pm2Name);
830
892
  if (again === 'errored') {
@@ -1455,6 +1517,7 @@ module.exports = fp(async (fastify, options) => {
1455
1517
  const snapshot = app.toJSON();
1456
1518
  await models.appVersion.destroy({ where: { appName: name } });
1457
1519
  await models.appOpenApiRecord.destroy({ where: { appName: name }, force: true });
1520
+ await models.appTenantDisplay.destroy({ where: { appName: name }, force: true });
1458
1521
  if (!linked && app.rootPath) {
1459
1522
  await fs.remove(app.rootPath).catch(() => {});
1460
1523
  }
@@ -43,7 +43,8 @@ module.exports = fp(async (fastify, options) => {
43
43
  const targets = [
44
44
  [models.appVersion, ['fileId', 'migrationFiles', 'envSchema']],
45
45
  [models.appOpenApiRecord, ['searchText']],
46
- [models.app, ['kind']]
46
+ [models.app, ['kind', 'labelI18n']],
47
+ [models.appTenantDisplay, ['labelI18n']]
47
48
  ];
48
49
  for (const [model, names] of targets) {
49
50
  const queryInterface = model.sequelize.getQueryInterface();
@@ -77,6 +78,13 @@ module.exports = fp(async (fastify, options) => {
77
78
  });
78
79
  }
79
80
  }
81
+ // 租户展示设置只配置多语言名称时不记展示方式:displayMode 既有非空约束改为可空(幂等)
82
+ const displayModel = models.appTenantDisplay;
83
+ const displayColumns = await queryInterface.describeTable(displayModel.getTableName());
84
+ const modeAttr = displayModel.rawAttributes.displayMode;
85
+ if (displayColumns[modeAttr.field]?.allowNull === false) {
86
+ await queryInterface.changeColumn(displayModel.getTableName(), modeAttr.field, { type: modeAttr.type, allowNull: true, comment: modeAttr.comment });
87
+ }
80
88
  // 与 model indexes 对齐:老库 addColumn 不会自动建索引
81
89
  const kindAttr = models.app.rawAttributes.kind;
82
90
  if (kindAttr) {
@@ -71,6 +71,36 @@ module.exports = fp(async (fastify, options) => {
71
71
  httpError(400, '未配置 ensureLinkedRegistration,无法完成外部应用 OIDC 登记');
72
72
  };
73
73
 
74
+ /**
75
+ * 关联应用登记进宿主 OIDC 应用注册表:权限树已由权限快照挂在顶层 <name> 下(permissionRoot),
76
+ * 远程回传 tenantSyncUri 时以 independent 登记,宿主租户变更推送给远程,远程把宿主租户同步为只读托管租户
77
+ */
78
+ const registerLinkedOidcApp = async (app, tenantSyncUri) => {
79
+ const register = fastify.oidc?.services?.app?.register;
80
+ const oidcInfo = app.options?.oidc;
81
+ if (typeof register !== 'function' || !tenantSyncUri || !oidcInfo?.serviceClientId) {
82
+ return;
83
+ }
84
+ const current = fastify.oidc.services.app.findByCode?.(app.name);
85
+ if (current && current.status === 'open' && current.tenantSyncUri === tenantSyncUri && current.serviceClientId === oidcInfo.serviceClientId && current.permissions?.root) {
86
+ return;
87
+ }
88
+ try {
89
+ await register({
90
+ serviceClientId: oidcInfo.serviceClientId,
91
+ code: app.name,
92
+ name: app.label || app.name,
93
+ tenantMode: 'independent',
94
+ clientId: oidcInfo.clientId,
95
+ resource: oidcInfo.audience,
96
+ permissionRoot: true,
97
+ tenantSyncUri
98
+ });
99
+ } catch (e) {
100
+ fastify.log.warn({ err: e, app: app.name }, 'linked app oidc register failed');
101
+ }
102
+ };
103
+
74
104
  const getOpsToken = async (app, scope) => {
75
105
  if (typeof options.getOpsServiceToken === 'function') {
76
106
  return options.getOpsServiceToken({ app, scope });
@@ -318,7 +348,8 @@ module.exports = fp(async (fastify, options) => {
318
348
  audience: oidcInfo.audience,
319
349
  clientId: oidcInfo.clientId,
320
350
  serviceClientId: oidcInfo.serviceClientId,
321
- serviceClientSecret: oidcInfo.serviceClientSecret
351
+ serviceClientSecret: oidcInfo.serviceClientSecret,
352
+ appCode: name
322
353
  }),
323
354
  signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
324
355
  });
@@ -342,6 +373,7 @@ module.exports = fp(async (fastify, options) => {
342
373
  });
343
374
  await app.reload();
344
375
  await applyPermissionSnapshot(app, manifest.permissions || []);
376
+ await registerLinkedOidcApp(app, activated.data?.tenantSyncUri);
345
377
  } catch (e) {
346
378
  if (typeof options.onAppRemoved === 'function' && oidcInfo) {
347
379
  try {
@@ -390,8 +422,9 @@ module.exports = fp(async (fastify, options) => {
390
422
 
391
423
  let syncError = null;
392
424
  let remotePerms = app.options?.permissionsSnapshot || app.options?.permissionTree || [];
425
+ let linkStatus = null;
393
426
  try {
394
- await remoteFetch(app, {
427
+ linkStatus = await remoteFetch(app, {
395
428
  path: '/app-ops/link/status',
396
429
  query: { issuer: app.options?.oidc?.issuer },
397
430
  scope: 'app-ops:permissions:read'
@@ -430,14 +463,60 @@ module.exports = fp(async (fastify, options) => {
430
463
  await options.ensureLinkedRegistration({ app, remoteBaseUrl: baseUrl });
431
464
  }
432
465
  await app.reload();
466
+ await registerLinkedOidcApp(app, linkStatus?.tenantSyncUri);
467
+ if (readyOk) {
468
+ await fastify[options.name].services.menu.refresh(app);
469
+ }
433
470
  } catch (e) {
434
471
  fastify.log.warn({ err: e, app: app.name }, 'linked apply snapshot failed');
435
472
  }
473
+ } else if (app.options?.permissionTree && typeof options.onPermissionsSynced === 'function') {
474
+ // 子应用挂了拿不到最新权限:租户权限源只在内存里,宿主重启时若不用上一次的权限树恢复,
475
+ // 该应用的权限会从租户权限树里消失(角色配置看不到,应用还会被当成没有权限树而放行)
476
+ try {
477
+ await options.onPermissionsSynced({ app, tree: app.options.permissionTree, sourceKey: `app:${app.name}` });
478
+ } catch (e) {
479
+ fastify.log.warn({ err: e, app: app.name }, 'linked restore cached permissions failed');
480
+ }
436
481
  }
437
482
 
438
483
  return { name: app.name, ok: readyOk, status: app.status, syncError: syncError?.message || null };
439
484
  };
440
485
 
486
+ const recheckAt = new Map();
487
+ const recheckInflight = new Map();
488
+
489
+ /**
490
+ * 健康检查失败(error)的 linked 应用按需复查:子应用重启恢复后,访问网关或列表即可恢复,不必等定时同步或打开详情。
491
+ * 同一应用 linkRecheckIntervalMs 内最多复查一次,并发请求共用同一次复查。
492
+ */
493
+ const recheckUnhealthy = async app => {
494
+ if (!app || !isLinked(app) || app.status !== 'error') {
495
+ return app;
496
+ }
497
+ if (recheckInflight.has(app.name)) {
498
+ return recheckInflight.get(app.name);
499
+ }
500
+ if (Date.now() - (recheckAt.get(app.name) || 0) < options.linkRecheckIntervalMs) {
501
+ return app;
502
+ }
503
+ recheckAt.set(app.name, Date.now());
504
+ const run = syncOne(app)
505
+ .then(() => app.reload())
506
+ .catch(err => {
507
+ fastify.log.warn({ err, app: app.name }, 'linked app recheck failed');
508
+ return app;
509
+ })
510
+ .finally(() => recheckInflight.delete(app.name));
511
+ recheckInflight.set(app.name, run);
512
+ return run;
513
+ };
514
+
515
+ const recheckUnhealthyLinked = async () => {
516
+ const apps = await models.app.findAll({ where: { kind: KIND_LINKED, status: 'error' } });
517
+ await Promise.all(apps.map(recheckUnhealthy));
518
+ };
519
+
441
520
  const syncAllLinked = async () => {
442
521
  const apps = await models.app.findAll({ where: { kind: KIND_LINKED } });
443
522
  const results = [];
@@ -639,6 +718,8 @@ module.exports = fp(async (fastify, options) => {
639
718
  importByInstallKey,
640
719
  syncOne,
641
720
  syncAllLinked,
721
+ recheckUnhealthy,
722
+ recheckUnhealthyLinked,
642
723
  decodeInstallKey,
643
724
  proxy,
644
725
  remoteFetch,