glasswork 0.12.2 → 0.13.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/dist/auth/abilities.d.ts +41 -0
- package/dist/auth/abilities.d.ts.map +1 -0
- package/dist/auth/abilities.js +62 -0
- package/dist/auth/abilities.js.map +1 -0
- package/dist/auth/assert.d.ts +20 -0
- package/dist/auth/assert.d.ts.map +1 -0
- package/dist/auth/assert.js +28 -0
- package/dist/auth/assert.js.map +1 -0
- package/dist/auth/better-auth-provider.d.ts +56 -0
- package/dist/auth/better-auth-provider.d.ts.map +1 -0
- package/dist/auth/better-auth-provider.js +62 -0
- package/dist/auth/better-auth-provider.js.map +1 -0
- package/dist/auth/index.d.ts +6 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +5 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/middleware.d.ts +31 -0
- package/dist/auth/middleware.d.ts.map +1 -0
- package/dist/auth/middleware.js +92 -0
- package/dist/auth/middleware.js.map +1 -0
- package/dist/auth/types.d.ts +54 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/auth/types.js +2 -0
- package/dist/auth/types.js.map +1 -0
- package/dist/core/bootstrap.d.ts.map +1 -1
- package/dist/core/bootstrap.js +5 -2
- package/dist/core/bootstrap.js.map +1 -1
- package/dist/core/types.d.ts +8 -2
- package/dist/core/types.d.ts.map +1 -1
- package/dist/http/route-helpers.d.ts +43 -0
- package/dist/http/route-helpers.d.ts.map +1 -1
- package/dist/http/route-helpers.js +90 -40
- package/dist/http/route-helpers.js.map +1 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/jobs/define-job.d.ts +34 -2
- package/dist/jobs/define-job.d.ts.map +1 -1
- package/dist/jobs/define-job.js.map +1 -1
- package/dist/jobs/drivers/eventbridge-scheduler-driver.d.ts +75 -0
- package/dist/jobs/drivers/eventbridge-scheduler-driver.d.ts.map +1 -0
- package/dist/jobs/drivers/eventbridge-scheduler-driver.js +135 -0
- package/dist/jobs/drivers/eventbridge-scheduler-driver.js.map +1 -0
- package/dist/jobs/drivers/mock-driver.d.ts +45 -10
- package/dist/jobs/drivers/mock-driver.d.ts.map +1 -1
- package/dist/jobs/drivers/mock-driver.js +36 -17
- package/dist/jobs/drivers/mock-driver.js.map +1 -1
- package/dist/jobs/drivers/sqs-driver.d.ts +26 -19
- package/dist/jobs/drivers/sqs-driver.d.ts.map +1 -1
- package/dist/jobs/drivers/sqs-driver.js +54 -69
- package/dist/jobs/drivers/sqs-driver.js.map +1 -1
- package/dist/jobs/errors.d.ts +8 -4
- package/dist/jobs/errors.d.ts.map +1 -1
- package/dist/jobs/errors.js +13 -7
- package/dist/jobs/errors.js.map +1 -1
- package/dist/jobs/index.d.ts +4 -3
- package/dist/jobs/index.d.ts.map +1 -1
- package/dist/jobs/index.js +3 -2
- package/dist/jobs/index.js.map +1 -1
- package/dist/jobs/job-registry.d.ts +4 -4
- package/dist/jobs/job-registry.d.ts.map +1 -1
- package/dist/jobs/job-registry.js.map +1 -1
- package/dist/jobs/job-service.js +1 -1
- package/dist/jobs/job-service.js.map +1 -1
- package/dist/jobs/schedule-constants.d.ts +0 -4
- package/dist/jobs/schedule-constants.d.ts.map +1 -1
- package/dist/jobs/schedule-constants.js +0 -4
- package/dist/jobs/schedule-constants.js.map +1 -1
- package/dist/jobs/scheduler.d.ts +1 -1
- package/dist/jobs/scheduler.d.ts.map +1 -1
- package/dist/jobs/scheduler.js +46 -10
- package/dist/jobs/scheduler.js.map +1 -1
- package/dist/jobs/types.d.ts +59 -50
- package/dist/jobs/types.d.ts.map +1 -1
- package/dist/jobs/utils.d.ts +0 -9
- package/dist/jobs/utils.d.ts.map +1 -1
- package/dist/jobs/utils.js +3 -23
- package/dist/jobs/utils.js.map +1 -1
- package/dist/jobs/worker.d.ts +2 -3
- package/dist/jobs/worker.d.ts.map +1 -1
- package/dist/jobs/worker.js +183 -82
- package/dist/jobs/worker.js.map +1 -1
- package/dist/list-query/casl.d.ts +18 -19
- package/dist/list-query/casl.d.ts.map +1 -1
- package/dist/list-query/casl.js +40 -46
- package/dist/list-query/casl.js.map +1 -1
- package/dist/uploads/file-upload.d.ts +44 -0
- package/dist/uploads/file-upload.d.ts.map +1 -0
- package/dist/uploads/file-upload.js +145 -0
- package/dist/uploads/file-upload.js.map +1 -0
- package/dist/uploads/index.d.ts +6 -0
- package/dist/uploads/index.d.ts.map +1 -0
- package/dist/uploads/index.js +7 -0
- package/dist/uploads/index.js.map +1 -0
- package/dist/uploads/uploads.service.d.ts +98 -0
- package/dist/uploads/uploads.service.d.ts.map +1 -0
- package/dist/uploads/uploads.service.js +134 -0
- package/dist/uploads/uploads.service.js.map +1 -0
- package/dist/uploads/validators.d.ts +41 -0
- package/dist/uploads/validators.d.ts.map +1 -0
- package/dist/uploads/validators.js +94 -0
- package/dist/uploads/validators.js.map +1 -0
- package/package.json +34 -3
- package/dist/email/compiler/code-generator.d.ts +0 -11
- package/dist/email/compiler/code-generator.d.ts.map +0 -1
- package/dist/email/compiler/code-generator.js +0 -319
- package/dist/email/compiler/code-generator.js.map +0 -1
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { customAlphabet } from 'nanoid';
|
|
2
|
+
import { BadRequestException, ForbiddenException } from '../http/errors.js';
|
|
3
|
+
// ============================================================================
|
|
4
|
+
// Constants
|
|
5
|
+
// ============================================================================
|
|
6
|
+
const UPLOAD_RANDOM_ID_LENGTH = 16;
|
|
7
|
+
const MAX_PATH_LENGTH = 1024;
|
|
8
|
+
const NANOID_ALPHABET = '1234567890abcdef';
|
|
9
|
+
// ============================================================================
|
|
10
|
+
// Upload Configuration
|
|
11
|
+
// ============================================================================
|
|
12
|
+
/**
|
|
13
|
+
* Creates an upload configuration object for presigned URL generation.
|
|
14
|
+
* Validates IDs and generates a unique random folder to prevent overwrites.
|
|
15
|
+
*
|
|
16
|
+
* @param prefix - Upload folder prefix (e.g., 'avatars', 'documents')
|
|
17
|
+
* @param ids - Array of IDs to include in path (e.g., [userId] or [clientId, orderId])
|
|
18
|
+
* @param fileName - Sanitized filename (validate with sanitizedFileName schema first)
|
|
19
|
+
* @returns Configuration object with dir and fileName properties
|
|
20
|
+
* @throws BadRequestException if prefix is empty or IDs contain invalid characters
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* // In route handler:
|
|
25
|
+
* const config = createUploadConfig('avatars', [user.id], query.name);
|
|
26
|
+
* const result = await uploadsService.getSignedUploadUrl(config);
|
|
27
|
+
* // Result path: /uploads/avatars/{userId}/{randomId}/{filename}
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export function createUploadConfig(prefix, ids, fileName) {
|
|
31
|
+
if (!prefix || prefix.trim() === '') {
|
|
32
|
+
throw new BadRequestException('Prefix cannot be empty');
|
|
33
|
+
}
|
|
34
|
+
for (const id of ids) {
|
|
35
|
+
if (!id || typeof id !== 'string') {
|
|
36
|
+
throw new BadRequestException(`Invalid ID: ${id}`);
|
|
37
|
+
}
|
|
38
|
+
if (id.includes('/') || id.includes('\\') || id.includes('..')) {
|
|
39
|
+
throw new BadRequestException(`Invalid character in ID: ${id}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/*
|
|
43
|
+
* Handle empty IDs array gracefully to avoid double slashes.
|
|
44
|
+
* If ids are present, join them with '/', otherwise use empty string.
|
|
45
|
+
*/
|
|
46
|
+
const idPath = ids.length > 0 ? `${ids.join('/')}/` : '';
|
|
47
|
+
const randomId = customAlphabet(NANOID_ALPHABET, UPLOAD_RANDOM_ID_LENGTH)();
|
|
48
|
+
const dir = `uploads/${prefix}/${idPath}${randomId}`;
|
|
49
|
+
return { dir, fileName };
|
|
50
|
+
}
|
|
51
|
+
// ============================================================================
|
|
52
|
+
// Path Ownership Validation
|
|
53
|
+
// ============================================================================
|
|
54
|
+
/**
|
|
55
|
+
* Validate IDs don't contain path traversal characters.
|
|
56
|
+
*/
|
|
57
|
+
function validateIdsForPath(ids, errorMessage) {
|
|
58
|
+
for (const id of ids) {
|
|
59
|
+
if (!id || typeof id !== 'string') {
|
|
60
|
+
throw new ForbiddenException(errorMessage);
|
|
61
|
+
}
|
|
62
|
+
if (id.includes('/') || id.includes('\\') || id.includes('..')) {
|
|
63
|
+
throw new ForbiddenException(errorMessage);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Check if path contains control characters (security measure).
|
|
69
|
+
*/
|
|
70
|
+
function hasControlCharacters(path) {
|
|
71
|
+
for (let i = 0; i < path.length; i++) {
|
|
72
|
+
const code = path.charCodeAt(i);
|
|
73
|
+
if ((code >= 0x00 && code <= 0x1f) || code === 0x7f) {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Decode and normalize path, rejecting traversal attempts.
|
|
81
|
+
*/
|
|
82
|
+
function decodeAndNormalizePath(path, errorMessage) {
|
|
83
|
+
let decodedPath;
|
|
84
|
+
try {
|
|
85
|
+
decodedPath = decodeURIComponent(path);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
throw new ForbiddenException(errorMessage);
|
|
89
|
+
}
|
|
90
|
+
if (decodedPath.includes('..') || decodedPath.includes('./') || decodedPath.includes('.\\')) {
|
|
91
|
+
throw new ForbiddenException(errorMessage);
|
|
92
|
+
}
|
|
93
|
+
if (decodedPath.includes('\\')) {
|
|
94
|
+
throw new ForbiddenException(errorMessage);
|
|
95
|
+
}
|
|
96
|
+
const normalizedPath = decodedPath.replace(/\/+/g, '/');
|
|
97
|
+
if (normalizedPath !== decodedPath) {
|
|
98
|
+
throw new ForbiddenException(errorMessage);
|
|
99
|
+
}
|
|
100
|
+
return normalizedPath;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Validate relative path has a valid filename at the end.
|
|
104
|
+
*/
|
|
105
|
+
function validateRelativePath(relativePath, errorMessage) {
|
|
106
|
+
if (relativePath === '' || relativePath.endsWith('/')) {
|
|
107
|
+
throw new ForbiddenException(errorMessage);
|
|
108
|
+
}
|
|
109
|
+
const lastSlashIndex = relativePath.lastIndexOf('/');
|
|
110
|
+
const filename = lastSlashIndex >= 0 ? relativePath.slice(lastSlashIndex + 1) : relativePath;
|
|
111
|
+
if (!filename || filename.trim() === '') {
|
|
112
|
+
throw new ForbiddenException(errorMessage);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Asserts that a file path belongs to the specified prefix and IDs.
|
|
117
|
+
* Use this to validate delete operations - ensures users can only delete their own files.
|
|
118
|
+
*
|
|
119
|
+
* @param path - The file path to validate (e.g., from query.name)
|
|
120
|
+
* @param prefix - The expected upload prefix (e.g., 'avatars', 'documents')
|
|
121
|
+
* @param ids - The expected IDs in the path
|
|
122
|
+
* @param errorMessage - Custom error message (default: 'Invalid file path')
|
|
123
|
+
* @throws ForbiddenException if path doesn't match expected structure
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```typescript
|
|
127
|
+
* // In delete handler:
|
|
128
|
+
* assertUploadPathOwnership(query.path, 'avatars', [user.id]);
|
|
129
|
+
* await uploadsService.deleteFile(query.path);
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
export function assertUploadPathOwnership(path, prefix, ids, errorMessage = 'Invalid file path') {
|
|
133
|
+
validateIdsForPath(ids, errorMessage);
|
|
134
|
+
if (path.length > MAX_PATH_LENGTH || hasControlCharacters(path)) {
|
|
135
|
+
throw new ForbiddenException(errorMessage);
|
|
136
|
+
}
|
|
137
|
+
const normalizedPath = decodeAndNormalizePath(path, errorMessage);
|
|
138
|
+
const idPath = ids.length > 0 ? `${ids.join('/')}/` : '';
|
|
139
|
+
const expectedPrefix = `/uploads/${prefix}/${idPath}`;
|
|
140
|
+
if (!normalizedPath.startsWith(expectedPrefix)) {
|
|
141
|
+
throw new ForbiddenException(errorMessage);
|
|
142
|
+
}
|
|
143
|
+
validateRelativePath(normalizedPath.slice(expectedPrefix.length), errorMessage);
|
|
144
|
+
}
|
|
145
|
+
//# sourceMappingURL=file-upload.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-upload.js","sourceRoot":"","sources":["../../src/uploads/file-upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE5E,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,MAAM,uBAAuB,GAAG,EAAE,CAAC;AACnC,MAAM,eAAe,GAAG,IAAI,CAAC;AAC7B,MAAM,eAAe,GAAG,kBAAkB,CAAC;AAa3C,+EAA+E;AAC/E,uBAAuB;AACvB,+EAA+E;AAE/E;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAAc,EACd,GAAsB,EACtB,QAAgB;IAEhB,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACpC,MAAM,IAAI,mBAAmB,CAAC,wBAAwB,CAAC,CAAC;IAC1D,CAAC;IACD,KAAK,MAAM,EAAE,IAAI,GAAG,EAAE,CAAC;QACrB,IAAI,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC;YAClC,MAAM,IAAI,mBAAmB,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC;QACrD,CAAC;QACD,IAAI,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAC/D,MAAM,IAAI,mBAAmB,CAAC,4BAA4B,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AAY,CAAC,KAAK,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;IAC7F,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACxC,MAAM,IAAI,kBAAkB,CAAC,YAAY,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,yBAAyB,CACvC,IAAY,EACZ,MAAc,EACd,GAAsB,EACtB,YAAY,GAAG,mBAAmB;IAElC,kBAAkB,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;IACtC,IAAI,IAAI,CAAC,MAAM,GAAG,eAAe,IAAI,oBAAoB,CAAC,IAAI,CAAC,EAAE,CAAC;QAChE,MAAM,IAAI,kBAAkB,CAAC,YAAY,CAAC,CAAC;IAC7C,CAAC;IACD,MAAM,cAAc,GAAG,sBAAsB,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IAClE,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IACzD,MAAM,cAAc,GAAG,YAAY,MAAM,IAAI,MAAM,EAAE,CAAC;IACtD,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;QAC/C,MAAM,IAAI,kBAAkB,CAAC,YAAY,CAAC,CAAC;IAC7C,CAAC;IACD,oBAAoB,CAAC,cAAc,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC,CAAC;AAClF,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { UploadPathConfig } from './file-upload.js';
|
|
2
|
+
export { assertUploadPathOwnership, createUploadConfig } from './file-upload.js';
|
|
3
|
+
export type { SignedDownloadUrlResponse, SignedUrlResponse, StreamFileResult, UploadFileConfig, UploadsServiceConfig, } from './uploads.service.js';
|
|
4
|
+
export { UploadsService } from './uploads.service.js';
|
|
5
|
+
export { fileNameWithExtension, sanitizedFileName } from './validators.js';
|
|
6
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/uploads/index.ts"],"names":[],"mappings":"AAEA,YAAY,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACjF,YAAY,EACV,yBAAyB,EACzB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Service
|
|
2
|
+
// Utilities
|
|
3
|
+
export { assertUploadPathOwnership, createUploadConfig } from './file-upload.js';
|
|
4
|
+
export { UploadsService } from './uploads.service.js';
|
|
5
|
+
// Validators
|
|
6
|
+
export { fileNameWithExtension, sanitizedFileName } from './validators.js';
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/uploads/index.ts"],"names":[],"mappings":"AAAA,UAAU;AAGV,YAAY;AACZ,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAQjF,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,aAAa;AACb,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { Readable } from 'node:stream';
|
|
2
|
+
export interface UploadFileConfig {
|
|
3
|
+
/** Directory path for the file (e.g., 'uploads/avatars/user123/abc123') */
|
|
4
|
+
readonly dir: string;
|
|
5
|
+
/** Sanitized file name (e.g., 'photo.jpg') */
|
|
6
|
+
readonly fileName: string;
|
|
7
|
+
}
|
|
8
|
+
export interface SignedUrlResponse {
|
|
9
|
+
/** Presigned URL for uploading the file */
|
|
10
|
+
readonly uploadUrl: string;
|
|
11
|
+
/** Relative path where the file will be stored (e.g., '/uploads/avatars/...') */
|
|
12
|
+
readonly path: string;
|
|
13
|
+
/** Expiration timestamp of the presigned URL */
|
|
14
|
+
readonly expiresAt: Date;
|
|
15
|
+
}
|
|
16
|
+
export interface SignedDownloadUrlResponse {
|
|
17
|
+
/** Presigned URL for downloading the file */
|
|
18
|
+
readonly downloadUrl: string;
|
|
19
|
+
/** Expiration timestamp of the presigned URL */
|
|
20
|
+
readonly expiresAt: Date;
|
|
21
|
+
}
|
|
22
|
+
export interface StreamFileResult {
|
|
23
|
+
/** Readable stream of the file contents */
|
|
24
|
+
readonly body: Readable;
|
|
25
|
+
/** MIME type of the file */
|
|
26
|
+
readonly contentType: string | undefined;
|
|
27
|
+
/** Size of the file in bytes */
|
|
28
|
+
readonly contentLength: number | undefined;
|
|
29
|
+
}
|
|
30
|
+
export interface UploadsServiceConfig {
|
|
31
|
+
/** AWS region (e.g., 'eu-west-1') */
|
|
32
|
+
readonly region: string;
|
|
33
|
+
/** S3 bucket name */
|
|
34
|
+
readonly bucketName: string;
|
|
35
|
+
/** Presigned URL expiration in seconds (default: 3600) */
|
|
36
|
+
readonly urlExpiration?: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Service for S3 file operations including presigned URL generation and streaming.
|
|
40
|
+
* Framework-agnostic - can be used anywhere TypeScript runs.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* const uploadsService = new UploadsService({
|
|
45
|
+
* region: 'eu-west-1',
|
|
46
|
+
* bucketName: 'my-files-bucket',
|
|
47
|
+
* urlExpiration: 3600,
|
|
48
|
+
* });
|
|
49
|
+
*
|
|
50
|
+
* // Generate presigned upload URL
|
|
51
|
+
* const { uploadUrl, path } = await uploadsService.getSignedUploadUrl({
|
|
52
|
+
* dir: 'uploads/avatars/user123',
|
|
53
|
+
* fileName: 'photo.jpg',
|
|
54
|
+
* });
|
|
55
|
+
*
|
|
56
|
+
* // Stream file for private access
|
|
57
|
+
* const { body, contentType } = await uploadsService.streamFile('/uploads/docs/file.pdf');
|
|
58
|
+
*
|
|
59
|
+
* // Generate presigned download URL for private files
|
|
60
|
+
* const { downloadUrl } = await uploadsService.getSignedDownloadUrl('/uploads/docs/private.pdf');
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export declare class UploadsService {
|
|
64
|
+
private readonly client;
|
|
65
|
+
private readonly bucketName;
|
|
66
|
+
private readonly urlExpiration;
|
|
67
|
+
constructor(config: UploadsServiceConfig);
|
|
68
|
+
/**
|
|
69
|
+
* Generate a presigned URL for uploading a file to S3.
|
|
70
|
+
* The URL allows direct upload from the client without going through Lambda.
|
|
71
|
+
*/
|
|
72
|
+
getSignedUploadUrl(fileConfig: UploadFileConfig): Promise<SignedUrlResponse>;
|
|
73
|
+
/**
|
|
74
|
+
* Stream a file from S3 for private file access.
|
|
75
|
+
* Returns a readable stream that can be piped to the HTTP response.
|
|
76
|
+
*
|
|
77
|
+
* **Note**: Lambda has a 6MB response payload limit for synchronous invocations.
|
|
78
|
+
* For larger files, consider using presigned GET URLs with short expiration.
|
|
79
|
+
*/
|
|
80
|
+
streamFile(filePath: string): Promise<StreamFileResult>;
|
|
81
|
+
/**
|
|
82
|
+
* Generate a presigned URL for downloading a file from S3.
|
|
83
|
+
* Use this instead of streaming for files that may exceed Lambda's 6MB response limit.
|
|
84
|
+
*
|
|
85
|
+
* @param filePath - Relative path to the file (e.g., '/uploads/docs/file.pdf')
|
|
86
|
+
* @param expiresIn - Optional expiration in seconds (default: service urlExpiration)
|
|
87
|
+
*/
|
|
88
|
+
getSignedDownloadUrl(filePath: string, expiresIn?: number): Promise<SignedDownloadUrlResponse>;
|
|
89
|
+
/**
|
|
90
|
+
* Delete a file from S3 by path.
|
|
91
|
+
*/
|
|
92
|
+
deleteFile(filePath: string): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Normalize file path to S3 key format (strip leading slashes).
|
|
95
|
+
*/
|
|
96
|
+
private normalizeKey;
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=uploads.service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uploads.service.d.ts","sourceRoot":"","sources":["../../src/uploads/uploads.service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAe5C,MAAM,WAAW,gBAAgB;IAC/B,2EAA2E;IAC3E,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,8CAA8C;IAC9C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,iBAAiB;IAChC,2CAA2C;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,iFAAiF;IACjF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,gDAAgD;IAChD,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,yBAAyB;IACxC,6CAA6C;IAC7C,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,gDAAgD;IAChD,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC/B,2CAA2C;IAC3C,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,4BAA4B;IAC5B,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,gCAAgC;IAChC,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5C;AAED,MAAM,WAAW,oBAAoB;IACnC,qCAAqC;IACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,qBAAqB;IACrB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,0DAA0D;IAC1D,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CACjC;AAaD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAW;IAClC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;gBAE3B,MAAM,EAAE,oBAAoB;IAMxC;;;OAGG;IACG,kBAAkB,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAgBlF;;;;;;OAMG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAsB7D;;;;;;OAMG;IACG,oBAAoB,CACxB,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,yBAAyB,CAAC;IAgBrC;;OAEG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASjD;;OAEG;IACH,OAAO,CAAC,YAAY;CAGrB"}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { DeleteObjectCommand, GetObjectCommand, PutObjectCommand, S3Client, S3ServiceException, } from '@aws-sdk/client-s3';
|
|
2
|
+
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
|
3
|
+
import { NotFoundException } from '../http/errors.js';
|
|
4
|
+
// ============================================================================
|
|
5
|
+
// Constants
|
|
6
|
+
// ============================================================================
|
|
7
|
+
const DEFAULT_URL_EXPIRATION = 3600; // 1 hour
|
|
8
|
+
const MILLISECONDS_PER_SECOND = 1000;
|
|
9
|
+
// ============================================================================
|
|
10
|
+
// Service
|
|
11
|
+
// ============================================================================
|
|
12
|
+
/**
|
|
13
|
+
* Service for S3 file operations including presigned URL generation and streaming.
|
|
14
|
+
* Framework-agnostic - can be used anywhere TypeScript runs.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* const uploadsService = new UploadsService({
|
|
19
|
+
* region: 'eu-west-1',
|
|
20
|
+
* bucketName: 'my-files-bucket',
|
|
21
|
+
* urlExpiration: 3600,
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // Generate presigned upload URL
|
|
25
|
+
* const { uploadUrl, path } = await uploadsService.getSignedUploadUrl({
|
|
26
|
+
* dir: 'uploads/avatars/user123',
|
|
27
|
+
* fileName: 'photo.jpg',
|
|
28
|
+
* });
|
|
29
|
+
*
|
|
30
|
+
* // Stream file for private access
|
|
31
|
+
* const { body, contentType } = await uploadsService.streamFile('/uploads/docs/file.pdf');
|
|
32
|
+
*
|
|
33
|
+
* // Generate presigned download URL for private files
|
|
34
|
+
* const { downloadUrl } = await uploadsService.getSignedDownloadUrl('/uploads/docs/private.pdf');
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export class UploadsService {
|
|
38
|
+
client;
|
|
39
|
+
bucketName;
|
|
40
|
+
urlExpiration;
|
|
41
|
+
constructor(config) {
|
|
42
|
+
this.client = new S3Client({ region: config.region });
|
|
43
|
+
this.bucketName = config.bucketName;
|
|
44
|
+
this.urlExpiration = config.urlExpiration ?? DEFAULT_URL_EXPIRATION;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Generate a presigned URL for uploading a file to S3.
|
|
48
|
+
* The URL allows direct upload from the client without going through Lambda.
|
|
49
|
+
*/
|
|
50
|
+
async getSignedUploadUrl(fileConfig) {
|
|
51
|
+
const filePath = `${fileConfig.dir}/${fileConfig.fileName}`;
|
|
52
|
+
const command = new PutObjectCommand({
|
|
53
|
+
Bucket: this.bucketName,
|
|
54
|
+
Key: filePath,
|
|
55
|
+
});
|
|
56
|
+
const url = await getSignedUrl(this.client, command, {
|
|
57
|
+
expiresIn: this.urlExpiration,
|
|
58
|
+
});
|
|
59
|
+
return {
|
|
60
|
+
uploadUrl: url,
|
|
61
|
+
path: `/${filePath}`,
|
|
62
|
+
expiresAt: new Date(Date.now() + this.urlExpiration * MILLISECONDS_PER_SECOND),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Stream a file from S3 for private file access.
|
|
67
|
+
* Returns a readable stream that can be piped to the HTTP response.
|
|
68
|
+
*
|
|
69
|
+
* **Note**: Lambda has a 6MB response payload limit for synchronous invocations.
|
|
70
|
+
* For larger files, consider using presigned GET URLs with short expiration.
|
|
71
|
+
*/
|
|
72
|
+
async streamFile(filePath) {
|
|
73
|
+
try {
|
|
74
|
+
const key = this.normalizeKey(filePath);
|
|
75
|
+
const command = new GetObjectCommand({
|
|
76
|
+
Bucket: this.bucketName,
|
|
77
|
+
Key: key,
|
|
78
|
+
});
|
|
79
|
+
const response = await this.client.send(command);
|
|
80
|
+
const body = response.Body;
|
|
81
|
+
return {
|
|
82
|
+
body,
|
|
83
|
+
contentType: response.ContentType,
|
|
84
|
+
contentLength: response.ContentLength,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (error instanceof S3ServiceException && error.name === 'NoSuchKey') {
|
|
89
|
+
throw new NotFoundException('File not found');
|
|
90
|
+
}
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Generate a presigned URL for downloading a file from S3.
|
|
96
|
+
* Use this instead of streaming for files that may exceed Lambda's 6MB response limit.
|
|
97
|
+
*
|
|
98
|
+
* @param filePath - Relative path to the file (e.g., '/uploads/docs/file.pdf')
|
|
99
|
+
* @param expiresIn - Optional expiration in seconds (default: service urlExpiration)
|
|
100
|
+
*/
|
|
101
|
+
async getSignedDownloadUrl(filePath, expiresIn) {
|
|
102
|
+
const key = this.normalizeKey(filePath);
|
|
103
|
+
const expiration = expiresIn ?? this.urlExpiration;
|
|
104
|
+
const command = new GetObjectCommand({
|
|
105
|
+
Bucket: this.bucketName,
|
|
106
|
+
Key: key,
|
|
107
|
+
});
|
|
108
|
+
const url = await getSignedUrl(this.client, command, {
|
|
109
|
+
expiresIn: expiration,
|
|
110
|
+
});
|
|
111
|
+
return {
|
|
112
|
+
downloadUrl: url,
|
|
113
|
+
expiresAt: new Date(Date.now() + expiration * MILLISECONDS_PER_SECOND),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Delete a file from S3 by path.
|
|
118
|
+
*/
|
|
119
|
+
async deleteFile(filePath) {
|
|
120
|
+
const key = this.normalizeKey(filePath);
|
|
121
|
+
const command = new DeleteObjectCommand({
|
|
122
|
+
Bucket: this.bucketName,
|
|
123
|
+
Key: key,
|
|
124
|
+
});
|
|
125
|
+
await this.client.send(command);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Normalize file path to S3 key format (strip leading slashes).
|
|
129
|
+
*/
|
|
130
|
+
normalizeKey(filePath) {
|
|
131
|
+
return filePath.replace(/^\/+/, '').replace(/\/+/g, '/');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=uploads.service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uploads.service.js","sourceRoot":"","sources":["../../src/uploads/uploads.service.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,kBAAkB,GACnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AA+CtD,+EAA+E;AAC/E,YAAY;A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AAK,CAAC,UAAU,CAAC,QAAgB;QAC/B,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QACxC,MAAM,OAAO,GAAG,IAAI,mBAAmB,CAAC;YACtC,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,GAAG,EAAE,GAAG;SACT,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IAED;;OAEG;IACK,YAAY,CAAC,QAAgB;QACnC,OAAO,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC3D,CAAC;CACF"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File name validation with extension check AND sanitization.
|
|
3
|
+
* Validates that the file has an allowed extension, then transforms it to a URL-safe slug.
|
|
4
|
+
*
|
|
5
|
+
* @param allowedExtensions - Extensions to allow (e.g., ['.jpg', '.png', '.pdf'])
|
|
6
|
+
* @param errorMessage - Custom error message for invalid file type
|
|
7
|
+
* @returns Valibot schema that validates and sanitizes the filename
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* // Define allowed extensions per use case
|
|
12
|
+
* const ALLOWED_IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp'] as const;
|
|
13
|
+
* const ALLOWED_DOCUMENT_EXTENSIONS = ['.pdf', '.docx'] as const;
|
|
14
|
+
*
|
|
15
|
+
* // Use in schema
|
|
16
|
+
* const GetUploadUrlQuery = v.object({
|
|
17
|
+
* name: sanitizedFileName(ALLOWED_IMAGE_EXTENSIONS),
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* // Input: "My Photo (1).PNG" → Output: "my-photo-1.png"
|
|
21
|
+
* // Input: "test.txt" → ValidationError (extension not allowed)
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare const sanitizedFileName: (allowedExtensions: readonly string[], errorMessage?: string) => import("valibot").SchemaWithPipe<readonly [import("valibot").StringSchema<undefined>, import("valibot").CheckAction<string, string>, import("valibot").TransformAction<string, string>]>;
|
|
25
|
+
/**
|
|
26
|
+
* File name validation with extension check (no transformation).
|
|
27
|
+
* Use when you want to validate the extension but keep the original filename.
|
|
28
|
+
*
|
|
29
|
+
* @param allowedExtensions - Extensions to allow (e.g., ['.jpg', '.png'])
|
|
30
|
+
* @param errorMessage - Custom error message for invalid file type
|
|
31
|
+
* @returns Valibot schema that validates the filename extension
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```typescript
|
|
35
|
+
* const schema = v.object({
|
|
36
|
+
* name: fileNameWithExtension(['.pdf', '.docx']),
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare const fileNameWithExtension: (allowedExtensions: readonly string[], errorMessage?: string) => import("valibot").SchemaWithPipe<readonly [import("valibot").StringSchema<undefined>, import("valibot").CheckAction<string, string>]>;
|
|
41
|
+
//# sourceMappingURL=validators.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.d.ts","sourceRoot":"","sources":["../../src/uploads/validators.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,iBAAiB,GAAI,mBAAmB,SAAS,MAAM,EAAE,EAAE,eAAe,MAAM,6LAwC1F,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,qBAAqB,GAChC,mBAAmB,SAAS,MAAM,EAAE,EACpC,eAAe,MAAM,0IAoBpB,CAAC"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { check, pipe, string, transform } from 'valibot';
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// File Name Validators
|
|
4
|
+
// ============================================================================
|
|
5
|
+
/**
|
|
6
|
+
* Slugify a filename base for URL-safe paths.
|
|
7
|
+
* Converts to lowercase, removes diacritics, replaces non-alphanumeric with hyphens, trims hyphens.
|
|
8
|
+
*/
|
|
9
|
+
function slugify(baseName) {
|
|
10
|
+
return baseName
|
|
11
|
+
.normalize('NFD')
|
|
12
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
13
|
+
.toLowerCase()
|
|
14
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
15
|
+
.replace(/^-+|-+$/g, '');
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* File name validation with extension check AND sanitization.
|
|
19
|
+
* Validates that the file has an allowed extension, then transforms it to a URL-safe slug.
|
|
20
|
+
*
|
|
21
|
+
* @param allowedExtensions - Extensions to allow (e.g., ['.jpg', '.png', '.pdf'])
|
|
22
|
+
* @param errorMessage - Custom error message for invalid file type
|
|
23
|
+
* @returns Valibot schema that validates and sanitizes the filename
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* // Define allowed extensions per use case
|
|
28
|
+
* const ALLOWED_IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp'] as const;
|
|
29
|
+
* const ALLOWED_DOCUMENT_EXTENSIONS = ['.pdf', '.docx'] as const;
|
|
30
|
+
*
|
|
31
|
+
* // Use in schema
|
|
32
|
+
* const GetUploadUrlQuery = v.object({
|
|
33
|
+
* name: sanitizedFileName(ALLOWED_IMAGE_EXTENSIONS),
|
|
34
|
+
* });
|
|
35
|
+
*
|
|
36
|
+
* // Input: "My Photo (1).PNG" → Output: "my-photo-1.png"
|
|
37
|
+
* // Input: "test.txt" → ValidationError (extension not allowed)
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export const sanitizedFileName = (allowedExtensions, errorMessage) => pipe(string(), check((input) => {
|
|
41
|
+
const lastDotIndex = input.lastIndexOf('.');
|
|
42
|
+
if (lastDotIndex === -1 || lastDotIndex === input.length - 1) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
// Check for double extensions like .tar.gz
|
|
46
|
+
const parts = input.toLowerCase().split('.');
|
|
47
|
+
const ext1 = `.${parts[parts.length - 1]}`;
|
|
48
|
+
const ext2 = parts.length > 2 ? `.${parts[parts.length - 2]}.${parts[parts.length - 1]}` : null;
|
|
49
|
+
return !!(allowedExtensions.includes(ext1) || (ext2 && allowedExtensions.includes(ext2)));
|
|
50
|
+
}, errorMessage ?? `Invalid file type. Allowed: ${allowedExtensions.join(', ')}`), transform((input) => {
|
|
51
|
+
const parts = input.split('.');
|
|
52
|
+
// Determine which extension to use based on allowed list
|
|
53
|
+
let extension = parts[parts.length - 1].toLowerCase();
|
|
54
|
+
let baseName = parts.slice(0, parts.length - 1).join('.');
|
|
55
|
+
if (parts.length > 2) {
|
|
56
|
+
const doubleExt = `.${parts[parts.length - 2]}.${parts[parts.length - 1]}`.toLowerCase();
|
|
57
|
+
if (allowedExtensions.includes(doubleExt)) {
|
|
58
|
+
extension = parts
|
|
59
|
+
.slice(parts.length - 2)
|
|
60
|
+
.join('.')
|
|
61
|
+
.toLowerCase();
|
|
62
|
+
baseName = parts.slice(0, parts.length - 2).join('.');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const slugifiedName = slugify(baseName);
|
|
66
|
+
return slugifiedName ? `${slugifiedName}.${extension}` : `file.${extension}`;
|
|
67
|
+
}));
|
|
68
|
+
/**
|
|
69
|
+
* File name validation with extension check (no transformation).
|
|
70
|
+
* Use when you want to validate the extension but keep the original filename.
|
|
71
|
+
*
|
|
72
|
+
* @param allowedExtensions - Extensions to allow (e.g., ['.jpg', '.png'])
|
|
73
|
+
* @param errorMessage - Custom error message for invalid file type
|
|
74
|
+
* @returns Valibot schema that validates the filename extension
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```typescript
|
|
78
|
+
* const schema = v.object({
|
|
79
|
+
* name: fileNameWithExtension(['.pdf', '.docx']),
|
|
80
|
+
* });
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export const fileNameWithExtension = (allowedExtensions, errorMessage) => pipe(string(), check((input) => {
|
|
84
|
+
const lastDotIndex = input.lastIndexOf('.');
|
|
85
|
+
if (lastDotIndex === -1 || lastDotIndex === input.length - 1) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
const lowerInput = input.toLowerCase();
|
|
89
|
+
const parts = lowerInput.split('.');
|
|
90
|
+
const ext1 = `.${parts[parts.length - 1]}`;
|
|
91
|
+
const ext2 = parts.length > 2 ? `.${parts[parts.length - 2]}.${parts[parts.length - 1]}` : null;
|
|
92
|
+
return !!(allowedExtensions.includes(ext1) || (ext2 && allowedExtensions.includes(ext2)));
|
|
93
|
+
}, errorMessage ?? `Invalid file type. Allowed: ${allowedExtensions.join(', ')}`));
|
|
94
|
+
//# sourceMappingURL=validators.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.js","sourceRoot":"","sources":["../../src/uploads/validators.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzD,+EAA+E;AAC/E,uBAAuB;AACvB,+EAA+E;AAE/E;;;GAGG;AACH,SAAS,OAAO,CAAC,QAAgB;IAC/B,OAAO,QAAQ;SACZ,SAAS,CAAC,KAAK,CAAC;SAChB,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC;SAC/B,WAAW,EAAE;SACb,OAAO,CAAC,aAAa,EAAE,GAAG,CAAC;SAC3B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,iBAAoC,EAAE,YAAqB,EAAE,EAAE,CAC/F,IAAI,CACF,MAAM,EAAE,EACR,KAAK,CACH,CAAC,KAAK,EAAE,EAAE;IACR,MAAM,YA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