mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(journey,files): close the cross-trip and role holes on the sharing surface
Files: two :id handlers took the file id from the URL and never resolved it against :tripId. Membership of any trip was enough to read another trip's file links (with the joined reservation titles) or to delete one. Both now resolve the file the way every sibling handler already does. Journey: a contributor with role 'viewer' - blocked from every other write in the domain - could overwrite or delete the Studio book, and could read the share token, which is an anonymous credential that outlives their contributor status. The book writes take canEdit now and the token read takes the owner check its own create and delete already use. Also: the share-link MCP tool reset every flag to permissive defaults when it was called to refresh a link, so a journey deliberately shared without its gallery or map quietly started publishing both; setShareLink dropped newest_first entirely; the public routes ignored the Journey addon switch; and photo uploads committed to storage before the access check, leaking the objects on the 403 path. Trips: DELETE answered 403 to someone with no access at all, which turns sequential ids into an existence oracle. A member who simply lacks trip_delete still gets 403.
This commit is contained in:
@@ -31,8 +31,10 @@ export function isVideoExtension(ext: string): boolean {
|
||||
// `allowed_file_types` is `*`, this list is still enforced so the
|
||||
// wildcard doesn't silently admit executables/scripts.
|
||||
export const BLOCKED_EXTENSIONS = [
|
||||
// Server-rendered / scripted content that could XSS a viewer
|
||||
'.svg', '.html', '.htm', '.xml', '.xhtml',
|
||||
// Server-rendered / scripted content that could XSS a viewer. Downloads are
|
||||
// served inline with an extension-derived Content-Type, so every spelling a
|
||||
// browser renders as a document has to be listed, not just the common ones.
|
||||
'.svg', '.svgz', '.html', '.htm', '.shtml', '.shtm', '.xml', '.xhtml', '.xht',
|
||||
// Scripts
|
||||
'.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.php', '.py', '.rb', '.pl',
|
||||
// Executables
|
||||
|
||||
@@ -279,6 +279,13 @@ export class FilesController {
|
||||
if (!this.files.can('file_edit', trip, user)) {
|
||||
throw new HttpException({ error: 'No permission' }, 403);
|
||||
}
|
||||
// deleteFileLink scopes by (linkId, fileId) only, so the file itself has to
|
||||
// be resolved against :tripId first. Otherwise a member of any trip could
|
||||
// drop a link row belonging to a foreign trip's file.
|
||||
const file = this.files.getFileById(id, tripId);
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'File not found' }, 404);
|
||||
}
|
||||
this.files.deleteFileLink(linkId, id);
|
||||
return { success: true };
|
||||
}
|
||||
@@ -286,6 +293,10 @@ export class FilesController {
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Get(':id/links')
|
||||
links(@CurrentUser() user: User, @Trip() trip: TripAccess, @Param('tripId') tripId: string, @Param('id') id: string) {
|
||||
const file = this.files.getFileById(id, tripId);
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'File not found' }, 404);
|
||||
}
|
||||
return { links: this.files.getFileLinks(id) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,10 +9,11 @@ import { JourneyDomainService } from './journey-domain.service';
|
||||
*
|
||||
* ── Access ───────────────────────────────────────────────────────────────
|
||||
*
|
||||
* A book belongs to its journey, so it inherits the journey's access exactly —
|
||||
* every contributor can open and edit it. There is no separate book permission
|
||||
* and there should not be: a second access model over the same object is how
|
||||
* two rules end up disagreeing about who may do what.
|
||||
* A book belongs to its journey, so it inherits the journey's access exactly:
|
||||
* every contributor can open it, and the ones who may edit the journey may edit
|
||||
* it. There is no separate book permission and there should not be: a second
|
||||
* access model over the same object is how two rules end up disagreeing about
|
||||
* who may do what.
|
||||
*
|
||||
* ── Concurrency ──────────────────────────────────────────────────────────
|
||||
*
|
||||
@@ -37,6 +38,15 @@ export class JourneyBookService {
|
||||
return !!this.journey.canAccessJourney(journeyId, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writing the book is an edit like any other in this domain, so it takes the
|
||||
* same owner-or-editor check the entry and photo writes take. canAccess also
|
||||
* covers role 'viewer', who may read the book but must not overwrite it.
|
||||
*/
|
||||
private canWrite(journeyId: number, userId: number): boolean {
|
||||
return this.journey.canEdit(journeyId, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this user may open the journey's book at all.
|
||||
*
|
||||
@@ -115,7 +125,7 @@ export class JourneyBookService {
|
||||
userId: number,
|
||||
input: { title: string; document: unknown; baseVersion?: number },
|
||||
): { record: BookRecord } | { conflict: BookRecord } | null {
|
||||
if (!this.canAccess(journeyId, userId)) return null;
|
||||
if (!this.canWrite(journeyId, userId)) return null;
|
||||
|
||||
const document = JSON.stringify(normalizeBookDocument(input.document));
|
||||
const existing = this.db
|
||||
@@ -160,7 +170,7 @@ export class JourneyBookService {
|
||||
}
|
||||
|
||||
deleteBook(journeyId: number, userId: number): boolean | null {
|
||||
if (!this.canAccess(journeyId, userId)) return null;
|
||||
if (!this.canWrite(journeyId, userId)) return null;
|
||||
const result = this.db
|
||||
.prepare('DELETE FROM journey_books WHERE journey_id = ?')
|
||||
.run(journeyId);
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { Controller, Get, HttpException, Param, Res } from '@nestjs/common';
|
||||
import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import path from 'node:path';
|
||||
import { JourneyService } from './journey.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { Public } from '../auth/public.decorator';
|
||||
|
||||
/**
|
||||
@@ -10,11 +13,18 @@ import { Public } from '../auth/public.decorator';
|
||||
* proxy for publicly shared journeys.
|
||||
*
|
||||
* Byte-identical to the legacy Express route (server/src/routes/journeyPublic.ts):
|
||||
* NOT behind any guard, every route validates the share token (404 on failure),
|
||||
* no authentication, every route validates the share token (404 on failure),
|
||||
* the unified proxy streams by trek_photo_id and the legacy proxy serves local
|
||||
* files (with the uploads-dir traversal guard) or proxies immich/synology.
|
||||
*
|
||||
* The addon gate is the one guard here, and it has to be: turning the Journey
|
||||
* addon off is meant to take the feature away, and without it already-published
|
||||
* journeys stayed publicly readable while the authenticated surface went dark.
|
||||
* AddonGuard only reads addon state, so it is safe in front of a @Public route.
|
||||
*/
|
||||
@Public('share-token validated: the whole point is a link that works without an account')
|
||||
@UseGuards(AddonGuard)
|
||||
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
|
||||
@Controller('api/public/journey')
|
||||
export class JourneyPublicController {
|
||||
constructor(
|
||||
@@ -72,7 +82,9 @@ export class JourneyPublicController {
|
||||
return;
|
||||
}
|
||||
|
||||
const effectiveOwnerId = valid.ownerId || Number(ownerId);
|
||||
// :ownerId stays in the path so old share links keep routing, but it is not
|
||||
// read any more: the owner comes from the row the token resolved to.
|
||||
const effectiveOwnerId = valid.ownerId;
|
||||
const streaming = this.journey.streamProviderAsset(
|
||||
res,
|
||||
provider,
|
||||
|
||||
@@ -44,6 +44,22 @@ export class JourneyShareService {
|
||||
// able to publish the journey or change which screens are shared.
|
||||
if (!this.journey.isOwner(journeyId, createdBy)) return null;
|
||||
|
||||
const existing = this.db.prepare('SELECT token, share_timeline, share_gallery, share_map, newest_first FROM journey_share_tokens WHERE journey_id = ?')
|
||||
.get(journeyId) as { token: string; share_timeline: number; share_gallery: number; share_map: number; newest_first: number } | undefined;
|
||||
|
||||
if (existing) {
|
||||
// An update only changes the flags it was actually given. Falling back to
|
||||
// the create-time defaults here would silently re-publish a gallery or map
|
||||
// the owner had switched off, at the unchanged token.
|
||||
const share_timeline = permissions.share_timeline ?? !!existing.share_timeline;
|
||||
const share_gallery = permissions.share_gallery ?? !!existing.share_gallery;
|
||||
const share_map = permissions.share_map ?? !!existing.share_map;
|
||||
const newest_first = permissions.newest_first ?? !!existing.newest_first;
|
||||
this.db.prepare('UPDATE journey_share_tokens SET share_timeline = ?, share_gallery = ?, share_map = ?, newest_first = ? WHERE journey_id = ?')
|
||||
.run(share_timeline ? 1 : 0, share_gallery ? 1 : 0, share_map ? 1 : 0, newest_first ? 1 : 0, journeyId);
|
||||
return { token: existing.token, created: false };
|
||||
}
|
||||
|
||||
const {
|
||||
share_timeline = true,
|
||||
share_gallery = true,
|
||||
@@ -51,13 +67,6 @@ export class JourneyShareService {
|
||||
newest_first = false,
|
||||
} = permissions;
|
||||
|
||||
const existing = this.db.prepare('SELECT token FROM journey_share_tokens WHERE journey_id = ?').get(journeyId) as { token: string } | undefined;
|
||||
if (existing) {
|
||||
this.db.prepare('UPDATE journey_share_tokens SET share_timeline = ?, share_gallery = ?, share_map = ?, newest_first = ? WHERE journey_id = ?')
|
||||
.run(share_timeline ? 1 : 0, share_gallery ? 1 : 0, share_map ? 1 : 0, newest_first ? 1 : 0, journeyId);
|
||||
return { token: existing.token, created: false };
|
||||
}
|
||||
|
||||
const token = crypto.randomBytes(24).toString('base64url');
|
||||
this.db.prepare('INSERT INTO journey_share_tokens (journey_id, token, created_by, share_timeline, share_gallery, share_map, newest_first) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(journeyId, token, createdBy, share_timeline ? 1 : 0, share_gallery ? 1 : 0, share_map ? 1 : 0, newest_first ? 1 : 0);
|
||||
@@ -109,13 +118,18 @@ export class JourneyShareService {
|
||||
// owner shared the gallery.
|
||||
if (!row.share_gallery) return null;
|
||||
const photo = this.db.prepare(`
|
||||
SELECT tkp.owner_id FROM journey_photos gp
|
||||
SELECT tkp.owner_id, j.user_id AS journey_owner_id
|
||||
FROM journey_photos gp
|
||||
JOIN trek_photos tkp ON tkp.id = gp.photo_id
|
||||
JOIN journeys j ON j.id = gp.journey_id
|
||||
WHERE tkp.asset_id = ? AND gp.journey_id = ?
|
||||
`).get(assetId, row.journey_id) as any;
|
||||
// Only resolve assets that actually belong to this shared journey.
|
||||
if (!photo) return null;
|
||||
return { ownerId: photo.owner_id };
|
||||
// trek_photos.owner_id can be NULL. The journey's owner is the fallback, the
|
||||
// same one the photo proxy uses. Whose provider credentials get tried must
|
||||
// never come from a number an anonymous caller put in the URL.
|
||||
return { ownerId: photo.owner_id || photo.journey_owner_id };
|
||||
}
|
||||
|
||||
getPublicJourney(token: string) {
|
||||
|
||||
@@ -152,6 +152,20 @@ export class JourneyController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop uploads that were committed before the authorization result was known.
|
||||
*
|
||||
* The commit has to happen first (the Immich mirror reads the final path), so
|
||||
* every refusal after it has to take the bytes back out. Nothing sweeps
|
||||
* orphans, and a loop of rejected POSTs would otherwise just fill the disk.
|
||||
*/
|
||||
private async discardJourneyUploads(files: Express.Multer.File[]): Promise<void> {
|
||||
for (const f of files) {
|
||||
if (f.path) { try { fs.unlinkSync(f.path); } catch { /* best-effort */ } }
|
||||
await this.storage.delete('journey', f.filename).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// The add call carries only an asset id, so when and where the picture was taken
|
||||
// are fetched from the provider afterwards rather than trusted from the client
|
||||
// (#1614). Detached: a slow or unreachable provider must not hold up the add.
|
||||
@@ -220,10 +234,15 @@ export class JourneyController {
|
||||
// reads each file at its final uploads/journey path.
|
||||
await this.commitJourneyUploads(files);
|
||||
const results: unknown[] = [];
|
||||
const refused: Express.Multer.File[] = [];
|
||||
for (const file of files) {
|
||||
const relativePath = `journey/${file.filename}`;
|
||||
const photo = this.journey.addPhoto(Number(entryId), user.id, relativePath, undefined, body?.caption as string | undefined);
|
||||
if (!photo) continue;
|
||||
if (!photo) {
|
||||
// No row points at this file, so nothing would ever clean it up.
|
||||
refused.push(file);
|
||||
continue;
|
||||
}
|
||||
// Mirror to Immich only when the user explicitly opted in (#730).
|
||||
if (this.journey.immichAutoUploadEnabled(user.id)) {
|
||||
try {
|
||||
@@ -238,6 +257,9 @@ export class JourneyController {
|
||||
}
|
||||
results.push(photo);
|
||||
}
|
||||
if (refused.length) {
|
||||
await this.discardJourneyUploads(refused);
|
||||
}
|
||||
if (!results.length) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
@@ -348,6 +370,7 @@ export class JourneyController {
|
||||
const filePaths = files.map((f) => ({ path: `journey/${f.filename}` }));
|
||||
const photos = this.journey.uploadGalleryPhotos(Number(id), user.id, filePaths);
|
||||
if (!photos.length) {
|
||||
await this.discardJourneyUploads(files);
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
// An uploaded file carries its own EXIF; reading it is what puts the photo on
|
||||
@@ -465,6 +488,7 @@ export class JourneyController {
|
||||
await this.commitJourneyUploads([file]);
|
||||
const result = this.journey.updateJourney(Number(id), user.id, { cover_image: `journey/${file.filename}` });
|
||||
if (!result) {
|
||||
await this.discardJourneyUploads([file]);
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
return result;
|
||||
@@ -679,6 +703,7 @@ export class JourneyController {
|
||||
share_timeline: body.share_timeline as boolean | undefined,
|
||||
share_gallery: body.share_gallery as boolean | undefined,
|
||||
share_map: body.share_map as boolean | undefined,
|
||||
newest_first: body.newest_first as boolean | undefined,
|
||||
});
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
|
||||
@@ -408,28 +408,36 @@ export class JourneyMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'get_journey_share_link',
|
||||
description: 'Get the current public share link for a journey. Returns null if none exists.',
|
||||
description: 'Get the current public share link for a journey. Owner only. Returns null if none exists.',
|
||||
inputSchema: { journeyId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'share' },
|
||||
})
|
||||
getJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
if (!this.journey.canAccessJourney(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
// Owner only, same as the REST route: handing out the token is handing out
|
||||
// the journey.
|
||||
if (!this.journey.isOwner(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
return ok({ shareLink: this.share.getJourneyShareLink(journeyId) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'create_journey_share_link',
|
||||
description: 'Create or update the public share link for a journey. Owner only.',
|
||||
inputSchema: { journeyId: z.number().int().positive() },
|
||||
description: 'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on.',
|
||||
inputSchema: {
|
||||
journeyId: z.number().int().positive(),
|
||||
share_timeline: z.boolean().optional(),
|
||||
share_gallery: z.boolean().optional(),
|
||||
share_map: z.boolean().optional(),
|
||||
newest_first: z.boolean().optional(),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'share' },
|
||||
})
|
||||
createJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
createJourneyShareLink({ journeyId, ...permissions }: { journeyId: number; share_timeline?: boolean; share_gallery?: boolean; share_map?: boolean; newest_first?: boolean }, ctx: McpContext) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const shareLink = this.share.createOrUpdateJourneyShareLink(journeyId, ctx.userId, {});
|
||||
const shareLink = this.share.createOrUpdateJourneyShareLink(journeyId, ctx.userId, permissions);
|
||||
if (!shareLink) return notFound('Journey not found or access denied.');
|
||||
return ok({ shareLink });
|
||||
}
|
||||
|
||||
@@ -78,11 +78,11 @@ export class JourneyService {
|
||||
removeContributor(id: number, userId: number, targetUserId: number) { return this.journey.removeContributor(id, userId, targetUserId); }
|
||||
|
||||
// Share links
|
||||
// Authorization: only someone with access to the journey may read its public
|
||||
// share token — same access model as create/delete here and the
|
||||
// get_journey_share_link MCP tool.
|
||||
// Authorization: the token is the whole credential, so reading it needs the
|
||||
// same owner check create/delete use. A viewer who reads it keeps a working
|
||||
// anonymous link after being removed as a contributor.
|
||||
getJourneyShareLink(id: number, userId: number) {
|
||||
if (!this.journey.canAccessJourney(id, userId)) return null;
|
||||
if (!this.journey.isOwner(id, userId)) return null;
|
||||
return this.share.getJourneyShareLink(id);
|
||||
}
|
||||
createOrUpdateJourneyShareLink(id: number, userId: number, data: Parameters<typeof this.share.createOrUpdateJourneyShareLink>[2]) { return this.share.createOrUpdateJourneyShareLink(id, userId, data); }
|
||||
|
||||
@@ -239,6 +239,13 @@ export class TripsController {
|
||||
if (!owner) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
// Someone with no access at all gets the same 404 as a trip that does not
|
||||
// exist, otherwise the 403 below turns sequential ids into an existence
|
||||
// oracle. Admins are exempt: they may delete trips they are not a member of,
|
||||
// which is what the isAdminDelete branch further down relies on.
|
||||
if (user.role !== 'admin' && !this.trips.canAccessTrip(id, user.id)) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (!this.trips.can('trip_delete', user.role, owner.user_id, user.id, owner.user_id !== user.id)) {
|
||||
throw new HttpException({ error: 'No permission to delete this trip' }, 403);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user