@cslug/storage 0.1.0 → 0.3.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/README.md +5 -2
- package/docs/README.md +60 -3
- package/docs/api.md +16 -0
- package/package.json +12 -2
- package/src/disk.ts +122 -0
- package/src/drivers.ts +148 -0
- package/src/fake.ts +34 -0
- package/src/index.ts +20 -4
- package/src/provider.ts +81 -0
- package/src/storage.ts +86 -0
package/README.md
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# @cslug/storage
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Disks for uploaded and generated files: local, any S3-compatible service (through `Bun.s3`), and memory.
|
|
4
|
+
Generated keys with the type sniffed from the bytes, signed download and direct-upload URLs, and a fake for tests.
|
|
5
|
+
List `StorageProvider` in `bootstrap/providers.ts`.
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
8
|
+
[guide 17](../../guides/17-storage-and-webhooks.md).
|
package/docs/README.md
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
# @cslug/storage
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
List `StorageProvider` in `bootstrap/providers.ts` and inject `Storage`. The guide is
|
|
4
|
+
[guide 17](../../../guides/17-storage-and-webhooks.md#storage).
|
|
4
5
|
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
## Disks
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
// config/storage.ts
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
default: env.APP_ENV === 'production' ? 's3' : 'local',
|
|
12
|
+
disks: {
|
|
13
|
+
local: { driver: 'local', root: 'storage/app' }, // relative to the app root
|
|
14
|
+
s3: { driver: 's3', bucket: env.S3_BUCKET, endpoint: env.S3_ENDPOINT, region: 'eu-west-3' },
|
|
15
|
+
},
|
|
16
|
+
})
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Without `config/storage.ts` there is one `local` disk at `storage/app`. `Storage` methods use the default disk;
|
|
20
|
+
`storage.disk('s3')` returns another. Drivers:
|
|
21
|
+
|
|
22
|
+
- `local`: files under `root` (`Bun.file`, `Bun.write`).
|
|
23
|
+
- `s3`: any S3-compatible service through `Bun.s3`. The options are `Bun.S3Options`; credentials default to the
|
|
24
|
+
`S3_ACCESS_KEY_ID` / `S3_SECRET_ACCESS_KEY` environment variables.
|
|
25
|
+
- `memory`: in the process (tests, throwaway data).
|
|
26
|
+
|
|
27
|
+
Keys are relative paths (`operators/7/licence/…pdf`); a leading `/`, `.` or `..` segments and backslashes are
|
|
28
|
+
refused (`storage.bad_key`), so a key can never leave the disk.
|
|
29
|
+
|
|
30
|
+
## Writing and reading
|
|
31
|
+
|
|
32
|
+
- `put(key, data, { type? })`: a string, bytes or a `Blob`.
|
|
33
|
+
- `putFile(dir, file)`: for uploads. The key is generated, `dir/<uuidv7>.<ext>`, never the client's file name; the
|
|
34
|
+
extension comes from the type sniffed from the first bytes (PDF, PNG, JPEG, GIF, WebP), else the declared type,
|
|
35
|
+
else the name's extension. Validate the upload first with `v.file({ maxSize, types })`, which checks the bytes too.
|
|
36
|
+
- `get(key)` (bytes), `text(key)`, `stream(key)`, `stat(key)` (`{ size, type }`), `exists(key)`, `delete(key)`
|
|
37
|
+
(a missing key is fine). A missing key throws `FileNotFoundError` (404 when it reaches a response).
|
|
38
|
+
|
|
39
|
+
## Signed URLs
|
|
40
|
+
|
|
41
|
+
`signedUrl(key, { expiresIn, download? })` is a private download link; `download: 'Licence.pdf'` sends it as an
|
|
42
|
+
attachment with that name. On S3 it is presigned by the service. On a local disk the app serves it: with
|
|
43
|
+
`@cslug/http` installed, `StorageProvider` adds `GET /_storage/:disk` (route `storage.file`), outside the web and
|
|
44
|
+
api groups, which checks the signature (`APP_KEY`) and expiry and streams the file with `Cache-Control: private,
|
|
45
|
+
no-store`. Without `@cslug/http`, a local signed URL throws `storage.no_http`.
|
|
46
|
+
|
|
47
|
+
## Direct uploads
|
|
48
|
+
|
|
49
|
+
`signedUploadUrl(key, { expiresIn, type, maxSize? })` returns `{ url, method: 'PUT', headers }` for the browser:
|
|
50
|
+
`fetch(url, { method, headers, body: file })`. The content type is part of the signature. When the browser reports
|
|
51
|
+
the upload done, call `verifyUpload(key, { maxSize?, types? })`: it checks the stored size and the type sniffed from
|
|
52
|
+
the bytes, returns `{ size, type }`, and deletes the file and throws `UploadRejectedError` (422,
|
|
53
|
+
`storage.upload_too_large` / `storage.upload_type`) when it does not pass.
|
|
54
|
+
|
|
55
|
+
Why the second step: an S3 presigned PUT cannot limit the size, so the size is checked after the upload. On a local
|
|
56
|
+
disk the `PUT /_storage/:disk` route also refuses another content type (415) and a body over `maxSize` (413), and it
|
|
57
|
+
is subject to `http.bodyLimit`.
|
|
58
|
+
|
|
59
|
+
## Tests
|
|
60
|
+
|
|
61
|
+
`testApp({ fakes: ['storage'] })` replaces every configured disk with a memory disk: `t.storage` is a
|
|
62
|
+
`StorageFake` with `assertExists(key, disk?)`, `assertMissing(key, disk?)` (a key ending in `/` matches any file
|
|
63
|
+
under it, for generated names) and `keys(disk?)`.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# @cslug/storage: API
|
|
2
|
+
|
|
3
|
+
| | |
|
|
4
|
+
|---|---|
|
|
5
|
+
| `Storage` | Injectable. The default disk's methods, `disk(name?)`, `names()`, `defaultDisk` |
|
|
6
|
+
| `Disk` | `put(key, data, { type? })`, `putFile(dir, file)` → key, `get`, `text`, `stream`, `stat` → `{ size, type }`, `exists`, `delete`, `signedUrl(key, { expiresIn, download? })`, `signedUploadUrl(key, { expiresIn, type, maxSize? })` → `{ url, method, headers }`, `verifyUpload(key, { maxSize?, types? })` → `{ size, type }` |
|
|
7
|
+
| `LocalDisk(name, root)` | `path(key)`; signed URLs through `StorageProvider` and @cslug/http |
|
|
8
|
+
| `S3Disk(name, options)` | `Bun.S3Options`; `client` is the `S3Client` |
|
|
9
|
+
| `MemoryDisk(name)` | `files`: the stored `Blob`s by key |
|
|
10
|
+
| `StorageProvider` | Config `storage`: `default`, `disks.<name>` (`{ driver: 'local', root }`, `{ driver: 's3', …S3Options }`, `{ driver: 'memory' }`). With @cslug/http: `GET`/`PUT /_storage/:disk` (route `storage.file`) |
|
|
11
|
+
| `createDisk(name, config, rootDir)` | A disk from its config |
|
|
12
|
+
| `checkKey(key)` | The key, or `storage.bad_key` |
|
|
13
|
+
| `extensionFor(type, name?)` | Extension for a type, else the name's |
|
|
14
|
+
| `FileNotFoundError` | 404 `storage.not_found`; `key` |
|
|
15
|
+
| `UploadRejectedError` | 422 `storage.upload_too_large` / `storage.upload_type` |
|
|
16
|
+
| `StorageFake`, `installStorageFake(app)` | `fakes: ['storage']`: memory disks, `assertExists`, `assertMissing`, `keys` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/storage",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Local and S3 disks, signed URLs, upload type sniffing.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -28,6 +28,16 @@
|
|
|
28
28
|
"bun": ">=1.3.14"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"@cslug/core": "0.
|
|
31
|
+
"@cslug/core": "0.3.0",
|
|
32
|
+
"@cslug/http": "0.3.0"
|
|
33
|
+
},
|
|
34
|
+
"peerDependenciesMeta": {
|
|
35
|
+
"@cslug/http": {
|
|
36
|
+
"optional": true
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@cslug/testing": "workspace:*",
|
|
41
|
+
"@cslug/http": "workspace:*"
|
|
32
42
|
}
|
|
33
43
|
}
|
package/src/disk.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { AppError, CslugError, type Duration, parseSize, sniffType } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** What `put()` accepts. */
|
|
4
|
+
export type Body = string | Uint8Array | ArrayBuffer | Blob
|
|
5
|
+
export type PutOptions = { type?: string }
|
|
6
|
+
/** `download` sends the file as an attachment with this name. */
|
|
7
|
+
export type SignedUrlOptions = { expiresIn: Duration; download?: string }
|
|
8
|
+
export type UploadUrlOptions = { expiresIn: Duration; type: string; maxSize?: string | number }
|
|
9
|
+
/** Where and how the browser sends the file: `fetch(url, { method, headers, body: file })`. */
|
|
10
|
+
export type UploadUrl = { url: string; method: 'PUT'; headers: Record<string, string> }
|
|
11
|
+
export type FileInfo = { size: number; type: string }
|
|
12
|
+
export type UploadRules = { maxSize?: string | number; types?: readonly string[] }
|
|
13
|
+
|
|
14
|
+
/** A key that does not exist on the disk. */
|
|
15
|
+
export class FileNotFoundError extends AppError {
|
|
16
|
+
constructor(readonly key: string) {
|
|
17
|
+
super('storage.not_found', 'File not found', { status: 404 })
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A direct upload that `verifyUpload()` refused (it is deleted). */
|
|
22
|
+
export class UploadRejectedError extends AppError {
|
|
23
|
+
constructor(reason: 'too_large' | 'type') {
|
|
24
|
+
super(`storage.upload_${reason}`, reason === 'type' ? 'File type not allowed' : 'File too large', { status: 422 })
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Keys are relative paths: no leading `/`, no `.` or `..` segments, no backslashes. */
|
|
29
|
+
export function checkKey(key: string): string {
|
|
30
|
+
if (!key || /^\/|\\|\0/.test(key) || key.split('/').some((s) => s === '' || s === '.' || s === '..'))
|
|
31
|
+
throw new CslugError('storage.bad_key', `Invalid storage key "${key}"`)
|
|
32
|
+
return key
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const EXTENSIONS: Record<string, string> = {
|
|
36
|
+
'application/pdf': 'pdf',
|
|
37
|
+
'image/png': 'png',
|
|
38
|
+
'image/jpeg': 'jpg',
|
|
39
|
+
'image/gif': 'gif',
|
|
40
|
+
'image/webp': 'webp',
|
|
41
|
+
'image/svg+xml': 'svg',
|
|
42
|
+
'text/plain': 'txt',
|
|
43
|
+
'text/csv': 'csv',
|
|
44
|
+
'application/json': 'json',
|
|
45
|
+
'application/zip': 'zip',
|
|
46
|
+
'audio/mpeg': 'mp3',
|
|
47
|
+
'video/mp4': 'mp4',
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The extension for a type, else the file name's (letters and digits only), else none. */
|
|
51
|
+
export function extensionFor(type: string, name?: string): string {
|
|
52
|
+
const known = EXTENSIONS[type.split(';')[0]?.trim() ?? '']
|
|
53
|
+
if (known) return known
|
|
54
|
+
const fromName = /\.([a-z0-9]{1,8})$/i.exec(name ?? '')?.[1]
|
|
55
|
+
return fromName ? fromName.toLowerCase() : ''
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* One storage location. Drivers provide `file()` (a Blob over the stored bytes), `put`, `exists`, `delete`, and
|
|
60
|
+
* signed URLs; reading, `putFile` and `verifyUpload` are shared.
|
|
61
|
+
*/
|
|
62
|
+
export abstract class Disk {
|
|
63
|
+
constructor(readonly name: string) {}
|
|
64
|
+
|
|
65
|
+
protected abstract file(key: string): Blob
|
|
66
|
+
abstract put(key: string, data: Body, options?: PutOptions): Promise<void>
|
|
67
|
+
abstract exists(key: string): Promise<boolean>
|
|
68
|
+
/** Deleting a missing key is not an error. */
|
|
69
|
+
abstract delete(key: string): Promise<void>
|
|
70
|
+
/** A private download link. */
|
|
71
|
+
abstract signedUrl(key: string, options: SignedUrlOptions): Promise<string>
|
|
72
|
+
/** A link the browser uploads to directly; call `verifyUpload()` once it reports the upload done. */
|
|
73
|
+
abstract signedUploadUrl(key: string, options: UploadUrlOptions): Promise<UploadUrl>
|
|
74
|
+
|
|
75
|
+
async stat(key: string): Promise<FileInfo> {
|
|
76
|
+
if (!(await this.exists(key))) throw new FileNotFoundError(key)
|
|
77
|
+
const f = this.file(key)
|
|
78
|
+
return { size: f.size, type: f.type }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async get(key: string): Promise<Uint8Array> {
|
|
82
|
+
try {
|
|
83
|
+
return new Uint8Array(await this.file(key).arrayBuffer())
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!(await this.exists(key))) throw new FileNotFoundError(key)
|
|
86
|
+
throw error
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async text(key: string): Promise<string> {
|
|
91
|
+
return new TextDecoder().decode(await this.get(key))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async stream(key: string): Promise<ReadableStream<Uint8Array>> {
|
|
95
|
+
if (!(await this.exists(key))) throw new FileNotFoundError(key)
|
|
96
|
+
return this.file(key).stream()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Store an upload under a generated name, `dir/<uuidv7>.<ext>` (type sniffed from the bytes); returns the key. */
|
|
100
|
+
async putFile(dir: string, file: Blob): Promise<string> {
|
|
101
|
+
const type = (await sniffType(file)) ?? file.type
|
|
102
|
+
const ext = extensionFor(type, (file as Partial<File>).name)
|
|
103
|
+
const key = checkKey(`${dir.replace(/\/+$/, '')}/${Bun.randomUUIDv7()}${ext ? `.${ext}` : ''}`)
|
|
104
|
+
await this.put(key, file, type ? { type } : {})
|
|
105
|
+
return key
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** After a direct upload: check size and type (from the bytes when recognisable); a refused file is deleted. */
|
|
109
|
+
async verifyUpload(key: string, rules: UploadRules): Promise<FileInfo> {
|
|
110
|
+
const info = await this.stat(key)
|
|
111
|
+
let reason: 'too_large' | 'type' | undefined
|
|
112
|
+
if (rules.maxSize !== undefined && info.size > parseSize(rules.maxSize)) reason = 'too_large'
|
|
113
|
+
else if (rules.types) {
|
|
114
|
+
const type = (await sniffType(this.file(key))) ?? info.type.split(';')[0] ?? ''
|
|
115
|
+
if (!rules.types.includes(type)) reason = 'type'
|
|
116
|
+
else info.type = type
|
|
117
|
+
}
|
|
118
|
+
if (!reason) return info
|
|
119
|
+
await this.delete(key)
|
|
120
|
+
throw new UploadRejectedError(reason)
|
|
121
|
+
}
|
|
122
|
+
}
|
package/src/drivers.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { rm } from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { CslugError, parseDuration, parseSize } from '@cslug/core'
|
|
4
|
+
import { S3Client, type S3Options } from 'bun'
|
|
5
|
+
import {
|
|
6
|
+
type Body,
|
|
7
|
+
checkKey,
|
|
8
|
+
Disk,
|
|
9
|
+
type FileInfo,
|
|
10
|
+
FileNotFoundError,
|
|
11
|
+
type PutOptions,
|
|
12
|
+
type SignedUrlOptions,
|
|
13
|
+
type UploadUrl,
|
|
14
|
+
type UploadUrlOptions,
|
|
15
|
+
} from './disk'
|
|
16
|
+
|
|
17
|
+
const seconds = (options: { expiresIn: SignedUrlOptions['expiresIn'] }) =>
|
|
18
|
+
Math.max(1, Math.round(parseDuration(options.expiresIn) / 1000))
|
|
19
|
+
const attachment = (name: string) => `attachment; filename="${name.replace(/["\\\r\n]/g, '_')}"`
|
|
20
|
+
|
|
21
|
+
/** Signs local-disk URLs; set by `StorageProvider` when @cslug/http is installed (served at `/_storage/:disk`). */
|
|
22
|
+
export type LocalSigner = (
|
|
23
|
+
query: Record<string, string>,
|
|
24
|
+
options: { expiresIn: SignedUrlOptions['expiresIn'] },
|
|
25
|
+
) => string
|
|
26
|
+
|
|
27
|
+
/** Files under a directory (`root`). Signed URLs are served by the app itself. */
|
|
28
|
+
export class LocalDisk extends Disk {
|
|
29
|
+
signer?: LocalSigner
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
name: string,
|
|
33
|
+
readonly root: string,
|
|
34
|
+
) {
|
|
35
|
+
super(name)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
path(key: string): string {
|
|
39
|
+
return join(this.root, checkKey(key))
|
|
40
|
+
}
|
|
41
|
+
protected file(key: string) {
|
|
42
|
+
return Bun.file(this.path(key))
|
|
43
|
+
}
|
|
44
|
+
async put(key: string, data: Body): Promise<void> {
|
|
45
|
+
await Bun.write(this.path(key), data, { createPath: true })
|
|
46
|
+
}
|
|
47
|
+
exists(key: string): Promise<boolean> {
|
|
48
|
+
return this.file(key).exists()
|
|
49
|
+
}
|
|
50
|
+
async delete(key: string): Promise<void> {
|
|
51
|
+
await rm(this.path(key), { force: true })
|
|
52
|
+
}
|
|
53
|
+
private sign(query: Record<string, string>, options: { expiresIn: SignedUrlOptions['expiresIn'] }): string {
|
|
54
|
+
if (!this.signer)
|
|
55
|
+
throw new CslugError('storage.no_http', `Signed URLs on the local disk "${this.name}" need @cslug/http`)
|
|
56
|
+
return this.signer({ disk: this.name, ...query }, options)
|
|
57
|
+
}
|
|
58
|
+
async signedUrl(key: string, options: SignedUrlOptions): Promise<string> {
|
|
59
|
+
return this.sign({ key: checkKey(key), ...(options.download ? { download: options.download } : {}) }, options)
|
|
60
|
+
}
|
|
61
|
+
async signedUploadUrl(key: string, options: UploadUrlOptions): Promise<UploadUrl> {
|
|
62
|
+
const query: Record<string, string> = { key: checkKey(key), upload: options.type }
|
|
63
|
+
if (options.maxSize !== undefined) query.max = String(parseSize(options.maxSize))
|
|
64
|
+
return { url: this.sign(query, options), method: 'PUT', headers: { 'content-type': options.type } }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** `config/storage.ts` → `{ driver: 's3', bucket, endpoint?, region?, accessKeyId?, secretAccessKey? }` (credentials default to the S3_* env). */
|
|
69
|
+
export type S3DiskConfig = { driver: 's3' } & S3Options
|
|
70
|
+
|
|
71
|
+
/** Any S3-compatible service, through `Bun.s3`. Signed URLs are presigned by the service's credentials. */
|
|
72
|
+
export class S3Disk extends Disk {
|
|
73
|
+
readonly client: S3Client
|
|
74
|
+
|
|
75
|
+
constructor(name: string, config: S3Options) {
|
|
76
|
+
super(name)
|
|
77
|
+
this.client = new S3Client(config)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
protected file(key: string) {
|
|
81
|
+
return this.client.file(checkKey(key))
|
|
82
|
+
}
|
|
83
|
+
async put(key: string, data: Body, options: PutOptions = {}): Promise<void> {
|
|
84
|
+
await this.client.write(checkKey(key), data, options.type ? { type: options.type } : {})
|
|
85
|
+
}
|
|
86
|
+
exists(key: string): Promise<boolean> {
|
|
87
|
+
return this.client.exists(checkKey(key))
|
|
88
|
+
}
|
|
89
|
+
async delete(key: string): Promise<void> {
|
|
90
|
+
await this.client.delete(checkKey(key))
|
|
91
|
+
}
|
|
92
|
+
override async stat(key: string): Promise<FileInfo> {
|
|
93
|
+
try {
|
|
94
|
+
const s = await this.client.stat(checkKey(key))
|
|
95
|
+
return { size: s.size, type: s.type }
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if ((error as { code?: string }).code === 'NoSuchKey' || !(await this.exists(key)))
|
|
98
|
+
throw new FileNotFoundError(key)
|
|
99
|
+
throw error
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async signedUrl(key: string, options: SignedUrlOptions): Promise<string> {
|
|
103
|
+
return this.client.presign(checkKey(key), {
|
|
104
|
+
method: 'GET',
|
|
105
|
+
expiresIn: seconds(options),
|
|
106
|
+
...(options.download ? { contentDisposition: attachment(options.download) } : {}),
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
/** Presigned PUT: the type is part of the signature; the size is checked afterwards by `verifyUpload()`. */
|
|
110
|
+
async signedUploadUrl(key: string, options: UploadUrlOptions): Promise<UploadUrl> {
|
|
111
|
+
const url = this.client.presign(checkKey(key), { method: 'PUT', expiresIn: seconds(options), type: options.type })
|
|
112
|
+
return { url, method: 'PUT', headers: { 'content-type': options.type } }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Files in memory: the `memory` driver and the test fake. Signed URLs are `memory://` placeholders. */
|
|
117
|
+
export class MemoryDisk extends Disk {
|
|
118
|
+
readonly files = new Map<string, Blob>()
|
|
119
|
+
|
|
120
|
+
protected file(key: string): Blob {
|
|
121
|
+
const blob = this.files.get(checkKey(key))
|
|
122
|
+
if (!blob) throw new FileNotFoundError(key)
|
|
123
|
+
return blob
|
|
124
|
+
}
|
|
125
|
+
async put(key: string, data: Body, options: PutOptions = {}): Promise<void> {
|
|
126
|
+
// a copy: later changes to the caller's buffer must not change the stored file
|
|
127
|
+
const bytes =
|
|
128
|
+
data instanceof Blob ? await data.arrayBuffer() : typeof data === 'string' ? data : new Uint8Array(data)
|
|
129
|
+
const type = options.type ?? (data instanceof Blob ? data.type : '')
|
|
130
|
+
this.files.set(checkKey(key), new Blob([bytes], { type }))
|
|
131
|
+
}
|
|
132
|
+
async exists(key: string): Promise<boolean> {
|
|
133
|
+
return this.files.has(checkKey(key))
|
|
134
|
+
}
|
|
135
|
+
async delete(key: string): Promise<void> {
|
|
136
|
+
this.files.delete(checkKey(key))
|
|
137
|
+
}
|
|
138
|
+
async signedUrl(key: string, options: SignedUrlOptions): Promise<string> {
|
|
139
|
+
return `memory://${this.name}/${checkKey(key)}?expires=${seconds(options)}`
|
|
140
|
+
}
|
|
141
|
+
async signedUploadUrl(key: string, options: UploadUrlOptions): Promise<UploadUrl> {
|
|
142
|
+
return {
|
|
143
|
+
url: `memory://${this.name}/${checkKey(key)}?upload=1&expires=${seconds(options)}`,
|
|
144
|
+
method: 'PUT',
|
|
145
|
+
headers: { 'content-type': options.type },
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
package/src/fake.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Application } from '@cslug/core'
|
|
2
|
+
import { MemoryDisk } from './drivers'
|
|
3
|
+
import { DEFAULT_DISKS, Storage, type StorageConfig } from './storage'
|
|
4
|
+
|
|
5
|
+
/** Every configured disk replaced by one in memory (`fakes: ['storage']` → `t.storage`). */
|
|
6
|
+
export class StorageFake extends Storage {
|
|
7
|
+
constructor(names: string[], defaultDisk: string) {
|
|
8
|
+
super(new Map(names.map((n) => [n, new MemoryDisk(n)])), defaultDisk)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Keys on a disk (the default one unless named). */
|
|
12
|
+
keys(disk?: string): string[] {
|
|
13
|
+
return [...(this.disk(disk) as MemoryDisk).files.keys()]
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A file exists at `key`, or under it when `key` ends with `/` (generated names: `putFile`). */
|
|
17
|
+
assertExists(key: string, disk?: string): void {
|
|
18
|
+
if (!this.keys(disk).some((k) => (key.endsWith('/') ? k.startsWith(key) : k === key)))
|
|
19
|
+
throw new Error(`Expected a file at "${key}"; stored: ${this.keys(disk).join(', ') || 'none'}`)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
assertMissing(key: string, disk?: string): void {
|
|
23
|
+
const found = this.keys(disk).filter((k) => (key.endsWith('/') ? k.startsWith(key) : k === key))
|
|
24
|
+
if (found.length) throw new Error(`Expected no file at "${key}"; found ${found.join(', ')}`)
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function installStorageFake(app: Application): StorageFake {
|
|
29
|
+
const config = app.config<StorageConfig | undefined>('storage') ?? {}
|
|
30
|
+
const names = Object.keys(config.disks ?? DEFAULT_DISKS)
|
|
31
|
+
const fake = new StorageFake(names, config.default ?? names[0] ?? 'local')
|
|
32
|
+
app.swap(Storage, fake)
|
|
33
|
+
return fake
|
|
34
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @cslug/storage:
|
|
3
|
-
*
|
|
4
|
-
* Not implemented yet. See docs/packages.md and docs/implementation-plan.md.
|
|
2
|
+
* @cslug/storage: disks (local, S3 through `Bun.s3`, memory), generated keys with the type sniffed from the bytes,
|
|
3
|
+
* signed download and upload URLs, and a fake for tests.
|
|
5
4
|
*/
|
|
6
|
-
export {
|
|
5
|
+
export {
|
|
6
|
+
type Body,
|
|
7
|
+
checkKey,
|
|
8
|
+
Disk,
|
|
9
|
+
extensionFor,
|
|
10
|
+
type FileInfo,
|
|
11
|
+
FileNotFoundError,
|
|
12
|
+
type PutOptions,
|
|
13
|
+
type SignedUrlOptions,
|
|
14
|
+
UploadRejectedError,
|
|
15
|
+
type UploadRules,
|
|
16
|
+
type UploadUrl,
|
|
17
|
+
type UploadUrlOptions,
|
|
18
|
+
} from './disk'
|
|
19
|
+
export { LocalDisk, type LocalSigner, MemoryDisk, S3Disk, type S3DiskConfig } from './drivers'
|
|
20
|
+
export { installStorageFake, StorageFake } from './fake'
|
|
21
|
+
export { StorageProvider } from './provider'
|
|
22
|
+
export { createDisk, type DiskConfig, Storage, type StorageConfig } from './storage'
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { AppError, CslugError, ForbiddenError, ServiceProvider } from '@cslug/core'
|
|
2
|
+
import type { HttpContext } from '@cslug/http'
|
|
3
|
+
import { FileNotFoundError } from './disk'
|
|
4
|
+
import { LocalDisk, type LocalSigner } from './drivers'
|
|
5
|
+
import { createDisk, DEFAULT_DISKS, Storage, type StorageConfig } from './storage'
|
|
6
|
+
|
|
7
|
+
type HttpModule = typeof import('@cslug/http')
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Binds `Storage` from `config/storage.ts`. With @cslug/http installed, local disks get signed URLs served at
|
|
11
|
+
* `/_storage/:disk` (route `storage.file`): GET downloads, PUT receives a direct upload.
|
|
12
|
+
*/
|
|
13
|
+
export class StorageProvider extends ServiceProvider {
|
|
14
|
+
private signer?: LocalSigner
|
|
15
|
+
|
|
16
|
+
register() {
|
|
17
|
+
this.app.singleton(Storage, () => {
|
|
18
|
+
const config = this.app.config<StorageConfig | undefined>('storage') ?? {}
|
|
19
|
+
const defs = config.disks ?? DEFAULT_DISKS
|
|
20
|
+
const disks = new Map(Object.entries(defs).map(([name, c]) => [name, createDisk(name, c, this.app.rootDir)]))
|
|
21
|
+
for (const disk of disks.values())
|
|
22
|
+
if (disk instanceof LocalDisk) disk.signer = (query, options) => this.sign(disk.name, query, options)
|
|
23
|
+
return new Storage(disks, config.default ?? Object.keys(defs)[0] ?? 'local')
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async boot() {
|
|
28
|
+
const http = await import('@cslug/http').catch(() => undefined)
|
|
29
|
+
if (!http || !this.app.has(http.Router)) return
|
|
30
|
+
const router = this.app.resolve(http.Router)
|
|
31
|
+
router.load((r) => {
|
|
32
|
+
r.get('/_storage/:disk', (ctx) => this.serve(http, ctx)).name('storage.file')
|
|
33
|
+
r.put('/_storage/:disk', (ctx) => this.serve(http, ctx))
|
|
34
|
+
})
|
|
35
|
+
this.signer = (query, options) =>
|
|
36
|
+
http.urlFor(
|
|
37
|
+
router,
|
|
38
|
+
this.app.config<string | undefined>('app.url'),
|
|
39
|
+
this.app.config<string | undefined>('app.key'),
|
|
40
|
+
'storage.file',
|
|
41
|
+
query,
|
|
42
|
+
{ signed: true, expiresIn: options.expiresIn },
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private sign(disk: string, query: Record<string, string>, options: Parameters<LocalSigner>[1]): string {
|
|
47
|
+
if (!this.signer)
|
|
48
|
+
throw new CslugError('storage.no_http', `Signed URLs on the local disk "${disk}" need @cslug/http`)
|
|
49
|
+
return this.signer(query, options)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
private async serve(http: HttpModule, ctx: HttpContext): Promise<Response> {
|
|
53
|
+
const key = this.app.config<string | undefined>('app.key')
|
|
54
|
+
if (!key || !http.verifySignedUrl(ctx.request.url.toString(), key))
|
|
55
|
+
throw new ForbiddenError('http.invalid_signature', 'This link is invalid or has expired.')
|
|
56
|
+
const disk = this.app.resolve(Storage).disk(ctx.params.disk)
|
|
57
|
+
if (!(disk instanceof LocalDisk)) throw new FileNotFoundError('')
|
|
58
|
+
const file = ctx.request.query('key') ?? ''
|
|
59
|
+
const upload = ctx.request.query('upload') // the signed content type of an upload link
|
|
60
|
+
if (ctx.request.method === 'PUT') {
|
|
61
|
+
if (!upload) throw new ForbiddenError('storage.not_an_upload_link', 'This link does not accept uploads.')
|
|
62
|
+
if (ctx.request.header('content-type') !== upload)
|
|
63
|
+
throw new AppError('storage.upload_type', `The upload must be sent as ${upload}`, { status: 415 })
|
|
64
|
+
const body = await ctx.request.raw()
|
|
65
|
+
const max = ctx.request.query('max')
|
|
66
|
+
if (max !== undefined && body.byteLength > Number(max))
|
|
67
|
+
throw new AppError('storage.upload_too_large', 'File too large', { status: 413 })
|
|
68
|
+
await disk.put(file, body)
|
|
69
|
+
return new Response(null, { status: 204 })
|
|
70
|
+
}
|
|
71
|
+
if (upload) throw new ForbiddenError('storage.upload_link', 'This link is for uploading.')
|
|
72
|
+
if (!(await disk.exists(file))) throw new FileNotFoundError(file)
|
|
73
|
+
const name = ctx.request.query('download')
|
|
74
|
+
return new Response(Bun.file(disk.path(file)), {
|
|
75
|
+
headers: {
|
|
76
|
+
'cache-control': 'private, no-store',
|
|
77
|
+
...(name ? { 'content-disposition': `attachment; filename="${name.replace(/["\\\r\n]/g, '_')}"` } : {}),
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
}
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { isAbsolute, join } from 'node:path'
|
|
2
|
+
import { CslugError } from '@cslug/core'
|
|
3
|
+
import type { Body, Disk, PutOptions, SignedUrlOptions, UploadRules, UploadUrlOptions } from './disk'
|
|
4
|
+
import { LocalDisk, MemoryDisk, S3Disk, type S3DiskConfig } from './drivers'
|
|
5
|
+
|
|
6
|
+
export type DiskConfig = { driver: 'local'; root: string } | S3DiskConfig | { driver: 'memory' }
|
|
7
|
+
|
|
8
|
+
/** `config/storage.ts`. Without it: one `local` disk at `storage/app`. */
|
|
9
|
+
export type StorageConfig = { default?: string; disks?: Record<string, DiskConfig> }
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_DISKS: Record<string, DiskConfig> = { local: { driver: 'local', root: 'storage/app' } }
|
|
12
|
+
|
|
13
|
+
/** Build a disk from its config; a relative local root is resolved against the app root. */
|
|
14
|
+
export function createDisk(name: string, config: DiskConfig, rootDir: string): Disk {
|
|
15
|
+
switch (config.driver) {
|
|
16
|
+
case 'local':
|
|
17
|
+
return new LocalDisk(name, isAbsolute(config.root) ? config.root : join(rootDir, config.root))
|
|
18
|
+
case 's3': {
|
|
19
|
+
const { driver: _, ...options } = config
|
|
20
|
+
return new S3Disk(name, options)
|
|
21
|
+
}
|
|
22
|
+
case 'memory':
|
|
23
|
+
return new MemoryDisk(name)
|
|
24
|
+
default:
|
|
25
|
+
throw new CslugError(
|
|
26
|
+
'storage.unknown_driver',
|
|
27
|
+
`Unknown storage driver "${(config as { driver: string }).driver}" (local, s3, memory)`,
|
|
28
|
+
)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The configured disks, injected as `Storage`. Its methods use the default disk; `disk(name)` picks another.
|
|
34
|
+
* Uploaded files never live under `public/`: they are read back through the app or a signed URL.
|
|
35
|
+
*/
|
|
36
|
+
export class Storage {
|
|
37
|
+
constructor(
|
|
38
|
+
private readonly disks: ReadonlyMap<string, Disk>,
|
|
39
|
+
readonly defaultDisk: string,
|
|
40
|
+
) {
|
|
41
|
+
if (!disks.has(defaultDisk)) throw new CslugError('storage.unknown_disk', `No disk "${defaultDisk}" configured`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
disk(name = this.defaultDisk): Disk {
|
|
45
|
+
const disk = this.disks.get(name)
|
|
46
|
+
if (!disk) throw new CslugError('storage.unknown_disk', `No disk "${name}" (config storage.disks)`)
|
|
47
|
+
return disk
|
|
48
|
+
}
|
|
49
|
+
names(): string[] {
|
|
50
|
+
return [...this.disks.keys()]
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
put(key: string, data: Body, options?: PutOptions) {
|
|
54
|
+
return this.disk().put(key, data, options)
|
|
55
|
+
}
|
|
56
|
+
putFile(dir: string, file: Blob) {
|
|
57
|
+
return this.disk().putFile(dir, file)
|
|
58
|
+
}
|
|
59
|
+
get(key: string) {
|
|
60
|
+
return this.disk().get(key)
|
|
61
|
+
}
|
|
62
|
+
text(key: string) {
|
|
63
|
+
return this.disk().text(key)
|
|
64
|
+
}
|
|
65
|
+
stream(key: string) {
|
|
66
|
+
return this.disk().stream(key)
|
|
67
|
+
}
|
|
68
|
+
exists(key: string) {
|
|
69
|
+
return this.disk().exists(key)
|
|
70
|
+
}
|
|
71
|
+
stat(key: string) {
|
|
72
|
+
return this.disk().stat(key)
|
|
73
|
+
}
|
|
74
|
+
delete(key: string) {
|
|
75
|
+
return this.disk().delete(key)
|
|
76
|
+
}
|
|
77
|
+
signedUrl(key: string, options: SignedUrlOptions) {
|
|
78
|
+
return this.disk().signedUrl(key, options)
|
|
79
|
+
}
|
|
80
|
+
signedUploadUrl(key: string, options: UploadUrlOptions) {
|
|
81
|
+
return this.disk().signedUploadUrl(key, options)
|
|
82
|
+
}
|
|
83
|
+
verifyUpload(key: string, rules: UploadRules) {
|
|
84
|
+
return this.disk().verifyUpload(key, rules)
|
|
85
|
+
}
|
|
86
|
+
}
|