Skip to content

feat(filecoin-encryption-envelope): add AbortSignal support, ciphertext length errors, and sizing exports - #1186

Merged
hugomrdias merged 7 commits into
masterfrom
hugomrdias/envelope-abort-errors-sizing
Dec 1, 2026
Merged

hugomrdias merged 7 commits into
masterfrom
hugomrdias/envelope-abort-errors-sizing

Conversation

@hugomrdias

Copy link
Copy Markdown
Member

Summary

Combines four filecoin-encryption-envelope improvements addressing filecoin-project/agents#181 as four cleanly separated Conventional Commits:

1. Sizing exports and preflight helper (#1178)

  • Export MAX_ENVELOPE_SIZE and TAG_SIZE from constants (src/public-constants.ts).
  • Export ciphertextLengthForPlaintext(plaintextLength, chunkSize) from the package root (src/index.ts) for preflight encoded-size checks.
  • Document preflight sizing in README.md and cover public exports and boundary cases in test/public-surface.test.ts.

2. Distinct truncated and excess ciphertext length errors (#1177)

  • Add TruncatedCiphertextError and ExcessCiphertextError (both extending InvalidCiphertextLengthError) in src/errors.ts.
  • Emit the specific subclass in streaming decryption (src/aes-gcm-stream.ts) and range planning (src/range/plan.ts) when observed/declared ciphertext lengths are shorter or longer than expected.
  • Update README.md, docs/implementation-guide.md, and test suites (test/aes-gcm-stream-decrypt.test.ts, test/range-plan.test.ts, test/range-decrypt.test.ts, test/public-surface.test.ts).

3. AbortSignal support across streaming and range decryption (#1172)

  • Add optional options?: DecryptOptions ({ signal?: AbortSignal }) to decrypt() and decryptWith(), and signal?: AbortSignal to RangeDecryptOptions for decryptRange() and decryptRangeWith().
  • Add src/internal/abort.ts (assertOptionalAbortSignal, throwIfAborted, raceAbort) to preserve exact signal.reason identity, reject promptly on pre-aborted or mid-flight aborts, unblock pending writes/reads, cancel active or late-arriving range streams, and clean up 'abort' listeners across all exit paths.
  • Forward options.signal to RandomAccessSource.openRange and Unwrapper (including stopping remaining unwrap attempts in createA256KWUnwrapper).
  • Add comprehensive coverage in test/abort-signal.test.ts.

4. AbortSignal for KeyResolver and key ownership guarantees (#1173)

  • Update KeyResolver to always receive (info: EnvelopeInfo, signal: AbortSignal) backed by an internal AbortController in createDecryptStream (existing 1-argument resolvers remain assignable).
  • Abort the resolver's signal inside failInput(reason) on readable cancellation, writable abort, stream failure, and options.signal abort (forwarding exact options.signal.reason), while leaving signal.aborted === false on successful EOF.
  • Guarantee that late keys returned after abort skip validation (assertAes256Key) and importAesGcmKey and are left untouched (never zeroed by FEE).
  • Document key ownership and KeyResolver abort semantics in README.md, docs/implementation-guide.md, and JSDoc, with unit and integration coverage in test/aes-gcm-stream-decrypt-resolver.test.ts, test/key-resolver-flow.test.ts, and test/abort-signal.test.ts.

Verification

  • pnpm run lint:fix — passed (0 errors)
  • pnpm turbo build --filter=filecoin-encryption-envelope --force — passed
  • pnpm turbo lint --filter=filecoin-encryption-envelope --force — passed (67 files checked)
  • pnpm turbo test --filter=filecoin-encryption-envelope --force — passed (Node: 756 passing; browser: 744 passing, 9 pending)
  • pnpm turbo test --filter=@filoz/keysmith — passed (Node: 179 passing; browser: 179 passing)
  • pnpm exec markdownlint-cli2 --config .github/.markdownlint-cli2.jsonc 'packages/filecoin-encryption-envelope/**/*.md' — passed (0 issues in 3 files)

Related: filecoin-project/agents#181

Closes #1172
Closes #1173
Closes #1177
Closes #1178

@github-project-automation github-project-automation Bot moved this to 📌 Triage in FOC Dec 1, 2026
@pkg-pr-new

pkg-pr-new Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

filecoin-encryption-envelope

npm i https://pkg.pr.new/filecoin-encryption-envelope@1186

@filoz/keysmith

npm i https://pkg.pr.new/@filoz/keysmith@1186

@filoz/synapse-core

npm i https://pkg.pr.new/@filoz/synapse-core@1186

@filoz/synapse-react

npm i https://pkg.pr.new/@filoz/synapse-react@1186

@filoz/synapse-sdk

npm i https://pkg.pr.new/@filoz/synapse-sdk@1186

commit: dee292d

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

Please fix two cancellation paths before merging: a range abort can leave the caller waiting on adapter cleanup, and resolver cleanup can make an aborted read report normal EOF.

Approach: Reusing the existing sizing logic, extending the existing length error, and giving KeyResolver a stream-owned signal are the right boundaries; the cancellation ordering needs two fixes.

Reviewed changes across the streaming and range APIs, recipient recovery, public exports, docs, and tests.

  • Sizing: Exposes the detached ciphertext calculation and the constants needed for full-object preflight checks.
  • Length errors: Distinguishes short and excess ciphertext against a declared plaintext_length while preserving instanceof InvalidCiphertextLengthError.
  • Cancellation and key ownership: Adds external signals to streaming and range decryption, forwards them to range sources and unwrappers, and notifies the resolver without mutating or importing late keys.
  • Verification: Build passed; Node tests had 756 passing and Chromium had 744 passing with 9 pending. Separate checks reproduced both cancellation findings.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-sol | 𝕏

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Docs preview: https://pr-1186-synapse-dev.filoz.workers.dev

Built from dee292d.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The previous cancellation fixes work, but the new paths can still leave reads pending after abort, replace a truncation error, or report success after cancellation.

Reviewed changes in d6f6d77, the commit added since the previous review.

  • Hardened cancellation by observing dependent signals, settling stream errors before cleanup, and no longer waiting for adapter teardown during range setup or failure.
  • Expanded signal coverage to parse(), streaming unwrappers, and ciphertext range opens.
  • Moved truncation detection to writable EOF so a short input can stop pending key recovery.
  • Added key cleanup for temporary AES-KW buffers while preserving ownership of keys returned by custom callbacks.
  • Verified the package build, lint, and Node and Chromium suites; reproduced the four findings separately in Node.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-sol | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The cancellation fixes work. The new strong observer also keeps discarded streams and their input buffers alive under a shared signal, so callers need an explicit cleanup contract.

Reviewed changes in b2f94b6, the commit added since the last Pullfrog review.

  • Kept pending operations abortable when only the read or writer.closed promise survives garbage collection.
  • Preserved the original writable error when resolver cleanup re-enters writer.abort() after short or excess input.
  • Rechecked cancellation after envelope probe cleanup starts and after each built-in AES-KW unwrap attempt, wiping any discarded key bytes.
  • Verified build and lint, 774 passing Node tests with forced GC, and 763 passing Chromium tests. A separate Node check confirmed the retention described inline.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-sol | 𝕏

@hugomrdias
hugomrdias force-pushed the hugomrdias/envelope-abort-errors-sizing branch from b2f94b6 to 2cf43f9 Compare December 1, 2026 16:56
@BravoNatalie

Copy link
Copy Markdown
Collaborator

Reviewed at 2cf43f9. Closes #1172, #1173, #1177 and #1178 as they asked; nothing blocking. A few notes:

  1. Option errors use MalformedEnvelopeError (readDecryptOptions, readRangeOptions, readParseOptions, assertOptionalAbortSignal). A bad signal is a caller mistake, not a damaged envelope, and callers that map MalformedEnvelopeError to "not encrypted" would show that to the user. TypeError would fit better (the existing Invalid unwrapper check has the same issue).

  2. Late keys: the KeyResolver and Unwrapper docs say a resolver that produces bytes after abort "should zero them itself instead of returning them". There's still a gap: the resolver checks the signal, returns, and the abort lands before FEE's resolverSignal.aborted check, so the key is dropped without being zeroed. Suggest wording it as: the caller owns every key it returns, including one FEE discards, and zeroes it once the stream settles.

  3. internal/abort.ts: with engines.node >=22, AbortSignal.any and throwIfAborted() always exist, so the typeof AbortSignal.any === 'function' fallbacks never run. The defence against synthetic dispatchEvent, stopImmediatePropagation and cross-realm signals, plus the WeakSet of observed signals, adds a lot of code and ~2.3k lines of tests for an optional parameter. Could throwIfAborted, AbortSignal.any and one { once: true } listener cover it?

  4. Truncated in the range path: planRange raises TruncatedCiphertextError when source.size is short, which means the stored object is short (not worth retrying), while in the stream path it means the bytes stopped early. Maybe one line in the docs, so callers don't treat both as retryable.

@hugomrdias

Copy link
Copy Markdown
Member Author

Thanks for the review @BravoNatalie! Addressed in dee292d8:

  1. Option validation errors: Kept MalformedEnvelopeError for consistency with the package's existing input validation (AGENTS.md / Invalid unwrapper / etc.).
  2. Late-key ownership wording: Updated KeyResolver, decrypt, Unwrapper JSDoc, README.md, and docs/implementation-guide.md to state that the caller owns every key it returns — including one FEE discards after cancellation — and should zero it once the stream/operation settles.
  3. src/internal/abort.ts simplification: Cut src/internal/abort.ts down to three small helpers (assertOptionalAbortSignal via AbortSignal.any, { once: true } onAbort, and raceAbort), switched all abort checks to native signal?.throwIfAborted(), removed the WeakSet, createPrivateAbortController, deriveExternalSignal, toObservedSignal, typeof AbortSignal.any fallbacks, duplicate observedSignal parameters, and synthetic-event/interception test boilerplate (-209 net lines).
  4. Range vs. stream TruncatedCiphertextError: Documented in src/errors.ts, README.md, and docs/implementation-guide.md that in range planning it means the reported source.size itself is shorter than declared (a short stored object, not a transient cutoff), whereas in streaming decryption it means the input stream ended early.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The simplified abort observer can reject a live decrypt stream or leave a cancelled operation pending. The new native API requirements also reject valid signals on browsers that lack AbortSignal.any().

Approach: The smaller helper surface is useful, but cancellation still needs to follow the signal’s state rather than the delivery of a public event.

Reviewed changes in dee292d, the only substantive commit since the previous Pullfrog review.

  • Simplified cancellation by attaching listeners directly to the supplied signals, forwarding the internal range signal to adapters, and switching to native signal methods.
  • Clarified ownership and errors by documenting stream retention under shared signals, ownership of discarded keys, and what truncation means in streaming versus range reads.
  • Verified that build, lint, 773 Node tests with forced GC, and 762 Chromium tests pass; separate Node checks confirmed the regressions inline.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-sol | 𝕏

@BravoNatalie BravoNatalie left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, re-reviewed at dee292d. All four addressed; agreed on keeping MalformedEnvelopeError per the package's error convention. The note about long-lived signals is a good addition.

@hugomrdias hugomrdias self-assigned this Dec 1, 2026
@github-project-automation github-project-automation Bot moved this from 📌 Triage to ✔️ Approved by reviewer in FOC Dec 1, 2026
@hugomrdias
hugomrdias merged commit 54dd1af into master Dec 1, 2026
12 checks passed
@hugomrdias
hugomrdias deleted the hugomrdias/envelope-abort-errors-sizing branch December 1, 2026 19:27
@github-project-automation github-project-automation Bot moved this from ✔️ Approved by reviewer to 🎉 Done in FOC Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: 🎉 Done

2 participants