fix architecture and write new tests

This commit is contained in:
root
2026-06-10 00:40:19 -04:00
parent 560da1cadf
commit 80a597bc10
377 changed files with 84020 additions and 1337 deletions
+34 -7
View File
@@ -10,12 +10,22 @@ const LEGACY_STORAGE_ROOTS = [
path.join(APP_SOURCE_ROOT, 'lib', 'storage'),
]
export type StorageVisibility = 'public' | 'private'
export function getStorageRoot(): string {
return process.env.FILE_STORAGE_ROOT
? path.resolve(process.env.FILE_STORAGE_ROOT)
: DEFAULT_STORAGE_ROOT
}
export function getPublicStorageRoot(): string {
return path.join(getStorageRoot(), 'public')
}
export function getPrivateStorageRoot(): string {
return path.join(getStorageRoot(), 'private')
}
export function getLegacyStorageRoots(): string[] {
return LEGACY_STORAGE_ROOTS
}
@@ -45,10 +55,22 @@ export function assertStorageConfiguration(): string {
return storageRoot
}
function ensureStorageRoot(): string {
const storageRoot = assertStorageConfiguration()
fs.mkdirSync(storageRoot, { recursive: true })
return storageRoot
function ensureStorageRoot(visibility: StorageVisibility): string {
assertStorageConfiguration()
const root = visibility === 'public' ? getPublicStorageRoot() : getPrivateStorageRoot()
fs.mkdirSync(root, { recursive: true })
return root
}
function inferVisibility(folder: string): StorageVisibility {
const normalized = folder.replace(/\\/g, '/')
if (/\/customers\//.test(`/${normalized}/`)) return 'private'
if (/\/licenses?\//.test(`/${normalized}/`)) return 'private'
if (/\/contracts?\//.test(`/${normalized}/`)) return 'private'
if (/\/documents?\//.test(`/${normalized}/`)) return 'private'
if (/\/inspections?\//.test(`/${normalized}/`)) return 'private'
if (/\/internal\//.test(`/${normalized}/`)) return 'private'
return 'public'
}
function getApiBase(): string {
@@ -77,10 +99,14 @@ export function getProtectedCustomerLicenseImageUrl(customerId: string): string
export async function uploadImage(
buffer: Buffer,
folder: string,
publicId?: string
publicId?: string,
visibility: StorageVisibility = inferVisibility(folder),
): Promise<string> {
const storageRoot = ensureStorageRoot()
const storageRoot = ensureStorageRoot(visibility)
const folderPath = path.join(storageRoot, folder)
if (!isWithinPath(folderPath, storageRoot)) {
throw new Error('Upload path escapes storage root')
}
fs.mkdirSync(folderPath, { recursive: true })
const filename = publicId
@@ -96,9 +122,10 @@ export function resolveStoredFilePath(imageUrl: string): string | null {
const relative = getStorageRelativePath(imageUrl)
if (!relative) return null
const roots = [assertStorageConfiguration(), ...getLegacyStorageRoots()]
const roots = [getPublicStorageRoot(), getPrivateStorageRoot(), ...getLegacyStorageRoots(), assertStorageConfiguration()]
for (const root of roots) {
const filePath = path.join(root, relative)
if (!isWithinPath(filePath, root)) continue
if (fs.existsSync(filePath)) {
return filePath
}