Files
MikrotikManager/backend/src/services/certificate-installation.ts
T

70 lines
5.7 KiB
TypeScript

type Row = Record<string, unknown>
function rows(value: unknown): Row[] {
if (!Array.isArray(value) || value.some(row => !row || typeof row !== "object" || Array.isArray(row))) throw new Error("Некорректный ответ проверки сертификата")
return value as Row[]
}
function fingerprint(value: unknown): string | null {
if (typeof value !== "string") return null
const normalized = value.replaceAll(":", "").toLowerCase()
return /^[a-f0-9]{64}$/.test(normalized) ? normalized : null
}
export function assertImportedCertificate(value: unknown, name: string, expectedFingerprint: string): Row {
const matches = rows(value).filter(row => row.name === name)
if (matches.length !== 1) throw new Error("Импорт не подтверждён: имя сертификата отсутствует или неоднозначно. Назначение сервисам не подтверждено.")
const row = matches[0]!
const expected = fingerprint(expectedFingerprint)
if (!expected || fingerprint(row.fingerprint) !== expected) throw new Error("Импорт не подтверждён: отпечаток сертификата отличается от выданного")
const privateKey = row["private-key"] === "true" || row["private-key"] === "yes" || row["private-key"] === undefined && typeof row.flags === "string" && row.flags.toUpperCase().includes("K")
if (!privateKey) throw new Error("Импорт не подтверждён: закрытый ключ сертификата не обнаружен")
return row
}
export function assertLogicalCertificateName(value: unknown, name: string): void {
if (rows(value).filter(row => row.name === name).length > 1) throw new Error("Имя существующего сертификата неоднозначно; сначала устраните дубликаты")
}
export async function applyVerifiedCertificateToServices(deps: {
certificates: () => Promise<unknown>
apply: () => Promise<void>
services: () => Promise<unknown>
}, name: string, expectedFingerprint: string): Promise<void> {
assertImportedCertificate(await deps.certificates(), name, expectedFingerprint)
await deps.apply()
assertImportedCertificate(await deps.certificates(), name, expectedFingerprint)
const services = rows(await deps.services()).filter(row => row.dynamic !== "true" && row.dynamic !== "yes")
for (const service of ["www-ssl", "api-ssl"]) {
const matching = services.filter(row => row.name === service)
if (matching.length !== 1 || matching[0]!.certificate !== name || !["false", "no"].includes(String(matching[0]!.disabled))) throw new Error(`Назначение сертификата сервису ${service} не подтверждено; проверьте фактические настройки устройства`)
}
}
export async function rotateCertificateGeneration(deps: {
certificates: () => Promise<unknown>
apply: (name: string) => Promise<void>
services: () => Promise<unknown>
rename: (id: string, name: string) => Promise<void>
}, logicalName: string, generationName: string, archiveName: string, expectedFingerprint: string): Promise<void> {
if (new Set([logicalName,generationName,archiveName]).size!==3) throw new Error("Имена поколений сертификата должны различаться")
const initial=await deps.certificates()
assertLogicalCertificateName(initial,logicalName)
const candidate=assertImportedCertificate(initial,generationName,expectedFingerprint)
const previous=rows(initial).find(row=>row.name===logicalName)
if(rows(initial).some(row=>row.name===archiveName))throw new Error("Имя архива сертификата уже занято")
const id=(row:Row):string=>{if(typeof row[".id"]!=="string"||!/^\*[a-z0-9]+$/i.test(row[".id"]))throw new Error("Native ID сертификата не подтверждён");return row[".id"]}
const candidateId=id(candidate),previousId=previous?id(previous):null
if(candidateId===previousId)throw new Error("Native ID поколений сертификата неоднозначен")
const verified=(name:string)=>applyVerifiedCertificateToServices({certificates:deps.certificates,apply:()=>deps.apply(name),services:deps.services},name,expectedFingerprint)
// Keep the original identity and key intact until both services use the verified generation.
await verified(generationName)
const current=await deps.certificates()
assertLogicalCertificateName(current,logicalName)
const currentPrevious=rows(current).find(row=>row.name===logicalName)
if(previousId ? !currentPrevious||id(currentPrevious)!==previousId||currentPrevious.fingerprint!==previous!.fingerprint : !!currentPrevious)throw new Error("Исходный сертификат изменился во время переключения; проверьте фактические назначения")
if(previousId)await deps.rename(previousId,archiveName)
const staged=await deps.certificates()
if(rows(staged).some(row=>row.name===logicalName))throw new Error("Освобождение исходного имени сертификата не подтверждено")
if(id(assertImportedCertificate(staged,generationName,expectedFingerprint))!==candidateId)throw new Error("Native ID нового поколения изменился")
if(previousId&&!rows(staged).some(row=>row.name===archiveName&&row[".id"]===previousId&&row.fingerprint===previous!.fingerprint))throw new Error("Сохранение прежнего поколения не подтверждено")
await deps.rename(candidateId,logicalName)
await verified(logicalName)
// The archived generation is intentionally retained; other consumers may still need its key.
}