Open History to see the last commit
1import { createHash } from 'node:crypto'
2import { advanceOffset, parseOffset } from './offset.js'
3
4const MAGIC = Buffer.from('NDSTRM01')
5const HEADER_BYTES = 60
6const FRAME_HEADER_BYTES = 74
7export const MAX_CHUNK_BYTES = 128 * 1024 * 1024
8export interface ChunkIdentity { readonly installationId: string; readonly streamId: string; readonly chunkId: string }
9export interface ChunkFrame {
10 readonly start: string
11 readonly end: string
12 readonly payload: Buffer
13 readonly messageEnds: readonly number[] | null
14}
15export interface Chunk extends ChunkIdentity { readonly frames: readonly ChunkFrame[] }
16export class ChunkIntegrityError extends Error { override readonly name = 'ChunkIntegrityError' }
17export function chunkDigest(bytes: Uint8Array): string { return createHash('sha256').update(bytes).digest('hex') }
18const uuidBytes = (uuid: string) => {
19 if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(uuid)) throw new ChunkIntegrityError('Invalid chunk identity')
20 return Buffer.from(uuid.replaceAll('-', ''), 'hex')
21}
22const uuidString = (bytes: Buffer) => {
23 const hex = bytes.toString('hex')
24 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
25}
26function validateFrames(frames: readonly ChunkFrame[]): void {
27 if (!frames.length || frames.length > 1024) throw new ChunkIntegrityError('Invalid frame count')
28 let previous: string | undefined
29 for (const frame of frames) {
30 try { parseOffset(frame.start); parseOffset(frame.end) } catch { throw new ChunkIntegrityError('Invalid frame offset') }
31 if (!frame.payload.length || frame.end !== advanceOffset(frame.start, frame.payload.length) || (previous && previous !== frame.start)) throw new ChunkIntegrityError('Noncontiguous chunk frames')
32 previous = frame.end
33 if (frame.messageEnds !== null) {
34 let prior = 0
35 if (!frame.messageEnds.length) throw new ChunkIntegrityError('Empty JSON index')
36 for (const end of frame.messageEnds) {
37 if (!Number.isSafeInteger(end) || end <= prior || end > frame.payload.length || frame.payload[end - 1] !== 44) throw new ChunkIntegrityError('Invalid JSON index')
38 prior = end
39 }
40 if (prior !== frame.payload.length) throw new ChunkIntegrityError('Truncated JSON index')
41 try { JSON.parse(`[${new TextDecoder('utf-8', { fatal: true }).decode(frame.payload.subarray(0, -1))}]`) } catch { throw new ChunkIntegrityError('Invalid JSON bytes') }
42 }
43 }
44}
45
46/** Fixed binary v1: identity, frame count, then offsets/lengths/indexes/raw bytes. */
47export function encodeChunk(chunk: Chunk): Buffer {
48 validateFrames(chunk.frames)
49 const length = HEADER_BYTES + chunk.frames.reduce((sum, frame) => sum + FRAME_HEADER_BYTES + (frame.messageEnds?.length ?? 0) * 4 + frame.payload.length, 0)
50 if (length > MAX_CHUNK_BYTES) throw new ChunkIntegrityError('Chunk exceeds format limit')
51 const bytes = Buffer.allocUnsafe(length)
52 MAGIC.copy(bytes)
53 uuidBytes(chunk.installationId).copy(bytes, 8)
54 uuidBytes(chunk.streamId).copy(bytes, 24)
55 uuidBytes(chunk.chunkId).copy(bytes, 40)
56 bytes.writeUInt32BE(chunk.frames.length, 56)
57 let position = HEADER_BYTES
58 for (const frame of chunk.frames) {
59 bytes.write(frame.start, position, 33, 'ascii'); position += 33
60 bytes.write(frame.end, position, 33, 'ascii'); position += 33
61 bytes.writeUInt32BE(frame.payload.length, position); position += 4
62 bytes.writeUInt32BE(frame.messageEnds === null ? 0xffffffff : frame.messageEnds.length, position); position += 4
63 for (const end of frame.messageEnds ?? []) { bytes.writeUInt32BE(end, position); position += 4 }
64 frame.payload.copy(bytes, position); position += frame.payload.length
65 }
66 return bytes
67}
68
69export function decodeChunk(bytes: Buffer, identity: ChunkIdentity, digest: string): Chunk {
70 if (bytes.length < HEADER_BYTES || bytes.length > MAX_CHUNK_BYTES || !bytes.subarray(0, 8).equals(MAGIC) || chunkDigest(bytes) !== digest) throw new ChunkIntegrityError('Invalid chunk envelope or checksum')
71 const actual = { installationId: uuidString(bytes.subarray(8, 24)), streamId: uuidString(bytes.subarray(24, 40)), chunkId: uuidString(bytes.subarray(40, 56)) }
72 if (actual.installationId !== identity.installationId || actual.streamId !== identity.streamId || actual.chunkId !== identity.chunkId) throw new ChunkIntegrityError('Chunk identity mismatch')
73 const count = bytes.readUInt32BE(56)
74 if (!count || count > 1024) throw new ChunkIntegrityError('Invalid frame count')
75 let position = HEADER_BYTES
76 const frames: ChunkFrame[] = []
77 for (let i = 0; i < count; i++) {
78 if (position + FRAME_HEADER_BYTES > bytes.length) throw new ChunkIntegrityError('Truncated frame header')
79 const start = bytes.toString('latin1', position, position + 33); position += 33
80 const end = bytes.toString('latin1', position, position + 33); position += 33
81 const length = bytes.readUInt32BE(position); position += 4
82 const n = bytes.readUInt32BE(position); position += 4
83 const indexBytes = n === 0xffffffff ? 0 : n * 4
84 if (position + indexBytes + length > bytes.length) throw new ChunkIntegrityError('Truncated frame data')
85 const messageEnds: number[] | null = n === 0xffffffff ? null : []
86 for (let j = 0; j < indexBytes; j += 4) messageEnds!.push(bytes.readUInt32BE(position + j))
87 position += indexBytes
88 frames.push({ start, end, payload: bytes.subarray(position, position + length), messageEnds })
89 position += length
90 }
91 if (position !== bytes.length) throw new ChunkIntegrityError('Unexpected trailing chunk bytes')
92 validateFrames(frames)
93 return { ...actual, frames }
94}