@kne/fastify-app-manager 0.1.29 → 0.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,59 @@
1
+ const fs = require('fs-extra');
2
+ const path = require('node:path');
3
+
4
+ const createProxyAuditStore = ({ appsRoot }) => {
5
+ const dir = path.join(appsRoot, '_link-audit');
6
+
7
+ const fileOf = appName => path.join(dir, `${appName}.jsonl`);
8
+
9
+ const append = async ({ appName, action, result = 'ok', statusCode = 200, actor = null, detail = null, platformOrigin = null }) => {
10
+ if (!appName) {
11
+ return;
12
+ }
13
+ await fs.ensureDir(dir);
14
+ const line = JSON.stringify({
15
+ at: new Date().toISOString(),
16
+ appName,
17
+ action,
18
+ result,
19
+ statusCode,
20
+ actor,
21
+ detail: detail ? String(detail).slice(0, 200) : null,
22
+ platformOrigin
23
+ });
24
+ await fs.appendFile(fileOf(appName), `${line}\n`);
25
+ };
26
+
27
+ const list = async ({ appName, limit = 50, offset = 0, action } = {}) => {
28
+ if (!appName) {
29
+ return { pageData: [], totalCount: 0 };
30
+ }
31
+ const file = fileOf(appName);
32
+ if (!(await fs.pathExists(file))) {
33
+ return { pageData: [], totalCount: 0 };
34
+ }
35
+ const text = await fs.readFile(file, 'utf8');
36
+ let rows = text
37
+ .split('\n')
38
+ .filter(Boolean)
39
+ .map(line => {
40
+ try {
41
+ return JSON.parse(line);
42
+ } catch (e) {
43
+ return null;
44
+ }
45
+ })
46
+ .filter(Boolean)
47
+ .reverse();
48
+ if (action) {
49
+ rows = rows.filter(r => r.action === action);
50
+ }
51
+ const totalCount = rows.length;
52
+ const pageData = rows.slice(Number(offset) || 0, (Number(offset) || 0) + (Number(limit) || 50));
53
+ return { pageData, totalCount };
54
+ };
55
+
56
+ return { append, list };
57
+ };
58
+
59
+ module.exports = { createProxyAuditStore };
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.31",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {