Skip to content

Commit fb1a479

Browse files
perf(api): 1600px viewer previews; let the app embed its own media cross-origin
- /thumb?s=1600: a light on-screen rendition so the viewer doesn't pull a multi-MB original (cached and encrypted like the 320px tiles). - File and thumbnail responses send Cross-Origin-Resource-Policy: same-site instead of Helmet's same-origin, which blocked <video>/<img> whenever the web app and API sit on different origins of one site (api.example.com, or :3000/:4000 in dev). Other websites still can't embed private files. - CORS exposes Accept-Ranges/Content-Range so pdf.js can range-load PDFs.
1 parent 5bf7ef8 commit fb1a479

6 files changed

Lines changed: 51 additions & 22 deletions

File tree

‎apps/api/src/routes/files.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { parseOr400 } from '../lib/validate.js';
55
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
66
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
77
import { sendStoredFile, startsAtBeginning } from '../services/stream.js';
8-
import { sendThumbnail } from '../services/thumbs.js';
8+
import { parseThumbSize, sendThumbnail } from '../services/thumbs.js';
99
import { MEDIA_ROUTE } from '../lib/media-route.js';
1010
import { hardDeleteFile, trashFile } from '../services/trash.js';
1111
import { pruneVersions, snapshotVersion } from '../services/versioning.js';
@@ -118,14 +118,14 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
118118
return sendStoredFile(app.ctx, req, reply, file, { disposition: asInline ? 'inline' : 'attachment' });
119119
});
120120

121-
// GET /files/:id/thumb — small cached WebP for image tiles (415 when not an image).
121+
// GET /files/:id/thumb — small cached WebP for image tiles (?s=1600: on-screen preview) (415 when not an image).
122122
app.get('/:id/thumb', MEDIA_ROUTE, async (req, reply) => {
123123
const { id } = req.params as { id: string };
124124
const file = await prisma.fileObject.findFirst({
125125
where: { id, ownerId: req.user!.id, spaceId: null, deletedAt: null },
126126
});
127127
if (!file) return reply.code(404).send({ error: 'File not found' });
128-
return sendThumbnail(app.ctx, req, reply, file);
128+
return sendThumbnail(app.ctx, req, reply, file, parseThumbSize((req.query as { s?: string }).s));
129129
});
130130

131131
// PATCH /files/:id — rename and/or move a SERVER-mode file.

‎apps/api/src/routes/spaces.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import {
3939
} from '../services/spaces.js';
4040
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
4141
import { sendStoredFile, startsAtBeginning } from '../services/stream.js';
42-
import { sendThumbnail } from '../services/thumbs.js';
42+
import { parseThumbSize, sendThumbnail } from '../services/thumbs.js';
4343
import { MEDIA_ROUTE } from '../lib/media-route.js';
4444
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
4545

@@ -412,7 +412,7 @@ export const spaceRoutes: FastifyPluginAsync = async (app) => {
412412
return sendStoredFile(app.ctx, req, reply, file, { disposition: asInline ? 'inline' : 'attachment' });
413413
});
414414

415-
// GET /spaces/:id/files/:fileId/thumb — small cached WebP for image tiles (any member).
415+
// GET /spaces/:id/files/:fileId/thumb — small cached WebP for image tiles (?s=1600: on-screen preview) (any member).
416416
app.get('/:id/files/:fileId/thumb', MEDIA_ROUTE, async (req, reply) => {
417417
const acc = await access(req, reply);
418418
if (!acc) return;
@@ -421,7 +421,7 @@ export const spaceRoutes: FastifyPluginAsync = async (app) => {
421421
where: { id: fileId, spaceId: acc.space.id, deletedAt: null },
422422
});
423423
if (!file) return reply.code(404).send({ error: 'File not found' });
424-
return sendThumbnail(app.ctx, req, reply, file);
424+
return sendThumbnail(app.ctx, req, reply, file, parseThumbSize((req.query as { s?: string }).s));
425425
});
426426

427427
// PATCH /spaces/:id/files/:fileId — rename and/or move within the space (editor+).

‎apps/api/src/server.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,12 @@ export async function buildServer(ctx: AppContext): Promise<FastifyInstance> {
8282

8383
// Everything browser-facing is wrapped so CORS applies only here (not to WebDAV).
8484
await app.register(async (web) => {
85-
await web.register(cors, { origin: ctx.env.APP_URL, credentials: true });
85+
await web.register(cors, {
86+
origin: ctx.env.APP_URL,
87+
credentials: true,
88+
// Let the browser (pdf.js, media) see range headers when the API is on another origin.
89+
exposedHeaders: ['Accept-Ranges', 'Content-Range', 'Content-Length', 'ETag'],
90+
});
8691
// gzip/brotli for API responses (folder listings shrink 5-10x). File-serving routes opt out via
8792
// MEDIA_ROUTE (media is already compressed, and compression would break byte ranges).
8893
await web.register(compress, {

‎apps/api/src/services/stream.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,10 @@ export function sendStoredFile(
168168

169169
reply
170170
.header('Accept-Ranges', 'bytes')
171+
// Helmet's default (same-origin) would block <video>/<img> when the web app and the API live on
172+
// different origins of the same site (api.example.com, or :3000/:4000 in dev). same-site still
173+
// stops OTHER websites from embedding a user's private files.
174+
.header('Cross-Origin-Resource-Policy', 'same-site')
171175
.header('ETag', etag)
172176
.header('Cache-Control', opts.cacheControl ?? 'private, no-cache')
173177
.header('Content-Type', file.mimeType || 'application/octet-stream')

‎apps/api/src/services/thumbs.ts‎

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,11 @@ import type { AppContext } from '../context.js';
2020
import { decryptServerFile } from './download.js';
2121
import { fileEtag, type StreamableFile } from './stream.js';
2222

23-
export const THUMB_PX = 320;
24-
const QUALITY = 72;
23+
/** 320 px = grid tile; 1600 px = on-screen preview in the viewer (instead of a multi-MB original). */
24+
export const THUMB_SIZES = [320, 1600] as const;
25+
export type ThumbSize = (typeof THUMB_SIZES)[number];
26+
export const THUMB_PX: ThumbSize = 320;
27+
const QUALITY: Record<ThumbSize, number> = { 320: 72, 1600: 80 };
2528
/** Don't decode absurdly large sources just for a tile (falls back to the icon). */
2629
const MAX_SOURCE_BYTES = 64 * 1024 * 1024;
2730
const THUMB_MIME = /^image\/(jpeg|pjpeg|png|webp|gif|avif|tiff|heic|heif)$/i;
@@ -56,11 +59,15 @@ export function thumbCacheDir(ctx: AppContext): string {
5659
return resolve(ctx.env.THUMB_CACHE_PATH ?? join(dirname(resolve(ctx.env.STORAGE_PATH)), 'thumbs'));
5760
}
5861

59-
/** Cache file for one (file, content version). The version part changes when the bytes change. */
60-
function cachePath(ctx: AppContext, file: ThumbSource): string | null {
62+
export function parseThumbSize(v: unknown): ThumbSize {
63+
return Number(v) === 1600 ? 1600 : 320;
64+
}
65+
66+
/** Cache file for one (file, content version, size). The version part changes with the bytes. */
67+
function cachePath(ctx: AppContext, file: ThumbSource, px: ThumbSize): string | null {
6168
if (!/^[a-z0-9]+$/i.test(file.id)) return null; // ids are cuids; refuse anything path-like
6269
const ver = fileEtag(file).replace(/"/g, '');
63-
return join(thumbCacheDir(ctx), file.id.slice(0, 2), `${file.id}-${ver}`);
70+
return join(thumbCacheDir(ctx), file.id.slice(0, 2), `${file.id}-${ver}-${px}`);
6471
}
6572

6673
function encryptWith(dek: Buffer, data: Buffer): Buffer {
@@ -91,22 +98,26 @@ async function readSource(ctx: AppContext, file: ThumbSource): Promise<Buffer> {
9198
return Buffer.concat(parts);
9299
}
93100

94-
async function render(source: Buffer): Promise<Buffer> {
101+
async function render(source: Buffer, px: ThumbSize): Promise<Buffer> {
95102
return sharp(source, { failOn: 'none', limitInputPixels: 120_000_000, animated: false })
96103
.rotate() // honour EXIF orientation (phone photos)
97-
.resize(THUMB_PX, THUMB_PX, { fit: 'inside', withoutEnlargement: true })
98-
.webp({ quality: QUALITY, effort: 4 })
104+
.resize(px, px, { fit: 'inside', withoutEnlargement: true })
105+
.webp({ quality: QUALITY[px], effort: 4 })
99106
.toBuffer();
100107
}
101108

102109
/**
103110
* Return the WebP thumbnail for an image file, generating and caching it on first request.
104111
* `null` = not an image we can thumbnail (unsupported format, too big, corrupt): show the icon.
105112
*/
106-
export async function getThumbnail(ctx: AppContext, file: ThumbSource): Promise<Buffer | null> {
113+
export async function getThumbnail(
114+
ctx: AppContext,
115+
file: ThumbSource,
116+
px: ThumbSize = THUMB_PX,
117+
): Promise<Buffer | null> {
107118
if (file.encMode === 'ZK' || !isThumbable(file.name, file.mimeType)) return null;
108119
if (Number(file.sizeBytes) > MAX_SOURCE_BYTES || Number(file.sizeBytes) === 0) return null;
109-
const path = cachePath(ctx, file);
120+
const path = cachePath(ctx, file, px);
110121
if (!path) return null;
111122
const isPlain = file.encMode === 'PUBLIC';
112123
const dek = isPlain ? null : file.wrappedKey ? unwrapKey(file.wrappedKey, ctx.env.masterKey) : null;
@@ -127,7 +138,7 @@ export async function getThumbnail(ctx: AppContext, file: ThumbSource): Promise<
127138
const job = withSlot(async () => {
128139
let out: Buffer | null = null;
129140
try {
130-
out = await render(await readSource(ctx, file));
141+
out = await render(await readSource(ctx, file), px);
131142
} catch {
132143
out = null;
133144
}
@@ -166,7 +177,7 @@ export async function sweepThumbnails(ctx: AppContext): Promise<number> {
166177
continue;
167178
}
168179
const entries = names
169-
.map((n) => ({ n, m: /^([a-z0-9]+)-([A-Za-z0-9_-]+)$/i.exec(n) }))
180+
.map((n) => ({ n, m: /^([a-z0-9]+)-(.+)-(\d+)$/i.exec(n) }))
170181
.filter((e) => e.m || e.n.endsWith('.tmp'));
171182
const ids = [...new Set(entries.filter((e) => e.m).map((e) => e.m![1]!))];
172183
const rows = ids.length
@@ -177,7 +188,8 @@ export async function sweepThumbnails(ctx: AppContext): Promise<number> {
177188
: [];
178189
const current = new Map(rows.map((r) => [r.id, fileEtag(r).replace(/"/g, '')]));
179190
for (const e of entries) {
180-
const stale = !e.m || current.get(e.m[1]!) !== e.m[2];
191+
const stale =
192+
!e.m || current.get(e.m[1]!) !== e.m[2] || !THUMB_SIZES.includes(Number(e.m[3]) as ThumbSize);
181193
if (!stale) continue;
182194
await rm(join(root, shard, e.n), { force: true }).catch(() => undefined);
183195
removed += 1;
@@ -193,13 +205,15 @@ export async function sendThumbnail(
193205
req: import('fastify').FastifyRequest,
194206
reply: import('fastify').FastifyReply,
195207
file: ThumbSource,
208+
px: ThumbSize = THUMB_PX,
196209
) {
197-
const etag = `"t${THUMB_PX}-${fileEtag(file).replace(/"/g, '')}"`;
210+
const etag = `"t${px}-${fileEtag(file).replace(/"/g, '')}"`;
198211
const cache = 'private, max-age=31536000, immutable';
212+
reply.header('Cross-Origin-Resource-Policy', 'same-site'); // see sendStoredFile
199213
if (req.headers['if-none-match'] === etag) {
200214
return reply.code(304).header('ETag', etag).header('Cache-Control', cache).send();
201215
}
202-
const buf = await getThumbnail(ctx, file);
216+
const buf = await getThumbnail(ctx, file, px);
203217
if (!buf) {
204218
return reply.code(415).header('Cache-Control', 'private, max-age=600').send({ error: 'No thumbnail' });
205219
}

‎apps/api/test/integration.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1244,6 +1244,12 @@ runIf('API integration', () => {
12441244
});
12451245
expect(t3.statusCode).toBe(304);
12461246

1247+
// The on-screen preview size for the viewer.
1248+
const big = await app.inject({ method: 'GET', url: `/files/${id}/thumb?s=1600`, headers: { cookie: auth.cookie } });
1249+
const bm = await sharp(Buffer.from(big.rawPayload)).metadata();
1250+
expect([bm.width, bm.height]).toEqual([1600, 800]);
1251+
expect(big.headers.etag).not.toBe(t.headers.etag);
1252+
12471253
// Non-images get 415 so the UI shows the file-type icon.
12481254
const txt = await uploadFile(app, '/files', auth, 'notes.txt', Buffer.from('hello'));
12491255
const nt = await app.inject({ method: 'GET', url: `/files/${txt.json().file.id}/thumb`, headers: { cookie: auth.cookie } });

0 commit comments

Comments
 (0)