@kne/fastify-app-manager 0.1.29 → 0.1.30

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/index.js CHANGED
@@ -55,6 +55,18 @@ module.exports = fp(
55
55
  getOpenApiToken: null,
56
56
  /** async ({ app, userId, tenantId }) => accessToken,以登录用户身份签发子应用令牌;不传则 /app/open-api/token 不可用 */
57
57
  issueUserAccessToken: null,
58
+ /**
59
+ * 外部关联(linked)应用:
60
+ * - origin:本平台对外 ORIGIN,须与 installKey.platformOrigin 一致
61
+ * - signPlatformAssertion / ensureLinkedRegistration / getOpsServiceToken:通常来自 createAppOidc 返回值
62
+ * - linkSyncIntervalMs:定时同步权限/健康,0 表示仅启动时同步一次
63
+ */
64
+ origin: null,
65
+ signPlatformAssertion: null,
66
+ ensureLinkedRegistration: null,
67
+ getOpsServiceToken: null,
68
+ linkSyncIntervalMs: 5 * 60 * 1000,
69
+ linkProxyTimeoutMs: 15000,
58
70
  /** async ({ fileId, name, version, request }) => Buffer,版本上传传 fileId 时读取宿主文件 */
59
71
  resolveVersionFile: null,
60
72
  secretEnvKeyPattern: /(SECRET|PASSWORD|TOKEN|KEY|PRIVATE)/i,
@@ -0,0 +1,68 @@
1
+ const fp = require('fastify-plugin');
2
+ const { str, obj, success, any } = require('../schema/response');
3
+
4
+ const TAG_APP = '应用中心管理后台-应用';
5
+
6
+ module.exports = fp(async (fastify, options) => {
7
+ const { services } = fastify[options.name];
8
+ const auth = () => options.createAuthenticate();
9
+
10
+ fastify.post(
11
+ `${options.prefix}/app/link/import`,
12
+ {
13
+ onRequest: auth(),
14
+ schema: {
15
+ tags: [TAG_APP],
16
+ summary: '凭 installKey 添加外部关联应用',
17
+ description: '解析远程登记生成的 installKey,用本平台 IdP 断言兑换并激活;创建 kind=linked 应用,不分配本机端口/PM2。需宿主配置 origin 与 createAppOidc 的 ensureLinkedRegistration / signPlatformAssertion / getServiceToken。',
18
+ body: {
19
+ type: 'object',
20
+ required: ['installKey'],
21
+ properties: {
22
+ installKey: { type: 'string', description: '远程一次性安装密钥(base64url JSON)' },
23
+ name: { type: 'string', description: '可选覆盖应用 slug;默认取 key 内 appName' },
24
+ label: { type: 'string', description: '可选覆盖显示名' }
25
+ }
26
+ },
27
+ response: success('导入后的应用', obj({ name: str('应用 name'), kind: str('managed|linked'), status: str('状态') }))
28
+ }
29
+ },
30
+ async request => services.link.importByInstallKey(request.body || {})
31
+ );
32
+
33
+ fastify.post(
34
+ `${options.prefix}/app/link/sync`,
35
+ {
36
+ onRequest: auth(),
37
+ schema: {
38
+ tags: [TAG_APP],
39
+ summary: '同步全部外部关联应用',
40
+ description: '拉取远程权限树快照、幂等 ensure OIDC,并探测 /ready 写回 status',
41
+ response: success('同步结果', any())
42
+ }
43
+ },
44
+ async () => services.link.syncAllLinked()
45
+ );
46
+
47
+ fastify.post(
48
+ `${options.prefix}/app/:name/link/sync`,
49
+ {
50
+ onRequest: auth(),
51
+ schema: {
52
+ tags: [TAG_APP],
53
+ summary: '同步单个外部关联应用',
54
+ params: {
55
+ type: 'object',
56
+ required: ['name'],
57
+ properties: { name: { type: 'string', description: '应用 name' } }
58
+ },
59
+ response: success('同步结果', any())
60
+ }
61
+ },
62
+ async request => {
63
+ const app = await services.app.detail({ name: request.params.name });
64
+ const row = await fastify[options.name].models.app.findOne({ where: { name: app.name } });
65
+ return services.link.syncOne(row);
66
+ }
67
+ );
68
+ });
@@ -13,11 +13,17 @@ module.exports = ({ DataTypes }) => {
13
13
  allowNull: false,
14
14
  comment: '用户可见应用名'
15
15
  },
16
+ kind: {
17
+ type: DataTypes.STRING,
18
+ allowNull: false,
19
+ defaultValue: 'managed',
20
+ comment: 'managed=本机托管 | linked=外部关联'
21
+ },
16
22
  domain: {
17
23
  type: DataTypes.STRING,
18
24
  allowNull: true,
19
25
  unique: true,
20
- comment: '绑定域名 Host'
26
+ comment: '绑定域名 Host;linked 必须为空'
21
27
  },
22
28
  icon: {
23
29
  type: DataTypes.STRING,
@@ -45,12 +51,12 @@ module.exports = ({ DataTypes }) => {
45
51
  type: DataTypes.JSON,
46
52
  allowNull: false,
47
53
  defaultValue: {},
48
- comment: '扩展字段'
54
+ comment: '扩展字段(linked 含 baseUrl / linkStatus / permissionsSnapshot)'
49
55
  },
50
56
  port: {
51
57
  type: DataTypes.INTEGER,
52
- allowNull: false,
53
- comment: '分配端口'
58
+ allowNull: true,
59
+ comment: '分配端口;linked 可空'
54
60
  },
55
61
  status: {
56
62
  type: DataTypes.STRING,
@@ -65,14 +71,14 @@ module.exports = ({ DataTypes }) => {
65
71
  },
66
72
  rootPath: {
67
73
  type: DataTypes.STRING,
68
- allowNull: false,
69
- comment: '应用根目录'
74
+ allowNull: true,
75
+ comment: '应用根目录;linked 可空'
70
76
  },
71
77
  pm2Name: {
72
78
  type: DataTypes.STRING,
73
- allowNull: false,
79
+ allowNull: true,
74
80
  unique: true,
75
- comment: 'PM2 进程名'
81
+ comment: 'PM2 进程名;linked 可空'
76
82
  },
77
83
  message: {
78
84
  type: DataTypes.TEXT,
@@ -82,7 +88,7 @@ module.exports = ({ DataTypes }) => {
82
88
  },
83
89
  options: {
84
90
  comment: '托管应用',
85
- indexes: [{ fields: ['status'] }, { fields: ['domain'] }]
91
+ indexes: [{ fields: ['status'] }, { fields: ['domain'] }, { fields: ['kind'] }]
86
92
  }
87
93
  };
88
94
  };
@@ -30,6 +30,7 @@ const { readSqlDir, writeSqlDir } = require('../utils/versionSql');
30
30
  const { createDeployProgress } = require('../utils/deployProgress');
31
31
  const pwaDocument = require('@kne/pwa-document');
32
32
  const pm2Util = require('../utils/pm2');
33
+ const { KIND_MANAGED, KIND_LINKED, isLinked, linkedBaseUrl, assertNotLinked } = require('../utils/appKind');
33
34
 
34
35
  const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
35
36
 
@@ -81,8 +82,14 @@ module.exports = fp(async (fastify, options) => {
81
82
  }, []);
82
83
  };
83
84
  const resolveEntries = appLike => {
84
- const base = mountPrefix(appLike.name);
85
- return normalizeEntries(appLike.options?.entries).map(entry => Object.assign({}, entry, { url: `${base}${entry.path}` }));
85
+ const linked = isLinked(appLike);
86
+ const remote = linked ? linkedBaseUrl(appLike) : null;
87
+ const base = remote || mountPrefix(appLike.name);
88
+ return normalizeEntries(appLike.options?.entries).map(entry => {
89
+ const pathPart = entry.path.startsWith('/') ? entry.path : `/${entry.path}`;
90
+ const url = remote ? `${remote}${pathPart}` : `${base}${pathPart}`;
91
+ return Object.assign({}, entry, { path: remote ? url : entry.path, url });
92
+ });
86
93
  };
87
94
 
88
95
  const toPublicApp = app => {
@@ -95,7 +102,11 @@ module.exports = fp(async (fastify, options) => {
95
102
  json.env = maskEnvForResponse(json.env || {}, envOpts);
96
103
  json.passthroughEnvKeys = options.passthroughEnvKeys || [];
97
104
  json.secretEnvKeys = collectSecretKeys(json.env || {}, envOpts);
98
- json.pathUrl = `${mountPrefix(json.name)}/`;
105
+ const linked = isLinked(json);
106
+ const remote = linked ? linkedBaseUrl(json) : null;
107
+ json.pathUrl = remote ? `${remote}/` : `${mountPrefix(json.name)}/`;
108
+ json.openUrl = json.pathUrl;
109
+ json.kind = linked ? KIND_LINKED : KIND_MANAGED;
99
110
  json.category = json.options?.category || null;
100
111
  json.isPublic = isAppPublic(json);
101
112
  json.entries = resolveEntries(json);
@@ -159,6 +170,7 @@ module.exports = fp(async (fastify, options) => {
159
170
  const app = await models.app.create({
160
171
  name,
161
172
  label,
173
+ kind: KIND_MANAGED,
162
174
  domain: domain || null,
163
175
  icon: icon || null,
164
176
  description: description || null,
@@ -218,6 +230,9 @@ module.exports = fp(async (fastify, options) => {
218
230
 
219
231
  const saveEnv = async ({ name, env, secretEnvKeys: nextSecretKeys } = {}) => {
220
232
  const app = await getByName(name);
233
+ if (isLinked(app)) {
234
+ httpError(400, '外部应用环境变量只读,请在远程部署侧修改后重启');
235
+ }
221
236
  // 密钥类型不可撤销,只随变量删除而移除
222
237
  const secretEnvKeys = normalizeSecretKeys([...resolveSecretEnvKeys(app), ...(nextSecretKeys || [])]);
223
238
  // PORT 由端口池分配,启动时总会覆盖,不接受外部写入
@@ -259,15 +274,29 @@ module.exports = fp(async (fastify, options) => {
259
274
  .filter(app => !publicOnly || isAppPublic(app))
260
275
  .map(app => {
261
276
  const active = deployProgress.active(app.name);
277
+ const linked = isLinked(app);
278
+ const base = linked ? linkedBaseUrl(app) : null;
279
+ const pathUrl = linked && base ? `${base}/` : `${mountPrefix(app.name)}/`;
280
+ const entries = resolveEntries(app)
281
+ .filter(entry => entry.showInCenter)
282
+ .map(entry =>
283
+ linked && base
284
+ ? Object.assign({}, entry, {
285
+ path: entry.path.startsWith('http') ? entry.path : `${base}${entry.path.startsWith('/') ? '' : '/'}${entry.path}`
286
+ })
287
+ : entry
288
+ );
262
289
  return {
263
290
  name: app.name,
264
291
  label: app.label,
292
+ kind: linked ? KIND_LINKED : KIND_MANAGED,
265
293
  icon: app.icon,
266
294
  description: app.description,
267
295
  category: app.options?.category || null,
268
296
  isPublic: isAppPublic(app),
269
- pathUrl: `${mountPrefix(app.name)}/`,
270
- entries: resolveEntries(app).filter(entry => entry.showInCenter),
297
+ pathUrl,
298
+ openUrl: pathUrl,
299
+ entries,
271
300
  deployment: active ? { source: active.source } : null
272
301
  };
273
302
  });
@@ -369,6 +398,7 @@ module.exports = fp(async (fastify, options) => {
369
398
  if (!app) {
370
399
  httpError(404, `app ${name} not found; create it first`);
371
400
  }
401
+ assertNotLinked(app, '版本上传');
372
402
  // The (app_name, version) unique index also covers soft-deleted rows, so they must be purged before reuse.
373
403
  const dup = await models.appVersion.findOne({ where: { appName: name, version }, paranoid: false });
374
404
  if (dup && !dup.isSoftDeleted()) {
@@ -789,7 +819,7 @@ module.exports = fp(async (fastify, options) => {
789
819
  const excluded = new Set(excludeIds.map(String));
790
820
  const results = [];
791
821
  for (const app of apps) {
792
- if (excluded.has(String(app.id))) {
822
+ if (excluded.has(String(app.id)) || isLinked(app)) {
793
823
  continue;
794
824
  }
795
825
  const shouldRecover = recoverIfMissing && (app.status === 'running' || app.status === 'deploying');
@@ -905,6 +935,9 @@ module.exports = fp(async (fastify, options) => {
905
935
  */
906
936
  const getEnvDeclaration = async ({ name, versionId } = {}) => {
907
937
  const app = await getByName(name);
938
+ if (isLinked(app)) {
939
+ return fastify[options.name].services.link.proxy.env(app);
940
+ }
908
941
  const ver = await resolveDeclarationVersion(app, versionId);
909
942
  const schema = ver ? await getVersionEnvSchema(ver) : null;
910
943
  const injected = listInjectedEnvKeys(app);
@@ -1012,6 +1045,9 @@ module.exports = fp(async (fastify, options) => {
1012
1045
  const apps = await models.app.findAll({ where: { currentVersionId: { [Op.ne]: null } } });
1013
1046
  const missing = [];
1014
1047
  for (const app of apps) {
1048
+ if (isLinked(app)) {
1049
+ continue;
1050
+ }
1015
1051
  const ver = await models.appVersion.findByPk(app.currentVersionId);
1016
1052
  if (ver && !(await fs.pathExists(path.join(ver.artifactPath, 'server')))) {
1017
1053
  missing.push({ app, ver });
@@ -1119,6 +1155,7 @@ module.exports = fp(async (fastify, options) => {
1119
1155
 
1120
1156
  const deploy = async ({ name, versionId, version, runMigration = true, migrations, progressId }) => {
1121
1157
  const app = await getByName(name);
1158
+ assertNotLinked(app, '部署');
1122
1159
  let ver = null;
1123
1160
  if (versionId) {
1124
1161
  ver = await models.appVersion.findByPk(versionId);
@@ -1250,6 +1287,7 @@ module.exports = fp(async (fastify, options) => {
1250
1287
 
1251
1288
  const stop = async ({ name }) => {
1252
1289
  const app = await getByName(name);
1290
+ assertNotLinked(app, '停止');
1253
1291
  try {
1254
1292
  await pm2Util.stopApp(app.pm2Name);
1255
1293
  } catch (e) {
@@ -1276,6 +1314,7 @@ module.exports = fp(async (fastify, options) => {
1276
1314
 
1277
1315
  const start = async ({ name }) => {
1278
1316
  const app = await getByName(name);
1317
+ assertNotLinked(app, '启动');
1279
1318
  const env = await prepareStartEnv(app);
1280
1319
  await app.update({ status: 'deploying', message: null });
1281
1320
  try {
@@ -1291,6 +1330,7 @@ module.exports = fp(async (fastify, options) => {
1291
1330
 
1292
1331
  const restart = async ({ name }) => {
1293
1332
  const app = await getByName(name);
1333
+ assertNotLinked(app, '重启');
1294
1334
  const env = await prepareStartEnv(app);
1295
1335
  await app.update({ status: 'deploying', message: null });
1296
1336
  try {
@@ -1312,21 +1352,24 @@ module.exports = fp(async (fastify, options) => {
1312
1352
 
1313
1353
  const remove = async ({ name, exportBeforeRemove = true, cleanupData = true, allowRemoveIfCleanupIncomplete = false, force = false, removeSqliteFile = false } = {}) => {
1314
1354
  const app = await getByName(name);
1315
- try {
1316
- await pm2Util.deleteProcess(app.pm2Name);
1317
- } catch (e) {
1318
- // ignore
1355
+ const linked = isLinked(app);
1356
+ if (!linked && app.pm2Name) {
1357
+ try {
1358
+ await pm2Util.deleteProcess(app.pm2Name);
1359
+ } catch (e) {
1360
+ // ignore
1361
+ }
1319
1362
  }
1320
1363
 
1321
1364
  const dbops = fastify[options.name].services.dbops;
1322
1365
  let exportResult = null;
1323
1366
  let cleanupResult = null;
1324
1367
 
1325
- if (exportBeforeRemove && !force) {
1368
+ if (!linked && exportBeforeRemove && !force) {
1326
1369
  exportResult = await dbops.exportData({ name });
1327
1370
  }
1328
1371
 
1329
- if (cleanupData) {
1372
+ if (!linked && cleanupData) {
1330
1373
  cleanupResult = await dbops.cleanup({ name, removeSqliteFile });
1331
1374
  if (cleanupResult.manualRequired && !allowRemoveIfCleanupIncomplete) {
1332
1375
  return {
@@ -1341,7 +1384,9 @@ module.exports = fp(async (fastify, options) => {
1341
1384
  const snapshot = app.toJSON();
1342
1385
  await models.appVersion.destroy({ where: { appName: name } });
1343
1386
  await models.appOpenApiRecord.destroy({ where: { appName: name }, force: true });
1344
- await fs.remove(app.rootPath).catch(() => {});
1387
+ if (!linked && app.rootPath) {
1388
+ await fs.remove(app.rootPath).catch(() => {});
1389
+ }
1345
1390
  deployProgress.clear(app.name);
1346
1391
  await app.destroy();
1347
1392
  if (typeof options.onAppRemoved === 'function') {
@@ -1376,12 +1421,18 @@ module.exports = fp(async (fastify, options) => {
1376
1421
 
1377
1422
  const logs = async ({ name, stream = 'out', file, perPage = 100, currentPage = 1, beforeLine } = {}) => {
1378
1423
  const app = await getByName(name);
1424
+ if (isLinked(app)) {
1425
+ return fastify[options.name].services.link.proxy.logs(app, { stream, file, perPage, currentPage, beforeLine });
1426
+ }
1379
1427
  const filePath = file ? await resolveExistingLogFile(app, file) : currentLogFile(app, stream);
1380
1428
  return readLogTail(filePath, { perPage, currentPage, beforeLine, timezone: options.logTimezone });
1381
1429
  };
1382
1430
 
1383
1431
  const logFiles = async ({ name }) => {
1384
1432
  const app = await getByName(name);
1433
+ if (isLinked(app)) {
1434
+ return fastify[options.name].services.link.proxy.logFiles(app);
1435
+ }
1385
1436
  const pageData = (await listLogFiles(logsDirOf(app))).map(item => Object.assign({}, item, { mtime: toIsoInTz(item.mtime, options.logTimezone) }));
1386
1437
  return { pageData, totalCount: pageData.length };
1387
1438
  };
@@ -42,7 +42,8 @@ module.exports = fp(async (fastify, options) => {
42
42
  const { models } = fastify[options.name];
43
43
  const targets = [
44
44
  [models.appVersion, ['fileId', 'migrationFiles', 'envSchema']],
45
- [models.appOpenApiRecord, ['searchText']]
45
+ [models.appOpenApiRecord, ['searchText']],
46
+ [models.app, ['kind']]
46
47
  ];
47
48
  for (const [model, names] of targets) {
48
49
  const queryInterface = model.sequelize.getQueryInterface();
@@ -51,10 +52,30 @@ module.exports = fp(async (fastify, options) => {
51
52
  for (const name of names) {
52
53
  const attr = model.rawAttributes[name];
53
54
  if (!columns[attr.field]) {
54
- await queryInterface.addColumn(table, attr.field, { type: attr.type, allowNull: true, comment: attr.comment });
55
+ await queryInterface.addColumn(table, attr.field, {
56
+ type: attr.type,
57
+ allowNull: attr.allowNull !== false,
58
+ defaultValue: attr.defaultValue,
59
+ comment: attr.comment
60
+ });
55
61
  }
56
62
  }
57
63
  }
64
+ // linked 应用不占本机端口/目录/PM2:将既有非空列改为可空(幂等)
65
+ const queryInterface = models.app.sequelize.getQueryInterface();
66
+ const table = models.app.getTableName();
67
+ const columns = await queryInterface.describeTable(table);
68
+ for (const name of ['port', 'rootPath', 'pm2Name']) {
69
+ const attr = models.app.rawAttributes[name];
70
+ const col = columns[attr.field];
71
+ if (col && col.allowNull === false) {
72
+ await queryInterface.changeColumn(table, attr.field, {
73
+ type: attr.type,
74
+ allowNull: true,
75
+ comment: attr.comment
76
+ });
77
+ }
78
+ }
58
79
  };
59
80
 
60
81
  const onReady = async () => {
@@ -123,7 +144,24 @@ module.exports = fp(async (fastify, options) => {
123
144
  if (options.loadSampleIntervalMs > 0) {
124
145
  sampleLoad().catch(err => fastify.log.debug({ err }, 'load sampling failed'));
125
146
  }
147
+ const link = fastify[options.name].services.link;
148
+ if (link?.syncAllLinked) {
149
+ link.syncAllLinked().catch(err => fastify.log.warn({ err }, 'linked apps sync failed'));
150
+ }
126
151
  });
152
+
153
+ const linkSyncMs = options.linkSyncIntervalMs || 0;
154
+ if (linkSyncMs > 0) {
155
+ const linkTimer = setInterval(() => {
156
+ const link = fastify[options.name].services.link;
157
+ if (link?.syncAllLinked) {
158
+ link.syncAllLinked().catch(err => fastify.log.warn({ err }, 'linked apps sync failed'));
159
+ }
160
+ }, linkSyncMs);
161
+ linkTimer.unref?.();
162
+ // 挂到实例上,onClose 时可清理;无专门字段时依赖进程退出
163
+ fastify[options.name]._linkSyncTimer = linkTimer;
164
+ }
127
165
  };
128
166
 
129
167
  const fsEnsureAppsRoot = async () => {
@@ -188,9 +226,13 @@ module.exports = fp(async (fastify, options) => {
188
226
  */
189
227
  const migratePm2Names = async () => {
190
228
  const { models } = fastify[options.name];
229
+ const { isLinked } = require('../utils/appKind');
191
230
  const apps = await models.app.findAll();
192
231
  const migrated = [];
193
232
  for (const app of apps) {
233
+ if (isLinked(app) || !app.pm2Name || !app.rootPath) {
234
+ continue;
235
+ }
194
236
  const pm2Name = createPm2Name(options.hostName, app.name);
195
237
  if (app.pm2Name === pm2Name) {
196
238
  continue;
@@ -236,9 +278,13 @@ module.exports = fp(async (fastify, options) => {
236
278
 
237
279
  const runRotation = async ({ now = new Date() } = {}) => {
238
280
  const { models } = fastify[options.name];
239
- const apps = await models.app.findAll({ attributes: ['name', 'rootPath'] });
281
+ const { isLinked } = require('../utils/appKind');
282
+ const apps = await models.app.findAll({ attributes: ['name', 'rootPath', 'kind', 'options'] });
240
283
  const targets = [];
241
284
  for (const app of apps) {
285
+ if (isLinked(app) || !app.rootPath) {
286
+ continue;
287
+ }
242
288
  const logsDir = path.join(app.rootPath, 'logs');
243
289
  if (await fs.pathExists(logsDir)) {
244
290
  targets.push({ name: app.name, logsDir });
@@ -314,16 +360,18 @@ module.exports = fp(async (fastify, options) => {
314
360
  }
315
361
  const { models } = fastify[options.name];
316
362
  const summary = summarizeProcesses(await pm2Util.list(), { now: now.getTime() });
317
- const apps = await models.app.findAll({ attributes: ['name', 'pm2Name'] });
363
+ const { isLinked } = require('../utils/appKind');
364
+ const apps = await models.app.findAll({ attributes: ['name', 'pm2Name', 'kind', 'options'] });
365
+ const managed = apps.filter(app => !isLinked(app) && app.pm2Name);
318
366
  const base = { ts: now.getTime(), sampledAt: toIsoInTz(now, options.logTimezone) };
319
- const samples = apps.map(app => {
367
+ const samples = managed.map(app => {
320
368
  const sample = Object.assign({ name: app.name }, base, summary.get(app.pm2Name) || OFFLINE_LOAD, {
321
369
  requests: requestMetrics.snapshot(app.name, { now: base.ts })
322
370
  });
323
371
  loadStore.push(app.name, sample);
324
372
  return sample;
325
373
  });
326
- const names = apps.map(app => app.name);
374
+ const names = managed.map(app => app.name);
327
375
  loadStore.retain(names);
328
376
  requestMetrics.retain(names);
329
377
  return samples;
@@ -24,6 +24,8 @@ module.exports = fp(async (fastify, options) => {
24
24
  throw err;
25
25
  };
26
26
 
27
+ const { isLinked } = require('../utils/appKind');
28
+
27
29
  const getByName = async name => {
28
30
  const app = await models.app.findOne({ where: { name } });
29
31
  if (!app) {
@@ -32,6 +34,8 @@ module.exports = fp(async (fastify, options) => {
32
34
  return app;
33
35
  };
34
36
 
37
+ const linkedProxy = () => fastify[options.name].services.link.proxy;
38
+
35
39
  const resolveEnvForApp = app =>
36
40
  resolveAppDbEnv({
37
41
  passthroughEnvKeys: options.passthroughEnvKeys,
@@ -116,6 +120,9 @@ module.exports = fp(async (fastify, options) => {
116
120
 
117
121
  const listTables = async ({ name, scope } = {}) => {
118
122
  const app = await getByName(name);
123
+ if (isLinked(app)) {
124
+ return linkedProxy().dbTables(app);
125
+ }
119
126
  return withSequelize(app, async (sequelize, env) => {
120
127
  const all = await listAllTables(sequelize);
121
128
  const dbScope = resolveDbScope(app.env || {}, app.options || {});
@@ -288,6 +295,9 @@ module.exports = fp(async (fastify, options) => {
288
295
 
289
296
  const listRows = async ({ name, table, currentPage = 1, perPage = 20, filter, includeDeleted, sort, keyword } = {}) => {
290
297
  const app = await getByName(name);
298
+ if (isLinked(app)) {
299
+ return linkedProxy().dbRows(app, { table, currentPage, perPage, filter, includeDeleted, sort, keyword });
300
+ }
291
301
  const showDeleted = includeDeleted === true || includeDeleted === 'true' || includeDeleted === 1;
292
302
  return withSequelize(app, async sequelize => {
293
303
  const all = await listAllTables(sequelize);
@@ -368,6 +378,9 @@ module.exports = fp(async (fastify, options) => {
368
378
 
369
379
  const saveRow = async ({ name, table, data = {}, autoGenerate } = {}) => {
370
380
  const app = await getByName(name);
381
+ if (isLinked(app)) {
382
+ return linkedProxy().dbSaveRow(app, { table, data, autoGenerate });
383
+ }
371
384
  return withSequelize(app, async sequelize => {
372
385
  const all = await listAllTables(sequelize);
373
386
  assertTableOwned(app, all, table);
@@ -457,6 +470,9 @@ module.exports = fp(async (fastify, options) => {
457
470
 
458
471
  const removeRow = async ({ name, table, id, pk, hard = false } = {}) => {
459
472
  const app = await getByName(name);
473
+ if (isLinked(app)) {
474
+ return linkedProxy().dbRemoveRow(app, { table, id, pk, hard });
475
+ }
460
476
  return withSequelize(app, async sequelize => {
461
477
  const all = await listAllTables(sequelize);
462
478
  assertTableOwned(app, all, table);
@@ -508,6 +524,9 @@ module.exports = fp(async (fastify, options) => {
508
524
 
509
525
  const runQuery = async ({ name, sql, replacements = {}, maxRows } = {}) => {
510
526
  const app = await getByName(name);
527
+ if (isLinked(app)) {
528
+ return linkedProxy().dbQuery(app, { sql, replacements, maxRows });
529
+ }
511
530
  const limit = Math.min(Math.max(1, Number(maxRows) || options.dbQueryMaxRows || 500), options.dbQueryMaxRows || 500);
512
531
  const checked = assertReadOnlyQuerySql(sql);
513
532
  return withSequelize(app, async sequelize => {
@@ -0,0 +1,334 @@
1
+ const fp = require('fastify-plugin');
2
+ const { KIND_LINKED, isLinked, linkedBaseUrl } = require('../utils/appKind');
3
+
4
+ const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
5
+
6
+ const decodeInstallKey = installKey => {
7
+ try {
8
+ return JSON.parse(Buffer.from(String(installKey), 'base64url').toString('utf8'));
9
+ } catch (e) {
10
+ const err = new Error('installKey 无效');
11
+ err.statusCode = 400;
12
+ throw err;
13
+ }
14
+ };
15
+
16
+ const unwrapEnvelope = async response => {
17
+ const text = await response.text();
18
+ let body;
19
+ try {
20
+ body = text ? JSON.parse(text) : {};
21
+ } catch (e) {
22
+ body = { message: text };
23
+ }
24
+ // app-runtime sendJson 可能包一层 { data } 或业务直接返回
25
+ if (body && Object.prototype.hasOwnProperty.call(body, 'data') && body.statusCode == null) {
26
+ return { ok: response.ok, status: response.status, data: body.data, raw: body };
27
+ }
28
+ if (body && body.data !== undefined && (body.statusCode || body.code)) {
29
+ return { ok: response.ok, status: response.status, data: body.data, raw: body };
30
+ }
31
+ return { ok: response.ok, status: response.status, data: body, raw: body };
32
+ };
33
+
34
+ module.exports = fp(async (fastify, options) => {
35
+ const { models } = fastify[options.name];
36
+
37
+ const httpError = (statusCode, message) => {
38
+ if (fastify.httpErrors) {
39
+ if (statusCode === 404) throw fastify.httpErrors.notFound(message);
40
+ if (statusCode === 409) throw fastify.httpErrors.conflict(message);
41
+ if (statusCode === 400) throw fastify.httpErrors.badRequest(message);
42
+ if (statusCode === 502) throw fastify.httpErrors.badGateway(message);
43
+ }
44
+ const err = new Error(message);
45
+ err.statusCode = statusCode;
46
+ throw err;
47
+ };
48
+
49
+ const platformOrigin = () => String(options.origin || options.linkOrigin || '').replace(/\/+$/, '');
50
+
51
+ const signAssertion = async audience => {
52
+ if (typeof options.signPlatformAssertion === 'function') {
53
+ return options.signPlatformAssertion({ audience });
54
+ }
55
+ const signer = fastify.oidc?.platformAssertion;
56
+ if (signer?.sign) {
57
+ return signer.sign({ audience });
58
+ }
59
+ httpError(400, '未配置平台断言签发(需宿主接入 createAppOidc / fastify-oidc)');
60
+ };
61
+
62
+ const ensureOidc = async ({ app, remoteBaseUrl }) => {
63
+ if (typeof options.ensureLinkedRegistration === 'function') {
64
+ return options.ensureLinkedRegistration({ app, remoteBaseUrl });
65
+ }
66
+ httpError(400, '未配置 ensureLinkedRegistration,无法完成外部应用 OIDC 登记');
67
+ };
68
+
69
+ const getOpsToken = async (app, scope) => {
70
+ if (typeof options.getOpsServiceToken === 'function') {
71
+ return options.getOpsServiceToken({ app, scope });
72
+ }
73
+ if (typeof options.getServiceToken === 'function') {
74
+ return options.getServiceToken({ app, scope });
75
+ }
76
+ httpError(400, '未配置 getOpsServiceToken,无法代理远程运维接口');
77
+ };
78
+
79
+ const remoteFetch = async (app, { path: opsPath, method = 'GET', query, body, scope }) => {
80
+ const baseUrl = linkedBaseUrl(app);
81
+ if (!baseUrl) {
82
+ httpError(400, '应用缺少 options.baseUrl');
83
+ }
84
+ const token = await getOpsToken(app, scope);
85
+ const url = new URL(opsPath.replace(/^\//, ''), `${baseUrl}/`);
86
+ if (query && typeof query === 'object') {
87
+ for (const [k, v] of Object.entries(query)) {
88
+ if (v !== undefined && v !== null && v !== '') {
89
+ url.searchParams.set(k, String(v));
90
+ }
91
+ }
92
+ }
93
+ const response = await fetch(url, {
94
+ method,
95
+ headers: Object.assign({ authorization: `Bearer ${token}` }, body ? { 'content-type': 'application/json' } : {}),
96
+ body: body ? JSON.stringify(body) : undefined,
97
+ signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
98
+ });
99
+ const { ok, status, data, raw } = await unwrapEnvelope(response);
100
+ if (!ok) {
101
+ const message = data?.message || raw?.message || raw?.data?.message || `远程 ${status}`;
102
+ httpError(status >= 400 && status < 600 ? status : 502, message);
103
+ }
104
+ return data;
105
+ };
106
+
107
+ const slugifyName = raw => {
108
+ const name = String(raw || '')
109
+ .replace(/^@[^/]+\//, '')
110
+ .toLowerCase()
111
+ .replace(/[^a-z0-9-]+/g, '-')
112
+ .replace(/^-+|-+$/g, '')
113
+ .slice(0, 64);
114
+ return name;
115
+ };
116
+
117
+ /**
118
+ * 凭 installKey 导入外部应用:redeem → 建 linked 记录 → OIDC → activate
119
+ */
120
+ const importByInstallKey = async ({ installKey, name: overrideName, label: overrideLabel } = {}) => {
121
+ if (!installKey) {
122
+ httpError(400, 'installKey 必填');
123
+ }
124
+ const key = decodeInstallKey(installKey);
125
+ const origin = platformOrigin();
126
+ if (!origin) {
127
+ httpError(400, '宿主未配置 origin,无法导入外部应用');
128
+ }
129
+ if (String(key.platformOrigin || '').replace(/\/+$/, '') !== origin) {
130
+ httpError(400, 'installKey 不属于本平台(platformOrigin 不匹配)');
131
+ }
132
+ if (key.expiresAt && new Date(key.expiresAt).getTime() < Date.now()) {
133
+ httpError(400, 'installKey 已过期');
134
+ }
135
+ const baseUrl = String(key.baseUrl || '').replace(/\/+$/, '');
136
+ if (!baseUrl) {
137
+ httpError(400, 'installKey 缺少 baseUrl');
138
+ }
139
+ const name = overrideName || slugifyName(key.appName);
140
+ if (!name || !NAME_RE.test(name)) {
141
+ httpError(400, '应用 name 无效:请传合法 slug 或远程改名');
142
+ }
143
+ const exists = await models.app.findOne({ where: { name } });
144
+ if (exists) {
145
+ httpError(409, `应用 ${name} 已存在`);
146
+ }
147
+
148
+ const assertion = await signAssertion(baseUrl);
149
+ const redeemRes = await fetch(`${baseUrl}/app-ops/link/redeem`, {
150
+ method: 'POST',
151
+ headers: { 'content-type': 'application/json' },
152
+ body: JSON.stringify({
153
+ installId: key.installId,
154
+ installSecret: key.installSecret,
155
+ assertion
156
+ }),
157
+ signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
158
+ });
159
+ const redeemed = await unwrapEnvelope(redeemRes);
160
+ if (!redeemed.ok) {
161
+ httpError(redeemed.status || 502, redeemed.data?.message || '远程 redeem 失败');
162
+ }
163
+ const manifest = redeemed.data || {};
164
+ const label = overrideLabel || manifest.label || key.appLabel || name;
165
+ const entries = Array.isArray(manifest.entries) ? manifest.entries : [{ label: '首页', path: '/', showInCenter: true }];
166
+
167
+ const app = await models.app.create({
168
+ name,
169
+ label,
170
+ kind: KIND_LINKED,
171
+ domain: null,
172
+ icon: manifest.icon || null,
173
+ description: manifest.description || null,
174
+ env: {},
175
+ pm2Config: {},
176
+ options: {
177
+ kind: KIND_LINKED,
178
+ baseUrl,
179
+ linkStatus: 'pending_activate',
180
+ permissionsSnapshot: manifest.permissions || [],
181
+ capabilities: manifest.capabilities || {},
182
+ entries,
183
+ isPublic: true
184
+ },
185
+ port: null,
186
+ status: 'idle',
187
+ rootPath: null,
188
+ pm2Name: null,
189
+ message: null
190
+ });
191
+
192
+ let oidcInfo;
193
+ try {
194
+ oidcInfo = await ensureOidc({ app, remoteBaseUrl: baseUrl });
195
+ const activateAssertion = await signAssertion(baseUrl);
196
+ const activateRes = await fetch(`${baseUrl}/app-ops/link/activate`, {
197
+ method: 'POST',
198
+ headers: { 'content-type': 'application/json' },
199
+ body: JSON.stringify({
200
+ assertion: activateAssertion,
201
+ issuer: oidcInfo.issuer,
202
+ audience: oidcInfo.audience,
203
+ clientId: oidcInfo.clientId,
204
+ serviceClientId: oidcInfo.serviceClientId,
205
+ serviceClientSecret: oidcInfo.serviceClientSecret
206
+ }),
207
+ signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
208
+ });
209
+ const activated = await unwrapEnvelope(activateRes);
210
+ if (!activated.ok) {
211
+ throw Object.assign(new Error(activated.data?.message || '远程 activate 失败'), { statusCode: activated.status || 502 });
212
+ }
213
+ await app.update({
214
+ status: 'running',
215
+ options: Object.assign({}, app.options, {
216
+ linkStatus: 'paired',
217
+ oidc: {
218
+ issuer: oidcInfo.issuer,
219
+ audience: oidcInfo.audience,
220
+ clientId: oidcInfo.clientId,
221
+ serviceClientId: oidcInfo.serviceClientId,
222
+ serviceClientSecret: oidcInfo.serviceClientSecret
223
+ },
224
+ permissionsSyncedAt: new Date().toISOString()
225
+ }),
226
+ message: null
227
+ });
228
+ await app.reload();
229
+ } catch (e) {
230
+ if (typeof options.onAppRemoved === 'function' && oidcInfo) {
231
+ try {
232
+ await options.onAppRemoved({
233
+ app: Object.assign(app.toJSON(), {
234
+ options: Object.assign({}, app.options, { oidc: oidcInfo }),
235
+ env: {
236
+ OIDC_CLIENT_ID: oidcInfo.clientId,
237
+ OIDC_SERVICE_CLIENT_ID: oidcInfo.serviceClientId,
238
+ OIDC_AUDIENCE: oidcInfo.audience
239
+ }
240
+ })
241
+ });
242
+ } catch (cleanupErr) {
243
+ fastify.log.warn({ err: cleanupErr }, 'rollback linked OIDC failed');
244
+ }
245
+ }
246
+ await app.destroy().catch(() => {});
247
+ httpError(e.statusCode || 502, e.message || '导入外部应用失败');
248
+ }
249
+
250
+ return fastify[options.name].services.app.toPublicApp(app);
251
+ };
252
+
253
+ const syncOne = async app => {
254
+ if (!isLinked(app)) {
255
+ return null;
256
+ }
257
+ const baseUrl = linkedBaseUrl(app);
258
+ try {
259
+ await remoteFetch(app, {
260
+ path: '/app-ops/link/status',
261
+ query: { issuer: app.options?.oidc?.issuer },
262
+ scope: 'app-ops:permissions:read'
263
+ });
264
+ const perms = await remoteFetch(app, {
265
+ path: '/app-ops/permissions',
266
+ scope: 'app-ops:permissions:read'
267
+ });
268
+ let readyOk = false;
269
+ try {
270
+ const ready = await fetch(`${baseUrl}/ready`, { signal: AbortSignal.timeout(5000) });
271
+ readyOk = ready.ok;
272
+ } catch (e) {
273
+ readyOk = false;
274
+ }
275
+ await app.update({
276
+ status: readyOk ? 'running' : 'error',
277
+ message: readyOk ? null : '远程健康检查失败',
278
+ options: Object.assign({}, app.options || {}, {
279
+ permissionsSnapshot: perms?.permissions || perms || app.options?.permissionsSnapshot || [],
280
+ permissionsSyncedAt: new Date().toISOString(),
281
+ linkStatus: 'paired'
282
+ })
283
+ });
284
+ if (typeof options.ensureLinkedRegistration === 'function') {
285
+ await options.ensureLinkedRegistration({ app, remoteBaseUrl: baseUrl });
286
+ }
287
+ await app.reload();
288
+ return { name: app.name, ok: true, status: app.status };
289
+ } catch (e) {
290
+ await app
291
+ .update({
292
+ status: 'error',
293
+ message: e.message
294
+ })
295
+ .catch(() => {});
296
+ return { name: app.name, ok: false, error: e.message };
297
+ }
298
+ };
299
+
300
+ const syncAllLinked = async () => {
301
+ const apps = await models.app.findAll({ where: { kind: KIND_LINKED } });
302
+ const results = [];
303
+ for (const app of apps) {
304
+ results.push(await syncOne(app));
305
+ }
306
+ return results.filter(Boolean);
307
+ };
308
+
309
+ const proxy = {
310
+ logs: (app, query) => remoteFetch(app, { path: '/app-ops/logs', query, scope: 'app-ops:logs:read' }),
311
+ logFiles: app => remoteFetch(app, { path: '/app-ops/logs/files', scope: 'app-ops:logs:read' }),
312
+ env: app => remoteFetch(app, { path: '/app-ops/env', scope: 'app-ops:env:read' }),
313
+ permissions: app => remoteFetch(app, { path: '/app-ops/permissions', scope: 'app-ops:permissions:read' }),
314
+ dbTables: app => remoteFetch(app, { path: '/app-ops/db/tables', scope: 'app-ops:db:read' }),
315
+ dbRows: (app, query) => remoteFetch(app, { path: '/app-ops/db/rows', query, scope: 'app-ops:db:read' }),
316
+ dbQuery: (app, body) => remoteFetch(app, { path: '/app-ops/db/query', method: 'POST', body, scope: 'app-ops:db:read' }),
317
+ dbSaveRow: (app, body) => remoteFetch(app, { path: '/app-ops/db/row/save', method: 'POST', body, scope: 'app-ops:db:write' }),
318
+ dbRemoveRow: (app, body) => remoteFetch(app, { path: '/app-ops/db/row/remove', method: 'POST', body, scope: 'app-ops:db:write' }),
319
+ migrationsList: app => remoteFetch(app, { path: '/app-ops/migrations/list', scope: 'app-ops:migrations:read' }),
320
+ migrationsContent: (app, query) => remoteFetch(app, { path: '/app-ops/migrations/content', query, scope: 'app-ops:migrations:read' }),
321
+ migrationsAction: (app, body) => remoteFetch(app, { path: '/app-ops/migrations/action', method: 'POST', body, scope: 'app-ops:migrations:execute' })
322
+ };
323
+
324
+ Object.assign(fastify[options.name].services, {
325
+ link: {
326
+ importByInstallKey,
327
+ syncOne,
328
+ syncAllLinked,
329
+ decodeInstallKey,
330
+ proxy,
331
+ remoteFetch
332
+ }
333
+ });
334
+ });
@@ -1,10 +1,12 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const { isValidSqlFileName, readExecutedMigrations, recordMigration, removeMigrationRecord } = require('../utils/migrate');
3
+ const { isLinked } = require('../utils/appKind');
3
4
 
4
5
  module.exports = fp(async (fastify, options) => {
5
6
  const { models } = fastify[options.name];
6
7
  const getDbops = () => fastify[options.name].services.dbops;
7
8
  const getAppService = () => fastify[options.name].services.app;
9
+ const linkedProxy = () => fastify[options.name].services.link.proxy;
8
10
 
9
11
  const httpError = (statusCode, message) => {
10
12
  if (fastify.httpErrors) {
@@ -46,6 +48,10 @@ module.exports = fp(async (fastify, options) => {
46
48
  };
47
49
 
48
50
  const list = async ({ name, versionId }) => {
51
+ const appRow = await models.app.findOne({ where: { name } });
52
+ if (appRow && isLinked(appRow)) {
53
+ return linkedProxy().migrationsList(appRow);
54
+ }
49
55
  const { app, ver } = await resolveVersion({ name, versionId });
50
56
  const files = await getFiles(ver);
51
57
  let executedMap = new Map();
@@ -74,12 +80,20 @@ module.exports = fp(async (fastify, options) => {
74
80
  };
75
81
 
76
82
  const content = async ({ name, versionId, file }) => {
83
+ const appRow = await models.app.findOne({ where: { name } });
84
+ if (appRow && isLinked(appRow)) {
85
+ return linkedProxy().migrationsContent(appRow, { file });
86
+ }
77
87
  const { ver } = await resolveVersion({ name, versionId });
78
88
  const item = await findFile(ver, file);
79
89
  return { name: file, content: item.content || '' };
80
90
  };
81
91
 
82
92
  const save = async ({ name, versionId, file, content: sql }) => {
93
+ const appRow = await models.app.findOne({ where: { name } });
94
+ if (appRow && isLinked(appRow)) {
95
+ httpError(400, '外部关联应用不支持在平台侧编辑迁移脚本');
96
+ }
83
97
  assertFileName(file);
84
98
  const { ver } = await resolveVersion({ name, versionId });
85
99
  const files = (await getFiles(ver)).filter(f => f.name !== file);
@@ -89,6 +103,10 @@ module.exports = fp(async (fastify, options) => {
89
103
  };
90
104
 
91
105
  const remove = async ({ name, versionId, file }) => {
106
+ const appRow = await models.app.findOne({ where: { name } });
107
+ if (appRow && isLinked(appRow)) {
108
+ httpError(400, '外部关联应用不支持在平台侧删除迁移脚本');
109
+ }
92
110
  const { ver } = await resolveVersion({ name, versionId });
93
111
  await findFile(ver, file);
94
112
  await getAppService().saveMigrationFiles(
@@ -133,6 +151,10 @@ module.exports = fp(async (fastify, options) => {
133
151
  };
134
152
 
135
153
  const action = async ({ action: type, ...props }) => {
154
+ const appRow = props.name ? await models.app.findOne({ where: { name: props.name } }) : null;
155
+ if (appRow && isLinked(appRow)) {
156
+ return linkedProxy().migrationsAction(appRow, { file: props.file, action: type });
157
+ }
136
158
  if (type === 'execute') return execute(props);
137
159
  if (type === 'mark') return mark(props);
138
160
  if (type === 'unmark') return unmark(props);
@@ -15,6 +15,8 @@ module.exports = fp(async (fastify, options) => {
15
15
  throw err;
16
16
  };
17
17
 
18
+ const { isLinked, linkedBaseUrl } = require('../utils/appKind');
19
+
18
20
  const getRunningApp = async (name, hook) => {
19
21
  if (typeof options[hook] !== 'function') {
20
22
  httpError(400, `未配置 ${hook},无法访问子应用接口文档(见 README「应用 OIDC 对接」)`);
@@ -26,11 +28,22 @@ module.exports = fp(async (fastify, options) => {
26
28
  return app;
27
29
  };
28
30
 
31
+ const openApiUrl = app => {
32
+ if (isLinked(app)) {
33
+ const base = linkedBaseUrl(app);
34
+ if (!base) {
35
+ httpError(400, `应用 ${app.name} 缺少 options.baseUrl`);
36
+ }
37
+ return `${base}/open-api.json`;
38
+ }
39
+ return `http://${options.upstreamHost}:${app.port}/open-api.json`;
40
+ };
41
+
29
42
  /** 以 open-api:read 服务令牌读取子应用 /open-api.json,原样返回 */
30
43
  const getDocument = async ({ name }) => {
31
44
  const app = await getRunningApp(name, 'getOpenApiToken');
32
45
  const token = await options.getOpenApiToken(app);
33
- const response = await fetch(`http://${options.upstreamHost}:${app.port}/open-api.json`, {
46
+ const response = await fetch(openApiUrl(app), {
34
47
  headers: { authorization: `Bearer ${token}` },
35
48
  signal: AbortSignal.timeout(15000)
36
49
  });
@@ -0,0 +1,33 @@
1
+ const KIND_MANAGED = 'managed';
2
+ const KIND_LINKED = 'linked';
3
+
4
+ const normalizeKind = kind => (kind === KIND_LINKED ? KIND_LINKED : KIND_MANAGED);
5
+
6
+ const isLinked = appLike => {
7
+ if (appLike?.kind != null && appLike.kind !== '') {
8
+ return normalizeKind(appLike.kind) === KIND_LINKED;
9
+ }
10
+ return normalizeKind(appLike?.options?.kind) === KIND_LINKED;
11
+ };
12
+
13
+ const linkedBaseUrl = appLike => {
14
+ const url = appLike?.options?.baseUrl || appLike?.baseUrl;
15
+ return url ? String(url).replace(/\/+$/, '') : null;
16
+ };
17
+
18
+ const assertNotLinked = (appLike, action) => {
19
+ if (isLinked(appLike)) {
20
+ const err = new Error(`外部关联应用不支持${action || '该操作'}`);
21
+ err.statusCode = 400;
22
+ throw err;
23
+ }
24
+ };
25
+
26
+ module.exports = {
27
+ KIND_MANAGED,
28
+ KIND_LINKED,
29
+ normalizeKind,
30
+ isLinked,
31
+ linkedBaseUrl,
32
+ assertNotLinked
33
+ };
package/oidc.js CHANGED
@@ -2,6 +2,9 @@
2
2
  * 应用中心子应用 OIDC 接入(可选):宿主已注册 @kne/fastify-oidc 作为主 IdP 时使用。
3
3
  * 子应用 server 依赖 @kne/fastify-oidc 时,部署时登记资源服务与 client,并以 central 模式启动;
4
4
  * 子应用在 server/env.schema.json 中声明 AUTH_MODE 默认值为 standalone 时,保持自己的登录。
5
+ *
6
+ * 外部关联(linked)时把返回值一并传给 app-manager:
7
+ * origin, signPlatformAssertion, ensureLinkedRegistration, getOpsServiceToken: getServiceToken
5
8
  */
6
9
  const path = require('node:path');
7
10
  const fs = require('fs-extra');
@@ -12,6 +15,16 @@ const OIDC_PACKAGE = '@kne/fastify-oidc';
12
15
  // 子应用 @kne/fastify-app-runtime 的 /open-api.json 放行带此 scope 的 client 令牌
13
16
  const OPEN_API_SCOPE = 'open-api:read';
14
17
  const DOCS_CLIENT_ID = 'app-center-docs';
18
+ /** linked 远程 App Ops 所需 scope(写类默认可登记到 resource,实际授权由 capabilities 控制) */
19
+ const APP_OPS_SCOPES = [
20
+ 'app-ops:permissions:read',
21
+ 'app-ops:logs:read',
22
+ 'app-ops:env:read',
23
+ 'app-ops:db:read',
24
+ 'app-ops:db:write',
25
+ 'app-ops:migrations:read',
26
+ 'app-ops:migrations:execute'
27
+ ];
15
28
 
16
29
  const SYSTEM_ENV_KEYS = ['AUTH_MODE', 'OIDC_ISSUER', 'OIDC_AUDIENCE', 'OIDC_CLIENT_ID', 'OIDC_SERVICE_CLIENT_ID', 'OIDC_SERVICE_CLIENT_SECRET'];
17
30
 
@@ -75,18 +88,25 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
75
88
  backchannel_logout_session_required: true
76
89
  });
77
90
 
78
- const ensureResourceServer = async ({ identifier, name }) => {
91
+ const ensureResourceServer = async ({ identifier, name, extraScopes = [] }) => {
79
92
  const { models, services, options } = oidc();
93
+ const required = [OPEN_API_SCOPE, ...extraScopes].filter(Boolean);
80
94
  const existing = await models.resourceServer.findOne({ where: { identifier } });
81
95
  if (!existing) {
82
- await services.resourceServer.create({ identifier, name, scope: `${options.defaultResourceScope} ${OPEN_API_SCOPE}`, description: '应用中心子应用自动登记' });
96
+ await services.resourceServer.create({
97
+ identifier,
98
+ name,
99
+ scope: `${options.defaultResourceScope} ${required.join(' ')}`,
100
+ description: '应用中心子应用自动登记'
101
+ });
83
102
  return;
84
103
  }
85
104
  const scopes = String(existing.scope || options.defaultResourceScope)
86
105
  .split(' ')
87
106
  .filter(Boolean);
88
- if (!scopes.includes(OPEN_API_SCOPE)) {
89
- await existing.update({ scope: [...scopes, OPEN_API_SCOPE].join(' ') });
107
+ const missing = required.filter(scope => !scopes.includes(scope));
108
+ if (missing.length) {
109
+ await existing.update({ scope: [...scopes, ...missing].join(' ') });
90
110
  }
91
111
  };
92
112
 
@@ -250,33 +270,122 @@ const createAppOidc = (fastify, { origin, issuer, serviceAudience, pathPrefix =
250
270
  };
251
271
 
252
272
  const onAppRemoved = async ({ app }) => {
253
- if (!app.env?.OIDC_CLIENT_ID) {
273
+ const clientId = app.env?.OIDC_CLIENT_ID || app.options?.oidc?.clientId;
274
+ const serviceClientId = app.env?.OIDC_SERVICE_CLIENT_ID || app.options?.oidc?.serviceClientId;
275
+ const audience = app.env?.OIDC_AUDIENCE || app.options?.oidc?.audience;
276
+ if (!clientId && !serviceClientId && !audience) {
254
277
  return;
255
278
  }
256
279
  const { models, services } = oidc();
257
280
  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 } });
281
+ for (const id of [clientId, serviceClientId].filter(Boolean)) {
282
+ const item = await models.client.findOne({ where: { clientId: id } });
260
283
  if (item) {
261
284
  await services.client.remove({ id: item.id });
262
285
  }
263
286
  }
264
- if (app.env.OIDC_AUDIENCE) {
287
+ if (audience) {
265
288
  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) });
289
+ if (docsClient && (docsClient.allowedResources || []).includes(audience)) {
290
+ await services.client.save({ id: docsClient.id, allowedResources: docsClient.allowedResources.filter(item => item !== audience) });
268
291
  }
269
- const item = await models.resourceServer.findOne({ where: { identifier: app.env.OIDC_AUDIENCE } });
292
+ const item = await models.resourceServer.findOne({ where: { identifier: audience } });
270
293
  if (item) {
271
294
  await services.resourceServer.remove({ id: item.id });
272
295
  }
273
296
  }
274
297
  };
275
298
 
276
- return { systemEnvKeys: SYSTEM_ENV_KEYS, resolveSystemEnv, onAppRemoved, getOpenApiToken, issueUserAccessToken };
299
+ /**
300
+ * linked 应用:audience 仍用本平台 /app/{name}/api;SPA 回调与 backchannel 指向远程 baseUrl。
301
+ */
302
+ const ensureLinkedRegistration = async ({ app, remoteBaseUrl }) => {
303
+ if (!remoteBaseUrl) {
304
+ throw new Error('ensureLinkedRegistration 需要 remoteBaseUrl');
305
+ }
306
+ await oidc().whenReady();
307
+ const base = String(remoteBaseUrl).replace(/\/+$/, '');
308
+ const urls = resolveUrls(app);
309
+ const ids = clientIds(app.name);
310
+ await ensureResourceServer({
311
+ identifier: urls.audience,
312
+ name: app.label || app.name,
313
+ extraScopes: APP_OPS_SCOPES
314
+ });
315
+ await ensureSpaClient({
316
+ clientId: ids.spa,
317
+ clientName: app.label || app.name,
318
+ metadata: spaMetadata({ bases: [base] }, base),
319
+ allowedResources: [urls.audience]
320
+ });
321
+ const serviceClientSecret = await ensureServiceClient({
322
+ clientId: ids.service,
323
+ clientName: `${app.label || app.name} 服务端`
324
+ });
325
+ await ensureDocsClient(urls.audience);
326
+ return {
327
+ issuer,
328
+ audience: urls.audience,
329
+ clientId: ids.spa,
330
+ serviceClientId: ids.service,
331
+ serviceClientSecret
332
+ };
333
+ };
334
+
335
+ /** 签发带指定 scope 的服务令牌(linked App Ops 代理用) */
336
+ const getServiceToken = async ({ app, scope }) => {
337
+ const audience = app.env?.OIDC_AUDIENCE || app.options?.oidc?.audience || resolveUrls(app).audience;
338
+ const clientId = app.env?.OIDC_SERVICE_CLIENT_ID || app.options?.oidc?.serviceClientId || clientIds(app.name).service;
339
+ let clientSecret = app.options?.oidc?.serviceClientSecret;
340
+ if (!clientSecret) {
341
+ clientSecret = await ensureServiceClient({ clientId, clientName: `${app.label || app.name} 服务端` });
342
+ }
343
+ await ensureResourceServer({ identifier: audience, name: app.label || app.name, extraScopes: APP_OPS_SCOPES });
344
+ const response = await fastify.inject({
345
+ method: 'POST',
346
+ url: `${new URL(issuer).pathname}/token`,
347
+ headers: {
348
+ 'content-type': 'application/x-www-form-urlencoded',
349
+ authorization: `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64')}`
350
+ },
351
+ payload: new URLSearchParams({
352
+ grant_type: 'client_credentials',
353
+ resource: audience,
354
+ scope: scope || APP_OPS_SCOPES.concat(OPEN_API_SCOPE).join(' ')
355
+ }).toString()
356
+ });
357
+ const data = response.json();
358
+ if (response.statusCode !== 200) {
359
+ throw new Error(`签发运维服务令牌失败:${data.error_description || data.error || response.statusCode}`);
360
+ }
361
+ return data.access_token;
362
+ };
363
+
364
+ const signPlatformAssertion = async ({ audience }) => {
365
+ const signer = oidc().platformAssertion;
366
+ if (!signer?.sign) {
367
+ throw new Error('IdP 未就绪,无法签发平台断言');
368
+ }
369
+ return signer.sign({ audience });
370
+ };
371
+
372
+ return {
373
+ systemEnvKeys: SYSTEM_ENV_KEYS,
374
+ resolveSystemEnv,
375
+ onAppRemoved,
376
+ getOpenApiToken,
377
+ issueUserAccessToken,
378
+ ensureLinkedRegistration,
379
+ getServiceToken,
380
+ signPlatformAssertion,
381
+ resolveUrls,
382
+ APP_OPS_SCOPES
383
+ };
277
384
  };
278
385
 
279
386
  module.exports = createAppOidc;
280
387
  module.exports.supportsOidc = supportsOidc;
281
388
  module.exports.prefersStandalone = prefersStandalone;
282
389
  module.exports.SYSTEM_ENV_KEYS = SYSTEM_ENV_KEYS;
390
+ module.exports.APP_OPS_SCOPES = APP_OPS_SCOPES;
391
+ module.exports.OPEN_API_SCOPE = OPEN_API_SCOPE;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.29",
3
+ "version": "0.1.30",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {