292 lines
26 KiB
TypeScript
292 lines
26 KiB
TypeScript
/** Original REST uptime speed command only. No bandwidth dispatch, enrollment,
|
|
* runtime wiring, history publication or substitute diagnostic workflow. */
|
|
import type { FastifyRequest } from "fastify"
|
|
import type { QueryConfig } from "pg"
|
|
import { readFile } from "node:fs/promises"
|
|
import { join } from "node:path"
|
|
import { performance } from "node:perf_hooks"
|
|
import { isDeepStrictEqual } from "node:util"
|
|
import { z } from "zod"
|
|
import { speedTestCommandSchema, type SpeedTestCommand } from "@mmapp/contracts"
|
|
import { pool } from "../db/index.js"
|
|
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, type VerifiedRestRequestAuthority } from "../plugins/auth.js"
|
|
import { fingerprint, McpError, mcpStateDirectory, privateFingerprinterExisting } from "../modules/mcp/security.js"
|
|
import type { RoutingEndpoint } from "../modules/mcp/routing-observation-source.js"
|
|
import type { BandwidthScope } from "./bandwidth-admission.js"
|
|
import type { BandwidthPeerExecutionIntent } from "./bandwidth-peer-execution-host.js"
|
|
import { readBandwidthPeerCompletion } from "./bandwidth-peer-execution-host.js"
|
|
import type { BandwidthPeerSourceSnapshot } from "./bandwidth-peer-observation.js"
|
|
import { parseBandwidthPeerRef, type BandwidthPeerRef } from "./bandwidth-peer-reference.js"
|
|
import { assertSpeedProbeContext } from "./speed-run-persistence.js"
|
|
import { MikrotikClient } from "./mikrotik.js"
|
|
import { createBandwidthSpeedRunIdentity, BANDWIDTH_SPEED_RUN_HISTORY_SQL, assertBandwidthSpeedRunHistoryAbsent, BandwidthSpeedRunIdUnavailable } from "./bandwidth-speed-run-identity.js"
|
|
|
|
declare const restSpeedBrand: unique symbol
|
|
export type RestSpeedBandwidthOriginal = Readonly<{ [restSpeedBrand]: true }>
|
|
export interface RestSpeedBandwidthContext {
|
|
readonly command: Readonly<SpeedTestCommand>; readonly srcAddress: string; readonly dstAddress: string
|
|
readonly address: string; readonly srcInterfaceAddress: string | null; readonly dstInterfaceAddress: string | null
|
|
}
|
|
const providers = new WeakSet<object>()
|
|
const deny = (): never => { throw new McpError("PERMISSION_DENIED", "Исходный REST speed-контекст изменён или недоступен", 403) }
|
|
export function assertRestSpeedBandwidthOriginalProvider(value: unknown): asserts value is ReturnType<typeof createRestSpeedBandwidthOriginalProvider> {
|
|
if (!value || typeof value !== "object" || !providers.has(value)) deny()
|
|
}
|
|
function freeze<T>(value: T): T {
|
|
if (value && typeof value === "object") { Object.values(value).forEach(freeze); Object.freeze(value) }
|
|
return value
|
|
}
|
|
const commandFields = new Set(["runId", "probeId", "srcServerId", "dstServerId", "srcInterface", "dstInterface", "protocol", "direction", "durationSec"])
|
|
function commandSnapshot(raw: unknown): Readonly<SpeedTestCommand> {
|
|
if (!raw || Object.getPrototypeOf(raw) !== Object.prototype) return deny()
|
|
const fields = Object.getOwnPropertyDescriptors(raw)
|
|
if (Reflect.ownKeys(raw).length !== Object.keys(fields).length || Object.keys(fields).some(key => !commandFields.has(key))
|
|
|| Object.values(fields).some(field => !("value" in field) || !field.enumerable || field.value !== undefined && !["string", "number"].includes(typeof field.value))) deny()
|
|
const parsed = speedTestCommandSchema.parse(Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value])))
|
|
// Keep optional absent IDs out of admission JSON while preserving the exact
|
|
// shared contract's coercion/defaults/trim behavior.
|
|
return freeze(Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== undefined)) as SpeedTestCommand)
|
|
}
|
|
function requestCommand(request: FastifyRequest): Readonly<SpeedTestCommand> {
|
|
const field = Object.getOwnPropertyDescriptor(request, "body")
|
|
if (!field || !("value" in field)) return deny()
|
|
return commandSnapshot(field.value)
|
|
}
|
|
function scopeSnapshot(raw: Readonly<BandwidthScope>): Readonly<BandwidthScope> {
|
|
if (!raw || Object.getPrototypeOf(raw) !== Object.prototype || Reflect.ownKeys(raw).length !== Object.keys(raw).length) deny()
|
|
const fields = Object.getOwnPropertyDescriptors(raw)
|
|
if (Object.keys(fields).some(key => !["deadlineAt", "signal"].includes(key)) || Object.values(fields).some(field => !("value" in field) || !field.enumerable)) deny()
|
|
const deadlineAt = fields.deadlineAt?.value, signal = fields.signal?.value
|
|
if (typeof deadlineAt !== "number" || !Number.isSafeInteger(deadlineAt) || signal !== undefined && !(signal instanceof AbortSignal)) return deny()
|
|
return Object.freeze({ deadlineAt, signal })
|
|
}
|
|
const metadataSchema = z.array(z.object({ id: z.number().int().positive().safe(), enabled: z.literal(true), routingEndpointEpoch: z.string().uuid() }).strict()).length(2)
|
|
const endpointSchema = z.object({ id: z.number().int().positive().safe(), enabled: z.literal(true), routingEndpointEpoch: z.string().uuid(), host: z.string().min(1).max(1000),
|
|
port: z.number().int().min(1).max(65535), useSsl: z.boolean(), verifySsl: z.boolean(), username: z.string().max(1000), password: z.string().max(65536) }).strict()
|
|
const probeSchema = z.object({ id: z.string(), srcServerId: z.number().int().positive().safe(), dstServerId: z.number().int().positive().safe(),
|
|
srcInterface: z.string(), dstInterface: z.string(), protocol: z.enum(["tcp", "udp"]), direction: z.enum(["both", "transmit", "receive"]), durationSec: z.number().int().min(3).max(2147483647), enabled: z.boolean() }).strict()
|
|
type Metadata = z.infer<typeof metadataSchema>
|
|
type Probe = z.infer<typeof probeSchema> | undefined
|
|
const purpose = "rest-speed-bandwidth-original-v1", keyMessage = "rest-speed-bandwidth-original-purpose-key-epoch-v1"
|
|
async function existingGeneration(directory: string) {
|
|
const bytes = await readFile(join(directory, "access-generation"))
|
|
if (bytes.length !== 32) return deny()
|
|
return bytes.toString("hex")
|
|
}
|
|
/** Fixed current-facts projection. Captured credentials are private parameters
|
|
* compared INSIDE PostgreSQL; ongoing validation returns only one Boolean.
|
|
* Completion uses a separate fixed query omitting ONLY the selected probe. */
|
|
function currentSnapshotSql(includeProbe: boolean): string {
|
|
return `/* rest-speed-original:${includeProbe ? "current-snapshot" : "completion-snapshot"} */ WITH expected AS MATERIALIZED (
|
|
SELECT * FROM pg_catalog.jsonb_to_recordset($1::jsonb) AS e(id bigint,enabled boolean,"routingEndpointEpoch" uuid,
|
|
host text,port integer,"useSsl" boolean,"verifySsl" boolean,username text,password text)),
|
|
matched AS MATERIALIZED (
|
|
SELECT s.id FROM public.servers s JOIN expected e ON e.id=s.id WHERE s.enabled=true
|
|
AND pg_catalog.jsonb_build_object('id',s.id,'enabled',s.enabled,'routingEndpointEpoch',s.routing_endpoint_epoch,
|
|
'host',s.host,'port',s.port,'useSsl',s.use_ssl,'verifySsl',s.verify_ssl,'username',s.username,'password',s.password)=pg_catalog.to_jsonb(e)),
|
|
endpoints_current AS MATERIALIZED (SELECT count(*)=2 AND count(DISTINCT id)=2
|
|
AND (SELECT count(*) FROM matched)=2 AS current FROM expected)${includeProbe ? `,
|
|
chosen_probe AS MATERIALIZED (SELECT pg_catalog.jsonb_build_object('id',p.id,'srcServerId',p.src_server_id,'dstServerId',p.dst_server_id,
|
|
'srcInterface',p.src_interface,'dstInterface',p.dst_interface,'protocol',p.protocol,'direction',p.direction,'durationSec',p.duration_sec,'enabled',p.enabled) AS projection
|
|
FROM public.uptime_speed_probes p WHERE p.id=$3::text LIMIT 2)` : ""}
|
|
SELECT (e.current${includeProbe ? ` AND ($2::jsonb IS NULL OR ((SELECT count(*) FROM chosen_probe)=1
|
|
AND (SELECT projection FROM chosen_probe LIMIT 1)=$2::jsonb))` : ""}) IS TRUE AS current FROM endpoints_current e`
|
|
}
|
|
const CURRENT_SNAPSHOT_SQL = currentSnapshotSql(true), COMPLETION_SNAPSHOT_SQL = currentSnapshotSql(false)
|
|
/** Same static-first/filter/order selection as executeBandwidthSpeedTestInner. */
|
|
function firstUsableIp(rows: Record<string, unknown>[], iface: string): string {
|
|
const candidates = rows.filter(row => String(row.interface ?? "").trim() === iface.trim()
|
|
&& String(row.disabled ?? "false").toLowerCase() !== "true" && String(row.invalid ?? "false").toLowerCase() !== "true" && String(row.address ?? "").trim().includes("/"))
|
|
candidates.sort((a, b) => (String(a.dynamic ?? "false").toLowerCase() === "true" ? 1 : 0) - (String(b.dynamic ?? "false").toLowerCase() === "true" ? 1 : 0))
|
|
return candidates[0]?.address ? String(candidates[0].address).split("/")[0]?.trim() ?? "" : ""
|
|
}
|
|
async function window<T>(input: Readonly<BandwidthScope>, authority: Readonly<VerifiedRestRequestAuthority>, originalEnd: number, originalSignal: AbortSignal | undefined, work: (scope: Readonly<BandwidthScope>, live: () => void) => Promise<T>): Promise<T> {
|
|
const scope = Object.freeze({ deadlineAt: Math.min(input.deadlineAt, authority.expiresAt), signal: input.signal })
|
|
const end = Math.min(originalEnd, performance.now() + Math.max(0, scope.deadlineAt - Date.now()))
|
|
const signals = [...new Set([scope.signal, originalSignal, authority.signal].filter((signal): signal is AbortSignal => !!signal))]
|
|
let active = true, rejectStopped!: (error: Error) => void
|
|
const live = () => { if (!active || Date.now() >= scope.deadlineAt || performance.now() >= end || signals.some(signal => signal.aborted)) deny() }
|
|
const stopped = new Promise<never>((_resolve, reject) => { rejectStopped = reject })
|
|
const stop = () => { active = false; rejectStopped(new McpError("PERMISSION_DENIED", "REST speed-контекст завершён", 403)) }
|
|
const timer = setTimeout(stop, Math.max(1, Math.min(scope.deadlineAt - Date.now(), end - performance.now())))
|
|
for (const signal of signals) signal.addEventListener("abort", stop, { once: true })
|
|
try { live(); return await Promise.race([Promise.resolve().then(async () => { live(); const result = await work(scope, live); live(); return result }), stopped]) }
|
|
finally { active = false; clearTimeout(timer); for (const signal of signals) signal.removeEventListener("abort", stop) }
|
|
}
|
|
|
|
/** Fixed production dependencies only. Constructor does no I/O and accepts no
|
|
* actor/client/SQL/proof callbacks. Capabilities remain bound to the live HTTP
|
|
* request; they are not background job or independent wire-mapping authority. */
|
|
export function createRestSpeedBandwidthOriginalProvider() {
|
|
type Entry = { intent: BandwidthPeerExecutionIntent; context: Readonly<RestSpeedBandwidthContext>; peers: ReadonlyMap<number, Readonly<BandwidthPeerSourceSnapshot>>
|
|
authority: Readonly<VerifiedRestRequestAuthority>; end: number; signal?: AbortSignal; assertCurrent(scope: Readonly<BandwidthScope>, live: () => void): Promise<void>
|
|
assertAuthorityCurrent(scope: Readonly<BandwidthScope>, live: () => void): Promise<void> }
|
|
const entries = new WeakMap<object, Entry>()
|
|
const captures = new WeakSet<object>()
|
|
const read = async (token: unknown, rawScope: Readonly<BandwidthScope>) => {
|
|
const scope = scopeSnapshot(rawScope), entry = token && typeof token === "object" ? entries.get(token) : undefined
|
|
if (!entry) return deny()
|
|
await window(scope, entry.authority, entry.end, entry.signal, (current, live) => entry.assertCurrent(current, live))
|
|
return entry
|
|
}
|
|
const provider = Object.freeze({
|
|
async capture(request: FastifyRequest, rawCommand: unknown, rawScope: Readonly<BandwidthScope>): Promise<RestSpeedBandwidthOriginal> {
|
|
const command = commandSnapshot(rawCommand), body = requestCommand(request), scope = scopeSnapshot(rawScope), entered = Date.now(), enteredMono = performance.now()
|
|
if (!isDeepStrictEqual(command, body)) return deny()
|
|
if (captures.has(request)) return deny()
|
|
captures.add(request)
|
|
const run = createBandwidthSpeedRunIdentity(command.runId)
|
|
const sealedCommand = freeze({ ...command, runId: run.runId })
|
|
const original = await captureVerifiedRestRequest(request, scope)
|
|
const authority = await inspectVerifiedRestRequest(original, scope, "mm:uptime:write")
|
|
if (authority.method !== "POST" || authority.path !== "/api/uptime/speed-test") return deny()
|
|
const end = Math.min(authority.monotonicDeadline, enteredMono + Math.max(0, authority.expiresAt - entered))
|
|
return window(scope, authority, end, scope.signal, async (current, live) => {
|
|
const ids = [command.srcServerId, command.dstServerId].sort((a, b) => a - b)
|
|
const sourceDirectory = mcpStateDirectory(), generation = await existingGeneration(sourceDirectory); live()
|
|
const sign = await privateFingerprinterExisting(purpose); live(); const keyProof = sign(keyMessage)
|
|
const basic = async (next: Readonly<BandwidthScope>, checkLive: () => void) => {
|
|
checkLive(); if (mcpStateDirectory() !== sourceDirectory || !isDeepStrictEqual(requestCommand(request), command)) deny()
|
|
if (!isDeepStrictEqual(await inspectVerifiedRestRequest(original, next, "mm:uptime:write"), authority)) deny(); checkLive()
|
|
if (await existingGeneration(sourceDirectory) !== generation || mcpStateDirectory() !== sourceDirectory) deny(); checkLive()
|
|
if ((await privateFingerprinterExisting(purpose))(keyMessage) !== keyProof || mcpStateDirectory() !== sourceDirectory) deny(); checkLive()
|
|
if (!isDeepStrictEqual(await inspectVerifiedRestRequest(original, next, "mm:uptime:write"), authority)) deny(); checkLive()
|
|
}
|
|
const query = async (text: string, values: unknown[], next: Readonly<BandwidthScope>, checkLive: () => void) => {
|
|
checkLive(); const config: QueryConfig & { query_timeout: number } = { text, values, query_timeout: Math.max(1, Math.min(5000, next.deadlineAt - Date.now())) }
|
|
const result = await pool.query(config); checkLive(); return result
|
|
}
|
|
const metadata = async (next: Readonly<BandwidthScope>, checkLive: () => void): Promise<Metadata> => {
|
|
await basic(next, checkLive)
|
|
const result = await query('/* rest-speed-original:metadata */ SELECT id,enabled,routing_endpoint_epoch AS "routingEndpointEpoch" FROM public.servers WHERE id=ANY($1::bigint[]) ORDER BY id LIMIT 3', [ids], next, checkLive)
|
|
await basic(next, checkLive)
|
|
const rows = metadataSchema.parse(result.rows)
|
|
if (!isDeepStrictEqual(rows.map(row => row.id), ids)) deny()
|
|
return rows
|
|
}
|
|
const probe = async (next: Readonly<BandwidthScope>, checkLive: () => void): Promise<Probe> => {
|
|
if (!command.probeId) return undefined
|
|
await basic(next, checkLive)
|
|
const rows = (await query('/* rest-speed-original:probe */ SELECT id,src_server_id AS "srcServerId",dst_server_id AS "dstServerId",src_interface AS "srcInterface",dst_interface AS "dstInterface",protocol,direction,duration_sec AS "durationSec",enabled FROM public.uptime_speed_probes WHERE id=$1 LIMIT 2', [command.probeId], next, checkLive)).rows
|
|
await basic(next, checkLive); if (rows.length !== 1) return deny()
|
|
const value = probeSchema.parse(rows[0]); assertSpeedProbeContext(value, { ...command, id: command.probeId }); return value
|
|
}
|
|
const endpoints = async (next: Readonly<BandwidthScope>, expected: Metadata, expectedProbe: Probe, checkLive: () => void) => {
|
|
await basic(next, checkLive)
|
|
// Pair epochs AND the exact selected probe gate credential projection
|
|
// in this SAME SQL snapshot, including drift since the prior reads.
|
|
// REST manual probes may be disabled: compare captured enabled exactly.
|
|
const result = await query(`/* rest-speed-original:credentials */ WITH expected AS MATERIALIZED (
|
|
SELECT * FROM pg_catalog.jsonb_to_recordset($1::jsonb) AS e(id bigint,epoch uuid)),
|
|
matched AS MATERIALIZED (SELECT s.id FROM public.servers s JOIN expected e ON e.id=s.id AND e.epoch=s.routing_endpoint_epoch WHERE s.enabled=true),
|
|
allowed AS MATERIALIZED (SELECT count(*)=2 AND ($2::jsonb IS NULL OR EXISTS (
|
|
SELECT 1 FROM public.uptime_speed_probes p WHERE p.id=$3::text
|
|
AND pg_catalog.jsonb_build_object('id',p.id,'srcServerId',p.src_server_id,'dstServerId',p.dst_server_id,
|
|
'srcInterface',p.src_interface,'dstInterface',p.dst_interface,'protocol',p.protocol,'direction',p.direction,
|
|
'durationSec',p.duration_sec,'enabled',p.enabled)=$2::jsonb)) AS complete FROM matched),
|
|
chosen AS MATERIALIZED (SELECT s.id,jsonb_build_object('id',s.id,'host',s.host,'port',s.port,'username',s.username,'password',s.password,
|
|
'useSsl',s.use_ssl,'verifySsl',s.verify_ssl,'enabled',s.enabled,'routingEndpointEpoch',s.routing_endpoint_epoch) AS endpoint
|
|
FROM public.servers s JOIN matched m ON m.id=s.id CROSS JOIN allowed a WHERE a.complete),
|
|
budget AS (SELECT coalesce(sum(octet_length(endpoint::text)),0) AS bytes FROM chosen)
|
|
SELECT id,CASE WHEN budget.bytes<=1048576 THEN endpoint END AS endpoint,budget.bytes>1048576 AS overflow FROM chosen CROSS JOIN budget ORDER BY id LIMIT 3`,
|
|
[JSON.stringify(expected.map(row => ({ id: row.id, epoch: row.routingEndpointEpoch }))), expectedProbe ? JSON.stringify(expectedProbe) : null, expectedProbe?.id ?? null], next, checkLive)
|
|
await basic(next, checkLive)
|
|
if (result.rows.some(row => row.overflow)) deny()
|
|
const rows = z.array(endpointSchema).length(2).parse(result.rows.map(row => row.endpoint))
|
|
if (rows.length !== 2 || !isDeepStrictEqual(rows.map(row => ({ id: row.id, enabled: row.enabled, routingEndpointEpoch: row.routingEndpointEpoch })), expected)) deny()
|
|
return freeze(rows)
|
|
}
|
|
const originalMetadata = freeze(await metadata(current, live)), originalProbe = freeze(await probe(current, live))
|
|
await basic(current, live)
|
|
let history: unknown
|
|
try { history = await query(BANDWIDTH_SPEED_RUN_HISTORY_SQL, [run.runId], current, live) }
|
|
catch { throw new BandwidthSpeedRunIdUnavailable(run.runId) }
|
|
assertBandwidthSpeedRunHistoryAbsent(history, run.runId)
|
|
await basic(current, live)
|
|
const originalEndpoints = await endpoints(current, originalMetadata, originalProbe, live)
|
|
const expectedEndpoints = JSON.stringify(originalEndpoints), expectedProbe = originalProbe ? JSON.stringify(originalProbe) : null
|
|
const filesCurrent = async (checkLive: () => void) => {
|
|
checkLive(); if (mcpStateDirectory() !== sourceDirectory || !isDeepStrictEqual(requestCommand(request), command)) deny()
|
|
if (await existingGeneration(sourceDirectory) !== generation || mcpStateDirectory() !== sourceDirectory) deny(); checkLive()
|
|
if ((await privateFingerprinterExisting(purpose))(keyMessage) !== keyProof || mcpStateDirectory() !== sourceDirectory) deny(); checkLive()
|
|
if (!isDeepStrictEqual(requestCommand(request), command)) deny()
|
|
}
|
|
const assertSnapshot = async (next: Readonly<BandwidthScope>, checkLive: () => void, includeProbe: boolean) => {
|
|
checkLive()
|
|
if (!isDeepStrictEqual(await inspectVerifiedRestRequest(original, next, "mm:uptime:write"), authority)) deny(); checkLive()
|
|
await filesCurrent(checkLive)
|
|
const result = await query(includeProbe ? CURRENT_SNAPSHOT_SQL : COMPLETION_SNAPSHOT_SQL,
|
|
includeProbe ? [expectedEndpoints, expectedProbe, originalProbe?.id ?? null] : [expectedEndpoints], next, checkLive)
|
|
if (!result || typeof result !== "object" || result.command !== "SELECT" || result.rowCount !== 1 || !Array.isArray(result.rows) || result.rows.length !== 1) deny()
|
|
const row = result.rows[0]
|
|
if (!row || typeof row !== "object" || Array.isArray(row) || Reflect.ownKeys(row).length !== 1) deny()
|
|
const field = Object.getOwnPropertyDescriptor(row, "current")
|
|
if (!field || !("value" in field) || !field.enumerable || field.value !== true) deny()
|
|
await filesCurrent(checkLive)
|
|
// Current actor/portal inspection is LAST, after the final file awaits.
|
|
if (!isDeepStrictEqual(await inspectVerifiedRestRequest(original, next, "mm:uptime:write"), authority)) deny(); checkLive()
|
|
}
|
|
const assertCurrent = (next: Readonly<BandwidthScope>, checkLive: () => void) => assertSnapshot(next, checkLive, true)
|
|
const assertAuthorityCurrent = (next: Readonly<BandwidthScope>, checkLive: () => void) => assertSnapshot(next, checkLive, false)
|
|
const source = originalEndpoints.find(endpoint => endpoint.id === command.srcServerId)!, destination = originalEndpoints.find(endpoint => endpoint.id === command.dstServerId)!
|
|
const addresses = async (endpoint: RoutingEndpoint): Promise<Record<string, unknown>[]> => {
|
|
let guardFailed = false
|
|
const guard = async () => { try { await assertCurrent(current, live) } catch (error) { guardFailed = true; throw error } }
|
|
await guard()
|
|
let result: unknown
|
|
const signal = current.signal ? AbortSignal.any([current.signal, authority.signal]) : authority.signal
|
|
try { result = await new MikrotikClient(endpoint, endpoint.id).get("/ip/address", Math.max(1, Math.min(10000, current.deadlineAt - Date.now())), signal, undefined, guard) }
|
|
catch { if (guardFailed) return deny(); await guard(); return [] }
|
|
await guard(); return z.array(z.record(z.string(), z.unknown())).max(10000).parse(result)
|
|
}
|
|
// Preserve existing order and fallbacks: destination first, then source.
|
|
const destinationRows = command.dstInterface ? await addresses(destination) : []
|
|
const sourceRows = command.srcInterface ? await addresses(source) : []
|
|
const dstAddress = command.dstInterface ? firstUsableIp(destinationRows, command.dstInterface) : destination.host
|
|
if (command.dstInterface && !dstAddress) throw new Error(`На интерфейсе назначения '${command.dstInterface}' нет активного IP (проверьте /ip/address — не disabled).`)
|
|
const srcAddress = command.srcInterface ? firstUsableIp(sourceRows, command.srcInterface) : source.host
|
|
const context = freeze({ command: sealedCommand, srcAddress, dstAddress, address: dstAddress || destination.host,
|
|
srcInterfaceAddress: command.srcInterface ? srcAddress || null : null, dstInterfaceAddress: command.dstInterface ? dstAddress || null : null })
|
|
const nativeBody = { address: context.address, user: destination.username, password: destination.password, protocol: command.protocol, direction: command.direction, duration: command.durationSec + "s" }
|
|
const intent = freeze({ attemptId: run.attemptId, operationId: run.operationId, callerKind: "rest-speed" as const, sourceServerId: source.id,
|
|
actualRemotePeer: { kind: "server" as const, serverId: destination.id }, credentialServerId: destination.id,
|
|
request: { command: sealedCommand } as BandwidthPeerExecutionIntent["request"], nativeBody, durationSec: command.durationSec,
|
|
// MikrotikClient.bandwidthTest's existing fixed timeout is 30_000ms.
|
|
socketTimeoutMs: 30000, authorityProof: sign("authority:" + fingerprint({ authority, command, run, generation })), authorityGeneration: generation, expiresAt: authority.expiresAt })
|
|
await assertCurrent(current, live)
|
|
const peers = new Map(originalEndpoints.map(endpoint => [endpoint.id, freeze({ peerRef: { kind: "server" as const, serverId: endpoint.id }, enabled: endpoint.enabled,
|
|
sourceProof: sign("endpoint:" + fingerprint({ generation, endpoint })), authorityGeneration: generation,
|
|
endpoint: { host: endpoint.host, port: endpoint.port, useSsl: endpoint.useSsl, verifySsl: endpoint.verifySsl, username: endpoint.username, password: endpoint.password, routingEndpointEpoch: endpoint.routingEndpointEpoch } })]))
|
|
live(); const token = Object.freeze(Object.create(null)) as RestSpeedBandwidthOriginal
|
|
entries.set(token, { intent, context, peers, authority, end, signal: scope.signal, assertCurrent, assertAuthorityCurrent }); return token
|
|
})
|
|
},
|
|
async readOriginal(token: unknown, scope: Readonly<BandwidthScope>): Promise<BandwidthPeerExecutionIntent> { return (await read(token, scope)).intent },
|
|
/** Internal transport lifetime only. The genuine context is checked before
|
|
* exposing its fixed horizon and cancellation; this data cannot mint a cap. */
|
|
async readLifetime(token: unknown, scope: Readonly<BandwidthScope>) {
|
|
const entry = await read(token, scope)
|
|
return Object.freeze({ expiresAt: entry.intent.expiresAt, monotonicDeadline: entry.end, signal: entry.authority.signal })
|
|
},
|
|
/** Internal full speed workflow metadata only; no credentials/public DTO. */
|
|
async readSpeedContext(token: unknown, scope: Readonly<BandwidthScope>): Promise<Readonly<RestSpeedBandwidthContext>> { return (await read(token, scope)).context },
|
|
async readPeer(token: unknown, rawPeer: BandwidthPeerRef, scope: Readonly<BandwidthScope>): Promise<Readonly<BandwidthPeerSourceSnapshot>> {
|
|
const peer = parseBandwidthPeerRef(rawPeer)
|
|
const entry = token && typeof token === "object" ? entries.get(token) : undefined
|
|
if (!entry || peer.kind !== "server" || !entry.peers.has(peer.serverId)) return deny()
|
|
await read(token, scope); return entry.peers.get(peer.serverId)!
|
|
},
|
|
/** Probe edits after a genuinely completed run affect history association,
|
|
* not the already sealed command. Actor/key/endpoint checks remain current. */
|
|
async readPeerAfterCompletion(token: unknown, result: unknown, rawPeer: BandwidthPeerRef, rawScope: Readonly<BandwidthScope>): Promise<Readonly<BandwidthPeerSourceSnapshot>> {
|
|
const scope = scopeSnapshot(rawScope), peer = parseBandwidthPeerRef(rawPeer)
|
|
const entry = token && typeof token === "object" ? entries.get(token) : undefined
|
|
if (!entry || peer.kind !== "server" || !entry.peers.has(peer.serverId)) return deny()
|
|
if (!isDeepStrictEqual(readBandwidthPeerCompletion(result, token), entry.intent)) return deny()
|
|
await window(scope, entry.authority, entry.end, entry.signal, (current, live) => entry.assertAuthorityCurrent(current, live))
|
|
return entry.peers.get(peer.serverId)!
|
|
},
|
|
})
|
|
providers.add(provider); return provider
|
|
}
|