chirli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/ARCHITECTURE.md +18 -20
  2. package/CONTRIBUTING.md +7 -3
  3. package/README.md +63 -55
  4. package/SECURITY.md +11 -11
  5. package/dist/allowlist.d.ts +3 -0
  6. package/dist/allowlist.js +9 -0
  7. package/dist/announcements.d.ts +4 -4
  8. package/dist/announcements.js +66 -34
  9. package/dist/attachments.d.ts +43 -0
  10. package/dist/attachments.js +340 -0
  11. package/dist/blossom.d.ts +2 -2
  12. package/dist/blossom.js +120 -66
  13. package/dist/bot-handlers.d.ts +9 -18
  14. package/dist/bot-handlers.js +125 -66
  15. package/dist/bot.d.ts +17 -20
  16. package/dist/bot.js +150 -55
  17. package/dist/client.d.ts +43 -39
  18. package/dist/client.js +476 -290
  19. package/dist/command-discovery.d.ts +2 -2
  20. package/dist/command-discovery.js +16 -7
  21. package/dist/command-schema.d.ts +2 -2
  22. package/dist/command-schema.js +62 -31
  23. package/dist/commands.d.ts +7 -6
  24. package/dist/commands.js +116 -51
  25. package/dist/defaults.js +13 -6
  26. package/dist/errors.d.ts +12 -12
  27. package/dist/errors.js +55 -18
  28. package/dist/inbox.d.ts +9 -7
  29. package/dist/inbox.js +107 -62
  30. package/dist/index.d.ts +25 -24
  31. package/dist/index.js +11 -11
  32. package/dist/key-sync.d.ts +4 -4
  33. package/dist/key-sync.js +88 -50
  34. package/dist/keys.d.ts +7 -6
  35. package/dist/keys.js +187 -93
  36. package/dist/message-storage-sqlite.d.ts +1 -1
  37. package/dist/message-storage-sqlite.js +32 -27
  38. package/dist/message-storage.d.ts +2 -2
  39. package/dist/messaging-metadata.d.ts +4 -4
  40. package/dist/messaging-metadata.js +73 -46
  41. package/dist/metadata.d.ts +3 -3
  42. package/dist/metadata.js +29 -15
  43. package/dist/modes.d.ts +7 -7
  44. package/dist/modes.js +53 -24
  45. package/dist/nip4e-compat.d.ts +2 -2
  46. package/dist/nip4e-compat.js +2 -2
  47. package/dist/nipcd.d.ts +14 -14
  48. package/dist/nipcd.js +225 -126
  49. package/dist/protocol.d.ts +7 -6
  50. package/dist/protocol.js +101 -54
  51. package/dist/public-inbox.d.ts +17 -15
  52. package/dist/public-inbox.js +129 -138
  53. package/dist/public-thread.d.ts +7 -4
  54. package/dist/public-thread.js +205 -88
  55. package/dist/relay-pool.d.ts +5 -5
  56. package/dist/relay-pool.js +172 -67
  57. package/dist/relay-roles.js +22 -13
  58. package/dist/relay.d.ts +11 -11
  59. package/dist/relay.js +194 -100
  60. package/dist/request-timing.d.ts +2 -2
  61. package/dist/request-timing.js +19 -7
  62. package/dist/session.js +7 -5
  63. package/dist/signer.d.ts +1 -1
  64. package/dist/signers/bunker-relays.d.ts +2 -2
  65. package/dist/signers/bunker-relays.js +16 -13
  66. package/dist/signers/bunker.d.ts +2 -2
  67. package/dist/signers/bunker.js +57 -37
  68. package/dist/signers/nsec.d.ts +2 -2
  69. package/dist/signers/nsec.js +8 -8
  70. package/dist/signers.d.ts +8 -8
  71. package/dist/signers.js +25 -18
  72. package/dist/storage-sqlite.d.ts +3 -1
  73. package/dist/storage-sqlite.js +110 -58
  74. package/dist/storage.d.ts +10 -6
  75. package/dist/store.d.ts +12 -8
  76. package/dist/store.js +156 -78
  77. package/docs/ACCESS.md +14 -25
  78. package/docs/API.md +125 -79
  79. package/docs/KEYS.md +3 -3
  80. package/docs/NIP-CD.md +29 -19
  81. package/docs/PUBLIC.md +33 -23
  82. package/docs/RECOVERY.md +7 -5
  83. package/docs/RELAYS.md +6 -6
  84. package/docs/SESSIONS.md +25 -21
  85. package/docs/SIGNERS.md +5 -3
  86. package/docs/STORAGE.md +15 -15
  87. package/docs/TUTORIAL.md +42 -39
  88. package/package.json +1 -37
  89. package/dist/inbound-policy.d.ts +0 -4
  90. package/dist/inbound-policy.js +0 -9
@@ -1,7 +1,14 @@
1
- import { signChecked } from './protocol.js';
2
- import { publicationGroups, relayUnion } from './relay-roles.js';
3
- const slot = (event) => JSON.stringify([event.kind, event.kind === 31992 ? event.tags.find(tag => tag[0] === 'd')?.[1] ?? '' : '']);
4
- const same = (event, template) => event.kind === template.kind && event.content === template.content && JSON.stringify(event.tags) === JSON.stringify(template.tags);
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);
5
12
  /** Durable public metadata retry. No command handlers, registry privacy inference or installation lists. */
6
13
  export class Announcements {
7
14
  identity;
@@ -15,68 +22,87 @@ export class Announcements {
15
22
  this.store = store;
16
23
  this.transport = transport;
17
24
  this.published = published;
18
- this.state = store.metadata('announcements') ?? {
25
+ this.state = store.metadata("announcements") ?? {
19
26
  version: 1,
20
27
  cache: {},
21
- pending: []
28
+ pending: [],
22
29
  };
23
- if (this.state.version !== 1 || !this.state.cache || !Array.isArray(this.state.pending)) {
24
- throw new Error('Unsupported announcement state');
30
+ if (this.state.version !== 1 ||
31
+ !this.state.cache ||
32
+ !Array.isArray(this.state.pending)) {
33
+ throw new Error("Unsupported announcement state");
25
34
  }
26
35
  // This journal owns relay and media server list announcements; command operations have a separate journal.
27
- const supported = (event) => event && (event.kind === 10002 || event.kind === 10050 || event.kind === 10063);
36
+ const supported = (event) => event &&
37
+ (event.kind === 10002 || event.kind === 10050 || event.kind === 10063);
28
38
  const cache = Object.fromEntries(Object.entries(this.state.cache).filter(([, event]) => supported(event)));
29
- const pending = this.state.pending.filter(item => supported(item.event));
30
- if (Object.keys(cache).length !== Object.keys(this.state.cache).length || pending.length !== this.state.pending.length) {
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) {
31
42
  this.save({ version: 1, cache, pending });
32
43
  }
33
44
  }
34
45
  save(next) {
35
- this.store.saveMetadata('announcements', next);
46
+ this.store.saveMetadata("announcements", next);
36
47
  this.state = next;
37
48
  }
38
49
  serialize(run) {
39
- const task = (this.operation ?? Promise.resolve()).catch(() => {
40
- }).then(run);
50
+ const task = (this.operation ?? Promise.resolve())
51
+ .catch(() => { })
52
+ .then(run);
41
53
  this.operation = task;
42
- void task.finally(() => {
54
+ void task
55
+ .finally(() => {
43
56
  if (this.operation === task) {
44
57
  this.operation = undefined;
45
58
  }
46
- }).catch(() => {
47
- });
59
+ })
60
+ .catch(() => { });
48
61
  return task;
49
62
  }
50
63
  publish(announcements) {
51
64
  return this.serialize(async () => {
52
65
  const cache = {
53
- ...this.state.cache
66
+ ...this.state.cache,
54
67
  };
55
68
  const planned = [];
56
69
  for (const { template, groups, optionalRelays = [] } of announcements) {
57
70
  const coordinate = slot(template), old = cache[coordinate];
58
- const event = old && same(old, template) ? old : await signChecked(this.identity, {
59
- ...template, created_at: Math.max(template.created_at, (old?.created_at ?? -1) + 1)
60
- });
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
+ });
61
77
  cache[coordinate] = event;
62
78
  const required = publicationGroups(groups);
63
- const requiredUrls = new Set(required.flat().map(url => new URL(url).href));
79
+ const requiredUrls = new Set(required.flat().map((url) => new URL(url).href));
64
80
  planned.push({
65
- event, groups: required,
66
- optionalRelays: relayUnion(optionalRelays).filter(url => !requiredUrls.has(new URL(url).href))
81
+ event,
82
+ groups: required,
83
+ optionalRelays: relayUnion(optionalRelays).filter((url) => !requiredUrls.has(new URL(url).href)),
67
84
  });
68
85
  }
69
- const canonicalSet = (urls) => urls.map(url => new URL(url).href).sort();
86
+ const canonicalSet = (urls) => urls.map((url) => new URL(url).href).sort();
70
87
  const plan = JSON.stringify(planned.map(({ event, groups, optionalRelays }) => [
71
- event.id, groups.map(canonicalSet), canonicalSet(optionalRelays)
88
+ event.id,
89
+ groups.map(canonicalSet),
90
+ canonicalSet(optionalRelays),
72
91
  ]));
73
92
  // Changed settings replace old obligations; unchanged pending work keeps exact progress and IDs.
74
93
  if (!this.state.pending.length || this.state.plan !== plan) {
75
- this.save({ version: 1, cache, plan, pending: planned.map(({ event, groups }) => ({ event, groups })) });
94
+ this.save({
95
+ version: 1,
96
+ cache,
97
+ plan,
98
+ pending: planned.map(({ event, groups }) => ({ event, groups })),
99
+ });
76
100
  for (const { event, optionalRelays } of planned) {
77
101
  if (optionalRelays.length) {
78
102
  // Extra discovery relays are not required acknowledgers and never enter the retry journal.
79
- void Promise.resolve().then(() => this.transport.publish(optionalRelays, event)).catch(() => { });
103
+ void Promise.resolve()
104
+ .then(() => this.transport.publish(optionalRelays, event))
105
+ .catch(() => { });
80
106
  }
81
107
  }
82
108
  }
@@ -86,25 +112,31 @@ export class Announcements {
86
112
  async drain() {
87
113
  const results = await Promise.allSettled(this.state.pending.flatMap(({ event, groups }) => groups.map(async (group) => {
88
114
  await this.transport.publish(group, event);
89
- const remaining = this.state.pending.find(item => item.event.id === event.id).groups.filter(other => other !== group);
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);
90
119
  this.save({
91
120
  ...this.state,
92
- pending: this.state.pending.flatMap(item => item.event.id !== event.id ? [item] : remaining.length ? [{ event, groups: remaining }] : [])
121
+ pending: this.state.pending.flatMap((item) => item.event.id !== event.id
122
+ ? [item]
123
+ : remaining.length
124
+ ? [{ event, groups: remaining }]
125
+ : []),
93
126
  });
94
127
  if (!remaining.length)
95
128
  this.published?.(event);
96
129
  })));
97
- const failures = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
130
+ const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
98
131
  if (failures.length === 1)
99
132
  throw failures[0];
100
133
  if (failures.length > 1)
101
- throw new AggregateError(failures, 'Account metadata publication failed');
134
+ throw new AggregateError(failures, "Account metadata publication failed");
102
135
  }
103
136
  hasPending() {
104
137
  return this.state.pending.length > 0;
105
138
  }
106
139
  async idle() {
107
- await this.operation?.catch(() => {
108
- });
140
+ await this.operation?.catch(() => { });
109
141
  }
110
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
+ }
package/dist/blossom.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Identity } from './protocol.js';
1
+ import { type Identity } from "./protocol.js";
2
2
  export declare function normalizeBlossomServers(values: readonly string[] | undefined): string[];
3
3
  /** Additional trusted HTTPS origins that may host a server's blob descriptors. */
4
4
  export declare function normalizeBlossomDownloadOrigins(values: readonly string[] | undefined): ReadonlySet<string>;
@@ -20,7 +20,7 @@ export interface SendFileOptions {
20
20
  /** ID of the decrypted parent message. */
21
21
  replyTo?: string;
22
22
  }
23
- export type ReplyFileOptions = Omit<SendFileOptions, 'replyTo'>;
23
+ export type ReplyFileOptions = Omit<SendFileOptions, "replyTo">;
24
24
  export declare function snapshotFile(data: Uint8Array): Buffer<ArrayBuffer>;
25
25
  export declare function encryptAttachment(data: Uint8Array, { mimeType, name }: SendFileOptions): {
26
26
  bytes: Buffer<ArrayBuffer>;