Skip to content

NWC Improvements#42

Merged
ntheile merged 6 commits into
masterfrom
nwc-improvments
Jun 26, 2026
Merged

NWC Improvements#42
ntheile merged 6 commits into
masterfrom
nwc-improvments

Conversation

@ntheile

@ntheile ntheile commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Added Lightning Address support for NWC nodes via getLightningAddress()
    • Implemented LNURL-verify support for validating Lightning Address payment requests
  • Improvements
    • Enhanced NWC error reporting with structured NwcError codes/messages and operation context
    • Improved timeout handling (including safer client closing behavior) and expanded invoice lookup resilience
  • Tests
    • Expanded coverage for Lightning Address resolution, LNURL-verify workflows, and new timeout/error scenarios

@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ntheile, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 21 minutes and 16 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: af97169e-8b0d-4270-bdef-ca5399fc6966

📥 Commits

Reviewing files that changed from the base of the PR and between f172d37 and 72dfe47.

📒 Files selected for processing (7)
  • bindings/typescript/src/__tests__/lnurl.test.ts
  • bindings/typescript/src/__tests__/nwc.test.ts
  • bindings/typescript/src/lnurl.ts
  • bindings/typescript/src/nodes/nwc.ts
  • crates/lni/lnurl/mod.rs
  • crates/lni/nwc/api.rs
  • crates/lni/nwc/lib.rs
📝 Walkthrough

Walkthrough

The PR adds Lightning Address support for NWC nodes, including LNURL-verify checks, structured NWC/NIP-47 error types, and updated request/error handling in both TypeScript and Rust. It also updates tests and package versions.

Changes

NWC Lightning Address and Error Handling

Layer / File(s) Summary
Error type contracts and NWC error code translation
bindings/typescript/src/errors.ts, crates/lni/lib.rs
TypeScript LniErrorCode gains NwcError and a new exported NwcError class is added. Rust ApiError gains an Nwc variant with code and message.
LNURL-verify flow and response helpers
bindings/typescript/src/lnurl.ts, crates/lni/lnurl/mod.rs
LNURL response/error types are expanded, error handling is centralized, and Lightning Address pay-request verification is added in both TypeScript and Rust.
Lightning Address data types and exports
bindings/typescript/src/types.ts, crates/lni/nwc/lib.rs, crates/lni/lib.rs
TypeScript LightningAddressInfo and Rust NwcLightningAddress are added, and the Rust NWC module re-exports the Lightning Address type.
NWC request helpers and error translation
bindings/typescript/src/nodes/nwc.ts, crates/lni/nwc/api.rs
NWC/NIP-47 errors are normalized through shared helpers, timeout handling is added, and request execution can use executeNip47Request when available.
NWC Lightning Address extraction and lookup
bindings/typescript/src/nodes/nwc.ts, crates/lni/nwc/api.rs, crates/lni/nwc/lib.rs
NWC URIs are parsed for lud16, Lightning Address verification is wired into getLightningAddress, and the Rust node API exposes the same capability.
NWC operation rewiring
bindings/typescript/src/nodes/nwc.ts, crates/lni/nwc/api.rs
getPermissions, getInfo, invoice creation/payment, lookup, and transaction listing now route through the centralized request/error path.
NWC test coverage
bindings/typescript/src/__tests__/nwc.test.ts, bindings/typescript/src/__tests__/integration/nwc.real.test.ts, crates/lni/nwc/api.rs, crates/lni/nwc/lib.rs
Tests add typed NIP-47 error mocks, Lightning Address verification coverage, lookup timeout behavior, and Rust assertions for error mapping and URI parsing.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I sniffed a lud16 in the wire,
And hopped through LNURL with careful desire.
NIP-47 grumbled, but codes stayed in tune,
While Lightning Addresses danced under the moon.
Hop-hop—verified invoices now sing!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is too generic and does not convey the specific NWC changes in this PR. Use a more descriptive title such as 'Add NWC Lightning Address support and typed error handling'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch nwc-improvments

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

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 26b40ebacd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread bindings/typescript/src/nodes/nwc.ts Outdated
@socket-security

socket-security Bot commented Jun 9, 2026

Copy link
Copy Markdown

No dependency changes detected. Learn more about Socket for GitHub.

👍 No dependency changes detected in pull request

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
bindings/typescript/src/__tests__/nwc.test.ts (1)

127-140: 💤 Low value

Consider consolidating duplicate payInvoice calls.

The test makes two separate calls to makeNode().payInvoice() with different assertions. This could be refactored to capture the rejection once:

-    await expect(makeNode().payInvoice({ invoice: BOLT11_INVOICE })).rejects.toMatchObject({
-      name: 'NwcError',
-      code: 'NwcError',
-      nwcCode: 'QUOTA_EXCEEDED',
-      nwcMessage: 'quota spent',
-      operation: 'pay_invoice',
-      message: 'quota spent',
-    });
-
-    await expect(makeNode().payInvoice({ invoice: BOLT11_INVOICE })).rejects.toBeInstanceOf(NwcError);
+    const error = await makeNode().payInvoice({ invoice: BOLT11_INVOICE }).catch(e => e);
+    
+    expect(error).toMatchObject({
+      name: 'NwcError',
+      code: 'NwcError',
+      nwcCode: 'QUOTA_EXCEEDED',
+      nwcMessage: 'quota spent',
+      operation: 'pay_invoice',
+      message: 'quota spent',
+    });
+    expect(error).toBeInstanceOf(NwcError);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bindings/typescript/src/__tests__/nwc.test.ts` around lines 127 - 140, Call
makeNode().payInvoice(...) only once and reuse that rejected promise for both
assertions: assign the result of makeNode().payInvoice({ invoice: BOLT11_INVOICE
}) to a variable (e.g., rejectedPromise) after configuring nwcMocks.payInvoice
to throw the Nip47Error, then await
expect(rejectedPromise).rejects.toMatchObject({...}) and await
expect(rejectedPromise).rejects.toBeInstanceOf(NwcError). Keep references to
makeNode, payInvoice, NwcError, nwcMocks.payInvoice, and nwcMocks.Nip47Error to
locate the code to change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@bindings/typescript/src/lnurl.ts`:
- Around line 397-400: The current check treats empty strings for maybeVerify.pr
and maybeVerify.verify as valid because it only tests typeof, leading to
downstream URL parsing errors instead of throwing LnurlVerifyUnsupportedError;
update the validation in the handler that casts callbackResponse to
Partial<LnurlVerifyInvoiceResponse> (the maybeVerify variable) to additionally
ensure both maybeVerify.pr and maybeVerify.verify are non-empty (e.g., check
they are strings with length > 0 or trim() !== '') and throw
LnurlVerifyUnsupportedError() when either is missing/empty so empty values are
normalized as unsupported verify responses.

In `@bindings/typescript/src/nodes/nwc.ts`:
- Around line 169-186: The current getLightningAddress implementation swallows
all errors from verifyLightningAddressPayRequest and returns
lnurlVerifySupported: false; change it to only treat LnurlVerifyUnsupportedError
as "unsupported" while letting genuine failures propagate: call
verifyLightningAddressPayRequest (from bindings/typescript/src/lnurl.ts) and
catch exceptions only of type LnurlVerifyUnsupportedError to set
lnurlVerifySupported = false, but rethrow any other errors (e.g. instances of
LniError or unknown errors) so they surface to the caller; keep the existing
extraction via extractLightningAddressFromNwcUri and preserve passing
this.options.fetch to the verify call.

In `@crates/lni/lnurl/mod.rs`:
- Around line 266-290: The code in verify_lightning_address_pay_request
currently fetches URLs derived from untrusted LNURL data (via
lightning_address_to_url, well_known.callback and verify_response.verify) using
fetch_lnurl_pay and fetch_lnurl_json_value without validating them first; add
strict URL validation before any outbound fetch: parse each URL (the URL
produced by lightning_address_to_url, the callback URL built by
callback_url_with_amount(&well_known.callback, …), and verify_response.verify),
ensure the scheme is https, reject IP-literal hosts or resolve the hostname and
verify the resolved addresses are not loopback/private/RFC1918/cloud metadata
ranges, or apply a safe-host allowlist; perform these checks in
verify_lightning_address_pay_request immediately before calling fetch_lnurl_pay
and before each fetch_lnurl_json_value, returning ApiError::InvalidInput on
failure.

---

Nitpick comments:
In `@bindings/typescript/src/__tests__/nwc.test.ts`:
- Around line 127-140: Call makeNode().payInvoice(...) only once and reuse that
rejected promise for both assertions: assign the result of
makeNode().payInvoice({ invoice: BOLT11_INVOICE }) to a variable (e.g.,
rejectedPromise) after configuring nwcMocks.payInvoice to throw the Nip47Error,
then await expect(rejectedPromise).rejects.toMatchObject({...}) and await
expect(rejectedPromise).rejects.toBeInstanceOf(NwcError). Keep references to
makeNode, payInvoice, NwcError, nwcMocks.payInvoice, and nwcMocks.Nip47Error to
locate the code to change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 633a7b89-7db4-4e44-ae1b-be6f8a9fa097

📥 Commits

Reviewing files that changed from the base of the PR and between 45a1d91 and 26b40eb.

📒 Files selected for processing (9)
  • bindings/typescript/src/__tests__/nwc.test.ts
  • bindings/typescript/src/errors.ts
  • bindings/typescript/src/lnurl.ts
  • bindings/typescript/src/nodes/nwc.ts
  • bindings/typescript/src/types.ts
  • crates/lni/lib.rs
  • crates/lni/lnurl/mod.rs
  • crates/lni/nwc/api.rs
  • crates/lni/nwc/lib.rs

Comment thread bindings/typescript/src/lnurl.ts
Comment thread bindings/typescript/src/nodes/nwc.ts
Comment thread crates/lni/lnurl/mod.rs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
bindings/typescript/src/nodes/nwc.ts (1)

240-256: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not hide get_info timeouts after closing the client.

A get_info timeout closes this.client in withTimeout, but the broad catch returns fallback node info as if the call succeeded, leaving the NwcNode silently unusable for later operations.

Proposed fix
-    } catch {
+    } catch (error) {
+      if (error instanceof LniError && error.code === 'NetworkError') {
+        throwNwcOrApiError(error, 'get_info', 'Failed to get info');
+      }
+
       return emptyNodeInfo({
         alias: 'NWC Node',
         pubkey: pubkeyFallback,

Also applies to: 503-511

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bindings/typescript/src/nodes/nwc.ts` around lines 240 - 256, The broad catch
in NwcNode’s get info flow is swallowing executeNip47Request/get_info timeout
failures and returning emptyNodeInfo, which hides that this.client may have been
closed by withTimeout. Update the try/catch around executeNip47Request in the
NwcNode method (and the similar fallback block in the other referenced location)
to detect timeout/closed-client failures and surface them instead of silently
mapping to fallback node info. Keep fallback node info only for non-fatal cases,
and preserve the error path so callers know the NwcNode is no longer usable
after a timeout.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@bindings/typescript/src/nodes/nwc.ts`:
- Around line 55-57: The LniError rewrap in nwc.ts is dropping structured
metadata, so update the error translation path to preserve the original status
and body when `error instanceof LniError` before throwing the new `LniError`.
Keep the existing `code` and `cause` behavior in the `LniError` construction,
and ensure the rethrown error carries through all original HTTP/API context
fields from the incoming `error` object.

---

Outside diff comments:
In `@bindings/typescript/src/nodes/nwc.ts`:
- Around line 240-256: The broad catch in NwcNode’s get info flow is swallowing
executeNip47Request/get_info timeout failures and returning emptyNodeInfo, which
hides that this.client may have been closed by withTimeout. Update the try/catch
around executeNip47Request in the NwcNode method (and the similar fallback block
in the other referenced location) to detect timeout/closed-client failures and
surface them instead of silently mapping to fallback node info. Keep fallback
node info only for non-fatal cases, and preserve the error path so callers know
the NwcNode is no longer usable after a timeout.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d005a7a7-2005-4238-874d-21e9dcda0821

📥 Commits

Reviewing files that changed from the base of the PR and between 26b40eb and f172d37.

⛔ Files ignored due to path filters (4)
  • bindings/typescript-arkade/package-lock.json is excluded by !**/package-lock.json
  • bindings/typescript-spark/examples/spark-expo-go/package-lock.json is excluded by !**/package-lock.json
  • bindings/typescript-spark/package-lock.json is excluded by !**/package-lock.json
  • bindings/typescript/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • bindings/typescript-arkade/package.json
  • bindings/typescript-spark/package.json
  • bindings/typescript/package.json
  • bindings/typescript/src/__tests__/integration/nwc.real.test.ts
  • bindings/typescript/src/__tests__/nwc.test.ts
  • bindings/typescript/src/nodes/nwc.ts
✅ Files skipped from review due to trivial changes (3)
  • bindings/typescript/package.json
  • bindings/typescript-arkade/package.json
  • bindings/typescript/src/tests/integration/nwc.real.test.ts

Comment thread bindings/typescript/src/nodes/nwc.ts
@ntheile
ntheile merged commit 1afd87c into master Jun 26, 2026
3 checks passed
This was referenced Jul 7, 2026
Merged
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.

1 participant