app: uploaded images for announcements, campaigns and events (APP-1.0-PLAN §10)
Photos (JPEG, PNG, WebP, checked by their bytes) uploaded in the admin are turned upright, stripped of their metadata and kept at most 2000 px wide in backend/uploads (UPLOAD_DIR), served at /api/uploads (never a listing, a sandboxing CSP). Content keeps the image's full address, so an upload and an image from elsewhere work alike. 5 GB included or the licence's storage limit; an image still in use can't be deleted. The announcement, campaign and event forms get Upload a photo next to the address. Migration media. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import sharp from 'sharp';
|
||||
import { cookieHeader, harness, MEMBER, PASTOR, signInAs, SITE, type Harness } from './support/harness.js';
|
||||
|
||||
const EDITOR = '77777777-7777-4777-8777-777777777777';
|
||||
const ORIGIN = 'https://app.hope.test';
|
||||
|
||||
async function setup() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cca-uploads-'));
|
||||
const h = await harness({ env: { UPLOAD_DIR: dir } }) as Harness;
|
||||
const as = (cookies: Record<string, string>) => ({
|
||||
get: (p: string) => request(h.app).get(p).set('Cookie', cookieHeader(cookies)),
|
||||
upload: (body: Buffer, type = 'image/jpeg') => request(h.app).post('/api/v1/admin/media?alt=Carols').set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).set('Content-Type', type).send(body),
|
||||
del: (p: string) => request(h.app).delete(p).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN),
|
||||
post: (p: string, body: object) => request(h.app).post(p).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body),
|
||||
});
|
||||
const editor = as(await signInAs(h, { sub: EDITOR, name: 'Editor', roles: ['content_admin'] }, true));
|
||||
const owner = as(await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', roles: ['owner'] }, true));
|
||||
const member = as(await signInAs(h, { sub: MEMBER, name: 'Thandi' }));
|
||||
return { h, dir, editor, owner, member };
|
||||
}
|
||||
|
||||
/** A phone photo: a JPEG with EXIF (a copyright line standing in for GPS). */
|
||||
const photo = () => sharp({ create: { width: 3000, height: 2000, channels: 3, background: '#c33' } }).jpeg().withExif({ IFD0: { Copyright: 'Where-I-live-123' } }).toBuffer();
|
||||
|
||||
describe('uploaded images (§10)', () => {
|
||||
it('keeps a photo without its metadata, at most 2000 px wide, and serves it', async () => {
|
||||
const { h, dir, editor, member } = await setup();
|
||||
assert.equal((await member.upload(await photo())).status, 403);
|
||||
const res = await editor.upload(await photo());
|
||||
assert.equal(res.status, 201);
|
||||
assert.equal(res.body.width, 2000);
|
||||
assert.equal(res.body.alt, 'Carols');
|
||||
assert.ok(res.body.url.startsWith(`${SITE}/api/uploads/`));
|
||||
const file = path.join(dir, res.body.url.slice(`${SITE}/api/uploads/`.length));
|
||||
const saved = fs.readFileSync(file);
|
||||
assert.ok(!saved.includes(Buffer.from('Where-I-live-123')));
|
||||
const served = await request(h.app).get(new URL(res.body.url).pathname);
|
||||
assert.equal(served.status, 200);
|
||||
assert.equal(served.headers['content-type'], 'image/jpeg');
|
||||
assert.match(served.headers['content-security-policy'], /sandbox/);
|
||||
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/../../package.json')).status));
|
||||
});
|
||||
|
||||
it('refuses what isn\'t a photo, whatever it\'s called', async () => {
|
||||
const { editor } = await setup();
|
||||
const res = await editor.upload(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'), 'image/png');
|
||||
assert.equal(res.status, 415);
|
||||
assert.equal(res.body.error.code, 'NOT_AN_IMAGE');
|
||||
});
|
||||
|
||||
it('won\'t delete an image an announcement still uses, and lists where each is used', async () => {
|
||||
const { h, editor } = await setup();
|
||||
const img = (await editor.upload(await photo())).body;
|
||||
await h.db.announcement.create({ data: { slug: 'carols', title: 'Carols', body: 'x', imageUrl: img.url, publishAt: new Date() } });
|
||||
const list = await editor.get('/api/v1/admin/media');
|
||||
assert.deepEqual(list.body.media[0].usedBy, ['Announcement "Carols"']);
|
||||
assert.ok(list.body.storage.usedBytes > 0);
|
||||
assert.equal((await editor.del(`/api/v1/admin/media/${img.id}`)).body.error.code, 'IN_USE');
|
||||
await h.db.announcement.deleteMany({});
|
||||
assert.equal((await editor.del(`/api/v1/admin/media/${img.id}`)).status, 200);
|
||||
assert.equal((await request(h.app).get(new URL(img.url).pathname)).status, 404);
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
outboxMessage: () => ({ sentAt: null, sentVia: null, failedAt: null, error: null, attempts: 0 }),
|
||||
notificationSettings: () => ({ requestUpdates: 'email', announcements: 'off', devotional: 'off', devotionalTime: '06:00', devotionalOfferedAt: null, lastDevotionalDate: null }),
|
||||
messageCount: () => ({ count: 0 }),
|
||||
mediaAsset: () => ({ width: null, height: null, alt: '', uploadedBy: null }),
|
||||
prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }),
|
||||
prayerRequestUpdate: () => ({ authorId: null }),
|
||||
announcement: () => ({ imageUrl: null, buttonLabel: null, buttonUrl: null, campus: null, audience: 'everyone', pinned: false, publishAt: null, endsAt: null, sendEmail: false, sendWhatsApp: false, sentAt: null, createdById: null }),
|
||||
@@ -31,7 +32,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', notificationSettings: 'memberId', messageCount: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
|
||||
/** Unique fields: one field, or several together (`@@unique([a, b])`). */
|
||||
const UNIQUE: Record<string, (string | string[])[]> = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] };
|
||||
const UNIQUE: Record<string, (string | string[])[]> = { mediaAsset: ['filename'], session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] };
|
||||
const HAS_UPDATED_AT = new Set(['notificationSettings', 'member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest', 'announcement', 'devotional', 'simpleEvent']);
|
||||
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
||||
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
||||
|
||||
Reference in New Issue
Block a user