fix(api): read body, query and handler-parsed ids with toRowId instead of Number() and parseInt

The services and controllers that took an id from a request with Number(), parseInt() or not at all now use toRowId. That covers admin users, notifications (and their limit and offset), trip members and guests, day notes, assignments, memories (photo owner, album link, body photo_id), photos, mail-ingest, the assistant id parsers, dawarich, registration invites, the plugin contribution routes and the collab reply.

The accommodation update body is open, so AccommodationsService reads the place and day refs of every stay write with toRowId and answers a refused one with the create schema's 400.

AdminService.deleteUser checked the caller with parseInt and deleted with Number(), so an admin could delete their own account by spelling its id in hex; both now use one parse.

The OAuth session revoke called Number(id) first and so revoked session 5 for '0x5'; the service now reads the id as sent.
This commit is contained in:
Maurice
2026-11-18 13:20:06 +01:00
parent 3973741509
commit 6dfba51f21
36 changed files with 242 additions and 112 deletions
@@ -47,7 +47,7 @@ export class AccommodationsController {
) {
const { accommodation, mirror } = await this.accommodations.createStay(
tripId,
rawBody as StayInput,
rawBody,
this.accommodations.restWriter(tripId, user, socketId),
);
// The stop rides in the answer as well, for the session that booked the night
@@ -67,6 +67,7 @@ export class AccommodationsController {
const { accommodation, mirror } = await this.accommodations.updateStay(
tripId,
id,
// The update body is open; the service reads the refs with toRowId and the rest by key.
rawBody as StayInput,
this.accommodations.restWriter(tripId, user, socketId),
);
@@ -92,11 +92,15 @@ export interface DayAccommodation {
notes: string | null;
}
/** The fields a stay write takes from its caller, before the required ones are checked. */
/**
* The fields a stay write takes from its caller, before the required ones are
* checked. The refs are as sent (a number or its digits, or anything at all from
* the open update body); the write reads them with `stayRefs`.
*/
export interface StayInput {
place_id?: number;
start_day_id?: number;
end_day_id?: number;
place_id?: unknown;
start_day_id?: unknown;
end_day_id?: unknown;
check_in?: string | null;
check_in_end?: string | null;
check_out?: string | null;
@@ -106,6 +110,26 @@ export interface StayInput {
const stayNotFound = () => new DomainError(404, 'Accommodation not found', { mcpMessage: 'Accommodation not found.' });
const STAY_REFS = ['place_id', 'start_day_id', 'end_day_id'] as const;
/**
* The place and day refs of a stay write, each read with toRowId; an absent one
* stays absent. A value it refuses ('0x1', '1e0', 1.5) is a 400 in the words the
* create schema answers it with, so the open update body, the MCP tool and the
* plugin RPC refuse it alike instead of binding it, which SQLite matches against
* nothing, Postgres 14 and 15 refuse and 16 and later read as row 1.
*/
function stayRefs(input: StayInput): { place_id?: number; start_day_id?: number; end_day_id?: number } {
const refs: { place_id?: number; start_day_id?: number; end_day_id?: number } = {};
for (const field of STAY_REFS) {
if (input[field] === undefined) continue;
const id = toRowId(input[field]);
if (id === null) throw new DomainError(400, `${field}: Invalid id`);
refs[field] = id;
}
return refs;
}
export interface CreateAccommodationData {
place_id: number;
start_day_id: number;
@@ -248,15 +272,14 @@ export class AccommodationsService {
/** Book a night: the stay, its partner hotel reservation and the day stop it implies. */
async createStay(tripId: string | number, input: StayInput, writer: TripWriter) {
await this.gate(tripId, writer);
const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = input;
if (!place_id || !start_day_id || !end_day_id) {
const { check_in, check_in_end, check_out, confirmation, notes } = input;
if (!input.place_id || !input.start_day_id || !input.end_day_id) {
throw new DomainError(400, 'place_id, start_day_id, and end_day_id are required');
}
await this.requireStayRefs(tripId, place_id, start_day_id, end_day_id);
const refs = stayRefs(input) as Required<ReturnType<typeof stayRefs>>;
await this.requireStayRefs(tripId, refs.place_id, refs.start_day_id, refs.end_day_id);
const result = await this.createAccommodation(tripId, {
place_id,
start_day_id,
end_day_id,
...refs,
check_in,
check_in_end,
check_out,
@@ -294,7 +317,8 @@ export class AccommodationsService {
await this.gate(tripId, writer);
const existing = await this.getAccommodation(id, tripId);
if (!existing) throw stayNotFound();
const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = fields;
const { check_in, check_in_end, check_out, confirmation, notes } = fields;
const { place_id, start_day_id, end_day_id } = stayRefs(fields);
await this.requireStayRefs(tripId, place_id, start_day_id, end_day_id);
const result = await this.updateAccommodation(
id,
+21 -13
View File
@@ -53,6 +53,7 @@ import { DomainError } from '../common/domain-error';
import { MANAGED_FORBIDDEN_ERROR } from '../common/managed';
import { validatePassword } from '../common/passwordPolicy';
import { getPhotoProviderConfig } from '../common/photo-provider-config';
import { toRowId } from '../common/row-id';
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../database/database-backup.interface';
import { UnitOfWork } from '../database/unit-of-work';
import { prepareLlmAddonConfigForWrite, maskLlmAddonConfig } from '../llm-parse/llm-config';
@@ -228,13 +229,14 @@ export class AdminService {
}
async updateUser(id: string, data: { username?: string; email?: string; role?: string; password?: string }) {
const userId = Number(id);
// toRowId, not Number(): '0x2' or '2e0' named user 2.
const userId = toRowId(id);
const username = typeof data.username === 'string' ? data.username.trim() : data.username;
const email = typeof data.email === 'string' ? data.email.trim() : data.email;
const { role, password } = data;
const user = await this.users.findById(userId);
const user = userId === null ? undefined : await this.users.findById(userId);
if (!user) throw new DomainError(404, 'User not found');
if (!user || userId === null) throw new DomainError(404, 'User not found');
if (role && !['user', 'admin'].includes(role)) {
throw new DomainError(400, 'Invalid role');
@@ -348,11 +350,15 @@ export class AdminService {
async deleteUser(id: string, currentUserId: number) {
// SECURITY: plain JS comparison, deliberately kept exactly here — never
// folded into a repository method's WHERE clause (R4).
if (Number.parseInt(id) === currentUserId) {
// One parse for the check and the delete: parseInt('0x2') is 0 where
// Number('0x2') is 2, so the two used to disagree and an admin could
// delete their own account by spelling its id in hex.
const targetId = toRowId(id);
if (targetId === currentUserId) {
throw new DomainError(400, 'Cannot delete own account');
}
const userToDel = await this.users.findIdAndEmail(Number(id));
const userToDel = targetId === null ? undefined : await this.users.findIdAndEmail(targetId);
if (!userToDel) throw new DomainError(404, 'User not found');
await this.userCleanup.deleteUserCompletely(userToDel.id);
@@ -360,8 +366,10 @@ export class AdminService {
return { email: userToDel.email };
}
resetUserPasskeys(id: string) {
return this.passkeys.adminResetPasskeys(Number(id));
async resetUserPasskeys(id: string) {
const userId = toRowId(id);
if (userId === null) throw new DomainError(404, 'User not found');
return this.passkeys.adminResetPasskeys(userId);
}
/**
@@ -378,14 +386,14 @@ export class AdminService {
* way to strip the second factor off the very account it came from.
*/
async resetUserMfa(id: string, actingUserId: number): Promise<{ success?: boolean; email?: string }> {
const targetId = Number(id);
const targetId = toRowId(id);
// SECURITY: plain JS comparison, deliberately kept exactly here — never
// folded into a repository method's WHERE clause (R4).
if (targetId === actingUserId) {
throw new DomainError(400, 'Use Settings to change your own two-factor setup');
}
const target = await this.users.findIdEmailMfaEnabled(targetId);
if (!target) throw new DomainError(404, 'User not found');
const target = targetId === null ? undefined : await this.users.findIdEmailMfaEnabled(targetId);
if (!target || targetId === null) throw new DomainError(404, 'User not found');
// Same three columns disableMfa clears, so an admin reset and a self-service
// disable leave the account in exactly one state rather than two; the
@@ -414,13 +422,13 @@ export class AdminService {
* came from.
*/
async unlinkUserSso(id: string, actingUserId: number): Promise<{ email: string; unlinked: boolean }> {
const targetId = Number(id);
const targetId = toRowId(id);
// SECURITY: plain JS comparison, kept here like resetUserMfa's (R4).
if (targetId === actingUserId) {
throw new DomainError(400, 'You cannot remove the SSO link of your own account');
}
const target = await this.users.findById(targetId);
if (!target || target.is_guest) throw new DomainError(404, 'User not found');
const target = targetId === null ? undefined : await this.users.findById(targetId);
if (!target || target.is_guest || targetId === null) throw new DomainError(404, 'User not found');
if (!target.oidc_sub && !target.oidc_issuer) return { email: target.email, unlinked: false };
await this.users.linkOidcIdentity(targetId, null, null);
@@ -325,8 +325,9 @@ export class AssignmentsService {
*/
async assignmentExistsInDay(id: string | number, dayId: string | number, tripId: string | number) {
const rowId = toRowId(id);
if (rowId === null) return false;
return await this.dayAssignmentsRepo.existsInDay(rowId, dayId, tripId);
const day = toRowId(dayId);
if (rowId === null || day === null) return false;
return await this.dayAssignmentsRepo.existsInDay(rowId, day, tripId);
}
/** AS10 — `DayAssignmentsRepository.deleteById`. */
@@ -7,6 +7,7 @@ import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { readImageHeader } from '../common/image-header';
import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { toRowId } from '../common/row-id';
import { JourneyAiPhotosService } from '../journey/journey-ai-photos.service';
import { AssistantBookContext } from './assistant-book-context';
import { AssistantRenderRegistry } from './assistant-render.registry';
@@ -39,8 +40,9 @@ const UPLOAD = {
/** A positive integer route id, or null. */
function routeId(value: string): number | null {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
// toRowId: Number() read '0x1' and '1e0' as 1.
const id = toRowId(value);
return id !== null && id > 0 ? id : null;
}
/**
@@ -7,6 +7,7 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { toRowId } from '../common/row-id';
import { onClientGone, openSseStream } from '../common/sse-stream';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { AssistantFoundPlacesService } from './assistant-found-places.service';
@@ -36,10 +37,10 @@ import {
import type { Response } from 'express';
/** A route id: a positive integer, or the 404 an unknown one gets. */
/** A route id: a positive integer as toRowId reads it, or the 404 an unknown one gets. */
export function idParam(value: string): number {
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) throw aiRefusal('not_found', 'Conversation not found');
const id = toRowId(value);
if (id === null || id <= 0) throw aiRefusal('not_found', 'Conversation not found');
return id;
}
@@ -68,8 +68,10 @@ export class RegistrationInvitesService {
// trips WHERE id = ?` existence probe.
let tripId: number | null = null;
if (data.trip_id != null && String(data.trip_id).trim() !== '') {
const parsed = Number.parseInt(String(data.trip_id));
if (!Number.isInteger(parsed) || !(await this.trips.existsById(parsed))) {
// toRowId, not parseInt: parseInt('5abc') bound trip 5, and a number past
// 2^53 reached Postgres as an out of range bigint.
const parsed = toRowId(data.trip_id);
if (parsed === null || !(await this.trips.existsById(parsed))) {
// Used to bind null silently, handing back a plain registration invite
// the admin never asked for. Thrown, so the controller writes neither
// the invite nor its audit row and the admin sees the 404.
+4 -2
View File
@@ -4,6 +4,7 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { DEMO_WRITE_ERROR, isDemoWriteBlocked } from '../common/demo-write';
import { ResponseContract } from '../common/response-contract';
import { toRowId } from '../common/row-id';
import { SpoolCleanupInterceptor } from '../common/spool-cleanup.interceptor';
import { BLOCKED_EXTENSIONS, MAX_FILE_SIZE } from '../files/files.constants';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
@@ -534,13 +535,14 @@ export class CollabController {
for (const name of committed) await this.storage.delete('files', name).catch(() => {});
throw err;
}
// The schema took a whole number or its digits; '' is the multipart form's "no reply".
const replyTo =
body.reply_to === undefined || body.reply_to === '' || body.reply_to === null ? null : Number(body.reply_to);
body.reply_to === undefined || body.reply_to === '' || body.reply_to === null ? null : toRowId(body.reply_to);
const result = await this.collab.postMessage(
tripId,
{
text,
replyTo: Number.isFinite(replyTo as number) ? replyTo : null,
replyTo,
files: uploaded.map((file) => ({
filename: file.filename,
originalname: file.originalname,
@@ -4,6 +4,7 @@ import type { DayNotesRepository } from '../../db/repositories/DayNotes.reposito
import type { DaysRepository } from '../../db/repositories/Days.repository';
import type { TripAccess } from '../../db/repositories/Trips.repository';
import type { DayNote, User } from '../../types';
import { toRowId, withRowId } from '../common/row-id';
import { PermissionsService } from '../permissions/permissions.service';
import { RealtimeService } from '../realtime/realtime.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
@@ -67,8 +68,11 @@ export class DayNotesService {
this.realtime.broadcast(tripId, event, payload, socketId);
}
// The route's ids are read through toRowId: a spelling it refuses names no
// day and no note, the same answer on every engine. The writes below only
// run after dayExists or getNote found the row.
async list(dayId: string | number, tripId: string | number) {
return this.dayNotes.listByDayAndTrip(dayId, tripId);
return (await withRowId(dayId, (day) => this.dayNotes.listByDayAndTrip(day, tripId))) ?? [];
}
async dayExists(dayId: string | number, tripId: string | number) {
@@ -76,7 +80,8 @@ export class DayNotesService {
}
async getNote(id: string | number, dayId: string | number, tripId: string | number) {
return this.dayNotes.findByIdDayTrip(id, dayId, tripId);
const day = toRowId(dayId);
return day === null ? undefined : withRowId(id, (note) => this.dayNotes.findByIdDayTrip(note, day, tripId));
}
async create(
@@ -5,6 +5,7 @@ import { RequireAddon } from '../addons/require-addon.decorator';
import { getClientIp } from '../audit/client-ip';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { toRowId } from '../common/row-id';
import { DawarichSuggestionsService, AcceptError } from './dawarich-suggestions.service';
import { DawarichSyncService } from './dawarich-sync.service';
import { DawarichTracksService } from './dawarich-tracks.service';
@@ -267,16 +268,17 @@ function toHttp(err: unknown): HttpException {
/** Ids are integers. `parseInt` would turn "12abc" into 12 and log a request nobody made. */
function parseId(raw: string): number {
if (!/^\d+$/.test(raw)) throw new HttpException({ error: 'Invalid id' }, 400);
const id = Number(raw);
if (!Number.isSafeInteger(id) || id <= 0) throw new HttpException({ error: 'Invalid id' }, 400);
const id = toRowId(raw);
if (id === null || id <= 0) throw new HttpException({ error: 'Invalid id' }, 400);
return id;
}
function parseOptionalId(raw: string | undefined, label: string): number | undefined {
if (raw === undefined || raw === '') return undefined;
if (!/^\d+$/.test(raw)) throw new HttpException({ error: `Invalid ${label}` }, 400);
return Number(raw);
// toRowId: digits alone let a number past 2^53 through, which Postgres refuses as out of range.
const id = toRowId(raw);
if (id === null) throw new HttpException({ error: `Invalid ${label}` }, 400);
return id;
}
/** An unknown state is a 400 rather than a silently unfiltered list. */
@@ -4,6 +4,7 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { DomainError } from '../common/domain-error';
import { ResponseContract } from '../common/response-contract';
import { toRowId } from '../common/row-id';
import { MailIngestActionsService } from './mail-ingest-actions.service';
import { MailIngestInboxService } from './mail-ingest-inbox.service';
import { MAIL_INGEST_LIMITS } from './mail-ingest.constants';
@@ -30,7 +31,6 @@ import {
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
idParamSchema,
mailIngestAddressResponseSchema,
mailIngestCandidateResponseSchema,
mailIngestInboxCountResponseSchema,
@@ -199,9 +199,10 @@ export class MailIngestController {
/** An id from the path; one that is no id names nothing, like an id nobody holds. */
function idOf(raw: string, missing: string): number {
const parsed = idParamSchema.safeParse(raw);
if (!parsed.success) throw new DomainError(404, missing);
return parsed.data;
// toRowId, not a coercing schema: Number() reads '0x1', '1e0' and '+1' as id 1.
const id = toRowId(raw);
if (id === null || id <= 0) throw new DomainError(404, missing);
return id;
}
function entryId(raw: string): number {
@@ -111,7 +111,7 @@ export class ImmichMemoriesController {
res.status(400).json({ error: 'Invalid asset ID' });
return;
}
if (!(await this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, assetId, 'immich'))) {
if (!(await this.memories.canAccessUserPhoto(user.id, ownerId, tripId, assetId, 'immich'))) {
res.status(403).json({ error: 'Forbidden' });
return;
}
@@ -135,7 +135,7 @@ export class ImmichMemoriesController {
res.status(400).json({ error: 'Invalid asset ID' });
return;
}
if (!(await this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, assetId, 'immich'))) {
if (!(await this.memories.canAccessUserPhoto(user.id, ownerId, tripId, assetId, 'immich'))) {
res.status(403).json({ error: 'Forbidden' });
return;
}
@@ -154,7 +154,7 @@ export class ImmichMemoriesController {
res.status(400).json({ error: 'Invalid asset ID' });
return;
}
if (!(await this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, assetId, 'immich'))) {
if (!(await this.memories.canAccessUserPhoto(user.id, ownerId, tripId, assetId, 'immich'))) {
res.status(403).json({ error: 'Forbidden' });
return;
}
@@ -60,13 +60,20 @@ export class MemoriesAccessService {
return await this.journeyContributors.hasAccess(journeyId, userId);
}
/**
* `owner` is the route's `:ownerId` as it came: read through toRowId, so a
* spelling it refuses ('0x2', '2e0') is nobody's photo rather than the
* caller's own through Number().
*/
async canAccessUserPhoto(
requestingUserId: number,
ownerUserId: number,
owner: number | string,
tripId: string,
assetId: string,
provider: string,
): Promise<boolean> {
const ownerUserId = toRowId(owner);
if (ownerUserId === null) return false;
if (requestingUserId === ownerUserId) {
return true;
}
+3 -3
View File
@@ -28,7 +28,7 @@ export class MemoriesService {
// ── Access check (reused by both provider asset routes) ──────────────────
canAccessUserPhoto(
requestingUserId: number,
ownerUserId: number,
ownerUserId: number | string,
tripId: string,
assetId: string,
provider: string,
@@ -54,11 +54,11 @@ export class MemoriesService {
return this.unified.addTripPhotos(tripId, userId, shared, selections, sid);
}
setTripPhotoSharing(tripId: string, userId: number, photoId: number, shared: boolean) {
setTripPhotoSharing(tripId: string, userId: number, photoId: number | null, shared: boolean) {
return this.unified.setTripPhotoSharing(tripId, userId, photoId, shared);
}
removeTripPhoto(tripId: string, userId: number, photoId: number) {
removeTripPhoto(tripId: string, userId: number, photoId: number | null) {
return this.unified.removeTripPhoto(tripId, userId, photoId);
}
@@ -189,7 +189,7 @@ export class SynologyMemoriesController {
@Res() res: Response,
): Promise<void> {
const passphrase = passphraseRaw ? String(passphraseRaw) : undefined;
if (!(await this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, photoId, 'synologyphotos'))) {
if (!(await this.memories.canAccessUserPhoto(user.id, ownerId, tripId, photoId, 'synologyphotos'))) {
this.handle(res, fail("You don't have access to this photo", 403));
} else {
this.handle(res, await this.memories.synologyGetAssetInfo(user.id, photoId, Number(ownerId), passphrase));
@@ -217,7 +217,7 @@ export class SynologyMemoriesController {
return;
}
if (!(await this.memories.canAccessUserPhoto(user.id, Number(ownerId), tripId, photoId, 'synologyphotos'))) {
if (!(await this.memories.canAccessUserPhoto(user.id, ownerId, tripId, photoId, 'synologyphotos'))) {
this.handle(res, fail("You don't have access to this photo", 403));
} else {
await this.memories.synologyStreamAsset(res, user.id, Number(ownerId), photoId, kind, String(size), passphrase);
@@ -11,6 +11,7 @@ import type { TripsRepository } from '../../db/repositories/Trips.repository';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { AddonsService } from '../addons/addons.service';
import { encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { NotificationsService } from '../notifications/notifications.service';
import { TrekPhotoRegistrationService } from '../photos/trek-photo-registration.service';
@@ -202,7 +203,7 @@ export class UnifiedMemoriesService {
async setTripPhotoSharing(
tripId: string,
userId: number,
photoId: number,
photoId: number | null,
shared: boolean,
sid?: string,
): Promise<ServiceResult<true>> {
@@ -210,6 +211,8 @@ export class UnifiedMemoriesService {
if (!access) {
return fail('Trip not found or access denied', 404);
}
// null: the caller's toRowId refused the body's photo id.
if (photoId === null) return fail('Invalid photo_id', 400);
try {
await this.tripPhotos.setShared(tripId, userId, photoId, shared ? 1 : 0);
@@ -222,11 +225,17 @@ export class UnifiedMemoriesService {
}
}
async removeTripPhoto(tripId: string, userId: number, photoId: number, sid?: string): Promise<ServiceResult<true>> {
async removeTripPhoto(
tripId: string,
userId: number,
photoId: number | null,
sid?: string,
): Promise<ServiceResult<true>> {
const access = await this.trips.findAccessible(tripId, userId);
if (!access) {
return fail('Trip not found or access denied', 404);
}
if (photoId === null) return fail('Invalid photo_id', 400);
try {
await this.uow.transactional(async () => {
@@ -299,13 +308,17 @@ export class UnifiedMemoriesService {
if (!access) {
return fail('Trip not found or access denied', 404);
}
// A link id toRowId refuses names no link, so there is nothing to remove,
// as for an id no link has; bound raw, Postgres refused it with an error.
const link = toRowId(linkId);
if (link === null) return success(true);
try {
const linkedPhotoIds = await this.tripPhotos.listPhotoIdsForAlbumLink(tripId, linkId);
const linkedPhotoIds = await this.tripPhotos.listPhotoIdsForAlbumLink(tripId, link);
await this.uow.transactional(async () => {
await this.tripPhotos.deleteForAlbumLink(tripId, linkId);
await this.tripAlbumLinks.deleteScoped(linkId, tripId, userId);
await this.tripPhotos.deleteForAlbumLink(tripId, link);
await this.tripAlbumLinks.deleteScoped(link, tripId, userId);
for (const photo_id of linkedPhotoIds) await this.photos.deleteIfOrphan(photo_id);
});
@@ -1,6 +1,7 @@
import type { User } from '../../types';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { toRowId } from '../common/row-id';
import { AddTripPhotosDto, CreateAlbumLinkDto, RemoveTripPhotoDto, SetTripPhotoSharingDto } from './memories.dto';
import type { Selection } from './memories.helpers';
import { MemoriesService } from './memories.service';
@@ -58,10 +59,11 @@ export class UnifiedMemoriesController {
@Body() body: SetTripPhotoSharingDto,
@Res() res: Response,
): Promise<void> {
// toRowId, not Number(): '0x1' and '1e0' named photo 1 and NaN reached SQL, which Postgres refused.
const result = await this.memories.setTripPhotoSharing(
tripId,
user.id,
Number(body?.photo_id),
toRowId(body?.photo_id),
body?.shared as boolean,
);
if ('error' in result) {
@@ -78,7 +80,7 @@ export class UnifiedMemoriesController {
@Body() body: RemoveTripPhotoDto,
@Res() res: Response,
): Promise<void> {
const result = await this.memories.removeTripPhoto(tripId, user.id, Number(body?.photo_id));
const result = await this.memories.removeTripPhoto(tripId, user.id, toRowId(body?.photo_id));
if ('error' in result) {
res.status(result.error.status).json({ error: result.error.message });
return;
@@ -3,6 +3,7 @@ import { AdminGuard } from '../auth-core/admin.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ManagedForbidden } from '../common/managed';
import { toRowId } from '../common/row-id';
import { NotificationPreferencesService } from './notification-preferences.service';
import {
PreferencesUpdateDto,
@@ -138,8 +139,9 @@ export class NotificationsController {
@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,
// toRowId, not parseInt: a negative LIMIT or OFFSET is no limit on SQLite and an error on Postgres.
limit: Math.min(toRowId(limit) || 20, 50),
offset: toRowId(offset) ?? 0,
unreadOnly: unreadOnly === 'true',
});
}
@@ -212,10 +214,10 @@ export class NotificationsController {
return { success: true, notification: result.notification };
}
/** parseInt + the legacy "Invalid id" 400 guard, shared by the /:id handlers. */
/** toRowId + the legacy "Invalid id" 400 guard, shared by the /:id handlers. parseInt read '1e0' as 1. */
private parseId(idParam: string): number {
const id = Number.parseInt(idParam);
if (Number.isNaN(id)) {
const id = toRowId(idParam);
if (id === null) {
throw new HttpException({ error: 'Invalid id' }, 400);
}
return id;
@@ -212,7 +212,7 @@ export class OauthApiController {
async revokeSession(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
await this.requireMcp403();
refuseForDemoAccount(user, DEMO_ACCOUNT_REFUSAL.mcp);
const result = await this.oauth.revokeSession(user.id, Number(id), getClientIp(req));
const result = await this.oauth.revokeSession(user.id, id, getClientIp(req));
if (result.error) {
throw new HttpException({ error: result.error }, result.status || 400);
}
+3 -7
View File
@@ -697,15 +697,11 @@ export class OauthService {
async revokeSession(
userId: number,
sessionId: number,
sessionId: number | string,
ip?: string | null,
): Promise<{ error?: string; status?: number; success?: boolean }> {
// `sessionId` is already a `number` here — `oauth-api.controller.ts`'s
// `DELETE /api/oauth/sessions/:id` calls `Number(id)` before this method
// (byte-identical to the legacy route), so `toRowId` only guards against
// `NaN`/a non-safe-integer, never narrows a string shape (Task 7 review,
// B-I2/A-M2's "pre-coerced Number() seam" — see `row-id.ts`'s own
// docstring). This is full parity, not the accepted-narrowing shape.
// The path id as sent: Number() read '0x5' and '5e0' as session 5, so the
// route revoked a session by a spelling every other route answers 404 for.
const id = toRowId(sessionId);
if (id === null) return { error: 'Session not found', status: 404 };
+5 -3
View File
@@ -1,6 +1,7 @@
import type { User } from '../../types';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { toRowId } from '../common/row-id';
import { PhotosService } from './photos.service';
import { Controller, Get, Headers, HttpException, Param, Res, UseGuards } from '@nestjs/common';
@@ -12,7 +13,7 @@ import type { Response } from 'express';
* to the response via the resolver service.
*
* Byte-identical to the legacy Express route (server/src/routes/photos.ts):
* a finite-id guard (400), the canAccessTrekPhoto check (403), then stream or
* a row-id guard (400), the canAccessTrekPhoto check (403), then stream or
* the provider info (404 inside the service / mapped error for info).
*/
@Controller('api/photos')
@@ -21,8 +22,9 @@ export class PhotosController {
constructor(private readonly photos: PhotosService) {}
private async requireAccess(user: User, rawId: string): Promise<number> {
const photoId = Number(rawId);
if (!Number.isFinite(photoId)) {
// toRowId: Number() read '0x1' and '1e0' as photo 1, and 1e20 reached Postgres as an out of range bigint.
const photoId = toRowId(rawId);
if (photoId === null) {
throw new HttpException({ error: 'Invalid photo ID' }, 400);
}
if (!(await this.photos.canAccess(user.id, photoId))) {
@@ -1,6 +1,7 @@
import { Days } from '../../../db/entities/Days.entity';
import type { DaysRepository } from '../../../db/repositories/Days.repository';
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -96,10 +97,9 @@ export class DayScheduleController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ items: DayScheduleItem[] }> {
if (!pluginsEnabled()) return { items: [] };
const tripId = Number(tripIdRaw);
const tripId = toRowId(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
return { items: [] };
if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { items: [] };
const ids = this.hooks.providersOf('dayScheduleProvider');
if (ids.length === 0) return { items: [] };
@@ -1,6 +1,7 @@
import { Days } from '../../../db/entities/Days.entity';
import type { DaysRepository } from '../../../db/repositories/Days.repository';
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -174,10 +175,9 @@ export class DayTintsController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ tints: DayTint[] }> {
if (!pluginsEnabled()) return { tints: [] };
const tripId = Number(tripIdRaw);
const tripId = toRowId(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
return { tints: [] };
if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { tints: [] };
const ids = this.hooks.providersOf('dayTintProvider');
if (ids.length === 0) return { tints: [] };
@@ -3,6 +3,7 @@ import { JourneyEntries } from '../../../db/entities/JourneyEntries.entity';
import type { JourneyEntriesRepository } from '../../../db/repositories/JourneyEntries.repository';
import { AddonsService } from '../../addons/addons.service';
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { JourneyDomainService } from '../../journey/journey-domain.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -91,9 +92,9 @@ export class JournalEntryRowsController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ providers: ProviderResult[] }> {
if (!pluginsEnabled() || !(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) return { providers: [] };
const entryId = Number(entryIdRaw);
const entryId = toRowId(entryIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(entryId) || userId == null) return { providers: [] };
if (entryId === null || userId == null) return { providers: [] };
// The entry's journey must be one the caller can access — same gate as a read.
const row = await this.journeyEntries.findById(entryId); // JEC1 — converted (Plan 3g Task 4)
@@ -1,4 +1,5 @@
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -159,10 +160,9 @@ export class MapLayersController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ layers: MapLayer[] }> {
if (!pluginsEnabled()) return { layers: [] };
const tripId = Number(tripIdRaw);
const tripId = toRowId(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
return { layers: [] };
if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { layers: [] };
const ids = this.hooks.providersOf('mapLayerProvider');
const perProvider = await Promise.all(
@@ -1,4 +1,5 @@
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -93,10 +94,9 @@ export class MapMarkersController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ markers: MapMarker[] }> {
if (!pluginsEnabled()) return { markers: [] };
const tripId = Number(tripIdRaw);
const tripId = toRowId(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
return { markers: [] };
if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId))) return { markers: [] };
const ids = this.hooks.providersOf('mapMarkerProvider');
const perProvider = await Promise.all(
@@ -1,4 +1,5 @@
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -88,9 +89,9 @@ export class PdfSectionsController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ sections: PdfSection[] }> {
if (!pluginsEnabled()) return { sections: [] };
const tripId = Number(tripIdRaw);
const tripId = toRowId(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId)))
return { sections: [] };
const ids = this.hooks.providersOf('pdfSectionProvider');
@@ -1,6 +1,7 @@
import { Places } from '../../../db/entities/Places.entity';
import type { PlacesRepository } from '../../../db/repositories/Places.repository';
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -80,9 +81,9 @@ export class PlaceDetailsController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ providers: ProviderResult[] }> {
if (!pluginsEnabled()) return { providers: [] };
const placeId = Number(placeIdRaw);
const placeId = toRowId(placeIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(placeId) || userId == null) return { providers: [] };
if (placeId === null || userId == null) return { providers: [] };
// The place must belong to a trip the caller can access — same gate as a read.
const tripId = await this.places.findTripId(placeId); // CT7 — Plan 3j
@@ -1,6 +1,7 @@
import { Plugins } from '../../../db/entities/Plugins.entity';
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -50,9 +51,8 @@ export class PluginRoutesController {
): Promise<{ route: PluginRouteOut | null }> {
if (!pluginsEnabled()) return { route: null };
const userId = req.user?.id;
const tripId = Number(body?.tripId);
if (userId == null || !Number.isFinite(tripId) || !(await this.trips.findAccessible(tripId, userId)))
return { route: null };
const tripId = toRowId(body?.tripId);
if (userId == null || tripId === null || !(await this.trips.findAccessible(tripId, userId))) return { route: null };
if (!PROFILE_RE.test(profileId)) return { route: null };
const waypoints = readWaypoints(body?.waypoints);
if (!waypoints) return { route: null };
@@ -1,4 +1,5 @@
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -110,8 +111,8 @@ export class TripCardContributionsController {
// are handed to any plugin.
const requested = (tripIdsRaw ?? '')
.split(',')
.map((s) => Number(s.trim()))
.filter((n) => Number.isInteger(n) && n > 0)
.map((s) => toRowId(s.trim()))
.filter((n): n is number => n !== null && n > 0)
.slice(0, MAX_TRIP_IDS);
const uniqueRequested = [...new Set(requested)];
// Sequential, not `Promise.all` (Plan 3c Task 0b, task-0a-review-security.md
@@ -1,4 +1,5 @@
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -39,9 +40,9 @@ export class TripWarningsController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ warnings: Warning[] }> {
if (!pluginsEnabled()) return { warnings: [] };
const tripId = Number(tripIdRaw);
const tripId = toRowId(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId)))
return { warnings: [] };
const ids = this.hooks.providersOf('warningProvider');
@@ -1,4 +1,5 @@
import { JwtAuthGuard } from '../../auth-core/jwt-auth.guard';
import { toRowId } from '../../common/row-id';
import { TripAccessService } from '../../trip-membership/trip-access.service';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
@@ -148,9 +149,9 @@ export class ViewContributionsController {
@Req() req: Request & { user?: { id: number } },
): Promise<{ contributions: Contribution[] }> {
if (!pluginsEnabled() || !VIEWS.has(view)) return { contributions: [] };
const tripId = Number(tripIdRaw);
const tripId = toRowId(tripIdRaw);
const userId = req.user?.id;
if (!Number.isFinite(tripId) || userId == null || !(await this.trips.findAccessible(tripId, userId)))
if (tripId === null || userId == null || !(await this.trips.findAccessible(tripId, userId)))
return { contributions: [] };
const ids = this.hooks.providersOf('tableContributor');
@@ -111,14 +111,16 @@ export class TripMembersController {
if (!access) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
const targetId = Number.parseInt(userId);
// A user id toRowId refuses names nobody, so it removes nobody, like an id no member holds.
const targetId = toRowId(userId);
if (
targetId !== user.id &&
!(await this.roster.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id))
) {
throw new HttpException({ error: 'No permission to remove members' }, 403);
}
await this.writes.removeMember(tripId, targetId, this.writes.restWriter(tripId, user, socketId));
if (targetId !== null)
await this.writes.removeMember(tripId, targetId, this.writes.restWriter(tripId, user, socketId));
return { success: true };
}
@@ -185,7 +187,8 @@ export class TripMembersController {
) {
try {
const writer = this.writes.restWriter(id, user, socketId);
if (!(await this.writes.renameGuest(id, Number.parseInt(userId), body.name, writer))) {
const guestId = toRowId(userId);
if (guestId === null || !(await this.writes.renameGuest(id, guestId, body.name, writer))) {
throw new HttpException({ error: 'Guest not found' }, 404);
}
return { success: true };
@@ -206,7 +209,8 @@ export class TripMembersController {
@Headers('x-socket-id') socketId?: string,
) {
const writer = this.writes.restWriter(id, user, socketId);
if (!(await this.writes.deleteGuest(id, Number.parseInt(userId), writer))) {
const guestId = toRowId(userId);
if (guestId === null || !(await this.writes.deleteGuest(id, guestId, writer))) {
throw new HttpException({ error: 'Guest not found' }, 404);
}
return { success: true };
+37
View File
@@ -12,6 +12,7 @@ import { OauthService } from '../../src/nest/oauth/oauth.service';
import { authCookie } from '../helpers/auth';
import { updateRows, upsertRow } from '../helpers/factories/rows';
import { makeUser } from '../helpers/factories/users';
import { oneByOne } from '../helpers/one-by-one';
import { resetDatabase } from '../helpers/reset-database';
import { resetRateLimits } from '../helpers/test-db';
import { MikroORM } from '@mikro-orm/core';
@@ -1100,6 +1101,42 @@ describe('Sessions — /api/oauth/sessions', () => {
expect(res.body).toEqual({ error: 'Session not found' });
});
it('OAUTH-043C: DELETE /sessions/:id by a hex or exponent spelling of a real session id is 404 and revokes nothing', async () => {
const { user } = await makeUser(orm);
const { client } = await createOAuthClient(user.id, 'App', ['https://app.example.com/cb'], ['trips:read']);
if (!client) throw new Error('the OAuth client was not created');
const { verifier, challenge } = makePkce();
const code = await createAuthCode({
clientId: client.client_id as string,
userId: user.id,
redirectUri: 'https://app.example.com/cb',
scopes: ['trips:read'],
codeChallenge: challenge,
codeChallengeMethod: 'S256',
resource: null,
});
await request(app).post('/oauth/token').send({
grant_type: 'authorization_code',
client_id: client.client_id,
client_secret: client.client_secret,
code,
redirect_uri: 'https://app.example.com/cb',
code_verifier: verifier,
});
const sessionId = (await request(app).get('/api/oauth/sessions').set('Cookie', authCookie(user.id))).body
.sessions[0].id as number;
// Number() read both as the session itself, so this route revoked it where every other answers 404.
const spellings = [`0x${sessionId.toString(16)}`, `${sessionId}e0`];
const answers = await oneByOne(spellings, async (spelling) => {
const res = await request(app).delete(`/api/oauth/sessions/${spelling}`).set('Cookie', authCookie(user.id));
return [res.status, res.body as unknown];
});
expect(answers).toEqual(spellings.map(() => [404, { error: 'Session not found' }]));
const after = await request(app).get('/api/oauth/sessions').set('Cookie', authCookie(user.id));
expect(after.body.sessions).toHaveLength(1);
});
it('OAUTH-044 — DELETE /sessions/:id returns 403 when addon disabled', async () => {
await setMcpEnabled(false);
const { user } = await makeUser(orm);
@@ -432,6 +432,18 @@ describe('deleteUser', () => {
const result = (await deleteUser('99999', admin.id)) as any;
expect(result.status).toBe(404);
});
it('ADMIN-SVC-017B: an id spelled in hex or with an exponent names no user, so an admin cannot delete their own account that way', async () => {
const { user: admin } = createAdmin(testDb);
// parseInt('0x..') was 0 for the self check while Number() reached the admin's own row.
const spellings = [`0x${admin.id.toString(16)}`, `${admin.id}e0`];
const results = (await Promise.all(spellings.map((spelling) => deleteUser(spelling, admin.id)))) as Array<{
status?: number;
}>;
expect(results.map((r) => r.status)).toEqual([404, 404]);
const kept = (await deleteUser(String(admin.id), admin.id)) as { status?: number };
expect(kept.status).toBe(400);
});
});
// ── getStats ──────────────────────────────────────────────────────────────────
@@ -452,7 +452,7 @@ describe('ImmichMemoriesController (parity with /api/integrations/memories/immic
});
const res = makeRes();
await new ImmichMemoriesController(svc).assetInfo(user, '5', 'a', '2', res);
expect(svc.canAccessUserPhoto).toHaveBeenCalledWith(7, 2, '5', 'a', 'immich');
expect(svc.canAccessUserPhoto).toHaveBeenCalledWith(7, '2', '5', 'a', 'immich');
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith({ error: 'Forbidden' });
});
@@ -850,7 +850,7 @@ describe('SynologyMemoriesController (parity with /api/integrations/memories/syn
const svc = makeService({ canAccessUserPhoto: vi.fn().mockReturnValue(false) });
const res = makeRes();
await new SynologyMemoriesController(svc).assetInfo(user, '5', 'p1', '2', undefined, res);
expect(svc.canAccessUserPhoto).toHaveBeenCalledWith(7, 2, '5', 'p1', 'synologyphotos');
expect(svc.canAccessUserPhoto).toHaveBeenCalledWith(7, '2', '5', 'p1', 'synologyphotos');
expect(res.status).toHaveBeenCalledWith(403);
expect(res.json).toHaveBeenCalledWith({ error: "You don't have access to this photo" });
});