mirror of
https://github.com/fosrl/pangolin.git
synced 2026-07-31 01:35:34 +02:00
267 lines
9.2 KiB
TypeScript
267 lines
9.2 KiB
TypeScript
/*
|
|
* This file is part of a proprietary work.
|
|
*
|
|
* Copyright (c) 2025-2026 Fossorial, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This file is licensed under the Fossorial Commercial License.
|
|
* You may not use this file except in compliance with the License.
|
|
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
|
|
*
|
|
* This file is not licensed under the AGPLv3.
|
|
*/
|
|
import { Request, Response, NextFunction } from "express";
|
|
import { z } from "zod";
|
|
import { certificates, db, domains, orgDomains } from "@server/db";
|
|
import { eq, and, or, like, inArray } from "drizzle-orm";
|
|
import response from "@server/lib/response";
|
|
import HttpCode from "@server/types/HttpCode";
|
|
import createHttpError from "http-errors";
|
|
import logger from "@server/logger";
|
|
import { fromError } from "zod-validation-error";
|
|
import { registry } from "@server/openApi";
|
|
import {
|
|
GetCertificateResponse,
|
|
type GetBatchedCertificateResponse
|
|
} from "@server/routers/certificates/types";
|
|
|
|
const getCertificateParamSchema = z.strictObject({
|
|
orgId: z.string()
|
|
});
|
|
|
|
const getCertificateQuerySchema = z.object({
|
|
domains: z.preprocess(
|
|
(val) => {
|
|
if (val === undefined || val === null || val === "") {
|
|
return undefined;
|
|
}
|
|
if (Array.isArray(val)) {
|
|
return val;
|
|
}
|
|
// the array is returned as this
|
|
if (typeof val === "string") {
|
|
return val.split(",");
|
|
}
|
|
return undefined;
|
|
},
|
|
z.array(z.string().min(1).max(255))
|
|
)
|
|
});
|
|
|
|
async function query1(domainId: string, domain: string) {
|
|
const [domainRecord] = await db
|
|
.select()
|
|
.from(domains)
|
|
.where(eq(domains.domainId, domainId))
|
|
.limit(1);
|
|
|
|
if (!domainRecord) {
|
|
throw new Error(`Domain with ID ${domainId} not found`);
|
|
}
|
|
|
|
const domainType = domainRecord.type;
|
|
|
|
let existing: any[] = [];
|
|
if (domainRecord.type == "ns" || domainRecord.type == "wildcard") {
|
|
const domainLevelDown = domain.split(".").slice(1).join(".");
|
|
const wildcardPrefixed = `*.${domainLevelDown}`;
|
|
|
|
existing = await db
|
|
.select({
|
|
certId: certificates.certId,
|
|
domain: certificates.domain,
|
|
wildcard: certificates.wildcard,
|
|
status: certificates.status,
|
|
expiresAt: certificates.expiresAt,
|
|
lastRenewalAttempt: certificates.lastRenewalAttempt,
|
|
createdAt: certificates.createdAt,
|
|
updatedAt: certificates.updatedAt,
|
|
errorMessage: certificates.errorMessage,
|
|
renewalCount: certificates.renewalCount
|
|
})
|
|
.from(certificates)
|
|
.where(
|
|
and(
|
|
eq(certificates.domainId, domainId),
|
|
or(
|
|
eq(certificates.domain, domain),
|
|
and(
|
|
eq(certificates.wildcard, true),
|
|
or(
|
|
eq(certificates.domain, domainLevelDown),
|
|
eq(certificates.domain, wildcardPrefixed)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
);
|
|
} else {
|
|
// For non-NS domains, we only match exact domain names
|
|
existing = await db
|
|
.select({
|
|
certId: certificates.certId,
|
|
domain: certificates.domain,
|
|
wildcard: certificates.wildcard,
|
|
status: certificates.status,
|
|
expiresAt: certificates.expiresAt,
|
|
lastRenewalAttempt: certificates.lastRenewalAttempt,
|
|
createdAt: certificates.createdAt,
|
|
updatedAt: certificates.updatedAt,
|
|
errorMessage: certificates.errorMessage,
|
|
renewalCount: certificates.renewalCount
|
|
})
|
|
.from(certificates)
|
|
.where(
|
|
and(
|
|
eq(certificates.domainId, domainId),
|
|
eq(certificates.domain, domain) // exact match for non-NS domains
|
|
)
|
|
);
|
|
}
|
|
|
|
return existing.length > 0 ? { ...existing[0], domainType } : null;
|
|
}
|
|
|
|
async function query(orgId: string, domainList: string[]) {
|
|
// Try to get CNAME certificates first
|
|
let existingCertificates = await db
|
|
.select({
|
|
certId: certificates.certId,
|
|
domain: certificates.domain,
|
|
wildcard: certificates.wildcard,
|
|
status: certificates.status,
|
|
expiresAt: certificates.expiresAt,
|
|
lastRenewalAttempt: certificates.lastRenewalAttempt,
|
|
createdAt: certificates.createdAt,
|
|
updatedAt: certificates.updatedAt,
|
|
errorMessage: certificates.errorMessage,
|
|
renewalCount: certificates.renewalCount,
|
|
domainType: domains.type
|
|
})
|
|
.from(certificates)
|
|
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
|
|
.innerJoin(
|
|
orgDomains,
|
|
and(
|
|
eq(domains.domainId, orgDomains.domainId),
|
|
eq(orgDomains.orgId, orgId)
|
|
)
|
|
)
|
|
.where(and(inArray(certificates.domain, domainList)));
|
|
|
|
// All non resolved domain certificates might be `ns` or `wildcard`,
|
|
// which means exact domain certificates do not
|
|
const nonAvailableCertificates = existingCertificates
|
|
.filter((cert) => !domainList.includes(cert.domain))
|
|
.map((cert) => cert.domain);
|
|
|
|
if (nonAvailableCertificates.length > 0) {
|
|
const domainLevelDownSet = new Set<string>();
|
|
const wildcardDomainSet = new Set<string>();
|
|
|
|
for (const domain of nonAvailableCertificates) {
|
|
const domainLevelDown = domain.split(".").slice(1).join(".");
|
|
const wildcardPrefixed = `*.${domainLevelDown}`;
|
|
domainLevelDownSet.add(domainLevelDown);
|
|
wildcardDomainSet.add(wildcardPrefixed);
|
|
}
|
|
|
|
// Need to map the certificates to each domain
|
|
const wildcardCertificates = await db
|
|
.select({
|
|
certId: certificates.certId,
|
|
domain: certificates.domain,
|
|
wildcard: certificates.wildcard,
|
|
status: certificates.status,
|
|
expiresAt: certificates.expiresAt,
|
|
lastRenewalAttempt: certificates.lastRenewalAttempt,
|
|
createdAt: certificates.createdAt,
|
|
updatedAt: certificates.updatedAt,
|
|
errorMessage: certificates.errorMessage,
|
|
renewalCount: certificates.renewalCount,
|
|
domainType: domains.type
|
|
})
|
|
.from(certificates)
|
|
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
|
|
.innerJoin(
|
|
orgDomains,
|
|
and(
|
|
eq(domains.domainId, orgDomains.domainId),
|
|
eq(orgDomains.orgId, orgId)
|
|
)
|
|
)
|
|
.where(
|
|
and(
|
|
eq(certificates.wildcard, true),
|
|
or(
|
|
inArray(certificates.domain, [...domainLevelDownSet]),
|
|
inArray(certificates.domain, [...wildcardDomainSet])
|
|
)
|
|
)
|
|
);
|
|
|
|
existingCertificates.push(...wildcardCertificates);
|
|
}
|
|
|
|
const certificateMap: Record<string, any> = {};
|
|
for (const domain of domainList) {
|
|
const domainLevelDown = domain.split(".").slice(1).join(".");
|
|
const wildcardPrefixed = `*.${domainLevelDown}`;
|
|
certificateMap[domain] =
|
|
existingCertificates.find(
|
|
(cert) =>
|
|
cert.domain === domain ||
|
|
cert.domain === domainLevelDown ||
|
|
cert.domain === wildcardPrefixed
|
|
) ?? null;
|
|
}
|
|
|
|
return certificateMap;
|
|
}
|
|
|
|
export async function getBatchedCertificates(
|
|
req: Request,
|
|
res: Response,
|
|
next: NextFunction
|
|
): Promise<any> {
|
|
try {
|
|
const parsedParams = getCertificateParamSchema.safeParse(req.params);
|
|
if (!parsedParams.success) {
|
|
return next(
|
|
createHttpError(
|
|
HttpCode.BAD_REQUEST,
|
|
fromError(parsedParams.error).toString()
|
|
)
|
|
);
|
|
}
|
|
|
|
const { orgId } = parsedParams.data;
|
|
const parsedQuery = getCertificateQuerySchema.safeParse(req.query);
|
|
if (!parsedQuery.success) {
|
|
return next(
|
|
createHttpError(
|
|
HttpCode.BAD_REQUEST,
|
|
fromError(parsedQuery.error).toString()
|
|
)
|
|
);
|
|
}
|
|
|
|
const { domains } = parsedQuery.data;
|
|
|
|
const cert = await query(orgId, domains);
|
|
|
|
return response<GetBatchedCertificateResponse>(res, {
|
|
data: cert,
|
|
success: true,
|
|
error: false,
|
|
message: "Certificates retrieved successfully",
|
|
status: HttpCode.OK
|
|
});
|
|
} catch (error) {
|
|
logger.error(error);
|
|
return next(
|
|
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
|
);
|
|
}
|
|
}
|