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.
Files changed (97) hide show
  1. package/ARCHITECTURE.md +103 -0
  2. package/CONTRIBUTING.md +56 -0
  3. package/LICENSE +22 -0
  4. package/README.md +281 -2
  5. package/SECURITY.md +55 -0
  6. package/THIRD_PARTY_NOTICES.md +51 -0
  7. package/dist/allowlist.d.ts +3 -0
  8. package/dist/allowlist.js +9 -0
  9. package/dist/announcements.d.ts +25 -0
  10. package/dist/announcements.js +142 -0
  11. package/dist/attachments.d.ts +43 -0
  12. package/dist/attachments.js +340 -0
  13. package/dist/blossom.d.ts +30 -0
  14. package/dist/blossom.js +233 -0
  15. package/dist/bot-handlers.d.ts +70 -0
  16. package/dist/bot-handlers.js +317 -0
  17. package/dist/bot.d.ts +63 -0
  18. package/dist/bot.js +244 -0
  19. package/dist/client.d.ts +221 -0
  20. package/dist/client.js +1197 -0
  21. package/dist/command-discovery.d.ts +4 -0
  22. package/dist/command-discovery.js +33 -0
  23. package/dist/command-schema.d.ts +4 -0
  24. package/dist/command-schema.js +101 -0
  25. package/dist/commands.d.ts +32 -0
  26. package/dist/commands.js +253 -0
  27. package/dist/defaults.d.ts +9 -0
  28. package/dist/defaults.js +22 -0
  29. package/dist/errors.d.ts +55 -0
  30. package/dist/errors.js +126 -0
  31. package/dist/inbox.d.ts +55 -0
  32. package/dist/inbox.js +376 -0
  33. package/dist/index.d.ts +25 -0
  34. package/dist/index.js +11 -0
  35. package/dist/key-sync.d.ts +33 -0
  36. package/dist/key-sync.js +293 -0
  37. package/dist/keys.d.ts +66 -0
  38. package/dist/keys.js +418 -0
  39. package/dist/message-storage-sqlite.d.ts +6 -0
  40. package/dist/message-storage-sqlite.js +90 -0
  41. package/dist/message-storage.d.ts +32 -0
  42. package/dist/message-storage.js +1 -0
  43. package/dist/messaging-metadata.d.ts +48 -0
  44. package/dist/messaging-metadata.js +280 -0
  45. package/dist/metadata.d.ts +7 -0
  46. package/dist/metadata.js +63 -0
  47. package/dist/modes.d.ts +26 -0
  48. package/dist/modes.js +108 -0
  49. package/dist/nip4e-compat.d.ts +4 -0
  50. package/dist/nip4e-compat.js +14 -0
  51. package/dist/nipcd.d.ts +109 -0
  52. package/dist/nipcd.js +555 -0
  53. package/dist/protocol.d.ts +68 -0
  54. package/dist/protocol.js +302 -0
  55. package/dist/public-inbox.d.ts +66 -0
  56. package/dist/public-inbox.js +295 -0
  57. package/dist/public-thread.d.ts +62 -0
  58. package/dist/public-thread.js +436 -0
  59. package/dist/relay-pool.d.ts +43 -0
  60. package/dist/relay-pool.js +429 -0
  61. package/dist/relay-roles.d.ts +18 -0
  62. package/dist/relay-roles.js +55 -0
  63. package/dist/relay.d.ts +52 -0
  64. package/dist/relay.js +493 -0
  65. package/dist/request-timing.d.ts +12 -0
  66. package/dist/request-timing.js +37 -0
  67. package/dist/session.d.ts +16 -0
  68. package/dist/session.js +51 -0
  69. package/dist/signer.d.ts +13 -0
  70. package/dist/signer.js +1 -0
  71. package/dist/signers/bunker-relays.d.ts +15 -0
  72. package/dist/signers/bunker-relays.js +87 -0
  73. package/dist/signers/bunker.d.ts +7 -0
  74. package/dist/signers/bunker.js +194 -0
  75. package/dist/signers/nsec.d.ts +3 -0
  76. package/dist/signers/nsec.js +62 -0
  77. package/dist/signers.d.ts +18 -0
  78. package/dist/signers.js +59 -0
  79. package/dist/storage-sqlite.d.ts +29 -0
  80. package/dist/storage-sqlite.js +221 -0
  81. package/dist/storage.d.ts +85 -0
  82. package/dist/storage.js +1 -0
  83. package/dist/store.d.ts +96 -0
  84. package/dist/store.js +404 -0
  85. package/docs/ACCESS.md +28 -0
  86. package/docs/API.md +382 -0
  87. package/docs/INTEROPERABILITY.md +32 -0
  88. package/docs/KEYS.md +75 -0
  89. package/docs/NIP-CD.md +112 -0
  90. package/docs/PUBLIC.md +88 -0
  91. package/docs/RECOVERY.md +59 -0
  92. package/docs/RELAYS.md +145 -0
  93. package/docs/SESSIONS.md +108 -0
  94. package/docs/SIGNERS.md +59 -0
  95. package/docs/STORAGE.md +71 -0
  96. package/docs/TUTORIAL.md +178 -0
  97. package/package.json +47 -4
@@ -0,0 +1,103 @@
1
+ # Architecture
2
+
3
+ Chirli is a Node.js SDK for Nostr private messages with text or attachments and explicitly scoped public commands. Applications own authorization, business effects, signer credentials and deployment. `src/index.ts` is the public entry point.
4
+
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()` resolves kind scopes and validates 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 opens inbox subscriptions and retries outgoing publications. It never replays claimed business inputs. Every write relay must accept command reconciliation. One ready DM replica can serve the Bot while other DM replicas reconnect.
32
+ 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`, `stop` or `close` reject; `requestStop()` requests shutdown without waiting on the caller.
35
+
36
+ ## Incoming messages
37
+
38
+ See the [event processing flow](docs/API.md#event-processing-flow) for the complete path from authentication to outgoing publication.
39
+
40
+ Giftwrap and seal signatures, rumor hash/author, times and one-to-one routing are verified before persistence. After verification, internal SQLite checks the persisted first DM activation time per identity and database against the inner rumor timestamp; both live delivery and catch-up use this guard. Eligible incoming DMs claim their canonical ID in the account/mode scope before any business middleware. Multiple giftwraps for the same rumor do not create multiple attempts.
41
+
42
+ - An unseen live claim may enter the serial conversation queue; different conversations can proceed concurrently.
43
+ - A middleware stop, failure or crash does not reopen the claim. The SDK does not store an incoming callback payload to replay.
44
+ - Routing retains an admitted live DM in private conversation history and sends detached copies to receipt observers. Passive historical inputs claim only their IDs, while outgoing self copies can still populate private history.
45
+ - Conversation history and outgoing publication have separate lifecycles from the ID claim. Applications own durable jobs, session coordination and idempotency for external effects.
46
+
47
+ ## Outgoing messages
48
+
49
+ A private reply references its parent rumor ID through an `e` tag inside the encrypted event. Outgoing kind-7 reactions use the same private envelope and durable outbox. Private history and dispatch accept kind 14 text and kind 15 file messages. Kind 15 uses the normal middleware and fallback handler and bypasses text command matching. Attachment retrieval is explicit, and verified plaintext files are stored by hash in a local per-account cache. Recipient metadata is resolved before queuing. A temporary outgoing message handoff and exact signed envelopes commit together before publication; the message is then inserted into MessageStorage before normal send publication. Each recipient/self envelope requires at least one relay ACK. Failure keeps the bundle pending; retries reuse its IDs and ciphertext.
50
+
51
+ Relay acceptance does not establish delivery or reading. A new `send()` call creates a new logical message.
52
+
53
+ ## Public commands
54
+
55
+ 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.
56
+
57
+ 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.
58
+
59
+ 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.
60
+
61
+ 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.
62
+
63
+ ## Protocol and keys
64
+
65
+ 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.
66
+
67
+ 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.
68
+
69
+ A remote signer sees NIP-44 plaintext it processes. Operational signer failures remain retryable and prevent recovery checkpoints from advancing.
70
+
71
+ ## Network and storage limits
72
+
73
+ 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.
74
+
75
+ 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`.
76
+
77
+ Recovered frames remain history. Saturated timestamp boundaries, page limits or failed reads leave coverage incomplete. No full archive or durable undecryptable-envelope quarantine is promised.
78
+
79
+ Store applies AES-GCM when a storage key is supplied, otherwise tagged plaintext. MessageStorage owns retained private conversation records and their diagnostic states. Internal SQLite owns atomic inbound ID claims. Its default sqliteMessageStorage uses indexed native queries. Internal SQLite owns outbox, keys, metadata and temporary cross-store handoffs, and accepts only a database path. Failed history handoffs can be repaired without replaying callbacks or replacing existing message state; internal message copies are removed after successful insertion. Use a fresh database for this storage format; no migration from earlier pre-release formats is provided. The SDK supports one active Client/process per account database. Distributed claims, admission/backpressure limits, pruning, forward secrecy and exactly-once external effects remain outside its scope.
80
+
81
+ ## References and validation
82
+
83
+ Protocol reference: PsstPsst checkout `5e6940fe6daa130d4143bf457078c3768202cc10`. Relay reference: `d7873d66fd1c0e6dbb0aaa2f55475944c4ba57ce`. Committed fixtures record upstream provenance; generation scripts use disposable keys without loading application state.
84
+
85
+ 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.
86
+
87
+ See [API](docs/API.md), [command lifecycle](docs/NIP-CD.md), [key custody](docs/KEYS.md), [storage](docs/STORAGE.md), [recovery](docs/RECOVERY.md) and [third-party notices](THIRD_PARTY_NOTICES.md).
88
+
89
+ ## Optional access and timing middleware
90
+
91
+ `allowlist` returns ordinary middleware over the authenticated input identity. It runs only on a claimed live attempt, like other registered middleware. `request-timing.ts` supplies downstream middleware with a frozen duration and outcome metric and isolates observer callbacks from processing.
92
+
93
+ ## Public input isolation
94
+
95
+ `public-inbox.ts` owns a separate verified kind 1/1111 subscription. Only matching, unambiguously targeted registered commands enter business middleware. Admission checks signatures, source relay, structure, scope and invocation before atomically claiming the event ID. There is no durable public input body or processing journal. Per-root queues and `public:` session keys never use DM message rows or peer sessions. `bot.observe`, message history/state/listing remain DM-only.
96
+
97
+ `public-thread.ts` parses legacy/NIP-22 topology, batches a root across legacy `#e` and modern `#E` (plus coordinate variants), and follows only the trigger ancestor branch under one deadline and size/lookup/depth limits. Public replies (kind 1111) and NIP-25 reactions (kind 7) share a durable outbox, configured write/source destinations, and exact-ID retries. Transport queries have no cancellation API; a timed-out resolver returns while already acquired transport queries settle under transport budgets. Stop drains active processing and cancels subscription/reconnect demand.
98
+
99
+ ## Event-based delayed actions
100
+
101
+ Reply, reaction and thread calls resolve a detached original input event into either an exact account-bound authenticated incoming DM record or a reverified public target. Bot exposes that path directly, and handler methods capture independent anchor snapshots and use the same execution. Public target lookup retains no new event-body index: a signed supplied event is sufficient, and only the immediate handler context retains known source provenance. Private thread reads retain the original record cutoff. No job queue or idempotency layer is introduced.
102
+
103
+ Command args use a single Zod 4 object. command-schema.ts projects its supported positional subset into unchanged wire CommandArgument metadata at registration. Ordinary middleware precedes decoding/validation. Only recognized target/scope matches can raise a framework terminal InvalidArgsError. Such errors are consumed after centralized observation; operational/business errors are reported without retrying the callback. Args-dependent authorization suppresses invalid-input response hooks; valid authorization and command-only context use Zod's parsed output.
@@ -0,0 +1,56 @@
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 npm tarball contains the SDK and documentation. The check runs demos and live CLI help from the checkout against the packed SDK. Local WebSocket tests and the loopback demo need permission to bind loopback sockets. No public relays, account keys, or paid APIs are required.
15
+
16
+ Run `npm run pack:release` to build, verify, and write the release tarball to the checkout. The checkout manifest is private and keeps the development scripts. Publish the verified tarball with `npm publish ./chirli-<version>.tgz`.
17
+
18
+ Use `npm run format` to apply Biome's default formatting and `npm run lint` to see its recommended lint warnings and errors. `npm run check:style` is the read-only CI style check; formatting differences and lint errors fail it. Biome covers JS/TS under `src`, `test`, `examples` and `scripts`, excluding fixtures. TypeScript still runs separately.
19
+
20
+ `npm test` uses temporary identities/databases. Two optional tests require an externally built PsstPsst Go relay:
21
+
22
+ ```sh
23
+ PSST_RELAY_BIN=/absolute/path/to/local-relay npm test
24
+ ```
25
+
26
+ 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.
27
+
28
+ ## Scope and changes
29
+
30
+ - 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.
31
+ - Verify signatures, authors, IDs and recipients before persisting or exposing messages. Do not bypass verification caches by trusting a previously marked object.
32
+ - Deduplicate by rumor ID. Keep protocol receipt, business status and relay acceptance separate.
33
+ - 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.
34
+ - Keep documentation, examples, comments and diagnostics in clear English. Follow existing TypeScript formatting; no formatter or linter is currently mandated.
35
+ - Never commit credentials, real account events, personal databases, or application plaintext. The committed protocol fixture uses disposable keys; keep its provenance and license notice.
36
+ - 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.
37
+
38
+ 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.
39
+
40
+ ## Reports and licensing
41
+
42
+ 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)
43
+
44
+ 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).
45
+
46
+ NIP-CD is a draft integration. Retain stable command coordinates and signature/deletion handling. Commands are always public on configured write relays; Bot startup reconciles the complete local registry before dispatch. Keep kind 31992 definitions and kind 5 withdrawals distinct from standard user-installed list 10992. Bot coordinates are command-name derived; wire decoding retains external d values. Do not describe the SDK's private-DM scope mapping as standardized. See docs/NIP-CD.md.
47
+
48
+ Storage adapters implement the exported synchronous opaque-record contract; keep codec selection/crypto in the SDK facade; preserve AES-GCM with storageKey and tagged plaintext without it. Preserve exact bytes, scopes, detached reads and durable atomic writes. Reuse test/storage-contract.ts and include rotation, uncertain ACK, restart and rollback cases. Multi-relay changes must preserve partial-success availability, first-ready startup, independent historical catch-up and rumor-ID dedup. Use authenticated inner DM time and the persisted first activation for admission. Recovered eligible DMs follow the same at-most-once path as live delivery. See docs/STORAGE.md and docs/RELAYS.md.
49
+
50
+ Sender authorization is ordinary middleware over authenticated identity authors, never wrapper or split encryption keys. Preserve absent versus empty allowlist semantics; authenticate and atomically claim the ID before middleware, and do not rerun middleware for rejected, failed or previously claimed input. Verify independent private history and outgoing delivery retry. See [access middleware](docs/ACCESS.md).
51
+
52
+ Live examples are real long-running bot programs, not offline walkthroughs. Their tests must launch the real compiled entrypoints using only test-generated config/identities and loopback relays. Never load an operator .env.chirli or inherit CHIRLI credentials into child fixtures. Preserve initializer non-overwrite/0600 behavior, restart persistence, clean signals and sanitized logs. Package smoke only runs live --help, never configured public-relay programs.
53
+
54
+ 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.
55
+
56
+ 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,282 @@
1
- # Temporary Holding Version
1
+ # Chirli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
54
+ await ctx.reply("pong");
55
+ });
56
+
57
+ try {
58
+ await bot.start();
59
+
60
+ console.log(`Bot public key: ${bot.pubkey}`);
61
+ await new Promise<void>((resolve) => {
62
+ process.once("SIGINT", () => resolve());
63
+ });
64
+ } finally {
65
+ await bot.close();
66
+ await signer.close();
67
+ }
68
+ ```
69
+
70
+ 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.
71
+
72
+ ### Use a remote signer
73
+
74
+ Replace the signer without changing handlers:
75
+
76
+ ```ts
77
+ import { bunkerSigner } from "chirli";
78
+
79
+ const signer = bunkerSigner(bunkerUri, {
80
+ clientSecret: bunkerClientKeyFromYourSecretManager,
81
+ });
82
+ ```
83
+
84
+ Pass this signer to `new Bot({ signer })`. After startup, `bot.pubkey` gives you the account key. Approve requests in the signer or configure its permissions ahead of time. See [remote signers](docs/SIGNERS.md#remote-bunker).
85
+
86
+ ## Handle ordinary messages
87
+
88
+ Use `handle()` to reply to messages that have no matching command:
89
+
90
+ ```ts
91
+ bot.handle(async (ctx) => {
92
+ await ctx.reply("Thanks for your message");
93
+ });
94
+
95
+ bot.onError((error, message) => {
96
+ // Forward sanitized diagnostics to your application's monitoring.
97
+ });
98
+ ```
99
+
100
+ Handlers run serially within a conversation and concurrently across conversations. An eligible authenticated input is claimed durably by its canonical ID before middleware. A failure is reported but does not cause a second attempt, even after reconnect or restart. Live and recovered incoming DMs created since first activation follow the same processing path. Eligible outgoing self copies can still populate history. [Event processing flow](docs/API.md#event-processing-flow)
101
+
102
+ `observe(observer)` monitors newly admitted DMs saved to local conversation history; it does not control processing. Register handlers before `start()`.
103
+
104
+ To reference the current DM in a reply, pass `ctx.input.id` as `replyTo`:
105
+
106
+ ```ts
107
+ await ctx.reply("Got it", { replyTo: ctx.input.id });
108
+ ```
109
+
110
+ Use `bot.getMessage(id)` for local private-message lookup, or `ctx.thread()` to load preceding context. To react to the current input, call `ctx.react('👍')`.
111
+
112
+ ### Inspect history and retry delivery
113
+
114
+ ```ts
115
+ const result = await bot.send(peerPubkey, "Hello");
116
+ // result.status: 'relay-accepted' | 'pending'
117
+
118
+ const page = bot.dmHistory(peerPubkey, { limit: 20 });
119
+ const state = bot.getMessageState(messageId);
120
+
121
+ await bot.flushOutbox();
122
+ ```
123
+
124
+ Rumor IDs prevent duplicate live attempts across relays and restarts. If a process exits after claiming a message, its callback may never run or may stop partway through. Use an application-owned job if you need durable business retries. Outbox retries reuse the original signed envelopes. Relay acceptance does not confirm delivery or reading.
125
+
126
+ History is local and paginated. Pass `page.nextCursor` to retrieve older rows; a local page does not imply a complete relay archive.
127
+
128
+ ## Commands and sessions
129
+
130
+ ```ts
131
+ const bot = new Bot<{ visits: number }>({
132
+ signer,
133
+ database: "./chirli.sqlite",
134
+ });
135
+
136
+ bot.command({ command: "visit", scopes: ["kind:14"] }, async (ctx) => {
137
+ const visits = ((await ctx.session.getItem("visits")) ?? 0) + 1;
138
+ ctx.session.setItem("visits", visits);
139
+ await ctx.reply(`Visit ${visits}`);
140
+ });
141
+
142
+ bot.handle(async (ctx) => {
143
+ await ctx.reply("Try /visit");
144
+ });
145
+ ```
146
+
147
+ 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.
148
+
149
+ Declare a typed argument schema in `command()` for typed arguments. Here `value` is inferred as `bigint`, and the published `d` is `count`.
150
+
151
+ ```ts
152
+ import { z } from "zod";
153
+
154
+ bot.command(
155
+ {
156
+ command: "count",
157
+ scopes: ["kind:14"],
158
+ title: "Count",
159
+ description: "Read an unsigned count.",
160
+ args: z.object({ value: z.bigint().meta({ label: "Value" }) }),
161
+ },
162
+ async (ctx, { value }) => {
163
+ await ctx.reply(String(value));
164
+ },
165
+ );
166
+ ```
167
+
168
+ To remove or rename a command, update the declared command set and restart with the same account and relay configuration. Startup automatically withdraws definitions absent from the new registry. There is no runtime removal method.
169
+
170
+ All registered commands are public on write relays. Startup adds or updates definitions and withdraws commands absent from the local registry. Definitions use kind `31992` and withdrawals use kind `5`; there is no executor-list event. User-installed kind `10992` lists are untouched.
171
+
172
+ Definitions and scopes describe command availability. Use `bot.use(allowlist(pubkeys))` to authorize senders, or an `authorize` callback for an individual typed command. [Command lifecycle](docs/NIP-CD.md) · [Sender authorization](docs/ACCESS.md)
173
+
174
+ ## Configuration
175
+
176
+ | Option | Purpose |
177
+ | --- | --- |
178
+ | `signer` | Required account signing and NIP-44 capabilities |
179
+ | `database` | SQLite path; defaults to `psstpsst.sqlite` |
180
+ | `messageStorage` | Message backend; defaults to `sqliteMessageStorage` |
181
+ | `storageKey` | Optional 32-byte key for local payload encryption |
182
+ | `relays` | Common list for each omitted relay role |
183
+ | `dmRelays` | Receive and deliver private messages |
184
+ | `readRelays` | Query public metadata |
185
+ | `writeRelays` | Publish public commands and account metadata |
186
+ | `discoveryRelays` | Extra targets for public account announcements |
187
+ | `mode` | `nip17` by default; `nip4e` enables separate messaging keys |
188
+
189
+ Use a fresh database for this pre-release storage format. Point `database` to a new path rather than replacing existing files. For subsequent restarts on this format, preserve the signer credentials, database and any storage key. `messageStorage` holds private conversation history and its diagnostic states; it defaults to `sqliteMessageStorage` in the configured database. Supply `sqliteMessageStorage('./messages.sqlite')` or implement `insert`, `query` and `updateState` to use another history backend. ID claims, outbox, keys and other internal data use `database`. Custom `Transport` implementations are also supported.
190
+
191
+ ### Resource lifecycle
192
+
193
+ The component that creates a resource closes it:
194
+
195
+ - Bot closes its built-in transport and storage.
196
+ - Your application closes injected signers, transports and storage adapters.
197
+ - `bot.stop()` drains handlers and keeps the Bot reusable. `bot.close()` also releases its resources.
198
+
199
+ Close Bot before its injected resources. Call stop/close outside message handlers; use `bot.requestStop()` when a handler needs to request shutdown.
200
+
201
+ ### Protocol modes and recovery
202
+
203
+ Default NIP-17 uses account-key encryption. Explicit `mode: 'nip4e'` generates or restores separate messaging keys for extension peers. Both modes accept supported standard NIP-17 and NIP-4E messages.
204
+
205
+ Relay connections are pooled and reconnect independently. Recovery uses bounded overlap paging. On first startup the Bot saves its DM activation time. Older DMs are ignored; new DMs found after downtime enter the same middleware and handlers as live DMs, at most once.
206
+
207
+ See [key rotation](docs/KEYS.md), [interoperability](docs/INTEROPERABILITY.md), [relay configuration](docs/RELAYS.md) and [recovery](docs/RECOVERY.md) for detailed behavior and limits.
208
+
209
+ ## Development
210
+
211
+ ```sh
212
+ npm run build
213
+ npm run typecheck
214
+ npm test
215
+ npm run examples:smoke
216
+ npm run pack:check
217
+ ```
218
+
219
+ `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.
220
+
221
+ ## Documentation
222
+
223
+ Start with the [first bot tutorial](docs/TUTORIAL.md) for a step-by-step path from the runnable demo to your own application.
224
+
225
+ | Guide | Contents |
226
+ | --- | --- |
227
+ | [API](docs/API.md) | Bot, middleware and public types |
228
+ | [Examples](https://github.com/CodyTseng/chirli/blob/main/examples/README.md) | Fourteen offline demos and a loopback demo |
229
+ | [Sessions](docs/SESSIONS.md) | Conversation state, resets and a custom SQLite session store |
230
+ | [Storage](docs/STORAGE.md) | Message adapters, encryption and persistence contracts |
231
+ | [Architecture](ARCHITECTURE.md) | Layer boundaries and failure semantics |
232
+ | [Contributing](CONTRIBUTING.md) | Development and validation expectations |
233
+ | [Security](SECURITY.md) | Trust boundaries and known limitations |
234
+
235
+ Chirli supports one-to-one private text and [file attachments](docs/API.md#receive-and-download-a-private-file), reply references, private and public reactions, and [explicitly scoped kind 1/1111 public commands](docs/PUBLIC.md). Groups, full archive recovery and exactly-once external effects are outside its scope. One active Bot/process per account database is supported. Public relays, external signer products and production deployments require separate validation.
236
+
237
+ Bot command identifiers come from their command names; custom `id` parameters are rejected. Renaming a command removes the old coordinate and adds the new one. Startup compares one broad author-scoped kind 31992 scan per write relay with the complete local registry; runtime additions synchronize automatically. Remote kind 5 queries belong to independent discovery, while locally pending withdrawals remain durable. See [command lifecycle and upgrade behavior](docs/NIP-CD.md).
238
+
239
+ ## Optional access and timing middleware
240
+
241
+ ```ts
242
+ import { Bot, allowlist, requestTiming } from "chirli";
243
+
244
+ const bot = new Bot({ signer });
245
+ bot.use(allowlist(trustedIdentityPubkeys));
246
+ bot.use(
247
+ requestTiming({
248
+ onTiming: (metric) => {
249
+ console.info(metric);
250
+ },
251
+ }),
252
+ );
253
+ bot.command({ command: "ping", scopes: ["kind:14"] }, async (ctx) => {
254
+ await ctx.reply("pong");
255
+ });
256
+ await bot.start(); // Command declarations remain automatic.
257
+ ```
258
+
259
+ `allowlist` snapshots the supplied lowercase hex identity keys. Register it first to block downstream middleware and handlers for nonmembers. `allowlist([])` blocks every external sender from routing, including eligible DMs discovered during recovery. Returning early does not undo the prior ID claim. [Sender authorization](docs/ACCESS.md)
260
+
261
+ `requestTiming({onTiming})` is optional ordinary middleware. Its observer receives only `{durationMs,outcome:'success'|'failure'}` for the downstream processing chain. It never reads message context or error details, does not log by default and cannot let observer failures change processing. It excludes receipt/decryption, queue waiting and session commit after the chain; no command route name is inferred from text. See [API](docs/API.md).
262
+
263
+ ## Public input and shared context
264
+
265
+ Omit `scopes` to publish `kind:14`, `kind:1` and `kind:1111`. Use an explicit list to narrow the scope. File DMs go to `bot.handle()`. Public reads require `publicInbox: {relays: [...]}`; they never use implicit default relays. `ctx.input` contains the authenticated input. `ctx.reply()` and `ctx.react()` preserve its private or public visibility, and `await ctx.thread({limit:30})` lazily loads prior context. Public context/session storage never reads private conversations.
266
+
267
+ ```ts
268
+ const bot = new Bot({ signer, publicInbox: { relays: publicInboxRelays } });
269
+ bot.command(
270
+ { command: "ping" },
271
+ async (ctx) => {
272
+ await ctx.reply("pong");
273
+ },
274
+ );
275
+ await bot.start();
276
+ ```
277
+
278
+ Run `npm run example:public` for an offline three-kind demo and deterministic application-owned `/summarize` mock. See [targeting, replies and thread bounds](docs/PUBLIC.md).
279
+
280
+ For application-owned background work, retain `ctx.input.event` and pass it to `bot.thread(event,{limit:30})`, `bot.reply(event,text)` or `bot.react(event,'👍')`. These methods preserve private/public routing and reuse handler semantics. DM authentication requires the same account's retained incoming record; a public target requires the complete signed event. See [delayed calls and trust requirements](docs/API.md#replies-and-context-after-a-handler), or run `npm run example:async-reply` entirely offline.
281
+
282
+ Command `args` accepts a Zod 4 `z.object(...)` directly. The schema both generates NIP-CD metadata and validates decoded input; handler-only `ctx.args` and the second handler argument share the inferred valid result. Use middleware or `bot.catch` for centralized `InvalidArgsError` handling; no automatic error reply or retry is added. See [schema support and authorization boundaries](docs/API.md#zod-command-arguments).
package/SECURITY.md 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; routing metadata, claimed IDs and status/timestamp indexes remain visible. Core Bot does not store identity signing secrets; the live application can persist a generated signer in a private adjacent file. Split encryption keys and pending declarations follow the configured plaintext/encrypted codec. Preserve the original storageKey whenever encryption is enabled. Protect storage keys, files, backups, process memory and your own logs. Downloaded attachments are saved as verified plaintext in a separate per-account directory; `storageKey` protects database payloads only. Attachment downloads are explicit and limited to configured origins, including each redirect.
15
+ - Authenticated canonical input IDs are claimed atomically before business middleware. Claims prevent a second SDK attempt, not missed or partial effects after a crash. The SDK does not retry business callbacks. Relay acceptance means neither delivery nor reading.
16
+ - Incoming DMs before first activation are ignored. Eligible incoming DMs found during downtime recovery can execute the same middleware and handlers as live input, but never rerun a claimed ID. Outgoing self copies and public history do not run business handlers.
17
+ - 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 DMs since first activation are eligible for a first dispatch, and incomplete scans leave checkpoints unchanged. A remote signer sees plaintext used in NIP-44 operations. Its operational failures are surfaced and stop recovery checkpoint advancement. Opaque remote decryption errors are conservatively treated as retryable, so corrupt signed wrappers can also leave a remote scan incomplete; there is no durable raw-envelope quarantine or product-specific error classification. See SIGNERS.md and RECOVERY.md.
26
+
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 retained encoded private messages, diagnostic state and routing metadata, never storageKey, keyrings, evidence or outbox records. They are trusted for durable unique insertion, state updates and account isolation. The SDK records input claims separately in internal SQLite. With storageKey, payloads are ciphertext; without it they are readable plaintext. Internal SQLite retains only temporary message handoffs until insertion succeeds. Protect both stores and follow docs/STORAGE.md. Multiple-relay discovery can be partial; cached evidence is not a globally fresh declaration guarantee. At least one ACK is not all-relay replication. See docs/RELAYS.md.
32
+
33
+ Register allowlist as the first middleware to restrict downstream callbacks to verified accounts. Anonymous wrapper authors and split messaging keys grant no authorization. An empty list blocks every external sender from routing; omitting it imposes no additional access restriction. Eligible IDs remain claimed even for denied inputs. A short-circuited DM does not enter private history; recovered copies do not bypass this by storing a body. Crypto and remote signer work can occur before the sender is known. Middleware is not an outbound ACL or rate limiter. See [access](docs/ACCESS.md).
34
+
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 retained conversation records and claim IDs. 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 an application-owned durable job or idempotency mechanism where a business effect must recover after a crash.
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
+ `requestTiming` telemetry contains only elapsed milliseconds and chain outcome, and isolates observer failures. Applications own their policies and observers. No access middleware runs before authentication and the ID claim.
50
+
51
+ Public kind 1/1111 input requires an explicit inbox and declared supported scopes. Signature, source, structure and unambiguous invocation targeting are checked before claiming an ID and running business middleware. Public session/thread methods never load private peer data. Public replies and reactions intentionally publish signed kind 1111 and kind 7 events, respectively, only to configured write/source relays; arbitrary tag URLs are not contacted. Public thread scope claims are signed claims, not proof of truthful ancestry, and resolved context remains untrusted application input. No public input history or callback payload is kept. Claims do not guarantee exactly-once external effects. The public outbox uses the same selected storage codec as internal metadata. See [public input boundaries](docs/PUBLIC.md).
52
+
53
+ Delayed `bot.reply(event,...)`, `bot.react(event,...)` and `bot.thread(event,...)` calls use original input events, never arbitrary IDs or outer envelopes. Signed public events are independently reverified; only immediate handler calls retain the incoming relay as a routing hint, and delayed replies and reactions use configured write relays. Unsigned DM rumors must match the account/mode's persisted authenticated incoming record, canonical hash/fields and private routing; a rumor's ID or asserted sender alone grants no trust. Applications own their worker queues and must protect saved DM events as plaintext. Calls are explicit application effects, not inbound policy dispatch; repeated calls are not deduplicated as jobs. See docs/API.md.
54
+
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,3 @@
1
+ import type { Context, Next } from "./bot-handlers.js";
2
+ /** Allow the selected verified account keys to continue through the middleware chain. */
3
+ export declare function allowlist(pubkeys: readonly string[]): (ctx: Pick<Context, "sender">, next: Next) => Promise<void> | undefined;
@@ -0,0 +1,9 @@
1
+ import { hexKey } from "./protocol.js";
2
+ /** Allow the selected verified account keys to continue through the middleware chain. */
3
+ export function allowlist(pubkeys) {
4
+ if (!Array.isArray(pubkeys) || !Array.from(pubkeys).every(hexKey)) {
5
+ throw new TypeError("allowlist must be an array of lowercase hex identity public keys");
6
+ }
7
+ const identities = new Set(pubkeys);
8
+ return (ctx, next) => (identities.has(ctx.sender) ? next() : undefined);
9
+ }