mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
fix: back-merge v3.1.4 hotfixes into dev (#1371)
Port the three main-only fixes onto dev's (post-rewrite) architecture:
- fix(backups): prevent recursion when the backup path sits inside the backed-up dir
- fix(share): convert budget items to the viewer's base currency instead of a flat EUR
- fix(files): surface the descriptive server error for unsupported upload types (#1363)
Cherry-picked from 819aa793 on main; the SharedTripPage and useTripPlanner
conflicts were resolved to keep dev's font-scaling and full import set while
taking the fixes' currency conversion and translateApiError wiring.
This commit is contained in:
@@ -39,7 +39,8 @@ const UPLOAD = {
|
||||
fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
const reject = () => {
|
||||
const err: Error & { statusCode?: number } = new Error('File type not allowed');
|
||||
// i18n key — the client resolves it via t() (see translateApiError).
|
||||
const err: Error & { statusCode?: number } = new Error('files.uploadErrorType');
|
||||
err.statusCode = 400;
|
||||
cb(err, false);
|
||||
};
|
||||
|
||||
@@ -184,9 +184,21 @@ export async function createBackup(): Promise<BackupInfo> {
|
||||
// Exclude the place-photo and trek-memory caches: both are re-derivable
|
||||
// (re-fetched on demand, keyed on stable ids) and would otherwise dominate
|
||||
// backup size. Restores self-heal — the cache dirs are recreated at startup.
|
||||
//
|
||||
// Also exclude backups/ and restore-*/: these live under data/, not uploads/,
|
||||
// but when an install maps data and uploads to the SAME directory (a
|
||||
// misconfiguration, but a catastrophic one) the glob would otherwise sweep
|
||||
// every prior backup zip into the new archive — each run embedding all
|
||||
// previous runs, so size compounds without bound (see issue #1358). Ignoring
|
||||
// them keeps the backup bounded regardless of how the volumes are mounted.
|
||||
archive.glob(
|
||||
'**/*',
|
||||
{ cwd: uploadsDir, ignore: ['photos/google/**', 'photos/trek/**'], nodir: true, dot: true },
|
||||
{
|
||||
cwd: uploadsDir,
|
||||
ignore: ['photos/google/**', 'photos/trek/**', 'backups/**', 'restore-*/**'],
|
||||
nodir: true,
|
||||
dot: true,
|
||||
},
|
||||
{ prefix: 'uploads' },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { db, canAccessTrip } from '../db/database';
|
||||
import crypto from 'crypto';
|
||||
import { loadTagsByPlaceIds } from './queryHelpers';
|
||||
import { serveFilePath } from './placePhotoCache';
|
||||
import { getUserSettings } from './settingsService';
|
||||
|
||||
const PLACE_PHOTO_PROXY_PREFIX = '/api/maps/place-photo/';
|
||||
|
||||
@@ -219,8 +220,23 @@ export function getSharedTripData(token: string): Record<string, any> | null {
|
||||
? db.prepare('SELECT m.*, u.username, u.avatar FROM collab_messages m JOIN users u ON m.user_id = u.id WHERE m.trip_id = ? AND m.deleted = 0 ORDER BY m.created_at').all(tripId)
|
||||
: [];
|
||||
|
||||
// Display currency the share owner sees in their Costs view. A public viewer has
|
||||
// no logged-in user, so the owner's per-user `default_currency` (with the admin
|
||||
// instance default already merged in by getUserSettings) is embedded in the
|
||||
// payload and used by the client to convert every expense — otherwise guests
|
||||
// fall back to the trip's base currency and see the wrong totals (#1361).
|
||||
// getUserSettings merges admin defaults under the user's own settings, so this
|
||||
// honours per-user → admin-default; we then fall back to trip currency → EUR.
|
||||
let baseCurrency = (trip as { currency?: string }).currency || 'EUR';
|
||||
if (shareRow.created_by != null) {
|
||||
const ownerDefault = getUserSettings(shareRow.created_by)['default_currency'];
|
||||
if (typeof ownerDefault === 'string' && ownerDefault.trim()) {
|
||||
baseCurrency = ownerDefault.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
trip, days, assignments, dayNotes, places, categories, permissions,
|
||||
trip, baseCurrency, days, assignments, dayNotes, places, categories, permissions,
|
||||
reservations: permissions.share_bookings ? reservations : [],
|
||||
accommodations: permissions.share_bookings ? accommodations : [],
|
||||
packing: permissions.share_packing ? packing : [],
|
||||
|
||||
@@ -126,6 +126,8 @@ describe('Upload file', () => {
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.attach('file', svgPath);
|
||||
expect(res.status).toBe(400);
|
||||
// The error is an i18n key the client resolves via t() (issue #1363).
|
||||
expect(res.body.error).toBe('files.uploadErrorType');
|
||||
} finally {
|
||||
if (fs.existsSync(svgPath)) fs.unlinkSync(svgPath);
|
||||
}
|
||||
|
||||
@@ -354,6 +354,56 @@ describe('Shared trip — ordering parity (issue #981)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Shared trip — display currency (issue #1361)', () => {
|
||||
it('SHARE-021 — baseCurrency resolves from the share owner\'s default_currency setting', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
// Trip keeps the EUR default; the owner's Costs display currency is CAD.
|
||||
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (?, 'default_currency', ?)")
|
||||
.run(user.id, JSON.stringify('CAD'));
|
||||
|
||||
const { body: { token } } = await request(app)
|
||||
.post(`/api/trips/${trip.id}/share-link`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.send({ share_budget: true });
|
||||
|
||||
const res = await request(app).get(`/api/shared/${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.baseCurrency).toBe('CAD');
|
||||
});
|
||||
|
||||
it('SHARE-022 — baseCurrency falls back to the trip currency when the owner has no setting', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
testDb.prepare('UPDATE trips SET currency = ? WHERE id = ?').run('GBP', trip.id);
|
||||
|
||||
const { body: { token } } = await request(app)
|
||||
.post(`/api/trips/${trip.id}/share-link`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.send({ share_budget: true });
|
||||
|
||||
const res = await request(app).get(`/api/shared/${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.baseCurrency).toBe('GBP');
|
||||
});
|
||||
|
||||
it('SHARE-023 — baseCurrency uses the admin instance default when the owner has no per-user setting', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id); // EUR trip default, no user setting
|
||||
testDb.prepare("INSERT INTO app_settings (key, value) VALUES ('default_user_setting_default_currency', ?)")
|
||||
.run(JSON.stringify('USD'));
|
||||
|
||||
const { body: { token } } = await request(app)
|
||||
.post(`/api/trips/${trip.id}/share-link`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.send({ share_budget: true });
|
||||
|
||||
const res = await request(app).get(`/api/shared/${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.baseCurrency).toBe('USD');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Shared trip — place photos in shared links (issue #1100)', () => {
|
||||
const PLACE_ID = 'ChIJsharedPhoto1100';
|
||||
const PROXY_URL = `/api/maps/place-photo/${encodeURIComponent(PLACE_ID)}/bytes`;
|
||||
|
||||
@@ -475,7 +475,7 @@ describe('BACKUP-036 createBackup', () => {
|
||||
'**/*',
|
||||
expect.objectContaining({
|
||||
cwd: expect.stringContaining('uploads'),
|
||||
ignore: ['photos/google/**', 'photos/trek/**'],
|
||||
ignore: ['photos/google/**', 'photos/trek/**', 'backups/**', 'restore-*/**'],
|
||||
}),
|
||||
{ prefix: 'uploads' },
|
||||
);
|
||||
@@ -483,6 +483,38 @@ describe('BACKUP-036 createBackup', () => {
|
||||
expect(archiverInstanceMock.directory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('BACKUP-036h — never sweeps backups/ or restore-* into the archive (issue #1358)', async () => {
|
||||
// Regression guard: when data and uploads map to the same directory, the
|
||||
// uploads glob would otherwise pick up the backups/ dir and recursively
|
||||
// embed every prior backup zip, compounding size without bound.
|
||||
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('uploads'));
|
||||
fsMock.mkdirSync.mockReturnValue(undefined);
|
||||
|
||||
const writableEvents: Record<string, Function> = {};
|
||||
const fakeWriteStream = {
|
||||
on: vi.fn((event: string, cb: Function) => {
|
||||
writableEvents[event] = cb;
|
||||
}),
|
||||
};
|
||||
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
|
||||
|
||||
archiverInstanceMock.on.mockImplementation((_e: string, _cb: Function) => {});
|
||||
archiverInstanceMock.pipe.mockReturnValue(undefined);
|
||||
archiverInstanceMock.finalize.mockImplementation(() => {
|
||||
if (writableEvents['close']) writableEvents['close']();
|
||||
});
|
||||
archiverMock.mockReturnValue(archiverInstanceMock);
|
||||
|
||||
fsMock.statSync.mockReturnValue({ size: 1024, birthtime: new Date('2026-04-06T12:00:00Z') });
|
||||
|
||||
await createBackup();
|
||||
|
||||
const globCall = archiverInstanceMock.glob.mock.calls.at(-1);
|
||||
const ignore: string[] = globCall?.[1]?.ignore ?? [];
|
||||
expect(ignore).toContain('backups/**');
|
||||
expect(ignore).toContain('restore-*/**');
|
||||
});
|
||||
|
||||
it('BACKUP-036f — bundles .encryption_key when present and ENCRYPTION_KEY env is unset', async () => {
|
||||
const prevEnvKey = process.env.ENCRYPTION_KEY;
|
||||
delete process.env.ENCRYPTION_KEY;
|
||||
|
||||
Reference in New Issue
Block a user