@prunellejs/files 0.0.0-stage → 0.6.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/src/keys.ts ADDED
@@ -0,0 +1,217 @@
1
+ // Path traversal defense, key/prefix normalization, URL encoding, TTL parsing, and HMAC URL signing.
2
+
3
+ import type { TtlInput } from './types'
4
+ import { createHmac } from 'node:crypto'
5
+ import { safeEqual } from 'prunelle/server'
6
+ import { FilesError } from './types'
7
+
8
+ const MAX_KEY_LENGTH = 1024
9
+ const MAX_DECODE_PASSES = 6
10
+ // Matches ASCII C0 controls (including NUL 0x00) and DEL (0x7f).
11
+ // eslint-disable-next-line no-control-regex
12
+ const CONTROL_CHAR_RE = /[\u0000-\u001F\u007F]/
13
+ // Catches single- or multi-percent-encoded `/`, `\`, or NUL (`%2f`, `%5c`, `%00`, `%252f`, ...).
14
+ const ENCODED_FORBIDDEN_RE = /%(?:25)*(?:2f|5c|00)/i
15
+ // Catches single- or multi-percent-encoded `.` or `..` segments even when mixed with malformed escapes.
16
+ const ENCODED_DOT_TOKEN_RE = /^(?:\.|%(?:25)*2e){1,2}$/i
17
+ const TTL_STRING_RE = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)$/i
18
+
19
+ const TTL_UNIT_SECONDS: Record<string, number> = {
20
+ s: 1,
21
+ m: 60,
22
+ h: 3600,
23
+ d: 86_400,
24
+ }
25
+
26
+ function invalidKey(label: string, reason: string): never {
27
+ throw new FilesError('INVALID_KEY', `@prunellejs/files: invalid ${label}: ${reason}.`, 400)
28
+ }
29
+
30
+ function safeDecodeOnce(value: string): string {
31
+ try {
32
+ return decodeURIComponent(value)
33
+ }
34
+ catch {
35
+ return value
36
+ }
37
+ }
38
+
39
+ function assertSafeSegment(segment: string, label: string): void {
40
+ if (segment.length === 0)
41
+ invalidKey(label, 'empty path segment is not allowed')
42
+ if (segment === '.' || segment === '..')
43
+ invalidKey(label, 'path traversal segment ("." or "..") is not allowed')
44
+ if (ENCODED_DOT_TOKEN_RE.test(segment))
45
+ invalidKey(label, 'encoded path traversal segment is not allowed')
46
+
47
+ let current = segment
48
+ for (let pass = 0; pass < MAX_DECODE_PASSES; pass++) {
49
+ if (CONTROL_CHAR_RE.test(current))
50
+ invalidKey(label, 'control characters and NUL bytes are not allowed')
51
+ if (current.includes('\\'))
52
+ invalidKey(label, 'backslashes are not allowed')
53
+ if (pass > 0 && current.includes('/'))
54
+ invalidKey(label, 'encoded path separators are not allowed')
55
+ if (current === '.' || current === '..' || ENCODED_DOT_TOKEN_RE.test(current))
56
+ invalidKey(label, 'encoded path traversal segment is not allowed')
57
+ if (ENCODED_FORBIDDEN_RE.test(current))
58
+ invalidKey(label, 'encoded separator or NUL byte is not allowed')
59
+
60
+ const next = safeDecodeOnce(current)
61
+ if (next === current)
62
+ break
63
+ current = next
64
+ }
65
+ }
66
+
67
+ function assertRawKeyBasics(raw: string, label: string): void {
68
+ if (typeof raw !== 'string' || raw.length === 0)
69
+ invalidKey(label, 'value must be a non-empty string')
70
+ if (raw.length > MAX_KEY_LENGTH)
71
+ invalidKey(label, `length exceeds ${MAX_KEY_LENGTH} characters`)
72
+ if (CONTROL_CHAR_RE.test(raw))
73
+ invalidKey(label, 'control characters and NUL bytes are not allowed')
74
+ if (raw.includes('\\'))
75
+ invalidKey(label, 'backslashes are not allowed')
76
+ if (raw.startsWith('/'))
77
+ invalidKey(label, 'leading slash is not allowed')
78
+ if (ENCODED_FORBIDDEN_RE.test(raw))
79
+ invalidKey(label, 'encoded separator or NUL byte is not allowed')
80
+ }
81
+
82
+ /**
83
+ * Validates and normalizes a storage file key.
84
+ * Rejects leading/trailing slashes, empty segments, `.` / `..`, backslashes, NUL/control characters,
85
+ * and single- or multi-percent-encoded traversal sequences (`%2e%2e`, `%252e%252e`, `%2f`, `%5c`, `%00`).
86
+ */
87
+ export function normalizeFileKey(key: string): string {
88
+ assertRawKeyBasics(key, 'file key')
89
+ if (key.endsWith('/'))
90
+ invalidKey('file key', 'trailing slash is not allowed')
91
+
92
+ const segments = key.split('/')
93
+ for (let i = 0; i < segments.length; i++)
94
+ assertSafeSegment(segments[i]!, 'file key')
95
+ return segments.join('/')
96
+ }
97
+
98
+ /**
99
+ * Validates and normalizes a storage key prefix (used for `put({ prefix })`, `list(prefix)`, and `deleteWhere(prefix)`).
100
+ * Strips a single trailing slash when present so `'users/42/'` and `'users/42'` normalize identically.
101
+ */
102
+ export function normalizeFilePrefix(prefix: string, options?: { allowEmpty?: boolean | undefined }): string {
103
+ if (prefix === '') {
104
+ if (options?.allowEmpty === true)
105
+ return ''
106
+ invalidKey('file prefix', 'prefix must not be empty')
107
+ }
108
+ assertRawKeyBasics(prefix, 'file prefix')
109
+ const trimmed = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix
110
+ if (trimmed.length === 0)
111
+ invalidKey('file prefix', 'prefix must not be empty')
112
+
113
+ const segments = trimmed.split('/')
114
+ for (let i = 0; i < segments.length; i++)
115
+ assertSafeSegment(segments[i]!, 'file prefix')
116
+ return segments.join('/')
117
+ }
118
+
119
+ /** Segment-boundary prefix match so `'users/4'` matches `'users/4/a.png'` without touching `'users/42/b.png'`. */
120
+ export function keyMatchesPrefix(key: string, normalizedPrefix: string): boolean {
121
+ if (normalizedPrefix === '')
122
+ return true
123
+ return key === normalizedPrefix || key.startsWith(`${normalizedPrefix}/`)
124
+ }
125
+
126
+ /** Validates `key` and percent-encodes each path segment for safe inclusion in a URL pathname. */
127
+ export function encodeKeySegments(key: string): string {
128
+ const normalized = normalizeFileKey(key)
129
+ return normalized.split('/').map(seg => encodeURIComponent(seg)).join('/')
130
+ }
131
+
132
+ /** Validates and normalizes `createFiles({ basePath })`. */
133
+ export function normalizeBasePath(basePath: string | undefined): string {
134
+ const raw = basePath ?? '/files'
135
+ if (!raw.startsWith('/'))
136
+ throw new FilesError('INVALID_CONFIG', `@prunellejs/files: basePath must start with "/", got ${JSON.stringify(raw)}.`, 500)
137
+ const trimmed = raw.endsWith('/') && raw.length > 1 ? raw.slice(0, -1) : raw
138
+ if (trimmed === '/')
139
+ throw new FilesError('INVALID_CONFIG', '@prunellejs/files: basePath cannot be "/"; use a dedicated prefix such as "/files".', 500)
140
+ return trimmed
141
+ }
142
+
143
+ /** Parses a TTL given in positive seconds or a duration string (`'30s'`, `'10m'`, `'1h'`, `'7d'`). */
144
+ export function parseTtlSeconds(ttl: TtlInput): number {
145
+ if (typeof ttl === 'number') {
146
+ if (!Number.isFinite(ttl) || ttl <= 0)
147
+ throw new FilesError('INVALID_TTL', `@prunellejs/files: TTL must be a positive finite number of seconds, got ${String(ttl)}.`, 400)
148
+ return Math.ceil(ttl)
149
+ }
150
+ if (typeof ttl === 'string') {
151
+ const match = TTL_STRING_RE.exec(ttl.trim())
152
+ if (match === null)
153
+ throw new FilesError('INVALID_TTL', `@prunellejs/files: invalid TTL ${JSON.stringify(ttl)}; use seconds or a duration like "30s", "10m", "1h", or "7d".`, 400)
154
+ const amount = Number(match[1])
155
+ const unit = TTL_UNIT_SECONDS[match[2]!.toLowerCase()]
156
+ if (!Number.isFinite(amount) || amount <= 0 || unit === undefined)
157
+ throw new FilesError('INVALID_TTL', `@prunellejs/files: TTL must be greater than zero, got ${JSON.stringify(ttl)}.`, 400)
158
+ return Math.ceil(amount * unit)
159
+ }
160
+ throw new FilesError('INVALID_TTL', '@prunellejs/files: TTL must be a number of seconds or a duration string.', 400)
161
+ }
162
+
163
+ /** Computes a URL-safe base64 HMAC-SHA256 signature binding `key` and expiry timestamp `expUnixSec`. */
164
+ export function signFileUrl(key: string, expUnixSec: number, secret: string): string {
165
+ return createHmac('sha256', secret)
166
+ .update(`${expUnixSec}\n${key}`)
167
+ .digest('base64url')
168
+ }
169
+
170
+ /** Constant-time verification of a signed file URL's expiry and HMAC-SHA256 signature. */
171
+ export function verifyFileSignature(
172
+ key: string,
173
+ expInput: string | number | null | undefined,
174
+ sigInput: string | null | undefined,
175
+ secret: string,
176
+ nowMs: number,
177
+ ): boolean {
178
+ if (sigInput === null || sigInput === undefined || sigInput.length === 0)
179
+ return false
180
+ if (expInput === null || expInput === undefined)
181
+ return false
182
+
183
+ let exp: number
184
+ if (typeof expInput === 'number') {
185
+ exp = expInput
186
+ }
187
+ else {
188
+ if (!/^\d+$/.test(expInput))
189
+ return false
190
+ exp = Number(expInput)
191
+ }
192
+
193
+ if (!Number.isSafeInteger(exp) || exp <= 0)
194
+ return false
195
+ if (nowMs >= exp * 1000)
196
+ return false
197
+
198
+ const expected = signFileUrl(key, exp, secret)
199
+ return safeEqual(sigInput, expected)
200
+ }
201
+
202
+ /** Sanitizes an optional original filename into a URL-safe stem (never keeping its untrusted extension). */
203
+ export function sanitizeFilenameStem(filename: string | undefined): string {
204
+ if (filename === undefined || filename.length === 0)
205
+ return ''
206
+ const base = filename.split(/[\\/]/).pop() ?? ''
207
+ const dot = base.lastIndexOf('.')
208
+ const rawStem = dot > 0 ? base.slice(0, dot) : base
209
+ const clean = rawStem
210
+ .normalize('NFKD')
211
+ .replace(/[\u0300-\u036F]/g, '')
212
+ .toLowerCase()
213
+ .replace(/[^a-z0-9_-]+/g, '-')
214
+ .replace(/^-+|-+$/g, '')
215
+ .slice(0, 40)
216
+ return clean
217
+ }
package/src/sniff.ts ADDED
@@ -0,0 +1,280 @@
1
+ // Magic-byte MIME type detection and allowlist matching (never trusts client-supplied File.type or extensions).
2
+
3
+ export const DEFAULT_ALLOWED_MIMES: readonly string[] = [
4
+ 'image/png',
5
+ 'image/jpeg',
6
+ 'image/webp',
7
+ 'image/gif',
8
+ 'image/avif',
9
+ 'application/pdf',
10
+ ]
11
+
12
+ const PNG_SIG = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
13
+ const JPEG_SIG = [0xFF, 0xD8, 0xFF]
14
+ const GIF87_SIG = [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]
15
+ const GIF89_SIG = [0x47, 0x49, 0x46, 0x38, 0x39, 0x61]
16
+ const PDF_SIG = [0x25, 0x50, 0x44, 0x46, 0x2D]
17
+ const GZIP_SIG = [0x1F, 0x8B, 0x08]
18
+ const OGG_SIG = [0x4F, 0x67, 0x67, 0x53]
19
+ const EBML_SIG = [0x1A, 0x45, 0xDF, 0xA3]
20
+ const ID3_SIG = [0x49, 0x44, 0x33]
21
+ const ICO_SIG = [0x00, 0x00, 0x01, 0x00]
22
+ const RIFF_SIG = [0x52, 0x49, 0x46, 0x46]
23
+ const FTYP_SIG = [0x66, 0x74, 0x79, 0x70]
24
+
25
+ const AVIF_BRANDS = new Set(['avif', 'avis'])
26
+ const MP4_BRANDS = new Set([
27
+ 'isom',
28
+ 'iso2',
29
+ 'iso3',
30
+ 'iso4',
31
+ 'iso5',
32
+ 'iso6',
33
+ 'mp41',
34
+ 'mp42',
35
+ 'M4V ',
36
+ 'M4A ',
37
+ 'avc1',
38
+ 'qt ',
39
+ 'dash',
40
+ 'msdh',
41
+ 'msix',
42
+ 'f4v ',
43
+ ])
44
+
45
+ const MIME_EXTENSIONS: Record<string, string> = {
46
+ 'image/png': 'png',
47
+ 'image/jpeg': 'jpg',
48
+ 'image/gif': 'gif',
49
+ 'image/webp': 'webp',
50
+ 'image/avif': 'avif',
51
+ 'image/svg+xml': 'svg',
52
+ 'image/x-icon': 'ico',
53
+ 'application/pdf': 'pdf',
54
+ 'application/zip': 'zip',
55
+ 'application/gzip': 'gz',
56
+ 'video/mp4': 'mp4',
57
+ 'video/webm': 'webm',
58
+ 'audio/mpeg': 'mp3',
59
+ 'audio/ogg': 'ogg',
60
+ 'audio/wav': 'wav',
61
+ 'text/plain': 'txt',
62
+ 'text/html': 'html',
63
+ 'application/xml': 'xml',
64
+ 'application/octet-stream': 'bin',
65
+ }
66
+
67
+ const UTF8_DECODER = new TextDecoder('utf-8', { fatal: true })
68
+
69
+ function hasBytesAt(bytes: Uint8Array, offset: number, expected: readonly number[]): boolean {
70
+ if (bytes.byteLength < offset + expected.length)
71
+ return false
72
+ for (let i = 0; i < expected.length; i++) {
73
+ if (bytes[offset + i] !== expected[i])
74
+ return false
75
+ }
76
+ return true
77
+ }
78
+
79
+ function readAscii4(bytes: Uint8Array, offset: number): string {
80
+ return String.fromCharCode(
81
+ bytes[offset]!,
82
+ bytes[offset + 1]!,
83
+ bytes[offset + 2]!,
84
+ bytes[offset + 3]!,
85
+ )
86
+ }
87
+
88
+ function sniffRiff(bytes: Uint8Array): string | undefined {
89
+ if (bytes.byteLength < 12 || !hasBytesAt(bytes, 0, RIFF_SIG))
90
+ return undefined
91
+ const form = readAscii4(bytes, 8)
92
+ if (form === 'WEBP')
93
+ return 'image/webp'
94
+ if (form === 'WAVE')
95
+ return 'audio/wav'
96
+ return undefined
97
+ }
98
+
99
+ function sniffIsoBmff(bytes: Uint8Array): string | undefined {
100
+ if (bytes.byteLength < 12 || !hasBytesAt(bytes, 4, FTYP_SIG))
101
+ return undefined
102
+
103
+ const boxSize = ((bytes[0]! << 24) | (bytes[1]! << 16) | (bytes[2]! << 8) | bytes[3]!) >>> 0
104
+ const scanEnd = Math.min(bytes.byteLength, boxSize >= 12 ? boxSize : bytes.byteLength, 128)
105
+ const major = readAscii4(bytes, 8)
106
+ if (AVIF_BRANDS.has(major))
107
+ return 'image/avif'
108
+
109
+ let hasMp4Brand = MP4_BRANDS.has(major)
110
+ for (let offset = 16; offset + 4 <= scanEnd; offset += 4) {
111
+ const brand = readAscii4(bytes, offset)
112
+ if (AVIF_BRANDS.has(brand))
113
+ return 'image/avif'
114
+ if (MP4_BRANDS.has(brand))
115
+ hasMp4Brand = true
116
+ }
117
+ return hasMp4Brand ? 'video/mp4' : undefined
118
+ }
119
+
120
+ function sniffZip(bytes: Uint8Array): boolean {
121
+ if (bytes.byteLength < 4 || bytes[0] !== 0x50 || bytes[1] !== 0x4B)
122
+ return false
123
+ const b2 = bytes[2]!
124
+ const b3 = bytes[3]!
125
+ return (b2 === 0x03 && b3 === 0x04)
126
+ || (b2 === 0x05 && b3 === 0x06)
127
+ || (b2 === 0x07 && b3 === 0x08)
128
+ }
129
+
130
+ function sniffWebm(bytes: Uint8Array): boolean {
131
+ if (!hasBytesAt(bytes, 0, EBML_SIG))
132
+ return false
133
+ const head = bytes.subarray(0, Math.min(bytes.byteLength, 64))
134
+ for (let i = 4; i + 4 <= head.length; i++) {
135
+ if (head[i] === 0x77 && head[i + 1] === 0x65 && head[i + 2] === 0x62 && head[i + 3] === 0x6D)
136
+ return true
137
+ }
138
+ return false
139
+ }
140
+
141
+ function sniffMp3Frame(bytes: Uint8Array): boolean {
142
+ if (bytes.byteLength < 2)
143
+ return false
144
+ const b0 = bytes[0]!
145
+ const b1 = bytes[1]!
146
+ // MPEG frame sync: 11 leading 1-bits (`0xFF`, top 3 bits of b1 set), valid version (!= 01), valid layer (!= 00).
147
+ return b0 === 0xFF && (b1 & 0xE0) === 0xE0 && (b1 & 0x18) !== 0x08 && (b1 & 0x06) !== 0x00
148
+ }
149
+
150
+ function sniffBinaryMime(bytes: Uint8Array): string | undefined {
151
+ if (hasBytesAt(bytes, 0, PNG_SIG))
152
+ return 'image/png'
153
+ if (hasBytesAt(bytes, 0, JPEG_SIG))
154
+ return 'image/jpeg'
155
+ if (hasBytesAt(bytes, 0, GIF87_SIG) || hasBytesAt(bytes, 0, GIF89_SIG))
156
+ return 'image/gif'
157
+
158
+ const riff = sniffRiff(bytes)
159
+ if (riff !== undefined)
160
+ return riff
161
+
162
+ const iso = sniffIsoBmff(bytes)
163
+ if (iso !== undefined)
164
+ return iso
165
+
166
+ if (hasBytesAt(bytes, 0, PDF_SIG))
167
+ return 'application/pdf'
168
+ if (sniffZip(bytes))
169
+ return 'application/zip'
170
+ if (hasBytesAt(bytes, 0, GZIP_SIG))
171
+ return 'application/gzip'
172
+ if (sniffWebm(bytes))
173
+ return 'video/webm'
174
+ if (hasBytesAt(bytes, 0, OGG_SIG))
175
+ return 'audio/ogg'
176
+ if (hasBytesAt(bytes, 0, ID3_SIG) || sniffMp3Frame(bytes))
177
+ return 'audio/mpeg'
178
+ if (hasBytesAt(bytes, 0, ICO_SIG) && bytes.byteLength >= 6 && (bytes[4]! !== 0 || bytes[5]! !== 0))
179
+ return 'image/x-icon'
180
+ return undefined
181
+ }
182
+
183
+ function hasDisallowedBinaryControls(bytes: Uint8Array): boolean {
184
+ const limit = Math.min(bytes.byteLength, 8192)
185
+ for (let i = 0; i < limit; i++) {
186
+ const b = bytes[i]!
187
+ if (b === 0x00)
188
+ return true
189
+ if (b < 0x20 && b !== 0x09 && b !== 0x0A && b !== 0x0D && b !== 0x0C)
190
+ return true
191
+ }
192
+ return false
193
+ }
194
+
195
+ function stripLeadingMarkupPrologue(text: string): string {
196
+ let rest = text.replace(/^\uFEFF/, '').trimStart()
197
+ for (let i = 0; i < 8; i++) {
198
+ if (rest.startsWith('<?xml')) {
199
+ const end = rest.indexOf('?>')
200
+ if (end < 0)
201
+ break
202
+ rest = rest.slice(end + 2).trimStart()
203
+ continue
204
+ }
205
+ if (rest.startsWith('<!--')) {
206
+ const end = rest.indexOf('-->')
207
+ if (end < 0)
208
+ break
209
+ rest = rest.slice(end + 3).trimStart()
210
+ continue
211
+ }
212
+ if (/^<!doctype\s+svg\b/i.test(rest)) {
213
+ const end = rest.indexOf('>')
214
+ if (end < 0)
215
+ break
216
+ rest = rest.slice(end + 1).trimStart()
217
+ continue
218
+ }
219
+ break
220
+ }
221
+ return rest
222
+ }
223
+
224
+ function sniffTextMime(bytes: Uint8Array): string | undefined {
225
+ if (bytes.byteLength === 0 || hasDisallowedBinaryControls(bytes))
226
+ return undefined
227
+
228
+ // Decode a bounded prefix for markup detection, and validate UTF-8 across the full buffer.
229
+ let fullText: string
230
+ try {
231
+ fullText = UTF8_DECODER.decode(bytes)
232
+ }
233
+ catch {
234
+ return undefined
235
+ }
236
+
237
+ const head = fullText.slice(0, 4096)
238
+ const trimmed = head.replace(/^\uFEFF/, '').trimStart()
239
+ if (/^<!doctype\s+html\b/i.test(trimmed) || /^<(?:html|head|body|script)\b/i.test(trimmed))
240
+ return 'text/html'
241
+
242
+ const afterPrologue = stripLeadingMarkupPrologue(head)
243
+ if (/^<svg(?:\s|>|\/)/i.test(afterPrologue))
244
+ return 'image/svg+xml'
245
+ if (trimmed.startsWith('<?xml'))
246
+ return 'application/xml'
247
+
248
+ return 'text/plain'
249
+ }
250
+
251
+ /**
252
+ * Sniffs the real MIME type from file bytes (magic bytes + UTF-8/SVG/HTML text inspection).
253
+ * Returns `undefined` for empty or unrecognized binary data.
254
+ */
255
+ export function sniffMime(bytes: Uint8Array): string | undefined {
256
+ if (bytes.byteLength === 0)
257
+ return undefined
258
+ return sniffBinaryMime(bytes) ?? sniffTextMime(bytes)
259
+ }
260
+
261
+ // Returns whether `detectedMime` matches at least one entry in `allow` (exact MIME, `type/*`, or wildcard `*/*`).
262
+ export function mimeMatchesAllowlist(detectedMime: string, allow: readonly string[]): boolean {
263
+ const mime = detectedMime.toLowerCase()
264
+ const slash = mime.indexOf('/')
265
+ const major = slash > 0 ? mime.slice(0, slash) : ''
266
+
267
+ for (let i = 0; i < allow.length; i++) {
268
+ const pattern = allow[i]!.trim().toLowerCase()
269
+ if (pattern === '*/*' || pattern === mime)
270
+ return true
271
+ if (pattern.endsWith('/*') && major.length > 0 && pattern.slice(0, -2) === major)
272
+ return true
273
+ }
274
+ return false
275
+ }
276
+
277
+ /** Canonical file extension (without leading dot) for a detected MIME type. */
278
+ export function extensionForMime(mime: string): string {
279
+ return MIME_EXTENSIONS[mime.toLowerCase()] ?? 'bin'
280
+ }