import { RegisterSingleton } from "@entity-access/entity-access/dist/di/di.js"; import { createSecureContext, SecureContext } from "node:tls"; import { cacheFor, ICacheContainer, ObjectCache } from "../../common/cacheFor.js"; import sleep from "../../common/sleep.js"; import { existsSync } from "node:fs"; import { readFile } from "node:fs/promises"; @RegisterSingleton export default class CertificateFetcher implements ICacheContainer { cache: ObjectCache; @cacheFor() public async getCert(servername: string): Promise { if(!servername) { throw new Error("Invalid domain name"); } let context = await this.readFile(servername); if(context) { return context; } await fetch(`https://${servername}`); for(let i=0;i<30;i++) { await sleep(1000); // check if we have certificate... context = await this.readFile(servername); if(context) { return context; } } return null; } async readFile(servername: string) { const certPath = `/cache/certs/${servername}/cert.pem`; const keyPath = `/cache/certs/${servername}/key.pem`; if (!existsSync(certPath) || !existsSync(keyPath)) { return null; } const cert = await readFile(certPath, "utf-8"); const key = await readFile(keyPath, "utf-8"); return createSecureContext({ cert, key }); } }