feat: Apple Wallet passes for bookings

"Add to Apple Wallet" on a booking in the iOS app turns it into a TREK pass:
a boarding pass from and to for flights, trains, buses and boats, check-in and
check-out for a stay, pickup and drop-off for a car, the time for anything
else, with the confirmation code as a QR code. Wallet brings it up on the lock
screen around its time and place: times carry the offset of the endpoint's zone
(looked up from the coordinates where the endpoint has none), stays and
restaurants their place's coordinates. The labels come from the booking forms'
own strings, so nothing new to translate on the pass.

Only liketrek holds the Pass Type ID certificate, so the server sends the pass's
texts to the TREK services' signer (TREK_WALLET_PASS_URL, push.liketrek.com)
once per tap; it stores nothing, and TREK_SERVICES=off turns it off with the
other services. Texts are cleaned of links and shortened here, the answer must
be a .pkpass within 512 KB, and a user gets 20 passes a minute.

- New wallet-pass domain: GET /api/trips/:tripId/reservations/:id/wallet-pass
  behind the trip guard, the booking checked to belong to the trip; trip title
  and place come from the reservations domain (findPassContext)
- MWalletButton in the transport and booking sheets, only where the app binary
  has the wallet feature; undated bookings and failures are told apart
- TREK_WALLET_PASS_URL in .env.example, compose, Helm and the wiki
This commit is contained in:
Maurice
2026-11-07 10:40:41 +01:00
parent 794da3be72
commit 37a4e84360
56 changed files with 1873 additions and 113 deletions
+3
View File
@@ -69,6 +69,8 @@ const DEFAULT_SERVICE_HOSTS = ['places.liketrek.com', 'photon.liketrek.com', 'va
const DEFAULT_PHOTON_URL = 'https://photon.liketrek.com';
/** The TREK services' Valhalla, asked through this server's routing relay. */
const DEFAULT_VALHALLA_URL = 'https://valhalla.liketrek.com';
/** Signs the Apple Wallet passes of bookings; only liketrek holds the pass certificate. */
const DEFAULT_WALLET_PASS_URL = 'https://push.liketrek.com/v1/wallet/pass';
/**
* How this installation identifies itself to the liketrek services. Unset is
@@ -84,6 +86,7 @@ export function deriveServices(raw: RawEnv) {
hosts: hosts?.length ? hosts : DEFAULT_SERVICE_HOSTS,
photonUrl: stripTrailingSlashes(raw.TREK_PHOTON_URL?.trim() || DEFAULT_PHOTON_URL),
valhallaUrl: stripTrailingSlashes(raw.TREK_VALHALLA_URL?.trim() || DEFAULT_VALHALLA_URL),
walletPassUrl: raw.TREK_WALLET_PASS_URL?.trim() || DEFAULT_WALLET_PASS_URL,
};
}
+1
View File
@@ -191,6 +191,7 @@ export const envSchema = z.object({
TREK_SERVICES_HOSTS: anyString,
TREK_PHOTON_URL: url,
TREK_VALHALLA_URL: url,
TREK_WALLET_PASS_URL: url,
PLACES_API_KEY: anyString,
AMAP_API_BASE: url,
AMAP_API_KEY: anyString,
@@ -1,13 +1,16 @@
import type { Reservations } from '../entities/Reservations.entity';
import { castIntegerKysely, concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';
import { coalesceOverride, columnRef, dayDistance } from '../dialect/sql-functions';
import { DayAssignments } from '../entities/DayAssignments.entity';
import { Days } from '../entities/Days.entity';
import { coalesceOverride, columnRef, dayDistance } from '../dialect/sql-functions';
import { castIntegerKysely, concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';
import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility';
import type { DayAssignmentRow } from './day-assignment-rows';
import { TrekRepository } from './_shared/trek-repository';
import type { Reservations } from '../entities/Reservations.entity';
import type { DB } from '../kysely/db';
import { ROADTRIP_RESERVATION_TYPES } from '@trek/shared';
import {
publicReservationExpr,
publicStayExists,
type ReservationVisibilityKyselyDB,
} from './_shared/reservation-visibility';
import { TrekRepository } from './_shared/trek-repository';
import type { DayAssignmentRow } from './day-assignment-rows';
import type {
PublicApiAccommodationKyselyDB,
PublicApiAccommodationRow,
@@ -17,6 +20,7 @@ import type {
PublicApiUnplannedPlaceRow,
PublicApiUnscheduledReservationRow,
} from './reservation-public-api-rows';
import { ROADTRIP_RESERVATION_TYPES } from '@trek/shared';
// The public API row types moved to their own module; re-exported so callers keep one import path.
export type {
@@ -64,7 +68,9 @@ type ReservationJoinKyselyDB = Pick<DB, 'reservations' | 'days' | 'places' | 'da
* TEXT column, widened to `string | number | null` so the plain `number`
* their statements bind against it type-checks (R2's ruling).
*/
type ReservationsNumericAccommodationBind = Omit<DB['reservations'], 'accommodation_id'> & { accommodation_id: string | number | null };
type ReservationsNumericAccommodationBind = Omit<DB['reservations'], 'accommodation_id'> & {
accommodation_id: string | number | null;
};
/**
* Kysely typing for `restampLinkedReservation` (DY23). `accommodation_id:
@@ -218,7 +224,8 @@ export interface CalendarStayRow {
reservation_title: string | null;
}
type CalendarStayKyselyDB = ReservationVisibilityKyselyDB & Pick<DB, 'day_accommodations' | 'reservations' | 'days' | 'places'>;
type CalendarStayKyselyDB = ReservationVisibilityKyselyDB &
Pick<DB, 'day_accommodations' | 'reservations' | 'days' | 'places'>;
/**
* RS20 (`ReservationsService.listUpcoming`) — the CTE + `UNION ALL`
@@ -268,7 +275,10 @@ interface EntriesRow extends UpcomingReservationRow {
at_time: string | null;
}
type UpcomingReservationsKyselyDB = Pick<DB, 'trips' | 'trip_members' | 'reservations' | 'days' | 'places' | 'day_accommodations'>;
type UpcomingReservationsKyselyDB = Pick<
DB,
'trips' | 'trip_members' | 'reservations' | 'days' | 'places' | 'day_accommodations'
>;
/**
* `share.service.ts:251` (`publicEndpointsByReservation`) — `SELECT
@@ -378,7 +388,42 @@ type SharePublicAccommodationKyselyDB = ReservationVisibilityKyselyDB & Pick<DB,
*/
type FlightsMissingEndpointsKyselyDB = Pick<DB, 'reservations' | 'reservation_endpoints'>;
/** `findPassContext`: the booking's trip title and the coordinates of its place or stay. */
type PassContextKyselyDB = Pick<DB, 'reservations' | 'trips' | 'places' | 'day_accommodations'>;
/** What a booking's Wallet pass needs beyond the booking: where it is, and the trip's name. */
export interface ReservationPassContext {
trip_title: string | null;
place_lat: number | null;
place_lng: number | null;
place_name: string | null;
}
export class ReservationsRepository extends TrekRepository<Reservations> {
/**
* The trip's title and the place a booking is at (its own place, else its
* stay's), for its Apple Wallet pass (WalletPassService). Scoped to the trip,
* so a booking of another trip reads as none.
*/
async findPassContext(id: number, trip_id: number): Promise<ReservationPassContext | undefined> {
const row = await this.kysely<PassContextKyselyDB>()
.selectFrom('reservations as r')
.innerJoin('trips as t', 't.id', 'r.trip_id')
.leftJoin('places as p', 'p.id', 'r.place_id')
.leftJoin('day_accommodations as ap', 'ap.id', 'r.accommodation_id')
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
.where('r.id', '=', id)
.where('r.trip_id', '=', trip_id)
.select([
't.title as trip_title',
(eb) => eb.fn.coalesce('p.lat', 'acc_p.lat').as('place_lat'),
(eb) => eb.fn.coalesce('p.lng', 'acc_p.lng').as('place_lng'),
(eb) => eb.fn.coalesce('p.name', 'acc_p.name').as('place_name'),
])
.executeTakeFirst();
return row as ReservationPassContext | undefined;
}
private joinedQuery() {
return this.kysely<ReservationJoinKyselyDB>()
.selectFrom('reservations as r')
@@ -415,7 +460,9 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* projection for one reservation, no `ORDER BY` (a single row).
*/
async findWithJoins(id: number | string): Promise<ReservationJoinRow | undefined> {
const row = await this.joinedQuery().where('r.id', '=', id as number).executeTakeFirst();
const row = await this.joinedQuery()
.where('r.id', '=', id as number)
.executeTakeFirst();
return row as ReservationJoinRow | undefined;
}
@@ -435,11 +482,17 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
}
/** RS45 (`ReservationsService.remove`'s pre-image read) — `SELECT id, title, type, accommodation_id FROM reservations WHERE id = ? AND trip_id = ?`. */
async findHeaderInTrip(id: number, trip_id: number): Promise<{ id: number; title: string; type: string | null; accommodation_id: string | null } | undefined> {
async findHeaderInTrip(
id: number,
trip_id: number,
): Promise<{ id: number; title: string; type: string | null; accommodation_id: string | null } | undefined> {
return this.qb('r')
.select(['r.id', 'r.title', 'r.type', 'r.accommodation_id'])
.where({ id, trip: trip_id })
.execute<{ id: number; title: string; type: string | null; accommodation_id: string | null } | undefined>('get', false);
.execute<{ id: number; title: string; type: string | null; accommodation_id: string | null } | undefined>(
'get',
false,
);
}
/**
@@ -448,19 +501,38 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* reservations WHERE trip_id = ? AND (type != 'hotel' OR accommodation_id
* IS NULL) AND reservation_time IS NOT NULL`.
*/
async listResyncCandidates(trip_id: number): Promise<{
id: number; reservation_time: string | null; reservation_end_time: string | null;
day_id: number | null; end_day_id: number | null;
}[]> {
async listResyncCandidates(trip_id: number): Promise<
{
id: number;
reservation_time: string | null;
reservation_end_time: string | null;
day_id: number | null;
end_day_id: number | null;
}[]
> {
const platform = this.getEntityManager().getPlatform();
return this.qb('r')
.select(['r.id', 'r.reservation_time', 'r.reservation_end_time', columnRef(platform, 'r.day_id').as('day_id'), columnRef(platform, 'r.end_day_id').as('end_day_id')])
.select([
'r.id',
'r.reservation_time',
'r.reservation_end_time',
columnRef(platform, 'r.day_id').as('day_id'),
columnRef(platform, 'r.end_day_id').as('end_day_id'),
])
.where({
trip: trip_id,
$or: [{ type: { $ne: 'hotel' } }, { accommodation_id: null }],
reservation_time: { $ne: null },
})
.execute<{ id: number; reservation_time: string | null; reservation_end_time: string | null; day_id: number | null; end_day_id: number | null }[]>('all', false);
.execute<
{
id: number;
reservation_time: string | null;
reservation_end_time: string | null;
day_id: number | null;
end_day_id: number | null;
}[]
>('all', false);
}
/** RS13 (`resyncReservationDays`'s per-row write) — `UPDATE reservations SET day_id = ?, end_day_id = ? WHERE id = ?`. */
@@ -530,42 +602,48 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* is handed — no SQL-side COALESCE. `id: number` (rule 21 — the SAME
* `toRowId`-parsed value `findInTrip`'s gate read used).
*/
async updateReservation(id: number, write: {
title: string;
reservation_time: string | null;
reservation_end_time: string | null;
location: string | null;
confirmation_number: string | null;
notes: string | null;
url: string | null;
day_id: number | null;
end_day_id: number | null;
place_id: number | null;
assignment_id: number | null;
status: string;
type: string;
accommodation_id: string | null;
metadata: string | null;
needs_review: number;
}): Promise<void> {
await this.nativeUpdate({ id }, {
title: write.title,
reservation_time: write.reservation_time,
reservation_end_time: write.reservation_end_time,
location: write.location,
confirmation_number: write.confirmation_number,
notes: write.notes,
url: write.url,
day: write.day_id,
endDay: write.end_day_id,
place: write.place_id,
assignment: write.assignment_id,
status: write.status,
type: write.type,
accommodation_id: write.accommodation_id,
metadata: write.metadata,
needs_review: write.needs_review,
});
async updateReservation(
id: number,
write: {
title: string;
reservation_time: string | null;
reservation_end_time: string | null;
location: string | null;
confirmation_number: string | null;
notes: string | null;
url: string | null;
day_id: number | null;
end_day_id: number | null;
place_id: number | null;
assignment_id: number | null;
status: string;
type: string;
accommodation_id: string | null;
metadata: string | null;
needs_review: number;
},
): Promise<void> {
await this.nativeUpdate(
{ id },
{
title: write.title,
reservation_time: write.reservation_time,
reservation_end_time: write.reservation_end_time,
location: write.location,
confirmation_number: write.confirmation_number,
notes: write.notes,
url: write.url,
day: write.day_id,
endDay: write.end_day_id,
place: write.place_id,
assignment: write.assignment_id,
status: write.status,
type: write.type,
accommodation_id: write.accommodation_id,
metadata: write.metadata,
needs_review: write.needs_review,
},
);
}
/**
@@ -585,15 +663,34 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
}
/** DY14 (`DaysService.restampReservationDates`) — `SELECT id, day_id, end_day_id, reservation_time, reservation_end_time FROM reservations WHERE trip_id = ?`. */
async listForRestamp(trip_id: number): Promise<{
id: number; day_id: number | null; end_day_id: number | null;
reservation_time: string | null; reservation_end_time: string | null;
}[]> {
async listForRestamp(trip_id: number): Promise<
{
id: number;
day_id: number | null;
end_day_id: number | null;
reservation_time: string | null;
reservation_end_time: string | null;
}[]
> {
const platform = this.getEntityManager().getPlatform();
return this.qb('r')
.select(['r.id', columnRef(platform, 'r.day_id').as('day_id'), columnRef(platform, 'r.end_day_id').as('end_day_id'), 'r.reservation_time', 'r.reservation_end_time'])
.select([
'r.id',
columnRef(platform, 'r.day_id').as('day_id'),
columnRef(platform, 'r.end_day_id').as('end_day_id'),
'r.reservation_time',
'r.reservation_end_time',
])
.where({ trip: trip_id })
.execute<{ id: number; day_id: number | null; end_day_id: number | null; reservation_time: string | null; reservation_end_time: string | null }[]>('all', false);
.execute<
{
id: number;
day_id: number | null;
end_day_id: number | null;
reservation_time: string | null;
reservation_end_time: string | null;
}[]
>('all', false);
}
/** DY15 — `UPDATE reservations SET reservation_time = ? WHERE id = ?`. */
@@ -632,7 +729,14 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
.case()
.when('reservation_time', 'is', null)
.then(eb.val(date))
.else(concatKysely(platform, eb, { value: date }, { expression: substringKysely(platform, eb, 'reservation_time', 11) }))
.else(
concatKysely(
platform,
eb,
{ value: date },
{ expression: substringKysely(platform, eb, 'reservation_time', 11) },
),
)
.end(),
}))
.where('accommodation_id', '=', accommodation_id)
@@ -980,7 +1084,12 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
}
/** RS20 — see {@link UpcomingReservationRow}'s docstring. */
async listUpcomingForUser(user_id: number, today: string, now_hhmm: string, limit: number): Promise<UpcomingReservationRow[]> {
async listUpcomingForUser(
user_id: number,
today: string,
now_hhmm: string,
limit: number,
): Promise<UpcomingReservationRow[]> {
const platform = this.getEntityManager().getPlatform();
// The `COALESCE(place name, nameless-stay's-linked-booking title, trip
@@ -995,10 +1104,15 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
.with('visible_trips', (qb) =>
qb
.selectFrom('trips as t')
.leftJoin('trip_members as tm', (join) => join.onRef('tm.trip_id', '=', 't.id').on('tm.user_id', '=', user_id))
.leftJoin('trip_members as tm', (join) =>
join.onRef('tm.trip_id', '=', 't.id').on('tm.user_id', '=', user_id),
)
.select(['t.id', 't.title', 't.cover_image'])
.where((eb) =>
eb.and([eb.or([eb('t.user_id', '=', user_id), eb('tm.user_id', 'is not', null)]), eb('t.is_archived', '=', 0)]),
eb.and([
eb.or([eb('t.user_id', '=', user_id), eb('tm.user_id', 'is not', null)]),
eb('t.is_archived', '=', 0),
]),
),
)
.with('entries', (qb) => {
@@ -1048,8 +1162,8 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
.select((eb) => [
'a.id as id',
'a.trip_id as trip_id',
eb
.fn.coalesce(
eb.fn
.coalesce(
eb.ref('p.name'),
eb
.selectFrom('reservations as res')
@@ -1089,8 +1203,8 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
.select((eb) => [
'a.id as id',
'a.trip_id as trip_id',
eb
.fn.coalesce(
eb.fn
.coalesce(
eb.ref('p.name'),
eb
.selectFrom('reservations as res')
@@ -1125,7 +1239,21 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
return bookings.unionAll(checkins).unionAll(checkouts);
})
.selectFrom('entries')
.select(['id', 'trip_id', 'title', 'type', 'status', 'location', 'reservation_time', 'confirmation_number', 'trip_title', 'trip_cover', 'day_date', 'place_name', 'place_image'])
.select([
'id',
'trip_id',
'title',
'type',
'status',
'location',
'reservation_time',
'confirmation_number',
'trip_title',
'trip_cover',
'day_date',
'place_name',
'place_image',
])
.where('at_date', 'is not', null)
.where((eb) =>
eb.or([
@@ -1146,7 +1274,18 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
const rows = await this.kysely<ShareEndpointsKyselyDB>()
.selectFrom('reservation_endpoints as e')
.innerJoin('reservations as r', 'r.id', 'e.reservation_id')
.select(['e.reservation_id', 'e.role', 'e.sequence', 'e.name', 'e.code', 'e.lat', 'e.lng', 'e.timezone', 'e.local_date', 'e.local_time'])
.select([
'e.reservation_id',
'e.role',
'e.sequence',
'e.name',
'e.code',
'e.lat',
'e.lng',
'e.timezone',
'e.local_date',
'e.local_time',
])
.where('r.trip_id', '=', trip_id as number)
.orderBy('e.reservation_id', 'asc')
.orderBy('e.sequence', 'asc')
@@ -1170,9 +1309,22 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
const rows = await this.kysely<SharePublicReservationKyselyDB>()
.selectFrom('reservations as r')
.select([
'r.id', 'r.trip_id', 'r.day_id', 'r.end_day_id', 'r.place_id', 'r.accommodation_id',
'r.title', 'r.type', 'r.status', 'r.location', 'r.reservation_time', 'r.reservation_end_time',
'r.notes', 'r.url', 'r.metadata', 'r.created_at',
'r.id',
'r.trip_id',
'r.day_id',
'r.end_day_id',
'r.place_id',
'r.accommodation_id',
'r.title',
'r.type',
'r.status',
'r.location',
'r.reservation_time',
'r.reservation_end_time',
'r.notes',
'r.url',
'r.metadata',
'r.created_at',
])
.where('r.trip_id', '=', trip_id as number)
.where((eb) => publicReservationExpr(eb, 'r.ingest_state'))
@@ -1189,9 +1341,19 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
.where((eb) => publicStayExists(eb))
.innerJoin('places as p', 'p.id', 'a.place_id')
.select([
'a.id', 'a.trip_id', 'a.place_id', 'a.start_day_id', 'a.end_day_id',
'a.check_in', 'a.check_in_end', 'a.check_out', 'a.notes',
'p.name as place_name', 'p.address as place_address', 'p.lat as place_lat', 'p.lng as place_lng',
'a.id',
'a.trip_id',
'a.place_id',
'a.start_day_id',
'a.end_day_id',
'a.check_in',
'a.check_in_end',
'a.check_out',
'a.notes',
'p.name as place_name',
'p.address as place_address',
'p.lat as place_lat',
'p.lng as place_lng',
])
.execute();
return rows as SharePublicAccommodationRow[];
@@ -1247,7 +1409,17 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
.leftJoin('places as p', 'p.id', 'a.place_id')
.leftJoin('days as ds', 'ds.id', 'a.start_day_id')
.leftJoin('days as de', 'de.id', 'a.end_day_id')
.select(['p.name', 'p.address', 'p.lat', 'p.lng', 'ds.date as start_date', 'de.date as end_date', 'a.check_in', 'a.check_out', 'a.notes'])
.select([
'p.name',
'p.address',
'p.lat',
'p.lng',
'ds.date as start_date',
'de.date as end_date',
'a.check_in',
'a.check_out',
'a.notes',
])
.where('a.trip_id', '=', trip_id)
.orderBy('ds.date', 'asc')
.execute();
@@ -1260,12 +1432,24 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
.selectFrom('places as p')
.leftJoin('categories as c', 'c.id', 'p.category_id')
.select((eb) => [
'p.name', 'p.address', 'p.lat', 'p.lng', 'p.place_time', 'p.end_time',
'p.duration_minutes', 'p.notes', 'p.transport_mode', 'c.name as category',
'p.name',
'p.address',
'p.lat',
'p.lng',
'p.place_time',
'p.end_time',
'p.duration_minutes',
'p.notes',
'p.transport_mode',
'c.name as category',
])
.where('p.trip_id', '=', trip_id)
.where((eb) => eb.not(eb.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id'))))
.where((eb) => eb.not(eb.exists(eb.selectFrom('day_accommodations as a').select('a.id').whereRef('a.place_id', '=', 'p.id'))))
.where((eb) =>
eb.not(eb.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id'))),
)
.where((eb) =>
eb.not(eb.exists(eb.selectFrom('day_accommodations as a').select('a.id').whereRef('a.place_id', '=', 'p.id'))),
)
.orderBy('p.created_at', 'asc')
.orderBy('p.id', 'asc')
.execute();
@@ -1305,7 +1489,10 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
// ---------------------------------------------------------------------------
/** BG54/BG85 — `SELECT id, metadata FROM reservations WHERE id = ? AND trip_id = ?`. */
async getIdAndMetadata(id: number | string, trip_id: number | string): Promise<{ id: number; metadata: string | null } | undefined> {
async getIdAndMetadata(
id: number | string,
trip_id: number | string,
): Promise<{ id: number; metadata: string | null } | undefined> {
return await this.kysely<Pick<DB, 'reservations'>>()
.selectFrom('reservations')
.select(['id', 'metadata'])
@@ -1352,7 +1539,9 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
}
/** ATI2 (`airtrail-import.service.ts#importAirtrailFlights`, existing-flight signature dedup) — `SELECT r.id, r.reservation_time, r.metadata FROM reservations r WHERE r.trip_id = ? AND r.type = 'flight'`. */
async listFlightReservationsForTrip(trip_id: number): Promise<{ id: number; reservation_time: string | null; metadata: string | null }[]> {
async listFlightReservationsForTrip(
trip_id: number,
): Promise<{ id: number; reservation_time: string | null; metadata: string | null }[]> {
return this.qb('r')
.select(['r.id', 'r.reservation_time', 'r.metadata'])
.where({ trip: trip_id, type: 'flight' })
@@ -1370,8 +1559,16 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* untracked reservation. Preserved exactly, not "fixed" with an added
* `uow.transactional` wrap.
*/
async linkAirtrailMultiLeg(id: number, external_id: string, external_owner_user_id: number, external_synced_at: string): Promise<void> {
await this.nativeUpdate({ id }, { external_source: 'airtrail', external_id, external_owner_user_id, sync_enabled: 0, external_synced_at });
async linkAirtrailMultiLeg(
id: number,
external_id: string,
external_owner_user_id: number,
external_synced_at: string,
): Promise<void> {
await this.nativeUpdate(
{ id },
{ external_source: 'airtrail', external_id, external_owner_user_id, sync_enabled: 0, external_synced_at },
);
}
/**
@@ -1381,8 +1578,24 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* external_hash = ?, external_synced_at = ? WHERE id = ?`. Same
* pre-existing tx gap as {@link linkAirtrailMultiLeg} — report don't fix.
*/
async linkAirtrailSingleFlight(id: number, external_id: string, external_owner_user_id: number, external_hash: string, external_synced_at: string): Promise<void> {
await this.nativeUpdate({ id }, { external_source: 'airtrail', external_id, external_owner_user_id, sync_enabled: 1, external_hash, external_synced_at });
async linkAirtrailSingleFlight(
id: number,
external_id: string,
external_owner_user_id: number,
external_hash: string,
external_synced_at: string,
): Promise<void> {
await this.nativeUpdate(
{ id },
{
external_source: 'airtrail',
external_id,
external_owner_user_id,
sync_enabled: 1,
external_hash,
external_synced_at,
},
);
}
/** ATL2 (`airtrail-link.service.ts#detach`) — `UPDATE reservations SET sync_enabled = 0 WHERE id = ?`. */
@@ -1397,12 +1610,36 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* via `columnRef` (the `listResyncCandidates` precedent above) — the
* mirror column, not a bare select.
*/
async findAirtrailLinked(id: number): Promise<{ id: number; trip_id: number; external_id: string | null; external_owner_user_id: number | null; sync_enabled: number | null } | undefined> {
async findAirtrailLinked(id: number): Promise<
| {
id: number;
trip_id: number;
external_id: string | null;
external_owner_user_id: number | null;
sync_enabled: number | null;
}
| undefined
> {
const platform = this.getEntityManager().getPlatform();
return this.qb('r')
.select(['r.id', columnRef(platform, 'r.trip_id').as('trip_id'), 'r.external_id', 'r.external_owner_user_id', 'r.sync_enabled'])
.select([
'r.id',
columnRef(platform, 'r.trip_id').as('trip_id'),
'r.external_id',
'r.external_owner_user_id',
'r.sync_enabled',
])
.where({ id, external_source: 'airtrail' })
.execute<{ id: number; trip_id: number; external_id: string | null; external_owner_user_id: number | null; sync_enabled: number | null } | undefined>('get', false);
.execute<
| {
id: number;
trip_id: number;
external_id: string | null;
external_owner_user_id: number | null;
sync_enabled: number | null;
}
| undefined
>('get', false);
}
/**
@@ -1420,12 +1657,17 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* external_id, external_hash FROM reservations WHERE external_source =
* 'airtrail' AND sync_enabled = 1 AND external_owner_user_id = ?`.
*/
async listAirtrailSyncCandidatesForOwner(owner_user_id: number): Promise<{ id: number; trip_id: number; external_id: string | null; external_hash: string | null }[]> {
async listAirtrailSyncCandidatesForOwner(
owner_user_id: number,
): Promise<{ id: number; trip_id: number; external_id: string | null; external_hash: string | null }[]> {
const platform = this.getEntityManager().getPlatform();
return this.qb('r')
.select(['r.id', columnRef(platform, 'r.trip_id').as('trip_id'), 'r.external_id', 'r.external_hash'])
.where({ external_source: 'airtrail', sync_enabled: 1, external_owner_user_id: owner_user_id })
.execute<{ id: number; trip_id: number; external_id: string | null; external_hash: string | null }[]>('all', false);
.execute<{ id: number; trip_id: number; external_id: string | null; external_hash: string | null }[]>(
'all',
false,
);
}
/**
@@ -1452,12 +1694,20 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* EXISTS guard, same shape as `Reservations.repository.ts`'s own
* `listUnplannedPlacesForPublicApi` NOT EXISTS precedent (`eb.not(eb.exists(...))`).
*/
async listFlightsMissingEndpoints(): Promise<{ id: number; metadata: string | null; reservation_time: string | null; reservation_end_time: string | null }[]> {
async listFlightsMissingEndpoints(): Promise<
{ id: number; metadata: string | null; reservation_time: string | null; reservation_end_time: string | null }[]
> {
const rows = await this.kysely<FlightsMissingEndpointsKyselyDB>()
.selectFrom('reservations as r')
.select(['r.id', 'r.metadata', 'r.reservation_time', 'r.reservation_end_time'])
.where('r.type', '=', 'flight')
.where((eb) => eb.not(eb.exists(eb.selectFrom('reservation_endpoints as e').select('e.id').whereRef('e.reservation_id', '=', 'r.id'))))
.where((eb) =>
eb.not(
eb.exists(
eb.selectFrom('reservation_endpoints as e').select('e.id').whereRef('e.reservation_id', '=', 'r.id'),
),
),
)
.execute();
return rows;
}
@@ -1470,18 +1720,17 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
/** RPL4/RPL5's shared select list, the columns of `RoadtripCarrierRow`. */
private roadtripCarrierQuery() {
const platform = this.getEntityManager().getPlatform();
return this.qb('r')
.select([
'r.id',
'r.type',
'r.title',
columnRef(platform, 'r.day_id').as('day_id'),
columnRef(platform, 'r.end_day_id').as('end_day_id'),
'r.reservation_time',
'r.reservation_end_time',
'r.metadata',
'r.day_plan_position',
]);
return this.qb('r').select([
'r.id',
'r.type',
'r.title',
columnRef(platform, 'r.day_id').as('day_id'),
columnRef(platform, 'r.end_day_id').as('end_day_id'),
'r.reservation_time',
'r.reservation_end_time',
'r.metadata',
'r.day_plan_position',
]);
}
/**
@@ -1504,9 +1753,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* NULL`. Which of them count as rides is `undatedRides` (shared) alone.
*/
async listRoadtripUndated(trip_id: number): Promise<RoadtripCarrierRow[]> {
return this.roadtripCarrierQuery()
.where({ trip: trip_id, day: null })
.execute<RoadtripCarrierRow[]>('all', false);
return this.roadtripCarrierQuery().where({ trip: trip_id, day: null }).execute<RoadtripCarrierRow[]>('all', false);
}
}
+2
View File
@@ -103,6 +103,7 @@ import { TransitModule } from './transit/transit.module';
import { TripInviteModule } from './trip-invite/trip-invite.module';
import { TripsModule } from './trips/trips.module';
import { VacayModule } from './vacay/vacay.module';
import { WalletPassModule } from './wallet-pass/wallet-pass.module';
import { WandererModule } from './wanderer/wanderer.module';
import { WeatherModule } from './weather/weather.module';
import { MikroOrmModule } from '@mikro-orm/nestjs';
@@ -189,6 +190,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
SettingsModule,
ServiceIdentityModule,
RoutingRelayModule,
WalletPassModule,
StorageModule,
BackupModule,
AuthModule,
@@ -5,7 +5,7 @@ import { Reservations } from '../../db/entities/Reservations.entity';
import type { ReservationDayPositionsRepository } from '../../db/repositories/ReservationDayPositions.repository';
import type { ReservationEndpointsRepository } from '../../db/repositories/ReservationEndpoints.repository';
import type { ReservationTravelersRepository } from '../../db/repositories/ReservationTravelers.repository';
import type { ReservationsRepository } from '../../db/repositories/Reservations.repository';
import type { ReservationPassContext, ReservationsRepository } from '../../db/repositories/Reservations.repository';
import { avatarUrl } from '../common/avatarUrl';
import type { ReservationRow, ReservationEndpoint, ReservationTraveler } from './reservations.service';
import { InjectRepository } from '@mikro-orm/nestjs';
@@ -72,6 +72,11 @@ export class ReservationsReadService {
return result;
}
/** The trip title and place coordinates a booking's Wallet pass shows (wallet-pass). */
passContext(id: number, tripId: number): Promise<ReservationPassContext | undefined> {
return this.reservationsRepo.findPassContext(id, tripId);
}
async loadEndpoints(reservationId: number): Promise<ReservationEndpoint[]> {
// RR2 — no ORDER BY difference: `ReservationEndpointsRepository
// .listForReservation` already orders by `sequence` (RR2's own shape).
@@ -0,0 +1,302 @@
import { createHash } from 'node:crypto';
import tzLookup from 'tz-lookup';
/**
* A booking as an Apple Wallet pass: what this server sends the TREK services'
* pass signer (push.liketrek.com/v1/wallet/pass), which builds and signs the
* .pkpass. Pure: the service hands the booking, its endpoints, the trip's title
* and the words in the user's language in; nothing here reads or fetches.
*
* The signer takes plain text of bounded length and refuses a spelled-out link,
* so every text is cleaned and shortened here rather than refused there.
*/
export type WalletPassKind =
'flight' | 'train' | 'bus' | 'boat' | 'car' | 'hotel' | 'restaurant' | 'event' | 'tour' | 'other';
export interface WalletPassField {
label: string;
value: string;
}
/** The signer's request body (control-plane/src/wallet-pass.ts in trek-hosted). */
export interface WalletPassRequest {
kind: WalletPassKind;
serial: string;
title: string;
trip?: string;
start: string;
end?: string;
from?: { code?: string; name: string };
to?: { code?: string; name: string };
location?: { latitude: number; longitude: number; name?: string };
details?: WalletPassField[];
back?: WalletPassField[];
confirmation?: WalletPassField;
locale?: string;
}
/** The labels a pass shows, in the user's language (wallet-pass.words.ts). */
export interface WalletWords {
locale: string;
departure: string;
arrival: string;
pickup: string;
dropOff: string;
checkIn: string;
checkOut: string;
time: string;
seat: string;
platform: string;
flightNumber: string;
trainNumber: string;
airline: string;
confirmation: string;
location: string;
}
export interface WalletPassEndpoint {
role: 'from' | 'to' | 'stop';
name: string;
code: string | null;
lat: number;
lng: number;
timezone: string | null;
local_time: string | null;
local_date: string | null;
}
export interface WalletPassSource {
reservation: {
id: number;
trip_id: number;
title: string;
type: string | null;
reservation_time?: string | null;
reservation_end_time?: string | null;
confirmation_number?: string | null;
location?: string | null;
created_at?: string | null;
metadata: Record<string, unknown>;
};
endpoints: WalletPassEndpoint[];
tripTitle: string | null;
/** The booking's place (the hotel, the restaurant), when it has coordinates. */
place: { lat: number; lng: number; name: string | null } | null;
}
const KIND_OF: Record<string, WalletPassKind> = {
flight: 'flight',
train: 'train',
bus: 'bus',
transit: 'bus',
cable_car: 'bus',
cruise: 'boat',
ferry: 'boat',
car: 'car',
taxi: 'car',
bicycle: 'car',
parking: 'car',
hotel: 'hotel',
restaurant: 'restaurant',
event: 'event',
tour: 'tour',
};
export function kindOf(type: string | null | undefined): WalletPassKind {
return (type && KIND_OF[type]) || 'other';
}
/** A text for the pass: no spelled-out links, single-spaced, at most `max` characters. */
export function clean(value: unknown, max: number): string | undefined {
if (value === null || value === undefined) return undefined;
const text = String(value)
.replace(/https?:\/\/\S+/gi, '')
.replace(/www\.\S+/gi, '')
.replace(/\s+/g, ' ')
.trim();
if (!text) return undefined;
return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
}
/** "2027-04-02T15:00" and "2027-04-02 15:00" as their date and time parts; a bare date gets no time. */
function splitLocal(value: string | null | undefined): { date: string; time: string | null } | null {
if (!value) return null;
const match = /^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}))?/.exec(value.trim());
if (!match) return null;
return { date: match[1] as string, time: match[2] ?? null };
}
/** The UTC offset of a zone at a wall-clock time, in minutes ("+09:00" is 540). */
function offsetMinutes(timeZone: string, wallClockAsUtc: number): number {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).formatToParts(new Date(wallClockAsUtc));
const get = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? 0);
const shown = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'));
return Math.round((shown - wallClockAsUtc) / 60_000);
}
/**
* A local date and time with the offset its zone has then: what Wallet needs to
* bring the pass up at the right moment. Without a zone the time is taken as UTC,
* which only shifts when the pass surfaces, never what it shows.
*/
export function withOffset(date: string, time: string | null, timeZone: string | null): string {
const clock = time ?? '00:00';
const asUtc = Date.parse(`${date}T${clock}:00Z`);
let offset = 0;
if (timeZone) {
try {
// Twice, so a wall-clock time right after a DST change takes the offset it really has.
offset = offsetMinutes(timeZone, asUtc - offsetMinutes(timeZone, asUtc) * 60_000);
} catch {
offset = 0;
}
}
const sign = offset < 0 ? '-' : '+';
const abs = Math.abs(offset);
const hh = String(Math.floor(abs / 60)).padStart(2, '0');
const mm = String(abs % 60).padStart(2, '0');
return `${date}T${clock}:00${sign}${hh}:${mm}`;
}
function zoneAt(lat: number | undefined, lng: number | undefined): string | null {
if (typeof lat !== 'number' || typeof lng !== 'number' || !Number.isFinite(lat) || !Number.isFinite(lng)) return null;
try {
return tzLookup(lat, lng);
} catch {
return null;
}
}
/** "Fri 2 Apr, 15:00" in the user's language, as the wall clock says it (no zone shift). */
export function displayTime(locale: string, date: string, time: string | null): string {
const asUtc = new Date(`${date}T${time ?? '00:00'}:00Z`);
const options: Intl.DateTimeFormatOptions = { timeZone: 'UTC', weekday: 'short', day: 'numeric', month: 'short' };
if (time) Object.assign(options, { hour: '2-digit', minute: '2-digit' });
try {
return new Intl.DateTimeFormat(locale, options).format(asUtc);
} catch {
return new Intl.DateTimeFormat('en', options).format(asUtc);
}
}
function text(meta: Record<string, unknown>, key: string, max = 64): string | undefined {
const value = meta[key];
return typeof value === 'string' || typeof value === 'number' ? clean(value, max) : undefined;
}
/** A stable serial for the booking, so adding its pass again replaces the one in Wallet. */
export function serialFor(reservation: WalletPassSource['reservation']): string {
const digest = createHash('sha256')
.update(`${reservation.trip_id}:${reservation.id}:${reservation.created_at ?? ''}`)
.digest('hex')
.slice(0, 16);
return `trek-${reservation.id}-${digest}`;
}
const CONFIRMATION = /^[A-Za-z0-9 ._/-]{1,40}$/;
/**
* The request for a booking's pass, or null when it has no date to bring the
* pass up on (a booking without a time is not something Wallet can surface).
*/
export function buildWalletPassRequest(src: WalletPassSource, words: WalletWords): WalletPassRequest | null {
const { reservation, endpoints } = src;
const meta = reservation.metadata;
const kind = kindOf(reservation.type);
const fromEnd = endpoints.find((e) => e.role === 'from');
const toEnd = [...endpoints].reverse().find((e) => e.role === 'to');
const journey = kind === 'flight' || kind === 'train' || kind === 'bus' || kind === 'boat';
// When it starts: the departure as the endpoint knows it, else the booking's own time.
const startLocal =
(journey && fromEnd?.local_date ? { date: fromEnd.local_date, time: fromEnd.local_time } : null) ??
splitLocal(reservation.reservation_time);
if (!startLocal) return null;
const endLocal =
(journey && toEnd?.local_date ? { date: toEnd.local_date, time: toEnd.local_time } : null) ??
splitLocal(reservation.reservation_end_time);
const place = src.place ?? (fromEnd && !journey ? { lat: fromEnd.lat, lng: fromEnd.lng, name: fromEnd.name } : null);
const startZone =
fromEnd?.timezone ?? zoneAt(journey ? fromEnd?.lat : place?.lat, journey ? fromEnd?.lng : place?.lng);
const endZone = toEnd?.timezone ?? zoneAt(toEnd?.lat ?? place?.lat, toEnd?.lng ?? place?.lng) ?? startZone;
const title = clean(reservation.title, 60) ?? clean(words.location, 60) ?? 'TREK';
const request: WalletPassRequest = {
kind,
serial: serialFor(reservation),
title,
start: withOffset(startLocal.date, startLocal.time, startZone),
locale: words.locale,
};
const trip = clean(src.tripTitle, 60);
if (trip) request.trip = trip;
if (endLocal) request.end = withOffset(endLocal.date, endLocal.time, endZone);
const details: WalletPassField[] = [];
const add = (label: string, value: string | undefined) => {
const v = clean(value, 64);
if (v && details.length < 4) details.push({ label: clean(label, 24) ?? label.slice(0, 24), value: v });
};
const when = (date: string, time: string | null) => displayTime(words.locale, date, time);
if (journey && fromEnd && toEnd) {
request.from = { name: clean(fromEnd.name, 40) ?? '?', ...(fromEnd.code ? { code: clean(fromEnd.code, 8) } : {}) };
request.to = { name: clean(toEnd.name, 40) ?? '?', ...(toEnd.code ? { code: clean(toEnd.code, 8) } : {}) };
add(words.departure, when(startLocal.date, startLocal.time));
if (kind === 'flight') {
const number = [text(meta, 'airline', 30), text(meta, 'flight_number', 12)].filter(Boolean).join(' ');
add(words.flightNumber, number || undefined);
}
if (kind === 'train') add(words.trainNumber, text(meta, 'train_number', 20));
add(words.seat, text(meta, 'seat', 16));
add(words.platform, text(meta, 'platform', 16));
if (endLocal) add(words.arrival, when(endLocal.date, endLocal.time));
} else if (kind === 'hotel') {
add(words.checkIn, when(startLocal.date, text(meta, 'check_in_time', 5) ?? startLocal.time));
if (endLocal) add(words.checkOut, when(endLocal.date, text(meta, 'check_out_time', 5) ?? endLocal.time));
} else if (kind === 'car') {
add(words.pickup, when(startLocal.date, startLocal.time));
if (endLocal) add(words.dropOff, when(endLocal.date, endLocal.time));
} else {
add(words.time, when(startLocal.date, startLocal.time));
}
// A journey without both ends is shown as a plain booking, which the signer accepts.
if (journey && !(request.from && request.to)) request.kind = 'other';
if (place && Number.isFinite(place.lat) && Number.isFinite(place.lng) && !journey) {
const name = clean(place.name ?? reservation.location, 60);
request.location = { latitude: place.lat, longitude: place.lng, ...(name ? { name } : {}) };
} else if (journey && fromEnd) {
request.location = {
latitude: fromEnd.lat,
longitude: fromEnd.lng,
...(fromEnd.name ? { name: clean(fromEnd.name, 60) } : {}),
};
}
if (details.length) request.details = details;
const back: WalletPassField[] = [];
const where = clean(reservation.location, 64);
if (where) back.push({ label: clean(words.location, 24) ?? 'Location', value: where });
const code = reservation.confirmation_number?.trim();
if (code && CONFIRMATION.test(code)) {
request.confirmation = { label: clean(words.confirmation, 24) ?? 'Confirmation', value: code };
} else if (code) {
const shown = clean(code, 64);
if (shown) back.push({ label: clean(words.confirmation, 24) ?? 'Confirmation', value: shown });
}
if (back.length) request.back = back;
return request;
}
@@ -0,0 +1,35 @@
import type { User } from '../../types';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { TripAccessGuard } from '../permissions/trip-access.guard';
import { WalletPassService } from './wallet-pass.service';
import { walletLanguage } from './wallet-pass.words';
import { Controller, Get, Param, ParseIntPipe, Query, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
/**
* GET /api/trips/:tripId/reservations/:id/wallet-pass: the booking's Apple
* Wallet pass, which the iOS app hands to Wallet's own sheet (native/wallet.ts).
*/
@Controller('api/trips/:tripId/reservations')
// TripAccessGuard resolves :tripId and 404s a trip the user cannot reach.
@UseGuards(JwtAuthGuard, TripAccessGuard)
export class WalletPassController {
constructor(private readonly passes: WalletPassService) {}
// response-contract-exempt: answers the signed .pkpass bytes through @Res(), not JSON.
@Get(':id/wallet-pass')
async pass(
@CurrentUser() user: User,
@Param('tripId', ParseIntPipe) tripId: number,
@Param('id', ParseIntPipe) id: number,
@Query('lang') lang: string | undefined,
@Res() res: Response,
): Promise<void> {
const pass = await this.passes.passFor(user.id, tripId, id, walletLanguage(lang));
res.set('Cache-Control', 'no-store');
res.set('Content-Disposition', `attachment; filename="${pass.filename}"`);
res.status(200).type('application/vnd.apple.pkpass').send(pass.bytes);
}
}
@@ -0,0 +1,15 @@
import { AppConfigModule } from '../app-config/app-config.module';
import { RateLimitModule } from '../common/rate-limit.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { ReservationsReadModule } from '../reservations/reservations-read.module';
import { WalletPassController } from './wallet-pass.controller';
import { WalletPassService } from './wallet-pass.service';
import { Module } from '@nestjs/common';
/** Apple Wallet passes for bookings, signed by the TREK services (wallet-pass.service.ts). */
@Module({
imports: [AppConfigModule, RateLimitModule, PermissionsModule, ReservationsReadModule],
controllers: [WalletPassController],
providers: [WalletPassService],
})
export class WalletPassModule {}
@@ -0,0 +1,153 @@
import { readCapped } from '../../utils/cappedFetch';
import { safeFetchAdminConfigured } from '../../utils/ssrfGuard';
import { servicesConfig } from '../app-config/tokens';
import { logWarn } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { RateLimitService } from '../common/rate-limit.service';
import { ReservationsReadService } from '../reservations/reservations-read.service';
import { buildWalletPassRequest, type WalletPassEndpoint } from './wallet-pass.builder';
import { loadWalletWords } from './wallet-pass.words';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
/** Per user and minute: a pass is one tap, this only stops a loop. */
const PASSES_PER_MINUTE = 20;
const RATE_WINDOW_MS = 60_000;
const TIMEOUT_MS = 10_000;
/** A pass is its texts plus TREK's icon and wordmark: some 25 KB. */
const MAX_PASS_BYTES = 512 * 1024;
const PKPASS = 'application/vnd.apple.pkpass';
/** Every ZIP, and so every .pkpass, starts with a local file header. */
const ZIP_LOCAL_HEADER = 0x04034b50;
export interface WalletPass {
bytes: Buffer;
filename: string;
}
/**
* A booking's Apple Wallet pass. Only liketrek holds the Pass Type ID
* certificate, so the pass's texts go to the TREK services' signer
* (TREK_WALLET_PASS_URL) once per tap and come back as a signed .pkpass; the
* signer stores nothing. Off with the other TREK services (TREK_SERVICES=off).
*/
@Injectable()
export class WalletPassService {
constructor(
@Inject(servicesConfig.KEY) private readonly config: ConfigType<typeof servicesConfig>,
private readonly reservations: ReservationsReadService,
private readonly rateLimit: RateLimitService,
) {}
/** Whether this server makes Wallet passes at all. */
enabled(): boolean {
return this.config.mode === 'auto';
}
async passFor(userId: number, tripId: number, reservationId: number, language: string): Promise<WalletPass> {
if (!this.enabled()) throw new DomainError(404, 'Wallet passes are off on this server');
const allowed = await this.rateLimit.check(
'wallet-pass',
String(userId),
PASSES_PER_MINUTE,
RATE_WINDOW_MS,
Date.now(),
);
if (!allowed) throw new DomainError(429, 'Too many Wallet passes, try again in a minute');
const row = await this.reservations.getReservationWithJoins(reservationId);
// The trip guard checked the trip; the booking must belong to it as well.
if (!row || Number(row.trip_id) !== tripId) throw new DomainError(404, 'Reservation not found');
// The trip's title and where the booking is, read by the reservations domain itself.
const context = await this.reservations.passContext(reservationId, tripId);
const request = buildWalletPassRequest(
{
reservation: {
id: row.id,
trip_id: row.trip_id,
title: row.title,
type: row.type,
reservation_time: stringOrNull(row.reservation_time),
reservation_end_time: stringOrNull(row.reservation_end_time),
confirmation_number: stringOrNull(row.confirmation_number),
location: stringOrNull(row.location),
created_at: stringOrNull(row.created_at),
metadata: parseMetadata(row.metadata),
},
endpoints: (row.endpoints ?? []) as WalletPassEndpoint[],
tripTitle: context?.trip_title ?? null,
place:
typeof context?.place_lat === 'number' && typeof context.place_lng === 'number'
? { lat: context.place_lat, lng: context.place_lng, name: context.place_name ?? null }
: null,
},
await loadWalletWords(language),
);
if (!request) throw new DomainError(422, 'A booking needs a date for a Wallet pass');
return { bytes: await this.sign(request), filename: `${filenameOf(row.title)}.pkpass` };
}
private async sign(request: object): Promise<Buffer> {
let response: Response;
try {
response = await safeFetchAdminConfigured(
this.config.walletPassUrl,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: PKPASS },
body: JSON.stringify(request),
signal: AbortSignal.timeout(TIMEOUT_MS),
},
0,
undefined,
MAX_PASS_BYTES,
);
} catch (err) {
logWarn(`[Wallet pass] signer unreachable: ${err instanceof Error ? err.message : String(err)}`);
throw new DomainError(502, 'The Wallet pass service did not answer');
}
if (response.status === 429) throw new DomainError(429, 'Too many Wallet passes, try again in a minute');
if (response.status !== 200 || !(response.headers.get('content-type') ?? '').startsWith(PKPASS)) {
const reason = await readCapped(response, 2048).then(
({ bytes }) => bytes.toString('utf8').slice(0, 300),
() => '',
);
logWarn(`[Wallet pass] signer answered ${response.status}: ${reason}`);
throw new DomainError(502, 'The Wallet pass service could not make this pass');
}
const { bytes, truncated } = await readCapped(response, MAX_PASS_BYTES);
// A .pkpass is a ZIP: anything else is not handed to the app as one.
if (truncated || bytes.length < 4 || bytes.readUInt32LE(0) !== ZIP_LOCAL_HEADER) {
throw new DomainError(502, 'The Wallet pass service sent something that is not a pass');
}
return bytes;
}
}
function stringOrNull(value: unknown): string | null {
return typeof value === 'string' ? value : null;
}
export function parseMetadata(raw: unknown): Record<string, unknown> {
if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw as Record<string, unknown>;
if (typeof raw !== 'string' || !raw) return {};
try {
const parsed: unknown = JSON.parse(raw);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};
} catch {
return {};
}
}
/** A file name from the booking's title: letters, digits and dashes. */
export function filenameOf(title: string): string {
const slug = title
.normalize('NFKD')
.replace(/\p{M}/gu, '')
.replace(/[^\p{L}\p{N}]+/gu, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 60);
return slug || 'booking';
}
@@ -0,0 +1,56 @@
import type { WalletWords } from './wallet-pass.builder';
import { getLocaleForLanguage, SUPPORTED_LANGUAGE_CODES } from '@trek/shared/i18n';
/**
* The labels on a booking's Wallet pass, in the user's language, from the same
* locale tables the booking forms read (`reservations.ts` of each locale), so a
* pass says "Sitz" where the app says "Sitz". Nothing new to translate.
*/
const KEYS: Readonly<Record<Exclude<keyof WalletWords, 'locale'>, string>> = {
departure: 'reservations.span.departure',
arrival: 'reservations.span.arrival',
pickup: 'reservations.span.pickup',
dropOff: 'reservations.span.dropOff',
checkIn: 'reservations.meta.checkIn',
checkOut: 'reservations.meta.checkOut',
time: 'reservations.time',
seat: 'reservations.meta.seat',
platform: 'reservations.meta.platform',
flightNumber: 'reservations.meta.flightNumber',
trainNumber: 'reservations.meta.trainNumber',
airline: 'reservations.meta.airline',
confirmation: 'reservations.confirmationCode',
location: 'reservations.locationAddress',
};
/** A language TREK has a table for; anything else is English. */
export function walletLanguage(value: unknown): string {
return typeof value === 'string' && SUPPORTED_LANGUAGE_CODES.includes(value) ? value : 'en';
}
async function tableOf(language: string): Promise<Record<string, unknown>> {
try {
// A supported code only (walletLanguage), so the path is one of the package's own locale entries.
const loaded: unknown = await import(`@trek/shared/i18n/${language}`);
const table = (loaded as { default?: unknown } | null)?.default;
return table !== null && typeof table === 'object' ? (table as Record<string, unknown>) : {};
} catch {
return {};
}
}
/** The words in `language`, English where its table lacks one. */
export async function loadWalletWords(language: string): Promise<WalletWords> {
const code = walletLanguage(language);
const own = await tableOf(code);
const english = code === 'en' ? own : await tableOf('en');
const word = (key: string) => {
const value = own[key] ?? english[key];
return typeof value === 'string' ? value : '';
};
const words = { locale: getLocaleForLanguage(code) } as WalletWords;
for (const [field, key] of Object.entries(KEYS) as [Exclude<keyof WalletWords, 'locale'>, string][]) {
words[field] = word(key);
}
return words;
}