chirli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +103 -0
- package/CONTRIBUTING.md +56 -0
- package/LICENSE +22 -0
- package/README.md +281 -2
- package/SECURITY.md +55 -0
- package/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/allowlist.d.ts +3 -0
- package/dist/allowlist.js +9 -0
- package/dist/announcements.d.ts +25 -0
- package/dist/announcements.js +142 -0
- package/dist/attachments.d.ts +43 -0
- package/dist/attachments.js +340 -0
- package/dist/blossom.d.ts +30 -0
- package/dist/blossom.js +233 -0
- package/dist/bot-handlers.d.ts +70 -0
- package/dist/bot-handlers.js +317 -0
- package/dist/bot.d.ts +63 -0
- package/dist/bot.js +244 -0
- package/dist/client.d.ts +221 -0
- package/dist/client.js +1197 -0
- package/dist/command-discovery.d.ts +4 -0
- package/dist/command-discovery.js +33 -0
- package/dist/command-schema.d.ts +4 -0
- package/dist/command-schema.js +101 -0
- package/dist/commands.d.ts +32 -0
- package/dist/commands.js +253 -0
- package/dist/defaults.d.ts +9 -0
- package/dist/defaults.js +22 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.js +126 -0
- package/dist/inbox.d.ts +55 -0
- package/dist/inbox.js +376 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +11 -0
- package/dist/key-sync.d.ts +33 -0
- package/dist/key-sync.js +293 -0
- package/dist/keys.d.ts +66 -0
- package/dist/keys.js +418 -0
- package/dist/message-storage-sqlite.d.ts +6 -0
- package/dist/message-storage-sqlite.js +90 -0
- package/dist/message-storage.d.ts +32 -0
- package/dist/message-storage.js +1 -0
- package/dist/messaging-metadata.d.ts +48 -0
- package/dist/messaging-metadata.js +280 -0
- package/dist/metadata.d.ts +7 -0
- package/dist/metadata.js +63 -0
- package/dist/modes.d.ts +26 -0
- package/dist/modes.js +108 -0
- package/dist/nip4e-compat.d.ts +4 -0
- package/dist/nip4e-compat.js +14 -0
- package/dist/nipcd.d.ts +109 -0
- package/dist/nipcd.js +555 -0
- package/dist/protocol.d.ts +68 -0
- package/dist/protocol.js +302 -0
- package/dist/public-inbox.d.ts +66 -0
- package/dist/public-inbox.js +295 -0
- package/dist/public-thread.d.ts +62 -0
- package/dist/public-thread.js +436 -0
- package/dist/relay-pool.d.ts +43 -0
- package/dist/relay-pool.js +429 -0
- package/dist/relay-roles.d.ts +18 -0
- package/dist/relay-roles.js +55 -0
- package/dist/relay.d.ts +52 -0
- package/dist/relay.js +493 -0
- package/dist/request-timing.d.ts +12 -0
- package/dist/request-timing.js +37 -0
- package/dist/session.d.ts +16 -0
- package/dist/session.js +51 -0
- package/dist/signer.d.ts +13 -0
- package/dist/signer.js +1 -0
- package/dist/signers/bunker-relays.d.ts +15 -0
- package/dist/signers/bunker-relays.js +87 -0
- package/dist/signers/bunker.d.ts +7 -0
- package/dist/signers/bunker.js +194 -0
- package/dist/signers/nsec.d.ts +3 -0
- package/dist/signers/nsec.js +62 -0
- package/dist/signers.d.ts +18 -0
- package/dist/signers.js +59 -0
- package/dist/storage-sqlite.d.ts +29 -0
- package/dist/storage-sqlite.js +221 -0
- package/dist/storage.d.ts +85 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +96 -0
- package/dist/store.js +404 -0
- package/docs/ACCESS.md +28 -0
- package/docs/API.md +382 -0
- package/docs/INTEROPERABILITY.md +32 -0
- package/docs/KEYS.md +75 -0
- package/docs/NIP-CD.md +112 -0
- package/docs/PUBLIC.md +88 -0
- package/docs/RECOVERY.md +59 -0
- package/docs/RELAYS.md +145 -0
- package/docs/SESSIONS.md +108 -0
- package/docs/SIGNERS.md +59 -0
- package/docs/STORAGE.md +71 -0
- package/docs/TUTORIAL.md +178 -0
- package/package.json +47 -4
package/dist/keys.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { generateSecretKey, getPublicKey, hexKey, identityMessagingKey, signChecked, } from "./protocol.js";
|
|
2
|
+
import { publicationGroups } from "./relay-roles.js";
|
|
3
|
+
import { messagingMetadata } from "./metadata.js";
|
|
4
|
+
import { Nip4eCompatibilityError } from "./errors.js";
|
|
5
|
+
const secret = (value) => new Uint8Array(Buffer.from(value, "hex"));
|
|
6
|
+
const pub = (value) => getPublicKey(secret(value));
|
|
7
|
+
const encoded = (value) => Buffer.from(value).toString("hex");
|
|
8
|
+
/** One account-local codec-protected keyring, independent of message-mode database scope. */
|
|
9
|
+
export class EncryptionKeys {
|
|
10
|
+
identity;
|
|
11
|
+
mode;
|
|
12
|
+
store;
|
|
13
|
+
transport;
|
|
14
|
+
relays;
|
|
15
|
+
publishRelays;
|
|
16
|
+
metadata;
|
|
17
|
+
state;
|
|
18
|
+
operation;
|
|
19
|
+
rotation;
|
|
20
|
+
constructor(identity, mode, store, transport, relays, options, publishRelays = [relays], metadata) {
|
|
21
|
+
this.identity = identity;
|
|
22
|
+
this.mode = mode;
|
|
23
|
+
this.store = store;
|
|
24
|
+
this.transport = transport;
|
|
25
|
+
this.relays = relays;
|
|
26
|
+
this.publishRelays = publishRelays;
|
|
27
|
+
this.metadata = metadata;
|
|
28
|
+
identityMessagingKey(identity);
|
|
29
|
+
if (options) {
|
|
30
|
+
if (mode !== "nip4e") {
|
|
31
|
+
throw new TypeError("keyRotation requires explicit mode: nip4e");
|
|
32
|
+
}
|
|
33
|
+
if (!Number.isSafeInteger(options.intervalMs) ||
|
|
34
|
+
options.intervalMs < 1000 ||
|
|
35
|
+
options.intervalMs > Number.MAX_SAFE_INTEGER / 2) {
|
|
36
|
+
throw new TypeError("intervalMs must be a safe integer >= 1000");
|
|
37
|
+
}
|
|
38
|
+
const retain = options.retainLegacyKeys ?? 5;
|
|
39
|
+
if (!Number.isSafeInteger(retain) || retain < 1 || retain > 100) {
|
|
40
|
+
throw new TypeError("retainLegacyKeys must be in 1..100");
|
|
41
|
+
}
|
|
42
|
+
if (options.legacyMaxAgeMs !== undefined &&
|
|
43
|
+
(!Number.isSafeInteger(options.legacyMaxAgeMs) ||
|
|
44
|
+
options.legacyMaxAgeMs < 1000)) {
|
|
45
|
+
throw new TypeError("legacyMaxAgeMs must be >= 1000");
|
|
46
|
+
}
|
|
47
|
+
this.rotation = {
|
|
48
|
+
...options,
|
|
49
|
+
retainLegacyKeys: retain,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
this.state = store.keyring(identity.pubkey) ?? {
|
|
53
|
+
version: 1,
|
|
54
|
+
legacy: [],
|
|
55
|
+
};
|
|
56
|
+
if (this.state.version !== 1 || !Array.isArray(this.state.legacy)) {
|
|
57
|
+
throw new Error("Unsupported encryption keyring");
|
|
58
|
+
}
|
|
59
|
+
// A stale application-supplied initial key may be a retained key after restart.
|
|
60
|
+
const supplied = identity.encryptionKey &&
|
|
61
|
+
getPublicKey(identity.encryptionKey) !== identity.pubkey
|
|
62
|
+
? encoded(identity.encryptionKey)
|
|
63
|
+
: undefined;
|
|
64
|
+
if (mode === "nip4e") {
|
|
65
|
+
if (!this.state.active) {
|
|
66
|
+
this.state.active = {
|
|
67
|
+
secret: supplied ?? encoded(generateSecretKey()),
|
|
68
|
+
since: Date.now(),
|
|
69
|
+
};
|
|
70
|
+
this.state.bootstrapPublicKey = pub(this.state.active.secret);
|
|
71
|
+
}
|
|
72
|
+
else if (supplied &&
|
|
73
|
+
pub(supplied) !== this.state.bootstrapPublicKey &&
|
|
74
|
+
supplied !== this.state.active.secret &&
|
|
75
|
+
!this.state.legacy.some((k) => k.secret === supplied)) {
|
|
76
|
+
throw new Error("Supplied messaging key conflicts with persisted keyring; use the saved account keyring");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const key of identity.oldEncryptionKeys ?? []) {
|
|
80
|
+
const value = encoded(key);
|
|
81
|
+
if (getPublicKey(key) !== identity.pubkey &&
|
|
82
|
+
value !== this.state.active?.secret &&
|
|
83
|
+
!this.state.legacy.some((k) => k.secret === value)) {
|
|
84
|
+
this.state.legacy.push({
|
|
85
|
+
secret: value,
|
|
86
|
+
since: Date.now(),
|
|
87
|
+
retiredAt: Date.now(),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
this.save();
|
|
92
|
+
this.apply();
|
|
93
|
+
}
|
|
94
|
+
save() {
|
|
95
|
+
this.store.saveKeyring(this.identity.pubkey, this.state);
|
|
96
|
+
}
|
|
97
|
+
apply() {
|
|
98
|
+
const keys = [
|
|
99
|
+
...(this.state.active ? [this.state.active] : []),
|
|
100
|
+
...this.state.legacy,
|
|
101
|
+
...(this.state.pending?.secret
|
|
102
|
+
? [
|
|
103
|
+
{
|
|
104
|
+
secret: this.state.pending.secret,
|
|
105
|
+
since: 0,
|
|
106
|
+
},
|
|
107
|
+
]
|
|
108
|
+
: []),
|
|
109
|
+
];
|
|
110
|
+
this.identity.oldEncryptionKeys = [...new Set(keys.map((k) => k.secret))]
|
|
111
|
+
.filter((k) => this.mode !== "nip4e" || k !== this.state.active?.secret)
|
|
112
|
+
.map(secret);
|
|
113
|
+
if (this.mode === "nip4e") {
|
|
114
|
+
this.identity.encryptionKey = secret(this.activeKey().secret);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
activeKey() {
|
|
118
|
+
const active = this.state.active;
|
|
119
|
+
if (!active)
|
|
120
|
+
throw new Error("Missing active encryption key");
|
|
121
|
+
return active;
|
|
122
|
+
}
|
|
123
|
+
current() {
|
|
124
|
+
return this.mode === "nip4e"
|
|
125
|
+
? pub(this.activeKey().secret)
|
|
126
|
+
: this.identity.pubkey;
|
|
127
|
+
}
|
|
128
|
+
status() {
|
|
129
|
+
return {
|
|
130
|
+
currentPublicKey: this.current(),
|
|
131
|
+
decryptionPublicKeys: [
|
|
132
|
+
...new Set([
|
|
133
|
+
this.identity.pubkey,
|
|
134
|
+
...(this.state.active ? [pub(this.state.active.secret)] : []),
|
|
135
|
+
...this.state.legacy.map((k) => pub(k.secret)),
|
|
136
|
+
...(this.state.pending?.secret
|
|
137
|
+
? [pub(this.state.pending.secret)]
|
|
138
|
+
: []),
|
|
139
|
+
]),
|
|
140
|
+
],
|
|
141
|
+
activatedAt: this.mode === "nip4e" ? this.state.active?.since : undefined,
|
|
142
|
+
legacy: this.state.legacy.map((k) => ({
|
|
143
|
+
publicKey: pub(k.secret),
|
|
144
|
+
retiredAt: k.retiredAt,
|
|
145
|
+
})),
|
|
146
|
+
...(this.state.pending
|
|
147
|
+
? {
|
|
148
|
+
pending: {
|
|
149
|
+
publicKey: this.state.pending.event.tags[0][1],
|
|
150
|
+
eventId: this.state.pending.event.id,
|
|
151
|
+
},
|
|
152
|
+
}
|
|
153
|
+
: {}),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
knows(key) {
|
|
157
|
+
return (key === this.identity.pubkey ||
|
|
158
|
+
[this.state.active, ...this.state.legacy].some((k) => k && pub(k.secret) === key));
|
|
159
|
+
}
|
|
160
|
+
onImported;
|
|
161
|
+
synchronize;
|
|
162
|
+
setSynchronizer(sync) {
|
|
163
|
+
this.synchronize = sync;
|
|
164
|
+
}
|
|
165
|
+
exportEncryptionKey(key = this.current()) {
|
|
166
|
+
if (key === this.identity.pubkey) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const found = [
|
|
170
|
+
this.state.active,
|
|
171
|
+
...this.state.legacy,
|
|
172
|
+
...(this.state.pending?.secret
|
|
173
|
+
? [
|
|
174
|
+
{
|
|
175
|
+
secret: this.state.pending.secret,
|
|
176
|
+
since: 0,
|
|
177
|
+
},
|
|
178
|
+
]
|
|
179
|
+
: []),
|
|
180
|
+
].find((value) => value && pub(value.secret) === key);
|
|
181
|
+
return found ? secret(found.secret) : undefined;
|
|
182
|
+
}
|
|
183
|
+
async accept(event, allowed) {
|
|
184
|
+
const key = event?.tags.find((tag) => tag[0] === "n")?.[1];
|
|
185
|
+
if (this.mode === "nip4e" &&
|
|
186
|
+
this.synchronize &&
|
|
187
|
+
hexKey(key) &&
|
|
188
|
+
key !== this.identity.pubkey &&
|
|
189
|
+
!allowed.includes(key) &&
|
|
190
|
+
!this.state.pending) {
|
|
191
|
+
const value = this.exportEncryptionKey(key) ?? (await this.synchronize(key));
|
|
192
|
+
try {
|
|
193
|
+
if (getPublicKey(value) !== key ||
|
|
194
|
+
this.store
|
|
195
|
+
.declaration(this.identity.pubkey)
|
|
196
|
+
?.tags.find((tag) => tag[0] === "n")?.[1] !== key) {
|
|
197
|
+
throw new Error("Key synchronization no longer matches the current declaration");
|
|
198
|
+
}
|
|
199
|
+
const now = Date.now(), next = structuredClone(this.state);
|
|
200
|
+
if (next.active) {
|
|
201
|
+
next.legacy.unshift({
|
|
202
|
+
...next.active,
|
|
203
|
+
retiredAt: now,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
next.active = {
|
|
207
|
+
secret: encoded(value),
|
|
208
|
+
since: now,
|
|
209
|
+
};
|
|
210
|
+
const seen = new Set([key]);
|
|
211
|
+
next.legacy = next.legacy
|
|
212
|
+
.filter((item) => {
|
|
213
|
+
const publicKey = pub(item.secret);
|
|
214
|
+
if (seen.has(publicKey)) {
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
seen.add(publicKey);
|
|
218
|
+
return true;
|
|
219
|
+
})
|
|
220
|
+
.slice(0, this.rotation?.retainLegacyKeys ?? 5);
|
|
221
|
+
this.store.saveKeyring(this.identity.pubkey, next);
|
|
222
|
+
this.state = next;
|
|
223
|
+
this.apply();
|
|
224
|
+
this.onImported?.();
|
|
225
|
+
}
|
|
226
|
+
finally {
|
|
227
|
+
value.fill(0);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
this.check(event, [...allowed, this.current()]);
|
|
231
|
+
}
|
|
232
|
+
async declaration() {
|
|
233
|
+
for (const event of await (this.metadata
|
|
234
|
+
? this.metadata.read(this.identity.pubkey, [10044])
|
|
235
|
+
: messagingMetadata(this.identity.pubkey, [10044], this.transport, this.relays))) {
|
|
236
|
+
this.store.rememberDeclaration(event);
|
|
237
|
+
}
|
|
238
|
+
return this.store.declaration(this.identity.pubkey);
|
|
239
|
+
}
|
|
240
|
+
check(event, allowed) {
|
|
241
|
+
if (!event) {
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const key = event.tags.find((t) => t[0] === "n")?.[1];
|
|
245
|
+
if (!hexKey(key)) {
|
|
246
|
+
throw new Nip4eCompatibilityError("NIP4E_DECLARATION_INVALID");
|
|
247
|
+
}
|
|
248
|
+
if (!allowed.includes(key)) {
|
|
249
|
+
throw new Nip4eCompatibilityError("NIP4E_KEY_CONFLICT");
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
serialize(run) {
|
|
253
|
+
const task = (this.operation ?? Promise.resolve())
|
|
254
|
+
.catch(() => { })
|
|
255
|
+
.then(run);
|
|
256
|
+
this.operation = task;
|
|
257
|
+
void task
|
|
258
|
+
.finally(() => {
|
|
259
|
+
if (this.operation === task) {
|
|
260
|
+
this.operation = undefined;
|
|
261
|
+
}
|
|
262
|
+
})
|
|
263
|
+
.catch(() => { });
|
|
264
|
+
return task;
|
|
265
|
+
}
|
|
266
|
+
async resume() {
|
|
267
|
+
const pending = this.state.pending;
|
|
268
|
+
if (!pending) {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
// A mode change must finish the previously authorized operation in its original mode.
|
|
272
|
+
const target = pending.event.tags[0][1];
|
|
273
|
+
if ((pending.secret && this.mode !== "nip4e") ||
|
|
274
|
+
(!pending.secret && target !== this.current())) {
|
|
275
|
+
throw new Error("Pending key declaration belongs to the previous mode; resume it before switching modes");
|
|
276
|
+
}
|
|
277
|
+
this.check(await this.declaration(), [
|
|
278
|
+
target,
|
|
279
|
+
...(pending.previous ? [pending.previous] : []),
|
|
280
|
+
]);
|
|
281
|
+
this.save();
|
|
282
|
+
this.apply(); // Reassert durable custody after any prior local persistence failure.
|
|
283
|
+
for (const group of publicationGroups(this.publishRelays)) {
|
|
284
|
+
await this.transport.publish(group, pending.event);
|
|
285
|
+
}
|
|
286
|
+
// Keep the exact signed declaration until ACK; keys were already durable before publish.
|
|
287
|
+
this.store.rememberDeclaration(pending.event);
|
|
288
|
+
this.metadata?.rememberOwn(pending.event);
|
|
289
|
+
const next = structuredClone(this.state);
|
|
290
|
+
if (pending.secret) {
|
|
291
|
+
const now = Date.now();
|
|
292
|
+
if (next.active) {
|
|
293
|
+
next.legacy.unshift({
|
|
294
|
+
...next.active,
|
|
295
|
+
retiredAt: now,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
next.active = {
|
|
299
|
+
secret: pending.secret,
|
|
300
|
+
since: now,
|
|
301
|
+
};
|
|
302
|
+
const retain = this.rotation?.retainLegacyKeys ?? 5, age = this.rotation?.legacyMaxAgeMs;
|
|
303
|
+
next.legacy = next.legacy
|
|
304
|
+
.filter((k) => age === undefined || now - k.retiredAt <= age)
|
|
305
|
+
.slice(0, retain);
|
|
306
|
+
}
|
|
307
|
+
delete next.pending;
|
|
308
|
+
this.store.saveKeyring(this.identity.pubkey, next);
|
|
309
|
+
this.state = next;
|
|
310
|
+
this.apply();
|
|
311
|
+
}
|
|
312
|
+
async prepare() {
|
|
313
|
+
await this.serialize(async () => {
|
|
314
|
+
await this.resume();
|
|
315
|
+
await this.accept(await this.declaration(), [this.current()]);
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
async announce(options = {}) {
|
|
319
|
+
await this.serialize(async () => {
|
|
320
|
+
await this.resume();
|
|
321
|
+
const current = await this.declaration(), old = current?.tags.find((t) => t[0] === "n")?.[1];
|
|
322
|
+
if (options.replaceEncryptionKey !== undefined &&
|
|
323
|
+
(!hexKey(options.replaceEncryptionKey) ||
|
|
324
|
+
old !== options.replaceEncryptionKey ||
|
|
325
|
+
!this.knows(options.replaceEncryptionKey))) {
|
|
326
|
+
throw new Error("replaceEncryptionKey must match the latest declaration and a locally available decryption key");
|
|
327
|
+
}
|
|
328
|
+
await this.accept(current, [
|
|
329
|
+
this.current(),
|
|
330
|
+
...(options.replaceEncryptionKey ? [options.replaceEncryptionKey] : []),
|
|
331
|
+
]);
|
|
332
|
+
if (current && old === this.current()) {
|
|
333
|
+
// Reuse the signed declaration but rebroadcast to current write/DM sets.
|
|
334
|
+
const next = {
|
|
335
|
+
...this.state,
|
|
336
|
+
pending: {
|
|
337
|
+
event: current,
|
|
338
|
+
previous: old,
|
|
339
|
+
},
|
|
340
|
+
};
|
|
341
|
+
this.store.saveKeyring(this.identity.pubkey, next);
|
|
342
|
+
this.state = next;
|
|
343
|
+
await this.resume();
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
await this.stage(this.current(), current, undefined);
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
async stage(key, previous, value) {
|
|
350
|
+
// Strictly newer than all known declaration/old-seal seconds, including rapid rotations.
|
|
351
|
+
const created_at = Math.max(Math.floor(Date.now() / 1000) + 1, (previous?.created_at ?? 0) + 1);
|
|
352
|
+
const event = await signChecked(this.identity, {
|
|
353
|
+
kind: 10044,
|
|
354
|
+
created_at,
|
|
355
|
+
tags: [["n", key]],
|
|
356
|
+
content: "",
|
|
357
|
+
});
|
|
358
|
+
const previousKey = previous?.tags.find((tag) => tag[0] === "n")?.[1];
|
|
359
|
+
const next = {
|
|
360
|
+
...this.state,
|
|
361
|
+
pending: {
|
|
362
|
+
event,
|
|
363
|
+
...(value
|
|
364
|
+
? {
|
|
365
|
+
secret: value,
|
|
366
|
+
}
|
|
367
|
+
: {}),
|
|
368
|
+
...(previousKey === undefined ? {} : { previous: previousKey }),
|
|
369
|
+
},
|
|
370
|
+
};
|
|
371
|
+
this.store.saveKeyring(this.identity.pubkey, next);
|
|
372
|
+
this.state = next;
|
|
373
|
+
this.apply();
|
|
374
|
+
await this.resume();
|
|
375
|
+
}
|
|
376
|
+
rotating;
|
|
377
|
+
rotate() {
|
|
378
|
+
if (this.mode !== "nip4e") {
|
|
379
|
+
return Promise.reject(new Error("Encryption-key rotation requires mode: nip4e"));
|
|
380
|
+
}
|
|
381
|
+
if (this.rotating) {
|
|
382
|
+
return this.rotating;
|
|
383
|
+
}
|
|
384
|
+
const task = this.serialize(async () => {
|
|
385
|
+
if (this.state.pending) {
|
|
386
|
+
await this.resume();
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
const current = await this.declaration();
|
|
390
|
+
await this.accept(current, [this.current()]);
|
|
391
|
+
const value = encoded(generateSecretKey());
|
|
392
|
+
await this.stage(pub(value), current, value);
|
|
393
|
+
});
|
|
394
|
+
this.rotating = task;
|
|
395
|
+
void task
|
|
396
|
+
.finally(() => {
|
|
397
|
+
if (this.rotating === task) {
|
|
398
|
+
this.rotating = undefined;
|
|
399
|
+
}
|
|
400
|
+
})
|
|
401
|
+
.catch(() => { });
|
|
402
|
+
return task;
|
|
403
|
+
}
|
|
404
|
+
async rotateIfDue() {
|
|
405
|
+
if (this.rotation &&
|
|
406
|
+
Date.now() - this.activeKey().since >= this.rotation.intervalMs) {
|
|
407
|
+
await this.rotate();
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
nextDelay() {
|
|
411
|
+
return this.rotation
|
|
412
|
+
? Math.min(2147483647, Math.max(1000, this.rotation.intervalMs - (Date.now() - this.activeKey().since)))
|
|
413
|
+
: undefined;
|
|
414
|
+
}
|
|
415
|
+
async idle() {
|
|
416
|
+
await this.operation?.catch(() => { });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { MessageStorage } from "./message-storage.js";
|
|
2
|
+
export interface SQLiteMessageStorage extends MessageStorage {
|
|
3
|
+
close(): void;
|
|
4
|
+
}
|
|
5
|
+
/** Indexed message persistence. The application owns instances passed into Client. */
|
|
6
|
+
export declare function sqliteMessageStorage(path?: string): SQLiteMessageStorage;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { closeSync, openSync } from "node:fs";
|
|
3
|
+
/** Indexed message persistence. The application owns instances passed into Client. */
|
|
4
|
+
export function sqliteMessageStorage(path = "chirli-messages.sqlite") {
|
|
5
|
+
if (path !== ":memory:")
|
|
6
|
+
closeSync(openSync(path, "a", 0o600));
|
|
7
|
+
const db = new DatabaseSync(path);
|
|
8
|
+
try {
|
|
9
|
+
db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
|
|
10
|
+
CREATE TABLE IF NOT EXISTS message_records(
|
|
11
|
+
account TEXT NOT NULL,id TEXT NOT NULL,conversation TEXT NOT NULL,
|
|
12
|
+
timestamp INTEGER NOT NULL,payload TEXT NOT NULL,state TEXT NOT NULL,PRIMARY KEY(account,id));
|
|
13
|
+
CREATE INDEX IF NOT EXISTS stored_message_history ON message_records(account,conversation,timestamp DESC,id ASC);
|
|
14
|
+
CREATE INDEX IF NOT EXISTS stored_message_list ON message_records(account,timestamp ASC,id ASC);
|
|
15
|
+
CREATE INDEX IF NOT EXISTS stored_message_state ON message_records(account,state,timestamp ASC,id ASC);
|
|
16
|
+
CREATE INDEX IF NOT EXISTS stored_message_unfinished ON message_records(account,timestamp ASC,id DESC)
|
|
17
|
+
WHERE state IN ('pending','processing','failed');`);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
db.close();
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
const validateState = (state) => {
|
|
24
|
+
if (!["pending", "processing", "failed", "done"].includes(state))
|
|
25
|
+
throw new TypeError("Invalid message state");
|
|
26
|
+
};
|
|
27
|
+
return {
|
|
28
|
+
insert(account, message) {
|
|
29
|
+
validateState(message.state);
|
|
30
|
+
return (db
|
|
31
|
+
.prepare("INSERT OR IGNORE INTO message_records VALUES(?,?,?,?,?,?)")
|
|
32
|
+
.run(account, message.id, message.conversation, message.timestamp, message.payload, message.state).changes === 1);
|
|
33
|
+
},
|
|
34
|
+
updateState(account, id, state) {
|
|
35
|
+
validateState(state);
|
|
36
|
+
db.prepare("UPDATE message_records SET state=? WHERE account=? AND id=?").run(state, account, id);
|
|
37
|
+
},
|
|
38
|
+
query(account, options = {}) {
|
|
39
|
+
const order = options.order ?? "oldest";
|
|
40
|
+
if (!["oldest", "newest", "recovery"].includes(order))
|
|
41
|
+
throw new TypeError("Invalid message query order");
|
|
42
|
+
const timeOrder = order === "newest" ? "DESC" : "ASC";
|
|
43
|
+
const idOrder = order === "recovery" ? "DESC" : "ASC";
|
|
44
|
+
const where = ["account=?"];
|
|
45
|
+
const parameters = [account];
|
|
46
|
+
if (options.id !== undefined) {
|
|
47
|
+
where.push("id=?");
|
|
48
|
+
parameters.push(options.id);
|
|
49
|
+
}
|
|
50
|
+
if (options.conversation !== undefined) {
|
|
51
|
+
where.push("conversation=?");
|
|
52
|
+
parameters.push(options.conversation);
|
|
53
|
+
}
|
|
54
|
+
if (options.states) {
|
|
55
|
+
if (!options.states.length)
|
|
56
|
+
return [];
|
|
57
|
+
const states = [...new Set(options.states)];
|
|
58
|
+
for (const state of states)
|
|
59
|
+
validateState(state);
|
|
60
|
+
if (states.length === 3 && !states.includes("done")) {
|
|
61
|
+
where.push("state IN ('pending','processing','failed')");
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
where.push(`state IN (${states.map(() => "?").join(",")})`);
|
|
65
|
+
parameters.push(...states);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (options.cursor) {
|
|
69
|
+
const timeComparison = order === "newest" ? "<" : ">";
|
|
70
|
+
const idComparison = order === "recovery" ? "<" : ">";
|
|
71
|
+
// This range lets SQLite seek into the ordering index before applying tie-breaking.
|
|
72
|
+
where.push(`timestamp ${timeComparison}= ? AND (timestamp ${timeComparison} ? OR (timestamp=? AND id ${idComparison} ?))`);
|
|
73
|
+
parameters.push(options.cursor.timestamp, options.cursor.timestamp, options.cursor.timestamp, options.cursor.id);
|
|
74
|
+
}
|
|
75
|
+
let sql = `SELECT id,conversation,timestamp,payload,state FROM message_records WHERE ${where.join(" AND ")} ORDER BY timestamp ${timeOrder},id ${idOrder}`;
|
|
76
|
+
if (options.limit !== undefined) {
|
|
77
|
+
if (!Number.isSafeInteger(options.limit) || options.limit < 0)
|
|
78
|
+
throw new TypeError("Invalid message query limit");
|
|
79
|
+
sql += " LIMIT ?";
|
|
80
|
+
parameters.push(options.limit);
|
|
81
|
+
}
|
|
82
|
+
return db
|
|
83
|
+
.prepare(sql)
|
|
84
|
+
.all(...parameters);
|
|
85
|
+
},
|
|
86
|
+
close() {
|
|
87
|
+
db.close();
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { MessageState } from "./storage.js";
|
|
2
|
+
/** Message payload and its processing state form one durable record. */
|
|
3
|
+
export interface MessageStorageEntry {
|
|
4
|
+
id: string;
|
|
5
|
+
conversation: string;
|
|
6
|
+
timestamp: number;
|
|
7
|
+
/** SDK-encoded bytes; preserve them without decoding or rewriting. */
|
|
8
|
+
payload: string;
|
|
9
|
+
state: MessageState;
|
|
10
|
+
}
|
|
11
|
+
export interface MessageStorageQuery {
|
|
12
|
+
id?: string;
|
|
13
|
+
conversation?: string;
|
|
14
|
+
states?: readonly MessageState[];
|
|
15
|
+
/** oldest: time ASC, ID ASC; newest: time DESC, ID ASC; recovery: time ASC, ID DESC. */
|
|
16
|
+
order?: "oldest" | "newest" | "recovery";
|
|
17
|
+
/** Exclusive position in the requested order. */
|
|
18
|
+
cursor?: {
|
|
19
|
+
timestamp: number;
|
|
20
|
+
id: string;
|
|
21
|
+
};
|
|
22
|
+
limit?: number;
|
|
23
|
+
}
|
|
24
|
+
/** Synchronous message persistence, including deduplication and processing state. */
|
|
25
|
+
export interface MessageStorage {
|
|
26
|
+
/** Atomically insert once by account + ID. A duplicate returns false without changes. */
|
|
27
|
+
insert(account: string, message: MessageStorageEntry): boolean;
|
|
28
|
+
/** Apply filters, ordering, cursors and limits inside the database; return detached rows. */
|
|
29
|
+
query(account: string, options?: MessageStorageQuery): MessageStorageEntry[];
|
|
30
|
+
/** Update only the state of an existing account + ID; never create or replace a message. */
|
|
31
|
+
updateState(account: string, id: string, state: MessageState): void;
|
|
32
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Event } from "nostr-tools";
|
|
2
|
+
import { type ReconnectOptions } from "./inbox.js";
|
|
3
|
+
import type { Store } from "./store.js";
|
|
4
|
+
import type { Transport } from "./relay.js";
|
|
5
|
+
export interface MetadataCacheOptions {
|
|
6
|
+
ttlMs?: number;
|
|
7
|
+
negativeTtlMs?: number;
|
|
8
|
+
maxStaleMs?: number;
|
|
9
|
+
maxEntries?: number;
|
|
10
|
+
}
|
|
11
|
+
export declare class MessagingMetadata {
|
|
12
|
+
private pubkey;
|
|
13
|
+
private store;
|
|
14
|
+
private transport;
|
|
15
|
+
private relays;
|
|
16
|
+
private error;
|
|
17
|
+
private reconnect;
|
|
18
|
+
private options;
|
|
19
|
+
private own;
|
|
20
|
+
private peers;
|
|
21
|
+
private flights;
|
|
22
|
+
private jobs;
|
|
23
|
+
private refreshQueue;
|
|
24
|
+
private queued;
|
|
25
|
+
private refreshing;
|
|
26
|
+
private retryAt;
|
|
27
|
+
private watcher?;
|
|
28
|
+
private starting?;
|
|
29
|
+
private watching;
|
|
30
|
+
private ttl;
|
|
31
|
+
private negative;
|
|
32
|
+
private stale;
|
|
33
|
+
private capacity;
|
|
34
|
+
onOwnEvent?: (event: Event) => Promise<void>;
|
|
35
|
+
constructor(pubkey: string, store: Store, transport: Transport, relays: string[], error: (error: unknown) => void, reconnect: false | ReconnectOptions | undefined, options?: false | MetadataCacheOptions);
|
|
36
|
+
private valid;
|
|
37
|
+
rememberOwn(event: Event): void;
|
|
38
|
+
private ownEvents;
|
|
39
|
+
ownDmRelays(fallback: string[]): string[];
|
|
40
|
+
start(): Promise<void>;
|
|
41
|
+
read(peer: string, kinds: number[], force?: boolean): Promise<Event[]>;
|
|
42
|
+
private refresh;
|
|
43
|
+
private drain;
|
|
44
|
+
private savePeer;
|
|
45
|
+
private fetch;
|
|
46
|
+
stop(): Promise<void>;
|
|
47
|
+
idle(): Promise<void>;
|
|
48
|
+
}
|