applesauce-signers 6.2.3 → 7.0.1
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.
- package/README.md +14 -0
- package/dist/helpers/nostr-connect.d.ts +5 -1
- package/dist/helpers/nostr-connect.js +13 -0
- package/dist/signers/android-native-signer.d.ts +3 -3
- package/dist/signers/android-native-signer.js +10 -7
- package/dist/signers/nostr-connect-provider.d.ts +8 -3
- package/dist/signers/nostr-connect-provider.js +15 -4
- package/dist/signers/nostr-connect-signer.d.ts +36 -4
- package/dist/signers/nostr-connect-signer.js +134 -40
- package/dist/signers/password-signer.js +3 -3
- package/dist/signers/private-key-signer.js +3 -3
- package/dist/signers/seed-words-signer.d.ts +23 -0
- package/dist/signers/seed-words-signer.js +41 -0
- package/dist/signers/serial-port-signer.d.ts +2 -1
- package/package.json +10 -10
package/README.md
CHANGED
|
@@ -45,6 +45,20 @@ window.crypto.getRandomValues(key);
|
|
|
45
45
|
const signer = new PrivateKeySigner(key);
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
+
### Seed Words Signer (NIP-06)
|
|
49
|
+
|
|
50
|
+
Derives a private key from validated BIP-39 seed words, with the same signing and encryption methods as `PrivateKeySigner`.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { SeedWordsSigner } from "applesauce-signers/signers/seed-words-signer";
|
|
54
|
+
import { wordlist } from "@scure/bip39/wordlists/english.js";
|
|
55
|
+
|
|
56
|
+
const signer = SeedWordsSigner.fromWords(words, { wordlist, account: 0, passphrase: "" });
|
|
57
|
+
const pubkey = await signer.getPublicKey();
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The account defaults to `0` and the passphrase to an empty string. Import the required BIP-39 wordlist explicitly so unused languages stay out of the bundle.
|
|
61
|
+
|
|
48
62
|
### Nostr Connect Signer (NIP-46)
|
|
49
63
|
|
|
50
64
|
A client-side implementation for remote signing using [NIP-46](https://github.com/nostr-protocol/nips/blob/master/46.md).
|
|
@@ -23,7 +23,9 @@ export declare enum NostrConnectMethod {
|
|
|
23
23
|
Logout = "logout"
|
|
24
24
|
}
|
|
25
25
|
export type ConnectRequestParams = {
|
|
26
|
-
[NostrConnectMethod.Connect]: [
|
|
26
|
+
[NostrConnectMethod.Connect]: [
|
|
27
|
+
string
|
|
28
|
+
] | [string, string] | [string, string, string] | [string, string, string, string];
|
|
27
29
|
[NostrConnectMethod.CreateAccount]: [string, string] | [string, string, string] | [string, string, string, string];
|
|
28
30
|
[NostrConnectMethod.GetPublicKey]: [];
|
|
29
31
|
[NostrConnectMethod.SignEvent]: [string];
|
|
@@ -120,6 +122,8 @@ export type NostrConnectURI = NostrConnectURIBase & ({
|
|
|
120
122
|
export declare function parseNostrConnectURI(uri: string): NostrConnectURI;
|
|
121
123
|
/** Create a nostrconnect:// URI from a {@link NostrConnectURI} object */
|
|
122
124
|
export declare function createNostrConnectURI(data: NostrConnectURI): string;
|
|
125
|
+
/** Creates the JSON `optional_client_metadata` param for a `connect` request, or undefined if empty */
|
|
126
|
+
export declare function createConnectMetadata(metadata?: NostrConnectAppMetadata): string | undefined;
|
|
123
127
|
/** Build an array of signing permissions for event kinds */
|
|
124
128
|
export declare function buildSigningPermissions(kinds: number[]): string[];
|
|
125
129
|
export {};
|
|
@@ -129,6 +129,19 @@ export function createNostrConnectURI(data) {
|
|
|
129
129
|
params.append("relay", relay);
|
|
130
130
|
return `nostrconnect://${data.client}?` + params.toString();
|
|
131
131
|
}
|
|
132
|
+
/** Creates the JSON `optional_client_metadata` param for a `connect` request, or undefined if empty */
|
|
133
|
+
export function createConnectMetadata(metadata) {
|
|
134
|
+
if (!metadata)
|
|
135
|
+
return undefined;
|
|
136
|
+
const json = {};
|
|
137
|
+
if (metadata.name)
|
|
138
|
+
json.name = metadata.name;
|
|
139
|
+
if (metadata.url)
|
|
140
|
+
json.url = String(metadata.url);
|
|
141
|
+
if (metadata.image)
|
|
142
|
+
json.image = metadata.image;
|
|
143
|
+
return Object.keys(json).length > 0 ? JSON.stringify(json) : undefined;
|
|
144
|
+
}
|
|
132
145
|
/** Build an array of signing permissions for event kinds */
|
|
133
146
|
export function buildSigningPermissions(kinds) {
|
|
134
147
|
return [Permission.GetPublicKey, ...kinds.map((k) => `${Permission.SignEvent}:${k}`)];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventTemplate, UnsignedEvent, verifyEvent } from "applesauce-core/helpers";
|
|
2
|
-
import { Permission } from "nostr-signer
|
|
2
|
+
import { Permission } from "capacitor-plugin-nostr-signer";
|
|
3
3
|
import { ISigner } from "../interop.js";
|
|
4
4
|
export declare class AndroidNativeSigner implements ISigner {
|
|
5
5
|
packageName: string;
|
|
@@ -15,8 +15,8 @@ export declare class AndroidNativeSigner implements ISigner {
|
|
|
15
15
|
encrypt: (pubkey: string, plaintext: string) => Promise<string>;
|
|
16
16
|
decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
|
|
17
17
|
};
|
|
18
|
-
constructor(packageName: string);
|
|
19
|
-
static getSignerApps(): Promise<
|
|
18
|
+
constructor(packageName: string, pubkey?: string);
|
|
19
|
+
static getSignerApps(): Promise<AppInfo[]>;
|
|
20
20
|
setup(): Promise<void>;
|
|
21
21
|
getPublicKey(): Promise<string>;
|
|
22
22
|
signEvent(template: UnsignedEvent | EventTemplate): Promise<import("nostr-tools/core").VerifiedEvent>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getEventHash, normalizeToPubkey, npubEncode, verifyEvent, } from "applesauce-core/helpers";
|
|
2
2
|
import { nanoid } from "nanoid";
|
|
3
|
-
import { NostrSignerPlugin } from "nostr-signer
|
|
3
|
+
import { NostrSignerPlugin } from "capacitor-plugin-nostr-signer";
|
|
4
4
|
export class AndroidNativeSigner {
|
|
5
5
|
packageName;
|
|
6
6
|
connected = false;
|
|
@@ -9,8 +9,9 @@ export class AndroidNativeSigner {
|
|
|
9
9
|
verifyEvent = verifyEvent;
|
|
10
10
|
nip04;
|
|
11
11
|
nip44;
|
|
12
|
-
constructor(packageName) {
|
|
12
|
+
constructor(packageName, pubkey) {
|
|
13
13
|
this.packageName = packageName;
|
|
14
|
+
this.pubkey = pubkey ?? null;
|
|
14
15
|
this.nip04 = {
|
|
15
16
|
encrypt: this.nip04Encrypt.bind(this),
|
|
16
17
|
decrypt: this.nip04Decrypt.bind(this),
|
|
@@ -27,11 +28,13 @@ export class AndroidNativeSigner {
|
|
|
27
28
|
if (this.connected)
|
|
28
29
|
return;
|
|
29
30
|
await NostrSignerPlugin.setPackageName(this.packageName);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
if (!this.pubkey) {
|
|
32
|
+
const result = await NostrSignerPlugin.getPublicKey(this.packageName, this.permissions);
|
|
33
|
+
const pubkey = normalizeToPubkey(result.pubkey);
|
|
34
|
+
if (!pubkey)
|
|
35
|
+
throw new Error("Invalid public key");
|
|
36
|
+
this.pubkey = pubkey;
|
|
37
|
+
}
|
|
35
38
|
this.connected = true;
|
|
36
39
|
}
|
|
37
40
|
async getPublicKey() {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Debugger } from "applesauce-core";
|
|
1
2
|
import { EventTemplate, NostrEvent } from "applesauce-core/helpers/event";
|
|
2
3
|
import { Subscription } from "rxjs";
|
|
3
4
|
import { ConnectRequestParams, ConnectResponseResults, NostrConnectMethod, NostrConnectResponse, NostrConnectURI } from "../helpers/nostr-connect.js";
|
|
@@ -49,9 +50,13 @@ export declare class NostrConnectProvider implements ProviderAuthorization {
|
|
|
49
50
|
/** The active nostr subscription */
|
|
50
51
|
protected subscriptionMethod: NostrSubscriptionMethod;
|
|
51
52
|
/** Internal logger */
|
|
52
|
-
protected log:
|
|
53
|
-
/**
|
|
54
|
-
|
|
53
|
+
protected log: Debugger;
|
|
54
|
+
/** The most request ids remembered before the oldest are forgotten */
|
|
55
|
+
static MAX_SEEN: number;
|
|
56
|
+
/** The timestamps of recently seen requests by id */
|
|
57
|
+
protected seen: Map<string, number>;
|
|
58
|
+
/** Requests at or before this timestamp are treated as seen, since their ids may have been forgotten */
|
|
59
|
+
protected seenUntil: number;
|
|
55
60
|
/** The main signer for the actual signing operations */
|
|
56
61
|
upstream: ISigner;
|
|
57
62
|
/** The identity signer (provider's identity) */
|
|
@@ -21,8 +21,12 @@ export class NostrConnectProvider {
|
|
|
21
21
|
subscriptionMethod;
|
|
22
22
|
/** Internal logger */
|
|
23
23
|
log = logger.extend("NostrConnectProvider");
|
|
24
|
-
/**
|
|
25
|
-
|
|
24
|
+
/** The most request ids remembered before the oldest are forgotten */
|
|
25
|
+
static MAX_SEEN = 1000;
|
|
26
|
+
/** The timestamps of recently seen requests by id */
|
|
27
|
+
seen = new Map();
|
|
28
|
+
/** Requests at or before this timestamp are treated as seen, since their ids may have been forgotten */
|
|
29
|
+
seenUntil = 0;
|
|
26
30
|
/** The main signer for the actual signing operations */
|
|
27
31
|
upstream;
|
|
28
32
|
/** The identity signer (provider's identity) */
|
|
@@ -164,6 +168,7 @@ export class NostrConnectProvider {
|
|
|
164
168
|
this.onClientDisconnect(this.client);
|
|
165
169
|
// Forget all seen requests
|
|
166
170
|
this.seen.clear();
|
|
171
|
+
this.seenUntil = 0;
|
|
167
172
|
this.client = undefined;
|
|
168
173
|
this.connected = false;
|
|
169
174
|
this.log("Stopped");
|
|
@@ -187,9 +192,15 @@ export class NostrConnectProvider {
|
|
|
187
192
|
if (!verifyEvent(event))
|
|
188
193
|
return;
|
|
189
194
|
// Do nothing if this request has already been seen
|
|
190
|
-
if (this.seen.has(event.id))
|
|
195
|
+
if (this.seen.has(event.id) || event.created_at <= this.seenUntil)
|
|
191
196
|
return;
|
|
192
|
-
this.seen.
|
|
197
|
+
this.seen.set(event.id, event.created_at);
|
|
198
|
+
// Forget the oldest request but keep ignoring anything as old, so relays can't replay it
|
|
199
|
+
if (this.seen.size > NostrConnectProvider.MAX_SEEN) {
|
|
200
|
+
const [id, created_at] = this.seen.entries().next().value;
|
|
201
|
+
this.seen.delete(id);
|
|
202
|
+
this.seenUntil = Math.max(this.seenUntil, created_at);
|
|
203
|
+
}
|
|
193
204
|
try {
|
|
194
205
|
const content = getHiddenContent(event) ||
|
|
195
206
|
// Support legacy NIP-04 encryption
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Debugger } from "applesauce-core";
|
|
1
2
|
import { EventTemplate, NostrEvent, verifyEvent } from "applesauce-core/helpers/event";
|
|
2
3
|
import { Deferred } from "applesauce-core/promise";
|
|
3
4
|
import { ISigner, NostrConnectionMethodsOptions, NostrPool, NostrPublishMethod, NostrSubscriptionMethod, PrivateKeySigner } from "applesauce-signers";
|
|
@@ -20,6 +21,17 @@ export type NostrConnectSignerOptions = NostrConnectionMethodsOptions & {
|
|
|
20
21
|
bunkerSecret?: string;
|
|
21
22
|
/** A method for handling "auth" requests */
|
|
22
23
|
onAuth?: (url: string) => Promise<void>;
|
|
24
|
+
/** Milliseconds to wait for a response before rejecting a request (default 60s, 0 to disable) */
|
|
25
|
+
timeout?: number;
|
|
26
|
+
/** Whether to send a `switch_relays` request after connecting (default false) */
|
|
27
|
+
autoSwitchRelays?: boolean;
|
|
28
|
+
/** Client metadata sent with `connect` requests and used for the nostrconnect:// URI */
|
|
29
|
+
metadata?: NostrConnectAppMetadata;
|
|
30
|
+
};
|
|
31
|
+
/** Options for {@link NostrConnectSigner.logout} */
|
|
32
|
+
export type NostrConnectLogoutOptions = {
|
|
33
|
+
/** Milliseconds to wait for the remote signer to acknowledge before closing (defaults to the signer timeout) */
|
|
34
|
+
timeout?: number;
|
|
23
35
|
};
|
|
24
36
|
export declare class NostrConnectSigner implements ISigner {
|
|
25
37
|
/** A fallback method to use for subscriptionMethod if none is pass in when creating the signer */
|
|
@@ -32,7 +44,7 @@ export declare class NostrConnectSigner implements ISigner {
|
|
|
32
44
|
protected publishMethod: NostrPublishMethod;
|
|
33
45
|
/** The active nostr subscription */
|
|
34
46
|
protected subscriptionMethod: NostrSubscriptionMethod;
|
|
35
|
-
protected log:
|
|
47
|
+
protected log: Debugger;
|
|
36
48
|
/** The local client signer */
|
|
37
49
|
signer: PrivateKeySigner;
|
|
38
50
|
/** Whether the signer is listening for events */
|
|
@@ -49,6 +61,12 @@ export declare class NostrConnectSigner implements ISigner {
|
|
|
49
61
|
get clientPubkey(): string;
|
|
50
62
|
/** A method for handling "auth" requests */
|
|
51
63
|
onAuth: (url: string) => Promise<void>;
|
|
64
|
+
/** Milliseconds to wait for a response before rejecting a request (0 to disable) */
|
|
65
|
+
timeout: number;
|
|
66
|
+
/** Whether to send a `switch_relays` request after connecting */
|
|
67
|
+
autoSwitchRelays: boolean;
|
|
68
|
+
/** Client metadata sent with `connect` requests */
|
|
69
|
+
metadata?: NostrConnectAppMetadata;
|
|
52
70
|
verifyEvent: typeof verifyEvent;
|
|
53
71
|
/** A secret used when initiating a connection from the client side (the `secret` in a nostrconnect:// URI) */
|
|
54
72
|
connectSecret: string;
|
|
@@ -70,14 +88,23 @@ export declare class NostrConnectSigner implements ISigner {
|
|
|
70
88
|
protected req?: Subscription;
|
|
71
89
|
/** Open the connection */
|
|
72
90
|
open(): Promise<void>;
|
|
91
|
+
/** Starts the REQ subscription on the current relays */
|
|
92
|
+
protected subscribe(): Promise<void>;
|
|
73
93
|
/** Close the connection */
|
|
74
94
|
close(): Promise<void>;
|
|
75
95
|
protected requests: Map<string, Deferred<any>>;
|
|
76
96
|
protected auths: Set<string>;
|
|
97
|
+
/** Timeout timers for pending requests */
|
|
98
|
+
protected timers: Map<string, number>;
|
|
99
|
+
/** Starts or restarts the timeout for a pending request */
|
|
100
|
+
protected startRequestTimeout(id: string, method: string): void;
|
|
77
101
|
/** Call this method with incoming events */
|
|
78
102
|
handleEvent(event: NostrEvent): Promise<void>;
|
|
79
103
|
protected createRequestEvent(content: string, target?: string | undefined, kind?: number): Promise<import("nostr-tools/core").VerifiedEvent>;
|
|
104
|
+
/** Sends a request and waits for the response */
|
|
80
105
|
private makeRequest;
|
|
106
|
+
/** Publishes a request and returns the pending response without waiting for it */
|
|
107
|
+
private sendRequest;
|
|
81
108
|
/**
|
|
82
109
|
* Connect to a remote signer
|
|
83
110
|
* @param bunkerSecret - The `secret` from a `bunker://` URI used to authorize this client with the remote signer
|
|
@@ -89,8 +116,12 @@ export declare class NostrConnectSigner implements ISigner {
|
|
|
89
116
|
waitForSigner(abort?: AbortSignal): Promise<void>;
|
|
90
117
|
/** Request to create an account on the remote signer */
|
|
91
118
|
createAccount(username: string, domain: string, email?: string, permissions?: string[]): Promise<string>;
|
|
92
|
-
/** Ensure the signer is
|
|
119
|
+
/** Ensure the signer is listening for responses from the remote signer */
|
|
93
120
|
requireConnection(): Promise<void>;
|
|
121
|
+
/** The in-flight automatic `switch_relays` request */
|
|
122
|
+
protected switching: Promise<unknown> | null;
|
|
123
|
+
/** Sends a `switch_relays` request in the background if {@link autoSwitchRelays} is enabled */
|
|
124
|
+
protected startAutoSwitchRelays(): void;
|
|
94
125
|
/** Get the users pubkey */
|
|
95
126
|
getPublicKey(): Promise<string>;
|
|
96
127
|
/** Request to sign an event */
|
|
@@ -115,9 +146,9 @@ export declare class NostrConnectSigner implements ISigner {
|
|
|
115
146
|
* remote signer does not acknowledge it. The consumer is responsible for deleting any persisted
|
|
116
147
|
* client keypair.
|
|
117
148
|
*/
|
|
118
|
-
logout(): Promise<void>;
|
|
149
|
+
logout(options?: NostrConnectLogoutOptions): Promise<void>;
|
|
119
150
|
/** Returns the nostrconnect:// URI for this signer */
|
|
120
|
-
getNostrConnectURI(metadata?: NostrConnectAppMetadata): string;
|
|
151
|
+
getNostrConnectURI(metadata?: NostrConnectAppMetadata | undefined): string;
|
|
121
152
|
/** Returns the nbunksec encoded session for this signer */
|
|
122
153
|
getNbunksec(): string;
|
|
123
154
|
/** Parses a bunker:// URI */
|
|
@@ -135,6 +166,7 @@ export declare class NostrConnectSigner implements ISigner {
|
|
|
135
166
|
}): Promise<NostrConnectSigner>;
|
|
136
167
|
/** Create a {@link NostrConnectSigner} from an nbunksec encoded session */
|
|
137
168
|
static fromNbunksec(encoded: string, options?: Omit<NostrConnectSignerOptions, "relays" | "remote" | "signer" | "bunkerSecret"> & {
|
|
169
|
+
/** @deprecated permissions are only sent with the initial `connect` request, use fromBunkerURI instead */
|
|
138
170
|
permissions?: string[];
|
|
139
171
|
}): Promise<NostrConnectSigner>;
|
|
140
172
|
}
|
|
@@ -7,7 +7,7 @@ import { PrivateKeySigner, getConnectionMethods, } from "applesauce-signers";
|
|
|
7
7
|
import { nanoid } from "nanoid";
|
|
8
8
|
import { filter, from, repeat, retry } from "rxjs";
|
|
9
9
|
import { isNIP04 } from "../helpers/encryption.js";
|
|
10
|
-
import { createNbunksec, NostrConnectMethod, buildSigningPermissions, createNostrConnectURI, parseBunkerURI, parseNbunksec, } from "../helpers/nostr-connect.js";
|
|
10
|
+
import { createConnectMetadata, createNbunksec, NostrConnectMethod, buildSigningPermissions, createNostrConnectURI, parseBunkerURI, parseNbunksec, } from "../helpers/nostr-connect.js";
|
|
11
11
|
async function defaultHandleAuth(url) {
|
|
12
12
|
window.open(url, "auth", "width=400,height=600,resizable=no,status=no,location=no,toolbar=no,menubar=no");
|
|
13
13
|
}
|
|
@@ -41,6 +41,12 @@ export class NostrConnectSigner {
|
|
|
41
41
|
}
|
|
42
42
|
/** A method for handling "auth" requests */
|
|
43
43
|
onAuth = defaultHandleAuth;
|
|
44
|
+
/** Milliseconds to wait for a response before rejecting a request (0 to disable) */
|
|
45
|
+
timeout;
|
|
46
|
+
/** Whether to send a `switch_relays` request after connecting */
|
|
47
|
+
autoSwitchRelays;
|
|
48
|
+
/** Client metadata sent with `connect` requests */
|
|
49
|
+
metadata;
|
|
44
50
|
verifyEvent = verifyEvent;
|
|
45
51
|
/** A secret used when initiating a connection from the client side (the `secret` in a nostrconnect:// URI) */
|
|
46
52
|
connectSecret;
|
|
@@ -61,6 +67,9 @@ export class NostrConnectSigner {
|
|
|
61
67
|
this.remote = options.remote;
|
|
62
68
|
this.connectSecret = options.connectSecret || options.secret || nanoid(12);
|
|
63
69
|
this.bunkerSecret = options.bunkerSecret;
|
|
70
|
+
this.timeout = options.timeout ?? 60_000;
|
|
71
|
+
this.autoSwitchRelays = options.autoSwitchRelays ?? false;
|
|
72
|
+
this.metadata = options.metadata;
|
|
64
73
|
// Get the subscription and publish methods
|
|
65
74
|
const { subscriptionMethod, publishMethod } = getConnectionMethods(options, NostrConnectSigner);
|
|
66
75
|
// Use arrow functions so "this" isn't bound to the signer
|
|
@@ -86,6 +95,12 @@ export class NostrConnectSigner {
|
|
|
86
95
|
if (this.listening)
|
|
87
96
|
return;
|
|
88
97
|
this.listening = true;
|
|
98
|
+
await this.subscribe();
|
|
99
|
+
this.log("Opened", this.relays);
|
|
100
|
+
}
|
|
101
|
+
/** Starts the REQ subscription on the current relays */
|
|
102
|
+
async subscribe() {
|
|
103
|
+
this.req?.unsubscribe();
|
|
89
104
|
const pubkey = await this.signer.getPublicKey();
|
|
90
105
|
// Setup subscription
|
|
91
106
|
this.req = from(this.subscriptionMethod(this.relays, [
|
|
@@ -102,12 +117,14 @@ export class NostrConnectSigner {
|
|
|
102
117
|
// Ignore strings (support for applesauce-relay)
|
|
103
118
|
filter((event) => typeof event !== "string"))
|
|
104
119
|
.subscribe(this.handleEvent.bind(this));
|
|
105
|
-
this.log("Opened", this.relays);
|
|
106
120
|
}
|
|
107
121
|
/** Close the connection */
|
|
108
122
|
async close() {
|
|
109
|
-
this.listening = false;
|
|
110
123
|
this.isConnected = false;
|
|
124
|
+
// Already closed, nothing to clean up
|
|
125
|
+
if (!this.listening)
|
|
126
|
+
return;
|
|
127
|
+
this.listening = false;
|
|
111
128
|
// Close the current subscription
|
|
112
129
|
if (this.req) {
|
|
113
130
|
this.req.unsubscribe();
|
|
@@ -118,17 +135,31 @@ export class NostrConnectSigner {
|
|
|
118
135
|
this.waitingPromise.reject(new Error("Closed"));
|
|
119
136
|
this.waitingPromise = null;
|
|
120
137
|
}
|
|
138
|
+
// Reject pending requests since their responses can no longer be received
|
|
139
|
+
for (const request of this.requests.values())
|
|
140
|
+
request.reject(new Error("Closed"));
|
|
121
141
|
this.log("Closed");
|
|
122
142
|
}
|
|
123
143
|
requests = new Map();
|
|
124
144
|
auths = new Set();
|
|
145
|
+
/** Timeout timers for pending requests */
|
|
146
|
+
timers = new Map();
|
|
147
|
+
/** Starts or restarts the timeout for a pending request */
|
|
148
|
+
startRequestTimeout(id, method) {
|
|
149
|
+
clearTimeout(this.timers.get(id));
|
|
150
|
+
if (!this.timeout)
|
|
151
|
+
return;
|
|
152
|
+
this.timers.set(id, setTimeout(() => {
|
|
153
|
+
this.requests.get(id)?.reject(new Error(`Remote signer did not respond to ${method} request`));
|
|
154
|
+
}, this.timeout));
|
|
155
|
+
}
|
|
125
156
|
/** Call this method with incoming events */
|
|
126
157
|
async handleEvent(event) {
|
|
127
|
-
if (!this.verifyEvent(event))
|
|
128
|
-
return;
|
|
129
158
|
// ignore the event if its not from the remote signer
|
|
130
159
|
if (this.remote && event.pubkey !== this.remote)
|
|
131
160
|
return;
|
|
161
|
+
if (!this.verifyEvent(event))
|
|
162
|
+
return;
|
|
132
163
|
try {
|
|
133
164
|
const responseStr = getHiddenContent(event) ??
|
|
134
165
|
(isNIP04(event.content)
|
|
@@ -137,14 +168,17 @@ export class NostrConnectSigner {
|
|
|
137
168
|
if (!responseStr)
|
|
138
169
|
return;
|
|
139
170
|
const response = JSON.parse(responseStr);
|
|
140
|
-
//
|
|
141
|
-
if (!this.remote
|
|
142
|
-
|
|
143
|
-
|
|
171
|
+
// Handle the remote signer connecting from a nostrconnect:// URI
|
|
172
|
+
if (!this.remote) {
|
|
173
|
+
// The secret must be validated to prevent connection spoofing, so "ack" is not accepted here
|
|
174
|
+
if (response.error || response.result !== this.connectSecret)
|
|
175
|
+
return;
|
|
176
|
+
this.log("Got connect response from", event.pubkey);
|
|
144
177
|
this.isConnected = true;
|
|
145
178
|
this.remote = event.pubkey;
|
|
146
179
|
this.waitingPromise?.resolve();
|
|
147
180
|
this.waitingPromise = null;
|
|
181
|
+
this.startAutoSwitchRelays();
|
|
148
182
|
return;
|
|
149
183
|
}
|
|
150
184
|
if (response.id) {
|
|
@@ -156,6 +190,8 @@ export class NostrConnectSigner {
|
|
|
156
190
|
if (response.result === "auth_url") {
|
|
157
191
|
if (!this.auths.has(response.id)) {
|
|
158
192
|
this.auths.add(response.id);
|
|
193
|
+
// Give the user time to authenticate before timing out
|
|
194
|
+
this.startRequestTimeout(response.id, "auth");
|
|
159
195
|
if (this.onAuth) {
|
|
160
196
|
try {
|
|
161
197
|
await this.onAuth(response.error);
|
|
@@ -187,7 +223,13 @@ export class NostrConnectSigner {
|
|
|
187
223
|
content,
|
|
188
224
|
});
|
|
189
225
|
}
|
|
226
|
+
/** Sends a request and waits for the response */
|
|
190
227
|
async makeRequest(method, params, kind = kinds.NostrConnect) {
|
|
228
|
+
const { response } = await this.sendRequest(method, params, kind);
|
|
229
|
+
return response;
|
|
230
|
+
}
|
|
231
|
+
/** Publishes a request and returns the pending response without waiting for it */
|
|
232
|
+
async sendRequest(method, params, kind = kinds.NostrConnect) {
|
|
191
233
|
// Talk to the remote signer or the users pubkey
|
|
192
234
|
if (!this.remote)
|
|
193
235
|
throw new Error("Missing remote signer pubkey");
|
|
@@ -198,14 +240,26 @@ export class NostrConnectSigner {
|
|
|
198
240
|
this.log(`Sending ${id} (${method}) ${JSON.stringify(params)}`);
|
|
199
241
|
const p = createDefer();
|
|
200
242
|
this.requests.set(id, p);
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
243
|
+
// Cleanup when the request is resolved, rejected, or timed out
|
|
244
|
+
const cleanup = () => {
|
|
245
|
+
this.requests.delete(id);
|
|
246
|
+
this.auths.delete(id);
|
|
247
|
+
clearTimeout(this.timers.get(id));
|
|
248
|
+
this.timers.delete(id);
|
|
249
|
+
};
|
|
250
|
+
p.then(cleanup, cleanup);
|
|
251
|
+
this.startRequestTimeout(id, method);
|
|
252
|
+
try {
|
|
253
|
+
// Handle returned Promise or Observable
|
|
254
|
+
const result = this.publishMethod(this.relays, event);
|
|
255
|
+
await new Promise((res, rej) => from(result).subscribe({ complete: res, error: rej }));
|
|
256
|
+
this.log(`Sent ${id} (${method})`);
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
p.reject(error);
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
return { response: p };
|
|
209
263
|
}
|
|
210
264
|
/**
|
|
211
265
|
* Connect to a remote signer
|
|
@@ -222,12 +276,12 @@ export class NostrConnectSigner {
|
|
|
222
276
|
try {
|
|
223
277
|
if (bunkerSecret !== undefined)
|
|
224
278
|
this.bunkerSecret = bunkerSecret;
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
]);
|
|
279
|
+
const metadata = createConnectMetadata(this.metadata);
|
|
280
|
+
const secret = this.bunkerSecret || "";
|
|
281
|
+
const perms = permissions?.join(",") ?? "";
|
|
282
|
+
const result = await this.makeRequest(NostrConnectMethod.Connect, metadata ? [this.remote, secret, perms, metadata] : [this.remote, secret, perms]);
|
|
230
283
|
this.isConnected = true;
|
|
284
|
+
this.startAutoSwitchRelays();
|
|
231
285
|
return result;
|
|
232
286
|
}
|
|
233
287
|
catch (e) {
|
|
@@ -242,13 +296,20 @@ export class NostrConnectSigner {
|
|
|
242
296
|
if (this.isConnected)
|
|
243
297
|
return Promise.resolve();
|
|
244
298
|
this.open();
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
299
|
+
const p = createDefer();
|
|
300
|
+
this.waitingPromise = p;
|
|
301
|
+
const onAbort = () => {
|
|
302
|
+
if (this.waitingPromise !== p)
|
|
303
|
+
return;
|
|
248
304
|
this.waitingPromise = null;
|
|
305
|
+
p.reject(new Error("Aborted"));
|
|
249
306
|
this.close();
|
|
250
|
-
}
|
|
251
|
-
|
|
307
|
+
};
|
|
308
|
+
abort?.addEventListener("abort", onAbort, true);
|
|
309
|
+
// Remove the listener once settled so a later abort can't close a connected signer
|
|
310
|
+
const cleanup = () => abort?.removeEventListener("abort", onAbort, true);
|
|
311
|
+
p.then(cleanup, cleanup);
|
|
312
|
+
return p;
|
|
252
313
|
}
|
|
253
314
|
/** Request to create an account on the remote signer */
|
|
254
315
|
async createAccount(username, domain, email, permissions) {
|
|
@@ -273,10 +334,32 @@ export class NostrConnectSigner {
|
|
|
273
334
|
throw e;
|
|
274
335
|
}
|
|
275
336
|
}
|
|
276
|
-
/** Ensure the signer is
|
|
337
|
+
/** Ensure the signer is listening for responses from the remote signer */
|
|
277
338
|
async requireConnection() {
|
|
278
|
-
|
|
279
|
-
|
|
339
|
+
// Wait for an in-flight relay switch so requests are sent on the new relays
|
|
340
|
+
if (this.switching)
|
|
341
|
+
await this.switching;
|
|
342
|
+
if (this.isConnected && this.listening)
|
|
343
|
+
return;
|
|
344
|
+
// Fallback for legacy sessions where the remote signer used the users key
|
|
345
|
+
if (!this.remote && this.pubkey)
|
|
346
|
+
this.remote = this.pubkey;
|
|
347
|
+
if (!this.remote)
|
|
348
|
+
throw new Error("Not connected to a remote signer");
|
|
349
|
+
// Sessions are keyed by the client pubkey, so an established session only needs to listen again.
|
|
350
|
+
// Re-sending `connect` would reuse a secret that remote signers are expected to ignore
|
|
351
|
+
await this.open();
|
|
352
|
+
this.isConnected = true;
|
|
353
|
+
}
|
|
354
|
+
/** The in-flight automatic `switch_relays` request */
|
|
355
|
+
switching = null;
|
|
356
|
+
/** Sends a `switch_relays` request in the background if {@link autoSwitchRelays} is enabled */
|
|
357
|
+
startAutoSwitchRelays() {
|
|
358
|
+
if (!this.autoSwitchRelays || this.switching)
|
|
359
|
+
return;
|
|
360
|
+
this.switching = this.switchRelays()
|
|
361
|
+
.catch((error) => this.log("Failed to switch relays", error))
|
|
362
|
+
.finally(() => (this.switching = null));
|
|
280
363
|
}
|
|
281
364
|
/** Get the users pubkey */
|
|
282
365
|
async getPublicKey() {
|
|
@@ -286,6 +369,7 @@ export class NostrConnectSigner {
|
|
|
286
369
|
const key = await this.makeRequest(NostrConnectMethod.GetPublicKey, []);
|
|
287
370
|
if (!isHexKey(key))
|
|
288
371
|
throw new Error("Remote signer returned an invalid public key");
|
|
372
|
+
this.pubkey = key;
|
|
289
373
|
return key;
|
|
290
374
|
}
|
|
291
375
|
/** Request to sign an event */
|
|
@@ -333,7 +417,8 @@ export class NostrConnectSigner {
|
|
|
333
417
|
* @returns An array of relay URLs if the signer wants to switch relays, or null if no change
|
|
334
418
|
*/
|
|
335
419
|
async switchRelays() {
|
|
336
|
-
|
|
420
|
+
if (!this.isConnected || !this.listening)
|
|
421
|
+
await this.requireConnection();
|
|
337
422
|
const response = await this.makeRequest(NostrConnectMethod.SwitchRelays, []);
|
|
338
423
|
// NIP-46 results are strings, so the relay list arrives JSON-stringified
|
|
339
424
|
let result = null;
|
|
@@ -348,10 +433,8 @@ export class NostrConnectSigner {
|
|
|
348
433
|
this.log("Switching relays from", this.relays, "to", result);
|
|
349
434
|
this.relays = result;
|
|
350
435
|
// Restart subscription with new relays
|
|
351
|
-
if (this.listening)
|
|
352
|
-
await this.
|
|
353
|
-
await this.open();
|
|
354
|
-
}
|
|
436
|
+
if (this.listening)
|
|
437
|
+
await this.subscribe();
|
|
355
438
|
}
|
|
356
439
|
return result;
|
|
357
440
|
}
|
|
@@ -362,21 +445,31 @@ export class NostrConnectSigner {
|
|
|
362
445
|
* remote signer does not acknowledge it. The consumer is responsible for deleting any persisted
|
|
363
446
|
* client keypair.
|
|
364
447
|
*/
|
|
365
|
-
async logout() {
|
|
448
|
+
async logout(options) {
|
|
449
|
+
const timeout = options?.timeout ?? this.timeout;
|
|
450
|
+
let timer;
|
|
366
451
|
try {
|
|
367
|
-
if (this.isConnected && this.remote)
|
|
368
|
-
await this.
|
|
452
|
+
if (this.isConnected && this.remote) {
|
|
453
|
+
const { response } = await this.sendRequest(NostrConnectMethod.Logout, []);
|
|
454
|
+
// Wait for the acknowledgement, but give up after the timeout since it's only a courtesy
|
|
455
|
+
const timedOut = new Promise((res) => {
|
|
456
|
+
if (timeout)
|
|
457
|
+
timer = setTimeout(res, timeout);
|
|
458
|
+
});
|
|
459
|
+
await Promise.race([response, timedOut]);
|
|
460
|
+
}
|
|
369
461
|
}
|
|
370
462
|
catch (error) {
|
|
371
463
|
this.log("Failed to send logout request", error);
|
|
372
464
|
}
|
|
373
465
|
finally {
|
|
466
|
+
clearTimeout(timer);
|
|
374
467
|
this.isConnected = false;
|
|
375
468
|
await this.close();
|
|
376
469
|
}
|
|
377
470
|
}
|
|
378
471
|
/** Returns the nostrconnect:// URI for this signer */
|
|
379
|
-
getNostrConnectURI(metadata) {
|
|
472
|
+
getNostrConnectURI(metadata = this.metadata) {
|
|
380
473
|
return createNostrConnectURI({
|
|
381
474
|
client: getPublicKey(this.signer.key),
|
|
382
475
|
connectSecret: this.connectSecret,
|
|
@@ -428,7 +521,8 @@ export class NostrConnectSigner {
|
|
|
428
521
|
bunkerSecret,
|
|
429
522
|
...options,
|
|
430
523
|
});
|
|
431
|
-
|
|
524
|
+
// The session already exists, so resume listening without re-sending `connect`
|
|
525
|
+
await client.requireConnection();
|
|
432
526
|
return client;
|
|
433
527
|
}
|
|
434
528
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { normalizeToSecretKey } from "applesauce-core/helpers";
|
|
2
|
-
import { nip04, nip44 } from "applesauce-core/helpers/encryption";
|
|
2
|
+
import { getCachedConversationKey, nip04, nip44 } from "applesauce-core/helpers/encryption";
|
|
3
3
|
import { finalizeEvent } from "applesauce-core/helpers/event";
|
|
4
4
|
import { decryptSecretKey, encryptSecretKey, getPublicKey } from "applesauce-core/helpers/keys";
|
|
5
5
|
import { createDefer } from "applesauce-core/promise";
|
|
@@ -90,11 +90,11 @@ export class PasswordSigner {
|
|
|
90
90
|
// NIP-44
|
|
91
91
|
async nip44Encrypt(pubkey, plaintext) {
|
|
92
92
|
await this.requestUnlock();
|
|
93
|
-
return nip44.v2.encrypt(plaintext,
|
|
93
|
+
return nip44.v2.encrypt(plaintext, getCachedConversationKey(this.key, pubkey));
|
|
94
94
|
}
|
|
95
95
|
async nip44Decrypt(pubkey, ciphertext) {
|
|
96
96
|
await this.requestUnlock();
|
|
97
|
-
return nip44.v2.decrypt(ciphertext,
|
|
97
|
+
return nip44.v2.decrypt(ciphertext, getCachedConversationKey(this.key, pubkey));
|
|
98
98
|
}
|
|
99
99
|
/** Creates a PasswordSigner from a hex private key or NIP-19 nsec and password */
|
|
100
100
|
static async fromPrivateKey(privateKey, password) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { finalizeEvent, normalizeToSecretKey } from "applesauce-core/helpers";
|
|
2
|
-
import { nip04, nip44 } from "applesauce-core/helpers/encryption";
|
|
2
|
+
import { getCachedConversationKey, nip04, nip44 } from "applesauce-core/helpers/encryption";
|
|
3
3
|
import { generateSecretKey, getPublicKey } from "applesauce-core/helpers/keys";
|
|
4
4
|
/** A Simple signer that holds the private key in memory */
|
|
5
5
|
export class PrivateKeySigner {
|
|
@@ -18,8 +18,8 @@ export class PrivateKeySigner {
|
|
|
18
18
|
decrypt: async (pubkey, ciphertext) => nip04.decrypt(this.key, pubkey, ciphertext),
|
|
19
19
|
};
|
|
20
20
|
nip44 = {
|
|
21
|
-
encrypt: async (pubkey, plaintext) => nip44.v2.encrypt(plaintext,
|
|
22
|
-
decrypt: async (pubkey, ciphertext) => nip44.v2.decrypt(ciphertext,
|
|
21
|
+
encrypt: async (pubkey, plaintext) => nip44.v2.encrypt(plaintext, getCachedConversationKey(this.key, pubkey)),
|
|
22
|
+
decrypt: async (pubkey, ciphertext) => nip44.v2.decrypt(ciphertext, getCachedConversationKey(this.key, pubkey)),
|
|
23
23
|
};
|
|
24
24
|
/** Creates a PrivateKeySigner from a hex private key or NIP-19 nsec */
|
|
25
25
|
static fromKey(privateKey) {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { PrivateKeySigner } from "./private-key-signer.js";
|
|
2
|
+
/** Options for deriving a signer from BIP-39 seed words */
|
|
3
|
+
export interface SeedWordsSignerOptions {
|
|
4
|
+
/** The NIP-06 account index, default 0 */
|
|
5
|
+
account?: number;
|
|
6
|
+
/** The BIP-39 passphrase, default empty */
|
|
7
|
+
passphrase?: string;
|
|
8
|
+
/** The BIP-39 wordlist used to validate the seed words; import only the language needed */
|
|
9
|
+
wordlist: string[];
|
|
10
|
+
}
|
|
11
|
+
/** A private key signer derived from BIP-39 seed words using NIP-06 */
|
|
12
|
+
export declare class SeedWordsSigner extends PrivateKeySigner {
|
|
13
|
+
/**
|
|
14
|
+
* Creates a SeedWordsSigner from a hex private key or NIP-19 nsec
|
|
15
|
+
* @throws If the private key is invalid
|
|
16
|
+
*/
|
|
17
|
+
static fromKey(privateKey: Uint8Array | string): SeedWordsSigner;
|
|
18
|
+
/**
|
|
19
|
+
* Creates a signer from validated seed words
|
|
20
|
+
* @throws If the mnemonic is invalid, the account is outside 0–2147483647, or key derivation fails
|
|
21
|
+
*/
|
|
22
|
+
static fromWords(words: string, options: SeedWordsSignerOptions): SeedWordsSigner;
|
|
23
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { HDKey } from "@scure/bip32";
|
|
2
|
+
import { mnemonicToSeedSync, validateMnemonic } from "@scure/bip39";
|
|
3
|
+
import { PrivateKeySigner } from "./private-key-signer.js";
|
|
4
|
+
/** A private key signer derived from BIP-39 seed words using NIP-06 */
|
|
5
|
+
export class SeedWordsSigner extends PrivateKeySigner {
|
|
6
|
+
/**
|
|
7
|
+
* Creates a SeedWordsSigner from a hex private key or NIP-19 nsec
|
|
8
|
+
* @throws If the private key is invalid
|
|
9
|
+
*/
|
|
10
|
+
static fromKey(privateKey) {
|
|
11
|
+
return new SeedWordsSigner(PrivateKeySigner.fromKey(privateKey).key);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Creates a signer from validated seed words
|
|
15
|
+
* @throws If the mnemonic is invalid, the account is outside 0–2147483647, or key derivation fails
|
|
16
|
+
*/
|
|
17
|
+
static fromWords(words, options) {
|
|
18
|
+
const { account = 0, passphrase, wordlist } = options;
|
|
19
|
+
if (!Number.isInteger(account) || account < 0 || account >= 0x80000000)
|
|
20
|
+
throw new Error("Invalid account index");
|
|
21
|
+
if (!validateMnemonic(words, wordlist))
|
|
22
|
+
throw new Error("Invalid mnemonic");
|
|
23
|
+
const seed = mnemonicToSeedSync(words, passphrase);
|
|
24
|
+
const root = HDKey.fromMasterSeed(seed);
|
|
25
|
+
try {
|
|
26
|
+
const child = root.derive(`m/44'/1237'/${account}'/0/0`);
|
|
27
|
+
try {
|
|
28
|
+
if (!child.privateKey)
|
|
29
|
+
throw new Error("Could not derive private key");
|
|
30
|
+
return new SeedWordsSigner(new Uint8Array(child.privateKey));
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
child.wipePrivateData();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
seed.fill(0);
|
|
38
|
+
root.wipePrivateData();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Debugger } from "applesauce-core";
|
|
1
2
|
import { EventTemplate, verifyEvent } from "applesauce-core/helpers/event";
|
|
2
3
|
import { Deferred } from "applesauce-core/promise";
|
|
3
4
|
import { ISigner } from "../interop.js";
|
|
@@ -10,7 +11,7 @@ type DeviceOpts = {
|
|
|
10
11
|
};
|
|
11
12
|
/** A signer that works with [nostr-signing-device](https://github.com/lnbits/nostr-signing-device) */
|
|
12
13
|
export declare class SerialPortSigner implements ISigner {
|
|
13
|
-
protected log:
|
|
14
|
+
protected log: Debugger;
|
|
14
15
|
protected writer: WritableStreamDefaultWriter<string> | null;
|
|
15
16
|
pubkey?: string;
|
|
16
17
|
get isConnected(): boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "applesauce-signers",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "7.0.1",
|
|
4
4
|
"description": "Signer classes for applesauce",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -46,26 +46,26 @@
|
|
|
46
46
|
"dependencies": {
|
|
47
47
|
"@noble/secp256k1": "^3.1.0",
|
|
48
48
|
"@scure/base": "^2.2.0",
|
|
49
|
-
"
|
|
50
|
-
"
|
|
49
|
+
"@scure/bip32": "^2.4.0",
|
|
50
|
+
"@scure/bip39": "^2.0.1",
|
|
51
|
+
"applesauce-core": "^7.0.0",
|
|
51
52
|
"nanoid": "^5.0.9",
|
|
52
53
|
"rxjs": "^7.8.2"
|
|
53
54
|
},
|
|
54
55
|
"devDependencies": {
|
|
55
|
-
"@types/debug": "^4.1.12",
|
|
56
56
|
"@types/dom-serial": "^1.0.6",
|
|
57
|
-
"rimraf": "^6.
|
|
58
|
-
"typescript": "^
|
|
59
|
-
"vitest": "^4.
|
|
57
|
+
"rimraf": "^6.1.3",
|
|
58
|
+
"typescript": "^7.0.2",
|
|
59
|
+
"vitest": "^4.1.11",
|
|
60
60
|
"vitest-websocket-mock": "^0.5.0"
|
|
61
61
|
},
|
|
62
|
-
"optionalDependencies": {
|
|
63
|
-
"nostr-signer-capacitor-plugin": "^0.0.5"
|
|
64
|
-
},
|
|
65
62
|
"funding": {
|
|
66
63
|
"type": "lightning",
|
|
67
64
|
"url": "lightning:nostrudel@geyser.fund"
|
|
68
65
|
},
|
|
66
|
+
"optionalDependencies": {
|
|
67
|
+
"capacitor-plugin-nostr-signer": "^0.2.0"
|
|
68
|
+
},
|
|
69
69
|
"scripts": {
|
|
70
70
|
"prebuild": "rimraf dist",
|
|
71
71
|
"build": "tsc",
|