chirli 0.0.0-stage → 0.2.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.
- package/ARCHITECTURE.md +103 -0
- package/CONTRIBUTING.md +56 -0
- package/LICENSE +22 -0
- package/README.md +281 -2
- package/SECURITY.md +55 -0
- package/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/allowlist.d.ts +3 -0
- package/dist/allowlist.js +9 -0
- package/dist/announcements.d.ts +25 -0
- package/dist/announcements.js +142 -0
- package/dist/attachments.d.ts +43 -0
- package/dist/attachments.js +340 -0
- package/dist/blossom.d.ts +30 -0
- package/dist/blossom.js +233 -0
- package/dist/bot-handlers.d.ts +70 -0
- package/dist/bot-handlers.js +317 -0
- package/dist/bot.d.ts +63 -0
- package/dist/bot.js +244 -0
- package/dist/client.d.ts +221 -0
- package/dist/client.js +1197 -0
- package/dist/command-discovery.d.ts +4 -0
- package/dist/command-discovery.js +33 -0
- package/dist/command-schema.d.ts +4 -0
- package/dist/command-schema.js +101 -0
- package/dist/commands.d.ts +32 -0
- package/dist/commands.js +253 -0
- package/dist/defaults.d.ts +9 -0
- package/dist/defaults.js +22 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.js +126 -0
- package/dist/inbox.d.ts +55 -0
- package/dist/inbox.js +376 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +11 -0
- package/dist/key-sync.d.ts +33 -0
- package/dist/key-sync.js +293 -0
- package/dist/keys.d.ts +66 -0
- package/dist/keys.js +418 -0
- package/dist/message-storage-sqlite.d.ts +6 -0
- package/dist/message-storage-sqlite.js +90 -0
- package/dist/message-storage.d.ts +32 -0
- package/dist/message-storage.js +1 -0
- package/dist/messaging-metadata.d.ts +48 -0
- package/dist/messaging-metadata.js +280 -0
- package/dist/metadata.d.ts +7 -0
- package/dist/metadata.js +63 -0
- package/dist/modes.d.ts +26 -0
- package/dist/modes.js +108 -0
- package/dist/nip4e-compat.d.ts +4 -0
- package/dist/nip4e-compat.js +14 -0
- package/dist/nipcd.d.ts +109 -0
- package/dist/nipcd.js +555 -0
- package/dist/protocol.d.ts +68 -0
- package/dist/protocol.js +302 -0
- package/dist/public-inbox.d.ts +66 -0
- package/dist/public-inbox.js +295 -0
- package/dist/public-thread.d.ts +62 -0
- package/dist/public-thread.js +436 -0
- package/dist/relay-pool.d.ts +43 -0
- package/dist/relay-pool.js +429 -0
- package/dist/relay-roles.d.ts +18 -0
- package/dist/relay-roles.js +55 -0
- package/dist/relay.d.ts +52 -0
- package/dist/relay.js +493 -0
- package/dist/request-timing.d.ts +12 -0
- package/dist/request-timing.js +37 -0
- package/dist/session.d.ts +16 -0
- package/dist/session.js +51 -0
- package/dist/signer.d.ts +13 -0
- package/dist/signer.js +1 -0
- package/dist/signers/bunker-relays.d.ts +15 -0
- package/dist/signers/bunker-relays.js +87 -0
- package/dist/signers/bunker.d.ts +7 -0
- package/dist/signers/bunker.js +194 -0
- package/dist/signers/nsec.d.ts +3 -0
- package/dist/signers/nsec.js +62 -0
- package/dist/signers.d.ts +18 -0
- package/dist/signers.js +59 -0
- package/dist/storage-sqlite.d.ts +29 -0
- package/dist/storage-sqlite.js +221 -0
- package/dist/storage.d.ts +85 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +96 -0
- package/dist/store.js +404 -0
- package/docs/ACCESS.md +28 -0
- package/docs/API.md +382 -0
- package/docs/INTEROPERABILITY.md +32 -0
- package/docs/KEYS.md +75 -0
- package/docs/NIP-CD.md +112 -0
- package/docs/PUBLIC.md +88 -0
- package/docs/RECOVERY.md +59 -0
- package/docs/RELAYS.md +145 -0
- package/docs/SESSIONS.md +108 -0
- package/docs/SIGNERS.md +59 -0
- package/docs/STORAGE.md +71 -0
- package/docs/TUTORIAL.md +178 -0
- package/package.json +47 -4
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { verifyEvent } from "nostr-tools";
|
|
2
|
+
import { hexKey, validTimestamp } from "./protocol.js";
|
|
3
|
+
import { messagingMetadata, standardRelays } from "./metadata.js";
|
|
4
|
+
import { InboxSubscription } from "./inbox.js";
|
|
5
|
+
const newer = (a, b) => a.created_at > b.created_at || (a.created_at === b.created_at && a.id < b.id);
|
|
6
|
+
export class MessagingMetadata {
|
|
7
|
+
pubkey;
|
|
8
|
+
store;
|
|
9
|
+
transport;
|
|
10
|
+
relays;
|
|
11
|
+
error;
|
|
12
|
+
reconnect;
|
|
13
|
+
options;
|
|
14
|
+
own = new Map();
|
|
15
|
+
peers = new Map();
|
|
16
|
+
flights = new Map();
|
|
17
|
+
jobs = new Set();
|
|
18
|
+
refreshQueue = [];
|
|
19
|
+
queued = new Set();
|
|
20
|
+
refreshing = 0;
|
|
21
|
+
retryAt = new Map();
|
|
22
|
+
watcher;
|
|
23
|
+
starting;
|
|
24
|
+
watching = false;
|
|
25
|
+
ttl;
|
|
26
|
+
negative;
|
|
27
|
+
stale;
|
|
28
|
+
capacity;
|
|
29
|
+
onOwnEvent;
|
|
30
|
+
constructor(pubkey, store, transport, relays, error, reconnect, options = {}) {
|
|
31
|
+
this.pubkey = pubkey;
|
|
32
|
+
this.store = store;
|
|
33
|
+
this.transport = transport;
|
|
34
|
+
this.relays = relays;
|
|
35
|
+
this.error = error;
|
|
36
|
+
this.reconnect = reconnect;
|
|
37
|
+
this.options = options;
|
|
38
|
+
this.ttl = options === false ? 0 : (options.ttlMs ?? 600000);
|
|
39
|
+
this.negative = options === false ? 0 : (options.negativeTtlMs ?? 30000);
|
|
40
|
+
this.stale = options === false ? 0 : (options.maxStaleMs ?? 86400000);
|
|
41
|
+
this.capacity = options === false ? 512 : (options.maxEntries ?? 512);
|
|
42
|
+
for (const value of [this.ttl, this.negative, this.stale]) {
|
|
43
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > 31536000000) {
|
|
44
|
+
throw new TypeError("Metadata cache durations must be integers in 0..31536000000");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (!Number.isSafeInteger(this.capacity) ||
|
|
48
|
+
this.capacity < 1 ||
|
|
49
|
+
this.capacity > 10000) {
|
|
50
|
+
throw new TypeError("metadataCache.maxEntries must be in 1..10000");
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
valid(event, author, kinds) {
|
|
54
|
+
try {
|
|
55
|
+
return (kinds.includes(event.kind) &&
|
|
56
|
+
event.pubkey === author &&
|
|
57
|
+
validTimestamp(event.created_at) &&
|
|
58
|
+
verifyEvent(JSON.parse(JSON.stringify(event))));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
rememberOwn(event) {
|
|
65
|
+
if (!this.valid(event, this.pubkey, [10044, 10050])) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const previous = this.own.get(event.kind);
|
|
69
|
+
if (!previous || newer(event, previous)) {
|
|
70
|
+
this.own.set(event.kind, structuredClone(event));
|
|
71
|
+
if (event.kind === 10044) {
|
|
72
|
+
this.store.rememberDeclaration(event);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
ownEvents(kinds) {
|
|
77
|
+
return kinds.flatMap((kind) => {
|
|
78
|
+
const event = this.own.get(kind);
|
|
79
|
+
return event ? [structuredClone(event)] : [];
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
ownDmRelays(fallback) {
|
|
83
|
+
try {
|
|
84
|
+
return standardRelays(this.ownEvents([10050]));
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return [...fallback];
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async start() {
|
|
91
|
+
if (this.watching) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (this.starting) {
|
|
95
|
+
return this.starting;
|
|
96
|
+
}
|
|
97
|
+
const task = (async () => {
|
|
98
|
+
this.watcher = new InboxSubscription({
|
|
99
|
+
transport: this.transport,
|
|
100
|
+
store: this.store,
|
|
101
|
+
relays: this.relays,
|
|
102
|
+
filter: {
|
|
103
|
+
authors: [this.pubkey],
|
|
104
|
+
kinds: [10044, 10050, 4454],
|
|
105
|
+
},
|
|
106
|
+
reconnect: this.reconnect,
|
|
107
|
+
recovery: false,
|
|
108
|
+
receive: (event) => {
|
|
109
|
+
if (!this.valid(event, this.pubkey, [10044, 10050, 4454])) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
this.rememberOwn(event);
|
|
113
|
+
if ((event.kind === 4454 || (event.kind === 10044 && this.watching)) &&
|
|
114
|
+
this.onOwnEvent) {
|
|
115
|
+
const job = this.onOwnEvent(event);
|
|
116
|
+
this.jobs.add(job);
|
|
117
|
+
void job.finally(() => this.jobs.delete(job)).catch(() => { });
|
|
118
|
+
return job;
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
error: this.error,
|
|
122
|
+
reconnected: async () => { },
|
|
123
|
+
});
|
|
124
|
+
await this.watcher.ready;
|
|
125
|
+
this.watching = true;
|
|
126
|
+
})()
|
|
127
|
+
.catch((error) => {
|
|
128
|
+
this.watcher?.close();
|
|
129
|
+
this.watcher = undefined;
|
|
130
|
+
throw error;
|
|
131
|
+
})
|
|
132
|
+
.finally(() => {
|
|
133
|
+
this.starting = undefined;
|
|
134
|
+
});
|
|
135
|
+
this.starting = task;
|
|
136
|
+
return task;
|
|
137
|
+
}
|
|
138
|
+
async read(peer, kinds, force = false) {
|
|
139
|
+
if (!hexKey(peer)) {
|
|
140
|
+
throw new TypeError("Invalid peer identity");
|
|
141
|
+
}
|
|
142
|
+
if (peer === this.pubkey && this.watching && !force) {
|
|
143
|
+
return this.ownEvents(kinds);
|
|
144
|
+
}
|
|
145
|
+
if (peer === this.pubkey) {
|
|
146
|
+
const events = await messagingMetadata(peer, kinds, this.transport, this.relays);
|
|
147
|
+
for (const event of events) {
|
|
148
|
+
this.rememberOwn(event);
|
|
149
|
+
}
|
|
150
|
+
return this.ownEvents(kinds);
|
|
151
|
+
}
|
|
152
|
+
const entry = this.peers.get(peer), age = entry ? Math.max(0, Date.now() - entry.at) : Infinity;
|
|
153
|
+
const usable = entry &&
|
|
154
|
+
(() => {
|
|
155
|
+
try {
|
|
156
|
+
standardRelays(entry.events);
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
})();
|
|
163
|
+
const ttl = usable ? this.ttl : this.negative;
|
|
164
|
+
if (!force &&
|
|
165
|
+
this.options !== false &&
|
|
166
|
+
entry &&
|
|
167
|
+
(age < ttl || (usable && age < this.stale))) {
|
|
168
|
+
this.peers.delete(peer);
|
|
169
|
+
this.peers.set(peer, entry);
|
|
170
|
+
if (age >= ttl) {
|
|
171
|
+
this.refresh(peer);
|
|
172
|
+
}
|
|
173
|
+
return structuredClone(entry.events.filter((event) => kinds.includes(event.kind)));
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
return (await this.fetch(peer)).filter((event) => kinds.includes(event.kind));
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (!force && this.store.evidence(peer)) {
|
|
180
|
+
this.savePeer(peer, {
|
|
181
|
+
events: [],
|
|
182
|
+
at: Date.now(),
|
|
183
|
+
});
|
|
184
|
+
return [];
|
|
185
|
+
}
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
refresh(peer) {
|
|
190
|
+
if (this.flights.has(peer) ||
|
|
191
|
+
this.queued.has(peer) ||
|
|
192
|
+
Date.now() < (this.retryAt.get(peer) ?? 0) ||
|
|
193
|
+
this.refreshQueue.length >= this.capacity) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
this.queued.add(peer);
|
|
197
|
+
this.refreshQueue.push(peer);
|
|
198
|
+
this.drain();
|
|
199
|
+
}
|
|
200
|
+
drain() {
|
|
201
|
+
while (this.refreshing < 4 && this.refreshQueue.length) {
|
|
202
|
+
const peer = this.refreshQueue.shift();
|
|
203
|
+
if (peer === undefined)
|
|
204
|
+
break;
|
|
205
|
+
this.queued.delete(peer);
|
|
206
|
+
if (!this.peers.has(peer)) {
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
this.refreshing++;
|
|
210
|
+
void this.fetch(peer)
|
|
211
|
+
.catch(() => {
|
|
212
|
+
if (this.peers.has(peer)) {
|
|
213
|
+
this.retryAt.set(peer, Date.now() + Math.max(1000, this.negative));
|
|
214
|
+
}
|
|
215
|
+
})
|
|
216
|
+
.finally(() => {
|
|
217
|
+
this.refreshing--;
|
|
218
|
+
this.drain();
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
savePeer(peer, entry) {
|
|
223
|
+
this.peers.delete(peer);
|
|
224
|
+
this.peers.set(peer, entry);
|
|
225
|
+
while (this.peers.size > this.capacity) {
|
|
226
|
+
const first = this.peers.keys().next();
|
|
227
|
+
if (first.done)
|
|
228
|
+
break;
|
|
229
|
+
const oldest = first.value;
|
|
230
|
+
this.peers.delete(oldest);
|
|
231
|
+
this.retryAt.delete(oldest);
|
|
232
|
+
this.queued.delete(oldest);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
fetch(peer) {
|
|
236
|
+
const existing = this.flights.get(peer);
|
|
237
|
+
if (existing) {
|
|
238
|
+
return existing;
|
|
239
|
+
}
|
|
240
|
+
const task = messagingMetadata(peer, [10044, 10050], this.transport, this.relays)
|
|
241
|
+
.then((events) => {
|
|
242
|
+
const previous = this.peers.get(peer), selected = new Map();
|
|
243
|
+
for (const event of [...(previous?.events ?? []), ...events]) {
|
|
244
|
+
const old = selected.get(event.kind);
|
|
245
|
+
if (!old || newer(event, old)) {
|
|
246
|
+
selected.set(event.kind, event);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const result = [...selected.values()];
|
|
250
|
+
this.savePeer(peer, {
|
|
251
|
+
events: structuredClone(result),
|
|
252
|
+
at: Date.now(),
|
|
253
|
+
});
|
|
254
|
+
this.retryAt.delete(peer);
|
|
255
|
+
return structuredClone(result);
|
|
256
|
+
})
|
|
257
|
+
.finally(() => {
|
|
258
|
+
this.flights.delete(peer);
|
|
259
|
+
});
|
|
260
|
+
this.flights.set(peer, task);
|
|
261
|
+
return task;
|
|
262
|
+
}
|
|
263
|
+
async stop() {
|
|
264
|
+
this.refreshQueue = [];
|
|
265
|
+
this.queued.clear();
|
|
266
|
+
this.watching = false;
|
|
267
|
+
this.watcher?.close();
|
|
268
|
+
this.watcher = undefined;
|
|
269
|
+
await this.starting?.catch(() => { });
|
|
270
|
+
this.watching = false;
|
|
271
|
+
await this.idle();
|
|
272
|
+
}
|
|
273
|
+
async idle() {
|
|
274
|
+
while (this.flights.size ||
|
|
275
|
+
this.jobs.size ||
|
|
276
|
+
this.refreshQueue.length ||
|
|
277
|
+
this.refreshing)
|
|
278
|
+
await Promise.allSettled([...this.flights.values(), ...this.jobs]);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Event } from "nostr-tools";
|
|
2
|
+
import { type Identity } from "./protocol.js";
|
|
3
|
+
import type { Transport } from "./relay.js";
|
|
4
|
+
export declare function messagingMetadata(peer: string, kinds: number[], transport: Transport, relays: string[]): Promise<Event[]>;
|
|
5
|
+
export declare function websocketURL(value: unknown): value is string;
|
|
6
|
+
export declare function standardRelays(events: Event[]): string[];
|
|
7
|
+
export declare function relayAnnouncement(identity: Identity, relays: string[]): Promise<Event>;
|
package/dist/metadata.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { verifyEvent } from "nostr-tools";
|
|
2
|
+
import { hexKey, signChecked, validTimestamp, } from "./protocol.js";
|
|
3
|
+
export async function messagingMetadata(peer, kinds, transport, relays) {
|
|
4
|
+
if (!hexKey(peer)) {
|
|
5
|
+
throw new Error("Invalid peer identity");
|
|
6
|
+
}
|
|
7
|
+
const events = await transport.query(relays, {
|
|
8
|
+
kinds,
|
|
9
|
+
authors: [peer],
|
|
10
|
+
});
|
|
11
|
+
return events
|
|
12
|
+
.filter((event) => {
|
|
13
|
+
try {
|
|
14
|
+
return (kinds.includes(event.kind) &&
|
|
15
|
+
event.pubkey === peer &&
|
|
16
|
+
validTimestamp(event.created_at) &&
|
|
17
|
+
verifyEvent(JSON.parse(JSON.stringify(event))));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
})
|
|
23
|
+
.sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id));
|
|
24
|
+
}
|
|
25
|
+
export function websocketURL(value) {
|
|
26
|
+
if (typeof value !== "string") {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const url = new URL(value);
|
|
31
|
+
return (["ws:", "wss:"].includes(url.protocol) &&
|
|
32
|
+
!!url.hostname &&
|
|
33
|
+
!url.username &&
|
|
34
|
+
!url.password &&
|
|
35
|
+
!url.hash);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export function standardRelays(events) {
|
|
42
|
+
const latest = events.find((event) => event.kind === 10050);
|
|
43
|
+
const relays = [
|
|
44
|
+
...new Set(latest?.tags
|
|
45
|
+
.filter((tag) => tag[0] === "relay" && websocketURL(tag[1]))
|
|
46
|
+
.map((tag) => tag[1]) ?? []),
|
|
47
|
+
];
|
|
48
|
+
if (!relays.length) {
|
|
49
|
+
throw new Error("nip17 requires a valid recipient kind 10050 DM relay list; no relay fallback");
|
|
50
|
+
}
|
|
51
|
+
return relays;
|
|
52
|
+
}
|
|
53
|
+
export function relayAnnouncement(identity, relays) {
|
|
54
|
+
if (!relays.length || !relays.every(websocketURL)) {
|
|
55
|
+
throw new Error("nip17 requires valid WebSocket inbox relay URLs");
|
|
56
|
+
}
|
|
57
|
+
return signChecked(identity, {
|
|
58
|
+
kind: 10050,
|
|
59
|
+
created_at: Math.floor(Date.now() / 1000),
|
|
60
|
+
tags: [...new Set(relays)].map((relay) => ["relay", relay]),
|
|
61
|
+
content: "",
|
|
62
|
+
});
|
|
63
|
+
}
|
package/dist/modes.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type EnvelopePolicy, type Identity, type DecodedEnvelope } from "./protocol.js";
|
|
2
|
+
import type { MessagingMetadata } from "./messaging-metadata.js";
|
|
3
|
+
import type { Store } from "./store.js";
|
|
4
|
+
import type { Transport } from "./relay.js";
|
|
5
|
+
import type { EncryptionKeys } from "./keys.js";
|
|
6
|
+
export type ProtocolMode = "nip4e" | "nip17";
|
|
7
|
+
export interface PeerMetadata {
|
|
8
|
+
encryptionPubkey: string;
|
|
9
|
+
relays: string[];
|
|
10
|
+
envelope?: EnvelopePolicy;
|
|
11
|
+
}
|
|
12
|
+
export interface Recipient extends PeerMetadata {
|
|
13
|
+
pubkey: string;
|
|
14
|
+
}
|
|
15
|
+
export interface MessagingProtocol {
|
|
16
|
+
readonly mode: ProtocolMode;
|
|
17
|
+
readonly scope: string;
|
|
18
|
+
readonly envelope: EnvelopePolicy;
|
|
19
|
+
prepare(): Promise<void>;
|
|
20
|
+
resolve(peer: string, store: Store, transport: Transport, discovery: string[], force?: boolean): Promise<PeerMetadata>;
|
|
21
|
+
recipients(peer: string, store: Store, transport: Transport, discovery: string[], input?: DecodedEnvelope): Promise<Recipient[]>;
|
|
22
|
+
remember(decoded: DecodedEnvelope, store: Store): void;
|
|
23
|
+
}
|
|
24
|
+
export declare function protocolScope(mode: ProtocolMode, identity: Identity): string;
|
|
25
|
+
/** Mode selects the outgoing key, while authenticated peer evidence selects the wire profile. */
|
|
26
|
+
export declare function createMessagingProtocol(mode: ProtocolMode, identity: Identity, keys: EncryptionKeys, metadata?: MessagingMetadata, ownRelays?: string[]): MessagingProtocol;
|
package/dist/modes.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { getPublicKey } from "nostr-tools";
|
|
2
|
+
import { compatibilityEnvelope, identitySplitEnvelope, identityMessagingKey, splitKey, splitEnvelope, standardEnvelope, timestamp, validateNip17Identity, } from "./protocol.js";
|
|
3
|
+
import { messagingMetadata, standardRelays } from "./metadata.js";
|
|
4
|
+
import { recordPeerMetadata } from "./nip4e-compat.js";
|
|
5
|
+
export function protocolScope(mode, identity) {
|
|
6
|
+
if (mode !== "nip17" && mode !== "nip4e") {
|
|
7
|
+
throw new Error(`Unsupported protocol mode: ${String(mode)}`);
|
|
8
|
+
}
|
|
9
|
+
identityMessagingKey(identity);
|
|
10
|
+
if (mode === "nip17") {
|
|
11
|
+
validateNip17Identity(identity);
|
|
12
|
+
}
|
|
13
|
+
return mode === "nip17" ? `nip17:${identity.pubkey}` : identity.pubkey;
|
|
14
|
+
}
|
|
15
|
+
/** Mode selects the outgoing key, while authenticated peer evidence selects the wire profile. */
|
|
16
|
+
export function createMessagingProtocol(mode, identity, keys, metadata, ownRelays = []) {
|
|
17
|
+
const scope = mode === "nip17" ? `nip17:${identity.pubkey}` : identity.pubkey;
|
|
18
|
+
const resolved = (peer, store, events, input) => {
|
|
19
|
+
recordPeerMetadata(store, events);
|
|
20
|
+
const evidence = store.evidence(peer), declaration = store.declaration(peer);
|
|
21
|
+
// Middleware can reply using authenticated, in-flight seal evidence without
|
|
22
|
+
// admitting the input body or its peer evidence to durable storage.
|
|
23
|
+
const incoming = input?.rumor.pubkey === peer ? input : undefined;
|
|
24
|
+
const incomingTime = incoming ? timestamp(incoming.rumor) : 0;
|
|
25
|
+
const preferIncoming = incoming &&
|
|
26
|
+
(!evidence ||
|
|
27
|
+
incomingTime > evidence.time ||
|
|
28
|
+
(incomingTime === evidence.time && incoming.rumor.id < evidence.id));
|
|
29
|
+
const key = preferIncoming ? incoming.encryptionPubkey : evidence?.key;
|
|
30
|
+
if (declaration && !key) {
|
|
31
|
+
throw new Error("No valid encryption key in peer NIP-4E declaration");
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
encryptionPubkey: key ?? peer,
|
|
35
|
+
relays: (() => {
|
|
36
|
+
try {
|
|
37
|
+
return standardRelays(events);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
if (ownRelays.length) {
|
|
41
|
+
return metadata ? metadata.ownDmRelays(ownRelays) : [...ownRelays];
|
|
42
|
+
}
|
|
43
|
+
throw new Error("No DM relay fallback configured");
|
|
44
|
+
}
|
|
45
|
+
})(),
|
|
46
|
+
envelope: store.isSplitPeer(peer) ||
|
|
47
|
+
incoming?.seal.tags.some((tag) => tag[0] === "n")
|
|
48
|
+
? mode === "nip4e"
|
|
49
|
+
? splitEnvelope
|
|
50
|
+
: identitySplitEnvelope
|
|
51
|
+
: standardEnvelope,
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
const protocol = {
|
|
55
|
+
mode,
|
|
56
|
+
scope,
|
|
57
|
+
envelope: compatibilityEnvelope,
|
|
58
|
+
prepare: () => keys.prepare(),
|
|
59
|
+
async resolve(peer, store, transport, discovery, force = false) {
|
|
60
|
+
return resolved(peer, store, await (metadata
|
|
61
|
+
? metadata.read(peer, [10044, 10050], force)
|
|
62
|
+
: messagingMetadata(peer, [10044, 10050], transport, discovery)));
|
|
63
|
+
},
|
|
64
|
+
async recipients(peer, store, transport, discovery, input) {
|
|
65
|
+
// Read independent snapshots concurrently; apply peer evidence only after own-key checks pass.
|
|
66
|
+
const [, selfEvents, peerEvents] = await Promise.all([
|
|
67
|
+
keys.prepare(),
|
|
68
|
+
metadata
|
|
69
|
+
? metadata.read(identity.pubkey, [10050])
|
|
70
|
+
: messagingMetadata(identity.pubkey, [10050], transport, discovery),
|
|
71
|
+
peer === identity.pubkey
|
|
72
|
+
? Promise.resolve(undefined)
|
|
73
|
+
: metadata
|
|
74
|
+
? metadata.read(peer, [10044, 10050])
|
|
75
|
+
: messagingMetadata(peer, [10044, 10050], transport, discovery),
|
|
76
|
+
]);
|
|
77
|
+
const self = {
|
|
78
|
+
pubkey: identity.pubkey,
|
|
79
|
+
encryptionPubkey: mode === "nip4e" ? getPublicKey(splitKey(identity)) : identity.pubkey,
|
|
80
|
+
relays: (() => {
|
|
81
|
+
try {
|
|
82
|
+
return standardRelays(selfEvents);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return [...ownRelays];
|
|
86
|
+
}
|
|
87
|
+
})(),
|
|
88
|
+
envelope: mode === "nip4e" ? splitEnvelope : standardEnvelope,
|
|
89
|
+
};
|
|
90
|
+
return peerEvents
|
|
91
|
+
? [
|
|
92
|
+
{
|
|
93
|
+
pubkey: peer,
|
|
94
|
+
...resolved(peer, store, peerEvents, input),
|
|
95
|
+
},
|
|
96
|
+
self,
|
|
97
|
+
]
|
|
98
|
+
: [self];
|
|
99
|
+
},
|
|
100
|
+
remember({ rumor, seal, encryptionPubkey }, store) {
|
|
101
|
+
if (seal.tags.some((t) => t[0] === "n")) {
|
|
102
|
+
store.markSplitPeer(rumor.pubkey);
|
|
103
|
+
}
|
|
104
|
+
store.observe(rumor.pubkey, encryptionPubkey, timestamp(rumor), rumor.id);
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
return protocol;
|
|
108
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { hexKey } from "./protocol.js";
|
|
2
|
+
/** Only authenticated metadata from messagingMetadata may enter this cache. */
|
|
3
|
+
export function recordPeerMetadata(store, events) {
|
|
4
|
+
for (const event of events) {
|
|
5
|
+
if (event.kind === 10044) {
|
|
6
|
+
store.rememberDeclaration(event);
|
|
7
|
+
const key = event.tags.find((t) => t[0] === "n")?.[1];
|
|
8
|
+
if (hexKey(key)) {
|
|
9
|
+
store.markSplitPeer(event.pubkey);
|
|
10
|
+
store.observe(event.pubkey, key, event.created_at * 1000, event.id);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
package/dist/nipcd.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
import { type Event, type EventTemplate } from "nostr-tools";
|
|
3
|
+
export declare const COMMAND_DEFINITION_KIND = 31992;
|
|
4
|
+
export type CommandArgumentType = "pubkey" | "event" | "address" | "relay" | "number" | "bool" | "enum" | "word" | "text";
|
|
5
|
+
export interface CommandArgument {
|
|
6
|
+
name: string;
|
|
7
|
+
type: CommandArgumentType;
|
|
8
|
+
required: boolean;
|
|
9
|
+
label: string;
|
|
10
|
+
choices?: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
export interface CommandDefinition {
|
|
13
|
+
id: string;
|
|
14
|
+
command: string;
|
|
15
|
+
title: string;
|
|
16
|
+
description: string;
|
|
17
|
+
args?: readonly CommandArgument[];
|
|
18
|
+
scopes?: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
/** Local command coordinates are derived from the trigger; custom identifiers are forbidden. */
|
|
21
|
+
export type BotCommandDefinition = Omit<CommandDefinition, "id" | "scopes" | "title" | "description" | "args"> & {
|
|
22
|
+
id?: never;
|
|
23
|
+
scopes?: readonly string[];
|
|
24
|
+
args?: z.ZodObject;
|
|
25
|
+
title?: string;
|
|
26
|
+
description?: string;
|
|
27
|
+
};
|
|
28
|
+
export interface CommandAddress {
|
|
29
|
+
kind: number;
|
|
30
|
+
pubkey: string;
|
|
31
|
+
identifier: string;
|
|
32
|
+
relays: string[];
|
|
33
|
+
}
|
|
34
|
+
export type CommandValue = string | bigint | boolean | CommandAddress;
|
|
35
|
+
/** Infer named values from a literal schema. Dynamic definitions retain a safe lookup type. */
|
|
36
|
+
export type CommandArgs<D extends string | BotCommandDefinition> = D extends string ? {
|
|
37
|
+
readonly text: string | undefined;
|
|
38
|
+
} : D extends {
|
|
39
|
+
args: infer A extends z.ZodObject;
|
|
40
|
+
} ? z.output<A> : "args" extends keyof D ? Readonly<Record<string, unknown>> : Record<never, never>;
|
|
41
|
+
export interface CommandEvent {
|
|
42
|
+
kind: number;
|
|
43
|
+
pubkey: string;
|
|
44
|
+
tags: string[][];
|
|
45
|
+
content: string;
|
|
46
|
+
}
|
|
47
|
+
export interface CommandMatchContext {
|
|
48
|
+
executor: string;
|
|
49
|
+
relay?: string;
|
|
50
|
+
}
|
|
51
|
+
export interface CommandInvocation<Args = Record<string, CommandValue | undefined>> {
|
|
52
|
+
definition: CommandDefinition;
|
|
53
|
+
qualifier?: string;
|
|
54
|
+
args: Args;
|
|
55
|
+
rawArgs: Record<string, string | undefined>;
|
|
56
|
+
}
|
|
57
|
+
export type CommandParseResult = {
|
|
58
|
+
status: "matched";
|
|
59
|
+
invocation: CommandInvocation;
|
|
60
|
+
} | {
|
|
61
|
+
status: "not-matched";
|
|
62
|
+
} | {
|
|
63
|
+
status: "invalid";
|
|
64
|
+
reason: string;
|
|
65
|
+
};
|
|
66
|
+
export interface PublishedCommand {
|
|
67
|
+
address: string;
|
|
68
|
+
executor: string;
|
|
69
|
+
definition: CommandDefinition;
|
|
70
|
+
event: Event;
|
|
71
|
+
}
|
|
72
|
+
export interface CommandDiscoveryResult {
|
|
73
|
+
commands: PublishedCommand[];
|
|
74
|
+
retired: {
|
|
75
|
+
address: string;
|
|
76
|
+
reason: "deleted" | "invalid-definition";
|
|
77
|
+
}[];
|
|
78
|
+
coverage: "relay-snapshot";
|
|
79
|
+
complete: false;
|
|
80
|
+
}
|
|
81
|
+
export interface DiscoverCommandsOptions {
|
|
82
|
+
authors: string[];
|
|
83
|
+
relays: string[];
|
|
84
|
+
ids?: string[];
|
|
85
|
+
limit?: number;
|
|
86
|
+
}
|
|
87
|
+
export declare function commandRelayURL(value: string): string;
|
|
88
|
+
export declare function commandAddress(executor: string, id: string): string;
|
|
89
|
+
export declare function validateCommandDefinition(input: CommandDefinition): CommandDefinition;
|
|
90
|
+
export declare function encodeCommandDefinition(input: CommandDefinition, createdAt?: number): EventTemplate;
|
|
91
|
+
export declare function decodeCommandDefinition(input: Event): PublishedCommand | undefined;
|
|
92
|
+
export declare function encodeCommandRevocation(executor: string, id: string, createdAt?: number): EventTemplate;
|
|
93
|
+
/** Select newest signed coordinates first; deleted/malformed latest versions never reveal an older fallback. */
|
|
94
|
+
export declare function selectCommandDefinitions(inputs: Event[], authors: string[], ids?: string[]): CommandDiscoveryResult;
|
|
95
|
+
export declare function matchesCommandScopes(scopes: readonly string[], event: CommandEvent, context?: {
|
|
96
|
+
relay?: string;
|
|
97
|
+
}): boolean;
|
|
98
|
+
/** Shared index-zero trigger/qualifier parser for simple and schema-defined commands. */
|
|
99
|
+
export declare function parseCommandHead(content: string, command: string, executor: string): {
|
|
100
|
+
status: "matched";
|
|
101
|
+
cursor: number;
|
|
102
|
+
qualifier?: string;
|
|
103
|
+
} | {
|
|
104
|
+
status: "not-matched";
|
|
105
|
+
} | {
|
|
106
|
+
status: "invalid";
|
|
107
|
+
reason: string;
|
|
108
|
+
};
|
|
109
|
+
export declare function parseCommand(input: CommandDefinition, event: CommandEvent, context: CommandMatchContext): CommandParseResult;
|