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