relay/src/relay.ts

230 lines
5.5 KiB
TypeScript
Raw Normal View History

2022-06-27 17:53:00 +00:00
// @ts-ignore
import DHT from "@hyperswarm/dht";
// @ts-ignore
2022-07-19 22:31:15 +00:00
import { relay } from "@hyperswarm/dht-relay";
2022-06-27 17:53:00 +00:00
// @ts-ignore
import Stream from "@hyperswarm/dht-relay/ws";
2022-07-19 22:31:15 +00:00
import express, { Express } from "express";
2022-07-05 19:02:07 +00:00
import config from "./config.js";
import * as http from "http";
import * as https from "https";
import * as tls from "tls";
import * as acme from "acme-client";
2022-07-19 22:31:15 +00:00
import { Buffer } from "buffer";
import { intervalToDuration } from "date-fns";
import cron from "node-cron";
2022-07-19 22:31:15 +00:00
import { get as getDHT } from "./dht.js";
import WS from "ws";
// @ts-ignore
import {
createIndependentFileSmall,
IndependentFileSmall,
openIndependentFileSmall,
overwriteIndependentFileSmall,
} from "./file.js";
import { seedPhraseToSeed } from "libskynet";
let sslCtx: tls.SecureContext = tls.createSecureContext();
const sslParams: tls.SecureContextOptions = { cert: "", key: "" };
2022-06-27 17:53:00 +00:00
const sslPrivateKey = await acme.forge.createPrivateKey();
const acmeClient = new acme.Client({
2022-07-19 22:31:15 +00:00
accountKey: sslPrivateKey,
directoryUrl:
config.str("ssl-mode") === "staging"
? acme.directory.letsencrypt.staging
: acme.directory.letsencrypt.production,
});
2022-06-27 21:52:20 +00:00
let app: Express;
let router = express.Router();
2022-06-27 17:53:00 +00:00
const FILE_CERT_NAME = "/lumeweb/relay/ssl.crt";
const FILE_KEY_NAME = "/lumeweb/relay/ssl.key";
type SslData = { crt: IndependentFileSmall; key: IndependentFileSmall };
export async function start() {
2022-07-22 23:55:09 +00:00
const relayPort = config.str("port");
2022-07-19 22:31:15 +00:00
app = express();
app.use(function (req, res, next) {
router(req, res, next);
});
let httpsServer = https.createServer({
SNICallback(servername, cb) {
cb(null, sslCtx);
},
});
let httpServer = http.createServer(app);
cron.schedule("0 * * * *", setupSSl);
2022-07-19 22:31:15 +00:00
await new Promise((resolve) => {
httpServer.listen(80, "0.0.0.0", function () {
console.info("HTTP Listening on ", httpServer.address());
resolve(null);
});
2022-07-19 22:31:15 +00:00
});
const dht = await getDHT();
2022-06-27 17:53:00 +00:00
2022-07-19 22:31:15 +00:00
let wsServer = new WS.Server({ server: httpsServer });
2022-07-19 22:31:15 +00:00
wsServer.on("connection", (socket: any) => {
relay(dht, new Stream(false, socket));
});
2022-07-19 22:31:15 +00:00
await new Promise((resolve) => {
httpsServer.listen(relayPort, "0.0.0.0", function () {
console.info("Relay started on ", httpsServer.address());
resolve(null);
});
2022-07-19 22:31:15 +00:00
});
await setupSSl();
}
async function setupSSl() {
let sslCert = await getSslCert();
let sslKey = await getSslKey();
let certInfo;
let exists = false;
let domainValid = false;
let dateValid = false;
if (sslCert && sslKey) {
sslParams.cert = Buffer.from((sslCert as IndependentFileSmall).fileData);
sslParams.key = Buffer.from((sslKey as IndependentFileSmall).fileData);
certInfo = await getCertInfo();
exists = true;
}
if (exists) {
const expires = certInfo?.notAfter as Date;
2022-07-19 22:31:15 +00:00
let duration = intervalToDuration({ start: new Date(), end: expires });
let daysLeft = (duration.months as number) * 30 + (duration.days as number);
2022-07-19 22:31:15 +00:00
if (daysLeft > 30) {
dateValid = true;
}
2022-07-22 23:55:09 +00:00
if (certInfo?.domains.commonName === config.str("domain")) {
domainValid = true;
}
2022-07-19 22:31:15 +00:00
}
if (dateValid && domainValid) {
return;
}
await createOrRenewSSl(
sslCert as IndependentFileSmall,
sslKey as IndependentFileSmall
);
}
async function createOrRenewSSl(
oldCert?: IndependentFileSmall,
oldKey?: IndependentFileSmall
) {
2022-07-19 22:31:15 +00:00
const [certificateKey, certificateRequest] = await acme.forge.createCsr({
2022-07-22 23:55:09 +00:00
commonName: config.str("domain"),
2022-07-19 22:31:15 +00:00
});
try {
sslParams.cert = await acmeClient.auto({
csr: certificateRequest,
termsOfServiceAgreed: true,
challengeCreateFn: async (authz, challenge, keyAuthorization) => {
router.get(
`/.well-known/acme-challenge/${challenge.token}`,
(req, res) => {
res.send(keyAuthorization);
}
);
},
challengeRemoveFn: async () => {
router = express.Router();
},
challengePriority: ["http-01"],
});
sslParams.cert = Buffer.from(sslParams.cert);
} catch (e: any) {
console.error((e as Error).message);
process.exit(1);
}
2022-07-19 22:31:15 +00:00
sslParams.key = certificateKey;
sslCtx = tls.createSecureContext(sslParams);
await saveSsl(oldCert, oldKey);
}
async function saveSsl(
oldCert?: IndependentFileSmall,
oldKey?: IndependentFileSmall
): Promise<void> {
const seed = getSeed();
if (oldCert) {
await overwriteIndependentFileSmall(
oldCert,
Buffer.from(sslParams.cert as any)
);
} else {
await createIndependentFileSmall(
seed,
FILE_CERT_NAME,
Buffer.from(sslParams.cert as any)
);
}
if (oldKey) {
await overwriteIndependentFileSmall(
oldKey,
Buffer.from(sslParams.key as any)
);
} else {
await createIndependentFileSmall(
seed,
FILE_KEY_NAME,
Buffer.from(sslParams.key as any)
);
}
}
async function getCertInfo() {
return acme.forge.readCertificateInfo(sslParams.cert as Buffer);
}
async function getSslCert(): Promise<IndependentFileSmall | boolean> {
return getSslFile(FILE_CERT_NAME);
}
async function getSslKey(): Promise<IndependentFileSmall | boolean> {
return getSslFile(FILE_KEY_NAME);
}
async function getSslFile(
name: string
): Promise<IndependentFileSmall | boolean> {
let seed = getSeed();
let [file, err] = await openIndependentFileSmall(seed, name);
if (err) {
return false;
}
return file;
}
function getSeed(): Uint8Array {
2022-07-22 23:55:09 +00:00
let [seed, err] = seedPhraseToSeed(config.str("seed"));
if (err) {
console.error(err);
process.exit(1);
}
return seed;
2022-06-27 17:53:00 +00:00
}