Files
MikrotikManager/backend/src/services/ipsec-existing-certificate-export-rest-journal.ts
T
DenozordecandClaude Opus 5.5 e7eb108c32 fix(ipsec): совместимость инициализации и клиентов IPsec с RouterOS 7.24
Проверено пробами на стенде RouterOS 7.24.5: /certificate не принимает comment, sign и export-certificate адресуются только по .id и не принимают name и days-valid, подпись меняет authority и digest-algorithm, peer с address 0.0.0.0/0 возвращается без address, id файлов имеют вид **<base62>. Сертификаты продукта опознаются по имени и цепочке подписи, версии операций повышены (init 5, user_create 3, экспорт 2). Стабы приёмки отказывают как RouterOS 7.24. Генеральная репетиция на CHR: init 13 и PSK-клиент 2 команды сошлись с проекцией продукта, туннель, ping 10/10, рост SA, сверка 66/66.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-21 12:04:15 +07:00

139 lines
8.8 KiB
TypeScript

import { createHash } from "node:crypto"
import { isDeepStrictEqual } from "node:util"
import { z } from "zod"
import type { PoolClient } from "pg"
import type { IpsecExistingCertificateExportRestAuthority } from "./ipsec-existing-certificate-export-rest.js"
export type { IpsecExistingCertificateExportRestAuthority } from "./ipsec-existing-certificate-export-rest.js"
type Client = Pick<PoolClient, "query">
export interface IpsecExistingCertificateExportRestJournalDependencies {
transaction<T>(work: (client: Client) => Promise<T>): Promise<T>
audit(client: Client, actor: string, action: string, connection: null, payload: unknown): Promise<void>
authorize(authority: IpsecExistingCertificateExportRestAuthority): Promise<unknown>
}
export interface IpsecExistingCertificateExportRestJournalCheckpoint {
completedCommands: number
afterProof: string
file?: { id: string; name: string; size: number }
}
export class IpsecExistingCertificateExportRestJournalError extends Error {
readonly code = "STATE_CONFLICT"
readonly statusCode = 409
constructor() { super("REST export journal refused; no automatic replay") }
}
function fail(): never { throw new IpsecExistingCertificateExportRestJournalError() }
const digest = z.string().regex(/^[a-f0-9]{64}$/), uuid = z.string().uuid()
const nativeId = z.string().regex(/^\*\*?[a-z0-9]+$/i).max(256) // RouterOS 7.24 file ids are `**<base62>`
const actorSchema = z.object({ id: z.string().min(1).max(200), email: z.string(), name: z.string(), apps: z.array(z.string()).max(1000),
permissions: z.array(z.string()).max(1000), isAdmin: z.boolean().optional(), expiresAt: z.number().int().positive().safe(), issuedAt: z.number().int().nonnegative().safe() }).strict()
const selectionSchema = z.object({ serverId: z.number().int().positive().safe(),
selector: z.discriminatedUnion("kind", [z.object({ kind: z.literal("client"), clientId: z.string().min(1).max(256) }).strict(),
z.object({ kind: z.literal("certificate"), name: z.string().min(1).max(256) }).strict()]),
privateKeyExport: z.literal(true), caPrivateKeyExport: z.boolean() }).strict()
const authoritySchema = z.object({ transport: z.literal("rest"), actor: actorSchema, ownerProof: digest, requestKey: uuid,
deadlineAt: z.number().int().positive().safe(), request: selectionSchema, receiptId: uuid, certificateId: nativeId,
certificateName: z.string().min(1).max(256), role: z.enum(["ca", "server", "client", "other"]),
sourceProof: digest, expectedProof: digest, referenceProof: digest, requestProof: digest }).strict()
const ownedFile = z.object({ id: nativeId, name: z.string(), size: z.number().int().positive().max(61438) }).strict()
const checkpointSchema = z.discriminatedUnion("completedCommands", [
z.object({ completedCommands: z.literal(1), afterProof: digest, file: ownedFile }).strict(),
z.object({ completedCommands: z.literal(2), afterProof: digest }).strict(),
])
const identitySchema = z.object({ receiptId: uuid, requestKey: uuid, serverId: z.number().int().positive().safe(), certificateId: nativeId,
role: z.enum(["ca", "server", "client", "other"]), ownerProof: digest, requestProof: digest, referenceProof: digest,
sourceProof: digest, expectedProof: digest }).strict()
const firstCheckpointSchema = identitySchema.extend({ completedCommands: z.literal(1), afterProof: digest,
file: z.object({ id: nativeId, size: z.number().int().positive().max(61438) }).strict() }).strict()
function canonical(value: unknown): string {
if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]"
if (value && typeof value === "object") return "{" + Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => JSON.stringify(key) + ":" + canonical(entry)).join(",") + "}"
return JSON.stringify(value) ?? "null"
}
const fingerprint = (value: unknown) => createHash("sha256").update(canonical(value)).digest("hex")
function freeze<T>(value: T): T {
if (value && typeof value === "object") { for (const child of Object.values(value)) freeze(child); Object.freeze(value) }
return value
}
function authority(raw: IpsecExistingCertificateExportRestAuthority): IpsecExistingCertificateExportRestAuthority {
const parsed = authoritySchema.safeParse(raw)
if (!parsed.success) fail()
const a = parsed.data, now = Date.now()
if (a.deadlineAt <= now || a.actor.expiresAt <= now || a.deadlineAt > a.actor.expiresAt || a.actor.issuedAt > now ||
a.ownerProof !== fingerprint(a.actor) || a.requestProof !== fingerprint(a.request)) fail()
return freeze(a)
}
function identity(a: IpsecExistingCertificateExportRestAuthority) {
return identitySchema.parse({ receiptId: a.receiptId, requestKey: a.requestKey, serverId: a.request.serverId,
certificateId: a.certificateId, role: a.role, ownerProof: a.ownerProof, requestProof: a.requestProof,
referenceProof: a.referenceProof, sourceProof: a.sourceProof, expectedProof: a.expectedProof })
}
const claimAction = "ipsec.existing.export.rest.claim", checkpointAction = "ipsec.existing.export.rest.checkpoint"
/** Inert mandatory journal: dependencies own transactions and authorization.
* Only actor/key serialization and metadata reach SQL; no private material,
* transport principal, actor PII or certificate names enter audit payloads. */
export function createIpsecExistingCertificateExportRestJournal(deps: IpsecExistingCertificateExportRestJournalDependencies) {
async function authorize(a: IpsecExistingCertificateExportRestAuthority) {
if (a.deadlineAt <= Date.now() || !a.actor.expiresAt || a.actor.expiresAt <= Date.now()) fail()
await deps.authorize(a)
if (a.deadlineAt <= Date.now() || a.actor.expiresAt <= Date.now()) fail()
}
async function locked<T>(a: IpsecExistingCertificateExportRestAuthority, work: (client: Client) => Promise<T>) {
await authorize(a)
return deps.transaction(async client => {
await client.query("SET LOCAL lock_timeout='2s'")
await client.query("SET LOCAL statement_timeout='5s'")
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`ipsec-existing-export-rest:${a.actor.id}:${a.requestKey}`])
await authorize(a)
const result = await work(client)
await authorize(a)
return result
})
}
async function rows(client: Client, a: IpsecExistingCertificateExportRestAuthority, action: string) {
const result = await client.query(`SELECT CASE WHEN octet_length(payload::text)<=8192 THEN payload ELSE NULL END AS payload
FROM mcp_audit WHERE actor_id=$1 AND connection_id IS NULL AND action=$2 AND payload->>'requestKey'=$3 ORDER BY id LIMIT 2`,
[a.actor.id, action, a.requestKey])
if (!Array.isArray(result.rows) || result.rows.length > 2) fail()
return result.rows as { payload: unknown }[]
}
return {
async claim(raw: IpsecExistingCertificateExportRestAuthority): Promise<void> {
try {
const a = authority(raw), payload = identity(a)
await locked(a, async client => {
// Any committed claim spends the actor/key, even with another receipt
// or changed payload. An uncertain COMMIT must never be replayed.
if ((await rows(client, a, claimAction)).length) fail()
await deps.audit(client, a.actor.id, claimAction, null, payload)
})
} catch { fail() }
},
async checkpoint(raw: IpsecExistingCertificateExportRestAuthority, rawValue: IpsecExistingCertificateExportRestJournalCheckpoint): Promise<void> {
try {
const a = authority(raw), parsed = checkpointSchema.safeParse(rawValue)
if (!parsed.success) fail()
const value = freeze(parsed.data), expected = identity(a)
if (value.completedCommands === 1 ? value.file.name !== `mm-ipsec-existing-${a.receiptId}.p12` : value.afterProof !== a.expectedProof) fail()
await locked(a, async client => {
const claims = await rows(client, a, claimAction)
if (claims.length !== 1 || !identitySchema.safeParse(claims[0].payload).success || !isDeepStrictEqual(claims[0].payload, expected)) fail()
const previous = await rows(client, a, checkpointAction)
if (value.completedCommands === 1) {
if (previous.length) fail()
} else {
if (previous.length !== 1) fail()
const first = firstCheckpointSchema.safeParse(previous[0].payload)
if (!first.success) fail()
const { completedCommands: _completedCommands, afterProof: _afterProof, file: _file, ...priorIdentity } = first.data
if (!isDeepStrictEqual(priorIdentity, expected)) fail()
}
await deps.audit(client, a.actor.id, checkpointAction, null, { ...expected,
completedCommands: value.completedCommands, afterProof: value.afterProof,
...(value.completedCommands === 1 ? { file: { id: value.file.id, size: value.file.size } } : {}) })
})
} catch { fail() }
},
}
}