Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

56.9 KB
Raw Blame
import { Knex } from "knex";

import { TDbClient } from "@app/db";
import { TableName, TCertificates, TCertificatesInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { sanitizeSqlLikeString } from "@app/lib/fn/string";
import { ormify, selectAllTableCols } from "@app/lib/knex";
import {
  applyProcessedPermissionRulesToQuery,
  type ProcessedPermissionRules
} from "@app/lib/knex/permission-filter-utils";
import { isUuidV4 } from "@app/lib/validator";
import {
  CertSubjectAlternativeNameType,
  mapExtendedKeyUsageToLegacy,
  mapLegacyExtendedKeyUsageToStandard
} from "@app/services/certificate-common/certificate-constants";
import {
  buildCertificateQuotaKey,
  certificateHasWildcard
} from "@app/services/certificate-common/certificate-quota-key";
import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";

import { keySizeToAlgorithms } from "./certificate-fns";
import { CertKeyAlgorithm, CertStatus } from "./certificate-types";

// Scoped to UI-surfaced algorithms; intentionally narrower than pqc-utils.PQC_ALGORITHMS.
export const PQC_KEY_ALGORITHMS: string[] = [
  CertKeyAlgorithm.ML_DSA_44,
  CertKeyAlgorithm.ML_DSA_65,
  CertKeyAlgorithm.ML_DSA_87
];

export const NON_PQC_KEY_ALGORITHMS: string[] = [
  CertKeyAlgorithm.RSA_2048,
  CertKeyAlgorithm.RSA_3072,
  CertKeyAlgorithm.RSA_4096,
  CertKeyAlgorithm.ECDSA_P256,
  CertKeyAlgorithm.ECDSA_P384,
  CertKeyAlgorithm.ECDSA_P521
];

export type TCertificateDALFactory = ReturnType<typeof certificateDALFactory>;

const toLegacyExtendedKeyUsageForQuery = (usage: string): string => {
  try {
    return mapExtendedKeyUsageToLegacy(mapLegacyExtendedKeyUsageToStandard(usage));
  } catch {
    return usage;
  }
};

export type TOriginatingCertificateRequest = {
  exists: boolean;
  enrollmentType: string | null;
  csr: string | null;
  commonName: string | null;
  organization: string | null;
  organizationalUnit: string | null;
  country: string | null;
  state: string | null;
  locality: string | null;
  domainComponents: string | null;
  altNames: { type: CertSubjectAlternativeNameType; value: string }[] | null;
  keyUsages: string[] | null;
  extendedKeyUsages: string[] | null;
  customExtensions: unknown;
  keyAlgorithm: string | null;
  signatureAlgorithm: string | null;
};

export const certificateDALFactory = (db: TDbClient) => {
  const certificateOrm = ormify(db, TableName.Certificate);

  // Every certificate insert funnels through here, so no site can forget these.
  const create = async (data: Omit<TCertificatesInsert, "quotaKey" | "hasWildcard">, tx?: Knex) =>
    certificateOrm.create(
      {
        ...data,
        quotaKey: buildCertificateQuotaKey({ commonName: data.commonName, altNames: data.altNames }),
        hasWildcard: certificateHasWildcard({ commonName: data.commonName, altNames: data.altNames })
      },
      tx
    );

  const findLatestActiveCertForSubscriber = async ({ subscriberId }: { subscriberId: string }) => {
    try {
      const cert = await db
        .replicaNode()(TableName.Certificate)
        .where({ pkiSubscriberId: subscriberId, status: CertStatus.ACTIVE })
        .where("notAfter", ">", new Date())
        .whereNull("deletedAt")
        .orderBy("notBefore", "desc")
        .first();

      return cert;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find latest active certificate for subscriber" });
    }
  };

  const findAllActiveCertsForSubscriber = async ({ subscriberId }: { subscriberId: string }) => {
    try {
      const certs = await db
        .replicaNode()(TableName.Certificate)
        .where({ pkiSubscriberId: subscriberId, status: CertStatus.ACTIVE })
        .where("notAfter", ">", new Date())
        .whereNull("deletedAt")
        .orderBy("notBefore", "desc");

      return certs;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find all active certificates for subscriber" });
    }
  };

  const findActiveDigiCertCertsByOrderIds = async (caId: string, orderIds: number[]) => {
    if (orderIds.length === 0) return [];
    try {
      const stringIds = orderIds.map(String);
      const placeholders = stringIds.map(() => "?").join(", ");
      const certs = await db
        .replicaNode()(TableName.Certificate)
        .where({ caId, status: CertStatus.ACTIVE })
        .whereRaw(`"externalMetadata"->>'type' = ?`, ["digicert"])
        .whereRaw(`("externalMetadata"->>'orderId') IN (${placeholders})`, stringIds)
        .select("id", "commonName", "serialNumber", "projectId", "applicationId", "deletedAt");

      return certs;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find active DigiCert certs by order IDs" });
    }
  };

  const findActiveDigiCertCertsByCaId = async (caId: string) => {
    try {
      const certs = await db
        .replicaNode()(TableName.Certificate)
        .where({ caId, status: CertStatus.ACTIVE })
        .where("notAfter", ">", new Date())
        .whereRaw(`"externalMetadata"->>'type' = ?`, ["digicert"])
        .select("id", "commonName", "serialNumber", "projectId", "applicationId", "deletedAt", "externalMetadata");

      return certs;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find active DigiCert certificates by CA" });
    }
  };

  type TInventoryFilterParams = {
    friendlyName?: string;
    commonName?: string;
    search?: string;
    status?: string | string[];
    includeDeleted?: boolean;
    profileIds?: string[];
    fromDate?: Date;
    toDate?: Date;
    metadataFilter?: Array<{ key: string; value?: string }>;
    extendedKeyUsage?: string;
    keyAlgorithm?: string | string[];
    signatureAlgorithm?: string;
    keySizes?: number[];
    caIds?: string[];
    enrollmentTypes?: string[];
    source?: string | string[];
    notAfterFrom?: Date;
    notAfterTo?: Date;
    notBeforeFrom?: Date;
    notBeforeTo?: Date;
    applicationId?: string;
    applicationIds?: string[];
  };

  type TSyncEligibilityFilterParams = Omit<TInventoryFilterParams, "status">;

  type TPkiSyncMatchFilters = {
    profileIds?: string[];
    certificateOrderIds?: string[];
    metadata?: { key: string; value?: string }[];
  };

  type TMatchedSyncCertificate = {
    id: string;
    commonName: string;
    altNames?: string | null;
    serialNumber: string;
    notAfter: Date;
    orderId: string;
    profileName?: string | null;
  };

  const applyInventoryFilters = (
    query: Knex.QueryBuilder,
    filters: TInventoryFilterParams,
    hasProfileJoin: boolean
  ): Knex.QueryBuilder => {
    let q = query;

    if (filters.friendlyName) {
      const sanitizedValue = sanitizeSqlLikeString(filters.friendlyName);
      q = q.andWhere(`${TableName.Certificate}.friendlyName`, "like", `%${sanitizedValue}%`);
    }

    if (filters.commonName) {
      const sanitizedValue = sanitizeSqlLikeString(filters.commonName);
      q = q.andWhere(`${TableName.Certificate}.commonName`, "like", `%${sanitizedValue}%`);
    }

    if (filters.search) {
      const sanitizedValue = sanitizeSqlLikeString(filters.search);
      q = q.andWhere((qb: Knex.QueryBuilder) => {
        void qb
          .where(`${TableName.Certificate}.commonName`, "like", `%${sanitizedValue}%`)
          .orWhere(`${TableName.Certificate}.altNames`, "like", `%${sanitizedValue}%`)
          .orWhere(`${TableName.Certificate}.serialNumber`, "like", `%${sanitizedValue}%`)
          .orWhere(`${TableName.Certificate}.friendlyName`, "like", `%${sanitizedValue}%`);

        if (isUuidV4(sanitizedValue)) {
          void qb.orWhere(`${TableName.Certificate}.id`, sanitizedValue);
        }
      });
    }

    if (!filters.status && !filters.includeDeleted) {
      q = q.whereNull(`${TableName.Certificate}.deletedAt`);
    }

    if (filters.status) {
      const now = new Date();
      const statuses = Array.isArray(filters.status) ? filters.status : [filters.status];

      q = q.andWhere((qb: Knex.QueryBuilder) => {
        statuses.forEach((statusValue, index) => {
          const whereMethod = index === 0 ? "where" : "orWhere";

          if (statusValue === CertStatus.DELETED) {
            void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
              void innerQb.whereNotNull(`${TableName.Certificate}.deletedAt`);
            });
          } else if (statusValue === CertStatus.ACTIVE) {
            void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
              void innerQb
                .where(`${TableName.Certificate}.notAfter`, ">", now)
                .andWhere(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
                .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
                .whereNull(`${TableName.Certificate}.deletedAt`);
            });
          } else if (statusValue === CertStatus.RENEWED) {
            void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
              void innerQb
                .where(`${TableName.Certificate}.notAfter`, ">", now)
                .andWhere(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
                .whereNotNull(`${TableName.Certificate}.renewedByCertificateId`)
                .whereNull(`${TableName.Certificate}.deletedAt`);
            });
          } else if (statusValue === CertStatus.EXPIRED) {
            void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
              void innerQb
                .where(`${TableName.Certificate}.notAfter`, "<=", now)
                .andWhere(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
                .whereNull(`${TableName.Certificate}.deletedAt`);
            });
          } else {
            void qb[whereMethod]((innerQb: Knex.QueryBuilder) => {
              void innerQb
                .where(`${TableName.Certificate}.status`, statusValue)
                .whereNull(`${TableName.Certificate}.deletedAt`);
            });
          }
        });
      });
    }

    if (filters.fromDate) {
      q = q.andWhere(`${TableName.Certificate}.createdAt`, ">=", filters.fromDate);
    }

    if (filters.toDate) {
      q = q.andWhere(`${TableName.Certificate}.createdAt`, "<=", filters.toDate);
    }

    if (filters.profileIds) {
      q = q.whereIn(`${TableName.Certificate}.profileId`, filters.profileIds);
    }

    if (filters.metadataFilter && filters.metadataFilter.length > 0) {
      q = applyMetadataFilter(q, filters.metadataFilter, "certificateId", TableName.Certificate);
    }

    if (filters.extendedKeyUsage) {
      q = q.whereRaw(`"${TableName.Certificate}"."extendedKeyUsages" @> ARRAY[?]::text[]`, [
        toLegacyExtendedKeyUsageForQuery(filters.extendedKeyUsage)
      ]);
    }

    if (filters.keyAlgorithm) {
      if (Array.isArray(filters.keyAlgorithm)) {
        q = q.whereIn(`${TableName.Certificate}.keyAlgorithm`, filters.keyAlgorithm);
      } else {
        q = q.andWhere(`${TableName.Certificate}.keyAlgorithm`, filters.keyAlgorithm);
      }
    }

    if (filters.signatureAlgorithm) {
      q = q.andWhere(`${TableName.Certificate}.signatureAlgorithm`, filters.signatureAlgorithm);
    }

    if (filters.keySizes && filters.keySizes.length > 0) {
      const allAlgorithms = filters.keySizes.flatMap((size) => keySizeToAlgorithms(size));
      q = q.whereIn(`${TableName.Certificate}.keyAlgorithm`, allAlgorithms);
    }

    if (filters.caIds) {
      q = q.whereIn(`${TableName.Certificate}.caId`, filters.caIds);
    }

    if (filters.enrollmentTypes && filters.enrollmentTypes.length > 0 && hasProfileJoin) {
      // Mirror the COALESCE expression used in the SELECT: the actual enrollment recorded
      // on the originating certificate_requests row takes precedence over the profile's
      // enrollmentType. Under the application/junction flow every profile defaults to 'api',
      // so filtering on the profile column alone would either match everything (API) or
      // nothing (other methods).
      const placeholders = filters.enrollmentTypes.map(() => "?").join(", ");
      q = q.whereRaw(
        `COALESCE(
          (
            SELECT certificate_requests."enrollmentType"
            FROM certificate_requests
            WHERE certificate_requests."certificateId" = certificates.id
            ORDER BY certificate_requests."createdAt" ASC
            LIMIT 1
          ),
          pki_certificate_profiles."enrollmentType",
          CASE
            WHEN certificates."caId" IS NULL AND certificates.source IN ('imported', 'discovered') THEN NULL
            ELSE 'api'
          END
        ) IN (${placeholders})`,
        filters.enrollmentTypes
      );
    }

    if (filters.source) {
      const sources = Array.isArray(filters.source) ? filters.source : [filters.source];
      const includesIssued = sources.includes("issued");
      const otherSources = sources.filter((s) => s !== "issued");

      q = q.andWhere((qb: Knex.QueryBuilder) => {
        if (otherSources.length > 0) {
          void qb.whereIn(`${TableName.Certificate}.source`, otherSources);
        }
        if (includesIssued) {
          void qb.orWhere(`${TableName.Certificate}.source`, "issued").orWhereNull(`${TableName.Certificate}.source`);
        }
      });
    }

    if (filters.notAfterFrom) {
      q = q.andWhere(`${TableName.Certificate}.notAfter`, ">=", filters.notAfterFrom);
    }

    if (filters.notAfterTo) {
      q = q.andWhere(`${TableName.Certificate}.notAfter`, "<=", filters.notAfterTo);
    }

    if (filters.notBeforeFrom) {
      q = q.andWhere(`${TableName.Certificate}.notBefore`, ">=", filters.notBeforeFrom);
    }

    if (filters.notBeforeTo) {
      q = q.andWhere(`${TableName.Certificate}.notBefore`, "<=", filters.notBeforeTo);
    }

    if (filters.applicationId) {
      q = q.andWhere(`${TableName.Certificate}.applicationId`, filters.applicationId);
    }

    if (filters.applicationIds && filters.applicationIds.length > 0) {
      q = q.whereIn(`${TableName.Certificate}.applicationId`, filters.applicationIds);
    }

    return q;
  };

  const countCertificatesInProject = async (
    {
      projectId,
      ...filters
    }: {
      projectId: string;
    } & TInventoryFilterParams,
    permissionFilters?: ProcessedPermissionRules
  ) => {
    try {
      interface CountResult {
        count: string;
      }

      let query = db.replicaNode()(TableName.Certificate).where(`${TableName.Certificate}.projectId`, projectId);

      const hasEnrollmentTypeFilter = Boolean(filters.enrollmentTypes);
      if (hasEnrollmentTypeFilter) {
        query = query.leftJoin(
          TableName.PkiCertificateProfile,
          `${TableName.Certificate}.profileId`,
          `${TableName.PkiCertificateProfile}.id`
        );
      }

      query = applyInventoryFilters(query, filters, hasEnrollmentTypeFilter) as typeof query;

      if (permissionFilters) {
        query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
      }

      const count = await query.count("*").first();

      return parseInt((count as unknown as CountResult).count || "0", 10);
    } catch (error) {
      throw new DatabaseError({ error, name: "Count all project certificates" });
    }
  };

  const countCertificatesForPkiSubscriber = async (subscriberId: string) => {
    try {
      interface CountResult {
        count: string;
      }

      const query = db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.pkiSubscriberId`, subscriberId);

      const count = await query.count("*").first();

      return parseInt((count as unknown as CountResult).count || "0", 10);
    } catch (error) {
      throw new DatabaseError({ error, name: "Count all subscriber certificates" });
    }
  };

  const findExpiredSyncedCertificates = async (): Promise<TCertificates[]> => {
    try {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      yesterday.setHours(0, 0, 0, 0);

      const today = new Date();
      today.setHours(0, 0, 0, 0);

      const certs = await db
        .replicaNode()(TableName.Certificate)
        .where("notAfter", ">=", yesterday)
        .where("notAfter", "<", today)
        .whereNotNull("pkiSubscriberId")
        .whereNull("deletedAt");

      return certs;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find expired synced certificates" });
    }
  };

  const findByThumbprintInOrg = async ({
    orgId,
    column,
    fingerprint,
    limit
  }: {
    orgId: string;
    column: "fingerprintSha1" | "fingerprintSha256";
    fingerprint: string;
    limit?: number;
  }): Promise<TCertificates[]> => {
    try {
      const query = db
        .replicaNode()(TableName.Certificate)
        .join(TableName.Project, `${TableName.Certificate}.projectId`, `${TableName.Project}.id`)
        .where(`${TableName.Project}.orgId`, orgId)
        .where(`${TableName.Certificate}.${column}`, fingerprint)
        .select(selectAllTableCols(TableName.Certificate));

      if (limit) void query.limit(limit);

      return await query;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find certificate by thumbprint in org" });
    }
  };

  const findActiveCertificatesByIds = async (certificateIds: string[], tx?: Knex): Promise<TCertificates[]> => {
    try {
      if (certificateIds.length === 0) {
        return [];
      }

      const certs = await (tx || db.replicaNode())(TableName.Certificate)
        .whereIn("id", certificateIds)
        .where({ status: CertStatus.ACTIVE })
        .where("notAfter", ">", new Date())
        .whereNull("renewedByCertificateId")
        .whereNull("deletedAt")
        .orderBy("notBefore", "desc")
        .select("*");

      return certs;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find active certificates by IDs" });
    }
  };

  const $applyActiveForSyncEligibility = (query: Knex.QueryBuilder): Knex.QueryBuilder =>
    query
      .where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
      .where(`${TableName.Certificate}.notAfter`, ">", new Date())
      .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
      .whereNull(`${TableName.Certificate}.deletedAt`);

  const findActiveCertificatesForSync = async (
    filter: TSyncEligibilityFilterParams & { projectId: string },
    options?: { limit?: number; offset?: number },
    permissionFilters?: ProcessedPermissionRules
  ): Promise<(TCertificates & { hasPrivateKey: boolean; profileName?: string | null })[]> => {
    try {
      const { projectId, ...inventoryFilters } = filter;

      let query = db
        .replicaNode()(TableName.Certificate)
        .leftJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`)
        .leftJoin(
          TableName.PkiCertificateProfile,
          `${TableName.Certificate}.profileId`,
          `${TableName.PkiCertificateProfile}.id`
        )
        .select(selectAllTableCols(TableName.Certificate))
        .select(db.ref(`${TableName.CertificateSecret}.certId`).as("privateKeyRef"))
        .select(db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName"))
        .andWhere(`${TableName.Certificate}.projectId`, projectId);

      query = $applyActiveForSyncEligibility(query) as typeof query;

      query = applyInventoryFilters(query, inventoryFilters, false) as typeof query;

      if (permissionFilters) {
        query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
      }

      if (options?.offset) {
        query = query.offset(options.offset);
      }

      if (options?.limit) {
        query = query.limit(options.limit);
      }

      query = query.orderBy("createdAt", "desc");

      const certs = await query;
      return certs.map((cert) => ({
        ...cert,
        hasPrivateKey: Boolean(cert.privateKeyRef)
      }));
    } catch (error) {
      throw new DatabaseError({ error, name: "Find active certificates for sync" });
    }
  };

  const $buildSyncFilterMatchQuery = (
    filters: TPkiSyncMatchFilters | null | undefined,
    scope: { projectId: string; applicationId: string; certificateId?: string },
    permissionFilters?: ProcessedPermissionRules
  ) => {
    let query = db(TableName.Certificate)
      .leftJoin(
        TableName.PkiCertificateProfile,
        `${TableName.Certificate}.profileId`,
        `${TableName.PkiCertificateProfile}.id`
      )
      .where(`${TableName.Certificate}.projectId`, scope.projectId)
      .andWhere(`${TableName.Certificate}.applicationId`, scope.applicationId);

    query = $applyActiveForSyncEligibility(query) as typeof query;

    if (scope.certificateId) {
      query = query.andWhere(`${TableName.Certificate}.id`, scope.certificateId);
    }

    if (filters?.certificateOrderIds) {
      query = query.whereIn(`${TableName.Certificate}.orderId`, filters.certificateOrderIds);
    }

    if (filters?.profileIds) {
      query = query.whereIn(`${TableName.Certificate}.profileId`, filters.profileIds);
    }

    if (filters?.metadata) {
      query = filters.metadata.length
        ? applyMetadataFilter(query, filters.metadata, "certificateId", TableName.Certificate)
        : query.whereRaw("1 = 0");
    }

    if (permissionFilters) {
      query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
    }

    return query;
  };

  const countCertificatesMatchingSyncFilters = async (
    filters: TPkiSyncMatchFilters | null | undefined,
    scope: { projectId: string; applicationId: string },
    permissionFilters?: ProcessedPermissionRules
  ): Promise<number> => {
    try {
      const result = (await $buildSyncFilterMatchQuery(filters, scope, permissionFilters).count(
        `${TableName.Certificate}.id as count`
      )) as unknown as Array<{ count: string }>;

      return Number(result?.[0]?.count ?? 0);
    } catch (error) {
      throw new DatabaseError({ error, name: "Count certificates matching sync filters" });
    }
  };

  const findReadableCertificateIds = async (
    certificateIds: string[],
    projectId: string,
    permissionFilters?: ProcessedPermissionRules
  ): Promise<string[]> => {
    try {
      if (certificateIds.length === 0) return [];

      let query = db(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereIn(`${TableName.Certificate}.id`, certificateIds);

      if (permissionFilters) {
        query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
      }

      const rows = (await query.select(`${TableName.Certificate}.id`)) as { id: string }[];

      return rows.map((row) => row.id);
    } catch (error) {
      throw new DatabaseError({ error, name: "Find readable certificates by IDs" });
    }
  };

  const findLatestCertificatesByOrderIds = async (
    orderIds: string[],
    scope: { projectId: string; applicationId: string },
    permissionFilters?: ProcessedPermissionRules
  ): Promise<{ orderId: string; commonName: string; altNames: string | null }[]> => {
    try {
      if (orderIds.length === 0) return [];

      let query = db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, scope.projectId)
        .andWhere(`${TableName.Certificate}.applicationId`, scope.applicationId)
        .whereIn(`${TableName.Certificate}.orderId`, orderIds);

      if (permissionFilters) {
        query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
      }

      const rows = await query
        .distinctOn(`${TableName.Certificate}.orderId`)
        .orderBy(`${TableName.Certificate}.orderId`, "asc")
        .orderByRaw(`"${TableName.Certificate}"."deletedAt" IS NOT NULL`)
        .orderBy([
          { column: `${TableName.Certificate}.notBefore`, order: "desc" },
          { column: `${TableName.Certificate}.createdAt`, order: "desc" }
        ])
        .select(
          `${TableName.Certificate}.orderId`,
          `${TableName.Certificate}.commonName`,
          `${TableName.Certificate}.altNames`
        );

      return rows as { orderId: string; commonName: string; altNames: string | null }[];
    } catch (error) {
      throw new DatabaseError({ error, name: "Find latest certificates by order IDs" });
    }
  };

  const findCertificatesMatchingSyncFilters = async (
    filters: TPkiSyncMatchFilters | null | undefined,
    scope: { projectId: string; applicationId: string; certificateId?: string },
    options?: { offset?: number; limit?: number; permissionFilters?: ProcessedPermissionRules }
  ): Promise<TMatchedSyncCertificate[]> => {
    try {
      let query = $buildSyncFilterMatchQuery(filters, scope, options?.permissionFilters);

      if (options?.offset) {
        query = query.offset(options.offset);
      }

      if (options?.limit) {
        query = query.limit(options.limit);
      }

      return (await query
        .orderBy(`${TableName.Certificate}.commonName`, "asc")
        .select(
          `${TableName.Certificate}.id`,
          `${TableName.Certificate}.commonName`,
          `${TableName.Certificate}.serialNumber`,
          `${TableName.Certificate}.notAfter`,
          `${TableName.Certificate}.orderId`,
          db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName")
        )) as TMatchedSyncCertificate[];
    } catch (error) {
      throw new DatabaseError({ error, name: "Find certificates matching sync filters" });
    }
  };

  const countActiveCertificatesForSync = async (
    filter: TSyncEligibilityFilterParams & { projectId: string },
    permissionFilters?: ProcessedPermissionRules
  ) => {
    try {
      interface CountResult {
        count: string;
      }

      const { projectId, ...inventoryFilters } = filter;

      let query = db.replicaNode()(TableName.Certificate).where(`${TableName.Certificate}.projectId`, projectId);

      query = $applyActiveForSyncEligibility(query) as typeof query;
      query = applyInventoryFilters(query, inventoryFilters, false) as typeof query;

      if (permissionFilters) {
        query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
      }

      const count = await query.count("*").first();

      return parseInt((count as unknown as CountResult).count || "0", 10);
    } catch (error) {
      throw new DatabaseError({ error, name: "Count active certificates for sync" });
    }
  };

  const findCertificatesEligibleForRenewal = async ({
    limit,
    offset
  }: {
    limit: number;
    offset: number;
  }): Promise<(TCertificates & { profileName?: string; applicationName?: string | null })[]> => {
    try {
      const now = new Date();
      const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);

      const certs = (await db
        .replicaNode()(TableName.Certificate)
        .select(selectAllTableCols(TableName.Certificate))
        .select(db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName"))
        .select(db.ref("name").withSchema(TableName.PkiApplication).as("applicationName"))
        .leftJoin(
          TableName.PkiCertificateProfile,
          `${TableName.Certificate}.profileId`,
          `${TableName.PkiCertificateProfile}.id`
        )
        .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`)
        .innerJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`)
        .where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
        .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .whereNull(`${TableName.Certificate}.renewalError`)
        .whereNull(`${TableName.Certificate}.revokedAt`)
        .whereNotNull(`${TableName.Certificate}.profileId`)
        .whereNotNull(`${TableName.Certificate}.notAfter`)
        .where(`${TableName.Certificate}.notAfter`, ">", now)
        .whereNotNull(`${TableName.Certificate}.renewBeforeDays`)
        .where(`${TableName.Certificate}.renewBeforeDays`, ">", 0)
        .whereRaw(
          `"${TableName.Certificate}"."notAfter" - INTERVAL '1 day' * "${TableName.Certificate}"."renewBeforeDays" <= ?`,
          [endOfDay]
        )
        .limit(limit)
        .offset(offset)
        .orderBy(`${TableName.Certificate}.notAfter`, "asc")) as TCertificates[];

      return certs;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find certificates eligible for renewal" });
    }
  };

  const getOriginatingRequestByCertId = async (certId: string, tx?: Knex): Promise<TOriginatingCertificateRequest> => {
    try {
      // Primary, not replica: eligibility checks must not miss a recently-issued request row.
      const row = (await (tx || db)(TableName.CertificateRequests)
        .where(`${TableName.CertificateRequests}.certificateId`, certId)
        .orderBy(`${TableName.CertificateRequests}.createdAt`, "asc")
        .select(
          `${TableName.CertificateRequests}.enrollmentType`,
          `${TableName.CertificateRequests}.csr`,
          `${TableName.CertificateRequests}.commonName`,
          `${TableName.CertificateRequests}.organization`,
          `${TableName.CertificateRequests}.organizationalUnit`,
          `${TableName.CertificateRequests}.country`,
          `${TableName.CertificateRequests}.state`,
          `${TableName.CertificateRequests}.locality`,
          `${TableName.CertificateRequests}.domainComponents`,
          `${TableName.CertificateRequests}.altNames`,
          `${TableName.CertificateRequests}.keyUsages`,
          `${TableName.CertificateRequests}.extendedKeyUsages`,
          `${TableName.CertificateRequests}.customExtensions`,
          `${TableName.CertificateRequests}.keyAlgorithm`,
          `${TableName.CertificateRequests}.signatureAlgorithm`
        )
        .first()) as Partial<TOriginatingCertificateRequest> | undefined;

      return {
        exists: Boolean(row),
        enrollmentType: row?.enrollmentType ?? null,
        csr: row?.csr ?? null,
        commonName: row?.commonName ?? null,
        organization: row?.organization ?? null,
        organizationalUnit: row?.organizationalUnit ?? null,
        country: row?.country ?? null,
        state: row?.state ?? null,
        locality: row?.locality ?? null,
        domainComponents: row?.domainComponents ?? null,
        altNames: row?.altNames ?? null,
        keyUsages: row?.keyUsages ?? null,
        extendedKeyUsages: row?.extendedKeyUsages ?? null,
        customExtensions: row?.customExtensions ?? null,
        keyAlgorithm: row?.keyAlgorithm ?? null,
        signatureAlgorithm: row?.signatureAlgorithm ?? null
      };
    } catch (error) {
      throw new DatabaseError({ error, name: "Get originating request by cert id" });
    }
  };

  const getRequestEnrollmentTypeByCertId = async (certId: string, tx?: Knex): Promise<string | null> =>
    (await getOriginatingRequestByCertId(certId, tx)).enrollmentType;

  type TCertificateWithInventoryFields = TCertificates & {
    hasPrivateKey: boolean;
    caName?: string | null;
    profileName?: string | null;
    enrollmentType?: string | null;
    applicationName?: string | null;
  };

  const findWithPrivateKeyInfo = async (
    filter: Partial<Omit<TCertificates, "status" | "keyAlgorithm" | "source"> & TInventoryFilterParams>,
    options?: { offset?: number; limit?: number; sort?: [string, "asc" | "desc"][] },
    permissionFilters?: ProcessedPermissionRules
  ): Promise<TCertificateWithInventoryFields[]> => {
    try {
      let query = db
        .replicaNode()(TableName.Certificate)
        .leftJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`)
        .leftJoin(
          TableName.CertificateAuthority,
          `${TableName.Certificate}.caId`,
          `${TableName.CertificateAuthority}.id`
        )
        .leftJoin(
          TableName.PkiCertificateProfile,
          `${TableName.Certificate}.profileId`,
          `${TableName.PkiCertificateProfile}.id`
        )
        .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`)
        .select(selectAllTableCols(TableName.Certificate))
        .select(db.ref(`${TableName.CertificateSecret}.certId`).as("privateKeyRef"))
        .select(db.ref("name").withSchema(TableName.CertificateAuthority).as("caName"))
        .select(db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName"))
        .select(
          db.raw(
            `COALESCE(
              (
                SELECT certificate_requests."enrollmentType"
                FROM certificate_requests
                WHERE certificate_requests."certificateId" = certificates.id
                ORDER BY certificate_requests."createdAt" ASC
                LIMIT 1
              ),
              pki_certificate_profiles."enrollmentType",
              CASE
                WHEN certificates."caId" IS NULL AND certificates.source IN ('imported', 'discovered') THEN NULL
                ELSE 'api'
              END
            ) as "enrollmentType"`
          )
        )
        .select(db.ref("name").withSchema(TableName.PkiApplication).as("applicationName"));

      const {
        friendlyName,
        commonName,
        search,
        status,
        includeDeleted,
        profileIds,
        fromDate,
        toDate,
        metadataFilter,
        extendedKeyUsage,
        keyAlgorithm,
        signatureAlgorithm,
        keySizes,
        caIds,
        enrollmentTypes,
        source,
        notAfterFrom,
        notAfterTo,
        notBeforeFrom,
        notBeforeTo,
        applicationIds,
        ...regularFilters
      } = filter;

      Object.entries(regularFilters).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          query = query.andWhere(`${TableName.Certificate}.${key}`, value);
        }
      });

      query = applyInventoryFilters(
        query,
        {
          friendlyName,
          commonName,
          search,
          status,
          includeDeleted,
          profileIds,
          fromDate,
          toDate,
          metadataFilter,
          extendedKeyUsage,
          keyAlgorithm,
          signatureAlgorithm,
          keySizes,
          caIds,
          enrollmentTypes,
          source,
          notAfterFrom,
          notAfterTo,
          notBeforeFrom,
          notBeforeTo,
          applicationIds
        },
        true
      ) as typeof query;

      if (permissionFilters) {
        query = applyProcessedPermissionRulesToQuery(query, TableName.Certificate, permissionFilters) as typeof query;
      }

      if (options?.offset) {
        query = query.offset(options.offset);
      }
      if (options?.limit) {
        query = query.limit(options.limit);
      }
      if (options?.sort) {
        options.sort.forEach(([column, direction]) => {
          query = query.orderBy(`${TableName.Certificate}.${column}`, direction);
        });
      }

      const results = await query;
      return results.map((row) => ({
        ...row,
        hasPrivateKey: row.privateKeyRef !== null
      }));
    } catch (error) {
      throw new DatabaseError({ error, name: "Find certificates with private key info" });
    }
  };

  type TCertificateWithRequestDetails = TCertificates & {
    caName?: string | null;
    profileName?: string | null;
    applicationName?: string | null;
    caType?: "internal" | "external" | null;
    hasPrivateKey: boolean;
  };

  type TCertificateLookupFilter = { id: string; serialNumber?: never } | { id?: never; serialNumber: string };

  const findByIdForUpdate = async (id: string, tx: Knex) => {
    try {
      return await tx(TableName.Certificate).where({ id }).forUpdate().first();
    } catch (error) {
      throw new DatabaseError({ error, name: "Find certificate by id for update" });
    }
  };

  const findLatestRenewalOf = async (anchor: { id: string; orderId: string }, tx?: Knex): Promise<string | null> => {
    try {
      const newer = await (tx || db.replicaNode())(TableName.Certificate)
        .where("orderId", anchor.orderId)
        .whereNot("status", CertStatus.REVOKED)
        .whereNull("deletedAt")
        .where("notAfter", ">", db.raw("NOW()"))
        .whereRaw(`("createdAt", "id") > (SELECT "createdAt", "id" FROM ?? WHERE "id" = ?)`, [
          TableName.Certificate,
          anchor.id
        ])
        .orderBy([
          { column: "createdAt", order: "desc" },
          { column: "id", order: "desc" }
        ])
        .select("id")
        .first();

      return newer?.id ?? null;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find latest renewal of certificate" });
    }
  };

  const findWithFullDetails = async (
    filter: TCertificateLookupFilter,
    tx?: Knex
  ): Promise<TCertificateWithRequestDetails | undefined> => {
    try {
      let query = (tx || db.replicaNode())(TableName.Certificate)
        .leftJoin(
          TableName.CertificateAuthority,
          `${TableName.Certificate}.caId`,
          `${TableName.CertificateAuthority}.id`
        )
        .leftJoin(
          TableName.PkiCertificateProfile,
          `${TableName.Certificate}.profileId`,
          `${TableName.PkiCertificateProfile}.id`
        )
        .leftJoin(
          TableName.InternalCertificateAuthority,
          `${TableName.CertificateAuthority}.id`,
          `${TableName.InternalCertificateAuthority}.caId`
        )
        .leftJoin(TableName.PkiApplication, `${TableName.Certificate}.applicationId`, `${TableName.PkiApplication}.id`)
        .leftJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`)
        .select(selectAllTableCols(TableName.Certificate))
        .select(db.ref("name").withSchema(TableName.CertificateAuthority).as("caName"))
        .select(db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName"))
        .select(db.ref("name").withSchema(TableName.PkiApplication).as("applicationName"))
        .select(db.ref("id").withSchema(TableName.InternalCertificateAuthority).as("internalCaId"))
        .select(db.ref("certId").withSchema(TableName.CertificateSecret).as("privateKeyRef"));

      if (filter.id) {
        query = query.where(`${TableName.Certificate}.id`, filter.id);
      } else {
        query = query.where(`${TableName.Certificate}.serialNumber`, filter.serialNumber);
      }

      const result = (await query.first()) as
        | (TCertificateWithRequestDetails & { internalCaId?: string | null; privateKeyRef?: string | null })
        | undefined;

      if (!result) {
        return undefined;
      }

      const { internalCaId, privateKeyRef, ...rest } = result;

      let caType: "internal" | "external" | null = null;
      if (result.caId) {
        caType = internalCaId ? "internal" : "external";
      }

      return {
        ...rest,
        caType,
        hasPrivateKey: Boolean(privateKeyRef)
      } as TCertificateWithRequestDetails;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find certificate with full details" });
    }
  };

  const getDashboardStats = async (projectId: string) => {
    try {
      const now = new Date();
      const thirtyDaysFromNow = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);

      interface TotalsRow {
        total: number;
        active: number;
        renewed: number;
        expiringSoon: number;
        expired: number;
        revoked: number;
        expiringSoonNoAutoRenewal: number;
        expiredNotRenewed: number;
      }

      interface LabelCount {
        label: string | null;
        count: string;
      }

      interface LabelCountWithId extends LabelCount {
        id: string | null;
        isSelfSigned: boolean;
      }

      interface BucketCount {
        bucket: string;
        count: string;
      }

      const [totalsRow] = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .select(
          db.raw("COUNT(*)::int as total"),
          db.raw(
            `COUNT(*) FILTER (WHERE "${TableName.Certificate}"."notAfter" > ? AND "${TableName.Certificate}"."status" != ? AND "${TableName.Certificate}"."renewedByCertificateId" IS NULL)::int as active`,
            [now, CertStatus.REVOKED]
          ),
          db.raw(
            `COUNT(*) FILTER (WHERE "${TableName.Certificate}"."notAfter" > ? AND "${TableName.Certificate}"."status" != ? AND "${TableName.Certificate}"."renewedByCertificateId" IS NOT NULL)::int as renewed`,
            [now, CertStatus.REVOKED]
          ),
          db.raw(
            `COUNT(*) FILTER (WHERE "${TableName.Certificate}"."notAfter" > ? AND "${TableName.Certificate}"."notAfter" <= ? AND "${TableName.Certificate}"."status" != ? AND "${TableName.Certificate}"."renewedByCertificateId" IS NULL)::int as "expiringSoon"`,
            [now, thirtyDaysFromNow, CertStatus.REVOKED]
          ),
          db.raw(
            `COUNT(*) FILTER (WHERE "${TableName.Certificate}"."notAfter" <= ? AND "${TableName.Certificate}"."status" != ?)::int as expired`,
            [now, CertStatus.REVOKED]
          ),
          db.raw(`COUNT(*) FILTER (WHERE "${TableName.Certificate}"."status" = ?)::int as revoked`, [
            CertStatus.REVOKED
          ]),
          db.raw(
            `COUNT(*) FILTER (WHERE "${TableName.Certificate}"."notAfter" > ? AND "${TableName.Certificate}"."notAfter" <= ? AND "${TableName.Certificate}"."status" != ? AND "${TableName.Certificate}"."renewedByCertificateId" IS NULL AND "${TableName.Certificate}"."renewBeforeDays" IS NULL)::int as "expiringSoonNoAutoRenewal"`,
            [now, thirtyDaysFromNow, CertStatus.REVOKED]
          ),
          db.raw(
            `COUNT(*) FILTER (WHERE "${TableName.Certificate}"."notAfter" <= ? AND "${TableName.Certificate}"."status" != ? AND "${TableName.Certificate}"."renewedByCertificateId" IS NULL)::int as "expiredNotRenewed"`,
            [now, CertStatus.REVOKED]
          )
        );

      const totals = totalsRow as unknown as TotalsRow;

      const byAlgorithm = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .select(`${TableName.Certificate}.keyAlgorithm as label`)
        .count("* as count")
        .groupBy(`${TableName.Certificate}.keyAlgorithm`);

      // Issuance never sets `source`, and only a self-signed profile issues without a CA. The request
      // check covers certificates whose profile was deleted, which nulls `profileId`.
      const isSelfSignedExpr = `(
        certificates."caId" IS NULL
        AND COALESCE(certificates.source, 'issued') = 'issued'
        AND (
          certificates."profileId" IS NOT NULL
          OR EXISTS (SELECT 1 FROM certificate_requests WHERE certificate_requests."certificateId" = certificates.id)
        )
      )`;

      const byCA = await db
        .replicaNode()(TableName.Certificate)
        .leftJoin(
          TableName.CertificateAuthority,
          `${TableName.Certificate}.caId`,
          `${TableName.CertificateAuthority}.id`
        )
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .select(`${TableName.CertificateAuthority}.id as id`)
        .select(`${TableName.CertificateAuthority}.name as label`)
        .select(db.raw(`${isSelfSignedExpr} as "isSelfSigned"`))
        .count("* as count")
        .groupBy(`${TableName.CertificateAuthority}.id`, `${TableName.CertificateAuthority}.name`)
        .groupByRaw(isSelfSignedExpr);

      const byStatus = [
        { label: "Active", count: totals.active },
        { label: "Renewed", count: totals.renewed },
        { label: "Expired", count: totals.expired },
        { label: "Revoked", count: totals.revoked }
      ];

      const byEnrollmentMethod = await db
        .replicaNode()(TableName.Certificate)
        .leftJoin(
          TableName.PkiCertificateProfile,
          `${TableName.Certificate}.profileId`,
          `${TableName.PkiCertificateProfile}.id`
        )
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .select(
          db.raw(
            `COALESCE(
              (
                SELECT certificate_requests."enrollmentType"
                FROM certificate_requests
                WHERE certificate_requests."certificateId" = certificates.id
                ORDER BY certificate_requests."createdAt" ASC
                LIMIT 1
              ),
              pki_certificate_profiles."enrollmentType",
              CASE
                WHEN certificates."caId" IS NULL AND certificates.source IN ('imported', 'discovered') THEN NULL
                ELSE 'api'
              END
            ) as label`
          )
        )
        .count("* as count")
        .groupBy("label");

      const sevenDaysFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
      const sixtyDaysFromNow = new Date(now.getTime() + 60 * 24 * 60 * 60 * 1000);
      const ninetyDaysFromNow = new Date(now.getTime() + 90 * 24 * 60 * 60 * 1000);

      const expirationBuckets = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .where(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
        .where((qb) => {
          void qb
            .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
            .orWhere(`${TableName.Certificate}.notAfter`, "<=", now);
        })
        .select(
          db.raw(
            `CASE
              WHEN "${TableName.Certificate}"."notAfter" < ? THEN 'expired'
              WHEN "${TableName.Certificate}"."notAfter" <= ? THEN '0-7d'
              WHEN "${TableName.Certificate}"."notAfter" <= ? THEN '8-30d'
              WHEN "${TableName.Certificate}"."notAfter" <= ? THEN '31-60d'
              WHEN "${TableName.Certificate}"."notAfter" <= ? THEN '61-90d'
              ELSE '90d+'
            END as bucket`,
            [now, sevenDaysFromNow, thirtyDaysFromNow, sixtyDaysFromNow, ninetyDaysFromNow]
          )
        )
        .select(db.raw("count(*)::int as count"))
        .groupBy("bucket");

      const validityBuckets = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .where(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
        .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
        .where(`${TableName.Certificate}.notAfter`, ">", now)
        .whereRaw(`"${TableName.Certificate}"."extendedKeyUsages" @> ARRAY[?]::text[]`, ["serverAuth"])
        .select(
          db.raw(
            `CASE
              WHEN EXTRACT(EPOCH FROM ("${TableName.Certificate}"."notAfter" - "${TableName.Certificate}"."notBefore")) / 86400 <= 47 THEN '<=47d'
              WHEN EXTRACT(EPOCH FROM ("${TableName.Certificate}"."notAfter" - "${TableName.Certificate}"."notBefore")) / 86400 <= 99 THEN '48-99d'
              WHEN EXTRACT(EPOCH FROM ("${TableName.Certificate}"."notAfter" - "${TableName.Certificate}"."notBefore")) / 86400 <= 199 THEN '100-199d'
              ELSE '>=200d'
            END as bucket`
          )
        )
        .select(db.raw("count(*)::int as count"))
        .groupBy("bucket");

      return {
        totals: {
          total: totals.total,
          active: totals.active,
          renewed: totals.renewed,
          expiringSoon: totals.expiringSoon,
          expired: totals.expired,
          revoked: totals.revoked
        },
        expiringSoonNoAutoRenewal: totals.expiringSoonNoAutoRenewal,
        expiredNotRenewed: totals.expiredNotRenewed,
        distributions: {
          byEnrollmentMethod: (byEnrollmentMethod as unknown as LabelCount[]).map((r) => ({
            label: r.label || "Other",
            count: Number(r.count)
          })),
          byAlgorithm: (byAlgorithm as unknown as LabelCount[]).map((r) => ({
            label: r.label || "Unknown",
            count: Number(r.count)
          })),
          byCA: (byCA as unknown as LabelCountWithId[]).map((r) => {
            let label = r.isSelfSigned ? "Self-signed" : "External";
            if (r.id) label = r.label || "Unknown";
            return { id: r.id ?? undefined, label, count: Number(r.count) };
          }),
          byStatus
        },
        expirationBuckets: (expirationBuckets as unknown as BucketCount[]).map((r) => ({
          bucket: r.bucket,
          count: Number(r.count)
        })),
        validityBuckets: (validityBuckets as unknown as BucketCount[]).map((r) => ({
          bucket: r.bucket,
          count: Number(r.count)
        }))
      };
    } catch (error) {
      throw new DatabaseError({ error, name: "Get dashboard stats" });
    }
  };

  const getActivityTrend = async (projectId: string, daysBack: number) => {
    try {
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - daysBack);
      startDate.setHours(0, 0, 0, 0);
      const now = new Date();

      const useDaily = daysBack <= 30;

      if (!useDaily) {
        startDate.setDate(1);
      }
      const truncUnit = useDaily ? "day" : "month";
      const dateFormat = useDaily ? "YYYY-MM-DD" : "YYYY-MM";

      const periodExpr = (col: string) =>
        db.raw(`to_char(date_trunc(?, "${TableName.Certificate}"."${col}"), ?) as period`, [truncUnit, dateFormat]);

      const issued = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .where(`${TableName.Certificate}.notBefore`, ">=", startDate)
        .where(`${TableName.Certificate}.notBefore`, "<=", now)
        .select(periodExpr("notBefore"))
        .select(db.raw("count(*)::int as count"))
        .groupBy("period")
        .orderBy("period");

      const expired = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .where(`${TableName.Certificate}.notAfter`, ">=", startDate)
        .where(`${TableName.Certificate}.notAfter`, "<=", now)
        .where(`${TableName.Certificate}.status`, "!=", CertStatus.REVOKED)
        .select(periodExpr("notAfter"))
        .select(db.raw("count(*)::int as count"))
        .groupBy("period")
        .orderBy("period");

      const revoked = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .where(`${TableName.Certificate}.status`, CertStatus.REVOKED)
        .where(`${TableName.Certificate}.revokedAt`, ">=", startDate)
        .where(`${TableName.Certificate}.revokedAt`, "<=", now)
        .select(periodExpr("revokedAt"))
        .select(db.raw("count(*)::int as count"))
        .groupBy("period")
        .orderBy("period");

      const renewed = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .whereNotNull(`${TableName.Certificate}.renewedFromCertificateId`)
        .where(`${TableName.Certificate}.notBefore`, ">=", startDate)
        .where(`${TableName.Certificate}.notBefore`, "<=", now)
        .select(periodExpr("notBefore"))
        .select(db.raw("count(*)::int as count"))
        .groupBy("period")
        .orderBy("period");

      const periods: Array<{
        period: string;
        issued: number;
        expired: number;
        revoked: number;
        renewed: number;
      }> = [];
      interface PeriodCount {
        period: string;
        count: string;
      }

      const typedIssued = issued as unknown as PeriodCount[];
      const typedExpired = expired as unknown as PeriodCount[];
      const typedRevoked = revoked as unknown as PeriodCount[];
      const typedRenewed = renewed as unknown as PeriodCount[];

      const issuedMap = new Map(typedIssued.map((r) => [r.period, r.count]));
      const expiredMap = new Map(typedExpired.map((r) => [r.period, r.count]));
      const revokedMap = new Map(typedRevoked.map((r) => [r.period, r.count]));
      const renewedMap = new Map(typedRenewed.map((r) => [r.period, r.count]));

      const cursor = new Date(startDate);
      while (cursor <= now) {
        let periodKey: string;
        if (useDaily) {
          periodKey = `${cursor.getFullYear()}-${String(cursor.getMonth() + 1).padStart(2, "0")}-${String(cursor.getDate()).padStart(2, "0")}`;
        } else {
          periodKey = `${cursor.getFullYear()}-${String(cursor.getMonth() + 1).padStart(2, "0")}`;
        }
        const issuedCount = issuedMap.get(periodKey);
        const expiredCount = expiredMap.get(periodKey);
        const revokedCount = revokedMap.get(periodKey);
        const renewedCount = renewedMap.get(periodKey);
        periods.push({
          period: periodKey,
          issued: issuedCount ? Number(issuedCount) : 0,
          expired: expiredCount ? Number(expiredCount) : 0,
          revoked: revokedCount ? Number(revokedCount) : 0,
          renewed: renewedCount ? Number(renewedCount) : 0
        });
        if (useDaily) {
          cursor.setDate(cursor.getDate() + 1);
        } else {
          cursor.setMonth(cursor.getMonth() + 1);
        }
      }

      return { periods };
    } catch (error) {
      throw new DatabaseError({ error, name: "Get activity trend" });
    }
  };

  const getPqcTrend = async (projectId: string, daysBack: number) => {
    try {
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - daysBack);
      startDate.setHours(0, 0, 0, 0);
      const now = new Date();

      const useDaily = daysBack <= 30;
      if (!useDaily) {
        startDate.setDate(1);
      }
      const truncUnit = useDaily ? "day" : "month";
      const dateFormat = useDaily ? "YYYY-MM-DD" : "YYYY-MM";

      const rows = await db
        .replicaNode()(TableName.Certificate)
        .where(`${TableName.Certificate}.projectId`, projectId)
        .whereNull(`${TableName.Certificate}.deletedAt`)
        .where(`${TableName.Certificate}.notBefore`, ">=", startDate)
        .where(`${TableName.Certificate}.notBefore`, "<=", now)
        .select(
          db.raw(`to_char(date_trunc(?, "${TableName.Certificate}"."notBefore"), ?) as period`, [truncUnit, dateFormat])
        )
        .select(
          db.raw(
            `CASE WHEN "${TableName.Certificate}"."keyAlgorithm" IN (${PQC_KEY_ALGORITHMS.map(() => "?").join(",")}) THEN 'pqc' ELSE 'nonPqc' END as bucket`,
            [...PQC_KEY_ALGORITHMS]
          )
        )
        .select(db.raw("count(*)::int as count"))
        .groupBy("period", "bucket")
        .orderBy("period");

      interface PeriodBucketCount {
        period: string;
        bucket: "pqc" | "nonPqc";
        count: string;
      }
      const typed = rows as unknown as PeriodBucketCount[];
      const pqcMap = new Map<string, number>();
      const nonPqcMap = new Map<string, number>();
      typed.forEach((r) => {
        if (r.bucket === "pqc") pqcMap.set(r.period, Number(r.count));
        else nonPqcMap.set(r.period, Number(r.count));
      });

      const periods: Array<{ period: string; pqc: number; nonPqc: number }> = [];
      const cursor = new Date(startDate);
      while (cursor <= now) {
        const periodKey = useDaily
          ? `${cursor.getFullYear()}-${String(cursor.getMonth() + 1).padStart(2, "0")}-${String(cursor.getDate()).padStart(2, "0")}`
          : `${cursor.getFullYear()}-${String(cursor.getMonth() + 1).padStart(2, "0")}`;
        periods.push({
          period: periodKey,
          pqc: pqcMap.get(periodKey) ?? 0,
          nonPqc: nonPqcMap.get(periodKey) ?? 0
        });
        if (useDaily) {
          cursor.setDate(cursor.getDate() + 1);
        } else {
          cursor.setMonth(cursor.getMonth() + 1);
        }
      }

      return { periods };
    } catch (error) {
      throw new DatabaseError({ error, name: "Get PQC trend" });
    }
  };

  const findByIdForShare = async (id: string, tx: Knex): Promise<TCertificates | undefined> => {
    try {
      return (await tx(TableName.Certificate).where({ id }).forShare().first()) as TCertificates | undefined;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find certificate by id for share" });
    }
  };

  const primaryNode = () => db.primaryNode();

  return {
    primaryNode,
    ...certificateOrm,
    findByIdForUpdate,
    findByIdForShare,
    create,
    countCertificatesInProject,
    countActiveCertificatesForSync,
    countCertificatesForPkiSubscriber,
    findLatestActiveCertForSubscriber,
    findAllActiveCertsForSubscriber,
    findActiveDigiCertCertsByOrderIds,
    findActiveDigiCertCertsByCaId,
    findExpiredSyncedCertificates,
    findByThumbprintInOrg,
    findActiveCertificatesByIds,
    findActiveCertificatesForSync,
    findCertificatesMatchingSyncFilters,
    countCertificatesMatchingSyncFilters,
    findReadableCertificateIds,
    findLatestCertificatesByOrderIds,
    findCertificatesEligibleForRenewal,
    getRequestEnrollmentTypeByCertId,
    getOriginatingRequestByCertId,
    findWithPrivateKeyInfo,
    findWithFullDetails,
    findLatestRenewalOf,
    getDashboardStats,
    getActivityTrend,
    getPqcTrend
  };
};