Open History to see the last commit
1import { advanceOffset, isSuccessor, parseOffset } from './offset.js'
2import { chunkDigest, ChunkIntegrityError, MAX_CHUNK_BYTES } from './chunk-types.js'
3import type { Chunk, ChunkFrame, ChunkIdentity } from './chunk-types.js'
4
5const MAGIC = Buffer.from('NDSBLK03')
6const HEADER_BYTES = 68
7const DIRECTORY_FIXED_BYTES = 56
8const MAX_FRAMES = 131072
9const MAX_BLOCK_FRAMES = 8192
10const MAX_OFFSET_BYTES = 255
11
12function validateOffset(value: string): void {
13 try { parseOffset(value) }
14 catch { throw new ChunkIntegrityError('Invalid block offset') }
15}
16
17export interface ChunkBlock {
18 readonly firstFrame: number
19 readonly frameCount: number
20 readonly payloadBytes: number
21 readonly byteStart: number
22 readonly byteLength: number
23 readonly sha256: string
24 readonly start: string
25 readonly end: string
26}
27
28export interface BlockObject {
29 readonly bytes: Buffer
30 readonly directory: readonly ChunkBlock[]
31 readonly packedDirectory: Buffer
32}
33
34function uuidBytes(value: string): Buffer {
35 if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value)) throw new ChunkIntegrityError('Invalid block identity')
36 return Buffer.from(value.replaceAll('-', ''), 'hex')
37}
38
39function integerBytes(value: number): number {
40 let length = 1
41 while (value >= 128) { value = Math.floor(value / 128); length++ }
42 return length
43}
44
45function writeInteger(bytes: Buffer, position: number, value: number): number {
46 while (value >= 128) {
47 bytes[position++] = value % 128 + 128
48 value = Math.floor(value / 128)
49 }
50 bytes[position++] = value
51 return position
52}
53
54function encodedFrameLength(frame: ChunkFrame): number {
55 let length = integerBytes(frame.payload.length) + integerBytes(frame.messageEnds === null ? 0 : frame.messageEnds.length) + frame.payload.length
56 let previous = 0
57 for (const end of frame.messageEnds ?? []) {
58 if (!Number.isSafeInteger(end) || end <= previous || end > frame.payload.length || frame.payload[end - 1] !== 44) throw new ChunkIntegrityError('Invalid block JSON index')
59 length += integerBytes(end - previous)
60 previous = end
61 }
62 if (frame.messageEnds !== null && previous !== frame.payload.length) throw new ChunkIntegrityError('Incomplete block JSON index')
63 return length
64}
65
66/** Writes each payload once. Offsets and lengths live in the compact directory. */
67export function encodeBlockObject(chunk: Chunk, targetBlockBytes = 65536): BlockObject {
68 if (!Number.isSafeInteger(targetBlockBytes) || targetBlockBytes < 1 || targetBlockBytes > 16 * 1024 * 1024) throw new ChunkIntegrityError('Invalid block target')
69 if (!chunk.frames.length || chunk.frames.length > MAX_FRAMES) throw new ChunkIntegrityError('Invalid block object frame count')
70 const blocks: { frames: ChunkFrame[]; encodedBytes: number; payloadBytes: number; firstFrame: number }[] = []
71 let current = { frames: [] as ChunkFrame[], encodedBytes: 0, payloadBytes: 0, firstFrame: 0 }
72 let previous = chunk.frames[0]!.start
73 for (const [index, frame] of chunk.frames.entries()) {
74 validateOffset(frame.start)
75 validateOffset(frame.end)
76 if (frame.start !== previous || !frame.payload.length || !isSuccessor(frame.start, frame.end)) throw new ChunkIntegrityError('Noncontiguous block frame')
77 previous = frame.end
78 const length = encodedFrameLength(frame)
79 if (current.frames.length && (current.frames.length >= MAX_BLOCK_FRAMES || current.encodedBytes >= targetBlockBytes || parseOffset(current.frames.at(-1)!.end).history !== parseOffset(frame.end).history)) {
80 blocks.push(current)
81 current = { frames: [], encodedBytes: 0, payloadBytes: 0, firstFrame: index }
82 }
83 current.frames.push(frame)
84 current.encodedBytes += length
85 current.payloadBytes += frame.payload.length
86 }
87 blocks.push(current)
88 const directoryBytes = blocks.reduce((sum, block) => sum + DIRECTORY_FIXED_BYTES + block.frames[0]!.start.length + block.frames.at(-1)!.end.length, 0)
89 const length = HEADER_BYTES + directoryBytes + blocks.reduce((sum, block) => sum + block.encodedBytes, 0)
90 if (length > MAX_CHUNK_BYTES) throw new ChunkIntegrityError('Block object exceeds size limit')
91 const bytes = Buffer.allocUnsafe(length)
92 MAGIC.copy(bytes)
93 uuidBytes(chunk.installationId).copy(bytes, 8)
94 uuidBytes(chunk.streamId).copy(bytes, 24)
95 uuidBytes(chunk.chunkId).copy(bytes, 40)
96 bytes.writeUInt32BE(chunk.frames.length, 56)
97 bytes.writeUInt32BE(blocks.length, 60)
98 bytes.writeUInt32BE(directoryBytes, 64)
99 let position = HEADER_BYTES + directoryBytes
100 const directory: ChunkBlock[] = []
101 for (const block of blocks) {
102 const byteStart = position
103 for (const frame of block.frames) {
104 position = writeInteger(bytes, position, frame.payload.length)
105 position = writeInteger(bytes, position, frame.messageEnds?.length ?? 0)
106 let previousEnd = 0
107 for (const end of frame.messageEnds ?? []) {
108 position = writeInteger(bytes, position, end - previousEnd)
109 previousEnd = end
110 }
111 bytes.set(frame.payload, position)
112 position += frame.payload.length
113 }
114 directory.push({ firstFrame: block.firstFrame, frameCount: block.frames.length, payloadBytes: block.payloadBytes,
115 byteStart, byteLength: position - byteStart, sha256: chunkDigest(bytes.subarray(byteStart, position)),
116 start: block.frames[0]!.start, end: block.frames.at(-1)!.end })
117 }
118 const packedDirectory = packBlockDirectory(directory)
119 packedDirectory.copy(bytes, HEADER_BYTES)
120 return { bytes, directory, packedDirectory }
121}
122
123export function packBlockDirectory(directory: readonly ChunkBlock[]): Buffer {
124 if (!directory.length || directory.length > MAX_FRAMES) throw new ChunkIntegrityError('Invalid block directory count')
125 const length = directory.reduce((sum, block) => sum + DIRECTORY_FIXED_BYTES + block.start.length + block.end.length, 0)
126 if (length > MAX_CHUNK_BYTES) throw new ChunkIntegrityError('Block directory exceeds size limit')
127 const bytes = Buffer.allocUnsafe(length)
128 let position = 0
129 for (const block of directory) {
130 validateOffset(block.start)
131 validateOffset(block.end)
132 if (![block.firstFrame, block.frameCount, block.payloadBytes, block.byteStart, block.byteLength].every((value) => Number.isSafeInteger(value) && value >= 0 && value <= 0xffffffff)) throw new ChunkIntegrityError('Invalid block directory integer')
133 if (!/^[0-9a-f]{64}$/.test(block.sha256)) throw new ChunkIntegrityError('Invalid block checksum')
134 if (block.start.length > MAX_OFFSET_BYTES || block.end.length > MAX_OFFSET_BYTES) throw new ChunkIntegrityError('Block offset exceeds encoding limit')
135 for (const value of [block.firstFrame, block.frameCount, block.payloadBytes, block.byteStart, block.byteLength]) {
136 bytes.writeUInt32BE(value, position)
137 position += 4
138 }
139 Buffer.from(block.sha256, 'hex').copy(bytes, position)
140 position += 32
141 bytes.writeUInt16BE(block.start.length, position)
142 bytes.writeUInt16BE(block.end.length, position + 2)
143 position += 4
144 position += bytes.write(block.start, position, 'ascii')
145 position += bytes.write(block.end, position, 'ascii')
146 }
147 return bytes
148}
149
150/** Validates the complete trusted manifest before any range is requested. */
151export function unpackBlockDirectory(bytes: Buffer, objectBytes: number, frameCount: number): readonly ChunkBlock[] {
152 if (!Number.isSafeInteger(objectBytes) || objectBytes > MAX_CHUNK_BYTES || objectBytes < HEADER_BYTES
153 || !Number.isSafeInteger(frameCount) || frameCount < 1 || frameCount > MAX_FRAMES || !bytes.length) throw new ChunkIntegrityError('Invalid block manifest bounds')
154 const blocks: ChunkBlock[] = []
155 let position = 0, nextFrame = 0, nextByte = HEADER_BYTES + bytes.length
156 let previousEnd: string | undefined
157 while (position < bytes.length) {
158 if (position + DIRECTORY_FIXED_BYTES > bytes.length) throw new ChunkIntegrityError('Truncated block directory')
159 const firstFrame = bytes.readUInt32BE(position), count = bytes.readUInt32BE(position + 4), payloadBytes = bytes.readUInt32BE(position + 8),
160 byteStart = bytes.readUInt32BE(position + 12), byteLength = bytes.readUInt32BE(position + 16), sha256 = bytes.toString('hex', position + 20, position + 52),
161 startLength = bytes.readUInt16BE(position + 52), endLength = bytes.readUInt16BE(position + 54)
162 position += DIRECTORY_FIXED_BYTES
163 if (!startLength || startLength > MAX_OFFSET_BYTES || !endLength || endLength > MAX_OFFSET_BYTES || position + startLength + endLength > bytes.length) throw new ChunkIntegrityError('Invalid block offset lengths')
164 const start = bytes.toString('latin1', position, position + startLength)
165 position += startLength
166 const end = bytes.toString('latin1', position, position + endLength)
167 position += endLength
168 validateOffset(start)
169 validateOffset(end)
170 if (firstFrame !== nextFrame || !count || count > MAX_BLOCK_FRAMES || firstFrame + count > frameCount || !payloadBytes || byteStart !== nextByte
171 || byteLength < count * 3 || payloadBytes > byteLength || byteStart + byteLength > objectBytes
172 || start >= end || parseOffset(end).ordinal - parseOffset(start).ordinal !== BigInt(count) || (previousEnd !== undefined && start !== previousEnd)) throw new ChunkIntegrityError('Noncontiguous block directory')
173 blocks.push({ firstFrame, frameCount: count, payloadBytes, byteStart, byteLength, sha256, start, end })
174 nextFrame += count
175 nextByte += byteLength
176 previousEnd = end
177 }
178 if (nextFrame !== frameCount || nextByte !== objectBytes) throw new ChunkIntegrityError('Incomplete block directory')
179 return blocks
180}
181
182/** Independently verifies a range before exposing any of its private views. */
183export function decodeBlock(bytes: Buffer, block: ChunkBlock): readonly ChunkFrame[] {
184 if (bytes.length !== block.byteLength || chunkDigest(bytes) !== block.sha256) throw new ChunkIntegrityError('Block size or checksum differs')
185 let position = 0
186 const integer = () => {
187 let value = 0, factor = 1
188 for (let index = 0; index < 5; index++) {
189 if (position >= bytes.length) throw new ChunkIntegrityError('Truncated block integer')
190 const digit = bytes[position++]!
191 value += (digit & 127) * factor
192 if (digit < 128) {
193 if (value > 0xffffffff || (index > 0 && digit === 0)) throw new ChunkIntegrityError('Invalid block integer')
194 return value
195 }
196 factor *= 128
197 }
198 throw new ChunkIntegrityError('Block integer exceeds limit')
199 }
200 const frames: ChunkFrame[] = []
201 let next = block.start, payloadBytes = 0
202 for (let index = 0; index < block.frameCount; index++) {
203 const length = integer(), messageCount = integer()
204 if (!length || length > bytes.length - position || messageCount > Math.floor(length / 2)) throw new ChunkIntegrityError('Invalid block frame bounds')
205 const messageEnds: number[] | null = messageCount ? [] : null
206 let previous = 0
207 for (let message = 0; message < messageCount; message++) {
208 const delta = integer()
209 if (!delta || previous + delta > length) throw new ChunkIntegrityError('Invalid block message delta')
210 previous += delta
211 messageEnds!.push(previous)
212 }
213 if (position + length > bytes.length) throw new ChunkIntegrityError('Truncated block payload')
214 const payload = bytes.subarray(position, position + length)
215 position += length
216 if (messageEnds) {
217 if (previous !== length || messageEnds.some((end) => payload[end - 1] !== 44)) throw new ChunkIntegrityError('Block JSON boundaries differ')
218 try { JSON.parse(`[${new TextDecoder('utf-8', { fatal: true }).decode(payload.subarray(0, -1))}]`) }
219 catch { throw new ChunkIntegrityError('Invalid block JSON') }
220 }
221 const end = advanceOffset(next, parseOffset(block.end).history)
222 frames.push({ start: next, end, payload, messageEnds })
223 next = end
224 payloadBytes += length
225 }
226 if (next !== block.end || payloadBytes !== block.payloadBytes || position !== bytes.length) throw new ChunkIntegrityError('Block differs from manifest')
227 return frames
228}
229
230export function decodeBlockObject(bytes: Buffer, identity: ChunkIdentity, sha256: string): Chunk {
231 if (bytes.length < HEADER_BYTES || bytes.length > MAX_CHUNK_BYTES || !bytes.subarray(0, 8).equals(MAGIC) || chunkDigest(bytes) !== sha256) throw new ChunkIntegrityError('Invalid block object envelope')
232 if (!bytes.subarray(8, 24).equals(uuidBytes(identity.installationId)) || !bytes.subarray(24, 40).equals(uuidBytes(identity.streamId))
233 || !bytes.subarray(40, 56).equals(uuidBytes(identity.chunkId))) throw new ChunkIntegrityError('Block object identity differs')
234 const directoryEnd = HEADER_BYTES + bytes.readUInt32BE(64)
235 if (directoryEnd > bytes.length) throw new ChunkIntegrityError('Truncated block object directory')
236 const blocks = unpackBlockDirectory(bytes.subarray(HEADER_BYTES, directoryEnd), bytes.length, bytes.readUInt32BE(56))
237 if (blocks.length !== bytes.readUInt32BE(60)) throw new ChunkIntegrityError('Block count differs')
238 return { ...identity, frames: blocks.flatMap((block) => decodeBlock(bytes.subarray(block.byteStart, block.byteStart + block.byteLength), block)) }
239}