@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.
@@ -0,0 +1,400 @@
1
+ const fp = require('fastify-plugin');
2
+ const { isLinked, linkedBaseUrl, linkedApiBaseUrl, KIND_LINKED, KIND_MANAGED } = require('../utils/appKind');
3
+ const { isServed, SERVED_STATUSES } = require('../utils/appAvailability');
4
+ const { normalizeMenuManifest, flattenLeafMenus } = require('../utils/menuManifest');
5
+ const { hasLabels, parseLabelI18n, mergeLabelI18n, appDefaultLabels } = require('../utils/labelI18n');
6
+
7
+ /** 拉取失败或没有菜单声明的应用,间隔多久再尝试一次懒拉取 */
8
+ const SNAPSHOT_RETRY_MS = 5 * 60 * 1000;
9
+ const FETCH_TIMEOUT_MS = 5000;
10
+ /** 状态检测的探测超时:前端异步调用,宁短勿长 */
11
+ const PROBE_TIMEOUT_MS = 3000;
12
+ const DISPLAY_MODES = ['center', 'menu'];
13
+
14
+ module.exports = fp(async (fastify, options) => {
15
+ const { models } = fastify[options.name];
16
+ const getServices = () => fastify[options.name].services;
17
+
18
+ const httpError = (statusCode, message) => {
19
+ if (fastify.httpErrors) {
20
+ if (statusCode === 400) throw fastify.httpErrors.badRequest(message);
21
+ if (statusCode === 403) throw fastify.httpErrors.forbidden(message);
22
+ if (statusCode === 404) throw fastify.httpErrors.notFound(message);
23
+ }
24
+ const err = new Error(message);
25
+ err.statusCode = statusCode;
26
+ throw err;
27
+ };
28
+
29
+ /** 读取子应用 manifest 原文;没有声明(404)返回 null */
30
+ const fetchRaw = async app => {
31
+ if (isLinked(app)) {
32
+ try {
33
+ return await getServices().link.remoteFetch(app, { path: '/app-ops/menus', scope: 'app-ops:permissions:read', auditAction: 'menus.read' });
34
+ } catch (e) {
35
+ if (e.statusCode === 404) {
36
+ return null;
37
+ }
38
+ throw e;
39
+ }
40
+ }
41
+ const headers = {};
42
+ if (typeof options.getOpenApiToken === 'function') {
43
+ headers.authorization = `Bearer ${await options.getOpenApiToken(app)}`;
44
+ }
45
+ const response = await fetch(`http://${options.upstreamHost}:${app.port}/open-menus.json`, {
46
+ headers,
47
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
48
+ });
49
+ const contentType = String(response.headers.get('content-type') || '');
50
+ if (response.status === 404 || (response.ok && !contentType.includes('application/json'))) {
51
+ // 子应用没有声明菜单:SPA fallback 会对未知路径回 HTML,同样视为未声明
52
+ return null;
53
+ }
54
+ if (!response.ok) {
55
+ throw new Error(`HTTP ${response.status} ${(await response.text()).slice(0, 200)}`);
56
+ }
57
+ return response.json();
58
+ };
59
+
60
+ const saveSnapshot = async (app, snapshot) => {
61
+ await app.update({ options: Object.assign({}, app.options || {}, { menuSnapshot: snapshot }) });
62
+ await app.reload();
63
+ return snapshot;
64
+ };
65
+
66
+ /**
67
+ * 拉取并保存菜单快照。
68
+ * 没有声明:status=none;拉取或校验失败:status=error,保留上一份可用 manifest,避免短暂故障让菜单消失。
69
+ */
70
+ const refresh = async app => {
71
+ const previous = app.options?.menuSnapshot || null;
72
+ const fetchedAt = new Date().toISOString();
73
+ try {
74
+ const raw = await fetchRaw(app);
75
+ if (raw == null) {
76
+ return await saveSnapshot(app, { status: 'none', fetchedAt, manifest: null });
77
+ }
78
+ const { ok, manifest, errors } = normalizeMenuManifest(raw, { appName: app.name, kind: isLinked(app) ? KIND_LINKED : KIND_MANAGED });
79
+ if (!ok) {
80
+ fastify.log.warn({ app: app.name, errors }, 'app menus manifest invalid');
81
+ return await saveSnapshot(app, { status: 'error', fetchedAt, error: errors.join(';'), manifest: previous?.manifest || null });
82
+ }
83
+ return await saveSnapshot(app, { status: 'ok', fetchedAt, manifest });
84
+ } catch (e) {
85
+ fastify.log.warn({ err: e, app: app.name }, 'fetch app menus failed');
86
+ return await saveSnapshot(app, { status: 'error', fetchedAt, error: e.message, manifest: previous?.manifest || null });
87
+ }
88
+ };
89
+
90
+ const shouldRetry = snapshot => {
91
+ if (!snapshot) {
92
+ return true;
93
+ }
94
+ if (snapshot.status === 'ok') {
95
+ return false;
96
+ }
97
+ return Date.now() - new Date(snapshot.fetchedAt || 0).getTime() > SNAPSHOT_RETRY_MS;
98
+ };
99
+
100
+ /**
101
+ * 读快照;从未拉取或失败/未声明已过冷却期时懒拉取(让升级本插件后无需重新部署也能生效)。
102
+ * 应用不在运行中(挂了)时不拉取,直接用上一次拿到的快照,避免每次请求都等一次必然超时的拉取。
103
+ */
104
+ const getSnapshot = async app => {
105
+ const snapshot = app.options?.menuSnapshot || null;
106
+ return app.status === 'running' && shouldRetry(snapshot) ? refresh(app) : snapshot;
107
+ };
108
+
109
+ const currentVersionOf = async app => {
110
+ if (!app.currentVersionId) {
111
+ return null;
112
+ }
113
+ const version = await models.appVersion.findByPk(app.currentVersionId);
114
+ return version ? version.version : null;
115
+ };
116
+
117
+ const buildItem = async (app, snapshot, tenantLabelI18n) => {
118
+ const { mountPrefix } = getServices().app;
119
+ const manifest = snapshot.manifest;
120
+ const linked = isLinked(app);
121
+ const base = linked ? linkedBaseUrl(app) : mountPrefix(app.name);
122
+ const item = {
123
+ name: app.name,
124
+ label: app.label,
125
+ icon: app.icon,
126
+ kind: linked ? KIND_LINKED : KIND_MANAGED,
127
+ status: app.status,
128
+ integration: manifest.integration,
129
+ baseUrl: base,
130
+ // 托管应用取当前部署版本;关联应用没有部署记录,取清单声明的 remote.version
131
+ version: linked ? manifest.remote?.version || null : await currentVersionOf(app),
132
+ menus: manifest.menus
133
+ };
134
+ // 应用名称多语言:租户配置 > 应用中心配置 > 子应用 manifest 声明
135
+ const labels = mergeLabelI18n(manifest.labelI18n, app.labelI18n, tenantLabelI18n);
136
+ if (hasLabels(labels)) {
137
+ item.labelI18n = labels;
138
+ }
139
+ if (manifest.integration === 'remote') {
140
+ item.remote = {
141
+ name: manifest.remote.name,
142
+ preset: manifest.remote.preset,
143
+ url: linked ? manifest.remote.url : base
144
+ };
145
+ // 接口一律走网关 /app/{name}:同源免跨域,网关把宿主登录令牌换成子应用令牌(关联应用再转到其 apiBaseUrl)
146
+ item.apiHost = mountPrefix(app.name);
147
+ }
148
+ return item;
149
+ };
150
+
151
+ const defaultMode = () => (options.defaultDisplayMode === 'menu' ? 'menu' : 'center');
152
+
153
+ const tenantIdOf = async request => {
154
+ if (request && typeof options.getTenantId === 'function') {
155
+ const tenantId = await options.getTenantId({ request });
156
+ return tenantId ? String(tenantId) : '';
157
+ }
158
+ return '';
159
+ };
160
+
161
+ const snapshotHasMenus = app => {
162
+ const manifest = app.options?.menuSnapshot?.manifest;
163
+ return !!(manifest && Array.isArray(manifest.menus) && manifest.menus.length);
164
+ };
165
+
166
+ /** 当前租户的展示设置行:应用 name -> { displayMode, labelI18n };只设置过多语言名称的应用 displayMode 为空 */
167
+ const loadConfigured = async ({ tenantId, names }) => {
168
+ if (!names.length) {
169
+ return new Map();
170
+ }
171
+ const rows = await models.appTenantDisplay.findAll({ where: { tenantId, appName: names } });
172
+ return new Map(rows.map(row => [row.appName, { displayMode: row.displayMode || null, labelI18n: row.labelI18n || null }]));
173
+ };
174
+
175
+ const configuredMode = (configured, name) => configured.get(name)?.displayMode || null;
176
+
177
+ /** 当前租户为应用配置的多语言名称:应用 name -> { 语言: 名称 },没有配置的应用不在其中 */
178
+ const tenantLabels = async ({ request, names }) => {
179
+ const configured = await loadConfigured({ tenantId: await tenantIdOf(request), names });
180
+ return new Map([...configured].filter(([, row]) => hasLabels(row.labelI18n)).map(([name, row]) => [name, row.labelI18n]));
181
+ };
182
+
183
+ /** 生效的展示方式:没有可展示菜单的应用只能在应用中心 */
184
+ const effectiveMode = (app, configured) => (snapshotHasMenus(app) ? configuredMode(configured, app.name) || defaultMode() : 'center');
185
+
186
+ /** 当前租户下以「左菜单」展示的应用 name 集合,应用中心据此隐藏这些应用 */
187
+ const menuDisplayedNames = async ({ request, names }) => {
188
+ if (!names.length) {
189
+ return new Set();
190
+ }
191
+ const [rows, configured] = await Promise.all([models.app.findAll({ where: { name: names } }), loadConfigured({ tenantId: await tenantIdOf(request), names })]);
192
+ return new Set(rows.filter(app => effectiveMode(app, configured) === 'menu').map(app => app.name));
193
+ };
194
+
195
+ /**
196
+ * 展示设置的管理范围:canManageDisplay 放行(超级管理员)且显式传了 tenantId 时,管理该租户;
197
+ * 否则只涉及当前登录租户,且不允许写入(写入要求 admin)。
198
+ */
199
+ const displayScope = async ({ request, tenantId }) => {
200
+ const requested = tenantId ? String(tenantId) : '';
201
+ const admin = !!requested && typeof options.canManageDisplay === 'function' && !!(await options.canManageDisplay({ request, tenantId: requested }));
202
+ return admin ? { tenantId: requested, admin } : { tenantId: await tenantIdOf(request), admin: false };
203
+ };
204
+
205
+ /**
206
+ * 管理范围内可提供的应用(运行中,或挂了但有缓存):管理员管理租户时列出全部(展示设置不受租户开通影响),否则按当前租户可见范围。
207
+ * 应用挂了不影响菜单与展示设置,沿用上一次的菜单快照。
208
+ */
209
+ const scopedServedApps = async (scope, request) => {
210
+ if (scope.admin) {
211
+ await getServices().link?.recheckUnhealthyLinked?.();
212
+ const rows = await models.app.findAll({ where: { status: SERVED_STATUSES }, order: [['createdAt', 'DESC']] });
213
+ return { rows: rows.filter(isServed) };
214
+ }
215
+ return visibleServedApps(request);
216
+ };
217
+
218
+ const visibleServedApps = async request => {
219
+ const { pageData: visibleApps } = await getServices().app.centerList({ request, includeMenuApps: true, includeUnavailable: true });
220
+ const names = visibleApps.map(item => item.name);
221
+ const rows = names.length ? await models.app.findAll({ where: { name: names, status: SERVED_STATUSES }, order: [['createdAt', 'DESC']] }) : [];
222
+ return { rows: rows.filter(isServed), visibleApps };
223
+ };
224
+
225
+ /**
226
+ * 登录用户的菜单列表:只含运行中(或挂了但有缓存,菜单取上一次的快照)、通过 filterCenterApps、当前租户设置为「左菜单」展示的应用,并按 filterCenterMenus 做用户级裁剪。
227
+ * 没有声明菜单、菜单为空的应用不出现。每个应用带 status,挂了的应用在进入页面时由前端异步检测并展示错误。
228
+ */
229
+ const centerMenus = async ({ request } = {}) => {
230
+ const { rows } = await visibleServedApps(request);
231
+ const configured = await loadConfigured({ tenantId: await tenantIdOf(request), names: rows.map(app => app.name) });
232
+ const items = [];
233
+ for (const app of rows) {
234
+ const snapshot = await getSnapshot(app);
235
+ if (!snapshot?.manifest || !snapshot.manifest.menus.length || effectiveMode(app, configured) !== 'menu') {
236
+ continue;
237
+ }
238
+ const item = await buildItem(app, snapshot, configured.get(app.name)?.labelI18n);
239
+ if (request && typeof options.filterCenterMenus === 'function') {
240
+ const filtered = await options.filterCenterMenus({ menus: item.menus, app: item, request });
241
+ if (Array.isArray(filtered)) {
242
+ item.menus = filtered;
243
+ }
244
+ }
245
+ if (item.menus.length) {
246
+ items.push(item);
247
+ }
248
+ }
249
+ return { pageData: items, totalCount: items.length };
250
+ };
251
+
252
+ /** 租户设置页:当前租户可见应用及其展示方式 */
253
+ const displaySettings = async ({ request, tenantId } = {}) => {
254
+ const scope = await displayScope({ request, tenantId });
255
+ const { rows } = await scopedServedApps(scope, request);
256
+ const configured = await loadConfigured({ tenantId: scope.tenantId, names: rows.map(app => app.name) });
257
+ const items = [];
258
+ for (const app of rows) {
259
+ const snapshot = await getSnapshot(app);
260
+ const menuCount = snapshot?.manifest ? flattenLeafMenus(snapshot.manifest.menus).length : 0;
261
+ items.push({
262
+ name: app.name,
263
+ label: app.label,
264
+ icon: app.icon,
265
+ kind: isLinked(app) ? KIND_LINKED : KIND_MANAGED,
266
+ status: app.status,
267
+ supportsMenu: menuCount > 0,
268
+ menuCount,
269
+ displayMode: effectiveMode(app, configured),
270
+ configured: !!configuredMode(configured, app.name),
271
+ labelI18n: configured.get(app.name)?.labelI18n || {},
272
+ defaultLabelI18n: mergeLabelI18n(snapshot?.manifest?.labelI18n, app.labelI18n),
273
+ menuStatus: snapshot?.status || 'none',
274
+ menuError: snapshot?.status === 'error' ? snapshot.error : null
275
+ });
276
+ }
277
+ return { pageData: items, totalCount: items.length };
278
+ };
279
+
280
+ /** 修改当前租户某应用的展示方式与多语言名称(至少传一项,只更新传入的项);需 canManageDisplay 放行,且只能设置当前租户可见的应用 */
281
+ const saveDisplaySetting = async ({ name, displayMode, labelI18n, tenantId, request }) => {
282
+ if (!tenantId) {
283
+ httpError(400, '请指定要设置的租户 tenantId');
284
+ }
285
+ const scope = await displayScope({ request, tenantId });
286
+ if (!scope.admin) {
287
+ httpError(403, '无权修改应用展示设置');
288
+ }
289
+ if (displayMode === undefined && labelI18n === undefined) {
290
+ httpError(400, '请至少指定 displayMode 或 labelI18n');
291
+ }
292
+ if (displayMode !== undefined && !DISPLAY_MODES.includes(displayMode)) {
293
+ httpError(400, `displayMode 只能是 ${DISPLAY_MODES.join(' / ')}`);
294
+ }
295
+ let labels;
296
+ if (labelI18n !== undefined) {
297
+ const parsed = parseLabelI18n(labelI18n);
298
+ if (parsed.error) {
299
+ httpError(400, parsed.error);
300
+ }
301
+ labels = parsed.value;
302
+ }
303
+ const { rows } = await scopedServedApps(scope, request);
304
+ const app = rows.find(item => item.name === name);
305
+ if (!app) {
306
+ httpError(404, `应用 ${name} 不存在或不可用`);
307
+ }
308
+ if (displayMode === 'menu') {
309
+ const snapshot = await getSnapshot(app);
310
+ if (!snapshot?.manifest || !snapshot.manifest.menus.length) {
311
+ httpError(400, `应用 ${name} 没有声明可展示的菜单,只能在应用中心展示`);
312
+ }
313
+ }
314
+ const tenantRef = scope.tenantId;
315
+ const patch = { userId: request?.userInfo?.id ? String(request.userInfo.id) : null };
316
+ if (displayMode !== undefined) {
317
+ patch.displayMode = displayMode;
318
+ }
319
+ if (labels !== undefined) {
320
+ patch.labelI18n = hasLabels(labels) ? labels : null;
321
+ }
322
+ const [row, created] = await models.appTenantDisplay.findOrCreate({ where: { tenantId: tenantRef, appName: name }, defaults: patch });
323
+ if (!created) {
324
+ await row.update(patch);
325
+ }
326
+ return { name, displayMode: row.displayMode || null, labelI18n: row.labelI18n || {} };
327
+ };
328
+
329
+ /**
330
+ * 以登录用户身份签发子应用令牌(嵌入的远程组件用)。
331
+ * 必须配置 canUseApp 把关(租户已开通、用户拥有该应用权限);返回 falsy 拒绝,返回 { tenantId } 则以该租户签发。
332
+ */
333
+ const resolveAppUse = async ({ name, request, forToken = true }) => {
334
+ if (typeof options.canUseApp !== 'function') {
335
+ httpError(400, '未配置 canUseApp,无法校验应用访问权限');
336
+ }
337
+ if (forToken && typeof options.issueUserAccessToken !== 'function') {
338
+ httpError(400, '未配置 issueUserAccessToken,无法签发应用访问令牌');
339
+ }
340
+ const userId = request?.userInfo?.id;
341
+ if (!userId) {
342
+ httpError(400, '缺少登录用户');
343
+ }
344
+ const app = await models.app.findOne({ where: { name } });
345
+ if (!app) {
346
+ httpError(404, `应用 ${name} 不存在`);
347
+ }
348
+ if (forToken && app.status !== 'running') {
349
+ httpError(400, `应用 ${name} 当前状态为 ${app.status},运行中才能访问`);
350
+ }
351
+ const verdict = await options.canUseApp({ app: getServices().app.toPublicApp(app), request });
352
+ if (!verdict) {
353
+ httpError(403, `无权访问应用 ${name}`);
354
+ }
355
+ const tenantId = verdict && typeof verdict === 'object' && verdict.tenantId ? verdict.tenantId : undefined;
356
+ return { app, userId, tenantId };
357
+ };
358
+
359
+ /** 探测应用是否真的能响应:托管应用探本机端口(规则同部署健康检查),关联应用探远程 /ready(规则同定时同步) */
360
+ const probeApp = async app => {
361
+ try {
362
+ if (isLinked(app)) {
363
+ const response = await fetch(`${linkedApiBaseUrl(app)}/ready`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
364
+ // 前端 SPA 会对未知路径回 HTML 200,不能当成健康
365
+ const ok = response.ok && !String(response.headers.get('content-type') || '').includes('text/html');
366
+ return { ok, message: ok ? null : response.ok ? '远程 /ready 返回了非 JSON(可能打到前端)' : `远程健康检查失败 HTTP ${response.status}` };
367
+ }
368
+ const response = await fetch(`http://${options.upstreamHost}:${app.port}${options.healthCheckPath || '/'}`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
369
+ const ok = response.status >= 200 && response.status < 500;
370
+ return { ok, message: ok ? null : `健康检查失败 HTTP ${response.status}` };
371
+ } catch (e) {
372
+ return { ok: false, message: e.message || '无法连接应用' };
373
+ }
374
+ };
375
+
376
+ /**
377
+ * 应用当前是否可用(前端进入应用页面后异步调用):同样经 canUseApp 把关。
378
+ * 状态不是 running 直接判定不可用;running 再实际探测一次,进程已死但状态还没同步过来的情况也能识别。
379
+ */
380
+ const appStatus = async ({ name, request }) => {
381
+ const { app } = await resolveAppUse({ name, request, forToken: false });
382
+ if (app.status !== 'running') {
383
+ return { name, status: app.status, healthy: false, message: app.message || null };
384
+ }
385
+ const probe = await probeApp(app);
386
+ return { name, status: app.status, healthy: probe.ok, message: probe.message };
387
+ };
388
+
389
+ const issueAppToken = async ({ app, userId, tenantId }) => {
390
+ const token = await options.issueUserAccessToken({ app, userId, tenantId });
391
+ const { exp } = JSON.parse(Buffer.from(String(token).split('.')[1] || '', 'base64url').toString('utf8') || '{}');
392
+ return { token, expiresAt: exp ? new Date(exp * 1000).toISOString() : null };
393
+ };
394
+
395
+ const issueCenterToken = async ({ name, request }) => issueAppToken(await resolveAppUse({ name, request }));
396
+
397
+ Object.assign(getServices(), {
398
+ menu: { refresh, getSnapshot, centerMenus, appStatus, resolveAppUse, issueAppToken, issueCenterToken, menuDisplayedNames, tenantLabels, displaySettings, saveDisplaySetting }
399
+ });
400
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 应用「挂了」时是否仍按缓存对外提供菜单与权限。
3
+ *
4
+ * 菜单快照只在应用就绪(或 linked 同步成功)时拉取,所以快照有记录就说明这个应用曾经可达过:
5
+ * 状态为 error 的应用此时仍使用上一次拿到的菜单快照与权限快照,入口保留,进入时由前端异步检测状态并展示错误。
6
+ * 没有快照记录(例如首次部署就失败)的 error 应用不对外提供。
7
+ */
8
+ const wasReady = app => {
9
+ const snapshot = app.options?.menuSnapshot;
10
+ return !!snapshot && (snapshot.status === 'ok' || snapshot.status === 'none' || !!snapshot.manifest);
11
+ };
12
+
13
+ /** 运行中,或挂了但有缓存可用 */
14
+ const isServed = app => app.status === 'running' || (app.status === 'error' && wasReady(app));
15
+
16
+ /** 查询候选状态:running 与 error;error 的需再用 isServed 过滤 */
17
+ const SERVED_STATUSES = ['running', 'error'];
18
+
19
+ module.exports = { wasReady, isServed, SERVED_STATUSES };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 应用名称多语言({ 语言码: 名称 })。
3
+ * 来源优先级(高 → 低):租户配置 > 应用中心配置(app.labelI18n)> 子应用 manifest 声明(manifest.labelI18n),都没有时取应用 label。
4
+ */
5
+ const LANGUAGE_CODE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
6
+ const LABEL_MAX_LENGTH = 100;
7
+
8
+ const hasLabels = labelI18n => !!labelI18n && typeof labelI18n === 'object' && Object.keys(labelI18n).length > 0;
9
+
10
+ /** 校验并规整多语言名称:语言码合法、名称去空、最长 100 字;全部为空时 value 为 {}。不合法返回 error 文案 */
11
+ const parseLabelI18n = raw => {
12
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
13
+ return { value: null, error: 'labelI18n 必须是 { 语言: 名称 } 对象' };
14
+ }
15
+ const value = {};
16
+ for (const lang of Object.keys(raw)) {
17
+ if (!LANGUAGE_CODE.test(lang)) {
18
+ return { value: null, error: `语言码 ${lang} 不合法` };
19
+ }
20
+ const label = typeof raw[lang] === 'string' ? raw[lang].trim() : '';
21
+ if (label.length > LABEL_MAX_LENGTH) {
22
+ return { value: null, error: `${lang} 的应用名称不能超过 ${LABEL_MAX_LENGTH} 个字符` };
23
+ }
24
+ if (label) {
25
+ value[lang] = label;
26
+ }
27
+ }
28
+ return { value, error: null };
29
+ };
30
+
31
+ /** 按优先级从低到高合并,后面的覆盖前面同语言的名称 */
32
+ const mergeLabelI18n = (...sources) => Object.assign({}, ...sources.filter(hasLabels));
33
+
34
+ /** 应用自身的默认多语言名称:应用中心配置覆盖子应用 manifest 声明;不含租户配置 */
35
+ const appDefaultLabels = app => mergeLabelI18n(app?.options?.menuSnapshot?.manifest?.labelI18n, app?.labelI18n);
36
+
37
+ module.exports = { LABEL_MAX_LENGTH, hasLabels, parseLabelI18n, mergeLabelI18n, appDefaultLabels };
@@ -0,0 +1,205 @@
1
+ /**
2
+ * 子应用菜单 manifest(open-menus.json)规范化与校验。
3
+ *
4
+ * 规范见《应用菜单集成规范》:
5
+ * - integration:remote(远程组件,首选)/ iframe / blank(新窗口)
6
+ * - menus 最多两级;叶子菜单 remote 需要 component,iframe / blank 需要 path
7
+ * - remote.name 必须等于应用 slug(托管应用);linked 应用另需 remote.url
8
+ * - labelI18n(可选):子应用声明自己在各语言下的名称,如 { "zh-CN": "订单", "en-US": "Orders" };应用中心与租户可覆盖
9
+ */
10
+
11
+ const { parseLabelI18n, hasLabels } = require('./labelI18n');
12
+
13
+ const MANIFEST_SCHEMA_VERSION = 1;
14
+ const INTEGRATIONS = ['remote', 'iframe', 'blank'];
15
+ const MAX_DEPTH = 2;
16
+ const KEY_RE = /^[a-z0-9][a-z0-9-]*$/;
17
+ const COMPONENT_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
18
+ const DEFAULT_PRESET = 'ComponentPreset';
19
+
20
+ const isPlainObject = value => !!value && typeof value === 'object' && !Array.isArray(value);
21
+ const text = value => (value == null ? '' : String(value).trim());
22
+
23
+ const normalizePath = value => {
24
+ const raw = text(value);
25
+ if (!raw) {
26
+ return '';
27
+ }
28
+ return raw.startsWith('/') ? raw : `/${raw}`;
29
+ };
30
+
31
+ /**
32
+ * @param {unknown} raw 子应用返回的 manifest 原文
33
+ * @param {{ appName: string, kind?: 'managed'|'linked' }} context
34
+ * @returns {{ ok: boolean, manifest: object|null, errors: string[] }}
35
+ */
36
+ const normalizeMenuManifest = (raw, { appName, kind = 'managed' } = {}) => {
37
+ const errors = [];
38
+ if (!isPlainObject(raw)) {
39
+ return { ok: false, manifest: null, errors: ['manifest 必须是对象'] };
40
+ }
41
+
42
+ const schemaVersion = raw.schemaVersion == null ? MANIFEST_SCHEMA_VERSION : Number(raw.schemaVersion);
43
+ if (schemaVersion !== MANIFEST_SCHEMA_VERSION) {
44
+ return { ok: false, manifest: null, errors: [`不支持的 schemaVersion:${raw.schemaVersion}`] };
45
+ }
46
+
47
+ const hasRemote = isPlainObject(raw.remote);
48
+ const integration = text(raw.integration) || (hasRemote ? 'remote' : 'iframe');
49
+ if (!INTEGRATIONS.includes(integration)) {
50
+ errors.push(`integration 只能是 ${INTEGRATIONS.join(' / ')}`);
51
+ }
52
+
53
+ let remote = null;
54
+ if (integration === 'remote') {
55
+ const name = text(raw.remote?.name);
56
+ if (!name) {
57
+ errors.push('integration=remote 时必须提供 remote.name');
58
+ } else if (name !== appName) {
59
+ errors.push(`remote.name 必须等于应用 slug(${appName}),当前为 ${name}`);
60
+ }
61
+ remote = {
62
+ name,
63
+ preset: text(raw.remote?.preset) || DEFAULT_PRESET
64
+ };
65
+ if (kind === 'linked') {
66
+ const url = text(raw.remote?.url).replace(/\/+$/, '');
67
+ if (!/^https?:\/\//i.test(url)) {
68
+ errors.push('linked 应用的 remote.url 必须是 http(s) 绝对地址');
69
+ }
70
+ remote.url = url;
71
+ // 关联应用没有部署版本记录:联邦容器名带版本后缀({name}_{version}),宿主据此拼容器名,必须声明与构建一致的版本
72
+ const version = text(raw.remote?.version);
73
+ if (!version) {
74
+ errors.push('linked 应用必须提供 remote.version(与构建时 package.json 的 version 一致,用于定位联邦容器名)');
75
+ } else if (!/^[A-Za-z0-9._+-]+$/.test(version)) {
76
+ errors.push('remote.version 只能包含字母、数字与 . _ + -');
77
+ } else {
78
+ remote.version = version;
79
+ }
80
+ }
81
+ }
82
+
83
+ let labelI18n = {};
84
+ if (raw.labelI18n !== undefined && raw.labelI18n !== null) {
85
+ const parsed = parseLabelI18n(raw.labelI18n);
86
+ if (parsed.error) {
87
+ errors.push(parsed.error);
88
+ } else {
89
+ labelI18n = parsed.value;
90
+ }
91
+ }
92
+
93
+ const walk = (list, depth, parentKeys, parentIndexes) => {
94
+ if (!Array.isArray(list)) {
95
+ return [];
96
+ }
97
+ const seen = new Set();
98
+ const output = [];
99
+ list.forEach((item, index) => {
100
+ const where = `menus[${[...parentIndexes, index].join('.')}]`;
101
+ if (!isPlainObject(item)) {
102
+ errors.push(`${where} 必须是对象`);
103
+ return;
104
+ }
105
+ const key = text(item.key);
106
+ if (!KEY_RE.test(key)) {
107
+ errors.push(`${where}.key 必须匹配 ${KEY_RE}`);
108
+ return;
109
+ }
110
+ if (seen.has(key)) {
111
+ errors.push(`${where}.key 同级重复:${key}`);
112
+ return;
113
+ }
114
+ seen.add(key);
115
+ const label = text(item.label);
116
+ if (!label) {
117
+ errors.push(`${where}.label 必填`);
118
+ return;
119
+ }
120
+ const node = { key, fullKey: [...parentKeys, key].join('/'), label };
121
+ if (isPlainObject(item.labelI18n)) {
122
+ node.labelI18n = Object.keys(item.labelI18n).reduce((result, lang) => {
123
+ const value = text(item.labelI18n[lang]);
124
+ return value ? Object.assign(result, { [lang]: value }) : result;
125
+ }, {});
126
+ }
127
+ if (text(item.icon)) {
128
+ node.icon = text(item.icon);
129
+ }
130
+ if (text(item.permission)) {
131
+ node.permission = text(item.permission);
132
+ node.permissionCode = `${appName}:${node.permission}`;
133
+ }
134
+
135
+ const children = Array.isArray(item.children) ? item.children : null;
136
+ if (children && children.length) {
137
+ if (depth >= MAX_DEPTH) {
138
+ errors.push(`${where} 超过 ${MAX_DEPTH} 级菜单`);
139
+ return;
140
+ }
141
+ if (item.component || item.path) {
142
+ errors.push(`${where} 有 children 时不能再声明 component / path`);
143
+ return;
144
+ }
145
+ node.children = walk(children, depth + 1, [...parentKeys, key], [...parentIndexes, index]);
146
+ } else if (integration === 'remote') {
147
+ const component = text(item.component);
148
+ if (!COMPONENT_RE.test(component)) {
149
+ errors.push(`${where}.component 必须是 src/components 下的组件目录名`);
150
+ return;
151
+ }
152
+ node.component = component;
153
+ if (isPlainObject(item.props)) {
154
+ node.props = item.props;
155
+ }
156
+ } else {
157
+ const path = normalizePath(item.path);
158
+ if (!path) {
159
+ errors.push(`${where}.path 必填(integration=${integration})`);
160
+ return;
161
+ }
162
+ node.path = path;
163
+ }
164
+ output.push(node);
165
+ });
166
+ return output;
167
+ };
168
+
169
+ const menus = walk(raw.menus, 1, [], []);
170
+ if (!Array.isArray(raw.menus)) {
171
+ errors.push('menus 必须是数组');
172
+ }
173
+
174
+ if (errors.length) {
175
+ return { ok: false, manifest: null, errors };
176
+ }
177
+ return {
178
+ ok: true,
179
+ manifest: Object.assign({ schemaVersion: MANIFEST_SCHEMA_VERSION, integration, menus }, remote ? { remote } : {}, hasLabels(labelI18n) ? { labelI18n } : {}),
180
+ errors
181
+ };
182
+ };
183
+
184
+ /** 打平叶子菜单(含所属父级 key 链) */
185
+ const flattenLeafMenus = menus => {
186
+ const output = [];
187
+ const visit = list =>
188
+ (list || []).forEach(node => {
189
+ if (node.children && node.children.length) {
190
+ visit(node.children);
191
+ } else {
192
+ output.push(node);
193
+ }
194
+ });
195
+ visit(menus);
196
+ return output;
197
+ };
198
+
199
+ module.exports = {
200
+ MANIFEST_SCHEMA_VERSION,
201
+ INTEGRATIONS,
202
+ DEFAULT_PRESET,
203
+ normalizeMenuManifest,
204
+ flattenLeafMenus
205
+ };
package/oidc.js CHANGED
@@ -292,6 +292,11 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
292
292
  }
293
293
  const { models, services } = oidc();
294
294
  await oidc().whenReady();
295
+ // 关联应用登记在 OIDC 应用注册表里:标记删除后通知远程关闭由宿主同步过去的托管租户
296
+ const registered = app.name && services.app?.findByCode?.(app.name);
297
+ if (registered && registered.status !== 'removed' && registered.serviceClientId === serviceClientId) {
298
+ await services.app.remove({ id: registered.id });
299
+ }
295
300
  for (const id of [clientId, serviceClientId].filter(Boolean)) {
296
301
  const item = await models.client.findOne({ where: { clientId: id } });
297
302
  if (item) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.38",
3
+ "version": "0.1.39",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {