Files
MikrotikManager/backend/src/services/server-probe-storage-source.ts
T

55 lines
3.4 KiB
TypeScript

/** Trusted source readers for an opt-in storage host's already owned backend.
* No pool, Drizzle, native calls or registration. Scope is host authority, never
* caller request JSON. Native dispatch and crypto stay in the production executor. */
import { z } from "zod"
import { ServerProbeExecutionError, type ServerProbeSourceReaders } from "./server-probe-execution.js"
import type { ProbeStorageSql } from "./server-probe-journal-maintenance.js"
import { resolveServerProbeRestBandwidthPeer, ServerProbeRestContractError } from "./server-probe-rest-contract.js"
const ids = z.array(z.number().int().positive().safe()).max(1000).refine(value => new Set(value).size === value.length)
const endpoint = z.object({ id: z.number().int().positive().safe(), enabled: z.boolean(), host: z.string(),
port: z.number().int().min(1).max(65535), useSsl: z.boolean(), verifySsl: z.boolean(), username: z.string(), password: z.string(), routingEndpointEpoch: z.string().uuid() }).strict()
const metadata = endpoint.pick({ id: true, enabled: true, host: true })
const deny = (): never => { throw new ServerProbeExecutionError("SOURCE_UNAVAILABLE", "Источник диагностики не подтверждён", 503) }
export function createSqlServerProbeSourceReaders(sql: ProbeStorageSql, allowedServerIds: readonly number[]): ServerProbeSourceReaders {
const scope = ids.parse([...allowedServerIds])
const checkRows = <T>(schema: z.ZodType<T>, rows: Record<string, unknown>[], maximum: number): T[] => {
if (rows.length > maximum) return deny()
const parsed = z.array(schema).safeParse(rows)
if (!parsed.success) return deny()
return parsed.data
}
return Object.freeze({
async getServer(id: number) {
if (!Number.isSafeInteger(id) || !scope.includes(id)) return undefined
const rows = checkRows(endpoint, (await sql.query(`/* probe-storage-source:endpoint */
SELECT id,enabled,host,port,use_ssl AS "useSsl",verify_ssl AS "verifySsl",username,password,
routing_endpoint_epoch AS "routingEndpointEpoch" FROM servers WHERE id=ANY($1::int[]) AND id=$2 LIMIT 2`, [scope, id])).rows, 1)
if (rows.some(row => row.id !== id)) return deny()
return rows[0]
},
async findDestination(remote: string, explicit: number | undefined, currentScope: readonly number[]) {
const current = ids.parse([...currentScope]), allowed = scope.filter(id => current.includes(id))
try {
const selected = await resolveServerProbeRestBandwidthPeer(remote, explicit, allowed, {
byId: async id => {
if (!allowed.includes(id)) return undefined
const rows = checkRows(metadata, (await sql.query(`/* probe-storage-source:peer-id */
SELECT id,host,enabled FROM servers WHERE id=ANY($1::int[]) AND id=$2 LIMIT 2`, [allowed, id])).rows, 1)
if (rows.some(row => row.id !== id)) return deny()
return rows[0]
},
enabledByHost: async host => checkRows(metadata, (await sql.query(`/* probe-storage-source:peer-host */
SELECT id,host,enabled FROM servers WHERE id=ANY($1::int[]) AND enabled=true
AND lower(btrim(host))=lower(btrim($2)) LIMIT 1001`, [allowed, host])).rows, 1000),
})
return { id: selected.id }
} catch (error) {
if (error instanceof ServerProbeRestContractError) throw new ServerProbeExecutionError(error.code, error.message, error.statusCode)
throw error
}
},
})
}