@kne/fastify-app-manager 0.1.30 → 0.1.32

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
@@ -65,6 +65,12 @@ module.exports = fp(
65
65
  signPlatformAssertion: null,
66
66
  ensureLinkedRegistration: null,
67
67
  getOpsServiceToken: null,
68
+ /** async ({ app, tree, sourceKey }) => void,权限快照合并后通知宿主(如 tenant.setPermissionSource) */
69
+ onPermissionsSynced: null,
70
+ /** async ({ app, sourceKey }) => void,删除 linked 应用时移除权限源 */
71
+ onPermissionsRemoved: null,
72
+ /** async () => string[],导入时校验 appName 不与本平台权限顶层码冲突 */
73
+ getPermissionRootCodes: null,
68
74
  linkSyncIntervalMs: 5 * 60 * 1000,
69
75
  linkProxyTimeoutMs: 15000,
70
76
  /** async ({ fileId, name, version, request }) => Buffer,版本上传传 fileId 时读取宿主文件 */
@@ -944,7 +944,15 @@ module.exports = fp(async (fastify, options) => {
944
944
  },
945
945
  async (request, reply) => {
946
946
  const { name, stream } = request.query;
947
- await services.app.detail({ name });
947
+ const app = await services.app.detail({ name });
948
+ if (app.kind === 'linked' || app.options?.kind === 'linked') {
949
+ return services.link.proxy.logStream(app, {
950
+ reply,
951
+ request,
952
+ stream: stream || 'out',
953
+ actor: request.userInfo?.id || request.user?.id || null
954
+ });
955
+ }
948
956
  const sse = createSseReply(reply, { heartbeatMs: options.sseHeartbeatMs });
949
957
  const hub = services.app.getLogHub();
950
958
 
@@ -65,4 +65,39 @@ module.exports = fp(async (fastify, options) => {
65
65
  return services.link.syncOne(row);
66
66
  }
67
67
  );
68
+
69
+ fastify.get(
70
+ `${options.prefix}/app/:name/link/audit`,
71
+ {
72
+ onRequest: auth(),
73
+ schema: {
74
+ tags: [TAG_APP],
75
+ summary: '外部关联应用代理审计',
76
+ description: '主平台侧记录:谁通过平台代理打了远程 /app-ops',
77
+ params: {
78
+ type: 'object',
79
+ required: ['name'],
80
+ properties: { name: { type: 'string', description: '应用 name' } }
81
+ },
82
+ querystring: {
83
+ type: 'object',
84
+ properties: {
85
+ action: { type: 'string', description: '按动作筛选' },
86
+ limit: { type: 'number', description: '条数,默认 50' },
87
+ offset: { type: 'number', description: '偏移' }
88
+ }
89
+ },
90
+ response: success('审计列表', any())
91
+ }
92
+ },
93
+ async request => {
94
+ await services.app.detail({ name: request.params.name });
95
+ return services.link.listProxyAudit({
96
+ appName: request.params.name,
97
+ action: request.query?.action,
98
+ limit: request.query?.limit,
99
+ offset: request.query?.offset
100
+ });
101
+ }
102
+ );
68
103
  });
@@ -10,7 +10,7 @@ module.exports = fp(async (fastify, options) => {
10
10
 
11
11
  const versionProps = {
12
12
  name: { type: 'string', description: '应用 name' },
13
- versionId: { type: 'string', description: '版本 ID' }
13
+ versionId: { type: 'string', description: '版本 ID;linked 外部应用可不传,代理远程 server/sql' }
14
14
  };
15
15
 
16
16
  fastify.get(
@@ -20,10 +20,10 @@ module.exports = fp(async (fastify, options) => {
20
20
  schema: {
21
21
  tags: [TAG],
22
22
  summary: '版本迁移脚本列表(含执行状态)',
23
- description: '脚本内容以数据库为准;执行状态读自应用数据库的迁移记录表,读取失败时 executed 为 null 并返回 dbError',
23
+ description: '脚本内容以数据库为准;执行状态读自应用数据库的迁移记录表,读取失败时 executed 为 null 并返回 dbError;linked 应用不传 versionId,代理远程 /app-ops/migrations',
24
24
  query: {
25
25
  type: 'object',
26
- required: ['name', 'versionId'],
26
+ required: ['name'],
27
27
  properties: versionProps
28
28
  },
29
29
  response: success(
@@ -61,7 +61,7 @@ module.exports = fp(async (fastify, options) => {
61
61
  summary: '读取迁移脚本内容',
62
62
  query: {
63
63
  type: 'object',
64
- required: ['name', 'versionId', 'file'],
64
+ required: ['name', 'file'],
65
65
  properties: Object.assign({}, versionProps, { file: { type: 'string', description: SQL_FILE } })
66
66
  },
67
67
  response: success('脚本内容', obj('脚本内容', { name: str('文件名'), content: str('SQL 内容') }))
@@ -120,10 +120,10 @@ module.exports = fp(async (fastify, options) => {
120
120
  description: 'execute 在应用数据库执行脚本并记录,mark 只记录为已执行,unmark 删除执行记录(不回滚已执行的 SQL)',
121
121
  body: {
122
122
  type: 'object',
123
- required: ['name', 'versionId', 'file', 'action'],
123
+ required: ['name', 'file', 'action'],
124
124
  properties: Object.assign({}, versionProps, {
125
125
  file: { type: 'string', description: SQL_FILE },
126
- action: { type: 'string', enum: ['execute', 'mark', 'unmark'], description: '操作:execute 执行,mark 标记已执行,unmark 撤销执行记录' }
126
+ action: { type: 'string', enum: ['execute', 'mark', 'unmark'], description: '操作:execute 执行,mark 标记已执行,unmark 撤销执行记录;linked 应用不传 versionId' }
127
127
  })
128
128
  },
129
129
  response: success('操作结果', migrationResult)
@@ -1396,6 +1396,13 @@ module.exports = fp(async (fastify, options) => {
1396
1396
  fastify.log.warn({ err: e, appName: name }, 'onAppRemoved hook failed');
1397
1397
  }
1398
1398
  }
1399
+ if (linked && typeof options.onPermissionsRemoved === 'function') {
1400
+ try {
1401
+ await options.onPermissionsRemoved({ app: snapshot, sourceKey: `app:${name}` });
1402
+ } catch (e) {
1403
+ fastify.log.warn({ err: e, appName: name }, 'onPermissionsRemoved hook failed');
1404
+ }
1405
+ }
1399
1406
  return {
1400
1407
  removed: true,
1401
1408
  export: exportResult,
@@ -1457,6 +1464,7 @@ module.exports = fp(async (fastify, options) => {
1457
1464
 
1458
1465
  const removeLogFiles = async ({ name, files = [] }) => {
1459
1466
  const app = await getByName(name);
1467
+ assertNotLinked(app, '删除远程日志');
1460
1468
  const targets = [];
1461
1469
  for (const fileName of files) {
1462
1470
  if (isCurrentFileName(fileName)) {
@@ -1,5 +1,7 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const { KIND_LINKED, isLinked, linkedBaseUrl } = require('../utils/appKind');
3
+ const { mergeAppPermissionTree } = require('../utils/permissionSnapshot');
4
+ const { createProxyAuditStore } = require('../utils/proxyAudit');
3
5
 
4
6
  const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
5
7
 
@@ -33,6 +35,7 @@ const unwrapEnvelope = async response => {
33
35
 
34
36
  module.exports = fp(async (fastify, options) => {
35
37
  const { models } = fastify[options.name];
38
+ const proxyAudit = createProxyAuditStore({ appsRoot: options.appsRoot });
36
39
 
37
40
  const httpError = (statusCode, message) => {
38
41
  if (fastify.httpErrors) {
@@ -76,32 +79,99 @@ module.exports = fp(async (fastify, options) => {
76
79
  httpError(400, '未配置 getOpsServiceToken,无法代理远程运维接口');
77
80
  };
78
81
 
79
- const remoteFetch = async (app, { path: opsPath, method = 'GET', query, body, scope }) => {
82
+ const remoteFetch = async (app, { path: opsPath, method = 'GET', query, body, scope, auditAction, actor } = {}) => {
80
83
  const baseUrl = linkedBaseUrl(app);
81
84
  if (!baseUrl) {
82
85
  httpError(400, '应用缺少 options.baseUrl');
83
86
  }
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));
87
+ const action = auditAction || opsPath.replace(/^\/app-ops\//, '').replace(/\//g, '.');
88
+ try {
89
+ const token = await getOpsToken(app, scope);
90
+ const url = new URL(opsPath.replace(/^\//, ''), `${baseUrl}/`);
91
+ if (query && typeof query === 'object') {
92
+ for (const [k, v] of Object.entries(query)) {
93
+ if (v !== undefined && v !== null && v !== '') {
94
+ url.searchParams.set(k, String(v));
95
+ }
90
96
  }
91
97
  }
98
+ const response = await fetch(url, {
99
+ method,
100
+ headers: Object.assign({ authorization: `Bearer ${token}` }, body ? { 'content-type': 'application/json' } : {}),
101
+ body: body ? JSON.stringify(body) : undefined,
102
+ signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
103
+ });
104
+ const { ok, status, data, raw } = await unwrapEnvelope(response);
105
+ if (!ok) {
106
+ const message = data?.message || raw?.message || raw?.data?.message || `远程 ${status}`;
107
+ await proxyAudit
108
+ .append({
109
+ appName: app.name,
110
+ action,
111
+ result: 'error',
112
+ statusCode: status,
113
+ actor,
114
+ detail: message
115
+ })
116
+ .catch(() => {});
117
+ httpError(status >= 400 && status < 600 ? status : 502, message);
118
+ }
119
+ await proxyAudit
120
+ .append({
121
+ appName: app.name,
122
+ action,
123
+ result: 'ok',
124
+ statusCode: 200,
125
+ actor,
126
+ detail: body?.file || query?.file || null
127
+ })
128
+ .catch(() => {});
129
+ return data;
130
+ } catch (e) {
131
+ if (!e.statusCode) {
132
+ await proxyAudit
133
+ .append({
134
+ appName: app.name,
135
+ action,
136
+ result: 'error',
137
+ statusCode: 502,
138
+ actor,
139
+ detail: e.message
140
+ })
141
+ .catch(() => {});
142
+ }
143
+ throw e;
92
144
  }
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)
145
+ };
146
+
147
+ const applyPermissionSnapshot = async (app, remotePermissions) => {
148
+ const previous = app.options?.permissionTree || null;
149
+ const tree = mergeAppPermissionTree(app.name, remotePermissions, previous);
150
+ const nextOptions = Object.assign({}, app.options || {}, {
151
+ permissionsSnapshot: remotePermissions,
152
+ permissionTree: tree,
153
+ permissionsSyncedAt: new Date().toISOString()
98
154
  });
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);
155
+ await app.update({ options: nextOptions });
156
+ await app.reload();
157
+ if (typeof options.onPermissionsSynced === 'function') {
158
+ await options.onPermissionsSynced({ app, tree, sourceKey: `app:${app.name}` });
159
+ }
160
+ return tree;
161
+ };
162
+
163
+ const assertNameAvailable = async name => {
164
+ const exists = await models.app.findOne({ where: { name } });
165
+ if (exists) {
166
+ httpError(409, `应用 ${name} 已存在`);
167
+ }
168
+ if (typeof options.getPermissionRootCodes === 'function') {
169
+ const roots = await options.getPermissionRootCodes();
170
+ const set = new Set((roots || []).map(String));
171
+ if (set.has(name)) {
172
+ httpError(409, `应用 name ${name} 与本平台权限顶层码冲突,请远程改名后重试`);
173
+ }
103
174
  }
104
- return data;
105
175
  };
106
176
 
107
177
  const slugifyName = raw => {
@@ -140,10 +210,7 @@ module.exports = fp(async (fastify, options) => {
140
210
  if (!name || !NAME_RE.test(name)) {
141
211
  httpError(400, '应用 name 无效:请传合法 slug 或远程改名');
142
212
  }
143
- const exists = await models.app.findOne({ where: { name } });
144
- if (exists) {
145
- httpError(409, `应用 ${name} 已存在`);
146
- }
213
+ await assertNameAvailable(name);
147
214
 
148
215
  const assertion = await signAssertion(baseUrl);
149
216
  const redeemRes = await fetch(`${baseUrl}/app-ops/link/redeem`, {
@@ -220,12 +287,12 @@ module.exports = fp(async (fastify, options) => {
220
287
  clientId: oidcInfo.clientId,
221
288
  serviceClientId: oidcInfo.serviceClientId,
222
289
  serviceClientSecret: oidcInfo.serviceClientSecret
223
- },
224
- permissionsSyncedAt: new Date().toISOString()
290
+ }
225
291
  }),
226
292
  message: null
227
293
  });
228
294
  await app.reload();
295
+ await applyPermissionSnapshot(app, manifest.permissions || []);
229
296
  } catch (e) {
230
297
  if (typeof options.onAppRemoved === 'function' && oidcInfo) {
231
298
  try {
@@ -276,17 +343,19 @@ module.exports = fp(async (fastify, options) => {
276
343
  status: readyOk ? 'running' : 'error',
277
344
  message: readyOk ? null : '远程健康检查失败',
278
345
  options: Object.assign({}, app.options || {}, {
279
- permissionsSnapshot: perms?.permissions || perms || app.options?.permissionsSnapshot || [],
280
- permissionsSyncedAt: new Date().toISOString(),
281
346
  linkStatus: 'paired'
282
347
  })
283
348
  });
349
+ await app.reload();
350
+ const remotePerms = perms?.permissions || perms || app.options?.permissionsSnapshot || [];
351
+ await applyPermissionSnapshot(app, remotePerms);
284
352
  if (typeof options.ensureLinkedRegistration === 'function') {
285
353
  await options.ensureLinkedRegistration({ app, remoteBaseUrl: baseUrl });
286
354
  }
287
355
  await app.reload();
288
356
  return { name: app.name, ok: true, status: app.status };
289
357
  } catch (e) {
358
+ // 远程不可达:沿用已有 permissionTree / snapshot,不清空
290
359
  await app
291
360
  .update({
292
361
  status: 'error',
@@ -306,9 +375,113 @@ module.exports = fp(async (fastify, options) => {
306
375
  return results.filter(Boolean);
307
376
  };
308
377
 
378
+ /**
379
+ * 透传远程 SSE(logs/stream)。会 hijack reply;超时加长以免掐断长连接。
380
+ */
381
+ const remoteStream = async (app, { path: opsPath, query, scope, reply, request, auditAction, actor } = {}) => {
382
+ const baseUrl = linkedBaseUrl(app);
383
+ if (!baseUrl) {
384
+ httpError(400, '应用缺少 options.baseUrl');
385
+ }
386
+ const action = auditAction || opsPath.replace(/^\/app-ops\//, '').replace(/\//g, '.');
387
+ const token = await getOpsToken(app, scope);
388
+ const url = new URL(opsPath.replace(/^\//, ''), `${baseUrl}/`);
389
+ if (query && typeof query === 'object') {
390
+ for (const [k, v] of Object.entries(query)) {
391
+ if (v !== undefined && v !== null && v !== '') {
392
+ url.searchParams.set(k, String(v));
393
+ }
394
+ }
395
+ }
396
+ const abort = new AbortController();
397
+ const onClose = () => abort.abort();
398
+ request.raw.on('close', onClose);
399
+ let response;
400
+ try {
401
+ response = await fetch(url, {
402
+ method: 'GET',
403
+ headers: { authorization: `Bearer ${token}`, accept: 'text/event-stream' },
404
+ signal: abort.signal
405
+ });
406
+ } catch (e) {
407
+ request.raw.off('close', onClose);
408
+ await proxyAudit
409
+ .append({
410
+ appName: app.name,
411
+ action,
412
+ result: 'error',
413
+ statusCode: 502,
414
+ actor,
415
+ detail: e.message
416
+ })
417
+ .catch(() => {});
418
+ httpError(502, e.message || '远程 SSE 连接失败');
419
+ }
420
+ if (!response.ok) {
421
+ request.raw.off('close', onClose);
422
+ const text = await response.text().catch(() => '');
423
+ await proxyAudit
424
+ .append({
425
+ appName: app.name,
426
+ action,
427
+ result: 'error',
428
+ statusCode: response.status,
429
+ actor,
430
+ detail: text.slice(0, 200)
431
+ })
432
+ .catch(() => {});
433
+ httpError(response.status >= 400 && response.status < 600 ? response.status : 502, text || `远程 ${response.status}`);
434
+ }
435
+ await proxyAudit
436
+ .append({
437
+ appName: app.name,
438
+ action,
439
+ result: 'ok',
440
+ statusCode: 200,
441
+ actor
442
+ })
443
+ .catch(() => {});
444
+
445
+ reply.hijack();
446
+ reply.raw.writeHead(200, {
447
+ 'Content-Type': 'text/event-stream; charset=utf-8',
448
+ 'Cache-Control': 'no-cache, no-transform',
449
+ Connection: 'keep-alive',
450
+ 'X-Accel-Buffering': 'no'
451
+ });
452
+
453
+ const { Readable } = require('node:stream');
454
+ const { pipeline } = require('node:stream/promises');
455
+ try {
456
+ const nodeStream = Readable.fromWeb(response.body);
457
+ await pipeline(nodeStream, reply.raw);
458
+ } catch (e) {
459
+ if (!abort.signal.aborted) {
460
+ fastify.log.warn({ err: e, app: app.name }, 'linked logs stream proxy ended');
461
+ }
462
+ } finally {
463
+ request.raw.off('close', onClose);
464
+ try {
465
+ reply.raw.end();
466
+ } catch (e) {
467
+ /* ignore */
468
+ }
469
+ }
470
+ };
471
+
309
472
  const proxy = {
310
473
  logs: (app, query) => remoteFetch(app, { path: '/app-ops/logs', query, scope: 'app-ops:logs:read' }),
311
474
  logFiles: app => remoteFetch(app, { path: '/app-ops/logs/files', scope: 'app-ops:logs:read' }),
475
+ logStream: (app, { reply, request, stream, actor }) =>
476
+ remoteStream(app, {
477
+ path: '/app-ops/logs/stream',
478
+ query: stream ? { stream } : {},
479
+ scope: 'app-ops:logs:read',
480
+ reply,
481
+ request,
482
+ auditAction: 'logs.stream',
483
+ actor
484
+ }),
312
485
  env: app => remoteFetch(app, { path: '/app-ops/env', scope: 'app-ops:env:read' }),
313
486
  permissions: app => remoteFetch(app, { path: '/app-ops/permissions', scope: 'app-ops:permissions:read' }),
314
487
  dbTables: app => remoteFetch(app, { path: '/app-ops/db/tables', scope: 'app-ops:db:read' }),
@@ -328,7 +501,10 @@ module.exports = fp(async (fastify, options) => {
328
501
  syncAllLinked,
329
502
  decodeInstallKey,
330
503
  proxy,
331
- remoteFetch
504
+ remoteFetch,
505
+ remoteStream,
506
+ listProxyAudit: proxyAudit.list,
507
+ applyPermissionSnapshot
332
508
  }
333
509
  });
334
510
  });
@@ -0,0 +1,140 @@
1
+ /**
2
+ * 将远程权限树规范为以 appName 为顶层 code 的 modules 树;
3
+ * 相对上一份快照:仍存在的码保留,远程已删的码标记 stale(不从树中移除,避免角色授予被清掉)。
4
+ */
5
+
6
+ const flattenCodes = (node, acc = new Set()) => {
7
+ if (!node) {
8
+ return acc;
9
+ }
10
+ if (Array.isArray(node)) {
11
+ node.forEach(item => flattenCodes(item, acc));
12
+ return acc;
13
+ }
14
+ if (node.code) {
15
+ acc.add(String(node.code));
16
+ }
17
+ if (Array.isArray(node.modules)) {
18
+ node.modules.forEach(item => flattenCodes(item, acc));
19
+ }
20
+ if (Array.isArray(node.permissions)) {
21
+ node.permissions.forEach(item => flattenCodes(item, acc));
22
+ }
23
+ return acc;
24
+ };
25
+
26
+ const markStaleDeep = (nodes, liveCodes) =>
27
+ (Array.isArray(nodes) ? nodes : []).map(node => {
28
+ const next = Object.assign({}, node);
29
+ if (next.code && !liveCodes.has(String(next.code))) {
30
+ next.stale = true;
31
+ } else if (next.stale) {
32
+ delete next.stale;
33
+ }
34
+ if (Array.isArray(next.modules)) {
35
+ next.modules = markStaleDeep(next.modules, liveCodes);
36
+ }
37
+ if (Array.isArray(next.permissions)) {
38
+ next.permissions = markStaleDeep(next.permissions, liveCodes);
39
+ }
40
+ return next;
41
+ });
42
+
43
+ const asModulesTree = permissions => {
44
+ if (!permissions) {
45
+ return { modules: [] };
46
+ }
47
+ if (Array.isArray(permissions)) {
48
+ return { modules: permissions };
49
+ }
50
+ if (Array.isArray(permissions.modules)) {
51
+ return { modules: permissions.modules };
52
+ }
53
+ return { modules: [] };
54
+ };
55
+
56
+ /**
57
+ * @param {string} appName
58
+ * @param {object|array} remotePermissions 远程返回
59
+ * @param {object|null} previousTree 上一份已规范树(含顶层 appName)
60
+ */
61
+ const mergeAppPermissionTree = (appName, remotePermissions, previousTree = null) => {
62
+ const name = String(appName);
63
+ const remote = asModulesTree(remotePermissions);
64
+ const liveCodes = flattenCodes(remote);
65
+ // 远程子树挂到 appName 顶层下;若远程已自带同名顶层则直接用
66
+ let children = remote.modules;
67
+ if (children.length === 1 && children[0].code === name) {
68
+ children = children[0].modules || children[0].permissions ? [children[0]] : children;
69
+ if (children[0].code === name) {
70
+ const root = Object.assign({}, children[0], { modules: markStaleDeep(children[0].modules || [], liveCodes) });
71
+ // 合并 previous 中已 stale 但仍存在的叶子
72
+ if (previousTree?.modules?.[0]?.code === name) {
73
+ root.modules = mergeMissingStale(root.modules || [], previousTree.modules[0].modules || [], liveCodes);
74
+ }
75
+ return { modules: [root] };
76
+ }
77
+ }
78
+
79
+ let modules = markStaleDeep(children, liveCodes);
80
+ if (previousTree?.modules?.[0]?.code === name) {
81
+ modules = mergeMissingStale(modules, previousTree.modules[0].modules || [], liveCodes);
82
+ }
83
+
84
+ const label = (previousTree?.modules?.[0] && previousTree.modules[0].name) || (remote.modules?.[0] && remote.modules[0].name) || name;
85
+
86
+ return {
87
+ modules: [
88
+ {
89
+ name: label,
90
+ code: name,
91
+ modules
92
+ }
93
+ ]
94
+ };
95
+ };
96
+
97
+ /** 上一份有、本次 live 没有的节点:以 stale 形式保留 */
98
+ const mergeMissingStale = (current, previous, liveCodes) => {
99
+ const byCode = new Map((current || []).filter(n => n.code).map(n => [String(n.code), n]));
100
+ for (const prev of previous || []) {
101
+ if (!prev?.code) {
102
+ continue;
103
+ }
104
+ const code = String(prev.code);
105
+ if (byCode.has(code)) {
106
+ const cur = byCode.get(code);
107
+ if (Array.isArray(prev.modules) || Array.isArray(cur.modules)) {
108
+ cur.modules = mergeMissingStale(cur.modules || [], prev.modules || [], liveCodes);
109
+ }
110
+ if (Array.isArray(prev.permissions) || Array.isArray(cur.permissions)) {
111
+ cur.permissions = mergeMissingStale(cur.permissions || [], prev.permissions || [], liveCodes);
112
+ }
113
+ continue;
114
+ }
115
+ if (!liveCodes.has(code)) {
116
+ byCode.set(
117
+ code,
118
+ Object.assign({}, prev, {
119
+ stale: true,
120
+ modules: prev.modules ? markStaleDeep(prev.modules, liveCodes) : prev.modules,
121
+ permissions: prev.permissions ? markStaleDeep(prev.permissions, liveCodes) : prev.permissions
122
+ })
123
+ );
124
+ }
125
+ }
126
+ return Array.from(byCode.values());
127
+ };
128
+
129
+ const topLevelCodes = tree =>
130
+ (tree?.modules || [])
131
+ .map(m => m.code)
132
+ .filter(Boolean)
133
+ .map(String);
134
+
135
+ module.exports = {
136
+ flattenCodes,
137
+ asModulesTree,
138
+ mergeAppPermissionTree,
139
+ topLevelCodes
140
+ };
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-app-manager",
3
- "version": "0.1.30",
3
+ "version": "0.1.32",
4
4
  "description": "Fastify 单机应用市场插件:版本上传、PM2 托管、路径/域名反代与日志 SSE",
5
5
  "main": "index.js",
6
6
  "scripts": {