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
package/dist/client.js CHANGED
@@ -1,25 +1,35 @@
1
- import { encryptAttachment, normalizeBlossomDownloadOrigins, normalizeBlossomServers, snapshotFile, uploadFile } from './blossom.js';
2
- import { PublicInbox } from './public-inbox.js';
3
- import { inputOf, threadLimit } from './public-thread.js';
4
- import { getEventHash } from 'nostr-tools';
5
- import { identityFromSigner } from './signers.js';
6
- import { AsyncLocalStorage } from 'node:async_hooks';
7
- import { Store } from './store.js';
8
- import { localReadBoundary, WebSocketTransport } from './relay.js';
9
- import { fileRumor, hexKey, reactionRumor, replyTarget, rumor, timestamp, unwrapAsync, wrap } from './protocol.js';
10
- import { createMessagingProtocol, protocolScope } from './modes.js';
11
- import { InboxSubscription } from './inbox.js';
12
- import { validateCommandDefinition, } from './nipcd.js';
13
- import { relayRoles, relayUnion, readWriteTags } from './relay-roles.js';
14
- import { KeySync } from './key-sync.js';
15
- import { MessagingMetadata } from './messaging-metadata.js';
16
- import { Announcements } from './announcements.js';
17
- import { discoverCommandCatalog } from './command-discovery.js';
18
- import { CommandCatalog } from './commands.js';
19
- import { EncryptionKeys } from './keys.js';
1
+ import { resolve } from "node:path";
2
+ import { AttachmentCache, parseAttachment } from "./attachments.js";
3
+ import { encryptAttachment, normalizeBlossomDownloadOrigins, normalizeBlossomServers, snapshotFile, uploadFile, } from "./blossom.js";
4
+ import { PublicInbox, } from "./public-inbox.js";
5
+ import { inputOf, threadLimit, } from "./public-thread.js";
6
+ import { getEventHash } from "nostr-tools";
7
+ import { identityFromSigner } from "./signers.js";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { Store } from "./store.js";
10
+ import { WebSocketTransport, } from "./relay.js";
11
+ import { fileRumor, hexKey, reactionRumor, replyTarget, rumor, timestamp, createdAtOrAfter, unwrapAsync, wrap, } from "./protocol.js";
12
+ import { createMessagingProtocol, protocolScope, } from "./modes.js";
13
+ import { InboxSubscription, } from "./inbox.js";
14
+ import { validateCommandDefinition, } from "./nipcd.js";
15
+ import { relayRoles, relayUnion, readWriteTags, } from "./relay-roles.js";
16
+ import { KeySync } from "./key-sync.js";
17
+ import { MessagingMetadata, } from "./messaging-metadata.js";
18
+ import { Announcements } from "./announcements.js";
19
+ import { discoverCommandCatalog } from "./command-discovery.js";
20
+ import { CommandCatalog } from "./commands.js";
21
+ import { EncryptionKeys, } from "./keys.js";
22
+ export function rejectRemovedIntakeOptions(options) {
23
+ if ("inboundPolicy" in options ||
24
+ "guards" in options ||
25
+ "allowlist" in options) {
26
+ throw new TypeError("Use bot.use(allowlist(pubkeys)) or custom middleware instead of inboundPolicy, guards or the allowlist option");
27
+ }
28
+ }
20
29
  export class Client {
21
30
  options;
22
31
  metadataLookupRelays;
32
+ attachments;
23
33
  blossomServers;
24
34
  blossomDownloadOrigins;
25
35
  announcements;
@@ -40,20 +50,19 @@ export class Client {
40
50
  account;
41
51
  mode;
42
52
  nip4eCompatibility;
43
- inboundPolicy;
44
53
  keys;
45
54
  rotationTimer;
46
55
  protocol;
47
56
  transport;
48
57
  ownsTransport;
49
58
  observers = new Set();
50
- handlers = new Set();
59
+ handlers = new Map();
51
60
  errors = new Set();
52
61
  queues = new Map();
53
- scheduled = new Set();
54
62
  intake = Promise.resolve();
55
63
  sub;
56
64
  running = false;
65
+ dmActivatedAt;
57
66
  closed = false;
58
67
  starting;
59
68
  stopping;
@@ -66,67 +75,85 @@ export class Client {
66
75
  }
67
76
  /** Resolve the account asynchronously, regardless of local or remote signing. */
68
77
  static async create(options) {
78
+ rejectRemovedIntakeOptions(options);
69
79
  const { signer, ...configuration } = options;
70
- if ('identity' in options) {
71
- throw new TypeError('Client.create accepts signer, not identity');
80
+ if ("identity" in options) {
81
+ throw new TypeError("Client.create accepts signer, not identity");
72
82
  }
73
- if ('storage' in options) {
74
- throw new TypeError('Use messageStorage for custom message history');
83
+ if ("storage" in options) {
84
+ throw new TypeError("Use messageStorage for custom message history");
75
85
  }
76
86
  const identity = await identityFromSigner(signer, {
77
- mode: options.mode ?? 'nip17'
87
+ mode: options.mode ?? "nip17",
78
88
  });
79
89
  return new Client({ ...configuration, identity });
80
90
  }
81
91
  constructor(input) {
92
+ rejectRemovedIntakeOptions(input);
82
93
  const { identity, ...configuration } = input;
83
94
  const roles = relayRoles(configuration);
84
95
  this.blossomServers = normalizeBlossomServers(configuration.blossomServers);
85
96
  this.blossomDownloadOrigins = normalizeBlossomDownloadOrigins(configuration.blossomDownloadOrigins);
86
- const options = this.options = {
97
+ const options = {
87
98
  ...configuration,
88
99
  ...roles,
89
- relays: roles.dmRelays
100
+ relays: roles.dmRelays,
90
101
  };
102
+ this.options = options;
91
103
  this.metadataLookupRelays = relayUnion(roles.readRelays, roles.writeRelays, roles.dmRelays);
92
104
  if (!hexKey(identity.pubkey) || !options.relays.length) {
93
- throw new Error('Identity and at least one relay required');
105
+ throw new Error("Identity and at least one relay required");
94
106
  }
95
- if (options.inboundPolicy !== undefined && typeof options.inboundPolicy !== 'function') {
96
- throw new TypeError('inboundPolicy must be a synchronous identity policy');
97
- }
98
- this.inboundPolicy = options.inboundPolicy;
99
107
  this.account = {
100
- ...identity, oldEncryptionKeys: identity.oldEncryptionKeys?.map(key => new Uint8Array(key))
108
+ ...identity,
109
+ oldEncryptionKeys: identity.oldEncryptionKeys?.map((key) => new Uint8Array(key)),
101
110
  };
102
- if (options.nip4eCompatibility !== undefined && typeof options.nip4eCompatibility !== 'boolean') {
103
- throw new TypeError('nip4eCompatibility must be boolean');
111
+ if (options.nip4eCompatibility !== undefined &&
112
+ typeof options.nip4eCompatibility !== "boolean") {
113
+ throw new TypeError("nip4eCompatibility must be boolean");
104
114
  }
105
- this.mode = options.mode ?? 'nip17';
115
+ this.mode = options.mode ?? "nip17";
106
116
  const scope = protocolScope(this.mode, this.account);
107
- this.nip4eCompatibility = this.mode === 'nip4e' || options.nip4eCompatibility !== false;
117
+ this.nip4eCompatibility =
118
+ this.mode === "nip4e" || options.nip4eCompatibility !== false;
108
119
  if (options.transport && options.transportOptions) {
109
- throw new TypeError('Choose transport or transportOptions, not both');
120
+ throw new TypeError("Choose transport or transportOptions, not both");
110
121
  }
111
- this.transport = options.transport ?? new WebSocketTransport(options.transportOptions ?? {}, template => this.account.sign(template));
122
+ this.transport =
123
+ options.transport ??
124
+ new WebSocketTransport(options.transportOptions ?? {}, (template) => this.account.sign(template));
112
125
  this.ownsTransport = !options.transport;
113
- if ('storage' in options)
114
- throw new TypeError('Internal storage accepts only a database path; use messageStorage for messages');
115
- this.coreStore = new Store(options.database ?? 'psstpsst.sqlite', options.storageKey, scope, options.messageStorage);
126
+ if ("storage" in options)
127
+ throw new TypeError("Internal storage accepts only a database path; use messageStorage for messages");
128
+ const database = options.database ?? "psstpsst.sqlite";
129
+ if (options.attachmentDirectory !== undefined &&
130
+ (typeof options.attachmentDirectory !== "string" ||
131
+ !options.attachmentDirectory.trim())) {
132
+ throw new TypeError("attachmentDirectory must be a nonempty path");
133
+ }
134
+ this.attachments = new AttachmentCache(resolve(options.attachmentDirectory ??
135
+ `${database === ":memory:" ? "psstpsst.sqlite" : database}.attachments`, this.account.pubkey), new Set([
136
+ ...this.blossomServers.map((server) => new URL(server).origin),
137
+ ...this.blossomDownloadOrigins,
138
+ ]));
139
+ this.coreStore = new Store(database, options.storageKey, scope, options.messageStorage);
116
140
  try {
117
- this.metadata = new MessagingMetadata(this.account.pubkey, this.coreStore, this.transport, this.metadataLookupRelays, error => this.report(error), options.reconnect, options.metadataCache);
141
+ this.metadata = new MessagingMetadata(this.account.pubkey, this.coreStore, this.transport, this.metadataLookupRelays, (error) => this.report(error), options.reconnect, options.metadataCache);
118
142
  this.keys = new EncryptionKeys(this.account, this.mode, this.coreStore, this.transport, this.metadataLookupRelays, options.keyRotation, [options.writeRelays, options.dmRelays], this.metadata);
119
143
  if (options.keySync !== false) {
120
- this.keySync = new KeySync(this.account, this.coreStore, this.transport, relayUnion(options.writeRelays, options.dmRelays), key => this.keys.exportEncryptionKey(key), () => this.coreStore.declaration(this.account.pubkey)?.tags.find(tag => tag[0] === 'n')?.[1], options.keySync);
121
- this.keys.setSynchronizer(key => this.keySync.request(key));
144
+ const keySync = new KeySync(this.account, this.coreStore, this.transport, relayUnion(options.writeRelays, options.dmRelays), (key) => this.keys.exportEncryptionKey(key), () => this.coreStore
145
+ .declaration(this.account.pubkey)
146
+ ?.tags.find((tag) => tag[0] === "n")?.[1], options.keySync);
147
+ this.keySync = keySync;
148
+ this.keys.setSynchronizer((key) => keySync.request(key));
122
149
  this.keys.onImported = () => {
123
150
  if (this.running && this.sub) {
124
- void this.sub.sync().catch(error => this.report(error));
151
+ void this.sub.sync().catch((error) => this.report(error));
125
152
  }
126
153
  };
127
154
  this.metadata.onOwnEvent = async (event) => {
128
155
  if (event.kind === 4454) {
129
- await this.keySync.handle(event);
156
+ await keySync.handle(event);
130
157
  return;
131
158
  }
132
159
  if (this.running) {
@@ -137,18 +164,20 @@ export class Client {
137
164
  this.protocol = createMessagingProtocol(this.mode, this.account, this.keys, this.metadata, this.options.dmRelays);
138
165
  this.commands = new CommandCatalog(this.account, this.coreStore, this.transport, this.options.writeRelays);
139
166
  if (options.publicInbox)
140
- this.publicInbox = new PublicInbox(this.account, this.coreStore, this.transport, options.publicInbox, options.writeRelays, options.reconnect, () => this.publicCommandDefinitions(), sender => this.allowsSender(sender), async (input) => {
167
+ this.publicInbox = new PublicInbox(this.account, this.coreStore, this.transport, options.publicInbox, options.writeRelays, options.reconnect, () => this.publicCommandDefinitions(), async (input) => {
141
168
  const context = { active: true };
142
169
  try {
143
- await this.handlerContext.run(context, async () => { for (const handler of this.publicHandlers)
144
- await handler(input); });
170
+ await this.handlerContext.run(context, async () => {
171
+ for (const handler of this.publicHandlers)
172
+ await handler(input);
173
+ });
145
174
  }
146
175
  finally {
147
176
  context.active = false;
148
177
  }
149
- }, error => this.report(error));
178
+ }, (error) => this.report(error));
150
179
  this.coreStore.recoverMessages();
151
- this.announcements = new Announcements(this.account, this.coreStore, this.transport, event => this.metadata.rememberOwn(event));
180
+ this.announcements = new Announcements(this.account, this.coreStore, this.transport, (event) => this.metadata.rememberOwn(event));
152
181
  }
153
182
  catch (error) {
154
183
  this.coreStore.close();
@@ -158,14 +187,14 @@ export class Client {
158
187
  throw error;
159
188
  }
160
189
  }
161
- /** Durable processing group: failures keep the message retryable. Register before start. */
162
- handle(handler) {
190
+ /** Internal Bot handlers manage history admission through the middleware chain. */
191
+ handle(handler, managesAdmission = false) {
163
192
  this.assertOpen();
164
- this.handlers.add(handler);
193
+ this.handlers.set(handler, managesAdmission);
165
194
  return () => this.handlers.delete(handler);
166
195
  }
167
196
  /** Receipt observer only: failures cannot change inbox state or replay business work. */
168
- on(event, observer) {
197
+ on(_event, observer) {
169
198
  this.assertOpen();
170
199
  this.observers.add(observer);
171
200
  return () => this.observers.delete(observer);
@@ -177,16 +206,14 @@ export class Client {
177
206
  report(error, message) {
178
207
  for (const fn of this.errors) {
179
208
  try {
180
- void Promise.resolve(fn(error, message)).catch(() => {
181
- });
182
- }
183
- catch {
209
+ void Promise.resolve(fn(error, message)).catch(() => { });
184
210
  }
211
+ catch { }
185
212
  }
186
213
  }
187
214
  assertOpen() {
188
215
  if (this.closed || this.closing) {
189
- throw new Error('Client is closed or closing');
216
+ throw new Error("Client is closed or closing");
190
217
  }
191
218
  }
192
219
  start(publishMetadata = false) {
@@ -224,7 +251,7 @@ export class Client {
224
251
  if (!current()) {
225
252
  return;
226
253
  }
227
- // Complete publication before starting business subscriptions or replaying handlers.
254
+ // Complete publication before starting business subscriptions.
228
255
  if (publishMetadata)
229
256
  await this.publishKeyMetadata();
230
257
  else
@@ -239,26 +266,24 @@ export class Client {
239
266
  await this.publishMetadata();
240
267
  if (!current())
241
268
  return;
242
- for (const m of this.coreStore.pending()) {
243
- this.enqueue(m);
244
- }
269
+ this.dmActivatedAt = this.coreStore.ensureDmActivation(this.pubkey, Date.now());
245
270
  this.sub = new InboxSubscription({
246
271
  transport: this.transport,
247
272
  store: this.coreStore,
248
273
  relays: this.options.relays,
249
274
  filter: {
250
275
  kinds: [1059],
251
- '#p': [this.account.pubkey],
252
- limit: this.options.historyLimit ?? 500
276
+ "#p": [this.account.pubkey],
277
+ limit: this.options.historyLimit ?? 500,
253
278
  },
254
279
  reconnect: this.options.reconnect,
255
280
  recovery: this.options.recovery,
281
+ recoveryBaseline: Math.floor(this.dmActivatedAt / 1000),
256
282
  localReadWindow: true,
257
283
  receive: (event, source, relay) => this.receive(event, source, {
258
- relay
259
- }).then(() => {
260
- }),
261
- error: error => this.report(error),
284
+ relay,
285
+ }).then(() => { }),
286
+ error: (error) => this.report(error),
262
287
  reconnected: () => this.flushOutbox(),
263
288
  });
264
289
  await this.sub.ready;
@@ -284,123 +309,148 @@ export class Client {
284
309
  }
285
310
  /** Verify and persist a relay event using the same asynchronous signer capabilities. */
286
311
  receive(event, source, metadata) {
312
+ if (!this.running || this.closing)
313
+ return Promise.resolve(false);
287
314
  this.assertOpen();
288
- if ([1, 1111].includes(event.kind))
289
- return Promise.resolve().then(() => this.publicInbox?.receive(event, source, metadata?.relay) ?? false);
290
- const boundary = localReadBoundary(event);
291
- const snapshot = metadata ? {
292
- relay: metadata.relay
293
- } : undefined;
294
- // Preserve wire intake order even when remote decrypt calls complete at different speeds.
315
+ const generation = this.generation;
316
+ const current = () => this.running && this.generation === generation && !this.closing;
317
+ if ([1, 1111].includes(event.kind)) {
318
+ return Promise.resolve().then(() => current()
319
+ ? (this.publicInbox?.receive(event, source, metadata?.relay) ?? false)
320
+ : false);
321
+ }
322
+ const snapshot = metadata
323
+ ? {
324
+ relay: metadata.relay,
325
+ }
326
+ : undefined;
327
+ // Preserve wire intake order; stop fences any decryption that was not yet admitted.
295
328
  const task = this.intake.then(async () => {
296
- const decoded = await unwrapAsync(event, this.account, this.protocol.envelope);
297
- return decoded ? this.accept(decoded, source === 'history' && boundary !== undefined && decoded.rumor.created_at > boundary ? 'live' : source, snapshot) : false;
298
- });
299
- this.intake = task.then(() => {
300
- }, () => {
329
+ if (!current())
330
+ return false;
331
+ try {
332
+ const decoded = await unwrapAsync(event, this.account, this.protocol.envelope, current);
333
+ return current() && decoded
334
+ ? this.accept(decoded, source, snapshot)
335
+ : false;
336
+ }
337
+ catch (error) {
338
+ if (!current())
339
+ return false;
340
+ throw error;
341
+ }
301
342
  });
343
+ this.intake = task.then(() => { }, () => { });
302
344
  return task;
303
345
  }
304
346
  accept(decoded, source, metadata) {
305
347
  const r = decoded.rumor, own = r.pubkey === this.account.pubkey;
306
- // decode has verified both signatures, rumor hash and equality with the signed seal author.
307
- if (!own && !this.allowsSender(r.pubkey)) {
348
+ // Classification uses only authenticated rumor time; relay/history labels and
349
+ // intentionally backdated wrappers never decide business eligibility.
350
+ if (this.dmActivatedAt === undefined ||
351
+ !createdAtOrAfter(r, this.dmActivatedAt))
352
+ return false;
353
+ const conversation = own
354
+ ? r.tags.find((tag) => tag[0] === "p")?.[1]
355
+ : r.pubkey;
356
+ if (!conversation ||
357
+ (r.kind === 15 && !parseAttachment(r)) ||
358
+ (!own && !this.coreStore.claimInput(r.id)))
308
359
  return false;
309
- }
310
360
  const replyTo = replyTarget(r);
311
361
  const message = {
312
362
  id: r.id,
313
363
  sender: r.pubkey,
314
- conversation: own ? r.tags.find(t => t[0] === 'p')[1] : r.pubkey,
315
- text: r.content,
364
+ conversation,
365
+ text: r.kind === 15 ? "" : r.content,
316
366
  timestamp: timestamp(r),
317
367
  source,
318
- direction: own ? 'outgoing' : 'incoming',
368
+ direction: own ? "outgoing" : "incoming",
319
369
  rumor: r,
320
370
  ...(replyTo === undefined ? {} : { replyTo }),
321
- ...(metadata?.relay ? {
322
- relay: metadata.relay
323
- } : {})
371
+ ...(metadata?.relay
372
+ ? {
373
+ relay: metadata.relay,
374
+ }
375
+ : {}),
324
376
  };
377
+ if (!own) {
378
+ this.enqueue(message, decoded);
379
+ return true;
380
+ }
325
381
  let inserted = false;
326
382
  this.coreStore.transaction(() => {
327
383
  this.protocol.remember(decoded, this.coreStore);
328
384
  inserted = this.coreStore.insert(message);
329
385
  });
330
- if (source === 'live' && !own && this.running && (inserted || this.coreStore.messageState(message.id) === 'pending')) {
331
- this.enqueue(message);
332
- }
333
- if (inserted && source === 'live' && !own && this.running) {
334
- // Notify once per receipt, using detached copies outside the durable processing group.
335
- for (const observer of this.observers) {
336
- try {
337
- void Promise.resolve(observer(structuredClone(message))).catch(error => this.report(error, structuredClone(message)));
338
- }
339
- catch (error) {
340
- this.report(error, structuredClone(message));
341
- }
342
- }
343
- }
344
386
  return inserted;
345
387
  }
346
- allowsSender(identity) {
347
- const policy = this.inboundPolicy;
348
- if (policy === undefined)
349
- return true;
350
- const accepted = policy(identity);
351
- if (typeof accepted !== 'boolean') {
352
- // JavaScript callers cannot accidentally authorize with a Promise or truthy value.
353
- void Promise.resolve(accepted).catch(() => { });
354
- throw new TypeError('inboundPolicy must return a boolean synchronously');
355
- }
356
- return accepted;
357
- }
358
- enqueue(message) {
359
- // Encrypted pending records were authenticated on receipt. Recheck the saved identity,
360
- // including sender/rumor consistency, before any listener, middleware or session access.
361
- if (message.direction !== 'incoming' || message.sender !== message.rumor.pubkey || message.sender === this.account.pubkey || !this.allowsSender(message.rumor.pubkey)) {
362
- this.coreStore.state(message.id, 'done');
363
- return; // Consume previously accepted work revoked by new configuration.
364
- }
365
- if (this.scheduled.has(message.id)) {
366
- return;
367
- }
368
- this.scheduled.add(message.id);
388
+ enqueue(message, decoded) {
369
389
  const previous = this.queues.get(message.conversation) ?? Promise.resolve();
370
- const next = previous.catch(() => {
371
- }).then(async () => {
372
- this.coreStore.state(message.id, 'processing');
390
+ const next = previous
391
+ .catch(() => { })
392
+ .then(async () => {
393
+ let admitted = false;
394
+ const admit = () => {
395
+ if (admitted)
396
+ return;
397
+ this.coreStore.transaction(() => {
398
+ this.protocol.remember(decoded, this.coreStore);
399
+ this.coreStore.insert(message, "processing");
400
+ });
401
+ admitted = true;
402
+ for (const observer of this.observers) {
403
+ try {
404
+ void Promise.resolve(observer(structuredClone(message))).catch((error) => this.report(error, structuredClone(message)));
405
+ }
406
+ catch (error) {
407
+ this.report(error, structuredClone(message));
408
+ }
409
+ }
410
+ };
411
+ const context = { active: true };
373
412
  try {
374
- const context = {
375
- active: true
376
- };
377
- try {
378
- await this.handlerContext.run(context, async () => {
379
- for (const handler of this.handlers) {
380
- await handler(message);
413
+ await this.handlerContext.run(context, async () => {
414
+ // Raw internal listeners are not a second route around Bot middleware.
415
+ const handlers = [...this.handlers];
416
+ const managed = handlers.filter(([, managesAdmission]) => managesAdmission);
417
+ for (const [handler] of managed)
418
+ await handler(structuredClone(message), admit, decoded);
419
+ if (!managed.length)
420
+ admit();
421
+ if (admitted) {
422
+ for (const [handler, managesAdmission] of handlers) {
423
+ if (!managesAdmission)
424
+ await handler(structuredClone(message), admit, decoded);
381
425
  }
382
- });
426
+ }
427
+ });
428
+ if (admitted)
429
+ this.coreStore.state(message.id, "done");
430
+ }
431
+ catch (error) {
432
+ try {
433
+ if (admitted)
434
+ this.coreStore.state(message.id, "failed");
383
435
  }
384
436
  finally {
385
- context.active = false;
437
+ this.report(error, message);
386
438
  }
387
- this.coreStore.state(message.id, 'done');
388
439
  }
389
- catch (e) {
390
- this.coreStore.state(message.id, 'failed');
391
- this.report(e, message);
440
+ finally {
441
+ context.active = false;
392
442
  }
393
- }).catch(error => this.report(error, message));
443
+ })
444
+ .catch((error) => this.report(error, message));
394
445
  this.queues.set(message.conversation, next);
395
446
  void next.finally(() => {
396
- this.scheduled.delete(message.id);
397
447
  if (this.queues.get(message.conversation) === next) {
398
448
  this.queues.delete(message.conversation);
399
449
  }
400
450
  });
401
451
  }
402
452
  async idle() {
403
- this.assertOutsideHandler('idle()');
453
+ this.assertOutsideHandler("idle()");
404
454
  await this.drainInbox();
405
455
  await this.publicInbox?.idle();
406
456
  }
@@ -414,60 +464,49 @@ export class Client {
414
464
  }
415
465
  }
416
466
  }
417
- async retryInbox(options = {}) {
418
- this.assertOpen();
419
- this.assertOutsideHandler('retryInbox()');
420
- if (options.ids && (!Array.isArray(options.ids) || !options.ids.every(hexKey))) {
421
- throw new TypeError('Invalid retry message IDs');
422
- }
423
- const ids = options.ids ? new Set(options.ids) : undefined;
424
- await this.idle();
425
- for (const message of this.coreStore.pending()) {
426
- if (!ids || ids.has(message.id)) {
427
- this.enqueue(message);
428
- }
429
- }
430
- this.publicInbox?.retry(ids);
431
- await this.idle();
432
- }
433
467
  getMessage(id, peer) {
434
468
  this.assertOpen();
435
469
  if (!hexKey(id))
436
- throw new TypeError('Invalid message ID');
437
- return this.coreStore.getMessage(id, peer);
470
+ throw new TypeError("Invalid message ID");
471
+ const message = this.coreStore.getMessage(id, peer);
472
+ return message && this.withAttachment(message);
438
473
  }
439
474
  getMessageState(id) {
440
475
  this.assertOpen();
441
476
  if (!hexKey(id)) {
442
- throw new TypeError('Invalid message ID');
477
+ throw new TypeError("Invalid message ID");
443
478
  }
444
479
  return this.coreStore.messageState(id);
445
480
  }
446
481
  listMessages(options) {
447
482
  this.assertOpen();
448
- return this.coreStore.listMessages(options);
483
+ const page = this.coreStore.listMessages(options);
484
+ for (const entry of page.entries)
485
+ this.withAttachment(entry.message);
486
+ return page;
449
487
  }
450
488
  // Closing rejects new work, but a draining handler must still commit its session.
451
489
  assertSessionOpen() {
452
- if (this.closed || (this.closing && !this.handlerContext.getStore()?.active)) {
453
- throw new Error('Client is closed or closing');
490
+ if (this.closed ||
491
+ (this.closing && !this.handlerContext.getStore()?.active)) {
492
+ throw new Error("Client is closed or closing");
454
493
  }
455
494
  }
456
495
  getSession(peer) {
457
496
  this.assertSessionOpen();
458
497
  if (!hexKey(peer)) {
459
- throw new TypeError('Invalid session peer');
498
+ throw new TypeError("Invalid session peer");
460
499
  }
461
500
  return this.coreStore.session(peer);
462
501
  }
463
502
  setSession(peer, value) {
464
503
  this.assertSessionOpen();
465
504
  if (!hexKey(peer)) {
466
- throw new TypeError('Invalid session peer');
505
+ throw new TypeError("Invalid session peer");
467
506
  }
468
507
  this.coreStore.saveSession(peer, value);
469
508
  }
470
- assertOutsideHandler(operation = 'stop() or close()') {
509
+ assertOutsideHandler(operation = "stop() or close()") {
471
510
  if (this.handlerContext.getStore()?.active) {
472
511
  throw new Error(`Cannot await ${operation} inside a message handler; drain outside the handler and use requestStop() for shutdown`);
473
512
  }
@@ -483,20 +522,17 @@ export class Client {
483
522
  this.publicInbox?.stop();
484
523
  // Cancel an initial metadata read before waiting for startup to finish.
485
524
  const metadata = this.metadata.stop();
486
- void metadata.catch(() => {
487
- });
525
+ void metadata.catch(() => { });
488
526
  return metadata;
489
527
  }
490
528
  async drainStop(metadata) {
491
529
  await this.drainInbox();
492
530
  await this.publicInbox?.idle();
493
531
  if (this.flushing) {
494
- await this.flushing.catch(() => {
495
- });
532
+ await this.flushing.catch(() => { });
496
533
  }
497
534
  await this.keys.idle();
498
- await this.announcing?.catch(() => {
499
- });
535
+ await this.announcing?.catch(() => { });
500
536
  await this.announcements.idle();
501
537
  await this.synchronizing?.catch(() => { });
502
538
  await this.commands.idle();
@@ -509,11 +545,9 @@ export class Client {
509
545
  }
510
546
  const startup = this.starting, metadata = this.quiesce();
511
547
  const task = (async () => {
512
- await startup?.catch(() => {
513
- });
548
+ await startup?.catch(() => { });
514
549
  await this.drainStop(metadata);
515
- })()
516
- .finally(() => {
550
+ })().finally(() => {
517
551
  if (this.stopping === task) {
518
552
  this.stopping = undefined;
519
553
  }
@@ -524,7 +558,7 @@ export class Client {
524
558
  /** Handler-safe stop request; await stop() outside handlers to drain current work. */
525
559
  requestStop() {
526
560
  this.assertOpen();
527
- void this.stopInternal().catch(error => this.report(error));
561
+ void this.stopInternal().catch((error) => this.report(error));
528
562
  }
529
563
  async stop() {
530
564
  this.assertOutsideHandler();
@@ -565,13 +599,29 @@ export class Client {
565
599
  async syncHistory() {
566
600
  this.assertOpen();
567
601
  if (!this.sub || !this.running) {
568
- throw new Error('Start the client before synchronizing history');
602
+ throw new Error("Start the client before synchronizing history");
569
603
  }
570
604
  return this.sub.sync();
571
605
  }
572
606
  history(peer, options) {
573
607
  this.assertOpen();
574
- return this.coreStore.history(peer, options);
608
+ const page = this.coreStore.history(peer, options);
609
+ for (const message of page.messages)
610
+ this.withAttachment(message);
611
+ return page;
612
+ }
613
+ withAttachment(message) {
614
+ const { id, rumor, conversation } = message;
615
+ const file = this.attachments.attachment(rumor, () => !this.closed &&
616
+ this.coreStore.getMessage(id, conversation) !== undefined);
617
+ if (file)
618
+ message.file = file;
619
+ return message;
620
+ }
621
+ inputForMessage(message) {
622
+ const input = inputOf(message.rumor);
623
+ const { file } = this.withAttachment(message);
624
+ return file ? { ...input, file } : input;
575
625
  }
576
626
  /** Rebind an unsigned rumor only to this account's authenticated incoming record. */
577
627
  authenticatedInput(event) {
@@ -580,31 +630,51 @@ export class Client {
580
630
  snapshot = structuredClone(event);
581
631
  }
582
632
  catch {
583
- throw new TypeError('Expected an authenticated input event');
633
+ throw new TypeError("Expected an authenticated input event");
584
634
  }
585
- if (!snapshot || typeof snapshot !== 'object')
586
- throw new TypeError('Expected an input event, not an ID');
635
+ if (!snapshot || typeof snapshot !== "object")
636
+ throw new TypeError("Expected an input event, not an ID");
587
637
  if (snapshot.kind === 1 || snapshot.kind === 1111) {
588
638
  if (!this.publicInbox)
589
- throw new Error('Public inbox is not configured');
639
+ throw new Error("Public inbox is not configured");
590
640
  return this.publicInbox.target(snapshot);
591
641
  }
592
- if (snapshot.kind !== 14 || 'sig' in snapshot || !hexKey(snapshot.id))
593
- throw new TypeError('Expected a signed kind 1/1111 event or authenticated kind 14 rumor');
642
+ if ((snapshot.kind !== 14 && snapshot.kind !== 15) ||
643
+ "sig" in snapshot ||
644
+ !hexKey(snapshot.id))
645
+ throw new TypeError("Expected a signed kind 1/1111 event or authenticated kind 14/15 rumor");
594
646
  const message = this.coreStore.getMessage(snapshot.id);
595
- const canonical = (input) => JSON.stringify([input.id, input.pubkey, input.kind, input.created_at, input.tags, input.content]);
596
- const recipients = Array.isArray(snapshot.tags) ? snapshot.tags.filter(tag => Array.isArray(tag) && tag[0] === 'p') : [];
647
+ if (!message) {
648
+ throw new TypeError("DM input does not match an authenticated incoming record for this account");
649
+ }
650
+ const canonical = (input) => JSON.stringify([
651
+ input.id,
652
+ input.pubkey,
653
+ input.kind,
654
+ input.created_at,
655
+ input.tags,
656
+ input.content,
657
+ ]);
658
+ const recipients = Array.isArray(snapshot.tags)
659
+ ? snapshot.tags.filter((tag) => Array.isArray(tag) && tag[0] === "p")
660
+ : [];
597
661
  try {
598
- if (!message || message.direction !== 'incoming' || message.sender === this.pubkey ||
599
- message.sender !== snapshot.pubkey || message.conversation !== snapshot.pubkey ||
600
- recipients.length !== 1 || recipients[0][1] !== this.pubkey ||
601
- snapshot.id !== getEventHash(snapshot) || canonical(snapshot) !== canonical(message.rumor) ||
602
- message.id !== snapshot.id || message.text !== snapshot.content || message.timestamp !== timestamp(snapshot) ||
662
+ if (message.direction !== "incoming" ||
663
+ message.sender === this.pubkey ||
664
+ message.sender !== snapshot.pubkey ||
665
+ message.conversation !== snapshot.pubkey ||
666
+ recipients.length !== 1 ||
667
+ recipients[0][1] !== this.pubkey ||
668
+ snapshot.id !== getEventHash(snapshot) ||
669
+ canonical(snapshot) !== canonical(message.rumor) ||
670
+ message.id !== snapshot.id ||
671
+ message.text !== (snapshot.kind === 15 ? "" : snapshot.content) ||
672
+ message.timestamp !== timestamp(snapshot) ||
603
673
  message.replyTo !== replyTarget(snapshot))
604
674
  throw new Error();
605
675
  }
606
676
  catch {
607
- throw new TypeError('DM input does not match an authenticated incoming record for this account');
677
+ throw new TypeError("DM input does not match an authenticated incoming record for this account");
608
678
  }
609
679
  return structuredClone(message);
610
680
  }
@@ -612,18 +682,28 @@ export class Client {
612
682
  async reply(event, text, options) {
613
683
  this.assertOpen();
614
684
  const target = this.authenticatedInput(event);
615
- if ('rumor' in target)
685
+ if ("rumor" in target)
616
686
  return this.send(target.conversation, text, options);
617
687
  if (options && Object.keys(options).length)
618
- throw new TypeError('DM send options are not valid for public replies');
688
+ throw new TypeError("DM send options are not valid for public replies");
619
689
  return this.replyPublic(target, text);
620
690
  }
621
691
  async replyFile(event, data, options = {}) {
622
692
  this.assertOpen();
623
693
  const target = this.authenticatedInput(event);
624
- if ('rumor' in target) {
625
- return this.sendFile(target.conversation, data, { ...options, replyTo: target.id });
694
+ if ("rumor" in target) {
695
+ return this.sendFile(target.conversation, data, {
696
+ ...options,
697
+ replyTo: target.id,
698
+ });
626
699
  }
700
+ return this.replyPublicFile(target, data, options);
701
+ }
702
+ /** Verified public context retains its source relay without journaling the input. */
703
+ async replyPublicFile(target, data, options = {}) {
704
+ this.assertOpen();
705
+ if (!this.publicInbox)
706
+ throw new Error("Public inbox is not configured");
627
707
  const { mimeType } = options;
628
708
  const bytes = snapshotFile(data);
629
709
  return this.publicInbox.replyFile(target, async () => {
@@ -635,41 +715,80 @@ export class Client {
635
715
  async thread(event, options) {
636
716
  this.assertOpen();
637
717
  const target = this.authenticatedInput(event);
638
- return 'rumor' in target ? this.threadPrivate(target, options) : this.threadPublic(target, options);
639
- }
640
- publicKinds() { return [...new Set(this.publicCommandDefinitions().flatMap(definition => (definition.scopes ?? []).filter(scope => scope === 'kind:1' || scope === 'kind:1111').map(scope => Number(scope.slice(5)))))]; }
641
- handlePublic(handler) { this.publicHandlers.add(handler); return () => { this.publicHandlers.delete(handler); }; }
642
- replyPublic(input, text) { this.assertOpen(); if (!this.publicInbox)
643
- throw new Error('Public inbox is not configured'); return this.publicInbox.reply(input, text); }
644
- threadPublic(input, options) { this.assertOpen(); if (!this.publicInbox)
645
- throw new Error('Public inbox is not configured'); return this.publicInbox.thread(input, options); }
646
- getPublicSession(key) { this.assertSessionOpen(); return this.coreStore.metadata(`public-session:${key}`); }
647
- setPublicSession(key, value) { this.assertSessionOpen(); this.coreStore.saveMetadata(`public-session:${key}`, value); }
718
+ return "rumor" in target
719
+ ? this.threadPrivate(target, options)
720
+ : this.threadPublic(target, options);
721
+ }
722
+ publicKinds() {
723
+ return [
724
+ ...new Set(this.publicCommandDefinitions().flatMap((definition) => (definition.scopes ?? [])
725
+ .filter((scope) => scope === "kind:1" || scope === "kind:1111")
726
+ .map((scope) => Number(scope.slice(5))))),
727
+ ];
728
+ }
729
+ handlePublic(handler) {
730
+ this.publicHandlers.add(handler);
731
+ return () => {
732
+ this.publicHandlers.delete(handler);
733
+ };
734
+ }
735
+ replyPublic(input, text) {
736
+ this.assertOpen();
737
+ if (!this.publicInbox)
738
+ throw new Error("Public inbox is not configured");
739
+ return this.publicInbox.reply(input, text);
740
+ }
741
+ threadPublic(input, options) {
742
+ this.assertOpen();
743
+ if (!this.publicInbox)
744
+ throw new Error("Public inbox is not configured");
745
+ return this.publicInbox.thread(input, options);
746
+ }
747
+ getPublicSession(key) {
748
+ this.assertSessionOpen();
749
+ return this.coreStore.metadata(`public-session:${key}`);
750
+ }
751
+ setPublicSession(key, value) {
752
+ this.assertSessionOpen();
753
+ this.coreStore.saveMetadata(`public-session:${key}`, value);
754
+ }
648
755
  async threadPrivate(message, options = {}) {
649
756
  const limit = threadLimit(options.limit);
650
757
  let cursor;
651
758
  const prior = [];
652
759
  for (let page = 0; page < 10 && prior.length <= limit; page++) {
653
- const history = this.history(message.conversation, { limit: 100, cursor });
654
- prior.push(...history.messages.filter(item => item.id !== message.id && (item.timestamp < message.timestamp || (item.timestamp === message.timestamp && item.id < message.id))));
760
+ const history = this.coreStore.history(message.conversation, {
761
+ limit: 100,
762
+ cursor,
763
+ });
764
+ prior.push(...history.messages.filter((item) => item.id !== message.id &&
765
+ (item.timestamp < message.timestamp ||
766
+ (item.timestamp === message.timestamp && item.id < message.id))));
655
767
  cursor = history.nextCursor;
656
768
  if (!cursor)
657
769
  break;
658
770
  }
659
- return { entries: prior.slice(0, limit).reverse().map(item => inputOf(item.rumor)), complete: false, coverage: 'local-conversation', reason: 'local-only' };
771
+ return {
772
+ entries: prior
773
+ .slice(0, limit)
774
+ .reverse()
775
+ .map((item) => this.inputForMessage(item)),
776
+ complete: false,
777
+ coverage: "local-conversation",
778
+ reason: "local-only",
779
+ };
660
780
  }
661
781
  /** Register one public command coordinate. Startup reconciles the complete local set. */
662
782
  registerCommandDefinition(definition) {
663
783
  this.assertOpen();
664
- if (arguments.length > 1)
665
- throw new TypeError('Commands are always public on configured write relays');
666
784
  this.managesCommandCatalog = true;
667
785
  const snapshot = validateCommandDefinition(definition);
668
- if (snapshot.scopes?.some(scope => scope === 'kind:1' || scope === 'kind:1111') && !this.publicInbox)
669
- throw new TypeError('Public commands require explicit publicInbox.relays');
786
+ if (snapshot.scopes?.some((scope) => scope === "kind:1" || scope === "kind:1111") &&
787
+ !this.publicInbox)
788
+ throw new TypeError("Public commands require explicit publicInbox.relays");
670
789
  const old = this.commandDefinitions.get(snapshot.id);
671
790
  if (old && JSON.stringify(old.definition) !== JSON.stringify(snapshot))
672
- throw new TypeError('Conflicting command coordinate');
791
+ throw new TypeError("Conflicting command coordinate");
673
792
  const entry = old ?? { definition: snapshot, refs: 0 };
674
793
  entry.refs++;
675
794
  this.commandDefinitions.set(snapshot.id, entry);
@@ -681,19 +800,29 @@ export class Client {
681
800
  if (removed)
682
801
  return;
683
802
  removed = true;
684
- if (this.commandDefinitions.get(snapshot.id) === entry && --entry.refs === 0 && !entry.manual) {
803
+ if (this.commandDefinitions.get(snapshot.id) === entry &&
804
+ --entry.refs === 0 &&
805
+ !entry.manual) {
685
806
  this.commandDefinitions.delete(snapshot.id);
686
807
  this.commandRevision++;
687
808
  this.scheduleCommandSync();
688
809
  }
689
810
  };
690
- return Object.assign(unregister, { active: () => !removed && this.commandDefinitions.get(snapshot.id) === entry });
811
+ return Object.assign(unregister, {
812
+ active: () => !removed && this.commandDefinitions.get(snapshot.id) === entry,
813
+ });
691
814
  }
692
815
  /** Claim the bot-owned command catalog, including an intentionally empty registry. */
693
- manageCommands() { this.assertOpen(); this.managesCommandCatalog = true; this.scheduleCommandSync(); }
694
- hasCommand(id) { return this.commandDefinitions.has(id); }
816
+ manageCommands() {
817
+ this.assertOpen();
818
+ this.managesCommandCatalog = true;
819
+ this.scheduleCommandSync();
820
+ }
821
+ hasCommand(id) {
822
+ return this.commandDefinitions.has(id);
823
+ }
695
824
  publicCommandDefinitions() {
696
- return [...this.commandDefinitions.values()].map(entry => structuredClone(entry.definition));
825
+ return [...this.commandDefinitions.values()].map((entry) => structuredClone(entry.definition));
697
826
  }
698
827
  scheduleCommandSync() {
699
828
  if (!this.running || this.closing || this.commandSyncScheduled)
@@ -702,7 +831,7 @@ export class Client {
702
831
  queueMicrotask(() => {
703
832
  this.commandSyncScheduled = false;
704
833
  if (this.running && !this.closing)
705
- void this.syncCommands().catch(error => this.report(error));
834
+ void this.syncCommands().catch((error) => this.report(error));
706
835
  });
707
836
  }
708
837
  /** Synchronize public definitions and NIP-09 withdrawals on write relays. */
@@ -719,10 +848,13 @@ export class Client {
719
848
  for (;;) {
720
849
  const revision = this.commandRevision, removals = [...this.revokedCommands];
721
850
  const result = await this.commands.sync(this.publicCommandDefinitions(), removals, active);
722
- for (const category of ['added', 'updated', 'removed']) {
851
+ for (const category of ["added", "updated", "removed"]) {
723
852
  for (const id of result[category]) {
724
- const change = changes.get(id) ?? { initial: category !== 'added', current: false };
725
- change.current = category !== 'removed';
853
+ const change = changes.get(id) ?? {
854
+ initial: category !== "added",
855
+ current: false,
856
+ };
857
+ change.current = category !== "removed";
726
858
  changes.set(id, change);
727
859
  }
728
860
  }
@@ -734,22 +866,28 @@ export class Client {
734
866
  await this.publicInbox?.start(this.publicKinds());
735
867
  // Registration can change while the new public subscription waits for EOSE.
736
868
  if (!active())
737
- throw new Error('Command synchronization canceled');
869
+ throw new Error("Command synchronization canceled");
738
870
  if (this.commandRevision !== revision)
739
871
  continue;
740
872
  this.syncedCommandRevision = revision;
741
- const combined = { added: [], updated: [], removed: [] };
873
+ const combined = {
874
+ added: [],
875
+ updated: [],
876
+ removed: [],
877
+ };
742
878
  for (const [id, change] of changes) {
743
879
  if (change.current)
744
- combined[change.initial ? 'updated' : 'added'].push(id);
880
+ combined[change.initial ? "updated" : "added"].push(id);
745
881
  else if (change.initial)
746
882
  combined.removed.push(id);
747
883
  }
748
884
  return combined;
749
885
  }
750
886
  }
751
- })().finally(() => { if (this.synchronizing === task)
752
- this.synchronizing = undefined; });
887
+ })().finally(() => {
888
+ if (this.synchronizing === task)
889
+ this.synchronizing = undefined;
890
+ });
753
891
  this.synchronizing = task;
754
892
  return task;
755
893
  }
@@ -790,21 +928,35 @@ export class Client {
790
928
  kind: 10002,
791
929
  created_at,
792
930
  tags: readWriteTags(this.options.readRelays, this.options.writeRelays),
793
- content: ''
794
- }, groups: [writeRelays], optionalRelays: discoveryRelays
931
+ content: "",
932
+ },
933
+ groups: [writeRelays],
934
+ optionalRelays: discoveryRelays,
795
935
  },
796
936
  {
797
937
  template: {
798
938
  kind: 10050,
799
939
  created_at,
800
- tags: this.options.dmRelays.map(url => ['relay', url]),
801
- content: ''
802
- }, groups: [writeRelays, dmRelays], optionalRelays: discoveryRelays
940
+ tags: this.options.dmRelays.map((url) => ["relay", url]),
941
+ content: "",
942
+ },
943
+ groups: [writeRelays, dmRelays],
944
+ optionalRelays: discoveryRelays,
803
945
  },
804
- ...(this.blossomServers.length ? [{
805
- template: { kind: 10063, created_at, tags: this.blossomServers.map(url => ['server', url]), content: '' },
806
- groups: [writeRelays], optionalRelays: discoveryRelays,
807
- }] : []),
946
+ ...(this.blossomServers.length
947
+ ? [
948
+ {
949
+ template: {
950
+ kind: 10063,
951
+ created_at,
952
+ tags: this.blossomServers.map((url) => ["server", url]),
953
+ content: "",
954
+ },
955
+ groups: [writeRelays],
956
+ optionalRelays: discoveryRelays,
957
+ },
958
+ ]
959
+ : []),
808
960
  ]);
809
961
  }
810
962
  /** Retry exact persisted public metadata; it does not register/execute discovered commands. */
@@ -815,7 +967,9 @@ export class Client {
815
967
  await this.keys.prepare();
816
968
  }
817
969
  // Background retries should not poll every relay once the registry has converged.
818
- if (this.managesCommandCatalog && (this.syncedCommandRevision !== this.commandRevision || this.commands.hasPending())) {
970
+ if (this.managesCommandCatalog &&
971
+ (this.syncedCommandRevision !== this.commandRevision ||
972
+ this.commands.hasPending())) {
819
973
  await this.syncCommands();
820
974
  }
821
975
  if (pendingKey || this.announcements.hasPending()) {
@@ -842,7 +996,10 @@ export class Client {
842
996
  return;
843
997
  }
844
998
  this.rotationTimer = setTimeout(() => {
845
- void this.keys.rotateIfDue().catch(error => this.report(error)).finally(() => this.scheduleRotation());
999
+ void this.keys
1000
+ .rotateIfDue()
1001
+ .catch((error) => this.report(error))
1002
+ .finally(() => this.scheduleRotation());
846
1003
  }, delay);
847
1004
  this.rotationTimer.unref();
848
1005
  }
@@ -850,53 +1007,62 @@ export class Client {
850
1007
  this.assertOpen();
851
1008
  const metadata = await this.protocol.resolve(peer, this.coreStore, this.transport, this.metadataLookupRelays, true);
852
1009
  return {
853
- encryptionPubkey: metadata.encryptionPubkey, relays: metadata.relays
1010
+ encryptionPubkey: metadata.encryptionPubkey,
1011
+ relays: metadata.relays,
854
1012
  };
855
1013
  }
856
1014
  async publishCommand(definition) {
857
1015
  this.assertOpen();
858
- if (arguments.length > 1)
859
- throw new TypeError('Commands are always public on configured write relays');
860
1016
  this.managesCommandCatalog = true;
861
1017
  const snapshot = validateCommandDefinition(definition), old = this.commandDefinitions.get(snapshot.id);
862
- if (old && old.refs > 0 && JSON.stringify(old.definition) !== JSON.stringify(snapshot))
863
- throw new TypeError('Replace the registered Bot command before publishing a changed definition');
1018
+ if (old &&
1019
+ old.refs > 0 &&
1020
+ JSON.stringify(old.definition) !== JSON.stringify(snapshot))
1021
+ throw new TypeError("Replace the registered Bot command before publishing a changed definition");
864
1022
  if (old) {
865
1023
  old.definition = snapshot;
866
1024
  old.manual = true;
867
1025
  }
868
1026
  else {
869
- this.commandDefinitions.set(snapshot.id, { definition: snapshot, refs: 0, manual: true });
1027
+ this.commandDefinitions.set(snapshot.id, {
1028
+ definition: snapshot,
1029
+ refs: 0,
1030
+ manual: true,
1031
+ });
870
1032
  }
871
1033
  this.revokedCommands.delete(snapshot.id);
872
1034
  this.commandRevision++;
873
1035
  await this.syncCommands();
874
- return { event: this.commands.definition(snapshot.id), status: 'relay-accepted' };
1036
+ const event = this.commands.definition(snapshot.id);
1037
+ if (!event)
1038
+ throw new Error("Command definition missing after synchronization");
1039
+ return { event, status: "relay-accepted" };
875
1040
  }
876
1041
  async revokeCommand(id) {
877
1042
  this.assertOpen();
878
- if (arguments.length > 1)
879
- throw new TypeError('Commands are always public on configured write relays');
880
1043
  this.managesCommandCatalog = true;
881
- if (typeof id !== 'string')
882
- throw new TypeError('Invalid command ID');
1044
+ if (typeof id !== "string")
1045
+ throw new TypeError("Invalid command ID");
883
1046
  this.commandDefinitions.delete(id);
884
1047
  this.revokedCommands.add(id);
885
1048
  this.commandRevision++;
886
1049
  await this.syncCommands();
887
- return { event: this.commands.revocation(id), status: 'relay-accepted' };
1050
+ const event = this.commands.revocation(id);
1051
+ if (!event)
1052
+ throw new Error("Command revocation missing after synchronization");
1053
+ return { event, status: "relay-accepted" };
888
1054
  }
889
1055
  async discoverCommands(options) {
890
1056
  this.assertOpen();
891
1057
  return discoverCommandCatalog(this.transport, options);
892
1058
  }
893
- async send(peer, text, { replyTo } = {}) {
1059
+ async send(peer, text, { replyTo } = {}, input) {
894
1060
  this.assertOpen();
895
- if (typeof text !== 'string' || !text.length) {
896
- throw new Error('Nonempty text required');
1061
+ if (typeof text !== "string" || !text.length) {
1062
+ throw new Error("Nonempty text required");
897
1063
  }
898
1064
  if (replyTo !== undefined && !hexKey(replyTo)) {
899
- throw new TypeError('replyTo must be a lowercase hex message ID');
1065
+ throw new TypeError("replyTo must be a lowercase hex message ID");
900
1066
  }
901
1067
  const r = rumor(this.account.pubkey, peer, text, undefined, replyTo);
902
1068
  const message = {
@@ -905,53 +1071,71 @@ export class Client {
905
1071
  conversation: peer,
906
1072
  text,
907
1073
  timestamp: timestamp(r),
908
- source: 'live',
909
- direction: 'outgoing',
1074
+ source: "live",
1075
+ direction: "outgoing",
910
1076
  rumor: r,
911
1077
  ...(replyTo === undefined ? {} : { replyTo }),
912
1078
  };
913
- return this.publishPrivate(peer, r, message);
1079
+ return this.publishPrivate(peer, r, message, input);
914
1080
  }
915
1081
  async uploadFile(data, options) {
916
1082
  this.assertOpen();
917
1083
  return uploadFile(this.account, this.blossomServers, this.blossomDownloadOrigins, data, options);
918
1084
  }
919
- async sendFile(peer, data, options = {}) {
1085
+ async sendFile(peer, data, options = {}, input) {
920
1086
  this.assertOpen();
921
1087
  if (!this.blossomServers.length)
922
- throw new Error('Configure blossomServers before sending files');
1088
+ throw new Error("Configure blossomServers before sending files");
923
1089
  if (!hexKey(peer))
924
- throw new TypeError('Expected a lowercase hex recipient pubkey');
1090
+ throw new TypeError("Expected a lowercase hex recipient pubkey");
925
1091
  const { replyTo } = options;
926
1092
  if (replyTo !== undefined && !hexKey(replyTo))
927
- throw new TypeError('replyTo must be a lowercase hex message ID');
1093
+ throw new TypeError("replyTo must be a lowercase hex message ID");
928
1094
  const { bytes, tags } = encryptAttachment(data, options);
929
1095
  await this.protocol.prepare();
930
1096
  this.assertOpen();
931
1097
  const { url, sha256, size } = await this.uploadFile(bytes);
932
1098
  this.assertOpen();
933
- const r = fileRumor(this.account.pubkey, peer, url, [...tags, ['x', sha256], ['size', String(size)]], replyTo);
1099
+ const r = fileRumor(this.account.pubkey, peer, url, [...tags, ["x", sha256], ["size", String(size)]], replyTo);
934
1100
  return this.publishPrivate(peer, r, {
935
- id: r.id, sender: r.pubkey, conversation: peer, text: '',
936
- timestamp: timestamp(r), source: 'live', direction: 'outgoing', rumor: r,
1101
+ id: r.id,
1102
+ sender: r.pubkey,
1103
+ conversation: peer,
1104
+ text: "",
1105
+ timestamp: timestamp(r),
1106
+ source: "live",
1107
+ direction: "outgoing",
1108
+ rumor: r,
937
1109
  ...(replyTo === undefined ? {} : { replyTo }),
938
- });
1110
+ }, input);
939
1111
  }
940
- async react(id, reaction = '+', peer) {
1112
+ async react(event, reaction) {
941
1113
  this.assertOpen();
942
- if (typeof reaction !== 'string' || !reaction.trim()) {
943
- throw new TypeError('Nonempty reaction required');
1114
+ const target = this.authenticatedInput(event);
1115
+ return "rumor" in target
1116
+ ? this.reactToMessage(target, reaction)
1117
+ : this.reactPublic(target, reaction);
1118
+ }
1119
+ async reactPublic(input, reaction) {
1120
+ this.assertOpen();
1121
+ if (!this.publicInbox)
1122
+ throw new Error("Public inbox is not configured");
1123
+ return this.publicInbox.react(input, reaction);
1124
+ }
1125
+ /** The Bot may use a verified incoming anchor before admitting it to history. */
1126
+ async reactToMessage(target, reaction = "+", input) {
1127
+ this.assertOpen();
1128
+ if (typeof reaction !== "string" || !reaction.trim()) {
1129
+ throw new TypeError("Nonempty reaction required");
944
1130
  }
945
- const target = this.getMessage(id, peer);
946
- if (!target)
947
- throw new Error('Reaction target was not found in local message history');
948
1131
  const r = reactionRumor(this.account.pubkey, target.conversation, target.id, reaction);
949
- return this.publishPrivate(target.conversation, r);
1132
+ return this.publishPrivate(target.conversation, r, undefined, input);
950
1133
  }
951
- async publishPrivate(peer, r, message) {
952
- const recipients = await this.protocol.recipients(peer, this.coreStore, this.transport, this.metadataLookupRelays);
1134
+ async publishPrivate(peer, r, message, input) {
1135
+ const recipients = await this.protocol.recipients(peer, this.coreStore, this.transport, this.metadataLookupRelays, input);
953
1136
  const sendingIdentity = {
954
- ...this.account, oldEncryptionKeys: this.account.oldEncryptionKeys?.slice()
1137
+ ...this.account,
1138
+ oldEncryptionKeys: this.account.oldEncryptionKeys?.slice(),
955
1139
  };
956
1140
  const events = [];
957
1141
  for (const recipient of recipients) {
@@ -972,15 +1156,17 @@ export class Client {
972
1156
  this.report(error);
973
1157
  }
974
1158
  return {
975
- id: r.id, status: this.coreStore.outbox().some(item => item.id === r.id) ? 'pending' : 'relay-accepted'
1159
+ id: r.id,
1160
+ status: this.coreStore.outbox().some((item) => item.id === r.id)
1161
+ ? "pending"
1162
+ : "relay-accepted",
976
1163
  };
977
1164
  }
978
1165
  flushOutbox() {
979
1166
  this.assertOpen();
980
1167
  // A caller arriving during a flush may have just committed a newer outbox row.
981
1168
  if (this.flushing) {
982
- return this.flushing.catch(() => {
983
- }).then(() => this.flushOutbox());
1169
+ return this.flushing.catch(() => { }).then(() => this.flushOutbox());
984
1170
  }
985
1171
  this.flushing = (async () => {
986
1172
  const pending = this.coreStore.outbox();
@@ -1000,7 +1186,7 @@ export class Client {
1000
1186
  }
1001
1187
  }
1002
1188
  if (errors.length) {
1003
- throw new AggregateError(errors, 'Some outbox messages remain pending');
1189
+ throw new AggregateError(errors, "Some outbox messages remain pending");
1004
1190
  }
1005
1191
  await this.publicInbox?.flush();
1006
1192
  })().finally(() => {