Skip to content

Make the transport proxy throw exceptions on every sw except 0x9000 (…#571

Merged
chcmedeiros merged 1 commit intomainfrom
dev
Aug 6, 2025
Merged

Make the transport proxy throw exceptions on every sw except 0x9000 (…#571
chcmedeiros merged 1 commit intomainfrom
dev

Conversation

@chcmedeiros
Copy link
Copy Markdown
Collaborator

@chcmedeiros chcmedeiros commented Aug 6, 2025

#566)

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for device communication by ensuring errors are detected and reported immediately when an invalid status code is returned.
  • Chores

    • Updated dependencies to include the latest error handling package.
  • Tests

    • Enhanced test coverage for error handling to ensure prompt detection of device communication errors.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 6, 2025

Walkthrough

A new dependency, @ledgerhq/errors, was added to the project. The Zemu transport wrapper was updated to explicitly check the APDU response status word after sending commands, throwing a TransportStatusError for non-success codes. Tests were adjusted to provide explicit status codes and data buffers, aligning with the new error handling logic.

Changes

Cohort / File(s) Change Summary
Dependency Update
package.json
Added @ledgerhq/errors dependency version ^6.23.0.
Transport Error Handling
src/Zemu.ts
Added APDU status word check after transport send; introduced ApduError enum; throw TransportStatusError on error SW.
Test Adjustments
tests/error-handling.test.ts
Modified test to supply explicit data buffer and statusList to transport.send to match new error handling logic.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Zemu
    participant Transport
    participant Errors

    Caller->>Zemu: getTransport().send(...)
    Zemu->>Transport: send(...)
    Transport-->>Zemu: responseBuffer
    Zemu->>Zemu: Extract SW from responseBuffer
    alt SW == NoError (0x9000)
        Zemu-->>Caller: Return responseBuffer
    else SW != NoError
        Zemu->>Errors: Throw TransportStatusError(SW)
        Zemu-->>Caller: Exception thrown
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/Zemu.ts (2)

70-72: ApduError enum design is minimal but functional.

The enum contains only the success status code. Consider adding other common APDU error codes for better maintainability and documentation.

 enum ApduError {
   NoError = 0x9000,
+  // Common APDU error codes
+  ConditionsNotSatisfied = 0x6985,
+  SecurityStatusNotSatisfied = 0x6982,
+  WrongData = 0x6a80,
+  WrongLength = 0x6700,
+  ClaNotSupported = 0x6e00,
+  InsNotSupported = 0x6d00,
 }

462-485: Consider extracting status word validation into a separate method.

The status word validation logic is repeated and could be extracted into a reusable method for better maintainability.

+    private validateStatusWord(result: Buffer, statusList?: number[]): void {
+      const sw = result.readUInt16BE(result.length - 2)
+      if (sw !== ApduError.NoError && (!statusList || !statusList.includes(sw))) {
+        throw new TransportStatusError(sw)
+      }
+    }
+
     // Return a proxy that intercepts send() calls
     return new Proxy(originalTransport, {
       get(target, prop, receiver) {
         if (prop === 'send') {
           return async function (cla: number, ins: number, p1: number, p2: number, data?: Buffer, statusList?: number[]) {
             try {
               self.lastTransportError = null // Clear previous error
               const result = await target.send(cla, ins, p1, p2, data, statusList)
-              const sw = result.readUInt16BE(result.length - 2)
-
-              if (sw !== ApduError.NoError) {
-                throw new TransportStatusError(sw)
-              }
+              self.validateStatusWord(result, statusList)
               return result
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 51812b8 and ebfc9a4.

⛔ Files ignored due to path filters (2)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/Zemu.ts (3 hunks)
  • tests/error-handling.test.ts (1 hunks)
🔇 Additional comments (4)
package.json (1)

45-45: Dependency addition confirmed.

The @ledgerhq/errors dependency at version ^6.23.0 is the latest stable release (published July 23, 2025) and aligns with the PR’s error handling enhancements. No further changes needed.

tests/error-handling.test.ts (2)

32-34: Test parameters correctly updated for new error handling.

The addition of an empty data buffer and explicit status list aligns with the new transport behavior that checks status words after APDU responses.


41-41: No changes needed: test behavior matches implementation

The send wrapper in src/Zemu.ts always throws a TransportStatusError for any status word other than ApduError.NoError (0x9000). Therefore, passing a statusList that includes 0x6e00 will still result in an exception on 0x6e00, which is exactly what the test asserts.

src/Zemu.ts (1)

18-18: Import statement is correct.

The TransportStatusError import from @ledgerhq/errors aligns with the new dependency added in package.json.

Comment thread src/Zemu.ts
Comment on lines +466 to +470
const sw = result.readUInt16BE(result.length - 2)

if (sw !== ApduError.NoError) {
throw new TransportStatusError(sw)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Status word validation logic is correct but breaks existing transport behavior.

The implementation correctly extracts the 2-byte status word from the end of the APDU response and throws TransportStatusError for non-success codes. However, this fundamentally changes the transport behavior by ignoring the statusList parameter that was previously used to accept specific error codes.

The current implementation ignores the statusList parameter and throws exceptions for ANY non-0x9000 status word. This breaks backward compatibility for code that intentionally accepts specific error status codes.

Consider this alternative approach:

-              const sw = result.readUInt16BE(result.length - 2)
-
-              if (sw !== ApduError.NoError) {
-                throw new TransportStatusError(sw)
-              }
+              const sw = result.readUInt16BE(result.length - 2)
+
+              // Only throw if status word is not in the accepted list
+              if (sw !== ApduError.NoError && (!statusList || !statusList.includes(sw))) {
+                throw new TransportStatusError(sw)
+              }

This preserves the original behavior where specific error codes can be accepted via the statusList parameter.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const sw = result.readUInt16BE(result.length - 2)
if (sw !== ApduError.NoError) {
throw new TransportStatusError(sw)
}
const sw = result.readUInt16BE(result.length - 2)
// Only throw if status word is not in the accepted list
if (sw !== ApduError.NoError && (!statusList || !statusList.includes(sw))) {
throw new TransportStatusError(sw)
}
🤖 Prompt for AI Agents
In src/Zemu.ts around lines 466 to 470, the current code throws a
TransportStatusError for any status word not equal to ApduError.NoError,
ignoring the statusList parameter. To fix this, modify the logic to check if the
extracted status word is included in the statusList array before throwing an
error. If the status word is not in statusList, then throw the
TransportStatusError; otherwise, allow the response to pass. This preserves
backward compatibility by respecting the statusList parameter.

@chcmedeiros chcmedeiros merged commit 931ff67 into main Aug 6, 2025
8 checks passed
@chcmedeiros chcmedeiros deleted the dev branch August 6, 2025 14:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants