applesauce-wallet-connect 7.1.0 → 7.2.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.
@@ -4,9 +4,11 @@ import { WALLET_INFO_KIND, WalletSupport } from "../helpers/support.js";
4
4
  import { TWalletMethod } from "../helpers/methods.js";
5
5
  export type WalletInfoTemplate = KnownEventTemplate<typeof WALLET_INFO_KIND>;
6
6
  export declare class WalletInfoFactory extends EventFactory<typeof WALLET_INFO_KIND, WalletInfoTemplate> {
7
- static create<Methods extends TWalletMethod>(info: WalletSupport<Methods>, client?: string, overrideRelay?: string): WalletInfoFactory;
7
+ static create<Methods extends TWalletMethod>(info: WalletSupport<Methods>, client?: string, overrideRelay?: string, state?: string): WalletInfoFactory;
8
8
  methods(methods: string[]): this;
9
9
  encryption(methods: string[]): this;
10
10
  notifications(types: string[]): this;
11
11
  client(pubkey: string, relay?: string): this;
12
+ /** Sets the state from a nostr+walletauth URI so the client can authenticate the wallet service */
13
+ state(state: string): this;
12
14
  }
@@ -3,14 +3,17 @@ import { includeSingletonTag } from "applesauce-core/operations/tags";
3
3
  import { setContent } from "applesauce-core/operations/content";
4
4
  import { WALLET_INFO_KIND } from "../helpers/support.js";
5
5
  export class WalletInfoFactory extends EventFactory {
6
- static create(info, client, overrideRelay) {
7
- const factory = new WalletInfoFactory((res) => res(blankEventTemplate(WALLET_INFO_KIND))).methods(info.methods);
6
+ static create(info, client, overrideRelay, state) {
7
+ // Factory methods return a new factory, so each optional step must be reassigned
8
+ let factory = new WalletInfoFactory((res) => res(blankEventTemplate(WALLET_INFO_KIND))).methods(info.methods);
8
9
  if (info.encryption)
9
- factory.encryption(info.encryption);
10
+ factory = factory.encryption(info.encryption);
10
11
  if (info.notifications)
11
- factory.notifications(info.notifications);
12
+ factory = factory.notifications(info.notifications);
12
13
  if (client)
13
- factory.client(client, overrideRelay);
14
+ factory = factory.client(client, overrideRelay);
15
+ if (state)
16
+ factory = factory.state(state);
14
17
  return factory;
15
18
  }
16
19
  methods(methods) {
@@ -25,4 +28,8 @@ export class WalletInfoFactory extends EventFactory {
25
28
  client(pubkey, relay) {
26
29
  return this.chain((draft) => includeSingletonTag(relay ? ["p", pubkey, relay] : ["p", pubkey])(draft));
27
30
  }
31
+ /** Sets the state from a nostr+walletauth URI so the client can authenticate the wallet service */
32
+ state(state) {
33
+ return this.chain((draft) => includeSingletonTag(["state", state])(draft));
34
+ }
28
35
  }
@@ -5,6 +5,8 @@ export interface WalletAuthURI<Methods extends TWalletMethod = CommonWalletMetho
5
5
  client: string;
6
6
  /** Required. URL of the relay where the client intends to communicate with the wallet service */
7
7
  relays: string[];
8
+ /** Random hex value the wallet service must echo in its info event so the client can authenticate it */
9
+ state?: string;
8
10
  /** The name of the client app (optional) */
9
11
  name?: string;
10
12
  /** The URL of an icon of the client app to display on the confirmation page (optional) */
@@ -20,6 +20,7 @@ export function parseWalletAuthURI(authURI) {
20
20
  if (relays.length === 0)
21
21
  throw new Error("missing required relay parameter in authorization URI");
22
22
  // Parse optional parameters
23
+ const state = searchParams.get("state") ?? undefined;
23
24
  const name = searchParams.get("name") ?? undefined;
24
25
  const icon = searchParams.get("icon") ?? undefined;
25
26
  const returnTo = searchParams.get("return_to") ?? undefined;
@@ -47,6 +48,7 @@ export function parseWalletAuthURI(authURI) {
47
48
  return {
48
49
  client,
49
50
  relays,
51
+ state,
50
52
  name,
51
53
  icon,
52
54
  returnTo,
@@ -70,6 +72,8 @@ export function createWalletAuthURI(parts) {
70
72
  for (const relay of parts.relays)
71
73
  url.searchParams.append("relay", relay);
72
74
  // Add optional parameters
75
+ if (parts.state)
76
+ url.searchParams.append("state", parts.state);
73
77
  if (parts.name)
74
78
  url.searchParams.append("name", parts.name);
75
79
  if (parts.icon)
@@ -1,6 +1,6 @@
1
1
  import { EncryptionMethod } from "applesauce-core/helpers";
2
2
  import { EventSigner } from "applesauce-core";
3
- import { NostrEvent } from "applesauce-core/helpers";
3
+ import { NostrEvent, verifyEvent } from "applesauce-core/helpers";
4
4
  import { BehaviorSubject, Observable, Subscription } from "rxjs";
5
5
  import { NotificationType, WalletAuthURI, WalletConnectEncryptionMethod, WalletConnectURI, WalletNotification, WalletNotificationEvent, WalletResponseEvent, WalletSupport } from "./helpers/index.js";
6
6
  import { CommonWalletMethods, GetBalanceMethod, GetInfoMethod, ListTransactionsMethod, LookupInvoiceMethod, MakeInvoiceMethod, MultiPayInvoiceMethod, MultiPayKeysendMethod, PayInvoiceMethod, PayKeysendMethod, Transaction, TWalletMethod } from "./helpers/methods.js";
@@ -17,6 +17,10 @@ export type WalletConnectOptions = NostrConnectionMethodsOptions & {
17
17
  timeout?: number;
18
18
  /** Whether to accept the relay hint from the wallet service */
19
19
  acceptRelayHint?: boolean;
20
+ /** The state of a pending nostr+walletauth connection (used for restoring a client waiting for the service) */
21
+ authState?: string;
22
+ /** A synchronous method that verifies event hashes and signatures, defaulting to WalletConnect.verifyEvent */
23
+ verifyEvent?: typeof verifyEvent;
20
24
  };
21
25
  export type WaitForPaidInvoice = MakeInvoiceMethod["response"]["result"] | LookupInvoiceMethod["request"]["params"];
22
26
  export type WaitForPaidOptions = {
@@ -30,6 +34,10 @@ export declare class WalletConnect<Methods extends TWalletMethod = CommonWalletM
30
34
  static publishMethod: NostrPublishMethod | undefined;
31
35
  /** A fallback pool to use if none is pass in when creating the signer */
32
36
  static pool: NostrPool | undefined;
37
+ /** The default event verifier for new instances */
38
+ static verifyEvent: typeof verifyEvent;
39
+ /** A synchronous method that verifies wallet info, response, and notification events */
40
+ verifyEvent: typeof verifyEvent;
33
41
  /** A method that is called when an event needs to be published */
34
42
  protected publishMethod: NostrPublishMethod;
35
43
  /** The active nostr subscription method */
@@ -42,6 +50,8 @@ export declare class WalletConnect<Methods extends TWalletMethod = CommonWalletM
42
50
  get relays(): string[];
43
51
  /** Whether to accept the relay hint from the wallet service */
44
52
  acceptRelayHint: boolean;
53
+ /** The random state the wallet service must echo in its info event for nostr+walletauth connections */
54
+ authState?: string;
45
55
  /** The wallet service public key ( unset if waiting for service ) */
46
56
  service$: BehaviorSubject<string | undefined>;
47
57
  get service(): string | undefined;
@@ -95,8 +105,10 @@ export declare class WalletConnect<Methods extends TWalletMethod = CommonWalletM
95
105
  * @returns a method to unsubscribe the listener
96
106
  */
97
107
  notification<T extends WalletNotification>(type: T["notification_type"], listener: (notification: T["notification"]) => any): Subscription;
98
- /** Gets the nostr+walletauth URI for the connection */
99
- getAuthURI(parts?: Omit<WalletAuthURI<Methods>, "client" | "relays">): string;
108
+ /** Gets the nostr+walletauth URI for the connection and generates the state the wallet service must echo */
109
+ getAuthURI(parts?: Omit<WalletAuthURI<Methods>, "client" | "relays" | "state">): string;
110
+ /** Checks if a wallet info event is signed and carries the state from the nostr+walletauth URI */
111
+ protected isAuthorizedServiceInfo(event: NostrEvent): boolean;
100
112
  /** Wait for the wallet service to connect */
101
113
  waitForService(abortSignal?: AbortSignal): Promise<string>;
102
114
  /** Get the wallet support info */
@@ -1,4 +1,4 @@
1
- import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
1
+ import { bytesToHex, hexToBytes, randomBytes } from "@noble/hashes/utils.js";
2
2
  import { simpleTimeout } from "applesauce-core";
3
3
  import { finalizeEvent, getPublicKey, verifyEvent } from "applesauce-core/helpers";
4
4
  import { getCachedConversationKey, nip04, nip44 } from "applesauce-core/helpers/encryption";
@@ -9,6 +9,14 @@ import { createWalletAuthURI, createWalletConnectURI, getPreferredEncryption, ge
9
9
  import { getConnectionMethods, } from "./interop.js";
10
10
  /** Node's 32-bit signed timer limit (~24.8 days); setTimeout delays beyond this overflow and clamp to ~1ms. */
11
11
  const MAX_TIMER_DELAY = 2_147_483_647;
12
+ /** Gets the relays a wallet service recommends in its info event, preferring NWC-08 relay tags over the legacy p tag hint */
13
+ function getServiceRelayHints(event) {
14
+ const relays = event.tags.filter((t) => t[0] === "relay" && t[1]).map((t) => t[1]);
15
+ if (relays.length > 0)
16
+ return relays;
17
+ const legacyRelay = event.tags.find((t) => t[0] === "p" && t[2])?.[2];
18
+ return legacyRelay ? [legacyRelay] : [];
19
+ }
12
20
  export class WalletConnect {
13
21
  /** A fallback method to use for subscriptionMethod if none is passed in when creating the client */
14
22
  static subscriptionMethod = undefined;
@@ -16,6 +24,10 @@ export class WalletConnect {
16
24
  static publishMethod = undefined;
17
25
  /** A fallback pool to use if none is pass in when creating the signer */
18
26
  static pool = undefined;
27
+ /** The default event verifier for new instances */
28
+ static verifyEvent = verifyEvent;
29
+ /** A synchronous method that verifies wallet info, response, and notification events */
30
+ verifyEvent;
19
31
  /** A method that is called when an event needs to be published */
20
32
  publishMethod;
21
33
  /** The active nostr subscription method */
@@ -30,6 +42,8 @@ export class WalletConnect {
30
42
  }
31
43
  /** Whether to accept the relay hint from the wallet service */
32
44
  acceptRelayHint;
45
+ /** The random state the wallet service must echo in its info event for nostr+walletauth connections */
46
+ authState;
33
47
  /** The wallet service public key ( unset if waiting for service ) */
34
48
  service$ = new BehaviorSubject(undefined);
35
49
  get service() {
@@ -57,8 +71,10 @@ export class WalletConnect {
57
71
  this.secret = options.secret;
58
72
  this.relays$.next(options.relays);
59
73
  this.acceptRelayHint = options.acceptRelayHint ?? true;
74
+ this.authState = options.authState;
60
75
  this.service$.next(options.service);
61
76
  this.defaultTimeout = options.timeout || 30000; // 30 second default timeout
77
+ this.verifyEvent = options.verifyEvent ?? WalletConnect.verifyEvent;
62
78
  // Create a signer for the factory
63
79
  this.signer = {
64
80
  getPublicKey: async () => getPublicKey(this.secret),
@@ -112,7 +128,9 @@ export class WalletConnect {
112
128
  share({
113
129
  resetOnRefCountZero: () => timer(60000), // Keep subscription open for 1 minute after last unsubscribe
114
130
  }));
115
- this.support$ = this.events$.pipe(filter((event) => event.kind === WALLET_INFO_KIND), map((event) => getWalletSupport(event)), share({
131
+ this.support$ = this.events$.pipe(filter((event) => event.kind === WALLET_INFO_KIND),
132
+ // Ignore unauthenticated info events seen while waiting for the service
133
+ filter((event) => event.pubkey === this.service), map((event) => getWalletSupport(event)), share({
116
134
  connector: () => new ReplaySubject(1),
117
135
  resetOnRefCountZero: () => timer(60000), // Keep info observable around for 1 minute after last unsubscribe
118
136
  }));
@@ -126,15 +144,17 @@ export class WalletConnect {
126
144
  this.events$.pipe(
127
145
  // Only listen for wallet info events
128
146
  filter((event) => event.kind === WALLET_INFO_KIND),
147
+ // Anyone can publish an info event tagging the client, so only adopt an authenticated one
148
+ filter((event) => this.isAuthorizedServiceInfo(event)),
129
149
  // Set the service to the pubkey of the wallet info event
130
150
  tap((event) => {
131
151
  // Set the service to the pubkey of the wallet info event
132
152
  this.service$.next(event.pubkey);
133
- // Switch to the relay from the service if its set
153
+ // Switch to the relays recommended by the service if they are set
134
154
  if (this.acceptRelayHint) {
135
- const relay = event.tags.find((t) => t[0] === "p" && t[2])?.[2];
136
- if (relay)
137
- this.relays$.next([relay]);
155
+ const relays = getServiceRelayHints(event);
156
+ if (relays.length > 0)
157
+ this.relays$.next(relays);
138
158
  }
139
159
  }),
140
160
  // Get the service pubkey from the event
@@ -146,7 +166,7 @@ export class WalletConnect {
146
166
  }
147
167
  /** Process response events and return WalletResponse or throw error */
148
168
  async handleResponseEvent(event, encryption) {
149
- if (!verifyEvent(event))
169
+ if (!this.verifyEvent(event))
150
170
  throw new Error("Invalid response event signature");
151
171
  const requestId = getWalletResponseRequestId(event);
152
172
  if (!requestId)
@@ -158,7 +178,7 @@ export class WalletConnect {
158
178
  }
159
179
  /** Handle notification events */
160
180
  async handleNotificationEvent(event) {
161
- if (!verifyEvent(event))
181
+ if (!this.verifyEvent(event))
162
182
  throw new Error("Invalid notification event signature");
163
183
  const notification = await unlockWalletNotification(event, this.signer);
164
184
  if (!notification)
@@ -215,9 +235,24 @@ export class WalletConnect {
215
235
  listener(notification.notification);
216
236
  });
217
237
  }
218
- /** Gets the nostr+walletauth URI for the connection */
238
+ /** Gets the nostr+walletauth URI for the connection and generates the state the wallet service must echo */
219
239
  getAuthURI(parts) {
220
- return createWalletAuthURI({ ...parts, client: getPublicKey(this.secret), relays: this.relays });
240
+ this.authState ??= bytesToHex(randomBytes(16));
241
+ return createWalletAuthURI({
242
+ ...parts,
243
+ client: getPublicKey(this.secret),
244
+ relays: this.relays,
245
+ state: this.authState,
246
+ });
247
+ }
248
+ /** Checks if a wallet info event is signed and carries the state from the nostr+walletauth URI */
249
+ isAuthorizedServiceInfo(event) {
250
+ if (!this.verifyEvent(event))
251
+ return false;
252
+ // Without a known state the URI was created elsewhere, so only the signature can be checked
253
+ if (this.authState === undefined)
254
+ return true;
255
+ return event.tags.some((t) => t[0] === "state" && t[1] === this.authState);
221
256
  }
222
257
  /** Wait for the wallet service to connect */
223
258
  async waitForService(abortSignal) {
@@ -1,4 +1,5 @@
1
1
  import { EventSigner, type Debugger } from "applesauce-core";
2
+ import { verifyEvent } from "applesauce-core/helpers/event";
2
3
  import { Observable, Subscription } from "rxjs";
3
4
  import { WalletAuthURI } from "./helpers/auth-uri.js";
4
5
  import { WalletErrorCode } from "./helpers/error.js";
@@ -34,6 +35,10 @@ export interface WalletServiceOptions<Methods extends TWalletMethod = CommonWall
34
35
  secret?: Uint8Array;
35
36
  /** The client's public key (used for restoring the service) */
36
37
  client?: string;
38
+ /** The state from the client's nostr+walletauth URI to echo in the info event */
39
+ state?: string;
40
+ /** A synchronous method that verifies request hashes and signatures, defaulting to WalletService.verifyEvent */
41
+ verifyEvent?: typeof verifyEvent;
37
42
  /** A method for getting the general wallet information (Can be overwritten if get_info is set in handlers) */
38
43
  getInfo?: () => Promise<WalletServiceInfo>;
39
44
  /** Map of method handlers */
@@ -49,6 +54,10 @@ export declare class WalletService<Methods extends TWalletMethod = CommonWalletM
49
54
  static publishMethod: NostrPublishMethod | undefined;
50
55
  /** A fallback pool to use if none is pass in when creating the signer */
51
56
  static pool: NostrPool | undefined;
57
+ /** The default event verifier for new instances */
58
+ static verifyEvent: typeof verifyEvent;
59
+ /** A synchronous method that verifies incoming request events */
60
+ verifyEvent: typeof verifyEvent;
52
61
  /** A method for subscribing to relays */
53
62
  protected readonly subscriptionMethod: NostrSubscriptionMethod;
54
63
  /** A method for publishing events */
@@ -70,6 +79,8 @@ export declare class WalletService<Methods extends TWalletMethod = CommonWalletM
70
79
  protected secret?: Uint8Array;
71
80
  /** The client's public key */
72
81
  client: string;
82
+ /** The state from the client's nostr+walletauth URI */
83
+ readonly state?: string;
73
84
  /** Shared observable for all wallet request events */
74
85
  protected events$: Observable<WalletRequestEvent> | null;
75
86
  /** Subscription to the events observable */
@@ -18,6 +18,10 @@ export class WalletService {
18
18
  static publishMethod = undefined;
19
19
  /** A fallback pool to use if none is pass in when creating the signer */
20
20
  static pool = undefined;
21
+ /** The default event verifier for new instances */
22
+ static verifyEvent = verifyEvent;
23
+ /** A synchronous method that verifies incoming request events */
24
+ verifyEvent;
21
25
  /** A method for subscribing to relays */
22
26
  subscriptionMethod;
23
27
  /** A method for publishing events */
@@ -39,6 +43,8 @@ export class WalletService {
39
43
  secret;
40
44
  /** The client's public key */
41
45
  client;
46
+ /** The state from the client's nostr+walletauth URI */
47
+ state;
42
48
  /** Shared observable for all wallet request events */
43
49
  events$ = null;
44
50
  /** Subscription to the events observable */
@@ -49,6 +55,8 @@ export class WalletService {
49
55
  this.relays = options.relays;
50
56
  this.signer = options.signer;
51
57
  this.handlers = options.handlers;
58
+ this.state = options.state;
59
+ this.verifyEvent = options.verifyEvent ?? WalletService.verifyEvent;
52
60
  // Set the client's secret and public key
53
61
  if (options.secret) {
54
62
  // Service was created with a custom secret
@@ -110,7 +118,7 @@ export class WalletService {
110
118
  // Ensure they are to our pubkey
111
119
  filter((event) => event.pubkey === this.client),
112
120
  // Verify event signature
113
- filter((event) => verifyEvent(event)),
121
+ filter((event) => this.verifyEvent(event)),
114
122
  // Only create a single subscription to the relays
115
123
  share());
116
124
  // Subscribe to request events and handle them
@@ -168,7 +176,7 @@ export class WalletService {
168
176
  try {
169
177
  // Tell the client which relay to use if there is only one (for nostr+walletauth URI connections)
170
178
  const overrideRelay = this.relays.length === 1 ? this.relays[0] : undefined;
171
- const event = await WalletInfoFactory.create(this.support, this.client, overrideRelay)
179
+ const event = await WalletInfoFactory.create(this.support, this.client, overrideRelay, this.state)
172
180
  .as(this.signer)
173
181
  .sign();
174
182
  await this.publishMethod(this.relays, event);
@@ -280,6 +288,7 @@ export class WalletService {
280
288
  return new WalletService({
281
289
  ...options,
282
290
  client: authURI.client,
291
+ state: authURI.state,
283
292
  relays,
284
293
  });
285
294
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "applesauce-wallet-connect",
3
- "version": "7.1.0",
3
+ "version": "7.2.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -65,7 +65,7 @@
65
65
  },
66
66
  "devDependencies": {
67
67
  "@hirez_io/observer-spy": "^2.2.0",
68
- "applesauce-signers": "^7.1.0",
68
+ "applesauce-signers": "^7.3.0",
69
69
  "rimraf": "^6.1.4",
70
70
  "typescript": "^7.0.2",
71
71
  "vitest": "^5.1.0"