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/store.js CHANGED
@@ -1,8 +1,8 @@
1
- import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2
- import { replyTarget } from './protocol.js';
3
- import { StorageEncryptionError } from './errors.js';
4
- import { sqliteMessageStorage } from './message-storage-sqlite.js';
5
- import { SQLiteStorage } from './storage-sqlite.js';
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
+ import { replyTarget } from "./protocol.js";
3
+ import { StorageEncryptionError } from "./errors.js";
4
+ import { sqliteMessageStorage } from "./message-storage-sqlite.js";
5
+ import { SQLiteStorage } from "./storage-sqlite.js";
6
6
  export class Store {
7
7
  key;
8
8
  account;
@@ -17,11 +17,16 @@ export class Store {
17
17
  this.account = account;
18
18
  this.messageStorage = messageStorage;
19
19
  if (key !== undefined && key.length !== 32) {
20
- throw new Error('storageKey must contain 32 bytes');
20
+ throw new Error("storageKey must contain 32 bytes");
21
21
  }
22
- this.ownsStorage = typeof storage === 'string';
23
- this.adapter = typeof storage === 'string' ? new SQLiteStorage(storage) : storage;
24
- if (!this.messageStorage && typeof storage === 'string') {
22
+ if (typeof storage !== "string" &&
23
+ typeof storage.claimInput !== "function") {
24
+ throw new TypeError("StorageAdapter.claimInput must atomically claim canonical input IDs");
25
+ }
26
+ this.ownsStorage = typeof storage === "string";
27
+ this.adapter =
28
+ typeof storage === "string" ? new SQLiteStorage(storage) : storage;
29
+ if (!this.messageStorage && typeof storage === "string") {
25
30
  try {
26
31
  const messages = sqliteMessageStorage(storage);
27
32
  this.messageStorage = messages;
@@ -35,30 +40,35 @@ export class Store {
35
40
  }
36
41
  encode(value, aad = this.account) {
37
42
  if (!this.key) {
38
- return ('chirli:plain:v1:' + JSON.stringify({
39
- scope: aad, value
40
- }));
43
+ return ("chirli:plain:v1:" +
44
+ JSON.stringify({
45
+ scope: aad,
46
+ value,
47
+ }));
41
48
  }
42
- const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', this.key, iv);
49
+ const iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", this.key, iv);
43
50
  cipher.setAAD(Buffer.from(aad));
44
- const data = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()]);
45
- return Buffer.concat([iv, cipher.getAuthTag(), data]).toString('base64');
51
+ const data = Buffer.concat([
52
+ cipher.update(JSON.stringify(value), "utf8"),
53
+ cipher.final(),
54
+ ]);
55
+ return Buffer.concat([iv, cipher.getAuthTag(), data]).toString("base64");
46
56
  }
47
57
  decode(value, aad = this.account) {
48
- if (value.startsWith('chirli:plain:v1:')) {
58
+ if (value.startsWith("chirli:plain:v1:")) {
49
59
  if (this.key) {
50
- throw new StorageEncryptionError('STORAGE_MODE_MISMATCH');
60
+ throw new StorageEncryptionError("STORAGE_MODE_MISMATCH");
51
61
  }
52
- const record = JSON.parse(value.slice('chirli:plain:v1:'.length));
53
- if (record.scope !== aad || !Object.hasOwn(record, 'value')) {
54
- throw new Error('Invalid plaintext storage record scope');
62
+ const record = JSON.parse(value.slice("chirli:plain:v1:".length));
63
+ if (record.scope !== aad || !Object.hasOwn(record, "value")) {
64
+ throw new Error("Invalid plaintext storage record scope");
55
65
  }
56
66
  return record.value;
57
67
  }
58
68
  if (!this.key) {
59
- throw new StorageEncryptionError('STORAGE_KEY_REQUIRED');
69
+ throw new StorageEncryptionError("STORAGE_KEY_REQUIRED");
60
70
  }
61
- const b = Buffer.from(value, 'base64'), cipher = createDecipheriv('aes-256-gcm', this.key, b.subarray(0, 12));
71
+ const b = Buffer.from(value, "base64"), cipher = createDecipheriv("aes-256-gcm", this.key, b.subarray(0, 12));
62
72
  cipher.setAAD(Buffer.from(aad));
63
73
  cipher.setAuthTag(b.subarray(12, 28));
64
74
  return JSON.parse(Buffer.concat([cipher.update(b.subarray(28)), cipher.final()]).toString());
@@ -71,31 +81,67 @@ export class Store {
71
81
  message.replyTo = replyTo;
72
82
  return message;
73
83
  }
74
- insert(m, state = m.source === 'live' && m.direction === 'incoming' ? 'pending' : 'done') {
84
+ insert(m, state = m.source === "live" && m.direction === "incoming"
85
+ ? "pending"
86
+ : "done") {
75
87
  // SQLite stages cross-store writes with metadata/outbox in the same core transaction.
76
88
  // The custom backend remains authoritative once that durable handoff completes.
77
- if (this.messageStorage && this.queryMessages({ id: m.id, limit: 1 }).length)
89
+ if (this.messageStorage &&
90
+ this.queryMessages({ id: m.id, limit: 1 }).length)
78
91
  return false;
79
92
  const inserted = this.adapter.insert(this.account, {
80
- collection: 'messages',
81
- record: { id: m.id, peer: m.conversation, time: m.timestamp, payload: this.encode(m), state },
93
+ collection: "messages",
94
+ record: {
95
+ id: m.id,
96
+ peer: m.conversation,
97
+ time: m.timestamp,
98
+ payload: this.encode(m),
99
+ state,
100
+ },
82
101
  });
83
102
  if (!this.transactionDepth)
84
103
  this.recoverMessages();
85
104
  return this.messageStorage ? true : inserted;
86
105
  }
106
+ ensureDmActivation(pubkey, proposedAt) {
107
+ const activatedAt = this.adapter.ensureDmActivation(pubkey, proposedAt);
108
+ if (!Number.isSafeInteger(activatedAt) || activatedAt < 0)
109
+ throw new Error("Invalid stored DM activation time");
110
+ return activatedAt;
111
+ }
112
+ claimInput(id) {
113
+ const result = this.adapter.claimInput(this.account, id);
114
+ if (result === true || result === false)
115
+ return result;
116
+ void Promise.resolve(result).catch(() => { });
117
+ throw new TypeError("StorageAdapter.claimInput must return a boolean synchronously");
118
+ }
87
119
  queryMessages(query = {}) {
88
120
  if (!this.messageStorage)
89
121
  return this.adapter.queryMessages(this.account, query);
90
- const order = query.order?.time === 'desc' ? 'newest' : query.order?.id === 'desc' ? 'recovery' : 'oldest';
122
+ const order = query.order?.time === "desc"
123
+ ? "newest"
124
+ : query.order?.id === "desc"
125
+ ? "recovery"
126
+ : "oldest";
91
127
  const rows = this.messageStorage.query(this.account, {
92
- id: query.id, conversation: query.peer, states: query.states, order,
93
- cursor: query.cursor ? { timestamp: query.cursor.time, id: query.cursor.id } : undefined,
128
+ id: query.id,
129
+ conversation: query.peer,
130
+ states: query.states,
131
+ order,
132
+ cursor: query.cursor
133
+ ? { timestamp: query.cursor.time, id: query.cursor.id }
134
+ : undefined,
94
135
  limit: query.limit,
95
136
  });
96
- this.assertSynchronous(rows, 'query');
97
- return rows.map(row => ({ id: row.id, peer: row.conversation, time: row.timestamp,
98
- payload: row.payload, state: row.state }));
137
+ this.assertSynchronous(rows, "query");
138
+ return rows.map((row) => ({
139
+ id: row.id,
140
+ peer: row.conversation,
141
+ time: row.timestamp,
142
+ payload: row.payload,
143
+ state: row.state,
144
+ }));
99
145
  }
100
146
  state(id, state) {
101
147
  if (!this.messageStorage) {
@@ -103,14 +149,14 @@ export class Store {
103
149
  return;
104
150
  }
105
151
  const result = this.messageStorage.updateState(this.account, id, state);
106
- this.assertSynchronous(result, 'updateState');
152
+ this.assertSynchronous(result, "updateState");
107
153
  }
108
154
  pending() {
109
155
  this.recoverMessages();
110
156
  return this.queryMessages({
111
- states: ['pending', 'processing', 'failed'],
112
- order: { time: 'asc', id: 'desc' },
113
- }).map(row => this.decodeMessage(row.payload));
157
+ states: ["pending", "processing", "failed"],
158
+ order: { time: "asc", id: "desc" },
159
+ }).map((row) => this.decodeMessage(row.payload));
114
160
  }
115
161
  messageState(id) {
116
162
  return this.queryMessages({ id, limit: 1 })[0]?.state;
@@ -122,95 +168,121 @@ export class Store {
122
168
  listMessages(options = {}) {
123
169
  const limit = options.limit ?? 30;
124
170
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) {
125
- throw new TypeError('Message list limit must be in 1..100');
171
+ throw new TypeError("Message list limit must be in 1..100");
126
172
  }
127
- if (options.state !== undefined && !['pending', 'processing', 'failed', 'done'].includes(options.state)) {
128
- throw new TypeError('Invalid message state');
173
+ if (options.state !== undefined &&
174
+ !["pending", "processing", "failed", "done"].includes(options.state)) {
175
+ throw new TypeError("Invalid message state");
129
176
  }
130
- let cursor = [0, ''];
177
+ let cursor = [0, ""];
131
178
  if (options.cursor !== undefined) {
132
179
  try {
133
- if (typeof options.cursor !== 'string' || options.cursor.length > 256 || !/^[A-Za-z0-9_-]+$/.test(options.cursor)) {
180
+ if (typeof options.cursor !== "string" ||
181
+ options.cursor.length > 256 ||
182
+ !/^[A-Za-z0-9_-]+$/.test(options.cursor)) {
134
183
  throw new Error();
135
184
  }
136
- const value = JSON.parse(Buffer.from(options.cursor, 'base64url').toString());
137
- if (!Array.isArray(value) || value.length !== 2 || !Number.isSafeInteger(value[0]) || value[0] < 0 || typeof value[1] !== 'string' || !/^[0-9a-f]{64}$/.test(value[1])) {
185
+ const value = JSON.parse(Buffer.from(options.cursor, "base64url").toString());
186
+ if (!Array.isArray(value) ||
187
+ value.length !== 2 ||
188
+ !Number.isSafeInteger(value[0]) ||
189
+ value[0] < 0 ||
190
+ typeof value[1] !== "string" ||
191
+ !/^[0-9a-f]{64}$/.test(value[1])) {
138
192
  throw new Error();
139
193
  }
140
194
  cursor = value;
141
195
  }
142
196
  catch {
143
- throw new TypeError('Invalid message list cursor');
197
+ throw new TypeError("Invalid message list cursor");
144
198
  }
145
199
  }
146
200
  this.recoverMessages();
147
201
  const rows = this.queryMessages({
148
202
  states: options.state ? [options.state] : undefined,
149
- order: { time: 'asc', id: 'asc' },
203
+ order: { time: "asc", id: "asc" },
150
204
  cursor: { time: cursor[0], id: cursor[1] },
151
- limit: limit + 1
205
+ limit: limit + 1,
152
206
  });
153
- const entries = rows.slice(0, limit).map(row => ({
154
- message: this.decodeMessage(row.payload), state: row.state
207
+ const entries = rows.slice(0, limit).map((row) => ({
208
+ message: this.decodeMessage(row.payload),
209
+ state: row.state,
155
210
  })), last = rows[Math.min(rows.length, limit) - 1];
156
211
  return {
157
- entries, ...(rows.length > limit && last ? {
158
- nextCursor: Buffer.from(JSON.stringify([last.time, last.id])).toString('base64url')
159
- } : {})
212
+ entries,
213
+ ...(rows.length > limit && last
214
+ ? {
215
+ nextCursor: Buffer.from(JSON.stringify([last.time, last.id])).toString("base64url"),
216
+ }
217
+ : {}),
160
218
  };
161
219
  }
162
220
  history(peer, options = {}) {
163
221
  const requestedLimit = options.limit ?? 30;
164
222
  if (!Number.isSafeInteger(requestedLimit) || requestedLimit < 1) {
165
- throw new TypeError('History limit must be a positive safe integer');
223
+ throw new TypeError("History limit must be a positive safe integer");
166
224
  }
167
225
  const limit = Math.min(100, requestedLimit);
168
- let cursor = [Number.MAX_SAFE_INTEGER, ''];
226
+ let cursor = [Number.MAX_SAFE_INTEGER, ""];
169
227
  if (options.cursor !== undefined) {
170
228
  try {
171
- if (typeof options.cursor !== 'string' || options.cursor.length > 256 || !/^[A-Za-z0-9_-]+$/.test(options.cursor)) {
229
+ if (typeof options.cursor !== "string" ||
230
+ options.cursor.length > 256 ||
231
+ !/^[A-Za-z0-9_-]+$/.test(options.cursor)) {
172
232
  throw new Error();
173
233
  }
174
- const decoded = JSON.parse(Buffer.from(options.cursor, 'base64url').toString());
175
- if (!Array.isArray(decoded) || decoded.length !== 2 || !Number.isSafeInteger(decoded[0]) || decoded[0] < 0 || typeof decoded[1] !== 'string' || !/^[0-9a-f]{64}$/.test(decoded[1])) {
234
+ const decoded = JSON.parse(Buffer.from(options.cursor, "base64url").toString());
235
+ if (!Array.isArray(decoded) ||
236
+ decoded.length !== 2 ||
237
+ !Number.isSafeInteger(decoded[0]) ||
238
+ decoded[0] < 0 ||
239
+ typeof decoded[1] !== "string" ||
240
+ !/^[0-9a-f]{64}$/.test(decoded[1])) {
176
241
  throw new Error();
177
242
  }
178
243
  cursor = decoded;
179
244
  }
180
245
  catch {
181
- throw new TypeError('Invalid history cursor');
246
+ throw new TypeError("Invalid history cursor");
182
247
  }
183
248
  }
184
249
  this.recoverMessages();
185
250
  const rows = this.queryMessages({
186
251
  peer,
187
- order: { time: 'desc', id: 'asc' },
252
+ order: { time: "desc", id: "asc" },
188
253
  cursor: { time: cursor[0], id: cursor[1] },
189
- limit: limit + 1
254
+ limit: limit + 1,
190
255
  });
191
- const messages = rows.slice(0, limit).map(r => this.decodeMessage(r.payload)), last = messages.at(-1);
256
+ const messages = rows
257
+ .slice(0, limit)
258
+ .map((r) => this.decodeMessage(r.payload)), last = messages.at(-1);
192
259
  return {
193
260
  messages,
194
- nextCursor: rows.length > limit && last ? Buffer.from(JSON.stringify([last.timestamp, last.id])).toString('base64url') : undefined,
195
- coverage: 'local-only',
196
- complete: false
261
+ nextCursor: rows.length > limit && last
262
+ ? Buffer.from(JSON.stringify([last.timestamp, last.id])).toString("base64url")
263
+ : undefined,
264
+ coverage: "local-only",
265
+ complete: false,
197
266
  };
198
267
  }
199
268
  putOutbox(id, events) {
200
269
  const inserted = this.adapter.insert(this.account, {
201
- collection: 'outbox',
202
- record: { id, payload: this.encode(events), state: 'pending' },
270
+ collection: "outbox",
271
+ record: { id, payload: this.encode(events), state: "pending" },
203
272
  });
204
273
  if (!inserted)
205
- throw new Error('Duplicate outbox ID');
274
+ throw new Error("Duplicate outbox ID");
206
275
  }
207
276
  outbox() {
208
- return this.adapter.queryOutbox(this.account, { state: 'pending' }).map(r => ({
209
- id: r.id, events: this.decode(r.payload)
277
+ return this.adapter
278
+ .queryOutbox(this.account, { state: "pending" })
279
+ .map((r) => ({
280
+ id: r.id,
281
+ events: this.decode(r.payload),
210
282
  }));
211
283
  }
212
284
  ack(id) {
213
- this.adapter.updateOutboxState(this.account, id, 'relay-accepted');
285
+ this.adapter.updateOutboxState(this.account, id, "relay-accepted");
214
286
  }
215
287
  evidence(peer) {
216
288
  return this.adapter.getEvidence(this.account, peer);
@@ -221,7 +293,7 @@ export class Store {
221
293
  this.adapter.setEvidence(this.account, peer, {
222
294
  key,
223
295
  time,
224
- id
296
+ id,
225
297
  });
226
298
  }
227
299
  }
@@ -231,11 +303,13 @@ export class Store {
231
303
  }
232
304
  rememberDeclaration(event) {
233
305
  const old = this.adapter.getDeclaration(this.account, event.pubkey);
234
- if (!old || event.created_at > old.time || (event.created_at === old.time && event.id < old.id)) {
306
+ if (!old ||
307
+ event.created_at > old.time ||
308
+ (event.created_at === old.time && event.id < old.id)) {
235
309
  this.adapter.setDeclaration(this.account, event.pubkey, {
236
310
  time: event.created_at,
237
311
  id: event.id,
238
- payload: this.encode(event)
312
+ payload: this.encode(event),
239
313
  });
240
314
  }
241
315
  }
@@ -282,7 +356,7 @@ export class Store {
282
356
  this.saveSession(`@chirli:${name}`, value);
283
357
  }
284
358
  assertSynchronous(result, method) {
285
- if (result && typeof result.then === 'function') {
359
+ if (result && typeof result.then === "function") {
286
360
  void Promise.resolve(result).catch(() => { });
287
361
  throw new TypeError(`MessageStorage.${method} must be synchronous`);
288
362
  }
@@ -292,7 +366,7 @@ export class Store {
292
366
  if (!this.messageStorage || this.transactionDepth || this.flushingMessages)
293
367
  return;
294
368
  if (!(this.adapter instanceof SQLiteStorage))
295
- throw new Error('Message storage requires the internal SQLite database');
369
+ throw new Error("Message storage requires the internal SQLite database");
296
370
  this.flushingMessages = true;
297
371
  try {
298
372
  for (;;) {
@@ -301,11 +375,15 @@ export class Store {
301
375
  break;
302
376
  for (const row of rows) {
303
377
  const inserted = this.messageStorage.insert(this.account, {
304
- id: row.id, conversation: row.peer, timestamp: row.time, payload: row.payload, state: row.state,
378
+ id: row.id,
379
+ conversation: row.peer,
380
+ timestamp: row.time,
381
+ payload: row.payload,
382
+ state: row.state,
305
383
  });
306
- this.assertSynchronous(inserted, 'insert');
307
- if (typeof inserted !== 'boolean')
308
- throw new TypeError('MessageStorage.insert must return a boolean');
384
+ this.assertSynchronous(inserted, "insert");
385
+ if (typeof inserted !== "boolean")
386
+ throw new TypeError("MessageStorage.insert must return a boolean");
309
387
  this.adapter.discardStagedMessage(this.account, row.id);
310
388
  }
311
389
  }
package/docs/ACCESS.md CHANGED
@@ -1,39 +1,28 @@
1
1
  # Incoming sender allowlist
2
2
 
3
- Use the `allowlist` helper as an inbound policy to control which authenticated accounts can send messages to your Bot.
3
+ Register `allowlist` as ordinary middleware to control which authenticated senders reach subsequent middleware, commands and the fallback handler.
4
4
 
5
5
  ```ts
6
- import { Bot, allowlist } from 'chirli';
6
+ import { Bot, allowlist } from "chirli";
7
7
 
8
- const bot = new Bot({
9
- signer,
10
- database: './chirli.sqlite',
11
- inboundPolicy: allowlist([trustedIdentityPubkey]),
12
- });
8
+ const bot = new Bot({ signer, database: "./chirli.sqlite" });
9
+ bot.use(allowlist([trustedIdentityPubkey]));
13
10
  ```
14
11
 
15
- | `inboundPolicy` value | Incoming policy |
12
+ | Middleware | Live processing |
16
13
  | --- | --- |
17
- | Omitted | Accept all authenticated senders |
18
- | `allowlist([])` | Deny all external senders |
19
- | `allowlist(pubkeys)` | Accept only the listed senders |
14
+ | No allowlist middleware | All otherwise eligible, authenticated inputs continue |
15
+ | `bot.use(allowlist([]))` | Stop every external live input |
16
+ | `bot.use(allowlist(pubkeys))` | Continue only for a listed sender |
20
17
 
21
- Use lowercase 64-character hex **account public keys**. Convert an `npub` to hex in your application. The account key is the author of the verified seal and the decrypted message. A giftwrap author, split messaging key or bunker connection key cannot identify an allowed sender.
18
+ Use lowercase 64-character hex **account public keys**. Convert an `npub` to hex in your application. For private input, the key is the authenticated author of the seal and decrypted rumor; for public input, it is the verified event author. A giftwrap author, split messaging key or bunker connection key is not an account identity. The helper validates and snapshots its list. Register it before any middleware whose effects should be restricted.
22
19
 
23
- The helper snapshots the list when called. To replace the list, create a new Bot with a new policy and the same signer, mode and database.
20
+ Custom access checks use the same `bot.use(async (ctx, next) => { ... })` API. Read the verified author from `ctx.input.sender` and call `await next()` only if allowed. Use the command's `authorize` option for a single command. Authentication and the atomic ID claim happen before any of these checks.
24
21
 
25
22
  ## What happens to denied messages
26
23
 
27
- - A newly denied message is discarded before storage, middleware, commands and session access. `bot.receive()` returns `false`, the same result as for a duplicate or unsupported envelope.
28
- - Existing history remains readable. Previously accepted unfinished work that the new policy denies is consumed without executing handlers. The stored receipt still deduplicates later copies.
29
- - A newly denied message leaves no denial record. If the policy later changes, the same message may be accepted when received again. A copy received as history is stored without dispatch.
24
+ - An eligible input ID stays claimed even if middleware returns without calling `next()` or throws. A duplicate does not revisit middleware after configuration changes, reconnection or restart. `bot.receive()` can return `true` for a newly claimed input that middleware later stops; this does not mean the sender was authorized.
25
+ - If the allowlist stops a DM from reaching routing, the SDK does not add it to conversation history or invoke receipt observers. DMs recovered after the first activation go through the same middleware. The allowlist does not erase existing history.
26
+ - Outgoing sends, eligible self copies and signed same-identity control traffic do not pass through this middleware. This is neither an outbound ACL nor a rate limiter. Crypto and remote signer work may occur before the sender is authenticated.
30
27
 
31
- The allowlist applies to incoming senders in both modes. Outgoing sends and self copies follow the usual routing rules. For command-specific rules, use the `authorize` option described in [NIP-CD commands](NIP-CD.md). See [security](../SECURITY.md) for signer and local storage trust boundaries.
32
-
33
- Run `npm run example:allowlist` after building to try the policy with disposable accounts and an in-memory relay.
34
-
35
- ## Official inbound policy
36
-
37
- The optional `inboundPolicy` hook receives only the authenticated sender's lowercase hex identity string and must return a synchronous boolean. It cannot mutate validated messages because no message object is supplied. `allowlist(pubkeys)` validates and snapshots the array; an empty array denies all external senders. It is used at both the post-decrypt/pre-persistence gate and pending startup/retry gate. Historical/reconnect intake uses the same gate. Own copies keep their existing bypass and are not dispatched as incoming messages; signed same-identity account-control events remain outside this external-message policy.
38
-
39
- Custom `InboundPolicy` functions should be pure and reentrant because the SDK can check them more than once. Returning `false` explicitly denies the sender. Exceptions and non-boolean results reject processing before new persistence. Operational policy failures can block history checkpoint progress and leave pending work retryable. Middleware registered with `bot.use()` runs after receipt persistence.
28
+ Replace the old `inboundPolicy`, `guards` or constructor `allowlist` option with registered middleware. These constructor options now throw instead of silently running unfiltered. See [security](../SECURITY.md) for signer and local storage boundaries.