File size: 6,376 Bytes
57a889c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import { safeFetch } from '../../utils/ssrfGuard';

/**
 * 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.
 *
 * Verified against AirTrail source:
 *  - Auth: `Authorization: Bearer <key>`; a key maps to exactly one user.
 *  - GET  /api/flight/list   — defaults to scope=mine. We NEVER send a scope
 *    param so the key only ever returns its owner's own flights (isolation
 *    holds even if an admin key is pasted).
 *  - GET  /api/flight/get/{id}
 *  - POST /api/flight/save   — `id` present => update, else create. seats[] is
 *    required (>=1). A seat with userId '<USER_ID>' is attributed to the key
 *    owner server-side, so we never need the caller's AirTrail user id.
 *  - There is no webhook and no updated_at on a flight, so change detection is
 *    snapshot-hash based (see airtrailSync).
 */

const TIMEOUT_MS = 12000;

export interface AirtrailCreds {
  /** Instance origin without a trailing /api. */
  baseUrl: string;
  apiKey: string;
  allowInsecureTls: boolean;
}

export class AirtrailAuthError extends Error {
  constructor(message = 'AirTrail rejected the API key') {
    super(message);
    this.name = 'AirtrailAuthError';
  }
}

export class AirtrailRequestError extends Error {
  status?: number;
  constructor(message: string, status?: number) {
    super(message);
    this.name = 'AirtrailRequestError';
    this.status = status;
  }
}

export interface AirtrailAirport {
  id: number;
  icao: string | null;
  iata: string | null;
  name: string | null;
  lat: number | null;
  lon: number | null;
  tz: string | null;
  country: string | null;
}

export interface AirtrailSeat {
  userId: string | null;
  guestName: string | null;
  seat: string | null;
  seatNumber: string | null;
  seatClass: string | null;
}

/** Airline/aircraft come back as joined objects (not bare codes) on a flight. */
export interface AirtrailNamedCode {
  id?: number;
  icao?: string | null;
  iata?: string | null;
  name?: string | null;
}

/** A flight as returned by list/get (the fields TREK consumes). */
export interface AirtrailFlightRaw {
  id: number;
  from: AirtrailAirport | null;
  to: AirtrailAirport | null;
  date: string | null;
  datePrecision: string | null;
  departure: string | null;
  arrival: string | null;
  airline: AirtrailNamedCode | null;
  flightNumber: string | null;
  aircraft: AirtrailNamedCode | null;
  aircraftReg: string | null;
  flightReason: string | null;
  note: string | null;
  seats: AirtrailSeat[];
}

/** Write shape accepted by POST /flight/save (airports/airline/aircraft as codes). */
export interface AirtrailSavePayload {
  id?: number;
  from: string;
  to: string;
  departure: string;
  departureTime?: string | null;
  arrival?: string | null;
  arrivalTime?: string | null;
  datePrecision?: string;
  airline?: string | null;
  flightNumber?: string | null;
  aircraft?: string | null;
  aircraftReg?: string | null;
  flightReason?: string | null;
  note?: string | null;
  seats: Array<{
    userId: string | null;
    guestName: string | null;
    seat: string | null;
    seatNumber: string | null;
    seatClass: string | null;
  }>;
}

function apiBase(baseUrl: string): string {
  // Tolerate a pasted trailing slash or '/api' suffix so we never build '/api/api'.
  const origin = baseUrl.trim().replace(/\/+$/, '').replace(/\/api$/i, '');
  return origin + '/api';
}

/**
 * Parse a response as JSON, but turn the cryptic "Unexpected token '<'" that a
 * misconfigured URL produces (AirTrail serving its SPA / an auth-proxy login
 * page) into an actionable message.
 */
async function parseJson<T>(resp: Response): Promise<T> {
  const text = await resp.text();
  try {
    return JSON.parse(text) as T;
  } catch {
    throw new AirtrailRequestError(
      'AirTrail returned a non-JSON response. Check the URL is your AirTrail base URL (e.g. https://airtrail.example.com, without /api) and that the instance is reachable without a separate login.',
    );
  }
}

async function request(creds: AirtrailCreds, path: string, init: RequestInit): Promise<Response> {
  const url = apiBase(creds.baseUrl) + path;
  let resp: Response;
  try {
    resp = await safeFetch(
      url,
      {
        ...init,
        headers: {
          Authorization: `Bearer ${creds.apiKey}`,
          Accept: 'application/json',
          ...(init.headers || {}),
        },
        signal: AbortSignal.timeout(TIMEOUT_MS) as any,
      },
      { rejectUnauthorized: !creds.allowInsecureTls },
    );
  } catch (err: unknown) {
    throw new AirtrailRequestError(err instanceof Error ? err.message : 'Could not reach AirTrail');
  }
  if (resp.status === 401 || resp.status === 403) {
    throw new AirtrailAuthError();
  }
  return resp;
}

export async function listFlights(creds: AirtrailCreds): Promise<AirtrailFlightRaw[]> {
  const resp = await request(creds, '/flight/list', { method: 'GET' });
  if (!resp.ok) throw new AirtrailRequestError(`AirTrail list failed (HTTP ${resp.status})`, resp.status);
  const data = await parseJson<{ flights?: AirtrailFlightRaw[] }>(resp);
  return data.flights ?? [];
}

export async function getFlight(creds: AirtrailCreds, id: number): Promise<AirtrailFlightRaw | null> {
  const resp = await request(creds, `/flight/get/${id}`, { method: 'GET' });
  if (resp.status === 404) return null;
  if (!resp.ok) throw new AirtrailRequestError(`AirTrail get failed (HTTP ${resp.status})`, resp.status);
  const data = await parseJson<{ flight?: AirtrailFlightRaw }>(resp);
  return data.flight ?? null;
}

export async function saveFlight(creds: AirtrailCreds, payload: AirtrailSavePayload): Promise<{ id?: number }> {
  const resp = await request(creds, '/flight/save', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  if (!resp.ok) {
    let msg = `AirTrail save failed (HTTP ${resp.status})`;
    try {
      const body = (await resp.json()) as { message?: string; errors?: unknown };
      if (body?.message) msg = body.message;
      else if (body?.errors) msg = JSON.stringify(body.errors);
    } catch {
      /* keep the generic message */
    }
    throw new AirtrailRequestError(msg, resp.status);
  }
  const data = await parseJson<{ id?: number }>(resp);
  return { id: data.id };
}