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.

feat(albums): improve rate limiting and error handling for albums

Ahmet Ömer555227470fb7
diff --git a/app/pages/albums/[albumId].vue b/app/pages/albums/[albumId].vue
index b258f9b9..0d2fc8da 100644
--- a/app/pages/albums/[albumId].vue
+++ b/app/pages/albums/[albumId].vue
@@ -46,9 +46,13 @@ const unlockAlbum = async () => {
await new Promise((resolve) => setTimeout(resolve, 220))
}
} catch (err: any) {
- unlockErrorMessageKey.value = err?.statusCode === 401 || err?.status === 401
- ? 'album.incorrectPassword'
- : 'album.failedToLoad'
+ const status = err?.statusCode ?? err?.status
+ unlockErrorMessageKey.value =
+ status === 401
+ ? 'album.incorrectPassword'
+ : status === 429
+ ? 'album.tooManyAttempts'
+ : 'album.failedToLoad'
} finally {
isUnlocking.value = false
}
diff --git a/i18n/locales/en.json b/i18n/locales/en.json
index 688a42e3..4a603571 100644
--- a/i18n/locales/en.json
+++ b/i18n/locales/en.json
@@ -157,6 +157,7 @@
"passwordRequired": "Password required",
"passwordPlaceholder": "Enter album password",
"incorrectPassword": "Incorrect password",
+ "tooManyAttempts": "Too many attempts. Try again within a minute.",
"unlock": "Unlock album",
"notFound": "Album not found",
"noDateInfo": "No date info",
diff --git a/i18n/locales/ja.json b/i18n/locales/ja.json
index a6db4f05..60c44492 100644
--- a/i18n/locales/ja.json
+++ b/i18n/locales/ja.json
@@ -157,6 +157,7 @@
"passwordRequired": "パスワードが必要です",
"passwordPlaceholder": "アルバムのパスワードを入力",
"incorrectPassword": "パスワードが正しくありません",
+ "tooManyAttempts": "試行回数が多すぎます。1分以内に再度お試しください。",
"unlock": "アルバムのロックを解除",
"notFound": "アルバムが見つかりません",
"noDateInfo": "日付情報なし",
diff --git a/i18n/locales/ru.json b/i18n/locales/ru.json
index 6935ccf6..016a2200 100644
--- a/i18n/locales/ru.json
+++ b/i18n/locales/ru.json
@@ -157,6 +157,7 @@
"passwordRequired": "Требуется пароль",
"passwordPlaceholder": "Введите пароль альбома",
"incorrectPassword": "Неверный пароль",
+ "tooManyAttempts": "Слишком много попыток. Повторите попытку в течение минуты.",
"unlock": "Разблокировать альбом",
"notFound": "Альбом не найден",
"noDateInfo": "Нет данных о дате",
diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.json
index fa33d794..ff0aaa66 100644
--- a/i18n/locales/zh-Hans.json
+++ b/i18n/locales/zh-Hans.json
@@ -171,6 +171,7 @@
"passwordRequired": "此相簿需要密码",
"passwordPlaceholder": "输入相簿密码",
"incorrectPassword": "密码错误",
+ "tooManyAttempts": "尝试次数过多。请在一分钟内再试。",
"unlock": "解锁相簿",
"notFound": "相簿未找到",
"noDateInfo": "无日期信息",
diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.json
index 3153e357..e4d2db64 100644
--- a/i18n/locales/zh-Hant-HK.json
+++ b/i18n/locales/zh-Hant-HK.json
@@ -171,6 +171,7 @@
"passwordRequired": "此相簿需要密碼",
"passwordPlaceholder": "輸入相簿密碼",
"incorrectPassword": "密碼錯誤",
+ "tooManyAttempts": "嘗試次數過多。請在一分鐘內再試。",
"unlock": "解鎖相簿",
"notFound": "搵唔到相簿",
"noDateInfo": "無日期資料",
diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.json
index 03d01ffd..a9779b47 100644
--- a/i18n/locales/zh-Hant-TW.json
+++ b/i18n/locales/zh-Hant-TW.json
@@ -171,6 +171,7 @@
"passwordRequired": "此相簿需要密碼",
"passwordPlaceholder": "輸入相簿密碼",
"incorrectPassword": "密碼錯誤",
+ "tooManyAttempts": "嘗試次數過多。請在一分鐘內再試。",
"unlock": "解鎖相簿",
"notFound": "找不到相簿",
"noDateInfo": "無日期資訊",
diff --git a/server/api/albums/[albumId]/unlock.post.ts b/server/api/albums/[albumId]/unlock.post.ts
index 97d83bdd..5070dbb3 100644
--- a/server/api/albums/[albumId]/unlock.post.ts
+++ b/server/api/albums/[albumId]/unlock.post.ts
@@ -1,45 +1,16 @@
import { eq } from 'drizzle-orm'
-import type { H3Event } from 'h3'
import { z } from 'zod'
import {
grantAlbumAccess,
verifyAlbumPassword,
} from '../../../utils/album-access'
+import {
+ assertAlbumUnlockRateLimit,
+ clearAlbumUnlockClient,
+} from '../../../utils/album-unlock-limit'
-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) {
- if (attempt.resetAt <= now) unlockAttempts.delete(key)
- }
-}
-
-function assertUnlockRateLimit(event: H3Event, albumId: number) {
- const ip = getRequestIP(event, { xForwardedFor: trustProxy }) || 'unknown'
- const now = Date.now()
- pruneUnlockAttempts(now)
- const key = `${albumId}:${ip}`
- const attempt = unlockAttempts.get(key)
- if (!attempt || attempt.resetAt <= now) {
- if (unlockAttempts.size >= UNLOCK_MAX_ENTRIES) {
- unlockAttempts.delete(unlockAttempts.keys().next().value as string)
- }
- 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,
@@ -59,14 +30,14 @@ export default eventHandler(async (event) => {
if (!album || album.isHidden || !album.passwordHash) {
throw createError({ statusCode: 404, statusMessage: 'Album not found' })
}
- assertUnlockRateLimit(event, albumId)
+ assertAlbumUnlockRateLimit(albumId, clientIp)
if (!(await verifyAlbumPassword(password, album.passwordHash))) {
throw createError({
statusCode: 401,
statusMessage: 'Incorrect album password',
})
}
- unlockAttempts.delete(`${albumId}:${clientIp}`)
+ clearAlbumUnlockClient(albumId, clientIp)
grantAlbumAccess(event, album.id, album.passwordHash)
return { ok: true }
})
diff --git a/server/utils/album-unlock-limit.ts b/server/utils/album-unlock-limit.ts
new file mode 100644
index 00000000..c0afb7b6
--- /dev/null
+++ b/server/utils/album-unlock-limit.ts
@@ -0,0 +1,182 @@
+import { isIP } from 'node:net'
+import { createError } from 'h3'
+
+const UNLOCK_WINDOW_MS = 60_000
+const UNLOCK_CLIENT_MAX_ATTEMPTS = 8
+const UNLOCK_ALBUM_MAX_ATTEMPTS = 32
+const UNLOCK_MAX_CLIENT_ENTRIES = 5_000
+
+type AttemptWindow = { count: number; resetAt: number }
+type WindowState = 'new' | 'open' | 'blocked'
+
+const clientAttempts = new Map<string, AttemptWindow>()
+const albumAttempts = new Map<number, AttemptWindow>()
+
+export function albumUnlockClientKey(ip: string): string {
+ const trimmed = ip.trim()
+ if (!trimmed || trimmed.toLowerCase() === 'unknown') return 'unknown'
+
+ let normalized = trimmed.toLowerCase()
+ if (normalized.startsWith('[') && normalized.includes(']')) {
+ normalized = normalized.slice(1, normalized.indexOf(']'))
+ }
+ const zoneAt = normalized.indexOf('%')
+ if (zoneAt !== -1) normalized = normalized.slice(0, zoneAt)
+ if (!normalized) return 'unknown'
+
+ const groups = expandIpv6(normalized)
+ if (groups && isIpv4Mapped(groups)) {
+ return `4:${formatIpv4(groups[6] ?? 0, groups[7] ?? 0)}`
+ }
+ if (isIP(normalized) === 4) return `4:${normalized}`
+ if (groups) return `6:${formatPrefix64(groups)}`
+ return `u:${normalized}`
+}
+
+function isIpv4Mapped(groups: number[]): boolean {
+ return (
+ groups[0] === 0 &&
+ groups[1] === 0 &&
+ groups[2] === 0 &&
+ groups[3] === 0 &&
+ groups[4] === 0 &&
+ groups[5] === 0xffff
+ )
+}
+
+function formatIpv4(hi: number, lo: number): string {
+ return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`
+}
+
+function formatPrefix64(groups: number[]): string {
+ return `${groups
+ .slice(0, 4)
+ .map((group) => group.toString(16))
+ .join(':')}::`
+}
+
+function expandIpv6(address: string): number[] | null {
+ const pure = address.includes('.') ? embedIpv4(address) : address
+ if (!pure || isIP(pure) !== 6) return null
+ return expandGroups(pure, 8)
+}
+
+function embedIpv4(address: string): string | null {
+ const lastColon = address.lastIndexOf(':')
+ if (lastColon === -1) return null
+ const v4 = address.slice(lastColon + 1)
+ if (isIP(v4) !== 4) return null
+ const octets = v4.split('.').map((part) => Number(part))
+ if (
+ octets.length !== 4 ||
+ octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)
+ ) {
+ return null
+ }
+ const hi = ((octets[0] ?? 0) << 8) | (octets[1] ?? 0)
+ const lo = ((octets[2] ?? 0) << 8) | (octets[3] ?? 0)
+ return `${address.slice(0, lastColon)}:${hi.toString(16)}:${lo.toString(16)}`
+}
+
+function expandGroups(address: string, expected: number): number[] | null {
+ const pieces = address.split('::')
+ if (pieces.length > 2) return null
+ const parseSide = (side: string): number[] | null => {
+ if (!side) return []
+ const parts = side.split(':')
+ if (parts.some((part) => !/^[0-9a-f]{1,4}$/.test(part))) return null
+ return parts.map((part) => Number.parseInt(part, 16))
+ }
+ const left = parseSide(pieces[0] ?? '')
+ if (!left) return null
+ if (pieces.length === 1) return left.length === expected ? left : null
+ const right = parseSide(pieces[1] ?? '')
+ if (!right) return null
+ const missing = expected - left.length - right.length
+ if (missing < 1) return null
+ return [...left, ...Array<number>(missing).fill(0), ...right]
+}
+
+function pruneWindows<K>(map: Map<K, AttemptWindow>, now: number) {
+ for (const [key, attempt] of map) {
+ if (attempt.resetAt <= now) map.delete(key)
+ }
+}
+
+function windowState(
+ attempt: AttemptWindow | undefined,
+ now: number,
+ max: number,
+): WindowState {
+ if (!attempt || attempt.resetAt <= now) return 'new'
+ if (attempt.count >= max) return 'blocked'
+ return 'open'
+}
+
+function rejectUnlockAttempt(): never {
+ throw createError({
+ statusCode: 429,
+ statusMessage: 'Too many unlock attempts',
+ })
+}
+
+function commitClient(
+ key: string,
+ state: Exclude<WindowState, 'blocked'>,
+ now: number,
+) {
+ if (state === 'new') {
+ if (
+ clientAttempts.size >= UNLOCK_MAX_CLIENT_ENTRIES &&
+ !clientAttempts.has(key)
+ ) {
+ const oldest = clientAttempts.keys().next().value
+ if (oldest !== undefined) clientAttempts.delete(oldest)
+ }
+ clientAttempts.set(key, { count: 1, resetAt: now + UNLOCK_WINDOW_MS })
+ return
+ }
+ const attempt = clientAttempts.get(key)
+ if (attempt) attempt.count += 1
+}
+
+function commitAlbum(
+ albumId: number,
+ state: Exclude<WindowState, 'blocked'>,
+ now: number,
+) {
+ if (state === 'new') {
+ albumAttempts.set(albumId, { count: 1, resetAt: now + UNLOCK_WINDOW_MS })
+ return
+ }
+ const attempt = albumAttempts.get(albumId)
+ if (attempt) attempt.count += 1
+}
+
+export function assertAlbumUnlockRateLimit(
+ albumId: number,
+ ip: string,
+ now = Date.now(),
+) {
+ pruneWindows(clientAttempts, now)
+ pruneWindows(albumAttempts, now)
+ const clientKey = `${albumId}:${albumUnlockClientKey(ip)}`
+ const client = windowState(
+ clientAttempts.get(clientKey),
+ now,
+ UNLOCK_CLIENT_MAX_ATTEMPTS,
+ )
+ if (client === 'blocked') rejectUnlockAttempt()
+ const album = windowState(
+ albumAttempts.get(albumId),
+ now,
+ UNLOCK_ALBUM_MAX_ATTEMPTS,
+ )
+ if (album === 'blocked') rejectUnlockAttempt()
+ commitClient(clientKey, client, now)
+ commitAlbum(albumId, album, now)
+}
+
+export function clearAlbumUnlockClient(albumId: number, ip: string) {
+ clientAttempts.delete(`${albumId}:${albumUnlockClientKey(ip)}`)
+}