2.3 KiB
2.3 KiB
chunk
Purpose
Wraps the chunk wire format above the bare header: takes raw chunk bytes (header + signature + ciphertext) and parses them into the structured Chunk and EncodedChunk shapes that the rest of the plugin consumes. This is the inverse of encrypt-stream's output and the input to verify-chunk / decrypt-chunk.
Features
parseChunk(raw): Chunk— splits raw bytes intometadata,sig, andciphertextslices usingHEADER_SIZEas the boundary.- Length validation — rejects anything shorter than
HEADER_SIZE + payloadLen. - Allocation-light — uses
Uint8Array.subarrayviews where safe andsliceonly where ownership matters. - Round-trip stable when paired with
encodeHeaderand the encrypt-stream output.
Usage: Basic Example
import { parseChunk } from "@suaveplan/drive-plugin-chunks";
const raw: Uint8Array = await chunks.getChunk(fileId, 0).then((b) => b!);
const chunk = parseChunk(raw);
console.log(chunk.metadata.chunkId, chunk.ciphertext.length);
Usage: Advanced Example
import {
decryptChunk,
parseChunk,
verifyChunkSig,
} from "@suaveplan/drive-plugin-chunks";
async function readVerifiedChunk(fileId: Uint8Array, idx: number) {
const raw = await chunks.getChunk(fileId, idx);
if (!raw) throw new Error("missing chunk");
const chunk = parseChunk(raw);
verifyChunkSig(raw, serverPubKey);
const plaintext = decryptChunk(chunk.metadata, chunk.ciphertext, fileKey);
return plaintext.slice(0, chunk.metadata.payloadLen);
}
API Reference
parseChunk(raw: Uint8Array): Chunk— returns{ metadata, sig, ciphertext }.metadataflows throughparseHeader;sigis the 64-byte Ed25519 signature slice;ciphertextis the trailingpayloadLenbytes.- Throws
ChunksError(CHUNKS.METADATA_INVALID)for under-length buffers (delegated toparseHeader). - Throws
ChunksError(CHUNKS.PAYLOAD_LEN_INVALID)when the trailing payload is shorter thanmetadata.payloadLen.
Implementation Notes
parseChunk does not verify the signature or decrypt — those are independent stages so peers can short-circuit on metadata-only inspection (manifest checks, availability gossip). The ciphertext is sliced rather than viewed when its length differs from the underlying buffer to avoid pinning the larger raw allocation in caches.