@nostrify/nostrify 0.48.1 → 0.48.3

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 (41) hide show
  1. package/.turbo/turbo-build.log +32 -32
  2. package/.turbo/turbo-typecheck.log +6 -0
  3. package/CHANGELOG.md +16 -0
  4. package/dist/tsconfig.tsbuildinfo +1 -1
  5. package/dist/uploaders/NostrBuildUploader.d.ts +1 -1
  6. package/dist/uploaders/NostrBuildUploader.d.ts.map +1 -1
  7. package/package.json +6 -2
  8. package/uploaders/NostrBuildUploader.ts +1 -1
  9. package/.turbo/turbo-setup.log +0 -13
  10. package/.turbo/turbo-test.log +0 -99
  11. package/dist/BunkerURI.ts +0 -58
  12. package/dist/NBrowserSigner.ts +0 -100
  13. package/dist/NCache.ts +0 -73
  14. package/dist/NConnectSigner.ts +0 -188
  15. package/dist/NIP05.ts +0 -51
  16. package/dist/NIP50.ts +0 -24
  17. package/dist/NIP98.ts +0 -111
  18. package/dist/NIP98Client.ts +0 -36
  19. package/dist/NKinds.ts +0 -26
  20. package/dist/NPool.ts +0 -243
  21. package/dist/NRelay1.ts +0 -447
  22. package/dist/NSchema.ts +0 -291
  23. package/dist/NSecSigner.ts +0 -62
  24. package/dist/NSet.ts +0 -210
  25. package/dist/RelayError.ts +0 -22
  26. package/dist/ln/LNURL.ts +0 -146
  27. package/dist/ln/mod.ts +0 -4
  28. package/dist/ln/types/LNURLCallback.ts +0 -7
  29. package/dist/ln/types/LNURLDetails.ts +0 -19
  30. package/dist/mod.ts +0 -17
  31. package/dist/test/ErrorRelay.ts +0 -52
  32. package/dist/test/MockRelay.ts +0 -92
  33. package/dist/test/TestRelayServer.ts +0 -185
  34. package/dist/test/mod.ts +0 -28
  35. package/dist/uploaders/BlossomUploader.ts +0 -100
  36. package/dist/uploaders/NostrBuildUploader.ts +0 -89
  37. package/dist/uploaders/mod.ts +0 -2
  38. package/dist/utils/CircularSet.ts +0 -36
  39. package/dist/utils/Machina.ts +0 -66
  40. package/dist/utils/N64.ts +0 -23
  41. package/dist/utils/mod.ts +0 -2
package/dist/NIP98.ts DELETED
@@ -1,111 +0,0 @@
1
- import type { NostrEvent } from "@nostrify/types";
2
- import { toHex } from "@smithy/util-hex-encoding";
3
- import { verifyEvent as _verifyEvent } from "nostr-tools";
4
-
5
- import { N64 } from "./utils/N64.ts";
6
-
7
- /** [NIP-98](https://github.com/nostr-protocol/nips/blob/master/98.md) HTTP auth. */
8
- export class NIP98 {
9
- /** Generate an auth event template from a Request. */
10
- static async template(
11
- request: Request,
12
- opts?: { validatePayload?: boolean },
13
- ): Promise<Omit<NostrEvent, "id" | "pubkey" | "sig">> {
14
- const {
15
- validatePayload = ["POST", "PUT", "PATCH"].includes(request.method),
16
- } = opts ?? {};
17
- const { method, url } = request;
18
-
19
- const tags = [
20
- ["method", method],
21
- ["u", url],
22
- ];
23
-
24
- if (validatePayload) {
25
- const buffer = await request.clone().arrayBuffer();
26
- const digest = await crypto.subtle.digest("SHA-256", buffer);
27
-
28
- tags.push(["payload", toHex(new Uint8Array(digest))]);
29
- }
30
-
31
- return {
32
- kind: 27235,
33
- content: "",
34
- tags,
35
- created_at: Math.floor(Date.now() / 1000),
36
- };
37
- }
38
-
39
- /** Compare the auth event with the request, throwing a human-readable error if validation fails. */
40
- static async verify(
41
- request: Request,
42
- opts?: {
43
- maxAge?: number;
44
- validatePayload?: boolean;
45
- verifyEvent?: (event: NostrEvent) => boolean;
46
- },
47
- ): Promise<NostrEvent> {
48
- const {
49
- maxAge = 60_000,
50
- validatePayload = ["POST", "PUT", "PATCH"].includes(request.method),
51
- verifyEvent = _verifyEvent,
52
- } = opts ?? {};
53
-
54
- const header = request.headers.get("authorization");
55
- if (!header) {
56
- throw new Error("Missing Nostr authorization header");
57
- }
58
-
59
- const token = header.match(/^Nostr (.+)$/)?.[1];
60
- if (!token) {
61
- throw new Error("Missing Nostr authorization token");
62
- }
63
-
64
- let event: NostrEvent;
65
- try {
66
- event = N64.decodeEvent(token);
67
- } catch (e) {
68
- if (
69
- e instanceof TypeError &&
70
- e.message.includes("Incorrect padding on base64")
71
- ) {
72
- throw new Error("Invalid token");
73
- } else {
74
- throw e;
75
- }
76
- }
77
-
78
- if (!verifyEvent(event)) {
79
- throw new Error("Event signature is invalid");
80
- }
81
-
82
- const age = Date.now() - (event.created_at * 1_000);
83
- const u = event.tags.find(([name]) => name === "u")?.[1];
84
- const method = event.tags.find(([name]) => name === "method")?.[1];
85
- const payload = event.tags.find(([name]) => name === "payload")?.[1];
86
-
87
- if (event.kind !== 27235) {
88
- throw new Error("Event must be kind 27235");
89
- }
90
- if (u !== request.url) {
91
- throw new Error("Event URL does not match request URL");
92
- }
93
- if (method !== request.method) {
94
- throw new Error("Event method does not match HTTP request method");
95
- }
96
- if (age >= maxAge) {
97
- throw new Error("Event expired");
98
- }
99
- if (validatePayload && payload !== undefined) {
100
- const buffer = await request.clone().arrayBuffer();
101
- const digest = await crypto.subtle.digest("SHA-256", buffer);
102
- const hexed = toHex(new Uint8Array(digest));
103
-
104
- if (hexed !== payload) {
105
- throw new Error("Event payload does not match request body");
106
- }
107
- }
108
-
109
- return event;
110
- }
111
- }
@@ -1,36 +0,0 @@
1
- import { type NostrSigner } from '@nostrify/types';
2
- import { NIP98 } from './NIP98.ts';
3
- import { N64 } from './utils/N64.ts';
4
-
5
- export interface NIP98ClientOpts {
6
- signer: NostrSigner;
7
- fetch?: typeof globalThis.fetch;
8
- }
9
-
10
- /** Wraps a fetch request with NIP98 authentication */
11
- export class NIP98Client {
12
- private signer: NostrSigner;
13
- private customFetch: typeof globalThis.fetch;
14
-
15
- constructor(opts: NIP98ClientOpts) {
16
- this.signer = opts.signer;
17
- this.customFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
18
- }
19
-
20
- /** Performs a fetch request with NIP98 authentication */
21
- async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
22
- // Normalize to a Request object
23
- const request = new Request(input, init);
24
-
25
- // Create the NIP98 token
26
- const template = await NIP98.template(request);
27
- const event = await this.signer.signEvent(template);
28
- const token = N64.encodeEvent(event);
29
-
30
- // Add the Authorization header
31
- request.headers.set('Authorization', `Nostr ${token}`);
32
-
33
- // Call the custom fetch function
34
- return this.customFetch(request);
35
- }
36
- }
package/dist/NKinds.ts DELETED
@@ -1,26 +0,0 @@
1
- export class NKinds {
2
- /** Events are **regular**, which means they're all expected to be stored by relays. */
3
- static regular(kind: number): boolean {
4
- return (1000 <= kind && kind < 10000) || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind);
5
- }
6
-
7
- /** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */
8
- static replaceable(kind: number): boolean {
9
- return (10000 <= kind && kind < 20000) || [0, 3].includes(kind);
10
- }
11
-
12
- /** Events are **ephemeral**, which means they are not expected to be stored by relays. */
13
- static ephemeral(kind: number): boolean {
14
- return 20000 <= kind && kind < 30000;
15
- }
16
-
17
- /** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */
18
- static addressable(kind: number): boolean {
19
- return 30000 <= kind && kind < 40000;
20
- }
21
-
22
- /** @deprecated Use `NKinds.addressable()` instead. */
23
- static parameterizedReplaceable(kind: number): boolean {
24
- return NKinds.addressable(kind);
25
- }
26
- }
package/dist/NPool.ts DELETED
@@ -1,243 +0,0 @@
1
- import type {
2
- NostrEvent,
3
- NostrFilter,
4
- NostrRelayCLOSED,
5
- NostrRelayEOSE,
6
- NostrRelayEVENT,
7
- NRelay,
8
- } from '@nostrify/types';
9
- import { getFilterLimit } from 'nostr-tools';
10
-
11
- import { CircularSet } from './utils/CircularSet.ts';
12
- import { Machina } from './utils/Machina.ts';
13
- import { NSet } from './NSet.ts';
14
-
15
- export interface NPoolOpts<T extends NRelay> {
16
- /** Creates an `NRelay` instance for the given URL. */
17
- open(url: string): T;
18
- /** Determines the relays to use for making `REQ`s to the given filters. To support the Outbox model, it should analyze the `authors` field of the filters. */
19
- reqRouter(
20
- filters: NostrFilter[],
21
- ):
22
- | ReadonlyMap<string, NostrFilter[]>
23
- | Promise<ReadonlyMap<string, NostrFilter[]>>;
24
- /** Determines the relays to use for publishing the given event. To support the Outbox model, it should analyze the `pubkey` field of the event. */
25
- eventRouter(event: NostrEvent): string[] | Promise<string[]>;
26
- }
27
-
28
- /**
29
- * The `NPool` class is a `NRelay` implementation for connecting to multiple relays.
30
- *
31
- * ```ts
32
- * const pool = new NPool({
33
- * open: (url) => new NRelay1(url),
34
- * reqRouter: async (filters) => new Map([
35
- * ['wss://relay1.mostr.pub', filters],
36
- * ['wss://relay2.mostr.pub', filters],
37
- * ]),
38
- * eventRouter: async (event) => ['wss://relay1.mostr.pub', 'wss://relay2.mostr.pub'],
39
- * });
40
- *
41
- * // Now you can use the pool like a regular relay.
42
- * for await (const msg of pool.req([{ kinds: [1] }])) {
43
- * if (msg[0] === 'EVENT') console.log(msg[2]);
44
- * if (msg[0] === 'EOSE') break;
45
- * }
46
- * ```
47
- *
48
- * This class is designed with the Outbox model in mind.
49
- * Instead of passing relay URLs into each method, you pass functions into the contructor that statically-analyze filters and events to determine which relays to use for requesting and publishing events.
50
- * If a relay wasn't already connected, it will be opened automatically.
51
- * Defining `open` will also let you use any relay implementation, such as `NRelay1`.
52
- *
53
- * Note that `pool.req` may stream duplicate events, while `pool.query` will correctly process replaceable events and deletions within the event set before returning them.
54
- *
55
- * `pool.req` will only emit an `EOSE` when all relays in its set have emitted an `EOSE`, and likewise for `CLOSED`.
56
- */
57
- export class NPool<T extends NRelay = NRelay> implements NRelay {
58
- private _relays = new Map<string, T>();
59
- private opts: NPoolOpts<T>;
60
-
61
- constructor(opts: NPoolOpts<T>) {
62
- this.opts = opts;
63
- }
64
-
65
- /** Get or create a relay instance for the given URL. */
66
- public relay(url: string): T {
67
- const relay = this._relays.get(url);
68
-
69
- if (relay) {
70
- return relay;
71
- } else {
72
- const relay = this.opts.open(url);
73
- this._relays.set(url, relay);
74
- return relay;
75
- }
76
- }
77
-
78
- /** Returns a new pool instance that uses the given relays. Connections are shared with the original pool. */
79
- public group(urls: string[]): NPool<T> {
80
- return new NPool({
81
- open: (url) => this.relay(url),
82
- reqRouter: (filters) => new Map(urls.map((url) => [url, filters])),
83
- eventRouter: () => urls,
84
- });
85
- }
86
-
87
- public get relays(): ReadonlyMap<string, T> {
88
- return this._relays;
89
- }
90
-
91
- /**
92
- * Sends a `REQ` to relays based on the configured `reqRouter`.
93
- *
94
- * `EVENT` messages from the selected relays are yielded.
95
- * `EOSE` and `CLOSE` messages are only yielded when all relays have emitted them.
96
- *
97
- * Deduplication of `EVENT` messages is attempted, so that each event is only yielded once.
98
- * A circular set of 1000 is used to track seen event IDs, so it's possible that very
99
- * long-running subscriptions (with over 1000 results) may yield duplicate events.
100
- */
101
- async *req(
102
- filters: NostrFilter[],
103
- opts?: { signal?: AbortSignal; relays?: string[] },
104
- ): AsyncIterable<NostrRelayEVENT | NostrRelayEOSE | NostrRelayCLOSED> {
105
- const controller = new AbortController();
106
- const signal = opts?.signal ? AbortSignal.any([opts.signal, controller.signal]) : controller.signal;
107
-
108
- const routes = opts?.relays
109
- ? new Map(opts.relays.map((url) => [url, filters]))
110
- : await this.opts.reqRouter(filters);
111
-
112
- if (routes.size < 1) {
113
- return;
114
- }
115
-
116
- const machina = new Machina<
117
- NostrRelayEVENT | NostrRelayEOSE | NostrRelayCLOSED
118
- >(signal);
119
-
120
- const eoses = new Set<string>();
121
- const closes = new Set<string>();
122
- const events = new CircularSet<string>(1000);
123
-
124
- const relayPromises: Promise<void>[] = [];
125
-
126
- for (const [url, filters] of routes.entries()) {
127
- const relay = this.relay(url);
128
- const relayPromise = (async () => {
129
- try {
130
- for await (const msg of relay.req(filters, { signal })) {
131
- if (msg[0] === 'EOSE') {
132
- eoses.add(url);
133
- if (eoses.size === routes.size) {
134
- machina.push(msg);
135
- }
136
- }
137
- if (msg[0] === 'CLOSED') {
138
- closes.add(url);
139
- if (closes.size === routes.size) {
140
- machina.push(msg);
141
- }
142
- }
143
- if (msg[0] === 'EVENT') {
144
- const [, , event] = msg;
145
- if (!events.has(event.id)) {
146
- events.add(event.id);
147
- machina.push(msg);
148
- }
149
- }
150
- }
151
- } catch {
152
- // Handle errors silently
153
- }
154
- })();
155
- relayPromises.push(relayPromise);
156
- }
157
-
158
- try {
159
- for await (const msg of machina) {
160
- yield msg;
161
- }
162
- } finally {
163
- controller.abort();
164
- // Wait for all relay promises to complete to prevent hanging promises
165
- await Promise.allSettled(relayPromises);
166
- }
167
- }
168
-
169
- /**
170
- * Events are sent to relays according to the `eventRouter`.
171
- * Returns a fulfilled promise if ANY relay accepted the event,
172
- * or a rejected promise if ALL relays rejected or failed to publish the event.
173
- */
174
- async event(
175
- event: NostrEvent,
176
- opts?: { signal?: AbortSignal; relays?: string[] },
177
- ): Promise<void> {
178
- const relayUrls = opts?.relays ?? await this.opts.eventRouter(event);
179
-
180
- if (!relayUrls.length) {
181
- return;
182
- }
183
-
184
- // @ts-ignore Promise.any exists for sure
185
- await Promise.any(
186
- relayUrls.map((url) => this.relay(url).event(event, opts)),
187
- );
188
- }
189
-
190
- /**
191
- * This method calls `.req` internally and then post-processes the results.
192
- * Please read the definition of `.req`.
193
- *
194
- * - The strategy is to seek regular events quickly, and to wait to find the latest versions of replaceable events.
195
- * - Filters for replaceable events will wait for all relays to `EOSE` (or `CLOSE`, or for the signal to be aborted) to ensure the latest event versions are retrieved.
196
- * - Filters for regular events will stop as soon as the filters are fulfilled.
197
- * - Events are deduplicated, sorted, and only the latest version of replaceable events is kept.
198
- * - If the signal is aborted, this method will return partial results instead of throwing.
199
- *
200
- * To implement a custom strategy, call `.req` directly.
201
- */
202
- async query(
203
- filters: NostrFilter[],
204
- opts?: { signal?: AbortSignal; relays?: string[] },
205
- ): Promise<NostrEvent[]> {
206
- const map = new Map<string, NostrEvent>();
207
- const events = new NSet(map);
208
-
209
- const limit = filters.reduce(
210
- (result, filter) => result + getFilterLimit(filter),
211
- 0,
212
- );
213
- if (limit === 0) return [];
214
-
215
- try {
216
- for await (const msg of this.req(filters, opts)) {
217
- if (msg[0] === 'EOSE') break;
218
- if (msg[0] === 'EVENT') events.add(msg[2]);
219
- if (msg[0] === 'CLOSED') break;
220
- }
221
- } catch {
222
- // Skip errors, return partial results.
223
- }
224
-
225
- // Don't sort results of search filters.
226
- if (filters.some((filter) => typeof filter.search === 'string')) {
227
- return [...map.values()];
228
- } else {
229
- return [...events];
230
- }
231
- }
232
-
233
- /** Close all the relays in the pool. */
234
- async close(): Promise<void> {
235
- await Promise.all(
236
- [...this._relays.values()].map((relay) => relay.close()),
237
- );
238
- }
239
-
240
- async [Symbol.asyncDispose](): Promise<void> {
241
- await this.close();
242
- }
243
- }