fix(airtrail): read the v1 answers at the boundary and refuse an arrival before the departure

The v1 bodies were cast to their types unchecked, so a flight page whose data
was not a list, or a passenger list of another shape, failed deeper down as a
TypeError instead of an AirTrail request error. Each v1 answer (a flight, a
page of flights, a created flight, a reference lookup, the key owner) is now
read through a small schema that keeps the fields TREK does not need lenient.

The legacy save refuses an arrival before the departure; the v1 body passed
it on, so an overnight arrival time without its date would have been stored
before the departure. The v1 write-back now refuses it with the same message.
This commit is contained in:
Maurice
2026-11-18 23:17:27 +01:00
parent 76ff6e15b1
commit d8c28c9998
3 changed files with 113 additions and 82 deletions
+59 -55
View File
@@ -1,6 +1,8 @@
import { wallClockInstant } from '../common/timezoneService';
import type { AirtrailAirport, AirtrailFlightRaw, AirtrailSavePayload } from './airtrail.client';
import { z } from 'zod';
/**
* The translation between AirTrail's `/api/v1` and the shapes the rest of TREK
* uses (AirtrailFlightRaw, AirtrailSavePayload), which are the shapes of the
@@ -14,47 +16,48 @@ import type { AirtrailAirport, AirtrailFlightRaw, AirtrailSavePayload } from './
*/
/** An airport as v1 returns it, on a flight and from `GET /api/v1/airports`. */
export interface AirtrailV1Airport {
id: number;
icao: string | null;
iata: string | null;
name: string | null;
latitude: number | null;
longitude: number | null;
timezone: string | null;
country: string | null;
}
/*
* The v1 bodies, read at the boundary. A field TREK does not need may be absent
* or null; a body of another shape (a list that is not a list, a flight without
* an id) is refused as a request error instead of failing deeper down.
*/
const optText = z.string().nullish();
const optNumber = z.number().nullish();
/** An airline or aircraft as v1 returns it. Aircraft have no IATA code. */
export interface AirtrailV1Entity {
id: number;
name: string | null;
icao: string | null;
iata?: string | null;
}
export const airtrailV1AirportSchema = z.object({
id: z.number(),
icao: optText,
iata: optText,
name: optText,
latitude: optNumber,
longitude: optNumber,
timezone: optText,
country: optText,
});
export type AirtrailV1Airport = z.infer<typeof airtrailV1AirportSchema>;
interface AirtrailV1Passenger {
id: number;
user: { id: string } | null;
guestName: string | null;
seat: string | null;
seatNumber: string | null;
seatClass: string | null;
flightReason: string | null;
}
export const airtrailV1EntitySchema = z.object({ id: z.number(), name: optText, icao: optText, iata: optText });
/** A flight as `GET /api/v1/flights` and `GET /api/v1/flights/{id}` return it. */
export interface AirtrailV1Flight {
id: number;
from: AirtrailV1Airport | null;
to: AirtrailV1Airport | null;
airline: AirtrailV1Entity | null;
aircraft: AirtrailV1Entity | null;
passengers: AirtrailV1Passenger[];
[key: string]: unknown;
}
const airtrailV1PassengerSchema = z.object({
user: z.object({ id: z.string() }).nullish(),
guestName: optText,
seat: optText,
seatNumber: optText,
seatClass: optText,
flightReason: optText,
});
/** A flight keeps every other field as AirTrail sent it: the sync reads the times and the rest from it. */
export const airtrailV1FlightSchema = z.looseObject({
id: z.number(),
from: airtrailV1AirportSchema.nullish(),
to: airtrailV1AirportSchema.nullish(),
airline: airtrailV1EntitySchema.nullish(),
aircraft: airtrailV1EntitySchema.nullish(),
passengers: z.array(airtrailV1PassengerSchema).nullish(),
});
type AirtrailV1Flight = z.infer<typeof airtrailV1FlightSchema>;
/** What a v1 write needs that a code-based payload does not carry. */
export interface AirtrailV1References {
from: AirtrailV1Airport;
to: AirtrailV1Airport;
@@ -75,17 +78,17 @@ export class AirtrailV1InputError extends Error {
/** The placeholder the legacy save resolved to the key owner. */
export const AIRTRAIL_SELF_USER_PLACEHOLDER = '<USER_ID>';
function toAirport(a: AirtrailV1Airport | null): AirtrailAirport | null {
function toAirport(a: AirtrailV1Airport | null | undefined): AirtrailAirport | null {
if (!a) return null;
return {
id: a.id,
icao: a.icao,
iata: a.iata,
name: a.name,
lat: a.latitude,
lon: a.longitude,
tz: a.timezone,
country: a.country,
icao: a.icao ?? null,
iata: a.iata ?? null,
name: a.name ?? null,
lat: a.latitude ?? null,
lon: a.longitude ?? null,
tz: a.timezone ?? null,
country: a.country ?? null,
};
}
@@ -103,11 +106,11 @@ export function fromAirtrailV1Flight(f: AirtrailV1Flight): AirtrailFlightRaw {
to: toAirport(f.to),
passengers: (f.passengers ?? []).map((p) => ({
userId: p.user?.id ?? null,
guestName: p.guestName,
seat: p.seat,
seatNumber: p.seatNumber,
seatClass: p.seatClass,
flightReason: p.flightReason,
guestName: p.guestName ?? null,
seat: p.seat ?? null,
seatNumber: p.seatNumber ?? null,
seatClass: p.seatClass ?? null,
flightReason: p.flightReason ?? null,
})),
};
}
@@ -171,7 +174,7 @@ function carriedInstant(p: Record<string, unknown>, key: string, zone: string |
* - Departure and its scheduled time are the local wall clock at the origin,
* arrival and its scheduled time at the destination. A date without a time
* gives no instant. An arrival time without an arrival date takes the
* departure date.
* departure date, and an arrival before the departure is refused.
* - `date` is the departure date, else the scheduled departure date.
* - A precision other than `day` keeps only the departure, at 10:00 UTC.
* - A flight-level reason fills each passenger that has none.
@@ -188,8 +191,8 @@ export function toAirtrailV1FlightInput(
refs: AirtrailV1References,
): Record<string, unknown> {
const p = payload as unknown as Record<string, unknown>;
const fromTz = refs.from.timezone;
const toTz = refs.to.timezone;
const fromTz = refs.from.timezone ?? null;
const toTz = refs.to.timezone ?? null;
const depDate = datePart(p.departure);
const date = depDate ?? datePart(p.departureScheduled);
@@ -243,8 +246,9 @@ export function toAirtrailV1FlightInput(
const known =
times.departure && times.arrival ? (Date.parse(times.arrival) - Date.parse(times.departure)) / 1000 : null;
const duration =
known !== null && known >= 0 ? Math.round(known) : typeof p.duration === 'number' ? p.duration : null;
// The legacy save refuses this; v1 would store it, for example an overnight arrival time without its date.
if (known !== null && known < 0) throw new AirtrailV1InputError('Arrival must be after departure');
const duration = known !== null ? Math.round(known) : typeof p.duration === 'number' ? p.duration : null;
return {
date,
+36 -16
View File
@@ -1,16 +1,18 @@
import { safeFetch } from '../../utils/ssrfGuard';
import {
AirtrailV1InputError,
airtrailV1AirportSchema,
airtrailV1EntitySchema,
airtrailV1FlightSchema,
fromAirtrailV1Flight,
pickAirtrailByCode,
AIRTRAIL_SELF_USER_PLACEHOLDER,
toAirtrailV1FlightInput,
type AirtrailV1Airport,
type AirtrailV1Entity,
type AirtrailV1Flight,
} from './airtrail-v1';
import { Injectable } from '@nestjs/common';
import { z } from 'zod';
/**
* Thin HTTP client for the AirTrail REST API (github.com/johanohly/AirTrail).
* This is the ONLY place that talks to a user's AirTrail instance.
@@ -233,6 +235,21 @@ async function parseJson<T>(resp: Response): Promise<T> {
}
}
/** A v1 body in the shape `schema` describes; any other shape is a request error, not a crash further down. */
async function parseV1<T>(resp: Response, schema: z.ZodType<T>, what: string): Promise<T> {
const parsed = schema.safeParse(await parseJson<unknown>(resp));
if (!parsed.success) throw new AirtrailRequestError(`AirTrail answered the ${what} in an unexpected shape`);
return parsed.data;
}
const v1FlightAnswer = z.object({ data: airtrailV1FlightSchema.nullish() });
const v1FlightPage = z.object({
data: z.array(airtrailV1FlightSchema),
page: z.object({ nextCursor: z.string().nullish() }).nullish(),
});
const v1Created = z.object({ data: z.object({ id: z.number() }).nullish() });
const v1Me = z.object({ data: z.object({ id: z.string() }) });
/** The error of a v1 error body (`{error:{code,message,details}}`), when the response holds one. */
async function airtrailV1Error(resp: Response): Promise<{ code: string | null; message: string } | null> {
try {
@@ -326,7 +343,7 @@ export class AirtrailClient {
if (resp.status === 404) return null;
if (!resp.ok) throw new AirtrailRequestError(`AirTrail get failed (HTTP ${resp.status})`, resp.status);
if (v1) {
const data = await parseJson<{ data?: AirtrailV1Flight }>(resp);
const data = await parseV1(resp, v1FlightAnswer, 'flight');
return data.data ? fromAirtrailV1Flight(data.data) : null;
}
const data = await parseJson<{ flight?: AirtrailFlightRaw }>(resp);
@@ -416,8 +433,8 @@ export class AirtrailClient {
if (cursor) query.set('cursor', cursor);
const resp = await request(creds, `/v1/flights?${query}`, { method: 'GET' });
if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status);
const body = await parseJson<{ data?: AirtrailV1Flight[]; page?: { nextCursor?: string | null } }>(resp);
for (const f of body.data ?? []) flights.push(fromAirtrailV1Flight(f));
const body = await parseV1(resp, v1FlightPage, 'flight list');
for (const f of body.data) flights.push(fromAirtrailV1Flight(f));
const next = body.page?.nextCursor ?? null;
if (!next) return flights;
// A cursor that came before makes an endless loop. AirTrail does not send one, but a caching proxy can.
@@ -430,11 +447,13 @@ export class AirtrailClient {
private async saveFlightV1(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> {
const [from, to, airline, aircraft] = await Promise.all([
this.findByCode<AirtrailV1Airport>(creds, 'airports', payload.from, false, 'departure airport'),
this.findByCode<AirtrailV1Airport>(creds, 'airports', payload.to, false, 'arrival airport'),
payload.airline ? this.findByCode<AirtrailV1Entity>(creds, 'airlines', payload.airline, true, 'airline') : null,
this.findByCode(creds, 'airports', payload.from, false, 'departure airport', airtrailV1AirportSchema),
this.findByCode(creds, 'airports', payload.to, false, 'arrival airport', airtrailV1AirportSchema),
payload.airline
? this.findByCode(creds, 'airlines', payload.airline, true, 'airline', airtrailV1EntitySchema)
: null,
payload.aircraft
? this.findByCode<AirtrailV1Entity>(creds, 'aircraft', payload.aircraft, true, 'aircraft')
? this.findByCode(creds, 'aircraft', payload.aircraft, true, 'aircraft', airtrailV1EntitySchema)
: null,
]);
const people = payload.passengers ?? payload.seats ?? [];
@@ -465,7 +484,7 @@ export class AirtrailClient {
if (!resp.ok) throw await airtrailV1Failure(resp, 'save');
// The legacy save answers an id only for a new flight. This method does the same.
if (update) return {};
const data = await parseJson<{ data?: { id?: number } }>(resp);
const data = await parseV1(resp, v1Created, 'saved flight');
return { id: data.data?.id };
}
@@ -479,13 +498,14 @@ export class AirtrailClient {
code: string,
icaoOnly: boolean,
label: string,
schema: z.ZodType<T>,
): Promise<T> {
const resp = await request(creds, `/v1/${kind}?${new URLSearchParams({ query: code.trim() })}`, {
method: 'GET',
});
if (!resp.ok) throw await airtrailV1Failure(resp, `${label} lookup`);
const body = await parseJson<{ data?: T[] }>(resp);
const row = pickAirtrailByCode(body.data ?? [], code, icaoOnly);
const body = await parseV1(resp, z.object({ data: z.array(schema) }), `${label} lookup`);
const row = pickAirtrailByCode(body.data, code, icaoOnly);
if (!row) throw new AirtrailRequestError(`Invalid ${label}: ${code}`, 400);
return row;
}
@@ -494,8 +514,8 @@ export class AirtrailClient {
private async selfUserId(creds: AirtrailCreds): Promise<string> {
const resp = await request(creds, '/v1/me', { method: 'GET' });
if (!resp.ok) throw await airtrailV1Failure(resp, 'profile read');
const body = await parseJson<{ data?: { id?: unknown } }>(resp);
if (typeof body.data?.id !== 'string') throw new AirtrailRequestError('AirTrail did not name the key owner');
return body.data.id;
const parsed = v1Me.safeParse(await parseJson<unknown>(resp));
if (!parsed.success) throw new AirtrailRequestError('AirTrail did not name the key owner');
return parsed.data.data.id;
}
}
@@ -159,6 +159,15 @@ describe('AirtrailClient picks the API the instance speaks', () => {
);
});
it('refuses a flight page of another shape with a request error, and lists nothing', async () => {
v1Instance();
on('GET', '/api/v1/flights', () => json({ data: { flights: [v1Flight(1)] }, page: { nextCursor: null } }));
await expect(new AirtrailClient().listFlights(creds)).rejects.toThrow(
new AirtrailRequestError('AirTrail answered the flight list in an unexpected shape'),
);
});
it('uses the legacy routes when the instance has no /api/v1', async () => {
on('GET', '/api/flight/list', () => json({ success: true, flights: [{ id: 9 }] }));
@@ -691,7 +700,7 @@ describe('toAirtrailV1FlightInput keeps the rules of the legacy save', () => {
});
it('puts an arrival time without an arrival date on the departure date', () => {
const body = toAirtrailV1FlightInput({ ...base, departureTime: '06:00', arrivalTime: '23:00' }, refs);
const body = toAirtrailV1FlightInput({ ...base, departureTime: '01:00', arrivalTime: '23:00' }, refs);
expect(body.arrival).toBe('2026-10-04T12:00:00.000+00:00');
});
@@ -789,15 +798,13 @@ describe('toAirtrailV1FlightInput converts the local wall clock to UTC', () => {
expect(body.departure).toBe('2026-10-04T23:30:00.000+00:00');
});
it('keeps the stored duration for an arrival before the departure', () => {
const body = toAirtrailV1FlightInput(
// `duration` is not a payload field; it passes through from the AirTrail flight.
{
...flight({ departure: '2026-10-05', departureTime: '10:00', arrival: '2026-10-05', arrivalTime: '09:00' }),
duration: 600,
} as AirtrailSavePayload,
refs(LHR, LHR),
);
expect(body.duration).toBe(600);
it('refuses an arrival before the departure, as the legacy save does, instead of storing it', () => {
// An overnight arrival time without its date lands on the departure date and before the departure.
expect(() =>
toAirtrailV1FlightInput(
flight({ departure: '2026-10-05', departureTime: '22:00', arrivalTime: '06:00' }),
refs(LHR, LHR),
),
).toThrow('Arrival must be after departure');
});
});