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