@backstage/backend-defaults
Version:
Backend defaults used by Backstage backend apps
305 lines (294 loc) • 9.23 kB
TypeScript
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
import { RootHttpRouterService, RootHealthService, RootConfigService, LoggerService, LifecycleService } from '@backstage/backend-plugin-api';
import * as express from 'express';
import { Handler, RequestHandler, ErrorRequestHandler, Express } from 'express';
import { Config } from '@backstage/config';
import * as http from 'http';
import { RequestListener } from 'http';
import { CorsOptions } from 'cors';
import { HelmetOptions } from 'helmet';
import { Server } from 'node:http';
/**
* Options for the {@link DefaultRootHttpRouter} class.
*
* @public
*/
interface DefaultRootHttpRouterOptions {
/**
* The path to forward all unmatched requests to. Defaults to '/api/app' if
* not given. Disables index path behavior if false is given.
*/
indexPath?: string | false;
}
/**
* The default implementation of the {@link @backstage/backend-plugin-api#RootHttpRouterService} interface for
* {@link @backstage/backend-plugin-api#coreServices.rootHttpRouter}.
*
* @public
*/
declare class DefaultRootHttpRouter implements RootHttpRouterService {
#private;
static create(options?: DefaultRootHttpRouterOptions): DefaultRootHttpRouter;
private constructor();
use(path: string, handler: Handler): void;
handler(): Handler;
}
/**
* @public
*/
declare function createHealthRouter(options: {
health: RootHealthService;
config: RootConfigService;
}): express.Router;
/**
* An HTTP server extended with utility methods.
*
* @public
*/
interface ExtendedHttpServer extends http.Server {
start(): Promise<void>;
stop(): Promise<void>;
port(): number;
}
/**
* Options for starting up an HTTP server.
*
* @public
*/
type HttpServerOptions = {
listen: {
port: number;
host: string;
};
https?: {
certificate: HttpServerCertificateOptions;
};
};
/**
* Options for configuring HTTPS for an HTTP server.
*
* @public
*/
type HttpServerCertificateOptions = {
type: 'pem';
key: string;
cert: string;
} | {
type: 'generated';
hostname: string;
};
/**
* Reads {@link HttpServerOptions} from a {@link @backstage/config#Config} object.
*
* @public
* @remarks
*
* The provided configuration object should contain the `listen` and
* additional keys directly.
*
* @example
* ```ts
* const opts = readHttpServerOptions(config.getConfig('backend'));
* ```
*/
declare function readHttpServerOptions(config?: Config): HttpServerOptions;
/**
* Creates a Node.js HTTP or HTTPS server instance.
*
* @public
*/
declare function createHttpServer(listener: RequestListener, options: HttpServerOptions, deps: {
logger: LoggerService;
}): Promise<ExtendedHttpServer>;
/**
* Options used to create a {@link MiddlewareFactory}.
*
* @public
*/
interface MiddlewareFactoryOptions {
config: RootConfigService;
logger: LoggerService;
}
/**
* Options passed to the {@link MiddlewareFactory.error} middleware.
*
* @public
*/
interface MiddlewareFactoryErrorOptions {
/**
* Whether error response bodies should show error stack traces or not.
*
* If not specified, by default shows stack traces only in development mode.
*/
showStackTraces?: boolean;
/**
* Whether any 4xx errors should be logged or not.
*
* If not specified, default to only logging 5xx errors.
*/
logAllErrors?: boolean;
}
/**
* A utility to configure common middleware.
*
* @public
*/
declare class MiddlewareFactory {
#private;
/**
* Creates a new {@link MiddlewareFactory}.
*/
static create(options: MiddlewareFactoryOptions): MiddlewareFactory;
private constructor();
/**
* Returns a middleware that unconditionally produces a 404 error response.
*
* @remarks
*
* Typically you want to place this middleware at the end of the chain, such
* that it's the last one attempted after no other routes matched.
*
* @returns An Express request handler
*/
notFound(): RequestHandler;
/**
* Returns the compression middleware.
*
* @remarks
*
* The middleware will attempt to compress response bodies for all requests
* that traverse through the middleware.
*/
compression(): RequestHandler;
/**
* Returns a request logging middleware.
*
* @remarks
*
* Typically you want to place this middleware at the start of the chain, such
* that it always logs requests whether they are "caught" by handlers farther
* down or not.
*
* @returns An Express request handler
*/
logging(): RequestHandler;
/**
* Returns a middleware that implements the helmet library.
*
* @remarks
*
* This middleware applies security policies to incoming requests and outgoing
* responses. It is configured using config keys such as `backend.csp`.
*
* @see {@link https://helmetjs.github.io/}
*
* @returns An Express request handler
*/
helmet(): RequestHandler;
/**
* Returns a middleware that implements the cors library.
*
* @remarks
*
* This middleware handles CORS. It is configured using the config key
* `backend.cors`.
*
* @see {@link https://github.com/expressjs/cors}
*
* @returns An Express request handler
*/
cors(): RequestHandler;
/**
* Returns a middleware that implements rate limiting.
*
* @remarks
*
* Rate limiting is a common technique to prevent abuse of APIs. This middleware is
* configured using the config key `backend.rateLimit`.
*
* @returns An Express request handler
*/
rateLimit(): RequestHandler;
/**
* Express middleware to handle errors during request processing.
*
* @remarks
*
* This is commonly the very last middleware in the chain.
*
* Its primary purpose is not to do translation of business logic exceptions,
* but rather to be a global catch-all for uncaught "fatal" errors that are
* expected to result in a 500 error. However, it also does handle some common
* error types (such as http-error exceptions, and the well-known error types
* in the `@backstage/errors` package) and returns the enclosed status code
* accordingly.
*
* It will also produce a response body with a serialized form of the error,
* unless a previous handler already did send a body. See
* {@link @backstage/errors#ErrorResponseBody} for the response shape used.
*
* @returns An Express error request handler
*/
error(options?: MiddlewareFactoryErrorOptions): ErrorRequestHandler;
}
/**
* Attempts to read a CORS options object from the backend configuration object.
*
* @public
* @param config - The backend configuration object.
* @returns A CORS options object, or undefined if no cors configuration is present.
*
* @example
* ```ts
* const corsOptions = readCorsOptions(config.getConfig('backend'));
* ```
*/
declare function readCorsOptions(config?: Config): CorsOptions;
/**
* Attempts to read Helmet options from the backend configuration object.
*
* @public
* @param config - The backend configuration object.
* @returns A Helmet options object, or undefined if no Helmet configuration is present.
*
* @example
* ```ts
* const helmetOptions = readHelmetOptions(config.getConfig('backend'));
* ```
*/
declare function readHelmetOptions(config?: Config): HelmetOptions;
/**
* @public
*/
interface RootHttpRouterConfigureContext {
app: Express;
server: Server;
middleware: MiddlewareFactory;
routes: RequestHandler;
config: RootConfigService;
logger: LoggerService;
lifecycle: LifecycleService;
healthRouter: RequestHandler;
applyDefaults: () => void;
}
/**
* HTTP route registration for root services.
*
* See {@link @backstage/code-plugin-api#RootHttpRouterService}
* and {@link https://backstage.io/docs/backend-system/core-services/root-http-router | the service docs}
* for more information.
*
* @public
*/
type RootHttpRouterFactoryOptions = {
/**
* The path to forward all unmatched requests to. Defaults to '/api/app' if
* not given. Disables index path behavior if false is given.
*/
indexPath?: string | false;
configure?(context: RootHttpRouterConfigureContext): void;
};
/** @public */
declare const rootHttpRouterServiceFactory: ((options?: RootHttpRouterFactoryOptions) => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.RootHttpRouterService, "root", "singleton">) & _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api.RootHttpRouterService, "root", "singleton">;
export { DefaultRootHttpRouter, MiddlewareFactory, createHealthRouter, createHttpServer, readCorsOptions, readHelmetOptions, readHttpServerOptions, rootHttpRouterServiceFactory };
export type { DefaultRootHttpRouterOptions, ExtendedHttpServer, HttpServerCertificateOptions, HttpServerOptions, MiddlewareFactoryErrorOptions, MiddlewareFactoryOptions, RootHttpRouterConfigureContext, RootHttpRouterFactoryOptions };