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