Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix: address PR review feedback for protected albums

copilot-swe-agent[bot]429c71cf19cd
diff --git a/app/pages/albums/[albumId].vue b/app/pages/albums/[albumId].vue
index d56ed0ad..8a2280c7 100644
--- a/app/pages/albums/[albumId].vue
+++ b/app/pages/albums/[albumId].vue
@@ -28,12 +28,12 @@ if (error.value && error.value.statusCode !== 403) {
const albumPassword = ref('')
const isUnlocking = ref(false)
-const unlockError = ref(false)
+const unlockErrorMessageKey = ref<string | null>(null)
const unlockSucceeded = ref(false)
const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)')
const unlockAlbum = async () => {
isUnlocking.value = true
- unlockError.value = false
+ unlockErrorMessageKey.value = null
unlockSucceeded.value = false
try {
await $fetch(`/api/albums/${albumId.value}/unlock`, {
@@ -45,8 +45,10 @@ const unlockAlbum = async () => {
if (!prefersReducedMotion.value) {
await new Promise((resolve) => setTimeout(resolve, 220))
}
- } catch {
- unlockError.value = true
+ } catch (err: any) {
+ unlockErrorMessageKey.value = err?.statusCode === 401 || err?.status === 401
+ ? 'album.incorrectPassword'
+ : 'album.failedToLoad'
} finally {
isUnlocking.value = false
}
@@ -224,15 +226,15 @@ useHead({
>
<form class="flex flex-col gap-3" @submit.prevent="unlockAlbum">
<motion.div
- :animate="unlockError && !prefersReducedMotion
+ :animate="unlockErrorMessageKey && !prefersReducedMotion
? { x: [0, -6, 6, -4, 4, 0] } : { x: 0 }"
:transition="{ duration: 0.32 }"
>
<UInput v-model="albumPassword" type="password" autocomplete="off"
:placeholder="$t('album.passwordPlaceholder')" autofocus class="w-full" />
</motion.div>
- <p v-if="unlockError" role="alert" class="text-sm text-error-500">
- {{ $t('album.incorrectPassword') }}
+ <p v-if="unlockErrorMessageKey" role="alert" class="text-sm text-error-500">
+ {{ $t(unlockErrorMessageKey) }}
</p>
<UButton type="submit" block :loading="isUnlocking" :disabled="!albumPassword">
{{ $t('album.unlock') }}
diff --git a/i18n/locales/ja.json b/i18n/locales/ja.json
index f8a06ced..12795b65 100644
--- a/i18n/locales/ja.json
+++ b/i18n/locales/ja.json
@@ -150,10 +150,10 @@
}
},
"album": {
- "passwordRequired": "Password required",
- "passwordPlaceholder": "Enter album password",
- "incorrectPassword": "Incorrect password",
- "unlock": "Unlock album",
+ "passwordRequired": "パスワードが必要です",
+ "passwordPlaceholder": "アルバムのパスワードを入力",
+ "incorrectPassword": "パスワードが正しくありません",
+ "unlock": "アルバムのロックを解除",
"notFound": "アルバムが見つかりません",
"noDateInfo": "日付情報なし",
"noPhotosTip": "このアルバムにはまだ写真がありません",
diff --git a/i18n/locales/ru.json b/i18n/locales/ru.json
index 3acdd23d..bce6b213 100644
--- a/i18n/locales/ru.json
+++ b/i18n/locales/ru.json
@@ -150,10 +150,10 @@
}
},
"album": {
- "passwordRequired": "Password required",
- "passwordPlaceholder": "Enter album password",
- "incorrectPassword": "Incorrect password",
- "unlock": "Unlock album",
+ "passwordRequired": "Требуется пароль",
+ "passwordPlaceholder": "Введите пароль альбома",
+ "incorrectPassword": "Неверный пароль",
+ "unlock": "Разблокировать альбом",
"notFound": "Альбом не найден",
"noDateInfo": "Нет данных о дате",
"noPhotosTip": "В этом альбоме пока нет фотографий",
diff --git a/server/api/albums/[albumId]/index.get.ts b/server/api/albums/[albumId]/index.get.ts
index a513961f..7053c5f6 100644
--- a/server/api/albums/[albumId]/index.get.ts
+++ b/server/api/albums/[albumId]/index.get.ts
@@ -47,7 +47,17 @@ export default eventHandler(async (event) => {
// Anonymous viewers must not see photos that are also members of any
// hidden album — otherwise a photo shared between a public and a hidden
// album would leak through the public album (see issue #299).
- const photos = await fetchAlbumPhotos(db, tables, albumId, isLoggedIn)
+ const rows = await fetchAlbumPhotos(db, tables, albumId, isLoggedIn)
+ 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
return {
...album,
diff --git a/server/api/albums/[albumId]/unlock.post.ts b/server/api/albums/[albumId]/unlock.post.ts
index 00b32891..22aa744b 100644
--- a/server/api/albums/[albumId]/unlock.post.ts
+++ b/server/api/albums/[albumId]/unlock.post.ts
@@ -1,20 +1,43 @@
import { eq } from 'drizzle-orm'
+import type { H3Event } from 'h3'
import { z } from 'zod'
import { grantAlbumAccess, verifyAlbumPassword } from '../../../utils/album-access'
+const UNLOCK_WINDOW_MS = 60_000
+const UNLOCK_MAX_ATTEMPTS = 8
+const unlockAttempts = new Map<string, { count: number; resetAt: number }>()
+
+function assertUnlockRateLimit(event: H3Event, albumId: number) {
+ const ip = getRequestIP(event, { xForwardedFor: true }) || 'unknown'
+ const now = Date.now()
+ const key = `${albumId}:${ip}`
+ const attempt = unlockAttempts.get(key)
+ if (!attempt || attempt.resetAt <= now) {
+ unlockAttempts.set(key, { count: 1, resetAt: now + UNLOCK_WINDOW_MS })
+ return
+ }
+ if (attempt.count >= UNLOCK_MAX_ATTEMPTS) {
+ throw createError({ statusCode: 429, statusMessage: 'Too many unlock attempts' })
+ }
+ attempt.count += 1
+}
+
export default eventHandler(async (event) => {
const { albumId } = await getValidatedRouterParams(event,
z.object({ albumId: z.coerce.number().int().positive() }).parse)
const { password } = await readValidatedBody(event,
z.object({ password: z.string().min(1).max(128) }).parse)
+ const clientIp = getRequestIP(event, { xForwardedFor: true }) || 'unknown'
+ assertUnlockRateLimit(event, albumId)
const album = useDB().select().from(tables.albums)
.where(eq(tables.albums.id, albumId)).get()
if (!album || album.isHidden || !album.passwordHash) {
throw createError({ statusCode: 404, statusMessage: 'Album not found' })
}
- if (!verifyAlbumPassword(password, album.passwordHash)) {
+ if (!await verifyAlbumPassword(password, album.passwordHash)) {
throw createError({ statusCode: 401, statusMessage: 'Incorrect album password' })
}
+ unlockAttempts.delete(`${albumId}:${clientIp}`)
grantAlbumAccess(event, album.id, album.passwordHash)
return { ok: true }
})
diff --git a/server/routes/image/[...key].get.ts b/server/routes/image/[...key].get.ts
index 5fa14193..a16ce983 100644
--- a/server/routes/image/[...key].get.ts
+++ b/server/routes/image/[...key].get.ts
@@ -1,4 +1,6 @@
+import { eq } from 'drizzle-orm'
import { assertPhotoAccess } from '../../utils/album-access'
+import { tables, useDB } from '../../utils/db'
export default eventHandler(async (event) => {
const { storageProvider } = useStorageProvider(event)
@@ -7,14 +9,51 @@ export default eventHandler(async (event) => {
if (!key) {
throw createError({ statusCode: 400, statusMessage: 'Invalid key' })
}
- if (decodeURIComponent(key).split(/[\\/]/).some((part) => part === '..' || part === '.')) {
+ const decodedKey = decodeURIComponent(key)
+ if (decodedKey.split(/[\\/]/).some((part) => part === '..' || part === '.')) {
throw createError({ statusCode: 400, statusMessage: 'Invalid key' })
}
- const restricted = await assertPhotoAccess(event, key)
+ const protectedMatch = /^__photo__\/([^/]+)\/(original|thumbnail|live)$/.exec(decodedKey)
+ if (protectedMatch) {
+ const [, photoId, kind] = protectedMatch
+ const photo = useDB().select().from(tables.photos).where(eq(tables.photos.id, photoId)).get()
+ if (!photo) {
+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
+ }
+ const restricted = await assertPhotoAccess(event, photo.id)
+ if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')
+
+ const targetUrl = kind === 'original'
+ ? photo.originalUrl
+ : kind === 'thumbnail'
+ ? photo.thumbnailUrl
+ : photo.livePhotoVideoUrl
+ if (!targetUrl) {
+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
+ }
+
+ const scheme = event.node.req.headers['x-forwarded-proto'] || 'http'
+ const host = event.node.req.headers.host
+ const absoluteTarget = targetUrl.startsWith('/') && host
+ ? `${scheme}://${host}${targetUrl}`
+ : targetUrl
+ const cookie = getHeader(event, 'cookie')
+ const response = await fetch(absoluteTarget, cookie && targetUrl.startsWith('/')
+ ? { headers: { cookie } }
+ : undefined)
+ if (!response.ok) {
+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
+ }
+ const contentType = response.headers.get('content-type')
+ if (contentType) setHeader(event, 'Content-Type', contentType)
+ return Buffer.from(await response.arrayBuffer())
+ }
+
+ const restricted = await assertPhotoAccess(event, decodedKey)
if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')
- const photo = await storageProvider.get(key)
+ const photo = await storageProvider.get(decodedKey)
if (!photo) {
throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
}
diff --git a/server/routes/thumb/[...thumbnailUrl].get.ts b/server/routes/thumb/[...thumbnailUrl].get.ts
index 3b2f964d..d0ce17a1 100644
--- a/server/routes/thumb/[...thumbnailUrl].get.ts
+++ b/server/routes/thumb/[...thumbnailUrl].get.ts
@@ -18,6 +18,10 @@ export default eventHandler(async (event) => {
? url.replace(/^\/(?:storage|image)\//, '') : url)
if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')
+ const shouldForwardCookieToStorage =
+ storageProvider.config?.provider === 'local' &&
+ url.startsWith('/storage/')
+
if (
storageProvider.config?.provider === 'local' &&
url.startsWith('/storage/')
@@ -26,7 +30,10 @@ export default eventHandler(async (event) => {
url = `${scheme}://${event.node.req.headers.host}${url}`
}
- const photo = await fetch(url)
+ const cookie = getHeader(event, 'cookie')
+ 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.ts
index e00b4bb3..6e823ded 100644
--- a/server/utils/album-access.ts
+++ b/server/utils/album-access.ts
@@ -1,10 +1,12 @@
-import { createHash, createHmac, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'
+import { createHash, createHmac, randomBytes, scrypt, scryptSync, timingSafeEqual } from 'node:crypto'
+import { promisify } from 'node:util'
import { eq, or } from 'drizzle-orm'
import type { H3Event } from 'h3'
import { tables, useDB } from './db'
const cookieName = 'album_access'
type Grant = { id: number; hash: string }
+const scryptAsync = promisify(scrypt)
const passwordVersion = (hash: string) =>
createHash('sha256').update(hash).digest('hex').slice(0, 16)
@@ -13,10 +15,10 @@ export function hashAlbumPassword(password: string): string {
return `${salt}:${scryptSync(password, salt, 64).toString('hex')}`
}
-export function verifyAlbumPassword(password: string, stored: string): boolean {
+export async function verifyAlbumPassword(password: string, stored: string): Promise<boolean> {
const [salt, expected] = stored.split(':')
if (!salt || !expected || !/^[a-f0-9]{128}$/.test(expected)) return false
- const actual = scryptSync(password, salt, 64)
+ const actual = await scryptAsync(password, salt, 64)
return timingSafeEqual(actual, Buffer.from(expected, 'hex'))
}
@@ -70,6 +72,7 @@ export async function assertPhotoAccess(event: H3Event, key: string): Promise<bo
const values = [key, `/storage/${key}`, `/image/${key}`]
const photo = db.select().from(tables.photos).where(or(
...values.flatMap((value) => [
+ eq(tables.photos.id, value),
eq(tables.photos.storageKey, value), eq(tables.photos.thumbnailKey, value),
eq(tables.photos.originalUrl, value), eq(tables.photos.thumbnailUrl, value),
eq(tables.photos.livePhotoVideoKey, value), eq(tables.photos.livePhotoVideoUrl, value),