Files
MikrotikManager/backend/src/db/database-runtime-writer-profile.ts
T

48 lines
2.5 KiB
TypeScript

import { z } from "zod"
import { canonical, epoch, publicKey, type ApplicationWriterPolicy } from "./application-writer-profile-format.js"
import { readCurrentApplicationWriterProfile, type ApplicationWriterRegistryReadSql } from "./application-writer-profile-registry-read.js"
import { RESTORE_WRITER_PROFILE_DEFINITION_SHA256, RESTORE_WRITER_PROFILE_MANIFEST_SHA256 } from "./database-restore-quarantine-profile.js"
const digest = z.string().regex(/^[a-f0-9]{64}$/)
const approvalSchema = z.object({
format: z.literal("database-runtime-writer-approval-v1"),
publicKeyPem: z.string().min(1).max(4096),
publicKeySpkiSha256: digest,
minimumEpoch: z.string().refine(value => { try { return epoch(value) === value } catch { return false } }),
minimumHeadSha256: digest,
}).strict()
export function approvedRuntimeWriterProfile(
bytes: Buffer,
expected: Pick<ApplicationWriterPolicy, "installationId" | "source" | "roles">,
) {
const approval = approvalSchema.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)))
const subject = { ...approval, installationId: expected.installationId }
publicKey(subject)
let expiresAt = 0
let acceptedEpoch = BigInt(approval.minimumEpoch)
let acceptedHead = approval.minimumHeadSha256
return {
async check(client: ApplicationWriterRegistryReadSql) {
const current = await readCurrentApplicationWriterProfile(client, subject)
const policy = current?.policy
if (!current || !policy || policy.definitionSha256 !== RESTORE_WRITER_PROFILE_DEFINITION_SHA256 ||
policy.manifestSha256 !== RESTORE_WRITER_PROFILE_MANIFEST_SHA256 ||
canonical(policy.source) !== canonical(expected.source) || canonical(policy.roles) !== canonical(expected.roles)) {
throw new Error("Текущий подписанный профиль записи PostgreSQL не подтверждён")
}
const observedEpoch = BigInt(current.epoch)
if (observedEpoch < acceptedEpoch || (observedEpoch === acceptedEpoch && current.headSha256 !== acceptedHead)) {
throw new Error("Состояние подписанного профиля записи PostgreSQL откатилось")
}
acceptedEpoch = observedEpoch
acceptedHead = current.headSha256
expiresAt = policy.notAfter
return { epoch: current.epoch, sha256: current.headSha256, issuedAt: policy.issuedAt }
},
assertLive() {
if (Date.now() >= expiresAt) throw new Error("Срок подтверждённого профиля записи PostgreSQL истёк")
},
}
}