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:
+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 */
|
||||
|
||||
Reference in New Issue
Block a user