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
package/dist/blossom.js CHANGED
@@ -1,32 +1,38 @@
1
- import { createCipheriv, createHash, randomBytes } from 'node:crypto';
2
- import { DEFAULT_BLOSSOM_SERVERS } from './defaults.js';
3
- import { signChecked } from './protocol.js';
1
+ import { createCipheriv, createHash, randomBytes } from "node:crypto";
2
+ import { DEFAULT_BLOSSOM_SERVERS } from "./defaults.js";
3
+ import { signChecked } from "./protocol.js";
4
4
  const maxFileBytes = 64 * 1024 * 1024;
5
5
  const maxDescriptorBytes = 16 * 1024;
6
6
  const uploadTimeoutMs = 60_000;
7
7
  const mirrorTimeoutMs = 10_000;
8
- const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
9
- const loopbackHost = (host) => ['localhost', '127.0.0.1', '[::1]'].includes(host);
8
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
9
+ const loopbackHost = (host) => ["localhost", "127.0.0.1", "[::1]"].includes(host);
10
10
  function httpUrl(value) {
11
- if (typeof value !== 'string' || value.length > 2048 || /\s/.test(value))
11
+ if (typeof value !== "string" || value.length > 2048 || /\s/.test(value))
12
12
  return;
13
13
  try {
14
14
  const url = new URL(value);
15
- if ((url.protocol === 'https:' || (loopbackHost(url.hostname) && url.protocol === 'http:')) &&
16
- !url.username && !url.password && !url.search && !url.hash)
15
+ if ((url.protocol === "https:" ||
16
+ (loopbackHost(url.hostname) && url.protocol === "http:")) &&
17
+ !url.username &&
18
+ !url.password &&
19
+ !url.search &&
20
+ !url.hash)
17
21
  return url;
18
22
  }
19
- catch { /* Invalid URL */ }
23
+ catch {
24
+ /* Invalid URL */
25
+ }
20
26
  }
21
27
  export function normalizeBlossomServers(values) {
22
28
  values ??= DEFAULT_BLOSSOM_SERVERS;
23
29
  if (!Array.isArray(values))
24
- throw new TypeError('blossomServers must be an array of HTTP(S) URLs');
25
- const servers = Array.from(values, value => {
30
+ throw new TypeError("blossomServers must be an array of HTTP(S) URLs");
31
+ const servers = Array.from(values, (value) => {
26
32
  const url = httpUrl(value);
27
33
  if (!url)
28
- throw new TypeError('Blossom URLs must use HTTPS (HTTP is allowed on loopback), without credentials, query or fragment');
29
- return url.pathname === '/' ? url.href : url.href.replace(/\/+$/, '');
34
+ throw new TypeError("Blossom URLs must use HTTPS (HTTP is allowed on loopback), without credentials, query or fragment");
35
+ return url.pathname === "/" ? url.href : url.href.replace(/\/+$/, "");
30
36
  });
31
37
  return [...new Set(servers)];
32
38
  }
@@ -35,52 +41,70 @@ export function normalizeBlossomDownloadOrigins(values) {
35
41
  if (values === undefined)
36
42
  return new Set();
37
43
  if (!Array.isArray(values))
38
- throw new TypeError('blossomDownloadOrigins must be an array of HTTPS origins');
39
- return new Set(Array.from(values, value => {
44
+ throw new TypeError("blossomDownloadOrigins must be an array of HTTPS origins");
45
+ return new Set(Array.from(values, (value) => {
40
46
  const url = httpUrl(value);
41
- if (!url || url.protocol !== 'https:' || url.pathname !== '/' || loopbackHost(url.hostname)) {
42
- throw new TypeError('blossomDownloadOrigins must contain HTTPS origins, without paths, credentials, queries or fragments');
47
+ if (url?.protocol !== "https:" ||
48
+ url.pathname !== "/" ||
49
+ loopbackHost(url.hostname)) {
50
+ throw new TypeError("blossomDownloadOrigins must contain HTTPS origins, without paths, credentials, queries or fragments");
43
51
  }
44
52
  return url.origin;
45
53
  }));
46
54
  }
47
55
  function validateSize(data, overhead = 0) {
48
- if (!(data instanceof Uint8Array) || data.byteLength === 0 || data.byteLength + overhead > maxFileBytes) {
49
- throw new TypeError('File must be a nonempty Uint8Array with an upload size of at most 64 MiB');
56
+ if (!(data instanceof Uint8Array) ||
57
+ data.byteLength === 0 ||
58
+ data.byteLength + overhead > maxFileBytes) {
59
+ throw new TypeError("File must be a nonempty Uint8Array with an upload size of at most 64 MiB");
50
60
  }
51
61
  }
52
62
  function validateMimeType(mimeType) {
53
- if (typeof mimeType !== 'string' || mimeType.length > 127 || !/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/.test(mimeType)) {
54
- throw new TypeError('Invalid file MIME type');
63
+ if (typeof mimeType !== "string" ||
64
+ mimeType.length > 127 ||
65
+ !/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/.test(mimeType)) {
66
+ throw new TypeError("Invalid file MIME type");
55
67
  }
56
68
  }
57
69
  export function snapshotFile(data) {
58
70
  validateSize(data);
59
71
  return Buffer.from(data);
60
72
  }
61
- export function encryptAttachment(data, { mimeType = 'application/octet-stream', name }) {
73
+ export function encryptAttachment(data, { mimeType = "application/octet-stream", name }) {
62
74
  validateSize(data, 16);
63
75
  validateMimeType(mimeType);
64
- if (name !== undefined && (typeof name !== 'string' || !name.length || Buffer.byteLength(name) > 255 || /[\x00-\x1f\x7f]/.test(name))) {
65
- throw new TypeError('Attachment name must be nonempty, without control characters, and at most 255 UTF-8 bytes');
76
+ if (name !== undefined &&
77
+ (typeof name !== "string" ||
78
+ !name.length ||
79
+ Buffer.byteLength(name) > 255 ||
80
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Reject ASCII control characters in attachment names.
81
+ /[\x00-\x1f\x7f]/.test(name))) {
82
+ throw new TypeError("Attachment name must be nonempty, without control characters, and at most 255 UTF-8 bytes");
66
83
  }
67
84
  const key = randomBytes(32), nonce = randomBytes(12);
68
- const cipher = createCipheriv('aes-256-gcm', key, nonce);
69
- const bytes = Buffer.concat([cipher.update(data), cipher.final(), cipher.getAuthTag()]);
85
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
86
+ const bytes = Buffer.concat([
87
+ cipher.update(data),
88
+ cipher.final(),
89
+ cipher.getAuthTag(),
90
+ ]);
70
91
  return {
71
92
  bytes,
72
93
  tags: [
73
- ['file-type', mimeType], ['encryption-algorithm', 'aes-gcm'],
74
- ['decryption-key', key.toString('hex')], ['decryption-nonce', nonce.toString('hex')],
75
- ['ox', hash(data)], ['plain-size', String(data.byteLength)],
76
- ...(name === undefined ? [] : [['name', name]]),
94
+ ["file-type", mimeType],
95
+ ["encryption-algorithm", "aes-gcm"],
96
+ ["decryption-key", key.toString("hex")],
97
+ ["decryption-nonce", nonce.toString("hex")],
98
+ ["ox", hash(data)],
99
+ ["plain-size", String(data.byteLength)],
100
+ ...(name === undefined ? [] : [["name", name]]),
77
101
  ],
78
102
  };
79
103
  }
80
104
  async function descriptor(response, sha256, size, server, downloadOrigins) {
81
105
  const reader = response.body?.getReader();
82
106
  if (!reader)
83
- throw new Error('Missing Blossom descriptor');
107
+ throw new Error("Missing Blossom descriptor");
84
108
  const chunks = [];
85
109
  let length = 0;
86
110
  try {
@@ -90,54 +114,78 @@ async function descriptor(response, sha256, size, server, downloadOrigins) {
90
114
  break;
91
115
  length += value.length;
92
116
  if (length > maxDescriptorBytes)
93
- throw new Error('Blossom descriptor too large');
117
+ throw new Error("Blossom descriptor too large");
94
118
  chunks.push(value);
95
119
  }
96
120
  }
97
121
  finally {
98
122
  void reader.cancel().catch(() => { });
99
123
  }
100
- const input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
101
- const url = typeof input?.url === 'string' ? httpUrl(input.url) : undefined;
124
+ const input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
125
+ const url = typeof input?.url === "string" ? httpUrl(input.url) : undefined;
102
126
  const serverOrigin = new URL(server).origin;
103
- const trustedOrigin = url && (url.origin === serverOrigin ||
104
- (!loopbackHost(url.hostname) && downloadOrigins.has(url.origin)));
105
- const filenameHash = url?.pathname.split('/').at(-1)?.match(/^([0-9a-f]{64})(?:\.[a-z0-9_-]+)?$/i)?.[1].toLowerCase();
106
- if (!url || !trustedOrigin || filenameHash !== sha256 || input?.sha256 !== sha256 || input.size !== size) {
107
- throw new Error('Invalid Blossom upload descriptor');
127
+ const trustedOrigin = url &&
128
+ (url.origin === serverOrigin ||
129
+ (!loopbackHost(url.hostname) && downloadOrigins.has(url.origin)));
130
+ const filenameHash = url?.pathname
131
+ .split("/")
132
+ .at(-1)
133
+ ?.match(/^([0-9a-f]{64})(?:\.[a-z0-9_-]+)?$/i)?.[1]
134
+ .toLowerCase();
135
+ if (!url ||
136
+ !trustedOrigin ||
137
+ filenameHash !== sha256 ||
138
+ input?.sha256 !== sha256 ||
139
+ input.size !== size) {
140
+ throw new Error("Invalid Blossom upload descriptor");
108
141
  }
109
142
  return url.href;
110
143
  }
111
144
  async function uploadAuthorization(identity, servers, sha256, size) {
112
- const hosts = [...new Set(servers.map(server => new URL(server).hostname))];
145
+ const hosts = [...new Set(servers.map((server) => new URL(server).hostname))];
113
146
  const now = Math.floor(Date.now() / 1000), expiration = now + 300;
114
147
  const event = await signChecked(identity, {
115
- kind: 24242, created_at: now, content: 'Upload file to Blossom',
116
- tags: [['t', 'upload'], ['x', sha256], ['size', String(size)],
117
- ...hosts.map(host => ['server', host]), ['expiration', String(expiration)]],
148
+ kind: 24242,
149
+ created_at: now,
150
+ content: "Upload file to Blossom",
151
+ tags: [
152
+ ["t", "upload"],
153
+ ["x", sha256],
154
+ ["size", String(size)],
155
+ ...hosts.map((host) => ["server", host]),
156
+ ["expiration", String(expiration)],
157
+ ],
118
158
  });
119
159
  const token = Buffer.from(JSON.stringify(event));
120
- return { base64url: token.toString('base64url'), base64: token.toString('base64'), expiresAt: expiration * 1000 };
160
+ return {
161
+ base64url: token.toString("base64url"),
162
+ base64: token.toString("base64"),
163
+ expiresAt: expiration * 1000,
164
+ };
121
165
  }
122
166
  async function putBlossom(authorization, server, operation, body, headers, sha256, size, downloadOrigins) {
123
167
  const remaining = authorization.expiresAt - Date.now();
124
168
  if (remaining <= 0)
125
- throw new Error('Blossom authorization expired while waiting for the signer');
126
- const signal = AbortSignal.timeout(Math.min(remaining, operation === 'mirror' ? mirrorTimeoutMs : uploadTimeoutMs));
127
- const put = (encoding) => fetch(server.replace(/\/+$/, '') + '/' + operation, {
128
- method: 'PUT', redirect: 'error', signal, body,
169
+ throw new Error("Blossom authorization expired while waiting for the signer");
170
+ const signal = AbortSignal.timeout(Math.min(remaining, operation === "mirror" ? mirrorTimeoutMs : uploadTimeoutMs));
171
+ const put = (encoding) => fetch(`${server.replace(/\/+$/, "")}/${operation}`, {
172
+ method: "PUT",
173
+ redirect: "error",
174
+ signal,
175
+ body,
129
176
  headers: {
130
177
  ...headers,
131
- authorization: 'Nostr ' + authorization[encoding],
132
- 'content-length': String(body.length),
133
- 'x-sha-256': sha256,
178
+ authorization: `Nostr ${authorization[encoding]}`,
179
+ "content-length": String(body.length),
180
+ "x-sha-256": sha256,
134
181
  },
135
182
  });
136
183
  try {
137
- let response = await put('base64url');
138
- if ((response.status === 400 || response.status === 401) && authorization.base64url !== authorization.base64) {
184
+ let response = await put("base64url");
185
+ if ((response.status === 400 || response.status === 401) &&
186
+ authorization.base64url !== authorization.base64) {
139
187
  void response.body?.cancel().catch(() => { });
140
- response = await put('base64');
188
+ response = await put("base64");
141
189
  }
142
190
  if (!response.ok) {
143
191
  void response.body?.cancel().catch(() => { });
@@ -145,35 +193,41 @@ async function putBlossom(authorization, server, operation, body, headers, sha25
145
193
  }
146
194
  return await descriptor(response, sha256, size, server, downloadOrigins);
147
195
  }
148
- catch { /* Do not copy server responses or tokens into errors. */ }
196
+ catch {
197
+ /* Do not copy server responses or tokens into errors. */
198
+ }
149
199
  }
150
200
  /** Use only configured servers, in priority order. Auth is not published to relays. */
151
- export async function uploadFile(identity, servers, downloadOrigins, data, { mimeType = 'application/octet-stream' } = {}) {
201
+ export async function uploadFile(identity, servers, downloadOrigins, data, { mimeType = "application/octet-stream" } = {}) {
152
202
  if (!servers.length)
153
- throw new Error('Configure blossomServers before uploading files');
203
+ throw new Error("Configure blossomServers before uploading files");
154
204
  validateMimeType(mimeType);
155
205
  const bytes = snapshotFile(data), size = bytes.length, sha256 = hash(bytes);
156
206
  let authorization;
157
207
  for (const [index, server] of servers.entries()) {
158
- if (!authorization || authorization.expiresAt - Date.now() <= uploadTimeoutMs + mirrorTimeoutMs) {
208
+ if (!authorization ||
209
+ authorization.expiresAt - Date.now() <= uploadTimeoutMs + mirrorTimeoutMs) {
159
210
  authorization = await uploadAuthorization(identity, servers.slice(index), sha256, size);
160
211
  }
161
212
  const signed = authorization;
162
- const url = await putBlossom(signed, server, 'upload', bytes, { 'content-type': mimeType }, sha256, size, downloadOrigins);
213
+ const url = await putBlossom(signed, server, "upload", bytes, { "content-type": mimeType }, sha256, size, downloadOrigins);
163
214
  if (!url)
164
215
  continue;
165
216
  // A descriptor may point at a CDN. Do not instruct another server to fetch an
166
217
  // arbitrary origin chosen by the descriptor; the configured primary serves
167
218
  // the same blob via the standard raw-hash endpoint.
168
- const source = server.replace(/\/+$/, '') + '/' + sha256;
219
+ const source = `${server.replace(/\/+$/, "")}/${sha256}`;
169
220
  const body = Buffer.from(JSON.stringify({ url: source }));
170
- const targets = servers.slice(index + 1).filter(target => !loopbackHost(new URL(source).hostname) || loopbackHost(new URL(target).hostname));
171
- await Promise.allSettled(targets.map(target => putBlossom(signed, target, 'mirror', body, {
172
- 'content-type': 'application/json',
173
- 'x-content-type': mimeType,
174
- 'x-content-length': String(size),
221
+ const targets = servers
222
+ .slice(index + 1)
223
+ .filter((target) => !loopbackHost(new URL(source).hostname) ||
224
+ loopbackHost(new URL(target).hostname));
225
+ await Promise.allSettled(targets.map((target) => putBlossom(signed, target, "mirror", body, {
226
+ "content-type": "application/json",
227
+ "x-content-type": mimeType,
228
+ "x-content-length": String(size),
175
229
  }, sha256, size, downloadOrigins)));
176
230
  return { url, sha256, size, mimeType };
177
231
  }
178
- throw new Error('No configured Blossom server accepted the file');
232
+ throw new Error("No configured Blossom server accepted the file");
179
233
  }
@@ -1,27 +1,18 @@
1
- import type { ReplyFileOptions } from './blossom.js';
2
- import { type Input, type ThreadOptions, type ThreadResult } from './public-thread.js';
3
- import { type Session, type SessionStore } from './session.js';
4
- import { Client, type SendOptions } from './client.js';
5
- import type { Message } from './store.js';
6
- import { type BotCommandDefinition, type CommandArgs, type CommandDefinition, type CommandInvocation } from './nipcd.js';
1
+ import type { ReplyFileOptions } from "./blossom.js";
2
+ import { type Input, type ThreadOptions, type ThreadResult } from "./public-thread.js";
3
+ import { type Session, type SessionStore } from "./session.js";
4
+ import type { Client, SendOptions } from "./client.js";
5
+ import { type BotCommandDefinition, type CommandArgs, type CommandDefinition, type CommandInvocation } from "./nipcd.js";
7
6
  export interface Context<S = Record<string, unknown>> {
8
7
  input: Input;
9
8
  thread(options?: ThreadOptions): Promise<ThreadResult>;
10
- /** DM-only compatibility view; throws for public input. */
11
- message: Message;
12
9
  sender: string;
13
10
  conversation: string;
14
- reply(text: string, options?: SendOptions): ReturnType<Client['send']> | ReturnType<Client['replyPublic']>;
11
+ reply(text: string, options?: SendOptions): ReturnType<Client["send"]> | ReturnType<Client["replyPublic"]>;
15
12
  /** Attach a file using the visibility of the triggering event. */
16
- replyFile(data: Uint8Array, options?: ReplyFileOptions): ReturnType<Client['replyFile']>;
17
- /** React to the current message or another message in this conversation. */
18
- react(reaction?: string, messageId?: string): ReturnType<Client['react']>;
19
- /** Look up a locally stored message in this conversation. */
20
- getMessage(id: string): Message | undefined;
21
- history(options?: {
22
- limit?: number;
23
- cursor?: string;
24
- }): ReturnType<Client['history']>;
13
+ replyFile(data: Uint8Array, options?: ReplyFileOptions): ReturnType<Client["replyFile"]>;
14
+ /** React to the current input, keeping its visibility. */
15
+ react(reaction?: string): ReturnType<Client["react"]>;
25
16
  session: Session<S>;
26
17
  }
27
18
  export interface CommandContext<A, S = Record<string, unknown>> extends Context<S> {