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 protected album access grants and media checks
Timothy Yinb2dc5ba74144
diff --git a/server/utils/album-access.ts b/server/utils/album-access.tsindex d91bd201..aeed7ef9 100644--- a/server/utils/album-access.ts+++ b/server/utils/album-access.ts@@ -11,7 +11,9 @@ import type { H3Event } from 'h3'import { tables, useDB } from './db'const cookieName = 'album_access'-type Grant = { id: number; hash: string }+const grantLifetimeSeconds = 7 * 24 * 60 * 60+const maxGrants = 30+type Grant = { id: number; hash: string; expiresAt: number }const scryptAsync = promisify(scrypt)function sessionSecret(): string {const secret = process.env.NUXT_SESSION_PASSWORD@@ -22,7 +24,11 @@ function sessionSecret(): string {}const passwordVersion = (hash: string) =>- createHmac('sha256', sessionSecret()).update(hash).digest('hex').slice(0, 16)+ createHmac('sha256', sessionSecret())+ .update('album-password-version\0')+ .update(hash)+ .digest('hex')+ .slice(0, 32)export function hashAlbumPassword(password: string): string {const salt = randomBytes(16).toString('hex')@@ -41,6 +47,7 @@ export async function verifyAlbumPassword(function signature(payload: string): string {return createHmac('sha256', sessionSecret())+ .update('album-access-cookie\0').update(payload).digest('base64url')}@@ -48,8 +55,9 @@ function signature(payload: string): string {function readGrants(event: H3Event): Grant[] {const token = getCookie(event, cookieName)if (!token || token.length > 4000) return []- const [payload, mac] = token.split('.')- if (!payload || !mac) return []+ const match = /^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]{43})$/.exec(token)+ if (!match) return []+ const [, payload, mac] = matchconst actual = signature(payload)if (mac.length !== actual.length ||@@ -60,11 +68,21 @@ function readGrants(event: H3Event): Grant[] {const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString(),)- if (!Array.isArray(parsed)) return []- return parsed.filter(- (item): item is Grant =>- Number.isSafeInteger(item?.id) && typeof item?.hash === 'string',+ if (!Array.isArray(parsed) || parsed.length > maxGrants) return []+ const now = Date.now()+ if (+ !parsed.every(+ (item): item is Grant =>+ Number.isSafeInteger(item?.id) &&+ item.id > 0 &&+ typeof item?.hash === 'string' &&+ /^[a-f0-9]{32}$/.test(item.hash) &&+ Number.isSafeInteger(item?.expiresAt) &&+ item.expiresAt <= now + grantLifetimeSeconds * 1000,+ ))+ return []+ return parsed.filter((grant) => grant.expiresAt > now)} catch {return []}@@ -76,10 +94,14 @@ export function grantAlbumAccess(hash: string,): void {const grants = readGrants(event).filter((grant) => grant.id !== id)- grants.push({ id, hash: passwordVersion(hash) })- const payload = Buffer.from(JSON.stringify(grants.slice(-60))).toString(- 'base64url',- )+ grants.push({+ id,+ hash: passwordVersion(hash),+ expiresAt: Date.now() + grantLifetimeSeconds * 1000,+ })+ const payload = Buffer.from(+ JSON.stringify(grants.slice(-maxGrants)),+ ).toString('base64url')const secure =getHeader(event, 'x-forwarded-proto') === 'https' ||getRequestURL(event).protocol === 'https:'@@ -88,6 +110,7 @@ export function grantAlbumAccess(sameSite: 'lax',secure,path: '/',+ maxAge: grantLifetimeSeconds,})}@@ -117,7 +140,7 @@ export async function assertPhotoAccess(): Promise<boolean> {const db = useDB()const values = [key, `/storage/${key}`, `/image/${key}`]- const photo = db+ const photos = db.select().from(tables.photos).where(@@ -133,25 +156,33 @@ export async function assertPhotoAccess(]),),)- .get()- if (!photo) return false- const { admin, canAccess } = await albumAccess(event)- const memberships = db- .select({ album: tables.albums })- .from(tables.albumPhotos)- .innerJoin(tables.albums, eq(tables.albumPhotos.albumId, tables.albums.id))- .where(eq(tables.albumPhotos.photoId, photo.id)).all()- const restricted = memberships.some(- ({ album }) => album.isHidden || album.passwordHash,- )- if (admin) return restricted- if (- memberships.some(({ album }) => album.isHidden) ||- (memberships.some(({ album }) => album.passwordHash) &&- !memberships.some(({ album }) => album.passwordHash && canAccess(album)))- ) {- throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ if (photos.length === 0) return false+ const { admin, canAccess } = await albumAccess(event)+ let restricted = false+ for (const photo of photos) {+ const memberships = db+ .select({ album: tables.albums })+ .from(tables.albumPhotos)+ .innerJoin(+ tables.albums,+ eq(tables.albumPhotos.albumId, tables.albums.id),+ )+ .where(eq(tables.albumPhotos.photoId, photo.id))+ .all()+ if (memberships.some(({ album }) => album.isHidden || album.passwordHash)) {+ restricted = true+ }+ if (+ !admin &&+ (memberships.some(({ album }) => album.isHidden) ||+ (memberships.some(({ album }) => album.passwordHash) &&+ !memberships.some(+ ({ album }) => album.passwordHash && canAccess(album),+ )))+ ) {+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ }}return restricted}