-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcds-plugin.js
336 lines (311 loc) · 10.7 KB
/
cds-plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"use strict";
const fs = require("fs");
const path = require("path");
const cds = require("@sap/cds");
const Broker = require("@sap/sbf");
const express = require("express");
const helmet = require("helmet");
const cors = require("cors");
const swaggerUi = require("swagger-ui-express");
const { StatusCodes, getReasonPhrase } = require("http-status-codes");
const toggles = require("@cap-js-community/feature-toggle-library");
const { config: eventQueueConfig } = require("@cap-js-community/event-queue");
const { mergeDeep, toObject } = require("./src/util/helper");
const config = mergeDeep(require("./config"), cds.env.requires?.["sap-afc-sdk"]?.config ?? {});
const APPROUTER_SUFFIX = "srv";
process.env.CDS_PLUGIN_PACKAGE ??= "@cap-js-community/sap-afc-sdk";
cds.on("bootstrap", () => {
secureRoutes();
addErrorMiddleware();
serveBroker();
serveUIs();
serveSwaggerUI();
});
cds.on("connect", (srv) => {
if (srv.name === "db") {
registerAfterJobReadFillLink(srv);
}
});
cds.on("listening", () => {
outboxServices();
handleFeatureToggles();
});
function secureRoutes() {
if (cds.env.requires?.["sap-afc-sdk"]?.api?.cors) {
const corsOptions = toObject(cds.env.requires?.["sap-afc-sdk"]?.api?.cors);
cds.app.use("/api", cors(corsOptions));
}
if (serverUrl().startsWith("http://localhost")) {
return;
}
if (cds.env.requires?.["sap-afc-sdk"]?.api?.csp) {
const csp = toObject(cds.env.requires?.["sap-afc-sdk"]?.api?.csp);
const defaultDirectives = helmet.contentSecurityPolicy.getDefaultDirectives();
cds.app.use(
"/api",
helmet({
contentSecurityPolicy: {
directives: {
...defaultDirectives,
"default-src": [
...(defaultDirectives["default-src"] || []),
approuterUrl(),
serverUrl(),
authorizationUrl(),
],
...csp,
},
},
}),
);
}
}
function addErrorMiddleware() {
cds.middlewares.after.unshift(handleError);
}
function handleError(err, req, res, next) {
if (!err) {
return next(err);
}
if (req.baseUrl?.startsWith("/api/")) {
return handleAPIError(err, req, res);
}
next(err);
}
function handleAPIError(err, req, res) {
let statusCode = StatusCodes.INTERNAL_SERVER_ERROR;
const codes = [err.statusCode, err.status, err.code, err];
for (const code of codes) {
if (!isNaN(code) && StatusCodes[String(code)]) {
statusCode = parseInt(code);
break;
}
}
res.status(statusCode).send({
code: String(err.code || statusCode),
message: err.message || getReasonPhrase(statusCode),
});
}
function serveBroker() {
if (!cds.env.requires?.["sap-afc-sdk"]?.broker) {
return;
}
let brokerConfig = toObject(cds.env.requires?.["sap-afc-sdk"]?.broker);
const brokerPath = path.join(cds.root, config.paths.broker);
try {
brokerConfig = mergeDeep(require(brokerPath), brokerConfig);
} catch (err) {
if (Object.keys(brokerConfig).length === 0) {
cds.log("/broker").info(`broker.json not found at '${brokerPath}'. Call 'afc add broker'`);
}
}
for (const service in brokerConfig?.SBF_SERVICE_CONFIG ?? {}) {
const endpoints = brokerConfig?.SBF_SERVICE_CONFIG[service]?.extend_credentials?.shared?.endpoints ?? {};
for (const endpoint in endpoints) {
if (!/https?:\/\//.test(endpoints[endpoint])) {
endpoints[endpoint] = `${serverUrl()}${endpoints[endpoint]}`;
}
}
}
for (const key in brokerConfig) {
if (key.startsWith("SBF_")) {
process.env[key] ??= JSON.stringify(brokerConfig[key]);
}
}
try {
const catalogPath = brokerConfig.catalog ?? config.paths.catalog;
const router = express.Router();
const broker = new Broker({
enableAuditLog: false,
catalog: catalogPath,
});
router.use("/broker", broker.app);
cds.app.use(router);
} catch (err) {
cds.log("/broker").error("Failed to start broker", err);
}
}
function serveUIs() {
if (process.env.CDS_PLUGIN_PACKAGE === "." && process.env.NODE_ENV !== "test") {
return;
}
if (!cds.env.requires?.["sap-afc-sdk"]?.ui) {
return;
}
const uiPath = cds.env.requires?.["sap-afc-sdk"]?.ui?.path;
let uiShowLaunchpad = cds.env.requires?.["sap-afc-sdk"]?.ui?.launchpad;
if (uiShowLaunchpad) {
const packageRoot = cds.utils.path.resolve(
require.resolve(path.join(process.env.CDS_PLUGIN_PACKAGE, "package.json"), { paths: [cds.root] }),
"..",
);
if (!fs.existsSync(`${cds.root}/${cds.env.folders.app}appconfig/fioriSandboxConfig.json`)) {
cds.app.serve(`${uiPath}/${config.paths.launchpad}`).from(process.env.CDS_PLUGIN_PACKAGE, "/app/launchpad.html");
cds.app.use(`/appconfig`, express.static(`${packageRoot}/app/appconfig`));
} else {
serveAppConfig(packageRoot, uiPath);
uiShowLaunchpad = false;
}
}
for (const app in config.apps) {
const uiShowApp = cds.env.requires?.["sap-afc-sdk"]?.ui?.[app];
if ((uiShowLaunchpad || uiShowApp) && !fs.existsSync(`${cds.root}/${cds.env.folders.app}${app}`)) {
cds.app
.serve(`${uiPath}/${app}`)
.from(process.env.CDS_PLUGIN_PACKAGE, config.paths[app] ?? `${cds.env.folders.app}${app}/webapp`);
cds.app
.serve(`${uiPath}/${app}/webapp`)
.from(process.env.CDS_PLUGIN_PACKAGE, config.paths[app] ?? `${cds.env.folders.app}${app}/webapp`);
}
}
}
function serveAppConfig(packageRoot, uiPath) {
cds.app.use(`/appconfig/fioriSandboxConfig.json`, (req, res) => {
const projectFioriSandboxConfig = require(`${cds.root}/${cds.env.folders.app}appconfig/fioriSandboxConfig.json`);
const packageFioriSandboxConfig = require(`${packageRoot}/app/appconfig/fioriSandboxConfig.json`);
if (uiPath) {
for (const name in packageFioriSandboxConfig.applications ?? {}) {
const application = packageFioriSandboxConfig.applications[name];
application.url = `${uiPath}/${application.url}`;
}
for (const name in packageFioriSandboxConfig.services?.ClientSideTargetResolution?.adapter?.config?.inbounds ??
{}) {
const inbound = packageFioriSandboxConfig.services?.ClientSideTargetResolution?.adapter?.config?.inbounds[name];
inbound.resolutionResult.url = `${uiPath}/${inbound.resolutionResult.url}`;
}
}
const mergedFioriSandboxConfig = mergeDeep(packageFioriSandboxConfig, projectFioriSandboxConfig);
res.send(mergedFioriSandboxConfig);
});
}
function serveSwaggerUI() {
const router = express.Router();
cds.on("serving", (service) => {
const openAPI = service.definition?.["@openapi"];
if (openAPI) {
const apiPath = config.paths.swaggerUi + service.path;
cds.log("/swagger").info("Serving Swagger UI for ", { service: service.name, at: apiPath });
router.use(
apiPath,
...cds.middlewares.before,
(req, res, next) => {
const restrict_all = cds.env.requires?.auth?.restrict_all_services !== false;
if (!restrict_all || cds.context?.user?._is_privileged || !cds.context?.user?._is_anonymous) {
return next();
}
res.send(401, "Unauthorized");
},
(req, res, next) => {
req.swaggerDoc = toOpenApiDoc(req, service, openAPI);
if (req.swaggerDoc) {
return next();
}
res.send(404, "Not found");
},
swaggerUi.serveFiles(),
swaggerUi.setup(null, {}),
...cds.middlewares.after,
);
addLinkToIndexHtml(service, apiPath);
}
});
cds.app.use(router);
}
const openAPICache = new Map();
function toOpenApiDoc(req, service, name) {
const filePath = `${name === true ? service.name : name}.${config.extensions.openapi}`;
if (openAPICache.has(filePath)) {
return openAPICache.get(filePath);
}
let openAPI;
const paths = [
path.join(cds.root, filePath),
path.join(cds.root, "openapi", filePath),
path.join(__dirname, filePath),
path.join(__dirname, "openapi", filePath),
];
for (const path of paths) {
if (fs.existsSync(path)) {
openAPI = JSON.parse(fs.readFileSync(path));
if (openAPI) {
break;
}
}
}
if (openAPI) {
const clientCredentials = openAPI?.components?.securitySchemes?.oauth2?.flows?.clientCredentials;
if (clientCredentials) {
clientCredentials.tokenUrl = authorizationUrl() + "/oauth/token";
}
openAPI.servers.forEach((server) => {
if (!server.url.startsWith("https://") && !server.url.startsWith("http://")) {
server.url = `${serverUrl()}${server.url}`;
}
});
openAPICache.set(filePath, openAPI);
}
return openAPI;
}
function approuterUrl() {
if (cds.env.requires?.["sap-afc-sdk"]?.endpoints?.approuter) {
return cds.env.requires?.["sap-afc-sdk"]?.endpoints?.approuter;
}
return serverUrl().replace(/(https?:\/\/)(.*?)(\..*)/, `$1$2-${APPROUTER_SUFFIX}$3`);
}
function serverUrl() {
if (cds.env.requires?.["sap-afc-sdk"]?.endpoints?.server) {
return cds.env.requires?.["sap-afc-sdk"]?.endpoints?.server;
}
// TODO: Kyma
if (process.env.VCAP_APPLICATION) {
const url = JSON.parse(process.env.VCAP_APPLICATION).uris?.[0];
if (url) {
return `https://${url}`;
}
}
return cds.server.url ?? `http://localhost:${process.env.PORT || cds.env.server?.port || 4004}`;
}
function authorizationUrl() {
// TODO: IAS
return cds.env.requires?.auth?.credentials?.url ?? config.endpoints.authentication;
}
function addLinkToIndexHtml(service, apiPath) {
const provider = () => {
return { href: apiPath, name: "Open API", title: "Show in Swagger UI" };
};
service.$linkProviders ? service.$linkProviders.push(provider) : (service.$linkProviders = [provider]);
}
function outboxServices() {
for (const service in config.services) {
if (cds.services[service] && cds.requires[service]?.outbox && config.services[service].outbox) {
cds.services[service].options.outbox = cds.requires[service].outbox;
cds.services[service] = cds.outboxed(cds.services[service]);
}
}
}
function handleFeatureToggles() {
// event-queue
for (const name in config.toggles.eventQueue) {
const toggle = config.toggles.eventQueue[name];
eventQueueConfig[name] = toggles.getFeatureValue(toggle);
toggles.registerFeatureValueChangeHandler(toggle, (value) => {
eventQueueConfig[name] = value;
});
}
}
function registerAfterJobReadFillLink(db) {
if (!cds.env.requires?.["sap-afc-sdk"]?.ui?.link) {
return;
}
db.after("READ", async (result, req) => {
if (req.target.name.split(".").pop() !== "Job") {
return;
}
result = Array.isArray(result) ? result : [result];
for (const row of result) {
if (row.ID && row.link === null) {
row.link = `${approuterUrl()}/${config.paths.launchpad}#Job-monitor&/Job(${row.ID})`;
}
}
});
}