@kne/fastify-app-manager 0.1.28 → 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 +12 -0
- package/libs/controllers/app.js +377 -137
- package/libs/controllers/dbops.js +130 -47
- package/libs/controllers/link.js +68 -0
- package/libs/controllers/migration.js +50 -13
- package/libs/models/app.js +15 -9
- package/libs/schema/response.js +234 -0
- package/libs/services/app.js +64 -13
- package/libs/services/bootstrap.js +54 -6
- package/libs/services/dbops.js +19 -0
- package/libs/services/link.js +334 -0
- package/libs/services/migration.js +22 -0
- package/libs/services/openApi.js +14 -1
- package/libs/utils/appKind.js +33 -0
- package/oidc.js +121 -12
- package/package.json +1 -1
|
@@ -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);
|
package/libs/services/openApi.js
CHANGED
|
@@ -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(
|
|
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({
|
|
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
|
-
|
|
89
|
-
|
|
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
|
-
|
|
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
|
|
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 (
|
|
287
|
+
if (audience) {
|
|
265
288
|
const docsClient = await models.client.findOne({ where: { clientId: DOCS_CLIENT_ID } });
|
|
266
|
-
if (docsClient && (docsClient.allowedResources || []).includes(
|
|
267
|
-
await services.client.save({ id: docsClient.id, allowedResources: docsClient.allowedResources.filter(item => item !==
|
|
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:
|
|
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
|
-
|
|
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;
|