Compare commits

..

5 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
35 changed files with 556 additions and 259 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))
-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} />
@@ -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}
@@ -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]">
+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)]')
})
})
@@ -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),
+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.
@@ -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();
});
});