|
1 | | -import crypto from 'crypto' |
| 1 | +import { randomBytes } from 'node:crypto' |
2 | 2 |
|
3 | 3 | import type { KeystoneConfig, FilesContext } from '../../types' |
4 | 4 | import { localFileAssetsAPI } from './local' |
5 | 5 | import { s3FileAssetsAPI } from './s3' |
6 | 6 | import type { FileAdapter } from './types' |
7 | 7 |
|
8 | | -const defaultTransformName = (path: string) => { |
9 | | - // Appends a UUID to the filename so that people can't brute-force guess stored filenames |
10 | | - // |
11 | | - // This regex lazily matches for any characters that aren't a new line |
| 8 | +// appends a 128-bit random identifier to the filename to prevent guessing |
| 9 | +function defaultTransformName (path: string) { |
| 10 | + // this regex lazily matches for any characters that aren't a new line |
12 | 11 | // it then optionally matches the last instance of a "." symbol |
13 | 12 | // followed by any alphanumerical character before the end of the string |
14 | 13 | const [, name, ext] = path.match(/^([^:\n].*?)(\.[A-Za-z0-9]{0,10})?$/) as RegExpMatchArray |
15 | 14 |
|
16 | | - const id = crypto.randomBytes(12).toString('base64url').slice(0, 12) |
17 | | - |
| 15 | + const id = randomBytes(16).toString('base64url') |
18 | 16 | const urlSafeName = name.replace(/[^A-Za-z0-9]/g, '-') |
19 | 17 | if (ext) return `${urlSafeName}-${id}${ext}` |
20 | 18 | return `${urlSafeName}-${id}` |
@@ -46,11 +44,11 @@ export function createFilesContext (config: KeystoneConfig): FilesContext { |
46 | 44 | }, |
47 | 45 | getDataFromStream: async (stream, originalFilename) => { |
48 | 46 | const storageConfig = config.storage![storageString] |
49 | | - const { transformName = defaultTransformName } = storageConfig as typeof storageConfig & { |
| 47 | + const { transformName = defaultTransformName } = storageConfig as (typeof storageConfig) & { |
50 | 48 | type: 'file' |
51 | 49 | } |
52 | | - const filename = await transformName(originalFilename) |
53 | 50 |
|
| 51 | + const filename = await transformName(originalFilename) |
54 | 52 | const { filesize } = await adapter.upload(stream, filename) |
55 | 53 | return { filename, filesize } |
56 | 54 | }, |
|
0 commit comments