Files
MikrotikManager/backend/src/services/server-poll-storage-journal.ts
T

129 lines
8.7 KiB
TypeScript

/** Private bridge between the authenticated poll journal and charged storage.
* No construction registers a route/service or enrolls a schema. */
import { publicationLayout } from "./server-poll-maintenance-groups.js"
import { fingerprint, privateSecretFingerprint } from "../modules/mcp/security.js"
import type { ProbeJournalSql } from "./server-probe-journal.js"
import type { ProbeStorageOptions } from "./server-probe-journal-maintenance.js"
import type { ServerPollJournalContext } from "./server-poll-journal.js"
import { createServerPollStorage, PollStorageRefused, type PollStorageBinding } from "./server-poll-storage.js"
export class PollStorageSpent extends PollStorageRefused {
readonly automaticReplay = false
constructor() { super(); this.message = "Poll admission is already spent; automatic replay forbidden"; this.name = "PollStorageSpent" }
}
export interface ServerPollJournalStorage {
read<T>(work: (sql: ProbeJournalSql) => Promise<T>): Promise<T | undefined>
transaction<T>(phase: "claim" | "write", work: (sql: ProbeJournalSql) => Promise<T>): Promise<T>
quarantine(): Promise<boolean>
}
export interface ServerPollStorageJournalOptions {
assertAuthority(context: Readonly<ServerPollJournalContext>): Promise<void>
deadlineAt: number
signal?: AbortSignal
}
interface Dependencies {
createStorage: typeof createServerPollStorage
contextProof(context: ServerPollJournalContext): Promise<string>
now(): number
}
const authorityOwners=new WeakMap<ServerPollJournalStorage,{context:string;provider:ServerPollStorageJournalOptions["assertAuthority"];local:()=>void}>()
/** A fixed production bridge already checks this exact authority before/after
* every SQL. Only immutable composition is recognized, never a cached grant.
* Serialized, wrapped or test-injected adapters cannot manufacture this proof. */
export function bindServerPollJournalAuthority(storage:ServerPollJournalStorage,context:ServerPollJournalContext,provider:ServerPollStorageJournalOptions["assertAuthority"]):(()=>void)|undefined{
const owner=authorityOwners.get(storage)
return owner&&owner.provider===provider&&owner.context===fingerprint(context)?owner.local:undefined
}
const production: Dependencies = { createStorage: createServerPollStorage,
contextProof: context => privateSecretFingerprint(fingerprint(context), "server-poll-journal-v1:context"), now: Date.now }
const fail = (): never => { throw new PollStorageRefused() }
function freeze<T>(value: T): T {
if (value && typeof value === "object") { for (const child of Object.values(value)) freeze(child); Object.freeze(value) }
return value
}
/** Callbacks are fixed journal source code, never caller-supplied SQL. Block
* writes/CTEs/SELECT INTO, lifecycle commands and multiple statements while
* retaining the journal's SELECT ... FOR UPDATE and leading comments. */
function readOnly(sql: ProbeJournalSql): ProbeJournalSql {
return Object.freeze({ query: async (text: string, values?: unknown[]) => {
const statement = text.replace(/\/\*[\s\S]*?\*\/|--[^\r\n]*/g, " ").trim()
const plain = statement.replace(/\bFOR\s+(?:NO\s+KEY\s+)?UPDATE\b/gi, "FOR_LOCK")
if (!/^SELECT\b/i.test(statement) || /;\s*\S/.test(statement) || /\b(?:INSERT|UPDATE|DELETE|MERGE|CREATE|ALTER|DROP|TRUNCATE|COPY|CALL|DO|INTO|BEGIN|COMMIT|ROLLBACK|SET|RESET|GRANT|REVOKE)\b/i.test(plain)) fail()
return sql.query(text, values)
} })
}
async function construct(raw: ServerPollJournalContext, rawOptions: ServerPollStorageJournalOptions, rawDependencies: Dependencies,productionOwner=false): Promise<ServerPollJournalStorage> {
const deps = Object.freeze({ ...rawDependencies }), context = freeze(structuredClone(raw)), authority = rawOptions.assertAuthority
const deadlineAt = Math.min(rawOptions.deadlineAt, context.identity.expiresAt, deps.now() + 180000)
const options: ProbeStorageOptions = Object.freeze({ deadlineAt, signal: rawOptions.signal })
if (typeof authority !== "function" || !Number.isSafeInteger(rawOptions.deadlineAt) || !Number.isSafeInteger(deadlineAt)
|| (context.plan.version !== 1 && context.plan.version !== 2 && context.plan.version !== 3 && context.plan.version !== 4) || context.plan.requiresHuman !== true || context.plan.scope !== "global"
|| !Array.isArray(context.plan.maintenance) || context.plan.maintenance.length > 2000) fail()
let maxStages:number
try{maxStages=publicationLayout(context.plan).journalMaxStages}catch{fail()}
let active = true
const live = () => { if (!active || options.signal?.aborted || deps.now() >= deadlineAt) fail() }
const authorize = async () => { live(); await authority(context); live() }
let stop!: () => void
const stopped = new Promise<never>((_yes, reject) => { stop = () => { active = false; reject(new PollStorageRefused()) } })
const timer = setTimeout(stop, Math.max(1, deadlineAt - deps.now()))
options.signal?.addEventListener("abort", stop, { once: true })
let storage: ReturnType<typeof createServerPollStorage>
try {
const setup = Promise.resolve().then(async () => {
await authorize()
const contextProof = await deps.contextProof(context); live()
if (!/^[a-f0-9]{64}$/.test(contextProof)) fail()
await authorize()
const binding: PollStorageBinding = { scope: { receiptId: context.plan.request.receiptId, kind: context.identity.kind,
executionId: context.identity.executionId, ownerId: context.identity.ownerId, bindingProof: context.plan.bindingProof, contextProof,
issuedAt: context.identity.issuedAt, expiresAt: context.identity.expiresAt },
connectionId: context.identity.kind === "mcp" ? context.identity.connectionId : null,
maxStages, authorize: async () => authorize() }
return deps.createStorage(binding)
})
if (options.signal?.aborted || deps.now() >= deadlineAt) stop()
storage = await Promise.race([setup, stopped]); live()
} catch { active = false; throw new PollStorageRefused() }
finally { clearTimeout(timer); options.signal?.removeEventListener("abort", stop) }
const boundary:ServerPollJournalStorage=Object.freeze({
async read<T>(work: (sql: ProbeJournalSql) => Promise<T>): Promise<T | undefined> {
live()
return storage.inspect(options, async (sql, row) => {
if (!row) return undefined
const anchors = (await sql.query(`/* poll-storage-journal:existing-anchor */ SELECT receipt_id,identity_kind,execution_id
FROM server_poll_executions WHERE receipt_id=$1 OR(identity_kind=$2 AND execution_id=$3) LIMIT 2 FOR UPDATE`,
[context.plan.request.receiptId, context.identity.kind, context.identity.executionId])).rows
if (!anchors.length) return undefined
if (anchors.length !== 1 || anchors[0].receipt_id !== context.plan.request.receiptId
|| anchors[0].identity_kind !== context.identity.kind || anchors[0].execution_id !== context.identity.executionId) return fail()
return work(readOnly(sql))
})
},
async transaction<T>(phase: "claim" | "write", work: (sql: ProbeJournalSql) => Promise<T>): Promise<T> {
live()
if (phase === "write") return storage.write(options, work)
if (phase !== "claim") return fail()
const found = await storage.inspect(options, async (sql, row) => {
if (!row) return { present: false as const }
const anchors = (await sql.query(`/* poll-storage-journal:existing-anchor */ SELECT receipt_id,identity_kind,execution_id
FROM server_poll_executions WHERE receipt_id=$1 OR(identity_kind=$2 AND execution_id=$3) LIMIT 2 FOR UPDATE`,
[context.plan.request.receiptId, context.identity.kind, context.identity.executionId])).rows
if (!anchors.length) throw new PollStorageSpent()
if (anchors.length !== 1 || anchors[0].receipt_id !== context.plan.request.receiptId
|| anchors[0].identity_kind !== context.identity.kind || anchors[0].execution_id !== context.identity.executionId) return fail()
return { present: true as const, value: await work(readOnly(sql)) }
})
return found.present ? found.value : storage.claim(options, work)
},
async quarantine() { try { await storage.quarantine(); return true } catch { return false } },
})
if(productionOwner)authorityOwners.set(boundary,{context:fingerprint(context),provider:authority,local:live})
return boundary
}
export const createServerPollStorageJournal = (context: ServerPollJournalContext, options: ServerPollStorageJournalOptions) => construct(context, options, production,true)
/** Explicit trusted unit composition only; no request can select these hooks. */
export const createServerPollStorageJournalForTests = (context: ServerPollJournalContext, options: ServerPollStorageJournalOptions, dependencies: Pick<Dependencies, "createStorage"> & Partial<Omit<Dependencies, "createStorage">>) => construct(context, options, { ...production, ...dependencies })