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
feat(albums): add password-protected albums
Timothy Yind94094adf209
diff --git a/app/pages/albums/[albumId].vue b/app/pages/albums/[albumId].vueindex 87ce4a97..d56ed0ad 100644--- a/app/pages/albums/[albumId].vue+++ b/app/pages/albums/[albumId].vue@@ -14,17 +14,44 @@ const {data: album,error,pending,+ refresh,} = await useFetch(() => `/api/albums/${albumId.value}`, {watch: [albumId],})-if (error.value) {+if (error.value && error.value.statusCode !== 403) {throw createError({statusCode: 404,statusMessage: $t('album.notFound'),})}+const albumPassword = ref('')+const isUnlocking = ref(false)+const unlockError = ref(false)+const unlockSucceeded = ref(false)+const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)')+const unlockAlbum = async () => {+ isUnlocking.value = true+ unlockError.value = false+ unlockSucceeded.value = false+ try {+ await $fetch(`/api/albums/${albumId.value}/unlock`, {+ method: 'POST', body: { password: albumPassword.value },+ })+ albumPassword.value = ''+ await refresh()+ unlockSucceeded.value = true+ if (!prefersReducedMotion.value) {+ await new Promise((resolve) => setTimeout(resolve, 220))+ }+ } catch {+ unlockError.value = true+ } finally {+ isUnlocking.value = false+ }+}+const albumData = computed(() => album.value)const albumStats = computed(() => {@@ -143,17 +170,16 @@ onUnmounted(() => {window.removeEventListener('scroll', handleScroll)})-onBeforeMount(() => {- useHead({- title: albumData.value ? albumData.value.title : $t('album.notFound'),- })+useHead({+ title: () => albumData.value?.title ||+ (error.value?.statusCode === 403 ? $t('album.passwordRequired') : $t('album.notFound')),})</script><template><div class="relative w-full"><div- v-if="pending"+ v-if="pending && !isUnlocking"class="flex flex-col items-center justify-center min-h-[50vh] gap-4"><UIcon@@ -165,6 +191,56 @@ onBeforeMount(() => {</p></div>+ <motion.div+ v-else-if="error?.statusCode === 403 || isUnlocking"+ class="relative mx-auto flex min-h-[65vh] max-w-md items-center justify-center overflow-hidden px-6 py-16"+ :initial="prefersReducedMotion ? false : { opacity: 0, y: 20, scale: 0.97 }"+ :animate="unlockSucceeded && !prefersReducedMotion+ ? { opacity: 0, y: -12, scale: 0.98 }+ : { opacity: 1, y: 0, scale: 1 }"+ :transition="{ duration: prefersReducedMotion ? 0 : 0.42, ease: 'easeOut' }"+ >+ <div class="relative w-full rounded-3xl border border-neutral-200/70 bg-white/80 p-8 shadow-xl shadow-neutral-900/5 backdrop-blur-xl dark:border-neutral-700/70 dark:bg-neutral-900/80 dark:shadow-black/20 sm:p-10">+ <motion.div+ class="mx-auto mb-4 flex size-16 items-center justify-center text-primary-600 dark:text-primary-400"+ :initial="prefersReducedMotion ? false : { opacity: 0, scale: 0.7, rotate: -12 }"+ :animate="{ opacity: 1, scale: 1, rotate: 0 }"+ :transition="{ delay: prefersReducedMotion ? 0 : 0.12, type: 'spring', stiffness: 260, damping: 20 }"+ >+ <Icon name="tabler:lock" class="size-10" />+ </motion.div>+ <motion.h1+ class="mb-5 text-center text-2xl font-semibold text-neutral-900 dark:text-white"+ :initial="prefersReducedMotion ? false : { opacity: 0, y: 10 }"+ :animate="{ opacity: 1, y: 0 }"+ :transition="{ delay: prefersReducedMotion ? 0 : 0.2, duration: prefersReducedMotion ? 0 : 0.35 }"+ >+ {{ $t('album.passwordRequired') }}+ </motion.h1>+ <motion.div+ :initial="prefersReducedMotion ? false : { opacity: 0, y: 12 }"+ :animate="{ opacity: 1, y: 0 }"+ :transition="{ delay: prefersReducedMotion ? 0 : 0.28, duration: prefersReducedMotion ? 0 : 0.35 }"+ >+ <form class="flex flex-col gap-3" @submit.prevent="unlockAlbum">+ <motion.div+ :animate="unlockError && !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>+ <UButton type="submit" block :loading="isUnlocking" :disabled="!albumPassword">+ {{ $t('album.unlock') }}+ </UButton>+ </form>+ </motion.div>+ </div>+ </motion.div><template v-else-if="albumData"><!-- Backdrop layer --><divdiff --git a/app/pages/albums/index.vue b/app/pages/albums/index.vueindex 2f4ec8ef..d7037a34 100644--- a/app/pages/albums/index.vue+++ b/app/pages/albums/index.vue@@ -3,6 +3,7 @@ import { motion } from 'motion-v'import type { Album } from '~~/server/utils/db'interface AlbumWithPhotos extends Album {photoIds?: string[]+ hasPassword?: boolean}const config = useRuntimeConfig()const { photos } = usePhotos()@@ -274,14 +275,14 @@ const hoveredAlbum = ref<number | null>(null)class="absolute inset-0 rounded-xl shadow-lg bg-linear-to-br from-neutral-100 to-neutral-50 dark:from-neutral-700 dark:to-neutral-800 flex flex-col items-center justify-center gap-3 border border-neutral-200 dark:border-neutral-600 group-hover:shadow-xl dark:group-hover:shadow-neutral-900/50 transition-shadow"><Icon- name="tabler:library-photo"+ :name="album.hasPassword ? 'tabler:lock' : 'tabler:library-photo'"class="size-10 text-neutral-400 dark:text-neutral-500"/><div class="text-center"><pclass="text-sm font-medium text-neutral-700 dark:text-neutral-300">- {{ $t('ui.album.noImage') }}+ {{ album.hasPassword ? $t('album.passwordRequired') : $t('ui.album.noImage') }}</p><!-- <p class="text-xs text-neutral-500 dark:text-neutral-400 mt-1">{{ $t('ui.album.emptyAlbumTip') }}diff --git a/app/pages/dashboard/albums.vue b/app/pages/dashboard/albums.vueindex 09190bde..af00cdd9 100644--- a/app/pages/dashboard/albums.vue+++ b/app/pages/dashboard/albums.vue@@ -11,6 +11,7 @@ useHead({})interface AlbumItem extends Album {+ hasPassword?: booleanphotoCount?: numberphotoIds?: string[]coverPhoto?: Photo | null@@ -20,6 +21,8 @@ interface AlbumFormState {title: stringdescription: stringisHidden: boolean+ password: string+ passwordEnabled: boolean}const albums = ref<AlbumItem[]>([])@@ -37,6 +40,8 @@ const formData = reactive<AlbumFormState>({title: '',description: '',isHidden: false,+ password: '',+ passwordEnabled: false,})const formRef = ref()@@ -71,6 +76,9 @@ const validateForm = (state: any): FormError[] => {message: $t('dashboard.albums.form.titleRequired'),})}+ if (state.passwordEnabled && !state.password && !currentAlbum.value?.hasPassword) {+ errors.push({ name: 'password', message: $t('dashboard.albums.form.passwordRequired') })+ }return errors}@@ -121,6 +129,8 @@ const openCreateSlideover = () => {formData.title = ''formData.description = ''formData.isHidden = false+ formData.password = ''+ formData.passwordEnabled = falseselectedPhotoIds.value = []coverPhotoId.value = ''formRef.value?.clear()@@ -134,6 +144,8 @@ const openEditSlideover = async (album: AlbumItem) => {formData.title = album.titleformData.description = album.description || ''formData.isHidden = album.isHidden || false+ formData.password = ''+ formData.passwordEnabled = Boolean(album.hasPassword)selectedPhotoIds.value = (albumDetail.photos || []).map((p: Photo) => p.id)coverPhotoId.value = album.coverPhotoId || ''formRef.value?.clear()@@ -164,6 +176,8 @@ const onFormSubmit = async (event: FormSubmitEvent<AlbumFormState>) => {coverPhotoId: coverPhotoId.value || undefined,photoIds: selectedPhotoIds.value,isHidden: event.data.isHidden,+ password: event.data.passwordEnabled+ ? (event.data.password || undefined) : '',},})@@ -182,6 +196,7 @@ const onFormSubmit = async (event: FormSubmitEvent<AlbumFormState>) => {coverPhotoId: coverPhotoId.value || undefined,photoIds: selectedPhotoIds.value,isHidden: event.data.isHidden,+ password: event.data.passwordEnabled ? event.data.password : undefined,},})@@ -741,6 +756,17 @@ const columns = computed<any[]>(() => [:label="$t('dashboard.albums.form.isHidden')"/></UFormField>++ <UFormField :label="$t('dashboard.albums.form.passwordProtection')">+ <UCheckbox v-model="formData.passwordEnabled"+ :label="$t('dashboard.albums.form.passwordProtection')" />+ </UFormField>+ <UFormField v-if="formData.passwordEnabled"+ :label="$t('dashboard.albums.form.password')" name="password"+ :hint="currentAlbum?.hasPassword ? $t('dashboard.albums.form.passwordKeepHint') : undefined">+ <UInput v-model="formData.password" type="password" autocomplete="new-password"+ class="w-full" :placeholder="$t('dashboard.albums.form.passwordPlaceholder')" />+ </UFormField></UForm><!-- 照片选择部分 -->diff --git a/i18n/locales/en.json b/i18n/locales/en.jsonindex a63273f9..01e131ef 100644--- a/i18n/locales/en.json+++ b/i18n/locales/en.json@@ -150,6 +150,10 @@}},"album": {+ "passwordRequired": "Password required",+ "passwordPlaceholder": "Enter album password",+ "incorrectPassword": "Incorrect password",+ "unlock": "Unlock album","notFound": "Album not found","noDateInfo": "No date info","noPhotosTip": "No photos in this album yet",@@ -864,6 +868,11 @@"clearAll": "Clear all","isHidden": "Hide album","isHiddenHint": "Photos in hidden albums are not shown on the home page",+ "passwordProtection": "Password protection",+ "password": "Password",+ "passwordPlaceholder": "Enter a password",+ "passwordKeepHint": "Leave blank to keep the current password",+ "passwordRequired": "Please enter a password","movePhotoUp": "Move photo up","movePhotoDown": "Move photo down","removePhoto": "Remove photo"diff --git a/i18n/locales/ja.json b/i18n/locales/ja.jsonindex d2888f78..f8a06ced 100644--- a/i18n/locales/ja.json+++ b/i18n/locales/ja.json@@ -150,6 +150,10 @@}},"album": {+ "passwordRequired": "Password required",+ "passwordPlaceholder": "Enter album password",+ "incorrectPassword": "Incorrect password",+ "unlock": "Unlock album","notFound": "アルバムが見つかりません","noDateInfo": "日付情報なし","noPhotosTip": "このアルバムにはまだ写真がありません",@@ -790,6 +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","movePhotoUp": "写真を上へ移動","movePhotoDown": "写真を下へ移動","removePhoto": "写真を選択から外す"diff --git a/i18n/locales/ru.json b/i18n/locales/ru.jsonindex 90267bad..3acdd23d 100644--- a/i18n/locales/ru.json+++ b/i18n/locales/ru.json@@ -150,6 +150,10 @@}},"album": {+ "passwordRequired": "Password required",+ "passwordPlaceholder": "Enter album password",+ "incorrectPassword": "Incorrect password",+ "unlock": "Unlock album","notFound": "Альбом не найден","noDateInfo": "Нет данных о дате","noPhotosTip": "В этом альбоме пока нет фотографий",@@ -863,6 +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","movePhotoUp": "Переместить фотографию вверх","movePhotoDown": "Переместить фотографию вниз","removePhoto": "Убрать фотографию"diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.jsonindex e8c4ee47..d37982be 100644--- a/i18n/locales/zh-Hans.json+++ b/i18n/locales/zh-Hans.json@@ -164,6 +164,10 @@}},"album": {+ "passwordRequired": "此相簿需要密码",+ "passwordPlaceholder": "输入相簿密码",+ "incorrectPassword": "密码错误",+ "unlock": "解锁相簿","notFound": "相簿未找到","noDateInfo": "无日期信息","noPhotosTip": "该相簿中还没有照片",@@ -864,6 +868,11 @@"clearAll": "全部清除","isHidden": "隐藏相簿","isHiddenHint": "隐藏的相簿中的照片不会在首页展示",+ "passwordProtection": "密码保护",+ "password": "密码",+ "passwordPlaceholder": "输入密码",+ "passwordKeepHint": "留空以保留当前密码",+ "passwordRequired": "请输入密码","movePhotoUp": "上移照片","movePhotoDown": "下移照片","removePhoto": "移除照片"diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.jsonindex a76d951e..f7693db0 100644--- a/i18n/locales/zh-Hant-HK.json+++ b/i18n/locales/zh-Hant-HK.json@@ -164,6 +164,10 @@}},"album": {+ "passwordRequired": "此相簿需要密碼",+ "passwordPlaceholder": "輸入相簿密碼",+ "incorrectPassword": "密碼錯誤",+ "unlock": "解鎖相簿","notFound": "搵唔到相簿","noDateInfo": "無日期資料","noPhotosTip": "呢個相簿仲冇相片",@@ -790,6 +794,11 @@"clearAll": "全部清除","isHidden": "隱藏相簿","isHiddenHint": "隱藏相簿中的照片不會在首頁顯示",+ "passwordProtection": "密碼保護",+ "password": "密碼",+ "passwordPlaceholder": "輸入密碼",+ "passwordKeepHint": "留空以保留目前密碼",+ "passwordRequired": "請輸入密碼","movePhotoUp": "上移相片","movePhotoDown": "下移相片","removePhoto": "移除相片"diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.jsonindex 5d9304bd..f028f1b5 100644--- a/i18n/locales/zh-Hant-TW.json+++ b/i18n/locales/zh-Hant-TW.json@@ -164,6 +164,10 @@}},"album": {+ "passwordRequired": "此相簿需要密碼",+ "passwordPlaceholder": "輸入相簿密碼",+ "incorrectPassword": "密碼錯誤",+ "unlock": "解鎖相簿","notFound": "找不到相簿","noDateInfo": "無日期資訊","noPhotosTip": "該相簿中還沒有相片",@@ -790,6 +794,11 @@"clearAll": "全部清除","isHidden": "隱藏相簿","isHiddenHint": "隱藏相簿中的照片不會在首頁顯示",+ "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.tsindex ade769ea..a513961f 100644--- a/server/api/albums/[albumId]/index.get.ts+++ b/server/api/albums/[albumId]/index.get.ts@@ -2,6 +2,7 @@ import { eq } from 'drizzle-orm'import z from 'zod'import { fetchAlbumPhotos } from '../../../utils/album-visibility'+import { albumAccess } from '../../../utils/album-access'export default eventHandler(async (event) => {const { albumId } = await getValidatedRouterParams(@@ -30,8 +31,7 @@ export default eventHandler(async (event) => {}// 检查相册是否隐藏,如果隐藏则需要用户登录才能访问- const session = await getUserSession(event)- const isLoggedIn = Boolean(session.user)+ const { admin: isLoggedIn, canAccess } = await albumAccess(event)if (album.isHidden && !isLoggedIn) {throw createError({@@ -40,6 +40,10 @@ export default eventHandler(async (event) => {})}+ if (!canAccess(album)) {+ 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).@@ -47,6 +51,8 @@ export default eventHandler(async (event) => {return {...album,+ passwordHash: undefined,+ hasPassword: Boolean(album.passwordHash),photos,}})diff --git a/server/api/albums/[albumId]/index.put.ts b/server/api/albums/[albumId]/index.put.tsindex fe3d590f..d0a40509 100644--- a/server/api/albums/[albumId]/index.put.ts+++ b/server/api/albums/[albumId]/index.put.ts@@ -1,4 +1,5 @@import { z } from 'zod'+import { hashAlbumPassword } from '../../../utils/album-access'export default eventHandler(async (event) => {await requireUserSession(event)@@ -21,6 +22,7 @@ export default eventHandler(async (event) => {coverPhotoId: z.string().optional(),photoIds: z.array(z.string()).optional(),isHidden: z.boolean().optional(),+ password: z.string().max(128).optional(),}).parse,)@@ -61,6 +63,9 @@ export default eventHandler(async (event) => {if (body.isHidden !== undefined) {updateData.isHidden = body.isHidden}+ if (body.password !== undefined) {+ updateData.passwordHash = body.password ? hashAlbumPassword(body.password) : null+ }tx.update(tables.albums).set(updateData)@@ -104,5 +109,5 @@ export default eventHandler(async (event) => {.get()})- return updatedAlbum+ return { ...updatedAlbum, passwordHash: undefined, hasPassword: Boolean(updatedAlbum?.passwordHash) }})diff --git a/server/api/albums/[albumId]/unlock.post.ts b/server/api/albums/[albumId]/unlock.post.tsnew file mode 100644index 00000000..00b32891--- /dev/null+++ b/server/api/albums/[albumId]/unlock.post.ts@@ -0,0 +1,20 @@+import { eq } from 'drizzle-orm'+import { z } from 'zod'+import { grantAlbumAccess, verifyAlbumPassword } from '../../../utils/album-access'++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 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)) {+ throw createError({ statusCode: 401, statusMessage: 'Incorrect album password' })+ }+ grantAlbumAccess(event, album.id, album.passwordHash)+ return { ok: true }+})diff --git a/server/api/albums/index.get.ts b/server/api/albums/index.get.tsindex ad857bd2..19784a7d 100644--- a/server/api/albums/index.get.ts+++ b/server/api/albums/index.get.ts@@ -1,7 +1,16 @@-import { asc, desc } from 'drizzle-orm'+import { asc, desc, or, isNotNull, eq } from 'drizzle-orm'+import { albumAccess } from '../../utils/album-access'-export default eventHandler(async (_event) => {+export default eventHandler(async (event) => {const db = useDB()+ const { admin } = await albumAccess(event)+ const restrictedPhotoIds = admin ? new Set<string>() : new Set(+ db.select({ photoId: tables.albumPhotos.photoId })+ .from(tables.albumPhotos)+ .innerJoin(tables.albums, eq(tables.albumPhotos.albumId, tables.albums.id))+ .where(or(eq(tables.albums.isHidden, true), isNotNull(tables.albums.passwordHash)))+ .all().map((row) => row.photoId),+ )// Fetch all albums ordered by position asc (createdAt desc as secondary sort)const albums = await db@@ -12,6 +21,7 @@ export default eventHandler(async (_event) => {// 为每个相册获取照片 ID 列表(避免循环引用)const albumsWithPhotoIds = await Promise.all(albums.map(async (album) => {+ const accessible = admin || (!album.isHidden && !album.passwordHash)const photoIds = await db.select({photoId: tables.albumPhotos.photoId,@@ -23,8 +33,13 @@ export default eventHandler(async (_event) => {return {...album,+ passwordHash: undefined,+ hasPassword: Boolean(album.passwordHash),+ coverPhotoId: admin || (accessible && !restrictedPhotoIds.has(album.coverPhotoId || ''))+ ? album.coverPhotoId : null,// 即使是空相册,也返回空数组而不是 undefined- photoIds: photoIds.length > 0 ? photoIds.map((p) => p.photoId) : [],+ photoIds: accessible ? photoIds.map((p) => p.photoId)+ .filter((id) => !restrictedPhotoIds.has(id)) : [],}}),)diff --git a/server/api/albums/index.post.ts b/server/api/albums/index.post.tsindex a7eac77d..8e1743df 100644--- a/server/api/albums/index.post.ts+++ b/server/api/albums/index.post.ts@@ -1,5 +1,6 @@import { min } from 'drizzle-orm'import z from 'zod'+import { hashAlbumPassword } from '../../utils/album-access'export default eventHandler(async (event) => {await requireUserSession(event)@@ -12,6 +13,7 @@ export default eventHandler(async (event) => {coverPhotoId: z.string().optional(),photoIds: z.array(z.string()).optional(),isHidden: z.boolean().optional(),+ password: z.string().min(1).max(128).optional(),}).parse,)@@ -33,6 +35,7 @@ export default eventHandler(async (event) => {description: body.description || null,coverPhotoId: body.coverPhotoId || null,isHidden: body.isHidden || false,+ passwordHash: body.password ? hashAlbumPassword(body.password) : null,position,}).returning()@@ -59,7 +62,7 @@ export default eventHandler(async (event) => {}}- return newAlbum+ return { ...newAlbum, passwordHash: undefined, hasPassword: Boolean(newAlbum.passwordHash) }})return albumdiff --git a/server/api/photos/[photoId]/albums.get.ts b/server/api/photos/[photoId]/albums.get.tsindex fb6b3448..d5add816 100644--- a/server/api/photos/[photoId]/albums.get.ts+++ b/server/api/photos/[photoId]/albums.get.ts@@ -1,5 +1,6 @@import { eq } from 'drizzle-orm'import z from 'zod'+import { albumAccess } from '../../../utils/album-access'export default eventHandler(async (event) => {const { photoId } = await getValidatedRouterParams(@@ -10,11 +11,14 @@ export default eventHandler(async (event) => {)const db = useDB()+ const { canAccess } = await albumAccess(event)// 获取包含该照片的所有相册const albums = await db.select({id: tables.albums.id,+ isHidden: tables.albums.isHidden,+ passwordHash: tables.albums.passwordHash,title: tables.albums.title,description: tables.albums.description,coverPhotoId: tables.albums.coverPhotoId,@@ -29,5 +33,7 @@ export default eventHandler(async (event) => {.where(eq(tables.albumPhotos.photoId, photoId)).all()- return albums+ return albums.filter(canAccess).map(({ passwordHash, ...album }) => ({+ ...album, hasPassword: Boolean(passwordHash),+ }))})diff --git a/server/api/photos/index.get.ts b/server/api/photos/index.get.tsindex f39cf077..16827cbe 100644--- a/server/api/photos/index.get.ts+++ b/server/api/photos/index.get.ts@@ -1,6 +1,7 @@import { desc } from 'drizzle-orm'export default eventHandler(async (_event) => {+ await requireUserSession(_event)return useDB().select().from(tables.photos)diff --git a/server/api/photos/visible.get.ts b/server/api/photos/visible.get.tsindex c267ab71..4cd041e0 100644--- a/server/api/photos/visible.get.ts+++ b/server/api/photos/visible.get.ts@@ -1,4 +1,4 @@-import { desc, notInArray } from 'drizzle-orm'+import { desc, notInArray, or, isNotNull } from 'drizzle-orm'export default eventHandler(async (_event) => {const db = useDB()@@ -10,7 +10,7 @@ export default eventHandler(async (_event) => {}).from(tables.albumPhotos).innerJoin(tables.albums, eq(tables.albumPhotos.albumId, tables.albums.id))- .where(eq(tables.albums.isHidden, true))+ .where(or(eq(tables.albums.isHidden, true), isNotNull(tables.albums.passwordHash))).all()const hiddenPhotoIds = hiddenAlbumPhotos.map((row) => row.photoId)diff --git a/server/database/migrations/0013_empty_vermin.sql b/server/database/migrations/0013_empty_vermin.sqlnew file mode 100644index 00000000..8d0cba5d--- /dev/null+++ b/server/database/migrations/0013_empty_vermin.sql@@ -0,0 +1 @@+ALTER TABLE `albums` ADD `password_hash` text;\ No newline at end of filediff --git a/server/database/migrations/meta/0013_snapshot.json b/server/database/migrations/meta/0013_snapshot.jsonnew file mode 100644index 00000000..f79a879f--- /dev/null+++ b/server/database/migrations/meta/0013_snapshot.json@@ -0,0 +1,803 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "58c6ce07-d486-4373-ba86-cfe4add7a94e",+ "prevId": "d76631f7-d170-408c-b85f-fb3517269420",+ "tables": {+ "album_photos": {+ "name": "album_photos",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "album_id": {+ "name": "album_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "photo_id": {+ "name": "photo_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 1000000+ },+ "added_at": {+ "name": "added_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "album_photos_album_id_albums_id_fk": {+ "name": "album_photos_album_id_albums_id_fk",+ "tableFrom": "album_photos",+ "tableTo": "albums",+ "columnsFrom": [+ "album_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "album_photos_photo_id_photos_id_fk": {+ "name": "album_photos_photo_id_photos_id_fk",+ "tableFrom": "album_photos",+ "tableTo": "photos",+ "columnsFrom": [+ "photo_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "albums": {+ "name": "albums",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cover_photo_id": {+ "name": "cover_photo_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_hidden": {+ "name": "is_hidden",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "password_hash": {+ "name": "password_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "position": {+ "name": "position",+ "type": "real",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "albums_cover_photo_id_photos_id_fk": {+ "name": "albums_cover_photo_id_photos_id_fk",+ "tableFrom": "albums",+ "tableTo": "photos",+ "columnsFrom": [+ "cover_photo_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "photo_reactions": {+ "name": "photo_reactions",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "photo_id": {+ "name": "photo_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "reaction_type": {+ "name": "reaction_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "fingerprint": {+ "name": "fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "photo_reactions_photo_id_photos_id_fk": {+ "name": "photo_reactions_photo_id_photos_id_fk",+ "tableFrom": "photo_reactions",+ "tableTo": "photos",+ "columnsFrom": [+ "photo_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "photos": {+ "name": "photos",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "width": {+ "name": "width",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "aspect_ratio": {+ "name": "aspect_ratio",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "date_taken": {+ "name": "date_taken",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "storage_key": {+ "name": "storage_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "thumbnail_key": {+ "name": "thumbnail_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "file_size": {+ "name": "file_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_modified": {+ "name": "last_modified",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "original_url": {+ "name": "original_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "thumbnail_url": {+ "name": "thumbnail_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "thumbnail_hash": {+ "name": "thumbnail_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tags": {+ "name": "tags",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "exif": {+ "name": "exif",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "latitude": {+ "name": "latitude",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "longitude": {+ "name": "longitude",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "country": {+ "name": "country",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "city": {+ "name": "city",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_live_photo": {+ "name": "is_live_photo",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "live_photo_video_url": {+ "name": "live_photo_video_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "live_photo_video_key": {+ "name": "live_photo_video_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "photos_id_unique": {+ "name": "photos_id_unique",+ "columns": [+ "id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "pipeline_queue": {+ "name": "pipeline_queue",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "payload": {+ "name": "payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{\"type\":\"photo\",\"storageKey\":\"\"}'"+ },+ "priority": {+ "name": "priority",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "max_attempts": {+ "name": "max_attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 3+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "status_stage": {+ "name": "status_stage",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "settings": {+ "name": "settings",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "namespace": {+ "name": "namespace",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'common'"+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "default_value": {+ "name": "default_value",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_public": {+ "name": "is_public",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_readonly": {+ "name": "is_readonly",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "is_secret": {+ "name": "is_secret",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "enum": {+ "name": "enum",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ },+ "updated_by": {+ "name": "updated_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_namespace_key": {+ "name": "idx_namespace_key",+ "columns": [+ "namespace",+ "key"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "settings_updated_by_users_id_fk": {+ "name": "settings_updated_by_users_id_fk",+ "tableFrom": "settings",+ "tableTo": "users",+ "columnsFrom": [+ "updated_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "settings_storage_providers": {+ "name": "settings_storage_providers",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(unixepoch())"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "avatar": {+ "name": "avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_admin": {+ "name": "is_admin",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "users_name_unique": {+ "name": "users_name_unique",+ "columns": [+ "name"+ ],+ "isUnique": true+ },+ "users_email_unique": {+ "name": "users_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/server/database/migrations/meta/_journal.json b/server/database/migrations/meta/_journal.jsonindex 782da678..c99f7e10 100644--- a/server/database/migrations/meta/_journal.json+++ b/server/database/migrations/meta/_journal.json@@ -92,6 +92,13 @@"when": 1789503318512,"tag": "0012_medical_raider","breakpoints": true+ },+ {+ "idx": 13,+ "version": "6",+ "when": 1790848090071,+ "tag": "0013_empty_vermin",+ "breakpoints": true}]-}+}\ No newline at end of filediff --git a/server/database/schema.ts b/server/database/schema.tsindex 2b155d0a..4d5cbca1 100644--- a/server/database/schema.ts+++ b/server/database/schema.ts@@ -140,6 +140,7 @@ export const albums = sqliteTable('albums', {onDelete: 'set null',}),isHidden: integer('is_hidden', { mode: 'boolean' }).default(false).notNull(),+ passwordHash: text('password_hash'),// Album sort position (ascending; smaller value appears first)position: real('position').notNull().default(0),createdAt: integer('created_at', { mode: 'timestamp' })diff --git a/server/routes/image/[...key].get.ts b/server/routes/image/[...key].get.tsindex 058588b5..5fa14193 100644--- a/server/routes/image/[...key].get.ts+++ b/server/routes/image/[...key].get.ts@@ -1,3 +1,5 @@+import { assertPhotoAccess } from '../../utils/album-access'+export default eventHandler(async (event) => {const { storageProvider } = useStorageProvider(event)const key = getRouterParam(event, 'key')@@ -5,6 +7,12 @@ export default eventHandler(async (event) => {if (!key) {throw createError({ statusCode: 400, statusMessage: 'Invalid key' })}+ if (decodeURIComponent(key).split(/[\\/]/).some((part) => part === '..' || part === '.')) {+ throw createError({ statusCode: 400, statusMessage: 'Invalid key' })+ }++ const restricted = await assertPhotoAccess(event, key)+ if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')const photo = await storageProvider.get(key)if (!photo) {diff --git a/server/routes/storage/[...path].ts b/server/routes/storage/[...path].tsindex e9509749..431f5bf1 100644--- a/server/routes/storage/[...path].ts+++ b/server/routes/storage/[...path].ts@@ -1,6 +1,7 @@import path from 'node:path'import { createReadStream, promises as fs } from 'node:fs'import { getStorageManager } from '../../plugins/3.storage'+import { assertPhotoAccess } from '../../utils/album-access'// lightweight: avoid TS type dep; fallback when not resolvableconst guessContentType = (filePath: string): string => {const ext = (filePath.split('.').pop() || '').toLowerCase()@@ -47,8 +48,10 @@ export default defineEventHandler(async (event) => {.replace(/\/+/g, '/').replace(/^\/+/, '')+ const restricted = await assertPhotoAccess(event, relPath)+// 阻止路径穿越- if (relPath.includes('..')) {+ if (relPath.includes('..') || relPath.split('/').includes('.')) {throw createError({ statusCode: 400, statusMessage: 'Invalid path' })}@@ -71,7 +74,8 @@ 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', '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 8a8c828f..3b2f964d 100644--- a/server/routes/thumb/[...thumbnailUrl].get.ts+++ b/server/routes/thumb/[...thumbnailUrl].get.ts@@ -1,4 +1,5 @@import sharp from 'sharp'+import { assertPhotoAccess } from '../../utils/album-access'export default eventHandler(async (event) => {const { storageProvider } = useStorageProvider(event)@@ -13,6 +14,9 @@ export default eventHandler(async (event) => {}url = decodeURIComponent(url)+ const restricted = await assertPhotoAccess(event, url.startsWith('/storage/') || url.startsWith('/image/')+ ? url.replace(/^\/(?:storage|image)\//, '') : url)+ if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')if (storageProvider.config?.provider === 'local' &&diff --git a/server/utils/album-access.ts b/server/utils/album-access.tsnew file mode 100644index 00000000..e00b4bb3--- /dev/null+++ b/server/utils/album-access.ts@@ -0,0 +1,92 @@+import { createHash, createHmac, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto'+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 passwordVersion = (hash: string) =>+ createHash('sha256').update(hash).digest('hex').slice(0, 16)++export function hashAlbumPassword(password: string): string {+ const salt = randomBytes(16).toString('hex')+ return `${salt}:${scryptSync(password, salt, 64).toString('hex')}`+}++export function verifyAlbumPassword(password: string, stored: string): boolean {+ const [salt, expected] = stored.split(':')+ if (!salt || !expected || !/^[a-f0-9]{128}$/.test(expected)) return false+ const actual = scryptSync(password, salt, 64)+ return timingSafeEqual(actual, Buffer.from(expected, 'hex'))+}++function signature(payload: string): string {+ return createHmac('sha256', process.env.NUXT_SESSION_PASSWORD || '')+ .update(payload).digest('base64url')+}++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 actual = signature(payload)+ if (mac.length !== actual.length ||+ !timingSafeEqual(Buffer.from(mac), Buffer.from(actual))) return []+ try {+ 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')+ } catch {+ return []+ }+}++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' ||+ getRequestURL(event).protocol === 'https:'+ setCookie(event, cookieName, `${payload}.${signature(payload)}`, {+ httpOnly: true, sameSite: 'lax', secure, path: '/',+ })+}++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!))))+ return { admin, canAccess }+}++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.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 })+ .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' })+ }+ return restricted+}diff --git a/server/utils/album-visibility.ts b/server/utils/album-visibility.tsindex 208dff3a..a41b2029 100644--- a/server/utils/album-visibility.ts+++ b/server/utils/album-visibility.ts@@ -1,4 +1,4 @@-import { asc, eq, getTableColumns } from 'drizzle-orm'+import { asc, eq, getTableColumns, or, isNotNull, ne, and } from 'drizzle-orm'import type { useDB } from './db'import type * as schema from '../database/schema'@@ -43,7 +43,8 @@ export async function fetchAlbumPhotos(tables.albums,eq(tables.albumPhotos.albumId, tables.albums.id),)- .where(eq(tables.albums.isHidden, true))+ .where(or(eq(tables.albums.isHidden, true), and(+ isNotNull(tables.albums.passwordHash), ne(tables.albums.id, albumId)))).all()).map((r: { photoId: string }) => r.photoId)