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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user