@prunellejs/files 0.7.3 → 0.8.0

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
@@ -20,12 +20,12 @@
20
20
  - `maxSize`: default upload size limit in bytes (falls back to `PrunelleConfig.maxRequestBodySize`, then 10 MiB). Throws `FilesError('FILE_TOO_LARGE', ..., 413)` when exceeded.
21
21
  - `allow`: allowed detected MIME types or wildcards (`'image/*'`, `'*/*'`). Default: `['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/avif', 'application/pdf']`.
22
22
  - `defaultPublic`: default visibility when `put()` omits `public` (default `false` — private by default).
23
- - `publicCacheControl` (default `'public, max-age=31536000, immutable'`) and `privateCacheControl` (default `'private, no-store'`).
23
+ - `publicCacheControl` (default `'public, max-age=31536000, immutable'` for a key `put()` generated, `'public, no-cache'` for a key you passed; setting it applies to every public file) and `privateCacheControl` (default `'private, no-store'`).
24
24
  - Refuses `prunelle build --static` with a clear error because uploads, signed private URLs, and deletions require a running server.
25
25
 
26
26
  ## Stores
27
27
 
28
- - `diskFiles(dir)`: stores objects under `<dir>/objects/<key>` and metadata under `<dir>/meta/<key>.json` (never directly served, zero sidecar key collisions), with `isInside` + symlink-chain confinement on every call.
28
+ - `diskFiles(dir)`: stores objects under `<dir>/objects/<key>` and metadata under `<dir>/meta/<key>.json` (never directly served, zero sidecar key collisions), each written `0600`, with `isInside` + symlink-chain confinement on every call.
29
29
  - `s3Files({ bucket?, region?, endpoint?, accessKeyId?, secretAccessKey?, sessionToken?, prefix?, client? })`: built directly on `Bun.S3Client` (works with AWS S3, Cloudflare R2, MinIO, Scaleway, or an injected `S3ClientLike` mock in tests).
30
30
  - `memoryFiles()`: in-memory store for dev and tests.
31
31
 
@@ -33,15 +33,16 @@
33
33
 
34
34
  - `await files.put(input, { prefix?, key?, filename?, public?, maxSize?, allow?, allowEmpty? })`: accepts `File | Blob | Uint8Array | ArrayBuffer`, sniffs real MIME from magic bytes (PNG, JPEG, GIF, WebP, AVIF, PDF, ZIP, GZIP, MP4, WebM, MP3, OGG, WAV, ICO, SVG, HTML/XML, plain UTF-8 text), refuses 0-byte files (`400`) unless `allowEmpty: true`, refuses oversized (`413`) and disallowed/unrecognized MIME (`415`), and returns the normalized `key`.
35
35
  - `await files.get(key)` / `await files.stat(key)` / `await files.list(prefix?)`.
36
- - `files.url(key)` -> `/files/<encodedKey>` (serves public files directly; private files return `403`).
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
- - `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.
36
+ - `files.url(key)` -> `/files/<encodedKey>` (serves public files directly; private files and missing keys both return `403` unsigned, so a probe cannot tell them apart; a valid signature on a missing key returns `404`).
37
+ - `files.signedUrl(key, ttl)` -> `/files/<encodedKey>?exp=<unix>&sig=<hmac>` (`ttl`: seconds or `'30s'` / `'10m'` / `'1h'` / `'7d'`). HMAC-SHA256 under `deriveKey('files-url', secret)` (from `prunelle/server`), verified in constant time; missing, tampered, or expired signatures return `403`. Links minted before this change no longer verify: mint them again.
38
+ - `await files.delete(key)` (idempotent) and `await files.deleteWhere(prefix)` (RGPD erasure on segment boundaries, e.g. `'users/42'` never touches `'users/420'`; also removes an object whose metadata is missing, and a failed `put()` removes its own object).
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
 
43
- - Sets `Content-Type` (from sniffed MIME), `X-Content-Type-Options: nosniff`, `ETag` + `If-None-Match` (`304`), and `Cache-Control` (`private, no-store` for signed/private responses; immutable public cache for public files).
44
- - Forces `Content-Disposition: attachment` and `Content-Security-Policy: default-src 'none'; sandbox` for active types (`image/svg+xml`, `text/html`, `application/xhtml+xml`, `text/xml`, `application/xml`).
43
+ - Sets `Content-Type` (from sniffed MIME), `X-Content-Type-Options: nosniff`, `ETag` + `If-None-Match` (`304`), and `Cache-Control` (`private, no-store` for signed/private responses; public files: immutable for a generated key, `public, no-cache` for an explicit one).
44
+ - One store lookup per request, body streamed. `FileStore.open?(key)` returns `{ meta, body() }` (`body()` a stream or bytes, called only on a 200); a store without it is read once through `get()`. `FileMetadata.immutable` marks generated keys.
45
+ - Forces `Content-Disposition: attachment` and `Content-Security-Policy: default-src 'none'; sandbox` for active types (`application/pdf`, `image/svg+xml`, `text/html`, `application/xhtml+xml`, `text/xml`, `application/xml`).
45
46
 
46
47
  ## Snippet
47
48
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/files",
3
- "version": "0.7.3",
3
+ "version": "0.8.0",
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.8.0"
25
25
  }
26
26
  }
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // signed private URLs, active-type hardening, and RGPD prefix erasure for Prunelle.
3
3
 
4
4
  import type { RequestContext } from 'prunelle/server'
5
- import type { FileInput, FileMetadata, Files, FilesOptions, FileStore, PutFileOptions, StoredFile, TtlInput } from './types'
5
+ import type { FileInput, FileMetadata, Files, FilesOptions, FileStore, OpenedFile, PutFileOptions, StoredFile, TtlInput } from './types'
6
6
  import { createHash, randomBytes } from 'node:crypto'
7
7
  import { definePlugin } from 'prunelle/config'
8
8
  import { nodeEnv } from 'prunelle/server'
@@ -23,6 +23,7 @@ export type {
23
23
  FilesErrorCode,
24
24
  FilesOptions,
25
25
  FileStore,
26
+ OpenedFile,
26
27
  PutFileOptions,
27
28
  S3ClientLike,
28
29
  S3FileLike,
@@ -35,9 +36,13 @@ export type {
35
36
  const DEFAULT_MAX_SIZE = 10 * 1024 * 1024 // 10 MiB
36
37
  const MIN_PROD_SECRET_BYTES = 32
37
38
  const DEFAULT_PUBLIC_CACHE_CONTROL = 'public, max-age=31536000, immutable'
39
+ // A public file under a key the app chose can be overwritten, so it is revalidated by ETag instead of held for a year.
40
+ const REVALIDATE_PUBLIC_CACHE_CONTROL = 'public, no-cache'
38
41
  const DEFAULT_PRIVATE_CACHE_CONTROL = 'private, no-store'
39
42
 
43
+ // Types a browser would run script from if it rendered them inline, PDF included through its viewer's JavaScript.
40
44
  const ACTIVE_CONTENT_TYPES = new Set([
45
+ 'application/pdf',
41
46
  'image/svg+xml',
42
47
  'text/html',
43
48
  'application/xhtml+xml',
@@ -148,25 +153,31 @@ function readServerMaxBodySize(config: Readonly<Record<string, unknown>> | undef
148
153
  return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : undefined
149
154
  }
150
155
 
151
- function buildServeResponse(
156
+ /** The store's one lookup for serving: `open()` when it has one, else `get()` whose bytes are already in hand. */
157
+ async function lookup(store: FileStore, key: string): Promise<OpenedFile | undefined> {
158
+ if (store.open !== undefined)
159
+ return await store.open(key)
160
+ const file = await store.get(key)
161
+ return file === undefined ? undefined : { meta: file, body: () => file.bytes }
162
+ }
163
+
164
+ async function buildServeResponse(
152
165
  ctx: RequestContext,
153
166
  key: string,
154
- file: StoredFile,
155
- isSignedRequest: boolean,
156
- publicCacheControl: string,
157
- privateCacheControl: string,
158
- ): Response {
159
- const quotedEtag = formatEtag(file.etag)
160
- const cacheControl = isSignedRequest || !file.public ? privateCacheControl : publicCacheControl
167
+ opened: OpenedFile,
168
+ cacheControl: string,
169
+ ): Promise<Response> {
170
+ const { meta } = opened
171
+ const quotedEtag = formatEtag(meta.etag)
161
172
  const headers = new Headers({
162
- 'content-type': file.contentType,
163
- 'content-length': String(file.size),
173
+ 'content-type': meta.contentType,
174
+ 'content-length': String(meta.size),
164
175
  'etag': quotedEtag,
165
176
  'cache-control': cacheControl,
166
177
  'x-content-type-options': 'nosniff',
167
178
  })
168
179
 
169
- if (ACTIVE_CONTENT_TYPES.has(file.contentType.toLowerCase())) {
180
+ if (ACTIVE_CONTENT_TYPES.has(meta.contentType.toLowerCase())) {
170
181
  headers.set('content-disposition', formatAttachmentDisposition(key))
171
182
  headers.set('content-security-policy', "default-src 'none'; sandbox")
172
183
  }
@@ -174,7 +185,8 @@ function buildServeResponse(
174
185
  if (etagMatches(ctx.request.headers.get('if-none-match'), quotedEtag))
175
186
  return new Response(null, { status: 304, headers })
176
187
 
177
- return new Response(new Uint8Array(file.bytes), { status: 200, headers })
188
+ const body = await opened.body()
189
+ return new Response(body instanceof Uint8Array ? new Uint8Array(body) : body, { status: 200, headers })
178
190
  }
179
191
 
180
192
  function createSecretResolver(explicitSecret: string | undefined): {
@@ -213,7 +225,8 @@ function createSecretResolver(explicitSecret: string | undefined): {
213
225
 
214
226
  interface ServeRouteDeps {
215
227
  store: FileStore
216
- publicCacheControl: string
228
+ /** Set when the app chose one `Cache-Control` for every public file. */
229
+ publicCacheControl: string | undefined
217
230
  privateCacheControl: string
218
231
  verifySignedUrl: (key: string, exp: string | number | null | undefined, sig: string | null | undefined) => boolean
219
232
  }
@@ -232,35 +245,27 @@ function createServeHandler(deps: ServeRouteDeps): (ctx: RequestContext) => Prom
232
245
  return new Response('Invalid file key', { status: 400, headers: { 'cache-control': 'no-store' } })
233
246
  }
234
247
 
235
- const meta = await deps.store.stat(key)
236
- if (meta === undefined)
237
- return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
238
-
239
248
  const expParam = ctx.url.searchParams.get('exp')
240
249
  const sigParam = ctx.url.searchParams.get('sig')
241
250
  const isSignedRequest = expParam !== null || sigParam !== null
251
+ const signatureValid = isSignedRequest && deps.verifySignedUrl(key, expParam, sigParam)
242
252
 
243
- if (!meta.public && !deps.verifySignedUrl(key, expParam, sigParam))
244
- return new Response('Forbidden', { status: 403, headers: { 'cache-control': deps.privateCacheControl } })
253
+ const opened = await lookup(deps.store, key)
254
+ // Without a valid signature a missing key and a private one answer alike, so a probe learns nothing about which keys exist.
255
+ if (opened === undefined)
256
+ return signatureValid ? new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } }) : forbidden(deps)
257
+ if (!opened.meta.public && !signatureValid)
258
+ return forbidden(deps)
245
259
 
246
- const quotedEtag = formatEtag(meta.etag)
247
- if (etagMatches(ctx.request.headers.get('if-none-match'), quotedEtag)) {
248
- const headers = new Headers({
249
- 'etag': quotedEtag,
250
- 'cache-control': isSignedRequest || !meta.public ? deps.privateCacheControl : deps.publicCacheControl,
251
- 'x-content-type-options': 'nosniff',
252
- })
253
- return new Response(null, { status: 304, headers })
254
- }
255
-
256
- const file = await deps.store.get(key)
257
- if (file === undefined)
258
- return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
259
-
260
- return buildServeResponse(ctx, key, file, isSignedRequest, deps.publicCacheControl, deps.privateCacheControl)
260
+ const publicCache = deps.publicCacheControl ?? (opened.meta.immutable === true ? DEFAULT_PUBLIC_CACHE_CONTROL : REVALIDATE_PUBLIC_CACHE_CONTROL)
261
+ return await buildServeResponse(ctx, key, opened, isSignedRequest || !opened.meta.public ? deps.privateCacheControl : publicCache)
261
262
  }
262
263
  }
263
264
 
265
+ function forbidden(deps: ServeRouteDeps): Response {
266
+ return new Response('Forbidden', { status: 403, headers: { 'cache-control': deps.privateCacheControl } })
267
+ }
268
+
264
269
  /**
265
270
  * Creates a `@prunellejs/files` plugin and storage handle.
266
271
  * Register the returned object in `prunelle.config.ts` (`plugins: [files]`) and import it in routes/actions
@@ -271,7 +276,7 @@ export function createFiles(options: FilesOptions = {}): Files {
271
276
  const basePath = normalizeBasePath(options.basePath)
272
277
  const defaultAllow = options.allow ?? DEFAULT_ALLOWED_MIMES
273
278
  const defaultPublic = options.defaultPublic ?? false
274
- const publicCacheControl = options.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL
279
+ const publicCacheControl = options.publicCacheControl
275
280
  const privateCacheControl = options.privateCacheControl ?? DEFAULT_PRIVATE_CACHE_CONTROL
276
281
  const allowMemoryInProd = options.allowMemoryInProd === true
277
282
  const now = options.now ?? (() => Date.now())
@@ -365,6 +370,7 @@ export function createFiles(options: FilesOptions = {}): Files {
365
370
  etag,
366
371
  public: isPublic,
367
372
  updatedAt: now(),
373
+ immutable: putOpts.key === undefined,
368
374
  })
369
375
 
370
376
  return key
package/src/keys.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  // Path traversal defense, key/prefix normalization, URL encoding, TTL parsing, and HMAC URL signing.
2
2
 
3
3
  import type { TtlInput } from './types'
4
- import { createHmac } from 'node:crypto'
5
- import { safeEqual } from 'prunelle/server'
4
+ import { deriveKey, safeEqual } from 'prunelle/server'
6
5
  import { FilesError } from './types'
7
6
 
7
+ const SIGNING_PURPOSE = 'files-url'
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)
@@ -160,9 +174,9 @@ export function parseTtlSeconds(ttl: TtlInput): number {
160
174
  throw new FilesError('INVALID_TTL', '@prunellejs/files: TTL must be a number of seconds or a duration string.', 400)
161
175
  }
162
176
 
163
- /** Computes a URL-safe base64 HMAC-SHA256 signature binding `key` and expiry timestamp `expUnixSec`. */
177
+ /** Computes a URL-safe base64 HMAC-SHA256 signature binding `key` and expiry timestamp `expUnixSec`, under a key derived from `secret` for file URLs alone. */
164
178
  export function signFileUrl(key: string, expUnixSec: number, secret: string): string {
165
- return createHmac('sha256', secret)
179
+ return new Bun.CryptoHasher('sha256', deriveKey(SIGNING_PURPOSE, secret))
166
180
  .update(`${expUnixSec}\n${key}`)
167
181
  .digest('base64url')
168
182
  }
package/src/stores.ts CHANGED
@@ -1,24 +1,15 @@
1
1
  // Storage backends for `@prunellejs/files`: `memoryFiles`, `diskFiles`, and `s3Files` (built on Bun's native S3Client).
2
2
 
3
3
  import type { S3Options } from 'bun'
4
- import type { FileMetadata, FilePutRecord, FileStore, S3ClientLike, S3FilesOptions, StoredFile } from './types'
4
+ import type { FileMetadata, FilePutRecord, FileStore, OpenedFile, S3ClientLike, S3FilesOptions, StoredFile } from './types'
5
5
  import { randomBytes } from 'node:crypto'
6
6
  import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs'
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
- interface SerializedMeta {
14
- key: string
15
- contentType: string
16
- size: number
17
- etag: string
18
- public: boolean
19
- updatedAt: number
20
- }
21
-
22
13
  function toMeta(record: FileMetadata): FileMetadata {
23
14
  return {
24
15
  key: record.key,
@@ -27,9 +18,14 @@ function toMeta(record: FileMetadata): FileMetadata {
27
18
  etag: record.etag,
28
19
  public: record.public,
29
20
  updatedAt: record.updatedAt,
21
+ ...(record.immutable === true ? { immutable: true } : {}),
30
22
  }
31
23
  }
32
24
 
25
+ function serializeMeta(record: FilePutRecord): string {
26
+ return JSON.stringify(toMeta({ ...record, size: record.bytes.byteLength }))
27
+ }
28
+
33
29
  function parseMetaJson(raw: string): FileMetadata | undefined {
34
30
  let parsed: unknown
35
31
  try {
@@ -51,14 +47,15 @@ function parseMetaJson(raw: string): FileMetadata | undefined {
51
47
  ) {
52
48
  return undefined
53
49
  }
54
- return {
50
+ return toMeta({
55
51
  key: obj.key,
56
52
  contentType: obj.contentType,
57
53
  size: obj.size,
58
54
  etag: obj.etag,
59
55
  public: obj.public,
60
56
  updatedAt: obj.updatedAt,
61
- }
57
+ immutable: obj.immutable === true,
58
+ })
62
59
  }
63
60
 
64
61
  function isEnoent(error: unknown): boolean {
@@ -68,6 +65,25 @@ function isEnoent(error: unknown): boolean {
68
65
  return code === 'ENOENT' || code === 'ENOTDIR'
69
66
  }
70
67
 
68
+ function isMissingOrDir(error: unknown): boolean {
69
+ if (isEnoent(error))
70
+ return true
71
+ if (error === null || typeof error !== 'object')
72
+ return false
73
+ return (error as { code?: unknown }).code === 'EISDIR'
74
+ }
75
+
76
+ function isRegularFile(path: string): boolean {
77
+ try {
78
+ return lstatSync(path).isFile()
79
+ }
80
+ catch (error) {
81
+ if (isEnoent(error))
82
+ return false
83
+ throw error
84
+ }
85
+ }
86
+
71
87
  function isS3NotFound(error: unknown): boolean {
72
88
  if (error === null || typeof error !== 'object')
73
89
  return false
@@ -87,16 +103,12 @@ export function memoryFiles(): FileStore {
87
103
  kind: 'memory',
88
104
  put(record: FilePutRecord): void {
89
105
  const key = normalizeFileKey(record.key)
106
+ for (const existing of entries.keys()) {
107
+ if (keysConflict(existing, key))
108
+ throw new FilesError('INVALID_KEY', `@prunellejs/files: key "${key}" conflicts with existing key "${existing}".`, 409)
109
+ }
90
110
  const bytes = new Uint8Array(record.bytes)
91
- entries.set(key, {
92
- key,
93
- bytes,
94
- contentType: record.contentType,
95
- size: bytes.byteLength,
96
- etag: record.etag,
97
- public: record.public,
98
- updatedAt: record.updatedAt,
99
- })
111
+ entries.set(key, { ...toMeta({ ...record, key, size: bytes.byteLength }), bytes })
100
112
  },
101
113
  get(key: string): StoredFile | undefined {
102
114
  const norm = normalizeFileKey(key)
@@ -105,6 +117,10 @@ export function memoryFiles(): FileStore {
105
117
  return undefined
106
118
  return { ...found, bytes: new Uint8Array(found.bytes) }
107
119
  },
120
+ open(key: string): OpenedFile | undefined {
121
+ const found = entries.get(normalizeFileKey(key))
122
+ return found === undefined ? undefined : { meta: toMeta(found), body: () => found.bytes }
123
+ },
108
124
  stat(key: string): FileMetadata | undefined {
109
125
  const norm = normalizeFileKey(key)
110
126
  const found = entries.get(norm)
@@ -166,11 +182,40 @@ function resolveDiskPath(baseDir: string, relKey: string): string {
166
182
  return target
167
183
  }
168
184
 
169
- function writeFileAtomic(targetPath: string, data: Uint8Array | string): void {
185
+ function assertNoDiskConflict(baseDir: string, relPath: string, key: string): void {
186
+ if (!existsSync(baseDir))
187
+ return
188
+ const parts = relPath.split('/')
189
+ let current = baseDir
190
+ for (let i = 0; i < parts.length - 1; i++) {
191
+ current = join(current, parts[i]!)
192
+ if (!existsSync(current))
193
+ return
194
+ const st = lstatSync(current)
195
+ if (!st.isDirectory()) {
196
+ throw new FilesError(
197
+ 'INVALID_KEY',
198
+ `@prunellejs/files: key "${key}" conflicts with an existing key at "${parts.slice(0, i + 1).join('/')}".`,
199
+ 409,
200
+ )
201
+ }
202
+ }
203
+ const target = join(current, parts[parts.length - 1]!)
204
+ if (existsSync(target) && lstatSync(target).isDirectory()) {
205
+ throw new FilesError(
206
+ 'INVALID_KEY',
207
+ `@prunellejs/files: key "${key}" conflicts with existing keys under "${relPath}/".`,
208
+ 409,
209
+ )
210
+ }
211
+ }
212
+
213
+ function writeFileAtomic(tmpDir: string, targetPath: string, data: Uint8Array | string): void {
170
214
  const parent = dirname(targetPath)
171
215
  mkdirSync(parent, { recursive: true })
172
- const tmpPath = join(parent, `.tmp-${randomBytes(8).toString('hex')}`)
173
- writeFileSync(tmpPath, data)
216
+ mkdirSync(tmpDir, { recursive: true })
217
+ const tmpPath = join(tmpDir, `${randomBytes(12).toString('hex')}.tmp`)
218
+ writeFileSync(tmpPath, data, { mode: 0o600 })
174
219
  try {
175
220
  renameSync(tmpPath, targetPath)
176
221
  }
@@ -188,6 +233,8 @@ function writeFileAtomic(targetPath: string, data: Uint8Array | string): void {
188
233
 
189
234
  function removeFileIfExists(path: string): boolean {
190
235
  try {
236
+ if (lstatSync(path).isDirectory())
237
+ return false
191
238
  unlinkSync(path)
192
239
  return true
193
240
  }
@@ -229,7 +276,7 @@ function collectDiskMeta(dir: string, realMetaRoot: string, normalizedPrefix: st
229
276
 
230
277
  for (let i = 0; i < entries.length; i++) {
231
278
  const entry = entries[i]!
232
- if (entry.isSymbolicLink() || entry.name.startsWith('.tmp-'))
279
+ if (entry.isSymbolicLink())
233
280
  continue
234
281
  const full = join(dir, entry.name)
235
282
  const realFull = realpathSync(full)
@@ -247,6 +294,21 @@ function collectDiskMeta(dir: string, realMetaRoot: string, normalizedPrefix: st
247
294
  }
248
295
  }
249
296
 
297
+ function collectDiskObjectKeys(root: string, dir: string, normalizedPrefix: string, out: Set<string>): void {
298
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
299
+ if (entry.isSymbolicLink())
300
+ continue
301
+ const full = join(dir, entry.name)
302
+ if (entry.isDirectory()) {
303
+ collectDiskObjectKeys(root, full, normalizedPrefix, out)
304
+ continue
305
+ }
306
+ const key = full.slice(root.length + 1).split(/[/\\]/).join('/')
307
+ if (entry.isFile() && keyMatchesPrefix(key, normalizedPrefix))
308
+ out.add(key)
309
+ }
310
+ }
311
+
250
312
  /**
251
313
  * Local disk storage under `dir`.
252
314
  * Stores objects under `<dir>/objects/<key>` and metadata under `<dir>/meta/<key>.json` so metadata
@@ -259,6 +321,7 @@ export function diskFiles(dir: string): FileStore {
259
321
  const rootDir = resolve(dir)
260
322
  const objectsDir = join(rootDir, 'objects')
261
323
  const metaDir = join(rootDir, 'meta')
324
+ const tmpDir = join(rootDir, '.tmp')
262
325
 
263
326
  const readDiskMeta = (normKey: string): FileMetadata | undefined => {
264
327
  const metaPath = resolveDiskPath(metaDir, `${normKey}.json`)
@@ -266,7 +329,7 @@ export function diskFiles(dir: string): FileStore {
266
329
  return parseMetaJson(readFileSync(metaPath, 'utf8'))
267
330
  }
268
331
  catch (error) {
269
- if (isEnoent(error))
332
+ if (isMissingOrDir(error))
270
333
  return undefined
271
334
  throw error
272
335
  }
@@ -288,21 +351,27 @@ export function diskFiles(dir: string): FileStore {
288
351
  kind: 'disk',
289
352
  put(record: FilePutRecord): void {
290
353
  const key = normalizeFileKey(record.key)
291
- mkdirSync(objectsDir, { recursive: true })
292
- mkdirSync(metaDir, { recursive: true })
293
354
  const objectPath = resolveDiskPath(objectsDir, key)
294
355
  const metaPath = resolveDiskPath(metaDir, `${key}.json`)
356
+ resolveDiskPath(rootDir, '.tmp')
357
+ assertNoDiskConflict(objectsDir, key, key)
358
+ assertNoDiskConflict(metaDir, `${key}.json`, key)
359
+
360
+ mkdirSync(objectsDir, { recursive: true })
361
+ mkdirSync(metaDir, { recursive: true })
295
362
 
296
- writeFileAtomic(objectPath, record.bytes)
297
- const serialized: SerializedMeta = {
298
- key,
299
- contentType: record.contentType,
300
- size: record.bytes.byteLength,
301
- etag: record.etag,
302
- public: record.public,
303
- updatedAt: record.updatedAt,
363
+ const existedBefore = isRegularFile(objectPath)
364
+ writeFileAtomic(tmpDir, objectPath, record.bytes)
365
+ try {
366
+ writeFileAtomic(tmpDir, metaPath, serializeMeta({ ...record, key }))
367
+ }
368
+ catch (error) {
369
+ if (!existedBefore) {
370
+ removeFileIfExists(objectPath)
371
+ pruneEmptyDirs(dirname(objectPath), objectsDir)
372
+ }
373
+ throw error
304
374
  }
305
- writeFileAtomic(metaPath, JSON.stringify(serialized))
306
375
  },
307
376
  get(key: string): StoredFile | undefined {
308
377
  const norm = normalizeFileKey(key)
@@ -315,18 +384,37 @@ 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
  }
322
391
  },
392
+ open(key: string): OpenedFile | undefined {
393
+ const norm = normalizeFileKey(key)
394
+ const meta = readDiskMeta(norm)
395
+ if (meta === undefined)
396
+ return undefined
397
+ const objectPath = resolveDiskPath(objectsDir, norm)
398
+ let info
399
+ try {
400
+ info = lstatSync(objectPath)
401
+ }
402
+ catch (error) {
403
+ if (isMissingOrDir(error))
404
+ return undefined
405
+ throw error
406
+ }
407
+ if (!info.isFile())
408
+ return undefined
409
+ return { meta: { ...meta, size: info.size }, body: () => Bun.file(objectPath).stream() }
410
+ },
323
411
  stat(key: string): FileMetadata | undefined {
324
412
  const norm = normalizeFileKey(key)
325
413
  const meta = readDiskMeta(norm)
326
414
  if (meta === undefined)
327
415
  return undefined
328
416
  const objectPath = resolveDiskPath(objectsDir, norm)
329
- return existsSync(objectPath) ? meta : undefined
417
+ return isRegularFile(objectPath) ? meta : undefined
330
418
  },
331
419
  delete(key: string): boolean {
332
420
  return removeOne(normalizeFileKey(key))
@@ -343,14 +431,19 @@ export function diskFiles(dir: string): FileStore {
343
431
  },
344
432
  deleteWhere(prefix: string): number {
345
433
  const norm = normalizeFilePrefix(prefix, { allowEmpty: false })
346
- if (!existsSync(metaDir))
347
- return 0
348
- const realMetaRoot = realpathSync(metaDir)
349
- const matching: FileMetadata[] = []
350
- collectDiskMeta(metaDir, realMetaRoot, norm, matching)
434
+ // An object whose metadata never landed (a crash between the two writes) has no meta file to find it by, so the objects are walked too.
435
+ const keys = new Set<string>()
436
+ if (existsSync(metaDir)) {
437
+ const matching: FileMetadata[] = []
438
+ collectDiskMeta(metaDir, realpathSync(metaDir), norm, matching)
439
+ for (const meta of matching)
440
+ keys.add(meta.key)
441
+ }
442
+ if (existsSync(objectsDir))
443
+ collectDiskObjectKeys(objectsDir, objectsDir, norm, keys)
351
444
  let removed = 0
352
- for (let i = 0; i < matching.length; i++) {
353
- if (removeOne(matching[i]!.key))
445
+ for (const key of keys) {
446
+ if (removeOne(key))
354
447
  removed++
355
448
  }
356
449
  return removed
@@ -389,11 +482,8 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
389
482
  const metaKey = (normKey: string): string => `${basePrefix}meta/${normKey}.json`
390
483
 
391
484
  const readS3Meta = async (normKey: string): Promise<FileMetadata | undefined> => {
392
- const file = client.file(metaKey(normKey))
393
- if (!(await file.exists()))
394
- return undefined
395
485
  try {
396
- return parseMetaJson(await file.text())
486
+ return parseMetaJson(await client.file(metaKey(normKey)).text())
397
487
  }
398
488
  catch (error) {
399
489
  if (isS3NotFound(error))
@@ -402,25 +492,32 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
402
492
  }
403
493
  }
404
494
 
405
- const listS3Meta = async (normPrefix: string): Promise<FileMetadata[]> => {
406
- const metaBase = `${basePrefix}meta/`
407
- const searchPrefix = normPrefix.length > 0 ? `${metaBase}${normPrefix}` : metaBase
408
- const metaPaths: string[] = []
495
+ const listS3Paths = async (searchPrefix: string): Promise<string[]> => {
496
+ const paths: string[] = []
409
497
  let continuationToken: string | undefined
410
-
411
498
  for (;;) {
412
499
  const input: { prefix?: string, continuationToken?: string } = { prefix: searchPrefix }
413
500
  if (continuationToken !== undefined)
414
501
  input.continuationToken = continuationToken
415
502
  const page = await client.list(input)
416
- for (const item of page.contents ?? []) {
417
- if (item.key.endsWith('.json'))
418
- metaPaths.push(item.key)
419
- }
503
+ for (const item of page.contents ?? [])
504
+ paths.push(item.key)
420
505
  if (page.isTruncated !== true || page.nextContinuationToken === undefined)
421
- break
506
+ return paths
422
507
  continuationToken = page.nextContinuationToken
423
508
  }
509
+ }
510
+
511
+ // An object whose metadata never landed has no meta file to be found by, so deleteWhere lists the objects as well.
512
+ const listS3ObjectKeys = async (normPrefix: string): Promise<string[]> => {
513
+ const objectBase = `${basePrefix}objects/`
514
+ const paths = await listS3Paths(normPrefix.length > 0 ? `${objectBase}${normPrefix}` : objectBase)
515
+ return paths.map(path => path.slice(objectBase.length)).filter(key => keyMatchesPrefix(key, normPrefix))
516
+ }
517
+
518
+ const listS3Meta = async (normPrefix: string): Promise<FileMetadata[]> => {
519
+ const metaBase = `${basePrefix}meta/`
520
+ const metaPaths = (await listS3Paths(normPrefix.length > 0 ? `${metaBase}${normPrefix}` : metaBase)).filter(path => path.endsWith('.json'))
424
521
 
425
522
  const out: FileMetadata[] = []
426
523
  for (let i = 0; i < metaPaths.length; i++) {
@@ -458,16 +555,29 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
458
555
  kind: 's3',
459
556
  async put(record: FilePutRecord): Promise<void> {
460
557
  const key = normalizeFileKey(record.key)
558
+ const existedBefore = await client.file(objectKey(key)).exists()
461
559
  await client.file(objectKey(key), { type: record.contentType }).write(record.bytes, { type: record.contentType })
462
- const serialized: SerializedMeta = {
463
- key,
464
- contentType: record.contentType,
465
- size: record.bytes.byteLength,
466
- etag: record.etag,
467
- public: record.public,
468
- updatedAt: record.updatedAt,
560
+ try {
561
+ await client.file(metaKey(key), { type: 'application/json' }).write(serializeMeta({ ...record, key }), { type: 'application/json' })
562
+ }
563
+ catch (error) {
564
+ if (!existedBefore)
565
+ await client.delete(objectKey(key)).catch((cleanupError: unknown) => {
566
+ throw new AggregateError([error, cleanupError], `@prunellejs/files: the metadata of "${key}" was not written and its object could not be removed, so it stays until deleteWhere erases it`)
567
+ })
568
+ throw error
569
+ }
570
+ },
571
+ async open(key: string): Promise<OpenedFile | undefined> {
572
+ const norm = normalizeFileKey(key)
573
+ const meta = await readS3Meta(norm)
574
+ if (meta === undefined)
575
+ return undefined
576
+ const file = client.file(objectKey(norm))
577
+ return {
578
+ meta,
579
+ body: () => file.stream !== undefined ? file.stream() : file.arrayBuffer().then(buffer => new Uint8Array(buffer)),
469
580
  }
470
- await client.file(metaKey(key), { type: 'application/json' }).write(JSON.stringify(serialized), { type: 'application/json' })
471
581
  },
472
582
  async get(key: string): Promise<StoredFile | undefined> {
473
583
  const norm = normalizeFileKey(key)
@@ -501,10 +611,13 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
501
611
  return await listS3Meta(normalizeFilePrefix(prefix, { allowEmpty: true }))
502
612
  },
503
613
  async deleteWhere(prefix: string): Promise<number> {
504
- const items = await listS3Meta(normalizeFilePrefix(prefix, { allowEmpty: false }))
614
+ const norm = normalizeFilePrefix(prefix, { allowEmpty: false })
615
+ const keys = new Set((await listS3Meta(norm)).map(meta => meta.key))
616
+ for (const key of await listS3ObjectKeys(norm))
617
+ keys.add(key)
505
618
  let removed = 0
506
- for (let i = 0; i < items.length; i++) {
507
- if (await deleteS3Pair(items[i]!.key))
619
+ for (const key of keys) {
620
+ if (await deleteS3Pair(key))
508
621
  removed++
509
622
  }
510
623
  return removed
package/src/types.ts CHANGED
@@ -36,6 +36,8 @@ export interface FileMetadata {
36
36
  readonly etag: string
37
37
  readonly public: boolean
38
38
  readonly updatedAt: number
39
+ /** The key was generated by `put()` and never rewritten, so a public response may be cached as immutable. Absent on an older record or a store that drops it: revalidated instead. */
40
+ readonly immutable?: boolean | undefined
39
41
  }
40
42
 
41
43
  export interface StoredFile extends FileMetadata {
@@ -49,12 +51,21 @@ export interface FilePutRecord {
49
51
  readonly etag: string
50
52
  readonly public: boolean
51
53
  readonly updatedAt: number
54
+ readonly immutable?: boolean | undefined
55
+ }
56
+
57
+ /** A file found by `FileStore.open()`: its metadata now, its bytes only when `body()` is called. */
58
+ export interface OpenedFile {
59
+ readonly meta: FileMetadata
60
+ body(): ReadableStream<Uint8Array> | Uint8Array | Promise<ReadableStream<Uint8Array> | Uint8Array>
52
61
  }
53
62
 
54
63
  export interface FileStore {
55
64
  readonly kind?: 'memory' | 'disk' | 's3' | string | undefined
56
65
  put(record: FilePutRecord): Promise<void> | void
57
66
  get(key: string): Promise<StoredFile | undefined> | StoredFile | undefined
67
+ /** One lookup for serving: the metadata, and a body opened only when asked for (a stream where the store can). Without it the server falls back to `get()`. */
68
+ open?(key: string): Promise<OpenedFile | undefined> | OpenedFile | undefined
58
69
  stat(key: string): Promise<FileMetadata | undefined> | FileMetadata | undefined
59
70
  delete(key: string): Promise<boolean> | boolean
60
71
  list(prefix?: string): Promise<readonly FileMetadata[]> | readonly FileMetadata[]
@@ -66,6 +77,8 @@ export interface S3FileLike {
66
77
  exists(): Promise<boolean>
67
78
  arrayBuffer(): Promise<ArrayBuffer>
68
79
  text(): Promise<string>
80
+ /** Streams the object; `s3Files()` falls back to `arrayBuffer()` when a mock has none. */
81
+ stream?(): ReadableStream<Uint8Array>
69
82
  write(data: Uint8Array | string, options?: { type?: string }): Promise<number>
70
83
  delete(): Promise<void>
71
84
  }