@prunellejs/files 0.0.0-stage → 0.7.3
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 +21 -0
- package/llms.txt +63 -0
- package/package.json +24 -4
- package/src/index.ts +408 -0
- package/src/keys.ts +264 -0
- package/src/sniff.ts +280 -0
- package/src/stores.ts +513 -0
- package/src/types.ts +176 -0
- package/README.md +0 -3
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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.3",
|
|
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.3"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
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, formatAttachmentDisposition, 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
|
+
async function readInputBytes(input: FileInput, maxSize: number): Promise<{ bytes: Uint8Array, inferredName: string | undefined }> {
|
|
74
|
+
if (input instanceof Blob) {
|
|
75
|
+
if (input.size > maxSize) {
|
|
76
|
+
throw new FilesError(
|
|
77
|
+
'FILE_TOO_LARGE',
|
|
78
|
+
`@prunellejs/files: file size (${input.size} bytes) exceeds maximum allowed size (${maxSize} bytes).`,
|
|
79
|
+
413,
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
const bytes = new Uint8Array(await input.arrayBuffer())
|
|
83
|
+
if (bytes.byteLength > maxSize) {
|
|
84
|
+
throw new FilesError(
|
|
85
|
+
'FILE_TOO_LARGE',
|
|
86
|
+
`@prunellejs/files: file size (${bytes.byteLength} bytes) exceeds maximum allowed size (${maxSize} bytes).`,
|
|
87
|
+
413,
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
const inferredName = 'name' in input && typeof input.name === 'string' && input.name.length > 0 ? input.name : undefined
|
|
91
|
+
return { bytes, inferredName }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const bytes = input instanceof Uint8Array
|
|
95
|
+
? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
|
|
96
|
+
: new Uint8Array(input)
|
|
97
|
+
|
|
98
|
+
if (bytes.byteLength > maxSize) {
|
|
99
|
+
throw new FilesError(
|
|
100
|
+
'FILE_TOO_LARGE',
|
|
101
|
+
`@prunellejs/files: file size (${bytes.byteLength} bytes) exceeds maximum allowed size (${maxSize} bytes).`,
|
|
102
|
+
413,
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
return { bytes, inferredName: undefined }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function generateKey(prefix: string | undefined, filename: string | undefined, contentType: string): string {
|
|
109
|
+
const normPrefix = prefix !== undefined && prefix.length > 0
|
|
110
|
+
? normalizeFilePrefix(prefix, { allowEmpty: false })
|
|
111
|
+
: ''
|
|
112
|
+
const stem = sanitizeFilenameStem(filename)
|
|
113
|
+
const id = randomBytes(16).toString('hex')
|
|
114
|
+
const ext = extensionForMime(contentType)
|
|
115
|
+
const leaf = stem.length > 0 ? `${stem}-${id}.${ext}` : `${id}.${ext}`
|
|
116
|
+
return normPrefix.length > 0 ? `${normPrefix}/${leaf}` : leaf
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function detectAndValidateMime(bytes: Uint8Array, allow: readonly string[], allowEmpty: boolean): string {
|
|
120
|
+
if (bytes.byteLength === 0) {
|
|
121
|
+
if (!allowEmpty)
|
|
122
|
+
throw new FilesError('EMPTY_FILE', '@prunellejs/files: empty (0-byte) files are not allowed; pass `allowEmpty: true` to permit them.', 400)
|
|
123
|
+
return 'application/octet-stream'
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const detected = sniffMime(bytes)
|
|
127
|
+
if (detected === undefined) {
|
|
128
|
+
throw new FilesError(
|
|
129
|
+
'UNKNOWN_MIME',
|
|
130
|
+
'@prunellejs/files: could not detect a recognized MIME type from file bytes; refusing unverified binary content.',
|
|
131
|
+
415,
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (!mimeMatchesAllowlist(detected, allow)) {
|
|
136
|
+
throw new FilesError(
|
|
137
|
+
'DISALLOWED_MIME',
|
|
138
|
+
`@prunellejs/files: detected MIME type "${detected}" is not allowed (allowed: ${allow.join(', ')}).`,
|
|
139
|
+
415,
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return detected
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function readServerMaxBodySize(config: Readonly<Record<string, unknown>> | undefined): number | undefined {
|
|
147
|
+
const raw = config?.maxRequestBodySize
|
|
148
|
+
return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : undefined
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function buildServeResponse(
|
|
152
|
+
ctx: RequestContext,
|
|
153
|
+
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
|
|
161
|
+
const headers = new Headers({
|
|
162
|
+
'content-type': file.contentType,
|
|
163
|
+
'content-length': String(file.size),
|
|
164
|
+
'etag': quotedEtag,
|
|
165
|
+
'cache-control': cacheControl,
|
|
166
|
+
'x-content-type-options': 'nosniff',
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
if (ACTIVE_CONTENT_TYPES.has(file.contentType.toLowerCase())) {
|
|
170
|
+
headers.set('content-disposition', formatAttachmentDisposition(key))
|
|
171
|
+
headers.set('content-security-policy', "default-src 'none'; sandbox")
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (etagMatches(ctx.request.headers.get('if-none-match'), quotedEtag))
|
|
175
|
+
return new Response(null, { status: 304, headers })
|
|
176
|
+
|
|
177
|
+
return new Response(new Uint8Array(file.bytes), { status: 200, headers })
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function createSecretResolver(explicitSecret: string | undefined): {
|
|
181
|
+
configured: () => string | undefined
|
|
182
|
+
resolve: () => string
|
|
183
|
+
} {
|
|
184
|
+
let ephemeralSecret: string | undefined
|
|
185
|
+
const configured = (): string | undefined =>
|
|
186
|
+
explicitSecret ?? process.env.FILES_SECRET ?? process.env.AUTH_SECRET
|
|
187
|
+
|
|
188
|
+
const resolve = (): string => {
|
|
189
|
+
const raw = configured()
|
|
190
|
+
if (raw !== undefined && raw.length > 0) {
|
|
191
|
+
if (nodeEnv() === 'production' && Buffer.byteLength(raw, 'utf8') < MIN_PROD_SECRET_BYTES) {
|
|
192
|
+
throw new FilesError(
|
|
193
|
+
'INVALID_CONFIG',
|
|
194
|
+
`@prunellejs/files: signing secret must be at least ${MIN_PROD_SECRET_BYTES} UTF-8 bytes in production.`,
|
|
195
|
+
500,
|
|
196
|
+
)
|
|
197
|
+
}
|
|
198
|
+
return raw
|
|
199
|
+
}
|
|
200
|
+
if (nodeEnv() === 'production') {
|
|
201
|
+
throw new FilesError(
|
|
202
|
+
'INVALID_CONFIG',
|
|
203
|
+
`@prunellejs/files: set FILES_SECRET (or AUTH_SECRET, or createFiles({ secret })) to at least ${MIN_PROD_SECRET_BYTES} bytes in production.`,
|
|
204
|
+
500,
|
|
205
|
+
)
|
|
206
|
+
}
|
|
207
|
+
ephemeralSecret ??= randomBytes(32).toString('hex')
|
|
208
|
+
return ephemeralSecret
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return { configured, resolve }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
interface ServeRouteDeps {
|
|
215
|
+
store: FileStore
|
|
216
|
+
publicCacheControl: string
|
|
217
|
+
privateCacheControl: string
|
|
218
|
+
verifySignedUrl: (key: string, exp: string | number | null | undefined, sig: string | null | undefined) => boolean
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function createServeHandler(deps: ServeRouteDeps): (ctx: RequestContext) => Promise<Response> {
|
|
222
|
+
return async (ctx: RequestContext): Promise<Response> => {
|
|
223
|
+
const rawKey = ctx.params.key
|
|
224
|
+
if (rawKey === undefined || rawKey.length === 0)
|
|
225
|
+
return new Response('Invalid file key', { status: 400, headers: { 'cache-control': 'no-store' } })
|
|
226
|
+
|
|
227
|
+
let key: string
|
|
228
|
+
try {
|
|
229
|
+
key = normalizeFileKey(rawKey)
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return new Response('Invalid file key', { status: 400, headers: { 'cache-control': 'no-store' } })
|
|
233
|
+
}
|
|
234
|
+
|
|
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
|
+
const expParam = ctx.url.searchParams.get('exp')
|
|
240
|
+
const sigParam = ctx.url.searchParams.get('sig')
|
|
241
|
+
const isSignedRequest = expParam !== null || sigParam !== null
|
|
242
|
+
|
|
243
|
+
if (!meta.public && !deps.verifySignedUrl(key, expParam, sigParam))
|
|
244
|
+
return new Response('Forbidden', { status: 403, headers: { 'cache-control': deps.privateCacheControl } })
|
|
245
|
+
|
|
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)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Creates a `@prunellejs/files` plugin and storage handle.
|
|
266
|
+
* Register the returned object in `prunelle.config.ts` (`plugins: [files]`) and import it in routes/actions
|
|
267
|
+
* to call `files.put()`, `files.url()`, `files.signedUrl()`, `files.delete()`, and `files.deleteWhere()`.
|
|
268
|
+
*/
|
|
269
|
+
export function createFiles(options: FilesOptions = {}): Files {
|
|
270
|
+
const store: FileStore = options.store ?? memoryFiles()
|
|
271
|
+
const basePath = normalizeBasePath(options.basePath)
|
|
272
|
+
const defaultAllow = options.allow ?? DEFAULT_ALLOWED_MIMES
|
|
273
|
+
const defaultPublic = options.defaultPublic ?? false
|
|
274
|
+
const publicCacheControl = options.publicCacheControl ?? DEFAULT_PUBLIC_CACHE_CONTROL
|
|
275
|
+
const privateCacheControl = options.privateCacheControl ?? DEFAULT_PRIVATE_CACHE_CONTROL
|
|
276
|
+
const allowMemoryInProd = options.allowMemoryInProd === true
|
|
277
|
+
const now = options.now ?? (() => Date.now())
|
|
278
|
+
|
|
279
|
+
if (options.maxSize !== undefined && (!Number.isFinite(options.maxSize) || options.maxSize <= 0))
|
|
280
|
+
throw new FilesError('INVALID_CONFIG', '@prunellejs/files: maxSize must be a positive finite number of bytes.', 500)
|
|
281
|
+
|
|
282
|
+
let serverMaxBodySize: number | undefined
|
|
283
|
+
const secret = createSecretResolver(options.secret)
|
|
284
|
+
|
|
285
|
+
const effectiveMaxSize = (override?: number): number => {
|
|
286
|
+
const limit = override ?? options.maxSize ?? serverMaxBodySize ?? DEFAULT_MAX_SIZE
|
|
287
|
+
if (!Number.isFinite(limit) || limit <= 0)
|
|
288
|
+
throw new FilesError('INVALID_CONFIG', '@prunellejs/files: maxSize must be a positive finite number of bytes.', 400)
|
|
289
|
+
return limit
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const verifySignedUrl = (
|
|
293
|
+
key: string,
|
|
294
|
+
exp: string | number | null | undefined,
|
|
295
|
+
sig: string | null | undefined,
|
|
296
|
+
): boolean => {
|
|
297
|
+
let normalized: string
|
|
298
|
+
try {
|
|
299
|
+
normalized = normalizeFileKey(key)
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
return false
|
|
303
|
+
}
|
|
304
|
+
return verifyFileSignature(normalized, exp, sig, secret.resolve(), now())
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const serveFileRoute = createServeHandler({ store, publicCacheControl, privateCacheControl, verifySignedUrl })
|
|
308
|
+
|
|
309
|
+
const plugin = definePlugin({
|
|
310
|
+
name: '@prunellejs/files',
|
|
311
|
+
requires() {
|
|
312
|
+
const unmet: string[] = []
|
|
313
|
+
if (store.kind === 'memory' && !allowMemoryInProd) {
|
|
314
|
+
unmet.push(
|
|
315
|
+
'store is memoryFiles(), which loses uploads on restart: pass `diskFiles(dir)` or `s3Files(...)` to `createFiles({ store })`, or set `allowMemoryInProd: true`.',
|
|
316
|
+
)
|
|
317
|
+
}
|
|
318
|
+
const configured = secret.configured()
|
|
319
|
+
if (configured === undefined || Buffer.byteLength(configured, 'utf8') < MIN_PROD_SECRET_BYTES) {
|
|
320
|
+
unmet.push(
|
|
321
|
+
`no signing secret of at least ${MIN_PROD_SECRET_BYTES} bytes: set \`FILES_SECRET\` (or \`AUTH_SECRET\`), or pass \`secret\` to \`createFiles()\`.`,
|
|
322
|
+
)
|
|
323
|
+
}
|
|
324
|
+
return unmet
|
|
325
|
+
},
|
|
326
|
+
build(ctx) {
|
|
327
|
+
if (ctx.isStatic) {
|
|
328
|
+
throw new Error(
|
|
329
|
+
'@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`.',
|
|
330
|
+
)
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
server(api) {
|
|
334
|
+
serverMaxBodySize = readServerMaxBodySize(api.config)
|
|
335
|
+
api.route('GET', `${basePath}/*key`, serveFileRoute)
|
|
336
|
+
api.onShutdown(() => {
|
|
337
|
+
serverMaxBodySize = undefined
|
|
338
|
+
})
|
|
339
|
+
},
|
|
340
|
+
})
|
|
341
|
+
|
|
342
|
+
return {
|
|
343
|
+
...plugin,
|
|
344
|
+
store,
|
|
345
|
+
basePath,
|
|
346
|
+
async put(input: FileInput, putOpts: PutFileOptions = {}): Promise<string> {
|
|
347
|
+
const maxSize = effectiveMaxSize(putOpts.maxSize)
|
|
348
|
+
const allow = putOpts.allow ?? defaultAllow
|
|
349
|
+
const allowEmpty = putOpts.allowEmpty === true
|
|
350
|
+
|
|
351
|
+
const { bytes, inferredName } = await readInputBytes(input, maxSize)
|
|
352
|
+
const contentType = detectAndValidateMime(bytes, allow, allowEmpty)
|
|
353
|
+
|
|
354
|
+
const key = putOpts.key !== undefined
|
|
355
|
+
? normalizeFileKey(putOpts.key)
|
|
356
|
+
: generateKey(putOpts.prefix, putOpts.filename ?? inferredName, contentType)
|
|
357
|
+
|
|
358
|
+
const etag = createHash('sha256').update(bytes).digest('hex').slice(0, 32)
|
|
359
|
+
const isPublic = putOpts.public ?? defaultPublic
|
|
360
|
+
|
|
361
|
+
await store.put({
|
|
362
|
+
key,
|
|
363
|
+
bytes,
|
|
364
|
+
contentType,
|
|
365
|
+
etag,
|
|
366
|
+
public: isPublic,
|
|
367
|
+
updatedAt: now(),
|
|
368
|
+
})
|
|
369
|
+
|
|
370
|
+
return key
|
|
371
|
+
},
|
|
372
|
+
async get(key: string): Promise<StoredFile | undefined> {
|
|
373
|
+
return await store.get(normalizeFileKey(key))
|
|
374
|
+
},
|
|
375
|
+
async stat(key: string): Promise<FileMetadata | undefined> {
|
|
376
|
+
return await store.stat(normalizeFileKey(key))
|
|
377
|
+
},
|
|
378
|
+
async list(prefix = ''): Promise<readonly FileMetadata[]> {
|
|
379
|
+
return await store.list(normalizeFilePrefix(prefix, { allowEmpty: true }))
|
|
380
|
+
},
|
|
381
|
+
async delete(key: string): Promise<boolean> {
|
|
382
|
+
return await store.delete(normalizeFileKey(key))
|
|
383
|
+
},
|
|
384
|
+
async deleteWhere(prefix: string): Promise<number> {
|
|
385
|
+
const norm = normalizeFilePrefix(prefix, { allowEmpty: false })
|
|
386
|
+
if (store.deleteWhere !== undefined)
|
|
387
|
+
return await store.deleteWhere(norm)
|
|
388
|
+
const matching = await store.list(norm)
|
|
389
|
+
let removed = 0
|
|
390
|
+
for (let i = 0; i < matching.length; i++) {
|
|
391
|
+
if (await store.delete(matching[i]!.key))
|
|
392
|
+
removed++
|
|
393
|
+
}
|
|
394
|
+
return removed
|
|
395
|
+
},
|
|
396
|
+
url(key: string): string {
|
|
397
|
+
return `${basePath}/${encodeKeySegments(key)}`
|
|
398
|
+
},
|
|
399
|
+
signedUrl(key: string, ttl: TtlInput): string {
|
|
400
|
+
const normalized = normalizeFileKey(key)
|
|
401
|
+
const ttlSeconds = parseTtlSeconds(ttl)
|
|
402
|
+
const exp = Math.floor(now() / 1000) + ttlSeconds
|
|
403
|
+
const sig = signFileUrl(normalized, exp, secret.resolve())
|
|
404
|
+
return `${basePath}/${encodeKeySegments(normalized)}?exp=${exp}&sig=${encodeURIComponent(sig)}`
|
|
405
|
+
},
|
|
406
|
+
verifySignedUrl,
|
|
407
|
+
}
|
|
408
|
+
}
|