Files
TREK/server/src/nest/notifications/notifications.controller.ts
T
Maurice 2c2d008dc2 fix: clear every open Sonar security issue, and half the reliability ones (#2037)
* 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.
2026-08-25 15:22:38 +02:00

234 lines
8.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
Body,
Controller,
Delete,
Get,
HttpCode,
HttpException,
Param,
Post,
Put,
Query,
UseGuards,
} from '@nestjs/common';
import type { ChannelTestResult, UnreadCountResult } from '@trek/shared';
import type { User } from '../../types';
import { NotificationsService } from './notifications.service';
import {
PreferencesUpdateDto,
TestSmtpDto,
TestWebhookDto,
TestNtfyDto,
NotificationRespondDto,
} from './notifications.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { NotificationPreferencesService } from './notification-preferences.service';
import { AdminNotificationPreferencesDto } from '../admin/admin.dto';
import { CurrentUser } from '../auth/current-user.decorator';
import { ManagedForbidden } from '../common/managed';
// The masked placeholder the client sends instead of a stored secret (8× U+2022).
const MASKED = '••••••••';
/**
* /api/notifications — channel-preference matrix, channel test pings, and in-app
* notifications.
*
* Byte-identical to the legacy Express route (server/src/routes/notifications.ts):
* same auth, the same inline admin gate on /test-smtp (note: it returns
* { error: 'Admin only' }, NOT the AdminGuard's wording), the same webhook/ntfy
* fallback resolution, the same id parsing + 400/404 bodies, and the same status
* codes. POSTs that answer with res.json stay 200 (Nest would default to 201).
* The static /in-app/read-all and /in-app/all routes are declared before the
* /in-app/:id routes so they win over the param, matching the legacy order.
* Bodies validate via notifications.dto.ts (@trek/shared schemas through the
* global ZodValidationPipe) — malformed bodies now get the pipe's standard
* { error: 'field: message; …' } envelope instead of the old inline checks
* (the sanctioned ratchet behavior); valid bodies behave byte-identically.
*/
@Controller('api/notifications')
@UseGuards(JwtAuthGuard)
export class NotificationsController {
constructor(private readonly notifications: NotificationsService) {}
@Get('preferences')
getPreferences(@CurrentUser() user: User) {
return this.notifications.getPreferences(user.id, user.role);
}
@Put('preferences')
setPreferences(@CurrentUser() user: User, @Body() body: PreferencesUpdateDto) {
this.notifications.setPreferences(user.id, body);
return this.notifications.getPreferences(user.id, user.role);
}
@ManagedForbidden('the relay is the operator credential; a test send would use their reputation')
@Post('test-smtp')
@HttpCode(200)
async testSmtp(@CurrentUser() user: User, @Body() body: TestSmtpDto): Promise<ChannelTestResult> {
if (user.role !== 'admin') {
throw new HttpException({ error: 'Admin only' }, 403);
}
return this.notifications.testSmtp(body.email || user.email);
}
@Post('test-webhook')
@HttpCode(200)
async testWebhook(@CurrentUser() user: User, @Body() body: TestWebhookDto): Promise<ChannelTestResult> {
let url: string | null | undefined = body.url;
if (!url || url === MASKED) {
url = this.notifications.userWebhookUrl(user.id);
if (!url && user.role === 'admin') url = this.notifications.adminWebhookUrl();
if (!url) {
throw new HttpException({ error: 'No webhook URL configured' }, 400);
}
}
try {
new URL(url);
} catch {
throw new HttpException({ error: 'Invalid URL' }, 400);
}
return this.notifications.testWebhook(url);
}
@Post('test-ntfy')
@HttpCode(200)
async testNtfy(@CurrentUser() user: User, @Body() body: TestNtfyDto): Promise<ChannelTestResult> {
const { topic, server, token } = body;
const userCfg = this.notifications.userNtfyConfig(user.id);
const adminCfg = this.notifications.adminNtfyConfig();
const resolvedTopic = topic || userCfg?.topic || undefined;
const resolvedServer = server || userCfg?.server || adminCfg.server || undefined;
// Reuse the saved token when the request sends null, empty, or the masked placeholder.
const resolvedToken = (token && token !== MASKED)
? token
: (userCfg?.token ?? adminCfg.token ?? null);
if (!resolvedTopic) {
throw new HttpException({ error: 'No ntfy topic configured' }, 400);
}
return this.notifications.testNtfy({ topic: resolvedTopic, server: resolvedServer ?? null, token: resolvedToken });
}
/**
* Generic channel test, dispatched through the registry — this is how a plugin
* channel's "Send test" button works. The three routes above stay as they are:
* they carry bespoke masked-secret and admin-fallback resolution whose exact
* error bodies the client depends on, and folding them in here would risk that.
*/
@Post('test/:channelId')
@HttpCode(200)
async testChannel(@CurrentUser() user: User, @Param('channelId') channelId: string): Promise<ChannelTestResult> {
return this.notifications.testChannel(user.id, channelId);
}
@Get('in-app')
listInApp(
@CurrentUser() user: User,
@Query('limit') limit?: string,
@Query('offset') offset?: string,
@Query('unread_only') unreadOnly?: string,
) {
return this.notifications.listInApp(user.id, {
limit: Math.min(Number.parseInt(limit as string) || 20, 50),
offset: Number.parseInt(offset as string) || 0,
unreadOnly: unreadOnly === 'true',
});
}
@Get('in-app/unread-count')
unreadCount(@CurrentUser() user: User): UnreadCountResult {
return { count: this.notifications.unreadCount(user.id) };
}
@Put('in-app/read-all')
readAll(@CurrentUser() user: User): { success: boolean; count: number } {
return { success: true, count: this.notifications.markAllRead(user.id) };
}
@Delete('in-app/all')
deleteAll(@CurrentUser() user: User): { success: boolean; count: number } {
return { success: true, count: this.notifications.deleteAll(user.id) };
}
@Put('in-app/:id/read')
markRead(@CurrentUser() user: User, @Param('id') idParam: string): { success: boolean } {
const id = this.parseId(idParam);
if (!this.notifications.markRead(id, user.id)) {
throw new HttpException({ error: 'Not found' }, 404);
}
return { success: true };
}
@Put('in-app/:id/unread')
markUnread(@CurrentUser() user: User, @Param('id') idParam: string): { success: boolean } {
const id = this.parseId(idParam);
if (!this.notifications.markUnread(id, user.id)) {
throw new HttpException({ error: 'Not found' }, 404);
}
return { success: true };
}
@Delete('in-app/:id')
deleteOne(@CurrentUser() user: User, @Param('id') idParam: string): { success: boolean } {
const id = this.parseId(idParam);
if (!this.notifications.deleteOne(id, user.id)) {
throw new HttpException({ error: 'Not found' }, 404);
}
return { success: true };
}
@Post('in-app/:id/respond')
@HttpCode(200)
async respond(
@CurrentUser() user: User,
@Param('id') idParam: string,
@Body() body: NotificationRespondDto,
): Promise<{ success: boolean; notification: unknown }> {
const id = this.parseId(idParam);
const result = await this.notifications.respond(id, user.id, body.response);
if (!result.success) {
throw new HttpException({ error: result.error }, 400);
}
return { success: true, notification: result.notification };
}
/** parseInt + the legacy "Invalid id" 400 guard, shared by the /:id handlers. */
private parseId(idParam: string): number {
const id = Number.parseInt(idParam);
if (isNaN(id)) {
throw new HttpException({ error: 'Invalid id' }, 400);
}
return id;
}
}
/**
* /api/admin/notification-preferences — the admin-scope row of the preference matrix.
*
* Two routes that sat on AdminController and reached NotificationPreferencesService
* through a pair of pass-through methods on AdminService. The owner is here; the
* 'admin' scope argument they always passed is now written once, at the only place
* that uses it.
*/
@Controller('api/admin/notification-preferences')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminNotificationPreferencesController {
constructor(private readonly prefs: NotificationPreferencesService) {}
@Get()
get(@CurrentUser() user: User) {
return this.prefs.getPreferencesMatrix(user.id, user.role, 'admin');
}
@Put()
set(@CurrentUser() user: User, @Body() body: AdminNotificationPreferencesDto) {
this.prefs.setAdminPreferences(user.id, body);
// Answer with the refreshed matrix rather than the raw write result — the admin
// panel renders straight from this response.
return this.prefs.getPreferencesMatrix(user.id, user.role, 'admin');
}
}