@kne/fastify-app-manager 0.1.39 → 0.1.41

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
@@ -207,7 +207,7 @@ await fastify.listen({ port: 3000 });
207
207
  | `getOpenApiToken` | function | 否 | `null` | `async app => accessToken`,签发读取子应用 `/open-api.json` 的服务令牌;未配置时 `GET .../app/open-api` 返回 400。接 OIDC 时传 `appOidc.getOpenApiToken` |
208
208
  | `issueUserAccessToken` | function | 否 | `null` | `async ({ app, userId, tenantId }) => accessToken`,以登录用户身份签发子应用令牌;未配置时 `POST .../app/open-api/token` 返回 400。接 OIDC 时传 `appOidc.issueUserAccessToken` |
209
209
  | `resolveVersionFile` | function | 否 | `null` | `async ({ fileId, name, version, request }) => Buffer`,版本上传传 `fileId`(而非 multipart 文件)时调用,返回 zip 内容;未配置时传 `fileId` 返回 400。版本记录保存 `fileId`;这类版本只在当前部署时常驻磁盘,部署非当前版本或启动时当前版本目录缺失会再次调用以重建 |
210
- | `saveIconFile` | function | 否 | `null` | `async ({ buffer, filename, mimetype }) => fileId`,凭 installKey 关联外部应用(`POST .../app/link/import`)且未传 `icon` 时,平台从远程应用站点收集 favicon / apple-touch-icon / manifest 图标,按真实像素取最大的一张,经此回调存入宿主文件系统并返回文件 id,写入应用 `icon`。未配置则不抓取;抓取或保存失败只记告警,不阻断关联 |
210
+ | `saveIconFile` | function | 否 | `null` | `async ({ buffer, filename, mimetype }) => fileId`,凭 installKey 关联外部应用(`POST .../app/link/import`)且未传 `icon` 时,平台从远程应用站点收集 favicon / apple-touch-icon / manifest 图标(首页没声明时也会探测根路径的 `/manifest.json`、`/apple-touch-icon.png`),按真实像素取最大的一张,经此回调存入宿主文件系统并返回文件 id,写入应用 `icon`。未配置则不抓取;抓取或保存失败只记告警,不阻断关联 |
211
211
  | (宿主接入 `@kne/fastify-oidc`) | — | — | — | 关联外部应用激活或同步时,远程 `@kne/fastify-app-runtime` 回传 `tenantSyncUri`(远程为新版 fastify-oidc 的 standalone 应用)则把该应用以 `tenantMode: 'independent'`、`permissionRoot: true` 登记进 `fastify.oidc.services.app`:开通判断与权限去前缀按顶层 `<name>`,宿主租户变更推送给远程,远程把宿主租户同步为只读托管租户、镜像宿主用户;删除应用时(`appOidc.onAppRemoved`)标记移除该登记。已配对的关联应用在应用中心列表里的 `openUrl` 与 `entries[].url` 带 `oidc_iss={本平台 issuer}`,远程据此用本平台账号登录 |
212
212
  | `filterCenterApps` | function | 否 | `null` | `async ({ apps, request }) => apps`,登录用户的应用中心列表(`GET .../app/center/list`)返回前调用,宿主可据 `request` 裁剪(如按租户已开通权限隐藏被关闭的应用),返回保留的应用数组;返回非数组则不裁剪。公开列表(`center/public-list`)无登录态,不调用 |
213
213
  | `filterCenterMenus` | function | 否 | `null` | `async ({ menus, app, request }) => menus`,登录用户菜单列表(`GET .../app/center/menus`)按应用逐个调用,宿主可据 `request` 做用户级裁剪(如按权限码 `menu.permissionCode` 隐藏菜单),返回保留的菜单数组;返回非数组则不裁剪;裁空的应用不出现 |
@@ -703,13 +703,13 @@ manifest 规则:
703
703
  | 字段 | 说明 |
704
704
  |------|------|
705
705
  | `integration` | `remote`(远程组件,默认当存在 `remote` 时)/ `iframe` / `blank`;缺省且无 `remote` 为 `iframe` |
706
- | `remote.name` | 联邦容器名,**必须等于应用 name**;托管应用的 `remote.url` 由本插件取 `/app/{name}`,linked 应用必须提供 http(s) 绝对地址;`apiHost` 一律为 `/app/{name}`(接口经网关同源转发并换令牌,linked 应用再转到其 `apiBaseUrl`) |
707
- | `remote.version` | linked 应用必填:与构建时 `package.json` 的 version 一致。联邦容器名为 `{name}_{version}`(默认开启版本后缀),关联应用没有部署版本记录,宿主据此定位容器;托管应用取当前部署版本,无需填写 |
706
+ | `remote.name` | 联邦容器名,**必须等于应用 name**;`apiHost` 一律为 `/app/{name}`(接口经网关同源转发并换令牌,linked 应用再转到其 `apiBaseUrl`) |
707
+ | `remote.url` / `remote.version` | **清单里不用声明**(声明了也会被忽略)。托管应用:`url` 取 `/app/{name}`,`version` 取当前部署版本;linked 应用:拉取菜单快照时读取其前端站点(`baseUrl`)的 `GET /remote-module-config.json`,取其 `url`(http(s) 绝对地址)与 `version`(联邦容器名 `{name}_{version}`)。线上由 `@kne/fastify-app-runtime` 提供(内容来自构建产物),本地 `craco start` 由 `@kne/modules-dev` 提供。接口不存在或内容不合法时,快照为 error 并给出原因 |
708
708
  | `menus` | 最多两级,同级 `key` 唯一(`[a-z0-9-]`);叶子菜单 remote 需 `component`,iframe / blank 需 `path`;有 `children` 的节点不能带 `component` / `path` |
709
709
  | `permission` | 子应用权限树内的相对码;返回时附加 `permissionCode = {应用 name}:{permission}`,缺省表示开通应用即可见 |
710
710
  | `menus[].icon` | 可选,原样透传给宿主。约定:含 `/` 或 `.` 视为图片地址(相对地址按 `remote.url` / `baseUrl` 解析,推荐单色 SVG,宿主用 mask 按菜单激活态着色,跨域时需 CORS 放行);否则视为 iconfont type;子菜单未声明时沿用父级,均未声明用宿主默认图标 |
711
711
 
712
- `version` 为当前部署版本号,宿主据此判断是否需要重载 `remoteEntry.js`。
712
+ `version` 为当前部署版本号(linked 应用为其 `/remote-module-config.json` 的 `version`),宿主据此判断是否需要重载 `remoteEntry.js`。
713
713
 
714
714
  ##### GET `{prefix}/app/center/display-settings`
715
715
 
@@ -2,6 +2,7 @@ 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
4
  const { normalizeMenuManifest, flattenLeafMenus } = require('../utils/menuManifest');
5
+ const { fetchRemoteModuleConfig } = require('../utils/remoteModuleConfig');
5
6
  const { hasLabels, parseLabelI18n, mergeLabelI18n, appDefaultLabels } = require('../utils/labelI18n');
6
7
 
7
8
  /** 拉取失败或没有菜单声明的应用,间隔多久再尝试一次懒拉取 */
@@ -75,11 +76,17 @@ module.exports = fp(async (fastify, options) => {
75
76
  if (raw == null) {
76
77
  return await saveSnapshot(app, { status: 'none', fetchedAt, manifest: null });
77
78
  }
78
- const { ok, manifest, errors } = normalizeMenuManifest(raw, { appName: app.name, kind: isLinked(app) ? KIND_LINKED : KIND_MANAGED });
79
+ const { ok, manifest, errors } = normalizeMenuManifest(raw, { appName: app.name });
79
80
  if (!ok) {
80
81
  fastify.log.warn({ app: app.name, errors }, 'app menus manifest invalid');
81
82
  return await saveSnapshot(app, { status: 'error', fetchedAt, error: errors.join(';'), manifest: previous?.manifest || null });
82
83
  }
84
+ if (isLinked(app) && manifest.integration === 'remote') {
85
+ // 关联应用没有部署记录:远程组件地址与版本(联邦容器名 {name}_{version})读前端站点(baseUrl)的 /remote-module-config.json;
86
+ // 线上由 fastify-app-runtime 提供,本地 craco start 由 @kne/modules-dev 提供
87
+ const { url, version } = await fetchRemoteModuleConfig({ baseUrl: linkedBaseUrl(app), timeoutMs: FETCH_TIMEOUT_MS });
88
+ manifest.remote = Object.assign({}, manifest.remote, { url, version });
89
+ }
83
90
  return await saveSnapshot(app, { status: 'ok', fetchedAt, manifest });
84
91
  } catch (e) {
85
92
  fastify.log.warn({ err: e, app: app.name }, 'fetch app menus failed');
@@ -4,7 +4,7 @@
4
4
  * 规范见《应用菜单集成规范》:
5
5
  * - integration:remote(远程组件,首选)/ iframe / blank(新窗口)
6
6
  * - menus 最多两级;叶子菜单 remote 需要 component,iframe / blank 需要 path
7
- * - remote.name 必须等于应用 slug(托管应用);linked 应用另需 remote.url
7
+ * - remote.name 必须等于应用 slug;remote 的地址与版本不在清单里声明:托管应用取部署记录,linked 应用读其 /remote-module-config.json
8
8
  * - labelI18n(可选):子应用声明自己在各语言下的名称,如 { "zh-CN": "订单", "en-US": "Orders" };应用中心与租户可覆盖
9
9
  */
10
10
 
@@ -30,10 +30,10 @@ const normalizePath = value => {
30
30
 
31
31
  /**
32
32
  * @param {unknown} raw 子应用返回的 manifest 原文
33
- * @param {{ appName: string, kind?: 'managed'|'linked' }} context
33
+ * @param {{ appName: string }} context
34
34
  * @returns {{ ok: boolean, manifest: object|null, errors: string[] }}
35
35
  */
36
- const normalizeMenuManifest = (raw, { appName, kind = 'managed' } = {}) => {
36
+ const normalizeMenuManifest = (raw, { appName } = {}) => {
37
37
  const errors = [];
38
38
  if (!isPlainObject(raw)) {
39
39
  return { ok: false, manifest: null, errors: ['manifest 必须是对象'] };
@@ -62,22 +62,6 @@ const normalizeMenuManifest = (raw, { appName, kind = 'managed' } = {}) => {
62
62
  name,
63
63
  preset: text(raw.remote?.preset) || DEFAULT_PRESET
64
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
65
  }
82
66
 
83
67
  let labelI18n = {};
@@ -131,8 +131,9 @@ const filenameOf = (url, mimetype) => {
131
131
  };
132
132
 
133
133
  /**
134
- * 从远程应用前端站点获取图标:首页 <link rel=icon/apple-touch-icon>、web manifest icons、/favicon.ico 全部作为候选,
135
- * 逐个下载后读真实像素尺寸,取最大的一张(站点没声明 sizes 也能比出大小);尺寸相同按 touch > icon > manifest > favicon.ico,普通图优先于 maskable。
134
+ * 从远程应用前端站点获取图标:首页 <link rel=icon/apple-touch-icon>、web manifest icons(首页没声明时探测 /manifest.json)、
135
+ * /apple-touch-icon.png、/favicon.ico 全部作为候选,
136
+ * 逐个下载后读真实像素尺寸,取最大的一张(站点没声明 sizes 也能比出大小);尺寸相同按 touch > icon > manifest > 约定路径 > favicon.ico,普通图优先于 maskable。
136
137
  * 只接受 image/* 且不超过 1MB 的响应(SPA 对未知路径回落 HTML 的会被丢弃)。
137
138
  * 失败返回 null,不抛错。
138
139
  */
@@ -148,24 +149,26 @@ const discoverRemoteIcon = async ({ baseUrl, timeoutMs = 5000, fetchImpl = fetch
148
149
 
149
150
  const candidates = [];
150
151
  const pageUrl = `${base}/`;
152
+ let declaredManifestUrl = null;
151
153
  try {
152
154
  const page = await request(pageUrl, 'text/html');
153
155
  if (page) {
154
156
  const { icons, manifestUrl } = parseHtmlIcons(await page.text(), pageUrl);
155
157
  candidates.push(...icons);
156
- if (manifestUrl) {
157
- try {
158
- const manifestRes = await request(manifestUrl, 'application/manifest+json,application/json');
159
- candidates.push(...parseManifestIcons(manifestRes ? await manifestRes.json() : null, manifestUrl));
160
- } catch (e) {
161
- // manifest 取不到不影响后续候选
162
- }
163
- }
158
+ declaredManifestUrl = manifestUrl;
164
159
  }
165
160
  } catch (e) {
166
- // 首页取不到,退回 /favicon.ico
161
+ // 首页取不到,仍按约定路径探测
162
+ }
163
+ // 首页没声明 manifest(老页面、或首页取不到)时按约定路径 /manifest.json 探测:站点常把 manifest 放在根路径却没在 HTML 里引用
164
+ const manifestUrl = declaredManifestUrl || `${base}/manifest.json`;
165
+ try {
166
+ const manifestRes = await request(manifestUrl, 'application/manifest+json,application/json');
167
+ candidates.push(...parseManifestIcons(manifestRes ? await manifestRes.json() : null, manifestUrl));
168
+ } catch (e) {
169
+ // manifest 取不到、或被 SPA 回落成 HTML 无法解析,不影响后续候选
167
170
  }
168
- candidates.push({ url: `${base}/favicon.ico`, size: 0 });
171
+ candidates.push({ url: `${base}/apple-touch-icon.png`, size: 0 }, { url: `${base}/favicon.ico`, size: 0 });
169
172
 
170
173
  const unique = [...new Map(candidates.map(item => [item.url, item])).values()].slice(0, MAX_CANDIDATES);
171
174
  const fetched = await Promise.all(
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 读取应用前端站点提供的 /remote-module-config.json(线上由 @kne/fastify-app-runtime 内置提供,内容来自构建产物 remote-module-config*.json;
3
+ * 本地 craco start 由 @kne/modules-dev 提供)。关联应用的远程组件地址与版本以它为准,不再要求应用在菜单清单里重复声明。
4
+ */
5
+
6
+ const DEFAULT_TIMEOUT_MS = 5000;
7
+ const VERSION_RE = /^[A-Za-z0-9._+-]+$/;
8
+
9
+ const text = value => (value == null ? '' : String(value).trim());
10
+
11
+ /**
12
+ * @param {{ baseUrl: string, timeoutMs?: number, fetchImpl?: typeof fetch }} params baseUrl 为应用前端站点根地址
13
+ * @returns {Promise<{ url: string, version: string }>} url 为远程组件 remoteEntry.js 所在目录的绝对地址
14
+ */
15
+ const fetchRemoteModuleConfig = async ({ baseUrl, timeoutMs = DEFAULT_TIMEOUT_MS, fetchImpl = fetch } = {}) => {
16
+ const base = text(baseUrl).replace(/\/+$/, '');
17
+ if (!base) {
18
+ throw new Error('缺少应用地址,无法读取 /remote-module-config.json');
19
+ }
20
+ const endpoint = `${base}/remote-module-config.json`;
21
+ const response = await fetchImpl(endpoint, { signal: AbortSignal.timeout(timeoutMs) });
22
+ if (response.status === 404) {
23
+ throw new Error(`${endpoint} 不存在:应用需使用 @kne/fastify-app-runtime,且构建产物包含 remote-module-config*.json`);
24
+ }
25
+ if (!response.ok) {
26
+ throw new Error(`${endpoint} 返回 HTTP ${response.status}`);
27
+ }
28
+ let config;
29
+ try {
30
+ config = await response.json();
31
+ } catch (e) {
32
+ throw new Error(`${endpoint} 返回的不是 JSON`);
33
+ }
34
+
35
+ const url = text(config?.url)
36
+ .replace(/\/+$/, '')
37
+ .replace(/\/remoteEntry\.js$/i, '');
38
+ if (!/^https?:\/\//i.test(url)) {
39
+ throw new Error(`${endpoint} 的 url 必须是 http(s) 绝对地址,当前为 ${url || '空'}`);
40
+ }
41
+ const version = text(config?.version);
42
+ if (!version || !VERSION_RE.test(version)) {
43
+ throw new Error(`${endpoint} 的 version 为空或包含不允许的字符:${version || '空'}`);
44
+ }
45
+ return { url, version };
46
+ };
47
+
48
+ module.exports = { fetchRemoteModuleConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.39",
3
+ "version": "0.1.41",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {