chirli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +103 -0
- package/CONTRIBUTING.md +56 -0
- package/LICENSE +22 -0
- package/README.md +281 -2
- package/SECURITY.md +55 -0
- package/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/allowlist.d.ts +3 -0
- package/dist/allowlist.js +9 -0
- package/dist/announcements.d.ts +25 -0
- package/dist/announcements.js +142 -0
- package/dist/attachments.d.ts +43 -0
- package/dist/attachments.js +340 -0
- package/dist/blossom.d.ts +30 -0
- package/dist/blossom.js +233 -0
- package/dist/bot-handlers.d.ts +70 -0
- package/dist/bot-handlers.js +317 -0
- package/dist/bot.d.ts +63 -0
- package/dist/bot.js +244 -0
- package/dist/client.d.ts +221 -0
- package/dist/client.js +1197 -0
- package/dist/command-discovery.d.ts +4 -0
- package/dist/command-discovery.js +33 -0
- package/dist/command-schema.d.ts +4 -0
- package/dist/command-schema.js +101 -0
- package/dist/commands.d.ts +32 -0
- package/dist/commands.js +253 -0
- package/dist/defaults.d.ts +9 -0
- package/dist/defaults.js +22 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.js +126 -0
- package/dist/inbox.d.ts +55 -0
- package/dist/inbox.js +376 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +11 -0
- package/dist/key-sync.d.ts +33 -0
- package/dist/key-sync.js +293 -0
- package/dist/keys.d.ts +66 -0
- package/dist/keys.js +418 -0
- package/dist/message-storage-sqlite.d.ts +6 -0
- package/dist/message-storage-sqlite.js +90 -0
- package/dist/message-storage.d.ts +32 -0
- package/dist/message-storage.js +1 -0
- package/dist/messaging-metadata.d.ts +48 -0
- package/dist/messaging-metadata.js +280 -0
- package/dist/metadata.d.ts +7 -0
- package/dist/metadata.js +63 -0
- package/dist/modes.d.ts +26 -0
- package/dist/modes.js +108 -0
- package/dist/nip4e-compat.d.ts +4 -0
- package/dist/nip4e-compat.js +14 -0
- package/dist/nipcd.d.ts +109 -0
- package/dist/nipcd.js +555 -0
- package/dist/protocol.d.ts +68 -0
- package/dist/protocol.js +302 -0
- package/dist/public-inbox.d.ts +66 -0
- package/dist/public-inbox.js +295 -0
- package/dist/public-thread.d.ts +62 -0
- package/dist/public-thread.js +436 -0
- package/dist/relay-pool.d.ts +43 -0
- package/dist/relay-pool.js +429 -0
- package/dist/relay-roles.d.ts +18 -0
- package/dist/relay-roles.js +55 -0
- package/dist/relay.d.ts +52 -0
- package/dist/relay.js +493 -0
- package/dist/request-timing.d.ts +12 -0
- package/dist/request-timing.js +37 -0
- package/dist/session.d.ts +16 -0
- package/dist/session.js +51 -0
- package/dist/signer.d.ts +13 -0
- package/dist/signer.js +1 -0
- package/dist/signers/bunker-relays.d.ts +15 -0
- package/dist/signers/bunker-relays.js +87 -0
- package/dist/signers/bunker.d.ts +7 -0
- package/dist/signers/bunker.js +194 -0
- package/dist/signers/nsec.d.ts +3 -0
- package/dist/signers/nsec.js +62 -0
- package/dist/signers.d.ts +18 -0
- package/dist/signers.js +59 -0
- package/dist/storage-sqlite.d.ts +29 -0
- package/dist/storage-sqlite.js +221 -0
- package/dist/storage.d.ts +85 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +96 -0
- package/dist/store.js +404 -0
- package/docs/ACCESS.md +28 -0
- package/docs/API.md +382 -0
- package/docs/INTEROPERABILITY.md +32 -0
- package/docs/KEYS.md +75 -0
- package/docs/NIP-CD.md +112 -0
- package/docs/PUBLIC.md +88 -0
- package/docs/RECOVERY.md +59 -0
- package/docs/RELAYS.md +145 -0
- package/docs/SESSIONS.md +108 -0
- package/docs/SIGNERS.md +59 -0
- package/docs/STORAGE.md +71 -0
- package/docs/TUTORIAL.md +178 -0
- package/package.json +47 -4
package/docs/API.md
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
# Public API
|
|
2
|
+
|
|
3
|
+
Chirli is an ESM-only Node.js 24+ package. Import from `chirli`; internal source subpaths are not package exports. Start with the [tutorial](TUTORIAL.md) for an application walkthrough.
|
|
4
|
+
|
|
5
|
+
## Construction
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Bot, nsecSigner } from "chirli";
|
|
9
|
+
|
|
10
|
+
const signer = nsecSigner(nsecFromYourSecretManager);
|
|
11
|
+
const bot = new Bot({
|
|
12
|
+
signer,
|
|
13
|
+
database: "./chirli.sqlite",
|
|
14
|
+
});
|
|
15
|
+
bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
|
|
16
|
+
await ctx.reply("pong");
|
|
17
|
+
});
|
|
18
|
+
await bot.start();
|
|
19
|
+
console.log(bot.pubkey);
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Construct the Bot and register handlers before calling `start()`. `start()` resolves and caches the signer's public key, opens storage, publishes discovery information and starts receiving messages. Read `bot.pubkey` after startup. `bot.mode` reports the selected protocol mode, with `nip17` as the default. The application owns injected resources. Close the Bot before closing its signer, transport or message backend.
|
|
23
|
+
|
|
24
|
+
## Configuration
|
|
25
|
+
|
|
26
|
+
| Option | Contract |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| `signer` | Required signing and account-key NIP-44 capabilities; see [signers](SIGNERS.md) |
|
|
29
|
+
| `database` | SQLite path; default `psstpsst.sqlite`; `:memory:` is ephemeral |
|
|
30
|
+
| `messageStorage` | Retained private conversation history and its diagnostic states; defaults to `sqliteMessageStorage` |
|
|
31
|
+
| `sessionStore` | Optional backend for conversation state. See the [custom store example](SESSIONS.md#use-a-custom-session-store). |
|
|
32
|
+
| `storageKey` | Optional 32-byte local encryption key; omission selects tagged plaintext |
|
|
33
|
+
| `transport` | Injected `Transport`; exclusive with `transportOptions` |
|
|
34
|
+
| `transportOptions` | Default WebSocket timeouts and query concurrency |
|
|
35
|
+
| `relays` | Nonempty shorthand for each omitted relay role |
|
|
36
|
+
| `dmRelays` | Inbox/delivery role; nonempty |
|
|
37
|
+
| `readRelays` | Metadata discovery role; `[]` is allowed |
|
|
38
|
+
| `writeRelays` | Public metadata/command role; nonempty |
|
|
39
|
+
| `discoveryRelays` | Extra recipients for public account announcements; `[]` disables this extra fan-out |
|
|
40
|
+
| `blossomServers` | Ordered upload servers; defaults to `https://blossom.jumble.social/`; `[]` disables file uploads |
|
|
41
|
+
| `blossomDownloadOrigins` | Additional trusted HTTPS origins for uploaded blob URLs and incoming attachment downloads |
|
|
42
|
+
| `attachmentDirectory` | Root directory for verified downloads. Defaults to `<database>.attachments`, or `psstpsst.sqlite.attachments` for an in-memory database |
|
|
43
|
+
| `mode` | `nip17` default, or explicit `nip4e` split messaging keys |
|
|
44
|
+
| `keyRotation` | Omitted/false, or split-mode rotation settings; see [keys](KEYS.md) |
|
|
45
|
+
| `nip4eCompatibility` | False suppresses identity-key 10044 publication; dual intake stays enabled |
|
|
46
|
+
| `reconnect` | Retry settings or false; enabled by default |
|
|
47
|
+
| `recovery` | Bounded history settings or false; enabled by default |
|
|
48
|
+
| `historyLimit` | Initial per-relay giftwrap request limit; default 500 |
|
|
49
|
+
| `metadataCache` | Peer cache settings or false; see [relays](RELAYS.md) |
|
|
50
|
+
| `keySync` | Same-identity split-key sync settings or false; see [keys](KEYS.md) |
|
|
51
|
+
|
|
52
|
+
Omitted relay roles use exported `DEFAULT_DM_RELAYS`, `DEFAULT_READ_RELAYS`, `DEFAULT_WRITE_RELAYS` and `DEFAULT_DISCOVERY_RELAYS` unless overridden by the `relays` shorthand. The account, mode and storage codec are fixed for a Bot's lifetime. Use a fresh database for this storage format; earlier pre-release databases are not migrated. Preserve credentials, this database and any storage key across restarts.
|
|
53
|
+
|
|
54
|
+
## Lifecycle
|
|
55
|
+
|
|
56
|
+
| Method | Behavior |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| `announce(options?)` | Explicitly publish account key/relay metadata and synchronize registered commands |
|
|
59
|
+
| `start()` | Resolve the signer, publish key/relay metadata, synchronize commands, open inbox and retry pending outgoing deliveries |
|
|
60
|
+
| `idle()` | Drain ordered crypto intake and currently queued handlers |
|
|
61
|
+
| `requestStop()` | Request shutdown from a handler without awaiting its own drain |
|
|
62
|
+
| `stop()` | Cancel subscriptions/timers/recovery and drain current work; Bot stays reusable |
|
|
63
|
+
| `close()` | Stop and release internally owned resources; idempotent |
|
|
64
|
+
| `syncHistory()` | Scan running subscriptions' bounded recovery windows |
|
|
65
|
+
| `flushAnnouncements()` | Retry pending account metadata and dirty/pending command state |
|
|
66
|
+
| `flushOutbox()` | Retry persisted message bundles; aggregate failures after attempting the snapshot |
|
|
67
|
+
|
|
68
|
+
`start()` does not render or return the identity. After it completes, `bot.pubkey` is the bot account’s 64-character lowercase hex public key. Applications can display it as text or derive a link or QR payload:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { npubEncode } from "nostr-tools/nip19";
|
|
72
|
+
|
|
73
|
+
await bot.start();
|
|
74
|
+
const uri = `nostr:${npubEncode(bot.pubkey)}`;
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Concurrent start calls share readiness/failure; a start during stop waits for teardown. Startup requires one ready DM replica, while command reconciliation requires every write relay. Other DM replicas can continue recovering. History scans may report incomplete coverage without failing startup. Start does not await every business handler.
|
|
78
|
+
|
|
79
|
+
`idle()` is not a remote synchronization or delivery barrier. `idle()`, `stop()` and `close()` reject inside message handlers because they would wait on themselves. Use `requestStop()` there, then drain outside the handler. Once stopping begins, new intake is ignored and `bot.receive()` returns `false` without consuming the ID. Work already queued for processing can finish; inputs still being decrypted are not admitted after stop.
|
|
80
|
+
|
|
81
|
+
Await application-owned sends and stop/await application timers before closing Bot. SDK shutdown drains its own work; it cannot cancel arbitrary application effects. One active Bot/process per account database is supported.
|
|
82
|
+
|
|
83
|
+
## Event processing flow
|
|
84
|
+
|
|
85
|
+
1. **Verify.** For a DM, unwrap the envelope and verify its signatures, canonical rumor ID, sender and recipient, then check its authenticated timestamp against first activation. For a public note or comment, verify the signed event and check its configured source relay, structure, command target and scope. Invalid or ineligible input stops here; it claims nothing and runs no middleware, command or fallback.
|
|
86
|
+
2. **Claim.** Atomically insert the canonical ID in the account/mode's SQLite store: the inner rumor ID for a DM, or the signed event ID for public input. A duplicate stops before middleware. Eligible public history still stops after claiming its ID; a later live copy does not run. Incoming DM recovery and live delivery use the same admission rule. Eligible outgoing self copies can populate private history without middleware.
|
|
87
|
+
3. **Run middleware once.** An eligible input enters its conversation or public-root queue. Middleware runs in registration order; put `bot.use(allowlist(pubkeys))` first to restrict everything downstream. Returning without `next()` stops routing. If the chain throws, the error is reported through the applicable error handler. In either case the ID stays claimed; reconnect and restart do not reopen it.
|
|
88
|
+
4. **Route.** When middleware reaches routing, a DM is saved to private conversation history and can notify receipt observers. Public input has no stored body or conversation history. The SDK invokes the matching scoped command (including argument checks and any command-specific authorization), or the DM fallback if no command matches. The claim is already durable: a crash can leave a callback partially executed or prevent it from running at all.
|
|
89
|
+
5. **Publish outgoing events separately.** Sends, replies and reactions are stored before publication. Startup, reconnect or `flushOutbox()` can retry that exact signed event, not the incoming callback. Relay acceptance does not confirm delivery or reading.
|
|
90
|
+
|
|
91
|
+
## Processing and observations
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
const detach = bot.handle(async (ctx) => {
|
|
95
|
+
await ctx.reply("Thanks");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const unobserve = bot.observe((message) => {
|
|
99
|
+
// Receipt observation only; no durable success/failure responsibility.
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`handle()` registers the handler for messages with no matching command. It receives the same context as command handlers and can be registered before or after commands. Each Bot has one fallback. Call the returned unsubscribe function before registering a replacement.
|
|
104
|
+
|
|
105
|
+
`observe()` subscribes to newly admitted DMs retained in local conversation history, using detached copies. It runs once routing is reached and does not control command matching or completion.
|
|
106
|
+
|
|
107
|
+
Callbacks are serial within a conversation or public root; different queues can proceed concurrently. See the [event processing flow](#event-processing-flow) for the claim, history and outgoing retry boundaries.
|
|
108
|
+
|
|
109
|
+
`onError(observer)` returns an unsubscribe function. It receives an error and optional verified message context. Observer failures are ignored; there is no SDK default logger.
|
|
110
|
+
|
|
111
|
+
For callers injecting protocol events, `await bot.receive(event, source, {relay})` reports intake, not handler success. An eligible new ID returns `true` even if access middleware later stops it; a duplicate or ineligible event returns `false`. Public injection requires a configured source relay. Use `await bot.idle()` to drain queued callbacks, not to force retries.
|
|
112
|
+
|
|
113
|
+
A `Message` contains rumor `id`, identity `sender`, peer `conversation`, `text`, millisecond `timestamp`, `source`, `direction`, verified `rumor`, optional parent `replyTo`, and optional transport `relay`. Relay provenance is not author-signed. Deduplication uses account/mode + rumor ID, not giftwrap ID.
|
|
114
|
+
|
|
115
|
+
## Sending and history
|
|
116
|
+
|
|
117
|
+
`send(peerPubkey, nonemptyText, options?)` returns `{id, status}`, where status is `relay-accepted` or `pending`.
|
|
118
|
+
|
|
119
|
+
### Upload file bytes
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const { url, sha256, size, mimeType } = await bot.uploadFile(bytes, {
|
|
123
|
+
mimeType: "image/png",
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
`uploadFile(bytes, options?)` uploads the supplied bytes as-is, without encryption, to the first configured Blossom server that accepts them. If the bytes are plaintext, people who can access the blob URL can read them. Callers can encrypt bytes themselves before uploading. Pass `mimeType` for the uploaded bytes, or omit it to use `application/octet-stream`. The result contains the verified URL, SHA-256, byte count and MIME sent in the request. The URL must end in the blob hash, with an optional extension, and use the accepting server’s origin or an explicit `blossomDownloadOrigins` entry. This upload does not send any Nostr message or publish a note; callers can use the result to build a public note with an `imeta` tag.
|
|
128
|
+
|
|
129
|
+
### Send a private file
|
|
130
|
+
|
|
131
|
+
Pass the file bytes, not a URL or a path. Configure the servers when constructing the bot:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { readFile } from "node:fs/promises";
|
|
135
|
+
import { Bot } from "chirli";
|
|
136
|
+
|
|
137
|
+
const bot = new Bot({ signer, blossomServers: ["https://files.example.com"] });
|
|
138
|
+
await bot.start();
|
|
139
|
+
const result = await bot.sendFile(peerPubkey, await readFile("report.pdf"), {
|
|
140
|
+
name: "report.pdf",
|
|
141
|
+
mimeType: "application/pdf",
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`sendFile(peerPubkey, bytes, options?)` accepts a nonempty `Uint8Array` (including a Node.js `Buffer`) up to an encrypted upload size of 64 MiB. It encrypts first, then uses the same `uploadFile()` path. The optional `name`, `mimeType` (default `application/octet-stream`) and `replyTo` stay inside the encrypted attachment message. Like `send()`, it returns the message ID and `relay-accepted` or `pending` after an upload succeeds. The relay outbox retries the same encrypted message without uploading again; if all uploads fail, the call rejects and queues no message. A successful upload can remain on the server if the later message send fails.
|
|
146
|
+
|
|
147
|
+
By default Chirli uses the exported `DEFAULT_BLOSSOM_SERVERS` list. An explicit list replaces it entirely. `start()` and `announce()` publish the ordered BUD-03 kind 10063 list to `writeRelays` and `discoveryRelays`, not to DM-only relays. With `blossomServers: []`, Chirli publishes no Blossom list and does not clear an existing public list. Use HTTPS URLs with no credentials, query or fragment. Explicit HTTP loopback URLs are allowed for development. Chirli tries only the configured servers, in order. After the first upload succeeds, it tries BUD-04 mirroring concurrently on the remaining configured servers. Mirrors are best-effort: failures do not change the successful upload result. Mirror requests reuse the successful upload authorization and have a 10-second HTTP timeout. The authorization is restricted to configured server hostnames; mirrors never ask the signer to sign again. No unconfigured server is used.
|
|
148
|
+
|
|
149
|
+
The server receives ciphertext, ciphertext size/hash and a signed upload authorization identifying the bot. The recipient gets the URL and decryption metadata inside a NIP-17 kind-15 gift wrap. Chirli stores outgoing file metadata in local message history like other messages; use `storageKey` (and an appropriate custom store, if configured) to protect it at rest. This API sends private files only.
|
|
150
|
+
|
|
151
|
+
See [NIP-17](https://github.com/nostr-protocol/nips/blob/master/17.md) and [Blossom server lists](https://github.com/hzrd149/blossom/blob/master/buds/03.md).
|
|
152
|
+
|
|
153
|
+
### Receive and download a private file
|
|
154
|
+
|
|
155
|
+
File DMs pass through the same middleware and `handle()` callback as text DMs. A kind-15 input has empty `text` and carries a `file` attachment. It bypasses text command matching. Incoming files use the same replay protection and history admission as other private messages.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
bot.handle(async (ctx) => {
|
|
159
|
+
const attachment = ctx.input.file;
|
|
160
|
+
if (!attachment) return;
|
|
161
|
+
|
|
162
|
+
const { file, error } = await attachment.download();
|
|
163
|
+
if (error !== null) {
|
|
164
|
+
await ctx.reply(`Unable to read the attachment (${error.code}).`);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
await ctx.reply(`Received ${file.name} (${file.size} bytes).`);
|
|
168
|
+
});
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
`FileAttachment` exposes the sender's URL, MIME type, encrypted SHA-256 (`x`), optional plaintext SHA-256 (`ox`), optional encrypted and plaintext byte counts, and an optional filename. These values describe the attachment as sent. Admitted files are also available on `Message.file` in receipt observers and retained history and on `Input.file` in a private thread. Download after the message is admitted, for example in `handle()` or from retained history.
|
|
172
|
+
|
|
173
|
+
`download()` resolves to `{ file, error: null }` or `{ file: null, error }`. The returned standard `File` supports `stream()` and `arrayBuffer()`. Its name defaults to the verified plaintext SHA-256 when the message has no usable filename. Errors have a `code`, a message, and an optional HTTP `status`. Codes cover download failure, integrity checks, decryption, storage and attempts to download outside admitted history.
|
|
174
|
+
|
|
175
|
+
Use `attachment.mimeType` when setting a `Content-Type` header or parsing the file with case-sensitive MIME parameters such as a multipart boundary. The standard `File` constructor lowercases `file.type`, including parameter values. [File API constructor](https://w3c.github.io/FileAPI/#file-constructor)
|
|
176
|
+
|
|
177
|
+
Downloads use the configured Blossom server origins and additional `blossomDownloadOrigins`. Redirects and fallback URLs must follow the same origin rules. If a source times out or returns ciphertext that fails verification, Chirli tries the next fallback URL. The network budget is 60 seconds, with each source receiving a share of the remaining time. The SDK buffers the attachment in memory without a fixed download size limit. Applications decide whether to call `download()`. The optional size fields are sender declarations and are verified after fetching. Chirli checks the encrypted hash, authenticates and decrypts with AES-GCM, then checks the plaintext hash and size when present. Verified plaintext is saved under the account's public key in `attachmentDirectory`, using the computed hash as its filename. A verified cache entry can be reused for the same sender and encryption metadata. Files on disk are plaintext even when `storageKey` protects the message database.
|
|
178
|
+
|
|
179
|
+
### Reply with a private or public file
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
await ctx.replyFile(bytes, { mimeType: "image/png", name: "report.png" });
|
|
183
|
+
await bot.replyFile(event, bytes, { mimeType: "image/png" }); // Outside the handler.
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`bot.replyFile` takes the same original `ctx.input.event` as `bot.reply`, not an event ID. Both forms return the normal send result. The anchor decides the visibility:
|
|
187
|
+
|
|
188
|
+
- Authenticated kind-14 or kind-15 DM: encrypt the bytes and send a kind-15 DM with a reference to the triggering rumor. The optional filename is inside the encrypted message.
|
|
189
|
+
- Signed kind 1/1111: **upload the supplied bytes as-is and publicly post the URL**. The reply is kind 1111 with the same root, parent and relay routing as `reply()`, plus an `imeta` tag. The DM filename option is ignored on this path. Only use this form with bytes you intend to publish.
|
|
190
|
+
|
|
191
|
+
For a new top-level public note rather than a reply, `uploadFile()` supplies the blob metadata; Chirli does not create the kind-1 note.
|
|
192
|
+
|
|
193
|
+
### Replies and references
|
|
194
|
+
|
|
195
|
+
To reference an earlier DM explicitly, pass its ID:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
await ctx.reply("Got it", { replyTo: ctx.input.id }); // Within a DM handler.
|
|
199
|
+
await bot.send(peerPubkey, "Follow-up", { replyTo: earlierMessage.id });
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`replyTo` is the lowercase hex private message ID. The SDK writes it as an `e` tag inside the encrypted message. Stored private `Message` objects include the optional parent ID as `message.replyTo`. Omit the option for a plain DM. Public replies instead reference the triggering note/comment automatically and do not accept DM options.
|
|
203
|
+
|
|
204
|
+
`bot.getMessage(id)` looks across the Bot's local private conversations and returns `undefined` if no message is stored. It does not fetch from relays. Use `ctx.thread()` to load context relative to the current input in a shared handler.
|
|
205
|
+
|
|
206
|
+
### Reactions
|
|
207
|
+
|
|
208
|
+
Use `ctx.react('👍')` to react to the current input, or pass the original event to `bot.react(event, '👍')`. The Bot method takes an event, not an ID. Omit the reaction string to send `+` (like). Pass a Unicode emoji or other nonblank reaction text; custom image emoji are not supported.
|
|
209
|
+
|
|
210
|
+
- For an authenticated DM, the reaction is a kind-7 rumor inside an encrypted DM envelope and uses the private outbox.
|
|
211
|
+
- For a signed public note or comment, the reaction is a public [NIP-25](https://nips.nostr.com/25) kind-7 event written through the durable public outbox. It tags the target event and author; kind-1111 targets also get a `k` tag.
|
|
212
|
+
|
|
213
|
+
Both methods return `{id, status}` with the same relay acceptance semantics as `send()`. Incoming reactions are ignored; reactions do not enter private text history or trigger handlers. See [delayed actions](#replies-and-context-after-a-handler) for what the Bot method verifies.
|
|
214
|
+
|
|
215
|
+
### Delivery and retries
|
|
216
|
+
|
|
217
|
+
Discovery, signing and pre-commit persistence errors reject. Once committed, network failure retains exact envelopes, reports through `onError`, and returns pending status. At least one relay ACK per recipient/self envelope is needed; it does not prove delivery or reading. A new send call creates a new logical message.
|
|
218
|
+
|
|
219
|
+
### Local history
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
const page = bot.dmHistory(peerPubkey, { limit: 20 });
|
|
223
|
+
if (page.nextCursor) {
|
|
224
|
+
const older = bot.dmHistory(peerPubkey, { cursor: page.nextCursor });
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
History is synchronous local storage access: newest timestamp first, then ascending ID. Default limit is 30, capped at 100. Each page includes `messages`, optional `nextCursor`, `coverage: 'local-only'`, and `complete: false`. The current incoming message and outgoing replies may be present; select context explicitly.
|
|
229
|
+
|
|
230
|
+
## Private history inspection and sessions
|
|
231
|
+
|
|
232
|
+
| Method | Result |
|
|
233
|
+
| --- | --- |
|
|
234
|
+
| `getMessage(id)` | A stored private message, or undefined |
|
|
235
|
+
| `getMessageState(id)` | Diagnostic status of a stored private message, or undefined |
|
|
236
|
+
| `listMessages({state?,limit?,cursor?})` | `{entries,nextCursor?}`, ordered timestamp/ID ascending |
|
|
237
|
+
| `await getSession(peer)` | Read the saved session from the configured backend |
|
|
238
|
+
| `await setSession(peer, value)` | Replace the saved snapshot in the configured backend |
|
|
239
|
+
|
|
240
|
+
Message list limits are 1..100, default 30. These APIs describe retained private history, not the internal set of claimed IDs. A DM short-circuited by middleware may have a durable ID claim without a history record. Status values never trigger retries.
|
|
241
|
+
|
|
242
|
+
Arbitrary external effects and session saves are not atomic; applications own idempotency.
|
|
243
|
+
|
|
244
|
+
## Bot middleware
|
|
245
|
+
|
|
246
|
+
Every handler has a conversation-scoped `ctx.session` with `getItem`, `setItem`, `removeItem` and `clear`. See [conversation sessions](SESSIONS.md) for defaults, commit behavior, and a complete custom storage example.
|
|
247
|
+
|
|
248
|
+
| Method | Behavior |
|
|
249
|
+
| --- | --- |
|
|
250
|
+
| `use(fn)` | Append middleware before message routing |
|
|
251
|
+
| `command(definition, fn, options?)` | Register a command with optional scopes and an optional typed argument schema |
|
|
252
|
+
| `handle(fn)` | Register the handler for messages with no matching command |
|
|
253
|
+
| `catch(observer)` | Observe session/middleware failures without consuming them |
|
|
254
|
+
| `getCommandDefinitions()` | Detached snapshots of this Bot's active definitions |
|
|
255
|
+
|
|
256
|
+
Use `bot.use()` to register Koa-style middleware. Each layer receives the same `ctx` and runs in registration order before routing. Call `next()` at most once; returning without it stops routing.
|
|
257
|
+
|
|
258
|
+
Routing calls the first matching command with `(ctx, args)`. If none matches, it calls the handler registered with `handle(ctx => …)`. Authorization denial for a matching command ends routing. Both kinds of handler use the same context: `input`, `sender`, `conversation`, `session`, `reply`, `replyFile`, `react` and `thread`.
|
|
259
|
+
|
|
260
|
+
When args is a Zod 4 object, TypeScript infers its validated output in a separate handler-only ctx.args and the existing second handler parameter. The middleware context is not mutated; its property descriptors, methods and shared session are retained on the handler view. Ordinary middleware/fallback Context has no args. Required values are present, optional values include `undefined`, and enum values use the declared choices. For a definition stored in a separate variable, use `as const satisfies BotCommandDefinition` to preserve its literal types. A dynamic definition exposes unknown argument values until narrowed.
|
|
261
|
+
|
|
262
|
+
The published `d` equals the command name; custom `id` and the old string shorthand are rejected. Omit `scopes` to use `["kind:14", "kind:1", "kind:1111"]`. An explicit list replaces the defaults and must contain at least one supported kind. Duplicate kinds are rejected. Public kinds require `publicInbox.relays`. Kind 15 files go through middleware and `handle()` because their content is an attachment URL. `authorize(ctx, invocation)` controls execution independently of public metadata.
|
|
263
|
+
|
|
264
|
+
`ctx.input` and `await ctx.thread({limit})` work across private and public input. `ctx.reply()` and `ctx.react()` stay encrypted for private input and publish kind 1111 and kind 7, respectively, for public input. Use Bot methods for receipt observation and local private history inspection. See [public inputs and threads](PUBLIC.md) for explicit inbox configuration, target rules and coverage limits.
|
|
265
|
+
|
|
266
|
+
Session load, middleware, fallback and session save share one error boundary. `catch()` observes failures without reopening the ID, and observer failures do not replace the original error. Session writes are buffered and commit when middleware returns successfully, even after an intentional short-circuit; an uncaught exception skips the session commit.
|
|
267
|
+
|
|
268
|
+
Omit a command from the next startup registry to withdraw it automatically on restart. Closing the Bot preserves the published catalog until that reconciliation. Runtime additions remain supported; runtime removal is not exposed.
|
|
269
|
+
|
|
270
|
+
## Public commands
|
|
271
|
+
|
|
272
|
+
All command definitions are public on configured write relays. Register the complete local set before startup. Observed remote commands absent locally are withdrawn with kind 5; no separate executor-list event is published. User-installed kind 10992 lists are untouched.
|
|
273
|
+
|
|
274
|
+
| Method | Behavior |
|
|
275
|
+
| --- | --- |
|
|
276
|
+
| `syncCommands()` | Reconcile own author-scoped definitions on write relays; return net added/updated/removed IDs across the whole coalesced call |
|
|
277
|
+
| `discoverCommands({authors,relays,ids?,limit?})` | Read and verify author-scoped kind 31992 definitions and kind 5 withdrawals; optional ids narrows definitions only |
|
|
278
|
+
|
|
279
|
+
Command discovery is read-only and returns a bounded relay snapshot with `complete: false`. Neither discovery nor scopes grant execution permission. See [command syntax, schemas and lifecycle](NIP-CD.md).
|
|
280
|
+
|
|
281
|
+
## Advanced integrations
|
|
282
|
+
|
|
283
|
+
`await receive(event, 'history' | 'live', {relay}?)` is the verified custom-intake boundary. It returns `true` for a newly claimed eligible DM or public input, or a newly stored own DM copy. An ID claim does not imply that a handler ran or that a payload was stored. Local and remote signers use the same asynchronous path. For DMs, the transport source is diagnostic: the authenticated rumor timestamp and first activation determine eligibility. Classify public source truthfully: old public history presented as live can execute commands.
|
|
284
|
+
|
|
285
|
+
Custom `Transport` supplies `query`, `subscribe`, `publish` and `close`. Custom subscription readiness retains its existing contract. Direct built-in Transport subscriptions and bounded queries require actual EOSE; SDK-owned long-lived inboxes alone permit the local read-window fallback described in the relay reference. Physical socket health is independent of either completion signal. The built-in transport uses nostr-tools for pooled physical connections, REQ, EOSE timers, keepalive and ACK tracking, with bounded connect/EOSE/ACK/AUTH operations; `InboxSubscription` owns reconnect and recovery. See [relays](RELAYS.md) and [recovery](RECOVERY.md).
|
|
286
|
+
|
|
287
|
+
`MessageStorage` implements `insert(account, entry)`, `query(account, options)` and `updateState(account, id, state)`. Entries include encoded payloads and diagnostic state. `sqliteMessageStorage(path)` supplies the default indexed backend. Bot creates and closes its default instance; supplied instances remain application-owned. Internal outbox, keys and metadata always use the `database` path. See [storage](STORAGE.md) for query and failure semantics.
|
|
288
|
+
|
|
289
|
+
`refreshPeer(pubkey)`, `encryptionKeys()` and `rotateEncryptionKey()` expose peer refresh and public key-custody operations. See [keys](KEYS.md) for retention, own-declaration conflicts and mode changes.
|
|
290
|
+
|
|
291
|
+
Exported `RelayError`, `SignerError`, `StorageEncryptionError` and `Nip4eCompatibilityError` distinguish operational failures. Relay diagnostics sanitize URLs/reasons; application error observers may still see sensitive business context. Optional timing observers cannot alter transport success. See [live diagnostics](https://github.com/CodyTseng/chirli/blob/main/examples/live/README.md#diagnose-slow-replies).
|
|
292
|
+
|
|
293
|
+
Command removal is expressed by the next startup registry, not a runtime method. `syncCommands()` returns only `added`, `updated`, `removed` and optionally waits/retries automatic synchronization; normal startup and running changes require no manual call. Startup performs broad author-only kind 31992 reads per write relay, without `#d` or remote kind 5 queries. Discovery independently reads 31992 plus kind 5, adding `#d` only when `ids` is supplied, and returns no index result field. Protocol-level `CommandDefinition.id` still denotes an external event's actual `d`, separate from its event hash. See [upgrade details](NIP-CD.md#upgrade-behavior).
|
|
294
|
+
|
|
295
|
+
## Optional official components
|
|
296
|
+
|
|
297
|
+
`allowlist(pubkeys: readonly string[])` returns ordinary middleware. Register `bot.use(allowlist(pubkeys))` before middleware whose effects need protection. It validates and snapshots lowercase hex account keys, checks the verified input author, and calls `next()` only for listed senders. `allowlist([])` blocks every external input from routing. The ID is already claimed; the middleware does not run on public history or outgoing self copies. [Sender authorization](ACCESS.md)
|
|
298
|
+
|
|
299
|
+
`requestTiming({onTiming})` returns ordinary `bot.use()` middleware. Register it before the processing middleware you want to measure. `RequestTiming` is a frozen object containing only readonly `durationMs:number` (monotonic elapsed milliseconds) and `outcome:'success'|'failure'`. `RequestTimingObserver` may return void or a Promise; synchronous exceptions and rejected observer promises are isolated, and the observer is not awaited. Successful processing stays successful, original handler errors stay the same errors and do not trigger a retry. No context, body, sender, event ID, route inferred from text, credentials or raw error is passed to telemetry. There is no default logger.
|
|
300
|
+
|
|
301
|
+
Timing covers the downstream middleware/command/fallback chain, including reply operations it awaits. It excludes work before this middleware, envelope verification/persistence, queue wait and session persistence after dispatch; a subsequent session-commit error is outside the measured chain outcome. It is neither end-to-end message latency nor a delivery measurement. No route hook or extra framework dependency is introduced.
|
|
302
|
+
|
|
303
|
+
## Replies and context after a handler
|
|
304
|
+
|
|
305
|
+
`bot.reply(event,text,options?)`, `bot.replyFile(event,bytes,options?)`, `bot.react(event,reaction?)` and `bot.thread(event,options?)` accept the original `ctx.input.event`: a signed kind 1/1111 Event or an authenticated decrypted kind 14 or 15 Rumor. No ID/string, outer gift wrap, context wrapper or token overload is accepted. They use the same routing and visibility as their handler counterparts. Private `replyTo` stays optional and is not inserted implicitly. Public replies reject nonempty DM send options.
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
// jobs is an application-owned queue; protect plaintext DM events in its storage.
|
|
309
|
+
bot.command(
|
|
310
|
+
{ command: "work", scopes: ["kind:14", "kind:1", "kind:1111"] },
|
|
311
|
+
async (ctx) => {
|
|
312
|
+
await jobs.add(structuredClone(ctx.input.event));
|
|
313
|
+
},
|
|
314
|
+
);
|
|
315
|
+
|
|
316
|
+
// After the handler finishes, with this Bot started and its account store available:
|
|
317
|
+
async function processJob(event: Event | Rumor) {
|
|
318
|
+
const prior = await bot.thread(event, { limit: 30 });
|
|
319
|
+
const text = await applicationProcessor(prior.entries);
|
|
320
|
+
return bot.reply(event, text);
|
|
321
|
+
}
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
The application supplies `jobs` and `applicationProcessor`; Chirli does not schedule or retain jobs. Import `Rumor` from `chirli` and `Event` from `nostr-tools`. Run `npm run example:async-reply` for a fully offline three-kind example.
|
|
325
|
+
|
|
326
|
+
Public events are cloned and independently reverified on every call, including IDs, signatures, eligible kind and thread structure. A retained full signed event works after completion/restart. The SDK stores no public input body or source relay for delayed calls. Delayed replies and reactions use configured write relays only; immediate handler calls can also use the configured inbox relay that delivered the input. Neither path trusts relay hints from tags. Thread queries use the configured public inbox. The public inbox must be configured.
|
|
327
|
+
|
|
328
|
+
A rumor has no standalone signature. The SDK requires an exact match with the current account/mode's persisted authenticated incoming DM record: hash, canonical fields/tags, sender, recipient, private conversation, text, timestamp and reply reference. Missing records, outgoing self copies, other accounts, changed rumors and outer envelopes are rejected. Reopen with the same signer, database, message backend, mode and any storage key; retaining a rumor alone cannot reconstruct its authentication. DM thread context remains anchored to the saved trigger and excludes later conversation entries.
|
|
329
|
+
|
|
330
|
+
Calls snapshot the event before asynchronous work, and handler methods retain separate internal snapshots. Mutating a caller object does not retarget an in-flight operation; supplying an already altered object fails verification. Calls require a started/open Bot instance and reject after close. These methods never invoke inbound handlers or provide a queue, token, idempotency key or exactly-once guarantee. Repeating a reply or reaction call creates a new outgoing action; use application idempotency and `flushOutbox()` for already pending sends. These are explicit application actions, not a second inbound authorization hook; allowlist is not an outbound ACL. Saved DM events contain plaintext and must not be logged or placed in an unprotected job store.
|
|
331
|
+
|
|
332
|
+
## Zod command arguments
|
|
333
|
+
|
|
334
|
+
Declare Zod 4 as an application dependency, import `z` from `zod`, and pass one object directly as `args`. No argument-builder API, second schema or per-command error callback is needed.
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
import { z } from "zod";
|
|
338
|
+
import { InvalidArgsError } from "chirli";
|
|
339
|
+
|
|
340
|
+
bot.use(async (ctx, next) => {
|
|
341
|
+
try {
|
|
342
|
+
await next();
|
|
343
|
+
} catch (error) {
|
|
344
|
+
if (!(error instanceof InvalidArgsError)) throw error;
|
|
345
|
+
await ctx.reply(`Usage error for /${error.command}`);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
bot.command(
|
|
350
|
+
{
|
|
351
|
+
command: "pick",
|
|
352
|
+
scopes: ["kind:14", "kind:1", "kind:1111"],
|
|
353
|
+
args: z.object({
|
|
354
|
+
user: z.string().meta({ label: "User", nipcdType: "pubkey" }),
|
|
355
|
+
count: z.bigint().min(1n).max(10n).meta({ label: "Count" }),
|
|
356
|
+
mode: z.enum(["short", "full"]).optional().meta({ label: "Mode" }),
|
|
357
|
+
}),
|
|
358
|
+
},
|
|
359
|
+
async (ctx, args) => {
|
|
360
|
+
// ctx.args and args are the same validated result; count is bigint.
|
|
361
|
+
await ctx.reply(`${ctx.args.mode ?? "short"}: ${args.count}`);
|
|
362
|
+
},
|
|
363
|
+
);
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
Field names and insertion order generate NIP-CD positional names/order. `optional()` sets required=false. Labels come from field `.meta({label})`, defaulting to the name. String → word, bigint → number, boolean → bool and string enum → enum/choices are inferred. Annotate strings with `nipcdType:'text'|'pubkey'|'event'|'relay'` when needed. For address use `.meta({nipcdType:'address'})` on `z.object({kind:z.number().int(),pubkey:z.string(),identifier:z.string(),relays:z.array(z.string())})`; decoder output matches the existing CommandAddress structure. Constraints/refinements run on decoded values, including asynchronous refinements.
|
|
367
|
+
|
|
368
|
+
The supported subset is deliberately bounded: top-level object with no __proto__ field, those scalar types, one optional wrapper per field, and the documented address object. Transforms/pipes, overwrites (including trim/normalize), coercion, defaults, nullable/union/lazy schemas, loose/catchall objects and arbitrary arrays/nested objects are rejected at registration. Validator exceptions are business errors, not normal schema rejection. Existing wire restrictions remain: unsigned protocol number tokens decode as bigint; required fields precede optional ones; at most one optional field; text is final. Zod min/max/refinements are local validation, not extra 31992 tags. No arbitrary transformations are inferred. Metadata should be attached to the field schema; use optional().meta(...) for optional fields.
|
|
369
|
+
|
|
370
|
+
Registration still automatically publishes the derived CommandArgument[] in the existing kind 31992 format; encode/decode/discovery and protocol CommandDefinition/CommandArgument stay unchanged. `getCommandDefinitions()` returns derived wire definitions, suitable for the pure `parseCommand()` helper. Old Bot args arrays must migrate to z.object; pure protocol helpers continue accepting wire arrays.
|
|
371
|
+
|
|
372
|
+
After middleware, routing first verifies command/target/scopes, then decodes and validates. A matched command's missing/invalid/extra arguments or Zod rejection raises `InvalidArgsError` with command, category (`decode` or `validation`) and bounded safe issues containing only code and registered field path. Submitted values, custom issue messages, raw decoder reasons and arbitrary custom paths are omitted. It never falls through to plain handling. Middleware may catch around await next(); otherwise bot.catch observes it once. With neither handler, it completes silently without an automatic response or retry. An uncaught framework InvalidArgsError skips the session commit; middleware that catches and returns successfully can commit its intentional session writes. The exact framework-generated error is handled separately from application-created errors, which are reported as ordinary failures. Neither path reruns the input.
|
|
373
|
+
|
|
374
|
+
If a command uses args-dependent `authorize`, malformed input is silently consumed: no validation-error callback is exposed because invalid arguments cannot authorize an error response. Validator exceptions before authorization are retained internally until middleware unwinds, then reported unchanged to operational `onError`. They bypass middleware catch and bot.catch, cannot authorize an error reply, and do not commit sessions. Validators without authorize and other business errors retain existing error-chain semantics. For valid data authorize receives the validated invocation.args before the business handler. No new response-authorization or per-command error callback is introduced. Wrong targets/scopes and early middleware stops never generate a command-argument error. Public initial admission remains restricted to known, genuinely targeted and scoped invocations; historical/repeated work does not replay error handlers.
|
|
375
|
+
|
|
376
|
+
Official requestTiming also reports failure for a validator exception deferred until after middleware because command authorization has not run. Its internal signal contains only failure state, without exposing the original exception or changing next() behavior. Operational `onError` observes that failure; no callback is retried.
|
|
377
|
+
|
|
378
|
+
### Command synchronization result across rounds
|
|
379
|
+
|
|
380
|
+
Concurrent syncCommands calls share one in-flight promise. If registrations change during reconciliation or public-subscription EOSE, it repeats until the current registry is synchronized and returns combined added/updated/removed IDs across every completed round of that promise, including rounds before a caller joined it. Each ID appears at most once, in one category, ordered by its first observed change. Added then updated remains added; added then removed disappears from the net result; updated then removed becomes removed; removed then re-added becomes updated. Updated means a previously present coordinate changed during this operation and ends present, even if its original content was restored. These are net presence deltas from the low-level observed per-round differences, not a global relay archive/content diff. The low-level journal, signed event IDs, ACK requirements and per-round reconciliation are unchanged. Failure/cancellation rejects instead of returning partial results; already published durable work is not rolled back.
|
|
381
|
+
|
|
382
|
+
A rejected initial public-subscription read is not readiness. Retrying the same kinds can create a fresh subscription; configured automatic reconnect can also recover its managed subscription. Stale failed attempts cannot close a newer subscription, and stop fences late readiness callbacks.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# NIP-17 and NIP-4E interoperability
|
|
2
|
+
|
|
3
|
+
Chirli receives both standard NIP-17 and the PsstPsst NIP-4E profile in either Bot mode. Choose the mode that determines how your Bot sends to extension-capable peers.
|
|
4
|
+
|
|
5
|
+
| Bot mode | Messaging key for extension peers |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| `nip17` (default) | The account identity key |
|
|
8
|
+
| `nip4e` | A separate key held in the local keyring |
|
|
9
|
+
|
|
10
|
+
## Key selection and envelopes
|
|
11
|
+
|
|
12
|
+
At startup, the Bot publishes its inbox relays (kind `10050`) and, when applicable, its messaging key (kind `10044`). It verifies peer declarations and can also learn a peer's messaging key from an authenticated incoming seal. See [relay routing](RELAYS.md) for discovery, fallback and caching.
|
|
13
|
+
|
|
14
|
+
- **Standard peer.** The Bot uses an empty-tag seal, a randomized seal timestamp and identity-key NIP-44, including when the Bot is in split-key mode.
|
|
15
|
+
- **Extension peer.** The Bot uses the first `n` seal tag and the message timestamp. Both encryption layers target the peer's verified messaging key.
|
|
16
|
+
- **Incoming messages.** The Bot can try the identity key and held split keys. It verifies the wrap, seal, message hash, author and one-to-one routing before exposing text.
|
|
17
|
+
|
|
18
|
+
Public giftwrap routing uses the recipient's stable identity key. Self copies use the Bot's own messaging profile. A standard-mode Bot can still decrypt messages for split keys it retained from an earlier configuration.
|
|
19
|
+
|
|
20
|
+
## Compatibility and key custody
|
|
21
|
+
|
|
22
|
+
`nip4eCompatibility: false` suppresses the identity-key `10044` announcement in NIP-17 mode. Both modes still receive both supported formats. Split mode announces its current split key.
|
|
23
|
+
|
|
24
|
+
A valid declaration or authenticated seal is evidence that a peer supports the extension. Metadata is limited to what the configured relays and local storage have observed. If another device publishes a conflicting key, use the [key migration procedure](KEYS.md#explicit-migration-and-upgrade).
|
|
25
|
+
|
|
26
|
+
Use a persistent database and protect its [keyring](KEYS.md#durable-custody-and-failure-recovery). Signing credentials remain in the [signer](SIGNERS.md). Neither profile provides forward secrecy.
|
|
27
|
+
|
|
28
|
+
## References and example
|
|
29
|
+
|
|
30
|
+
Chirli's extension behavior follows the [PsstPsst profile](https://psstpsst.chat/docs/private-messages/) and the [NIP-4E draft](https://github.com/nostr-protocol/nips/pull/1647). The standard envelope uses [NIP-17](https://github.com/nostr-protocol/nips/blob/master/17.md), [NIP-59](https://github.com/nostr-protocol/nips/blob/master/59.md) and [NIP-44](https://github.com/nostr-protocol/nips/blob/master/44.md).
|
|
31
|
+
|
|
32
|
+
Run `npm run example:interop` after building for an offline mixed-mode command and reply. The [contributor guide](../CONTRIBUTING.md) describes the optional interop fixtures and tests.
|
package/docs/KEYS.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Messaging keys, rotation and migration
|
|
2
|
+
|
|
3
|
+
Chirli uses the account identity key in `nip17` mode by default. Set `mode: 'nip4e'` to use a separate messaging key. Both modes can receive both supported envelope formats. See [interoperability](INTEROPERABILITY.md) for key selection on the wire.
|
|
4
|
+
|
|
5
|
+
## Configuration and lifecycle
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
const day = 24 * 60 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
const bot = new Bot({
|
|
11
|
+
signer,
|
|
12
|
+
mode: "nip4e",
|
|
13
|
+
database: "./chirli.sqlite",
|
|
14
|
+
storageKey,
|
|
15
|
+
keyRotation: {
|
|
16
|
+
intervalMs: 30 * day,
|
|
17
|
+
retainLegacyKeys: 5,
|
|
18
|
+
legacyMaxAgeMs: 90 * day,
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
await bot.start();
|
|
23
|
+
const status = bot.encryptionKeys();
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
| Option or method | Behavior |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| `keyRotation` | Enables automatic rotation in split mode. Omit it for manual rotation only. |
|
|
29
|
+
| `intervalMs` | Time since the active key was activated. Minimum 1,000 ms. |
|
|
30
|
+
| `retainLegacyKeys` | Number of retired keys to keep. Default 5, range 1–100. |
|
|
31
|
+
| `legacyMaxAgeMs` | Optional age limit for retired keys. Minimum 1,000 ms. |
|
|
32
|
+
| `await bot.rotateEncryptionKey()` | Rotate the split key explicitly. |
|
|
33
|
+
| `bot.encryptionKeys()` | Inspect public keys, timestamps and pending rotation status. |
|
|
34
|
+
|
|
35
|
+
Startup performs at most one overdue rotation. Future rotations are scheduled while the Bot runs. Stop and close cancel timers and wait for in-flight key work. The account signing key stays with the [signer](SIGNERS.md).
|
|
36
|
+
|
|
37
|
+
## Durable custody and failure recovery
|
|
38
|
+
|
|
39
|
+
The account keyring lives in the internal database and is shared across modes. It holds split secrets, activation and retirement metadata, and any pending signed key declaration. `storageKey` encrypts the payloads. Preserve the database and original key across restarts.
|
|
40
|
+
|
|
41
|
+
Rotation checks the latest observed authenticated own `10044`, generates a candidate, and stores the candidate and exact signed declaration before publication. The new key can then decrypt incoming messages. The Bot activates it for outgoing messages after the declaration is accepted in the configured write and DM sets and the activation is saved.
|
|
42
|
+
|
|
43
|
+
An uncertain or failed publication leaves the old outgoing key active and the candidate available for retry. Startup and new sends resume the staged declaration. Pending message envelopes retain their original keys, ciphertext, IDs and relay targets through rotation.
|
|
44
|
+
|
|
45
|
+
## Legacy count and expiration
|
|
46
|
+
|
|
47
|
+
Retired keys let the Bot decrypt messages from peers using stale routing data. Pruning runs after a successful split-key rotation. It applies the optional age limit first, then the count limit. The key just retired by that rotation remains available.
|
|
48
|
+
|
|
49
|
+
An envelope addressed only to an evicted key can no longer be decrypted. Local text already decrypted remains readable. SQLite pages, WAL files and backups may retain older data. See [security](../SECURITY.md) for storage and credential boundaries.
|
|
50
|
+
|
|
51
|
+
## Explicit migration and upgrade
|
|
52
|
+
|
|
53
|
+
When using a different mode with the same account, close the old Bot and keep its database and storage key. If the account already advertises a different key, acknowledge the exact locally held key in `announce()` before starting.
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
const split = new Bot({ mode: "nip4e", signer, database, storageKey, relays });
|
|
57
|
+
await split.announce({ replaceEncryptionKey: await signer.getPublicKey() });
|
|
58
|
+
await split.start();
|
|
59
|
+
const previousSplitKey = split.encryptionKeys().currentPublicKey;
|
|
60
|
+
await split.close();
|
|
61
|
+
|
|
62
|
+
const standard = new Bot({ signer, database, storageKey, relays });
|
|
63
|
+
await standard.announce({ replaceEncryptionKey: previousSplitKey });
|
|
64
|
+
await standard.start();
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A replacement must match the latest verified declaration and a locally available decryption key. Conflicts raise `Nip4eCompatibilityError`. Finish pending key publication in its original mode before switching. History, inbox, outbox and sessions remain mode-scoped even though the keyring is shared.
|
|
68
|
+
|
|
69
|
+
## Automatic same-identity key synchronization
|
|
70
|
+
|
|
71
|
+
In split mode, a Bot missing its advertised key can request it from another device using the same signing identity. The requester sends signed kind `4454`. A device holding the key can return an encrypted kind `4455` response tied to that request. The Bot checks the author, request binding and key against the latest observed declaration, then stores the key before adopting it.
|
|
72
|
+
|
|
73
|
+
Authorization relies on the account signature. Requests can grant access to held split keys, so give signing permission accordingly. Identity signing secrets are never transferred. A PsstPsst device may require approval in its own UI.
|
|
74
|
+
|
|
75
|
+
Set `keySync: false` to disable requests and responses. The default request timeout is 30 seconds. A timeout or unavailable peer leaves held keys and pending rotation state intact. Run `npm run example:key-sync` after building to try two disposable in-memory devices.
|
package/docs/NIP-CD.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# NIP-CD command definitions
|
|
2
|
+
|
|
3
|
+
Command definitions and invocation syntax follow the [NIP-CD draft](https://github.com/nostr-protocol/nips/blob/master/CD.md). Each command has its own signed kind **31992** event and a stable `(31992, executor pubkey, d)` coordinate.
|
|
4
|
+
|
|
5
|
+
Kind **10992** is a user’s installed-command list. Chirli neither publishes it nor treats it as an executor-owned registry.
|
|
6
|
+
|
|
7
|
+
## Register the complete set before starting
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
|
|
12
|
+
const bot = new Bot({ signer });
|
|
13
|
+
bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
|
|
14
|
+
await ctx.reply("pong");
|
|
15
|
+
});
|
|
16
|
+
bot.command(
|
|
17
|
+
{
|
|
18
|
+
command: "sum",
|
|
19
|
+
scopes: ["kind:14"],
|
|
20
|
+
title: "Sum",
|
|
21
|
+
description: "Add two integers.",
|
|
22
|
+
args: z.object({
|
|
23
|
+
left: z.bigint().meta({ label: "Left" }),
|
|
24
|
+
right: z.bigint().meta({ label: "Right" }),
|
|
25
|
+
}),
|
|
26
|
+
},
|
|
27
|
+
async (ctx, { left, right }) => {
|
|
28
|
+
await ctx.reply(String(left + right));
|
|
29
|
+
},
|
|
30
|
+
{ authorize: (ctx) => allowedSenders.has(ctx.sender) },
|
|
31
|
+
);
|
|
32
|
+
await bot.start();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Command metadata is public and goes to `writeRelays`. The `authorize` callback controls execution. Register the complete command set before startup. Use one registry owner per account so different processes do not withdraw each other's commands.
|
|
36
|
+
|
|
37
|
+
## Automatic startup reconciliation
|
|
38
|
+
|
|
39
|
+
Before business subscriptions begin, startup:
|
|
40
|
+
|
|
41
|
+
1. Reads the executor's complete kind 31992 snapshot from every configured write relay, scoped to its identity author. This is one broad logical scan per relay, with bounded paging when necessary, never one query per command. No `#d` filter or kind 5 query is used for startup reconciliation.
|
|
42
|
+
2. Compares that snapshot with the complete local registry, keeps unchanged definitions and publishes missing/changed definitions.
|
|
43
|
+
3. Publishes NIP-09 kind 5 coordinate withdrawals for definitions present remotely but absent locally, plus explicit removals and durable pending withdrawals.
|
|
44
|
+
|
|
45
|
+
No separate executor-list event is published. An empty Bot registry withdraws observed remote definitions; an ordinary Client does not claim registry ownership. Command registration and running additions synchronize automatically; there is no publication opt-in or manual setup step.
|
|
46
|
+
|
|
47
|
+
Startup requires successful reads and writes on every configured write relay. A failed or detectably incomplete scan blocks reconciliation. A relay may silently cap or omit results, so a completed bounded scan is not proof of globally complete history. Local confirmed cache entries alone never establish fresh remote presence or cause repeated withdrawals after a relay removes the event. Durable pending definitions/withdrawals are distinct from confirmed cache and retain their exact event IDs on retry.
|
|
48
|
+
|
|
49
|
+
Relays commonly remove the targeted definition after accepting kind 5. Reconciliation therefore does not fetch remote deletion history. Local tombstones are retained for retries and monotonic re-registration timestamps. Definitions, withdrawals and different relay replicas are not published atomically; partial failure can expose mixed snapshots.
|
|
50
|
+
|
|
51
|
+
## Runtime addition and restart reconciliation
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
bot.command({ command: "help", scopes: ["kind:14"] }, async (ctx) => {
|
|
55
|
+
await ctx.reply("Available commands…");
|
|
56
|
+
});
|
|
57
|
+
// Optional: await the automatic background synchronization before reading a snapshot.
|
|
58
|
+
await bot.syncCommands();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The published `d` is always the command name in `bot.command()`. Custom `id` arguments, even those matching the command name, are rejected. To remove a command, omit it from the next complete startup registry and restart with the same account and relays. A rename is removal of the old command plus registration of a new command at a different coordinate. If publication fails, `flushAnnouncements()` or `syncCommands()` can optionally await/retry the same automatic process.
|
|
62
|
+
|
|
63
|
+
`syncCommands()` returns added, updated and removed identifiers only; it is an optional wait/retry helper. Closing the Bot preserves public definitions and pending publication operations for restart, not pending handler work.
|
|
64
|
+
|
|
65
|
+
## Discovery
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
const snapshot = await bot.discoverCommands({
|
|
69
|
+
authors: [knownExecutorPubkey],
|
|
70
|
+
relays: discoveryRelays,
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Discovery independently queries author-scoped kind 31992 definitions and kind 5 withdrawals, verifies signatures and author binding, and selects the newest non-withdrawn coordinates. Optional `ids` adds `#d` only to the definition query; deletion queries stay author-scoped. No executor membership list filters results. The result is read-only and reports `coverage: 'relay-snapshot'` and `complete: false`.
|
|
75
|
+
|
|
76
|
+
Unlike startup reconciliation, discovery retains deletion verification because relays and cross-relay snapshots can contain stale definitions. Protocol helpers preserve an external definition's actual `d` (`CommandDefinition.id`) even if it differs from its trigger. This is distinct from the Nostr event's hash `event.id`. Bot registration accepts neither a custom `d` nor a custom event ID.
|
|
77
|
+
|
|
78
|
+
## Invocation and parsing
|
|
79
|
+
|
|
80
|
+
Invocations begin at content index zero:
|
|
81
|
+
|
|
82
|
+
```text
|
|
83
|
+
/<command>[@nostr:<npub>] [<arg>...] [<text>]
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The qualifier is optional. Both `@npub` and `@nostr:npub` target the executor's identity key.
|
|
87
|
+
|
|
88
|
+
- Registration uses one object form with optional scopes. To accept trailing text, declare an optional terminal `text` argument.
|
|
89
|
+
- A full definition supports positional `pubkey`, `event`, `address`, `relay`, `number`, `bool`, `enum`, `word` and `text` arguments. Numbers are parsed as `bigint`.
|
|
90
|
+
- A terminal `text` argument removes one separator and preserves the rest, including leading spaces and newlines.
|
|
91
|
+
- The first matching command owns the route. An unknown trigger, unselected target or scope mismatch can fall through to the DM `handle()`. Recognized, correctly targeted/scoped commands with invalid arguments never fall through. An authorization denial on the matched command stops routing.
|
|
92
|
+
|
|
93
|
+
## Scope rules
|
|
94
|
+
|
|
95
|
+
Bot publishes `kind:14`, `kind:1` and `kind:1111` by default. An explicit `scopes` list replaces the defaults and must include at least one supported kind. Duplicate kind scopes are rejected. Text command routing checks the published scopes against verified input. Kind 15 files go through middleware and `handle()` because their content is an attachment URL. Additional scopes narrow command matching:
|
|
96
|
+
|
|
97
|
+
| Scope | Checks |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `author:<pubkey>` | Verified sender identity |
|
|
100
|
+
| `relay:<url>` | The relay that actually supplied the message |
|
|
101
|
+
| `tag:<name>` | A nonempty value for that tag in the authenticated DM rumor or public event |
|
|
102
|
+
| `tag:<name>:<value>` | An exact tag value in the authenticated DM rumor or public event |
|
|
103
|
+
|
|
104
|
+
Scopes of the same type are alternatives. Different types must all match. Tag scopes are grouped by tag name. A configured relay alone does not establish message provenance. Bot rejects unsupported kind scopes. Public input additionally requires explicit inbox relays and an unambiguous target; see [PUBLIC.md](PUBLIC.md).
|
|
105
|
+
|
|
106
|
+
## Upgrade behavior
|
|
107
|
+
|
|
108
|
+
Replace `command('name', fn)` with `command({command:'name', scopes:['kind:14']}, fn)`; add an optional text argument schema if needed. Remove custom `id` from Bot registration code. Remove unwanted declarations from the next startup registry. On the next automatic reconciliation, old custom coordinates found in the relay snapshot are withdrawn and the name-derived coordinates are published. Existing foreign wire definitions remain decodable with their original identifiers.
|
|
109
|
+
|
|
110
|
+
The existing SQLite journal keys/schema are retained. Unsupported legacy executor-list events in command known/pending state and relay-announcement state are filtered out at load and never replayed. Supported pending definitions and kind 5 withdrawals retain their exact signed IDs. No remote legacy list is read, republished or automatically erased. Removed index exports/result fields are no longer part of the API.
|
|
111
|
+
|
|
112
|
+
Bot args are now a Zod 4 object; labels/types/order/required/enum choices generate the same protocol argument tags. The protocol CommandArgument structure and pure encode/decode/discovery APIs remain unchanged. See [supported schemas and terminal errors](API.md#zod-command-arguments).
|