@prunellejs/files 0.0.0-stage → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt ADDED
@@ -0,0 +1,63 @@
1
+ # @prunellejs/files Reference
2
+
3
+ > Zero-dependency file upload storage (local disk, Bun's native `S3Client`, and in-memory), magic-byte MIME sniffing, time-limited HMAC-SHA256 signed URLs for private files, active-content hardening, and RGPD prefix erasure.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/files`:
8
+ - Core: `createFiles`, `FilesError`
9
+ - Stores: `diskFiles`, `s3Files`, `memoryFiles`
10
+ - Helpers: `sniffMime`, `mimeMatchesAllowlist`, `extensionForMime`, `DEFAULT_ALLOWED_MIMES`, `normalizeFileKey`, `normalizeFilePrefix`, `encodeKeySegments`, `parseTtlSeconds`
11
+ - Types: `Files`, `FilesOptions`, `PutFileOptions`, `FileInput`, `FileStore`, `FileMetadata`, `StoredFile`, `FilePutRecord`, `S3FilesOptions`, `S3ClientLike`, `S3FileLike`, `S3ListResultLike`, `TtlInput`, `FilesErrorCode`
12
+
13
+ ## Setup (`createFiles(options?)`)
14
+
15
+ `createFiles()` returns a single object that is both the `PrunellePlugin` (register in `prunelle.config.ts`) and the handle routes/actions use:
16
+
17
+ - `store`: `diskFiles(dir)`, `s3Files(opts)`, or `memoryFiles()` (default). Production refuses `memoryFiles()` via `requires()` unless `allowMemoryInProd: true`.
18
+ - `basePath`: serving URL prefix (default `'/files'`).
19
+ - `secret`: HMAC-SHA256 key for private signed URLs (falls back to `FILES_SECRET`, then `AUTH_SECRET`, then an ephemeral key outside production). Must be at least 32 UTF-8 bytes in production.
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
+ - `allow`: allowed detected MIME types or wildcards (`'image/*'`, `'*/*'`). Default: `['image/png', 'image/jpeg', 'image/webp', 'image/gif', 'image/avif', 'application/pdf']`.
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'`).
24
+ - Refuses `prunelle build --static` with a clear error because uploads, signed private URLs, and deletions require a running server.
25
+
26
+ ## Stores
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.
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
+ - `memoryFiles()`: in-memory store for dev and tests.
31
+
32
+ ## Upload, Read, URLs & RGPD Erasure
33
+
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
+ - `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.
40
+
41
+ ## HTTP Serving (`GET ${basePath}/*key`)
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`).
45
+
46
+ ## Snippet
47
+
48
+ ```ts
49
+ // src/files.ts (register `plugins: [files]` in prunelle.config.ts)
50
+ import { createFiles, diskFiles } from '@prunellejs/files'
51
+
52
+ export const files = createFiles({
53
+ store: diskFiles('./data/uploads'),
54
+ allow: ['image/*', 'application/pdf'],
55
+ })
56
+
57
+ // In a server action:
58
+ const key = await files.put(file, { prefix: `users/${user.id}`, public: false })
59
+ const downloadUrl = files.signedUrl(key, '15m')
60
+
61
+ // On RGPD account deletion:
62
+ await files.deleteWhere(`users/${user.id}`)
63
+ ```
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@prunellejs/files",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
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
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "engines": {
16
+ "bun": ">=1.4.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/Kayno0o/prunelle",
21
+ "directory": "packages/plugin-files"
22
+ },
23
+ "peerDependencies": {
24
+ "prunelle": "^0.7.0"
25
+ }
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,414 @@
1
+ // @prunellejs/files — Zero-dependency file upload storage (disk, Bun S3, memory), magic-byte MIME sniffing,
2
+ // signed private URLs, active-type hardening, and RGPD prefix erasure for Prunelle.
3
+
4
+ import type { RequestContext } from 'prunelle/server'
5
+ import type { FileInput, FileMetadata, Files, FilesOptions, FileStore, PutFileOptions, StoredFile, TtlInput } from './types'
6
+ import { createHash, randomBytes } from 'node:crypto'
7
+ import { definePlugin } from 'prunelle/config'
8
+ import { nodeEnv } from 'prunelle/server'
9
+ import { encodeKeySegments, normalizeBasePath, normalizeFileKey, normalizeFilePrefix, parseTtlSeconds, sanitizeFilenameStem, signFileUrl, verifyFileSignature } from './keys'
10
+ import { DEFAULT_ALLOWED_MIMES, extensionForMime, mimeMatchesAllowlist, sniffMime } from './sniff'
11
+ import { memoryFiles } from './stores'
12
+ import { FilesError } from './types'
13
+
14
+ export { encodeKeySegments, normalizeFileKey, normalizeFilePrefix, parseTtlSeconds } from './keys'
15
+ export { DEFAULT_ALLOWED_MIMES, extensionForMime, mimeMatchesAllowlist, sniffMime } from './sniff'
16
+ export { diskFiles, memoryFiles, s3Files } from './stores'
17
+ export { FilesError } from './types'
18
+ export type {
19
+ FileInput,
20
+ FileMetadata,
21
+ FilePutRecord,
22
+ Files,
23
+ FilesErrorCode,
24
+ FilesOptions,
25
+ FileStore,
26
+ PutFileOptions,
27
+ S3ClientLike,
28
+ S3FileLike,
29
+ S3FilesOptions,
30
+ S3ListResultLike,
31
+ StoredFile,
32
+ TtlInput,
33
+ } from './types'
34
+
35
+ const DEFAULT_MAX_SIZE = 10 * 1024 * 1024 // 10 MiB
36
+ const MIN_PROD_SECRET_BYTES = 32
37
+ const DEFAULT_PUBLIC_CACHE_CONTROL = 'public, max-age=31536000, immutable'
38
+ const DEFAULT_PRIVATE_CACHE_CONTROL = 'private, no-store'
39
+
40
+ const ACTIVE_CONTENT_TYPES = new Set([
41
+ 'image/svg+xml',
42
+ 'text/html',
43
+ 'application/xhtml+xml',
44
+ 'text/xml',
45
+ 'application/xml',
46
+ ])
47
+
48
+ function formatEtag(raw: string): string {
49
+ const trimmed = raw.trim()
50
+ if (trimmed.startsWith('"') && trimmed.endsWith('"'))
51
+ return trimmed
52
+ return `"${trimmed.replaceAll('"', '')}"`
53
+ }
54
+
55
+ function stripWeakTag(tag: string): string {
56
+ const trimmed = tag.trim()
57
+ return trimmed.startsWith('W/') || trimmed.startsWith('w/') ? trimmed.slice(2).trim() : trimmed
58
+ }
59
+
60
+ function etagMatches(ifNoneMatch: string | null, quotedEtag: string): boolean {
61
+ if (ifNoneMatch === null || ifNoneMatch.trim().length === 0)
62
+ return false
63
+ const target = stripWeakTag(quotedEtag)
64
+ const candidates = ifNoneMatch.split(',')
65
+ for (let i = 0; i < candidates.length; i++) {
66
+ const candidate = candidates[i]!.trim()
67
+ if (candidate === '*' || stripWeakTag(candidate) === target)
68
+ return true
69
+ }
70
+ return false
71
+ }
72
+
73
+ function safeDownloadFilename(key: string): string {
74
+ const base = key.split('/').pop() ?? 'download'
75
+ const cleaned = base.replace(/["\\\r\n;]/g, '_').trim()
76
+ return cleaned.length > 0 ? cleaned : 'download'
77
+ }
78
+
79
+ async function readInputBytes(input: FileInput, maxSize: number): Promise<{ bytes: Uint8Array, inferredName: string | undefined }> {
80
+ if (input instanceof Blob) {
81
+ if (input.size > maxSize) {
82
+ throw new FilesError(
83
+ 'FILE_TOO_LARGE',
84
+ `@prunellejs/files: file size (${input.size} bytes) exceeds maximum allowed size (${maxSize} bytes).`,
85
+ 413,
86
+ )
87
+ }
88
+ const bytes = new Uint8Array(await input.arrayBuffer())
89
+ if (bytes.byteLength > maxSize) {
90
+ throw new FilesError(
91
+ 'FILE_TOO_LARGE',
92
+ `@prunellejs/files: file size (${bytes.byteLength} bytes) exceeds maximum allowed size (${maxSize} bytes).`,
93
+ 413,
94
+ )
95
+ }
96
+ const inferredName = 'name' in input && typeof input.name === 'string' && input.name.length > 0 ? input.name : undefined
97
+ return { bytes, inferredName }
98
+ }
99
+
100
+ const bytes = input instanceof Uint8Array
101
+ ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
102
+ : new Uint8Array(input)
103
+
104
+ if (bytes.byteLength > maxSize) {
105
+ throw new FilesError(
106
+ 'FILE_TOO_LARGE',
107
+ `@prunellejs/files: file size (${bytes.byteLength} bytes) exceeds maximum allowed size (${maxSize} bytes).`,
108
+ 413,
109
+ )
110
+ }
111
+ return { bytes, inferredName: undefined }
112
+ }
113
+
114
+ function generateKey(prefix: string | undefined, filename: string | undefined, contentType: string): string {
115
+ const normPrefix = prefix !== undefined && prefix.length > 0
116
+ ? normalizeFilePrefix(prefix, { allowEmpty: false })
117
+ : ''
118
+ const stem = sanitizeFilenameStem(filename)
119
+ const id = randomBytes(16).toString('hex')
120
+ const ext = extensionForMime(contentType)
121
+ const leaf = stem.length > 0 ? `${stem}-${id}.${ext}` : `${id}.${ext}`
122
+ return normPrefix.length > 0 ? `${normPrefix}/${leaf}` : leaf
123
+ }
124
+
125
+ function detectAndValidateMime(bytes: Uint8Array, allow: readonly string[], allowEmpty: boolean): string {
126
+ if (bytes.byteLength === 0) {
127
+ if (!allowEmpty)
128
+ throw new FilesError('EMPTY_FILE', '@prunellejs/files: empty (0-byte) files are not allowed; pass `allowEmpty: true` to permit them.', 400)
129
+ return 'application/octet-stream'
130
+ }
131
+
132
+ const detected = sniffMime(bytes)
133
+ if (detected === undefined) {
134
+ throw new FilesError(
135
+ 'UNKNOWN_MIME',
136
+ '@prunellejs/files: could not detect a recognized MIME type from file bytes; refusing unverified binary content.',
137
+ 415,
138
+ )
139
+ }
140
+
141
+ if (!mimeMatchesAllowlist(detected, allow)) {
142
+ throw new FilesError(
143
+ 'DISALLOWED_MIME',
144
+ `@prunellejs/files: detected MIME type "${detected}" is not allowed (allowed: ${allow.join(', ')}).`,
145
+ 415,
146
+ )
147
+ }
148
+
149
+ return detected
150
+ }
151
+
152
+ function readServerMaxBodySize(config: Readonly<Record<string, unknown>> | undefined): number | undefined {
153
+ const raw = config?.maxRequestBodySize
154
+ return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : undefined
155
+ }
156
+
157
+ function buildServeResponse(
158
+ ctx: RequestContext,
159
+ key: string,
160
+ file: StoredFile,
161
+ isSignedRequest: boolean,
162
+ publicCacheControl: string,
163
+ privateCacheControl: string,
164
+ ): Response {
165
+ const quotedEtag = formatEtag(file.etag)
166
+ const cacheControl = isSignedRequest || !file.public ? privateCacheControl : publicCacheControl
167
+ const headers = new Headers({
168
+ 'content-type': file.contentType,
169
+ 'content-length': String(file.size),
170
+ 'etag': quotedEtag,
171
+ 'cache-control': cacheControl,
172
+ 'x-content-type-options': 'nosniff',
173
+ })
174
+
175
+ if (ACTIVE_CONTENT_TYPES.has(file.contentType.toLowerCase())) {
176
+ headers.set('content-disposition', `attachment; filename="${safeDownloadFilename(key)}"`)
177
+ headers.set('content-security-policy', "default-src 'none'; sandbox")
178
+ }
179
+
180
+ if (etagMatches(ctx.request.headers.get('if-none-match'), quotedEtag))
181
+ return new Response(null, { status: 304, headers })
182
+
183
+ return new Response(new Uint8Array(file.bytes), { status: 200, headers })
184
+ }
185
+
186
+ function createSecretResolver(explicitSecret: string | undefined): {
187
+ configured: () => string | undefined
188
+ resolve: () => string
189
+ } {
190
+ let ephemeralSecret: string | undefined
191
+ const configured = (): string | undefined =>
192
+ explicitSecret ?? process.env.FILES_SECRET ?? process.env.AUTH_SECRET
193
+
194
+ const resolve = (): string => {
195
+ const raw = configured()
196
+ if (raw !== undefined && raw.length > 0) {
197
+ if (nodeEnv() === 'production' && Buffer.byteLength(raw, 'utf8') < MIN_PROD_SECRET_BYTES) {
198
+ throw new FilesError(
199
+ 'INVALID_CONFIG',
200
+ `@prunellejs/files: signing secret must be at least ${MIN_PROD_SECRET_BYTES} UTF-8 bytes in production.`,
201
+ 500,
202
+ )
203
+ }
204
+ return raw
205
+ }
206
+ if (nodeEnv() === 'production') {
207
+ throw new FilesError(
208
+ 'INVALID_CONFIG',
209
+ `@prunellejs/files: set FILES_SECRET (or AUTH_SECRET, or createFiles({ secret })) to at least ${MIN_PROD_SECRET_BYTES} bytes in production.`,
210
+ 500,
211
+ )
212
+ }
213
+ ephemeralSecret ??= randomBytes(32).toString('hex')
214
+ return ephemeralSecret
215
+ }
216
+
217
+ return { configured, resolve }
218
+ }
219
+
220
+ interface ServeRouteDeps {
221
+ store: FileStore
222
+ publicCacheControl: string
223
+ privateCacheControl: string
224
+ verifySignedUrl: (key: string, exp: string | number | null | undefined, sig: string | null | undefined) => boolean
225
+ }
226
+
227
+ function createServeHandler(deps: ServeRouteDeps): (ctx: RequestContext) => Promise<Response> {
228
+ return async (ctx: RequestContext): Promise<Response> => {
229
+ const rawKey = ctx.params.key
230
+ if (rawKey === undefined || rawKey.length === 0)
231
+ return new Response('Invalid file key', { status: 400, headers: { 'cache-control': 'no-store' } })
232
+
233
+ let key: string
234
+ try {
235
+ key = normalizeFileKey(rawKey)
236
+ }
237
+ catch {
238
+ return new Response('Invalid file key', { status: 400, headers: { 'cache-control': 'no-store' } })
239
+ }
240
+
241
+ const meta = await deps.store.stat(key)
242
+ if (meta === undefined)
243
+ return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
244
+
245
+ const expParam = ctx.url.searchParams.get('exp')
246
+ const sigParam = ctx.url.searchParams.get('sig')
247
+ const isSignedRequest = expParam !== null || sigParam !== null
248
+
249
+ if (!meta.public && !deps.verifySignedUrl(key, expParam, sigParam))
250
+ return new Response('Forbidden', { status: 403, headers: { 'cache-control': deps.privateCacheControl } })
251
+
252
+ const quotedEtag = formatEtag(meta.etag)
253
+ if (etagMatches(ctx.request.headers.get('if-none-match'), quotedEtag)) {
254
+ const headers = new Headers({
255
+ 'etag': quotedEtag,
256
+ 'cache-control': isSignedRequest || !meta.public ? deps.privateCacheControl : deps.publicCacheControl,
257
+ 'x-content-type-options': 'nosniff',
258
+ })
259
+ return new Response(null, { status: 304, headers })
260
+ }
261
+
262
+ const file = await deps.store.get(key)
263
+ if (file === undefined)
264
+ return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
265
+
266
+ return buildServeResponse(ctx, key, file, isSignedRequest, deps.publicCacheControl, deps.privateCacheControl)
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Creates a `@prunellejs/files` plugin and storage handle.
272
+ * Register the returned object in `prunelle.config.ts` (`plugins: [files]`) and import it in routes/actions
273
+ * to call `files.put()`, `files.url()`, `files.signedUrl()`, `files.delete()`, and `files.deleteWhere()`.
274
+ */
275
+ export function createFiles(options: FilesOptions = {}): Files {
276
+ const store: FileStore = options.store ?? memoryFiles()
277
+ const basePath = normalizeBasePath(options.basePath)
278
+ const defaultAllow = options.allow ?? DEFAULT_ALLOWED_MIMES
279
+ const defaultPublic = options.defaultPublic ?? false
280
+ const publicCacheControl = options.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL
281
+ const privateCacheControl = options.privateCacheControl ?? DEFAULT_PRIVATE_CACHE_CONTROL
282
+ const allowMemoryInProd = options.allowMemoryInProd === true
283
+ const now = options.now ?? (() => Date.now())
284
+
285
+ if (options.maxSize !== undefined && (!Number.isFinite(options.maxSize) || options.maxSize <= 0))
286
+ throw new FilesError('INVALID_CONFIG', '@prunellejs/files: maxSize must be a positive finite number of bytes.', 500)
287
+
288
+ let serverMaxBodySize: number | undefined
289
+ const secret = createSecretResolver(options.secret)
290
+
291
+ const effectiveMaxSize = (override?: number): number => {
292
+ const limit = override ?? options.maxSize ?? serverMaxBodySize ?? DEFAULT_MAX_SIZE
293
+ if (!Number.isFinite(limit) || limit <= 0)
294
+ throw new FilesError('INVALID_CONFIG', '@prunellejs/files: maxSize must be a positive finite number of bytes.', 400)
295
+ return limit
296
+ }
297
+
298
+ const verifySignedUrl = (
299
+ key: string,
300
+ exp: string | number | null | undefined,
301
+ sig: string | null | undefined,
302
+ ): boolean => {
303
+ let normalized: string
304
+ try {
305
+ normalized = normalizeFileKey(key)
306
+ }
307
+ catch {
308
+ return false
309
+ }
310
+ return verifyFileSignature(normalized, exp, sig, secret.resolve(), now())
311
+ }
312
+
313
+ const serveFileRoute = createServeHandler({ store, publicCacheControl, privateCacheControl, verifySignedUrl })
314
+
315
+ const plugin = definePlugin({
316
+ name: '@prunellejs/files',
317
+ requires() {
318
+ const unmet: string[] = []
319
+ if (store.kind === 'memory' && !allowMemoryInProd) {
320
+ unmet.push(
321
+ 'store is memoryFiles(), which loses uploads on restart: pass `diskFiles(dir)` or `s3Files(...)` to `createFiles({ store })`, or set `allowMemoryInProd: true`.',
322
+ )
323
+ }
324
+ const configured = secret.configured()
325
+ if (configured === undefined || Buffer.byteLength(configured, 'utf8') < MIN_PROD_SECRET_BYTES) {
326
+ unmet.push(
327
+ `no signing secret of at least ${MIN_PROD_SECRET_BYTES} bytes: set \`FILES_SECRET\` (or \`AUTH_SECRET\`), or pass \`secret\` to \`createFiles()\`.`,
328
+ )
329
+ }
330
+ return unmet
331
+ },
332
+ build(ctx) {
333
+ if (ctx.isStatic) {
334
+ throw new Error(
335
+ '@prunellejs/files cannot run with `prunelle build --static`: file uploads, private signed URLs, and deletions require a running server. Build without `--static` or remove `@prunellejs/files`.',
336
+ )
337
+ }
338
+ },
339
+ server(api) {
340
+ serverMaxBodySize = readServerMaxBodySize(api.config)
341
+ api.route('GET', `${basePath}/*key`, serveFileRoute)
342
+ api.onShutdown(() => {
343
+ serverMaxBodySize = undefined
344
+ })
345
+ },
346
+ })
347
+
348
+ return {
349
+ ...plugin,
350
+ store,
351
+ basePath,
352
+ async put(input: FileInput, putOpts: PutFileOptions = {}): Promise<string> {
353
+ const maxSize = effectiveMaxSize(putOpts.maxSize)
354
+ const allow = putOpts.allow ?? defaultAllow
355
+ const allowEmpty = putOpts.allowEmpty === true
356
+
357
+ const { bytes, inferredName } = await readInputBytes(input, maxSize)
358
+ const contentType = detectAndValidateMime(bytes, allow, allowEmpty)
359
+
360
+ const key = putOpts.key !== undefined
361
+ ? normalizeFileKey(putOpts.key)
362
+ : generateKey(putOpts.prefix, putOpts.filename ?? inferredName, contentType)
363
+
364
+ const etag = createHash('sha256').update(bytes).digest('hex').slice(0, 32)
365
+ const isPublic = putOpts.public ?? defaultPublic
366
+
367
+ await store.put({
368
+ key,
369
+ bytes,
370
+ contentType,
371
+ etag,
372
+ public: isPublic,
373
+ updatedAt: now(),
374
+ })
375
+
376
+ return key
377
+ },
378
+ async get(key: string): Promise<StoredFile | undefined> {
379
+ return await store.get(normalizeFileKey(key))
380
+ },
381
+ async stat(key: string): Promise<FileMetadata | undefined> {
382
+ return await store.stat(normalizeFileKey(key))
383
+ },
384
+ async list(prefix = ''): Promise<readonly FileMetadata[]> {
385
+ return await store.list(normalizeFilePrefix(prefix, { allowEmpty: true }))
386
+ },
387
+ async delete(key: string): Promise<boolean> {
388
+ return await store.delete(normalizeFileKey(key))
389
+ },
390
+ async deleteWhere(prefix: string): Promise<number> {
391
+ const norm = normalizeFilePrefix(prefix, { allowEmpty: false })
392
+ if (store.deleteWhere !== undefined)
393
+ return await store.deleteWhere(norm)
394
+ const matching = await store.list(norm)
395
+ let removed = 0
396
+ for (let i = 0; i < matching.length; i++) {
397
+ if (await store.delete(matching[i]!.key))
398
+ removed++
399
+ }
400
+ return removed
401
+ },
402
+ url(key: string): string {
403
+ return `${basePath}/${encodeKeySegments(key)}`
404
+ },
405
+ signedUrl(key: string, ttl: TtlInput): string {
406
+ const normalized = normalizeFileKey(key)
407
+ const ttlSeconds = parseTtlSeconds(ttl)
408
+ const exp = Math.floor(now() / 1000) + ttlSeconds
409
+ const sig = signFileUrl(normalized, exp, secret.resolve())
410
+ return `${basePath}/${encodeKeySegments(normalized)}?exp=${exp}&sig=${encodeURIComponent(sig)}`
411
+ },
412
+ verifySignedUrl,
413
+ }
414
+ }