Skip to content
106 changes: 90 additions & 16 deletions packages/filecoin-encryption-envelope/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@ commits to that length in the protected header and fails the stream if the
source supplies a different number of bytes. Omit it when the length cannot
be guaranteed.

When decrypting an object that declares `plaintext_length`, receiving fewer
ciphertext bytes than declared fails with `errors.TruncatedCiphertextError`
and receiving more fails with `errors.ExcessCiphertextError` (both extend
`errors.InvalidCiphertextLengthError`). Because the header is unauthenticated
until a chunk tag verifies, these errors report a mismatch with the declared
length rather than proof of a transport failure or which side was altered. In
streaming decryption `TruncatedCiphertextError` means the input stream ended
early; in range decryption (`decryptRange` / `decryptRangeWith`) it means the
reported `source.size` itself is shorter than declared (a short stored object
rather than a transient read cutoff).

For a browser `File` and a file handle supplied by the application:

```ts
Expand Down Expand Up @@ -127,10 +138,11 @@ response before handing it over.
function httpSource(versionedUrl: string, size: number): fee.RandomAccessSource {
return {
size,
async openRange(offset, length) {
async openRange(offset, length, signal) {
const end = offset + length - 1
const response = await fetch(versionedUrl, {
headers: { Range: `bytes=${offset}-${end}` },
signal,
})
if (
response.status !== 206 ||
Expand All @@ -146,14 +158,17 @@ function httpSource(versionedUrl: string, size: number): fee.RandomAccessSource
}

const source = httpSource(versionedUrl, exactEncodedLength)
const info = await fee.parse(source)
// Optional cancellation signal, e.g. from an incoming request or AbortSignal.timeout(...)
const controller = new AbortController()
const { signal } = controller
const info = await fee.parse(source, { signal })
if (info.scheme !== 'chunked') throw new Error('Range reads require a chunked object')

const result = await fee.decryptRange(
source,
cek,
{ offset: 100_000, length: 50_000 },
{ params: info.params }
{ params: info.params, signal }
)
await result.stream.pipeTo(rangeSink)
```
Expand All @@ -171,40 +186,99 @@ validate any scope or identifier before using it for a key lookup.

```ts
// allowedScope and keyStore are supplied by your application.
const resolver: fee.KeyResolver = async (info) => {
const resolver: fee.KeyResolver = async (info, signal) => {
const scope = info.appMetadata?.scope
const salt = info.appMetadata?.salt
if (scope !== allowedScope || typeof salt !== 'string' || !/^[0-9a-f]{32}$/.test(salt)) {
throw new Error('Envelope metadata is not allowed for this key lookup')
}
// keyStore is your application or key-management library.
return keyStore.deriveCek({ scope, salt })
const cek = await keyStore.deriveCek({ scope, salt, signal })
if (signal.aborted) {
cek.fill(0)
throw signal.reason
}
return cek
}

await encryptedSource.pipeThrough(fee.decrypt(resolver)).pipeTo(plaintextSink)
```

The resolver runs at most once, before any chunk is decrypted. Its checks control
which key may be requested; they do not authenticate the metadata. For a range
read, call `parse(source)`, validate its metadata, derive the CEK, then pass
that key and `info.params` to `decryptRange()`.
which key may be requested; they do not authenticate the metadata. The `signal`
argument aborts if the stream is cancelled, aborted (including via
`options.signal`), or fails, and does not abort on successful completion.

The library borrows the returned key bytes only long enough to import them into
a non-extractable `CryptoKey` and never zeroes the caller's buffer. Your
application owns every key it returns — including one the library discards
after cancellation (when `signal.aborted` becomes `true` before import and the
library skips validation and import) — and should zero it once the stream
settles.

For a range read, call `parse(source)`, validate its metadata, derive the CEK,
then pass that key and `info.params` to `decryptRange()`.

## Security and limits

- CEKs and A256KW KEKs must be 32-byte `Uint8Array` values and cannot be all
zero. The library validates their shape but cannot tell whether they are
secret, unpredictable, or fresh.
- Streaming options, including keys and metadata, are borrowed until the stream
closes or errors. Do not modify or clear them while it is running. A plaintext
block may be reused once its `write()` resolves. For a range read, the CEK is
borrowed until the `decryptRange()` promise settles, and the source until the
result stream closes or errors.
- Streaming options, including keys and metadata, may be read lazily (as late as
the stream's first read), so they stay borrowed until the stream closes or
errors. When imported, raw key bytes are imported into a `CryptoKey`
(non-extractable unless recipient wrapping requires extractability) and the
library never zeroes caller-owned buffers; do not modify or clear them while
the stream is running, and zero them once the stream settles if desired. A
plaintext block may be reused once its `write()` resolves. For a range read,
the CEK is borrowed until the `decryptRange()` promise settles, and the source
until the result stream closes or errors.
- When passing `options.signal` to `decrypt()`, `decryptWith()`,
`decryptRange()`, or `decryptRangeWith()`, the listener on `signal` retains
the stream (and, for range reads, its `source`) until the stream settles or
`signal` aborts so pending reads and `writer.closed` remain abortable. When
reusing a long-lived `AbortSignal`, consume or explicitly cancel unused
streams (or use an operation-scoped signal).
- Application metadata is visible without a key. Its values are authenticated
only after a content tag verifies. Content tags do not authenticate the
recipient list or establish sender identity.
- A failed stream may already have emitted bytes. Discard them all. Successful
decryption of an entire object requires reading through the final chunk.

The chunked scheme permits an encoded object of at most 64 GiB. Scheme 1
permits at most 64 MiB of plaintext. For the wire profile, range rules, and
other limits, see the [implementation guide](https://github.com/FilOzone/synapse-sdk/blob/master/packages/filecoin-encryption-envelope/docs/implementation-guide.md).
The chunked scheme permits an encoded object of at most 64 GiB
(`fee.constants.MAX_ENCODED_OBJECT_SIZE`), covering both the COSE envelope and
the detached ciphertext. Scheme 1 permits at most 64 MiB of plaintext
(`fee.constants.MAX_AES_GCM_PLAINTEXT_SIZE`).

To preflight-check whether a plaintext length fits before reading or encrypting,
call `ciphertextLengthForPlaintext(plaintextLength, chunkSize)`. It returns the
detached ciphertext length in bytes — including one 16-byte
(`fee.constants.TAG_SIZE`) authentication tag per chunk, and one tag even for
empty input (`0`) — and throws `InvalidPlaintextLengthError` if the detached
ciphertext alone exceeds `MAX_ENCODED_OBJECT_SIZE` or `ChunkCountExceededError`
if the chunk count exceeds the 32-bit chunk-index limit. For a full-object
check, add the actual encoded envelope length, or
`fee.constants.MAX_ENVELOPE_SIZE` (1 MiB) as a conservative upper bound when
the envelope length is not known yet:

```ts
function fitsChunkedLimit(
plaintextLength: number,
chunkSize = fee.constants.DEFAULT_CHUNK_SIZE
): boolean {
try {
const ciphertextLength = fee.ciphertextLengthForPlaintext(plaintextLength, chunkSize)
return ciphertextLength + fee.constants.MAX_ENVELOPE_SIZE <= fee.constants.MAX_ENCODED_OBJECT_SIZE
} catch (error) {
if (
error instanceof fee.errors.InvalidPlaintextLengthError ||
error instanceof fee.errors.ChunkCountExceededError
) {
return false
}
throw error
}
}
```

For the wire profile, range rules, and other limits, see the [implementation guide](https://github.com/FilOzone/synapse-sdk/blob/master/packages/filecoin-encryption-envelope/docs/implementation-guide.md).
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,13 @@ transfer; omit it when unsure and the object is valid, just without the commitme
When the field is present, recompute `N` and `C` from `P` and compare `C` against the observed
detached ciphertext length for the same object version. Reject a negative, non-integer or unsafe
`P`, a derived count outside the format range of 1 … 2³² − 1, an unsafe derived length
or offset, and any mismatch. The mapping is unambiguous:
or offset, and any mismatch. A shorter ciphertext than `C` raises `TruncatedCiphertextError` and a
longer one raises `ExcessCiphertextError` (both subclasses of `InvalidCiphertextLengthError`); as
`P` is unauthenticated until a chunk tag verifies, these report a mismatch with the declared length
rather than proof of a transport failure. In streaming decryption `TruncatedCiphertextError` means
the input stream ended early; in range planning (`planRange` / `decryptRange`) it means the reported
`source.size` itself is shorter than declared (a short stored object rather than a transient read
cutoff). The mapping is unambiguous:
`P + 16 × max(1, ceil(P / S))` is strictly increasing in `P`, so one ciphertext length admits
exactly one valid `P`.

Expand Down Expand Up @@ -409,7 +415,8 @@ namespace recipients {
}

type Unwrapper = (
recipients: readonly RecipientInfo[]
recipients: readonly RecipientInfo[],
signal?: AbortSignal
) => Promise<Uint8Array | undefined>

interface A256KWKey {
Expand Down Expand Up @@ -443,16 +450,32 @@ interface ChunkedEncryptOptions {

// ── chunked decryption, exported at the root as fee.decrypt / fee.decryptWith
// Use as encrypted.pipeThrough(fee.decrypt(cek)).
function decrypt(key: Uint8Array | KeyResolver): ReadableWritablePair<Uint8Array, Uint8Array>
function decryptWith(unwrapper: recipients.Unwrapper): ReadableWritablePair<Uint8Array, Uint8Array>
interface DecryptOptions {
signal?: AbortSignal
}

function decrypt(
key: Uint8Array | KeyResolver,
options?: DecryptOptions
): ReadableWritablePair<Uint8Array, Uint8Array>
function decryptWith(
unwrapper: recipients.Unwrapper,
options?: DecryptOptions
): ReadableWritablePair<Uint8Array, Uint8Array>

// Derives or fetches the CEK from the decoded envelope, e.g. from a salt and
// scope in appMetadata. Called at most once, after the envelope decodes and
// before any chunk is decrypted, with the same EnvelopeInfo parse() returns.
// That info is unauthenticated: check it (an allowed scope, say) before
// fetching a key. A returned key is borrowed until the stream settles. A
// resolver failure becomes KeyResolutionError; an invalid key, InvalidKeyError.
type KeyResolver = (info: EnvelopeInfo) => Promise<Uint8Array> | Uint8Array
// before any chunk is decrypted, with the same EnvelopeInfo parse() returns
// and an AbortSignal that aborts if the stream is cancelled, aborted (including
// via options.signal), or fails (never on successful EOF). That info is
// unauthenticated: check it (an allowed scope, say) before fetching a key. FEE
// borrows the returned bytes only long enough to import them into a
// non-extractable CryptoKey and never zeroes the caller's buffer; the caller
// owns every key it returns — including one FEE discards after cancellation —
// and should zero it once the stream settles.
// A resolver failure becomes KeyResolutionError unless the signal aborted; an
// invalid key, InvalidKeyError.
type KeyResolver = (info: EnvelopeInfo, signal: AbortSignal) => Promise<Uint8Array> | Uint8Array

// ── whole-object AES-GCM (scheme 1), exported as fee.aesGcm ─────────────────
namespace aesGcm {
Expand All @@ -473,7 +496,11 @@ namespace aesGcm {
}

// ── inspection, no key required, exported at the root as fee.parse ──────────
function parse(source: Uint8Array | RandomAccessSource): Promise<EnvelopeInfo>
interface ParseOptions {
signal?: AbortSignal
}

function parse(source: Uint8Array | RandomAccessSource, options?: ParseOptions): Promise<EnvelopeInfo>

interface EnvelopeInfoBase {
contentType?: string | number // tstr / uint; a number must be a non-negative safe integer
Expand All @@ -488,19 +515,24 @@ type EnvelopeInfo =
| (EnvelopeInfoBase & { scheme: 'chunked'; params: ChunkedEnvelopeParams })

// ── range decryption, exported at the root ──────────────────────────────────
interface RangeDecryptOptions {
params?: ChunkedEnvelopeParams
signal?: AbortSignal
}

function decryptRange(
source: RandomAccessSource | Uint8Array,
cek: Uint8Array,
range: ByteRange,
options?: { params?: ChunkedEnvelopeParams }
options?: RangeDecryptOptions
): Promise<RangeResult>

// Same, recovering the CEK through an unwrapper (tag 96 only), like decryptWith.
function decryptRangeWith(
source: RandomAccessSource | Uint8Array,
unwrapper: recipients.Unwrapper,
range: ByteRange,
options?: { params?: ChunkedEnvelopeParams }
options?: RangeDecryptOptions
): Promise<RangeResult>

interface ByteRange {
Expand Down Expand Up @@ -528,7 +560,7 @@ interface RandomAccessSource {
readonly size: number

/** Open the half-open byte range [offset, offset + length). */
openRange(offset: number, length: number): Promise<ReadableStream<Uint8Array>>
openRange(offset: number, length: number, signal?: AbortSignal): Promise<ReadableStream<Uint8Array>>
}

// ── cached chunked-envelope parameters ──────────────────────────────────────
Expand Down Expand Up @@ -581,19 +613,33 @@ the unwrapper; it is not an unsupported content scheme.

Operations borrow caller inputs while they may still read them. Callers MUST NOT modify plaintext,
encoded bytes, keys, recipient objects, or metadata until the returned promise settles. The library
does not modify caller-owned inputs or retain key bytes after the operation settles; callers may
clear their keys afterward. Values retained
does not modify or zero caller-owned inputs and does not retain key bytes after the operation
settles; raw keys are borrowed only long enough to import them into a non-extractable `CryptoKey`
(unless recipient wrapping requires extractability), and callers own the buffers and may zero them
afterward. Values retained
beyond a call or passed to an unwrapper are copied where needed. Byte inputs passed to Web Crypto
MUST be backed by an ordinary `ArrayBuffer`; a `SharedArrayBuffer`-backed view is rejected with the
relevant input error.

Streaming operations follow the same rule, with the stream in place of the promise: option buffers
(CEK, recipient KEKs and kids, metadata) stay borrowed until the returned stream closes or errors, and
may be read as late as its first read. A source block may be reused once its `write()` resolves. A key
returned by a `KeyResolver` is borrowed the same way as a directly passed one.
returned by a `KeyResolver` or custom `Unwrapper` is caller-owned and borrowed the same way as a
directly passed one: the library borrows the bytes only long enough to import them into a
non-extractable `CryptoKey`, never zeroes the buffer, and skips validation and import if the stream
or signal aborted before recovery settled. The caller owns every key it returns — including one the
library discards after cancellation — and should zero it once the operation settles. When the
built-in unwrapper from `recipients.createA256KWUnwrapper`
is passed directly to `decryptWith`, `decryptRangeWith`, or `aesGcm.decryptWith`, the library zeroes
its own temporary unwrapped key buffer after importing it (and on any abort or validation discard
path), and skips raw export if aborted before export.

Range reads split the two: the CEK is borrowed until the `decryptRange` promise settles, since the key
is imported before it resolves, and the source is borrowed until the result stream closes or errors.
When `options.signal` is supplied to `decrypt`, `decryptWith`, `decryptRange`, or `decryptRangeWith`,
its abort listener retains the stream (and, for range reads, its `source`) until the stream settles
or `signal` aborts; callers sharing a long-lived `AbortSignal` should consume or explicitly cancel
unused streams (or use an operation-scoped signal).

### Random-access source contract

Expand Down Expand Up @@ -621,8 +667,14 @@ A response with extra bytes after the requested length is rejected before the la
is released. Errors from the source's own stream propagate unchanged, and a failure while reading an
opened range cancels that stream. An `openRange` that fails before returning a stream has nothing to
cancel. Cancelling a range read never waits on a pending `openRange`; a stream that arrives
after cancellation is cancelled too. Stopping a hung open itself is left to the adapter, for example
with a fetch timeout.
after cancellation is cancelled too. When `options.signal` is passed to `parse`, `decryptRange`, or
`decryptRangeWith`, that signal is forwarded to `openRange` during envelope setup (omitted when
none is provided) and to any `Unwrapper`, aborts setup or errors an active result stream with the
exact `signal.reason`, cancels active or late-arriving source streams, and discards late key results
without importing them. For ciphertext spans opened by `RangeResult.stream`, the stream always passes
its own stream-scoped `AbortSignal` to `openRange`, which mirrors `options.signal` when supplied and
also aborts if the result stream is cancelled or fails. Adapters that ignore the third `signal`
argument remain supported; stopping a hung transport request itself is still up to the adapter.

The source contract provides consistent layout input; it does not authenticate the source. The
library still treats `size` and returned bytes as untrusted, validates all derived offsets, and
Expand Down
Loading
Loading