Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix(search): encode cabin class in tfs booking deep-links (#231)

Salvatore Arena98671cf07888
diff --git a/fli-js/src/search/flights.ts b/fli-js/src/search/flights.ts
index 77064ed..22c3e79 100644
--- a/fli-js/src/search/flights.ts
+++ b/fli-js/src/search/flights.ts
@@ -6,7 +6,7 @@
import type { GoogleFlightsUrlOptions } from "../core/links.ts";
import type { BookingOption, FlightResult } from "../models/google-flights/base.ts";
-import { TripType } from "../models/google-flights/base.ts";
+import { SeatType, TripType } from "../models/google-flights/base.ts";
import { FlightSearchFilters } from "../models/google-flights/flights.ts";
import { type Client, getClient } from "./client.ts";
import { parallelMap } from "./concurrency.ts";
@@ -31,8 +31,11 @@ export interface BookingOptions {
sessionId?: string | null;
}
-/** Locale knobs for {@link SearchFlights.buildFlightBookingUrl} (alias of the core options). */
-export type BookingUrlOptions = GoogleFlightsUrlOptions;
+/** Locale knobs plus cabin class for {@link SearchFlights.buildFlightBookingUrl}. */
+export interface BookingUrlOptions extends GoogleFlightsUrlOptions {
+ /** Cabin class encoded into the `tfs` token (field 9). Defaults to economy. */
+ seatType?: SeatType;
+}
export class SearchFlights {
static readonly BASE_URL =
@@ -251,7 +254,7 @@ export class SearchFlights {
flightNumber: leg.flight_number,
})),
);
- const tfs = buildTfsToken(segments, { isOneWay });
+ const tfs = buildTfsToken(segments, { isOneWay, 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 abe42ec..3b88efd 100644
--- a/fli-js/src/search/proto.ts
+++ b/fli-js/src/search/proto.ts
@@ -347,6 +347,12 @@ export interface LegSpec {
export interface BuildTfsTokenOptions {
/** `true` for one-way (incl. multi-city); `false` for round-trip. */
isOneWay?: boolean;
+ /**
+ * 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.
+ */
+ seat?: number;
}
/**
@@ -363,6 +369,7 @@ export interface BuildTfsTokenOptions {
*/
export function buildTfsToken(segments: LegSpec[][], options: BuildTfsTokenOptions = {}): string {
const isOneWay = options.isOneWay ?? true;
+ 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++) {
const seg = segments[i];
@@ -402,7 +409,7 @@ export function buildTfsToken(segments: LegSpec[][], options: BuildTfsTokenOptio
varintField(2, 2),
segmentProtos,
varintField(8, 1),
- varintField(9, 1),
+ varintField(9, seat), // 1=economy 2=premium 3=business 4=first
varintField(14, 1),
lengthDelim(16, concatBytes(tag(1, 0), varintBig(MAX_U64))),
varintField(19, f19),
diff --git a/fli-js/tests/search/flights_booking_url.test.ts b/fli-js/tests/search/flights_booking_url.test.ts
index 76b3e59..cebe872 100644
--- a/fli-js/tests/search/flights_booking_url.test.ts
+++ b/fli-js/tests/search/flights_booking_url.test.ts
@@ -9,7 +9,11 @@ import { describe, expect, test } from "bun:test";
import { Buffer } from "node:buffer";
import { Airline } from "../../src/models/airline.ts";
import { Airport } from "../../src/models/airport.ts";
-import type { FlightLeg, FlightResult } from "../../src/models/google-flights/base.ts";
+import {
+ type FlightLeg,
+ type FlightResult,
+ SeatType,
+} from "../../src/models/google-flights/base.ts";
import { SearchFlights } from "../../src/search/flights.ts";
/** Build a leg with a LOCAL departure datetime (matches the decoder). */
@@ -195,4 +199,18 @@ describe("buildFlightBookingUrl", () => {
test("returns a string", () => {
expect(typeof search.buildFlightBookingUrl(oneWay())).toBe("string");
});
+
+ test("seatType defaults to economy (field 9 = 1)", () => {
+ const raw = tfsBytes(search.buildFlightBookingUrl(oneWay()));
+ expect(Buffer.from(raw).includes(Buffer.from([0x48, 0x01]))).toBe(true);
+ expect(Buffer.from(raw).includes(Buffer.from([0x48, 0x03]))).toBe(false);
+ });
+
+ test("seatType BUSINESS encodes field 9 as 3", () => {
+ const economy = search.buildFlightBookingUrl(oneWay());
+ const business = search.buildFlightBookingUrl(oneWay(), { seatType: SeatType.BUSINESS });
+ expect(economy).not.toBe(business);
+ const raw = tfsBytes(business);
+ expect(Buffer.from(raw).includes(Buffer.from([0x48, 0x03]))).toBe(true);
+ });
});
diff --git a/fli-js/tests/search/proto.test.ts b/fli-js/tests/search/proto.test.ts
index 43c62eb..3e8d916 100644
--- a/fli-js/tests/search/proto.test.ts
+++ b/fli-js/tests/search/proto.test.ts
@@ -355,4 +355,24 @@ describe("buildTfsToken", () => {
test("empty leg list throws", () => {
expect(() => buildTfsToken([[]])).toThrow("no legs");
});
+
+ test("seat defaults to economy (field 9 = 1)", () => {
+ const built = buildTfsToken([
+ [{ origin: "SFO", depDate: "2026-09-01", dest: "PHX", airline: "AA", flightNumber: "100" }],
+ ]);
+ const raw = tfsBytes(built);
+ const text = Buffer.from(raw);
+ expect(text.includes(Buffer.from([0x40, 0x01, 0x48, 0x01, 0x70, 0x01]))).toBe(true);
+ });
+
+ test("seat=3 encodes field 9 as business", () => {
+ const segs: LegSpec[][] = [
+ [{ origin: "SFO", depDate: "2026-09-01", dest: "PHX", airline: "AA", flightNumber: "100" }],
+ ];
+ const economy = tfsBytes(buildTfsToken(segs));
+ const business = tfsBytes(buildTfsToken(segs, { seat: 3 }));
+ expect(Buffer.from(economy).includes(Buffer.from([0x48, 0x01]))).toBe(true);
+ expect(Buffer.from(business).includes(Buffer.from([0x48, 0x03]))).toBe(true);
+ expect(Buffer.from(economy).equals(Buffer.from(business))).toBe(false);
+ });
});
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index a1f995e..cd5eb74 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -204,7 +204,11 @@ def _search_flights_core(
# Build per-flight booking deep-links (tfs; never raises).
booking_urls = [
search_client.build_flight_booking_url(
- result, currency=currency, language=language, country=country
+ result,
+ currency=currency,
+ language=language,
+ country=country,
+ seat_type=seat_type,
)
for result in results
]
diff --git a/fli/mcp/server.py b/fli/mcp/server.py
index 208d143..2ad073c 100755
--- a/fli/mcp/server.py
+++ b/fli/mcp/server.py
@@ -673,6 +673,7 @@ def _execute_flight_search(params: FlightSearchParams) -> dict[str, Any]:
currency=params.currency,
language=params.language,
country=params.country,
+ seat_type=filters.seat_type,
),
)
for f in flights
@@ -760,6 +761,7 @@ def _execute_booking_options(
currency=params.currency,
language=params.language,
country=params.country,
+ seat_type=filters.seat_type,
)
serialized = [_serialize_booking_option(o) for o in options]
result = {
diff --git a/fli/search/_proto.py b/fli/search/_proto.py
index bea7e99..4372a3a 100644
--- a/fli/search/_proto.py
+++ b/fli/search/_proto.py
@@ -246,6 +246,7 @@ def build_tfs_token(
segments: list[list[LegSpec]],
*,
is_one_way: bool = True,
+ seat: int = 1,
) -> str:
"""Build the ``tfs`` query parameter for a Google Flights deep-link URL.
@@ -264,6 +265,9 @@ def build_tfs_token(
direction (one leg for nonstop, two or more for connections).
is_one_way: ``True`` for one-way (including multi-city); ``False``
for round-trip. Controls the ``f19`` constant.
+ 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.
Returns:
URL-safe base64 string (no ``=`` padding) suitable for use as the
@@ -316,7 +320,7 @@ def build_tfs_token(
+ _varint_field(2, 2)
+ segment_protos
+ _varint_field(8, 1)
- + _varint_field(9, 1)
+ + _varint_field(9, seat) # 1=economy 2=premium 3=business 4=first
+ _varint_field(14, 1)
+ _length_delim(16, _varint_field(1, _MAX_U64))
+ _varint_field(19, f19)
diff --git a/fli/search/flights.py b/fli/search/flights.py
index 62c159a..b23f953 100644
--- a/fli/search/flights.py
+++ b/fli/search/flights.py
@@ -17,6 +17,7 @@ from fli.models import (
BookingOption,
FlightResult,
FlightSearchFilters,
+ SeatType,
)
from fli.models.google_flights.base import TripType
from fli.search._concurrency import parallel_map
@@ -357,6 +358,7 @@ class SearchFlights:
currency: str | None = None,
language: str | None = None,
country: str | None = None,
+ seat_type: SeatType = SeatType.ECONOMY,
) -> str:
"""Build a Google Flights deep-link URL for a specific itinerary.
@@ -377,6 +379,8 @@ class SearchFlights:
currency: ISO 4217 currency code appended as ``curr=``.
language: BCP-47 language code appended as ``hl=``.
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.
Returns:
A ``https://www.google.com/travel/flights/booking?tfs=…`` URL.
@@ -405,7 +409,7 @@ class SearchFlights:
for leg in result.legs
]
segments.append(seg_legs)
- tfs = build_tfs_token(segments, is_one_way=is_one_way)
+ tfs = build_tfs_token(segments, is_one_way=is_one_way, 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 662368f..7235075 100644
--- a/tests/cli/test_flights.py
+++ b/tests/cli/test_flights.py
@@ -7,7 +7,7 @@ import pytest
from typer.testing import CliRunner
from fli.cli.main import app
-from fli.models import Airline, Airport, FlightLeg, FlightResult
+from fli.models import Airline, Airport, FlightLeg, FlightResult, SeatType
from fli.models.google_flights.base import TripType
@@ -114,6 +114,11 @@ def test_flights_with_cabin_class(runner, mock_search_flights, mock_console):
)
assert result.exit_code == 0
mock_search_flights.search.assert_called_once()
+ args, _ = mock_search_flights.search.call_args
+ assert args[0].seat_type == SeatType.BUSINESS
+ mock_search_flights.build_flight_booking_url.assert_called()
+ _, kwargs = mock_search_flights.build_flight_booking_url.call_args
+ assert kwargs["seat_type"] == SeatType.BUSINESS
def test_flights_with_stops(runner, mock_search_flights, mock_console):
diff --git a/tests/search/test_booking_url.py b/tests/search/test_booking_url.py
index 2a0b6ab..6c49a92 100644
--- a/tests/search/test_booking_url.py
+++ b/tests/search/test_booking_url.py
@@ -9,7 +9,7 @@ import urllib.parse
from datetime import datetime, timezone
from unittest.mock import MagicMock
-from fli.models import Airline, Airport, FlightLeg, FlightResult
+from fli.models import Airline, Airport, FlightLeg, FlightResult, SeatType
from fli.search.flights import SearchFlights
# ---------------------------------------------------------------------------
@@ -231,3 +231,33 @@ class TestBuildFlightBookingUrl:
client = _make_client()
result = client.build_flight_booking_url(_one_way())
assert isinstance(result, str)
+
+ def test_seat_type_defaults_to_economy(self):
+ """Omitted seat_type still encodes field 9 as economy (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 b"\x48\x01" in raw
+ assert b"\x48\x03" not in raw
+
+ def test_seat_type_business_changes_tfs_field_9(self):
+ """Passing SeatType.BUSINESS encodes field 9 as 3, not the economy default."""
+ import base64
+
+ client = _make_client()
+ economy_url = client.build_flight_booking_url(_one_way())
+ business_url = client.build_flight_booking_url(_one_way(), seat_type=SeatType.BUSINESS)
+ assert economy_url != business_url
+
+ def _raw(url: str) -> bytes:
+ tfs = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["tfs"][0]
+ pad = "=" * ((4 - len(tfs) % 4) % 4)
+ return base64.urlsafe_b64decode(tfs + pad)
+
+ 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
diff --git a/tests/search/test_proto.py b/tests/search/test_proto.py
index 0edb79b..d724a59 100644
--- a/tests/search/test_proto.py
+++ b/tests/search/test_proto.py
@@ -303,6 +303,23 @@ class TestBuildTfsToken:
raw = _b64url_to_bytes(built)
assert b"F9" in raw
+ def test_seat_defaults_to_economy(self):
+ """Field 9 is economy (1) when seat is omitted; matches captured tokens."""
+ built = build_tfs_token([[LegSpec("SFO", "2026-09-01", "PHX", "AA", "100")]])
+ raw = _b64url_to_bytes(built)
+ # f8=1 (0x40 0x01), f9=1 (0x48 0x01), f14=1 (0x70 0x01)
+ assert b"\x40\x01\x48\x01\x70\x01" in raw
+
+ def test_seat_business_encodes_field_9(self):
+ """Field 9 is business (3) when seat=3; golden tokens stay economy-only."""
+ segs = [[LegSpec("SFO", "2026-09-01", "PHX", "AA", "100")]]
+ economy = _b64url_to_bytes(build_tfs_token(segs))
+ business = _b64url_to_bytes(build_tfs_token(segs, seat=3))
+ assert b"\x48\x01" in economy
+ assert b"\x48\x03" in business
+ assert b"\x48\x03" not in economy
+ assert economy != business
+
class TestToUrlsafeB64:
def test_converts_standard_to_urlsafe(self):