Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 1x 22x 22x 1x 18x 18x 29x 29x 29x 29x 21x 21x 1x 20x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 10x 10x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 2x 1x | /**
* Local filesystem storage controller
*/
import * as fs from 'fs';
import * as path from 'path';
import { promisify } from 'util';
import {
StorageController,
LocalStorageConfig,
DEFAULT_MAX_FILE_SIZE
} from './types';
import {
UploadFileProps,
UploadFileResult,
DownloadConfig,
DownloadMetadata,
StorageListResult,
StorageReference
} from '@rebasepro/types';
const mkdir = promisify(fs.mkdir);
const writeFile = promisify(fs.writeFile);
const readFile = promisify(fs.readFile);
const unlink = promisify(fs.unlink);
const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);
const access = promisify(fs.access);
/**
* Remove initial and trailing slashes from a path.
* Handles paths like "/images/", "images/", "/images" → "images"
*/
function normalizeStoragePath(s: string): string {
let result = s;
while (result.startsWith('/')) {
result = result.slice(1);
}
while (result.endsWith('/')) {
result = result.slice(0, -1);
}
return result;
}
/**
* Local filesystem storage implementation
* Stores files in a directory structure: {basePath}/{bucket}/{path}
*/
export class LocalStorageController implements StorageController {
private config: LocalStorageConfig;
private basePath: string;
constructor(config: LocalStorageConfig) {
this.config = config;
this.basePath = path.resolve(config.basePath);
}
getType(): 'local' {
return 'local';
}
/**
* Ensure directory exists, creating it if necessary
*/
private async ensureDir(dirPath: string): Promise<void> {
try {
await mkdir(dirPath, { recursive: true });
} catch (error: unknown) {
Iif (error instanceof Error && (error as NodeJS.ErrnoException).code !== 'EEXIST') {
throw error;
}
}
}
/**
* Get the full filesystem path for a storage path.
* Includes a path traversal guard to prevent escaping the base directory.
*/
private getFullPath(storagePath: string, bucket?: string): string {
const parts = bucket ? [this.basePath, bucket, storagePath] : [this.basePath, storagePath];
const resolved = path.resolve(path.join(...parts));
Iif (!resolved.startsWith(this.basePath + path.sep) && resolved !== this.basePath) {
throw new Error("Path traversal detected: resolved storage path is outside the base directory.");
}
return resolved;
}
/**
* Validate file before upload
*/
private validateFile(file: File): void {
const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
if (file.size > maxSize) {
throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);
}
if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {
if (!this.config.allowedMimeTypes.includes(file.type)) {
throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(', ')}`);
}
}
}
async uploadFile({
file,
fileName,
path: storagePath,
metadata,
bucket
}: UploadFileProps): Promise<UploadFileResult> {
this.validateFile(file);
// Always use a bucket (default to 'default')
const usedBucket = bucket ?? 'default';
const usedFileName = fileName ?? file.name;
// Normalize storage path to remove leading/trailing slashes
const normalizedPath = storagePath ? normalizeStoragePath(storagePath) : '';
const fullStoragePath = normalizedPath ? `${normalizedPath}/${usedFileName}` : usedFileName;
const fullPath = this.getFullPath(fullStoragePath, usedBucket);
// Ensure parent directory exists
await this.ensureDir(path.dirname(fullPath));
// Convert File to Buffer and write
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
await writeFile(fullPath, buffer);
// Always save metadata file with at least contentType (required for preview)
const metadataPath = `${fullPath}.metadata.json`;
await writeFile(metadataPath, JSON.stringify({
...(metadata || {}),
contentType: file.type,
size: file.size,
uploadedAt: new Date().toISOString()
}, null, 2));
return {
path: fullStoragePath,
bucket: usedBucket,
storageUrl: `local://${usedBucket}/${fullStoragePath}`
};
}
async getDownloadURL(storagePath: string, bucket?: string): Promise<DownloadConfig> {
// Handle local:// URLs
let resolvedPath = storagePath;
let resolvedBucket = bucket;
if (storagePath.startsWith('local://')) {
const withoutProtocol = storagePath.substring('local://'.length);
const firstSlash = withoutProtocol.indexOf('/');
if (firstSlash > 0) {
resolvedBucket = withoutProtocol.substring(0, firstSlash);
resolvedPath = withoutProtocol.substring(firstSlash + 1);
}
}
// Normalize path to handle leading/trailing slashes
resolvedPath = normalizeStoragePath(resolvedPath);
const fullPath = this.getFullPath(resolvedPath, resolvedBucket);
try {
await access(fullPath, fs.constants.R_OK);
} catch {
return {
url: null,
fileNotFound: true
};
}
// Read metadata if available
let metadata: DownloadMetadata | undefined;
const metadataPath = `${fullPath}.metadata.json`;
try {
const metadataContent = await readFile(metadataPath, 'utf-8');
const savedMetadata = JSON.parse(metadataContent);
const fileStat = await stat(fullPath);
metadata = {
bucket: resolvedBucket ?? 'default',
fullPath: resolvedPath,
name: path.basename(resolvedPath),
size: fileStat.size,
contentType: savedMetadata.contentType || 'application/octet-stream',
customMetadata: savedMetadata
};
} catch {
// No metadata file, create basic metadata from stat
try {
const fileStat = await stat(fullPath);
metadata = {
bucket: resolvedBucket ?? 'default',
fullPath: resolvedPath,
name: path.basename(resolvedPath),
size: fileStat.size,
contentType: 'application/octet-stream',
customMetadata: {}
};
} catch {
// Stat failed
}
}
// Return a relative URL that will be served by the storage routes
const bucketPath = resolvedBucket ? `${resolvedBucket}/` : '';
const url = `/api/storage/file/${bucketPath}${resolvedPath}`;
return {
url,
metadata
};
}
async getFile(storagePath: string, bucket?: string): Promise<File | null> {
// Handle local:// URLs
let resolvedPath = storagePath;
let resolvedBucket = bucket;
if (storagePath.startsWith('local://')) {
const withoutProtocol = storagePath.substring('local://'.length);
const firstSlash = withoutProtocol.indexOf('/');
if (firstSlash > 0) {
resolvedBucket = withoutProtocol.substring(0, firstSlash);
resolvedPath = withoutProtocol.substring(firstSlash + 1);
}
}
// Normalize path to handle leading/trailing slashes
resolvedPath = normalizeStoragePath(resolvedPath);
const fullPath = this.getFullPath(resolvedPath, resolvedBucket);
try {
await access(fullPath, fs.constants.R_OK);
const buffer = await readFile(fullPath);
// Try to get content type from metadata
let contentType = 'application/octet-stream';
try {
const metadataPath = `${fullPath}.metadata.json`;
const metadataContent = await readFile(metadataPath, 'utf-8');
const metadata = JSON.parse(metadataContent);
contentType = metadata.contentType || contentType;
} catch {
// No metadata, use default content type
}
const blob = new Blob([buffer], { type: contentType });
return new File([blob], path.basename(resolvedPath), { type: contentType });
} catch {
return null;
}
}
async deleteFile(storagePath: string, bucket?: string): Promise<void> {
// Handle local:// URLs
let resolvedPath = storagePath;
let resolvedBucket = bucket;
if (storagePath.startsWith('local://')) {
const withoutProtocol = storagePath.substring('local://'.length);
const firstSlash = withoutProtocol.indexOf('/');
if (firstSlash > 0) {
resolvedBucket = withoutProtocol.substring(0, firstSlash);
resolvedPath = withoutProtocol.substring(firstSlash + 1);
}
}
// Normalize path to handle leading/trailing slashes
resolvedPath = normalizeStoragePath(resolvedPath);
const fullPath = this.getFullPath(resolvedPath, resolvedBucket);
try {
await unlink(fullPath);
// Also delete metadata file if exists
try {
await unlink(`${fullPath}.metadata.json`);
} catch {
// Metadata file might not exist
}
} catch (error: unknown) {
Iif (error instanceof Error && (error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error;
}
// File doesn't exist, nothing to delete
}
}
async list(storagePath: string, options?: {
bucket?: string;
maxResults?: number;
pageToken?: string;
}): Promise<StorageListResult> {
// Normalize path to handle leading/trailing slashes
const normalizedPath = normalizeStoragePath(storagePath);
const fullPath = this.getFullPath(normalizedPath, options?.bucket);
const items: StorageReference[] = [];
const prefixes: StorageReference[] = [];
try {
await access(fullPath, fs.constants.R_OK);
const entries = await readdir(fullPath, { withFileTypes: true });
let count = 0;
const maxResults = options?.maxResults ?? 1000;
const startIndex = options?.pageToken ? parseInt(options.pageToken, 10) : 0;
for (let i = startIndex; i < entries.length && count < maxResults; i++) {
const entry = entries[i];
// Skip metadata files
if (entry.name.endsWith('.metadata.json')) {
continue;
}
const entryPath = storagePath ? `${storagePath}/${entry.name}` : entry.name;
const bucket = options?.bucket ?? 'default';
const ref: StorageReference = {
bucket,
fullPath: entryPath,
name: entry.name,
parent: null as never, // Simplified - not fully implementing parent chain
root: null as never,
toString: () => `local://${bucket}/${entryPath}`
};
Iif (entry.isDirectory()) {
prefixes.push(ref);
} else {
items.push(ref);
}
count++;
}
const nextPageToken = startIndex + count < entries.length
? String(startIndex + count)
: undefined;
return {
items,
prefixes,
nextPageToken
};
} catch (error: any) {
const code = error?.code;
if (code === 'ENOENT' || code === 'ENOTDIR') {
return { items: [], prefixes: [] };
}
throw error;
}
}
/**
* Get the absolute filesystem path for serving files
* Used by the storage routes to serve files directly
*/
getAbsolutePath(storagePath: string, bucket?: string): string {
return this.getFullPath(storagePath, bucket);
}
/**
* Get the base path for the storage
*/
getBasePath(): string {
return this.basePath;
}
}
|