Files
MikrotikManager/backend/src/services/acme-settings-update.ts
T

44 lines
4.5 KiB
TypeScript

import { putAcmeCloudflareSettingsSchema } from "@mmapp/contracts/certificates"
import { pool } from "../db/index.js"
import { McpError } from "../modules/mcp/security.js"
import { executeGuardedApplicationWrite } from "./config-mutation-policy.js"
import { planAcmeSettingsUpdate, publicAcmeSettings, type AcmeSettingsRecord } from "./acme-settings-update-model.js"
export async function readAcmeSettingsRecord(bounded = true): Promise<AcmeSettingsRecord | undefined> {
if (!bounded) return (await pool.query<AcmeSettingsRecord>(`SELECT directory_url AS "directoryUrl",default_zone_id AS "defaultZoneId",cloudflare_api_token AS "cloudflareApiToken",account_private_key AS "accountPrivateKey",to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "updatedAt",xmin::text AS revision FROM acme_settings WHERE id=1`)).rows[0]
const row = (await pool.query<AcmeSettingsRecord>(`SELECT
CASE WHEN octet_length(directory_url)<=8192 THEN directory_url ELSE NULL END AS "directoryUrl",
CASE WHEN octet_length(default_zone_id)<=16384 THEN default_zone_id ELSE NULL END AS "defaultZoneId",
CASE WHEN octet_length(cloudflare_api_token)<=4096 THEN cloudflare_api_token ELSE NULL END AS "cloudflareApiToken",
CASE WHEN octet_length(account_private_key)<=65536 THEN account_private_key ELSE NULL END AS "accountPrivateKey",
to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "updatedAt",xmin::text AS revision FROM acme_settings WHERE id=1`)).rows[0]
if (row && [row.directoryUrl,row.defaultZoneId,row.cloudflareApiToken,row.accountPrivateKey].some(value=>typeof value!=="string")) throw new McpError("STATE_UNAVAILABLE", "Настройки ACME превышают предел безопасного чтения", 503)
return row
}
/** REST and MCP use one guarded mutation, preserving the existing PUT field semantics. */
export async function performAcmeSettingsUpdate(raw: unknown, options: {
beforeWrite?: () => Promise<unknown>; afterWrite?: () => Promise<unknown>; expected?: AcmeSettingsRecord | null
} = {}) {
const input = putAcmeCloudflareSettingsSchema.strict().parse(raw)
return executeGuardedApplicationWrite({ kind: "acme-settings", id: "1" }, "all", async () => {
// Human REST retains its existing unbounded string contract. MCP supplies an
// expected source and uses SQL-side bounds before reading credential bytes.
const bounded = options.expected !== undefined
const row = await readAcmeSettingsRecord(bounded), next = planAcmeSettingsUpdate(row, input, new Date().toISOString().replace(/Z$/, "000Z"))
await options.beforeWrite?.()
// A compare-and-set also closes the interval between the last fence and SQL.
let result
if (options.expected === null) {
result = await pool.query('INSERT INTO acme_settings(id,directory_url,default_zone_id,cloudflare_api_token,account_private_key,updated_at) VALUES(1,$1,$2,$3,$4,$5) ON CONFLICT(id) DO NOTHING RETURNING id,xmin::text AS revision', [next.directoryUrl,next.defaultZoneId,next.cloudflareApiToken,next.accountPrivateKey,next.updatedAt])
} else if (options.expected) {
const expected = options.expected
result = await pool.query('UPDATE acme_settings SET directory_url=$1,default_zone_id=$2,cloudflare_api_token=$3,updated_at=$4 WHERE id=1 AND directory_url=$5 AND default_zone_id=$6 AND cloudflare_api_token=$7 AND account_private_key=$8 AND updated_at=$9 AND xmin::text=$10 RETURNING id,xmin::text AS revision', [next.directoryUrl,next.defaultZoneId,next.cloudflareApiToken,next.updatedAt,expected.directoryUrl,expected.defaultZoneId,expected.cloudflareApiToken,expected.accountPrivateKey,expected.updatedAt,expected.revision])
} else {
result = await pool.query('INSERT INTO acme_settings(id,directory_url,default_zone_id,cloudflare_api_token,account_private_key,updated_at) VALUES(1,$1,$2,$3,$4,$5) ON CONFLICT(id) DO UPDATE SET directory_url=EXCLUDED.directory_url,default_zone_id=EXCLUDED.default_zone_id,cloudflare_api_token=EXCLUDED.cloudflare_api_token,updated_at=EXCLUDED.updated_at RETURNING id,xmin::text AS revision', [next.directoryUrl,next.defaultZoneId,next.cloudflareApiToken,next.accountPrivateKey,next.updatedAt])
}
if (result.rowCount !== 1) throw new McpError("STATE_CONFLICT", "Настройки ACME изменились перед записью", 409)
await options.afterWrite?.()
return { saved: { ...next, revision: result.rows[0]?.revision as string | undefined }, publicSettings: publicAcmeSettings(await readAcmeSettingsRecord(bounded)) }
})
}