65 lines
5.2 KiB
TypeScript
65 lines
5.2 KiB
TypeScript
import { z } from "zod"
|
|
import { ipsecCertBundleSchema, ipsecExistingCertificateExportBodySchema, ipsecCertExportByNameRequestSchema, ipsecExistingCertificateExportRequestKeySchema, type IpsecCertBundle } from "@mmapp/contracts/ipsec"
|
|
import type { AuthUser } from "../lib/permissions.js"
|
|
import { McpError } from "../modules/mcp/security.js"
|
|
import { parseDbServerId } from "../utils/server-id.js"
|
|
import { IpsecExistingCertificateExportExecutionError } from "./ipsec-existing-certificate-export.js"
|
|
import type { createIpsecExistingCertificateExportRestAdapter } from "./ipsec-existing-certificate-export-rest.js"
|
|
|
|
const bodySchema = ipsecExistingCertificateExportBodySchema
|
|
const certificateBodySchema = ipsecCertExportByNameRequestSchema
|
|
const uuid = ipsecExistingCertificateExportRequestKeySchema, clientIdSchema = z.string().min(1).max(256)
|
|
const bundleSchema = ipsecCertBundleSchema.extend({
|
|
user: z.string().min(1), serverEndpoint: z.string().min(1), filename: z.string().min(1),
|
|
contentB64: z.string().min(4).max(1048576).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/),
|
|
mime: z.literal("application/x-pkcs12"), passphrase: z.string().min(8).max(16384),
|
|
sswanFilename: z.string().min(1), sswanContent: z.string().min(1), instructions: z.string().min(1),
|
|
}).strict()
|
|
const receiptSchema = z.object({
|
|
ok: z.literal(true), verified: z.literal(true), receiptId: uuid, certificateId: z.string().regex(/^\*[a-z0-9]+$/i).max(100), serverId: z.number().int().positive().safe(),
|
|
commandCount: z.literal(2), completedCommands: z.literal(2), confirmedWrites: z.literal(2), afterProof: z.string().regex(/^[a-f0-9]{64}$/), automaticReplay: z.literal(false), forwardingVerified: z.literal(false), publication: bundleSchema,
|
|
}).strict()
|
|
export type IpsecExistingCertificateExportRestHttpAdapter = Pick<ReturnType<typeof createIpsecExistingCertificateExportRestAdapter>, "prepare" | "execute">
|
|
export interface IpsecExistingCertificateExportRestHttpInput {
|
|
actor: AuthUser
|
|
serverId: string | number
|
|
body: unknown
|
|
/** Stable UUID Idempotency-Key from the caller; never generated or rotated. */
|
|
requestKey: string | undefined
|
|
signal?: AbortSignal
|
|
}
|
|
export interface IpsecExistingCertificateExportRestHttpClientInput extends IpsecExistingCertificateExportRestHttpInput { clientId: string }
|
|
const invalid = () => new McpError("INVALID_INPUT", "Некорректный запрос REST-экспорта или отсутствует UUID Idempotency-Key", 400)
|
|
function sanitized(error: unknown): never {
|
|
if (error instanceof IpsecExistingCertificateExportExecutionError) throw new IpsecExistingCertificateExportExecutionError(error.code === "VERIFICATION_FAILED" ? "VERIFICATION_FAILED" : "MUTATION_OUTCOME_UNKNOWN", error.confirmedWrites, error.completedCommands)
|
|
if (error instanceof McpError) throw new McpError(error.code, "REST-экспорт не подтверждён; автоматический повтор запрещён", error.statusCode)
|
|
throw new McpError("STATE_UNAVAILABLE", "REST-экспорт не подтверждён; требуется сверка перед новой операцией", 502)
|
|
}
|
|
|
|
/** HTTP mapping only. No routes, activation, actor defaults, native algorithm,
|
|
* MCP artifacts or retry. Production activation remains a separate boundary. */
|
|
export function createIpsecExistingCertificateExportRestHttpHandlers(adapter: IpsecExistingCertificateExportRestHttpAdapter) {
|
|
const execute = async (input: IpsecExistingCertificateExportRestHttpInput, kind: "client" | "certificate", clientId?: string): Promise<IpsecCertBundle> => {
|
|
try {
|
|
// Validate every URL/header/body field before touching the adapter.
|
|
const serverId = typeof input.serverId === "string" || typeof input.serverId === "number" ? parseDbServerId(input.serverId) : null
|
|
const key = uuid.safeParse(input.requestKey)
|
|
const body = (kind === "client" ? bodySchema : certificateBodySchema).safeParse(input.body)
|
|
if (serverId === null || !key.success || !body.success || (kind === "client" && !clientIdSchema.safeParse(clientId).success)) throw invalid()
|
|
const parsed = body.data
|
|
const selection = kind === "client" ? { kind: "client" as const, clientId: clientId! } : { kind: "certificate" as const, name: (parsed as z.infer<typeof certificateBodySchema>).name }
|
|
const request = { serverId, selector: selection, privateKeyExport: parsed.privateKeyExport, caPrivateKeyExport: parsed.caPrivateKeyExport, passphrase: parsed.passphrase }
|
|
const options = { signal: input.signal, timeoutMs: 180000 }
|
|
const token = await adapter.prepare(input.actor, request, key.data, options)
|
|
const raw = await adapter.execute(token, input.actor, options)
|
|
const checked = receiptSchema.safeParse(raw)
|
|
if (!checked.success || checked.data.serverId !== serverId || checked.data.publication.filename !== `mm-ipsec-existing-${checked.data.receiptId}.p12`) throw new IpsecExistingCertificateExportExecutionError("VERIFICATION_FAILED", 0, 0)
|
|
return checked.data.publication
|
|
} catch (error) { sanitized(error) }
|
|
}
|
|
return {
|
|
client: (input: IpsecExistingCertificateExportRestHttpClientInput) => execute(input, "client", input.clientId),
|
|
certificate: (input: IpsecExistingCertificateExportRestHttpInput) => execute(input, "certificate"),
|
|
}
|
|
}
|