@kne/fastify-app-manager 0.1.18 → 0.1.20
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 +52 -4
- package/index.js +29 -6
- package/libs/controllers/app.js +23 -1
- package/libs/controllers/gateway.js +2 -2
- package/libs/services/app.js +32 -3
- package/libs/utils/portPool.js +4 -4
- package/oidc.js +282 -0
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -198,20 +198,22 @@ await fastify.listen({ port: 3000 });
|
|
|
198
198
|
| `portMax` | number | 否 | `7999` | 端口池上限(含) |
|
|
199
199
|
| `pathPrefix` | string | 否 | `'/app'` | 路径访问前缀(无尾斜杠亦可) |
|
|
200
200
|
| `passthroughEnvKeys` | array | 否 | `[]` | 允许注入子进程的宿主 env 键名 |
|
|
201
|
+
| `pwaIconPrefix` | string | 否 | `'/api/v1/static/file-id'` | PWA manifest 图标地址前缀(应用 `icon` 为文件 id 时拼接) |
|
|
201
202
|
| `secretEnvKeyPattern` | RegExp | 否 | `/(SECRET\|PASSWORD\|TOKEN\|KEY\|PRIVATE)/i` | 按键名正则脱敏;与显式 `secretEnvKeys` 取并集 |
|
|
202
203
|
| `systemEnvKeys` | array | 否 | `[]` | 宿主维护的系统变量键名,与内置 `DB_TABLE_PREFIX` 合并:接口不返回,create / save / saveEnv 不可新增、修改或删除 |
|
|
203
|
-
| `resolveSystemEnv` | function | 否 | `null` | `async ({ app, version, serverDir }) => env \| null
|
|
204
|
+
| `resolveSystemEnv` | function | 否 | `null` | `async ({ app, version, serverDir, upstreamUrl }) => env \| null`(`upstreamUrl` 为子应用进程地址 `http://{upstreamHost}:{port}`),每次启动进程(deploy / start / restart / 恢复)前调用;返回值覆盖应用变量注入子进程,值为 `null` / `undefined` 的键忽略,属于 `systemEnvKeys` 的键持久化到 `app.env` |
|
|
204
205
|
| `onAppRemoved` | function | 否 | `null` | `async ({ app }) => void`,应用删除成功后调用,`app` 为删除前快照(含 `env`);数据清理未完成而未删除时不调用,钩子报错只记 warn 日志 |
|
|
205
206
|
| `resolveVersionFile` | function | 否 | `null` | `async ({ fileId, name, version, request }) => Buffer`,版本上传传 `fileId`(而非 multipart 文件)时调用,返回 zip 内容;未配置时传 `fileId` 返回 400。版本记录保存 `fileId`;这类版本只在当前部署时常驻磁盘,部署非当前版本或启动时当前版本目录缺失会再次调用以重建 |
|
|
206
207
|
| `defaultAppDb` | object | 否 | `appsRoot/_shared/apps-data.sqlite` | 托管应用默认库(须与宿主主库分离) |
|
|
207
208
|
| `dbQueryMaxRows` | number | 否 | `500` | 只读 query SQL 最大返回行数 |
|
|
208
209
|
| `pm2Defaults` | object | 否 | 见下表 | 全局 PM2 默认;可被应用 `pm2Config` 覆盖 |
|
|
209
|
-
| `createAuthenticate` | function | 否 | 见说明 | 返回 `onRequest`
|
|
210
|
+
| `createAuthenticate` | function | 否 | 见说明 | 返回 `onRequest` 钩子数组;默认 `fastify.account.authenticate.user` + `admin` |
|
|
210
211
|
| `createUserAuthenticate` | function | 否 | 见说明 | 应用中心等普通用户接口的 `onRequest` 钩子数组;默认尝试 `fastify.account.authenticate.user` |
|
|
212
|
+
| `upstreamHost` | string | 否 | `'127.0.0.1'` | 子应用进程监听地址:网关转发、WebSocket、就绪探测、端口探测与 `resolveSystemEnv` 的 `upstreamUrl` 共用 |
|
|
211
213
|
| `healthCheckPath` | string | 否 | `'/'` | 部署后就绪探测路径 |
|
|
212
214
|
| `healthCheckTimeoutMs` | number | 否 | `30000` | 探测总超时(毫秒) |
|
|
213
215
|
| `healthCheckIntervalMs` | number | 否 | `1000` | 探测轮询间隔(毫秒) |
|
|
214
|
-
| `maxZipSize` | number | 否 | `209715200` | zip 最大字节(200MB
|
|
216
|
+
| `maxZipSize` | number | 否 | `209715200` | zip 最大字节(200MB);上传接口按此值读取 multipart,不受宿主已注册 multipart 的限制影响 |
|
|
215
217
|
| `maxZipEntries` | number | 否 | `20000` | zip 最大条目数(不含被丢弃的 `node_modules` 条目) |
|
|
216
218
|
| `npmInstallTimeoutMs` | number | 否 | `600000` | `server` 目录 `npm install` 超时 |
|
|
217
219
|
| `deployRecordKeep` | number | 否 | `20` | 每个应用保留的部署记录条数 |
|
|
@@ -247,7 +249,11 @@ await fastify.listen({ port: 3000 });
|
|
|
247
249
|
|
|
248
250
|
应用级 `pm2Config` 仅允许覆盖:`exec_mode`、`instances`、`autorestart`、`max_memory_restart`、`max_restarts`、`min_uptime`、`kill_timeout`、`merge_logs`。
|
|
249
251
|
|
|
250
|
-
> **关键设计**:`createAuthenticate` 默认实现在存在 `fastify.account.authenticate.admin`
|
|
252
|
+
> **关键设计**:`createAuthenticate` 默认实现在存在 `fastify.account.authenticate.admin` 时返回 `[user, admin]`(admin 依赖 user 先写入 `request.userInfo`),否则返回空数组(便于本地无 account 插件时调试)。生产环境应显式传入鉴权。
|
|
253
|
+
>
|
|
254
|
+
> **query token**:`createAuthenticate` / `createUserAuthenticate` 返回非空数组时,会在最前面自动加一个钩子:请求没有 `Authorization` 头而 query 带 `token` 时,转成 `Bearer {token}`(日志 SSE、原生导航下载无法带请求头)。宿主无需自行处理。
|
|
255
|
+
>
|
|
256
|
+
> **重复注册**:宿主已注册 `@fastify/multipart` 或 `@fastify/reply-from` 时(如 `@kne/fastify-file-manager` 会注册 multipart),本插件不再重复注册。
|
|
251
257
|
|
|
252
258
|
> **依赖**:插件 `dependencies: ['fastify-sequelize']`,须先 `register('@kne/fastify-sequelize')` 再注册本插件,并在业务侧调用 `fastify.sequelize.sync()`。
|
|
253
259
|
|
|
@@ -566,6 +572,15 @@ data: {"progressId":"p-1","step":"ready","status":"done","detail":null,"message"
|
|
|
566
572
|
|
|
567
573
|
公开应用中心列表,**无需登录**。返回结构同 `app/center/list`,仅包含运行中且 `isPublic` 不为 `false` 的应用。
|
|
568
574
|
|
|
575
|
+
##### GET `{prefix}/app/center/webmanifest`
|
|
576
|
+
|
|
577
|
+
公开应用的 PWA manifest,**无需登录**,`Content-Type: application/manifest+json`。由 `@kne/pwa-document` 的 `buildWebManifest` 生成。
|
|
578
|
+
|
|
579
|
+
| 参数 | 类型 | 必填 | 说明 |
|
|
580
|
+
|------|------|------|------|
|
|
581
|
+
| `name` | string | 是 | 应用名;不在公开列表中时 404 |
|
|
582
|
+
| `path` | string | 否 | 应用入口路径(主入口或 `entries[].path`);不匹配时回落到第一个入口 |
|
|
583
|
+
|
|
569
584
|
##### GET `{prefix}/app/detail`
|
|
570
585
|
|
|
571
586
|
| 参数名 | 类型 | 必填 | 说明 |
|
|
@@ -777,6 +792,8 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
777
792
|
| `resolveAppLogFile({ name, file })` | 校验并返回 `{ path, fileName, size, compressed }`(下载用) |
|
|
778
793
|
| `resolveAppLogFiles({ name, files })` | 批量校验(去重),返回 `{ name, files: [{ path, fileName, size, mtime, compressed }] }`(打包下载用) |
|
|
779
794
|
| `removeLogFiles({ name, files })` | 删除归档,返回 `{ removed }` |
|
|
795
|
+
| `pwaManifest({ name, path? })` | 同 `GET .../app/center/webmanifest` |
|
|
796
|
+
| `resolvePwaEntry(urlPath, { shellEntries?, defaultIcon? })` | 按访问路径在公开应用中匹配 PWA 入口(`@kne/pwa-document` 的 `resolveEntry`),未命中时回落 `shellEntries`;宿主用于在 HTML 中注入 manifest |
|
|
780
797
|
| `load({ name })` | 返回 `{ intervalMs, current, pageData }` |
|
|
781
798
|
| `getLoadStore()` | 负载环形缓冲:`history(name)` / `latest(name)` / `emitter`(事件 `load:{name}`) |
|
|
782
799
|
| `findByHost(host, { running? })` | 网关:按 domain 查找;默认只查 `running`,`running: false` 时不限状态 |
|
|
@@ -953,3 +970,34 @@ pickHostEnv(passthroughEnvKeys) → app.env → PORT=分配端口(强制)
|
|
|
953
970
|
```
|
|
954
971
|
|
|
955
972
|
API 响应脱敏:`secretEnvKeyPattern` ∪ `options.secretEnvKeys`;明文密钥不回传,顶层 `secretEnvKeys` 只暴露键名。
|
|
973
|
+
|
|
974
|
+
#### 应用 OIDC 对接(可选)
|
|
975
|
+
|
|
976
|
+
宿主已注册 `@kne/fastify-oidc` 作为主 IdP、希望子应用统一登录时使用;不传则子应用不注入任何登录相关变量,按各自的登录运行(`@kne/fastify-oidc` 未设置 `AUTH_MODE` 时默认 `standalone`)。`@kne/fastify-oidc` 为可选 peer 依赖,不用 OIDC 的宿主无需安装。
|
|
977
|
+
|
|
978
|
+
```js
|
|
979
|
+
const createAppOidc = require('@kne/fastify-app-manager/oidc');
|
|
980
|
+
|
|
981
|
+
const appOidc = createAppOidc(fastify, { origin, issuer, serviceAudience });
|
|
982
|
+
fastify.register(require('@kne/fastify-app-manager'), {
|
|
983
|
+
systemEnvKeys: appOidc.systemEnvKeys,
|
|
984
|
+
resolveSystemEnv: appOidc.resolveSystemEnv,
|
|
985
|
+
onAppRemoved: appOidc.onAppRemoved
|
|
986
|
+
});
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|
|
990
|
+
|------|------|------|--------|------|
|
|
991
|
+
| origin | string | 是 | - | 宿主对外地址,拼子应用回调地址与 audience |
|
|
992
|
+
| issuer | string | 是 | - | 宿主 IdP issuer |
|
|
993
|
+
| serviceAudience | string | 是 | - | 子应用服务 client 可访问的宿主资源标识 |
|
|
994
|
+
| pathPrefix | string | 否 | `'/app'` | 与 app-manager 的 `pathPrefix` 一致 |
|
|
995
|
+
| backchannelLogoutPath | string | 否 | `'/api/oidc/backchannel-logout'` | 子应用登出通知路径,拼在 `upstreamUrl` 之后,直连子应用进程 |
|
|
996
|
+
|
|
997
|
+
返回 `{ systemEnvKeys, resolveSystemEnv, onAppRemoved, getOpenApiToken, issueUserAccessToken }`。
|
|
998
|
+
|
|
999
|
+
| 子应用情况 | 行为 |
|
|
1000
|
+
|------|------|
|
|
1001
|
+
| `server/package.json` 未依赖 `@kne/fastify-oidc` | 不登记、不注入 |
|
|
1002
|
+
| `server/env.schema.json` 声明 `AUTH_MODE` 默认值为 `standalone` | 不登记、不注入,保持自己的登录;之前以 central 启动过的应用注入 `AUTH_MODE=standalone` 覆盖 |
|
|
1003
|
+
| 其它依赖 `@kne/fastify-oidc` 的应用 | 登记资源服务、前端 client、服务 client,注入 `AUTH_MODE=central` 与 `OIDC_*` |
|
package/index.js
CHANGED
|
@@ -15,6 +15,8 @@ module.exports = fp(
|
|
|
15
15
|
prefix: '/api/v1/app-manager',
|
|
16
16
|
appsRoot,
|
|
17
17
|
portMin: 4000,
|
|
18
|
+
/** 子应用进程监听地址:网关转发、WebSocket、就绪探测、端口探测与 resolveSystemEnv 的 upstreamUrl 共用 */
|
|
19
|
+
upstreamHost: '127.0.0.1',
|
|
18
20
|
portMax: 7999,
|
|
19
21
|
pathPrefix: '/app',
|
|
20
22
|
healthCheckPath: '/',
|
|
@@ -51,6 +53,8 @@ module.exports = fp(
|
|
|
51
53
|
/** async ({ fileId, name, version, request }) => Buffer,版本上传传 fileId 时读取宿主文件 */
|
|
52
54
|
resolveVersionFile: null,
|
|
53
55
|
secretEnvKeyPattern: /(SECRET|PASSWORD|TOKEN|KEY|PRIVATE)/i,
|
|
56
|
+
/** 应用图标为文件 id 时,PWA manifest 中图标地址的前缀 */
|
|
57
|
+
pwaIconPrefix: '/api/v1/static/file-id',
|
|
54
58
|
sqlPath: 'sql',
|
|
55
59
|
migrateBeforeStart: false,
|
|
56
60
|
defaultAppDb: {
|
|
@@ -72,9 +76,10 @@ module.exports = fp(
|
|
|
72
76
|
kill_timeout: 5000,
|
|
73
77
|
merge_logs: true
|
|
74
78
|
},
|
|
79
|
+
// admin 依赖 user 先写入 request.userInfo,不可只挂 authenticate.admin
|
|
75
80
|
createAuthenticate: () => {
|
|
76
81
|
if (fastify.account?.authenticate?.admin) {
|
|
77
|
-
return [fastify.account.authenticate.admin];
|
|
82
|
+
return [fastify.account.authenticate.user, fastify.account.authenticate.admin];
|
|
78
83
|
}
|
|
79
84
|
return [];
|
|
80
85
|
},
|
|
@@ -107,13 +112,31 @@ module.exports = fp(
|
|
|
107
112
|
await fs.ensureDir(path.dirname(options.defaultAppDb.storage));
|
|
108
113
|
}
|
|
109
114
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
115
|
+
// 日志 SSE、原生导航下载无法带请求头,token 放在 query 中
|
|
116
|
+
const queryTokenToAuthorization = async request => {
|
|
117
|
+
if (!request.headers.authorization && typeof request.query?.token === 'string' && request.query.token) {
|
|
118
|
+
request.headers.authorization = `Bearer ${request.query.token}`;
|
|
113
119
|
}
|
|
114
|
-
}
|
|
120
|
+
};
|
|
121
|
+
const withQueryToken = createAuthenticate => () => {
|
|
122
|
+
const list = createAuthenticate() || [];
|
|
123
|
+
return list.length ? [queryTokenToAuthorization, ...list] : list;
|
|
124
|
+
};
|
|
125
|
+
options.createAuthenticate = withQueryToken(options.createAuthenticate);
|
|
126
|
+
options.createUserAuthenticate = withQueryToken(options.createUserAuthenticate);
|
|
115
127
|
|
|
116
|
-
|
|
128
|
+
// 宿主可能已注册(如 fastify-file-manager),重复注册会报错
|
|
129
|
+
if (!fastify.hasDecorator('multipartErrors')) {
|
|
130
|
+
await fastify.register(require('@fastify/multipart'), {
|
|
131
|
+
limits: {
|
|
132
|
+
fileSize: options.maxZipSize
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (!fastify.hasReplyDecorator('from')) {
|
|
138
|
+
await fastify.register(require('@fastify/reply-from'));
|
|
139
|
+
}
|
|
117
140
|
|
|
118
141
|
fastify.register(require('@kne/fastify-namespace'), {
|
|
119
142
|
options,
|
package/libs/controllers/app.js
CHANGED
|
@@ -94,6 +94,28 @@ module.exports = fp(async (fastify, options) => {
|
|
|
94
94
|
async () => services.app.centerList({ publicOnly: true })
|
|
95
95
|
);
|
|
96
96
|
|
|
97
|
+
fastify.get(
|
|
98
|
+
`${options.prefix}/app/center/webmanifest`,
|
|
99
|
+
{
|
|
100
|
+
schema: {
|
|
101
|
+
summary: '应用中心:公开应用的 PWA manifest(无需登录)',
|
|
102
|
+
querystring: {
|
|
103
|
+
type: 'object',
|
|
104
|
+
required: ['name'],
|
|
105
|
+
properties: {
|
|
106
|
+
name: { type: 'string' },
|
|
107
|
+
path: { type: 'string' }
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
async (request, reply) => {
|
|
113
|
+
const manifest = await services.app.pwaManifest({ name: request.query.name, path: request.query.path });
|
|
114
|
+
reply.type('application/manifest+json; charset=utf-8').send(manifest);
|
|
115
|
+
return reply;
|
|
116
|
+
}
|
|
117
|
+
);
|
|
118
|
+
|
|
97
119
|
fastify.post(
|
|
98
120
|
`${options.prefix}/app/save-env`,
|
|
99
121
|
{
|
|
@@ -145,7 +167,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
145
167
|
let { name, version, label, fileId } = request.isMultipart() ? {} : request.body || {};
|
|
146
168
|
let zipBuffer;
|
|
147
169
|
if (request.isMultipart()) {
|
|
148
|
-
for await (const part of request.parts()) {
|
|
170
|
+
for await (const part of request.parts({ limits: { fileSize: options.maxZipSize } })) {
|
|
149
171
|
if (part.type === 'file') {
|
|
150
172
|
zipBuffer = await part.toBuffer();
|
|
151
173
|
} else {
|
|
@@ -24,7 +24,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
24
24
|
const rawUrl = request.raw.url || '/';
|
|
25
25
|
const targetPath = stripPrefix ? stripMountPrefix(rawUrl, app.name) : rawUrl;
|
|
26
26
|
|
|
27
|
-
const dest = `http
|
|
27
|
+
const dest = `http://${options.upstreamHost}:${app.port}${targetPath}`;
|
|
28
28
|
const mountPrefix = `${pathPrefix}/${app.name}`;
|
|
29
29
|
|
|
30
30
|
const tracker = fastify[ns].requestMetrics?.begin(app.name);
|
|
@@ -196,7 +196,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
196
196
|
}
|
|
197
197
|
|
|
198
198
|
req.url = targetPath;
|
|
199
|
-
wsProxy.ws(req, socket, head, { target: `http
|
|
199
|
+
wsProxy.ws(req, socket, head, { target: `http://${options.upstreamHost}:${app.port}` }, error => {
|
|
200
200
|
fastify.log.warn({ err: error, app: app.name }, 'websocket upgrade proxy failed');
|
|
201
201
|
rejectUpgrade(socket, 502);
|
|
202
202
|
});
|
package/libs/services/app.js
CHANGED
|
@@ -27,6 +27,7 @@ const { toIsoInTz, convertLogText } = require('../utils/logTime');
|
|
|
27
27
|
const { runSqlMigrations, MIGRATION_ACTIONS } = require('../utils/migrate');
|
|
28
28
|
const { readSqlDir, writeSqlDir } = require('../utils/versionSql');
|
|
29
29
|
const { createDeployProgress } = require('../utils/deployProgress');
|
|
30
|
+
const pwaDocument = require('@kne/pwa-document');
|
|
30
31
|
const pm2Util = require('../utils/pm2');
|
|
31
32
|
|
|
32
33
|
const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
|
|
@@ -136,7 +137,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
136
137
|
const port = await portPool.allocate({
|
|
137
138
|
models,
|
|
138
139
|
portMin: options.portMin,
|
|
139
|
-
portMax: options.portMax
|
|
140
|
+
portMax: options.portMax,
|
|
141
|
+
host: options.upstreamHost
|
|
140
142
|
});
|
|
141
143
|
|
|
142
144
|
const normalizedOptions = Object.assign({}, appOptions || {});
|
|
@@ -267,6 +269,31 @@ module.exports = fp(async (fastify, options) => {
|
|
|
267
269
|
return { pageData, totalCount: pageData.length };
|
|
268
270
|
};
|
|
269
271
|
|
|
272
|
+
const pwaOptions = () => ({ manifestPrefix: options.prefix, staticPrefix: options.pwaIconPrefix });
|
|
273
|
+
|
|
274
|
+
/** 公开应用的 webmanifest;path 为应用入口地址,不传或不匹配时用应用根路径 */
|
|
275
|
+
const pwaManifest = async ({ name, path: surfacePath } = {}) => {
|
|
276
|
+
const { pageData } = await centerList({ publicOnly: true });
|
|
277
|
+
const app = pageData.find(item => item.name === name);
|
|
278
|
+
if (!app) {
|
|
279
|
+
httpError(404, `app ${name} not found`);
|
|
280
|
+
}
|
|
281
|
+
const surfaces = pwaDocument.appSurfaces(app);
|
|
282
|
+
const wanted = pwaDocument.normalizePath(surfacePath || app.pathUrl);
|
|
283
|
+
const surface = surfaces.find(item => pwaDocument.normalizePath(item.path) === wanted) || surfaces[0];
|
|
284
|
+
return pwaDocument.buildWebManifest(app, {
|
|
285
|
+
path: surface.path,
|
|
286
|
+
title: surface.title,
|
|
287
|
+
icon: pwaDocument.iconUrlFor(app.icon, pwaOptions())
|
|
288
|
+
});
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/** 按请求路径匹配公开应用入口,shellEntries 为宿主自身页面;无匹配返回 null */
|
|
292
|
+
const resolvePwaEntry = async (urlPath, { shellEntries = [], defaultIcon } = {}) => {
|
|
293
|
+
const { pageData } = await centerList({ publicOnly: true });
|
|
294
|
+
return pwaDocument.resolveEntry(urlPath, pageData, Object.assign(pwaOptions(), { shellEntries, defaultIcon }));
|
|
295
|
+
};
|
|
296
|
+
|
|
270
297
|
const detail = async ({ name }) => {
|
|
271
298
|
const app = await getByName(name);
|
|
272
299
|
return Object.assign(toPublicApp(app), { deployment: deployProgress.active(app.name), lastDeployment: await lastDeployment(app.name) });
|
|
@@ -463,7 +490,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
463
490
|
|
|
464
491
|
const healthCheck = async (port, { timeoutMs, intervalMs, healthPath }) => {
|
|
465
492
|
const started = Date.now();
|
|
466
|
-
const url = `http
|
|
493
|
+
const url = `http://${options.upstreamHost}:${port}${healthPath || '/'}`;
|
|
467
494
|
while (Date.now() - started < timeoutMs) {
|
|
468
495
|
try {
|
|
469
496
|
const res = await fetch(url, { method: 'GET' });
|
|
@@ -782,7 +809,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
782
809
|
}
|
|
783
810
|
|
|
784
811
|
if (typeof options.resolveSystemEnv === 'function') {
|
|
785
|
-
const systemEnv = await options.resolveSystemEnv({ app, version, serverDir });
|
|
812
|
+
const systemEnv = await options.resolveSystemEnv({ app, version, serverDir, upstreamUrl: `http://${options.upstreamHost}:${app.port}` });
|
|
786
813
|
const injectedKeys = [];
|
|
787
814
|
if (systemEnv && typeof systemEnv === 'object') {
|
|
788
815
|
const persisted = {};
|
|
@@ -1439,6 +1466,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1439
1466
|
saveEnv,
|
|
1440
1467
|
list,
|
|
1441
1468
|
centerList,
|
|
1469
|
+
pwaManifest,
|
|
1470
|
+
resolvePwaEntry,
|
|
1442
1471
|
detail,
|
|
1443
1472
|
uploadVersion,
|
|
1444
1473
|
listVersions,
|
package/libs/utils/portPool.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const net = require('node:net');
|
|
2
2
|
|
|
3
|
-
const isPortFree = port =>
|
|
3
|
+
const isPortFree = (port, host = '127.0.0.1') =>
|
|
4
4
|
new Promise(resolve => {
|
|
5
5
|
const server = net.createServer();
|
|
6
6
|
server.unref();
|
|
@@ -8,19 +8,19 @@ const isPortFree = port =>
|
|
|
8
8
|
server.once('listening', () => {
|
|
9
9
|
server.close(() => resolve(true));
|
|
10
10
|
});
|
|
11
|
-
server.listen(port,
|
|
11
|
+
server.listen(port, host);
|
|
12
12
|
});
|
|
13
13
|
|
|
14
14
|
module.exports = {
|
|
15
15
|
isPortFree,
|
|
16
|
-
async allocate({ models, portMin, portMax, excludePorts = [] }) {
|
|
16
|
+
async allocate({ models, portMin, portMax, excludePorts = [], host }) {
|
|
17
17
|
const rows = await models.app.findAll({ attributes: ['port'] });
|
|
18
18
|
const used = new Set([...rows.map(r => r.port), ...excludePorts]);
|
|
19
19
|
for (let port = portMin; port <= portMax; port++) {
|
|
20
20
|
if (used.has(port)) {
|
|
21
21
|
continue;
|
|
22
22
|
}
|
|
23
|
-
if (await isPortFree(port)) {
|
|
23
|
+
if (await isPortFree(port, host)) {
|
|
24
24
|
return port;
|
|
25
25
|
}
|
|
26
26
|
}
|
package/oidc.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 应用中心子应用 OIDC 接入(可选):宿主已注册 @kne/fastify-oidc 作为主 IdP 时使用。
|
|
3
|
+
* 子应用 server 依赖 @kne/fastify-oidc 时,部署时登记资源服务与 client,并以 central 模式启动;
|
|
4
|
+
* 子应用在 server/env.schema.json 中声明 AUTH_MODE 默认值为 standalone 时,保持自己的登录。
|
|
5
|
+
*/
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
const fs = require('fs-extra');
|
|
8
|
+
const isEqual = require('lodash/isEqual');
|
|
9
|
+
// 宿主启用 OIDC 时才会用到,未安装 @kne/fastify-oidc 的宿主不受影响
|
|
10
|
+
const oidcCrypto = () => require('@kne/fastify-oidc/libs/utils/crypto');
|
|
11
|
+
const OIDC_PACKAGE = '@kne/fastify-oidc';
|
|
12
|
+
// 子应用 @kne/fastify-app-runtime 的 /open-api.json 放行带此 scope 的 client 令牌
|
|
13
|
+
const OPEN_API_SCOPE = 'open-api:read';
|
|
14
|
+
const DOCS_CLIENT_ID = 'app-center-docs';
|
|
15
|
+
|
|
16
|
+
const SYSTEM_ENV_KEYS = ['AUTH_MODE', 'OIDC_ISSUER', 'OIDC_AUDIENCE', 'OIDC_CLIENT_ID', 'OIDC_SERVICE_CLIENT_ID', 'OIDC_SERVICE_CLIENT_SECRET'];
|
|
17
|
+
|
|
18
|
+
const supportsOidc = async serverDir => {
|
|
19
|
+
try {
|
|
20
|
+
const pkg = await fs.readJson(path.join(serverDir, 'package.json'));
|
|
21
|
+
return !!pkg.dependencies?.[OIDC_PACKAGE];
|
|
22
|
+
} catch (e) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const prefersStandalone = async serverDir => {
|
|
28
|
+
try {
|
|
29
|
+
const schema = await fs.readJson(path.join(serverDir, 'env.schema.json'));
|
|
30
|
+
return schema?.properties?.AUTH_MODE?.default === 'standalone';
|
|
31
|
+
} catch (e) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param fastify 已注册 @kne/fastify-oidc 的宿主实例
|
|
38
|
+
* @param options.origin 宿主对外地址,拼子应用回调地址与 audience
|
|
39
|
+
* @param options.issuer 宿主 IdP issuer
|
|
40
|
+
* @param options.serviceAudience 子应用服务 client 可访问的宿主资源标识
|
|
41
|
+
* @param options.pathPrefix 应用中心路径前缀,与 app-manager 的 pathPrefix 一致
|
|
42
|
+
* @param options.backchannelLogoutPath 子应用 fastify-oidc 的登出通知路径,默认与其默认 prefix /api/oidc 对应
|
|
43
|
+
*/
|
|
44
|
+
const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix = '/app', backchannelLogoutPath = '/api/oidc/backchannel-logout' } = {}) => {
|
|
45
|
+
if (!origin || !issuer || !serviceAudience) {
|
|
46
|
+
throw new Error('createAppOidc requires origin, issuer and serviceAudience');
|
|
47
|
+
}
|
|
48
|
+
origin = origin.replace(/\/+$/, '');
|
|
49
|
+
const oidc = () => fastify.oidc;
|
|
50
|
+
const { protocol } = new URL(origin);
|
|
51
|
+
|
|
52
|
+
const clientIds = name => ({ spa: `app-${name}`, service: `app-${name}-service` });
|
|
53
|
+
|
|
54
|
+
const resolveUrls = app => {
|
|
55
|
+
const pathBase = `${origin}${pathPrefix}/${app.name}`;
|
|
56
|
+
const domainBase = app.domain ? `${protocol}//${app.domain}` : null;
|
|
57
|
+
return {
|
|
58
|
+
bases: [domainBase, pathBase].filter(Boolean),
|
|
59
|
+
// 子应用用 ORIGIN 拼邀请 / 重置密码等对外链接,路径模式必须带 /app/{name};fastify-oidc 只取其 origin 部分
|
|
60
|
+
appUrl: domainBase || pathBase,
|
|
61
|
+
// 资源标识只作 token 的 aud,固定用路径形式,绑定 / 更换域名后不变
|
|
62
|
+
audience: `${pathBase}/api`
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const spaMetadata = ({ bases }, upstreamUrl) => ({
|
|
67
|
+
application_type: 'web',
|
|
68
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
69
|
+
response_types: ['code'],
|
|
70
|
+
token_endpoint_auth_method: 'none',
|
|
71
|
+
redirect_uris: bases.map(base => `${base}/oidc-callback`),
|
|
72
|
+
post_logout_redirect_uris: bases.map(base => `${base}/`),
|
|
73
|
+
// 登出通知直连子应用进程(地址由 app-manager 的 upstreamHost 决定),不经过网关
|
|
74
|
+
backchannel_logout_uri: `${upstreamUrl}${backchannelLogoutPath}`,
|
|
75
|
+
backchannel_logout_session_required: true
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const ensureResourceServer = async ({ identifier, name }) => {
|
|
79
|
+
const { models, services, options } = oidc();
|
|
80
|
+
const existing = await models.resourceServer.findOne({ where: { identifier } });
|
|
81
|
+
if (!existing) {
|
|
82
|
+
await services.resourceServer.create({ identifier, name, scope: `${options.defaultResourceScope} ${OPEN_API_SCOPE}`, description: '应用中心子应用自动登记' });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const scopes = String(existing.scope || options.defaultResourceScope)
|
|
86
|
+
.split(' ')
|
|
87
|
+
.filter(Boolean);
|
|
88
|
+
if (!scopes.includes(OPEN_API_SCOPE)) {
|
|
89
|
+
await existing.update({ scope: [...scopes, OPEN_API_SCOPE].join(' ') });
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const ensureSpaClient = async ({ clientId, clientName, metadata, allowedResources }) => {
|
|
94
|
+
const { models, services } = oidc();
|
|
95
|
+
const existing = await models.client.findOne({ where: { clientId } });
|
|
96
|
+
if (!existing) {
|
|
97
|
+
await services.client.create({ clientId, clientName, metadata, allowedResources, description: '应用中心子应用自动登记' });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const nextMetadata = Object.assign({}, existing.metadata, metadata);
|
|
101
|
+
if (!isEqual(nextMetadata, existing.metadata) || !isEqual(allowedResources, existing.allowedResources)) {
|
|
102
|
+
await services.client.save({ id: existing.id, metadata: nextMetadata, allowedResources });
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const ensureServiceClient = async ({ clientId, clientName }) => {
|
|
107
|
+
const { models, services, options } = oidc();
|
|
108
|
+
const existing = await models.client.findOne({ where: { clientId } });
|
|
109
|
+
if (!existing) {
|
|
110
|
+
const clientSecret = oidcCrypto().randomSecret(32);
|
|
111
|
+
await services.client.create({
|
|
112
|
+
clientId,
|
|
113
|
+
clientName,
|
|
114
|
+
clientSecret,
|
|
115
|
+
metadata: { grant_types: ['client_credentials'], response_types: [], token_endpoint_auth_method: 'client_secret_basic' },
|
|
116
|
+
allowedResources: [serviceAudience],
|
|
117
|
+
description: '应用中心子应用自动登记'
|
|
118
|
+
});
|
|
119
|
+
return clientSecret;
|
|
120
|
+
}
|
|
121
|
+
// 以认证管理中的实际 secret 为准(管理员可能重置过)
|
|
122
|
+
return oidcCrypto().decrypt(options.keyEncryptionSecret, existing.clientSecret);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** 本系统读取子应用文档用的 client:allowedResources 随需要读取的子应用 audience 增加 */
|
|
126
|
+
const ensureDocsClient = async audience => {
|
|
127
|
+
const { models, services, options } = oidc();
|
|
128
|
+
const existing = await models.client.findOne({ where: { clientId: DOCS_CLIENT_ID } });
|
|
129
|
+
if (!existing) {
|
|
130
|
+
const clientSecret = oidcCrypto().randomSecret(32);
|
|
131
|
+
await services.client.create({
|
|
132
|
+
clientId: DOCS_CLIENT_ID,
|
|
133
|
+
clientName: '应用中心文档读取',
|
|
134
|
+
clientSecret,
|
|
135
|
+
metadata: { grant_types: ['client_credentials'], response_types: [], token_endpoint_auth_method: 'client_secret_basic' },
|
|
136
|
+
allowedResources: [audience],
|
|
137
|
+
description: '应用中心 MCP 读取子应用 OpenAPI 文档'
|
|
138
|
+
});
|
|
139
|
+
return clientSecret;
|
|
140
|
+
}
|
|
141
|
+
const allowedResources = existing.allowedResources || [];
|
|
142
|
+
if (!allowedResources.includes(audience)) {
|
|
143
|
+
await services.client.save({ id: existing.id, allowedResources: [...allowedResources, audience] });
|
|
144
|
+
}
|
|
145
|
+
return oidcCrypto().decrypt(options.keyEncryptionSecret, existing.clientSecret);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const docsTokenCache = new Map();
|
|
149
|
+
|
|
150
|
+
/** 签发访问子应用 /open-api.json 的服务令牌(audience 为子应用 OIDC_AUDIENCE,scope 为 open-api:read) */
|
|
151
|
+
const getOpenApiToken = async app => {
|
|
152
|
+
// app 详情接口会剔除系统注入的 env,audience 按部署时相同规则推导,以资源服务是否已登记判断接入
|
|
153
|
+
const { audience } = resolveUrls(app);
|
|
154
|
+
await oidc().whenReady();
|
|
155
|
+
if (!(await oidc().models.resourceServer.findOne({ where: { identifier: audience } }))) {
|
|
156
|
+
throw new Error(`应用 ${app.name} 未接入 OIDC(server 未依赖 ${OIDC_PACKAGE} 或尚未部署),无法签发读取文档的令牌`);
|
|
157
|
+
}
|
|
158
|
+
await ensureResourceServer({ identifier: audience, name: app.label || app.name });
|
|
159
|
+
const cached = docsTokenCache.get(audience);
|
|
160
|
+
if (cached && cached.expiresAt - 30 * 1000 > Date.now()) {
|
|
161
|
+
return cached.accessToken;
|
|
162
|
+
}
|
|
163
|
+
const clientSecret = await ensureDocsClient(audience);
|
|
164
|
+
// IdP 挂在本进程上,直接 inject 到 token 端点,不经公网 issuer 地址绕回自身
|
|
165
|
+
const response = await fastify.inject({
|
|
166
|
+
method: 'POST',
|
|
167
|
+
url: `${new URL(issuer).pathname}/token`,
|
|
168
|
+
headers: {
|
|
169
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
170
|
+
authorization: `Basic ${Buffer.from(`${encodeURIComponent(DOCS_CLIENT_ID)}:${encodeURIComponent(clientSecret)}`).toString('base64')}`
|
|
171
|
+
},
|
|
172
|
+
payload: new URLSearchParams({ grant_type: 'client_credentials', resource: audience, scope: OPEN_API_SCOPE }).toString()
|
|
173
|
+
});
|
|
174
|
+
const data = response.json();
|
|
175
|
+
if (response.statusCode !== 200) {
|
|
176
|
+
throw new Error(`签发读取文档的令牌失败:${data.error_description || data.error || response.statusCode}`);
|
|
177
|
+
}
|
|
178
|
+
docsTokenCache.set(audience, { accessToken: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 });
|
|
179
|
+
return data.access_token;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/** 以登录用户身份签发访问子应用 API 的用户令牌(audience 为子应用 OIDC_AUDIENCE) */
|
|
183
|
+
const issueUserAccessToken = async ({ app, userId, tenantId }) => {
|
|
184
|
+
const { audience } = resolveUrls(app);
|
|
185
|
+
await oidc().whenReady();
|
|
186
|
+
const resource = await oidc().models.resourceServer.findOne({ where: { identifier: audience } });
|
|
187
|
+
if (!resource) {
|
|
188
|
+
throw new Error(`应用 ${app.name} 未接入 OIDC(server 未依赖 ${OIDC_PACKAGE} 或尚未部署),无法代登录用户调用`);
|
|
189
|
+
}
|
|
190
|
+
const provider = oidc().idp.getProvider();
|
|
191
|
+
if (!provider) {
|
|
192
|
+
throw new Error('IdP 尚未就绪,无法代登录用户调用');
|
|
193
|
+
}
|
|
194
|
+
const client = await provider.Client.find(clientIds(app.name).spa);
|
|
195
|
+
if (!client) {
|
|
196
|
+
throw new Error(`应用 ${app.name} 尚未登记登录客户端,请先完成一次部署`);
|
|
197
|
+
}
|
|
198
|
+
const scope =
|
|
199
|
+
String(resource.scope || oidc().options.defaultResourceScope)
|
|
200
|
+
.split(/\s+/)
|
|
201
|
+
.filter(item => item && item !== OPEN_API_SCOPE)
|
|
202
|
+
.join(' ') || oidc().options.defaultResourceScope;
|
|
203
|
+
const token = new provider.AccessToken({
|
|
204
|
+
client,
|
|
205
|
+
accountId: String(userId),
|
|
206
|
+
scope,
|
|
207
|
+
gty: 'mcp'
|
|
208
|
+
});
|
|
209
|
+
token.resourceServer = new provider.ResourceServer(audience, {
|
|
210
|
+
scope: resource.scope,
|
|
211
|
+
audience,
|
|
212
|
+
accessTokenTTL: resource.accessTokenTTL || oidc().options.ttl.accessToken,
|
|
213
|
+
accessTokenFormat: 'jwt',
|
|
214
|
+
jwt: { sign: { alg: 'RS256' } }
|
|
215
|
+
});
|
|
216
|
+
if (tenantId) {
|
|
217
|
+
token.kneTenantId = String(tenantId);
|
|
218
|
+
}
|
|
219
|
+
return token.save();
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const resolveSystemEnv = async ({ app, serverDir, upstreamUrl }) => {
|
|
223
|
+
if (!(await supportsOidc(serverDir)) || (await prefersStandalone(serverDir))) {
|
|
224
|
+
// 之前以 central 启动过的应用,持久化的 AUTH_MODE 需覆盖回 standalone
|
|
225
|
+
return app.env?.AUTH_MODE ? { AUTH_MODE: 'standalone' } : null;
|
|
226
|
+
}
|
|
227
|
+
await oidc().whenReady();
|
|
228
|
+
const urls = resolveUrls(app);
|
|
229
|
+
const ids = clientIds(app.name);
|
|
230
|
+
await ensureResourceServer({ identifier: urls.audience, name: app.label || app.name });
|
|
231
|
+
await ensureSpaClient({
|
|
232
|
+
clientId: ids.spa,
|
|
233
|
+
clientName: app.label || app.name,
|
|
234
|
+
metadata: spaMetadata(urls, upstreamUrl),
|
|
235
|
+
allowedResources: [urls.audience]
|
|
236
|
+
});
|
|
237
|
+
const serviceSecret = await ensureServiceClient({ clientId: ids.service, clientName: `${app.label || app.name} 服务端` });
|
|
238
|
+
|
|
239
|
+
return Object.assign(
|
|
240
|
+
{
|
|
241
|
+
AUTH_MODE: 'central',
|
|
242
|
+
OIDC_ISSUER: issuer,
|
|
243
|
+
OIDC_AUDIENCE: urls.audience,
|
|
244
|
+
OIDC_CLIENT_ID: ids.spa,
|
|
245
|
+
OIDC_SERVICE_CLIENT_ID: ids.service,
|
|
246
|
+
OIDC_SERVICE_CLIENT_SECRET: serviceSecret
|
|
247
|
+
},
|
|
248
|
+
app.env?.ORIGIN ? {} : { ORIGIN: urls.appUrl }
|
|
249
|
+
);
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const onAppRemoved = async ({ app }) => {
|
|
253
|
+
if (!app.env?.OIDC_CLIENT_ID) {
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const { models, services } = oidc();
|
|
257
|
+
await oidc().whenReady();
|
|
258
|
+
for (const clientId of [app.env.OIDC_CLIENT_ID, app.env.OIDC_SERVICE_CLIENT_ID].filter(Boolean)) {
|
|
259
|
+
const item = await models.client.findOne({ where: { clientId } });
|
|
260
|
+
if (item) {
|
|
261
|
+
await services.client.remove({ id: item.id });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (app.env.OIDC_AUDIENCE) {
|
|
265
|
+
const docsClient = await models.client.findOne({ where: { clientId: DOCS_CLIENT_ID } });
|
|
266
|
+
if (docsClient && (docsClient.allowedResources || []).includes(app.env.OIDC_AUDIENCE)) {
|
|
267
|
+
await services.client.save({ id: docsClient.id, allowedResources: docsClient.allowedResources.filter(item => item !== app.env.OIDC_AUDIENCE) });
|
|
268
|
+
}
|
|
269
|
+
const item = await models.resourceServer.findOne({ where: { identifier: app.env.OIDC_AUDIENCE } });
|
|
270
|
+
if (item) {
|
|
271
|
+
await services.resourceServer.remove({ id: item.id });
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
return { systemEnvKeys: SYSTEM_ENV_KEYS, resolveSystemEnv, onAppRemoved, getOpenApiToken, issueUserAccessToken };
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
module.exports = createAppOidc;
|
|
280
|
+
module.exports.supportsOidc = supportsOidc;
|
|
281
|
+
module.exports.prefersStandalone = prefersStandalone;
|
|
282
|
+
module.exports.SYSTEM_ENV_KEYS = SYSTEM_ENV_KEYS;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kne/fastify-app-manager",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.20",
|
|
4
4
|
"description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
},
|
|
21
21
|
"files": [
|
|
22
22
|
"index.js",
|
|
23
|
+
"oidc.js",
|
|
23
24
|
"libs"
|
|
24
25
|
],
|
|
25
26
|
"repository": {
|
|
@@ -46,7 +47,13 @@
|
|
|
46
47
|
"peerDependencies": {
|
|
47
48
|
"@kne/fastify-namespace": "*",
|
|
48
49
|
"@kne/fastify-sequelize": "*",
|
|
49
|
-
"fastify-plugin": ">=5"
|
|
50
|
+
"fastify-plugin": ">=5",
|
|
51
|
+
"@kne/fastify-oidc": "*"
|
|
52
|
+
},
|
|
53
|
+
"peerDependenciesMeta": {
|
|
54
|
+
"@kne/fastify-oidc": {
|
|
55
|
+
"optional": true
|
|
56
|
+
}
|
|
50
57
|
},
|
|
51
58
|
"devDependencies": {
|
|
52
59
|
"@fastify/env": "^5.0.2",
|
|
@@ -68,6 +75,7 @@
|
|
|
68
75
|
"@fastify/multipart": "^10.1.1",
|
|
69
76
|
"@fastify/reply-from": "^12.6.5",
|
|
70
77
|
"@kne/ensure-slash": "^0.1.0",
|
|
78
|
+
"@kne/pwa-document": "^0.1.0",
|
|
71
79
|
"adm-zip": "^0.6.0",
|
|
72
80
|
"ajv": "^8.17.1",
|
|
73
81
|
"fs-extra": "^11.4.0",
|