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,87 @@
1
+ import { verifyEvent } from "nostr-tools";
2
+ import { AbstractSimplePool, } from "nostr-tools/abstract-pool";
3
+ import { websocketURL } from "../metadata.js";
4
+ import { DEFAULT_RELAY_TIMEOUTS, WebSocketTransport, subscribeRequests, } from "../relay.js";
5
+ export function bunkerRelayURLs(values) {
6
+ if (!Array.isArray(values) || !values.length)
7
+ throw new TypeError("At least one bunker relay is required");
8
+ if (!Array.from(values).every(websocketURL))
9
+ throw new TypeError("Invalid bunker relay URL");
10
+ return [...new Set(values.map((value) => new URL(value).href))];
11
+ }
12
+ /** Bridge the two pool operations used by nostr-tools' BunkerSigner. */
13
+ export class BunkerRelayPool extends AbstractSimplePool {
14
+ transport;
15
+ subscriptionClosers = new Set();
16
+ current;
17
+ constructor(timeoutMs) {
18
+ super({ verifyEvent, maxWaitForConnection: timeoutMs });
19
+ this.transport = new WebSocketTransport({
20
+ connectionTimeoutMs: timeoutMs,
21
+ publishTimeoutMs: Math.min(timeoutMs, DEFAULT_RELAY_TIMEOUTS.publishTimeoutMs),
22
+ });
23
+ }
24
+ subscribe(relays, filter, params) {
25
+ const urls = bunkerRelayURLs(relays);
26
+ const subscriptions = new Map();
27
+ const reasons = new Map();
28
+ let closed = false;
29
+ const close = () => {
30
+ closed = true;
31
+ this.subscriptionClosers.delete(close);
32
+ if (this.current === publish)
33
+ this.current = undefined;
34
+ for (const sub of subscriptions.values())
35
+ sub.close();
36
+ subscriptions.clear();
37
+ };
38
+ const open = (url) => {
39
+ const failed = (error) => {
40
+ if (subscriptions.get(url) !== sub)
41
+ return;
42
+ sub.close();
43
+ subscriptions.delete(url);
44
+ reasons.set(url, error.message);
45
+ if (!subscriptions.size) {
46
+ close();
47
+ params.onclose?.(urls.map((url) => ({
48
+ url,
49
+ reason: reasons.get(url) ?? "Subscription closed",
50
+ })));
51
+ }
52
+ };
53
+ const sub = subscribeRequests(this.transport, [url], filter, (event) => params.onevent?.(event), failed);
54
+ subscriptions.set(url, sub);
55
+ void sub.ready.catch(failed);
56
+ return sub;
57
+ };
58
+ const publish = async (url, event) => {
59
+ if (closed || !urls.includes(url))
60
+ throw new Error("Bunker subscription unavailable");
61
+ const sub = subscriptions.get(url) ?? open(url);
62
+ await sub.ready;
63
+ if (subscriptions.get(url) !== sub)
64
+ throw new Error("Bunker subscription unavailable");
65
+ await this.transport.publish([url], event);
66
+ return "";
67
+ };
68
+ for (const url of urls)
69
+ open(url);
70
+ this.subscriptionClosers.add(close);
71
+ this.current = publish;
72
+ return { close };
73
+ }
74
+ publish(relays, event) {
75
+ const publish = this.current;
76
+ return bunkerRelayURLs(relays).map(async (url) => {
77
+ if (!publish)
78
+ throw new Error("Bunker subscription unavailable");
79
+ return publish(url, event);
80
+ });
81
+ }
82
+ destroy() {
83
+ for (const close of this.subscriptionClosers)
84
+ close();
85
+ this.transport.close();
86
+ }
87
+ }
@@ -0,0 +1,7 @@
1
+ import type { Signer } from "../signer.js";
2
+ export interface BunkerOptions {
3
+ clientSecret: Uint8Array;
4
+ timeoutMs?: number;
5
+ }
6
+ /** Lazy, shared NIP-46 handshake; closing releases this session, never logs out/deletes an account. */
7
+ export declare function bunkerSigner(input: string, options: BunkerOptions): Signer & Required<Pick<Signer, "close" | "nip04Encrypt" | "nip04Decrypt">>;
@@ -0,0 +1,194 @@
1
+ import { getPublicKey, getEventHash, verifyEvent } from "nostr-tools";
2
+ import { BunkerSigner } from "nostr-tools/nip46";
3
+ import { BunkerRelayPool, bunkerRelayURLs } from "./bunker-relays.js";
4
+ import { hexKey } from "../protocol.js";
5
+ import { SignerError } from "../errors.js";
6
+ /** Lazy, shared NIP-46 handshake; closing releases this session, never logs out/deletes an account. */
7
+ export function bunkerSigner(input, options) {
8
+ let pointer;
9
+ try {
10
+ const url = new URL(input);
11
+ if (url.protocol !== "bunker:" ||
12
+ !hexKey(url.hostname) ||
13
+ url.username ||
14
+ url.password ||
15
+ url.port ||
16
+ (url.pathname && url.pathname !== "/") ||
17
+ url.hash) {
18
+ throw new Error();
19
+ }
20
+ pointer = {
21
+ pubkey: url.hostname,
22
+ relays: bunkerRelayURLs(url.searchParams.getAll("relay")),
23
+ secret: url.searchParams.get("secret"),
24
+ };
25
+ }
26
+ catch {
27
+ throw new TypeError("Invalid bunker connection URI");
28
+ }
29
+ if (!(options?.clientSecret instanceof Uint8Array) ||
30
+ options.clientSecret.length !== 32) {
31
+ throw new TypeError("clientSecret must be a 32-byte NIP-46 client private key");
32
+ }
33
+ const timeoutMs = options.timeoutMs ?? 15000;
34
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000) {
35
+ throw new TypeError("timeoutMs must be in 1..300000");
36
+ }
37
+ const clientSecret = new Uint8Array(options.clientSecret);
38
+ try {
39
+ getPublicKey(clientSecret);
40
+ }
41
+ catch {
42
+ throw new TypeError("clientSecret must be a valid NIP-46 client private key");
43
+ }
44
+ let closed = false, inner, connecting;
45
+ let pinnedAccount;
46
+ const candidates = new Map();
47
+ const check = () => {
48
+ if (closed) {
49
+ throw new SignerError("session", "SIGNER_CLOSED");
50
+ }
51
+ };
52
+ async function bounded(operation, promise) {
53
+ let timer;
54
+ try {
55
+ const value = await Promise.race([
56
+ promise,
57
+ new Promise((_resolve, reject) => {
58
+ timer = setTimeout(() => reject(new SignerError(operation, "SIGNER_TIMEOUT")), timeoutMs);
59
+ }),
60
+ ]);
61
+ check();
62
+ return value;
63
+ }
64
+ catch (error) {
65
+ if (closed) {
66
+ throw new SignerError(operation, "SIGNER_CLOSED");
67
+ }
68
+ if (error instanceof SignerError) {
69
+ throw error;
70
+ }
71
+ throw new SignerError(operation, error instanceof Error && /timeout/i.test(error.message)
72
+ ? "SIGNER_TIMEOUT"
73
+ : "SIGNER_FAILED");
74
+ }
75
+ finally {
76
+ clearTimeout(timer);
77
+ }
78
+ }
79
+ async function discard(signer) {
80
+ const pool = candidates.get(signer);
81
+ if (!pool) {
82
+ return;
83
+ }
84
+ candidates.delete(signer);
85
+ if (inner === signer) {
86
+ inner = undefined;
87
+ }
88
+ await signer.close().catch(() => { });
89
+ pool.destroy();
90
+ }
91
+ function ensure() {
92
+ try {
93
+ check();
94
+ }
95
+ catch (error) {
96
+ return Promise.reject(error);
97
+ }
98
+ if (inner) {
99
+ return Promise.resolve(inner);
100
+ }
101
+ if (connecting) {
102
+ return connecting;
103
+ }
104
+ const pool = new BunkerRelayPool(timeoutMs);
105
+ const candidate = BunkerSigner.fromBunker(clientSecret, {
106
+ ...pointer,
107
+ relays: [...pointer.relays],
108
+ }, {
109
+ pool,
110
+ timeout: timeoutMs,
111
+ });
112
+ candidates.set(candidate, pool);
113
+ const pending = (async () => {
114
+ try {
115
+ await bounded("connect", candidate.connect({ name: "Chirli" }));
116
+ pointer.secret = null; // Reconnect with the same client key, never reuse the single-use token.
117
+ const account = await bounded("get_public_key", candidate.getPublicKey());
118
+ if (!hexKey(account) || (pinnedAccount && pinnedAccount !== account)) {
119
+ throw new SignerError("account binding");
120
+ }
121
+ pinnedAccount = account;
122
+ await bounded("switch_relays", candidate.switchRelays());
123
+ bunkerRelayURLs(candidate.bp.relays);
124
+ check();
125
+ inner = candidate;
126
+ return candidate;
127
+ }
128
+ catch (error) {
129
+ await discard(candidate);
130
+ throw error;
131
+ }
132
+ })().finally(() => {
133
+ if (connecting === pending) {
134
+ connecting = undefined;
135
+ }
136
+ });
137
+ connecting = pending;
138
+ return pending;
139
+ }
140
+ function accountKey() {
141
+ if (!pinnedAccount)
142
+ throw new SignerError("account binding");
143
+ return pinnedAccount;
144
+ }
145
+ async function request(operation, run) {
146
+ const signer = await ensure();
147
+ try {
148
+ return await bounded(operation, run(signer));
149
+ }
150
+ catch (error) {
151
+ if (error instanceof SignerError && error.code === "SIGNER_TIMEOUT") {
152
+ await discard(signer);
153
+ }
154
+ throw error;
155
+ }
156
+ }
157
+ return {
158
+ async getPublicKey() {
159
+ await ensure();
160
+ check();
161
+ return accountKey();
162
+ },
163
+ async signEvent(template) {
164
+ const snapshot = structuredClone(template);
165
+ await ensure();
166
+ const account = accountKey();
167
+ const expected = getEventHash({
168
+ ...snapshot,
169
+ pubkey: account,
170
+ });
171
+ const signed = await request("sign_event", (signer) => signer.signEvent(snapshot));
172
+ if (signed.pubkey !== account ||
173
+ signed.id !== expected ||
174
+ !verifyEvent(JSON.parse(JSON.stringify(signed)))) {
175
+ throw new SignerError("sign_event validation");
176
+ }
177
+ return signed;
178
+ },
179
+ nip44Encrypt: (peer, text) => request("nip44_encrypt", (signer) => signer.nip44Encrypt(peer, text)),
180
+ nip44Decrypt: (peer, content) => request("nip44_decrypt", (signer) => signer.nip44Decrypt(peer, content)),
181
+ nip04Encrypt: (peer, text) => request("nip04_encrypt", (signer) => signer.nip04Encrypt(peer, text)),
182
+ nip04Decrypt: (peer, content) => request("nip04_decrypt", (signer) => signer.nip04Decrypt(peer, content)),
183
+ async close() {
184
+ if (closed) {
185
+ return;
186
+ }
187
+ closed = true;
188
+ clientSecret.fill(0);
189
+ pointer.secret = null;
190
+ inner = undefined;
191
+ await Promise.all([...candidates.keys()].map(discard));
192
+ },
193
+ };
194
+ }
@@ -0,0 +1,3 @@
1
+ import type { Signer } from "../signer.js";
2
+ /** Local account signer. Secret bytes live only in this instance's closure. */
3
+ export declare function nsecSigner(nsec: string | Uint8Array): Signer & Required<Pick<Signer, "close" | "nip04Encrypt" | "nip04Decrypt">>;
@@ -0,0 +1,62 @@
1
+ import { finalizeEvent, getPublicKey, nip44 } from "nostr-tools";
2
+ import { decode } from "nostr-tools/nip19";
3
+ import * as nip04 from "nostr-tools/nip04";
4
+ import { SignerError } from "../errors.js";
5
+ /** Local account signer. Secret bytes live only in this instance's closure. */
6
+ export function nsecSigner(nsec) {
7
+ let secret;
8
+ let pubkey;
9
+ try {
10
+ if (typeof nsec === "string") {
11
+ const decoded = decode(nsec);
12
+ if (decoded.type !== "nsec") {
13
+ throw new Error();
14
+ }
15
+ secret = new Uint8Array(decoded.data);
16
+ }
17
+ else {
18
+ // Copy caller bytes: closing one signer must never wipe another owner's key.
19
+ secret = new Uint8Array(nsec);
20
+ }
21
+ pubkey = getPublicKey(secret);
22
+ }
23
+ catch {
24
+ throw new TypeError("Invalid nsec secret key");
25
+ }
26
+ let closed = false;
27
+ const check = () => {
28
+ if (closed) {
29
+ throw new SignerError("local", "SIGNER_CLOSED");
30
+ }
31
+ };
32
+ return {
33
+ async getPublicKey() {
34
+ check();
35
+ return pubkey;
36
+ },
37
+ async signEvent(template) {
38
+ check();
39
+ return finalizeEvent(template, secret);
40
+ },
41
+ async nip44Encrypt(peer, text) {
42
+ check();
43
+ return nip44.v2.encrypt(text, nip44.v2.utils.getConversationKey(secret, peer));
44
+ },
45
+ async nip44Decrypt(peer, content) {
46
+ check();
47
+ return nip44.v2.decrypt(content, nip44.v2.utils.getConversationKey(secret, peer));
48
+ },
49
+ async nip04Encrypt(peer, text) {
50
+ check();
51
+ return nip04.encrypt(secret, peer, text);
52
+ },
53
+ async nip04Decrypt(peer, content) {
54
+ check();
55
+ return nip04.decrypt(secret, peer, content);
56
+ },
57
+ async close() {
58
+ closed = true;
59
+ secret.fill(0);
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,18 @@
1
+ import { type Identity, type LocalIdentity } from "./protocol.js";
2
+ import type { Signer } from "./signer.js";
3
+ import { nsecSigner } from "./signers/nsec.js";
4
+ import { bunkerSigner } from "./signers/bunker.js";
5
+ export { nsecSigner, bunkerSigner };
6
+ export type { Signer } from "./signer.js";
7
+ export type { BunkerOptions } from "./signers/bunker.js";
8
+ /** Internal protocol capabilities resolved once from the account signer. */
9
+ export declare function identityFromSigner(signer: Signer, options: {
10
+ mode?: "nip4e";
11
+ encryptionKey: Uint8Array;
12
+ oldEncryptionKeys?: Uint8Array[];
13
+ }): Promise<LocalIdentity>;
14
+ export declare function identityFromSigner(signer: Signer, options?: {
15
+ mode?: "nip17" | "nip4e";
16
+ encryptionKey?: Uint8Array;
17
+ oldEncryptionKeys?: Uint8Array[];
18
+ }): Promise<Identity>;
@@ -0,0 +1,59 @@
1
+ import { getPublicKey } from "nostr-tools";
2
+ import { hexKey } from "./protocol.js";
3
+ import { SignerError } from "./errors.js";
4
+ import { nsecSigner } from "./signers/nsec.js";
5
+ import { bunkerSigner } from "./signers/bunker.js";
6
+ export { nsecSigner, bunkerSigner };
7
+ export async function identityFromSigner(signer, options = {}) {
8
+ if (options.mode !== undefined &&
9
+ options.mode !== "nip4e" &&
10
+ options.mode !== "nip17") {
11
+ throw new TypeError("Invalid signer identity mode");
12
+ }
13
+ // Supplying a messaging key is the legacy explicit split-key form.
14
+ const mode = options.mode ?? (options.encryptionKey ? "nip4e" : "nip17");
15
+ if (mode === "nip17" && options.encryptionKey) {
16
+ throw new TypeError("nip17 signer identities do not accept split messaging keys");
17
+ }
18
+ // Every supported DM profile needs identity-key NIP-44, even with split outgoing keys.
19
+ for (const capability of [
20
+ "getPublicKey",
21
+ "signEvent",
22
+ "nip44Encrypt",
23
+ "nip44Decrypt",
24
+ ]) {
25
+ if (typeof signer?.[capability] !== "function") {
26
+ throw new TypeError(`Signer must implement ${capability}`);
27
+ }
28
+ }
29
+ const pubkey = await signer.getPublicKey();
30
+ if (!hexKey(pubkey)) {
31
+ throw new SignerError("get_public_key validation");
32
+ }
33
+ const crypto = {
34
+ publicKey: pubkey,
35
+ asynchronous: true,
36
+ encrypt: (text, peer) => signer.nip44Encrypt(peer, text),
37
+ decrypt: (content, peer) => signer.nip44Decrypt(peer, content),
38
+ };
39
+ const common = {
40
+ pubkey,
41
+ sign: (template) => signer.signEvent(template),
42
+ identityEncryption: crypto,
43
+ };
44
+ if (mode === "nip17") {
45
+ return {
46
+ ...common,
47
+ messaging: crypto,
48
+ oldEncryptionKeys: options.oldEncryptionKeys,
49
+ };
50
+ }
51
+ if (options.encryptionKey) {
52
+ getPublicKey(options.encryptionKey);
53
+ }
54
+ return {
55
+ ...common,
56
+ encryptionKey: options.encryptionKey,
57
+ oldEncryptionKeys: options.oldEncryptionKeys,
58
+ };
59
+ }
@@ -0,0 +1,29 @@
1
+ import type { StorageAdapter, StoragePayload, StoredMessage, StoredOutbox, MessageState, KeyEvidence, StoredDeclaration, MessageQuery, OutboxQuery, OutboxState, StorageRecord } from "./storage.js";
2
+ /** Indexed relational storage. Query planning stays in the database. */
3
+ export declare class SQLiteStorage implements StorageAdapter {
4
+ private db;
5
+ constructor(path?: string);
6
+ /** Remove a committed handoff only after the message backend has durably accepted it. */
7
+ discardStagedMessage(account: string, id: string): void;
8
+ insert(account: string, value: StorageRecord): boolean;
9
+ ensureDmActivation(pubkey: string, proposedAt: number): number;
10
+ claimInput(account: string, id: string): boolean;
11
+ queryMessages(account: string, query?: MessageQuery): StoredMessage[];
12
+ queryOutbox(account: string, query?: OutboxQuery): StoredOutbox[];
13
+ updateMessageState(account: string, id: string, state: MessageState): void;
14
+ updateOutboxState(account: string, id: string, state: OutboxState): void;
15
+ getEvidence(a: string, p: string): KeyEvidence | undefined;
16
+ setEvidence(a: string, p: string, r: KeyEvidence): void;
17
+ getDeclaration(a: string, p: string): StoredDeclaration | undefined;
18
+ setDeclaration(a: string, p: string, r: StoredDeclaration): void;
19
+ markSplitPeer(a: string, p: string): void;
20
+ isSplitPeer(a: string, p: string): boolean;
21
+ getSession(a: string, p: string): StoragePayload | undefined;
22
+ setSession(a: string, p: string, payload: StoragePayload): void;
23
+ getCheckpoint(a: string, r: string): number | undefined;
24
+ setCheckpoint(a: string, r: string, t: number): void;
25
+ getKeyring(i: string): StoragePayload | undefined;
26
+ setKeyring(i: string, p: StoragePayload): void;
27
+ transaction(run: () => void): void;
28
+ close(): void;
29
+ }
@@ -0,0 +1,221 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import { openSync, closeSync } from "node:fs";
3
+ /** Indexed relational storage. Query planning stays in the database. */
4
+ export class SQLiteStorage {
5
+ db;
6
+ constructor(path = "psstpsst.sqlite") {
7
+ if (path !== ":memory:")
8
+ closeSync(openSync(path, "a", 0o600));
9
+ this.db = new DatabaseSync(path);
10
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
11
+ CREATE TABLE IF NOT EXISTS messages(account TEXT,id TEXT,peer TEXT,time INTEGER,payload TEXT,state TEXT,PRIMARY KEY(account,id));
12
+ CREATE INDEX IF NOT EXISTS history ON messages(account,peer,time DESC,id ASC);
13
+ CREATE INDEX IF NOT EXISTS message_list ON messages(account,time ASC,id ASC);
14
+ CREATE INDEX IF NOT EXISTS message_state ON messages(account,state,time ASC,id ASC);
15
+ CREATE INDEX IF NOT EXISTS message_unfinished ON messages(account,time ASC,id DESC) WHERE state IN ('pending','processing','failed');
16
+ CREATE TABLE IF NOT EXISTS dm_activations(pubkey TEXT PRIMARY KEY, activated_at INTEGER NOT NULL) WITHOUT ROWID;
17
+ CREATE TABLE IF NOT EXISTS input_claims(account TEXT,id TEXT,PRIMARY KEY(account,id)) WITHOUT ROWID;
18
+ CREATE TABLE IF NOT EXISTS outbox(account TEXT,id TEXT,payload TEXT,state TEXT,PRIMARY KEY(account,id));
19
+ CREATE INDEX IF NOT EXISTS outbox_state ON outbox(account,state,id);
20
+ CREATE TABLE IF NOT EXISTS evidence(account TEXT,peer TEXT,key TEXT,time INTEGER,id TEXT,PRIMARY KEY(account,peer));
21
+ CREATE TABLE IF NOT EXISTS sessions(account TEXT,peer TEXT,payload TEXT,PRIMARY KEY(account,peer));
22
+ CREATE TABLE IF NOT EXISTS relay_checkpoints(account TEXT,relay TEXT,through INTEGER,PRIMARY KEY(account,relay));
23
+ CREATE TABLE IF NOT EXISTS encryption_keyrings(identity TEXT PRIMARY KEY,payload TEXT);
24
+ CREATE TABLE IF NOT EXISTS peer_declarations(account TEXT,peer TEXT,time INTEGER,id TEXT,payload TEXT,split_seen INTEGER DEFAULT 0,PRIMARY KEY(account,peer));`);
25
+ }
26
+ /** Remove a committed handoff only after the message backend has durably accepted it. */
27
+ discardStagedMessage(account, id) {
28
+ this.db
29
+ .prepare("DELETE FROM messages WHERE account=? AND id=?")
30
+ .run(account, id);
31
+ }
32
+ insert(account, value) {
33
+ const row = value.record;
34
+ if (value.collection === "messages") {
35
+ const message = value.record;
36
+ return (this.db
37
+ .prepare("INSERT OR IGNORE INTO messages VALUES(?,?,?,?,?,?)")
38
+ .run(account, message.id, message.peer, message.time, message.payload, message.state).changes === 1);
39
+ }
40
+ if (value.collection !== "outbox")
41
+ throw new TypeError("Invalid storage collection");
42
+ return (this.db
43
+ .prepare("INSERT OR IGNORE INTO outbox VALUES(?,?,?,?)")
44
+ .run(account, row.id, row.payload, row.state).changes === 1);
45
+ }
46
+ ensureDmActivation(pubkey, proposedAt) {
47
+ this.db
48
+ .prepare("INSERT OR IGNORE INTO dm_activations(pubkey, activated_at) VALUES(?,?)")
49
+ .run(pubkey, proposedAt);
50
+ return this.db
51
+ .prepare("SELECT activated_at FROM dm_activations WHERE pubkey=?")
52
+ .get(pubkey).activated_at;
53
+ }
54
+ claimInput(account, id) {
55
+ return (this.db
56
+ .prepare("INSERT OR IGNORE INTO input_claims(account,id) VALUES(?,?)")
57
+ .run(account, id).changes === 1);
58
+ }
59
+ queryMessages(account, query = {}) {
60
+ const timeOrder = query.order?.time ?? "asc";
61
+ const idOrder = query.order?.id ?? "asc";
62
+ if (!["asc", "desc"].includes(timeOrder) ||
63
+ !["asc", "desc"].includes(idOrder)) {
64
+ throw new TypeError("Invalid message query ordering");
65
+ }
66
+ const where = ["account=?"];
67
+ const parameters = [account];
68
+ if (query.id !== undefined) {
69
+ where.push("id=?");
70
+ parameters.push(query.id);
71
+ }
72
+ if (query.peer !== undefined) {
73
+ where.push("peer=?");
74
+ parameters.push(query.peer);
75
+ }
76
+ if (query.states) {
77
+ if (!query.states.length)
78
+ return [];
79
+ const states = [...new Set(query.states)];
80
+ if (!states.every((state) => ["pending", "processing", "failed", "done"].includes(state)))
81
+ throw new TypeError("Invalid message query state");
82
+ if (states.length === 3 && !states.includes("done")) {
83
+ // Match the unfinished-work partial index without scanning completed history.
84
+ where.push("state IN ('pending','processing','failed')");
85
+ }
86
+ else {
87
+ where.push(`state IN (${states.map(() => "?").join(",")})`);
88
+ parameters.push(...states);
89
+ }
90
+ }
91
+ if (query.cursor) {
92
+ const timeComparison = timeOrder === "asc" ? ">" : "<";
93
+ const idComparison = idOrder === "asc" ? ">" : "<";
94
+ // The outer range condition lets SQLite seek to the cursor in the ordering index.
95
+ where.push(`time ${timeComparison}= ? AND (time ${timeComparison} ? OR (time=? AND id ${idComparison} ?))`);
96
+ parameters.push(query.cursor.time, query.cursor.time, query.cursor.time, query.cursor.id);
97
+ }
98
+ let sql = `SELECT id,peer,time,payload,state FROM messages WHERE ${where.join(" AND ")} ORDER BY time ${timeOrder},id ${idOrder}`;
99
+ if (query.limit !== undefined) {
100
+ if (!Number.isSafeInteger(query.limit) || query.limit < 0)
101
+ throw new TypeError("Invalid query limit");
102
+ sql += " LIMIT ?";
103
+ parameters.push(query.limit);
104
+ }
105
+ return this.db
106
+ .prepare(sql)
107
+ .all(...parameters);
108
+ }
109
+ queryOutbox(account, query = {}) {
110
+ const where = ["account=?"];
111
+ const parameters = [account];
112
+ if (query.id !== undefined) {
113
+ where.push("id=?");
114
+ parameters.push(query.id);
115
+ }
116
+ if (query.state !== undefined) {
117
+ where.push("state=?");
118
+ parameters.push(query.state);
119
+ }
120
+ let sql = `SELECT id,payload,state FROM outbox WHERE ${where.join(" AND ")} ORDER BY id ASC`;
121
+ if (query.limit !== undefined) {
122
+ if (!Number.isSafeInteger(query.limit) || query.limit < 0)
123
+ throw new TypeError("Invalid query limit");
124
+ sql += " LIMIT ?";
125
+ parameters.push(query.limit);
126
+ }
127
+ return this.db.prepare(sql).all(...parameters);
128
+ }
129
+ updateMessageState(account, id, state) {
130
+ if (!["pending", "processing", "failed", "done"].includes(state))
131
+ throw new TypeError("Invalid message state");
132
+ this.db
133
+ .prepare("UPDATE messages SET state=? WHERE account=? AND id=?")
134
+ .run(state, account, id);
135
+ }
136
+ updateOutboxState(account, id, state) {
137
+ if (!["pending", "relay-accepted"].includes(state))
138
+ throw new TypeError("Invalid outbox state");
139
+ this.db
140
+ .prepare("UPDATE outbox SET state=? WHERE account=? AND id=?")
141
+ .run(state, account, id);
142
+ }
143
+ getEvidence(a, p) {
144
+ return this.db
145
+ .prepare("SELECT key,time,id FROM evidence WHERE account=? AND peer=?")
146
+ .get(a, p);
147
+ }
148
+ setEvidence(a, p, r) {
149
+ this.db
150
+ .prepare("INSERT INTO evidence VALUES(?,?,?,?,?) ON CONFLICT(account,peer) DO UPDATE SET key=excluded.key,time=excluded.time,id=excluded.id")
151
+ .run(a, p, r.key, r.time, r.id);
152
+ }
153
+ getDeclaration(a, p) {
154
+ const row = this.db
155
+ .prepare("SELECT time,id,payload FROM peer_declarations WHERE account=? AND peer=?")
156
+ .get(a, p);
157
+ return row?.payload ? row : undefined;
158
+ }
159
+ setDeclaration(a, p, r) {
160
+ this.db
161
+ .prepare("INSERT INTO peer_declarations(account,peer,time,id,payload) VALUES(?,?,?,?,?) ON CONFLICT(account,peer) DO UPDATE SET time=excluded.time,id=excluded.id,payload=excluded.payload")
162
+ .run(a, p, r.time, r.id, r.payload);
163
+ }
164
+ markSplitPeer(a, p) {
165
+ this.db
166
+ .prepare("INSERT INTO peer_declarations(account,peer,split_seen) VALUES(?,?,1) ON CONFLICT(account,peer) DO UPDATE SET split_seen=1")
167
+ .run(a, p);
168
+ }
169
+ isSplitPeer(a, p) {
170
+ return (this.db
171
+ .prepare("SELECT split_seen FROM peer_declarations WHERE account=? AND peer=?")
172
+ .get(a, p)?.split_seen === 1);
173
+ }
174
+ getSession(a, p) {
175
+ return this.db
176
+ .prepare("SELECT payload FROM sessions WHERE account=? AND peer=?")
177
+ .get(a, p)?.payload;
178
+ }
179
+ setSession(a, p, payload) {
180
+ this.db
181
+ .prepare("INSERT INTO sessions VALUES(?,?,?) ON CONFLICT(account,peer) DO UPDATE SET payload=excluded.payload")
182
+ .run(a, p, payload);
183
+ }
184
+ getCheckpoint(a, r) {
185
+ return this.db
186
+ .prepare("SELECT through FROM relay_checkpoints WHERE account=? AND relay=?")
187
+ .get(a, r)?.through;
188
+ }
189
+ setCheckpoint(a, r, t) {
190
+ this.db
191
+ .prepare("INSERT INTO relay_checkpoints VALUES(?,?,?) ON CONFLICT(account,relay) DO UPDATE SET through=excluded.through")
192
+ .run(a, r, t);
193
+ }
194
+ getKeyring(i) {
195
+ return this.db
196
+ .prepare("SELECT payload FROM encryption_keyrings WHERE identity=?")
197
+ .get(i)?.payload;
198
+ }
199
+ setKeyring(i, p) {
200
+ this.db
201
+ .prepare("INSERT INTO encryption_keyrings VALUES(?,?) ON CONFLICT(identity) DO UPDATE SET payload=excluded.payload")
202
+ .run(i, p);
203
+ }
204
+ transaction(run) {
205
+ this.db.exec("BEGIN");
206
+ try {
207
+ run();
208
+ this.db.exec("COMMIT");
209
+ }
210
+ catch (error) {
211
+ try {
212
+ this.db.exec("ROLLBACK");
213
+ }
214
+ catch { }
215
+ throw error;
216
+ }
217
+ }
218
+ close() {
219
+ this.db.close();
220
+ }
221
+ }