mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-21 22:46:32 +00:00
2c2d008dc2
* fix(security): mint idempotency keys properly, and resolve the extractor by path Three findings out of a sweep of every open Sonar security issue. The other 49 turned out to be false positives and are documented in sonar-project.properties rather than changed — each entry scoped to a file, never a whole rule, so a future Math.random() on an auth path still fails. The idempotency key is the one that can lose data. Both producers fell back to Math.random when crypto.randomUUID was missing, and randomUUID needs a secure context — TREK's own quickstart is http://localhost:3000 and LAN installs run on http://192.168.x.x, so on the deployments the README documents the fallback is what actually runs. The axios one was `Math.random().toString(36).slice(2)`, which is not length-stable: 0.5 yields a single character and 0 yields the empty string, which the interceptor reads as "no key" and skips deduplication for entirely. Two writes sharing a key collapse into one — the second gets the first one's cached response and the edit is gone with no error anywhere. Both now come from utils/randomId, which has the getRandomValues rung that works in insecure contexts too. The extractor probe stored the bare binary name, so every extraction re-resolved it through whatever PATH held at that moment. The official image sets KITINERARY_EXTRACTOR_PATH and never reaches that branch, but a bare-metal install without it ran an unqualified name from a PATH it does not control. It now walks the search path itself and keeps the absolute path of the file it verified; execFileSync also drops the /bin/sh hop the old probe needed. PATH comes through app-config because process.env is walled off in src/. * fix: four tests and sorts that were not doing what they claimed Sonar reported 43 high-impact reliability issues. Reading all of them, four are real; the rest are cosmetic or would be made worse by the suggested change. budget.test.ts hand-built `paid: true`, but both emitters send `paid: body.paid ? 1 : 0` and the handler stores the value verbatim — the test asserted a payload the server never sends. The line below it already used a number. admin.controller.test.ts had a `.resolves` assertion with no await. The promise was dropped, so that line could not fail the test. The two to-do category lists sorted with a bare .sort(), which is byte order: every accented name files behind the whole ASCII range, so in a German trip "Übernachtung" lands after "Zelt". TREK ships 23 locales, so this is real data. One side effect worth knowing: katColor picks a category's dot colour by its index, so re-sorting can move which category shows which colour — it already moves whenever a category is added, and the colour carries no meaning. Deliberately not changed: the two `| 0` truncations (Math.trunc is not equivalent — `| 0` wraps at 32 bits and these carry millisecond timestamps), the two .map() callbacks whose second parameter is declared and used, and the sha1 in thumbnail.service (its own comment says a swap would orphan every existing thumbnail). * refactor: give every button a type, and prefer the Number statics Two mechanical sweeps, no behaviour change intended in either. A <button> with no type attribute is type="submit" per the HTML spec. Outside a form that does nothing today, but it turns into a surprise the moment the markup is wrapped in one, which is what Sonar's S9011 is warning about. 870 buttons get an explicit type="button". Two things were left alone on purpose: buttons that take a {...spread}, because the spread may carry a type and the merge order decides which wins, and anything inside a <form> — there the answer is a judgement call, and checking all eleven form files found every real submit button already carrying type="submit". The Number sweep covers only the three globals that are exactly equivalent to their Number twin: parseInt, parseFloat and NaN. isNaN is NOT in it — the global coerces its argument, so isNaN('abc') is true where Number.isNaN('abc') is false, and renaming it would change what the code does. It reaches server and plugin-sdk as well as the client; both copies of egress-policy.ts got the identical edit, so the mirror the SDK's parity test guards stays intact.
103 lines
4.4 KiB
TypeScript
103 lines
4.4 KiB
TypeScript
import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Req, UseGuards } from '@nestjs/common';
|
|
import type { Request } from 'express';
|
|
import type { User } from '../../types';
|
|
import { TripInviteService } from './trip-invite.service';
|
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
|
import { CurrentUser } from '../auth/current-user.decorator';
|
|
import { RateLimitService } from '../common/rate-limit.service';
|
|
import { TripInviteLinkCreateDto } from './trip-invite.dto';
|
|
import { getClientIp } from '../audit/client-ip';
|
|
import { AuditService } from '../audit/audit.service';
|
|
|
|
const RL_WINDOW = 15 * 60 * 1000;
|
|
|
|
/**
|
|
* /api/trips/:tripId/invite-link — manage a trip's invite link (#1143).
|
|
*
|
|
* Mirrors the public share link: trip access (404) + the 'share_manage'
|
|
* permission (403). Unlike the share link this one is not public — see
|
|
* TripInviteController for the login-required join.
|
|
*/
|
|
@Controller('api/trips/:tripId/invite-link')
|
|
@UseGuards(JwtAuthGuard)
|
|
export class TripInviteLinkController {
|
|
constructor(private readonly invites: TripInviteService, private readonly audit: AuditService) {}
|
|
|
|
private requireManage(tripId: string, user: User) {
|
|
const trip = this.invites.verifyTripAccess(tripId, user.id);
|
|
if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
|
|
if (!this.invites.canManage(trip, user)) throw new HttpException({ error: 'No permission' }, 403);
|
|
}
|
|
|
|
@Get()
|
|
get(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
|
// The token grants trip membership, so reading it needs the same
|
|
// share_manage permission as creating/rotating it — not just trip access.
|
|
this.requireManage(tripId, user);
|
|
const info = this.invites.get(tripId);
|
|
return info ? info : { token: null };
|
|
}
|
|
|
|
@Post()
|
|
create(
|
|
@CurrentUser() user: User,
|
|
@Param('tripId') tripId: string,
|
|
@Body() body: TripInviteLinkCreateDto,
|
|
@Req() req: Request,
|
|
) {
|
|
this.requireManage(tripId, user);
|
|
const days = body?.expires_in_days != null && String(body.expires_in_days).trim() !== ''
|
|
? Number.parseInt(String(body.expires_in_days))
|
|
: null;
|
|
const info = this.invites.createOrRotate(tripId, user.id, Number.isFinite(days as number) ? days : null);
|
|
this.audit.writeAudit({ userId: user.id, action: 'trip.invite_link_create', resource: tripId, ip: getClientIp(req), details: { expires_in_days: days } });
|
|
return info;
|
|
}
|
|
|
|
@Delete()
|
|
remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Req() req: Request) {
|
|
this.requireManage(tripId, user);
|
|
this.invites.remove(tripId);
|
|
this.audit.writeAudit({ userId: user.id, action: 'trip.invite_link_delete', resource: tripId, ip: getClientIp(req) });
|
|
return { success: true };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* /api/trip-invites/:token — resolve + accept a trip invite as an existing,
|
|
* logged-in user. JWT-guarded: an anonymous visitor is redirected to /login by
|
|
* the client (never registration). Rate-limited to blunt any token probing even
|
|
* though the tokens are 192-bit and unguessable. The join is idempotent and
|
|
* owner-safe (see joinTripAsMember).
|
|
*/
|
|
@Controller('api/trip-invites')
|
|
@UseGuards(JwtAuthGuard)
|
|
export class TripInviteController {
|
|
constructor(private readonly invites: TripInviteService, private readonly rl: RateLimitService, private readonly audit: AuditService) {}
|
|
|
|
private limit(req: Request, max: number): void {
|
|
if (!this.rl.check('trip_invite', req.ip || 'unknown', max, RL_WINDOW, Date.now())) {
|
|
throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429);
|
|
}
|
|
}
|
|
|
|
@Get(':token')
|
|
preview(@Param('token') token: string, @Req() req: Request) {
|
|
this.limit(req, 30);
|
|
const resolved = this.invites.resolve(token);
|
|
if (!resolved) throw new HttpException({ error: 'Invalid or expired invite link' }, 404);
|
|
return { trip_id: resolved.trip_id, title: resolved.title };
|
|
}
|
|
|
|
@Post(':token/accept')
|
|
@HttpCode(200)
|
|
accept(@CurrentUser() user: User, @Param('token') token: string, @Req() req: Request) {
|
|
this.limit(req, 20);
|
|
const resolved = this.invites.resolve(token);
|
|
if (!resolved) throw new HttpException({ error: 'Invalid or expired invite link' }, 404);
|
|
const result = this.invites.join(resolved.trip_id, user.id);
|
|
this.audit.writeAudit({ userId: user.id, action: 'trip.invite_link_join', resource: String(resolved.trip_id), ip: getClientIp(req), details: { joined: result.joined } });
|
|
return { trip_id: resolved.trip_id, joined: result.joined };
|
|
}
|
|
}
|