mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(server): the second pass over this branch's own fixes
An adversarial review of what had already landed here turned up three that
were wrong, and they are the reason for this commit.
The CSP change removed 'unsafe-eval', which is not leftover: heic-to's
libheif build initialises embind through new Function(), and without it every
iPhone .heic upload fails in the browser. 'wasm-unsafe-eval' alone was tried
once already and was not enough (93b51a0b). Put back, with the reason written
down this time and the test pinning it rather than its absence.
The idempotency in-flight guard never fired. finalize() runs when the
handler's observable completes, but Nest writes the response - and therefore
stores the row - several microtasks later, so the waiting request always woke
up before the row existed and ran the handler a second time. It releases from
the point the row is written now; finalize is the backstop for handlers that
answer another way. The test drove the two in the opposite order from Nest,
which is why it passed either way.
And the trip-scoping check treated an id that resolves to nothing like one
belonging to someone else. accommodation_id has no foreign key, so shortening
a trip's dates leaves a booking pointing at a gap - which update() has always
healed by clearing the link, and which would have become a permanent 400.
The rest: a reply to a soft-deleted chat message is refused and the create
path blanks the quote like the list path does; the ws-token buckets are keyed
by account rather than by IP, where every user behind one NAT shared a
ceiling; the weather and vacay caps read through the stream, since a chunked
response has no content-length to check; the Google host gate takes country
domains again; abandoned response bodies are cancelled instead of left to GC;
the boot failure prints its errno; and a share link that is not yours to read
now says so instead of reporting that the journey has none.
TICKETJSON gets a real repair: the in-place GLOB fix only helps installs that
have not run it yet, so an appended migration puts back the note text the
case-insensitive LIKE cut off, for rows where what it stored is not valid
JSON. A genuine receipt always parses, so it cannot be touched.
Wiki: the audit log records the IP Express resolves after TRUST_PROXY, not
the leftmost X-Forwarded-For entry a caller can write. That is the right way
round, but it means the hop count has to be accurate - said plainly in both
places now.
This commit is contained in:
+10
-4
@@ -37,16 +37,22 @@ if (_encryptionKey) {
|
||||
try {
|
||||
_encryptionKey = fs.readFileSync(encKeyFile, 'utf8').trim();
|
||||
} catch (readErr: unknown) {
|
||||
if ((readErr as NodeJS.ErrnoException)?.code !== 'ENOENT') {
|
||||
const code = (readErr as NodeJS.ErrnoException)?.code;
|
||||
if (code !== 'ENOENT') {
|
||||
// The file is there, we just cannot read it (permissions, I/O error).
|
||||
// Continuing would resolve a different key and overwrite this one below,
|
||||
// which permanently orphans every stored secret. Refuse to start instead.
|
||||
// The errno goes in the line because this exit crash-loops the container,
|
||||
// and the code is the only part that says which of these it is.
|
||||
console.error(
|
||||
'FATAL: could not read',
|
||||
encKeyFile,
|
||||
'-',
|
||||
`FATAL: could not read ${encKeyFile} (${code ?? 'no errno'}) -`,
|
||||
readErr instanceof Error ? readErr.message : readErr,
|
||||
);
|
||||
if (code === 'EISDIR') {
|
||||
// Compose creating a missing bind-mount source as a directory is by far
|
||||
// the most common way this file stops being a file.
|
||||
console.error('EISDIR: the path is a directory. A bind mount pointed at data/.encryption_key created it as one — remove it and mount the data directory instead.');
|
||||
}
|
||||
console.error('Fix the file permissions or set ENCRYPTION_KEY explicitly.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -4089,6 +4089,40 @@ function runMigrations(db: Database.Database): void {
|
||||
() => {
|
||||
db.exec("UPDATE trip_files SET filename = substr(filename, 7) WHERE filename LIKE 'files/%'");
|
||||
},
|
||||
// Give back the notes the TICKETJSON step chopped up (#1658).
|
||||
//
|
||||
// That step matched with LIKE, which is case-insensitive in SQLite, so a
|
||||
// note somebody had typed starting "ticketjson:" was read as a receipt: the
|
||||
// first eleven characters were dropped, the rest was moved into ticket_json
|
||||
// and the note was set to NULL. The step now matches with GLOB, but that
|
||||
// only helps a fresh install — the array is index-addressed against
|
||||
// schema_version, so a repaired step never runs again on a database that
|
||||
// already applied it.
|
||||
//
|
||||
// A receipt comes out of JSON.stringify and always parses; typed text does
|
||||
// not. So a row moves back only when its ticket_json fails to parse AND the
|
||||
// note is still empty — anything that parses, and any row someone has
|
||||
// written a note on since, is left exactly as it is. The eleven marker
|
||||
// characters themselves are gone for good: their case was the only thing
|
||||
// separating a receipt from a note, and writing "TICKETJSON:" back would
|
||||
// hand the row straight to the reader that reads that prefix as a receipt.
|
||||
// Appended LAST — the array is index-addressed against schema_version.
|
||||
() => {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT id, ticket_json FROM budget_items
|
||||
WHERE ticket_json IS NOT NULL AND ticket_json != '' AND COALESCE(note, '') = ''`
|
||||
)
|
||||
.all() as Array<{ id: number; ticket_json: string }>;
|
||||
const restore = db.prepare('UPDATE budget_items SET note = ?, ticket_json = NULL WHERE id = ?');
|
||||
for (const row of rows) {
|
||||
try {
|
||||
JSON.parse(row.ticket_json);
|
||||
} catch {
|
||||
restore.run(row.ticket_json, row.id);
|
||||
}
|
||||
}
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -165,7 +165,15 @@ export function applyGlobalMiddleware(
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", "'wasm-unsafe-eval'"],
|
||||
// 'unsafe-eval' is load-bearing, not leftover: heic-to's libheif build
|
||||
// initialises embind through new Function(), and that is what converts
|
||||
// an iPhone .heic the moment somebody picks one. 'wasm-unsafe-eval'
|
||||
// alone was tried first and was not enough (93b51a0b). The package
|
||||
// ships a CSP-safe entry point at heic-to/csp; dropping this directive
|
||||
// means switching client/src/utils/convertHeic.ts over to it and
|
||||
// verifying a real .heic upload in a browser, not just deleting the
|
||||
// string here.
|
||||
scriptSrc: ["'self'", "'wasm-unsafe-eval'", "'unsafe-eval'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://unpkg.com"],
|
||||
imgSrc: ["'self'", "data:", "blob:", "https:"],
|
||||
connectSrc: [
|
||||
|
||||
@@ -66,7 +66,8 @@ export const AVATAR_FILE_FILTER: Options['fileFilter'] = (_req, file, cb) => {
|
||||
* the demo-mode block), settings, key validation, MFA setup/enable/disable, MCP
|
||||
* tokens and the short-lived ws/resource tokens. The per-IP rate limits reuse
|
||||
* the shared buckets (the inline rateLimiter(5) shares the 'login' bucket, as in
|
||||
* the legacy code). create-token answers 201; everything else 200.
|
||||
* the legacy code); the two token-minting routes are keyed per account instead,
|
||||
* see limitUser. create-token answers 201; everything else 200.
|
||||
*/
|
||||
@Controller('api/auth')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@@ -79,6 +80,21 @@ export class AuthController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Same limiter, keyed on the account instead of the address. What these
|
||||
* buckets bound is one account's share of the process-wide ephemeral token
|
||||
* store, and an address is the wrong unit for that: an office, a school or a
|
||||
* mobile carrier arrives as one IP, and the first user to reconnect a lot
|
||||
* would take the ceiling away from everybody behind it. The pre-auth buckets
|
||||
* (login, register, forgot-password) keep the IP key — there is no account
|
||||
* to charge yet.
|
||||
*/
|
||||
private limitUser(bucket: string, userId: number, max: number): void {
|
||||
if (!this.rl.check(bucket, String(userId), max, WINDOW, Date.now())) {
|
||||
throw new HttpException({ error: 'Too many attempts. Please try again later.' }, 429);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@MfaExempt('the client needs to know who it is to render the setup screen')
|
||||
me(@CurrentUser() user: User) {
|
||||
@@ -307,13 +323,13 @@ export class AuthController {
|
||||
|
||||
@Post('ws-token')
|
||||
@HttpCode(200)
|
||||
wsToken(@CurrentUser() user: User, @Req() req: Request) {
|
||||
wsToken(@CurrentUser() user: User) {
|
||||
// Own bucket, not 'login': a client that reconnects its socket in a loop
|
||||
// must not be able to lock itself out of signing in. The ceiling is far
|
||||
// above any real client, which mints one token per socket connect, but it
|
||||
// stops a single account from filling the process-wide ephemeral store and
|
||||
// 503-ing every other user's ws and download tokens.
|
||||
this.limit('ws_token', req, 120);
|
||||
this.limitUser('ws_token', user.id, 120);
|
||||
const result = this.tokens.createWsToken(user.id);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
@@ -323,8 +339,8 @@ export class AuthController {
|
||||
|
||||
@Post('resource-token')
|
||||
@HttpCode(200)
|
||||
resourceToken(@CurrentUser() user: User, @Body() body: ResourceTokenDto, @Req() req: Request) {
|
||||
this.limit('resource_token', req, 120);
|
||||
resourceToken(@CurrentUser() user: User, @Body() body: ResourceTokenDto) {
|
||||
this.limitUser('resource_token', user.id, 120);
|
||||
const token = this.tokens.createResourceToken(user.id, body.purpose);
|
||||
if (!token) {
|
||||
throw new HttpException({ error: 'Service unavailable' }, 503);
|
||||
|
||||
@@ -422,7 +422,11 @@ export class CollabService {
|
||||
|
||||
createMessage(tripId: string | number, userId: number, text: string, replyTo?: number | null): { error?: string; message?: ReturnType<CollabService['formatMessage']> } {
|
||||
if (replyTo) {
|
||||
const replyMsg = this.db.get('SELECT id FROM collab_messages WHERE id = ? AND trip_id = ?', replyTo, tripId);
|
||||
// A soft-deleted message is gone as far as anyone replying is concerned:
|
||||
// its row survives only so the placeholder can be drawn where it was.
|
||||
const replyMsg = this.db.get(
|
||||
'SELECT id FROM collab_messages WHERE id = ? AND trip_id = ? AND deleted = 0', replyTo, tripId,
|
||||
);
|
||||
if (!replyMsg) return { error: 'reply_not_found' };
|
||||
}
|
||||
|
||||
@@ -432,7 +436,8 @@ export class CollabService {
|
||||
|
||||
const message = this.db.get<CollabMessage>(`
|
||||
SELECT m.*, u.username, u.avatar,
|
||||
rm.text AS reply_text, ru.username AS reply_username
|
||||
CASE WHEN rm.deleted = 1 THEN '' ELSE rm.text END AS reply_text,
|
||||
ru.username AS reply_username
|
||||
FROM collab_messages m
|
||||
JOIN users u ON m.user_id = u.id
|
||||
LEFT JOIN collab_messages rm ON m.reply_to = rm.id
|
||||
|
||||
@@ -118,6 +118,19 @@ export class IdempotencyInterceptor implements NestInterceptor {
|
||||
): Observable<unknown> {
|
||||
const originalJson = res.json.bind(res);
|
||||
const database = this.database;
|
||||
|
||||
let done!: () => void;
|
||||
inFlight.set(signature, new Promise<void>((resolve) => { done = resolve; }));
|
||||
let released = false;
|
||||
// Idempotent: whichever of the two paths below gets there first releases the
|
||||
// waiter, and the other one is a no-op.
|
||||
const release = () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
inFlight.delete(signature);
|
||||
done();
|
||||
};
|
||||
|
||||
res.json = function (body: unknown): Response {
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
try {
|
||||
@@ -133,16 +146,24 @@ export class IdempotencyInterceptor implements NestInterceptor {
|
||||
// Non-fatal: if storage fails, the request still succeeds.
|
||||
}
|
||||
}
|
||||
// Release here, not in finalize: this is the point the row exists, and a
|
||||
// waiter woken any earlier looks the key up, misses, and runs the handler
|
||||
// a second time - the duplicate write the key is meant to prevent.
|
||||
// Release here, not in finalize: this is the point the row exists, and a
|
||||
// waiter woken any earlier looks the key up, misses, and runs the handler
|
||||
// a second time - the duplicate write the key is meant to prevent.
|
||||
release();
|
||||
return originalJson(body);
|
||||
};
|
||||
|
||||
let done!: () => void;
|
||||
inFlight.set(signature, new Promise<void>((resolve) => { done = resolve; }));
|
||||
|
||||
return next.handle().pipe(
|
||||
finalize(() => {
|
||||
inFlight.delete(signature);
|
||||
done();
|
||||
// Backstop for a handler that never reaches res.json: it threw, or it
|
||||
// answered through @Res() with send/end. Deferred by a full tick because
|
||||
// finalize runs when the handler's observable completes and Nest writes
|
||||
// the response several microtasks after that - firing straight away
|
||||
// would beat the wrapper above to it on the ordinary path.
|
||||
setImmediate(release);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -55,7 +55,6 @@ export class JourneyPublicController {
|
||||
@Param('token') token: string,
|
||||
@Param('provider') provider: string,
|
||||
@Param('assetId') assetId: string,
|
||||
@Param('ownerId') ownerId: string,
|
||||
@Param('kind') kind: string,
|
||||
@Res() res: Response,
|
||||
): Promise<void> {
|
||||
@@ -82,8 +81,9 @@ export class JourneyPublicController {
|
||||
return;
|
||||
}
|
||||
|
||||
// :ownerId stays in the path so old share links keep routing, but it is not
|
||||
// read any more: the owner comes from the row the token resolved to.
|
||||
// :ownerId stays in the route pattern so old share links keep routing, but
|
||||
// it is not bound at all any more: the owner comes from the row the token
|
||||
// resolved to.
|
||||
const effectiveOwnerId = valid.ownerId;
|
||||
const streaming = this.journey.streamProviderAsset(
|
||||
res,
|
||||
|
||||
@@ -73,6 +73,24 @@ export class JourneyShareService {
|
||||
return { token, created: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the link on behalf of a user. Owner only, the same check create and
|
||||
* delete take: the token is the whole credential and it keeps working after a
|
||||
* contributor is removed, so handing it out is handing out the journey.
|
||||
*
|
||||
* The refusal is its own answer rather than a null link, because those two
|
||||
* mean opposite things to the caller — a published journey that reads as
|
||||
* unpublished puts a "create link" button in front of somebody it will then
|
||||
* refuse. Both the REST route and the MCP tool read the link through here.
|
||||
*/
|
||||
readJourneyShareLink(
|
||||
journeyId: number,
|
||||
userId: number,
|
||||
): { allowed: false } | { allowed: true; link: JourneyShareTokenInfo | null } {
|
||||
if (!this.journey.isOwner(journeyId, userId)) return { allowed: false };
|
||||
return { allowed: true, link: this.getJourneyShareLink(journeyId) };
|
||||
}
|
||||
|
||||
getJourneyShareLink(journeyId: number): JourneyShareTokenInfo | null {
|
||||
const row = this.db.prepare('SELECT * FROM journey_share_tokens WHERE journey_id = ?').get(journeyId) as any;
|
||||
if (!row) return null;
|
||||
|
||||
@@ -599,7 +599,7 @@ export class JourneyController {
|
||||
baseVersion: body.baseVersion,
|
||||
});
|
||||
if (result === null) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
throw this.bookRefusal(Number(id), user.id);
|
||||
}
|
||||
if ('conflict' in result) {
|
||||
/*
|
||||
@@ -624,10 +624,24 @@ export class JourneyController {
|
||||
deleteBook(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const removed = this.books.deleteBook(Number(id), user.id);
|
||||
if (removed === null) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
throw this.bookRefusal(Number(id), user.id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a book write was refused, in a way the editor can act on.
|
||||
*
|
||||
* Both refusals come back as null, and answering 404 for both would tell a
|
||||
* viewer who has just spent an hour laying out pages that their journey does
|
||||
* not exist. Someone who cannot see the journey at all still gets the 404 —
|
||||
* the status is not an existence oracle for them.
|
||||
*/
|
||||
private bookRefusal(journeyId: number, userId: number): HttpException {
|
||||
return this.books.canOpen(journeyId, userId)
|
||||
? new HttpException({ error: 'Not allowed' }, 403)
|
||||
: new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
|
||||
@Post(':id/entries')
|
||||
createEntry(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyEntryCreateDto, @Headers('x-socket-id') socketId?: string) {
|
||||
if (!body.entry_date) {
|
||||
@@ -693,7 +707,15 @@ export class JourneyController {
|
||||
// ── Share Link ──────────────────────────────────────────────────────────
|
||||
@Get(':id/share-link')
|
||||
getShareLink(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
return { link: this.journey.getJourneyShareLink(Number(id), user.id) };
|
||||
// Reading the token is owner-only. It refuses like its siblings rather than
|
||||
// answering with a null link: "not published" and "not yours to see" are
|
||||
// different answers, and a client told the first one offers a create button
|
||||
// that the POST below then refuses.
|
||||
const result = this.journey.getJourneyShareLink(Number(id), user.id);
|
||||
if (!result.allowed) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { link: result.link };
|
||||
}
|
||||
|
||||
@Post(':id/share-link')
|
||||
|
||||
@@ -415,10 +415,11 @@ export class JourneyMcp {
|
||||
access: { group: 'journey', mode: 'share' },
|
||||
})
|
||||
getJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
// Owner only, same as the REST route: handing out the token is handing out
|
||||
// the journey.
|
||||
if (!this.journey.isOwner(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
return ok({ shareLink: this.share.getJourneyShareLink(journeyId) });
|
||||
// Same read the REST route uses, so the owner check cannot drift apart
|
||||
// between the two surfaces: handing out the token is handing out the journey.
|
||||
const result = this.share.readJourneyShareLink(journeyId, ctx.userId);
|
||||
if (!result.allowed) return notFound('Journey not found or access denied.');
|
||||
return ok({ shareLink: result.link });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
|
||||
@@ -78,13 +78,10 @@ export class JourneyService {
|
||||
removeContributor(id: number, userId: number, targetUserId: number) { return this.journey.removeContributor(id, userId, targetUserId); }
|
||||
|
||||
// Share links
|
||||
// Authorization: the token is the whole credential, so reading it needs the
|
||||
// same owner check create/delete use. A viewer who reads it keeps a working
|
||||
// anonymous link after being removed as a contributor.
|
||||
getJourneyShareLink(id: number, userId: number) {
|
||||
if (!this.journey.isOwner(id, userId)) return null;
|
||||
return this.share.getJourneyShareLink(id);
|
||||
}
|
||||
// Authorization lives in JourneyShareService.readJourneyShareLink, which the
|
||||
// MCP tool reads through as well; { allowed: false } is a refusal, not "no
|
||||
// link exists".
|
||||
getJourneyShareLink(id: number, userId: number) { return this.share.readJourneyShareLink(id, userId); }
|
||||
createOrUpdateJourneyShareLink(id: number, userId: number, data: Parameters<typeof this.share.createOrUpdateJourneyShareLink>[2]) { return this.share.createOrUpdateJourneyShareLink(id, userId, data); }
|
||||
deleteJourneyShareLink(id: number, userId: number) { return this.share.deleteJourneyShareLink(id, userId); }
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
} from '@trek/shared';
|
||||
import { readEnv, getAppUrl } from '../../app-config';
|
||||
import { safeFetchFollow, SsrfBlockedError } from '../../utils/ssrfGuard';
|
||||
import { exceedsDeclaredLength, readCappedText } from '../../utils/cappedFetch';
|
||||
import { discardBody, exceedsDeclaredLength, readCappedText } from '../../utils/cappedFetch';
|
||||
import { resolveApiKey, type ApiKeySource } from '../settings/instance-api-keys';
|
||||
// ── Photo cache (disk-backed) ────────────────────────────────────────────────
|
||||
import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';
|
||||
@@ -342,6 +342,20 @@ interface GooglePlaceDetails extends GooglePlaceResult {
|
||||
// unbounded body out of memory.
|
||||
const MAX_MAPS_PAGE_BYTES = 2_000_000;
|
||||
|
||||
const GOOGLE_SHORT_HOSTS = ['goo.gl', 'maps.app.goo.gl'];
|
||||
|
||||
/**
|
||||
* Google Maps lives on every country domain — google.de, maps.google.co.uk,
|
||||
* google.com.au — so the host is matched by shape. A fixed list of .com hosts
|
||||
* would quietly stop resolving the ccTLD links people actually paste. The TLD
|
||||
* labels stay short (2-3 letters, optionally two of them) so that
|
||||
* `google.evil.com` is not a Google host.
|
||||
*/
|
||||
function isGoogleMapsHost(hostname: string): boolean {
|
||||
return GOOGLE_SHORT_HOSTS.includes(hostname)
|
||||
|| /^(www\.|maps\.)?google\.[a-z]{2,3}(\.[a-z]{2})?$/.test(hostname);
|
||||
}
|
||||
|
||||
const WIKI_TIMEOUT_MS = 6000;
|
||||
|
||||
// Tighter than the wiki calls, because this one sits at the FRONT of a chain:
|
||||
@@ -2038,9 +2052,8 @@ export class MapsService {
|
||||
// usually carries the !3d!4d data param we can then parse. Redirects are
|
||||
// followed manually so every hop is SSRF-re-checked.
|
||||
const parsed = new URL(url);
|
||||
const GOOGLE_MAPS_HOSTS = ['goo.gl', 'maps.app.goo.gl', 'google.com', 'www.google.com', 'maps.google.com'];
|
||||
const isShort = ['goo.gl', 'maps.app.goo.gl'].includes(parsed.hostname);
|
||||
const isGoogleMaps = GOOGLE_MAPS_HOSTS.includes(parsed.hostname);
|
||||
const isShort = GOOGLE_SHORT_HOSTS.includes(parsed.hostname);
|
||||
const isGoogleMaps = isGoogleMapsHost(parsed.hostname);
|
||||
if (isShort || (isGoogleMaps && !extractCoords(url))) {
|
||||
resolvedUrl = (await followRedirects(url)).url || resolvedUrl;
|
||||
}
|
||||
@@ -2053,12 +2066,15 @@ export class MapsService {
|
||||
// short link that lands on maps.google.com still qualifies.
|
||||
let resolvedHost = '';
|
||||
try { resolvedHost = new URL(resolvedUrl).hostname; } catch { /* keep the empty host, the branch is skipped */ }
|
||||
if (!coords && GOOGLE_MAPS_HOSTS.includes(resolvedHost)) {
|
||||
if (!coords && isGoogleMapsHost(resolvedHost)) {
|
||||
try {
|
||||
const pageRes = await followRedirects(resolvedUrl, {
|
||||
headers: { 'User-Agent': UA },
|
||||
});
|
||||
if (!exceedsDeclaredLength(pageRes, MAX_MAPS_PAGE_BYTES)) {
|
||||
if (exceedsDeclaredLength(pageRes, MAX_MAPS_PAGE_BYTES)) {
|
||||
// Nothing here will read it, and an unread body keeps its socket.
|
||||
discardBody(pageRes);
|
||||
} else {
|
||||
// The map data sits near the top of the document, so a truncated read
|
||||
// still finds the coordinates; an oversized page degrades to the same
|
||||
// 400 an unparseable one already produced.
|
||||
|
||||
@@ -445,27 +445,39 @@ export class ReservationsService {
|
||||
*/
|
||||
referencesOutsideTrip(tripId: string | number, data: CreateReservationData | UpdateReservationData): string[] {
|
||||
const offenders: string[] = [];
|
||||
const inTrip = (table: 'days' | 'places' | 'day_accommodations', id: unknown) =>
|
||||
!!this.db.get(`SELECT id FROM ${table} WHERE id = ? AND trip_id = ?`, id, tripId);
|
||||
// An id that resolves to nothing is not an offender. accommodation_id in
|
||||
// particular carries no foreign key, so shortening a trip's date range
|
||||
// cascades the day_accommodations row away and leaves the reservation
|
||||
// pointing at a gap; update() has always healed that by clearing the link,
|
||||
// and refusing the whole write instead would make such a booking
|
||||
// permanently uneditable. Only a row that exists in a DIFFERENT trip is one
|
||||
// the caller must not have reached for.
|
||||
const elsewhere = (table: 'days' | 'places' | 'day_accommodations', id: unknown) => {
|
||||
const row = this.db.get<{ trip_id: number }>(`SELECT trip_id FROM ${table} WHERE id = ?`, id);
|
||||
return !!row && String(row.trip_id) !== String(tripId);
|
||||
};
|
||||
|
||||
const check = (field: string, ok: boolean) => { if (!ok) offenders.push(field); };
|
||||
const check = (field: string, offending: boolean) => { if (offending) offenders.push(field); };
|
||||
|
||||
if (data.day_id != null) check('day_id', inTrip('days', data.day_id));
|
||||
if (data.end_day_id != null) check('end_day_id', inTrip('days', data.end_day_id));
|
||||
if (data.place_id != null) check('place_id', inTrip('places', data.place_id));
|
||||
if (data.accommodation_id != null) check('accommodation_id', inTrip('day_accommodations', data.accommodation_id));
|
||||
if (data.day_id != null) check('day_id', elsewhere('days', data.day_id));
|
||||
if (data.end_day_id != null) check('end_day_id', elsewhere('days', data.end_day_id));
|
||||
if (data.place_id != null) check('place_id', elsewhere('places', data.place_id));
|
||||
if (data.accommodation_id != null) check('accommodation_id', elsewhere('day_accommodations', data.accommodation_id));
|
||||
if (data.assignment_id != null) {
|
||||
check('assignment_id', !!this.db.get(
|
||||
'SELECT da.id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE da.id = ? AND d.trip_id = ?',
|
||||
data.assignment_id, tripId,
|
||||
));
|
||||
// An assignment belongs to a trip through its day, so the join is the
|
||||
// lookup — same shape as the MCP tool's getAssignmentForTrip.
|
||||
const row = this.db.get<{ trip_id: number }>(
|
||||
'SELECT d.trip_id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE da.id = ?',
|
||||
data.assignment_id,
|
||||
);
|
||||
check('assignment_id', !!row && String(row.trip_id) !== String(tripId));
|
||||
}
|
||||
|
||||
const acc = data.create_accommodation;
|
||||
if (acc) {
|
||||
if (acc.place_id != null) check('create_accommodation.place_id', inTrip('places', acc.place_id));
|
||||
if (acc.start_day_id != null) check('create_accommodation.start_day_id', inTrip('days', acc.start_day_id));
|
||||
if (acc.end_day_id != null) check('create_accommodation.end_day_id', inTrip('days', acc.end_day_id));
|
||||
if (acc.place_id != null) check('create_accommodation.place_id', elsewhere('places', acc.place_id));
|
||||
if (acc.start_day_id != null) check('create_accommodation.start_day_id', elsewhere('days', acc.start_day_id));
|
||||
if (acc.end_day_id != null) check('create_accommodation.end_day_id', elsewhere('days', acc.end_day_id));
|
||||
}
|
||||
|
||||
return offenders;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { exceedsDeclaredLength } from '../../utils/cappedFetch';
|
||||
import { discardBody, readCappedJson } from '../../utils/cappedFetch';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@@ -465,8 +465,10 @@ export class VacayService {
|
||||
if (!holidays) {
|
||||
if (!COUNTRY_RE.test(country)) continue;
|
||||
const resp = await fetch(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok || exceedsDeclaredLength(resp, MAX_HOLIDAY_BYTES)) continue;
|
||||
holidays = await resp.json() as Holiday[];
|
||||
if (!resp.ok) { discardBody(resp); continue; }
|
||||
const parsed = await readCappedJson<Holiday[]>(resp, MAX_HOLIDAY_BYTES);
|
||||
if (parsed === undefined) continue;
|
||||
holidays = parsed;
|
||||
this.holidayCache.set(cacheKey, { data: holidays, time: Date.now() });
|
||||
}
|
||||
const hasRegions = holidays.some((h: Holiday) => h.counties && h.counties.length > 0);
|
||||
@@ -1231,8 +1233,9 @@ export class VacayService {
|
||||
if (cached && Date.now() - cached.time < CACHE_TTL) return { data: cached.data };
|
||||
try {
|
||||
const resp = await fetch('https://date.nager.at/api/v3/AvailableCountries', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok || exceedsDeclaredLength(resp, MAX_HOLIDAY_BYTES)) return { error: 'Failed to fetch countries' };
|
||||
const data = await resp.json();
|
||||
if (!resp.ok) { discardBody(resp); return { error: 'Failed to fetch countries' }; }
|
||||
const data = await readCappedJson(resp, MAX_HOLIDAY_BYTES);
|
||||
if (data === undefined) return { error: 'Failed to fetch countries' };
|
||||
this.holidayCache.set(cacheKey, { data, time: Date.now() });
|
||||
return { data };
|
||||
} catch {
|
||||
@@ -1249,8 +1252,9 @@ export class VacayService {
|
||||
if (cached && Date.now() - cached.time < CACHE_TTL) return { data: cached.data };
|
||||
try {
|
||||
const resp = await fetch(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok || exceedsDeclaredLength(resp, MAX_HOLIDAY_BYTES)) return { error: 'Failed to fetch holidays' };
|
||||
const data = await resp.json();
|
||||
if (!resp.ok) { discardBody(resp); return { error: 'Failed to fetch holidays' }; }
|
||||
const data = await readCappedJson(resp, MAX_HOLIDAY_BYTES);
|
||||
if (data === undefined) return { error: 'Failed to fetch holidays' };
|
||||
this.holidayCache.set(cacheKey, { data, time: Date.now() });
|
||||
return { data };
|
||||
} catch {
|
||||
@@ -1269,14 +1273,15 @@ export class VacayService {
|
||||
fetch(`https://openholidaysapi.org/Groups?countryIsoCode=${country}&languageIsoCode=${normalizedLanguage}`, { headers: { accept: 'text/json' }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }),
|
||||
fetch(`https://openholidaysapi.org/Subdivisions?countryIsoCode=${country}&languageIsoCode=${normalizedLanguage}`, { headers: { accept: 'text/json' }, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }),
|
||||
]);
|
||||
if (!groupsResp.ok || !subdivisionsResp.ok) return { error: 'Failed to fetch school holiday regions' };
|
||||
if (exceedsDeclaredLength(groupsResp, MAX_HOLIDAY_BYTES) || exceedsDeclaredLength(subdivisionsResp, MAX_HOLIDAY_BYTES)) {
|
||||
if (!groupsResp.ok || !subdivisionsResp.ok) {
|
||||
discardBody(groupsResp);
|
||||
discardBody(subdivisionsResp);
|
||||
return { error: 'Failed to fetch school holiday regions' };
|
||||
}
|
||||
const data = {
|
||||
groups: await groupsResp.json(),
|
||||
subdivisions: await subdivisionsResp.json(),
|
||||
};
|
||||
const groups = await readCappedJson(groupsResp, MAX_HOLIDAY_BYTES);
|
||||
const subdivisions = await readCappedJson(subdivisionsResp, MAX_HOLIDAY_BYTES);
|
||||
if (groups === undefined || subdivisions === undefined) return { error: 'Failed to fetch school holiday regions' };
|
||||
const data = { groups, subdivisions };
|
||||
this.holidayCache.set(cacheKey, { data, time: Date.now() });
|
||||
return { data };
|
||||
} catch {
|
||||
@@ -1305,8 +1310,9 @@ export class VacayService {
|
||||
headers: { accept: 'text/json' },
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!resp.ok || exceedsDeclaredLength(resp, MAX_HOLIDAY_BYTES)) return { error: 'Failed to fetch school holidays' };
|
||||
const data = await resp.json();
|
||||
if (!resp.ok) { discardBody(resp); return { error: 'Failed to fetch school holidays' }; }
|
||||
const data = await readCappedJson(resp, MAX_HOLIDAY_BYTES);
|
||||
if (data === undefined) return { error: 'Failed to fetch school holidays' };
|
||||
this.holidayCache.set(cacheKey, { data, time: Date.now() });
|
||||
return { data };
|
||||
} catch {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { exceedsDeclaredLength } from '../../utils/cappedFetch';
|
||||
import { readCappedJson } from '../../utils/cappedFetch';
|
||||
|
||||
// Open-Meteo sits on the request path as a third party: without a deadline a hung
|
||||
// connection holds the caller until the socket gives up on its own. Every other
|
||||
@@ -24,13 +24,21 @@ function hourIndexFromTime(time?: string): number | null {
|
||||
// misbehaving, not that the trip got longer.
|
||||
const MAX_WEATHER_BYTES = 1024 * 1024;
|
||||
|
||||
/** Open-Meteo GET with the shared deadline and the declared-size cap. */
|
||||
async function fetchOpenMeteo(url: string): Promise<Response> {
|
||||
/**
|
||||
* Open-Meteo GET with the shared deadline and the size cap.
|
||||
*
|
||||
* The body is read through the cap rather than buffered with .json(): Open-Meteo
|
||||
* answers chunked, so there is no content-length to check and a declared-length
|
||||
* test alone would let any amount of data through. The caller still gets the
|
||||
* response, because the status and `reason` are what shape its error.
|
||||
*/
|
||||
async function fetchOpenMeteo(url: string): Promise<{ response: Response; data: OpenMeteoForecast }> {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(WEATHER_TIMEOUT_MS) });
|
||||
if (exceedsDeclaredLength(response, MAX_WEATHER_BYTES)) {
|
||||
const data = await readCappedJson<OpenMeteoForecast>(response, MAX_WEATHER_BYTES);
|
||||
if (!data) {
|
||||
throw new ApiError(502, 'Open-Meteo API error');
|
||||
}
|
||||
return response;
|
||||
return { response, data };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -241,8 +249,7 @@ async function _getWeatherImpl(
|
||||
// Forecast range (-1 .. +16 days)
|
||||
if (diffDays >= -1 && diffDays <= 16) {
|
||||
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=auto&forecast_days=16`;
|
||||
const response = await fetchOpenMeteo(url);
|
||||
const data = await response.json() as OpenMeteoForecast;
|
||||
const { response, data } = await fetchOpenMeteo(url);
|
||||
|
||||
if (!response.ok || data.error) {
|
||||
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
|
||||
@@ -279,8 +286,7 @@ async function _getWeatherImpl(
|
||||
? '&hourly=temperature_2m,weathercode'
|
||||
: '';
|
||||
const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${dateStr}&end_date=${dateStr}&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum${hourParam}&timezone=auto`;
|
||||
const response = await fetchOpenMeteo(url);
|
||||
const data = await response.json() as OpenMeteoForecast;
|
||||
const { response, data } = await fetchOpenMeteo(url);
|
||||
|
||||
if (!response.ok || data.error) {
|
||||
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Archive API error');
|
||||
@@ -336,8 +342,7 @@ async function _getWeatherImpl(
|
||||
const endStr = endDate.toISOString().slice(0, 10);
|
||||
|
||||
const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${startStr}&end_date=${endStr}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=auto`;
|
||||
const response = await fetchOpenMeteo(url);
|
||||
const data = await response.json() as OpenMeteoForecast;
|
||||
const { response, data } = await fetchOpenMeteo(url);
|
||||
|
||||
if (!response.ok || data.error) {
|
||||
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Climate API error');
|
||||
@@ -389,8 +394,7 @@ async function _getWeatherImpl(
|
||||
if (cached) return cached;
|
||||
|
||||
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}¤t=temperature_2m,weathercode&timezone=auto`;
|
||||
const response = await fetchOpenMeteo(url);
|
||||
const data = await response.json() as OpenMeteoForecast;
|
||||
const { response, data } = await fetchOpenMeteo(url);
|
||||
|
||||
if (!response.ok || data.error) {
|
||||
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
|
||||
@@ -464,8 +468,7 @@ async function _getDetailedWeatherImpl(
|
||||
+ `&hourly=temperature_2m,precipitation,weathercode,windspeed_10m,relativehumidity_2m`
|
||||
+ `&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum,windspeed_10m_max,sunrise,sunset`
|
||||
+ `&timezone=auto`;
|
||||
const response = await fetchOpenMeteo(url);
|
||||
const data = await response.json() as OpenMeteoForecast;
|
||||
const { response, data } = await fetchOpenMeteo(url);
|
||||
|
||||
if (!response.ok || data.error) {
|
||||
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Climate API error');
|
||||
@@ -527,8 +530,7 @@ async function _getDetailedWeatherImpl(
|
||||
+ `&daily=temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset,precipitation_probability_max,precipitation_sum,windspeed_10m_max`
|
||||
+ `&timezone=auto&start_date=${dateStr}&end_date=${dateStr}`;
|
||||
|
||||
const response = await fetchOpenMeteo(url);
|
||||
const data = await response.json() as OpenMeteoForecast;
|
||||
const { response, data } = await fetchOpenMeteo(url);
|
||||
|
||||
if (!response.ok || data.error) {
|
||||
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
|
||||
|
||||
@@ -16,9 +16,10 @@ interface CappedReader {
|
||||
}
|
||||
interface CappedResponse {
|
||||
headers?: { get(name: string): string | null } | null;
|
||||
body?: { getReader(): CappedReader } | null;
|
||||
body?: { getReader(): CappedReader; cancel?(): Promise<unknown> } | null;
|
||||
arrayBuffer?(): Promise<ArrayBuffer>;
|
||||
text?(): Promise<string>;
|
||||
json?(): Promise<unknown>;
|
||||
}
|
||||
|
||||
/** True when the provider declares a body larger than the budget. */
|
||||
@@ -26,6 +27,41 @@ export function exceedsDeclaredLength(res: CappedResponse, maxBytes: number): bo
|
||||
return Number(res.headers?.get('content-length') ?? 0) > maxBytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Let go of a body nobody is going to read. undici keeps the connection
|
||||
* reserved until the stream ends, so a bail-out that just returns leaves the
|
||||
* socket pinned until the garbage collector gets around to it — which is the
|
||||
* one thing a size cap is supposed to prevent.
|
||||
*/
|
||||
export function discardBody(res: CappedResponse): void {
|
||||
void res.body?.cancel?.().catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* readCappedText plus the parse, for the providers that only ever answer with a
|
||||
* JSON document. Answers `undefined` when the body is over the cap, was cut off
|
||||
* at it, or does not parse: every caller already has a "the provider
|
||||
* misbehaved" branch, and none of them can do anything with half a document.
|
||||
*/
|
||||
export async function readCappedJson<T>(res: CappedResponse, maxBytes: number): Promise<T | undefined> {
|
||||
if (exceedsDeclaredLength(res, maxBytes)) {
|
||||
discardBody(res);
|
||||
return undefined;
|
||||
}
|
||||
// Neither a stream nor text() means there is nothing to read incrementally
|
||||
// and nothing to cap — a null-body status, or a partial stub in a test.
|
||||
if (!res.body?.getReader && !res.text && !res.arrayBuffer && res.json) {
|
||||
return await res.json() as T;
|
||||
}
|
||||
const { text, truncated } = await readCappedText(res, maxBytes);
|
||||
if (truncated) return undefined;
|
||||
try {
|
||||
return JSON.parse(text) as T;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a body, stopping once maxBytes have arrived. Callers that must reject
|
||||
* an oversized payload look at `truncated`; callers that only scan the head of
|
||||
|
||||
Reference in New Issue
Block a user