@941design/nostr-events 0.0.0-stage → 0.2.0-alpha.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.
Files changed (66) hide show
  1. package/CHANGELOG.md +340 -0
  2. package/LICENSE +21 -0
  3. package/README.md +121 -2
  4. package/dist/branded/index.d.ts +30 -0
  5. package/dist/branded/index.js +22 -0
  6. package/dist/clock/index.d.ts +22 -0
  7. package/dist/clock/index.js +29 -0
  8. package/dist/error/index.d.ts +55 -0
  9. package/dist/error/index.js +207 -0
  10. package/dist/event/index.d.ts +95 -0
  11. package/dist/event/index.js +104 -0
  12. package/dist/factory/index.d.ts +130 -0
  13. package/dist/factory/index.js +92 -0
  14. package/dist/gift-wrap/index.d.ts +93 -0
  15. package/dist/gift-wrap/index.js +341 -0
  16. package/dist/loaders/batcher.d.ts +70 -0
  17. package/dist/loaders/batcher.js +258 -0
  18. package/dist/loaders/index.d.ts +169 -0
  19. package/dist/loaders/index.js +581 -0
  20. package/dist/nip19/index.d.ts +17 -0
  21. package/dist/nip19/index.js +17 -0
  22. package/dist/parsers/index.d.ts +148 -0
  23. package/dist/parsers/index.js +293 -0
  24. package/dist/signer/adapters/index.d.ts +79 -0
  25. package/dist/signer/adapters/index.js +388 -0
  26. package/dist/signer/budget/index.d.ts +132 -0
  27. package/dist/signer/budget/index.js +807 -0
  28. package/dist/signer/capability/index.d.ts +31 -0
  29. package/dist/signer/capability/index.js +145 -0
  30. package/dist/signer/escrow/index.d.ts +24 -0
  31. package/dist/signer/escrow/index.js +60 -0
  32. package/dist/signer/extension/index.d.ts +21 -0
  33. package/dist/signer/extension/index.js +200 -0
  34. package/dist/signer/index.d.ts +56 -0
  35. package/dist/signer/index.js +51 -0
  36. package/dist/signer/nostr-connect/index.d.ts +141 -0
  37. package/dist/signer/nostr-connect/index.js +1097 -0
  38. package/dist/signer/nostr-connect/uri.d.ts +84 -0
  39. package/dist/signer/nostr-connect/uri.js +243 -0
  40. package/dist/signer/permissions/index.d.ts +89 -0
  41. package/dist/signer/permissions/index.js +120 -0
  42. package/dist/signer/private-key/index.d.ts +16 -0
  43. package/dist/signer/private-key/index.js +147 -0
  44. package/dist/transport/bounded/index.d.ts +50 -0
  45. package/dist/transport/bounded/index.js +360 -0
  46. package/dist/transport/contract/conformance/fake-relay.d.ts +131 -0
  47. package/dist/transport/contract/conformance/fake-relay.js +564 -0
  48. package/dist/transport/contract/conformance/index.d.ts +38 -0
  49. package/dist/transport/contract/conformance/index.js +558 -0
  50. package/dist/transport/contract/index.d.ts +32 -0
  51. package/dist/transport/contract/index.js +63 -0
  52. package/dist/transport/inbox-relays/index.d.ts +96 -0
  53. package/dist/transport/inbox-relays/index.js +231 -0
  54. package/dist/transport/index.d.ts +73 -0
  55. package/dist/transport/index.js +20 -0
  56. package/dist/transport/raw-ws/index.d.ts +149 -0
  57. package/dist/transport/raw-ws/index.js +778 -0
  58. package/dist/transport/reconnect/index.d.ts +90 -0
  59. package/dist/transport/reconnect/index.js +400 -0
  60. package/dist/transport/request/index.d.ts +61 -0
  61. package/dist/transport/request/index.js +325 -0
  62. package/dist/transport/simple-pool/index.d.ts +215 -0
  63. package/dist/transport/simple-pool/index.js +1734 -0
  64. package/dist/transport/timer-limits/index.d.ts +1 -0
  65. package/dist/transport/timer-limits/index.js +22 -0
  66. package/package.json +189 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,340 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0-alpha.1
4
+
5
+ ### Patch Changes
6
+
7
+ - c6d8ba5: Add portable bounded relay reads and an optional read-only local MCP adapter with configured relay policy, resource budgets, cancellation and explicit partial-result metadata. Add installed-package browser and Node runtime verification.
8
+ - 0362cac: Fix HTTP request-slot exhaustion, preserve partial results across read deadlines, and make configured relay defaults usable. Improve cursor-store fairness, signer lookup and budget handling, relay authentication retries, transport metadata forwarding and safe CLI diagnostics. Account bounded read responses incrementally and clarify bounded subscription and NIP-59 delivery semantics.
9
+
10
+ ## 0.2.0-alpha.0
11
+
12
+ ### Minor Changes
13
+
14
+ - 09a3c7f: New subpath `@941design/nostr-events/loaders` with three batched, re-validating loaders over a `NostrNetworkInterface`:
15
+
16
+ - **`createAddressLoader({ network, relays, timeoutMs, ... })`** resolves `(kind, pubkey, d?)` coordinates of replaceable
17
+ and addressable events. Lookups issued in the same synchronous turn (or within `coalesceMs`) share one `batch` of
18
+ relay filters, concurrent lookups for one coordinate share one fetch, and nothing is cached once a lookup settles.
19
+ The latest valid event wins (highest `created_at`, lowest `id` on a tie).
20
+ - **`createEventLoader({ network, relays, timeoutMs, ... })`** does the same for event ids (`ids` filters, chunked at
21
+ `maxIdsPerFilter`).
22
+ - **`createTimelineLoader({ network, relays, timeoutMs, filter, pageSize? })`** returns an `AsyncIterable<TimelinePage>`
23
+ that walks a filter newest-first without losing events that share a boundary second, deduplicating by id.
24
+
25
+ Every delivered event is re-checked locally (key or filter match plus `safeVerifyEvent`), so a relay that over-delivers
26
+ or forges cannot inject anything. Address and event lookups resolve to a `LoadResult` (`event`, `timedOut`,
27
+ `silentRelays`); a timeout or a failing relay is reported there, never as a rejection. Errors are `NetworkError` only:
28
+ option problems throw `NetworkError('invalid-options')` synchronously, a malformed pointer or id rejects with it, and an
29
+ aborted signal (per call for the address and event loaders, factory-level for the timeline) rejects with
30
+ `NetworkError('aborted')`. The TSDoc states the `verifyEvents: false` residual (a faster hostile relay can suppress,
31
+ never forge, an event) and the timeline's `since` / `pageSize` guidance.
32
+
33
+ No runtime dependency is added: the subpath imports `nostr-tools/filter` (the existing `nostr-tools` peer) and the
34
+ `event`, `error` and `transport` subpaths of this package; its published size is about 4 kB.
35
+ - f63fac7: New `createNostrConnectUri({ clientSecret, relays, perms?, secret?, name?,
36
+ url?, image? })` on `@941design/nostr-events/signer/nostr-connect` builds the
37
+ client-generated NIP-46
38
+ `nostrconnect://<client-pubkey>?relay=…&secret=…&perms=…` URI that a remote
39
+ signer (Amber, nsec.app) reads from a QR code or deep link. It is pure and
40
+ synchronous and touches no transport. It returns `{ uri, secret, clientPubkey
41
+ }`. Each relay becomes its own `relay=` pair in input order, kept verbatim
42
+ with duplicates. Every value is encoded once, and absent optional keys are
43
+ left out. When `secret` is omitted, 16 bytes from `crypto.getRandomValues` are
44
+ rendered as 32 lowercase hex characters. Invalid input throws
45
+ `SignerError('init')`: a `clientSecret` that is not 32 bytes or not a valid
46
+ secp256k1 secret key (the same error `createNostrConnectSigner` now throws for
47
+ such a key instead of a raw noble Error), a `name` / `url` / `image` that is
48
+ not a string, no relay or an empty relay, a `secret` outside
49
+ `[A-Za-z0-9_-]{1,64}`, or a `perms` entry that is empty or contains a comma.
50
+ Neither secret appears in the error. New exported types:
51
+ `CreateNostrConnectUriOptions`, `CreateNostrConnectUriResult`.
52
+ - f63fac7: New `listenForNostrConnect({ transport, clientSecret, uri, timeoutMs?,
53
+ handshakeTimeoutMs?, signal? })` on `@941design/nostr-events/signer/nostr-connect`
54
+ completes the standard NIP-46 client-generated `nostrconnect://` sign-in
55
+ (Amber, nsec.app). Call it with the URI from `createNostrConnectUri` before
56
+ showing the URI: it opens the kind-24133 subscription for the client pubkey on
57
+ the URI's relays synchronously, waits for the remote signer's `connect`
58
+ response whose `result` echoes the URI secret, and resolves to a connected
59
+ signer whose requests go to the response's author. Stray, spoofed or
60
+ wrong-secret responses are ignored. No `connect` request is sent. The result
61
+ type `NostrConnectSession` is a `Signer` with `dispose()` and readonly
62
+ `remotePubkey` and `relays`. To reconnect later, persist them with
63
+ `clientSecret` and call `createNostrConnectSigner({ transport, remote:
64
+ remotePubkey, relays, clientSecret, perms })`, which sends `connect`
65
+ without a secret. The
66
+ handshake wait defaults to 300 seconds (`handshakeTimeoutMs`); requests keep
67
+ the 30-second `timeoutMs`. Rejections are `SignerError` with code `init`
68
+ (invalid URI or `clientSecret`, or a URI host that is not the `clientSecret`
69
+ pubkey), `cancelled`, `timeout` or `transport`, and leave no subscription,
70
+ timer or abort listener behind. New exported types:
71
+ `ListenForNostrConnectOptions`, `NostrConnectSession`. `createNostrConnectSigner`
72
+ now shares the same session core; its wire output is unchanged, except that a
73
+ subscription that terminates inside `subscribe()` now rejects `transport` at
74
+ once without sending `connect`. The `transport` option of both functions is
75
+ now typed `Pick<NostrNetworkInterface, 'subscription' | 'publish'>`, which
76
+ every `NostrNetworkInterface` and `TransportContract` satisfies.
77
+ - a7d0158: `createNostrConnectSigner` and `listenForNostrConnect` (`@941design/nostr-events/signer/nostr-connect`) accept an optional
78
+ `onAuthUrl(url, requestId)` callback. When set, a NIP-46 `auth_url` response no longer fails the request: the callback
79
+ gets the URL to show the user, the request stays pending under its id, and the signer's follow-up response settles it
80
+ (still bounded by `timeoutMs`; raise it to give the user time). This applies to the `connect` handshake too. Without
81
+ the option, `auth_url` still rejects at once with `SignerError('auth-required')` and the URL in `details.url`.
82
+ - 74f30dd: **Breaking:** `createNostrConnectSigner` on
83
+ `@941design/nostr-events/signer/nostr-connect` no longer accepts a
84
+ `nostrconnect://` URI as `remote`. The removed mode read the URI host as the
85
+ remote signer's pubkey and published `connect` to it, which no real signer
86
+ supports: a `nostrconnect://` URI is generated by the client and its host is
87
+ the client's own pubkey. Such a `remote` now throws `SignerError('init')` at
88
+ construction, without touching the transport, with a message that names
89
+ `listenForNostrConnect` and carries no part of the URI (no secret, no query).
90
+ Migrate by building the URI with `createNostrConnectUri`, showing it to the
91
+ remote signer, and awaiting `listenForNostrConnect`. Removed with the mode: the
92
+ merge of a URI `perms=` value into `perms`, the secret-echo check on the
93
+ `connect` result, and the one-time `auth_url` deferral of the `connect`
94
+ request. `bunker://` and bare-hex remotes behave and serialise exactly as
95
+ before; an `auth_url` answer to their `connect` stays a terminal
96
+ `auth-required` rejection.
97
+ - c32d11d: `@941design/nostr-events/parsers` gains two pure parsers over attacker-controlled events:
98
+
99
+ - **`parseProfileMetadata(event)`** reads a kind 0 (NIP-01) profile into `ProfileMetadata`. A wrong kind, non-string
100
+ `content`, invalid JSON or a non-object JSON value throws `CodecError('malformed-event')`. Well-known string fields are
101
+ copied verbatim (`""` is kept), a well-known field with a non-string value is dropped, `__proto__`, `constructor` and
102
+ `prototype` are dropped, and every other key passes through as an own property.
103
+ - **`parseContactList(event)`** reads a kind 3 (NIP-02) contact list into `Contact[]` from its `p` tags. A wrong kind
104
+ throws `CodecError('malformed-event')`; a tag that is malformed or whose pubkey is not 64 lowercase hex characters is
105
+ skipped. Contacts are deduped by pubkey (first occurrence wins entirely); `relayHint` and `petname` are kept verbatim
106
+ only when non-empty. `content` is never read.
107
+
108
+ Readonly convention: the new `ProfileMetadata` and `Contact` types declare their fields `readonly`, while the older
109
+ `RelayList10002` and `DmRelayList10050` stay mutable for compatibility. The difference is deliberate: adding `readonly`
110
+ to those later would be a breaking change, whereas removing it would not.
111
+
112
+ The `parsers` subpath now imports `isHex32` from `event/`, so it pulls `nostr-tools/pure` (a required peer) into its
113
+ module graph; its published size stays well below the 3 kB limit.
114
+ - a805f9c: `createRawWebSocketNetwork` `subscription()` no longer degrades or hangs
115
+ silently:
116
+
117
+ - New optional `onSubscriptionLegClosed(relayUrl, error)` hook. It fires once
118
+ for each relay leg that stops delivering: on a relay `CLOSED` frame
119
+ (`relay-error`), or on socket loss, failed open, a failed REQ send or a
120
+ throwing WebSocket constructor (`transport-error`). Before, a leg that died
121
+ while others survived was invisible. The hook only signals; the adapter
122
+ does not re-dial. A throwing hook is swallowed, and your own `unsubscribe()`
123
+ never fires it.
124
+ - When every relay's WebSocket constructor throws (e.g. a scheme-less URL),
125
+ the observer now gets one `transport-error` on a microtask. Before, the
126
+ subscription hung with no signal, so `withReconnect` never retried it.
127
+ - 05cadf6: Breaking (pre-1.0): `ReconnectStatus` (`nostr-events/transport/reconnect`) is
128
+ now `'connected' | 'reconnecting'`. The `'offline'` member was never emitted:
129
+ `withReconnect` reconnects forever and has no terminal state that could be
130
+ called offline. Drop any `case 'offline'` branch in an `onStatus` handler. An
131
+ environment-driven offline signal (e.g. `navigator.onLine`) belongs in the
132
+ application.
133
+ - 1b19215: Breaking (pre-1.0): the `NDK_SHAPE` preset of `nostr-events/signer/adapters` is
134
+ renamed `NIP46_RPC_SHAPE`, with no deprecated alias. Its flat
135
+ `getPublicKey` / `signEvent` / `nip44Encrypt` / `nip44Decrypt` layout is the
136
+ NIP-46 RPC method layout; it never matched `@nostr-dev-kit/ndk`'s `NDKSigner`
137
+ (sync `pubkey` getter, `sign()` returning only the signature,
138
+ `encrypt(user, value, scheme)`). Replace `methods: NDK_SHAPE` with
139
+ `methods: NIP46_RPC_SHAPE`; behaviour is unchanged. No NDK adapter is provided.
140
+ - a805f9c: `createSimplePoolNetwork` accepts an optional
141
+ `reconnectBackoff: { initialMs, maxMs, jitterRatio? }` that sets the
142
+ `autoReconnect` re-issue delays for each (relay, filter) pair. If you omit it,
143
+ the existing 500 ms initial delay, 10 s cap and 0.2 jitter apply. The config is
144
+ read once and validated when the network is created, with the same rules as
145
+ `new ExponentialBackoff(...)`. A bad value throws `NetworkError` code
146
+ `invalid-options` at creation, not at the first drop.
147
+ - f78d148: Adds `TransportContract` (a narrowed, three-method transport surface —
148
+ `publish`, `requestWithDeadline`, `subscription`) and a Vitest-importable
149
+ conformance suite (`runTransportConformance`, `FakeRelay`) so a
150
+ third-party adapter can prove itself against the same behaviour both
151
+ shipped adapters (`raw-ws`, `simple-pool`) now pass in CI, plus the
152
+ NIP-65/NIP-17 relay-list parsers, event-template factory, and inbox-relay
153
+ lookup this contract unlocks. Full detail (including every declared
154
+ behaviour change and its rationale) lives in `CHANGELOG.md`'s
155
+ `## Unreleased` section as of this release; this summary is what
156
+ `changeset version` will publish as the actual dated version entry.
157
+
158
+ **Breaking (shipping as a minor per this package's pre-1.0 policy):**
159
+
160
+ - `createSimplePoolNetwork`'s `publish` now rejects `NetworkError`
161
+ code `aborted` when `opts.signal` aborts during `publish` or
162
+ `requestWithDeadline` — previously resolved `{ ok: false, message:
163
+ 'publish aborted' }`.
164
+ - `ExponentialBackoff({ initialMs, maxMs, jitterRatio })` now throws
165
+ `NetworkError` code `invalid-options` (a new code) instead of a bare
166
+ `RangeError`, and gained a fourth rejection condition —
167
+ `maxMs·(1+jitterRatio) > 2³¹−1`, the `setTimeout` delay ceiling — so
168
+ `maxMs: Infinity`, accepted before this release, now throws.
169
+ - `createRawWebSocketNetwork()` now throws `NetworkError` code
170
+ `no-websocket` (a new code) synchronously at construction when no
171
+ `WebSocket` implementation is available, instead of throwing lazily
172
+ at first use. Relatedly (documented only in JSDoc until now): the
173
+ `WebSocket` implementation is captured once, at construction — a
174
+ `globalThis.WebSocket` assigned afterward is not picked up by a
175
+ later connection on the same instance.
176
+ - A raw-ws `["CLOSED", subId, msg]` frame now completes the matching
177
+ subscription's observer with `error` (`NetworkError` code
178
+ `relay-error`) instead of being a no-op; under `withReconnect` this
179
+ now triggers a reconnect.
180
+ - `fetchNip65InboxRelays` and `fetchNip17DmRelays`
181
+ (`nostr-events/transport/inbox-relays`) now require a
182
+ `TransportContract` (not a raw `NostrNetworkInterface`) and a
183
+ required `timeoutMs` option, routing every request through the
184
+ bounded `requestWithDeadline` instead of the unbounded
185
+ `network.request`.
186
+ - `pickLatest`, the replaceable-event selector shared by both
187
+ inbox-relay fetchers and the new `lookupInboxRelays`, now breaks
188
+ equal-`created_at` ties by the lower event id instead of
189
+ first-occurrence order.
190
+ - `requestWithDeadline` now rejects `NetworkError` code
191
+ `invalid-options` for a `timeoutMs` of `NaN`, `<= 0`, `Infinity`, or
192
+ above the 32-bit `setTimeout` ceiling — values `setTimeout` silently
193
+ turned into a next-tick deadline, reported as an ordinary empty
194
+ `timedOut: true` result.
195
+
196
+ **Added:**
197
+
198
+ - `nostr-events/transport/contract` (`TransportContract`,
199
+ `toTransportContract`) and `nostr-events/transport/contract/conformance`
200
+ (`runTransportConformance`, `FakeRelay`) — see above.
201
+ - `onNotice` and `onProtocolError` observer hooks on
202
+ `createRawWebSocketNetwork`; a socket-level transport error on a
203
+ `subscription` leg (previously silent) now also surfaces via
204
+ `observer.error(NetworkError('transport-error'))`.
205
+ - `onAuthFailed` hook and full NIP-42 re-authentication on reconnect
206
+ for `createSimplePoolNetwork`: `request`/`requestWithDeadline` now
207
+ wire `onauth`, so a relay that re-demands AUTH after a reconnect is
208
+ answered rather than left hanging.
209
+ - `nostr-events/parsers` (`parseRelayList10002`, `parseDmRelayList10050`)
210
+ and `nostr-events/factory` (`deletion`, `relayList10002`,
211
+ `dmRelayList10050`, also grouped under `templates`).
212
+ - `lookupInboxRelays(transport, pubkey, opts)`
213
+ (`nostr-events/transport/inbox-relays`) — combined, fact-returning
214
+ NIP-17/NIP-65 relay lookup.
215
+ - b637b3b: `requestWithDeadline` sends one REQ per relay instead of two. It used to pair a
216
+ `subscription([url])` with each `request([url])` only to see events before
217
+ EOSE. `NostrNetworkInterface.request()` now takes `RequestOptions`
218
+ (`{ signal?, onEvent? }`); `onEvent` delivers each event as it arrives. An
219
+ adapter that declares `requestStreamsEvents: true` gets the one-REQ path; both
220
+ shipped adapters (raw-ws, simple-pool) declare it. A relay's REQ that still
221
+ owes EOSE is now closed when the call settles. Adapters without the flag keep
222
+ the old paired path.
223
+
224
+ Relay provenance, additive and optional:
225
+ - `Observer.next(value, meta?)`: adapters may pass `DeliveryMeta`
226
+ (`{ relay }`), the caller's URL string of the relay the event arrived on (the
227
+ first one, under cross-relay dedup). raw-ws and simple-pool supply it, and
228
+ `withReconnect` forwards it.
229
+ - `RequestWithDeadlineResult.eventRelays?: Map<eventId, relayUrl[]>` lists every
230
+ queried relay that delivered each event. `requestWithDeadline` always sets
231
+ it.
232
+
233
+ `runTransportConformance` gains AC-CONTRACT-12 (exactly one REQ per relay per
234
+ `requestWithDeadline`) and AC-CONTRACT-13 (provenance may be absent, but must
235
+ be correct when present). A hand-written adapter wrapped with
236
+ `toTransportContract` must implement `onEvent` and declare
237
+ `requestStreamsEvents` to pass AC-CONTRACT-12.
238
+
239
+ ### Patch Changes
240
+
241
+ - 36e5299: `FakeRelay.stop()` (transport conformance kit) no longer hangs when a client
242
+ connection was accepted before `stop()` but finished its WebSocket upgrade
243
+ afterwards. `stop()` now refuses late upgrades and closes connections that
244
+ are still mid-handshake. The package build also cleans `dist/` first, so
245
+ deleted modules no longer linger in the published tarball.
246
+ - 05c888c: `FakeRelay` (transport conformance kit) now handles WebSocket frames that
247
+ arrive in the same TCP packet as the HTTP upgrade request right away. They
248
+ used to be buffered until the client sent more bytes, so a client whose first
249
+ frame travelled with the upgrade saw the relay stall.
250
+ - 1b6789d: First npm pre-release (alpha) of all four packages.
251
+ - b20aa59: `createNostrConnectSigner` on `@941design/nostr-events/signer/nostr-connect`
252
+ now keeps NIP-46's secret slot (connect param index 1) when it sends `perms`
253
+ without a handshake secret: the params are `[remotePubkey, '', perms]`.
254
+ Previously `perms` landed at index 1, where a remote signer reads the secret.
255
+ Without `perms` the params are unchanged: `[remotePubkey]` or
256
+ `[remotePubkey, secret]`.
257
+ - cb9952f: `createNostrConnectSigner` on `@941design/nostr-events/signer/nostr-connect`
258
+ now throws `SignerError('init')` at construction when the bare-hex or
259
+ `bunker://` remote equals the pubkey derived from `clientSecret`. Such a
260
+ remote would encrypt every request to the client itself. The error is raised
261
+ before the transport is touched; its message describes the remote and the
262
+ client key in words and contains neither key. Remotes that differ from the
263
+ client pubkey construct and serialise exactly as before.
264
+ - 05c888c: `createNostrConnectSigner`'s `signEvent` now checks the bunker's signed event
265
+ against the template snapshot it sent, not against the caller's template as it
266
+ stands when the response arrives. A caller that mutates its template (tags or
267
+ content) while the request is pending no longer makes an honest bunker look
268
+ like it altered the event, and a bunker that returns the mutated fields is
269
+ refused. This matches `fromForeignSigner`.
270
+ - 18a1138: `simple-pool` reads nostr-tools 2.26's `{ url, reason }` close reasons as well as the bare reason strings of
271
+ 2.23–2.25, so it type-checks against every nostr-tools version the peer range admits and still reports
272
+ `auth-required` closes (`onAuthFailed`, the request-path AUTH retry) on 2.26.
273
+ - ff32d79: `createRawWebSocketNetwork` accepts an optional `onAuthFailed(relayUrl, error)`
274
+ hook (same shape as simple-pool's) that reports NIP-42 AUTH refusals: a
275
+ `CLOSED` or `OK`-false frame whose reason starts with `auth-required:` or
276
+ `restricted:`. A bare `AUTH` challenge is not reported, since many relays
277
+ challenge on connect and still serve unauthenticated requests. The hook fires
278
+ at most once per relay socket (first refusal wins) with a `NetworkError` of
279
+ code `auth-required` that carries the relay's reason verbatim. The adapter
280
+ still performs no AUTH handshake, and publish, request and subscription
281
+ results are unchanged.
282
+ - 996fc10: `requestWithDeadline` (`@941design/nostr-events/transport/request`) fixes:
283
+
284
+ - **Duplicate copies of an id:** when several distinct bodies arrive under one event id, the first that passes
285
+ `safeVerifyEvent` is kept (the first delivered when none does). A faster relay delivering a tampered body under an
286
+ honest id no longer suppresses the valid copy from a slower relay on an adapter with `verifyEvents: false`; the
287
+ loaders' documented first-copy residual is gone. Identical copies are not verified. `eventRelays` still lists every
288
+ relay that delivered an event under the id.
289
+ - **Repeated relay URLs** are queried once. Before, the call could only end on the timer and reported `timedOut`.
290
+ - **Non-event junk** (`null`, `undefined`, non-objects, objects without a string `id`) from a contract-breaking adapter
291
+ is ignored, as is a non-array resolved value. Before, it raised an unhandled rejection and the relay was reported
292
+ silent.
293
+ - A synchronous throw from the adapter while wiring up now tears down the subscriptions already opened and the abort
294
+ listener before rejecting with that error.
295
+ - On adapters without `requestStreamsEvents`, events in the per-relay `request()` result are merged too (deduplicated),
296
+ not only those seen on the parallel subscription.
297
+ - 8eb3026: `withSignerBudget` now rejects a `concurrency`, `minSpacingMs`, `timeoutMs` or
298
+ `leaseMs` that is not a primitive number with `SignerError` code `init`
299
+ (`withSignerBudget: <field> must be a number (got <type>)`). String values, such
300
+ as config read from env or JSON, used to pass the range checks by coercion. The
301
+ `leaseMs`-vs-`timeoutMs` check then compared them as strings (`'20' > '100'`),
302
+ so a lease shorter than its timeout was admitted and the concurrency limit
303
+ stopped holding.
304
+ - 7701c6a: `createSimplePoolNetwork`'s `onAuthFailed(relayUrl, error)` hook now also
305
+ reports NIP-42 AUTH failures from `subscription()`, on the initial open and on
306
+ every `autoReconnect` re-issue, with and without an `authSigner`: code
307
+ `auth-required` when no signer is configured and the relay answers
308
+ `CLOSED "auth-required: …"`, code `auth-failed` when the signer fails or the
309
+ relay refuses the signed AUTH event. It fires at most once per relay per
310
+ `subscribe()` call and socket. The observer and the reconnect behaviour are
311
+ unchanged (no `observer.error`, no attempt cap). With the hook supplied,
312
+ `subscription()` opens one SimplePool subscription per (relay, filter) pair, as
313
+ `autoReconnect` already does, and keeps cross-relay dedup itself. A failing
314
+ signer still stalls the subscription afterwards; that is an upstream
315
+ nostr-tools 2.23.x limitation (`AbstractRelay.auth()` never settles).
316
+ - a805f9c: `publishTimeoutMs` is now validated when the network is created, and an
317
+ invalid value throws `NetworkError` code `invalid-options`:
318
+
319
+ - `createSimplePoolNetwork` rejects `0`, negative values, `NaN`, non-numbers and
320
+ values above the `setTimeout` ceiling (2^31 - 1 ms). Before, `0` or a
321
+ negative value made every publish time out at once, and an oversized value
322
+ fired on the next tick. Here the deadline is the only backstop against a
323
+ nostr-tools AUTH hang, so it cannot be disabled.
324
+ - `createRawWebSocketNetwork` keeps its documented "`<= 0` disables the
325
+ deadline" meaning. It now rejects `NaN`, non-numbers and values above the
326
+ `setTimeout` ceiling.
327
+ - 996fc10: Export the types that public signatures already referenced, so the API docs build cleanly:
328
+
329
+ - `@941design/nostr-events/signer/nostr-connect`: `NostrConnectTransport` (the `transport` option of
330
+ `createNostrConnectSigner` and `listenForNostrConnect`; a `NostrNetworkInterface` or `TransportContract` satisfies it).
331
+ - `@941design/marmot`: `DeviceKeyRotationGroupOutcome` (`DeviceKeyRotationOutcome.perGroupOutcome`) and `JoinEvidence`
332
+ (`WindowNode.joinEvidence`). `OwnChangeLostReason` is now spelled out as a literal union (same members).
333
+
334
+ All notable changes to `nostr-events` are documented here. Versioning
335
+ follows semver; while at `0.x.y`, breaking changes may ship in minor
336
+ releases.
337
+
338
+ ## 0.0.0 — 2026-05-03
339
+
340
+ Initial pre-publish snapshot (not published to npm).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Markus Rother
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,122 @@
1
- # Temporary Holding Version
1
+ # nostr-events
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared Nostr protocol primitives — typed event surface, pluggable signer
4
+ interface, NIP-59 gift-wrap helpers, and transport abstractions. ESM-only,
5
+ browser-first, tree-shakable, zero runtime dependency on `applesauce-*`,
6
+ no module-global state, no WASM in the hot path.
7
+
8
+ The library sits **structurally below** `@internet-privacy/marmot-ts`: its
9
+ types are assignable to what marmot-ts already consumes, no marmot-ts
10
+ changes required.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @941design/nostr-events nostr-tools
16
+ # or npm / yarn / bun — nostr-tools is a peer dependency (>=2.23.0)
17
+ ```
18
+
19
+ ## Subpaths only
20
+
21
+ There is no root/default export — `import '@941design/nostr-events'` (bare, with no
22
+ subpath) rejects with `ERR_PACKAGE_PATH_NOT_EXPORTED`. Consumers import
23
+ only what they need from one of the subpaths below; each subpath
24
+ tree-shakes independently.
25
+
26
+ | Subpath | Surface |
27
+ | ------------------------------------ | ------------------------------------------------------------------------ |
28
+ | `@941design/nostr-events/event` | `Rumor`, `NostrEvent`, `EventTemplate`, `Filter`, validators, `getEventHash`, `verifyEvent`, `safeVerifyEvent`, `serializeEvent`, `stripEmptySig` |
29
+ | `@941design/nostr-events/clock` | `nowSeconds`, `MonotonicClock` |
30
+ | `@941design/nostr-events/signer` | `Signer` interface, `probeSigner`, `SignerError` |
31
+ | `@941design/nostr-events/signer/private-key` | `createPrivateKeySigner`, `secretKeyFromNsec` |
32
+ | `@941design/nostr-events/signer/extension` | `createExtensionSigner` (NIP-07) |
33
+ | `@941design/nostr-events/signer/nostr-connect` | `createNostrConnectSigner` (NIP-46 `bunker://` / hex remote), `createNostrConnectUri` + `listenForNostrConnect` (client-generated `nostrconnect://` sign-in) |
34
+ | `@941design/nostr-events/signer/capability` | `checkSignerCapabilities`, `CapabilityReport` |
35
+ | `@941design/nostr-events/gift-wrap` | `wrap`, `unwrap`, `seal`, `unseal`, `safeUnwrap`, `Result` |
36
+ | `@941design/nostr-events/transport` | `NostrNetworkInterface`, `Subscribable`, `Observer`, `PublishResponse`, `NetworkError` |
37
+ | `@941design/nostr-events/transport/raw-ws` | `createRawWebSocketNetwork` |
38
+ | `@941design/nostr-events/transport/simple-pool` | `createSimplePoolNetwork` (caller-owned `SimplePool`) |
39
+ | `@941design/nostr-events/transport/bounded` | `boundedRead`, finite verified matching reads with ingress and retention budgets |
40
+ | `@941design/nostr-events/transport/request` | `requestWithDeadline` |
41
+ | `@941design/nostr-events/transport/inbox-relays`| `fetchNip65InboxRelays`, `fetchNip17DmRelays` |
42
+ | `@941design/nostr-events/loaders` | `createAddressLoader`, `createEventLoader` (batched, re-verified lookups), `createTimelineLoader` (paged history) |
43
+ | `@941design/nostr-events/transport/reconnect` | `withReconnect`, `ExponentialBackoff` |
44
+ | `@941design/nostr-events/error` | `LibError` + subsystem subclasses, `formatError`, `Result` |
45
+ | `@941design/nostr-events/nip19` | NIP-19 codec re-exports from `nostr-tools/nip19` |
46
+ | `@941design/nostr-events/branded` | Opt-in nominal brands: `Hex32`, `Sig64`, `asHex32`, `tryAsHex32` |
47
+
48
+ ## Quick example — sign and gift-wrap a rumor
49
+
50
+ ```ts
51
+ import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
52
+ import { createPrivateKeySigner } from '@941design/nostr-events/signer/private-key';
53
+ import { wrap, unwrap } from '@941design/nostr-events/gift-wrap';
54
+ import { getEventHash } from '@941design/nostr-events/event';
55
+
56
+ const senderSk = generateSecretKey();
57
+ const recipientSk = generateSecretKey();
58
+ const sender = createPrivateKeySigner(senderSk);
59
+ const recipient = createPrivateKeySigner(recipientSk);
60
+
61
+ const rumor = {
62
+ pubkey: getPublicKey(senderSk),
63
+ kind: 1,
64
+ created_at: Math.floor(Date.now() / 1000),
65
+ tags: [],
66
+ content: 'hello',
67
+ id: '',
68
+ };
69
+ rumor.id = getEventHash(rumor);
70
+
71
+ const wrapped = await wrap({
72
+ senderSigner: sender,
73
+ recipientPubkey: getPublicKey(recipientSk),
74
+ rumor,
75
+ });
76
+
77
+ const { rumor: recovered, seal, wrap: outer } = await unwrap({
78
+ wrap: wrapped,
79
+ recipientSigner: recipient,
80
+ });
81
+ // recovered is byte-identical to the original rumor
82
+ ```
83
+
84
+ ## Cross-cutting invariants
85
+
86
+ These rules bind every part of the library:
87
+
88
+ - **Verbatim** — inner-event `Rumor` round-trips byte-for-byte.
89
+ - **Verify-asymmetry** — kind-13 seal sig is verified; kind-1059 wrap sig
90
+ is not (NIP-59 wraps are signed by ephemeral keys).
91
+ - **No module-global state** — every factory takes its dependencies as
92
+ parameters; multi-identity by construction.
93
+ - **No top-level browser-API access** — importing any subpath on Node /
94
+ during SSR will not throw.
95
+ - **No WASM** in the hot path; pure-JS dependencies only.
96
+ - **`LibError` discriminator** — every error thrown by the library extends
97
+ `LibError`. A single `if (err instanceof LibError)` catches everything.
98
+ - **No storage backends on the API surface** — storage is consumer
99
+ territory.
100
+ - **No kind allowlist on inner rumors** — the library never inspects
101
+ `rumor.kind` for filtering.
102
+
103
+ ## Status
104
+
105
+ Pre-1.0. Until `1.0.0`, treat every `0.x` minor release as a potential
106
+ breaking change — pin an exact version or a narrow range (e.g. `~0.3.0`),
107
+ not a caret range. This policy stays in force until the first consumer
108
+ applications have integrated and run in production for at least one minor
109
+ cycle. See
110
+ `CHANGELOG.md` for what actually shipped in each release.
111
+
112
+ ## License
113
+
114
+ MIT — see `LICENSE`.
115
+
116
+ ## Browser and local MCP runtimes
117
+
118
+ Browser applications import the core package directly. `@941design/nostr-mcp` is an optional separate Node adapter; core imports do not load its SDK or CLI. `@941design/nostr-events/transport/bounded` exports `boundedRead` for finite verified, filter-matching reads with explicit per-relay outcomes and incremental budgets. It owns its operation sockets and supports the existing `webSocketImpl` constructor contract. Explicit cancellation rejects with `NetworkError('aborted')`; deadline expiration returns valid partial results. Coverage always remains unknown.
119
+
120
+ The [installed runtime fixture](../../fixtures/runtime/README.md) runs signing, verification, NIP-59 round trips, finite queries and live subscription cleanup against a local deterministic relay in Node, Chromium and Firefox. Extension signing requires a browser NIP-07 provider (`window.nostr`); it cannot supply server identity. Private-key signing needs a caller-owned 32-byte key and Web Crypto randomness; NIP-46 needs an available WebSocket implementation, relay connectivity and a remote signer. Node >=22 supplies the required Web Crypto/WebSocket capabilities.
121
+
122
+ Raw subscriptions remain live after EOSE. Call synchronous idempotent `unsubscribe()` to release that subscription; the consumer owns injected socket/transport lifecycle. The MCP adapter supports operation-owned sockets rather than shared pools under strict ingress budgets. See its [configuration and compatibility reference](../nostr-mcp/README.md).
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Opt-in nominal brand for a 32-byte (64-char lowercase hex) value.
3
+ * Runtime representation is a plain string; the brand exists only at
4
+ * the type level. Plain `string` is not assignable to `Hex32` without
5
+ * passing through `asHex32` / `tryAsHex32`. Branded types are NOT the
6
+ * canonical shape of the library — most APIs accept plain string.
7
+ */
8
+ export type Hex32 = string & {
9
+ readonly __brand: 'Hex32';
10
+ };
11
+ /**
12
+ * Opt-in nominal brand for a 64-byte (128-char lowercase hex) Schnorr
13
+ * signature. Same opt-in contract as Hex32.
14
+ */
15
+ export type Sig64 = string & {
16
+ readonly __brand: 'Sig64';
17
+ };
18
+ /**
19
+ * Validates that `s` is a 64-char lowercase-hex string and returns it
20
+ * branded as Hex32. Throws CodecError('invalid-hex') otherwise. The
21
+ * thrown message NEVER echoes the rejected input (callers may pass
22
+ * private-key material by mistake).
23
+ */
24
+ export declare function asHex32(s: string): Hex32;
25
+ /**
26
+ * Non-throwing variant of asHex32. Returns the branded value on success
27
+ * or null on rejection. Useful in parsing pipelines where invalid input
28
+ * is expected and not exceptional.
29
+ */
30
+ export declare function tryAsHex32(s: string): Hex32 | null;
@@ -0,0 +1,22 @@
1
+ import { isHex32 } from '../event/index.js';
2
+ import { CodecError } from '../error/index.js';
3
+ /**
4
+ * Validates that `s` is a 64-char lowercase-hex string and returns it
5
+ * branded as Hex32. Throws CodecError('invalid-hex') otherwise. The
6
+ * thrown message NEVER echoes the rejected input (callers may pass
7
+ * private-key material by mistake).
8
+ */
9
+ export function asHex32(s) {
10
+ if (!isHex32(s)) {
11
+ throw new CodecError('invalid-hex', 'asHex32: input is not a 64-char lowercase-hex string');
12
+ }
13
+ return s;
14
+ }
15
+ /**
16
+ * Non-throwing variant of asHex32. Returns the branded value on success
17
+ * or null on rejection. Useful in parsing pipelines where invalid input
18
+ * is expected and not exceptional.
19
+ */
20
+ export function tryAsHex32(s) {
21
+ return isHex32(s) ? s : null;
22
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Returns the current Unix epoch in whole seconds. Wraps Date.now / 1000
3
+ * via floor; consumers wanting strictly monotonic timestamps within the
4
+ * same second should use MonotonicClock.
5
+ */
6
+ export declare function nowSeconds(): number;
7
+ /**
8
+ * Strictly monotonic seconds clock. now() is guaranteed to return a
9
+ * value greater than every previous return on the same instance, even
10
+ * across rapid in-loop calls within a single wall-clock second. Holds
11
+ * per-instance state only — there is no shared module-global clock.
12
+ *
13
+ * Caveat: under sustained calls faster than 1/sec, the returned value
14
+ * drifts ahead of wall-clock seconds and stays ahead until the wall
15
+ * clock passes it again (AC-TYPE-8: now() = max(prev + 1, wall)).
16
+ * Intended for NIP-style created_at sequencing — do not use as a true
17
+ * wall-clock timestamp.
18
+ */
19
+ export declare class MonotonicClock {
20
+ #private;
21
+ now(): number;
22
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Returns the current Unix epoch in whole seconds. Wraps Date.now / 1000
3
+ * via floor; consumers wanting strictly monotonic timestamps within the
4
+ * same second should use MonotonicClock.
5
+ */
6
+ export function nowSeconds() {
7
+ return Math.floor(Date.now() / 1000);
8
+ }
9
+ /**
10
+ * Strictly monotonic seconds clock. now() is guaranteed to return a
11
+ * value greater than every previous return on the same instance, even
12
+ * across rapid in-loop calls within a single wall-clock second. Holds
13
+ * per-instance state only — there is no shared module-global clock.
14
+ *
15
+ * Caveat: under sustained calls faster than 1/sec, the returned value
16
+ * drifts ahead of wall-clock seconds and stays ahead until the wall
17
+ * clock passes it again (AC-TYPE-8: now() = max(prev + 1, wall)).
18
+ * Intended for NIP-style created_at sequencing — do not use as a true
19
+ * wall-clock timestamp.
20
+ */
21
+ export class MonotonicClock {
22
+ #last = 0;
23
+ now() {
24
+ const wall = Math.floor(Date.now() / 1000);
25
+ const next = wall > this.#last ? wall : this.#last + 1;
26
+ this.#last = next;
27
+ return next;
28
+ }
29
+ }
@@ -0,0 +1,55 @@
1
+ export type SignerErrorCode = 'init' | 'timeout' | 'user-rejected' | 'cancelled' | 'unsupported-capability' | 'permission-denied' | 'key-unavailable' | 'invalid-template' | 'transport' | 'crypto' | 'auth-required' | 'disposed';
2
+ export type GiftWrapErrorCode = 'decrypt' | 'seal-decrypt' | 'seal-sig-invalid' | 'pubkey-mismatch' | 'id-mismatch' | 'malformed-seal' | 'malformed-rumor' | 'signer-incapable' | 'wrap-build-failed';
3
+ export type NetworkErrorCode = 'relay-timeout' | 'relay-error' | 'transport-error' | 'malformed-filter' | 'aborted' | 'auth-required' | 'auth-failed' | 'auth-timeout' | 'publish-timeout' | 'no-websocket' | 'invalid-options';
4
+ export type CodecErrorCode = 'malformed-event' | 'hash-mismatch' | 'invalid-hex' | 'invalid-tag-shape';
5
+ export type Subsystem = 'signer' | 'gift-wrap' | 'network' | 'codec';
6
+ export type Result<T, E> = {
7
+ ok: true;
8
+ value: T;
9
+ } | {
10
+ ok: false;
11
+ error: E;
12
+ };
13
+ export declare abstract class LibError extends Error {
14
+ abstract readonly subsystem: Subsystem;
15
+ abstract readonly code: string;
16
+ readonly cause?: unknown;
17
+ constructor(message: string, opts?: {
18
+ cause?: unknown;
19
+ });
20
+ }
21
+ export declare class SignerError extends LibError {
22
+ readonly subsystem: "signer";
23
+ readonly code: SignerErrorCode;
24
+ readonly details?: {
25
+ url?: string;
26
+ };
27
+ constructor(code: SignerErrorCode, message: string, opts?: {
28
+ cause?: unknown;
29
+ details?: {
30
+ url?: string;
31
+ };
32
+ });
33
+ }
34
+ export declare class GiftWrapError extends LibError {
35
+ readonly subsystem: "gift-wrap";
36
+ readonly code: GiftWrapErrorCode;
37
+ constructor(code: GiftWrapErrorCode, message: string, opts?: {
38
+ cause?: unknown;
39
+ });
40
+ }
41
+ export declare class NetworkError extends LibError {
42
+ readonly subsystem: "network";
43
+ readonly code: NetworkErrorCode;
44
+ constructor(code: NetworkErrorCode, message: string, opts?: {
45
+ cause?: unknown;
46
+ });
47
+ }
48
+ export declare class CodecError extends LibError {
49
+ readonly subsystem: "codec";
50
+ readonly code: CodecErrorCode;
51
+ constructor(code: CodecErrorCode, message: string, opts?: {
52
+ cause?: unknown;
53
+ });
54
+ }
55
+ export declare function formatError(err: unknown): string;