chirli 0.0.0-stage → 0.1.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 +105 -0
- package/CONTRIBUTING.md +52 -0
- package/LICENSE +22 -0
- package/README.md +273 -2
- package/SECURITY.md +55 -0
- package/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/announcements.d.ts +25 -0
- package/dist/announcements.js +110 -0
- package/dist/blossom.d.ts +30 -0
- package/dist/blossom.js +179 -0
- package/dist/bot-handlers.d.ts +79 -0
- package/dist/bot-handlers.js +258 -0
- package/dist/bot.d.ts +66 -0
- package/dist/bot.js +149 -0
- package/dist/client.d.ts +217 -0
- package/dist/client.js +1011 -0
- package/dist/command-discovery.d.ts +4 -0
- package/dist/command-discovery.js +24 -0
- package/dist/command-schema.d.ts +4 -0
- package/dist/command-schema.js +70 -0
- package/dist/commands.d.ts +31 -0
- package/dist/commands.js +188 -0
- package/dist/defaults.d.ts +9 -0
- package/dist/defaults.js +15 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.js +89 -0
- package/dist/inbound-policy.d.ts +4 -0
- package/dist/inbound-policy.js +9 -0
- package/dist/inbox.d.ts +53 -0
- package/dist/inbox.js +331 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +11 -0
- package/dist/key-sync.d.ts +33 -0
- package/dist/key-sync.js +255 -0
- package/dist/keys.d.ts +65 -0
- package/dist/keys.js +324 -0
- package/dist/message-storage-sqlite.d.ts +6 -0
- package/dist/message-storage-sqlite.js +85 -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 +253 -0
- package/dist/metadata.d.ts +7 -0
- package/dist/metadata.js +49 -0
- package/dist/modes.d.ts +26 -0
- package/dist/modes.js +79 -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 +456 -0
- package/dist/protocol.d.ts +67 -0
- package/dist/protocol.js +255 -0
- package/dist/public-inbox.d.ts +64 -0
- package/dist/public-inbox.js +304 -0
- package/dist/public-thread.d.ts +59 -0
- package/dist/public-thread.js +319 -0
- package/dist/relay-pool.d.ts +43 -0
- package/dist/relay-pool.js +324 -0
- package/dist/relay-roles.d.ts +18 -0
- package/dist/relay-roles.js +46 -0
- package/dist/relay.d.ts +52 -0
- package/dist/relay.js +399 -0
- package/dist/request-timing.d.ts +12 -0
- package/dist/request-timing.js +25 -0
- package/dist/session.d.ts +16 -0
- package/dist/session.js +49 -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 +84 -0
- package/dist/signers/bunker.d.ts +7 -0
- package/dist/signers/bunker.js +174 -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 +52 -0
- package/dist/storage-sqlite.d.ts +27 -0
- package/dist/storage-sqlite.js +169 -0
- package/dist/storage.d.ts +81 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +92 -0
- package/dist/store.js +326 -0
- package/docs/ACCESS.md +39 -0
- package/docs/API.md +336 -0
- package/docs/INTEROPERABILITY.md +32 -0
- package/docs/KEYS.md +75 -0
- package/docs/NIP-CD.md +102 -0
- package/docs/PUBLIC.md +78 -0
- package/docs/RECOVERY.md +57 -0
- package/docs/RELAYS.md +145 -0
- package/docs/SESSIONS.md +104 -0
- package/docs/SIGNERS.md +57 -0
- package/docs/STORAGE.md +71 -0
- package/docs/TUTORIAL.md +175 -0
- package/package.json +83 -4
package/ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
Chirli is a Node.js SDK for Nostr private text and explicitly scoped public commands. Applications own authorization, business effects, signer credentials and deployment. `src/index.ts` is the public entry point.
|
|
4
|
+
|
|
5
|
+
## Module responsibilities
|
|
6
|
+
|
|
7
|
+
| Layer | Modules | Responsibility |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| Application | `examples/live/`, application code | Configuration, ready output, signals, provider adapters and periodic retries |
|
|
10
|
+
| Bot | `bot.ts`, `bot-handlers.ts` | Public lifecycle and messaging API, middleware, commands and sessions |
|
|
11
|
+
| Internal client | `client.ts` | Lifecycle, verified intake, conversation queues and coordination of lower layers |
|
|
12
|
+
| Commands | `nipcd.ts`, `commands.ts`, `command-discovery.ts` | Pure schemas/parsing, durable public reconciliation, and read-only discovery |
|
|
13
|
+
| Signers | `signer.ts`, `signers/`, `signers.ts` | Account capabilities and the internal protocol bridge |
|
|
14
|
+
| Protocol | `protocol.ts`, `modes.ts`, `nip4e-compat.ts` | Envelope verification, mode policy and authenticated peer-key evidence |
|
|
15
|
+
| Keys and metadata | `keys.ts`, `key-sync.ts`, `metadata.ts`, `messaging-metadata.ts`, `announcements.ts` | Key custody, device sync, verified metadata views and relay-list publication |
|
|
16
|
+
| Network | `relay-pool.ts`, `relay.ts`, `inbox.ts` | Physical connections, bounded operations, reconnect demand and history recovery |
|
|
17
|
+
| Persistence | `store.ts`, `storage.ts`, `storage-sqlite.ts` | Internal SQLite state and replaceable message/state persistence (`message-storage*.ts`) |
|
|
18
|
+
|
|
19
|
+
Bot owns one internal client. Each queued message runs middleware before routing to a matching command or to the optional text fallback. AI/model adapters belong to applications.
|
|
20
|
+
|
|
21
|
+
Command execution, publication and discovery are independent: discovery never installs a handler or publishes metadata. `command()` validates explicitly scoped object definitions before registering them in the same command pipeline.
|
|
22
|
+
|
|
23
|
+
## Construction and ownership
|
|
24
|
+
|
|
25
|
+
`new Bot({ signer })` accepts configuration and handlers synchronously. Startup resolves the public key and opens persistence. The Bot closes its built-in resources. Injected signers, transports and message storage remain application-owned.
|
|
26
|
+
|
|
27
|
+
## Startup and shutdown
|
|
28
|
+
|
|
29
|
+
1. Construct the Bot and register handlers and the full command set.
|
|
30
|
+
2. `start()` publishes key/relay metadata and reconciles the public command catalog, including an empty set.
|
|
31
|
+
3. Startup restores unfinished work, opens inbox subscriptions and retries the outbox. Every write relay must accept command reconciliation. One ready DM replica can serve the Bot while other DM replicas reconnect.
|
|
32
|
+
4. The live runner prints the identity and QR after startup succeeds.
|
|
33
|
+
|
|
34
|
+
Stop cancels subscription/reconnect demand and drains intake, handlers and SDK work. Close then releases owned resources. Application timers are stopped and awaited before their injected dependencies are closed. Handler calls to self-draining `idle`, `retryInbox`, `stop` or `close` reject; `requestStop()` requests shutdown without waiting on the caller.
|
|
35
|
+
|
|
36
|
+
## Incoming messages
|
|
37
|
+
|
|
38
|
+
Giftwrap and seal signatures, rumor hash/author, times and one-to-one routing are verified before persistence. The optional inbound policy runs after authentication and before peer evidence, history insertion and dispatch.
|
|
39
|
+
|
|
40
|
+
A temporary rumor handoff and its key evidence commit atomically in internal SQLite before insertion into MessageStorage. The handoff is removed after durable insertion. `(account/mode, rumor ID)` deduplicates wrappers across relays and restarts.
|
|
41
|
+
|
|
42
|
+
- New incoming live messages enter `pending → processing → done`.
|
|
43
|
+
- A handler failure records `failed`; retry or restart can run it again.
|
|
44
|
+
- History and outgoing self copies become `done` without business dispatch.
|
|
45
|
+
- Conversation queues are serial; different conversations can proceed concurrently.
|
|
46
|
+
|
|
47
|
+
Receipt observers receive detached copies and do not control durable success. Multiple durable handlers form one processing group, so a later failure can repeat earlier effects. Session saves and arbitrary external effects are not one transaction; applications need their own idempotency.
|
|
48
|
+
|
|
49
|
+
## Outgoing messages
|
|
50
|
+
|
|
51
|
+
A reply references its parent rumor ID through an `e` tag inside the encrypted kind-14 event. Outgoing kind-7 reactions use the same private envelope and durable outbox. Text history and incoming dispatch accept kind 14. Recipient metadata is resolved before queuing. A temporary outgoing message handoff and exact signed envelopes commit together before publication; the message is then inserted into MessageStorage before normal send publication. Each recipient/self envelope requires at least one relay ACK. Failure keeps the bundle pending; retries reuse its IDs and ciphertext.
|
|
52
|
+
|
|
53
|
+
Relay acceptance does not establish delivery or reading. A new `send()` call creates a new logical message.
|
|
54
|
+
|
|
55
|
+
## Public commands
|
|
56
|
+
|
|
57
|
+
Each command has one kind `31992` coordinate derived from its local trigger; user-installed kind `10992` lists are untouched. Startup uses broad author-scoped definition snapshots without querying withdrawals; local pending kind 5 operations remain durable. Independent discovery verifies author-scoped definitions and withdrawals without a membership list.
|
|
58
|
+
|
|
59
|
+
Reconciliation queries each write relay separately, combines signed definitions/deletions with durable retry state, publishes additions/updates/withdrawals, and commits the complete catalog last. Known truncated queries fail rather than becoming deletion evidence. Every write destination must ACK before advancing.
|
|
60
|
+
|
|
61
|
+
Handler registrations and standalone metadata registrations hold independent references. Public metadata cannot change an attached handler's schema. Revocation removes the coordinate globally and invalidates old handler registrations.
|
|
62
|
+
|
|
63
|
+
Background announcement retry only reconciles dirty/pending command state. Startup and explicit `syncCommands()` still verify the full remote view. Read-only discovery reports a bounded relay snapshot, not global completeness.
|
|
64
|
+
|
|
65
|
+
## Protocol and keys
|
|
66
|
+
|
|
67
|
+
Default NIP-17 uses account-key NIP-44. Explicit NIP-4E mode keeps local split messaging keys while retaining account-key crypto for standard peers. Both modes accept supported standard and extension envelopes.
|
|
68
|
+
|
|
69
|
+
The account keyring is shared across mode scopes; messages, sessions, checkpoints and business work are scoped separately. Rotation persists the candidate and signed declaration before publication, activates after ACK/durable commit, and retains configured retired keys. Unknown advertised own keys cannot be silently overwritten.
|
|
70
|
+
|
|
71
|
+
A remote signer sees NIP-44 plaintext it processes. Operational signer failures remain retryable and prevent recovery checkpoints from advancing.
|
|
72
|
+
|
|
73
|
+
## Network and storage limits
|
|
74
|
+
|
|
75
|
+
One nostr-tools AbstractRelay per configured relay URL shares operations and AUTH; the Node socket adapter preserves exact paths and queries. Connect/EOSE/ACK/AUTH budgets are separate. Inbox owns durable reconnect demand and bounded overlap paging; the physical pool does not independently reconnect.
|
|
76
|
+
|
|
77
|
+
The NIP-46 signer uses an `AbstractSimplePool` adapter backed by its own `WebSocketTransport` instance. It shares the physical relay implementation with Bot traffic and reopens missing response subscriptions on demand. Closing the signer releases its relay connections, including connections to relays returned by `switch_relays`.
|
|
78
|
+
|
|
79
|
+
Recovered frames remain history. Saturated timestamp boundaries, page limits or failed reads leave coverage incomplete. No full archive or durable undecryptable-envelope quarantine is promised.
|
|
80
|
+
|
|
81
|
+
Store applies AES-GCM when a storage key is supplied, otherwise tagged plaintext. MessageStorage owns message records, duplicate detection and processing state. Its default sqliteMessageStorage uses indexed native queries. Internal SQLite owns outbox, keys, metadata and temporary cross-store handoffs, and accepts only a database path. Failed handoffs are replayed without replacing existing message state; internal message copies are removed after successful insertion. The SDK supports one active Client/process per account database. Distributed claims, admission/backpressure limits, pruning, forward secrecy and exactly-once external effects remain outside its scope.
|
|
82
|
+
|
|
83
|
+
## References and validation
|
|
84
|
+
|
|
85
|
+
Protocol reference: PsstPsst checkout `5e6940fe6daa130d4143bf457078c3768202cc10`. Relay reference: `d7873d66fd1c0e6dbb0aaa2f55475944c4ba57ce`. Committed fixtures record upstream provenance; generation scripts use disposable keys without loading application state.
|
|
86
|
+
|
|
87
|
+
Tests cover protocol verification, persistence/restart, command reconciliation, lifecycle concurrency and application readiness. Offline examples use memory transport; loopback tests require socket binding. Optional `PSST_RELAY_BIN` and `PSST_SOURCE` tests exercise external reference implementations when configured. These checks do not establish physical-device interoperability or an independent security audit.
|
|
88
|
+
|
|
89
|
+
See [API](docs/API.md), [command lifecycle](docs/NIP-CD.md), [key custody](docs/KEYS.md), [storage](docs/STORAGE.md), [recovery](docs/RECOVERY.md) and [third-party notices](THIRD_PARTY_NOTICES.md).
|
|
90
|
+
|
|
91
|
+
## Optional official policy and timing
|
|
92
|
+
|
|
93
|
+
`inbound-policy.ts` supplies an identity allowlist helper and the `InboundPolicy` type. Client passes only the authenticated sender string to the optional policy at verified intake and before dispatching pending work. `request-timing.ts` supplies downstream middleware with a frozen duration and outcome metric and isolates observer callbacks from processing.
|
|
94
|
+
|
|
95
|
+
## Public input isolation
|
|
96
|
+
|
|
97
|
+
`public-inbox.ts` owns a separate verified kind 1/1111 subscription and durable public journal in internal account/mode storage. Only matching, unambiguously targeted registered commands enter business middleware. Admission checks signatures, source relay, author policy, structure, scope and invocation before persistence, and repeats policy before dispatch. Per-root queues and `public:` session keys never use DM message rows or peer sessions. `bot.observe`, message history/state/listing remain DM-only.
|
|
98
|
+
|
|
99
|
+
`public-thread.ts` parses legacy/NIP-22 topology, batches a root across legacy `#e` and modern `#E` (plus coordinate variants), and follows only the trigger ancestor branch under one deadline and size/lookup/depth limits. Public replies are signed kind 1111 events with a durable outbox, configured write/source destinations, and exact-ID retries. Transport queries have no cancellation API; a timed-out resolver returns while already acquired transport queries settle under transport budgets. Stop drains active processing and cancels subscription/reconnect demand.
|
|
100
|
+
|
|
101
|
+
## Event-based delayed actions
|
|
102
|
+
|
|
103
|
+
Client.reply/thread resolve a detached original input event into either an exact account-bound authenticated incoming DM record or a reverified public target. Bot exposes that path directly, and handler methods capture independent anchor snapshots and use the same execution. Public target lookup retains no new event-body index: a signed supplied event is sufficient, while the existing journal may supply known source provenance. Private thread reads retain the original record cutoff. No job queue or idempotency layer is introduced.
|
|
104
|
+
|
|
105
|
+
Command args use a single Zod 4 object. command-schema.ts projects its supported positional subset into unchanged wire CommandArgument metadata at registration. Entry policy and ordinary middleware precede decoding/validation. Only recognized target/scope matches can raise a framework terminal InvalidArgsError. Such errors are consumed after centralized observation; operational/business errors preserve retry behavior. Args-dependent authorization suppresses invalid-input response hooks; valid authorization and command-only context use Zod's parsed output.
|
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Contributing to Chirli
|
|
2
|
+
|
|
3
|
+
Chirli is a Nostr bot SDK for private messages and explicitly scoped public commands. Applications own message handling, context selection and external effects. The package name is `chirli`; `Bot` and its public interfaces are shared across protocol modes; `Client` is internal. Keep AI adapters in applications/examples, not SDK core.
|
|
4
|
+
|
|
5
|
+
## Local development
|
|
6
|
+
|
|
7
|
+
Use Node 24+ and npm. From this checkout:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm ci --ignore-scripts
|
|
11
|
+
npm run check
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
`check` builds from a clean `dist/`, checks all TypeScript, runs tests, executes fourteen offline examples, and checks an actual npm tarball in an isolated consumer. The consumer runs the checkout examples against the packed SDK. Local WebSocket tests and the loopback demo need permission to bind loopback sockets. No public relays, account keys, or paid APIs are required.
|
|
15
|
+
|
|
16
|
+
`npm test` uses temporary identities/databases. Two optional tests require an externally built PsstPsst Go relay:
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
PSST_RELAY_BIN=/absolute/path/to/local-relay npm test
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The optional `PSST_SOURCE=/path/to/psstpsst/src/services/crypto/nip17-gift-wrap.ts npm test` also exercises actual extracted software-envelope functions. If their environment variables are unset, these optional integrations are reported as skipped; the independent local WebSocket and protocol-helper tests still run. Do not silently substitute public-relay tests. GitHub Actions is configured for Node 24 on Linux and macOS; adding a workflow does not imply a remote run has passed.
|
|
23
|
+
|
|
24
|
+
## Scope and changes
|
|
25
|
+
|
|
26
|
+
- Preserve default identity-key NIP-17, explicit split-key opt-in and dual-protocol receive in both modes. Key rotation must persist candidate custody before publication and preserve legacy/retry identities. Concentrate differences in protocol strategies and envelope policies.
|
|
27
|
+
- Verify signatures, authors, IDs and recipients before persisting or exposing messages. Do not bypass verification caches by trusting a previously marked object.
|
|
28
|
+
- Deduplicate by rumor ID. Keep protocol receipt, business status and relay acceptance separate.
|
|
29
|
+
- Add focused regression tests for behavior changes, particularly concurrency, history/live boundaries, restart and mode isolation. Tests should exercise observable behavior rather than copy implementation details.
|
|
30
|
+
- Keep documentation, examples, comments and diagnostics in clear English. Follow existing TypeScript formatting; no formatter or linter is currently mandated.
|
|
31
|
+
- Never commit credentials, real account events, personal databases, or application plaintext. The committed protocol fixture uses disposable keys; keep its provenance and license notice.
|
|
32
|
+
- Keep changes focused. Explain what changed, why, tests run, compatibility and known limits in a contribution description. Do not claim delivery/read confirmation or exactly-once effects from relay ACKs.
|
|
33
|
+
|
|
34
|
+
See [API.md](docs/API.md), [signers](docs/SIGNERS.md), [recovery](docs/RECOVERY.md), [ARCHITECTURE.md](ARCHITECTURE.md) and [examples/README.md](https://github.com/CodyTseng/chirli/blob/main/examples/README.md). Dependency changes must preserve a reproducible lockfile and update THIRD_PARTY_NOTICES.md when licenses or copied code change.
|
|
35
|
+
|
|
36
|
+
## Reports and licensing
|
|
37
|
+
|
|
38
|
+
For ordinary bugs, provide runtime versions, selected mode, a minimal reproduction with disposable keys, and expected and actual behavior. Keep private keys, storage keys, personal messages and relay credentials out of reports. [GitHub Issues](https://github.com/CodyTseng/chirli/issues)
|
|
39
|
+
|
|
40
|
+
Report potential vulnerabilities privately using the instructions in [SECURITY.md](SECURITY.md). Chirli is licensed under MIT and retains the upstream attributions in [LICENSE](LICENSE) and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
|
|
41
|
+
|
|
42
|
+
NIP-CD is a draft integration. Retain stable command coordinates and signature/deletion handling. Commands are always public on configured write relays; Bot startup reconciles the complete local registry before dispatch. Keep kind 31992 definitions and kind 5 withdrawals distinct from standard user-installed list 10992. Bot coordinates are command-name derived; wire decoding retains external d values. Do not describe the SDK's private-DM scope mapping as standardized. See docs/NIP-CD.md.
|
|
43
|
+
|
|
44
|
+
Storage adapters implement the exported synchronous opaque-record contract; keep codec selection/crypto in the SDK facade; preserve AES-GCM with storageKey and tagged plaintext without it. Preserve exact bytes, scopes, detached reads and durable atomic writes. Reuse test/storage-contract.ts and include rotation, uncertain ACK, restart and rollback cases. Multi-relay changes must preserve partial-success availability, first-ready startup, independent historical catch-up and rumor-ID dedup. Never treat a replica's recovery page as a new command. See docs/STORAGE.md and docs/RELAYS.md.
|
|
45
|
+
|
|
46
|
+
Authorization changes must match authenticated identity authors, never wrapper or n encryption keys, and run before storage/business/session effects. Preserve absent versus empty policy semantics and recheck pending retry/start paths. See docs/ACCESS.md and test/allowlist.test.ts for protocol, spoofing and replay coverage.
|
|
47
|
+
|
|
48
|
+
Live examples are real long-running bot programs, not offline walkthroughs. Their tests must launch the real compiled entrypoints using only test-generated config/identities and loopback relays. Never load an operator .env.chirli or inherit CHIRLI credentials into child fixtures. Preserve initializer non-overwrite/0600 behavior, restart persistence, clean signals and sanitized logs. Package smoke only runs live --help, never configured public-relay programs.
|
|
49
|
+
|
|
50
|
+
Test zero-config defaults without contacting public relays: unit-check the PsstPsst default list, but override CHIRLI_RELAYS to loopback for live child processes. Generated test identities must use temporary databases/directories. Cover signer reuse, plaintext persistence, optional encrypted signer files and missing/wrong-key refusal; never regenerate an identity over existing/corrupt account state.
|
|
51
|
+
|
|
52
|
+
Public input changes must preserve explicit kind scopes/inbox relays, verified author/source gates, no history replay, ID deduplication, public/private state separation, kind 1111 root/parent references, and bounded ancestor-only resolution. Keep public URLs out of tests; use the loopback replica and memory tests in test/public.test.ts. New application processing belongs in handlers rather than SDK core.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cody Tseng
|
|
4
|
+
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,274 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Chirli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A TypeScript SDK for Nostr bots with private messages and file attachments, public note/comment commands, middleware and persistent sessions.
|
|
4
|
+
|
|
5
|
+
**Node.js 24+ · ESM · Experimental**
|
|
6
|
+
|
|
7
|
+
Applications choose what to process and which external services to call. The SDK has no built-in AI provider or automatic history upload.
|
|
8
|
+
|
|
9
|
+
## Try a bot
|
|
10
|
+
|
|
11
|
+
Run the commands bot from this checkout:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm ci --ignore-scripts
|
|
15
|
+
npm run build
|
|
16
|
+
npm run bot:commands
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Wait for the ready banner, then send `/ping` to the printed npub. The identity appears only after startup completes. Press Ctrl+C to stop.
|
|
20
|
+
|
|
21
|
+
The runner creates persistent credentials and a database on first launch. Configuration is optional; local storage is **plaintext unless a storage key is supplied**. Wire messages remain encrypted.
|
|
22
|
+
|
|
23
|
+
| Command | Example |
|
|
24
|
+
| --- | --- |
|
|
25
|
+
| `npm run bot:commands` | `/help`, `/ping`, `/whoami` |
|
|
26
|
+
| `npm run bot:echo` | Reply to incoming text |
|
|
27
|
+
| `npm run bot:session` | Persist conversation state |
|
|
28
|
+
| `npm run bot:notes` | `/remember`, `/notes` |
|
|
29
|
+
|
|
30
|
+
The GitHub checkout contains live and offline examples. To explore without external connections, run `npm run examples:smoke` after building. [Live setup](https://github.com/CodyTseng/chirli/blob/main/examples/live/README.md)
|
|
31
|
+
|
|
32
|
+
## Build your own bot
|
|
33
|
+
|
|
34
|
+
Once the first release is available on npm, install Chirli in your project.
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
npm install chirli
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
For a guided path from the runnable demo to your own application, see the [first bot tutorial](docs/TUTORIAL.md).
|
|
41
|
+
|
|
42
|
+
Select a signer at the application boundary. This example reads an application-provided nsec from `CHIRLI_NSEC`:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { Bot, nsecSigner } from 'chirli';
|
|
46
|
+
|
|
47
|
+
const signer = nsecSigner(process.env.CHIRLI_NSEC!);
|
|
48
|
+
const bot = new Bot({
|
|
49
|
+
signer,
|
|
50
|
+
database: './chirli.sqlite',
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
bot.command({ command: 'ping', scopes: ['kind:14'] }, async ctx => {
|
|
55
|
+
await ctx.reply('pong');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
await bot.start();
|
|
60
|
+
|
|
61
|
+
console.log(`Bot public key: ${bot.pubkey}`);
|
|
62
|
+
await new Promise<void>(resolve => {
|
|
63
|
+
process.once('SIGINT', () => resolve());
|
|
64
|
+
});
|
|
65
|
+
} finally {
|
|
66
|
+
await bot.close();
|
|
67
|
+
await signer.close();
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Register the complete command set before starting. `bot.start()` resolves the signer, publishes account and inbox metadata, synchronizes commands on write relays, and opens the inbox.
|
|
72
|
+
|
|
73
|
+
### Use a remote signer
|
|
74
|
+
|
|
75
|
+
Replace the signer without changing handlers:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { bunkerSigner } from 'chirli';
|
|
79
|
+
|
|
80
|
+
const signer = bunkerSigner(bunkerUri, { clientSecret: bunkerClientKeyFromYourSecretManager });
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Pass this signer to `new Bot({ signer })`. After startup, `bot.pubkey` gives you the account key. Approve requests in the signer or configure its permissions ahead of time. See [remote signers](docs/SIGNERS.md#remote-bunker).
|
|
84
|
+
|
|
85
|
+
## Handle ordinary messages
|
|
86
|
+
|
|
87
|
+
Use `handle()` to reply to messages that have no matching command:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
bot.handle(async ctx => {
|
|
91
|
+
await ctx.reply('Thanks for your message');
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
bot.onError((error, message) => {
|
|
95
|
+
// Forward sanitized diagnostics to your application's monitoring.
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Handlers run serially within a conversation and concurrently across conversations. A failure leaves the message retryable. Historical messages and outgoing self copies are stored without running handlers.
|
|
100
|
+
|
|
101
|
+
`observe(observer)` observes a new receipt; it does not participate in durable processing. Register handlers before `start()`.
|
|
102
|
+
|
|
103
|
+
To reference the current message in a reply, pass its ID to `ctx.reply()`:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
await ctx.reply('Got it', { replyTo: ctx.message.id });
|
|
107
|
+
|
|
108
|
+
const parentId = ctx.message.replyTo;
|
|
109
|
+
const parent = parentId === undefined ? undefined : ctx.getMessage(parentId);
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Use `bot.getMessage(id)` to look up a local message by ID outside a handler. To send a reaction instead, call `ctx.react('👍')` or `bot.react(id, '👍')`.
|
|
113
|
+
|
|
114
|
+
### Inspect and retry
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
const result = await bot.send(peerPubkey, 'Hello');
|
|
118
|
+
// result.status: 'relay-accepted' | 'pending'
|
|
119
|
+
|
|
120
|
+
const page = bot.history(peerPubkey, { limit: 20 });
|
|
121
|
+
const state = bot.getMessageState(messageId);
|
|
122
|
+
|
|
123
|
+
await bot.retryInbox({ ids: [messageId] });
|
|
124
|
+
await bot.flushOutbox();
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Rumor IDs prevent duplicate intake across relays and restarts. Failed handlers may repeat application effects: use the message ID for application idempotency. Outbox retries reuse the original signed envelopes. Relay acceptance does not confirm delivery or reading.
|
|
128
|
+
|
|
129
|
+
History is local and paginated. Pass `page.nextCursor` to retrieve older rows; a local page does not imply a complete relay archive.
|
|
130
|
+
|
|
131
|
+
## Commands and sessions
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
const bot = new Bot<{ visits: number }>({
|
|
135
|
+
signer,
|
|
136
|
+
database: './chirli.sqlite',
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
bot.command({ command: 'visit', scopes: ['kind:14'] }, async ctx => {
|
|
140
|
+
const visits = (await ctx.session.getItem('visits') ?? 0) + 1;
|
|
141
|
+
ctx.session.setItem('visits', visits);
|
|
142
|
+
await ctx.reply(`Visit ${visits}`);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
bot.handle(async ctx => {
|
|
146
|
+
await ctx.reply('Try /visit');
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Register shared middleware with `bot.use((ctx, next) => ...)`. Middleware runs in registration order before routing. After middleware calls `next()`, the first matching command handles the message. When no command matches, the message goes to `bot.handle()`. Sessions are saved after successful processing and survive restart with persistent storage.
|
|
151
|
+
|
|
152
|
+
Declare a typed argument schema in `command()` for typed arguments. Here `value` is inferred as `bigint`, and the published `d` is `count`.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import {z} from 'zod';
|
|
156
|
+
|
|
157
|
+
bot.command(
|
|
158
|
+
{
|
|
159
|
+
command: 'count', scopes: ['kind:14'],
|
|
160
|
+
title: 'Count',
|
|
161
|
+
description: 'Read an unsigned count.',
|
|
162
|
+
args: z.object({ value: z.bigint().meta({label:'Value'}) }),
|
|
163
|
+
},
|
|
164
|
+
async (ctx, { value }) => {
|
|
165
|
+
await ctx.reply(String(value));
|
|
166
|
+
},
|
|
167
|
+
);
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
To remove or rename a command, update the declared command set and restart with the same account and relay configuration. Startup automatically withdraws definitions absent from the new registry. There is no runtime removal method.
|
|
172
|
+
|
|
173
|
+
All registered commands are public on write relays. Startup adds or updates definitions and withdraws commands absent from the local registry. Definitions use kind `31992` and withdrawals use kind `5`; there is no executor-list event. User-installed kind `10992` lists are untouched.
|
|
174
|
+
|
|
175
|
+
Definitions and scopes describe command availability. Use `inboundPolicy` to authorize senders or an `authorize` callback for an individual typed command. [Command lifecycle](docs/NIP-CD.md) · [Sender authorization](docs/ACCESS.md)
|
|
176
|
+
|
|
177
|
+
## Configuration
|
|
178
|
+
|
|
179
|
+
| Option | Purpose |
|
|
180
|
+
| --- | --- |
|
|
181
|
+
| `signer` | Required account signing and NIP-44 capabilities |
|
|
182
|
+
| `database` | SQLite path; defaults to `psstpsst.sqlite` |
|
|
183
|
+
| `messageStorage` | Message backend; defaults to `sqliteMessageStorage` |
|
|
184
|
+
| `storageKey` | Optional 32-byte key for local payload encryption |
|
|
185
|
+
| `inboundPolicy` | Optional synchronous gate for verified incoming senders |
|
|
186
|
+
| `relays` | Common list for each omitted relay role |
|
|
187
|
+
| `dmRelays` | Receive and deliver private messages |
|
|
188
|
+
| `readRelays` | Query public metadata |
|
|
189
|
+
| `writeRelays` | Publish public commands and account metadata |
|
|
190
|
+
| `discoveryRelays` | Extra targets for public account announcements |
|
|
191
|
+
| `mode` | `nip17` by default; `nip4e` enables separate messaging keys |
|
|
192
|
+
|
|
193
|
+
Preserve signer credentials, the database and any storage key across restarts. `messageStorage` stores messages, deduplication and processing state; it defaults to `sqliteMessageStorage` in the configured database. Supply `sqliteMessageStorage('./messages.sqlite')` or implement `insert`, `query` and `updateState` to use another message backend. Outbox, keys and other internal data always use SQLite configured by `database`. Custom `Transport` implementations are also supported.
|
|
194
|
+
|
|
195
|
+
### Resource lifecycle
|
|
196
|
+
|
|
197
|
+
The component that creates a resource closes it:
|
|
198
|
+
|
|
199
|
+
- Bot closes its built-in transport and storage.
|
|
200
|
+
- Your application closes injected signers, transports and storage adapters.
|
|
201
|
+
- `bot.stop()` drains handlers and keeps the Bot reusable. `bot.close()` also releases its resources.
|
|
202
|
+
|
|
203
|
+
Close Bot before its injected resources. Call stop/close outside message handlers; use `bot.requestStop()` when a handler needs to request shutdown.
|
|
204
|
+
|
|
205
|
+
### Protocol modes and recovery
|
|
206
|
+
|
|
207
|
+
Default NIP-17 uses account-key encryption. Explicit `mode: 'nip4e'` generates or restores separate messaging keys for extension peers. Both modes accept supported standard NIP-17 and NIP-4E messages.
|
|
208
|
+
|
|
209
|
+
Relay connections are pooled and reconnect independently. History recovery uses bounded overlap paging. Messages recovered after downtime remain history and do not automatically execute commands.
|
|
210
|
+
|
|
211
|
+
See [key rotation](docs/KEYS.md), [interoperability](docs/INTEROPERABILITY.md), [relay configuration](docs/RELAYS.md) and [recovery](docs/RECOVERY.md) for detailed behavior and limits.
|
|
212
|
+
|
|
213
|
+
## Development
|
|
214
|
+
|
|
215
|
+
```sh
|
|
216
|
+
npm run build
|
|
217
|
+
npm run typecheck
|
|
218
|
+
npm test
|
|
219
|
+
npm run examples:smoke
|
|
220
|
+
npm run pack:check
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`npm run check` runs the complete pipeline. Tests use disposable accounts and temporary storage; loopback integration tests require local socket binding. Package checks use a temporary tarball consumer and installed dependencies without registry access.
|
|
224
|
+
|
|
225
|
+
## Documentation
|
|
226
|
+
|
|
227
|
+
Start with the [first bot tutorial](docs/TUTORIAL.md) for a step-by-step path from the runnable demo to your own application.
|
|
228
|
+
|
|
229
|
+
| Guide | Contents |
|
|
230
|
+
| --- | --- |
|
|
231
|
+
| [API](docs/API.md) | Bot, middleware and public types |
|
|
232
|
+
| [Examples](https://github.com/CodyTseng/chirli/blob/main/examples/README.md) | Fourteen offline demos and a loopback demo |
|
|
233
|
+
| [Sessions](docs/SESSIONS.md) | Conversation state, resets and a custom SQLite session store |
|
|
234
|
+
| [Storage](docs/STORAGE.md) | Message adapters, encryption and persistence contracts |
|
|
235
|
+
| [Architecture](ARCHITECTURE.md) | Layer boundaries and failure semantics |
|
|
236
|
+
| [Contributing](CONTRIBUTING.md) | Development and validation expectations |
|
|
237
|
+
| [Security](SECURITY.md) | Trust boundaries and known limitations |
|
|
238
|
+
|
|
239
|
+
Chirli supports one-to-one private text, reply references, sending reactions, and explicitly scoped kind 1/1111 public commands. See [public inputs and threads](docs/PUBLIC.md). Groups, receiving or downloading attachments, full archive recovery and exactly-once external effects are outside its scope. One active Bot/process per account database is supported. Public relays, external signer products and production deployments require separate validation.
|
|
240
|
+
|
|
241
|
+
Bot command identifiers come from their command names; custom `id` parameters are rejected. Renaming a command removes the old coordinate and adds the new one. Startup compares one broad author-scoped kind 31992 scan per write relay with the complete local registry; runtime additions synchronize automatically. Remote kind 5 queries belong to independent discovery, while locally pending withdrawals remain durable. See [command lifecycle and upgrade behavior](docs/NIP-CD.md).
|
|
242
|
+
|
|
243
|
+
## Optional inbound policy and processing timing
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
import { Bot, allowlist, requestTiming } from 'chirli';
|
|
247
|
+
|
|
248
|
+
const bot = new Bot({ signer, inboundPolicy: allowlist(trustedIdentityPubkeys) });
|
|
249
|
+
bot.use(requestTiming({ onTiming: metric => { console.info(metric); } }));
|
|
250
|
+
bot.command({ command: 'ping', scopes: ['kind:14'] }, async ctx => { await ctx.reply('pong'); });
|
|
251
|
+
await bot.start(); // Command declarations remain automatic.
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
`inboundPolicy` runs after identity verification and before incoming history, peer evidence, observers or business callbacks. `allowlist` snapshots the supplied lowercase hex identity keys. `allowlist([])` denies every external sender. Middleware registered through `bot.use()` runs after receipt persistence. [Sender authorization](docs/ACCESS.md)
|
|
255
|
+
|
|
256
|
+
`requestTiming({onTiming})` is optional ordinary middleware. Its observer receives only `{durationMs,outcome:'success'|'failure'}` for the downstream processing chain. It never reads message context or error details, does not log by default and cannot let observer failures change processing. It excludes receipt/decryption, queue waiting and session commit after the chain; no command route name is inferred from text. See [API](docs/API.md).
|
|
257
|
+
|
|
258
|
+
## Public input and shared context
|
|
259
|
+
|
|
260
|
+
Register one explicitly scoped command for DMs, notes and comments. Public reads require `publicInbox: {relays: [...]}`; they never use implicit default relays. `ctx.input` contains the authenticated input, `ctx.reply()` chooses encrypted DM or public kind 1111, and `await ctx.thread({limit:30})` lazily loads prior context. Public context/session storage never reads private conversations.
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
const bot = new Bot({signer, publicInbox:{relays:publicInboxRelays}});
|
|
264
|
+
bot.command({command:'ping',scopes:['kind:14','kind:1','kind:1111']}, async ctx => {
|
|
265
|
+
await ctx.reply('pong');
|
|
266
|
+
});
|
|
267
|
+
await bot.start();
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
Run `npm run example:public` for an offline three-kind demo and deterministic application-owned `/summarize` mock. See [targeting, replies, thread bounds and migration](docs/PUBLIC.md).
|
|
271
|
+
|
|
272
|
+
For application-owned background work, retain `ctx.input.event` and later call `await bot.thread(event,{limit:30})` and `await bot.reply(event,text)`. Both preserve private/public routing and reuse handler semantics. DM authentication requires the same account's retained incoming record; a public target requires the complete signed event. See [delayed calls and trust requirements](docs/API.md#replies-and-context-after-a-handler), or run `npm run example:async-reply` entirely offline.
|
|
273
|
+
|
|
274
|
+
Command `args` accepts a Zod 4 `z.object(...)` directly. The schema both generates NIP-CD metadata and validates decoded input; handler-only `ctx.args` and the second handler argument share the inferred valid result. Use middleware or `bot.catch` for centralized `InvalidArgsError` handling; no automatic error reply or retry is added. See [schema support and authorization boundaries](docs/API.md#zod-command-arguments).
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Security policy
|
|
2
|
+
|
|
3
|
+
Chirli is experimental. It has not had an independent security audit. No supported-release or response-time commitment has been established.
|
|
4
|
+
|
|
5
|
+
## Reporting
|
|
6
|
+
|
|
7
|
+
Use GitHub's private vulnerability reporting form to contact the Chirli maintainers. [Report a vulnerability](https://github.com/CodyTseng/chirli/security/advisories/new)
|
|
8
|
+
|
|
9
|
+
Include the affected version and mode, expected and actual behavior, impact, sanitized diagnostics and a minimal local reproduction with disposable keys. Keep live credentials and private messages out of reports. Use the private channel for vulnerability details.
|
|
10
|
+
|
|
11
|
+
## Boundaries
|
|
12
|
+
|
|
13
|
+
- The decoder verifies the giftwrap, seal, rumor hash, author and one-to-one recipient before exposing text. Default identity-key NIP-17 and explicit split-key mode both accept verified standard and NIP-4E envelopes; the legacy compatibility:false flag only suppresses identity-key declaration publication. Known unrelated own key declarations block publication; discovery freshness is bounded by relays/cache, not globally guaranteed. See docs/INTEROPERABILITY.md.
|
|
14
|
+
- Database payloads use AES-256-GCM only when storageKey is supplied; otherwise payloads/keyrings are explicitly tagged plaintext without cryptographic tamper protection; public routing metadata and status/timestamp indexes remain visible. Core Bot does not store identity signing secrets; the live application can persist a generated signer in a private adjacent file. Split encryption keys and pending declarations follow the configured plaintext/encrypted codec. Preserve the original storageKey whenever encryption is enabled. Protect storage keys, files, backups, process memory and your own logs.
|
|
15
|
+
- Incoming rumor IDs deduplicate protocol receipt, not arbitrary external side effects. Failed/incomplete business work can run again. Relay acceptance means neither delivery nor reading.
|
|
16
|
+
- Historical and self-copy messages do not run live handlers. A new subscription, including one after AUTH, treats frames before EOSE as history. Downtime messages may be synchronized without executing old commands.
|
|
17
|
+
- Untrusted relay URLs come from signed metadata or application configuration. The SDK makes outbound WebSocket connections to them; applications deploying in restricted networks must enforce their own destination policy. There is no built-in SSRF allowlist or tenant boundary.
|
|
18
|
+
- Identity signers must sign the exact requested template. Both modes retain identity-key crypto for standard peers; split mode adds generated/imported current, pending and legacy local keys. Neither mode supplies forward secrecy or key-vault isolation by itself.
|
|
19
|
+
- Error observers can see verified message context and application errors. Observer failures are ignored so monitoring cannot crash message processing; sanitize logging and handle telemetry failures in your application.
|
|
20
|
+
|
|
21
|
+
One active process/client per account database, including across modes, is supported. Synchronous storage and crypto execute on the Node thread, and received-event history/dispatch queues are not a production-grade resource admission system. Full archive enumeration, undecryptable-envelope retention, storage-key migration, distributed workers and application authorization are outside this MVP. See README and API.md before deployment.
|
|
22
|
+
|
|
23
|
+
The checked-in CI uses only disposable/local protocol tests. Actual public relays, mobile apps, external bunker products and hardware signers and production deployments require separate assessment. No real AI provider or external tool execution is part of this SDK.
|
|
24
|
+
|
|
25
|
+
Managed subscriptions reconnect with bounded backoff and overlap paging; raw transport alone does not. Recovered envelopes never execute live commands, and incomplete scans leave checkpoints unchanged. A remote signer sees plaintext used in NIP-44 operations. Its operational failures are surfaced and stop recovery checkpoint advancement. Opaque remote decryption errors are conservatively treated as retryable, so corrupt signed wrappers can also leave a remote scan incomplete; there is no durable raw-envelope quarantine or product-specific error classification. See SIGNERS.md and RECOVERY.md.
|
|
26
|
+
|
|
27
|
+
Registered NIP-CD definitions are always public on configured write relays. Bot startup reconciles its account's complete registry, including deleting old definitions absent locally. Register every module before starting one account owner. Ordinary Clients do not own catalogs or modify user-installed kind 10992 lists. All write-relay queries/publications must succeed before Bot startup completes. An unavailable or known truncated snapshot never becomes deletion evidence. Metadata/scopes grant no execution permission, and public withdrawal cannot erase cached copies.
|
|
28
|
+
|
|
29
|
+
Explicit keyRotation configuration authorizes scheduled public encryption-key declarations while started. Candidates are durable before publication; ACK failure keeps pending custody and retries the same event. Retired-key count/optional age pruning happens only after successful rotation. Evicted keys cannot decrypt unseen old envelopes; SQLite/WAL/backups are not securely erased. Known foreign declarations require explicit locally held-key migration, never forced overwrite. Relay/cache checks are not a globally fresh account lock. See [key custody and migration](docs/KEYS.md).
|
|
30
|
+
|
|
31
|
+
Custom MessageStorage implementations receive encoded messages, processing state and public routing metadata, never storageKey, keyrings, evidence or outbox records. They are trusted for durable unique insertion, state updates and account isolation; losing or changing done states can cause repeated handling. With storageKey, payloads are ciphertext; without it they are readable plaintext. Internal SQLite retains only temporary message handoffs until insertion succeeds. Protect both stores and follow docs/STORAGE.md. Multiple-relay discovery can be partial; cached evidence is not a globally fresh declaration guarantee. At least one ACK is not all-relay replication. See docs/RELAYS.md.
|
|
32
|
+
|
|
33
|
+
Bot allowlist is checked against the verified seal/rumor identity in both modes before new history, peer evidence or business callbacks. Anonymous wrapper authors and separated n encryption keys grant no authorization. Empty lists deny all external incoming senders; absent lists preserve open intake. Rejected new rumors have no durable denial receipt, so policy changes can admit later live presentations. Revoked pending business work is consumed without callbacks; old history remains readable. Crypto/remote signer work and operational error monitoring still occur before a hidden sender can be authenticated. This inbound policy is not an outbound ACL or rate limiter. See [access](docs/ACCESS.md).
|
|
34
|
+
|
|
35
|
+
The optional live-example initializer creates a fresh bot nsec/storageKey in an ignored 0600 .env file; this is operator credential storage, separate from SDK keyring persistence and not a hardware vault. Live runners intentionally read operator configuration only when explicitly started, publish their own key/relay metadata and registered public commands and respond to permitted DMs. They do not print incoming text, credentials or bunker authorization URLs. Protect config/database backups. Automated tests use generated temporary configs and local relays only.
|
|
36
|
+
|
|
37
|
+
Zero-config live startup reuses/creates a 0600 identity file beside the database and logs only public keys. That file is encrypted if CHIRLI_STORAGE_KEY is provided, otherwise plaintext. It is never overwritten to fix parsing/key/mode errors. Existing databases without their generated signer file require the original signer to avoid silently changing accounts. Default public relays match PsstPsst; testing does not connect to them. Plaintext persistence assumes trusted filesystem/backend contents, including pending business records. Initial wire signature/author validation and NIP-44 encryption remain mandatory in either storage mode.
|
|
38
|
+
|
|
39
|
+
Built-in RelayError diagnostic fields expose only origin, operation/code, whitelisted network/reason codes and numeric statuses/kinds. Relay paths/queries/credentials, raw rejection bodies, AUTH challenges and message text are withheld. The live formatter does not print arbitrary application Error.message/stack and bounds aggregate recursion. Explicit custom application logging remains the application's responsibility. Read-only operator connectivity diagnostics do not require a private key or event publication.
|
|
40
|
+
|
|
41
|
+
Automatic NIP-4E device sync is enabled by default. Only verified requests signed by the exact account identity can export held separated keys, and only encrypted 4455 responses are published. Identity signing secrets are excluded. This headless policy authenticates signing capability, not human presence; permission to sign 4454 is secret-transfer authorization. Use keySync:false / CHIRLI_KEY_SYNC=0 if this is unsuitable. Imported responses must bind to the exact ephemeral requester and latest observed 10044 before durable custody/activation. Requests are freshness-bounded and completed IDs are journaled. See [automatic key sync](docs/KEYS.md#automatic-same-identity-key-synchronization).
|
|
42
|
+
|
|
43
|
+
Own metadata subscriptions and peer cache hold only verified signed state; newest observed does not mean globally fresh. Stale peer routes/keys can temporarily remain in use within the documented cache window. Missing peer 10050 uses own DM relay fallback, so peer receipt is not guaranteed. Metadata snapshots are instance-local memory; durable seal/declaration ordering remains in the existing store. Full lookup failures do not establish a successful absence; fallback after total failure requires existing authenticated key evidence.
|
|
44
|
+
|
|
45
|
+
Construct a Bot with a signer. Its startup resolves the account through Signer.getPublicKey and uses Signer.signEvent and NIP-44 operations. Signer implementations keep the credentials, and the application owns their lifetime. Receipt callbacks registered with `observe()` receive detached snapshots. Use durable handlers for business effects, with application idempotency where retry can repeat an effect.
|
|
46
|
+
|
|
47
|
+
Startup command reconciliation uses author-scoped kind 31992 snapshots only; signature/author checks and detectably incomplete-read failures remain mandatory. Fresh absence does not make confirmed local cache into remote presence. Relays can silently omit/cap results, and public operations across replicas are not atomic. Independent discovery still verifies kind 5 withdrawals to exclude stale definitions. Unsupported legacy journal event kinds are dropped before replay; supported pending command operations retain exact IDs.
|
|
48
|
+
|
|
49
|
+
The `allowlist` helper supplies an inbound policy over the authenticated sender string. The policy runs before incoming persistence, evidence and observers and is rechecked for pending work. An explicit boolean `true` authorizes the sender. `requestTiming` telemetry contains only elapsed milliseconds and chain outcome and isolates observer failures. Applications supply custom policies and observers. Business middleware starts after receipt persistence.
|
|
50
|
+
|
|
51
|
+
Public kind 1/1111 input requires an explicit inbox and declared supported scopes. Signature, source, author policy, structure and unambiguous invocation targeting are checked before the separate public journal or business middleware. Public session/thread methods never load private peer data. Public replies are intentionally public kind 1111, routed only to configured write/source relays; arbitrary tag URLs are not contacted. Public thread scope claims are signed claims, not proof of truthful ancestry, and resolved context remains untrusted application input. Public ID deduplication retains at most 5000 records; eviction, failed handlers and uncertain completion prevent an exactly-once guarantee. Public queued payloads/outbox use the same selected storage codec as internal metadata. See [public input boundaries](docs/PUBLIC.md).
|
|
52
|
+
|
|
53
|
+
Delayed `bot.reply(event,...)` / `bot.thread(event,...)` calls use original input events, never arbitrary IDs or outer envelopes. Signed public events are independently reverified; source provenance is local-journal-only. Unsigned DM rumors must match the account/mode's persisted authenticated incoming record, canonical hash/fields and private routing; a rumor's ID or asserted sender alone grants no trust. Applications own their worker queues and must protect saved DM events as plaintext. Calls are explicit application effects, not inbound policy dispatch; repeated calls are not deduplicated as jobs. See docs/API.md.
|
|
54
|
+
|
|
55
|
+
The nostr-tools transport uses a native JSON syntax preflight and canonical EVENT framing to prevent malformed inputs from reaching the dependency raw logger. Non-string CLOSED reasons are normalized to a constant safe rejection. The library uses an origin-only diagnostic label while the socket and NIP-42 tag preserve the exact configured URL. Tests cover malformed/truncated EVENT and control JSON with synthetic token/content values. This framing guard adds one native JSON decode before library decoding; it is not an independent Nostr parser or a guarantee about all future dependency diagnostics. See docs/RELAYS.md for tested boundaries and remaining ACK/keepalive timer behavior.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
Chirli is licensed under MIT. The [LICENSE](LICENSE) includes the project's copyright and retains the inherited attributions.
|
|
4
|
+
|
|
5
|
+
PsstPsst protocol behavior and compatibility fixture generation are derived from the MIT-licensed PsstPsst project by Cody Tseng. Its complete original license, including the Expo attribution, is retained in LICENSE. The fixture generator extracts unchanged envelope functions from an explicitly supplied upstream source file; that temporary source is removed after fixture generation. No application account key material is included. The fixture contains only randomly generated disposable encryption keys.
|
|
6
|
+
|
|
7
|
+
References inspected (read-only):
|
|
8
|
+
- PsstPsst `docs/protocols/nip4e.md`, `docs/protocols/nip17-extensions.md`
|
|
9
|
+
- `src/services/crypto/nip17-gift-wrap.ts` and its tests
|
|
10
|
+
- `src/services/dm/observed-peer-key.service.ts`, `peer-encryption-key.service.ts`, and receive logic in `dm.service.ts`
|
|
11
|
+
- PsstPsst relay `docs/filters.md`, `README.md`, and executable entry point. Relay software is built externally for optional interoperability testing, not copied or distributed here.
|
|
12
|
+
|
|
13
|
+
Runtime dependencies: nostr-tools 2.26.0 (Unlicense), ws (MIT). Development dependencies: TypeScript (Apache-2.0), tsx (MIT), @types/node and @types/ws (MIT); transitive dependencies retain their own licenses in the installed packages. package-lock.json records exact versions. No grammY implementation was copied; the bot API is an original minimal middleware/command layer inspired by the familiar framework model.
|
|
14
|
+
|
|
15
|
+
The default standard mode follows the official nostr-protocol NIP-17, NIP-59 and NIP-44 specifications (checked 2026-11-15). Its tests use the installed Unlicense-licensed nostr-tools NIP-17 helpers as an independent wire-format reference. No additional implementation was copied from those specifications or another bot framework.
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## License verification for this checkout
|
|
19
|
+
|
|
20
|
+
Direct dependency/license metadata and license files were inspected locally on 2026-11-15: nostr-tools 2.26.0 uses Unlicense; ws 8.22.0 uses MIT. The earlier notice calling nostr-tools MIT was incorrect and has been corrected. TypeScript 5.9.3 uses Apache-2.0; tsx 4.23.15, @types/node 24.19.2 and @types/ws 8.18.2 use MIT. The lockfile records the exact versions and transitive license metadata; installed dependency directories retain their original license texts.
|
|
21
|
+
|
|
22
|
+
Dependencies are not bundled into the Chirli tarball. Compiled SDK/examples are original project code; the local relay fixture is maintained within this project. The upstream PsstPsst source extraction generator and disposable-key compatibility fixture remain development-only and are excluded from the npm artifact. No source code was copied from grammY or another bot framework. Do not remove upstream notices if redistributing derived fixtures or regenerated source.
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
The headless reconnect/pager and signer adapters were informed by additional read-only MIT PsstPsst references: `src/services/relay/managed-relay-pool.ts`, `src/services/dm/gift-wrap-pager.ts`, reconnect recovery in `dm.service.ts`, `src/services/signer/nsec-signer.ts`, `nip46-signer.ts`, and `nip46-timeout.ts`. This project adapts their lifecycle concepts rather than importing application/platform code. Applicable original MIT notices remain intact. Bunker wire transport is provided by installed nostr-tools 2.26.0 (Unlicense); the SDK's adapter and local mock RPC fixture are original code. The standard NIP-46 specification was also checked; no real bunker credentials or account key material were read.
|
|
26
|
+
|
|
27
|
+
Draft NIP-CD support was implemented against the official nostr-protocol NIP-CD, NIP-01 addressable-event and NIP-09 deletion specifications checked 2026-11-15. No third-party command framework implementation was copied. The SDK-specific DM projection and parsing/discovery boundaries are documented in docs/NIP-CD.md.
|
|
28
|
+
|
|
29
|
+
Identity-key interoperability additionally references PsstPsst's native iOS/Android account decrypt paths (which require the first `n` seal tag), its current 10044 declaration handling, and the open NIP-4E proposal (nostr-protocol/nips PR 1647, `per-device-keys/4e.md`). The unique temporary extraction helper exercises unchanged MIT software-envelope functions solely for optional testing; no app runtime, vault or account data is loaded. A committed disposable-key identity-recipient fixture retains source SHA-256 provenance. No reference checkout was modified.
|
|
30
|
+
|
|
31
|
+
Configurable key rotation additionally references read-only PsstPsst `src/services/dm/encryption-key-rotation.service.ts`, `encryption-key-rotation-prefs.ts`, and native iOS/Android messaging-key vault retention (ten total records). Chirli implements its own encrypted Node SQLite custody and pending-ACK state machine with an explicit configurable retired-key policy; no native vault code, stored accounts or credentials were copied. Existing MIT notices are retained.
|
|
32
|
+
|
|
33
|
+
Incoming allowlist identity extraction was checked against the read-only PsstPsst software envelope identity-binding checks (seal author equals verified rumor author). Chirli's policy, pending-work handling and tests are original SDK code; no application allowlist/authorization implementation or account data was imported.
|
|
34
|
+
|
|
35
|
+
The default DM relay URL list is derived from read-only PsstPsst src/lib/nostr/relay-url.ts DEFAULT_DM_RELAYS on 2026-11-15, with nip17.com intentionally removed by Chirli configuration policy on 2026-11-16. Chirli does not import that application module or test/publish against those public endpoints. Existing MIT attribution is retained.
|
|
36
|
+
|
|
37
|
+
Read/write relay defaults and publication routing were additionally checked against read-only PsstPsst `src/services/relay/relay-list.service.ts`, `relay-router.ts`, and `src/lib/nostr/relay-url.ts` DISCOVERY_RELAYS. Chirli uses PsstPsst's read/write fallback URLs and independently implements SDK role routing/publication. NIP-65 kind 10002 tags follow the official nostr-protocol/nips specification. Existing MIT source attribution is retained; no account configuration or application module was imported.
|
|
38
|
+
|
|
39
|
+
Peer caching/refresh and automatic encrypted key transfer additionally reference read-only MIT PsstPsst `src/services/dm/peer-encryption-key.service.ts`, `observed-peer-key.service.ts`, `encryption-key.service.ts`, `key-sync-session.ts`, `src/services/relay/relay-list.service.ts`, and its NIP-4E protocol profile. Chirli independently implements own-account live subscriptions, instance-local bounded peer caching and headless same-identity signature authorization. The source app's UI approval requirement is intentionally not copied; Chirli documents its automatic policy and disable option. Existing MIT notices remain unchanged.
|
|
40
|
+
|
|
41
|
+
## Jumble structural reference
|
|
42
|
+
|
|
43
|
+
Public kind 1/1111 root/parent parsing, mixed-thread batching and relay-routing design were informed by read-only review of Jumble (`src/lib/draft-event.ts`, `src/lib/event-core.ts`, `src/services/thread.service.ts`, `src/services/client.service.ts`), MIT License, Copyright (c) 2025 Cody Tseng. Chirli's bounded headless resolver and isolated public journal were implemented locally; no Jumble runtime or dependency is bundled. The project's existing MIT license text is retained. Protocol references are NIP-22 and the NIP-CD draft.
|
|
44
|
+
|
|
45
|
+
Command argument declaration and validation uses Zod 4 (MIT), through the installed package API. Zod is a runtime dependency, not bundled source. The dependency retains its upstream MIT license. The bounded schema-to-NIP-CD projection uses documented Zod 4 schema definitions/metadata and is original Chirli code; it does not copy a command framework.
|
|
46
|
+
|
|
47
|
+
Relay stability was additionally checked against read-only Jumble `src/lib/managed-relay.ts`, `relay-subscription.ts`, and `relay-pool-lifecycle.ts` (MIT, Copyright (c) 2025 Cody Tseng), plus PsstPsst `src/services/relay/lifecycle-relay.ts`, `managed-relay-pool.ts`, `src/services/dm/gift-wrap-pager.ts` and `dm.service.ts` under the retained upstream MIT notice. Chirli independently adapts current-attempt health and once-only local initialization; no client UI, account state, source implementation or platform lifecycle hook is bundled by this change.
|
|
48
|
+
|
|
49
|
+
Production relay connections use the public nostr-tools AbstractRelay and Subscription APIs. No upstream relay implementation was copied; Chirli retains its own demand, recovery, and strict query policy. The adapter and differences from the reference clients are documented in docs/RELAYS.md.
|
|
50
|
+
|
|
51
|
+
Private file sending was checked against PsstPsst’s Blossom upload and kind-15 attachment format and Jumble’s Blossom server-list and attachment handling. Chirli uses Node.js crypto and HTTP APIs and independently implements the applicable NIP-17 and Blossom BUD-02, BUD-03 and BUD-11 wire formats. No application source or additional dependency is bundled.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Event, EventTemplate } from 'nostr-tools';
|
|
2
|
+
import { type Identity } from './protocol.js';
|
|
3
|
+
import type { Store } from './store.js';
|
|
4
|
+
import type { Transport } from './relay.js';
|
|
5
|
+
export interface Announcement {
|
|
6
|
+
template: EventTemplate;
|
|
7
|
+
groups: string[][];
|
|
8
|
+
optionalRelays?: string[];
|
|
9
|
+
}
|
|
10
|
+
/** Durable public metadata retry. No command handlers, registry privacy inference or installation lists. */
|
|
11
|
+
export declare class Announcements {
|
|
12
|
+
private identity;
|
|
13
|
+
private store;
|
|
14
|
+
private transport;
|
|
15
|
+
private published?;
|
|
16
|
+
private state;
|
|
17
|
+
private operation?;
|
|
18
|
+
constructor(identity: Identity, store: Store, transport: Transport, published?: ((event: Event) => void) | undefined);
|
|
19
|
+
private save;
|
|
20
|
+
private serialize;
|
|
21
|
+
publish(announcements: Announcement[]): Promise<void>;
|
|
22
|
+
private drain;
|
|
23
|
+
hasPending(): boolean;
|
|
24
|
+
idle(): Promise<void>;
|
|
25
|
+
}
|