@cedarjs/storage 0.0.4
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/README.md +123 -0
- package/dist/UrlSigner.d.ts +46 -0
- package/dist/UrlSigner.d.ts.map +1 -0
- package/dist/UrlSigner.js +106 -0
- package/dist/adapters/BaseStorageAdapter.d.ts +31 -0
- package/dist/adapters/BaseStorageAdapter.d.ts.map +1 -0
- package/dist/adapters/BaseStorageAdapter.js +19 -0
- package/dist/adapters/FileSystemStorage/FileSystemStorage.d.ts +16 -0
- package/dist/adapters/FileSystemStorage/FileSystemStorage.d.ts.map +1 -0
- package/dist/adapters/FileSystemStorage/FileSystemStorage.js +38 -0
- package/dist/adapters/MemoryStorage/MemoryStorage.d.ts +15 -0
- package/dist/adapters/MemoryStorage/MemoryStorage.d.ts.map +1 -0
- package/dist/adapters/MemoryStorage/MemoryStorage.js +33 -0
- package/dist/cjs/UrlSigner.d.ts +46 -0
- package/dist/cjs/UrlSigner.d.ts.map +1 -0
- package/dist/cjs/UrlSigner.js +142 -0
- package/dist/cjs/adapters/BaseStorageAdapter.d.ts +31 -0
- package/dist/cjs/adapters/BaseStorageAdapter.d.ts.map +1 -0
- package/dist/cjs/adapters/BaseStorageAdapter.js +53 -0
- package/dist/cjs/adapters/FileSystemStorage/FileSystemStorage.d.ts +16 -0
- package/dist/cjs/adapters/FileSystemStorage/FileSystemStorage.d.ts.map +1 -0
- package/dist/cjs/adapters/FileSystemStorage/FileSystemStorage.js +72 -0
- package/dist/cjs/adapters/MemoryStorage/MemoryStorage.d.ts +15 -0
- package/dist/cjs/adapters/MemoryStorage/MemoryStorage.d.ts.map +1 -0
- package/dist/cjs/adapters/MemoryStorage/MemoryStorage.js +67 -0
- package/dist/cjs/createSavers.d.ts +15 -0
- package/dist/cjs/createSavers.d.ts.map +1 -0
- package/dist/cjs/createSavers.js +75 -0
- package/dist/cjs/fileToDataUri.d.ts +3 -0
- package/dist/cjs/fileToDataUri.d.ts.map +1 -0
- package/dist/cjs/fileToDataUri.js +32 -0
- package/dist/cjs/index.d.ts +40 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +50 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/prismaExtension.d.ts +29 -0
- package/dist/cjs/prismaExtension.d.ts.map +1 -0
- package/dist/cjs/prismaExtension.js +240 -0
- package/dist/createSavers.d.ts +15 -0
- package/dist/createSavers.d.ts.map +1 -0
- package/dist/createSavers.js +50 -0
- package/dist/fileToDataUri.d.ts +3 -0
- package/dist/fileToDataUri.d.ts.map +1 -0
- package/dist/fileToDataUri.js +8 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/prismaExtension.d.ts +29 -0
- package/dist/prismaExtension.d.ts.map +1 -0
- package/dist/prismaExtension.js +216 -0
- package/package.json +77 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Cedar
|
|
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/README.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# `@redwoodjs/storage`
|
|
2
|
+
|
|
3
|
+
This package houses
|
|
4
|
+
|
|
5
|
+
- Prisma extension for handling uploads. Currently
|
|
6
|
+
a) Query Extension: will save, delete, replace files on disk during CRUD
|
|
7
|
+
b) Result Extension: gives you functions like `.withSignedUri` on configured prisma results - which will take the paths, and convert it to a signed url
|
|
8
|
+
- Storage adapters e.g. FS and Memory to use with the prisma extension
|
|
9
|
+
- Processors - i.e. utility functions which will take [`Files`](https://developer.mozilla.org/en-US/docs/Web/API/File) and save them to storage
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
In `api/src/uploads.ts` - setup uploads - processors, storage and the prisma extension.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// api/src/lib/uploads.ts
|
|
17
|
+
nua
|
|
18
|
+
import { setupUploads, UploadsConfig } from '@cedarjs/storage'
|
|
19
|
+
import { FileSystemStorage } from '@cedarjs/storage/FileSystemStorage'
|
|
20
|
+
import { UrlSigner } from '@cedarjs/storage/UrlSigner'
|
|
21
|
+
|
|
22
|
+
const uploadsConfig: UploadsConfig = {
|
|
23
|
+
// 👇 prisma model
|
|
24
|
+
profile: {
|
|
25
|
+
// 👇 pass in fields that are going to be File uploads
|
|
26
|
+
// these should be configured as string in the Prisma.schema
|
|
27
|
+
fields: ['avatar', 'coverPhoto'],
|
|
28
|
+
},
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// 👇 exporting these allows you access elsewhere on the api side
|
|
32
|
+
export const fsStorage = new FileSystemStorage({
|
|
33
|
+
baseDir: './uploads',
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
// Optional
|
|
37
|
+
export const urlSigner = new UrlSigner({
|
|
38
|
+
secret: process.env.UPLOADS_SECRET,
|
|
39
|
+
endpoint: '/signedUrl',
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
const { saveFiles, storagePrismaExtension } = setupStorage({
|
|
43
|
+
uploadsConfig,
|
|
44
|
+
storageAdapter: fsStorage,
|
|
45
|
+
urlSigner,
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
export { saveFiles, storagePrismaExtension }
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Configuring db to use the prisma extension
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// api/src/lib/db.ts
|
|
55
|
+
|
|
56
|
+
import { PrismaClient } from '@prisma/client'
|
|
57
|
+
|
|
58
|
+
import { emitLogLevels, handlePrismaLogging } from '@cedarjs/api/logger'
|
|
59
|
+
|
|
60
|
+
import { logger } from './logger'
|
|
61
|
+
import { storagePrismaExtension } from './uploads'
|
|
62
|
+
|
|
63
|
+
// 👇 Notice here we create prisma client, and don't export it yet
|
|
64
|
+
export const prismaClient = new PrismaClient({
|
|
65
|
+
log: emitLogLevels(['info', 'warn', 'error']),
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
handlePrismaLogging({
|
|
69
|
+
db: prismaClient,
|
|
70
|
+
logger,
|
|
71
|
+
logLevels: ['info', 'warn', 'error'],
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
// 👇 Export db after adding uploads extension
|
|
75
|
+
export const db = prismaClient.$extends(storagePrismaExtension)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Using Prisma extension
|
|
79
|
+
|
|
80
|
+
### A) CRUD operations
|
|
81
|
+
|
|
82
|
+
No need to do anything here, but you have to use processors to supply Prisma with data in the correct format.
|
|
83
|
+
|
|
84
|
+
### B) Result extensions
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// api/src/services/profiles/profiles.ts
|
|
88
|
+
|
|
89
|
+
export const profile: QueryResolvers['profile'] = async ({ id }) => {
|
|
90
|
+
// 👇 await the result from your prisma query
|
|
91
|
+
const profile = await db.profile.findUnique({
|
|
92
|
+
where: { id },
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
// Convert the avatar and coverPhoto fields to signed URLs
|
|
96
|
+
// Note that you still need to add a api endpoint to handle these signed urls
|
|
97
|
+
return profile?.withSignedUrl()
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Using `saveFiles`
|
|
102
|
+
|
|
103
|
+
In your services, you can use the preconfigured "processors" - exported as `saveFiles` to convert Files to paths on storage, for Prisma to save into the database. The processors, and storage adapters determine where the file is saved.
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
// api/src/services/profiles/profiles.ts
|
|
107
|
+
|
|
108
|
+
export const updateProfile: MutationResolvers['updateProfile'] = async ({
|
|
109
|
+
id,
|
|
110
|
+
input,
|
|
111
|
+
}) => {
|
|
112
|
+
const processedInput = await saveFiles.forProfile(input)
|
|
113
|
+
|
|
114
|
+
// This becomes a string 👇
|
|
115
|
+
// The configuration on where it was saved is passed when we setup uploads in src/lib/uploads.ts
|
|
116
|
+
// processedInput.avatar = '/mySavePath/profile/avatar/generatedId.jpg'
|
|
117
|
+
|
|
118
|
+
return db.profile.update({
|
|
119
|
+
data: processedInput,
|
|
120
|
+
where: { id },
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
```
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export type SignedUrlSettings = {
|
|
2
|
+
endpoint: string;
|
|
3
|
+
secret: string;
|
|
4
|
+
};
|
|
5
|
+
export type SignatureValidationArgs = {
|
|
6
|
+
path: string;
|
|
7
|
+
s: string;
|
|
8
|
+
expiry?: number | string;
|
|
9
|
+
};
|
|
10
|
+
export declare class UrlSigner {
|
|
11
|
+
private secret;
|
|
12
|
+
private endpoint;
|
|
13
|
+
constructor({ secret, endpoint }: SignedUrlSettings);
|
|
14
|
+
generateSignature({ filePath, expiresInMs, }: {
|
|
15
|
+
filePath: string;
|
|
16
|
+
expiresInMs?: number;
|
|
17
|
+
}): {
|
|
18
|
+
expiry: number;
|
|
19
|
+
signature: string;
|
|
20
|
+
} | {
|
|
21
|
+
signature: string;
|
|
22
|
+
expiry: undefined;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* The signature and expires have to be extracted from the URL
|
|
26
|
+
*/
|
|
27
|
+
validateSignature({ s: signature, path: filePath, // In the URL we call it path
|
|
28
|
+
expiry, }: SignatureValidationArgs): string;
|
|
29
|
+
validateSignedUrl(fullPathWithQueryParametersOrUrl: string): string;
|
|
30
|
+
generateSignedUrl(filePath: string, expiresIn?: number): string;
|
|
31
|
+
}
|
|
32
|
+
export declare const getSignedDetailsFromUrl: (url: string) => {
|
|
33
|
+
expires: number | undefined;
|
|
34
|
+
file: string | null;
|
|
35
|
+
signature: string | null;
|
|
36
|
+
};
|
|
37
|
+
export declare const EXPIRES_IN: {
|
|
38
|
+
seconds: (s: number) => number;
|
|
39
|
+
minutes: (m: number) => number;
|
|
40
|
+
hours: (h: number) => number;
|
|
41
|
+
days: (d: number) => number;
|
|
42
|
+
weeks: (w: number) => number;
|
|
43
|
+
months: (m: number) => number;
|
|
44
|
+
years: (y: number) => number;
|
|
45
|
+
};
|
|
46
|
+
//# sourceMappingURL=UrlSigner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"UrlSigner.d.ts","sourceRoot":"","sources":["../src/UrlSigner.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAED,MAAM,MAAM,uBAAuB,GAAG;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,CAAC,EAAE,MAAM,CAAA;IACT,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CACzB,CAAA;AACD,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,QAAQ,CAAQ;gBAEZ,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,iBAAiB;IASnD,iBAAiB,CAAC,EAChB,QAAQ,EACR,WAAW,GACZ,EAAE;QACD,QAAQ,EAAE,MAAM,CAAA;QAChB,WAAW,CAAC,EAAE,MAAM,CAAA;KACrB;;;;;;;IA2BD;;OAEG;IACH,iBAAiB,CAAC,EAChB,CAAC,EAAE,SAAS,EACZ,IAAI,EAAE,QAAQ,EAAE,6BAA6B;IAC7C,MAAM,GACP,EAAE,uBAAuB;IAiC1B,iBAAiB,CAAC,gCAAgC,EAAE,MAAM;IAuB1D,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;CAiBvD;AAED,eAAO,MAAM,uBAAuB,QAAS,MAAM;;;;CAQlD,CAAA;AAED,eAAO,MAAM,UAAU;iBACR,MAAM;iBACN,MAAM;eACR,MAAM;cACP,MAAM;eACL,MAAM;gBACL,MAAM;eACP,MAAM;CAClB,CAAA"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { getConfig } from "@cedarjs/project-config";
|
|
3
|
+
class UrlSigner {
|
|
4
|
+
secret;
|
|
5
|
+
endpoint;
|
|
6
|
+
constructor({ secret, endpoint }) {
|
|
7
|
+
this.secret = secret;
|
|
8
|
+
this.endpoint = endpoint;
|
|
9
|
+
this.endpoint = endpoint.startsWith("http") ? endpoint : `${getConfig().web.apiUrl}${endpoint}`;
|
|
10
|
+
}
|
|
11
|
+
generateSignature({
|
|
12
|
+
filePath,
|
|
13
|
+
expiresInMs
|
|
14
|
+
}) {
|
|
15
|
+
if (!this.secret) {
|
|
16
|
+
throw new Error("Please configure the secret");
|
|
17
|
+
}
|
|
18
|
+
if (expiresInMs) {
|
|
19
|
+
const expiry = Date.now() + expiresInMs;
|
|
20
|
+
const signature = crypto.createHmac("sha256", this.secret).update(`${filePath}:${expiry}`).digest("hex");
|
|
21
|
+
return { expiry, signature };
|
|
22
|
+
} else {
|
|
23
|
+
const signature = crypto.createHmac("sha256", this.secret).update(filePath).digest("hex");
|
|
24
|
+
return {
|
|
25
|
+
signature,
|
|
26
|
+
expiry: void 0
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The signature and expires have to be extracted from the URL
|
|
32
|
+
*/
|
|
33
|
+
validateSignature({
|
|
34
|
+
s: signature,
|
|
35
|
+
path: filePath,
|
|
36
|
+
// In the URL we call it path
|
|
37
|
+
expiry
|
|
38
|
+
}) {
|
|
39
|
+
if (!this.secret) {
|
|
40
|
+
throw new Error("Please configure the secret");
|
|
41
|
+
}
|
|
42
|
+
if (expiry) {
|
|
43
|
+
if (Date.now() > +expiry) {
|
|
44
|
+
throw new Error("Signature has expired");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const decodedFilePath = decodeURIComponent(filePath);
|
|
48
|
+
const validSignature = expiry ? crypto.createHmac("sha256", this.secret).update(`${decodedFilePath}:${expiry}`).digest("hex") : crypto.createHmac("sha256", this.secret).update(`${decodedFilePath}`).digest("hex");
|
|
49
|
+
if (validSignature !== signature) {
|
|
50
|
+
throw new Error("Invalid signature");
|
|
51
|
+
}
|
|
52
|
+
return decodedFilePath;
|
|
53
|
+
}
|
|
54
|
+
validateSignedUrl(fullPathWithQueryParametersOrUrl) {
|
|
55
|
+
const url = new URL(
|
|
56
|
+
fullPathWithQueryParametersOrUrl,
|
|
57
|
+
// We don't care about the host, but just need to create a URL object
|
|
58
|
+
// to parse search params
|
|
59
|
+
fullPathWithQueryParametersOrUrl.startsWith("http") ? void 0 : "http://localhost"
|
|
60
|
+
);
|
|
61
|
+
const path = url.searchParams.get("path");
|
|
62
|
+
this.validateSignature({
|
|
63
|
+
// Note the signature is called 's' in the URL
|
|
64
|
+
s: url.searchParams.get("s"),
|
|
65
|
+
expiry: url.searchParams.get("expiry"),
|
|
66
|
+
path
|
|
67
|
+
});
|
|
68
|
+
return decodeURIComponent(path);
|
|
69
|
+
}
|
|
70
|
+
generateSignedUrl(filePath, expiresIn) {
|
|
71
|
+
const { signature, expiry } = this.generateSignature({
|
|
72
|
+
filePath,
|
|
73
|
+
expiresInMs: expiresIn
|
|
74
|
+
});
|
|
75
|
+
const params = new URLSearchParams();
|
|
76
|
+
params.set("s", signature);
|
|
77
|
+
if (expiry) {
|
|
78
|
+
params.set("expiry", expiry.toString());
|
|
79
|
+
}
|
|
80
|
+
params.set("path", filePath);
|
|
81
|
+
return `${this.endpoint}?${params.toString()}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const getSignedDetailsFromUrl = (url) => {
|
|
85
|
+
const urlObj = new URL(url);
|
|
86
|
+
const expires = urlObj.searchParams.get("expires");
|
|
87
|
+
return {
|
|
88
|
+
expires: expires ? parseInt(expires) : void 0,
|
|
89
|
+
file: urlObj.searchParams.get("file"),
|
|
90
|
+
signature: urlObj.searchParams.get("s")
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
const EXPIRES_IN = {
|
|
94
|
+
seconds: (s) => s * 1e3,
|
|
95
|
+
minutes: (m) => m * 60 * 1e3,
|
|
96
|
+
hours: (h) => h * 60 * 60 * 1e3,
|
|
97
|
+
days: (d) => d * 24 * 60 * 60 * 1e3,
|
|
98
|
+
weeks: (w) => w * 7 * 24 * 60 * 60 * 1e3,
|
|
99
|
+
months: (m) => m * 30 * 24 * 60 * 60 * 1e3,
|
|
100
|
+
years: (y) => y * 365 * 24 * 60 * 60 * 1e3
|
|
101
|
+
};
|
|
102
|
+
export {
|
|
103
|
+
EXPIRES_IN,
|
|
104
|
+
UrlSigner,
|
|
105
|
+
getSignedDetailsFromUrl
|
|
106
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The storage adapter will just save the file and return
|
|
3
|
+
* {
|
|
4
|
+
* fileId: string,
|
|
5
|
+
* location: string, // depending on storage it could be a path
|
|
6
|
+
* }
|
|
7
|
+
*/
|
|
8
|
+
import mime from 'mime-types';
|
|
9
|
+
export type AdapterResult = {
|
|
10
|
+
location: string;
|
|
11
|
+
};
|
|
12
|
+
export type SaveOptionsOverride = {
|
|
13
|
+
fileName?: string;
|
|
14
|
+
path?: string;
|
|
15
|
+
};
|
|
16
|
+
export type AdapterOptions = {
|
|
17
|
+
baseDir: string;
|
|
18
|
+
};
|
|
19
|
+
export declare abstract class BaseStorageAdapter {
|
|
20
|
+
adapterOpts: AdapterOptions;
|
|
21
|
+
constructor(adapterOpts: AdapterOptions);
|
|
22
|
+
getAdapterOptions(): AdapterOptions;
|
|
23
|
+
generateFileNameWithExtension(saveOpts: SaveOptionsOverride | undefined, file: File): string;
|
|
24
|
+
abstract save(file: File, saveOpts?: SaveOptionsOverride): Promise<AdapterResult>;
|
|
25
|
+
abstract remove(fileLocation: AdapterResult['location']): Promise<void>;
|
|
26
|
+
abstract read(fileLocation: AdapterResult['location']): Promise<{
|
|
27
|
+
contents: Buffer | string;
|
|
28
|
+
type: ReturnType<typeof mime.lookup>;
|
|
29
|
+
}>;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=BaseStorageAdapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseStorageAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/BaseStorageAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,IAAI,MAAM,YAAY,CAAA;AAG7B,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,CAAA;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,8BAAsB,kBAAkB;IACtC,WAAW,EAAE,cAAc,CAAA;gBACf,WAAW,EAAE,cAAc;IAIvC,iBAAiB;IAIjB,6BAA6B,CAC3B,QAAQ,EAAE,mBAAmB,GAAG,SAAS,EACzC,IAAI,EAAE,IAAI;IASZ,QAAQ,CAAC,IAAI,CACX,IAAI,EAAE,IAAI,EACV,QAAQ,CAAC,EAAE,mBAAmB,GAC7B,OAAO,CAAC,aAAa,CAAC;IACzB,QAAQ,CAAC,MAAM,CAAC,YAAY,EAAE,aAAa,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IACvE,QAAQ,CAAC,IAAI,CAAC,YAAY,EAAE,aAAa,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC;QAC9D,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAA;QACzB,IAAI,EAAE,UAAU,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,CAAA;KACrC,CAAC;CACH"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import mime from "mime-types";
|
|
2
|
+
import { ulid } from "ulid";
|
|
3
|
+
class BaseStorageAdapter {
|
|
4
|
+
adapterOpts;
|
|
5
|
+
constructor(adapterOpts) {
|
|
6
|
+
this.adapterOpts = adapterOpts;
|
|
7
|
+
}
|
|
8
|
+
getAdapterOptions() {
|
|
9
|
+
return this.adapterOpts;
|
|
10
|
+
}
|
|
11
|
+
generateFileNameWithExtension(saveOpts, file) {
|
|
12
|
+
const fileName = saveOpts?.fileName || ulid();
|
|
13
|
+
const extension = mime.extension(file.type) ? `.${mime.extension(file.type)}` : "";
|
|
14
|
+
return `${fileName}${extension}`;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
BaseStorageAdapter
|
|
19
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SaveOptionsOverride } from '../BaseStorageAdapter.js';
|
|
2
|
+
import { BaseStorageAdapter } from '../BaseStorageAdapter.js';
|
|
3
|
+
export declare class FileSystemStorage extends BaseStorageAdapter implements BaseStorageAdapter {
|
|
4
|
+
constructor(opts: {
|
|
5
|
+
baseDir: string;
|
|
6
|
+
});
|
|
7
|
+
save(file: File, saveOverride?: SaveOptionsOverride): Promise<{
|
|
8
|
+
location: string;
|
|
9
|
+
}>;
|
|
10
|
+
read(filePath: string): Promise<{
|
|
11
|
+
contents: Buffer;
|
|
12
|
+
type: string | false;
|
|
13
|
+
}>;
|
|
14
|
+
remove(filePath: string): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=FileSystemStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FileSystemStorage.d.ts","sourceRoot":"","sources":["../../../src/adapters/FileSystemStorage/FileSystemStorage.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAE7D,qBAAa,iBACX,SAAQ,kBACR,YAAW,kBAAkB;gBAEjB,IAAI,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE;IAQ/B,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,YAAY,CAAC,EAAE,mBAAmB;;;IAanD,IAAI,CAAC,QAAQ,EAAE,MAAM;;;;IAOrB,MAAM,CAAC,QAAQ,EAAE,MAAM;CAG9B"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import mime from "mime-types";
|
|
5
|
+
import { ensurePosixPath } from "@cedarjs/project-config";
|
|
6
|
+
import { BaseStorageAdapter } from "../BaseStorageAdapter.js";
|
|
7
|
+
class FileSystemStorage extends BaseStorageAdapter {
|
|
8
|
+
constructor(opts) {
|
|
9
|
+
super(opts);
|
|
10
|
+
if (!existsSync(opts.baseDir)) {
|
|
11
|
+
const posixBaseDir = ensurePosixPath(opts.baseDir);
|
|
12
|
+
console.log("Creating baseDir >", posixBaseDir);
|
|
13
|
+
mkdirSync(posixBaseDir, { recursive: true });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
async save(file, saveOverride) {
|
|
17
|
+
const fileName = this.generateFileNameWithExtension(saveOverride, file);
|
|
18
|
+
const location = path.join(
|
|
19
|
+
ensurePosixPath(saveOverride?.path || this.adapterOpts.baseDir),
|
|
20
|
+
fileName
|
|
21
|
+
);
|
|
22
|
+
const nodeBuffer = await file.arrayBuffer();
|
|
23
|
+
await fs.writeFile(location, Buffer.from(nodeBuffer));
|
|
24
|
+
return { location };
|
|
25
|
+
}
|
|
26
|
+
async read(filePath) {
|
|
27
|
+
return {
|
|
28
|
+
contents: await fs.readFile(filePath),
|
|
29
|
+
type: mime.lookup(filePath)
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
async remove(filePath) {
|
|
33
|
+
await fs.unlink(filePath);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export {
|
|
37
|
+
FileSystemStorage
|
|
38
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { BaseStorageAdapter } from '../BaseStorageAdapter.js';
|
|
2
|
+
import type { SaveOptionsOverride } from '../BaseStorageAdapter.js';
|
|
3
|
+
export declare class MemoryStorage extends BaseStorageAdapter implements BaseStorageAdapter {
|
|
4
|
+
store: Record<string, any>;
|
|
5
|
+
save(file: File, saveOpts?: SaveOptionsOverride): Promise<{
|
|
6
|
+
location: string;
|
|
7
|
+
}>;
|
|
8
|
+
remove(filePath: string): Promise<void>;
|
|
9
|
+
read(filePath: string): Promise<{
|
|
10
|
+
contents: any;
|
|
11
|
+
type: string | false;
|
|
12
|
+
}>;
|
|
13
|
+
clear(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=MemoryStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MemoryStorage.d.ts","sourceRoot":"","sources":["../../../src/adapters/MemoryStorage/MemoryStorage.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAC7D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAEnE,qBAAa,aACX,SAAQ,kBACR,YAAW,kBAAkB;IAE7B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAK;IAEzB,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,EAAE,mBAAmB;;;IAgB/C,MAAM,CAAC,QAAQ,EAAE,MAAM;IAIvB,IAAI,CAAC,QAAQ,EAAE,MAAM;;;;IAOrB,KAAK;CAGZ"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import mime from "mime-types";
|
|
3
|
+
import { BaseStorageAdapter } from "../BaseStorageAdapter.js";
|
|
4
|
+
class MemoryStorage extends BaseStorageAdapter {
|
|
5
|
+
store = {};
|
|
6
|
+
async save(file, saveOpts) {
|
|
7
|
+
const fileName = this.generateFileNameWithExtension(saveOpts, file);
|
|
8
|
+
const location = path.join(
|
|
9
|
+
saveOpts?.path || this.adapterOpts.baseDir,
|
|
10
|
+
fileName
|
|
11
|
+
);
|
|
12
|
+
const nodeBuffer = await file.arrayBuffer();
|
|
13
|
+
this.store[location] = Buffer.from(nodeBuffer);
|
|
14
|
+
return {
|
|
15
|
+
location
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
async remove(filePath) {
|
|
19
|
+
delete this.store[filePath];
|
|
20
|
+
}
|
|
21
|
+
async read(filePath) {
|
|
22
|
+
return {
|
|
23
|
+
contents: this.store[filePath],
|
|
24
|
+
type: mime.lookup(filePath)
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
async clear() {
|
|
28
|
+
this.store = {};
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export {
|
|
32
|
+
MemoryStorage
|
|
33
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export type SignedUrlSettings = {
|
|
2
|
+
endpoint: string;
|
|
3
|
+
secret: string;
|
|
4
|
+
};
|
|
5
|
+
export type SignatureValidationArgs = {
|
|
6
|
+
path: string;
|
|
7
|
+
s: string;
|
|
8
|
+
expiry?: number | string;
|
|
9
|
+
};
|
|
10
|
+
export declare class UrlSigner {
|
|
11
|
+
private secret;
|
|
12
|
+
private endpoint;
|
|
13
|
+
constructor({ secret, endpoint }: SignedUrlSettings);
|
|
14
|
+
generateSignature({ filePath, expiresInMs, }: {
|
|
15
|
+
filePath: string;
|
|
16
|
+
expiresInMs?: number;
|
|
17
|
+
}): {
|
|
18
|
+
expiry: number;
|
|
19
|
+
signature: string;
|
|
20
|
+
} | {
|
|
21
|
+
signature: string;
|
|
22
|
+
expiry: undefined;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* The signature and expires have to be extracted from the URL
|
|
26
|
+
*/
|
|
27
|
+
validateSignature({ s: signature, path: filePath, // In the URL we call it path
|
|
28
|
+
expiry, }: SignatureValidationArgs): string;
|
|
29
|
+
validateSignedUrl(fullPathWithQueryParametersOrUrl: string): string;
|
|
30
|
+
generateSignedUrl(filePath: string, expiresIn?: number): string;
|
|
31
|
+
}
|
|
32
|
+
export declare const getSignedDetailsFromUrl: (url: string) => {
|
|
33
|
+
expires: number | undefined;
|
|
34
|
+
file: string | null;
|
|
35
|
+
signature: string | null;
|
|
36
|
+
};
|
|
37
|
+
export declare const EXPIRES_IN: {
|
|
38
|
+
seconds: (s: number) => number;
|
|
39
|
+
minutes: (m: number) => number;
|
|
40
|
+
hours: (h: number) => number;
|
|
41
|
+
days: (d: number) => number;
|
|
42
|
+
weeks: (w: number) => number;
|
|
43
|
+
months: (m: number) => number;
|
|
44
|
+
years: (y: number) => number;
|
|
45
|
+
};
|
|
46
|
+
//# sourceMappingURL=UrlSigner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"UrlSigner.d.ts","sourceRoot":"","sources":["../../src/UrlSigner.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAED,MAAM,MAAM,uBAAuB,GAAG;IACpC,IAAI,EAAE,MAAM,CAAA;IACZ,CAAC,EAAE,MAAM,CAAA;IACT,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;CACzB,CAAA;AACD,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,QAAQ,CAAQ;gBAEZ,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,iBAAiB;IASnD,iBAAiB,CAAC,EAChB,QAAQ,EACR,WAAW,GACZ,EAAE;QACD,QAAQ,EAAE,MAAM,CAAA;QAChB,WAAW,CAAC,EAAE,MAAM,CAAA;KACrB;;;;;;;IA2BD;;OAEG;IACH,iBAAiB,CAAC,EAChB,CAAC,EAAE,SAAS,EACZ,IAAI,EAAE,QAAQ,EAAE,6BAA6B;IAC7C,MAAM,GACP,EAAE,uBAAuB;IAiC1B,iBAAiB,CAAC,gCAAgC,EAAE,MAAM;IAuB1D,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;CAiBvD;AAED,eAAO,MAAM,uBAAuB,QAAS,MAAM;;;;CAQlD,CAAA;AAED,eAAO,MAAM,UAAU;iBACR,MAAM;iBACN,MAAM;eACR,MAAM;cACP,MAAM;eACL,MAAM;gBACL,MAAM;eACP,MAAM;CAClB,CAAA"}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var UrlSigner_exports = {};
|
|
30
|
+
__export(UrlSigner_exports, {
|
|
31
|
+
EXPIRES_IN: () => EXPIRES_IN,
|
|
32
|
+
UrlSigner: () => UrlSigner,
|
|
33
|
+
getSignedDetailsFromUrl: () => getSignedDetailsFromUrl
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(UrlSigner_exports);
|
|
36
|
+
var import_node_crypto = __toESM(require("node:crypto"), 1);
|
|
37
|
+
var import_project_config = require("@cedarjs/project-config");
|
|
38
|
+
class UrlSigner {
|
|
39
|
+
secret;
|
|
40
|
+
endpoint;
|
|
41
|
+
constructor({ secret, endpoint }) {
|
|
42
|
+
this.secret = secret;
|
|
43
|
+
this.endpoint = endpoint;
|
|
44
|
+
this.endpoint = endpoint.startsWith("http") ? endpoint : `${(0, import_project_config.getConfig)().web.apiUrl}${endpoint}`;
|
|
45
|
+
}
|
|
46
|
+
generateSignature({
|
|
47
|
+
filePath,
|
|
48
|
+
expiresInMs
|
|
49
|
+
}) {
|
|
50
|
+
if (!this.secret) {
|
|
51
|
+
throw new Error("Please configure the secret");
|
|
52
|
+
}
|
|
53
|
+
if (expiresInMs) {
|
|
54
|
+
const expiry = Date.now() + expiresInMs;
|
|
55
|
+
const signature = import_node_crypto.default.createHmac("sha256", this.secret).update(`${filePath}:${expiry}`).digest("hex");
|
|
56
|
+
return { expiry, signature };
|
|
57
|
+
} else {
|
|
58
|
+
const signature = import_node_crypto.default.createHmac("sha256", this.secret).update(filePath).digest("hex");
|
|
59
|
+
return {
|
|
60
|
+
signature,
|
|
61
|
+
expiry: void 0
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The signature and expires have to be extracted from the URL
|
|
67
|
+
*/
|
|
68
|
+
validateSignature({
|
|
69
|
+
s: signature,
|
|
70
|
+
path: filePath,
|
|
71
|
+
// In the URL we call it path
|
|
72
|
+
expiry
|
|
73
|
+
}) {
|
|
74
|
+
if (!this.secret) {
|
|
75
|
+
throw new Error("Please configure the secret");
|
|
76
|
+
}
|
|
77
|
+
if (expiry) {
|
|
78
|
+
if (Date.now() > +expiry) {
|
|
79
|
+
throw new Error("Signature has expired");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const decodedFilePath = decodeURIComponent(filePath);
|
|
83
|
+
const validSignature = expiry ? import_node_crypto.default.createHmac("sha256", this.secret).update(`${decodedFilePath}:${expiry}`).digest("hex") : import_node_crypto.default.createHmac("sha256", this.secret).update(`${decodedFilePath}`).digest("hex");
|
|
84
|
+
if (validSignature !== signature) {
|
|
85
|
+
throw new Error("Invalid signature");
|
|
86
|
+
}
|
|
87
|
+
return decodedFilePath;
|
|
88
|
+
}
|
|
89
|
+
validateSignedUrl(fullPathWithQueryParametersOrUrl) {
|
|
90
|
+
const url = new URL(
|
|
91
|
+
fullPathWithQueryParametersOrUrl,
|
|
92
|
+
// We don't care about the host, but just need to create a URL object
|
|
93
|
+
// to parse search params
|
|
94
|
+
fullPathWithQueryParametersOrUrl.startsWith("http") ? void 0 : "http://localhost"
|
|
95
|
+
);
|
|
96
|
+
const path = url.searchParams.get("path");
|
|
97
|
+
this.validateSignature({
|
|
98
|
+
// Note the signature is called 's' in the URL
|
|
99
|
+
s: url.searchParams.get("s"),
|
|
100
|
+
expiry: url.searchParams.get("expiry"),
|
|
101
|
+
path
|
|
102
|
+
});
|
|
103
|
+
return decodeURIComponent(path);
|
|
104
|
+
}
|
|
105
|
+
generateSignedUrl(filePath, expiresIn) {
|
|
106
|
+
const { signature, expiry } = this.generateSignature({
|
|
107
|
+
filePath,
|
|
108
|
+
expiresInMs: expiresIn
|
|
109
|
+
});
|
|
110
|
+
const params = new URLSearchParams();
|
|
111
|
+
params.set("s", signature);
|
|
112
|
+
if (expiry) {
|
|
113
|
+
params.set("expiry", expiry.toString());
|
|
114
|
+
}
|
|
115
|
+
params.set("path", filePath);
|
|
116
|
+
return `${this.endpoint}?${params.toString()}`;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const getSignedDetailsFromUrl = (url) => {
|
|
120
|
+
const urlObj = new URL(url);
|
|
121
|
+
const expires = urlObj.searchParams.get("expires");
|
|
122
|
+
return {
|
|
123
|
+
expires: expires ? parseInt(expires) : void 0,
|
|
124
|
+
file: urlObj.searchParams.get("file"),
|
|
125
|
+
signature: urlObj.searchParams.get("s")
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
const EXPIRES_IN = {
|
|
129
|
+
seconds: (s) => s * 1e3,
|
|
130
|
+
minutes: (m) => m * 60 * 1e3,
|
|
131
|
+
hours: (h) => h * 60 * 60 * 1e3,
|
|
132
|
+
days: (d) => d * 24 * 60 * 60 * 1e3,
|
|
133
|
+
weeks: (w) => w * 7 * 24 * 60 * 60 * 1e3,
|
|
134
|
+
months: (m) => m * 30 * 24 * 60 * 60 * 1e3,
|
|
135
|
+
years: (y) => y * 365 * 24 * 60 * 60 * 1e3
|
|
136
|
+
};
|
|
137
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
138
|
+
0 && (module.exports = {
|
|
139
|
+
EXPIRES_IN,
|
|
140
|
+
UrlSigner,
|
|
141
|
+
getSignedDetailsFromUrl
|
|
142
|
+
});
|