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/PUBLIC.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Public notes, comments and private input
|
|
2
|
+
|
|
3
|
+
Chirli accepts authenticated kind 14 and kind 15 DMs and verified public kind 1/1111 commands. Applications still own message processing and authorization. There is no general event-adapter framework or AI dependency.
|
|
4
|
+
|
|
5
|
+
## Explicit registration and inbox
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
const bot = new Bot({
|
|
9
|
+
signer,
|
|
10
|
+
publicInbox: {
|
|
11
|
+
relays: ["wss://your-inbox.example", "wss://your-second-inbox.example"],
|
|
12
|
+
thread: { timeoutMs: 3000, maxEvents: 500, maxLookups: 16, maxDepth: 64 },
|
|
13
|
+
},
|
|
14
|
+
writeRelays: ["wss://your-write.example"],
|
|
15
|
+
});
|
|
16
|
+
bot.command(
|
|
17
|
+
{ command: "ping" },
|
|
18
|
+
async (ctx) => {
|
|
19
|
+
await ctx.reply("pong");
|
|
20
|
+
},
|
|
21
|
+
);
|
|
22
|
+
await bot.start();
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The example URLs are placeholders. Public inbox URLs must be chosen explicitly by the operator; no default public firehose opens. A public subscription selects only kinds declared by current commands, with a 500-event initial window per relay. Runtime additions update public subscriptions after command catalog synchronization. To remove commands, omit them from the next registry and restart; startup withdraws their definitions. DM subscription, metadata publication and automatic kind 31992 reconciliation retain their existing behavior.
|
|
26
|
+
|
|
27
|
+
Omitting `scopes` publishes `kind:14`, `kind:1` and `kind:1111`. An explicit list replaces the defaults and must contain at least one supported kind. Kind 15 files go through middleware and `handle()`. Duplicate or unsupported kind scopes are rejected. Same-type scopes are alternatives; different scope types combine. Scope checks use the authenticated rumor/public event and actual source relay, never configured-relay membership as proof of provenance. Registration/publication and routing use the same scopes.
|
|
28
|
+
|
|
29
|
+
Public invocation must start at content index zero. Either `/ping@npub...` or `/ping@nostr:npub...` explicitly selects the bot; no `p` tag is required. An unqualified `/ping` is accepted only when the distinct lowercase `p` targets consist solely of this bot. A conflicting qualifier remains rejected even with the bot's `p` tag. An ordinary structural reply or mention is never an invocation. These stricter public targeting rules are Chirli policy; NIP-CD itself permits multiple executors to match an unqualified invocation. Public `handle()`/middleware runs only for admitted registered invocations, not arbitrary notes. DM fallback behavior is unchanged.
|
|
30
|
+
|
|
31
|
+
Signatures, kind, structural references, source, invocation and scopes are checked before the SDK atomically claims the signed event ID. Own public events are ignored. Access middleware runs after the claim and receives a detached copy of the verified input. Commands can additionally use `authorize`.
|
|
32
|
+
|
|
33
|
+
## Shared context and privacy
|
|
34
|
+
|
|
35
|
+
`ctx.input` contains `{id,sender,createdAt,kind,text,event}`. `createdAt` is Nostr seconds. `event` is the authenticated decrypted kind 14 or 15 rumor for DMs, or the signature-verified raw public event. A kind-15 input also has `file` and empty `text`. [Receiving private files](API.md#receive-and-download-a-private-file) Anonymous gift-wrap keys are never exposed as the sender.
|
|
36
|
+
|
|
37
|
+
`ctx.reply(text)` encrypts a DM when the input is private. For public inputs it signs kind 1111 with uppercase root scope and lowercase direct parent references, including mixed legacy kind 1/comment ancestry. Only the root author and direct parent author are copied. Missing/malformed legacy roots cause an error instead of a guessed attachment. An explicit modern root is preserved as declared in the signed comment; this does not prove the root's availability or truthfulness. A relay ACK means relay acceptance, never delivery or reading.
|
|
38
|
+
|
|
39
|
+
`ctx.replyFile(bytes, options?)` follows the same kind-1111 threading rules. It publishes the file URL and `imeta`; the bytes are uploaded **without encryption** for public input. The same call on a DM instead uploads ciphertext and replies with a kind-15 DM. Use `bot.replyFile(ctx.input.event, bytes, options?)` for delayed replies.
|
|
40
|
+
|
|
41
|
+
`ctx.react(reaction?)` signs a public [NIP-25](https://nips.nostr.com/25) kind-7 reaction. It references the target ID with an `e` tag and the target author with a `p` tag; kind-1111 targets also have a `k` tag. Omitting the reaction sends `+` (like). For a private input the same call sends an encrypted kind-7 rumor.
|
|
42
|
+
|
|
43
|
+
Public replies and reactions use configured `writeRelays` plus the configured inbox relay that supplied the input. Untrusted relay hints in tags do not initiate contacts; automatic destination-author relay discovery is not implemented. DM send options are rejected for public replies.
|
|
44
|
+
|
|
45
|
+
`ctx.session` uses separate `public:` thread keys for public input. Default storage namespaces also separate it from private peer sessions. A custom session store receives those prefixed keys and must preserve their separation and account isolation. Legacy unmarked chains may have an intermediate declared root and consequently a different session key until the application chooses a canonical key. Sessions and external side effects are not atomic with business completion.
|
|
46
|
+
|
|
47
|
+
The handler context has the same fields and methods for both kinds of input. Use `ctx.input` for the current input and `ctx.thread()` for preceding context. `bot.getMessage`, `bot.dmHistory`, `bot.observe`, message listing/state and `bot.send` remain private-message APIs.
|
|
48
|
+
|
|
49
|
+
## Lazy ancestor context
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
bot.command(
|
|
53
|
+
{ command: "summarize", scopes: ["kind:14", "kind:1", "kind:1111"] },
|
|
54
|
+
async (ctx) => {
|
|
55
|
+
const result = await ctx.thread({ limit: 30 });
|
|
56
|
+
const reply = await applicationProcessor(result.entries, {
|
|
57
|
+
complete: result.complete,
|
|
58
|
+
});
|
|
59
|
+
await ctx.reply(reply);
|
|
60
|
+
},
|
|
61
|
+
);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
No history is sent anywhere automatically. `applicationProcessor` belongs to your application. The offline demo uses a deterministic mock.
|
|
65
|
+
|
|
66
|
+
`thread()` returns `{entries,complete,coverage,reason?}`. Entries have the same shape as `ctx.input`, ordered oldest ancestor to direct parent, excluding the trigger. Limits are 1..100, default 30.
|
|
67
|
+
|
|
68
|
+
- DMs use up to ten local 100-message pages from the current private conversation. Coverage is `local-conversation`, always `complete:false`/`local-only`; there is no relay archive claim. Equal-second entries use the local history ordering.
|
|
69
|
+
- Public input batches its known root: the root event, kind 1 `#e` and kind 1111 `#E`, plus coordinate `#a`/`#A` variants where applicable. Only the current ancestor path is selected, never siblings or descendants. Legacy marked and positional references are supported; marked mentions and embedded NIP-19 quotes are excluded from positional topology. Missing ancestors use bounded targeted lookups. Modern address parents with an exact event ID resolve that version.
|
|
70
|
+
- Missing ancestors, inconsistent roots, timeouts, query windows, cycles and entry/size/depth/lookup bounds produce incomplete results with a reason. Defaults: 3000 ms total, 500 verified events, 16 queries, 64 ancestor steps. The total timer returns without waiting for an unresponsive custom query; the Transport interface cannot abort acquired queries. Built-in transport operations retain their own finite budgets and are closed with owned resources. A complete ancestor chain means those signed references resolved within the window, not complete relay history or global availability.
|
|
71
|
+
|
|
72
|
+
## Claims and outgoing retries
|
|
73
|
+
|
|
74
|
+
The internal SQLite store claims eligible public IDs before middleware. Public input bodies, relay provenance and pending/failed callback work are not retained; the private `MessageStorage` is not involved. Eligible historical IDs are also claimed without running commands. Offline-gap commands received as history are not executed later as live duplicates.
|
|
75
|
+
|
|
76
|
+
Live attempts are serial per declared public root, and different roots can proceed concurrently. Returning early, failure or restart does not reopen a claim. A crash can interrupt an attempt or occur before its callback starts. Public replies and reactions use an independent outbox: after signing they are stored before publication, and `flushOutbox()` and reconnect retry the same signed event ID. Applications own any durable business jobs and idempotency.
|
|
77
|
+
|
|
78
|
+
## Command definitions and references
|
|
79
|
+
|
|
80
|
+
For a private command use `command({command:'ping',scopes:['kind:14']},handler)`. For trailing text declare `args:z.object({text:z.string().optional().meta({label:'Text',nipcdType:'text'})})`. Custom command identifiers are rejected; `d` is the command name. Renames are removal plus addition. Foreign protocol definitions retain their actual `d` values when decoded.
|
|
81
|
+
|
|
82
|
+
References: [NIP-22](https://nips.nostr.com/22), [NIP-CD draft](https://github.com/nostr-protocol/nips/blob/master/CD.md), and read-only review of Jumble's MIT-licensed structural/thread/routing patterns. No running Jumble device or public relay interoperability is covered by local tests.
|
|
83
|
+
|
|
84
|
+
## Application-owned delayed replies
|
|
85
|
+
|
|
86
|
+
Retain `ctx.input.event` to call `bot.reply(event,text)`, `bot.react(event,reaction?)` or `bot.thread(event,options)` after the handler finishes. Keep the full signed public event, not its ID. The SDK stores no incoming public body. Reverification is mandatory. A delayed reply or reaction uses configured write relays only; an immediate handler action can also use its configured source relay. Relay hints are never inferred from event tags. DM calls require the matching authenticated incoming record in the same account/mode store and protect the retained plaintext event. See [the shared API and offline example](API.md#replies-and-context-after-a-handler).
|
|
87
|
+
|
|
88
|
+
Public admission checks only a registered command head, verified target and scopes before enqueueing. NIP-CD argument decoding and Zod validation happen after middleware. This permits centralized invalid-argument handling without subscribing to arbitrary event handlers. History/replayed IDs still never run validation/error callbacks. An args-dependent authorize callback suppresses malformed-input error callbacks because no valid arguments exist to authorize a response. See [Zod arguments](API.md#zod-command-arguments).
|
package/docs/RECOVERY.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Reconnect and history recovery
|
|
2
|
+
|
|
3
|
+
The Bot manages one inbox subscription per DM relay. Each reconnects independently and can scan for missed DMs and outgoing self copies. Eligible incoming DMs recovered from a relay use the same middleware and handlers as live delivery, without retrying a previously claimed input.
|
|
4
|
+
|
|
5
|
+
## Defaults and configuration
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
const bot = new Bot({
|
|
9
|
+
signer,
|
|
10
|
+
reconnect: { maxDelayMs: 60_000, jitter: 0.2, stableResetMs: 30_000 },
|
|
11
|
+
recovery: { pageSize: 500, maxPages: 20, overlapSeconds: 176_400 },
|
|
12
|
+
});
|
|
13
|
+
await bot.start();
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
| Setting | Default behavior |
|
|
17
|
+
| --- | --- |
|
|
18
|
+
| Reconnect | Delay steps of 1, 2, 5, 10, 20, 30 and 60 seconds, with jitter and a 60-second cap |
|
|
19
|
+
| `reconnect.initialDelayMs` | Specifying it selects exponential backoff |
|
|
20
|
+
| `stableResetMs` | Reset failure counts after 30 seconds of an established connection |
|
|
21
|
+
| `recovery.pageSize` and `maxPages` | Query up to 500 events per page and 20 pages per pass |
|
|
22
|
+
| `recovery.overlapSeconds` | Two days and one hour to account for randomized giftwrap timestamps |
|
|
23
|
+
|
|
24
|
+
Set `reconnect: false` to disable automatic reconnect. Set `recovery: false` to skip extra history pages while keeping the inbox subscription's initial history.
|
|
25
|
+
|
|
26
|
+
## What a recovery pass does
|
|
27
|
+
|
|
28
|
+
When a relay has no checkpoint, its next scan starts at the Bot’s persisted first activation minus the configured overlap. Later passes start at that relay’s saved checkpoint minus the overlap. Scan bounds filter the outer giftwrap’s timestamp, not the inner DM timestamp. Each pass fixes its upper bound before querying; only a complete pass advances the checkpoint. Checkpoints are scoped to the account, mode and relay.
|
|
29
|
+
|
|
30
|
+
Pagination includes the oldest returned second in the next request. If a full page cannot move past that boundary, the pass reports `boundary-overflow`. Query failures, page limits and boundary overflow leave the checkpoint unchanged. A retry can read earlier pages again. Deduplication uses the decrypted message ID.
|
|
31
|
+
|
|
32
|
+
### Live messages and recovered history
|
|
33
|
+
|
|
34
|
+
The SDK saves the first DM activation time per bot public key and database before opening its DM inbox. It is reused on subsequent starts. After verification, the SDK discards both incoming DMs and outgoing self copies whose inner rumor timestamp is older than that time. A valid `ms` tag gives millisecond precision; when absent or unusable, a rumor in the same whole second as activation is eligible. Sender clocks can differ.
|
|
35
|
+
|
|
36
|
+
Once eligible, an incoming DM goes through the same ID claim, middleware and routing whether it arrived live, before EOSE, or in a catch-up query. Failed or denied inputs stay claimed. A later duplicate never reruns the handler. Eligible outgoing self copies can populate local history without middleware. Public command subscriptions keep their separate live/history rules.
|
|
37
|
+
|
|
38
|
+
## Trigger and inspect recovery
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
const results = await bot.syncHistory();
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Call `syncHistory()` on a running Bot. It returns one result per DM relay with its time window, page count and status:
|
|
45
|
+
|
|
46
|
+
| Status | Meaning |
|
|
47
|
+
| --- | --- |
|
|
48
|
+
| `window-complete` | The relay's bounded query window drained |
|
|
49
|
+
| `incomplete` | See `reason`: `page-limit`, `boundary-overflow` or `query-failed` |
|
|
50
|
+
| `aborted` | The pass was interrupted or its replica was unavailable |
|
|
51
|
+
| `disabled` | Additional recovery paging is disabled |
|
|
52
|
+
|
|
53
|
+
Concurrent calls share a relay's active pass. Local `bot.dmHistory()` always reports `coverage: 'local-only'` and `complete: false`. Recovery is bounded and requires the keys needed to decrypt each message. See [key retention](KEYS.md#legacy-count-and-expiration).
|
|
54
|
+
|
|
55
|
+
## Startup and retries
|
|
56
|
+
|
|
57
|
+
Startup waits for at least one inbox replica to finish its initial read window (real EOSE or the long-lived inbox fallback) and finish its initial recovery attempt. This initialization gate is separate from physical WebSocket connection health. An incomplete recovery can still leave the Bot ready. Reconnected subscriptions retry pending outbox envelopes with their original ciphertext, IDs and targets. The SDK retries that outgoing work on startup and reconnect, and the live runner also has a periodic [retry timer](https://github.com/CodyTseng/chirli/blob/main/examples/live/README.md).
|
|
58
|
+
|
|
59
|
+
An established replica's transient network failures get a 30-second recovery window before `onError()` reports one warning for the outage. Initial failures, explicit protocol rejections and history errors are reported immediately. `stop()` and `close()` cancel reconnect demand, delayed warnings and in-progress recovery. See [relays](RELAYS.md) for timeouts and diagnostics.
|
package/docs/RELAYS.md
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# Relay roles
|
|
2
|
+
|
|
3
|
+
Set each relay role independently. The common `relays` option supplies any role you leave unspecified.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
const bot = new Bot({
|
|
7
|
+
signer,
|
|
8
|
+
dmRelays: ["wss://inbox.example"],
|
|
9
|
+
readRelays: ["wss://read.example"],
|
|
10
|
+
writeRelays: ["wss://write.example"],
|
|
11
|
+
});
|
|
12
|
+
await bot.start();
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
| Role | Purpose | Default hosts |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| `dmRelays` | Subscribe to the inbox, recover history and provide delivery fallback | relay.psstpsst.chat, nos.lol, relay.ditto.pub |
|
|
18
|
+
| `readRelays` | Add relays for metadata discovery | nos.lol, relay.primal.net, relay.ditto.pub, offchain.pub |
|
|
19
|
+
| `writeRelays` | Publish commands and account metadata | Same as `readRelays` |
|
|
20
|
+
| `discoveryRelays` | Extra publication targets for public account lists | Same as `readRelays` and `writeRelays` |
|
|
21
|
+
|
|
22
|
+
Defaults are exported as `DEFAULT_DM_RELAYS`, `DEFAULT_READ_RELAYS`, `DEFAULT_WRITE_RELAYS` and `DEFAULT_DISCOVERY_RELAYS`. The DM and write lists must be nonempty. Pass `readRelays: []` or `discoveryRelays: []` to omit the respective role. Peer metadata lookup still queries the union of configured read, write and DM relays. The live examples map these roles to [environment variables](https://github.com/CodyTseng/chirli/blob/main/examples/live/README.md).
|
|
23
|
+
|
|
24
|
+
## Account announcements
|
|
25
|
+
|
|
26
|
+
Startup signs and publishes account metadata before opening the inbox.
|
|
27
|
+
|
|
28
|
+
| Kind | Published data | Targets |
|
|
29
|
+
| --- | --- | --- |
|
|
30
|
+
| `10044` | Messaging key | Write and DM relays |
|
|
31
|
+
| `10002` | Read and write relay roles | Write + discovery relays |
|
|
32
|
+
| `10050` | Inbox relay URLs | Write + discovery relays, plus DM relays |
|
|
33
|
+
| `10063` | Ordered Blossom server list | Write + discovery relays |
|
|
34
|
+
| `31992`, `5` | Command definitions and withdrawals | Write relays |
|
|
35
|
+
|
|
36
|
+
Each public list requires one positive ACK from the configured write relays. The inbox list also requires a DM ACK unless the two groups are identical. Discovery-only destinations are tried best-effort: they cannot satisfy a required ACK, do not block readiness, and are not queued for retry. URLs already covered by a required group are not tried again for discovery; discovery-only URLs are not advertised as read/write or inbox role tags. A failed required group does not stop other lists from being attempted. An unchanged configuration retries only unacknowledged groups with the original signed events. Key metadata keeps its existing separate write/DM ACK rules. Command synchronization requires successful queries and publication on every configured write relay. See [command synchronization](NIP-CD.md) and [messaging key configuration](KEYS.md).
|
|
37
|
+
|
|
38
|
+
## Readiness and delivery
|
|
39
|
+
|
|
40
|
+
- **Inbox startup.** One DM relay must finish its initial read window (real EOSE or the long-lived inbox fallback below) and finish its initial recovery attempt. Other replicas can continue reconnecting. If all initial attempts fail, startup rejects. See [recovery](RECOVERY.md).
|
|
41
|
+
- **Discovery.** Metadata queries combine successful relay snapshots. If every query fails, discovery reports an error. Results reflect only what those relays returned.
|
|
42
|
+
- **Delivery.** Each encrypted peer or self copy needs one positive ACK. Relay acceptance indicates that a relay accepted the event. A wholly unsuccessful bundle stays in the outbox. `flushOutbox()`, startup and reconnect reuse the original ciphertext, IDs and targets.
|
|
43
|
+
|
|
44
|
+
Peer delivery uses verified inbox metadata. The Bot falls back to its own DM relays when it has no usable peer inbox list. Self copies use the Bot's advertised inbox or its configured DM relays.
|
|
45
|
+
|
|
46
|
+
## Transport and diagnostics
|
|
47
|
+
|
|
48
|
+
The default WebSocket transport pools normalized relay URLs and shares NIP-42 authentication per connection. Specify overrides through `transportOptions`.
|
|
49
|
+
|
|
50
|
+
| Deadline | Default |
|
|
51
|
+
| --- | --- |
|
|
52
|
+
| `connectionTimeoutMs` | 5 seconds |
|
|
53
|
+
| `eoseTimeoutMs` | 25 seconds |
|
|
54
|
+
| `publishTimeoutMs` | 5 seconds |
|
|
55
|
+
| `authTimeoutMs` | 8 seconds |
|
|
56
|
+
| `idleTimeoutMs` | 30 seconds |
|
|
57
|
+
| `heartbeatIntervalMs` / `heartbeatTimeoutMs` | Ping every 30 seconds, allow 10 seconds for pong |
|
|
58
|
+
|
|
59
|
+
An injected transport is application-owned. Its raw subscriptions report readiness and failures. The Bot manages reconnect and per-relay recovery above the transport.
|
|
60
|
+
|
|
61
|
+
`RelayError` includes an operation, error code and sanitized relay origin. Optional fields include a network code, HTTP status, WebSocket close code and event kind. An `AggregateError` can contain failures from multiple relays. The live runner formats these diagnostics and supports timing output. See [diagnosing slow replies](https://github.com/CodyTseng/chirli/blob/main/examples/live/README.md#diagnose-slow-replies).
|
|
62
|
+
|
|
63
|
+
## Own metadata and peer cache
|
|
64
|
+
|
|
65
|
+
The Bot subscribes to its own verified `10044` and `10050` events. This view informs routing and key checks. Changing an advertised inbox does not reconfigure the Bot's actual subscriptions. Recreate the Bot with the new `dmRelays` to change them.
|
|
66
|
+
|
|
67
|
+
Peer metadata stays in memory. It can be refreshed in the background, and a newer authenticated seal can supersede cached key evidence.
|
|
68
|
+
|
|
69
|
+
| `metadataCache` setting | Default |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `ttlMs` | 10 minutes for usable data |
|
|
72
|
+
| `negativeTtlMs` | 30 seconds for confirmed absence |
|
|
73
|
+
| `maxStaleMs` | 24 hours for previously usable data |
|
|
74
|
+
| `maxEntries` | 512 peers |
|
|
75
|
+
|
|
76
|
+
Call `await bot.refreshPeer(peerPubkey)` to force discovery, or set `metadataCache: false` to disable peer cache reads. Already queued outbox bundles retain their original encryption and targets.
|
|
77
|
+
|
|
78
|
+
After building, run `npm run example:local` for a two-relay loopback demo.
|
|
79
|
+
|
|
80
|
+
Command startup synchronization reads the broad own-author 31992 snapshot once per write relay (bounded paging if needed), not one query per command and not remote withdrawal history. Local pending kind 5 requests retry unchanged even when relays already removed their targets. Confirmed local definitions absent from fresh snapshots do not trigger repeated withdrawals. Independent command discovery uses author-scoped 31992/5 snapshots to verify deletions across replicas. Silent relay caps/omissions cannot be detected universally.
|
|
81
|
+
|
|
82
|
+
## Explicit public command inbox
|
|
83
|
+
|
|
84
|
+
Public kind 1/1111 subscriptions require `publicInbox:{relays:[...]}` independently of DM roles and never inherit a default public firehose. Only currently declared public kinds are subscribed. Replicas reconnect through the shared managed subscription layer; initial history is not executed; the no-EOSE fallback below uses a conservative authenticated timestamp boundary. Replies route to configured write relays and the configured source relay, not arbitrary relay hints. Public thread lookups use the explicit inbox relay set and bounded query budgets. See [public input](PUBLIC.md).
|
|
85
|
+
|
|
86
|
+
## Current subscription health and initial recovery
|
|
87
|
+
|
|
88
|
+
Physical connection health, subscription usability and initial read completion are separate. The built-in pool considers a relay connected only while its current WebSocket is OPEN; EOSE, REQ rejection and AUTH completion are not connection signals. Heartbeat failure retires the socket. An OPEN socket waiting for EOSE remains connected, but an OPEN socket does not repair a failed REQ. These are internal checks, with no new public status API. A custom Transport without a physical socket probe remains unknown and uses its own subscription lifecycle; Chirli never infers its socket state from EOSE.
|
|
89
|
+
|
|
90
|
+
Failed subscription attempts are removed immediately and late callbacks are fenced. With `reconnect:false`, no background retry is scheduled. If all public replicas later become unavailable, explicit `syncCommands()` starts a fresh same-kind attempt. Another usable replica is preserved, even if it is still awaiting its initial read completion. Automatic reconnect remains the default and repairs replica demand independently with the existing backoff.
|
|
91
|
+
|
|
92
|
+
Initial reads and reconnect scans can deliver DMs at or after first activation through the same middleware and router as live DMs. They can also restore eligible outgoing self copies and retry pending outgoing publications. They never rerun a previously claimed business input. Stop fences delayed recovery and cancels reconnect demand.
|
|
93
|
+
|
|
94
|
+
### Relays that omit EOSE
|
|
95
|
+
|
|
96
|
+
Only long-lived DM and public inbox subscriptions in the built-in transport use a local read-window fallback. After the socket opens and REQ is sent, `eoseTimeoutMs` without EOSE completes that subscription's initial window locally. It neither sends an EOSE frame nor claims the relay sent one. Pending AUTH, CLOSED and disconnect still fail through their normal paths. Real EOSE and local completion settle initialization at most once; real EOSE can still arrive later and restore normal live classification.
|
|
97
|
+
|
|
98
|
+
Before real EOSE, frames remain transport history and carry an internal local boundary. The verified public-input layer allows execution only when the signed event's `created_at` is strictly later than that boundary. DM business admission is independent of EOSE and uses the verified inner rumor timestamp relative to persisted first activation. The backdated giftwrap timestamp only selects relay query windows. Signature, authenticated identity, scope and deduplication still apply.
|
|
99
|
+
|
|
100
|
+
This is degraded compatibility, not proof of message ordering: signed timestamps are sender-controlled, clocks can differ, future-dated old messages may pass, and new messages from a slow clock may remain history. Real EOSE behavior is unchanged. Applications requiring a reliable history/live boundary should choose relays that provide EOSE.
|
|
101
|
+
|
|
102
|
+
Direct Transport subscriptions, bounded queries, command catalog reconciliation, pagination and recovery scans still require **real EOSE**. A timeout does not establish a complete command snapshot, permit withdrawals, or advance a durable recovery checkpoint. Startup stage ordering is unchanged; an initial inbox window is not a physical connection check or an archive-completeness guarantee.
|
|
103
|
+
|
|
104
|
+
### Source comparison and scope
|
|
105
|
+
|
|
106
|
+
Read-only source review informed these changes; application state/UI code was not imported:
|
|
107
|
+
|
|
108
|
+
| Reference | Useful lifecycle pattern | Chirli behavior |
|
|
109
|
+
| --- | --- | --- |
|
|
110
|
+
| Jumble `src/lib/managed-relay.ts` | Logical subscriptions survive physical sockets; generation checks discard stale callbacks; no-demand/offline paths cancel retry timers | Existing managed demand and generation fencing are retained; current socket state and owned subscription attempts are distinguished from initial read completion |
|
|
111
|
+
| Jumble `src/lib/relay-subscription.ts` | Keep read completion, closure and AUTH retry separate | Strict reads retain real EOSE and separate timeout errors; only long-lived inboxes permit an explicitly local window completion |
|
|
112
|
+
| Jumble `src/lib/relay-pool-lifecycle.ts` | Browser online/resume hints trigger health checks | DOM/UI hooks are not copied into the headless SDK; applications own process lifecycle |
|
|
113
|
+
| PsstPsst `src/services/relay/managed-relay-pool.ts` | Per-relay physical generations, demand-driven retry with jitter, replay, idle release and current subscription status | Existing pooled transport, AUTH replay, per-replica retry, quiet transient diagnostics and stop cancellation remain |
|
|
114
|
+
| PsstPsst `src/services/relay/lifecycle-relay.ts` | Failed REQ/AUTH writes retire an unusable socket rather than leave orphan demand | Chirli's existing socket-failure path and transport leases remain responsible for write/disconnect signaling |
|
|
115
|
+
| PsstPsst `src/services/dm/gift-wrap-pager.ts`, `src/services/dm/dm.service.ts` | Distinguish first readiness from reconnect; bounded, epoch-fenced history recovery | Recovered DMs since first activation can dispatch once; public subscription readiness and outgoing retries are separate |
|
|
116
|
+
|
|
117
|
+
Chirli already has independent connect/EOSE/ACK/AUTH deadlines, ping/pong half-open detection, pooled connections, stable-period backoff reset and bounded per-relay DM recovery. This change does not add a second connection manager or mobile foreground/background pause policy. Inbox initialization requires a completed initial window and a settled bounded recovery attempt; neither implies a complete relay archive or confirmed recipient delivery. Long-running production outages, OS sleep/network changes, proxies and real external relays still require deployment validation; local tests use disposable identities and memory/loopback relays only.
|
|
118
|
+
|
|
119
|
+
### nostr-tools transport
|
|
120
|
+
|
|
121
|
+
The default transport uses one nostr-tools `AbstractRelay` per configured relay URL for connection setup, WebSocket ping/pong, subscription framing, event validation and publication ACK tracking. A small Node WebSocket adapter preserves the configured path and query when opening the socket, even when the library normalizes its internal URL. There is no parallel connection pool.
|
|
122
|
+
|
|
123
|
+
| Operation | Shared approach with Jumble and PsstPsst | Chirli-specific behavior |
|
|
124
|
+
| --- | --- | --- |
|
|
125
|
+
| Queries and subscriptions | Use the library's REQ handling and EOSE timer; keep subscription completion separate from socket health | Observe real EOSE by subscription ID. A long-lived inbox can use the library's timeout; strict catalog, pagination and recovery reads reject timeout or a page that lost wire entries during validation. |
|
|
126
|
+
| Publishing and NIP-42 | Use the library's publication and ACK machinery. On authentication, replay the original signed event or subscription demand. | Require a boolean `true` ACK, share in-flight publishes of the same event per relay, and keep authentication scoped to the current challenge and exact relay URL. |
|
|
127
|
+
| Reconnect | Preserve logical demand across physical connections and discard callbacks from retired connections | Chirli's managed inbox alone schedules per-relay backoff and recovery. The library's automatic reconnect is disabled so it cannot independently replay the same subscription. |
|
|
128
|
+
|
|
129
|
+
The adapter does not import browser or mobile lifecycle code. Hosted relay behavior, network changes and long-duration outages should still be validated separately from the local tests.
|
|
130
|
+
|
|
131
|
+
### Authentication attempts and query isolation
|
|
132
|
+
|
|
133
|
+
As in Jumble's `src/lib/relay-publication.ts` and PsstPsst's `publishToRelay`, a logical publication has at most one authentication retry and always resends the original signed event. A challenge can arrive without rejecting the original EVENT. In that case Chirli resends through the library's public `send()` while retaining the existing ACK promise; it does not overwrite the library's same-ID ACK slot. Concurrent same-event callers share one physical attempt and one resend. Neither authentication nor retransmission renews the overall operation deadline. A new challenge cannot make a publication loop indefinitely.
|
|
134
|
+
|
|
135
|
+
Each replacement REQ receives a fresh physical subscription ID, as in the reference clients' resubscribe paths. Retired IDs, callbacks and EOSE frames cannot complete its replacement. A strict query clears its local page buffer and wire/accepted counters for each actual attempt, returning only the attempt completed by real EOSE. Per-relay merge behavior is unchanged. Validation drops still fail strict reads rather than turning a saturated dirty page into a short complete page.
|
|
136
|
+
|
|
137
|
+
The installed library caches `auth()` across challenges. Chirli therefore builds the exact-URL NIP-42 template, validates the signer's result, and uses the library publication/ACK machinery with an AUTH-only send adaptation. ACKs must be exactly boolean `true`. This uses no private library fields and creates no additional physical connection. The library alone owns subscription EOSE timers; cancellation detaches `oneose`, calls public `receivedEose()` solely to clear that timer, and closes the subscription without claiming a wire EOSE.
|
|
138
|
+
|
|
139
|
+
### Malformed-frame logging boundary
|
|
140
|
+
|
|
141
|
+
The adapter performs a native JSON syntax preflight, rejects non-array/unknown controls, and normalizes a non-string CLOSED reason into a constant safe rejection. EVENT framing is canonicalized before the library's fast header scanner; Nostr verification and delivery remain in nostr-tools. Tests include truncated/invalid EVENT JSON, malformed EVENT shapes, unusual whitespace and fake query tokens/content and verify that these paths do not invoke the dependency's raw-frame/URL logger. The library's own relay label is origin-only; the actual socket and NIP-42 relay tag still use the exact configured URL.
|
|
142
|
+
|
|
143
|
+
There is a deliberate cost: valid EVENT JSON is decoded by the syntax preflight and again by nostr-tools. This small native framing guard is needed because the installed dependency has no public logger-suppression hook for parser failures. It does not add a second Nostr dispatcher, signature implementation, physical pool or EOSE timer. No global console patch or private library field is used. The previously reproduced malformed-EVENT URL-query warning path is covered by regressions; this is not an independent audit of every future dependency diagnostic.
|
|
144
|
+
|
|
145
|
+
Closing pending operations fences their results, but nostr-tools 2.26.0 can retain ACK/keepalive timeout handles until their configured deadline. This may briefly delay Node process exit; Chirli does not reach into private timer maps to cancel them. Browser/mobile background scheduling and network-online state from the reference apps are not transplanted into this headless SDK.
|
package/docs/SESSIONS.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Conversation sessions
|
|
2
|
+
|
|
3
|
+
Use `ctx.session` to keep business state between messages in the same DM conversation. Each conversation has its own keys. For example, a Bot can remember the current step of a form or count how many times one user has issued a command.
|
|
4
|
+
|
|
5
|
+
## Use the default SQLite storage
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Bot } from "chirli";
|
|
9
|
+
|
|
10
|
+
const bot = new Bot<{ visits: number }>({
|
|
11
|
+
signer,
|
|
12
|
+
database: "./bot.sqlite",
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
bot.command({ command: "visit", scopes: ["kind:14"] }, async (ctx) => {
|
|
16
|
+
const visits = ((await ctx.session.getItem("visits")) ?? 0) + 1;
|
|
17
|
+
ctx.session.setItem("visits", visits);
|
|
18
|
+
await ctx.reply(`Visit ${visits}`);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
bot.command({ command: "reset", scopes: ["kind:14"] }, async (ctx) => {
|
|
22
|
+
ctx.session.clear();
|
|
23
|
+
await ctx.reply("Session reset.");
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
await bot.start();
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The type argument checks keys and value types. Supply a default where you read a missing key. The Bot uses the internal `database` by default, scoped by account, protocol mode and the other participant's public key. Keep the same signer, mode and database across restarts. If you supply `storageKey`, it encrypts the stored payloads.
|
|
30
|
+
|
|
31
|
+
| Method | Behavior |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| `await ctx.session.getItem(key)` | Return a detached value or `undefined`. The first read loads the saved snapshot on demand. |
|
|
34
|
+
| `ctx.session.setItem(key, value)` | Stage a JSON-serializable value. Later reads in the current message see it. |
|
|
35
|
+
| `ctx.session.removeItem(key)` | Stage deletion of one key. |
|
|
36
|
+
| `ctx.session.clear()` | Reset the current conversation. Later writes in the same message become the new snapshot. |
|
|
37
|
+
|
|
38
|
+
Middleware and the chosen command or text handler share the same session for the current message. Successful processing commits changes once. If processing throws before the commit, the staged changes are discarded. If a custom store fails during commit, the error is reported and the SDK does not rerun the callback. A reply or other effect that already succeeded is not rolled back.
|
|
39
|
+
|
|
40
|
+
## Use a custom session store
|
|
41
|
+
|
|
42
|
+
Pass `sessionStore` to `new Bot()` to choose where business sessions are saved. `get(conversation)` returns the saved `Partial<State>` or `undefined`. `set(conversation, snapshot)` must replace the whole snapshot, so keys removed by `removeItem()` stay deleted and `clear()` persists an empty object. Both methods may be asynchronous.
|
|
43
|
+
|
|
44
|
+
The following example uses an application-owned SQLite file for a Bot whose session stores a visit count. The `signer` is the one configured for your Bot.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { DatabaseSync } from "node:sqlite";
|
|
48
|
+
import { Bot, type SessionStore } from "chirli";
|
|
49
|
+
|
|
50
|
+
type State = { visits: number };
|
|
51
|
+
|
|
52
|
+
const db = new DatabaseSync("./my-sessions.sqlite");
|
|
53
|
+
db.exec(`
|
|
54
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
55
|
+
conversation TEXT PRIMARY KEY,
|
|
56
|
+
snapshot TEXT NOT NULL
|
|
57
|
+
) STRICT
|
|
58
|
+
`);
|
|
59
|
+
|
|
60
|
+
const read = db.prepare("SELECT snapshot FROM sessions WHERE conversation = ?");
|
|
61
|
+
const write = db.prepare(`
|
|
62
|
+
INSERT INTO sessions (conversation, snapshot) VALUES (?, ?)
|
|
63
|
+
ON CONFLICT(conversation) DO UPDATE SET snapshot = excluded.snapshot
|
|
64
|
+
`);
|
|
65
|
+
|
|
66
|
+
const sessionStore: SessionStore<State> = {
|
|
67
|
+
get(conversation) {
|
|
68
|
+
const row = read.get(conversation);
|
|
69
|
+
if (row === undefined) return undefined;
|
|
70
|
+
if (typeof row.snapshot !== "string")
|
|
71
|
+
throw new Error("Invalid session snapshot");
|
|
72
|
+
|
|
73
|
+
const value: unknown = JSON.parse(row.snapshot);
|
|
74
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
75
|
+
throw new Error("Invalid session snapshot");
|
|
76
|
+
}
|
|
77
|
+
if (!("visits" in value)) return {};
|
|
78
|
+
if (
|
|
79
|
+
typeof value.visits !== "number" ||
|
|
80
|
+
!Number.isSafeInteger(value.visits)
|
|
81
|
+
) {
|
|
82
|
+
throw new Error("Invalid session count");
|
|
83
|
+
}
|
|
84
|
+
return { visits: value.visits };
|
|
85
|
+
},
|
|
86
|
+
set(conversation, snapshot) {
|
|
87
|
+
write.run(conversation, JSON.stringify(snapshot));
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const bot = new Bot({ signer, sessionStore });
|
|
92
|
+
bot.command({ command: "visit", scopes: ["kind:14"] }, async (ctx) => {
|
|
93
|
+
const visits = ((await ctx.session.getItem("visits")) ?? 0) + 1;
|
|
94
|
+
ctx.session.setItem("visits", visits);
|
|
95
|
+
await ctx.reply(`Visit ${visits}`);
|
|
96
|
+
});
|
|
97
|
+
await bot.start();
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
This example dedicates the session file to one Bot account and mode. When sharing a backend, namespace keys by account and mode in addition to the conversation. The application owns the custom connection and its encryption. Close the Bot before closing the database with `db.close()` so in-flight handlers can finish saving.
|
|
101
|
+
|
|
102
|
+
## Inspect or replace a session outside a handler
|
|
103
|
+
|
|
104
|
+
Use `await bot.getSession(peerPubkey)` for a detached snapshot from the configured backend, or `await bot.setSession(peerPubkey, snapshot)` to replace it. To reset state from a handler, use `ctx.session.clear()` so the change is committed with that message's other session changes. Schedule external snapshot replacements outside active processing for that conversation to avoid overwriting a handler's pending edits.
|
|
105
|
+
|
|
106
|
+
Run `npm run build && npm run example:session` from the GitHub checkout to try a session with two disposable accounts. [Session demo](https://github.com/CodyTseng/chirli/blob/main/examples/session.ts) · [API reference](API.md)
|
|
107
|
+
|
|
108
|
+
Public kind 1/1111 handlers use separate `public:` conversation keys and internal session namespaces. They never read a DM peer session. Custom stores must preserve that separation and account isolation; public threads may involve multiple authors sharing one root session. See [public context](PUBLIC.md#shared-context-and-privacy).
|
package/docs/SIGNERS.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Signers
|
|
2
|
+
|
|
3
|
+
Create a Bot with a signer. Local nsec and remote bunker credentials use the same API; application handlers never inspect the signing backend.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { Bot, nsecSigner, bunkerSigner } from "chirli";
|
|
7
|
+
|
|
8
|
+
const signer = nsecSigner(nsecFromYourSecretManager);
|
|
9
|
+
// Alternatively: const signer = bunkerSigner(bunkerUri, { clientSecret: bunkerClientKeyFromYourSecretManager });
|
|
10
|
+
const bot = new Bot({
|
|
11
|
+
signer,
|
|
12
|
+
database: "./inbox.sqlite",
|
|
13
|
+
});
|
|
14
|
+
await bot.start();
|
|
15
|
+
console.log(bot.pubkey);
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Capability contract
|
|
19
|
+
|
|
20
|
+
`Signer` requires four asynchronous methods:
|
|
21
|
+
|
|
22
|
+
- `getPublicKey()` resolves the account public key, cached during startup.
|
|
23
|
+
- `signEvent(template)` signs the exact event requested.
|
|
24
|
+
- `nip44Encrypt(peer, plaintext)` encrypts using account-key NIP-44.
|
|
25
|
+
- `nip44Decrypt(peer, ciphertext)` decrypts using account-key NIP-44.
|
|
26
|
+
|
|
27
|
+
`nip04Encrypt` and `nip04Decrypt` are optional. Both built-in signers provide them, but Chirli messaging uses NIP-44. Custom signers can omit these methods and `close()`.
|
|
28
|
+
|
|
29
|
+
## Ownership
|
|
30
|
+
|
|
31
|
+
The application always owns the signer. Bot never calls its optional `close()`, including after failed construction. Close all Bots using a signer first, then call `await signer.close?.()` yourself. Local signer closure wipes its private copy of secret bytes; it never modifies the caller's byte array.
|
|
32
|
+
|
|
33
|
+
## Local nsec
|
|
34
|
+
|
|
35
|
+
`nsecSigner(nsecOrSecretBytes)` accepts a valid nsec or a 32-byte secret. Persist credentials in your application secret store; the SDK does not save identity signing secrets. Reuse the same credentials and database after restart.
|
|
36
|
+
|
|
37
|
+
## Remote bunker
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
const signer = bunkerSigner(bunkerUri, {
|
|
41
|
+
clientSecret: bunkerClientKeyFromYourSecretManager,
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
A bunker URI identifies the service key. Chirli resolves the account key through NIP-46 and checks it on reconnect. A timed-out operation discards the connection. Later requests can reconnect using the same client key.
|
|
46
|
+
|
|
47
|
+
Bunker connections use the same WebSocket transport as the Bot with a separate pool. The pool starts with the URI's relay URLs and can accept an updated list through the optional `switch_relays` RPC supported by nostr-tools. A request is sent after its response subscription is issued on that relay. It can receive the response before EOSE. Subsequent requests can reopen disconnected replicas. The bunker pool uses the shared heartbeat and idle defaults. `timeoutMs` sets the WebSocket connection deadline and caps the default relay publication deadline. Bunker relays must accept the NIP-46 traffic without relay-side NIP-42 authentication.
|
|
48
|
+
|
|
49
|
+
Approve requests in the signer's own app or configure its permissions ahead of time. If the signer sends a NIP-46 URL challenge, the request fails.
|
|
50
|
+
|
|
51
|
+
Supply a valid 32-byte NIP-46 client private key as `clientSecret`. Generate a dedicated key before first pairing and keep it in your application's secret store. To reconnect after a process restart, reuse that key and remove a consumed one-time `secret` parameter from the bunker URI. The remote signer must still recognize the client's authorization. Use `timeoutMs` to change the default 15-second deadline.
|
|
52
|
+
|
|
53
|
+
Closing releases the session without logout or deletion of remote credentials. The remote signer sees plaintext passed to its encryption/decryption methods.
|
|
54
|
+
|
|
55
|
+
## Messaging keys and failures
|
|
56
|
+
|
|
57
|
+
Default NIP-17 uses signer NIP-44. Explicit `mode:'nip4e'` generates/restores local split messaging keys; signer NIP-44 remains necessary for standard peers. Changing signer backend does not change Bot handlers, command registration, sessions or message processing.
|
|
58
|
+
|
|
59
|
+
Operational failures should raise `SignerError`. They remain retryable and prevent history checkpoint advancement. Ordinary decryption errors indicate invalid ciphertext. See [interoperability](INTEROPERABILITY.md) for key selection and [security](../SECURITY.md) for remote-signer trust boundaries.
|
package/docs/STORAGE.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# Message storage
|
|
2
|
+
|
|
3
|
+
Retained private messages and their diagnostic states belong to `MessageStorage`. The first DM activation timestamp, atomic inbound ID claims, outbox, keys, peer evidence, declarations, sessions and relay checkpoints stay in internal SQLite. Internal persistence accepts only a `database` path; its backend cannot be replaced.
|
|
4
|
+
|
|
5
|
+
Business conversation state uses `ctx.session`. A Bot can supply a `sessionStore` for that state. Internal sessions used by the framework stay in SQLite. See the [session guide and custom store example](SESSIONS.md#use-a-custom-session-store).
|
|
6
|
+
|
|
7
|
+
## Configuration
|
|
8
|
+
|
|
9
|
+
Bot uses `sqliteMessageStorage` by default, with message records in the same database file as the internal tables. `:memory:` keeps both stores in memory. To choose a separate message database:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Bot, sqliteMessageStorage } from "chirli";
|
|
13
|
+
|
|
14
|
+
const messages = sqliteMessageStorage("./messages.sqlite");
|
|
15
|
+
const bot = new Bot({
|
|
16
|
+
signer,
|
|
17
|
+
database: "./internal.sqlite",
|
|
18
|
+
storageKey,
|
|
19
|
+
messageStorage: messages,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
try {
|
|
23
|
+
await bot.start();
|
|
24
|
+
} finally {
|
|
25
|
+
await bot.close();
|
|
26
|
+
messages.close();
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Bot closes its default message backend. Close an injected backend after closing the Bot. Use fresh database paths for this pre-release storage format, including for any separate history database. Earlier files are unsupported; no migration is provided. Leave them in place if you want to keep them. Preserve the new databases and any storage key across restarts.
|
|
31
|
+
|
|
32
|
+
## Three-method interface
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
interface MessageStorage {
|
|
36
|
+
insert(account: string, message: MessageStorageEntry): boolean;
|
|
37
|
+
query(account: string, options?: MessageStorageQuery): MessageStorageEntry[];
|
|
38
|
+
updateState(account: string, id: string, state: MessageState): void;
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Each entry contains `id`, `conversation`, millisecond `timestamp`, opaque `payload`, and `state`. The SDK handles payload encryption and decoding. These are diagnostic fields on conversation records, not a work queue. An admitted live message can be `processing`, `failed` or `done`. Outgoing and self-copy messages need no incoming handler.
|
|
43
|
+
|
|
44
|
+
- `insert` must atomically insert once by account + ID. Return false on duplicates, preserving the existing payload and state. This deduplicates storage writes; the prior ID claim in internal SQLite separately controls callback eligibility.
|
|
45
|
+
- `updateState` durably changes only an existing record's state, scoped by account + ID. It must not create a missing message.
|
|
46
|
+
- `query` returns detached records. Optional filters are exact `id`, exact `conversation`, and any of `states`; an empty state array matches nothing. `limit` bounds the result, including zero.
|
|
47
|
+
- `order` defaults to `oldest` (timestamp ASC, ID ASC). `newest` uses timestamp DESC, ID ASC; `recovery` uses timestamp ASC, ID DESC. The optional `{timestamp, id}` cursor is exclusive in that order.
|
|
48
|
+
- Implement filtering, ordering, cursors and limits in the database. Queries by exact ID, conversation or diagnostic state should use indexes.
|
|
49
|
+
- All methods are synchronous and durable on return. Promise-returning methods are unsupported.
|
|
50
|
+
|
|
51
|
+
History, `getMessage`, `listMessages` and `getMessageState` use this backend. A claimed ID need not have a history entry. An eligible incoming DM, including one recovered from a relay, is saved only when middleware reaches routing. Pre-activation DMs are ignored and short-circuited DMs retain only their ID claim. No inbound claim, outbox, keyring or metadata interface is required from custom implementations.
|
|
52
|
+
|
|
53
|
+
## Failures and restart
|
|
54
|
+
|
|
55
|
+
For cross-store writes, internal SQLite first commits a temporary message handoff with the corresponding peer metadata or exact outgoing outbox bundle. Only then does the SDK insert the message into `MessageStorage`. Successful insertion removes the temporary record. A crash or uncertain insert can repeat insertion, so duplicates must never reset an existing diagnostic state. This repairs storage only, not a handler attempt.
|
|
56
|
+
|
|
57
|
+
A failed insert can leave a durable handoff for storage recovery. Recovering that record later does not call middleware or handlers. A send may fail after committing its exact outbox bundle. Use `flushOutbox()` to retry that bundle. A new `send()` creates a new message.
|
|
58
|
+
|
|
59
|
+
An error in a handler or state write does not reopen the ID claim. Keep the internal database as well as any injected history backend across restarts. To retry business effects, persist and operate your own jobs. One active Bot/process per account database is supported.
|
|
60
|
+
|
|
61
|
+
## SQLite and encryption
|
|
62
|
+
|
|
63
|
+
`sqliteMessageStorage(path)` provides WAL, synchronous FULL, 0600 permissions for new files, atomic unique insertion and indexed native queries. It exposes only the three message operations and `close`.
|
|
64
|
+
|
|
65
|
+
`storageKey` encrypts payloads with AES-GCM before storage. Without it, payloads use tagged plaintext. Routing metadata and states remain visible. Preserve the original key; missing/wrong keys fail rather than resetting data.
|
|
66
|
+
|
|
67
|
+
The `JsonMessageStorage` demo shows these operations for small files using an in-memory scan. Run `npm run example:storage` from the GitHub checkout to verify custom message history and internal session recovery after restart. [JsonMessageStorage example](https://github.com/CodyTseng/chirli/blob/main/examples/_json-storage.ts)
|
|
68
|
+
|
|
69
|
+
## Public command journal
|
|
70
|
+
|
|
71
|
+
Public inputs retain canonical ID claims, not a history, incoming body or queued callback payload. Signed outgoing public replies and reactions share a durable public outbox with exact-ID retries. Neither uses the replaceable DM MessageStorage. Default public sessions use a separate namespace. Custom SessionStore implementations must preserve public/private and account key separation. The selected storage codec applies to public outbox and session values. See [public claims and outgoing retries](PUBLIC.md#claims-and-outgoing-retries).
|