Skip to content

Commit

Permalink
Add TLS options to CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
t-ski committed Oct 5, 2024
1 parent 0b7bc6d commit 70d7c4b
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 48 deletions.
122 changes: 75 additions & 47 deletions packages/rjs-server/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
createServer as createHTTPServer
} from "http";
import { createServer as createHTTPSServer } from "https";
import { resolve } from "path";
import { existsSync, readFileSync } from "fs";

import { THTTPMethod } from "./.shared/global.types";
import { ISerialRequest, ISerialResponse } from "./.shared/global.interfaces";
Expand All @@ -20,10 +22,10 @@ export interface IServerOptions extends IHandlerOptions {
port: number;

tls?: {
cert: string;
key: string;
cert: string | Buffer;
key: string | Buffer;

ca?: string[];
ca?: (string | Buffer)[];
};
}

Expand Down Expand Up @@ -69,53 +71,79 @@ export class Server extends EventEmitter {

const logger: Logger = new Logger(options.cwd);

const resolveTLSParameter = (
param: (string | Buffer)[] | undefined
): (string | Buffer)[] => {
return [param]
.flat()
.map((param: string | Buffer | undefined) => {
if (!param) return null;
if (param instanceof Buffer) return param;

const potentialPath: string = resolve(options.cwd, param);
if (!existsSync(potentialPath)) return param;

return readFileSync(potentialPath);
})
.filter((param: string | Buffer | null) => !!param);
};

(
(!options.dev && optionsWithDefaults.tls
? createHTTPSServer
: createHTTPServer) as typeof createHTTPSServer
)((dReq: IncomingMessage, dRes: ServerResponse) => {
(["POST"].includes(dReq.method)
? new Promise((resolve, reject) => {
const body: string[] = [];
dReq.on("readable", () => {
body.push(dReq.read() as string);
});
dReq.on("end", () => resolve(body.join("")));
dReq.on("error", (err: Error) => reject(err));
})
: Promise.resolve(null)
)
.then((body: string) => {
const sReq: ISerialRequest = {
method: dReq.method as THTTPMethod,
url: dReq.url,
headers: dReq.headers,
body: body,
clientIP: dReq.socket.remoteAddress
};

this.instance
.handleRequest(sReq)
.then((sRes: ISerialResponse) => {
dRes.statusCode = sRes.status;
for (const header in sRes.headers) {
dRes.setHeader(
header,
[sRes.headers[header]].flat().join(", ")
);
}
sRes.body && dRes.write(sRes.body);
})
.finally(() => dRes.end());

this.emit("request", sReq);
})
.catch((err: Error) => {
dRes.statusCode = 500;
dRes.end();

logger && logger.error(err);
});
}).listen(this.port, () => onlineDeferral.call());
)(
{
...(optionsWithDefaults.tls
? {
ca: resolveTLSParameter(optionsWithDefaults.tls.ca)
}
: {})
},
(dReq: IncomingMessage, dRes: ServerResponse) => {
(["POST"].includes(dReq.method)
? new Promise((resolve, reject) => {
const body: string[] = [];
dReq.on("readable", () => {
body.push(dReq.read() as string);
});
dReq.on("end", () => resolve(body.join("")));
dReq.on("error", (err: Error) => reject(err));
})
: Promise.resolve(null)
)
.then((body: string) => {
const sReq: ISerialRequest = {
method: dReq.method as THTTPMethod,
url: dReq.url,
headers: dReq.headers,
body: body,
clientIP: dReq.socket.remoteAddress
};

this.instance
.handleRequest(sReq)
.then((sRes: ISerialResponse) => {
dRes.statusCode = sRes.status;
for (const header in sRes.headers) {
dRes.setHeader(
header,
[sRes.headers[header]].flat().join(", ")
);
}
sRes.body && dRes.write(sRes.body);
})
.finally(() => dRes.end());

this.emit("request", sReq);
})
.catch((err: Error) => {
dRes.statusCode = 500;
dRes.end();

logger && logger.error(err);
});
}
).listen(this.port, () => onlineDeferral.call());
}
}
4 changes: 3 additions & 1 deletion packages/rjs-server/test/http/composite.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ new HTTPTest("GET error")
"Connection": "keep-alive",
"Cache-Control": "max-age=86400000, stale-while-revalidate=300, must-revalidate"
}
});
});

// TODO: TLS test
2 changes: 2 additions & 0 deletions packages/rjs/cli.help.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,7 @@ Example: rjs serve -D --port 8000
--plugins-dir Path to plugins directory (default './src').
--public-dir Path to public files directory (default './public').
--port, -P Alternative server port (default '80/443' (HTTP/HTTPS), or '7777' (development mode)).
--tls-cert, -C Path to (or raw) TLS cetrificate for inherent HTTPS application.
--tls-key, -K Path to (or raw) TLS key for inherent HTTPS application.

Read more at https://rapidjs.org.
4 changes: 4 additions & 0 deletions packages/rjs/src/cli/registry/_serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ new Command("serve", () => {
dev,

port: Args.parseOption("port", "P").number(),
tls: {
cert: Args.parseOption("tls-cert", "C").string(),
key: Args.parseOption("tls-key", "K").string()
},
apiDirPath: Args.parseOption("api-dir").string(),
pluginDirPath: Args.parseOption("plugins-dir").string(),
publicDirPath: Args.parseOption("public-dir").string()
Expand Down

0 comments on commit 70d7c4b

Please sign in to comment.