From 116130cc4324b778188425e53e6f4922937c34d5 Mon Sep 17 00:00:00 2001 From: SAY-5 Date: Wed, 15 Apr 2026 01:52:44 -0700 Subject: [PATCH] docs: use crypto.randomBytes for custom filename example (#1386) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The custom `diskStorage` example in the README used `Date.now() + Math.round(Math.random() * 1E9)` to build a unique filename suffix, which is exactly the pattern production apps copy when they need a custom `filename` (e.g. to preserve a file extension). `Math.random()` is not cryptographically secure — V8's xorshift128+ state can be recovered from a small sample of outputs — and combined with `Date.now()` the entropy is effectively ~30 bits, which is enumerable when uploads land in a web-accessible directory. Multer's built-in default already uses `crypto.randomBytes(16)` (`storage/disk.js:6-9`). Update the README to teach the same pattern so copy-paste users get the secure default by construction. No code changes. Docs only. --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 630a495a..41942cdc 100644 --- a/README.md +++ b/README.md @@ -207,12 +207,17 @@ where you are handling the uploaded files. The disk storage engine gives you full control on storing files to disk. ```javascript +const crypto = require('crypto') + const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, '/tmp/my-uploads') }, filename: function (req, file, cb) { - const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) + // Use a cryptographically strong suffix so filenames cannot be + // guessed or enumerated from a weak PRNG like `Math.random()`. The + // built-in `DiskStorage` default uses the same approach. + const uniqueSuffix = crypto.randomBytes(16).toString('hex') cb(null, file.fieldname + '-' + uniqueSuffix) } })