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
refactor: extract core read use cases and serve local media directly
HoshinoSuzumiBote21f8b669259
diff --git a/Dockerfile b/Dockerfileindex d63de48f..3cec0f87 100644--- a/Dockerfile+++ b/Dockerfile@@ -8,6 +8,7 @@ WORKDIR /usr/src/appCOPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./COPY packages/webgl-image/package.json ./packages/webgl-image/COPY packages/contracts/package.json ./packages/contracts/+COPY packages/core/package.json ./packages/core/COPY packages/storage/package.json ./packages/storage/COPY packages/media/package.json ./packages/media/COPY packages/geocoding/package.json ./packages/geocoding/diff --git a/package.json b/package.jsonindex 4a13abad..4aa3b358 100644--- a/package.json+++ b/package.json@@ -33,7 +33,7 @@"docs:dev": "vitepress dev docs","docs:build": "vitepress build docs","docs:preview": "vitepress preview docs",- "check:packages": "node scripts/check-package-boundaries.mjs && pnpm --filter @chronoframe/contracts --filter @chronoframe/storage --filter @chronoframe/media --filter @chronoframe/geocoding type-check",+ "check:packages": "node scripts/check-package-boundaries.mjs && pnpm --filter @chronoframe/core --filter @chronoframe/contracts --filter @chronoframe/storage --filter @chronoframe/media --filter @chronoframe/geocoding type-check","test": "node --experimental-strip-types --test tests/*.test.ts"},"dependencies": {@@ -86,7 +86,9 @@"zod": "^4.6.6","@chronoframe/storage": "workspace:*","@chronoframe/media": "workspace:*",- "@chronoframe/geocoding": "workspace:*"+ "@chronoframe/geocoding": "workspace:*",+ "@chronoframe/core": "workspace:*",+ "h3": "^1.15.11"},"packageManager": "[email protected]","devDependencies": {diff --git a/packages/core/README.md b/packages/core/README.mdnew file mode 100644index 00000000..ed164621--- /dev/null+++ b/packages/core/README.md@@ -0,0 +1,15 @@+# @chronoframe/core++Transport-independent photo and album read use cases. The package depends only+on contracts; it has no Nuxt globals, database connections, filesystem or session+implementation. Repository methods are asynchronous and preserve query ordering.++The application injects a repository and trusted request access context. Hidden+album membership excludes photos from anonymous reads; public album listings do+not expose protected membership. Authorized protected album details replace raw+storage references with access-controlled media URLs. Password hashes remain in+internal access records and never appear in response resources.++This first P2 batch covers reads only. Writes, settings, Site scoping, database+migration, and job lifecycle remain in later batches. Do not use this interface+for multi-site data until a required Site context is introduced.diff --git a/packages/core/package.json b/packages/core/package.jsonnew file mode 100644index 00000000..971b7e3a--- /dev/null+++ b/packages/core/package.json@@ -0,0 +1,18 @@+{+ "name": "@chronoframe/core",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "type-check": "tsc --noEmit"+ },+ "dependencies": {+ "@chronoframe/contracts": "workspace:*"+ },+ "devDependencies": {+ "typescript": "^5.9.3"+ }+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsnew file mode 100644index 00000000..875c312a--- /dev/null+++ b/packages/core/src/index.ts@@ -0,0 +1,144 @@+import type { Album, Photo } from '@chronoframe/contracts/resources'++/** Internal access data stays separate from the public album resource. */+export interface AlbumReadRecord {+ resource: Album+ passwordHash: string | null+}++export interface PhotoMembership {+ photoId: string+ albumId: number+ hidden: boolean+ protected: boolean+}++/** Async boundary allows both embedded SQLite and future asynchronous adapters. */+export interface ResourceReadRepository {+ listPhotos(excludedIds?: string[]): Promise<Photo[]>+ listAlbums(): Promise<AlbumReadRecord[]>+ getAlbum(id: number): Promise<AlbumReadRecord | null>+ listAlbumPhotos(id: number): Promise<Photo[]>+ listAlbumPhotoIds(id: number): Promise<string[]>+ listMemberships(): Promise<PhotoMembership[]>+}++export interface ReadAccess {+ admin: boolean+ canAccess(album: {+ id: number+ isHidden: boolean+ passwordHash: string | null+ }): boolean+}++/** Transport-neutral failure translated to HTTP by the application adapter. */+export class ResourceReadError extends Error {+ readonly statusCode: 401 | 403 | 404+ constructor(statusCode: 401 | 403 | 404, message: string) {+ super(message)+ this.statusCode = statusCode+ this.name = 'ResourceReadError'+ }+}++/** Read use cases own visibility rules; repositories own query and ordering details. */+export function createResourceReader(repository: ResourceReadRepository) {+ return {+ async listPhotos(access: Pick<ReadAccess, 'admin'>): Promise<Photo[]> {+ if (!access.admin) throw new ResourceReadError(401, 'Unauthorized')+ return repository.listPhotos()+ },++ async listVisiblePhotos(): Promise<Photo[]> {+ const excluded = new Set(+ (await repository.listMemberships())+ .filter((m) => m.hidden || m.protected)+ .map((m) => m.photoId),+ )+ return repository.listPhotos([...excluded])+ },++ async listAlbums(+ access: Pick<ReadAccess, 'admin'>,+ ): Promise<Array<Album & { photoIds: string[] }>> {+ const memberships = await repository.listMemberships()+ const excluded = new Set(+ memberships+ .filter((m) => m.hidden || m.protected)+ .map((m) => m.photoId),+ )+ const albums = await repository.listAlbums()+ return Promise.all(+ albums+ .filter(({ resource }) => access.admin || !resource.isHidden)+ .map(async ({ resource, passwordHash }) => {+ const accessible =+ access.admin || (!resource.isHidden && !passwordHash)+ const photos = accessible+ ? await repository.listAlbumPhotoIds(resource.id)+ : []+ return {+ ...resource,+ coverPhotoId:+ access.admin ||+ (accessible && !excluded.has(resource.coverPhotoId || ''))+ ? resource.coverPhotoId+ : null,+ photoIds: photos.filter(+ (id) => access.admin || !excluded.has(id),+ ),+ }+ }),+ )+ },++ async getAlbum(+ id: number,+ access: ReadAccess,+ ): Promise<Album & { photos: Photo[] }> {+ const record = await repository.getAlbum(id)+ if (!record || (record.resource.isHidden && !access.admin))+ throw new ResourceReadError(404, 'Album not found')+ const { resource, passwordHash } = record+ if (!access.canAccess({ id, isHidden: resource.isHidden, passwordHash }))+ throw new ResourceReadError(403, 'Album password required')+ const excluded = new Set(+ access.admin+ ? []+ : (await repository.listMemberships())+ .filter(+ (m) =>+ m.hidden ||+ (!passwordHash && m.protected && m.albumId !== id),+ )+ .map((m) => m.photoId),+ )+ const photos = (await repository.listAlbumPhotos(id)).filter(+ (photo) => !excluded.has(photo.id),+ )+ return {+ ...resource,+ photos: passwordHash+ ? photos.map((photo) => {+ const {+ storageKey,+ thumbnailKey: _thumbnailKey,+ livePhotoVideoKey: _videoKey,+ ...safePhoto+ } = photo+ return {+ ...safePhoto,+ fileName: storageKey?.split(/[\\/]/).pop() || null,+ originalUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/original`,+ thumbnailUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/thumbnail`,+ livePhotoVideoUrl: photo.livePhotoVideoUrl+ ? `/image/__photo__/${encodeURIComponent(photo.id)}/live`+ : null,+ }+ })+ : photos,+ }+ },+ }+}diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonnew file mode 100644index 00000000..c5a02e36--- /dev/null+++ b/packages/core/tsconfig.json@@ -0,0 +1,15 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "types": [],+ "lib": ["ES2022"],+ "skipLibCheck": true,+ "noUncheckedIndexedAccess": true+ },+ "include": ["src/**/*.ts"]+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7c933c7f..71243ec3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -20,6 +20,9 @@ importers:'@chronoframe/contracts':specifier: workspace:*version: link:packages/contracts+ '@chronoframe/core':+ specifier: workspace:*+ version: link:packages/core'@chronoframe/geocoding':specifier: workspace:*version: link:packages/geocoding@@ -92,6 +95,9 @@ importers:file-type:specifier: ^22.1.1version: 22.1.1+ h3:+ specifier: ^1.15.11+ version: 1.15.11heic-convert:specifier: ^2.1.0version: 2.1.0@@ -245,6 +251,16 @@ importers:specifier: ^5.9.3version: 5.9.3+ packages/core:+ dependencies:+ '@chronoframe/contracts':+ specifier: workspace:*+ version: link:../contracts+ devDependencies:+ typescript:+ specifier: ^5.9.3+ version: 5.9.3+packages/geocoding:dependencies:'@chronoframe/contracts':diff --git a/scripts/check-package-boundaries.mjs b/scripts/check-package-boundaries.mjsindex 6f7e631c..2419d26b 100644--- a/scripts/check-package-boundaries.mjs+++ b/scripts/check-package-boundaries.mjs@@ -3,7 +3,7 @@ import path from 'node:path'import { builtinModules } from 'node:module'import ts from 'typescript'-const packageNames = ['contracts', 'storage', 'media', 'geocoding']+const packageNames = ['contracts', 'core', 'storage', 'media', 'geocoding']const builtins = new Set(builtinModules.map((name) => name.replace(/^node:/, '')),)@@ -72,7 +72,8 @@ for (const name of packageNames) {) {fail('application aliases and absolute imports are forbidden')} else if (builtins.has(value.replace(/^node:/, ''))) {- if (name === 'contracts') fail('contracts must be browser-compatible')+ if (name === 'contracts' || name === 'core')+ fail('contracts and core must be runtime-independent')} else {const dependency = value.startsWith('@')? value.split('/').slice(0, 2).join('/')diff --git a/server/api/albums/[albumId]/index.get.ts b/server/api/albums/[albumId]/index.get.tsindex c4225226..6015d276 100644--- a/server/api/albums/[albumId]/index.get.ts+++ b/server/api/albums/[albumId]/index.get.ts@@ -1,9 +1,9 @@-import { toAlbumDto, toPhotoDto } from '../../../utils/dto'-import { eq } from 'drizzle-orm'import z from 'zod'--import { fetchAlbumPhotos } from '../../../utils/album-visibility'import { albumAccess } from '../../../utils/album-access'+import {+ resourceReadResponse,+ useResourceReader,+} from '../../../utils/resource-reader'export default eventHandler(async (event) => {const { albumId } = await getValidatedRouterParams(@@ -12,76 +12,11 @@ export default eventHandler(async (event) => {albumId: z.string().regex(/^\d+$/)- .transform((val) => parseInt(val, 10)),+ .transform((value) => parseInt(value, 10)),}).parse,)-- const db = useDB()-- const album = db- .select()- .from(tables.albums)- .where(eq(tables.albums.id, albumId))- .get()-- if (!album) {- throw createError({- statusCode: 404,- statusMessage: 'Album not found',- })- }-- // 检查相册是否隐藏,如果隐藏则需要用户登录才能访问- const { admin: isLoggedIn, canAccess } = await albumAccess(event)-- if (album.isHidden && !isLoggedIn) {- throw createError({- statusCode: 404,- statusMessage: 'Album not found',- })- }-- 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).- const rows = await fetchAlbumPhotos(- db,- tables,- albumId,- isLoggedIn,- isLoggedIn || Boolean(album.passwordHash),+ const access = await albumAccess(event)+ return resourceReadResponse(() =>+ useResourceReader().getAlbum(albumId, access),)- const photoDtos = rows.map(toPhotoDto)- const photos = album.passwordHash- ? photoDtos.map((photo) => {- const fileName = photo.storageKey?.split(/[\\/]/).pop() || null- const {- storageKey: _storageKey,- thumbnailKey: _thumbnailKey,- livePhotoVideoKey: _livePhotoVideoKey,- ...safePhoto- } = photo- return {- ...safePhoto,- fileName,- originalUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/original`,- thumbnailUrl: `/image/__photo__/${encodeURIComponent(photo.id)}/thumbnail`,- livePhotoVideoUrl: photo.livePhotoVideoUrl- ? `/image/__photo__/${encodeURIComponent(photo.id)}/live`- : null,- }- })- : photoDtos-- return {- ...toAlbumDto(album),- photos,- }})diff --git a/server/api/albums/index.get.ts b/server/api/albums/index.get.tsindex 1472498b..5fb78a5f 100644--- a/server/api/albums/index.get.ts+++ b/server/api/albums/index.get.ts@@ -1,69 +1,6 @@-import { toAlbumDto } from '../../utils/dto'-import { asc, desc, or, isNotNull, eq } from 'drizzle-orm'import { albumAccess } from '../../utils/album-access'+import { useResourceReader } from '../../utils/resource-reader'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- .select()- .from(tables.albums)- .orderBy(asc(tables.albums.position), desc(tables.albums.createdAt))- const visibleAlbums = admin- ? albums- : albums.filter((album) => !album.isHidden)-- // 为每个相册获取照片 ID 列表(避免循环引用)- const albumsWithPhotoIds = await Promise.all(- visibleAlbums.map(async (album) => {- const accessible = admin || (!album.isHidden && !album.passwordHash)- const photoIds = await db- .select({- photoId: tables.albumPhotos.photoId,- position: tables.albumPhotos.position,- })- .from(tables.albumPhotos)- .where(eq(tables.albumPhotos.albumId, album.id))- .orderBy(tables.albumPhotos.position)-- return {- ...toAlbumDto(album),- coverPhotoId:- admin ||- (accessible && !restrictedPhotoIds.has(album.coverPhotoId || ''))- ? album.coverPhotoId- : null,- // 即使是空相册,也返回空数组而不是 undefined- photoIds: accessible- ? photoIds- .map((p) => p.photoId)- .filter((id) => !restrictedPhotoIds.has(id))- : [],- }- }),- )-- // Already ordered by position asc at the SQL layer- return albumsWithPhotoIds+ return useResourceReader().listAlbums(await albumAccess(event))})diff --git a/server/api/photos/index.get.ts b/server/api/photos/index.get.tsindex 910bb5b1..e218ad1b 100644--- a/server/api/photos/index.get.ts+++ b/server/api/photos/index.get.ts@@ -1,12 +1,6 @@-import { toPhotoDto } from '../../utils/dto'-import { desc } from 'drizzle-orm'+import { useResourceReader } from '../../utils/resource-reader'-export default eventHandler(async (_event) => {- await requireUserSession(_event)- return useDB()- .select()- .from(tables.photos)- .orderBy(desc(tables.photos.dateTaken))- .all()- .map(toPhotoDto)+export default eventHandler(async (event) => {+ await requireUserSession(event)+ return useResourceReader().listPhotos({ admin: true })})diff --git a/server/api/photos/visible.get.ts b/server/api/photos/visible.get.tsindex 21950f27..c337e86f 100644--- a/server/api/photos/visible.get.ts+++ b/server/api/photos/visible.get.ts@@ -1,42 +1,3 @@-import { toPhotoDto } from '../../utils/dto'-import { desc, notInArray, or, isNotNull } from 'drizzle-orm'+import { useResourceReader } from '../../utils/resource-reader'-export default eventHandler(async (_event) => {- const db = useDB()-- // 获取所有隐藏相册中的照片ID- const hiddenAlbumPhotos = 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()-- const hiddenPhotoIds = hiddenAlbumPhotos.map((row) => row.photoId)-- // 查询所有照片,排除隐藏相册中的照片- if (hiddenPhotoIds.length > 0) {- return db- .select()- .from(tables.photos)- .where(notInArray(tables.photos.id, hiddenPhotoIds))- .orderBy(desc(tables.photos.dateTaken))- .all()- .map(toPhotoDto)- }-- // 如果没有隐藏的照片,直接返回所有照片- return db- .select()- .from(tables.photos)- .orderBy(desc(tables.photos.dateTaken))- .all()- .map(toPhotoDto)-})+export default eventHandler(async () => useResourceReader().listVisiblePhotos())diff --git a/server/repositories/sqlite-resources.ts b/server/repositories/sqlite-resources.tsnew file mode 100644index 00000000..e721da20--- /dev/null+++ b/server/repositories/sqlite-resources.ts@@ -0,0 +1,86 @@+import { asc, desc, eq, getTableColumns, notInArray } from 'drizzle-orm'+import type { ResourceReadRepository } from '@chronoframe/core'+import { tables, type useDB } from '../utils/db.ts'+import { toAlbumDto, toPhotoDto } from '../utils/dto.ts'++/** Adapt existing SQLite queries without changing connections, schema or lifecycle. */+export function createSqliteResourceRepository(+ db: ReturnType<typeof useDB>,+): ResourceReadRepository {+ const albumRecord = (row: typeof tables.albums.$inferSelect) => ({+ resource: toAlbumDto(row),+ passwordHash: row.passwordHash,+ })+ return {+ async listPhotos(excludedIds = []) {+ return db+ .select()+ .from(tables.photos)+ .where(+ excludedIds.length+ ? notInArray(tables.photos.id, excludedIds)+ : undefined,+ )+ .orderBy(desc(tables.photos.dateTaken))+ .all()+ .map(toPhotoDto)+ },+ async listAlbums() {+ return db+ .select()+ .from(tables.albums)+ .orderBy(asc(tables.albums.position), desc(tables.albums.createdAt))+ .all()+ .map(albumRecord)+ },+ async getAlbum(id) {+ const row = db+ .select()+ .from(tables.albums)+ .where(eq(tables.albums.id, id))+ .get()+ return row ? albumRecord(row) : null+ },+ async listAlbumPhotoIds(id) {+ return db+ .select({ id: tables.albumPhotos.photoId })+ .from(tables.albumPhotos)+ .where(eq(tables.albumPhotos.albumId, id))+ .orderBy(asc(tables.albumPhotos.position))+ .all()+ .map((row) => row.id)+ },+ async listAlbumPhotos(id) {+ return db+ .select(getTableColumns(tables.photos))+ .from(tables.photos)+ .innerJoin(+ tables.albumPhotos,+ eq(tables.photos.id, tables.albumPhotos.photoId),+ )+ .where(eq(tables.albumPhotos.albumId, id))+ .orderBy(asc(tables.albumPhotos.position))+ .all()+ .map(toPhotoDto)+ },+ async listMemberships() {+ return db+ .select({+ photoId: tables.albumPhotos.photoId,+ albumId: tables.albums.id,+ hidden: tables.albums.isHidden,+ passwordHash: tables.albums.passwordHash,+ })+ .from(tables.albumPhotos)+ .innerJoin(+ tables.albums,+ eq(tables.albumPhotos.albumId, tables.albums.id),+ )+ .all()+ .map(({ passwordHash, ...membership }) => ({+ ...membership,+ protected: passwordHash !== null,+ }))+ },+ }+}diff --git a/server/routes/image/[...key].get.ts b/server/routes/image/[...key].get.tsindex e0c00446..bb6a8627 100644--- a/server/routes/image/[...key].get.ts+++ b/server/routes/image/[...key].get.ts@@ -1,3 +1,4 @@+import { serveLocalMedia } from '../../utils/local-media'import { eq } from 'drizzle-orm'import { Readable } from 'node:stream'import { assertPhotoAccess } from '../../utils/album-access'@@ -47,6 +48,22 @@ export default eventHandler(async (event) => {throw createError({ statusCode: 404, statusMessage: 'Photo not found' })}+ if (+ storageProvider.config?.provider === 'local' &&+ /^\/(?:storage|image)\//.test(targetUrl)+ ) {+ const localKey = decodeURIComponent(+ targetUrl.replace(/^\/(?:storage|image)\//, ''),+ )+ const targetRestricted = await assertPhotoAccess(event, localKey)+ return serveLocalMedia(+ event,+ storageProvider.config,+ localKey,+ restricted || targetRestricted,+ )+ }+const absoluteTarget = new URL(targetUrl, getRequestURL(event)).toString()const cookie = getHeader(event, 'cookie')const headers: Record<string, string> = {}diff --git a/server/routes/storage/[...path].ts b/server/routes/storage/[...path].tsindex 80c7abfa..14d104cd 100644--- a/server/routes/storage/[...path].ts+++ b/server/routes/storage/[...path].ts@@ -1,134 +1,13 @@-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 resolvable-const guessContentType = (filePath: string): string => {- const ext = (filePath.split('.').pop() || '').toLowerCase()- switch (ext) {- case 'jpg':- case 'jpeg':- return 'image/jpeg'- case 'png':- return 'image/png'- case 'webp':- return 'image/webp'- case 'gif':- return 'image/gif'- case 'bmp':- return 'image/bmp'- case 'tif':- case 'tiff':- return 'image/tiff'- case 'mp4':- return 'video/mp4'- case 'mov':- return 'video/quicktime'- case 'json':- return 'application/json'- default:- return 'application/octet-stream'- }-}+import { serveLocalMedia } from '../../utils/local-media'export default defineEventHandler(async (event) => {- const manager = getStorageManager()- const provider = manager.getProvider()-- if ((provider as any).config?.provider !== 'local') {- throw createError({ statusCode: 404, statusMessage: 'Not Found' })- }-- const p = getRouterParam(event, 'path') || ''- const relPathRaw = Array.isArray(p) ? p.join('/') : p- // handle CJK characters in URL- const decodedPath = decodeURIComponent(relPathRaw)- const relPath = decodedPath- .replace(/\\/g, '/')- .replace(/\/+/g, '/')- .replace(/^\/+/, '')-- if (decodedPath !== relPath) {- throw createError({ statusCode: 404, statusMessage: 'Not Found' })- }-- const restricted = await assertPhotoAccess(event, relPath)-- // 阻止路径穿越- if (relPath.includes('..') || relPath.split('/').includes('.')) {- throw createError({ statusCode: 400, statusMessage: 'Invalid path' })- }-- const basePath = (provider as any).config.basePath as string- const absolute = path.resolve(basePath, relPath)-- // 再次确认目标仍在 basePath 内- if (!absolute.startsWith(path.resolve(basePath) + path.sep)) {- throw createError({ statusCode: 400, statusMessage: 'Invalid path' })- }-- let stat: Awaited<ReturnType<typeof fs.stat>>- try {- stat = await fs.stat(absolute)- if (!stat.isFile()) {- throw createError({ statusCode: 404, statusMessage: 'Not Found' })- }-- // 设置缓存头- const etag = `W/"${stat.size}-${stat.mtimeMs}"`- setHeader(event, 'ETag', etag)- setHeader(event, 'Last-Modified', stat.mtime.toUTCString())- setHeader(- event,- 'Cache-Control',- restricted ? 'private, no-store' : 'public, max-age=31536000, immutable',- )-- // Content-Type- const contentType = guessContentType(absolute)- setHeader(event, 'Content-Type', contentType)-- // 条件请求- const inm = getHeader(event, 'if-none-match')- const ims = getHeader(event, 'if-modified-since')- if (- inm === etag ||- (ims && new Date(ims).getTime() >= stat.mtime.getTime())- ) {- event.node.res.statusCode = 304- return null- }-- // Range 支持- const range = getHeader(event, 'range')- if (range) {- const matches = /^bytes=(\d*)-(\d*)$/.exec(range)- if (matches) {- const start = matches[1] ? parseInt(matches[1], 10) : 0- const end = matches[2] ? parseInt(matches[2], 10) : stat.size - 1- if (start <= end && end < stat.size) {- event.node.res.statusCode = 206- setHeader(- event,- 'Content-Range',- `bytes ${start}-${end}/${stat.size}`,- )- setHeader(event, 'Accept-Ranges', 'bytes')- event.node.res.setHeader('Content-Length', String(end - start + 1))- const stream = createReadStream(absolute, { start, end })- return sendStream(event, stream)- }- }- }- } catch {+ const provider = getStorageManager().getProvider()+ if (provider.config?.provider !== 'local') {throw createError({ statusCode: 404, statusMessage: 'Not Found' })}-- // Full-file response: advertise the size so browsers can compute download- // progress (XHR `lengthComputable`). Without it Node falls back to chunked- // transfer encoding and the viewer's progress stays at 0% (#191).- setHeader(event, 'Accept-Ranges', 'bytes')- setHeader(event, 'Content-Length', stat.size)- const stream = createReadStream(absolute)- return sendStream(event, stream)+ const key = decodeURIComponent(getRouterParam(event, 'path') || '')+ const restricted = await assertPhotoAccess(event, key)+ return serveLocalMedia(event, provider.config, key, restricted)})diff --git a/server/routes/thumb/[...thumbnailUrl].get.ts b/server/routes/thumb/[...thumbnailUrl].get.tsindex 371ee8d6..36c83a6e 100644--- a/server/routes/thumb/[...thumbnailUrl].get.ts+++ b/server/routes/thumb/[...thumbnailUrl].get.ts@@ -1,3 +1,7 @@+import { readFile } from 'node:fs/promises'+import { resolveLocalMediaPath } from '../../utils/local-media'+import { eq } from 'drizzle-orm'+import { tables, useDB } from '../../utils/db'import sharp from 'sharp'import { assertPhotoAccess } from '../../utils/album-access'@@ -36,32 +40,42 @@ export default eventHandler(async (event) => {const restricted = await assertPhotoAccess(event, accessKey, !isAppPath)if (restricted) setHeader(event, 'Cache-Control', 'private, no-store')- const shouldForwardCookieToStorage =- storageProvider.config?.provider === 'local' &&- (url.startsWith('/storage/') || url.startsWith('/image/'))-- if (- storageProvider.config?.provider === 'local' &&- (url.startsWith('/storage/') || url.startsWith('/image/'))- ) {- const scheme = event.node.req.headers['x-forwarded-proto'] || 'http'- url = `${scheme}://${event.node.req.headers.host}${url}`- }-- const cookie = getHeader(event, 'cookie')- const photo = await fetch(- url,- cookie && shouldForwardCookieToStorage- ? { headers: { cookie } }- : undefined,- )- .then((res) => {- if (!res.ok) {+ let photo: Buffer+ if (storageProvider.config?.provider === 'local' && isAppPath) {+ let target = url+ if (protectedPhotoMatch) {+ const row = useDB()+ .select()+ .from(tables.photos)+ .where(eq(tables.photos.id, accessKey))+ .get()+ const kind = url.split('/').pop()+ const resourceUrl =+ kind === 'original'+ ? row?.originalUrl+ : kind === 'live'+ ? row?.livePhotoVideoUrl+ : row?.thumbnailUrl+ if (!resourceUrl)throw createError({ statusCode: 404, statusMessage: 'Photo not found' })- }- return res.arrayBuffer()- })- .then((buf) => Buffer.from(buf))+ target = resourceUrl+ }+ if (!/^\/(?:storage|image)\//.test(target))+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ const localKey = decodeURIComponent(+ target.replace(/^\/(?:storage|image)\//, ''),+ )+ const targetRestricted = await assertPhotoAccess(event, localKey)+ if (targetRestricted) setHeader(event, 'Cache-Control', 'private, no-store')+ photo = await readFile(+ await resolveLocalMediaPath(storageProvider.config, localKey),+ )+ } else {+ const response = await fetch(url)+ if (!response.ok)+ throw createError({ statusCode: 404, statusMessage: 'Photo not found' })+ photo = Buffer.from(await response.arrayBuffer())+ }const sharpInst = sharp(photo).rotate()return await sharpInst.jpeg({ quality: 85 }).toBuffer()diff --git a/server/utils/local-media.ts b/server/utils/local-media.tsnew file mode 100644index 00000000..cadeaa0a--- /dev/null+++ b/server/utils/local-media.ts@@ -0,0 +1,141 @@+import path from 'node:path'+import { createReadStream, promises as fs } from 'node:fs'+import { createError, getHeader, setHeader, sendStream, type H3Event } from 'h3'+import type { LocalStorageConfig } from '@chronoframe/contracts/storage'++const guessContentType = (filePath: string): string => {+ const ext = (filePath.split('.').pop() || '').toLowerCase()+ switch (ext) {+ case 'jpg':+ case 'jpeg':+ return 'image/jpeg'+ case 'png':+ return 'image/png'+ case 'webp':+ return 'image/webp'+ case 'gif':+ return 'image/gif'+ case 'bmp':+ return 'image/bmp'+ case 'tif':+ case 'tiff':+ return 'image/tiff'+ case 'mp4':+ return 'video/mp4'+ case 'mov':+ return 'video/quicktime'+ case 'json':+ return 'application/json'+ default:+ return 'application/octet-stream'+ }+}++/** Resolve a canonical key within the real storage root, rejecting symlink escapes. */+export async function resolveLocalMediaPath(+ config: LocalStorageConfig,+ key: string,+) {+ if (+ !key ||+ key.includes('\\') ||+ key.startsWith('/') ||+ key.split('/').some((part) => !part || part === '.' || part === '..')+ ) {+ throw createError({ statusCode: 400, statusMessage: 'Invalid path' })+ }+ try {+ const base = await fs.realpath(config.basePath)+ const absolute = await fs.realpath(path.resolve(base, key))+ const relative = path.relative(base, absolute)+ if (+ !relative ||+ relative.startsWith('..' + path.sep) ||+ relative === '..' ||+ path.isAbsolute(relative)+ ) {+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ }+ return absolute+ } catch {+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ }+}++/** Serve an already-authorized Local object without an HTTP request to this application. */+export async function serveLocalMedia(+ event: H3Event,+ config: LocalStorageConfig,+ key: string,+ restricted: boolean,+) {+ const absolute = await resolveLocalMediaPath(config, key)+ const stat = await fs.stat(absolute)+ if (!stat.isFile())+ throw createError({ statusCode: 404, statusMessage: 'Not Found' })+ const etag = `W/"${stat.size}-${stat.mtimeMs}"`+ setHeader(event, 'ETag', etag)+ setHeader(event, 'Last-Modified', stat.mtime.toUTCString())+ setHeader(+ event,+ 'Cache-Control',+ restricted ? 'private, no-store' : 'public, max-age=31536000, immutable',+ )+ setHeader(event, 'Content-Type', guessContentType(absolute))+ setHeader(event, 'Accept-Ranges', 'bytes')+ const inm = getHeader(event, 'if-none-match')+ const ims = getHeader(event, 'if-modified-since')+ if (+ (inm &&+ (inm === '*' ||+ inm+ .split(',')+ .map((value) => value.trim())+ .includes(etag))) ||+ (!inm &&+ ims &&+ new Date(ims).getTime() >= Math.floor(stat.mtimeMs / 1000) * 1000)+ ) {+ event.node.res.statusCode = 304+ return null+ }+ const range = getHeader(event, 'range')+ const ifRange = getHeader(event, 'if-range')+ // Weak validators cannot satisfy If-Range; a stale validator requests the full object.+ const allowRange =+ !ifRange ||+ (!ifRange.startsWith('W/') &&+ !ifRange.startsWith('"') &&+ new Date(ifRange).getTime() >= Math.floor(stat.mtimeMs / 1000) * 1000)+ if (range && allowRange) {+ const match = /^bytes=(\d*)-(\d*)$/.exec(range)+ if (match && (match[1] || match[2])) {+ const suffix = !match[1]+ const start = suffix+ ? Math.max(0, stat.size - Number(match[2]))+ : Number(match[1])+ const end =+ suffix || !match[2]+ ? stat.size - 1+ : Math.min(Number(match[2]), stat.size - 1)+ if (+ !Number.isSafeInteger(start) ||+ !Number.isSafeInteger(end) ||+ start > end ||+ start >= stat.size+ ) {+ setHeader(event, 'Content-Range', `bytes */${stat.size}`)+ throw createError({+ statusCode: 416,+ statusMessage: 'Range Not Satisfiable',+ })+ }+ event.node.res.statusCode = 206+ setHeader(event, 'Content-Range', `bytes ${start}-${end}/${stat.size}`)+ setHeader(event, 'Content-Length', end - start + 1)+ return sendStream(event, createReadStream(absolute, { start, end }))+ }+ }+ setHeader(event, 'Content-Length', stat.size)+ return sendStream(event, createReadStream(absolute))+}diff --git a/server/utils/resource-reader.ts b/server/utils/resource-reader.tsnew file mode 100644index 00000000..b8b5013a--- /dev/null+++ b/server/utils/resource-reader.ts@@ -0,0 +1,25 @@+import { createError } from 'h3'+import { createResourceReader, ResourceReadError } from '@chronoframe/core'+import { createSqliteResourceRepository } from '../repositories/sqlite-resources'+import { useDB } from './db'++/** Assemble the current self-hosted repository at the application boundary. */+export function useResourceReader() {+ return createResourceReader(createSqliteResourceRepository(useDB()))+}++/** Translate only known domain failures; preserve unexpected errors for server handling. */+export async function resourceReadResponse<T>(+ operation: () => Promise<T>,+): Promise<T> {+ try {+ return await operation()+ } catch (error) {+ if (error instanceof ResourceReadError)+ throw createError({+ statusCode: error.statusCode,+ statusMessage: error.message,+ })+ throw error+ }+}diff --git a/tests/core-read.test.ts b/tests/core-read.test.tsnew file mode 100644index 00000000..65148db2--- /dev/null+++ b/tests/core-read.test.ts@@ -0,0 +1,135 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import {+ createResourceReader,+ ResourceReadError,+ type ResourceReadRepository,+ type ReadAccess,+} from '@chronoframe/core'+import type { Album, Photo } from '@chronoframe/contracts/resources'+import { toPhotoDto } from '../server/utils/dto.ts'+import type { Photo as PhotoRow } from '../server/utils/db.ts'++const photos = ['public', 'shared-hidden', 'locked', 'shared-locked'].map(+ (id) =>+ toPhotoDto({+ id,+ storageKey: `${id}.jpg`,+ originalUrl: `/storage/${id}.jpg`,+ thumbnailUrl: `/storage/${id}.webp`,+ livePhotoVideoKey: `${id}.mp4`,+ livePhotoVideoUrl: `/storage/${id}.mp4`,+ } as PhotoRow),+)+const albums = [+ { id: 1, isHidden: false, hasPassword: false, coverPhotoId: 'shared-hidden' },+ { id: 2, isHidden: true, hasPassword: false, coverPhotoId: 'shared-hidden' },+ { id: 3, isHidden: false, hasPassword: true, coverPhotoId: 'locked' },+ { id: 4, isHidden: false, hasPassword: true, coverPhotoId: 'shared-locked' },+].map((resource) => ({+ resource: {+ title: 'Album',+ description: null,+ position: 0,+ createdAt: '2026-01-01',+ updatedAt: '2026-01-01',+ ...resource,+ } satisfies Album,+ passwordHash: resource.hasPassword ? 'private-hash' : null,+}))+const memberships = [+ { albumId: 1, photoId: 'public', hidden: false, protected: false },+ { albumId: 1, photoId: 'shared-hidden', hidden: false, protected: false },+ { albumId: 1, photoId: 'shared-locked', hidden: false, protected: false },+ { albumId: 2, photoId: 'shared-hidden', hidden: true, protected: false },+ { albumId: 3, photoId: 'shared-hidden', hidden: false, protected: true },+ { albumId: 3, photoId: 'locked', hidden: false, protected: true },+ { albumId: 3, photoId: 'shared-locked', hidden: false, protected: true },+ { albumId: 4, photoId: 'shared-locked', hidden: false, protected: true },+]+const repository: ResourceReadRepository = {+ async listPhotos(excludedIds = []) {+ return photos.filter((photo) => !excludedIds.includes(photo.id))+ },+ async listAlbums() {+ return albums+ },+ async getAlbum(id) {+ return albums.find((album) => album.resource.id === id) || null+ },+ async listMemberships() {+ return memberships+ },+ async listAlbumPhotoIds(id) {+ return memberships.filter((m) => m.albumId === id).map((m) => m.photoId)+ },+ async listAlbumPhotos(id) {+ return Promise.all(+ (await this.listAlbumPhotoIds(id)).map(async (id) =>+ photos.find((photo) => photo.id === id)!,+ ),+ )+ },+}+const reader = createResourceReader(repository)+const anonymous: ReadAccess = {+ admin: false,+ canAccess: (album) => !album.isHidden && !album.passwordHash,+}+const admin: ReadAccess = { admin: true, canAccess: () => true }+const unlocked: ReadAccess = {+ admin: false,+ canAccess: (album) => album.id === 3 || anonymous.canAccess(album),+}+const ids = (photos: Photo[]) => photos.map((photo) => photo.id)+const fails = (status: number) => (error: unknown) =>+ error instanceof ResourceReadError && error.statusCode === status++test('core read boundaries hide restricted membership from public feeds and listings', async () => {+ assert.deepEqual(ids(await reader.listVisiblePhotos()), ['public'])+ await assert.rejects(reader.listPhotos(anonymous), fails(401))+ assert.deepEqual(ids(await reader.listPhotos(admin)), ids(photos))+ const listed = await reader.listAlbums(anonymous)+ assert.deepEqual(+ listed.map((album) => album.id),+ [1, 3, 4],+ )+ assert.deepEqual(listed[0]!.photoIds, ['public'])+ assert.equal(listed[0]!.coverPhotoId, null)+ assert.equal(listed[1]!.coverPhotoId, null)+ assert.deepEqual(listed[1]!.photoIds, [])+ assert.equal('passwordHash' in listed[1]!, false)+ const all = await reader.listAlbums(admin)+ assert.equal(all.length, 4)+ assert.deepEqual(all[0]!.photoIds, [+ 'public',+ 'shared-hidden',+ 'shared-locked',+ ])+})++test('album read authorization preserves hidden, locked and shared-photo rules', async () => {+ await assert.rejects(reader.getAlbum(999, anonymous), fails(404))+ await assert.rejects(reader.getAlbum(2, anonymous), fails(404))+ await assert.rejects(reader.getAlbum(3, anonymous), fails(403))+ assert.deepEqual(ids((await reader.getAlbum(1, anonymous)).photos), [+ 'public',+ ])+ const result = await reader.getAlbum(3, unlocked)+ assert.deepEqual(ids(result.photos), ['locked', 'shared-locked'])+ assert.equal('passwordHash' in result, false)+ for (const photo of result.photos) {+ assert.equal('storageKey' in photo, false)+ assert.equal('thumbnailKey' in photo, false)+ assert.equal('livePhotoVideoKey' in photo, false)+ assert.equal(photo.originalUrl, `/image/__photo__/${photo.id}/original`)+ }+ assert.deepEqual(ids((await reader.getAlbum(2, admin)).photos), [+ 'shared-hidden',+ ])+ assert.deepEqual(ids((await reader.getAlbum(3, admin)).photos), [+ 'shared-hidden',+ 'locked',+ 'shared-locked',+ ])+})diff --git a/tests/local-media.test.ts b/tests/local-media.test.tsnew file mode 100644index 00000000..685b3f93--- /dev/null+++ b/tests/local-media.test.ts@@ -0,0 +1,111 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { mkdtemp, writeFile, rm, symlink } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { createServer } from 'node:http'+import { once } from 'node:events'+import { createApp, eventHandler, toNodeListener } from 'h3'+import {+ resolveLocalMediaPath,+ serveLocalMedia,+} from '../server/utils/local-media.ts'++test('Local media stays within its real storage root, including symlink targets', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'local-media-'))+ const outside = await mkdtemp(path.join(tmpdir(), 'outside-media-'))+ const config = { provider: 'local' as const, basePath: root }+ try {+ await writeFile(path.join(root, '照片.jpg'), 'photo')+ await writeFile(path.join(outside, 'secret.jpg'), 'secret')+ await symlink(outside, path.join(root, 'escape'))+ assert.equal(+ await resolveLocalMediaPath(config, '照片.jpg'),+ path.join(root, '照片.jpg'),+ )+ for (const key of [+ '../secret.jpg',+ '/secret.jpg',+ 'a/../secret.jpg',+ './照片.jpg',+ 'a\\secret.jpg',+ 'a//b',+ ]) {+ await assert.rejects(+ resolveLocalMediaPath(config, key),+ (error: any) => error.statusCode === 400,+ )+ }+ await assert.rejects(+ resolveLocalMediaPath(config, 'escape/secret.jpg'),+ (error: any) => error.statusCode === 404,+ )+ } finally {+ await rm(root, { recursive: true, force: true })+ await rm(outside, { recursive: true, force: true })+ }+})++test('authorized Local responses preserve ranges and private caching without trusting Host', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'local-response-'))+ await writeFile(path.join(root, 'video.mp4'), '0123456789')+ const app = createApp()+ app.use(+ eventHandler((event) =>+ serveLocalMedia(+ event,+ { provider: 'local', basePath: root },+ 'video.mp4',+ true,+ ),+ ),+ )+ const server = createServer(toNodeListener(app))+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/`+ try {+ const headers = {+ Host: 'unreachable.example:65530',+ 'x-forwarded-proto': 'https',+ }+ const full = await fetch(url, { headers })+ assert.equal(full.status, 200)+ assert.equal(await full.text(), '0123456789')+ assert.equal(full.headers.get('content-type'), 'video/mp4')+ assert.equal(full.headers.get('cache-control'), 'private, no-store')+ for (const [range, text, contentRange] of [+ ['bytes=2-4', '234', 'bytes 2-4/10'],+ ['bytes=-3', '789', 'bytes 7-9/10'],+ ['bytes=8-', '89', 'bytes 8-9/10'],+ ['bytes=8-50', '89', 'bytes 8-9/10'],+ ]) {+ const response = await fetch(url, {+ headers: { ...headers, range: range! },+ })+ assert.equal(response.status, 206)+ assert.equal(await response.text(), text)+ assert.equal(response.headers.get('content-range'), contentRange)+ }+ const unsatisfiable = await fetch(url, { headers: { range: 'bytes=99-' } })+ assert.equal(unsatisfiable.status, 416)+ assert.equal(unsatisfiable.headers.get('content-range'), 'bytes */10')+ const stale = await fetch(url, {+ headers: {+ range: 'bytes=1-2',+ 'if-range': 'Thu, 01 Jan 1970 00:00:00 GMT',+ },+ })+ assert.equal(stale.status, 200)+ await stale.arrayBuffer()+ const cached = await fetch(url, {+ headers: { 'if-none-match': full.headers.get('etag')! },+ })+ assert.equal(cached.status, 304)+ assert.equal(cached.headers.get('cache-control'), 'private, no-store')+ } finally {+ server.closeAllConnections()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ await rm(root, { recursive: true, force: true })+ }+})diff --git a/tests/sqlite-resource-read.test.ts b/tests/sqlite-resource-read.test.tsnew file mode 100644index 00000000..dfdb8293--- /dev/null+++ b/tests/sqlite-resource-read.test.ts@@ -0,0 +1,89 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import Database from 'better-sqlite3'+import { drizzle } from 'drizzle-orm/better-sqlite3'+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'+import { createResourceReader } from '@chronoframe/core'+import * as schema from '../server/database/schema.ts'+import { createSqliteResourceRepository } from '../server/repositories/sqlite-resources.ts'+import { fetchAlbumPhotos } from '../server/utils/album-visibility.ts'++test('SQLite reader preserves migrated data, ordering and legacy album visibility', async () => {+ const sqlite = new Database(':memory:')+ const db = drizzle(sqlite, { schema })+ migrate(db, { migrationsFolder: './server/database/migrations' })+ try {+ db.insert(schema.photos)+ .values([+ { id: 'old', dateTaken: '2020-01-01', title: null },+ { id: 'new', dateTaken: '2026-01-01' },+ { id: 'hidden' },+ { id: 'locked' },+ ])+ .run()+ db.insert(schema.albums)+ .values([+ { id: 1, title: 'Public', position: 2 },+ { id: 2, title: 'Hidden', isHidden: true, position: 1 },+ { id: 3, title: 'Locked', passwordHash: 'private-hash', position: 0 },+ ])+ .run()+ db.insert(schema.albumPhotos)+ .values([+ { albumId: 1, photoId: 'old', position: 30 },+ { albumId: 1, photoId: 'new', position: 10 },+ { albumId: 1, photoId: 'hidden', position: 5 },+ { albumId: 1, photoId: 'locked', position: 20 },+ { albumId: 2, photoId: 'hidden', position: 0 },+ { albumId: 3, photoId: 'locked', position: 0 },+ ])+ .run()+ const reader = createResourceReader(createSqliteResourceRepository(db))+ const anonymous = {+ admin: false,+ canAccess: (album: { isHidden: boolean; passwordHash: string | null }) =>+ !album.isHidden && !album.passwordHash,+ }+ assert.deepEqual(+ (await reader.listPhotos({ admin: true }))+ .slice(0, 2)+ .map((photo) => photo.id),+ ['new', 'old'],+ )+ assert.deepEqual(+ (await reader.listAlbums(anonymous)).map((album) => album.id),+ [3, 1],+ )+ assert.deepEqual(+ (await reader.listVisiblePhotos()).map((photo) => photo.id),+ ['new', 'old'],+ )+ const listed = await reader.listAlbums(anonymous)+ assert.deepEqual(listed[1]!.photoIds, ['new', 'old'])+ assert.deepEqual(listed[0]!.photoIds, [])+ for (const [id, admin, unlocked] of [+ [1, false, false],+ [1, true, false],+ [3, false, true],+ ] as const) {+ const access = { admin, canAccess: () => admin || unlocked || id === 1 }+ const actual = await reader.getAlbum(id, access)+ const expected = await fetchAlbumPhotos(+ db,+ schema,+ id,+ admin,+ admin || id === 3,+ )+ assert.deepEqual(+ actual.photos.map((photo) => photo.id),+ expected.map((photo) => photo.id),+ )+ assert.equal('passwordHash' in actual, false)+ }+ assert.equal((await reader.getAlbum(1, anonymous)).photos[1]!.title, null)+ assert.equal(db.select().from(schema.photos).all().length, 4)+ } finally {+ sqlite.close()+ }+})