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,25 @@
1
+ import type { Event, EventTemplate } from "nostr-tools";
2
+ import { type Identity } from "./protocol.js";
3
+ import type { Store } from "./store.js";
4
+ import type { Transport } from "./relay.js";
5
+ export interface Announcement {
6
+ template: EventTemplate;
7
+ groups: string[][];
8
+ optionalRelays?: string[];
9
+ }
10
+ /** Durable public metadata retry. No command handlers, registry privacy inference or installation lists. */
11
+ export declare class Announcements {
12
+ private identity;
13
+ private store;
14
+ private transport;
15
+ private published?;
16
+ private state;
17
+ private operation?;
18
+ constructor(identity: Identity, store: Store, transport: Transport, published?: ((event: Event) => void) | undefined);
19
+ private save;
20
+ private serialize;
21
+ publish(announcements: Announcement[]): Promise<void>;
22
+ private drain;
23
+ hasPending(): boolean;
24
+ idle(): Promise<void>;
25
+ }
@@ -0,0 +1,142 @@
1
+ import { signChecked } from "./protocol.js";
2
+ import { publicationGroups, relayUnion } from "./relay-roles.js";
3
+ const slot = (event) => JSON.stringify([
4
+ event.kind,
5
+ event.kind === 31992
6
+ ? (event.tags.find((tag) => tag[0] === "d")?.[1] ?? "")
7
+ : "",
8
+ ]);
9
+ const same = (event, template) => event.kind === template.kind &&
10
+ event.content === template.content &&
11
+ JSON.stringify(event.tags) === JSON.stringify(template.tags);
12
+ /** Durable public metadata retry. No command handlers, registry privacy inference or installation lists. */
13
+ export class Announcements {
14
+ identity;
15
+ store;
16
+ transport;
17
+ published;
18
+ state;
19
+ operation;
20
+ constructor(identity, store, transport, published) {
21
+ this.identity = identity;
22
+ this.store = store;
23
+ this.transport = transport;
24
+ this.published = published;
25
+ this.state = store.metadata("announcements") ?? {
26
+ version: 1,
27
+ cache: {},
28
+ pending: [],
29
+ };
30
+ if (this.state.version !== 1 ||
31
+ !this.state.cache ||
32
+ !Array.isArray(this.state.pending)) {
33
+ throw new Error("Unsupported announcement state");
34
+ }
35
+ // This journal owns relay and media server list announcements; command operations have a separate journal.
36
+ const supported = (event) => event &&
37
+ (event.kind === 10002 || event.kind === 10050 || event.kind === 10063);
38
+ const cache = Object.fromEntries(Object.entries(this.state.cache).filter(([, event]) => supported(event)));
39
+ const pending = this.state.pending.filter((item) => supported(item.event));
40
+ if (Object.keys(cache).length !== Object.keys(this.state.cache).length ||
41
+ pending.length !== this.state.pending.length) {
42
+ this.save({ version: 1, cache, pending });
43
+ }
44
+ }
45
+ save(next) {
46
+ this.store.saveMetadata("announcements", next);
47
+ this.state = next;
48
+ }
49
+ serialize(run) {
50
+ const task = (this.operation ?? Promise.resolve())
51
+ .catch(() => { })
52
+ .then(run);
53
+ this.operation = task;
54
+ void task
55
+ .finally(() => {
56
+ if (this.operation === task) {
57
+ this.operation = undefined;
58
+ }
59
+ })
60
+ .catch(() => { });
61
+ return task;
62
+ }
63
+ publish(announcements) {
64
+ return this.serialize(async () => {
65
+ const cache = {
66
+ ...this.state.cache,
67
+ };
68
+ const planned = [];
69
+ for (const { template, groups, optionalRelays = [] } of announcements) {
70
+ const coordinate = slot(template), old = cache[coordinate];
71
+ const event = old && same(old, template)
72
+ ? old
73
+ : await signChecked(this.identity, {
74
+ ...template,
75
+ created_at: Math.max(template.created_at, (old?.created_at ?? -1) + 1),
76
+ });
77
+ cache[coordinate] = event;
78
+ const required = publicationGroups(groups);
79
+ const requiredUrls = new Set(required.flat().map((url) => new URL(url).href));
80
+ planned.push({
81
+ event,
82
+ groups: required,
83
+ optionalRelays: relayUnion(optionalRelays).filter((url) => !requiredUrls.has(new URL(url).href)),
84
+ });
85
+ }
86
+ const canonicalSet = (urls) => urls.map((url) => new URL(url).href).sort();
87
+ const plan = JSON.stringify(planned.map(({ event, groups, optionalRelays }) => [
88
+ event.id,
89
+ groups.map(canonicalSet),
90
+ canonicalSet(optionalRelays),
91
+ ]));
92
+ // Changed settings replace old obligations; unchanged pending work keeps exact progress and IDs.
93
+ if (!this.state.pending.length || this.state.plan !== plan) {
94
+ this.save({
95
+ version: 1,
96
+ cache,
97
+ plan,
98
+ pending: planned.map(({ event, groups }) => ({ event, groups })),
99
+ });
100
+ for (const { event, optionalRelays } of planned) {
101
+ if (optionalRelays.length) {
102
+ // Extra discovery relays are not required acknowledgers and never enter the retry journal.
103
+ void Promise.resolve()
104
+ .then(() => this.transport.publish(optionalRelays, event))
105
+ .catch(() => { });
106
+ }
107
+ }
108
+ }
109
+ await this.drain();
110
+ });
111
+ }
112
+ async drain() {
113
+ const results = await Promise.allSettled(this.state.pending.flatMap(({ event, groups }) => groups.map(async (group) => {
114
+ await this.transport.publish(group, event);
115
+ const pending = this.state.pending.find((item) => item.event.id === event.id);
116
+ if (!pending)
117
+ return; // Another completion has already removed this event.
118
+ const remaining = pending.groups.filter((other) => other !== group);
119
+ this.save({
120
+ ...this.state,
121
+ pending: this.state.pending.flatMap((item) => item.event.id !== event.id
122
+ ? [item]
123
+ : remaining.length
124
+ ? [{ event, groups: remaining }]
125
+ : []),
126
+ });
127
+ if (!remaining.length)
128
+ this.published?.(event);
129
+ })));
130
+ const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
131
+ if (failures.length === 1)
132
+ throw failures[0];
133
+ if (failures.length > 1)
134
+ throw new AggregateError(failures, "Account metadata publication failed");
135
+ }
136
+ hasPending() {
137
+ return this.state.pending.length > 0;
138
+ }
139
+ async idle() {
140
+ await this.operation?.catch(() => { });
141
+ }
142
+ }
@@ -0,0 +1,43 @@
1
+ import { type Rumor } from "./protocol.js";
2
+ export interface FileAttachment {
3
+ readonly url: string;
4
+ readonly mimeType: string;
5
+ readonly name?: string;
6
+ readonly encryptedSha256: string;
7
+ readonly plaintextSha256?: string;
8
+ readonly encryptedSize?: number;
9
+ readonly plaintextSize?: number;
10
+ download(): Promise<FileDownloadResult>;
11
+ }
12
+ export type FileDownloadErrorCode = "DOWNLOAD_FAILED" | "INTEGRITY_CHECK_FAILED" | "DECRYPTION_FAILED" | "STORAGE_FAILED" | "INPUT_NOT_ADMITTED";
13
+ export interface FileDownloadError {
14
+ readonly code: FileDownloadErrorCode;
15
+ readonly message: string;
16
+ readonly status?: number;
17
+ }
18
+ export type FileDownloadResult = {
19
+ file: File;
20
+ error: null;
21
+ } | {
22
+ file: null;
23
+ error: FileDownloadError;
24
+ };
25
+ type AttachmentMetadata = Omit<FileAttachment, "download">;
26
+ interface AttachmentDescriptor {
27
+ metadata: AttachmentMetadata;
28
+ key: string;
29
+ nonce: string;
30
+ fallbackUrls: string[];
31
+ }
32
+ export declare function parseAttachment(rumor: Rumor): AttachmentDescriptor | undefined;
33
+ export declare class AttachmentCache {
34
+ private readonly directory;
35
+ private readonly origins;
36
+ private readonly active;
37
+ constructor(directory: string, origins: ReadonlySet<string>);
38
+ attachment(rumor: Rumor, admitted: () => boolean): FileAttachment | undefined;
39
+ private download;
40
+ private fetchAttachment;
41
+ private fetchSource;
42
+ }
43
+ export {};
@@ -0,0 +1,340 @@
1
+ import { createDecipheriv, createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { mkdir, open, rename, rm } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { MIMEType } from "node:util";
6
+ import { hexKey } from "./protocol.js";
7
+ const downloadTimeoutMs = 60_000;
8
+ const authTagBytes = 16;
9
+ function downloadUrl(value) {
10
+ if (!value || value.length > 2048 || /\s/.test(value))
11
+ return;
12
+ try {
13
+ const url = new URL(value);
14
+ if ((url.protocol === "https:" ||
15
+ (url.protocol === "http:" &&
16
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) &&
17
+ !url.username &&
18
+ !url.password &&
19
+ !url.hash) {
20
+ return url;
21
+ }
22
+ }
23
+ catch {
24
+ // Invalid URL.
25
+ }
26
+ }
27
+ function sizeTag(value) {
28
+ if (!/^\d+$/.test(value))
29
+ return;
30
+ const size = Number(value);
31
+ return Number.isSafeInteger(size) ? size : undefined;
32
+ }
33
+ function fileMimeType(value) {
34
+ if (!value || value.length > 1024 || !/^[\t\x20-\x7e]+$/.test(value))
35
+ return;
36
+ try {
37
+ return new MIMEType(value).toString();
38
+ }
39
+ catch {
40
+ return;
41
+ }
42
+ }
43
+ export function parseAttachment(rumor) {
44
+ if (rumor.kind !== 15 || !hexKey(rumor.id) || !downloadUrl(rumor.content))
45
+ return;
46
+ const single = new Map();
47
+ const fields = new Set([
48
+ "file-type",
49
+ "name",
50
+ "x",
51
+ "ox",
52
+ "size",
53
+ "plain-size",
54
+ "encryption-algorithm",
55
+ "decryption-key",
56
+ "decryption-nonce",
57
+ ]);
58
+ const fallbackUrls = [];
59
+ for (const [tag, value] of rumor.tags) {
60
+ if (tag === "fallback" && typeof value === "string" && downloadUrl(value)) {
61
+ if (fallbackUrls.length < 5 && !fallbackUrls.includes(value))
62
+ fallbackUrls.push(value);
63
+ }
64
+ if (!fields.has(tag))
65
+ continue;
66
+ if (single.has(tag) || typeof value !== "string" || !value)
67
+ return;
68
+ single.set(tag, value);
69
+ }
70
+ const mimeType = fileMimeType(single.get("file-type"));
71
+ const encryptedSha256 = single.get("x")?.toLowerCase();
72
+ const plaintextSha256 = single.get("ox")?.toLowerCase();
73
+ const key = single.get("decryption-key");
74
+ const nonce = single.get("decryption-nonce");
75
+ if (!mimeType ||
76
+ !hexKey(encryptedSha256) ||
77
+ (plaintextSha256 !== undefined && !hexKey(plaintextSha256)) ||
78
+ single.get("encryption-algorithm") !== "aes-gcm" ||
79
+ !key ||
80
+ !/^[0-9a-f]{64}$/i.test(key) ||
81
+ !nonce ||
82
+ !/^[0-9a-f]{24}$/i.test(nonce))
83
+ return;
84
+ const encryptedSize = sizeTag(single.get("size") ?? "");
85
+ const plaintextSize = sizeTag(single.get("plain-size") ?? "");
86
+ const name = single.get("name");
87
+ const safeName = name &&
88
+ name !== "." &&
89
+ name !== ".." &&
90
+ Buffer.byteLength(name) <= 255 &&
91
+ !/[\\/]/.test(name) &&
92
+ [...name].every((character) => {
93
+ const code = character.charCodeAt(0);
94
+ return code >= 32 && code !== 127;
95
+ })
96
+ ? name
97
+ : undefined;
98
+ return {
99
+ key,
100
+ nonce,
101
+ fallbackUrls,
102
+ metadata: {
103
+ url: rumor.content,
104
+ mimeType,
105
+ encryptedSha256,
106
+ ...(plaintextSha256 === undefined ? {} : { plaintextSha256 }),
107
+ ...(encryptedSize === undefined ? {} : { encryptedSize }),
108
+ ...(plaintextSize === undefined ? {} : { plaintextSize }),
109
+ ...(safeName === undefined ? {} : { name: safeName }),
110
+ },
111
+ };
112
+ }
113
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
114
+ const failure = (code, message, status) => ({
115
+ file: null,
116
+ error: { code, message, ...(status === undefined ? {} : { status }) },
117
+ });
118
+ class DownloadFailure extends Error {
119
+ result;
120
+ constructor(result) {
121
+ super(result.error.message);
122
+ this.result = result;
123
+ }
124
+ }
125
+ async function readRegularFile(path, limit = Infinity) {
126
+ let file;
127
+ try {
128
+ file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
129
+ }
130
+ catch (error) {
131
+ if (error.code === "ENOENT")
132
+ return;
133
+ throw error;
134
+ }
135
+ try {
136
+ const info = await file.stat();
137
+ if (!info.isFile() || info.size > limit)
138
+ return;
139
+ const bytes = Buffer.alloc(info.size);
140
+ let offset = 0;
141
+ while (offset < bytes.length) {
142
+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
143
+ if (bytesRead === 0)
144
+ return;
145
+ offset += bytesRead;
146
+ }
147
+ const end = await file.read(Buffer.alloc(1), 0, 1, offset);
148
+ if (end.bytesRead === 0)
149
+ return bytes;
150
+ }
151
+ finally {
152
+ await file.close();
153
+ }
154
+ }
155
+ async function writeAtomically(path, value) {
156
+ const temporary = `${path}.${randomUUID()}.tmp`;
157
+ const file = await open(temporary, "wx", 0o600);
158
+ try {
159
+ try {
160
+ await file.writeFile(value);
161
+ }
162
+ finally {
163
+ await file.close();
164
+ }
165
+ await rename(temporary, path);
166
+ }
167
+ finally {
168
+ await rm(temporary, { force: true });
169
+ }
170
+ }
171
+ export class AttachmentCache {
172
+ directory;
173
+ origins;
174
+ active = new Map();
175
+ constructor(directory, origins) {
176
+ this.directory = directory;
177
+ this.origins = origins;
178
+ }
179
+ attachment(rumor, admitted) {
180
+ const descriptor = parseAttachment(rumor);
181
+ if (!descriptor)
182
+ return;
183
+ const { id, pubkey } = rumor;
184
+ const { metadata, key, nonce } = descriptor;
185
+ // This binds cache reuse to the authenticated author and the verified encryption metadata.
186
+ const binding = sha256(Buffer.from(JSON.stringify([
187
+ pubkey,
188
+ metadata.encryptedSha256,
189
+ key.toLowerCase(),
190
+ nonce.toLowerCase(),
191
+ metadata.plaintextSha256,
192
+ metadata.encryptedSize,
193
+ metadata.plaintextSize,
194
+ ])));
195
+ const attachment = {
196
+ ...metadata,
197
+ download: async () => {
198
+ try {
199
+ if (!admitted())
200
+ return failure("INPUT_NOT_ADMITTED", "The attachment is not available in private history");
201
+ }
202
+ catch {
203
+ return failure("STORAGE_FAILED", "Unable to check private message history");
204
+ }
205
+ const active = this.active.get(id);
206
+ if (active)
207
+ return active;
208
+ const task = this.download(binding, descriptor).finally(() => {
209
+ this.active.delete(id);
210
+ });
211
+ this.active.set(id, task);
212
+ return task;
213
+ },
214
+ };
215
+ // Keep metadata cloneable and the download capability on the original object.
216
+ Object.defineProperty(attachment, "download", { enumerable: false });
217
+ return Object.freeze(attachment);
218
+ }
219
+ async download(binding, descriptor) {
220
+ const { metadata } = descriptor;
221
+ const receipts = join(this.directory, "verified");
222
+ const receipt = join(receipts, binding);
223
+ const asFile = (bytes, hash) => ({
224
+ file: new File([bytes], metadata.name ?? hash, {
225
+ type: metadata.mimeType,
226
+ }),
227
+ error: null,
228
+ });
229
+ try {
230
+ const stored = await readRegularFile(receipt, 64);
231
+ const hash = stored?.toString("ascii");
232
+ // A claimed ox is a lookup hint. The receipt binds the attachment to verified bytes.
233
+ if (hexKey(hash) &&
234
+ (!metadata.plaintextSha256 || hash === metadata.plaintextSha256)) {
235
+ const bytes = await readRegularFile(join(this.directory, hash));
236
+ if (bytes && sha256(bytes) === hash)
237
+ return asFile(bytes, hash);
238
+ }
239
+ }
240
+ catch {
241
+ return failure("STORAGE_FAILED", "Unable to read the attachment cache");
242
+ }
243
+ let encrypted;
244
+ try {
245
+ encrypted = await this.fetchAttachment(descriptor);
246
+ }
247
+ catch (error) {
248
+ if (error instanceof DownloadFailure)
249
+ return error.result;
250
+ return failure("DOWNLOAD_FAILED", "Unable to download the attachment");
251
+ }
252
+ let bytes;
253
+ try {
254
+ const decipher = createDecipheriv("aes-256-gcm", Buffer.from(descriptor.key, "hex"), Buffer.from(descriptor.nonce, "hex"));
255
+ decipher.setAuthTag(encrypted.subarray(-authTagBytes));
256
+ bytes = Buffer.concat([
257
+ decipher.update(encrypted.subarray(0, -authTagBytes)),
258
+ decipher.final(),
259
+ ]);
260
+ }
261
+ catch {
262
+ return failure("DECRYPTION_FAILED", "Unable to authenticate or decrypt the attachment");
263
+ }
264
+ const hash = sha256(bytes);
265
+ if ((metadata.plaintextSha256 !== undefined &&
266
+ hash !== metadata.plaintextSha256) ||
267
+ (metadata.plaintextSize !== undefined &&
268
+ bytes.length !== metadata.plaintextSize))
269
+ return failure("INTEGRITY_CHECK_FAILED", "Decrypted attachment failed verification");
270
+ try {
271
+ await mkdir(receipts, { recursive: true, mode: 0o700 });
272
+ await writeAtomically(join(this.directory, hash), bytes);
273
+ await writeAtomically(receipt, hash);
274
+ return asFile(bytes, hash);
275
+ }
276
+ catch {
277
+ return failure("STORAGE_FAILED", "Unable to save the verified attachment");
278
+ }
279
+ }
280
+ async fetchAttachment({ metadata, fallbackUrls, }) {
281
+ const urls = [
282
+ ...new Set([metadata.url, ...fallbackUrls].flatMap((value) => {
283
+ const url = downloadUrl(value);
284
+ return url && this.origins.has(url.origin) ? [url.href] : [];
285
+ })),
286
+ ];
287
+ const deadline = performance.now() + downloadTimeoutMs;
288
+ const totalSignal = AbortSignal.timeout(downloadTimeoutMs);
289
+ let lastError;
290
+ let integrityError;
291
+ for (const [index, url] of urls.entries()) {
292
+ const remainingMs = Math.floor(deadline - performance.now());
293
+ if (totalSignal.aborted || remainingMs <= 0)
294
+ break;
295
+ const remainingSources = urls.length - index;
296
+ const signal = remainingSources === 1
297
+ ? totalSignal
298
+ : AbortSignal.any([
299
+ totalSignal,
300
+ AbortSignal.timeout(Math.floor(remainingMs / remainingSources)),
301
+ ]);
302
+ try {
303
+ const encrypted = await this.fetchSource(url, signal);
304
+ if (encrypted.length >= authTagBytes &&
305
+ (metadata.encryptedSize === undefined ||
306
+ encrypted.length === metadata.encryptedSize) &&
307
+ sha256(encrypted) === metadata.encryptedSha256)
308
+ return encrypted;
309
+ integrityError = new DownloadFailure(failure("INTEGRITY_CHECK_FAILED", "Encrypted attachment failed verification"));
310
+ }
311
+ catch (error) {
312
+ if (error instanceof DownloadFailure)
313
+ lastError = error;
314
+ }
315
+ }
316
+ throw (integrityError ??
317
+ lastError ??
318
+ new DownloadFailure(failure("DOWNLOAD_FAILED", "Unable to download the attachment")));
319
+ }
320
+ async fetchSource(value, signal) {
321
+ let url = downloadUrl(value);
322
+ for (let redirects = 0; redirects <= 5; redirects++) {
323
+ if (!url || !this.origins.has(url.origin))
324
+ break;
325
+ const response = await fetch(url, { redirect: "manual", signal });
326
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
327
+ const location = response.headers.get("location");
328
+ await response.body?.cancel();
329
+ url = location ? downloadUrl(new URL(location, url).href) : undefined;
330
+ continue;
331
+ }
332
+ if (response.status !== 200 || !response.body) {
333
+ await response.body?.cancel();
334
+ throw new DownloadFailure(failure("DOWNLOAD_FAILED", "Attachment host returned an unsuccessful response", response.status));
335
+ }
336
+ return Buffer.from(await response.arrayBuffer());
337
+ }
338
+ throw new DownloadFailure(failure("DOWNLOAD_FAILED", "Attachment source or redirect is not allowed"));
339
+ }
340
+ }
@@ -0,0 +1,30 @@
1
+ import { type Identity } from "./protocol.js";
2
+ export declare function normalizeBlossomServers(values: readonly string[] | undefined): string[];
3
+ /** Additional trusted HTTPS origins that may host a server's blob descriptors. */
4
+ export declare function normalizeBlossomDownloadOrigins(values: readonly string[] | undefined): ReadonlySet<string>;
5
+ export interface UploadFileOptions {
6
+ /** MIME type of exactly the bytes to upload, default application/octet-stream. */
7
+ mimeType?: string;
8
+ }
9
+ export interface UploadFileResult {
10
+ url: string;
11
+ sha256: string;
12
+ size: number;
13
+ mimeType: string;
14
+ }
15
+ export interface SendFileOptions {
16
+ /** MIME type inside the encrypted message, default application/octet-stream. */
17
+ mimeType?: string;
18
+ /** Optional filename inside the encrypted message. */
19
+ name?: string;
20
+ /** ID of the decrypted parent message. */
21
+ replyTo?: string;
22
+ }
23
+ export type ReplyFileOptions = Omit<SendFileOptions, "replyTo">;
24
+ export declare function snapshotFile(data: Uint8Array): Buffer<ArrayBuffer>;
25
+ export declare function encryptAttachment(data: Uint8Array, { mimeType, name }: SendFileOptions): {
26
+ bytes: Buffer<ArrayBuffer>;
27
+ tags: string[][];
28
+ };
29
+ /** Use only configured servers, in priority order. Auth is not published to relays. */
30
+ export declare function uploadFile(identity: Identity, servers: readonly string[], downloadOrigins: ReadonlySet<string>, data: Uint8Array, { mimeType }?: UploadFileOptions): Promise<UploadFileResult>;