@941design/nostr-events 0.2.0-alpha.0 → 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.
- package/CHANGELOG.md +7 -0
- package/README.md +32 -23
- package/dist/transport/bounded/index.d.ts +50 -0
- package/dist/transport/bounded/index.js +360 -0
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
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
|
+
|
|
3
10
|
## 0.2.0-alpha.0
|
|
4
11
|
|
|
5
12
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -12,45 +12,46 @@ changes required.
|
|
|
12
12
|
## Install
|
|
13
13
|
|
|
14
14
|
```sh
|
|
15
|
-
pnpm add nostr-events nostr-tools
|
|
15
|
+
pnpm add @941design/nostr-events nostr-tools
|
|
16
16
|
# or npm / yarn / bun — nostr-tools is a peer dependency (>=2.23.0)
|
|
17
17
|
```
|
|
18
18
|
|
|
19
19
|
## Subpaths only
|
|
20
20
|
|
|
21
|
-
There is no root/default export — `import 'nostr-events'` (bare, with no
|
|
21
|
+
There is no root/default export — `import '@941design/nostr-events'` (bare, with no
|
|
22
22
|
subpath) rejects with `ERR_PACKAGE_PATH_NOT_EXPORTED`. Consumers import
|
|
23
23
|
only what they need from one of the subpaths below; each subpath
|
|
24
24
|
tree-shakes independently.
|
|
25
25
|
|
|
26
26
|
| Subpath | Surface |
|
|
27
27
|
| ------------------------------------ | ------------------------------------------------------------------------ |
|
|
28
|
-
|
|
|
29
|
-
|
|
|
30
|
-
|
|
|
31
|
-
|
|
|
32
|
-
|
|
|
33
|
-
|
|
|
34
|
-
|
|
|
35
|
-
|
|
|
36
|
-
|
|
|
37
|
-
|
|
|
38
|
-
|
|
|
39
|
-
|
|
|
40
|
-
|
|
|
41
|
-
|
|
|
42
|
-
|
|
|
43
|
-
|
|
|
44
|
-
|
|
|
45
|
-
|
|
|
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` |
|
|
46
47
|
|
|
47
48
|
## Quick example — sign and gift-wrap a rumor
|
|
48
49
|
|
|
49
50
|
```ts
|
|
50
51
|
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';
|
|
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';
|
|
54
55
|
|
|
55
56
|
const senderSk = generateSecretKey();
|
|
56
57
|
const recipientSk = generateSecretKey();
|
|
@@ -111,3 +112,11 @@ cycle. See
|
|
|
111
112
|
## License
|
|
112
113
|
|
|
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,50 @@
|
|
|
1
|
+
/** Finite reads with application-level ingress and retention budgets.
|
|
2
|
+
* Each call owns its sockets; no shared pool is closed. WebSocket implementations
|
|
3
|
+
* may allocate a complete message before this code can inspect its size.
|
|
4
|
+
*/
|
|
5
|
+
import { NetworkError } from "../../error/index.js";
|
|
6
|
+
import { type Filter, type NostrEvent } from "../../event/index.js";
|
|
7
|
+
import type { WebSocketImpl } from "../raw-ws/index.js";
|
|
8
|
+
export interface ReadLimits {
|
|
9
|
+
events: number;
|
|
10
|
+
timeoutMs: number;
|
|
11
|
+
frameBytes: number;
|
|
12
|
+
ingressBytes: number;
|
|
13
|
+
candidates: number;
|
|
14
|
+
responseBytes: number;
|
|
15
|
+
}
|
|
16
|
+
export type StopReason = "eose" | "timeout" | "event_limit" | "byte_limit" | "scan_limit" | "relay_error";
|
|
17
|
+
export type RelayStatus = {
|
|
18
|
+
status: "eose" | "timeout" | "failed" | "cancelled";
|
|
19
|
+
};
|
|
20
|
+
export interface BoundedReadResult {
|
|
21
|
+
schemaVersion: "1";
|
|
22
|
+
events: NostrEvent[];
|
|
23
|
+
limits: ReadLimits;
|
|
24
|
+
stopReason: StopReason;
|
|
25
|
+
timedOut: boolean;
|
|
26
|
+
truncated: boolean;
|
|
27
|
+
coverage: "unknown";
|
|
28
|
+
relays: Record<string, RelayStatus>;
|
|
29
|
+
provenance: Record<string, string[]>;
|
|
30
|
+
metrics: {
|
|
31
|
+
candidates: number;
|
|
32
|
+
ingressBytes: number;
|
|
33
|
+
retainedBytes: number;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export declare class BoundedReadError extends NetworkError {
|
|
37
|
+
readonly relays: Record<string, RelayStatus>;
|
|
38
|
+
constructor(relays: Record<string, RelayStatus>);
|
|
39
|
+
}
|
|
40
|
+
export interface BoundedReadOptions {
|
|
41
|
+
relays: Record<string, string>;
|
|
42
|
+
filter: Filter;
|
|
43
|
+
limits: ReadLimits;
|
|
44
|
+
signal?: AbortSignal;
|
|
45
|
+
webSocketImpl?: WebSocketImpl;
|
|
46
|
+
}
|
|
47
|
+
/** Includes both MCP representations and conservative protocol/metadata headroom. */
|
|
48
|
+
export declare function readResponseBytes(result: unknown): number;
|
|
49
|
+
export declare function matchesReadFilter(event: NostrEvent, filter: Filter): boolean;
|
|
50
|
+
export declare function boundedRead(options: BoundedReadOptions): Promise<BoundedReadResult>;
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/** Finite reads with application-level ingress and retention budgets.
|
|
2
|
+
* Each call owns its sockets; no shared pool is closed. WebSocket implementations
|
|
3
|
+
* may allocate a complete message before this code can inspect its size.
|
|
4
|
+
*/
|
|
5
|
+
import { NetworkError } from "../../error/index.js";
|
|
6
|
+
import { safeVerifyEvent, } from "../../event/index.js";
|
|
7
|
+
export class BoundedReadError extends NetworkError {
|
|
8
|
+
relays;
|
|
9
|
+
constructor(relays) {
|
|
10
|
+
super("relay-error", "Configured relays are unavailable. Retry later.");
|
|
11
|
+
this.relays = relays;
|
|
12
|
+
this.name = "BoundedReadError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const encoder = new TextEncoder();
|
|
16
|
+
const bytes = (value) => encoder.encode(value).byteLength;
|
|
17
|
+
// A JSON fragment occurs once in structuredContent and once inside the textual
|
|
18
|
+
// fallback's JSON string. Escaping cost is compositional across fragments.
|
|
19
|
+
const responseFragmentBytes = (json) => bytes(json) + bytes(JSON.stringify(json)) - 2;
|
|
20
|
+
/** Includes both MCP representations and conservative protocol/metadata headroom. */
|
|
21
|
+
export function readResponseBytes(result) {
|
|
22
|
+
return bytes(JSON.stringify({
|
|
23
|
+
result: {
|
|
24
|
+
structuredContent: result,
|
|
25
|
+
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
26
|
+
},
|
|
27
|
+
jsonrpc: "2.0",
|
|
28
|
+
id: "x".repeat(256),
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
export function matchesReadFilter(event, filter) {
|
|
32
|
+
if (filter.ids && !filter.ids.includes(event.id))
|
|
33
|
+
return false;
|
|
34
|
+
if (filter.authors && !filter.authors.includes(event.pubkey))
|
|
35
|
+
return false;
|
|
36
|
+
if (filter.kinds && !filter.kinds.includes(event.kind))
|
|
37
|
+
return false;
|
|
38
|
+
if (filter.since !== undefined && event.created_at < filter.since)
|
|
39
|
+
return false;
|
|
40
|
+
if (filter.until !== undefined && event.created_at > filter.until)
|
|
41
|
+
return false;
|
|
42
|
+
for (const [key, values] of Object.entries(filter)) {
|
|
43
|
+
if (key.startsWith("#") &&
|
|
44
|
+
Array.isArray(values) &&
|
|
45
|
+
!event.tags.some((tag) => tag[0] === key.slice(1) && values.includes(tag[1])))
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
const priority = {
|
|
51
|
+
byte_limit: 6,
|
|
52
|
+
scan_limit: 5,
|
|
53
|
+
event_limit: 4,
|
|
54
|
+
timeout: 3,
|
|
55
|
+
relay_error: 2,
|
|
56
|
+
eose: 1,
|
|
57
|
+
};
|
|
58
|
+
function aborted() {
|
|
59
|
+
return new NetworkError("aborted", "Read cancelled");
|
|
60
|
+
}
|
|
61
|
+
export async function boundedRead(options) {
|
|
62
|
+
const { filter, signal } = options;
|
|
63
|
+
const limits = {
|
|
64
|
+
...options.limits,
|
|
65
|
+
events: Math.min(options.limits.events, options.filter.limit ?? options.limits.events),
|
|
66
|
+
};
|
|
67
|
+
if (Object.values(limits).some((value) => !Number.isSafeInteger(value) || value <= 0) ||
|
|
68
|
+
limits.timeoutMs > 2_147_483_647)
|
|
69
|
+
throw new NetworkError("invalid-options", "Read budgets must be positive safe integers");
|
|
70
|
+
if (signal?.aborted)
|
|
71
|
+
throw aborted();
|
|
72
|
+
const WebSocketClass = options.webSocketImpl ?? globalThis.WebSocket;
|
|
73
|
+
if (!WebSocketClass)
|
|
74
|
+
throw new NetworkError("no-websocket", "WebSocket capability is required; supply webSocketImpl");
|
|
75
|
+
const entries = Object.entries(options.relays);
|
|
76
|
+
if (entries.length === 0)
|
|
77
|
+
throw new NetworkError("invalid-options", "At least one relay is required");
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
const relays = Object.create(null);
|
|
80
|
+
const events = new Map();
|
|
81
|
+
const provenance = Object.create(null);
|
|
82
|
+
const sockets = [];
|
|
83
|
+
const metrics = { candidates: 0, ingressBytes: 0, retainedBytes: 0 };
|
|
84
|
+
let done = false;
|
|
85
|
+
let requested;
|
|
86
|
+
let timer;
|
|
87
|
+
const makeResult = (reason) => ({
|
|
88
|
+
schemaVersion: "1",
|
|
89
|
+
events: [...events.values()].sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id)),
|
|
90
|
+
limits,
|
|
91
|
+
stopReason: reason,
|
|
92
|
+
timedOut: reason === "timeout",
|
|
93
|
+
truncated: ["byte_limit", "scan_limit", "event_limit"].includes(reason),
|
|
94
|
+
coverage: "unknown",
|
|
95
|
+
relays,
|
|
96
|
+
provenance,
|
|
97
|
+
metrics,
|
|
98
|
+
});
|
|
99
|
+
const cleanup = () => {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
signal?.removeEventListener("abort", onAbort);
|
|
102
|
+
for (const { socket, listeners } of sockets) {
|
|
103
|
+
const removable = socket;
|
|
104
|
+
for (const [type, listener] of listeners)
|
|
105
|
+
removable.removeEventListener?.(type, listener);
|
|
106
|
+
try {
|
|
107
|
+
if (socket.readyState === 1)
|
|
108
|
+
socket.send(JSON.stringify(["CLOSE", "bounded"]));
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
/* cleanup */
|
|
112
|
+
}
|
|
113
|
+
// Node's ws emits an asynchronous error when close interrupts a handshake.
|
|
114
|
+
// Keep a temporary sink until close; all operation callbacks are detached.
|
|
115
|
+
if (socket.readyState === 0) {
|
|
116
|
+
const ignore = () => { };
|
|
117
|
+
const detached = () => {
|
|
118
|
+
removable.removeEventListener?.("error", ignore);
|
|
119
|
+
removable.removeEventListener?.("close", detached);
|
|
120
|
+
};
|
|
121
|
+
socket.addEventListener("error", ignore);
|
|
122
|
+
socket.addEventListener("close", detached);
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
socket.close();
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
/* cleanup */
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
const settle = () => {
|
|
133
|
+
if (done || !requested)
|
|
134
|
+
return;
|
|
135
|
+
done = true;
|
|
136
|
+
for (const [id] of entries)
|
|
137
|
+
relays[id] ??= {
|
|
138
|
+
status: requested === "timeout" ? "timeout" : "cancelled",
|
|
139
|
+
};
|
|
140
|
+
cleanup();
|
|
141
|
+
if (Object.values(relays).every((value) => value.status === "failed") &&
|
|
142
|
+
events.size === 0)
|
|
143
|
+
reject(new BoundedReadError(relays));
|
|
144
|
+
else
|
|
145
|
+
resolve(makeResult(requested));
|
|
146
|
+
};
|
|
147
|
+
const stop = (reason) => {
|
|
148
|
+
if (done)
|
|
149
|
+
return;
|
|
150
|
+
if (!requested || priority[reason] > priority[requested])
|
|
151
|
+
requested = reason;
|
|
152
|
+
queueMicrotask(settle);
|
|
153
|
+
};
|
|
154
|
+
const onAbort = () => {
|
|
155
|
+
if (done)
|
|
156
|
+
return;
|
|
157
|
+
done = true;
|
|
158
|
+
cleanup();
|
|
159
|
+
reject(aborted());
|
|
160
|
+
};
|
|
161
|
+
const completed = () => {
|
|
162
|
+
if (entries.every(([id]) => relays[id]))
|
|
163
|
+
stop(Object.values(relays).some((value) => value.status === "failed")
|
|
164
|
+
? "relay_error"
|
|
165
|
+
: "eose");
|
|
166
|
+
};
|
|
167
|
+
// Reserve worst-case status, provenance, metrics, and protocol fields before connecting.
|
|
168
|
+
const reserve = 4096 +
|
|
169
|
+
entries.reduce((sum, [id]) => sum + bytes(JSON.stringify(id)) * 8, 0);
|
|
170
|
+
// Metadata maxima cover changing decimal counters, relay states and racing
|
|
171
|
+
// stop reasons. Event/provenance payloads are then charged exactly once.
|
|
172
|
+
let responseBytes = readResponseBytes({
|
|
173
|
+
schemaVersion: "1",
|
|
174
|
+
events: [],
|
|
175
|
+
limits,
|
|
176
|
+
stopReason: "event_limit",
|
|
177
|
+
timedOut: false,
|
|
178
|
+
truncated: false,
|
|
179
|
+
coverage: "unknown",
|
|
180
|
+
relays: Object.fromEntries(entries.map(([id]) => [id, { status: "cancelled" }])),
|
|
181
|
+
provenance: {},
|
|
182
|
+
metrics: {
|
|
183
|
+
candidates: limits.candidates,
|
|
184
|
+
ingressBytes: limits.ingressBytes,
|
|
185
|
+
retainedBytes: limits.responseBytes,
|
|
186
|
+
},
|
|
187
|
+
}) + reserve;
|
|
188
|
+
if (limits.responseBytes < responseBytes) {
|
|
189
|
+
reject(new NetworkError("invalid-options", "Response budget cannot contain metadata"));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
timer = setTimeout(() => stop("timeout"), limits.timeoutMs);
|
|
193
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
194
|
+
for (const [id, url] of entries) {
|
|
195
|
+
if (done || requested)
|
|
196
|
+
break;
|
|
197
|
+
let socket;
|
|
198
|
+
try {
|
|
199
|
+
socket = new WebSocketClass(url);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
relays[id] = { status: "failed" };
|
|
203
|
+
completed();
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const listeners = [];
|
|
207
|
+
sockets.push({ socket, listeners });
|
|
208
|
+
const add = (type, listener) => {
|
|
209
|
+
listeners.push([type, listener]);
|
|
210
|
+
socket.addEventListener(type, listener);
|
|
211
|
+
};
|
|
212
|
+
const fail = () => {
|
|
213
|
+
if (done || requested || relays[id])
|
|
214
|
+
return;
|
|
215
|
+
relays[id] = { status: "failed" };
|
|
216
|
+
completed();
|
|
217
|
+
};
|
|
218
|
+
add("open", () => {
|
|
219
|
+
if (done || requested || relays[id])
|
|
220
|
+
return;
|
|
221
|
+
try {
|
|
222
|
+
socket.send(JSON.stringify([
|
|
223
|
+
"REQ",
|
|
224
|
+
"bounded",
|
|
225
|
+
{ ...filter, limit: limits.events },
|
|
226
|
+
]));
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
fail();
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
add("close", fail);
|
|
233
|
+
add("error", ((event) => {
|
|
234
|
+
if (done || relays[id])
|
|
235
|
+
return;
|
|
236
|
+
// Optional transport-level payload rejection, e.g. Node ws maxPayload.
|
|
237
|
+
// WHATWG ErrorEvent wraps the original error in its `error` property.
|
|
238
|
+
const error = event;
|
|
239
|
+
if (error?.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ||
|
|
240
|
+
error?.error?.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")
|
|
241
|
+
stop("byte_limit");
|
|
242
|
+
else
|
|
243
|
+
fail();
|
|
244
|
+
}));
|
|
245
|
+
add("message", ((message) => {
|
|
246
|
+
if (done || requested || relays[id])
|
|
247
|
+
return;
|
|
248
|
+
let raw;
|
|
249
|
+
let frameBytes;
|
|
250
|
+
const exceedsIngress = (size) => size > limits.frameBytes ||
|
|
251
|
+
size > limits.ingressBytes - metrics.ingressBytes;
|
|
252
|
+
if (typeof message.data === "string") {
|
|
253
|
+
raw = message.data;
|
|
254
|
+
frameBytes = bytes(raw);
|
|
255
|
+
}
|
|
256
|
+
else if (message.data instanceof ArrayBuffer ||
|
|
257
|
+
ArrayBuffer.isView(message.data)) {
|
|
258
|
+
// Inspect binary size before decoding allocates a second full frame.
|
|
259
|
+
frameBytes = message.data.byteLength;
|
|
260
|
+
if (exceedsIngress(frameBytes)) {
|
|
261
|
+
stop("byte_limit");
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
raw = new TextDecoder().decode(message.data);
|
|
265
|
+
}
|
|
266
|
+
else {
|
|
267
|
+
stop("byte_limit");
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
// Count original wire bytes before parse, without growing retained state.
|
|
271
|
+
if (exceedsIngress(frameBytes)) {
|
|
272
|
+
stop("byte_limit");
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
metrics.ingressBytes += frameBytes;
|
|
276
|
+
let frame;
|
|
277
|
+
try {
|
|
278
|
+
frame = JSON.parse(raw);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (!Array.isArray(frame) || frame[1] !== "bounded")
|
|
284
|
+
return;
|
|
285
|
+
if (frame[0] === "EOSE") {
|
|
286
|
+
relays[id] = { status: "eose" };
|
|
287
|
+
completed();
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if (frame[0] === "CLOSED") {
|
|
291
|
+
fail();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (frame[0] !== "EVENT")
|
|
295
|
+
return;
|
|
296
|
+
if (metrics.candidates >= limits.candidates) {
|
|
297
|
+
stop("scan_limit");
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
metrics.candidates++;
|
|
301
|
+
const candidate = frame[2];
|
|
302
|
+
if (!safeVerifyEvent(candidate) ||
|
|
303
|
+
!Number.isSafeInteger(candidate.kind) ||
|
|
304
|
+
candidate.kind < 0 ||
|
|
305
|
+
!Number.isSafeInteger(candidate.created_at) ||
|
|
306
|
+
candidate.created_at < 0 ||
|
|
307
|
+
!matchesReadFilter(candidate, filter)) {
|
|
308
|
+
if (metrics.candidates === limits.candidates)
|
|
309
|
+
stop("scan_limit");
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
// Only the seven signed NIP-01 fields cross the retention boundary.
|
|
313
|
+
// Relay-supplied extension properties are not part of the signed event.
|
|
314
|
+
const event = {
|
|
315
|
+
id: candidate.id,
|
|
316
|
+
pubkey: candidate.pubkey,
|
|
317
|
+
kind: candidate.kind,
|
|
318
|
+
created_at: candidate.created_at,
|
|
319
|
+
tags: candidate.tags,
|
|
320
|
+
content: candidate.content,
|
|
321
|
+
sig: candidate.sig,
|
|
322
|
+
};
|
|
323
|
+
if (events.has(event.id)) {
|
|
324
|
+
if (!provenance[event.id].includes(id)) {
|
|
325
|
+
const addition = responseFragmentBytes("," + JSON.stringify(id));
|
|
326
|
+
if (responseBytes + addition > limits.responseBytes) {
|
|
327
|
+
stop("byte_limit");
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
provenance[event.id].push(id);
|
|
331
|
+
responseBytes += addition;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
const eventJson = JSON.stringify(event);
|
|
336
|
+
const provenanceJson = JSON.stringify(event.id) + ":" + JSON.stringify([id]);
|
|
337
|
+
// Both arrays/objects start empty; each subsequent event adds one
|
|
338
|
+
// comma in each representation, hence four bytes combined.
|
|
339
|
+
const addition = responseFragmentBytes(eventJson) +
|
|
340
|
+
responseFragmentBytes(provenanceJson) +
|
|
341
|
+
(events.size ? 4 : 0);
|
|
342
|
+
if (responseBytes + addition > limits.responseBytes) {
|
|
343
|
+
stop("byte_limit");
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
metrics.retainedBytes = events.size
|
|
347
|
+
? metrics.retainedBytes + 1 + bytes(eventJson)
|
|
348
|
+
: 2 + bytes(eventJson);
|
|
349
|
+
events.set(event.id, event);
|
|
350
|
+
provenance[event.id] = [id];
|
|
351
|
+
responseBytes += addition;
|
|
352
|
+
}
|
|
353
|
+
if (metrics.candidates === limits.candidates)
|
|
354
|
+
stop("scan_limit");
|
|
355
|
+
if (events.size === limits.events)
|
|
356
|
+
stop("event_limit");
|
|
357
|
+
}));
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@941design/nostr-events",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.1",
|
|
4
4
|
"description": "Shared Nostr protocol primitives library — typed event surface, signer interface, NIP-59 gift-wrap, transport abstractions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -141,6 +141,10 @@
|
|
|
141
141
|
"./loaders": {
|
|
142
142
|
"types": "./dist/loaders/index.d.ts",
|
|
143
143
|
"import": "./dist/loaders/index.js"
|
|
144
|
+
},
|
|
145
|
+
"./transport/bounded": {
|
|
146
|
+
"types": "./dist/transport/bounded/index.d.ts",
|
|
147
|
+
"import": "./dist/transport/bounded/index.js"
|
|
144
148
|
}
|
|
145
149
|
},
|
|
146
150
|
"peerDependencies": {
|