Files
MikrotikManager/backend/src/services/backup-content-bounds.ts
T

27 lines
1.2 KiB
TypeScript

/** Optional limits for the shared REST/MCP backup reader. No truncation is accepted. */
export interface BackupReadOptions {
maxBytes?: number
signal?: AbortSignal
authorize?: () => Promise<unknown>
sourceRead?: (source: "s3" | "local") => void
}
export class BackupContentLimitError extends Error {}
export class BackupReadGuardError extends Error {}
export async function checkBackupRead(options: BackupReadOptions, bytes = 0) {
options.signal?.throwIfAborted()
if (options.maxBytes !== undefined && (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1 || bytes > options.maxBytes)) throw new BackupContentLimitError("Backup exceeds download limit")
try { await options.authorize?.() } catch { throw new BackupReadGuardError("Backup download authorization changed") }
options.signal?.throwIfAborted()
}
export async function collectBackupBytes(source: AsyncIterable<Uint8Array>, options: BackupReadOptions): Promise<Buffer> {
const chunks: Buffer[] = []
let bytes = 0
for await (const chunk of source) {
bytes += chunk.byteLength
await checkBackupRead(options, bytes)
chunks.push(Buffer.from(chunk))
}
await checkBackupRead(options, bytes)
return Buffer.concat(chunks, bytes)
}