@remit/storage-service 0.0.12 → 0.0.14

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.
@@ -1,624 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { PassThrough, type Readable } from "node:stream";
3
- import { pipeline } from "node:stream/promises";
4
- import { createGunzip, createGzip, gunzipSync, gzipSync } from "node:zlib";
5
- import {
6
- DeleteObjectCommand,
7
- DeleteObjectsCommand,
8
- GetObjectCommand,
9
- HeadObjectCommand,
10
- ListObjectsV2Command,
11
- PutObjectCommand,
12
- type S3Client,
13
- } from "@aws-sdk/client-s3";
14
- import { Upload } from "@aws-sdk/lib-storage";
15
- import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
16
- import { ContentEncoding, StorageType } from "@remit/domain-enums";
17
- import type {
18
- OutboxAttachmentListItem,
19
- ParsedBody,
20
- StorageReference,
21
- StorageService,
22
- } from "../storage.js";
23
- import {
24
- buildBodyPartKey,
25
- buildDeduplicatedKey,
26
- buildExportArchiveKey,
27
- buildMessageBodyKey,
28
- buildOutboxAttachmentKey,
29
- buildOutboxAttachmentPrefix,
30
- buildParsedBodyKey,
31
- computeChecksum,
32
- isStorageNotFoundError,
33
- } from "../storage.js";
34
- import { parseStorageUri } from "../uri.js";
35
-
36
- interface StoreParams {
37
- key: string;
38
- content: Buffer;
39
- contentType?: string;
40
- compress?: boolean;
41
- }
42
-
43
- export const createS3StorageService = (
44
- client: S3Client,
45
- bucketName: string,
46
- ): StorageService => {
47
- const storeInternal = async (
48
- params: StoreParams,
49
- ): Promise<StorageReference> => {
50
- const { key, content, contentType, compress = true } = params;
51
- const contentChecksumSha256 = computeChecksum(content);
52
- const contentEncoding = compress
53
- ? ContentEncoding.Gzip
54
- : ContentEncoding.None;
55
- const body = compress ? gzipSync(content) : content;
56
-
57
- await client.send(
58
- new PutObjectCommand({
59
- Bucket: bucketName,
60
- Key: key,
61
- Body: body,
62
- ContentType: contentType,
63
- ContentEncoding: compress ? "gzip" : undefined,
64
- }),
65
- );
66
-
67
- return {
68
- uri: `s3://${bucketName}/${key}`,
69
- storageType: StorageType.S3,
70
- storageLocation: bucketName,
71
- storageKey: key,
72
- sizeBytes: body.length,
73
- checksumSha256: contentChecksumSha256,
74
- contentEncoding,
75
- };
76
- };
77
-
78
- const storeMessageBody: StorageService["storeMessageBody"] = (params) => {
79
- const { accountConfigId, accountId, messageId, content } = params;
80
- return storeInternal({
81
- key: buildMessageBodyKey(accountConfigId, accountId, messageId),
82
- content,
83
- contentType: "message/rfc822",
84
- });
85
- };
86
-
87
- const storeMessageBodyStream: StorageService["storeMessageBodyStream"] =
88
- async (params) => {
89
- const { accountConfigId, accountId, messageId, content } = params;
90
- const key = buildMessageBodyKey(accountConfigId, accountId, messageId);
91
-
92
- // Hash the logical (pre-gzip) bytes as they flow, gzip them, and feed
93
- // the gzipped stream to a multipart Upload — the whole body is never
94
- // held in memory. `Upload` buffers only one part at a time.
95
- const hash = createHash("sha256");
96
- const hashTap = new PassThrough();
97
- hashTap.on("data", (chunk: Buffer) => hash.update(chunk));
98
-
99
- const gzip = createGzip();
100
- const uploadBody = new PassThrough();
101
-
102
- let storedBytes = 0;
103
- uploadBody.on("data", (chunk: Buffer) => {
104
- storedBytes += chunk.length;
105
- });
106
-
107
- const upload = new Upload({
108
- client,
109
- params: {
110
- Bucket: bucketName,
111
- Key: key,
112
- Body: uploadBody,
113
- ContentType: "message/rfc822",
114
- ContentEncoding: "gzip",
115
- },
116
- });
117
-
118
- const pumped = pipeline(content, hashTap, gzip, uploadBody);
119
- await Promise.all([upload.done(), pumped]).catch(async (error) => {
120
- // Abort the multipart upload so a failed pump doesn't leak parts.
121
- await upload.abort().catch(() => {});
122
- throw error;
123
- });
124
-
125
- return {
126
- uri: `s3://${bucketName}/${key}`,
127
- storageType: StorageType.S3,
128
- storageLocation: bucketName,
129
- storageKey: key,
130
- sizeBytes: storedBytes,
131
- checksumSha256: hash.digest("hex"),
132
- contentEncoding: ContentEncoding.Gzip,
133
- };
134
- };
135
-
136
- const storeBodyPart: StorageService["storeBodyPart"] = (params) => {
137
- const {
138
- accountConfigId,
139
- accountId,
140
- messageId,
141
- partPath,
142
- content,
143
- contentType,
144
- } = params;
145
- return storeInternal({
146
- key: buildBodyPartKey(accountConfigId, accountId, messageId, partPath),
147
- content,
148
- contentType,
149
- });
150
- };
151
-
152
- const bodyPartExists: StorageService["bodyPartExists"] = (
153
- accountConfigId,
154
- accountId,
155
- messageId,
156
- partPath,
157
- ) => {
158
- const key = buildBodyPartKey(
159
- accountConfigId,
160
- accountId,
161
- messageId,
162
- partPath,
163
- );
164
- return client
165
- .send(new HeadObjectCommand({ Bucket: bucketName, Key: key }))
166
- .then(() => true)
167
- .catch(() => false);
168
- };
169
-
170
- const retrieveBodyPart: StorageService["retrieveBodyPart"] = async (
171
- accountConfigId,
172
- accountId,
173
- messageId,
174
- partPath,
175
- ) => {
176
- const key = buildBodyPartKey(
177
- accountConfigId,
178
- accountId,
179
- messageId,
180
- partPath,
181
- );
182
-
183
- const response = await client
184
- .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
185
- .catch((error: unknown) => {
186
- if (isStorageNotFoundError(error)) return null;
187
- throw error;
188
- });
189
-
190
- if (!response) return null;
191
- if (!response.Body) {
192
- throw new Error(`Empty response body for body part: ${key}`);
193
- }
194
-
195
- const body = await response.Body.transformToByteArray();
196
- const buffer = Buffer.from(body);
197
- return response.ContentEncoding === "gzip" ? gunzipSync(buffer) : buffer;
198
- };
199
-
200
- const storeOutboxAttachment: StorageService["storeOutboxAttachment"] = (
201
- params,
202
- ) => {
203
- const {
204
- accountConfigId,
205
- accountId,
206
- outboxMessageId,
207
- outboxAttachmentId,
208
- content,
209
- } = params;
210
- // `application/octet-stream` rather than the uploader's declared type:
211
- // the object is only ever read back to build a MIME part, and a stored
212
- // `text/html` would be a type any future signed-URL read path could be
213
- // tricked into serving from the content origin.
214
- return storeInternal({
215
- key: buildOutboxAttachmentKey(
216
- accountConfigId,
217
- accountId,
218
- outboxMessageId,
219
- outboxAttachmentId,
220
- ),
221
- content,
222
- contentType: "application/octet-stream",
223
- compress: false,
224
- });
225
- };
226
-
227
- const listOutboxAttachments: StorageService["listOutboxAttachments"] = async (
228
- accountConfigId,
229
- accountId,
230
- outboxMessageId,
231
- ) => {
232
- const prefix = buildOutboxAttachmentPrefix(
233
- accountConfigId,
234
- accountId,
235
- outboxMessageId,
236
- );
237
- const items: OutboxAttachmentListItem[] = [];
238
- let continuationToken: string | undefined;
239
-
240
- do {
241
- const response = await client.send(
242
- new ListObjectsV2Command({
243
- Bucket: bucketName,
244
- Prefix: prefix,
245
- ContinuationToken: continuationToken,
246
- }),
247
- );
248
- for (const object of response.Contents ?? []) {
249
- if (!object.Key) continue;
250
- items.push({
251
- outboxAttachmentId: object.Key.slice(prefix.length),
252
- key: object.Key,
253
- sizeBytes: object.Size ?? 0,
254
- });
255
- }
256
- continuationToken = response.IsTruncated
257
- ? response.NextContinuationToken
258
- : undefined;
259
- } while (continuationToken);
260
-
261
- return items;
262
- };
263
-
264
- const listOutboxDraftsWithAttachments: StorageService["listOutboxDraftsWithAttachments"] =
265
- async (accountConfigId, accountId) => {
266
- const root = `accounts/${accountConfigId}/${accountId}/outbox/`;
267
- const drafts = new Set<string>();
268
- let continuationToken: string | undefined;
269
-
270
- // Delimited listing: S3 answers with the directory-like prefixes rather
271
- // than every object under them, so this stays one call per page of
272
- // drafts instead of one per object.
273
- do {
274
- const response = await client.send(
275
- new ListObjectsV2Command({
276
- Bucket: bucketName,
277
- Prefix: root,
278
- Delimiter: "/",
279
- ContinuationToken: continuationToken,
280
- }),
281
- );
282
- for (const entry of response.CommonPrefixes ?? []) {
283
- if (!entry.Prefix) continue;
284
- drafts.add(entry.Prefix.slice(root.length).replace(/\/$/, ""));
285
- }
286
- continuationToken = response.IsTruncated
287
- ? response.NextContinuationToken
288
- : undefined;
289
- } while (continuationToken);
290
-
291
- return [...drafts];
292
- };
293
-
294
- const deleteOutboxAttachment: StorageService["deleteOutboxAttachment"] =
295
- async (accountConfigId, accountId, outboxMessageId, outboxAttachmentId) => {
296
- const prefix = buildOutboxAttachmentPrefix(
297
- accountConfigId,
298
- accountId,
299
- outboxMessageId,
300
- );
301
- await client.send(
302
- new DeleteObjectCommand({
303
- Bucket: bucketName,
304
- Key: `${prefix}${outboxAttachmentId}`,
305
- }),
306
- );
307
- };
308
-
309
- const statOutboxAttachment: StorageService["statOutboxAttachment"] = async (
310
- accountConfigId,
311
- accountId,
312
- outboxMessageId,
313
- outboxAttachmentId,
314
- ) => {
315
- const head = await client
316
- .send(
317
- new HeadObjectCommand({
318
- Bucket: bucketName,
319
- Key: buildOutboxAttachmentKey(
320
- accountConfigId,
321
- accountId,
322
- outboxMessageId,
323
- outboxAttachmentId,
324
- ),
325
- }),
326
- )
327
- .catch((error: unknown) => {
328
- if (isStorageNotFoundError(error)) return null;
329
- // A HEAD on a missing key answers 404 with no NoSuchKey code, so the
330
- // SDK's NotFound is the same absence.
331
- if ((error as { name?: string })?.name === "NotFound") return null;
332
- throw error;
333
- });
334
- if (!head) return null;
335
- return { sizeBytes: head.ContentLength ?? 0 };
336
- };
337
-
338
- const retrieveOutboxAttachment: StorageService["retrieveOutboxAttachment"] =
339
- async (accountConfigId, accountId, outboxMessageId, outboxAttachmentId) => {
340
- const key = buildOutboxAttachmentKey(
341
- accountConfigId,
342
- accountId,
343
- outboxMessageId,
344
- outboxAttachmentId,
345
- );
346
- const response = await client
347
- .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
348
- .catch((error: unknown) => {
349
- if (isStorageNotFoundError(error)) return null;
350
- throw error;
351
- });
352
- if (!response) return null;
353
- if (!response.Body) {
354
- throw new Error(`Empty response body for outbox attachment: ${key}`);
355
- }
356
- const bytes = await response.Body.transformToByteArray();
357
- return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
358
- };
359
-
360
- // The browser PUTs straight to the bucket and these bytes never touch the
361
- // API. `ContentLength` on the command hoists `content-length` into
362
- // X-Amz-SignedHeaders, so S3 recomputes the signature over the length it was
363
- // sent: a request declaring any other size fails the signature check, and a
364
- // PUT is read for exactly that many bytes. The size is bound by S3 itself,
365
- // not by anything downstream trusting the client.
366
- const createOutboxAttachmentUploadUrl: StorageService["createOutboxAttachmentUploadUrl"] =
367
- async (params) => {
368
- const expiresIn = Math.max(
369
- 1,
370
- params.expiresAt - Math.floor(Date.now() / 1000),
371
- );
372
- const uploadUrl = await getSignedUrl(
373
- client,
374
- new PutObjectCommand({
375
- Bucket: bucketName,
376
- Key: buildOutboxAttachmentKey(
377
- params.accountConfigId,
378
- params.accountId,
379
- params.outboxMessageId,
380
- params.outboxAttachmentId,
381
- ),
382
- ContentLength: params.sizeBytes,
383
- }),
384
- { expiresIn },
385
- );
386
- return { uploadUrl };
387
- };
388
-
389
- const deleteOutboxAttachments: StorageService["deleteOutboxAttachments"] =
390
- async (accountConfigId, accountId, outboxMessageId) => {
391
- const prefix = buildOutboxAttachmentPrefix(
392
- accountConfigId,
393
- accountId,
394
- outboxMessageId,
395
- );
396
- let continuationToken: string | undefined;
397
-
398
- do {
399
- const response = await client.send(
400
- new ListObjectsV2Command({
401
- Bucket: bucketName,
402
- Prefix: prefix,
403
- ContinuationToken: continuationToken,
404
- }),
405
- );
406
- const keys = (response.Contents ?? [])
407
- .map((object) => object.Key)
408
- .filter((key): key is string => typeof key === "string");
409
-
410
- if (keys.length > 0) {
411
- await client.send(
412
- new DeleteObjectsCommand({
413
- Bucket: bucketName,
414
- Delete: { Objects: keys.map((Key) => ({ Key })) },
415
- }),
416
- );
417
- }
418
-
419
- continuationToken = response.IsTruncated
420
- ? response.NextContinuationToken
421
- : undefined;
422
- } while (continuationToken);
423
- };
424
-
425
- const storeDeduplicated: StorageService["storeDeduplicated"] = (params) => {
426
- const { accountConfigId, accountId, content, contentType } = params;
427
- const checksumSha256 = computeChecksum(content);
428
- return storeInternal({
429
- key: buildDeduplicatedKey(accountConfigId, accountId, checksumSha256),
430
- content,
431
- contentType,
432
- });
433
- };
434
-
435
- const storeParsedBody: StorageService["storeParsedBody"] = (params) => {
436
- const { accountConfigId, accountId, messageId, parsed } = params;
437
- const content = Buffer.from(JSON.stringify(parsed), "utf8");
438
- return storeInternal({
439
- key: buildParsedBodyKey(accountConfigId, accountId, messageId),
440
- content,
441
- contentType: "application/json",
442
- });
443
- };
444
-
445
- const retrieveParsedBody: StorageService["retrieveParsedBody"] = async (
446
- accountConfigId,
447
- accountId,
448
- messageId,
449
- ) => {
450
- const key = buildParsedBodyKey(accountConfigId, accountId, messageId);
451
-
452
- const response = await client
453
- .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
454
- .catch((error: unknown) => {
455
- if (isStorageNotFoundError(error)) return null;
456
- throw error;
457
- });
458
-
459
- if (!response) return null;
460
- if (!response.Body) {
461
- throw new Error(`Empty response body for parsed body: ${key}`);
462
- }
463
-
464
- const body = await response.Body.transformToByteArray();
465
- const buffer = Buffer.from(body);
466
- const decoded =
467
- response.ContentEncoding === "gzip" ? gunzipSync(buffer) : buffer;
468
- return JSON.parse(decoded.toString("utf8")) as ParsedBody;
469
- };
470
-
471
- const retrieve = async (uri: string): Promise<Buffer> => {
472
- const { storageKey } = parseStorageUri(uri);
473
-
474
- const response = await client.send(
475
- new GetObjectCommand({
476
- Bucket: bucketName,
477
- Key: storageKey,
478
- }),
479
- );
480
-
481
- if (!response.Body) {
482
- throw new Error(`Empty response body for: ${uri}`);
483
- }
484
-
485
- const body = await response.Body.transformToByteArray();
486
- const buffer = Buffer.from(body);
487
-
488
- if (response.ContentEncoding === "gzip") {
489
- return gunzipSync(buffer);
490
- }
491
-
492
- return buffer;
493
- };
494
-
495
- const retrieveMessageBody: StorageService["retrieveMessageBody"] = async (
496
- accountConfigId,
497
- accountId,
498
- messageId,
499
- ) => {
500
- const key = buildMessageBodyKey(accountConfigId, accountId, messageId);
501
-
502
- const response = await client
503
- .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
504
- .catch((error: unknown) => {
505
- if (isStorageNotFoundError(error)) return null;
506
- throw error;
507
- });
508
-
509
- if (!response) return null;
510
- if (!response.Body) {
511
- throw new Error(`Empty response body for message body: ${key}`);
512
- }
513
-
514
- const body = await response.Body.transformToByteArray();
515
- const buffer = Buffer.from(body);
516
- return response.ContentEncoding === "gzip" ? gunzipSync(buffer) : buffer;
517
- };
518
-
519
- const retrieveMessageBodyStream: StorageService["retrieveMessageBodyStream"] =
520
- async (accountConfigId, accountId, messageId) => {
521
- const key = buildMessageBodyKey(accountConfigId, accountId, messageId);
522
-
523
- const response = await client
524
- .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
525
- .catch((error: unknown) => {
526
- if (isStorageNotFoundError(error)) return null;
527
- throw error;
528
- });
529
-
530
- if (!response) return null;
531
- if (!response.Body) {
532
- throw new Error(`Empty response body for message body: ${key}`);
533
- }
534
-
535
- const source = response.Body as Readable;
536
- if (response.ContentEncoding === "gzip") {
537
- return source.pipe(createGunzip());
538
- }
539
- return source;
540
- };
541
-
542
- const exists = async (uri: string): Promise<boolean> => {
543
- const { storageKey } = parseStorageUri(uri);
544
-
545
- return client
546
- .send(
547
- new HeadObjectCommand({
548
- Bucket: bucketName,
549
- Key: storageKey,
550
- }),
551
- )
552
- .then(() => true)
553
- .catch(() => false);
554
- };
555
-
556
- const del = async (uri: string): Promise<void> => {
557
- const { storageKey } = parseStorageUri(uri);
558
-
559
- await client.send(
560
- new DeleteObjectCommand({
561
- Bucket: bucketName,
562
- Key: storageKey,
563
- }),
564
- );
565
- };
566
-
567
- const storeExportArchiveStream = async (
568
- accountConfigId: string,
569
- exportRequestId: string,
570
- body: Readable,
571
- ): Promise<string> => {
572
- const key = buildExportArchiveKey(accountConfigId, exportRequestId);
573
- const upload = new Upload({
574
- client,
575
- params: {
576
- Bucket: bucketName,
577
- Key: key,
578
- Body: body,
579
- ContentType: "application/zip",
580
- },
581
- });
582
- await upload.done().catch(async (error) => {
583
- await upload.abort().catch(() => {});
584
- throw error;
585
- });
586
- return key;
587
- };
588
-
589
- const getPresignedDownloadUrl = (
590
- key: string,
591
- expiresInSeconds: number,
592
- ): Promise<string> =>
593
- getSignedUrl(
594
- client,
595
- new GetObjectCommand({ Bucket: bucketName, Key: key }),
596
- { expiresIn: expiresInSeconds },
597
- );
598
-
599
- return {
600
- storeMessageBody,
601
- storeMessageBodyStream,
602
- storeBodyPart,
603
- bodyPartExists,
604
- retrieveBodyPart,
605
- storeOutboxAttachment,
606
- listOutboxAttachments,
607
- listOutboxDraftsWithAttachments,
608
- deleteOutboxAttachments,
609
- deleteOutboxAttachment,
610
- statOutboxAttachment,
611
- retrieveOutboxAttachment,
612
- createOutboxAttachmentUploadUrl,
613
- storeDeduplicated,
614
- storeParsedBody,
615
- retrieveParsedBody,
616
- retrieveMessageBody,
617
- retrieveMessageBodyStream,
618
- retrieve,
619
- exists,
620
- delete: del,
621
- storeExportArchiveStream,
622
- getPresignedDownloadUrl,
623
- };
624
- };
package/src/index.ts DELETED
@@ -1,53 +0,0 @@
1
- export {
2
- type OutboxSweepResult,
3
- sweepAbandonedOutboxAttachments,
4
- } from "./outbox-sweep.js";
5
- export {
6
- type AuthorizeUploadInput,
7
- type AuthorizeUploadResult,
8
- authorizeUploadRequest,
9
- UPLOAD_ROUTE_PREFIX,
10
- UPLOAD_URL_SIGNING_LABEL,
11
- UPLOAD_URL_TTL_SECONDS,
12
- } from "./outbox-upload-url.js";
13
- export {
14
- type SignedPathFailure,
15
- type SignedPathResult,
16
- signStoragePath,
17
- verifyStoragePath,
18
- } from "./signed-path.js";
19
- export {
20
- buildBodyPartKey,
21
- buildDeduplicatedKey,
22
- buildExportArchiveKey,
23
- buildMessageBodyKey,
24
- buildOutboxAttachmentKey,
25
- buildOutboxAttachmentPrefix,
26
- buildParsedBodyKey,
27
- type ContentEncodingValue,
28
- type CreateOutboxAttachmentUploadUrlParams,
29
- computeChecksum,
30
- createMockStorageService,
31
- isStorageNotFoundError,
32
- type OutboxAttachmentListItem,
33
- type OutboxAttachmentUploadTarget,
34
- type ParsedAttachmentMeta,
35
- type ParsedBody,
36
- type ParsedContentStorageKey,
37
- type ParsedOutboxAttachmentKey,
38
- parseContentStorageKey,
39
- parseOutboxAttachmentKey,
40
- type StorageReference,
41
- type StorageService,
42
- type StorageTypeValue,
43
- type StoreBodyPartParams,
44
- type StoreDeduplicatedParams,
45
- type StoreMessageBodyParams,
46
- type StoreOutboxAttachmentParams,
47
- type StoreParsedBodyParams,
48
- } from "./storage.js";
49
- export {
50
- buildStorageUri,
51
- type ParsedStorageUri,
52
- parseStorageUri,
53
- } from "./uri.js";