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/ARCHITECTURE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Architecture
2
2
 
3
- Chirli is a Node.js SDK for Nostr private text and explicitly scoped public commands. Applications own authorization, business effects, signer credentials and deployment. `src/index.ts` is the public entry point.
3
+ Chirli is a Node.js SDK for Nostr private messages with text or attachments and explicitly scoped public commands. Applications own authorization, business effects, signer credentials and deployment. `src/index.ts` is the public entry point.
4
4
 
5
5
  ## Module responsibilities
6
6
 
@@ -18,7 +18,7 @@ Chirli is a Node.js SDK for Nostr private text and explicitly scoped public comm
18
18
 
19
19
  Bot owns one internal client. Each queued message runs middleware before routing to a matching command or to the optional text fallback. AI/model adapters belong to applications.
20
20
 
21
- Command execution, publication and discovery are independent: discovery never installs a handler or publishes metadata. `command()` validates explicitly scoped object definitions before registering them in the same command pipeline.
21
+ Command execution, publication and discovery are independent: discovery never installs a handler or publishes metadata. `command()` resolves kind scopes and validates object definitions before registering them in the same command pipeline.
22
22
 
23
23
  ## Construction and ownership
24
24
 
@@ -28,27 +28,25 @@ Command execution, publication and discovery are independent: discovery never in
28
28
 
29
29
  1. Construct the Bot and register handlers and the full command set.
30
30
  2. `start()` publishes key/relay metadata and reconciles the public command catalog, including an empty set.
31
- 3. Startup restores unfinished work, opens inbox subscriptions and retries the outbox. Every write relay must accept command reconciliation. One ready DM replica can serve the Bot while other DM replicas reconnect.
31
+ 3. Startup opens inbox subscriptions and retries outgoing publications. It never replays claimed business inputs. Every write relay must accept command reconciliation. One ready DM replica can serve the Bot while other DM replicas reconnect.
32
32
  4. The live runner prints the identity and QR after startup succeeds.
33
33
 
34
- Stop cancels subscription/reconnect demand and drains intake, handlers and SDK work. Close then releases owned resources. Application timers are stopped and awaited before their injected dependencies are closed. Handler calls to self-draining `idle`, `retryInbox`, `stop` or `close` reject; `requestStop()` requests shutdown without waiting on the caller.
34
+ Stop cancels subscription/reconnect demand and drains intake, handlers and SDK work. Close then releases owned resources. Application timers are stopped and awaited before their injected dependencies are closed. Handler calls to self-draining `idle`, `stop` or `close` reject; `requestStop()` requests shutdown without waiting on the caller.
35
35
 
36
36
  ## Incoming messages
37
37
 
38
- Giftwrap and seal signatures, rumor hash/author, times and one-to-one routing are verified before persistence. The optional inbound policy runs after authentication and before peer evidence, history insertion and dispatch.
38
+ See the [event processing flow](docs/API.md#event-processing-flow) for the complete path from authentication to outgoing publication.
39
39
 
40
- A temporary rumor handoff and its key evidence commit atomically in internal SQLite before insertion into MessageStorage. The handoff is removed after durable insertion. `(account/mode, rumor ID)` deduplicates wrappers across relays and restarts.
40
+ Giftwrap and seal signatures, rumor hash/author, times and one-to-one routing are verified before persistence. After verification, internal SQLite checks the persisted first DM activation time per identity and database against the inner rumor timestamp; both live delivery and catch-up use this guard. Eligible incoming DMs claim their canonical ID in the account/mode scope before any business middleware. Multiple giftwraps for the same rumor do not create multiple attempts.
41
41
 
42
- - New incoming live messages enter `pending → processing → done`.
43
- - A handler failure records `failed`; retry or restart can run it again.
44
- - History and outgoing self copies become `done` without business dispatch.
45
- - Conversation queues are serial; different conversations can proceed concurrently.
46
-
47
- Receipt observers receive detached copies and do not control durable success. Multiple durable handlers form one processing group, so a later failure can repeat earlier effects. Session saves and arbitrary external effects are not one transaction; applications need their own idempotency.
42
+ - An unseen live claim may enter the serial conversation queue; different conversations can proceed concurrently.
43
+ - A middleware stop, failure or crash does not reopen the claim. The SDK does not store an incoming callback payload to replay.
44
+ - Routing retains an admitted live DM in private conversation history and sends detached copies to receipt observers. Passive historical inputs claim only their IDs, while outgoing self copies can still populate private history.
45
+ - Conversation history and outgoing publication have separate lifecycles from the ID claim. Applications own durable jobs, session coordination and idempotency for external effects.
48
46
 
49
47
  ## Outgoing messages
50
48
 
51
- A reply references its parent rumor ID through an `e` tag inside the encrypted kind-14 event. Outgoing kind-7 reactions use the same private envelope and durable outbox. Text history and incoming dispatch accept kind 14. Recipient metadata is resolved before queuing. A temporary outgoing message handoff and exact signed envelopes commit together before publication; the message is then inserted into MessageStorage before normal send publication. Each recipient/self envelope requires at least one relay ACK. Failure keeps the bundle pending; retries reuse its IDs and ciphertext.
49
+ A private reply references its parent rumor ID through an `e` tag inside the encrypted event. Outgoing kind-7 reactions use the same private envelope and durable outbox. Private history and dispatch accept kind 14 text and kind 15 file messages. Kind 15 uses the normal middleware and fallback handler and bypasses text command matching. Attachment retrieval is explicit, and verified plaintext files are stored by hash in a local per-account cache. Recipient metadata is resolved before queuing. A temporary outgoing message handoff and exact signed envelopes commit together before publication; the message is then inserted into MessageStorage before normal send publication. Each recipient/self envelope requires at least one relay ACK. Failure keeps the bundle pending; retries reuse its IDs and ciphertext.
52
50
 
53
51
  Relay acceptance does not establish delivery or reading. A new `send()` call creates a new logical message.
54
52
 
@@ -78,7 +76,7 @@ The NIP-46 signer uses an `AbstractSimplePool` adapter backed by its own `WebSoc
78
76
 
79
77
  Recovered frames remain history. Saturated timestamp boundaries, page limits or failed reads leave coverage incomplete. No full archive or durable undecryptable-envelope quarantine is promised.
80
78
 
81
- Store applies AES-GCM when a storage key is supplied, otherwise tagged plaintext. MessageStorage owns message records, duplicate detection and processing state. Its default sqliteMessageStorage uses indexed native queries. Internal SQLite owns outbox, keys, metadata and temporary cross-store handoffs, and accepts only a database path. Failed handoffs are replayed without replacing existing message state; internal message copies are removed after successful insertion. The SDK supports one active Client/process per account database. Distributed claims, admission/backpressure limits, pruning, forward secrecy and exactly-once external effects remain outside its scope.
79
+ Store applies AES-GCM when a storage key is supplied, otherwise tagged plaintext. MessageStorage owns retained private conversation records and their diagnostic states. Internal SQLite owns atomic inbound ID claims. Its default sqliteMessageStorage uses indexed native queries. Internal SQLite owns outbox, keys, metadata and temporary cross-store handoffs, and accepts only a database path. Failed history handoffs can be repaired without replaying callbacks or replacing existing message state; internal message copies are removed after successful insertion. Use a fresh database for this storage format; no migration from earlier pre-release formats is provided. The SDK supports one active Client/process per account database. Distributed claims, admission/backpressure limits, pruning, forward secrecy and exactly-once external effects remain outside its scope.
82
80
 
83
81
  ## References and validation
84
82
 
@@ -88,18 +86,18 @@ Tests cover protocol verification, persistence/restart, command reconciliation,
88
86
 
89
87
  See [API](docs/API.md), [command lifecycle](docs/NIP-CD.md), [key custody](docs/KEYS.md), [storage](docs/STORAGE.md), [recovery](docs/RECOVERY.md) and [third-party notices](THIRD_PARTY_NOTICES.md).
90
88
 
91
- ## Optional official policy and timing
89
+ ## Optional access and timing middleware
92
90
 
93
- `inbound-policy.ts` supplies an identity allowlist helper and the `InboundPolicy` type. Client passes only the authenticated sender string to the optional policy at verified intake and before dispatching pending work. `request-timing.ts` supplies downstream middleware with a frozen duration and outcome metric and isolates observer callbacks from processing.
91
+ `allowlist` returns ordinary middleware over the authenticated input identity. It runs only on a claimed live attempt, like other registered middleware. `request-timing.ts` supplies downstream middleware with a frozen duration and outcome metric and isolates observer callbacks from processing.
94
92
 
95
93
  ## Public input isolation
96
94
 
97
- `public-inbox.ts` owns a separate verified kind 1/1111 subscription and durable public journal in internal account/mode storage. Only matching, unambiguously targeted registered commands enter business middleware. Admission checks signatures, source relay, author policy, structure, scope and invocation before persistence, and repeats policy before dispatch. Per-root queues and `public:` session keys never use DM message rows or peer sessions. `bot.observe`, message history/state/listing remain DM-only.
95
+ `public-inbox.ts` owns a separate verified kind 1/1111 subscription. Only matching, unambiguously targeted registered commands enter business middleware. Admission checks signatures, source relay, structure, scope and invocation before atomically claiming the event ID. There is no durable public input body or processing journal. Per-root queues and `public:` session keys never use DM message rows or peer sessions. `bot.observe`, message history/state/listing remain DM-only.
98
96
 
99
- `public-thread.ts` parses legacy/NIP-22 topology, batches a root across legacy `#e` and modern `#E` (plus coordinate variants), and follows only the trigger ancestor branch under one deadline and size/lookup/depth limits. Public replies are signed kind 1111 events with a durable outbox, configured write/source destinations, and exact-ID retries. Transport queries have no cancellation API; a timed-out resolver returns while already acquired transport queries settle under transport budgets. Stop drains active processing and cancels subscription/reconnect demand.
97
+ `public-thread.ts` parses legacy/NIP-22 topology, batches a root across legacy `#e` and modern `#E` (plus coordinate variants), and follows only the trigger ancestor branch under one deadline and size/lookup/depth limits. Public replies (kind 1111) and NIP-25 reactions (kind 7) share a durable outbox, configured write/source destinations, and exact-ID retries. Transport queries have no cancellation API; a timed-out resolver returns while already acquired transport queries settle under transport budgets. Stop drains active processing and cancels subscription/reconnect demand.
100
98
 
101
99
  ## Event-based delayed actions
102
100
 
103
- Client.reply/thread resolve a detached original input event into either an exact account-bound authenticated incoming DM record or a reverified public target. Bot exposes that path directly, and handler methods capture independent anchor snapshots and use the same execution. Public target lookup retains no new event-body index: a signed supplied event is sufficient, while the existing journal may supply known source provenance. Private thread reads retain the original record cutoff. No job queue or idempotency layer is introduced.
101
+ Reply, reaction and thread calls resolve a detached original input event into either an exact account-bound authenticated incoming DM record or a reverified public target. Bot exposes that path directly, and handler methods capture independent anchor snapshots and use the same execution. Public target lookup retains no new event-body index: a signed supplied event is sufficient, and only the immediate handler context retains known source provenance. Private thread reads retain the original record cutoff. No job queue or idempotency layer is introduced.
104
102
 
105
- Command args use a single Zod 4 object. command-schema.ts projects its supported positional subset into unchanged wire CommandArgument metadata at registration. Entry policy and ordinary middleware precede decoding/validation. Only recognized target/scope matches can raise a framework terminal InvalidArgsError. Such errors are consumed after centralized observation; operational/business errors preserve retry behavior. Args-dependent authorization suppresses invalid-input response hooks; valid authorization and command-only context use Zod's parsed output.
103
+ Command args use a single Zod 4 object. command-schema.ts projects its supported positional subset into unchanged wire CommandArgument metadata at registration. Ordinary middleware precedes decoding/validation. Only recognized target/scope matches can raise a framework terminal InvalidArgsError. Such errors are consumed after centralized observation; operational/business errors are reported without retrying the callback. Args-dependent authorization suppresses invalid-input response hooks; valid authorization and command-only context use Zod's parsed output.
package/CONTRIBUTING.md CHANGED
@@ -11,7 +11,11 @@ npm ci --ignore-scripts
11
11
  npm run check
12
12
  ```
13
13
 
14
- `check` builds from a clean `dist/`, checks all TypeScript, runs tests, executes fourteen offline examples, and checks an actual npm tarball in an isolated consumer. The consumer runs the checkout examples against the packed SDK. Local WebSocket tests and the loopback demo need permission to bind loopback sockets. No public relays, account keys, or paid APIs are required.
14
+ `check` builds from a clean `dist/`, checks all TypeScript, runs tests, executes fourteen offline examples, and checks an actual npm tarball in an isolated consumer. The npm tarball contains the SDK and documentation. The check runs demos and live CLI help from the checkout against the packed SDK. Local WebSocket tests and the loopback demo need permission to bind loopback sockets. No public relays, account keys, or paid APIs are required.
15
+
16
+ Run `npm run pack:release` to build, verify, and write the release tarball to the checkout. The checkout manifest is private and keeps the development scripts. Publish the verified tarball with `npm publish ./chirli-<version>.tgz`.
17
+
18
+ Use `npm run format` to apply Biome's default formatting and `npm run lint` to see its recommended lint warnings and errors. `npm run check:style` is the read-only CI style check; formatting differences and lint errors fail it. Biome covers JS/TS under `src`, `test`, `examples` and `scripts`, excluding fixtures. TypeScript still runs separately.
15
19
 
16
20
  `npm test` uses temporary identities/databases. Two optional tests require an externally built PsstPsst Go relay:
17
21
 
@@ -41,9 +45,9 @@ Report potential vulnerabilities privately using the instructions in [SECURITY.m
41
45
 
42
46
  NIP-CD is a draft integration. Retain stable command coordinates and signature/deletion handling. Commands are always public on configured write relays; Bot startup reconciles the complete local registry before dispatch. Keep kind 31992 definitions and kind 5 withdrawals distinct from standard user-installed list 10992. Bot coordinates are command-name derived; wire decoding retains external d values. Do not describe the SDK's private-DM scope mapping as standardized. See docs/NIP-CD.md.
43
47
 
44
- Storage adapters implement the exported synchronous opaque-record contract; keep codec selection/crypto in the SDK facade; preserve AES-GCM with storageKey and tagged plaintext without it. Preserve exact bytes, scopes, detached reads and durable atomic writes. Reuse test/storage-contract.ts and include rotation, uncertain ACK, restart and rollback cases. Multi-relay changes must preserve partial-success availability, first-ready startup, independent historical catch-up and rumor-ID dedup. Never treat a replica's recovery page as a new command. See docs/STORAGE.md and docs/RELAYS.md.
48
+ Storage adapters implement the exported synchronous opaque-record contract; keep codec selection/crypto in the SDK facade; preserve AES-GCM with storageKey and tagged plaintext without it. Preserve exact bytes, scopes, detached reads and durable atomic writes. Reuse test/storage-contract.ts and include rotation, uncertain ACK, restart and rollback cases. Multi-relay changes must preserve partial-success availability, first-ready startup, independent historical catch-up and rumor-ID dedup. Use authenticated inner DM time and the persisted first activation for admission. Recovered eligible DMs follow the same at-most-once path as live delivery. See docs/STORAGE.md and docs/RELAYS.md.
45
49
 
46
- Authorization changes must match authenticated identity authors, never wrapper or n encryption keys, and run before storage/business/session effects. Preserve absent versus empty policy semantics and recheck pending retry/start paths. See docs/ACCESS.md and test/allowlist.test.ts for protocol, spoofing and replay coverage.
50
+ Sender authorization is ordinary middleware over authenticated identity authors, never wrapper or split encryption keys. Preserve absent versus empty allowlist semantics; authenticate and atomically claim the ID before middleware, and do not rerun middleware for rejected, failed or previously claimed input. Verify independent private history and outgoing delivery retry. See [access middleware](docs/ACCESS.md).
47
51
 
48
52
  Live examples are real long-running bot programs, not offline walkthroughs. Their tests must launch the real compiled entrypoints using only test-generated config/identities and loopback relays. Never load an operator .env.chirli or inherit CHIRLI credentials into child fixtures. Preserve initializer non-overwrite/0600 behavior, restart persistence, clean signals and sanitized logs. Package smoke only runs live --help, never configured public-relay programs.
49
53
 
package/README.md CHANGED
@@ -42,25 +42,24 @@ For a guided path from the runnable demo to your own application, see the [first
42
42
  Select a signer at the application boundary. This example reads an application-provided nsec from `CHIRLI_NSEC`:
43
43
 
44
44
  ```ts
45
- import { Bot, nsecSigner } from 'chirli';
45
+ import { Bot, nsecSigner } from "chirli";
46
46
 
47
47
  const signer = nsecSigner(process.env.CHIRLI_NSEC!);
48
48
  const bot = new Bot({
49
49
  signer,
50
- database: './chirli.sqlite',
50
+ database: "./chirli.sqlite",
51
51
  });
52
52
 
53
-
54
- bot.command({ command: 'ping', scopes: ['kind:14'] }, async ctx => {
55
- await ctx.reply('pong');
53
+ bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
54
+ await ctx.reply("pong");
56
55
  });
57
56
 
58
57
  try {
59
58
  await bot.start();
60
59
 
61
60
  console.log(`Bot public key: ${bot.pubkey}`);
62
- await new Promise<void>(resolve => {
63
- process.once('SIGINT', () => resolve());
61
+ await new Promise<void>((resolve) => {
62
+ process.once("SIGINT", () => resolve());
64
63
  });
65
64
  } finally {
66
65
  await bot.close();
@@ -75,9 +74,11 @@ Register the complete command set before starting. `bot.start()` resolves the si
75
74
  Replace the signer without changing handlers:
76
75
 
77
76
  ```ts
78
- import { bunkerSigner } from 'chirli';
77
+ import { bunkerSigner } from "chirli";
79
78
 
80
- const signer = bunkerSigner(bunkerUri, { clientSecret: bunkerClientKeyFromYourSecretManager });
79
+ const signer = bunkerSigner(bunkerUri, {
80
+ clientSecret: bunkerClientKeyFromYourSecretManager,
81
+ });
81
82
  ```
82
83
 
83
84
  Pass this signer to `new Bot({ signer })`. After startup, `bot.pubkey` gives you the account key. Approve requests in the signer or configure its permissions ahead of time. See [remote signers](docs/SIGNERS.md#remote-bunker).
@@ -87,8 +88,8 @@ Pass this signer to `new Bot({ signer })`. After startup, `bot.pubkey` gives you
87
88
  Use `handle()` to reply to messages that have no matching command:
88
89
 
89
90
  ```ts
90
- bot.handle(async ctx => {
91
- await ctx.reply('Thanks for your message');
91
+ bot.handle(async (ctx) => {
92
+ await ctx.reply("Thanks for your message");
92
93
  });
93
94
 
94
95
  bot.onError((error, message) => {
@@ -96,35 +97,31 @@ bot.onError((error, message) => {
96
97
  });
97
98
  ```
98
99
 
99
- Handlers run serially within a conversation and concurrently across conversations. A failure leaves the message retryable. Historical messages and outgoing self copies are stored without running handlers.
100
+ Handlers run serially within a conversation and concurrently across conversations. An eligible authenticated input is claimed durably by its canonical ID before middleware. A failure is reported but does not cause a second attempt, even after reconnect or restart. Live and recovered incoming DMs created since first activation follow the same processing path. Eligible outgoing self copies can still populate history. [Event processing flow](docs/API.md#event-processing-flow)
100
101
 
101
- `observe(observer)` observes a new receipt; it does not participate in durable processing. Register handlers before `start()`.
102
+ `observe(observer)` monitors newly admitted DMs saved to local conversation history; it does not control processing. Register handlers before `start()`.
102
103
 
103
- To reference the current message in a reply, pass its ID to `ctx.reply()`:
104
+ To reference the current DM in a reply, pass `ctx.input.id` as `replyTo`:
104
105
 
105
106
  ```ts
106
- await ctx.reply('Got it', { replyTo: ctx.message.id });
107
-
108
- const parentId = ctx.message.replyTo;
109
- const parent = parentId === undefined ? undefined : ctx.getMessage(parentId);
107
+ await ctx.reply("Got it", { replyTo: ctx.input.id });
110
108
  ```
111
109
 
112
- Use `bot.getMessage(id)` to look up a local message by ID outside a handler. To send a reaction instead, call `ctx.react('👍')` or `bot.react(id, '👍')`.
110
+ Use `bot.getMessage(id)` for local private-message lookup, or `ctx.thread()` to load preceding context. To react to the current input, call `ctx.react('👍')`.
113
111
 
114
- ### Inspect and retry
112
+ ### Inspect history and retry delivery
115
113
 
116
114
  ```ts
117
- const result = await bot.send(peerPubkey, 'Hello');
115
+ const result = await bot.send(peerPubkey, "Hello");
118
116
  // result.status: 'relay-accepted' | 'pending'
119
117
 
120
- const page = bot.history(peerPubkey, { limit: 20 });
118
+ const page = bot.dmHistory(peerPubkey, { limit: 20 });
121
119
  const state = bot.getMessageState(messageId);
122
120
 
123
- await bot.retryInbox({ ids: [messageId] });
124
121
  await bot.flushOutbox();
125
122
  ```
126
123
 
127
- Rumor IDs prevent duplicate intake across relays and restarts. Failed handlers may repeat application effects: use the message ID for application idempotency. Outbox retries reuse the original signed envelopes. Relay acceptance does not confirm delivery or reading.
124
+ Rumor IDs prevent duplicate live attempts across relays and restarts. If a process exits after claiming a message, its callback may never run or may stop partway through. Use an application-owned job if you need durable business retries. Outbox retries reuse the original signed envelopes. Relay acceptance does not confirm delivery or reading.
128
125
 
129
126
  History is local and paginated. Pass `page.nextCursor` to retrieve older rows; a local page does not imply a complete relay archive.
130
127
 
@@ -133,17 +130,17 @@ History is local and paginated. Pass `page.nextCursor` to retrieve older rows; a
133
130
  ```ts
134
131
  const bot = new Bot<{ visits: number }>({
135
132
  signer,
136
- database: './chirli.sqlite',
133
+ database: "./chirli.sqlite",
137
134
  });
138
135
 
139
- bot.command({ command: 'visit', scopes: ['kind:14'] }, async ctx => {
140
- const visits = (await ctx.session.getItem('visits') ?? 0) + 1;
141
- ctx.session.setItem('visits', visits);
136
+ bot.command({ command: "visit", scopes: ["kind:14"] }, async (ctx) => {
137
+ const visits = ((await ctx.session.getItem("visits")) ?? 0) + 1;
138
+ ctx.session.setItem("visits", visits);
142
139
  await ctx.reply(`Visit ${visits}`);
143
140
  });
144
141
 
145
- bot.handle(async ctx => {
146
- await ctx.reply('Try /visit');
142
+ bot.handle(async (ctx) => {
143
+ await ctx.reply("Try /visit");
147
144
  });
148
145
  ```
149
146
 
@@ -152,27 +149,27 @@ Register shared middleware with `bot.use((ctx, next) => ...)`. Middleware runs i
152
149
  Declare a typed argument schema in `command()` for typed arguments. Here `value` is inferred as `bigint`, and the published `d` is `count`.
153
150
 
154
151
  ```ts
155
- import {z} from 'zod';
152
+ import { z } from "zod";
156
153
 
157
154
  bot.command(
158
155
  {
159
- command: 'count', scopes: ['kind:14'],
160
- title: 'Count',
161
- description: 'Read an unsigned count.',
162
- args: z.object({ value: z.bigint().meta({label:'Value'}) }),
156
+ command: "count",
157
+ scopes: ["kind:14"],
158
+ title: "Count",
159
+ description: "Read an unsigned count.",
160
+ args: z.object({ value: z.bigint().meta({ label: "Value" }) }),
163
161
  },
164
162
  async (ctx, { value }) => {
165
163
  await ctx.reply(String(value));
166
164
  },
167
165
  );
168
-
169
166
  ```
170
167
 
171
168
  To remove or rename a command, update the declared command set and restart with the same account and relay configuration. Startup automatically withdraws definitions absent from the new registry. There is no runtime removal method.
172
169
 
173
170
  All registered commands are public on write relays. Startup adds or updates definitions and withdraws commands absent from the local registry. Definitions use kind `31992` and withdrawals use kind `5`; there is no executor-list event. User-installed kind `10992` lists are untouched.
174
171
 
175
- Definitions and scopes describe command availability. Use `inboundPolicy` to authorize senders or an `authorize` callback for an individual typed command. [Command lifecycle](docs/NIP-CD.md) · [Sender authorization](docs/ACCESS.md)
172
+ Definitions and scopes describe command availability. Use `bot.use(allowlist(pubkeys))` to authorize senders, or an `authorize` callback for an individual typed command. [Command lifecycle](docs/NIP-CD.md) · [Sender authorization](docs/ACCESS.md)
176
173
 
177
174
  ## Configuration
178
175
 
@@ -182,7 +179,6 @@ Definitions and scopes describe command availability. Use `inboundPolicy` to aut
182
179
  | `database` | SQLite path; defaults to `psstpsst.sqlite` |
183
180
  | `messageStorage` | Message backend; defaults to `sqliteMessageStorage` |
184
181
  | `storageKey` | Optional 32-byte key for local payload encryption |
185
- | `inboundPolicy` | Optional synchronous gate for verified incoming senders |
186
182
  | `relays` | Common list for each omitted relay role |
187
183
  | `dmRelays` | Receive and deliver private messages |
188
184
  | `readRelays` | Query public metadata |
@@ -190,7 +186,7 @@ Definitions and scopes describe command availability. Use `inboundPolicy` to aut
190
186
  | `discoveryRelays` | Extra targets for public account announcements |
191
187
  | `mode` | `nip17` by default; `nip4e` enables separate messaging keys |
192
188
 
193
- Preserve signer credentials, the database and any storage key across restarts. `messageStorage` stores messages, deduplication and processing state; it defaults to `sqliteMessageStorage` in the configured database. Supply `sqliteMessageStorage('./messages.sqlite')` or implement `insert`, `query` and `updateState` to use another message backend. Outbox, keys and other internal data always use SQLite configured by `database`. Custom `Transport` implementations are also supported.
189
+ Use a fresh database for this pre-release storage format. Point `database` to a new path rather than replacing existing files. For subsequent restarts on this format, preserve the signer credentials, database and any storage key. `messageStorage` holds private conversation history and its diagnostic states; it defaults to `sqliteMessageStorage` in the configured database. Supply `sqliteMessageStorage('./messages.sqlite')` or implement `insert`, `query` and `updateState` to use another history backend. ID claims, outbox, keys and other internal data use `database`. Custom `Transport` implementations are also supported.
194
190
 
195
191
  ### Resource lifecycle
196
192
 
@@ -206,7 +202,7 @@ Close Bot before its injected resources. Call stop/close outside message handler
206
202
 
207
203
  Default NIP-17 uses account-key encryption. Explicit `mode: 'nip4e'` generates or restores separate messaging keys for extension peers. Both modes accept supported standard NIP-17 and NIP-4E messages.
208
204
 
209
- Relay connections are pooled and reconnect independently. History recovery uses bounded overlap paging. Messages recovered after downtime remain history and do not automatically execute commands.
205
+ Relay connections are pooled and reconnect independently. Recovery uses bounded overlap paging. On first startup the Bot saves its DM activation time. Older DMs are ignored; new DMs found after downtime enter the same middleware and handlers as live DMs, at most once.
210
206
 
211
207
  See [key rotation](docs/KEYS.md), [interoperability](docs/INTEROPERABILITY.md), [relay configuration](docs/RELAYS.md) and [recovery](docs/RECOVERY.md) for detailed behavior and limits.
212
208
 
@@ -236,39 +232,51 @@ Start with the [first bot tutorial](docs/TUTORIAL.md) for a step-by-step path fr
236
232
  | [Contributing](CONTRIBUTING.md) | Development and validation expectations |
237
233
  | [Security](SECURITY.md) | Trust boundaries and known limitations |
238
234
 
239
- Chirli supports one-to-one private text, reply references, sending reactions, and explicitly scoped kind 1/1111 public commands. See [public inputs and threads](docs/PUBLIC.md). Groups, receiving or downloading attachments, full archive recovery and exactly-once external effects are outside its scope. One active Bot/process per account database is supported. Public relays, external signer products and production deployments require separate validation.
235
+ Chirli supports one-to-one private text and [file attachments](docs/API.md#receive-and-download-a-private-file), reply references, private and public reactions, and [explicitly scoped kind 1/1111 public commands](docs/PUBLIC.md). Groups, full archive recovery and exactly-once external effects are outside its scope. One active Bot/process per account database is supported. Public relays, external signer products and production deployments require separate validation.
240
236
 
241
237
  Bot command identifiers come from their command names; custom `id` parameters are rejected. Renaming a command removes the old coordinate and adds the new one. Startup compares one broad author-scoped kind 31992 scan per write relay with the complete local registry; runtime additions synchronize automatically. Remote kind 5 queries belong to independent discovery, while locally pending withdrawals remain durable. See [command lifecycle and upgrade behavior](docs/NIP-CD.md).
242
238
 
243
- ## Optional inbound policy and processing timing
239
+ ## Optional access and timing middleware
244
240
 
245
241
  ```ts
246
- import { Bot, allowlist, requestTiming } from 'chirli';
247
-
248
- const bot = new Bot({ signer, inboundPolicy: allowlist(trustedIdentityPubkeys) });
249
- bot.use(requestTiming({ onTiming: metric => { console.info(metric); } }));
250
- bot.command({ command: 'ping', scopes: ['kind:14'] }, async ctx => { await ctx.reply('pong'); });
242
+ import { Bot, allowlist, requestTiming } from "chirli";
243
+
244
+ const bot = new Bot({ signer });
245
+ bot.use(allowlist(trustedIdentityPubkeys));
246
+ bot.use(
247
+ requestTiming({
248
+ onTiming: (metric) => {
249
+ console.info(metric);
250
+ },
251
+ }),
252
+ );
253
+ bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
254
+ await ctx.reply("pong");
255
+ });
251
256
  await bot.start(); // Command declarations remain automatic.
252
257
  ```
253
258
 
254
- `inboundPolicy` runs after identity verification and before incoming history, peer evidence, observers or business callbacks. `allowlist` snapshots the supplied lowercase hex identity keys. `allowlist([])` denies every external sender. Middleware registered through `bot.use()` runs after receipt persistence. [Sender authorization](docs/ACCESS.md)
259
+ `allowlist` snapshots the supplied lowercase hex identity keys. Register it first to block downstream middleware and handlers for nonmembers. `allowlist([])` blocks every external sender from routing, including eligible DMs discovered during recovery. Returning early does not undo the prior ID claim. [Sender authorization](docs/ACCESS.md)
255
260
 
256
261
  `requestTiming({onTiming})` is optional ordinary middleware. Its observer receives only `{durationMs,outcome:'success'|'failure'}` for the downstream processing chain. It never reads message context or error details, does not log by default and cannot let observer failures change processing. It excludes receipt/decryption, queue waiting and session commit after the chain; no command route name is inferred from text. See [API](docs/API.md).
257
262
 
258
263
  ## Public input and shared context
259
264
 
260
- Register one explicitly scoped command for DMs, notes and comments. Public reads require `publicInbox: {relays: [...]}`; they never use implicit default relays. `ctx.input` contains the authenticated input, `ctx.reply()` chooses encrypted DM or public kind 1111, and `await ctx.thread({limit:30})` lazily loads prior context. Public context/session storage never reads private conversations.
265
+ Omit `scopes` to publish `kind:14`, `kind:1` and `kind:1111`. Use an explicit list to narrow the scope. File DMs go to `bot.handle()`. Public reads require `publicInbox: {relays: [...]}`; they never use implicit default relays. `ctx.input` contains the authenticated input. `ctx.reply()` and `ctx.react()` preserve its private or public visibility, and `await ctx.thread({limit:30})` lazily loads prior context. Public context/session storage never reads private conversations.
261
266
 
262
267
  ```ts
263
- const bot = new Bot({signer, publicInbox:{relays:publicInboxRelays}});
264
- bot.command({command:'ping',scopes:['kind:14','kind:1','kind:1111']}, async ctx => {
265
- await ctx.reply('pong');
266
- });
268
+ const bot = new Bot({ signer, publicInbox: { relays: publicInboxRelays } });
269
+ bot.command(
270
+ { command: "ping" },
271
+ async (ctx) => {
272
+ await ctx.reply("pong");
273
+ },
274
+ );
267
275
  await bot.start();
268
276
  ```
269
277
 
270
- Run `npm run example:public` for an offline three-kind demo and deterministic application-owned `/summarize` mock. See [targeting, replies, thread bounds and migration](docs/PUBLIC.md).
278
+ Run `npm run example:public` for an offline three-kind demo and deterministic application-owned `/summarize` mock. See [targeting, replies and thread bounds](docs/PUBLIC.md).
271
279
 
272
- For application-owned background work, retain `ctx.input.event` and later call `await bot.thread(event,{limit:30})` and `await bot.reply(event,text)`. Both preserve private/public routing and reuse handler semantics. DM authentication requires the same account's retained incoming record; a public target requires the complete signed event. See [delayed calls and trust requirements](docs/API.md#replies-and-context-after-a-handler), or run `npm run example:async-reply` entirely offline.
280
+ For application-owned background work, retain `ctx.input.event` and pass it to `bot.thread(event,{limit:30})`, `bot.reply(event,text)` or `bot.react(event,'👍')`. These methods preserve private/public routing and reuse handler semantics. DM authentication requires the same account's retained incoming record; a public target requires the complete signed event. See [delayed calls and trust requirements](docs/API.md#replies-and-context-after-a-handler), or run `npm run example:async-reply` entirely offline.
273
281
 
274
282
  Command `args` accepts a Zod 4 `z.object(...)` directly. The schema both generates NIP-CD metadata and validates decoded input; handler-only `ctx.args` and the second handler argument share the inferred valid result. Use middleware or `bot.catch` for centralized `InvalidArgsError` handling; no automatic error reply or retry is added. See [schema support and authorization boundaries](docs/API.md#zod-command-arguments).
package/SECURITY.md CHANGED
@@ -11,9 +11,9 @@ Include the affected version and mode, expected and actual behavior, impact, san
11
11
  ## Boundaries
12
12
 
13
13
  - The decoder verifies the giftwrap, seal, rumor hash, author and one-to-one recipient before exposing text. Default identity-key NIP-17 and explicit split-key mode both accept verified standard and NIP-4E envelopes; the legacy compatibility:false flag only suppresses identity-key declaration publication. Known unrelated own key declarations block publication; discovery freshness is bounded by relays/cache, not globally guaranteed. See docs/INTEROPERABILITY.md.
14
- - Database payloads use AES-256-GCM only when storageKey is supplied; otherwise payloads/keyrings are explicitly tagged plaintext without cryptographic tamper protection; public routing metadata and status/timestamp indexes remain visible. Core Bot does not store identity signing secrets; the live application can persist a generated signer in a private adjacent file. Split encryption keys and pending declarations follow the configured plaintext/encrypted codec. Preserve the original storageKey whenever encryption is enabled. Protect storage keys, files, backups, process memory and your own logs.
15
- - Incoming rumor IDs deduplicate protocol receipt, not arbitrary external side effects. Failed/incomplete business work can run again. Relay acceptance means neither delivery nor reading.
16
- - Historical and self-copy messages do not run live handlers. A new subscription, including one after AUTH, treats frames before EOSE as history. Downtime messages may be synchronized without executing old commands.
14
+ - Database payloads use AES-256-GCM only when storageKey is supplied; otherwise payloads/keyrings are explicitly tagged plaintext without cryptographic tamper protection; routing metadata, claimed IDs and status/timestamp indexes remain visible. Core Bot does not store identity signing secrets; the live application can persist a generated signer in a private adjacent file. Split encryption keys and pending declarations follow the configured plaintext/encrypted codec. Preserve the original storageKey whenever encryption is enabled. Protect storage keys, files, backups, process memory and your own logs. Downloaded attachments are saved as verified plaintext in a separate per-account directory; `storageKey` protects database payloads only. Attachment downloads are explicit and limited to configured origins, including each redirect.
15
+ - Authenticated canonical input IDs are claimed atomically before business middleware. Claims prevent a second SDK attempt, not missed or partial effects after a crash. The SDK does not retry business callbacks. Relay acceptance means neither delivery nor reading.
16
+ - Incoming DMs before first activation are ignored. Eligible incoming DMs found during downtime recovery can execute the same middleware and handlers as live input, but never rerun a claimed ID. Outgoing self copies and public history do not run business handlers.
17
17
  - Untrusted relay URLs come from signed metadata or application configuration. The SDK makes outbound WebSocket connections to them; applications deploying in restricted networks must enforce their own destination policy. There is no built-in SSRF allowlist or tenant boundary.
18
18
  - Identity signers must sign the exact requested template. Both modes retain identity-key crypto for standard peers; split mode adds generated/imported current, pending and legacy local keys. Neither mode supplies forward secrecy or key-vault isolation by itself.
19
19
  - Error observers can see verified message context and application errors. Observer failures are ignored so monitoring cannot crash message processing; sanitize logging and handle telemetry failures in your application.
@@ -22,19 +22,19 @@ One active process/client per account database, including across modes, is suppo
22
22
 
23
23
  The checked-in CI uses only disposable/local protocol tests. Actual public relays, mobile apps, external bunker products and hardware signers and production deployments require separate assessment. No real AI provider or external tool execution is part of this SDK.
24
24
 
25
- Managed subscriptions reconnect with bounded backoff and overlap paging; raw transport alone does not. Recovered envelopes never execute live commands, and incomplete scans leave checkpoints unchanged. A remote signer sees plaintext used in NIP-44 operations. Its operational failures are surfaced and stop recovery checkpoint advancement. Opaque remote decryption errors are conservatively treated as retryable, so corrupt signed wrappers can also leave a remote scan incomplete; there is no durable raw-envelope quarantine or product-specific error classification. See SIGNERS.md and RECOVERY.md.
25
+ Managed subscriptions reconnect with bounded backoff and overlap paging; raw transport alone does not. Recovered DMs since first activation are eligible for a first dispatch, and incomplete scans leave checkpoints unchanged. A remote signer sees plaintext used in NIP-44 operations. Its operational failures are surfaced and stop recovery checkpoint advancement. Opaque remote decryption errors are conservatively treated as retryable, so corrupt signed wrappers can also leave a remote scan incomplete; there is no durable raw-envelope quarantine or product-specific error classification. See SIGNERS.md and RECOVERY.md.
26
26
 
27
27
  Registered NIP-CD definitions are always public on configured write relays. Bot startup reconciles its account's complete registry, including deleting old definitions absent locally. Register every module before starting one account owner. Ordinary Clients do not own catalogs or modify user-installed kind 10992 lists. All write-relay queries/publications must succeed before Bot startup completes. An unavailable or known truncated snapshot never becomes deletion evidence. Metadata/scopes grant no execution permission, and public withdrawal cannot erase cached copies.
28
28
 
29
29
  Explicit keyRotation configuration authorizes scheduled public encryption-key declarations while started. Candidates are durable before publication; ACK failure keeps pending custody and retries the same event. Retired-key count/optional age pruning happens only after successful rotation. Evicted keys cannot decrypt unseen old envelopes; SQLite/WAL/backups are not securely erased. Known foreign declarations require explicit locally held-key migration, never forced overwrite. Relay/cache checks are not a globally fresh account lock. See [key custody and migration](docs/KEYS.md).
30
30
 
31
- Custom MessageStorage implementations receive encoded messages, processing state and public routing metadata, never storageKey, keyrings, evidence or outbox records. They are trusted for durable unique insertion, state updates and account isolation; losing or changing done states can cause repeated handling. With storageKey, payloads are ciphertext; without it they are readable plaintext. Internal SQLite retains only temporary message handoffs until insertion succeeds. Protect both stores and follow docs/STORAGE.md. Multiple-relay discovery can be partial; cached evidence is not a globally fresh declaration guarantee. At least one ACK is not all-relay replication. See docs/RELAYS.md.
31
+ Custom MessageStorage implementations receive retained encoded private messages, diagnostic state and routing metadata, never storageKey, keyrings, evidence or outbox records. They are trusted for durable unique insertion, state updates and account isolation. The SDK records input claims separately in internal SQLite. With storageKey, payloads are ciphertext; without it they are readable plaintext. Internal SQLite retains only temporary message handoffs until insertion succeeds. Protect both stores and follow docs/STORAGE.md. Multiple-relay discovery can be partial; cached evidence is not a globally fresh declaration guarantee. At least one ACK is not all-relay replication. See docs/RELAYS.md.
32
32
 
33
- Bot allowlist is checked against the verified seal/rumor identity in both modes before new history, peer evidence or business callbacks. Anonymous wrapper authors and separated n encryption keys grant no authorization. Empty lists deny all external incoming senders; absent lists preserve open intake. Rejected new rumors have no durable denial receipt, so policy changes can admit later live presentations. Revoked pending business work is consumed without callbacks; old history remains readable. Crypto/remote signer work and operational error monitoring still occur before a hidden sender can be authenticated. This inbound policy is not an outbound ACL or rate limiter. See [access](docs/ACCESS.md).
33
+ Register allowlist as the first middleware to restrict downstream callbacks to verified accounts. Anonymous wrapper authors and split messaging keys grant no authorization. An empty list blocks every external sender from routing; omitting it imposes no additional access restriction. Eligible IDs remain claimed even for denied inputs. A short-circuited DM does not enter private history; recovered copies do not bypass this by storing a body. Crypto and remote signer work can occur before the sender is known. Middleware is not an outbound ACL or rate limiter. See [access](docs/ACCESS.md).
34
34
 
35
35
  The optional live-example initializer creates a fresh bot nsec/storageKey in an ignored 0600 .env file; this is operator credential storage, separate from SDK keyring persistence and not a hardware vault. Live runners intentionally read operator configuration only when explicitly started, publish their own key/relay metadata and registered public commands and respond to permitted DMs. They do not print incoming text, credentials or bunker authorization URLs. Protect config/database backups. Automated tests use generated temporary configs and local relays only.
36
36
 
37
- Zero-config live startup reuses/creates a 0600 identity file beside the database and logs only public keys. That file is encrypted if CHIRLI_STORAGE_KEY is provided, otherwise plaintext. It is never overwritten to fix parsing/key/mode errors. Existing databases without their generated signer file require the original signer to avoid silently changing accounts. Default public relays match PsstPsst; testing does not connect to them. Plaintext persistence assumes trusted filesystem/backend contents, including pending business records. Initial wire signature/author validation and NIP-44 encryption remain mandatory in either storage mode.
37
+ Zero-config live startup reuses/creates a 0600 identity file beside the database and logs only public keys. That file is encrypted if CHIRLI_STORAGE_KEY is provided, otherwise plaintext. It is never overwritten to fix parsing/key/mode errors. Existing databases without their generated signer file require the original signer to avoid silently changing accounts. Default public relays match PsstPsst; testing does not connect to them. Plaintext persistence assumes trusted filesystem/backend contents, including retained conversation records and claim IDs. Initial wire signature/author validation and NIP-44 encryption remain mandatory in either storage mode.
38
38
 
39
39
  Built-in RelayError diagnostic fields expose only origin, operation/code, whitelisted network/reason codes and numeric statuses/kinds. Relay paths/queries/credentials, raw rejection bodies, AUTH challenges and message text are withheld. The live formatter does not print arbitrary application Error.message/stack and bounds aggregate recursion. Explicit custom application logging remains the application's responsibility. Read-only operator connectivity diagnostics do not require a private key or event publication.
40
40
 
@@ -42,14 +42,14 @@ Automatic NIP-4E device sync is enabled by default. Only verified requests signe
42
42
 
43
43
  Own metadata subscriptions and peer cache hold only verified signed state; newest observed does not mean globally fresh. Stale peer routes/keys can temporarily remain in use within the documented cache window. Missing peer 10050 uses own DM relay fallback, so peer receipt is not guaranteed. Metadata snapshots are instance-local memory; durable seal/declaration ordering remains in the existing store. Full lookup failures do not establish a successful absence; fallback after total failure requires existing authenticated key evidence.
44
44
 
45
- Construct a Bot with a signer. Its startup resolves the account through Signer.getPublicKey and uses Signer.signEvent and NIP-44 operations. Signer implementations keep the credentials, and the application owns their lifetime. Receipt callbacks registered with `observe()` receive detached snapshots. Use durable handlers for business effects, with application idempotency where retry can repeat an effect.
45
+ Construct a Bot with a signer. Its startup resolves the account through Signer.getPublicKey and uses Signer.signEvent and NIP-44 operations. Signer implementations keep the credentials, and the application owns their lifetime. Receipt callbacks registered with `observe()` receive detached snapshots. Use an application-owned durable job or idempotency mechanism where a business effect must recover after a crash.
46
46
 
47
47
  Startup command reconciliation uses author-scoped kind 31992 snapshots only; signature/author checks and detectably incomplete-read failures remain mandatory. Fresh absence does not make confirmed local cache into remote presence. Relays can silently omit/cap results, and public operations across replicas are not atomic. Independent discovery still verifies kind 5 withdrawals to exclude stale definitions. Unsupported legacy journal event kinds are dropped before replay; supported pending command operations retain exact IDs.
48
48
 
49
- The `allowlist` helper supplies an inbound policy over the authenticated sender string. The policy runs before incoming persistence, evidence and observers and is rechecked for pending work. An explicit boolean `true` authorizes the sender. `requestTiming` telemetry contains only elapsed milliseconds and chain outcome and isolates observer failures. Applications supply custom policies and observers. Business middleware starts after receipt persistence.
49
+ `requestTiming` telemetry contains only elapsed milliseconds and chain outcome, and isolates observer failures. Applications own their policies and observers. No access middleware runs before authentication and the ID claim.
50
50
 
51
- Public kind 1/1111 input requires an explicit inbox and declared supported scopes. Signature, source, author policy, structure and unambiguous invocation targeting are checked before the separate public journal or business middleware. Public session/thread methods never load private peer data. Public replies are intentionally public kind 1111, routed only to configured write/source relays; arbitrary tag URLs are not contacted. Public thread scope claims are signed claims, not proof of truthful ancestry, and resolved context remains untrusted application input. Public ID deduplication retains at most 5000 records; eviction, failed handlers and uncertain completion prevent an exactly-once guarantee. Public queued payloads/outbox use the same selected storage codec as internal metadata. See [public input boundaries](docs/PUBLIC.md).
51
+ Public kind 1/1111 input requires an explicit inbox and declared supported scopes. Signature, source, structure and unambiguous invocation targeting are checked before claiming an ID and running business middleware. Public session/thread methods never load private peer data. Public replies and reactions intentionally publish signed kind 1111 and kind 7 events, respectively, only to configured write/source relays; arbitrary tag URLs are not contacted. Public thread scope claims are signed claims, not proof of truthful ancestry, and resolved context remains untrusted application input. No public input history or callback payload is kept. Claims do not guarantee exactly-once external effects. The public outbox uses the same selected storage codec as internal metadata. See [public input boundaries](docs/PUBLIC.md).
52
52
 
53
- Delayed `bot.reply(event,...)` / `bot.thread(event,...)` calls use original input events, never arbitrary IDs or outer envelopes. Signed public events are independently reverified; source provenance is local-journal-only. Unsigned DM rumors must match the account/mode's persisted authenticated incoming record, canonical hash/fields and private routing; a rumor's ID or asserted sender alone grants no trust. Applications own their worker queues and must protect saved DM events as plaintext. Calls are explicit application effects, not inbound policy dispatch; repeated calls are not deduplicated as jobs. See docs/API.md.
53
+ Delayed `bot.reply(event,...)`, `bot.react(event,...)` and `bot.thread(event,...)` calls use original input events, never arbitrary IDs or outer envelopes. Signed public events are independently reverified; only immediate handler calls retain the incoming relay as a routing hint, and delayed replies and reactions use configured write relays. Unsigned DM rumors must match the account/mode's persisted authenticated incoming record, canonical hash/fields and private routing; a rumor's ID or asserted sender alone grants no trust. Applications own their worker queues and must protect saved DM events as plaintext. Calls are explicit application effects, not inbound policy dispatch; repeated calls are not deduplicated as jobs. See docs/API.md.
54
54
 
55
55
  The nostr-tools transport uses a native JSON syntax preflight and canonical EVENT framing to prevent malformed inputs from reaching the dependency raw logger. Non-string CLOSED reasons are normalized to a constant safe rejection. The library uses an origin-only diagnostic label while the socket and NIP-42 tag preserve the exact configured URL. Tests cover malformed/truncated EVENT and control JSON with synthetic token/content values. This framing guard adds one native JSON decode before library decoding; it is not an independent Nostr parser or a guarantee about all future dependency diagnostics. See docs/RELAYS.md for tested boundaries and remaining ACK/keepalive timer behavior.
@@ -0,0 +1,3 @@
1
+ import type { Context, Next } from "./bot-handlers.js";
2
+ /** Allow the selected verified account keys to continue through the middleware chain. */
3
+ export declare function allowlist(pubkeys: readonly string[]): (ctx: Pick<Context, "sender">, next: Next) => Promise<void> | undefined;
@@ -0,0 +1,9 @@
1
+ import { hexKey } from "./protocol.js";
2
+ /** Allow the selected verified account keys to continue through the middleware chain. */
3
+ export function allowlist(pubkeys) {
4
+ if (!Array.isArray(pubkeys) || !Array.from(pubkeys).every(hexKey)) {
5
+ throw new TypeError("allowlist must be an array of lowercase hex identity public keys");
6
+ }
7
+ const identities = new Set(pubkeys);
8
+ return (ctx, next) => (identities.has(ctx.sender) ? next() : undefined);
9
+ }
@@ -1,7 +1,7 @@
1
- import type { Event, EventTemplate } from 'nostr-tools';
2
- import { type Identity } from './protocol.js';
3
- import type { Store } from './store.js';
4
- import type { Transport } from './relay.js';
1
+ import type { Event, EventTemplate } from "nostr-tools";
2
+ import { type Identity } from "./protocol.js";
3
+ import type { Store } from "./store.js";
4
+ import type { Transport } from "./relay.js";
5
5
  export interface Announcement {
6
6
  template: EventTemplate;
7
7
  groups: string[][];