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 protected album review findings

Timothy Yind9eff535ea90
diff --git a/i18n/locales/ja.json b/i18n/locales/ja.json
index 12795b65..bc0d7e72 100644
--- a/i18n/locales/ja.json
+++ b/i18n/locales/ja.json
@@ -794,11 +794,11 @@
"clearAll": "すべてクリア",
"isHidden": "アルバムを非表示",
"isHiddenHint": "非表示のアルバム内の写真はホームページに表示されません",
- "passwordProtection": "Password protection",
- "password": "Password",
- "passwordPlaceholder": "Enter a password",
- "passwordKeepHint": "Leave blank to keep the current password",
- "passwordRequired": "Please enter a password",
+ "passwordProtection": "パスワード保護",
+ "password": "パスワード",
+ "passwordPlaceholder": "パスワードを入力",
+ "passwordKeepHint": "現在のパスワードを変更しない場合は空欄にしてください",
+ "passwordRequired": "パスワードを入力してください",
"movePhotoUp": "写真を上へ移動",
"movePhotoDown": "写真を下へ移動",
"removePhoto": "写真を選択から外す"
diff --git a/i18n/locales/ru.json b/i18n/locales/ru.json
index bce6b213..86eb446b 100644
--- a/i18n/locales/ru.json
+++ b/i18n/locales/ru.json
@@ -867,11 +867,11 @@
"clearAll": "Очистить всё",
"isHidden": "Скрыть альбом",
"isHiddenHint": "Фотографии из скрытых альбомов не отображаются на главной странице",
- "passwordProtection": "Password protection",
- "password": "Password",
- "passwordPlaceholder": "Enter a password",
- "passwordKeepHint": "Leave blank to keep the current password",
- "passwordRequired": "Please enter a password",
+ "passwordProtection": "Защита паролем",
+ "password": "Пароль",
+ "passwordPlaceholder": "Введите пароль",
+ "passwordKeepHint": "Оставьте поле пустым, чтобы сохранить текущий пароль",
+ "passwordRequired": "Введите пароль",
"movePhotoUp": "Переместить фотографию вверх",
"movePhotoDown": "Переместить фотографию вниз",
"removePhoto": "Убрать фотографию"
diff --git a/server/api/albums/[albumId]/index.get.ts b/server/api/albums/[albumId]/index.get.ts
index 7053c5f6..652cecc6 100644
--- a/server/api/albums/[albumId]/index.get.ts
+++ b/server/api/albums/[albumId]/index.get.ts
@@ -41,13 +41,22 @@ export default eventHandler(async (event) => {
}
if (!canAccess(album)) {
- throw createError({ statusCode: 403, statusMessage: 'Album password required' })
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Album password required',
+ })
}
// 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 rows = await fetchAlbumPhotos(db, tables, albumId, isLoggedIn)
+ const rows = await fetchAlbumPhotos(
+ db,
+ tables,
+ albumId,
+ isLoggedIn,
+ isLoggedIn || Boolean(album.passwordHash),
+ )
const photos = album.passwordHash
? rows.map((photo) => ({
...photo,
diff --git a/server/api/albums/[albumId]/unlock.post.ts b/server/api/albums/[albumId]/unlock.post.ts
index 8f33471e..97d83bdd 100644
--- a/server/api/albums/[albumId]/unlock.post.ts
+++ b/server/api/albums/[albumId]/unlock.post.ts
@@ -1,12 +1,16 @@
import { eq } from 'drizzle-orm'
import type { H3Event } from 'h3'
import { z } from 'zod'
-import { grantAlbumAccess, verifyAlbumPassword } from '../../../utils/album-access'
+import {
+ grantAlbumAccess,
+ verifyAlbumPassword,
+} from '../../../utils/album-access'
const UNLOCK_WINDOW_MS = 60_000
const UNLOCK_MAX_ATTEMPTS = 8
const UNLOCK_MAX_ENTRIES = 5_000
const unlockAttempts = new Map<string, { count: number; resetAt: number }>()
+const trustProxy = process.env.NUXT_TRUST_PROXY === 'true'
function pruneUnlockAttempts(now: number) {
for (const [key, attempt] of unlockAttempts) {
@@ -15,7 +19,7 @@ function pruneUnlockAttempts(now: number) {
}
function assertUnlockRateLimit(event: H3Event, albumId: number) {
- const ip = getRequestIP(event, { xForwardedFor: false }) || 'unknown'
+ const ip = getRequestIP(event, { xForwardedFor: trustProxy }) || 'unknown'
const now = Date.now()
pruneUnlockAttempts(now)
const key = `${albumId}:${ip}`
@@ -28,25 +32,39 @@ function assertUnlockRateLimit(event: H3Event, albumId: number) {
return
}
if (attempt.count >= UNLOCK_MAX_ATTEMPTS) {
- throw createError({ statusCode: 429, statusMessage: 'Too many unlock 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: false }) || 'unknown'
- const album = useDB().select().from(tables.albums)
- .where(eq(tables.albums.id, albumId)).get()
+ 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: trustProxy }) || 'unknown'
+ 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' })
}
assertUnlockRateLimit(event, albumId)
- if (!await verifyAlbumPassword(password, album.passwordHash)) {
- throw createError({ statusCode: 401, statusMessage: 'Incorrect album password' })
+ if (!(await verifyAlbumPassword(password, album.passwordHash))) {
+ throw createError({
+ statusCode: 401,
+ statusMessage: 'Incorrect album password',
+ })
}
unlockAttempts.delete(`${albumId}:${clientIp}`)
grantAlbumAccess(event, album.id, album.passwordHash)
diff --git a/server/routes/image/[...key].get.ts b/server/routes/image/[...key].get.ts
index a16ce983..12b6ade0 100644
--- a/server/routes/image/[...key].get.ts
+++ b/server/routes/image/[...key].get.ts
@@ -1,4 +1,5 @@
import { eq } from 'drizzle-orm'
+import { Readable } from 'node:stream'
import { assertPhotoAccess } from '../../utils/album-access'
import { tables, useDB } from '../../utils/db'
@@ -14,40 +15,65 @@ export default eventHandler(async (event) => {
throw createError({ statusCode: 400, statusMessage: 'Invalid key' })
}
- const protectedMatch = /^__photo__\/([^/]+)\/(original|thumbnail|live)$/.exec(decodedKey)
+ 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()
+ 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
+ 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 absoluteTarget = new URL(targetUrl, getRequestURL(event)).toString()
const cookie = getHeader(event, 'cookie')
- const response = await fetch(absoluteTarget, cookie && targetUrl.startsWith('/')
- ? { headers: { cookie } }
- : undefined)
+ const headers: Record<string, string> = {}
+ if (cookie && targetUrl.startsWith('/')) headers.cookie = cookie
+ for (const name of ['range', 'if-range']) {
+ const value = getHeader(event, name)
+ if (value) headers[name] = value
+ }
+ const response = await fetch(
+ absoluteTarget,
+ Object.keys(headers).length ? { headers } : 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())
+ event.node.res.statusCode = response.status
+ for (const name of [
+ 'content-type',
+ 'content-length',
+ 'content-range',
+ 'accept-ranges',
+ 'content-disposition',
+ 'etag',
+ 'last-modified',
+ 'cache-control',
+ ]) {
+ const value = response.headers.get(name)
+ if (value) setHeader(event, name, value)
+ }
+ if (!response.body) {
+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })
+ }
+ return sendStream(event, Readable.fromWeb(response.body))
}
const restricted = await assertPhotoAccess(event, decodedKey)
diff --git a/server/utils/album-access.ts b/server/utils/album-access.ts
index 6e823ded..25ad7368 100644
--- a/server/utils/album-access.ts
+++ b/server/utils/album-access.ts
@@ -1,4 +1,11 @@
-import { createHash, createHmac, randomBytes, scrypt, 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'
@@ -15,7 +22,10 @@ export function hashAlbumPassword(password: string): string {
return `${salt}:${scryptSync(password, salt, 64).toString('hex')}`
}
-export async function verifyAlbumPassword(password: string, stored: string): Promise<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 = await scryptAsync(password, salt, 64)
@@ -23,8 +33,11 @@ export async function verifyAlbumPassword(password: string, stored: string): Pro
}
function signature(payload: string): string {
- return createHmac('sha256', process.env.NUXT_SESSION_PASSWORD || '')
- .update(payload).digest('base64url')
+ const secret = process.env.NUXT_SESSION_PASSWORD
+ if (!secret) {
+ throw new Error('NUXT_SESSION_PASSWORD is not configured')
+ }
+ return createHmac('sha256', secret).update(payload).digest('base64url')
}
function readGrants(event: H3Event): Grant[] {
@@ -33,26 +46,43 @@ function readGrants(event: H3Event): Grant[] {
const [payload, mac] = token.split('.')
if (!payload || !mac) return []
const actual = signature(payload)
- if (mac.length !== actual.length ||
- !timingSafeEqual(Buffer.from(mac), Buffer.from(actual))) return []
+ if (
+ mac.length !== actual.length ||
+ !timingSafeEqual(Buffer.from(mac), Buffer.from(actual))
+ )
+ return []
try {
- const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString())
+ 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')
+ return parsed.filter(
+ (item): item is Grant =>
+ Number.isSafeInteger(item?.id) && typeof item?.hash === 'string',
+ )
} catch {
return []
}
}
-export function grantAlbumAccess(event: H3Event, id: number, hash: string): void {
+export function grantAlbumAccess(
+ event: H3Event,
+ id: number,
+ 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')
- const secure = getHeader(event, 'x-forwarded-proto') === 'https' ||
+ const payload = Buffer.from(JSON.stringify(grants.slice(-60))).toString(
+ 'base64url',
+ )
+ const secure =
+ getHeader(event, 'x-forwarded-proto') === 'https' ||
getRequestURL(event).protocol === 'https:'
setCookie(event, cookieName, `${payload}.${signature(payload)}`, {
- httpOnly: true, sameSite: 'lax', secure, path: '/',
+ httpOnly: true,
+ sameSite: 'lax',
+ secure,
+ path: '/',
})
}
@@ -60,35 +90,62 @@ export async function albumAccess(event: H3Event) {
const session = await getUserSession(event)
const admin = Boolean(session.user)
const grants = readGrants(event)
- const canAccess = (album: { id: number; isHidden: boolean; passwordHash: string | null }) =>
- admin || (!album.isHidden && (!album.passwordHash ||
- grants.some((grant) => grant.id === album.id &&
- grant.hash === passwordVersion(album.passwordHash!))))
+ const canAccess = (album: {
+ id: number
+ isHidden: boolean
+ passwordHash: string | null
+ }) =>
+ admin ||
+ (!album.isHidden &&
+ (!album.passwordHash ||
+ grants.some(
+ (grant) =>
+ grant.id === album.id &&
+ grant.hash === passwordVersion(album.passwordHash!),
+ )))
return { admin, canAccess }
}
-export async function assertPhotoAccess(event: H3Event, key: string): Promise<boolean> {
+export async function assertPhotoAccess(
+ event: H3Event,
+ key: string,
+): Promise<boolean> {
const db = useDB()
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),
- ]),
- )).get()
+ 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),
+ ]),
+ ),
+ )
+ .get()
if (!photo) return false
const { admin, canAccess } = await albumAccess(event)
- const memberships = db.select({ album: tables.albums })
+ 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)
+ .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))) {
+ 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' })
}
return restricted
diff --git a/server/utils/album-visibility.ts b/server/utils/album-visibility.ts
index a41b2029..3248afbc 100644
--- a/server/utils/album-visibility.ts
+++ b/server/utils/album-visibility.ts
@@ -17,6 +17,7 @@ export async function fetchAlbumPhotos(
tables: typeof schema,
albumId: number,
loggedIn: boolean,
+ includePasswordProtected = loggedIn,
) {
const rows = await db
.select({
@@ -31,7 +32,7 @@ export async function fetchAlbumPhotos(
.orderBy(asc(tables.albumPhotos.position))
.all()
- if (loggedIn) {
+ if (includePasswordProtected) {
return rows
}
@@ -43,8 +44,15 @@ export async function fetchAlbumPhotos(
tables.albums,
eq(tables.albumPhotos.albumId, tables.albums.id),
)
- .where(or(eq(tables.albums.isHidden, true), and(
- isNotNull(tables.albums.passwordHash), ne(tables.albums.id, albumId))))
+ .where(
+ or(
+ eq(tables.albums.isHidden, true),
+ and(
+ isNotNull(tables.albums.passwordHash),
+ ne(tables.albums.id, albumId),
+ ),
+ ),
+ )
.all()
).map((r: { photoId: string }) => r.photoId)