@backstage/plugin-app-backend 0.3.75-next.0 → 0.3.75

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,18 +1,10 @@
1
1
  # @backstage/plugin-app-backend
2
2
 
3
- ## 0.3.75-next.0
3
+ ## 0.3.75
4
4
 
5
5
  ### Patch Changes
6
6
 
7
- - 094eaa3: Remove references to in-repo backend-common
8
- - Updated dependencies
9
- - @backstage/plugin-auth-node@0.5.3-next.0
10
- - @backstage/backend-plugin-api@1.0.1-next.0
11
- - @backstage/config@1.2.0
12
- - @backstage/config-loader@1.9.1
13
- - @backstage/errors@1.2.4
14
- - @backstage/types@1.1.1
15
- - @backstage/plugin-app-node@0.1.26-next.0
7
+ - 9206a12: Fixed unexpected behaviour where configuration supplied with `APP_CONFIG_*` environment variables where not filtered by the configuration schema.
16
8
 
17
9
  ## 0.3.74
18
10
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-app-backend__alpha",
3
- "version": "0.3.75-next.0",
3
+ "version": "0.3.75",
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-iVPYMLvA.cjs.js');
6
+ var router = require('./cjs/router-Bi0af47X.cjs.js');
7
7
  var pluginAppNode = require('@backstage/plugin-app-node');
8
8
  require('@backstage/backend-common');
9
9
  require('helmet');
@@ -251,26 +251,25 @@ async function injectConfig(options) {
251
251
 
252
252
  async function readFrontendConfig(options) {
253
253
  const { env, appDistDir, config } = options;
254
- const appConfigs = configLoader.readEnvConfig(env);
255
254
  const schemaPath = path.resolve(appDistDir, ".config-schema.json");
256
255
  if (await fs__default.default.pathExists(schemaPath)) {
256
+ const envConfigs = configLoader.readEnvConfig(env);
257
257
  const serializedSchema = await fs__default.default.readJson(schemaPath);
258
258
  try {
259
259
  const schema = options.schema || await configLoader.loadConfigSchema({
260
260
  serialized: serializedSchema
261
261
  });
262
- const frontendConfigs = await schema.process(
263
- [{ data: config.get(), context: "app" }],
262
+ return await schema.process(
263
+ [...envConfigs, { data: config.get(), context: "app" }],
264
264
  { visibility: ["frontend"], withDeprecatedKeys: true }
265
265
  );
266
- appConfigs.push(...frontendConfigs);
267
266
  } catch (error) {
268
267
  throw new Error(
269
268
  `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
269
  );
271
270
  }
272
271
  }
273
- return appConfigs;
272
+ return [];
274
273
  }
275
274
 
276
275
  async function createRouter(options) {
@@ -433,4 +432,4 @@ async function createEntryPointRouter({
433
432
  }
434
433
 
435
434
  exports.createRouter = createRouter;
436
- //# sourceMappingURL=router-iVPYMLvA.cjs.js.map
435
+ //# sourceMappingURL=router-Bi0af47X.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router-Bi0af47X.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 schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const envConfigs = readEnvConfig(env);\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 return await schema.process(\n [...envConfigs, { data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'], withDeprecatedKeys: true },\n );\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 [];\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,C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AA,CAAA;AAClC,EAAO,MAAA,CAAA,GAAA;AAAA,IACLH,wBAAA,CAAQ,OAAO,OAAS,EAAA;AAAA,MACtB,UAAA,EAAY,CAAC,GAAA,EAAK,IAAS,KAAA;AAGzB,QAAA,IACGA,yBAAQ,MAAO,CAAA,IAAA,CAAyB,MAAO,CAAA,IAAI,MAAM,WAC1D,EAAA;AACA,UAAI,GAAA,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-iVPYMLvA.cjs.js');
3
+ var router = require('./cjs/router-Bi0af47X.cjs.js');
4
4
  require('@backstage/backend-common');
5
5
  require('@backstage/backend-plugin-api');
6
6
  require('helmet');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-app-backend",
3
- "version": "0.3.75-next.0",
3
+ "version": "0.3.75",
4
4
  "description": "A Backstage backend plugin that serves the Backstage frontend app",
5
5
  "backstage": {
6
6
  "role": "backend-plugin",
@@ -31,7 +31,6 @@
31
31
  "default": "./dist/index.cjs.js"
32
32
  },
33
33
  "./alpha": {
34
- "backstage": "@backstage/BackendFeature",
35
34
  "require": "./dist/alpha.cjs.js",
36
35
  "types": "./dist/alpha.d.ts",
37
36
  "default": "./dist/alpha.cjs.js"
@@ -58,12 +57,12 @@
58
57
  },
59
58
  "dependencies": {
60
59
  "@backstage/backend-common": "^0.25.0",
61
- "@backstage/backend-plugin-api": "^1.0.1-next.0",
60
+ "@backstage/backend-plugin-api": "^1.0.0",
62
61
  "@backstage/config": "^1.2.0",
63
62
  "@backstage/config-loader": "^1.9.1",
64
63
  "@backstage/errors": "^1.2.4",
65
- "@backstage/plugin-app-node": "^0.1.26-next.0",
66
- "@backstage/plugin-auth-node": "^0.5.3-next.0",
64
+ "@backstage/plugin-app-node": "^0.1.25",
65
+ "@backstage/plugin-auth-node": "^0.5.2",
67
66
  "@backstage/types": "^1.1.1",
68
67
  "@types/express": "^4.17.6",
69
68
  "express": "^4.17.1",
@@ -77,10 +76,10 @@
77
76
  "yn": "^4.0.0"
78
77
  },
79
78
  "devDependencies": {
80
- "@backstage/backend-app-api": "^1.0.1-next.0",
81
- "@backstage/backend-defaults": "^0.5.1-next.0",
82
- "@backstage/backend-test-utils": "^1.0.1-next.0",
83
- "@backstage/cli": "^0.28.0-next.0",
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",
84
83
  "@backstage/types": "^1.1.1",
85
84
  "@types/supertest": "^2.0.8",
86
85
  "node-fetch": "^2.7.0",
@@ -1 +0,0 @@
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,C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