Compare commits

...

9 Commits

Author SHA1 Message Date
Maurice 3e8496dce6 feat(ios): hide the status bar where a corner capsule was measured
On a window where the app measured an element in a top corner, an iPhone
Duo's status capsule, it now hides the status bar, which is meant to take
the capsule away; whatever still covers the corner stays in the safe area
the page keeps clear of. Each window size keeps its answer once seen, so
hiding the bar never brings it back, and the folded and unfolded displays
decide on their own. Devices without such an element are not affected.
2026-11-22 19:36:31 +01:00
Maurice ea1b75e639 fix(mobile): keep every screen clear of the iPhone Duo's status capsule
The capsule in a top corner was handled screen by screen: the m-corner-*
classes and --m-corner-clear put bars beside it and lifted content below
it, so every layer that did not opt in sat under it, and testers found it
on almost every page.

It now counts as safe area in mobile.css. Upright the top inset reaches
below the capsule and the sides keep their full width; on a wide window
its side is given up over the whole height instead. The per-screen
handling and corner.css are gone. Control rows a screen places itself and
layers that fill the window keep to the side insets through m-safe-row and
m-safe-trail, and the trip's pane keeps its content off the capsule's side
on a wide window. On every other device the insets come out as before.
2026-11-22 19:36:31 +01:00
Maurice c0f6551cf4 test(server): send the API key requests without awaiting in a loop
Server lint counted one no-await-in-loop warning over the tests baseline, from the loop in the new API key test.
2026-11-22 18:24:15 +01:00
Maurice 1fdf74e7f2 fix(auth): mark an address the account moved before an admin saved it
Both backfills of email_self_asserted skip any account with an
admin.user_update row naming email. The edit dialog sends the email on every
save, so a role change made long after an account moved its own address kept
it at 0, and a verified SSO sign-in with that address still linked into it.

A new migration reads the address each admin save found (targetUser): an
account is marked when every save already found its current address, or when
the last save that found another one sent no email. A save that may have typed
the current address in still leaves the account alone, since the audit rows
cannot tell it from a change the account made itself before 5.0.0. Only rows
still at 0 are touched and nothing is cleared.
2026-11-22 18:15:51 +01:00
Maurice c7de823c78 fix(auth): renew a session cookie only after it verifies on its own
SessionRenewalInterceptor took req.user as proof that the trek_session cookie
had been verified. On a route with its own guard chain that does not hold:
ApiTokenGuard authenticates a public API key and sets req.user, and the cookie
sent beside it is never checked. Past half its lifetime such a cookie was
decoded without its signature and renewed, so a holder of a read-only key
could come away with a signed session of the key's owner.

The interceptor now runs the cookie through the guards' own check (signature,
expiry, password version, active session) before it renews, requires it to
name the request's user, and renews nothing on a request a public API key
authenticated.
2026-11-22 18:15:51 +01:00
Maurice 49b9ffc77d fix(client): keep the seat change clear of the sheet's held ref and of non-null assertions
Client lint was red: passing the ref-held reservation to bookingSeats added a react-hooks/refs warning in MTransportSheet, so the sheet now reads the seats from the legs it already has (seatsOfLegs). The new PDF test used a non-null assertion.
2026-11-21 15:45:04 +01:00
Maurice 7006891ce0 style(server): format the legs-only seat test
Server lint was red: lint:format found the new update_transport cases in tools-transports.test.ts unformatted.
2026-11-21 15:37:00 +01:00
Maurice 4d01439c75 test(server): type the created transport in the legs-only seat test
Server lint was red: the new MCP test cast its result to any, one no-explicit-any warning over the tests baseline.
2026-11-21 15:29:53 +01:00
Maurice adb6a2c80d fix(planner): show each leg's own seat on a flight with a stop
A flight with a stop saves a seat per leg, but every view read the
booking's flat seat, which mirrors the first leg's. A seat booked only on
the second leg showed nowhere, and one on the first leg showed on both.
#2701 had fixed this for trains only.

- getFlightLegs reads each leg's seat. The first leg falls back to the flat
  seat, as the booking form does, so older bookings keep theirs.
- bookingSeats lists the seat of every leg that has one with its route.
  The detail views (the phone's transport sheet, the booking detail) show
  each leg's seat under its route ("Seat IST → JFK"), and a leg opened
  from its row shows its own. The cards and field grids (bookings list,
  the phone's Bookings and Transports tabs, the day plan's transport
  detail) hold every seat in one Seat cell, so a card cutting its grid
  short no longer drops the second leg's.
- The day plan's flight leg rows carry their seat, and the PDF prints a
  flight's seat, direct or per leg.
- The watch and the Wallet pass name every leg's seat of the booking.
- A legs-only MCP update sets the flat seat, airline and flight number
  (train number and platform) again from the new first leg, so a seat
  taken off the first leg does not live on in the flat seat. A flat value
  the stored first leg never had stays.

Closes #3158
2026-11-21 15:24:52 +01:00
57 changed files with 965 additions and 293 deletions
@@ -121,6 +121,9 @@ class TrekBridgeViewController: CAPBridgeViewController {
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
)
let corner = cornerElement(in: frame, window: window)
if corner != .zero, cornerWindowSizes.insert(sizeKey(window.bounds.size)).inserted {
setNeedsStatusBarAppearanceUpdate()
}
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
publishedSafeArea = insets
publishedCorner = corner
@@ -139,15 +142,36 @@ class TrekBridgeViewController: CAPBridgeViewController {
private var publishedCorner: UIEdgeInsets?
// MARK: - The status bar beside a corner element
/// The window sizes on which a corner element was seen. On an iPhone Duo
/// that element is the status capsule, so the app hides the status bar
/// there to take the capsule away; whatever still covers the corner stays
/// in the safe area the page keeps clear of. A size stays in the set
/// once seen: with the bar hidden the next measure may find no corner, and
/// showing the bar again would bring the capsule back and start over. The
/// folded and the unfolded display differ in size, so each keeps its own
/// answer, and a device without such an element never hides its bar.
private var cornerWindowSizes = Set<String>()
private func sizeKey(_ size: CGSize) -> String {
"\(Int(size.width.rounded()))x\(Int(size.height.rounded()))"
}
override var prefersStatusBarHidden: Bool {
if super.prefersStatusBarHidden { return true }
guard let size = view.window?.bounds.size else { return false }
return cornerWindowSizes.contains(sizeKey(size))
}
/// An element in a top corner of the screen, such as the status capsule of
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
/// side (left/right), in the web view's coordinates; zero where there is
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
/// the corner avoided vertically reaches lower than the one avoiding it
/// horizontally, which in turn is wider on the corner's side. The page puts
/// its top bar beside the element and starts its content below it, using
/// the full width (mobile.css), instead of giving up a strip of the whole
/// height.
/// horizontally, which in turn is wider on the corner's side. The page
/// counts it into its safe area (mobile.css): upright its content starts
/// below the element, on a wide window it leaves the element's side free.
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
guard #available(iOS 26.0, *) else { return .zero }
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
+19
View File
@@ -259,6 +259,25 @@ describe('downloadTripPDF', () => {
expect(iframe!.srcdoc).toContain('Air Italia · AI123 · CDG → FCO')
})
it('FE-COMP-TRIPPDF-013s: a flight prints its seat, a direct one and each leg of one with a stop alike', async () => {
const direct = { ...transportReservation, metadata: JSON.stringify({ airline: 'Air Italia', flight_number: 'AI123', seat: '31A', departure_airport: 'CDG', arrival_airport: 'FCO' }) }
const stopover = {
...multiLegFlight,
metadata: JSON.stringify({
legs: [
{ from: 'FRA', to: 'BER', airline: 'Lufthansa', flight_number: 'LH1' },
{ from: 'BER', to: 'HND', airline: 'Lufthansa', flight_number: 'LH2', seat: '14C' },
],
departure_airport: 'FRA', arrival_airport: 'HND', airline: 'Lufthansa', flight_number: 'LH1',
}),
}
await downloadTripPDF({ ...richArgs, reservations: [direct, stopover] })
const html = getIframe()?.srcdoc ?? ''
expect(html).toContain('Air Italia · AI123 · reservations.meta.seat 31A · CDG → FCO')
expect(html).toContain('Lufthansa · LH2 · reservations.meta.seat 14C · BER → HND')
expect(html).not.toContain('LH1 · reservations.meta.seat')
})
it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => {
// The desktop toolbar hands the export the store's assignments, hidden stop and
// all, and that stop heads its check-in day. The day plan hides it and shows the
+1 -1
View File
@@ -417,7 +417,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
// flat metadata pair for legacy single-leg flights without endpoints.
const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)).map(e => e.code || e.name)
const route = stops.length >= 2 ? stops.join(' → ') : (meta.departure_airport && meta.arrival_airport ? `${meta.departure_airport} → ${meta.arrival_airport}` : '')
subtitle = [meta.airline, meta.flight_number, route].filter(Boolean).join(' · ')
subtitle = [meta.airline, meta.flight_number, meta.seat ? `${tr('reservations.meta.seat')} ${meta.seat}` : '', route].filter(Boolean).join(' · ')
}
}
else if (r.type === 'train') {
@@ -8,7 +8,7 @@ import { BlurredCode } from '../shared/BookingCode'
import { DialogButton, DialogFooter, DialogSection, DialogShell, FooterSpacer, PILL } from '../shared/DialogShell'
import { useTripStore } from '../../store/tripStore'
import { formatTime, splitReservationDateTime } from '../../utils/formatters'
import { parseReservationMetadata } from '../../utils/flightLegs'
import { parseReservationMetadata, seatCells } from '../../utils/flightLegs'
import { BookingDialogHeader } from './bookings/BookingDialogShell'
import { BOX, Eyebrow, Field, fs, toneColor, toneOf } from './bookings/bookingParts'
import { filesFor } from '../../utils/reservationFiles'
@@ -175,11 +175,13 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
add(t('reservations.meta.flightNumber'), meta.flight_number)
add(t('reservations.meta.from'), meta.departure_airport)
add(t('reservations.meta.to'), meta.arrival_airport)
add(t('reservations.meta.seat'), meta.seat)
} else if (res.type === 'train') {
add(t('reservations.meta.trainNumber'), meta.train_number)
add(t('reservations.meta.platform'), meta.platform)
add(t('reservations.meta.seat'), meta.seat)
}
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
if (res.type === 'flight' || res.type === 'train') {
for (const c of seatCells(res, t('reservations.meta.seat'))) add(c.label, c.value)
}
add(t('reservations.confirmationCode'), res.confirmation_number, true)
// A stopover booking can carry its own reference per segment (#1943); the
@@ -118,6 +118,19 @@ describe('BookingDetailDialog', () => {
expect(screen.getByText('#SEG2')).toBeInTheDocument();
});
it('FE-PLANNER-BKDETAIL-015: a flight with a stop shows the seat booked on its second leg, once, under that leg', () => {
const r = buildReservation({
title: 'MXP to JFK', type: 'flight',
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
});
renderDetail(r);
const dialog = screen.getByRole('dialog', { name: 'MXP to JFK' });
expect(within(dialog).getByText('14C')).toBeInTheDocument();
expect(within(dialog).getByText('Seat IST → JFK')).toBeInTheDocument();
// The tile stands for it; the field grid does not repeat it.
expect(within(dialog).queryByText('14C, Economy')).toBeNull();
});
it('FE-PLANNER-BKDETAIL-006: place, accommodation, linked stop, link, travelers and notes', () => {
const place = buildPlace({ name: 'Kinkaku-ji', place_time: '10:00' });
const a = buildAssignment({ id: 4401, day_id: 1302, place });
@@ -27,7 +27,7 @@ import { BookingDialogHeader, StatusPill, TypePill } from './BookingDialogShell'
import { DeleteButton, DialogButton, DialogFooter, DialogSection as Section, DialogShell, FooterSpacer, PILL } from '../../shared/DialogShell'
import FlightLiveCard from '../flightLive/FlightLiveCard'
import { useFlightLiveCardLegs } from '../flightLive/useFlightLiveCard'
import { getFlightLegs } from '../../../utils/flightLegs'
import { bookingSeats, getFlightLegs, seatLabel } from '../../../utils/flightLegs'
export interface BookingDetailDialogProps {
r: Reservation
@@ -84,6 +84,7 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
const subParts = [meta.airline, meta.flight_number, meta.train_number, facts.endpoints.length >= 2 ? facts.endpoints.map(e => e.code || e.name).join(' → ') : null].filter(Boolean)
const sub = subParts.length ? subParts.join(' ') : null
const seats = bookingSeats(r)
const stats: { value: string; label: string }[] = []
if (facts.isHotel) {
stats.push(...stayStats(facts, meta, t, locale))
@@ -100,7 +101,8 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
// Under a minute of walking is not worth a tile.
if (transit && transit.walk > 59) stats.push({ value: t('transit.min', { count: Math.round(transit.walk / 60) }), label: t('transit.walkLabel') })
if (meta.platform) stats.push({ value: meta.platform, label: t('reservations.meta.platform') })
if (meta.seat) stats.push({ value: meta.seat, label: t('reservations.meta.seat') })
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
for (const s of seats) stats.push({ value: s.seat, label: seatLabel(t('reservations.meta.seat'), s.route) })
}
// Cells already shown as a stat stay out of the field grid below.
const shownAsStat = new Set([t('reservations.meta.platform'), t('reservations.meta.seat'), t('reservations.meta.checkIn'), t('reservations.meta.checkOut')])
@@ -4,6 +4,7 @@ import type { Reservation } from '../../../types'
import { useTranslation } from '../../../i18n'
import { BlurredCode } from '../../shared/BookingCode'
import { formatMoney } from '../../../utils/formatters'
import { bookingSeats } from '../../../utils/flightLegs'
import { TransitLegChips } from '../transitDisplay'
import { displayTitle, parseMeta, type BookingGroup, type CostTotal } from './bookingsModel'
import type { BookingFacts } from './bookingFacts'
@@ -82,7 +83,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
const sub = facts.endpoints.length >= 2
? facts.endpoints.map(e => e.code || e.name).join(' → ')
: facts.accommodation || facts.place || ''
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, meta.seat, meta.platform].filter(Boolean)
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, ...bookingSeats(r).map(s => s.seat), meta.platform].filter(Boolean)
return (
<div
@@ -231,3 +231,14 @@ describe('bookingFacts: codes, links and places', () => {
expect(bookingFacts(buildReservation({ url: 'javascript:alert(1)' }), ctx()).url?.href).toBeNull();
});
});
describe('bookingFacts: seats of a flight with a stop', () => {
it('FE-PLANNER-BKFACTS-025: the Seat cell holds the seat booked only on the second leg', () => {
const r = buildReservation({
type: 'flight',
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
});
const facts = bookingFacts(r, ctx());
expect(cell(facts, 'reservations.meta.seat')).toBe('14C, Economy');
});
});
@@ -1,6 +1,6 @@
import type { Day, Reservation, ReservationEndpoint } from '../../../types'
import { formatPriceText, formatTime, splitReservationDateTime } from '../../../utils/formatters'
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../utils/flightLegs'
import { getFlightLegs, getTrainLegs, seatCells, usesStationRoute } from '../../../utils/flightLegs'
import { safeExternalHref } from '../../../utils/safeUrl'
import { bookingDates, daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
@@ -102,7 +102,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
if (!hasEndpoints && meta.arrival_airport) cells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
if (meta.train_number) cells.push({ label: t('reservations.meta.trainNumber'), value: meta.train_number })
if (meta.platform) cells.push({ label: t('reservations.meta.platform'), value: meta.platform })
if (meta.seat) cells.push({ label: t('reservations.meta.seat'), value: meta.class ? `${meta.seat}, ${meta.class}` : meta.seat })
// One seat per leg on a booking with a stop, each under its route; otherwise the booking's own.
cells.push(...seatCells(r, t('reservations.meta.seat'), meta.class ? `, ${meta.class}` : ''))
if (!c.hasLinkedCost && meta.price != null && meta.price !== '') {
cells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, c.tripCurrency, locale) })
}
-1
View File
@@ -14,7 +14,6 @@ import { useNativeCapabilities } from '../native/capabilities'
import { isNativeIos } from '../native/platform'
import { useWindowFold } from '../native/windowFold'
import './mobile.css'
import './corner.css'
interface MobileShellProps {
isPhone: boolean
@@ -48,7 +48,7 @@ export default function MImageViewer({
type="button"
onClick={onClose}
aria-label={t('collab.chat.closeImage')}
className="m-corner-beside absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
className="m-safe-row absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
>
<X size={20} strokeWidth={2} />
</button>
+1 -1
View File
@@ -89,7 +89,7 @@ export function MSectionList({
* width on both screens.
*/
export const SECTION_SCREEN =
'm-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
'px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
interface MSectionNavProps {
title: string;
+5 -5
View File
@@ -86,11 +86,11 @@ type MSheetWideAnchor = 'center' | 'rail-foot'
* docked sheet just above the dock; neither lies across the dock.
*/
const REGION: Record<MSheetVariant, string> = {
card: 'inset-x-[14px] top-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
card: 'inset-x-[14px] top-[var(--m-safe-top,12px)] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
// On a phone on its side the gap it keeps at the top would leave it a strip
// of a few rows, so there it may rise nearly to the top.
bottom:
'inset-x-4 top-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
'inset-x-4 top-[calc(var(--m-safe-top,12px)+56px)] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
drawer: 'start-0 top-0 bottom-0 w-[78%] max-w-[320px]',
}
@@ -109,15 +109,15 @@ const WIDE_REGION: Record<MSheetWideAnchor, string> = {
// A form on a window as short as a phone on its side: a sheet the window's
// full height, over the dock, as wide as a form reads well and no wider.
const SHORT_FORM_REGION =
'short:inset-x-4 short:top-[max(env(safe-area-inset-top,0px),8px)] short:bottom-0 short:items-center short:justify-stretch'
'short:inset-x-4 short:top-[max(var(--m-safe-t,0px),8px)] short:bottom-0 short:items-center short:justify-stretch'
const SHORT_FORM_BOX = 'short:max-w-[640px] short:flex-1'
/** The region the sheet stands in, on a phone and on a wide window. */
function regionClass(variant: MSheetVariant, anchor: MSheetWideAnchor = 'center', form = false): string {
const base = 'pointer-events-none absolute flex flex-col'
if (variant === 'drawer') return `${base} ${REGION.drawer}`
// m-corner-side: on a wide window the sheet keeps off a corner element's side (a Duo's status capsule).
return `${base} m-corner-side ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
// m-safe-trail: on a wide window the sheet keeps off the trailing side's safe area (a Duo's status capsule).
return `${base} m-safe-trail ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
}
/** The sheet's own box inside the region: its width, and the arrow when it has one. */
-31
View File
@@ -1,31 +0,0 @@
/* ── An element in a top corner (an iPhone Duo's status capsule) ──────────────
Beside mobile.css, which holds the variables these read (--m-corner-*).
For the screens that place their own controls rather than sit in .m-page
(the trip, its map). Every variable is 0 without such an element, so these
change nothing on any other device.
m-corner-beside: a control row in the corner's height ends before it.
m-corner-side: a layer that fills the page ends before the corner's side on
a wide window (--m-corner-side-*, 0 upright, where content starts below the
corner through --m-corner-clear instead).
The element sits where the hardware puts it, whatever the reading
direction, so right to left swaps the two sides back. */
.m-corner-beside {
margin-inline: var(--m-corner-l-gap, 0px) var(--m-corner-r-gap, 0px);
}
html[dir='rtl'] .m-corner-beside {
margin-inline: var(--m-corner-r-gap, 0px) var(--m-corner-l-gap, 0px);
}
.m-corner-side {
margin-inline: var(--m-corner-side-l, 0px) var(--m-corner-side-r, 0px);
}
html[dir='rtl'] .m-corner-side {
margin-inline: var(--m-corner-side-r, 0px) var(--m-corner-side-l, 0px);
}
/* m-corner-beside-in: m-corner-beside for a row inside .m-page, upright only
(on a wide window the page itself already ends before the corner). */
.m-corner-beside-in {
margin-inline: var(--m-corner-in-l, 0px) var(--m-corner-in-r, 0px);
}
html[dir='rtl'] .m-corner-beside-in {
margin-inline: var(--m-corner-in-r, 0px) var(--m-corner-in-l, 0px);
}
+52 -72
View File
@@ -66,43 +66,26 @@
* publishSafeArea) is a floor under env(): where a release lays the web view
* out below the status bar, WebKit reports 0 while a camera in a corner still
* reaches into the page. In a browser the variables are unset: env() alone. */
--m-safe-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--m-safe-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--m-safe-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
--m-safe-top: calc(var(--m-safe-t) + 12px);
--m-raw-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--m-raw-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--m-raw-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
/* An element in a top corner of the screen, such as an iPhone Duo's status
* capsule, as the iOS app measures it (TrekBridgeViewController
* cornerElement): how far down it reaches and how wide it is on its side.
* The floating bars stand beside it; the page keeps the side's full width
* and starts below it, instead of giving up a strip of the whole height to
* an inset that only exists in the corner. 0 everywhere else. */
--m-corner-b: var(--trek-native-corner-bottom, 0px);
--m-bar-l: max(var(--m-safe-l), var(--trek-native-corner-left, 0px));
--m-bar-r: max(var(--m-safe-r), var(--trek-native-corner-right, 0px));
--m-page-l: max(0px, var(--m-safe-l) - var(--trek-native-corner-left, 0px));
--m-page-r: max(0px, var(--m-safe-r) - var(--trek-native-corner-right, 0px));
/* A bar's side inset plus a little air: next to a Duo's status capsule a
* bar that ends exactly at the inset reads as touching it. Without an inset
* cornerElement), counts as safe area like a notch, so every screen keeps
* clear of it without knowing it is there. Upright the top inset reaches
* below it and the sides keep their full width (iOS reports the element as
* a side inset too, which is taken back out); on a wide window its side is
* given up over the whole height instead (below), where a band across the
* top would cost a quarter of the height. 0 on every other device. */
--m-safe-t: max(var(--m-raw-t), var(--trek-native-corner-bottom, 0px));
--m-safe-l: max(0px, var(--m-raw-l) - var(--trek-native-corner-left, 0px));
--m-safe-r: max(0px, var(--m-raw-r) - var(--trek-native-corner-right, 0px));
--m-safe-top: calc(var(--m-safe-t) + 12px);
/* A side inset plus a little air, for a bar beside it: a bar that ends
* exactly at the inset reads as touching what is there. Without an inset
* the air is 0 too (min() of 0 and 8px). */
--m-safe-l-gap: calc(var(--m-bar-l) + min(var(--m-bar-l), 8px));
--m-safe-r-gap: calc(var(--m-bar-r) + min(var(--m-bar-r), 8px));
/* The corner element alone, with the same air, for the screens that place
* their own controls (the trip, the map): a control row in the corner's
* height ends this far from the screen's side (m-corner-beside). Physical
* sides, as the element is: right to left does not move it. */
--m-corner-l-gap: calc(var(--trek-native-corner-left, 0px) + min(var(--trek-native-corner-left, 0px), 8px));
--m-corner-r-gap: calc(var(--trek-native-corner-right, 0px) + min(var(--trek-native-corner-right, 0px), 8px));
/* Where the content of a screen that places its own scroll body begins at
* the latest, so its first row is not under the corner element: just below
* it (m-corner-below). Upright that is the cheaper way round; on a wide
* window the page gives up the corner's side instead (below). 0 elsewhere. */
--m-corner-clear: calc(var(--m-corner-b) + min(var(--m-corner-b), 10px));
--m-corner-side-l: 0px;
--m-corner-side-r: 0px;
/* The same air for a control row inside .m-page, which on a wide window has
* already given up the corner's side (m-corner-beside-in). */
--m-corner-in-l: var(--m-corner-l-gap);
--m-corner-in-r: var(--m-corner-r-gap);
--m-safe-l-gap: calc(var(--m-safe-l) + min(var(--m-safe-l), 8px));
--m-safe-r-gap: calc(var(--m-safe-r) + min(var(--m-safe-r), 8px));
/* The navigation rail's share of the leading edge (wide windows only), what
* every full-width fixed bar and the page column start after. */
--m-rail-w: 0px;
@@ -115,21 +98,15 @@
* reads the same values as the shell. */
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
--bottom-nav-h: env(safe-area-inset-bottom, 0px);
--m-rail-w: calc(var(--m-bar-l) + 100px);
--m-rail-w: calc(var(--m-safe-l) + 100px);
/* A wide window gives up the corner element's side over the whole height,
* as an iPhone on its side does for its camera: on an unfolded Duo lifting
* every page below the status capsule cost a quarter of the height. The
* rail already takes the leading side, so only the trailing side's corner
* counts here. */
--m-corner-clear: 0px;
--m-corner-side-r: var(--m-corner-r-gap);
--m-corner-in-l: 0px;
--m-corner-in-r: 0px;
* as an iPhone on its side does for its camera, and keeps the top as it is. */
--m-safe-t: var(--m-raw-t);
--m-safe-l: max(var(--m-raw-l), var(--trek-native-corner-left, 0px));
--m-safe-r: max(var(--m-raw-r), var(--trek-native-corner-right, 0px));
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
--m-rail-w: calc(var(--m-bar-r) + 100px);
--m-corner-side-l: var(--m-corner-l-gap);
--m-corner-side-r: 0px;
--m-rail-w: calc(var(--m-safe-r) + 100px);
}
.dark .m-root {
@@ -649,40 +626,43 @@ html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-span-x {
inset-inline-end: var(--m-safe-l-gap, 0px);
}
/* A control row or button a screen places by itself (m-safe-row: the trip's
top row, the map's controls, a viewer's close button, a dropdown) keeps
clear of the sides' safe area like the bars above: both sides on a phone,
the trailing side on a wide window, where the rail holds the leading one.
A layer that fills the window (m-safe-trail: a sheet, the assistant, the
trip's pane and map) does the same on a wide window only; on a phone its
own insets keep it off the sides. On an unfolded Duo that trailing side is
the status capsule's. */
html:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {
margin-inline: var(--m-safe-l-gap, 0px) var(--m-safe-r-gap, 0px);
}
html[dir='rtl']:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {
margin-inline: var(--m-safe-r-gap, 0px) var(--m-safe-l-gap, 0px);
}
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {
margin-inline-end: var(--m-safe-r-gap, 0px);
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {
margin-inline-end: var(--m-safe-l-gap, 0px);
}
/* The page itself keeps clear of the sides' safe area, as iOS asks of every
app, and starts below an element in a top corner: on a Duo the status
capsule ran over the cards under the top bar (TestFlight feedback). The
padding lifts the content only by what the capsule reaches below the top
bar's row (about 70px under the top clearance), so with no corner element
it is 0. Margins, so the rail's wide:ps on the same element stays; fixed
layers are the window's and keep their own rules. The rail already takes
the leading inset on a wide window. */
app. Margins, so the rail's wide:ps on the same element stays; fixed layers
are the window's and keep their own rules. On a wide window the rail takes
the leading inset, so the page starts at the rail and ends before the
trailing inset. */
.m-page {
margin-inline: var(--m-page-l, 0px) var(--m-page-r, 0px);
padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));
margin-inline: var(--m-safe-l, 0px) var(--m-safe-r, 0px);
}
html[dir='rtl'] .m-page {
margin-inline: var(--m-page-r, 0px) var(--m-page-l, 0px);
margin-inline: var(--m-safe-r, 0px) var(--m-safe-l, 0px);
}
/* The lift above counts on a floating top bar over the page. A screen whose
first row is part of the page (m-corner-flow: settings, administration,
collections) is lifted until that row starts below the corner element; one
that keeps clear of it by itself (m-corner-own: a map under its own bars, a
calendar under its own header) is not lifted at all. */
.m-page:has(.m-corner-flow) {
padding-top: max(0px, calc(var(--m-corner-clear, 0px) - var(--m-safe-top, 12px)));
}
.m-page:has(.m-corner-own) {
padding-top: 0;
}
/* On a wide window the page starts at the top and ends before the corner
element instead (--m-corner-side-*, 0 without one). */
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
margin-inline-start: 0;
margin-inline-end: max(var(--m-page-r, 0px), var(--m-corner-side-r, 0px));
margin-inline-end: var(--m-safe-r-gap, 0px);
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
margin-inline-end: max(var(--m-page-l, 0px), var(--m-corner-side-l, 0px));
margin-inline-end: var(--m-safe-l-gap, 0px);
}
/* A screen whose background is a map reaches under the rail: the map runs to
the window's edge and the rail floats over it like the top controls do. Its
@@ -786,7 +766,7 @@ html:has(.m-shell) [data-desktop-navbar] {
html:has(.m-shell) [data-plugin-page] {
--plugin-page-h: calc(100dvh - var(--bottom-nav-h, 0px));
box-sizing: border-box;
padding-top: env(safe-area-inset-top, 0px);
padding-top: var(--m-safe-t, env(safe-area-inset-top, 0px));
padding-inline-start: var(--m-rail-w, 0px);
}
html:has(.m-shell) .leaflet-control-zoom {
+1 -1
View File
@@ -122,7 +122,7 @@ export default function MAtlas() {
return (
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
// and a map on a percentage of an auto-height parent collapses to zero.
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden">
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden">
<div ref={mapRef} className="absolute inset-0 z-[1] bg-[color:var(--m-mapb)] [&_.leaflet-control-zoom]:hidden" />
{/* Region hover tooltip — positioned imperatively by useAtlas. */}
<div
@@ -50,7 +50,7 @@ export default function MAtlasSearch({
const q = query.trim().toLowerCase()
const rows = q ? options.filter((o) => o.label.toLowerCase().includes(q)).slice(0, 6) : suggestions
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[max(calc(var(--m-safe-top,12px)+12px),var(--m-corner-clear,0px))] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[calc(var(--m-safe-top,12px)+12px)] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
return (
<div
@@ -220,7 +220,7 @@ export default function MCollections() {
// Map view fills the viewport like the trip and journal maps do (#2104);
// h-dvh because the shell owns no scroll container (#1809). List view
// keeps the document as the scroller.
className={`m-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
className={`px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
>
{split && (
<nav
@@ -66,7 +66,7 @@ export default function MUserMenu({ open, onClose }: MUserMenuProps): React.Reac
}
return (
<MDropdownPanel open={open} onClose={onClose} className="m-corner-beside end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
<MDropdownPanel open={open} onClose={onClose} className="m-safe-row end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
<div className="flex items-center gap-[10px] p-[10px_10px_12px]">
<span className="flex h-10 w-10 flex-none items-center justify-center overflow-hidden rounded-full bg-[image:linear-gradient(135deg,#6A6A74,#1A1A1E)] text-[0.9375rem] font-bold text-white">
{user?.avatar_url
@@ -346,7 +346,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
return (
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
// and a map on a percentage of an auto-height parent collapses to zero.
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
{/* Integrated map — always mounted, the gallery overlays it. Beside the feed
it begins where the feed ends, so its controls and its framing stay in
the part that can be seen. */}
@@ -358,7 +358,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
ref={mapRef}
layers={mapLayers}
hideLayerControl
controlsTop="max(calc(var(--m-safe-top, 12px) + 50px), var(--m-corner-clear, 0px))"
controlsTop="calc(var(--m-safe-top, 12px) + 50px)"
// Its satellite switch sits in the bar above, beside the menu.
baseLayer={mapBase}
onOpenEntry={handleMarkerClick}
@@ -382,7 +382,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
{/* Gallery tab overlay */}
{view === 'gallery' && (
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[calc(var(--m-safe-top,12px)+56px)] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
{gallery.length === 0 ? (
<div className="flex min-h-full flex-col items-center justify-center px-8 py-10 text-center">
<MDancingTrek scene="journey" className="mb-2" />
@@ -849,7 +849,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
* With the header in the shell's row, what the screen measures from its top
* starts right under that row instead of under a row of its own.
*/
const IN_SHELL_ROW = { '--m-safe-top': 'calc(env(safe-area-inset-top, 0px) + 6px)' } as CSSProperties
const IN_SHELL_ROW = { '--m-safe-top': 'calc(var(--m-safe-t, env(safe-area-inset-top, 0px)) + 6px)' } as CSSProperties
/** The header row: on the screen, or in the trip shell's top row when the journal is a trip tab. */
function HeaderFrame({ slot, feed, children }: { slot: HTMLElement | null; feed: boolean; children: ReactNode }) {
+12 -17
View File
@@ -1,4 +1,4 @@
import { useEffect, useLayoutEffect, useRef, useState, type ComponentType } from 'react'
import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'
import { findFocusDayId, findTodayDayId } from '../../../components/Planner/today'
import { takeResumeDay } from '../../../utils/resumeRoute'
import {
@@ -573,6 +573,13 @@ export default function MTripShell({
// one is open, otherwise the page column after the rail.
const chromeSpan = paneOpen ? 'split:end-auto split:w-[calc(var(--trip-pane)-32px)]' : ''
const paneBox = 'absolute inset-y-0 start-0 end-0 wide:start-[var(--m-rail-w)] split:end-auto split:w-[var(--trip-pane)]'
// A pane over the map. Its content keeps off the trailing side's safe area where the pane
// reaches that side (a wide window; beside the map in split it ends long before).
const pane = (layer: string, content: ReactNode) => (
<div className={`${paneBox} ${layer} bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
<div className={split ? 'relative h-full' : 'm-safe-trail relative h-full'}>{content}</div>
</div>
)
// Where the map begins. Beside an open pane, after it; while the map is the
// whole screen it runs under the floating rail to the window's edge, with its
// controls kept clear of the rail (--trip-map-inset); behind a full-width
@@ -604,26 +611,14 @@ export default function MTripShell({
<div className="absolute inset-y-0 end-0 start-[var(--trip-map-start)] transition-[inset-inline-start] duration-300 ease-out motion-reduce:transition-none">
<MapArea planner={planner} shell={shell} />
</div>
{trTab === 'plan' && view === 'plan' && mode !== 'browse' && (
<div className={`${paneBox} z-10 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
<PlanTimeline planner={planner} shell={shell} />
</div>
)}
{trTab === 'plan' && mode === 'browse' && (
<div className={`${paneBox} z-30 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
<PlacesBrowser planner={planner} shell={shell} />
</div>
)}
{trTab === 'plan' && view === 'plan' && mode !== 'browse' && pane('z-10', <PlanTimeline planner={planner} shell={shell} />)}
{trTab === 'plan' && mode === 'browse' && pane('z-30', <PlacesBrowser planner={planner} shell={shell} />)}
{/*
The stage lives at z-20, below the day chips at z-25, which is the whole
of the stage picker: the chips belong to the shell and were only ever
hidden because non-plan panels cover them at z-30.
*/}
{trTab === 'roadtrip' && rtView === 'list' && (
<div className={`${paneBox} z-20 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] split:border-e split:border-[color:var(--m-rowbr)]`}>
<TabPanel planner={planner} shell={shell} tab={trTab} />
</div>
)}
{trTab === 'roadtrip' && rtView === 'list' && pane('z-20', <TabPanel planner={planner} shell={shell} tab={trTab} />)}
{trTab === 'roadtrip' && rtView === 'map' && (
// The stage's bars keep to the page column while the map runs under the rail.
<div className="pointer-events-none absolute inset-0 wide:start-[var(--m-rail-w)]">
@@ -634,7 +629,7 @@ export default function MTripShell({
)}
{!MAP_TABS.has(trTab) && (
<div className="absolute inset-0 z-30 bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] wide:start-[var(--m-rail-w)]">
<div className="m-corner-side relative h-full">
<div className="m-safe-trail relative h-full">
<TabPanel planner={planner} shell={shell} tab={trTab} />
</div>
</div>
@@ -68,7 +68,7 @@ export function GlassSegment({ children, activeKey }: { children: ReactNode; act
* The box of the trip's floating rows (the top controls, the day chips): the page's width after
* the rail, beside an element in a top corner such as a Duo's status capsule (mobile.css).
*/
export const CHROME_ROW = 'm-corner-beside absolute end-4 start-[calc(var(--m-rail-w,0px)+16px)]';
export const CHROME_ROW = 'm-safe-row absolute end-4 start-[calc(var(--m-rail-w,0px)+16px)]';
/** A phone's header group: after the back button (transports, bookings), or centred on the bar (costs, files). */
export const ROW_AFTER_BACK = 'absolute start-[52px] end-2 justify-center';
@@ -216,10 +216,10 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
hidden={hidden}
tabIndex={-1}
onKeyDown={(e) => keepTabInside(e, sectionRef.current)}
className={`m-corner-side fixed inset-0 z-[var(--z-bar)] ${hidden ? 'hidden' : 'flex'} m-panel-in flex-col bg-[var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink outline-none wide:inset-auto wide:bottom-3 wide:end-3 wide:top-3 wide:w-[min(500px,calc(100vw-var(--m-rail-w,0px)-24px))] wide:overflow-hidden wide:rounded-[28px] wide:border wide:border-[color:var(--m-shbr)] wide:shadow-modal`}
className={`m-safe-trail fixed inset-0 z-[var(--z-bar)] ${hidden ? 'hidden' : 'flex'} m-panel-in flex-col bg-[var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink outline-none wide:inset-auto wide:bottom-3 wide:end-3 wide:top-3 wide:w-[min(500px,calc(100vw-var(--m-rail-w,0px)-24px))] wide:overflow-hidden wide:rounded-[28px] wide:border wide:border-[color:var(--m-shbr)] wide:shadow-modal`}
style={{ paddingBottom: `max(env(safe-area-inset-bottom, 0px), ${keyboard}px)` }}
>
<header className="m-corner-beside-in flex flex-none items-center gap-2 px-4 pb-2 pt-[var(--m-safe-top,12px)] wide:pt-3">
<header className="flex flex-none items-center gap-2 px-4 pb-2 pt-[var(--m-safe-top,12px)] wide:pt-3">
<MIconBtn ariaLabel={t('common.back')} onClick={close}>
<ChevronLeft size={19} strokeWidth={2.2} />
</MIconBtn>
@@ -256,7 +256,7 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
<MDropdownPanel
open={panel === 'history'}
onClose={() => setPanel(null)}
className="m-corner-beside-in end-4 top-[calc(var(--m-safe-top,12px)+48px)] max-h-[60vh] overflow-y-auto"
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)] max-h-[60vh] overflow-y-auto"
>
<MListRow icon={Plus} label={t('assistant.history.new')} onClick={() => pick(thread.newThread)} />
{threads.length === 0 ? (
@@ -285,7 +285,7 @@ export function AssistantScreen({ tripId, tripTitle, hidden, hops, onOpenTripCha
<MDropdownPanel
open={panel === 'menu'}
onClose={() => setPanel(null)}
className="m-corner-beside-in end-4 top-[calc(var(--m-safe-top,12px)+48px)]"
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)]"
>
{tripChat && (
<MListRow
@@ -473,7 +473,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
<div
// Beside the trip's pane nothing lies over the map, so the bar takes the
// top edge, level with the pane's own top row.
className={`m-corner-beside pointer-events-none absolute end-4 start-[calc(var(--trip-map-inset,0px)+16px)] z-[25] flex flex-col items-center gap-2 ${
className={`m-safe-row pointer-events-none absolute end-4 start-[calc(var(--trip-map-inset,0px)+16px)] z-[25] flex flex-col items-center gap-2 ${
shell.paneOpen ? 'top-[var(--m-safe-top,12px)]' : 'top-[calc(var(--m-safe-top,12px)+96px)]'
}`}
>
@@ -118,7 +118,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
return (
<div className="flex h-full flex-col">
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]">
{/* ── Places/Tours, the filter chips and Import (Add sits in the search row
below to free space). The switch has a row of its own, except where the
screen is short (a phone on its side): there it shares the chips' row,
@@ -212,7 +212,7 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
Beside the map the card is the pane and runs down to that line, as the
places list does; across the page it is as tall as its day, so a short
day leaves no empty card under it. */}
<div className="absolute inset-x-4 flex flex-col gap-3 top-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))] bottom-[calc(env(safe-area-inset-bottom,0px)+90px)] wide:bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
<div className="absolute inset-x-4 flex flex-col gap-3 top-[calc(var(--m-safe-top,12px)+102px)] bottom-[calc(env(safe-area-inset-bottom,0px)+90px)] wide:bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
{!editing && <UpNextCard tl={tl} t={t} onOpen={openPlace} />}
{editing && <EditHeader tl={tl} planner={planner} shell={shell} />}
@@ -64,7 +64,7 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
// fall back to the trip's first routed day, which is not the one on screen, and every
// distance it answered with would be measured against a road nobody is looking at.
const searchBar = stage && (
<div className="m-corner-beside pointer-events-auto absolute inset-x-4 top-[calc(var(--m-safe-top,12px)+96px)] z-[26]">
<div className="m-safe-row pointer-events-auto absolute inset-x-4 top-[calc(var(--m-safe-top,12px)+96px)] z-[26]">
<MRtCorridorBar planner={planner} corridor={corridor} onOpen={() => shell.openSheet('rtsearch')} />
</div>
)
@@ -197,7 +197,7 @@ function RoadtripStagePage({ planner, shell, dayId: pageDayId, alts, chrome }: O
return (
<div
className={`absolute inset-0 overflow-x-hidden overflow-y-auto overscroll-y-contain px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] ${
stage ? 'pt-[max(calc(var(--m-safe-top,12px)+150px),var(--m-corner-clear,0px))]' : 'pt-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))]'
stage ? 'pt-[calc(var(--m-safe-top,12px)+150px)]' : 'pt-[calc(var(--m-safe-top,12px)+102px)]'
}`}
>
<UndatedRides rides={undated} t={t} onOpen={openBooking} />
@@ -7,7 +7,7 @@ import { useTranslation } from '../../../../i18n'
import { useSettingsStore } from '../../../../store/settingsStore'
import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants'
import { splitReservationDateTime } from '../../../../utils/formatters'
import { getFlightLegs, getTrainLegs, usesStationRoute, type FlightLeg, type TrainLeg } from '../../../../utils/flightLegs'
import { getFlightLegs, getTrainLegs, seatLabel, seatsOfLegs, usesStationRoute, type FlightLeg, type TrainLeg } from '../../../../utils/flightLegs'
import { runsOnDay } from '../../../../utils/reservationRoutes'
import { filesFor } from '../../../../utils/reservationFiles'
import { bookingDayLabel, segmentCodeLabel } from '../../../../components/Planner/transportDetailModel'
@@ -169,8 +169,12 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
if (leg && (leg.from || leg.to)) subParts.push(flowText([leg.from, leg.to].filter((n): n is string => !!n)))
else if (from?.name && to?.name) subParts.push(flowText([from.name, to.name]))
// A flight's legs carry no seat or platform of their own, so those stay the booking's.
const seat = leg && !isFlight ? legDetail.seat : meta.seat
// Opened from a leg, that leg's own seat; the whole booking lists the seat of
// every leg that has one, each under its route, rather than only the first's.
const seats: { route: string | null; seat: string }[] = leg ? (legDetail.seat ? [{ route: null, seat: legDetail.seat }] : []) : seatsOfLegs(routeLegs, meta.seat)
const ownSeat = seats.find(s => s.route == null)?.seat
const legSeats = seats.filter(s => s.route != null)
// A flight's legs carry no platform of their own, so that stays the booking's.
const platform = leg && !isFlight ? legDetail.platform : meta.platform
const transitLegs: TransitLeg[] = Array.isArray(meta.transit?.legs) ? meta.transit.legs : []
@@ -212,6 +216,9 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
)
: []
// The times, platform and booking seat; each leg's seat gets a row of its own below it.
const statRow = hotelStats.length === 0 && ((showTimes && (depTime || arrTime)) || !!ownSeat || !!platform)
// The editor that fits the booking: transports have their own, everything
// else (a stay, a table, a ticket) the booking editor, as in the Bookings tab.
const editTransport = () => {
@@ -275,7 +282,7 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
))}
{/* ── Times / seat stats (the live card already shows the times) ── */}
{hotelStats.length === 0 && ((showTimes && (depTime || arrTime)) || seat || platform) && (
{statRow && (
<div className="mt-[14px] flex gap-[6px]">
{showTimes && depTime && (
<StatBox caption={depDate} value={displayTime(depTime, locale, timeFormat)} label={depLabel} />
@@ -284,7 +291,12 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
<StatBox caption={arrDate} value={displayTime(arrTime, locale, timeFormat)} label={arrLabel} />
)}
{platform && <StatBox value={platform} label={t('reservations.meta.platform')} />}
{seat && <StatBox value={seat} label={t('reservations.meta.seat')} />}
{ownSeat && <StatBox value={ownSeat} label={t('reservations.meta.seat')} />}
</div>
)}
{hotelStats.length === 0 && legSeats.length > 0 && (
<div className={`${statRow ? 'mt-[6px]' : 'mt-[14px]'} flex gap-[6px]`}>
{legSeats.map((s, i) => <StatBox key={i} value={s.seat} label={seatLabel(t('reservations.meta.seat'), s.route)} />)}
</div>
)}
@@ -11,7 +11,7 @@ import { cardWhen, parseTransportMeta, timeRange } from './transportsModel'
import { BOOKING_TYPE_COLOR, hotelStayTimes } from '../../../../components/Planner/bookings/bookingsModel'
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
import { orderedEndpoints } from '../../../../utils/flightLegs'
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
import { filesFor } from '../../../../utils/reservationFiles'
/**
@@ -115,7 +115,7 @@ function BookingCard({ res, planner, canEdit, compact, onView }: {
if (!hasEndpoints && meta.departure_airport) metaCells.push({ label: t('reservations.meta.from'), value: meta.departure_airport })
if (!hasEndpoints && meta.arrival_airport) metaCells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
if (meta.platform) metaCells.push({ label: t('reservations.meta.platform'), value: meta.platform })
if (meta.seat) metaCells.push({ label: t('reservations.meta.seat'), value: meta.seat + (meta.class ? ` · ${meta.class}` : '') })
metaCells.push(...seatCells(res, t('reservations.meta.seat'), meta.class ? ` · ${meta.class}` : ''))
if (meta.price != null && meta.price !== '') {
metaCells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, planner.trip?.currency, locale) })
}
@@ -91,7 +91,7 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
return (
<div
className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]"
className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]"
style={keyboard > 0 ? { paddingBottom: keyboard + 8 } : undefined}
>
{loading ? (
@@ -74,7 +74,7 @@ function CollabPanel({ planner, tab }: { planner: MTabScreenProps['planner']; ta
if (tab === 'chat') {
if (!planner.collabFeatures.chat) {
return (
<div className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
<div className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)]">
<CollabDisabledNotice icon={MessageCircle} label={label} />
</div>
)
@@ -265,12 +265,12 @@ export default function MFilesTab({ planner, shell }: MTabScreenProps) {
if (split && picked) {
return (
<div className="flex h-full">
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-[calc(var(--bottom-nav-h,84px)+22px)] pe-3 ps-6 pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]">
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-[calc(var(--bottom-nav-h,84px)+22px)] pe-3 ps-6 pt-[calc(var(--m-safe-top,12px)+58px)]">
{body}
</div>
<aside
aria-label={t('common.preview')}
className="m-pane-trail min-h-0 flex-none overflow-y-auto overflow-x-hidden border-s border-[color:var(--m-rowbr)] px-5 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]"
className="m-pane-trail min-h-0 flex-none overflow-y-auto overflow-x-hidden border-s border-[color:var(--m-rowbr)] px-5 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]"
>
<FilePreviewPane
file={picked}
@@ -10,7 +10,7 @@ import { cardWhen, parseTransportMeta } from './transportsModel'
import { TRANSPORT_TYPE_COLOR } from '../../../../components/Planner/bookings/bookingsModel'
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
import { orderedEndpoints } from '../../../../utils/flightLegs'
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
import { filesFor } from '../../../../utils/reservationFiles'
import MFlightLiveStrip from '../MFlightLiveStrip'
@@ -113,7 +113,7 @@ function TransportCard({ res, planner, shell, canEdit, compact }: {
if (!hasEndpoints && meta.arrival_airport) metaCells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
if (meta.train_number) metaCells.push({ label: t('reservations.meta.trainNumber'), value: meta.train_number })
if (meta.platform) metaCells.push({ label: t('reservations.meta.platform'), value: meta.platform })
if (meta.seat) metaCells.push({ label: t('reservations.meta.seat'), value: meta.seat + (meta.class ? ` · ${meta.class}` : '') })
metaCells.push(...seatCells(res, t('reservations.meta.seat'), meta.class ? ` · ${meta.class}` : ''))
if (meta.price != null && meta.price !== '') {
metaCells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, planner.trip?.currency, locale) })
}
@@ -37,7 +37,7 @@ export default function MTripTabPanel({ planner, shell, tab }: MTripTabPanelProp
if (tab.startsWith('plugin:')) {
return (
<div
className="absolute inset-0 pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+22px)]"
className="absolute inset-0 pt-[calc(var(--m-safe-top,12px)+58px)] pb-[calc(var(--bottom-nav-h,84px)+22px)]"
>
<PluginFrame
pluginId={tab.slice('plugin:'.length)}
@@ -78,7 +78,7 @@ export default function MTripTabPanel({ planner, shell, tab }: MTripTabPanelProp
// below the trip's floating top controls: its bars measure from --m-safe-top.
case 'journal':
return planner.journalId == null ? null : (
<div className="absolute inset-0 overflow-hidden [--m-safe-top:calc(env(safe-area-inset-top,0px)+62px)]">
<div className="absolute inset-0 overflow-hidden [--m-safe-top:calc(var(--m-safe-t,env(safe-area-inset-top,0px))+62px)]">
<MJourneyDetail journeyId={planner.journalId} embedded />
</div>
)
@@ -33,8 +33,8 @@ export function TabScroller({ children, wide = 'readable' }: { children: ReactNo
}
/** The room a tab's scroll body keeps clear: the floating top controls above, the dock (or the home indicator) below. */
const TAB_INSETS = 'px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))] wide:px-6'
const PANE_INSETS = 'pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]'
const TAB_INSETS = 'px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:px-6'
const PANE_INSETS = 'pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]'
/**
* The cards of a list tab (transports, bookings, tasks, polls): one column on a
+3 -3
View File
@@ -91,9 +91,9 @@ export default function MVacay() {
return (
// h-dvh, not h-full: the shell stopped providing a definite height (#1809).
<div className="m-corner-own relative h-dvh">
<div className="relative h-dvh">
{/* Header, beside a corner element (a Duo's status capsule) upright */}
<div className="m-corner-beside-in absolute inset-x-4 z-[5] flex items-center gap-2 top-[var(--m-safe-top,12px)]">
<div className="absolute inset-x-4 z-[5] flex items-center gap-2 top-[var(--m-safe-top,12px)]">
<MIconBtn onClick={() => v.setSheet('invite')} ariaLabel={t('vacay.inviteUser')}>
<UserPlus size={16} strokeWidth={2} className="text-m-muted" />
</MIconBtn>
@@ -115,7 +115,7 @@ export default function MVacay() {
</div>
{/* Scroll container */}
<div className={`absolute inset-0 overflow-y-auto px-4 pt-[max(calc(var(--m-safe-top,12px)+44px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+12px)] ${edit ? 'wide:pb-[calc(env(safe-area-inset-bottom,0px)+84px)]' : ''}`}>
<div className={`absolute inset-0 overflow-y-auto px-4 pt-[calc(var(--m-safe-top,12px)+44px)] pb-[calc(var(--bottom-nav-h,84px)+12px)] ${edit ? 'wide:pb-[calc(env(safe-area-inset-bottom,0px)+84px)]' : ''}`}>
{/* Selected person card */}
{v.selectedUser && stat && (
<div className="mt-2 flex items-center gap-3 rounded-[18px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-[14px] py-[9px]">
+14
View File
@@ -168,6 +168,20 @@ describe('watchBooking', () => {
});
});
it('carries the seat of every leg of a flight with a stop, also one booked only on the second', () => {
const stopover = reservation({
...flight,
metadata: JSON.stringify({
legs: [
{ from: 'MXP', to: 'IST' },
{ from: 'IST', to: 'JFK', seat: '14C' },
],
}),
});
const b = watchBooking(stopover, { day: '2026-11-17', time: '13:05' }, { dayDates: new Map(), places: new Map() });
expect(b.seat).toBe('14C');
});
it('gives a stay its check-in, check-out, dates from its days and the hotel as the place to go', () => {
const dayDates = new Map([
[2, '2026-11-18'],
+8 -2
View File
@@ -1,5 +1,5 @@
import type { Day, PackingItem, Place, Reservation, TodoItem, Trip } from '../types';
import { parseReservationMetadata } from '../utils/flightLegs';
import { bookingSeats, parseReservationMetadata } from '../utils/flightLegs';
import { splitReservationDateTime } from '../utils/formatters';
import { hasNativeFeature } from './capabilities';
import { isNativeIos } from './platform';
@@ -274,7 +274,13 @@ export function watchBooking(
to: point(to),
code: text(r.confirmation_number, 40),
carrier: carrierOf(meta),
seat: metaText(meta, 'seat'),
// A flight or train with a stop: the seat of every leg, not only the first leg's.
seat: text(
bookingSeats(r)
.map((s) => s.seat)
.join(', '),
20
),
platform: metaText(meta, 'platform'),
...whereOf(r, places),
checkIn: metaText(meta, 'check_in_time'),
+17
View File
@@ -192,6 +192,23 @@ describe('getTransportForDay', () => {
expect(day2[0].__leg).toMatchObject({ index: 1, from: 'Frankfurt', to: 'München', train_number: 'ICE 500', platform: '9' })
})
it('gives each leg of a flight with a stop its own seat, the first leg the flat one when it has none', () => {
const flight = (legs: object[], seat?: string) => [{
id: 42, type: 'flight', day_id: 1, end_day_id: 1,
metadata: JSON.stringify({ ...(seat ? { seat } : {}), legs }),
}]
const legs = [
{ from: 'MXP', to: 'IST', dep_day_id: 1, dep_time: '11:00', arr_day_id: 1, arr_time: '15:10' },
{ from: 'IST', to: 'JFK', seat: '14C', dep_day_id: 1, dep_time: '17:05', arr_day_id: 1, arr_time: '20:40' },
]
const rows = getTransportForDay({ reservations: flight(legs), dayId: 1, dayAssignmentIds: [], days })
expect(rows.map(r => r.__leg.seat)).toEqual([null, '14C'])
// A booking saved before legs had seats keeps its flat seat on the first leg only.
const unseated = [{ ...legs[0] }, { ...legs[1], seat: undefined }]
const legacy = getTransportForDay({ reservations: flight(unseated, '3A'), dayId: 1, dayAssignmentIds: [], days })
expect(legacy.map(r => r.__leg.seat)).toEqual(['3A', null])
})
it('leaves a single-leg train untouched (no __leg)', () => {
const reservations = [{ id: 41, type: 'train', day_id: 1, end_day_id: 1, metadata: JSON.stringify({ train_number: 'RE 1' }) }]
const rows = getTransportForDay({ reservations, dayId: 1, dayAssignmentIds: [], days })
+10 -4
View File
@@ -156,7 +156,12 @@ function parseMultiLegs(r: any): any[] | null {
// Defensive: recover metadata that was accidentally double-encoded by an earlier
// bug (a JSON string of a JSON string) so already-saved bookings heal on read.
if (typeof meta === 'string') { try { meta = JSON.parse(meta || '{}') } catch { meta = {} } }
if (meta && Array.isArray(meta.legs) && meta.legs.length > 1) return meta.legs
if (meta && Array.isArray(meta.legs) && meta.legs.length > 1) {
// The flat seat mirrors the first leg's, so a booking saved before legs had
// seats keeps it on its first leg (flightLegs' legSeat reads it the same way).
const flatSeat = typeof meta.seat === 'string' && meta.seat ? meta.seat : null
return meta.legs.map((l: Record<string, unknown> | null, i: number) => (i === 0 && flatSeat && !l?.seat ? { ...l, seat: flatSeat } : l))
}
return null
}
@@ -200,9 +205,10 @@ export function expandFlightLegsForDay(
index: i, total: legs.length,
from: leg.from ?? null, to: leg.to ?? null,
airline: leg.airline ?? null, flight_number: leg.flight_number ?? null,
// Train legs carry their own per-leg detail; added only for trains so a
// flight's __leg object stays byte-identical to before.
...(r.type === 'train' ? { train_number: leg.train_number ?? null, platform: leg.platform ?? null, seat: leg.seat ?? null } : {}),
// Each leg's own seat, a flight's too: it is saved per leg, and reading the
// booking's flat seat showed the first leg's on every leg.
seat: leg.seat ?? null,
...(r.type === 'train' ? { train_number: leg.train_number ?? null, platform: leg.platform ?? null } : {}),
},
})
})
+37 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { getFlightLegs, getTrainLegs, isMultiLegTrain, stripAirportCode, usesStationRoute } from './flightLegs'
import { bookingSeats, getFlightLegs, getTrainLegs, isMultiLegTrain, seatCells, seatLabel, stripAirportCode, usesStationRoute } from './flightLegs'
import type { Reservation } from '../types'
function res(partial: Partial<Reservation>): Reservation {
@@ -97,6 +97,42 @@ describe('per-segment booking references (#1943)', () => {
})
})
describe('the seats of a booking with a stop', () => {
const stopover = (legs: object[], extra: Record<string, unknown> = {}) =>
res({ type: 'flight', metadata: JSON.stringify({ ...extra, legs }) })
it('reads each flight leg its own seat, so one booked only on the second leg is not lost', () => {
const r = stopover([{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }])
expect(getFlightLegs(r).map(l => l.seat)).toEqual([undefined, '14C'])
expect(bookingSeats(r)).toEqual([{ route: 'IST → JFK', seat: '14C' }])
})
it('gives the first leg the flat seat when it has none of its own, as the booking form does', () => {
const r = stopover([{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK' }], { seat: '3A' })
expect(getFlightLegs(r).map(l => l.seat)).toEqual(['3A', undefined])
expect(bookingSeats(r)).toEqual([{ route: 'MXP → IST', seat: '3A' }])
})
it('lists a train with a stop leg by leg too', () => {
const r = res({ metadata: JSON.stringify({ legs: [{ from: 'Takayama', to: 'Nagoya', seat: '10-4C' }, { from: 'Nagoya', to: 'Kyoto', seat: '4-5A' }] }) })
expect(bookingSeats(r)).toEqual([{ route: 'Takayama → Nagoya', seat: '10-4C' }, { route: 'Nagoya → Kyoto', seat: '4-5A' }])
})
it('gives a booking of one leg, of any type, its own seat without a route', () => {
expect(bookingSeats(res({ type: 'flight', metadata: JSON.stringify({ seat: '31A' }) }))).toEqual([{ route: null, seat: '31A' }])
expect(bookingSeats(res({ type: 'event', metadata: JSON.stringify({ seat: 'Row 4' }) }))).toEqual([{ route: null, seat: 'Row 4' }])
expect(bookingSeats(res({ type: 'flight', metadata: null }))).toEqual([])
})
it('labels a leg seat with its route and a booking seat plainly', () => {
expect(seatLabel('Seat', 'IST → JFK')).toBe('Seat IST → JFK')
expect(seatLabel('Seat', null)).toBe('Seat')
const r = stopover([{ from: 'MXP', to: 'IST', seat: '3A' }, { from: 'IST', to: 'JFK', seat: '14C' }])
expect(seatCells(r, 'Seat', ' · Economy')).toEqual([{ label: 'Seat', value: '3A, 14C · Economy' }])
expect(seatCells(res({ type: 'flight', metadata: null }), 'Seat')).toEqual([])
})
})
describe('stripAirportCode', () => {
it('drops the code the forms and the airport backfill append, and nothing else', () => {
expect(stripAirportCode('Paris Charles de Gaulle (CDG)')).toBe('Paris Charles de Gaulle')
+53 -3
View File
@@ -19,6 +19,8 @@ export interface FlightLeg {
to: string | null
airline?: string
flight_number?: string
/** This leg's own seat; the first leg falls back to the booking's flat seat (see legSeat). */
seat?: string
/** This segment's own booking reference, when it was booked separately (#1943). */
confirmation_number?: string
dep_day_id?: number | null
@@ -67,11 +69,12 @@ export function stripAirportCode(name: string): string {
export function getFlightLegs(r: Reservation): FlightLeg[] {
const meta = parseReservationMetadata(r)
if (Array.isArray(meta.legs) && meta.legs.length > 0) {
return meta.legs.map((l: any): FlightLeg => ({
return meta.legs.map((l: any, i: number): FlightLeg => ({
from: l.from ?? null,
to: l.to ?? null,
airline: l.airline || undefined,
flight_number: l.flight_number || undefined,
seat: legSeat(l, i, meta),
confirmation_number: l.confirmation_number || undefined,
dep_day_id: l.dep_day_id ?? null,
dep_time: l.dep_time ?? null,
@@ -91,6 +94,7 @@ export function getFlightLegs(r: Reservation): FlightLeg[] {
to: toCode,
airline: meta.airline || undefined,
flight_number: meta.flight_number || undefined,
seat: meta.seat || undefined,
// The single segment IS the booking, so its reference is the booking's.
confirmation_number: r.confirmation_number || undefined,
dep_day_id: r.day_id ?? null,
@@ -127,12 +131,12 @@ export interface TrainLeg {
export function getTrainLegs(r: Reservation): TrainLeg[] {
const meta = parseReservationMetadata(r)
if (Array.isArray(meta.legs) && meta.legs.length > 0) {
return meta.legs.map((l: any): TrainLeg => ({
return meta.legs.map((l: any, i: number): TrainLeg => ({
from: l.from ?? null,
to: l.to ?? null,
train_number: l.train_number || undefined,
platform: l.platform || undefined,
seat: l.seat || undefined,
seat: legSeat(l, i, meta),
confirmation_number: l.confirmation_number || undefined,
dep_day_id: l.dep_day_id ?? null,
dep_time: l.dep_time ?? null,
@@ -161,6 +165,52 @@ export function getTrainLegs(r: Reservation): TrainLeg[] {
}]
}
/**
* A leg's own seat. The flat `metadata.seat` mirrors the first leg's, so a
* booking saved before legs carried seats, or one an import gave only the flat
* seat, still shows it on its first leg, as the booking form reads it.
*/
function legSeat(leg: { seat?: unknown } | null | undefined, index: number, meta: { seat?: unknown }): string | undefined {
if (typeof leg?.seat === 'string' && leg.seat) return leg.seat
return index === 0 && typeof meta.seat === 'string' && meta.seat ? meta.seat : undefined
}
/**
* The seats of a booking, each with the route of the leg it belongs to. A flight
* or train with a stop lists one per leg that has a seat, so a seat booked only
* on the second leg is not lost behind the first leg's empty one; any other
* booking gives its own seat with no route.
*/
export function bookingSeats(r: Reservation): { route: string | null; seat: string }[] {
const legs: (FlightLeg | TrainLeg)[] =
r.type === 'flight' ? getFlightLegs(r) : usesStationRoute(r.type) ? getTrainLegs(r) : []
return seatsOfLegs(legs, parseReservationMetadata(r).seat)
}
/** bookingSeats for legs already read (getFlightLegs or getTrainLegs) and the booking's flat seat. */
export function seatsOfLegs(legs: readonly (FlightLeg | TrainLeg)[], flatSeat: unknown): { route: string | null; seat: string }[] {
if (legs.length > 1) {
return legs.flatMap((l) => (l.seat ? [{ route: [l.from, l.to].filter(Boolean).join(' → ') || null, seat: l.seat }] : []))
}
return typeof flatSeat === 'string' && flatSeat ? [{ route: null, seat: flatSeat }] : []
}
/** The label of one of bookingSeats' seats: "Seat", or "Seat FRA → IST" for a leg. */
export function seatLabel(seatWord: string, route: string | null): string {
return route ? `${seatWord} ${route}` : seatWord
}
/**
* bookingSeats as the one Seat cell of a booking's field grid: every leg's seat
* in route order, then `suffix` (its class). One cell, because a card cuts its
* grid after a few cells and a route in the label does not fit a narrow one;
* the detail views name each leg's seat under its route.
*/
export function seatCells(r: Reservation, seatWord: string, suffix = ''): { label: string; value: string }[] {
const seats = bookingSeats(r)
return seats.length ? [{ label: seatWord, value: seats.map((s) => s.seat).join(', ') + suffix }] : []
}
/** Number of flight segments. 1 for a simple from -> to booking. */
export function legCount(r: Reservation): number {
return getFlightLegs(r).length
+1 -1
View File
@@ -507,7 +507,7 @@ describe('MSheet', () => {
<span>body</span>
</MSheet>,
);
expect(region().className).toContain('top-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))]');
expect(region().className).toContain('top-[var(--m-safe-top,12px)]');
expect(region().className).toContain('bottom-[calc(var(--bottom-nav-h,84px)+12px)]');
expect(panel().className).toContain('max-h-full');
});
+53 -76
View File
@@ -52,12 +52,15 @@ describe('MGlassBar', () => {
describe('safe area in the touch shell', () => {
// jsdom applies no stylesheet and has no env(), so the rules are read from source.
const css = readFileSync(resolve(root, 'src/mobile/mobile.css'), 'utf8');
const wideRoot = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
const rtlWideRoot = "html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
const block = (selector: string) => css.split(selector)[1]?.split('}')[0] ?? '';
it('FE-MOB-CHROME-004: the top clearance takes env() with the measurement of the app as a floor, never in its place', () => {
expect(css).toContain('--m-safe-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));');
it('FE-MOB-CHROME-004: the insets take env() with the measurement of the app as a floor, never in its place', () => {
expect(css).toContain('--m-raw-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));');
expect(css).toContain('--m-raw-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));');
expect(css).toContain('--m-raw-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));');
expect(css).toContain('--m-safe-top: calc(var(--m-safe-t) + 12px);');
expect(css).toContain('--m-safe-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));');
expect(css).toContain('--m-safe-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));');
});
it('FE-MOB-CHROME-005: without the rail the floating bars keep clear of a side inset, such as a camera in a corner', () => {
@@ -74,92 +77,66 @@ describe('safe area in the touch shell', () => {
});
it('FE-MOB-CHROME-006: a side inset gets a little air, and none where there is no inset', () => {
expect(css).toContain('--m-safe-r-gap: calc(var(--m-bar-r) + min(var(--m-bar-r), 8px));');
expect(css).toContain('--m-safe-l-gap: calc(var(--m-bar-l) + min(var(--m-bar-l), 8px));');
expect(css).toContain('--m-safe-r-gap: calc(var(--m-safe-r) + min(var(--m-safe-r), 8px));');
expect(css).toContain('--m-safe-l-gap: calc(var(--m-safe-l) + min(var(--m-safe-l), 8px));');
});
it('FE-MOB-CHROME-007: on a wide window the bars end before the trailing inset, by their box, not a margin', () => {
const wide = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-bar-x {";
expect(css.split(wide)[1]?.split('}')[0] ?? '').toContain(
'inset-inline-end: calc(16px + var(--m-safe-r-gap, 0px));'
);
expect(block(wide)).toContain('inset-inline-end: calc(16px + var(--m-safe-r-gap, 0px));');
const rtl = `html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-bar-x {`;
expect(css.split(rtl)[1]?.split('}')[0] ?? '').toContain(
'inset-inline-end: calc(16px + var(--m-safe-l-gap, 0px));'
);
expect(block(rtl)).toContain('inset-inline-end: calc(16px + var(--m-safe-l-gap, 0px));');
});
it('FE-MOB-CHROME-008: the page keeps clear of the side insets, the leading one left to the rail on a wide window', () => {
expect(css.split('\n.m-page {')[1]?.split('}')[0] ?? '').toContain(
'margin-inline: var(--m-page-l, 0px) var(--m-page-r, 0px);'
);
expect(css.split("html[dir='rtl'] .m-page {")[1]?.split('}')[0] ?? '').toContain(
'margin-inline: var(--m-page-r, 0px) var(--m-page-l, 0px);'
);
const wide = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {";
expect(css.split(wide)[1]?.split('}')[0] ?? '').toContain('margin-inline-start: 0;');
expect(block('\n.m-page {')).toContain('margin-inline: var(--m-safe-l, 0px) var(--m-safe-r, 0px);');
expect(block('\n.m-page {')).not.toContain('padding-top');
expect(block("html[dir='rtl'] .m-page {")).toContain('margin-inline: var(--m-safe-r, 0px) var(--m-safe-l, 0px);');
const wide = block("html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {");
expect(wide).toContain('margin-inline-start: 0;');
expect(wide).toContain('margin-inline-end: var(--m-safe-r-gap, 0px);');
const rtlWide = block("html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {");
expect(rtlWide).toContain('margin-inline-end: var(--m-safe-l-gap, 0px);');
});
it('FE-MOB-CHROME-009: an element in a top corner moves the bars beside it and the page below it, not a whole strip aside', () => {
// The bars avoid the wider of the side inset and the corner element.
expect(css).toContain('--m-bar-r: max(var(--m-safe-r), var(--trek-native-corner-right, 0px));');
expect(css).toContain('--m-bar-l: max(var(--m-safe-l), var(--trek-native-corner-left, 0px));');
// The page gives the corner's width back and starts below the corner instead.
expect(css).toContain('--m-page-r: max(0px, var(--m-safe-r) - var(--trek-native-corner-right, 0px));');
expect(css).toContain('--m-page-l: max(0px, var(--m-safe-l) - var(--trek-native-corner-left, 0px));');
expect(css.split('\n.m-page {')[1]?.split('}')[0] ?? '').toContain(
'padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));'
);
expect(css).toContain('--m-corner-clear: calc(var(--m-corner-b) + min(var(--m-corner-b), 10px));');
// Without a corner element (every other device, iOS before 26) nothing moves.
expect(css).toContain('--m-corner-b: var(--trek-native-corner-bottom, 0px);');
it('FE-MOB-CHROME-009: upright, an element in a top corner counts as top inset, and the sides keep their width', () => {
// A Duo's status capsule: everything that clears the top clears it too.
expect(css).toContain('--m-safe-t: max(var(--m-raw-t), var(--trek-native-corner-bottom, 0px));');
// iOS reports it as a side inset as well; upright that width is given back.
expect(css).toContain('--m-safe-l: max(0px, var(--m-raw-l) - var(--trek-native-corner-left, 0px));');
expect(css).toContain('--m-safe-r: max(0px, var(--m-raw-r) - var(--trek-native-corner-right, 0px));');
});
it('FE-MOB-CHROME-010: on a wide window the page ends before a corner element instead of starting below it', () => {
const wideRoot = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
const block = css.split(wideRoot)[1]?.split('}')[0] ?? '';
expect(block).toContain('--m-corner-clear: 0px;');
expect(block).toContain('--m-corner-side-r: var(--m-corner-r-gap);');
expect(block).toContain('--m-rail-w: calc(var(--m-bar-l) + 100px);');
const widePage = "html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {";
expect(css.split(widePage)[1]?.split('}')[0] ?? '').toContain(
'margin-inline-end: max(var(--m-page-r, 0px), var(--m-corner-side-r, 0px));'
);
// Right to left the rail stands on the corner's side and takes it.
const rtlRoot = "html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {";
const rtl = css.split(rtlRoot)[1]?.split('}')[0] ?? '';
expect(rtl).toContain('--m-rail-w: calc(var(--m-bar-r) + 100px);');
expect(rtl).toContain('--m-corner-side-r: 0px;');
it('FE-MOB-CHROME-010: on a wide window the corner element takes its side over the whole height instead', () => {
const wide = block(wideRoot);
expect(wide).toContain('--m-safe-t: var(--m-raw-t);');
expect(wide).toContain('--m-safe-l: max(var(--m-raw-l), var(--trek-native-corner-left, 0px));');
expect(wide).toContain('--m-safe-r: max(var(--m-raw-r), var(--trek-native-corner-right, 0px));');
expect(wide).toContain('--m-rail-w: calc(var(--m-safe-l) + 100px);');
// Right to left the rail stands on the other side and takes that inset.
expect(block(rtlWideRoot)).toContain('--m-rail-w: calc(var(--m-safe-r) + 100px);');
});
it('FE-MOB-CHROME-011: the screens that place their own controls keep them beside a corner element and their content below it', () => {
const corner = readFileSync(resolve(root, 'src/mobile/corner.css'), 'utf8');
expect(corner).toMatch(
/\.m-corner-beside \{\s*margin-inline: var\(--m-corner-l-gap, 0px\) var\(--m-corner-r-gap, 0px\);/
);
// The element stays where the hardware has it, so right to left swaps the sides back.
expect(corner).toMatch(
/html\[dir='rtl'\] \.m-corner-beside \{\s*margin-inline: var\(--m-corner-r-gap, 0px\) var\(--m-corner-l-gap, 0px\);/
);
expect(corner).toMatch(
/\.m-corner-side \{\s*margin-inline: var\(--m-corner-side-l, 0px\) var\(--m-corner-side-r, 0px\);/
);
expect(css).toMatch(/\.m-page:has\(\.m-corner-own\) \{\s*padding-top: 0;/);
expect(readFileSync(resolve(root, 'src/mobile/MobileShell.tsx'), 'utf8')).toContain("import './corner.css'");
it('FE-MOB-CHROME-011: rows and layers a screen places itself keep to the same insets, and no screen handles the corner on its own', () => {
const narrowRow = "html:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {";
expect(block(narrowRow)).toContain('margin-inline: var(--m-safe-l-gap, 0px) var(--m-safe-r-gap, 0px);');
const wideBoth =
"html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {";
expect(block(wideBoth)).toContain('margin-inline-end: var(--m-safe-r-gap, 0px);');
const src = (file: string) => readFileSync(resolve(root, 'src', file), 'utf8');
const shell = src('mobile/screens/trip/MTripShell.tsx');
// The top row and the day chips stand beside it, a list tab ends before it on a wide window.
expect(src('mobile/screens/trip/MTripShellParts.tsx')).toContain("CHROME_ROW = 'm-corner-beside absolute end-4");
expect(shell.match(/\$\{CHROME_ROW\}/g)).toHaveLength(2);
expect(shell).toContain('<div className="m-corner-side relative h-full">');
expect(src('mobile/screens/trip/map/MMapArea.tsx')).toContain('m-corner-beside pointer-events-none absolute end-4');
// A list tab's first row and a docked sheet start below it.
expect(src('mobile/screens/trip/tabs/tabChrome.tsx')).toContain(
'pt-[max(calc(var(--m-safe-top,12px)+58px),var(--m-corner-clear,0px))]'
);
expect(src('mobile/components/MSheet.tsx')).toContain(
'top-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))]'
);
expect(src('mobile/components/MSectionNav.tsx')).toContain("'m-corner-flow px-4 ");
expect(src('mobile/screens/trip/MTripShellParts.tsx')).toContain("CHROME_ROW = 'm-safe-row absolute end-4");
expect(src('mobile/screens/trip/MTripShell.tsx')).toContain('<div className="m-safe-trail relative h-full">');
expect(src('mobile/screens/trip/map/MMapArea.tsx')).toContain('m-safe-row pointer-events-none absolute end-4');
expect(src('mobile/components/MSheet.tsx')).toContain('${base} m-safe-trail ');
// The capsule's own measurement is read in mobile.css alone.
expect(src('mobile/MobileShell.tsx')).not.toContain('corner.css');
for (const file of [
'mobile/components/MSectionNav.tsx',
'mobile/screens/trip/tabs/tabChrome.tsx',
'mobile/screens/journey/MJourneyDetail.tsx',
'mobile/screens/vacay/MVacay.tsx',
]) {
expect(src(file)).not.toMatch(/m-corner|trek-native-corner/);
}
});
});
@@ -600,7 +600,7 @@ describe('MRoadtripTab', () => {
const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
// 96px band plus a 44px bar plus its gap. A padding left at the old 102 would
// put the head card's first line behind the glass.
expect(scroller.className).toContain('pt-[max(calc(var(--m-safe-top,12px)+150px),var(--m-corner-clear,0px))]')
expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+150px)]')
})
it('FE-MOB-RTTAB-031: no stage, no search bar, and the chain keeps its old top', () => {
// Without a stage the corridor falls back to the trip's first routed day, which
@@ -610,7 +610,7 @@ describe('MRoadtripTab', () => {
expect(screen.queryByText('roadtrip.poi.title')).toBeNull()
const scroller = container.querySelector('[class*="overflow-y-auto"]') as HTMLElement
expect(scroller.className).toContain('pt-[max(calc(var(--m-safe-top,12px)+102px),var(--m-corner-clear,0px))]')
expect(scroller.className).toContain('pt-[calc(var(--m-safe-top,12px)+102px)]')
})
})
@@ -500,10 +500,43 @@ describe('MTransportSheet', () => {
expect(screen.queryByText('10-4C')).not.toBeInTheDocument()
})
it('FE-MOB-TRSH-035: without a leg the sheet still shows the booking as a whole', () => {
it('FE-MOB-TRSH-035: without a leg the sheet shows the booking as a whole, with the seat of each leg under its route', () => {
render(<MTransportSheet planner={makePlanner({ reservations: [TRAIN] })} shell={makeShell({ sheet: { id: 'transport', payload: { reservationId: 8 } } })} />)
expect(screen.getByText('10-4C')).toBeInTheDocument()
expect(screen.queryByText('4-5A')).not.toBeInTheDocument()
expect(screen.getByText('10-4C').nextElementSibling).toHaveTextContent('Seat Takayama → Nagoya')
expect(screen.getByText('4-5A').nextElementSibling).toHaveTextContent('Seat Nagoya → Kyoto')
})
})
// A flight with a stop saves a seat per leg; the sheet showed only the first leg's.
describe('the seats of a flight with a stop', () => {
const STOPOVER = {
...FLIGHT, id: 9, title: 'MXP to JFK',
metadata: JSON.stringify({
airline: 'Turkish Airlines', flight_number: 'TK 1874',
legs: [
{ from: 'MXP', to: 'IST', airline: 'Turkish Airlines', flight_number: 'TK 1874', dep_time: '11:00', arr_time: '15:10' },
{ from: 'IST', to: 'JFK', airline: 'Turkish Airlines', flight_number: 'TK 1', seat: '14C', dep_time: '17:05', arr_time: '20:40' },
],
}),
} as unknown as Reservation
const open = (legIndex?: number) => render(
<MTransportSheet planner={makePlanner({ reservations: [STOPOVER] })} shell={makeShell({ sheet: { id: 'transport', payload: { reservationId: 9, legIndex } } })} />,
)
it('FE-MOB-TRSH-045: the second leg shows its own seat', () => {
open(1)
expect(screen.getByText('14C').nextElementSibling).toHaveTextContent('Seat')
})
it('FE-MOB-TRSH-046: the first leg, booked without a seat, shows none', () => {
open(0)
expect(screen.queryByText('14C')).not.toBeInTheDocument()
expect(screen.queryByText('Seat')).not.toBeInTheDocument()
})
it('FE-MOB-TRSH-047: the whole booking names the seat booked on its second leg', () => {
open()
expect(screen.getByText('14C').nextElementSibling).toHaveTextContent('Seat IST → JFK')
})
})
@@ -0,0 +1,128 @@
import { Migration } from '@mikro-orm/migrations';
interface AuditRow {
action: string;
user_id: number | string | null;
resource: string | null;
details: string | null;
}
interface UserEmailRow {
id: number | string;
email: string;
}
interface AuditDetails {
email?: unknown;
targetUser?: unknown;
fields?: unknown;
}
/** One admin save of an account: the address it found, and whether it sent an email at all. */
interface AdminSave {
found: string | null;
sentEmail: boolean;
}
interface History {
/** The addresses the account was created or registered with; null once one of them is unreadable. */
baselines: string[] | null;
/** The admin saves since its creation, oldest first. */
saves: AdminSave[];
}
function readDetails(details: string | null): AuditDetails {
if (!details) return {};
try {
const value: unknown = JSON.parse(details);
return value && typeof value === 'object' ? (value as AuditDetails) : {};
} catch {
return {};
}
}
const normalize = (email: string) => email.trim().toLowerCase();
/**
* Marks an address an account set itself even when an admin saved the account
* afterwards.
*
* `Migration20200101042800_an_email_the_account_typed_in_itself` and
* `Migration20200101046480_an_address_changed_after_an_admin_made_the_account`
* set `email_self_asserted` for an account whose address moved away from the one
* it was registered or created with, unless an `admin.user_update` row names
* `email`. But the edit dialog sends the email on every save, so every admin save
* names it, a role change too, and one save of the account at any time kept the
* flag at 0, even long after the account had moved its own address.
*
* Each such row also holds the address the account had when the admin saved it
* (`targetUser`). So the history answers who set the current address: if every
* admin save already found it, it was set before the first save, and between the
* creation and that save only the account itself could change it. If the last
* save that found another address sent no email, the address moved after that
* save, again by the account itself. Either way the account is marked.
*
* When that last save did send an email, the admin may have typed the current
* address in, and the rows cannot tell: the admin's new address is not logged,
* and neither is a change the account made in its settings before 5.0.0. Such an
* account stays as it is, the same as every account at its registered address and
* every account with no creation row: marking it would refuse the first SSO
* sign-in of an address an admin vouched for. Since 5.0.0 a change in the
* settings sets the flag directly and an admin's new address clears it, so an
* account this can still mark is one whose address moved before that.
*
* A creation row starts the account's history anew, so the saves of an account
* that once held the same id do not count. An unreadable creation row or save
* leaves the account as it is. Only accounts still at 0 are touched, and nothing
* is ever cleared.
*/
export class Migration20200101046500_an_address_moved_before_an_admin_saved_the_account extends Migration {
override name = 'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account';
override async up(): Promise<void> {
const rows = (await this.execute(
`SELECT action, user_id, resource, details FROM audit_log
WHERE action IN ('user.register', 'admin.user_create', 'admin.user_update')
ORDER BY id`,
)) as AuditRow[];
const histories = new Map<string, History>();
for (const row of rows) {
const details = readDetails(row.details);
if (row.action === 'admin.user_update') {
const history = row.resource ? histories.get(row.resource) : undefined;
if (!history) continue;
const found = typeof details.targetUser === 'string' ? normalize(details.targetUser) : null;
const sentEmail = !Array.isArray(details.fields) || details.fields.includes('email');
history.saves.push({ found, sentEmail });
continue;
}
// A registration names the account in user_id, an admin's creation in resource.
const owner = row.action === 'user.register' ? row.user_id : row.resource;
if (owner === null) continue;
const id = String(owner);
const before = histories.get(id)?.baselines;
const baselines =
typeof details.email === 'string' && before !== null ? [...(before ?? []), normalize(details.email)] : null;
histories.set(id, { baselines, saves: [] });
}
if (histories.size === 0) return;
const users = (await this.execute(
`SELECT id, email FROM users WHERE COALESCE(is_guest, 0) = 0 AND email_self_asserted = 0`,
)) as UserEmailRow[];
// Queued, run after up() returns; the id comes from the database and is
// checked to be an integer, nothing a user typed.
for (const user of users) {
const history = histories.get(String(user.id));
if (!history?.baselines) continue;
const current = normalize(user.email);
if (history.baselines.includes(current)) continue;
const lastOther = [...history.saves].reverse().find((save) => save.found !== current);
if (lastOther && (lastOther.found === null || lastOther.sentEmail)) continue;
const rowId = Number(user.id);
if (!Number.isInteger(rowId)) continue;
this.addSql(`UPDATE users SET email_self_asserted = 1 WHERE id = ${rowId}`);
}
}
}
@@ -1,6 +1,7 @@
import { decodeSessionClaims } from '../auth-core/jwt-verify';
import { setAuthCookie } from '../common/cookie';
import { SessionsService, sessionClientFrom } from '../sessions/sessions.service';
import { AuthService } from './auth.service';
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import type { Request, Response } from 'express';
@@ -15,19 +16,23 @@ import type { Observable } from 'rxjs';
* historical default duration).
*
* Cheap by construction, one write per half-life at most:
* - `req.user` is only set after a guard ran verifyJwtAndLoadUser on this exact
* request, which already proved the token's `pv` matches the DB and its
* session is active, so the user id, pv and session id can be copied from
* the decoded (not re-verified) token.
* - Only a token past half its life is looked at again: the decoded claims
* answer that, and every younger token costs nothing more.
* - Such a token is verified once more, through the same check the guards use
* (signature, expiry, `pv` against the DB, an active session), and must name
* the user this request runs as. `req.user` alone proves nothing about the
* cookie: a route with its own guard chain lets that chain authenticate, and
* ApiTokenGuard does so with a public API key while the cookie beside it was
* never checked. Renewing that cookie re-signed whatever it claimed.
* - A request a public API key authenticated renews nothing, even beside a
* valid cookie: the key is that request's credential, and a key must never
* yield a browser session.
* - A tracked token is re-signed under the same session id and the session's
* expiry moves with it; a token from before sessions were tracked comes back
* as a tracked session whose id is derived from that token, so the parallel
* requests of one page load renew it into one session, not several. If the
* session ended in between, nothing is renewed.
* - The cookie is only renewed when it is the verified credential: extractToken
* prefers the cookie over the Authorization header, so cookie-present +
* req.user set means the guard verified the cookie. Bearer-only callers
* (MCP, API clients) are never renewed.
* - Bearer-only callers (MCP, API clients) carry no cookie and are never renewed.
*
* The cookie is written eagerly, before the handler runs: renewal doesn't
* depend on the handler's outcome, and this sidesteps @Res()/streaming routes
@@ -38,7 +43,10 @@ import type { Observable } from 'rxjs';
*/
@Injectable()
export class SessionRenewalInterceptor implements NestInterceptor {
constructor(private readonly sessions: SessionsService) {}
constructor(
private readonly sessions: SessionsService,
private readonly auth: AuthService,
) {}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
if (context.getType() === 'http') {
@@ -51,7 +59,7 @@ export class SessionRenewalInterceptor implements NestInterceptor {
private async maybeRenew(req: Request & { user?: { id: number } }, res: Response): Promise<void> {
const cookieToken: string | undefined = (req as { cookies?: Record<string, string> }).cookies?.trek_session;
if (!req.user || !cookieToken || res.headersSent) return;
if (!req.user || req.apiToken || !cookieToken || res.headersSent) return;
const claims = decodeSessionClaims(cookieToken);
if (!claims || claims.purpose || claims.id !== req.user.id) return;
@@ -60,6 +68,9 @@ export class SessionRenewalInterceptor implements NestInterceptor {
const halfLife = claims.iat + (claims.exp - claims.iat) / 2;
if (Date.now() / 1000 < halfLife) return;
const owner = await this.auth.verifyJwtToken(cookieToken);
if (!owner || owner.id !== req.user.id) return;
const token = await this.sessions.renew(
{ id: req.user.id, pv: claims.pv, remember: claims.remember, jti: claims.jti, token: cookieToken },
sessionClientFrom(req),
@@ -146,6 +146,23 @@ const legsSchema = z.array(z.strictObject(transportLegInputSchema.shape)).option
type MetaRecord = Record<string, unknown>;
/**
* The stored metadata a legs-only update starts from, without the flat keys
* that only mirrored the stored first leg's own detail. Those are set again
* from the new legs; kept, a first leg's seat taken away stayed in the flat
* seat, and the planner, which reads that as the first leg's, brought it back.
* A flat value the first leg never had (an older booking) is the booking's own
* and stays.
*/
function withoutLegMirrors(stored: MetaRecord, type: string): MetaRecord {
const mirrored = type === 'flight' ? ['airline', 'flight_number', 'seat'] : ['train_number', 'platform', 'seat'];
const leg: unknown = Array.isArray(stored.legs) ? stored.legs[0] : null;
const firstLeg = leg && typeof leg === 'object' ? (leg as MetaRecord) : null;
return Object.fromEntries(
Object.entries(stored).filter(([key, value]) => !(firstLeg && mirrored.includes(key) && firstLeg[key] === value)),
);
}
/**
* `reservations.metadata` as stored: a JSON string, or (from an old
* double-encoding bug the client readers still heal around) a JSON string of a
@@ -827,8 +844,8 @@ export class ReservationsMcp {
})),
// metadata keeps replacing wholesale when it is sent; a legs-only update
// must not drop departure_airport / airtrail_ids / transit, so it merges
// into what is stored instead.
baseMetadata: metadata !== undefined ? { ...metadata } : { ...stored },
// into what is stored instead, less the first leg's mirrored detail.
baseMetadata: metadata !== undefined ? { ...metadata } : withoutLegMirrors(stored, resolvedType),
previousLegs: Array.isArray(stored.legs) ? stored.legs as unknown[] : [],
startDayId: start_day_id,
endDayId: end_day_id,
@@ -193,6 +193,23 @@ function text(meta: Record<string, unknown>, key: string, max = 64): string | un
return typeof value === 'string' || typeof value === 'number' ? clean(value, max) : undefined;
}
/**
* The seat a pass shows. One pass covers a whole flight or train with a stop,
* so it lists the seat of every leg that has one (the first leg falling back
* to the flat seat, which mirrors it); before, a seat booked only on a later
* leg was missing and the first leg's stood for the whole route.
*/
function seatsOf(meta: Record<string, unknown>): string | undefined {
const legs = Array.isArray(meta.legs) && meta.legs.length > 1 ? (meta.legs as unknown[]) : null;
if (!legs) return text(meta, 'seat', 16);
const seats = legs.flatMap((leg, i) => {
const own = leg && typeof leg === 'object' ? (leg as Record<string, unknown>).seat : undefined;
const seat = typeof own === 'string' && own.trim() ? own : i === 0 ? meta.seat : undefined;
return typeof seat === 'string' && seat.trim() ? [seat.trim()] : [];
});
return seats.length ? clean(seats.join(' / '), 16) : 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')
@@ -258,7 +275,7 @@ export function buildWalletPassRequest(src: WalletPassSource, words: WalletWords
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.seat, seatsOf(meta));
add(words.platform, text(meta, 'platform', 16));
if (endLocal) add(words.arrival, when(endLocal.date, endLocal.time));
} else if (kind === 'hotel') {
+4 -1
View File
@@ -12,6 +12,7 @@ import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { AuthModule } from '../../src/nest/auth/auth.module';
import { AuthService } from '../../src/nest/auth/auth.service';
import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.interceptor';
import { encrypt_api_key } from '../../src/nest/common/crypto/apiKeyCrypto';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
@@ -86,7 +87,9 @@ describe('Auth e2e (real auth guard + real service + real cookie service + temp
nest.useGlobalPipes(new ZodValidationPipe());
// Mirror the production APP_INTERCEPTOR: sliding session renewal (#1927).
// Inert for the harness's exp-less tokens and freshly issued logins.
nest.useGlobalInterceptors(new SessionRenewalInterceptor(moduleRef.get(SessionsService)));
nest.useGlobalInterceptors(
new SessionRenewalInterceptor(moduleRef.get(SessionsService), moduleRef.get(AuthService)),
);
await nest.init();
return nest;
}
+40 -2
View File
@@ -15,16 +15,19 @@ import { db } from '../../src/db/database';
import { UserSessions } from '../../src/db/entities/UserSessions.entity';
import { Users } from '../../src/db/entities/Users.entity';
import { AuthModule } from '../../src/nest/auth/auth.module';
import { AuthService } from '../../src/nest/auth/auth.service';
import { SessionRenewalInterceptor } from '../../src/nest/auth/session-renewal.interceptor';
import { encryptMfaSecret } from '../../src/nest/common/crypto/mfaCrypto';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { withRequestContext } from '../../src/nest/database/request-context';
import { MailerService } from '../../src/nest/notifications/mailer/mailer.service';
import { PublicApiModule } from '../../src/nest/public-api/public-api.module';
import { SessionPurgeJob } from '../../src/nest/sessions/session-purge.job';
import { SessionsService } from '../../src/nest/sessions/sessions.service';
import { createUser } from '../helpers/factories';
import { insertRow, updateRows } from '../helpers/factories/rows';
import { makeMcpToken } from '../helpers/factories/tokens';
import { sessionRows } from '../helpers/sessions';
import { resetRateLimits } from '../helpers/test-db';
import { createTestMikroOrmModule } from '../helpers/test-orm';
@@ -71,7 +74,14 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
async function build() {
moduleRef = await Test.createTestingModule({
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), AuthModule],
// PublicApiModule brings the one guard chain that authenticates by something
// other than the session cookie, which the renewal must not mistake for it.
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
AuthModule,
PublicApiModule,
],
})
.overrideProvider(MailerService)
.useValue({ sendPasswordResetEmail })
@@ -80,7 +90,9 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalInterceptors(new SessionRenewalInterceptor(moduleRef.get(SessionsService)));
nest.useGlobalInterceptors(
new SessionRenewalInterceptor(moduleRef.get(SessionsService), moduleRef.get(AuthService)),
);
await nest.init();
return nest;
}
@@ -296,6 +308,32 @@ describe('Sessions e2e (sign-in sessions that can be ended)', () => {
]);
}, 10000);
it('a public API key beside a session cookie never yields a session, whatever the cookie claims', async () => {
const { user } = freshUser('sess-apikey');
const key = 'trek_' + '7'.repeat(48);
await makeMcpToken(moduleRef.get(MikroORM), user.id, {
rawToken: key,
token_prefix: key.slice(0, 13),
kind: 'api',
});
const iat = Math.floor(Date.now() / 1000) - 60000;
// Past half its life, naming the key's owner and no session: one signed with a
// secret that is not the server's, and a real one.
const forged = `trek_session=${jwt.sign({ id: user.id, pv: 0, iat }, 'not-the-server-secret', { expiresIn: 86400, algorithm: 'HS256' })}`;
const genuine = sessionCookie(user.id, 0, { lifetime: 86400, consumed: 60000 });
const withKey = (cookie: string) =>
request(server).get('/api/v1/trips').set('Authorization', `Bearer ${key}`).set('Cookie', cookie);
for (const res of [await withKey(forged), await withKey(genuine)]) {
expect(res.status).toBe(200);
const set = (res.headers['set-cookie'] ?? []) as unknown as string[];
expect(set.some((c) => c.startsWith('trek_session='))).toBe(false);
}
expect(await sessionRows(db as never, user.id)).toEqual([]);
// The forged cookie opens nothing on its own either.
expect((await me(forged)).status).toBe(401);
}, 10000);
it("on a demo instance, visitors of the shared demo account neither see nor end each other's sessions", async () => {
createUser(db as never, { username: 'demo', email: 'demo@trek.app' });
vi.stubEnv('DEMO_MODE', 'true');
@@ -7,9 +7,15 @@
* `Migration20200101046480_an_address_changed_after_an_admin_made_the_account`
* applies the same rule to an account an admin created, whose baseline is the
* address in the `admin.user_create` row instead of a `user.register` one.
*
* `Migration20200101046500_an_address_moved_before_an_admin_saved_the_account`
* reads the address each admin save found, so a save after the account moved
* its own address no longer keeps it at 0, while a save that may have typed the
* current address in still does.
*/
import { Migration20200101042800_an_email_the_account_typed_in_itself } from '../../../src/db/migrations/Migration20200101042800_an_email_the_account_typed_in_itself';
import { Migration20200101046480_an_address_changed_after_an_admin_made_the_account } from '../../../src/db/migrations/Migration20200101046480_an_address_changed_after_an_admin_made_the_account';
import { Migration20200101046500_an_address_moved_before_an_admin_saved_the_account } from '../../../src/db/migrations/Migration20200101046500_an_address_moved_before_an_admin_saved_the_account';
import {
createMigrationOrm,
migrateTo,
@@ -24,6 +30,7 @@ import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101042800_an_email_the_account_typed_in_itself';
const ADMIN_MADE = 'Migration20200101046480_an_address_changed_after_an_admin_made_the_account';
const SAVED_AFTER = 'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account';
async function ormBeforeTarget(target = TARGET): Promise<MikroORM> {
const orm = await createMigrationOrm();
@@ -193,3 +200,123 @@ describe('admin-made account email migration', () => {
}
}, 30000);
});
async function seedSaves(orm: MikroORM): Promise<void> {
// 9 is the admin; every save below is the edit dialog's unless said otherwise,
// which sends the email each time. 1 was made by the admin, moved its address
// itself, and the admin changed its role afterwards; 2 the same but the save
// came first, so the admin may have typed the new address in; 3 got its new
// address from the admin; 4 registered, moved, and the admin saved it later;
// 5 registered and an API save sent no email before the account moved; 6 has a
// save whose details are broken; 7 was made under an id an earlier account
// held, whose save does not count; 8 moved, was saved, then the admin gave it
// another address; 10 moved with no save at all; 11 is still at the address it
// was made with; 12 is already marked; 13 has no creation row; 14 is a guest.
await rawExec(
orm,
`INSERT INTO users (id, username, email, password_hash, email_self_asserted, is_guest) VALUES
(1, 'later', 'colleague-1@test', 'x', 0, 0),
(2, 'earlier', 'colleague-2@test', 'x', 0, 0),
(3, 'given', 'given-by-admin@test', 'x', 0, 0),
(4, 'registered', 'colleague-4@test', 'x', 0, 0),
(5, 'api', 'colleague-5@test', 'x', 0, 0),
(6, 'broken', 'colleague-6@test', 'x', 0, 0),
(7, 'reused', 'colleague-7@test', 'x', 0, 0),
(8, 'regiven', 'regiven-by-admin@test', 'x', 0, 0),
(9, 'admin', 'admin@test', 'x', 0, 0),
(10, 'unsaved', 'colleague-10@test', 'x', 0, 0),
(11, 'kept', 'Kept@Test', 'x', 0, 0),
(12, 'marked', 'marked-now@test', 'x', 1, 0),
(13, 'seeded', 'seeded-now@test', 'x', 0, 0),
(14, 'guest', 'guest-now@test', '', 0, 1)`,
);
await rawExec(
orm,
`INSERT INTO audit_log (user_id, action, resource, details) VALUES
(9, 'admin.user_create', '1', '{"username":"later","email":"later@test","role":"user"}'),
(9, 'admin.user_update', '1', '{"targetUser":"colleague-1@test","fields":["username","email","role"]}'),
(9, 'admin.user_create', '2', '{"username":"earlier","email":"earlier@test","role":"user"}'),
(9, 'admin.user_update', '2', '{"targetUser":"earlier@test","fields":["username","email","role"]}'),
(9, 'admin.user_create', '3', '{"username":"given","email":"given@test","role":"user"}'),
(9, 'admin.user_update', '3', '{"targetUser":"given@test","fields":["username","email","role"]}'),
(4, 'user.register', NULL, '{"username":"registered","email":"registered@test","role":"user"}'),
(9, 'admin.user_update', '4', '{"targetUser":"Colleague-4@Test","fields":["username","email","role"]}'),
(5, 'user.register', NULL, '{"username":"api","email":"api@test","role":"user"}'),
(9, 'admin.user_update', '5', '{"targetUser":"api@test","fields":["role"]}'),
(9, 'admin.user_create', '6', '{"username":"broken","email":"broken@test","role":"user"}'),
(9, 'admin.user_update', '6', 'not json'),
(9, 'admin.user_create', '7', '{"username":"gone","email":"gone@test","role":"user"}'),
(9, 'admin.user_update', '7', '{"targetUser":"gone@test","fields":["username","email","role"]}'),
(7, 'user.register', NULL, '{"username":"reused","email":"reused@test","role":"user"}'),
(9, 'admin.user_create', '8', '{"username":"regiven","email":"regiven@test","role":"user"}'),
(9, 'admin.user_update', '8', '{"targetUser":"colleague-8@test","fields":["username","email","role"]}'),
(9, 'admin.user_update', '8', '{"targetUser":"colleague-8@test","fields":["username","email","role"]}'),
(9, 'admin.user_create', '10', '{"username":"unsaved","email":"unsaved@test","role":"user"}'),
(9, 'admin.user_create', '11', '{"username":"kept","email":"kept@test","role":"user"}'),
(9, 'admin.user_update', '11', '{"targetUser":"kept@test","fields":["username","email","role"]}'),
(12, 'user.register', NULL, '{"username":"marked","email":"marked@test","role":"user"}'),
(9, 'admin.user_update', '13', '{"targetUser":"seeded@test","fields":["role"]}'),
(9, 'admin.user_create', '14', '{"username":"guest","email":"guest@test","role":"user"}')`,
);
}
const SAVED_AFTER_EXPECTED = [
{ id: 1, email_self_asserted: 1 },
{ id: 2, email_self_asserted: 0 },
{ id: 3, email_self_asserted: 0 },
{ id: 4, email_self_asserted: 1 },
{ id: 5, email_self_asserted: 1 },
{ id: 6, email_self_asserted: 0 },
{ id: 7, email_self_asserted: 1 },
{ id: 8, email_self_asserted: 0 },
{ id: 9, email_self_asserted: 0 },
{ id: 10, email_self_asserted: 1 },
{ id: 11, email_self_asserted: 0 },
{ id: 12, email_self_asserted: 1 },
{ id: 13, email_self_asserted: 0 },
{ id: 14, email_self_asserted: 0 },
];
describe('admin saves after the account moved its address', () => {
it('EMAILSELF-MIG-006: an address no admin save can have set is marked, whatever the save sent', async () => {
const orm = await ormBeforeTarget(SAVED_AFTER);
try {
await seedSaves(orm);
await migrateTo(orm, SAVED_AFTER);
expect(await flags(orm)).toEqual(SAVED_AFTER_EXPECTED);
} finally {
await orm.close(true);
}
}, 30000);
it('EMAILSELF-MIG-007: running it again changes nothing', async () => {
const orm = await ormBeforeTarget(SAVED_AFTER);
try {
await seedSaves(orm);
await migrateTo(orm, SAVED_AFTER);
await runMigrationDirect(orm, Migration20200101046500_an_address_moved_before_an_admin_saved_the_account);
expect(await flags(orm)).toEqual(SAVED_AFTER_EXPECTED);
} finally {
await orm.close(true);
}
}, 30000);
it('EMAILSELF-MIG-008: an audit log without a creation row reads no account', async () => {
const orm = await ormBeforeTarget(SAVED_AFTER);
try {
await rawExec(
orm,
`INSERT INTO users (id, username, email, password_hash) VALUES (1, 'solo', 'solo-now@test', 'x')`,
);
await rawExec(
orm,
`INSERT INTO audit_log (user_id, action, resource, details) VALUES
(1, 'admin.user_update', '1', '{"targetUser":"solo-now@test","fields":["role"]}')`,
);
await migrateTo(orm, SAVED_AFTER);
expect(await flags(orm)).toEqual([{ id: 1, email_self_asserted: 0 }]);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -116,6 +116,7 @@ const UNNUMBERED = [
'Migration20200101046460_an_upgraded_install_gets_the_columns_its_history_skipped',
'Migration20200101046480_an_address_changed_after_an_admin_made_the_account',
'Migration20200101046490_a_trip_can_switch_its_own_addons',
'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -1712,3 +1712,66 @@ describe('Transport tools: the full type list', () => {
});
});
});
// The flat seat mirrors the first leg's; the planner reads it as the first leg's
// seat when that leg has none, so a legs-only update must not leave it stale.
describe('update_transport: the flat keys of a legs-only update', () => {
const create = async (h: McpHarness, tripId: number) =>
parseToolResult(
await h.client.callTool({
name: 'create_transport',
arguments: {
tripId,
type: 'flight',
title: 'AMS to FCO',
endpoints: stopoverEndpoints,
legs: [
{ from: 'AMS', to: 'CDG', airline: 'KLM', seat: '3A' },
{ from: 'CDG', to: 'FCO', airline: 'Air France', seat: '14C' },
],
},
}),
) as { reservation: { id: number } };
const updateLegs = (h: McpHarness, tripId: number, reservationId: number, legs: object[]) =>
h.client.callTool({ name: 'update_transport', arguments: { tripId, reservationId, legs } });
it("takes the first leg's seat away from the flat seat too, and follows a new one", async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
await withHarness(user.id, async (h) => {
const data = await create(h, trip.id);
expect((await storedMetadata(data.reservation.id)).seat).toBe('3A');
await updateLegs(h, trip.id, data.reservation.id, [
{ from: 'AMS', to: 'CDG', airline: 'KLM' },
{ from: 'CDG', to: 'FCO', airline: 'Air France', seat: '14C' },
]);
const cleared = await storedMetadata(data.reservation.id);
expect(cleared.seat).toBeUndefined();
expect(cleared.airline).toBe('KLM');
await updateLegs(h, trip.id, data.reservation.id, [
{ from: 'AMS', to: 'CDG', airline: 'Transavia', seat: '5C' },
{ from: 'CDG', to: 'FCO', airline: 'Air France', seat: '14C' },
]);
const changed = await storedMetadata(data.reservation.id);
expect([changed.seat, changed.airline]).toEqual(['5C', 'Transavia']);
});
});
it('keeps a flat seat the first leg never had, as an older booking stores it', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
await withHarness(user.id, async (h) => {
const data = await create(h, trip.id);
const legs = [
{ from: 'AMS', to: 'CDG' },
{ from: 'CDG', to: 'FCO' },
];
await setMetadata(JSON.stringify({ seat: '22F', legs }), data.reservation.id);
await updateLegs(h, trip.id, data.reservation.id, legs);
expect((await storedMetadata(data.reservation.id)).seat).toBe('22F');
});
});
});
@@ -4,8 +4,10 @@
* lifetime. Covers the renew path (fresh token + cookie semantics per the
* `remember` claim) and every skip condition: young token, bearer-only request,
* unauthenticated request, purpose token, id mismatch, malformed claims,
* headers already sent, non-http context.
* headers already sent, non-http context, a cookie the session check refuses
* and a request a public API key authenticated.
*/
import type { AuthService } from '../../../src/nest/auth/auth.service';
import { SessionRenewalInterceptor } from '../../../src/nest/auth/session-renewal.interceptor';
import type { SessionsService } from '../../../src/nest/sessions/sessions.service';
import type { CallHandler, ExecutionContext } from '@nestjs/common';
@@ -30,6 +32,7 @@ function makeRes(headersSent = false) {
type ReqShape = {
cookies?: Record<string, string>;
user?: { id: number };
apiToken?: { scopes: string[] | null };
headers?: Record<string, string>;
secure?: boolean;
};
@@ -46,10 +49,18 @@ function handler(): CallHandler & { handle: ReturnType<typeof vi.fn> } {
return { handle: vi.fn(() => of('ok')) };
}
function makeInterceptor(renewed: string | null = 'renewed.jwt') {
/**
* `verified` is what the session check answers for the cookie: the user its
* token names when it is a live session, null when it is not one.
*/
function makeInterceptor(renewed: string | null = 'renewed.jwt', verified: { id: number } | null = { id: 1 }) {
const renew = vi.fn().mockResolvedValue(renewed);
const interceptor = new SessionRenewalInterceptor({ renew } as unknown as SessionsService);
return { interceptor, renew };
const verifyJwtToken = vi.fn().mockResolvedValue(verified);
const interceptor = new SessionRenewalInterceptor(
{ renew } as unknown as SessionsService,
{ verifyJwtToken } as unknown as AuthService,
);
return { interceptor, renew, verifyJwtToken };
}
async function run(
@@ -65,12 +76,13 @@ async function run(
}
describe('SessionRenewalInterceptor', () => {
it('SES-RENEW-001: does not renew a token under half of its lifetime', async () => {
const { interceptor, renew } = makeInterceptor();
it('SES-RENEW-001: does not renew a token under half of its lifetime, nor look it up', async () => {
const { interceptor, renew, verifyJwtToken } = makeInterceptor();
const res = makeRes();
const t = token({ id: 1, pv: 0 }, 86400, 1000); // ~1% consumed
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 } }, res);
expect(renew).not.toHaveBeenCalled();
expect(verifyJwtToken).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
@@ -226,4 +238,37 @@ describe('SessionRenewalInterceptor', () => {
expect(renew).toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
it('SES-RENEW-014: renews no cookie the session check refuses, whoever req.user is', async () => {
// What a route with its own guard chain can see: ApiTokenGuard set req.user from
// a key, and the cookie beside it is unsigned, past half its life and names the
// key's owner without a session id. Decoding it alone would re-sign it.
const { interceptor, renew, verifyJwtToken } = makeInterceptor('renewed.jwt', null);
const res = makeRes();
const iat = Math.floor(Date.now() / 1000) - 60000;
const forged = jwt.sign({ id: 1, pv: 0, iat }, 'not-the-server-secret', { expiresIn: 86400, algorithm: 'HS256' });
await run(interceptor, { cookies: { trek_session: forged }, user: { id: 1 } }, res);
expect(verifyJwtToken).toHaveBeenCalledWith(forged);
expect(renew).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
it('SES-RENEW-015: renews no cookie whose session belongs to another user than the request', async () => {
const { interceptor, renew } = makeInterceptor('renewed.jwt', { id: 2 });
const res = makeRes();
const t = token({ id: 1, pv: 0 }, 86400, 60000);
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 } }, res);
expect(renew).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
it('SES-RENEW-016: a request a public API key authenticated renews nothing, even beside a valid cookie', async () => {
const { interceptor, renew, verifyJwtToken } = makeInterceptor();
const res = makeRes();
const t = token({ id: 1, pv: 0 }, 86400, 60000);
await run(interceptor, { cookies: { trek_session: t }, user: { id: 1 }, apiToken: { scopes: null } }, res);
expect(verifyJwtToken).not.toHaveBeenCalled();
expect(renew).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
});
@@ -159,6 +159,61 @@ describe('wallet pass builder', () => {
expect(request?.details?.[1]?.value).toBe('Lufthansa LH716');
});
const ENDS = [
{
role: 'from',
name: 'Milan',
code: 'MXP',
lat: 45.63,
lng: 8.72,
timezone: 'Europe/Rome',
local_date: '2027-04-02',
local_time: '11:00',
},
{
role: 'to',
name: 'New York',
code: 'JFK',
lat: 40.64,
lng: -73.78,
timezone: 'America/New_York',
local_date: '2027-04-02',
local_time: '20:40',
},
] as WalletPassSource['endpoints'];
it('WALLET-B-011: a flight with a stop shows the seat of each leg, also one booked only on the second', () => {
const seat = (metadata: Record<string, unknown>) =>
buildWalletPassRequest(
source({ type: 'flight', reservation_time: '2027-04-02T11:00', metadata }, { endpoints: ENDS }),
WORDS,
)?.details?.find((d) => d.label === 'Seat')?.value;
const legs = [
{ from: 'MXP', to: 'IST' },
{ from: 'IST', to: 'JFK', seat: '14C' },
];
expect(seat({ legs })).toBe('14C');
expect(seat({ seat: '3A', legs: [{ from: 'MXP', to: 'IST', seat: '3A' }, legs[1]] })).toBe('3A / 14C');
// An older booking keeps its flat seat on the first leg.
expect(
seat({
seat: '3A',
legs: [
{ from: 'MXP', to: 'IST' },
{ from: 'IST', to: 'JFK' },
],
}),
).toBe('3A');
expect(
seat({
legs: [
{ from: 'MXP', to: 'IST' },
{ from: 'IST', to: 'JFK' },
],
}),
).toBeUndefined();
});
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');