Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix: carry the search's passenger mix into per-flight booking links (#252)

Punit Arani25dec29007cb
diff --git a/CLAUDE.md b/CLAUDE.md
index 65779a8..d3d41bc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -216,10 +216,13 @@ Search for flights on a specific date.
**Response:** Each flight in `flights[]` carries its own `booking_url` — a
`tfs` protobuf deep link that opens the specific itinerary's booking page
(vendor fares + "Continue" CTA) on Google Flights. The token is deterministic
-(no session id), so the same itinerary always yields the same URL. The
-top-level `booking_url` is a broader search-page link (route + dates
-pre-filled) kept as a reliable fallback. Each flight's `flight_number` can be
-passed to `get_booking_options` for per-vendor pricing.
+(no session id), so the same itinerary always yields the same URL, and it
+carries the search's cabin class and passenger mix (adults, children,
+infants) so the booking page opens priced for the same travelers as the
+search results. The top-level `booking_url` is a broader search-page link
+(route + dates pre-filled) kept as a reliable fallback. Each flight's
+`flight_number` can be passed to `get_booking_options` for per-vendor
+pricing.
### `search_dates`
Find cheapest travel dates within a range.
diff --git a/docs/guides/mcp.md b/docs/guides/mcp.md
index e6bbde4..b33f468 100644
--- a/docs/guides/mcp.md
+++ b/docs/guides/mcp.md
@@ -138,10 +138,12 @@ Search for flights between two airports on a specific date.
Each flight in `flights[]` carries a `booking_url` that deep-links directly to
that specific flight's booking page on Google Flights (pre-loaded itinerary, no
-search step required). The top-level `booking_url` is a broader search-page
-link (route + date pre-filled) and is a reliable fallback. To retrieve
-per-vendor prices and airline-direct booking links, pass the flight's
-`flight_number` (e.g. `BA178`) to [`get_booking_options`](#get_booking_options).
+search step required). It carries the search's cabin class and passenger mix
+too, so it opens priced for the same travelers as the search results. The
+top-level `booking_url` is a broader search-page link (route + date
+pre-filled) and is a reliable fallback. To retrieve per-vendor prices and
+airline-direct booking links, pass the flight's `flight_number` (e.g.
+`BA178`) to [`get_booking_options`](#get_booking_options).
### `search_dates`
diff --git a/fli-js/src/search/flights.ts b/fli-js/src/search/flights.ts
index de6738d..7dacddc 100644
--- a/fli-js/src/search/flights.ts
+++ b/fli-js/src/search/flights.ts
@@ -11,7 +11,7 @@
*/
import type { GoogleFlightsUrlOptions } from "../core/links.ts";
-import type { BookingOption, FlightResult } from "../models/google-flights/base.ts";
+import type { BookingOption, FlightResult, PassengerInfo } from "../models/google-flights/base.ts";
import { SeatType, SortBy, TripType } from "../models/google-flights/base.ts";
import type { FlightSearchFilters } from "../models/google-flights/flights.ts";
import { type Client, getClient } from "./client.ts";
@@ -20,7 +20,7 @@ import { parallelMap, throwIfAborted } from "./concurrency.ts";
import { parseBookingChunk, parseFlightRow } from "./decoders.ts";
import { SearchParseError } from "./exceptions.ts";
import { getSearchLogger } from "./logging.ts";
-import { buildBookingToken, buildTfsToken, type LegSpec } from "./proto.ts";
+import { buildBookingToken, buildTfsToken, type LegSpec, passengerCodes } from "./proto.ts";
import {
applyClientSideFilters,
buildTfs,
@@ -91,6 +91,12 @@ export interface BookingOptions {
export interface BookingUrlOptions extends GoogleFlightsUrlOptions {
/** Cabin class encoded into the `tfs` token (field 9). Defaults to economy. */
seatType?: SeatType;
+ /**
+ * Passenger mix encoded into the `tfs` token (field 8, one entry per
+ * traveller). Defaults to a single adult, matching this method's output
+ * before this option existed.
+ */
+ passengerInfo?: Partial<PassengerInfo>;
}
export class SearchFlights {
@@ -409,7 +415,11 @@ export class SearchFlights {
flightNumber: leg.flight_number,
})),
);
- const tfs = buildTfsToken(segments, { isOneWay, seat: options.seatType ?? SeatType.ECONOMY });
+ const tfs = buildTfsToken(segments, {
+ isOneWay,
+ passengers: passengerCodes(options.passengerInfo),
+ seat: options.seatType ?? SeatType.ECONOMY,
+ });
url = `https://www.google.com/travel/flights/booking?tfs=${tfs}`;
} catch {
url = "https://www.google.com/travel/flights";
diff --git a/fli-js/src/search/proto.ts b/fli-js/src/search/proto.ts
index 0fa8904..07fc9d8 100644
--- a/fli-js/src/search/proto.ts
+++ b/fli-js/src/search/proto.ts
@@ -6,6 +6,7 @@
*/
import { Buffer } from "node:buffer";
+import type { PassengerInfo } from "../models/google-flights/base.ts";
function concatBytes(...parts: Uint8Array[]): Uint8Array {
let total = 0;
@@ -347,6 +348,13 @@ export interface LegSpec {
export interface BuildTfsTokenOptions {
/** `true` for one-way (incl. multi-city); `false` for round-trip. */
isOneWay?: boolean;
+ /**
+ * Passenger kind codes, one entry per traveller (field 8). Build these
+ * from a search's `PassengerInfo` with {@link passengerCodes}. Defaults
+ * to a single adult so existing callers keep producing the captured
+ * tokens.
+ */
+ passengers?: readonly number[];
/**
* Cabin class encoded in field 9.
* `1` = economy, `2` = premium economy, `3` = business, `4` = first.
@@ -376,6 +384,83 @@ export interface BuildTfsTokenOptions {
const MAX_U64 = (1n << 64n) - 1n;
+/**
+ * Passenger kinds, in the order Google's repeated field 8 numbers them:
+ * 1 = adult, 2 = child, 3 = infant on lap, 4 = infant in own seat.
+ *
+ * The two infant codes are easy to transpose and the mistake is expensive
+ * rather than loud: on an international route a lap infant prices at ~10%
+ * of the adult fare and an infant in its own seat at ~100%, so a swap
+ * quotes a plausible but wrong fare instead of erroring. The legacy RPC
+ * struct orders the same four counts
+ * `[adults, children, infants_on_lap, infants_in_seat]`.
+ */
+const PASSENGER_FIELDS: ReadonlyArray<readonly [keyof PassengerInfo, number]> = [
+ ["adults", 1],
+ ["children", 2],
+ ["infants_on_lap", 3],
+ ["infants_in_seat", 4],
+];
+
+/**
+ * Google's own per-booking limit. The Python port's `PassengerInfo` enforces
+ * this in `validate_passenger_counts`
+ * (`fli/models/google_flights/base.py`) — `PassengerInfoSchema` here has no
+ * equivalent cross-field check, so this is the one place on the TypeScript
+ * side that rejects an over-the-limit mix. Keep this in sync with the
+ * Python validator if Google's limit ever changes.
+ */
+const MAX_TOTAL_PASSENGERS = 9;
+
+/**
+ * Convert a `PassengerInfo` into `tfs` field-8 codes, one per traveller.
+ *
+ * Shared by {@link buildTfs} in `tfs.ts` (the search token) and
+ * {@link buildTfsToken} (the per-flight booking token) so the two cannot
+ * drift on how they encode the passenger mix.
+ *
+ * @param passengerInfo A `PassengerInfo`, or any duck-typed object exposing
+ * some subset of `adults`/`children`/`infants_on_lap`/`infants_in_seat`
+ * (missing ones count as zero). `null`/`undefined` is treated as an
+ * all-zero mix.
+ * @returns One code per traveller, in field order. Falls back to `[1]` (a
+ * single adult) when the mix would otherwise be empty.
+ * @throws {RangeError} Any count is not a non-negative integer, or the
+ * total exceeds {@link MAX_TOTAL_PASSENGERS}. Checked before building the
+ * result array, so a wildly out-of-range count (a duck-typed
+ * `adults: 1_000_000`, say) fails immediately instead of allocating an
+ * array that size — callers that pass a validated `PassengerInfo` never
+ * hit this; it exists for the duck-typed callers this function otherwise
+ * tolerates.
+ */
+export function passengerCodes(passengerInfo: Partial<PassengerInfo> | null | undefined): number[] {
+ let total = 0;
+ const counts: Array<readonly [number, number]> = []; // [code, count]
+ for (const [field, code] of PASSENGER_FIELDS) {
+ const count = (passengerInfo as Partial<PassengerInfo> | null)?.[field] ?? 0;
+ if (!Number.isInteger(count) || count < 0) {
+ throw new RangeError(
+ `passengerInfo.${field} must be a non-negative integer, got ${JSON.stringify(count)}`,
+ );
+ }
+ total += count;
+ counts.push([code, count]);
+ }
+
+ if (total > MAX_TOTAL_PASSENGERS) {
+ throw new RangeError(
+ `passengerInfo totals ${total} travellers, over the ` +
+ `${MAX_TOTAL_PASSENGERS}-traveller limit Google's booking page enforces`,
+ );
+ }
+
+ const codes: number[] = [];
+ for (const [code, count] of counts) {
+ for (let i = 0; i < count; i++) codes.push(code);
+ }
+ return codes.length > 0 ? codes : [1];
+}
+
/** Optional per-segment restrictions Google reads out of the `tfs` segment. */
export interface EncodeTfsSegmentOptions {
/**
@@ -522,6 +607,7 @@ export function encodeTfsPayload(segments: Uint8Array, options: EncodeTfsPayload
*/
export function buildTfsToken(segments: LegSpec[][], options: BuildTfsTokenOptions = {}): string {
const isOneWay = options.isOneWay ?? true;
+ const passengers = options.passengers ?? [1];
const seat = options.seat ?? 1;
if (segments.length === 0) throw new Error("segments must be non-empty");
for (let i = 0; i < segments.length; i++) {
@@ -539,5 +625,5 @@ export function buildTfsToken(segments: LegSpec[][], options: BuildTfsTokenOptio
);
}
- return encodeTfsPayload(segmentProtos, { isOneWay, seat, pinMaxU64: true });
+ return encodeTfsPayload(segmentProtos, { isOneWay, passengers, seat, pinMaxU64: true });
}
diff --git a/fli-js/src/search/tfs.ts b/fli-js/src/search/tfs.ts
index 5c88ab9..bfd128d 100644
--- a/fli-js/src/search/tfs.ts
+++ b/fli-js/src/search/tfs.ts
@@ -43,7 +43,7 @@ import type { Client } from "./client.ts";
import { sleep, throwIfAborted } from "./concurrency.ts";
import { SearchUnsupportedError } from "./exceptions.ts";
import { getSearchLogger } from "./logging.ts";
-import { encodeTfsPayload, encodeTfsSegment, type LegSpec } from "./proto.ts";
+import { encodeTfsPayload, encodeTfsSegment, type LegSpec, passengerCodes } from "./proto.ts";
/** Filter objects this transport can encode — both carry the same core fields. */
export type TfsFilters = FlightSearchFilters | DateSearchFilters;
@@ -89,26 +89,6 @@ const DS_BLOB = /AF_initDataCallback\((\{[\s\S]*?\})\);/g;
const DS_KEY = /key:\s*'([^']+)'/;
const DS_DATA = /data:([\s\S]*?), sideChannel/;
-/**
- * Passenger kinds, in the order Google's repeated field 8 numbers them:
- * 1 = adult, 2 = child, 3 = infant on lap, 4 = infant in own seat.
- *
- * The two infant codes are easy to transpose and the mistake is expensive
- * rather than loud: on an international route a lap infant prices at ~10%
- * of the adult fare and an infant in its own seat at ~100%, so a swap
- * quotes a plausible but wrong fare instead of erroring. Pricing one fixed
- * itinerary (BA178 JFK->LHR, economy) confirms the mapping — $295 for
- * `[1]`, $324 for `[1, 3]` (+10%, lap), $589 for `[1, 4]` (+100%, own
- * seat, same as the `[1, 2]` child fare). The legacy RPC struct orders the
- * same four counts `[adults, children, infants_on_lap, infants_in_seat]`.
- */
-const PASSENGER_FIELDS = [
- ["adults", 1],
- ["children", 2],
- ["infants_on_lap", 3],
- ["infants_in_seat", 4],
-] as const;
-
/**
* Filters with no `tfs` encoding and no reliable post-hoc equivalent —
* the decoded rows don't carry the data needed to apply them locally.
@@ -182,11 +162,7 @@ export function buildTfs(filters: TfsFilters, options: BuildTfsOptions = {}): st
const travelDates = options.travelDates ?? null;
const stops = filters.stops;
- const passengers: number[] = [];
- for (const [field, code] of PASSENGER_FIELDS) {
- const count = filters.passenger_info[field] ?? 0;
- for (let i = 0; i < count; i++) passengers.push(code);
- }
+ const passengers = passengerCodes(filters.passenger_info);
// Google reads alliances out of the same carrier lists as airline codes.
const carriers = (filters.alliances ?? []).map((a) => String(a));
@@ -231,7 +207,7 @@ export function buildTfs(filters: TfsFilters, options: BuildTfsOptions = {}): st
return encodeTfsPayload(segments, {
isOneWay: filters.trip_type === TripType.ONE_WAY,
- passengers: passengers.length > 0 ? passengers : [1],
+ passengers,
seat: filters.seat_type,
});
}
diff --git a/fli-js/tests/search/flights_booking_url.test.ts b/fli-js/tests/search/flights_booking_url.test.ts
index cebe872..e7c2055 100644
--- a/fli-js/tests/search/flights_booking_url.test.ts
+++ b/fli-js/tests/search/flights_booking_url.test.ts
@@ -12,9 +12,11 @@ import { Airport } from "../../src/models/airport.ts";
import {
type FlightLeg,
type FlightResult,
+ type PassengerInfo,
SeatType,
} from "../../src/models/google-flights/base.ts";
import { SearchFlights } from "../../src/search/flights.ts";
+import { _readVarint } from "../../src/search/proto.ts";
/** Build a leg with a LOCAL departure datetime (matches the decoder). */
function makeLeg(
@@ -213,4 +215,67 @@ describe("buildFlightBookingUrl", () => {
const raw = tfsBytes(business);
expect(Buffer.from(raw).includes(Buffer.from([0x48, 0x03]))).toBe(true);
});
+
+ /** Walk the top-level message and collect every field-8 (passenger) code. */
+ function field8Codes(raw: Uint8Array): number[] {
+ const codes: number[] = [];
+ let offset = 0;
+ while (offset < raw.length) {
+ const [tagVal, afterTag] = _readVarint(raw, offset);
+ offset = afterTag;
+ const field = tagVal >> 3;
+ const wire = tagVal & 0x7;
+ if (wire === 0) {
+ const [value, afterVal] = _readVarint(raw, offset);
+ offset = afterVal;
+ if (field === 8) codes.push(value);
+ } else if (wire === 2) {
+ const [length, afterLen] = _readVarint(raw, offset);
+ offset = afterLen + length;
+ } else {
+ throw new Error(`unexpected wire type ${wire} at offset ${offset}`);
+ }
+ }
+ return codes;
+ }
+
+ test("passengerInfo defaults to a single adult (field 8 = [1])", () => {
+ const raw = tfsBytes(search.buildFlightBookingUrl(oneWay()));
+ expect(field8Codes(raw)).toEqual([1]);
+ });
+
+ test("passengerInfo family mix encodes one field-8 entry per traveller", () => {
+ const passengerInfo: PassengerInfo = {
+ adults: 2,
+ children: 1,
+ infants_in_seat: 0,
+ infants_on_lap: 0,
+ };
+ const raw = tfsBytes(search.buildFlightBookingUrl(oneWay(), { passengerInfo }));
+ expect(field8Codes(raw)).toEqual([1, 1, 2]);
+ });
+
+ test("garbage passengerInfo still returns a URL (never throws)", () => {
+ const url = search.buildFlightBookingUrl(oneWay(), {
+ passengerInfo: "not-a-passenger-info" as unknown as PassengerInfo,
+ });
+ expect(typeof url).toBe("string");
+ expect(url.startsWith("https://www.google.com/travel/flights/booking?tfs=")).toBe(true);
+ });
+
+ test("a duck-typed count in the millions falls back quickly, not after building a giant token", () => {
+ // passengerCodes rejects a count this large before building any array,
+ // so the existing catch-all below still returns the generic fallback
+ // URL — quickly, not after tens of seconds spent building a
+ // multi-megabyte token.
+ const start = performance.now();
+ const url = search.buildFlightBookingUrl(oneWay(), {
+ passengerInfo: { adults: 1_000_000 } as PassengerInfo,
+ });
+ const elapsed = performance.now() - start;
+
+ expect(elapsed).toBeLessThan(1000);
+ expect(url.length).toBeLessThan(200);
+ expect(url.startsWith("https://www.google.com/travel/flights")).toBe(true);
+ });
});
diff --git a/fli-js/tests/search/proto.test.ts b/fli-js/tests/search/proto.test.ts
index 3e8d916..36e8535 100644
--- a/fli-js/tests/search/proto.test.ts
+++ b/fli-js/tests/search/proto.test.ts
@@ -7,6 +7,7 @@
import { describe, expect, test } from "bun:test";
import { Buffer } from "node:buffer";
+import type { PassengerInfo } from "../../src/models/google-flights/base.ts";
import {
_readVarint,
buildBookingToken,
@@ -15,6 +16,7 @@ import {
extractBookingTokenFromTfu,
extractSessionIdFromTfu,
type LegSpec,
+ passengerCodes,
} from "../../src/search/proto.ts";
// Captured live 2026-05-14 (JFK → LAX outbound AA171, return AA28, RT $346.80).
@@ -375,4 +377,139 @@ describe("buildTfsToken", () => {
expect(Buffer.from(business).includes(Buffer.from([0x48, 0x03]))).toBe(true);
expect(Buffer.from(economy).equals(Buffer.from(business))).toBe(false);
});
+
+ /** Walk the top-level message and collect every field-8 (passenger) code. */
+ function field8Codes(raw: Uint8Array): number[] {
+ const codes: number[] = [];
+ let offset = 0;
+ while (offset < raw.length) {
+ const [tagVal, afterTag] = _readVarint(raw, offset);
+ offset = afterTag;
+ const field = tagVal >> 3;
+ const wire = tagVal & 0x7;
+ if (wire === 0) {
+ const [value, afterVal] = _readVarint(raw, offset);
+ offset = afterVal;
+ if (field === 8) codes.push(value);
+ } else if (wire === 2) {
+ const [length, afterLen] = _readVarint(raw, offset);
+ offset = afterLen + length;
+ } else {
+ throw new Error(`unexpected wire type ${wire} at offset ${offset}`);
+ }
+ }
+ return codes;
+ }
+
+ test("passengers defaults to a single adult", () => {
+ const built = buildTfsToken([
+ [{ origin: "SFO", depDate: "2026-09-01", dest: "PHX", airline: "AA", flightNumber: "100" }],
+ ]);
+ expect(field8Codes(tfsBytes(built))).toEqual([1]);
+ });
+
+ test("passengers=[1,1,2] (2 adults, 1 child) encodes one entry per traveller", () => {
+ const built = buildTfsToken(
+ [[{ origin: "SFO", depDate: "2026-09-01", dest: "PHX", airline: "AA", flightNumber: "100" }]],
+ { passengers: [1, 1, 2] },
+ );
+ expect(field8Codes(tfsBytes(built))).toEqual([1, 1, 2]);
+ });
+
+ test("passengers do not disturb the seat or trip-type fields", () => {
+ const segs: LegSpec[][] = [
+ [{ origin: "SFO", depDate: "2026-09-01", dest: "PHX", airline: "AA", flightNumber: "100" }],
+ ];
+ const built = buildTfsToken(segs, { passengers: [1, 1, 2], seat: 3 });
+ const raw = tfsBytes(built);
+ const text = Buffer.from(raw);
+ // Three f8 entries, then f9=3 (business), then f14=1 — same layout as
+ // the single-passenger case, just with more f8 entries ahead of f9.
+ expect(
+ text.includes(Buffer.from([0x40, 0x01, 0x40, 0x01, 0x40, 0x02, 0x48, 0x03, 0x70, 0x01])),
+ ).toBe(true);
+ // f19 (trip type) is unaffected by the passenger count.
+ expect(Array.from(raw.slice(-3))).toEqual([0x98, 0x01, 0x02]);
+ });
+});
+
+describe("passengerCodes", () => {
+ // Maps a PassengerInfo to `tfs` field-8 codes — extracted out of
+ // `tfs.ts::buildTfs` so the search token and the booking token
+ // (buildTfsToken) cannot drift on how they encode the passenger mix.
+
+ test("family mix", () => {
+ expect(passengerCodes({ adults: 2, children: 1, infants_on_lap: 1 })).toEqual([1, 1, 2, 3]);
+ });
+
+ test("infant in seat is code 4", () => {
+ expect(passengerCodes({ adults: 1, infants_in_seat: 1 })).toEqual([1, 4]);
+ });
+
+ test("null/undefined defaults to a single adult", () => {
+ expect(passengerCodes(null)).toEqual([1]);
+ expect(passengerCodes(undefined)).toEqual([1]);
+ });
+
+ test("object with no passenger fields defaults to a single adult", () => {
+ expect(passengerCodes({})).toEqual([1]);
+ });
+
+ test("exactly nine travellers is accepted", () => {
+ const info = { adults: 4, children: 2, infants_in_seat: 2, infants_on_lap: 1 };
+ expect(passengerCodes(info)).toHaveLength(9);
+ });
+
+ test("ten travellers, one over the ceiling, throws", () => {
+ expect(() => passengerCodes({ adults: 10, children: 0 })).toThrow(RangeError);
+ });
+
+ test("ten travellers spread across two fields throws", () => {
+ expect(() => passengerCodes({ adults: 5, children: 5 })).toThrow(RangeError);
+ });
+
+ test("a negative count throws, naming the field", () => {
+ expect(() => passengerCodes({ adults: -1 })).toThrow(/adults/);
+ });
+
+ test.each([2.5, "3", true])("a non-integer count (%p) throws", (bad) => {
+ expect(() => passengerCodes({ adults: bad as unknown as number })).toThrow(RangeError);
+ });
+
+ test("a duck-typed count in the millions throws immediately, not after building a list", () => {
+ // Before this guard, an `adults: 1_000_000`-shaped object made this
+ // function (and everything downstream, including the booking token)
+ // spend tens of seconds building a multi-megabyte array instead of
+ // rejecting the obviously-impossible count up front.
+ const start = performance.now();
+ expect(() => passengerCodes({ adults: 1_000_000 })).toThrow(RangeError);
+ expect(performance.now() - start).toBeLessThan(1000);
+ });
+});
+
+describe("passengerCodes accept/reject table", () => {
+ // Same table as Python's `TestPassengerCodesAcceptRejectTable` in
+ // tests/search/test_proto.py — both languages must reach the same
+ // accept/reject verdict for each row. Keep the two in sync.
+ const cases: Array<[string, { adults: unknown; children?: unknown }, boolean]> = [
+ ["baseline single adult", { adults: 1 }, true],
+ ["all-zero mix still books one adult", { adults: 0, children: 0 }, true],
+ ["exactly Google's ceiling", { adults: 9 }, true],
+ ["one over the ceiling", { adults: 10 }, false],
+ ["ceiling crossed by summing two fields", { adults: 5, children: 5 }, false],
+ ["negative count", { adults: -1 }, false],
+ ["non-integer count (float)", { adults: 2.5 }, false],
+ ["non-integer count (numeric string)", { adults: "3" }, false],
+ ["boolean count", { adults: true }, false],
+ ];
+
+ for (const [label, info, accepted] of cases) {
+ test(`${label} -> ${accepted ? "accepted" : "rejected"}`, () => {
+ if (accepted) {
+ expect(() => passengerCodes(info as Partial<PassengerInfo>)).not.toThrow();
+ } else {
+ expect(() => passengerCodes(info as Partial<PassengerInfo>)).toThrow(RangeError);
+ }
+ });
+ }
});
diff --git a/fli-js/tests/search/tfs.test.ts b/fli-js/tests/search/tfs.test.ts
index 4f56fd3..daae2a9 100644
--- a/fli-js/tests/search/tfs.test.ts
+++ b/fli-js/tests/search/tfs.test.ts
@@ -30,6 +30,7 @@ import { FlightSearchFilters } from "../../src/models/google-flights/flights.ts"
import { Client } from "../../src/search/client.ts";
import { SearchUnsupportedError } from "../../src/search/exceptions.ts";
import { setSearchLogger } from "../../src/search/logging.ts";
+import { buildTfsToken, passengerCodes as passengerCodesFromInfo } from "../../src/search/proto.ts";
import {
_setPageRetrySleep,
applyClientSideFilters,
@@ -642,6 +643,27 @@ describe("passenger wire codes", () => {
});
});
+describe("passenger codes parity with buildTfsToken", () => {
+ // Drift guard: buildTfs (search token) and buildTfsToken (booking-URL
+ // token) must encode the identical field-8 sequence for the same
+ // PassengerInfo — both are built from proto.ts's passengerCodes helper.
+ test("family mix matches between the search token and the booking token", () => {
+ const info = pax({ adults: 2, children: 1, infants_on_lap: 1 });
+ const spec = filters([[["JFK"], ["LAX"], OUT]], { passenger_info: info });
+ const searchCodes = passengerCodes(buildTfs(spec));
+
+ const bookingToken = buildTfsToken(
+ [[{ origin: "JFK", depDate: OUT, dest: "LAX", airline: "AA", flightNumber: "171" }]],
+ { passengers: passengerCodesFromInfo(info) },
+ );
+ const bookingCodes = passengerCodes(bookingToken);
+
+ expect(searchCodes).toEqual([1, 1, 2, 3]);
+ expect(bookingCodes).toEqual([1, 1, 2, 3]);
+ expect(searchCodes).toEqual(bookingCodes);
+ });
+});
+
describe("pageUrl", () => {
test("includes locale and currency", () => {
const url = pageUrl("TFS", "EUR", "de", "DE");
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index 54224be..d2b941b 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -248,6 +248,7 @@ def _search_flights_core(
language=language,
country=country,
seat_type=seat_type,
+ passenger_info=filters.passenger_info,
)
for result in results
]
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index 8a93728..104c033 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -745,6 +745,7 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
language=params.language,
country=params.country,
seat_type=filters.seat_type,
+ passenger_info=filters.passenger_info,
),
)
for f in flights
@@ -857,6 +858,7 @@ def _execute_booking_options(
language=params.language,
country=params.country,
seat_type=filters.seat_type,
+ passenger_info=filters.passenger_info,
)
serialized = [_serialize_booking_option(o) for o in options]
result = {
diff --git a/fli/search/_proto.py b/fli/search/_proto.py
index 7c2ce8c..627ebea 100644
--- a/fli/search/_proto.py
+++ b/fli/search/_proto.py
@@ -35,6 +35,7 @@ import base64
import logging
from collections.abc import Sequence
from dataclasses import dataclass
+from typing import Any
logger = logging.getLogger(__name__)
@@ -264,6 +265,80 @@ def _to_urlsafe_b64(data: bytes) -> str:
_MAX_U64 = (1 << 64) - 1
+# Passenger kinds, in the order Google's repeated field 8 numbers them:
+# 1 = adult, 2 = child, 3 = infant on lap, 4 = infant in own seat.
+#
+# The two infant codes are easy to transpose and the mistake is expensive
+# rather than loud: on an international route a lap infant prices at ~10% of
+# the adult fare and an infant in its own seat at ~100%, so a swap quotes a
+# plausible but wrong fare instead of erroring. Pricing one fixed itinerary
+# (BA178 JFK->LHR, economy) confirms the mapping — $295 for ``[1]``, $324 for
+# ``[1, 3]`` (+10%, lap), $589 for ``[1, 4]`` (+100%, own seat, same as the
+# ``[1, 2]`` child fare). The legacy RPC struct orders the same four counts
+# ``[adults, children, infants_on_lap, infants_in_seat]``; see
+# ``FlightSearchFilters.format`` in :mod:`fli.models.google_flights.flights`.
+_PASSENGER_FIELDS = ("adults", "children", "infants_on_lap", "infants_in_seat")
+
+# Google's own per-booking limit — the same ceiling ``PassengerInfo`` enforces
+# in ``validate_passenger_counts`` (``fli.models.google_flights.base``).
+# ``PassengerInfo`` has no public constant for it (just the literal in that
+# validator), so this is a second copy of the same number rather than an
+# import; keep the two in sync if Google's limit ever changes.
+_MAX_TOTAL_PASSENGERS = 9
+
+
+def passenger_codes(passenger_info: Any) -> list[int]:
+ """Convert a ``PassengerInfo`` into ``tfs`` field-8 codes, one per traveller.
+
+ Shared by :func:`fli.search._tfs.build_tfs` (the search token) and
+ :func:`build_tfs_token` (the per-flight booking token) so the two cannot
+ drift on how they encode the passenger mix — see ``_PASSENGER_FIELDS``
+ above for why getting the codes right (especially the two infant kinds)
+ matters.
+
+ Args:
+ passenger_info: A ``PassengerInfo``, or any duck-typed object
+ exposing some subset of ``adults``/``children``/
+ ``infants_on_lap``/``infants_in_seat`` as attributes (missing
+ ones count as zero). ``None`` is treated as an all-zero mix.
+
+ Returns:
+ One code per traveller, in field order. Falls back to ``[1]`` (a
+ single adult) when the mix would otherwise be empty — Google's
+ booking page requires at least one traveller, and that is also the
+ implicit default callers got before this helper existed.
+
+ Raises:
+ ValueError: Any count is not a non-negative ``int`` (``bool``
+ included — it is an ``int`` subclass but not a traveller count),
+ or the total exceeds :data:`_MAX_TOTAL_PASSENGERS`. Checked
+ before building the result list, so a wildly out-of-range count
+ (a duck-typed ``adults=10**6``, say) fails immediately instead of
+ allocating a list that size — callers that pass a validated
+ ``PassengerInfo`` never hit this; it exists for the duck-typed
+ callers this function otherwise tolerates.
+
+ """
+ total = 0
+ counts: list[tuple[int, int]] = [] # (code, count), one pair per field
+ for kind, code in zip(_PASSENGER_FIELDS, (1, 2, 3, 4), strict=False):
+ count = getattr(passenger_info, kind, 0)
+ # `bool` is a subclass of `int` in Python, so `isinstance(True, int)`
+ # is true — excluded explicitly, since `True` is not a traveller count.
+ if not isinstance(count, int) or isinstance(count, bool) or count < 0:
+ raise ValueError(f"passenger_info.{kind} must be a non-negative int, got {count!r}")
+ total += count
+ counts.append((code, count))
+
+ if total > _MAX_TOTAL_PASSENGERS:
+ raise ValueError(
+ f"passenger_info totals {total} travellers, over the "
+ f"{_MAX_TOTAL_PASSENGERS}-traveller limit Google's booking page enforces"
+ )
+
+ codes = [code for code, count in counts for _ in range(count)]
+ return codes or [1]
+
def encode_tfs_segment(
origin: str,
@@ -351,8 +426,8 @@ def encode_tfs_payload(
seat). The two infant codes are the ones to get right: a lap
infant prices at ~10% of the adult fare and an infant in its own
seat at ~100%, and transposing them produces a plausible wrong
- quote rather than an error. See ``_PASSENGER_FIELDS`` in
- :mod:`fli.search._tfs` for the live fare evidence.
+ quote rather than an error. See ``_PASSENGER_FIELDS`` above (and
+ :func:`passenger_codes`) for the live fare evidence.
seat: Cabin class (1 = economy, 2 = premium, 3 = business, 4 = first).
pin_max_u64: Emit the field 16 constant that booking deep links
carry. The search page does not need it.
@@ -375,6 +450,7 @@ def build_tfs_token(
segments: list[list[LegSpec]],
*,
is_one_way: bool = True,
+ passengers: Sequence[int] = (1,),
seat: int = 1,
) -> str:
"""Build the ``tfs`` query parameter for a Google Flights deep-link URL.
@@ -394,6 +470,10 @@ def build_tfs_token(
direction (one leg for nonstop, two or more for connections).
is_one_way: ``True`` for one-way; ``False`` for round-trip.
Controls the ``f19`` constant.
+ passengers: Passenger kind codes, one entry per traveller (field 8).
+ Build these from a search's ``PassengerInfo`` with
+ :func:`passenger_codes`. Defaults to a single adult so existing
+ callers keep producing the captured tokens.
seat: Cabin class encoded in field 9. ``1`` = economy, ``2`` =
premium economy, ``3`` = business, ``4`` = first. Defaults to
economy so existing callers keep producing the captured tokens.
@@ -416,4 +496,6 @@ def build_tfs_token(
encode_tfs_segment(seg[0].origin, seg[-1].dest, seg[0].dep_date, legs=seg)
for seg in segments
)
- return encode_tfs_payload(encoded, is_one_way=is_one_way, seat=seat, pin_max_u64=True)
+ return encode_tfs_payload(
+ encoded, is_one_way=is_one_way, passengers=passengers, seat=seat, pin_max_u64=True
+ )
diff --git a/fli/search/_tfs.py b/fli/search/_tfs.py
index 50258c0..498048e 100644
--- a/fli/search/_tfs.py
+++ b/fli/search/_tfs.py
@@ -37,7 +37,7 @@ import time
from typing import TYPE_CHECKING, Any
from fli.models.google_flights.base import TripType
-from fli.search._proto import LegSpec, encode_tfs_payload, encode_tfs_segment
+from fli.search._proto import LegSpec, encode_tfs_payload, encode_tfs_segment, passenger_codes
from fli.search.exceptions import SearchUnsupportedError
if TYPE_CHECKING:
@@ -69,20 +69,6 @@ _DS_BLOB = re.compile(r"AF_initDataCallback\((\{.*?\})\);", re.S)
_DS_KEY = re.compile(r"key:\s*'([^']+)'")
_DS_DATA = re.compile(r"data:(.*?), sideChannel", re.S)
-# Passenger kinds, in the order Google's repeated field 8 numbers them:
-# 1 = adult, 2 = child, 3 = infant on lap, 4 = infant in own seat.
-#
-# The two infant codes are easy to transpose and the mistake is expensive
-# rather than loud: on an international route a lap infant prices at ~10% of
-# the adult fare and an infant in its own seat at ~100%, so a swap quotes a
-# plausible but wrong fare instead of erroring. Pricing one fixed itinerary
-# (BA178 JFK->LHR, economy) confirms the mapping — $295 for ``[1]``, $324 for
-# ``[1, 3]`` (+10%, lap), $589 for ``[1, 4]`` (+100%, own seat, same as the
-# ``[1, 2]`` child fare). The legacy RPC struct orders the same four counts
-# ``[adults, children, infants_on_lap, infants_in_seat]``; see
-# ``FlightSearchFilters.format`` in :mod:`fli.models.google_flights.flights`.
-_PASSENGER_FIELDS = ("adults", "children", "infants_on_lap", "infants_in_seat")
-
# Filters with no ``tfs`` encoding and no reliable post-hoc equivalent —
# the decoded rows don't carry the data needed to apply them locally.
_UNSUPPORTED = (
@@ -145,11 +131,7 @@ def build_tfs(filters: Any, *, travel_dates: list[str] | None = None) -> str:
)
stops = filters.stops.value
- passengers = [
- code
- for kind, code in zip(_PASSENGER_FIELDS, (1, 2, 3, 4), strict=False)
- for _ in range(getattr(filters.passenger_info, kind, 0))
- ]
+ passengers = passenger_codes(filters.passenger_info)
# Google reads alliances out of the same carrier lists as airline codes.
carriers = [a.value for a in (getattr(filters, "alliances", None) or [])]
@@ -177,7 +159,7 @@ def build_tfs(filters: Any, *, travel_dates: list[str] | None = None) -> str:
return encode_tfs_payload(
segments,
is_one_way=filters.trip_type == TripType.ONE_WAY,
- passengers=passengers or [1],
+ passengers=passengers,
seat=filters.seat_type.value,
)
diff --git a/fli/search/flights.py b/fli/search/flights.py
index b7d1c52..70294cf 100644
--- a/fli/search/flights.py
+++ b/fli/search/flights.py
@@ -19,6 +19,7 @@ from fli.models import (
BookingOption,
FlightResult,
FlightSearchFilters,
+ PassengerInfo,
SeatType,
)
from fli.models.google_flights.base import SortBy, TripType
@@ -405,6 +406,7 @@ class SearchFlights:
language: str | None = None,
country: str | None = None,
seat_type: SeatType = SeatType.ECONOMY,
+ passenger_info: PassengerInfo | None = None,
) -> str:
"""Build a Google Flights deep-link URL for a specific itinerary.
@@ -427,12 +429,16 @@ class SearchFlights:
country: ISO 3166-1 alpha-2 country code appended as ``gl=``.
seat_type: Cabin class encoded into the ``tfs`` token (field 9).
Defaults to economy for backward compatibility.
+ passenger_info: Passenger mix encoded into the ``tfs`` token
+ (field 8, one entry per traveller). ``None`` defaults to a
+ single adult, matching this method's output before this
+ parameter existed.
Returns:
A ``https://www.google.com/travel/flights/booking?tfs=…`` URL.
"""
- from fli.search._proto import LegSpec, build_tfs_token
+ from fli.search._proto import LegSpec, build_tfs_token, passenger_codes
def _iata(airport: object) -> str:
# Handle both Airport enum (has .name) and plain strings.
@@ -455,7 +461,12 @@ class SearchFlights:
for leg in result.legs
]
segments.append(seg_legs)
- tfs = build_tfs_token(segments, is_one_way=is_one_way, seat=seat_type.value)
+ tfs = build_tfs_token(
+ segments,
+ is_one_way=is_one_way,
+ passengers=passenger_codes(passenger_info),
+ seat=seat_type.value,
+ )
url = f"https://www.google.com/travel/flights/booking?tfs={tfs}"
except Exception:
logger.debug("build_flight_booking_url: tfs construction failed", exc_info=True)
diff --git a/tests/cli/test_flights.py b/tests/cli/test_flights.py
index 4f9acb4..29ccae7 100644
--- a/tests/cli/test_flights.py
+++ b/tests/cli/test_flights.py
@@ -112,6 +112,15 @@ def test_flights_with_family_passenger_mix(runner, mock_search_flights, mock_con
assert args[0].passenger_info.children == 1
assert args[0].passenger_info.infants_in_seat == 1
assert args[0].passenger_info.infants_on_lap == 1
+ # The same passenger mix must reach the per-flight booking deep link —
+ # otherwise the family sees a family-priced result but a single-adult
+ # booking page.
+ mock_search_flights.build_flight_booking_url.assert_called()
+ _, kwargs = mock_search_flights.build_flight_booking_url.call_args
+ assert kwargs["passenger_info"].adults == 2
+ assert kwargs["passenger_info"].children == 1
+ assert kwargs["passenger_info"].infants_in_seat == 1
+ assert kwargs["passenger_info"].infants_on_lap == 1
def test_flights_json_query_echoes_full_passenger_mix(runner, mock_search_flights, mock_console):
@@ -143,6 +152,89 @@ def test_flights_json_query_echoes_full_passenger_mix(runner, mock_search_flight
assert payload["query"]["infants_on_lap"] == 1
+def _field_8_codes(raw: bytes) -> list[int]:
+ """Walk the top-level tfs message and collect every field-8 (passenger) code."""
+ from fli.search._proto import _read_varint
+
+ codes: list[int] = []
+ offset = 0
+ while offset < len(raw):
+ tag, offset = _read_varint(raw, offset)
+ field, wire = tag >> 3, tag & 0x7
+ if wire == 0:
+ value, offset = _read_varint(raw, offset)
+ if field == 8:
+ codes.append(value)
+ elif wire == 2:
+ length, offset = _read_varint(raw, offset)
+ offset += length
+ else: # pragma: no cover - the encoder emits only wire types 0 and 2
+ raise AssertionError(f"unexpected wire type {wire} at offset {offset}")
+ return codes
+
+
+def test_flights_json_booking_url_token_decodes_to_the_requested_mix(
+ runner, mock_console, monkeypatch
+):
+ """One un-patched assertion: decode the real tfs token in --format json output.
+
+ Every other CLI passenger-mix test uses ``mock_search_flights``, which
+ replaces the whole ``SearchFlights`` instance (``build_flight_booking_url``
+ included) and only checks the kwargs a mock recorded. Here only
+ ``SearchFlights.search`` is stubbed, so ``build_flight_booking_url`` runs
+ for real and produces an actual token — a bug in the token builder
+ itself, not just in how the CLI calls it, would be caught here too.
+ """
+ import base64
+ import urllib.parse
+
+ from fli.search.flights import SearchFlights
+
+ departure = datetime.now() + timedelta(days=30)
+ flight = FlightResult(
+ price=299.99,
+ currency="USD",
+ duration=360,
+ stops=0,
+ legs=[
+ FlightLeg(
+ airline=Airline.DL,
+ flight_number="123",
+ departure_airport=Airport.JFK,
+ arrival_airport=Airport.LAX,
+ departure_datetime=departure,
+ arrival_datetime=departure + timedelta(hours=6),
+ duration=360,
+ )
+ ],
+ )
+ monkeypatch.setattr(SearchFlights, "search", lambda self, *a, **k: [flight])
+
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LAX",
+ departure.strftime("%Y-%m-%d"),
+ "--passengers",
+ "2",
+ "--children",
+ "1",
+ "--format",
+ "json",
+ ],
+ )
+ assert result.exit_code == 0
+ payload = json.loads(result.stdout)
+ booking_url = payload["flights"][0]["booking_url"]
+
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(booking_url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ raw = base64.urlsafe_b64decode(tfs + pad)
+ assert _field_8_codes(raw) == [1, 1, 2]
+
+
def test_flights_invalid_passenger_mix_exits_nonzero_with_clean_message(
runner, mock_search_flights, mock_console
):
diff --git a/tests/mcp/test_mcp_server_unit.py b/tests/mcp/test_mcp_server_unit.py
index 6aefaf4..07de36e 100644
--- a/tests/mcp/test_mcp_server_unit.py
+++ b/tests/mcp/test_mcp_server_unit.py
@@ -45,6 +45,27 @@ def _make_raiser(exc: BaseException):
return _raiser
+def _field_8_codes(raw: bytes) -> list[int]:
+ """Walk the top-level tfs message and collect every field-8 (passenger) code."""
+ from fli.search._proto import _read_varint
+
+ codes: list[int] = []
+ offset = 0
+ while offset < len(raw):
+ tag, offset = _read_varint(raw, offset)
+ field, wire = tag >> 3, tag & 0x7
+ if wire == 0:
+ value, offset = _read_varint(raw, offset)
+ if field == 8:
+ codes.append(value)
+ elif wire == 2:
+ length, offset = _read_varint(raw, offset)
+ offset += length
+ else: # pragma: no cover - the encoder emits only wire types 0 and 2
+ raise AssertionError(f"unexpected wire type {wire} at offset {offset}")
+ return codes
+
+
class TestAirlineCode:
def test_enum_with_leading_underscore_stripped(self):
airline = MagicMock()
@@ -511,6 +532,84 @@ class TestSearchReturnsBookingUrl:
"https://www.google.com/travel/flights/booking?tfs=TEST"
)
+ def test_per_flight_booking_url_carries_search_passenger_mix(self, monkeypatch, params):
+ """A family search's passenger_info reaches build_flight_booking_url.
+
+ Otherwise the flights array shows a family-priced result but every
+ booking_url opens Google's page priced for a single adult.
+ """
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ captured_kwargs: dict = {}
+
+ def _capture(self, f, **kw):
+ captured_kwargs.update(kw)
+ return "https://www.google.com/travel/flights/booking?tfs=TEST"
+
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.build_flight_booking_url", _capture)
+
+ family_params = params.model_copy(
+ update={"passengers": 2, "children": 1, "infants_on_lap": 1}
+ )
+ result = _execute_flight_search(family_params)
+ assert result["success"] is True
+ passenger_info = captured_kwargs["passenger_info"]
+ assert passenger_info.adults == 2
+ assert passenger_info.children == 1
+ assert passenger_info.infants_on_lap == 1
+
+ def test_booking_url_token_decodes_to_the_requested_mix(self, monkeypatch, params):
+ """One un-patched assertion: decode the real booking_url token.
+
+ Every other passenger-mix test at this layer monkeypatches
+ ``build_flight_booking_url`` and asserts on the captured
+ ``PassengerInfo`` object. Here only ``SearchFlights.search`` is
+ stubbed, so ``build_flight_booking_url`` runs for real and produces
+ an actual ``tfs`` token — a bug in the token builder itself, not
+ just in how this call site passes ``passenger_info``, would be
+ caught here too.
+ """
+ import base64
+ import urllib.parse
+ from datetime import datetime
+
+ from fli.models import Airline, Airport, FlightLeg, FlightResult
+
+ flight = FlightResult(
+ price=342.0,
+ currency="USD",
+ duration=420,
+ stops=0,
+ legs=[
+ FlightLeg(
+ airline=Airline.BA,
+ flight_number="178",
+ departure_airport=Airport.JFK,
+ arrival_airport=Airport.LHR,
+ departure_datetime=datetime(2026, 12, 1, 20, 30),
+ arrival_datetime=datetime(2026, 12, 2, 8, 30),
+ duration=420,
+ )
+ ],
+ )
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ family_params = params.model_copy(update={"passengers": 2, "children": 1})
+
+ result = _execute_flight_search(family_params)
+ assert result["success"] is True
+ booking_url = result["flights"][0]["booking_url"]
+
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(booking_url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ raw = base64.urlsafe_b64decode(tfs + pad)
+ assert _field_8_codes(raw) == [1, 1, 2]
+
def test_top_level_search_booking_url_still_present(self, monkeypatch, params):
"""The top-level search booking_url (q= link) is kept alongside per-flight links."""
flight = _make_bookable_flight()
@@ -578,6 +677,32 @@ class TestExecuteBookingOptions:
"https://www.google.com/travel/flights/booking?tfs=SEL"
)
+ def test_selected_flight_booking_url_carries_search_passenger_mix(self, monkeypatch, params):
+ """get_booking_options forwards the search's passenger_info too."""
+ flight = _make_bookable_flight()
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.search",
+ lambda self, *a, **k: [flight],
+ )
+ monkeypatch.setattr(
+ "fli.mcp.server.SearchFlights.get_booking_options",
+ lambda self, *a, **k: [_make_option_helper()],
+ )
+ captured_kwargs: dict = {}
+
+ def _capture(self, f, **kw):
+ captured_kwargs.update(kw)
+ return "https://www.google.com/travel/flights/booking?tfs=SEL"
+
+ monkeypatch.setattr("fli.mcp.server.SearchFlights.build_flight_booking_url", _capture)
+
+ family_params = params.model_copy(update={"passengers": 2, "children": 1})
+ result = _execute_booking_options(family_params, ["BA178"])
+ assert result["success"] is True
+ passenger_info = captured_kwargs["passenger_info"]
+ assert passenger_info.adults == 2
+ assert passenger_info.children == 1
+
def test_no_match_lists_available_flights(self, monkeypatch, params):
flight = _make_bookable_flight()
monkeypatch.setattr(
diff --git a/tests/search/test_booking_url.py b/tests/search/test_booking_url.py
index 6c49a92..96bdf31 100644
--- a/tests/search/test_booking_url.py
+++ b/tests/search/test_booking_url.py
@@ -261,3 +261,78 @@ class TestBuildFlightBookingUrl:
business = _raw(business_url)
assert b"\x40\x01\x48\x03\x70\x01" in business
assert b"\x40\x01\x48\x01\x70\x01" not in business
+
+ def _field_8_codes(self, raw: bytes) -> list[int]:
+ """Walk the top-level message and collect every field-8 (passenger) code."""
+ from fli.search._proto import _read_varint
+
+ codes: list[int] = []
+ offset = 0
+ while offset < len(raw):
+ tag, offset = _read_varint(raw, offset)
+ field, wire = tag >> 3, tag & 0x7
+ if wire == 0:
+ value, offset = _read_varint(raw, offset)
+ if field == 8:
+ codes.append(value)
+ elif wire == 2:
+ length, offset = _read_varint(raw, offset)
+ offset += length
+ else: # pragma: no cover - the encoder emits only wire types 0 and 2
+ raise AssertionError(f"unexpected wire type {wire} at offset {offset}")
+ return codes
+
+ def test_passenger_info_defaults_to_single_adult(self):
+ """Omitted passenger_info still encodes field 8 as one adult (1)."""
+ import base64
+
+ client = _make_client()
+ url = client.build_flight_booking_url(_one_way())
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ raw = base64.urlsafe_b64decode(tfs + pad)
+ assert self._field_8_codes(raw) == [1]
+
+ def test_passenger_info_family_mix_encodes_one_entry_per_traveller(self):
+ """A family PassengerInfo's decoded tfs token carries one field-8 code per traveller."""
+ import base64
+
+ from fli.models import PassengerInfo
+
+ client = _make_client()
+ url = client.build_flight_booking_url(
+ _one_way(), passenger_info=PassengerInfo(adults=2, children=1)
+ )
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ raw = base64.urlsafe_b64decode(tfs + pad)
+ assert self._field_8_codes(raw) == [1, 1, 2]
+
+ def test_garbage_passenger_info_still_returns_url(self):
+ """A malformed passenger_info degrades to a single adult, never raises."""
+ client = _make_client()
+ url = client.build_flight_booking_url(_one_way(), passenger_info="not-a-passenger-info")
+ assert isinstance(url, str)
+ assert url.startswith("https://www.google.com/travel/flights/booking?tfs=")
+
+ def test_huge_duck_typed_count_falls_back_quickly(self):
+ """An out-of-range duck-typed count must not build a multi-megabyte URL.
+
+ ``passenger_codes`` rejects a count this large before building any
+ list, so the existing broad ``except Exception`` here still returns
+ the generic fallback URL — quickly, not after seconds spent building
+ a list with a million entries.
+ """
+ import time
+
+ class _Duck:
+ adults = 10**6
+
+ client = _make_client()
+ start = time.monotonic()
+ url = client.build_flight_booking_url(_one_way(), passenger_info=_Duck())
+ elapsed = time.monotonic() - start
+
+ assert elapsed < 1.0
+ assert len(url) < 200
+ assert url.startswith("https://www.google.com/travel/flights")
diff --git a/tests/search/test_proto.py b/tests/search/test_proto.py
index d724a59..7443055 100644
--- a/tests/search/test_proto.py
+++ b/tests/search/test_proto.py
@@ -320,6 +320,203 @@ class TestBuildTfsToken:
assert b"\x48\x03" not in economy
assert economy != business
+ def _field_8_codes(self, raw: bytes) -> list[int]:
+ """Walk the top-level message and collect every field-8 (passenger) code.
+
+ Mirrors ``_passenger_codes`` in ``tests/search/test_tfs.py`` — a proper
+ walk instead of scanning for the 0x40 tag byte, which also occurs
+ inside length-delimited payloads (e.g. flight numbers).
+ """
+ from fli.search._proto import _read_varint
+
+ codes: list[int] = []
+ offset = 0
+ while offset < len(raw):
+ tag, offset = _read_varint(raw, offset)
+ field, wire = tag >> 3, tag & 0x7
+ if wire == 0:
+ value, offset = _read_varint(raw, offset)
+ if field == 8:
+ codes.append(value)
+ elif wire == 2:
+ length, offset = _read_varint(raw, offset)
+ offset += length
+ else: # pragma: no cover - the encoder emits only wire types 0 and 2
+ raise AssertionError(f"unexpected wire type {wire} at offset {offset}")
+ return codes
+
+ def test_passengers_defaults_to_single_adult(self):
+ """Omitted ``passengers`` still encodes field 8 as one adult (1)."""
+ built = build_tfs_token([[LegSpec("SFO", "2026-09-01", "PHX", "AA", "100")]])
+ raw = _b64url_to_bytes(built)
+ assert self._field_8_codes(raw) == [1]
+
+ def test_passengers_family_mix_encodes_one_entry_per_traveller(self):
+ """``passengers=(1, 1, 2)`` (2 adults, 1 child) encodes three field-8 entries."""
+ built = build_tfs_token(
+ [[LegSpec("SFO", "2026-09-01", "PHX", "AA", "100")]],
+ passengers=(1, 1, 2),
+ )
+ raw = _b64url_to_bytes(built)
+ assert self._field_8_codes(raw) == [1, 1, 2]
+
+ def test_passengers_do_not_disturb_seat_or_trip_type_fields(self):
+ """Field 9 (seat) and field 19 (trip type) keep their own values and position."""
+ segs = [[LegSpec("SFO", "2026-09-01", "PHX", "AA", "100")]]
+ built = build_tfs_token(segs, passengers=(1, 1, 2), seat=3)
+ raw = _b64url_to_bytes(built)
+ # Three f8 entries, then f9=3 (business), then f14=1 — same layout as
+ # the single-passenger case, just with more f8 entries ahead of f9.
+ assert b"\x40\x01\x40\x01\x40\x02\x48\x03\x70\x01" in raw
+ # f19 (trip type) is unaffected by the passenger count.
+ assert raw.endswith(bytes([0x98, 0x01, 0x02]))
+
+
+class TestPassengerCodes:
+ """``passenger_codes`` maps a ``PassengerInfo`` to ``tfs`` field-8 codes.
+
+ This is the helper extracted out of ``fli.search._tfs.build_tfs`` so the
+ search token and the booking token (:func:`build_tfs_token`) cannot drift
+ on how they encode the passenger mix.
+ """
+
+ def test_family_mix(self):
+ from fli.models import PassengerInfo
+ from fli.search._proto import passenger_codes
+
+ info = PassengerInfo(adults=2, children=1, infants_on_lap=1)
+ assert passenger_codes(info) == [1, 1, 2, 3]
+
+ def test_infant_in_seat_is_code_four(self):
+ from fli.models import PassengerInfo
+ from fli.search._proto import passenger_codes
+
+ info = PassengerInfo(adults=1, infants_in_seat=1)
+ assert passenger_codes(info) == [1, 4]
+
+ def test_none_defaults_to_single_adult(self):
+ from fli.search._proto import passenger_codes
+
+ assert passenger_codes(None) == [1]
+
+ def test_duck_typed_object_with_no_passenger_attrs_defaults_to_single_adult(self):
+ """A non-``PassengerInfo`` object with none of the expected attributes.
+
+ Mirrors the ``getattr(..., 0)`` tolerance ``build_tfs`` already
+ relies on — malformed input degrades to "one adult" rather than
+ raising, matching :meth:`SearchFlights.build_flight_booking_url`'s
+ "never raises" contract.
+ """
+ from fli.search._proto import passenger_codes
+
+ assert passenger_codes(object()) == [1]
+
+ def test_total_at_the_nine_traveller_ceiling_is_accepted(self):
+ from fli.models import PassengerInfo
+ from fli.search._proto import passenger_codes
+
+ info = PassengerInfo(adults=4, children=2, infants_in_seat=2, infants_on_lap=1)
+ assert len(passenger_codes(info)) == 9
+
+ @pytest.mark.parametrize(
+ "counts",
+ [
+ {"adults": 10, "children": 0}, # total 10, one over the ceiling
+ {"adults": 5, "children": 5}, # total 10 spread across two fields
+ ],
+ )
+ def test_total_over_nine_travellers_raises(self, counts):
+ from fli.search._proto import passenger_codes
+
+ class _Duck:
+ def __init__(self, **kw):
+ for k, v in kw.items():
+ setattr(self, k, v)
+
+ with pytest.raises(ValueError, match="9"):
+ passenger_codes(_Duck(**counts))
+
+ @pytest.mark.parametrize(
+ "bad_value",
+ [2.5, "3", True],
+ )
+ def test_non_integer_count_raises(self, bad_value):
+ from fli.search._proto import passenger_codes
+
+ class _Duck:
+ adults = bad_value
+
+ with pytest.raises(ValueError, match="adults"):
+ passenger_codes(_Duck())
+
+ def test_negative_count_raises(self):
+ from fli.search._proto import passenger_codes
+
+ class _Duck:
+ adults = -1
+
+ with pytest.raises(ValueError, match="adults"):
+ passenger_codes(_Duck())
+
+ def test_huge_count_raises_immediately_instead_of_building_a_giant_list(self):
+ """A duck-typed count in the millions must fail fast, not build a list that big.
+
+ Before this guard, an ``adults=10**6``-shaped object made this
+ function (and everything downstream of it, including the booking
+ URL) spend seconds building a multi-megabyte result instead of
+ rejecting the obviously-impossible passenger count up front.
+ """
+ import time
+
+ from fli.search._proto import passenger_codes
+
+ class _Duck:
+ adults = 10**6
+
+ start = time.monotonic()
+ with pytest.raises(ValueError, match="9"):
+ passenger_codes(_Duck())
+ assert time.monotonic() - start < 1.0
+
+
+class TestPassengerCodesAcceptRejectTable:
+ """Which duck-typed inputs `passenger_codes` accepts or rejects.
+
+ The TypeScript port (`fli-js/tests/search/proto.test.ts`,
+ `describe("passengerCodes accept/reject table")`) runs this same table of
+ inputs against its own `passengerCodes` and must reach the same
+ accept/reject verdict for each row — keep the two in sync.
+ """
+
+ @pytest.mark.parametrize(
+ ("adults", "children", "accepted"),
+ [
+ (1, 0, True),
+ (0, 0, True), # all-zero mix still books one adult
+ (9, 0, True), # exactly Google's ceiling
+ (10, 0, False), # one over the ceiling
+ (5, 5, False), # ceiling crossed by summing two fields
+ (-1, 0, False),
+ (2.5, 0, False),
+ ("3", 0, False),
+ (True, 0, False),
+ ],
+ )
+ def test_accept_reject(self, adults, children, accepted):
+ from fli.search._proto import passenger_codes
+
+ class _Duck:
+ def __init__(self, adults, children):
+ self.adults = adults
+ self.children = children
+
+ info = _Duck(adults, children)
+ if accepted:
+ passenger_codes(info) # must not raise
+ else:
+ with pytest.raises(ValueError):
+ passenger_codes(info)
+
class TestToUrlsafeB64:
def test_converts_standard_to_urlsafe(self):
diff --git a/tests/search/test_tfs.py b/tests/search/test_tfs.py
index acf8d58..2fdf26c 100644
--- a/tests/search/test_tfs.py
+++ b/tests/search/test_tfs.py
@@ -371,6 +371,32 @@ class TestPassengerCodes:
assert _passenger_codes(build_tfs(one_lap_each)) == [1, 1, 3, 3]
+class TestPassengerCodesParityWithBookingToken:
+ """Drift guard: the search token and the booking token must agree.
+
+ ``build_tfs`` (search token) and ``build_tfs_token`` (per-flight booking
+ deep link) both encode field 8 from the same ``passenger_codes`` helper —
+ this pins that they produce the identical sequence for the same
+ ``PassengerInfo``, the way a manual re-implementation in one of the two
+ places could silently stop doing.
+ """
+
+ def test_family_mix_matches_between_search_and_booking_tokens(self):
+ from fli.search._proto import LegSpec, build_tfs_token, passenger_codes
+
+ info = PassengerInfo(adults=2, children=1, infants_on_lap=1)
+ spec = _filters([("JFK", "LAX", OUTBOUND_DATE)], passenger_info=info)
+ search_codes = _passenger_codes(build_tfs(spec))
+
+ booking_token = build_tfs_token(
+ [[LegSpec("JFK", OUTBOUND_DATE, "LAX", "AA", "171")]],
+ passengers=passenger_codes(info),
+ )
+ booking_codes = _passenger_codes(booking_token)
+
+ assert search_codes == passenger_codes(info) == booking_codes == [1, 1, 2, 3]
+
+
class TestPageUrl:
def test_includes_locale_and_currency(self):
url = page_url("TFS", currency="EUR", language="de", country="DE")