@enclave-vm/stream package - streaming protocol building blocks: NDJSON parsing, reconnection helpers, and encryption primitives.
Installation
NDJSON Parsing
serializeEvent(event)
Serialize an event to NDJSON format (single line, no trailing newline).serializeEvents(events)
Serialize multiple events to NDJSON format.parseLine(line)
Parse a single NDJSON line into an event. The line is validated against the event schemas of@enclave-vm/types.
parseLines(data)
Parse multiple NDJSON lines into events.NdjsonParseOptions
Options of the incremental parsers (NdjsonStreamParser, createNdjsonParseStream, parseNdjsonStream).
NdjsonStreamParser
Incremental NDJSON parser for streaming data. Handles partial lines across chunks.onError. A line longer than maxLineLength is reported through onError once and skipped.
Example:
createNdjsonParseStream(options?)
Create a transform stream that parses NDJSON. Works with browserfetch() and Node.js streams.
maxLineLength ends the stream with an NdjsonLineTooLongError.
Example:
createNdjsonSerializeStream()
Create a transform stream that serializes events to NDJSON.parseNdjsonStream(stream, options?)
Async generator that parses NDJSON from a ReadableStream.maxLineLength ends the iteration with an NdjsonLineTooLongError and cancels the stream.
Example:
NdjsonLineTooLongError
A line of the stream is longer than the parser’smaxLineLength.
ECDH Key Exchange
generateKeyPair(curve?)
Generate an ephemeral ECDH key pair. The private key cannot be exported.
Example:
exportPublicKey(publicKey)
Export a public key to base64 format.importPublicKey(publicKeyB64, curve?)
Import a public key from base64 format.deriveSharedSecret(privateKey, peerPublicKey)
Derive shared secret from private key and peer’s public key.createClientHello(keyPair)
Create a client hello message for the encryption handshake.createServerHello(keyPair, keyId)
Create a server hello message for the encryption handshake. The message has nosignatureB64.
processClientHello(clientHello)
Process a client hello and generate server response: the server’s ephemeral key pair, a key id, and the server hello. Nothing here proves who sent the hello. ThrowsEcdhError when the hello names a protocol version, curve or algorithm that is not implemented.
processServerHello(serverHello)
Process a server hello and extract peer’s public key.signatureB64 is not verified: the public key is only as trustworthy as the connection it arrived on.
Throws EcdhError when the hello names a protocol version, curve, algorithm or key derivation that is not implemented, or has no key id.
EcdhError
Error class for ECDH operations.Key Derivation (HKDF)
deriveKey(sharedSecret, salt, info, keyLength?)
Derive a key using HKDF-SHA256.deriveSessionKeys(sharedSecret, sessionId)
Derive session keys for bidirectional communication: two keys, one per direction. The result holds raw key bytes.importAesGcmKey(keyBytes)
Import raw key bytes as a non-extractable CryptoKey for AES-GCM.deriveSessionCryptoKeys(sharedSecret, sessionId)
Derive and import session keys as CryptoKeys.HkdfError
Error class for HKDF operations.AES-GCM Encryption
encrypt(key, plaintext, nonce, additionalData?)
Encrypt data using AES-GCM. Returns the ciphertext with the authentication tag appended.decrypt(key, ciphertext, nonce, additionalData?)
Decrypt data using AES-GCM.encryptJson(key, keyId, data, nonce?, additionalData?)
Encrypt a JSON object and create an encrypted envelope payload. A random nonce is generated when none is given.decryptJson(key, payload, additionalData?)
Decrypt a payload made byencryptJson and parse it as JSON. Pass the additional authenticated data that was given to encryptJson, if any.
This does not open an envelope: the payload of an envelope is read with openEncryptedEnvelope, which also checks the envelope’s header.
createEncryptedEnvelope(key, keyId, sessionId, seq, innerEvent, nonce?)
Create an encrypted envelope from an event. The envelope’s header (protocol version, session id, sequence number, key id) is authenticated together with the event.openEncryptedEnvelope(key, envelope)
Decrypt an encrypted envelope and parse the event inside it. ThrowsAesGcmError when the ciphertext or any header field of the envelope (protocol version, session id, sequence number, key id) is not what the sender encrypted. Whether a sequence number was seen before is for the caller to check, for example with SequenceTracker.
encodeEnvelopeHeader(header)
Encode an envelope header as the additional authenticated data that the envelope functions pass to AES-GCM. ThrowsAesGcmError when a field is not of its type.
generateNonce()
Generate a random 12-byte nonce for AES-GCM.generateCounterNonce(prefix, counter)
Generate a counter-based nonce (8 bytes prefix + 4 bytes counter). ThrowsAesGcmError when the prefix is not 8 bytes or the counter is outside 0 to 2^32 - 1.
toBase64(bytes)
Encode bytes to base64.fromBase64(base64)
Decode base64 to bytes. ThrowsAesGcmError when the input is not base64.
AesGcmError
Error class for AES-GCM operations.SessionEncryptionContext
Manages encryption key state for one direction of a session.deriveSessionKeys gives two keys, one per direction: use one context per direction, never one context for both.
createEnvelopeauthenticates the envelope’s header (protocol version, session id, sequence number, key id) together with the event. Read envelopes withopenEnvelope, which throwsAesGcmErrorwhen the ciphertext or a header field differs. Whether a sequence number was seen before is for the caller to check.decryptanddecryptJsonread payloads made byencryptandencryptJson. They do not open an envelope.- The nonce is 8 random bytes chosen per context followed by a 32-bit counter.
- A context made by
fromKeyBytesrefuses to encrypt after 2^30 messages (MAX_MESSAGES_PER_KEY):needsRotation()returnstrueandencryptthrowsAesGcmError. There is no rotation: exchange keys again. toKeyInfo()returns the raw key bytes. Treat its result as the key itself.
Reconnection
ConnectionState
Connection state enumeration.DEFAULT_RECONNECTION_CONFIG
Default reconnection configuration.ReconnectionStateMachine
Manages connection state and automatic reconnection.SequenceTracker
Tracks sequence numbers and detects gaps for replay.receive() answers { gap: false } for a sequence number at or below the last one. To detect a duplicate, compare the number with getLastSeq() before calling receive().
Example:
EventBuffer
Buffer for storing events during reconnection.HeartbeatMonitor
Monitors heartbeats to detect stale connections.Re-exported Types
This package re-exports all types from@enclave-vm/types:
Related
- Stream Overview - Usage guide
- @enclave-vm/types - Type definitions
- @enclave-vm/client - Client SDK
- Streaming Protocol - Protocol concepts