Compare commits

...

35 Commits

Author SHA1 Message Date
Maurice 39d2196a14 feat(postgres): support PostgreSQL 19
PostgreSQL 19 was released on 19.11.2026, and TREK refused it at boot as
newer than the 14 to 18 it supported (discussion #3214). It now supports 14
to 19.

The image installs the version 19 client tools from PGDG's main component,
since the per-major component can trail a new release; a client handles
every server up to its own major, so pg_dump, pg_restore and psql 19 back up
and restore every supported server. The tools are looked for in the 19
directory first. Installs that pointed TREK_DB_PG_BIN_DIR at the old
/usr/lib/postgresql/18/bin keep working: the image keeps that path as a link
to the 19 tools. CI runs the Postgres lane on 14 and 19 instead of 14 and
18, so the job count stays the same, and the Docker job boots on 19. The
list of server functions and roles that reach the host was checked against
the release notes; PostgreSQL 19 adds none. The compose example stays on 18,
because an existing database stays on the major it was created with.
2026-11-26 23:48:52 +01:00
Maurice a9fd443b63 feat(db): present a Postgres client certificate from sslcert and sslkey in TREK_DB_URL
A Postgres server that authenticates clients by certificate could not be
used: TREK read only sslmode and sslrootcert from TREK_DB_URL, so neither
the connection pool nor pg_dump, pg_restore and psql ever offered a client
certificate (discussion #3215).

TREK_DB_URL now also takes libpq's sslcert and sslkey. Both must be given
together and only with a verifying sslmode, and each file must be readable,
or the boot refuses with the same kind of message as for sslrootcert. The
pool gets them as its TLS cert and key, the tools as PGSSLCERT and
PGSSLKEY. The Postgres wiki page shows the URL, how to mount the files with
Compose or the chart's extraVolumes, and libpq's rule for the key file's
permissions, which the backup tools enforce.
2026-11-26 23:35:18 +01:00
Maurice b8dffdbb13 fix(files): serve the stored offline copy when a live download stalls
Opening a document that was stored for offline use fetched it from the
server first and only fell back to the stored copy when the request
rejected. On a weak or stalled connection the request never rejects, so a
boarding pass already on the phone could spin indefinitely.

With a stored copy, the live download now gets five seconds, request and
body together; after that the stored copy is served and the download is
aborted. A connection that breaks while the body arrives serves the copy as
well. An HTTP error that comes back in time still surfaces over the copy,
and without a stored copy the download waits as long as it always did. The
test file is now formatted and leaves the format baseline.
2026-11-26 23:35:18 +01:00
Maurice 3b42ffa67b feat(helm): render extra Kubernetes objects from an extraObjects list
The chart had no way to ship objects of the operator's own next to TREK, so
a backup CronJob, a ConfigMap for it or any other helper had to live in a
second release or be applied by hand (discussion #3194). extraObjects takes
a list, empty by default so nothing renders, and renders each item through
tpl: a map as YAML, a string as written, so names such as
{{ .Release.Name }} resolve in both forms.

The values comment, the chart README and the Helm wiki page say that braces
are evaluated in both forms, that a backup job must mount the data volume
read only, and that it should copy TREK's own backup archives rather than
the live travel.db. Those archives carry the encryption key unless
ENCRYPTION_KEY comes from the environment, so their destination needs the
same protection as the volume. CI renders a variant with a CronJob in the
map form and a ConfigMap in the string form, checks it with kubeconform
-strict, and fails when a {{ is left unrendered.
2026-11-26 23:35:18 +01:00
Maurice 2ea1c99e31 ci(native): publish the Play-signed Android APK to liketrek/trek-android for installs outside Google Play
People who install apps from GitHub (Obtainium and the like) asked for the
Android app outside Google Play. After the Play upload, the release job now
fetches the universal APK Google Play builds of that same bundle, signed
with the Play app signing key, and publishes it with a checksum to
liketrek/trek-android: one release per app version, a newer build of the
same version replacing its APK. A phone can move between the Play install
and this APK without uninstalling, and Play Billing and push work in it
wherever Google Play services do.

It runs only inside the app builds that already happen, so a server release
without app changes publishes nothing. A build is held back while the app
needs a newer native API than the latest server release answers, so no APK
asks for a server that is not out yet. The APKs live in their own repository
so app releases never show up in the server's release list or update check.
2026-11-26 23:12:27 +01:00
Maurice d383d3527b fix(oauth): bind an authorization code to the session that consented, not to the password version
Reading the password version from the oauth domain meant injecting the
users repository, which the auth domain owns. The sessions domain answers
the same question and more: a password reset or change ends every session
of the user, and a sign-out ends the one that consented. The code now
carries that session's id and both token endpoints issue tokens for it
only while the session is active, checked in the transaction that writes
them. A token from before sessions were tracked has no session to check
and passes, as it does everywhere until it expires. A refused code is
audited as session_ended.
2026-11-26 22:46:15 +01:00
Maurice 05843c8e5b test(oauth): give the pending-code fixture its password version and format the controller test 2026-11-26 22:32:44 +01:00
Maurice 19270adef8 test(oauth): read the granted code without non-null assertions 2026-11-26 22:26:58 +01:00
Maurice f9ab280b7e fix(oauth): an authorization code mints tokens only while the password it was granted under holds
The consent page mints a two-minute authorization code from the cookie
session. A password reset or change revokes the user's OAuth tokens but
left such a pending code alone, so a code granted before the reset still
redeemed afterwards into a fresh token pair at either token endpoint.

The code now carries the password version of the session that consented,
and both token endpoints issue tokens for it only while that version is
still the account's, checked in the transaction that writes the tokens.
A refused code answers invalid_grant as any other and is audited as
password_changed.
2026-11-26 22:21:46 +01:00
Maurice c88d3abc5e fix(auth): a native app hand-off code redeems only while the session that minted it stands
The browser side of the native sign-in mints a one-time code from its
cookie session, and the app redeems it within a minute for a session of
its own. The code was bound to the account alone, so one minted before a
password reset, a sign-out or a revoked session still redeemed afterwards
into a fresh session, carrying access across the point where the account
took it back.

The code now carries the session it came from: its password version and,
for a tracked session, its id. Redeeming it mints a session only while the
password is unchanged and that session is still active, checked in the
same transaction that mints the new one.
2026-11-26 22:14:12 +01:00
Maurice 10d95a39ac fix(map): open a day the routing relay could not answer drawn, without waiting for it again
On an instance that routes its days with Valhalla (the TREK services by
default), a day the relay could not answer in time was drawn by OSRM and
kept only under the OSRM key. The next visit missed the Valhalla key, asked
the relay again and waited out its deadline, up to twelve seconds a day,
before the kept road showed, so every reload showed straight lines first.

OSRM's answer now stands in for such a day for an hour under a key of its
own, on the device only. Reopening the trip draws it at once; after the
hour the relay is asked again and its answer becomes the day's. Days that
avoid something keep asking Valhalla, since the stand-in drives the road
they mean to leave out.

Closes #3228
2026-11-26 22:09:59 +01:00
Maurice 7d802081ce test(assistant): replay the changed requests side by side in ANTH-010 2026-11-26 20:04:40 +01:00
Maurice 7586126797 fix(assistant): send Anthropic's thinking back only where the conversation before it is unchanged
Follow-up messages failed with HTTP 400 on Anthropic once a thread held an
answer that thought: the API binds each thinking block to everything the
request sends before it and refuses the request when any of that changed.
It changes in normal use: a tool group loaded later in the turn, an earlier
tool answer cut short once a new question follows, a held change applied
since, a trip card that moved on.

Each recorded step now keeps a fingerprint of what its request sent before
it (model, system blocks, tools, history). On replay its thinking blocks go
back only while that fingerprint still matches; otherwise the step goes back
without them, which the API accepts. Records written before this change
carry no fingerprint and go back without their thinking.

A refusal from Anthropic is now logged with the path its message names
(such as messages.1.content.0), without the rest of the message.

Closes #3094
2026-11-26 20:00:00 +01:00
Maurice 9fa2bef101 test(journey): keep the journey page suite's journal and handlers in its helper
The suite carried its sample journal and the journal's default handlers inline, and waiting for the reload in FE-PAGE-JOURNEYDETAIL-153 took it past its size limit. Both move to tests/helpers/journeyDetail.ts beside seedJourneyOwner; the file is 142 lines shorter and its size baseline follows.
2026-11-26 14:21:04 +01:00
Maurice ed1bba9371 test(client): finish moving the tests to msw 3
Two more window.location stand-ins sat on http://localhost while the
page runs on http://localhost:3000; they now use locationAt like the
rest, which brings back the plugin settings answer FE-COMP-
PLUGINSETTINGS-020 waits for. FE-PAGE-JOURNEYDETAIL-153 ended while the
journal reload it set off was still out, which timed out after the
test; it now waits for that read. The reload mocks in
versionHandover.test.ts carry the signatures of location.replace and
location.reload, as locationAt's overrides require.
2026-11-26 14:03:46 +01:00
Maurice 3c1cf8b347 chore(server): lower the strict baseline of the repository base class
MikroORM 7.2.12's typings leave trek-repository.ts with 4 strict errors instead of 8; the ratchet holds it there.
2026-11-26 14:03:46 +01:00
Maurice 1ed77870f9 test(db): see the unnamed temp files SQLite 3.54 opens on Linux
SQLite 3.54, which better-sqlite3 13.2.0 bundles, opens its temp files
with O_TMPFILE where the system has it. On Linux such a file has no
name: among the process's descriptors it reads <dir>/#<inode> (deleted)
instead of etilqs_<random>. The watcher only looked for the name, so
the control test saw nothing, and the test that TREK's own connection
never touches a temp file would have passed whatever happened. The
watcher now knows both forms; the control proves again that it sees
them.
2026-11-26 14:03:46 +01:00
Maurice 22ee4dbac7 ci(dependabot): let MikroORM and msw move again
Both are on their new versions now: MikroORM 7.2.12 with the OAuth
repositories writing the client the way it accepts, and the client tests
on msw 3. Their ignore entries go. better-sqlite3 and kysely, which
@mikro-orm/sqlite pins exactly, join the MikroORM group instead of being
ignored, so the three move in one pull request. cron and the musl rollup
pins stay held back for their own reasons.
2026-11-26 13:41:29 +01:00
Maurice 6926591112 fix(admin): a default setting reset right after typing is the value that stays
Typing a new Mapbox token or CARTO key and clicking that field's reset
link straight away sent two requests at once: the field's save on blur,
then the reset. Nothing ordered them, so when the server handled the
save last, the key typed a moment ago was stored again while the field
showed it cleared, on the desktop tab and on the phone screen alike.

The hook both shells share now sends its writes one after another, in
the order they were made (useWritesInOrder; a write that fails does not
hold up the next). FE-ADMIN-DUS-032 types, clicks reset at once and
makes the save the slower request; it fails without the order.
FE-HOOK-WRITES-001 to 003 cover the helper.
2026-11-26 13:41:28 +01:00
Maurice 66382e791b fix(admin): keep the dev notification buttons mounted while the panel updates
The desktop panel declared its button component inside its render, so
every state change (each lookup landing, each send starting and ending)
made a new component type and React remounted every button: focus and
hover were lost, and a click that arrived during a re-render went to a
button that was no longer there. Btn now lives at module level and takes
the send in flight as a prop, as the phone panel's Btn already does.
FE-ADMIN-DEVNOTIF-017 holds a button across the lookups landing and
expects the same element; it fails with the old panel.
2026-11-26 13:41:28 +01:00
Maurice 32837afe2e chore(deps-dev): bump msw from 2.15.0 to 3.0.8 and move the client tests to it
msw 3 renames onUnhandledRequest to onUnhandledFrame and reports every
network frame there; the setup judges the HTTP frames as before (another
origin is an error, the page's own a warning).

It also resolves a relative handler, and its fetch interceptor a
relative URL, against location.href at the time of the request, while
jsdom's XHR sends to the document's own address. Tests that replaced
window.location with a stand-in on http://localhost while the page runs
on http://localhost:3000 sent their requests past every handler.
tests/helpers/location.ts builds such stand-ins on the page's own origin
(locationAt, pageUrl), and every one of them now uses it.

msw no longer escapes fake timers, and responses are timed differently,
which surfaced tests that ended with work still running: a held request
answering in the next test, a lookup still out when the assertions ran,
a reload switched by counting reads. Each of those now waits for, or
releases, what it started, and answers by what happened rather than by
a count.

The day panel suites share their setup through
tests/helpers/dayDetailPanel.ts instead of a copy each, which keeps the
larger one under its size limit.
2026-11-26 13:15:45 +01:00
Maurice 05f4c84885 test(reservations): cover the traveller insert that ignores existing rows
ReservationTravelers.insertIgnore had no test of its own. MikroORM 7.2.10 changed how upsertMany with a composite conflict key matches rows read back after a conflict, which is exactly the case of a traveller already on the booking next to a new one in one call. RS9-001 to RS9-004 pin that case, a duplicate id, another booking's row and an empty list; the first two fail with a plain insert.
2026-11-26 12:57:32 +01:00
Maurice 6905729ab6 chore(deps): bump MikroORM from 7.2.8 to 7.2.12 with better-sqlite3 13.2.0 and kysely 0.29.9
From 7.2.9 on, MikroORM reads a bare value given for a relation as the
target's primary key. The client relation of oauth_tokens and
oauth_consents points at oauth_clients.client_id, a unique column that
is not the primary key, so every token mint and every consent grant was
refused ("Cannot set OauthTokens.client to a reference of OauthClients
without the value of OauthClients.client_id"): every OAuth and MCP
sign-in would have failed.

insertToken now hands the referenced column itself to the relation
(oauthClientRef), which MikroORM writes to client_id as it is.
upsertGrant writes the row with Kysely's onConflict on
UNIQUE(client_id, user_id), because em.upsert takes that same value as
the data of a new OauthClients entity. The test fixtures that seed
tokens and consents use the same helper. Reading client_id back is
unchanged; the repository tests seed clients whose primary key differs
from their client_id, one of them a decoy whose primary key equals
another client's client_id.

The lockfile resolves the MikroORM tree from scratch, so there is one
@mikro-orm/core again instead of a second copy next to @mikro-orm/nestjs.
better-sqlite3 13.2.0 ships prebuilt binaries for every platform the
image builds, musl included.
2026-11-26 12:39:43 +01:00
Maurice 85aa1c91ff test(booking-import): check the upload limits the route sets, not Nest's whole set
NestJS 11.2.12 adds its default parts limit to every multer interceptor, so the options hold one more key than the route names.
2026-11-26 11:26:35 +01:00
Maurice de9901d941 refactor(files): drop the drop zone's noClick option, which is its default
Keeps useFileManager within the function length limit now that it names noPaste; react-dropzone's noClick defaults to false, so a click still opens the picker.
2026-11-26 11:26:35 +01:00
Maurice 95a0cd2f77 ci(dependabot): hold back the updates that cannot move on their own
The last grouped update showed which packages break when Dependabot moves
them alone: MikroORM from 7.2.9 on refuses the OAuth repositories'
foreign key writes, better-sqlite3 and kysely are pinned by
@mikro-orm/sqlite, cron by @nestjs/schedule, the musl rollup pins have
to follow the installed rollup, and msw 3 is a migration of the client
tests. Each is held back with its reason and moves by hand. The rules
name the version update types rather than the whole package wherever
that is enough, and a security advisory for any of them still shows in
the Security tab.
2026-11-26 11:15:46 +01:00
Maurice f922068a8e chore(deps): bump express from 4.22.3 to 5.3.0 and @types/express to 5.0.6
Nest already serves every request through Express 5. Only the parsers,
the static handler and their types still came from the direct Express 4
dependency, so this moves those three and keeps their behaviour:

- body-parser 2 leaves req.body undefined when it did not read a body,
  where body-parser 1 left an empty object. A bodyless POST to a route
  whose fields are all optional answered 400, and a plugin route got
  null. emptyBodyDefault restores the empty object for everything but
  /mcp, which stays raw (BOOT-009, PACK-3T-004).
- serve-static 2 no longer exposes its mime table. The Brotli copy of
  an asset is typed through mime-types 3 with the fallback send uses,
  so it keeps the Content-Type of the original file (PRECOMP-001).
- @types/express 5 types a route param as string or string[]; the
  photo route names its single :filename param.

The MCP SDK resolves the same Express 5.3 now; Nest keeps the 5.2.1 it
pins.
2026-11-26 11:09:32 +01:00
Maurice 5c5d85ef60 chore(deps): bump NestJS to 11.2.12, @nestjs/swagger to 11.4.8 and jimp to 1.7.0
The NestJS part of the grouped Dependabot update, without the packages
that cannot move yet: MikroORM stays on 7.2.8 together with the
better-sqlite3 and kysely versions it pins, cron stays on the 4.4.0
that @nestjs/schedule pins exactly, and the musl rollup pins stay on
the rollup version the lockfile installs.

What changed in Nest does not reach TREK's own paths: TrekWsAdapter
builds its server and binds every handler itself, so the new WsAdapter
defaults do not apply, and the new limit of 1000 multipart parts per
request is far above what the upload routes receive.
2026-11-26 11:04:58 +01:00
Maurice d83e98366b chore(deps): bump react-dropzone from 14.4.1 to 20.2.1
react-dropzone 19.2 turned on a paste handler of its own on the drop
zone. The file panel already uploads pasted files once for the whole
panel, after the upload permission check, so a paste while the zone
had focus sent every file twice. The zone's paste handling is switched
off with noPaste; FE-COMP-FILEMANAGER-039 pastes on the zone itself
and expects a single upload.

prop-types and loose-envify leave the lockfile with the old version.
2026-11-26 11:03:21 +01:00
Maurice 756eae39ff chore(deps-dev): bump @types/node from 25.9.8 to 26.6.11
Type definitions only; the image and .nvmrc stay on Node 24. npm drops the stale peer flag from the optional rollup binaries while it rewrites the lockfile; nothing installs with --omit=peer.
2026-11-26 11:02:10 +01:00
Maurice 4f66a344ca fix(auth): retire password reset links when the account's email or password changes
A reset link is a credential sent to the address the account had when it
was asked for. It stayed valid for its full hour after the account moved
to another address or got a new password, so a link sent to the old
mailbox could still set a password on the account.

Changing the email in the user's own settings, changing the password,
and an admin changing a user's email or setting a password now consume
every live reset link of that user, in the same transaction as the
change. Saving the same address, or it in another case, keeps the link,
and a link asked for afterwards works as before.
2026-11-26 10:17:13 +01:00
Maurice 96b2778c2f fix(native): keep the server picker clear of Android's navigation bar
On Android the web view can report env(safe-area-inset-*) as 0 while the
app draws edge to edge, so the buttons at the foot of the app's first
screens sat under the three-button navigation bar and the logo under the
status bar. Capacitor's SystemBars plugin writes the real insets to the
page as --safe-area-inset-*; the first screens now read them as one more
floor next to env() and the insets iOS measures itself. Where Capacitor
lays the web view out between the bars it writes 0, and in a browser the
variables are unset, so nothing changes there.

Closes #3221
2026-11-26 10:10:22 +01:00
Maurice 98c883b4e8 test(assistant): load the tool cap's groups without awaiting in a loop
The cap suite added eleven no-await-in-loop and two non-null assertion
warnings to the server tests, past the lint ratchet. Independent sessions
now run side by side and the sequential loads go through a recursive
helper.
2026-11-25 22:48:57 +01:00
Maurice df82208bd5 fix(assistant): keep every step within the 128 tools OpenAI and Azure accept
A trip chat offered 130 tools in its first step and up to 359 with every
group loaded. OpenAI's APIs and Azure refuse a request with more than 128
function tools (array_above_max_length), so the trip assistant failed at
once on an OpenAI style or Azure Foundry connection, while Anthropic and
the ChatGPT login took the longer list.

The trip's bookings, its packing lists and to-dos, changes to its budget
and its tags now load as groups like the addons do, which brings the core
to 63 tools, so any one group fits beside it. Loading a group that would
pass the limit unloads the one used longest ago, a call to one of its
tools loads it again, and groups asked for together that do not fit are
named so the model loads them later. The groups that are part of the trip
carry no domain on their change cards. Reading the costs stays in the
core.
2026-11-25 22:34:41 +01:00
Maurice 18867d9499 fix(weather): answer the day 16 days out with climate instead of an error
The detailed weather took the forecast path for any day whose distance
from now was at most 16 days, measured as a fraction of a day. Open-Meteo's
forecast reaches today + 15 calendar days, and the day 16 out lies 15.x
days from now, so it was asked of the forecast, refused with a 400, and
the day showed "No weather data". The cutoff now counts calendar days and
sends anything past today + 15 to the climate path. The forecast measures
its range from the place's own date, which trails UTC in the Americas for
part of the day, so a refusal of that range also falls back to climate.

Closes #3216
2026-11-25 22:21:16 +01:00
130 changed files with 3898 additions and 2228 deletions
+15 -1
View File
@@ -28,8 +28,10 @@ updates:
groups:
# Packages that release in lockstep move together, so a PR never pins
# half of them on one version and half on the next.
# better-sqlite3 and kysely are pinned exactly by @mikro-orm/sqlite and
# share its connection, so they move with MikroORM.
mikro-orm:
patterns: ['@mikro-orm/*']
patterns: ['@mikro-orm/*', better-sqlite3, kysely]
update-types: [minor, patch]
nestjs:
patterns: ['@nestjs/*']
@@ -54,6 +56,18 @@ updates:
# by hand once mapbox-gl checks the built-ins first again.
- dependency-name: mapbox-gl
versions: ['>=3.33.0']
# The packages below move by hand, each for its reason. A security
# advisory for one of them still shows up in the Security tab, where it
# is handled together with that reason.
#
# Pinned exactly by @nestjs/schedule; a newer cron of our own would be a
# second copy whose CronJob the scheduler does not accept.
- dependency-name: cron
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# Root pins that must name the rollup version the lockfile installs (the
# Alpine image needs the musl binaries).
- dependency-name: '@rollup/rollup-linux-*-musl'
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
- package-ecosystem: npm
+54 -1
View File
@@ -105,9 +105,62 @@ jobs:
track: ${{ inputs.track || 'internal' }}
status: draft
# The same build for installs outside Google Play: the universal APK Google
# Play makes of this bundle, signed with the Play app signing key, published
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). Held back
# while the app needs a server version that is not released yet.
- name: Whether the latest server release serves this build
id: released
env:
GH_TOKEN: ${{ github.token }}
run: |
tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
git fetch --depth=1 origin "refs/tags/$tag:refs/tags/$tag"
git show "$tag:server/src/nest/health/features.controller.ts" > "$RUNNER_TEMP/released-features.ts"
node scripts/ci/android-apk-release.mjs guard "$RUNNER_TEMP/released-features.ts" >> "$GITHUB_OUTPUT"
- name: Universal APK from Google Play
if: steps.released.outputs.publish == 'true'
env:
PLAY_APK_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_APK_SERVICE_ACCOUNT_JSON }}
APK: trek-${{ steps.version.outputs.version }}.apk
run: |
printf '%s' "$PLAY_APK_SERVICE_ACCOUNT_JSON" > "$RUNNER_TEMP/play-apk.json"
node scripts/ci/android-apk-release.mjs download "$RUNNER_TEMP/play-apk.json" com.liketrek.trek \
"${{ steps.version.outputs.build }}" "$RUNNER_TEMP/$APK"
rm -f "$RUNNER_TEMP/play-apk.json"
cd "$RUNNER_TEMP" && sha256sum "$APK" > "$APK.sha256"
- uses: actions/create-github-app-token@v3
if: steps.released.outputs.publish == 'true'
id: apk-token
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: liketrek
repositories: trek-android
# One release per app version: a newer build of the same version replaces
# its APK, so the release always holds what Google Play holds for it.
- name: Publish to liketrek/trek-android
if: steps.released.outputs.publish == 'true'
env:
GH_TOKEN: ${{ steps.apk-token.outputs.token }}
VERSION: ${{ steps.version.outputs.version }}
BUILD: ${{ steps.version.outputs.build }}
run: |
apk="$RUNNER_TEMP/trek-$VERSION.apk"
notes="TREK $VERSION for Android (build $BUILD): the build Google Play distributes, with the same signature. Connect it to your own TREK server; push and TREK Cloud need Google Play services. Changes: https://github.com/liketrek/TREK/releases"
if gh release view "v$VERSION" -R liketrek/trek-android > /dev/null 2>&1; then
gh release upload "v$VERSION" -R liketrek/trek-android --clobber "$apk" "$apk.sha256"
gh release edit "v$VERSION" -R liketrek/trek-android --notes "$notes"
else
gh release create "v$VERSION" -R liketrek/trek-android --title "TREK $VERSION" --notes "$notes" "$apk" "$apk.sha256"
fi
- name: Remove the upload key
if: always()
run: rm -f "$RUNNER_TEMP/upload.jks"
run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
ios:
if: github.repository == 'liketrek/TREK'
+17 -9
View File
@@ -35,7 +35,7 @@ permissions:
# Server tests i/10 one slice of the server suite, with coverage
# Server coverage merges the slices, checks the per-domain
# thresholds, uploads lcov
# Server Postgres 14 i/3, Server Postgres 18 i/3
# Server Postgres 14 i/3, Server Postgres 19 i/3
# per supported major, in three slices: the probe
# (the repository SQL against Postgres, first slice
# only), then a slice of the lane (every suite that
@@ -55,7 +55,7 @@ permissions:
# Client e2e i/2 one slice of the browser flows in Chromium and
# WebKit, in the Playwright container
# Docker and Helm builds the image and boots it until ready, on
# SQLite and on Postgres 18; lints and renders the
# SQLite and on Postgres 19; lints and renders the
# Helm chart and checks the compose files
# Sonar SonarCloud analysis, not required
# ci-ok the one required check (below)
@@ -639,7 +639,7 @@ jobs:
retention-days: 1
# TREK on Postgres, once per supported major: the oldest (14) and the newest
# (18). Both steps run against the same service, the probe on an empty
# (19). Both steps run against the same service, the probe on an empty
# database of its own, the lane on databases it creates and drops.
#
# The probe (server/scripts/pg-probe.ts): against an empty Postgres it
@@ -696,7 +696,7 @@ jobs:
strategy:
fail-fast: false
matrix:
postgres: [14, 18]
postgres: [14, 19]
shard: [1, 2, 3]
services:
postgres:
@@ -757,14 +757,14 @@ jobs:
if-no-files-found: ignore
retention-days: 14
# The image ships the 18 client tools, which write settings a 14 server
# The image ships the 19 client tools, which write settings a 14 server
# does not know; the backup round trip runs with the same tools here.
- name: Install the PostgreSQL 18 client tools
- name: Install the PostgreSQL 19 client tools
run: |
set -euo pipefail
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >/dev/null
sudo apt-get install -y --no-install-recommends postgresql-client-18 >/dev/null
/usr/lib/postgresql/18/bin/pg_restore --version
sudo apt-get install -y --no-install-recommends postgresql-client-19 >/dev/null
/usr/lib/postgresql/19/bin/pg_restore --version
- name: Run the Postgres lane
if: ${{ !cancelled() }}
@@ -1224,6 +1224,14 @@ jobs:
--set service.port=8080 \
--set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \
> "$out/http-route-variants.yaml"
helm template trek charts/trek \
--set-json 'extraObjects=[{"apiVersion":"batch/v1","kind":"CronJob","metadata":{"name":"{{ include \"trek.fullname\" . }}-backup-copy"},"spec":{"schedule":"0 3 * * *","jobTemplate":{"spec":{"template":{"spec":{"restartPolicy":"OnFailure","containers":[{"name":"copy","image":"busybox:1.36","command":["ls","/data/backups"],"volumeMounts":[{"name":"data","mountPath":"/data","readOnly":true}]}],"volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"{{ include \"trek.fullname\" . }}-data","readOnly":true}}]}}}}}},"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: {{ .Release.Name }}-notes\ndata:\n release: {{ .Release.Name | quote }}\n"]' \
> "$out/extra-objects.yaml"
# kubeconform accepts a name that still reads {{ ... }}, so check that both forms went through tpl.
if grep -n '{{' "$out/extra-objects.yaml"; then
echo "::error::extraObjects left a template unrendered"
exit 1
fi
- name: Check the manifests against the Kubernetes schemas
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
@@ -1339,7 +1347,7 @@ jobs:
set -euo pipefail
docker network create trek-ci-pg
docker run -d --name trek-ci-db --network trek-ci-pg \
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:18
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:19
for _ in $(seq 1 30); do
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
sleep 2
+1 -1
View File
@@ -137,7 +137,7 @@ These principles come out of a full-repo audit and shape all new code:
## Quality gates in CI
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 19, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 19, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
+17 -9
View File
@@ -73,22 +73,30 @@ COPY server/package.json ./server/
# The upgrade takes the Debian security fixes the base image was built before
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
#
# postgresql-client-18 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres
# postgresql-client-19 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/19/bin, which back up and restore an install on Postgres
# (TREK_DB_URL). A client handles every server up to its own major and refuses
# a newer one, so the image carries the newest major TREK supports (14 to 18).
# a newer one, so the image carries the newest major TREK supports (14 to 19).
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
# repository (PGDG): the `18` component lists that major's packages and no
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at
# build time. Raise both together when TREK supports a newer major.
# repository (PGDG): its `main` component carries every major the project
# supports, and the package name pins the one installed. The per-major
# components can trail a new release, so the image does not rely on them. The
# repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2 44A0 7FCC 7D46
# ACCC 4CF8) is kept beside the entrypoint instead of fetched at build time.
# Raise the package together with SUPPORTED_SERVER_MAJORS in
# server/src/db/engine/postgres/server-checks.ts.
# Earlier images carried the version 18 tools, and installs that set
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin (the old .env.example value)
# would lose backups and the pre-migrate snapshot after updating, so that path
# stays as a link to the 19 tools, which handle every supported server.
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main' \
> /etc/apt/sources.list.d/pgdg.list && \
apt-get update && \
apt-get upgrade -y --no-install-recommends && \
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
libkitinerary-bin libsqlite3-0 postgresql-client-19 && \
mkdir -p /usr/lib/postgresql/18 && ln -s /usr/lib/postgresql/19/bin /usr/lib/postgresql/18/bin && \
npm ci --workspace=server --omit=dev --ignore-scripts && \
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
+1 -1
View File
@@ -288,7 +288,7 @@ docker compose up -d
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
for the full walkthrough.
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 19 database instead. The
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and
how to move an existing SQLite install to Postgres with the command TREK ships for it.
+1
View File
@@ -60,3 +60,4 @@ See `values.yaml` for more options.
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
- Use `extraObjects` to render further Kubernetes objects next to the chart's own, for example a backup `CronJob`. Each item is a map or a string of YAML, and `{{ }}` in it is evaluated, so `{{ .Release.Name }}` works. A backup job should copy TREK's own backups from `backups/` on the data volume and mount it read only, since that volume also holds the encryption key. The archives carry `.encryption_key` too unless `ENCRYPTION_KEY` is set, so protect the copy's destination like the data volume.
+8
View File
@@ -0,0 +1,8 @@
{{- range .Values.extraObjects }}
---
{{- if kindIs "string" . }}
{{ tpl . $ }}
{{- else }}
{{ tpl (toYaml .) $ }}
{{- end }}
{{- end }}
+24 -1
View File
@@ -190,7 +190,7 @@ env:
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
# (nor a member of one, nor hold a right that reaches the server's files or programs): a
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
# SQL that creates such a role. PostgreSQL 14 to 19 is supported.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database:
url: ""
@@ -338,6 +338,29 @@ extraVolumes: []
# readOnly: true
extraVolumeMounts: []
# Further Kubernetes objects the chart renders next to its own, for example a Job, a
# CronJob or a ConfigMap. Each item is rendered as written, either as a map or as a
# string of YAML, and {{ }} in it is evaluated, so {{ include "trek.fullname" . }} or
# {{ .Release.Name }} work, in both forms. Write literal braces as {{ "{{" }}.
# A backup job must only read the data volume: it also holds the encryption key and the
# server's secrets, and a second writer corrupts travel.db. Rather than copying the live
# travel.db, copy TREK's own backups (Admin, Backup, automatic backups) from backups/ in
# that volume. Those archives carry .encryption_key too (unless ENCRYPTION_KEY is set),
# so protect the job's destination like the data volume itself.
# extraObjects:
# - apiVersion: v1
# kind: ConfigMap
# metadata:
# name: '{{ include "trek.fullname" . }}-extra'
# data:
# note: hello
# - |
# apiVersion: v1
# kind: ConfigMap
# metadata:
# name: {{ .Release.Name }}-notes
extraObjects: []
resources:
requests:
cpu: 100m
+26 -5
View File
@@ -204,11 +204,32 @@
--sea: #cfe3ef;
--text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
/* The insets of the device, from the web view or, on iOS, from the native side. */
--safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px));
--safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
/* The insets of the device, from the web view or from the native side. On
* Android a web view can report env() as 0 while the page reaches under the
* status and navigation bars; Capacitor's SystemBars writes the real insets
* to --safe-area-inset-* instead (0 where it lays the web view out between
* the bars). iOS measures its own (TrekBridgeViewController publishSafeArea).
* In a browser the variables are unset: env() alone. */
--safe-top: max(
env(safe-area-inset-top, 0px),
var(--safe-area-inset-top, 0px),
var(--trek-native-safe-top, 0px)
);
--safe-bottom: max(
env(safe-area-inset-bottom, 0px),
var(--safe-area-inset-bottom, 0px),
var(--trek-native-safe-bottom, 0px)
);
--safe-start: max(
env(safe-area-inset-left, 0px),
var(--safe-area-inset-left, 0px),
var(--trek-native-safe-left, 0px)
);
--safe-end: max(
env(safe-area-inset-right, 0px),
var(--safe-area-inset-right, 0px),
var(--trek-native-safe-right, 0px)
);
color-scheme: light;
-webkit-text-size-adjust: 100%;
}
+3 -3
View File
@@ -118,7 +118,7 @@
"plyr": "^3.8.5",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^14.4.1",
"react-dropzone": "^20.2.1",
"react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0",
@@ -141,7 +141,7 @@
"@testing-library/user-event": "^14.6.13",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/leaflet": "^1.9.22",
"@types/node": "^25.9.8",
"@types/node": "^26.6.11",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.2.1",
@@ -154,7 +154,7 @@
"eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1",
"msw": "^2.15.0",
"msw": "^3.0.8",
"postcss": "^8.5.33",
"prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0",
+1 -1
View File
@@ -15,7 +15,7 @@
"@typescript-eslint/no-unused-vars": 117,
"react-hooks/immutability": 28,
"max-lines-per-function": 127,
"react-hooks/static-components": 50,
"react-hooks/static-components": 38,
"react-hooks/preserve-manual-memoization": 12,
"no-useless-assignment": 7,
"no-empty": 19,
-1
View File
@@ -2121,7 +2121,6 @@
"tests/unit/sync/tripSyncManager.test.ts",
"tests/unit/tripStore.test.ts",
"tests/unit/utils/cleanAmount.test.ts",
"tests/unit/utils/fileDownload.test.ts",
"tests/unit/utils/formatters.test.ts",
"tests/unit/utils/placeFiles.test.ts",
"tests/unit/utils/shellGuard.test.ts",
+2 -2
View File
@@ -8,7 +8,7 @@
"src/components/Map/MapView.tsx": 1200,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2116,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
"src/components/Planner/DayDetailPanel.test.tsx": 2332,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
@@ -17,7 +17,7 @@
"src/components/Studio/countryShapes.ts": 2595,
"src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
"src/pages/JourneyDetailPage.test.tsx": 4028,
"src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1294,
"src/pages/TripPlannerPage.tsx": 1128,
"src/pages/atlas/useAtlas.ts": 1207,
+28 -4
View File
@@ -1,13 +1,14 @@
import React from 'react'
import { render, screen, waitFor, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../tests/helpers/msw/server'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
import { resetAllStores } from '../tests/helpers/store'
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
import { locationAt } from '../tests/helpers/location'
import { offlineDb } from './db/offlineDb'
import { SETTINGS_WAIT_MS } from './utils/startDestination'
import App from './App'
@@ -185,9 +186,29 @@ describe('RootRedirect — startup destination', () => {
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
stubActiveTrip({ id: 42, title: 'Japan' })
// App asks for the settings on its own as soon as the user is signed in.
// Held until the redirect is decided, or whichever answer lands first wins
// and the test proves nothing about the mirror; released here, so it cannot
// land in the next test either.
let releaseSettings = () => {}
const settingsHeld = new Promise<void>((resolve) => { releaseSettings = resolve })
onTestFinished(() => releaseSettings())
server.use(
http.get('/api/settings', async () => {
await settingsHeld
return HttpResponse.json({
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
})
}),
)
renderApp('/')
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
expect(currentPath()).toBe('/trips/42?tab=finanzplan')
expect(useSettingsStore.getState().isLoaded).toBe(false)
releaseSettings()
await waitFor(() => expect(useSettingsStore.getState().isLoaded).toBe(true))
})
})
@@ -532,7 +553,7 @@ describe('Version cache-busting', () => {
const reload = vi.fn()
Object.defineProperty(window, 'location', {
writable: true,
value: { ...window.location, reload },
value: locationAt('/', { reload }),
})
server.use(
@@ -587,7 +608,7 @@ describe('Version cache-busting', () => {
// and try to update.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
server.use(
http.get('/api/auth/app-config', () =>
@@ -609,7 +630,7 @@ describe('Version cache-busting', () => {
// failure neither deletes anything nor reloads into the old worker's shell.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
const cachesDelete = vi.fn().mockResolvedValue(true)
const unregister = vi.fn().mockResolvedValue(true)
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
@@ -685,6 +706,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
// No backend: the settings never arrive, so only the timeout can decide.
// Answered, they would open the dashboard on their own and hide the wait.
server.use(http.get('/api/settings', () => HttpResponse.error()))
renderApp('/')
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
@@ -1,7 +1,7 @@
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { delay, http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildAdmin } from '../../../tests/helpers/factories';
@@ -341,12 +341,43 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('pk.old');
await user.clear(input);
await user.type(input, 'pk.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }, { mapbox_access_token: null }]));
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
it('FE-ADMIN-DUS-032: a reset clicked while the save of the field is still out is the one that stays', async () => {
const user = userEvent.setup();
const { state } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
// The save is the slower request: sent at once, the reset would overtake it.
const done: string[] = [];
server.use(
http.put('/api/admin/default-user-settings', async ({ request }) => {
const body = await request.json() as Record<string, unknown>;
if (body.mapbox_access_token !== null) await delay(100);
if (body.mapbox_access_token === null) delete state.mapbox_access_token;
else state.mapbox_access_token = body.mapbox_access_token;
done.push(body.mapbox_access_token === null ? 'reset' : 'save');
return HttpResponse.json({ ...state });
}),
);
render(<DefaultUserSettingsTab />);
await screen.findByText('Shared Mapbox token');
const input = screen.getByPlaceholderText('pk.eyJ…');
await user.clear(input);
await user.type(input, 'pk.new');
// The click leaves the field, which saves it, and resets it right after.
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(done).toEqual(['save', 'reset']));
expect(state.mapbox_access_token).toBeUndefined();
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
@@ -449,12 +480,14 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('ck.old');
await user.clear(input);
await user.type(input, 'ck.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared CARTO key'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null }));
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }, { carto_api_key: null }]));
await waitFor(() => expect(cartoInput()).toHaveValue(''));
});
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' });
/**
* Renders the panel and waits until both lookups (trips and users) have landed, so a test
* acts on the settled panel and no lookup answers after it has ended.
*/
async function renderSettled() {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
}
const LOOKUPS = ['/api/admin/users', '/api/trips'];
/**
* Records the GET requests to `paths` that have been answered, for the tests whose lookups
* come back empty or failed and so change nothing on screen to wait for. Call before render;
* the returned function waits until exactly `paths` (a path once per expected request) ended.
*/
function trackRequests(paths: string[] = LOOKUPS) {
const answered: string[] = [];
const onEnd = ({ request }: { request: Request }) => {
const { pathname } = new URL(request.url);
if (request.method === 'GET' && paths.includes(pathname)) answered.push(pathname);
};
server.events.on('request:end', onEnd);
return async () => {
try {
await waitFor(() => expect([...answered].sort()).toEqual([...paths].sort()));
} finally {
server.events.removeListener('request:end', onEnd);
}
};
}
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
@@ -21,9 +54,12 @@ afterEach(() => {
});
describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
// Let the lookups the panel started land here, not in the next test
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
});
it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => {
@@ -36,8 +72,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const options = Array.from(tripSelect.querySelectorAll('option'));
const labels = options.map(o => o.textContent);
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const selects = screen.getAllByRole('combobox');
// Second combobox is the user selector (first is trip selector)
const userSelect = selects[1];
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody).toMatchObject({
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
scope: 'user',
targetId: ADMIN_USER.id,
});
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
// The send is held open until the assertion ran, then released, so it settles in this test
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use(
http.post('/api/admin/dev/test-notification', async () => {
await new Promise(() => {}); // never resolves — simulates in-flight
await gate;
return HttpResponse.json({ ok: true });
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
// The request handler never resolves, so sending stays true after the click settles
// The request handler is held, so sending stays true after the click settles
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => {
const buttons = screen.getAllByRole('button');
buttons.forEach(btn => expect(btn).toBeDisabled());
});
release();
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
@@ -117,8 +156,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('No channel configured')).toBeInTheDocument();
});
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Failed')).toBeInTheDocument();
});
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody!.targetId).toBe(tokyoId);
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: booking_change');
});
it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
);
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
// Wait for user data to confirm async effects have settled
await screen.findByText('User-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
});
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Boolean → Me').closest('button')!);
await screen.findByText('Sent: boolean-me');
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tripId = Number((tripSelect as HTMLSelectElement).value);
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
@@ -278,9 +315,11 @@ describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
});
@@ -288,22 +327,38 @@ describe('DevNotificationsPanel', () => {
server.use(
http.get('/api/trips', () => HttpResponse.error()),
http.get('/api/admin/users', () => HttpResponse.error()),
// A network error makes the API client probe /api/health before it rejects; the server
// is down here, so the probe fails too instead of going out to the real network
http.get('/api/health', () => HttpResponse.error()),
);
const lookupsAnswered = trackRequests([...LOOKUPS, '/api/health', '/api/health']);
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(await screen.findByText('Type Testing')).toBeInTheDocument();
await lookupsAnswered();
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
const btn = screen.getByText('Simple → Me').closest('button')!;
fireEvent.mouseEnter(btn);
expect(btn.style.background).toBe('');
expect(btn.className).toContain('hover:bg-surface-secondary');
});
it('FE-ADMIN-DEVNOTIF-017: a send button stays the same element while the panel updates around it', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
const btn = screen.getByRole('button', { name: /Simple → Me/ });
// The lookups answer and re-render the panel.
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
expect(btn.isConnected).toBe(true);
expect(screen.getByRole('button', { name: /Simple → Me/ })).toBe(btn);
});
});
@@ -25,20 +25,17 @@ function ButtonGrid({ children }: { children: React.ReactNode }): React.ReactEle
return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div>
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
// ── Helpers ──────────────────────────────────────────────────────────────
const Btn = ({
id, label, sub, icon: Icon, onClick,
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void
}) => (
/**
* One send button. Declared here, not inside the panel: a component made during
* render is a new type on every render, so React would remount every button on
* each state change and a click could land on one that is already gone.
*/
function Btn({
id, label, sub, icon: Icon, onClick, sending,
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void; sending: string | null
}): React.ReactElement {
return (
<button type="button"
onClick={onClick}
disabled={sending !== null}
@@ -54,6 +51,14 @@ export default function DevNotificationsPanel(): React.ReactElement {
{sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />}
</button>
)
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
return (
<div>
@@ -66,16 +71,16 @@ export default function DevNotificationsPanel(): React.ReactElement {
badge={<StatusPill tone="warning">DEV ONLY</StatusPill>}
>
<ButtonGrid>
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
<Btn sending={sending} id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
onClick={send.simpleMe}
/>
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
<Btn sending={sending} id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
onClick={send.booleanMe}
/>
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
<Btn sending={sending} id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
onClick={send.navigateMe}
/>
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
<Btn sending={sending} id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
onClick={send.simpleAdmins}
/>
</ButtonGrid>
@@ -94,19 +99,19 @@ export default function DevNotificationsPanel(): React.ReactElement {
</SelectBox>
</EditorField>
<ButtonGrid>
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
<Btn sending={sending} id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
onClick={send.bookingChange}
/>
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
<Btn sending={sending} id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
onClick={send.tripReminder}
/>
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
<Btn sending={sending} id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
onClick={send.photosShared}
/>
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
<Btn sending={sending} id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
onClick={send.collabMessage}
/>
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
<Btn sending={sending} id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
onClick={send.packingTagged}
/>
</ButtonGrid>
@@ -127,6 +132,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
</EditorField>
<ButtonGrid>
<Btn
sending={sending}
id={tripInviteId}
label="trip_invite"
sub="navigate · user"
@@ -134,6 +140,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
onClick={send.tripInvite}
/>
<Btn
sending={sending}
id={vacayInviteId}
label="vacay_invite"
sub="navigate · user"
@@ -147,7 +154,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
<SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users.">
<ButtonGrid>
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download}
<Btn sending={sending} id="version_available" label="version_available" sub="navigate · admin" icon={Download}
onClick={send.versionAvailable}
/>
</ButtonGrid>
@@ -137,19 +137,25 @@ describe('useDefaultUserSettings', () => {
act(() => result.current.pickTilePreset(''));
act(() => result.current.pickStylePreset(''));
// Writes go out in order, a microtask later: let any that was queued start first.
await act(async () => {});
expect(update).not.toHaveBeenCalled();
act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png'));
expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png');
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' })
);
act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron'));
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' });
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' })
);
act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre'));
act(() => result.current.commitStyle());
expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE);
expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE });
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }));
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));
});
});
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { adminApi } from '../../api/client';
import { useWritesInOrder } from '../../hooks/useWritesInOrder';
import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
@@ -87,32 +88,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
.catch(() => setLoaded(true));
}, []);
const save = async (patch: Partial<Defaults>) => {
try {
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
// A field's save on blur and the reset clicked right after it reach the server in
// that order, or the save landing last would store the old value again.
const inOrder = useWritesInOrder();
const reset = async (key: keyof Defaults) => {
try {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
setDefaults(updated);
if (key === 'map_tile_url') setMapTileUrl('');
if (key === 'mapbox_access_token') setMapboxToken('');
if (key === 'carto_api_key') setCartoKey('');
if (key === 'mapbox_style' || key === 'maplibre_style') {
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
const save = (patch: Partial<Defaults>) =>
inOrder(async () => {
try {
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
toast.success(t('admin.defaultSettings.reset'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
});
const reset = (key: keyof Defaults) =>
inOrder(async () => {
try {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
setDefaults(updated);
if (key === 'map_tile_url') setMapTileUrl('');
if (key === 'mapbox_access_token') setMapboxToken('');
if (key === 'carto_api_key') setCartoKey('');
if (key === 'mapbox_style' || key === 'maplibre_style') {
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
}
toast.success(t('admin.defaultSettings.reset'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
});
const isSet = (key: keyof Defaults) => defaults[key] !== undefined;
@@ -526,6 +526,24 @@ describe('FileManager', () => {
});
});
it('FE-COMP-FILEMANAGER-039: a file pasted while the drop zone has focus is uploaded once', async () => {
const onUpload = vi.fn().mockResolvedValue({ file: { id: 56 } });
render(<FileManager {...defaultProps} onUpload={onUpload} />);
const zone = document.querySelector('[role="presentation"]') as HTMLElement;
const file = new File(['data'], 'pasted.png', { type: 'image/png' });
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true });
Object.defineProperty(pasteEvent, 'clipboardData', {
value: { types: ['Files'], files: [file], items: [{ kind: 'file', type: 'image/png', getAsFile: () => file }] },
});
await fireEvent(zone, pasteEvent);
await waitFor(() => expect(onUpload).toHaveBeenCalled());
await new Promise((resolve) => setTimeout(resolve, 50));
expect(onUpload).toHaveBeenCalledTimes(1);
});
it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => {
const { buildPlace } = await import('../../../tests/helpers/factories');
const place = buildPlace({ id: 10, name: 'Sagrada Familia' });
@@ -124,7 +124,9 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
toast.error(t('files.uploadErrorSize', { max: maxUploadMb }))
}
},
noClick: false,
// Pasting is handled once for the whole panel (handlePaste), with the upload
// permission check; the zone's own paste upload would send each file twice.
noPaste: true,
})
const handlePaste = useCallback((e: React.ClipboardEvent) => {
+14 -2
View File
@@ -3,7 +3,7 @@ import { pluginsApi } from '../../api/client'
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import { haversineKm } from '../../utils/geo'
import { countRoute } from './routeUsageCounter'
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
import { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
import type { RouteAlternative } from './routeTypes'
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
@@ -289,6 +289,12 @@ function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
*
* A day that avoids nothing and that Valhalla could not route is not put to it again for a
* while: OSRM's answer, the same road an OSRM instance draws, stands in for it under a key
* of its own, so every visit does not wait out the relay first (#3228). Never under the
* Valhalla key, which holds only what Valhalla answered. A day that avoids something is
* asked again, since the stand-in drives the very road it means to leave out.
*/
async function valhallaOrOsrmDay(
waypoints: Waypoint[],
@@ -299,6 +305,9 @@ async function valhallaOrOsrmDay(
signal?: AbortSignal
},
): Promise<RouteWithLegs> {
const standInKey = avoiding.length ? null : `${keys.valhalla}:standin`
const stoodIn = standInKey ? await standIn(standInKey) : null
if (stoodIn) return stoodIn
const asking = avoiding.length > 0 || valhallaRoutesDays()
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
if (routed) {
@@ -307,7 +316,10 @@ async function valhallaOrOsrmDay(
}
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain)
return withFallbackNoted(plain, avoiding)
const drawn = withFallbackNoted(plain, avoiding)
// A day left before Valhalla answered was never refused by it.
if (standInKey && !signal?.aborted) keepStandIn(standInKey, drawn)
return drawn
}
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
+18
View File
@@ -39,3 +39,21 @@ export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
if (kept) rememberRoute(key, kept);
return kept;
}
/**
* How long OSRM's answer stands in for a day Valhalla could not route. Long enough that
* reopening the trip draws that day at once instead of waiting out the relay again on
* every visit (#3228), short enough that a Valhalla back from an outage gets the day again
* the same day.
*/
const STAND_IN_MS = 60 * 60 * 1000;
/** Keeps OSRM's answer for a day Valhalla could not route, on the device only, for `STAND_IN_MS`. */
export function keepStandIn(key: string, route: RouteWithLegs): void {
void routeCacheRepo.put(key, route);
}
/** The answer that stood in for a day Valhalla could not route, while it is recent enough. */
export function standIn(key: string): Promise<RouteWithLegs | null> {
return routeCacheRepo.get<RouteWithLegs>(key, STAND_IN_MS);
}
@@ -59,6 +59,8 @@ interface Traffic {
osrm: string[];
}
const HOUR = 60 * 60 * 1000;
const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) });
/** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */
@@ -274,9 +276,41 @@ describe('the route cache keeps the engine apart', () => {
up = true;
resetValhallaTurns();
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
expect(traffic.relay).toHaveLength(1);
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
it('VDAY-CACHE-005: a day the relay could not route opens drawn after a reload, without waiting for the relay again (#3228)', async () => {
const points = freshDay(3);
let slow = true;
const traffic = listen((body) =>
slow ? HttpResponse.json({ error: 'The TREK routing service took too long' }, { status: 504 }) : answered(body)
);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
const { offlineDb } = await import('../../db/offlineDb');
const stoodIn = (key: string) => key.includes(`${points[0].lng},${points[0].lat}`) && key.endsWith(':standin');
await vi.waitFor(async () => expect(await offlineDb.routeCache.filter((row) => stoodIn(row.key)).count()).toBe(1));
// A reload: the modules, and with them the routes in memory and the relay's rest, start over.
vi.resetModules();
const reloaded = await import('./RouteCalculator');
const again = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([again.distance, again.engine]).toEqual([2000, 'osrm']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 1]);
// An hour on, the relay gets the day again and its answer is kept as the day's.
slow = false;
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
const routed = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
});
describe('the route cache while the relay rests', () => {
@@ -1,32 +1,12 @@
// FE-PLANNER-DAYDETAIL-DF-001 to FE-PLANNER-DAYDETAIL-DF-002
// The day panel's heading with "date first in day headings" on (#2921).
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { buildAdmin, buildDay, buildTrip } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { dayDetailProps as props, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { seedStore } from '../../../tests/helpers/store';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import DayDetailPanel from './DayDetailPanel';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const props = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
function settings(dayDateFirst: boolean) {
seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: dayDateFirst },
@@ -34,14 +14,7 @@ function settings(dayDateFirst: boolean) {
}
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
resetDayDetailPanel();
});
describe('DayDetailPanel with the date first', () => {
@@ -5,43 +5,17 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import { useSettingsStore } from '../../store/settingsStore';
import { usePermissionsStore } from '../../store/permissionsStore';
import { usePluginStore } from '../../store/pluginStore';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser, buildAdmin, buildTrip, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
import { seedStore } from '../../../tests/helpers/store';
import { buildUser, buildAdmin, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
import { dayDetailDay as day, dayDetailProps as defaultProps, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import DayDetailPanel from './DayDetailPanel';
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const defaultProps = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] })),
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false },
});
resetDayDetailPanel({ time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false });
});
/** The stay picker filters by category through a pill that opens its list; this picks one entry of it. */
@@ -147,13 +121,23 @@ describe('DayDetailPanel', () => {
});
it('FE-PLANNER-DAYDETAIL-009: weather loading state shown briefly', async () => {
// The forecast is held until the spinner was seen, then released, so the request
// does not stay open past this test.
let release!: () => void;
const gate = new Promise<void>((resolve) => { release = resolve; });
server.use(
http.get('/api/weather/detailed', () => new Promise(() => {})), // never resolves
http.get('/api/weather/detailed', async () => {
await gate;
return HttpResponse.json({ error: true });
}),
);
render(<DayDetailPanel {...defaultProps} lat={48.8566} lng={2.3522} />);
// The spinner announces itself as a loading status
const spinner = await screen.findByRole('status', { name: 'Loading...' });
expect(spinner.querySelector('.animate-spin')).not.toBeNull();
release();
expect(await screen.findByText(/No weather/i)).toBeInTheDocument();
});
it('FE-PLANNER-DAYDETAIL-101: a late forecast for the previous day never replaces the one for the current day', async () => {
@@ -1606,14 +1590,14 @@ describe('DayDetailPanel remaining branches', () => {
const user = userEvent.setup();
const onAccommodationChange = vi.fn();
let updateBody: Record<string, unknown> | null = null;
let listCalls = 0;
// The reload after the save reads the new name; keyed on the save, not on a
// count of reads, so a stray read before it cannot rename the stay early.
server.use(
http.get('/api/trips/1/accommodations', () => {
listCalls += 1;
return HttpResponse.json({
accommodations: [hotel(listCalls > 1 ? { place_name: 'Reloaded Hotel' } : {})],
});
}),
http.get('/api/trips/1/accommodations', () =>
HttpResponse.json({
accommodations: [hotel(updateBody ? { place_name: 'Reloaded Hotel' } : {})],
}),
),
http.put('/api/trips/1/accommodations/1', async ({ request }) => {
updateBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ accommodation: hotel() });
@@ -1874,25 +1858,40 @@ describe('DayDetailPanel remaining branches, part two', () => {
expect(await screen.findByText('15h 20m')).toBeInTheDocument();
});
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', () => {
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', async () => {
// Each mount reads the stays; wait for that read to be answered, so it cannot
// reach the handler of the test that runs next.
let staysRead = 0;
server.use(
http.get('/api/trips/1/accommodations', () => {
staysRead += 1;
return HttpResponse.json({ accommodations: [] });
}),
);
const bare = buildDay({ id: 2, trip_id: 1, date: null, title: null });
const { unmount } = render(<DayDetailPanel {...defaultProps} day={bare} days={[defaultProps.day, bare]} collapsed />);
expect(screen.getByText('Day 2')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(1));
unmount();
render(<DayDetailPanel {...defaultProps} day={bare} days={[]} collapsed />);
expect(screen.getByText('Day ?')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(2));
});
it('FE-W5DDP-020: an empty reload after the edit-save clears the accommodation', async () => {
const user = userEvent.setup();
let listCalls = 0;
// The list empties once the edit is saved, not on a count of reads, so a stray
// read before the save cannot empty it early.
let saved = false;
server.use(
http.get('/api/trips/1/accommodations', () => {
listCalls += 1;
return listCalls === 1 ? HttpResponse.json({ accommodations: [hotel()] }) : HttpResponse.json({});
http.get('/api/trips/1/accommodations', () =>
saved ? HttpResponse.json({}) : HttpResponse.json({ accommodations: [hotel()] }),
),
http.put('/api/trips/1/accommodations/1', () => {
saved = true;
return HttpResponse.json({ accommodation: hotel() });
}),
http.put('/api/trips/1/accommodations/1', () => HttpResponse.json({ accommodation: hotel() })),
);
render(<DayDetailPanel {...defaultProps} places={[buildPlace({ id: 5, name: 'Grand Hotel' })]} />);
@@ -1,5 +1,6 @@
// FE-COMP-PLUGIN-USERSET-001 to -012: the per plugin user settings logic both settings shells share.
import { act, renderHook, waitFor } from '@testing-library/react';
import { locationAt } from '../../../tests/helpers/location';
import { pluginsApi, type PluginAction, type PluginUserSettingField } from '../../api/client';
import { SECRET_MASK } from './settingsForm';
import { usePluginOAuth, usePluginUserSettings } from './usePluginUserSettings';
@@ -150,7 +151,7 @@ describe('usePluginOAuth', () => {
it('FE-COMP-PLUGIN-USERSET-012: a connect hands off to the provider and keeps the button busy', async () => {
const realLocation = window.location;
const loc = { href: 'http://localhost/settings' };
const loc = locationAt('/settings');
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc });
try {
vi.spyOn(pluginsApi, 'oauthConnect').mockResolvedValue({
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import { server } from '../../../tests/helpers/msw/server';
import { locationAt } from '../../../tests/helpers/location';
import { ToastContainer } from '../shared/Toast';
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
import type { PluginAction, PluginUserSettingField } from '../../api/client';
@@ -367,7 +368,7 @@ describe('PluginSettingsTab', () => {
it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => {
const user = userEvent.setup();
const loc = { href: 'http://localhost/settings', origin: 'http://localhost', pathname: '/settings' };
const loc = locationAt('/settings');
vi.stubGlobal('location', loc);
serve('weather', {}, { configured: true, connected: false });
server.use(http.post('/api/plugin-oauth/weather/connect', () =>
+73
View File
@@ -0,0 +1,73 @@
import { renderHook } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { useWritesInOrder } from './useWritesInOrder';
/** A write that only finishes when the test says so, and notes when it starts and ends. */
function heldWrite(log: string[], name: string) {
let finish!: () => void;
let fail!: (err: Error) => void;
const done = new Promise<void>((resolve, reject) => {
finish = resolve;
fail = reject;
});
const write = async () => {
log.push(`${name} start`);
await done;
log.push(`${name} end`);
};
return { write, finish, fail };
}
describe('useWritesInOrder', () => {
it('FE-HOOK-WRITES-001: a write starts only once the one before it has finished', async () => {
const { result } = renderHook(() => useWritesInOrder());
const log: string[] = [];
const first = heldWrite(log, 'first');
const second = heldWrite(log, 'second');
const firstDone = result.current(first.write);
const secondDone = result.current(second.write);
await Promise.resolve();
expect(log).toEqual(['first start']);
second.finish();
first.finish();
await Promise.all([firstDone, secondDone]);
expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);
});
it('FE-HOOK-WRITES-002: a failed write does not hold up the next one, and its caller sees the failure', async () => {
const { result } = renderHook(() => useWritesInOrder());
const log: string[] = [];
const first = heldWrite(log, 'first');
const second = heldWrite(log, 'second');
const firstDone = result.current(first.write);
const secondDone = result.current(second.write);
first.fail(new Error('offline'));
await expect(firstDone).rejects.toThrow('offline');
second.finish();
await secondDone;
expect(log).toEqual(['first start', 'second start', 'second end']);
});
it('FE-HOOK-WRITES-003: the order holds across renders of the component using it', async () => {
const { result, rerender } = renderHook(() => useWritesInOrder());
const log: string[] = [];
const first = heldWrite(log, 'first');
const second = heldWrite(log, 'second');
const firstDone = result.current(first.write);
rerender();
const secondDone = result.current(second.write);
await Promise.resolve();
expect(log).toEqual(['first start']);
first.finish();
second.finish();
await Promise.all([firstDone, secondDone]);
expect(log).toEqual(['first start', 'first end', 'second start', 'second end']);
});
});
+18
View File
@@ -0,0 +1,18 @@
import { useRef } from 'react';
/**
* Runs async writes one after another, in the order they were started.
*
* Two writes to the same record that leave close together, such as a field saved on
* blur and a reset clicked right after it, otherwise race: the server may handle them
* in either order, and whichever it handles last is what stays. A write that fails
* does not hold up the ones queued behind it.
*/
export function useWritesInOrder(): (write: () => Promise<void>) => Promise<void> {
const tail = useRef<Promise<void>>(Promise.resolve());
return (write) => {
const next = tail.current.then(write, write);
tail.current = next;
return next;
};
}
+4 -2
View File
@@ -1535,8 +1535,10 @@ describe('AdminPage', () => {
const matrixCard = matrixHeading.closest<HTMLElement>('section');
// The matrix switch is named after its event and channel; the card's first
// buttons belong to the webhook and ntfy targets above the matrix.
fireEvent.click(within(matrixCard!).getByRole('button', { name: /, email$/i }));
// buttons belong to the webhook and ntfy targets above the matrix. The card's
// heading renders before the matrix fetch lands (a loading row stands in until
// then), so wait for the switch itself.
fireEvent.click(await within(matrixCard!).findByRole('button', { name: /, email$/i }));
await waitFor(() => {
expect(prefUpdateCalled).toBe(true);
+6 -1
View File
@@ -276,7 +276,10 @@ describe('AtlasPage wiring', () => {
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
// The cancel above already closed with null, so wait for the unmark's own close:
// it comes only after the region delete and the country check have both answered.
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledTimes(2));
expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null);
expect(atlas.visitedRegions).toEqual({});
const data = atlas.data as AtlasData;
expect(data.countries.map((c) => c.code)).toEqual(['FR']);
@@ -379,6 +382,8 @@ describe('AtlasPage wiring', () => {
fireEvent.click(screen.getByText('atlas.addToBucket'));
await waitFor(() => expect(body).toMatchObject({ name: 'Bretagne', country_code: 'FR', target_date: null }));
// Let the post answer and the popup close here, not in the next test.
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
});
it('FE-PAGE-ATLASW-018b: a country already wishlisted for that date is not posted again (#1898)', async () => {
+9 -152
View File
@@ -5,7 +5,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server';
import { resetAllStores } from '../../tests/helpers/store';
import { seedJourneyOwner } from '../../tests/helpers/journeyDetail';
import { journeyNow as now, mockJourneyDetail, seedJourneyOwner, setupJourneyHandlers as setupDefaultHandlers } from '../../tests/helpers/journeyDetail';
import { buildUser } from '../../tests/helpers/factories';
import { useJourneyStore } from '../store/journeyStore';
import JourneyDetailPage from './JourneyDetailPage';
@@ -77,157 +77,6 @@ vi.mock('react-router', async () => {
};
});
// ── Mock Data ────────────────────────────────────────────────────────────────
const now = Date.now();
const mockJourneyDetail = {
id: 1,
user_id: 1,
title: 'Italy 2026',
subtitle: 'Rome, Florence, Venice',
status: 'active',
cover_image: null,
cover_gradient: null,
created_at: now,
updated_at: now,
entries: [
{
id: 10,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-15',
title: 'Arrived in Rome',
story: 'Amazing city!',
location_name: 'Rome',
location_lat: 41.9,
location_lng: 12.5,
mood: 'amazing',
weather: 'sunny',
tags: ['culture'],
pros_cons: { pros: ['Great food'], cons: ['Crowded'] },
visibility: 'private',
sort_order: 0,
entry_time: '10:00',
photos: [
{
id: 100,
entry_id: 10,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: now,
},
],
created_at: now,
updated_at: now,
},
{
id: 11,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-16',
title: 'Florence Day',
story: null,
location_name: 'Florence',
location_lat: 43.77,
location_lng: 11.25,
mood: 'good',
weather: 'cloudy',
tags: [],
pros_cons: null,
visibility: 'private',
sort_order: 0,
entry_time: null,
photos: [],
created_at: now,
updated_at: now,
},
],
trips: [
{
trip_id: 5,
added_at: now,
title: 'Italy Trip',
start_date: '2026-03-14',
end_date: '2026-03-20',
cover_image: null,
currency: 'EUR',
place_count: 8,
},
],
contributors: [
{
journey_id: 1,
user_id: 1,
role: 'owner',
added_at: now,
username: 'testuser',
avatar: null,
},
],
stats: { entries: 2, photos: 1, places: 2 },
gallery: [
{
id: 100,
journey_id: 1,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: now,
},
],
};
// ── MSW Handlers ─────────────────────────────────────────────────────────────
function setupDefaultHandlers(journeyOverride?: Record<string, unknown>) {
const journey = journeyOverride
? { ...mockJourneyDetail, ...journeyOverride }
: mockJourneyDetail;
server.use(
http.get('/api/journeys/1', () => {
return HttpResponse.json(journey);
}),
http.get('/api/addons', () => {
return HttpResponse.json({
addons: [
{ id: 'journey', name: 'Journey', type: 'feature', icon: 'book', enabled: true },
{ id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true },
],
});
}),
http.get('/api/integrations/memories/:provider/status', () => {
return HttpResponse.json({ connected: false });
}),
http.patch('/api/journeys/1', () => {
return HttpResponse.json({ ...mockJourneyDetail, title: 'Updated' });
}),
http.get('/api/journeys/1/share-link', () => {
return HttpResponse.json({ link: null });
}),
);
}
// ── Setup ────────────────────────────────────────────────────────────────────
const ownerUser = buildUser({ id: 1, username: 'testuser' });
@@ -3805,8 +3654,13 @@ describe('JourneyDetailPage', () => {
let createCalls = 0;
let updateCalls = 0;
let providerCalls = 0;
let journeyReads = 0;
server.use(
http.get('/api/journeys/1', () => {
journeyReads++;
return HttpResponse.json(mockJourneyDetail);
}),
http.get('/api/integrations/memories/:provider/status', () => HttpResponse.json({ connected: true })),
http.post('/api/integrations/memories/:provider/search', () => HttpResponse.json({
assets: [{ id: 'context-1', takenAt: '2026-03-15T12:00:00Z', city: 'Rome' }],
@@ -3851,10 +3705,13 @@ describe('JourneyDetailPage', () => {
expect(createCalls).toBe(1);
expect(screen.getByText('New Entry')).toBeInTheDocument();
const readsBeforeRetry = journeyReads;
await user.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(providerCalls).toBe(2));
expect(createCalls).toBe(1);
expect(updateCalls).toBe(1);
// The photos landed and the journal reloads; let that read answer here, not after the test.
await waitFor(() => expect(journeyReads).toBeGreaterThan(readsBeforeRetry));
});
});
@@ -5,6 +5,7 @@ import React from 'react';
import { MemoryRouter } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAppConfig } from '../../../tests/helpers/factories';
import { locationAt, pageUrl } from '../../../tests/helpers/location';
import { server } from '../../../tests/helpers/msw/server';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
@@ -54,7 +55,7 @@ beforeEach(() => {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search: '' },
value: locationAt('/login'),
});
});
@@ -78,7 +79,7 @@ describe('useLogin in the native app', () => {
);
const { result } = renderLogin();
await waitFor(() => expect(result.current.appConfig).not.toBeNull());
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
expect(result.current.oidcOnly).toBe(true);
});
+17 -10
View File
@@ -7,6 +7,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store';
import { buildAppConfig } from '../../../tests/helpers/factories';
import { locationAt, pageUrl } from '../../../tests/helpers/location';
import { markSignedOut, clearSignedOut, wasSignedOut } from '../../utils/signedOut';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore, type LoginResult } from '../../store/authStore';
@@ -54,7 +55,7 @@ function setSearch(search: string) {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search },
value: locationAt(`/login${search}`),
});
}
@@ -196,7 +197,7 @@ describe('useLogin — app config probe', () => {
await ready(result);
expect(result.current.noRedirect).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-009: never auto-redirects on a cached config', async () => {
@@ -210,7 +211,7 @@ describe('useLogin — app config probe', () => {
await ready(result);
expect(result.current.oidcOnly).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
});
@@ -1183,13 +1184,13 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
await waitFor(() => expect(result.current.redirectScreen).toBe(false));
expect(result.current.configWait).toBe(false);
expect(result.current.oidcOnly).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-208: a redirect that stalls offers the way on by hand after eight seconds', () => {
it('FE-LOGIN-HOOK-208: a redirect that stalls offers the way on by hand after eight seconds', async () => {
vi.useFakeTimers();
localStorage.setItem(CONFIG_CACHE_KEY, JSON.stringify(oidcOnlyConfig()));
heldConfig(oidcOnlyConfig());
const release = heldConfig(oidcOnlyConfig());
const { result } = renderLogin();
expect(result.current.redirectScreen).toBe(true);
@@ -1197,6 +1198,12 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.idpSlow).toBe(false);
act(() => { vi.advanceTimersByTime(1); });
expect(result.current.idpSlow).toBe(true);
// The probe answers in the end and the redirect goes ahead, here and not in
// the next test.
vi.useRealTimers();
release();
await waitFor(() => expect(window.location.href).toBe('/api/auth/oidc/login?remember=1'));
});
it('FE-LOGIN-HOOK-209: a failed sign-in at the IdP shows the OIDC-only screen and its error, without going back', async () => {
@@ -1209,7 +1216,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.configWait).toBe(false);
expect(result.current.redirectScreen).toBe(false);
expect(result.current.error).not.toBe('');
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login?oidc_error=token_failed'));
});
it('FE-LOGIN-HOOK-215: with the auto redirect turned off the page stays, with its SSO button (#2925)', async () => {
@@ -1222,7 +1229,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
expect(result.current.oidcOnly).toBe(true);
expect(result.current.redirectScreen).toBe(false);
expect(result.current.configWait).toBe(false);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-216: a cached config with the auto redirect off announces no redirect while the probe is out', async () => {
@@ -1237,7 +1244,7 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
release();
await ready(result);
expect(result.current.redirectScreen).toBe(false);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-LOGIN-HOOK-217: a server from before the switch, with no field, keeps the redirect', async () => {
@@ -1259,6 +1266,6 @@ describe('useLogin — the wait before the sign-in is known (#1167)', () => {
release();
await ready(result);
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
});
@@ -2,6 +2,7 @@
import React from 'react';
import { MemoryRouter } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { locationAt } from '../../../tests/helpers/location';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import { rememberHandoffReturn, requestHandoffCode, signInWithPasskey } from '../../native/browserSignIn';
@@ -28,7 +29,7 @@ function setSearch(search: string) {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { ...realLocation, search, href: 'http://localhost/native-handoff' + search, replace: vi.fn() },
value: locationAt(`/native-handoff${search}`, { replace: vi.fn() }),
});
}
+3 -3
View File
@@ -23,11 +23,11 @@ async function prune(): Promise<void> {
* anything this store cannot read or write is simply routed again.
*/
export const routeCacheRepo = {
/** The route kept under `key`, unless it is missing or too old. */
async get<T>(key: string): Promise<T | null> {
/** The route kept under `key`, unless it is missing or older than `maxAgeMs`. */
async get<T>(key: string, maxAgeMs = MAX_AGE_MS): Promise<T | null> {
try {
const row = await offlineDb.routeCache.get(key);
if (!row || Date.now() - row.savedAt > MAX_AGE_MS) return null;
if (!row || Date.now() - row.savedAt > maxAgeMs) return null;
return row.route as T;
} catch {
// A closed or blocked database: the leg is routed again.
+7
View File
@@ -160,6 +160,13 @@ describe('helpStore: search', () => {
})
describe('helpStore: doc index', () => {
// Loading the index has no debounce, so these tests await the response directly.
// msw no longer runs its own timers outside fake ones, and a successful mocked
// response only arrives once a timer fires, so these tests run on real timers.
beforeEach(() => {
vi.useRealTimers()
})
it('loads the table of contents once and resolves titles from it', async () => {
let calls = 0
server.use(
+9 -7
View File
@@ -1,4 +1,5 @@
import { isChunkLoadError, reloadOnceForChunk, clearChunkReloadMarker, reloadFresh, importChunk, FRESH_LOAD_PARAM } from './chunkReload';
import { locationAt, pageUrl } from '../../tests/helpers/location';
const net = vi.hoisted(() => ({
probeNow: vi.fn(async () => 'online' as 'online' | 'offline' | 'proxy-wall'),
@@ -38,11 +39,11 @@ describe('isChunkLoadError', () => {
* A recovery reload is a location.replace onto a fresh URL (reloadFresh), so the
* stub records the replace. `plain` is the location.reload() it must not use.
*/
function stubLocation(href = 'http://localhost/trips/4?tab=plan#day-2') {
function stubLocation(path = '/trips/4?tab=plan#day-2', overrides: Partial<Location> = {}) {
const reload = vi.fn();
const plain = vi.fn();
Object.defineProperty(window, 'location', {
value: { ...window.location, href, replace: reload, reload: plain },
value: locationAt(path, { replace: reload, reload: plain, ...overrides }),
writable: true,
});
return { reload, plain };
@@ -56,7 +57,8 @@ describe('reloadFresh', () => {
expect(plain).not.toHaveBeenCalled();
expect(reload).toHaveBeenCalledTimes(1);
const target = new URL(reload.mock.calls[0][0] as string);
// Path, query and hash stay, so the app comes back where it was.
// Origin, path, query and hash stay, so the app comes back where it was.
expect(target.origin).toBe(new URL(pageUrl('/')).origin);
expect(target.pathname).toBe('/trips/4');
expect(target.searchParams.get('tab')).toBe('plan');
expect(target.hash).toBe('#day-2');
@@ -64,7 +66,7 @@ describe('reloadFresh', () => {
});
it('FE-UTIL-CHUNK-016: two reloads never share a URL', () => {
const { reload } = stubLocation('http://localhost/dashboard');
const { reload } = stubLocation('/dashboard');
const now = vi.spyOn(Date, 'now').mockReturnValue(1790358416100);
reloadFresh();
now.mockReturnValue(1790358416101);
@@ -73,7 +75,7 @@ describe('reloadFresh', () => {
});
it('FE-UTIL-CHUNK-017: falls back to a plain reload when the URL cannot be built', () => {
const { reload, plain } = stubLocation('not a url');
const { reload, plain } = stubLocation('/', { href: 'not a url' });
reloadFresh();
expect(reload).not.toHaveBeenCalled();
expect(plain).toHaveBeenCalledTimes(1);
@@ -145,7 +147,7 @@ describe('reloadOntoCurrentBuild', () => {
const deleted: string[] = [];
Object.defineProperty(globalThis, 'caches', {
value: {
keys: vi.fn(async () => ['workbox-precache-v2-http://localhost/', 'map-tiles']),
keys: vi.fn(async () => [`workbox-precache-v2-${pageUrl('/')}`, 'map-tiles']),
delete: vi.fn(async (name: string) => { deleted.push(name); return true; }),
},
configurable: true,
@@ -191,7 +193,7 @@ describe('reloadOntoCurrentBuild', () => {
// Not before the shell is gone: the reload would come back to the same error.
expect(reload).not.toHaveBeenCalled();
await vi.waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
expect(deleted).toEqual(['workbox-precache-v2-http://localhost/']);
expect(deleted).toEqual([`workbox-precache-v2-${pageUrl('/')}`]);
expect(registration.unregister).toHaveBeenCalledTimes(1);
});
+60 -15
View File
@@ -39,13 +39,51 @@ function triggerAnchorDownload(blobUrl: string, filename?: string): void {
setTimeout(() => { URL.revokeObjectURL(blobUrl); a.remove() }, 100)
}
// How long a live download may take before a copy stored for offline use is
// served instead. Without a stored copy the live download keeps going as long
// as it takes, since there is nothing better to show.
const STORED_COPY_WAIT_MS = 5000
// A network failure (the request or the body read rejected) serves the stored
// copy when there is one. After our own abort the stored copy is already being
// served, so the error only has to end this read.
async function storedCopyOr(url: string, err: unknown, signal: AbortSignal): Promise<Blob> {
if (signal.aborted) throw err
const cached = await getCachedBlob(url)
if (cached) return cached
throw err
}
async function readLive(url: string, signal: AbortSignal): Promise<Blob> {
let resp: Response
try {
resp = await fetch(url, { credentials: 'include', signal })
} catch (err) {
// Genuine network failure: the fetch itself rejected (offline, or a flaky
// link even though navigator.onLine is true). Serve the pre-downloaded copy.
return storedCopyOr(url, err, signal)
}
// The server answered: a non-ok status (401/403/404/…) is a real error and must
// surface, not be masked by a stale cached copy.
if (!resp.ok) throw new Error(resp.status === 401 ? 'Unauthorized' : `HTTP ${resp.status}`)
try {
return await resp.blob()
} catch (err) {
// The connection broke while the body was still arriving.
return storedCopyOr(url, err, signal)
}
}
/**
* Resolves a protected file to a Blob, preferring the live server but falling
* back to the offline cache (pre-downloaded by the trip sync manager). This is
* what lets attachments open in a PWA / airplane mode. When offline we go
* straight to the cache; when online we fetch live and only fall back if the
* network actually fails — which also covers flaky links where navigator.onLine
* still reports true ("sometimes it works, sometimes it doesn't").
* straight to the cache; when online we fetch live and fall back if the
* network fails, which also covers flaky links where navigator.onLine still
* reports true ("sometimes it works, sometimes it doesn't"). A stalled link
* never rejects, so once the live download has run for STORED_COPY_WAIT_MS the
* stored copy, if there is one, is served and the download aborted. The cache
* is only read then, so a quick HTTP error still surfaces on its own.
*/
async function getFileBlob(url: string): Promise<Blob> {
assertRelativeUrl(url)
@@ -54,20 +92,27 @@ async function getFileBlob(url: string): Promise<Blob> {
if (cached) return cached
throw new Error('File not available offline')
}
let resp: Response
// A controller and a timer rather than AbortSignal.timeout, which Safari only
// has from 16 on.
const live = new AbortController()
let settled = false
let timer: ReturnType<typeof setTimeout> | undefined
const storedAfterWait = new Promise<Blob>((resolve) => {
timer = setTimeout(() => {
void getCachedBlob(url).then((cached) => {
// Nothing stored: keep waiting on the live download, as before.
if (!cached || settled) return
resolve(cached)
live.abort()
})
}, STORED_COPY_WAIT_MS)
})
try {
resp = await fetch(url, { credentials: 'include' })
} catch (err) {
// Genuine network failure — the fetch itself rejected (offline, or a flaky
// link even though navigator.onLine is true). Serve the pre-downloaded copy.
const cached = await getCachedBlob(url)
if (cached) return cached
throw err
return await Promise.race([readLive(url, live.signal), storedAfterWait])
} finally {
settled = true
clearTimeout(timer)
}
// The server answered: a non-ok status (401/403/404/…) is a real error and must
// surface, not be masked by a stale cached copy.
if (!resp.ok) throw new Error(resp.status === 401 ? 'Unauthorized' : `HTTP ${resp.status}`)
return await resp.blob()
}
/**
+7 -6
View File
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import { locationAt } from '../../tests/helpers/location'
/*
* reconcileAppVersion notes the worker that served the page when its module
@@ -75,17 +76,17 @@ function breakStorage(method: 'getItem' | 'setItem', broken: () => Storage) {
const marker = () => localStorage.getItem('trek_app_version')
// The version the bundle under test is built as (vite define, from package.json).
const BUILT = __TREK_UI_VERSION__
let reload: ReturnType<typeof vi.fn>
let plainReload: ReturnType<typeof vi.fn>
let reload: Mock<Location['replace']>
let plainReload: Mock<Location['reload']>
beforeEach(() => {
// Every reload here asks for the page under a fresh URL (reloadFresh), which is
// a location.replace. `plainReload` is the location.reload() it must not use.
reload = vi.fn()
plainReload = vi.fn()
reload = vi.fn<Location['replace']>()
plainReload = vi.fn<Location['reload']>()
Object.defineProperty(window, 'location', {
writable: true,
value: { ...window.location, href: 'http://localhost/dashboard', replace: reload, reload: plainReload },
value: locationAt('/dashboard', { replace: reload, reload: plainReload }),
})
})
+44
View File
@@ -0,0 +1,44 @@
import { http, HttpResponse } from 'msw';
import { vi } from 'vitest';
import { useAuthStore } from '../../src/store/authStore';
import { useSettingsStore } from '../../src/store/settingsStore';
import { useTripStore } from '../../src/store/tripStore';
import type { Settings } from '../../src/types';
import { buildAdmin, buildDay, buildTrip } from './factories';
import { server } from './msw/server';
import { resetAllStores, seedStore } from './store';
/** The day the day panel suites open. */
export const dayDetailDay = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
/** The panel's props for that day, with nothing planned on it. */
export const dayDetailProps = {
day: dayDetailDay,
days: [dayDetailDay],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
/**
* Fresh stores for each day panel test: an admin on trip 1, the forecast and the stays
* answering empty, and the given settings when the suite wants them before rendering.
*/
export function resetDayDetailPanel(settings?: Partial<Settings>): void {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
if (settings) seedStore(useSettingsStore, { settings });
}
+150
View File
@@ -1,7 +1,9 @@
import { http, HttpResponse } from 'msw';
import { useAddonStore } from '../../src/store/addonStore';
import { useAuthStore } from '../../src/store/authStore';
import { usePermissionsStore } from '../../src/store/permissionsStore';
import type { User } from '../../src/types';
import { server } from './msw/server';
import { seedStore } from './store';
/**
@@ -15,3 +17,151 @@ export function seedJourneyOwner(user: User): void {
addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', enabled: true } as never],
});
}
/** When the suite's journal was made; its entries and photos are dated by it. */
export const journeyNow = Date.now();
/** The journal the page suite opens: an owner's active trip journal with entries, photos and a synced trip. */
export const mockJourneyDetail = {
id: 1,
user_id: 1,
title: 'Italy 2026',
subtitle: 'Rome, Florence, Venice',
status: 'active',
cover_image: null,
cover_gradient: null,
created_at: journeyNow,
updated_at: journeyNow,
entries: [
{
id: 10,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-15',
title: 'Arrived in Rome',
story: 'Amazing city!',
location_name: 'Rome',
location_lat: 41.9,
location_lng: 12.5,
mood: 'amazing',
weather: 'sunny',
tags: ['culture'],
pros_cons: { pros: ['Great food'], cons: ['Crowded'] },
visibility: 'private',
sort_order: 0,
entry_time: '10:00',
photos: [
{
id: 100,
entry_id: 10,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: journeyNow,
},
],
created_at: journeyNow,
updated_at: journeyNow,
},
{
id: 11,
journey_id: 1,
author_id: 1,
type: 'entry',
entry_date: '2026-03-16',
title: 'Florence Day',
story: null,
location_name: 'Florence',
location_lat: 43.77,
location_lng: 11.25,
mood: 'good',
weather: 'cloudy',
tags: [],
pros_cons: null,
visibility: 'private',
sort_order: 0,
entry_time: null,
photos: [],
created_at: journeyNow,
updated_at: journeyNow,
},
],
trips: [
{
trip_id: 5,
added_at: journeyNow,
title: 'Italy Trip',
start_date: '2026-03-14',
end_date: '2026-03-20',
cover_image: null,
currency: 'EUR',
place_count: 8,
},
],
contributors: [
{
journey_id: 1,
user_id: 1,
role: 'owner',
added_at: journeyNow,
username: 'testuser',
avatar: null,
},
],
stats: { entries: 2, photos: 1, places: 2 },
gallery: [
{
id: 100,
journey_id: 1,
photo_id: 100,
provider: 'local',
file_path: 'photos/test.jpg',
asset_id: null,
owner_id: null,
thumbnail_path: null,
caption: 'Colosseum',
sort_order: 0,
width: 800,
height: 600,
shared: 1,
created_at: journeyNow,
},
],
};
/** The journal's own reads and writes, answered with that journal (merged with `journeyOverride`). */
export function setupJourneyHandlers(journeyOverride?: Record<string, unknown>) {
const journey = journeyOverride ? { ...mockJourneyDetail, ...journeyOverride } : mockJourneyDetail;
server.use(
http.get('/api/journeys/1', () => {
return HttpResponse.json(journey);
}),
http.get('/api/addons', () => {
return HttpResponse.json({
addons: [
{ id: 'journey', name: 'Journey', type: 'feature', icon: 'book', enabled: true },
{ id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true },
],
});
}),
http.get('/api/integrations/memories/:provider/status', () => {
return HttpResponse.json({ connected: false });
}),
http.patch('/api/journeys/1', () => {
return HttpResponse.json({ ...mockJourneyDetail, title: 'Updated' });
}),
http.get('/api/journeys/1/share-link', () => {
return HttpResponse.json({ link: null });
})
);
}
+35
View File
@@ -0,0 +1,35 @@
// The page's own location, taken when this module loads, before any test
// replaces window.location with a stand-in.
const pageLocation = window.location;
const pageOrigin = new URL(document.baseURI).origin;
/** `path` as an absolute URL on the page's own origin, for asserting on location.href. */
export function pageUrl(path: string): string {
return new URL(path, pageOrigin).href;
}
/**
* A stand-in for window.location that shows `path` on the page's own origin.
*
* Requests have to stay on one origin for the HTTP mocks to answer them: msw
* resolves its relative handlers, and its fetch interceptor a relative URL,
* against location.href, while jsdom's XHR resolves against the document. A
* stand-in on another origin (`http://localhost/` while the page runs on
* `http://localhost:3000`) sends every request past its handler.
*/
export function locationAt(path: string, overrides: Partial<Location> = {}): Location {
const url = new URL(path, pageOrigin);
return {
...pageLocation,
href: url.href,
origin: url.origin,
protocol: url.protocol,
host: url.host,
hostname: url.hostname,
port: url.port,
pathname: url.pathname,
search: url.search,
hash: url.hash,
...overrides,
};
}
+27 -19
View File
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { http, HttpResponse } from 'msw';
import { server } from '../../helpers/msw/server';
import { buildUser } from '../../helpers/factories';
import { locationAt, pageUrl } from '../../helpers/location';
// The global setup.ts mocks websocket with getSocketId returning null.
// We need to be able to control what getSocketId returns per-test.
@@ -59,7 +60,7 @@ describe('API client interceptors', () => {
// Reset window.location to a neutral path
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/', pathname: '/', search: '', hash: '' },
value: locationAt('/'),
});
});
@@ -97,7 +98,7 @@ describe('API client interceptors', () => {
it('FE-API-003: 401 with AUTH_REQUIRED → redirects to /login with redirect param', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/', pathname: '/dashboard', search: '', hash: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -118,7 +119,7 @@ describe('API client interceptors', () => {
it('FE-API-003b: 401 without AUTH_REQUIRED code does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
const originalHref = window.location.href;
@@ -141,7 +142,7 @@ describe('API client interceptors', () => {
it('FE-API-003c: 401 on /login page does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/login', pathname: '/login', search: '' },
value: locationAt('/login'),
});
server.use(
@@ -157,13 +158,13 @@ describe('API client interceptors', () => {
}
// href should NOT have been changed to /login?redirect=...
expect(window.location.href).toBe('http://localhost/login');
expect(window.location.href).toBe(pageUrl('/login'));
});
it('FE-API-004: 403 with MFA_REQUIRED → redirects to /settings?mfa=required', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -184,7 +185,7 @@ describe('API client interceptors', () => {
it('FE-API-004b: 403 with MFA_REQUIRED on /settings page does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/settings', pathname: '/settings', search: '' },
value: locationAt('/settings'),
});
server.use(
@@ -200,7 +201,7 @@ describe('API client interceptors', () => {
}
// Should NOT redirect when already on /settings
expect(window.location.href).toBe('http://localhost/settings');
expect(window.location.href).toBe(pageUrl('/settings'));
});
it('FE-API-005: successful API call returns response data', async () => {
@@ -253,7 +254,7 @@ describe('API client interceptors', () => {
it('FE-API-008: 401 AUTH_REQUIRED on /register path does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/register', pathname: '/register', search: '' },
value: locationAt('/register'),
});
server.use(
@@ -264,13 +265,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/register');
expect(window.location.href).toBe(pageUrl('/register'));
});
it('FE-API-009: 401 AUTH_REQUIRED on /shared/:token path does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/shared/abc123', pathname: '/shared/abc123', search: '' },
value: locationAt('/shared/abc123'),
});
server.use(
@@ -281,13 +282,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/shared/abc123');
expect(window.location.href).toBe(pageUrl('/shared/abc123'));
});
it('FE-API-010: 401 AUTH_REQUIRED still rejects the promise even when redirect fires', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -304,7 +305,7 @@ describe('API client interceptors', () => {
it('FE-API-011: 403 without MFA_REQUIRED code does not redirect', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -315,13 +316,13 @@ describe('API client interceptors', () => {
try { await authApi.me(); } catch { /* expected */ }
expect(window.location.href).toBe('http://localhost/dashboard');
expect(window.location.href).toBe(pageUrl('/dashboard'));
});
it('FE-API-012: 403 MFA_REQUIRED still rejects the promise after redirect fires', async () => {
Object.defineProperty(window, 'location', {
writable: true,
value: { href: 'http://localhost/dashboard', pathname: '/dashboard', search: '' },
value: locationAt('/dashboard'),
});
server.use(
@@ -962,11 +963,13 @@ describe('mapsApi', () => {
it('FE-MAPS-004: mapsApi.autocomplete rejects when AbortSignal is aborted', async () => {
const controller = new AbortController();
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use(
http.post('/api/maps/autocomplete', async () => {
// Never resolves — request will be aborted
await new Promise(() => {});
// Held until the request has been aborted
await gate;
return HttpResponse.json({ suggestions: [] });
})
);
@@ -974,6 +977,11 @@ describe('mapsApi', () => {
const promise = mapsApi.autocomplete('Paris', undefined, undefined, controller.signal);
controller.abort();
await expect(promise).rejects.toThrow();
try {
await expect(promise).rejects.toThrow();
} finally {
// Let the held handler finish here, not in whatever runs after this test.
release();
}
});
});
+6 -3
View File
@@ -26,10 +26,13 @@ vi.mock('../src/api/websocket', () => ({
// lets it through, so the runner really talks to frankfurter or a tile server and settles
// a promise after the test environment is gone (see handlers/external.ts). Those fail now.
// An unhandled same-origin call stays a warning: that is a missing handler, not egress.
// Only HTTP frames are judged, as before msw 3 reported every network frame here.
beforeAll(() => server.listen({
onUnhandledRequest: (request, print) => {
if (new URL(request.url).origin === location.origin) print.warning();
else print.error();
onUnhandledFrame: ({ frame, defaults }) => {
if (frame.protocol !== 'http') return;
const { request } = frame.data as { request: Request };
if (new URL(request.url).origin === location.origin) defaults.warn();
else defaults.error();
},
}));
afterEach(() => {
@@ -442,6 +442,9 @@ describe('MSettingsPlugins', () => {
expect(frame).toHaveAttribute('data-plugin', 'p1');
expect(frame).toHaveAttribute('data-path', 'settings.html');
expect(frame).toHaveAttribute('data-title', 'Weather Pro');
// The framed card renders at once, the declared-field form only once its
// settings request answered; wait for that form before counting the cards.
await screen.findByPlaceholderText('https://api.example');
// Declared-field form and framed surface are two separate cards
expect(screen.getAllByText('Weather Pro')).toHaveLength(2);
});
@@ -266,7 +266,9 @@ describe('MCollabChat', () => {
expect(send).toBeEnabled()
fireEvent.click(send)
expect(await screen.findByText('Landed safely')).toBeInTheDocument()
// React mirrors the draft into the textarea's text, so the composer itself
// matches the trimmed text; wait for the appended bubble, not the draft.
expect(await screen.findByText('Landed safely', { ignore: 'script, style, textarea' })).toBeInTheDocument()
expect(sentBodies).toEqual([{ text: 'Landed safely' }])
expect(input).toHaveValue('')
})
@@ -1,21 +1,39 @@
// FE-MOB-MVACINV-001 to FE-MOB-MVACINV-010
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, vi, type MockInstance } from 'vitest';
import { http, HttpResponse } from 'msw';
import { render, screen, fireEvent, waitFor, within } from '../../../helpers/render';
import { render, screen, fireEvent, waitFor, within, act } from '../../../helpers/render';
import { server } from '../../../helpers/msw/server';
import { resetAllStores } from '../../../helpers/store';
import { useVacayStore } from '../../../../src/store/vacayStore';
import apiClient from '../../../../src/api/client';
import MVacayInviteSheet from '../../../../src/mobile/screens/vacay/MVacayInviteSheet';
const toasts: { type: string; message: string }[] = [];
const USERS_ENDPOINT = '/addons/vacay/available-users';
let getSpy: MockInstance<typeof apiClient.get>;
function availableUsers(users: { id: number; username: string; color: string | null }[]) {
server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ users })));
}
/**
* Waits until the sheet has asked for the invitable users `lookups` times and
* every answer has come back and been applied. The answer is not on screen when
* it changes nothing (an empty list, the same list on a reload), and a lookup
* still out when the test ends would land in the next one.
*/
async function usersSettled(lookups: number) {
const calls = () => getSpy.mock.calls.flatMap(([url], i) => (url === USERS_ENDPOINT ? [getSpy.mock.results[i].value] : []));
await waitFor(() => expect(calls()).toHaveLength(lookups));
await act(async () => {
await Promise.allSettled(calls());
});
}
beforeEach(() => {
resetAllStores();
getSpy = vi.spyOn(apiClient, 'get');
toasts.length = 0;
window.__addToast = ((message: string, type?: string) => {
toasts.push({ type: type ?? 'info', message });
@@ -28,6 +46,7 @@ beforeEach(() => {
});
afterEach(() => {
getSpy.mockRestore();
delete window.__addToast;
});
@@ -54,6 +73,7 @@ describe('MVacayInviteSheet', () => {
it('FE-MOB-MVACINV-003: falls back to the empty state when the lookup fails', async () => {
server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
renderSheet();
await usersSettled(1);
expect(await screen.findByText('No users available')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Select user' })).not.toBeInTheDocument();
@@ -74,7 +94,9 @@ describe('MVacayInviteSheet', () => {
const send = await screen.findByRole('button', { name: 'Send Invite' });
expect(send).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'Select user' }));
// The picker shows up once the users are in; nobody is picked yet.
fireEvent.click(await screen.findByRole('button', { name: 'Select user' }));
expect(screen.getByRole('button', { name: 'Send Invite' })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'bob' }));
expect(screen.getByRole('button', { name: 'Send Invite' })).toBeEnabled();
});
@@ -122,6 +144,7 @@ describe('MVacayInviteSheet', () => {
fireEvent.click(within(row).getByRole('button', { name: 'Cancel' }));
expect(cancelInvite).toHaveBeenCalledWith(9);
await usersSettled(1);
});
it('FE-MOB-MVACINV-009: the close icon and the cancel button both dismiss the sheet', async () => {
@@ -131,6 +154,7 @@ describe('MVacayInviteSheet', () => {
const dialog = screen.getByRole('dialog', { name: 'Invite User' });
fireEvent.click(within(dialog).getAllByRole('button', { name: 'Cancel' })[0]);
expect(onClose).toHaveBeenCalledTimes(2);
await usersSettled(1);
});
it('FE-MOB-MVACINV-010: reopening resets the previous selection', async () => {
@@ -141,6 +165,7 @@ describe('MVacayInviteSheet', () => {
rerender(<MVacayInviteSheet open={false} onClose={() => {}} />);
rerender(<MVacayInviteSheet open onClose={() => {}} />);
await usersSettled(2);
expect(await screen.findByRole('button', { name: 'Select user' })).toBeInTheDocument();
});
+16 -1
View File
@@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest';
import { directionOf, pickLocale, translator } from '../../../native-shell/i18n';
// FE-NATIVE-SHELL-001 to FE-NATIVE-SHELL-006
// FE-NATIVE-SHELL-001 to FE-NATIVE-SHELL-007
//
// The app's own first screens (client/native-shell): which language and reading
// direction they start in, and the layout rules in shell.css that no component
@@ -97,4 +97,19 @@ describe('native shell', () => {
/margin-left|margin-right|padding-left|padding-right|text-align:\s*left|[^-]left:\s|[^-]right:\s/
);
});
it("FE-NATIVE-SHELL-007: every edge clears the system bars from Android's injected insets too, and the foot keeps clear of the navigation bar", () => {
const root = find(':root')
.map((r) => r.body)
.join('');
const side = (name: string, edge: string) =>
new RegExp(
`--${name}:\\s*max\\(\\s*env\\(safe-area-inset-${edge}, 0px\\),\\s*var\\(--safe-area-inset-${edge}, 0px\\),\\s*var\\(--trek-native-safe-${edge}, 0px\\)\\s*\\)`
);
expect(root).toMatch(side('safe-top', 'top'));
expect(root).toMatch(side('safe-bottom', 'bottom'));
expect(root).toMatch(side('safe-start', 'left'));
expect(root).toMatch(side('safe-end', 'right'));
expect(find('.dock')[0]?.body).toMatch(/padding-block:[^;]*var\(--safe-bottom\)/);
});
});
+264 -134
View File
@@ -1,225 +1,355 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { downloadFile, openFile } from '../../../src/utils/fileDownload'
import { getCachedBlob } from '../../../src/db/offlineDb'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getCachedBlob } from '../../../src/db/offlineDb';
import { downloadFile, openFile } from '../../../src/utils/fileDownload';
// Mock the offline DB so these tests never touch Dexie/IndexedDB.
vi.mock('../../../src/db/offlineDb', () => ({ getCachedBlob: vi.fn() }))
vi.mock('../../../src/db/offlineDb', () => ({ getCachedBlob: vi.fn() }));
function makeFetchMock(status: number, blob: Blob = new Blob(['data'], { type: 'application/pdf' })) {
return vi.fn().mockResolvedValue({
status,
ok: status >= 200 && status < 300,
blob: () => Promise.resolve(blob),
})
});
}
beforeEach(() => {
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock-url')
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
vi.spyOn(document.body, 'appendChild').mockImplementation((el) => el)
vi.spyOn(document.body, 'removeChild').mockImplementation((el) => el)
vi.useFakeTimers()
})
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock-url');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
vi.spyOn(document.body, 'appendChild').mockImplementation((el) => el);
vi.spyOn(document.body, 'removeChild').mockImplementation((el) => el);
vi.useFakeTimers();
});
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})
vi.restoreAllMocks();
vi.useRealTimers();
});
describe('assertRelativeUrl (URL guard)', () => {
it('rejects absolute http URLs', async () => {
await expect(downloadFile('https://evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL')
})
await expect(downloadFile('https://evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL');
});
it('rejects protocol-relative URLs', async () => {
await expect(downloadFile('//evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL')
})
await expect(downloadFile('//evil.com/x')).rejects.toThrow('Refusing to fetch non-relative URL');
});
it('allows relative paths', async () => {
vi.stubGlobal('fetch', makeFetchMock(200))
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
await expect(downloadFile('/trips/1/files/2/download')).resolves.toBeUndefined()
})
})
vi.stubGlobal('fetch', makeFetchMock(200));
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await expect(downloadFile('/trips/1/files/2/download')).resolves.toBeUndefined();
});
});
describe('downloadFile', () => {
it('fetches with credentials:include and triggers anchor download', async () => {
const fetchMock = makeFetchMock(200)
vi.stubGlobal('fetch', fetchMock)
const fetchMock = makeFetchMock(200);
vi.stubGlobal('fetch', fetchMock);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/test.pdf', 'test.pdf')
await downloadFile('/uploads/files/test.pdf', 'test.pdf');
expect(fetchMock).toHaveBeenCalledWith('/uploads/files/test.pdf', { credentials: 'include' })
expect(URL.createObjectURL).toHaveBeenCalled()
expect(clickSpy).toHaveBeenCalled()
expect(fetchMock).toHaveBeenCalledWith('/uploads/files/test.pdf', {
credentials: 'include',
signal: expect.any(AbortSignal),
});
expect(URL.createObjectURL).toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalled();
// Revoke happens after setTimeout(100)
vi.runAllTimers()
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url')
})
vi.runAllTimers();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url');
});
it('sets download attribute to filename when provided', async () => {
vi.stubGlobal('fetch', makeFetchMock(200))
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
vi.stubGlobal('fetch', makeFetchMock(200));
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/report.pdf', 'report.pdf')
await downloadFile('/uploads/files/report.pdf', 'report.pdf');
// Check anchor was created with download attribute
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement
expect(anchor.download).toBe('report.pdf')
})
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.download).toBe('report.pdf');
});
it('throws on 401 response', async () => {
vi.stubGlobal('fetch', makeFetchMock(401))
await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized')
expect(URL.createObjectURL).not.toHaveBeenCalled()
})
})
vi.stubGlobal('fetch', makeFetchMock(401));
await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized');
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
});
describe('openFile', () => {
it('fetches with credentials:include and opens blob URL via target=_blank anchor', async () => {
vi.stubGlobal('fetch', makeFetchMock(200))
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
vi.stubGlobal('fetch', makeFetchMock(200));
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/doc.pdf')
await openFile('/uploads/files/doc.pdf');
expect(window.fetch).toHaveBeenCalledWith('/uploads/files/doc.pdf', { credentials: 'include' })
expect(URL.createObjectURL).toHaveBeenCalled()
expect(window.fetch).toHaveBeenCalledWith('/uploads/files/doc.pdf', {
credentials: 'include',
signal: expect.any(AbortSignal),
});
expect(URL.createObjectURL).toHaveBeenCalled();
// Must NOT call window.open — that path returns null when noreferrer is
// set, which previously caused the file to also open in the current tab.
expect(openSpy).not.toHaveBeenCalled()
expect(clickSpy).toHaveBeenCalledTimes(1)
expect(openSpy).not.toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalledTimes(1);
// The anchor used to open the new tab must be target=_blank, must NOT
// carry a `download` attribute (otherwise it would download in-page
// instead of opening), and must use rel=noopener noreferrer.
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement
expect(anchor.target).toBe('_blank')
expect(anchor.rel).toBe('noopener noreferrer')
expect(anchor.hasAttribute('download')).toBe(false)
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.target).toBe('_blank');
expect(anchor.rel).toBe('noopener noreferrer');
expect(anchor.hasAttribute('download')).toBe(false);
// Revoke happens after 30s timeout
vi.runAllTimers()
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url')
})
vi.runAllTimers();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url');
});
it('does not trigger a second in-page action for safe inline types (regression: no double-open)', async () => {
vi.stubGlobal('fetch', makeFetchMock(200))
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
vi.stubGlobal('fetch', makeFetchMock(200));
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/doc.pdf', 'doc.pdf')
await openFile('/uploads/files/doc.pdf', 'doc.pdf');
// Exactly ONE anchor click — opening the new tab. No fallback download.
expect(clickSpy).toHaveBeenCalledTimes(1)
})
expect(clickSpy).toHaveBeenCalledTimes(1);
});
it('throws on 401 response', async () => {
vi.stubGlobal('fetch', makeFetchMock(401, new Blob([], { type: 'application/pdf' })))
await expect(openFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized')
expect(URL.createObjectURL).not.toHaveBeenCalled()
})
vi.stubGlobal('fetch', makeFetchMock(401, new Blob([], { type: 'application/pdf' })));
await expect(openFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized');
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
it('forces download for unsafe MIME types (HTML) instead of opening inline', async () => {
const htmlBlob = new Blob(['<script>alert(1)</script>'], { type: 'text/html' })
vi.stubGlobal('fetch', makeFetchMock(200, htmlBlob))
const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window)
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const htmlBlob = new Blob(['<script>alert(1)</script>'], { type: 'text/html' });
vi.stubGlobal('fetch', makeFetchMock(200, htmlBlob));
const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/malicious.html', 'malicious.html')
await openFile('/uploads/files/malicious.html', 'malicious.html');
// Must NOT open inline — download anchor clicked instead
expect(openSpy).not.toHaveBeenCalled()
expect(clickSpy).toHaveBeenCalledTimes(1)
expect(openSpy).not.toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalledTimes(1);
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement
expect(anchor.download).toBe('malicious.html')
})
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.download).toBe('malicious.html');
});
it('forces download for SVG MIME type', async () => {
const svgBlob = new Blob(['<svg><script>alert(1)</script></svg>'], { type: 'image/svg+xml' })
vi.stubGlobal('fetch', makeFetchMock(200, svgBlob))
const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window)
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const svgBlob = new Blob(['<svg><script>alert(1)</script></svg>'], { type: 'image/svg+xml' });
vi.stubGlobal('fetch', makeFetchMock(200, svgBlob));
const openSpy = vi.spyOn(window, 'open').mockReturnValue({} as Window);
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await openFile('/uploads/files/malicious.svg')
await openFile('/uploads/files/malicious.svg');
expect(openSpy).not.toHaveBeenCalled()
expect(clickSpy).toHaveBeenCalledTimes(1)
})
expect(openSpy).not.toHaveBeenCalled();
expect(clickSpy).toHaveBeenCalledTimes(1);
});
it('falls back to download in iOS PWA standalone mode (blob URL inaccessible to Safari)', async () => {
vi.stubGlobal('fetch', makeFetchMock(200))
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
vi.stubGlobal('fetch', makeFetchMock(200));
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
// Simulate iOS PWA (Add-to-Home-Screen) context
Object.defineProperty(navigator, 'standalone', { configurable: true, value: true })
Object.defineProperty(navigator, 'standalone', { configurable: true, value: true });
try {
await openFile('/uploads/files/doc.pdf', 'doc.pdf')
await openFile('/uploads/files/doc.pdf', 'doc.pdf');
// Single anchor click — and it must be a DOWNLOAD anchor (no target=_blank),
// because target="_blank" in iOS PWA would hand off to Safari which cannot
// read the in-WebView blob URL.
expect(clickSpy).toHaveBeenCalledTimes(1)
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement
expect(anchor.target).toBe('')
expect(anchor.download).toBe('doc.pdf')
expect(clickSpy).toHaveBeenCalledTimes(1);
const appendCalls = (document.body.appendChild as ReturnType<typeof vi.fn>).mock.calls;
const anchor = appendCalls[0]?.[0] as HTMLAnchorElement;
expect(anchor.target).toBe('');
expect(anchor.download).toBe('doc.pdf');
} finally {
// Clean up the non-standard iOS-only property we forced above.
delete (navigator as any).standalone
delete (navigator as any).standalone;
}
})
})
});
});
describe('offline fallback (#1046)', () => {
function setOnline(value: boolean) {
Object.defineProperty(navigator, 'onLine', { value, configurable: true })
Object.defineProperty(navigator, 'onLine', { value, configurable: true });
}
beforeEach(() => vi.mocked(getCachedBlob).mockReset())
afterEach(() => setOnline(true))
beforeEach(() => vi.mocked(getCachedBlob).mockReset());
afterEach(() => setOnline(true));
it('serves the cached blob without a network call when offline', async () => {
setOnline(false)
const blob = new Blob(['x'], { type: 'application/pdf' })
vi.mocked(getCachedBlob).mockResolvedValue(blob)
const fetchSpy = vi.fn()
vi.stubGlobal('fetch', fetchSpy)
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
setOnline(false);
const blob = new Blob(['x'], { type: 'application/pdf' });
vi.mocked(getCachedBlob).mockResolvedValue(blob);
const fetchSpy = vi.fn();
vi.stubGlobal('fetch', fetchSpy);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/cached.pdf')
await downloadFile('/uploads/files/cached.pdf');
expect(fetchSpy).not.toHaveBeenCalled()
expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf')
expect(URL.createObjectURL).toHaveBeenCalledWith(blob)
})
expect(fetchSpy).not.toHaveBeenCalled();
expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf');
expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
});
it('falls back to the cache when a live fetch rejects (network error) while online', async () => {
setOnline(true)
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down')))
const blob = new Blob(['x'], { type: 'application/pdf' })
vi.mocked(getCachedBlob).mockResolvedValue(blob)
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
setOnline(true);
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down')));
const blob = new Blob(['x'], { type: 'application/pdf' });
vi.mocked(getCachedBlob).mockResolvedValue(blob);
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
await downloadFile('/uploads/files/cached.pdf')
await downloadFile('/uploads/files/cached.pdf');
expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf')
expect(URL.createObjectURL).toHaveBeenCalledWith(blob)
})
expect(getCachedBlob).toHaveBeenCalledWith('/uploads/files/cached.pdf');
expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
});
it('throws when offline and the file was never cached', async () => {
setOnline(false)
vi.mocked(getCachedBlob).mockResolvedValue(null)
await expect(downloadFile('/uploads/files/missing.pdf')).rejects.toThrow(/offline/i)
})
setOnline(false);
vi.mocked(getCachedBlob).mockResolvedValue(null);
await expect(downloadFile('/uploads/files/missing.pdf')).rejects.toThrow(/offline/i);
});
it('does not consult the cache on an HTTP error — a 401 still surfaces', async () => {
setOnline(true)
vi.stubGlobal('fetch', makeFetchMock(401))
await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized')
expect(getCachedBlob).not.toHaveBeenCalled()
})
})
setOnline(true);
vi.stubGlobal('fetch', makeFetchMock(401));
await expect(downloadFile('/uploads/files/secret.pdf')).rejects.toThrow('Unauthorized');
expect(getCachedBlob).not.toHaveBeenCalled();
});
});
describe('stalled connection with a stored copy (#3066)', () => {
const stored = new Blob(['stored'], { type: 'application/pdf' });
// A promise that never settles on its own and rejects like fetch once the
// signal aborts, which is what a stalled link looks like to the page.
function stallUntilAbort<T>(signal: AbortSignal | undefined): Promise<T> {
return new Promise<T>((_resolve, reject) => {
signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
});
}
function track<T>(promise: Promise<T>) {
const state = { done: false };
const finish = () => {
state.done = true;
};
promise.then(finish, finish);
return state;
}
beforeEach(() => {
vi.mocked(getCachedBlob).mockReset();
Object.defineProperty(navigator, 'onLine', { value: true, configurable: true });
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
});
it('serves the stored copy once a stalled request has run past the wait', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
let signal: AbortSignal | undefined;
vi.stubGlobal(
'fetch',
vi.fn((_url: string, init?: RequestInit) => {
signal = init?.signal ?? undefined;
return stallUntilAbort<Response>(signal);
})
);
const pending = downloadFile('/uploads/files/stalled.pdf');
const state = track(pending);
await vi.advanceTimersByTimeAsync(4999);
expect(state.done).toBe(false);
await vi.advanceTimersByTimeAsync(1);
await pending;
expect(URL.createObjectURL).toHaveBeenCalledWith(stored);
expect(signal?.aborted).toBe(true);
});
it('serves the stored copy when the body stalls mid download', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
let signal: AbortSignal | undefined;
vi.stubGlobal(
'fetch',
vi.fn((_url: string, init?: RequestInit) => {
signal = init?.signal ?? undefined;
return Promise.resolve({ ok: true, status: 200, blob: () => stallUntilAbort<Blob>(signal) });
})
);
const pending = openFile('/uploads/files/half.pdf');
await vi.advanceTimersByTimeAsync(5000);
await pending;
expect(URL.createObjectURL).toHaveBeenCalledWith(stored);
expect(signal?.aborted).toBe(true);
});
it('still surfaces an HTTP error over the stored copy', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
vi.stubGlobal('fetch', makeFetchMock(403));
await expect(downloadFile('/uploads/files/forbidden.pdf')).rejects.toThrow('HTTP 403');
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
it('serves the stored copy when the connection breaks while the body arrives', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(stored);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.reject(new TypeError('network')) })
);
await openFile('/uploads/files/broken.pdf');
expect(URL.createObjectURL).toHaveBeenCalledWith(stored);
});
it('surfaces a broken body read when nothing is stored', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(null);
const broken = new TypeError('network');
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.reject(broken) }));
await expect(openFile('/uploads/files/broken.pdf')).rejects.toBe(broken);
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
it('keeps waiting on the live download when nothing is stored', async () => {
vi.mocked(getCachedBlob).mockResolvedValue(null);
const live = new Blob(['live'], { type: 'application/pdf' });
let answer: ((resp: unknown) => void) | undefined;
let signal: AbortSignal | undefined;
vi.stubGlobal(
'fetch',
vi.fn((_url: string, init?: RequestInit) => {
signal = init?.signal ?? undefined;
return new Promise((resolve) => {
answer = resolve;
});
})
);
const pending = downloadFile('/uploads/files/slow.pdf');
const state = track(pending);
await vi.advanceTimersByTimeAsync(60_000);
expect(state.done).toBe(false);
expect(signal?.aborted).toBe(false);
answer?.({ ok: true, status: 200, blob: () => Promise.resolve(live) });
await pending;
expect(URL.createObjectURL).toHaveBeenCalledWith(live);
});
});
+10 -7
View File
@@ -5,10 +5,13 @@
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { locationAt, pageUrl } from '../../helpers/location';
const SOURCE = readFileSync(resolve(process.cwd(), 'public/shell-guard.js'), 'utf8');
const ENTRY = '/assets/index-BZcJ9-lk.js';
const MARKER = 'trek:shell-reload';
// Workbox names its precache after the scope the worker was registered for.
const PRECACHE = `workbox-precache-v2-${pageUrl('/')}`;
type Listener = [string, EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined];
let listeners: Listener[] = [];
@@ -51,21 +54,21 @@ interface Env {
deleted: string[];
}
/** A page a service worker served, unless `controlled` is false. */
function install(href = 'http://localhost/trips/4?tab=plan#day-2', controlled = true): Env {
/** The page at `path`, one a service worker served unless `controlled` is false. */
function install(path = '/trips/4?tab=plan#day-2', controlled = true): Env {
const replace = vi.fn();
Object.defineProperty(window, 'location', { value: { ...window.location, href, replace }, writable: true, configurable: true });
Object.defineProperty(window, 'location', { value: locationAt(path, { replace }), writable: true, configurable: true });
const fetch = vi.fn(async () => healthAnswer(true, 'application/json; charset=utf-8'));
vi.stubGlobal('fetch', fetch);
const unregister = vi.fn(async () => true);
Object.defineProperty(navigator, 'serviceWorker', {
value: { controller: controlled ? { scriptURL: 'http://localhost/sw.js' } : null, getRegistration: vi.fn(async () => ({ unregister })) },
value: { controller: controlled ? { scriptURL: pageUrl('/sw.js') } : null, getRegistration: vi.fn(async () => ({ unregister })) },
configurable: true,
});
const deleted: string[] = [];
Object.defineProperty(globalThis, 'caches', {
value: {
keys: vi.fn(async () => ['workbox-precache-v2-http://localhost/', 'map-tiles', 'gl-map-offline', 'user-uploads']),
keys: vi.fn(async () => [PRECACHE, 'map-tiles', 'gl-map-offline', 'user-uploads']),
delete: vi.fn(async (name: string) => { deleted.push(name); return true; }),
},
configurable: true,
@@ -117,7 +120,7 @@ describe('shell-guard.js', () => {
expect(env.fetch).toHaveBeenCalledWith('/api/health', expect.objectContaining({ cache: 'no-store', redirect: 'manual' }));
// Only the precache: offline map regions and cached uploads were downloaded on purpose.
expect(env.deleted).toEqual(['workbox-precache-v2-http://localhost/']);
expect(env.deleted).toEqual([PRECACHE]);
expect(env.unregister).toHaveBeenCalledTimes(1);
const target = new URL(env.replace.mock.calls[0][0] as string);
expect(target.pathname + target.hash).toBe('/trips/4#day-2');
@@ -191,7 +194,7 @@ describe('shell-guard.js', () => {
it('FE-SHELLGUARD-011: a page that came from the network is reloaded afresh and its worker kept', async () => {
// Nothing the worker keeps answered this load, so throwing it away would only
// cost the offline shell.
const env = install('http://localhost/dashboard', false);
const env = install('/dashboard', false);
runGuard();
fail(moduleScript(ENTRY));
await vi.waitFor(() => expect(env.replace).toHaveBeenCalledTimes(1));
+7 -6
View File
@@ -21,11 +21,12 @@
# superuser trek; the wiki page Database-Postgres ("Moving a compose install
# off the superuser") shows how to move it to this layout.
#
# The database runs PostgreSQL 18. TREK supports 14 to 18: to run 14 to 17,
# change the image tag and mount the volume at /var/lib/postgresql/data
# instead, where those images keep their data (the 18 image refuses that
# path). An existing database stays on the major it was created with: when
# you update this file, keep your image tag and volume path. Moving to
# The database runs PostgreSQL 18. TREK supports 14 to 19: a new database
# may run postgres:19 on the same volume path. To run 14 to 17, change the
# image tag and mount the volume at /var/lib/postgresql/data instead, where
# those images keep their data (the 18 and 19 images refuse that path). An
# existing database stays on the major it was created with: when you update
# this file, keep your image tag and volume path. Moving to
# another major needs pg_upgrade, or a dump and restore (a TREK backup
# restored into a new, empty database of the same or a newer major), never
# just a new image tag.
@@ -46,7 +47,7 @@ services:
- no-new-privileges:true
# No ports are published: only the trek service on the compose network reaches the database.
volumes:
# The path the postgres:18 image expects. Images 14 to 17 need
# The path the postgres:18 and :19 images expect. Images 14 to 17 need
# /var/lib/postgresql/data here (see the top of this file).
- trek-pgdata:/var/lib/postgresql
healthcheck:
+865 -1412
View File
File diff suppressed because it is too large Load Diff
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env node
// The Android app as an APK outside Google Play, for Obtainium and the like.
//
// native-release.yml uploads each Android build to Google Play, which signs it
// with the app signing key only Google holds. Google Play also builds a
// universal APK of that bundle, signed with the same key. This script fetches
// that APK, so the copy published in liketrek/trek-android carries the very
// signature of the Play install: a phone can move between the two without
// uninstalling, and Play Billing and push work in it wherever Google Play
// services do.
//
// guard <features.controller.ts of the latest server release>
// Whether this build may go out now. The app refuses a server older than
// its MIN_NATIVE_API (client/src/native/serverAddress.ts), and a build can
// be cut from dev before the server it needs is released. It may go out
// once the latest server release answers a nativeApi at least that high
// (its server/src/nest/health/features.controller.ts, which the workflow
// writes out with git show). Prints publish=true or publish=false, for
// $GITHUB_OUTPUT.
//
// download <service account json> <package> <version code> <out.apk>
// Asks the Play Developer API for the universal APK of that version code,
// waiting a while for Google to generate it, and writes it to <out.apk>.
//
// No secret is printed: the service account file is read, not echoed.
import { createSign } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
const APP_MIN_FILE = 'client/src/native/serverAddress.ts';
const SERVER_API_FILE = 'server/src/nest/health/features.controller.ts';
const API = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications';
const REQUEST_TIMEOUT_MS = 30_000;
const APK_TIMEOUT_MS = 5 * 60_000;
const WAIT_STEPS_MS = [15_000, 30_000, 60_000, 120_000, 240_000];
const MAX_APK_BYTES = 400 * 1024 * 1024;
/** The app's MIN_NATIVE_API in the source of serverAddress.ts; throws when it cannot be read. */
export function appMinimumApi(source) {
const found = /\bconst MIN_NATIVE_API = (\d+);/.exec(source);
if (!found) throw new Error(`MIN_NATIVE_API not found in ${APP_MIN_FILE}`);
return Number(found[1]);
}
/** The nativeApi the server answers in the source of features.controller.ts; throws when it cannot be read. */
export function serverApi(source) {
const found = /\bnativeApi: (\d+),/.exec(source);
if (!found) throw new Error(`nativeApi not found in ${SERVER_API_FILE}`);
return Number(found[1]);
}
/** Whether a build that needs `appMinimum` may go out while the newest server release answers `released`. */
export function mayPublish(appMinimum, released) {
return released >= appMinimum;
}
function guard(releasedFeatures) {
const appMinimum = appMinimumApi(readFileSync(APP_MIN_FILE, 'utf8'));
const released = serverApi(readFileSync(releasedFeatures, 'utf8'));
const publish = mayPublish(appMinimum, released);
console.error(`the app needs native API ${appMinimum}, the latest release answers ${released}: ${publish ? 'publish' : 'hold back'}`);
console.log(`publish=${publish}`);
}
const b64url = (value) => Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)).toString('base64url');
async function accessToken(account) {
const now = Math.floor(Date.now() / 1000);
const unsigned = `${b64url({ alg: 'RS256', typ: 'JWT' })}.${b64url({
iss: account.client_email,
scope: 'https://www.googleapis.com/auth/androidpublisher',
aud: account.token_uri,
iat: now,
exp: now + 600,
})}`;
const signature = createSign('RSA-SHA256').update(unsigned).sign(account.private_key).toString('base64url');
const response = await fetch(account.token_uri, {
method: 'POST',
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: `${unsigned}.${signature}`,
}),
});
const body = await response.json();
if (!response.ok || typeof body.access_token !== 'string') {
throw new Error(`Google refused the service account: HTTP ${response.status} ${body.error ?? ''}`);
}
return body.access_token;
}
/** The download id of the universal APK in a generatedApks.list answer, or null while Google has none yet. */
export function universalDownloadId(answer) {
for (const generated of answer?.generatedApks ?? []) {
const id = generated?.generatedUniversalApk?.downloadId;
if (typeof id === 'string' && id.length > 0) return id;
}
return null;
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function download(accountFile, pkg, versionCode, out) {
if (!/^[\w.]+$/.test(pkg) || !/^\d+$/.test(versionCode)) throw new Error('package or version code malformed');
const token = await accessToken(JSON.parse(readFileSync(accountFile, 'utf8')));
const headers = { authorization: `Bearer ${token}` };
const base = `${API}/${pkg}/generatedApks/${versionCode}`;
let id = null;
for (let attempt = 0; id === null; attempt++) {
const response = await fetch(base, { headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
const body = await response.json();
// 404 while Google has not processed the bundle yet; anything else is final.
if (!response.ok && response.status !== 404) {
throw new Error(`generatedApks.list: HTTP ${response.status} ${body.error?.message ?? ''}`);
}
id = response.ok ? universalDownloadId(body) : null;
if (id === null) {
if (attempt >= WAIT_STEPS_MS.length) throw new Error(`no universal APK for version code ${versionCode} yet`);
console.error(`waiting for Google to build the universal APK of ${versionCode}`);
await sleep(WAIT_STEPS_MS[attempt]);
}
}
const response = await fetch(`${base}/downloads/${encodeURIComponent(id)}:download?alt=media`, {
headers,
signal: AbortSignal.timeout(APK_TIMEOUT_MS),
});
if (!response.ok) throw new Error(`generatedApks.download: HTTP ${response.status}`);
const apk = Buffer.from(await response.arrayBuffer());
// An APK is a zip archive; anything else is an error page.
if (apk.length > MAX_APK_BYTES || apk.subarray(0, 2).toString('latin1') !== 'PK') {
throw new Error(`the download is not an APK (${apk.length} bytes)`);
}
writeFileSync(out, apk);
console.error(`wrote ${out} (${apk.length} bytes)`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [command, ...args] = process.argv.slice(2);
try {
if (command === 'guard' && args.length === 1) guard(args[0]);
else if (command === 'download' && args.length === 4) await download(...args);
else throw new Error('usage: android-apk-release.mjs guard <features.controller.ts> | download <account.json> <package> <code> <out.apk>');
} catch (err) {
console.error(`::error::${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
}
}
+39
View File
@@ -0,0 +1,39 @@
import { appMinimumApi, mayPublish, serverApi, universalDownloadId } from './android-apk-release.mjs';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
const read = (path) => readFileSync(fileURLToPath(new URL(`../../${path}`, import.meta.url)), 'utf8');
describe('android-apk-release', () => {
it('reads the native API the app needs and the one the server answers from the real files', () => {
const appMinimum = appMinimumApi(read('client/src/native/serverAddress.ts'));
const answered = serverApi(read('server/src/nest/health/features.controller.ts'));
assert.ok(Number.isInteger(appMinimum) && appMinimum >= 1);
// A commit never needs more than the server it ships with.
assert.ok(answered >= appMinimum);
});
it('refuses to guess when a constant moved', () => {
assert.throws(() => appMinimumApi('export const MIN_API = 3;'), /MIN_NATIVE_API not found/);
assert.throws(() => serverApi('nativeApi = 3'), /nativeApi not found/);
});
it('holds back a build that needs a server not released yet', () => {
assert.equal(mayPublish(3, 3), true);
assert.equal(mayPublish(3, 4), true);
assert.equal(mayPublish(4, 3), false);
});
it('finds the universal APK in a generatedApks answer, and nothing in one without it', () => {
assert.equal(
universalDownloadId({ generatedApks: [{ generatedSplitApks: [{}] }, { generatedUniversalApk: { downloadId: 'abc' } }] }),
'abc',
);
assert.equal(universalDownloadId({ generatedApks: [{ generatedSplitApks: [{}] }] }), null);
assert.equal(universalDownloadId({}), null);
assert.equal(universalDownloadId(null), null);
});
});
+2 -2
View File
@@ -52,8 +52,8 @@ DEMO_MODE=false # Demo mode: resets data hourly
# BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120)
# BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size).
# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). A Unix socket: postgresql://trek@localhost/trek?host=/var/run/postgresql (a host= or port= parameter takes the place of the URL's own, as in libpq). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS.
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<18..14>/bin, newest first, then /usr/local/bin and /usr/bin (the Docker image installs the version 18 tools, which work with every supported server; tools older than the server are refused). Unused on SQLite.
# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). For a server that asks for a client certificate, sslcert= and sslkey= name the certificate and its key file, both together and only with a verifying sslmode. A Unix socket: postgresql://trek@localhost/trek?host=/var/run/postgresql (a host= or port= parameter takes the place of the URL's own, as in libpq). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS.
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/19/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<19..14>/bin, newest first, then /usr/local/bin and /usr/bin (the Docker image installs the version 19 tools, which work with every supported server; tools older than the server are refused). Unused on SQLite.
# TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10)
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db (a .pgdump made with pg_dump on Postgres) before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
+3 -3
View File
File diff suppressed because one or more lines are too long
+23 -21
View File
@@ -65,42 +65,43 @@
"dependencies": {
"@aws-lite/client": "^0.24.1",
"@aws-lite/s3": "^0.2.7",
"@mikro-orm/cli": "^7.2.7",
"@mikro-orm/core": "^7.2.7",
"@mikro-orm/migrations": "^7.2.7",
"@mikro-orm/cli": "^7.2.12",
"@mikro-orm/core": "^7.2.12",
"@mikro-orm/migrations": "^7.2.12",
"@mikro-orm/nestjs": "^7.1.0",
"@mikro-orm/postgresql": "^7.2.7",
"@mikro-orm/seeder": "^7.2.7",
"@mikro-orm/sql": "^7.2.1",
"@mikro-orm/sqlite": "^7.2.7",
"@mikro-orm/postgresql": "^7.2.12",
"@mikro-orm/seeder": "^7.2.12",
"@mikro-orm/sql": "^7.2.12",
"@mikro-orm/sqlite": "^7.2.12",
"@modelcontextprotocol/sdk": "^1.32.2",
"@nestjs/common": "^11.2.5",
"@nestjs/common": "^11.2.12",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.2.5",
"@nestjs/platform-express": "^11.2.5",
"@nestjs/platform-ws": "^11.2.5",
"@nestjs/core": "^11.2.12",
"@nestjs/platform-express": "^11.2.12",
"@nestjs/platform-ws": "^11.2.12",
"@nestjs/schedule": "^12.0.4",
"@nestjs/swagger": "^11.4.7",
"@nestjs/websockets": "^11.2.5",
"@nestjs/swagger": "^11.4.8",
"@nestjs/websockets": "^11.2.12",
"@simplewebauthn/server": "^14.1.0",
"@trek/shared": "*",
"archiver": "^6.0.2",
"bcryptjs": "^2.4.3",
"better-sqlite3": "^13.0.3",
"better-sqlite3": "^13.2.0",
"compression": "^1.8.2",
"cookie-parser": "^1.4.7",
"cors": "^2.8.6",
"cron": "^4.4.0",
"dotenv": "^18.0.10",
"exifr": "7.1.3",
"express": "^4.22.3",
"express": "^5.3.0",
"fast-xml-parser": "^5.12.1",
"helmet": "^8.3.0",
"imapflow": "^1.0.0",
"jimp": "^1.6.1",
"jimp": "^1.7.0",
"json5": "^2.2.3",
"jsonwebtoken": "^9.0.3",
"kysely": "^0.29.6",
"kysely": "^0.29.9",
"mime-types": "^3.0.2",
"multer": "^2.5.0",
"nestjs-zod": "^5.6.0",
"nodemailer": "^10.6.1",
@@ -124,8 +125,8 @@
"devDependencies": {
"@aws-lite/s3-types": "^0.2.8",
"@eslint/js": "^10.0.1",
"@mikro-orm/entity-generator": "^7.2.7",
"@nestjs/testing": "^11.2.5",
"@mikro-orm/entity-generator": "^7.2.12",
"@nestjs/testing": "^11.2.12",
"@swc/core": "^1.16.22",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/archiver": "^7.0.0",
@@ -134,10 +135,11 @@
"@types/compression": "^1.8.1",
"@types/cookie-parser": "^1.4.10",
"@types/cors": "^2.8.19",
"@types/express": "^4.17.25",
"@types/express": "^5.0.6",
"@types/jsonwebtoken": "^9.0.10",
"@types/mime-types": "^3.0.1",
"@types/multer": "^2.3.0",
"@types/node": "^25.9.8",
"@types/node": "^26.6.11",
"@types/nodemailer": "^8.0.2",
"@types/qrcode": "^1.5.6",
"@types/semver": "^7.8.0",
+1 -1
View File
@@ -53,7 +53,7 @@
"src/db/repositories/VacayShares.repository.ts": 1,
"src/db/repositories/VacayYears.repository.ts": 1,
"src/db/repositories/WebauthnCredentials.repository.ts": 1,
"src/db/repositories/_shared/trek-repository.ts": 8,
"src/db/repositories/_shared/trek-repository.ts": 4,
"src/mcp/sessionManager.ts": 2,
"src/mcp/tools.ts": 1,
"src/nest-mcp/registry.ts": 2,
+8
View File
@@ -232,6 +232,14 @@ export async function buildApp(): Promise<INestApplication> {
instance.use(function urlencodedParser(req: Request, res: Response, next: NextFunction) {
return isMcp(req) ? next() : urlencoded(req, res, next);
});
// A request the parsers above did not read (no body, or another content type)
// keeps an empty object as its body, as it always had: body-parser 2 leaves
// it undefined, which a route whose fields are all optional would refuse and a
// plugin route would receive as null. /mcp stays raw.
instance.use(function emptyBodyDefault(req: Request, _res: Response, next: NextFunction) {
if (req.body === undefined && !isMcp(req)) req.body = {};
next();
});
// Every request value without NUL from here on (nest/common/nul-free-input.ts):
// the path, the query string, the parsed body and the cookies, before any
// guard, interceptor or controller reads them, so a key or a check made from
+8 -2
View File
@@ -14,12 +14,13 @@ export type PgTool = 'pg_dump' | 'pg_restore' | 'psql';
/**
* Where the client tools are looked for when `TREK_DB_PG_BIN_DIR` is unset:
* Debian's versioned directories newest first (the Docker image installs 18),
* Debian's versioned directories newest first (the Docker image installs 19),
* then the usual prefixes. Newest first because a client dumps and restores
* every server up to its own major version and refuses a newer one. Never
* PATH: a binary is run by its absolute path.
*/
const DEFAULT_BIN_DIRS = [
'/usr/lib/postgresql/19/bin',
'/usr/lib/postgresql/18/bin',
'/usr/lib/postgresql/17/bin',
'/usr/lib/postgresql/16/bin',
@@ -63,7 +64,8 @@ export function resolvePgTool(tool: PgTool, binDir: string | undefined): string
* read. An sslmode that asks for SSL verifies the server's certificate, as the
* app's own pool does (`postgres-engine.ts`): against the URL's sslrootcert,
* else the system's trusted CAs (`system`, which `run` accepts only from a
* client that understands it).
* client that understands it), and presents the URL's client certificate
* (sslcert and sslkey) when it names one.
*/
export function pgConnectionEnv(url: string): Record<string, string> {
const parsed = new URL(url);
@@ -81,6 +83,10 @@ export function pgConnectionEnv(url: string): Record<string, string> {
else if (sslmode) {
env.PGSSLMODE = 'verify-full';
env.PGSSLROOTCERT = parsed.searchParams.get('sslrootcert') ?? 'system';
const clientCert = parsed.searchParams.get('sslcert');
const clientKey = parsed.searchParams.get('sslkey');
if (clientCert) env.PGSSLCERT = clientCert;
if (clientKey) env.PGSSLKEY = clientKey;
}
return env;
}
@@ -38,7 +38,7 @@ import path from 'node:path';
*
* Which names are functions of `pg_catalog` is read from
* `assets/postgres/catalog-functions.txt`: every function name of every
* supported major (14 to 18; the boot refuses any other server). The Postgres
* supported major (14 to 19; the boot refuses any other server). The Postgres
* lane compares it with `pg_proc` on the server it runs on and fails on a
* name missing there (PGPLUG-021), so a new major cannot add a function a
* plugin may call without someone deciding whether it belongs here.
@@ -8,8 +8,8 @@ import { run } from './pg-process';
* psql then refuses every meta-command until the matching `\unrestrict`.
*
* RESTRICT_SINCE holds, per major, the first minor that carries the fix, for
* every major TREK supports (14 to 18; 18 has it from 18.0). Every major after
* the last one listed has it from its first release.
* the majors TREK supports from 14 to 18 (18 has it from 18.0). Every major after
* the last one listed (19 and later) has it from its first release.
*/
const RESTRICT_SINCE: Readonly<Partial<Record<number, number>>> = { 14: 19, 15: 14, 16: 10, 17: 6, 18: 0 };
const LAST_MAJOR_WITHOUT_IT = Math.max(...Object.keys(RESTRICT_SINCE).map(Number));
@@ -46,6 +46,6 @@ export async function refuseToolsWithoutRestrict(binDir: string | undefined): Pr
if (stale < 0) return;
throw new Error(
`${tools[stale]} is too old to restore safely (${versions[stale].trim()}): it must be at least ${minimumVersionsText()} ` +
'(the Docker image has 18). Upgrade the PostgreSQL client tools or point TREK_DB_PG_BIN_DIR at newer ones.',
'(the Docker image has 19). Upgrade the PostgreSQL client tools or point TREK_DB_PG_BIN_DIR at newer ones.',
);
}
@@ -8,7 +8,7 @@ import { REFUSAL } from '../../legacy-baseline';
*/
/** The PostgreSQL majors TREK supports and CI runs: the oldest and the newest. */
const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 19 } as const;
/**
* The `pg_catalog` functions that read, list or write files on the database
+36 -9
View File
@@ -4,10 +4,23 @@ import { readFileSync } from 'node:fs';
const VERIFYING_MODES = new Set(['require', 'verify-ca', 'verify-full']);
/** The `ssl` option of a `pg` pool, as `sslOptionFor` builds it. */
type PgSslOption = false | { rejectUnauthorized: true; ca?: string };
type PgSslOption = false | VerifiedSsl;
/** SSL that verifies the server, with the CA and the client certificate the URL names. */
type VerifiedSsl = { rejectUnauthorized: true; ca?: string; cert?: string; key?: string };
/** The contents of the file a URL parameter names, or the refusal that names the parameter. */
function readNamedFile(param: string, file: string): string {
try {
return readFileSync(file, 'utf8');
} catch (error) {
throw new Error(`TREK_DB_URL names ${param} ${file}, which cannot be read.`, { cause: error });
}
}
/**
* The `ssl` option for the pool, from the URL's `sslmode` and `sslrootcert`.
* The `ssl` option for the pool, from the URL's `sslmode`, `sslrootcert`,
* `sslcert` and `sslkey`.
*
* MikroORM builds the pool from the URL's host, port, user, password and
* database alone and drops the rest of the query, so an `sslmode` in
@@ -17,26 +30,40 @@ type PgSslOption = false | { rejectUnauthorized: true; ca?: string };
* default (no SSL). A mode that would connect without verifying (`prefer`,
* `allow`, `no-verify`) or that is misspelt refuses, rather than quietly
* connecting with less than was asked. `sslrootcert` names the CA file a host
* that signs its own certificates needs (Supabase's, say).
* that signs its own certificates needs (Supabase's, say). `sslcert` and
* `sslkey` name the client certificate and its key for a server that wants
* one (mutual TLS); they come together or not at all, and only with a
* verifying mode.
*/
export function sslOptionFor(url: string): PgSslOption | undefined {
const params = new URL(url).searchParams;
const mode = params.get('sslmode');
const rootCert = params.get('sslrootcert');
const clientCert = params.get('sslcert');
const clientKey = params.get('sslkey');
if ((clientCert === null) !== (clientKey === null)) {
throw new Error('TREK_DB_URL names only one of sslcert and sslkey; a client certificate needs both.');
}
const hasClientCert = clientCert !== null && clientKey !== null;
if (mode === null) {
if (rootCert !== null) throw new Error('TREK_DB_URL names an sslrootcert without sslmode=verify-full.');
if (hasClientCert) throw new Error('TREK_DB_URL names an sslcert and sslkey without sslmode=verify-full.');
return undefined;
}
if (mode === 'disable') return false;
if (mode === 'disable') {
if (hasClientCert) throw new Error('TREK_DB_URL names an sslcert and sslkey with sslmode=disable.');
return false;
}
if (!VERIFYING_MODES.has(mode)) {
throw new Error(
`TREK_DB_URL has sslmode "${mode}"; use disable, require, verify-ca or verify-full (all but disable verify the server).`,
);
}
if (rootCert === null) return { rejectUnauthorized: true };
try {
return { rejectUnauthorized: true, ca: readFileSync(rootCert, 'utf8') };
} catch (error) {
throw new Error(`TREK_DB_URL names sslrootcert ${rootCert}, which cannot be read.`, { cause: error });
const option: VerifiedSsl = { rejectUnauthorized: true };
if (rootCert !== null) option.ca = readNamedFile('sslrootcert', rootCert);
if (hasClientCert) {
option.cert = readNamedFile('sslcert', clientCert);
option.key = readNamedFile('sslkey', clientKey);
}
return option;
}
+3 -1
View File
@@ -387,10 +387,12 @@ const aiProviderStateSchema = z.discriminatedUnion('adapter', [
adapter: z.literal('openai-responses'),
items: z.array(z.record(z.string(), z.unknown())),
}),
// Anthropic's content blocks of an answer that searched the web or thought, replayed as they came.
// Anthropic's content blocks of an answer that searched the web or thought, replayed as they came, and the
// fingerprint of what its request sent before it, which its thinking blocks are bound to.
z.object({
adapter: z.literal('anthropic-messages'),
blocks: z.array(z.record(z.string(), z.unknown())),
sentBefore: z.string().optional(),
}),
// Gemini's thought signature per tool call id, which its Chat Completions endpoint wants back with the call.
z.object({
@@ -1,5 +1,6 @@
import { currentTimestamp } from '../dialect/sql-functions';
import { currentTimestampKysely } from '../dialect/kysely-functions';
import { OauthConsents } from '../entities/OauthConsents.entity';
import type { DB } from '../kysely/db';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
@@ -63,27 +64,17 @@ export class OauthConsentsRepository extends TrekRepository<OauthConsents> {
/**
* `INSERT OR REPLACE INTO oauth_consents (client_id, user_id, scopes,
* updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)` —
* **security-sensitive** (authorization grant). `em.upsert` with
* `onConflictFields: ['client', 'user']` (the RELATION properties, not
* their `persist(false)` mirrors — `Settings.repository.ts::upsertForUser`'s
* precedent) against the entity's own `uniques: [{ properties: ['client',
* 'user'] }]` — the natural key the migration's `UNIQUE(client_id,
* user_id)` declares, verified against the migration before choosing this
* over a delete+insert fallback (task brief ruling).
* **security-sensitive** (authorization grant). Written with Kysely's
* `onConflict` on the migration's `UNIQUE(client_id, user_id)`, so the
* client goes in as the `client_id` column value it is. `em.upsert` would
* read it through the `client` relation, which points at
* `oauth_clients.client_id` rather than the primary key: MikroORM takes a
* bare value there for the target's primary key, and the referenced value
* as a plain object for the data of a new `OauthClients` entity.
*
* `updated_at` is explicit in the payload, not left to the column's
* `defaultRaw('CURRENT_TIMESTAMP')`: a default only fires on INSERT, and
* `em.upsert`'s `'merge'` action updates ONLY the fields present in the
* payload on a conflict (verified against the installed 7.2.1 behaviour
* and the MikroORM docs: "values generated by property `onCreate` hooks…
* are automatically excluded from the merge clause") — the legacy
* statement's `INSERT OR REPLACE` always re-writes `updated_at` to
* `CURRENT_TIMESTAMP` regardless of whether the row existed (SQLite's
* `OR REPLACE` deletes-then-inserts, so there is no "update" branch to
* distinguish), so this repository stamps it explicitly on every call
* through `currentTimestamp(platform)`, matching that unconditional
* behaviour rather than relying on a default that would only cover the
* insert half.
* `updated_at` is stamped on every call, on the insert and on the update
* half alike: the legacy `INSERT OR REPLACE` always rewrote it, and a
* column default would only cover the insert.
*
* Named `upsertGrant`, not `upsert` — `EntityRepository#upsert` already
* exists with an incompatible signature (`(entityOrData, options) =>
@@ -91,20 +82,22 @@ export class OauthConsentsRepository extends TrekRepository<OauthConsents> {
* hide the base method, the same collision `Users.repository.ts::insertUser`
* avoided with `create`.
*
* One more divergence from the legacy statement (Task 7 review, B-I1),
* One divergence from the legacy statement (Task 7 review, B-I1),
* unobservable and strictly better: the legacy `INSERT OR REPLACE`
* deletes-then-inserts, so a re-consent always assigned a NEW surrogate
* `id`; `em.upsert` with `onConflictAction: 'merge'` keeps the existing
* one. `oauth_consents` has only `id`/`client_id`/`user_id`/`scopes`/
* `updated_at` and nothing reads `id`, so this is unobservable — and it
* avoids the FK churn a delete+insert would otherwise cause if anything
* ever did reference this row's surrogate key.
* `id`; the update on conflict keeps the existing one. `oauth_consents` has
* only `id`/`client_id`/`user_id`/`scopes`/`updated_at` and nothing reads
* `id`, so this is unobservable, and it avoids the FK churn a
* delete+insert would cause if anything ever referenced this row's
* surrogate key.
*/
async upsertGrant(clientId: string, userId: number, scopes: string): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.upsert(
{ client: clientId, user: userId, scopes, updated_at: currentTimestamp(platform) },
{ onConflictFields: ['client', 'user'], onConflictAction: 'merge' },
);
const now = currentTimestampKysely(platform);
await this.kysely<Pick<DB, 'oauth_consents'>>()
.insertInto('oauth_consents')
.values({ client_id: clientId, user_id: userId, scopes, updated_at: now })
.onConflict((oc) => oc.columns(['client_id', 'user_id']).doUpdateSet({ scopes, updated_at: now }))
.execute();
}
}
@@ -2,6 +2,7 @@ import { columnRef, currentTimestamp } from '../dialect/sql-functions';
import { OauthTokens } from '../entities/OauthTokens.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import { oauthClientRef } from './_shared/oauth-client-ref';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
@@ -178,7 +179,7 @@ export class OauthTokensRepository extends TrekRepository<OauthTokens> {
*/
async insertToken(row: NewOauthTokenRow): Promise<void> {
await this.insert({
client: row.client_id,
client: oauthClientRef(row.client_id),
user: row.user_id,
access_token_hash: row.access_token_hash,
refresh_token_hash: row.refresh_token_hash,
@@ -0,0 +1,21 @@
import type { OauthClients } from '../../entities/OauthClients.entity';
import type { Ref } from '@mikro-orm/core';
/**
* The value an `oauth_tokens` or `oauth_consents` row writes for its `client`
* relation, from the client's public `client_id`.
*
* That relation points at `oauth_clients.client_id`, the unique natural key,
* not at the primary key `id` (`referencedColumnNames('client_id')` in both
* entities). Given a bare string, MikroORM reads it as the target's primary key
* and refuses the write, because it cannot know the `client_id` of that row
* without loading it. Given the referenced property itself, it writes that
* value to the column as it is.
*
* The typings only know a relation as an entity, a reference or a primary key,
* so the plain object is handed over as the reference it stands for.
*/
export function oauthClientRef(clientId: string): Ref<OauthClients> {
const referenced: Pick<OauthClients, 'client_id'> = { client_id: clientId };
return referenced as unknown as Ref<OauthClients>;
}
+5 -1
View File
@@ -275,7 +275,8 @@ export class AdminService {
// An address the admin enters is one the admin vouches for, so an SSO sign-in
// may link to it again. The edit dialog sends the email on every save, so only
// a new address counts, not the unchanged one or the same one in another case.
if (email && email.toLowerCase() !== user.email.toLowerCase()) patch.email_self_asserted = 0;
const emailChanged = !!email && email.toLowerCase() !== user.email.toLowerCase();
if (emailChanged) patch.email_self_asserted = 0;
if (role) patch.role = role;
if (password) {
patch.password_hash = passwordHash!;
@@ -302,6 +303,9 @@ export class AdminService {
}
}
await this.users.applyAdminEdit(userId, patch);
// A reset link sent to the old address, or asked for before the admin set
// a password, must not reopen the account afterwards.
if (emailChanged || password) await this.auth.retirePasswordResetLinks(userId);
if (password) {
// The version bump only invalidates JWT cookies. These two stores carry
@@ -23,6 +23,8 @@ import {
} from './provider-http';
import { readSseEvents } from './sse-lines';
import { createHash, type Hash } from 'node:crypto';
export const ANTHROPIC_VERSION = '2023-06-01';
/**
* The answer cap of one step, which Anthropic requires to be set: the most
@@ -40,18 +42,50 @@ function imageBlock(image: AiImage): ContentBlock {
return { type: 'image', source: { type: 'base64', media_type: image.mimeType, data: image.data } };
}
/**
* What a thinking block is bound to: Anthropic checks its signature against
* everything the request sends before it (the system blocks, the tools, the
* earlier turns) and refuses the whole request when any of it changed since
* the block was written. The history does change: a tool group loaded later
* in the turn, an earlier answer cut short once a new question follows, a
* held change applied since, a trip card that moved on. The fingerprint of
* what was sent before a step is kept with its record (AnthropicTurn), and
* its thinking goes back only while the request still sends the same before
* it (#3094).
*/
export class SentBefore {
private readonly hash: Hash;
constructor(head: unknown) {
this.hash = createHash('sha256').update(JSON.stringify(head));
}
add(role: AnthropicMessage['role'], blocks: readonly ContentBlock[]): void {
for (const block of blocks) this.hash.update(`${role}\n${JSON.stringify(block)}\n`);
}
fingerprint(): string {
return this.hash.copy().digest('base64url');
}
}
/**
* The provider-neutral history as Messages API turns: a tool result is a
* `tool_result` block of a user turn, and turns of the same role that follow
* each other merge into one, since the API wants them alternating. An image
* of a tool result goes inside that `tool_result`, after its text, where the
* model reads it as what the tool produced; a user's images go before their
* words.
* words. A recorded answer keeps its thinking only where `sent` still holds
* what was sent before it; without a record of that it goes back without.
*/
export function toAnthropicMessages(messages: AiChatMessage[]): AnthropicMessage[] {
export function toAnthropicMessages(
messages: AiChatMessage[],
sent: SentBefore = new SentBefore(null),
): AnthropicMessage[] {
const out: AnthropicMessage[] = [];
const push = (role: AnthropicMessage['role'], blocks: ContentBlock[]) => {
if (blocks.length === 0) return;
sent.add(role, blocks);
const last = out.at(-1);
if (last?.role === role) last.content.push(...blocks);
else out.push({ role, content: blocks });
@@ -60,7 +94,11 @@ export function toAnthropicMessages(messages: AiChatMessage[]): AnthropicMessage
if (message.role === 'user') {
push('user', [...(message.images ?? []).map(imageBlock), { type: 'text', text: message.text }]);
} else if (message.role === 'assistant' && message.providerState?.adapter === 'anthropic-messages') {
push('assistant', message.providerState.blocks.filter((block) => !isBlankText(block)).map(replayed));
const bound = message.providerState.sentBefore === sent.fingerprint();
const blocks = message.providerState.blocks.filter(
(block) => !isBlankText(block) && (bound || !isThinking(block)),
);
push('assistant', blocks.map(replayed));
} else if (message.role === 'assistant') {
push('assistant', [
...(message.text.trim() ? [{ type: 'text', text: message.text }] : []),
@@ -159,15 +197,8 @@ export class AnthropicMessagesClient implements AiChatClient {
const system = [request.system, request.context]
.filter((text): text is string => !!text)
.map((text) => ({ type: 'text', text, cache_control: CACHED }));
const messages = toAnthropicMessages(request.messages);
markHistoryForCache(messages, MAX_CACHE_BREAKPOINTS - system.length);
const body = {
model: this.model,
max_tokens: MAX_TOKENS,
stream: true,
system,
messages,
...(request.tools.length > 0 || request.webSearch
const tools =
request.tools.length > 0 || request.webSearch
? {
tools: [
...request.tools.map((tool) => ({
@@ -180,8 +211,12 @@ export class AnthropicMessagesClient implements AiChatClient {
// `none` is allowed with extended thinking, unlike forcing a tool.
...(request.toolChoice === 'none' ? { tool_choice: { type: 'none' } } : {}),
}
: {}),
};
: {};
const sent = new SentBefore({ model: this.model, system, ...tools });
const messages = toAnthropicMessages(request.messages, sent);
const sentBefore = sent.fingerprint();
markHistoryForCache(messages, MAX_CACHE_BREAKPOINTS - system.length);
const body = { model: this.model, max_tokens: MAX_TOKENS, stream: true, system, messages, ...tools };
const events = await openProviderStream(
this.fetcher,
this.kind,
@@ -199,7 +234,7 @@ export class AnthropicMessagesClient implements AiChatClient {
signal,
);
const turn = new AnthropicTurn();
const turn = new AnthropicTurn(sentBefore);
for await (const sse of readSseEvents(events)) {
const event = parseEventData(sse.data);
if (!event) continue;
@@ -242,6 +277,9 @@ class AnthropicTurn {
private readonly cited = new Set<string>();
private searched = false;
/** `sentBefore`: the fingerprint of what the request sent before this answer, kept with its record. */
constructor(private readonly sentBefore: string) {}
*apply(event: Record<string, unknown>): Generator<AiChatEvent> {
const index = asCount(event.index);
switch (event.type) {
@@ -321,7 +359,7 @@ class AnthropicTurn {
const blocks = [...this.blocks.entries()].sort(([a], [b]) => a - b).map(([, open]) => open.block);
const thought = blocks.some(isThinking);
if (!this.searched && !thought) return null;
return { adapter: 'anthropic-messages', blocks };
return { adapter: 'anthropic-messages', blocks, sentBefore: this.sentBefore };
}
}
@@ -70,10 +70,15 @@ export async function refusalOf(kind: AiConnectionKind, res: Response): Promise<
return failure;
}
/** The field an error body names as refused (OpenAI's `param`, such as `input[12]`), when it is a bare path. */
/**
* The field an error body names as refused, when it is a bare path: OpenAI's
* `param` (`input[12]`), or the path Anthropic's message starts with
* (`messages.1.content.0: ...`), of which nothing after the path is kept.
*/
function refusedParamOf(body: unknown): string | undefined {
const param = asRecord(asRecord(body).error).param;
return typeof param === 'string' && /^[\w.[\]-]{1,80}$/.test(param) ? param : undefined;
const error = asRecord(asRecord(body).error);
const param = typeof error.param === 'string' ? error.param : /^([\w.]{1,80}): /.exec(asText(error.message))?.[1];
return param !== undefined && /^[\w.[\]-]{1,80}$/.test(param) ? param : undefined;
}
/** One SSE data payload as a JSON object; null for anything else (a `[DONE]`, a keepalive). */
@@ -11,9 +11,10 @@ import { PACKAGE_HELD_READS, PACKAGE_TOOL_CONTROLLERS } from './cards/registry';
* annotated read-only runs at once, every other one waits as a change card.
*
* Offering all of them in every step would cost a lot of tokens and runs past
* what some providers take in one request, so a turn starts with the core of
* a trip (days, places, bookings, packing, to-dos, budget, weather, search)
* and the model loads an addon's tools when it needs them (USE_TOOLS_TOOL).
* what some providers take in one request (MAX_OFFERED_TOOLS), so a turn
* starts with the core of a trip (days, places, the plan, weather, search)
* and the model loads the rest of the trip and the addons when it needs them
* (USE_TOOLS_TOOL).
*/
/**
@@ -286,7 +287,14 @@ export function checkDenylist(names: Iterable<string>): string[] {
return problems;
}
type ToolGroups = Readonly<Record<string, { about: string; controllers: readonly string[] }>>;
interface ToolGroup {
about: string;
controllers: readonly string[];
/** A part of the trip itself rather than of the rest of TREK: its changes carry no place in TREK of their own. */
tripPart?: true;
}
type ToolGroups = Readonly<Record<string, ToolGroup>>;
/**
* The tool groups a turn can load, by the MCP controller that registers the
@@ -295,6 +303,30 @@ type ToolGroups = Readonly<Record<string, { about: string; controllers: readonly
* belongs to the core, which every step offers.
*/
const CORE_TOOL_GROUPS: ToolGroups = {
bookings: {
about:
"The trip's bookings: flights, trains, stays and every other reservation, the hotels and other " +
'accommodation, airports and the live status of a flight.',
controllers: ['ReservationsMcp', 'ReservationsReadMcp', 'AccommodationsMcp', 'AirportsMcp', 'FlightLiveMcp'],
tripPart: true,
},
packing: {
about: "The trip's packing lists (items, bags, templates) and its to-do list.",
controllers: ['PackingMcp', 'TodoMcp'],
tripPart: true,
},
budget: {
about:
"Changing the trip's budget: costs, who paid and who shares them, settlements and frozen exchange rates. " +
'Reading the costs needs nothing loaded.',
controllers: ['BudgetMcp'],
tripPart: true,
},
tags: {
about: 'Tags and categories of places.',
controllers: ['TagsMcp', 'TripTagsMcp', 'CategoriesMcp'],
tripPart: true,
},
tours: {
about:
'Tours: hikes (also over several days in stages), city walks, bike tours (road, gravel, mountain bike), ' +
@@ -407,6 +439,11 @@ export function withPackageControllers(
export const ASSISTANT_TOOL_GROUPS = withPackageControllers(CORE_TOOL_GROUPS, PACKAGE_TOOL_CONTROLLERS);
/** Whether a group is a part of the trip itself, whose changes show no place in TREK beside them. */
export function isTripPart(group: string): boolean {
return ASSISTANT_TOOL_GROUPS[group]?.tripPart === true;
}
const GROUP_OF_CONTROLLER = new Map(
Object.entries(ASSISTANT_TOOL_GROUPS).flatMap(([group, { controllers }]) =>
controllers.map((controller) => [controller, group] as const),
@@ -428,7 +465,8 @@ function useToolsDescription(core: string): string {
Object.entries(ASSISTANT_TOOL_GROUPS)
.map(([group, { about }]) => `"${group}" (${about})`)
.join('; ') +
`. ${core}`
`. ${core} Only so many tools fit in one step: loading a group can unload the one used longest ago, ` +
'which comes back when you call one of its tools.'
);
}
@@ -449,8 +487,7 @@ const USE_TOOLS_PARAMETERS: AiToolSpec['parameters'] = {
export const HOME_USE_TOOLS_SPEC: AiToolSpec = {
name: USE_TOOLS_TOOL,
description: useToolsDescription(
'Reading the trips (list_trips, and a trip by its id: days, places, bookings, packing, to-dos, budget, weather) ' +
'needs nothing loaded.',
'Reading the trips (list_trips, and a trip by its id: days, places, costs, weather) needs nothing loaded.',
),
parameters: USE_TOOLS_PARAMETERS,
};
@@ -458,7 +495,7 @@ export const HOME_USE_TOOLS_SPEC: AiToolSpec = {
export const USE_TOOLS_SPEC: AiToolSpec = {
name: USE_TOOLS_TOOL,
description: useToolsDescription(
'The trip itself (days, places, bookings, packing, to-dos, budget, weather, search) needs nothing loaded.',
'The trip itself (days, places, the plan, notes, costs, weather, search) needs nothing loaded.',
),
parameters: {
type: 'object',
@@ -19,6 +19,12 @@ export const MAX_READS_PER_STEP = 30;
/** Answer cards one step shows; the reads past it answer the model as usual, without a card. */
export const MAX_CARDS_PER_STEP = 12;
/**
* The most tools one request offers the model: OpenAI's APIs and Azure refuse
* a longer list (`array_above_max_length`), whatever else the provider takes.
*/
export const MAX_OFFERED_TOOLS = 128;
/** What a tool answer may cost the conversation, as JSON text, after it was cut down to its structure. */
export const MAX_TOOL_OUTPUT_CHARS = 40_000;
@@ -31,6 +31,7 @@ import {
HOME_USE_TOOLS_SPEC,
isOfferedTool,
isStudioController,
isTripPart,
JOURNEY_PINNED_ARG,
keptAtHome,
USE_TOOLS_SPEC,
@@ -39,6 +40,7 @@ import {
import {
ASSISTANT_SCOPES,
ASSISTANT_SERVER_TOOLS,
MAX_OFFERED_TOOLS,
PINNED_ARG,
PREVIEW_BOOK_PAGE_TOOL,
REMEMBER_TOOL,
@@ -82,6 +84,8 @@ export interface ToolHint {
destructive: boolean;
creates: boolean;
group: string | null;
/** The group is a part of the trip itself (its bookings, its packing), not a place elsewhere in TREK. */
tripPart?: true;
}
interface ListedTool {
@@ -218,6 +222,15 @@ function modelSchema(name: string, schema: Record<string, unknown>, pinArg: stri
return { ...rest, properties, ...(required.length > 0 ? { required } : {}) };
}
function hintOf(annotations: { destructiveHint?: boolean; idempotentHint?: boolean }, group: string | null): ToolHint {
return {
destructive: annotations.destructiveHint === true,
creates: annotations.idempotentHint === false,
group,
...(group && isTripPart(group) ? { tripPart: true as const } : {}),
};
}
function readResult(result: unknown): ToolRun {
const record = (result ?? {}) as { content?: unknown; isError?: unknown };
const text = Array.isArray(record.content)
@@ -264,7 +277,7 @@ export class AssistantToolSession {
private readonly pinArg: string = PINNED_ARG,
) {}
/** The groups this turn loaded; the core is always there. */
/** The groups this turn loaded, the one used longest ago first; the core is always there. */
private readonly loaded = new Set<string>();
/** Reads the model called before their group was loaded in this turn, by name, with that group; told once. */
@@ -286,6 +299,10 @@ export class AssistantToolSession {
specs(): AiToolSpec[] {
// The step these specs go to sees every loaded group's schema.
this.unoffered.clear();
return this.offeredSpecs();
}
private offeredSpecs(): AiToolSpec[] {
const listed = [...this.tools.values()]
.filter((tool) => tool.offered)
.filter((tool) => !this.grouped || tool.hint.group === null || this.loaded.has(tool.hint.group))
@@ -345,7 +362,7 @@ export class AssistantToolSession {
// name from an earlier turn), so it wrote the arguments without the
// schema (#2967). Its group is loaded here, so the next step offers the
// schema.
this.loaded.add(unloaded);
this.use([unloaded]);
this.unoffered.add(unloaded);
}
const group = this.tools.get(name)?.hint.group;
@@ -382,6 +399,8 @@ export class AssistantToolSession {
if (name === OPEN_JOURNEY_CHAT_TOOL && this.offersJournalChat) {
return openJourneyChat(args, await this.invoke(OPEN_JOURNEY_CHAT_READ, {}));
}
const group = this.tools.get(name)?.hint.group;
if (group && this.loaded.delete(group)) this.loaded.add(group);
const final = name === TRANSIT_CREATE_TOOL ? await this.withFoundItinerary(args) : args;
const run = await this.invoke(name, final);
this.audit(name);
@@ -436,9 +455,54 @@ ${hint}`,
const groups = asked.filter((group) => group in ASSISTANT_TOOL_GROUPS);
if (groups.length === 0)
return { ok: false, value: `Name one of: ${Object.keys(ASSISTANT_TOOL_GROUPS).join(', ')}` };
for (const group of groups) this.loaded.add(group);
const tools = [...this.tools.values()].filter((tool) => tool.hint.group && groups.includes(tool.hint.group));
return { ok: true, value: { loaded: groups, tools: tools.map((tool) => tool.name) } };
const { unloaded, refused } = this.use(groups);
const loaded = groups.filter((group) => !refused.includes(group));
const tools = [...this.tools.values()].filter((tool) => tool.hint.group && loaded.includes(tool.hint.group));
return {
ok: true,
value: {
loaded,
tools: tools.map((tool) => tool.name),
...(unloaded.length > 0 ? { unloaded } : {}),
...(refused.length > 0
? {
notLoaded: refused,
note: 'Too many tools for one step: load these on their own once the others are done.',
}
: {}),
},
};
}
/**
* Loads groups as the ones used last, then unloads the ones used longest
* ago until the step offers no more than MAX_OFFERED_TOOLS. Groups asked for
* together that do not fit even alone are left out from the last one asked.
*/
private use(groups: readonly string[]): { unloaded: string[]; refused: string[] } {
for (const group of groups) {
this.loaded.delete(group);
this.loaded.add(group);
}
const unloaded: string[] = [];
const refused: string[] = [];
const drop = (group: string) => {
this.loaded.delete(group);
this.unoffered.delete(group);
};
while (this.offeredSpecs().length > MAX_OFFERED_TOOLS) {
const oldest = [...this.loaded].find((group) => !groups.includes(group));
if (oldest) {
drop(oldest);
unloaded.push(oldest);
continue;
}
const last = [...this.loaded].reverse().find((group) => groups.includes(group) && !refused.includes(group));
if (!last || this.loaded.size === 1) break;
drop(last);
refused.push(last);
}
return { unloaded, refused };
}
async close(): Promise<void> {
@@ -620,11 +684,7 @@ export class AssistantToolsService implements OnApplicationBootstrap {
inputSchema,
kind,
pinned: pinNamesOf(pin.arg).some((key) => key in properties),
hint: {
destructive: annotations.destructiveHint === true,
creates: annotations.idempotentHint === false,
group: entry ? groupOf(entry) : null,
},
hint: hintOf(annotations, entry ? groupOf(entry) : null),
offered: true,
};
if (offer.keep(listed)) tools.set(tool.name, { ...listed, offered: offer.offered?.(listed) ?? true });
@@ -29,7 +29,7 @@ How you work:
- The trip card may start with what the user is asking about. A question about "this place", "it" or "here" is about that; never ask which place they mean then.
- The user can name days, places and bookings with "@" before the name. The trip card then lists what they named, with the ids; use those.
- The app shows the places your searches find as cards with a picture, and the weather you look up as a strip. Do not list them again in your text; say in a sentence or two which ones you suggest and why.
- Besides the open trip you can work in the rest of TREK: tours (hikes, bike tours, city walks), the road trip, the travel journal, the vacation planner, the atlas, collections, the trip's chat, polls and notes, files and the user's settings. Their tools are not loaded at first: call use_addon_tools with the groups you need, then use them in the same reply. Tools without a trip work on the user's own data across trips.
- Besides the open trip you can work in the rest of TREK: tours (hikes, bike tours, city walks), the road trip, the travel journal, the vacation planner, the atlas, collections, the trip's chat, polls and notes, files and the user's settings. Their tools are not loaded at first, and neither are those of the trip's bookings, its packing lists and to-dos, changes to its budget and its tags: call use_addon_tools with the groups you need, then use them in the same reply. Tools without a trip work on the user's own data across trips.
- Propose a deletion only when the user asks for it; it cannot be undone, and the card says so.
- You cannot share, invite people, publish links or calendar feeds, change who can see a trip, leave, copy or delete the trip, or make a new one. If asked, say so in one sentence and where in TREK the user can do it.
- Keep what will matter later with remember_for_trip on your own, without asking: who travels, needs, likes and dislikes, budget, pace, fixed times the user mentions, and anything they ask you to remember. It is kept at once and comes back as <trip_notes> in every later conversation; say briefly that you noted it. Where you are not sure it lasts, offer it as a follow-up instead ("Remember: …"). Never say you cannot remember things.
@@ -205,6 +205,6 @@ export function describeGeneric(
undoable: false,
effect: null,
tool: toolName,
...(hint?.group ? { domain: hint.group } : {}),
...(hint?.group && !hint.tripPart ? { domain: hint.group } : {}),
};
}
+3 -3
View File
@@ -209,6 +209,7 @@ export class AuthService {
// Reset-email delivery (canonical app URL, never request headers)
getAppUrl() { return getAppUrl(); }
sendPasswordResetEmail(email: string, url: string, userId: number | null) { return this.mailer.sendPasswordResetEmail(email, url, userId); }
retirePasswordResetLinks(userId: number) { return this.passwordResetTokens.consumeAllLiveForUser(userId); }
// -------------------------------------------------------------------------
// Toggles + tokens
@@ -651,9 +652,8 @@ export class AuthService {
await this.uow.transactional(async () => {
await this.usersRepo.setPassword(userId, hash, newPv);
// A password change ends every session (the pv bump covers the tokens from
// before sessions were tracked) and prunes the MCP static token and OAuth
// bearer-token stores to match, the same set the password reset revokes.
// Ends every session, reset link, MCP and OAuth token, the same set the password reset revokes.
await this.retirePasswordResetLinks(userId);
await this.mcpTokens.deleteAllForUser(userId);
try { await this.oauthTokens.revokeAllForUser(userId); } catch { /* no oauth_tokens in very old installs */ }
// Push devices keep receiving notifications without any session, so they
+28 -7
View File
@@ -1,11 +1,23 @@
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { dbNow } from '../../db/types/db-timestamp.type';
import { UnitOfWork } from '../database/unit-of-work';
import type { SessionClient } from '../sessions/sessions.service';
import { SessionsService, type SessionClient } from '../sessions/sessions.service';
import { AuthService } from './auth.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
/**
* The signed-in session a new one is carried on from: its account, the
* password version it was issued under, and its id (null on a token from
* before sessions were tracked).
*/
export interface SessionOrigin {
userId: number;
passwordVersion: number;
sessionId: string | null;
}
/**
* Signs in an account whose identity another way in has already proven: the
* login is recorded on the account and the session minted in one transaction.
@@ -18,16 +30,25 @@ export class LoginSessionService {
constructor(
private readonly auth: AuthService,
private readonly uow: UnitOfWork,
private readonly sessions: SessionsService,
@InjectRepository(Users) private readonly users: UsersRepository,
) {}
/** The session token, or null when the account no longer exists. */
async signIn(userId: number, remember: boolean | undefined, client?: SessionClient): Promise<string | null> {
/**
* The session token, or null when the session it is carried on from no
* longer stands: the account is gone, the password changed since, or that
* session ended (a sign-out, a revocation, a password reset). A credential
* the account took back cannot mint a new one this way.
*/
async signIn(origin: SessionOrigin, remember: boolean | undefined, client?: SessionClient): Promise<string | null> {
return this.uow.transactional(async () => {
const passwordVersion = await this.users.getPasswordVersion(userId);
if (passwordVersion === null) return null;
await this.users.touchLastLogin(userId);
return this.auth.generateToken({ id: userId, password_version: passwordVersion }, remember, client);
const passwordVersion = await this.users.getPasswordVersion(origin.userId);
if (passwordVersion === null || passwordVersion !== origin.passwordVersion) return null;
if (origin.sessionId !== null && !(await this.sessions.findActive(origin.sessionId, origin.userId, dbNow()))) {
return null;
}
await this.users.touchLastLogin(origin.userId);
return this.auth.generateToken({ id: origin.userId, password_version: passwordVersion }, remember, client);
});
}
}
@@ -1,7 +1,9 @@
import { readEnv, getAppUrl } from '../../app-config';
import { AppSettings } from '../../db/entities/AppSettings.entity';
import { PasswordResetTokens } from '../../db/entities/PasswordResetTokens.entity';
import { Users } from '../../db/entities/Users.entity';
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
import type { PasswordResetTokensRepository } from '../../db/repositories/PasswordResetTokens.repository';
import {
UserIdentityTakenError,
type UsersRepository,
@@ -58,6 +60,7 @@ export class UserProfileService {
private readonly uow: UnitOfWork,
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
@InjectRepository(PasswordResetTokens) private readonly passwordResetTokens: PasswordResetTokensRepository,
) {}
/**
@@ -282,6 +285,9 @@ export class UserProfileService {
try {
await this.uow.transactional(async () => {
await this.usersRepo.patchProfile(userId, changes);
// A reset link is a credential sent to the address the account had,
// so it must not outlive the move to another one.
if (emailChanged) await this.passwordResetTokens.consumeAllLiveForUser(userId);
if (!keyLocked) await this.mirrorInstanceKeys(body, isAdmin);
});
} catch (err) {
@@ -3,6 +3,7 @@ import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { CookieAuthGuard } from '../auth-core/cookie-auth.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { verifiedSessionClaims } from '../auth-core/jwt-verify';
import { Public } from '../auth-core/public.decorator';
import { setAuthCookie } from '../common/cookie';
import { RateLimitService } from '../common/rate-limit.service';
@@ -67,14 +68,25 @@ export class NativeAuthController {
/**
* Cookie only: an API or MCP bearer token must not be able to mint itself a
* full browser session this way.
* full browser session this way. The code is bound to the cookie's session,
* which the guard has just verified, so it redeems only while that stands.
*/
@Post('handoff')
@UseGuards(CookieAuthGuard)
@HttpCode(200)
@ResponseContract(nativeHandoffResponseSchema)
async handoff(@Body() body: NativeHandoffDto, @CurrentUser() user: User): Promise<NativeHandoffResponse> {
return { code: await this.nativeAuth.issueCode(user.id, body.challenge) };
async handoff(
@Body() body: NativeHandoffDto,
@CurrentUser() user: User,
@Req() req: Request,
): Promise<NativeHandoffResponse> {
const claims = verifiedSessionClaims((req.cookies as Record<string, string> | undefined)?.trek_session);
const origin = {
userId: user.id,
passwordVersion: claims?.pv ?? 0,
sessionId: typeof claims?.jti === 'string' ? claims.jti : null,
};
return { code: await this.nativeAuth.issueCode(origin, body.challenge) };
}
/**
@@ -1,4 +1,4 @@
import { LoginSessionService } from '../auth/login-session.service';
import { LoginSessionService, type SessionOrigin } from '../auth/login-session.service';
import { DomainError } from '../common/domain-error';
import type { SessionClient } from '../sessions/sessions.service';
import { NATIVE_HANDOFF_CODE_TTL_MS, NativeHandoffStore } from './native-handoff.store';
@@ -30,10 +30,10 @@ export class NativeAuthService {
private readonly handoffs: NativeHandoffStore,
) {}
async issueCode(userId: number, challenge: string): Promise<string> {
async issueCode(origin: SessionOrigin, challenge: string): Promise<string> {
const code = randomBytes(32).toString('base64url');
const stored = await this.handoffs.put(code, {
userId,
origin,
challenge,
expiresAt: Date.now() + NATIVE_HANDOFF_CODE_TTL_MS,
});
@@ -45,13 +45,15 @@ export class NativeAuthService {
* Burns the code on every attempt, right or wrong, so a code that leaked
* through the URL scheme gets exactly one guess. The session is always the
* long one: an app that forgets its login whenever the system unloads it
* would be useless on the road.
* would be useless on the road. It is carried on from the browser session
* that handed it off, so a code minted before that session ended (a
* password reset above all) mints nothing afterwards.
*/
async redeem(code: string, verifier: string, client: SessionClient): Promise<{ token: string; userId: number }> {
const entry = await this.handoffs.take(code);
if (!entry || !verifierMatches(entry.challenge, verifier)) throw new DomainError(400, INVALID_CODE);
const token = await this.logins.signIn(entry.userId, true, client);
const token = await this.logins.signIn(entry.origin, true, client);
if (!token) throw new DomainError(400, INVALID_CODE);
return { token, userId: entry.userId };
return { token, userId: entry.origin.userId };
}
}
@@ -1,6 +1,9 @@
import type { SessionOrigin } from '../auth/login-session.service';
/** A sign-in the system browser handed off and the app has not redeemed yet. */
export interface NativeHandoff {
userId: number;
/** The browser session that handed it off; the app's session stands only while that one does. */
origin: SessionOrigin;
/** Hex sha256 of the verifier the app kept to itself. */
challenge: string;
expiresAt: number;
@@ -3,6 +3,7 @@ import { getClientIp } from '../audit/client-ip';
import { CookieAuthGuard } from '../auth-core/cookie-auth.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { verifiedSessionClaims } from '../auth-core/jwt-verify';
import { OptionalJwtGuard } from '../auth-core/optional-jwt.guard';
import { DEMO_ACCOUNT_REFUSAL, refuseForDemoAccount } from '../common/demo-write';
import { RateLimitService } from '../common/rate-limit.service';
@@ -28,6 +29,12 @@ import type { Request, Response } from 'express';
const MIN = 60_000;
/** The id of the cookie session a consent comes from, null for a token from before sessions were tracked. */
function consentingSession(req: Request): string | null {
const jti = verifiedSessionClaims((req.cookies as Record<string, string> | undefined)?.trek_session)?.jti;
return typeof jti === 'string' ? jti : null;
}
/**
* Authenticated OAuth management endpoints (the SPA's consent + client/session
* UI) — byte-identical to the legacy oauthApiRouter (server/src/routes/oauth.ts):
@@ -135,6 +142,8 @@ export class OauthApiController {
resource: validation.resource ?? null,
codeChallenge: body.code_challenge,
codeChallengeMethod: 'S256',
// The cookie session the guard has just verified: the code is good only while it stands.
sessionId: consentingSession(req),
});
if (!code) {
throw new HttpException(
@@ -95,13 +95,8 @@ export class OauthPublicController {
}
if (!this.oauth.verifyPKCE(code_verifier, pending.codeChallenge))
return invalidGrant('pkce_failed', pending.userId);
const tokens = await this.oauth.issueTokens(
client_id,
pending.userId,
pending.scopes,
null,
pending.resource ?? null,
);
const tokens = await this.oauth.issueTokensForCode(pending);
if (!tokens) return invalidGrant('session_ended', pending.userId);
await this.audit.writeAudit({
userId: pending.userId,
action: 'oauth.token.issue',
+2 -7
View File
@@ -184,13 +184,8 @@ export class TrekOAuthProvider implements OAuthServerProvider {
if (!codeVerifier || !this.oauth.verifyPKCE(codeVerifier, pending.codeChallenge))
throw new Error('Authorization grant is invalid.');
const tokens = await this.oauth.issueTokens(
client.client_id,
pending.userId,
pending.scopes,
null,
pending.resource ?? null,
);
const tokens = await this.oauth.issueTokensForCode(pending);
if (!tokens) throw new Error('Authorization grant is invalid.');
await this.audit.writeAudit({
userId: pending.userId,
action: 'oauth.token.issue',
+5 -2
View File
@@ -8,6 +8,7 @@ import { createMcpAddonGate } from '../addons/mcp-addon-gate';
import { AuditModule } from '../audit/audit.module';
import { RateLimitModule } from '../common/rate-limit.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { SessionsModule } from '../sessions/sessions.module';
import { OauthApiController } from './oauth-api.controller';
import { CimdClientResolver } from './oauth-cimd';
import { OauthPublicController } from './oauth-public.controller';
@@ -57,15 +58,17 @@ import type { MiddlewareConsumer, NestModule } from '@nestjs/common';
* module availability (inventory §6 — `OauthTokensRepository` needs to be
* importable from `AuthModule` too, Task 5's `revokeAllForUser`, the same
* shape `McpTokensRepository`/`InviteTokensRepository` already use across
* `nest/tokens`/`nest/auth`/`nest/oidc`) even though `OauthService` itself
* never injects `UsersRepository` directly — OA16/OA31 read `users` columns
* `nest/tokens`/`nest/auth`/`nest/oidc`). OA16/OA31 read `users` columns
* THROUGH `OauthTokensRepository`'s own join methods, not a separate
* `Users` call (Task 1's ruling: "do not add users methods" for this join).
* Whether the session that consented to an authorization code still stands
* is the sessions domain's to answer (`SessionsService.findActive`).
*/
@Module({
imports: [
RateLimitModule,
AuditModule,
SessionsModule,
AddonsModule,
SchedulingModule,
MikroOrmModule.forFeature([OauthClients, OauthTokens, OauthConsents, Users]),
@@ -28,6 +28,12 @@ export interface PendingCode {
resource: string | null;
codeChallenge: string;
codeChallengeMethod: 'S256';
/**
* The browser session that consented (`user_sessions.id`), or null for a
* token from before sessions were tracked; the code mints tokens only while
* that session is active.
*/
sessionId: string | null;
expiresAt: number;
}
+20
View File
@@ -28,6 +28,7 @@ import { AuditService } from '../audit/audit.service';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { SessionsService } from '../sessions/sessions.service';
import { CimdClientResolver, isCimdClientId, type CimdClient } from './oauth-cimd';
import {
ACCESS_TOKEN_TTL_S,
@@ -133,6 +134,7 @@ export class OauthService {
@InjectRepository(OauthClients) private readonly clients: OauthClientsRepository,
@InjectRepository(OauthTokens) private readonly tokens: OauthTokensRepository,
@InjectRepository(OauthConsents) private readonly consents: OauthConsentsRepository,
private readonly sessions: SessionsService,
private readonly addons: AddonsService,
private readonly audit: AuditService,
private readonly uow: UnitOfWork,
@@ -317,6 +319,7 @@ export class OauthService {
resource: string | null;
codeChallenge: string;
codeChallengeMethod: 'S256';
sessionId: string | null;
}): Promise<string | null> {
const rawCode = randomBytes(32).toString('hex');
const stored = await this.pendingCodes.put(rawCode, { ...params, expiresAt: Date.now() + AUTH_CODE_TTL_MS });
@@ -388,6 +391,23 @@ export class OauthService {
// Token issuance
// -------------------------------------------------------------------------
/**
* The tokens a redeemed authorization code grants, or null when the session
* that consented has ended since: a password reset or change ends every
* session along with the user's tokens, and a sign-out ends this one, so a
* code from before must not mint new tokens. Checked in the transaction
* that writes them. A token from before sessions were tracked has no
* session to check and passes, as it does everywhere until it expires.
*/
async issueTokensForCode(pending: PendingCode): Promise<Awaited<ReturnType<OauthService['issueTokens']>> | null> {
return this.uow.transactional(async () => {
if (pending.sessionId !== null && !(await this.sessions.findActive(pending.sessionId, pending.userId, dbNow()))) {
return null;
}
return this.issueTokens(pending.clientId, pending.userId, pending.scopes, null, pending.resource ?? null);
});
}
async issueTokens(
clientId: string,
userId: number,
+2 -2
View File
@@ -155,7 +155,7 @@ async function resolveServedName(name: string, serving: PublicServing | undefine
async function servePhoto(
storage: StorageService,
req: Request,
req: Request<{ filename: string }>,
res: Response,
users: UsersRepository,
shareTokens: ShareTokensRepository,
@@ -314,7 +314,7 @@ export function applyPlatformUploads(
// photo's trip. Previously any share token for any trip could request
// any photo filename by UUID — fine in practice because UUIDs are
// unguessable, but the auth model was wrong.
app.get('/uploads/photos/:filename', (req: Request, res: Response, next: NextFunction) => {
app.get('/uploads/photos/:filename', (req: Request<{ filename: string }>, res: Response, next: NextFunction) => {
if (!orm) {
next(new Error('applyPlatformUploads: no MikroORM available to build a request context for /uploads/photos/*'));
return;
@@ -1,4 +1,5 @@
import express, { type NextFunction, type Request, type Response } from 'express';
import type { NextFunction, Request, Response } from 'express';
import { contentType } from 'mime-types';
import { readdirSync } from 'node:fs';
import path from 'node:path';
@@ -19,12 +20,9 @@ function collectPrecompressed(dir: string, urlPrefix: string, into: Set<string>)
return into;
}
/** The Content-Type the static handler gives the original file, charset included, from the same table. */
/** The Content-Type the static handler (send) gives the original file, from the same table and with the same fallback. */
function contentTypeOf(file: string): string {
const { mime } = express.static;
const type = mime.lookup(file);
const charset = mime.charsets.lookup(type, '');
return charset ? `${type}; charset=${charset}` : type;
return contentType(path.extname(file)) || 'application/octet-stream';
}
/**
+48 -13
View File
@@ -640,6 +640,47 @@ async function detailedFromArchive(
};
}
/**
* The last day Open-Meteo's forecast answers, counted in calendar days from today.
* The fraction of a day between now and the target's midnight is not that count:
* the day 16 out lies 15.x days away and slipped through a `<= 16` test (#3216).
*/
const FORECAST_LAST_DAY = 15;
function calendarDaysAhead(day: string, now: Date): number {
const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
return Math.round((Date.parse(`${day}T00:00:00Z`) - today) / 86_400_000);
}
/**
* The forecast counts its range from the place's own date, which trails UTC's in
* the Americas for part of the day, so its last day can still be refused there.
*/
function isOutsideForecastRange(status: number, reason: string | undefined): boolean {
return status === 400 && /out of allowed range/i.test(reason ?? '');
}
/** Last year's day standing in for a trip day the forecast does not reach. */
async function detailedClimate(
lat: string,
lng: string,
targetDate: Date,
now: Date,
descriptions: Record<number, string>,
ck: string,
): Promise<WeatherResult> {
let refYear = targetDate.getFullYear() - 1;
// Archive API only has data up to yesterday — go back further if needed
const yesterday = new Date(now.getTime() - 86400000);
if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--;
const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
const climate = await detailedFromArchive(lat, lng, refDateStr, 'climate', descriptions);
if (!climate) return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
setCache(ck, climate, TTL_CLIMATE_MS);
return climate;
}
async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, lang: string): Promise<WeatherResult> {
const ck = `detailed_${cacheKey(lat, lng, date, lang)}`;
@@ -652,18 +693,9 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
const dateStr = targetDate.toISOString().slice(0, 10);
const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;
// Climate path (> 16 days out): last year's day stands in for the trip's.
if (diffDays > 16) {
let refYear = targetDate.getFullYear() - 1;
// Archive API only has data up to yesterday — go back further if needed
const yesterday = new Date(now.getTime() - 86400000);
if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--;
const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
const climate = await detailedFromArchive(lat, lng, refDateStr, 'climate', descriptions);
if (!climate) return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
setCache(ck, climate, TTL_CLIMATE_MS);
return climate;
// Climate path: past the forecast's last day, last year's day stands in for the trip's.
if (calendarDaysAhead(dateStr, now) > FORECAST_LAST_DAY) {
return detailedClimate(lat, lng, targetDate, now, descriptions, ck);
}
// Past day: the forecast API answers nulls once a date is a couple of months
@@ -678,7 +710,7 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
}
}
// Forecast path (<= 16 days)
// Forecast path (up to today + 15 days)
const url =
`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}` +
`&hourly=temperature_2m,precipitation_probability,precipitation,weathercode,windspeed_10m,relativehumidity_2m` +
@@ -688,6 +720,9 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
const { response, data } = await fetchOpenMeteo(url);
if (!response.ok || data.error) {
if (isOutsideForecastRange(response.status, data.reason)) {
return detailedClimate(lat, lng, targetDate, now, descriptions, ck);
}
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
}
+78
View File
@@ -143,3 +143,81 @@ describe('Native sign-in hand-off e2e', () => {
expect((await request(server).get('/api/auth/native/start?challenge=nope')).status).toBe(400);
});
});
describe('a hand-off code outlives no end of the session that minted it', () => {
const sessionFrom = (response: request.Response): string =>
(response.headers['set-cookie'] as unknown as string[] | undefined)
?.find((c) => c.startsWith('trek_session='))
?.split(';')[0] ?? '';
/** A tracked browser session of a fresh account, as a sign-in leaves one. */
async function signedIn(name: string): Promise<{ email: string; cookie: string }> {
const email = `${name}@example.test`;
const { user } = await makeUser(orm, { username: name, email });
const minted = await handoff(sessionCookie(user.id));
const cookie = sessionFrom(await exchange({ code: minted.body.code, verifier }));
expect(cookie).not.toBe('');
return { email, cookie };
}
async function resetPassword(email: string): Promise<void> {
const mailer = app.get(MailerService) as unknown as { sendPasswordResetEmail: ReturnType<typeof vi.fn> };
mailer.sendPasswordResetEmail.mockClear();
mailer.sendPasswordResetEmail.mockResolvedValue({ delivered: 'test' });
expect((await request(server).post('/api/auth/forgot-password').send({ email })).status).toBe(200);
const url = String(mailer.sendPasswordResetEmail.mock.calls.at(-1)?.[1]);
const token = new URL(url).searchParams.get('token');
const reset = await request(server)
.post('/api/auth/reset-password')
.send({ token, new_password: 'Native-Reset-Check!2026' });
expect(reset.status).toBe(200);
}
async function refused(code: string): Promise<void> {
const late = await exchange({ code, verifier });
expect(late.status).toBe(400);
expect(late.body).toEqual({ error: 'Invalid or expired code' });
expect(late.headers['set-cookie']).toBeUndefined();
}
it('NATIVE-E2E-007: a code minted before a password reset mints no session after it', async () => {
const account = await signedIn('native-reset-tracked');
const minted = await handoff(account.cookie);
expect(minted.status).toBe(200);
await resetPassword(account.email);
await refused(minted.body.code);
});
it('NATIVE-E2E-008: a code minted from a session from before tracking is refused after a reset too', async () => {
const email = 'native-reset-untracked@example.test';
const { user } = await makeUser(orm, { username: 'native-reset-untracked', email });
const minted = await handoff(sessionCookie(user.id));
expect(minted.status).toBe(200);
await resetPassword(email);
await refused(minted.body.code);
});
it('NATIVE-E2E-009: a code minted before its session signed out mints no session after it', async () => {
const account = await signedIn('native-logout');
const minted = await handoff(account.cookie);
expect((await request(server).post('/api/auth/logout').set('Cookie', account.cookie)).status).toBe(200);
await refused(minted.body.code);
});
it('NATIVE-E2E-010: a code redeemed before the reset gives a session the reset then ends', async () => {
const account = await signedIn('native-reset-before');
const minted = await handoff(account.cookie);
const appSession = sessionFrom(await exchange({ code: minted.body.code, verifier }));
expect((await request(server).get('/api/auth/me').set('Cookie', appSession)).status).toBe(200);
await resetPassword(account.email);
expect((await request(server).get('/api/auth/me').set('Cookie', appSession)).status).toBe(401);
});
});
+1
View File
@@ -61,6 +61,7 @@ const { oauthSvc } = vi.hoisted(() => ({
consumeAuthCode: vi.fn(),
saveConsent: vi.fn(),
issueTokens: vi.fn(),
issueTokensForCode: vi.fn(),
issueClientCredentialsToken: vi.fn(),
refreshTokens: vi.fn(),
revokeToken: vi.fn(),
+1 -1
View File
@@ -28,7 +28,7 @@
* (tests/unit/nest-rpc/rpc-row-id-params.test.ts) for plugin RPC params.
*
* It boots the app on the real database module, so it runs in the SQLite
* suite and in the Postgres lane on 14 and 18.
* suite and in the Postgres lane on 14 and 19.
*/
import { buildApp } from '../../src/bootstrap';
import { Addons } from '../../src/db/entities/Addons.entity';
+3 -2
View File
@@ -37,6 +37,7 @@ import { VacayPlanMembers } from '../../src/db/entities/VacayPlanMembers.entity'
import { VacayPlans } from '../../src/db/entities/VacayPlans.entity';
import { VisitedCountries } from '../../src/db/entities/VisitedCountries.entity';
import { VisitedRegions } from '../../src/db/entities/VisitedRegions.entity';
import { oauthClientRef } from '../../src/db/repositories/_shared/oauth-client-ref';
import { dbNow } from '../../src/db/types/db-timestamp.type';
import { authCookie } from '../helpers/auth';
import { makeBucketListItem, markCountryVisited } from '../helpers/factories/atlas';
@@ -278,14 +279,14 @@ describe('Admin user management', () => {
client_secret_hash: 'h',
});
await insertRow(orm, OauthTokens, {
client: 'cid-admin-test',
client: oauthClientRef('cid-admin-test'),
user: target.id,
access_token_hash: 'ath-admin',
refresh_token_hash: 'rth-admin',
access_token_expires_at: dbNow(new Date(Date.now() + 60 * 60 * 1000)),
refresh_token_expires_at: dbNow(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)),
});
await insertRow(orm, OauthConsents, { client: 'cid-admin-test', user: target.id });
await insertRow(orm, OauthConsents, { client: oauthClientRef('cid-admin-test'), user: target.id });
// vacay_plans.owner_id (CASCADE): target owns a vacation plan
const vacayPlanId = (await makeVacayPlan(orm, target.id)).id;
+3 -2
View File
@@ -39,6 +39,7 @@ import { VacayPlanMembers } from '../../src/db/entities/VacayPlanMembers.entity'
import { VacayPlans } from '../../src/db/entities/VacayPlans.entity';
import { VisitedCountries } from '../../src/db/entities/VisitedCountries.entity';
import { VisitedRegions } from '../../src/db/entities/VisitedRegions.entity';
import { oauthClientRef } from '../../src/db/repositories/_shared/oauth-client-ref';
import { dbNow } from '../../src/db/types';
import { authCookie, authHeader } from '../helpers/auth';
import { makeBucketListItem, markCountryVisited } from '../helpers/factories/atlas';
@@ -810,14 +811,14 @@ describe('Account deletion', () => {
client_secret_hash: 'h',
});
await insertRow(orm, OauthTokens, {
client: 'cid-auth-test',
client: oauthClientRef('cid-auth-test'),
user: target.id,
access_token_hash: 'ath-auth',
refresh_token_hash: 'rth-auth',
access_token_expires_at: dbNow(new Date(Date.now() + 3600_000)),
refresh_token_expires_at: dbNow(new Date(Date.now() + 30 * 86_400_000)),
});
await insertRow(orm, OauthConsents, { client: 'cid-auth-test', user: target.id });
await insertRow(orm, OauthConsents, { client: oauthClientRef('cid-auth-test'), user: target.id });
// vacay_plans.owner_id (CASCADE): target owns a vacation plan
const vacayPlanId = await insertRow(orm, VacayPlans, { owner: target.id });
@@ -132,6 +132,24 @@ describe('BOOTSTRAP (F6) — unified NestJS app serves the whole surface', () =>
expect(res.body.type).toBe('FeatureCollection');
});
it('BOOT-009 — a request without a parsed body gets an empty object, except /mcp, which stays raw', async () => {
type Layer = { name: string; handle: (req: object, res: object, next: () => void) => void };
const { stack } = (instance as unknown as { router: { stack: Layer[] } }).router;
const names = stack.map((layer) => layer.name);
expect(names.indexOf('emptyBodyDefault')).toBeGreaterThan(names.indexOf('urlencodedParser'));
const emptyBodyDefault = stack[names.indexOf('emptyBodyDefault')].handle;
const run = (path: string, body?: unknown) =>
new Promise<unknown>((resolve) => {
const req = { path, body };
emptyBodyDefault(req, {}, () => resolve(req.body));
});
expect(await run('/api/trips/1/packing/2/contributors')).toEqual({});
expect(await run('/api/trips', { name: 'kept' })).toEqual({ name: 'kept' });
expect(await run('/mcp')).toBeUndefined();
expect(await run('/mcp/')).toBeUndefined();
});
it('BOOTSTRAP-ORM-001: the ORM unit of work resolves from the container', () => {
expect(app.get(UnitOfWork)).toBeInstanceOf(UnitOfWork);
});

Some files were not shown because too many files have changed in this diff Show More