From af4203d9f1c73b9e7fc209824f143d29231c429f Mon Sep 17 00:00:00 2001 From: Denozordec Date: Thu, 19 Nov 2026 13:59:39 +0700 Subject: [PATCH] =?UTF-8?q?fix(mcp):=20=D1=83=D1=81=D0=BA=D0=BE=D1=80?= =?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81=D1=8B?= =?UTF-8?q?=20WireGuard=20-=20=D1=81=D0=BE=D0=B1=D1=81=D1=82=D0=B2=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D0=B0=D1=8F=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=80=D0=B0=D0=B7=20=D0=BD=D0=B0=20=D1=8D=D1=82?= =?UTF-8?q?=D0=B0=D0=BF,=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D1=81=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=BE=D1=8F=D0=BD=D0=B8=D1=8F=20=D1=87=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=B7=20stat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Профиль приёмки создания WireGuard (81 с): ~3000 свежих проверок прав MCP, ~20000 проверок источника прав и ~63000 чтений файлов состояния с диска (24 с) - всё перед каждым чтением роутера. - сервисы WireGuard (создание интерфейса и пира, изменение, импорт): собственная проверка (ключи, защиты, допуск) раз на этап, чтения переиспользуют доказательство моложе 2 с; перед каждой нативной записью права MCP и защиты по-прежнему проверяются заново (executeGuardedConfigurationWrite), у создания интерфейса и собственная проверка перед отправкой свежая; - assertVerifiedConfigurationReadAccess - проверка этапа только для чтений; assertVerifiedConfigurationAccess остаётся свежей (записи и публикации); - access-generation и отметки отзыва портала проверяются через stat и перечитываются только при изменении файла (замена видна сразу); ключ шифрования читается как раньше. Приёмка создания WireGuard 81 -> 14 с отдельно; шарды WireGuard 224/198 -> 69/66 с; весь набор зелёный, 149 строк результатов на месте. Co-Authored-By: Claude Opus 5.5 --- backend/src/modules/mcp/portal-revocation.ts | 5 +++-- backend/src/modules/mcp/security.ts | 8 ++++--- .../src/modules/mcp/state-file-cache.test.ts | 22 +++++++++++++++++++ backend/src/modules/mcp/state-file-cache.ts | 22 +++++++++++++++++++ .../modules/mcp/wireguard-import-actions.ts | 11 ++++++---- .../mcp/wireguard-interface-create-actions.ts | 14 +++++++----- .../mcp/wireguard-interface-update-actions.ts | 11 ++++++---- .../mcp/wireguard-peer-create-actions.ts | 11 ++++++---- .../src/services/config-mutation-policy.ts | 10 ++++++++- .../services/wireguard-interface-create.ts | 5 +++-- 10 files changed, 93 insertions(+), 26 deletions(-) create mode 100644 backend/src/modules/mcp/state-file-cache.test.ts create mode 100644 backend/src/modules/mcp/state-file-cache.ts diff --git a/backend/src/modules/mcp/portal-revocation.ts b/backend/src/modules/mcp/portal-revocation.ts index 6d42d48a..7fc88d86 100644 --- a/backend/src/modules/mcp/portal-revocation.ts +++ b/backend/src/modules/mcp/portal-revocation.ts @@ -1,6 +1,6 @@ import { createHash, createHmac, timingSafeEqual } from "node:crypto" import { randomUUID } from "node:crypto" -import { mkdir, open, readFile, unlink } from "node:fs/promises" +import { mkdir, open, unlink } from "node:fs/promises" import path from "node:path" import type { PoolClient } from "pg" import { principalBytes, sourceAliases, principalSourceSql } from "./principal-security-sql.js" @@ -12,12 +12,13 @@ import { pool } from "../../db/index.js" import type { AuthUser } from "../../lib/permissions.js" import { McpError, mcpStateDirectory } from "./security.js" import { publishStateFile } from "./state-file-publish.js" +import { readStateFile } from "./state-file-cache.js" import { audit, transaction } from "./store.js" import type { ConnectionRow, McpPrincipal } from "./store.js" const ownerFile = (ownerId: string) => path.join(mcpStateDirectory(), "owner-revocations", createHash("sha256").update(ownerId).digest("hex") + ".json") async function externalCutoff(ownerId: string): Promise { - try { return z.object({ invalidBefore: z.number().int().nonnegative() }).parse(JSON.parse(await readFile(ownerFile(ownerId), "utf8"))).invalidBefore } + try { return z.object({ invalidBefore: z.number().int().nonnegative() }).parse(JSON.parse((await readStateFile(ownerFile(ownerId))).toString("utf8"))).invalidBefore } catch (error) { if (error instanceof Error && "code" in error && error.code === "ENOENT") return 0 throw new McpError("STATE_UNAVAILABLE", "Внешнее состояние отзыва недоступно", 503) diff --git a/backend/src/modules/mcp/security.ts b/backend/src/modules/mcp/security.ts index 06af6b69..b617f2a5 100644 --- a/backend/src/modules/mcp/security.ts +++ b/backend/src/modules/mcp/security.ts @@ -1,6 +1,7 @@ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto" import { mkdir, open, readFile, rename } from "node:fs/promises" import path from "node:path" +import { readStateFile } from "./state-file-cache.js" import { env } from "../../config.js" export class McpError extends Error { @@ -27,9 +28,10 @@ async function durableValue(name: string, bytes: number): Promise { if (value.length !== bytes) throw new McpError("STATE_UNAVAILABLE", "Повреждено состояние доступа MCP", 503) return value } - // Re-read current material on EVERY check. Existing installations need no - // mkdir/open-wx/EEXIST round trip; rotation/revocation is never cached. - try { return checked(await readFile(filename)) } + // Check current material on EVERY call. Existing installations need no + // mkdir/open-wx/EEXIST round trip; rotation/revocation is never cached: the + // non-secret generation is re-validated by stat, key material is re-read. + try { return checked(name === "access-generation" ? await readStateFile(filename) : await readFile(filename)) } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error } await mkdir(directory, { recursive: true, mode: 0o700 }) try { diff --git a/backend/src/modules/mcp/state-file-cache.test.ts b/backend/src/modules/mcp/state-file-cache.test.ts new file mode 100644 index 00000000..e4276c33 --- /dev/null +++ b/backend/src/modules/mcp/state-file-cache.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict" +import { mkdtemp, rename, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { readStateFile } from "./state-file-cache.js" + +const directory = await mkdtemp(join(tmpdir(), "mcp-state-cache-")), file = join(directory, "access-generation") +try { + await writeFile(file, Buffer.alloc(32, 1)) + assert.deepEqual(await readStateFile(file), Buffer.alloc(32, 1)) + const copy = await readStateFile(file); copy.fill(9) + assert.deepEqual(await readStateFile(file), Buffer.alloc(32, 1), "callers get a copy; zeroizing it never touches the cache") + // Rotation by atomic replace is seen on the very next call. + await writeFile(file + ".tmp", Buffer.alloc(32, 2)); await rename(file + ".tmp", file) + assert.deepEqual(await readStateFile(file), Buffer.alloc(32, 2)) + // In-place overwrite is seen as well. + await writeFile(file, Buffer.alloc(32, 3)) + assert.deepEqual(await readStateFile(file), Buffer.alloc(32, 3)) + await rm(file) + await assert.rejects(readStateFile(file), (error: NodeJS.ErrnoException) => error.code === "ENOENT") +} finally { await rm(directory, { recursive: true, force: true }) } +console.log("MCP state file cache: copy per call, atomic replace/in-place overwrite seen at once, removal is ENOENT") diff --git a/backend/src/modules/mcp/state-file-cache.ts b/backend/src/modules/mcp/state-file-cache.ts new file mode 100644 index 00000000..87136cbe --- /dev/null +++ b/backend/src/modules/mcp/state-file-cache.ts @@ -0,0 +1,22 @@ +import { readFile, stat } from "node:fs/promises" + +/** Non-secret MCP state files (access generation, owner revocation marks) are checked on every + * call, but by `stat` (~11x cheaper than a read on Windows); the content is re-read only when + * the file's identity, size or timestamps changed, so a rotation or revocation is seen at once. + * Never use for key material: the cached bytes stay in process memory. */ +const cache = new Map() +const version = async (filename: string) => { + const info = await stat(filename, { bigint: true }) + return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` +} + +export async function readStateFile(filename: string): Promise { + const current = await version(filename) // ENOENT and other errors propagate like readFile + const hit = cache.get(filename) + if (hit?.version === current) return Buffer.from(hit.value) + const value = await readFile(filename) + // Cache only a read that no concurrent replacement overlapped. + if (await version(filename).catch(() => undefined) === current) cache.set(filename, { version: current, value: Buffer.from(value) }) + else cache.delete(filename) + return value +} diff --git a/backend/src/modules/mcp/wireguard-import-actions.ts b/backend/src/modules/mcp/wireguard-import-actions.ts index 71b587ff..db532c13 100644 --- a/backend/src/modules/mcp/wireguard-import-actions.ts +++ b/backend/src/modules/mcp/wireguard-import-actions.ts @@ -2,12 +2,13 @@ import { z } from "zod" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { parseWireguardImportPlan, wireguardImportPreview, wireguardImportStages, wireguardImportObjects, assertWireguardImportAllowed, WIREGUARD_IMPORT_MAX_BYTES } from "../../services/wireguard-import-plan.js" import { executeWireguardImport, wireguardImportPrefix, wireguardImportProtectionProof, type WireguardImportCheckpoint } from "../../services/wireguard-import-execution.js" import { readWireguardInterfaceCreateState } from "../../services/wireguard-interface-create.js" import { effectiveMcpConnection, audit } from "./store.js" import { routerClient } from "./resources.js" +import { coalesceAuthorization } from "./authorization-stage.js" import { accessGeneration, fingerprint, McpError, decryptSecret, privateSecretFingerprint, redact } from "./security.js" import { registerMcpService } from "./service-registry.js" import type { add } from "./actions.js" @@ -53,10 +54,12 @@ async function material(input: Record, signal?: AbortSignal) { export function registerWireguardImportActions(register: typeof add) { const source = async (input: Record, signal?: AbortSignal) => { const value = await material(input, signal), objects = wireguardImportObjects(value.plan, String(input.receiptId)), protectionProof = await wireguardImportProtectionProof(Number(input.serverId), objects) - const authorize = async () => { + // Service checks run once per stage (reads reuse a proof younger than 2 s); every native write + // still re-proves MCP rights and protections in executeGuardedConfigurationWrite. + const authorize = coalesceAuthorization(async () => { if ((await material(input, signal)).referenceProof !== value.referenceProof) throw fail("STATE_CONFLICT", "Содержимое ссылки WireGuard изменилось") if (await wireguardImportProtectionProof(Number(input.serverId), objects) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились") - } + }).coalesced await authorize() const { server } = await routerClient(Number(input.serverId)) const state = await readWireguardInterfaceCreateState(server, authorize) @@ -82,7 +85,7 @@ export function registerWireguardImportActions(register: typeof add) { const before = await source(input) if (fingerprint(before.publicState) !== input.beforeFingerprint) throw fail("STATE_CONFLICT", "WireGuard, ссылка или зависимости изменились после подтверждения") const principal = input.principal as { connectionId: string } - return executeWireguardImport(before.server, before.plan, before.state.proof, async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }, { + return executeWireguardImport(before.server, before.plan, before.state.proof, async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() }, { receiptId: String(input.receiptId), checkpoint: async checkpoint => { await assertVerifiedConfigurationAccess(); await before.authorize() diff --git a/backend/src/modules/mcp/wireguard-interface-create-actions.ts b/backend/src/modules/mcp/wireguard-interface-create-actions.ts index 02fdc92c..db0b795a 100644 --- a/backend/src/modules/mcp/wireguard-interface-create-actions.ts +++ b/backend/src/modules/mcp/wireguard-interface-create-actions.ts @@ -2,10 +2,11 @@ import { z } from "zod" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { wireguardInterfaceCreateSchema, wireguardCreateKey, assertWireguardCreateAllowed, readWireguardInterfaceCreateState, createWireguardInterface, wireguardCreateStages, wireguardCreateProtectionProof } from "../../services/wireguard-interface-create.js" import { effectiveMcpConnection } from "./store.js" import { routerClient } from "./resources.js" +import { coalesceAuthorization } from "./authorization-stage.js" import { fingerprint, McpError, decryptSecret, privateSecretFingerprint, redact } from "./security.js" import { registerMcpService } from "./service-registry.js" import type { add } from "./actions.js" @@ -50,21 +51,22 @@ export function registerWireguardInterfaceCreateActions(register: typeof add) { const source = async (input: Record, signal?: AbortSignal) => { const keys = await material(input, signal) const protectionProof = await wireguardCreateProtectionProof(Number(input.serverId)) - const authorize = async () => { + // Reads inside a stage reuse a recent proof; the write path calls `authorizeFresh`. + const stage = coalesceAuthorization(async () => { const current = await material(input, signal) if (current.referenceProof !== keys.referenceProof) throw fail("STATE_CONFLICT", "Ссылка на ключ изменилась") if (await wireguardCreateProtectionProof(Number(input.serverId)) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились") - } + }), authorize = stage.coalesced const { server } = await routerClient(Number(input.serverId)), state = await readWireguardInterfaceCreateState(server, authorize) - await authorize() - return { ...keys, state, server, authorize, publicState: { proof: state.proof, referenceProof: keys.referenceProof, protectionProof } } + await stage.fresh() + return { ...keys, state, server, authorize, authorizeFresh: stage.fresh, publicState: { proof: state.proof, referenceProof: keys.referenceProof, protectionProof } } } registerMcpService("network.wireguard.interfaces.create", { current: async input => (await source(input)).publicState, execute: async input => { const before = await source(input) if (fingerprint(before.publicState) !== input.beforeFingerprint) throw fail("STATE_CONFLICT", "Источник, ключи или зависимости WireGuard изменились") - return createWireguardInterface(before.server, before.body, before.state.proof, async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }) + return createWireguardInterface(before.server, before.body, before.state.proof, async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() }, { authorizeWrite: async () => { await assertVerifiedConfigurationAccess(); await before.authorizeFresh() } }) }, verify: async (input, result) => { const receipt = result as { verified?: boolean; afterProof?: string } | null; return receipt?.verified === true && (await source(input)).state.proof === receipt.afterProof }, reconcile: async (input, authorize) => { diff --git a/backend/src/modules/mcp/wireguard-interface-update-actions.ts b/backend/src/modules/mcp/wireguard-interface-update-actions.ts index ad169c33..3ddea965 100644 --- a/backend/src/modules/mcp/wireguard-interface-update-actions.ts +++ b/backend/src/modules/mcp/wireguard-interface-update-actions.ts @@ -2,11 +2,12 @@ import { z } from "zod" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { wireguardCreateKey, wireguardCreateProtectionProof } from "../../services/wireguard-interface-create.js" import { wireguardInterfaceUpdateSchema, readWireguardInterfaceUpdateState, updateWireguardInterface, planWireguardInterfaceUpdate } from "../../services/wireguard-interface-update.js" import { effectiveMcpConnection } from "./store.js" import { routerClient } from "./resources.js" +import { coalesceAuthorization } from "./authorization-stage.js" import { fingerprint, McpError, decryptSecret, privateSecretFingerprint, redact } from "./security.js" import { registerMcpService } from "./service-registry.js" import type { add } from "./actions.js" @@ -47,11 +48,13 @@ export function registerWireguardInterfaceUpdateActions(register: typeof add) { const source = async (input: Record, signal?: AbortSignal) => { const keys = await material(input, signal) const protectionProof = await wireguardCreateProtectionProof(Number(input.serverId)) - const authorize = async () => { + // Service checks run once per stage (reads reuse a proof younger than 2 s); every native write + // still re-proves MCP rights and protections in executeGuardedConfigurationWrite. + const authorize = coalesceAuthorization(async () => { const current = await material(input, signal) if (current.referenceProof !== keys.referenceProof) throw fail("STATE_CONFLICT", "Ссылка на ключ изменилась") if (await wireguardCreateProtectionProof(Number(input.serverId)) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились") - } + }).coalesced const { server } = await routerClient(Number(input.serverId)), state = await readWireguardInterfaceUpdateState(server, String((input.request as { interfaceId: string }).interfaceId), authorize) await authorize() return { ...keys, state, server, authorize, publicState: { proof: state.proof, referenceProof: keys.referenceProof, protectionProof } } @@ -61,7 +64,7 @@ export function registerWireguardInterfaceUpdateActions(register: typeof add) { execute: async input => { const before = await source(input) if (fingerprint(before.publicState) !== input.beforeFingerprint) throw fail("STATE_CONFLICT", "Источник, ключи или зависимости WireGuard изменились") - return updateWireguardInterface(before.server, String((input.request as { interfaceId: string }).interfaceId), before.body, before.state.proof, async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }) + return updateWireguardInterface(before.server, String((input.request as { interfaceId: string }).interfaceId), before.body, before.state.proof, async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() }) }, verify: async (input, result) => { const receipt = result as { verified?: boolean; afterProof?: string } | null; return receipt?.verified === true && (await source(input)).state.proof === receipt.afterProof }, reconcile: async (input, authorize) => { diff --git a/backend/src/modules/mcp/wireguard-peer-create-actions.ts b/backend/src/modules/mcp/wireguard-peer-create-actions.ts index b71e78eb..5ac2d9cf 100644 --- a/backend/src/modules/mcp/wireguard-peer-create-actions.ts +++ b/backend/src/modules/mcp/wireguard-peer-create-actions.ts @@ -2,13 +2,14 @@ import { z } from "zod" import { randomUUID } from "node:crypto" import { pool } from "../../db/index.js" import { hasPermission } from "../../lib/permissions.js" -import { assertVerifiedConfigurationAccess } from "../../services/config-mutation-policy.js" +import { assertVerifiedConfigurationAccess, assertVerifiedConfigurationReadAccess } from "../../services/config-mutation-policy.js" import { wireguardCreateKey, wireguardCreateProtectionProof, readWireguardInterfaceCreateState } from "../../services/wireguard-interface-create.js" import { wireguardPeerCreateSchema, assertWireguardPeerCreateAllowed, createWireguardPeer, wireguardPeerCreateStages } from "../../services/wireguard-peer-create.js" import { wireguardReadDiagnostic } from "../../services/wireguard-read-diagnostic.js" import { WIREGUARD_PEER_KEY_PURPOSE } from "./wireguard-interface-create-actions.js" import { effectiveMcpConnection } from "./store.js" import { routerClient } from "./resources.js" +import { coalesceAuthorization } from "./authorization-stage.js" import { fingerprint, McpError, decryptSecret, privateSecretFingerprint, redact } from "./security.js" import { registerMcpService } from "./service-registry.js" import type { add } from "./actions.js" @@ -55,10 +56,12 @@ async function material(input: Record, signal?: AbortSignal) { export function registerWireguardPeerCreateActions(register: typeof add) { const source = async (input: Record, signal?: AbortSignal) => { const keys = await material(input, signal), protectionProof = await wireguardCreateProtectionProof(Number(input.serverId)) - const authorize = async () => { + // Service checks run once per stage (reads reuse a proof younger than 2 s); every native write + // still re-proves MCP rights and protections in executeGuardedConfigurationWrite. + const authorize = coalesceAuthorization(async () => { if ((await material(input, signal)).referenceProof !== keys.referenceProof) throw fail("STATE_CONFLICT", "Ссылка на ключ peer изменилась") if (await wireguardCreateProtectionProof(Number(input.serverId)) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились") - } + }).coalesced const { server } = await routerClient(Number(input.serverId)), state = await readWireguardInterfaceCreateState(server, authorize) await authorize() return { ...keys, state, server, authorize, publicState: { proof: state.proof, referenceProof: keys.referenceProof, protectionProof } } @@ -74,7 +77,7 @@ export function registerWireguardPeerCreateActions(register: typeof add) { const before = await source(input) if (fingerprint(before.publicState) !== input.beforeFingerprint) throw fail("STATE_CONFLICT", "Источник, ключи или зависимости peer изменились") phase = "apply-executor" - return await createWireguardPeer(before.server, before.body, before.state.proof, async () => { await assertVerifiedConfigurationAccess(); await before.authorize() }) + return await createWireguardPeer(before.server, before.body, before.state.proof, async () => { await assertVerifiedConfigurationReadAccess(); await before.authorize() }) } catch (error) { reportPeerSourceFailure(phase, error) throw error diff --git a/backend/src/services/config-mutation-policy.ts b/backend/src/services/config-mutation-policy.ts index 45bb9e8a..8139c26a 100644 --- a/backend/src/services/config-mutation-policy.ts +++ b/backend/src/services/config-mutation-policy.ts @@ -116,12 +116,20 @@ export async function withVerifiedConfigurationChange(input: Omit { const context = verified.getStore() if (!context?.active || !context.authorize) throw new McpError("PERMISSION_DENIED", "Нет действующего контекста операции измерения", 403) await (context.authorizeWrite ?? context.authorize)() } +/** For service read sweeps only: may reuse a rights proof from the current stage + * (MCP_AUTHORIZATION_STAGE_MS). Never use before a write or a publication. */ +export async function assertVerifiedConfigurationReadAccess(): Promise { + const context = verified.getStore() + if (!context?.active || !context.authorize) throw new McpError("PERMISSION_DENIED", "Нет действующего контекста операции измерения", 403) + await context.authorize() +} /** A full database replacement affects every protected domain, including non-router objects. */ export async function assertDatabaseRestoreAllowed() { diff --git a/backend/src/services/wireguard-interface-create.ts b/backend/src/services/wireguard-interface-create.ts index eeb41d96..7534cb67 100644 --- a/backend/src/services/wireguard-interface-create.ts +++ b/backend/src/services/wireguard-interface-create.ts @@ -129,13 +129,14 @@ export function wireguardCreatePreserved(before: State, after: State, input: Wir } return true } -export async function createWireguardInterface(server: ServerRow, raw: unknown, expectedProof?: string, authorize: () => Promise = async () => {}, options: { recordRevision?: boolean } = {}) { +export async function createWireguardInterface(server: ServerRow, raw: unknown, expectedProof?: string, authorize: () => Promise = async () => {}, options: { recordRevision?: boolean; authorizeWrite?: () => Promise } = {}) { const parsed = wireguardInterfaceCreateSchema.safeParse(raw) if (!parsed.success || parsed.data.serverId !== server.id) throw fail("INVALID_INPUT", "Некорректные параметры создания WireGuard") const input = parsed.data let protectionProof: string | undefined + // `authorize` guards reads (may reuse a stage proof); the pre-dispatch fence re-proves rights. const source = async () => { - await authorize() + await (options.authorizeWrite ?? authorize)() const fresh = await getServerRowById(server.id) if (!fresh?.enabled || fingerprint(fresh) !== fingerprint(server)) throw fail("STATE_CONFLICT", "Источник WireGuard изменился") if (protectionProof !== undefined && await wireguardCreateProtectionProof(server.id) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились; требуется новый план")