@prunellejs/files 0.7.3 → 0.7.4

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.
package/llms.txt CHANGED
@@ -36,7 +36,7 @@
36
36
  - `files.url(key)` -> `/files/<encodedKey>` (serves public files directly; private files return `403`).
37
37
  - `files.signedUrl(key, ttl)` -> `/files/<encodedKey>?exp=<unix>&sig=<hmac>` (`ttl`: seconds or `'30s'` / `'10m'` / `'1h'` / `'7d'`). Verified in constant time; missing, tampered, or expired signatures return `403`.
38
38
  - `await files.delete(key)` (idempotent) and `await files.deleteWhere(prefix)` (RGPD erasure on segment boundaries, e.g. `'users/42'` never touches `'users/420'`).
39
- - Path traversal defense: `../`, `..\`, leading `/`, NUL/control chars, backslashes, `.` / `..`, and single- or multi-encoded `%2e%2e`, `%252e%252e`, `%2f`, `%5c`, `%00` are rejected everywhere.
39
+ - Path traversal & key limits: `../`, `..\`, leading `/`, NUL/control chars, backslashes, `.` / `..`, segments over 240 UTF-8 bytes, and single- or multi-encoded `%2e%2e`, `%252e%252e`, `%2f`, `%5c`, `%00` are rejected everywhere; conflicting file/prefix keys (e.g. `col` and `col/b`, or `m` and `m.json/x`) fail with `FilesError('INVALID_KEY', ..., 409)` on both `memoryFiles` and `diskFiles`.
40
40
 
41
41
  ## HTTP Serving (`GET ${basePath}/*key`)
42
42
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/files",
3
- "version": "0.7.3",
3
+ "version": "0.7.4",
4
4
  "description": "Zero-dependency file upload storage (disk, Bun S3, memory), magic-byte MIME sniffing, signed private URLs, and RGPD erasure plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-files"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.7.3"
24
+ "prunelle": "^0.7.4"
25
25
  }
26
26
  }
package/src/keys.ts CHANGED
@@ -6,6 +6,8 @@ import { safeEqual } from 'prunelle/server'
6
6
  import { FilesError } from './types'
7
7
 
8
8
  const MAX_KEY_LENGTH = 1024
9
+ // POSIX NAME_MAX is 255 UTF-8 bytes and disk metadata appends `.json` (5 bytes); capping each segment at 240 UTF-8 bytes keeps memory and disk aligned.
10
+ const MAX_SEGMENT_BYTES = 240
9
11
  const MAX_DECODE_PASSES = 6
10
12
  // Matches ASCII C0 controls (including NUL 0x00) and DEL (0x7f).
11
13
  // eslint-disable-next-line no-control-regex
@@ -39,6 +41,8 @@ function safeDecodeOnce(value: string): string {
39
41
  function assertSafeSegment(segment: string, label: string): void {
40
42
  if (segment.length === 0)
41
43
  invalidKey(label, 'empty path segment is not allowed')
44
+ if (Buffer.byteLength(segment, 'utf8') > MAX_SEGMENT_BYTES)
45
+ invalidKey(label, `segment exceeds ${MAX_SEGMENT_BYTES} UTF-8 bytes`)
42
46
  if (segment === '.' || segment === '..')
43
47
  invalidKey(label, 'path traversal segment ("." or "..") is not allowed')
44
48
  if (ENCODED_DOT_TOKEN_RE.test(segment))
@@ -123,6 +127,16 @@ export function keyMatchesPrefix(key: string, normalizedPrefix: string): boolean
123
127
  return key === normalizedPrefix || key.startsWith(`${normalizedPrefix}/`)
124
128
  }
125
129
 
130
+ /** Returns `true` when two distinct normalized keys would collide in hierarchical object or `.json` metadata trees. */
131
+ export function keysConflict(a: string, b: string): boolean {
132
+ if (a === b)
133
+ return false
134
+ return b.startsWith(`${a}/`)
135
+ || a.startsWith(`${b}/`)
136
+ || b.startsWith(`${a}.json/`)
137
+ || a.startsWith(`${b}.json/`)
138
+ }
139
+
126
140
  /** Validates `key` and percent-encodes each path segment for safe inclusion in a URL pathname. */
127
141
  export function encodeKeySegments(key: string): string {
128
142
  const normalized = normalizeFileKey(key)
package/src/stores.ts CHANGED
@@ -7,7 +7,7 @@ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSy
7
7
  import { dirname, join, resolve } from 'node:path'
8
8
  import { S3Client } from 'bun'
9
9
  import { isInside } from 'prunelle/config'
10
- import { keyMatchesPrefix, normalizeFileKey, normalizeFilePrefix } from './keys'
10
+ import { keyMatchesPrefix, keysConflict, normalizeFileKey, normalizeFilePrefix } from './keys'
11
11
  import { FilesError } from './types'
12
12
 
13
13
  interface SerializedMeta {
@@ -68,6 +68,25 @@ function isEnoent(error: unknown): boolean {
68
68
  return code === 'ENOENT' || code === 'ENOTDIR'
69
69
  }
70
70
 
71
+ function isMissingOrDir(error: unknown): boolean {
72
+ if (isEnoent(error))
73
+ return true
74
+ if (error === null || typeof error !== 'object')
75
+ return false
76
+ return (error as { code?: unknown }).code === 'EISDIR'
77
+ }
78
+
79
+ function isRegularFile(path: string): boolean {
80
+ try {
81
+ return lstatSync(path).isFile()
82
+ }
83
+ catch (error) {
84
+ if (isEnoent(error))
85
+ return false
86
+ throw error
87
+ }
88
+ }
89
+
71
90
  function isS3NotFound(error: unknown): boolean {
72
91
  if (error === null || typeof error !== 'object')
73
92
  return false
@@ -87,6 +106,10 @@ export function memoryFiles(): FileStore {
87
106
  kind: 'memory',
88
107
  put(record: FilePutRecord): void {
89
108
  const key = normalizeFileKey(record.key)
109
+ for (const existing of entries.keys()) {
110
+ if (keysConflict(existing, key))
111
+ throw new FilesError('INVALID_KEY', `@prunellejs/files: key "${key}" conflicts with existing key "${existing}".`, 409)
112
+ }
90
113
  const bytes = new Uint8Array(record.bytes)
91
114
  entries.set(key, {
92
115
  key,
@@ -166,10 +189,39 @@ function resolveDiskPath(baseDir: string, relKey: string): string {
166
189
  return target
167
190
  }
168
191
 
169
- function writeFileAtomic(targetPath: string, data: Uint8Array | string): void {
192
+ function assertNoDiskConflict(baseDir: string, relPath: string, key: string): void {
193
+ if (!existsSync(baseDir))
194
+ return
195
+ const parts = relPath.split('/')
196
+ let current = baseDir
197
+ for (let i = 0; i < parts.length - 1; i++) {
198
+ current = join(current, parts[i]!)
199
+ if (!existsSync(current))
200
+ return
201
+ const st = lstatSync(current)
202
+ if (!st.isDirectory()) {
203
+ throw new FilesError(
204
+ 'INVALID_KEY',
205
+ `@prunellejs/files: key "${key}" conflicts with an existing key at "${parts.slice(0, i + 1).join('/')}".`,
206
+ 409,
207
+ )
208
+ }
209
+ }
210
+ const target = join(current, parts[parts.length - 1]!)
211
+ if (existsSync(target) && lstatSync(target).isDirectory()) {
212
+ throw new FilesError(
213
+ 'INVALID_KEY',
214
+ `@prunellejs/files: key "${key}" conflicts with existing keys under "${relPath}/".`,
215
+ 409,
216
+ )
217
+ }
218
+ }
219
+
220
+ function writeFileAtomic(tmpDir: string, targetPath: string, data: Uint8Array | string): void {
170
221
  const parent = dirname(targetPath)
171
222
  mkdirSync(parent, { recursive: true })
172
- const tmpPath = join(parent, `.tmp-${randomBytes(8).toString('hex')}`)
223
+ mkdirSync(tmpDir, { recursive: true })
224
+ const tmpPath = join(tmpDir, `${randomBytes(12).toString('hex')}.tmp`)
173
225
  writeFileSync(tmpPath, data)
174
226
  try {
175
227
  renameSync(tmpPath, targetPath)
@@ -188,6 +240,8 @@ function writeFileAtomic(targetPath: string, data: Uint8Array | string): void {
188
240
 
189
241
  function removeFileIfExists(path: string): boolean {
190
242
  try {
243
+ if (lstatSync(path).isDirectory())
244
+ return false
191
245
  unlinkSync(path)
192
246
  return true
193
247
  }
@@ -229,7 +283,7 @@ function collectDiskMeta(dir: string, realMetaRoot: string, normalizedPrefix: st
229
283
 
230
284
  for (let i = 0; i < entries.length; i++) {
231
285
  const entry = entries[i]!
232
- if (entry.isSymbolicLink() || entry.name.startsWith('.tmp-'))
286
+ if (entry.isSymbolicLink())
233
287
  continue
234
288
  const full = join(dir, entry.name)
235
289
  const realFull = realpathSync(full)
@@ -259,6 +313,7 @@ export function diskFiles(dir: string): FileStore {
259
313
  const rootDir = resolve(dir)
260
314
  const objectsDir = join(rootDir, 'objects')
261
315
  const metaDir = join(rootDir, 'meta')
316
+ const tmpDir = join(rootDir, '.tmp')
262
317
 
263
318
  const readDiskMeta = (normKey: string): FileMetadata | undefined => {
264
319
  const metaPath = resolveDiskPath(metaDir, `${normKey}.json`)
@@ -266,7 +321,7 @@ export function diskFiles(dir: string): FileStore {
266
321
  return parseMetaJson(readFileSync(metaPath, 'utf8'))
267
322
  }
268
323
  catch (error) {
269
- if (isEnoent(error))
324
+ if (isMissingOrDir(error))
270
325
  return undefined
271
326
  throw error
272
327
  }
@@ -288,12 +343,17 @@ export function diskFiles(dir: string): FileStore {
288
343
  kind: 'disk',
289
344
  put(record: FilePutRecord): void {
290
345
  const key = normalizeFileKey(record.key)
291
- mkdirSync(objectsDir, { recursive: true })
292
- mkdirSync(metaDir, { recursive: true })
293
346
  const objectPath = resolveDiskPath(objectsDir, key)
294
347
  const metaPath = resolveDiskPath(metaDir, `${key}.json`)
348
+ resolveDiskPath(rootDir, '.tmp')
349
+ assertNoDiskConflict(objectsDir, key, key)
350
+ assertNoDiskConflict(metaDir, `${key}.json`, key)
295
351
 
296
- writeFileAtomic(objectPath, record.bytes)
352
+ mkdirSync(objectsDir, { recursive: true })
353
+ mkdirSync(metaDir, { recursive: true })
354
+
355
+ const existedBefore = isRegularFile(objectPath)
356
+ writeFileAtomic(tmpDir, objectPath, record.bytes)
297
357
  const serialized: SerializedMeta = {
298
358
  key,
299
359
  contentType: record.contentType,
@@ -302,7 +362,16 @@ export function diskFiles(dir: string): FileStore {
302
362
  public: record.public,
303
363
  updatedAt: record.updatedAt,
304
364
  }
305
- writeFileAtomic(metaPath, JSON.stringify(serialized))
365
+ try {
366
+ writeFileAtomic(tmpDir, metaPath, JSON.stringify(serialized))
367
+ }
368
+ catch (error) {
369
+ if (!existedBefore) {
370
+ removeFileIfExists(objectPath)
371
+ pruneEmptyDirs(dirname(objectPath), objectsDir)
372
+ }
373
+ throw error
374
+ }
306
375
  },
307
376
  get(key: string): StoredFile | undefined {
308
377
  const norm = normalizeFileKey(key)
@@ -315,7 +384,7 @@ export function diskFiles(dir: string): FileStore {
315
384
  return { ...meta, bytes, size: bytes.byteLength }
316
385
  }
317
386
  catch (error) {
318
- if (isEnoent(error))
387
+ if (isMissingOrDir(error))
319
388
  return undefined
320
389
  throw error
321
390
  }
@@ -326,7 +395,7 @@ export function diskFiles(dir: string): FileStore {
326
395
  if (meta === undefined)
327
396
  return undefined
328
397
  const objectPath = resolveDiskPath(objectsDir, norm)
329
- return existsSync(objectPath) ? meta : undefined
398
+ return isRegularFile(objectPath) ? meta : undefined
330
399
  },
331
400
  delete(key: string): boolean {
332
401
  return removeOne(normalizeFileKey(key))