@bymax-one/nest-storage 1.0.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.
@@ -0,0 +1,1836 @@
1
+ import { HttpStatus, Injectable, Inject, Global, Module, Logger, HttpException } from '@nestjs/common';
2
+ import { S3Client, HeadObjectCommand, GetObjectCommand, DeleteObjectCommand, PutObjectCommand, ListObjectsV2Command, CopyObjectCommand, DeleteObjectsCommand, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
3
+ import { Upload } from '@aws-sdk/lib-storage';
4
+ import { PassThrough } from 'stream';
5
+ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
6
+ import { createHash } from 'crypto';
7
+
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __decorateClass = (decorators, target, key, kind) => {
10
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
11
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
12
+ if (decorator = decorators[i])
13
+ result = (decorator(result)) || result;
14
+ return result;
15
+ };
16
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
17
+
18
+ // src/server/bymax-storage.constants.ts
19
+ var BYMAX_STORAGE_OPTIONS = /* @__PURE__ */ Symbol("BYMAX_STORAGE_OPTIONS");
20
+ var BYMAX_STORAGE_S3_CLIENT = /* @__PURE__ */ Symbol("BYMAX_STORAGE_S3_CLIENT");
21
+ var BYMAX_STORAGE_UPLOAD_VALIDATORS = /* @__PURE__ */ Symbol("BYMAX_STORAGE_UPLOAD_VALIDATORS");
22
+ var BYMAX_STORAGE_FILE_SCANNER = /* @__PURE__ */ Symbol("BYMAX_STORAGE_FILE_SCANNER");
23
+ var BYMAX_STORAGE_LOGGER = /* @__PURE__ */ Symbol("BYMAX_STORAGE_LOGGER");
24
+ var BYMAX_STORAGE_IDEMPOTENCY_CACHE = /* @__PURE__ */ Symbol("BYMAX_STORAGE_IDEMPOTENCY_CACHE");
25
+
26
+ // src/shared/constants/error-codes.constants.ts
27
+ var STORAGE_ERROR_CODES = {
28
+ STORAGE_NOT_CONFIGURED: "STORAGE_NOT_CONFIGURED",
29
+ STORAGE_KEY_INVALID: "STORAGE_KEY_INVALID",
30
+ STORAGE_BODY_MISSING: "STORAGE_BODY_MISSING",
31
+ STORAGE_CONTENT_TYPE_REQUIRED: "STORAGE_CONTENT_TYPE_REQUIRED",
32
+ STORAGE_MIME_NOT_ALLOWED: "STORAGE_MIME_NOT_ALLOWED",
33
+ STORAGE_SIZE_EXCEEDED: "STORAGE_SIZE_EXCEEDED",
34
+ STORAGE_VALIDATION_FAILED: "STORAGE_VALIDATION_FAILED",
35
+ STORAGE_SCAN_INFECTED: "STORAGE_SCAN_INFECTED",
36
+ STORAGE_SCAN_INCONCLUSIVE: "STORAGE_SCAN_INCONCLUSIVE",
37
+ STORAGE_OBJECT_NOT_FOUND: "STORAGE_OBJECT_NOT_FOUND",
38
+ STORAGE_PROVIDER_ERROR: "STORAGE_PROVIDER_ERROR",
39
+ STORAGE_SIGNED_URL_TTL_INVALID: "STORAGE_SIGNED_URL_TTL_INVALID",
40
+ STORAGE_PART_TOO_SMALL: "STORAGE_PART_TOO_SMALL",
41
+ STORAGE_INVALID_PART_COUNT: "STORAGE_INVALID_PART_COUNT",
42
+ STORAGE_BUCKET_UNDEFINED: "STORAGE_BUCKET_UNDEFINED",
43
+ STORAGE_MULTIPART_ABORTED: "STORAGE_MULTIPART_ABORTED",
44
+ STORAGE_INVALID_CONFIG: "STORAGE_INVALID_CONFIG",
45
+ STORAGE_TIMEOUT: "STORAGE_TIMEOUT"
46
+ };
47
+
48
+ // src/server/errors/storage-error-messages.ts
49
+ var STORAGE_ERROR_MESSAGES = {
50
+ [STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED]: "Storage credentials are not configured",
51
+ [STORAGE_ERROR_CODES.STORAGE_KEY_INVALID]: "Invalid storage key",
52
+ [STORAGE_ERROR_CODES.STORAGE_BODY_MISSING]: "Upload body is missing",
53
+ [STORAGE_ERROR_CODES.STORAGE_CONTENT_TYPE_REQUIRED]: "Content-Type is required",
54
+ [STORAGE_ERROR_CODES.STORAGE_MIME_NOT_ALLOWED]: "MIME type is not allowed",
55
+ [STORAGE_ERROR_CODES.STORAGE_SIZE_EXCEEDED]: "File size exceeds the allowed maximum",
56
+ [STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED]: "Custom validation failed",
57
+ [STORAGE_ERROR_CODES.STORAGE_SCAN_INFECTED]: "File scan reported the content as infected",
58
+ [STORAGE_ERROR_CODES.STORAGE_SCAN_INCONCLUSIVE]: "File scan was inconclusive and rejection-on-unknown is enabled",
59
+ [STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND]: "Object not found",
60
+ [STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR]: "Storage provider returned an error",
61
+ [STORAGE_ERROR_CODES.STORAGE_SIGNED_URL_TTL_INVALID]: "Signed URL TTL is invalid",
62
+ [STORAGE_ERROR_CODES.STORAGE_PART_TOO_SMALL]: "Multipart part size is below the 5 MB minimum",
63
+ [STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT]: "Multipart part count is invalid (must be a positive integer)",
64
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED]: "Bucket is undefined (no default configured and none provided per call)",
65
+ [STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED]: "Multipart upload was aborted",
66
+ [STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG]: "Module configuration is invalid",
67
+ [STORAGE_ERROR_CODES.STORAGE_TIMEOUT]: "Storage request timed out"
68
+ };
69
+ var STORAGE_ERROR_STATUS = {
70
+ [STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED]: HttpStatus.SERVICE_UNAVAILABLE,
71
+ [STORAGE_ERROR_CODES.STORAGE_KEY_INVALID]: HttpStatus.BAD_REQUEST,
72
+ [STORAGE_ERROR_CODES.STORAGE_BODY_MISSING]: HttpStatus.BAD_REQUEST,
73
+ [STORAGE_ERROR_CODES.STORAGE_CONTENT_TYPE_REQUIRED]: HttpStatus.BAD_REQUEST,
74
+ [STORAGE_ERROR_CODES.STORAGE_MIME_NOT_ALLOWED]: HttpStatus.UNSUPPORTED_MEDIA_TYPE,
75
+ [STORAGE_ERROR_CODES.STORAGE_SIZE_EXCEEDED]: HttpStatus.PAYLOAD_TOO_LARGE,
76
+ [STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED]: HttpStatus.BAD_REQUEST,
77
+ [STORAGE_ERROR_CODES.STORAGE_SCAN_INFECTED]: HttpStatus.UNPROCESSABLE_ENTITY,
78
+ [STORAGE_ERROR_CODES.STORAGE_SCAN_INCONCLUSIVE]: HttpStatus.UNPROCESSABLE_ENTITY,
79
+ [STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND]: HttpStatus.NOT_FOUND,
80
+ [STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR]: HttpStatus.BAD_GATEWAY,
81
+ [STORAGE_ERROR_CODES.STORAGE_SIGNED_URL_TTL_INVALID]: HttpStatus.BAD_REQUEST,
82
+ [STORAGE_ERROR_CODES.STORAGE_PART_TOO_SMALL]: HttpStatus.BAD_REQUEST,
83
+ [STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT]: HttpStatus.BAD_REQUEST,
84
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED]: HttpStatus.BAD_REQUEST,
85
+ [STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED]: HttpStatus.INTERNAL_SERVER_ERROR,
86
+ [STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG]: HttpStatus.INTERNAL_SERVER_ERROR,
87
+ [STORAGE_ERROR_CODES.STORAGE_TIMEOUT]: HttpStatus.GATEWAY_TIMEOUT
88
+ };
89
+
90
+ // src/server/errors/storage-exception.ts
91
+ var StorageException = class extends HttpException {
92
+ code;
93
+ constructor(code, statusCode = STORAGE_ERROR_STATUS[code], details) {
94
+ super(
95
+ {
96
+ error: {
97
+ code,
98
+ message: STORAGE_ERROR_MESSAGES[code],
99
+ ...details ? { details } : {}
100
+ }
101
+ },
102
+ statusCode
103
+ );
104
+ this.code = code;
105
+ }
106
+ };
107
+
108
+ // src/server/config/validate-options.ts
109
+ var MIN_PART_SIZE_BYTES = 5 * 1024 * 1024;
110
+ function invalid(reason) {
111
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG, HttpStatus.INTERNAL_SERVER_ERROR, {
112
+ reason
113
+ });
114
+ }
115
+ function isObject(value) {
116
+ return typeof value === "object" && value !== null;
117
+ }
118
+ function isNonEmptyString(value) {
119
+ return typeof value === "string" && value.length > 0;
120
+ }
121
+ function validateOptions(options) {
122
+ if (!isObject(options)) {
123
+ throw invalid("options object is required");
124
+ }
125
+ if (!isNonEmptyString(options.endpoint)) {
126
+ throw invalid("options.endpoint must be a non-empty string");
127
+ }
128
+ if (!isNonEmptyString(options.region)) {
129
+ throw invalid("options.region must be a non-empty string");
130
+ }
131
+ if (!isNonEmptyString(options.bucket)) {
132
+ throw invalid("options.bucket must be a non-empty string");
133
+ }
134
+ if (!isObject(options.credentials)) {
135
+ throw invalid("options.credentials is required");
136
+ }
137
+ const signedUrls = options.signedUrls;
138
+ if (isObject(signedUrls) && typeof signedUrls.maxTtlSeconds === "number" && signedUrls.maxTtlSeconds <= 0) {
139
+ throw invalid("signedUrls.maxTtlSeconds must be > 0");
140
+ }
141
+ const multipart = options.multipart;
142
+ if (isObject(multipart) && typeof multipart.partSizeBytes === "number" && multipart.partSizeBytes < MIN_PART_SIZE_BYTES) {
143
+ throw invalid("multipart.partSizeBytes must be >= 5 MB (S3 hard limit)");
144
+ }
145
+ if (options.serverSideEncryption === "aws:kms" && !options.kmsKeyId) {
146
+ throw invalid('kmsKeyId is required when serverSideEncryption === "aws:kms"');
147
+ }
148
+ }
149
+
150
+ // src/server/utils/trim-trailing-slashes.ts
151
+ var SLASH = "/";
152
+ function trimTrailingSlashes(value) {
153
+ let end = value.length;
154
+ while (end > 0 && value[end - 1] === SLASH) {
155
+ end -= 1;
156
+ }
157
+ return end === value.length ? value : value.slice(0, end);
158
+ }
159
+
160
+ // src/shared/constants/default-ttls.constants.ts
161
+ var DEFAULT_SIGNED_URL_TTL_SECONDS = 300;
162
+ var MAX_SIGNED_URL_TTL_SECONDS = 604800;
163
+ var DEFAULT_MULTIPART_THRESHOLD_BYTES = 5242880;
164
+ var DEFAULT_MULTIPART_PART_SIZE_BYTES = 5242880;
165
+ var DEFAULT_MULTIPART_QUEUE_SIZE = 4;
166
+
167
+ // src/server/constants/default-options.constants.ts
168
+ var DEFAULT_CACHE_CONTROL = "public, max-age=31536000, immutable";
169
+ var DEFAULT_CONTENT_DISPOSITION = "inline";
170
+ var DEFAULT_MAX_ATTEMPTS = 3;
171
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
172
+ var DEFAULT_FORCE_PATH_STYLE = false;
173
+ var DEFAULT_PUBLIC_READ = false;
174
+ var DEFAULT_CHECKSUM_CALCULATION = "WHEN_SUPPORTED";
175
+ var DEFAULT_CHECKSUM_VALIDATION = "WHEN_SUPPORTED";
176
+ var DEFAULT_SIGNED_URLS = {
177
+ defaultGetTtlSeconds: DEFAULT_SIGNED_URL_TTL_SECONDS,
178
+ defaultPutTtlSeconds: DEFAULT_SIGNED_URL_TTL_SECONDS,
179
+ maxTtlSeconds: MAX_SIGNED_URL_TTL_SECONDS
180
+ };
181
+ var DEFAULT_MULTIPART = {
182
+ thresholdBytes: DEFAULT_MULTIPART_THRESHOLD_BYTES,
183
+ partSizeBytes: DEFAULT_MULTIPART_PART_SIZE_BYTES,
184
+ queueSize: DEFAULT_MULTIPART_QUEUE_SIZE
185
+ };
186
+ var DEFAULT_IDEMPOTENCY_CACHE_MAX_ENTRIES = 1e3;
187
+ var DEFAULT_IDEMPOTENCY_CACHE_TTL_MS = 864e5;
188
+
189
+ // src/server/config/apply-defaults.ts
190
+ function applyDefaults(options) {
191
+ const hasCredentials = Boolean(options.credentials.accessKeyId) && Boolean(options.credentials.secretAccessKey);
192
+ const publicBaseUrl = options.publicBaseUrl ?? `${trimTrailingSlashes(options.endpoint)}/${options.bucket}`;
193
+ return {
194
+ endpoint: options.endpoint,
195
+ region: options.region,
196
+ bucket: options.bucket,
197
+ credentials: { ...options.credentials },
198
+ forcePathStyle: options.forcePathStyle ?? DEFAULT_FORCE_PATH_STYLE,
199
+ publicBaseUrl,
200
+ ...options.cdnBaseUrl !== void 0 ? { cdnBaseUrl: options.cdnBaseUrl } : {},
201
+ defaultPublicRead: options.defaultPublicRead ?? DEFAULT_PUBLIC_READ,
202
+ keyPrefix: options.keyPrefix ?? "",
203
+ defaultCacheControl: options.defaultCacheControl ?? DEFAULT_CACHE_CONTROL,
204
+ defaultContentDisposition: options.defaultContentDisposition ?? DEFAULT_CONTENT_DISPOSITION,
205
+ signedUrls: { ...DEFAULT_SIGNED_URLS, ...options.signedUrls ?? {} },
206
+ multipart: { ...DEFAULT_MULTIPART, ...options.multipart ?? {} },
207
+ ...options.validation !== void 0 ? { validation: options.validation } : {},
208
+ ...options.scanner !== void 0 ? { scanner: options.scanner } : {},
209
+ ...options.serverSideEncryption !== void 0 ? { serverSideEncryption: options.serverSideEncryption } : {},
210
+ ...options.kmsKeyId !== void 0 ? { kmsKeyId: options.kmsKeyId } : {},
211
+ requestChecksumCalculation: options.requestChecksumCalculation ?? DEFAULT_CHECKSUM_CALCULATION,
212
+ responseChecksumValidation: options.responseChecksumValidation ?? DEFAULT_CHECKSUM_VALIDATION,
213
+ maxAttempts: options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
214
+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
215
+ hasCredentials
216
+ };
217
+ }
218
+ var S3ClientProvider = class {
219
+ constructor(options) {
220
+ this.options = options;
221
+ }
222
+ options;
223
+ logger = new Logger(S3ClientProvider.name);
224
+ client;
225
+ onModuleInit() {
226
+ if (!this.options.hasCredentials) {
227
+ this.logger.warn(
228
+ "Storage credentials are missing \u2014 module is registered but operations will throw STORAGE_NOT_CONFIGURED."
229
+ );
230
+ return;
231
+ }
232
+ this.resolveClient();
233
+ }
234
+ onApplicationShutdown() {
235
+ if (this.client) {
236
+ this.client.destroy();
237
+ this.client = void 0;
238
+ }
239
+ }
240
+ /**
241
+ * Returns the live client, building it on first use, or `null` when storage is
242
+ * not configured. Used by the public raw-client token so its value does not
243
+ * depend on lifecycle-hook ordering.
244
+ *
245
+ * @returns The singleton client, or `null` when no credentials are configured.
246
+ */
247
+ getClientOrNull() {
248
+ if (!this.options.hasCredentials) {
249
+ return null;
250
+ }
251
+ return this.resolveClient();
252
+ }
253
+ /**
254
+ * Returns the singleton client. Throws when storage is not configured — call
255
+ * `isConfigured()` first and surface a typed `STORAGE_NOT_CONFIGURED`.
256
+ *
257
+ * @returns The singleton `S3Client`.
258
+ * @throws Error when storage is not configured.
259
+ */
260
+ getClient() {
261
+ if (!this.client) {
262
+ throw new Error("S3Client is not available \u2014 storage is not configured");
263
+ }
264
+ return this.client;
265
+ }
266
+ /**
267
+ * Reports whether the singleton client has been built.
268
+ *
269
+ * @returns `true` once the client exists, `false` otherwise.
270
+ */
271
+ isConfigured() {
272
+ return Boolean(this.client);
273
+ }
274
+ resolveClient() {
275
+ this.client ??= this.createClient();
276
+ return this.client;
277
+ }
278
+ createClient() {
279
+ const config = {
280
+ endpoint: this.options.endpoint,
281
+ region: this.options.region,
282
+ forcePathStyle: this.options.forcePathStyle,
283
+ credentials: {
284
+ accessKeyId: this.options.credentials.accessKeyId,
285
+ secretAccessKey: this.options.credentials.secretAccessKey,
286
+ ...this.options.credentials.sessionToken ? { sessionToken: this.options.credentials.sessionToken } : {}
287
+ },
288
+ maxAttempts: this.options.maxAttempts,
289
+ // Data-integrity checksums: AWS SDK v3 defaults to 'WHEN_SUPPORTED' (CRC32
290
+ // headers), which non-AWS S3-compatible providers reject. Provider recipes
291
+ // pass 'WHEN_REQUIRED'.
292
+ requestChecksumCalculation: this.options.requestChecksumCalculation,
293
+ responseChecksumValidation: this.options.responseChecksumValidation
294
+ };
295
+ this.logger.log(
296
+ `S3Client initialized: endpoint=${this.options.endpoint} region=${this.options.region}`
297
+ );
298
+ return new S3Client(config);
299
+ }
300
+ };
301
+ S3ClientProvider = __decorateClass([
302
+ Injectable(),
303
+ __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS))
304
+ ], S3ClientProvider);
305
+ function keyInvalid(reason) {
306
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_KEY_INVALID, HttpStatus.BAD_REQUEST, { reason });
307
+ }
308
+ var KeyResolverService = class {
309
+ keyPrefix;
310
+ constructor(options) {
311
+ const trimmedPrefix = options.keyPrefix ? options.keyPrefix.replace(/^\/+|\/+$/g, "") : "";
312
+ this.keyPrefix = trimmedPrefix ? `${trimmedPrefix}/` : "";
313
+ }
314
+ /**
315
+ * Normalizes a raw key into the final S3 object key. Rejects empty keys, null
316
+ * bytes, a leading `/`, and any `..` path segment; collapses duplicate slashes;
317
+ * prepends the configured prefix.
318
+ *
319
+ * @param rawKey - The caller-provided key, already URL-decoded by the caller.
320
+ * @returns The prefixed, normalized object key.
321
+ * @throws StorageException with code `STORAGE_KEY_INVALID`.
322
+ */
323
+ normalize(rawKey) {
324
+ if (rawKey.length === 0) {
325
+ throw keyInvalid("Key must be a non-empty string");
326
+ }
327
+ if (rawKey.includes("\0")) {
328
+ throw keyInvalid("Key must not contain null bytes");
329
+ }
330
+ if (rawKey.startsWith("/")) {
331
+ throw keyInvalid('Key must not start with "/"');
332
+ }
333
+ if (rawKey.split("/").some((segment) => segment === "..")) {
334
+ throw keyInvalid('Key must not contain ".." path segments');
335
+ }
336
+ const collapsed = rawKey.replace(/\/{2,}/g, "/");
337
+ return `${this.keyPrefix}${collapsed}`;
338
+ }
339
+ /**
340
+ * Strips the global key prefix from a key — useful when returning keys to the
341
+ * consumer so they need not know the prefix exists.
342
+ *
343
+ * @param fullKey - A normalized key that may carry the global prefix.
344
+ * @returns The key without the configured prefix.
345
+ */
346
+ stripPrefix(fullKey) {
347
+ if (this.keyPrefix && fullKey.startsWith(this.keyPrefix)) {
348
+ return fullKey.slice(this.keyPrefix.length);
349
+ }
350
+ return fullKey;
351
+ }
352
+ /**
353
+ * Read-only accessor for the resolved prefix.
354
+ *
355
+ * @returns The normalized prefix (empty string when none is configured).
356
+ */
357
+ getPrefix() {
358
+ return this.keyPrefix;
359
+ }
360
+ };
361
+ KeyResolverService = __decorateClass([
362
+ Injectable(),
363
+ __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS))
364
+ ], KeyResolverService);
365
+ function isBufferLike(body) {
366
+ return body instanceof Uint8Array;
367
+ }
368
+ function isReadable(body) {
369
+ return !isBufferLike(body);
370
+ }
371
+ function getBodySize(body) {
372
+ return isBufferLike(body) ? body.byteLength : void 0;
373
+ }
374
+ async function peekFirstBytes(body, maxBytes) {
375
+ if (isBufferLike(body)) {
376
+ const buf = Buffer.isBuffer(body) ? body : Buffer.from(body);
377
+ return { head: buf.subarray(0, maxBytes), replacementBody: buf };
378
+ }
379
+ return teeAndPeek(body, maxBytes);
380
+ }
381
+ async function teeAndPeek(source, maxBytes) {
382
+ const peekPT = new PassThrough();
383
+ const uploadPT = new PassThrough();
384
+ let peeked = 0;
385
+ let isPeekClosed = false;
386
+ const closePeek = () => {
387
+ if (!isPeekClosed) {
388
+ isPeekClosed = true;
389
+ peekPT.end();
390
+ }
391
+ };
392
+ source.on("data", (chunk) => {
393
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
394
+ if (peeked < maxBytes) {
395
+ const slice = buf.subarray(0, maxBytes - peeked);
396
+ peekPT.write(slice);
397
+ peeked += slice.byteLength;
398
+ if (peeked >= maxBytes) {
399
+ closePeek();
400
+ }
401
+ }
402
+ const hasCapacity = uploadPT.write(buf);
403
+ if (!hasCapacity && isPeekClosed) {
404
+ source.pause();
405
+ uploadPT.once("drain", () => source.resume());
406
+ }
407
+ });
408
+ source.on("end", () => {
409
+ closePeek();
410
+ uploadPT.end();
411
+ });
412
+ source.on("error", (err) => {
413
+ closePeek();
414
+ uploadPT.destroy(err);
415
+ });
416
+ const head = await collectStream(peekPT);
417
+ return { head, replacementBody: uploadPT };
418
+ }
419
+ async function collectStream(stream) {
420
+ const chunks = [];
421
+ for await (const chunk of stream) {
422
+ chunks.push(chunk);
423
+ }
424
+ return Buffer.concat(chunks);
425
+ }
426
+
427
+ // src/server/utils/mime-match.ts
428
+ function mimeMatches(mime, whitelist) {
429
+ if (typeof mime !== "string") {
430
+ return false;
431
+ }
432
+ const mimeBase = mime.includes(";") ? mime.slice(0, mime.indexOf(";")) : mime;
433
+ const normalized = mimeBase.trim().toLowerCase();
434
+ if (normalized.length === 0 || !normalized.includes("/")) {
435
+ return false;
436
+ }
437
+ const slashIdx = normalized.indexOf("/");
438
+ const type = normalized.slice(0, slashIdx);
439
+ for (const rawPattern of whitelist) {
440
+ const pattern = rawPattern.trim().toLowerCase();
441
+ if (pattern === normalized) {
442
+ return true;
443
+ }
444
+ if (pattern === "*/*") {
445
+ return true;
446
+ }
447
+ const patSlash = pattern.indexOf("/");
448
+ if (patSlash !== -1) {
449
+ const patType = pattern.slice(0, patSlash);
450
+ const patSubtype = pattern.slice(patSlash + 1);
451
+ if (patSubtype === "*" && patType === type) {
452
+ return true;
453
+ }
454
+ }
455
+ }
456
+ return false;
457
+ }
458
+
459
+ // src/server/services/validation.service.ts
460
+ var ValidationService = class {
461
+ constructor(options, validators) {
462
+ this.options = options;
463
+ this.validators = validators;
464
+ }
465
+ options;
466
+ validators;
467
+ /**
468
+ * Runs the upload validation pipeline in the canonical order:
469
+ * 1. MIME whitelist (when configured)
470
+ * 2. Size check (best-effort — skipped when `size` is absent)
471
+ * 3. Custom `IUploadValidator` chain (first rejection short-circuits)
472
+ *
473
+ * @param input - The upload options subset used for validation.
474
+ * @returns The validated body (possibly replaced via a tee'd stream).
475
+ * @throws StorageException `STORAGE_MIME_NOT_ALLOWED` on a MIME violation.
476
+ * @throws StorageException `STORAGE_SIZE_EXCEEDED` when `size > maxSizeBytes`.
477
+ * @throws StorageException `STORAGE_VALIDATION_FAILED` on a custom validator rejection.
478
+ */
479
+ async validate(input) {
480
+ this.checkMime(input.contentType);
481
+ this.checkSize(input.size);
482
+ const body = await this.runCustomValidators(input);
483
+ return { body };
484
+ }
485
+ /** Checks the MIME against the configured whitelist (no-op when absent or empty). */
486
+ checkMime(contentType) {
487
+ const whitelist = this.options.validation?.mimeWhitelist;
488
+ if (!whitelist || whitelist.length === 0) {
489
+ return;
490
+ }
491
+ if (!mimeMatches(contentType, whitelist)) {
492
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_MIME_NOT_ALLOWED, void 0, {
493
+ contentType,
494
+ whitelist
495
+ });
496
+ }
497
+ }
498
+ /** Best-effort size check — skipped when size is undefined. */
499
+ checkSize(size) {
500
+ const maxSizeBytes = this.options.validation?.maxSizeBytes;
501
+ if (maxSizeBytes === void 0 || size === void 0) {
502
+ return;
503
+ }
504
+ if (size > maxSizeBytes) {
505
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SIZE_EXCEEDED, void 0, {
506
+ size,
507
+ maxSize: maxSizeBytes
508
+ });
509
+ }
510
+ }
511
+ /**
512
+ * Runs the custom validator chain. When a validator calls `readBytes`, the
513
+ * body is tee'd and the replacement stream is propagated to subsequent
514
+ * validators and the final upload.
515
+ */
516
+ async runCustomValidators(input) {
517
+ let body = input.body;
518
+ for (const validator of this.validators) {
519
+ const readBytes = async (maxBytes) => {
520
+ const { head, replacementBody } = await peekFirstBytes(body, maxBytes);
521
+ body = replacementBody;
522
+ return head;
523
+ };
524
+ const result = await validator.validate({
525
+ key: input.key,
526
+ contentType: input.contentType,
527
+ ...input.size !== void 0 ? { size: input.size } : {},
528
+ ...input.metadata !== void 0 ? { metadata: input.metadata } : {},
529
+ readBytes
530
+ });
531
+ if (!result.ok) {
532
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
533
+ validator: validator.name,
534
+ reason: result.reason
535
+ });
536
+ }
537
+ }
538
+ return body;
539
+ }
540
+ };
541
+ ValidationService = __decorateClass([
542
+ Injectable(),
543
+ __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
544
+ __decorateParam(1, Inject(BYMAX_STORAGE_UPLOAD_VALIDATORS))
545
+ ], ValidationService);
546
+ var FileScannerService = class {
547
+ constructor(options, scanner) {
548
+ this.options = options;
549
+ this.scanner = scanner;
550
+ }
551
+ options;
552
+ scanner;
553
+ logger = new Logger(FileScannerService.name);
554
+ /**
555
+ * Returns `true` when both a scanner implementation and scanner options are
556
+ * configured.
557
+ *
558
+ * @returns `true` when scanning is active.
559
+ */
560
+ isEnabled() {
561
+ return this.scanner !== null && this.options.scanner !== void 0;
562
+ }
563
+ /**
564
+ * Returns the configured scan mode, or `null` when scanning is disabled.
565
+ *
566
+ * @returns `'pre-upload'`, `'post-upload'`, or `null`.
567
+ */
568
+ getMode() {
569
+ if (!this.isEnabled()) {
570
+ return null;
571
+ }
572
+ return this.options.scanner?.mode ?? "pre-upload";
573
+ }
574
+ /**
575
+ * Scans the given input. Callers MUST guard with `isEnabled()` — calling this
576
+ * method without a configured scanner is a programming error and throws a
577
+ * plain `Error`.
578
+ *
579
+ * Infected results throw `STORAGE_SCAN_INFECTED`. Inconclusive results throw
580
+ * `STORAGE_SCAN_INCONCLUSIVE` when `rejectOnUnknown` is set; otherwise they
581
+ * are returned with a warning log.
582
+ *
583
+ * @param input - The scan input.
584
+ * @returns The scan result when `status` is `'clean'` or `'unknown'` (non-rejecting).
585
+ * @throws Error when called without a configured scanner.
586
+ * @throws StorageException `STORAGE_SCAN_INFECTED` on an infected result.
587
+ * @throws StorageException `STORAGE_SCAN_INCONCLUSIVE` on an unknown result with `rejectOnUnknown`.
588
+ */
589
+ async scan(input) {
590
+ if (!this.scanner) {
591
+ throw new Error(
592
+ "FileScannerService.scan() called without a configured scanner \u2014 guard with isEnabled() first."
593
+ );
594
+ }
595
+ const result = await this.scanner.scan(input);
596
+ if (result.status === "infected") {
597
+ this.logger.warn(`Infected file detected: key=${input.key} engine=${result.engine} threat=${result.threat ?? "unknown"}`);
598
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INFECTED, void 0, {
599
+ engine: result.engine,
600
+ threat: result.threat,
601
+ details: result.details
602
+ });
603
+ }
604
+ if (result.status === "unknown") {
605
+ if (this.options.scanner?.rejectOnUnknown) {
606
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INCONCLUSIVE, void 0, {
607
+ engine: result.engine,
608
+ details: result.details
609
+ });
610
+ }
611
+ this.logger.warn(`Inconclusive scan result accepted: key=${input.key} engine=${result.engine}`);
612
+ }
613
+ return result;
614
+ }
615
+ };
616
+ FileScannerService = __decorateClass([
617
+ Injectable(),
618
+ __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
619
+ __decorateParam(1, Inject(BYMAX_STORAGE_FILE_SCANNER))
620
+ ], FileScannerService);
621
+ function mapAwsError(err, context) {
622
+ const e = err ?? {};
623
+ const httpStatus = e.$metadata?.httpStatusCode;
624
+ const awsCode = e.Code ?? e.name;
625
+ const requestId = e.$metadata?.requestId;
626
+ const details = {
627
+ ...context ?? {},
628
+ awsCode,
629
+ httpStatus,
630
+ requestId,
631
+ awsMessage: e.message
632
+ };
633
+ if (e.name === "NotFound" || httpStatus === 404) {
634
+ return new StorageException(
635
+ STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
636
+ HttpStatus.NOT_FOUND,
637
+ details
638
+ );
639
+ }
640
+ if (e.name === "TimeoutError") {
641
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, HttpStatus.GATEWAY_TIMEOUT, details);
642
+ }
643
+ return new StorageException(
644
+ STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR,
645
+ HttpStatus.BAD_GATEWAY,
646
+ details
647
+ );
648
+ }
649
+
650
+ // src/server/utils/header-utils.ts
651
+ function buildContentDisposition(perCall, defaultValue) {
652
+ return perCall ?? defaultValue;
653
+ }
654
+ function buildCacheControl(perCall, defaultValue) {
655
+ return perCall ?? defaultValue;
656
+ }
657
+ function buildSSE(perCall, perCallKmsKeyId, module) {
658
+ if (perCall === "NONE") {
659
+ return {};
660
+ }
661
+ const sse = perCall ?? module.serverSideEncryption;
662
+ if (!sse) {
663
+ return {};
664
+ }
665
+ if (sse === "aws:kms") {
666
+ const kmsKeyId = perCallKmsKeyId ?? module.kmsKeyId;
667
+ return kmsKeyId !== void 0 ? { ServerSideEncryption: "aws:kms", SSEKMSKeyId: kmsKeyId } : { ServerSideEncryption: "aws:kms" };
668
+ }
669
+ return { ServerSideEncryption: sse };
670
+ }
671
+ function buildACL(perCall, defaultValue) {
672
+ return perCall ?? defaultValue ? "public-read" : void 0;
673
+ }
674
+
675
+ // src/server/utils/upload-strategy.ts
676
+ function pickUploadStrategy(body, declaredSize, thresholdBytes) {
677
+ const size = declaredSize ?? getBodySize(body);
678
+ if (isReadable(body) && size === void 0) {
679
+ return "multipart";
680
+ }
681
+ if (size !== void 0 && size >= thresholdBytes) {
682
+ return "multipart";
683
+ }
684
+ return "single-shot";
685
+ }
686
+
687
+ // src/server/services/storage.service.ts
688
+ var MAX_LIST_KEYS = 1e3;
689
+ var DELETE_BATCH_LIMIT = 1e3;
690
+ var StorageService = class {
691
+ constructor(options, s3Provider, keyResolver, idempotencyCache, validation, scanner) {
692
+ this.options = options;
693
+ this.s3Provider = s3Provider;
694
+ this.keyResolver = keyResolver;
695
+ this.idempotencyCache = idempotencyCache;
696
+ this.validation = validation;
697
+ this.scanner = scanner;
698
+ }
699
+ options;
700
+ s3Provider;
701
+ keyResolver;
702
+ idempotencyCache;
703
+ validation;
704
+ scanner;
705
+ logger = new Logger(StorageService.name);
706
+ /**
707
+ * Uploads an object, choosing single-shot or multipart automatically. When an
708
+ * `idempotencyKey` is supplied and a matching result is cached within the TTL
709
+ * window, the cached result is returned without re-uploading.
710
+ *
711
+ * @param options - The upload request.
712
+ * @returns The upload result.
713
+ * @throws StorageException for missing configuration, body, or content type.
714
+ */
715
+ async upload(options) {
716
+ this.assertConfigured();
717
+ const rawBody = options.body;
718
+ if (rawBody === void 0 || rawBody === null) {
719
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BODY_MISSING);
720
+ }
721
+ if (!options.contentType) {
722
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_CONTENT_TYPE_REQUIRED);
723
+ }
724
+ const finalKey = this.keyResolver.normalize(options.key);
725
+ const bucket = this.resolveBucket(options.bucket);
726
+ if (options.idempotencyKey) {
727
+ const cacheKey = this.idempotencyCache.computeKey(options.idempotencyKey, finalKey);
728
+ const cached = this.idempotencyCache.get(cacheKey);
729
+ if (cached) {
730
+ return { ...cached, fromIdempotencyCache: true };
731
+ }
732
+ }
733
+ const validated = await this.validation.validate({
734
+ key: finalKey,
735
+ body: options.body,
736
+ contentType: options.contentType,
737
+ ...options.size !== void 0 ? { size: options.size } : {},
738
+ ...options.metadata !== void 0 ? { metadata: options.metadata } : {}
739
+ });
740
+ const validatedOptions = { ...options, body: validated.body };
741
+ await this.runPreUploadScan(validated.body, finalKey, bucket, options);
742
+ const strategy = pickUploadStrategy(
743
+ validatedOptions.body,
744
+ validatedOptions.size,
745
+ this.options.multipart.thresholdBytes
746
+ );
747
+ const result = strategy === "multipart" ? await this.uploadMultipart(validatedOptions, finalKey, bucket) : await this.uploadSingleShot(validatedOptions, finalKey, bucket);
748
+ await this.runPostUploadScan(finalKey, bucket, options);
749
+ if (options.idempotencyKey) {
750
+ this.idempotencyCache.set(
751
+ this.idempotencyCache.computeKey(options.idempotencyKey, finalKey),
752
+ result
753
+ );
754
+ }
755
+ return result;
756
+ }
757
+ /** Runs a pre-upload scan when configured; throws on infected. */
758
+ async runPreUploadScan(body, finalKey, bucket, options) {
759
+ if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload") {
760
+ return;
761
+ }
762
+ await this.scanner.scan({
763
+ mode: "pre-upload",
764
+ body: this.normalizeScanBody(body),
765
+ key: finalKey,
766
+ bucket,
767
+ contentType: options.contentType,
768
+ ...options.size !== void 0 ? { size: options.size } : {}
769
+ });
770
+ }
771
+ /**
772
+ * Coerces a buffer-like scan body (`Buffer` or `Uint8Array`) to a `Buffer` so
773
+ * the scanner always receives its declared contract type; streams pass through
774
+ * unchanged.
775
+ */
776
+ normalizeScanBody(body) {
777
+ if (isBufferLike(body)) {
778
+ return Buffer.isBuffer(body) ? body : Buffer.from(body);
779
+ }
780
+ return body;
781
+ }
782
+ /**
783
+ * Runs a post-upload scan. On infection, deletes the just-uploaded object
784
+ * (logging delete failures as errors) and re-throws the scan exception.
785
+ */
786
+ async runPostUploadScan(finalKey, bucket, options) {
787
+ if (!this.scanner.isEnabled() || this.scanner.getMode() !== "post-upload") {
788
+ return;
789
+ }
790
+ try {
791
+ await this.scanner.scan({
792
+ mode: "post-upload",
793
+ key: finalKey,
794
+ bucket,
795
+ contentType: options.contentType,
796
+ ...options.size !== void 0 ? { size: options.size } : {}
797
+ });
798
+ } catch (scanErr) {
799
+ await this.delete(finalKey, { bucket }).catch((deleteErr) => {
800
+ this.logger.error(
801
+ `Post-upload cleanup failed for infected/inconclusive object: ${finalKey}`,
802
+ deleteErr.message
803
+ );
804
+ });
805
+ throw scanErr;
806
+ }
807
+ }
808
+ /**
809
+ * Returns metadata for an object without downloading its body.
810
+ *
811
+ * @param key - The raw object key (normalized internally).
812
+ * @param options - Optional per-call bucket override.
813
+ * @returns The object metadata.
814
+ * @throws StorageException `STORAGE_OBJECT_NOT_FOUND` when the key is absent.
815
+ */
816
+ async head(key, options) {
817
+ this.assertConfigured();
818
+ const finalKey = this.keyResolver.normalize(key);
819
+ const bucket = this.resolveBucket(options?.bucket);
820
+ try {
821
+ const response = await this.s3Provider.getClient().send(new HeadObjectCommand({ Bucket: bucket, Key: finalKey }));
822
+ return this.toObjectMetadata(response, finalKey, bucket);
823
+ } catch (err) {
824
+ throw mapAwsError(err, { key: finalKey, bucket, op: "head" });
825
+ }
826
+ }
827
+ /**
828
+ * Best-effort existence check. Returns `false` for a missing object and, to
829
+ * stay non-throwing, also `false` (with a warning) for any other error.
830
+ *
831
+ * @param key - The raw object key.
832
+ * @param options - Optional per-call bucket override.
833
+ * @returns `true` when the object exists, `false` otherwise.
834
+ */
835
+ async exists(key, options) {
836
+ try {
837
+ await this.head(key, options);
838
+ return true;
839
+ } catch (err) {
840
+ if (err instanceof StorageException && err.code === STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND) {
841
+ return false;
842
+ }
843
+ this.logger.warn(`exists() \u2014 treating a non-404 error as "false": ${err.message}`);
844
+ return false;
845
+ }
846
+ }
847
+ /**
848
+ * Builds the public URL for an object. Not validated against the bucket policy
849
+ * — public delivery depends on the bucket allowing anonymous reads or a CDN.
850
+ *
851
+ * @param key - The raw object key.
852
+ * @param options - Optional per-call bucket override.
853
+ * @returns The public URL.
854
+ */
855
+ getPublicUrl(key, options) {
856
+ const finalKey = this.keyResolver.normalize(key);
857
+ const bucket = this.resolveBucket(options?.bucket);
858
+ return this.buildPublicUrl(finalKey, bucket);
859
+ }
860
+ /**
861
+ * Streams an object. The returned `stream` is a Node `Readable` consumable via
862
+ * `for await` or `.pipe()`. `range` / `ifNoneMatch` / `ifMatch` are forwarded as
863
+ * conditional/partial GET headers.
864
+ *
865
+ * @param options - The download request.
866
+ * @returns The object stream and its metadata.
867
+ * @throws StorageException `STORAGE_OBJECT_NOT_FOUND` when the body is absent.
868
+ */
869
+ async download(options) {
870
+ this.assertConfigured();
871
+ const finalKey = this.keyResolver.normalize(options.key);
872
+ const bucket = this.resolveBucket(options.bucket);
873
+ try {
874
+ const response = await this.s3Provider.getClient().send(
875
+ new GetObjectCommand({
876
+ Bucket: bucket,
877
+ Key: finalKey,
878
+ Range: options.range,
879
+ IfNoneMatch: options.ifNoneMatch,
880
+ IfMatch: options.ifMatch
881
+ })
882
+ );
883
+ if (!response.Body) {
884
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND, void 0, {
885
+ key: finalKey,
886
+ bucket
887
+ });
888
+ }
889
+ const stream = response.Body;
890
+ return { stream, metadata: this.toObjectMetadata(response, finalKey, bucket) };
891
+ } catch (err) {
892
+ if (err instanceof StorageException) {
893
+ throw err;
894
+ }
895
+ throw mapAwsError(err, { key: finalKey, bucket, op: "download" });
896
+ }
897
+ }
898
+ /**
899
+ * Materializes an object fully into memory via the sdk-stream-mixin. NOT
900
+ * recommended for files larger than 10 MB — use {@link download} for those.
901
+ *
902
+ * @param options - The download request.
903
+ * @returns The object buffer and its metadata.
904
+ */
905
+ async downloadBuffer(options) {
906
+ const { stream, metadata } = await this.download(options);
907
+ const bytes = await stream.transformToByteArray();
908
+ return { buffer: Buffer.from(bytes), metadata };
909
+ }
910
+ /**
911
+ * Deletes an object. Idempotent: a missing object is a no-op (logged as a
912
+ * warning), not an error. Any other failure is propagated.
913
+ *
914
+ * @param key - The raw object key.
915
+ * @param options - Optional per-call bucket override.
916
+ */
917
+ async delete(key, options) {
918
+ this.assertConfigured();
919
+ const finalKey = this.keyResolver.normalize(key);
920
+ const bucket = this.resolveBucket(options?.bucket);
921
+ try {
922
+ await this.s3Provider.getClient().send(new DeleteObjectCommand({ Bucket: bucket, Key: finalKey }));
923
+ } catch (err) {
924
+ const mapped = mapAwsError(err, { key: finalKey, bucket, op: "delete" });
925
+ if (mapped.code === STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND) {
926
+ this.logger.warn(`delete() \u2014 key not found (idempotent no-op): ${finalKey}`);
927
+ return;
928
+ }
929
+ throw mapped;
930
+ }
931
+ }
932
+ /** Throws when the S3 client was never built (missing credentials). */
933
+ assertConfigured() {
934
+ if (!this.s3Provider.isConfigured()) {
935
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED);
936
+ }
937
+ }
938
+ /** Resolves the target bucket from a per-call override or the module default. */
939
+ resolveBucket(perCall) {
940
+ const bucket = perCall ?? this.options.bucket;
941
+ if (!bucket) {
942
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
943
+ }
944
+ return bucket;
945
+ }
946
+ /** Builds a public URL, avoiding a duplicated bucket segment in the base. */
947
+ buildPublicUrl(finalKey, bucket) {
948
+ const base = trimTrailingSlashes(this.options.cdnBaseUrl ?? this.options.publicBaseUrl);
949
+ return this.baseCarriesBucket(base, bucket) ? `${base}/${finalKey}` : `${base}/${bucket}/${finalKey}`;
950
+ }
951
+ /**
952
+ * Reports whether the base URL already carries the bucket as a real segment —
953
+ * the leading host label (virtual-hosted-style `bucket.host`) or a path segment
954
+ * (path-style `/bucket` or `/bucket/…`) — rather than an incidental substring,
955
+ * so `bucket="test"` is not matched by a `latest` elsewhere in the base.
956
+ */
957
+ baseCarriesBucket(base, bucket) {
958
+ const schemeless = base.replace(/^[a-z][a-z\d+.-]*:\/\//i, "");
959
+ const pathStart = schemeless.indexOf("/");
960
+ const authority = pathStart === -1 ? schemeless : schemeless.slice(0, pathStart);
961
+ const path = pathStart === -1 ? "" : schemeless.slice(pathStart);
962
+ const leadingHostLabel = authority.split(".")[0];
963
+ const pathSegments = path.split("/").filter((segment) => segment.length > 0);
964
+ return leadingHostLabel === bucket || pathSegments.includes(bucket);
965
+ }
966
+ /** Maps an S3 metadata response onto the public `ObjectMetadata` shape. */
967
+ toObjectMetadata(response, finalKey, bucket) {
968
+ return {
969
+ key: finalKey,
970
+ bucket,
971
+ size: response.ContentLength ?? 0,
972
+ contentType: response.ContentType ?? "application/octet-stream",
973
+ etag: response.ETag ?? "",
974
+ lastModified: response.LastModified ?? /* @__PURE__ */ new Date(0),
975
+ metadata: response.Metadata ?? {},
976
+ ...response.CacheControl !== void 0 ? { cacheControl: response.CacheControl } : {},
977
+ ...response.ContentDisposition !== void 0 ? { contentDisposition: response.ContentDisposition } : {},
978
+ ...response.StorageClass !== void 0 ? { storageClass: response.StorageClass } : {},
979
+ ...response.VersionId !== void 0 ? { versionId: response.VersionId } : {}
980
+ };
981
+ }
982
+ /** Single `PutObject` upload for bodies below the multipart threshold. */
983
+ async uploadSingleShot(options, finalKey, bucket) {
984
+ const total = options.size ?? getBodySize(options.body);
985
+ const input = {
986
+ Bucket: bucket,
987
+ Key: finalKey,
988
+ Body: this.normalizeSingleShotBody(options.body),
989
+ ContentType: options.contentType,
990
+ ContentLength: total,
991
+ CacheControl: buildCacheControl(options.cacheControl, this.options.defaultCacheControl),
992
+ ContentDisposition: buildContentDisposition(
993
+ options.contentDisposition,
994
+ this.options.defaultContentDisposition
995
+ ),
996
+ // `public-read` only takes effect on buckets that allow ACLs (see header-utils).
997
+ ACL: buildACL(options.publicRead, this.options.defaultPublicRead),
998
+ Metadata: options.metadata,
999
+ ...buildSSE(options.serverSideEncryption, options.kmsKeyId, this.options)
1000
+ };
1001
+ try {
1002
+ const response = await this.s3Provider.getClient().send(new PutObjectCommand(input));
1003
+ if (options.onProgress) {
1004
+ this.emitProgress(options.onProgress, total, total);
1005
+ }
1006
+ return this.buildUploadResult({
1007
+ finalKey,
1008
+ bucket,
1009
+ etag: response.ETag,
1010
+ versionId: response.VersionId,
1011
+ size: total,
1012
+ contentType: options.contentType,
1013
+ multipart: false
1014
+ });
1015
+ } catch (err) {
1016
+ throw mapAwsError(err, { key: finalKey, bucket, op: "upload-single" });
1017
+ }
1018
+ }
1019
+ /**
1020
+ * Multipart upload via `@aws-sdk/lib-storage`. `leavePartsOnError: false` makes
1021
+ * the SDK abort and clean up parts on failure, so no manual abort is issued.
1022
+ */
1023
+ async uploadMultipart(options, finalKey, bucket) {
1024
+ const params = {
1025
+ Bucket: bucket,
1026
+ Key: finalKey,
1027
+ Body: options.body,
1028
+ ContentType: options.contentType,
1029
+ CacheControl: buildCacheControl(options.cacheControl, this.options.defaultCacheControl),
1030
+ ContentDisposition: buildContentDisposition(
1031
+ options.contentDisposition,
1032
+ this.options.defaultContentDisposition
1033
+ ),
1034
+ ACL: buildACL(options.publicRead, this.options.defaultPublicRead),
1035
+ Metadata: options.metadata,
1036
+ ...buildSSE(options.serverSideEncryption, options.kmsKeyId, this.options)
1037
+ };
1038
+ const uploader = new Upload({
1039
+ client: this.s3Provider.getClient(),
1040
+ params,
1041
+ queueSize: this.options.multipart.queueSize,
1042
+ partSize: this.options.multipart.partSizeBytes,
1043
+ leavePartsOnError: false
1044
+ });
1045
+ if (options.onProgress) {
1046
+ const onProgress = options.onProgress;
1047
+ uploader.on("httpUploadProgress", (event) => {
1048
+ this.emitProgress(onProgress, event.loaded, event.total, event.part);
1049
+ });
1050
+ }
1051
+ try {
1052
+ const response = await uploader.done();
1053
+ return this.buildUploadResult({
1054
+ finalKey,
1055
+ bucket,
1056
+ etag: response.ETag,
1057
+ versionId: response.VersionId,
1058
+ size: options.size,
1059
+ contentType: options.contentType,
1060
+ multipart: true
1061
+ });
1062
+ } catch (err) {
1063
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED, void 0, {
1064
+ key: finalKey,
1065
+ bucket,
1066
+ awsMessage: err.message
1067
+ });
1068
+ }
1069
+ }
1070
+ /** Converts a `Uint8Array` body to a `Buffer` for SDK safety; passes others through. */
1071
+ normalizeSingleShotBody(body) {
1072
+ if (isBufferLike(body)) {
1073
+ return Buffer.isBuffer(body) ? body : Buffer.from(body);
1074
+ }
1075
+ return body;
1076
+ }
1077
+ /** Assembles an `UploadResult`, omitting optional fields that are absent. */
1078
+ buildUploadResult(params) {
1079
+ return {
1080
+ key: params.finalKey,
1081
+ bucket: params.bucket,
1082
+ etag: params.etag ?? "",
1083
+ contentType: params.contentType,
1084
+ publicUrl: this.buildPublicUrl(params.finalKey, params.bucket),
1085
+ multipart: params.multipart,
1086
+ fromIdempotencyCache: false,
1087
+ ...params.size !== void 0 ? { size: params.size } : {},
1088
+ ...params.versionId !== void 0 ? { versionId: params.versionId } : {}
1089
+ };
1090
+ }
1091
+ /** Emits a progress event, omitting `total`/`part` when they are unknown. */
1092
+ emitProgress(onProgress, loaded, total, part) {
1093
+ onProgress({
1094
+ loaded: loaded ?? 0,
1095
+ ...total !== void 0 ? { total } : {},
1096
+ ...part !== void 0 ? { part } : {}
1097
+ });
1098
+ }
1099
+ /**
1100
+ * Lists objects in the bucket as a single page. Applies the global key prefix
1101
+ * to the caller's `prefix`, caps `maxKeys` at the S3 hard limit of 1000, threads
1102
+ * the continuation token, and strips the global prefix from every returned key.
1103
+ *
1104
+ * @param options - The listing request.
1105
+ * @returns One page of objects plus `commonPrefixes`, truncation, and the next token.
1106
+ * @throws StorageException mapped from any AWS failure.
1107
+ */
1108
+ async list(options) {
1109
+ this.assertConfigured();
1110
+ const bucket = this.resolveBucket(options.bucket);
1111
+ const maxKeys = Math.min(options.maxKeys ?? MAX_LIST_KEYS, MAX_LIST_KEYS);
1112
+ const prefix = options.prefix ? this.keyResolver.normalize(options.prefix) : this.keyResolver.getPrefix();
1113
+ try {
1114
+ const response = await this.s3Provider.getClient().send(
1115
+ new ListObjectsV2Command({
1116
+ Bucket: bucket,
1117
+ Prefix: prefix,
1118
+ MaxKeys: maxKeys,
1119
+ ContinuationToken: options.continuationToken,
1120
+ Delimiter: options.delimiter
1121
+ })
1122
+ );
1123
+ return this.toListResult(response);
1124
+ } catch (err) {
1125
+ throw mapAwsError(err, { bucket, prefix, op: "list" });
1126
+ }
1127
+ }
1128
+ /** Maps a `ListObjectsV2` response onto the public `ListResult` shape. */
1129
+ toListResult(response) {
1130
+ const objects = (response.Contents ?? []).map((obj) => this.toListedObject(obj));
1131
+ const commonPrefixes = (response.CommonPrefixes ?? []).map((cp) => cp.Prefix ?? "").filter((cp) => cp.length > 0).map((cp) => this.keyResolver.stripPrefix(cp));
1132
+ return {
1133
+ objects,
1134
+ commonPrefixes,
1135
+ isTruncated: response.IsTruncated ?? false,
1136
+ ...response.NextContinuationToken !== void 0 ? { nextContinuationToken: response.NextContinuationToken } : {}
1137
+ };
1138
+ }
1139
+ /** Maps one `Contents` entry onto `ListedObject`, stripping the global prefix. */
1140
+ toListedObject(obj) {
1141
+ return {
1142
+ key: this.keyResolver.stripPrefix(obj.Key ?? ""),
1143
+ size: obj.Size ?? 0,
1144
+ etag: obj.ETag ?? "",
1145
+ lastModified: obj.LastModified ?? /* @__PURE__ */ new Date(0),
1146
+ ...obj.StorageClass !== void 0 ? { storageClass: obj.StorageClass } : {}
1147
+ };
1148
+ }
1149
+ /**
1150
+ * Server-side copy of an object (no bytes flow through the app). Supports both
1151
+ * same-bucket and cross-bucket copies and preserves the source metadata.
1152
+ *
1153
+ * @param options - Source/destination keys and buckets plus copy overrides.
1154
+ * @returns The new object's ETag.
1155
+ * @throws StorageException mapped from any AWS failure.
1156
+ */
1157
+ async copy(options) {
1158
+ this.assertConfigured();
1159
+ const sourceKey = this.keyResolver.normalize(options.sourceKey);
1160
+ const destKey = this.keyResolver.normalize(options.destinationKey);
1161
+ const sourceBucket = this.resolveBucket(options.sourceBucket);
1162
+ const destBucket = this.resolveBucket(options.destinationBucket);
1163
+ try {
1164
+ const response = await this.s3Provider.getClient().send(
1165
+ new CopyObjectCommand({
1166
+ Bucket: destBucket,
1167
+ Key: destKey,
1168
+ // `CopySource` must be URL-encoded per path segment; the slashes that
1169
+ // separate the segments stay literal so the bucket/key boundaries hold.
1170
+ CopySource: `/${sourceBucket}/${sourceKey.split("/").map(encodeURIComponent).join("/")}`,
1171
+ CacheControl: options.cacheControl ?? this.options.defaultCacheControl,
1172
+ // ACLs are a no-op on modern S3 (Object Ownership) and R2; see header-utils.
1173
+ ACL: buildACL(options.publicRead, this.options.defaultPublicRead),
1174
+ MetadataDirective: "COPY"
1175
+ })
1176
+ );
1177
+ return { etag: response.CopyObjectResult?.ETag ?? "" };
1178
+ } catch (err) {
1179
+ throw mapAwsError(err, { sourceKey, destKey, op: "copy" });
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Deletes many objects, chunking the input at the S3 hard limit of 1000 keys
1184
+ * per request. Reports both successes and per-key failures; a whole-chunk send
1185
+ * failure marks every key in that chunk as failed. Returned keys are stripped of
1186
+ * the global prefix.
1187
+ *
1188
+ * @param keys - The raw object keys to delete.
1189
+ * @param options - Optional per-call bucket override.
1190
+ * @returns The deleted keys and the per-key failures.
1191
+ */
1192
+ async deleteMany(keys, options) {
1193
+ this.assertConfigured();
1194
+ if (keys.length === 0) {
1195
+ return { deleted: [], failed: [] };
1196
+ }
1197
+ const bucket = this.resolveBucket(options?.bucket);
1198
+ const normalized = keys.map((key) => this.keyResolver.normalize(key));
1199
+ const deleted = [];
1200
+ const failed = [];
1201
+ for (let i = 0; i < normalized.length; i += DELETE_BATCH_LIMIT) {
1202
+ const chunk = normalized.slice(i, i + DELETE_BATCH_LIMIT);
1203
+ const outcome = await this.deleteChunk(bucket, chunk);
1204
+ deleted.push(...outcome.deleted);
1205
+ failed.push(...outcome.failed);
1206
+ }
1207
+ return { deleted, failed };
1208
+ }
1209
+ /** Deletes one chunk (≤ 1000 keys); a whole-chunk failure fails every key. */
1210
+ async deleteChunk(bucket, chunk) {
1211
+ const deleted = [];
1212
+ const failed = [];
1213
+ try {
1214
+ const response = await this.s3Provider.getClient().send(
1215
+ new DeleteObjectsCommand({
1216
+ Bucket: bucket,
1217
+ // `Quiet: false` returns both successes and per-key errors.
1218
+ Delete: { Objects: chunk.map((key) => ({ Key: key })), Quiet: false }
1219
+ })
1220
+ );
1221
+ for (const ok of response.Deleted ?? []) {
1222
+ if (ok.Key !== void 0) {
1223
+ deleted.push(this.keyResolver.stripPrefix(ok.Key));
1224
+ }
1225
+ }
1226
+ for (const failure of response.Errors ?? []) {
1227
+ if (failure.Key !== void 0) {
1228
+ failed.push({
1229
+ key: this.keyResolver.stripPrefix(failure.Key),
1230
+ error: `${failure.Code ?? "Unknown"}: ${failure.Message ?? ""}`
1231
+ });
1232
+ }
1233
+ }
1234
+ } catch (err) {
1235
+ const message = err instanceof Error ? err.message : String(err);
1236
+ for (const key of chunk) {
1237
+ failed.push({ key: this.keyResolver.stripPrefix(key), error: message });
1238
+ }
1239
+ }
1240
+ return { deleted, failed };
1241
+ }
1242
+ };
1243
+ StorageService = __decorateClass([
1244
+ Injectable(),
1245
+ __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
1246
+ __decorateParam(1, Inject(S3ClientProvider)),
1247
+ __decorateParam(2, Inject(KeyResolverService)),
1248
+ __decorateParam(3, Inject(BYMAX_STORAGE_IDEMPOTENCY_CACHE)),
1249
+ __decorateParam(4, Inject(ValidationService)),
1250
+ __decorateParam(5, Inject(FileScannerService))
1251
+ ], StorageService);
1252
+
1253
+ // src/server/utils/ttl-clamp.ts
1254
+ function clampTtl(ttlSeconds, defaultTtl, maxTtl) {
1255
+ const ttl = ttlSeconds ?? defaultTtl;
1256
+ if (ttl <= 0) {
1257
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SIGNED_URL_TTL_INVALID, void 0, {
1258
+ reason: "TTL must be > 0",
1259
+ provided: ttl
1260
+ });
1261
+ }
1262
+ return Math.min(ttl, maxTtl);
1263
+ }
1264
+
1265
+ // src/server/services/signed-url.service.ts
1266
+ var SignedUrlService = class {
1267
+ constructor(options, s3Provider, keyResolver) {
1268
+ this.options = options;
1269
+ this.s3Provider = s3Provider;
1270
+ this.keyResolver = keyResolver;
1271
+ }
1272
+ options;
1273
+ s3Provider;
1274
+ keyResolver;
1275
+ /**
1276
+ * Issues a presigned GET URL for downloading an object.
1277
+ *
1278
+ * SECURITY: The returned URL is a temporary credential. NEVER log it, store it
1279
+ * in a database, or cache it across users. Issue a fresh URL per request.
1280
+ *
1281
+ * @param options - The download URL options.
1282
+ * @returns The presigned URL and its expiry metadata.
1283
+ * @throws StorageException `STORAGE_NOT_CONFIGURED` when the client is absent.
1284
+ * @throws StorageException `STORAGE_SIGNED_URL_TTL_INVALID` for non-positive TTL.
1285
+ */
1286
+ async getDownloadUrl(options) {
1287
+ this.assertConfigured();
1288
+ const finalKey = this.keyResolver.normalize(options.key);
1289
+ const bucket = this.resolveBucket(options.bucket);
1290
+ const ttl = clampTtl(
1291
+ options.ttlSeconds,
1292
+ this.options.signedUrls.defaultGetTtlSeconds,
1293
+ this.options.signedUrls.maxTtlSeconds
1294
+ );
1295
+ try {
1296
+ const command = new GetObjectCommand({
1297
+ Bucket: bucket,
1298
+ Key: finalKey,
1299
+ ...options.responseContentDisposition !== void 0 ? { ResponseContentDisposition: options.responseContentDisposition } : {},
1300
+ ...options.responseContentType !== void 0 ? { ResponseContentType: options.responseContentType } : {}
1301
+ });
1302
+ const url = await getSignedUrl(this.s3Provider.getClient(), command, { expiresIn: ttl });
1303
+ return { url, expiresAt: new Date(Date.now() + ttl * 1e3), method: "GET", requiredHeaders: {} };
1304
+ } catch (err) {
1305
+ if (err instanceof StorageException) throw err;
1306
+ throw mapAwsError(err, { key: finalKey, bucket, op: "getDownloadUrl" });
1307
+ }
1308
+ }
1309
+ /**
1310
+ * Issues a presigned PUT URL for uploading an object. The client MUST send
1311
+ * every header listed in `requiredHeaders` verbatim — each one is part of the
1312
+ * URL signature, so an omitted header yields `SignatureDoesNotMatch`. The map
1313
+ * always carries `Content-Type` and additionally lists `x-amz-acl` when an ACL
1314
+ * is signed and an `x-amz-meta-<key>` entry per metadata pair.
1315
+ *
1316
+ * SECURITY: The returned URL is a temporary credential — NEVER log it. A signed
1317
+ * PUT bypasses the server-side MIME/size validation pipeline. Size limits are
1318
+ * NOT enforced at presign time: a SigV4 PUT signature can only pin an exact
1319
+ * `Content-Length`, never a maximum, so binding one would reject valid smaller
1320
+ * uploads. Enforce size after the fact via a post-upload HEAD/size check plus
1321
+ * the post-upload scanner path for defence-in-depth.
1322
+ *
1323
+ * ACL caveat: `publicRead` emits `ACL: public-read`, which returns HTTP 400
1324
+ * `AccessControlListNotSupported` on modern AWS S3 buckets (Object Ownership
1325
+ * = "Bucket owner enforced") and is a no-op on Cloudflare R2. Prefer a bucket
1326
+ * policy, CDN, or signed GET URL for public delivery.
1327
+ *
1328
+ * @param options - The upload URL options.
1329
+ * @returns The presigned URL, its expiry metadata, and required headers.
1330
+ * @throws StorageException `STORAGE_NOT_CONFIGURED` when the client is absent.
1331
+ * @throws StorageException `STORAGE_SIGNED_URL_TTL_INVALID` for non-positive TTL.
1332
+ */
1333
+ async getUploadUrl(options) {
1334
+ this.assertConfigured();
1335
+ const finalKey = this.keyResolver.normalize(options.key);
1336
+ const bucket = this.resolveBucket(options.bucket);
1337
+ const ttl = clampTtl(
1338
+ options.ttlSeconds,
1339
+ this.options.signedUrls.defaultPutTtlSeconds,
1340
+ this.options.signedUrls.maxTtlSeconds
1341
+ );
1342
+ try {
1343
+ const acl = buildACL(options.publicRead, this.options.defaultPublicRead);
1344
+ const command = new PutObjectCommand({
1345
+ Bucket: bucket,
1346
+ Key: finalKey,
1347
+ ContentType: options.contentType,
1348
+ ACL: acl,
1349
+ ...options.metadata !== void 0 ? { Metadata: options.metadata } : {}
1350
+ });
1351
+ const url = await getSignedUrl(this.s3Provider.getClient(), command, { expiresIn: ttl });
1352
+ return {
1353
+ url,
1354
+ expiresAt: new Date(Date.now() + ttl * 1e3),
1355
+ method: "PUT",
1356
+ requiredHeaders: this.buildPutRequiredHeaders(options, acl)
1357
+ };
1358
+ } catch (err) {
1359
+ if (err instanceof StorageException) throw err;
1360
+ throw mapAwsError(err, { key: finalKey, bucket, op: "getUploadUrl" });
1361
+ }
1362
+ }
1363
+ /**
1364
+ * Builds the set of headers a client MUST send for a signed PUT, mirroring the
1365
+ * headers folded into the SigV4 signature. Always includes `Content-Type`; adds
1366
+ * `x-amz-acl` when an ACL is signed and an `x-amz-meta-<key>` entry (key
1367
+ * lowercased to match SigV4 canonicalisation) for every metadata pair.
1368
+ */
1369
+ buildPutRequiredHeaders(options, acl) {
1370
+ const headers = { "Content-Type": options.contentType };
1371
+ if (acl !== void 0) {
1372
+ headers["x-amz-acl"] = acl;
1373
+ }
1374
+ if (options.metadata !== void 0) {
1375
+ for (const [key, value] of Object.entries(options.metadata)) {
1376
+ headers[`x-amz-meta-${key.toLowerCase()}`] = value;
1377
+ }
1378
+ }
1379
+ return headers;
1380
+ }
1381
+ /**
1382
+ * Presigns a multipart upload: creates the upload session on S3, then returns
1383
+ * N presigned `UploadPart` URLs (1-indexed) and a presigned `CompleteMultipart`
1384
+ * URL. The client uploads parts directly to S3 and then calls the complete URL.
1385
+ *
1386
+ * SECURITY: All returned URLs are temporary credentials — NEVER log them.
1387
+ *
1388
+ * @param options - The multipart URL options.
1389
+ * @returns `uploadId`, `partUrls`, and `completeUrl`.
1390
+ * @throws StorageException `STORAGE_NOT_CONFIGURED` when the client is absent.
1391
+ * @throws StorageException `STORAGE_SIGNED_URL_TTL_INVALID` for non-positive TTL.
1392
+ * @throws StorageException `STORAGE_PROVIDER_ERROR` when no `UploadId` is returned.
1393
+ */
1394
+ async getMultipartUploadUrls(options) {
1395
+ this.assertConfigured();
1396
+ if (options.parts <= 0) {
1397
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT, void 0, {
1398
+ reason: "parts must be a positive integer",
1399
+ provided: options.parts
1400
+ });
1401
+ }
1402
+ const finalKey = this.keyResolver.normalize(options.key);
1403
+ const bucket = this.resolveBucket(options.bucket);
1404
+ const ttl = clampTtl(
1405
+ options.ttlSeconds,
1406
+ this.options.signedUrls.defaultPutTtlSeconds,
1407
+ this.options.signedUrls.maxTtlSeconds
1408
+ );
1409
+ try {
1410
+ const createCmd = new CreateMultipartUploadCommand({
1411
+ Bucket: bucket,
1412
+ Key: finalKey,
1413
+ ContentType: options.contentType
1414
+ });
1415
+ const createResp = await this.s3Provider.getClient().send(createCmd);
1416
+ const uploadId = createResp.UploadId;
1417
+ if (!uploadId) {
1418
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR, void 0, {
1419
+ reason: "CreateMultipartUpload returned no UploadId",
1420
+ key: finalKey,
1421
+ bucket
1422
+ });
1423
+ }
1424
+ return await this.presignMultipartParts({ finalKey, bucket, uploadId, parts: options.parts, ttl });
1425
+ } catch (err) {
1426
+ if (err instanceof StorageException) throw err;
1427
+ throw mapAwsError(err, { key: finalKey, bucket, op: "getMultipartUploadUrls" });
1428
+ }
1429
+ }
1430
+ /** Presigns all part URLs and the complete URL in parallel. */
1431
+ async presignMultipartParts(params) {
1432
+ const { finalKey, bucket, uploadId, parts, ttl } = params;
1433
+ const client = this.s3Provider.getClient();
1434
+ const opts = { expiresIn: ttl };
1435
+ const partNums = Array.from({ length: parts }, (_, i) => i + 1);
1436
+ const partUrls = await Promise.all(
1437
+ partNums.map(async (partNumber) => {
1438
+ const cmd = new UploadPartCommand({ Bucket: bucket, Key: finalKey, UploadId: uploadId, PartNumber: partNumber });
1439
+ const url = await getSignedUrl(client, cmd, opts);
1440
+ return { partNumber, url };
1441
+ })
1442
+ );
1443
+ const completeCmd = new CompleteMultipartUploadCommand({ Bucket: bucket, Key: finalKey, UploadId: uploadId });
1444
+ const completeUrl = await getSignedUrl(client, completeCmd, opts);
1445
+ return { uploadId, partUrls, completeUrl };
1446
+ }
1447
+ /** Throws when the S3 client was never built (missing credentials). */
1448
+ assertConfigured() {
1449
+ if (!this.s3Provider.isConfigured()) {
1450
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED);
1451
+ }
1452
+ }
1453
+ /** Resolves the target bucket from a per-call override or the module default. */
1454
+ resolveBucket(perCall) {
1455
+ const bucket = perCall ?? this.options.bucket;
1456
+ if (!bucket) {
1457
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
1458
+ }
1459
+ return bucket;
1460
+ }
1461
+ };
1462
+ SignedUrlService = __decorateClass([
1463
+ Injectable(),
1464
+ __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
1465
+ __decorateParam(1, Inject(S3ClientProvider)),
1466
+ __decorateParam(2, Inject(KeyResolverService))
1467
+ ], SignedUrlService);
1468
+ var IdempotencyCache = class {
1469
+ /**
1470
+ * @param maxEntries - Hard cap; the oldest entries are evicted beyond it.
1471
+ * @param ttlMs - Lifetime of each entry in milliseconds.
1472
+ * @param now - Injectable clock for deterministic tests; defaults to `Date.now`.
1473
+ */
1474
+ constructor(maxEntries, ttlMs, now = Date.now) {
1475
+ this.maxEntries = maxEntries;
1476
+ this.ttlMs = ttlMs;
1477
+ this.now = now;
1478
+ }
1479
+ maxEntries;
1480
+ ttlMs;
1481
+ now;
1482
+ entries = /* @__PURE__ */ new Map();
1483
+ /**
1484
+ * Derives a deterministic cache key by hashing the idempotency key together
1485
+ * with the final object key. Hashing avoids storing the raw idempotency key as
1486
+ * a `Map` key, where it could be inspected during debugging.
1487
+ *
1488
+ * The two components are hashed through a structured JSON encoding so their
1489
+ * boundary is unambiguous: without it, pairs such as `('a', 'b:c')` and
1490
+ * `('a:b', 'c')` would flatten to the same preimage and collide.
1491
+ *
1492
+ * @param idempotencyKey - The caller-provided idempotency key.
1493
+ * @param finalKey - The normalized, prefixed object key.
1494
+ * @returns A hex-encoded sha256 digest.
1495
+ */
1496
+ computeKey(idempotencyKey, finalKey) {
1497
+ const preimage = JSON.stringify([idempotencyKey, finalKey]);
1498
+ return createHash("sha256").update(preimage).digest("hex");
1499
+ }
1500
+ /**
1501
+ * Looks up a cached result. Expired entries are dropped and reported as a miss.
1502
+ * A live hit is touched (moved to the newest position) to preserve LRU order.
1503
+ *
1504
+ * @param cacheKey - The key returned by {@link computeKey}.
1505
+ * @returns The cached result, or `undefined` on a miss or expiry.
1506
+ */
1507
+ get(cacheKey) {
1508
+ const entry = this.entries.get(cacheKey);
1509
+ if (entry === void 0) {
1510
+ return void 0;
1511
+ }
1512
+ if (entry.expiresAt <= this.now()) {
1513
+ this.entries.delete(cacheKey);
1514
+ return void 0;
1515
+ }
1516
+ this.entries.delete(cacheKey);
1517
+ this.entries.set(cacheKey, entry);
1518
+ return entry.value;
1519
+ }
1520
+ /**
1521
+ * Stores a result under `cacheKey`, refreshing its position, then evicts the
1522
+ * oldest entries while the cache is over capacity.
1523
+ *
1524
+ * @param cacheKey - The key returned by {@link computeKey}.
1525
+ * @param value - The upload result to cache.
1526
+ */
1527
+ set(cacheKey, value) {
1528
+ this.entries.delete(cacheKey);
1529
+ this.entries.set(cacheKey, { value, expiresAt: this.now() + this.ttlMs });
1530
+ while (this.entries.size > this.maxEntries) {
1531
+ for (const oldestKey of this.entries.keys()) {
1532
+ this.entries.delete(oldestKey);
1533
+ break;
1534
+ }
1535
+ }
1536
+ }
1537
+ /**
1538
+ * Reports the current number of cached entries.
1539
+ *
1540
+ * @returns The entry count.
1541
+ */
1542
+ size() {
1543
+ return this.entries.size;
1544
+ }
1545
+ /** Removes every cached entry. */
1546
+ clear() {
1547
+ this.entries.clear();
1548
+ }
1549
+ };
1550
+
1551
+ // src/server/bymax-storage.module.ts
1552
+ function resolveAsyncOptions(options) {
1553
+ validateOptions(options);
1554
+ return applyDefaults(options);
1555
+ }
1556
+ var BymaxStorageModule = class {
1557
+ /**
1558
+ * Synchronous configuration. Validates and resolves the options, then returns
1559
+ * the wired dynamic module.
1560
+ *
1561
+ * @param options - The storage module options.
1562
+ * @returns The configured `DynamicModule`.
1563
+ * @throws StorageException with code `STORAGE_INVALID_CONFIG` on invalid options.
1564
+ *
1565
+ * @example
1566
+ * BymaxStorageModule.forRoot({
1567
+ * endpoint: 'https://s3.us-east-1.amazonaws.com',
1568
+ * region: 'us-east-1',
1569
+ * bucket: 'my-bucket',
1570
+ * credentials: { accessKeyId, secretAccessKey },
1571
+ * })
1572
+ */
1573
+ static forRoot(options) {
1574
+ const resolved = resolveAsyncOptions(options);
1575
+ const providers = [
1576
+ { provide: BYMAX_STORAGE_OPTIONS, useValue: resolved },
1577
+ {
1578
+ provide: BYMAX_STORAGE_UPLOAD_VALIDATORS,
1579
+ useValue: resolved.validation?.customValidators ?? []
1580
+ },
1581
+ { provide: BYMAX_STORAGE_FILE_SCANNER, useValue: resolved.scanner?.impl ?? null },
1582
+ ...BymaxStorageModule.buildCoreProviders()
1583
+ ];
1584
+ return {
1585
+ module: BymaxStorageModule,
1586
+ providers,
1587
+ exports: BymaxStorageModule.buildExports()
1588
+ };
1589
+ }
1590
+ /**
1591
+ * Asynchronous configuration (the canonical NestJS pattern). Resolves the
1592
+ * options from injected dependencies via `useFactory` (+ `inject`), `useClass`,
1593
+ * or `useExisting`, running `validateOptions` + `applyDefaults` inside the
1594
+ * factory. Replicates every provider and export of {@link forRoot}.
1595
+ *
1596
+ * @param asyncOptions - The async options descriptor.
1597
+ * @returns The configured `DynamicModule`.
1598
+ * @throws Error when none of `useFactory`/`useClass`/`useExisting` is provided.
1599
+ *
1600
+ * @example
1601
+ * BymaxStorageModule.forRootAsync({
1602
+ * imports: [ConfigModule],
1603
+ * inject: [ConfigService],
1604
+ * useFactory: (config: ConfigService) => ({
1605
+ * endpoint: config.getOrThrow('S3_ENDPOINT'),
1606
+ * region: config.getOrThrow('S3_REGION'),
1607
+ * bucket: config.getOrThrow('S3_BUCKET'),
1608
+ * credentials: {
1609
+ * accessKeyId: config.getOrThrow('S3_ACCESS_KEY_ID'),
1610
+ * secretAccessKey: config.getOrThrow('S3_SECRET_ACCESS_KEY'),
1611
+ * },
1612
+ * }),
1613
+ * })
1614
+ */
1615
+ static forRootAsync(asyncOptions) {
1616
+ const providers = [
1617
+ ...BymaxStorageModule.buildAsyncOptionsProviders(asyncOptions),
1618
+ {
1619
+ provide: BYMAX_STORAGE_UPLOAD_VALIDATORS,
1620
+ useFactory: (resolved) => resolved.validation?.customValidators ?? [],
1621
+ inject: [BYMAX_STORAGE_OPTIONS]
1622
+ },
1623
+ {
1624
+ provide: BYMAX_STORAGE_FILE_SCANNER,
1625
+ useFactory: (resolved) => resolved.scanner?.impl ?? null,
1626
+ inject: [BYMAX_STORAGE_OPTIONS]
1627
+ },
1628
+ ...BymaxStorageModule.buildCoreProviders()
1629
+ ];
1630
+ return {
1631
+ module: BymaxStorageModule,
1632
+ imports: asyncOptions.imports ?? [],
1633
+ providers,
1634
+ exports: BymaxStorageModule.buildExports()
1635
+ };
1636
+ }
1637
+ /** Providers shared by both configuration paths (options-agnostic). */
1638
+ static buildCoreProviders() {
1639
+ return [
1640
+ S3ClientProvider,
1641
+ KeyResolverService,
1642
+ {
1643
+ // Per-instance idempotency cache for deduplicating uploads within the TTL.
1644
+ provide: BYMAX_STORAGE_IDEMPOTENCY_CACHE,
1645
+ useFactory: () => new IdempotencyCache(
1646
+ DEFAULT_IDEMPOTENCY_CACHE_MAX_ENTRIES,
1647
+ DEFAULT_IDEMPOTENCY_CACHE_TTL_MS
1648
+ )
1649
+ },
1650
+ StorageService,
1651
+ SignedUrlService,
1652
+ // ValidationService and FileScannerService are internal — consumed via
1653
+ // StorageService.upload() only, not exported from the module.
1654
+ ValidationService,
1655
+ FileScannerService,
1656
+ {
1657
+ // Public raw-client token. Null-tolerant so the module still registers
1658
+ // without credentials (resolves to null until configured).
1659
+ provide: BYMAX_STORAGE_S3_CLIENT,
1660
+ useFactory: (provider) => provider.getClientOrNull(),
1661
+ inject: [S3ClientProvider]
1662
+ }
1663
+ ];
1664
+ }
1665
+ /**
1666
+ * Public DI surface: the facades, the resolved options, the raw-client token,
1667
+ * and the user-supplied validators + scanner tokens. Internal services and the
1668
+ * idempotency cache are intentionally not exported.
1669
+ */
1670
+ static buildExports() {
1671
+ return [
1672
+ StorageService,
1673
+ SignedUrlService,
1674
+ BYMAX_STORAGE_OPTIONS,
1675
+ BYMAX_STORAGE_S3_CLIENT,
1676
+ BYMAX_STORAGE_UPLOAD_VALIDATORS,
1677
+ BYMAX_STORAGE_FILE_SCANNER
1678
+ ];
1679
+ }
1680
+ /**
1681
+ * Builds the options provider plus, for `useClass`, the factory-class provider
1682
+ * that must be registered so Nest can instantiate and inject it.
1683
+ */
1684
+ static buildAsyncOptionsProviders(asyncOptions) {
1685
+ const optionsProvider = BymaxStorageModule.createAsyncOptionsProvider(asyncOptions);
1686
+ if (asyncOptions.useClass) {
1687
+ return [optionsProvider, { provide: asyncOptions.useClass, useClass: asyncOptions.useClass }];
1688
+ }
1689
+ return [optionsProvider];
1690
+ }
1691
+ /** Builds the `BYMAX_STORAGE_OPTIONS` provider from the async descriptor. */
1692
+ static createAsyncOptionsProvider(asyncOptions) {
1693
+ const { useFactory, useClass, useExisting } = asyncOptions;
1694
+ if (useFactory) {
1695
+ return {
1696
+ provide: BYMAX_STORAGE_OPTIONS,
1697
+ useFactory: async (...args) => resolveAsyncOptions(await useFactory(...args)),
1698
+ inject: [...asyncOptions.inject ?? []]
1699
+ };
1700
+ }
1701
+ const factoryToken = useClass ?? useExisting;
1702
+ if (factoryToken) {
1703
+ return {
1704
+ provide: BYMAX_STORAGE_OPTIONS,
1705
+ useFactory: async (factory) => resolveAsyncOptions(await factory.createStorageOptions()),
1706
+ inject: [factoryToken]
1707
+ };
1708
+ }
1709
+ throw new Error(
1710
+ "BymaxStorageModule.forRootAsync requires useFactory, useClass, or useExisting"
1711
+ );
1712
+ }
1713
+ };
1714
+ BymaxStorageModule = __decorateClass([
1715
+ Global(),
1716
+ Module({})
1717
+ ], BymaxStorageModule);
1718
+
1719
+ // src/server/providers/no-op-validator.ts
1720
+ var NoOpUploadValidator = class {
1721
+ /** Identifies this validator in validation-failed error details. */
1722
+ name = "no-op";
1723
+ /**
1724
+ * Always returns `{ ok: true }` — no validation is performed.
1725
+ *
1726
+ * @param _ctx - The upload context (ignored).
1727
+ * @returns A passing validation result.
1728
+ */
1729
+ validate(_ctx) {
1730
+ return Promise.resolve({ ok: true });
1731
+ }
1732
+ };
1733
+
1734
+ // src/server/providers/no-op-scanner.ts
1735
+ var NoOpFileScanner = class {
1736
+ /**
1737
+ * Always returns `{ status: 'clean', engine: 'noop' }`.
1738
+ *
1739
+ * @param _input - The scan input (ignored).
1740
+ * @returns A clean scan result with the `'noop'` engine identifier.
1741
+ */
1742
+ scan(_input) {
1743
+ return Promise.resolve({ status: "clean", engine: "noop" });
1744
+ }
1745
+ };
1746
+
1747
+ // src/server/config/provider-recipes.ts
1748
+ var NON_AWS_CHECKSUM = {
1749
+ requestChecksumCalculation: "WHEN_REQUIRED",
1750
+ responseChecksumValidation: "WHEN_REQUIRED"
1751
+ };
1752
+ function toCredentials(input) {
1753
+ return {
1754
+ accessKeyId: input.accessKeyId,
1755
+ secretAccessKey: input.secretAccessKey,
1756
+ ...input.sessionToken !== void 0 ? { sessionToken: input.sessionToken } : {}
1757
+ };
1758
+ }
1759
+ var providerRecipes = {
1760
+ /** AWS S3 — keeps the SDK's default checksum behaviour (`'WHEN_SUPPORTED'`). */
1761
+ awsS3(input) {
1762
+ return {
1763
+ endpoint: `https://s3.${input.region}.amazonaws.com`,
1764
+ region: input.region,
1765
+ bucket: input.bucket,
1766
+ credentials: toCredentials(input),
1767
+ forcePathStyle: false,
1768
+ publicBaseUrl: `https://${input.bucket}.s3.${input.region}.amazonaws.com`,
1769
+ serverSideEncryption: "AES256"
1770
+ };
1771
+ },
1772
+ /** DigitalOcean Spaces — virtual-hosted, public by default, with a CDN host. */
1773
+ digitalOceanSpaces(input) {
1774
+ return {
1775
+ endpoint: `https://${input.region}.digitaloceanspaces.com`,
1776
+ region: input.region,
1777
+ bucket: input.bucket,
1778
+ credentials: toCredentials(input),
1779
+ forcePathStyle: false,
1780
+ publicBaseUrl: `https://${input.bucket}.${input.region}.digitaloceanspaces.com`,
1781
+ cdnBaseUrl: `https://${input.bucket}.${input.region}.cdn.digitaloceanspaces.com`,
1782
+ defaultPublicRead: true,
1783
+ ...NON_AWS_CHECKSUM
1784
+ };
1785
+ },
1786
+ /** Cloudflare R2 — region `'auto'`; public reads require a custom domain. */
1787
+ cloudflareR2(input) {
1788
+ return {
1789
+ endpoint: `https://${input.accountId}.r2.cloudflarestorage.com`,
1790
+ region: "auto",
1791
+ bucket: input.bucket,
1792
+ credentials: toCredentials(input),
1793
+ forcePathStyle: false,
1794
+ publicBaseUrl: input.customDomain,
1795
+ ...NON_AWS_CHECKSUM
1796
+ };
1797
+ },
1798
+ /** Backblaze B2 — S3-compatible API; virtual-hosted matches `publicBaseUrl`. */
1799
+ backblazeB2(input) {
1800
+ return {
1801
+ endpoint: `https://${input.endpointHost}`,
1802
+ region: input.region,
1803
+ bucket: input.bucket,
1804
+ credentials: toCredentials(input),
1805
+ forcePathStyle: false,
1806
+ publicBaseUrl: `https://${input.bucket}.${input.endpointHost}`,
1807
+ ...NON_AWS_CHECKSUM
1808
+ };
1809
+ },
1810
+ /** MinIO — dev / CI / self-hosted; path-style addressing. */
1811
+ minio(input) {
1812
+ return {
1813
+ endpoint: input.endpoint,
1814
+ region: input.region ?? "us-east-1",
1815
+ bucket: input.bucket,
1816
+ credentials: toCredentials(input),
1817
+ forcePathStyle: true,
1818
+ publicBaseUrl: `${trimTrailingSlashes(input.endpoint)}/${input.bucket}`,
1819
+ ...NON_AWS_CHECKSUM
1820
+ };
1821
+ },
1822
+ /** Wasabi — Hot Cloud Storage; virtual-hosted. */
1823
+ wasabi(input) {
1824
+ return {
1825
+ endpoint: `https://s3.${input.region}.wasabisys.com`,
1826
+ region: input.region,
1827
+ bucket: input.bucket,
1828
+ credentials: toCredentials(input),
1829
+ forcePathStyle: false,
1830
+ publicBaseUrl: `https://${input.bucket}.s3.${input.region}.wasabisys.com`,
1831
+ ...NON_AWS_CHECKSUM
1832
+ };
1833
+ }
1834
+ };
1835
+
1836
+ export { BYMAX_STORAGE_FILE_SCANNER, BYMAX_STORAGE_IDEMPOTENCY_CACHE, BYMAX_STORAGE_LOGGER, BYMAX_STORAGE_OPTIONS, BYMAX_STORAGE_S3_CLIENT, BYMAX_STORAGE_UPLOAD_VALIDATORS, BymaxStorageModule, NoOpFileScanner, NoOpUploadValidator, STORAGE_ERROR_CODES, SignedUrlService, StorageException, StorageService, providerRecipes };