Spaces:
Paused
Paused
Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- server/src/systemNotices/service.ts +83 -0
- server/src/systemNotices/types.ts +46 -0
- server/src/types.ts +437 -0
- server/src/typings/express.d.ts +21 -0
- server/src/utils/ssrfGuard.ts +235 -0
- server/src/websocket.ts +232 -0
- server/tests/e2e/addons.e2e.test.ts +112 -0
- server/tests/e2e/admin.e2e.test.ts +99 -0
- server/tests/e2e/airports.e2e.test.ts +95 -0
- server/tests/e2e/assignments.e2e.test.ts +109 -0
- server/tests/e2e/atlas.e2e.test.ts +133 -0
- server/tests/e2e/auth.e2e.test.ts +130 -0
- server/tests/e2e/backup.e2e.test.ts +108 -0
- server/tests/e2e/budget.e2e.test.ts +107 -0
- server/tests/e2e/categories.e2e.test.ts +119 -0
- server/tests/e2e/collab.e2e.test.ts +137 -0
- server/tests/e2e/config.e2e.test.ts +39 -0
- server/tests/e2e/days.e2e.test.ts +113 -0
- server/tests/e2e/files.e2e.test.ts +135 -0
- server/tests/e2e/harness.ts +65 -0
- server/tests/e2e/journey.e2e.test.ts +119 -0
- server/tests/e2e/maps.e2e.test.ts +101 -0
- server/tests/e2e/memories.e2e.test.ts +411 -0
- server/tests/e2e/notifications.e2e.test.ts +116 -0
- server/tests/e2e/oauth.e2e.test.ts +113 -0
- server/tests/e2e/oidc.e2e.test.ts +86 -0
- server/tests/e2e/packing.e2e.test.ts +106 -0
- server/tests/e2e/places.e2e.test.ts +114 -0
- server/tests/e2e/reservations.e2e.test.ts +145 -0
- server/tests/e2e/settings.e2e.test.ts +90 -0
- server/tests/e2e/share.e2e.test.ts +137 -0
- server/tests/e2e/system-notices.e2e.test.ts +92 -0
- server/tests/e2e/tags.e2e.test.ts +111 -0
- server/tests/e2e/todo.e2e.test.ts +100 -0
- server/tests/e2e/trips.e2e.test.ts +119 -0
- server/tests/e2e/vacay.e2e.test.ts +100 -0
- server/tests/e2e/weather.e2e.test.ts +88 -0
- server/tests/fixtures/large-test.gpx +0 -0
- server/tests/fixtures/large-test.kml +0 -0
- server/tests/fixtures/large-test.kmz +0 -0
- server/tests/fixtures/small-image.jpg +0 -0
- server/tests/fixtures/test-malformed.kml +8 -0
- server/tests/fixtures/test-nested.kml +26 -0
- server/tests/fixtures/test.gpx +11 -0
- server/tests/fixtures/test.kml +21 -0
- server/tests/fixtures/test.kmz +0 -0
- server/tests/fixtures/test.pdf +0 -0
- server/tests/helpers/auth.ts +34 -0
- server/tests/helpers/factories.ts +743 -0
.gitattributes
CHANGED
|
@@ -27,3 +27,5 @@
|
|
| 27 |
*.zip binary
|
| 28 |
server/assets/atlas/admin0.geojson.gz filter=lfs diff=lfs merge=lfs -text
|
| 29 |
server/assets/atlas/admin1.geojson.gz filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 27 |
*.zip binary
|
| 28 |
server/assets/atlas/admin0.geojson.gz filter=lfs diff=lfs merge=lfs -text
|
| 29 |
server/assets/atlas/admin1.geojson.gz filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
shared/node_modules/@rolldown/binding-linux-x64-gnu/rolldown-binding.linux-x64-gnu.node filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
shared/node_modules/@rolldown/binding-linux-x64-musl/rolldown-binding.linux-x64-musl.node filter=lfs diff=lfs merge=lfs -text
|
server/src/systemNotices/service.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createRequire } from 'module';
|
| 2 |
+
import semver from 'semver';
|
| 3 |
+
import { db } from '../db/database.js';
|
| 4 |
+
import { SYSTEM_NOTICES } from './registry.js';
|
| 5 |
+
import { evaluate } from './conditions.js';
|
| 6 |
+
import type { SystemNotice, SystemNoticeDTO } from './types.js';
|
| 7 |
+
|
| 8 |
+
function getCurrentAppVersion(): string {
|
| 9 |
+
const fromEnv = semver.valid(process.env.APP_VERSION ?? '');
|
| 10 |
+
if (fromEnv) return fromEnv;
|
| 11 |
+
try {
|
| 12 |
+
const pkg = require('../../package.json') as { version?: string };
|
| 13 |
+
return semver.valid(pkg.version ?? '') ?? '0.0.0';
|
| 14 |
+
} catch {
|
| 15 |
+
return '0.0.0';
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
export function isNoticeVersionActive(n: SystemNotice, currentAppVersion: string): boolean {
|
| 20 |
+
const appVersion = semver.coerce(currentAppVersion)?.version ?? '0.0.0';
|
| 21 |
+
if (n.minVersion !== undefined) {
|
| 22 |
+
const min = semver.valid(n.minVersion);
|
| 23 |
+
if (!min) { console.warn(`[systemNotices] "${n.id}" invalid minVersion "${n.minVersion}" — skipping`); return false; }
|
| 24 |
+
if (semver.lt(appVersion, min)) return false;
|
| 25 |
+
}
|
| 26 |
+
if (n.maxVersion !== undefined) {
|
| 27 |
+
const max = semver.valid(n.maxVersion);
|
| 28 |
+
if (!max) { console.warn(`[systemNotices] "${n.id}" invalid maxVersion "${n.maxVersion}" — skipping`); return false; }
|
| 29 |
+
if (semver.gte(appVersion, max)) return false;
|
| 30 |
+
}
|
| 31 |
+
return true;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
function severityWeight(s: string): number {
|
| 35 |
+
return s === 'critical' ? 2 : s === 'warn' ? 1 : 0;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
export function getActiveNoticesFor(userId: number): SystemNoticeDTO[] {
|
| 39 |
+
const user = db.prepare(
|
| 40 |
+
'SELECT login_count, first_seen_version, role FROM users WHERE id = ?'
|
| 41 |
+
).get(userId) as { login_count: number; first_seen_version: string; role: string } | undefined;
|
| 42 |
+
|
| 43 |
+
if (!user) return [];
|
| 44 |
+
|
| 45 |
+
const { count: tripCount } = db.prepare(
|
| 46 |
+
'SELECT COUNT(*) AS count FROM trips WHERE user_id = ?'
|
| 47 |
+
).get(userId) as { count: number };
|
| 48 |
+
|
| 49 |
+
const dismissedIds = new Set<string>(
|
| 50 |
+
(db.prepare('SELECT notice_id FROM user_notice_dismissals WHERE user_id = ?')
|
| 51 |
+
.all(userId) as Array<{ notice_id: string }>)
|
| 52 |
+
.map(r => r.notice_id)
|
| 53 |
+
);
|
| 54 |
+
|
| 55 |
+
const now = new Date();
|
| 56 |
+
const currentAppVersion = getCurrentAppVersion();
|
| 57 |
+
const ctx = { user: { ...user, noTrips: tripCount }, currentAppVersion, now };
|
| 58 |
+
|
| 59 |
+
return SYSTEM_NOTICES
|
| 60 |
+
.filter(n => {
|
| 61 |
+
if (dismissedIds.has(n.id)) return false;
|
| 62 |
+
if (!isNoticeVersionActive(n, currentAppVersion)) return false;
|
| 63 |
+
return evaluate(n, ctx);
|
| 64 |
+
})
|
| 65 |
+
.sort((a, b) => {
|
| 66 |
+
const pw = (b.priority ?? 0) - (a.priority ?? 0);
|
| 67 |
+
if (pw !== 0) return pw;
|
| 68 |
+
const sw = severityWeight(b.severity) - severityWeight(a.severity);
|
| 69 |
+
if (sw !== 0) return sw;
|
| 70 |
+
return new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime();
|
| 71 |
+
})
|
| 72 |
+
.map(({ conditions: _c, publishedAt: _p, minVersion: _mn, maxVersion: _mx, priority: _pr, ...dto }) => dto);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
export function dismissNotice(userId: number, noticeId: string): boolean {
|
| 76 |
+
const exists = SYSTEM_NOTICES.some(n => n.id === noticeId);
|
| 77 |
+
if (!exists) return false;
|
| 78 |
+
db.prepare(`
|
| 79 |
+
INSERT OR IGNORE INTO user_notice_dismissals (user_id, notice_id, dismissed_at)
|
| 80 |
+
VALUES (?, ?, ?)
|
| 81 |
+
`).run(userId, noticeId, Date.now());
|
| 82 |
+
return true;
|
| 83 |
+
}
|
server/src/systemNotices/types.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export type Display = 'modal' | 'banner' | 'toast';
|
| 2 |
+
export type Severity = 'info' | 'warn' | 'critical';
|
| 3 |
+
|
| 4 |
+
export type NoticeCondition =
|
| 5 |
+
| { kind: 'firstLogin' }
|
| 6 |
+
| { kind: 'always' }
|
| 7 |
+
| { kind: 'noTrips' }
|
| 8 |
+
| { kind: 'existingUserBeforeVersion'; version: string }
|
| 9 |
+
| { kind: 'dateWindow'; startsAt: string; endsAt?: string }
|
| 10 |
+
| { kind: 'role'; roles: Array<'admin' | 'user'> }
|
| 11 |
+
| { kind: 'addonEnabled'; addonId: string }
|
| 12 |
+
| { kind: 'custom'; id: string };
|
| 13 |
+
|
| 14 |
+
export interface NoticeMedia {
|
| 15 |
+
src: string;
|
| 16 |
+
srcDark?: string;
|
| 17 |
+
altKey: string;
|
| 18 |
+
placement?: 'hero' | 'inline';
|
| 19 |
+
aspectRatio?: string;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
export type NoticeCta =
|
| 23 |
+
| { kind: 'nav'; labelKey: string; href: string }
|
| 24 |
+
| { kind: 'action'; labelKey: string; actionId: string; dismissOnAction?: boolean };
|
| 25 |
+
|
| 26 |
+
export interface SystemNotice {
|
| 27 |
+
id: string;
|
| 28 |
+
display: Display;
|
| 29 |
+
severity: Severity;
|
| 30 |
+
titleKey: string;
|
| 31 |
+
bodyKey: string;
|
| 32 |
+
bodyParams?: Record<string, string>;
|
| 33 |
+
icon?: string;
|
| 34 |
+
media?: NoticeMedia;
|
| 35 |
+
highlights?: Array<{ labelKey: string; iconName?: string }>;
|
| 36 |
+
cta?: NoticeCta;
|
| 37 |
+
dismissible: boolean;
|
| 38 |
+
conditions: NoticeCondition[];
|
| 39 |
+
publishedAt: string;
|
| 40 |
+
minVersion?: string;
|
| 41 |
+
maxVersion?: string;
|
| 42 |
+
priority?: number;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// DTO sent to client (same shape minus the conditions — server evaluates those)
|
| 46 |
+
export type SystemNoticeDTO = Omit<SystemNotice, 'conditions' | 'publishedAt' | 'minVersion' | 'maxVersion' | 'priority'>;
|
server/src/types.ts
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Request } from 'express';
|
| 2 |
+
|
| 3 |
+
export interface User {
|
| 4 |
+
id: number;
|
| 5 |
+
username: string;
|
| 6 |
+
email: string;
|
| 7 |
+
role: 'admin' | 'user';
|
| 8 |
+
password_hash?: string;
|
| 9 |
+
maps_api_key?: string | null;
|
| 10 |
+
unsplash_api_key?: string | null;
|
| 11 |
+
openweather_api_key?: string | null;
|
| 12 |
+
avatar?: string | null;
|
| 13 |
+
oidc_sub?: string | null;
|
| 14 |
+
oidc_issuer?: string | null;
|
| 15 |
+
last_login?: string | null;
|
| 16 |
+
mfa_enabled?: number | boolean;
|
| 17 |
+
mfa_secret?: string | null;
|
| 18 |
+
mfa_backup_codes?: string | null;
|
| 19 |
+
must_change_password?: number | boolean;
|
| 20 |
+
first_seen_version?: string;
|
| 21 |
+
login_count?: number;
|
| 22 |
+
created_at?: string;
|
| 23 |
+
updated_at?: string;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export interface Trip {
|
| 27 |
+
id: number;
|
| 28 |
+
user_id: number;
|
| 29 |
+
title: string;
|
| 30 |
+
description?: string | null;
|
| 31 |
+
start_date?: string | null;
|
| 32 |
+
end_date?: string | null;
|
| 33 |
+
currency: string;
|
| 34 |
+
cover_image?: string | null;
|
| 35 |
+
is_archived: number;
|
| 36 |
+
reminder_days: number;
|
| 37 |
+
created_at?: string;
|
| 38 |
+
updated_at?: string;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
export interface Day {
|
| 42 |
+
id: number;
|
| 43 |
+
trip_id: number;
|
| 44 |
+
day_number: number;
|
| 45 |
+
date?: string | null;
|
| 46 |
+
notes?: string | null;
|
| 47 |
+
title?: string | null;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export interface Place {
|
| 51 |
+
id: number;
|
| 52 |
+
trip_id: number;
|
| 53 |
+
name: string;
|
| 54 |
+
description?: string | null;
|
| 55 |
+
lat?: number | null;
|
| 56 |
+
lng?: number | null;
|
| 57 |
+
address?: string | null;
|
| 58 |
+
category_id?: number | null;
|
| 59 |
+
price?: number | null;
|
| 60 |
+
currency?: string | null;
|
| 61 |
+
reservation_status?: string;
|
| 62 |
+
reservation_notes?: string | null;
|
| 63 |
+
reservation_datetime?: string | null;
|
| 64 |
+
place_time?: string | null;
|
| 65 |
+
end_time?: string | null;
|
| 66 |
+
duration_minutes?: number;
|
| 67 |
+
notes?: string | null;
|
| 68 |
+
image_url?: string | null;
|
| 69 |
+
google_place_id?: string | null;
|
| 70 |
+
osm_id?: string | null;
|
| 71 |
+
website?: string | null;
|
| 72 |
+
phone?: string | null;
|
| 73 |
+
transport_mode?: string;
|
| 74 |
+
created_at?: string;
|
| 75 |
+
updated_at?: string;
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
export interface Category {
|
| 79 |
+
id: number;
|
| 80 |
+
name: string;
|
| 81 |
+
color: string;
|
| 82 |
+
icon: string;
|
| 83 |
+
user_id?: number | null;
|
| 84 |
+
created_at?: string;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
export interface Tag {
|
| 88 |
+
id: number;
|
| 89 |
+
user_id: number;
|
| 90 |
+
name: string;
|
| 91 |
+
color: string;
|
| 92 |
+
created_at?: string;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
export interface DayAssignment {
|
| 96 |
+
id: number;
|
| 97 |
+
day_id: number;
|
| 98 |
+
place_id: number;
|
| 99 |
+
order_index: number;
|
| 100 |
+
notes?: string | null;
|
| 101 |
+
reservation_status?: string;
|
| 102 |
+
reservation_notes?: string | null;
|
| 103 |
+
reservation_datetime?: string | null;
|
| 104 |
+
assignment_time?: string | null;
|
| 105 |
+
assignment_end_time?: string | null;
|
| 106 |
+
created_at?: string;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
export interface PackingItem {
|
| 110 |
+
id: number;
|
| 111 |
+
trip_id: number;
|
| 112 |
+
name: string;
|
| 113 |
+
checked: number;
|
| 114 |
+
category?: string | null;
|
| 115 |
+
sort_order: number;
|
| 116 |
+
created_at?: string;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
export interface BudgetItem {
|
| 120 |
+
id: number;
|
| 121 |
+
trip_id: number;
|
| 122 |
+
category: string;
|
| 123 |
+
name: string;
|
| 124 |
+
total_price: number;
|
| 125 |
+
currency?: string | null;
|
| 126 |
+
exchange_rate?: number;
|
| 127 |
+
persons?: number | null;
|
| 128 |
+
days?: number | null;
|
| 129 |
+
note?: string | null;
|
| 130 |
+
reservation_id?: number | null;
|
| 131 |
+
paid_by_user_id?: number | null;
|
| 132 |
+
expense_date?: string | null;
|
| 133 |
+
sort_order: number;
|
| 134 |
+
created_at?: string;
|
| 135 |
+
members?: BudgetItemMember[];
|
| 136 |
+
payers?: BudgetItemPayer[];
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
export interface BudgetItemMember {
|
| 140 |
+
user_id: number;
|
| 141 |
+
paid: number;
|
| 142 |
+
username: string;
|
| 143 |
+
avatar_url?: string | null;
|
| 144 |
+
avatar?: string | null;
|
| 145 |
+
budget_item_id?: number;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
export interface BudgetItemPayer {
|
| 149 |
+
user_id: number;
|
| 150 |
+
amount: number;
|
| 151 |
+
username?: string;
|
| 152 |
+
avatar_url?: string | null;
|
| 153 |
+
avatar?: string | null;
|
| 154 |
+
budget_item_id?: number;
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
export interface ReservationEndpoint {
|
| 158 |
+
id: number;
|
| 159 |
+
reservation_id: number;
|
| 160 |
+
role: 'from' | 'to' | 'stop';
|
| 161 |
+
sequence: number;
|
| 162 |
+
name: string;
|
| 163 |
+
code: string | null;
|
| 164 |
+
lat: number;
|
| 165 |
+
lng: number;
|
| 166 |
+
timezone: string | null;
|
| 167 |
+
local_time: string | null;
|
| 168 |
+
local_date: string | null;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
export interface Reservation {
|
| 172 |
+
id: number;
|
| 173 |
+
trip_id: number;
|
| 174 |
+
day_id?: number | null;
|
| 175 |
+
end_day_id?: number | null;
|
| 176 |
+
place_id?: number | null;
|
| 177 |
+
assignment_id?: number | null;
|
| 178 |
+
title: string;
|
| 179 |
+
reservation_time?: string | null;
|
| 180 |
+
reservation_end_time?: string | null;
|
| 181 |
+
location?: string | null;
|
| 182 |
+
confirmation_number?: string | null;
|
| 183 |
+
notes?: string | null;
|
| 184 |
+
status: string;
|
| 185 |
+
type: string;
|
| 186 |
+
accommodation_id?: number | null;
|
| 187 |
+
metadata?: string | null;
|
| 188 |
+
needs_review?: number;
|
| 189 |
+
endpoints?: ReservationEndpoint[];
|
| 190 |
+
created_at?: string;
|
| 191 |
+
day_number?: number;
|
| 192 |
+
place_name?: string;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
export interface TripFile {
|
| 196 |
+
id: number;
|
| 197 |
+
trip_id: number;
|
| 198 |
+
place_id?: number | null;
|
| 199 |
+
reservation_id?: number | null;
|
| 200 |
+
note_id?: number | null;
|
| 201 |
+
uploaded_by?: number | null;
|
| 202 |
+
uploaded_by_name?: string | null;
|
| 203 |
+
filename: string;
|
| 204 |
+
original_name: string;
|
| 205 |
+
file_size?: number | null;
|
| 206 |
+
mime_type?: string | null;
|
| 207 |
+
description?: string | null;
|
| 208 |
+
starred?: number;
|
| 209 |
+
deleted_at?: string | null;
|
| 210 |
+
created_at?: string;
|
| 211 |
+
reservation_title?: string;
|
| 212 |
+
url?: string;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
export interface TripMember {
|
| 216 |
+
id: number;
|
| 217 |
+
trip_id: number;
|
| 218 |
+
user_id: number;
|
| 219 |
+
invited_by?: number | null;
|
| 220 |
+
added_at?: string;
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
export interface DayNote {
|
| 224 |
+
id: number;
|
| 225 |
+
day_id: number;
|
| 226 |
+
trip_id: number;
|
| 227 |
+
text: string;
|
| 228 |
+
time?: string | null;
|
| 229 |
+
icon: string;
|
| 230 |
+
sort_order: number;
|
| 231 |
+
created_at?: string;
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
export interface CollabNote {
|
| 235 |
+
id: number;
|
| 236 |
+
trip_id: number;
|
| 237 |
+
user_id: number;
|
| 238 |
+
category: string;
|
| 239 |
+
title: string;
|
| 240 |
+
content?: string | null;
|
| 241 |
+
color: string;
|
| 242 |
+
pinned: number;
|
| 243 |
+
website?: string | null;
|
| 244 |
+
username?: string;
|
| 245 |
+
avatar?: string | null;
|
| 246 |
+
created_at?: string;
|
| 247 |
+
updated_at?: string;
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
export interface CollabPoll {
|
| 251 |
+
id: number;
|
| 252 |
+
trip_id: number;
|
| 253 |
+
user_id: number;
|
| 254 |
+
question: string;
|
| 255 |
+
options: string;
|
| 256 |
+
multiple: number;
|
| 257 |
+
closed: number;
|
| 258 |
+
deadline?: string | null;
|
| 259 |
+
username?: string;
|
| 260 |
+
avatar?: string | null;
|
| 261 |
+
created_at?: string;
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
export interface CollabMessage {
|
| 265 |
+
id: number;
|
| 266 |
+
trip_id: number;
|
| 267 |
+
user_id: number;
|
| 268 |
+
text: string;
|
| 269 |
+
reply_to?: number | null;
|
| 270 |
+
deleted?: number;
|
| 271 |
+
username?: string;
|
| 272 |
+
avatar?: string | null;
|
| 273 |
+
reply_text?: string | null;
|
| 274 |
+
reply_username?: string | null;
|
| 275 |
+
created_at?: string;
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
export interface Addon {
|
| 279 |
+
id: string;
|
| 280 |
+
name: string;
|
| 281 |
+
description?: string | null;
|
| 282 |
+
type: string;
|
| 283 |
+
icon: string;
|
| 284 |
+
enabled: number;
|
| 285 |
+
config: string;
|
| 286 |
+
sort_order: number;
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
export interface AppSetting {
|
| 290 |
+
key: string;
|
| 291 |
+
value?: string | null;
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
export interface Setting {
|
| 295 |
+
id: number;
|
| 296 |
+
user_id: number;
|
| 297 |
+
key: string;
|
| 298 |
+
value?: string | null;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
export interface AuthRequest extends Request {
|
| 302 |
+
user: User;
|
| 303 |
+
trip?: { id: number; user_id: number };
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
export interface OptionalAuthRequest extends Request {
|
| 307 |
+
user: User | null;
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
export interface AssignmentRow extends DayAssignment {
|
| 311 |
+
place_name: string;
|
| 312 |
+
place_description: string | null;
|
| 313 |
+
lat: number | null;
|
| 314 |
+
lng: number | null;
|
| 315 |
+
address: string | null;
|
| 316 |
+
category_id: number | null;
|
| 317 |
+
price: number | null;
|
| 318 |
+
place_currency: string | null;
|
| 319 |
+
place_time: string | null;
|
| 320 |
+
end_time: string | null;
|
| 321 |
+
duration_minutes: number;
|
| 322 |
+
place_notes: string | null;
|
| 323 |
+
image_url: string | null;
|
| 324 |
+
transport_mode: string;
|
| 325 |
+
google_place_id: string | null;
|
| 326 |
+
website: string | null;
|
| 327 |
+
phone: string | null;
|
| 328 |
+
category_name: string | null;
|
| 329 |
+
category_color: string | null;
|
| 330 |
+
category_icon: string | null;
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
export interface Participant {
|
| 334 |
+
user_id: number;
|
| 335 |
+
username: string;
|
| 336 |
+
avatar?: string | null;
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
// ── Journey addon ─────────────────────────────────────────────────────────
|
| 340 |
+
|
| 341 |
+
export interface Journey {
|
| 342 |
+
id: number;
|
| 343 |
+
user_id: number;
|
| 344 |
+
title: string;
|
| 345 |
+
subtitle?: string | null;
|
| 346 |
+
cover_gradient?: string | null;
|
| 347 |
+
cover_image?: string | null;
|
| 348 |
+
status: 'draft' | 'active' | 'completed' | 'archived';
|
| 349 |
+
created_at: number;
|
| 350 |
+
updated_at: number;
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
export interface JourneyEntry {
|
| 354 |
+
id: number;
|
| 355 |
+
journey_id: number;
|
| 356 |
+
source_trip_id?: number | null;
|
| 357 |
+
source_place_id?: number | null;
|
| 358 |
+
author_id: number;
|
| 359 |
+
type: 'entry' | 'checkin' | 'skeleton';
|
| 360 |
+
title?: string | null;
|
| 361 |
+
story?: string | null;
|
| 362 |
+
entry_date: string;
|
| 363 |
+
entry_time?: string | null;
|
| 364 |
+
location_name?: string | null;
|
| 365 |
+
location_lat?: number | null;
|
| 366 |
+
location_lng?: number | null;
|
| 367 |
+
mood?: string | null;
|
| 368 |
+
weather?: string | null;
|
| 369 |
+
tags?: string | null;
|
| 370 |
+
pros_cons?: string | null;
|
| 371 |
+
visibility: 'private' | 'shared' | 'public';
|
| 372 |
+
sort_order: number;
|
| 373 |
+
created_at: number;
|
| 374 |
+
updated_at: number;
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
export interface TrekPhoto {
|
| 378 |
+
id: number;
|
| 379 |
+
provider: string;
|
| 380 |
+
asset_id?: string | null;
|
| 381 |
+
owner_id?: number | null;
|
| 382 |
+
file_path?: string | null;
|
| 383 |
+
thumbnail_path?: string | null;
|
| 384 |
+
width?: number | null;
|
| 385 |
+
height?: number | null;
|
| 386 |
+
passphrase?: string | null;
|
| 387 |
+
created_at: string;
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
export interface JourneyPhoto {
|
| 391 |
+
id: number;
|
| 392 |
+
entry_id: number;
|
| 393 |
+
photo_id: number;
|
| 394 |
+
caption?: string | null;
|
| 395 |
+
sort_order: number;
|
| 396 |
+
shared: number;
|
| 397 |
+
created_at: number;
|
| 398 |
+
// Joined from trek_photos for API responses
|
| 399 |
+
provider?: string;
|
| 400 |
+
asset_id?: string | null;
|
| 401 |
+
owner_id?: number | null;
|
| 402 |
+
file_path?: string | null;
|
| 403 |
+
thumbnail_path?: string | null;
|
| 404 |
+
width?: number | null;
|
| 405 |
+
height?: number | null;
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
export interface GalleryPhoto {
|
| 409 |
+
id: number;
|
| 410 |
+
journey_id: number;
|
| 411 |
+
photo_id: number;
|
| 412 |
+
caption?: string | null;
|
| 413 |
+
shared: number;
|
| 414 |
+
sort_order: number;
|
| 415 |
+
created_at: number;
|
| 416 |
+
// Joined from trek_photos for API responses
|
| 417 |
+
provider?: string;
|
| 418 |
+
asset_id?: string | null;
|
| 419 |
+
owner_id?: number | null;
|
| 420 |
+
file_path?: string | null;
|
| 421 |
+
thumbnail_path?: string | null;
|
| 422 |
+
width?: number | null;
|
| 423 |
+
height?: number | null;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
export interface JourneyTrip {
|
| 427 |
+
journey_id: number;
|
| 428 |
+
trip_id: number;
|
| 429 |
+
added_at: number;
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
export interface JourneyContributor {
|
| 433 |
+
journey_id: number;
|
| 434 |
+
user_id: number;
|
| 435 |
+
role: 'owner' | 'editor' | 'viewer';
|
| 436 |
+
added_at: number;
|
| 437 |
+
}
|
server/src/typings/express.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Augments Express's `Request` with the fields TREK middleware + Nest guards
|
| 2 |
+
// attach after authentication. Replaces the per-site casts
|
| 3 |
+
// (`(req as AuthRequest).user`, `getRequest<Request & { user?: User }>()`) with
|
| 4 |
+
// a single source of truth so downstream code can read `req.user` directly.
|
| 5 |
+
|
| 6 |
+
import type { User } from '../types';
|
| 7 |
+
|
| 8 |
+
declare module 'express-serve-static-core' {
|
| 9 |
+
interface Request {
|
| 10 |
+
/**
|
| 11 |
+
* Set by `authenticate` middleware (Express) and `JwtAuthGuard` (Nest).
|
| 12 |
+
* Present on every route mounted behind those guards. `null` is used by
|
| 13 |
+
* `optionalAuthenticate` to signal "checked, but unauthenticated".
|
| 14 |
+
*/
|
| 15 |
+
user?: User | null;
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
// This file has imports, so TS treats it as a module. The empty export keeps
|
| 20 |
+
// the `declare module` augmentation visible project-wide.
|
| 21 |
+
export {};
|
server/src/utils/ssrfGuard.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dns from 'node:dns/promises';
|
| 2 |
+
import { Agent } from 'undici';
|
| 3 |
+
|
| 4 |
+
const ALLOW_INTERNAL_NETWORK = process.env.ALLOW_INTERNAL_NETWORK?.toLowerCase() === 'true';
|
| 5 |
+
|
| 6 |
+
export interface SsrfResult {
|
| 7 |
+
allowed: boolean;
|
| 8 |
+
resolvedIp?: string;
|
| 9 |
+
isPrivate: boolean;
|
| 10 |
+
error?: string;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
// Always blocked — no override possible
|
| 14 |
+
function isAlwaysBlocked(ip: string): boolean {
|
| 15 |
+
// Strip IPv6 brackets
|
| 16 |
+
const addr = ip.startsWith('[') ? ip.slice(1, -1) : ip;
|
| 17 |
+
|
| 18 |
+
// Loopback
|
| 19 |
+
if (addr.startsWith('127.') || addr === '::1') return true;
|
| 20 |
+
// Unspecified
|
| 21 |
+
if (addr.startsWith('0.')) return true;
|
| 22 |
+
// Link-local / cloud metadata
|
| 23 |
+
if (addr.startsWith('169.254.') || /^fe80:/i.test(addr)) return true;
|
| 24 |
+
// IPv4-mapped loopback / link-local: ::ffff:127.x.x.x, ::ffff:169.254.x.x
|
| 25 |
+
if (/^::ffff:127\./i.test(addr) || /^::ffff:169\.254\./i.test(addr)) return true;
|
| 26 |
+
|
| 27 |
+
return false;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// Blocked unless ALLOW_INTERNAL_NETWORK=true
|
| 31 |
+
function isPrivateNetwork(ip: string): boolean {
|
| 32 |
+
const addr = ip.startsWith('[') ? ip.slice(1, -1) : ip;
|
| 33 |
+
|
| 34 |
+
// RFC-1918 private ranges
|
| 35 |
+
if (addr.startsWith('10.')) return true;
|
| 36 |
+
if (/^172\.(1[6-9]|2\d|3[01])\./.test(addr)) return true;
|
| 37 |
+
if (addr.startsWith('192.168.')) return true;
|
| 38 |
+
// CGNAT / Tailscale shared address space (100.64.0.0/10)
|
| 39 |
+
if (/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(addr)) return true;
|
| 40 |
+
// IPv6 ULA (fc00::/7)
|
| 41 |
+
if (/^f[cd]/i.test(addr)) return true;
|
| 42 |
+
// IPv4-mapped RFC-1918
|
| 43 |
+
if (/^::ffff:10\./i.test(addr)) return true;
|
| 44 |
+
if (/^::ffff:172\.(1[6-9]|2\d|3[01])\./i.test(addr)) return true;
|
| 45 |
+
if (/^::ffff:192\.168\./i.test(addr)) return true;
|
| 46 |
+
|
| 47 |
+
return false;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
function isInternalHostname(hostname: string): boolean {
|
| 51 |
+
const h = hostname.toLowerCase();
|
| 52 |
+
return h.endsWith('.local') || h.endsWith('.internal') || h === 'localhost';
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export async function checkSsrf(rawUrl: string, bypassInternalIpAllowed: boolean = false): Promise<SsrfResult> {
|
| 56 |
+
let url: URL;
|
| 57 |
+
try {
|
| 58 |
+
url = new URL(rawUrl);
|
| 59 |
+
} catch {
|
| 60 |
+
return { allowed: false, isPrivate: false, error: 'Invalid URL' };
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
if (!['http:', 'https:'].includes(url.protocol)) {
|
| 64 |
+
return { allowed: false, isPrivate: false, error: 'Only HTTP and HTTPS URLs are allowed' };
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
const hostname = url.hostname.toLowerCase();
|
| 68 |
+
|
| 69 |
+
// Resolve hostname to IP
|
| 70 |
+
let resolvedIp: string;
|
| 71 |
+
try {
|
| 72 |
+
const result = await dns.lookup(hostname);
|
| 73 |
+
resolvedIp = result.address;
|
| 74 |
+
} catch (error_) {
|
| 75 |
+
const code = error_ instanceof Error && 'code' in error_ ? String(error_.code) : 'unknown';
|
| 76 |
+
return { allowed: false, isPrivate: false, error: `Could not resolve hostname (${code})` };
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
if (isAlwaysBlocked(resolvedIp)) {
|
| 80 |
+
return {
|
| 81 |
+
allowed: false,
|
| 82 |
+
isPrivate: true,
|
| 83 |
+
resolvedIp,
|
| 84 |
+
error: 'Requests to loopback and link-local addresses are not allowed',
|
| 85 |
+
};
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
if (isPrivateNetwork(resolvedIp) || isInternalHostname(hostname)) {
|
| 89 |
+
if (!ALLOW_INTERNAL_NETWORK || bypassInternalIpAllowed) {
|
| 90 |
+
return {
|
| 91 |
+
allowed: false,
|
| 92 |
+
isPrivate: true,
|
| 93 |
+
resolvedIp,
|
| 94 |
+
error:
|
| 95 |
+
'Requests to private/internal network addresses are not allowed. Set ALLOW_INTERNAL_NETWORK=true to permit this for self-hosted setups.',
|
| 96 |
+
};
|
| 97 |
+
}
|
| 98 |
+
return { allowed: true, isPrivate: true, resolvedIp };
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
return { allowed: true, isPrivate: false, resolvedIp };
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
/**
|
| 105 |
+
* Thrown by safeFetch() when the URL is blocked by the SSRF guard.
|
| 106 |
+
*/
|
| 107 |
+
export class SsrfBlockedError extends Error {
|
| 108 |
+
constructor(message: string) {
|
| 109 |
+
super(message);
|
| 110 |
+
this.name = 'SsrfBlockedError';
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
export interface SafeFetchOptions {
|
| 115 |
+
rejectUnauthorized?: boolean;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
/**
|
| 119 |
+
* SSRF-safe fetch wrapper. Validates the URL with checkSsrf(), then makes
|
| 120 |
+
* the request using a DNS-pinned dispatcher so the resolved IP cannot change
|
| 121 |
+
* between the check and the actual connection (DNS rebinding prevention).
|
| 122 |
+
*
|
| 123 |
+
* Pass `{ rejectUnauthorized: false }` for targets that use self-signed TLS
|
| 124 |
+
* certificates (e.g. a Synology NAS on a local network). The SSRF guard still
|
| 125 |
+
* applies — only the TLS certificate check is relaxed.
|
| 126 |
+
*/
|
| 127 |
+
export async function safeFetch(url: string, init?: RequestInit, options?: SafeFetchOptions): Promise<Response> {
|
| 128 |
+
const ssrf = await checkSsrf(url);
|
| 129 |
+
if (!ssrf.allowed) {
|
| 130 |
+
throw new SsrfBlockedError(ssrf.error ?? 'Request blocked by SSRF guard');
|
| 131 |
+
}
|
| 132 |
+
const dispatcher = createPinnedDispatcher(ssrf.resolvedIp!, options?.rejectUnauthorized ?? true);
|
| 133 |
+
return fetch(url, { ...init, dispatcher } as any);
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
export interface SafeFetchFollowOptions extends SafeFetchOptions {
|
| 137 |
+
/** Maximum number of redirects to follow before giving up. Defaults to 5. */
|
| 138 |
+
maxRedirects?: number;
|
| 139 |
+
/**
|
| 140 |
+
* When true, private/internal IPs that ALLOW_INTERNAL_NETWORK would normally
|
| 141 |
+
* permit are still blocked (matches `checkSsrf(url, true)`). Loopback and
|
| 142 |
+
* link-local are always blocked regardless. Defaults to false.
|
| 143 |
+
*/
|
| 144 |
+
bypassInternalIpAllowed?: boolean;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
/**
|
| 148 |
+
* SSRF-safe fetch that follows redirects MANUALLY, re-validating every hop.
|
| 149 |
+
*
|
| 150 |
+
* `safeFetch()` (and a one-shot `checkSsrf()` + `fetch(redirect:'follow')`) only
|
| 151 |
+
* guards the INITIAL URL: a validated public URL can 302-redirect to an internal
|
| 152 |
+
* IP that the platform fetch would then follow unchecked (redirect TOCTOU). This
|
| 153 |
+
* helper instead requests with `redirect: 'manual'`, and on every 3xx it resolves
|
| 154 |
+
* the `Location` header against the current URL, runs `checkSsrf()` on the new
|
| 155 |
+
* target, and only then fetches the next hop through a dispatcher pinned to THAT
|
| 156 |
+
* hop's resolved IP. Each hop is therefore SSRF-checked + DNS-pinned, while
|
| 157 |
+
* legitimate cross-host redirects (e.g. goo.gl → maps.google.com) still resolve
|
| 158 |
+
* because the dispatcher is re-pinned per hop rather than locked to the first IP.
|
| 159 |
+
*
|
| 160 |
+
* The returned Response is the first non-redirect response (or the last redirect
|
| 161 |
+
* if the hop limit is reached). `response.url` reflects the final hop so callers
|
| 162 |
+
* relying on the resolved URL keep working.
|
| 163 |
+
*/
|
| 164 |
+
export async function safeFetchFollow(
|
| 165 |
+
url: string,
|
| 166 |
+
init?: RequestInit,
|
| 167 |
+
options?: SafeFetchFollowOptions,
|
| 168 |
+
): Promise<Response> {
|
| 169 |
+
const maxRedirects = options?.maxRedirects ?? 5;
|
| 170 |
+
const rejectUnauthorized = options?.rejectUnauthorized ?? true;
|
| 171 |
+
const bypassInternalIpAllowed = options?.bypassInternalIpAllowed ?? false;
|
| 172 |
+
|
| 173 |
+
let currentUrl = url;
|
| 174 |
+
|
| 175 |
+
for (let hop = 0; ; hop++) {
|
| 176 |
+
const ssrf = await checkSsrf(currentUrl, bypassInternalIpAllowed);
|
| 177 |
+
if (!ssrf.allowed) {
|
| 178 |
+
throw new SsrfBlockedError(ssrf.error ?? 'Request blocked by SSRF guard');
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
const dispatcher = createPinnedDispatcher(ssrf.resolvedIp!, rejectUnauthorized);
|
| 182 |
+
const response = await fetch(currentUrl, {
|
| 183 |
+
...init,
|
| 184 |
+
redirect: 'manual',
|
| 185 |
+
dispatcher,
|
| 186 |
+
} as any);
|
| 187 |
+
|
| 188 |
+
// Only a 3xx WITH a Location header is a redirect we follow; anything else
|
| 189 |
+
// (2xx/4xx/5xx, or a 3xx with no Location) is the final response.
|
| 190 |
+
const status = typeof response.status === 'number' ? response.status : 0;
|
| 191 |
+
const isRedirectStatus = status >= 300 && status < 400;
|
| 192 |
+
const location = isRedirectStatus ? (response.headers?.get('location') ?? null) : null;
|
| 193 |
+
if (!location) {
|
| 194 |
+
return response;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
if (hop >= maxRedirects) {
|
| 198 |
+
throw new SsrfBlockedError('Too many redirects');
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
// Resolve relative redirects against the current URL, then loop to
|
| 202 |
+
// re-check + re-pin on the next iteration. Drain the body so the
|
| 203 |
+
// connection can be reused/closed.
|
| 204 |
+
let nextUrl: string;
|
| 205 |
+
try {
|
| 206 |
+
nextUrl = new URL(location, currentUrl).toString();
|
| 207 |
+
} catch {
|
| 208 |
+
throw new SsrfBlockedError('Invalid redirect location');
|
| 209 |
+
}
|
| 210 |
+
void response.body?.cancel().catch(() => {});
|
| 211 |
+
currentUrl = nextUrl;
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
/**
|
| 216 |
+
* Returns an undici Agent whose connect.lookup is pinned to the already-validated
|
| 217 |
+
* IP. This prevents DNS rebinding (TOCTOU) by ensuring the outbound connection
|
| 218 |
+
* goes to the IP we checked, not a re-resolved one.
|
| 219 |
+
*/
|
| 220 |
+
export function createPinnedDispatcher(resolvedIp: string, rejectUnauthorized = true): Agent {
|
| 221 |
+
return new Agent({
|
| 222 |
+
connect: {
|
| 223 |
+
rejectUnauthorized,
|
| 224 |
+
lookup: (_hostname: string, opts: Record<string, unknown>, callback: Function) => {
|
| 225 |
+
const family = resolvedIp.includes(':') ? 6 : 4;
|
| 226 |
+
// Node.js 18+ may call lookup with `all: true`, expecting an array of address objects
|
| 227 |
+
if (opts?.all) {
|
| 228 |
+
callback(null, [{ address: resolvedIp, family }]);
|
| 229 |
+
} else {
|
| 230 |
+
callback(null, resolvedIp, family);
|
| 231 |
+
}
|
| 232 |
+
},
|
| 233 |
+
},
|
| 234 |
+
});
|
| 235 |
+
}
|
server/src/websocket.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { WebSocketServer, WebSocket } from 'ws';
|
| 2 |
+
import { db, canAccessTrip } from './db/database';
|
| 3 |
+
import { consumeEphemeralTokenWithMeta } from './services/ephemeralTokens';
|
| 4 |
+
import { User } from './types';
|
| 5 |
+
import http from 'node:http';
|
| 6 |
+
|
| 7 |
+
interface NomadWebSocket extends WebSocket {
|
| 8 |
+
isAlive: boolean;
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
// Room management: tripId -> Set<WebSocket>
|
| 12 |
+
const rooms = new Map<number, Set<NomadWebSocket>>();
|
| 13 |
+
|
| 14 |
+
// Track which rooms each socket is in
|
| 15 |
+
const socketRooms = new WeakMap<NomadWebSocket, Set<number>>();
|
| 16 |
+
|
| 17 |
+
// Track user info per socket
|
| 18 |
+
const socketUser = new WeakMap<NomadWebSocket, User>();
|
| 19 |
+
|
| 20 |
+
// Track unique socket ID
|
| 21 |
+
const socketId = new WeakMap<NomadWebSocket, number>();
|
| 22 |
+
let nextSocketId = 1;
|
| 23 |
+
|
| 24 |
+
let wss: WebSocketServer | null = null;
|
| 25 |
+
|
| 26 |
+
// Per-connection message rate limiting
|
| 27 |
+
const WS_MSG_LIMIT = 30; // max messages
|
| 28 |
+
const WS_MSG_WINDOW = 10_000; // per 10 seconds
|
| 29 |
+
const socketMsgCounts = new WeakMap<NomadWebSocket, { count: number; windowStart: number }>();
|
| 30 |
+
|
| 31 |
+
/** Attaches a WebSocket server with JWT auth, room-based trip channels, and heartbeat keep-alive. */
|
| 32 |
+
function setupWebSocket(server: http.Server): void {
|
| 33 |
+
const allowedOrigins = process.env.ALLOWED_ORIGINS
|
| 34 |
+
? process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim())
|
| 35 |
+
: null;
|
| 36 |
+
|
| 37 |
+
wss = new WebSocketServer({
|
| 38 |
+
server,
|
| 39 |
+
path: '/ws',
|
| 40 |
+
maxPayload: 64 * 1024, // 64 KB max message size
|
| 41 |
+
verifyClient: allowedOrigins
|
| 42 |
+
? ({ origin }, cb) => {
|
| 43 |
+
if (!origin || allowedOrigins.includes(origin)) cb(true);
|
| 44 |
+
else cb(false, 403, 'Origin not allowed');
|
| 45 |
+
}
|
| 46 |
+
: undefined,
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
| 50 |
+
const heartbeat = setInterval(() => {
|
| 51 |
+
wss.clients.forEach((ws) => {
|
| 52 |
+
const nws = ws as NomadWebSocket;
|
| 53 |
+
if (nws.isAlive === false) return nws.terminate();
|
| 54 |
+
nws.isAlive = false;
|
| 55 |
+
nws.ping();
|
| 56 |
+
});
|
| 57 |
+
}, HEARTBEAT_INTERVAL);
|
| 58 |
+
|
| 59 |
+
wss.on('close', () => clearInterval(heartbeat));
|
| 60 |
+
|
| 61 |
+
wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
|
| 62 |
+
const nws = ws as NomadWebSocket;
|
| 63 |
+
// Extract token from query param
|
| 64 |
+
const url = new URL(req.url, 'http://localhost');
|
| 65 |
+
const token = url.searchParams.get('token');
|
| 66 |
+
|
| 67 |
+
if (!token) {
|
| 68 |
+
nws.close(4001, 'Authentication required');
|
| 69 |
+
return;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
const consumed = consumeEphemeralTokenWithMeta(token, 'ws');
|
| 73 |
+
if (!consumed) {
|
| 74 |
+
nws.close(4001, 'Invalid or expired token');
|
| 75 |
+
return;
|
| 76 |
+
}
|
| 77 |
+
const { userId } = consumed;
|
| 78 |
+
|
| 79 |
+
let row: (User & { password_version?: number }) | undefined;
|
| 80 |
+
row = db.prepare(
|
| 81 |
+
'SELECT id, username, email, role, mfa_enabled, password_version FROM users WHERE id = ?'
|
| 82 |
+
).get(userId) as (User & { password_version?: number }) | undefined;
|
| 83 |
+
if (!row) {
|
| 84 |
+
nws.close(4001, 'User not found');
|
| 85 |
+
return;
|
| 86 |
+
}
|
| 87 |
+
// Session gate (defence-in-depth): reject a ws-token minted before a
|
| 88 |
+
// password change. Tokens carry the pv they were issued with; tokens
|
| 89 |
+
// minted without a pv (legacy) are treated as version 0, matching the
|
| 90 |
+
// JWT `pv` claim semantics in verifyJwtAndLoadUser.
|
| 91 |
+
const tokenPv = typeof consumed.pv === 'number' ? consumed.pv : 0;
|
| 92 |
+
const currentPv = typeof row.password_version === 'number' ? row.password_version : 0;
|
| 93 |
+
if (tokenPv !== currentPv) {
|
| 94 |
+
nws.close(4001, 'Invalid or expired token');
|
| 95 |
+
return;
|
| 96 |
+
}
|
| 97 |
+
// Don't leak password_version beyond the handshake.
|
| 98 |
+
const { password_version: _pv, ...user } = row;
|
| 99 |
+
const requireMfa = (db.prepare("SELECT value FROM app_settings WHERE key = 'require_mfa'").get() as { value: string } | undefined)?.value === 'true';
|
| 100 |
+
const mfaOk = user.mfa_enabled === 1 || user.mfa_enabled === true;
|
| 101 |
+
if (requireMfa && !mfaOk) {
|
| 102 |
+
nws.close(4403, 'MFA required');
|
| 103 |
+
return;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
nws.isAlive = true;
|
| 107 |
+
const sid = nextSocketId++;
|
| 108 |
+
socketId.set(nws, sid);
|
| 109 |
+
socketUser.set(nws, user);
|
| 110 |
+
socketRooms.set(nws, new Set());
|
| 111 |
+
nws.send(JSON.stringify({ type: 'welcome', socketId: sid }));
|
| 112 |
+
|
| 113 |
+
nws.on('pong', () => { nws.isAlive = true; });
|
| 114 |
+
|
| 115 |
+
socketMsgCounts.set(nws, { count: 0, windowStart: Date.now() });
|
| 116 |
+
|
| 117 |
+
nws.on('message', (data) => {
|
| 118 |
+
// Rate limiting
|
| 119 |
+
const rate = socketMsgCounts.get(nws);
|
| 120 |
+
const now = Date.now();
|
| 121 |
+
if (now - rate.windowStart > WS_MSG_WINDOW) {
|
| 122 |
+
rate.count = 1;
|
| 123 |
+
rate.windowStart = now;
|
| 124 |
+
} else {
|
| 125 |
+
rate.count++;
|
| 126 |
+
if (rate.count > WS_MSG_LIMIT) {
|
| 127 |
+
nws.send(JSON.stringify({ type: 'error', message: 'Rate limit exceeded' }));
|
| 128 |
+
return;
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
let msg: { type: string; tripId?: number | string };
|
| 133 |
+
try {
|
| 134 |
+
msg = JSON.parse(data.toString());
|
| 135 |
+
} catch {
|
| 136 |
+
return; // Malformed JSON, ignore
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// Basic validation
|
| 140 |
+
if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') return;
|
| 141 |
+
|
| 142 |
+
if (msg.type === 'join' && msg.tripId) {
|
| 143 |
+
const tripId = Number(msg.tripId);
|
| 144 |
+
// Verify the user has access to this trip
|
| 145 |
+
if (!canAccessTrip(tripId, user.id)) {
|
| 146 |
+
nws.send(JSON.stringify({ type: 'error', message: 'Access denied' }));
|
| 147 |
+
return;
|
| 148 |
+
}
|
| 149 |
+
// Add to room
|
| 150 |
+
if (!rooms.has(tripId)) rooms.set(tripId, new Set());
|
| 151 |
+
rooms.get(tripId).add(nws);
|
| 152 |
+
socketRooms.get(nws).add(tripId);
|
| 153 |
+
nws.send(JSON.stringify({ type: 'joined', tripId }));
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
if (msg.type === 'leave' && msg.tripId) {
|
| 157 |
+
const tripId = Number(msg.tripId);
|
| 158 |
+
leaveRoom(nws, tripId);
|
| 159 |
+
nws.send(JSON.stringify({ type: 'left', tripId }));
|
| 160 |
+
}
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
+
nws.on('close', () => {
|
| 164 |
+
// Clean up all rooms this socket was in
|
| 165 |
+
const myRooms = socketRooms.get(nws);
|
| 166 |
+
if (myRooms) {
|
| 167 |
+
for (const tripId of myRooms) {
|
| 168 |
+
leaveRoom(nws, tripId);
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
});
|
| 172 |
+
});
|
| 173 |
+
|
| 174 |
+
console.log('WebSocket server attached at /ws');
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
function leaveRoom(ws: NomadWebSocket, tripId: number): void {
|
| 178 |
+
const room = rooms.get(tripId);
|
| 179 |
+
if (room) {
|
| 180 |
+
room.delete(ws);
|
| 181 |
+
if (room.size === 0) rooms.delete(tripId);
|
| 182 |
+
}
|
| 183 |
+
const myRooms = socketRooms.get(ws);
|
| 184 |
+
if (myRooms) myRooms.delete(tripId);
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
/**
|
| 188 |
+
* Broadcast an event to all sockets in a trip room, optionally excluding a socket.
|
| 189 |
+
*/
|
| 190 |
+
function broadcast(tripId: number | string, eventType: string, payload: Record<string, unknown>, excludeSid?: number | string): void {
|
| 191 |
+
tripId = Number(tripId);
|
| 192 |
+
const room = rooms.get(tripId);
|
| 193 |
+
if (!room || room.size === 0) return;
|
| 194 |
+
|
| 195 |
+
const excludeNum = excludeSid ? Number(excludeSid) : null;
|
| 196 |
+
|
| 197 |
+
for (const ws of room) {
|
| 198 |
+
if (ws.readyState !== 1) continue; // WebSocket.OPEN === 1
|
| 199 |
+
// Exclude the specific socket that triggered the change
|
| 200 |
+
if (excludeNum && socketId.get(ws) === excludeNum) continue;
|
| 201 |
+
ws.send(JSON.stringify({ type: eventType, tripId, ...payload }));
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
/** Send a message to all sockets belonging to a specific user (e.g., for trip invitations). */
|
| 206 |
+
function broadcastToUser(userId: number, payload: Record<string, unknown>, excludeSid?: number | string): void {
|
| 207 |
+
if (!wss) return;
|
| 208 |
+
const excludeNum = excludeSid ? Number(excludeSid) : null;
|
| 209 |
+
for (const ws of wss.clients) {
|
| 210 |
+
const nws = ws as NomadWebSocket;
|
| 211 |
+
if (nws.readyState !== 1) continue;
|
| 212 |
+
if (excludeNum && socketId.get(nws) === excludeNum) continue;
|
| 213 |
+
const user = socketUser.get(nws);
|
| 214 |
+
if (user?.id === userId) {
|
| 215 |
+
nws.send(JSON.stringify(payload));
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
function getOnlineUserIds(): Set<number> {
|
| 221 |
+
const ids = new Set<number>();
|
| 222 |
+
if (!wss) return ids;
|
| 223 |
+
for (const ws of wss.clients) {
|
| 224 |
+
const nws = ws as NomadWebSocket;
|
| 225 |
+
if (nws.readyState !== 1) continue;
|
| 226 |
+
const user = socketUser.get(nws);
|
| 227 |
+
if (user) ids.add(user.id);
|
| 228 |
+
}
|
| 229 |
+
return ids;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
export { setupWebSocket, broadcast, broadcastToUser, getOnlineUserIds };
|
server/tests/e2e/addons.e2e.test.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* GET /api/addons e2e — exercises the AddonsController through the real
|
| 3 |
+
* JwtAuthGuard against a temp SQLite db. getCollabFeatures + getPhotoProviderConfig
|
| 4 |
+
* are mocked; the addons/photo_providers/photo_provider_fields reads run against
|
| 5 |
+
* the temp db. Asserts the byte-identical body the legacy inline handler produced.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
tmp.exec(`CREATE TABLE addons (id TEXT PRIMARY KEY, name TEXT, type TEXT, icon TEXT, enabled INTEGER, sort_order INTEGER);`);
|
| 22 |
+
tmp.exec(`CREATE TABLE photo_providers (id TEXT PRIMARY KEY, name TEXT, icon TEXT, enabled INTEGER, sort_order INTEGER);`);
|
| 23 |
+
tmp.exec(`CREATE TABLE photo_provider_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, provider_id TEXT, field_key TEXT,
|
| 24 |
+
label TEXT, input_type TEXT, placeholder TEXT, hint TEXT, required INTEGER, secret INTEGER,
|
| 25 |
+
settings_key TEXT, payload_key TEXT, sort_order INTEGER);`);
|
| 26 |
+
return { db: tmp };
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
vi.mock('../../src/db/database', () => ({
|
| 30 |
+
db, canAccessTrip: vi.fn(), isOwner: vi.fn(), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
| 31 |
+
}));
|
| 32 |
+
|
| 33 |
+
const { getCollabFeatures, getBagTracking, getPhotoProviderConfig } = vi.hoisted(() => ({
|
| 34 |
+
getCollabFeatures: vi.fn(() => ({ chat: true, notes: true, polls: true, whatsnext: true })),
|
| 35 |
+
getBagTracking: vi.fn(() => ({ enabled: true })),
|
| 36 |
+
getPhotoProviderConfig: vi.fn(() => ({ url: 'https://immich.example' })),
|
| 37 |
+
}));
|
| 38 |
+
vi.mock('../../src/services/adminService', () => ({ getCollabFeatures, getBagTracking }));
|
| 39 |
+
vi.mock('../../src/services/memories/helpersService', () => ({ getPhotoProviderConfig }));
|
| 40 |
+
|
| 41 |
+
import { AddonsModule } from '../../src/nest/addons/addons.module';
|
| 42 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 43 |
+
|
| 44 |
+
describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
|
| 45 |
+
let server: Server;
|
| 46 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 47 |
+
|
| 48 |
+
async function build() {
|
| 49 |
+
const moduleRef = await Test.createTestingModule({ imports: [AddonsModule] }).compile();
|
| 50 |
+
const nest = moduleRef.createNestApplication();
|
| 51 |
+
nest.use(cookieParser());
|
| 52 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 53 |
+
await nest.init();
|
| 54 |
+
return nest;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
beforeAll(async () => {
|
| 58 |
+
seedUser(db as never, { id: 1 });
|
| 59 |
+
db.prepare("INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('packing','Packing','trip','Backpack',1,1)").run();
|
| 60 |
+
db.prepare("INSERT INTO addons (id, name, type, icon, enabled, sort_order) VALUES ('disabled','Disabled','trip','X',0,2)").run();
|
| 61 |
+
db.prepare("INSERT INTO photo_providers (id, name, icon, enabled, sort_order) VALUES ('immich','Immich','Image',1,1)").run();
|
| 62 |
+
db.prepare(`INSERT INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order)
|
| 63 |
+
VALUES ('immich','base_url','Base URL','text','https://...',NULL,1,0,'immich_url',NULL,1)`).run();
|
| 64 |
+
app = await build();
|
| 65 |
+
server = app.getHttpServer();
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
afterAll(async () => {
|
| 69 |
+
await app.close();
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
it('401 without a cookie', async () => {
|
| 73 |
+
expect((await request(server).get('/api/addons')).status).toBe(401);
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
// Session 1 is a default-role ('user') account — i.e. a non-admin. Asserting the
|
| 77 |
+
// global bagTracking flag here is present is the #1124 regression guard: reading the
|
| 78 |
+
// toggle must not require admin.
|
| 79 |
+
it('200 returns enabled addons + photo providers (disabled addon excluded)', async () => {
|
| 80 |
+
const res = await request(server).get('/api/addons').set('Cookie', sessionCookie(1));
|
| 81 |
+
expect(res.status).toBe(200);
|
| 82 |
+
expect(res.body).toEqual({
|
| 83 |
+
collabFeatures: { chat: true, notes: true, polls: true, whatsnext: true },
|
| 84 |
+
bagTracking: true,
|
| 85 |
+
addons: [
|
| 86 |
+
{ id: 'packing', name: 'Packing', type: 'trip', icon: 'Backpack', enabled: true },
|
| 87 |
+
{
|
| 88 |
+
id: 'immich',
|
| 89 |
+
name: 'Immich',
|
| 90 |
+
type: 'photo_provider',
|
| 91 |
+
icon: 'Image',
|
| 92 |
+
enabled: true,
|
| 93 |
+
config: { url: 'https://immich.example' },
|
| 94 |
+
fields: [
|
| 95 |
+
{
|
| 96 |
+
key: 'base_url',
|
| 97 |
+
label: 'Base URL',
|
| 98 |
+
input_type: 'text',
|
| 99 |
+
placeholder: 'https://...',
|
| 100 |
+
hint: null,
|
| 101 |
+
required: true,
|
| 102 |
+
secret: false,
|
| 103 |
+
settings_key: 'immich_url',
|
| 104 |
+
payload_key: null,
|
| 105 |
+
sort_order: 1,
|
| 106 |
+
},
|
| 107 |
+
],
|
| 108 |
+
},
|
| 109 |
+
],
|
| 110 |
+
});
|
| 111 |
+
});
|
| 112 |
+
});
|
server/tests/e2e/admin.e2e.test.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Admin e2e — exercises the migrated /api/admin endpoints through the real
|
| 3 |
+
* JwtAuthGuard + AdminGuard against a temp SQLite db. The admin service +
|
| 4 |
+
* helpers are mocked; this focuses on auth (401), the admin gate (403 for a
|
| 5 |
+
* non-admin), create-201, validation 400 and the dev-only 404.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
return { db: tmp };
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 25 |
+
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: () => '1.2.3.4', logInfo: vi.fn() }));
|
| 26 |
+
vi.mock('../../src/mcp', () => ({ invalidateMcpSessions: vi.fn() }));
|
| 27 |
+
vi.mock('../../src/services/notificationPreferencesService', () => ({ getPreferencesMatrix: vi.fn(() => ({})), setAdminPreferences: vi.fn() }));
|
| 28 |
+
vi.mock('../../src/services/settingsService', () => ({ getAdminUserDefaults: vi.fn(() => ({})), setAdminUserDefaults: vi.fn() }));
|
| 29 |
+
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
| 30 |
+
|
| 31 |
+
const { adminSvc } = vi.hoisted(() => ({
|
| 32 |
+
adminSvc: { listUsers: vi.fn(), createUser: vi.fn(), updatePlacesPhotos: vi.fn() },
|
| 33 |
+
}));
|
| 34 |
+
vi.mock('../../src/services/adminService', () => adminSvc);
|
| 35 |
+
|
| 36 |
+
import { AdminModule } from '../../src/nest/admin/admin.module';
|
| 37 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 38 |
+
|
| 39 |
+
describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
|
| 40 |
+
let server: Server;
|
| 41 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 42 |
+
|
| 43 |
+
async function build() {
|
| 44 |
+
const moduleRef = await Test.createTestingModule({ imports: [AdminModule] }).compile();
|
| 45 |
+
const nest = moduleRef.createNestApplication();
|
| 46 |
+
nest.use(cookieParser());
|
| 47 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 48 |
+
await nest.init();
|
| 49 |
+
return nest;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
beforeAll(async () => {
|
| 53 |
+
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' });
|
| 54 |
+
seedUser(db as never, { id: 2, role: 'user', email: 'member@example.test' });
|
| 55 |
+
app = await build();
|
| 56 |
+
server = app.getHttpServer();
|
| 57 |
+
adminSvc.listUsers.mockReturnValue([{ id: 1 }]);
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
beforeEach(() => { delete process.env.NODE_ENV; });
|
| 61 |
+
|
| 62 |
+
afterAll(async () => {
|
| 63 |
+
await app.close();
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
it('401 without a session', async () => {
|
| 67 |
+
expect((await request(server).get('/api/admin/users')).status).toBe(401);
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
it('403 for a non-admin', async () => {
|
| 71 |
+
const res = await request(server).get('/api/admin/users').set('Cookie', sessionCookie(2));
|
| 72 |
+
expect(res.status).toBe(403);
|
| 73 |
+
expect(res.body).toEqual({ error: 'Admin access required' });
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
it('200 list for an admin', async () => {
|
| 77 |
+
const res = await request(server).get('/api/admin/users').set('Cookie', sessionCookie(1));
|
| 78 |
+
expect(res.status).toBe(200);
|
| 79 |
+
expect(res.body).toEqual({ users: [{ id: 1 }] });
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
it('201 on user create', async () => {
|
| 83 |
+
adminSvc.createUser.mockReturnValue({ user: { id: 3 }, insertedId: 3, auditDetails: {} });
|
| 84 |
+
const res = await request(server).post('/api/admin/users').set('Cookie', sessionCookie(1)).send({ email: 'new@x.y' });
|
| 85 |
+
expect(res.status).toBe(201);
|
| 86 |
+
expect(res.body).toEqual({ user: { id: 3 } });
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it('400 on a non-boolean feature toggle', async () => {
|
| 90 |
+
const res = await request(server).put('/api/admin/places-photos').set('Cookie', sessionCookie(1)).send({ enabled: 'yes' });
|
| 91 |
+
expect(res.status).toBe(400);
|
| 92 |
+
expect(res.body).toEqual({ error: 'enabled must be a boolean' });
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('404 on the dev-only test-notification outside development', async () => {
|
| 96 |
+
const res = await request(server).post('/api/admin/dev/test-notification').set('Cookie', sessionCookie(1)).send({});
|
| 97 |
+
expect(res.status).toBe(404);
|
| 98 |
+
});
|
| 99 |
+
});
|
server/tests/e2e/airports.e2e.test.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Airports module e2e — exercises the migrated /api/airports endpoints through
|
| 3 |
+
* the real JwtAuthGuard against a temp SQLite db (seeded via the shared harness).
|
| 4 |
+
* The airport service is mocked so the test doesn't depend on the bundled dataset.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 24 |
+
|
| 25 |
+
const { mockSearch, mockFindByIata } = vi.hoisted(() => ({ mockSearch: vi.fn(), mockFindByIata: vi.fn() }));
|
| 26 |
+
vi.mock('../../src/services/airportService', async (importActual) => {
|
| 27 |
+
const actual = await importActual<typeof import('../../src/services/airportService')>();
|
| 28 |
+
return { ...actual, searchAirports: mockSearch, findByIata: mockFindByIata };
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
import { AirportsModule } from '../../src/nest/airports/airports.module';
|
| 32 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 33 |
+
|
| 34 |
+
const BER = {
|
| 35 |
+
iata: 'BER', icao: 'EDDB', name: 'Berlin Brandenburg', city: 'Berlin',
|
| 36 |
+
country: 'DE', lat: 52.36, lng: 13.5, tz: 'Europe/Berlin',
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
describe('Airports e2e (real auth guard + temp SQLite)', () => {
|
| 40 |
+
let server: Server;
|
| 41 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 42 |
+
|
| 43 |
+
async function build() {
|
| 44 |
+
const moduleRef = await Test.createTestingModule({ imports: [AirportsModule] }).compile();
|
| 45 |
+
const nest = moduleRef.createNestApplication();
|
| 46 |
+
nest.use(cookieParser());
|
| 47 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 48 |
+
await nest.init();
|
| 49 |
+
return nest;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
beforeAll(async () => {
|
| 53 |
+
seedUser(db as never, { id: 1 });
|
| 54 |
+
app = await build();
|
| 55 |
+
server = app.getHttpServer();
|
| 56 |
+
mockSearch.mockReturnValue([BER]);
|
| 57 |
+
mockFindByIata.mockImplementation((code: string) => (code === 'BER' ? BER : null));
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
afterAll(async () => {
|
| 61 |
+
await app.close();
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
it('401 { error, code } without a session cookie', async () => {
|
| 65 |
+
const res = await request(server).get('/api/airports/search').query({ q: 'ber' });
|
| 66 |
+
expect(res.status).toBe(401);
|
| 67 |
+
expect(res.body).toEqual({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
it('200 with results for a query', async () => {
|
| 71 |
+
const res = await request(server).get('/api/airports/search').set('Cookie', sessionCookie(1)).query({ q: 'ber' });
|
| 72 |
+
expect(res.status).toBe(200);
|
| 73 |
+
expect(res.body).toEqual([BER]);
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
it('200 [] for a missing query without hitting the service', async () => {
|
| 77 |
+
mockSearch.mockClear();
|
| 78 |
+
const res = await request(server).get('/api/airports/search').set('Cookie', sessionCookie(1));
|
| 79 |
+
expect(res.status).toBe(200);
|
| 80 |
+
expect(res.body).toEqual([]);
|
| 81 |
+
expect(mockSearch).not.toHaveBeenCalled();
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it('200 for a known IATA code', async () => {
|
| 85 |
+
const res = await request(server).get('/api/airports/BER').set('Cookie', sessionCookie(1));
|
| 86 |
+
expect(res.status).toBe(200);
|
| 87 |
+
expect(res.body).toEqual(BER);
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
it('404 { error } for an unknown IATA code', async () => {
|
| 91 |
+
const res = await request(server).get('/api/airports/ZZZ').set('Cookie', sessionCookie(1));
|
| 92 |
+
expect(res.status).toBe(404);
|
| 93 |
+
expect(res.body).toEqual({ error: 'Airport not found' });
|
| 94 |
+
});
|
| 95 |
+
});
|
server/tests/e2e/assignments.e2e.test.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Assignments module e2e — exercises both migrated controllers through the real
|
| 3 |
+
* JwtAuthGuard against a temp SQLite db. assignmentService, journeyService,
|
| 4 |
+
* the permission check, canAccessTrip and the WebSocket broadcast are mocked.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
| 24 |
+
vi.mock('../../src/db/database', () => ({
|
| 25 |
+
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
| 26 |
+
}));
|
| 27 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 28 |
+
vi.mock('../../src/services/journeyService', () => ({ onPlaceCreated: vi.fn() }));
|
| 29 |
+
|
| 30 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 31 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 32 |
+
|
| 33 |
+
const { asg } = vi.hoisted(() => ({
|
| 34 |
+
asg: {
|
| 35 |
+
getAssignmentWithPlace: vi.fn(), listDayAssignments: vi.fn(), dayExists: vi.fn(), placeExists: vi.fn(),
|
| 36 |
+
createAssignment: vi.fn(), assignmentExistsInDay: vi.fn(), deleteAssignment: vi.fn(), reorderAssignments: vi.fn(),
|
| 37 |
+
getAssignmentForTrip: vi.fn(), moveAssignment: vi.fn(), getParticipants: vi.fn(), updateTime: vi.fn(), setParticipants: vi.fn(),
|
| 38 |
+
},
|
| 39 |
+
}));
|
| 40 |
+
vi.mock('../../src/services/assignmentService', () => asg);
|
| 41 |
+
|
| 42 |
+
import { AssignmentsModule } from '../../src/nest/assignments/assignments.module';
|
| 43 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 44 |
+
|
| 45 |
+
describe('Assignments e2e (real auth guard + temp SQLite)', () => {
|
| 46 |
+
let server: Server;
|
| 47 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 48 |
+
|
| 49 |
+
async function build() {
|
| 50 |
+
const moduleRef = await Test.createTestingModule({ imports: [AssignmentsModule] }).compile();
|
| 51 |
+
const nest = moduleRef.createNestApplication();
|
| 52 |
+
nest.use(cookieParser());
|
| 53 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 54 |
+
await nest.init();
|
| 55 |
+
return nest;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
beforeAll(async () => {
|
| 59 |
+
seedUser(db as never, { id: 1 });
|
| 60 |
+
app = await build();
|
| 61 |
+
server = app.getHttpServer();
|
| 62 |
+
asg.listDayAssignments.mockReturnValue([{ id: 1 }]);
|
| 63 |
+
asg.createAssignment.mockReturnValue({ id: 9 });
|
| 64 |
+
asg.getParticipants.mockReturnValue([{ user_id: 2 }]);
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
beforeEach(() => {
|
| 68 |
+
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
| 69 |
+
checkPermission.mockReturnValue(true);
|
| 70 |
+
asg.dayExists.mockReturnValue(true);
|
| 71 |
+
asg.placeExists.mockReturnValue(true);
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
afterAll(async () => {
|
| 75 |
+
await app.close();
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
it('401 without a cookie', async () => {
|
| 79 |
+
expect((await request(server).get('/api/trips/5/days/3/assignments')).status).toBe(401);
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
it('200 list day-assignments', async () => {
|
| 83 |
+
const res = await request(server).get('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1));
|
| 84 |
+
expect(res.status).toBe(200);
|
| 85 |
+
expect(res.body).toEqual({ assignments: [{ id: 1 }] });
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
it('201 create, 404 place', async () => {
|
| 89 |
+
const ok = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1)).send({ place_id: 2 });
|
| 90 |
+
expect(ok.status).toBe(201);
|
| 91 |
+
expect(ok.body).toEqual({ assignment: { id: 9 } });
|
| 92 |
+
asg.placeExists.mockReturnValue(false);
|
| 93 |
+
const miss = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1)).send({ place_id: 99 });
|
| 94 |
+
expect(miss.status).toBe(404);
|
| 95 |
+
expect(miss.body).toEqual({ error: 'Place not found' });
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
it('200 participants (access-only)', async () => {
|
| 99 |
+
const res = await request(server).get('/api/trips/5/assignments/9/participants').set('Cookie', sessionCookie(1));
|
| 100 |
+
expect(res.status).toBe(200);
|
| 101 |
+
expect(res.body).toEqual({ participants: [{ user_id: 2 }] });
|
| 102 |
+
});
|
| 103 |
+
|
| 104 |
+
it('400 set participants with non-array', async () => {
|
| 105 |
+
const res = await request(server).put('/api/trips/5/assignments/9/participants').set('Cookie', sessionCookie(1)).send({ user_ids: 'no' });
|
| 106 |
+
expect(res.status).toBe(400);
|
| 107 |
+
expect(res.body).toEqual({ error: 'user_ids must be an array' });
|
| 108 |
+
});
|
| 109 |
+
});
|
server/tests/e2e/atlas.e2e.test.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Atlas module e2e — exercises the migrated /api/addons/atlas endpoints through
|
| 3 |
+
* the real JwtAuthGuard against a temp SQLite db. atlasService is mocked; this
|
| 4 |
+
* focuses on auth, status codes (mark POSTs stay 200), the cache headers and the
|
| 5 |
+
* bespoke 400/404 bodies.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
return { db: tmp };
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 25 |
+
|
| 26 |
+
const { mocks } = vi.hoisted(() => ({
|
| 27 |
+
mocks: {
|
| 28 |
+
getStats: vi.fn(),
|
| 29 |
+
getCountryPlaces: vi.fn(),
|
| 30 |
+
markCountryVisited: vi.fn(),
|
| 31 |
+
unmarkCountryVisited: vi.fn(),
|
| 32 |
+
markRegionVisited: vi.fn(),
|
| 33 |
+
unmarkRegionVisited: vi.fn(),
|
| 34 |
+
getVisitedRegions: vi.fn(),
|
| 35 |
+
getRegionGeo: vi.fn(),
|
| 36 |
+
getCountryGeo: vi.fn(),
|
| 37 |
+
listBucketList: vi.fn(),
|
| 38 |
+
createBucketItem: vi.fn(),
|
| 39 |
+
updateBucketItem: vi.fn(),
|
| 40 |
+
deleteBucketItem: vi.fn(),
|
| 41 |
+
},
|
| 42 |
+
}));
|
| 43 |
+
vi.mock('../../src/services/atlasService', () => mocks);
|
| 44 |
+
|
| 45 |
+
import { AtlasModule } from '../../src/nest/atlas/atlas.module';
|
| 46 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 47 |
+
|
| 48 |
+
describe('Atlas e2e (real auth guard + temp SQLite)', () => {
|
| 49 |
+
let server: Server;
|
| 50 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 51 |
+
|
| 52 |
+
async function build() {
|
| 53 |
+
const moduleRef = await Test.createTestingModule({ imports: [AtlasModule] }).compile();
|
| 54 |
+
const nest = moduleRef.createNestApplication();
|
| 55 |
+
nest.use(cookieParser());
|
| 56 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 57 |
+
await nest.init();
|
| 58 |
+
return nest;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
beforeAll(async () => {
|
| 62 |
+
seedUser(db as never, { id: 1 });
|
| 63 |
+
app = await build();
|
| 64 |
+
server = app.getHttpServer();
|
| 65 |
+
mocks.getStats.mockResolvedValue({ countries: 3 });
|
| 66 |
+
mocks.markCountryVisited.mockReturnValue(undefined);
|
| 67 |
+
mocks.listBucketList.mockReturnValue([{ id: 1, name: 'Tokyo' }]);
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
afterAll(async () => {
|
| 71 |
+
await app.close();
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
it('401 without a session cookie', async () => {
|
| 75 |
+
const res = await request(server).get('/api/addons/atlas/stats');
|
| 76 |
+
expect(res.status).toBe(401);
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
it('200 countries/geo returns the admin-0 FeatureCollection', async () => {
|
| 80 |
+
mocks.getCountryGeo.mockReturnValue({ type: 'FeatureCollection', features: [{ id: 'NO' }] });
|
| 81 |
+
const res = await request(server).get('/api/addons/atlas/countries/geo').set('Cookie', sessionCookie(1));
|
| 82 |
+
expect(res.status).toBe(200);
|
| 83 |
+
expect(res.body.type).toBe('FeatureCollection');
|
| 84 |
+
expect(res.headers['cache-control']).toContain('max-age=86400');
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
it('200 stats for an authenticated user', async () => {
|
| 88 |
+
const res = await request(server).get('/api/addons/atlas/stats').set('Cookie', sessionCookie(1));
|
| 89 |
+
expect(res.status).toBe(200);
|
| 90 |
+
expect(res.body).toEqual({ countries: 3 });
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it('200 (not 201) on POST country mark, with upper-cased code', async () => {
|
| 94 |
+
const res = await request(server).post('/api/addons/atlas/country/de/mark').set('Cookie', sessionCookie(1));
|
| 95 |
+
expect(res.status).toBe(200);
|
| 96 |
+
expect(res.body).toEqual({ success: true });
|
| 97 |
+
expect(mocks.markCountryVisited).toHaveBeenCalledWith(1, 'DE');
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
it('400 on region mark without name/country_code', async () => {
|
| 101 |
+
const res = await request(server).post('/api/addons/atlas/region/by/mark').set('Cookie', sessionCookie(1)).send({ name: 'Bavaria' });
|
| 102 |
+
expect(res.status).toBe(400);
|
| 103 |
+
expect(res.body).toEqual({ error: 'name and country_code are required' });
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
it('no-store cache header on /regions', async () => {
|
| 107 |
+
mocks.getVisitedRegions.mockResolvedValue({ regions: {} });
|
| 108 |
+
const res = await request(server).get('/api/addons/atlas/regions').set('Cookie', sessionCookie(1));
|
| 109 |
+
expect(res.status).toBe(200);
|
| 110 |
+
expect(res.headers['cache-control']).toBe('no-cache, no-store');
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it('empty FeatureCollection (no cache header) when /regions/geo has no countries', async () => {
|
| 114 |
+
const res = await request(server).get('/api/addons/atlas/regions/geo').set('Cookie', sessionCookie(1));
|
| 115 |
+
expect(res.status).toBe(200);
|
| 116 |
+
expect(res.body).toEqual({ type: 'FeatureCollection', features: [] });
|
| 117 |
+
expect(res.headers['cache-control']).toBeUndefined();
|
| 118 |
+
});
|
| 119 |
+
|
| 120 |
+
it('201 on bucket-list create', async () => {
|
| 121 |
+
mocks.createBucketItem.mockReturnValue({ id: 2, name: 'Kyoto' });
|
| 122 |
+
const res = await request(server).post('/api/addons/atlas/bucket-list').set('Cookie', sessionCookie(1)).send({ name: 'Kyoto' });
|
| 123 |
+
expect(res.status).toBe(201);
|
| 124 |
+
expect(res.body).toEqual({ item: { id: 2, name: 'Kyoto' } });
|
| 125 |
+
});
|
| 126 |
+
|
| 127 |
+
it('404 on delete of a missing bucket item', async () => {
|
| 128 |
+
mocks.deleteBucketItem.mockReturnValue(false);
|
| 129 |
+
const res = await request(server).delete('/api/addons/atlas/bucket-list/9').set('Cookie', sessionCookie(1));
|
| 130 |
+
expect(res.status).toBe(404);
|
| 131 |
+
expect(res.body).toEqual({ error: 'Item not found' });
|
| 132 |
+
});
|
| 133 |
+
});
|
server/tests/e2e/auth.e2e.test.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Auth e2e — exercises the migrated /api/auth endpoints through the real
|
| 3 |
+
* JwtAuthGuard/OptionalJwtGuard AND the real cookie service against a temp
|
| 4 |
+
* SQLite db. Only the authService (credential/MFA logic) + audit/notifications
|
| 5 |
+
* are mocked; this proves the httpOnly trek_session cookie is set on login and
|
| 6 |
+
* cleared on logout, that /me requires a session, and that /app-config is
|
| 7 |
+
* optional-auth.
|
| 8 |
+
*/
|
| 9 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 10 |
+
import request from 'supertest';
|
| 11 |
+
import cookieParser from 'cookie-parser';
|
| 12 |
+
import type { Server } from 'http';
|
| 13 |
+
import { Test } from '@nestjs/testing';
|
| 14 |
+
import { seedUser, sessionCookie } from './harness';
|
| 15 |
+
|
| 16 |
+
const { db } = vi.hoisted(() => {
|
| 17 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 18 |
+
const Database = require('better-sqlite3');
|
| 19 |
+
const tmp = new Database(':memory:');
|
| 20 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 21 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 22 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 23 |
+
return { db: tmp };
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 27 |
+
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4') }));
|
| 28 |
+
vi.mock('../../src/services/notifications', () => ({ getAppUrl: () => 'https://x', sendPasswordResetEmail: vi.fn().mockResolvedValue({ delivered: true }) }));
|
| 29 |
+
|
| 30 |
+
const { authSvc } = vi.hoisted(() => ({
|
| 31 |
+
authSvc: {
|
| 32 |
+
getAppConfig: vi.fn(), demoLogin: vi.fn(), validateInviteToken: vi.fn(), registerUser: vi.fn(), loginUser: vi.fn(),
|
| 33 |
+
requestPasswordReset: vi.fn(), resetPassword: vi.fn(), verifyMfaLogin: vi.fn(), getCurrentUser: vi.fn(),
|
| 34 |
+
changePassword: vi.fn(), deleteAccount: vi.fn(), updateMapsKey: vi.fn(), updateApiKeys: vi.fn(), updateSettings: vi.fn(),
|
| 35 |
+
getSettings: vi.fn(), saveAvatar: vi.fn(), deleteAvatar: vi.fn(), listUsers: vi.fn(), validateKeys: vi.fn(),
|
| 36 |
+
getAppSettings: vi.fn(), updateAppSettings: vi.fn(), getTravelStats: vi.fn(), setupMfa: vi.fn(), enableMfa: vi.fn(),
|
| 37 |
+
disableMfa: vi.fn(), listMcpTokens: vi.fn(), createMcpToken: vi.fn(), deleteMcpToken: vi.fn(), createWsToken: vi.fn(),
|
| 38 |
+
createResourceToken: vi.fn(),
|
| 39 |
+
},
|
| 40 |
+
}));
|
| 41 |
+
vi.mock('../../src/services/authService', () => authSvc);
|
| 42 |
+
|
| 43 |
+
import { AuthModule } from '../../src/nest/auth/auth.module';
|
| 44 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 45 |
+
|
| 46 |
+
describe('Auth e2e (real auth guard + real cookie service + temp SQLite)', () => {
|
| 47 |
+
let server: Server;
|
| 48 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 49 |
+
|
| 50 |
+
async function build() {
|
| 51 |
+
const moduleRef = await Test.createTestingModule({ imports: [AuthModule] }).compile();
|
| 52 |
+
const nest = moduleRef.createNestApplication();
|
| 53 |
+
nest.use(cookieParser());
|
| 54 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 55 |
+
await nest.init();
|
| 56 |
+
return nest;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
beforeAll(async () => {
|
| 60 |
+
seedUser(db as never, { id: 1, email: 'u@example.test' });
|
| 61 |
+
app = await build();
|
| 62 |
+
server = app.getHttpServer();
|
| 63 |
+
authSvc.getAppConfig.mockReturnValue({ version: '3' });
|
| 64 |
+
authSvc.loginUser.mockReturnValue({ token: 'jwt.token.value', user: { id: 1 } });
|
| 65 |
+
authSvc.getCurrentUser.mockReturnValue({ id: 1, email: 'u@example.test' });
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
beforeEach(() => vi.clearAllMocks());
|
| 69 |
+
|
| 70 |
+
afterAll(async () => {
|
| 71 |
+
await app.close();
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
it('GET /app-config is optional-auth (200 without a cookie)', async () => {
|
| 75 |
+
authSvc.getAppConfig.mockReturnValue({ version: '3' });
|
| 76 |
+
const res = await request(server).get('/api/auth/app-config');
|
| 77 |
+
expect(res.status).toBe(200);
|
| 78 |
+
expect(res.body).toEqual({ version: '3' });
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('GET /me requires a session (401 without a cookie)', async () => {
|
| 82 |
+
expect((await request(server).get('/api/auth/me')).status).toBe(401);
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
it('GET /me returns the user with a valid session', async () => {
|
| 86 |
+
authSvc.getCurrentUser.mockReturnValue({ id: 1, email: 'u@example.test' });
|
| 87 |
+
const res = await request(server).get('/api/auth/me').set('Cookie', sessionCookie(1));
|
| 88 |
+
expect(res.status).toBe(200);
|
| 89 |
+
expect(res.body).toEqual({ user: { id: 1, email: 'u@example.test' } });
|
| 90 |
+
});
|
| 91 |
+
|
| 92 |
+
it('POST /login sets the httpOnly trek_session cookie', async () => {
|
| 93 |
+
authSvc.loginUser.mockReturnValue({ token: 'jwt.token.value', user: { id: 1 } });
|
| 94 |
+
const res = await request(server).post('/api/auth/login').send({ email: 'u@example.test', password: 'pw' });
|
| 95 |
+
expect(res.status).toBe(200);
|
| 96 |
+
expect(res.body).toEqual({ token: 'jwt.token.value', user: { id: 1 } });
|
| 97 |
+
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
| 98 |
+
expect(setCookie.some((c) => c.startsWith('trek_session=') && /HttpOnly/i.test(c))).toBe(true);
|
| 99 |
+
}, 10000);
|
| 100 |
+
|
| 101 |
+
it('POST /login with remember_me sets a persistent cookie (Max-Age present)', async () => {
|
| 102 |
+
authSvc.loginUser.mockReturnValue({ token: 'jwt.token.value', user: { id: 1 }, remember: true });
|
| 103 |
+
const res = await request(server).post('/api/auth/login').send({ email: 'u@example.test', password: 'pw', remember_me: true });
|
| 104 |
+
expect(res.status).toBe(200);
|
| 105 |
+
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
| 106 |
+
const cookie = setCookie.find((c) => c.startsWith('trek_session='))!;
|
| 107 |
+
expect(cookie).toMatch(/Max-Age=\d+/i);
|
| 108 |
+
// 30d default — well above the 24h (86400s) non-remember window.
|
| 109 |
+
const maxAge = Number(/Max-Age=(\d+)/i.exec(cookie)?.[1]);
|
| 110 |
+
expect(maxAge).toBeGreaterThan(86_400);
|
| 111 |
+
}, 10000);
|
| 112 |
+
|
| 113 |
+
it('POST /login without remember_me sets a session cookie (no Max-Age)', async () => {
|
| 114 |
+
authSvc.loginUser.mockReturnValue({ token: 'jwt.token.value', user: { id: 1 }, remember: false });
|
| 115 |
+
const res = await request(server).post('/api/auth/login').send({ email: 'u@example.test', password: 'pw' });
|
| 116 |
+
expect(res.status).toBe(200);
|
| 117 |
+
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
| 118 |
+
const cookie = setCookie.find((c) => c.startsWith('trek_session='))!;
|
| 119 |
+
expect(cookie).not.toMatch(/Max-Age/i);
|
| 120 |
+
expect(cookie).not.toMatch(/Expires/i);
|
| 121 |
+
}, 10000);
|
| 122 |
+
|
| 123 |
+
it('POST /logout clears the session cookie', async () => {
|
| 124 |
+
const res = await request(server).post('/api/auth/logout');
|
| 125 |
+
expect(res.status).toBe(200);
|
| 126 |
+
expect(res.body).toEqual({ success: true });
|
| 127 |
+
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
| 128 |
+
expect(setCookie.some((c) => c.startsWith('trek_session='))).toBe(true);
|
| 129 |
+
});
|
| 130 |
+
});
|
server/tests/e2e/backup.e2e.test.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Backup e2e — exercises the migrated /api/backup endpoints through the real
|
| 3 |
+
* JwtAuthGuard + AdminGuard against a temp SQLite db. The backup service +
|
| 4 |
+
* audit log are mocked; this focuses on auth (401), the admin gate (403 for a
|
| 5 |
+
* non-admin), the rate-limit 429, filename guards and status codes.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
return { db: tmp };
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 25 |
+
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4') }));
|
| 26 |
+
|
| 27 |
+
const { backupSvc } = vi.hoisted(() => ({
|
| 28 |
+
backupSvc: {
|
| 29 |
+
listBackups: vi.fn(), createBackup: vi.fn(), restoreFromZip: vi.fn(), getAutoSettings: vi.fn(),
|
| 30 |
+
updateAutoSettings: vi.fn(), deleteBackup: vi.fn(), isValidBackupFilename: vi.fn(), backupFilePath: vi.fn(),
|
| 31 |
+
backupFileExists: vi.fn(), checkRateLimit: vi.fn(), getUploadTmpDir: () => '/tmp', BACKUP_RATE_WINDOW: 3600000,
|
| 32 |
+
MAX_BACKUP_UPLOAD_SIZE: 1024,
|
| 33 |
+
},
|
| 34 |
+
}));
|
| 35 |
+
vi.mock('../../src/services/backupService', () => backupSvc);
|
| 36 |
+
|
| 37 |
+
import { BackupModule } from '../../src/nest/backup/backup.module';
|
| 38 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 39 |
+
|
| 40 |
+
describe('Backup e2e (real auth + admin guard + temp SQLite)', () => {
|
| 41 |
+
let server: Server;
|
| 42 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 43 |
+
|
| 44 |
+
async function build() {
|
| 45 |
+
const moduleRef = await Test.createTestingModule({ imports: [BackupModule] }).compile();
|
| 46 |
+
const nest = moduleRef.createNestApplication();
|
| 47 |
+
nest.use(cookieParser());
|
| 48 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 49 |
+
await nest.init();
|
| 50 |
+
return nest;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
beforeAll(async () => {
|
| 54 |
+
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' });
|
| 55 |
+
seedUser(db as never, { id: 2, role: 'user', email: 'member@example.test' });
|
| 56 |
+
app = await build();
|
| 57 |
+
server = app.getHttpServer();
|
| 58 |
+
backupSvc.listBackups.mockReturnValue([{ filename: 'a.zip', size: 1 }]);
|
| 59 |
+
backupSvc.createBackup.mockResolvedValue({ filename: 'b.zip', size: 10 });
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
+
beforeEach(() => {
|
| 63 |
+
backupSvc.isValidBackupFilename.mockReturnValue(true);
|
| 64 |
+
backupSvc.backupFileExists.mockReturnValue(true);
|
| 65 |
+
backupSvc.checkRateLimit.mockReturnValue(true);
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
afterAll(async () => {
|
| 69 |
+
await app.close();
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
it('401 without a session cookie', async () => {
|
| 73 |
+
expect((await request(server).get('/api/backup/list')).status).toBe(401);
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
it('403 for a non-admin', async () => {
|
| 77 |
+
const res = await request(server).get('/api/backup/list').set('Cookie', sessionCookie(2));
|
| 78 |
+
expect(res.status).toBe(403);
|
| 79 |
+
expect(res.body).toEqual({ error: 'Admin access required' });
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
it('200 list for an admin', async () => {
|
| 83 |
+
const res = await request(server).get('/api/backup/list').set('Cookie', sessionCookie(1));
|
| 84 |
+
expect(res.status).toBe(200);
|
| 85 |
+
expect(res.body).toEqual({ backups: [{ filename: 'a.zip', size: 1 }] });
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
it('429 when create is rate-limited', async () => {
|
| 89 |
+
backupSvc.checkRateLimit.mockReturnValue(false);
|
| 90 |
+
const res = await request(server).post('/api/backup/create').set('Cookie', sessionCookie(1));
|
| 91 |
+
expect(res.status).toBe(429);
|
| 92 |
+
expect(res.body).toEqual({ error: 'Too many backup requests. Please try again later.' });
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('400 on an invalid download filename', async () => {
|
| 96 |
+
backupSvc.isValidBackupFilename.mockReturnValue(false);
|
| 97 |
+
const res = await request(server).get('/api/backup/download/bad').set('Cookie', sessionCookie(1));
|
| 98 |
+
expect(res.status).toBe(400);
|
| 99 |
+
expect(res.body).toEqual({ error: 'Invalid filename' });
|
| 100 |
+
});
|
| 101 |
+
|
| 102 |
+
it('404 deleting a missing backup', async () => {
|
| 103 |
+
backupSvc.backupFileExists.mockReturnValue(false);
|
| 104 |
+
const res = await request(server).delete('/api/backup/x.zip').set('Cookie', sessionCookie(1));
|
| 105 |
+
expect(res.status).toBe(404);
|
| 106 |
+
expect(res.body).toEqual({ error: 'Backup not found' });
|
| 107 |
+
});
|
| 108 |
+
});
|
server/tests/e2e/budget.e2e.test.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Budget module e2e — exercises the migrated /api/trips/:tripId/budget endpoints
|
| 3 |
+
* through the real JwtAuthGuard against a temp SQLite db. budgetService, the
|
| 4 |
+
* permission check and the WebSocket broadcast are mocked.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 24 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 25 |
+
|
| 26 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 27 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 28 |
+
|
| 29 |
+
const { svc } = vi.hoisted(() => ({
|
| 30 |
+
svc: {
|
| 31 |
+
verifyTripAccess: vi.fn(), listBudgetItems: vi.fn(), createBudgetItem: vi.fn(), updateBudgetItem: vi.fn(),
|
| 32 |
+
deleteBudgetItem: vi.fn(), updateMembers: vi.fn(), toggleMemberPaid: vi.fn(), getPerPersonSummary: vi.fn(),
|
| 33 |
+
calculateSettlement: vi.fn(), reorderBudgetItems: vi.fn(), reorderBudgetCategories: vi.fn(),
|
| 34 |
+
},
|
| 35 |
+
}));
|
| 36 |
+
vi.mock('../../src/services/budgetService', () => svc);
|
| 37 |
+
|
| 38 |
+
import { BudgetModule } from '../../src/nest/budget/budget.module';
|
| 39 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 40 |
+
|
| 41 |
+
describe('Budget e2e (real auth guard + temp SQLite)', () => {
|
| 42 |
+
let server: Server;
|
| 43 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 44 |
+
|
| 45 |
+
async function build() {
|
| 46 |
+
const moduleRef = await Test.createTestingModule({ imports: [BudgetModule] }).compile();
|
| 47 |
+
const nest = moduleRef.createNestApplication();
|
| 48 |
+
nest.use(cookieParser());
|
| 49 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 50 |
+
await nest.init();
|
| 51 |
+
return nest;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
beforeAll(async () => {
|
| 55 |
+
seedUser(db as never, { id: 1 });
|
| 56 |
+
app = await build();
|
| 57 |
+
server = app.getHttpServer();
|
| 58 |
+
svc.listBudgetItems.mockReturnValue([{ id: 1, name: 'Hotel' }]);
|
| 59 |
+
svc.createBudgetItem.mockReturnValue({ id: 9, name: 'Hotel' });
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
+
beforeEach(() => {
|
| 63 |
+
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
| 64 |
+
checkPermission.mockReturnValue(true);
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
afterAll(async () => {
|
| 68 |
+
await app.close();
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
it('401 without a session cookie', async () => {
|
| 72 |
+
const res = await request(server).get('/api/trips/5/budget');
|
| 73 |
+
expect(res.status).toBe(401);
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
it('200 list for an accessible trip', async () => {
|
| 77 |
+
const res = await request(server).get('/api/trips/5/budget').set('Cookie', sessionCookie(1));
|
| 78 |
+
expect(res.status).toBe(200);
|
| 79 |
+
expect(res.body).toEqual({ items: [{ id: 1, name: 'Hotel' }] });
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
it('404 when the trip is not accessible', async () => {
|
| 83 |
+
svc.verifyTripAccess.mockReturnValue(undefined);
|
| 84 |
+
const res = await request(server).get('/api/trips/5/budget').set('Cookie', sessionCookie(1));
|
| 85 |
+
expect(res.status).toBe(404);
|
| 86 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it('201 on create with permission', async () => {
|
| 90 |
+
const res = await request(server).post('/api/trips/5/budget').set('Cookie', sessionCookie(1)).send({ name: 'Hotel' });
|
| 91 |
+
expect(res.status).toBe(201);
|
| 92 |
+
expect(res.body).toEqual({ item: { id: 9, name: 'Hotel' } });
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('403 on create without permission', async () => {
|
| 96 |
+
checkPermission.mockReturnValue(false);
|
| 97 |
+
const res = await request(server).post('/api/trips/5/budget').set('Cookie', sessionCookie(1)).send({ name: 'Hotel' });
|
| 98 |
+
expect(res.status).toBe(403);
|
| 99 |
+
expect(res.body).toEqual({ error: 'No permission' });
|
| 100 |
+
});
|
| 101 |
+
|
| 102 |
+
it('400 on member update with a non-array user_ids', async () => {
|
| 103 |
+
const res = await request(server).put('/api/trips/5/budget/9/members').set('Cookie', sessionCookie(1)).send({ user_ids: 'no' });
|
| 104 |
+
expect(res.status).toBe(400);
|
| 105 |
+
expect(res.body).toEqual({ error: 'user_ids must be an array' });
|
| 106 |
+
});
|
| 107 |
+
});
|
server/tests/e2e/categories.e2e.test.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Categories module e2e — exercises the migrated /api/categories endpoints
|
| 3 |
+
* through the real JwtAuthGuard + AdminGuard against a temp SQLite db seeded
|
| 4 |
+
* with an admin and a normal user. categoryService is mocked.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 24 |
+
|
| 25 |
+
const { mocks } = vi.hoisted(() => ({
|
| 26 |
+
mocks: {
|
| 27 |
+
listCategories: vi.fn(),
|
| 28 |
+
createCategory: vi.fn(),
|
| 29 |
+
getCategoryById: vi.fn(),
|
| 30 |
+
updateCategory: vi.fn(),
|
| 31 |
+
deleteCategory: vi.fn(),
|
| 32 |
+
},
|
| 33 |
+
}));
|
| 34 |
+
vi.mock('../../src/services/categoryService', () => mocks);
|
| 35 |
+
|
| 36 |
+
import { CategoriesModule } from '../../src/nest/categories/categories.module';
|
| 37 |
+
import { DatabaseModule } from '../../src/nest/database/database.module';
|
| 38 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 39 |
+
|
| 40 |
+
const cat = { id: 1, name: 'Food', color: '#fff', icon: '🍔' };
|
| 41 |
+
|
| 42 |
+
describe('Categories e2e (real JwtAuthGuard + AdminGuard + temp SQLite)', () => {
|
| 43 |
+
let server: Server;
|
| 44 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 45 |
+
|
| 46 |
+
async function build() {
|
| 47 |
+
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, CategoriesModule] }).compile();
|
| 48 |
+
const nest = moduleRef.createNestApplication();
|
| 49 |
+
nest.use(cookieParser());
|
| 50 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 51 |
+
await nest.init();
|
| 52 |
+
return nest;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
beforeAll(async () => {
|
| 56 |
+
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' });
|
| 57 |
+
seedUser(db as never, { id: 2, role: 'user', email: 'user@example.test' });
|
| 58 |
+
app = await build();
|
| 59 |
+
server = app.getHttpServer();
|
| 60 |
+
mocks.listCategories.mockReturnValue([cat]);
|
| 61 |
+
mocks.createCategory.mockReturnValue(cat);
|
| 62 |
+
mocks.getCategoryById.mockImplementation((id: string | number) => (String(id) === '1' ? cat : undefined));
|
| 63 |
+
mocks.updateCategory.mockReturnValue({ ...cat, name: 'Drinks' });
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
afterAll(async () => {
|
| 67 |
+
await app.close();
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
it('401 without a session cookie', async () => {
|
| 71 |
+
const res = await request(server).get('/api/categories');
|
| 72 |
+
expect(res.status).toBe(401);
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
it('200 list for any authenticated user (non-admin allowed)', async () => {
|
| 76 |
+
const res = await request(server).get('/api/categories').set('Cookie', sessionCookie(2));
|
| 77 |
+
expect(res.status).toBe(200);
|
| 78 |
+
expect(res.body).toEqual({ categories: [cat] });
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('403 when a non-admin tries to create', async () => {
|
| 82 |
+
const res = await request(server).post('/api/categories').set('Cookie', sessionCookie(2)).send({ name: 'X' });
|
| 83 |
+
expect(res.status).toBe(403);
|
| 84 |
+
expect(res.body).toEqual({ error: 'Admin access required' });
|
| 85 |
+
expect(mocks.createCategory).not.toHaveBeenCalled();
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
it('201 when an admin creates a category', async () => {
|
| 89 |
+
const res = await request(server).post('/api/categories').set('Cookie', sessionCookie(1)).send({ name: 'Food', color: '#fff', icon: '🍔' });
|
| 90 |
+
expect(res.status).toBe(201);
|
| 91 |
+
expect(res.body).toEqual({ category: cat });
|
| 92 |
+
expect(mocks.createCategory).toHaveBeenCalledWith(1, 'Food', '#fff', '🍔');
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('400 when an admin creates without a name', async () => {
|
| 96 |
+
const res = await request(server).post('/api/categories').set('Cookie', sessionCookie(1)).send({});
|
| 97 |
+
expect(res.status).toBe(400);
|
| 98 |
+
expect(res.body).toEqual({ error: 'Category name is required' });
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
it('200 when an admin updates an existing category', async () => {
|
| 102 |
+
const res = await request(server).put('/api/categories/1').set('Cookie', sessionCookie(1)).send({ name: 'Drinks' });
|
| 103 |
+
expect(res.status).toBe(200);
|
| 104 |
+
expect(res.body).toEqual({ category: { ...cat, name: 'Drinks' } });
|
| 105 |
+
});
|
| 106 |
+
|
| 107 |
+
it('404 when an admin updates a missing category', async () => {
|
| 108 |
+
const res = await request(server).put('/api/categories/9').set('Cookie', sessionCookie(1)).send({ name: 'X' });
|
| 109 |
+
expect(res.status).toBe(404);
|
| 110 |
+
expect(res.body).toEqual({ error: 'Category not found' });
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it('200 when an admin deletes an existing category', async () => {
|
| 114 |
+
const res = await request(server).delete('/api/categories/1').set('Cookie', sessionCookie(1));
|
| 115 |
+
expect(res.status).toBe(200);
|
| 116 |
+
expect(res.body).toEqual({ success: true });
|
| 117 |
+
expect(mocks.deleteCategory).toHaveBeenCalledWith('1');
|
| 118 |
+
});
|
| 119 |
+
});
|
server/tests/e2e/collab.e2e.test.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Collab module e2e — exercises the migrated /api/trips/:tripId/collab endpoints
|
| 3 |
+
* through the real JwtAuthGuard against a temp SQLite db. The collab service,
|
| 4 |
+
* permission check, WebSocket broadcast and the chat/note notification are
|
| 5 |
+
* mocked; this focuses on auth, trip-access 404, permission 403, the create-201
|
| 6 |
+
* status codes and the vote/react 200 overrides.
|
| 7 |
+
*/
|
| 8 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 9 |
+
import request from 'supertest';
|
| 10 |
+
import cookieParser from 'cookie-parser';
|
| 11 |
+
import type { Server } from 'http';
|
| 12 |
+
import { Test } from '@nestjs/testing';
|
| 13 |
+
import { seedUser, sessionCookie } from './harness';
|
| 14 |
+
|
| 15 |
+
const { db } = vi.hoisted(() => {
|
| 16 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 17 |
+
const Database = require('better-sqlite3');
|
| 18 |
+
const tmp = new Database(':memory:');
|
| 19 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 20 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 21 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 22 |
+
// The note/message notifications read the trip title fire-and-forget; the table
|
| 23 |
+
// must exist so that query doesn't throw after the test has torn down.
|
| 24 |
+
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
|
| 25 |
+
tmp.prepare("INSERT INTO trips (id, title) VALUES (5, 'Trip')").run();
|
| 26 |
+
return { db: tmp };
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 30 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 31 |
+
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
| 32 |
+
|
| 33 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 34 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 35 |
+
|
| 36 |
+
const { svc } = vi.hoisted(() => ({
|
| 37 |
+
svc: {
|
| 38 |
+
verifyTripAccess: vi.fn(), listNotes: vi.fn(), createNote: vi.fn(), updateNote: vi.fn(), deleteNote: vi.fn(),
|
| 39 |
+
addNoteFile: vi.fn(), getFormattedNoteById: vi.fn(), deleteNoteFile: vi.fn(),
|
| 40 |
+
listPolls: vi.fn(), createPoll: vi.fn(), votePoll: vi.fn(), closePoll: vi.fn(), deletePoll: vi.fn(),
|
| 41 |
+
listMessages: vi.fn(), createMessage: vi.fn(), deleteMessage: vi.fn(), addOrRemoveReaction: vi.fn(), fetchLinkPreview: vi.fn(),
|
| 42 |
+
},
|
| 43 |
+
}));
|
| 44 |
+
vi.mock('../../src/services/collabService', () => svc);
|
| 45 |
+
|
| 46 |
+
import { CollabModule } from '../../src/nest/collab/collab.module';
|
| 47 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 48 |
+
|
| 49 |
+
describe('Collab e2e (real auth guard + temp SQLite)', () => {
|
| 50 |
+
let server: Server;
|
| 51 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 52 |
+
|
| 53 |
+
async function build() {
|
| 54 |
+
const moduleRef = await Test.createTestingModule({ imports: [CollabModule] }).compile();
|
| 55 |
+
const nest = moduleRef.createNestApplication();
|
| 56 |
+
nest.use(cookieParser());
|
| 57 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 58 |
+
await nest.init();
|
| 59 |
+
return nest;
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
beforeAll(async () => {
|
| 63 |
+
seedUser(db as never, { id: 1 });
|
| 64 |
+
app = await build();
|
| 65 |
+
server = app.getHttpServer();
|
| 66 |
+
svc.listNotes.mockReturnValue([{ id: 1, title: 'N' }]);
|
| 67 |
+
svc.createNote.mockReturnValue({ id: 9, title: 'N' });
|
| 68 |
+
svc.createPoll.mockReturnValue({ id: 7 });
|
| 69 |
+
svc.votePoll.mockReturnValue({ poll: { id: 7 } });
|
| 70 |
+
svc.createMessage.mockReturnValue({ message: { id: 3, text: 'hi' } });
|
| 71 |
+
svc.addOrRemoveReaction.mockReturnValue({ found: true, reactions: [{ emoji: '👍', count: 1 }] });
|
| 72 |
+
svc.fetchLinkPreview.mockResolvedValue({ title: 'T', description: null, image: null, url: 'http://x' });
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
beforeEach(() => {
|
| 76 |
+
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
| 77 |
+
checkPermission.mockReturnValue(true);
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
afterAll(async () => {
|
| 81 |
+
await app.close();
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it('401 without a session cookie', async () => {
|
| 85 |
+
expect((await request(server).get('/api/trips/5/collab/notes')).status).toBe(401);
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
it('200 list notes for an accessible trip', async () => {
|
| 89 |
+
const res = await request(server).get('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1));
|
| 90 |
+
expect(res.status).toBe(200);
|
| 91 |
+
expect(res.body).toEqual({ notes: [{ id: 1, title: 'N' }] });
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it('404 when the trip is not accessible', async () => {
|
| 95 |
+
svc.verifyTripAccess.mockReturnValue(undefined);
|
| 96 |
+
const res = await request(server).get('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1));
|
| 97 |
+
expect(res.status).toBe(404);
|
| 98 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
it('201 on note create with permission', async () => {
|
| 102 |
+
const res = await request(server).post('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1)).send({ title: 'N' });
|
| 103 |
+
expect(res.status).toBe(201);
|
| 104 |
+
expect(res.body).toEqual({ note: { id: 9, title: 'N' } });
|
| 105 |
+
});
|
| 106 |
+
|
| 107 |
+
it('403 on note create without permission', async () => {
|
| 108 |
+
checkPermission.mockReturnValue(false);
|
| 109 |
+
const res = await request(server).post('/api/trips/5/collab/notes').set('Cookie', sessionCookie(1)).send({ title: 'N' });
|
| 110 |
+
expect(res.status).toBe(403);
|
| 111 |
+
expect(res.body).toEqual({ error: 'No permission' });
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
it('200 on poll vote (not 201)', async () => {
|
| 115 |
+
const res = await request(server).post('/api/trips/5/collab/polls/7/vote').set('Cookie', sessionCookie(1)).send({ option_index: 0 });
|
| 116 |
+
expect(res.status).toBe(200);
|
| 117 |
+
expect(res.body).toEqual({ poll: { id: 7 } });
|
| 118 |
+
});
|
| 119 |
+
|
| 120 |
+
it('201 on message create', async () => {
|
| 121 |
+
const res = await request(server).post('/api/trips/5/collab/messages').set('Cookie', sessionCookie(1)).send({ text: 'hi' });
|
| 122 |
+
expect(res.status).toBe(201);
|
| 123 |
+
expect(res.body).toEqual({ message: { id: 3, text: 'hi' } });
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
it('200 on react (not 201)', async () => {
|
| 127 |
+
const res = await request(server).post('/api/trips/5/collab/messages/3/react').set('Cookie', sessionCookie(1)).send({ emoji: '👍' });
|
| 128 |
+
expect(res.status).toBe(200);
|
| 129 |
+
expect(res.body).toEqual({ reactions: [{ emoji: '👍', count: 1 }] });
|
| 130 |
+
});
|
| 131 |
+
|
| 132 |
+
it('400 on link-preview without a url', async () => {
|
| 133 |
+
const res = await request(server).get('/api/trips/5/collab/link-preview').set('Cookie', sessionCookie(1));
|
| 134 |
+
expect(res.status).toBe(400);
|
| 135 |
+
expect(res.body).toEqual({ error: 'URL is required' });
|
| 136 |
+
});
|
| 137 |
+
});
|
server/tests/e2e/config.e2e.test.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Public config e2e — verifies /api/config is reachable WITHOUT authentication
|
| 3 |
+
* (it has no guard) and returns the server default language. No db needed.
|
| 4 |
+
*/
|
| 5 |
+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
| 6 |
+
import request from 'supertest';
|
| 7 |
+
import type { Server } from 'http';
|
| 8 |
+
import { Test } from '@nestjs/testing';
|
| 9 |
+
import { ConfigModule } from '../../src/nest/config/config.module';
|
| 10 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 11 |
+
import { DEFAULT_LANGUAGE } from '../../src/config';
|
| 12 |
+
|
| 13 |
+
describe('Public config e2e (no auth guard)', () => {
|
| 14 |
+
let server: Server;
|
| 15 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 16 |
+
|
| 17 |
+
async function build() {
|
| 18 |
+
const moduleRef = await Test.createTestingModule({ imports: [ConfigModule] }).compile();
|
| 19 |
+
const nest = moduleRef.createNestApplication();
|
| 20 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 21 |
+
await nest.init();
|
| 22 |
+
return nest;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
beforeAll(async () => {
|
| 26 |
+
app = await build();
|
| 27 |
+
server = app.getHttpServer();
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
afterAll(async () => {
|
| 31 |
+
await app.close();
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
it('200 with the default language and no cookie required', async () => {
|
| 35 |
+
const res = await request(server).get('/api/config');
|
| 36 |
+
expect(res.status).toBe(200);
|
| 37 |
+
expect(res.body).toEqual({ defaultLanguage: DEFAULT_LANGUAGE });
|
| 38 |
+
});
|
| 39 |
+
});
|
server/tests/e2e/days.e2e.test.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Days + day-notes module e2e — exercises both migrated mounts through the real
|
| 3 |
+
* JwtAuthGuard against a temp SQLite db. The day/day-note services, the
|
| 4 |
+
* permission check, canAccessTrip and the WebSocket broadcast are mocked.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
| 24 |
+
vi.mock('../../src/db/database', () => ({
|
| 25 |
+
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
| 26 |
+
}));
|
| 27 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 28 |
+
|
| 29 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 30 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 31 |
+
|
| 32 |
+
const { day, note } = vi.hoisted(() => ({
|
| 33 |
+
day: { listDays: vi.fn(), createDay: vi.fn(), getDay: vi.fn(), updateDay: vi.fn(), deleteDay: vi.fn() },
|
| 34 |
+
note: {
|
| 35 |
+
verifyTripAccess: vi.fn(), listNotes: vi.fn(), dayExists: vi.fn(), createNote: vi.fn(),
|
| 36 |
+
getNote: vi.fn(), updateNote: vi.fn(), deleteNote: vi.fn(),
|
| 37 |
+
},
|
| 38 |
+
}));
|
| 39 |
+
vi.mock('../../src/services/dayService', () => day);
|
| 40 |
+
vi.mock('../../src/services/dayNoteService', () => note);
|
| 41 |
+
|
| 42 |
+
import { DaysModule } from '../../src/nest/days/days.module';
|
| 43 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 44 |
+
|
| 45 |
+
describe('Days + day-notes e2e (real auth guard + temp SQLite)', () => {
|
| 46 |
+
let server: Server;
|
| 47 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 48 |
+
|
| 49 |
+
async function build() {
|
| 50 |
+
const moduleRef = await Test.createTestingModule({ imports: [DaysModule] }).compile();
|
| 51 |
+
const nest = moduleRef.createNestApplication();
|
| 52 |
+
nest.use(cookieParser());
|
| 53 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 54 |
+
await nest.init();
|
| 55 |
+
return nest;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
beforeAll(async () => {
|
| 59 |
+
seedUser(db as never, { id: 1 });
|
| 60 |
+
app = await build();
|
| 61 |
+
server = app.getHttpServer();
|
| 62 |
+
day.listDays.mockReturnValue({ days: [{ id: 1 }] });
|
| 63 |
+
day.createDay.mockReturnValue({ id: 9 });
|
| 64 |
+
note.listNotes.mockReturnValue([{ id: 1 }]);
|
| 65 |
+
note.dayExists.mockReturnValue(true);
|
| 66 |
+
note.createNote.mockReturnValue({ id: 7 });
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
beforeEach(() => {
|
| 70 |
+
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
| 71 |
+
note.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
| 72 |
+
checkPermission.mockReturnValue(true);
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
afterAll(async () => {
|
| 76 |
+
await app.close();
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
it('401 without a cookie', async () => {
|
| 80 |
+
expect((await request(server).get('/api/trips/5/days')).status).toBe(401);
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
it('200 list days (the { days } envelope)', async () => {
|
| 84 |
+
const res = await request(server).get('/api/trips/5/days').set('Cookie', sessionCookie(1));
|
| 85 |
+
expect(res.status).toBe(200);
|
| 86 |
+
expect(res.body).toEqual({ days: [{ id: 1 }] });
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it('201 create day, 404 trip when not accessible', async () => {
|
| 90 |
+
const ok = await request(server).post('/api/trips/5/days').set('Cookie', sessionCookie(1)).send({ date: '2026-07-01' });
|
| 91 |
+
expect(ok.status).toBe(201);
|
| 92 |
+
expect(ok.body).toEqual({ day: { id: 9 } });
|
| 93 |
+
canAccessTrip.mockReturnValue(undefined);
|
| 94 |
+
const miss = await request(server).get('/api/trips/5/days').set('Cookie', sessionCookie(1));
|
| 95 |
+
expect(miss.status).toBe(404);
|
| 96 |
+
expect(miss.body).toEqual({ error: 'Trip not found' });
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
it('201 create note, 400 on over-long text (before access)', async () => {
|
| 100 |
+
const ok = await request(server).post('/api/trips/5/days/3/notes').set('Cookie', sessionCookie(1)).send({ text: 'Lunch' });
|
| 101 |
+
expect(ok.status).toBe(201);
|
| 102 |
+
expect(ok.body).toEqual({ note: { id: 7 } });
|
| 103 |
+
const long = await request(server).post('/api/trips/5/days/3/notes').set('Cookie', sessionCookie(1)).send({ text: 'x'.repeat(501) });
|
| 104 |
+
expect(long.status).toBe(400);
|
| 105 |
+
expect(long.body).toEqual({ error: 'text must be 500 characters or less' });
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
it('400 note without text', async () => {
|
| 109 |
+
const res = await request(server).post('/api/trips/5/days/3/notes').set('Cookie', sessionCookie(1)).send({ text: ' ' });
|
| 110 |
+
expect(res.status).toBe(400);
|
| 111 |
+
expect(res.body).toEqual({ error: 'Text required' });
|
| 112 |
+
});
|
| 113 |
+
});
|
server/tests/e2e/files.e2e.test.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Files + photos e2e — exercises the migrated /api/trips/:tripId/files and
|
| 3 |
+
* /api/photos endpoints through the real JwtAuthGuard against a temp SQLite db.
|
| 4 |
+
* The file/photo services, permission check and broadcast are mocked; this
|
| 5 |
+
* focuses on auth (incl. the unguarded download's own token auth), trip-access
|
| 6 |
+
* 404, permission 403, the photo id/access guards and status codes.
|
| 7 |
+
*/
|
| 8 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 9 |
+
import request from 'supertest';
|
| 10 |
+
import cookieParser from 'cookie-parser';
|
| 11 |
+
import type { Server } from 'http';
|
| 12 |
+
import { Test } from '@nestjs/testing';
|
| 13 |
+
import { seedUser, sessionCookie } from './harness';
|
| 14 |
+
|
| 15 |
+
const { db } = vi.hoisted(() => {
|
| 16 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 17 |
+
const Database = require('better-sqlite3');
|
| 18 |
+
const tmp = new Database(':memory:');
|
| 19 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 20 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 21 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 22 |
+
return { db: tmp };
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 26 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 27 |
+
vi.mock('../../src/services/demo', () => ({ isDemoEmail: vi.fn(() => false) }));
|
| 28 |
+
|
| 29 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 30 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 31 |
+
|
| 32 |
+
const { fileSvc } = vi.hoisted(() => ({
|
| 33 |
+
fileSvc: {
|
| 34 |
+
MAX_FILE_SIZE: 50 * 1024 * 1024, BLOCKED_EXTENSIONS: ['.exe', '.svg'], filesDir: '/tmp/files', getAllowedExtensions: () => '*',
|
| 35 |
+
verifyTripAccess: vi.fn(), resolveFilePath: vi.fn(), authenticateDownload: vi.fn(),
|
| 36 |
+
listFiles: vi.fn(), getFileById: vi.fn(), getDeletedFile: vi.fn(), createFile: vi.fn(), updateFile: vi.fn(),
|
| 37 |
+
toggleStarred: vi.fn(), softDeleteFile: vi.fn(), restoreFile: vi.fn(), permanentDeleteFile: vi.fn(),
|
| 38 |
+
emptyTrash: vi.fn(), createFileLink: vi.fn(), deleteFileLink: vi.fn(), getFileLinks: vi.fn(), formatFile: vi.fn(),
|
| 39 |
+
},
|
| 40 |
+
}));
|
| 41 |
+
vi.mock('../../src/services/fileService', () => fileSvc);
|
| 42 |
+
|
| 43 |
+
const { photoSvc, helperSvc } = vi.hoisted(() => ({
|
| 44 |
+
photoSvc: { streamPhoto: vi.fn(), getPhotoInfo: vi.fn(), resolveTrekPhoto: vi.fn() },
|
| 45 |
+
helperSvc: { canAccessTrekPhoto: vi.fn() },
|
| 46 |
+
}));
|
| 47 |
+
vi.mock('../../src/services/memories/photoResolverService', () => photoSvc);
|
| 48 |
+
vi.mock('../../src/services/memories/helpersService', () => helperSvc);
|
| 49 |
+
|
| 50 |
+
import { FilesModule } from '../../src/nest/files/files.module';
|
| 51 |
+
import { PhotosModule } from '../../src/nest/photos/photos.module';
|
| 52 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 53 |
+
|
| 54 |
+
describe('Files + photos e2e (real auth guard + temp SQLite)', () => {
|
| 55 |
+
let server: Server;
|
| 56 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 57 |
+
|
| 58 |
+
async function build() {
|
| 59 |
+
const moduleRef = await Test.createTestingModule({ imports: [FilesModule, PhotosModule] }).compile();
|
| 60 |
+
const nest = moduleRef.createNestApplication();
|
| 61 |
+
nest.use(cookieParser());
|
| 62 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 63 |
+
await nest.init();
|
| 64 |
+
return nest;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
beforeAll(async () => {
|
| 68 |
+
seedUser(db as never, { id: 1 });
|
| 69 |
+
app = await build();
|
| 70 |
+
server = app.getHttpServer();
|
| 71 |
+
fileSvc.listFiles.mockReturnValue([{ id: 1, original_name: 'a.pdf' }]);
|
| 72 |
+
fileSvc.getFileById.mockReturnValue({ id: 9, starred: 0 });
|
| 73 |
+
fileSvc.toggleStarred.mockReturnValue({ id: 9, starred: 1 });
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
beforeEach(() => {
|
| 77 |
+
fileSvc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
| 78 |
+
checkPermission.mockReturnValue(true);
|
| 79 |
+
helperSvc.canAccessTrekPhoto.mockReturnValue(true);
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
afterAll(async () => {
|
| 83 |
+
await app.close();
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
it('401 listing files without a session cookie', async () => {
|
| 87 |
+
expect((await request(server).get('/api/trips/5/files')).status).toBe(401);
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
it('200 list for an accessible trip', async () => {
|
| 91 |
+
const res = await request(server).get('/api/trips/5/files').set('Cookie', sessionCookie(1));
|
| 92 |
+
expect(res.status).toBe(200);
|
| 93 |
+
expect(res.body).toEqual({ files: [{ id: 1, original_name: 'a.pdf' }] });
|
| 94 |
+
});
|
| 95 |
+
|
| 96 |
+
it('404 when the trip is not accessible', async () => {
|
| 97 |
+
fileSvc.verifyTripAccess.mockReturnValue(undefined);
|
| 98 |
+
const res = await request(server).get('/api/trips/5/files').set('Cookie', sessionCookie(1));
|
| 99 |
+
expect(res.status).toBe(404);
|
| 100 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
it('200 toggling a star with permission', async () => {
|
| 104 |
+
const res = await request(server).patch('/api/trips/5/files/9/star').set('Cookie', sessionCookie(1));
|
| 105 |
+
expect(res.status).toBe(200);
|
| 106 |
+
expect(res.body).toEqual({ file: { id: 9, starred: 1 } });
|
| 107 |
+
});
|
| 108 |
+
|
| 109 |
+
it('403 deleting without file_delete permission', async () => {
|
| 110 |
+
checkPermission.mockReturnValue(false);
|
| 111 |
+
const res = await request(server).delete('/api/trips/5/files/9').set('Cookie', sessionCookie(1));
|
| 112 |
+
expect(res.status).toBe(403);
|
| 113 |
+
expect(res.body).toEqual({ error: 'No permission to delete files' });
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
it('download is unguarded but enforces its own token auth (401 without one)', async () => {
|
| 117 |
+
fileSvc.authenticateDownload.mockReturnValue({ error: 'Authentication required', status: 401 });
|
| 118 |
+
const res = await request(server).get('/api/trips/5/files/9/download');
|
| 119 |
+
expect(res.status).toBe(401);
|
| 120 |
+
expect(res.body).toEqual({ error: 'Authentication required' });
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
it('400 on a photo with a non-finite id', async () => {
|
| 124 |
+
const res = await request(server).get('/api/photos/abc/thumbnail').set('Cookie', sessionCookie(1));
|
| 125 |
+
expect(res.status).toBe(400);
|
| 126 |
+
expect(res.body).toEqual({ error: 'Invalid photo ID' });
|
| 127 |
+
});
|
| 128 |
+
|
| 129 |
+
it('403 on a photo the user cannot access', async () => {
|
| 130 |
+
helperSvc.canAccessTrekPhoto.mockReturnValue(false);
|
| 131 |
+
const res = await request(server).get('/api/photos/5/original').set('Cookie', sessionCookie(1));
|
| 132 |
+
expect(res.status).toBe(403);
|
| 133 |
+
expect(res.body).toEqual({ error: 'Forbidden' });
|
| 134 |
+
});
|
| 135 |
+
});
|
server/tests/e2e/harness.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import Database from 'better-sqlite3';
|
| 2 |
+
import jwt from 'jsonwebtoken';
|
| 3 |
+
import { JWT_SECRET } from '../../src/config';
|
| 4 |
+
|
| 5 |
+
/**
|
| 6 |
+
* Shared e2e harness for migrated Nest modules.
|
| 7 |
+
*
|
| 8 |
+
* Gives each module e2e test a throwaway in-memory SQLite db (the same shape the
|
| 9 |
+
* shared connection exposes), a seed helper for demo data, and a session-cookie
|
| 10 |
+
* signer that produces tokens the REAL JwtAuthGuard accepts — so e2e tests cover
|
| 11 |
+
* the actual auth path end-to-end, not a stubbed guard.
|
| 12 |
+
*
|
| 13 |
+
* Wire it in a test with `vi.mock('../../src/db/database', () => ({ db, ... }))`
|
| 14 |
+
* using the db returned here, then build the Nest app under test.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
export interface SeededUser {
|
| 18 |
+
id: number;
|
| 19 |
+
username: string;
|
| 20 |
+
email: string;
|
| 21 |
+
role: 'user' | 'admin';
|
| 22 |
+
password_version: number;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
/** Fresh in-memory db with the minimal `users` table the auth guard reads. */
|
| 26 |
+
export function createTempDb(): Database.Database {
|
| 27 |
+
const db = new Database(':memory:');
|
| 28 |
+
db.exec('PRAGMA journal_mode = WAL');
|
| 29 |
+
db.exec('PRAGMA foreign_keys = ON');
|
| 30 |
+
db.exec(`
|
| 31 |
+
CREATE TABLE users (
|
| 32 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 33 |
+
username TEXT NOT NULL,
|
| 34 |
+
email TEXT NOT NULL UNIQUE,
|
| 35 |
+
role TEXT NOT NULL DEFAULT 'user',
|
| 36 |
+
password_version INTEGER NOT NULL DEFAULT 0
|
| 37 |
+
);
|
| 38 |
+
`);
|
| 39 |
+
return db;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/** Insert a demo user and return its row. */
|
| 43 |
+
export function seedUser(db: Database.Database, overrides: Partial<SeededUser> = {}): SeededUser {
|
| 44 |
+
const user: SeededUser = {
|
| 45 |
+
id: overrides.id ?? 1,
|
| 46 |
+
username: overrides.username ?? 'e2e-user',
|
| 47 |
+
email: overrides.email ?? 'e2e@example.test',
|
| 48 |
+
role: overrides.role ?? 'user',
|
| 49 |
+
password_version: overrides.password_version ?? 0,
|
| 50 |
+
};
|
| 51 |
+
db.prepare(
|
| 52 |
+
'INSERT INTO users (id, username, email, role, password_version) VALUES (?, ?, ?, ?, ?)',
|
| 53 |
+
).run(user.id, user.username, user.email, user.role, user.password_version);
|
| 54 |
+
return user;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/** Sign a `trek_session` token the real guard will accept (matching JWT_SECRET + pv). */
|
| 58 |
+
export function signSession(userId: number, passwordVersion = 0): string {
|
| 59 |
+
return jwt.sign({ id: userId, pv: passwordVersion }, JWT_SECRET, { algorithm: 'HS256' });
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/** Convenience: the Cookie header value for a signed session. */
|
| 63 |
+
export function sessionCookie(userId: number, passwordVersion = 0): string {
|
| 64 |
+
return `trek_session=${signSession(userId, passwordVersion)}`;
|
| 65 |
+
}
|
server/tests/e2e/journey.e2e.test.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Journey e2e — exercises the migrated /api/journeys and /api/public/journey
|
| 3 |
+
* endpoints through the real JwtAuthGuard against a temp SQLite db. The journey
|
| 4 |
+
* services + addon gate are mocked; this focuses on the addon-gate-before-auth
|
| 5 |
+
* ordering (404 wins over 401), auth, the service-owned 403/404 mapping, status
|
| 6 |
+
* codes and the unguarded public route.
|
| 7 |
+
*/
|
| 8 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 9 |
+
import request from 'supertest';
|
| 10 |
+
import cookieParser from 'cookie-parser';
|
| 11 |
+
import type { Server } from 'http';
|
| 12 |
+
import { Test } from '@nestjs/testing';
|
| 13 |
+
import { seedUser, sessionCookie } from './harness';
|
| 14 |
+
|
| 15 |
+
const { db } = vi.hoisted(() => {
|
| 16 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 17 |
+
const Database = require('better-sqlite3');
|
| 18 |
+
const tmp = new Database(':memory:');
|
| 19 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 20 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 21 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 22 |
+
return { db: tmp };
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 26 |
+
|
| 27 |
+
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
|
| 28 |
+
vi.mock('../../src/services/adminService', () => ({ isAddonEnabled }));
|
| 29 |
+
vi.mock('../../src/services/fileService', () => ({ getAllowedExtensions: () => '*' }));
|
| 30 |
+
vi.mock('../../src/services/memories/immichService', () => ({ uploadToImmich: vi.fn(), streamImmichAsset: vi.fn() }));
|
| 31 |
+
vi.mock('../../src/services/memories/photoResolverService', () => ({ streamPhoto: vi.fn() }));
|
| 32 |
+
|
| 33 |
+
const { jsvc } = vi.hoisted(() => ({
|
| 34 |
+
jsvc: { listJourneys: vi.fn(), createJourney: vi.fn(), getJourneyFull: vi.fn() },
|
| 35 |
+
}));
|
| 36 |
+
vi.mock('../../src/services/journeyService', () => jsvc);
|
| 37 |
+
|
| 38 |
+
const { sharesvc } = vi.hoisted(() => ({ sharesvc: { getPublicJourney: vi.fn() } }));
|
| 39 |
+
vi.mock('../../src/services/journeyShareService', () => sharesvc);
|
| 40 |
+
|
| 41 |
+
import { JourneyModule } from '../../src/nest/journey/journey.module';
|
| 42 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 43 |
+
|
| 44 |
+
describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
| 45 |
+
let server: Server;
|
| 46 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 47 |
+
|
| 48 |
+
async function build() {
|
| 49 |
+
const moduleRef = await Test.createTestingModule({ imports: [JourneyModule] }).compile();
|
| 50 |
+
const nest = moduleRef.createNestApplication();
|
| 51 |
+
nest.use(cookieParser());
|
| 52 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 53 |
+
await nest.init();
|
| 54 |
+
return nest;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
beforeAll(async () => {
|
| 58 |
+
seedUser(db as never, { id: 1 });
|
| 59 |
+
app = await build();
|
| 60 |
+
server = app.getHttpServer();
|
| 61 |
+
jsvc.listJourneys.mockReturnValue([{ id: 1, title: 'J' }]);
|
| 62 |
+
jsvc.createJourney.mockReturnValue({ id: 9, title: 'J' });
|
| 63 |
+
sharesvc.getPublicJourney.mockReturnValue({ id: 9 });
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
beforeEach(() => {
|
| 67 |
+
isAddonEnabled.mockReturnValue(true);
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
afterAll(async () => {
|
| 71 |
+
await app.close();
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
it('404 (addon gate wins over auth) when the Journey addon is disabled', async () => {
|
| 75 |
+
isAddonEnabled.mockReturnValue(false);
|
| 76 |
+
const res = await request(server).get('/api/journeys');
|
| 77 |
+
expect(res.status).toBe(404);
|
| 78 |
+
expect(res.body).toEqual({ error: 'Journey addon is not enabled' });
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('401 with the addon enabled but no session cookie', async () => {
|
| 82 |
+
expect((await request(server).get('/api/journeys')).status).toBe(401);
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
it('200 list with a session', async () => {
|
| 86 |
+
const res = await request(server).get('/api/journeys').set('Cookie', sessionCookie(1));
|
| 87 |
+
expect(res.status).toBe(200);
|
| 88 |
+
expect(res.body).toEqual({ journeys: [{ id: 1, title: 'J' }] });
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
it('201 create, 400 without a title', async () => {
|
| 92 |
+
const ok = await request(server).post('/api/journeys').set('Cookie', sessionCookie(1)).send({ title: 'J' });
|
| 93 |
+
expect(ok.status).toBe(201);
|
| 94 |
+
expect(ok.body).toEqual({ id: 9, title: 'J' });
|
| 95 |
+
const bad = await request(server).post('/api/journeys').set('Cookie', sessionCookie(1)).send({});
|
| 96 |
+
expect(bad.status).toBe(400);
|
| 97 |
+
expect(bad.body).toEqual({ error: 'Title is required' });
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
it('404 for an inaccessible journey', async () => {
|
| 101 |
+
jsvc.getJourneyFull.mockReturnValue(null);
|
| 102 |
+
const res = await request(server).get('/api/journeys/9').set('Cookie', sessionCookie(1));
|
| 103 |
+
expect(res.status).toBe(404);
|
| 104 |
+
expect(res.body).toEqual({ error: 'Journey not found' });
|
| 105 |
+
});
|
| 106 |
+
|
| 107 |
+
it('public journey read is unguarded (200 with a valid token, no cookie)', async () => {
|
| 108 |
+
const res = await request(server).get('/api/public/journey/tok');
|
| 109 |
+
expect(res.status).toBe(200);
|
| 110 |
+
expect(res.body).toEqual({ id: 9 });
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it('public journey 404 for an unknown token', async () => {
|
| 114 |
+
sharesvc.getPublicJourney.mockReturnValueOnce(null);
|
| 115 |
+
const res = await request(server).get('/api/public/journey/bad');
|
| 116 |
+
expect(res.status).toBe(404);
|
| 117 |
+
expect(res.body).toEqual({ error: 'Not found' });
|
| 118 |
+
});
|
| 119 |
+
});
|
server/tests/e2e/maps.e2e.test.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Maps module e2e — exercises the migrated /api/maps endpoints through the real
|
| 3 |
+
* JwtAuthGuard against a temp SQLite db. mapsService is mocked (no outbound HTTP),
|
| 4 |
+
* and the temp db carries an empty app_settings table so the kill-switch reads
|
| 5 |
+
* resolve to "enabled".
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
tmp.exec('CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);');
|
| 22 |
+
return { db: tmp };
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 26 |
+
|
| 27 |
+
const { mocks } = vi.hoisted(() => ({
|
| 28 |
+
mocks: {
|
| 29 |
+
searchPlaces: vi.fn(),
|
| 30 |
+
autocompletePlaces: vi.fn(),
|
| 31 |
+
getPlaceDetails: vi.fn(),
|
| 32 |
+
getPlaceDetailsExpanded: vi.fn(),
|
| 33 |
+
getPlacePhoto: vi.fn(),
|
| 34 |
+
reverseGeocode: vi.fn(),
|
| 35 |
+
resolveGoogleMapsUrl: vi.fn(),
|
| 36 |
+
},
|
| 37 |
+
}));
|
| 38 |
+
vi.mock('../../src/services/mapsService', async (importActual) => {
|
| 39 |
+
const actual = await importActual<typeof import('../../src/services/mapsService')>();
|
| 40 |
+
return { ...actual, ...mocks };
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
import { MapsModule } from '../../src/nest/maps/maps.module';
|
| 44 |
+
import { DatabaseModule } from '../../src/nest/database/database.module';
|
| 45 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 46 |
+
|
| 47 |
+
describe('Maps e2e (real auth guard + temp SQLite)', () => {
|
| 48 |
+
let server: Server;
|
| 49 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 50 |
+
|
| 51 |
+
async function build() {
|
| 52 |
+
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, MapsModule] }).compile();
|
| 53 |
+
const nest = moduleRef.createNestApplication();
|
| 54 |
+
nest.use(cookieParser());
|
| 55 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 56 |
+
await nest.init();
|
| 57 |
+
return nest;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
beforeAll(async () => {
|
| 61 |
+
seedUser(db as never, { id: 1 });
|
| 62 |
+
app = await build();
|
| 63 |
+
server = app.getHttpServer();
|
| 64 |
+
mocks.searchPlaces.mockResolvedValue({ places: [{ name: 'Berlin' }], source: 'osm' });
|
| 65 |
+
mocks.reverseGeocode.mockResolvedValue({ name: 'Spot', address: 'Street 1' });
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
afterAll(async () => {
|
| 69 |
+
await app.close();
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
it('401 without a session cookie', async () => {
|
| 73 |
+
const res = await request(server).post('/api/maps/search').send({ query: 'berlin' });
|
| 74 |
+
expect(res.status).toBe(401);
|
| 75 |
+
expect(res.body).toEqual({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
it('400 when authenticated but query is missing', async () => {
|
| 79 |
+
const res = await request(server).post('/api/maps/search').set('Cookie', sessionCookie(1)).send({});
|
| 80 |
+
expect(res.status).toBe(400);
|
| 81 |
+
expect(res.body).toEqual({ error: 'Search query is required' });
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it('200 with results for a search (POST stays 200, not 201)', async () => {
|
| 85 |
+
const res = await request(server).post('/api/maps/search').set('Cookie', sessionCookie(1)).send({ query: 'berlin' });
|
| 86 |
+
expect(res.status).toBe(200);
|
| 87 |
+
expect(res.body).toEqual({ places: [{ name: 'Berlin' }], source: 'osm' });
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
it('200 on reverse geocode', async () => {
|
| 91 |
+
const res = await request(server).get('/api/maps/reverse').set('Cookie', sessionCookie(1)).query({ lat: '52.5', lng: '13.4' });
|
| 92 |
+
expect(res.status).toBe(200);
|
| 93 |
+
expect(res.body).toEqual({ name: 'Spot', address: 'Street 1' });
|
| 94 |
+
});
|
| 95 |
+
|
| 96 |
+
it('400 on reverse geocode without coordinates', async () => {
|
| 97 |
+
const res = await request(server).get('/api/maps/reverse').set('Cookie', sessionCookie(1)).query({ lat: '52.5' });
|
| 98 |
+
expect(res.status).toBe(400);
|
| 99 |
+
expect(res.body).toEqual({ error: 'lat and lng required' });
|
| 100 |
+
});
|
| 101 |
+
});
|
server/tests/e2e/memories.e2e.test.ts
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Memories (photo-providers) module e2e — exercises the migrated
|
| 3 |
+
* /api/integrations/memories endpoints (unified + immich + synologyphotos)
|
| 4 |
+
* through the real JwtAuthGuard against a temp SQLite db. The provider services
|
| 5 |
+
* and canAccessUserPhoto are mocked; fail/success stay real so the envelope
|
| 6 |
+
* shapes are produced by the actual helper code.
|
| 7 |
+
*
|
| 8 |
+
* Focus: auth (401), every route's happy path, the CRITICAL 200-on-failure
|
| 9 |
+
* behaviour of /test + /status, and at least one error envelope per provider
|
| 10 |
+
* router — all asserted byte-identical to the legacy Express routers.
|
| 11 |
+
*/
|
| 12 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 13 |
+
import request from 'supertest';
|
| 14 |
+
import cookieParser from 'cookie-parser';
|
| 15 |
+
import type { Server } from 'http';
|
| 16 |
+
import { Test } from '@nestjs/testing';
|
| 17 |
+
import { seedUser, sessionCookie } from './harness';
|
| 18 |
+
|
| 19 |
+
const { db } = vi.hoisted(() => {
|
| 20 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 21 |
+
const Database = require('better-sqlite3');
|
| 22 |
+
const tmp = new Database(':memory:');
|
| 23 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 24 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 25 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 26 |
+
return { db: tmp };
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
vi.mock('../../src/db/database', () => ({ db, canAccessTrip: vi.fn(), closeDb: () => {}, reinitialize: () => {} }));
|
| 30 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 31 |
+
|
| 32 |
+
// Provider services — fully mocked. fail/success/canAccessUserPhoto from the
|
| 33 |
+
// helper module are kept real except canAccessUserPhoto which we override.
|
| 34 |
+
const { unified, immich, synology } = vi.hoisted(() => ({
|
| 35 |
+
unified: {
|
| 36 |
+
listTripPhotos: vi.fn(), addTripPhotos: vi.fn(), setTripPhotoSharing: vi.fn(),
|
| 37 |
+
removeTripPhoto: vi.fn(), listTripAlbumLinks: vi.fn(), createTripAlbumLink: vi.fn(), removeAlbumLink: vi.fn(),
|
| 38 |
+
},
|
| 39 |
+
immich: {
|
| 40 |
+
getConnectionSettings: vi.fn(), saveImmichSettings: vi.fn(), setImmichAutoUpload: vi.fn(),
|
| 41 |
+
testConnection: vi.fn(), getConnectionStatus: vi.fn(), browseTimeline: vi.fn(), searchPhotos: vi.fn(),
|
| 42 |
+
streamImmichAsset: vi.fn(), listAlbums: vi.fn(), getAlbumPhotos: vi.fn(), syncAlbumAssets: vi.fn(),
|
| 43 |
+
getAssetInfo: vi.fn(), isValidAssetId: vi.fn(),
|
| 44 |
+
},
|
| 45 |
+
synology: {
|
| 46 |
+
getSynologySettings: vi.fn(), updateSynologySettings: vi.fn(), getSynologyStatus: vi.fn(),
|
| 47 |
+
testSynologyConnection: vi.fn(), listSynologyAlbums: vi.fn(), getSynologyAlbumPhotos: vi.fn(),
|
| 48 |
+
syncSynologyAlbumLink: vi.fn(), searchSynologyPhotos: vi.fn(), getSynologyAssetInfo: vi.fn(),
|
| 49 |
+
streamSynologyAsset: vi.fn(),
|
| 50 |
+
},
|
| 51 |
+
}));
|
| 52 |
+
vi.mock('../../src/services/memories/unifiedService', () => unified);
|
| 53 |
+
vi.mock('../../src/services/memories/immichService', () => immich);
|
| 54 |
+
vi.mock('../../src/services/memories/synologyService', () => synology);
|
| 55 |
+
|
| 56 |
+
const { canAccessUserPhoto } = vi.hoisted(() => ({ canAccessUserPhoto: vi.fn() }));
|
| 57 |
+
vi.mock('../../src/services/memories/helpersService', async () => {
|
| 58 |
+
const actual = await vi.importActual<typeof import('../../src/services/memories/helpersService')>(
|
| 59 |
+
'../../src/services/memories/helpersService',
|
| 60 |
+
);
|
| 61 |
+
return { ...actual, canAccessUserPhoto };
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
import { MemoriesModule } from '../../src/nest/memories/memories.module';
|
| 65 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 66 |
+
|
| 67 |
+
const BASE = '/api/integrations/memories';
|
| 68 |
+
const UNIFIED = `${BASE}/unified`;
|
| 69 |
+
const IMMICH = `${BASE}/immich`;
|
| 70 |
+
const SYNO = `${BASE}/synologyphotos`;
|
| 71 |
+
|
| 72 |
+
describe('Memories e2e (real auth guard + temp SQLite)', () => {
|
| 73 |
+
let server: Server;
|
| 74 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 75 |
+
|
| 76 |
+
async function build() {
|
| 77 |
+
const moduleRef = await Test.createTestingModule({ imports: [MemoriesModule] }).compile();
|
| 78 |
+
const nest = moduleRef.createNestApplication();
|
| 79 |
+
nest.use(cookieParser());
|
| 80 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 81 |
+
await nest.init();
|
| 82 |
+
return nest;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
beforeAll(async () => {
|
| 86 |
+
seedUser(db as never, { id: 1 });
|
| 87 |
+
app = await build();
|
| 88 |
+
server = app.getHttpServer();
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
afterAll(async () => {
|
| 92 |
+
await app.close();
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
beforeEach(() => {
|
| 96 |
+
vi.clearAllMocks();
|
| 97 |
+
canAccessUserPhoto.mockReturnValue(true);
|
| 98 |
+
immich.isValidAssetId.mockReturnValue(true);
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
// ── Auth ───────────────────────────────────────────────────────────────────
|
| 102 |
+
describe('auth', () => {
|
| 103 |
+
it('401 without a cookie (unified photos)', async () => {
|
| 104 |
+
expect((await request(server).get(`${UNIFIED}/trips/5/photos`)).status).toBe(401);
|
| 105 |
+
});
|
| 106 |
+
it('401 without a cookie (immich status)', async () => {
|
| 107 |
+
expect((await request(server).get(`${IMMICH}/status`)).status).toBe(401);
|
| 108 |
+
});
|
| 109 |
+
it('401 without a cookie (synology albums)', async () => {
|
| 110 |
+
expect((await request(server).get(`${SYNO}/albums`)).status).toBe(401);
|
| 111 |
+
});
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
// ── Unified ──────────────────────────────────────────────────────────────────
|
| 115 |
+
describe('unified', () => {
|
| 116 |
+
it('200 list photos -> { photos }', async () => {
|
| 117 |
+
unified.listTripPhotos.mockReturnValue({ success: true, data: [{ photo_id: 1, asset_id: 'a' }] });
|
| 118 |
+
const res = await request(server).get(`${UNIFIED}/trips/5/photos`).set('Cookie', sessionCookie(1));
|
| 119 |
+
expect(res.status).toBe(200);
|
| 120 |
+
expect(res.body).toEqual({ photos: [{ photo_id: 1, asset_id: 'a' }] });
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
it('200 add photos -> { success, added } (POST stays 200, not 201)', async () => {
|
| 124 |
+
unified.addTripPhotos.mockResolvedValue({ success: true, data: { added: 2, shared: true } });
|
| 125 |
+
const res = await request(server).post(`${UNIFIED}/trips/5/photos`).set('Cookie', sessionCookie(1))
|
| 126 |
+
.send({ shared: true, selections: [{ provider: 'immich', asset_ids: ['a', 'b'] }] });
|
| 127 |
+
expect(res.status).toBe(200);
|
| 128 |
+
expect(res.body).toEqual({ success: true, added: 2 });
|
| 129 |
+
// x-socket-id absent -> undefined, matching the legacy `req.headers['x-socket-id'] as string`.
|
| 130 |
+
expect(unified.addTripPhotos).toHaveBeenCalledWith('5', 1, true, [{ provider: 'immich', asset_ids: ['a', 'b'] }], undefined);
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
it('400 add photos with empty selections -> error envelope', async () => {
|
| 134 |
+
unified.addTripPhotos.mockResolvedValue({ success: false, error: { message: 'No photos selected', status: 400 } });
|
| 135 |
+
const res = await request(server).post(`${UNIFIED}/trips/5/photos`).set('Cookie', sessionCookie(1)).send({ selections: [] });
|
| 136 |
+
expect(res.status).toBe(400);
|
| 137 |
+
expect(res.body).toEqual({ error: 'No photos selected' });
|
| 138 |
+
});
|
| 139 |
+
|
| 140 |
+
it('200 PUT sharing -> { success: true }', async () => {
|
| 141 |
+
unified.setTripPhotoSharing.mockResolvedValue({ success: true, data: true });
|
| 142 |
+
const res = await request(server).put(`${UNIFIED}/trips/5/photos/sharing`).set('Cookie', sessionCookie(1)).send({ photo_id: 9, shared: true });
|
| 143 |
+
expect(res.status).toBe(200);
|
| 144 |
+
expect(res.body).toEqual({ success: true });
|
| 145 |
+
});
|
| 146 |
+
|
| 147 |
+
it('404 DELETE photo on inaccessible trip -> error envelope', async () => {
|
| 148 |
+
unified.removeTripPhoto.mockReturnValue({ success: false, error: { message: 'Trip not found or access denied', status: 404 } });
|
| 149 |
+
const res = await request(server).delete(`${UNIFIED}/trips/5/photos`).set('Cookie', sessionCookie(1)).send({ photo_id: 9 });
|
| 150 |
+
expect(res.status).toBe(404);
|
| 151 |
+
expect(res.body).toEqual({ error: 'Trip not found or access denied' });
|
| 152 |
+
});
|
| 153 |
+
|
| 154 |
+
it('200 list album-links -> { links }', async () => {
|
| 155 |
+
unified.listTripAlbumLinks.mockReturnValue({ success: true, data: [{ id: 'l1' }] });
|
| 156 |
+
const res = await request(server).get(`${UNIFIED}/trips/5/album-links`).set('Cookie', sessionCookie(1));
|
| 157 |
+
expect(res.status).toBe(200);
|
| 158 |
+
expect(res.body).toEqual({ links: [{ id: 'l1' }] });
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
it('200 create album-link / 409 duplicate envelope', async () => {
|
| 162 |
+
unified.createTripAlbumLink.mockReturnValue({ success: true, data: true });
|
| 163 |
+
const ok = await request(server).post(`${UNIFIED}/trips/5/album-links`).set('Cookie', sessionCookie(1)).send({ provider: 'immich', album_id: 'al', album_name: 'A' });
|
| 164 |
+
expect(ok.status).toBe(200);
|
| 165 |
+
expect(ok.body).toEqual({ success: true });
|
| 166 |
+
|
| 167 |
+
unified.createTripAlbumLink.mockReturnValue({ success: false, error: { message: 'Album already linked', status: 409 } });
|
| 168 |
+
const dup = await request(server).post(`${UNIFIED}/trips/5/album-links`).set('Cookie', sessionCookie(1)).send({ provider: 'immich', album_id: 'al', album_name: 'A' });
|
| 169 |
+
expect(dup.status).toBe(409);
|
| 170 |
+
expect(dup.body).toEqual({ error: 'Album already linked' });
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
it('200 DELETE album-link -> { success: true }', async () => {
|
| 174 |
+
unified.removeAlbumLink.mockReturnValue({ success: true, data: true });
|
| 175 |
+
const res = await request(server).delete(`${UNIFIED}/trips/5/album-links/7`).set('Cookie', sessionCookie(1));
|
| 176 |
+
expect(res.status).toBe(200);
|
| 177 |
+
expect(res.body).toEqual({ success: true });
|
| 178 |
+
});
|
| 179 |
+
});
|
| 180 |
+
|
| 181 |
+
// ── Immich ───────────────────────────────────────────────────────────────────
|
| 182 |
+
describe('immich', () => {
|
| 183 |
+
it('200 settings', async () => {
|
| 184 |
+
immich.getConnectionSettings.mockReturnValue({ immich_url: '', connected: false, auto_upload: false });
|
| 185 |
+
const res = await request(server).get(`${IMMICH}/settings`).set('Cookie', sessionCookie(1));
|
| 186 |
+
expect(res.status).toBe(200);
|
| 187 |
+
expect(res.body).toEqual({ immich_url: '', connected: false, auto_upload: false });
|
| 188 |
+
});
|
| 189 |
+
|
| 190 |
+
it('200 PUT settings success / 400 invalid url', async () => {
|
| 191 |
+
immich.saveImmichSettings.mockResolvedValue({ success: true });
|
| 192 |
+
const ok = await request(server).put(`${IMMICH}/settings`).set('Cookie', sessionCookie(1)).send({ immich_url: 'https://x', immich_api_key: 'k', auto_upload: true });
|
| 193 |
+
expect(ok.status).toBe(200);
|
| 194 |
+
expect(ok.body).toEqual({ success: true });
|
| 195 |
+
expect(immich.setImmichAutoUpload).toHaveBeenCalledWith(1, true);
|
| 196 |
+
|
| 197 |
+
immich.saveImmichSettings.mockResolvedValue({ success: false, error: 'Invalid Immich URL: bad' });
|
| 198 |
+
const bad = await request(server).put(`${IMMICH}/settings`).set('Cookie', sessionCookie(1)).send({ immich_url: 'bad' });
|
| 199 |
+
expect(bad.status).toBe(400);
|
| 200 |
+
expect(bad.body).toEqual({ error: 'Invalid Immich URL: bad' });
|
| 201 |
+
});
|
| 202 |
+
|
| 203 |
+
it('CRITICAL: 200 /status with { connected: false } on failure', async () => {
|
| 204 |
+
immich.getConnectionStatus.mockResolvedValue({ connected: false, error: 'Not configured' });
|
| 205 |
+
const res = await request(server).get(`${IMMICH}/status`).set('Cookie', sessionCookie(1));
|
| 206 |
+
expect(res.status).toBe(200);
|
| 207 |
+
expect(res.body).toEqual({ connected: false, error: 'Not configured' });
|
| 208 |
+
});
|
| 209 |
+
|
| 210 |
+
it('CRITICAL: 200 /test missing fields -> { connected: false, error } without calling service', async () => {
|
| 211 |
+
const res = await request(server).post(`${IMMICH}/test`).set('Cookie', sessionCookie(1)).send({ immich_url: 'https://x' });
|
| 212 |
+
expect(res.status).toBe(200);
|
| 213 |
+
expect(res.body).toEqual({ connected: false, error: 'URL and API key required' });
|
| 214 |
+
expect(immich.testConnection).not.toHaveBeenCalled();
|
| 215 |
+
});
|
| 216 |
+
|
| 217 |
+
it('200 /test with creds delegates to service', async () => {
|
| 218 |
+
immich.testConnection.mockResolvedValue({ connected: true, user: { name: 'T' } });
|
| 219 |
+
const res = await request(server).post(`${IMMICH}/test`).set('Cookie', sessionCookie(1)).send({ immich_url: 'https://x', immich_api_key: 'k' });
|
| 220 |
+
expect(res.status).toBe(200);
|
| 221 |
+
expect(res.body).toEqual({ connected: true, user: { name: 'T' } });
|
| 222 |
+
});
|
| 223 |
+
|
| 224 |
+
it('200 browse / 400 not configured', async () => {
|
| 225 |
+
immich.browseTimeline.mockResolvedValue({ buckets: [{ count: 3 }] });
|
| 226 |
+
const ok = await request(server).get(`${IMMICH}/browse`).set('Cookie', sessionCookie(1));
|
| 227 |
+
expect(ok.status).toBe(200);
|
| 228 |
+
expect(ok.body).toEqual({ buckets: [{ count: 3 }] });
|
| 229 |
+
|
| 230 |
+
immich.browseTimeline.mockResolvedValue({ error: 'Immich not configured', status: 400 });
|
| 231 |
+
const bad = await request(server).get(`${IMMICH}/browse`).set('Cookie', sessionCookie(1));
|
| 232 |
+
expect(bad.status).toBe(400);
|
| 233 |
+
expect(bad.body).toEqual({ error: 'Immich not configured' });
|
| 234 |
+
});
|
| 235 |
+
|
| 236 |
+
it('200 search (POST stays 200) / 502 envelope', async () => {
|
| 237 |
+
immich.searchPhotos.mockResolvedValue({ assets: [{ id: 'a' }], hasMore: true });
|
| 238 |
+
const ok = await request(server).post(`${IMMICH}/search`).set('Cookie', sessionCookie(1)).send({ page: 1, size: 50 });
|
| 239 |
+
expect(ok.status).toBe(200);
|
| 240 |
+
expect(ok.body).toEqual({ assets: [{ id: 'a' }], hasMore: true });
|
| 241 |
+
expect(immich.searchPhotos).toHaveBeenCalledWith(1, undefined, undefined, 1, 50);
|
| 242 |
+
|
| 243 |
+
immich.searchPhotos.mockResolvedValue({ error: 'Could not reach Immich', status: 502 });
|
| 244 |
+
const bad = await request(server).post(`${IMMICH}/search`).set('Cookie', sessionCookie(1)).send({});
|
| 245 |
+
expect(bad.status).toBe(502);
|
| 246 |
+
expect(bad.body).toEqual({ error: 'Could not reach Immich' });
|
| 247 |
+
});
|
| 248 |
+
|
| 249 |
+
it('200 asset info / 400 invalid id / 403 no access', async () => {
|
| 250 |
+
immich.getAssetInfo.mockResolvedValue({ data: { id: 'asset-1', city: 'Paris' } });
|
| 251 |
+
const ok = await request(server).get(`${IMMICH}/assets/5/asset-1/1/info`).set('Cookie', sessionCookie(1));
|
| 252 |
+
expect(ok.status).toBe(200);
|
| 253 |
+
expect(ok.body).toEqual({ id: 'asset-1', city: 'Paris' });
|
| 254 |
+
|
| 255 |
+
immich.isValidAssetId.mockReturnValue(false);
|
| 256 |
+
const invalid = await request(server).get(`${IMMICH}/assets/5/bad/1/info`).set('Cookie', sessionCookie(1));
|
| 257 |
+
expect(invalid.status).toBe(400);
|
| 258 |
+
expect(invalid.body).toEqual({ error: 'Invalid asset ID' });
|
| 259 |
+
|
| 260 |
+
immich.isValidAssetId.mockReturnValue(true);
|
| 261 |
+
canAccessUserPhoto.mockReturnValue(false);
|
| 262 |
+
const forbidden = await request(server).get(`${IMMICH}/assets/5/asset-1/2/info`).set('Cookie', sessionCookie(1));
|
| 263 |
+
expect(forbidden.status).toBe(403);
|
| 264 |
+
expect(forbidden.body).toEqual({ error: 'Forbidden' });
|
| 265 |
+
});
|
| 266 |
+
|
| 267 |
+
it('streams thumbnail bytes via the service helper', async () => {
|
| 268 |
+
immich.streamImmichAsset.mockImplementation(async (res: any) => {
|
| 269 |
+
res.status(200);
|
| 270 |
+
res.set('Content-Type', 'image/webp');
|
| 271 |
+
res.end(Buffer.from('thumb-bytes'));
|
| 272 |
+
});
|
| 273 |
+
const res = await request(server).get(`${IMMICH}/assets/5/asset-1/1/thumbnail`).set('Cookie', sessionCookie(1));
|
| 274 |
+
expect(res.status).toBe(200);
|
| 275 |
+
expect(res.headers['content-type']).toContain('image/webp');
|
| 276 |
+
expect(immich.streamImmichAsset).toHaveBeenCalledWith(expect.anything(), 1, 'asset-1', 'thumbnail', 1);
|
| 277 |
+
});
|
| 278 |
+
|
| 279 |
+
it('200 albums / 200 album photos', async () => {
|
| 280 |
+
immich.listAlbums.mockResolvedValue({ albums: [{ id: 'al' }] });
|
| 281 |
+
const albums = await request(server).get(`${IMMICH}/albums`).set('Cookie', sessionCookie(1));
|
| 282 |
+
expect(albums.status).toBe(200);
|
| 283 |
+
expect(albums.body).toEqual({ albums: [{ id: 'al' }] });
|
| 284 |
+
|
| 285 |
+
immich.getAlbumPhotos.mockResolvedValue({ assets: [{ id: 'p1' }] });
|
| 286 |
+
const photos = await request(server).get(`${IMMICH}/albums/al/photos`).set('Cookie', sessionCookie(1));
|
| 287 |
+
expect(photos.status).toBe(200);
|
| 288 |
+
expect(photos.body).toEqual({ assets: [{ id: 'p1' }] });
|
| 289 |
+
});
|
| 290 |
+
|
| 291 |
+
it('200 album sync (POST stays 200) / 404 envelope', async () => {
|
| 292 |
+
immich.syncAlbumAssets.mockResolvedValue({ success: true, added: 3, total: 10 });
|
| 293 |
+
const ok = await request(server).post(`${IMMICH}/trips/5/album-links/7/sync`).set('Cookie', sessionCookie(1));
|
| 294 |
+
expect(ok.status).toBe(200);
|
| 295 |
+
expect(ok.body).toEqual({ success: true, added: 3, total: 10 });
|
| 296 |
+
|
| 297 |
+
immich.syncAlbumAssets.mockResolvedValue({ error: 'Album link not found', status: 404 });
|
| 298 |
+
const bad = await request(server).post(`${IMMICH}/trips/5/album-links/9/sync`).set('Cookie', sessionCookie(1));
|
| 299 |
+
expect(bad.status).toBe(404);
|
| 300 |
+
expect(bad.body).toEqual({ error: 'Album link not found' });
|
| 301 |
+
});
|
| 302 |
+
});
|
| 303 |
+
|
| 304 |
+
// ── Synology ───────────────────────────────────────────────────────────────
|
| 305 |
+
describe('synologyphotos', () => {
|
| 306 |
+
it('200 settings', async () => {
|
| 307 |
+
synology.getSynologySettings.mockResolvedValue({ success: true, data: { synology_url: 'u', synology_username: 'n', synology_skip_ssl: true, connected: true } });
|
| 308 |
+
const res = await request(server).get(`${SYNO}/settings`).set('Cookie', sessionCookie(1));
|
| 309 |
+
expect(res.status).toBe(200);
|
| 310 |
+
expect(res.body).toEqual({ synology_url: 'u', synology_username: 'n', synology_skip_ssl: true, connected: true });
|
| 311 |
+
});
|
| 312 |
+
|
| 313 |
+
it('400 PUT settings without url/username -> envelope', async () => {
|
| 314 |
+
const res = await request(server).put(`${SYNO}/settings`).set('Cookie', sessionCookie(1)).send({ synology_url: '' });
|
| 315 |
+
expect(res.status).toBe(400);
|
| 316 |
+
expect(res.body).toEqual({ error: 'URL and username are required' });
|
| 317 |
+
expect(synology.updateSynologySettings).not.toHaveBeenCalled();
|
| 318 |
+
});
|
| 319 |
+
|
| 320 |
+
it('200 PUT settings delegates when valid', async () => {
|
| 321 |
+
synology.updateSynologySettings.mockResolvedValue({ success: true, data: 'settings updated' });
|
| 322 |
+
const res = await request(server).put(`${SYNO}/settings`).set('Cookie', sessionCookie(1)).send({ synology_url: 'https://nas', synology_username: 'admin', synology_password: 'pw' });
|
| 323 |
+
expect(res.status).toBe(200);
|
| 324 |
+
expect(res.body).toEqual('settings updated');
|
| 325 |
+
});
|
| 326 |
+
|
| 327 |
+
it('CRITICAL: 200 /status with { connected: false } on failure', async () => {
|
| 328 |
+
synology.getSynologyStatus.mockResolvedValue({ success: true, data: { connected: false, error: 'Synology not configured' } });
|
| 329 |
+
const res = await request(server).get(`${SYNO}/status`).set('Cookie', sessionCookie(1));
|
| 330 |
+
expect(res.status).toBe(200);
|
| 331 |
+
expect(res.body).toEqual({ connected: false, error: 'Synology not configured' });
|
| 332 |
+
});
|
| 333 |
+
|
| 334 |
+
it('CRITICAL: 200 /test missing fields -> 200 { connected: false, error } without calling service', async () => {
|
| 335 |
+
const res = await request(server).post(`${SYNO}/test`).set('Cookie', sessionCookie(1)).send({ synology_url: 'https://nas' });
|
| 336 |
+
expect(res.status).toBe(200);
|
| 337 |
+
expect(res.body).toEqual({ connected: false, error: 'Username, Password are required' });
|
| 338 |
+
expect(synology.testSynologyConnection).not.toHaveBeenCalled();
|
| 339 |
+
});
|
| 340 |
+
|
| 341 |
+
it('200 /test delegates when all fields present', async () => {
|
| 342 |
+
synology.testSynologyConnection.mockResolvedValue({ success: true, data: { connected: true, user: { name: 'admin' } } });
|
| 343 |
+
const res = await request(server).post(`${SYNO}/test`).set('Cookie', sessionCookie(1)).send({ synology_url: 'https://nas', synology_username: 'admin', synology_password: 'pw' });
|
| 344 |
+
expect(res.status).toBe(200);
|
| 345 |
+
expect(res.body).toEqual({ connected: true, user: { name: 'admin' } });
|
| 346 |
+
});
|
| 347 |
+
|
| 348 |
+
it('200 albums / 200 album photos with passphrase', async () => {
|
| 349 |
+
synology.listSynologyAlbums.mockResolvedValue({ success: true, data: { albums: [{ id: '1', albumName: 'A', assetCount: 3 }] } });
|
| 350 |
+
const albums = await request(server).get(`${SYNO}/albums`).set('Cookie', sessionCookie(1));
|
| 351 |
+
expect(albums.status).toBe(200);
|
| 352 |
+
expect(albums.body).toEqual({ albums: [{ id: '1', albumName: 'A', assetCount: 3 }] });
|
| 353 |
+
|
| 354 |
+
synology.getSynologyAlbumPhotos.mockResolvedValue({ success: true, data: { assets: [{ id: 'p', takenAt: '' }], total: 1, hasMore: false } });
|
| 355 |
+
const photos = await request(server).get(`${SYNO}/albums/1/photos?passphrase=secret`).set('Cookie', sessionCookie(1));
|
| 356 |
+
expect(photos.status).toBe(200);
|
| 357 |
+
expect(photos.body).toEqual({ assets: [{ id: 'p', takenAt: '' }], total: 1, hasMore: false });
|
| 358 |
+
expect(synology.getSynologyAlbumPhotos).toHaveBeenCalledWith(1, '1', 'secret');
|
| 359 |
+
});
|
| 360 |
+
|
| 361 |
+
it('200 search (POST stays 200) with offset/limit coercion', async () => {
|
| 362 |
+
synology.searchSynologyPhotos.mockResolvedValue({ success: true, data: { assets: [], total: 0, hasMore: false } });
|
| 363 |
+
const res = await request(server).post(`${SYNO}/search`).set('Cookie', sessionCookie(1)).send({ page: 3, size: 20 });
|
| 364 |
+
expect(res.status).toBe(200);
|
| 365 |
+
expect(res.body).toEqual({ assets: [], total: 0, hasMore: false });
|
| 366 |
+
// page=3 -> (3-1)=2; size=20 -> limit=20; offset = 2 * 20 = 40
|
| 367 |
+
expect(synology.searchSynologyPhotos).toHaveBeenCalledWith(1, undefined, undefined, 40, 20);
|
| 368 |
+
});
|
| 369 |
+
|
| 370 |
+
it('200 album sync (POST stays 200)', async () => {
|
| 371 |
+
synology.syncSynologyAlbumLink.mockResolvedValue({ success: true, data: { added: 2, total: 5 } });
|
| 372 |
+
const res = await request(server).post(`${SYNO}/trips/5/album-links/7/sync`).set('Cookie', sessionCookie(1));
|
| 373 |
+
expect(res.status).toBe(200);
|
| 374 |
+
expect(res.body).toEqual({ added: 2, total: 5 });
|
| 375 |
+
});
|
| 376 |
+
|
| 377 |
+
it('200 asset info / 403 distinct synology string on no access', async () => {
|
| 378 |
+
synology.getSynologyAssetInfo.mockResolvedValue({ success: true, data: { id: '40808_1', takenAt: null } });
|
| 379 |
+
const ok = await request(server).get(`${SYNO}/assets/5/40808_1/1/info`).set('Cookie', sessionCookie(1));
|
| 380 |
+
expect(ok.status).toBe(200);
|
| 381 |
+
expect(ok.body).toEqual({ id: '40808_1', takenAt: null });
|
| 382 |
+
|
| 383 |
+
canAccessUserPhoto.mockReturnValue(false);
|
| 384 |
+
const forbidden = await request(server).get(`${SYNO}/assets/5/40808_1/2/info`).set('Cookie', sessionCookie(1));
|
| 385 |
+
expect(forbidden.status).toBe(403);
|
| 386 |
+
expect(forbidden.body).toEqual({ error: "You don't have access to this photo" });
|
| 387 |
+
});
|
| 388 |
+
|
| 389 |
+
it('400 invalid asset kind / 403 no access / stream on valid kind', async () => {
|
| 390 |
+
const invalid = await request(server).get(`${SYNO}/assets/5/40808_1/1/bogus`).set('Cookie', sessionCookie(1));
|
| 391 |
+
expect(invalid.status).toBe(400);
|
| 392 |
+
expect(invalid.body).toEqual({ error: 'Invalid asset kind' });
|
| 393 |
+
|
| 394 |
+
canAccessUserPhoto.mockReturnValue(false);
|
| 395 |
+
const forbidden = await request(server).get(`${SYNO}/assets/5/40808_1/2/thumbnail`).set('Cookie', sessionCookie(1));
|
| 396 |
+
expect(forbidden.status).toBe(403);
|
| 397 |
+
expect(forbidden.body).toEqual({ error: "You don't have access to this photo" });
|
| 398 |
+
|
| 399 |
+
canAccessUserPhoto.mockReturnValue(true);
|
| 400 |
+
synology.streamSynologyAsset.mockImplementation(async (res: any) => {
|
| 401 |
+
res.status(200);
|
| 402 |
+
res.set('Content-Type', 'image/jpeg');
|
| 403 |
+
res.end(Buffer.from('syno-bytes'));
|
| 404 |
+
});
|
| 405 |
+
const ok = await request(server).get(`${SYNO}/assets/5/40808_1/1/thumbnail?size=xl`).set('Cookie', sessionCookie(1));
|
| 406 |
+
expect(ok.status).toBe(200);
|
| 407 |
+
expect(ok.headers['content-type']).toContain('image/jpeg');
|
| 408 |
+
expect(synology.streamSynologyAsset).toHaveBeenCalledWith(expect.anything(), 1, 1, '40808_1', 'thumbnail', 'xl', undefined);
|
| 409 |
+
});
|
| 410 |
+
});
|
| 411 |
+
});
|
server/tests/e2e/notifications.e2e.test.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Notifications module e2e — exercises the migrated /api/notifications endpoints
|
| 3 |
+
* through the real JwtAuthGuard against a temp SQLite db. The notification
|
| 4 |
+
* services are mocked; this focuses on auth, the inline admin gate on
|
| 5 |
+
* /test-smtp, routing (the /in-app/all ordering trap) and status/body shapes.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
return { db: tmp };
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 25 |
+
|
| 26 |
+
const { prefs, inapp, channels } = vi.hoisted(() => ({
|
| 27 |
+
prefs: { getPreferencesMatrix: vi.fn(), setPreferences: vi.fn() },
|
| 28 |
+
inapp: {
|
| 29 |
+
getNotifications: vi.fn(), getUnreadCount: vi.fn(), markRead: vi.fn(), markUnread: vi.fn(),
|
| 30 |
+
markAllRead: vi.fn(), deleteNotification: vi.fn(), deleteAll: vi.fn(), respondToBoolean: vi.fn(),
|
| 31 |
+
},
|
| 32 |
+
channels: {
|
| 33 |
+
testSmtp: vi.fn(), testWebhook: vi.fn(), testNtfy: vi.fn(),
|
| 34 |
+
getUserWebhookUrl: vi.fn(), getAdminWebhookUrl: vi.fn(),
|
| 35 |
+
getUserNtfyConfig: vi.fn(), getAdminNtfyConfig: vi.fn(),
|
| 36 |
+
},
|
| 37 |
+
}));
|
| 38 |
+
vi.mock('../../src/services/notificationPreferencesService', () => prefs);
|
| 39 |
+
vi.mock('../../src/services/inAppNotifications', () => inapp);
|
| 40 |
+
vi.mock('../../src/services/notifications', () => channels);
|
| 41 |
+
|
| 42 |
+
import { NotificationsModule } from '../../src/nest/notifications/notifications.module';
|
| 43 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 44 |
+
|
| 45 |
+
describe('Notifications e2e (real auth guard + temp SQLite)', () => {
|
| 46 |
+
let server: Server;
|
| 47 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 48 |
+
|
| 49 |
+
async function build() {
|
| 50 |
+
const moduleRef = await Test.createTestingModule({ imports: [NotificationsModule] }).compile();
|
| 51 |
+
const nest = moduleRef.createNestApplication();
|
| 52 |
+
nest.use(cookieParser());
|
| 53 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 54 |
+
await nest.init();
|
| 55 |
+
return nest;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
beforeAll(async () => {
|
| 59 |
+
seedUser(db as never, { id: 1, role: 'admin', email: 'admin@example.test' });
|
| 60 |
+
seedUser(db as never, { id: 2, role: 'user', email: 'user@example.test' });
|
| 61 |
+
app = await build();
|
| 62 |
+
server = app.getHttpServer();
|
| 63 |
+
prefs.getPreferencesMatrix.mockReturnValue({ preferences: {}, available_channels: {}, event_types: [], implemented_combos: {} });
|
| 64 |
+
inapp.getUnreadCount.mockReturnValue(2);
|
| 65 |
+
inapp.deleteAll.mockReturnValue(4);
|
| 66 |
+
channels.testSmtp.mockResolvedValue({ success: true });
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
afterAll(async () => {
|
| 70 |
+
await app.close();
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
it('401 without a session cookie', async () => {
|
| 74 |
+
const res = await request(server).get('/api/notifications/preferences');
|
| 75 |
+
expect(res.status).toBe(401);
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
it('200 preferences for an authenticated user', async () => {
|
| 79 |
+
const res = await request(server).get('/api/notifications/preferences').set('Cookie', sessionCookie(2));
|
| 80 |
+
expect(res.status).toBe(200);
|
| 81 |
+
expect(res.body).toMatchObject({ preferences: {} });
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it('403 { error: Admin only } when a non-admin hits test-smtp', async () => {
|
| 85 |
+
const res = await request(server).post('/api/notifications/test-smtp').set('Cookie', sessionCookie(2)).send({});
|
| 86 |
+
expect(res.status).toBe(403);
|
| 87 |
+
expect(res.body).toEqual({ error: 'Admin only' });
|
| 88 |
+
expect(channels.testSmtp).not.toHaveBeenCalled();
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
it('200 test-smtp for an admin (stays 200, not 201)', async () => {
|
| 92 |
+
const res = await request(server).post('/api/notifications/test-smtp').set('Cookie', sessionCookie(1)).send({ email: 'x@y.z' });
|
| 93 |
+
expect(res.status).toBe(200);
|
| 94 |
+
expect(res.body).toEqual({ success: true });
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
it('200 unread-count', async () => {
|
| 98 |
+
const res = await request(server).get('/api/notifications/in-app/unread-count').set('Cookie', sessionCookie(2));
|
| 99 |
+
expect(res.status).toBe(200);
|
| 100 |
+
expect(res.body).toEqual({ count: 2 });
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
it('DELETE /in-app/all hits deleteAll, not deleteNotification', async () => {
|
| 104 |
+
const res = await request(server).delete('/api/notifications/in-app/all').set('Cookie', sessionCookie(2));
|
| 105 |
+
expect(res.status).toBe(200);
|
| 106 |
+
expect(res.body).toEqual({ success: true, count: 4 });
|
| 107 |
+
expect(inapp.deleteAll).toHaveBeenCalledWith(2);
|
| 108 |
+
expect(inapp.deleteNotification).not.toHaveBeenCalled();
|
| 109 |
+
});
|
| 110 |
+
|
| 111 |
+
it('400 on a non-numeric in-app id', async () => {
|
| 112 |
+
const res = await request(server).put('/api/notifications/in-app/abc/read').set('Cookie', sessionCookie(2));
|
| 113 |
+
expect(res.status).toBe(400);
|
| 114 |
+
expect(res.body).toEqual({ error: 'Invalid id' });
|
| 115 |
+
});
|
| 116 |
+
});
|
server/tests/e2e/oauth.e2e.test.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* OAuth e2e — exercises the migrated /oauth/* and /api/oauth/* endpoints through
|
| 3 |
+
* the real JwtAuthGuard / CookieAuthGuard / OptionalJwtGuard against a temp
|
| 4 |
+
* SQLite db. The OAuth service + addon gate are mocked; this focuses on the
|
| 5 |
+
* public token/userinfo guards, the MCP 404/403 gates, and the cookie-only auth
|
| 6 |
+
* on the management endpoints (a Bearer must NOT satisfy them).
|
| 7 |
+
*/
|
| 8 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 9 |
+
import request from 'supertest';
|
| 10 |
+
import cookieParser from 'cookie-parser';
|
| 11 |
+
import type { Server } from 'http';
|
| 12 |
+
import { Test } from '@nestjs/testing';
|
| 13 |
+
import { seedUser, sessionCookie, signSession } from './harness';
|
| 14 |
+
|
| 15 |
+
const { db } = vi.hoisted(() => {
|
| 16 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 17 |
+
const Database = require('better-sqlite3');
|
| 18 |
+
const tmp = new Database(':memory:');
|
| 19 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 20 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 21 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 22 |
+
return { db: tmp };
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 26 |
+
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: () => '1.2.3.4', logWarn: vi.fn() }));
|
| 27 |
+
vi.mock('../../src/services/notifications', () => ({ getMcpSafeUrl: () => 'https://app' }));
|
| 28 |
+
|
| 29 |
+
const { isAddonEnabled } = vi.hoisted(() => ({ isAddonEnabled: vi.fn(() => true) }));
|
| 30 |
+
vi.mock('../../src/services/adminService', () => ({ isAddonEnabled }));
|
| 31 |
+
|
| 32 |
+
const { oauthSvc } = vi.hoisted(() => ({
|
| 33 |
+
oauthSvc: {
|
| 34 |
+
validateAuthorizeRequest: vi.fn(), createAuthCode: vi.fn(), consumeAuthCode: vi.fn(), saveConsent: vi.fn(),
|
| 35 |
+
issueTokens: vi.fn(), issueClientCredentialsToken: vi.fn(), refreshTokens: vi.fn(), revokeToken: vi.fn(),
|
| 36 |
+
verifyPKCE: vi.fn(), authenticateClient: vi.fn(), listOAuthClients: vi.fn(), createOAuthClient: vi.fn(),
|
| 37 |
+
deleteOAuthClient: vi.fn(), rotateOAuthClientSecret: vi.fn(), listOAuthSessions: vi.fn(), revokeSession: vi.fn(),
|
| 38 |
+
getUserByAccessToken: vi.fn(),
|
| 39 |
+
},
|
| 40 |
+
}));
|
| 41 |
+
vi.mock('../../src/services/oauthService', () => oauthSvc);
|
| 42 |
+
|
| 43 |
+
import { OauthModule } from '../../src/nest/oauth/oauth.module';
|
| 44 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 45 |
+
|
| 46 |
+
describe('OAuth e2e (real guards + temp SQLite)', () => {
|
| 47 |
+
let server: Server;
|
| 48 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 49 |
+
|
| 50 |
+
async function build() {
|
| 51 |
+
const moduleRef = await Test.createTestingModule({ imports: [OauthModule] }).compile();
|
| 52 |
+
const nest = moduleRef.createNestApplication();
|
| 53 |
+
nest.use(cookieParser());
|
| 54 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 55 |
+
await nest.init();
|
| 56 |
+
return nest;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
beforeAll(async () => {
|
| 60 |
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
| 61 |
+
seedUser(db as never, { id: 1 });
|
| 62 |
+
app = await build();
|
| 63 |
+
server = app.getHttpServer();
|
| 64 |
+
oauthSvc.listOAuthClients.mockReturnValue([{ id: 'c1' }]);
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
beforeEach(() => { isAddonEnabled.mockReturnValue(true); });
|
| 68 |
+
|
| 69 |
+
afterAll(async () => {
|
| 70 |
+
await app.close();
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
it('POST /oauth/token is public — 401 invalid_client without client_id', async () => {
|
| 74 |
+
const res = await request(server).post('/oauth/token').send({});
|
| 75 |
+
expect(res.status).toBe(401);
|
| 76 |
+
expect(res.body).toEqual({ error: 'invalid_client', error_description: 'client_id is required' });
|
| 77 |
+
expect(res.headers['cache-control']).toBe('no-store');
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it('POST /oauth/token 404 (empty) when MCP is disabled', async () => {
|
| 81 |
+
isAddonEnabled.mockReturnValue(false);
|
| 82 |
+
const res = await request(server).post('/oauth/token').send({ client_id: 'c' });
|
| 83 |
+
expect(res.status).toBe(404);
|
| 84 |
+
expect(res.text).toBe('');
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
it('GET /oauth/userinfo 401 with a WWW-Authenticate challenge', async () => {
|
| 88 |
+
const res = await request(server).get('/oauth/userinfo');
|
| 89 |
+
expect(res.status).toBe(401);
|
| 90 |
+
expect(res.headers['www-authenticate']).toContain('Bearer');
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it('GET /api/oauth/clients 401 without a session', async () => {
|
| 94 |
+
expect((await request(server).get('/api/oauth/clients')).status).toBe(401);
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
it('GET /api/oauth/clients works with a Bearer (authenticate) session', async () => {
|
| 98 |
+
const res = await request(server).get('/api/oauth/clients').set('Authorization', `Bearer ${signSession(1)}`);
|
| 99 |
+
expect(res.status).toBe(200);
|
| 100 |
+
expect(res.body).toEqual({ clients: [{ id: 'c1' }] });
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
it('POST /api/oauth/clients requires a COOKIE session (a Bearer is rejected)', async () => {
|
| 104 |
+
const bearer = await request(server).post('/api/oauth/clients').set('Authorization', `Bearer ${signSession(1)}`).send({ name: 'CLI', allowed_scopes: ['a'] });
|
| 105 |
+
expect(bearer.status).toBe(401);
|
| 106 |
+
expect(bearer.body).toEqual({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' });
|
| 107 |
+
|
| 108 |
+
oauthSvc.createOAuthClient.mockReturnValue({ client_id: 'c1', client_secret: 's' });
|
| 109 |
+
const cookie = await request(server).post('/api/oauth/clients').set('Cookie', sessionCookie(1)).send({ name: 'CLI', allowed_scopes: ['a'] });
|
| 110 |
+
expect(cookie.status).toBe(201);
|
| 111 |
+
expect(cookie.body).toEqual({ client_id: 'c1', client_secret: 's' });
|
| 112 |
+
});
|
| 113 |
+
});
|
server/tests/e2e/oidc.e2e.test.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* OIDC e2e — exercises the migrated /api/auth/oidc flow with the real cookie
|
| 3 |
+
* service. The OIDC service + auth toggles are mocked; this proves the flow is
|
| 4 |
+
* unauthenticated, the sso-disabled 403, the login redirect, and that /exchange
|
| 5 |
+
* sets the httpOnly trek_session cookie from a valid auth code.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
|
| 13 |
+
vi.mock('../../src/services/notifications', () => ({ getAppUrl: () => 'https://app' }));
|
| 14 |
+
|
| 15 |
+
const { toggles } = vi.hoisted(() => ({ toggles: { oidc_login: true } }));
|
| 16 |
+
vi.mock('../../src/services/authService', () => ({ resolveAuthToggles: () => toggles }));
|
| 17 |
+
|
| 18 |
+
const { oidcSvc } = vi.hoisted(() => ({
|
| 19 |
+
oidcSvc: {
|
| 20 |
+
getOidcConfig: vi.fn(), discover: vi.fn(), createState: vi.fn(), consumeState: vi.fn(), createAuthCode: vi.fn(),
|
| 21 |
+
consumeAuthCode: vi.fn(), exchangeCodeForToken: vi.fn(), getUserInfo: vi.fn(), verifyIdToken: vi.fn(),
|
| 22 |
+
findOrCreateUser: vi.fn(), touchLastLogin: vi.fn(), generateToken: vi.fn(), frontendUrl: (p: string) => 'https://app' + p,
|
| 23 |
+
},
|
| 24 |
+
}));
|
| 25 |
+
vi.mock('../../src/services/oidcService', () => oidcSvc);
|
| 26 |
+
|
| 27 |
+
import { OidcModule } from '../../src/nest/oidc/oidc.module';
|
| 28 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 29 |
+
|
| 30 |
+
describe('OIDC e2e (real cookie service)', () => {
|
| 31 |
+
let server: Server;
|
| 32 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 33 |
+
|
| 34 |
+
async function build() {
|
| 35 |
+
const moduleRef = await Test.createTestingModule({ imports: [OidcModule] }).compile();
|
| 36 |
+
const nest = moduleRef.createNestApplication();
|
| 37 |
+
nest.use(cookieParser());
|
| 38 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 39 |
+
await nest.init();
|
| 40 |
+
return nest;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
beforeAll(async () => {
|
| 44 |
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
| 45 |
+
app = await build();
|
| 46 |
+
server = app.getHttpServer();
|
| 47 |
+
oidcSvc.getOidcConfig.mockReturnValue({ issuer: 'https://idp', clientId: 'c', clientSecret: 's', discoveryUrl: null });
|
| 48 |
+
oidcSvc.discover.mockResolvedValue({ authorization_endpoint: 'https://idp/auth', userinfo_endpoint: 'https://idp/ui', issuer: 'https://idp' });
|
| 49 |
+
oidcSvc.createState.mockReturnValue({ state: 'st', codeChallenge: 'cc' });
|
| 50 |
+
oidcSvc.consumeAuthCode.mockReturnValue({ token: 'jwt.value' });
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
beforeEach(() => { toggles.oidc_login = true; });
|
| 54 |
+
|
| 55 |
+
afterAll(async () => {
|
| 56 |
+
await app.close();
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
it('GET /login is unauthenticated and redirects (302) to the provider', async () => {
|
| 60 |
+
const res = await request(server).get('/api/auth/oidc/login').redirects(0);
|
| 61 |
+
expect(res.status).toBe(302);
|
| 62 |
+
expect(res.headers.location).toContain('https://idp/auth?');
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
it('GET /login returns 403 when SSO is disabled', async () => {
|
| 66 |
+
toggles.oidc_login = false;
|
| 67 |
+
const res = await request(server).get('/api/auth/oidc/login');
|
| 68 |
+
expect(res.status).toBe(403);
|
| 69 |
+
expect(res.body).toEqual({ error: 'SSO login is disabled.' });
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
it('GET /exchange 400 without a code', async () => {
|
| 73 |
+
const res = await request(server).get('/api/auth/oidc/exchange');
|
| 74 |
+
expect(res.status).toBe(400);
|
| 75 |
+
expect(res.body).toEqual({ error: 'Code required' });
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
it('GET /exchange sets the httpOnly trek_session cookie + returns the token', async () => {
|
| 79 |
+
oidcSvc.consumeAuthCode.mockReturnValue({ token: 'jwt.value' });
|
| 80 |
+
const res = await request(server).get('/api/auth/oidc/exchange').query({ code: 'good' });
|
| 81 |
+
expect(res.status).toBe(200);
|
| 82 |
+
expect(res.body).toEqual({ token: 'jwt.value' });
|
| 83 |
+
const setCookie = res.headers['set-cookie'] as unknown as string[];
|
| 84 |
+
expect(setCookie.some((c) => c.startsWith('trek_session=') && /HttpOnly/i.test(c))).toBe(true);
|
| 85 |
+
});
|
| 86 |
+
});
|
server/tests/e2e/packing.e2e.test.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Packing module e2e — exercises the migrated /api/trips/:tripId/packing
|
| 3 |
+
* endpoints through the real JwtAuthGuard against a temp SQLite db. The packing
|
| 4 |
+
* service, permission check and WebSocket broadcast are mocked; this focuses on
|
| 5 |
+
* auth, trip-access 404, permission 403, status codes and bodies.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
|
| 22 |
+
return { db: tmp };
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 26 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 27 |
+
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
| 28 |
+
|
| 29 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 30 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 31 |
+
|
| 32 |
+
const { svc } = vi.hoisted(() => ({
|
| 33 |
+
svc: {
|
| 34 |
+
verifyTripAccess: vi.fn(), listItems: vi.fn(), createItem: vi.fn(), updateItem: vi.fn(),
|
| 35 |
+
deleteItem: vi.fn(), bulkImport: vi.fn(), reorderItems: vi.fn(), listBags: vi.fn(),
|
| 36 |
+
createBag: vi.fn(), updateBag: vi.fn(), deleteBag: vi.fn(), applyTemplate: vi.fn(),
|
| 37 |
+
saveAsTemplate: vi.fn(), setBagMembers: vi.fn(), getCategoryAssignees: vi.fn(),
|
| 38 |
+
updateCategoryAssignees: vi.fn(),
|
| 39 |
+
},
|
| 40 |
+
}));
|
| 41 |
+
vi.mock('../../src/services/packingService', () => svc);
|
| 42 |
+
|
| 43 |
+
import { PackingModule } from '../../src/nest/packing/packing.module';
|
| 44 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 45 |
+
|
| 46 |
+
describe('Packing e2e (real auth guard + temp SQLite)', () => {
|
| 47 |
+
let server: Server;
|
| 48 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 49 |
+
|
| 50 |
+
async function build() {
|
| 51 |
+
const moduleRef = await Test.createTestingModule({ imports: [PackingModule] }).compile();
|
| 52 |
+
const nest = moduleRef.createNestApplication();
|
| 53 |
+
nest.use(cookieParser());
|
| 54 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 55 |
+
await nest.init();
|
| 56 |
+
return nest;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
beforeAll(async () => {
|
| 60 |
+
seedUser(db as never, { id: 1 });
|
| 61 |
+
app = await build();
|
| 62 |
+
server = app.getHttpServer();
|
| 63 |
+
svc.listItems.mockReturnValue([{ id: 1, name: 'Socks' }]);
|
| 64 |
+
svc.createItem.mockReturnValue({ id: 9, name: 'Socks' });
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
beforeEach(() => {
|
| 68 |
+
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
| 69 |
+
checkPermission.mockReturnValue(true);
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
afterAll(async () => {
|
| 73 |
+
await app.close();
|
| 74 |
+
});
|
| 75 |
+
|
| 76 |
+
it('401 without a session cookie', async () => {
|
| 77 |
+
const res = await request(server).get('/api/trips/5/packing');
|
| 78 |
+
expect(res.status).toBe(401);
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('200 list for an accessible trip', async () => {
|
| 82 |
+
const res = await request(server).get('/api/trips/5/packing').set('Cookie', sessionCookie(1));
|
| 83 |
+
expect(res.status).toBe(200);
|
| 84 |
+
expect(res.body).toEqual({ items: [{ id: 1, name: 'Socks' }] });
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
it('404 when the trip is not accessible', async () => {
|
| 88 |
+
svc.verifyTripAccess.mockReturnValue(undefined);
|
| 89 |
+
const res = await request(server).get('/api/trips/5/packing').set('Cookie', sessionCookie(1));
|
| 90 |
+
expect(res.status).toBe(404);
|
| 91 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it('201 on create with permission', async () => {
|
| 95 |
+
const res = await request(server).post('/api/trips/5/packing').set('Cookie', sessionCookie(1)).send({ name: 'Socks' });
|
| 96 |
+
expect(res.status).toBe(201);
|
| 97 |
+
expect(res.body).toEqual({ item: { id: 9, name: 'Socks' } });
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
it('403 on create without permission', async () => {
|
| 101 |
+
checkPermission.mockReturnValue(false);
|
| 102 |
+
const res = await request(server).post('/api/trips/5/packing').set('Cookie', sessionCookie(1)).send({ name: 'Socks' });
|
| 103 |
+
expect(res.status).toBe(403);
|
| 104 |
+
expect(res.body).toEqual({ error: 'No permission' });
|
| 105 |
+
});
|
| 106 |
+
});
|
server/tests/e2e/places.e2e.test.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Places module e2e — exercises the migrated /api/trips/:tripId/places endpoints
|
| 3 |
+
* through the real JwtAuthGuard against a temp SQLite db. placeService,
|
| 4 |
+
* journeyService, the permission check, canAccessTrip and the WebSocket
|
| 5 |
+
* broadcast are mocked.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
return { db: tmp };
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
| 25 |
+
vi.mock('../../src/db/database', () => ({
|
| 26 |
+
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
| 27 |
+
}));
|
| 28 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 29 |
+
vi.mock('../../src/services/journeyService', () => ({ onPlaceCreated: vi.fn(), onPlaceUpdated: vi.fn(), onPlaceDeleted: vi.fn() }));
|
| 30 |
+
|
| 31 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 32 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 33 |
+
|
| 34 |
+
const { pl } = vi.hoisted(() => ({
|
| 35 |
+
pl: {
|
| 36 |
+
listPlaces: vi.fn(), createPlace: vi.fn(), getPlace: vi.fn(), updatePlace: vi.fn(), deletePlace: vi.fn(),
|
| 37 |
+
deletePlacesMany: vi.fn(), importGpx: vi.fn(), importMapFile: vi.fn(), importGoogleList: vi.fn(),
|
| 38 |
+
importNaverList: vi.fn(), searchPlaceImage: vi.fn(),
|
| 39 |
+
},
|
| 40 |
+
}));
|
| 41 |
+
vi.mock('../../src/services/placeService', () => pl);
|
| 42 |
+
|
| 43 |
+
import { PlacesModule } from '../../src/nest/places/places.module';
|
| 44 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 45 |
+
|
| 46 |
+
describe('Places e2e (real auth guard + temp SQLite)', () => {
|
| 47 |
+
let server: Server;
|
| 48 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 49 |
+
|
| 50 |
+
async function build() {
|
| 51 |
+
const moduleRef = await Test.createTestingModule({ imports: [PlacesModule] }).compile();
|
| 52 |
+
const nest = moduleRef.createNestApplication();
|
| 53 |
+
nest.use(cookieParser());
|
| 54 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 55 |
+
await nest.init();
|
| 56 |
+
return nest;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
beforeAll(async () => {
|
| 60 |
+
seedUser(db as never, { id: 1 });
|
| 61 |
+
app = await build();
|
| 62 |
+
server = app.getHttpServer();
|
| 63 |
+
pl.listPlaces.mockReturnValue([{ id: 1, name: 'Spot' }]);
|
| 64 |
+
pl.createPlace.mockReturnValue({ id: 9, name: 'Spot' });
|
| 65 |
+
pl.deletePlacesMany.mockReturnValue([1, 2]);
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
beforeEach(() => {
|
| 69 |
+
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
| 70 |
+
checkPermission.mockReturnValue(true);
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
afterAll(async () => {
|
| 74 |
+
await app.close();
|
| 75 |
+
});
|
| 76 |
+
|
| 77 |
+
it('401 without a cookie', async () => {
|
| 78 |
+
expect((await request(server).get('/api/trips/5/places')).status).toBe(401);
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('200 list', async () => {
|
| 82 |
+
const res = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
|
| 83 |
+
expect(res.status).toBe(200);
|
| 84 |
+
expect(res.body).toEqual({ places: [{ id: 1, name: 'Spot' }] });
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
it('201 create, 403 without permission, 400 over-long name', async () => {
|
| 88 |
+
const ok = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({ name: 'Spot' });
|
| 89 |
+
expect(ok.status).toBe(201);
|
| 90 |
+
expect(ok.body).toEqual({ place: { id: 9, name: 'Spot' } });
|
| 91 |
+
const long = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({ name: 'x'.repeat(201) });
|
| 92 |
+
expect(long.status).toBe(400);
|
| 93 |
+
expect(long.body).toEqual({ error: 'name must be 200 characters or less' });
|
| 94 |
+
checkPermission.mockReturnValue(false);
|
| 95 |
+
const forbidden = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({ name: 'Spot' });
|
| 96 |
+
expect(forbidden.status).toBe(403);
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
it('200 (not 201) bulk-delete, 400 on bad ids', async () => {
|
| 100 |
+
const ok = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: [1, 2] });
|
| 101 |
+
expect(ok.status).toBe(200);
|
| 102 |
+
expect(ok.body).toEqual({ deleted: [1, 2], count: 2 });
|
| 103 |
+
const bad = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: ['a'] });
|
| 104 |
+
expect(bad.status).toBe(400);
|
| 105 |
+
expect(bad.body).toEqual({ error: 'ids must be an array of numbers' });
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
it('404 trip when not accessible', async () => {
|
| 109 |
+
canAccessTrip.mockReturnValue(undefined);
|
| 110 |
+
const res = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
|
| 111 |
+
expect(res.status).toBe(404);
|
| 112 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 113 |
+
});
|
| 114 |
+
});
|
server/tests/e2e/reservations.e2e.test.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Reservations + accommodations module e2e — exercises both migrated mounts
|
| 3 |
+
* through the real JwtAuthGuard against a temp SQLite db. The reservation/day/
|
| 4 |
+
* budget services, the permission check, canAccessTrip and the WebSocket
|
| 5 |
+
* broadcast are mocked.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
|
| 22 |
+
return { db: tmp };
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
| 26 |
+
vi.mock('../../src/db/database', () => ({
|
| 27 |
+
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
| 28 |
+
}));
|
| 29 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 30 |
+
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
| 31 |
+
|
| 32 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 33 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 34 |
+
|
| 35 |
+
const { resv, budget, day } = vi.hoisted(() => ({
|
| 36 |
+
resv: {
|
| 37 |
+
verifyTripAccess: vi.fn(), listReservations: vi.fn(), createReservation: vi.fn(), updatePositions: vi.fn(),
|
| 38 |
+
getReservation: vi.fn(), updateReservation: vi.fn(), deleteReservation: vi.fn(), getUpcomingReservations: vi.fn(),
|
| 39 |
+
},
|
| 40 |
+
budget: { createBudgetItem: vi.fn(), updateBudgetItem: vi.fn(), deleteBudgetItem: vi.fn(), linkBudgetItemToReservation: vi.fn() },
|
| 41 |
+
day: {
|
| 42 |
+
listAccommodations: vi.fn(), validateAccommodationRefs: vi.fn(), createAccommodation: vi.fn(),
|
| 43 |
+
getAccommodation: vi.fn(), updateAccommodation: vi.fn(), deleteAccommodation: vi.fn(),
|
| 44 |
+
},
|
| 45 |
+
}));
|
| 46 |
+
vi.mock('../../src/services/reservationService', () => resv);
|
| 47 |
+
vi.mock('../../src/services/budgetService', () => budget);
|
| 48 |
+
vi.mock('../../src/services/dayService', () => day);
|
| 49 |
+
|
| 50 |
+
import { ReservationsModule } from '../../src/nest/reservations/reservations.module';
|
| 51 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 52 |
+
|
| 53 |
+
describe('Reservations + accommodations e2e (real auth guard + temp SQLite)', () => {
|
| 54 |
+
let server: Server;
|
| 55 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 56 |
+
|
| 57 |
+
async function build() {
|
| 58 |
+
const moduleRef = await Test.createTestingModule({ imports: [ReservationsModule] }).compile();
|
| 59 |
+
const nest = moduleRef.createNestApplication();
|
| 60 |
+
nest.use(cookieParser());
|
| 61 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 62 |
+
await nest.init();
|
| 63 |
+
return nest;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
beforeAll(async () => {
|
| 67 |
+
seedUser(db as never, { id: 1 });
|
| 68 |
+
app = await build();
|
| 69 |
+
server = app.getHttpServer();
|
| 70 |
+
resv.listReservations.mockReturnValue([{ id: 1, title: 'Hotel' }]);
|
| 71 |
+
resv.createReservation.mockReturnValue({ reservation: { id: 9, title: 'Hotel' }, accommodationCreated: false });
|
| 72 |
+
day.listAccommodations.mockReturnValue([{ id: 1 }]);
|
| 73 |
+
day.validateAccommodationRefs.mockReturnValue([]);
|
| 74 |
+
day.createAccommodation.mockReturnValue({ id: 9 });
|
| 75 |
+
resv.getUpcomingReservations.mockReturnValue([{ id: 1, trip_id: 5, title: 'Flight' }]);
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
beforeEach(() => {
|
| 79 |
+
resv.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
| 80 |
+
canAccessTrip.mockReturnValue({ id: 5, user_id: 1 });
|
| 81 |
+
checkPermission.mockReturnValue(true);
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
afterAll(async () => {
|
| 85 |
+
await app.close();
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
it('401 without a cookie (reservations)', async () => {
|
| 89 |
+
expect((await request(server).get('/api/trips/5/reservations')).status).toBe(401);
|
| 90 |
+
});
|
| 91 |
+
|
| 92 |
+
it('200 list reservations', async () => {
|
| 93 |
+
const res = await request(server).get('/api/trips/5/reservations').set('Cookie', sessionCookie(1));
|
| 94 |
+
expect(res.status).toBe(200);
|
| 95 |
+
expect(res.body).toEqual({ reservations: [{ id: 1, title: 'Hotel' }] });
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
it('401 without a cookie (upcoming feed)', async () => {
|
| 99 |
+
expect((await request(server).get('/api/reservations/upcoming')).status).toBe(401);
|
| 100 |
+
});
|
| 101 |
+
|
| 102 |
+
it('200 cross-trip upcoming reservations feed', async () => {
|
| 103 |
+
const res = await request(server).get('/api/reservations/upcoming').set('Cookie', sessionCookie(1));
|
| 104 |
+
expect(res.status).toBe(200);
|
| 105 |
+
expect(res.body).toEqual({ reservations: [{ id: 1, trip_id: 5, title: 'Flight' }] });
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
it('404 when trip not accessible (reservations)', async () => {
|
| 109 |
+
resv.verifyTripAccess.mockReturnValue(undefined);
|
| 110 |
+
const res = await request(server).get('/api/trips/5/reservations').set('Cookie', sessionCookie(1));
|
| 111 |
+
expect(res.status).toBe(404);
|
| 112 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 113 |
+
});
|
| 114 |
+
|
| 115 |
+
it('201 create reservation, 400 without title', async () => {
|
| 116 |
+
const ok = await request(server).post('/api/trips/5/reservations').set('Cookie', sessionCookie(1)).send({ title: 'Hotel' });
|
| 117 |
+
expect(ok.status).toBe(201);
|
| 118 |
+
expect(ok.body).toEqual({ reservation: { id: 9, title: 'Hotel' } });
|
| 119 |
+
const bad = await request(server).post('/api/trips/5/reservations').set('Cookie', sessionCookie(1)).send({});
|
| 120 |
+
expect(bad.status).toBe(400);
|
| 121 |
+
expect(bad.body).toEqual({ error: 'Title is required' });
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
it('200 list accommodations + 201 create', async () => {
|
| 125 |
+
const list = await request(server).get('/api/trips/5/accommodations').set('Cookie', sessionCookie(1));
|
| 126 |
+
expect(list.status).toBe(200);
|
| 127 |
+
expect(list.body).toEqual({ accommodations: [{ id: 1 }] });
|
| 128 |
+
const create = await request(server).post('/api/trips/5/accommodations').set('Cookie', sessionCookie(1)).send({ place_id: 2, start_day_id: 10, end_day_id: 11 });
|
| 129 |
+
expect(create.status).toBe(201);
|
| 130 |
+
expect(create.body).toEqual({ accommodation: { id: 9 } });
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
it('404 when trip not accessible (accommodations)', async () => {
|
| 134 |
+
canAccessTrip.mockReturnValue(undefined);
|
| 135 |
+
const res = await request(server).get('/api/trips/5/accommodations').set('Cookie', sessionCookie(1));
|
| 136 |
+
expect(res.status).toBe(404);
|
| 137 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 138 |
+
});
|
| 139 |
+
|
| 140 |
+
it('400 accommodation create without refs', async () => {
|
| 141 |
+
const res = await request(server).post('/api/trips/5/accommodations').set('Cookie', sessionCookie(1)).send({ place_id: 2 });
|
| 142 |
+
expect(res.status).toBe(400);
|
| 143 |
+
expect(res.body).toEqual({ error: 'place_id, start_day_id, and end_day_id are required' });
|
| 144 |
+
});
|
| 145 |
+
});
|
server/tests/e2e/settings.e2e.test.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Settings e2e — exercises the migrated /api/settings endpoints through the real
|
| 3 |
+
* JwtAuthGuard against a temp SQLite db. The settings service is mocked; this
|
| 4 |
+
* focuses on auth, the 400 guards, the masked-sentinel no-op and status codes.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 24 |
+
|
| 25 |
+
const { settingsSvc } = vi.hoisted(() => ({
|
| 26 |
+
settingsSvc: { getUserSettings: vi.fn(), upsertSetting: vi.fn(), bulkUpsertSettings: vi.fn() },
|
| 27 |
+
}));
|
| 28 |
+
vi.mock('../../src/services/settingsService', () => settingsSvc);
|
| 29 |
+
|
| 30 |
+
import { SettingsModule } from '../../src/nest/settings/settings.module';
|
| 31 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 32 |
+
|
| 33 |
+
describe('Settings e2e (real auth guard + temp SQLite)', () => {
|
| 34 |
+
let server: Server;
|
| 35 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 36 |
+
|
| 37 |
+
async function build() {
|
| 38 |
+
const moduleRef = await Test.createTestingModule({ imports: [SettingsModule] }).compile();
|
| 39 |
+
const nest = moduleRef.createNestApplication();
|
| 40 |
+
nest.use(cookieParser());
|
| 41 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 42 |
+
await nest.init();
|
| 43 |
+
return nest;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
beforeAll(async () => {
|
| 47 |
+
seedUser(db as never, { id: 1 });
|
| 48 |
+
app = await build();
|
| 49 |
+
server = app.getHttpServer();
|
| 50 |
+
settingsSvc.getUserSettings.mockReturnValue({ theme: 'dark' });
|
| 51 |
+
settingsSvc.bulkUpsertSettings.mockReturnValue(2);
|
| 52 |
+
});
|
| 53 |
+
|
| 54 |
+
beforeEach(() => vi.clearAllMocks());
|
| 55 |
+
|
| 56 |
+
afterAll(async () => {
|
| 57 |
+
await app.close();
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
it('401 without a session cookie', async () => {
|
| 61 |
+
expect((await request(server).get('/api/settings')).status).toBe(401);
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
it('200 list with a session', async () => {
|
| 65 |
+
settingsSvc.getUserSettings.mockReturnValue({ theme: 'dark' });
|
| 66 |
+
const res = await request(server).get('/api/settings').set('Cookie', sessionCookie(1));
|
| 67 |
+
expect(res.status).toBe(200);
|
| 68 |
+
expect(res.body).toEqual({ settings: { theme: 'dark' } });
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
it('PUT 400 without a key', async () => {
|
| 72 |
+
const res = await request(server).put('/api/settings').set('Cookie', sessionCookie(1)).send({ value: 'x' });
|
| 73 |
+
expect(res.status).toBe(400);
|
| 74 |
+
expect(res.body).toEqual({ error: 'Key is required' });
|
| 75 |
+
});
|
| 76 |
+
|
| 77 |
+
it('PUT no-ops on the masked sentinel', async () => {
|
| 78 |
+
const res = await request(server).put('/api/settings').set('Cookie', sessionCookie(1)).send({ key: 'secret', value: '••••••••' });
|
| 79 |
+
expect(res.status).toBe(200);
|
| 80 |
+
expect(res.body).toEqual({ success: true, key: 'secret', unchanged: true });
|
| 81 |
+
expect(settingsSvc.upsertSetting).not.toHaveBeenCalled();
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it('POST /bulk 200', async () => {
|
| 85 |
+
settingsSvc.bulkUpsertSettings.mockReturnValue(2);
|
| 86 |
+
const res = await request(server).post('/api/settings/bulk').set('Cookie', sessionCookie(1)).send({ settings: { a: 1, b: 2 } });
|
| 87 |
+
expect(res.status).toBe(200);
|
| 88 |
+
expect(res.body).toEqual({ success: true, updated: 2 });
|
| 89 |
+
});
|
| 90 |
+
});
|
server/tests/e2e/share.e2e.test.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Share-link e2e — exercises the migrated /api/trips/:tripId/share-link and the
|
| 3 |
+
* public /api/shared/:token endpoints through the real JwtAuthGuard against a
|
| 4 |
+
* temp SQLite db. The share service + permission check are mocked; this focuses
|
| 5 |
+
* on auth, trip-access 404, permission 403, the create-201-vs-update-200 split
|
| 6 |
+
* and the unguarded public read.
|
| 7 |
+
*/
|
| 8 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 9 |
+
import request from 'supertest';
|
| 10 |
+
import cookieParser from 'cookie-parser';
|
| 11 |
+
import os from 'node:os';
|
| 12 |
+
import path from 'node:path';
|
| 13 |
+
import fs from 'node:fs';
|
| 14 |
+
import type { Server } from 'http';
|
| 15 |
+
import { Test } from '@nestjs/testing';
|
| 16 |
+
import { seedUser, sessionCookie } from './harness';
|
| 17 |
+
|
| 18 |
+
const { db, canAccessTrip } = vi.hoisted(() => {
|
| 19 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 20 |
+
const Database = require('better-sqlite3');
|
| 21 |
+
const tmp = new Database(':memory:');
|
| 22 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 23 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 24 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 25 |
+
return { db: tmp, canAccessTrip: vi.fn() };
|
| 26 |
+
});
|
| 27 |
+
|
| 28 |
+
vi.mock('../../src/db/database', () => ({ db, canAccessTrip, closeDb: () => {}, reinitialize: () => {} }));
|
| 29 |
+
|
| 30 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 31 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 32 |
+
|
| 33 |
+
const { shareSvc } = vi.hoisted(() => ({
|
| 34 |
+
shareSvc: { createOrUpdateShareLink: vi.fn(), getShareLink: vi.fn(), deleteShareLink: vi.fn(), getSharedTripData: vi.fn(), getSharedPlacePhotoPath: vi.fn() },
|
| 35 |
+
}));
|
| 36 |
+
vi.mock('../../src/services/shareService', () => shareSvc);
|
| 37 |
+
|
| 38 |
+
import { ShareModule } from '../../src/nest/share/share.module';
|
| 39 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 40 |
+
|
| 41 |
+
describe('Share-link e2e (real auth guard + temp SQLite)', () => {
|
| 42 |
+
let server: Server;
|
| 43 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 44 |
+
|
| 45 |
+
async function build() {
|
| 46 |
+
const moduleRef = await Test.createTestingModule({ imports: [ShareModule] }).compile();
|
| 47 |
+
const nest = moduleRef.createNestApplication();
|
| 48 |
+
nest.use(cookieParser());
|
| 49 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 50 |
+
await nest.init();
|
| 51 |
+
return nest;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
beforeAll(async () => {
|
| 55 |
+
seedUser(db as never, { id: 1 });
|
| 56 |
+
app = await build();
|
| 57 |
+
server = app.getHttpServer();
|
| 58 |
+
shareSvc.getSharedTripData.mockReturnValue({ trip: { id: 9 } });
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
beforeEach(() => {
|
| 62 |
+
canAccessTrip.mockReturnValue({ user_id: 1 });
|
| 63 |
+
checkPermission.mockReturnValue(true);
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
afterAll(async () => {
|
| 67 |
+
await app.close();
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
it('401 without a session cookie', async () => {
|
| 71 |
+
expect((await request(server).get('/api/trips/5/share-link')).status).toBe(401);
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
it('201 on first create, 200 on a subsequent update', async () => {
|
| 75 |
+
shareSvc.createOrUpdateShareLink.mockReturnValueOnce({ token: 't', created: true });
|
| 76 |
+
const created = await request(server).post('/api/trips/5/share-link').set('Cookie', sessionCookie(1)).send({ share_map: true });
|
| 77 |
+
expect(created.status).toBe(201);
|
| 78 |
+
expect(created.body).toEqual({ token: 't' });
|
| 79 |
+
|
| 80 |
+
shareSvc.createOrUpdateShareLink.mockReturnValueOnce({ token: 't', created: false });
|
| 81 |
+
const updated = await request(server).post('/api/trips/5/share-link').set('Cookie', sessionCookie(1)).send({});
|
| 82 |
+
expect(updated.status).toBe(200);
|
| 83 |
+
expect(updated.body).toEqual({ token: 't' });
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
it('403 without share_manage', async () => {
|
| 87 |
+
checkPermission.mockReturnValue(false);
|
| 88 |
+
const res = await request(server).post('/api/trips/5/share-link').set('Cookie', sessionCookie(1)).send({});
|
| 89 |
+
expect(res.status).toBe(403);
|
| 90 |
+
expect(res.body).toEqual({ error: 'No permission' });
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it('404 when the trip is not accessible', async () => {
|
| 94 |
+
canAccessTrip.mockReturnValue(undefined);
|
| 95 |
+
const res = await request(server).get('/api/trips/5/share-link').set('Cookie', sessionCookie(1));
|
| 96 |
+
expect(res.status).toBe(404);
|
| 97 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
it('public shared read is unguarded (200, no cookie)', async () => {
|
| 101 |
+
const res = await request(server).get('/api/shared/tok');
|
| 102 |
+
expect(res.status).toBe(200);
|
| 103 |
+
expect(res.body).toEqual({ trip: { id: 9 } });
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
it('public shared read 404 for an invalid token', async () => {
|
| 107 |
+
shareSvc.getSharedTripData.mockReturnValueOnce(null);
|
| 108 |
+
const res = await request(server).get('/api/shared/bad');
|
| 109 |
+
expect(res.status).toBe(404);
|
| 110 |
+
expect(res.body).toEqual({ error: 'Invalid or expired link' });
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
describe('public place-photo proxy (/api/shared/:token/place-photo/:placeId/bytes)', () => {
|
| 114 |
+
const photoFile = path.join(os.tmpdir(), 'trek-share-photo.e2e.jpg');
|
| 115 |
+
const photoBytes = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]); // JPEG-ish header
|
| 116 |
+
|
| 117 |
+
beforeAll(() => fs.writeFileSync(photoFile, photoBytes));
|
| 118 |
+
afterAll(() => { try { fs.unlinkSync(photoFile); } catch { /* ignore */ } });
|
| 119 |
+
|
| 120 |
+
it('streams cached bytes with no cookie (unguarded) for a valid token + place', async () => {
|
| 121 |
+
shareSvc.getSharedPlacePhotoPath.mockReturnValueOnce(photoFile);
|
| 122 |
+
const res = await request(server).get('/api/shared/tok/place-photo/ChIJabc/bytes');
|
| 123 |
+
expect(res.status).toBe(200);
|
| 124 |
+
expect(res.headers['content-type']).toContain('image/jpeg');
|
| 125 |
+
expect(res.headers['cache-control']).toContain('immutable');
|
| 126 |
+
expect(Buffer.from(res.body)).toEqual(photoBytes);
|
| 127 |
+
expect(shareSvc.getSharedPlacePhotoPath).toHaveBeenCalledWith('tok', 'ChIJabc');
|
| 128 |
+
});
|
| 129 |
+
|
| 130 |
+
it('404 when the token/place does not resolve to a cached photo', async () => {
|
| 131 |
+
shareSvc.getSharedPlacePhotoPath.mockReturnValueOnce(null);
|
| 132 |
+
const res = await request(server).get('/api/shared/bad/place-photo/ChIJabc/bytes');
|
| 133 |
+
expect(res.status).toBe(404);
|
| 134 |
+
expect(res.body).toEqual({ error: 'Photo not cached' });
|
| 135 |
+
});
|
| 136 |
+
});
|
| 137 |
+
});
|
server/tests/e2e/system-notices.e2e.test.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* System-notices module e2e — exercises the migrated /api/system-notices
|
| 3 |
+
* endpoints through the real JwtAuthGuard against a temp SQLite db. The notices
|
| 4 |
+
* service is mocked so the test doesn't depend on the static registry or the
|
| 5 |
+
* dismissal tables; it focuses on routing, auth, status codes and bodies.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
return { db: tmp };
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 25 |
+
|
| 26 |
+
const { mockGetActive, mockDismiss } = vi.hoisted(() => ({ mockGetActive: vi.fn(), mockDismiss: vi.fn() }));
|
| 27 |
+
vi.mock('../../src/systemNotices/service', () => ({
|
| 28 |
+
getActiveNoticesFor: mockGetActive,
|
| 29 |
+
dismissNotice: mockDismiss,
|
| 30 |
+
}));
|
| 31 |
+
|
| 32 |
+
import { SystemNoticesModule } from '../../src/nest/system-notices/system-notices.module';
|
| 33 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 34 |
+
|
| 35 |
+
const notice = {
|
| 36 |
+
id: 'welcome', display: 'modal', severity: 'info',
|
| 37 |
+
titleKey: 'notice.welcome.title', bodyKey: 'notice.welcome.body', dismissible: true,
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
describe('System-notices e2e (real auth guard + temp SQLite)', () => {
|
| 41 |
+
let server: Server;
|
| 42 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 43 |
+
|
| 44 |
+
async function build() {
|
| 45 |
+
const moduleRef = await Test.createTestingModule({ imports: [SystemNoticesModule] }).compile();
|
| 46 |
+
const nest = moduleRef.createNestApplication();
|
| 47 |
+
nest.use(cookieParser());
|
| 48 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 49 |
+
await nest.init();
|
| 50 |
+
return nest;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
beforeAll(async () => {
|
| 54 |
+
seedUser(db as never, { id: 1 });
|
| 55 |
+
app = await build();
|
| 56 |
+
server = app.getHttpServer();
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
afterAll(async () => {
|
| 60 |
+
await app.close();
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
it('401 without a session cookie', async () => {
|
| 64 |
+
const res = await request(server).get('/api/system-notices/active');
|
| 65 |
+
expect(res.status).toBe(401);
|
| 66 |
+
expect(res.body).toEqual({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
it('200 with the active notices for the user', async () => {
|
| 70 |
+
mockGetActive.mockReturnValue([notice]);
|
| 71 |
+
const res = await request(server).get('/api/system-notices/active').set('Cookie', sessionCookie(1));
|
| 72 |
+
expect(res.status).toBe(200);
|
| 73 |
+
expect(res.body).toEqual([notice]);
|
| 74 |
+
expect(mockGetActive).toHaveBeenCalledWith(1);
|
| 75 |
+
});
|
| 76 |
+
|
| 77 |
+
it('204 with no body on a successful dismiss', async () => {
|
| 78 |
+
mockDismiss.mockReturnValue(true);
|
| 79 |
+
const res = await request(server).post('/api/system-notices/welcome/dismiss').set('Cookie', sessionCookie(1));
|
| 80 |
+
expect(res.status).toBe(204);
|
| 81 |
+
expect(res.body).toEqual({});
|
| 82 |
+
expect(res.text).toBe('');
|
| 83 |
+
expect(mockDismiss).toHaveBeenCalledWith(1, 'welcome');
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
it('404 { error: NOTICE_NOT_FOUND } when the id is unknown', async () => {
|
| 87 |
+
mockDismiss.mockReturnValue(false);
|
| 88 |
+
const res = await request(server).post('/api/system-notices/nope/dismiss').set('Cookie', sessionCookie(1));
|
| 89 |
+
expect(res.status).toBe(404);
|
| 90 |
+
expect(res.body).toEqual({ error: 'NOTICE_NOT_FOUND' });
|
| 91 |
+
});
|
| 92 |
+
});
|
server/tests/e2e/tags.e2e.test.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Tags module e2e — exercises the migrated /api/tags endpoints through the real
|
| 3 |
+
* JwtAuthGuard against a temp SQLite db. tagService is mocked; tags are
|
| 4 |
+
* user-scoped (no admin gate), so a normal authenticated user can do everything.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 24 |
+
|
| 25 |
+
const { mocks } = vi.hoisted(() => ({
|
| 26 |
+
mocks: {
|
| 27 |
+
listTags: vi.fn(),
|
| 28 |
+
createTag: vi.fn(),
|
| 29 |
+
getTagByIdAndUser: vi.fn(),
|
| 30 |
+
updateTag: vi.fn(),
|
| 31 |
+
deleteTag: vi.fn(),
|
| 32 |
+
},
|
| 33 |
+
}));
|
| 34 |
+
vi.mock('../../src/services/tagService', () => mocks);
|
| 35 |
+
|
| 36 |
+
import { TagsModule } from '../../src/nest/tags/tags.module';
|
| 37 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 38 |
+
|
| 39 |
+
const tag = { id: 1, user_id: 1, name: 'Beach', color: '#10b981' };
|
| 40 |
+
|
| 41 |
+
describe('Tags e2e (real auth guard + temp SQLite)', () => {
|
| 42 |
+
let server: Server;
|
| 43 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 44 |
+
|
| 45 |
+
async function build() {
|
| 46 |
+
const moduleRef = await Test.createTestingModule({ imports: [TagsModule] }).compile();
|
| 47 |
+
const nest = moduleRef.createNestApplication();
|
| 48 |
+
nest.use(cookieParser());
|
| 49 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 50 |
+
await nest.init();
|
| 51 |
+
return nest;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
beforeAll(async () => {
|
| 55 |
+
seedUser(db as never, { id: 1 });
|
| 56 |
+
app = await build();
|
| 57 |
+
server = app.getHttpServer();
|
| 58 |
+
mocks.listTags.mockReturnValue([tag]);
|
| 59 |
+
mocks.createTag.mockReturnValue(tag);
|
| 60 |
+
mocks.getTagByIdAndUser.mockImplementation((id: string | number) => (String(id) === '1' ? tag : undefined));
|
| 61 |
+
mocks.updateTag.mockReturnValue({ ...tag, name: 'Hike' });
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
afterAll(async () => {
|
| 65 |
+
await app.close();
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
it('401 without a session cookie', async () => {
|
| 69 |
+
const res = await request(server).get('/api/tags');
|
| 70 |
+
expect(res.status).toBe(401);
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
it('200 list scoped to the user', async () => {
|
| 74 |
+
const res = await request(server).get('/api/tags').set('Cookie', sessionCookie(1));
|
| 75 |
+
expect(res.status).toBe(200);
|
| 76 |
+
expect(res.body).toEqual({ tags: [tag] });
|
| 77 |
+
expect(mocks.listTags).toHaveBeenCalledWith(1);
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it('201 on create', async () => {
|
| 81 |
+
const res = await request(server).post('/api/tags').set('Cookie', sessionCookie(1)).send({ name: 'Beach', color: '#10b981' });
|
| 82 |
+
expect(res.status).toBe(201);
|
| 83 |
+
expect(res.body).toEqual({ tag });
|
| 84 |
+
expect(mocks.createTag).toHaveBeenCalledWith(1, 'Beach', '#10b981');
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
it('400 on create without a name', async () => {
|
| 88 |
+
const res = await request(server).post('/api/tags').set('Cookie', sessionCookie(1)).send({});
|
| 89 |
+
expect(res.status).toBe(400);
|
| 90 |
+
expect(res.body).toEqual({ error: 'Tag name is required' });
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it('200 on update of an owned tag', async () => {
|
| 94 |
+
const res = await request(server).put('/api/tags/1').set('Cookie', sessionCookie(1)).send({ name: 'Hike' });
|
| 95 |
+
expect(res.status).toBe(200);
|
| 96 |
+
expect(res.body).toEqual({ tag: { ...tag, name: 'Hike' } });
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
it('404 on update of a tag the user does not own', async () => {
|
| 100 |
+
const res = await request(server).put('/api/tags/9').set('Cookie', sessionCookie(1)).send({ name: 'X' });
|
| 101 |
+
expect(res.status).toBe(404);
|
| 102 |
+
expect(res.body).toEqual({ error: 'Tag not found' });
|
| 103 |
+
});
|
| 104 |
+
|
| 105 |
+
it('200 on delete of an owned tag', async () => {
|
| 106 |
+
const res = await request(server).delete('/api/tags/1').set('Cookie', sessionCookie(1));
|
| 107 |
+
expect(res.status).toBe(200);
|
| 108 |
+
expect(res.body).toEqual({ success: true });
|
| 109 |
+
expect(mocks.deleteTag).toHaveBeenCalledWith('1');
|
| 110 |
+
});
|
| 111 |
+
});
|
server/tests/e2e/todo.e2e.test.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* To-do module e2e — exercises the migrated /api/trips/:tripId/todo endpoints
|
| 3 |
+
* through the real JwtAuthGuard against a temp SQLite db. todoService, the
|
| 4 |
+
* permission check and the WebSocket broadcast are mocked.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 24 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 25 |
+
|
| 26 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 27 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 28 |
+
|
| 29 |
+
const { svc } = vi.hoisted(() => ({
|
| 30 |
+
svc: {
|
| 31 |
+
verifyTripAccess: vi.fn(), listItems: vi.fn(), createItem: vi.fn(), updateItem: vi.fn(),
|
| 32 |
+
deleteItem: vi.fn(), reorderItems: vi.fn(), getCategoryAssignees: vi.fn(), updateCategoryAssignees: vi.fn(),
|
| 33 |
+
},
|
| 34 |
+
}));
|
| 35 |
+
vi.mock('../../src/services/todoService', () => svc);
|
| 36 |
+
|
| 37 |
+
import { TodoModule } from '../../src/nest/todo/todo.module';
|
| 38 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 39 |
+
|
| 40 |
+
describe('To-do e2e (real auth guard + temp SQLite)', () => {
|
| 41 |
+
let server: Server;
|
| 42 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 43 |
+
|
| 44 |
+
async function build() {
|
| 45 |
+
const moduleRef = await Test.createTestingModule({ imports: [TodoModule] }).compile();
|
| 46 |
+
const nest = moduleRef.createNestApplication();
|
| 47 |
+
nest.use(cookieParser());
|
| 48 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 49 |
+
await nest.init();
|
| 50 |
+
return nest;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
beforeAll(async () => {
|
| 54 |
+
seedUser(db as never, { id: 1 });
|
| 55 |
+
app = await build();
|
| 56 |
+
server = app.getHttpServer();
|
| 57 |
+
svc.listItems.mockReturnValue([{ id: 1, name: 'Book hotel' }]);
|
| 58 |
+
svc.createItem.mockReturnValue({ id: 9, name: 'Book hotel' });
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
beforeEach(() => {
|
| 62 |
+
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
|
| 63 |
+
checkPermission.mockReturnValue(true);
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
afterAll(async () => {
|
| 67 |
+
await app.close();
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
it('401 without a session cookie', async () => {
|
| 71 |
+
const res = await request(server).get('/api/trips/5/todo');
|
| 72 |
+
expect(res.status).toBe(401);
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
it('200 list for an accessible trip', async () => {
|
| 76 |
+
const res = await request(server).get('/api/trips/5/todo').set('Cookie', sessionCookie(1));
|
| 77 |
+
expect(res.status).toBe(200);
|
| 78 |
+
expect(res.body).toEqual({ items: [{ id: 1, name: 'Book hotel' }] });
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('404 when the trip is not accessible', async () => {
|
| 82 |
+
svc.verifyTripAccess.mockReturnValue(undefined);
|
| 83 |
+
const res = await request(server).get('/api/trips/5/todo').set('Cookie', sessionCookie(1));
|
| 84 |
+
expect(res.status).toBe(404);
|
| 85 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
it('201 on create with permission', async () => {
|
| 89 |
+
const res = await request(server).post('/api/trips/5/todo').set('Cookie', sessionCookie(1)).send({ name: 'Book hotel' });
|
| 90 |
+
expect(res.status).toBe(201);
|
| 91 |
+
expect(res.body).toEqual({ item: { id: 9, name: 'Book hotel' } });
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it('403 on create without permission', async () => {
|
| 95 |
+
checkPermission.mockReturnValue(false);
|
| 96 |
+
const res = await request(server).post('/api/trips/5/todo').set('Cookie', sessionCookie(1)).send({ name: 'Book hotel' });
|
| 97 |
+
expect(res.status).toBe(403);
|
| 98 |
+
expect(res.body).toEqual({ error: 'No permission' });
|
| 99 |
+
});
|
| 100 |
+
});
|
server/tests/e2e/trips.e2e.test.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Trips module e2e — exercises the migrated /api/trips aggregate-root endpoints
|
| 3 |
+
* through the real JwtAuthGuard against a temp SQLite db. tripService, the bundle
|
| 4 |
+
* list-services, auditLog, demo, the permission check, canAccessTrip and the
|
| 5 |
+
* WebSocket broadcast are mocked.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
|
| 22 |
+
return { db: tmp };
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
const { canAccessTrip } = vi.hoisted(() => ({ canAccessTrip: vi.fn() }));
|
| 26 |
+
vi.mock('../../src/db/database', () => ({
|
| 27 |
+
db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags: vi.fn(), closeDb: () => {}, reinitialize: () => {},
|
| 28 |
+
}));
|
| 29 |
+
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
|
| 30 |
+
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
|
| 31 |
+
vi.mock('../../src/services/auditLog', () => ({ writeAudit: vi.fn(), getClientIp: vi.fn(() => '1.2.3.4'), logInfo: vi.fn() }));
|
| 32 |
+
vi.mock('../../src/services/demo', () => ({ isDemoEmail: vi.fn(() => false) }));
|
| 33 |
+
|
| 34 |
+
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
|
| 35 |
+
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
|
| 36 |
+
|
| 37 |
+
const { tripSvc } = vi.hoisted(() => ({
|
| 38 |
+
tripSvc: {
|
| 39 |
+
listTrips: vi.fn(), createTrip: vi.fn(), getTrip: vi.fn(), updateTrip: vi.fn(), deleteTrip: vi.fn(),
|
| 40 |
+
getTripRaw: vi.fn(), getTripOwner: vi.fn(), deleteOldCover: vi.fn(), updateCoverImage: vi.fn(),
|
| 41 |
+
listMembers: vi.fn(), addMember: vi.fn(), removeMember: vi.fn(), exportICS: vi.fn(), copyTripById: vi.fn(),
|
| 42 |
+
verifyTripAccess: vi.fn(), NotFoundError: class NotFoundError extends Error {}, ValidationError: class ValidationError extends Error {}, TRIP_SELECT: 'SELECT',
|
| 43 |
+
},
|
| 44 |
+
}));
|
| 45 |
+
vi.mock('../../src/services/tripService', () => tripSvc);
|
| 46 |
+
vi.mock('../../src/services/dayService', () => ({ listDays: () => ({ days: [] }), listAccommodations: () => [] }));
|
| 47 |
+
vi.mock('../../src/services/placeService', () => ({ listPlaces: () => [] }));
|
| 48 |
+
vi.mock('../../src/services/packingService', () => ({ listItems: () => [] }));
|
| 49 |
+
vi.mock('../../src/services/todoService', () => ({ listItems: () => [] }));
|
| 50 |
+
vi.mock('../../src/services/budgetService', () => ({ listBudgetItems: () => [] }));
|
| 51 |
+
vi.mock('../../src/services/reservationService', () => ({ listReservations: () => [] }));
|
| 52 |
+
vi.mock('../../src/services/fileService', () => ({ listFiles: () => [] }));
|
| 53 |
+
|
| 54 |
+
import { TripsModule } from '../../src/nest/trips/trips.module';
|
| 55 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 56 |
+
|
| 57 |
+
describe('Trips e2e (real auth guard + temp SQLite)', () => {
|
| 58 |
+
let server: Server;
|
| 59 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 60 |
+
|
| 61 |
+
async function build() {
|
| 62 |
+
const moduleRef = await Test.createTestingModule({ imports: [TripsModule] }).compile();
|
| 63 |
+
const nest = moduleRef.createNestApplication();
|
| 64 |
+
nest.use(cookieParser());
|
| 65 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 66 |
+
await nest.init();
|
| 67 |
+
return nest;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
beforeAll(async () => {
|
| 71 |
+
seedUser(db as never, { id: 1 });
|
| 72 |
+
app = await build();
|
| 73 |
+
server = app.getHttpServer();
|
| 74 |
+
tripSvc.listTrips.mockReturnValue([{ id: 1, title: 'T' }]);
|
| 75 |
+
tripSvc.createTrip.mockReturnValue({ trip: { id: 9 }, tripId: 9, reminderDays: 0 });
|
| 76 |
+
tripSvc.getTrip.mockImplementation((id: string) => (id === '9' ? { id: 9, user_id: 1 } : undefined));
|
| 77 |
+
tripSvc.listMembers.mockReturnValue({ owner: { id: 1 }, members: [] });
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
beforeEach(() => {
|
| 81 |
+
canAccessTrip.mockReturnValue({ user_id: 1 });
|
| 82 |
+
checkPermission.mockReturnValue(true);
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
afterAll(async () => {
|
| 86 |
+
await app.close();
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it('401 without a cookie', async () => {
|
| 90 |
+
expect((await request(server).get('/api/trips')).status).toBe(401);
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it('200 list', async () => {
|
| 94 |
+
const res = await request(server).get('/api/trips').set('Cookie', sessionCookie(1));
|
| 95 |
+
expect(res.status).toBe(200);
|
| 96 |
+
expect(res.body).toEqual({ trips: [{ id: 1, title: 'T' }] });
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
it('201 create, 403 without permission', async () => {
|
| 100 |
+
const ok = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'T' });
|
| 101 |
+
expect(ok.status).toBe(201);
|
| 102 |
+
expect(ok.body).toEqual({ trip: { id: 9 } });
|
| 103 |
+
checkPermission.mockReturnValue(false);
|
| 104 |
+
const forbidden = await request(server).post('/api/trips').set('Cookie', sessionCookie(1)).send({ title: 'T' });
|
| 105 |
+
expect(forbidden.status).toBe(403);
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
it('404 on a missing trip', async () => {
|
| 109 |
+
const res = await request(server).get('/api/trips/77').set('Cookie', sessionCookie(1));
|
| 110 |
+
expect(res.status).toBe(404);
|
| 111 |
+
expect(res.body).toEqual({ error: 'Trip not found' });
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
it('200 bundle for an accessible trip', async () => {
|
| 115 |
+
const res = await request(server).get('/api/trips/9/bundle').set('Cookie', sessionCookie(1));
|
| 116 |
+
expect(res.status).toBe(200);
|
| 117 |
+
expect(res.body).toMatchObject({ trip: { id: 9 }, days: [], members: [{ id: 1 }] });
|
| 118 |
+
});
|
| 119 |
+
});
|
server/tests/e2e/vacay.e2e.test.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Vacay module e2e — exercises the migrated /api/addons/vacay endpoints through
|
| 3 |
+
* the real JwtAuthGuard against a temp SQLite db. vacayService is mocked; this
|
| 4 |
+
* focuses on auth, status codes (POSTs stay 200) and a couple of validation/403
|
| 5 |
+
* bodies.
|
| 6 |
+
*/
|
| 7 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 8 |
+
import request from 'supertest';
|
| 9 |
+
import cookieParser from 'cookie-parser';
|
| 10 |
+
import type { Server } from 'http';
|
| 11 |
+
import { Test } from '@nestjs/testing';
|
| 12 |
+
import { seedUser, sessionCookie } from './harness';
|
| 13 |
+
|
| 14 |
+
const { db } = vi.hoisted(() => {
|
| 15 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 16 |
+
const Database = require('better-sqlite3');
|
| 17 |
+
const tmp = new Database(':memory:');
|
| 18 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 19 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 20 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 21 |
+
return { db: tmp };
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 25 |
+
|
| 26 |
+
const { svc } = vi.hoisted(() => ({
|
| 27 |
+
svc: {
|
| 28 |
+
getPlanData: vi.fn(), getActivePlanId: vi.fn(), getActivePlan: vi.fn(), updatePlan: vi.fn(),
|
| 29 |
+
addHolidayCalendar: vi.fn(), updateHolidayCalendar: vi.fn(), deleteHolidayCalendar: vi.fn(),
|
| 30 |
+
getPlanUsers: vi.fn(), setUserColor: vi.fn(), sendInvite: vi.fn(), acceptInvite: vi.fn(),
|
| 31 |
+
declineInvite: vi.fn(), cancelInvite: vi.fn(), dissolvePlan: vi.fn(), getAvailableUsers: vi.fn(),
|
| 32 |
+
listYears: vi.fn(), addYear: vi.fn(), deleteYear: vi.fn(), getEntries: vi.fn(),
|
| 33 |
+
toggleEntry: vi.fn(), toggleCompanyHoliday: vi.fn(), getStats: vi.fn(), updateStats: vi.fn(),
|
| 34 |
+
getCountries: vi.fn(), getHolidays: vi.fn(),
|
| 35 |
+
},
|
| 36 |
+
}));
|
| 37 |
+
vi.mock('../../src/services/vacayService', () => svc);
|
| 38 |
+
|
| 39 |
+
import { VacayModule } from '../../src/nest/vacay/vacay.module';
|
| 40 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 41 |
+
|
| 42 |
+
describe('Vacay e2e (real auth guard + temp SQLite)', () => {
|
| 43 |
+
let server: Server;
|
| 44 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 45 |
+
|
| 46 |
+
async function build() {
|
| 47 |
+
const moduleRef = await Test.createTestingModule({ imports: [VacayModule] }).compile();
|
| 48 |
+
const nest = moduleRef.createNestApplication();
|
| 49 |
+
nest.use(cookieParser());
|
| 50 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 51 |
+
await nest.init();
|
| 52 |
+
return nest;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
beforeAll(async () => {
|
| 56 |
+
seedUser(db as never, { id: 1 });
|
| 57 |
+
app = await build();
|
| 58 |
+
server = app.getHttpServer();
|
| 59 |
+
svc.getActivePlanId.mockReturnValue(10);
|
| 60 |
+
svc.getActivePlan.mockReturnValue({ id: 10 });
|
| 61 |
+
svc.getPlanUsers.mockReturnValue([{ id: 1 }]);
|
| 62 |
+
svc.getPlanData.mockReturnValue({ plan: { id: 10 } });
|
| 63 |
+
svc.toggleEntry.mockReturnValue({ action: 'added' });
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
afterAll(async () => {
|
| 67 |
+
await app.close();
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
it('401 without a session cookie', async () => {
|
| 71 |
+
const res = await request(server).get('/api/addons/vacay/plan');
|
| 72 |
+
expect(res.status).toBe(401);
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
it('200 plan for an authenticated user', async () => {
|
| 76 |
+
const res = await request(server).get('/api/addons/vacay/plan').set('Cookie', sessionCookie(1));
|
| 77 |
+
expect(res.status).toBe(200);
|
| 78 |
+
expect(res.body).toEqual({ plan: { id: 10 } });
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('200 (not 201) on POST entries/toggle, forwarding the socket id', async () => {
|
| 82 |
+
const res = await request(server).post('/api/addons/vacay/entries/toggle')
|
| 83 |
+
.set('Cookie', sessionCookie(1)).set('X-Socket-Id', 'sock-7').send({ date: '2026-07-01' });
|
| 84 |
+
expect(res.status).toBe(200);
|
| 85 |
+
expect(res.body).toEqual({ action: 'added' });
|
| 86 |
+
expect(svc.toggleEntry).toHaveBeenCalledWith(1, 10, '2026-07-01', 'sock-7');
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it('400 on entries/toggle without a date', async () => {
|
| 90 |
+
const res = await request(server).post('/api/addons/vacay/entries/toggle').set('Cookie', sessionCookie(1)).send({});
|
| 91 |
+
expect(res.status).toBe(400);
|
| 92 |
+
expect(res.body).toEqual({ error: 'date required' });
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('403 on color for a user not in the plan', async () => {
|
| 96 |
+
const res = await request(server).put('/api/addons/vacay/color').set('Cookie', sessionCookie(1)).send({ color: '#fff', target_user_id: 99 });
|
| 97 |
+
expect(res.status).toBe(403);
|
| 98 |
+
expect(res.body).toEqual({ error: 'User not in plan' });
|
| 99 |
+
});
|
| 100 |
+
});
|
server/tests/e2e/weather.e2e.test.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Weather module e2e — exercises the migrated /api/weather endpoints through the
|
| 3 |
+
* real JwtAuthGuard against a temp SQLite db (seeded via the shared harness).
|
| 4 |
+
* The weather service is mocked so no real Open-Meteo calls happen.
|
| 5 |
+
*/
|
| 6 |
+
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
| 7 |
+
import request from 'supertest';
|
| 8 |
+
import cookieParser from 'cookie-parser';
|
| 9 |
+
import type { Server } from 'http';
|
| 10 |
+
import { Test } from '@nestjs/testing';
|
| 11 |
+
import { createTempDb, seedUser, sessionCookie } from './harness';
|
| 12 |
+
|
| 13 |
+
const { db } = vi.hoisted(() => {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
| 15 |
+
const Database = require('better-sqlite3');
|
| 16 |
+
const tmp = new Database(':memory:');
|
| 17 |
+
tmp.exec('PRAGMA journal_mode = WAL');
|
| 18 |
+
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
| 19 |
+
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
|
| 20 |
+
return { db: tmp };
|
| 21 |
+
});
|
| 22 |
+
|
| 23 |
+
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
|
| 24 |
+
|
| 25 |
+
const { mockGet, mockGetDetailed } = vi.hoisted(() => ({ mockGet: vi.fn(), mockGetDetailed: vi.fn() }));
|
| 26 |
+
vi.mock('../../src/services/weatherService', async (importActual) => {
|
| 27 |
+
const actual = await importActual<typeof import('../../src/services/weatherService')>();
|
| 28 |
+
return { ...actual, getWeather: mockGet, getDetailedWeather: mockGetDetailed };
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
import { WeatherModule } from '../../src/nest/weather/weather.module';
|
| 32 |
+
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
| 33 |
+
|
| 34 |
+
describe('Weather e2e (real auth guard + temp SQLite)', () => {
|
| 35 |
+
let server: Server;
|
| 36 |
+
let app: Awaited<ReturnType<typeof build>>;
|
| 37 |
+
|
| 38 |
+
async function build() {
|
| 39 |
+
const moduleRef = await Test.createTestingModule({ imports: [WeatherModule] }).compile();
|
| 40 |
+
const nest = moduleRef.createNestApplication();
|
| 41 |
+
nest.use(cookieParser());
|
| 42 |
+
nest.useGlobalFilters(new TrekExceptionFilter());
|
| 43 |
+
await nest.init();
|
| 44 |
+
return nest;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
beforeAll(async () => {
|
| 48 |
+
seedUser(db as never, { id: 1 });
|
| 49 |
+
app = await build();
|
| 50 |
+
server = app.getHttpServer();
|
| 51 |
+
mockGet.mockResolvedValue({ temp: 21, main: 'Clear', description: 'Klar', type: 'current' });
|
| 52 |
+
mockGetDetailed.mockResolvedValue({ temp: 20, main: 'Rain', description: 'Regen', type: 'forecast', hourly: [] });
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
afterAll(async () => {
|
| 56 |
+
await app.close();
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
it('401 { error, code } without a session cookie', async () => {
|
| 60 |
+
const res = await request(server).get('/api/weather').query({ lat: '1', lng: '2' });
|
| 61 |
+
expect(res.status).toBe(401);
|
| 62 |
+
expect(res.body).toEqual({ error: 'Access token required', code: 'AUTH_REQUIRED' });
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
it('401 with an invalid token', async () => {
|
| 66 |
+
const res = await request(server).get('/api/weather').set('Cookie', 'trek_session=not-a-jwt').query({ lat: '1', lng: '2' });
|
| 67 |
+
expect(res.status).toBe(401);
|
| 68 |
+
expect(res.body).toEqual({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' });
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
it('400 when authenticated but lat/lng missing', async () => {
|
| 72 |
+
const res = await request(server).get('/api/weather').set('Cookie', sessionCookie(1)).query({ lng: '2' });
|
| 73 |
+
expect(res.status).toBe(400);
|
| 74 |
+
expect(res.body).toEqual({ error: 'Latitude and longitude are required' });
|
| 75 |
+
});
|
| 76 |
+
|
| 77 |
+
it('200 with a valid session cookie', async () => {
|
| 78 |
+
const res = await request(server).get('/api/weather').set('Cookie', sessionCookie(1)).query({ lat: '52.5', lng: '13.4' });
|
| 79 |
+
expect(res.status).toBe(200);
|
| 80 |
+
expect(res.body).toMatchObject({ temp: 21, main: 'Clear', type: 'current' });
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
it('200 on /detailed with a valid session cookie', async () => {
|
| 84 |
+
const res = await request(server).get('/api/weather/detailed').set('Cookie', sessionCookie(1)).query({ lat: '1', lng: '2', date: '2026-07-01' });
|
| 85 |
+
expect(res.status).toBe(200);
|
| 86 |
+
expect(res.body).toMatchObject({ type: 'forecast' });
|
| 87 |
+
});
|
| 88 |
+
});
|
server/tests/fixtures/large-test.gpx
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
server/tests/fixtures/large-test.kml
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
server/tests/fixtures/large-test.kmz
ADDED
|
Binary file (26.4 kB). View file
|
|
|
server/tests/fixtures/small-image.jpg
ADDED
|
server/tests/fixtures/test-malformed.kml
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<kml>
|
| 3 |
+
<Document>
|
| 4 |
+
<Placemark>
|
| 5 |
+
<name>Broken Placemark</name>
|
| 6 |
+
<Point><coordinates>2.1,48.1,0</coordinates></Point>
|
| 7 |
+
</Document>
|
| 8 |
+
</kml>
|
server/tests/fixtures/test-nested.kml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<kml xmlns="http://www.opengis.net/kml/2.2">
|
| 3 |
+
<Document>
|
| 4 |
+
<Folder>
|
| 5 |
+
<name>Food</name>
|
| 6 |
+
<Folder>
|
| 7 |
+
<name>Parks</name>
|
| 8 |
+
<Placemark>
|
| 9 |
+
<name>Nested Place</name>
|
| 10 |
+
<description>Nested <i>folder</i> placemark<br/>line 2</description>
|
| 11 |
+
<Point>
|
| 12 |
+
<coordinates>13.4050,52.5200,15</coordinates>
|
| 13 |
+
</Point>
|
| 14 |
+
</Placemark>
|
| 15 |
+
</Folder>
|
| 16 |
+
<Placemark>
|
| 17 |
+
<name>Empty Placemark</name>
|
| 18 |
+
</Placemark>
|
| 19 |
+
<Placemark>
|
| 20 |
+
<Point>
|
| 21 |
+
<coordinates>13.4010,52.5210,0</coordinates>
|
| 22 |
+
</Point>
|
| 23 |
+
</Placemark>
|
| 24 |
+
</Folder>
|
| 25 |
+
</Document>
|
| 26 |
+
</kml>
|
server/tests/fixtures/test.gpx
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<gpx version="1.1" creator="TREK Tests" xmlns="http://www.topografix.com/GPX/1/1">
|
| 3 |
+
<wpt lat="48.8566" lon="2.3522">
|
| 4 |
+
<name>Eiffel Tower</name>
|
| 5 |
+
<desc>Paris landmark</desc>
|
| 6 |
+
</wpt>
|
| 7 |
+
<wpt lat="48.8606" lon="2.3376">
|
| 8 |
+
<name>Louvre Museum</name>
|
| 9 |
+
<desc>Art museum</desc>
|
| 10 |
+
</wpt>
|
| 11 |
+
</gpx>
|
server/tests/fixtures/test.kml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 2 |
+
<kml xmlns="http://www.opengis.net/kml/2.2">
|
| 3 |
+
<Document>
|
| 4 |
+
<Folder>
|
| 5 |
+
<name>Museums</name>
|
| 6 |
+
<Placemark>
|
| 7 |
+
<name>Eiffel Tower View</name>
|
| 8 |
+
<description><![CDATA[Great spot<br>for photos <b>and</b> skyline.]]></description>
|
| 9 |
+
<Point>
|
| 10 |
+
<coordinates>2.2945,48.8584,0</coordinates>
|
| 11 |
+
</Point>
|
| 12 |
+
</Placemark>
|
| 13 |
+
<Placemark>
|
| 14 |
+
<description>Coordinates only placemark</description>
|
| 15 |
+
<Point>
|
| 16 |
+
<coordinates>2.3333,48.8600,0</coordinates>
|
| 17 |
+
</Point>
|
| 18 |
+
</Placemark>
|
| 19 |
+
</Folder>
|
| 20 |
+
</Document>
|
| 21 |
+
</kml>
|
server/tests/fixtures/test.kmz
ADDED
|
Binary file (408 Bytes). View file
|
|
|
server/tests/fixtures/test.pdf
ADDED
|
Binary file (329 Bytes). View file
|
|
|
server/tests/helpers/auth.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Auth helpers for integration tests.
|
| 3 |
+
*
|
| 4 |
+
* Provides utilities to generate JWTs and authenticate supertest requests
|
| 5 |
+
* using the fixed test JWT_SECRET from TEST_CONFIG.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
import jwt from 'jsonwebtoken';
|
| 9 |
+
import { TEST_CONFIG } from './test-db';
|
| 10 |
+
|
| 11 |
+
/** Signs a JWT for the given user ID using the test secret. */
|
| 12 |
+
export function generateToken(userId: number, extraClaims: Record<string, unknown> = {}): string {
|
| 13 |
+
return jwt.sign(
|
| 14 |
+
{ id: userId, ...extraClaims },
|
| 15 |
+
TEST_CONFIG.JWT_SECRET,
|
| 16 |
+
{ algorithm: 'HS256', expiresIn: '1h' }
|
| 17 |
+
);
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
/**
|
| 21 |
+
* Returns a cookie string suitable for supertest:
|
| 22 |
+
* request(app).get('/api/...').set('Cookie', authCookie(userId))
|
| 23 |
+
*/
|
| 24 |
+
export function authCookie(userId: number): string {
|
| 25 |
+
return `trek_session=${generateToken(userId)}`;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/**
|
| 29 |
+
* Returns an Authorization header object suitable for supertest:
|
| 30 |
+
* request(app).get('/api/...').set(authHeader(userId))
|
| 31 |
+
*/
|
| 32 |
+
export function authHeader(userId: number): Record<string, string> {
|
| 33 |
+
return { Authorization: `Bearer ${generateToken(userId)}` };
|
| 34 |
+
}
|
server/tests/helpers/factories.ts
ADDED
|
@@ -0,0 +1,743 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Test data factories.
|
| 3 |
+
* Each factory inserts a row into the provided in-memory DB and returns the created object.
|
| 4 |
+
* Passwords are stored as bcrypt hashes (cost factor 4 for speed in tests).
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import Database from 'better-sqlite3';
|
| 8 |
+
import bcrypt from 'bcryptjs';
|
| 9 |
+
import { encryptMfaSecret } from '../../src/services/mfaCrypto';
|
| 10 |
+
import { encrypt_api_key } from '../../src/services/apiKeyCrypto';
|
| 11 |
+
|
| 12 |
+
let _userSeq = 0;
|
| 13 |
+
let _tripSeq = 0;
|
| 14 |
+
let _categorySeq = 0;
|
| 15 |
+
let _tagSeq = 0;
|
| 16 |
+
|
| 17 |
+
// ---------------------------------------------------------------------------
|
| 18 |
+
// Users
|
| 19 |
+
// ---------------------------------------------------------------------------
|
| 20 |
+
|
| 21 |
+
export interface TestUser {
|
| 22 |
+
id: number;
|
| 23 |
+
username: string;
|
| 24 |
+
email: string;
|
| 25 |
+
role: 'admin' | 'user';
|
| 26 |
+
password_hash: string;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
export function createUser(
|
| 30 |
+
db: Database.Database,
|
| 31 |
+
overrides: Partial<{ username: string; email: string; password: string; role: 'admin' | 'user' }> = {}
|
| 32 |
+
): { user: TestUser; password: string } {
|
| 33 |
+
_userSeq++;
|
| 34 |
+
const password = overrides.password ?? `TestPass${_userSeq}!`;
|
| 35 |
+
const email = overrides.email ?? `user${_userSeq}@test.example.com`;
|
| 36 |
+
const username = overrides.username ?? `testuser${_userSeq}`;
|
| 37 |
+
const role = overrides.role ?? 'user';
|
| 38 |
+
const hash = bcrypt.hashSync(password, 4); // cost 4 for test speed
|
| 39 |
+
|
| 40 |
+
const result = db.prepare(
|
| 41 |
+
'INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)'
|
| 42 |
+
).run(username, email, hash, role);
|
| 43 |
+
|
| 44 |
+
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(result.lastInsertRowid) as TestUser;
|
| 45 |
+
return { user, password };
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
export function createAdmin(
|
| 49 |
+
db: Database.Database,
|
| 50 |
+
overrides: Partial<{ username: string; email: string; password: string }> = {}
|
| 51 |
+
): { user: TestUser; password: string } {
|
| 52 |
+
return createUser(db, { ...overrides, role: 'admin' });
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/**
|
| 56 |
+
* Creates a user with MFA already enabled (directly in DB, bypasses rate-limited HTTP endpoints).
|
| 57 |
+
* Returns the user, password, and the TOTP secret so tests can generate valid codes.
|
| 58 |
+
*/
|
| 59 |
+
const KNOWN_MFA_SECRET = 'JBSWY3DPEHPK3PXP'; // fixed base32 secret for deterministic tests
|
| 60 |
+
export function createUserWithMfa(
|
| 61 |
+
db: Database.Database,
|
| 62 |
+
overrides: Partial<{ username: string; email: string; password: string; role: 'admin' | 'user' }> = {}
|
| 63 |
+
): { user: TestUser; password: string; totpSecret: string } {
|
| 64 |
+
const { user, password } = createUser(db, overrides);
|
| 65 |
+
const encryptedSecret = encryptMfaSecret(KNOWN_MFA_SECRET);
|
| 66 |
+
db.prepare(
|
| 67 |
+
'UPDATE users SET mfa_enabled = 1, mfa_secret = ? WHERE id = ?'
|
| 68 |
+
).run(encryptedSecret, user.id);
|
| 69 |
+
const updated = db.prepare('SELECT * FROM users WHERE id = ?').get(user.id) as TestUser;
|
| 70 |
+
return { user: updated, password, totpSecret: KNOWN_MFA_SECRET };
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// ---------------------------------------------------------------------------
|
| 74 |
+
// Trips
|
| 75 |
+
// ---------------------------------------------------------------------------
|
| 76 |
+
|
| 77 |
+
export interface TestTrip {
|
| 78 |
+
id: number;
|
| 79 |
+
user_id: number;
|
| 80 |
+
title: string;
|
| 81 |
+
start_date: string | null;
|
| 82 |
+
end_date: string | null;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
export function createTrip(
|
| 86 |
+
db: Database.Database,
|
| 87 |
+
userId: number,
|
| 88 |
+
overrides: Partial<{ title: string; start_date: string; end_date: string; description: string }> = {}
|
| 89 |
+
): TestTrip {
|
| 90 |
+
_tripSeq++;
|
| 91 |
+
const title = overrides.title ?? `Test Trip ${_tripSeq}`;
|
| 92 |
+
const result = db.prepare(
|
| 93 |
+
'INSERT INTO trips (user_id, title, description, start_date, end_date) VALUES (?, ?, ?, ?, ?)'
|
| 94 |
+
).run(userId, title, overrides.description ?? null, overrides.start_date ?? null, overrides.end_date ?? null);
|
| 95 |
+
|
| 96 |
+
// Auto-generate days if dates are provided
|
| 97 |
+
if (overrides.start_date && overrides.end_date) {
|
| 98 |
+
const start = new Date(overrides.start_date);
|
| 99 |
+
const end = new Date(overrides.end_date);
|
| 100 |
+
const tripId = result.lastInsertRowid as number;
|
| 101 |
+
let dayNumber = 1;
|
| 102 |
+
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
|
| 103 |
+
const dateStr = d.toISOString().slice(0, 10);
|
| 104 |
+
db.prepare('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)').run(tripId, dayNumber++, dateStr);
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
return db.prepare('SELECT * FROM trips WHERE id = ?').get(result.lastInsertRowid) as TestTrip;
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
// ---------------------------------------------------------------------------
|
| 112 |
+
// Days
|
| 113 |
+
// ---------------------------------------------------------------------------
|
| 114 |
+
|
| 115 |
+
export interface TestDay {
|
| 116 |
+
id: number;
|
| 117 |
+
trip_id: number;
|
| 118 |
+
day_number: number;
|
| 119 |
+
date: string | null;
|
| 120 |
+
title: string | null;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
export function createDay(
|
| 124 |
+
db: Database.Database,
|
| 125 |
+
tripId: number,
|
| 126 |
+
overrides: Partial<{ date: string; title: string; day_number: number }> = {}
|
| 127 |
+
): TestDay {
|
| 128 |
+
// Find the next day_number for this trip if not provided
|
| 129 |
+
const maxDay = db.prepare('SELECT MAX(day_number) as max FROM days WHERE trip_id = ?').get(tripId) as { max: number | null };
|
| 130 |
+
const dayNumber = overrides.day_number ?? (maxDay.max ?? 0) + 1;
|
| 131 |
+
const result = db.prepare(
|
| 132 |
+
'INSERT INTO days (trip_id, day_number, date, title) VALUES (?, ?, ?, ?)'
|
| 133 |
+
).run(tripId, dayNumber, overrides.date ?? null, overrides.title ?? null);
|
| 134 |
+
return db.prepare('SELECT * FROM days WHERE id = ?').get(result.lastInsertRowid) as TestDay;
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
// ---------------------------------------------------------------------------
|
| 138 |
+
// Places
|
| 139 |
+
// ---------------------------------------------------------------------------
|
| 140 |
+
|
| 141 |
+
export interface TestPlace {
|
| 142 |
+
id: number;
|
| 143 |
+
trip_id: number;
|
| 144 |
+
name: string;
|
| 145 |
+
lat: number | null;
|
| 146 |
+
lng: number | null;
|
| 147 |
+
category_id: number | null;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
export function createPlace(
|
| 151 |
+
db: Database.Database,
|
| 152 |
+
tripId: number,
|
| 153 |
+
overrides: Partial<{ name: string; lat: number; lng: number; category_id: number; description: string }> = {}
|
| 154 |
+
): TestPlace {
|
| 155 |
+
// Get first available category if none provided
|
| 156 |
+
const defaultCat = db.prepare('SELECT id FROM categories LIMIT 1').get() as { id: number } | undefined;
|
| 157 |
+
const categoryId = overrides.category_id ?? defaultCat?.id ?? null;
|
| 158 |
+
|
| 159 |
+
const result = db.prepare(
|
| 160 |
+
'INSERT INTO places (trip_id, name, lat, lng, category_id, description) VALUES (?, ?, ?, ?, ?, ?)'
|
| 161 |
+
).run(
|
| 162 |
+
tripId,
|
| 163 |
+
overrides.name ?? 'Test Place',
|
| 164 |
+
overrides.lat ?? 48.8566,
|
| 165 |
+
overrides.lng ?? 2.3522,
|
| 166 |
+
categoryId,
|
| 167 |
+
overrides.description ?? null
|
| 168 |
+
);
|
| 169 |
+
return db.prepare('SELECT * FROM places WHERE id = ?').get(result.lastInsertRowid) as TestPlace;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
// ---------------------------------------------------------------------------
|
| 173 |
+
// Trip Members
|
| 174 |
+
// ---------------------------------------------------------------------------
|
| 175 |
+
|
| 176 |
+
export function addTripMember(db: Database.Database, tripId: number, userId: number): void {
|
| 177 |
+
db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, userId);
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
// ---------------------------------------------------------------------------
|
| 181 |
+
// Budget Items
|
| 182 |
+
// ---------------------------------------------------------------------------
|
| 183 |
+
|
| 184 |
+
export interface TestBudgetItem {
|
| 185 |
+
id: number;
|
| 186 |
+
trip_id: number;
|
| 187 |
+
name: string;
|
| 188 |
+
category: string;
|
| 189 |
+
total_price: number;
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
export function createBudgetItem(
|
| 193 |
+
db: Database.Database,
|
| 194 |
+
tripId: number,
|
| 195 |
+
overrides: Partial<{ name: string; category: string; total_price: number }> = {}
|
| 196 |
+
): TestBudgetItem {
|
| 197 |
+
const result = db.prepare(
|
| 198 |
+
'INSERT INTO budget_items (trip_id, name, category, total_price) VALUES (?, ?, ?, ?)'
|
| 199 |
+
).run(
|
| 200 |
+
tripId,
|
| 201 |
+
overrides.name ?? 'Test Budget Item',
|
| 202 |
+
overrides.category ?? 'Transport',
|
| 203 |
+
overrides.total_price ?? 100
|
| 204 |
+
);
|
| 205 |
+
return db.prepare('SELECT * FROM budget_items WHERE id = ?').get(result.lastInsertRowid) as TestBudgetItem;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
// ---------------------------------------------------------------------------
|
| 209 |
+
// Packing Items
|
| 210 |
+
// ---------------------------------------------------------------------------
|
| 211 |
+
|
| 212 |
+
export interface TestPackingItem {
|
| 213 |
+
id: number;
|
| 214 |
+
trip_id: number;
|
| 215 |
+
name: string;
|
| 216 |
+
category: string;
|
| 217 |
+
checked: number;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
export function createPackingItem(
|
| 221 |
+
db: Database.Database,
|
| 222 |
+
tripId: number,
|
| 223 |
+
overrides: Partial<{ name: string; category: string }> = {}
|
| 224 |
+
): TestPackingItem {
|
| 225 |
+
const result = db.prepare(
|
| 226 |
+
'INSERT INTO packing_items (trip_id, name, category, checked) VALUES (?, ?, ?, 0)'
|
| 227 |
+
).run(tripId, overrides.name ?? 'Test Item', overrides.category ?? 'Clothing');
|
| 228 |
+
return db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid) as TestPackingItem;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
// ---------------------------------------------------------------------------
|
| 232 |
+
// Reservations
|
| 233 |
+
// ---------------------------------------------------------------------------
|
| 234 |
+
|
| 235 |
+
export interface TestReservation {
|
| 236 |
+
id: number;
|
| 237 |
+
trip_id: number;
|
| 238 |
+
title: string;
|
| 239 |
+
type: string;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
export function createReservation(
|
| 243 |
+
db: Database.Database,
|
| 244 |
+
tripId: number,
|
| 245 |
+
overrides: Partial<{ title: string; type: string; day_id: number }> = {}
|
| 246 |
+
): TestReservation {
|
| 247 |
+
const result = db.prepare(
|
| 248 |
+
'INSERT INTO reservations (trip_id, title, type, day_id) VALUES (?, ?, ?, ?)'
|
| 249 |
+
).run(tripId, overrides.title ?? 'Test Reservation', overrides.type ?? 'flight', overrides.day_id ?? null);
|
| 250 |
+
return db.prepare('SELECT * FROM reservations WHERE id = ?').get(result.lastInsertRowid) as TestReservation;
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
// ---------------------------------------------------------------------------
|
| 254 |
+
// Invite Tokens
|
| 255 |
+
// ---------------------------------------------------------------------------
|
| 256 |
+
|
| 257 |
+
export interface TestInviteToken {
|
| 258 |
+
id: number;
|
| 259 |
+
token: string;
|
| 260 |
+
max_uses: number | null;
|
| 261 |
+
used_count: number;
|
| 262 |
+
expires_at: string | null;
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
// ---------------------------------------------------------------------------
|
| 266 |
+
// Day Notes
|
| 267 |
+
// ---------------------------------------------------------------------------
|
| 268 |
+
|
| 269 |
+
export interface TestDayNote {
|
| 270 |
+
id: number;
|
| 271 |
+
day_id: number;
|
| 272 |
+
trip_id: number;
|
| 273 |
+
text: string;
|
| 274 |
+
time: string | null;
|
| 275 |
+
icon: string;
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
export function createDayNote(
|
| 279 |
+
db: Database.Database,
|
| 280 |
+
dayId: number,
|
| 281 |
+
tripId: number,
|
| 282 |
+
overrides: Partial<{ text: string; time: string; icon: string }> = {}
|
| 283 |
+
): TestDayNote {
|
| 284 |
+
const result = db.prepare(
|
| 285 |
+
'INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order) VALUES (?, ?, ?, ?, ?, 9999)'
|
| 286 |
+
).run(dayId, tripId, overrides.text ?? 'Test note', overrides.time ?? null, overrides.icon ?? '📝');
|
| 287 |
+
return db.prepare('SELECT * FROM day_notes WHERE id = ?').get(result.lastInsertRowid) as TestDayNote;
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
// ---------------------------------------------------------------------------
|
| 291 |
+
// Collab Notes
|
| 292 |
+
// ---------------------------------------------------------------------------
|
| 293 |
+
|
| 294 |
+
export interface TestCollabNote {
|
| 295 |
+
id: number;
|
| 296 |
+
trip_id: number;
|
| 297 |
+
user_id: number;
|
| 298 |
+
title: string;
|
| 299 |
+
content: string | null;
|
| 300 |
+
category: string;
|
| 301 |
+
color: string;
|
| 302 |
+
pinned: number;
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
export function createCollabNote(
|
| 306 |
+
db: Database.Database,
|
| 307 |
+
tripId: number,
|
| 308 |
+
userId: number,
|
| 309 |
+
overrides: Partial<{ title: string; content: string; category: string; color: string }> = {}
|
| 310 |
+
): TestCollabNote {
|
| 311 |
+
const result = db.prepare(
|
| 312 |
+
'INSERT INTO collab_notes (trip_id, user_id, title, content, category, color) VALUES (?, ?, ?, ?, ?, ?)'
|
| 313 |
+
).run(
|
| 314 |
+
tripId,
|
| 315 |
+
userId,
|
| 316 |
+
overrides.title ?? 'Test Note',
|
| 317 |
+
overrides.content ?? null,
|
| 318 |
+
overrides.category ?? 'General',
|
| 319 |
+
overrides.color ?? '#6366f1'
|
| 320 |
+
);
|
| 321 |
+
return db.prepare('SELECT * FROM collab_notes WHERE id = ?').get(result.lastInsertRowid) as TestCollabNote;
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
// ---------------------------------------------------------------------------
|
| 325 |
+
// Todo Items
|
| 326 |
+
// ---------------------------------------------------------------------------
|
| 327 |
+
|
| 328 |
+
export interface TestTodoItem {
|
| 329 |
+
id: number;
|
| 330 |
+
trip_id: number;
|
| 331 |
+
name: string;
|
| 332 |
+
checked: number;
|
| 333 |
+
category: string | null;
|
| 334 |
+
sort_order: number;
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
export function createTodoItem(
|
| 338 |
+
db: Database.Database,
|
| 339 |
+
tripId: number,
|
| 340 |
+
overrides: Partial<{ name: string; category: string; checked: number }> = {}
|
| 341 |
+
): TestTodoItem {
|
| 342 |
+
const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM todo_items WHERE trip_id = ?').get(tripId) as { max: number | null };
|
| 343 |
+
const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
|
| 344 |
+
const result = db.prepare(
|
| 345 |
+
'INSERT INTO todo_items (trip_id, name, checked, category, sort_order) VALUES (?, ?, ?, ?, ?)'
|
| 346 |
+
).run(tripId, overrides.name ?? 'Test Todo', overrides.checked ?? 0, overrides.category ?? null, sortOrder);
|
| 347 |
+
return db.prepare('SELECT * FROM todo_items WHERE id = ?').get(result.lastInsertRowid) as TestTodoItem;
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
// ---------------------------------------------------------------------------
|
| 351 |
+
// Day Assignments
|
| 352 |
+
// ---------------------------------------------------------------------------
|
| 353 |
+
|
| 354 |
+
export interface TestDayAssignment {
|
| 355 |
+
id: number;
|
| 356 |
+
day_id: number;
|
| 357 |
+
place_id: number;
|
| 358 |
+
order_index: number;
|
| 359 |
+
notes: string | null;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
export function createDayAssignment(
|
| 363 |
+
db: Database.Database,
|
| 364 |
+
dayId: number,
|
| 365 |
+
placeId: number,
|
| 366 |
+
overrides: Partial<{ order_index: number; notes: string }> = {}
|
| 367 |
+
): TestDayAssignment {
|
| 368 |
+
const maxOrder = db.prepare('SELECT MAX(order_index) as max FROM day_assignments WHERE day_id = ?').get(dayId) as { max: number | null };
|
| 369 |
+
const orderIndex = overrides.order_index ?? (maxOrder.max !== null ? maxOrder.max + 1 : 0);
|
| 370 |
+
const result = db.prepare(
|
| 371 |
+
'INSERT INTO day_assignments (day_id, place_id, order_index, notes) VALUES (?, ?, ?, ?)'
|
| 372 |
+
).run(dayId, placeId, orderIndex, overrides.notes ?? null);
|
| 373 |
+
return db.prepare('SELECT * FROM day_assignments WHERE id = ?').get(result.lastInsertRowid) as TestDayAssignment;
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
// ---------------------------------------------------------------------------
|
| 377 |
+
// Bucket List
|
| 378 |
+
// ---------------------------------------------------------------------------
|
| 379 |
+
|
| 380 |
+
export interface TestBucketListItem {
|
| 381 |
+
id: number;
|
| 382 |
+
user_id: number;
|
| 383 |
+
name: string;
|
| 384 |
+
lat: number | null;
|
| 385 |
+
lng: number | null;
|
| 386 |
+
country_code: string | null;
|
| 387 |
+
notes: string | null;
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
export function createBucketListItem(
|
| 391 |
+
db: Database.Database,
|
| 392 |
+
userId: number,
|
| 393 |
+
overrides: Partial<{ name: string; lat: number; lng: number; country_code: string; notes: string }> = {}
|
| 394 |
+
): TestBucketListItem {
|
| 395 |
+
const result = db.prepare(
|
| 396 |
+
'INSERT INTO bucket_list (user_id, name, lat, lng, country_code, notes) VALUES (?, ?, ?, ?, ?, ?)'
|
| 397 |
+
).run(
|
| 398 |
+
userId,
|
| 399 |
+
overrides.name ?? 'Test Destination',
|
| 400 |
+
overrides.lat ?? null,
|
| 401 |
+
overrides.lng ?? null,
|
| 402 |
+
overrides.country_code ?? null,
|
| 403 |
+
overrides.notes ?? null
|
| 404 |
+
);
|
| 405 |
+
return db.prepare('SELECT * FROM bucket_list WHERE id = ?').get(result.lastInsertRowid) as TestBucketListItem;
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
// ---------------------------------------------------------------------------
|
| 409 |
+
// Visited Countries
|
| 410 |
+
// ---------------------------------------------------------------------------
|
| 411 |
+
|
| 412 |
+
export function createVisitedCountry(
|
| 413 |
+
db: Database.Database,
|
| 414 |
+
userId: number,
|
| 415 |
+
countryCode: string
|
| 416 |
+
): void {
|
| 417 |
+
db.prepare('INSERT OR IGNORE INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(userId, countryCode.toUpperCase());
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
// ---------------------------------------------------------------------------
|
| 421 |
+
// Day Accommodations
|
| 422 |
+
// ---------------------------------------------------------------------------
|
| 423 |
+
|
| 424 |
+
export interface TestDayAccommodation {
|
| 425 |
+
id: number;
|
| 426 |
+
trip_id: number;
|
| 427 |
+
place_id: number;
|
| 428 |
+
start_day_id: number;
|
| 429 |
+
end_day_id: number;
|
| 430 |
+
check_in: string | null;
|
| 431 |
+
check_out: string | null;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
export function createDayAccommodation(
|
| 435 |
+
db: Database.Database,
|
| 436 |
+
tripId: number,
|
| 437 |
+
placeId: number,
|
| 438 |
+
startDayId: number,
|
| 439 |
+
endDayId: number,
|
| 440 |
+
overrides: Partial<{ check_in: string; check_out: string; confirmation: string }> = {}
|
| 441 |
+
): TestDayAccommodation {
|
| 442 |
+
const result = db.prepare(
|
| 443 |
+
'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
| 444 |
+
).run(
|
| 445 |
+
tripId,
|
| 446 |
+
placeId,
|
| 447 |
+
startDayId,
|
| 448 |
+
endDayId,
|
| 449 |
+
overrides.check_in ?? null,
|
| 450 |
+
overrides.check_out ?? null,
|
| 451 |
+
overrides.confirmation ?? null
|
| 452 |
+
);
|
| 453 |
+
return db.prepare('SELECT * FROM day_accommodations WHERE id = ?').get(result.lastInsertRowid) as TestDayAccommodation;
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
// ---------------------------------------------------------------------------
|
| 457 |
+
// MCP Tokens
|
| 458 |
+
// ---------------------------------------------------------------------------
|
| 459 |
+
|
| 460 |
+
import { createHash } from 'crypto';
|
| 461 |
+
|
| 462 |
+
export interface TestMcpToken {
|
| 463 |
+
id: number;
|
| 464 |
+
tokenHash: string;
|
| 465 |
+
rawToken: string;
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
export function createMcpToken(
|
| 469 |
+
db: Database.Database,
|
| 470 |
+
userId: number,
|
| 471 |
+
overrides: Partial<{ name: string; rawToken: string }> = {}
|
| 472 |
+
): TestMcpToken {
|
| 473 |
+
const rawToken = overrides.rawToken ?? `trek_test_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
| 474 |
+
const tokenHash = createHash('sha256').update(rawToken).digest('hex');
|
| 475 |
+
const tokenPrefix = rawToken.slice(0, 12);
|
| 476 |
+
const result = db.prepare(
|
| 477 |
+
'INSERT INTO mcp_tokens (user_id, token_hash, token_prefix, name) VALUES (?, ?, ?, ?)'
|
| 478 |
+
).run(userId, tokenHash, tokenPrefix, overrides.name ?? 'Test Token');
|
| 479 |
+
return { id: result.lastInsertRowid as number, tokenHash, rawToken };
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
// ---------------------------------------------------------------------------
|
| 483 |
+
// Invite Tokens
|
| 484 |
+
// ---------------------------------------------------------------------------
|
| 485 |
+
|
| 486 |
+
export function createInviteToken(
|
| 487 |
+
db: Database.Database,
|
| 488 |
+
overrides: Partial<{ token: string; max_uses: number; expires_at: string; created_by: number }> = {}
|
| 489 |
+
): TestInviteToken {
|
| 490 |
+
const token = overrides.token ?? `test-invite-${Date.now()}`;
|
| 491 |
+
// created_by is required by the schema; use an existing admin or create one
|
| 492 |
+
let createdBy = overrides.created_by;
|
| 493 |
+
if (!createdBy) {
|
| 494 |
+
const admin = db.prepare("SELECT id FROM users WHERE role = 'admin' LIMIT 1").get() as { id: number } | undefined;
|
| 495 |
+
if (admin) {
|
| 496 |
+
createdBy = admin.id;
|
| 497 |
+
} else {
|
| 498 |
+
const any = db.prepare('SELECT id FROM users LIMIT 1').get() as { id: number } | undefined;
|
| 499 |
+
if (any) {
|
| 500 |
+
createdBy = any.id;
|
| 501 |
+
} else {
|
| 502 |
+
const r = db.prepare("INSERT INTO users (username, email, password_hash, role) VALUES ('invite_creator', 'invite_creator@test.example.com', 'x', 'admin')").run();
|
| 503 |
+
createdBy = r.lastInsertRowid as number;
|
| 504 |
+
}
|
| 505 |
+
}
|
| 506 |
+
}
|
| 507 |
+
const result = db.prepare(
|
| 508 |
+
'INSERT INTO invite_tokens (token, max_uses, used_count, expires_at, created_by) VALUES (?, ?, 0, ?, ?)'
|
| 509 |
+
).run(token, overrides.max_uses ?? 1, overrides.expires_at ?? null, createdBy);
|
| 510 |
+
return db.prepare('SELECT * FROM invite_tokens WHERE id = ?').get(result.lastInsertRowid) as TestInviteToken;
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
// ---------------------------------------------------------------------------
|
| 514 |
+
// Notification helpers
|
| 515 |
+
// ---------------------------------------------------------------------------
|
| 516 |
+
|
| 517 |
+
/** Upsert a key/value pair into app_settings. */
|
| 518 |
+
export function setAppSetting(db: Database.Database, key: string, value: string): void {
|
| 519 |
+
db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(key, value);
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
/** Set the active notification channels (e.g. 'email', 'webhook', 'email,webhook', 'none'). */
|
| 523 |
+
export function setNotificationChannels(db: Database.Database, channels: string): void {
|
| 524 |
+
setAppSetting(db, 'notification_channels', channels);
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
/** Explicitly disable a per-user notification preference for a given event+channel combo. */
|
| 528 |
+
export function disableNotificationPref(
|
| 529 |
+
db: Database.Database,
|
| 530 |
+
userId: number,
|
| 531 |
+
eventType: string,
|
| 532 |
+
channel: string
|
| 533 |
+
): void {
|
| 534 |
+
db.prepare(
|
| 535 |
+
'INSERT OR REPLACE INTO notification_channel_preferences (user_id, event_type, channel, enabled) VALUES (?, ?, ?, 0)'
|
| 536 |
+
).run(userId, eventType, channel);
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
// ---------------------------------------------------------------------------
|
| 540 |
+
// Photo integration helpers
|
| 541 |
+
// ---------------------------------------------------------------------------
|
| 542 |
+
|
| 543 |
+
export interface TestTripPhoto {
|
| 544 |
+
id: number;
|
| 545 |
+
trip_id: number;
|
| 546 |
+
user_id: number;
|
| 547 |
+
asset_id: string;
|
| 548 |
+
provider: string;
|
| 549 |
+
shared: number;
|
| 550 |
+
album_link_id: number | null;
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
export function addTripPhoto(
|
| 554 |
+
db: Database.Database,
|
| 555 |
+
tripId: number,
|
| 556 |
+
userId: number,
|
| 557 |
+
assetId: string,
|
| 558 |
+
provider: string,
|
| 559 |
+
opts: { shared?: boolean; albumLinkId?: number } = {}
|
| 560 |
+
): TestTripPhoto {
|
| 561 |
+
// Insert into trek_photos first (central registry)
|
| 562 |
+
db.prepare(
|
| 563 |
+
'INSERT OR IGNORE INTO trek_photos (provider, asset_id, owner_id) VALUES (?, ?, ?)'
|
| 564 |
+
).run(provider, assetId, userId);
|
| 565 |
+
const trekPhoto = db.prepare(
|
| 566 |
+
'SELECT id FROM trek_photos WHERE provider = ? AND asset_id = ? AND owner_id = ?'
|
| 567 |
+
).get(provider, assetId, userId) as { id: number };
|
| 568 |
+
|
| 569 |
+
const result = db.prepare(
|
| 570 |
+
'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, photo_id, shared, album_link_id) VALUES (?, ?, ?, ?, ?)'
|
| 571 |
+
).run(tripId, userId, trekPhoto.id, opts.shared ? 1 : 0, opts.albumLinkId ?? null);
|
| 572 |
+
return db.prepare(`
|
| 573 |
+
SELECT tp.id, tp.trip_id, tp.user_id, tkp.asset_id, tkp.provider, tp.shared, tp.album_link_id
|
| 574 |
+
FROM trip_photos tp
|
| 575 |
+
JOIN trek_photos tkp ON tkp.id = tp.photo_id
|
| 576 |
+
WHERE tp.id = ?
|
| 577 |
+
`).get(result.lastInsertRowid) as TestTripPhoto;
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
export interface TestAlbumLink {
|
| 581 |
+
id: number;
|
| 582 |
+
trip_id: number;
|
| 583 |
+
user_id: number;
|
| 584 |
+
provider: string;
|
| 585 |
+
album_id: string;
|
| 586 |
+
album_name: string;
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
export function addAlbumLink(
|
| 590 |
+
db: Database.Database,
|
| 591 |
+
tripId: number,
|
| 592 |
+
userId: number,
|
| 593 |
+
provider: string,
|
| 594 |
+
albumId: string,
|
| 595 |
+
albumName = 'Test Album'
|
| 596 |
+
): TestAlbumLink {
|
| 597 |
+
const result = db.prepare(
|
| 598 |
+
'INSERT INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)'
|
| 599 |
+
).run(tripId, userId, provider, albumId, albumName);
|
| 600 |
+
return db.prepare('SELECT * FROM trip_album_links WHERE id = ?').get(result.lastInsertRowid) as TestAlbumLink;
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
export function setImmichCredentials(
|
| 604 |
+
db: Database.Database,
|
| 605 |
+
userId: number,
|
| 606 |
+
url: string,
|
| 607 |
+
apiKey: string
|
| 608 |
+
): void {
|
| 609 |
+
db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ? WHERE id = ?')
|
| 610 |
+
.run(url, encrypt_api_key(apiKey), userId);
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
export function setSynologyCredentials(
|
| 614 |
+
db: Database.Database,
|
| 615 |
+
userId: number,
|
| 616 |
+
url: string,
|
| 617 |
+
username: string,
|
| 618 |
+
password: string
|
| 619 |
+
): void {
|
| 620 |
+
db.prepare('UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ? WHERE id = ?')
|
| 621 |
+
.run(url, username, encrypt_api_key(password), userId);
|
| 622 |
+
}
|
| 623 |
+
|
| 624 |
+
// ---------------------------------------------------------------------------
|
| 625 |
+
// Categories
|
| 626 |
+
// ---------------------------------------------------------------------------
|
| 627 |
+
|
| 628 |
+
export function createCategory(
|
| 629 |
+
db: Database.Database,
|
| 630 |
+
overrides: { name?: string; color?: string; icon?: string; user_id?: number | null } = {}
|
| 631 |
+
) {
|
| 632 |
+
const name = overrides.name ?? `Test Category ${++_categorySeq}`;
|
| 633 |
+
const color = overrides.color ?? '#6366f1';
|
| 634 |
+
const icon = overrides.icon ?? '📍';
|
| 635 |
+
const userId = overrides.user_id ?? null;
|
| 636 |
+
const result = db.prepare('INSERT INTO categories (name, color, icon, user_id) VALUES (?, ?, ?, ?)').run(name, color, icon, userId);
|
| 637 |
+
return db.prepare('SELECT * FROM categories WHERE id = ?').get(result.lastInsertRowid) as { id: number; name: string; color: string; icon: string; user_id: number | null };
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
// ---------------------------------------------------------------------------
|
| 641 |
+
// Tags
|
| 642 |
+
// ---------------------------------------------------------------------------
|
| 643 |
+
|
| 644 |
+
export function createTag(
|
| 645 |
+
db: Database.Database,
|
| 646 |
+
userId: number,
|
| 647 |
+
overrides: { name?: string; color?: string } = {}
|
| 648 |
+
) {
|
| 649 |
+
const name = overrides.name ?? `Test Tag ${++_tagSeq}`;
|
| 650 |
+
const color = overrides.color ?? '#10b981';
|
| 651 |
+
const result = db.prepare('INSERT INTO tags (user_id, name, color) VALUES (?, ?, ?)').run(userId, name, color);
|
| 652 |
+
return db.prepare('SELECT * FROM tags WHERE id = ?').get(result.lastInsertRowid) as { id: number; user_id: number; name: string; color: string };
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
// ---------------------------------------------------------------------------
|
| 656 |
+
// Journeys
|
| 657 |
+
// ---------------------------------------------------------------------------
|
| 658 |
+
|
| 659 |
+
let _journeySeq = 0;
|
| 660 |
+
|
| 661 |
+
export interface TestJourney {
|
| 662 |
+
id: number;
|
| 663 |
+
user_id: number;
|
| 664 |
+
title: string;
|
| 665 |
+
subtitle: string | null;
|
| 666 |
+
status: string;
|
| 667 |
+
cover_image: string | null;
|
| 668 |
+
created_at: number;
|
| 669 |
+
updated_at: number;
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
export function createJourney(
|
| 673 |
+
db: Database.Database,
|
| 674 |
+
userId: number,
|
| 675 |
+
overrides: Partial<{ title: string; subtitle: string; status: string }> = {}
|
| 676 |
+
): TestJourney {
|
| 677 |
+
_journeySeq++;
|
| 678 |
+
const title = overrides.title ?? `Test Journey ${_journeySeq}`;
|
| 679 |
+
const now = Date.now();
|
| 680 |
+
const result = db.prepare(
|
| 681 |
+
'INSERT INTO journeys (user_id, title, subtitle, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)'
|
| 682 |
+
).run(userId, title, overrides.subtitle ?? null, overrides.status ?? 'active', now, now);
|
| 683 |
+
|
| 684 |
+
const journeyId = result.lastInsertRowid as number;
|
| 685 |
+
|
| 686 |
+
// Auto-add owner as contributor
|
| 687 |
+
db.prepare(
|
| 688 |
+
"INSERT INTO journey_contributors (journey_id, user_id, role, added_at) VALUES (?, ?, 'owner', ?)"
|
| 689 |
+
).run(journeyId, userId, now);
|
| 690 |
+
|
| 691 |
+
return db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as TestJourney;
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
export interface TestJourneyEntry {
|
| 695 |
+
id: number;
|
| 696 |
+
journey_id: number;
|
| 697 |
+
author_id: number;
|
| 698 |
+
type: string;
|
| 699 |
+
entry_date: string;
|
| 700 |
+
title: string | null;
|
| 701 |
+
story: string | null;
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
export function createJourneyEntry(
|
| 705 |
+
db: Database.Database,
|
| 706 |
+
journeyId: number,
|
| 707 |
+
authorId: number,
|
| 708 |
+
overrides: Partial<{ type: string; entry_date: string; title: string; story: string; location_name: string; mood: string; weather: string }> = {}
|
| 709 |
+
): TestJourneyEntry {
|
| 710 |
+
const now = Date.now();
|
| 711 |
+
const result = db.prepare(`
|
| 712 |
+
INSERT INTO journey_entries (journey_id, author_id, type, entry_date, title, story, location_name, mood, weather, visibility, sort_order, created_at, updated_at)
|
| 713 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'private', 0, ?, ?)
|
| 714 |
+
`).run(
|
| 715 |
+
journeyId, authorId,
|
| 716 |
+
overrides.type ?? 'entry',
|
| 717 |
+
overrides.entry_date ?? '2026-01-15',
|
| 718 |
+
overrides.title ?? null,
|
| 719 |
+
overrides.story ?? null,
|
| 720 |
+
overrides.location_name ?? null,
|
| 721 |
+
overrides.mood ?? null,
|
| 722 |
+
overrides.weather ?? null,
|
| 723 |
+
now, now
|
| 724 |
+
);
|
| 725 |
+
return db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(result.lastInsertRowid) as TestJourneyEntry;
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
export function addJourneyContributor(
|
| 729 |
+
db: Database.Database,
|
| 730 |
+
journeyId: number,
|
| 731 |
+
userId: number,
|
| 732 |
+
role: 'editor' | 'viewer' = 'editor'
|
| 733 |
+
): void {
|
| 734 |
+
db.prepare(
|
| 735 |
+
'INSERT OR IGNORE INTO journey_contributors (journey_id, user_id, role, added_at) VALUES (?, ?, ?, ?)'
|
| 736 |
+
).run(journeyId, userId, role, Date.now());
|
| 737 |
+
}
|
| 738 |
+
|
| 739 |
+
export function linkTripToJourney(db: Database.Database, journeyId: number, tripId: number): void {
|
| 740 |
+
db.prepare(
|
| 741 |
+
'INSERT OR IGNORE INTO journey_trips (journey_id, trip_id, linked_at) VALUES (?, ?, ?)'
|
| 742 |
+
).run(journeyId, tripId, Date.now());
|
| 743 |
+
}
|