How to use the koa-helmet function in koa-helmet

To help you get started, we’ve selected a few koa-helmet examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github OXOYO / X-RESTful-API-Generator-Koa / src / middleware / index.js View on Github external
export default function middleware (app) {
  return compose([
    logger(),
    helmet(),
    KoaStatic('.'),
    // 跨域处理
    convert(cors({
      origin: function (request) {
        let host = request.header.origin
        let isIncludes = false
        // console.log('host', request.header)
        // FIXME 安全起见,上线时需注掉如下判断
        if (!host) {
          return '*'
        }
        for (let i in SystemConfig.accessHost) {
          if (host.includes(SystemConfig.accessHost[i])) {
            isIncludes = true
            break
          }
github marmelab / javascript-boilerplate / src / api / index.js View on Github external
});

process.on('unhandledRejection', (error, promise) => {
    console.error('unhandled promise rejection:', { // eslint-disable-line no-console
        error,
        promise,
    });
});

app.use(koaMount('/healthcare', healthcare));

// XmlHttpRequest shim for IE
app.use(xdomainRoute);

// Security headers
app.use(koaHelmet());
app.use(koaHelmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"] } }));
app.use(koaHelmet.frameguard('deny'));
app.use(koaCors({
    credentials: true,
    exposeHeaders: [
        'Authorization',
        'Content-Disposition',
        'Content-Type',
        'X-Entities',
    ],
    allowHeaders: [
        'Authorization',
        'Content-Disposition',
        'Content-Type',
        'X-Entities',
    ],
github lbryio / lighthouse.js / server / index.js View on Github external
import winston from 'winston';
import slack from 'node-slack';
require('winston-daily-rotate-file');

// Setup logging
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, { colorize: true, timestamp: true, prettyPrint: true });
var slackAPIKey = process.env.SLACK_HOOK_URL;
var mySlack = new slack(slackAPIKey, {});
// Create Koa Application
const app = new Koa();

app
  .use(logger())
  .use(bodyParser())
  .use(helmet())
  .use(cors());

routing(app);

// Start the application
app.listen(port, () => logToSlack(`Lighthouse API server is running at http://localhost:${port}/`));

export default app;

export function logToSlack (message) {
  winston.log('info', 'SentToSlack: ' + message);
  mySlack.send({
    text      : message,
    channel   : '#lighthouse-status',
    username  : 'Lighthouse',
    icon_emoji: 'lighthouse',
github hung-phan / koa-react-isomorphic / app / server / infrastructure / middlewares / index.js View on Github external
export const securityLayer = (app: Object) => {
  app.keys = [process.env.SECRET_KEY];

  const csrf = new CSRF();

  app
    .use(session({ maxAge: 86400000 }, app)) // https://github.com/koajs/session
    .use((ctx, next) => {
      // don't check csrf for request coming from the server
      if (ctx.get("x-app-secret") === process.env.SECRET_KEY) {
        return next();
      }

      return csrf(ctx, next);
    }) // https://github.com/koajs/csrf
    .use(helmet()); // https://github.com/venables/koa-helmet
};
github iam4x / isomorphic-flux-boilerplate / server / koa.js View on Github external
import Router from 'koa-router'
import convert from 'koa-convert'

import router from './router'
import config from '../internals/config/private'
import { apiPrefix } from '../internals/config/public'

const app = new Koa()
const env = process.env.NODE_ENV || 'development'

// add header `X-Response-Time`
app.use(responseTime())
app.use(convert(logger()))

// various security headers
app.use(helmet())

const cacheOpts = { maxAge: 86400000, gzip: true }
app.use(favicon(path.join(__dirname, '../app/images/favicon.ico')))

if (env === 'production') {
  // set debug env to `koa` only
  // must be set programmaticaly for windows
  debug.enable('koa')

  // load production middleware
  app.use(require('koa-conditional-get')())
  app.use(convert(require('koa-etag')()))
  app.use(require('koa-compress')())

  app.use(mount('/assets', staticCache(path.join(__dirname, '../dist'), cacheOpts)))
  // mount static folder for SW
github eankeen / tails / operator / app.js View on Github external
import Koa from 'koa'
import logger from 'koa-logger'
import helmet from 'koa-helmet'
import bodyParser from 'koa-bodyparser'

import './core/cleanup'
import './core/db'
import './subscribers/project'
import routes from './routes'

const app = new Koa()
app.use(logger())
app.use(helmet())
app.use(bodyParser())

app.use(routes)

app.on('error', err => console.error('e: ', err))

const port = process.env.PORT || 3020
app.listen(port)

export default app.listen()
github Baiang / ReactSSR / server / index.ts View on Github external
const nextApp = next({
  dev,
  conf,
  dir:'./src'
});

const handle = nextApp.getRequestHandler();
router.ssrCache(nextApp)
router.nextRoute(handle);
const app = new Koa();

!dev ? app.use(logger()) : '';
app.use(bodyParser());
app.use(requestId());
app.use(helmet());
app.use(cors({
  exposeHeaders: ['X-Request-Id']
}));
app.use(responseHandler());

if (!module.parent) {
  nextApp.prepare()
    .then(() => {
      app.use(router.routes());
      app.use(router.allowedMethods());
      (async () => {
          let port = await getPort({port: [config[env].port, 3000, 3001, 3002]})
          app.listen(port, config[env].host, () => {
            log.info(`API server listening on ${config[env].host}:${port}, in ${env}`);
          });
      })();
github saadq / resumake.io / app / server / src / index.js View on Github external
*/

import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import helmet from 'koa-helmet'
import router from './routes'
import { errorHandler } from './middleware'

const app = new Koa()

if (app.env === 'development') {
  app.proxy = true
}

app.use(errorHandler())
app.use(helmet())
app.use(bodyParser())
app.use(router)

export default app
github poetapp / frost-api / src / api / RestServer.ts View on Github external
const ConfiguredKoa = ({
  maxApiRequestLimitForm,
  maxApiRequestLimitJson,
  loggingConfiguration,
}: Partial) =>
  new Koa()
    .use(errorHandling())
    .use(logger(createModuleLogger(loggingConfiguration)))
    .use(helmet(securityHeaders))
    .use(
      cors({
        origin: (ctx: any, next: any) => '*',
      }),
    )
    .use(
      bodyParser({
        formLimit: maxApiRequestLimitForm,
        jsonLimit: maxApiRequestLimitJson,
      }),
    )
github garbin / koapi / src / koapi.es View on Github external
helmet(config){
    if (config) {
      this.koa.use(helmet(config));
    }
    return this
  }