0.0.1 • Published 6 years ago

@usvc/component-server v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
6 years ago

@usvc/component-server

Creates a bootstrapped server based on Express.

Scope

  • Basic HTTP security
  • Support for reading cookies
  • Support for issuing cookies
  • Parses POST data with Content-Type: application/json correctly
  • Parses POST data with Content-Type: application/x-www-form-urlencoded correctly
  • Support for Cross-Origin-Resource-Sharing (CORS)
  • Support for Content-Security-Policy (CSP) management
  • Bundled metrics supporting Prometheus
  • Bundled distributed tracing with Zipkin
  • Readiness check configuration
  • Liveness check configuration

Installation

npm i @usvc/component-server;
# OR
yarn add @usvc/component-server;

Usage

const {createServer} = require('@usvc/component-server');
// OR
import {createServer} from '@usvc/component-server';

Basic

// require as ^
const server = createServer();
const instance = server.listen(() => {
  const {port} = instance.address;
  console.info(`Listening on http://localhost:${port}`)
});

Full Configuration

// require as ^
const server = createServer({
  enableCookies: true,
  enableCors: true,
  enableJsonBody: true,
  enableUrlEncodedBody: true,
  cookies: {
    keys: [],
    name: 'session',
    secret: undefined,
    domain: 'localhost',
    httpOnly: true,
    maxAge: 60e3 * 60,
    path: '/',
  },
  cors: {
    allowedHeaders: undefined,
    credentials: true,
    exposedHeaders: undefined,
    maxAge: ONE_DAY,
    methods: ALL_HTTP_METHODS,
    optionsSuccessStatus: 204,
    preflightContinue: true,
    urls: [],
  },
  csp: {
    childSrc: ['"self"'],
    connectSrc: ['"self"'],
    defaultSrc: ['"self"'],
    disableAndroid: false,
    fontSrc: ['"self"'],
    imgSrc: ['"self"'],
    logger: console,
    logLevel: 'warn',
    objectSrc: ['"none"'],
    reportUri: '/csp-report',
    sandbox: ['allow-forms', 'allow-scripts'],
    scriptSrc: ['"self"'],
    styleSrc: ['"self"'],
  },
  jsonBody: {
    limit: '100kb',
    type: '*/json',
  },
  logger: console,
  metrics: {
    uri: '/metrics',
  },
  middlewares: {},
  urlEncodedBody: {
    limit: '100kb',
    type: '*/x-www-form-urlencoded',
  },
});

const instance = server.listen(() => {
  const {port} = instance.address;
  console.info(`Listening on http://localhost:${port}`)
});

API Documentaiton

.createServer(:options)

Returns a bootstrapped Express server. The :options parameter has the following schema:

KeyTypeDefaults ToDescription
enableCookiesBooleantrueEnables use of .cookies and .session in the request object in Express handlers
enableCorsBooleantrueEnables the use of Cross-Origin-Resource-Sharing headers
enableCspBooleantrueEnables the use of Content-Security-Policy headers
enableJsonBodyBooleantrueEnables use of .body in the request object if the Content-Type matches the :jsonBodyType parameter
enableMetricsBooleantrueEnables use of metrics
enableUrlEncodedBodyBooleantrueEnables use of .body in the request object if the Content-Type matches the :urlEncodedType parameter
cookiesDataCookieOptions-Options for configuring cookies management
corsSecurityCorsOptions-Options for configuring CORS
jsonBodyDataJsonOptions-Options for configuring parsing of JSON body data
loggerObjectconsoleThe logger to use for this server instance
metricsMetricsOptions-Configuration options for the metrics
middlewaresCreateServerHooks{}Any pre/post middleware injections you may need
urlEncodedBodyDataUrlEncodedOptions-Options for configuring parsing of URL encoded body data

Options Documentation

Options for cookies (DataCookiesOptions)

KeyTypeDefaults ToDescription
keysString[][]Keys used to sign (index zero) and verify cookies (other index numbers)
nameString"session"Name of the cookie
secretString-Secret used to compute the hash
domainString"localhost"Domain which the cookie is registered on
httpOnlyBooleantrueSet the HTTP-Only flag or not
maxAgeNumber60e3 * 60Maximum time the cookie is cacheable
pathString"/"Path of the cookie

Options for cors (SecurityCorsOptions)

KeyTypeDefaults ToDescription
allowedHeadersString[]undefinedSets the Access-Control-Allow-Headers HTTP response header
credentialsBooleantrueSpecifies if credentials are allowed
exposedHeadersString[]undefinedSets the allowed headers to be exposed
maxAgeNumberOne dayThe maximum age of caching in milliseconds
methodsString[]All HTTP methodsThe allowed HTTP methods
optionsSuccessStatusNumber204Specifies the HTTP status code to send on OPTIONS success
preflightContinueBooleantrueSpecifies if the preflight response should be sent immediately (false) or not (true)
urlsString[][]An array of allowed URLs for which the Origin request header can be

Options for csp (SecurityCspOptions)

KeyTypeDefaults ToDescription
childSrcString[]['"self"']Sets the child-src in the CSP
connectSrcString[]['"self"']Sets the connect-src in the CSP
defaultSrcString[]['"self"']Sets the default-src in the CSP
disableAndroidBooleanfalse
fontSrcString[]['"self"']Sets the font-src in the CSP
imgSrcString[]['"self"']Sets the img-src in the CSP
loggerObjectconsoleThe logger object to use for logging
logLevelString"warn"The log level to use with the logger object. If this level is not found as a property of the logger object, an error will be thrown at runtime
objectSrcString[]['"none"']Sets the object-src in the CSP
reportUriURI"/csp-report"Sets the report-uri in the CSP where browsers will post to if a CSP violation is found.
sandboxString[]['allow-forms', 'allow-scripts]Sets the sandbox in the CSP
scriptSrcString[]['"self"']Sets the script-src in the CSP
styleSrcString[]['"self"']Sets the style-src in the CSP

Options for jsonBody (DataJsonOptions)

KeyTypeDefaults ToDescription
limitString"100kb"Maximum size of the JSON body
typeString"*/json"Pattern of the Content-Type HTTP header value to invoke JSON body parsing

Options for metrics (ObservabilityMetricsOptions)

KeyTypeDefaults ToDescription
uriString"/metrics"The endpoint where the metrics can be assessed from

Options for middlewares (CreateServerHooks)

KeytypeDefaults ToDescription
afterRequestHandler[][]Any post-initialisation middlewares
beforeRequestHandler[][]Any pre-initialisation middlewares

Options for urlEncodedBody (DataUrlEncodedOptions)

KeyTypeDefaults ToDescription
limitString"100kb"Maximum size of the JSON body
typeString"*/x-www-form-urlencoded"Pattern of the Content-Type HTTP header value to invoke JSON body parsing

Examples

WIP

Development

WIP

License

This package is licensed under the MIT license.

View the license at LICENSE.

Changelog

0.0.x

0.0.1

  • Added cookie sessions
  • Added CSP support
  • Added server middleware hooks
  • Cross Origin Resource Sharing (CORS) support
  • Cookie parsing
  • Basic HTTP header security
  • Parsing of JSON encoded boday data
  • Parsing of URL encoded body data

Contributors

NameEmailWebsiteAbout Me
Joseph-https://github.com/zephinzer-

Cheers