@backstage/plugin-app-backend 0.3.74-next.1 → 0.3.74

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/CHANGELOG.md CHANGED
@@ -1,5 +1,54 @@
1
1
  # @backstage/plugin-app-backend
2
2
 
3
+ ## 0.3.74
4
+
5
+ ### Patch Changes
6
+
7
+ - 72a8c7b: Return HTTP status 400 rather than 500 when receiving an unknown POST request.
8
+ - d3f79d1: Fixing dependency metadata with the new `@backstage/plugin-app` package
9
+ - 590fb2d: **BREAKING**: The app backend now supports the new `index.html.tmpl` output from `@backstage/cli`. If available, the `index.html` will be templated at runtime with the current configuration of the app backend.
10
+
11
+ This is marked as a breaking change because you must now supply the app build-time configuration to the backend. This change also affects the public path behavior, where it is no longer necessary to build the app with the correct public path upfront. You now only need to supply a correct `app.baseUrl` to the app backend plugin at runtime.
12
+
13
+ An effect that this change has is that the `index.html` will now contain and present the frontend configuration in an easily readable way, which can aid in debugging. This data was always available in the frontend, but it was injected and hidden in the static bundle.
14
+
15
+ This templating behavior is enabled by default, but it can be disabled by setting the `app.disableConfigInjection` configuration option to `true`.
16
+
17
+ - d425fc4: Modules, plugins, and services are now `BackendFeature`, not a function that returns a feature.
18
+ - c2b63ab: Updated dependency `supertest` to `^7.0.0`.
19
+ - Updated dependencies
20
+ - @backstage/backend-common@0.25.0
21
+ - @backstage/backend-plugin-api@1.0.0
22
+ - @backstage/plugin-auth-node@0.5.2
23
+ - @backstage/plugin-app-node@0.1.25
24
+ - @backstage/config-loader@1.9.1
25
+ - @backstage/config@1.2.0
26
+ - @backstage/errors@1.2.4
27
+ - @backstage/types@1.1.1
28
+
29
+ ## 0.3.74-next.2
30
+
31
+ ### Patch Changes
32
+
33
+ - 590fb2d: **BREAKING**: The app backend now supports the new `index.html.tmpl` output from `@backstage/cli`. If available, the `index.html` will be templated at runtime with the current configuration of the app backend.
34
+
35
+ This is marked as a breaking change because you must now supply the app build-time configuration to the backend. This change also affects the public path behavior, where it is no longer necessary to build the app with the correct public path upfront. You now only need to supply a correct `app.baseUrl` to the app backend plugin at runtime.
36
+
37
+ An effect that this change has is that the `index.html` will now contain and present the frontend configuration in an easily readable way, which can aid in debugging. This data was always available in the frontend, but it was injected and hidden in the static bundle.
38
+
39
+ This templating behavior is enabled by default, but it can be disabled by setting the `app.disableConfigInjection` configuration option to `true`.
40
+
41
+ - c2b63ab: Updated dependency `supertest` to `^7.0.0`.
42
+ - Updated dependencies
43
+ - @backstage/backend-common@0.25.0-next.2
44
+ - @backstage/plugin-auth-node@0.5.2-next.2
45
+ - @backstage/backend-plugin-api@1.0.0-next.2
46
+ - @backstage/config-loader@1.9.1-next.0
47
+ - @backstage/config@1.2.0
48
+ - @backstage/errors@1.2.4
49
+ - @backstage/types@1.1.1
50
+ - @backstage/plugin-app-node@0.1.25-next.2
51
+
3
52
  ## 0.3.74-next.1
4
53
 
5
54
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-app-backend__alpha",
3
- "version": "0.3.74-next.1",
3
+ "version": "0.3.74",
4
4
  "main": "../dist/alpha.cjs.js",
5
5
  "types": "../dist/alpha.d.ts"
6
6
  }
package/dist/alpha.cjs.js CHANGED
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var backendPluginApi = require('@backstage/backend-plugin-api');
6
- var router = require('./cjs/router-9HkxMeSl.cjs.js');
6
+ var router = require('./cjs/router-iVPYMLvA.cjs.js');
7
7
  var pluginAppNode = require('@backstage/plugin-app-node');
8
8
  require('@backstage/backend-common');
9
9
  require('helmet');
@@ -11,11 +11,13 @@ require('express');
11
11
  require('express-promise-router');
12
12
  require('fs-extra');
13
13
  require('path');
14
- require('@backstage/config-loader');
15
14
  require('luxon');
16
15
  require('lodash/partition');
17
16
  require('globby');
18
17
  require('@backstage/errors');
18
+ require('lodash/template');
19
+ require('@backstage/config');
20
+ require('@backstage/config-loader');
19
21
 
20
22
  const appPlugin = backendPluginApi.createBackendPlugin({
21
23
  pluginId: "app",
@@ -1 +1 @@
1
- {"version":3,"file":"alpha.cjs.js","sources":["../src/service/appPlugin.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { createRouter } from './router';\nimport {\n configSchemaExtensionPoint,\n staticFallbackHandlerExtensionPoint,\n} from '@backstage/plugin-app-node';\nimport { ConfigSchema } from '@backstage/config-loader';\n\n/**\n * The App plugin is responsible for serving the frontend app bundle and static assets.\n * @alpha\n */\nexport const appPlugin = createBackendPlugin({\n pluginId: 'app',\n register(env) {\n let staticFallbackHandler: express.Handler | undefined;\n let schema: ConfigSchema | undefined;\n\n env.registerExtensionPoint(staticFallbackHandlerExtensionPoint, {\n setStaticFallbackHandler(handler) {\n if (staticFallbackHandler) {\n throw new Error(\n 'Attempted to install a static fallback handler for the app-backend twice',\n );\n }\n staticFallbackHandler = handler;\n },\n });\n\n env.registerExtensionPoint(configSchemaExtensionPoint, {\n setConfigSchema(configSchema) {\n if (schema) {\n throw new Error(\n 'Attempted to set config schema for the app-backend twice',\n );\n }\n schema = configSchema;\n },\n });\n\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n database: coreServices.database,\n httpRouter: coreServices.httpRouter,\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n },\n async init({ logger, config, database, httpRouter, auth, httpAuth }) {\n const appPackageName =\n config.getOptionalString('app.packageName') ?? 'app';\n\n const router = await createRouter({\n logger,\n config,\n database,\n auth,\n httpAuth,\n appPackageName,\n staticFallbackHandler,\n schema,\n });\n httpRouter.use(router);\n\n // Access control is handled within the router\n httpRouter.addAuthPolicy({\n allow: 'unauthenticated',\n path: '/',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","staticFallbackHandlerExtensionPoint","configSchemaExtensionPoint","coreServices","router","createRouter"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCO,MAAM,YAAYA,oCAAoB,CAAA;AAAA,EAC3C,QAAU,EAAA,KAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAI,IAAA,qBAAA,CAAA;AACJ,IAAI,IAAA,MAAA,CAAA;AAEJ,IAAA,GAAA,CAAI,uBAAuBC,iDAAqC,EAAA;AAAA,MAC9D,yBAAyB,OAAS,EAAA;AAChC,QAAA,IAAI,qBAAuB,EAAA;AACzB,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,0EAAA;AAAA,WACF,CAAA;AAAA,SACF;AACA,QAAwB,qBAAA,GAAA,OAAA,CAAA;AAAA,OAC1B;AAAA,KACD,CAAA,CAAA;AAED,IAAA,GAAA,CAAI,uBAAuBC,wCAA4B,EAAA;AAAA,MACrD,gBAAgB,YAAc,EAAA;AAC5B,QAAA,IAAI,MAAQ,EAAA;AACV,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,0DAAA;AAAA,WACF,CAAA;AAAA,SACF;AACA,QAAS,MAAA,GAAA,YAAA,CAAA;AAAA,OACX;AAAA,KACD,CAAA,CAAA;AAED,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,QAAQC,6BAAa,CAAA,MAAA;AAAA,QACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,QACrB,UAAUA,6BAAa,CAAA,QAAA;AAAA,QACvB,YAAYA,6BAAa,CAAA,UAAA;AAAA,QACzB,MAAMA,6BAAa,CAAA,IAAA;AAAA,QACnB,UAAUA,6BAAa,CAAA,QAAA;AAAA,OACzB;AAAA,MACA,MAAM,KAAK,EAAE,MAAA,EAAQ,QAAQ,QAAU,EAAA,UAAA,EAAY,IAAM,EAAA,QAAA,EAAY,EAAA;AACnE,QAAA,MAAM,cACJ,GAAA,MAAA,CAAO,iBAAkB,CAAA,iBAAiB,CAAK,IAAA,KAAA,CAAA;AAEjD,QAAM,MAAAC,QAAA,GAAS,MAAMC,mBAAa,CAAA;AAAA,UAChC,MAAA;AAAA,UACA,MAAA;AAAA,UACA,QAAA;AAAA,UACA,IAAA;AAAA,UACA,QAAA;AAAA,UACA,cAAA;AAAA,UACA,qBAAA;AAAA,UACA,MAAA;AAAA,SACD,CAAA,CAAA;AACD,QAAA,UAAA,CAAW,IAAID,QAAM,CAAA,CAAA;AAGrB,QAAA,UAAA,CAAW,aAAc,CAAA;AAAA,UACvB,KAAO,EAAA,iBAAA;AAAA,UACP,IAAM,EAAA,GAAA;AAAA,SACP,CAAA,CAAA;AAAA,OACH;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;"}
1
+ {"version":3,"file":"alpha.cjs.js","sources":["../src/service/appPlugin.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport express from 'express';\nimport {\n coreServices,\n createBackendPlugin,\n} from '@backstage/backend-plugin-api';\nimport { createRouter } from './router';\nimport {\n configSchemaExtensionPoint,\n staticFallbackHandlerExtensionPoint,\n} from '@backstage/plugin-app-node';\nimport { ConfigSchema } from '@backstage/config-loader';\n\n/**\n * The App plugin is responsible for serving the frontend app bundle and static assets.\n * @alpha\n */\nexport const appPlugin = createBackendPlugin({\n pluginId: 'app',\n register(env) {\n let staticFallbackHandler: express.Handler | undefined;\n let schema: ConfigSchema | undefined;\n\n env.registerExtensionPoint(staticFallbackHandlerExtensionPoint, {\n setStaticFallbackHandler(handler) {\n if (staticFallbackHandler) {\n throw new Error(\n 'Attempted to install a static fallback handler for the app-backend twice',\n );\n }\n staticFallbackHandler = handler;\n },\n });\n\n env.registerExtensionPoint(configSchemaExtensionPoint, {\n setConfigSchema(configSchema) {\n if (schema) {\n throw new Error(\n 'Attempted to set config schema for the app-backend twice',\n );\n }\n schema = configSchema;\n },\n });\n\n env.registerInit({\n deps: {\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n database: coreServices.database,\n httpRouter: coreServices.httpRouter,\n auth: coreServices.auth,\n httpAuth: coreServices.httpAuth,\n },\n async init({ logger, config, database, httpRouter, auth, httpAuth }) {\n const appPackageName =\n config.getOptionalString('app.packageName') ?? 'app';\n\n const router = await createRouter({\n logger,\n config,\n database,\n auth,\n httpAuth,\n appPackageName,\n staticFallbackHandler,\n schema,\n });\n httpRouter.use(router);\n\n // Access control is handled within the router\n httpRouter.addAuthPolicy({\n allow: 'unauthenticated',\n path: '/',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","staticFallbackHandlerExtensionPoint","configSchemaExtensionPoint","coreServices","router","createRouter"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgCO,MAAM,YAAYA,oCAAoB,CAAA;AAAA,EAC3C,QAAU,EAAA,KAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAI,IAAA,qBAAA,CAAA;AACJ,IAAI,IAAA,MAAA,CAAA;AAEJ,IAAA,GAAA,CAAI,uBAAuBC,iDAAqC,EAAA;AAAA,MAC9D,yBAAyB,OAAS,EAAA;AAChC,QAAA,IAAI,qBAAuB,EAAA;AACzB,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,0EAAA;AAAA,WACF,CAAA;AAAA,SACF;AACA,Q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AA,GACH;AACF,CAAC;;;;"}
@@ -7,11 +7,13 @@ var express = require('express');
7
7
  var Router = require('express-promise-router');
8
8
  var fs = require('fs-extra');
9
9
  var path = require('path');
10
- var configLoader = require('@backstage/config-loader');
11
10
  var luxon = require('luxon');
12
11
  var partition = require('lodash/partition');
13
12
  var globby = require('globby');
14
13
  var errors = require('@backstage/errors');
14
+ var compileTemplate = require('lodash/template');
15
+ var config = require('@backstage/config');
16
+ var configLoader = require('@backstage/config-loader');
15
17
 
16
18
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
17
19
 
@@ -21,60 +23,7 @@ var Router__default = /*#__PURE__*/_interopDefaultCompat(Router);
21
23
  var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
22
24
  var partition__default = /*#__PURE__*/_interopDefaultCompat(partition);
23
25
  var globby__default = /*#__PURE__*/_interopDefaultCompat(globby);
24
-
25
- async function injectConfig(options) {
26
- const { staticDir, logger, appConfigs } = options;
27
- const files = await fs__default.default.readdir(staticDir);
28
- const jsFiles = files.filter((file) => file.endsWith(".js"));
29
- const escapedData = JSON.stringify(appConfigs).replace(/("|'|\\)/g, "\\$1");
30
- const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/"${escapedData}"/*__INJECTED_END__*/`;
31
- for (const jsFile of jsFiles) {
32
- const path$1 = path.resolve(staticDir, jsFile);
33
- const content = await fs__default.default.readFile(path$1, "utf8");
34
- if (content.includes("__APP_INJECTED_RUNTIME_CONFIG__")) {
35
- logger.info(`Injecting env config into ${jsFile}`);
36
- const newContent = content.replaceAll(
37
- '"__APP_INJECTED_RUNTIME_CONFIG__"',
38
- injected
39
- );
40
- await fs__default.default.writeFile(path$1, newContent, "utf8");
41
- return path$1;
42
- } else if (content.includes("__APP_INJECTED_CONFIG_MARKER__")) {
43
- logger.info(`Replacing injected env config in ${jsFile}`);
44
- const newContent = content.replaceAll(
45
- /\/\*__APP_INJECTED_CONFIG_MARKER__\*\/.*?\/\*__INJECTED_END__\*\//g,
46
- injected
47
- );
48
- await fs__default.default.writeFile(path$1, newContent, "utf8");
49
- return path$1;
50
- }
51
- }
52
- logger.info("Env config not injected");
53
- return void 0;
54
- }
55
- async function readConfigs(options) {
56
- const { env, appDistDir, config } = options;
57
- const appConfigs = configLoader.readEnvConfig(env);
58
- const schemaPath = path.resolve(appDistDir, ".config-schema.json");
59
- if (await fs__default.default.pathExists(schemaPath)) {
60
- const serializedSchema = await fs__default.default.readJson(schemaPath);
61
- try {
62
- const schema = options.schema || await configLoader.loadConfigSchema({
63
- serialized: serializedSchema
64
- });
65
- const frontendConfigs = await schema.process(
66
- [{ data: config.get(), context: "app" }],
67
- { visibility: ["frontend"], withDeprecatedKeys: true }
68
- );
69
- appConfigs.push(...frontendConfigs);
70
- } catch (error) {
71
- throw new Error(
72
- `Invalid app bundle schema. If this error is unexpected you need to run \`yarn build\` in the app. If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. Caused by the following schema error, ${error}`
73
- );
74
- }
75
- }
76
- return appConfigs;
77
- }
26
+ var compileTemplate__default = /*#__PURE__*/_interopDefaultCompat(compileTemplate);
78
27
 
79
28
  const migrationsDir = backendPluginApi.resolvePackagePath(
80
29
  "@backstage/plugin-app-backend",
@@ -221,6 +170,109 @@ function createStaticAssetMiddleware(store) {
221
170
  };
222
171
  }
223
172
 
173
+ const HTML_TEMPLATE_NAME = "index.html.tmpl";
174
+ async function injectConfigIntoHtml(options) {
175
+ const { rootDir, appConfigs } = options;
176
+ const templatePath = path.resolve(rootDir, HTML_TEMPLATE_NAME);
177
+ if (!await fs__default.default.exists(templatePath)) {
178
+ return false;
179
+ }
180
+ const templateContent = await fs__default.default.readFile(
181
+ path.resolve(rootDir, HTML_TEMPLATE_NAME),
182
+ "utf8"
183
+ );
184
+ const config$1 = config.ConfigReader.fromConfigs(appConfigs);
185
+ const templateSource = compileTemplate__default.default(templateContent, {
186
+ interpolate: /<%=([\s\S]+?)%>/g
187
+ });
188
+ const publicPath = resolvePublicPath(config$1);
189
+ const indexHtmlContent = templateSource({
190
+ config: config$1,
191
+ publicPath
192
+ });
193
+ const indexHtmlContentWithConfig = indexHtmlContent.replace(
194
+ "</head>",
195
+ `
196
+ <script type="backstage.io/config">
197
+ ${JSON.stringify(appConfigs, null, 2).replaceAll("<\/script", "").replaceAll("<!--", "")}
198
+ <\/script>
199
+ </head>`
200
+ );
201
+ await fs__default.default.writeFile(
202
+ path.resolve(rootDir, "index.html"),
203
+ indexHtmlContentWithConfig,
204
+ "utf8"
205
+ );
206
+ return true;
207
+ }
208
+ function resolvePublicPath(config) {
209
+ const baseUrl = new URL(
210
+ config.getOptionalString("app.baseUrl") ?? "/",
211
+ "http://localhost:7007"
212
+ );
213
+ return baseUrl.pathname.replace(/\/+$/, "");
214
+ }
215
+
216
+ async function injectConfigIntoStatic(options) {
217
+ const { staticDir, logger, appConfigs } = options;
218
+ const files = await fs__default.default.readdir(staticDir);
219
+ const jsFiles = files.filter((file) => file.endsWith(".js"));
220
+ const escapedData = JSON.stringify(appConfigs).replace(/("|'|\\)/g, "\\$1");
221
+ const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/"${escapedData}"/*__INJECTED_END__*/`;
222
+ for (const jsFile of jsFiles) {
223
+ const path$1 = path.resolve(staticDir, jsFile);
224
+ const content = await fs__default.default.readFile(path$1, "utf8");
225
+ if (content.includes("__APP_INJECTED_RUNTIME_CONFIG__")) {
226
+ logger.info(`Injecting env config into ${jsFile}`);
227
+ const newContent = content.replaceAll(
228
+ '"__APP_INJECTED_RUNTIME_CONFIG__"',
229
+ injected
230
+ );
231
+ await fs__default.default.writeFile(path$1, newContent, "utf8");
232
+ return path$1;
233
+ } else if (content.includes("__APP_INJECTED_CONFIG_MARKER__")) {
234
+ logger.info(`Replacing injected env config in ${jsFile}`);
235
+ const newContent = content.replaceAll(
236
+ /\/\*__APP_INJECTED_CONFIG_MARKER__\*\/.*?\/\*__INJECTED_END__\*\//g,
237
+ injected
238
+ );
239
+ await fs__default.default.writeFile(path$1, newContent, "utf8");
240
+ return path$1;
241
+ }
242
+ }
243
+ logger.info("Env config not injected");
244
+ return void 0;
245
+ }
246
+
247
+ async function injectConfig(options) {
248
+ await injectConfigIntoHtml(options);
249
+ return injectConfigIntoStatic(options);
250
+ }
251
+
252
+ async function readFrontendConfig(options) {
253
+ const { env, appDistDir, config } = options;
254
+ const appConfigs = configLoader.readEnvConfig(env);
255
+ const schemaPath = path.resolve(appDistDir, ".config-schema.json");
256
+ if (await fs__default.default.pathExists(schemaPath)) {
257
+ const serializedSchema = await fs__default.default.readJson(schemaPath);
258
+ try {
259
+ const schema = options.schema || await configLoader.loadConfigSchema({
260
+ serialized: serializedSchema
261
+ });
262
+ const frontendConfigs = await schema.process(
263
+ [{ data: config.get(), context: "app" }],
264
+ { visibility: ["frontend"], withDeprecatedKeys: true }
265
+ );
266
+ appConfigs.push(...frontendConfigs);
267
+ } catch (error) {
268
+ throw new Error(
269
+ `Invalid app bundle schema. If this error is unexpected you need to run \`yarn build\` in the app. If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. Caused by the following schema error, ${error}`
270
+ );
271
+ }
272
+ }
273
+ return appConfigs;
274
+ }
275
+
224
276
  async function createRouter(options) {
225
277
  const {
226
278
  config,
@@ -246,7 +298,7 @@ async function createRouter(options) {
246
298
  return Router__default.default();
247
299
  }
248
300
  logger.info(`Serving static app content from ${appDistDir}`);
249
- const appConfigs = disableConfigInjection ? void 0 : await readConfigs({
301
+ const appConfigs = disableConfigInjection ? void 0 : await readFrontendConfig({
250
302
  config,
251
303
  appDistDir,
252
304
  env: process.env,
@@ -298,7 +350,9 @@ async function createRouter(options) {
298
350
  req.method = "GET";
299
351
  next("router");
300
352
  } else {
301
- throw new Error("Invalid POST request to /");
353
+ throw new errors.InputError(
354
+ "Invalid POST request to app-backend wildcard endpoint"
355
+ );
302
356
  }
303
357
  }
304
358
  );
@@ -332,7 +386,7 @@ async function createEntryPointRouter({
332
386
  appConfigs
333
387
  }) {
334
388
  const staticDir = path.resolve(rootDir, "static");
335
- const injectedConfigPath = appConfigs && await injectConfig({ appConfigs, logger, staticDir });
389
+ const injectedConfigPath = appConfigs && await injectConfig({ appConfigs, logger, rootDir, staticDir });
336
390
  const router = Router__default.default();
337
391
  const staticRouter = Router__default.default();
338
392
  staticRouter.use(
@@ -379,4 +433,4 @@ async function createEntryPointRouter({
379
433
  }
380
434
 
381
435
  exports.createRouter = createRouter;
382
- //# sourceMappingURL=router-9HkxMeSl.cjs.js.map
436
+ //# sourceMappingURL=router-iVPYMLvA.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router-iVPYMLvA.cjs.js","sources":["../../src/lib/assets/StaticAssetsStore.ts","../../src/lib/assets/findStaticAssets.ts","../../src/lib/headers.ts","../../src/lib/assets/createStaticAssetMiddleware.ts","../../src/lib/config/injectConfigIntoHtml.ts","../../src/lib/config/injectConfigIntoStatic.ts","../../src/lib/config/injectConfig.ts","../../src/lib/config/readFrontendConfig.ts","../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PluginDatabaseManager } from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\nimport {\n LoggerService,\n resolvePackagePath,\n} from '@backstage/backend-plugin-api';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-app-backend',\n 'migrations',\n);\n\ninterface StaticAssetRow {\n path: string;\n content: Buffer;\n namespace: string | null;\n last_modified_at: Date;\n}\n\n/** @internal */\nexport interface StaticAssetsStoreOptions {\n database: PluginDatabaseManager;\n logger: LoggerService;\n}\n\n/**\n * A storage for static assets that are assumed to be immutable.\n *\n * @internal\n */\nexport class StaticAssetsStore implements StaticAssetProvider {\n #db: Knex;\n #logger: LoggerService;\n #namespace: string;\n\n static async create(options: StaticAssetsStoreOptions) {\n const { database } = options;\n const client = await database.getClient();\n\n if (!database.migrations?.skip) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new StaticAssetsStore(client, options.logger);\n }\n\n private constructor(client: Knex, logger: LoggerService, namespace?: string) {\n this.#db = client;\n this.#logger = logger;\n this.#namespace = namespace ?? 'default';\n }\n\n /**\n * Creates a new store with the provided namespace, using the same underlying storage.\n */\n withNamespace(namespace: string): StaticAssetsStore {\n return new StaticAssetsStore(this.#db, this.#logger, namespace);\n }\n\n /**\n * Store the provided assets.\n *\n * If an asset for a given path already exists the modification time will be\n * updated, but the contents will not.\n */\n async storeAssets(assets: StaticAssetInput[]) {\n const existingRows = await this.#db<StaticAssetRow>('static_assets_cache')\n .where('namespace', this.#namespace)\n .whereIn(\n 'path',\n assets.map(a => a.path),\n );\n const existingAssetPaths = new Set(existingRows.map(r => r.path));\n\n const [modified, added] = partition(assets, asset =>\n existingAssetPaths.has(asset.path),\n );\n\n this.#logger.info(\n `Storing ${modified.length} updated assets and ${added.length} new assets`,\n );\n\n await this.#db('static_assets_cache')\n .update({\n last_modified_at: this.#db.fn.now(),\n })\n .where('namespace', this.#namespace)\n .whereIn(\n 'path',\n modified.map(a => a.path),\n );\n\n for (const asset of added) {\n // We ignore conflicts with other nodes, it doesn't matter if someone else\n // added the same asset just before us.\n await this.#db('static_assets_cache')\n .insert({\n path: asset.path,\n content: await asset.content(),\n namespace: this.#namespace,\n })\n .onConflict(['namespace', 'path'])\n .ignore();\n }\n }\n\n /**\n * Retrieve an asset from the store with the given path.\n */\n async getAsset(path: string): Promise<StaticAsset | undefined> {\n const [row] = await this.#db<StaticAssetRow>('static_assets_cache').where({\n path,\n namespace: this.#namespace,\n });\n if (!row) {\n return undefined;\n }\n return {\n path: row.path,\n content: row.content,\n lastModifiedAt:\n typeof row.last_modified_at === 'string'\n ? DateTime.fromSQL(row.last_modified_at, { zone: 'UTC' }).toJSDate()\n : row.last_modified_at,\n };\n }\n\n /**\n * Delete any assets from the store whose modification time is older than the max age.\n */\n async trimAssets(options: { maxAgeSeconds: number }) {\n const { maxAgeSeconds } = options;\n let lastModifiedInterval = this.#db.raw(\n `now() + interval '${-maxAgeSeconds} seconds'`,\n );\n if (this.#db.client.config.client.includes('mysql')) {\n lastModifiedInterval = this.#db.raw(\n `date_sub(now(), interval ${maxAgeSeconds} second)`,\n );\n } else if (this.#db.client.config.client.includes('sqlite3')) {\n lastModifiedInterval = this.#db.raw(`datetime('now', ?)`, [\n `-${maxAgeSeconds} seconds`,\n ]);\n }\n await this.#db<StaticAssetRow>('static_assets_cache')\n .where('namespace', this.#namespace)\n .where('last_modified_at', '<=', lastModifiedInterval)\n .delete();\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport globby from 'globby';\nimport { StaticAssetInput } from './types';\nimport { resolveSafeChildPath } from '@backstage/backend-plugin-api';\n\n/**\n * Finds all static assets within a directory\n *\n * @internal\n */\nexport async function findStaticAssets(\n staticDir: string,\n): Promise<StaticAssetInput[]> {\n const assetPaths = await globby('**/*', {\n ignore: ['**/*.map'], // Ignore source maps since they're quite large\n cwd: staticDir,\n dot: true,\n });\n\n return assetPaths.map(path => ({\n path,\n content: async () => fs.readFile(resolveSafeChildPath(staticDir, path)),\n }));\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const CACHE_CONTROL_NO_CACHE = 'no-store, max-age=0';\nexport const CACHE_CONTROL_MAX_CACHE = 'public, max-age=1209600'; // 14 days\nexport const CACHE_CONTROL_REVALIDATE_CACHE = 'no-cache'; // require revalidating cached responses before reuse them.\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extname } from 'path';\nimport { RequestHandler } from 'express';\nimport { StaticAssetProvider } from './types';\nimport { CACHE_CONTROL_MAX_CACHE } from '../headers';\n\n/**\n * Creates a middleware that serves static assets from a static asset provider\n *\n * @internal\n */\nexport function createStaticAssetMiddleware(\n store: StaticAssetProvider,\n): RequestHandler {\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n\n // Let's not assume we're in promise-router\n Promise.resolve(\n (async () => {\n // Drop leading slashes from the incoming path\n const path = req.path.startsWith('/') ? req.path.slice(1) : req.path;\n\n const asset = await store.getAsset(path);\n if (!asset) {\n next();\n return;\n }\n\n // Set the Content-Type header, falling back to octet-stream\n const ext = extname(asset.path);\n if (ext) {\n res.type(ext);\n } else {\n res.type('bin');\n }\n\n // Same as our express.static override\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n res.setHeader('Last-Modified', asset.lastModifiedAt.toUTCString());\n\n res.send(asset.content);\n })(),\n ).catch(next);\n };\n}\n","/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { InjectOptions } from './types';\nimport compileTemplate from 'lodash/template';\nimport { Config, ConfigReader } from '@backstage/config';\n\nconst HTML_TEMPLATE_NAME = 'index.html.tmpl';\n\n/** @internal */\nexport async function injectConfigIntoHtml(\n options: InjectOptions,\n): Promise<boolean> {\n const { rootDir, appConfigs } = options;\n\n const templatePath = resolvePath(rootDir, HTML_TEMPLATE_NAME);\n\n if (!(await fs.exists(templatePath))) {\n return false;\n }\n\n const templateContent = await fs.readFile(\n resolvePath(rootDir, HTML_TEMPLATE_NAME),\n 'utf8',\n );\n\n const config = ConfigReader.fromConfigs(appConfigs);\n\n const templateSource = compileTemplate(templateContent, {\n interpolate: /<%=([\\s\\S]+?)%>/g,\n });\n\n const publicPath = resolvePublicPath(config);\n const indexHtmlContent = templateSource({\n config,\n publicPath,\n });\n\n const indexHtmlContentWithConfig = indexHtmlContent.replace(\n '</head>',\n `\n<script type=\"backstage.io/config\">\n${JSON.stringify(appConfigs, null, 2)\n // Note on the security aspects of this: We generally trust the app config to\n // be safe, since control of the app config effectively means full control of\n // the app. These substitutions are here as an extra precaution to avoid\n // unintentionally breaking the app, to avoid this being flagged, and in case\n // someone decides to hook up user input to the app config in their own setup.\n .replaceAll('</script', '')\n .replaceAll('<!--', '')}\n</script>\n</head>`,\n );\n\n await fs.writeFile(\n resolvePath(rootDir, 'index.html'),\n indexHtmlContentWithConfig,\n 'utf8',\n );\n\n return true;\n}\n\nexport function resolvePublicPath(config: Config) {\n const baseUrl = new URL(\n config.getOptionalString('app.baseUrl') ?? '/',\n 'http://localhost:7007',\n );\n return baseUrl.pathname.replace(/\\/+$/, '');\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { InjectOptions } from './types';\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n */\nexport async function injectConfigIntoStatic(\n options: InjectOptions,\n): Promise<string | undefined> {\n const { staticDir, logger, appConfigs } = options;\n\n const files = await fs.readdir(staticDir);\n const jsFiles = files.filter(file => file.endsWith('.js'));\n\n const escapedData = JSON.stringify(appConfigs).replace(/(\"|'|\\\\)/g, '\\\\$1');\n const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/\"${escapedData}\"/*__INJECTED_END__*/`;\n\n for (const jsFile of jsFiles) {\n const path = resolvePath(staticDir, jsFile);\n\n const content = await fs.readFile(path, 'utf8');\n if (content.includes('__APP_INJECTED_RUNTIME_CONFIG__')) {\n logger.info(`Injecting env config into ${jsFile}`);\n\n const newContent = content.replaceAll(\n '\"__APP_INJECTED_RUNTIME_CONFIG__\"',\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return path;\n } else if (content.includes('__APP_INJECTED_CONFIG_MARKER__')) {\n logger.info(`Replacing injected env config in ${jsFile}`);\n\n const newContent = content.replaceAll(\n /\\/\\*__APP_INJECTED_CONFIG_MARKER__\\*\\/.*?\\/\\*__INJECTED_END__\\*\\//g,\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return path;\n }\n }\n logger.info('Env config not injected');\n return undefined;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { injectConfigIntoHtml } from './injectConfigIntoHtml';\nimport { injectConfigIntoStatic } from './injectConfigIntoStatic';\nimport { InjectOptions } from './types';\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n * @internal\n */\nexport async function injectConfig(\n options: InjectOptions,\n): Promise<string | undefined> {\n // In order to minimize the potential impact when rolling out the new config\n // injection, we use both methods for a few releases. This allows the frontend\n // app to be behind the backend by a version or two, but temporarily increases\n // config injection overhead.\n // TODO(Rugvip): After the 1.32 release we can stop calling the static injection if the HTML one is successful\n await injectConfigIntoHtml(options);\n\n return injectConfigIntoStatic(options);\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport {\n ConfigSchema,\n loadConfigSchema,\n readEnvConfig,\n} from '@backstage/config-loader';\n\n/**\n * Read config from environment and process the backend config using the\n * schema that is embedded in the frontend build.\n */\nexport async function readFrontendConfig(options: {\n env: { [name: string]: string | undefined };\n appDistDir: string;\n config: Config;\n schema?: ConfigSchema;\n}): Promise<AppConfig[]> {\n const { env, appDistDir, config } = options;\n\n const appConfigs = readEnvConfig(env);\n\n const schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const serializedSchema = await fs.readJson(schemaPath);\n\n try {\n const schema =\n options.schema ||\n (await loadConfigSchema({\n serialized: serializedSchema,\n }));\n\n const frontendConfigs = await schema.process(\n [{ data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'], withDeprecatedKeys: true },\n );\n appConfigs.push(...frontendConfigs);\n } catch (error) {\n throw new Error(\n 'Invalid app bundle schema. If this error is unexpected you need to run `yarn build` in the app. ' +\n `If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. ` +\n `Caused by the following schema error, ${error}`,\n );\n }\n }\n\n return appConfigs;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { notFoundHandler } from '@backstage/backend-common';\nimport {\n DatabaseService,\n resolvePackagePath,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { AppConfig } from '@backstage/config';\nimport helmet from 'helmet';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport {\n createStaticAssetMiddleware,\n findStaticAssets,\n StaticAssetsStore,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n CACHE_CONTROL_REVALIDATE_CACHE,\n} from '../lib/headers';\nimport { ConfigSchema } from '@backstage/config-loader';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { AuthenticationError, InputError } from '@backstage/errors';\nimport { injectConfig, readFrontendConfig } from '../lib/config';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n config: RootConfigService;\n logger: LoggerService;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n\n /**\n * If a database is provided it will be used to cache previously deployed static assets.\n *\n * This is a built-in alternative to using a `staticFallbackHandler`.\n */\n database?: DatabaseService;\n\n /**\n * The name of the app package that content should be served from. The same app package should be\n * added as a dependency to the backend package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package this would be set to 'app'.\n */\n appPackageName: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n\n /**\n *\n * Provides a ConfigSchema.\n *\n */\n schema?: ConfigSchema;\n}\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n config,\n logger,\n appPackageName,\n staticFallbackHandler,\n auth,\n httpAuth,\n schema,\n } = options;\n\n const disableConfigInjection =\n options.disableConfigInjection ??\n config.getOptionalBoolean('app.disableConfigInjection');\n const disableStaticFallbackCache = config.getOptionalBoolean(\n 'app.disableStaticFallbackCache',\n );\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n if (process.env.NODE_ENV === 'production') {\n logger.error(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n }\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n const appConfigs = disableConfigInjection\n ? undefined\n : await readFrontendConfig({\n config,\n appDistDir,\n env: process.env,\n schema,\n });\n\n const assetStore =\n options.database && !disableStaticFallbackCache\n ? await StaticAssetsStore.create({\n logger,\n database: options.database,\n })\n : undefined;\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n const publicDistDir = resolvePath(appDistDir, 'public');\n\n const enablePublicEntryPoint =\n (await fs.pathExists(publicDistDir)) && auth && httpAuth;\n\n if (enablePublicEntryPoint && auth && httpAuth) {\n logger.info(\n `App is running in protected mode, serving public content from ${publicDistDir}`,\n );\n\n const publicRouter = Router();\n\n publicRouter.use(async (req, res, next) => {\n try {\n const credentials = await httpAuth.credentials(req, {\n allow: ['user', 'service', 'none'],\n allowLimitedAccess: true,\n });\n\n if (credentials.principal.type === 'none') {\n next();\n } else {\n next('router');\n }\n } catch {\n // If we fail to authenticate, make sure the session cookie is cleared\n // and continue as unauthenticated. If the user is logged in they will\n // immediately be redirected back to the protected app via the POST.\n await httpAuth.issueUserCookie(res, {\n credentials: await auth.getNoneCredentials(),\n });\n next();\n }\n });\n\n publicRouter.post(\n '*',\n express.urlencoded({ extended: true }),\n async (req, res, next) => {\n if (req.body.type === 'sign-in') {\n const credentials = await auth.authenticate(req.body.token);\n\n if (!auth.isPrincipal(credentials, 'user')) {\n throw new AuthenticationError('Invalid token, not a user');\n }\n\n await httpAuth.issueUserCookie(res, {\n credentials,\n });\n\n // Resume as if it was a GET request towards the outer protected router, serving index.html\n req.method = 'GET';\n next('router');\n } else {\n throw new InputError(\n 'Invalid POST request to app-backend wildcard endpoint',\n );\n }\n },\n );\n\n publicRouter.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'public' }),\n rootDir: publicDistDir,\n assetStore: assetStore?.withNamespace('public'),\n appConfigs, // TODO(Rugvip): We should not be including the full config here\n }),\n );\n\n router.use(publicRouter);\n }\n\n router.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'main' }),\n rootDir: appDistDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n }),\n );\n\n return router;\n}\n\nasync function createEntryPointRouter({\n logger,\n rootDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n}: {\n logger: LoggerService;\n rootDir: string;\n assetStore?: StaticAssetsStore;\n staticFallbackHandler?: express.Handler;\n appConfigs?: AppConfig[];\n}) {\n const staticDir = resolvePath(rootDir, 'static');\n\n const injectedConfigPath =\n appConfigs &&\n (await injectConfig({ appConfigs, logger, rootDir, staticDir }));\n\n const router = Router();\n\n // Use a separate router for static content so that a fallback can be provided by backend\n const staticRouter = Router();\n staticRouter.use(\n express.static(staticDir, {\n setHeaders: (res, path) => {\n if (path === injectedConfigPath) {\n res.setHeader('Cache-Control', CACHE_CONTROL_REVALIDATE_CACHE);\n } else {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n }\n },\n }),\n );\n\n if (assetStore) {\n const assets = await findStaticAssets(staticDir);\n await assetStore.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await assetStore.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(assetStore));\n }\n\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n router.use(\n express.static(rootDir, {\n setHeaders: (res, path) => {\n // The Cache-Control header instructs the browser to not cache html files since it might\n // link to static assets from recently deployed versions.\n if (\n (express.static.mime as unknown as Mime).lookup(path) === 'text/html'\n ) {\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n }\n },\n }),\n );\n\n router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(rootDir, 'index.html'), {\n headers: {\n // The Cache-Control header instructs the browser to not cache the index.html since it might\n // link to static assets from recently deployed versions.\n 'cache-control': CACHE_CONTROL_NO_CACHE,\n },\n });\n });\n\n return router;\n}\n"],"names":["resolvePackagePath","partition","DateTime","globby","fs","resolveSafeChildPath","path","extname","resolvePath","config","ConfigReader","compileTemplate","readEnvConfig","loadConfigSchema","Router","helmet","express","AuthenticationError","InputError","notFoundHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,aAAgB,GAAAA,mCAAA;AAAA,EACpB,+BAAA;AAAA,EACA,YAAA;AACF,CAAA,CAAA;AAoBO,MAAM,iBAAiD,CAAA;AAAA,EAC5D,GAAA,CAAA;AAAA,EACA,OAAA,CAAA;AAAA,EACA,UAAA,CAAA;AAAA,EAEA,aAAa,OAAO,OAAmC,EAAA;AACrD,IAAM,MAAA,EAAE,UAAa,GAAA,OAAA,CAAA;AACrB,IAAM,MAAA,MAAA,GAAS,MAAM,QAAA,CAAS,SAAU,EAAA,CAAA;AAExC,IAAI,IAAA,CAAC,QAAS,CAAA,UAAA,EAAY,IAAM,EAAA;AAC9B,MAAM,MAAA,MAAA,CAAO,QAAQ,MAAO,CAAA;AAAA,QAC1B,SAAW,EAAA,aAAA;AAAA,OACZ,CAAA,CAAA;AAAA,KACH;AAEA,IAAA,OAAO,IAAI,iBAAA,CAAkB,MAAQ,EAAA,OAAA,CAAQ,MAAM,CAAA,CAAA;AAAA,GACrD;A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,CAAA,SAAA,CAAU,iBAAiB,sBAAsB,CAAA,CAAA;AAAA,SACvD;AAAA,OACF;AAAA,KACD,CAAA;AAAA,GACH,CAAA;AAEA,EAAA,MAAA,CAAO,GAAI,CAAA,IAAA,EAAM,CAAC,IAAA,EAAM,GAAQ,KAAA;AAC9B,IAAA,GAAA,CAAI,QAAS,CAAAR,YAAA,CAAY,OAAS,EAAA,YAAY,CAAG,EAAA;AAAA,MAC/C,OAAS,EAAA;AAAA;AAAA;AAAA,QAGP,eAAiB,EAAA,sBAAA;AAAA,OACnB;AAAA,KACD,CAAA,CAAA;AAAA,GACF,CAAA,CAAA;AAED,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
package/dist/index.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var router = require('./cjs/router-9HkxMeSl.cjs.js');
3
+ var router = require('./cjs/router-iVPYMLvA.cjs.js');
4
4
  require('@backstage/backend-common');
5
5
  require('@backstage/backend-plugin-api');
6
6
  require('helmet');
@@ -8,11 +8,13 @@ require('express');
8
8
  require('express-promise-router');
9
9
  require('fs-extra');
10
10
  require('path');
11
- require('@backstage/config-loader');
12
11
  require('luxon');
13
12
  require('lodash/partition');
14
13
  require('globby');
15
14
  require('@backstage/errors');
15
+ require('lodash/template');
16
+ require('@backstage/config');
17
+ require('@backstage/config-loader');
16
18
 
17
19
 
18
20
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-app-backend",
3
- "version": "0.3.74-next.1",
3
+ "version": "0.3.74",
4
4
  "description": "A Backstage backend plugin that serves the Backstage frontend app",
5
5
  "backstage": {
6
6
  "role": "backend-plugin",
@@ -56,13 +56,13 @@
56
56
  "test": "backstage-cli package test"
57
57
  },
58
58
  "dependencies": {
59
- "@backstage/backend-common": "^0.25.0-next.1",
60
- "@backstage/backend-plugin-api": "^0.9.0-next.1",
59
+ "@backstage/backend-common": "^0.25.0",
60
+ "@backstage/backend-plugin-api": "^1.0.0",
61
61
  "@backstage/config": "^1.2.0",
62
- "@backstage/config-loader": "^1.9.0",
62
+ "@backstage/config-loader": "^1.9.1",
63
63
  "@backstage/errors": "^1.2.4",
64
- "@backstage/plugin-app-node": "^0.1.25-next.1",
65
- "@backstage/plugin-auth-node": "^0.5.2-next.1",
64
+ "@backstage/plugin-app-node": "^0.1.25",
65
+ "@backstage/plugin-auth-node": "^0.5.2",
66
66
  "@backstage/types": "^1.1.1",
67
67
  "@types/express": "^4.17.6",
68
68
  "express": "^4.17.1",
@@ -76,14 +76,14 @@
76
76
  "yn": "^4.0.0"
77
77
  },
78
78
  "devDependencies": {
79
- "@backstage/backend-app-api": "^0.10.0-next.1",
80
- "@backstage/backend-defaults": "^0.5.0-next.1",
81
- "@backstage/backend-test-utils": "^0.6.0-next.1",
82
- "@backstage/cli": "^0.27.1-next.1",
79
+ "@backstage/backend-app-api": "^1.0.0",
80
+ "@backstage/backend-defaults": "^0.5.0",
81
+ "@backstage/backend-test-utils": "^1.0.0",
82
+ "@backstage/cli": "^0.27.1",
83
83
  "@backstage/types": "^1.1.1",
84
84
  "@types/supertest": "^2.0.8",
85
85
  "node-fetch": "^2.7.0",
86
- "supertest": "^6.1.3"
86
+ "supertest": "^7.0.0"
87
87
  },
88
88
  "configSchema": "config.d.ts"
89
89
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"router-9HkxMeSl.cjs.js","sources":["../../src/lib/config.ts","../../src/lib/assets/StaticAssetsStore.ts","../../src/lib/assets/findStaticAssets.ts","../../src/lib/headers.ts","../../src/lib/assets/createStaticAssetMiddleware.ts","../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport {\n ConfigSchema,\n loadConfigSchema,\n readEnvConfig,\n} from '@backstage/config-loader';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: LoggerService;\n};\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n */\nexport async function injectConfig(\n options: InjectOptions,\n): Promise<string | undefined> {\n const { staticDir, logger, appConfigs } = options;\n\n const files = await fs.readdir(staticDir);\n const jsFiles = files.filter(file => file.endsWith('.js'));\n\n const escapedData = JSON.stringify(appConfigs).replace(/(\"|'|\\\\)/g, '\\\\$1');\n const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/\"${escapedData}\"/*__INJECTED_END__*/`;\n\n for (const jsFile of jsFiles) {\n const path = resolvePath(staticDir, jsFile);\n\n const content = await fs.readFile(path, 'utf8');\n if (content.includes('__APP_INJECTED_RUNTIME_CONFIG__')) {\n logger.info(`Injecting env config into ${jsFile}`);\n\n const newContent = content.replaceAll(\n '\"__APP_INJECTED_RUNTIME_CONFIG__\"',\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return path;\n } else if (content.includes('__APP_INJECTED_CONFIG_MARKER__')) {\n logger.info(`Replacing injected env config in ${jsFile}`);\n\n const newContent = content.replaceAll(\n /\\/\\*__APP_INJECTED_CONFIG_MARKER__\\*\\/.*?\\/\\*__INJECTED_END__\\*\\//g,\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return path;\n }\n }\n logger.info('Env config not injected');\n return undefined;\n}\n\ntype ReadOptions = {\n env: { [name: string]: string | undefined };\n appDistDir: string;\n config: Config;\n schema?: ConfigSchema;\n};\n\n/**\n * Read config from environment and process the backend config using the\n * schema that is embedded in the frontend build.\n */\nexport async function readConfigs(options: ReadOptions): Promise<AppConfig[]> {\n const { env, appDistDir, config } = options;\n\n const appConfigs = readEnvConfig(env);\n\n const schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const serializedSchema = await fs.readJson(schemaPath);\n\n try {\n const schema =\n options.schema ||\n (await loadConfigSchema({\n serialized: serializedSchema,\n }));\n\n const frontendConfigs = await schema.process(\n [{ data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'], withDeprecatedKeys: true },\n );\n appConfigs.push(...frontendConfigs);\n } catch (error) {\n throw new Error(\n 'Invalid app bundle schema. If this error is unexpected you need to run `yarn build` in the app. ' +\n `If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. ` +\n `Caused by the following schema error, ${error}`,\n );\n }\n }\n\n return appConfigs;\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PluginDatabaseManager } from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\nimport {\n LoggerService,\n resolvePackagePath,\n} from '@backstage/backend-plugin-api';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-app-backend',\n 'migrations',\n);\n\ninterface StaticAssetRow {\n path: string;\n content: Buffer;\n namespace: string | null;\n last_modified_at: Date;\n}\n\n/** @internal */\nexport interface StaticAssetsStoreOptions {\n database: PluginDatabaseManager;\n logger: LoggerService;\n}\n\n/**\n * A storage for static assets that are assumed to be immutable.\n *\n * @internal\n */\nexport class StaticAssetsStore implements StaticAssetProvider {\n #db: Knex;\n #logger: LoggerService;\n #namespace: string;\n\n static async create(options: StaticAssetsStoreOptions) {\n const { database } = options;\n const client = await database.getClient();\n\n if (!database.migrations?.skip) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new StaticAssetsStore(client, options.logger);\n }\n\n private constructor(client: Knex, logger: LoggerService, namespace?: string) {\n this.#db = client;\n this.#logger = logger;\n this.#namespace = namespace ?? 'default';\n }\n\n /**\n * Creates a new store with the provided namespace, using the same underlying storage.\n */\n withNamespace(namespace: string): StaticAssetsStore {\n return new StaticAssetsStore(this.#db, this.#logger, namespace);\n }\n\n /**\n * Store the provided assets.\n *\n * If an asset for a given path already exists the modification time will be\n * updated, but the contents will not.\n */\n async storeAssets(assets: StaticAssetInput[]) {\n const existingRows = await this.#db<StaticAssetRow>('static_assets_cache')\n .where('namespace', this.#namespace)\n .whereIn(\n 'path',\n assets.map(a => a.path),\n );\n const existingAssetPaths = new Set(existingRows.map(r => r.path));\n\n const [modified, added] = partition(assets, asset =>\n existingAssetPaths.has(asset.path),\n );\n\n this.#logger.info(\n `Storing ${modified.length} updated assets and ${added.length} new assets`,\n );\n\n await this.#db('static_assets_cache')\n .update({\n last_modified_at: this.#db.fn.now(),\n })\n .where('namespace', this.#namespace)\n .whereIn(\n 'path',\n modified.map(a => a.path),\n );\n\n for (const asset of added) {\n // We ignore conflicts with other nodes, it doesn't matter if someone else\n // added the same asset just before us.\n await this.#db('static_assets_cache')\n .insert({\n path: asset.path,\n content: await asset.content(),\n namespace: this.#namespace,\n })\n .onConflict(['namespace', 'path'])\n .ignore();\n }\n }\n\n /**\n * Retrieve an asset from the store with the given path.\n */\n async getAsset(path: string): Promise<StaticAsset | undefined> {\n const [row] = await this.#db<StaticAssetRow>('static_assets_cache').where({\n path,\n namespace: this.#namespace,\n });\n if (!row) {\n return undefined;\n }\n return {\n path: row.path,\n content: row.content,\n lastModifiedAt:\n typeof row.last_modified_at === 'string'\n ? DateTime.fromSQL(row.last_modified_at, { zone: 'UTC' }).toJSDate()\n : row.last_modified_at,\n };\n }\n\n /**\n * Delete any assets from the store whose modification time is older than the max age.\n */\n async trimAssets(options: { maxAgeSeconds: number }) {\n const { maxAgeSeconds } = options;\n let lastModifiedInterval = this.#db.raw(\n `now() + interval '${-maxAgeSeconds} seconds'`,\n );\n if (this.#db.client.config.client.includes('mysql')) {\n lastModifiedInterval = this.#db.raw(\n `date_sub(now(), interval ${maxAgeSeconds} second)`,\n );\n } else if (this.#db.client.config.client.includes('sqlite3')) {\n lastModifiedInterval = this.#db.raw(`datetime('now', ?)`, [\n `-${maxAgeSeconds} seconds`,\n ]);\n }\n await this.#db<StaticAssetRow>('static_assets_cache')\n .where('namespace', this.#namespace)\n .where('last_modified_at', '<=', lastModifiedInterval)\n .delete();\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport globby from 'globby';\nimport { StaticAssetInput } from './types';\nimport { resolveSafeChildPath } from '@backstage/backend-plugin-api';\n\n/**\n * Finds all static assets within a directory\n *\n * @internal\n */\nexport async function findStaticAssets(\n staticDir: string,\n): Promise<StaticAssetInput[]> {\n const assetPaths = await globby('**/*', {\n ignore: ['**/*.map'], // Ignore source maps since they're quite large\n cwd: staticDir,\n dot: true,\n });\n\n return assetPaths.map(path => ({\n path,\n content: async () => fs.readFile(resolveSafeChildPath(staticDir, path)),\n }));\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const CACHE_CONTROL_NO_CACHE = 'no-store, max-age=0';\nexport const CACHE_CONTROL_MAX_CACHE = 'public, max-age=1209600'; // 14 days\nexport const CACHE_CONTROL_REVALIDATE_CACHE = 'no-cache'; // require revalidating cached responses before reuse them.\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extname } from 'path';\nimport { RequestHandler } from 'express';\nimport { StaticAssetProvider } from './types';\nimport { CACHE_CONTROL_MAX_CACHE } from '../headers';\n\n/**\n * Creates a middleware that serves static assets from a static asset provider\n *\n * @internal\n */\nexport function createStaticAssetMiddleware(\n store: StaticAssetProvider,\n): RequestHandler {\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n\n // Let's not assume we're in promise-router\n Promise.resolve(\n (async () => {\n // Drop leading slashes from the incoming path\n const path = req.path.startsWith('/') ? req.path.slice(1) : req.path;\n\n const asset = await store.getAsset(path);\n if (!asset) {\n next();\n return;\n }\n\n // Set the Content-Type header, falling back to octet-stream\n const ext = extname(asset.path);\n if (ext) {\n res.type(ext);\n } else {\n res.type('bin');\n }\n\n // Same as our express.static override\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n res.setHeader('Last-Modified', asset.lastModifiedAt.toUTCString());\n\n res.send(asset.content);\n })(),\n ).catch(next);\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { notFoundHandler } from '@backstage/backend-common';\nimport {\n DatabaseService,\n resolvePackagePath,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { AppConfig } from '@backstage/config';\nimport helmet from 'helmet';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { injectConfig, readConfigs } from '../lib/config';\nimport {\n createStaticAssetMiddleware,\n findStaticAssets,\n StaticAssetsStore,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n CACHE_CONTROL_REVALIDATE_CACHE,\n} from '../lib/headers';\nimport { ConfigSchema } from '@backstage/config-loader';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { AuthenticationError } from '@backstage/errors';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n config: RootConfigService;\n logger: LoggerService;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n\n /**\n * If a database is provided it will be used to cache previously deployed static assets.\n *\n * This is a built-in alternative to using a `staticFallbackHandler`.\n */\n database?: DatabaseService;\n\n /**\n * The name of the app package that content should be served from. The same app package should be\n * added as a dependency to the backend package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package this would be set to 'app'.\n */\n appPackageName: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n\n /**\n *\n * Provides a ConfigSchema.\n *\n */\n schema?: ConfigSchema;\n}\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n config,\n logger,\n appPackageName,\n staticFallbackHandler,\n auth,\n httpAuth,\n schema,\n } = options;\n\n const disableConfigInjection =\n options.disableConfigInjection ??\n config.getOptionalBoolean('app.disableConfigInjection');\n const disableStaticFallbackCache = config.getOptionalBoolean(\n 'app.disableStaticFallbackCache',\n );\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n if (process.env.NODE_ENV === 'production') {\n logger.error(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n }\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n const appConfigs = disableConfigInjection\n ? undefined\n : await readConfigs({\n config,\n appDistDir,\n env: process.env,\n schema,\n });\n\n const assetStore =\n options.database && !disableStaticFallbackCache\n ? await StaticAssetsStore.create({\n logger,\n database: options.database,\n })\n : undefined;\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n const publicDistDir = resolvePath(appDistDir, 'public');\n\n const enablePublicEntryPoint =\n (await fs.pathExists(publicDistDir)) && auth && httpAuth;\n\n if (enablePublicEntryPoint && auth && httpAuth) {\n logger.info(\n `App is running in protected mode, serving public content from ${publicDistDir}`,\n );\n\n const publicRouter = Router();\n\n publicRouter.use(async (req, res, next) => {\n try {\n const credentials = await httpAuth.credentials(req, {\n allow: ['user', 'service', 'none'],\n allowLimitedAccess: true,\n });\n\n if (credentials.principal.type === 'none') {\n next();\n } else {\n next('router');\n }\n } catch {\n // If we fail to authenticate, make sure the session cookie is cleared\n // and continue as unauthenticated. If the user is logged in they will\n // immediately be redirected back to the protected app via the POST.\n await httpAuth.issueUserCookie(res, {\n credentials: await auth.getNoneCredentials(),\n });\n next();\n }\n });\n\n publicRouter.post(\n '*',\n express.urlencoded({ extended: true }),\n async (req, res, next) => {\n if (req.body.type === 'sign-in') {\n const credentials = await auth.authenticate(req.body.token);\n\n if (!auth.isPrincipal(credentials, 'user')) {\n throw new AuthenticationError('Invalid token, not a user');\n }\n\n await httpAuth.issueUserCookie(res, {\n credentials,\n });\n\n // Resume as if it was a GET request towards the outer protected router, serving index.html\n req.method = 'GET';\n next('router');\n } else {\n throw new Error('Invalid POST request to /');\n }\n },\n );\n\n publicRouter.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'public' }),\n rootDir: publicDistDir,\n assetStore: assetStore?.withNamespace('public'),\n appConfigs, // TODO(Rugvip): We should not be including the full config here\n }),\n );\n\n router.use(publicRouter);\n }\n\n router.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'main' }),\n rootDir: appDistDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n }),\n );\n\n return router;\n}\n\nasync function createEntryPointRouter({\n logger,\n rootDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n}: {\n logger: LoggerService;\n rootDir: string;\n assetStore?: StaticAssetsStore;\n staticFallbackHandler?: express.Handler;\n appConfigs?: AppConfig[];\n}) {\n const staticDir = resolvePath(rootDir, 'static');\n\n const injectedConfigPath =\n appConfigs && (await injectConfig({ appConfigs, logger, staticDir }));\n\n const router = Router();\n\n // Use a separate router for static content so that a fallback can be provided by backend\n const staticRouter = Router();\n staticRouter.use(\n express.static(staticDir, {\n setHeaders: (res, path) => {\n if (path === injectedConfigPath) {\n res.setHeader('Cache-Control', CACHE_CONTROL_REVALIDATE_CACHE);\n } else {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n }\n },\n }),\n );\n\n if (assetStore) {\n const assets = await findStaticAssets(staticDir);\n await assetStore.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await assetStore.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(assetStore));\n }\n\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n router.use(\n express.static(rootDir, {\n setHeaders: (res, path) => {\n // The Cache-Control header instructs the browser to not cache html files since it might\n // link to static assets from recently deployed versions.\n if (\n (express.static.mime as unknown as Mime).lookup(path) === 'text/html'\n ) {\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n }\n },\n }),\n );\n\n router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(rootDir, 'index.html'), {\n headers: {\n // The Cache-Control header instructs the browser to not cache the index.html since it might\n // link to static assets from recently deployed versions.\n 'cache-control': CACHE_CONTROL_NO_CACHE,\n },\n });\n });\n\n return router;\n}\n"],"names":["fs","path","resolvePath","readEnvConfig","loadConfigSchema","resolvePackagePath","partition","DateTime","globby","resolveSafeChildPath","extname","Router","helmet","express","AuthenticationError","notFoundHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqCA,eAAsB,aACpB,OAC6B,EAAA;AAC7B,EAAA,MAAM,EAAE,SAAA,EAAW,MAAQ,EAAA,UAAA,EAAe,GAAA,OAAA,CAAA;AAE1C,EAAA,MAAM,KAAQ,GAAA,MAAMA,mBAAG,CAAA,OAAA,CAAQ,SAAS,CAAA,CAAA;AACxC,EAAA,MAAM,UAAU,KAAM,CAAA,MAAA,CAAO,UAAQ,IAAK,CAAA,QAAA,CAAS,KAAK,CAAC,CAAA,CAAA;AAEzD,EAAA,MAAM,cAAc,IAAK,CAAA,SAAA,CAAU,UAAU,CAAE,CAAA,OAAA,CAAQ,aAAa,MAAM,CAAA,CAAA;AAC1E,EAAM,MAAA,QAAA,GAAW,sCAAsC,WAAW,CAAA,qBAAA,CAAA,CAAA;AAElE,EAAA,KAAA,MAAW,UAAU,OAAS,EAAA;AAC5B,IAAM,MAAAC,MAAA,GAAOC,YAAY,CAAA,SAAA,EAAW,MAAM,CAAA,CAAA;AAE1C,IAAA,MAAM,OAAU,GAAA,MAAMF,mBAAG,CAAA,QAAA,CAASC,QAAM,MAAM,CAAA,CAAA;AAC9C,IAAI,IAAA,OAAA,CAAQ,QAAS,CAAA,iCAAiC,CAAG,EAAA;AACvD,MAAO,MAAA,CAAA,IAAA,CAAK,CAA6B,0BAAA,EAAA,MAAM,CAAE,CAAA,CAAA,CAAA;AAEjD,MAAA,MAAM,aAAa,OAAQ,CAAA,UAAA;AAAA,QACzB,mCAAA;AAAA,QACA,QAAA;AAAA,OACF,CAAA;AACA,MAAA,MAAMD,mBAAG,CAAA,SAAA,CAAUC,MAAM,EAAA,UAAA,EAAY,MAAM,CAAA,CAAA;AAC3C,MAAO,OAAAA,MAAA,CAAA;AAAA,KACE,MAAA,IAAA,OAAA,CAAQ,QAAS,CAAA,gCAAgC,CAAG,EAA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