@prunellejs/files 0.7.4 → 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 +8 -7
- package/package.json +2 -2
- package/src/index.ts +42 -36
- package/src/keys.ts +4 -4
- package/src/stores.ts +107 -63
- package/src/types.ts +13 -0
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'`).
|
|
38
|
-
- `await files.delete(key)` (idempotent) and `await files.deleteWhere(prefix)` (RGPD erasure on segment boundaries, e.g. `'users/42'` never touches `'users/420'`).
|
|
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
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
|
|
44
|
-
-
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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':
|
|
163
|
-
'content-length': String(
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
244
|
-
|
|
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
|
|
247
|
-
|
|
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
|
|
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,10 +1,10 @@
|
|
|
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 {
|
|
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
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
10
|
const MAX_SEGMENT_BYTES = 240
|
|
@@ -174,9 +174,9 @@ export function parseTtlSeconds(ttl: TtlInput): number {
|
|
|
174
174
|
throw new FilesError('INVALID_TTL', '@prunellejs/files: TTL must be a number of seconds or a duration string.', 400)
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
-
/** 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. */
|
|
178
178
|
export function signFileUrl(key: string, expUnixSec: number, secret: string): string {
|
|
179
|
-
return
|
|
179
|
+
return new Bun.CryptoHasher('sha256', deriveKey(SIGNING_PURPOSE, secret))
|
|
180
180
|
.update(`${expUnixSec}\n${key}`)
|
|
181
181
|
.digest('base64url')
|
|
182
182
|
}
|
package/src/stores.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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'
|
|
@@ -10,15 +10,6 @@ import { isInside } from 'prunelle/config'
|
|
|
10
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 {
|
|
@@ -111,15 +108,7 @@ export function memoryFiles(): FileStore {
|
|
|
111
108
|
throw new FilesError('INVALID_KEY', `@prunellejs/files: key "${key}" conflicts with existing key "${existing}".`, 409)
|
|
112
109
|
}
|
|
113
110
|
const bytes = new Uint8Array(record.bytes)
|
|
114
|
-
entries.set(key, {
|
|
115
|
-
key,
|
|
116
|
-
bytes,
|
|
117
|
-
contentType: record.contentType,
|
|
118
|
-
size: bytes.byteLength,
|
|
119
|
-
etag: record.etag,
|
|
120
|
-
public: record.public,
|
|
121
|
-
updatedAt: record.updatedAt,
|
|
122
|
-
})
|
|
111
|
+
entries.set(key, { ...toMeta({ ...record, key, size: bytes.byteLength }), bytes })
|
|
123
112
|
},
|
|
124
113
|
get(key: string): StoredFile | undefined {
|
|
125
114
|
const norm = normalizeFileKey(key)
|
|
@@ -128,6 +117,10 @@ export function memoryFiles(): FileStore {
|
|
|
128
117
|
return undefined
|
|
129
118
|
return { ...found, bytes: new Uint8Array(found.bytes) }
|
|
130
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
|
+
},
|
|
131
124
|
stat(key: string): FileMetadata | undefined {
|
|
132
125
|
const norm = normalizeFileKey(key)
|
|
133
126
|
const found = entries.get(norm)
|
|
@@ -222,7 +215,7 @@ function writeFileAtomic(tmpDir: string, targetPath: string, data: Uint8Array |
|
|
|
222
215
|
mkdirSync(parent, { recursive: true })
|
|
223
216
|
mkdirSync(tmpDir, { recursive: true })
|
|
224
217
|
const tmpPath = join(tmpDir, `${randomBytes(12).toString('hex')}.tmp`)
|
|
225
|
-
writeFileSync(tmpPath, data)
|
|
218
|
+
writeFileSync(tmpPath, data, { mode: 0o600 })
|
|
226
219
|
try {
|
|
227
220
|
renameSync(tmpPath, targetPath)
|
|
228
221
|
}
|
|
@@ -301,6 +294,21 @@ function collectDiskMeta(dir: string, realMetaRoot: string, normalizedPrefix: st
|
|
|
301
294
|
}
|
|
302
295
|
}
|
|
303
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
|
+
|
|
304
312
|
/**
|
|
305
313
|
* Local disk storage under `dir`.
|
|
306
314
|
* Stores objects under `<dir>/objects/<key>` and metadata under `<dir>/meta/<key>.json` so metadata
|
|
@@ -354,16 +362,8 @@ export function diskFiles(dir: string): FileStore {
|
|
|
354
362
|
|
|
355
363
|
const existedBefore = isRegularFile(objectPath)
|
|
356
364
|
writeFileAtomic(tmpDir, objectPath, record.bytes)
|
|
357
|
-
const serialized: SerializedMeta = {
|
|
358
|
-
key,
|
|
359
|
-
contentType: record.contentType,
|
|
360
|
-
size: record.bytes.byteLength,
|
|
361
|
-
etag: record.etag,
|
|
362
|
-
public: record.public,
|
|
363
|
-
updatedAt: record.updatedAt,
|
|
364
|
-
}
|
|
365
365
|
try {
|
|
366
|
-
writeFileAtomic(tmpDir, metaPath,
|
|
366
|
+
writeFileAtomic(tmpDir, metaPath, serializeMeta({ ...record, key }))
|
|
367
367
|
}
|
|
368
368
|
catch (error) {
|
|
369
369
|
if (!existedBefore) {
|
|
@@ -389,6 +389,25 @@ export function diskFiles(dir: string): FileStore {
|
|
|
389
389
|
throw error
|
|
390
390
|
}
|
|
391
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
|
+
},
|
|
392
411
|
stat(key: string): FileMetadata | undefined {
|
|
393
412
|
const norm = normalizeFileKey(key)
|
|
394
413
|
const meta = readDiskMeta(norm)
|
|
@@ -412,14 +431,19 @@ export function diskFiles(dir: string): FileStore {
|
|
|
412
431
|
},
|
|
413
432
|
deleteWhere(prefix: string): number {
|
|
414
433
|
const norm = normalizeFilePrefix(prefix, { allowEmpty: false })
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
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)
|
|
420
444
|
let removed = 0
|
|
421
|
-
for (
|
|
422
|
-
if (removeOne(
|
|
445
|
+
for (const key of keys) {
|
|
446
|
+
if (removeOne(key))
|
|
423
447
|
removed++
|
|
424
448
|
}
|
|
425
449
|
return removed
|
|
@@ -458,11 +482,8 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
|
|
|
458
482
|
const metaKey = (normKey: string): string => `${basePrefix}meta/${normKey}.json`
|
|
459
483
|
|
|
460
484
|
const readS3Meta = async (normKey: string): Promise<FileMetadata | undefined> => {
|
|
461
|
-
const file = client.file(metaKey(normKey))
|
|
462
|
-
if (!(await file.exists()))
|
|
463
|
-
return undefined
|
|
464
485
|
try {
|
|
465
|
-
return parseMetaJson(await file.text())
|
|
486
|
+
return parseMetaJson(await client.file(metaKey(normKey)).text())
|
|
466
487
|
}
|
|
467
488
|
catch (error) {
|
|
468
489
|
if (isS3NotFound(error))
|
|
@@ -471,25 +492,32 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
|
|
|
471
492
|
}
|
|
472
493
|
}
|
|
473
494
|
|
|
474
|
-
const
|
|
475
|
-
const
|
|
476
|
-
const searchPrefix = normPrefix.length > 0 ? `${metaBase}${normPrefix}` : metaBase
|
|
477
|
-
const metaPaths: string[] = []
|
|
495
|
+
const listS3Paths = async (searchPrefix: string): Promise<string[]> => {
|
|
496
|
+
const paths: string[] = []
|
|
478
497
|
let continuationToken: string | undefined
|
|
479
|
-
|
|
480
498
|
for (;;) {
|
|
481
499
|
const input: { prefix?: string, continuationToken?: string } = { prefix: searchPrefix }
|
|
482
500
|
if (continuationToken !== undefined)
|
|
483
501
|
input.continuationToken = continuationToken
|
|
484
502
|
const page = await client.list(input)
|
|
485
|
-
for (const item of page.contents ?? [])
|
|
486
|
-
|
|
487
|
-
metaPaths.push(item.key)
|
|
488
|
-
}
|
|
503
|
+
for (const item of page.contents ?? [])
|
|
504
|
+
paths.push(item.key)
|
|
489
505
|
if (page.isTruncated !== true || page.nextContinuationToken === undefined)
|
|
490
|
-
|
|
506
|
+
return paths
|
|
491
507
|
continuationToken = page.nextContinuationToken
|
|
492
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'))
|
|
493
521
|
|
|
494
522
|
const out: FileMetadata[] = []
|
|
495
523
|
for (let i = 0; i < metaPaths.length; i++) {
|
|
@@ -527,16 +555,29 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
|
|
|
527
555
|
kind: 's3',
|
|
528
556
|
async put(record: FilePutRecord): Promise<void> {
|
|
529
557
|
const key = normalizeFileKey(record.key)
|
|
558
|
+
const existedBefore = await client.file(objectKey(key)).exists()
|
|
530
559
|
await client.file(objectKey(key), { type: record.contentType }).write(record.bytes, { type: record.contentType })
|
|
531
|
-
|
|
532
|
-
key,
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
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)),
|
|
538
580
|
}
|
|
539
|
-
await client.file(metaKey(key), { type: 'application/json' }).write(JSON.stringify(serialized), { type: 'application/json' })
|
|
540
581
|
},
|
|
541
582
|
async get(key: string): Promise<StoredFile | undefined> {
|
|
542
583
|
const norm = normalizeFileKey(key)
|
|
@@ -570,10 +611,13 @@ export function s3Files(options: S3FilesOptions = {}): FileStore {
|
|
|
570
611
|
return await listS3Meta(normalizeFilePrefix(prefix, { allowEmpty: true }))
|
|
571
612
|
},
|
|
572
613
|
async deleteWhere(prefix: string): Promise<number> {
|
|
573
|
-
const
|
|
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)
|
|
574
618
|
let removed = 0
|
|
575
|
-
for (
|
|
576
|
-
if (await deleteS3Pair(
|
|
619
|
+
for (const key of keys) {
|
|
620
|
+
if (await deleteS3Pair(key))
|
|
577
621
|
removed++
|
|
578
622
|
}
|
|
579
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
|
}
|