Package a self-contained macOS app and harden serving
- Add macos/build.mjs: stages a universal .app outside the checkout, bundles and checksums Node, installs production deps per architecture, compiles the launcher shim, signs ad-hoc or with a Developer ID, and writes a zip and dmg with an optional notarization path. - Serve precompressed brotli/gzip assets and split admin panels and the public pages out of the main bundle. - Support HTTP range requests, and fix upload and quota accounting, gallery download counts and unreadable-file handling. - Add server HTTP integration tests, a Gitea CI workflow, a catalog backup script and a crash screen for the UI.
This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Server HTTP integration tests.
|
||||
*
|
||||
* The real server is started once against a throwaway data directory, so these
|
||||
* exercise the routing, session, ownership, quota, gallery and file-serving
|
||||
* layers that the pure-logic suite cannot reach. Nothing touches a real catalog.
|
||||
*/
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const PORT = 18_000 + Math.floor(Math.random() * 20_000);
|
||||
const BASE = `http://127.0.0.1:${PORT}`;
|
||||
|
||||
let child = null;
|
||||
let dataDir = '';
|
||||
let output = '';
|
||||
|
||||
/** One browser: keeps the cookies the server sets for this session. */
|
||||
class Client {
|
||||
cookies = new Map();
|
||||
|
||||
async call(pathname, init = {}) {
|
||||
const headers = { ...(init.headers ?? {}) };
|
||||
if (this.cookies.size) {
|
||||
headers.cookie = [...this.cookies].map(([key, value]) => `${key}=${value}`).join('; ');
|
||||
}
|
||||
const res = await fetch(BASE + pathname, { ...init, headers });
|
||||
for (const raw of res.headers.getSetCookie?.() ?? []) {
|
||||
const [pair] = raw.split(';');
|
||||
const at = pair.indexOf('=');
|
||||
const key = pair.slice(0, at).trim();
|
||||
const value = pair.slice(at + 1).trim();
|
||||
if (!value || /Max-Age=0/i.test(raw)) this.cookies.delete(key);
|
||||
else this.cookies.set(key, value);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
async json(pathname, init = {}) {
|
||||
const res = await this.call(pathname, init);
|
||||
const text = await res.text();
|
||||
let body = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = { raw: text };
|
||||
}
|
||||
return { res, body };
|
||||
}
|
||||
}
|
||||
|
||||
const postJson = (payload) => ({
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const putJson = (payload) => ({ ...postJson(payload), method: 'PUT' });
|
||||
|
||||
const admin = new Client();
|
||||
const member = new Client();
|
||||
const guest = new Client();
|
||||
|
||||
const eventId = 'evt-http-test';
|
||||
const photoId = 'ph-http-test';
|
||||
const photoBytes = Buffer.alloc(8 * 1024, 7);
|
||||
|
||||
function photoRecord(extra = {}) {
|
||||
return {
|
||||
id: photoId,
|
||||
eventId,
|
||||
name: 'audit.jpg',
|
||||
width: 100,
|
||||
height: 80,
|
||||
size: 2,
|
||||
mime: 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
edits: {},
|
||||
history: [],
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
keywords: [],
|
||||
thumb: '',
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
dataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'luminary-http-'));
|
||||
child = spawn(process.execPath, ['server/index.mjs'], {
|
||||
cwd: ROOT,
|
||||
env: {
|
||||
...process.env,
|
||||
LUMINARY_DATA: dataDir,
|
||||
PORT: String(PORT),
|
||||
HOST: '127.0.0.1',
|
||||
LUMINARY_LOCAL: '',
|
||||
LUMINARY_INVITE: '',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
child.stdout.on('data', (chunk) => {
|
||||
output += chunk;
|
||||
});
|
||||
child.stderr.on('data', (chunk) => {
|
||||
output += chunk;
|
||||
});
|
||||
|
||||
const deadline = Date.now() + 30_000;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const res = await fetch(`${BASE}/api/health`);
|
||||
if (res.ok) return;
|
||||
} catch {
|
||||
/* not listening yet */
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
}
|
||||
throw new Error(`server did not start\n${output}`);
|
||||
}, 45_000);
|
||||
|
||||
afterAll(async () => {
|
||||
child?.kill('SIGKILL');
|
||||
if (dataDir) await fsp.rm(dataDir, { recursive: true, force: true }).catch(() => undefined);
|
||||
});
|
||||
|
||||
describe('auth and ownership', () => {
|
||||
test('the first account is the admin and gets a session', async () => {
|
||||
const { res, body } = await admin.json(
|
||||
'/api/auth/register',
|
||||
postJson({ email: 'Admin@Example.com', password: 'password123', name: 'Admin' }),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
expect(body.user.role).toBe('admin');
|
||||
|
||||
const me = await admin.json('/api/auth/me');
|
||||
expect(me.res.status).toBe(200);
|
||||
expect(me.body.user.email).toBe('admin@example.com');
|
||||
});
|
||||
|
||||
test('registration is closed once an account exists', async () => {
|
||||
const { res } = await guest.json(
|
||||
'/api/auth/register',
|
||||
postJson({ email: 'walk-in@example.com', password: 'password123' }),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
test('an invited member cannot reach another owner\'s photo', async () => {
|
||||
const invite = await admin.json(
|
||||
'/api/admin/invites',
|
||||
postJson({ email: 'member@example.com', role: 'member' }),
|
||||
);
|
||||
expect(invite.res.status).toBe(201);
|
||||
|
||||
const registered = await member.json(
|
||||
'/api/auth/register',
|
||||
postJson({
|
||||
email: 'member@example.com',
|
||||
password: 'password123',
|
||||
inviteToken: invite.body.invite.token,
|
||||
}),
|
||||
);
|
||||
expect(registered.res.status).toBe(201);
|
||||
expect(registered.body.user.role).toBe('member');
|
||||
|
||||
const upload = await admin.call(`/api/photos/${photoId}/original?name=audit.jpg&mime=image/jpeg`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
body: photoBytes,
|
||||
});
|
||||
expect(upload.status).toBe(201);
|
||||
});
|
||||
|
||||
test('a saved record cannot shrink its measured size', async () => {
|
||||
const saved = await admin.json(`/api/photos/${photoId}`, putJson(photoRecord()));
|
||||
expect(saved.res.status).toBe(200);
|
||||
|
||||
const quota = await admin.json('/api/quota');
|
||||
expect(quota.res.status).toBe(200);
|
||||
expect(quota.body.used).toBe(photoBytes.length);
|
||||
});
|
||||
|
||||
test('a member cannot read or overwrite the admin\'s photo', async () => {
|
||||
const preview = await member.call(`/api/photos/${photoId}/preview`);
|
||||
expect(preview.status).toBe(404);
|
||||
|
||||
const overwrite = await member.call(`/api/photos/${photoId}`, putJson({ ...photoRecord(), name: 'stolen.jpg' }));
|
||||
expect(overwrite.status).toBe(404);
|
||||
});
|
||||
|
||||
test('a member cannot park a photo inside another owner\'s event', async () => {
|
||||
const event = await admin.call(`/api/events/${eventId}`, putJson({ id: eventId, name: 'Audit shoot', createdAt: Date.now() }));
|
||||
expect(event.status).toBe(200);
|
||||
|
||||
const sneaky = await member.call('/api/photos/ph-member-1', putJson(photoRecord({ id: 'ph-member-1' })));
|
||||
expect(sneaky.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('file serving', () => {
|
||||
test('byte ranges resume a download', async () => {
|
||||
const res = await admin.call(`/api/photos/${photoId}/original`, {
|
||||
headers: { range: 'bytes=100-199' },
|
||||
});
|
||||
expect(res.status).toBe(206);
|
||||
expect(res.headers.get('content-range')).toBe(`bytes 100-199/${photoBytes.length}`);
|
||||
expect(res.headers.get('accept-ranges')).toBe('bytes');
|
||||
const body = Buffer.from(await res.arrayBuffer());
|
||||
expect(body.equals(photoBytes.subarray(100, 200))).toBe(true);
|
||||
});
|
||||
|
||||
test('an impossible range is refused without touching other requests', async () => {
|
||||
const res = await admin.call(`/api/photos/${photoId}/original`, {
|
||||
headers: { range: `bytes=${photoBytes.length + 10}-` },
|
||||
});
|
||||
expect(res.status).toBe(416);
|
||||
const health = await fetch(`${BASE}/api/health`);
|
||||
expect(health.status).toBe(200);
|
||||
});
|
||||
|
||||
test('an unreadable original answers 404 and leaves the server running', async () => {
|
||||
if (process.getuid?.() === 0) return; // root ignores file permissions
|
||||
const original = path.join(dataDir, 'originals', `${photoId}.jpg`);
|
||||
fs.chmodSync(original, 0o000);
|
||||
try {
|
||||
const res = await admin.call(`/api/photos/${photoId}/original`);
|
||||
expect(res.status).toBe(404);
|
||||
const health = await fetch(`${BASE}/api/health`);
|
||||
expect(health.status).toBe(200);
|
||||
} finally {
|
||||
fs.chmodSync(original, 0o644);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('proofing gallery', () => {
|
||||
test('downloads count against the cap only when a file is sent', async () => {
|
||||
const share = await admin.json(`/api/events/${eventId}/share`, { method: 'POST' });
|
||||
expect(share.res.status).toBe(200);
|
||||
const token = share.body.token;
|
||||
|
||||
const settings = await admin.call(
|
||||
`/api/events/${eventId}/share/settings`,
|
||||
putJson({ allowDownloads: true, downloadCap: 2 }),
|
||||
);
|
||||
expect(settings.status).toBe(200);
|
||||
|
||||
const pick = await guest.call(
|
||||
`/api/galleries/${token}/picks`,
|
||||
postJson({ photoId, clientId: 'client-1', clientName: 'Client', picked: true }),
|
||||
);
|
||||
expect(pick.status).toBe(200);
|
||||
|
||||
// First download uses one of the two allowed downloads.
|
||||
const first = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(first.status).toBe(200);
|
||||
await first.arrayBuffer();
|
||||
|
||||
// A missing render must not consume the remaining allowance.
|
||||
const original = path.join(dataDir, 'originals', `${photoId}.jpg`);
|
||||
// Outside originals/: any `<id>.*` name inside that folder is still an original.
|
||||
const parked = path.join(dataDir, `${photoId}.jpg.parked`);
|
||||
await fsp.rename(original, parked);
|
||||
const missing = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(missing.status).toBe(404);
|
||||
await fsp.rename(parked, original);
|
||||
|
||||
const second = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(second.status).toBe(200);
|
||||
await second.arrayBuffer();
|
||||
|
||||
const third = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(third.status).toBe(403);
|
||||
});
|
||||
});
|
||||
+154
-23
@@ -58,6 +58,7 @@ import {
|
||||
import {
|
||||
defaultRoot,
|
||||
findOriginal,
|
||||
findOriginals,
|
||||
findPreview,
|
||||
findPreview16,
|
||||
findProof,
|
||||
@@ -531,7 +532,13 @@ function match(pathname, pattern) {
|
||||
const params = {};
|
||||
for (let i = 0; i < p.length; i++) {
|
||||
if (p[i].startsWith(':')) {
|
||||
params[p[i].slice(1)] = decodeURIComponent(a[i]);
|
||||
// A malformed escape such as %E0%A4%A must not throw URIError out of the
|
||||
// router; it simply cannot match any record.
|
||||
try {
|
||||
params[p[i].slice(1)] = decodeURIComponent(a[i]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} else if (p[i] !== a[i]) {
|
||||
return null;
|
||||
}
|
||||
@@ -539,6 +546,40 @@ function match(pathname, pattern) {
|
||||
return params;
|
||||
}
|
||||
|
||||
/** `bytes=start-end` / `bytes=start-` / `bytes=-suffix`, first range only. */
|
||||
function parseRange(header, size) {
|
||||
if (typeof header !== 'string' || !header.startsWith('bytes=')) return null;
|
||||
const spec = header.slice(6).split(',')[0].trim();
|
||||
const match = /^(\d*)-(\d*)$/.exec(spec);
|
||||
if (!match) return null;
|
||||
const [, rawStart, rawEnd] = match;
|
||||
if (!rawStart && !rawEnd) return null;
|
||||
let start;
|
||||
let end;
|
||||
if (!rawStart) {
|
||||
const suffix = Number(rawEnd);
|
||||
if (!Number.isFinite(suffix) || suffix <= 0) return { unsatisfiable: true };
|
||||
start = Math.max(0, size - suffix);
|
||||
end = size - 1;
|
||||
} else {
|
||||
start = Number(rawStart);
|
||||
end = rawEnd ? Number(rawEnd) : size - 1;
|
||||
if (end >= size) end = size - 1;
|
||||
}
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= size) {
|
||||
return { unsatisfiable: true };
|
||||
}
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
/** The precompressed variant the client can take, if this build wrote one. */
|
||||
function acceptedEncoding(req) {
|
||||
const value = String(req.headers['accept-encoding'] ?? '').toLowerCase();
|
||||
if (value.includes('br')) return 'br';
|
||||
if (value.includes('gzip')) return 'gzip';
|
||||
return null;
|
||||
}
|
||||
|
||||
function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': type,
|
||||
@@ -561,19 +602,59 @@ function bridgeLinkForPhoto(photoId) {
|
||||
|
||||
async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400', extraHeaders = {}) {
|
||||
if (!filePath) return error(res, 404, 'Not found');
|
||||
// Open first, then stat the open handle. A file can vanish or lose its
|
||||
// permissions between a separate stat and open, and a ReadStream error with
|
||||
// no listener is an uncaught exception that takes the whole server down.
|
||||
let handle;
|
||||
try {
|
||||
const stat = await fsp.stat(filePath);
|
||||
res.writeHead(200, {
|
||||
handle = await fsp.open(filePath, 'r');
|
||||
} catch {
|
||||
return error(res, 404, 'Not found');
|
||||
}
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
// Byte ranges let a 300 MB original resume after a dropped connection
|
||||
// instead of starting over. The whole file is still streamed, never read
|
||||
// into memory.
|
||||
const range = req.method === 'GET' ? parseRange(req.headers.range, stat.size) : null;
|
||||
if (range?.unsatisfiable) {
|
||||
await handle.close();
|
||||
res.writeHead(416, {
|
||||
'Content-Range': `bytes */${stat.size}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Cache-Control': cache,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
});
|
||||
return res.end();
|
||||
}
|
||||
const start = range ? range.start : 0;
|
||||
const end = range ? range.end : stat.size - 1;
|
||||
const length = stat.size === 0 ? 0 : end - start + 1;
|
||||
const headers = {
|
||||
'Content-Type': type,
|
||||
'Content-Length': stat.size,
|
||||
'Content-Length': length,
|
||||
'Cache-Control': cache,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Accept-Ranges': 'bytes',
|
||||
...extraHeaders,
|
||||
});
|
||||
if (req.method === 'HEAD') return res.end();
|
||||
fs.createReadStream(filePath).pipe(res);
|
||||
};
|
||||
if (range) headers['Content-Range'] = `bytes ${start}-${end}/${stat.size}`;
|
||||
res.writeHead(range ? 206 : 200, headers);
|
||||
if (req.method === 'HEAD' || length === 0) {
|
||||
await handle.close();
|
||||
return res.end();
|
||||
}
|
||||
const stream = range ? handle.createReadStream({ start, end }) : handle.createReadStream();
|
||||
// A read that fails mid-transfer (unmounted volume, I/O error) cannot be
|
||||
// turned into an error page once the 200 is on the wire, but it must not
|
||||
// crash the process either.
|
||||
stream.on('error', () => res.destroy());
|
||||
res.on('close', () => stream.destroy());
|
||||
return stream.pipe(res);
|
||||
} catch {
|
||||
error(res, 404, 'Not found');
|
||||
await handle.close().catch(() => undefined);
|
||||
if (!res.headersSent) return error(res, 404, 'Not found');
|
||||
return res.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1765,9 +1846,12 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
|
||||
if (!hit) return error(res, 404, 'Not found');
|
||||
const proof = findProof(params.id);
|
||||
const file = proof ?? findPreview(params.id) ?? findOriginal(params.id);
|
||||
if (!file) return error(res, 404, 'Not found');
|
||||
const originalName = String(hit.photo.name || 'photo.jpg');
|
||||
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
|
||||
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
|
||||
// Count the download only once there is a file to send, so a missing render
|
||||
// does not quietly use up the client's allowance.
|
||||
noteGalleryDownload(params.token);
|
||||
return sendFile(req, res, file, mime, 'private, max-age=3600', {
|
||||
'Content-Disposition': `attachment; filename="${safe}"`,
|
||||
@@ -2088,18 +2172,32 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
// New ids are part of the normal import flow: the client uploads bytes first
|
||||
// and PUTs the record afterwards. Until that row exists the bytes are charged
|
||||
// to this user's quota, so nobody can fill the disk with unclaimed files.
|
||||
const limit = owner
|
||||
? MAX_UPLOAD
|
||||
: Math.min(MAX_UPLOAD, Math.max(0, quotaState(user.id).remaining - pendingBytes(user.id)));
|
||||
// An existing photo may still be replaced, but the replacement only has the
|
||||
// room its own file frees plus what is left of the quota: an account that is
|
||||
// already full can shrink an original, never grow one past its cap.
|
||||
const replacing = owner !== null ? findOriginal(params.id) : null;
|
||||
const replacedBytes = replacing
|
||||
? ((await fsp.stat(replacing).catch(() => null))?.size ?? 0)
|
||||
: 0;
|
||||
const limit = Math.min(
|
||||
MAX_UPLOAD,
|
||||
Math.max(0, quotaState(user.id).remaining + replacedBytes - pendingBytes(user.id)),
|
||||
);
|
||||
if (limit < 1) {
|
||||
return error(res, 413, 'This account has no storage quota left for a new upload');
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
? 'This account has no storage quota left for this file'
|
||||
: 'This account has no storage quota left for a new upload',
|
||||
);
|
||||
}
|
||||
const announced = Number(req.headers['content-length']);
|
||||
if (Number.isFinite(announced) && announced > limit) {
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
announced > MAX_UPLOAD
|
||||
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
||||
: 'This upload does not fit in the remaining storage quota',
|
||||
);
|
||||
@@ -2117,8 +2215,6 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
}
|
||||
|
||||
const target = originalTarget(params.id, ext);
|
||||
const previous = findOriginal(params.id);
|
||||
if (previous) await fsp.rm(previous, { force: true }).catch(() => undefined);
|
||||
|
||||
let size = 0;
|
||||
try {
|
||||
@@ -2129,7 +2225,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
limit >= MAX_UPLOAD
|
||||
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
||||
: 'This upload does not fit in the remaining storage quota',
|
||||
);
|
||||
@@ -2141,6 +2237,15 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
return error(res, 400, 'Empty upload');
|
||||
}
|
||||
|
||||
// Replace the previous bytes only now that the new file is safely on disk: a
|
||||
// failed or aborted replacement must leave the photo it was replacing
|
||||
// readable. Other extensions are dropped too, so an id never keeps a stale
|
||||
// copy that `findOriginal` might return instead of the new file.
|
||||
for (const previous of findOriginals(params.id)) {
|
||||
if (previous === target) continue;
|
||||
await fsp.rm(previous, { force: true }).catch(() => undefined);
|
||||
}
|
||||
|
||||
recentUploads.set(params.id, {
|
||||
ownerId: user.id,
|
||||
bytes: size,
|
||||
@@ -2458,6 +2563,13 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL');
|
||||
const record = { ...body, id: params.id };
|
||||
|
||||
// A photo may only join an event in the same workspace; otherwise a member
|
||||
// could park rows inside someone else's event and skew its totals.
|
||||
const targetEventId = typeof record.eventId === 'string' ? record.eventId : '';
|
||||
if (targetEventId && !ownedBy(eventOwner(targetEventId), user)) {
|
||||
return error(res, 404, 'No such event');
|
||||
}
|
||||
|
||||
// Quota accounting uses bytes the server actually received, not the client's
|
||||
// claim, for an upload that just finished.
|
||||
const upload = recentUploads.get(params.id);
|
||||
@@ -2467,6 +2579,16 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
}
|
||||
record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name);
|
||||
|
||||
// Library totals, quota usage and prune plans are measured from the bytes on
|
||||
// disk, not from what a saved record claims. Without this a client could PUT
|
||||
// size: 2 for a 20 MB original, shrink its reported usage and dodge its quota
|
||||
// while the file stayed on the volume.
|
||||
const storedOriginal = findOriginal(params.id);
|
||||
if (storedOriginal) {
|
||||
const stat = await fsp.stat(storedOriginal).catch(() => null);
|
||||
if (stat) record.size = stat.size;
|
||||
}
|
||||
|
||||
const thumb = decodeDataUrl(record.thumb);
|
||||
if (thumb) {
|
||||
await writeThumb(params.id, thumb.data);
|
||||
@@ -2543,13 +2665,22 @@ async function serveStatic(req, res, url) {
|
||||
if (stat.isFile()) {
|
||||
const ext = path.extname(candidate).toLowerCase();
|
||||
const immutable = pathname.startsWith('/assets/');
|
||||
return sendFile(
|
||||
req,
|
||||
res,
|
||||
candidate,
|
||||
MIME[ext] ?? 'application/octet-stream',
|
||||
immutable ? 'public, max-age=31536000, immutable' : 'no-cache',
|
||||
);
|
||||
const cache = immutable ? 'public, max-age=31536000, immutable' : 'no-cache';
|
||||
const mime = MIME[ext] ?? 'application/octet-stream';
|
||||
// `npm run build` writes .br/.gz copies of the text assets, so the
|
||||
// first request does not pay for compression and every later one is
|
||||
// just a file read.
|
||||
const encoding = acceptedEncoding(req);
|
||||
const variants = encoding === 'br' ? ['br', 'gz'] : encoding === 'gzip' ? ['gz'] : [];
|
||||
for (const variant of variants) {
|
||||
const packed = `${candidate}.${variant}`;
|
||||
if (!fs.existsSync(packed)) continue;
|
||||
return sendFile(req, res, packed, mime, cache, {
|
||||
'Content-Encoding': variant === 'br' ? 'br' : 'gzip',
|
||||
Vary: 'Accept-Encoding',
|
||||
});
|
||||
}
|
||||
return sendFile(req, res, candidate, mime, cache);
|
||||
}
|
||||
} catch {
|
||||
/* fall through to the SPA entry */
|
||||
|
||||
+11
-6
@@ -88,15 +88,20 @@ export function originalTarget(id, ext = 'bin') {
|
||||
return originalPath(id, ext);
|
||||
}
|
||||
|
||||
export function findOriginal(id) {
|
||||
export function findOriginals(id) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return null;
|
||||
if (!safe) return [];
|
||||
const { originals } = dirs();
|
||||
const prefix = `${safe}.`;
|
||||
for (const name of listFiles(originals)) {
|
||||
if (name.startsWith(prefix)) return path.join(originals, name);
|
||||
}
|
||||
return null;
|
||||
return listFiles(originals)
|
||||
// An interrupted upload leaves `<id>.<ext>.part-xxxx` behind; it is not a
|
||||
// usable original, and returning it would serve a truncated image.
|
||||
.filter((name) => name.startsWith(prefix) && !name.includes('.part-'))
|
||||
.map((name) => path.join(originals, name));
|
||||
}
|
||||
|
||||
export function findOriginal(id) {
|
||||
return findOriginals(id)[0] ?? null;
|
||||
}
|
||||
|
||||
export async function writePreview(id, data, ext = 'jpg') {
|
||||
|
||||
Reference in New Issue
Block a user