@backstage/plugin-app-backend 0.3.64 → 0.3.65-next.1
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 +27 -0
- package/alpha/package.json +1 -1
- package/dist/alpha.cjs.js +8 -3
- package/dist/alpha.cjs.js.map +1 -1
- package/dist/cjs/{router-DVSRooks.cjs.js → router-BpjcQ_K5.cjs.js} +138 -29
- package/dist/cjs/router-BpjcQ_K5.cjs.js.map +1 -0
- package/dist/index.cjs.js +2 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/migrations/20240113144027_assets-namespace.js +38 -0
- package/package.json +10 -8
- package/dist/cjs/router-DVSRooks.cjs.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# @backstage/plugin-app-backend
|
|
2
2
|
|
|
3
|
+
## 0.3.65-next.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c884b9a: Track assets namespace in the cache store, implement a cookie authentication for when the public entry is enabled and used with the new auth services.
|
|
8
|
+
- Updated dependencies
|
|
9
|
+
- @backstage/backend-common@0.21.7-next.1
|
|
10
|
+
- @backstage/backend-plugin-api@0.6.17-next.1
|
|
11
|
+
- @backstage/plugin-auth-node@0.4.12-next.1
|
|
12
|
+
- @backstage/config@1.2.0
|
|
13
|
+
- @backstage/config-loader@1.8.0-next.0
|
|
14
|
+
- @backstage/errors@1.2.4
|
|
15
|
+
- @backstage/types@1.1.1
|
|
16
|
+
- @backstage/plugin-app-node@0.1.17-next.1
|
|
17
|
+
|
|
18
|
+
## 0.3.65-next.0
|
|
19
|
+
|
|
20
|
+
### Patch Changes
|
|
21
|
+
|
|
22
|
+
- Updated dependencies
|
|
23
|
+
- @backstage/backend-common@0.21.7-next.0
|
|
24
|
+
- @backstage/config-loader@1.8.0-next.0
|
|
25
|
+
- @backstage/backend-plugin-api@0.6.17-next.0
|
|
26
|
+
- @backstage/config@1.2.0
|
|
27
|
+
- @backstage/types@1.1.1
|
|
28
|
+
- @backstage/plugin-app-node@0.1.17-next.0
|
|
29
|
+
|
|
3
30
|
## 0.3.64
|
|
4
31
|
|
|
5
32
|
### Patch Changes
|
package/alpha/package.json
CHANGED
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-
|
|
6
|
+
var router = require('./cjs/router-BpjcQ_K5.cjs.js');
|
|
7
7
|
var backendCommon = require('@backstage/backend-common');
|
|
8
8
|
var pluginAppNode = require('@backstage/plugin-app-node');
|
|
9
9
|
require('helmet');
|
|
@@ -15,6 +15,7 @@ require('@backstage/config-loader');
|
|
|
15
15
|
require('luxon');
|
|
16
16
|
require('lodash/partition');
|
|
17
17
|
require('globby');
|
|
18
|
+
require('@backstage/errors');
|
|
18
19
|
|
|
19
20
|
const appPlugin = backendPluginApi.createBackendPlugin({
|
|
20
21
|
pluginId: "app",
|
|
@@ -46,9 +47,11 @@ const appPlugin = backendPluginApi.createBackendPlugin({
|
|
|
46
47
|
logger: backendPluginApi.coreServices.logger,
|
|
47
48
|
config: backendPluginApi.coreServices.rootConfig,
|
|
48
49
|
database: backendPluginApi.coreServices.database,
|
|
49
|
-
httpRouter: backendPluginApi.coreServices.httpRouter
|
|
50
|
+
httpRouter: backendPluginApi.coreServices.httpRouter,
|
|
51
|
+
auth: backendPluginApi.coreServices.auth,
|
|
52
|
+
httpAuth: backendPluginApi.coreServices.httpAuth
|
|
50
53
|
},
|
|
51
|
-
async init({ logger, config, database, httpRouter }) {
|
|
54
|
+
async init({ logger, config, database, httpRouter, auth, httpAuth }) {
|
|
52
55
|
var _a;
|
|
53
56
|
const appPackageName = (_a = config.getOptionalString("app.packageName")) != null ? _a : "app";
|
|
54
57
|
const winstonLogger = backendCommon.loggerToWinstonLogger(logger);
|
|
@@ -56,6 +59,8 @@ const appPlugin = backendPluginApi.createBackendPlugin({
|
|
|
56
59
|
logger: winstonLogger,
|
|
57
60
|
config,
|
|
58
61
|
database,
|
|
62
|
+
auth,
|
|
63
|
+
httpAuth,
|
|
59
64
|
appPackageName,
|
|
60
65
|
staticFallbackHandler,
|
|
61
66
|
schema
|
package/dist/alpha.cjs.js.map
CHANGED
|
@@ -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 { loggerToWinstonLogger } from '@backstage/backend-common';\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 },\n async init({ logger, config, database, httpRouter }) {\n const appPackageName =\n config.getOptionalString('app.packageName') ?? 'app';\n\n const winstonLogger = loggerToWinstonLogger(logger);\n\n const router = await createRouter({\n logger: winstonLogger,\n config,\n database,\n appPackageName,\n staticFallbackHandler,\n schema,\n });\n httpRouter.use(router);\n httpRouter.addAuthPolicy({\n allow: 'unauthenticated',\n path: '/',\n });\n },\n });\n },\n});\n"],"names":["createBackendPlugin","staticFallbackHandlerExtensionPoint","configSchemaExtensionPoint","coreServices","loggerToWinstonLogger","router","createRouter"],"mappings":"
|
|
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 { loggerToWinstonLogger } from '@backstage/backend-common';\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 winstonLogger = loggerToWinstonLogger(logger);\n\n const router = await createRouter({\n logger: winstonLogger,\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","loggerToWinstonLogger","router","createRouter"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCO,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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AA,UACP,IAAM,EAAA,GAAA;AAAA,SACP,CAAA,CAAA;AAAA,OACH;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;"}
|
|
@@ -10,6 +10,7 @@ var configLoader = require('@backstage/config-loader');
|
|
|
10
10
|
var luxon = require('luxon');
|
|
11
11
|
var partition = require('lodash/partition');
|
|
12
12
|
var globby = require('globby');
|
|
13
|
+
var errors = require('@backstage/errors');
|
|
13
14
|
|
|
14
15
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
15
16
|
|
|
@@ -92,17 +93,19 @@ var __privateSet = (obj, member, value, setter) => {
|
|
|
92
93
|
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
93
94
|
return value;
|
|
94
95
|
};
|
|
95
|
-
var _db, _logger;
|
|
96
|
+
var _db, _logger, _namespace;
|
|
96
97
|
const migrationsDir = backendCommon.resolvePackagePath(
|
|
97
98
|
"@backstage/plugin-app-backend",
|
|
98
99
|
"migrations"
|
|
99
100
|
);
|
|
100
101
|
const _StaticAssetsStore = class _StaticAssetsStore {
|
|
101
|
-
constructor(client, logger) {
|
|
102
|
+
constructor(client, logger, namespace) {
|
|
102
103
|
__privateAdd(this, _db, void 0);
|
|
103
104
|
__privateAdd(this, _logger, void 0);
|
|
105
|
+
__privateAdd(this, _namespace, void 0);
|
|
104
106
|
__privateSet(this, _db, client);
|
|
105
107
|
__privateSet(this, _logger, logger);
|
|
108
|
+
__privateSet(this, _namespace, namespace != null ? namespace : null);
|
|
106
109
|
}
|
|
107
110
|
static async create(options) {
|
|
108
111
|
var _a;
|
|
@@ -115,6 +118,12 @@ const _StaticAssetsStore = class _StaticAssetsStore {
|
|
|
115
118
|
}
|
|
116
119
|
return new _StaticAssetsStore(client, options.logger);
|
|
117
120
|
}
|
|
121
|
+
/**
|
|
122
|
+
* Creates a new store with the provided namespace, using the same underlying storage.
|
|
123
|
+
*/
|
|
124
|
+
withNamespace(namespace) {
|
|
125
|
+
return new _StaticAssetsStore(__privateGet(this, _db), __privateGet(this, _logger), namespace);
|
|
126
|
+
}
|
|
118
127
|
/**
|
|
119
128
|
* Store the provided assets.
|
|
120
129
|
*
|
|
@@ -122,7 +131,7 @@ const _StaticAssetsStore = class _StaticAssetsStore {
|
|
|
122
131
|
* updated, but the contents will not.
|
|
123
132
|
*/
|
|
124
133
|
async storeAssets(assets) {
|
|
125
|
-
const existingRows = await __privateGet(this, _db).call(this, "static_assets_cache").whereIn(
|
|
134
|
+
const existingRows = await __privateGet(this, _db).call(this, "static_assets_cache").where("namespace", __privateGet(this, _namespace)).whereIn(
|
|
126
135
|
"path",
|
|
127
136
|
assets.map((a) => a.path)
|
|
128
137
|
);
|
|
@@ -136,14 +145,15 @@ const _StaticAssetsStore = class _StaticAssetsStore {
|
|
|
136
145
|
);
|
|
137
146
|
await __privateGet(this, _db).call(this, "static_assets_cache").update({
|
|
138
147
|
last_modified_at: __privateGet(this, _db).fn.now()
|
|
139
|
-
}).whereIn(
|
|
148
|
+
}).where("namespace", __privateGet(this, _namespace)).whereIn(
|
|
140
149
|
"path",
|
|
141
150
|
modified.map((a) => a.path)
|
|
142
151
|
);
|
|
143
152
|
for (const asset of added) {
|
|
144
153
|
await __privateGet(this, _db).call(this, "static_assets_cache").insert({
|
|
145
154
|
path: asset.path,
|
|
146
|
-
content: await asset.content()
|
|
155
|
+
content: await asset.content(),
|
|
156
|
+
namespace: __privateGet(this, _namespace)
|
|
147
157
|
}).onConflict("path").ignore();
|
|
148
158
|
}
|
|
149
159
|
}
|
|
@@ -152,7 +162,8 @@ const _StaticAssetsStore = class _StaticAssetsStore {
|
|
|
152
162
|
*/
|
|
153
163
|
async getAsset(path) {
|
|
154
164
|
const [row] = await __privateGet(this, _db).call(this, "static_assets_cache").where({
|
|
155
|
-
path
|
|
165
|
+
path,
|
|
166
|
+
namespace: __privateGet(this, _namespace)
|
|
156
167
|
});
|
|
157
168
|
if (!row) {
|
|
158
169
|
return void 0;
|
|
@@ -180,11 +191,12 @@ const _StaticAssetsStore = class _StaticAssetsStore {
|
|
|
180
191
|
`-${maxAgeSeconds} seconds`
|
|
181
192
|
]);
|
|
182
193
|
}
|
|
183
|
-
await __privateGet(this, _db).call(this, "static_assets_cache").where("last_modified_at", "<=", lastModifiedInterval).delete();
|
|
194
|
+
await __privateGet(this, _db).call(this, "static_assets_cache").where("namespace", __privateGet(this, _namespace)).where("last_modified_at", "<=", lastModifiedInterval).delete();
|
|
184
195
|
}
|
|
185
196
|
};
|
|
186
197
|
_db = new WeakMap();
|
|
187
198
|
_logger = new WeakMap();
|
|
199
|
+
_namespace = new WeakMap();
|
|
188
200
|
let StaticAssetsStore = _StaticAssetsStore;
|
|
189
201
|
|
|
190
202
|
async function findStaticAssets(staticDir) {
|
|
@@ -234,7 +246,14 @@ function createStaticAssetMiddleware(store) {
|
|
|
234
246
|
|
|
235
247
|
async function createRouter(options) {
|
|
236
248
|
var _a;
|
|
237
|
-
const {
|
|
249
|
+
const {
|
|
250
|
+
config,
|
|
251
|
+
logger,
|
|
252
|
+
appPackageName,
|
|
253
|
+
staticFallbackHandler,
|
|
254
|
+
auth,
|
|
255
|
+
httpAuth
|
|
256
|
+
} = options;
|
|
238
257
|
const disableConfigInjection = (_a = options.disableConfigInjection) != null ? _a : config.getOptionalBoolean("app.disableConfigInjection");
|
|
239
258
|
const disableStaticFallbackCache = config.getOptionalBoolean(
|
|
240
259
|
"app.disableStaticFallbackCache"
|
|
@@ -250,21 +269,115 @@ async function createRouter(options) {
|
|
|
250
269
|
return Router__default.default();
|
|
251
270
|
}
|
|
252
271
|
logger.info(`Serving static app content from ${appDistDir}`);
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
272
|
+
const appConfigs = disableConfigInjection ? void 0 : await readConfigs({
|
|
273
|
+
config,
|
|
274
|
+
appDistDir,
|
|
275
|
+
env: process.env
|
|
276
|
+
});
|
|
277
|
+
const assetStore = options.database && !disableStaticFallbackCache ? await StaticAssetsStore.create({
|
|
278
|
+
logger,
|
|
279
|
+
database: options.database
|
|
280
|
+
}) : void 0;
|
|
281
|
+
const router = Router__default.default();
|
|
282
|
+
router.use(helmet__default.default.frameguard({ action: "deny" }));
|
|
283
|
+
const publicDistDir = path.resolve(appDistDir, "public");
|
|
284
|
+
const enablePublicEntryPoint = await fs__default.default.pathExists(publicDistDir) && auth && httpAuth;
|
|
285
|
+
if (enablePublicEntryPoint && auth && httpAuth) {
|
|
286
|
+
logger.info(
|
|
287
|
+
`App is running in protected mode, serving public content from ${publicDistDir}`
|
|
288
|
+
);
|
|
289
|
+
const publicRouter = Router__default.default();
|
|
290
|
+
publicRouter.use(async (req, res, next) => {
|
|
291
|
+
try {
|
|
292
|
+
const credentials = await httpAuth.credentials(req, {
|
|
293
|
+
allow: ["user", "service", "none"],
|
|
294
|
+
allowLimitedAccess: true
|
|
295
|
+
});
|
|
296
|
+
if (credentials.principal.type === "none") {
|
|
297
|
+
next();
|
|
298
|
+
} else {
|
|
299
|
+
next("router");
|
|
300
|
+
}
|
|
301
|
+
} catch {
|
|
302
|
+
await httpAuth.issueUserCookie(res, {
|
|
303
|
+
credentials: await auth.getNoneCredentials()
|
|
304
|
+
});
|
|
305
|
+
next();
|
|
306
|
+
}
|
|
260
307
|
});
|
|
261
|
-
|
|
308
|
+
publicRouter.post(
|
|
309
|
+
"*",
|
|
310
|
+
express__default.default.urlencoded({ extended: true }),
|
|
311
|
+
async (req, res, next) => {
|
|
312
|
+
if (req.body.type === "sign-in") {
|
|
313
|
+
const credentials = await auth.authenticate(req.body.token);
|
|
314
|
+
if (!auth.isPrincipal(credentials, "user")) {
|
|
315
|
+
throw new errors.AuthenticationError("Invalid token, not a user");
|
|
316
|
+
}
|
|
317
|
+
await httpAuth.issueUserCookie(res, {
|
|
318
|
+
credentials
|
|
319
|
+
});
|
|
320
|
+
req.method = "GET";
|
|
321
|
+
next("router");
|
|
322
|
+
} else {
|
|
323
|
+
throw new Error("Invalid POST request to /");
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
);
|
|
327
|
+
publicRouter.use(
|
|
328
|
+
await createEntryPointRouter({
|
|
329
|
+
appMode: "public",
|
|
330
|
+
logger: logger.child({ entry: "public" }),
|
|
331
|
+
rootDir: publicDistDir,
|
|
332
|
+
assetStore: assetStore == null ? void 0 : assetStore.withNamespace("public"),
|
|
333
|
+
appConfigs
|
|
334
|
+
// TODO(Rugvip): We should not be including the full config here
|
|
335
|
+
})
|
|
336
|
+
);
|
|
337
|
+
router.use(publicRouter);
|
|
262
338
|
}
|
|
339
|
+
router.use(
|
|
340
|
+
await createEntryPointRouter({
|
|
341
|
+
appMode: enablePublicEntryPoint ? "protected" : "public",
|
|
342
|
+
logger: logger.child({ entry: "main" }),
|
|
343
|
+
rootDir: appDistDir,
|
|
344
|
+
assetStore,
|
|
345
|
+
staticFallbackHandler,
|
|
346
|
+
appConfigs
|
|
347
|
+
})
|
|
348
|
+
);
|
|
349
|
+
return router;
|
|
350
|
+
}
|
|
351
|
+
async function injectAppMode(options) {
|
|
352
|
+
const { appMode, rootDir } = options;
|
|
353
|
+
const content = await fs__default.default.readFile(path.resolve(rootDir, "index.html"), "utf8");
|
|
354
|
+
const metaTag = `<meta name="backstage-app-mode" content="${appMode}">`;
|
|
355
|
+
let newContent;
|
|
356
|
+
if (content.includes("backstage-app-mode")) {
|
|
357
|
+
newContent = content.replace(
|
|
358
|
+
/<meta name="backstage-app-mode" content="[^"]+">/,
|
|
359
|
+
metaTag
|
|
360
|
+
);
|
|
361
|
+
} else {
|
|
362
|
+
newContent = content.replace(/<head>/, `<head>${metaTag}`);
|
|
363
|
+
}
|
|
364
|
+
await fs__default.default.writeFile(path.resolve(rootDir, "index.html"), newContent, "utf8");
|
|
365
|
+
}
|
|
366
|
+
async function createEntryPointRouter({
|
|
367
|
+
logger,
|
|
368
|
+
rootDir,
|
|
369
|
+
assetStore,
|
|
370
|
+
staticFallbackHandler,
|
|
371
|
+
appMode,
|
|
372
|
+
appConfigs
|
|
373
|
+
}) {
|
|
374
|
+
const staticDir = path.resolve(rootDir, "static");
|
|
375
|
+
const injectedConfigPath = appConfigs && await injectConfig({ appConfigs, logger, staticDir });
|
|
376
|
+
await injectAppMode({ appMode, rootDir });
|
|
263
377
|
const router = Router__default.default();
|
|
264
|
-
router.use(helmet__default.default.frameguard({ action: "deny" }));
|
|
265
378
|
const staticRouter = Router__default.default();
|
|
266
379
|
staticRouter.use(
|
|
267
|
-
express__default.default.static(
|
|
380
|
+
express__default.default.static(staticDir, {
|
|
268
381
|
setHeaders: (res, path) => {
|
|
269
382
|
if (path === injectedConfigPath) {
|
|
270
383
|
res.setHeader("Cache-Control", CACHE_CONTROL_REVALIDATE_CACHE);
|
|
@@ -274,15 +387,11 @@ async function createRouter(options) {
|
|
|
274
387
|
}
|
|
275
388
|
})
|
|
276
389
|
);
|
|
277
|
-
if (
|
|
278
|
-
const store = await StaticAssetsStore.create({
|
|
279
|
-
logger,
|
|
280
|
-
database: options.database
|
|
281
|
-
});
|
|
390
|
+
if (assetStore) {
|
|
282
391
|
const assets = await findStaticAssets(staticDir);
|
|
283
|
-
await
|
|
284
|
-
await
|
|
285
|
-
staticRouter.use(createStaticAssetMiddleware(
|
|
392
|
+
await assetStore.storeAssets(assets);
|
|
393
|
+
await assetStore.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });
|
|
394
|
+
staticRouter.use(createStaticAssetMiddleware(assetStore));
|
|
286
395
|
}
|
|
287
396
|
if (staticFallbackHandler) {
|
|
288
397
|
staticRouter.use(staticFallbackHandler);
|
|
@@ -290,7 +399,7 @@ async function createRouter(options) {
|
|
|
290
399
|
staticRouter.use(backendCommon.notFoundHandler());
|
|
291
400
|
router.use("/static", staticRouter);
|
|
292
401
|
router.use(
|
|
293
|
-
express__default.default.static(
|
|
402
|
+
express__default.default.static(rootDir, {
|
|
294
403
|
setHeaders: (res, path) => {
|
|
295
404
|
if (express__default.default.static.mime.lookup(path) === "text/html") {
|
|
296
405
|
res.setHeader("Cache-Control", CACHE_CONTROL_NO_CACHE);
|
|
@@ -299,7 +408,7 @@ async function createRouter(options) {
|
|
|
299
408
|
})
|
|
300
409
|
);
|
|
301
410
|
router.get("/*", (_req, res) => {
|
|
302
|
-
res.sendFile(path.resolve(
|
|
411
|
+
res.sendFile(path.resolve(rootDir, "index.html"), {
|
|
303
412
|
headers: {
|
|
304
413
|
// The Cache-Control header instructs the browser to not cache the index.html since it might
|
|
305
414
|
// link to static assets from recently deployed versions.
|
|
@@ -311,4 +420,4 @@ async function createRouter(options) {
|
|
|
311
420
|
}
|
|
312
421
|
|
|
313
422
|
exports.createRouter = createRouter;
|
|
314
|
-
//# sourceMappingURL=router-
|
|
423
|
+
//# sourceMappingURL=router-BpjcQ_K5.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router-BpjcQ_K5.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 { Logger } from 'winston';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport {\n ConfigSchema,\n loadConfigSchema,\n readEnvConfig,\n} from '@backstage/config-loader';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: Logger;\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 {\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { Logger } from 'winston';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\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: Logger;\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: Logger;\n #namespace: string | null;\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: Logger, namespace?: string) {\n this.#db = client;\n this.#logger = logger;\n this.#namespace = namespace ?? null;\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('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-common';\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 {\n notFoundHandler,\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { AppConfig, Config } 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 { Logger } from 'winston';\nimport { injectConfig, readConfigs } from '../lib/config';\nimport {\n StaticAssetsStore,\n findStaticAssets,\n createStaticAssetMiddleware,\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 { AuthService, HttpAuthService } 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/** @public */\nexport interface RouterOptions {\n config: Config;\n logger: Logger;\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?: PluginDatabaseManager;\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/** @public */\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 } = 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 });\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 appMode: 'public',\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 appMode: enablePublicEntryPoint ? 'protected' : 'public',\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 injectAppMode(options: {\n appMode: 'public' | 'protected';\n rootDir: string;\n}) {\n const { appMode, rootDir } = options;\n const content = await fs.readFile(resolvePath(rootDir, 'index.html'), 'utf8');\n\n const metaTag = `<meta name=\"backstage-app-mode\" content=\"${appMode}\">`;\n\n let newContent;\n if (content.includes('backstage-app-mode')) {\n newContent = content.replace(\n /<meta name=\"backstage-app-mode\" content=\"[^\"]+\">/,\n metaTag,\n );\n } else {\n newContent = content.replace(/<head>/, `<head>${metaTag}`);\n }\n\n await fs.writeFile(resolvePath(rootDir, 'index.html'), newContent, 'utf8');\n}\n\nasync function createEntryPointRouter({\n logger,\n rootDir,\n assetStore,\n staticFallbackHandler,\n appMode,\n appConfigs,\n}: {\n logger: Logger;\n rootDir: string;\n assetStore?: StaticAssetsStore;\n staticFallbackHandler?: express.Handler;\n appMode: 'public' | 'protected';\n appConfigs?: AppConfig[];\n}) {\n const staticDir = resolvePath(rootDir, 'static');\n\n const injectedConfigPath =\n appConfigs && (await injectConfig({ appConfigs, logger, staticDir }));\n\n await injectAppMode({ appMode, rootDir });\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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require('./cjs/router-
|
|
3
|
+
var router = require('./cjs/router-BpjcQ_K5.cjs.js');
|
|
4
4
|
require('@backstage/backend-common');
|
|
5
5
|
require('helmet');
|
|
6
6
|
require('express');
|
|
@@ -11,6 +11,7 @@ require('@backstage/config-loader');
|
|
|
11
11
|
require('luxon');
|
|
12
12
|
require('lodash/partition');
|
|
13
13
|
require('globby');
|
|
14
|
+
require('@backstage/errors');
|
|
14
15
|
|
|
15
16
|
|
|
16
17
|
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -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/dist/index.d.ts
CHANGED
|
@@ -3,11 +3,14 @@ import { Config } from '@backstage/config';
|
|
|
3
3
|
import express from 'express';
|
|
4
4
|
import { Logger } from 'winston';
|
|
5
5
|
import { ConfigSchema } from '@backstage/config-loader';
|
|
6
|
+
import { AuthService, HttpAuthService } from '@backstage/backend-plugin-api';
|
|
6
7
|
|
|
7
8
|
/** @public */
|
|
8
9
|
interface RouterOptions {
|
|
9
10
|
config: Config;
|
|
10
11
|
logger: Logger;
|
|
12
|
+
auth?: AuthService;
|
|
13
|
+
httpAuth?: HttpAuthService;
|
|
11
14
|
/**
|
|
12
15
|
* If a database is provided it will be used to cache previously deployed static assets.
|
|
13
16
|
*
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2021 The Backstage Authors
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// @ts-check
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {import('knex').Knex} knex
|
|
21
|
+
*/
|
|
22
|
+
exports.up = async function up(knex) {
|
|
23
|
+
await knex.schema.alterTable('static_assets_cache', table => {
|
|
24
|
+
// The namespace is used to allow operations on asset groups, e.g. delete all assets in a namespace
|
|
25
|
+
table.string('namespace').comment('The namespace of the file');
|
|
26
|
+
table.index('namespace', 'static_asset_cache_namespace_idx');
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {import('knex').Knex} knex
|
|
32
|
+
*/
|
|
33
|
+
exports.down = async function down(knex) {
|
|
34
|
+
await knex.schema.alterTable('static_assets_cache', table => {
|
|
35
|
+
table.dropIndex([], 'static_asset_cache_namespace_idx');
|
|
36
|
+
table.dropColumn('namespace');
|
|
37
|
+
});
|
|
38
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-app-backend",
|
|
3
3
|
"description": "A Backstage backend plugin that serves the Backstage frontend app",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.65-next.1",
|
|
5
5
|
"main": "./dist/index.cjs.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"license": "Apache-2.0",
|
|
@@ -43,11 +43,13 @@
|
|
|
43
43
|
"clean": "backstage-cli package clean"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@backstage/backend-common": "^0.21.
|
|
47
|
-
"@backstage/backend-plugin-api": "^0.6.
|
|
46
|
+
"@backstage/backend-common": "^0.21.7-next.1",
|
|
47
|
+
"@backstage/backend-plugin-api": "^0.6.17-next.1",
|
|
48
48
|
"@backstage/config": "^1.2.0",
|
|
49
|
-
"@backstage/config-loader": "^1.
|
|
50
|
-
"@backstage/
|
|
49
|
+
"@backstage/config-loader": "^1.8.0-next.0",
|
|
50
|
+
"@backstage/errors": "^1.2.4",
|
|
51
|
+
"@backstage/plugin-app-node": "^0.1.17-next.1",
|
|
52
|
+
"@backstage/plugin-auth-node": "^0.4.12-next.1",
|
|
51
53
|
"@backstage/types": "^1.1.1",
|
|
52
54
|
"@types/express": "^4.17.6",
|
|
53
55
|
"express": "^4.17.1",
|
|
@@ -62,9 +64,9 @@
|
|
|
62
64
|
"yn": "^4.0.0"
|
|
63
65
|
},
|
|
64
66
|
"devDependencies": {
|
|
65
|
-
"@backstage/backend-app-api": "^0.
|
|
66
|
-
"@backstage/backend-test-utils": "^0.3.
|
|
67
|
-
"@backstage/cli": "^0.26.
|
|
67
|
+
"@backstage/backend-app-api": "^0.7.0-next.1",
|
|
68
|
+
"@backstage/backend-test-utils": "^0.3.7-next.1",
|
|
69
|
+
"@backstage/cli": "^0.26.3-next.1",
|
|
68
70
|
"@backstage/types": "^1.1.1",
|
|
69
71
|
"@types/supertest": "^2.0.8",
|
|
70
72
|
"node-fetch": "^2.6.7",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router-DVSRooks.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 { Logger } from 'winston';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport {\n ConfigSchema,\n loadConfigSchema,\n readEnvConfig,\n} from '@backstage/config-loader';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: Logger;\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 {\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { Logger } from 'winston';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-app-backend',\n 'migrations',\n);\n\ninterface StaticAssetRow {\n path: string;\n content: Buffer;\n last_modified_at: Date;\n}\n\n/** @internal */\nexport interface StaticAssetsStoreOptions {\n database: PluginDatabaseManager;\n logger: Logger;\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: Logger;\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: Logger) {\n this.#db = client;\n this.#logger = logger;\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>(\n 'static_assets_cache',\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 .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 })\n .onConflict('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 });\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('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-common';\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 {\n notFoundHandler,\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Config } 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 { Logger } from 'winston';\nimport { injectConfig, readConfigs } from '../lib/config';\nimport {\n StaticAssetsStore,\n findStaticAssets,\n createStaticAssetMiddleware,\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';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/** @public */\nexport interface RouterOptions {\n config: Config;\n logger: Logger;\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?: PluginDatabaseManager;\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/** @public */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { config, logger, appPackageName, staticFallbackHandler } = 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 let injectedConfigPath: string | undefined;\n if (!disableConfigInjection) {\n const appConfigs = await readConfigs({\n config,\n appDistDir,\n env: process.env,\n schema: options.schema,\n });\n\n injectedConfigPath = await injectConfig({ appConfigs, logger, staticDir });\n }\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\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(resolvePath(appDistDir, 'static'), {\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 (options.database && !disableStaticFallbackCache) {\n const store = await StaticAssetsStore.create({\n logger,\n database: options.database,\n });\n\n const assets = await findStaticAssets(staticDir);\n await store.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await store.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(store));\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(appDistDir, {\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 router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(appDistDir, '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","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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