feat(http): native TLS termination → https/wss via tls option
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+117
-5
No files matched your search
+3
-2
@@ -14,6 +14,7 @@ import {
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
|
||||
import { connectLink, type Link } from './mesh/link';
|
||||
import { Rooms } from './rooms';
|
||||
import type { TlsOptions } from './security';
|
||||
import { buildRemote } from './mesh/teacup';
|
||||
import { buildManifest, createMeshControl } from './mesh/teapot';
|
||||
import type { MeshControl } from './http';
|
||||
@@ -52,7 +53,7 @@ export interface MeshConfig {
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown> }): App {
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown>; tls?: TlsOptions }): App {
|
||||
const bus = new Bus();
|
||||
const container = new Container();
|
||||
let server: http.Server | undefined;
|
||||
@@ -358,7 +359,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
},
|
||||
}));
|
||||
|
||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams });
|
||||
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls });
|
||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||
return server;
|
||||
|
||||
+9
-3
@@ -1,4 +1,5 @@
|
||||
import http from 'http';
|
||||
import https from 'https';
|
||||
import { once } from 'events';
|
||||
import { channel } from './channel';
|
||||
import { errorToResponse } from './transformers';
|
||||
@@ -7,6 +8,7 @@ import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||
import type { Transport } from './metadata';
|
||||
import type { Bus } from './bus';
|
||||
import type { TlsOptions } from './security';
|
||||
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
@@ -14,7 +16,7 @@ export interface RequestLimits {
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
}
|
||||
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> }
|
||||
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions }
|
||||
|
||||
export type RouteHandler = (req: {
|
||||
method: string; url: string;
|
||||
@@ -186,7 +188,7 @@ export function createHttpServer(
|
||||
routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const handler = async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
||||
@@ -233,7 +235,11 @@ export function createHttpServer(
|
||||
const r: ResponseShape = result;
|
||||
res.writeHead(r.status, r.headers);
|
||||
res.end(r.body);
|
||||
});
|
||||
};
|
||||
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
||||
const server: http.Server = (opts?.tls
|
||||
? https.createServer(opts.tls as https.ServerOptions, handler)
|
||||
: http.createServer(handler)) as unknown as http.Server;
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
-----BEGIN CERTI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gdHPIFQcomuJX75LRry+OEnFOmHGyK1eYs8sT9D9F+TmJHVA51qvp3v7KRdxBS
|
||||
wGWh9ghqzXnyfyCkQgpxJfLJgAMR5j91IGXpSJg5D1ISXyLeqooCyw8=
|
||||
-----END CERTIFICATE-----
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC53qs2t06DxGBc
|
||||
1vUrD/3gmBS+tWb/l2ZqrzX9PAd55FzUAjOPesmTwoz9nIevwW1jQFQyu+6fb2FA
|
||||
7gXSRXsQ4G7yOT++a75CxwKPAiOkbdQGJ1iprt1BrLZHxElWfiSevRuLr8hhgKtR
|
||||
lj41MdEZtf2xpfsNot49KK+Yp87huynZOk6RhYKoAJ4SzReoga+w6jtelfkJiWWv
|
||||
m5fPeKo/Y/z8VRZdgL823BZe4vkZ5+PiW2bLHvPRwWlD1s67r/PtW8wweLe0z4dY
|
||||
cpkXb0f+rwx4hOGnUtbAPgZxIFX6J0h+jfBovS60HTEcxmPYm31IDXU2fKsPIiPt
|
||||
KG47UF45AgMBAAECggEAASvLkTLFTPQRNbHesGivd+QKvhXcrNpqboclPwUgY0P3
|
||||
/Wz4dVxicJV5TRrDScKdUBKxGnMP1+jRfcwndLxJKswjNCWosWgyi29UueEbUjdP
|
||||
7pb+X8P73bn7GbIn/SJv1CE1uc2qefTKf4nZC/2WR0Qb3FaYTEJyWy51BsWd5Sha
|
||||
4XfUzHBldJdZcELCBtwQFJWnqpc1qlnn4Uj9nmD+n7q5t54jqaa67qDhqDScU4DH
|
||||
nguXuH+Cb1zWGsKfoOc//jGWZKX3FJ6nKLHhh4QxxJa/A0VIoqf2lHDfKiJNUqMl
|
||||
BLq78MiFD1SnPXp/024EtEpC5KAS9oSHRusEmDbgAQKBgQDy6j5h9fgI5Bnxjv+E
|
||||
+ASagBSYN4+mszHvZVXtXAl8OZVXkHUKoaco5IPe4/Ysg7WTPVAQAggtbqq/QE15
|
||||
S1sQZyPBmr2ewqQHKNJHMsB0u9AlXOHK3DHVq3+6kM7RGeuuWDvycsM2KHV9pUtA
|
||||
rIg1aMc9NGMkCsaQT2lJeyTOOQKBgQDD4cgK0a4XCot3fW4FaofDUE69TDJwk0Me
|
||||
IneH0BpK3iuSqS/mqjH8ZV6Z5lNVopUGGObnwLtEHZX8q2jakBPa7mCYnulnAsO9
|
||||
WTEZ5oHoN3Gr8O7WJW4LoOOIeci8qPiz58CazhBjK+Qa6/C+rRN0u5hbG3zTEAoS
|
||||
vsjMDYgQAQKBgC8P1OAzwEcwshoLo1OGnZW1RMgs04bvZrhDwL8Iusm3ekiJszNJ
|
||||
GFKi2y2eqr37En2hPlarnhv3OdttwNTEFbN62AGVUjFk8lR0wzCKE6FKFcx3T0N3
|
||||
H6yO2mMx1O/L/s47R/nz5AAlHIYoNQklpAn878Ta1m5QLCIfUH2s/vd5AoGBAL01
|
||||
9i6FNj2pgOiOL11p9vQyOaze0oYtqZKNRprY6NzS2JIVfWC5nAkqvgO5GVxJ7Ntz
|
||||
6G+KmxmD3qKvzFv6+kLrKkGiluBbKkpXwnc7UtbF37Zvx7TxeOggpEjrIn0iVwIo
|
||||
5cJjNC8ncXKT3/u/YWDL6LJwzdVu09whkAKTO5ABAoGBANGHFvW/LCn0R24Xk2lF
|
||||
tFXsj2M5TqjqEeAa37doHPsUx2Bvp/YTpkA6sRKzlHcfyEC/gUKjNaEjIil5836P
|
||||
qjd7abz8xF7STS+9SzGDBEbjKk/IRrBjcYEh9x6kGWqnN6w4wXHsoZyMi/zSP/OG
|
||||
KPTzBQvDzHuVu5n+/a7izTeb
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,9 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const dir = join(__dirname, '..', 'fixtures');
|
||||
|
||||
export const selfSignedTls = () => ({
|
||||
key: readFileSync(join(dir, 'key.pem')),
|
||||
cert: readFileSync(join(dir, 'cert.pem')),
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import https from 'https';
|
||||
import WebSocket from 'ws';
|
||||
import { createApp, Route, Get, Ws, Module, inbound, channel } from '../src';
|
||||
import { selfSignedTls } from './helpers/tls';
|
||||
|
||||
@Route('/')
|
||||
class Api {
|
||||
@Get('/ping') ping() { return { ok: true }; }
|
||||
@Ws('/echo') echo(@inbound() msgs: AsyncIterable<unknown>) {
|
||||
const out = channel<unknown>();
|
||||
(async () => { for await (const m of msgs) out.push(m); })();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
@Module({ mountpoint: '/', controllers: [Api] })
|
||||
class ApiModule {}
|
||||
|
||||
let app: any;
|
||||
afterEach(async () => { await app?.close(); });
|
||||
|
||||
describe('TLS', () => {
|
||||
it('serves https', async () => {
|
||||
app = createApp({ modules: [ApiModule], tls: selfSignedTls() });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
const body = await new Promise<string>((resolve, reject) => {
|
||||
https.get({ port, path: '/ping', rejectUnauthorized: false }, (res) => {
|
||||
let d = ''; res.on('data', (c) => (d += c)); res.on('end', () => resolve(d));
|
||||
}).on('error', reject);
|
||||
});
|
||||
expect(JSON.parse(body)).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('upgrades wss on the same server', async () => {
|
||||
app = createApp({ modules: [ApiModule], tls: selfSignedTls() });
|
||||
const server = await app.listen(0);
|
||||
const port = (server.address() as any).port;
|
||||
const ws = new WebSocket(`wss://127.0.0.1:${port}/echo`, { rejectUnauthorized: false });
|
||||
const got = await new Promise<string>((resolve, reject) => {
|
||||
ws.on('open', () => ws.send('hi'));
|
||||
ws.on('message', (d) => resolve(d.toString()));
|
||||
ws.on('error', reject);
|
||||
});
|
||||
expect(got).toBe('hi');
|
||||
ws.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user