Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix: harden media filename handling and photo access checks
Timothy Yinb5fe12ec364e
diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vueindex 2747a546..03287632 100644--- a/app/components/photo/InfoPanel.vue+++ b/app/components/photo/InfoPanel.vue@@ -127,11 +127,12 @@ const formatedExifData = computed<Record<string, KVData[]>>(() => {{title: $t('exif.sections.basic'),items: [- props.currentPhoto.storageKey+ props.currentPhoto.fileName || props.currentPhoto.storageKey? {label: $t('exif.filename'),value:- props.currentPhoto.storageKey.split('/').pop() ||+ props.currentPhoto.fileName ||+ props.currentPhoto.storageKey?.split('/').pop() ||props.currentPhoto.storageKey,icon: 'tabler:file',}diff --git a/server/api/albums/[albumId]/index.get.ts b/server/api/albums/[albumId]/index.get.tsindex 652cecc6..eb7721ad 100644--- a/server/api/albums/[albumId]/index.get.ts+++ b/server/api/albums/[albumId]/index.get.ts@@ -58,14 +58,24 @@ export default eventHandler(async (event) => {isLoggedIn || Boolean(album.passwordHash),)const photos = album.passwordHash- ? rows.map((photo) => ({- ...photo,- originalUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/original`,- thumbnailUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/thumbnail`,- livePhotoVideoUrl: photo.livePhotoVideoUrl- ? `/image/__photo__/${encodeURIComponent(photo.id)}/live`- : null,- }))+ ? rows.map((photo) => {+ const fileName = photo.storageKey?.split(/[\\/]/).pop() || null+ const {+ storageKey: _storageKey,+ thumbnailKey: _thumbnailKey,+ livePhotoVideoKey: _livePhotoVideoKey,+ ...safePhoto+ } = photo+ return {+ ...safePhoto,+ fileName,+ originalUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/original`,+ thumbnailUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/thumbnail`,+ livePhotoVideoUrl: photo.livePhotoVideoUrl+ ? `/image/__photo__/${encodeURIComponent(photo.id)}/live`+ : null,+ }+ }): rowsreturn {diff --git a/server/routes/image/[...key].get.ts b/server/routes/image/[...key].get.tsindex 28400dc1..e0c00446 100644--- a/server/routes/image/[...key].get.ts+++ b/server/routes/image/[...key].get.ts@@ -11,7 +11,14 @@ export default eventHandler(async (event) => {throw createError({ statusCode: 400, statusMessage: 'Invalid key' })}const decodedKey = decodeURIComponent(key)- if (decodedKey.split(/[\\/]/).some((part) => part === '..' || part === '.')) {+ const cleanKey = decodedKey+ .replace(/\\/g, '/')+ .replace(/\/+/g, '/')+ .replace(/^\/+/, '')+ if (decodedKey !== cleanKey) {+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ }+ if (cleanKey.split('/').some((part) => part === '..' || part === '.')) {throw createError({ statusCode: 400, statusMessage: 'Invalid key' })}@@ -76,10 +83,10 @@ export default eventHandler(async (event) => {return sendStream(event, Readable.fromWeb(response.body))}- const restricted = await assertPhotoAccess(event, decodedKey)+ const restricted = await assertPhotoAccess(event, cleanKey)if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')- const photo = await storageProvider.get(decodedKey)+ const photo = await storageProvider.get(cleanKey)if (!photo) {throw createError({ statusCode: 404, statusMessage: 'Photo not found' })}diff --git a/server/routes/storage/[...path].ts b/server/routes/storage/[...path].tsindex 431f5bf1..80c7abfa 100644--- a/server/routes/storage/[...path].ts+++ b/server/routes/storage/[...path].ts@@ -48,6 +48,10 @@ export default defineEventHandler(async (event) => {.replace(/\/+/g, '/').replace(/^\/+/, '')+ if (decodedPath !== relPath) {+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ }+const restricted = await assertPhotoAccess(event, relPath)// 阻止路径穿越@@ -74,8 +78,11 @@ export default defineEventHandler(async (event) => {const etag = `W/"${stat.size}-${stat.mtimeMs}"`setHeader(event, 'ETag', etag)setHeader(event, 'Last-Modified', stat.mtime.toUTCString())- setHeader(event, 'Cache-Control', restricted- ? 'private, no-store' : 'public, max-age=31536000, immutable')+ setHeader(+ event,+ 'Cache-Control',+ restricted ? 'private, no-store' : 'public, max-age=31536000, immutable',+ )// Content-Typeconst contentType = guessContentType(absolute)diff --git a/server/routes/thumb/[...thumbnailUrl].get.ts b/server/routes/thumb/[...thumbnailUrl].get.tsindex e100dc88..371ee8d6 100644--- a/server/routes/thumb/[...thumbnailUrl].get.ts+++ b/server/routes/thumb/[...thumbnailUrl].get.ts@@ -14,13 +14,26 @@ export default eventHandler(async (event) => {}url = decodeURIComponent(url)- const protectedPhotoMatch = /^\/image\/__photo__\/([^/]+)\/(?:thumbnail|original|live)$/.exec(url)+ const isAppPath = url.startsWith('/storage/') || url.startsWith('/image/')+ let absoluteUrl: URL | undefined+ if (!isAppPath) {+ try {+ absoluteUrl = new URL(url)+ } catch {+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ }+ if (absoluteUrl.protocol !== 'http:' && absoluteUrl.protocol !== 'https:') {+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ }+ }+ const protectedPhotoMatch =+ /^\/image\/__photo__\/([^/]+)\/(?:thumbnail|original|live)$/.exec(url)const accessKey = protectedPhotoMatch? decodeURIComponent(protectedPhotoMatch[1] || '')- : (url.startsWith('/storage/') || url.startsWith('/image/')- ? url.replace(/^\/(?:storage|image)\//, '')- : url)- const restricted = await assertPhotoAccess(event, accessKey)+ : isAppPath+ ? url.replace(/^\/(?:storage|image)\//, '')+ : url+ const restricted = await assertPhotoAccess(event, accessKey, !isAppPath)if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')const shouldForwardCookieToStorage =@@ -36,9 +49,12 @@ export default eventHandler(async (event) => {}const cookie = getHeader(event, 'cookie')- const photo = await fetch(url, cookie && shouldForwardCookieToStorage- ? { headers: { cookie } }- : undefined)+ const photo = await fetch(+ url,+ cookie && shouldForwardCookieToStorage+ ? { headers: { cookie } }+ : undefined,+ ).then((res) => {if (!res.ok) {throw createError({ statusCode: 404, statusMessage: 'Photo not found' })diff --git a/server/utils/album-access.ts b/server/utils/album-access.tsindex 67e528fa..a11fe885 100644--- a/server/utils/album-access.ts+++ b/server/utils/album-access.ts@@ -136,9 +136,21 @@ export async function albumAccess(event: H3Event) {export async function assertPhotoAccess(event: H3Event,key: string,+ requireKnown = false,): Promise<boolean> {+ const { admin, canAccess } = await albumAccess(event)+ // Match the local storage provider's path cleanup, but never silently+ // authorize a non-canonical spelling that the provider would normalize.+ const isAbsoluteUrl = /^https?:\/\//i.test(key)+ const cleanKey = isAbsoluteUrl+ ? key+ : key.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '')+ if (!isAbsoluteUrl && key !== cleanKey) {+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ }+const db = useDB()- const values = [key, `/storage/${key}`, `/image/${key}`]+ const values = [cleanKey, `/storage/${cleanKey}`, `/image/${cleanKey}`]const photos = db.select().from(tables.photos)@@ -156,10 +168,37 @@ export async function assertPhotoAccess(),).all()- if (photos.length === 0) return false- const { admin, canAccess } = await albumAccess(event)+ const normalized = db.select().from(tables.photos).all()+ const matches = normalized.filter((photo) =>+ [+ photo.id,+ photo.storageKey,+ photo.thumbnailKey,+ photo.originalUrl,+ photo.thumbnailUrl,+ photo.livePhotoVideoKey,+ photo.livePhotoVideoUrl,+ ]+ .filter((value): value is string => Boolean(value))+ .some(+ (value) =>+ value.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/+/, '') ===+ cleanKey,+ ),+ )+ const matchedPhotos = [+ ...new Map(+ [...photos, ...matches].map((photo) => [photo.id, photo]),+ ).values(),+ ]+ if (matchedPhotos.length === 0) {+ if (!admin || requireKnown) {+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ }+ return false+ }let restricted = false- for (const photo of photos) {+ for (const photo of matchedPhotos) {const memberships = db.select({ album: tables.albums }).from(tables.albumPhotos)diff --git a/shared/types/global.d.ts b/shared/types/global.d.tsindex 0df6f43b..0fe21b4f 100644--- a/shared/types/global.d.ts+++ b/shared/types/global.d.ts@@ -2,6 +2,9 @@ import type { WorkerPool } from '../../server/services/pipeline-queue'declare global {var __workerPool: WorkerPool | undefined+ interface Photo {+ fileName?: string | null+ }}export {}