@nostrify/nostrify 0.50.5 → 0.51.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,32 +1,36 @@
1
-
2
- > @nostrify/nostrify@0.50.5 build /home/alex/Projects/nostrify/packages/nostrify
3
- > npx tsc -p tsconfig.json && node ../../esbuild.config.js --package ./
4
-
5
- npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
6
- npm warn Unknown env config "_jsr-registry". This will stop working in the next major version of npm.
7
- Building with esbuild...
8
-
9
- dist/NRelay1.js 10.7kb
10
- dist/NSchema.js 8.2kb
11
- dist/NPool.js 6.0kb
12
- dist/test/TestRelayServer.js 4.7kb
13
- dist/NSet.js 4.1kb
14
- dist/NConnectSigner.js 3.9kb
15
- dist/NBrowserSigner.js 3.9kb
16
- dist/ln/LNURL.js 3.3kb
17
- dist/NIP98.js 2.7kb
18
- dist/uploaders/BlossomUploader.js 2.3kb
19
- dist/uploaders/NostrBuildUploader.js 1.9kb
20
- dist/test/MockRelay.js 1.4kb
21
- dist/BunkerURI.js 1.4kb
22
- dist/NKinds.js 1.1kb
23
- dist/utils/getFilterLimit.js 1.1kb
24
- dist/NIP05.js 1.1kb
25
- dist/NSecSigner.js 1.1kb
26
- dist/utils/Machina.js 925b
27
- dist/NCache.js 828b
28
- dist/mod.js 815b
29
- ...and 12 more output files...
30
-
31
- Done in 24ms
32
- Done!
1
+
2
+
3
+ > @nostrify/nostrify@0.51.0 build /home/alex/Projects/nostrify/packages/nostrify
4
+ > npx tsc -p tsconfig.json && node ../../esbuild.config.js --package ./
5
+
6
+ npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
7
+ npm warn Unknown env config "_jsr-registry". This will stop working in the next major version of npm.
8
+ ⠙Building with esbuild...
9
+
10
+ dist/NRelay1.js 12.8kb
11
+ dist/NSchema.js 8.2kb
12
+ dist/NPool.js 6.0kb
13
+ dist/test/TestRelayServer.js 4.7kb
14
+ dist/NSet.js 4.1kb
15
+ dist/NConnectSigner.js 3.9kb
16
+ dist/NBrowserSigner.js 3.9kb
17
+ dist/ln/LNURL.js 3.3kb
18
+ dist/NIP98.js 2.7kb
19
+ dist/uploaders/BlossomUploader.js 2.3kb
20
+ dist/uploaders/NostrBuildUploader.js 1.9kb
21
+ dist/test/MockRelay.js 1.4kb
22
+ dist/BunkerURI.js 1.4kb
23
+ dist/NKinds.js 1.1kb
24
+ dist/utils/getFilterLimit.js 1.1kb
25
+ dist/NIP05.js 1.1kb
26
+ dist/NSecSigner.js 1.1kb
27
+ dist/utils/Machina.js 925b 
28
+ dist/NCache.js 828b 
29
+ dist/mod.js 815b 
30
+ dist/test/mod.js 701b 
31
+ dist/NIP98Client.js 664b 
32
+ dist/test/ErrorRelay.js 557b 
33
+ ...and 9 more output files...
34
+
35
+ ⚡ Done in 22ms
36
+ Done!
@@ -1,111 +1,130 @@
1
1
 
2
- > @nostrify/nostrify@0.50.4 test /home/alex/Projects/nostrify/packages/nostrify
2
+ > @nostrify/nostrify@0.50.5 test /home/alex/Projects/nostrify/packages/nostrify
3
3
  > node --test "**/*.test.ts"
4
4
 
5
- ✔ BunkerURI (4.746225ms)
6
- ✔ BunkerURI.fromJSON (2.258631ms)
7
- ✔ NBrowserSigner - without extension (408.083868ms)
8
- ✔ NBrowserSigner - with extension polyfill (210.998188ms)
9
- ✔ NBrowserSigner.nip44 - with extension polyfill (69.247265ms)
10
- ✔ NBrowserSigner.nip04 - with extension polyfill (35.341396ms)
11
- ✔ NBrowserSigner.getRelays - with extension polyfill (2.962389ms)
12
- ✔ NBrowserSigner - missing nip44 support (1.052295ms)
13
- ✔ NBrowserSigner - missing nip04 support (1.702803ms)
14
- ✔ NBrowserSigner - feature detection (1.125042ms)
15
- ✔ NBrowserSigner - extension appears after delay (303.472084ms)
16
- ✔ NBrowserSigner - nip44 works when extension appears after delay (324.400107ms)
17
- ✔ NCache (9.658392ms)
18
- ✔ NConnectSigner.signEvent with nip04 encryption (391.774809ms)
19
- ✔ NConnectSigner.signEvent with nip44 encryption (207.494929ms)
20
- ✔ NIP05.lookup (133.058123ms)
21
- ✔ NIP05.lookup with invalid values but valid profile pointer (14.302013ms)
22
- ✔ NIP05.lookup with invalid document (23.813217ms)
23
- ✔ NIP50.parseInput (8.291733ms)
24
- ✔ NIP50.parseInput with negated token (3.697095ms)
25
- ✔ NIP98.template (11.10432ms)
26
- ✔ NIP98.template with payload (49.424727ms)
27
- ✔ NIP98.verify (196.555049ms)
28
- ✔ NIP98.verify fails with missing header (3.038283ms)
29
- ✔ NIP98.verify fails with missing token (2.190563ms)
30
- ✔ NIP98.verify fails with invalid token (2.09342ms)
31
- ✔ NIP98.verify fails with invalid event (83.997252ms)
32
- ✔ NIP98.verify fails with wrong event kind (41.704081ms)
33
- ✔ NIP98.verify fails with wrong request URL (72.762617ms)
34
- ✔ NIP98.verify fails with wrong request method (48.279566ms)
35
- ✔ NIP98.verify fails with expired event (33.173366ms)
36
- ✔ NIP98.verify fails with invalid payload (49.772463ms)
37
- ✔ NIP98Client.fetch - basic GET request (194.533194ms)
38
- ✔ NIP98Client.fetch - POST request with body (108.697493ms)
39
- ✔ NIP98Client.fetch - with Request object input (38.584365ms)
40
- ✔ NIP98Client.fetch - with URL object input (23.447316ms)
41
- ✔ NIP98Client.fetch - uses default fetch when not provided (14.447727ms)
42
- ✔ NIP98Client.fetch - preserves existing headers (11.962379ms)
43
- ✔ NIP98Client.fetch - event can be verified with NIP98.verify (42.905196ms)
44
- ✔ NIP98Client.fetch - handles different HTTP methods (125.16977ms)
45
- ✔ NKinds (2.69246ms)
46
- ✔ NPool.query (672.497853ms)
47
- ✔ NPool.req (192.651524ms)
48
- ✔ NPool.event (135.901938ms)
49
- ✔ NPool.query with eoseTimeout (674.863957ms)
50
- ✔ NPool.query with eoseTimeout disabled (538.297274ms)
51
- ✔ NRelay1.query (489.184286ms)
52
- ✔ NRelay1.query with NIP-50 search preserves relay order (116.873749ms)
53
- ✔ NRelay1.query mismatched filter (61.927786ms)
54
- ✔ NRelay1.req (181.155305ms)
55
- ✔ NRelay1.event (39.385065ms)
56
- NRelay1 backoff (0.638474ms) # SKIP
5
+ ✔ BunkerURI (4.028694ms)
6
+ ✔ BunkerURI.fromJSON (1.194504ms)
7
+ ✔ NBrowserSigner - without extension (408.101823ms)
8
+ ✔ NBrowserSigner - with extension polyfill (177.58652ms)
9
+ ✔ NBrowserSigner.nip44 - with extension polyfill (53.432633ms)
10
+ ✔ NBrowserSigner.nip04 - with extension polyfill (31.318082ms)
11
+ ✔ NBrowserSigner.getRelays - with extension polyfill (3.337439ms)
12
+ ✔ NBrowserSigner - missing nip44 support (1.117529ms)
13
+ ✔ NBrowserSigner - missing nip04 support (1.643893ms)
14
+ ✔ NBrowserSigner - feature detection (1.047697ms)
15
+ ✔ NBrowserSigner - extension appears after delay (306.657599ms)
16
+ ✔ NBrowserSigner - nip44 works when extension appears after delay (336.700014ms)
17
+ ✔ NCache (32.945945ms)
18
+ ✔ NConnectSigner.signEvent with nip04 encryption (509.267873ms)
19
+ ✔ NConnectSigner.signEvent with nip44 encryption (111.33369ms)
20
+ ✔ NIP05.lookup (154.653466ms)
21
+ ✔ NIP05.lookup with invalid values but valid profile pointer (12.873408ms)
22
+ ✔ NIP05.lookup with invalid document (16.375048ms)
23
+ ✔ NIP50.parseInput (12.96974ms)
24
+ ✔ NIP50.parseInput with negated token (0.650367ms)
25
+ ✔ NIP98.template (17.834683ms)
26
+ ✔ NIP98.template with payload (52.701182ms)
27
+ ✔ NIP98.verify (228.10839ms)
28
+ ✔ NIP98.verify fails with missing header (6.332332ms)
29
+ ✔ NIP98.verify fails with missing token (2.281917ms)
30
+ ✔ NIP98.verify fails with invalid token (2.654441ms)
31
+ ✔ NIP98.verify fails with invalid event (31.769946ms)
32
+ ✔ NIP98.verify fails with wrong event kind (76.829174ms)
33
+ ✔ NIP98.verify fails with wrong request URL (28.079039ms)
34
+ ✔ NIP98.verify fails with wrong request method (26.629332ms)
35
+ ✔ NIP98.verify fails with expired event (23.384448ms)
36
+ ✔ NIP98.verify fails with invalid payload (43.967678ms)
37
+ ✔ NIP98Client.fetch - basic GET request (355.876029ms)
38
+ ✔ NIP98Client.fetch - POST request with body (162.747693ms)
39
+ ✔ NIP98Client.fetch - with Request object input (78.965075ms)
40
+ ✔ NIP98Client.fetch - with URL object input (46.142403ms)
41
+ ✔ NIP98Client.fetch - uses default fetch when not provided (56.968837ms)
42
+ ✔ NIP98Client.fetch - preserves existing headers (38.948264ms)
43
+ ✔ NIP98Client.fetch - event can be verified with NIP98.verify (44.201489ms)
44
+ ✔ NIP98Client.fetch - handles different HTTP methods (150.07877ms)
45
+ ✔ NKinds (2.788644ms)
46
+ ✔ NPool.query (692.063225ms)
47
+ ✔ NPool.req (214.981082ms)
48
+ ✔ NPool.event (126.440494ms)
49
+ ✔ NPool.query with eoseTimeout (659.85331ms)
50
+ ✔ NPool.query with eoseTimeout disabled (565.131734ms)
51
+ ✔ NRelay1.query (485.876171ms)
52
+ ✔ NRelay1.query with NIP-50 search preserves relay order (120.209463ms)
53
+ ✔ NRelay1.query mismatched filter (63.99025ms)
54
+ ✔ NRelay1.req (191.837028ms)
55
+ ✔ NRelay1.event sends while connection is open (41.721819ms)
56
+ NRelay1.event sends before connection is open (63.494985ms)
57
+ ✔ NRelay1.event throws when OK is false (29.705869ms)
58
+ ✔ NRelay1.event sends after reconnect from CLOSING state (88.273164ms)
59
+ ﹣ NRelay1 backoff (0.48232ms) # SKIP
57
60
  ▶ NRelay1 idleTimeout
58
- ✔ websocket opens (7.858275ms)
59
- ✔ websocket closes after idleTimeout (151.842041ms)
60
- ✔ websocket wakes up during activity (30.190448ms)
61
- ✔ NRelay1 idleTimeout (198.365795ms)
62
- ✔ NRelay1.count rejects when the server sends CLOSED (35.144825ms)
63
- ✔ NRelay1 closes when it receives a binary message (41.616786ms)
64
- n.id (9.547513ms)
65
- n.bech32 (4.65879ms)
66
- n.filter (131.436935ms)
67
- n.event (70.944096ms)
68
- ✔ n.metadata (97.979282ms)
69
- NSecSigner (291.691919ms)
70
- NSecSigner.nip44 (80.607728ms)
71
- NSet (40.639953ms)
72
- NSet.add (replaceable) (0.621333ms)
73
- NSet.add (parameterized) (0.741169ms)
74
- NSet.add (deletion) (0.904847ms)
75
- Construct a RelayError from the reason message (4.510339ms)
76
- Throw a new RelayError if the OK message is false (0.66793ms)
77
- LNURL.fromString (9.361371ms)
78
- LNURL.fromLightningAddress (2.017806ms)
79
- LNURL.toString (0.99139ms)
80
- LNURL.getDetails (132.517443ms)
81
- ✔ LNURL.getInvoice (13.935902ms)
82
- ErrorRelay (211.320757ms)
83
- MockRelay (5.595707ms)
84
- BlossomUploader.upload (850.402405ms)
85
- NostrBuildUploader.upload (29.655028ms)
86
- CircularSet (3.028483ms)
87
- push, iterate, & close (105.244549ms)
88
- close & reopen (0.783748ms)
89
- aborts with signal (53.551362ms)
90
- already aborted signal in constructor (3.530691ms)
91
- ✔ push after abort (1.118661ms)
92
- multiple messages in queue (3.467462ms)
93
- N64 (21.22806ms)
94
- N64.encodeEvent (0.471119ms)
95
- N64.decodeEvent (10.169586ms)
96
- tests 90
61
+ ✔ websocket opens (6.360034ms)
62
+ ✔ websocket closes after idleTimeout (149.970737ms)
63
+ ✔ websocket wakes up during activity (27.214357ms)
64
+ ✔ NRelay1 idleTimeout (191.021158ms)
65
+ ✔ NRelay1.count rejects when the server sends CLOSED (20.042641ms)
66
+ ✔ NRelay1 closes when it receives a binary message (17.620458ms)
67
+ NRelay1 NIP-42 auth-required REQ retry (118.486511ms)
68
+ NRelay1 NIP-42 auth-required EVENT retry (62.036903ms)
69
+ NRelay1 NIP-42 auth-required does not retry without auth callback (18.852174ms)
70
+ NRelay1 NIP-42 auth-required does not retry infinitely (68.63132ms)
71
+ ✔ n.id (24.32918ms)
72
+ n.bech32 (7.411329ms)
73
+ n.filter (135.407499ms)
74
+ n.event (90.556593ms)
75
+ n.metadata (164.43043ms)
76
+ NSecSigner (371.990996ms)
77
+ NSecSigner.nip44 (105.236803ms)
78
+ NSet (49.973754ms)
79
+ NSet.add (replaceable) (0.581187ms)
80
+ NSet.add (parameterized) (5.114544ms)
81
+ NSet.add (deletion) (0.606013ms)
82
+ Construct a RelayError from the reason message (2.640955ms)
83
+ Throw a new RelayError if the OK message is false (0.810269ms)
84
+ ✔ LNURL.fromString (13.598537ms)
85
+ LNURL.fromLightningAddress (2.106787ms)
86
+ LNURL.toString (0.99578ms)
87
+ LNURL.getDetails (113.054838ms)
88
+ LNURL.getInvoice (40.071474ms)
89
+ ErrorRelay (216.352701ms)
90
+ MockRelay (5.899475ms)
91
+ BlossomUploader.upload (1023.233031ms)
92
+ NostrBuildUploader.upload (35.675948ms)
93
+ CircularSet (3.09927ms)
94
+ ✔ push, iterate, & close (107.709499ms)
95
+ close & reopen (0.89543ms)
96
+ aborts with signal (55.223022ms)
97
+ already aborted signal in constructor (0.925958ms)
98
+ push after abort (3.545873ms)
99
+ multiple messages in queue (0.634127ms)
100
+ ✔ N64 (20.852057ms)
101
+ ✔ N64.encodeEvent (0.470058ms)
102
+ ✔ N64.decodeEvent (13.615198ms)
103
+ ✔ getFilterLimit returns Infinity for single replaceable kind + single author (2.743969ms)
104
+ ✔ getFilterLimit returns Infinity for single addressable kind + single author + single #d (0.812543ms)
105
+ ✔ getFilterLimit allows since/until on coordinate filters (0.598139ms)
106
+ ✔ getFilterLimit respects explicit limit on coordinate filters (0.530141ms)
107
+ ✔ getFilterLimit enforces limit for multiple authors with replaceable kind (0.868239ms)
108
+ ✔ getFilterLimit enforces limit for multiple kinds with replaceable kinds (0.580065ms)
109
+ ✔ getFilterLimit returns Infinity for addressable kind without #d (not a coordinate filter, but nostr-tools also returns Infinity) (0.439419ms)
110
+ ✔ getFilterLimit enforces limit for addressable kind with multiple #d values (0.465198ms)
111
+ ✔ getFilterLimit enforces limit when extra filter properties are present (2.643249ms)
112
+ ✔ getFilterLimit returns 0 for empty arrays (0.566329ms)
113
+ ✔ getFilterLimit works normally for regular kinds (0.710531ms)
114
+ ✔ getFilterLimit works normally for ids filter (0.295778ms)
115
+ ℹ tests 109
97
116
  ℹ suites 0
98
- ℹ pass 88
117
+ ℹ pass 107
99
118
  ℹ fail 1
100
119
  ℹ cancelled 0
101
120
  ℹ skipped 1
102
121
  ℹ todo 0
103
- ℹ duration_ms 4116.611574
122
+ ℹ duration_ms 4739.688853
104
123
 
105
124
  ✖ failing tests:
106
125
 
107
126
  test at uploaders/NostrBuildUploader.test.ts:12:7
108
- ✖ NostrBuildUploader.upload (29.655028ms)
127
+ ✖ NostrBuildUploader.upload (35.675948ms)
109
128
  Error: nostr.build with default uploader requires a secret key to be configured
110
129
  at TestContext.<anonymous> (file:///home/alex/Projects/nostrify/packages/nostrify/uploaders/NostrBuildUploader.test.ts:25:13)
111
130
  at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
@@ -1,6 +1,8 @@
1
-
2
- > @nostrify/nostrify@0.50.5 typecheck /home/alex/Projects/nostrify/packages/nostrify
3
- > npx tsc --noEmit
4
-
5
- npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
6
- npm warn Unknown env config "_jsr-registry". This will stop working in the next major version of npm.
1
+
2
+
3
+ > @nostrify/nostrify@0.51.0 typecheck /home/alex/Projects/nostrify/packages/nostrify
4
+ > npx tsc --noEmit
5
+
6
+ npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
7
+ npm warn Unknown env config "_jsr-registry". This will stop working in the next major version of npm.
8
+ ⠙
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.51.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a9dc610: NRelay1: automatically retry REQ and EVENT after NIP-42 AUTH
8
+
9
+ When a relay responds with `auth-required:` in a CLOSED or OK message, NRelay1 now waits for the AUTH flow to complete and re-sends the original request. This implements the full NIP-42 client-side protocol flow. Retries are limited to one attempt per subscription/event to prevent infinite loops.
10
+
3
11
  ## 0.50.5
4
12
 
5
13
  ### Patch Changes
package/NRelay1.test.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { it, test } from "node:test";
2
- import type { NostrEvent } from "@nostrify/types";
2
+ import type { NostrClientMsg, NostrEvent } from "@nostrify/types";
3
3
  import { deepStrictEqual, ok, rejects } from "node:assert";
4
4
  import { finalizeEvent, generateSecretKey } from "nostr-tools";
5
5
  import { ExponentialBackoff, WebsocketEvent } from "websocket-ts";
@@ -304,3 +304,150 @@ await test("NRelay1 closes when it receives a binary message", async () => {
304
304
 
305
305
  await rejects(() => relay.query([{ kinds: [1] }]));
306
306
  });
307
+
308
+ await test("NRelay1 NIP-42 auth-required REQ retry", async () => {
309
+ const sk = generateSecretKey();
310
+ const testEvent = genEvent({ kind: 4, content: "secret DM" }, sk);
311
+
312
+ let reqCount = 0;
313
+
314
+ await using server = await TestRelayServer.create({
315
+ handleMessage(socket, msg: NostrClientMsg) {
316
+ if (msg[0] === "REQ") {
317
+ const [, subId] = msg;
318
+ reqCount++;
319
+ if (reqCount === 1) {
320
+ // First REQ: send AUTH challenge, then reject with auth-required
321
+ socket.send(JSON.stringify(["AUTH", "challenge123"]));
322
+ socket.send(JSON.stringify(["CLOSED", subId, "auth-required: authentication required"]));
323
+ } else {
324
+ // Second REQ (after auth): serve the events
325
+ socket.send(JSON.stringify(["EVENT", subId, testEvent]));
326
+ socket.send(JSON.stringify(["EOSE", subId]));
327
+ }
328
+ }
329
+ if (msg[0] === "AUTH") {
330
+ // Accept the AUTH event
331
+ socket.send(JSON.stringify(["OK", msg[1].id, true, ""]));
332
+ }
333
+ },
334
+ });
335
+
336
+ await using relay = new NRelay1(server.url, {
337
+ auth: async (challenge) => {
338
+ return genEvent({
339
+ kind: 22242,
340
+ tags: [["relay", server.url], ["challenge", challenge]],
341
+ }, sk);
342
+ },
343
+ });
344
+
345
+ const result = await relay.query([{ kinds: [4] }]);
346
+
347
+ deepStrictEqual(result.length, 1);
348
+ deepStrictEqual(result[0].id, testEvent.id);
349
+ deepStrictEqual(reqCount, 2);
350
+ });
351
+
352
+ await test("NRelay1 NIP-42 auth-required EVENT retry", async () => {
353
+ const sk = generateSecretKey();
354
+ const eventToPublish: NostrEvent = finalizeEvent({
355
+ kind: 1,
356
+ content: "Hello from authenticated user",
357
+ tags: [],
358
+ created_at: Math.floor(Date.now() / 1000),
359
+ }, sk);
360
+
361
+ let eventCount = 0;
362
+
363
+ await using server = await TestRelayServer.create({
364
+ handleMessage(socket, msg: NostrClientMsg) {
365
+ if (msg[0] === "EVENT") {
366
+ eventCount++;
367
+ if (eventCount === 1) {
368
+ // First EVENT: send AUTH challenge, then reject with auth-required
369
+ socket.send(JSON.stringify(["AUTH", "challenge456"]));
370
+ socket.send(JSON.stringify(["OK", msg[1].id, false, "auth-required: authentication required"]));
371
+ } else {
372
+ // Second EVENT (after auth): accept
373
+ socket.send(JSON.stringify(["OK", msg[1].id, true, ""]));
374
+ }
375
+ }
376
+ if (msg[0] === "AUTH") {
377
+ // Accept the AUTH event
378
+ socket.send(JSON.stringify(["OK", msg[1].id, true, ""]));
379
+ }
380
+ },
381
+ });
382
+
383
+ await using relay = new NRelay1(server.url, {
384
+ auth: async (challenge) => {
385
+ return genEvent({
386
+ kind: 22242,
387
+ tags: [["relay", server.url], ["challenge", challenge]],
388
+ }, sk);
389
+ },
390
+ });
391
+
392
+ // Should succeed after automatic auth + retry
393
+ await relay.event(eventToPublish);
394
+ deepStrictEqual(eventCount, 2);
395
+ });
396
+
397
+ await test("NRelay1 NIP-42 auth-required does not retry without auth callback", async () => {
398
+ let reqCount = 0;
399
+
400
+ await using server = await TestRelayServer.create({
401
+ handleMessage(socket, msg: NostrClientMsg) {
402
+ if (msg[0] === "REQ") {
403
+ reqCount++;
404
+ const [, subId] = msg;
405
+ socket.send(JSON.stringify(["CLOSED", subId, "auth-required: authentication required"]));
406
+ }
407
+ },
408
+ });
409
+
410
+ // No auth callback provided — CLOSED should pass through without retry
411
+ await using relay = new NRelay1(server.url);
412
+
413
+ const result = await relay.query([{ kinds: [4] }]);
414
+ deepStrictEqual(result, []);
415
+ deepStrictEqual(reqCount, 1);
416
+ });
417
+
418
+ await test("NRelay1 NIP-42 auth-required does not retry infinitely", async () => {
419
+ const sk = generateSecretKey();
420
+ let reqCount = 0;
421
+
422
+ await using server = await TestRelayServer.create({
423
+ handleMessage(socket, msg: NostrClientMsg) {
424
+ if (msg[0] === "REQ") {
425
+ const [, subId] = msg;
426
+ reqCount++;
427
+ // Send AUTH challenge on first REQ only
428
+ if (reqCount === 1) {
429
+ socket.send(JSON.stringify(["AUTH", "challenge789"]));
430
+ }
431
+ // Always reject with auth-required, even after auth
432
+ socket.send(JSON.stringify(["CLOSED", subId, "auth-required: still not allowed"]));
433
+ }
434
+ if (msg[0] === "AUTH") {
435
+ socket.send(JSON.stringify(["OK", msg[1].id, true, ""]));
436
+ }
437
+ },
438
+ });
439
+
440
+ await using relay = new NRelay1(server.url, {
441
+ auth: async (challenge) => {
442
+ return genEvent({
443
+ kind: 22242,
444
+ tags: [["relay", server.url], ["challenge", challenge]],
445
+ }, sk);
446
+ },
447
+ });
448
+
449
+ // Should stop after one retry (reqCount=2), not loop forever
450
+ const result = await relay.query([{ kinds: [4] }]);
451
+ deepStrictEqual(result, []);
452
+ deepStrictEqual(reqCount, 2);
453
+ });
package/NRelay1.ts CHANGED
@@ -65,6 +65,15 @@ export class NRelay1 implements NRelay {
65
65
  private opts: NRelay1Opts;
66
66
  private relayInfoPromise?: Promise<NostrRelayInfo | undefined>;
67
67
 
68
+ /** Promise that resolves when the current AUTH flow completes. */
69
+ private authPromise?: Promise<void>;
70
+ /** Set of subscription IDs that have already been retried after auth, to prevent infinite loops. */
71
+ private authRetriedSubs = new Set<string>();
72
+ /** Set of event IDs that have already been retried after auth, to prevent infinite loops. */
73
+ private authRetriedEvents = new Set<string>();
74
+ /** Pending events waiting for AUTH, keyed by event ID. */
75
+ private pendingEvents = new Map<string, NostrEvent>();
76
+
68
77
  private ee = new EventTarget();
69
78
 
70
79
  get subscriptions(): readonly NostrClientREQ[] {
@@ -241,7 +250,12 @@ export class NRelay1 implements NRelay {
241
250
  );
242
251
  break;
243
252
  case 'CLOSED':
253
+ if (auth && msg[2].startsWith('auth-required:') && !this.authRetriedSubs.has(msg[1])) {
254
+ this.retrySubAfterAuth(msg[1]);
255
+ break;
256
+ }
244
257
  this.subs.delete(msg[1]);
258
+ this.authRetriedSubs.delete(msg[1]);
245
259
  this.maybeStartIdleTimer();
246
260
  this.ee.dispatchEvent(
247
261
  new CustomEvent(`sub:${msg[1]}`, { detail: msg }),
@@ -251,6 +265,12 @@ export class NRelay1 implements NRelay {
251
265
  );
252
266
  break;
253
267
  case 'OK':
268
+ if (auth && !msg[2] && msg[3].startsWith('auth-required:') && !this.authRetriedEvents.has(msg[1])) {
269
+ this.retryEventAfterAuth(msg[1]);
270
+ break;
271
+ }
272
+ this.pendingEvents.delete(msg[1]);
273
+ this.authRetriedEvents.delete(msg[1]);
254
274
  this.ee.dispatchEvent(new CustomEvent(`ok:${msg[1]}`, { detail: msg }));
255
275
  break;
256
276
  case 'NOTICE':
@@ -262,9 +282,62 @@ export class NRelay1 implements NRelay {
262
282
  );
263
283
  break;
264
284
  case 'AUTH':
265
- auth?.(msg[1]).then((event) => this.send(['AUTH', event])).catch(
266
- () => {},
267
- );
285
+ if (auth) {
286
+ this.authPromise = this.doAuth(auth, msg[1]);
287
+ }
288
+ }
289
+ }
290
+
291
+ /** Perform NIP-42 authentication and wait for the relay's OK response. */
292
+ private async doAuth(auth: (challenge: string) => Promise<NostrEvent>, challenge: string): Promise<void> {
293
+ try {
294
+ const event = await auth(challenge);
295
+ const result = this.once(`ok:${event.id}`);
296
+ this.send(['AUTH', event]);
297
+ const [, , ok] = await result;
298
+ if (!ok) {
299
+ this.log({ level: 'warn', ns: 'relay.auth', message: 'AUTH failed' });
300
+ }
301
+ } catch {
302
+ // AUTH failed, nothing to do
303
+ }
304
+ }
305
+
306
+ /** Re-send a subscription after AUTH completes. */
307
+ private async retrySubAfterAuth(subscriptionId: string): Promise<void> {
308
+ const req = this.subs.get(subscriptionId);
309
+ if (!req) return;
310
+
311
+ this.authRetriedSubs.add(subscriptionId);
312
+
313
+ try {
314
+ await this.authPromise;
315
+ } catch {
316
+ // AUTH failed — fall through to let the CLOSED propagate
317
+ }
318
+
319
+ // Re-send the original REQ if the subscription is still active.
320
+ if (this.subs.has(subscriptionId)) {
321
+ this.send(req);
322
+ }
323
+ }
324
+
325
+ /** Re-send an event after AUTH completes. */
326
+ private async retryEventAfterAuth(eventId: string): Promise<void> {
327
+ const event = this.pendingEvents.get(eventId);
328
+ if (!event) return;
329
+
330
+ this.authRetriedEvents.add(eventId);
331
+
332
+ try {
333
+ await this.authPromise;
334
+ } catch {
335
+ // AUTH failed — fall through to let the failed OK propagate
336
+ }
337
+
338
+ // Re-send the event if it's still pending.
339
+ if (this.pendingEvents.has(eventId)) {
340
+ this.send(['EVENT', event]);
268
341
  }
269
342
  }
270
343
 
@@ -282,6 +355,8 @@ export class NRelay1 implements NRelay {
282
355
  this.maybeStartIdleTimer();
283
356
  break;
284
357
  case 'EVENT':
358
+ this.pendingEvents.set(msg[1].id, msg[1]);
359
+ return this.socket.send(JSON.stringify(msg));
285
360
  case 'COUNT':
286
361
  return this.socket.send(JSON.stringify(msg));
287
362
  }
package/dist/NRelay1.d.ts CHANGED
@@ -33,6 +33,14 @@ export declare class NRelay1 implements NRelay {
33
33
  private url;
34
34
  private opts;
35
35
  private relayInfoPromise?;
36
+ /** Promise that resolves when the current AUTH flow completes. */
37
+ private authPromise?;
38
+ /** Set of subscription IDs that have already been retried after auth, to prevent infinite loops. */
39
+ private authRetriedSubs;
40
+ /** Set of event IDs that have already been retried after auth, to prevent infinite loops. */
41
+ private authRetriedEvents;
42
+ /** Pending events waiting for AUTH, keyed by event ID. */
43
+ private pendingEvents;
36
44
  private ee;
37
45
  get subscriptions(): readonly NostrClientREQ[];
38
46
  private log;
@@ -47,6 +55,12 @@ export declare class NRelay1 implements NRelay {
47
55
  private createSocket;
48
56
  /** Handle a NIP-01 relay message. */
49
57
  protected receive(msg: NostrRelayMsg): void;
58
+ /** Perform NIP-42 authentication and wait for the relay's OK response. */
59
+ private doAuth;
60
+ /** Re-send a subscription after AUTH completes. */
61
+ private retrySubAfterAuth;
62
+ /** Re-send an event after AUTH completes. */
63
+ private retryEventAfterAuth;
50
64
  /** Send a NIP-01 client message to the relay. */
51
65
  protected send(msg: NostrClientMsg): void;
52
66
  req(filters: NostrFilter[], opts?: {
@@ -1 +1 @@
1
- {"version":3,"file":"NRelay1.d.ts","sourceRoot":"","sources":["../NRelay1.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACd,UAAU,EACV,WAAW,EACX,gBAAgB,EAEhB,cAAc,EACd,eAAe,EACf,aAAa,EAGb,cAAc,EACd,MAAM,EACP,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAAkC,SAAS,EAAoC,MAAM,cAAc,CAAC;AAC3G,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAc1C,2DAA2D;AAC7D,MAAM,WAAW,WAAW;IAC1B,6EAA6E;IAC7E,IAAI,CAAC,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAC9C,8GAA8G;IAC9G,OAAO,CAAC,EAAE,OAAO,GAAG,KAAK,CAAC;IAC1B,8JAA8J;IAC9J,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAC7B,wFAAwF;IACxF,WAAW,CAAC,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC;IACzC,uBAAuB;IACvB,GAAG,CAAC,CAAC,GAAG,EAAE,UAAU,GAAG,IAAI,CAAC;IAC5B,kGAAkG;IAClG,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC;AAED,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM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