mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
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:
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* GET /api/trips/:tripId/reservations/:id/wallet-pass end to end: the session,
|
||||
* the trip guard, the booking read through the reservations module and the
|
||||
* request the TREK services' pass signer receives. The signer itself is
|
||||
* stubbed at the fetch seam.
|
||||
*/
|
||||
import { servicesConfig } from '../../src/nest/app-config/tokens';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { WalletPassModule } from '../../src/nest/wallet-pass/wallet-pass.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makeReservation, makeReservationEndpoint } from '../helpers/factories/reservations';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { safeFetchAdminConfigured } = vi.hoisted(() => ({ safeFetchAdminConfigured: vi.fn() }));
|
||||
vi.mock('../../src/utils/ssrfGuard', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../src/utils/ssrfGuard')>()),
|
||||
safeFetchAdminConfigured,
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const OWNER = 1;
|
||||
const STRANGER = 2;
|
||||
const PASS = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.from('signed pass')]);
|
||||
|
||||
let orm: TestOrm;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let tripId: number;
|
||||
let flightId: number;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), WalletPassModule],
|
||||
})
|
||||
.overrideProvider(servicesConfig.KEY)
|
||||
.useValue({ mode: 'auto', key: null, hosts: [], walletPassUrl: 'https://push.liketrek.com/v1/wallet/pass' })
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
const path = (trip: number, id: number, lang = 'de') =>
|
||||
`/api/trips/${trip}/reservations/${id}/wallet-pass?lang=${lang}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
await makeUser(orm, { id: OWNER, username: 'owner', email: 'owner@example.test' });
|
||||
await makeUser(orm, { id: STRANGER, username: 'stranger', email: 'stranger@example.test' });
|
||||
const trip = await makeTrip(orm, OWNER, { title: 'Japan 2027' });
|
||||
tripId = trip.id;
|
||||
const flight = await makeReservation(orm, tripId, {
|
||||
title: 'LH 716',
|
||||
type: 'flight',
|
||||
reservation_time: '2027-04-01T13:25',
|
||||
confirmation_number: 'X7K2QP',
|
||||
metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH716', seat: '34K' }),
|
||||
});
|
||||
flightId = flight.id;
|
||||
await makeReservationEndpoint(orm, flightId, {
|
||||
role: 'from',
|
||||
name: 'Frankfurt',
|
||||
code: 'FRA',
|
||||
lat: 50.03,
|
||||
lng: 8.57,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2027-04-01',
|
||||
local_time: '13:25',
|
||||
});
|
||||
await makeReservationEndpoint(orm, flightId, {
|
||||
role: 'to',
|
||||
sequence: 1,
|
||||
name: 'Tokyo Haneda',
|
||||
code: 'HND',
|
||||
lat: 35.55,
|
||||
lng: 139.78,
|
||||
timezone: 'Asia/Tokyo',
|
||||
local_date: '2027-04-02',
|
||||
local_time: '08:50',
|
||||
});
|
||||
app = await build();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
safeFetchAdminConfigured.mockReset();
|
||||
safeFetchAdminConfigured.mockResolvedValue(
|
||||
new Response(PASS, { status: 200, headers: { 'content-type': 'application/vnd.apple.pkpass' } }),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
describe('GET /api/trips/:tripId/reservations/:id/wallet-pass', () => {
|
||||
it('WALLET-E2E-001: answers 401 without a session and asks nobody', async () => {
|
||||
const res = await request(app.getHttpServer()).get(path(tripId, flightId));
|
||||
expect(res.status).toBe(401);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-E2E-002: someone outside the trip gets a 404, not a pass', async () => {
|
||||
const res = await request(app.getHttpServer()).get(path(tripId, flightId)).set(as(STRANGER));
|
||||
expect(res.status).toBe(404);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-E2E-003: the owner gets the signed pass, built from the booking in their language', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(path(tripId, flightId))
|
||||
.set(as(OWNER))
|
||||
.buffer(true)
|
||||
.parse((r, done) => {
|
||||
const chunks: Buffer[] = [];
|
||||
r.on('data', (c: Buffer) => chunks.push(c));
|
||||
r.on('end', () => done(null, Buffer.concat(chunks)));
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('application/vnd.apple.pkpass');
|
||||
expect(res.headers['content-disposition']).toBe('attachment; filename="LH-716.pkpass"');
|
||||
expect(Buffer.compare(res.body as Buffer, PASS)).toBe(0);
|
||||
|
||||
const [url, init] = safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('https://push.liketrek.com/v1/wallet/pass');
|
||||
const body = JSON.parse(String(init.body));
|
||||
expect(body).toMatchObject({
|
||||
kind: 'flight',
|
||||
title: 'LH 716',
|
||||
trip: 'Japan 2027',
|
||||
start: '2027-04-01T13:25:00+02:00',
|
||||
end: '2027-04-02T08:50:00+09:00',
|
||||
from: { code: 'FRA', name: 'Frankfurt' },
|
||||
to: { code: 'HND', name: 'Tokyo Haneda' },
|
||||
confirmation: { value: 'X7K2QP' },
|
||||
locale: 'de-DE',
|
||||
});
|
||||
expect(body.details.map((d: { label: string }) => d.label)).toContain('Sitzplatz');
|
||||
});
|
||||
|
||||
it('WALLET-E2E-004: a booking of another trip, or none, is a 404', async () => {
|
||||
const other = await makeTrip(orm, OWNER, { title: 'Elsewhere' });
|
||||
expect((await request(app.getHttpServer()).get(path(other.id, flightId)).set(as(OWNER))).status).toBe(404);
|
||||
expect((await request(app.getHttpServer()).get(path(tripId, 999_999)).set(as(OWNER))).status).toBe(404);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-E2E-005: a booking without a date gets a 422, and the signer failing a 502', async () => {
|
||||
const undated = await makeReservation(orm, tripId, { title: 'Someday', type: 'event', reservation_time: null });
|
||||
expect((await request(app.getHttpServer()).get(path(tripId, undated.id)).set(as(OWNER))).status).toBe(422);
|
||||
|
||||
safeFetchAdminConfigured.mockRejectedValueOnce(new Error('ECONNREFUSED'));
|
||||
expect((await request(app.getHttpServer()).get(path(tripId, flightId)).set(as(OWNER))).status).toBe(502);
|
||||
});
|
||||
});
|
||||
@@ -1032,3 +1032,40 @@ describe('ReservationsRepository — confirmIfPending', () => {
|
||||
expect((await findRow(await orm(), Reservations, { id: cancelled.id }))?.status).toBe('cancelled');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ReservationsRepository — findPassContext', () => {
|
||||
it('RES-PASS-001: reads the trip title and the place of the booking, else of its stay, within the trip only', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { title: 'Japan 2027', start_date: '2027-04-01', end_date: '2027-04-06' });
|
||||
const day1 = createDay(testDb, trip.id, { date: '2027-04-01' });
|
||||
const day2 = createDay(testDb, trip.id, { date: '2027-04-02' });
|
||||
const restaurant = createPlace(testDb, trip.id, { name: 'Gion Karyo', lat: 35.0, lng: 135.77 });
|
||||
const hotel = createPlace(testDb, trip.id, { name: 'Hotel Granvia Kyoto', lat: 34.985, lng: 135.758 });
|
||||
const stay = createDayAccommodation(testDb, trip.id, hotel.id, day1.id, day2.id);
|
||||
|
||||
const dinner = createReservation(testDb, trip.id, { title: 'Dinner', type: 'restaurant' });
|
||||
await setReservation(dinner.id, { place: restaurant.id });
|
||||
const room = createReservation(testDb, trip.id, { title: 'Room', type: 'hotel' });
|
||||
await setReservation(room.id, { accommodation_id: String(stay.id) });
|
||||
const bare = createReservation(testDb, trip.id, { title: 'Museum', type: 'event' });
|
||||
|
||||
expect(await reservationsRepo.findPassContext(dinner.id, trip.id)).toEqual({
|
||||
trip_title: 'Japan 2027',
|
||||
place_lat: 35.0,
|
||||
place_lng: 135.77,
|
||||
place_name: 'Gion Karyo',
|
||||
});
|
||||
expect(await reservationsRepo.findPassContext(room.id, trip.id)).toMatchObject({
|
||||
place_lat: 34.985,
|
||||
place_name: 'Hotel Granvia Kyoto',
|
||||
});
|
||||
expect(await reservationsRepo.findPassContext(bare.id, trip.id)).toEqual({
|
||||
trip_title: 'Japan 2027',
|
||||
place_lat: null,
|
||||
place_lng: null,
|
||||
place_name: null,
|
||||
});
|
||||
const other = createTrip(testDb, user.id, { title: 'Elsewhere' });
|
||||
expect(await reservationsRepo.findPassContext(dinner.id, other.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
import {
|
||||
buildWalletPassRequest,
|
||||
clean,
|
||||
displayTime,
|
||||
kindOf,
|
||||
serialFor,
|
||||
withOffset,
|
||||
type WalletPassSource,
|
||||
type WalletWords,
|
||||
} from '../../../../src/nest/wallet-pass/wallet-pass.builder';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const WORDS: WalletWords = {
|
||||
locale: 'en-GB',
|
||||
departure: 'Departure',
|
||||
arrival: 'Arrival',
|
||||
pickup: 'Pickup',
|
||||
dropOff: 'Drop-off',
|
||||
checkIn: 'Check-in',
|
||||
checkOut: 'Check-out',
|
||||
time: 'Time',
|
||||
seat: 'Seat',
|
||||
platform: 'Platform',
|
||||
flightNumber: 'Flight No.',
|
||||
trainNumber: 'Train No.',
|
||||
airline: 'Airline',
|
||||
confirmation: 'Booking Code',
|
||||
location: 'Location / Address',
|
||||
};
|
||||
|
||||
function source(
|
||||
over: Partial<WalletPassSource['reservation']> = {},
|
||||
rest: Partial<WalletPassSource> = {},
|
||||
): WalletPassSource {
|
||||
return {
|
||||
reservation: {
|
||||
id: 7,
|
||||
trip_id: 42,
|
||||
title: 'Hotel Granvia Kyoto',
|
||||
type: 'hotel',
|
||||
reservation_time: '2027-04-02T15:00',
|
||||
reservation_end_time: '2027-04-06T11:00',
|
||||
confirmation_number: 'HG-48213',
|
||||
location: 'Karasuma-dori, Kyoto',
|
||||
created_at: '2026-11-01 10:00:00',
|
||||
metadata: { check_in_time: '15:00', check_out_time: '11:00' },
|
||||
...over,
|
||||
},
|
||||
endpoints: [],
|
||||
tripTitle: 'Japan 2027',
|
||||
place: { lat: 34.985, lng: 135.758, name: 'Hotel Granvia Kyoto' },
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
|
||||
describe('wallet pass builder', () => {
|
||||
it('WALLET-B-001: maps every booking type to a pass kind', () => {
|
||||
expect(kindOf('flight')).toBe('flight');
|
||||
expect(kindOf('cruise')).toBe('boat');
|
||||
expect(kindOf('ferry')).toBe('boat');
|
||||
expect(kindOf('transit')).toBe('bus');
|
||||
expect(kindOf('taxi')).toBe('car');
|
||||
expect(kindOf('hotel')).toBe('hotel');
|
||||
expect(kindOf('tour')).toBe('tour');
|
||||
expect(kindOf('transport_other')).toBe('other');
|
||||
expect(kindOf(null)).toBe('other');
|
||||
});
|
||||
|
||||
it('WALLET-B-002: cleans texts of links and shortens them', () => {
|
||||
expect(clean('Pay at https://evil.example/now please', 60)).toBe('Pay at please');
|
||||
expect(clean('see www.example.com', 60)).toBe('see');
|
||||
expect(clean(' a b ', 10)).toBe('a b');
|
||||
expect(clean('x'.repeat(30), 10)).toBe(`${'x'.repeat(9)}…`);
|
||||
expect(clean('https://only.link', 10)).toBeUndefined();
|
||||
expect(clean(null, 10)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('WALLET-B-003: gives a wall-clock time the offset its zone has then', () => {
|
||||
expect(withOffset('2027-04-02', '15:00', 'Asia/Tokyo')).toBe('2027-04-02T15:00:00+09:00');
|
||||
expect(withOffset('2027-07-01', '08:30', 'Europe/Berlin')).toBe('2027-07-01T08:30:00+02:00');
|
||||
expect(withOffset('2027-01-15', '08:30', 'Europe/Berlin')).toBe('2027-01-15T08:30:00+01:00');
|
||||
expect(withOffset('2027-01-15', '08:30', 'America/St_Johns')).toBe('2027-01-15T08:30:00-03:30');
|
||||
expect(withOffset('2027-01-15', null, null)).toBe('2027-01-15T00:00:00+00:00');
|
||||
expect(withOffset('2027-01-15', '10:00', 'Not/AZone')).toBe('2027-01-15T10:00:00+00:00');
|
||||
});
|
||||
|
||||
it('WALLET-B-004: shows a time as the wall clock says it, in the user language', () => {
|
||||
expect(displayTime('en-GB', '2027-04-02', '15:00')).toMatch(/Fri.*2 Apr.*15:00/);
|
||||
expect(displayTime('de-DE', '2027-04-02', null)).toMatch(/Fr.*2\. Apr/);
|
||||
expect(displayTime('no-such-LOCALE-x', '2027-04-02', null)).toMatch(/Apr/);
|
||||
});
|
||||
|
||||
it('WALLET-B-005: a hotel becomes a pass with check-in, check-out, place and QR code', () => {
|
||||
const request = buildWalletPassRequest(source(), WORDS);
|
||||
expect(request).toMatchObject({
|
||||
kind: 'hotel',
|
||||
title: 'Hotel Granvia Kyoto',
|
||||
trip: 'Japan 2027',
|
||||
start: '2027-04-02T15:00:00+09:00',
|
||||
end: '2027-04-06T11:00:00+09:00',
|
||||
location: { latitude: 34.985, longitude: 135.758, name: 'Hotel Granvia Kyoto' },
|
||||
confirmation: { label: 'Booking Code', value: 'HG-48213' },
|
||||
locale: 'en-GB',
|
||||
});
|
||||
expect(request?.details?.map((d) => d.label)).toEqual(['Check-in', 'Check-out']);
|
||||
expect(request?.back).toEqual([{ label: 'Location / Address', value: 'Karasuma-dori, Kyoto' }]);
|
||||
expect(request?.serial).toBe(serialFor(source().reservation));
|
||||
expect(request?.serial).toMatch(/^trek-7-[0-9a-f]{16}$/);
|
||||
});
|
||||
|
||||
it('WALLET-B-006: a flight becomes a boarding pass from and to, in the departure zone', () => {
|
||||
const request = buildWalletPassRequest(
|
||||
source(
|
||||
{
|
||||
title: 'LH 716',
|
||||
type: 'flight',
|
||||
reservation_time: '2027-04-01T13:25',
|
||||
reservation_end_time: null,
|
||||
metadata: { airline: 'Lufthansa', flight_number: 'LH716', seat: '34K' },
|
||||
},
|
||||
{
|
||||
place: null,
|
||||
endpoints: [
|
||||
{
|
||||
role: 'from',
|
||||
name: 'Frankfurt',
|
||||
code: 'FRA',
|
||||
lat: 50.03,
|
||||
lng: 8.57,
|
||||
timezone: 'Europe/Berlin',
|
||||
local_date: '2027-04-01',
|
||||
local_time: '13:25',
|
||||
},
|
||||
{
|
||||
role: 'to',
|
||||
name: 'Tokyo Haneda',
|
||||
code: 'HND',
|
||||
lat: 35.55,
|
||||
lng: 139.78,
|
||||
timezone: 'Asia/Tokyo',
|
||||
local_date: '2027-04-02',
|
||||
local_time: '08:50',
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
WORDS,
|
||||
);
|
||||
expect(request).toMatchObject({
|
||||
kind: 'flight',
|
||||
start: '2027-04-01T13:25:00+02:00',
|
||||
end: '2027-04-02T08:50:00+09:00',
|
||||
from: { code: 'FRA', name: 'Frankfurt' },
|
||||
to: { code: 'HND', name: 'Tokyo Haneda' },
|
||||
location: { latitude: 50.03, longitude: 8.57, name: 'Frankfurt' },
|
||||
});
|
||||
expect(request?.details?.map((d) => d.label)).toEqual(['Departure', 'Flight No.', 'Seat', 'Arrival']);
|
||||
expect(request?.details?.[1]?.value).toBe('Lufthansa LH716');
|
||||
});
|
||||
|
||||
it('WALLET-B-007: a journey without both ends is a plain booking; a train shows its number and platform', () => {
|
||||
const half = buildWalletPassRequest(source({ type: 'train', metadata: {} }, { place: null, endpoints: [] }), WORDS);
|
||||
expect(half?.kind).toBe('other');
|
||||
expect(half?.from).toBeUndefined();
|
||||
|
||||
const train = buildWalletPassRequest(
|
||||
source(
|
||||
{ type: 'train', metadata: { train_number: 'ICE 597', platform: '7', seat: '61' } },
|
||||
{
|
||||
place: null,
|
||||
endpoints: [
|
||||
{
|
||||
role: 'from',
|
||||
name: 'Berlin Hbf',
|
||||
code: null,
|
||||
lat: 52.52,
|
||||
lng: 13.37,
|
||||
timezone: null,
|
||||
local_date: null,
|
||||
local_time: null,
|
||||
},
|
||||
{
|
||||
role: 'to',
|
||||
name: 'München Hbf',
|
||||
code: null,
|
||||
lat: 48.14,
|
||||
lng: 11.56,
|
||||
timezone: null,
|
||||
local_date: null,
|
||||
local_time: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
WORDS,
|
||||
);
|
||||
expect(train?.kind).toBe('train');
|
||||
// No zone on the endpoint: looked up from its coordinates.
|
||||
expect(train?.start).toBe('2027-04-02T15:00:00+02:00');
|
||||
// At most four lines under the title; the arrival is the one that gives way.
|
||||
expect(train?.details?.map((d) => d.label)).toEqual(['Departure', 'Train No.', 'Seat', 'Platform']);
|
||||
expect(train?.from).toEqual({ name: 'Berlin Hbf' });
|
||||
});
|
||||
|
||||
it('WALLET-B-008: a car shows pickup and drop-off, a restaurant its time', () => {
|
||||
const car = buildWalletPassRequest(source({ type: 'car', title: 'Sixt' }), WORDS);
|
||||
expect(car?.details?.map((d) => d.label)).toEqual(['Pickup', 'Drop-off']);
|
||||
const dinner = buildWalletPassRequest(
|
||||
source({ type: 'restaurant', title: 'Gion Karyo', reservation_end_time: null }),
|
||||
WORDS,
|
||||
);
|
||||
expect(dinner?.kind).toBe('restaurant');
|
||||
expect(dinner?.details).toEqual([{ label: 'Time', value: expect.stringMatching(/15:00/) }]);
|
||||
expect(dinner?.end).toBeUndefined();
|
||||
});
|
||||
|
||||
it('WALLET-B-009: a confirmation that is no code goes on the back; no date means no pass', () => {
|
||||
const odd = buildWalletPassRequest(source({ confirmation_number: 'Ref: 12#34 (see mail)' }), WORDS);
|
||||
expect(odd?.confirmation).toBeUndefined();
|
||||
expect(odd?.back).toContainEqual({ label: 'Booking Code', value: 'Ref: 12#34 (see mail)' });
|
||||
expect(buildWalletPassRequest(source({ reservation_time: null }), WORDS)).toBeNull();
|
||||
expect(buildWalletPassRequest(source({ reservation_time: 'soon' }), WORDS)).toBeNull();
|
||||
});
|
||||
|
||||
it('WALLET-B-010: a booking without place or trip still makes a pass, its title cleaned', () => {
|
||||
const request = buildWalletPassRequest(
|
||||
source(
|
||||
{ title: 'Museum https://tickets.example', type: 'event', location: null, confirmation_number: null },
|
||||
{ place: null, tripTitle: null },
|
||||
),
|
||||
WORDS,
|
||||
);
|
||||
expect(request).toMatchObject({ kind: 'event', title: 'Museum' });
|
||||
expect(request?.trip).toBeUndefined();
|
||||
expect(request?.location).toBeUndefined();
|
||||
expect(request?.back).toBeUndefined();
|
||||
expect(request?.start).toBe('2027-04-02T15:00:00+00:00');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { WalletPassController } from '../../../../src/nest/wallet-pass/wallet-pass.controller';
|
||||
import type { User } from '../../../../src/types';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
function response() {
|
||||
const res = {
|
||||
headers: {} as Record<string, string>,
|
||||
statusCode: 0,
|
||||
contentType: '',
|
||||
body: undefined as unknown,
|
||||
set: vi.fn((name: string, value: string) => {
|
||||
res.headers[name] = value;
|
||||
return res;
|
||||
}),
|
||||
status: vi.fn((code: number) => {
|
||||
res.statusCode = code;
|
||||
return res;
|
||||
}),
|
||||
type: vi.fn((t: string) => {
|
||||
res.contentType = t;
|
||||
return res;
|
||||
}),
|
||||
send: vi.fn((body: unknown) => {
|
||||
res.body = body;
|
||||
return res;
|
||||
}),
|
||||
};
|
||||
return res;
|
||||
}
|
||||
|
||||
const user = { id: 5 } as User;
|
||||
|
||||
describe('WalletPassController', () => {
|
||||
it('WALLET-C-001: answers the pass as a download that is never cached, in the asked language', async () => {
|
||||
const passFor = vi.fn(async () => ({ bytes: Buffer.from('PK\u0003\u0004'), filename: 'LH-716.pkpass' }));
|
||||
const controller = new WalletPassController({ passFor } as never);
|
||||
const res = response();
|
||||
await controller.pass(user, 42, 7, 'ja', res as never);
|
||||
expect(passFor).toHaveBeenCalledWith(5, 42, 7, 'ja');
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.contentType).toBe('application/vnd.apple.pkpass');
|
||||
expect(res.headers['Content-Disposition']).toBe('attachment; filename="LH-716.pkpass"');
|
||||
expect(res.headers['Cache-Control']).toBe('no-store');
|
||||
});
|
||||
|
||||
it('WALLET-C-002: an unknown language falls back to English; a refusal is passed on', async () => {
|
||||
const passFor = vi.fn(async () => {
|
||||
throw new DomainError(422, 'A booking needs a date for a Wallet pass');
|
||||
});
|
||||
const controller = new WalletPassController({ passFor } as never);
|
||||
await expect(controller.pass(user, 42, 7, 'klingon', response() as never)).rejects.toBeInstanceOf(DomainError);
|
||||
expect(passFor).toHaveBeenCalledWith(5, 42, 7, 'en');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { filenameOf, parseMetadata, WalletPassService } from '../../../../src/nest/wallet-pass/wallet-pass.service';
|
||||
import { loadWalletWords, walletLanguage } from '../../../../src/nest/wallet-pass/wallet-pass.words';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { safeFetchAdminConfigured } = vi.hoisted(() => ({ safeFetchAdminConfigured: vi.fn() }));
|
||||
vi.mock('../../../../src/utils/ssrfGuard', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/utils/ssrfGuard')>()),
|
||||
safeFetchAdminConfigured,
|
||||
}));
|
||||
|
||||
const PASS = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.from('rest of the zip')]);
|
||||
const ROW = {
|
||||
id: 7,
|
||||
trip_id: 42,
|
||||
title: 'Hotel Granvia Kyoto',
|
||||
type: 'hotel',
|
||||
status: 'confirmed',
|
||||
reservation_time: '2027-04-02T15:00',
|
||||
reservation_end_time: '2027-04-06T11:00',
|
||||
confirmation_number: 'HG-48213',
|
||||
location: null,
|
||||
created_at: '2026-11-01 10:00:00',
|
||||
metadata: '{"check_in_time":"15:00"}',
|
||||
place_id: 3,
|
||||
endpoints: [],
|
||||
};
|
||||
|
||||
function make(mode: 'auto' | 'off' = 'auto') {
|
||||
const reservations = {
|
||||
getReservationWithJoins: vi.fn(async (): Promise<Record<string, unknown> | undefined> => ({ ...ROW })),
|
||||
passContext: vi.fn(async (): Promise<Record<string, unknown> | undefined> => ({
|
||||
trip_title: 'Japan 2027',
|
||||
place_lat: 34.985,
|
||||
place_lng: 135.758,
|
||||
place_name: 'Hotel Granvia Kyoto',
|
||||
})),
|
||||
};
|
||||
const rateLimit = { check: vi.fn(async () => true) };
|
||||
const service = new WalletPassService(
|
||||
{ mode, walletPassUrl: 'https://push.liketrek.com/v1/wallet/pass' } as never,
|
||||
reservations as never,
|
||||
rateLimit as never,
|
||||
);
|
||||
return { service, reservations, rateLimit };
|
||||
}
|
||||
|
||||
const signerAnswers = (status: number, body: BodyInit, type = 'application/vnd.apple.pkpass') =>
|
||||
safeFetchAdminConfigured.mockResolvedValue(new Response(body, { status, headers: { 'content-type': type } }));
|
||||
|
||||
async function refusal(promise: Promise<unknown>): Promise<number> {
|
||||
try {
|
||||
await promise;
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(DomainError);
|
||||
return (err as DomainError).getStatus();
|
||||
}
|
||||
throw new Error('expected a refusal');
|
||||
}
|
||||
|
||||
beforeEach(() => safeFetchAdminConfigured.mockReset());
|
||||
|
||||
describe('WalletPassService', () => {
|
||||
it('WALLET-S-001: sends the booking to the signer and hands back the signed pass', async () => {
|
||||
const { service, reservations } = make();
|
||||
signerAnswers(200, PASS);
|
||||
const pass = await service.passFor(1, 42, 7, 'de');
|
||||
expect(pass.bytes.equals(PASS)).toBe(true);
|
||||
expect(pass.filename).toBe('Hotel-Granvia-Kyoto.pkpass');
|
||||
expect(reservations.passContext).toHaveBeenCalledWith(7, 42);
|
||||
|
||||
const [url, init] = safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('https://push.liketrek.com/v1/wallet/pass');
|
||||
const body = JSON.parse(String(init.body));
|
||||
expect(body).toMatchObject({
|
||||
kind: 'hotel',
|
||||
trip: 'Japan 2027',
|
||||
locale: 'de-DE',
|
||||
start: '2027-04-02T15:00:00+09:00',
|
||||
});
|
||||
expect(body.details[0].label).toBe('Check-in');
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal);
|
||||
});
|
||||
|
||||
it('WALLET-S-002: is off with the TREK services, and asks nobody', async () => {
|
||||
const { service } = make('off');
|
||||
expect(service.enabled()).toBe(false);
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(404);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-S-003: a booking of another trip, a missing one or one without a date is refused', async () => {
|
||||
const { service, reservations } = make();
|
||||
expect(await refusal(service.passFor(1, 99, 7, 'en'))).toBe(404);
|
||||
reservations.getReservationWithJoins.mockResolvedValueOnce(undefined);
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(404);
|
||||
reservations.getReservationWithJoins.mockResolvedValueOnce({ ...ROW, reservation_time: null, place_id: null });
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(422);
|
||||
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-S-004: a user asking too often is slowed down before anything is read', async () => {
|
||||
const { service, rateLimit, reservations } = make();
|
||||
rateLimit.check.mockResolvedValueOnce(false);
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(429);
|
||||
expect(reservations.getReservationWithJoins).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('WALLET-S-005: the signer down, refusing, busy or answering something else is a clear error', async () => {
|
||||
const { service } = make();
|
||||
safeFetchAdminConfigured.mockRejectedValueOnce(new Error('ECONNREFUSED'));
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(502);
|
||||
signerAnswers(400, '{"error":"title: required"}', 'application/json');
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(502);
|
||||
signerAnswers(429, '');
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(429);
|
||||
signerAnswers(200, '<html>captive portal</html>', 'application/vnd.apple.pkpass');
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(502);
|
||||
signerAnswers(200, PASS, 'text/html');
|
||||
expect(await refusal(service.passFor(1, 42, 7, 'en'))).toBe(502);
|
||||
});
|
||||
|
||||
it('WALLET-S-006: a place without coordinates is no location; metadata reads in any shape', async () => {
|
||||
const { service, reservations } = make();
|
||||
reservations.passContext.mockResolvedValueOnce({
|
||||
trip_title: null,
|
||||
place_lat: null,
|
||||
place_lng: null,
|
||||
place_name: null,
|
||||
});
|
||||
signerAnswers(200, PASS);
|
||||
await service.passFor(1, 42, 7, 'en');
|
||||
const body = JSON.parse(String((safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit])[1].body));
|
||||
expect(body.location).toBeUndefined();
|
||||
|
||||
expect(parseMetadata('{"seat":"1A"}')).toEqual({ seat: '1A' });
|
||||
expect(parseMetadata({ seat: '1A' })).toEqual({ seat: '1A' });
|
||||
expect(parseMetadata('[1]')).toEqual({});
|
||||
expect(parseMetadata('not json')).toEqual({});
|
||||
expect(parseMetadata(null)).toEqual({});
|
||||
});
|
||||
|
||||
it('WALLET-S-007: file names and languages stay safe', async () => {
|
||||
expect(filenameOf('Hôtel "Le Nid" / Paris')).toBe('Hotel-Le-Nid-Paris');
|
||||
expect(filenameOf('***')).toBe('booking');
|
||||
expect(walletLanguage('de')).toBe('de');
|
||||
expect(walletLanguage('../../etc')).toBe('en');
|
||||
expect(walletLanguage(undefined)).toBe('en');
|
||||
const words = await loadWalletWords('de');
|
||||
expect(words.locale).toBe('de-DE');
|
||||
expect(words.seat).toBe('Sitzplatz');
|
||||
expect((await loadWalletWords('xx')).seat).toBe('Seat');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user