chirli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/ARCHITECTURE.md +18 -20
  2. package/CONTRIBUTING.md +7 -3
  3. package/README.md +63 -55
  4. package/SECURITY.md +11 -11
  5. package/dist/allowlist.d.ts +3 -0
  6. package/dist/allowlist.js +9 -0
  7. package/dist/announcements.d.ts +4 -4
  8. package/dist/announcements.js +66 -34
  9. package/dist/attachments.d.ts +43 -0
  10. package/dist/attachments.js +340 -0
  11. package/dist/blossom.d.ts +2 -2
  12. package/dist/blossom.js +120 -66
  13. package/dist/bot-handlers.d.ts +9 -18
  14. package/dist/bot-handlers.js +125 -66
  15. package/dist/bot.d.ts +17 -20
  16. package/dist/bot.js +150 -55
  17. package/dist/client.d.ts +43 -39
  18. package/dist/client.js +476 -290
  19. package/dist/command-discovery.d.ts +2 -2
  20. package/dist/command-discovery.js +16 -7
  21. package/dist/command-schema.d.ts +2 -2
  22. package/dist/command-schema.js +62 -31
  23. package/dist/commands.d.ts +7 -6
  24. package/dist/commands.js +116 -51
  25. package/dist/defaults.js +13 -6
  26. package/dist/errors.d.ts +12 -12
  27. package/dist/errors.js +55 -18
  28. package/dist/inbox.d.ts +9 -7
  29. package/dist/inbox.js +107 -62
  30. package/dist/index.d.ts +25 -24
  31. package/dist/index.js +11 -11
  32. package/dist/key-sync.d.ts +4 -4
  33. package/dist/key-sync.js +88 -50
  34. package/dist/keys.d.ts +7 -6
  35. package/dist/keys.js +187 -93
  36. package/dist/message-storage-sqlite.d.ts +1 -1
  37. package/dist/message-storage-sqlite.js +32 -27
  38. package/dist/message-storage.d.ts +2 -2
  39. package/dist/messaging-metadata.d.ts +4 -4
  40. package/dist/messaging-metadata.js +73 -46
  41. package/dist/metadata.d.ts +3 -3
  42. package/dist/metadata.js +29 -15
  43. package/dist/modes.d.ts +7 -7
  44. package/dist/modes.js +53 -24
  45. package/dist/nip4e-compat.d.ts +2 -2
  46. package/dist/nip4e-compat.js +2 -2
  47. package/dist/nipcd.d.ts +14 -14
  48. package/dist/nipcd.js +225 -126
  49. package/dist/protocol.d.ts +7 -6
  50. package/dist/protocol.js +101 -54
  51. package/dist/public-inbox.d.ts +17 -15
  52. package/dist/public-inbox.js +129 -138
  53. package/dist/public-thread.d.ts +7 -4
  54. package/dist/public-thread.js +205 -88
  55. package/dist/relay-pool.d.ts +5 -5
  56. package/dist/relay-pool.js +172 -67
  57. package/dist/relay-roles.js +22 -13
  58. package/dist/relay.d.ts +11 -11
  59. package/dist/relay.js +194 -100
  60. package/dist/request-timing.d.ts +2 -2
  61. package/dist/request-timing.js +19 -7
  62. package/dist/session.js +7 -5
  63. package/dist/signer.d.ts +1 -1
  64. package/dist/signers/bunker-relays.d.ts +2 -2
  65. package/dist/signers/bunker-relays.js +16 -13
  66. package/dist/signers/bunker.d.ts +2 -2
  67. package/dist/signers/bunker.js +57 -37
  68. package/dist/signers/nsec.d.ts +2 -2
  69. package/dist/signers/nsec.js +8 -8
  70. package/dist/signers.d.ts +8 -8
  71. package/dist/signers.js +25 -18
  72. package/dist/storage-sqlite.d.ts +3 -1
  73. package/dist/storage-sqlite.js +110 -58
  74. package/dist/storage.d.ts +10 -6
  75. package/dist/store.d.ts +12 -8
  76. package/dist/store.js +156 -78
  77. package/docs/ACCESS.md +14 -25
  78. package/docs/API.md +125 -79
  79. package/docs/KEYS.md +3 -3
  80. package/docs/NIP-CD.md +29 -19
  81. package/docs/PUBLIC.md +33 -23
  82. package/docs/RECOVERY.md +7 -5
  83. package/docs/RELAYS.md +6 -6
  84. package/docs/SESSIONS.md +25 -21
  85. package/docs/SIGNERS.md +5 -3
  86. package/docs/STORAGE.md +15 -15
  87. package/docs/TUTORIAL.md +42 -39
  88. package/package.json +1 -37
  89. package/dist/inbound-policy.d.ts +0 -4
  90. package/dist/inbound-policy.js +0 -9
@@ -1,9 +1,9 @@
1
- import { signChecked } from './protocol.js';
2
- import { commandRelayURL, parseCommandHead, matchesCommandScopes } from './nipcd.js';
3
- import { InboxSubscription } from './inbox.js';
4
- import { relayUnion } from './relay-roles.js';
5
- import { PublicThreads, publicEvent, threadStructure, referenceKey, commentReply } from './public-thread.js';
6
- import { localReadBoundary } from './relay.js';
1
+ import { signChecked } from "./protocol.js";
2
+ import { commandRelayURL, parseCommandHead, matchesCommandScopes, } from "./nipcd.js";
3
+ import { InboxSubscription } from "./inbox.js";
4
+ import { relayUnion } from "./relay-roles.js";
5
+ import { PublicThreads, publicEvent, threadStructure, referenceKey, commentReply, } from "./public-thread.js";
6
+ import { localReadBoundary } from "./relay.js";
7
7
  /** Explicit public command inbox. Never shares private message rows, conversation keys or outbox. */
8
8
  export class PublicInbox {
9
9
  identity;
@@ -12,46 +12,50 @@ export class PublicInbox {
12
12
  writes;
13
13
  reconnect;
14
14
  definitions;
15
- allowed;
16
15
  process;
17
16
  report;
18
17
  state;
19
18
  subscriptions;
20
19
  running = false;
21
- kinds = '';
20
+ kinds = "";
22
21
  initialReady = false;
23
22
  starting;
24
23
  generation = 0;
25
24
  queues = new Map();
26
- scheduled = new Set();
27
25
  flushing;
28
26
  relays;
29
27
  threads;
30
- constructor(identity, store, transport, options, writes, reconnect, definitions, allowed, process, report) {
28
+ constructor(identity, store, transport, options, writes, reconnect, definitions, process, report) {
31
29
  this.identity = identity;
32
30
  this.store = store;
33
31
  this.transport = transport;
34
32
  this.writes = writes;
35
33
  this.reconnect = reconnect;
36
34
  this.definitions = definitions;
37
- this.allowed = allowed;
38
35
  this.process = process;
39
36
  this.report = report;
40
37
  if (!Array.isArray(options.relays) || !options.relays.length)
41
- throw new TypeError('publicInbox.relays requires explicit relay URLs');
38
+ throw new TypeError("publicInbox.relays requires explicit relay URLs");
42
39
  this.relays = [...new Set(options.relays.map(commandRelayURL))];
43
40
  this.threads = new PublicThreads(transport, this.relays, options.thread);
44
- this.state = store.metadata('public-inputs') ?? { version: 1, records: {}, outbox: [] };
45
- if (this.state.version !== 1 || !this.state.records || !Array.isArray(this.state.outbox))
46
- throw new Error('Unsupported public input journal');
47
- for (const record of Object.values(this.state.records))
48
- if (record.state === 'processing')
49
- record.state = 'pending';
41
+ const existing = store.metadata("public-inputs");
42
+ if (existing &&
43
+ (existing.version !== 2 || !Array.isArray(existing.outbox))) {
44
+ throw new Error("Unsupported public input journal; use a fresh database");
45
+ }
46
+ this.state = existing ?? { version: 2, outbox: [] };
47
+ }
48
+ save() {
49
+ this.store.saveMetadata("public-inputs", this.state);
50
+ }
51
+ conversation(event) {
52
+ const structure = threadStructure(event);
53
+ return `public:${structure.root ? referenceKey(structure.root) : `e:${event.id}`}`;
50
54
  }
51
- save() { this.store.saveMetadata('public-inputs', this.state); }
52
- conversation(event) { const structure = threadStructure(event); return `public:${structure.root ? referenceKey(structure.root) : `e:${event.id}`}`; }
53
55
  accepted(event, relay) {
54
- if (![1, 1111].includes(event.kind) || event.pubkey === this.identity.pubkey || !this.relays.includes(commandRelayURL(relay)) || !this.allowed(event.pubkey))
56
+ if (![1, 1111].includes(event.kind) ||
57
+ event.pubkey === this.identity.pubkey ||
58
+ !this.relays.includes(commandRelayURL(relay)))
55
59
  return false;
56
60
  try {
57
61
  threadStructure(event);
@@ -59,22 +63,25 @@ export class PublicInbox {
59
63
  catch {
60
64
  return false;
61
65
  }
62
- return this.definitions().some(definition => {
66
+ return this.definitions().some((definition) => {
63
67
  const result = parseCommandHead(event.content, definition.command, this.identity.pubkey);
64
- if (result.status !== 'matched' || !matchesCommandScopes(definition.scopes ?? [], event, { relay }))
68
+ if (result.status !== "matched" ||
69
+ !matchesCommandScopes(definition.scopes ?? [], event, { relay }))
65
70
  return false;
66
71
  if (result.qualifier !== undefined)
67
72
  return true;
68
- const targets = new Set(event.tags.filter(tag => tag[0] === 'p').map(tag => tag[1]));
73
+ const targets = new Set(event.tags.filter((tag) => tag[0] === "p").map((tag) => tag[1]));
69
74
  return targets.size === 1 && targets.has(this.identity.pubkey);
70
75
  });
71
76
  }
72
77
  start(kinds) {
73
- const next = [...new Set(kinds)].sort().join(',');
74
- const alreadyInitialized = this.running && next === this.kinds && this.initialReady;
78
+ const next = [...new Set(kinds)].sort().join(",");
75
79
  // initialReady gates inbox initialization only. A failed REQ still needs retry even
76
80
  // on an OPEN socket; an active REQ does not become disconnected while awaiting EOSE.
77
- const reusable = this.initialReady && (this.reconnect !== false || !kinds.length || this.subscriptions?.hasUsableSubscription());
81
+ const reusable = this.initialReady &&
82
+ (this.reconnect !== false ||
83
+ !kinds.length ||
84
+ this.subscriptions?.hasUsableSubscription());
78
85
  if (this.running && next === this.kinds && (reusable || this.starting))
79
86
  return this.starting ?? Promise.resolve();
80
87
  this.subscriptions?.close();
@@ -88,28 +95,29 @@ export class PublicInbox {
88
95
  this.starting = undefined;
89
96
  return Promise.resolve();
90
97
  }
91
- const current = () => this.running && this.generation === generation && this.subscriptions === subscription;
92
- // Replay only pre-existing local unfinished work, once for this activation. New live
93
- // failures and replayed relay history must not become automatic recovery retries.
94
- const unfinished = Object.entries(this.state.records).filter(([, record]) => ['pending', 'failed'].includes(record.state) && record.event).map(([id]) => id);
95
- let initialized = alreadyInitialized;
98
+ const current = () => this.running &&
99
+ this.generation === generation &&
100
+ this.subscriptions === subscription;
96
101
  const initialize = async () => {
97
102
  if (!current())
98
103
  return;
99
104
  this.initialReady = true;
100
- if (!initialized) {
101
- initialized = true;
102
- for (const id of unfinished) {
103
- const record = this.state.records[id];
104
- if (record && ['pending', 'failed'].includes(record.state) && record.event)
105
- this.enqueue(id, record);
106
- }
107
- }
108
105
  await this.flush();
109
106
  };
110
- const subscription = new InboxSubscription({ transport: this.transport, store: this.store, relays: this.relays, filter: { kinds, limit: 500 }, recovery: false, localReadWindow: true, reconnect: this.reconnect,
111
- receive: async (event, source, relay) => { this.receive(event, source, relay); }, error: this.report,
112
- reconnected: initialize });
107
+ const subscription = new InboxSubscription({
108
+ transport: this.transport,
109
+ store: this.store,
110
+ relays: this.relays,
111
+ filter: { kinds, limit: 500 },
112
+ recovery: false,
113
+ localReadWindow: true,
114
+ reconnect: this.reconnect,
115
+ receive: async (event, source, relay) => {
116
+ this.receive(event, source, relay);
117
+ },
118
+ error: this.report,
119
+ reconnected: initialize,
120
+ });
113
121
  this.subscriptions = subscription;
114
122
  const task = (async () => {
115
123
  try {
@@ -129,8 +137,10 @@ export class PublicInbox {
129
137
  throw error;
130
138
  }
131
139
  await initialize();
132
- })().finally(() => { if (this.starting === task)
133
- this.starting = undefined; });
140
+ })().finally(() => {
141
+ if (this.starting === task)
142
+ this.starting = undefined;
143
+ });
134
144
  this.starting = task;
135
145
  return task;
136
146
  }
@@ -140,114 +150,88 @@ export class PublicInbox {
140
150
  const boundary = localReadBoundary(input), event = publicEvent(input);
141
151
  if (!event || !this.accepted(event, relay))
142
152
  return false;
143
- if (source === 'history' && boundary !== undefined && event.created_at > boundary)
144
- source = 'live';
145
- if (Object.hasOwn(this.state.records, event.id))
153
+ if (source === "history" &&
154
+ boundary !== undefined &&
155
+ event.created_at > boundary)
156
+ source = "live";
157
+ if (!this.store.claimInput(event.id))
146
158
  return false;
147
- let evicted;
148
- if (Object.keys(this.state.records).length >= 5000) {
149
- const old = Object.keys(this.state.records).find(id => ['history', 'done'].includes(this.state.records[id].state));
150
- if (!old)
151
- throw new Error('Public pending journal capacity exceeded');
152
- evicted = [old, this.state.records[old]];
153
- delete this.state.records[old];
154
- }
155
- const record = { ...(source === 'live' ? { event } : {}), relay, state: source === 'history' ? 'history' : 'pending' };
156
- this.state.records[event.id] = record;
157
- try {
158
- this.save();
159
- }
160
- catch (error) {
161
- delete this.state.records[event.id];
162
- if (evicted)
163
- this.state.records[evicted[0]] = evicted[1];
164
- throw error;
165
- }
166
- if (source === 'live')
167
- this.enqueue(event.id, record);
159
+ if (source === "live")
160
+ this.enqueue({ event, relay, conversation: this.conversation(event) });
168
161
  return true;
169
162
  }
170
- enqueue(id, record) {
171
- if (this.scheduled.has(id) || !record.event)
172
- return;
173
- const event = publicEvent(record.event);
174
- if (!event || !this.accepted(event, record.relay)) {
175
- record.state = 'done';
176
- delete record.event;
177
- this.save();
178
- return;
179
- }
180
- const conversation = this.conversation(event);
181
- this.scheduled.add(id);
182
- const task = (this.queues.get(conversation) ?? Promise.resolve()).catch(() => { }).then(async () => {
183
- if (!this.accepted(event, record.relay)) {
184
- record.state = 'done';
185
- delete record.event;
186
- this.save();
187
- return;
188
- }
189
- const previous = record.state;
190
- record.state = 'processing';
191
- try {
192
- this.save();
193
- }
194
- catch (error) {
195
- record.state = previous;
196
- throw error;
197
- }
198
- try {
199
- await this.process({ event: structuredClone(event), relay: record.relay, conversation });
200
- record.state = 'done';
201
- delete record.event;
202
- }
203
- catch (error) {
204
- record.state = 'failed';
205
- this.report(error);
206
- }
207
- try {
208
- this.save();
209
- }
210
- catch (error) {
211
- record.state = 'failed';
212
- record.event = event;
213
- throw error;
214
- }
215
- }).catch(error => this.report(error)).finally(() => {
216
- this.scheduled.delete(id);
163
+ enqueue(input) {
164
+ const { event, relay, conversation } = input;
165
+ const task = (this.queues.get(conversation) ?? Promise.resolve())
166
+ .catch(() => { })
167
+ .then(async () => {
168
+ if (this.accepted(event, relay))
169
+ await this.process(input);
170
+ })
171
+ .catch((error) => this.report(error))
172
+ .finally(() => {
217
173
  if (this.queues.get(conversation) === task)
218
174
  this.queues.delete(conversation);
219
175
  });
220
176
  this.queues.set(conversation, task);
221
177
  }
222
- /** Signed public input is sufficient; provenance comes only from our own journal. */
178
+ /** A delayed signed event is sufficient but does not carry verified relay provenance. */
223
179
  target(input) {
224
180
  const event = publicEvent(input);
225
181
  if (!event || ![1, 1111].includes(event.kind))
226
- throw new TypeError('Expected a valid signed kind 1/1111 event');
182
+ throw new TypeError("Expected a valid signed kind 1/1111 event");
227
183
  threadStructure(event);
228
- const known = this.state.records[event.id]?.relay;
229
- const relay = known && this.relays.includes(commandRelayURL(known)) ? known : '';
230
- return { event, relay, conversation: this.conversation(event) };
184
+ return { event, relay: "", conversation: this.conversation(event) };
231
185
  }
232
186
  async reply(input, text) {
233
- if (typeof text !== 'string' || !text.length)
234
- throw new TypeError('Nonempty reply text required');
187
+ if (typeof text !== "string" || !text.length)
188
+ throw new TypeError("Nonempty reply text required");
235
189
  const root = await this.threads.rootForReply(input.event);
236
- return this.publishReply(input, commentReply(input.event, root, text, input.relay));
190
+ return this.publishOutput(input, commentReply(input.event, root, text, input.relay));
237
191
  }
238
192
  async replyFile(input, upload) {
239
193
  const root = await this.threads.rootForReply(input.event);
240
194
  // Validate the reply structure before exposing any bytes to an upload endpoint.
241
- const template = commentReply(input.event, root, 'attachment', input.relay);
195
+ const template = commentReply(input.event, root, "attachment", input.relay);
242
196
  const { url, mimeType, sha256, size } = await upload();
243
197
  template.content = url;
244
198
  template.created_at = Math.floor(Date.now() / 1000);
245
- template.tags.push(['imeta', `url ${url}`, `m ${mimeType}`, `x ${sha256}`, `size ${size}`]);
246
- return this.publishReply(input, template);
199
+ template.tags.push([
200
+ "imeta",
201
+ `url ${url}`,
202
+ `m ${mimeType}`,
203
+ `x ${sha256}`,
204
+ `size ${size}`,
205
+ ]);
206
+ return this.publishOutput(input, template);
207
+ }
208
+ async react(input, reaction = "+") {
209
+ if (typeof reaction !== "string" || !reaction.trim())
210
+ throw new TypeError("Nonempty reaction required");
211
+ const target = input.event, hint = this.sourceRelay(input);
212
+ const tags = [
213
+ ["e", target.id, hint, target.pubkey],
214
+ ["p", target.pubkey],
215
+ ];
216
+ if (target.kind !== 1)
217
+ tags.push(["k", String(target.kind)]);
218
+ return this.publishOutput(input, {
219
+ kind: 7,
220
+ content: reaction,
221
+ tags,
222
+ created_at: Math.floor(Date.now() / 1000),
223
+ });
224
+ }
225
+ sourceRelay(input) {
226
+ if (!input.relay)
227
+ return "";
228
+ const relay = commandRelayURL(input.relay);
229
+ return this.relays.includes(relay) ? relay : "";
247
230
  }
248
- async publishReply(input, template) {
231
+ async publishOutput(input, template) {
249
232
  const event = await signChecked(this.identity, template);
250
- const relays = relayUnion(this.writes, input.relay && this.relays.includes(commandRelayURL(input.relay)) ? [input.relay] : []);
233
+ const source = this.sourceRelay(input);
234
+ const relays = relayUnion(this.writes, source ? [source] : []);
251
235
  this.state.outbox.push({ event, relays });
252
236
  try {
253
237
  this.save();
@@ -262,7 +246,12 @@ export class PublicInbox {
262
246
  catch (error) {
263
247
  this.report(error);
264
248
  }
265
- return { id: event.id, status: this.state.outbox.some(item => item.event.id === event.id) ? 'pending' : 'relay-accepted' };
249
+ return {
250
+ id: event.id,
251
+ status: this.state.outbox.some((item) => item.event.id === event.id)
252
+ ? "pending"
253
+ : "relay-accepted",
254
+ };
266
255
  }
267
256
  flush() {
268
257
  if (this.flushing)
@@ -287,15 +276,17 @@ export class PublicInbox {
287
276
  this.flushing = task;
288
277
  return task;
289
278
  }
290
- retry(ids) {
291
- if (!this.running)
292
- return;
293
- for (const [id, record] of Object.entries(this.state.records))
294
- if ((!ids || ids.has(id)) && ['pending', 'failed'].includes(record.state))
295
- this.enqueue(id, record);
279
+ thread(input, options) {
280
+ return this.threads.resolve(input.event, options);
281
+ }
282
+ stop() {
283
+ this.running = false;
284
+ this.generation++;
285
+ this.initialReady = false;
286
+ this.starting = undefined;
287
+ this.subscriptions?.close();
288
+ this.subscriptions = undefined;
296
289
  }
297
- thread(input, options) { return this.threads.resolve(input.event, options); }
298
- stop() { this.running = false; this.generation++; this.initialReady = false; this.starting = undefined; this.subscriptions?.close(); this.subscriptions = undefined; }
299
290
  async idle() {
300
291
  while (this.queues.size)
301
292
  await Promise.all(this.queues.values());
@@ -1,17 +1,20 @@
1
- import { type Event, type EventTemplate } from 'nostr-tools';
2
- import { type Rumor } from './protocol.js';
3
- import type { Transport } from './relay.js';
1
+ import { type Event, type EventTemplate } from "nostr-tools";
2
+ import { type Rumor } from "./protocol.js";
3
+ import type { FileAttachment } from "./attachments.js";
4
+ import type { Transport } from "./relay.js";
4
5
  export interface Input {
5
6
  readonly id: string;
6
7
  readonly sender: string;
7
8
  readonly createdAt: number;
9
+ readonly kind: number;
8
10
  readonly text: string;
11
+ readonly file?: FileAttachment;
9
12
  readonly event: Event | Rumor;
10
13
  }
11
14
  export interface ThreadResult {
12
15
  entries: Input[];
13
16
  complete: boolean;
14
- coverage: 'local-conversation' | 'public-ancestors';
17
+ coverage: "local-conversation" | "public-ancestors";
15
18
  reason?: string;
16
19
  }
17
20
  export interface ThreadOptions {