@backstage/backend-app-api 0.0.0-nightly-20230111022819 → 0.0.0-nightly-20230113023010
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.
Potentially problematic release.
This version of @backstage/backend-app-api might be problematic. Click here for more details.
- package/CHANGELOG.md +11 -6
- package/alpha/package.json +1 -1
- package/dist/index.alpha.d.ts +46 -1
- package/dist/index.beta.d.ts +46 -1
- package/dist/index.cjs.js +172 -127
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +46 -1
- package/package.json +9 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @backstage/backend-app-api
|
|
2
2
|
|
|
3
|
-
## 0.0.0-nightly-
|
|
3
|
+
## 0.0.0-nightly-20230113023010
|
|
4
4
|
|
|
5
5
|
### Minor Changes
|
|
6
6
|
|
|
@@ -12,18 +12,23 @@
|
|
|
12
12
|
|
|
13
13
|
- ecc6bfe4c9: Use new `ServiceFactoryOrFunction` type.
|
|
14
14
|
- b99c030f1b: Moved over implementation of the root HTTP service from `@backstage/backend-common`, and replaced the `middleware` option with a `configure` callback option.
|
|
15
|
+
- 170282ece6: Fixed a bug in the default token manager factory where it created multiple incompatible instances.
|
|
16
|
+
- 843a0a158c: Added service factory for the new core identity service.
|
|
15
17
|
- 150a7dd790: An error will now be thrown if attempting to override the plugin metadata service.
|
|
16
18
|
- 015a6dced6: The `createSpecializedBackend` function will now throw an error if duplicate service implementations are provided.
|
|
17
19
|
- e3fca10038: Tweaked the plugin logger to use `plugin` as the label for the plugin ID, rather than `pluginId`.
|
|
20
|
+
- 51b7a7ed07: Exported the default root HTTP router implementation as `DefaultRootHttpRouter`. It only implements the routing layer and needs to be exposed via an HTTP server similar to the built-in setup in the `rootHttpRouterFactory`.
|
|
18
21
|
- 8e06f3cf00: Switched imports of `loggerToWinstonLogger` to `@backstage/backend-common`.
|
|
22
|
+
- 3b8fd4169b: Internal folder structure refactor.
|
|
19
23
|
- 6cfd4d7073: Updated implementations for the new `RootLifecycleService`.
|
|
20
24
|
- Updated dependencies
|
|
21
|
-
- @backstage/backend-plugin-api@0.0.0-nightly-
|
|
22
|
-
- @backstage/backend-common@0.0.0-nightly-
|
|
23
|
-
- @backstage/backend-tasks@0.0.0-nightly-
|
|
24
|
-
- @backstage/config@0.0.0-nightly-
|
|
25
|
+
- @backstage/backend-plugin-api@0.0.0-nightly-20230113023010
|
|
26
|
+
- @backstage/backend-common@0.0.0-nightly-20230113023010
|
|
27
|
+
- @backstage/backend-tasks@0.0.0-nightly-20230113023010
|
|
28
|
+
- @backstage/config@0.0.0-nightly-20230113023010
|
|
25
29
|
- @backstage/errors@1.1.4
|
|
26
|
-
- @backstage/plugin-
|
|
30
|
+
- @backstage/plugin-auth-node@0.0.0-nightly-20230113023010
|
|
31
|
+
- @backstage/plugin-permission-node@0.0.0-nightly-20230113023010
|
|
27
32
|
|
|
28
33
|
## 0.3.0-next.1
|
|
29
34
|
|
package/alpha/package.json
CHANGED
package/dist/index.alpha.d.ts
CHANGED
|
@@ -13,9 +13,11 @@ import { CorsOptions } from 'cors';
|
|
|
13
13
|
import { ErrorRequestHandler } from 'express';
|
|
14
14
|
import { Express as Express_2 } from 'express';
|
|
15
15
|
import { ExtensionPoint } from '@backstage/backend-plugin-api';
|
|
16
|
+
import { Handler } from 'express';
|
|
16
17
|
import { HelmetOptions } from 'helmet';
|
|
17
18
|
import * as http from 'http';
|
|
18
19
|
import { HttpRouterService } from '@backstage/backend-plugin-api';
|
|
20
|
+
import { IdentityService } from '@backstage/backend-plugin-api';
|
|
19
21
|
import { LifecycleService } from '@backstage/backend-plugin-api';
|
|
20
22
|
import { LoggerService } from '@backstage/backend-plugin-api';
|
|
21
23
|
import { PermissionsService } from '@backstage/backend-plugin-api';
|
|
@@ -73,6 +75,33 @@ export declare interface CreateSpecializedBackendOptions {
|
|
|
73
75
|
/** @public */
|
|
74
76
|
export declare const databaseFactory: (options?: undefined) => ServiceFactory<PluginDatabaseManager>;
|
|
75
77
|
|
|
78
|
+
/**
|
|
79
|
+
* The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for
|
|
80
|
+
* {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.
|
|
81
|
+
*
|
|
82
|
+
* @public
|
|
83
|
+
*/
|
|
84
|
+
export declare class DefaultRootHttpRouter implements RootHttpRouterService {
|
|
85
|
+
#private;
|
|
86
|
+
static create(options?: DefaultRootHttpRouterOptions): DefaultRootHttpRouter;
|
|
87
|
+
private constructor();
|
|
88
|
+
use(path: string, handler: Handler): void;
|
|
89
|
+
handler(): Handler;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Options for the {@link DefaultRootHttpRouter} class.
|
|
94
|
+
*
|
|
95
|
+
* @public
|
|
96
|
+
*/
|
|
97
|
+
export declare interface DefaultRootHttpRouterOptions {
|
|
98
|
+
/**
|
|
99
|
+
* The path to forward all unmatched requests to. Defaults to '/api/app' if
|
|
100
|
+
* not given. Disables index path behavior if false is given.
|
|
101
|
+
*/
|
|
102
|
+
indexPath?: string | false;
|
|
103
|
+
}
|
|
104
|
+
|
|
76
105
|
/** @public */
|
|
77
106
|
export declare const discoveryFactory: (options?: undefined) => ServiceFactory<PluginEndpointDiscovery>;
|
|
78
107
|
|
|
@@ -129,6 +158,21 @@ export declare type HttpServerOptions = {
|
|
|
129
158
|
};
|
|
130
159
|
};
|
|
131
160
|
|
|
161
|
+
/** @public */
|
|
162
|
+
export declare const identityFactory: (options?: IdentityFactoryOptions | undefined) => ServiceFactory<IdentityService>;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* An identity client options object which allows extra configurations
|
|
166
|
+
*
|
|
167
|
+
* @public
|
|
168
|
+
*/
|
|
169
|
+
export declare type IdentityFactoryOptions = {
|
|
170
|
+
issuer?: string;
|
|
171
|
+
/** JWS "alg" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.
|
|
172
|
+
* More info on supported algorithms: https://github.com/panva/jose */
|
|
173
|
+
algorithms?: string[];
|
|
174
|
+
};
|
|
175
|
+
|
|
132
176
|
/**
|
|
133
177
|
* Allows plugins to register shutdown hooks that are run when the process is about to exit.
|
|
134
178
|
* @public */
|
|
@@ -327,7 +371,8 @@ export declare const rootHttpRouterFactory: (options?: RootHttpRouterFactoryOpti
|
|
|
327
371
|
*/
|
|
328
372
|
export declare type RootHttpRouterFactoryOptions = {
|
|
329
373
|
/**
|
|
330
|
-
* The path to forward all unmatched requests to. Defaults to '/api/app'
|
|
374
|
+
* The path to forward all unmatched requests to. Defaults to '/api/app' if
|
|
375
|
+
* not given. Disables index path behavior if false is given.
|
|
331
376
|
*/
|
|
332
377
|
indexPath?: string | false;
|
|
333
378
|
configure?(options: RootHttpRouterConfigureOptions): void;
|
package/dist/index.beta.d.ts
CHANGED
|
@@ -13,9 +13,11 @@ import { CorsOptions } from 'cors';
|
|
|
13
13
|
import { ErrorRequestHandler } from 'express';
|
|
14
14
|
import { Express as Express_2 } from 'express';
|
|
15
15
|
import { ExtensionPoint } from '@backstage/backend-plugin-api';
|
|
16
|
+
import { Handler } from 'express';
|
|
16
17
|
import { HelmetOptions } from 'helmet';
|
|
17
18
|
import * as http from 'http';
|
|
18
19
|
import { HttpRouterService } from '@backstage/backend-plugin-api';
|
|
20
|
+
import { IdentityService } from '@backstage/backend-plugin-api';
|
|
19
21
|
import { LifecycleService } from '@backstage/backend-plugin-api';
|
|
20
22
|
import { LoggerService } from '@backstage/backend-plugin-api';
|
|
21
23
|
import { PermissionsService } from '@backstage/backend-plugin-api';
|
|
@@ -73,6 +75,33 @@ export declare interface CreateSpecializedBackendOptions {
|
|
|
73
75
|
/** @public */
|
|
74
76
|
export declare const databaseFactory: (options?: undefined) => ServiceFactory<PluginDatabaseManager>;
|
|
75
77
|
|
|
78
|
+
/**
|
|
79
|
+
* The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for
|
|
80
|
+
* {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.
|
|
81
|
+
*
|
|
82
|
+
* @public
|
|
83
|
+
*/
|
|
84
|
+
export declare class DefaultRootHttpRouter implements RootHttpRouterService {
|
|
85
|
+
#private;
|
|
86
|
+
static create(options?: DefaultRootHttpRouterOptions): DefaultRootHttpRouter;
|
|
87
|
+
private constructor();
|
|
88
|
+
use(path: string, handler: Handler): void;
|
|
89
|
+
handler(): Handler;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Options for the {@link DefaultRootHttpRouter} class.
|
|
94
|
+
*
|
|
95
|
+
* @public
|
|
96
|
+
*/
|
|
97
|
+
export declare interface DefaultRootHttpRouterOptions {
|
|
98
|
+
/**
|
|
99
|
+
* The path to forward all unmatched requests to. Defaults to '/api/app' if
|
|
100
|
+
* not given. Disables index path behavior if false is given.
|
|
101
|
+
*/
|
|
102
|
+
indexPath?: string | false;
|
|
103
|
+
}
|
|
104
|
+
|
|
76
105
|
/** @public */
|
|
77
106
|
export declare const discoveryFactory: (options?: undefined) => ServiceFactory<PluginEndpointDiscovery>;
|
|
78
107
|
|
|
@@ -129,6 +158,21 @@ export declare type HttpServerOptions = {
|
|
|
129
158
|
};
|
|
130
159
|
};
|
|
131
160
|
|
|
161
|
+
/** @public */
|
|
162
|
+
export declare const identityFactory: (options?: IdentityFactoryOptions | undefined) => ServiceFactory<IdentityService>;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* An identity client options object which allows extra configurations
|
|
166
|
+
*
|
|
167
|
+
* @public
|
|
168
|
+
*/
|
|
169
|
+
export declare type IdentityFactoryOptions = {
|
|
170
|
+
issuer?: string;
|
|
171
|
+
/** JWS "alg" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.
|
|
172
|
+
* More info on supported algorithms: https://github.com/panva/jose */
|
|
173
|
+
algorithms?: string[];
|
|
174
|
+
};
|
|
175
|
+
|
|
132
176
|
/**
|
|
133
177
|
* Allows plugins to register shutdown hooks that are run when the process is about to exit.
|
|
134
178
|
* @public */
|
|
@@ -327,7 +371,8 @@ export declare const rootHttpRouterFactory: (options?: RootHttpRouterFactoryOpti
|
|
|
327
371
|
*/
|
|
328
372
|
export declare type RootHttpRouterFactoryOptions = {
|
|
329
373
|
/**
|
|
330
|
-
* The path to forward all unmatched requests to. Defaults to '/api/app'
|
|
374
|
+
* The path to forward all unmatched requests to. Defaults to '/api/app' if
|
|
375
|
+
* not given. Disables index path behavior if false is given.
|
|
331
376
|
*/
|
|
332
377
|
indexPath?: string | false;
|
|
333
378
|
configure?(options: RootHttpRouterConfigureOptions): void;
|
package/dist/index.cjs.js
CHANGED
|
@@ -15,9 +15,12 @@ var compression = require('compression');
|
|
|
15
15
|
var minimatch = require('minimatch');
|
|
16
16
|
var errors = require('@backstage/errors');
|
|
17
17
|
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
18
|
-
var express = require('express');
|
|
19
18
|
var backendCommon = require('@backstage/backend-common');
|
|
19
|
+
var config = require('@backstage/config');
|
|
20
|
+
var pluginAuthNode = require('@backstage/plugin-auth-node');
|
|
20
21
|
var pluginPermissionNode = require('@backstage/plugin-permission-node');
|
|
22
|
+
var express = require('express');
|
|
23
|
+
var trimEnd = require('lodash/trimEnd');
|
|
21
24
|
var backendTasks = require('@backstage/backend-tasks');
|
|
22
25
|
|
|
23
26
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
@@ -50,6 +53,7 @@ var helmet__default = /*#__PURE__*/_interopDefaultLegacy(helmet);
|
|
|
50
53
|
var morgan__default = /*#__PURE__*/_interopDefaultLegacy(morgan);
|
|
51
54
|
var compression__default = /*#__PURE__*/_interopDefaultLegacy(compression);
|
|
52
55
|
var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
|
|
56
|
+
var trimEnd__default = /*#__PURE__*/_interopDefaultLegacy(trimEnd);
|
|
53
57
|
|
|
54
58
|
const DEFAULT_PORT = 7007;
|
|
55
59
|
const DEFAULT_HOST = "";
|
|
@@ -1012,6 +1016,67 @@ function createSpecializedBackend(options) {
|
|
|
1012
1016
|
return new BackstageBackend(services);
|
|
1013
1017
|
}
|
|
1014
1018
|
|
|
1019
|
+
const cacheFactory = backendPluginApi.createServiceFactory({
|
|
1020
|
+
service: backendPluginApi.coreServices.cache,
|
|
1021
|
+
deps: {
|
|
1022
|
+
config: backendPluginApi.coreServices.config,
|
|
1023
|
+
plugin: backendPluginApi.coreServices.pluginMetadata
|
|
1024
|
+
},
|
|
1025
|
+
async factory({ config }) {
|
|
1026
|
+
const cacheManager = backendCommon.CacheManager.fromConfig(config);
|
|
1027
|
+
return async ({ plugin }) => {
|
|
1028
|
+
return cacheManager.forPlugin(plugin.getId());
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
});
|
|
1032
|
+
|
|
1033
|
+
const configFactory = backendPluginApi.createServiceFactory({
|
|
1034
|
+
service: backendPluginApi.coreServices.config,
|
|
1035
|
+
deps: {
|
|
1036
|
+
logger: backendPluginApi.coreServices.rootLogger
|
|
1037
|
+
},
|
|
1038
|
+
async factory({ logger }) {
|
|
1039
|
+
const config = await backendCommon.loadBackendConfig({
|
|
1040
|
+
argv: process.argv,
|
|
1041
|
+
logger: backendCommon.loggerToWinstonLogger(logger)
|
|
1042
|
+
});
|
|
1043
|
+
return config;
|
|
1044
|
+
}
|
|
1045
|
+
});
|
|
1046
|
+
|
|
1047
|
+
const databaseFactory = backendPluginApi.createServiceFactory({
|
|
1048
|
+
service: backendPluginApi.coreServices.database,
|
|
1049
|
+
deps: {
|
|
1050
|
+
config: backendPluginApi.coreServices.config,
|
|
1051
|
+
plugin: backendPluginApi.coreServices.pluginMetadata
|
|
1052
|
+
},
|
|
1053
|
+
async factory({ config: config$1 }) {
|
|
1054
|
+
const databaseManager = config$1.getOptional("backend.database") ? backendCommon.DatabaseManager.fromConfig(config$1) : backendCommon.DatabaseManager.fromConfig(
|
|
1055
|
+
new config.ConfigReader({
|
|
1056
|
+
backend: {
|
|
1057
|
+
database: { client: "better-sqlite3", connection: ":memory:" }
|
|
1058
|
+
}
|
|
1059
|
+
})
|
|
1060
|
+
);
|
|
1061
|
+
return async ({ plugin }) => {
|
|
1062
|
+
return databaseManager.forPlugin(plugin.getId());
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
});
|
|
1066
|
+
|
|
1067
|
+
const discoveryFactory = backendPluginApi.createServiceFactory({
|
|
1068
|
+
service: backendPluginApi.coreServices.discovery,
|
|
1069
|
+
deps: {
|
|
1070
|
+
config: backendPluginApi.coreServices.config
|
|
1071
|
+
},
|
|
1072
|
+
async factory({ config }) {
|
|
1073
|
+
const discovery = backendCommon.SingleHostDiscovery.fromConfig(config);
|
|
1074
|
+
return async () => {
|
|
1075
|
+
return discovery;
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
});
|
|
1079
|
+
|
|
1015
1080
|
const httpRouterFactory = backendPluginApi.createServiceFactory({
|
|
1016
1081
|
service: backendPluginApi.coreServices.httpRouter,
|
|
1017
1082
|
deps: {
|
|
@@ -1032,6 +1097,73 @@ const httpRouterFactory = backendPluginApi.createServiceFactory({
|
|
|
1032
1097
|
}
|
|
1033
1098
|
});
|
|
1034
1099
|
|
|
1100
|
+
const identityFactory = backendPluginApi.createServiceFactory({
|
|
1101
|
+
service: backendPluginApi.coreServices.identity,
|
|
1102
|
+
deps: {
|
|
1103
|
+
config: backendPluginApi.coreServices.config,
|
|
1104
|
+
discovery: backendPluginApi.coreServices.discovery,
|
|
1105
|
+
tokenManager: backendPluginApi.coreServices.tokenManager
|
|
1106
|
+
},
|
|
1107
|
+
async factory({}, options) {
|
|
1108
|
+
return async ({ discovery }) => {
|
|
1109
|
+
return pluginAuthNode.DefaultIdentityClient.create({ discovery, ...options });
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
});
|
|
1113
|
+
|
|
1114
|
+
const lifecycleFactory = backendPluginApi.createServiceFactory({
|
|
1115
|
+
service: backendPluginApi.coreServices.lifecycle,
|
|
1116
|
+
deps: {
|
|
1117
|
+
logger: backendPluginApi.coreServices.logger,
|
|
1118
|
+
rootLifecycle: backendPluginApi.coreServices.rootLifecycle,
|
|
1119
|
+
pluginMetadata: backendPluginApi.coreServices.pluginMetadata
|
|
1120
|
+
},
|
|
1121
|
+
async factory({ rootLifecycle }) {
|
|
1122
|
+
return async ({ logger, pluginMetadata }) => {
|
|
1123
|
+
const plugin = pluginMetadata.getId();
|
|
1124
|
+
return {
|
|
1125
|
+
addShutdownHook(options) {
|
|
1126
|
+
var _a, _b;
|
|
1127
|
+
rootLifecycle.addShutdownHook({
|
|
1128
|
+
...options,
|
|
1129
|
+
logger: (_b = (_a = options.logger) == null ? void 0 : _a.child({ plugin })) != null ? _b : logger
|
|
1130
|
+
});
|
|
1131
|
+
}
|
|
1132
|
+
};
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
});
|
|
1136
|
+
|
|
1137
|
+
const loggerFactory = backendPluginApi.createServiceFactory({
|
|
1138
|
+
service: backendPluginApi.coreServices.logger,
|
|
1139
|
+
deps: {
|
|
1140
|
+
rootLogger: backendPluginApi.coreServices.rootLogger,
|
|
1141
|
+
plugin: backendPluginApi.coreServices.pluginMetadata
|
|
1142
|
+
},
|
|
1143
|
+
async factory({ rootLogger }) {
|
|
1144
|
+
return async ({ plugin }) => {
|
|
1145
|
+
return rootLogger.child({ plugin: plugin.getId() });
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
const permissionsFactory = backendPluginApi.createServiceFactory({
|
|
1151
|
+
service: backendPluginApi.coreServices.permissions,
|
|
1152
|
+
deps: {
|
|
1153
|
+
config: backendPluginApi.coreServices.config,
|
|
1154
|
+
discovery: backendPluginApi.coreServices.discovery,
|
|
1155
|
+
tokenManager: backendPluginApi.coreServices.tokenManager
|
|
1156
|
+
},
|
|
1157
|
+
async factory({ config }) {
|
|
1158
|
+
return async ({ discovery, tokenManager }) => {
|
|
1159
|
+
return pluginPermissionNode.ServerPermissionClient.fromConfig(config, {
|
|
1160
|
+
discovery,
|
|
1161
|
+
tokenManager
|
|
1162
|
+
});
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
});
|
|
1166
|
+
|
|
1035
1167
|
var __accessCheck = (obj, member, msg) => {
|
|
1036
1168
|
if (!member.has(obj))
|
|
1037
1169
|
throw TypeError("Cannot " + msg);
|
|
@@ -1056,9 +1188,9 @@ var __privateMethod = (obj, member, method) => {
|
|
|
1056
1188
|
};
|
|
1057
1189
|
var _indexPath, _router, _namedRoutes, _indexRouter, _existingPaths, _findConflictingPath, findConflictingPath_fn;
|
|
1058
1190
|
function normalizePath(path) {
|
|
1059
|
-
return path
|
|
1191
|
+
return `${trimEnd__default["default"](path, "/")}/`;
|
|
1060
1192
|
}
|
|
1061
|
-
class
|
|
1193
|
+
const _DefaultRootHttpRouter = class {
|
|
1062
1194
|
constructor(indexPath) {
|
|
1063
1195
|
__privateAdd(this, _findConflictingPath);
|
|
1064
1196
|
__privateAdd(this, _indexPath, void 0);
|
|
@@ -1068,7 +1200,22 @@ class RestrictedIndexedRouter {
|
|
|
1068
1200
|
__privateAdd(this, _existingPaths, new Array());
|
|
1069
1201
|
__privateSet(this, _indexPath, indexPath);
|
|
1070
1202
|
__privateGet(this, _router).use(__privateGet(this, _namedRoutes));
|
|
1071
|
-
|
|
1203
|
+
if (__privateGet(this, _indexPath)) {
|
|
1204
|
+
__privateGet(this, _router).use(__privateGet(this, _indexRouter));
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
static create(options) {
|
|
1208
|
+
let indexPath;
|
|
1209
|
+
if ((options == null ? void 0 : options.indexPath) === false) {
|
|
1210
|
+
indexPath = void 0;
|
|
1211
|
+
} else if ((options == null ? void 0 : options.indexPath) === void 0) {
|
|
1212
|
+
indexPath = "/api/app";
|
|
1213
|
+
} else if ((options == null ? void 0 : options.indexPath) === "") {
|
|
1214
|
+
throw new Error("indexPath option may not be an empty string");
|
|
1215
|
+
} else {
|
|
1216
|
+
indexPath = options.indexPath;
|
|
1217
|
+
}
|
|
1218
|
+
return new _DefaultRootHttpRouter(indexPath);
|
|
1072
1219
|
}
|
|
1073
1220
|
use(path, handler) {
|
|
1074
1221
|
if (path.match(/^[/\s]*$/)) {
|
|
@@ -1089,7 +1236,8 @@ class RestrictedIndexedRouter {
|
|
|
1089
1236
|
handler() {
|
|
1090
1237
|
return __privateGet(this, _router);
|
|
1091
1238
|
}
|
|
1092
|
-
}
|
|
1239
|
+
};
|
|
1240
|
+
let DefaultRootHttpRouter = _DefaultRootHttpRouter;
|
|
1093
1241
|
_indexPath = new WeakMap();
|
|
1094
1242
|
_router = new WeakMap();
|
|
1095
1243
|
_namedRoutes = new WeakMap();
|
|
@@ -1134,9 +1282,9 @@ const rootHttpRouterFactory = backendPluginApi.createServiceFactory({
|
|
|
1134
1282
|
indexPath,
|
|
1135
1283
|
configure = defaultConfigure
|
|
1136
1284
|
} = {}) {
|
|
1137
|
-
const router = new RestrictedIndexedRouter(indexPath != null ? indexPath : "/api/app");
|
|
1138
1285
|
const logger = rootLogger.child({ service: "rootHttpRouter" });
|
|
1139
1286
|
const app = express__default["default"]();
|
|
1287
|
+
const router = DefaultRootHttpRouter.create({ indexPath });
|
|
1140
1288
|
const middleware = MiddlewareFactory.create({ config, logger });
|
|
1141
1289
|
configure({
|
|
1142
1290
|
app,
|
|
@@ -1162,74 +1310,6 @@ const rootHttpRouterFactory = backendPluginApi.createServiceFactory({
|
|
|
1162
1310
|
}
|
|
1163
1311
|
});
|
|
1164
1312
|
|
|
1165
|
-
const cacheFactory = backendPluginApi.createServiceFactory({
|
|
1166
|
-
service: backendPluginApi.coreServices.cache,
|
|
1167
|
-
deps: {
|
|
1168
|
-
config: backendPluginApi.coreServices.config,
|
|
1169
|
-
plugin: backendPluginApi.coreServices.pluginMetadata
|
|
1170
|
-
},
|
|
1171
|
-
async factory({ config }) {
|
|
1172
|
-
const cacheManager = backendCommon.CacheManager.fromConfig(config);
|
|
1173
|
-
return async ({ plugin }) => {
|
|
1174
|
-
return cacheManager.forPlugin(plugin.getId());
|
|
1175
|
-
};
|
|
1176
|
-
}
|
|
1177
|
-
});
|
|
1178
|
-
|
|
1179
|
-
const configFactory = backendPluginApi.createServiceFactory({
|
|
1180
|
-
service: backendPluginApi.coreServices.config,
|
|
1181
|
-
deps: {
|
|
1182
|
-
logger: backendPluginApi.coreServices.rootLogger
|
|
1183
|
-
},
|
|
1184
|
-
async factory({ logger }) {
|
|
1185
|
-
const config = await backendCommon.loadBackendConfig({
|
|
1186
|
-
argv: process.argv,
|
|
1187
|
-
logger: backendCommon.loggerToWinstonLogger(logger)
|
|
1188
|
-
});
|
|
1189
|
-
return config;
|
|
1190
|
-
}
|
|
1191
|
-
});
|
|
1192
|
-
|
|
1193
|
-
const databaseFactory = backendPluginApi.createServiceFactory({
|
|
1194
|
-
service: backendPluginApi.coreServices.database,
|
|
1195
|
-
deps: {
|
|
1196
|
-
config: backendPluginApi.coreServices.config,
|
|
1197
|
-
plugin: backendPluginApi.coreServices.pluginMetadata
|
|
1198
|
-
},
|
|
1199
|
-
async factory({ config }) {
|
|
1200
|
-
const databaseManager = backendCommon.DatabaseManager.fromConfig(config);
|
|
1201
|
-
return async ({ plugin }) => {
|
|
1202
|
-
return databaseManager.forPlugin(plugin.getId());
|
|
1203
|
-
};
|
|
1204
|
-
}
|
|
1205
|
-
});
|
|
1206
|
-
|
|
1207
|
-
const discoveryFactory = backendPluginApi.createServiceFactory({
|
|
1208
|
-
service: backendPluginApi.coreServices.discovery,
|
|
1209
|
-
deps: {
|
|
1210
|
-
config: backendPluginApi.coreServices.config
|
|
1211
|
-
},
|
|
1212
|
-
async factory({ config }) {
|
|
1213
|
-
const discovery = backendCommon.SingleHostDiscovery.fromConfig(config);
|
|
1214
|
-
return async () => {
|
|
1215
|
-
return discovery;
|
|
1216
|
-
};
|
|
1217
|
-
}
|
|
1218
|
-
});
|
|
1219
|
-
|
|
1220
|
-
const loggerFactory = backendPluginApi.createServiceFactory({
|
|
1221
|
-
service: backendPluginApi.coreServices.logger,
|
|
1222
|
-
deps: {
|
|
1223
|
-
rootLogger: backendPluginApi.coreServices.rootLogger,
|
|
1224
|
-
plugin: backendPluginApi.coreServices.pluginMetadata
|
|
1225
|
-
},
|
|
1226
|
-
async factory({ rootLogger }) {
|
|
1227
|
-
return async ({ plugin }) => {
|
|
1228
|
-
return rootLogger.child({ plugin: plugin.getId() });
|
|
1229
|
-
};
|
|
1230
|
-
}
|
|
1231
|
-
});
|
|
1232
|
-
|
|
1233
1313
|
class BackstageLogger {
|
|
1234
1314
|
constructor(winston) {
|
|
1235
1315
|
this.winston = winston;
|
|
@@ -1261,33 +1341,20 @@ const rootLoggerFactory = backendPluginApi.createServiceFactory({
|
|
|
1261
1341
|
}
|
|
1262
1342
|
});
|
|
1263
1343
|
|
|
1264
|
-
const permissionsFactory = backendPluginApi.createServiceFactory({
|
|
1265
|
-
service: backendPluginApi.coreServices.permissions,
|
|
1266
|
-
deps: {
|
|
1267
|
-
config: backendPluginApi.coreServices.config,
|
|
1268
|
-
discovery: backendPluginApi.coreServices.discovery,
|
|
1269
|
-
tokenManager: backendPluginApi.coreServices.tokenManager
|
|
1270
|
-
},
|
|
1271
|
-
async factory({ config }) {
|
|
1272
|
-
return async ({ discovery, tokenManager }) => {
|
|
1273
|
-
return pluginPermissionNode.ServerPermissionClient.fromConfig(config, {
|
|
1274
|
-
discovery,
|
|
1275
|
-
tokenManager
|
|
1276
|
-
});
|
|
1277
|
-
};
|
|
1278
|
-
}
|
|
1279
|
-
});
|
|
1280
|
-
|
|
1281
1344
|
const schedulerFactory = backendPluginApi.createServiceFactory({
|
|
1282
1345
|
service: backendPluginApi.coreServices.scheduler,
|
|
1283
1346
|
deps: {
|
|
1284
|
-
|
|
1285
|
-
|
|
1347
|
+
plugin: backendPluginApi.coreServices.pluginMetadata,
|
|
1348
|
+
databaseManager: backendPluginApi.coreServices.database,
|
|
1349
|
+
logger: backendPluginApi.coreServices.logger
|
|
1286
1350
|
},
|
|
1287
|
-
async factory(
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1351
|
+
async factory() {
|
|
1352
|
+
return async ({ plugin, databaseManager, logger }) => {
|
|
1353
|
+
return backendTasks.TaskScheduler.forPlugin({
|
|
1354
|
+
pluginId: plugin.getId(),
|
|
1355
|
+
databaseManager,
|
|
1356
|
+
logger: backendCommon.loggerToWinstonLogger(logger)
|
|
1357
|
+
});
|
|
1291
1358
|
};
|
|
1292
1359
|
}
|
|
1293
1360
|
});
|
|
@@ -1296,14 +1363,13 @@ const tokenManagerFactory = backendPluginApi.createServiceFactory({
|
|
|
1296
1363
|
service: backendPluginApi.coreServices.tokenManager,
|
|
1297
1364
|
deps: {
|
|
1298
1365
|
config: backendPluginApi.coreServices.config,
|
|
1299
|
-
logger: backendPluginApi.coreServices.
|
|
1366
|
+
logger: backendPluginApi.coreServices.rootLogger
|
|
1300
1367
|
},
|
|
1301
|
-
async factory() {
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
};
|
|
1368
|
+
async factory({ config, logger }) {
|
|
1369
|
+
const tokenManager = backendCommon.ServerTokenManager.fromConfig(config, {
|
|
1370
|
+
logger
|
|
1371
|
+
});
|
|
1372
|
+
return async () => tokenManager;
|
|
1307
1373
|
}
|
|
1308
1374
|
});
|
|
1309
1375
|
|
|
@@ -1323,29 +1389,7 @@ const urlReaderFactory = backendPluginApi.createServiceFactory({
|
|
|
1323
1389
|
}
|
|
1324
1390
|
});
|
|
1325
1391
|
|
|
1326
|
-
|
|
1327
|
-
service: backendPluginApi.coreServices.lifecycle,
|
|
1328
|
-
deps: {
|
|
1329
|
-
logger: backendPluginApi.coreServices.logger,
|
|
1330
|
-
rootLifecycle: backendPluginApi.coreServices.rootLifecycle,
|
|
1331
|
-
pluginMetadata: backendPluginApi.coreServices.pluginMetadata
|
|
1332
|
-
},
|
|
1333
|
-
async factory({ rootLifecycle }) {
|
|
1334
|
-
return async ({ logger, pluginMetadata }) => {
|
|
1335
|
-
const plugin = pluginMetadata.getId();
|
|
1336
|
-
return {
|
|
1337
|
-
addShutdownHook(options) {
|
|
1338
|
-
var _a, _b;
|
|
1339
|
-
rootLifecycle.addShutdownHook({
|
|
1340
|
-
...options,
|
|
1341
|
-
logger: (_b = (_a = options.logger) == null ? void 0 : _a.child({ plugin })) != null ? _b : logger
|
|
1342
|
-
});
|
|
1343
|
-
}
|
|
1344
|
-
};
|
|
1345
|
-
};
|
|
1346
|
-
}
|
|
1347
|
-
});
|
|
1348
|
-
|
|
1392
|
+
exports.DefaultRootHttpRouter = DefaultRootHttpRouter;
|
|
1349
1393
|
exports.MiddlewareFactory = MiddlewareFactory;
|
|
1350
1394
|
exports.cacheFactory = cacheFactory;
|
|
1351
1395
|
exports.configFactory = configFactory;
|
|
@@ -1354,6 +1398,7 @@ exports.createSpecializedBackend = createSpecializedBackend;
|
|
|
1354
1398
|
exports.databaseFactory = databaseFactory;
|
|
1355
1399
|
exports.discoveryFactory = discoveryFactory;
|
|
1356
1400
|
exports.httpRouterFactory = httpRouterFactory;
|
|
1401
|
+
exports.identityFactory = identityFactory;
|
|
1357
1402
|
exports.lifecycleFactory = lifecycleFactory;
|
|
1358
1403
|
exports.loggerFactory = loggerFactory;
|
|
1359
1404
|
exports.permissionsFactory = permissionsFactory;
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/http/config.ts","../src/http/getGeneratedCertificate.ts","../src/http/createHttpServer.ts","../src/http/readHelmetOptions.ts","../src/http/readCorsOptions.ts","../src/http/MiddlewareFactory.ts","../src/services/implementations/rootLifecycleService.ts","../src/wiring/BackendInitializer.ts","../src/wiring/ServiceRegistry.ts","../src/wiring/BackstageBackend.ts","../src/wiring/createSpecializedBackend.ts","../src/services/implementations/httpRouter/httpRouterFactory.ts","../src/services/implementations/rootHttpRouter/RestrictedIndexedRouter.ts","../src/services/implementations/rootHttpRouter/rootHttpRouterFactory.ts","../src/services/implementations/cacheService.ts","../src/services/implementations/configService.ts","../src/services/implementations/databaseService.ts","../src/services/implementations/discoveryService.ts","../src/services/implementations/loggerService.ts","../src/services/implementations/rootLoggerService.ts","../src/services/implementations/permissionsService.ts","../src/services/implementations/schedulerService.ts","../src/services/implementations/tokenManagerService.ts","../src/services/implementations/urlReaderService.ts","../src/services/implementations/lifecycleService.ts"],"sourcesContent":["/*\n * Copyright 2023 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 { Config } from '@backstage/config';\nimport { HttpServerOptions } from './types';\n\nconst DEFAULT_PORT = 7007;\nconst DEFAULT_HOST = '';\n\n/**\n * Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.\n *\n * @public\n * @remarks\n *\n * The provided configuration object should contain the `listen` and\n * additional keys directly.\n *\n * @example\n * ```ts\n * const opts = readHttpServerOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHttpServerOptions(config?: Config): HttpServerOptions {\n return {\n listen: readHttpListenOptions(config),\n https: readHttpsOptions(config),\n };\n}\n\nfunction readHttpListenOptions(config?: Config): HttpServerOptions['listen'] {\n const listen = config?.getOptional('listen');\n if (typeof listen === 'string') {\n const parts = String(listen).split(':');\n const port = parseInt(parts[parts.length - 1], 10);\n if (!isNaN(port)) {\n if (parts.length === 1) {\n return { port, host: DEFAULT_HOST };\n }\n if (parts.length === 2) {\n return { host: parts[0], port };\n }\n }\n throw new Error(\n `Unable to parse listen address ${listen}, expected <port> or <host>:<port>`,\n );\n }\n\n // Workaround to allow empty string\n const host = config?.getOptional('listen.host') ?? DEFAULT_HOST;\n if (typeof host !== 'string') {\n config?.getOptionalString('listen.host'); // will throw\n throw new Error('unreachable');\n }\n\n return {\n port: config?.getOptionalNumber('listen.port') ?? DEFAULT_PORT,\n host,\n };\n}\n\nfunction readHttpsOptions(config?: Config): HttpServerOptions['https'] {\n const https = config?.getOptional('https');\n if (https === true) {\n const baseUrl = config!.getString('baseUrl');\n let hostname;\n try {\n hostname = new URL(baseUrl).hostname;\n } catch (error) {\n throw new Error(`Invalid baseUrl \"${baseUrl}\"`);\n }\n\n return { certificate: { type: 'generated', hostname } };\n }\n\n const cc = config?.getOptionalConfig('https');\n if (!cc) {\n return undefined;\n }\n\n return {\n certificate: {\n type: 'plain',\n cert: cc.getString('certificate.cert'),\n key: cc.getString('certificate.key'),\n },\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 fs from 'fs-extra';\nimport { resolve as resolvePath, dirname } from 'path';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport forge from 'node-forge';\n\nconst FIVE_DAYS_IN_MS = 5 * 24 * 60 * 60 * 1000;\n\nconst IP_HOSTNAME_REGEX = /:|^\\d+\\.\\d+\\.\\d+\\.\\d+$/;\n\nexport async function getGeneratedCertificate(\n hostname: string,\n logger: LoggerService,\n) {\n const hasModules = await fs.pathExists('node_modules');\n let certPath;\n if (hasModules) {\n certPath = resolvePath(\n 'node_modules/.cache/backstage-backend/dev-cert.pem',\n );\n await fs.ensureDir(dirname(certPath));\n } else {\n certPath = resolvePath('.dev-cert.pem');\n }\n\n if (await fs.pathExists(certPath)) {\n try {\n const cert = await fs.readFile(certPath);\n\n const crt = forge.pki.certificateFromPem(cert.toString());\n const remainingMs = crt.validity.notAfter.getTime() - Date.now();\n if (remainingMs > FIVE_DAYS_IN_MS) {\n logger.info('Using existing self-signed certificate');\n return {\n key: cert,\n cert,\n };\n }\n } catch (error) {\n logger.warn(`Unable to use existing self-signed certificate, ${error}`);\n }\n }\n\n logger.info('Generating new self-signed certificate');\n const newCert = await generateCertificate(hostname);\n await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');\n return newCert;\n}\n\nasync function generateCertificate(hostname: string) {\n const attributes = [\n {\n name: 'commonName',\n value: 'dev-cert',\n },\n ];\n\n const sans = [\n {\n type: 2, // DNS\n value: 'localhost',\n },\n {\n type: 2,\n value: 'localhost.localdomain',\n },\n {\n type: 2,\n value: '[::1]',\n },\n {\n type: 7, // IP\n ip: '127.0.0.1',\n },\n {\n type: 7,\n ip: 'fe80::1',\n },\n ];\n\n // Add hostname from backend.baseUrl if it doesn't already exist in our list of SANs\n if (!sans.find(({ value, ip }) => value === hostname || ip === hostname)) {\n sans.push(\n IP_HOSTNAME_REGEX.test(hostname)\n ? {\n type: 7,\n ip: hostname,\n }\n : {\n type: 2,\n value: hostname,\n },\n );\n }\n\n const params = {\n algorithm: 'sha256',\n keySize: 2048,\n days: 30,\n extensions: [\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true,\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n timeStamping: true,\n },\n {\n name: 'subjectAltName',\n altNames: sans,\n },\n ],\n };\n\n return new Promise<{ key: string; cert: string }>((resolve, reject) =>\n require('selfsigned').generate(\n attributes,\n params,\n (err: Error, bundle: { private: string; cert: string }) => {\n if (err) {\n reject(err);\n } else {\n resolve({ key: bundle.private, cert: bundle.cert });\n }\n },\n ),\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 * as http from 'http';\nimport * as https from 'https';\nimport stoppableServer from 'stoppable';\nimport { RequestListener } from 'http';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { HttpServerOptions, ExtendedHttpServer } from './types';\nimport { getGeneratedCertificate } from './getGeneratedCertificate';\n\n/**\n * Creates a Node.js HTTP or HTTPS server instance.\n *\n * @public\n */\nexport async function createHttpServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<ExtendedHttpServer> {\n const server = await createServer(listener, options, deps);\n\n const stopper = stoppableServer(server, 0);\n // The stopper here is actually the server itself, so if we try\n // to call stopper.stop() down in the stop implementation, we'll\n // be calling ourselves.\n const stopServer = stopper.stop.bind(stopper);\n\n return Object.assign(server, {\n start() {\n return new Promise<void>((resolve, reject) => {\n const handleStartupError = (error: Error) => {\n server.close();\n reject(error);\n };\n\n server.on('error', handleStartupError);\n\n const { host, port } = options.listen;\n server.listen(port, host, () => {\n server.off('error', handleStartupError);\n deps.logger.info(`Listening on ${host}:${port}`);\n resolve();\n });\n });\n },\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n stopServer((error?: Error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n },\n\n port() {\n const address = server.address();\n if (typeof address === 'string' || address === null) {\n throw new Error(`Unexpected server address '${address}'`);\n }\n return address.port;\n },\n });\n}\n\nasync function createServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<http.Server> {\n if (options.https) {\n const { certificate } = options.https;\n if (certificate.type === 'generated') {\n const credentials = await getGeneratedCertificate(\n certificate.hostname,\n deps.logger,\n );\n return https.createServer(credentials, listener);\n }\n return https.createServer(certificate, listener);\n }\n\n return http.createServer(listener);\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 { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport { HelmetOptions } from 'helmet';\nimport { ContentSecurityPolicyOptions } from 'helmet/dist/types/middlewares/content-security-policy';\n\n/**\n * Attempts to read Helmet options from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A Helmet options object, or undefined if no Helmet configuration is present.\n *\n * @example\n * ```ts\n * const helmetOptions = readHelmetOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHelmetOptions(config?: Config): HelmetOptions {\n const cspOptions = readCspDirectives(config);\n return {\n contentSecurityPolicy: {\n useDefaults: false,\n directives: applyCspDirectives(cspOptions),\n },\n // These are all disabled in order to maintain backwards compatibility\n // when bumping helmet v5. We can't enable these by default because\n // there is no way for users to configure them.\n // TODO(Rugvip): We should give control of this setup to consumers\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n };\n}\n\ntype CspDirectives = Record<string, string[] | false> | undefined;\n\n/**\n * Attempts to read a CSP directives from the backend configuration object.\n *\n * @example\n * ```yaml\n * backend:\n * csp:\n * connect-src: [\"'self'\", 'http:', 'https:']\n * upgrade-insecure-requests: false\n * ```\n */\nfunction readCspDirectives(config?: Config): CspDirectives {\n const cc = config?.getOptionalConfig('csp');\n if (!cc) {\n return undefined;\n }\n\n const result: Record<string, string[] | false> = {};\n for (const key of cc.keys()) {\n if (cc.get(key) === false) {\n result[key] = false;\n } else {\n result[key] = cc.getStringArray(key);\n }\n }\n\n return result;\n}\n\nexport function applyCspDirectives(\n directives: CspDirectives,\n): ContentSecurityPolicyOptions['directives'] {\n const result: ContentSecurityPolicyOptions['directives'] =\n helmet.contentSecurityPolicy.getDefaultDirectives();\n\n // TODO(Rugvip): We currently use non-precompiled AJV for validation in the frontend, which uses eval.\n // It should be replaced by any other solution that doesn't require unsafe-eval.\n result['script-src'] = [\"'self'\", \"'unsafe-eval'\"];\n\n // TODO(Rugvip): This is removed so that we maintained backwards compatibility\n // when bumping to helmet v5, we could remove this as well as\n // skip setting `useDefaults: false` in the future.\n delete result['form-action'];\n\n if (directives) {\n for (const [key, value] of Object.entries(directives)) {\n if (value === false) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n }\n\n return result;\n}\n","/*\n * Copyright 2023 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 { Config } from '@backstage/config';\nimport { CorsOptions } from 'cors';\nimport { Minimatch } from 'minimatch';\n\n/**\n * Attempts to read a CORS options object from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A CORS options object, or undefined if no cors configuration is present.\n *\n * @example\n * ```ts\n * const corsOptions = readCorsOptions(config.getConfig('backend'));\n * ```\n */\nexport function readCorsOptions(config?: Config): CorsOptions {\n const cc = config?.getOptionalConfig('cors');\n if (!cc) {\n return { origin: false }; // Disable CORS\n }\n\n return {\n origin: createCorsOriginMatcher(readStringArray(cc, 'origin')),\n methods: readStringArray(cc, 'methods'),\n allowedHeaders: readStringArray(cc, 'allowedHeaders'),\n exposedHeaders: readStringArray(cc, 'exposedHeaders'),\n credentials: cc.getOptionalBoolean('credentials'),\n maxAge: cc.getOptionalNumber('maxAge'),\n preflightContinue: cc.getOptionalBoolean('preflightContinue'),\n optionsSuccessStatus: cc.getOptionalNumber('optionsSuccessStatus'),\n };\n}\n\nfunction readStringArray(config: Config, key: string): string[] | undefined {\n const value = config.getOptional(key);\n if (typeof value === 'string') {\n return [value];\n } else if (!value) {\n return undefined;\n }\n return config.getStringArray(key);\n}\n\nfunction createCorsOriginMatcher(allowedOriginPatterns: string[] | undefined) {\n if (!allowedOriginPatterns) {\n return undefined;\n }\n\n const allowedOriginMatchers = allowedOriginPatterns.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n );\n\n return (\n origin: string | undefined,\n callback: (\n err: Error | null,\n origin: boolean | string | RegExp | (boolean | string | RegExp)[],\n ) => void,\n ) => {\n return callback(\n null,\n allowedOriginMatchers.some(pattern => pattern.match(origin ?? '')),\n );\n };\n}\n","/*\n * Copyright 2023 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 { ConfigService, LoggerService } from '@backstage/backend-plugin-api';\nimport {\n Request,\n Response,\n ErrorRequestHandler,\n NextFunction,\n RequestHandler,\n} from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport morgan from 'morgan';\nimport compression from 'compression';\nimport { readHelmetOptions } from './readHelmetOptions';\nimport { readCorsOptions } from './readCorsOptions';\nimport {\n AuthenticationError,\n ConflictError,\n ErrorResponseBody,\n InputError,\n NotAllowedError,\n NotFoundError,\n NotModifiedError,\n serializeError,\n} from '@backstage/errors';\n\n/**\n * Options used to create a {@link MiddlewareFactory}.\n *\n * @public\n */\nexport interface MiddlewareFactoryOptions {\n config: ConfigService;\n logger: LoggerService;\n}\n\n/**\n * Options passed to the {@link MiddlewareFactory.error} middleware.\n *\n * @public\n */\nexport interface MiddlewareFactoryErrorOptions {\n /**\n * Whether error response bodies should show error stack traces or not.\n *\n * If not specified, by default shows stack traces only in development mode.\n */\n showStackTraces?: boolean;\n\n /**\n * Whether any 4xx errors should be logged or not.\n *\n * If not specified, default to only logging 5xx errors.\n */\n logAllErrors?: boolean;\n}\n\n/**\n * A utility to configure common middleware.\n *\n * @public\n */\nexport class MiddlewareFactory {\n #config: ConfigService;\n #logger: LoggerService;\n\n /**\n * Creates a new {@link MiddlewareFactory}.\n */\n static create(options: MiddlewareFactoryOptions) {\n return new MiddlewareFactory(options);\n }\n\n private constructor(options: MiddlewareFactoryOptions) {\n this.#config = options.config;\n this.#logger = options.logger;\n }\n\n /**\n * Returns a middleware that unconditionally produces a 404 error response.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the end of the chain, such\n * that it's the last one attempted after no other routes matched.\n *\n * @returns An Express request handler\n */\n notFound(): RequestHandler {\n return (_req: Request, res: Response) => {\n res.status(404).end();\n };\n }\n\n /**\n * Returns the compression middleware.\n *\n * @remarks\n *\n * The middleware will attempt to compress response bodies for all requests\n * that traverse through the middleware.\n */\n compression(): RequestHandler {\n return compression();\n }\n\n /**\n * Returns a request logging middleware.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the start of the chain, such\n * that it always logs requests whether they are \"caught\" by handlers farther\n * down or not.\n *\n * @returns An Express request handler\n */\n logging(): RequestHandler {\n const logger = this.#logger.child({\n type: 'incomingRequest',\n });\n\n return morgan('combined', {\n stream: {\n write(message: string) {\n logger.info(message.trimEnd());\n },\n },\n });\n }\n\n /**\n * Returns a middleware that implements the helmet library.\n *\n * @remarks\n *\n * This middleware applies security policies to incoming requests and outgoing\n * responses. It is configured using config keys such as `backend.csp`.\n *\n * @see {@link https://helmetjs.github.io/}\n *\n * @returns An Express request handler\n */\n helmet(): RequestHandler {\n return helmet(readHelmetOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements the cors library.\n *\n * @remarks\n *\n * This middleware handles CORS. It is configured using the config key\n * `backend.cors`.\n *\n * @see {@link https://github.com/expressjs/cors}\n *\n * @returns An Express request handler\n */\n cors(): RequestHandler {\n return cors(readCorsOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Express middleware to handle errors during request processing.\n *\n * @remarks\n *\n * This is commonly the very last middleware in the chain.\n *\n * Its primary purpose is not to do translation of business logic exceptions,\n * but rather to be a global catch-all for uncaught \"fatal\" errors that are\n * expected to result in a 500 error. However, it also does handle some common\n * error types (such as http-error exceptions, and the well-known error types\n * in the `@backstage/errors` package) and returns the enclosed status code\n * accordingly.\n *\n * It will also produce a response body with a serialized form of the error,\n * unless a previous handler already did send a body. See\n * {@link @backstage/errors#ErrorResponseBody} for the response shape used.\n *\n * @returns An Express error request handler\n */\n error(options: MiddlewareFactoryErrorOptions = {}): ErrorRequestHandler {\n const showStackTraces =\n options.showStackTraces ?? process.env.NODE_ENV === 'development';\n\n const logger = this.#logger.child({\n type: 'errorHandler',\n });\n\n return (error: Error, req: Request, res: Response, next: NextFunction) => {\n const statusCode = getStatusCode(error);\n if (options.logAllErrors || statusCode >= 500) {\n logger.error(`Request failed with status ${statusCode}`, error);\n }\n\n if (res.headersSent) {\n // If the headers have already been sent, do not send the response again\n // as this will throw an error in the backend.\n next(error);\n return;\n }\n\n const body: ErrorResponseBody = {\n error: serializeError(error, { includeStack: showStackTraces }),\n request: { method: req.method, url: req.url },\n response: { statusCode },\n };\n\n res.status(statusCode).json(body);\n };\n }\n}\n\nfunction getStatusCode(error: Error): number {\n // Look for common http library status codes\n const knownStatusCodeFields = ['statusCode', 'status'];\n for (const field of knownStatusCodeFields) {\n const statusCode = (error as any)[field];\n if (\n typeof statusCode === 'number' &&\n (statusCode | 0) === statusCode && // is whole integer\n statusCode >= 100 &&\n statusCode <= 599\n ) {\n return statusCode;\n }\n }\n\n // Handle well-known error types\n switch (error.name) {\n case NotModifiedError.name:\n return 304;\n case InputError.name:\n return 400;\n case AuthenticationError.name:\n return 401;\n case NotAllowedError.name:\n return 403;\n case NotFoundError.name:\n return 404;\n case ConflictError.name:\n return 409;\n default:\n break;\n }\n\n // Fall back to internal server error\n return 500;\n}\n","/*\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 {\n createServiceFactory,\n coreServices,\n LifecycleServiceShutdownHook,\n RootLifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\nconst CALLBACKS = ['SIGTERM', 'SIGINT', 'beforeExit'];\nexport class BackendLifecycleImpl implements RootLifecycleService {\n constructor(private readonly logger: LoggerService) {\n CALLBACKS.map(signal => process.on(signal, () => this.shutdown()));\n }\n\n #isCalled = false;\n #shutdownTasks: Array<LifecycleServiceShutdownHook> = [];\n\n addShutdownHook(options: LifecycleServiceShutdownHook): void {\n this.#shutdownTasks.push(options);\n }\n\n async shutdown(): Promise<void> {\n if (this.#isCalled) {\n return;\n }\n this.#isCalled = true;\n\n this.logger.info(`Running ${this.#shutdownTasks.length} shutdown tasks...`);\n await Promise.all(\n this.#shutdownTasks.map(async hook => {\n const { logger = this.logger } = hook;\n try {\n await hook.fn();\n logger.info(`Shutdown hook succeeded`);\n } catch (error) {\n logger.error(`Shutdown hook failed, ${error}`);\n }\n }),\n );\n }\n}\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n * @public */\nexport const rootLifecycleFactory = createServiceFactory({\n service: coreServices.rootLifecycle,\n deps: {\n logger: coreServices.rootLogger,\n },\n async factory({ logger }) {\n return new BackendLifecycleImpl(logger);\n },\n});\n","/*\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 {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n} from '@backstage/backend-plugin-api';\nimport { BackendLifecycleImpl } from '../services/implementations/rootLifecycleService';\nimport {\n BackendRegisterInit,\n EnumerableServiceHolder,\n ServiceOrExtensionPoint,\n} from './types';\n\nexport class BackendInitializer {\n #started = false;\n #features = new Map<BackendFeature, unknown>();\n #registerInits = new Array<BackendRegisterInit>();\n #extensionPoints = new Map<ExtensionPoint<unknown>, unknown>();\n #serviceHolder: EnumerableServiceHolder;\n\n constructor(serviceHolder: EnumerableServiceHolder) {\n this.#serviceHolder = serviceHolder;\n }\n\n async #getInitDeps(\n deps: { [name: string]: ServiceOrExtensionPoint },\n pluginId: string,\n ) {\n const result = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(deps)) {\n const extensionPoint = this.#extensionPoints.get(\n ref as ExtensionPoint<unknown>,\n );\n if (extensionPoint) {\n result.set(name, extensionPoint);\n } else {\n const impl = await this.#serviceHolder.get(\n ref as ServiceRef<unknown>,\n pluginId,\n );\n if (impl) {\n result.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No extension point or service available for the following ref(s): ${missing}`,\n );\n }\n\n return Object.fromEntries(result);\n }\n\n add<TOptions>(feature: BackendFeature, options?: TOptions) {\n if (this.#started) {\n throw new Error('feature can not be added after the backend has started');\n }\n this.#features.set(feature, options);\n }\n\n async start(): Promise<void> {\n if (this.#started) {\n throw new Error('Backend has already started');\n }\n this.#started = true;\n\n // Initialize all root scoped services\n for (const ref of this.#serviceHolder.getServiceRefs()) {\n if (ref.scope === 'root') {\n await this.#serviceHolder.get(ref, 'root');\n }\n }\n\n // Initialize all features\n for (const [feature] of this.#features) {\n const provides = new Set<ExtensionPoint<unknown>>();\n\n let registerInit: BackendRegisterInit | undefined = undefined;\n\n feature.register({\n registerExtensionPoint: (extensionPointRef, impl) => {\n if (registerInit) {\n throw new Error('registerExtensionPoint called after registerInit');\n }\n if (this.#extensionPoints.has(extensionPointRef)) {\n throw new Error(`API ${extensionPointRef.id} already registered`);\n }\n this.#extensionPoints.set(extensionPointRef, impl);\n provides.add(extensionPointRef);\n },\n registerInit: registerOptions => {\n if (registerInit) {\n throw new Error('registerInit must only be called once');\n }\n registerInit = {\n id: feature.id,\n provides,\n consumes: new Set(Object.values(registerOptions.deps)),\n deps: registerOptions.deps,\n init: registerOptions.init as BackendRegisterInit['init'],\n };\n },\n });\n\n if (!registerInit) {\n throw new Error(\n `registerInit was not called by register in ${feature.id}`,\n );\n }\n\n this.#registerInits.push(registerInit);\n }\n\n const orderedRegisterResults = this.#resolveInitOrder(this.#registerInits);\n\n for (const registerInit of orderedRegisterResults) {\n const deps = await this.#getInitDeps(registerInit.deps, registerInit.id);\n await registerInit.init(deps);\n }\n }\n\n #resolveInitOrder(registerInits: Array<BackendRegisterInit>) {\n let registerInitsToOrder = registerInits.slice();\n const orderedRegisterInits = new Array<BackendRegisterInit>();\n\n // TODO: Validate duplicates\n\n while (registerInitsToOrder.length > 0) {\n const toRemove = new Set<unknown>();\n\n for (const registerInit of registerInitsToOrder) {\n const unInitializedDependents = [];\n\n for (const provided of registerInit.provides) {\n if (\n registerInitsToOrder.some(\n init => init !== registerInit && init.consumes.has(provided),\n )\n ) {\n unInitializedDependents.push(provided);\n }\n }\n\n if (unInitializedDependents.length === 0) {\n orderedRegisterInits.push(registerInit);\n toRemove.add(registerInit);\n }\n }\n\n registerInitsToOrder = registerInitsToOrder.filter(r => !toRemove.has(r));\n }\n\n return orderedRegisterInits;\n }\n\n async stop(): Promise<void> {\n if (!this.#started) {\n return;\n }\n\n const lifecycleService = await this.#serviceHolder.get(\n coreServices.rootLifecycle,\n 'root',\n );\n\n // TODO(Rugvip): Find a better way to do this\n if (lifecycleService instanceof BackendLifecycleImpl) {\n await lifecycleService.shutdown();\n } else {\n throw new Error('Unexpected lifecycle service implementation');\n }\n }\n}\n","/*\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 {\n ServiceFactory,\n ServiceRef,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { stringifyError } from '@backstage/errors';\nimport { EnumerableServiceHolder } from './types';\n/**\n * Keep in sync with `@backstage/backend-plugin-api/src/services/system/types.ts`\n * @internal\n */\nexport type InternalServiceRef<T> = ServiceRef<T> & {\n __defaultFactory?: (\n service: ServiceRef<T>,\n ) => Promise<ServiceFactory<T> | (() => ServiceFactory<T>)>;\n};\n\nexport class ServiceRegistry implements EnumerableServiceHolder {\n readonly #providedFactories: Map<string, ServiceFactory>;\n readonly #loadedDefaultFactories: Map<Function, Promise<ServiceFactory>>;\n readonly #implementations: Map<\n ServiceFactory,\n {\n factoryFunc: Promise<\n (deps: { [name in string]: unknown }) => Promise<unknown>\n >;\n byPlugin: Map<string, Promise<unknown>>;\n }\n >;\n\n constructor(factories: Array<ServiceFactory<unknown>>) {\n this.#providedFactories = new Map(factories.map(f => [f.service.id, f]));\n this.#loadedDefaultFactories = new Map();\n this.#implementations = new Map();\n }\n\n #resolveFactory(\n ref: ServiceRef<unknown>,\n pluginId: string,\n ): Promise<ServiceFactory> | undefined {\n // Special case handling of the plugin metadata service, generating a custom factory for it each time\n if (ref.id === coreServices.pluginMetadata.id) {\n return Promise.resolve({\n scope: 'plugin',\n service: coreServices.pluginMetadata,\n deps: {},\n factory: async () => async () => ({\n getId() {\n return pluginId;\n },\n }),\n });\n }\n\n let resolvedFactory: Promise<ServiceFactory> | ServiceFactory | undefined =\n this.#providedFactories.get(ref.id);\n const { __defaultFactory: defaultFactory } =\n ref as InternalServiceRef<unknown>;\n if (!resolvedFactory && !defaultFactory) {\n return undefined;\n }\n\n if (!resolvedFactory) {\n let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory!);\n if (!loadedFactory) {\n loadedFactory = Promise.resolve()\n .then(() => defaultFactory!(ref))\n .then(f =>\n typeof f === 'function' ? f() : f,\n ) as Promise<ServiceFactory>;\n this.#loadedDefaultFactories.set(defaultFactory!, loadedFactory);\n }\n resolvedFactory = loadedFactory.catch(error => {\n throw new Error(\n `Failed to instantiate service '${\n ref.id\n }' because the default factory loader threw an error, ${stringifyError(\n error,\n )}`,\n );\n });\n }\n\n return Promise.resolve(resolvedFactory);\n }\n\n #separateMapForTheRootService = new Map<ServiceFactory, Promise<unknown>>();\n\n #checkForMissingDeps(factory: ServiceFactory, pluginId: string) {\n const missingDeps = Object.values(factory.deps).filter(ref => {\n if (ref.id === coreServices.pluginMetadata.id) {\n return false;\n }\n if (this.#providedFactories.get(ref.id)) {\n return false;\n }\n\n return !(ref as InternalServiceRef<unknown>).__defaultFactory;\n });\n\n if (missingDeps.length) {\n const missing = missingDeps.map(r => `'${r.id}'`).join(', ');\n throw new Error(\n `Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`,\n );\n }\n }\n\n getServiceRefs(): ServiceRef<unknown>[] {\n return Array.from(this.#providedFactories.values()).map(f => f.service);\n }\n\n get<T>(ref: ServiceRef<T>, pluginId: string): Promise<T> | undefined {\n return this.#resolveFactory(ref, pluginId)?.then(factory => {\n if (factory.scope === 'root') {\n let existing = this.#separateMapForTheRootService.get(factory);\n if (!existing) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope !== 'root') {\n throw new Error(\n `Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`,\n );\n }\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n\n existing = Promise.all(rootDeps).then(entries =>\n factory.factory(Object.fromEntries(entries)),\n );\n this.#separateMapForTheRootService.set(factory, existing);\n }\n return existing as Promise<T>;\n }\n\n let implementation = this.#implementations.get(factory);\n if (!implementation) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope === 'root') {\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n }\n\n implementation = {\n factoryFunc: Promise.all(rootDeps)\n .then(entries => factory.factory(Object.fromEntries(entries)))\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' because the top-level factory function threw an error, ${cause}`,\n );\n }),\n byPlugin: new Map(),\n };\n\n this.#implementations.set(factory, implementation);\n }\n\n let result = implementation.byPlugin.get(pluginId) as Promise<any>;\n if (!result) {\n const allDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n const target = this.get(serviceRef, pluginId)!;\n allDeps.push(target.then(impl => [name, impl]));\n }\n\n result = implementation.factoryFunc\n .then(func =>\n Promise.all(allDeps).then(entries =>\n func(Object.fromEntries(entries)),\n ),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`,\n );\n });\n implementation.byPlugin.set(pluginId, result);\n }\n\n return result;\n });\n }\n}\n","/*\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 { ServiceFactory, BackendFeature } from '@backstage/backend-plugin-api';\nimport { BackendInitializer } from './BackendInitializer';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport { Backend } from './types';\n\nexport class BackstageBackend implements Backend {\n #services: ServiceRegistry;\n #initializer: BackendInitializer;\n\n constructor(apiFactories: ServiceFactory[]) {\n this.#services = new ServiceRegistry(apiFactories);\n this.#initializer = new BackendInitializer(this.#services);\n }\n\n add(feature: BackendFeature): void {\n this.#initializer.add(feature);\n }\n\n async start(): Promise<void> {\n await this.#initializer.start();\n }\n\n async stop(): Promise<void> {\n await this.#initializer.stop();\n }\n}\n","/*\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 { coreServices } from '@backstage/backend-plugin-api';\nimport { BackstageBackend } from './BackstageBackend';\nimport { Backend, CreateSpecializedBackendOptions } from './types';\n\n/**\n * @public\n */\nexport function createSpecializedBackend(\n options: CreateSpecializedBackendOptions,\n): Backend {\n const services = options.services.map(sf =>\n typeof sf === 'function' ? sf() : sf,\n );\n\n const exists = new Set<string>();\n const duplicates = new Set<string>();\n for (const { service } of services) {\n if (exists.has(service.id)) {\n duplicates.add(service.id);\n } else {\n exists.add(service.id);\n }\n }\n if (duplicates.size > 0) {\n const ids = Array.from(duplicates).join(', ');\n throw new Error(`Duplicate service implementations provided for ${ids}`);\n }\n if (exists.has(coreServices.pluginMetadata.id)) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n return new BackstageBackend(services);\n}\n","/*\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 {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { Handler } from 'express';\n\n/**\n * @public\n */\nexport type HttpRouterFactoryOptions = {\n /**\n * A callback used to generate the path for each plugin, defaults to `/api/{pluginId}`.\n */\n getPath(pluginId: string): string;\n};\n\n/** @public */\nexport const httpRouterFactory = createServiceFactory({\n service: coreServices.httpRouter,\n deps: {\n plugin: coreServices.pluginMetadata,\n rootHttpRouter: coreServices.rootHttpRouter,\n },\n async factory({ rootHttpRouter }, options?: HttpRouterFactoryOptions) {\n const getPath = options?.getPath ?? (id => `/api/${id}`);\n\n return async ({ plugin }) => {\n const path = getPath(plugin.getId());\n return {\n use(handler: Handler) {\n rootHttpRouter.use(path, handler);\n },\n };\n };\n },\n});\n","/*\n * Copyright 2023 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 { RootHttpRouterService } from '@backstage/backend-plugin-api';\nimport { Handler, Router } from 'express';\n\nfunction normalizePath(path: string): string {\n return path.replace(/\\/*$/, '/');\n}\n\nexport class RestrictedIndexedRouter implements RootHttpRouterService {\n #indexPath?: false | string;\n\n #router = Router();\n #namedRoutes = Router();\n #indexRouter = Router();\n #existingPaths = new Array<string>();\n\n constructor(indexPath?: false | string) {\n this.#indexPath = indexPath;\n this.#router.use(this.#namedRoutes);\n this.#router.use(this.#indexRouter);\n }\n\n use(path: string, handler: Handler) {\n if (path.match(/^[/\\s]*$/)) {\n throw new Error(`Root router path may not be empty`);\n }\n const conflictingPath = this.#findConflictingPath(path);\n if (conflictingPath) {\n throw new Error(\n `Path ${path} conflicts with the existing path ${conflictingPath}`,\n );\n }\n this.#existingPaths.push(path);\n this.#namedRoutes.use(path, handler);\n\n if (this.#indexPath === path) {\n this.#indexRouter.use(handler);\n }\n }\n\n handler(): Handler {\n return this.#router;\n }\n\n #findConflictingPath(newPath: string): string | undefined {\n const normalizedNewPath = normalizePath(newPath);\n for (const path of this.#existingPaths) {\n const normalizedPath = normalizePath(path);\n if (normalizedPath.startsWith(normalizedNewPath)) {\n return path;\n }\n if (normalizedNewPath.startsWith(normalizedPath)) {\n return path;\n }\n }\n return undefined;\n }\n}\n","/*\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 {\n ConfigService,\n coreServices,\n createServiceFactory,\n LifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport express, { RequestHandler, Express } from 'express';\nimport {\n createHttpServer,\n MiddlewareFactory,\n readHttpServerOptions,\n} from '../../../http';\nimport { RestrictedIndexedRouter } from './RestrictedIndexedRouter';\n\n/**\n * @public\n */\nexport interface RootHttpRouterConfigureOptions {\n app: Express;\n middleware: MiddlewareFactory;\n routes: RequestHandler;\n config: ConfigService;\n logger: LoggerService;\n lifecycle: LifecycleService;\n}\n\n/**\n * @public\n */\nexport type RootHttpRouterFactoryOptions = {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app'\n */\n indexPath?: string | false;\n\n configure?(options: RootHttpRouterConfigureOptions): void;\n};\n\nfunction defaultConfigure({\n app,\n routes,\n middleware,\n}: RootHttpRouterConfigureOptions) {\n app.use(middleware.helmet());\n app.use(middleware.cors());\n app.use(middleware.compression());\n app.use(middleware.logging());\n app.use(routes);\n app.use(middleware.notFound());\n app.use(middleware.error());\n}\n\n/** @public */\nexport const rootHttpRouterFactory = createServiceFactory({\n service: coreServices.rootHttpRouter,\n deps: {\n config: coreServices.config,\n rootLogger: coreServices.rootLogger,\n lifecycle: coreServices.rootLifecycle,\n },\n async factory(\n { config, rootLogger, lifecycle },\n {\n indexPath,\n configure = defaultConfigure,\n }: RootHttpRouterFactoryOptions = {},\n ) {\n const router = new RestrictedIndexedRouter(indexPath ?? '/api/app');\n const logger = rootLogger.child({ service: 'rootHttpRouter' });\n\n const app = express();\n\n const middleware = MiddlewareFactory.create({ config, logger });\n\n configure({\n app,\n routes: router.handler(),\n middleware,\n config,\n logger,\n lifecycle,\n });\n\n const server = await createHttpServer(\n app,\n readHttpServerOptions(config.getOptionalConfig('backend')),\n { logger },\n );\n\n lifecycle.addShutdownHook({\n async fn() {\n await server.stop();\n },\n logger,\n });\n\n await server.start();\n\n return router;\n },\n});\n","/*\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 { CacheManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const cacheFactory = createServiceFactory({\n service: coreServices.cache,\n deps: {\n config: coreServices.config,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ config }) {\n const cacheManager = CacheManager.fromConfig(config);\n return async ({ plugin }) => {\n return cacheManager.forPlugin(plugin.getId());\n };\n },\n});\n","/*\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 {\n loadBackendConfig,\n loggerToWinstonLogger,\n} from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const configFactory = createServiceFactory({\n service: coreServices.config,\n deps: {\n logger: coreServices.rootLogger,\n },\n async factory({ logger }) {\n const config = await loadBackendConfig({\n argv: process.argv,\n logger: loggerToWinstonLogger(logger),\n });\n return config;\n },\n});\n","/*\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 { DatabaseManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const databaseFactory = createServiceFactory({\n service: coreServices.database,\n deps: {\n config: coreServices.config,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ config }) {\n const databaseManager = DatabaseManager.fromConfig(config);\n return async ({ plugin }) => {\n return databaseManager.forPlugin(plugin.getId());\n };\n },\n});\n","/*\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 { SingleHostDiscovery } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const discoveryFactory = createServiceFactory({\n service: coreServices.discovery,\n deps: {\n config: coreServices.config,\n },\n async factory({ config }) {\n const discovery = SingleHostDiscovery.fromConfig(config);\n return async () => {\n return discovery;\n };\n },\n});\n","/*\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 {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const loggerFactory = createServiceFactory({\n service: coreServices.logger,\n deps: {\n rootLogger: coreServices.rootLogger,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ rootLogger }) {\n return async ({ plugin }) => {\n return rootLogger.child({ plugin: plugin.getId() });\n };\n },\n});\n","/*\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 { createRootLogger } from '@backstage/backend-common';\nimport {\n createServiceFactory,\n LoggerService,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { LogMeta } from '@backstage/backend-plugin-api';\nimport { Logger as WinstonLogger } from 'winston';\n\nclass BackstageLogger implements LoggerService {\n static fromWinston(logger: WinstonLogger): BackstageLogger {\n return new BackstageLogger(logger);\n }\n\n private constructor(private readonly winston: WinstonLogger) {}\n\n error(message: string, meta?: LogMeta): void {\n this.winston.error(message, meta);\n }\n\n warn(message: string, meta?: LogMeta): void {\n this.winston.warn(message, meta);\n }\n\n info(message: string, meta?: LogMeta): void {\n this.winston.info(message, meta);\n }\n\n debug(message: string, meta?: LogMeta): void {\n this.winston.debug(message, meta);\n }\n\n child(meta: LogMeta): LoggerService {\n return new BackstageLogger(this.winston.child(meta));\n }\n}\n\n/** @public */\nexport const rootLoggerFactory = createServiceFactory({\n service: coreServices.rootLogger,\n deps: {},\n async factory() {\n return BackstageLogger.fromWinston(createRootLogger());\n },\n});\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerPermissionClient } from '@backstage/plugin-permission-node';\n\n/** @public */\nexport const permissionsFactory = createServiceFactory({\n service: coreServices.permissions,\n deps: {\n config: coreServices.config,\n discovery: coreServices.discovery,\n tokenManager: coreServices.tokenManager,\n },\n async factory({ config }) {\n return async ({ discovery, tokenManager }) => {\n return ServerPermissionClient.fromConfig(config, {\n discovery,\n tokenManager,\n });\n };\n },\n});\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { TaskScheduler } from '@backstage/backend-tasks';\n\n/** @public */\nexport const schedulerFactory = createServiceFactory({\n service: coreServices.scheduler,\n deps: {\n config: coreServices.config,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ config }) {\n const taskScheduler = TaskScheduler.fromConfig(config);\n return async ({ plugin }) => {\n return taskScheduler.forPlugin(plugin.getId());\n };\n },\n});\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n loggerToWinstonLogger,\n ServerTokenManager,\n} from '@backstage/backend-common';\n\n/** @public */\nexport const tokenManagerFactory = createServiceFactory({\n service: coreServices.tokenManager,\n deps: {\n config: coreServices.config,\n logger: coreServices.logger,\n },\n async factory() {\n return async ({ config, logger }) => {\n return ServerTokenManager.fromConfig(config, {\n logger: loggerToWinstonLogger(logger),\n });\n };\n },\n});\n","/*\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 { loggerToWinstonLogger, UrlReaders } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const urlReaderFactory = createServiceFactory({\n service: coreServices.urlReader,\n deps: {\n config: coreServices.config,\n logger: coreServices.logger,\n },\n async factory() {\n return async ({ config, logger }) => {\n return UrlReaders.default({\n config,\n logger: loggerToWinstonLogger(logger),\n });\n };\n },\n});\n","/*\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 */\nimport {\n createServiceFactory,\n coreServices,\n LifecycleServiceShutdownHook,\n} from '@backstage/backend-plugin-api';\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n * @public */\nexport const lifecycleFactory = createServiceFactory({\n service: coreServices.lifecycle,\n deps: {\n logger: coreServices.logger,\n rootLifecycle: coreServices.rootLifecycle,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ rootLifecycle }) {\n return async ({ logger, pluginMetadata }) => {\n const plugin = pluginMetadata.getId();\n return {\n addShutdownHook(options: LifecycleServiceShutdownHook): void {\n rootLifecycle.addShutdownHook({\n ...options,\n\n logger: options.logger?.child({ plugin }) ?? logger,\n });\n },\n };\n };\n },\n});\n"],"names":["fs","resolvePath","dirname","forge","stoppableServer","https","http","helmet","Minimatch","__privateAdd","__privateSet","compression","__privateGet","morgan","cors","serializeError","NotModifiedError","InputError","AuthenticationError","NotAllowedError","NotFoundError","ConflictError","createServiceFactory","coreServices","__privateMethod","stringifyError","Router","express","CacheManager","loadBackendConfig","loggerToWinstonLogger","DatabaseManager","SingleHostDiscovery","createRootLogger","ServerPermissionClient","TaskScheduler","ServerTokenManager","UrlReaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,YAAe,GAAA,IAAA,CAAA;AACrB,MAAM,YAAe,GAAA,EAAA,CAAA;AAgBd,SAAS,sBAAsB,MAAoC,EAAA;AACxE,EAAO,OAAA;AAAA,IACL,MAAA,EAAQ,sBAAsB,MAAM,CAAA;AAAA,IACpC,KAAA,EAAO,iBAAiB,MAAM,CAAA;AA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AA,GAAS,eAAe,KAAM,EAAA,CAAA;AACpC,MAAO,OAAA;AAAA,QACL,gBAAgB,OAA6C,EAAA;AAnCrE,UAAA,IAAA,EAAA,EAAA,EAAA,CAAA;AAoCU,UAAA,aAAA,CAAc,eAAgB,CAAA;AAAA,YAC5B,GAAG,OAAA;AAAA,YAEH,MAAA,EAAA,CAAQ,mBAAQ,MAAR,KAAA,IAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAAgB,MAAM,EAAE,MAAA,QAAxB,IAAqC,GAAA,EAAA,GAAA,MAAA;AAAA,WAC9C,CAAA,CAAA;AAAA,SACH;AAAA,OACF,CAAA;AAAA,KACF,CAAA;AAAA,GACF;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/http/config.ts","../src/http/getGeneratedCertificate.ts","../src/http/createHttpServer.ts","../src/http/readHelmetOptions.ts","../src/http/readCorsOptions.ts","../src/http/MiddlewareFactory.ts","../src/services/implementations/rootLifecycle/rootLifecycleFactory.ts","../src/wiring/BackendInitializer.ts","../src/wiring/ServiceRegistry.ts","../src/wiring/BackstageBackend.ts","../src/wiring/createSpecializedBackend.ts","../src/services/implementations/cache/cacheFactory.ts","../src/services/implementations/config/configFactory.ts","../src/services/implementations/database/databaseFactory.ts","../src/services/implementations/discovery/discoveryFactory.ts","../src/services/implementations/httpRouter/httpRouterFactory.ts","../src/services/implementations/identity/identityFactory.ts","../src/services/implementations/lifecycle/lifecycleFactory.ts","../src/services/implementations/logger/loggerFactory.ts","../src/services/implementations/permissions/permissionsFactory.ts","../src/services/implementations/rootHttpRouter/DefaultRootHttpRouter.ts","../src/services/implementations/rootHttpRouter/rootHttpRouterFactory.ts","../src/services/implementations/rootLogger/rootLoggerFactory.ts","../src/services/implementations/scheduler/schedulerFactory.ts","../src/services/implementations/tokenManager/tokenManagerFactory.ts","../src/services/implementations/urlReader/urlReaderFactory.ts"],"sourcesContent":["/*\n * Copyright 2023 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 { Config } from '@backstage/config';\nimport { HttpServerOptions } from './types';\n\nconst DEFAULT_PORT = 7007;\nconst DEFAULT_HOST = '';\n\n/**\n * Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.\n *\n * @public\n * @remarks\n *\n * The provided configuration object should contain the `listen` and\n * additional keys directly.\n *\n * @example\n * ```ts\n * const opts = readHttpServerOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHttpServerOptions(config?: Config): HttpServerOptions {\n return {\n listen: readHttpListenOptions(config),\n https: readHttpsOptions(config),\n };\n}\n\nfunction readHttpListenOptions(config?: Config): HttpServerOptions['listen'] {\n const listen = config?.getOptional('listen');\n if (typeof listen === 'string') {\n const parts = String(listen).split(':');\n const port = parseInt(parts[parts.length - 1], 10);\n if (!isNaN(port)) {\n if (parts.length === 1) {\n return { port, host: DEFAULT_HOST };\n }\n if (parts.length === 2) {\n return { host: parts[0], port };\n }\n }\n throw new Error(\n `Unable to parse listen address ${listen}, expected <port> or <host>:<port>`,\n );\n }\n\n // Workaround to allow empty string\n const host = config?.getOptional('listen.host') ?? DEFAULT_HOST;\n if (typeof host !== 'string') {\n config?.getOptionalString('listen.host'); // will throw\n throw new Error('unreachable');\n }\n\n return {\n port: config?.getOptionalNumber('listen.port') ?? DEFAULT_PORT,\n host,\n };\n}\n\nfunction readHttpsOptions(config?: Config): HttpServerOptions['https'] {\n const https = config?.getOptional('https');\n if (https === true) {\n const baseUrl = config!.getString('baseUrl');\n let hostname;\n try {\n hostname = new URL(baseUrl).hostname;\n } catch (error) {\n throw new Error(`Invalid baseUrl \"${baseUrl}\"`);\n }\n\n return { certificate: { type: 'generated', hostname } };\n }\n\n const cc = config?.getOptionalConfig('https');\n if (!cc) {\n return undefined;\n }\n\n return {\n certificate: {\n type: 'plain',\n cert: cc.getString('certificate.cert'),\n key: cc.getString('certificate.key'),\n },\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 fs from 'fs-extra';\nimport { resolve as resolvePath, dirname } from 'path';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport forge from 'node-forge';\n\nconst FIVE_DAYS_IN_MS = 5 * 24 * 60 * 60 * 1000;\n\nconst IP_HOSTNAME_REGEX = /:|^\\d+\\.\\d+\\.\\d+\\.\\d+$/;\n\nexport async function getGeneratedCertificate(\n hostname: string,\n logger: LoggerService,\n) {\n const hasModules = await fs.pathExists('node_modules');\n let certPath;\n if (hasModules) {\n certPath = resolvePath(\n 'node_modules/.cache/backstage-backend/dev-cert.pem',\n );\n await fs.ensureDir(dirname(certPath));\n } else {\n certPath = resolvePath('.dev-cert.pem');\n }\n\n if (await fs.pathExists(certPath)) {\n try {\n const cert = await fs.readFile(certPath);\n\n const crt = forge.pki.certificateFromPem(cert.toString());\n const remainingMs = crt.validity.notAfter.getTime() - Date.now();\n if (remainingMs > FIVE_DAYS_IN_MS) {\n logger.info('Using existing self-signed certificate');\n return {\n key: cert,\n cert,\n };\n }\n } catch (error) {\n logger.warn(`Unable to use existing self-signed certificate, ${error}`);\n }\n }\n\n logger.info('Generating new self-signed certificate');\n const newCert = await generateCertificate(hostname);\n await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');\n return newCert;\n}\n\nasync function generateCertificate(hostname: string) {\n const attributes = [\n {\n name: 'commonName',\n value: 'dev-cert',\n },\n ];\n\n const sans = [\n {\n type: 2, // DNS\n value: 'localhost',\n },\n {\n type: 2,\n value: 'localhost.localdomain',\n },\n {\n type: 2,\n value: '[::1]',\n },\n {\n type: 7, // IP\n ip: '127.0.0.1',\n },\n {\n type: 7,\n ip: 'fe80::1',\n },\n ];\n\n // Add hostname from backend.baseUrl if it doesn't already exist in our list of SANs\n if (!sans.find(({ value, ip }) => value === hostname || ip === hostname)) {\n sans.push(\n IP_HOSTNAME_REGEX.test(hostname)\n ? {\n type: 7,\n ip: hostname,\n }\n : {\n type: 2,\n value: hostname,\n },\n );\n }\n\n const params = {\n algorithm: 'sha256',\n keySize: 2048,\n days: 30,\n extensions: [\n {\n name: 'keyUsage',\n keyCertSign: true,\n digitalSignature: true,\n nonRepudiation: true,\n keyEncipherment: true,\n dataEncipherment: true,\n },\n {\n name: 'extKeyUsage',\n serverAuth: true,\n clientAuth: true,\n codeSigning: true,\n timeStamping: true,\n },\n {\n name: 'subjectAltName',\n altNames: sans,\n },\n ],\n };\n\n return new Promise<{ key: string; cert: string }>((resolve, reject) =>\n require('selfsigned').generate(\n attributes,\n params,\n (err: Error, bundle: { private: string; cert: string }) => {\n if (err) {\n reject(err);\n } else {\n resolve({ key: bundle.private, cert: bundle.cert });\n }\n },\n ),\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 * as http from 'http';\nimport * as https from 'https';\nimport stoppableServer from 'stoppable';\nimport { RequestListener } from 'http';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { HttpServerOptions, ExtendedHttpServer } from './types';\nimport { getGeneratedCertificate } from './getGeneratedCertificate';\n\n/**\n * Creates a Node.js HTTP or HTTPS server instance.\n *\n * @public\n */\nexport async function createHttpServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<ExtendedHttpServer> {\n const server = await createServer(listener, options, deps);\n\n const stopper = stoppableServer(server, 0);\n // The stopper here is actually the server itself, so if we try\n // to call stopper.stop() down in the stop implementation, we'll\n // be calling ourselves.\n const stopServer = stopper.stop.bind(stopper);\n\n return Object.assign(server, {\n start() {\n return new Promise<void>((resolve, reject) => {\n const handleStartupError = (error: Error) => {\n server.close();\n reject(error);\n };\n\n server.on('error', handleStartupError);\n\n const { host, port } = options.listen;\n server.listen(port, host, () => {\n server.off('error', handleStartupError);\n deps.logger.info(`Listening on ${host}:${port}`);\n resolve();\n });\n });\n },\n\n stop() {\n return new Promise<void>((resolve, reject) => {\n stopServer((error?: Error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n },\n\n port() {\n const address = server.address();\n if (typeof address === 'string' || address === null) {\n throw new Error(`Unexpected server address '${address}'`);\n }\n return address.port;\n },\n });\n}\n\nasync function createServer(\n listener: RequestListener,\n options: HttpServerOptions,\n deps: { logger: LoggerService },\n): Promise<http.Server> {\n if (options.https) {\n const { certificate } = options.https;\n if (certificate.type === 'generated') {\n const credentials = await getGeneratedCertificate(\n certificate.hostname,\n deps.logger,\n );\n return https.createServer(credentials, listener);\n }\n return https.createServer(certificate, listener);\n }\n\n return http.createServer(listener);\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 { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport { HelmetOptions } from 'helmet';\nimport { ContentSecurityPolicyOptions } from 'helmet/dist/types/middlewares/content-security-policy';\n\n/**\n * Attempts to read Helmet options from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A Helmet options object, or undefined if no Helmet configuration is present.\n *\n * @example\n * ```ts\n * const helmetOptions = readHelmetOptions(config.getConfig('backend'));\n * ```\n */\nexport function readHelmetOptions(config?: Config): HelmetOptions {\n const cspOptions = readCspDirectives(config);\n return {\n contentSecurityPolicy: {\n useDefaults: false,\n directives: applyCspDirectives(cspOptions),\n },\n // These are all disabled in order to maintain backwards compatibility\n // when bumping helmet v5. We can't enable these by default because\n // there is no way for users to configure them.\n // TODO(Rugvip): We should give control of this setup to consumers\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n originAgentCluster: false,\n };\n}\n\ntype CspDirectives = Record<string, string[] | false> | undefined;\n\n/**\n * Attempts to read a CSP directives from the backend configuration object.\n *\n * @example\n * ```yaml\n * backend:\n * csp:\n * connect-src: [\"'self'\", 'http:', 'https:']\n * upgrade-insecure-requests: false\n * ```\n */\nfunction readCspDirectives(config?: Config): CspDirectives {\n const cc = config?.getOptionalConfig('csp');\n if (!cc) {\n return undefined;\n }\n\n const result: Record<string, string[] | false> = {};\n for (const key of cc.keys()) {\n if (cc.get(key) === false) {\n result[key] = false;\n } else {\n result[key] = cc.getStringArray(key);\n }\n }\n\n return result;\n}\n\nexport function applyCspDirectives(\n directives: CspDirectives,\n): ContentSecurityPolicyOptions['directives'] {\n const result: ContentSecurityPolicyOptions['directives'] =\n helmet.contentSecurityPolicy.getDefaultDirectives();\n\n // TODO(Rugvip): We currently use non-precompiled AJV for validation in the frontend, which uses eval.\n // It should be replaced by any other solution that doesn't require unsafe-eval.\n result['script-src'] = [\"'self'\", \"'unsafe-eval'\"];\n\n // TODO(Rugvip): This is removed so that we maintained backwards compatibility\n // when bumping to helmet v5, we could remove this as well as\n // skip setting `useDefaults: false` in the future.\n delete result['form-action'];\n\n if (directives) {\n for (const [key, value] of Object.entries(directives)) {\n if (value === false) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n }\n\n return result;\n}\n","/*\n * Copyright 2023 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 { Config } from '@backstage/config';\nimport { CorsOptions } from 'cors';\nimport { Minimatch } from 'minimatch';\n\n/**\n * Attempts to read a CORS options object from the backend configuration object.\n *\n * @public\n * @param config - The backend configuration object.\n * @returns A CORS options object, or undefined if no cors configuration is present.\n *\n * @example\n * ```ts\n * const corsOptions = readCorsOptions(config.getConfig('backend'));\n * ```\n */\nexport function readCorsOptions(config?: Config): CorsOptions {\n const cc = config?.getOptionalConfig('cors');\n if (!cc) {\n return { origin: false }; // Disable CORS\n }\n\n return {\n origin: createCorsOriginMatcher(readStringArray(cc, 'origin')),\n methods: readStringArray(cc, 'methods'),\n allowedHeaders: readStringArray(cc, 'allowedHeaders'),\n exposedHeaders: readStringArray(cc, 'exposedHeaders'),\n credentials: cc.getOptionalBoolean('credentials'),\n maxAge: cc.getOptionalNumber('maxAge'),\n preflightContinue: cc.getOptionalBoolean('preflightContinue'),\n optionsSuccessStatus: cc.getOptionalNumber('optionsSuccessStatus'),\n };\n}\n\nfunction readStringArray(config: Config, key: string): string[] | undefined {\n const value = config.getOptional(key);\n if (typeof value === 'string') {\n return [value];\n } else if (!value) {\n return undefined;\n }\n return config.getStringArray(key);\n}\n\nfunction createCorsOriginMatcher(allowedOriginPatterns: string[] | undefined) {\n if (!allowedOriginPatterns) {\n return undefined;\n }\n\n const allowedOriginMatchers = allowedOriginPatterns.map(\n pattern => new Minimatch(pattern, { nocase: true, noglobstar: true }),\n );\n\n return (\n origin: string | undefined,\n callback: (\n err: Error | null,\n origin: boolean | string | RegExp | (boolean | string | RegExp)[],\n ) => void,\n ) => {\n return callback(\n null,\n allowedOriginMatchers.some(pattern => pattern.match(origin ?? '')),\n );\n };\n}\n","/*\n * Copyright 2023 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 { ConfigService, LoggerService } from '@backstage/backend-plugin-api';\nimport {\n Request,\n Response,\n ErrorRequestHandler,\n NextFunction,\n RequestHandler,\n} from 'express';\nimport cors from 'cors';\nimport helmet from 'helmet';\nimport morgan from 'morgan';\nimport compression from 'compression';\nimport { readHelmetOptions } from './readHelmetOptions';\nimport { readCorsOptions } from './readCorsOptions';\nimport {\n AuthenticationError,\n ConflictError,\n ErrorResponseBody,\n InputError,\n NotAllowedError,\n NotFoundError,\n NotModifiedError,\n serializeError,\n} from '@backstage/errors';\n\n/**\n * Options used to create a {@link MiddlewareFactory}.\n *\n * @public\n */\nexport interface MiddlewareFactoryOptions {\n config: ConfigService;\n logger: LoggerService;\n}\n\n/**\n * Options passed to the {@link MiddlewareFactory.error} middleware.\n *\n * @public\n */\nexport interface MiddlewareFactoryErrorOptions {\n /**\n * Whether error response bodies should show error stack traces or not.\n *\n * If not specified, by default shows stack traces only in development mode.\n */\n showStackTraces?: boolean;\n\n /**\n * Whether any 4xx errors should be logged or not.\n *\n * If not specified, default to only logging 5xx errors.\n */\n logAllErrors?: boolean;\n}\n\n/**\n * A utility to configure common middleware.\n *\n * @public\n */\nexport class MiddlewareFactory {\n #config: ConfigService;\n #logger: LoggerService;\n\n /**\n * Creates a new {@link MiddlewareFactory}.\n */\n static create(options: MiddlewareFactoryOptions) {\n return new MiddlewareFactory(options);\n }\n\n private constructor(options: MiddlewareFactoryOptions) {\n this.#config = options.config;\n this.#logger = options.logger;\n }\n\n /**\n * Returns a middleware that unconditionally produces a 404 error response.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the end of the chain, such\n * that it's the last one attempted after no other routes matched.\n *\n * @returns An Express request handler\n */\n notFound(): RequestHandler {\n return (_req: Request, res: Response) => {\n res.status(404).end();\n };\n }\n\n /**\n * Returns the compression middleware.\n *\n * @remarks\n *\n * The middleware will attempt to compress response bodies for all requests\n * that traverse through the middleware.\n */\n compression(): RequestHandler {\n return compression();\n }\n\n /**\n * Returns a request logging middleware.\n *\n * @remarks\n *\n * Typically you want to place this middleware at the start of the chain, such\n * that it always logs requests whether they are \"caught\" by handlers farther\n * down or not.\n *\n * @returns An Express request handler\n */\n logging(): RequestHandler {\n const logger = this.#logger.child({\n type: 'incomingRequest',\n });\n\n return morgan('combined', {\n stream: {\n write(message: string) {\n logger.info(message.trimEnd());\n },\n },\n });\n }\n\n /**\n * Returns a middleware that implements the helmet library.\n *\n * @remarks\n *\n * This middleware applies security policies to incoming requests and outgoing\n * responses. It is configured using config keys such as `backend.csp`.\n *\n * @see {@link https://helmetjs.github.io/}\n *\n * @returns An Express request handler\n */\n helmet(): RequestHandler {\n return helmet(readHelmetOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Returns a middleware that implements the cors library.\n *\n * @remarks\n *\n * This middleware handles CORS. It is configured using the config key\n * `backend.cors`.\n *\n * @see {@link https://github.com/expressjs/cors}\n *\n * @returns An Express request handler\n */\n cors(): RequestHandler {\n return cors(readCorsOptions(this.#config.getOptionalConfig('backend')));\n }\n\n /**\n * Express middleware to handle errors during request processing.\n *\n * @remarks\n *\n * This is commonly the very last middleware in the chain.\n *\n * Its primary purpose is not to do translation of business logic exceptions,\n * but rather to be a global catch-all for uncaught \"fatal\" errors that are\n * expected to result in a 500 error. However, it also does handle some common\n * error types (such as http-error exceptions, and the well-known error types\n * in the `@backstage/errors` package) and returns the enclosed status code\n * accordingly.\n *\n * It will also produce a response body with a serialized form of the error,\n * unless a previous handler already did send a body. See\n * {@link @backstage/errors#ErrorResponseBody} for the response shape used.\n *\n * @returns An Express error request handler\n */\n error(options: MiddlewareFactoryErrorOptions = {}): ErrorRequestHandler {\n const showStackTraces =\n options.showStackTraces ?? process.env.NODE_ENV === 'development';\n\n const logger = this.#logger.child({\n type: 'errorHandler',\n });\n\n return (error: Error, req: Request, res: Response, next: NextFunction) => {\n const statusCode = getStatusCode(error);\n if (options.logAllErrors || statusCode >= 500) {\n logger.error(`Request failed with status ${statusCode}`, error);\n }\n\n if (res.headersSent) {\n // If the headers have already been sent, do not send the response again\n // as this will throw an error in the backend.\n next(error);\n return;\n }\n\n const body: ErrorResponseBody = {\n error: serializeError(error, { includeStack: showStackTraces }),\n request: { method: req.method, url: req.url },\n response: { statusCode },\n };\n\n res.status(statusCode).json(body);\n };\n }\n}\n\nfunction getStatusCode(error: Error): number {\n // Look for common http library status codes\n const knownStatusCodeFields = ['statusCode', 'status'];\n for (const field of knownStatusCodeFields) {\n const statusCode = (error as any)[field];\n if (\n typeof statusCode === 'number' &&\n (statusCode | 0) === statusCode && // is whole integer\n statusCode >= 100 &&\n statusCode <= 599\n ) {\n return statusCode;\n }\n }\n\n // Handle well-known error types\n switch (error.name) {\n case NotModifiedError.name:\n return 304;\n case InputError.name:\n return 400;\n case AuthenticationError.name:\n return 401;\n case NotAllowedError.name:\n return 403;\n case NotFoundError.name:\n return 404;\n case ConflictError.name:\n return 409;\n default:\n break;\n }\n\n // Fall back to internal server error\n return 500;\n}\n","/*\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 {\n createServiceFactory,\n coreServices,\n LifecycleServiceShutdownHook,\n RootLifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\n\nconst CALLBACKS = ['SIGTERM', 'SIGINT', 'beforeExit'];\nexport class BackendLifecycleImpl implements RootLifecycleService {\n constructor(private readonly logger: LoggerService) {\n CALLBACKS.map(signal => process.on(signal, () => this.shutdown()));\n }\n\n #isCalled = false;\n #shutdownTasks: Array<LifecycleServiceShutdownHook> = [];\n\n addShutdownHook(options: LifecycleServiceShutdownHook): void {\n this.#shutdownTasks.push(options);\n }\n\n async shutdown(): Promise<void> {\n if (this.#isCalled) {\n return;\n }\n this.#isCalled = true;\n\n this.logger.info(`Running ${this.#shutdownTasks.length} shutdown tasks...`);\n await Promise.all(\n this.#shutdownTasks.map(async hook => {\n const { logger = this.logger } = hook;\n try {\n await hook.fn();\n logger.info(`Shutdown hook succeeded`);\n } catch (error) {\n logger.error(`Shutdown hook failed, ${error}`);\n }\n }),\n );\n }\n}\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n * @public */\nexport const rootLifecycleFactory = createServiceFactory({\n service: coreServices.rootLifecycle,\n deps: {\n logger: coreServices.rootLogger,\n },\n async factory({ logger }) {\n return new BackendLifecycleImpl(logger);\n },\n});\n","/*\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 {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n} from '@backstage/backend-plugin-api';\nimport { BackendLifecycleImpl } from '../services/implementations/rootLifecycle/rootLifecycleFactory';\nimport {\n BackendRegisterInit,\n EnumerableServiceHolder,\n ServiceOrExtensionPoint,\n} from './types';\n\nexport class BackendInitializer {\n #started = false;\n #features = new Map<BackendFeature, unknown>();\n #registerInits = new Array<BackendRegisterInit>();\n #extensionPoints = new Map<ExtensionPoint<unknown>, unknown>();\n #serviceHolder: EnumerableServiceHolder;\n\n constructor(serviceHolder: EnumerableServiceHolder) {\n this.#serviceHolder = serviceHolder;\n }\n\n async #getInitDeps(\n deps: { [name: string]: ServiceOrExtensionPoint },\n pluginId: string,\n ) {\n const result = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(deps)) {\n const extensionPoint = this.#extensionPoints.get(\n ref as ExtensionPoint<unknown>,\n );\n if (extensionPoint) {\n result.set(name, extensionPoint);\n } else {\n const impl = await this.#serviceHolder.get(\n ref as ServiceRef<unknown>,\n pluginId,\n );\n if (impl) {\n result.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No extension point or service available for the following ref(s): ${missing}`,\n );\n }\n\n return Object.fromEntries(result);\n }\n\n add<TOptions>(feature: BackendFeature, options?: TOptions) {\n if (this.#started) {\n throw new Error('feature can not be added after the backend has started');\n }\n this.#features.set(feature, options);\n }\n\n async start(): Promise<void> {\n if (this.#started) {\n throw new Error('Backend has already started');\n }\n this.#started = true;\n\n // Initialize all root scoped services\n for (const ref of this.#serviceHolder.getServiceRefs()) {\n if (ref.scope === 'root') {\n await this.#serviceHolder.get(ref, 'root');\n }\n }\n\n // Initialize all features\n for (const [feature] of this.#features) {\n const provides = new Set<ExtensionPoint<unknown>>();\n\n let registerInit: BackendRegisterInit | undefined = undefined;\n\n feature.register({\n registerExtensionPoint: (extensionPointRef, impl) => {\n if (registerInit) {\n throw new Error('registerExtensionPoint called after registerInit');\n }\n if (this.#extensionPoints.has(extensionPointRef)) {\n throw new Error(`API ${extensionPointRef.id} already registered`);\n }\n this.#extensionPoints.set(extensionPointRef, impl);\n provides.add(extensionPointRef);\n },\n registerInit: registerOptions => {\n if (registerInit) {\n throw new Error('registerInit must only be called once');\n }\n registerInit = {\n id: feature.id,\n provides,\n consumes: new Set(Object.values(registerOptions.deps)),\n deps: registerOptions.deps,\n init: registerOptions.init as BackendRegisterInit['init'],\n };\n },\n });\n\n if (!registerInit) {\n throw new Error(\n `registerInit was not called by register in ${feature.id}`,\n );\n }\n\n this.#registerInits.push(registerInit);\n }\n\n const orderedRegisterResults = this.#resolveInitOrder(this.#registerInits);\n\n for (const registerInit of orderedRegisterResults) {\n const deps = await this.#getInitDeps(registerInit.deps, registerInit.id);\n await registerInit.init(deps);\n }\n }\n\n #resolveInitOrder(registerInits: Array<BackendRegisterInit>) {\n let registerInitsToOrder = registerInits.slice();\n const orderedRegisterInits = new Array<BackendRegisterInit>();\n\n // TODO: Validate duplicates\n\n while (registerInitsToOrder.length > 0) {\n const toRemove = new Set<unknown>();\n\n for (const registerInit of registerInitsToOrder) {\n const unInitializedDependents = [];\n\n for (const provided of registerInit.provides) {\n if (\n registerInitsToOrder.some(\n init => init !== registerInit && init.consumes.has(provided),\n )\n ) {\n unInitializedDependents.push(provided);\n }\n }\n\n if (unInitializedDependents.length === 0) {\n orderedRegisterInits.push(registerInit);\n toRemove.add(registerInit);\n }\n }\n\n registerInitsToOrder = registerInitsToOrder.filter(r => !toRemove.has(r));\n }\n\n return orderedRegisterInits;\n }\n\n async stop(): Promise<void> {\n if (!this.#started) {\n return;\n }\n\n const lifecycleService = await this.#serviceHolder.get(\n coreServices.rootLifecycle,\n 'root',\n );\n\n // TODO(Rugvip): Find a better way to do this\n if (lifecycleService instanceof BackendLifecycleImpl) {\n await lifecycleService.shutdown();\n } else {\n throw new Error('Unexpected lifecycle service implementation');\n }\n }\n}\n","/*\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 {\n ServiceFactory,\n ServiceRef,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { stringifyError } from '@backstage/errors';\nimport { EnumerableServiceHolder } from './types';\n/**\n * Keep in sync with `@backstage/backend-plugin-api/src/services/system/types.ts`\n * @internal\n */\nexport type InternalServiceRef<T> = ServiceRef<T> & {\n __defaultFactory?: (\n service: ServiceRef<T>,\n ) => Promise<ServiceFactory<T> | (() => ServiceFactory<T>)>;\n};\n\nexport class ServiceRegistry implements EnumerableServiceHolder {\n readonly #providedFactories: Map<string, ServiceFactory>;\n readonly #loadedDefaultFactories: Map<Function, Promise<ServiceFactory>>;\n readonly #implementations: Map<\n ServiceFactory,\n {\n factoryFunc: Promise<\n (deps: { [name in string]: unknown }) => Promise<unknown>\n >;\n byPlugin: Map<string, Promise<unknown>>;\n }\n >;\n\n constructor(factories: Array<ServiceFactory<unknown>>) {\n this.#providedFactories = new Map(factories.map(f => [f.service.id, f]));\n this.#loadedDefaultFactories = new Map();\n this.#implementations = new Map();\n }\n\n #resolveFactory(\n ref: ServiceRef<unknown>,\n pluginId: string,\n ): Promise<ServiceFactory> | undefined {\n // Special case handling of the plugin metadata service, generating a custom factory for it each time\n if (ref.id === coreServices.pluginMetadata.id) {\n return Promise.resolve({\n scope: 'plugin',\n service: coreServices.pluginMetadata,\n deps: {},\n factory: async () => async () => ({\n getId() {\n return pluginId;\n },\n }),\n });\n }\n\n let resolvedFactory: Promise<ServiceFactory> | ServiceFactory | undefined =\n this.#providedFactories.get(ref.id);\n const { __defaultFactory: defaultFactory } =\n ref as InternalServiceRef<unknown>;\n if (!resolvedFactory && !defaultFactory) {\n return undefined;\n }\n\n if (!resolvedFactory) {\n let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory!);\n if (!loadedFactory) {\n loadedFactory = Promise.resolve()\n .then(() => defaultFactory!(ref))\n .then(f =>\n typeof f === 'function' ? f() : f,\n ) as Promise<ServiceFactory>;\n this.#loadedDefaultFactories.set(defaultFactory!, loadedFactory);\n }\n resolvedFactory = loadedFactory.catch(error => {\n throw new Error(\n `Failed to instantiate service '${\n ref.id\n }' because the default factory loader threw an error, ${stringifyError(\n error,\n )}`,\n );\n });\n }\n\n return Promise.resolve(resolvedFactory);\n }\n\n #separateMapForTheRootService = new Map<ServiceFactory, Promise<unknown>>();\n\n #checkForMissingDeps(factory: ServiceFactory, pluginId: string) {\n const missingDeps = Object.values(factory.deps).filter(ref => {\n if (ref.id === coreServices.pluginMetadata.id) {\n return false;\n }\n if (this.#providedFactories.get(ref.id)) {\n return false;\n }\n\n return !(ref as InternalServiceRef<unknown>).__defaultFactory;\n });\n\n if (missingDeps.length) {\n const missing = missingDeps.map(r => `'${r.id}'`).join(', ');\n throw new Error(\n `Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`,\n );\n }\n }\n\n getServiceRefs(): ServiceRef<unknown>[] {\n return Array.from(this.#providedFactories.values()).map(f => f.service);\n }\n\n get<T>(ref: ServiceRef<T>, pluginId: string): Promise<T> | undefined {\n return this.#resolveFactory(ref, pluginId)?.then(factory => {\n if (factory.scope === 'root') {\n let existing = this.#separateMapForTheRootService.get(factory);\n if (!existing) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope !== 'root') {\n throw new Error(\n `Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`,\n );\n }\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n\n existing = Promise.all(rootDeps).then(entries =>\n factory.factory(Object.fromEntries(entries)),\n );\n this.#separateMapForTheRootService.set(factory, existing);\n }\n return existing as Promise<T>;\n }\n\n let implementation = this.#implementations.get(factory);\n if (!implementation) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope === 'root') {\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n }\n\n implementation = {\n factoryFunc: Promise.all(rootDeps)\n .then(entries => factory.factory(Object.fromEntries(entries)))\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' because the top-level factory function threw an error, ${cause}`,\n );\n }),\n byPlugin: new Map(),\n };\n\n this.#implementations.set(factory, implementation);\n }\n\n let result = implementation.byPlugin.get(pluginId) as Promise<any>;\n if (!result) {\n const allDeps = new Array<Promise<[name: string, impl: unknown]>>();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n const target = this.get(serviceRef, pluginId)!;\n allDeps.push(target.then(impl => [name, impl]));\n }\n\n result = implementation.factoryFunc\n .then(func =>\n Promise.all(allDeps).then(entries =>\n func(Object.fromEntries(entries)),\n ),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`,\n );\n });\n implementation.byPlugin.set(pluginId, result);\n }\n\n return result;\n });\n }\n}\n","/*\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 { ServiceFactory, BackendFeature } from '@backstage/backend-plugin-api';\nimport { BackendInitializer } from './BackendInitializer';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport { Backend } from './types';\n\nexport class BackstageBackend implements Backend {\n #services: ServiceRegistry;\n #initializer: BackendInitializer;\n\n constructor(apiFactories: ServiceFactory[]) {\n this.#services = new ServiceRegistry(apiFactories);\n this.#initializer = new BackendInitializer(this.#services);\n }\n\n add(feature: BackendFeature): void {\n this.#initializer.add(feature);\n }\n\n async start(): Promise<void> {\n await this.#initializer.start();\n }\n\n async stop(): Promise<void> {\n await this.#initializer.stop();\n }\n}\n","/*\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 { coreServices } from '@backstage/backend-plugin-api';\nimport { BackstageBackend } from './BackstageBackend';\nimport { Backend, CreateSpecializedBackendOptions } from './types';\n\n/**\n * @public\n */\nexport function createSpecializedBackend(\n options: CreateSpecializedBackendOptions,\n): Backend {\n const services = options.services.map(sf =>\n typeof sf === 'function' ? sf() : sf,\n );\n\n const exists = new Set<string>();\n const duplicates = new Set<string>();\n for (const { service } of services) {\n if (exists.has(service.id)) {\n duplicates.add(service.id);\n } else {\n exists.add(service.id);\n }\n }\n if (duplicates.size > 0) {\n const ids = Array.from(duplicates).join(', ');\n throw new Error(`Duplicate service implementations provided for ${ids}`);\n }\n if (exists.has(coreServices.pluginMetadata.id)) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n return new BackstageBackend(services);\n}\n","/*\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 { CacheManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const cacheFactory = createServiceFactory({\n service: coreServices.cache,\n deps: {\n config: coreServices.config,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ config }) {\n const cacheManager = CacheManager.fromConfig(config);\n return async ({ plugin }) => {\n return cacheManager.forPlugin(plugin.getId());\n };\n },\n});\n","/*\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 {\n loadBackendConfig,\n loggerToWinstonLogger,\n} from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const configFactory = createServiceFactory({\n service: coreServices.config,\n deps: {\n logger: coreServices.rootLogger,\n },\n async factory({ logger }) {\n const config = await loadBackendConfig({\n argv: process.argv,\n logger: loggerToWinstonLogger(logger),\n });\n return config;\n },\n});\n","/*\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 { DatabaseManager } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ConfigReader } from '@backstage/config';\n\n/** @public */\nexport const databaseFactory = createServiceFactory({\n service: coreServices.database,\n deps: {\n config: coreServices.config,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ config }) {\n const databaseManager = config.getOptional('backend.database')\n ? DatabaseManager.fromConfig(config)\n : DatabaseManager.fromConfig(\n new ConfigReader({\n backend: {\n database: { client: 'better-sqlite3', connection: ':memory:' },\n },\n }),\n );\n\n return async ({ plugin }) => {\n return databaseManager.forPlugin(plugin.getId());\n };\n },\n});\n","/*\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 { SingleHostDiscovery } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const discoveryFactory = createServiceFactory({\n service: coreServices.discovery,\n deps: {\n config: coreServices.config,\n },\n async factory({ config }) {\n const discovery = SingleHostDiscovery.fromConfig(config);\n return async () => {\n return discovery;\n };\n },\n});\n","/*\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 {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { Handler } from 'express';\n\n/**\n * @public\n */\nexport type HttpRouterFactoryOptions = {\n /**\n * A callback used to generate the path for each plugin, defaults to `/api/{pluginId}`.\n */\n getPath(pluginId: string): string;\n};\n\n/** @public */\nexport const httpRouterFactory = createServiceFactory({\n service: coreServices.httpRouter,\n deps: {\n plugin: coreServices.pluginMetadata,\n rootHttpRouter: coreServices.rootHttpRouter,\n },\n async factory({ rootHttpRouter }, options?: HttpRouterFactoryOptions) {\n const getPath = options?.getPath ?? (id => `/api/${id}`);\n\n return async ({ plugin }) => {\n const path = getPath(plugin.getId());\n return {\n use(handler: Handler) {\n rootHttpRouter.use(path, handler);\n },\n };\n };\n },\n});\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { DefaultIdentityClient } from '@backstage/plugin-auth-node';\n\n/**\n * An identity client options object which allows extra configurations\n *\n * @public\n */\nexport type IdentityFactoryOptions = {\n issuer?: string;\n\n /** JWS \"alg\" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.\n * More info on supported algorithms: https://github.com/panva/jose */\n algorithms?: string[];\n};\n\n/** @public */\nexport const identityFactory = createServiceFactory({\n service: coreServices.identity,\n deps: {\n config: coreServices.config,\n discovery: coreServices.discovery,\n tokenManager: coreServices.tokenManager,\n },\n\n async factory({}, options?: IdentityFactoryOptions) {\n return async ({ discovery }) => {\n return DefaultIdentityClient.create({ discovery, ...options });\n };\n },\n});\n","/*\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 */\nimport {\n createServiceFactory,\n coreServices,\n LifecycleServiceShutdownHook,\n} from '@backstage/backend-plugin-api';\n\n/**\n * Allows plugins to register shutdown hooks that are run when the process is about to exit.\n * @public */\nexport const lifecycleFactory = createServiceFactory({\n service: coreServices.lifecycle,\n deps: {\n logger: coreServices.logger,\n rootLifecycle: coreServices.rootLifecycle,\n pluginMetadata: coreServices.pluginMetadata,\n },\n async factory({ rootLifecycle }) {\n return async ({ logger, pluginMetadata }) => {\n const plugin = pluginMetadata.getId();\n return {\n addShutdownHook(options: LifecycleServiceShutdownHook): void {\n rootLifecycle.addShutdownHook({\n ...options,\n\n logger: options.logger?.child({ plugin }) ?? logger,\n });\n },\n };\n };\n },\n});\n","/*\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 {\n createServiceFactory,\n coreServices,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const loggerFactory = createServiceFactory({\n service: coreServices.logger,\n deps: {\n rootLogger: coreServices.rootLogger,\n plugin: coreServices.pluginMetadata,\n },\n async factory({ rootLogger }) {\n return async ({ plugin }) => {\n return rootLogger.child({ plugin: plugin.getId() });\n };\n },\n});\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerPermissionClient } from '@backstage/plugin-permission-node';\n\n/** @public */\nexport const permissionsFactory = createServiceFactory({\n service: coreServices.permissions,\n deps: {\n config: coreServices.config,\n discovery: coreServices.discovery,\n tokenManager: coreServices.tokenManager,\n },\n async factory({ config }) {\n return async ({ discovery, tokenManager }) => {\n return ServerPermissionClient.fromConfig(config, {\n discovery,\n tokenManager,\n });\n };\n },\n});\n","/*\n * Copyright 2023 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 { RootHttpRouterService } from '@backstage/backend-plugin-api';\nimport { Handler, Router } from 'express';\nimport trimEnd from 'lodash/trimEnd';\n\nfunction normalizePath(path: string): string {\n return `${trimEnd(path, '/')}/`;\n}\n\n/**\n * Options for the {@link DefaultRootHttpRouter} class.\n *\n * @public\n */\nexport interface DefaultRootHttpRouterOptions {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n}\n\n/**\n * The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for\n * {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.\n *\n * @public\n */\nexport class DefaultRootHttpRouter implements RootHttpRouterService {\n #indexPath?: string;\n\n #router = Router();\n #namedRoutes = Router();\n #indexRouter = Router();\n #existingPaths = new Array<string>();\n\n static create(options?: DefaultRootHttpRouterOptions) {\n let indexPath;\n if (options?.indexPath === false) {\n indexPath = undefined;\n } else if (options?.indexPath === undefined) {\n indexPath = '/api/app';\n } else if (options?.indexPath === '') {\n throw new Error('indexPath option may not be an empty string');\n } else {\n indexPath = options.indexPath;\n }\n return new DefaultRootHttpRouter(indexPath);\n }\n\n private constructor(indexPath?: string) {\n this.#indexPath = indexPath;\n this.#router.use(this.#namedRoutes);\n if (this.#indexPath) {\n this.#router.use(this.#indexRouter);\n }\n }\n\n use(path: string, handler: Handler) {\n if (path.match(/^[/\\s]*$/)) {\n throw new Error(`Root router path may not be empty`);\n }\n const conflictingPath = this.#findConflictingPath(path);\n if (conflictingPath) {\n throw new Error(\n `Path ${path} conflicts with the existing path ${conflictingPath}`,\n );\n }\n this.#existingPaths.push(path);\n this.#namedRoutes.use(path, handler);\n\n if (this.#indexPath === path) {\n this.#indexRouter.use(handler);\n }\n }\n\n handler(): Handler {\n return this.#router;\n }\n\n #findConflictingPath(newPath: string): string | undefined {\n const normalizedNewPath = normalizePath(newPath);\n for (const path of this.#existingPaths) {\n const normalizedPath = normalizePath(path);\n if (normalizedPath.startsWith(normalizedNewPath)) {\n return path;\n }\n if (normalizedNewPath.startsWith(normalizedPath)) {\n return path;\n }\n }\n return undefined;\n }\n}\n","/*\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 {\n ConfigService,\n coreServices,\n createServiceFactory,\n LifecycleService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport express, { RequestHandler, Express } from 'express';\nimport {\n createHttpServer,\n MiddlewareFactory,\n readHttpServerOptions,\n} from '../../../http';\nimport { DefaultRootHttpRouter } from './DefaultRootHttpRouter';\n\n/**\n * @public\n */\nexport interface RootHttpRouterConfigureOptions {\n app: Express;\n middleware: MiddlewareFactory;\n routes: RequestHandler;\n config: ConfigService;\n logger: LoggerService;\n lifecycle: LifecycleService;\n}\n\n/**\n * @public\n */\nexport type RootHttpRouterFactoryOptions = {\n /**\n * The path to forward all unmatched requests to. Defaults to '/api/app' if\n * not given. Disables index path behavior if false is given.\n */\n indexPath?: string | false;\n\n configure?(options: RootHttpRouterConfigureOptions): void;\n};\n\nfunction defaultConfigure({\n app,\n routes,\n middleware,\n}: RootHttpRouterConfigureOptions) {\n app.use(middleware.helmet());\n app.use(middleware.cors());\n app.use(middleware.compression());\n app.use(middleware.logging());\n app.use(routes);\n app.use(middleware.notFound());\n app.use(middleware.error());\n}\n\n/** @public */\nexport const rootHttpRouterFactory = createServiceFactory({\n service: coreServices.rootHttpRouter,\n deps: {\n config: coreServices.config,\n rootLogger: coreServices.rootLogger,\n lifecycle: coreServices.rootLifecycle,\n },\n async factory(\n { config, rootLogger, lifecycle },\n {\n indexPath,\n configure = defaultConfigure,\n }: RootHttpRouterFactoryOptions = {},\n ) {\n const logger = rootLogger.child({ service: 'rootHttpRouter' });\n const app = express();\n\n const router = DefaultRootHttpRouter.create({ indexPath });\n const middleware = MiddlewareFactory.create({ config, logger });\n\n configure({\n app,\n routes: router.handler(),\n middleware,\n config,\n logger,\n lifecycle,\n });\n\n const server = await createHttpServer(\n app,\n readHttpServerOptions(config.getOptionalConfig('backend')),\n { logger },\n );\n\n lifecycle.addShutdownHook({\n async fn() {\n await server.stop();\n },\n logger,\n });\n\n await server.start();\n\n return router;\n },\n});\n","/*\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 { createRootLogger } from '@backstage/backend-common';\nimport {\n createServiceFactory,\n LoggerService,\n coreServices,\n} from '@backstage/backend-plugin-api';\nimport { LogMeta } from '@backstage/backend-plugin-api';\nimport { Logger as WinstonLogger } from 'winston';\n\nclass BackstageLogger implements LoggerService {\n static fromWinston(logger: WinstonLogger): BackstageLogger {\n return new BackstageLogger(logger);\n }\n\n private constructor(private readonly winston: WinstonLogger) {}\n\n error(message: string, meta?: LogMeta): void {\n this.winston.error(message, meta);\n }\n\n warn(message: string, meta?: LogMeta): void {\n this.winston.warn(message, meta);\n }\n\n info(message: string, meta?: LogMeta): void {\n this.winston.info(message, meta);\n }\n\n debug(message: string, meta?: LogMeta): void {\n this.winston.debug(message, meta);\n }\n\n child(meta: LogMeta): LoggerService {\n return new BackstageLogger(this.winston.child(meta));\n }\n}\n\n/** @public */\nexport const rootLoggerFactory = createServiceFactory({\n service: coreServices.rootLogger,\n deps: {},\n async factory() {\n return BackstageLogger.fromWinston(createRootLogger());\n },\n});\n","/*\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 { loggerToWinstonLogger } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { TaskScheduler } from '@backstage/backend-tasks';\n\n/** @public */\nexport const schedulerFactory = createServiceFactory({\n service: coreServices.scheduler,\n deps: {\n plugin: coreServices.pluginMetadata,\n databaseManager: coreServices.database,\n logger: coreServices.logger,\n },\n async factory() {\n return async ({ plugin, databaseManager, logger }) => {\n return TaskScheduler.forPlugin({\n pluginId: plugin.getId(),\n databaseManager,\n logger: loggerToWinstonLogger(logger),\n });\n };\n },\n});\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerTokenManager } from '@backstage/backend-common';\n\n/** @public */\nexport const tokenManagerFactory = createServiceFactory({\n service: coreServices.tokenManager,\n deps: {\n config: coreServices.config,\n logger: coreServices.rootLogger,\n },\n async factory({ config, logger }) {\n const tokenManager = ServerTokenManager.fromConfig(config, {\n logger,\n });\n return async () => tokenManager;\n },\n});\n","/*\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 { loggerToWinstonLogger, UrlReaders } from '@backstage/backend-common';\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\n\n/** @public */\nexport const urlReaderFactory = createServiceFactory({\n service: coreServices.urlReader,\n deps: {\n config: coreServices.config,\n logger: coreServices.logger,\n },\n async factory() {\n return async ({ config, logger }) => {\n return UrlReaders.default({\n config,\n logger: loggerToWinstonLogger(logger),\n });\n };\n },\n});\n"],"names":["fs","resolvePath","dirname","forge","stoppableServer","https","http","helmet","Minimatch","__privateAdd","__privateSet","compression","__privateGet","morgan","cors","serializeError","NotModifiedError","InputError","AuthenticationError","NotAllowedError","NotFoundError","ConflictError","createServiceFactory","coreServices","__privateMethod","stringifyError","CacheManager","loadBackendConfig","loggerToWinstonLogger","config","DatabaseManager","ConfigReader","SingleHostDiscovery","DefaultIdentityClient","ServerPermissionClient","trimEnd","Router","express","createRootLogger","TaskScheduler","ServerTokenManager","UrlReaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,YAAe,GAAA,IAAA,CAAA;AACrB,MAAM,YAAe,GAAA,EAAA,CAAA;AAgBd,SAAS,sBAAsB,MAAoC,EAAA;AACxE,EAAO,OAAA;AAAA,IACL,MAAA,EAAQ,sBAAsB,MAAM,CAAA;AAAA,IACpC,KAAA,EAAO,iBAAiB,MAAM,CAAA;AAAA,GAChC,CAAA;AACF,CAAA;AAEA,SAAS,sBAAsB,MAA8C,EAAA;AA3C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ChC,IAAM,MAAA,YAAA,GAAeiB,gCAAmB,CAAA,UAAA,CAAW,MAAQ,EAAA;AAAA,MACzD,MAAA;AAAA,KACD,CAAA,CAAA;AACD,IAAA,OAAO,YAAY,YAAA,CAAA;AAAA,GACrB;AACF,CAAC;;ACZM,MAAM,mBAAmBlB,qCAAqB,CAAA;AAAA,EACnD,SAASC,6BAAa,CAAA,SAAA;AAAA,EACtB,IAAM,EAAA;AAAA,IACJ,QAAQA,6BAAa,CAAA,MAAA;AAAA,IACrB,QAAQA,6BAAa,CAAA,MAAA;AAAA,GACvB;AAAA,EACA,MAAM,OAAU,GAAA;AACd,IAAA,OAAO,OAAO,EAAE,MAAQ,EAAA,MAAA,EAAa,KAAA;AACnC,MAAA,OAAOkB,yBAAW,OAAQ,CAAA;AAAA,QACxB,MAAA;AAAA,QACA,MAAA,EAAQb,oCAAsB,MAAM,CAAA;AAAA,OACrC,CAAA,CAAA;AAAA,KACH,CAAA;AAAA,GACF;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,9 +13,11 @@ import { CorsOptions } from 'cors';
|
|
|
13
13
|
import { ErrorRequestHandler } from 'express';
|
|
14
14
|
import { Express as Express_2 } from 'express';
|
|
15
15
|
import { ExtensionPoint } from '@backstage/backend-plugin-api';
|
|
16
|
+
import { Handler } from 'express';
|
|
16
17
|
import { HelmetOptions } from 'helmet';
|
|
17
18
|
import * as http from 'http';
|
|
18
19
|
import { HttpRouterService } from '@backstage/backend-plugin-api';
|
|
20
|
+
import { IdentityService } from '@backstage/backend-plugin-api';
|
|
19
21
|
import { LifecycleService } from '@backstage/backend-plugin-api';
|
|
20
22
|
import { LoggerService } from '@backstage/backend-plugin-api';
|
|
21
23
|
import { PermissionsService } from '@backstage/backend-plugin-api';
|
|
@@ -73,6 +75,33 @@ export declare interface CreateSpecializedBackendOptions {
|
|
|
73
75
|
/** @public */
|
|
74
76
|
export declare const databaseFactory: (options?: undefined) => ServiceFactory<PluginDatabaseManager>;
|
|
75
77
|
|
|
78
|
+
/**
|
|
79
|
+
* The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for
|
|
80
|
+
* {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.
|
|
81
|
+
*
|
|
82
|
+
* @public
|
|
83
|
+
*/
|
|
84
|
+
export declare class DefaultRootHttpRouter implements RootHttpRouterService {
|
|
85
|
+
#private;
|
|
86
|
+
static create(options?: DefaultRootHttpRouterOptions): DefaultRootHttpRouter;
|
|
87
|
+
private constructor();
|
|
88
|
+
use(path: string, handler: Handler): void;
|
|
89
|
+
handler(): Handler;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Options for the {@link DefaultRootHttpRouter} class.
|
|
94
|
+
*
|
|
95
|
+
* @public
|
|
96
|
+
*/
|
|
97
|
+
export declare interface DefaultRootHttpRouterOptions {
|
|
98
|
+
/**
|
|
99
|
+
* The path to forward all unmatched requests to. Defaults to '/api/app' if
|
|
100
|
+
* not given. Disables index path behavior if false is given.
|
|
101
|
+
*/
|
|
102
|
+
indexPath?: string | false;
|
|
103
|
+
}
|
|
104
|
+
|
|
76
105
|
/** @public */
|
|
77
106
|
export declare const discoveryFactory: (options?: undefined) => ServiceFactory<PluginEndpointDiscovery>;
|
|
78
107
|
|
|
@@ -129,6 +158,21 @@ export declare type HttpServerOptions = {
|
|
|
129
158
|
};
|
|
130
159
|
};
|
|
131
160
|
|
|
161
|
+
/** @public */
|
|
162
|
+
export declare const identityFactory: (options?: IdentityFactoryOptions | undefined) => ServiceFactory<IdentityService>;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* An identity client options object which allows extra configurations
|
|
166
|
+
*
|
|
167
|
+
* @public
|
|
168
|
+
*/
|
|
169
|
+
export declare type IdentityFactoryOptions = {
|
|
170
|
+
issuer?: string;
|
|
171
|
+
/** JWS "alg" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.
|
|
172
|
+
* More info on supported algorithms: https://github.com/panva/jose */
|
|
173
|
+
algorithms?: string[];
|
|
174
|
+
};
|
|
175
|
+
|
|
132
176
|
/**
|
|
133
177
|
* Allows plugins to register shutdown hooks that are run when the process is about to exit.
|
|
134
178
|
* @public */
|
|
@@ -327,7 +371,8 @@ export declare const rootHttpRouterFactory: (options?: RootHttpRouterFactoryOpti
|
|
|
327
371
|
*/
|
|
328
372
|
export declare type RootHttpRouterFactoryOptions = {
|
|
329
373
|
/**
|
|
330
|
-
* The path to forward all unmatched requests to. Defaults to '/api/app'
|
|
374
|
+
* The path to forward all unmatched requests to. Defaults to '/api/app' if
|
|
375
|
+
* not given. Disables index path behavior if false is given.
|
|
331
376
|
*/
|
|
332
377
|
indexPath?: string | false;
|
|
333
378
|
configure?(options: RootHttpRouterConfigureOptions): void;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/backend-app-api",
|
|
3
3
|
"description": "Core API used by Backstage backend apps",
|
|
4
|
-
"version": "0.0.0-nightly-
|
|
4
|
+
"version": "0.0.0-nightly-20230113023010",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"publishConfig": {
|
|
@@ -33,12 +33,13 @@
|
|
|
33
33
|
"start": "backstage-cli package start"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@backstage/backend-common": "^0.0.0-nightly-
|
|
37
|
-
"@backstage/backend-plugin-api": "^0.0.0-nightly-
|
|
38
|
-
"@backstage/backend-tasks": "^0.0.0-nightly-
|
|
39
|
-
"@backstage/config": "^0.0.0-nightly-
|
|
36
|
+
"@backstage/backend-common": "^0.0.0-nightly-20230113023010",
|
|
37
|
+
"@backstage/backend-plugin-api": "^0.0.0-nightly-20230113023010",
|
|
38
|
+
"@backstage/backend-tasks": "^0.0.0-nightly-20230113023010",
|
|
39
|
+
"@backstage/config": "^0.0.0-nightly-20230113023010",
|
|
40
40
|
"@backstage/errors": "^1.1.4",
|
|
41
|
-
"@backstage/plugin-
|
|
41
|
+
"@backstage/plugin-auth-node": "^0.0.0-nightly-20230113023010",
|
|
42
|
+
"@backstage/plugin-permission-node": "^0.0.0-nightly-20230113023010",
|
|
42
43
|
"@types/cors": "^2.8.6",
|
|
43
44
|
"@types/express": "^4.17.6",
|
|
44
45
|
"compression": "^1.7.4",
|
|
@@ -47,6 +48,7 @@
|
|
|
47
48
|
"express-promise-router": "^4.1.0",
|
|
48
49
|
"fs-extra": "10.1.0",
|
|
49
50
|
"helmet": "^6.0.0",
|
|
51
|
+
"lodash": "^4.17.21",
|
|
50
52
|
"minimatch": "^5.0.0",
|
|
51
53
|
"morgan": "^1.10.0",
|
|
52
54
|
"node-forge": "^1.3.1",
|
|
@@ -55,7 +57,7 @@
|
|
|
55
57
|
"winston": "^3.2.1"
|
|
56
58
|
},
|
|
57
59
|
"devDependencies": {
|
|
58
|
-
"@backstage/cli": "^0.0.0-nightly-
|
|
60
|
+
"@backstage/cli": "^0.0.0-nightly-20230113023010",
|
|
59
61
|
"@types/compression": "^1.7.0",
|
|
60
62
|
"@types/fs-extra": "^9.0.3",
|
|
61
63
|
"@types/http-errors": "^2.0.0",
|