Finish the contract ratchet, the upload bridge and the client leftovers

BODY_CONTRACT_ALLOW_LIST is empty. The last seventeen handlers type their
body with a createZodDto class, so the fail-closed boot gate has nothing left
to forgive; it still refuses a boot for a new handler that reads @Body()
without one.

Several of those contracts describe rather than constrain, and that is the
whole care in this change. The pipe runs before the handler, so a schema
stricter than the handler moves a user-visible answer:

- TagsController.create answers { error: 'Tag name is required' }, pinned
  byte-for-byte in two tests, and the pipe formats as `field: message`. The
  DTO leaves name optional and the handler keeps the check that owns the
  message. Same shape for the booking-import confirm body, which additionally
  gains per-item validation the handler never did.
- PluginsController.activate and install answer 503 when plugins are disabled,
  and check that BEFORE looking at the body. A schema that rejected first
  would turn that into a 400 for an operator whose server has plugins off.
- setEgressHosts reads a non-array `hosts` as "clear the list", which is the
  documented reset. Typing it as string[] would have removed a working admin
  action rather than tightened anything.
- PluginRoutesController.route answers { route: null } at 200 for everything
  it dislikes, so the client falls back to straight lines. A 400 there would
  turn a graceful degradation into a visible error.

files.bridge is gone. The multer options are built by
MulterModule.registerAsync from an AllowedFileTypesService leaf, so the
fileFilter reads the operator's extension list from the container instead of
from a second FilesService built outside it. Nest injects
MULTER_MODULE_OPTIONS with @Optional(), so a token that fails to resolve is
not a boot error: it silently falls back to defaults, with no filter and no
size cap. FILE-020 already proved that for trip files by uploading an .svg
over HTTP and expecting 400; journey uploads had no such case, and now do.
VIDEO_UPLOAD is untouched, including the filename callback that forces .jpg
regardless of what the client sends, which guards the public share proxy.

PluginFrame gets an onError. A frame whose document fails to load left a
blank element at full height, which reads as a hung app rather than as a
plugin that is gone.

typecheck:tests runs in CI now, with the test tree at zero errors. tz-lookup
is left as it is: the build puts it in a lazy helpers chunk, not the entry
chunk, and the remaining split would trade a synchronous render for an async
one to move 172 kB that is already off the critical path.
This commit is contained in:
Maurice
2026-08-10 19:35:47 +02:00
committed by Maurice
parent 7078ac7a4d
commit ba7d55f999
74 changed files with 620 additions and 196 deletions
@@ -3,26 +3,16 @@
* class — grandfathered when the fail-closed boot gate landed
* (validate-body-contracts.ts). Entries are `ControllerClass.methodName`.
*
* RATCHET ONLY: never add an entry. When a domain migrates, wrap its
* @trek/shared schema in a colocated <domain>.dto.ts and DELETE the routes
* here — the gate throws on stale entries, so removal is enforced too.
* EMPTY, and it stays that way. Every mutation handler in the tree now types
* its body with a createZodDto class, so the gate has nothing to forgive. It
* still runs: a new handler that reads @Body() without a contract refuses the
* boot rather than shipping unvalidated. Adding an entry here to get past that
* is not the fix.
*
* The last seventeen came off in the migration remainder. Several of their
* contracts describe rather than constrain, which is deliberate and documented
* at each DTO: those handlers own rejections the pipe would otherwise pre-empt,
* including two that answer 503 before ever looking at the body and one that
* answers `{ route: null }` at 200 for anything it dislikes.
*/
export const BODY_CONTRACT_ALLOW_LIST: string[] = [
'LlmLocalController.pull',
'OauthApiController.authorize',
'OauthApiController.createClient',
'PluginRoutesController.route',
'PluginUserSettingsController.update',
'PluginsController.activate',
'PluginsController.install',
'PluginsController.link',
'PluginsController.retrust',
'PluginsController.setEgressHosts',
'PluginsController.uninstall',
'PluginsController.updateConfig',
'ReservationImportController.confirm',
'ReservationImportController.preview',
'ReservationImportController.previewAsync',
'TagsController.create',
'TagsController.update',
];
export const BODY_CONTRACT_ALLOW_LIST: string[] = [];
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { AllowedFileTypesService } from './allowed-file-types.service';
/**
* A leaf so both upload paths can reach the extension list without importing
* each other's domain. DatabaseModule is @Global, so this imports nothing.
*/
@Module({
providers: [AllowedFileTypesService],
exports: [AllowedFileTypesService],
})
export class AllowedFileTypesModule {}
@@ -0,0 +1,29 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { DEFAULT_ALLOWED_EXTENSIONS } from './files.constants';
/**
* The operator's allowed-extension list, on its own.
*
* Split out of FilesService so the multer factories can inject it without
* pulling the whole files domain into JourneyModule's injector. It is the only
* thing an upload's fileFilter needs from the container, and it is a live read:
* an admin changing the list in settings applies to the next upload, with no
* invalidation wiring.
*/
@Injectable()
export class AllowedFileTypesService {
constructor(private readonly db: DatabaseService) {}
/** Comma-separated, as the admin panel stores it. `*` means anything. */
get(): string {
try {
const row = this.db.get<{ value: string }>(
"SELECT value FROM app_settings WHERE key = 'allowed_file_types'",
);
return row?.value || DEFAULT_ALLOWED_EXTENSIONS;
} catch {
return DEFAULT_ALLOWED_EXTENSIONS;
}
}
}
-24
View File
@@ -1,24 +0,0 @@
import { db } from '../../db/database';
import { DatabaseService } from '../database/database.service';
import { RealtimeService } from '../realtime/realtime.service';
import { FilesService } from './files.service';
import { PermissionsService } from '../permissions/permissions.service';
import { EphemeralTokenService } from '../auth/ephemeral-token.service';
/**
* Non-Nest entry point for the files domain. Unlike todo.bridge.ts this does
* NOT serve a legacy MCP registrar (files has no MCP surface) — it exists only
* because multer interceptor options are module-scope object literals (the
* UPLOAD configs in files.controller.ts and journey.controller.ts are built
* before any DI container exists), yet their fileFilter closures need the
* request-time app_settings read. Everything else injects FilesService.
* Delete this file if uploads ever move to MulterModule.registerAsync.
*
* Module-level construction is safe: `db` is the reinitialize-proof Proxy onto
* the shared better-sqlite3 singleton.
*/
const files = new FilesService(new DatabaseService(db), new PermissionsService(new DatabaseService(db)), new RealtimeService(), new EphemeralTokenService());
export function getAllowedExtensions(): string {
return files.getAllowedExtensions();
}
+38 -27
View File
@@ -30,34 +30,45 @@ import { TripAccessGuard } from '../permissions/trip-access.guard';
import type { TripAccess } from '../database/database.service';
import { Trip } from '../permissions/trip.decorator';
import { MAX_FILE_SIZE, MAX_VIDEO_SIZE, BLOCKED_EXTENSIONS, filesDir, isVideoExtension } from './files.constants';
import { getAllowedExtensions } from './files.bridge';
import { FileUploadDto, FileUpdateDto, FileLinkDto } from './files.dto';
import { AllowedFileTypesService } from './allowed-file-types.service';
const UPLOAD = {
storage: diskStorage({
destination: (_req, _file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir); },
filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`),
}),
// Allow up to the video cap; non-video files are still held to MAX_FILE_SIZE by
// the per-type guard in the upload handler (#823).
limits: { fileSize: MAX_VIDEO_SIZE },
defParamCharset: 'utf8', // parity with legacy routes/files.ts — preserve non-ASCII original filenames
fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
const ext = path.extname(file.originalname).toLowerCase();
const reject = () => {
// i18n key — the client resolves it via t() (see translateApiError).
const err: Error & { statusCode?: number } = new Error('files.uploadErrorType');
err.statusCode = 400;
cb(err, false);
};
if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg')) return reject();
const allowed = getAllowedExtensions().split(',').map((e) => e.trim().toLowerCase());
const fileExt = ext.replace('.', '');
// Video is accepted as media regardless of the admin doc-types allowlist (#823).
if (allowed.includes(fileExt) || isVideoExtension(fileExt) || (allowed.includes('*') && !BLOCKED_EXTENSIONS.includes(ext))) return cb(null, true);
reject();
},
};
/**
* Trip-file upload options, built from the container.
*
* A factory rather than a module-scope literal because the fileFilter reads the
* operator's allowed-extension list at request time, and that list lives in the
* database. It used to reach it through files.bridge.ts, which built a second
* FilesService outside the injector; MulterModule.registerAsync gives the
* closure the real one.
*/
export function buildFilesUploadOptions(allowedTypes: AllowedFileTypesService) {
return {
storage: diskStorage({
destination: (_req, _file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir); },
filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`),
}),
// Allow up to the video cap; non-video files are still held to MAX_FILE_SIZE by
// the per-type guard in the upload handler (#823).
limits: { fileSize: MAX_VIDEO_SIZE },
defParamCharset: 'utf8', // parity with legacy routes/files.ts — preserve non-ASCII original filenames
fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
const ext = path.extname(file.originalname).toLowerCase();
const reject = () => {
// i18n key — the client resolves it via t() (see translateApiError).
const err: Error & { statusCode?: number } = new Error('files.uploadErrorType');
err.statusCode = 400;
cb(err, false);
};
if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg')) return reject();
const allowed = allowedTypes.get().split(',').map((e) => e.trim().toLowerCase());
const fileExt = ext.replace('.', '');
// Video is accepted as media regardless of the admin doc-types allowlist (#823).
if (allowed.includes(fileExt) || isVideoExtension(fileExt) || (allowed.includes('*') && !BLOCKED_EXTENSIONS.includes(ext))) return cb(null, true);
reject();
},
};
}
/**
* /api/trips/:tripId/files — trip file manager (upload, metadata, starring,
@@ -105,7 +116,7 @@ export class FilesController {
}
@Post()
@UseInterceptors(FileInterceptor('file', UPLOAD))
@UseInterceptors(FileInterceptor('file'))
upload(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
+11 -1
View File
@@ -8,9 +8,19 @@ import { RealtimeModule } from '../realtime/realtime.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { AppConfigModule } from '../app-config/app-config.module';
import { EphemeralTokenModule } from '../auth/ephemeral-token.module';
import { MulterModule } from '@nestjs/platform-express';
import { AllowedFileTypesModule } from './allowed-file-types.module';
import { AllowedFileTypesService } from './allowed-file-types.service';
import { buildFilesUploadOptions } from './files.controller';
@Module({
imports: [EphemeralTokenModule, PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule],
imports: [
MulterModule.registerAsync({
imports: [AllowedFileTypesModule],
inject: [AllowedFileTypesService],
useFactory: (allowedTypes: AllowedFileTypesService) => buildFilesUploadOptions(allowedTypes),
}),
EphemeralTokenModule, PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule],
controllers: [FilesController, FilesDownloadController],
providers: [FilesService, FilesRpc],
exports: [FilesService],
+36 -26
View File
@@ -34,31 +34,41 @@ import {
JourneyReorderEntriesDto, JourneyShareLinkDto, JourneyUpdateDto,
} from './journey.dto';
import { isVideoMime, isVideoExtension, MAX_VIDEO_SIZE } from '../files/files.constants';
import { getAllowedExtensions } from '../files/files.bridge';
import { AllowedFileTypesService } from '../files/allowed-file-types.service';
const uploadsBase = path.join(__dirname, '../../../uploads/journey');
const IMAGE_UPLOAD = {
storage: diskStorage({
destination: (_req, _file, cb) => { if (!fs.existsSync(uploadsBase)) fs.mkdirSync(uploadsBase, { recursive: true }); cb(null, uploadsBase); },
filename: (_req, file, cb) => cb(null, `${crypto.randomUUID()}${path.extname(file.originalname).toLowerCase() || '.jpg'}`),
}),
limits: { fileSize: 20 * 1024 * 1024 },
fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
if (!file.mimetype.startsWith('image/') || file.mimetype.includes('svg')) {
const err: Error & { statusCode?: number } = new Error('Only image files are allowed');
err.statusCode = 400;
return cb(err, false);
}
const ext = path.extname(file.originalname).toLowerCase().replace('.', '');
const allowed = getAllowedExtensions().split(',').map((e) => e.trim().toLowerCase());
if (!allowed.includes('*') && !allowed.includes(ext)) {
const err: Error & { statusCode?: number } = new Error(`File type .${ext} is not allowed`);
err.statusCode = 400;
return cb(err, false);
}
cb(null, true);
},
};
/**
* Journey image upload options, built from the container.
*
* Same reason as the trip-file factory: the fileFilter reads the operator's
* allowed-extension list at request time. Note this config carries NO
* defParamCharset, unlike the trip-file one; that difference is deliberate and
* predates the move, so the two are not folded into one shared object.
*/
export function buildJourneyImageUploadOptions(allowedTypes: AllowedFileTypesService) {
return {
storage: diskStorage({
destination: (_req, _file, cb) => { if (!fs.existsSync(uploadsBase)) fs.mkdirSync(uploadsBase, { recursive: true }); cb(null, uploadsBase); },
filename: (_req, file, cb) => cb(null, `${crypto.randomUUID()}${path.extname(file.originalname).toLowerCase() || '.jpg'}`),
}),
limits: { fileSize: 20 * 1024 * 1024 },
fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
if (!file.mimetype.startsWith('image/') || file.mimetype.includes('svg')) {
const err: Error & { statusCode?: number } = new Error('Only image files are allowed');
err.statusCode = 400;
return cb(err, false);
}
const ext = path.extname(file.originalname).toLowerCase().replace('.', '');
const allowed = allowedTypes.get().split(',').map((e) => e.trim().toLowerCase());
if (!allowed.includes('*') && !allowed.includes(ext)) {
const err: Error & { statusCode?: number } = new Error(`File type .${ext} is not allowed`);
err.statusCode = 400;
return cb(err, false);
}
cb(null, true);
},
};
}
// Gallery video upload (#823): one video plus an optional client-captured poster
// image, written to the same uploads/journey store. Larger cap than images since
@@ -161,7 +171,7 @@ export class JourneyController {
}
@Post('entries/:entryId/photos')
@UseInterceptors(FilesInterceptor('photos', undefined, IMAGE_UPLOAD))
@UseInterceptors(FilesInterceptor('photos'))
async uploadEntryPhotos(@CurrentUser() user: User, @Param('entryId') entryId: string, @UploadedFiles() files: Express.Multer.File[] | undefined, @Body() body: JourneyEntryPhotoUploadDto) {
if (!files?.length) {
throw new HttpException({ error: 'No files uploaded' }, 400);
@@ -257,7 +267,7 @@ export class JourneyController {
// ── Gallery (prefix /:id/gallery — before /:id) ─────────────────────────
@Post(':id/gallery/photos')
@UseInterceptors(FilesInterceptor('photos', undefined, IMAGE_UPLOAD))
@UseInterceptors(FilesInterceptor('photos'))
uploadGalleryPhotos(@CurrentUser() user: User, @Param('id') id: string, @UploadedFiles() files: Express.Multer.File[] | undefined) {
if (!files?.length) {
throw new HttpException({ error: 'No files uploaded' }, 400);
@@ -360,7 +370,7 @@ export class JourneyController {
@Post(':id/cover')
@HttpCode(200) // Express answers cover with res.json (200).
@UseInterceptors(FileInterceptor('cover', IMAGE_UPLOAD))
@UseInterceptors(FileInterceptor('cover'))
cover(@CurrentUser() user: User, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined) {
if (!file) {
throw new HttpException({ error: 'No file uploaded' }, 400);
+11 -1
View File
@@ -7,10 +7,20 @@ import { MemoriesModule } from '../memories/memories.module';
import { JourneyDomainModule } from './journey-domain.module';
import { JourneyMcp } from './journey.mcp';
import { AuthModule } from '../auth/auth.module';
import { MulterModule } from '@nestjs/platform-express';
import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
import { AllowedFileTypesService } from '../files/allowed-file-types.service';
import { buildJourneyImageUploadOptions } from './journey.controller';
@Module({
// MemoriesModule: the journey gallery streams provider assets and uploads to Immich.
imports: [AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule],
imports: [
MulterModule.registerAsync({
imports: [AllowedFileTypesModule],
inject: [AllowedFileTypesService],
useFactory: (allowedTypes: AllowedFileTypesService) => buildJourneyImageUploadOptions(allowedTypes),
}),
AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule],
controllers: [JourneyController, JourneyPublicController],
providers: [JourneyService, JourneyMcp],
})
@@ -3,6 +3,7 @@ import type { Response } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { LlmLocalService } from './llm-local.service';
import { LlmLocalPullDto } from './llm-local.dto';
/**
* Admin-only management of a local LLM server (Ollama): list installed models and
@@ -24,7 +25,7 @@ export class LlmLocalController {
* response body to render a progress bar. Uses @Res() to stream manually.
*/
@Post('pull')
async pull(@Body() body: { baseUrl?: string; model?: string }, @Res() res: Response): Promise<void> {
async pull(@Body() body: LlmLocalPullDto, @Res() res: Response): Promise<void> {
const stream = await this.local.pull(body?.baseUrl, body?.model ?? '');
res.status(200);
res.setHeader('Content-Type', 'application/x-ndjson');
@@ -0,0 +1,10 @@
import { createZodDto } from 'nestjs-zod';
import { z } from 'zod';
/**
* The Ollama pull body. Both fields are optional because the service supplies
* its own defaults for a missing baseUrl and reports an empty model itself.
*/
export class LlmLocalPullDto extends createZodDto(
z.looseObject({ baseUrl: z.string().optional(), model: z.string().optional() }),
) {}
@@ -9,6 +9,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
import { getClientIp } from '../audit/client-ip';
import type { User } from '../../types';
import type { AuthorizeParams } from './oauth.service';
import { OauthClientCreateDto, OauthConsentDto } from './oauth.dto';
const MIN = 60_000;
@@ -67,10 +68,7 @@ export class OauthApiController {
@Post('authorize')
@HttpCode(200) // Express answers consent with res.json (200), not the POST-default 201.
@UseGuards(CookieAuthGuard)
authorize(@CurrentUser() user: User, @Body() body: {
client_id: string; redirect_uri: string; scope: string; state?: string;
code_challenge: string; code_challenge_method: string; approved: boolean; resource?: string;
}, @Req() req: Request) {
authorize(@CurrentUser() user: User, @Body() body: OauthConsentDto, @Req() req: Request) {
const ip = getClientIp(req);
if (!this.oauth.mcpEnabled()) {
throw new HttpException({ error: 'MCP is not enabled' }, 403);
@@ -126,7 +124,7 @@ export class OauthApiController {
@Post('clients')
@HttpCode(201)
@UseGuards(CookieAuthGuard)
createClient(@CurrentUser() user: User, @Body() body: { name: string; redirect_uris?: string[]; allowed_scopes: string[]; allows_client_credentials?: boolean }, @Req() req: Request) {
createClient(@CurrentUser() user: User, @Body() body: OauthClientCreateDto, @Req() req: Request) {
this.requireMcp403();
const result = this.oauth.createOAuthClient(user.id, body.name, body.redirect_uris ?? [], body.allowed_scopes, getClientIp(req), { allowsClientCredentials: body.allows_client_credentials });
if (result.error) {
+17
View File
@@ -0,0 +1,17 @@
import { createZodDto } from 'nestjs-zod';
import { oauthClientCreateRequestSchema, oauthConsentRequestSchema } from '@trek/shared';
/**
* Server-side createZodDto wrappers over the @trek/shared OAuth contracts.
*
* Both schemas already described these two bodies exactly; they were written
* with the contracts and then never wired to the handlers, which declared the
* same shape inline as an anonymous type. The inline types are gone now, so the
* wire shape has one definition instead of two that could drift.
*
* Neither handler owns a bespoke required-field message: consent redirects with
* `error=access_denied` on a rejection, and client creation surfaces whatever
* the service returns. So nothing user-visible moves in front of the pipe here.
*/
export class OauthConsentDto extends createZodDto(oauthConsentRequestSchema) {}
export class OauthClientCreateDto extends createZodDto(oauthClientCreateRequestSchema) {}
@@ -6,6 +6,7 @@ import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
import { pluginsEnabled } from '../kill-switch';
import { PluginHooks } from '../plugin-hooks.service';
import { stripEmoji } from '../text-sanitize';
import { PluginRouteDto } from '../plugins.dto';
/**
* POST /api/plugin-routes/:pluginId/:profileId — ask ONE routeProvider plugin to
@@ -158,7 +159,7 @@ export class PluginRoutesController {
async route(
@Param('pluginId') pluginId: string,
@Param('profileId') profileId: string,
@Body() body: Record<string, unknown> | undefined,
@Body() body: PluginRouteDto,
@Req() req: Request & { user?: { id: number } },
): Promise<{ route: PluginRouteOut | null }> {
if (!pluginsEnabled()) return { route: null };
@@ -5,6 +5,7 @@ import { pluginsEnabled } from './kill-switch';
import { PluginsService } from './plugins.service';
import { PluginRuntimeService } from './plugin-runtime.service';
import { DatabaseService } from '../database/database.service';
import { PluginUserSettingsUpdateDto } from './plugins.dto';
/**
* GET/POST /api/plugin-settings/:id — a USER's own `scope:'user'` settings for a
@@ -74,7 +75,7 @@ export class PluginUserSettingsController {
@Post(':id')
update(
@Param('id') id: string,
@Body() body: { config?: Record<string, unknown> },
@Body() body: PluginUserSettingsUpdateDto,
@Req() req: Request & { user?: { id: number } },
): { config: Record<string, unknown> } {
const userId = req.user?.id;
@@ -11,6 +11,7 @@ import { CurrentUser } from '../auth/current-user.decorator';
import { getClientIp } from '../audit/client-ip';
import { pluginsEnabled } from './kill-switch';
import { devLinkEnabled } from './dev-link';
import { PluginActivateDto, PluginConfigDto, PluginEgressHostsDto, PluginInstallDto, PluginLinkDto, PluginRetrustDto, PluginUninstallDto } from './plugins.dto';
/**
* Flatten a registry/install failure into the error envelope — CARRYING THE CODE.
@@ -70,7 +71,7 @@ export class PluginsController {
@Post('install')
@HttpCode(200)
async install(@Body() body: { id?: string; version?: string; constraint?: string; withDependencies?: boolean }) {
async install(@Body() body: PluginInstallDto) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
if (!body?.id) throw new HttpException({ error: 'id is required' }, 400);
try {
@@ -104,7 +105,7 @@ export class PluginsController {
*/
@Post('link')
@HttpCode(200)
async link(@Body() body: { path?: string }) {
async link(@Body() body: PluginLinkDto) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
if (!devLinkEnabled()) throw new HttpException({ error: 'Dev-link is disabled (set TREK_PLUGINS_DEV_LINK=1)' }, 403);
const dir = body?.path?.trim();
@@ -122,7 +123,7 @@ export class PluginsController {
}
@Put(':id/config')
updateConfig(@Param('id') id: string, @Body() body: Record<string, unknown>) {
updateConfig(@Param('id') id: string, @Body() body: PluginConfigDto) {
return { config: this.plugins.updateInstanceConfig(id, body || {}) };
}
@@ -138,7 +139,7 @@ export class PluginsController {
}
@Put(':id/egress-hosts')
async setEgressHosts(@Param('id') id: string, @Body() body: { hosts?: unknown } = {}) {
async setEgressHosts(@Param('id') id: string, @Body() body: PluginEgressHostsDto) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
const hosts = Array.isArray(body.hosts) ? body.hosts.map(String) : [];
try {
@@ -150,7 +151,7 @@ export class PluginsController {
@Post(':id/activate')
@HttpCode(200)
async activate(@Param('id') id: string, @Body() body: { consent?: boolean } = {}) {
async activate(@Param('id') id: string, @Body() body: PluginActivateDto) {
if (!pluginsEnabled()) throw new HttpException({ error: 'Plugins are disabled by server configuration' }, 503);
try {
await this.runtime.activate(id, !!body?.consent);
@@ -231,7 +232,7 @@ export class PluginsController {
@HttpCode(200)
async retrust(
@Param('id') id: string,
@Body() body: { version?: string; publicKey?: string },
@Body() body: PluginRetrustDto,
@CurrentUser() user: { id: number },
@Req() req: Request,
) {
@@ -247,7 +248,7 @@ export class PluginsController {
@Post(':id/uninstall')
@HttpCode(200)
async uninstall(@Param('id') id: string, @Body() body: { deleteData?: boolean }) {
async uninstall(@Param('id') id: string, @Body() body: PluginUninstallDto) {
await this.runtime.uninstall(id, !!body?.deleteData);
return { status: 'uninstalled' };
}
+73
View File
@@ -0,0 +1,73 @@
import { createZodDto } from 'nestjs-zod';
import { z } from 'zod';
/**
* Body contracts for the plugin surfaces, written to DESCRIBE rather than to
* tighten (the journey-contract doctrine, #1842).
*
* Every one of these handlers already owns its own rejection, and several of
* them answer something other than 400 for a body they dislike: activate and
* install answer 503 when plugins are disabled, and they check that BEFORE
* looking at the body. A schema that rejected first would move a 503 to a 400
* for an operator whose server has plugins off. So the fields stay optional and
* the objects stay loose: the DTO pins the wire TYPES, and the handler keeps
* every decision it already made, in the order it already made it.
*/
/** `id is required` stays the handler's answer, so id is optional here. */
export class PluginInstallDto extends createZodDto(
z.looseObject({
id: z.string().optional(),
version: z.string().optional(),
constraint: z.string().optional(),
withDependencies: z.boolean().optional(),
}),
) {}
/** `path is required` likewise, and dev-link answers 403 before reading it. */
export class PluginLinkDto extends createZodDto(
z.looseObject({ path: z.string().optional() }),
) {}
export class PluginActivateDto extends createZodDto(
z.looseObject({ consent: z.boolean().optional() }),
) {}
export class PluginUninstallDto extends createZodDto(
z.looseObject({ deleteData: z.boolean().optional() }),
) {}
export class PluginRetrustDto extends createZodDto(
z.looseObject({ version: z.string().optional(), publicKey: z.string().optional() }),
) {}
/**
* `hosts` is deliberately unknown, not `string[]`.
*
* The handler reads `Array.isArray(body.hosts) ? body.hosts.map(String) : []`,
* which means an omitted or non-array `hosts` CLEARS the operator egress list.
* That is the documented way to reset it, so a schema demanding an array would
* not tighten validation, it would remove a working admin action.
*/
export class PluginEgressHostsDto extends createZodDto(
z.looseObject({ hosts: z.unknown().optional() }),
) {}
/**
* Plugin instance config is defined by the plugin's own manifest, not by TREK,
* so there is no shape to assert here beyond "a JSON object".
*/
export class PluginConfigDto extends createZodDto(z.looseObject({})) {}
export class PluginUserSettingsUpdateDto extends createZodDto(
z.looseObject({ config: z.record(z.string(), z.unknown()).optional() }),
) {}
/**
* The route hook answers `{ route: null }` at 200 for every input it dislikes:
* a missing trip, a bad profile, unusable waypoints, a slow provider. The client
* draws straight lines on a null and shows nothing on a 400, so a schema that
* rejected a malformed body would turn a graceful fallback into a visible error.
* Loose and fully optional on purpose.
*/
export class PluginRouteDto extends createZodDto(z.looseObject({})) {}
@@ -26,6 +26,7 @@ import { AirtrailImportDto } from '../integrations/airtrail.dto';
import type { AirtrailImportResult } from '@trek/shared';
import { bookingImportModeSchema } from '@trek/shared';
import type { BookingImportPreviewItem, BookingImportPreviewResponse, BookingImportConfirmResponse, BookingImportMode } from '@trek/shared';
import { BookingImportConfirmDto, BookingImportPreviewDto } from './reservation-import.dto';
const ACCEPTED_EXTS = new Set(['.eml', '.pdf', '.pkpass', '.html', '.htm', '.txt']);
const MAX_FILE_BYTES = 10 * 1024 * 1024;
@@ -127,9 +128,9 @@ export class ReservationImportController {
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@UploadedFiles() files: Express.Multer.File[] | undefined,
@Body('mode') rawMode?: string,
@Body() body: BookingImportPreviewDto,
): Promise<BookingImportPreviewResponse> {
const mode = this.validateImport(tripId, user, files, rawMode);
const mode = this.validateImport(tripId, user, files, body?.mode);
return this.bookingImport.preview(files!, mode, user.id);
}
@@ -147,9 +148,9 @@ export class ReservationImportController {
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@UploadedFiles() files: Express.Multer.File[] | undefined,
@Body('mode') rawMode?: string,
@Body() body: BookingImportPreviewDto,
): Promise<{ jobId: string }> {
const mode = this.validateImport(tripId, user, files, rawMode);
const mode = this.validateImport(tripId, user, files, body?.mode);
const jobId = this.importJobs.start(tripId, files!, mode, user.id);
return { jobId };
}
@@ -175,7 +176,7 @@ export class ReservationImportController {
async confirm(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { items?: BookingImportPreviewItem[] },
@Body() body: BookingImportConfirmDto,
@Headers('x-socket-id') socketId?: string,
): Promise<BookingImportConfirmResponse> {
@@ -0,0 +1,29 @@
import { createZodDto } from 'nestjs-zod';
import { z } from 'zod';
import { bookingImportPreviewItemSchema } from '@trek/shared';
/**
* Server-side createZodDto wrappers for the booking-import bodies.
*
* Confirm validates each item against the shared contract but leaves `items`
* itself optional, which is narrower than `bookingImportConfirmRequestSchema`
* on purpose. That schema declares `.min(1)`, and the pipe reports a rejection
* as `field: message` — so adopting it verbatim would replace the endpoint's
* `{ error: 'items must be a non-empty array' }`. The handler keeps the check
* that owns the message, and the DTO adds what the handler never did: per-item
* shape validation.
*
* Preview and its async twin carry a multipart body, so every field arrives as a
* string and the real payload is the files. `mode` is described here for the
* type, and deliberately not narrowed to the mode enum: `validateImport` parses
* it with `bookingImportModeSchema` and owns the `Invalid mode` response. The
* object is not strict, because a multipart form may carry fields the browser
* adds and the handler ignores.
*/
export class BookingImportConfirmDto extends createZodDto(
z.object({ items: z.array(bookingImportPreviewItemSchema).optional() }),
) {}
export class BookingImportPreviewDto extends createZodDto(
z.object({ mode: z.string().optional() }),
) {}
+5 -7
View File
@@ -4,6 +4,7 @@ import type { User } from '../../types';
import { TagsService } from './tags.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { TagCreateDto, TagUpdateDto } from './tags.dto';
/**
* /api/tags — per-user place-tag CRUD.
@@ -25,11 +26,8 @@ export class TagsController {
}
@Post()
create(
@CurrentUser() user: User,
@Body('name') name?: string,
@Body('color') color?: string,
): { tag: Tag } {
create(@CurrentUser() user: User, @Body() body: TagCreateDto): { tag: Tag } {
const { name, color } = body;
if (!name) {
throw new HttpException({ error: 'Tag name is required' }, 400);
}
@@ -40,9 +38,9 @@ export class TagsController {
update(
@CurrentUser() user: User,
@Param('id') id: string,
@Body('name') name?: string,
@Body('color') color?: string,
@Body() body: TagUpdateDto,
): { tag: Tag } {
const { name, color } = body;
if (!this.tags.getByIdAndUser(id, user.id)) {
throw new HttpException({ error: 'Tag not found' }, 404);
}
+24
View File
@@ -0,0 +1,24 @@
import { createZodDto } from 'nestjs-zod';
import { z } from 'zod';
import { updateTagRequestSchema } from '@trek/shared';
/**
* Server-side createZodDto wrappers over the @trek/shared tag contracts.
*
* Create deliberately does NOT use `createTagRequestSchema` as written. That
* schema declares `name: z.string().min(1)`, and the pipe reports a rejection as
* `field: message` — so adopting it verbatim would replace the endpoint's
* `{ error: 'Tag name is required' }` with `name: ...`. Two tests pin that
* string, and more to the point it is what a client shows the user.
*
* So the DTO accepts the shape and leaves `name` optional, and the handler keeps
* the check that owns the message. The endpoint's actual contract is unchanged:
* a request without a name still gets 400, with the same body it always had.
* What the DTO does add is type and shape validation on everything else, which
* is what took this route off the allow-list.
*/
export class TagCreateDto extends createZodDto(
z.object({ name: z.string().optional(), color: z.string().optional() }),
) {}
export class TagUpdateDto extends createZodDto(updateTagRequestSchema) {}