applesauce-wallet-connect 6.2.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { EventFactory, blankEventTemplate } from "applesauce-core/factories";
2
+ import { eventPipe } from "applesauce-core/helpers/pipeline";
2
3
  import { includeSingletonTag } from "applesauce-core/operations/tags";
3
4
  import { setEncryptedContent } from "applesauce-core/operations/encrypted-content";
4
5
  import { WALLET_REQUEST_KIND } from "../helpers/request.js";
@@ -13,10 +14,11 @@ export class WalletRequestFactory extends EventFactory {
13
14
  }
14
15
  request(request, encryption = "nip44_v2") {
15
16
  let result;
16
- result = this.chain(async (draft) => {
17
- const encrypted = await setEncryptedContent(draft.tags.find((t) => t[0] === "p")?.[1] || "", JSON.stringify(request), result.signer, encryption === "nip44_v2" ? "nip44" : "nip04")(draft);
18
- return includeSingletonTag(["encryption", encryption])(encrypted);
19
- });
17
+ // Compose via eventPipe so the "encryption" tag's `{ ...draft }` spread cannot silently drop
18
+ // the non-enumerable EncryptedContentSymbol that setEncryptedContent writes — the pipe's
19
+ // same-kind carry-forward restores it. Sequencing these two operations by hand (encrypt then
20
+ // spread) dropped the plaintext cache once the write became non-enumerable.
21
+ result = this.chain((draft) => eventPipe(setEncryptedContent(draft.tags.find((t) => t[0] === "p")?.[1] || "", JSON.stringify(request), result.signer, encryption === "nip44_v2" ? "nip44" : "nip04"), includeSingletonTag(["encryption", encryption]))(draft));
20
22
  return result;
21
23
  }
22
24
  }
@@ -1,4 +1,4 @@
1
- import { getHiddenContent, isHiddenContentUnlocked, notifyEventUpdate, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers";
1
+ import { getHiddenContent, isHiddenContentUnlocked, notifyEventUpdate, safeParse, setCachedValue, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers";
2
2
  export const WALLET_NOTIFICATION_KIND = 23197;
3
3
  export const WALLET_LEGACY_NOTIFICATION_KIND = 23196;
4
4
  /** A symbol used to cache the wallet notification on the event */
@@ -8,7 +8,9 @@ setHiddenContentEncryptionMethod(WALLET_NOTIFICATION_KIND, "nip44");
8
8
  setHiddenContentEncryptionMethod(WALLET_LEGACY_NOTIFICATION_KIND, "nip04");
9
9
  /** Checks if a kind 23196 or 23197 event is locked */
10
10
  export function isWalletNotificationUnlocked(notification) {
11
- // Wrap in try catch to avoid throwing validation errors
11
+ // The catch guards the `any` parameter only: `X in notification` throws a TypeError when
12
+ // handed a primitive. It is no longer masking a parse failure — getWalletNotification returns
13
+ // undefined for malformed content rather than throwing.
12
14
  try {
13
15
  return (WalletNotificationSymbol in notification ||
14
16
  (isHiddenContentUnlocked(notification) && getWalletNotification(notification) !== undefined));
@@ -34,10 +36,16 @@ export function getWalletNotification(notification) {
34
36
  const content = getHiddenContent(notification);
35
37
  if (!content)
36
38
  return undefined;
37
- // Parse the content as a wallet notification
38
- const parsed = JSON.parse(content);
39
- // Save the parsed content
40
- Reflect.set(notification, WalletNotificationSymbol, parsed);
39
+ // Parse the content as a wallet notification. safeParse (not JSON.parse) because this content
40
+ // arrives from the remote wallet service — malformed JSON is a routine network condition, not
41
+ // a programmer error, and this getter's return type already carries undefined for it.
42
+ const parsed = safeParse(content);
43
+ // Not cached on failure: the rejection describes the content available right now, and caching
44
+ // it would leave the notification permanently unreadable.
45
+ if (!parsed)
46
+ return undefined;
47
+ // Save the parsed content (identity memo, non-enumerable so a spread drops it)
48
+ setCachedValue(notification, WalletNotificationSymbol, parsed);
41
49
  notifyEventUpdate(notification);
42
50
  return parsed;
43
51
  }
@@ -1,6 +1,7 @@
1
1
  import { isNIP04Encrypted } from "applesauce-core/helpers/encryption";
2
2
  import { getTagValue, notifyEventUpdate } from "applesauce-core/helpers/event";
3
3
  import { getHiddenContent, isHiddenContentUnlocked, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers/hidden-content";
4
+ import { setCachedValue } from "applesauce-core/helpers/cache";
4
5
  import { unixNow } from "applesauce-core/helpers/time";
5
6
  import { nip47EncryptionMethodToNip07EncryptionMethod } from "./encryption.js";
6
7
  export const WALLET_REQUEST_KIND = 23194;
@@ -37,8 +38,8 @@ export function getWalletRequest(request) {
37
38
  if (!content)
38
39
  return undefined;
39
40
  const parsed = JSON.parse(content);
40
- // Save the parsed content
41
- Reflect.set(request, WalletRequestSymbol, parsed);
41
+ // Save the parsed content (identity memo, non-enumerable so a spread drops it)
42
+ setCachedValue(request, WalletRequestSymbol, parsed);
42
43
  notifyEventUpdate(request);
43
44
  return parsed;
44
45
  }
@@ -1,6 +1,7 @@
1
1
  import { isNIP04Encrypted } from "applesauce-core/helpers/encryption";
2
2
  import { getTagValue, notifyEventUpdate } from "applesauce-core/helpers/event";
3
3
  import { getHiddenContent, isHiddenContentUnlocked, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers/hidden-content";
4
+ import { setCachedValue } from "applesauce-core/helpers/cache";
4
5
  export const WALLET_RESPONSE_KIND = 23195;
5
6
  // Set the encryption method to use for response kind
6
7
  setHiddenContentEncryptionMethod(WALLET_RESPONSE_KIND, "nip04");
@@ -37,8 +38,8 @@ export function getWalletResponse(response) {
37
38
  if (!content)
38
39
  return undefined;
39
40
  const parsed = JSON.parse(content);
40
- // Save the parsed content
41
- Reflect.set(response, WalletResponseSymbol, parsed);
41
+ // Save the parsed content (identity memo, non-enumerable so a spread drops it)
42
+ setCachedValue(response, WalletResponseSymbol, parsed);
42
43
  notifyEventUpdate(response);
43
44
  return parsed;
44
45
  }
@@ -1,12 +1,14 @@
1
1
  import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
2
2
  import { simpleTimeout } from "applesauce-core";
3
3
  import { finalizeEvent, getPublicKey, verifyEvent } from "applesauce-core/helpers";
4
- import { nip04, nip44 } from "applesauce-core/helpers/encryption";
4
+ import { getCachedConversationKey, nip04, nip44 } from "applesauce-core/helpers/encryption";
5
5
  import { BehaviorSubject, combineLatest, defer, filter, firstValueFrom, from, fromEvent, identity, ignoreElements, interval, lastValueFrom, map, merge, mergeMap, of, repeat, ReplaySubject, retry, share, switchMap, take, takeUntil, tap, timer, toArray, } from "rxjs";
6
6
  import { WalletRequestFactory } from "./factories/index.js";
7
7
  import { createWalletError } from "./helpers/error.js";
8
8
  import { createWalletAuthURI, createWalletConnectURI, getPreferredEncryption, getWalletRequestEncryption, getWalletResponseRequestId, getWalletSupport, isValidWalletNotification, isValidWalletResponse, parseWalletConnectURI, supportsMethod, supportsNotifications, supportsNotificationType, unlockWalletNotification, unlockWalletResponse, WALLET_INFO_KIND, WALLET_LEGACY_NOTIFICATION_KIND, WALLET_NOTIFICATION_KIND, WALLET_RESPONSE_KIND, } from "./helpers/index.js";
9
9
  import { getConnectionMethods, } from "./interop.js";
10
+ /** Node's 32-bit signed timer limit (~24.8 days); setTimeout delays beyond this overflow and clamp to ~1ms. */
11
+ const MAX_TIMER_DELAY = 2_147_483_647;
10
12
  export class WalletConnect {
11
13
  /** A fallback method to use for subscriptionMethod if none is passed in when creating the client */
12
14
  static subscriptionMethod = undefined;
@@ -66,8 +68,8 @@ export class WalletConnect {
66
68
  decrypt: async (pubkey, ciphertext) => nip04.decrypt(this.secret, pubkey, ciphertext),
67
69
  },
68
70
  nip44: {
69
- encrypt: async (pubkey, plaintext) => nip44.encrypt(plaintext, nip44.getConversationKey(this.secret, pubkey)),
70
- decrypt: async (pubkey, ciphertext) => nip44.decrypt(ciphertext, nip44.getConversationKey(this.secret, pubkey)),
71
+ encrypt: async (pubkey, plaintext) => nip44.encrypt(plaintext, getCachedConversationKey(this.secret, pubkey)),
72
+ decrypt: async (pubkey, ciphertext) => nip44.decrypt(ciphertext, getCachedConversationKey(this.secret, pubkey)),
71
73
  },
72
74
  };
73
75
  // Get the subscription and publish methods
@@ -167,24 +169,24 @@ export class WalletConnect {
167
169
  genericCall(method, params, options = {}) {
168
170
  if (!this.service)
169
171
  throw new Error("WalletConnect is not connected to a service");
170
- // Create the request event
171
- return defer(async () => {
172
- // Get the preferred encryption method for the wallet
173
- const encryption = await firstValueFrom(this.encryption$);
174
- // Create and sign the request event
175
- return await WalletRequestFactory.create(this.service, { method, params }, encryption).as(this.signer).sign();
176
- }).pipe(
172
+ const timeout = options.timeout || this.defaultTimeout;
173
+ // Keep negotiation in the stream so timing out also releases its subscription.
174
+ return this.encryption$.pipe(
175
+ // Use the first negotiation result, then release the negotiation subscription
176
+ take(1),
177
+ // Create and sign the request event once the encryption method is known
178
+ switchMap((encryption) => defer(() => WalletRequestFactory.create(this.service, { method, params }, encryption).as(this.signer).sign())),
177
179
  // Then switch to the request observable
178
180
  switchMap((requestEvent) => {
179
181
  const encryption = getWalletRequestEncryption(requestEvent) === "nip44_v2" ? "nip44" : "nip04";
180
182
  // Create an observable that publishes the request event when subscribed to
181
183
  const request$ = defer(() => from(this.publishMethod(this.relays, requestEvent))).pipe(ignoreElements());
182
184
  // Create an observable that listens for response events
183
- const responses$ = this.events$.pipe(filter(isValidWalletResponse), filter((response) => getWalletResponseRequestId(response) === requestEvent.id), mergeMap((response) => this.handleResponseEvent(response, encryption)),
184
- // Set timeout for response events
185
- simpleTimeout(options.timeout || this.defaultTimeout));
185
+ const responses$ = this.events$.pipe(filter(isValidWalletResponse), filter((response) => getWalletResponseRequestId(response) === requestEvent.id), mergeMap((response) => this.handleResponseEvent(response, encryption)));
186
186
  return merge(request$, responses$);
187
- }));
187
+ }),
188
+ // Bound negotiation and request creation until the first response; promises already running cannot be cancelled.
189
+ simpleTimeout(timeout, "WalletConnect request timed out"));
188
190
  }
189
191
  /** Request method with generic type */
190
192
  async genericRequest(method, params, options = {}) {
@@ -221,6 +223,9 @@ export class WalletConnect {
221
223
  async waitForService(abortSignal) {
222
224
  if (this.service)
223
225
  return this.service;
226
+ // fromEvent only observes future aborts.
227
+ if (abortSignal?.aborted)
228
+ throw abortSignal.reason ?? new Error("Aborted");
224
229
  return await firstValueFrom(this.waitForService$.pipe(
225
230
  // Listen for abort signal
226
231
  abortSignal ? takeUntil(fromEvent(abortSignal, "abort")) : identity));
@@ -299,7 +304,10 @@ export class WalletConnect {
299
304
  if (result.state === "expired")
300
305
  throw new Error("Invoice expired");
301
306
  return [];
302
- }), simpleTimeout(expiresAt ? expiresAt - now : Infinity)));
307
+ }),
308
+ // Skip the timeout operator entirely when there's no expiry — an Infinity delay
309
+ // would clamp to ~1ms, causing an immediate spurious TimeoutError.
310
+ expiresAt ? simpleTimeout(expiresAt - now) : identity));
303
311
  }
304
312
  return new Promise((resolve, reject) => {
305
313
  const subscription = this.notification("payment_received", (payment) => {
@@ -308,11 +316,14 @@ export class WalletConnect {
308
316
  cleanup();
309
317
  resolve(payment);
310
318
  });
319
+ // Clamp the delay to the 32-bit timer limit; invoices expiring further out than
320
+ // ~24.8 days will reject at the cap instead of at the true expiry (accepted tradeoff,
321
+ // since this callback rejects rather than re-arming and so cannot hot-loop).
311
322
  const timeout = expiresAt
312
323
  ? setTimeout(() => {
313
324
  cleanup();
314
325
  reject(new Error("Invoice expired"));
315
- }, expiresAt - now)
326
+ }, Math.min(expiresAt - now, MAX_TIMER_DELAY))
316
327
  : undefined;
317
328
  function cleanup() {
318
329
  subscription.unsubscribe();
@@ -1,4 +1,4 @@
1
- import { EventSigner } from "applesauce-core";
1
+ import { EventSigner, type Debugger } from "applesauce-core";
2
2
  import { Observable, Subscription } from "rxjs";
3
3
  import { WalletAuthURI } from "./helpers/auth-uri.js";
4
4
  import { WalletErrorCode } from "./helpers/error.js";
@@ -53,7 +53,7 @@ export declare class WalletService<Methods extends TWalletMethod = CommonWalletM
53
53
  protected readonly subscriptionMethod: NostrSubscriptionMethod;
54
54
  /** A method for publishing events */
55
55
  protected readonly publishMethod: NostrPublishMethod;
56
- protected log: import("debug").Debugger;
56
+ protected log: Debugger;
57
57
  /** A special method for getting the generic wallet information */
58
58
  getInfo?: () => Promise<WalletServiceInfo>;
59
59
  /** The relays to use for the service */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "applesauce-wallet-connect",
3
- "version": "6.2.0",
3
+ "version": "7.1.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -58,18 +58,17 @@
58
58
  }
59
59
  },
60
60
  "dependencies": {
61
- "@noble/hashes": "^2.2.0",
62
- "applesauce-common": "^6.2.0",
63
- "applesauce-core": "^6.2.0",
64
- "rxjs": "^7.8.1"
61
+ "@noble/hashes": "^2.4.0",
62
+ "applesauce-common": "^7.1.0",
63
+ "applesauce-core": "^7.1.0",
64
+ "rxjs": "^7.8.2"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@hirez_io/observer-spy": "^2.2.0",
68
- "@types/debug": "^4.1.12",
69
- "applesauce-signers": "^6.2.0",
70
- "rimraf": "^6.0.1",
71
- "typescript": "^5.8.3",
72
- "vitest": "^4.0.15"
68
+ "applesauce-signers": "^7.1.0",
69
+ "rimraf": "^6.1.4",
70
+ "typescript": "^7.0.2",
71
+ "vitest": "^5.1.0"
73
72
  },
74
73
  "funding": {
75
74
  "type": "lightning",
@@ -79,7 +78,7 @@
79
78
  "prebuild": "rimraf dist",
80
79
  "build": "tsc",
81
80
  "watch:build": "tsc --watch > /dev/null",
82
- "test": "vitest run --passWithNoTests",
83
- "watch:test": "vitest"
81
+ "test": "vitest run --config ../../vitest.config.mts --dir . --passWithNoTests",
82
+ "watch:test": "vitest --config ../../vitest.config.mts --dir ."
84
83
  }
85
84
  }