@bymax-one/nest-storage 1.1.16 → 1.1.18

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.
@@ -174,6 +174,9 @@ function assertMetadata(metadata) {
174
174
 
175
175
  // src/server/config/validate-options.ts
176
176
  var MIN_PART_SIZE_BYTES = 5 * 1024 * 1024;
177
+ var MAX_PART_SIZE_BYTES = 5 * 1024 * 1024 * 1024;
178
+ var MAX_QUEUE_SIZE = 1e3;
179
+ var REGION_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
177
180
  function invalid(reason) {
178
181
  return new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG, HttpStatus.INTERNAL_SERVER_ERROR, {
179
182
  reason
@@ -213,18 +216,73 @@ function assertTimerMs(options, name, min) {
213
216
  );
214
217
  }
215
218
  }
216
- function assertLimitsAndEncryption(options) {
217
- const signedUrls = options.signedUrls;
218
- if (isObject(signedUrls) && typeof signedUrls.maxTtlSeconds === "number" && signedUrls.maxTtlSeconds <= 0) {
219
- throw invalid("signedUrls.maxTtlSeconds must be > 0");
219
+ function assertBoundedInteger(section, group, key, range) {
220
+ if (!isObject(section)) return;
221
+ const value = section[key];
222
+ if (value === void 0 || value === null) return;
223
+ if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
224
+ throw invalid(
225
+ `${group}.${key} must be an integer ${range.words ?? `from ${String(range.min)} to ${String(range.max)}`}`
226
+ );
227
+ }
228
+ }
229
+ function assertScanner(scanner) {
230
+ if (scanner === void 0) return;
231
+ if (scanner === null) throw invalid("scanner must not be null; omit it for no scanner");
232
+ if (!isObject(scanner)) throw invalid("scanner must be an object");
233
+ const impl = scanner.impl;
234
+ if (!isObject(impl) || typeof impl.scan !== "function") {
235
+ throw invalid("scanner.impl must be an object with a scan function");
236
+ }
237
+ const { mode, rejectOnUnknown } = scanner;
238
+ if (mode !== void 0 && mode !== null && mode !== "pre-upload" && mode !== "post-upload") {
239
+ throw invalid("scanner.mode must be 'pre-upload' or 'post-upload'");
240
+ }
241
+ if (rejectOnUnknown !== void 0 && rejectOnUnknown !== null && typeof rejectOnUnknown !== "boolean") {
242
+ throw invalid("scanner.rejectOnUnknown must be a boolean");
243
+ }
244
+ }
245
+ function assertValidationKinds(validation) {
246
+ if (!isObject(validation)) return;
247
+ const { maxSizeBytes, mimeWhitelist, customValidators } = validation;
248
+ if (maxSizeBytes === null) {
249
+ throw invalid("validation.maxSizeBytes must not be null; omit it for no size limit");
220
250
  }
221
- const multipart = options.multipart;
222
- if (isObject(multipart) && typeof multipart.partSizeBytes === "number" && multipart.partSizeBytes < MIN_PART_SIZE_BYTES) {
223
- throw invalid("multipart.partSizeBytes must be >= 5 MB (S3 hard limit)");
251
+ if (mimeWhitelist === null) {
252
+ throw invalid("validation.mimeWhitelist must not be null; omit it to allow every type");
224
253
  }
254
+ if (mimeWhitelist !== void 0 && (!Array.isArray(mimeWhitelist) || !Array.from(mimeWhitelist).every((entry) => typeof entry === "string"))) {
255
+ throw invalid("validation.mimeWhitelist must be an array of strings");
256
+ }
257
+ if (customValidators === null) {
258
+ throw invalid("validation.customValidators must not be null; omit it to run no custom validator");
259
+ }
260
+ if (customValidators !== void 0 && !Array.isArray(customValidators)) {
261
+ throw invalid("validation.customValidators must be an array");
262
+ }
263
+ }
264
+ function assertNumericSections(options) {
265
+ const MAX = Number.MAX_SAFE_INTEGER;
266
+ assertBoundedInteger(options.validation, "validation", "maxSizeBytes", { min: 1, max: MAX });
267
+ for (const key of ["defaultGetTtlSeconds", "defaultPutTtlSeconds", "maxTtlSeconds"]) {
268
+ assertBoundedInteger(options.signedUrls, "signedUrls", key, { min: 1, max: MAX });
269
+ }
270
+ assertBoundedInteger(options.scanner, "scanner", "timeoutMs", { min: 1, max: MAX_TIMER_MS });
271
+ assertBoundedInteger(options.multipart, "multipart", "thresholdBytes", { min: 1, max: MAX });
272
+ assertBoundedInteger(options.multipart, "multipart", "partSizeBytes", {
273
+ min: MIN_PART_SIZE_BYTES,
274
+ max: MAX_PART_SIZE_BYTES,
275
+ words: ">= 5 MB (S3 hard limit) and <= 5 GB"
276
+ });
277
+ assertBoundedInteger(options.multipart, "multipart", "queueSize", { min: 1, max: MAX_QUEUE_SIZE });
278
+ }
279
+ function assertLimitsAndEncryption(options) {
280
+ assertNumericSections(options);
281
+ assertValidationKinds(options.validation);
282
+ assertScanner(options.scanner);
225
283
  const maxAttempts = options.maxAttempts;
226
- if (maxAttempts !== void 0 && (typeof maxAttempts !== "number" || !Number.isInteger(maxAttempts) || maxAttempts < 1)) {
227
- throw invalid("maxAttempts must be an integer >= 1");
284
+ if (maxAttempts !== void 0 && (typeof maxAttempts !== "number" || !Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > Number.MAX_SAFE_INTEGER)) {
285
+ throw invalid("maxAttempts must be an integer from 1 to 9007199254740991");
228
286
  }
229
287
  assertTimerMs(options, "requestTimeoutMs", 1);
230
288
  assertTimerMs(options, "uploadIdleTimeoutMs", 0);
@@ -254,9 +312,17 @@ function validateOptions(options) {
254
312
  if (!isNonEmptyString(options.region)) {
255
313
  throw invalid("options.region must be a non-empty string");
256
314
  }
315
+ if (!REGION_SHAPE.test(options.region)) {
316
+ throw invalid(
317
+ "options.region must be 1 to 63 letters, digits, '.', '_' or '-', starting with a letter or digit"
318
+ );
319
+ }
257
320
  if (!isNonEmptyString(options.bucket)) {
258
321
  throw invalid("options.bucket must be a non-empty string");
259
322
  }
323
+ if (options.keyPrefix !== void 0 && options.keyPrefix !== null && typeof options.keyPrefix !== "string") {
324
+ throw invalid("options.keyPrefix must be a string");
325
+ }
260
326
  if (!isObject(options.credentials)) {
261
327
  throw invalid("options.credentials is required");
262
328
  }
@@ -285,6 +351,7 @@ var DEFAULT_CACHE_CONTROL = "public, max-age=31536000, immutable";
285
351
  var DEFAULT_CONTENT_DISPOSITION = "inline";
286
352
  var DEFAULT_MAX_ATTEMPTS = 3;
287
353
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
354
+ var DEFAULT_SCANNER_TIMEOUT_MS = 6e4;
288
355
  var DEFAULT_FORCE_PATH_STYLE = false;
289
356
  var DEFAULT_PUBLIC_READ = false;
290
357
  var DEFAULT_CHECKSUM_CALCULATION = "WHEN_SUPPORTED";
@@ -302,9 +369,52 @@ var DEFAULT_MULTIPART = {
302
369
  var DEFAULT_IDEMPOTENCY_CACHE_MAX_ENTRIES = 1e3;
303
370
  var DEFAULT_IDEMPOTENCY_CACHE_TTL_MS = 864e5;
304
371
 
372
+ // src/server/config/option-keys.ts
373
+ function keysOf() {
374
+ return (keys) => keys;
375
+ }
376
+ var OPTION_KEYS = keysOf()([
377
+ "endpoint",
378
+ "region",
379
+ "bucket",
380
+ "credentials",
381
+ "forcePathStyle",
382
+ "publicBaseUrl",
383
+ "cdnBaseUrl",
384
+ "defaultPublicRead",
385
+ "keyPrefix",
386
+ "defaultCacheControl",
387
+ "defaultContentDisposition",
388
+ "signedUrls",
389
+ "multipart",
390
+ "validation",
391
+ "scanner",
392
+ "serverSideEncryption",
393
+ "kmsKeyId",
394
+ "requestChecksumCalculation",
395
+ "responseChecksumValidation",
396
+ "maxAttempts",
397
+ "requestTimeoutMs",
398
+ "uploadIdleTimeoutMs",
399
+ "bodyIdleTimeoutMs"
400
+ ]);
401
+ var CREDENTIAL_KEYS = keysOf()(["accessKeyId", "secretAccessKey", "sessionToken"]);
402
+ var SIGNED_URL_KEYS = keysOf()(["defaultGetTtlSeconds", "defaultPutTtlSeconds", "maxTtlSeconds"]);
403
+ var MULTIPART_KEYS = keysOf()(["thresholdBytes", "partSizeBytes", "queueSize"]);
404
+ var VALIDATION_KEYS = keysOf()(["mimeWhitelist", "maxSizeBytes", "customValidators"]);
405
+ var SCANNER_KEYS = keysOf()(["impl", "mode", "rejectOnUnknown", "timeoutMs"]);
406
+
305
407
  // src/server/config/apply-defaults.ts
408
+ function definedOnly(group, keys) {
409
+ const picked = {};
410
+ for (const key of keys) {
411
+ const value = group?.[key];
412
+ if (value !== void 0 && value !== null) picked[key] = value;
413
+ }
414
+ return picked;
415
+ }
306
416
  function resolveSignedUrls(configured) {
307
- const merged = { ...DEFAULT_SIGNED_URLS, ...configured ?? {} };
417
+ const merged = { ...DEFAULT_SIGNED_URLS, ...definedOnly(configured, SIGNED_URL_KEYS) };
308
418
  return { ...merged, maxTtlSeconds: Math.min(merged.maxTtlSeconds, MAX_SIGNED_URL_TTL_SECONDS) };
309
419
  }
310
420
  function attachCredentials(resolved, credentials) {
@@ -331,9 +441,10 @@ function applyDefaults(options) {
331
441
  defaultCacheControl: options.defaultCacheControl ?? DEFAULT_CACHE_CONTROL,
332
442
  defaultContentDisposition: options.defaultContentDisposition ?? DEFAULT_CONTENT_DISPOSITION,
333
443
  signedUrls: resolveSignedUrls(options.signedUrls),
334
- multipart: { ...DEFAULT_MULTIPART, ...options.multipart ?? {} },
335
- ...options.validation !== void 0 ? { validation: options.validation } : {},
336
- ...options.scanner !== void 0 ? { scanner: options.scanner } : {},
444
+ multipart: { ...DEFAULT_MULTIPART, ...definedOnly(options.multipart, MULTIPART_KEYS) },
445
+ ...options.validation !== void 0 ? { validation: definedOnly(options.validation, VALIDATION_KEYS) } : {},
446
+ // A group is an object or it is not configured. `forRoot` refuses a `null` scanner before this runs; if one reaches here it adds no scanner.
447
+ ...options.scanner ? { scanner: definedOnly(options.scanner, SCANNER_KEYS) } : {},
337
448
  ...options.serverSideEncryption !== void 0 ? { serverSideEncryption: options.serverSideEncryption } : {},
338
449
  ...options.kmsKeyId !== void 0 ? { kmsKeyId: options.kmsKeyId } : {},
339
450
  requestChecksumCalculation: options.requestChecksumCalculation ?? DEFAULT_CHECKSUM_CALCULATION,
@@ -348,6 +459,51 @@ function applyDefaults(options) {
348
459
  return resolved;
349
460
  }
350
461
 
462
+ // src/server/config/snapshot-options.ts
463
+ function isObject2(value) {
464
+ return typeof value === "object" && value !== null;
465
+ }
466
+ function pick(source, keys) {
467
+ const copy = {};
468
+ for (const key of keys) {
469
+ const value = source[key];
470
+ if (value !== void 0) copy[key] = value;
471
+ }
472
+ return copy;
473
+ }
474
+ function pickGroup(value, keys) {
475
+ return isObject2(value) ? pick(value, keys) : value;
476
+ }
477
+ function copyArray(value) {
478
+ if (!Array.isArray(value)) return value;
479
+ try {
480
+ return Array.from(value);
481
+ } catch {
482
+ return value;
483
+ }
484
+ }
485
+ var GROUPS = {
486
+ credentials: CREDENTIAL_KEYS,
487
+ signedUrls: SIGNED_URL_KEYS,
488
+ multipart: MULTIPART_KEYS,
489
+ validation: VALIDATION_KEYS,
490
+ scanner: SCANNER_KEYS
491
+ };
492
+ function snapshotOptions(options) {
493
+ if (!isObject2(options)) return options;
494
+ const copy = pick(options, OPTION_KEYS);
495
+ for (const [group, keys] of Object.entries(GROUPS)) {
496
+ if (group in copy) copy[group] = pickGroup(copy[group], keys);
497
+ }
498
+ const validation = copy.validation;
499
+ if (isObject2(validation)) {
500
+ for (const key of ["mimeWhitelist", "customValidators"]) {
501
+ if (key in validation) validation[key] = copyArray(validation[key]);
502
+ }
503
+ }
504
+ return copy;
505
+ }
506
+
351
507
  // src/server/utils/describe-endpoint.ts
352
508
  function describeEndpoint(endpoint) {
353
509
  try {
@@ -514,6 +670,39 @@ KeyResolverService = __decorateClass([
514
670
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS))
515
671
  ], KeyResolverService);
516
672
 
673
+ // src/server/utils/call-input.ts
674
+ function wrongKind(field2, needs) {
675
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
676
+ field: field2,
677
+ reason: `${field2} must be ${needs}`
678
+ });
679
+ }
680
+ function resolveBucket(perCall, moduleDefault) {
681
+ if (perCall !== void 0 && perCall !== null && typeof perCall !== "string") {
682
+ throw wrongKind("bucket", "a string");
683
+ }
684
+ const bucket = perCall ?? moduleDefault;
685
+ if (!bucket) {
686
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
687
+ }
688
+ return bucket;
689
+ }
690
+ function assertAbortSignal(signal) {
691
+ if (signal === void 0 || signal === null) return;
692
+ if (!hasSignalSurface(signal)) {
693
+ throw wrongKind("abortSignal", "an AbortSignal");
694
+ }
695
+ }
696
+ function hasSignalSurface(signal) {
697
+ if (typeof signal !== "object") return false;
698
+ const candidate = signal;
699
+ try {
700
+ return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function";
701
+ } catch {
702
+ return false;
703
+ }
704
+ }
705
+
517
706
  // src/server/utils/describe-error.ts
518
707
  var NON_PRINTABLE_REJECTION = "non-printable rejection value";
519
708
  function describeError(value) {
@@ -970,11 +1159,7 @@ var BucketLifecycleService = class {
970
1159
  }
971
1160
  }
972
1161
  resolveBucket(perCall) {
973
- const bucket = perCall ?? this.options.bucket;
974
- if (!bucket) {
975
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
976
- }
977
- return bucket;
1162
+ return resolveBucket(perCall, this.options.bucket);
978
1163
  }
979
1164
  };
980
1165
  BucketLifecycleService = __decorateClass([
@@ -1093,6 +1278,14 @@ function toUploadBody(body) {
1093
1278
  if (ArrayBuffer.isView(body) && !(body instanceof Uint8Array)) {
1094
1279
  return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
1095
1280
  }
1281
+ const stream = body;
1282
+ const readable = typeof stream?.pipe === "function" && typeof stream.on === "function" && typeof stream.once === "function" && typeof stream.pause === "function" && typeof stream.resume === "function";
1283
+ if (!(body instanceof Uint8Array) && !readable) {
1284
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1285
+ field: "body",
1286
+ reason: "body must be a Buffer, Uint8Array, ArrayBuffer, string or readable stream"
1287
+ });
1288
+ }
1096
1289
  return body;
1097
1290
  }
1098
1291
 
@@ -1132,6 +1325,17 @@ function assertMimeAllowed(whitelist, contentType) {
1132
1325
  });
1133
1326
  }
1134
1327
 
1328
+ // src/server/utils/numeric-input.ts
1329
+ function assertIntegerInput(value, field2, min) {
1330
+ if (value === void 0) return;
1331
+ if (!Number.isInteger(value) || value < min) {
1332
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1333
+ field: field2,
1334
+ reason: `${field2} must be an integer of at least ${String(min)}`
1335
+ });
1336
+ }
1337
+ }
1338
+
1135
1339
  // src/server/services/validation.service.ts
1136
1340
  var ValidationService = class {
1137
1341
  constructor(options, validators) {
@@ -1180,6 +1384,7 @@ var ValidationService = class {
1180
1384
  }
1181
1385
  /** Best-effort size check — skipped when size is undefined. */
1182
1386
  checkSize(size) {
1387
+ assertIntegerInput(size, "size", 0);
1183
1388
  const maxSizeBytes = this.options.validation?.maxSizeBytes;
1184
1389
  if (maxSizeBytes === void 0 || size === void 0) {
1185
1390
  return;
@@ -1226,8 +1431,26 @@ ValidationService = __decorateClass([
1226
1431
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
1227
1432
  __decorateParam(1, Inject(BYMAX_STORAGE_UPLOAD_VALIDATORS))
1228
1433
  ], ValidationService);
1434
+
1435
+ // src/server/utils/cut-text.ts
1436
+ function cutText(text, max) {
1437
+ if (text.length <= max) return text;
1438
+ const lastKept = text.charCodeAt(max - 1);
1439
+ const splitsPair = lastKept >= 55296 && lastKept <= 56319;
1440
+ return text.slice(0, splitsPair ? max - 1 : max);
1441
+ }
1442
+
1443
+ // src/server/services/file-scanner.service.ts
1229
1444
  var UNSERIALISABLE = "[unserialisable]";
1445
+ var MAX_SCANNER_LABEL_LENGTH = 200;
1230
1446
  var MAX_SCANNER_DETAILS_LENGTH = 300;
1447
+ var MAX_STATUS_LOG_LENGTH = 40;
1448
+ function statusForLog(status) {
1449
+ return typeof status === "string" ? logValue(cutText(status, MAX_STATUS_LOG_LENGTH)) : `<${typeof status}>`;
1450
+ }
1451
+ function scannerLabel(value) {
1452
+ return typeof value === "string" ? cutText(value, MAX_SCANNER_LABEL_LENGTH) : void 0;
1453
+ }
1231
1454
  function toJson(value) {
1232
1455
  return JSON.stringify(value);
1233
1456
  }
@@ -1239,7 +1462,7 @@ function scannerDetailsForLog(details) {
1239
1462
  } catch {
1240
1463
  text = UNSERIALISABLE;
1241
1464
  }
1242
- return ` details=${logValue(text.slice(0, MAX_SCANNER_DETAILS_LENGTH))}`;
1465
+ return ` details=${logValue(cutText(text, MAX_SCANNER_DETAILS_LENGTH))}`;
1243
1466
  }
1244
1467
  var FileScannerService = class {
1245
1468
  constructor(options, scanner) {
@@ -1276,13 +1499,16 @@ var FileScannerService = class {
1276
1499
  *
1277
1500
  * Infected results throw `STORAGE_SCAN_INFECTED`. Inconclusive results throw
1278
1501
  * `STORAGE_SCAN_INCONCLUSIVE` when `rejectOnUnknown` is set; otherwise they
1279
- * are returned with a warning log.
1502
+ * are returned with a warning log. Anything else (no result, a status that is not exactly
1503
+ * `'clean'`, `'infected'` or `'unknown'`) is rejected as inconclusive whatever `rejectOnUnknown`
1504
+ * says, and a scan that outlasts `scanner.timeoutMs` throws `STORAGE_TIMEOUT`.
1280
1505
  *
1281
1506
  * @param input - The scan input.
1282
1507
  * @returns The scan result when `status` is `'clean'` or `'unknown'` (non-rejecting).
1283
1508
  * @throws Error when called without a configured scanner.
1284
1509
  * @throws StorageException `STORAGE_SCAN_INFECTED` on an infected result.
1285
- * @throws StorageException `STORAGE_SCAN_INCONCLUSIVE` on an unknown result with `rejectOnUnknown`.
1510
+ * @throws StorageException `STORAGE_SCAN_INCONCLUSIVE` on an unknown result with `rejectOnUnknown`, or a result outside the contract.
1511
+ * @throws StorageException `STORAGE_TIMEOUT` when the scan outlasts `scanner.timeoutMs`.
1286
1512
  */
1287
1513
  async scan(input) {
1288
1514
  if (!this.scanner) {
@@ -1290,24 +1516,76 @@ var FileScannerService = class {
1290
1516
  "FileScannerService.scan() called without a configured scanner \u2014 guard with isEnabled() first."
1291
1517
  );
1292
1518
  }
1293
- const result = await this.scanner.scan(input);
1294
- if (result.status === "infected") {
1295
- this.logger.warn(`Infected file detected: key=${logValue(input.key)} engine=${logValue(result.engine)} threat=${logValue(result.threat ?? "unknown")}${scannerDetailsForLog(result.details)}`);
1519
+ const result = await this.scanLogged(this.scanner, input);
1520
+ const status = result?.status;
1521
+ const engine = scannerLabel(result?.engine);
1522
+ const threat = scannerLabel(result?.threat);
1523
+ const details = scannerDetailsForLog(result?.details);
1524
+ if (status === "clean") {
1525
+ return result;
1526
+ }
1527
+ if (status === "infected") {
1528
+ this.logger.warn(`Infected file detected: key=${logValue(input.key)} engine=${logValue(engine)} threat=${logValue(threat ?? "unknown")}${details}`);
1296
1529
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INFECTED, void 0, {
1297
- engine: result.engine,
1298
- threat: result.threat
1530
+ engine,
1531
+ threat
1299
1532
  });
1300
1533
  }
1301
- if (result.status === "unknown") {
1302
- if (this.options.scanner?.rejectOnUnknown) {
1303
- this.logger.warn(`Inconclusive scan result rejected: key=${logValue(input.key)} engine=${logValue(result.engine)}${scannerDetailsForLog(result.details)}`);
1304
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INCONCLUSIVE, void 0, {
1305
- engine: result.engine
1306
- });
1534
+ if (status === "unknown" && !this.options.scanner?.rejectOnUnknown) {
1535
+ this.logger.warn(`Inconclusive scan result accepted: key=${logValue(input.key)} engine=${logValue(engine)}`);
1536
+ return result;
1537
+ }
1538
+ const unrecognised = status !== "unknown";
1539
+ this.logger.warn(`Inconclusive scan result rejected: key=${logValue(input.key)} engine=${logValue(engine)}${unrecognised ? ` status=${statusForLog(status)}` : ""}${details}`);
1540
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INCONCLUSIVE, void 0, {
1541
+ engine,
1542
+ ...unrecognised ? { reason: "unrecognised scanner status" } : {}
1543
+ });
1544
+ }
1545
+ /**
1546
+ * Runs the scan and logs a scanner that throws: the caller is answered 500 for that, and without the
1547
+ * line there would be no trace of why. A typed failure of ours (the deadline) says it itself.
1548
+ */
1549
+ async scanLogged(scanner, input) {
1550
+ try {
1551
+ return await this.scanWithinDeadline(scanner, input);
1552
+ } catch (err) {
1553
+ if (!(err instanceof StorageException)) {
1554
+ this.logger.warn(
1555
+ `Scanner failed: key=${logValue(input.key)} error=${logValue(cutText(describeError(err), MAX_SCANNER_DETAILS_LENGTH))}`
1556
+ );
1307
1557
  }
1308
- this.logger.warn(`Inconclusive scan result accepted: key=${logValue(input.key)} engine=${logValue(result.engine)}`);
1558
+ throw err;
1559
+ }
1560
+ }
1561
+ /**
1562
+ * Runs the scanner and gives up after `scanner.timeoutMs`: a scanner that never settles would hold
1563
+ * the upload for good. The scanner is handed a signal that aborts then; one that ignores it keeps
1564
+ * running.
1565
+ */
1566
+ async scanWithinDeadline(scanner, input) {
1567
+ const timeoutMs = this.options.scanner?.timeoutMs ?? DEFAULT_SCANNER_TIMEOUT_MS;
1568
+ const controller = new AbortController();
1569
+ let timer;
1570
+ const deadline = new Promise((_resolve, reject) => {
1571
+ timer = setTimeout(() => {
1572
+ this.logger.warn(`Scan timed out: key=${logValue(input.key)} timeoutMs=${String(timeoutMs)}`);
1573
+ reject(
1574
+ new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, void 0, {
1575
+ key: input.key,
1576
+ bucket: input.bucket,
1577
+ phase: "scan",
1578
+ timeoutMs
1579
+ })
1580
+ );
1581
+ controller.abort();
1582
+ }, timeoutMs);
1583
+ });
1584
+ try {
1585
+ return await Promise.race([scanner.scan({ ...input, signal: controller.signal }), deadline]);
1586
+ } finally {
1587
+ clearTimeout(timer);
1309
1588
  }
1310
- return result;
1311
1589
  }
1312
1590
  };
1313
1591
  FileScannerService = __decorateClass([
@@ -1325,7 +1603,11 @@ var SourceIdleError = class extends Error {
1325
1603
  };
1326
1604
  function isError(value) {
1327
1605
  const candidate = value;
1328
- return typeof candidate?.name === "string" && typeof candidate.message === "string";
1606
+ try {
1607
+ return typeof candidate?.name === "string" && typeof candidate.message === "string";
1608
+ } catch {
1609
+ return false;
1610
+ }
1329
1611
  }
1330
1612
  function withinIdleTime(next, idleMs) {
1331
1613
  return new Promise((resolve, reject) => {
@@ -1400,6 +1682,56 @@ function withSizeLimit(source, limitBytes, kind) {
1400
1682
  pipeline(source, guard, () => void 0);
1401
1683
  return guard;
1402
1684
  }
1685
+ var SizeShortfallError = class extends Error {
1686
+ constructor(declaredBytes, receivedBytes) {
1687
+ super(`The upload body has ${String(receivedBytes)} bytes, fewer than the ${String(declaredBytes)} declared`);
1688
+ this.declaredBytes = declaredBytes;
1689
+ this.receivedBytes = receivedBytes;
1690
+ this.name = "SizeShortfallError";
1691
+ }
1692
+ declaredBytes;
1693
+ receivedBytes;
1694
+ };
1695
+ function withExactSize(source, declaredBytes) {
1696
+ let seen = 0;
1697
+ let held = Buffer.alloc(0);
1698
+ const guard = new Transform({
1699
+ // `decodeStrings` is on, so a chunk that arrives as a string has already become a `Buffer`.
1700
+ transform(bytes, _encoding, callback) {
1701
+ seen += bytes.byteLength;
1702
+ if (seen > declaredBytes) {
1703
+ callback(new SizeLimitError(declaredBytes, "declared"));
1704
+ return;
1705
+ }
1706
+ const all = Buffer.concat([held, bytes]);
1707
+ held = all.subarray(all.byteLength - 1);
1708
+ callback(null, all.subarray(0, all.byteLength - 1));
1709
+ },
1710
+ flush(callback) {
1711
+ if (seen < declaredBytes) {
1712
+ callback(new SizeShortfallError(declaredBytes, seen));
1713
+ return;
1714
+ }
1715
+ callback(null, held);
1716
+ }
1717
+ });
1718
+ let ended = false;
1719
+ source.once("end", () => {
1720
+ ended = true;
1721
+ });
1722
+ source.once("error", (err) => {
1723
+ guard.destroy(err instanceof Error ? err : new Error(String(err)));
1724
+ });
1725
+ source.once("close", () => {
1726
+ if (!ended) guard.destroy();
1727
+ });
1728
+ guard.once("close", () => {
1729
+ destroyStream(source);
1730
+ });
1731
+ guard.on("error", () => void 0);
1732
+ source.pipe(guard);
1733
+ return guard;
1734
+ }
1403
1735
 
1404
1736
  // src/server/errors/size-limit-exception.ts
1405
1737
  function sizeLimitException(limitBytes, kind, context) {
@@ -1410,11 +1742,31 @@ function sizeLimitException(limitBytes, kind, context) {
1410
1742
  });
1411
1743
  }
1412
1744
  function mapSizeLimitError(err, context) {
1745
+ if (err instanceof SizeShortfallError) {
1746
+ return declaredSizeMismatch(err.declaredBytes, err.receivedBytes, context);
1747
+ }
1413
1748
  if (!(err instanceof SizeLimitError)) {
1414
1749
  return void 0;
1415
1750
  }
1416
1751
  return sizeLimitException(err.limitBytes, err.kind, context);
1417
1752
  }
1753
+ function shortfallDetails(declaredBytes, receivedBytes) {
1754
+ return {
1755
+ field: "size",
1756
+ reason: "The body is shorter than the declared size",
1757
+ declaredSize: declaredBytes,
1758
+ receivedSize: receivedBytes
1759
+ };
1760
+ }
1761
+ function declaredSizeMismatch(declaredBytes, receivedBytes, context) {
1762
+ if (receivedBytes > declaredBytes) {
1763
+ return sizeLimitException(declaredBytes, "declared", context);
1764
+ }
1765
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1766
+ ...context,
1767
+ ...shortfallDetails(declaredBytes, receivedBytes)
1768
+ });
1769
+ }
1418
1770
 
1419
1771
  // src/server/errors/multipart-error-mapper.ts
1420
1772
  var ABORT_FAILED_MESSAGE = "Multipart upload failed and could not be aborted";
@@ -1489,6 +1841,7 @@ function requestAborted(signal, context) {
1489
1841
  });
1490
1842
  }
1491
1843
  function throwIfAborted(signal, context) {
1844
+ assertAbortSignal(signal);
1492
1845
  if (signal?.aborted) {
1493
1846
  throw requestAborted(signal, context);
1494
1847
  }
@@ -1561,6 +1914,22 @@ async function abortable(work, signal, context) {
1561
1914
  work.catch(() => void 0);
1562
1915
  }
1563
1916
  }
1917
+ function abortOnBodyFailure(body, signal) {
1918
+ const stream = body;
1919
+ if (typeof stream?.once !== "function") {
1920
+ return { signal, failure: () => void 0 };
1921
+ }
1922
+ const controller = new AbortController();
1923
+ let failure;
1924
+ stream.once("error", (err) => {
1925
+ failure = err;
1926
+ controller.abort();
1927
+ });
1928
+ return {
1929
+ signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
1930
+ failure: () => failure
1931
+ };
1932
+ }
1564
1933
 
1565
1934
  // src/server/utils/multipart-abort.ts
1566
1935
  async function closeMultipartUpload(client, bucket, key, uploadId, onFailure) {
@@ -1723,10 +2092,13 @@ function withBytesBody(options) {
1723
2092
  }
1724
2093
  function boundStreamSize(body, declaredSize, options) {
1725
2094
  const limit = declaredSize ?? options.validation?.maxSizeBytes;
1726
- const singleShot = pickUploadStrategy(body, declaredSize, options.multipart.thresholdBytes) === "single-shot";
1727
- if (isBufferLike(body) || singleShot || limit === void 0) {
2095
+ if (isBufferLike(body) || limit === void 0) {
1728
2096
  return body;
1729
2097
  }
2098
+ const singleShot = pickUploadStrategy(body, declaredSize, options.multipart.thresholdBytes) === "single-shot";
2099
+ if (declaredSize !== void 0 && singleShot) {
2100
+ return withExactSize(body, declaredSize);
2101
+ }
1730
2102
  return withSizeLimit(body, limit, declaredSize === void 0 ? "max" : "declared");
1731
2103
  }
1732
2104
  async function bufferStreamForScan(body, finalKey, maxSizeBytes) {
@@ -1747,6 +2119,14 @@ async function bufferStreamForScan(body, finalKey, maxSizeBytes) {
1747
2119
  }
1748
2120
  return buffered;
1749
2121
  }
2122
+ function assertScannedSize(body, declaredSize, thresholdBytes, context) {
2123
+ if (!isBufferLike(body) || declaredSize === void 0 || body.byteLength === declaredSize) {
2124
+ return;
2125
+ }
2126
+ if (body.byteLength > declaredSize || declaredSize < thresholdBytes) {
2127
+ throw declaredSizeMismatch(declaredSize, body.byteLength, context);
2128
+ }
2129
+ }
1750
2130
 
1751
2131
  // src/server/utils/download-body.ts
1752
2132
  function guardDownloadBody(body, idleMs, context, signal) {
@@ -1788,7 +2168,7 @@ function baseCarriesBucket(base, bucket) {
1788
2168
 
1789
2169
  // src/server/utils/upload-support.ts
1790
2170
  function normalizeScanBody(body) {
1791
- return Buffer.isBuffer(body) ? body : Buffer.from(body);
2171
+ return body;
1792
2172
  }
1793
2173
  function forwardProgress(uploader, onProgress) {
1794
2174
  if (!onProgress) return;
@@ -1935,6 +2315,7 @@ var StorageService = class {
1935
2315
  if (rawBody === void 0 || rawBody === null) {
1936
2316
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BODY_MISSING);
1937
2317
  }
2318
+ assertIntegerInput(requested.size, "size", 0);
1938
2319
  const options = withBytesBody(requested);
1939
2320
  if (!options.contentType) {
1940
2321
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_CONTENT_TYPE_REQUIRED);
@@ -1979,22 +2360,26 @@ var StorageService = class {
1979
2360
  signal,
1980
2361
  context
1981
2362
  );
2363
+ assertScannedSize(scanned, options.size, this.options.multipart.thresholdBytes, context);
1982
2364
  const body = boundStreamSize(scanned, options.size, this.options);
1983
2365
  const validatedOptions = { ...options, body };
1984
2366
  await abortable(this.runPreUploadScan(body, finalKey, bucket, options), signal, context);
1985
2367
  return validatedOptions;
1986
2368
  }
1987
2369
  /**
1988
- * In pre-upload scan mode a stream body is read into one `Buffer`, so the scanner
1989
- * and the upload see the same bytes; a stream is single-use, and one the scanner
2370
+ * In pre-upload scan mode a stream body is read into one `Buffer`, and a buffer body is copied, so
2371
+ * the scanner and the upload see the same bytes; a stream is single-use, and one the scanner
1990
2372
  * had consumed would leave the upload with nothing to send. The read is bounded by
1991
2373
  * `validation.maxSizeBytes`, and a stream with no bound is refused rather than
1992
2374
  * buffered without limit. Other bodies and modes pass through unchanged.
1993
2375
  */
1994
2376
  async bufferForPreUploadScan(body, finalKey) {
1995
- if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload" || isBufferLike(body)) {
2377
+ if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload") {
1996
2378
  return body;
1997
2379
  }
2380
+ if (isBufferLike(body)) {
2381
+ return Buffer.from(body);
2382
+ }
1998
2383
  return bufferStreamForScan(body, finalKey, this.options.validation?.maxSizeBytes);
1999
2384
  }
2000
2385
  /** Runs a pre-upload scan when configured; throws on infected. */
@@ -2234,11 +2619,7 @@ var StorageService = class {
2234
2619
  }
2235
2620
  /** Resolves the target bucket from a per-call override or the module default. */
2236
2621
  resolveBucket(perCall) {
2237
- const bucket = perCall ?? this.options.bucket;
2238
- if (!bucket) {
2239
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
2240
- }
2241
- return bucket;
2622
+ return resolveBucket(perCall, this.options.bucket);
2242
2623
  }
2243
2624
  /** Maps an S3 metadata response onto the public `ObjectMetadata` shape. */
2244
2625
  toObjectMetadata(response, finalKey, bucket) {
@@ -2264,8 +2645,9 @@ var StorageService = class {
2264
2645
  Body: normalizeSingleShotBody(options.body),
2265
2646
  ContentLength: total
2266
2647
  };
2648
+ const watch = abortOnBodyFailure(input.Body, options.abortSignal);
2267
2649
  try {
2268
- const response = await this.s3Provider.getClient().send(new PutObjectCommand(input), sendOptions(options.abortSignal));
2650
+ const response = await this.s3Provider.getClient().send(new PutObjectCommand(input), sendOptions(watch.signal));
2269
2651
  if (options.onProgress) {
2270
2652
  emitProgress(options.onProgress, total, total);
2271
2653
  }
@@ -2280,7 +2662,8 @@ var StorageService = class {
2280
2662
  });
2281
2663
  } catch (err) {
2282
2664
  const context = { key: finalKey, bucket, op: "upload-single" };
2283
- throw failureOrAbort(options.abortSignal, context, mapAwsError(err, context));
2665
+ const mapped = mapSizeLimitError(watch.failure(), context) ?? mapAwsError(err, context);
2666
+ throw failureOrAbort(options.abortSignal, context, mapped);
2284
2667
  }
2285
2668
  }
2286
2669
  /**
@@ -2368,6 +2751,7 @@ var StorageService = class {
2368
2751
  async list(options) {
2369
2752
  this.assertConfigured();
2370
2753
  const bucket = this.resolveBucket(options.bucket);
2754
+ assertIntegerInput(options.maxKeys, "maxKeys", 1);
2371
2755
  const maxKeys = Math.min(options.maxKeys ?? MAX_LIST_KEYS, MAX_LIST_KEYS);
2372
2756
  const prefix = options.prefix ? this.keyResolver.normalize(options.prefix) : this.keyResolver.getPrefix();
2373
2757
  const context = { bucket, prefix, op: "list" };
@@ -2470,11 +2854,13 @@ StorageService = __decorateClass([
2470
2854
 
2471
2855
  // src/server/utils/ttl-clamp.ts
2472
2856
  function clampTtl(ttlSeconds, defaultTtl, maxTtl) {
2473
- const ttl = ttlSeconds ?? defaultTtl;
2474
- if (ttl <= 0) {
2857
+ const requested = ttlSeconds;
2858
+ const ttl = requested === void 0 ? defaultTtl : requested;
2859
+ if (!Number.isInteger(ttl) || ttl <= 0) {
2475
2860
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SIGNED_URL_TTL_INVALID, void 0, {
2476
- reason: "TTL must be > 0",
2477
- provided: ttl
2861
+ reason: Number.isFinite(ttl) && ttl <= 0 ? "TTL must be > 0" : "TTL must be a whole number of seconds greater than 0",
2862
+ // Only a finite number is echoed: a string, a Symbol or a function could carry anything the caller holds.
2863
+ ...Number.isFinite(ttl) ? { provided: ttl } : {}
2478
2864
  });
2479
2865
  }
2480
2866
  return Math.min(ttl, maxTtl);
@@ -2632,7 +3018,8 @@ var SignedUrlService = class {
2632
3018
  if (!Number.isInteger(options.parts) || options.parts < 1 || options.parts > MAX_MULTIPART_PARTS) {
2633
3019
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT, void 0, {
2634
3020
  reason: `parts must be an integer from 1 to ${String(MAX_MULTIPART_PARTS)}`,
2635
- provided: options.parts
3021
+ // Only a number is repeated: any other value is the caller's to keep.
3022
+ ...Number.isFinite(options.parts) ? { provided: options.parts } : {}
2636
3023
  });
2637
3024
  }
2638
3025
  const finalKey = this.keyResolver.normalize(options.key);
@@ -2688,11 +3075,7 @@ var SignedUrlService = class {
2688
3075
  }
2689
3076
  /** Resolves the target bucket from a per-call override or the module default. */
2690
3077
  resolveBucket(perCall) {
2691
- const bucket = perCall ?? this.options.bucket;
2692
- if (!bucket) {
2693
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
2694
- }
2695
- return bucket;
3078
+ return resolveBucket(perCall, this.options.bucket);
2696
3079
  }
2697
3080
  };
2698
3081
  SignedUrlService = __decorateClass([
@@ -2803,7 +3186,8 @@ var IdempotencyCache = class {
2803
3186
  };
2804
3187
 
2805
3188
  // src/server/bymax-storage.module.ts
2806
- function resolveAsyncOptions(options) {
3189
+ function resolveAsyncOptions(raw) {
3190
+ const options = snapshotOptions(raw);
2807
3191
  validateOptions(options);
2808
3192
  const resolved = applyDefaults(options);
2809
3193
  const configured = options.signedUrls?.maxTtlSeconds;