@travetto/web-http-server
v6.0.3
Published
Web HTTP Server Support
Downloads
6
Readme
Web HTTP Server Support
Web HTTP Server Support
Install: @travetto/web-http-server
npm install @travetto/web-http-server
# or
yarn add @travetto/web-http-serverThis module provides basic for running http. https and http2 servers, along with support for tls key generation during development.
Running a Server
By default, the framework provides a default @CliCommand for WebHttpServer that will follow default behaviors, and spin up the server. Currently, Node Web Server is the only module that provides a compatible WebHttpServer.
Terminal: Standard application
$ trv web:http
Initialized {
manifest: {
main: {
name: '@travetto-doc/web-http-server',
folder: './doc-exec'
},
workspace: {
name: '@travetto-doc/web-http-server',
path: './doc-exec',
mono: false,
manager: 'npm',
type: 'commonjs',
defaultEnv: 'local'
}
},
runtime: {
env: 'local',
debug: false,
production: false,
dynamic: false,
resourcePaths: [
'./doc-exec/resources'
],
profiles: []
},
config: {
sources: [ { priority: 999, source: 'memory://override' } ],
active: {
AcceptConfig: { applies: false, types: [] },
CacheControlConfig: { applies: true },
CompressConfig: {
applies: true,
supportedEncodings: [ 'br', 'gzip', 'identity', 'deflate' ]
},
CookieConfig: { applies: true, httponly: true, sameSite: 'lax', path: '/' },
CorsConfig: { applies: true },
DecompressConfig: {
applies: true,
supportedEncodings: [ 'br', 'gzip', 'deflate', 'identity' ]
},
EtagConfig: { applies: true, minimumSize: '10kb' },
TrustProxyConfig: { applies: true, ips: [] },
WebBodyConfig: {
applies: true,
limit: '1mb',
parsingTypes: {
text: 'text',
'application/json': 'json',
'application/x-www-form-urlencoded': 'form'
}
},
WebConfig: { defaultMessage: true },
WebHttpConfig: {
httpVersion: '1.1',
port: 3000,
bindAddress: '0.0.0.0',
tls: false
},
WebLogConfig: { applies: true, showStackTrace: true }
}
}
}
Listening on port { port: 3000 }Configuration
Code: Standard Web Http Config
export class WebHttpConfig {
/**
* What version of HTTP to use
* Version 2 requires SSL for direct browser access
*/
@EnvVar('WEB_HTTP_VERSION')
httpVersion: '1.1' | '2' = '1.1';
/**
* The port to run on
*/
@EnvVar('WEB_HTTP_PORT')
port: number = 3000;
/**
* The bind address, defaults to 0.0.0.0
*/
bindAddress: string = '';
/**
* Is TLS active
*/
@EnvVar('WEB_HTTP_TLS')
tls?: boolean;
/**
* TLS Keys
*/
@Secret()
tlsKeys?: WebSecureKeyPair;
@Ignore()
fetchUrl: string;
async postConstruct(): Promise<void> {
this.tls ??= (this.httpVersion === '2' || !!this.tlsKeys);
this.port = (this.port < 0 ? await NetUtil.getFreePort() : this.port);
this.bindAddress ||= await NetUtil.getLocalAddress();
if (!this.tls) {
// Clear out keys if ssl is not set
this.tlsKeys = undefined;
} else if (!this.tlsKeys) {
if (Runtime.production) {
throw new AppError('Default ssl keys are only valid for development use, please specify a config value at web.ssl.keys');
}
this.tlsKeys = await WebSslUtil.generateKeyPair();
} else {
if (this.tlsKeys.key.length < 100) { // We have files or resources
this.tlsKeys.key = (await RuntimeResources.read(this.tlsKeys.key, true)).toString('utf8');
this.tlsKeys.cert = (await RuntimeResources.read(this.tlsKeys.cert, true)).toString('utf8');
}
}
this.fetchUrl = `${this.tls ? 'https' : 'http'}://${this.bindAddress}:${this.port}`;
}
}Creating a Custom CLI Entry Point
To customize a Web server, you may need to construct an entry point using the @CliCommand decorator. This could look like:
Code: Application entry point for Web Applications
import { Env, toConcrete } from '@travetto/runtime';
import { CliCommand } from '@travetto/cli';
import { DependencyRegistry } from '@travetto/di';
import { RootRegistry } from '@travetto/registry';
import { WebHttpServer, WebHttpConfig } from '@travetto/web-http-server';
import './config-override.ts';
@CliCommand({ runTarget: true })
export class SampleApp {
preMain(): void {
Env.TRV_ENV.set('prod');
Env.NODE_ENV.set('production');
}
async main() {
console.log('CUSTOM STARTUP');
await RootRegistry.init();
const ssl = await DependencyRegistry.getInstance(WebHttpConfig);
ssl.tls = true;
// Configure server before running
const instance = await DependencyRegistry.getInstance(toConcrete<WebHttpServer>());
const { complete } = await instance.serve();
return complete;
}
}And using the pattern established in the Command Line Interface module, you would run your program using npx trv web:custom.
Terminal: Custom application
$ trv web:custom
CUSTOM STARTUP
Initialized {
manifest: {
main: {
name: '@travetto-doc/web-http-server',
folder: './doc-exec'
},
workspace: {
name: '@travetto-doc/web-http-server',
path: './doc-exec',
mono: false,
manager: 'npm',
type: 'commonjs',
defaultEnv: 'local'
}
},
runtime: {
env: 'prod',
debug: false,
production: true,
dynamic: false,
resourcePaths: [
'./doc-exec/resources'
],
profiles: []
},
config: {
sources: [
{ priority: 10, source: 'direct' },
{ priority: 999, source: 'memory://override' }
],
active: {
AcceptConfig: { applies: false, types: [] },
CacheControlConfig: { applies: true },
CompressConfig: {
applies: true,
supportedEncodings: [ 'br', 'gzip', 'identity', 'deflate' ]
},
CookieConfig: { applies: true, httponly: true, sameSite: 'lax', path: '/' },
CorsConfig: { applies: true },
DecompressConfig: {
applies: true,
supportedEncodings: [ 'br', 'gzip', 'deflate', 'identity' ]
},
EtagConfig: { applies: true, minimumSize: '10kb' },
TrustProxyConfig: { applies: true, ips: [] },
WebBodyConfig: {
applies: true,
limit: '1mb',
parsingTypes: {
text: 'text',
'application/json': 'json',
'application/x-www-form-urlencoded': 'form'
}
},
WebConfig: { defaultMessage: true },
WebHttpConfig: {
httpVersion: '1.1',
port: 3000,
bindAddress: '0.0.0.0',
tls: true
},
WebLogConfig: { applies: true, showStackTrace: true }
}
}
}
Listening on port { port: 3000 }TLS Support
Additionally the framework supports TLS out of the box, by allowing you to specify your public and private keys for the cert. In dev mode, the framework will also automatically generate a self-signed cert if:
- TLS support is configured
- node-forge is installed
- Not running in prod
- No keys provided
This is useful for local development where you implicitly trust the cert.
TLS support can be enabled by setting web.http.tls: true in your config. The key/cert can be specified as string directly in the config file/environment variables. The key/cert can also be specified as a path to be picked up by RuntimeResources.
